diff --git a/.github/CHANGELOG.md b/.github/CHANGELOG.md
index f372e04..e51b481 100644
--- a/.github/CHANGELOG.md
+++ b/.github/CHANGELOG.md
@@ -1,3 +1,16 @@
+
+# [v2.4.0](https://github.com/AleksandrRogov/DynamicsWebApi/releases/tag/v2.4.0) - 28 Oct 2025
+
+## What's Changed
+* Allowing `@odata.id` to have an alternate key format. It used to force an absolute URL which should have only been done in POST requests to `/$ref`. Fixes [#195](https://github.com/AleksandrRogov/DynamicsWebApi/issues/195) .
+:warning: This change may be a breaking change in case you were making an _undocumented_ request that included `@odata.id` in the body of the request which will result in the value of the `@odata.id` to not have an absolute URL. A quick fix could be done by using a new utility function:
+* `dynamicsWebApi.Utility.toAbsoluteUrl` - a new utility function that prepends a url from the `dataApi` config to a provided value.
+
+**Full Changelog**: https://github.com/AleksandrRogov/DynamicsWebApi/compare/v2.3.2...v2.4.0
+
+[Changes][v2.4.0]
+
+
# [v2.3.2](https://github.com/AleksandrRogov/DynamicsWebApi/releases/tag/v2.3.2) - 20 Aug 2025
@@ -1141,6 +1154,7 @@ Added:
[Changes][v1.2.0]
+[v2.4.0]: https://github.com/AleksandrRogov/DynamicsWebApi/compare/v2.3.2...v2.4.0
[v2.3.2]: https://github.com/AleksandrRogov/DynamicsWebApi/compare/v2.3.1...v2.3.2
[v2.3.1]: https://github.com/AleksandrRogov/DynamicsWebApi/compare/v2.3.0...v2.3.1
[v2.3.0]: https://github.com/AleksandrRogov/DynamicsWebApi/compare/v2.2.1...v2.3.0
diff --git a/.github/README.md b/.github/README.md
index f15f4aa..5b2fed3 100644
--- a/.github/README.md
+++ b/.github/README.md
@@ -2863,6 +2863,7 @@ the config option "formatted" will enable developers to retrieve all information
- [X] Background Operations for custom actions. `Added in v2.3.0`
- [X] Support Search API 2.0 [#174](https://github.com/AleksandrRogov/DynamicsWebApi/issues/174). `Added in v2.3.0`
- [ ] [Session token](https://learn.microsoft.com/en-ca/power-apps/developer/data-platform/use-elastic-tables?tabs=webapi#work-with-the-session-token) support. `Coming in v2.3.x`
+- [ ] Support for a custom logger + a console fallback debug logging.
- [ ] Custom requests.
Many more features to come!
diff --git a/dist/browser/esm/dynamics-web-api.js b/dist/browser/esm/dynamics-web-api.js
index cc366ea..99c030d 100644
--- a/dist/browser/esm/dynamics-web-api.js
+++ b/dist/browser/esm/dynamics-web-api.js
@@ -1,4 +1,4 @@
-/*! dynamics-web-api v2.3.2 (c) 2025 Aleksandr Rogov. License: MIT */
+/*! dynamics-web-api v2.4.0 (c) 2025 Aleksandr Rogov. License: MIT */
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -85,7 +85,7 @@ function sanitizeCookie(cookie) {
return cookie.replace(SPECIAL_CHARACTER_REGEX, (char) => characterMap[char]);
}
function removeLeadingSlash(value) {
- return value.replace(LEADING_SLASH_REGEX, "");
+ return value.startsWith("/") ? value.slice(1) : value;
}
function escapeUnicodeSymbols(value) {
return value.replace(UNICODE_SYMBOLS_REGEX, (chr) => `\\u${("0000" + chr.charCodeAt(0).toString(16)).slice(-4)}`);
@@ -103,7 +103,7 @@ function extractPreferCallbackUrl(value) {
const match = PREFER_CALLBACK_URL_REGEX.exec(value);
return match ? match[1] : null;
}
-var UUID, UUID_REGEX, EXTRACT_UUID_REGEX, EXTRACT_UUID_FROM_URL_REGEX, REMOVE_BRACKETS_FROM_UUID_REGEX, ENTITY_UUID_REGEX, QUOTATION_MARK_REGEX, PAGING_COOKIE_REGEX, SPECIAL_CHARACTER_REGEX, LEADING_SLASH_REGEX, UNICODE_SYMBOLS_REGEX, DOUBLE_QUOTE_REGEX, BATCH_RESPONSE_HEADERS_REGEX, HTTP_STATUS_REGEX, CONTENT_TYPE_PLAIN_REGEX, ODATA_ENTITYID_REGEX, TEXT_REGEX, LINE_ENDING_REGEX, SEARCH_FOR_ENTITY_NAME_REGEX, SPECIAL_COLLECTION_FOR_UPDATE_REGEX, FETCH_XML_TOP_REGEX, FETCH_XML_PAGE_REGEX, FETCH_XML_REPLACE_REGEX, DATE_FORMAT_REGEX, SEARCH_SPECIAL_CHARACTERS_REGEX, PREFER_CALLBACK_URL_REGEX;
+var UUID, UUID_REGEX, EXTRACT_UUID_REGEX, EXTRACT_UUID_FROM_URL_REGEX, REMOVE_BRACKETS_FROM_UUID_REGEX, ENTITY_UUID_REGEX, QUOTATION_MARK_REGEX, PAGING_COOKIE_REGEX, SPECIAL_CHARACTER_REGEX, UNICODE_SYMBOLS_REGEX, DOUBLE_QUOTE_REGEX, BATCH_RESPONSE_HEADERS_REGEX, HTTP_STATUS_REGEX, CONTENT_TYPE_PLAIN_REGEX, ODATA_ENTITYID_REGEX, TEXT_REGEX, LINE_ENDING_REGEX, SEARCH_FOR_ENTITY_NAME_REGEX, SPECIAL_COLLECTION_FOR_UPDATE_REGEX, FETCH_XML_TOP_REGEX, FETCH_XML_PAGE_REGEX, FETCH_XML_REPLACE_REGEX, DATE_FORMAT_REGEX, SEARCH_SPECIAL_CHARACTERS_REGEX, PREFER_CALLBACK_URL_REGEX;
var init_Regex = __esm({
"src/helpers/Regex.ts"() {
"use strict";
@@ -116,7 +116,6 @@ var init_Regex = __esm({
QUOTATION_MARK_REGEX = /(["'].*?["'])/;
PAGING_COOKIE_REGEX = /pagingcookie="()/;
SPECIAL_CHARACTER_REGEX = /[<>"']/g;
- LEADING_SLASH_REGEX = /^\//;
UNICODE_SYMBOLS_REGEX = /[\u007F-\uFFFF]/g;
DOUBLE_QUOTE_REGEX = /"/g;
BATCH_RESPONSE_HEADERS_REGEX = /^([^()<>@,;:\\"\/[\]?={} \t]+)\s?:\s?(.*)/;
@@ -262,6 +261,9 @@ function convertToFileBuffer(binaryString) {
}
return bytes;
}
+function toAbsoluteUrl(client, value) {
+ return `${client.config.dataApi.url}${removeLeadingSlash(value)}`;
+}
var downloadChunkSize;
var init_Utility = __esm({
"src/utils/Utility.ts"() {
@@ -1422,13 +1424,15 @@ var processData = (data, config) => {
return value;
};
const stringifiedData = JSON.stringify(data, (key, value) => {
- if (key.endsWith("@odata.bind") || key.endsWith("@odata.id")) {
+ if (key === "@odata.id" || key.endsWith("@odata.bind")) {
if (typeof value === "string" && !value.startsWith("$")) {
value = removeCurlyBracketsFromUuid(value);
if (config.useEntityNames) {
value = replaceEntityNameWithCollectionName(value);
}
- value = addFullWebApiUrl(key, value);
+ if (key !== "@odata.id") {
+ value = addFullWebApiUrl(key, value);
+ }
}
} else if (key.startsWith("oData") || key.endsWith("_Formatted") || key.endsWith("_NavigationProperty") || key.endsWith("_LogicalName")) {
return void 0;
@@ -1726,7 +1730,7 @@ var associate = async (request, client) => {
if (!client.isBatch || client.isBatch && !request.relatedKey.startsWith("$")) {
ErrorHelper.stringParameterCheck(request.relatedCollection, REQUEST_NAME, "request.relatedCollection");
relatedKey = ErrorHelper.keyParameterCheck(request.relatedKey, REQUEST_NAME, "request.relatedKey");
- odataId = `${request.relatedCollection}(${relatedKey})`;
+ odataId = `${client.config.dataApi.url}${request.relatedCollection}(${relatedKey})`;
}
let internalRequest = copyRequest(request, ["primaryKey"]);
internalRequest.method = "POST";
@@ -1751,7 +1755,7 @@ var associateSingleValued = async (request, client) => {
if (!client.isBatch || client.isBatch && !request.relatedKey.startsWith("$")) {
ErrorHelper.stringParameterCheck(request.relatedCollection, REQUEST_NAME2, "request.relatedCollection");
relatedKey = ErrorHelper.keyParameterCheck(request.relatedKey, REQUEST_NAME2, "request.relatedKey");
- odataId = `${request.relatedCollection}(${relatedKey})`;
+ odataId = `${client.config.dataApi.url}${request.relatedCollection}(${relatedKey})`;
}
let internalRequest = copyRequest(request, ["primaryKey"]);
internalRequest.method = "PUT";
@@ -2896,6 +2900,7 @@ async function cancelBackgroundOperation(backgroundOperationId, client) {
}
// src/dynamics-web-api.ts
+init_Utility();
var _client;
var _DynamicsWebApi = class _DynamicsWebApi {
/**
@@ -3304,7 +3309,13 @@ var _DynamicsWebApi = class _DynamicsWebApi {
* @param {string} entityName entity name
* @returns {string | null} collection name
*/
- getCollectionName: (entityName) => getCollectionName(entityName)
+ getCollectionName: (entityName) => getCollectionName(entityName),
+ /**
+ * Adds an absolute Web API URL to the beginning of a provided value.
+ * @param value The value to modify.
+ * @returns The absolute URL.
+ */
+ toAbsoluteUrl: (value) => toAbsoluteUrl(__privateGet(this, _client), value)
};
__privateSet(this, _client, new DataverseClient(config));
}
diff --git a/dist/browser/esm/dynamics-web-api.js.map b/dist/browser/esm/dynamics-web-api.js.map
index 42f5cdc..b0b6b8e 100644
--- a/dist/browser/esm/dynamics-web-api.js.map
+++ b/dist/browser/esm/dynamics-web-api.js.map
@@ -1,7 +1,7 @@
{
"version": 3,
"sources": ["../../../src/helpers/Crypto.ts", "../../../src/helpers/Regex.ts", "../../../src/utils/Utility.ts", "../../../src/helpers/ErrorHelper.ts", "../../../src/dwa.ts", "../../../src/client/helpers/dateReviver.ts", "../../../src/client/helpers/parseBatchResponse.ts", "../../../src/client/helpers/parseResponse.ts", "../../../src/client/helpers/parseResponseHeaders.ts", "../../../src/client/xhr.ts", "../../../src/utils/Config.ts", "../../../src/requests/constants.ts", "../../../src/client/RequestClient.ts", "../../../src/client/helpers/entityNameMapper.ts", "../../../src/client/helpers/executeRequest.ts", "../../../src/client/request/composers/url.ts", "../../../src/client/request/composers/headers.ts", "../../../src/client/request/composers/preferHeader.ts", "../../../src/client/request/composers/request.ts", "../../../src/client/request/processData.ts", "../../../src/client/helpers/index.ts", "../../../src/client/request/setStandardHeaders.ts", "../../../src/client/request/convertToBatch.ts", "../../../src/client/dataverse.ts", "../../../src/requests/associate.ts", "../../../src/requests/associateSingleValued.ts", "../../../src/requests/callAction.ts", "../../../src/requests/callFunction.ts", "../../../src/requests/create.ts", "../../../src/requests/count.ts", "../../../src/requests/countAll.ts", "../../../src/requests/retrieveAll.ts", "../../../src/requests/retrieveMultiple.ts", "../../../src/requests/disassociate.ts", "../../../src/requests/disassociateSingleValued.ts", "../../../src/requests/retrieve.ts", "../../../src/requests/fetchXml.ts", "../../../src/requests/fetchXmlAll.ts", "../../../src/requests/update.ts", "../../../src/requests/updateSingleProperty.ts", "../../../src/requests/upsert.ts", "../../../src/requests/delete.ts", "../../../src/requests/uploadFile.ts", "../../../src/requests/downloadFile.ts", "../../../src/requests/executeBatch.ts", "../../../src/requests/metadata/createEntity.ts", "../../../src/requests/metadata/updateEntity.ts", "../../../src/requests/metadata/retrieveEntity.ts", "../../../src/requests/metadata/retrieveEntities.ts", "../../../src/requests/metadata/createAttribute.ts", "../../../src/requests/metadata/updateAttribute.ts", "../../../src/requests/metadata/retrieveAttributes.ts", "../../../src/requests/metadata/retrieveAttribute.ts", "../../../src/requests/metadata/createRelationship.ts", "../../../src/requests/metadata/updateRelationship.ts", "../../../src/requests/metadata/deleteRelationship.ts", "../../../src/requests/metadata/retrieveRelationships.ts", "../../../src/requests/metadata/retrieveRelationship.ts", "../../../src/requests/metadata/createGlobalOptionSet.ts", "../../../src/requests/metadata/updateGlobalOptionSet.ts", "../../../src/requests/metadata/deleteGlobalOptionSet.ts", "../../../src/requests/metadata/retrieveGlobalOptionSet.ts", "../../../src/requests/metadata/retrieveGlobalOptionSets.ts", "../../../src/requests/metadata/retrieveCsdlMetadata.ts", "../../../src/requests/search/query.ts", "../../../src/requests/search/convertSearchQuery.ts", "../../../src/requests/search/responseParsers/parseQueryResponse.ts", "../../../src/requests/search/suggest.ts", "../../../src/requests/search/responseParsers/parseSuggestResponse.ts", "../../../src/requests/search/autocomplete.ts", "../../../src/requests/search/responseParsers/parseAutocompleteResponse.ts", "../../../src/requests/backgroundOperation/getStatus.ts", "../../../src/requests/backgroundOperation/cancel.ts", "../../../src/dynamics-web-api.ts"],
- "sourcesContent": ["export function getCrypto(): T {\r\n return global.DWA_BROWSER ? (global.window.crypto as T) : require(\"./crypto/node\").getCrypto();\r\n}\r\n", "import type { ReferenceObject } from \"../types\";\r\n\r\nconst UUID = \"[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}\";\r\n\r\nexport const UUID_REGEX = new RegExp(UUID, \"i\");\r\nexport const EXTRACT_UUID_REGEX = new RegExp(\"^{?(\" + UUID + \")}?$\", \"i\");\r\nexport const EXTRACT_UUID_FROM_URL_REGEX = new RegExp(\"(\" + UUID + \")\\\\)$\", \"i\");\r\n//global here is fine because the state is reset inside string.replace function\r\nexport const REMOVE_BRACKETS_FROM_UUID_REGEX = new RegExp(`{(${UUID})}`, \"g\");\r\nexport const ENTITY_UUID_REGEX = new RegExp(`\\\\/(\\\\w+)\\\\((${UUID})`, \"i\");\r\n\r\nexport function isUuid(value: string): boolean {\r\n const match = UUID_REGEX.exec(value);\r\n return !!match;\r\n}\r\n\r\nexport function extractUuid(value: string): string | null {\r\n const match = EXTRACT_UUID_REGEX.exec(value);\r\n return match ? match[1] : null;\r\n}\r\n\r\nexport function extractUuidFromUrl(url?: string): string | null {\r\n if (!url) return null;\r\n const match = EXTRACT_UUID_FROM_URL_REGEX.exec(url);\r\n return match ? match[1] : null;\r\n}\r\n\r\nexport function removeCurlyBracketsFromUuid(value: string): string {\r\n return value.replace(REMOVE_BRACKETS_FROM_UUID_REGEX, (_match, p1) => p1);\r\n}\r\n\r\nconst QUOTATION_MARK_REGEX = /([\"'].*?[\"'])/;\r\n\r\n/**\r\n * Safely removes curly brackets from guids in a URL\r\n * @param url URL to remove curly brackets from\r\n * @returns URL with guid without curly brackets\r\n */\r\nexport function safelyRemoveCurlyBracketsFromUrl(url: string): string {\r\n //todo: in future I will need to replace this with a negative lookbehind and lookahead\r\n\r\n // Split the filter string by quotation marks\r\n const parts = url.split(QUOTATION_MARK_REGEX);\r\n return parts\r\n .map((part, index) => {\r\n // Only process parts that are not within quotes\r\n if (index % 2 === 0) {\r\n return removeCurlyBracketsFromUuid(part);\r\n }\r\n return part;\r\n })\r\n .join(\"\");\r\n}\r\n\r\n/**\r\n * Converts a response to a reference object\r\n * @param {Object} responseData - Response object\r\n * @returns {ReferenceObject}\r\n */\r\nexport function convertToReferenceObject(responseData: Record): ReferenceObject {\r\n const result = ENTITY_UUID_REGEX.exec(responseData[\"@odata.id\"]);\r\n return { id: result![2], collection: result![1], oDataContext: responseData[\"@odata.context\"] };\r\n}\r\n\r\nexport const PAGING_COOKIE_REGEX = /pagingcookie=\"()/;\r\nexport const SPECIAL_CHARACTER_REGEX = /[<>\"']/g;\r\n\r\n/**\r\n * Parses a paging cookie\r\n * @param pagingCookie Paging cookie to parse\r\n * @returns\r\n */\r\nexport function parsePagingCookie(pagingCookie: string) {\r\n const info = PAGING_COOKIE_REGEX.exec(pagingCookie);\r\n\r\n if (!info) return null;\r\n\r\n const page = parseInt(info[2], 10);\r\n const sanitizedCookie = sanitizeCookie(info[1]);\r\n\r\n return { page, sanitizedCookie };\r\n}\r\n\r\n/**\r\n * Sanitizes a cookie\r\n * @param cookie Cookie to sanitize\r\n * @returns\r\n */\r\nfunction sanitizeCookie(cookie: string): string {\r\n const characterMap: { [key: string]: string } = {\r\n \"<\": \"<\",\r\n \">\": \">\",\r\n '\"': \""\",\r\n \"'\": \"'\", // Use numeric reference for single quote to avoid confusion\r\n };\r\n\r\n return cookie.replace(SPECIAL_CHARACTER_REGEX, (char) => characterMap[char]);\r\n}\r\n\r\nconst LEADING_SLASH_REGEX = /^\\//;\r\nexport function removeLeadingSlash(value: string): string {\r\n return value.replace(LEADING_SLASH_REGEX, \"\");\r\n}\r\n\r\nconst UNICODE_SYMBOLS_REGEX = /[\\u007F-\\uFFFF]/g;\r\nexport function escapeUnicodeSymbols(value: string): string {\r\n return value.replace(UNICODE_SYMBOLS_REGEX, (chr: string) => `\\\\u${(\"0000\" + chr.charCodeAt(0).toString(16)).slice(-4)}`);\r\n}\r\n\r\nconst DOUBLE_QUOTE_REGEX = /\"/g;\r\nexport function removeDoubleQuotes(value: string): string {\r\n return value.replace(DOUBLE_QUOTE_REGEX, \"\");\r\n}\r\n\r\nexport const BATCH_RESPONSE_HEADERS_REGEX = /^([^()<>@,;:\\\\\"\\/[\\]?={} \\t]+)\\s?:\\s?(.*)/;\r\nexport const HTTP_STATUS_REGEX = /HTTP\\/?\\s*[\\d.]*\\s+(\\d{3})\\s+([\\w\\s]*)$/m;\r\nexport const CONTENT_TYPE_PLAIN_REGEX = /Content-Type: text\\/plain/i;\r\nexport const ODATA_ENTITYID_REGEX = /OData-EntityId.+/i;\r\nexport const TEXT_REGEX = /\\w+$/g;\r\nexport const LINE_ENDING_REGEX = /\\r?\\n/;\r\nexport const SEARCH_FOR_ENTITY_NAME_REGEX = /(\\w+)(\\([\\d\\w-]+\\))$/;\r\nexport const SPECIAL_COLLECTION_FOR_UPDATE_REGEX = /EntityDefinitions|RelationshipDefinitions|GlobalOptionSetDefinitions/;\r\n\r\n/**Metadata definitions cannot be updated using \"PATCH\" method */\r\nexport function getUpdateMethod(collection: string | undefined | null){\r\n return SPECIAL_COLLECTION_FOR_UPDATE_REGEX.test(collection ?? \"\") ? \"PUT\" : \"PATCH\";\r\n}\r\n\r\nexport const FETCH_XML_TOP_REGEX = /^ {\r\n let value = parameters[parameterName];\r\n if (value == null) return;\r\n\r\n value = formatParameterValue(value);\r\n\r\n const paramIndex = index + 1;\r\n functionParams.push(`${parameterName}=@p${paramIndex}`);\r\n urlQuery.push(`@p${paramIndex}=${extractUuid(value) || value}`);\r\n });\r\n\r\n return {\r\n key: `(${functionParams.join(\",\")})`,\r\n queryParams: urlQuery,\r\n };\r\n}\r\n\r\nexport function hasHeader(headers: Record, name: string): boolean {\r\n return headers.hasOwnProperty(name) || headers.hasOwnProperty(name.toLowerCase());\r\n}\r\n\r\nexport function getHeader(headers: Record, name: string): string | undefined {\r\n if (headers[name]) return headers[name];\r\n\r\n return headers[name.toLowerCase()];\r\n}\r\n\r\n/**\r\n * Builds parametes for a funciton. Returns '()' (if no parameters) or '([params])?[query]'\r\n *\r\n * @param {Object} [parameters] - Function's input parameters. Example: { param1: \"test\", param2: 3 }.\r\n * @returns {string}\r\n */\r\nexport function buildFunctionParameters(parameters?: any): Core.FunctionParameters {\r\n return parameters ? processParameters(parameters) : { key: \"()\" };\r\n}\r\n\r\n/**\r\n * Parses a paging cookie returned in response\r\n *\r\n * @param {string} pageCookies - Page cookies returned in @Microsoft.Dynamics.CRM.fetchxmlpagingcookie.\r\n * @param {number} currentPageNumber - A current page number. Fix empty paging-cookie for complex fetch xmls.\r\n * @returns {{cookie: \"\", number: 0, next: 1}}\r\n */\r\nexport function getFetchXmlPagingCookie(pageCookies: string = \"\", currentPageNumber: number = 1): Core.FetchXmlCookie {\r\n //get the page cokies\r\n pageCookies = decodeURIComponent(decodeURIComponent(pageCookies));\r\n\r\n const result = parsePagingCookie(pageCookies);\r\n\r\n // http://stackoverflow.com/questions/41262772/execution-of-fetch-xml-using-web-api-dynamics-365 workaround\r\n return {\r\n cookie: result?.sanitizedCookie || \"\",\r\n page: result?.page || currentPageNumber,\r\n nextPage: result?.page ? result.page + 1 : currentPageNumber + 1,\r\n };\r\n}\r\n\r\n// static isNodeEnv = isNodeEnv;\r\n\r\n/**\r\n * Checks whether the value is JS Null.\r\n * @param {Object} value\r\n * @returns {boolean}\r\n */\r\nexport function isNull(value: any): value is undefined | null {\r\n return typeof value === \"undefined\" || value == null;\r\n}\r\n\r\n/** Generates UUID */\r\nexport function generateUUID() {\r\n return getCrypto().randomUUID();\r\n}\r\n\r\nexport function getXrmContext(): any {\r\n if (typeof GetGlobalContext !== \"undefined\") {\r\n return GetGlobalContext();\r\n } else {\r\n if (typeof Xrm !== \"undefined\") {\r\n //d365 v.9.0\r\n if (!isNull(Xrm.Utility) && !isNull(Xrm.Utility.getGlobalContext)) {\r\n return Xrm.Utility.getGlobalContext();\r\n } else if (!isNull(Xrm.Page) && !isNull(Xrm.Page.context)) {\r\n return Xrm.Page.context;\r\n }\r\n }\r\n }\r\n\r\n throw new Error(\r\n \"Xrm Context is not available. In most cases, it can be resolved by adding a reference to a ClientGlobalContext.js.aspx. Please refer to MSDN documentation for more details.\",\r\n );\r\n}\r\n\r\n// static getXrmUtility(): any {\r\n// return typeof Xrm !== \"undefined\" ? Xrm.Utility : null;\r\n// }\r\n\r\nexport function getClientUrl(): string {\r\n const context = getXrmContext();\r\n\r\n let clientUrl = context.getClientUrl();\r\n\r\n if (clientUrl.match(/\\/$/)) {\r\n clientUrl = clientUrl.substring(0, clientUrl.length - 1);\r\n }\r\n return clientUrl;\r\n}\r\n\r\n/**\r\n * Checks whether the app is currently running in a Dynamics Portals Environment.\r\n *\r\n * In that case we switch to the Web API for Dynamics Portals.\r\n * @returns {boolean}\r\n */\r\nexport function isRunningWithinPortals(): boolean {\r\n return global.DWA_BROWSER ? !!global.window.shell : false;\r\n}\r\n\r\nexport function isObject(obj: any): boolean {\r\n return typeof obj === \"object\" && !!obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== \"[object Date]\";\r\n}\r\n\r\nexport function copyObject(src: any, excludeProps?: string[]): T {\r\n let target = {};\r\n for (let prop in src) {\r\n if (src.hasOwnProperty(prop) && !excludeProps?.includes(prop)) {\r\n // if the value is a nested object, recursively copy all its properties\r\n if (isObject(src[prop])) {\r\n target[prop] = copyObject(src[prop]);\r\n } else if (Array.isArray(src[prop])) {\r\n target[prop] = src[prop].slice();\r\n } else {\r\n target[prop] = src[prop];\r\n }\r\n }\r\n }\r\n return target;\r\n}\r\n\r\nexport function copyRequest(src: any, excludeProps: string[] = []): Core.InternalRequest {\r\n //todo: do we need to include \"data\" in here?\r\n if (!excludeProps.includes(\"signal\")) excludeProps.push(\"signal\");\r\n\r\n const result = copyObject(src, excludeProps);\r\n result.signal = src.signal;\r\n\r\n return result;\r\n}\r\n\r\nexport function setFileChunk(request: Core.InternalRequest, fileBuffer: Uint8Array | Buffer, chunkSize: number, offset: number): void {\r\n offset = offset || 0;\r\n\r\n const count = offset + chunkSize > fileBuffer.length ? fileBuffer.length % chunkSize : chunkSize;\r\n\r\n let content: any;\r\n\r\n if (global.DWA_BROWSER) {\r\n content = new Uint8Array(count);\r\n for (let i = 0; i < count; i++) {\r\n content[i] = fileBuffer[offset + i];\r\n }\r\n } else {\r\n content = fileBuffer.slice(offset, offset + count);\r\n }\r\n\r\n request.data = content;\r\n request.contentRange = \"bytes \" + offset + \"-\" + (offset + count - 1) + \"/\" + fileBuffer.length;\r\n}\r\n\r\nexport function convertToFileBuffer(binaryString: string): Uint8Array | Buffer {\r\n if (!global.DWA_BROWSER) return Buffer.from(binaryString, \"binary\");\r\n\r\n const bytes = new Uint8Array(binaryString.length);\r\n for (var i = 0; i < binaryString.length; i++) {\r\n bytes[i] = binaryString.charCodeAt(i);\r\n }\r\n return bytes;\r\n}\r\n", "\uFEFFimport { AccessToken } from \"../dynamics-web-api\";\r\nimport { extractUuid } from \"./Regex\";\r\n\r\nexport interface DynamicsWebApiError extends Error {\r\n status: number;\r\n statusText: string;\r\n statusMessage: string;\r\n headers: Record;\r\n stack?: string;\r\n}\r\n\r\nfunction throwParameterError(functionName: string, parameterName: string, type: string | null | undefined): never {\r\n throw new Error(\r\n type ? `${functionName} requires a ${parameterName} parameter to be of type ${type}.` : `${functionName} requires a ${parameterName} parameter.`\r\n );\r\n}\r\n\r\nexport class ErrorHelper {\r\n static handleErrorResponse(req): void {\r\n throw new Error(`Error: ${req.status}: ${req.message}`);\r\n }\r\n\r\n static parameterCheck(parameter: any, functionName: string, parameterName: string, type?: string): void {\r\n if (typeof parameter === \"undefined\" || parameter === null || parameter === \"\") {\r\n throwParameterError(functionName, parameterName, type);\r\n }\r\n }\r\n\r\n static stringParameterCheck(parameter: any, functionName: string, parameterName: string): void {\r\n if (typeof parameter !== \"string\") {\r\n throwParameterError(functionName, parameterName, \"String\");\r\n }\r\n }\r\n\r\n static maxLengthStringParameterCheck(parameter: string | null, functionName: string, parameterName: string, maxLength: number): void {\r\n if (!parameter) return;\r\n\r\n if (parameter.length > maxLength) {\r\n throw new Error(`${parameterName} has a ${maxLength} character limit.`);\r\n }\r\n }\r\n\r\n static arrayParameterCheck(parameter: any, functionName: string, parameterName: string): void {\r\n if (parameter.constructor !== Array) {\r\n throwParameterError(functionName, parameterName, \"Array\");\r\n }\r\n }\r\n\r\n static stringOrArrayParameterCheck(parameter: any, functionName: string, parameterName: string): void {\r\n if (parameter.constructor !== Array && typeof parameter !== \"string\") {\r\n throwParameterError(functionName, parameterName, \"String or Array\");\r\n }\r\n }\r\n\r\n static numberParameterCheck(parameter: any, functionName: string, parameterName: string): void {\r\n if (typeof parameter != \"number\") {\r\n if (typeof parameter === \"string\" && parameter) {\r\n if (!isNaN(parseInt(parameter))) {\r\n return;\r\n }\r\n }\r\n throwParameterError(functionName, parameterName, \"Number\");\r\n }\r\n }\r\n\r\n static batchIsEmpty(): Error[] {\r\n return [\r\n new Error(\r\n \"Payload of the batch operation is empty. Please make that you have other operations in between startBatch() and executeBatch() to successfuly build a batch payload.\"\r\n ),\r\n ];\r\n }\r\n\r\n static handleHttpError(parsedError: any, parameters?: any): DynamicsWebApiError {\r\n const error = new Error();\r\n\r\n Object.keys(parsedError).forEach((k) => {\r\n error[k] = parsedError[k];\r\n });\r\n\r\n if (parameters) {\r\n Object.keys(parameters).forEach((k) => {\r\n error[k] = parameters[k];\r\n });\r\n }\r\n\r\n return error;\r\n }\r\n\r\n static boolParameterCheck(parameter: any, functionName: string, parameterName: string): void {\r\n if (typeof parameter != \"boolean\") {\r\n throwParameterError(functionName, parameterName, \"Boolean\");\r\n }\r\n }\r\n\r\n /**\r\n * Private function used to check whether required parameter is a valid GUID\r\n * @param parameter The GUID parameter to check\r\n * @param functionName\r\n * @param parameterName\r\n * @returns\r\n */\r\n static guidParameterCheck(parameter: any, functionName: string, parameterName: string): string {\r\n const match = extractUuid(parameter);\r\n if (!match) throwParameterError(functionName, parameterName, \"GUID String\");\r\n\r\n return match!;\r\n }\r\n\r\n static keyParameterCheck(parameter: any, functionName: string, parameterName: string): string {\r\n try {\r\n ErrorHelper.stringParameterCheck(parameter, functionName, parameterName);\r\n\r\n //check if the param is a guid\r\n const match = extractUuid(parameter);\r\n if (match) return match;\r\n\r\n //check the alternate key\r\n const alternateKeys = parameter.split(\",\");\r\n\r\n if (alternateKeys.length) {\r\n for (let i = 0; i < alternateKeys.length; i++) {\r\n alternateKeys[i] = alternateKeys[i].trim().replace(/\"/g, \"'\");\r\n /^[\\w\\d\\_]+\\=(.+)$/i.exec(alternateKeys[i])![0];\r\n }\r\n }\r\n\r\n return alternateKeys.join(\",\");\r\n } catch (error) {\r\n throwParameterError(functionName, parameterName, \"String representing GUID or Alternate Key\");\r\n }\r\n }\r\n\r\n static callbackParameterCheck(callbackParameter: () => Promise, functionName: string, parameterName: string): void {\r\n if (typeof callbackParameter != \"function\") {\r\n throwParameterError(functionName, parameterName, \"Function\");\r\n }\r\n }\r\n\r\n static throwBatchIncompatible(functionName: string, isBatch: boolean): void {\r\n if (isBatch) {\r\n isBatch = false;\r\n throw new Error(functionName + \" cannot be used in a BATCH request.\");\r\n }\r\n }\r\n\r\n static throwBatchNotStarted(isBatch: boolean): void {\r\n if (!isBatch) {\r\n throw new Error(\r\n \"Batch operation has not been started. Please call a DynamicsWebApi.startBatch() function prior to calling DynamicsWebApi.executeBatch() to perform a batch request correctly.\"\r\n );\r\n }\r\n }\r\n}\r\n", "class DWA {\r\n\tstatic Prefer = class {\r\n\t\tstatic ReturnRepresentation: string = \"return=representation\";\r\n\t\tstatic Annotations = class {\r\n\t\t\tstatic AssociatedNavigationProperty: string = \"Microsoft.Dynamics.CRM.associatednavigationproperty\";\r\n\t\t\tstatic LookupLogicalName: string = \"Microsoft.Dynamics.CRM.lookuplogicalname\";\r\n\t\t\tstatic All: string = \"*\";\r\n\t\t\tstatic FormattedValue: string = \"OData.Community.Display.V1.FormattedValue\";\r\n\t\t\tstatic FetchXmlPagingCookie: string = \"Microsoft.Dynamics.CRM.fetchxmlpagingcookie\";\r\n\t\t};\r\n\t\tstatic IncludeAnnotations: string = \"odata.include-annotations\";\r\n\t\tstatic get(annotation: string) {\r\n\t\t\treturn `${DWA.Prefer.IncludeAnnotations}=\"${annotation}\"`;\r\n\t\t}\r\n\t};\r\n}\r\n\r\nexport { DWA };\r\n", "\uFEFFimport { DATE_FORMAT_REGEX } from \"../../helpers/Regex\";\r\n\r\nexport function dateReviver(key: string, value: any): Date {\r\n if (typeof value === \"string\") {\r\n const a = DATE_FORMAT_REGEX.exec(value);\r\n if (a) {\r\n return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));\r\n }\r\n }\r\n return value;\r\n}\r\n", "import { DynamicsWebApiError, ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport {\r\n BATCH_RESPONSE_HEADERS_REGEX,\r\n LINE_ENDING_REGEX,\r\n HTTP_STATUS_REGEX,\r\n TEXT_REGEX,\r\n CONTENT_TYPE_PLAIN_REGEX,\r\n ODATA_ENTITYID_REGEX,\r\n extractUuidFromUrl,\r\n} from \"../../helpers/Regex\";\r\nimport { handleJsonResponse, handlePlainResponse } from \"./parseResponse\";\r\n\r\n//partially taken from http://olingo.apache.org/doc/javascript/apidoc/batch.js.html\r\nfunction parseBatchHeaders(text: string): any {\r\n const ctx = { position: 0 };\r\n const headers: Record = {};\r\n let parts: RegExpExecArray | null;\r\n let line: string | null;\r\n let pos: number;\r\n\r\n do {\r\n pos = ctx.position;\r\n line = readLine(text, ctx);\r\n if (!line) break; //if the line is empty, then it is the end of the headers\r\n parts = BATCH_RESPONSE_HEADERS_REGEX.exec(line);\r\n if (parts !== null) {\r\n headers[parts[1].toLowerCase()] = parts[2];\r\n } else {\r\n // Whatever was found is not a header, so reset the context position.\r\n ctx.position = pos;\r\n }\r\n } while (line && parts);\r\n\r\n return headers;\r\n}\r\n\r\n//partially taken from http://olingo.apache.org/doc/javascript/apidoc/batch.js.html\r\nfunction readLine(text: string, ctx: { position: number }): string | null {\r\n return readTo(text, ctx, LINE_ENDING_REGEX);\r\n}\r\n\r\n//partially taken from http://olingo.apache.org/doc/javascript/apidoc/batch.js.html\r\nfunction readTo(text: string, ctx: { position: number }, searchRegTerm: RegExp): string | null {\r\n const start = ctx.position || 0;\r\n const slicedText = text.slice(start);\r\n const match = searchRegTerm.exec(slicedText);\r\n if (!match) {\r\n return null;\r\n }\r\n const end = start + match.index;\r\n ctx.position = end + match[0].length;\r\n return text.substring(start, end);\r\n}\r\n\r\n//partially taken from https://github.com/emiltholin/google-api-batch-utils\r\nfunction getHttpStatus(response: string) {\r\n const parts = HTTP_STATUS_REGEX.exec(response);\r\n //todo: add error handler for httpStatus and httpStatusMessage; remove \"!\" operator\r\n return { httpStatusString: parts![0], httpStatus: parseInt(parts![1]), httpStatusMessage: parts![2].trim() };\r\n}\r\n\r\nfunction getPlainContent(response: string) {\r\n // Reset the lastIndex property to ensure correct matching\r\n HTTP_STATUS_REGEX.lastIndex = 0;\r\n\r\n const textReg = TEXT_REGEX.exec(response.trim());\r\n return textReg?.length ? textReg[0] : undefined;\r\n}\r\n\r\nfunction handlePlainContent(batchResponse: string, parseParams: any, requestNumber: number): any {\r\n const plainContent = getPlainContent(batchResponse);\r\n return handlePlainResponse(plainContent);\r\n}\r\n\r\nfunction handleEmptyContent(batchResponse: string, parseParams: any, requestNumber: number): any {\r\n if (parseParams?.[requestNumber]?.valueIfEmpty !== undefined) {\r\n return parseParams[requestNumber].valueIfEmpty;\r\n } else {\r\n const entityUrl = ODATA_ENTITYID_REGEX.exec(batchResponse);\r\n return extractUuidFromUrl(entityUrl?.[0]) ?? undefined;\r\n }\r\n}\r\n\r\nfunction processBatchPart(batchResponse: string, parseParams: any, requestNumber: number): any {\r\n const { httpStatusString, httpStatus, httpStatusMessage } = getHttpStatus(batchResponse);\r\n const responseData = batchResponse.substring(batchResponse.indexOf(\"{\"), batchResponse.lastIndexOf(\"}\") + 1);\r\n\r\n //if the batch part does not contain a json response, parse it as plain or empty content\r\n if (!responseData) {\r\n if (CONTENT_TYPE_PLAIN_REGEX.test(batchResponse)) {\r\n return handlePlainContent(batchResponse, parseParams, requestNumber);\r\n }\r\n\r\n return handleEmptyContent(batchResponse, parseParams, requestNumber);\r\n }\r\n\r\n //parse json data\r\n const parsedResponse = handleJsonResponse(responseData, parseParams, requestNumber);\r\n\r\n if (httpStatus < 400) {\r\n return parsedResponse;\r\n }\r\n\r\n //handle error\r\n const responseHeaders = parseBatchHeaders(\r\n batchResponse.substring(batchResponse.indexOf(httpStatusString) + httpStatusString.length + 1, batchResponse.indexOf(\"{\"))\r\n );\r\n\r\n return ErrorHelper.handleHttpError(parsedResponse, {\r\n status: httpStatus,\r\n statusText: httpStatusMessage,\r\n statusMessage: httpStatusMessage,\r\n headers: responseHeaders,\r\n });\r\n}\r\n\r\n/**\r\n *\r\n * @param {string} response - response that needs to be parsed\r\n * @param {Array} parseParams - parameters for parsing the response\r\n * @param {Number} [requestNumber] - number of the request\r\n * @returns {any} parsed batch response\r\n */\r\nexport function parseBatchResponse(response: string, parseParams: any, requestNumber: number = 0): (string | undefined | DynamicsWebApiError | Number)[] {\r\n // Not the same delimiter in the response as we specify ourselves in the request,\r\n // so we have to extract it.\r\n const delimiter = response.substring(0, response.search(LINE_ENDING_REGEX));\r\n const batchResponseParts = response.split(delimiter);\r\n // The first part will always be an empty string. Just remove it.\r\n batchResponseParts.shift();\r\n // The last part will be the \"--\". Just remove it.\r\n batchResponseParts.pop();\r\n\r\n let result: (string | undefined | DynamicsWebApiError | Number)[] = [];\r\n for (let part of batchResponseParts) {\r\n if (part.indexOf(\"--changesetresponse_\") === -1) {\r\n result.push(processBatchPart(part, parseParams, requestNumber++));\r\n continue;\r\n }\r\n\r\n part = part.trim();\r\n const batchToProcess = part.substring(part.search(LINE_ENDING_REGEX) + 1).trim();\r\n result = result.concat(parseBatchResponse(batchToProcess, parseParams, requestNumber++));\r\n }\r\n\r\n return result;\r\n}\r\n", "\uFEFFimport { DWA } from \"../../dwa\";\r\nimport { getHeader, hasHeader, getFetchXmlPagingCookie } from \"../../utils/Utility\";\r\nimport { dateReviver } from \"./dateReviver\";\r\nimport type * as Core from \"../../types\";\r\nimport { convertToReferenceObject, extractUuidFromUrl } from \"../../helpers/Regex\";\r\nimport { parseBatchResponse } from \"./parseBatchResponse\";\r\n\r\nfunction getFormattedKeyValue(keyName: string, value: any): any[] {\r\n let newKey: string | null = null;\r\n if (keyName.indexOf(\"@\") !== -1) {\r\n const format = keyName.split(\"@\");\r\n switch (format[1]) {\r\n case \"odata.context\":\r\n newKey = \"oDataContext\";\r\n break;\r\n case \"odata.count\":\r\n newKey = \"oDataCount\";\r\n value = value != null ? parseInt(value) : 0;\r\n break;\r\n case \"odata.nextLink\":\r\n newKey = \"oDataNextLink\";\r\n break;\r\n case \"odata.deltaLink\":\r\n newKey = \"oDataDeltaLink\";\r\n break;\r\n case DWA.Prefer.Annotations.FormattedValue:\r\n newKey = format[0] + \"_Formatted\";\r\n break;\r\n case DWA.Prefer.Annotations.AssociatedNavigationProperty:\r\n newKey = format[0] + \"_NavigationProperty\";\r\n break;\r\n case DWA.Prefer.Annotations.LookupLogicalName:\r\n newKey = format[0] + \"_LogicalName\";\r\n break;\r\n }\r\n }\r\n\r\n return [newKey, value];\r\n}\r\n\r\n/**\r\n *\r\n * @param object - parsed JSON object\r\n * @param parseParams - parameters for parsing the response\r\n * @returns parsed batch response\r\n */\r\nexport function parseData(object: Record, parseParams?: any): any {\r\n if (parseParams) {\r\n if (parseParams.isRef && object[\"@odata.id\"] != null) {\r\n return convertToReferenceObject(object);\r\n }\r\n\r\n if (parseParams.toCount) {\r\n return getFormattedKeyValue(\"@odata.count\", object[\"@odata.count\"])[1] || 0;\r\n }\r\n }\r\n\r\n for (const currentKey in object) {\r\n if (object[currentKey] != null) {\r\n if (Array.isArray(object[currentKey])) {\r\n for (var j = 0; j < object[currentKey].length; j++) {\r\n object[currentKey][j] = parseData(object[currentKey][j]);\r\n }\r\n } else if (typeof object[currentKey] === \"object\") {\r\n parseData(object[currentKey]);\r\n }\r\n }\r\n\r\n //parse formatted values\r\n let formattedKeyValue = getFormattedKeyValue(currentKey, object[currentKey]);\r\n if (formattedKeyValue[0]) {\r\n object[formattedKeyValue[0]] = formattedKeyValue[1];\r\n }\r\n\r\n //parse aliased values\r\n if (currentKey.indexOf(\"_x002e_\") !== -1) {\r\n const aliasKeys = currentKey.split(\"_x002e_\");\r\n\r\n if (!object.hasOwnProperty(aliasKeys[0])) {\r\n object[aliasKeys[0]] = { _dwaType: \"alias\" };\r\n }\r\n //throw an error if there is already a property which is not an 'alias'\r\n else if (\r\n typeof object[aliasKeys[0]] !== \"object\" ||\r\n (typeof object[aliasKeys[0]] === \"object\" && !object[aliasKeys[0]].hasOwnProperty(\"_dwaType\"))\r\n ) {\r\n throw new Error(\"The alias name of the linked entity must be unique!\");\r\n }\r\n\r\n object[aliasKeys[0]][aliasKeys[1]] = object[currentKey];\r\n\r\n //aliases also contain formatted values\r\n formattedKeyValue = getFormattedKeyValue(aliasKeys[1], object[currentKey]);\r\n if (formattedKeyValue[0]) {\r\n object[aliasKeys[0]][formattedKeyValue[0]] = formattedKeyValue[1];\r\n }\r\n }\r\n }\r\n\r\n if (parseParams) {\r\n if (parseParams.hasOwnProperty(\"pageNumber\") && object[\"@\" + DWA.Prefer.Annotations.FetchXmlPagingCookie] != null) {\r\n object.PagingInfo = getFetchXmlPagingCookie(object[\"@\" + DWA.Prefer.Annotations.FetchXmlPagingCookie], parseParams.pageNumber);\r\n }\r\n }\r\n\r\n return object;\r\n}\r\n\r\nfunction base64ToString(base64: string): string {\r\n return global.DWA_BROWSER ? global.window.atob(base64) : Buffer.from(base64, \"base64\").toString(\"binary\");\r\n}\r\n\r\nfunction parseFileResponse(response: string, responseHeaders: any, parseParams: any): Core.FileParseResult {\r\n let data = response;\r\n\r\n if (parseParams?.hasOwnProperty(\"parse\")) {\r\n data = JSON.parse(data).value;\r\n data = base64ToString(data);\r\n }\r\n\r\n const parseResult: Core.FileParseResult = {\r\n value: data,\r\n };\r\n\r\n if (responseHeaders[\"x-ms-file-name\"]) parseResult.fileName = responseHeaders[\"x-ms-file-name\"];\r\n if (responseHeaders[\"x-ms-file-size\"]) parseResult.fileSize = parseInt(responseHeaders[\"x-ms-file-size\"]);\r\n const location = getHeader(responseHeaders, \"Location\");\r\n if (location) parseResult.location = location;\r\n\r\n return parseResult;\r\n}\r\n\r\nfunction isBatchResponse(response: string): boolean {\r\n return response.indexOf(\"--batchresponse_\") > -1;\r\n}\r\n\r\nfunction isFileResponse(responseHeaders: Record): boolean {\r\n return hasHeader(responseHeaders, \"Content-Disposition\");\r\n}\r\nfunction isJsonResponse(responseHeaders: Record): boolean {\r\n const contentType = getHeader(responseHeaders, \"Content-Type\");\r\n return contentType?.startsWith(\"application/json\") == true;\r\n}\r\n\r\nfunction handleBatchResponse(response: string, parseParams: any) {\r\n const batch = parseBatchResponse(response, parseParams);\r\n return parseParams?.[0].convertedToBatch ? batch[0] : batch;\r\n}\r\n\r\nfunction handleFileResponse(response: string, responseHeaders: any, parseParams: any): any {\r\n return parseFileResponse(response, responseHeaders, parseParams[0]);\r\n}\r\n\r\nexport function handleJsonResponse(response: string, parseParams: any, requestNumber: number = 0): any {\r\n return parseData(JSON.parse(response, dateReviver), parseParams[requestNumber]);\r\n}\r\n\r\nexport function handlePlainResponse(response?: string): number | string | undefined {\r\n const numberResponse = Number(response);\r\n return isFinite(numberResponse) ? numberResponse : response;\r\n}\r\n\r\nfunction handleEmptyResponse(responseHeaders: Record, parseParams: any): any {\r\n //checking if there is a valueIfEmpty parameter and return it if it is set\r\n if (parseParams?.[0]?.valueIfEmpty !== undefined) {\r\n return parseParams[0].valueIfEmpty;\r\n }\r\n //checking if the response contains an entity id, if it does - return it\r\n const entityUrl = getHeader(responseHeaders, \"OData-EntityId\");\r\n if (entityUrl) {\r\n return extractUuidFromUrl(entityUrl) ?? undefined;\r\n }\r\n //checking if the response has a location header\r\n const location = getHeader(responseHeaders, \"Location\");\r\n if (location) {\r\n const result: { location: string; chunkSize?: number; backgroundOperationId?: string } = { location: location };\r\n if (responseHeaders[\"x-ms-chunk-size\"]) {\r\n result.chunkSize = parseInt(responseHeaders[\"x-ms-chunk-size\"]);\r\n }\r\n if (responseHeaders[\"x-ms-dyn-backgroundoperationid\"]) {\r\n result.backgroundOperationId = responseHeaders[\"x-ms-dyn-backgroundoperationid\"];\r\n }\r\n return result;\r\n }\r\n}\r\n\r\n/**\r\n *\r\n * @param response - response that needs to be parsed\r\n * @param responseHeaders - response headers\r\n * @param parseParams - parameters for parsing the response\r\n * @returns parsed response\r\n */\r\nexport function parseResponse(response: string, responseHeaders: Record, parseParams: any[]): any {\r\n if (!response.length) {\r\n return handleEmptyResponse(responseHeaders, parseParams);\r\n }\r\n if (isBatchResponse(response)) {\r\n return handleBatchResponse(response, parseParams);\r\n }\r\n if (isFileResponse(responseHeaders)) {\r\n return handleFileResponse(response, responseHeaders, parseParams);\r\n }\r\n if (isJsonResponse(responseHeaders)) {\r\n return handleJsonResponse(response, parseParams);\r\n }\r\n return handlePlainResponse(response);\r\n}\r\n", "\uFEFFexport function parseResponseHeaders(headerStr: string): Record {\r\n\tconst headers: Record = {};\r\n\tif (!headerStr) {\r\n\t\treturn headers;\r\n\t}\r\n\tconst headerPairs = headerStr.split(\"\\u000d\\u000a\");\r\n\tfor (let i = 0, ilen = headerPairs.length; i < ilen; i++) {\r\n\t\tconst headerPair = headerPairs[i];\r\n\t\tconst index = headerPair.indexOf(\"\\u003a\\u0020\");\r\n\t\tif (index > 0) {\r\n\t\t\theaders[headerPair.substring(0, index)] = headerPair.substring(index + 2);\r\n\t\t}\r\n\t}\r\n\treturn headers;\r\n}\r\n", "\uFEFFimport type * as Core from \"../types\";\r\nimport { ErrorHelper } from \"./../helpers/ErrorHelper\";\r\nimport { parseResponse } from \"./helpers/parseResponse\";\r\nimport { parseResponseHeaders } from \"./helpers/parseResponseHeaders\";\r\n\r\nexport function executeRequest(options: Core.RequestOptions): Promise {\r\n return new Promise((resolve, reject) => {\r\n _executeRequest(options, resolve, reject);\r\n });\r\n}\r\n\r\nfunction _executeRequest(\r\n options: Core.RequestOptions,\r\n successCallback: (response: Core.WebApiResponse) => void,\r\n errorCallback: (error: Core.WebApiErrorResponse | Core.WebApiErrorResponse[]) => void,\r\n) {\r\n const data = options.data;\r\n const headers = options.headers;\r\n const responseParams = options.responseParams;\r\n const signal = options.abortSignal;\r\n\r\n if (signal?.aborted) {\r\n errorCallback(\r\n ErrorHelper.handleHttpError({\r\n name: \"AbortError\",\r\n code: 20,\r\n message: \"The user aborted a request.\",\r\n }),\r\n );\r\n\r\n return;\r\n }\r\n\r\n let request = new XMLHttpRequest();\r\n request.open(options.method, options.uri, options.isAsync || false);\r\n\r\n //set additional headers\r\n for (let key in headers) {\r\n request.setRequestHeader(key, headers[key]);\r\n }\r\n\r\n request.onreadystatechange = function () {\r\n if (request.readyState === 4) {\r\n if (signal) signal.removeEventListener(\"abort\", abort);\r\n\r\n if (!request || request.status === 0) return; // response was handled elsewhere or will be handled by onerror\r\n\r\n if ((request.status >= 200 && request.status < 300) || request.status === 304) {\r\n // Success with Not Modified\r\n const responseHeaders = parseResponseHeaders(request.getAllResponseHeaders());\r\n const responseData = parseResponse(request.responseText, responseHeaders, responseParams[options.requestId]);\r\n\r\n const response = {\r\n data: responseData,\r\n headers: responseHeaders,\r\n status: request.status,\r\n };\r\n\r\n request = null as any;\r\n\r\n successCallback(response);\r\n } else {\r\n // All other statuses are error cases.\r\n let error;\r\n let headers;\r\n try {\r\n headers = parseResponseHeaders(request.getAllResponseHeaders());\r\n const errorParsed = parseResponse(request.responseText, headers, responseParams[options.requestId]);\r\n\r\n if (Array.isArray(errorParsed)) {\r\n errorCallback(errorParsed);\r\n return;\r\n }\r\n\r\n error = errorParsed.error;\r\n } catch (e) {\r\n if (request.response.length > 0) {\r\n error = { message: request.response };\r\n } else {\r\n error = { message: \"Unexpected Error\" };\r\n }\r\n }\r\n\r\n const errorParameters = {\r\n status: request.status,\r\n statusText: request.statusText,\r\n headers: headers,\r\n };\r\n\r\n request = null as any;\r\n\r\n errorCallback(ErrorHelper.handleHttpError(error, errorParameters));\r\n }\r\n }\r\n };\r\n\r\n if (options.timeout) {\r\n request.timeout = options.timeout;\r\n }\r\n\r\n request.onerror = function () {\r\n const headers = parseResponseHeaders(request.getAllResponseHeaders());\r\n errorCallback(\r\n ErrorHelper.handleHttpError({\r\n status: request.status,\r\n statusText: request.statusText,\r\n message: request.responseText || \"Network Error\",\r\n headers: headers,\r\n }),\r\n );\r\n request = null as any;\r\n };\r\n\r\n request.ontimeout = function () {\r\n const headers = parseResponseHeaders(request.getAllResponseHeaders());\r\n errorCallback(\r\n ErrorHelper.handleHttpError({\r\n name: \"TimeoutError\",\r\n status: request.status,\r\n statusText: request.statusText,\r\n message: request.responseText || \"Request Timed Out\",\r\n headers: headers,\r\n }),\r\n );\r\n request = null as any;\r\n };\r\n\r\n //browser abort\r\n request.onabort = function () {\r\n if (!request) return;\r\n\r\n const headers = parseResponseHeaders(request.getAllResponseHeaders());\r\n errorCallback(\r\n ErrorHelper.handleHttpError({\r\n status: request.status,\r\n statusText: request.statusText,\r\n message: \"Request aborted\",\r\n headers: headers,\r\n }),\r\n );\r\n request = null as any;\r\n };\r\n\r\n //manual abort/cancellation\r\n const abort = () => {\r\n if (!request) return;\r\n\r\n const headers = parseResponseHeaders(request.getAllResponseHeaders());\r\n\r\n errorCallback(\r\n ErrorHelper.handleHttpError({\r\n name: \"AbortError\",\r\n code: 20,\r\n status: request.status,\r\n statusText: request.statusText,\r\n message: \"The user aborted a request.\",\r\n headers: headers,\r\n }),\r\n );\r\n\r\n request.abort();\r\n\r\n request = null as any;\r\n };\r\n\r\n if (signal) {\r\n signal.addEventListener(\"abort\", abort);\r\n }\r\n\r\n data ? request.send(data) : request.send();\r\n\r\n //called for testing\r\n if (XhrWrapper.afterSendEvent) XhrWrapper.afterSendEvent();\r\n}\r\n\r\n/**\r\n * Sends a request to given URL with given parameters\r\n */\r\nexport class XhrWrapper {\r\n //for testing\r\n static afterSendEvent: () => void;\r\n}\r\n", "import { isRunningWithinPortals, getClientUrl } from \"./Utility\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { ApiConfig, Config, SearchApiOptions } from \"../dynamics-web-api\";\r\nimport { LIBRARY_NAME } from \"../requests/constants\";\r\n\r\ntype ApiType = \"dataApi\" | \"searchApi\" | \"serviceApi\";\r\n\r\nconst FUNCTION_NAME = `${LIBRARY_NAME}.setConfig`;\r\n\r\nconst apiConfigs: ApiType[] = [\"dataApi\", \"searchApi\", \"serviceApi\"];\r\n\r\nexport interface InternalApiConfig extends ApiConfig {\r\n url: string;\r\n escapeSpecialCharacters?: boolean;\r\n enableSearchApiResponseCompatibility?: boolean;\r\n}\r\n\r\nexport interface InternalConfig extends Config {\r\n dataApi: InternalApiConfig;\r\n searchApi: InternalApiConfig;\r\n serviceApi: InternalApiConfig;\r\n}\r\n\r\nexport const getApiUrl = (serverUrl: string | undefined | null, apiConfig: ApiConfig): string => {\r\n if (isRunningWithinPortals()) {\r\n return new URL(\"_api\", global.window.location.origin).toString() + \"/\";\r\n } else {\r\n if (!serverUrl) serverUrl = getClientUrl();\r\n\r\n let url = \"api\";\r\n if (apiConfig.path) {\r\n url += `/${apiConfig.path}`;\r\n }\r\n if (apiConfig.version) {\r\n url += `/v${apiConfig.version}`;\r\n }\r\n\r\n return new URL(url, serverUrl).toString() + \"/\";\r\n }\r\n};\r\n\r\nconst mergeSearchApiOptions = (internalApiConfig: InternalApiConfig, options: SearchApiOptions | undefined): void => {\r\n if (!options) return;\r\n\r\n if (options.escapeSpecialCharacters != null) {\r\n ErrorHelper.boolParameterCheck(options.escapeSpecialCharacters, FUNCTION_NAME, `config.searchApi.options.escapeSpecialCharacters`);\r\n internalApiConfig.escapeSpecialCharacters = options.escapeSpecialCharacters;\r\n }\r\n\r\n if (options.enableResponseCompatibility != null) {\r\n ErrorHelper.boolParameterCheck(options.enableResponseCompatibility, FUNCTION_NAME, `config.searchApi.options.enableResponseCompatibility`);\r\n internalApiConfig.enableSearchApiResponseCompatibility = options.enableResponseCompatibility;\r\n }\r\n};\r\n\r\nexport const mergeApiConfig = (internalConfig: InternalConfig, apiType: ApiType, config: Config | undefined): void => {\r\n const internalApiConfig = internalConfig[apiType] as InternalApiConfig;\r\n const apiConfig = config?.[apiType] as ApiConfig | undefined;\r\n\r\n if (apiConfig?.version) {\r\n ErrorHelper.stringParameterCheck(apiConfig.version, FUNCTION_NAME, `config.${apiType}.version`);\r\n internalApiConfig.version = apiConfig.version;\r\n }\r\n\r\n if (apiConfig?.path) {\r\n ErrorHelper.stringParameterCheck(apiConfig.path, FUNCTION_NAME, `config.${apiType}.path`);\r\n internalApiConfig.path = apiConfig.path;\r\n }\r\n\r\n if (apiType === \"searchApi\") {\r\n mergeSearchApiOptions(internalApiConfig, apiConfig?.options);\r\n }\r\n\r\n internalApiConfig.url = getApiUrl(internalConfig.serverUrl, internalApiConfig);\r\n};\r\n\r\nexport function mergeConfig(internalConfig: InternalConfig, config?: Config): void {\r\n if (config?.serverUrl) {\r\n ErrorHelper.stringParameterCheck(config.serverUrl, FUNCTION_NAME, \"config.serverUrl\");\r\n internalConfig.serverUrl = config.serverUrl;\r\n }\r\n\r\n apiConfigs.forEach((apiType) => {\r\n mergeApiConfig(internalConfig, apiType, config);\r\n });\r\n\r\n if (config?.impersonate) {\r\n internalConfig.impersonate = ErrorHelper.guidParameterCheck(config.impersonate, FUNCTION_NAME, \"config.impersonate\");\r\n }\r\n\r\n if (config?.impersonateAAD) {\r\n internalConfig.impersonateAAD = ErrorHelper.guidParameterCheck(config.impersonateAAD, FUNCTION_NAME, \"config.impersonateAAD\");\r\n }\r\n\r\n if (config?.onTokenRefresh) {\r\n ErrorHelper.callbackParameterCheck(config.onTokenRefresh, FUNCTION_NAME, \"config.onTokenRefresh\");\r\n internalConfig.onTokenRefresh = config.onTokenRefresh;\r\n }\r\n\r\n if (config?.includeAnnotations) {\r\n ErrorHelper.stringParameterCheck(config.includeAnnotations, FUNCTION_NAME, \"config.includeAnnotations\");\r\n internalConfig.includeAnnotations = config.includeAnnotations;\r\n }\r\n\r\n if (config?.timeout) {\r\n ErrorHelper.numberParameterCheck(config.timeout, FUNCTION_NAME, \"config.timeout\");\r\n internalConfig.timeout = config.timeout;\r\n }\r\n\r\n if (config?.maxPageSize) {\r\n ErrorHelper.numberParameterCheck(config.maxPageSize, FUNCTION_NAME, \"config.maxPageSize\");\r\n internalConfig.maxPageSize = config.maxPageSize;\r\n }\r\n\r\n if (config?.returnRepresentation != null) {\r\n ErrorHelper.boolParameterCheck(config.returnRepresentation, FUNCTION_NAME, \"config.returnRepresentation\");\r\n internalConfig.returnRepresentation = config.returnRepresentation;\r\n }\r\n\r\n if (config?.useEntityNames != null) {\r\n ErrorHelper.boolParameterCheck(config.useEntityNames, FUNCTION_NAME, \"config.useEntityNames\");\r\n internalConfig.useEntityNames = config.useEntityNames;\r\n }\r\n\r\n if (config?.headers) {\r\n internalConfig.headers = config.headers;\r\n }\r\n\r\n if (!global.DWA_BROWSER && config?.proxy) {\r\n ErrorHelper.parameterCheck(config.proxy, FUNCTION_NAME, \"config.proxy\");\r\n\r\n if (config.proxy.url) {\r\n ErrorHelper.stringParameterCheck(config.proxy.url, FUNCTION_NAME, \"config.proxy.url\");\r\n\r\n if (config.proxy.auth) {\r\n ErrorHelper.parameterCheck(config.proxy.auth, FUNCTION_NAME, \"config.proxy.auth\");\r\n ErrorHelper.stringParameterCheck(config.proxy.auth.username, FUNCTION_NAME, \"config.proxy.auth.username\");\r\n ErrorHelper.stringParameterCheck(config.proxy.auth.password, FUNCTION_NAME, \"config.proxy.auth.password\");\r\n }\r\n }\r\n\r\n internalConfig.proxy = config.proxy;\r\n }\r\n}\r\n\r\nexport function defaultConfig(): InternalConfig {\r\n return {\r\n serverUrl: null,\r\n impersonate: null,\r\n impersonateAAD: null,\r\n onTokenRefresh: null,\r\n includeAnnotations: null,\r\n maxPageSize: null,\r\n returnRepresentation: null,\r\n proxy: null,\r\n dataApi: {\r\n path: \"data\",\r\n version: \"9.2\",\r\n url: \"\",\r\n },\r\n searchApi: {\r\n path: \"search\",\r\n version: \"1.0\",\r\n url: \"\",\r\n },\r\n serviceApi: {\r\n url: \"\",\r\n },\r\n };\r\n}\r\n", "export const LIBRARY_NAME = \"DynamicsWebApi\";", "import type * as Core from \"../types\";\r\nimport type { AccessToken } from \"../dynamics-web-api\";\r\nimport type { InternalConfig } from \"../utils/Config\";\r\nimport { generateUUID, isRunningWithinPortals, isNull } from \"../utils/Utility\";\r\nimport * as EntityMapper from \"./helpers/entityNameMapper\";\r\nimport { executeRequest } from \"./helpers/executeRequest\";\r\nimport { DynamicsWebApiError, ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { composeRequest, convertToBatch, processData, setStandardHeaders } from \"./request\";\r\n\r\nconst _addResponseParams = (requestId: string, responseParams: Record) => {\r\n if (_responseParseParams[requestId]) _responseParseParams[requestId].push(responseParams);\r\n else _responseParseParams[requestId] = [responseParams];\r\n};\r\n\r\nconst _addRequestToBatchCollection = (requestId: string, request: Core.InternalRequest) => {\r\n if (_batchRequestCollection[requestId]) _batchRequestCollection[requestId].push(request);\r\n else _batchRequestCollection[requestId] = [request];\r\n};\r\n\r\nconst _clearRequestData = (requestId: string): void => {\r\n delete _responseParseParams[requestId];\r\n if (_batchRequestCollection.hasOwnProperty(requestId)) delete _batchRequestCollection[requestId];\r\n};\r\n\r\nconst _runRequest = async (request: Core.InternalRequest, config: InternalConfig): Promise => {\r\n try {\r\n const result = await sendRequest(request, config);\r\n _clearRequestData(request.requestId!);\r\n\r\n return result;\r\n } catch (error) {\r\n _clearRequestData(request.requestId!);\r\n throw error;\r\n } finally {\r\n _clearRequestData(request.requestId!);\r\n }\r\n};\r\n\r\nlet _batchRequestCollection: Core.BatchRequestCollection = {};\r\nlet _responseParseParams: { [key: string]: any[] } = {};\r\n\r\nconst _nameExceptions = [\r\n \"$metadata\",\r\n \"EntityDefinitions\",\r\n \"RelationshipDefinitions\",\r\n \"GlobalOptionSetDefinitions\",\r\n \"ManagedPropertyDefinitions\",\r\n \"query\",\r\n \"suggest\",\r\n \"autocomplete\",\r\n];\r\n\r\nconst _isEntityNameException = (entityName: string): boolean => {\r\n return _nameExceptions.indexOf(entityName) > -1;\r\n};\r\n\r\nconst _getCollectionNames = async (entityName: string, config: InternalConfig): Promise => {\r\n if (!isNull(EntityMapper.entityNames)) {\r\n return EntityMapper.findCollectionName(entityName) || entityName;\r\n }\r\n\r\n const request = composeRequest(\r\n {\r\n method: \"GET\",\r\n collection: \"EntityDefinitions\",\r\n select: [\"EntitySetName\", \"LogicalName\"],\r\n noCache: true,\r\n functionName: \"retrieveMultiple\",\r\n },\r\n config,\r\n );\r\n\r\n const result = await _runRequest(request, config);\r\n EntityMapper.setEntityNames({});\r\n for (let i = 0; i < result.data.value.length; i++) {\r\n EntityMapper.entityNames![result.data.value[i].LogicalName] = result.data.value[i].EntitySetName;\r\n }\r\n\r\n return EntityMapper.findCollectionName(entityName) || entityName;\r\n};\r\n\r\nconst _checkCollectionName = async (entityName: string | null | undefined, config: InternalConfig): Promise => {\r\n if (!entityName || _isEntityNameException(entityName)) {\r\n return entityName;\r\n }\r\n\r\n entityName = entityName.toLowerCase();\r\n\r\n if (!config.useEntityNames) {\r\n return entityName;\r\n }\r\n\r\n try {\r\n return await _getCollectionNames(entityName, config);\r\n } catch (error: any) {\r\n throw new Error(\"Unable to fetch Collection Names. Error: \" + (error as DynamicsWebApiError).message);\r\n }\r\n};\r\n\r\n/**\r\n * Sends a request to given URL with given parameters\r\n *\r\n * @param {InternalRequest} request - Composed request to D365 Web Api\r\n * @param {InternalConfig} config - DynamicsWebApi config.\r\n */\r\nexport const sendRequest = async (request: Core.InternalRequest, config: InternalConfig): Promise => {\r\n request.headers = request.headers || {};\r\n request.responseParameters = request.responseParameters || {};\r\n request.requestId = request.requestId || generateUUID();\r\n\r\n //add response parameters to parse\r\n _addResponseParams(request.requestId, request.responseParameters);\r\n\r\n //stringify passed data\r\n let processedData = null;\r\n\r\n const isBatchConverted = request.responseParameters?.convertedToBatch;\r\n\r\n if (request.path === \"$batch\" && !isBatchConverted) {\r\n const batchRequest = _batchRequestCollection[request.requestId];\r\n\r\n if (!batchRequest) throw ErrorHelper.batchIsEmpty();\r\n\r\n const batchResult = convertToBatch(batchRequest, config, request);\r\n\r\n processedData = batchResult.body;\r\n request.headers = { ...batchResult.headers, ...request.headers };\r\n\r\n //clear an array of requests\r\n delete _batchRequestCollection[request.requestId];\r\n } else {\r\n processedData = !isBatchConverted ? processData(request.data, config) : request.data;\r\n\r\n // don't set headers if the request is a part of batch request\r\n // or if it is set to not include default dataverse headers\r\n // todo: use the latter option in batch requests as well\r\n if (!isBatchConverted && request.includeDefaultDataverseHeaders !== false) {\r\n request.headers = setStandardHeaders(request.headers, request.data);\r\n }\r\n }\r\n\r\n if (config.impersonate && !request.headers![\"MSCRMCallerID\"]) {\r\n request.headers![\"MSCRMCallerID\"] = config.impersonate;\r\n }\r\n\r\n if (config.impersonateAAD && !request.headers![\"CallerObjectId\"]) {\r\n request.headers![\"CallerObjectId\"] = config.impersonateAAD;\r\n }\r\n\r\n let token: AccessToken | string | null = null;\r\n\r\n //call a token refresh callback only if it is set and there is no \"Authorization\" header set yet\r\n if (config.onTokenRefresh && (!request.headers || (request.headers && !request.headers[\"Authorization\"]))) {\r\n token = await config.onTokenRefresh();\r\n if (!token) throw new Error(\"Token is empty. Request is aborted.\");\r\n }\r\n\r\n if (token) {\r\n request.headers![\"Authorization\"] = \"Bearer \" + (token.hasOwnProperty(\"accessToken\") ? (token as AccessToken).accessToken : token);\r\n }\r\n\r\n if (isRunningWithinPortals()) {\r\n request.headers![\"__RequestVerificationToken\"] = await global.window.shell!.getTokenDeferred();\r\n }\r\n\r\n const url = request.apiConfig ? request.apiConfig.url : config.dataApi.url;\r\n\r\n return await executeRequest({\r\n method: request.method!,\r\n uri: url!.toString() + request.path,\r\n data: processedData,\r\n proxy: config.proxy,\r\n isAsync: request.async,\r\n headers: request.headers!,\r\n requestId: request.requestId!,\r\n abortSignal: request.signal,\r\n responseParams: _responseParseParams,\r\n timeout: request.timeout || config.timeout,\r\n });\r\n};\r\n\r\nexport const makeRequest = async (request: Core.InternalRequest, config: InternalConfig): Promise => {\r\n request.responseParameters = request.responseParameters || {};\r\n //we don't want to mix headers set by the library and by the user\r\n request.userHeaders = request.headers;\r\n delete request.headers;\r\n\r\n if (!request.isBatch) {\r\n const collectionName = await _checkCollectionName(request.collection, config);\r\n\r\n request.collection = collectionName;\r\n composeRequest(request, config);\r\n request.responseParameters.convertedToBatch = false;\r\n\r\n //the URL contains more characters than max possible limit, convert the request to a batch request\r\n if (request.path!.length > 2000) {\r\n const batchRequest = convertToBatch([request], config);\r\n\r\n //#175 authorization header must be copied as well.\r\n //todo: is it the only one that needs to be copied?\r\n if (request.headers![\"Authorization\"]) {\r\n batchRequest.headers[\"Authorization\"] = request.headers![\"Authorization\"];\r\n }\r\n\r\n request.method = \"POST\";\r\n request.path = \"$batch\";\r\n request.data = batchRequest.body;\r\n request.headers = { ...batchRequest.headers, ...request.userHeaders };\r\n request.responseParameters.convertedToBatch = true;\r\n }\r\n\r\n return _runRequest(request, config);\r\n }\r\n\r\n //no need to make a request to web api if it's a part of batch\r\n composeRequest(request, config);\r\n //add response parameters to parse\r\n _addResponseParams(request.requestId!, request.responseParameters);\r\n _addRequestToBatchCollection(request.requestId!, request);\r\n};\r\n\r\nexport const _clearTestData = (): void => {\r\n EntityMapper.setEntityNames(null);\r\n _responseParseParams = {};\r\n _batchRequestCollection = {};\r\n};\r\n\r\nexport const getCollectionName = (entityName: string): string | null => {\r\n return EntityMapper.findCollectionName(entityName);\r\n};\r\n", "import { isNull } from \"../../utils/Utility\";\r\n\r\nexport let entityNames: Record | null = null;\r\n\r\nexport const setEntityNames = (newEntityNames: Record | null) => {\r\n entityNames = newEntityNames;\r\n};\r\n\r\nexport const findCollectionName = (entityName: string): string | null => {\r\n if (isNull(entityNames)) return null;\r\n\r\n const collectionName = entityNames[entityName];\r\n if (!collectionName) {\r\n for (const key in entityNames) {\r\n if (entityNames[key] === entityName) {\r\n return entityName;\r\n }\r\n }\r\n }\r\n\r\n return collectionName;\r\n};", "import type { RequestOptions, WebApiResponse } from \"../../types\";\r\n\r\nexport async function executeRequest(options: RequestOptions): Promise {\r\n return global.DWA_BROWSER ? require(\"../xhr\").executeRequest(options) : require(\"../http\").executeRequest(options);\r\n}\r\n", "import { ErrorHelper } from \"../../../helpers/ErrorHelper\";\r\nimport { InternalRequest } from \"../../../types\";\r\nimport { safelyRemoveCurlyBracketsFromUrl } from \"../../../helpers/Regex\";\r\nimport { Config } from \"../../../dynamics-web-api\";\r\nimport { isNull } from \"../../../utils/Utility\";\r\n\r\n/**\r\n * Converts optional parameters of the request to URL. If expand parameter exists this function is called recursively.\r\n * @param request Internal request object\r\n * @param config Internal configuration object\r\n * @param url Starting url\r\n * @param joinSymbol Join symbol. \"&\" by default and \";\" inside an expand query parameter\r\n * @returns Request URL\r\n */\r\nexport const composeUrl = (request: InternalRequest | null, config: Config | null, url: string = \"\", joinSymbol: \"&\" | \";\" = \"&\"): string => {\r\n const queryArray: string[] = [];\r\n\r\n if (request) {\r\n if (request.navigationProperty) {\r\n ErrorHelper.stringParameterCheck(request.navigationProperty, `DynamicsWebApi.${request.functionName}`, \"request.navigationProperty\");\r\n url += \"/\" + request.navigationProperty;\r\n\r\n if (request.navigationPropertyKey) {\r\n let navigationKey = ErrorHelper.keyParameterCheck(\r\n request.navigationPropertyKey,\r\n `DynamicsWebApi.${request.functionName}`,\r\n \"request.navigationPropertyKey\",\r\n );\r\n url += \"(\" + navigationKey + \")\";\r\n }\r\n\r\n if (request.navigationProperty === \"Attributes\") {\r\n if (request.metadataAttributeType) {\r\n ErrorHelper.stringParameterCheck(request.metadataAttributeType, `DynamicsWebApi.${request.functionName}`, \"request.metadataAttributeType\");\r\n url += \"/\" + request.metadataAttributeType;\r\n }\r\n }\r\n }\r\n\r\n if (request.select?.length) {\r\n ErrorHelper.arrayParameterCheck(request.select, `DynamicsWebApi.${request.functionName}`, \"request.select\");\r\n\r\n if (request.functionName == \"retrieve\" && request.select.length == 1 && request.select[0].endsWith(\"/$ref\")) {\r\n url += \"/\" + request.select[0];\r\n } else {\r\n if (request.select[0].startsWith(\"/\") && request.functionName == \"retrieve\") {\r\n if (request.navigationProperty == null) {\r\n url += request.select.shift();\r\n } else {\r\n request.select.shift();\r\n }\r\n }\r\n\r\n //check if anything left in the array\r\n if (request.select.length) {\r\n queryArray.push(\"$select=\" + request.select.join(\",\"));\r\n }\r\n }\r\n }\r\n\r\n if (request.filter) {\r\n ErrorHelper.stringParameterCheck(request.filter, `DynamicsWebApi.${request.functionName}`, \"request.filter\");\r\n const filterResult = safelyRemoveCurlyBracketsFromUrl(request.filter);\r\n queryArray.push(\"$filter=\" + encodeURIComponent(filterResult));\r\n }\r\n\r\n //todo: delete in v2.5\r\n if (request.fieldName) {\r\n ErrorHelper.stringParameterCheck(request.fieldName, `DynamicsWebApi.${request.functionName}`, \"request.fieldName\");\r\n if (!request.property) request.property = request.fieldName;\r\n delete request.fieldName;\r\n }\r\n\r\n if (request.property) {\r\n ErrorHelper.stringParameterCheck(request.property, `DynamicsWebApi.${request.functionName}`, \"request.property\");\r\n url += \"/\" + request.property;\r\n }\r\n\r\n if (request.savedQuery) {\r\n queryArray.push(\"savedQuery=\" + ErrorHelper.guidParameterCheck(request.savedQuery, `DynamicsWebApi.${request.functionName}`, \"request.savedQuery\"));\r\n }\r\n\r\n if (request.userQuery) {\r\n queryArray.push(\"userQuery=\" + ErrorHelper.guidParameterCheck(request.userQuery, `DynamicsWebApi.${request.functionName}`, \"request.userQuery\"));\r\n }\r\n\r\n if (request.apply) {\r\n ErrorHelper.stringParameterCheck(request.apply, `DynamicsWebApi.${request.functionName}`, \"request.apply\");\r\n queryArray.push(\"$apply=\" + request.apply);\r\n }\r\n\r\n if (request.count) {\r\n ErrorHelper.boolParameterCheck(request.count, `DynamicsWebApi.${request.functionName}`, \"request.count\");\r\n queryArray.push(\"$count=\" + request.count);\r\n }\r\n\r\n if (request.top && request.top > 0) {\r\n ErrorHelper.numberParameterCheck(request.top, `DynamicsWebApi.${request.functionName}`, \"request.top\");\r\n queryArray.push(\"$top=\" + request.top);\r\n }\r\n\r\n if (request.orderBy != null && request.orderBy.length) {\r\n ErrorHelper.arrayParameterCheck(request.orderBy, `DynamicsWebApi.${request.functionName}`, \"request.orderBy\");\r\n queryArray.push(\"$orderby=\" + request.orderBy.join(\",\"));\r\n }\r\n\r\n if (request.partitionId) {\r\n ErrorHelper.stringParameterCheck(request.partitionId, `DynamicsWebApi.${request.functionName}`, \"request.partitionId\");\r\n queryArray.push(\"partitionid='\" + request.partitionId + \"'\");\r\n }\r\n\r\n if (request.downloadSize) {\r\n ErrorHelper.stringParameterCheck(request.downloadSize, `DynamicsWebApi.${request.functionName}`, \"request.downloadSize\");\r\n queryArray.push(\"size=\" + request.downloadSize);\r\n }\r\n\r\n if (request.tag) {\r\n ErrorHelper.stringParameterCheck(request.tag, `DynamicsWebApi.${request.functionName}`, \"request.tag\");\r\n queryArray.push(\"tag=\" + encodeURIComponent(request.tag));\r\n }\r\n\r\n if (request.queryParams?.length) {\r\n ErrorHelper.arrayParameterCheck(request.queryParams, `DynamicsWebApi.${request.functionName}`, \"request.queryParams\");\r\n queryArray.push(request.queryParams.join(\"&\"));\r\n }\r\n\r\n if (request.fileName) {\r\n ErrorHelper.stringParameterCheck(request.fileName, `DynamicsWebApi.${request.functionName}`, \"request.fileName\");\r\n queryArray.push(\"x-ms-file-name=\" + request.fileName);\r\n }\r\n\r\n if (request.data) {\r\n ErrorHelper.parameterCheck(request.data, `DynamicsWebApi.${request.functionName}`, \"request.data\");\r\n }\r\n\r\n if (request.isBatch) {\r\n ErrorHelper.boolParameterCheck(request.isBatch, `DynamicsWebApi.${request.functionName}`, \"request.isBatch\");\r\n }\r\n\r\n if (request.fetchXml) {\r\n ErrorHelper.stringParameterCheck(request.fetchXml, `DynamicsWebApi.${request.functionName}`, \"request.fetchXml\");\r\n queryArray.push(\"fetchXml=\" + encodeURIComponent(request.fetchXml));\r\n }\r\n\r\n if (!isNull(request.inChangeSet)) {\r\n ErrorHelper.boolParameterCheck(request.inChangeSet, `DynamicsWebApi.${request.functionName}`, \"request.inChangeSet\");\r\n }\r\n\r\n if (request.isBatch && isNull(request.inChangeSet)) request.inChangeSet = true;\r\n\r\n if (request.timeout) {\r\n ErrorHelper.numberParameterCheck(request.timeout, `DynamicsWebApi.${request.functionName}`, \"request.timeout\");\r\n }\r\n\r\n if (request.expand?.length) {\r\n ErrorHelper.stringOrArrayParameterCheck(request.expand, `DynamicsWebApi.${request.functionName}`, \"request.expand\");\r\n if (typeof request.expand === \"string\") {\r\n queryArray.push(\"$expand=\" + request.expand);\r\n } else {\r\n const expandQueryArray: string[] = [];\r\n for (const { property, ...expand } of request.expand) {\r\n if (!property) continue;\r\n\r\n const expandRequest: InternalRequest = {\r\n functionName: `${request.functionName} $expand`,\r\n ...expand,\r\n };\r\n let expandConverted = composeUrl(expandRequest, config, \"\", \";\");\r\n if (expandConverted) {\r\n expandConverted = `(${expandConverted})`;\r\n }\r\n expandQueryArray.push(property + expandConverted);\r\n }\r\n if (expandQueryArray.length) {\r\n queryArray.push(\"$expand=\" + expandQueryArray.join(\",\"));\r\n }\r\n }\r\n }\r\n }\r\n\r\n // nothing to add to the URL\r\n if (!queryArray.length) {\r\n return url;\r\n }\r\n\r\n // in any other cases the joinSymbol is \";\" (during expand process)\r\n if (joinSymbol === \"&\") {\r\n url += \"?\";\r\n }\r\n\r\n return url + queryArray.join(joinSymbol);\r\n\r\n // return !queryArray.length ? url : url + \"?\" + queryArray.join(joinSymbol);\r\n};\r\n", "import type { Config, HeaderCollection } from \"../../../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../../../helpers/ErrorHelper\";\r\nimport type { InternalRequest } from \"../../../types\";\r\nimport { composePreferHeader } from \"./preferHeader\";\r\n\r\nexport const composeHeaders = (request: InternalRequest, config: Config): HeaderCollection => {\r\n const headers: HeaderCollection = { ...config.headers, ...request.userHeaders };\r\n\r\n const prefer = composePreferHeader(request, config);\r\n if (prefer.length) {\r\n headers[\"Prefer\"] = prefer;\r\n }\r\n\r\n if (request.collection === \"$metadata\") {\r\n headers[\"Accept\"] = \"application/xml\";\r\n }\r\n\r\n if (request.transferMode) {\r\n headers[\"x-ms-transfer-mode\"] = request.transferMode;\r\n }\r\n\r\n if (request.ifmatch != null && request.ifnonematch != null) {\r\n throw new Error(\r\n `DynamicsWebApi.${request.functionName}. Either one of request.ifmatch or request.ifnonematch parameters should be used in a call, not both.`,\r\n );\r\n }\r\n\r\n if (request.ifmatch) {\r\n ErrorHelper.stringParameterCheck(request.ifmatch, `DynamicsWebApi.${request.functionName}`, \"request.ifmatch\");\r\n headers[\"If-Match\"] = request.ifmatch;\r\n }\r\n\r\n if (request.ifnonematch) {\r\n ErrorHelper.stringParameterCheck(request.ifnonematch, `DynamicsWebApi.${request.functionName}`, \"request.ifnonematch\");\r\n headers[\"If-None-Match\"] = request.ifnonematch;\r\n }\r\n\r\n if (request.impersonate) {\r\n ErrorHelper.stringParameterCheck(request.impersonate, `DynamicsWebApi.${request.functionName}`, \"request.impersonate\");\r\n headers[\"MSCRMCallerID\"] = ErrorHelper.guidParameterCheck(request.impersonate, `DynamicsWebApi.${request.functionName}`, \"request.impersonate\");\r\n }\r\n\r\n if (request.impersonateAAD) {\r\n ErrorHelper.stringParameterCheck(request.impersonateAAD, `DynamicsWebApi.${request.functionName}`, \"request.impersonateAAD\");\r\n headers[\"CallerObjectId\"] = ErrorHelper.guidParameterCheck(request.impersonateAAD, `DynamicsWebApi.${request.functionName}`, \"request.impersonateAAD\");\r\n }\r\n\r\n if (request.token) {\r\n ErrorHelper.stringParameterCheck(request.token, `DynamicsWebApi.${request.functionName}`, \"request.token\");\r\n headers[\"Authorization\"] = \"Bearer \" + request.token;\r\n }\r\n\r\n if (request.duplicateDetection) {\r\n ErrorHelper.boolParameterCheck(request.duplicateDetection, `DynamicsWebApi.${request.functionName}`, \"request.duplicateDetection\");\r\n headers[\"MSCRM.SuppressDuplicateDetection\"] = \"false\";\r\n }\r\n\r\n if (request.bypassCustomPluginExecution) {\r\n ErrorHelper.boolParameterCheck(request.bypassCustomPluginExecution, `DynamicsWebApi.${request.functionName}`, \"request.bypassCustomPluginExecution\");\r\n headers[\"MSCRM.BypassCustomPluginExecution\"] = \"true\";\r\n }\r\n\r\n if (request.noCache) {\r\n ErrorHelper.boolParameterCheck(request.noCache, `DynamicsWebApi.${request.functionName}`, \"request.noCache\");\r\n headers[\"Cache-Control\"] = \"no-cache\";\r\n }\r\n\r\n if (request.mergeLabels) {\r\n ErrorHelper.boolParameterCheck(request.mergeLabels, `DynamicsWebApi.${request.functionName}`, \"request.mergeLabels\");\r\n headers[\"MSCRM.MergeLabels\"] = \"true\";\r\n }\r\n\r\n if (request.contentId) {\r\n ErrorHelper.stringParameterCheck(request.contentId, `DynamicsWebApi.${request.functionName}`, \"request.contentId\");\r\n if (!request.contentId.startsWith(\"$\")) {\r\n headers[\"Content-ID\"] = request.contentId;\r\n }\r\n }\r\n\r\n if (request.contentRange) {\r\n ErrorHelper.stringParameterCheck(request.contentRange, `DynamicsWebApi.${request.functionName}`, \"request.contentRange\");\r\n headers[\"Content-Range\"] = request.contentRange;\r\n }\r\n\r\n if (request.range) {\r\n ErrorHelper.stringParameterCheck(request.range, `DynamicsWebApi.${request.functionName}`, \"request.range\");\r\n headers[\"Range\"] = request.range;\r\n }\r\n\r\n return headers;\r\n};", "import type { Config } from \"../../../dynamics-web-api\";\r\nimport type { InternalRequest } from \"../../../types\";\r\nimport { ErrorHelper } from \"../../../helpers/ErrorHelper\";\r\nimport { extractPreferCallbackUrl, removeDoubleQuotes } from \"../../../helpers/Regex\";\r\n\r\ntype PreferOptions = {\r\n returnRepresentation?: boolean | null;\r\n includeAnnotations?: string | null;\r\n maxPageSize?: number | null;\r\n trackChanges?: boolean;\r\n continueOnError?: boolean;\r\n backgroundOperationCallbackUrl?: string | null;\r\n respondAsync?: boolean;\r\n};\r\n\r\nexport const composePreferHeader = (request: InternalRequest, config: Config): string => {\r\n const functionName = `DynamicsWebApi.${request.functionName}`;\r\n\r\n // Extract request options with defaults from config\r\n const options: PreferOptions = {\r\n respondAsync: request.respondAsync,\r\n backgroundOperationCallbackUrl: request.backgroundOperationCallbackUrl ?? config?.backgroundOperationCallbackUrl,\r\n returnRepresentation: request.returnRepresentation ?? config?.returnRepresentation,\r\n includeAnnotations: request.includeAnnotations ?? config?.includeAnnotations,\r\n maxPageSize: request.maxPageSize ?? config?.maxPageSize,\r\n trackChanges: request.trackChanges,\r\n continueOnError: request.continueOnError,\r\n };\r\n\r\n const prefer: Set = new Set();\r\n\r\n // Process prefer header from request. Request items have a higher priority than config\r\n if (request.prefer?.length) {\r\n ErrorHelper.stringOrArrayParameterCheck(request.prefer, functionName, \"request.prefer\");\r\n const preferArray = typeof request.prefer === \"string\" ? request.prefer.split(\",\") : request.prefer;\r\n\r\n for (const item of preferArray) {\r\n const trimmedItem = item.trim();\r\n\r\n if (trimmedItem.includes(\"respond-async\")) {\r\n options.respondAsync = true;\r\n } else if (trimmedItem.startsWith(\"odata.callback\")) {\r\n options.backgroundOperationCallbackUrl = extractPreferCallbackUrl(trimmedItem);\r\n } else if (trimmedItem === \"return=representation\") {\r\n options.returnRepresentation = true;\r\n } else if (trimmedItem.includes(\"odata.include-annotations=\")) {\r\n options.includeAnnotations = removeDoubleQuotes(trimmedItem.replace(\"odata.include-annotations=\", \"\"));\r\n } else if (trimmedItem.startsWith(\"odata.maxpagesize=\")) {\r\n options.maxPageSize = Number(removeDoubleQuotes(trimmedItem.replace(\"odata.maxpagesize=\", \"\"))) || 0;\r\n } else if (trimmedItem.includes(\"odata.track-changes\")) {\r\n options.trackChanges = true;\r\n } else if (trimmedItem.includes(\"odata.continue-on-error\")) {\r\n options.continueOnError = true;\r\n } else {\r\n prefer.add(trimmedItem);\r\n }\r\n }\r\n }\r\n\r\n // Process prefer options\r\n for (const key in options) {\r\n const optionFactory = preferOptionsFactory[key];\r\n if (optionFactory && options[key]) {\r\n optionFactory.validator?.(options[key], functionName, `request.${key}`);\r\n if (optionFactory.condition(options[key], options)) {\r\n prefer.add(optionFactory.formatter(options[key], options));\r\n }\r\n }\r\n }\r\n\r\n return Array.from(prefer).join(\",\");\r\n};\r\n\r\ntype PreferValidationHandler = (value: any, functionName: string, paramName: string) => void;\r\ninterface PreferFactoryOption {\r\n validator?: PreferValidationHandler;\r\n condition: (value: any, options: Record) => boolean;\r\n formatter: (value: any, options: Record) => string;\r\n}\r\n\r\nconst preferOptionsFactory: Record = {\r\n respondAsync: {\r\n validator: ErrorHelper.boolParameterCheck,\r\n condition: (value) => !!value,\r\n formatter: () => \"respond-async\",\r\n },\r\n backgroundOperationCallbackUrl: {\r\n validator: ErrorHelper.stringParameterCheck,\r\n condition: (value, options) => value && options.respondAsync,\r\n formatter: (url) => `odata.callback;url=\"${url}\"`,\r\n },\r\n returnRepresentation: {\r\n validator: ErrorHelper.boolParameterCheck,\r\n condition: (value) => !!value,\r\n formatter: () => \"return=representation\",\r\n },\r\n includeAnnotations: {\r\n validator: ErrorHelper.stringParameterCheck,\r\n condition: (value) => !!value,\r\n formatter: (annotations) => `odata.include-annotations=\"${annotations}\"`,\r\n },\r\n maxPageSize: {\r\n validator: (value, functionName) => (value > 0 ? ErrorHelper.numberParameterCheck(value, functionName, \"request.maxPageSize\") : undefined),\r\n condition: (value) => value > 0,\r\n formatter: (size) => `odata.maxpagesize=${size}`,\r\n },\r\n trackChanges: {\r\n validator: ErrorHelper.boolParameterCheck,\r\n condition: (value) => !!value,\r\n formatter: () => \"odata.track-changes\",\r\n },\r\n continueOnError: {\r\n validator: ErrorHelper.boolParameterCheck,\r\n condition: (value) => !!value,\r\n formatter: () => \"odata.continue-on-error\",\r\n },\r\n};\r\n", "import { composeHeaders, composeUrl } from \".\";\r\nimport { ErrorHelper } from \"../../../helpers/ErrorHelper\";\r\nimport type { InternalRequest } from \"../../../types\";\r\nimport type { InternalConfig } from \"../../../utils/Config\";\r\n\r\n/**\r\n * Converts a request object to URL link\r\n * @param request Internal request object\r\n * @param config Internal configuration object\r\n * @returns Modified internal request object\r\n */\r\nexport const composeRequest = (request: InternalRequest, config: Partial): InternalRequest => {\r\n request.path = \"\"; //path must always be reset\r\n request.functionName = request.functionName || \"\";\r\n if (!request.url) {\r\n if (!request._isUnboundRequest && !request.contentId && !request.collection) {\r\n ErrorHelper.parameterCheck(request.collection, `DynamicsWebApi.${request.functionName}`, \"request.collection\");\r\n }\r\n\r\n if (request.contentId) {\r\n ErrorHelper.stringParameterCheck(request.contentId, `DynamicsWebApi.${request.functionName}`, \"request.contentId\");\r\n if (request.contentId.startsWith(\"$\")) {\r\n request.path = request.contentId;\r\n }\r\n }\r\n\r\n if (request.collection != null) {\r\n ErrorHelper.stringParameterCheck(request.collection, `DynamicsWebApi.${request.functionName}`, \"request.collection\");\r\n request.path += request.path ? `/${request.collection}` : request.collection;\r\n\r\n //add alternate key feature\r\n if (request.key) {\r\n request.key = ErrorHelper.keyParameterCheck(request.key, `DynamicsWebApi.${request.functionName}`, \"request.key\");\r\n request.path += `(${request.key})`;\r\n }\r\n }\r\n\r\n if (request.addPath) {\r\n if (request.path) {\r\n request.path += \"/\";\r\n }\r\n request.path += request.addPath;\r\n }\r\n\r\n request.path = composeUrl(request, config, request.path);\r\n } else {\r\n ErrorHelper.stringParameterCheck(request.url, `DynamicsWebApi.${request.functionName}`, \"request.url\");\r\n request.path = request.url.replace(config.dataApi!.url, \"\");\r\n }\r\n\r\n if (request.hasOwnProperty(\"async\") && request.async != null) {\r\n ErrorHelper.boolParameterCheck(request.async, `DynamicsWebApi.${request.functionName}`, \"request.async\");\r\n } else {\r\n request.async = true;\r\n }\r\n\r\n request.headers = composeHeaders(request, config);\r\n\r\n return request;\r\n};", "import { escapeUnicodeSymbols, removeCurlyBracketsFromUuid, removeLeadingSlash, SEARCH_FOR_ENTITY_NAME_REGEX } from \"../../helpers/Regex\";\r\nimport type { InternalConfig } from \"../../utils/Config\";\r\nimport { isNull } from \"../../utils/Utility\";\r\nimport { findCollectionName } from \"../helpers\";\r\n\r\nexport const processData = (data: any, config: InternalConfig): string | Uint8Array | Uint16Array | Uint32Array | null => {\r\n if (!data) return null;\r\n\r\n if (data instanceof Uint8Array || data instanceof Uint16Array || data instanceof Uint32Array) return data;\r\n\r\n const replaceEntityNameWithCollectionName = (value: string): string => {\r\n const valueParts = SEARCH_FOR_ENTITY_NAME_REGEX.exec(value);\r\n if (valueParts && valueParts.length > 2) {\r\n const collectionName = findCollectionName(valueParts[1]);\r\n if (!isNull(collectionName)) {\r\n return value.replace(SEARCH_FOR_ENTITY_NAME_REGEX, `${collectionName}$2`);\r\n }\r\n }\r\n return value;\r\n };\r\n\r\n const addFullWebApiUrl = (key: string, value: string): string => {\r\n if (!value.startsWith(config.dataApi.url)) {\r\n if (key.endsWith(\"@odata.bind\")) {\r\n if (!value.startsWith(\"/\")) {\r\n value = `/${value}`;\r\n }\r\n } else {\r\n value = `${config.dataApi.url}${removeLeadingSlash(value)}`;\r\n }\r\n }\r\n return value;\r\n };\r\n\r\n const stringifiedData = JSON.stringify(data, (key, value) => {\r\n if (key.endsWith(\"@odata.bind\") || key.endsWith(\"@odata.id\")) {\r\n if (typeof value === \"string\" && !value.startsWith(\"$\")) {\r\n value = removeCurlyBracketsFromUuid(value);\r\n if (config.useEntityNames) {\r\n value = replaceEntityNameWithCollectionName(value);\r\n }\r\n value = addFullWebApiUrl(key, value);\r\n }\r\n } else if (key.startsWith(\"oData\") || key.endsWith(\"_Formatted\") || key.endsWith(\"_NavigationProperty\") || key.endsWith(\"_LogicalName\")) {\r\n return undefined;\r\n }\r\n return value;\r\n });\r\n\r\n return escapeUnicodeSymbols(stringifiedData);\r\n};\r\n", "export * from \"./entityNameMapper\";\r\nexport * from \"./dateReviver\";\r\nexport * from \"./executeRequest\";\r\nexport * from \"./parseBatchResponse\";\r\nexport * from \"./parseResponse\";\r\nexport * from \"./parseResponseHeaders\";", "import type { HeaderCollection } from \"../../dynamics-web-api\";\r\n\r\nexport const setStandardHeaders = (headers: HeaderCollection = {}, data?: any): HeaderCollection => {\r\n if (!headers[\"Accept\"]) headers[\"Accept\"] = \"application/json\";\r\n if (!headers[\"OData-MaxVersion\"]) headers[\"OData-MaxVersion\"] = \"4.0\";\r\n if (!headers[\"OData-Version\"]) headers[\"OData-Version\"] = \"4.0\";\r\n if (headers[\"Content-Range\"]) headers[\"Content-Type\"] = \"application/octet-stream\";\r\n else if (!headers[\"Content-Type\"] && data) headers[\"Content-Type\"] = \"application/json; charset=utf-8\";\r\n\r\n return headers;\r\n};", "import { processData, setStandardHeaders } from \".\";\r\nimport { InternalConfig } from \"../../utils/Config\";\r\nimport { generateUUID } from \"../../utils/Utility\";\r\nimport type { InternalBatchRequest, InternalRequest } from \"../../types\";\r\n\r\nexport const convertToBatch = (requests: InternalRequest[], config: InternalConfig, batchRequest?: InternalRequest): InternalBatchRequest => {\r\n const batchBoundary = `dwa_batch_${generateUUID()}`;\r\n\r\n const batchBody: string[] = [];\r\n let currentChangeSet: string | null = null;\r\n let contentId = 100000;\r\n\r\n const addHeaders = (headers: Record, batchBody: string[]) => {\r\n for (const key in headers) {\r\n if (key === \"Authorization\" || key === \"Content-ID\") continue;\r\n batchBody.push(`${key}: ${headers[key]}`);\r\n }\r\n };\r\n\r\n requests.forEach((internalRequest) => {\r\n internalRequest.functionName = \"executeBatch\";\r\n if (batchRequest?.inChangeSet === false) internalRequest.inChangeSet = false;\r\n const inChangeSet = internalRequest.method === \"GET\" ? false : !!internalRequest.inChangeSet;\r\n\r\n if (!inChangeSet && currentChangeSet) {\r\n //end current change set\r\n batchBody.push(`\\r\\n--${currentChangeSet}--`);\r\n\r\n currentChangeSet = null;\r\n contentId = 100000;\r\n }\r\n\r\n if (!currentChangeSet) {\r\n batchBody.push(`\\r\\n--${batchBoundary}`);\r\n\r\n if (inChangeSet) {\r\n currentChangeSet = `changeset_${generateUUID()}`;\r\n batchBody.push(\"Content-Type: multipart/mixed;boundary=\" + currentChangeSet);\r\n }\r\n }\r\n\r\n if (inChangeSet) {\r\n batchBody.push(`\\r\\n--${currentChangeSet}`);\r\n }\r\n\r\n batchBody.push(\"Content-Type: application/http\");\r\n batchBody.push(\"Content-Transfer-Encoding: binary\");\r\n\r\n if (inChangeSet) {\r\n const contentIdValue = internalRequest.headers!.hasOwnProperty(\"Content-ID\") ? internalRequest.headers![\"Content-ID\"] : ++contentId;\r\n\r\n batchBody.push(`Content-ID: ${contentIdValue}`);\r\n }\r\n\r\n if (!internalRequest.path?.startsWith(\"$\")) {\r\n batchBody.push(`\\r\\n${internalRequest.method} ${config.dataApi.url}${internalRequest.path} HTTP/1.1`);\r\n } else {\r\n batchBody.push(`\\r\\n${internalRequest.method} ${internalRequest.path} HTTP/1.1`);\r\n }\r\n\r\n if (internalRequest.method === \"GET\") {\r\n batchBody.push(\"Accept: application/json\");\r\n } else {\r\n batchBody.push(\"Content-Type: application/json\");\r\n }\r\n\r\n if (internalRequest.headers) {\r\n addHeaders(internalRequest.headers, batchBody);\r\n }\r\n\r\n if (internalRequest.data) {\r\n batchBody.push(`\\r\\n${processData(internalRequest.data, config)}`);\r\n }\r\n });\r\n\r\n if (currentChangeSet) {\r\n batchBody.push(`\\r\\n--${currentChangeSet}--`);\r\n }\r\n\r\n batchBody.push(`\\r\\n--${batchBoundary}--\\r\\n`);\r\n\r\n const headers = setStandardHeaders(batchRequest?.userHeaders, batchRequest?.data);\r\n headers[\"Content-Type\"] = `multipart/mixed;boundary=${batchBoundary}`;\r\n\r\n return { headers: headers, body: batchBody.join(\"\\r\\n\") };\r\n};\r\n", "import { Config } from \"../dynamics-web-api\";\r\nimport type { InternalRequest, WebApiResponse } from \"../types\";\r\nimport { defaultConfig, mergeConfig, type InternalConfig } from \"../utils/Config\";\r\nimport { makeRequest } from \"./RequestClient\";\r\n\r\n// module is in development; multiple changes might be made here\r\n\r\nexport interface IDataverseClient {\r\n get config(): InternalConfig;\r\n get isBatch(): boolean;\r\n set isBatch(value: boolean);\r\n get batchRequestId(): string | null;\r\n set batchRequestId(value: string | null);\r\n\r\n setConfig(config: Config): void;\r\n makeRequest(request: InternalRequest): Promise;\r\n}\r\n\r\nexport class DataverseClient implements IDataverseClient {\r\n #config = defaultConfig();\r\n #isBatch = false;\r\n #batchRequestId: string | null = null;\r\n\r\n constructor(config?: Config) {\r\n mergeConfig(this.#config, config);\r\n }\r\n get batchRequestId(): string | null {\r\n return this.#batchRequestId;\r\n }\r\n set batchRequestId(value: string | null) {\r\n this.#batchRequestId = value;\r\n }\r\n\r\n get config(): InternalConfig {\r\n return this.#config;\r\n }\r\n\r\n get isBatch(): boolean {\r\n return this.#isBatch;\r\n }\r\n\r\n set isBatch(value: boolean) {\r\n this.#isBatch = value;\r\n }\r\n\r\n setConfig = (config: Config) => mergeConfig(this.#config, config);\r\n\r\n makeRequest = (request: InternalRequest): Promise => {\r\n request.isBatch = this.#isBatch;\r\n if (this.#batchRequestId) request.requestId = this.#batchRequestId;\r\n return makeRequest(request, this.#config);\r\n };\r\n}\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { AssociateRequest } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { copyRequest } from \"../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\n\r\nconst FUNCTION_NAME = \"associate\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const associate = async (request: AssociateRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.parameterCheck(request.relatedKey, REQUEST_NAME, \"request.relatedKey\");\r\n ErrorHelper.stringParameterCheck(request.relationshipName, REQUEST_NAME, \"request.relationshipName\");\r\n\r\n let relatedKey = request.relatedKey;\r\n let odataId = request.relatedKey;\r\n\r\n // relatedKey can be a contentId that starts with \"$\" during batch requests.\r\n // In this case, we do not need to check it as a key parameter.\r\n if (!client.isBatch || (client.isBatch && !request.relatedKey.startsWith(\"$\"))) {\r\n ErrorHelper.stringParameterCheck(request.relatedCollection, REQUEST_NAME, \"request.relatedCollection\");\r\n relatedKey = ErrorHelper.keyParameterCheck(request.relatedKey, REQUEST_NAME, \"request.relatedKey\");\r\n odataId = `${request.relatedCollection}(${relatedKey})`;\r\n }\r\n\r\n let internalRequest = copyRequest(request, [\"primaryKey\"]);\r\n internalRequest.method = \"POST\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n internalRequest.navigationProperty = request.relationshipName + \"/$ref\";\r\n internalRequest.key = request.primaryKey;\r\n internalRequest.data = { \"@odata.id\": odataId };\r\n\r\n await client.makeRequest(internalRequest);\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { AssociateSingleValuedRequest } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { copyRequest } from \"../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\n\r\nconst FUNCTION_NAME = \"associateSingleValued\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const associateSingleValued = async (request: AssociateSingleValuedRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.parameterCheck(request.relatedKey, REQUEST_NAME, \"request.relatedKey\");\r\n ErrorHelper.stringParameterCheck(request.navigationProperty, REQUEST_NAME, \"request.navigationProperty\");\r\n\r\n let relatedKey = request.relatedKey;\r\n let odataId = request.relatedKey;\r\n\r\n // relatedKey can be a contentId that starts with \"$\" during batch requests.\r\n // In this case, we do not need to check it as a key parameter.\r\n if (!client.isBatch || (client.isBatch && !request.relatedKey.startsWith(\"$\"))) {\r\n ErrorHelper.stringParameterCheck(request.relatedCollection, REQUEST_NAME, \"request.relatedCollection\");\r\n relatedKey = ErrorHelper.keyParameterCheck(request.relatedKey, REQUEST_NAME, \"request.relatedKey\");\r\n odataId = `${request.relatedCollection}(${relatedKey})`;\r\n }\r\n\r\n let internalRequest = copyRequest(request, [\"primaryKey\"]);\r\n internalRequest.method = \"PUT\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n internalRequest.navigationProperty += \"/$ref\";\r\n internalRequest.key = request.primaryKey;\r\n internalRequest.data = { \"@odata.id\": odataId };\r\n\r\n await client.makeRequest(internalRequest);\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { BoundActionRequest, UnboundActionRequest } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { copyRequest } from \"../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\n\r\nconst FUNCTION_NAME = \"callAction\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const callAction = async (\r\n request: BoundActionRequest | UnboundActionRequest,\r\n client: IDataverseClient,\r\n): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.stringParameterCheck(request.actionName, REQUEST_NAME, \"request.actionName\");\r\n\r\n const internalRequest = copyRequest(request, [\"action\"]);\r\n internalRequest.method = \"POST\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n internalRequest.addPath = request.actionName;\r\n internalRequest._isUnboundRequest = !internalRequest.collection;\r\n internalRequest.data = request.action;\r\n\r\n const response = await client.makeRequest(internalRequest);\r\n return response?.data;\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { BoundFunctionRequest, UnboundFunctionRequest } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport type { InternalRequest } from \"../types\";\r\nimport { buildFunctionParameters, copyObject } from \"../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\n\r\nconst FUNCTION_NAME = \"callFunction\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const callFunction = async (request: string | BoundFunctionRequest | UnboundFunctionRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n const getFunctionName = (request: BoundFunctionRequest | UnboundFunctionRequest) => request.name || request.functionName;\r\n\r\n const isObject = typeof request !== \"string\";\r\n const functionName = isObject ? getFunctionName(request) : request;\r\n const parameterName = isObject ? \"request.name\" : \"name\";\r\n const internalRequest: InternalRequest = isObject ? copyObject(request, [\"name\"]) : { functionName: functionName };\r\n\r\n ErrorHelper.stringParameterCheck(functionName, REQUEST_NAME, parameterName);\r\n\r\n const functionParameters = buildFunctionParameters(internalRequest.parameters);\r\n\r\n internalRequest.method = \"GET\";\r\n internalRequest.addPath = functionName + functionParameters.key;\r\n internalRequest.queryParams = functionParameters.queryParams;\r\n internalRequest._isUnboundRequest = !internalRequest.collection;\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n const response = await client.makeRequest(internalRequest);\r\n return response?.data;\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { CreateRequest } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport type { InternalRequest } from \"../types\";\r\nimport { copyRequest } from \"../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\n\r\nconst FUNCTION_NAME = \"create\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const create = async (request: CreateRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n let internalRequest: InternalRequest;\r\n\r\n if (!(request).functionName) {\r\n internalRequest = copyRequest(request);\r\n internalRequest.functionName = FUNCTION_NAME;\r\n } else internalRequest = request;\r\n\r\n internalRequest.method = \"POST\";\r\n\r\n const response = await client.makeRequest(internalRequest);\r\n\r\n return response?.data;\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { CountRequest } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { copyRequest } from \"../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\n\r\nconst FUNCTION_NAME = \"count\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const count = async (request: CountRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.method = \"GET\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n if (internalRequest.filter?.length) {\r\n internalRequest.count = true;\r\n } else {\r\n internalRequest.navigationProperty = \"$count\";\r\n }\r\n\r\n internalRequest.responseParameters = { toCount: internalRequest.count };\r\n\r\n //if filter has not been specified then simplify the request\r\n const response = await client.makeRequest(internalRequest);\r\n return response?.data;\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { CountAllRequest } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\nimport { retrieveAllRequest } from \"./retrieveAll\";\r\n\r\nconst FUNCTION_NAME = \"countAll\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const countAll = async (request: CountAllRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.throwBatchIncompatible(REQUEST_NAME, client.isBatch);\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n const response = await retrieveAllRequest(request, client);\r\n\r\n return response.value.length;\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { AllResponse, RetrieveMultipleRequest } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\nimport { retrieveMultiple } from \"./retrieveMultiple\";\r\n\r\nconst FUNCTION_NAME = \"retrieveAll\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const retrieveAllRequest = async (\r\n request: RetrieveMultipleRequest,\r\n client: IDataverseClient,\r\n nextPageLink?: string,\r\n records: any[] = [],\r\n): Promise> => {\r\n const response = await retrieveMultiple(request, client, nextPageLink);\r\n records = records.concat(response.value);\r\n\r\n const pageLink = response.oDataNextLink;\r\n\r\n if (pageLink) {\r\n return retrieveAllRequest(request, client, pageLink, records);\r\n }\r\n\r\n const result: AllResponse = { value: records };\r\n\r\n if (response.oDataDeltaLink) {\r\n result[\"@odata.deltaLink\"] = response.oDataDeltaLink;\r\n result.oDataDeltaLink = response.oDataDeltaLink;\r\n }\r\n\r\n return result;\r\n};\r\n\r\n/**\r\n * Sends an asynchronous request to retrieve all records.\r\n *\r\n * @param {DWARequest} request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\nexport const retrieveAll = (request: RetrieveMultipleRequest, client: IDataverseClient): Promise> => {\r\n ErrorHelper.throwBatchIncompatible(REQUEST_NAME, client.isBatch);\r\n return retrieveAllRequest(request, client);\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { RetrieveMultipleRequest, RetrieveMultipleResponse } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport type { InternalRequest } from \"../types\";\r\nimport { copyRequest } from \"../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\n\r\nconst FUNCTION_NAME = \"retrieveMultiple\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const retrieveMultiple = async (\r\n request: RetrieveMultipleRequest,\r\n client: IDataverseClient,\r\n nextPageLink?: string,\r\n): Promise> => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n let internalRequest: InternalRequest;\r\n\r\n if (!(request).functionName) {\r\n internalRequest = copyRequest(request);\r\n internalRequest.functionName = FUNCTION_NAME;\r\n } else internalRequest = request;\r\n\r\n internalRequest.method = \"GET\";\r\n\r\n if (nextPageLink) {\r\n ErrorHelper.stringParameterCheck(nextPageLink, REQUEST_NAME, \"nextPageLink\");\r\n internalRequest.url = nextPageLink;\r\n }\r\n\r\n const response = await client.makeRequest(internalRequest);\r\n\r\n return response?.data;\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { DisassociateRequest } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { copyRequest } from \"../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\n\r\nconst FUNCTION_NAME = \"disassociate\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const disassociate = async (request: DisassociateRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n let internalRequest = copyRequest(request);\r\n internalRequest.method = \"DELETE\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n ErrorHelper.stringParameterCheck(request.relationshipName, REQUEST_NAME, \"request.relationshipName\");\r\n const primaryKey = ErrorHelper.keyParameterCheck(request.primaryKey, REQUEST_NAME, \"request.primaryKey\");\r\n const relatedKey = ErrorHelper.keyParameterCheck(request.relatedKey, REQUEST_NAME, \"request.relatedId\");\r\n\r\n internalRequest.key = primaryKey;\r\n internalRequest.navigationProperty = `${request.relationshipName}(${relatedKey})/$ref`;\r\n\r\n await client.makeRequest(internalRequest);\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { DisassociateSingleValuedRequest } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { copyRequest } from \"../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\n\r\nconst FUNCTION_NAME = \"disassociateSingleValued\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const disassociateSingleValued = async (request: DisassociateSingleValuedRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n let internalRequest = copyRequest(request);\r\n internalRequest.method = \"DELETE\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n ErrorHelper.stringParameterCheck(request.navigationProperty, REQUEST_NAME, \"request.navigationProperty\");\r\n const primaryKey = ErrorHelper.keyParameterCheck(request.primaryKey, REQUEST_NAME, \"request.primaryKey\");\r\n\r\n internalRequest.navigationProperty += \"/$ref\";\r\n internalRequest.key = primaryKey;\r\n\r\n await client.makeRequest(internalRequest);\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { RetrieveRequest } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport type { InternalRequest } from \"../types\";\r\nimport { copyRequest } from \"../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\n\r\nconst FUNCTION_NAME = \"retrieve\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const retrieve = async (request: RetrieveRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n let internalRequest: InternalRequest;\r\n\r\n if (!(request).functionName) {\r\n internalRequest = copyRequest(request);\r\n internalRequest.functionName = FUNCTION_NAME;\r\n } else internalRequest = request;\r\n\r\n internalRequest.method = \"GET\";\r\n internalRequest.responseParameters = {\r\n isRef: internalRequest.select?.length === 1 && internalRequest.select[0].endsWith(\"/$ref\"),\r\n };\r\n\r\n const response = await client.makeRequest(internalRequest);\r\n return response?.data;\r\n};", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { FetchXmlRequest, FetchXmlResponse } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { FETCH_XML_PAGE_REGEX, FETCH_XML_REPLACE_REGEX, FETCH_XML_TOP_REGEX } from \"../helpers/Regex\";\r\nimport { copyRequest } from \"../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\n\r\nconst FUNCTION_NAME = \"fetch\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const fetchXml = async (request: FetchXmlRequest, client: IDataverseClient): Promise> => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.method = \"GET\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n ErrorHelper.stringParameterCheck(internalRequest.fetchXml, REQUEST_NAME, \"request.fetchXml\");\r\n\r\n //only add paging if there is no top\r\n if (internalRequest.fetchXml && !FETCH_XML_TOP_REGEX.test(internalRequest.fetchXml)) {\r\n let replacementString: string = \"\";\r\n\r\n if (!FETCH_XML_PAGE_REGEX.test(internalRequest.fetchXml)) {\r\n internalRequest.pageNumber = internalRequest.pageNumber || 1;\r\n\r\n ErrorHelper.numberParameterCheck(internalRequest.pageNumber, REQUEST_NAME, \"request.pageNumber\");\r\n replacementString = `$1 page=\"${internalRequest.pageNumber}\"`;\r\n }\r\n\r\n if (internalRequest.pagingCookie != null) {\r\n ErrorHelper.stringParameterCheck(internalRequest.pagingCookie, REQUEST_NAME, \"request.pagingCookie\");\r\n replacementString += ` paging-cookie=\"${internalRequest.pagingCookie}\"`;\r\n }\r\n\r\n //add page number and paging cookie to fetch xml\r\n if (replacementString) internalRequest.fetchXml = internalRequest.fetchXml.replace(FETCH_XML_REPLACE_REGEX, replacementString);\r\n }\r\n\r\n internalRequest.responseParameters = { pageNumber: internalRequest.pageNumber };\r\n\r\n const response = await client.makeRequest(internalRequest);\r\n\r\n return response?.data;\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { FetchAllRequest, FetchXmlRequest, FetchXmlResponse } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\nimport { fetchXml } from \"./fetchXml\";\r\n\r\nconst FUNCTION_NAME = \"fetchAll\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nconst executeFetchXmlAll = async (request: FetchXmlRequest, client: IDataverseClient, records: any[] = []): Promise> => {\r\n const response = await fetchXml(request, client);\r\n\r\n records = records.concat(response.value);\r\n\r\n if (response.PagingInfo) {\r\n request.pageNumber = response.PagingInfo.nextPage;\r\n request.pagingCookie = response.PagingInfo.cookie;\r\n\r\n return executeFetchXmlAll(request, client, records);\r\n }\r\n\r\n return { value: records };\r\n};\r\n\r\nexport const fetchXmlAll = async (request: FetchAllRequest, client: IDataverseClient): Promise> => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.throwBatchIncompatible(REQUEST_NAME, client.isBatch);\r\n\r\n return executeFetchXmlAll(request, client);\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { UpdateRequest } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { getUpdateMethod } from \"../helpers/Regex\";\r\nimport type { InternalRequest } from \"../types\";\r\nimport { copyRequest } from \"../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\n\r\nconst FUNCTION_NAME = \"update\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const update = async (request: UpdateRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n let internalRequest: InternalRequest;\r\n\r\n if (!(request).functionName) {\r\n internalRequest = copyRequest(request);\r\n internalRequest.functionName = FUNCTION_NAME;\r\n } else internalRequest = request;\r\n\r\n internalRequest.method ??= getUpdateMethod(internalRequest.collection);\r\n internalRequest.responseParameters = { valueIfEmpty: true };\r\n internalRequest.ifmatch ??= \"*\"; //to prevent upsert\r\n\r\n //copy locally\r\n const ifmatch = internalRequest.ifmatch;\r\n\r\n try {\r\n const response = await client.makeRequest(internalRequest);\r\n return response?.data;\r\n } catch (error: any) {\r\n if (ifmatch && error.status === 412) {\r\n //precondition failed - not updated\r\n return false as any; //todo: check this\r\n }\r\n //rethrow error otherwise\r\n throw error;\r\n }\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { UpdateSinglePropertyRequest } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { copyRequest } from \"../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\n\r\nconst FUNCTION_NAME = \"updateSingleProperty\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const updateSingleProperty = async (request: UpdateSinglePropertyRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.parameterCheck(request.fieldValuePair, REQUEST_NAME, \"request.fieldValuePair\");\r\n\r\n var field = Object.keys(request.fieldValuePair)[0];\r\n var fieldValue = request.fieldValuePair[field];\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.navigationProperty = field;\r\n internalRequest.data = { value: fieldValue };\r\n internalRequest.functionName = FUNCTION_NAME;\r\n internalRequest.method = \"PUT\";\r\n\r\n delete internalRequest[\"fieldValuePair\"];\r\n\r\n const response = await client.makeRequest(internalRequest);\r\n return response?.data;\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { UpsertRequest } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { copyRequest } from \"../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\n\r\nconst FUNCTION_NAME = \"upsert\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const upsert = async (request: UpsertRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.method = \"PATCH\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n //copy locally\r\n const ifnonematch = internalRequest.ifnonematch;\r\n const ifmatch = internalRequest.ifmatch;\r\n try {\r\n const response = await client.makeRequest(internalRequest);\r\n return response?.data;\r\n } catch (error: any) {\r\n if (ifnonematch && error.status === 412) {\r\n //if prevent update\r\n return null as any; //todo: check this\r\n } else if (ifmatch && error.status === 404) {\r\n //if prevent create\r\n return null as any; //todo: check this\r\n }\r\n //rethrow error otherwise\r\n throw error;\r\n }\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { DeleteRequest } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport type { InternalRequest } from \"../types\";\r\nimport { copyRequest } from \"../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\n\r\nconst FUNCTION_NAME = \"deleteRecord\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const deleteRecord = async (request: DeleteRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n let internalRequest: InternalRequest;\r\n\r\n if (!(request).functionName) {\r\n internalRequest = copyRequest(request);\r\n internalRequest.functionName = FUNCTION_NAME;\r\n } else internalRequest = request;\r\n\r\n internalRequest.method = \"DELETE\";\r\n internalRequest.responseParameters = { valueIfEmpty: true };\r\n\r\n //copy locally\r\n const ifmatch = internalRequest.ifmatch;\r\n\r\n try {\r\n const response = await client.makeRequest(internalRequest);\r\n return response?.data;\r\n } catch (error: any) {\r\n if (ifmatch && error.status === 412) {\r\n //precondition failed - not updated\r\n return false; //todo: check this\r\n }\r\n //rethrow error otherwise\r\n throw error;\r\n }\r\n};\r\n", "import { LIBRARY_NAME } from \"./constants\";\r\nimport type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { UploadRequest } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport type { InternalRequest } from \"../types\";\r\nimport { copyRequest, setFileChunk } from \"../utils/Utility\";\r\n\r\nconst FUNCTION_NAME = \"uploadFile\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nconst _uploadFileChunk = async (\r\n request: InternalRequest,\r\n client: IDataverseClient,\r\n fileBytes: Uint8Array | Buffer,\r\n chunkSize: number,\r\n offset: number = 0,\r\n): Promise => {\r\n // offset = offset || 0;\r\n setFileChunk(request, fileBytes, chunkSize, offset);\r\n\r\n await client.makeRequest(request);\r\n\r\n offset += chunkSize;\r\n if (offset <= fileBytes.length) {\r\n return _uploadFileChunk(request, client, fileBytes, chunkSize, offset);\r\n }\r\n};\r\n\r\nexport const uploadFile = async (request: UploadRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.throwBatchIncompatible(REQUEST_NAME, client.isBatch);\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n const internalRequest = copyRequest(request, [\"data\"]);\r\n internalRequest.method = \"PATCH\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n internalRequest.transferMode = \"chunked\";\r\n\r\n const response = await client.makeRequest(internalRequest);\r\n\r\n internalRequest.url = response?.data.location;\r\n delete internalRequest.transferMode;\r\n delete internalRequest.fieldName;\r\n delete internalRequest.property;\r\n delete internalRequest.fileName;\r\n return _uploadFileChunk(internalRequest, client, request.data, response?.data.chunkSize);\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { DownloadRequest, DownloadResponse } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport type { InternalRequest } from \"../types\";\r\nimport { convertToFileBuffer, copyRequest, downloadChunkSize } from \"../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\n\r\nconst FUNCTION_NAME = \"downloadFile\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nconst downloadFileChunk = async (\r\n request: InternalRequest,\r\n client: IDataverseClient,\r\n bytesDownloaded: number = 0,\r\n data: string = \"\",\r\n): Promise => {\r\n request.range = \"bytes=\" + bytesDownloaded + \"-\" + (bytesDownloaded + downloadChunkSize - 1);\r\n request.downloadSize = \"full\";\r\n\r\n const response = await client.makeRequest(request);\r\n\r\n request.url = response?.data.location;\r\n data += response?.data.value;\r\n\r\n bytesDownloaded += downloadChunkSize;\r\n\r\n if (bytesDownloaded <= response?.data.fileSize) {\r\n return downloadFileChunk(request, client, bytesDownloaded, data);\r\n }\r\n\r\n return {\r\n fileName: response?.data.fileName,\r\n fileSize: response?.data.fileSize,\r\n data: convertToFileBuffer(data),\r\n };\r\n};\r\n\r\n/**\r\n * Download a file from a File Attribute\r\n * @param request - An object that represents all possible options for a current request.\r\n */\r\nexport const downloadFile = (request: DownloadRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.throwBatchIncompatible(REQUEST_NAME, client.isBatch);\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.method = \"GET\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n internalRequest.responseParameters = { parse: true };\r\n\r\n return downloadFileChunk(internalRequest, client);\r\n};\r\n", "import type { IDataverseClient } from \"../client/dataverse\";\r\nimport type { BatchRequest } from \"../dynamics-web-api\";\r\nimport { copyRequest, generateUUID } from \"../utils/Utility\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { InternalRequest } from \"../types\";\r\nimport { LIBRARY_NAME } from \"./constants\";\r\n\r\nconst FUNCTION_NAME = \"executeBatch\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport async function executeBatch(request: BatchRequest | undefined, client: IDataverseClient): Promise {\r\n ErrorHelper.throwBatchNotStarted(client.isBatch);\r\n\r\n const internalRequest: InternalRequest = !request ? {} : copyRequest(request);\r\n\r\n internalRequest.collection = \"$batch\";\r\n internalRequest.method = \"POST\";\r\n internalRequest.functionName = REQUEST_NAME;\r\n internalRequest.requestId = client.batchRequestId;\r\n\r\n client.batchRequestId = null;\r\n client.isBatch = false;\r\n\r\n const response = await client.makeRequest(internalRequest);\r\n return response?.data;\r\n}\r\n\r\nexport function startBatch(client: IDataverseClient): void {\r\n client.isBatch = true;\r\n client.batchRequestId = generateUUID();\r\n}\r\n", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { CreateEntityRequest, CreateRequest } from \"../../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"../constants\";\r\nimport { create } from \"../create\";\r\n\r\nconst FUNCTION_NAME = \"createEntity\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const createEntity = async (request: CreateEntityRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.parameterCheck(request.data, REQUEST_NAME, \"request.data\");\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n return create(internalRequest, client);\r\n};\r\n", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { UpdateEntityRequest, UpdateRequest } from \"../../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"../constants\";\r\nimport { update } from \"../update\";\r\n\r\nconst FUNCTION_NAME = \"updateEntity\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const updateEntity = async (request: UpdateEntityRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.parameterCheck(request.data, REQUEST_NAME, \"request.data\");\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n internalRequest.key = internalRequest.data.MetadataId;\r\n internalRequest.method = \"PUT\";\r\n\r\n return await update(internalRequest, client);\r\n};\r\n", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { RetrieveEntityRequest, RetrieveRequest } from \"../../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"../constants\";\r\nimport { retrieve } from \"../retrieve\";\r\n\r\nconst FUNCTION_NAME = \"retrieveEntity\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const retrieveEntity = async (request: RetrieveEntityRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.keyParameterCheck(request.key, REQUEST_NAME, \"request.key\");\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.functionName = \"retrieveEntity\";\r\n\r\n return await retrieve(internalRequest, client);\r\n};\r\n", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { RetrieveEntitiesRequest, RetrieveMultipleResponse, RetrieveMultipleRequest } from \"../../dynamics-web-api\";\r\nimport type { InternalRequest } from \"../../types\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { retrieveMultiple } from \"../retrieveMultiple\";\r\n\r\nconst FUNCTION_NAME = \"retrieveEntities\";\r\n\r\nexport const retrieveEntities = (client: IDataverseClient, request?: RetrieveEntitiesRequest): Promise> => {\r\n const internalRequest: InternalRequest = !request ? {} : copyRequest(request);\r\n\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n return retrieveMultiple(internalRequest, client);\r\n};\r\n", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { CreateAttributeRequest, CreateRequest } from \"../../dynamics-web-api\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { create } from \"../create\";\r\nimport { LIBRARY_NAME } from \"../constants\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\n\r\nconst FUNCTION_NAME = \"createAttribute\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const createAttribute = (request: CreateAttributeRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.parameterCheck(request.data, REQUEST_NAME, \"request.data\");\r\n ErrorHelper.keyParameterCheck(request.entityKey, REQUEST_NAME, \"request.entityKey\");\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n internalRequest.navigationProperty = \"Attributes\";\r\n internalRequest.key = request.entityKey;\r\n\r\n return create(internalRequest as CreateRequest, client);\r\n};\r\n", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { UpdateAttributeRequest, UpdateRequest } from \"../../dynamics-web-api\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { update } from \"../update\";\r\nimport { LIBRARY_NAME } from \"../constants\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\n\r\nconst FUNCTION_NAME = \"updateAttribute\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const updateAttribute = (request: UpdateAttributeRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.parameterCheck(request.data, REQUEST_NAME, \"request.data\");\r\n ErrorHelper.keyParameterCheck(request.entityKey, REQUEST_NAME, \"request.entityKey\");\r\n ErrorHelper.guidParameterCheck(request.data.MetadataId, REQUEST_NAME, \"request.data.MetadataId\");\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n internalRequest.navigationProperty = \"Attributes\";\r\n internalRequest.navigationPropertyKey = request.data.MetadataId;\r\n internalRequest.metadataAttributeType = request.castType;\r\n internalRequest.key = request.entityKey;\r\n internalRequest.method = \"PUT\";\r\n\r\n return update(internalRequest as UpdateRequest, client);\r\n};\r\n", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { RetrieveMultipleRequest, RetrieveAttributesRequest, RetrieveMultipleResponse } from \"../../dynamics-web-api\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { retrieveMultiple } from \"../retrieveMultiple\";\r\nimport { LIBRARY_NAME } from \"../constants\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\n\r\nconst FUNCTION_NAME = \"retrieveAttributes\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const retrieveAttributes = (request: RetrieveAttributesRequest, client: IDataverseClient): Promise> => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.keyParameterCheck(request.entityKey, REQUEST_NAME, \"request.entityKey\");\r\n\r\n if (request.castType) {\r\n ErrorHelper.stringParameterCheck(request.castType, REQUEST_NAME, \"request.castType\");\r\n }\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n internalRequest.navigationProperty = \"Attributes\";\r\n internalRequest.key = request.entityKey;\r\n internalRequest.metadataAttributeType = request.castType;\r\n\r\n return retrieveMultiple(internalRequest as RetrieveMultipleRequest, client);\r\n}", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { RetrieveRequest, RetrieveAttributeRequest } from \"../../dynamics-web-api\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { retrieve } from \"../retrieve\";\r\nimport { LIBRARY_NAME } from \"../constants\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\n\r\nconst FUNCTION_NAME = \"retrieveAttributes\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const retrieveAttribute = (request: RetrieveAttributeRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.keyParameterCheck(request.entityKey, REQUEST_NAME, \"request.entityKey\");\r\n ErrorHelper.keyParameterCheck(request.attributeKey, REQUEST_NAME, \"request.attributeKey\");\r\n\r\n if (request.castType) {\r\n ErrorHelper.stringParameterCheck(request.castType, REQUEST_NAME, \"request.castType\");\r\n }\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.navigationProperty = \"Attributes\";\r\n internalRequest.navigationPropertyKey = request.attributeKey;\r\n internalRequest.metadataAttributeType = request.castType;\r\n internalRequest.key = request.entityKey;\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n return retrieve(internalRequest as RetrieveRequest, client);\r\n};", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { CreateRequest, CreateRelationshipRequest } from \"../../dynamics-web-api\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { create } from \"../create\";\r\nimport { LIBRARY_NAME } from \"../constants\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\n\r\nconst FUNCTION_NAME = \"createRelationship\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport const createRelationship = (request: CreateRelationshipRequest, client: IDataverseClient): Promise => {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.parameterCheck(request.data, REQUEST_NAME, \"request.data\");\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.collection = \"RelationshipDefinitions\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n return create(internalRequest as CreateRequest, client);\r\n};", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { UpdateRelationshipRequest, UpdateRequest } from \"../../dynamics-web-api\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { update } from \"../update\";\r\nimport { LIBRARY_NAME } from \"../constants\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\n\r\nconst FUNCTION_NAME = \"updateRelationship\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\n\r\nexport function updateRelationship(request: UpdateRelationshipRequest, client: IDataverseClient): Promise {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.parameterCheck(request.data, REQUEST_NAME, \"request.data\");\r\n ErrorHelper.guidParameterCheck(request.data.MetadataId, REQUEST_NAME, \"request.data.MetadataId\");\r\n\r\n if (request.castType) {\r\n ErrorHelper.stringParameterCheck(request.castType, REQUEST_NAME, \"request.castType\");\r\n }\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.collection = \"RelationshipDefinitions\";\r\n internalRequest.key = request.data.MetadataId;\r\n internalRequest.navigationProperty = request.castType;\r\n internalRequest.functionName = FUNCTION_NAME;\r\n internalRequest.method = \"PUT\";\r\n\r\n return update(internalRequest as UpdateRequest, client);\r\n}", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { DeleteRelationshipRequest, DeleteRequest } from \"../../dynamics-web-api\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { LIBRARY_NAME } from \"../constants\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport { deleteRecord } from \"../delete\";\r\n\r\nconst FUNCTION_NAME = \"deleteRelationship\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport async function deleteRelationship(request: DeleteRelationshipRequest, client: IDataverseClient): Promise {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.keyParameterCheck(request.key, REQUEST_NAME, \"request.key\");\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.collection = \"RelationshipDefinitions\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n return deleteRecord(internalRequest as DeleteRequest, client);\r\n}", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { RetrieveRelationshipsRequest, RetrieveMultipleRequest, RetrieveMultipleResponse } from \"../../dynamics-web-api\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport { retrieveMultiple } from \"../retrieveMultiple\";\r\nimport { InternalRequest } from \"../../types\";\r\n\r\nconst FUNCTION_NAME = \"retrieveRelationships\";\r\nconst REQUEST_NAME = `DynamicsWebApi.${FUNCTION_NAME}`;\r\n\r\nexport async function retrieveRelationships(request: RetrieveRelationshipsRequest | undefined, client: IDataverseClient): Promise> {\r\n const internalRequest: InternalRequest = !request ? {} : copyRequest(request);\r\n\r\n internalRequest.collection = \"RelationshipDefinitions\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n if (request) {\r\n if (request.castType) {\r\n ErrorHelper.stringParameterCheck(request.castType, REQUEST_NAME, \"request.castType\");\r\n internalRequest.navigationProperty = request.castType;\r\n }\r\n }\r\n\r\n return retrieveMultiple(internalRequest, client);\r\n}", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { RetrieveRelationshipRequest, RetrieveRequest } from \"../../dynamics-web-api\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport { retrieve } from \"../retrieve\";\r\n\r\nconst FUNCTION_NAME = \"retrieveRelationship\";\r\nconst REQUEST_NAME = `DynamicsWebApi.${FUNCTION_NAME}`;\r\n\r\nexport async function retrieveRelationship(request: RetrieveRelationshipRequest, client: IDataverseClient): Promise {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.keyParameterCheck(request.key, REQUEST_NAME, \"request.key\");\r\n\r\n if (request.castType) {\r\n ErrorHelper.stringParameterCheck(request.castType, REQUEST_NAME, \"request.castType\");\r\n }\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.collection = \"RelationshipDefinitions\";\r\n internalRequest.navigationProperty = request.castType;\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n return retrieve(internalRequest, client);\r\n}", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { CreateGlobalOptionSetRequest, CreateRequest } from \"../../dynamics-web-api\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport { create } from \"../create\";\r\n\r\nconst FUNCTION_NAME = \"createGlobalOptionSet\";\r\nconst REQUEST_NAME = `DynamicsWebApi.${FUNCTION_NAME}`;\r\n\r\nexport async function createGlobalOptionSet(request: CreateGlobalOptionSetRequest, client: IDataverseClient): Promise {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.parameterCheck(request.data, REQUEST_NAME, \"request.data\");\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.collection = \"GlobalOptionSetDefinitions\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n return create(internalRequest, client);\r\n}\r\n", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { UpdateGlobalOptionSetRequest, UpdateRequest } from \"../../dynamics-web-api\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport { update } from \"../update\";\r\n\r\nconst FUNCTION_NAME = \"updateGlobalOptionSet\";\r\nconst REQUEST_NAME = `DynamicsWebApi.${FUNCTION_NAME}`;\r\n\r\nexport async function updateGlobalOptionSet(request: UpdateGlobalOptionSetRequest, client: IDataverseClient): Promise {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n ErrorHelper.parameterCheck(request.data, REQUEST_NAME, \"request.data\");\r\n ErrorHelper.guidParameterCheck(request.data.MetadataId, REQUEST_NAME, \"request.data.MetadataId\");\r\n\r\n if (request.castType) {\r\n ErrorHelper.stringParameterCheck(request.castType, REQUEST_NAME, \"request.castType\");\r\n }\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.collection = \"GlobalOptionSetDefinitions\";\r\n internalRequest.key = request.data.MetadataId;\r\n internalRequest.functionName = FUNCTION_NAME;\r\n internalRequest.method = \"PUT\";\r\n\r\n return update(internalRequest, client);\r\n}", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { DeleteGlobalOptionSetRequest, DeleteRequest } from \"../../dynamics-web-api\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport { deleteRecord } from \"../delete\";\r\n\r\nconst FUNCTION_NAME = \"deleteGlobalOptionSet\";\r\nconst REQUEST_NAME = `DynamicsWebApi.${FUNCTION_NAME}`;\r\n\r\nexport async function deleteGlobalOptionSet(request: DeleteGlobalOptionSetRequest, client: IDataverseClient): Promise {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.collection = \"GlobalOptionSetDefinitions\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n return deleteRecord(internalRequest, client);\r\n}", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { RetrieveGlobalOptionSetRequest, RetrieveRequest } from \"../../dynamics-web-api\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport { retrieve } from \"../retrieve\";\r\n\r\nconst FUNCTION_NAME = \"retrieveGlobalOptionSet\";\r\nconst REQUEST_NAME = `DynamicsWebApi.${FUNCTION_NAME}`;\r\n\r\nexport async function retrieveGlobalOptionSet(request: RetrieveGlobalOptionSetRequest, client: IDataverseClient): Promise {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n if (request.castType) {\r\n ErrorHelper.stringParameterCheck(request.castType, REQUEST_NAME, \"request.castType\");\r\n }\r\n\r\n const internalRequest = copyRequest(request);\r\n internalRequest.collection = \"GlobalOptionSetDefinitions\";\r\n internalRequest.navigationProperty = request.castType;\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n return retrieve(internalRequest, client);\r\n}", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { RetrieveGlobalOptionSetsRequest, RetrieveMultipleRequest, RetrieveMultipleResponse } from \"../../dynamics-web-api\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport { retrieveMultiple } from \"../retrieveMultiple\";\r\nimport { InternalRequest } from \"../../types\";\r\n\r\nconst FUNCTION_NAME = \"retrieveGlobalOptionSets\";\r\nconst REQUEST_NAME = `DynamicsWebApi.${FUNCTION_NAME}`;\r\n\r\nexport async function retrieveGlobalOptionSets(request: RetrieveGlobalOptionSetsRequest | undefined, client: IDataverseClient): Promise> {\r\n const internalRequest: InternalRequest = !request ? {} : copyRequest(request);\r\n\r\n internalRequest.collection = \"GlobalOptionSetDefinitions\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n if (request?.castType) {\r\n ErrorHelper.stringParameterCheck(request.castType, REQUEST_NAME, \"request.castType\");\r\n internalRequest.navigationProperty = request.castType;\r\n }\r\n\r\n return retrieveMultiple(internalRequest, client);\r\n}", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { CsdlMetadataRequest } from \"../../dynamics-web-api\";\r\nimport { copyRequest } from \"../../utils/Utility\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport { InternalRequest } from \"../../types\";\r\n\r\nconst FUNCTION_NAME = \"retrieveCsdlMetadata\";\r\nconst REQUEST_NAME = `DynamicsWebApi.${FUNCTION_NAME}`;\r\n\r\nexport async function retrieveCsdlMetadata(request: CsdlMetadataRequest | undefined, client: IDataverseClient): Promise {\r\n const internalRequest: InternalRequest = !request ? {} : copyRequest(request);\r\n\r\n internalRequest.collection = \"$metadata\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n\r\n if (request?.addAnnotations) {\r\n ErrorHelper.boolParameterCheck(request.addAnnotations, REQUEST_NAME, \"request.addAnnotations\");\r\n internalRequest.includeAnnotations = \"*\";\r\n }\r\n\r\n const response = await client.makeRequest(internalRequest);\r\n return response?.data;\r\n}\r\n", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { QueryRequest, QueryResponse } from \"../../dynamics-web-api\";\r\nimport { copyObject } from \"../../utils/Utility\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport { InternalRequest } from \"../../types\";\r\nimport { LIBRARY_NAME } from \"../constants\";\r\nimport { convertSearchQuery } from \"./convertSearchQuery\";\r\nimport { parseQueryResponse } from \"./responseParsers/parseQueryResponse\";\r\n\r\nconst FUNCTION_NAME = \"query\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport async function query(request: string | QueryRequest, client: IDataverseClient): Promise {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n const _isObject = typeof request !== \"string\";\r\n const parameterName = _isObject ? \"request.query.search\" : \"term\";\r\n const internalRequest: InternalRequest = _isObject ? copyObject(request) : { query: { search: request } };\r\n\r\n ErrorHelper.parameterCheck(internalRequest.query, REQUEST_NAME, \"request.query\");\r\n ErrorHelper.stringParameterCheck(internalRequest.query.search, REQUEST_NAME, parameterName);\r\n ErrorHelper.maxLengthStringParameterCheck(internalRequest.query.search, REQUEST_NAME, parameterName, 100);\r\n\r\n internalRequest.collection = \"query\";\r\n internalRequest.functionName = FUNCTION_NAME;\r\n internalRequest.method = \"POST\";\r\n internalRequest.data = convertSearchQuery(internalRequest.query, FUNCTION_NAME, client.config.searchApi);\r\n internalRequest.apiConfig = client.config.searchApi;\r\n\r\n delete internalRequest.query;\r\n\r\n const response = await client.makeRequest(internalRequest);\r\n return parseQueryResponse(response!.data, client.config.searchApi);\r\n}\r\n", "import { escapeSearchSpecialCharacters } from \"../../helpers/Regex\";\r\nimport type { Autocomplete, Suggest, Query, SearchEntity, SearchOptions, SuggestOptions } from \"../../dynamics-web-api\";\r\nimport type { InternalApiConfig } from \"../../utils/Config\";\r\nimport type { SearchApiFunction } from \"./search.types\";\r\n\r\nexport function convertSearchQuery(\r\n query: Query | Suggest | Autocomplete,\r\n functionName: SearchApiFunction,\r\n config: InternalApiConfig,\r\n): Query | Suggest | Autocomplete {\r\n if (!query) return query;\r\n\r\n //escape special characters in a search query only if the option is set to true\r\n if (config?.escapeSpecialCharacters === true) {\r\n query.search = escapeSearchSpecialCharacters(query.search);\r\n }\r\n\r\n if (query.entities?.length) {\r\n query.entities = convertEntitiesProperty(query.entities, config?.version);\r\n }\r\n\r\n switch (functionName) {\r\n case \"query\":\r\n convertQuery(query as Query, config?.version);\r\n break;\r\n default:\r\n convertSuggestOrAutocompleteQuery(query as Suggest | Autocomplete, config?.version);\r\n break;\r\n }\r\n\r\n return query;\r\n}\r\n\r\nexport function convertEntitiesProperty(entities?: string | string[] | SearchEntity[], version: string = \"1.0\"): string | string[] | undefined {\r\n if (!entities) return entities;\r\n if (typeof entities === \"string\") {\r\n if (version !== \"1.0\") return entities;\r\n try {\r\n entities = JSON.parse(entities) as SearchEntity[];\r\n } catch {\r\n throw new Error(\"The 'query.entities' property must be a valid JSON string.\");\r\n }\r\n\r\n if (!Array.isArray(entities)) {\r\n throw new Error(\"The 'query.entities' property must be an array of strings or objects.\");\r\n }\r\n }\r\n\r\n const toStringArray = (entity: string | SearchEntity) => {\r\n if (typeof entity === \"string\") return entity;\r\n return entity.name;\r\n };\r\n\r\n const toSearchEntity = (entity: string | SearchEntity) => {\r\n if (typeof entity === \"string\") return { name: entity };\r\n return entity;\r\n };\r\n\r\n const toReturn = entities.map((entity: string | SearchEntity) => (version === \"1.0\" ? toStringArray(entity) : toSearchEntity(entity)));\r\n\r\n if (version !== \"1.0\") return JSON.stringify(toReturn);\r\n return toReturn as string[];\r\n}\r\n\r\nexport function convertQuery(query: Query, version: string = \"1.0\"): void {\r\n const toV1 = (query: Query) => {\r\n if (query.count != null) {\r\n if (query.returnTotalRecordCount == null) {\r\n query.returnTotalRecordCount = query.count;\r\n }\r\n delete query.count;\r\n }\r\n\r\n if (query.options) {\r\n if (typeof query.options === \"string\") {\r\n try {\r\n query.options = JSON.parse(query.options, searchOptionsReviver) as SearchOptions;\r\n } catch {\r\n throw new Error(\"The 'query.options' property must be a valid JSON string.\");\r\n }\r\n }\r\n\r\n if (!query.searchMode) {\r\n query.searchMode = query.options.searchMode;\r\n }\r\n\r\n if (!query.searchType) {\r\n query.searchType = query.options.queryType === \"lucene\" ? \"full\" : query.options.queryType;\r\n }\r\n\r\n delete query.options;\r\n }\r\n\r\n // in v1.0, orderBy and facets are arrays of strings\r\n for (const prop of specialProperties) {\r\n if (query[prop] && typeof query[prop] === \"string\") {\r\n try {\r\n query[prop] = JSON.parse(query[prop]);\r\n } catch {\r\n throw new Error(`The 'query.${prop}' property must be a valid JSON string.`);\r\n }\r\n }\r\n }\r\n };\r\n\r\n const toV2 = (query: Query) => {\r\n if (query.returnTotalRecordCount != null) {\r\n if (query.count == null) {\r\n query.count = query.returnTotalRecordCount;\r\n }\r\n delete query.returnTotalRecordCount;\r\n }\r\n\r\n if (query.searchMode || query.searchType) {\r\n //only set the options property if it's not a string\r\n if (typeof query.options !== \"string\") {\r\n if (!query.options) query.options = {};\r\n\r\n if (!query.options.searchMode) {\r\n query.options.searchMode = query.searchMode;\r\n }\r\n\r\n if (!query.options.queryType) {\r\n query.options.queryType = query.searchType === \"full\" ? \"lucene\" : query.searchType;\r\n }\r\n }\r\n\r\n delete query.searchMode;\r\n delete query.searchType;\r\n }\r\n\r\n if (query.orderBy && typeof query.orderBy !== \"string\") {\r\n //@ts-ignore - orderby for some reason must be lowercase in v2.\r\n query.orderby = JSON.stringify(query.orderBy);\r\n delete query.orderBy;\r\n }\r\n\r\n if (query.facets && typeof query.facets !== \"string\") {\r\n query.facets = JSON.stringify(query.facets);\r\n }\r\n\r\n //convert options to string if it's an object\r\n if (query.options && typeof query.options !== \"string\") {\r\n query.options = JSON.stringify(convertOptionKeysToLowerCase(query.options));\r\n }\r\n };\r\n\r\n version === \"1.0\" ? toV1(query) : toV2(query);\r\n}\r\n\r\nexport function convertSuggestOrAutocompleteQuery(query: Suggest | Autocomplete, version: string = \"1.0\"): void {\r\n const toV1 = (query: Suggest) => {\r\n if (query.fuzzy != null) {\r\n if (query.useFuzzy == null) {\r\n query.useFuzzy = query.fuzzy;\r\n }\r\n delete query.fuzzy;\r\n }\r\n\r\n delete query.options;\r\n\r\n if (query.orderBy && typeof query.orderBy === \"string\") {\r\n try {\r\n query.orderBy = JSON.parse(query.orderBy);\r\n } catch {\r\n throw new Error(`The 'query.orderBy' property must be a valid JSON string.`);\r\n }\r\n }\r\n };\r\n\r\n const toV2 = (query: Suggest) => {\r\n if (query.useFuzzy != null) {\r\n if (query.fuzzy == null) {\r\n query.fuzzy = query.useFuzzy;\r\n }\r\n delete query.useFuzzy;\r\n }\r\n\r\n if (query.orderBy && typeof query.orderBy !== \"string\") {\r\n //@ts-ignore - orderby for some reason must be lowercase in v2.\r\n query.orderby = JSON.stringify(query.orderBy);\r\n delete query.orderBy;\r\n }\r\n\r\n //convert options to string if it's an object\r\n if (query.options && typeof query.options !== \"string\") {\r\n query.options = JSON.stringify(convertOptionKeysToLowerCase(query.options));\r\n }\r\n };\r\n\r\n version === \"1.0\" ? toV1(query) : toV2(query);\r\n}\r\n\r\nfunction convertOptionKeysToLowerCase(options: SearchOptions): SearchOptions {\r\n const newOptions: SearchOptions = {};\r\n\r\n for (const key in options) {\r\n newOptions[key.toLowerCase()] = options[key];\r\n }\r\n\r\n return newOptions;\r\n}\r\n\r\n//we need a reviver to change the keys of the search options to camel case\r\nfunction searchOptionsReviver(this: SearchOptions, key: string, value: any): any {\r\n switch (key) {\r\n case \"searchmode\":\r\n this.searchMode = value;\r\n break;\r\n case \"querytype\":\r\n this.queryType = value;\r\n break;\r\n default:\r\n return value;\r\n }\r\n}\r\n\r\nconst specialProperties = [\"orderBy\", \"facets\"];\r\n", "import { dateReviver } from \"../../../client/helpers\";\r\nimport type { QueryResponse } from \"../../../dynamics-web-api\";\r\nimport type { InternalApiConfig } from \"../../../utils/Config\";\r\n\r\nexport interface QueryResponseInternal extends Omit {\r\n response: string;\r\n}\r\n\r\nexport function parseQueryResponse(queryResponse: QueryResponseInternal, config: InternalApiConfig): QueryResponse {\r\n if (!queryResponse) return queryResponse;\r\n\r\n const toV1 = (): QueryResponse => {\r\n const responseValue = JSON.parse(queryResponse.response, dateReviver) as QueryResponse[\"response\"];\r\n\r\n const toReturn = {\r\n ...queryResponse,\r\n response: responseValue,\r\n };\r\n\r\n if (config.enableSearchApiResponseCompatibility) {\r\n toReturn.value = responseValue.Value;\r\n toReturn.facets = responseValue.Facets;\r\n toReturn.totalrecordcount = responseValue.Count;\r\n toReturn.querycontext = responseValue.QueryContext;\r\n }\r\n\r\n return toReturn;\r\n };\r\n\r\n const toV2 = (): QueryResponse => {\r\n // @ts-ignore we don't enforce to have all properties in the response if the compatibility is disabled\r\n const toReturn: QueryResponse = {\r\n ...queryResponse,\r\n };\r\n\r\n if (config.enableSearchApiResponseCompatibility) {\r\n toReturn.response = {\r\n Count: queryResponse.totalrecordcount,\r\n Value: queryResponse.value,\r\n Facets: queryResponse.facets,\r\n QueryContext: queryResponse.querycontext,\r\n Error: null,\r\n };\r\n }\r\n\r\n return toReturn;\r\n };\r\n\r\n return config?.version === \"2.0\" ? toV1() : toV2();\r\n}\r\n", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { SuggestRequest, SuggestResponse } from \"../../dynamics-web-api\";\r\nimport { copyObject } from \"../../utils/Utility\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport { InternalRequest } from \"../../types\";\r\nimport { LIBRARY_NAME } from \"../constants\";\r\nimport { convertSearchQuery } from \"./convertSearchQuery\";\r\nimport { parseSuggestResponse } from \"./responseParsers/parseSuggestResponse\";\r\n\r\nconst FUNCTION_NAME = \"suggest\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport async function suggest(request: string | SuggestRequest, client: IDataverseClient): Promise> {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n const _isObject = typeof request !== \"string\";\r\n const parameterName = _isObject ? \"request.query.search\" : \"term\";\r\n const internalRequest: InternalRequest = _isObject ? copyObject(request) : { query: { search: request } };\r\n\r\n ErrorHelper.parameterCheck(internalRequest.query, REQUEST_NAME, \"request.query\");\r\n ErrorHelper.stringParameterCheck(internalRequest.query.search, REQUEST_NAME, parameterName);\r\n ErrorHelper.maxLengthStringParameterCheck(internalRequest.query.search, REQUEST_NAME, parameterName, 100);\r\n\r\n internalRequest.functionName = internalRequest.collection = FUNCTION_NAME;\r\n internalRequest.method = \"POST\";\r\n internalRequest.data = convertSearchQuery(internalRequest.query, FUNCTION_NAME, client.config.searchApi);\r\n internalRequest.apiConfig = client.config.searchApi;\r\n\r\n delete internalRequest.query;\r\n\r\n const response = await client.makeRequest(internalRequest);\r\n return parseSuggestResponse(response!.data, client.config.searchApi);\r\n}\r\n", "import { dateReviver } from \"../../../client/helpers\";\r\nimport type { SuggestResponse, SuggestResponseValue } from \"../../../dynamics-web-api\";\r\nimport type { InternalApiConfig } from \"../../../utils/Config\";\r\n\r\nexport interface SuggestResponseInternal extends Omit {\r\n response: string;\r\n}\r\n\r\nexport function parseSuggestResponse(queryResponse: SuggestResponseInternal, config: InternalApiConfig): SuggestResponse {\r\n if (!queryResponse) return queryResponse;\r\n\r\n const toV1 = (): SuggestResponse => {\r\n const responseValue = JSON.parse(queryResponse.response, dateReviver) as SuggestResponse[\"response\"];\r\n\r\n if (config.enableSearchApiResponseCompatibility) {\r\n responseValue.Value?.forEach((item: SuggestResponseValue) => {\r\n item.document = item.Document;\r\n item.text = item.Text;\r\n });\r\n }\r\n\r\n const toReturn = {\r\n ...queryResponse,\r\n response: responseValue,\r\n };\r\n\r\n if (config.enableSearchApiResponseCompatibility) {\r\n toReturn.value = responseValue.Value;\r\n toReturn.querycontext = responseValue.QueryContext;\r\n }\r\n\r\n return toReturn;\r\n };\r\n\r\n const toV2 = (): SuggestResponse => {\r\n if (config.enableSearchApiResponseCompatibility) {\r\n queryResponse.value?.forEach((item: SuggestResponseValue) => {\r\n item.Document = item.document;\r\n item.Text = item.text;\r\n });\r\n }\r\n\r\n // @ts-ignore we don't enforce to have all properties in the response if the compatibility is disabled\r\n const toReturn: SuggestResponse = {\r\n ...queryResponse,\r\n };\r\n\r\n if (config.enableSearchApiResponseCompatibility) {\r\n toReturn.response = {\r\n Value: queryResponse.value,\r\n QueryContext: queryResponse.querycontext,\r\n Error: null,\r\n };\r\n }\r\n\r\n return toReturn;\r\n };\r\n\r\n return config?.version === \"2.0\" ? toV1() : toV2();\r\n}\r\n", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { AutocompleteRequest, AutocompleteResponse } from \"../../dynamics-web-api\";\r\nimport { copyObject } from \"../../utils/Utility\";\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport { InternalRequest } from \"../../types\";\r\nimport { LIBRARY_NAME } from \"../constants\";\r\nimport { convertSearchQuery } from \"./convertSearchQuery\";\r\nimport { parseAutocompleteResponse } from \"./responseParsers/parseAutocompleteResponse\";\r\n\r\nconst FUNCTION_NAME = \"autocomplete\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport async function autocomplete(request: string | AutocompleteRequest, client: IDataverseClient): Promise {\r\n ErrorHelper.parameterCheck(request, REQUEST_NAME, \"request\");\r\n\r\n const _isObject = typeof request !== \"string\";\r\n const parameterName = _isObject ? \"request.query.search\" : \"term\";\r\n const internalRequest: InternalRequest = _isObject ? copyObject(request) : { query: { search: request } };\r\n\r\n if (_isObject) ErrorHelper.parameterCheck(internalRequest.query, REQUEST_NAME, \"request.query\");\r\n ErrorHelper.stringParameterCheck(internalRequest.query.search, REQUEST_NAME, parameterName);\r\n ErrorHelper.maxLengthStringParameterCheck(internalRequest.query.search, REQUEST_NAME, parameterName, 100);\r\n\r\n internalRequest.functionName = internalRequest.collection = FUNCTION_NAME;\r\n internalRequest.method = \"POST\";\r\n internalRequest.data = convertSearchQuery(internalRequest.query, FUNCTION_NAME, client.config.searchApi);\r\n internalRequest.apiConfig = client.config.searchApi;\r\n\r\n delete internalRequest.query;\r\n\r\n const response = await client.makeRequest(internalRequest);\r\n return parseAutocompleteResponse(response!.data, client.config.searchApi);\r\n}\r\n", "import { dateReviver } from \"../../../client/helpers\";\r\nimport type { AutocompleteResponse } from \"../../../dynamics-web-api\";\r\nimport type { InternalApiConfig } from \"../../../utils/Config\";\r\n\r\nexport interface AutocompleteResponseInternal extends Omit {\r\n response: string;\r\n}\r\n\r\nexport function parseAutocompleteResponse(queryResponse: AutocompleteResponseInternal, config: InternalApiConfig): AutocompleteResponse {\r\n if (!queryResponse) return queryResponse;\r\n\r\n const toV1 = (): AutocompleteResponse => {\r\n const responseValue = JSON.parse(queryResponse.response, dateReviver) as AutocompleteResponse[\"response\"];\r\n\r\n const toReturn = {\r\n ...queryResponse,\r\n response: responseValue,\r\n };\r\n\r\n if (config.enableSearchApiResponseCompatibility) {\r\n toReturn.value = responseValue.Value;\r\n toReturn.querycontext = responseValue.QueryContext;\r\n }\r\n\r\n return toReturn;\r\n };\r\n\r\n const toV2 = (): AutocompleteResponse => {\r\n // @ts-ignore we don't enforce to have all properties in the response if the compatibility is disabled\r\n const toReturn: AutocompleteResponse = {\r\n ...queryResponse,\r\n };\r\n\r\n if (config.enableSearchApiResponseCompatibility) {\r\n toReturn.response = {\r\n Value: queryResponse.value,\r\n QueryContext: queryResponse.querycontext,\r\n Error: null,\r\n };\r\n }\r\n\r\n return toReturn;\r\n };\r\n\r\n return config?.version === \"2.0\" ? toV1() : toV2();\r\n}\r\n", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { BackgroundOperationStatusResponse } from \"../../dynamics-web-api\";\r\n\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport { InternalRequest } from \"../../types\";\r\nimport { LIBRARY_NAME } from \"../constants\";\r\n\r\nconst FUNCTION_NAME = \"getBackgroundOperationStatus\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport async function getBackgroundOperationStatus(backgroundOperationId: string, client: IDataverseClient): Promise {\r\n ErrorHelper.throwBatchIncompatible(REQUEST_NAME, client.isBatch);\r\n ErrorHelper.keyParameterCheck(backgroundOperationId, REQUEST_NAME, \"backgroundOperationId\");\r\n\r\n const internalRequest: InternalRequest = {\r\n method: \"GET\",\r\n addPath: `backgroundoperation/${backgroundOperationId}`,\r\n functionName: FUNCTION_NAME,\r\n apiConfig: client.config.serviceApi,\r\n includeDefaultDataverseHeaders: false,\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n },\r\n //todo: need to get rid of this parameter somehow\r\n _isUnboundRequest: true,\r\n };\r\n\r\n const response = await client.makeRequest(internalRequest);\r\n return response?.data;\r\n}\r\n", "import type { IDataverseClient } from \"../../client/dataverse\";\r\nimport type { BackgroundOperationStatusResponse } from \"../../dynamics-web-api\";\r\n\r\nimport { ErrorHelper } from \"../../helpers/ErrorHelper\";\r\nimport { InternalRequest } from \"../../types\";\r\nimport { LIBRARY_NAME } from \"../constants\";\r\n\r\nconst FUNCTION_NAME = \"cancelBackgroundOperation\";\r\nconst REQUEST_NAME = `${LIBRARY_NAME}.${FUNCTION_NAME}`;\r\n\r\nexport async function cancelBackgroundOperation(backgroundOperationId: string, client: IDataverseClient): Promise {\r\n ErrorHelper.throwBatchIncompatible(REQUEST_NAME, client.isBatch);\r\n ErrorHelper.keyParameterCheck(backgroundOperationId, REQUEST_NAME, \"backgroundOperationId\");\r\n\r\n const internalRequest: InternalRequest = {\r\n method: \"DELETE\",\r\n addPath: `backgroundoperation/${backgroundOperationId}`,\r\n functionName: FUNCTION_NAME,\r\n apiConfig: client.config.serviceApi,\r\n includeDefaultDataverseHeaders: false,\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n },\r\n _isUnboundRequest: true,\r\n };\r\n\r\n const response = await client.makeRequest(internalRequest);\r\n return response?.data;\r\n}\r\n", "\uFEFFimport { DataverseClient, type IDataverseClient } from \"./client/dataverse\";\r\nimport { getCollectionName } from \"./client/RequestClient\";\r\nimport * as Dataverse from \"./requests\";\r\n\r\n/**\r\n * Microsoft Dataverse Web API helper library for Node.js and Browser.\r\n * It is compatible with: Dataverse, Dynamics 365 (online), Dynamics 365 (on-premise), Dynamics CRM 2016, Dynamics CRM Online.\r\n */\r\nexport class DynamicsWebApi {\r\n #client: IDataverseClient;\r\n\r\n /**\r\n * Initializes a new instance of DynamicsWebApi\r\n * @param config - Configuration object\r\n */\r\n constructor(config?: Config) {\r\n this.#client = new DataverseClient(config);\r\n }\r\n\r\n /**\r\n\t * Merges provided configuration properties with an existing one.\r\n\t *\r\n\t * @param {DynamicsWebApi.Config} config - Configuration\r\n\t * @example\r\n\t dynamicsWebApi.setConfig({ serverUrl: 'https://contoso.api.crm.dynamics.com/' });\r\n\t */\r\n setConfig = (config: Config) => this.#client.setConfig(config);\r\n\r\n /**\r\n * Sends an asynchronous request to create a new record.\r\n *\r\n * @param {DWARequest} request - An object that represents all possible options for a current request.\r\n * @template TData - Type of the data to be created.\r\n * @template TResponse - Type of the response to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n * @example\r\n *const lead = {\r\n * subject: \"Test WebAPI\",\r\n * firstname: \"Test\",\r\n * lastname: \"WebAPI\",\r\n * jobtitle: \"Title\"\r\n *};\r\n *\r\n *const request = {\r\n * data: lead,\r\n * collection: \"leads\",\r\n * returnRepresentation: true\r\n *}\r\n *\r\n *const response = await dynamicsWebApi.create(request);\r\n *\r\n */\r\n create = async (request: CreateRequest): Promise => Dataverse.create(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve a record.\r\n *\r\n * @param {DWARequest} request - An object that represents all possible options for a current request.\r\n * @template TResponse - Type of the response to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n * @example\r\n *const request = {\r\n * key: '7d577253-3ef0-4a0a-bb7f-8335c2596e70',\r\n * collection: \"leads\",\r\n * select: [\"fullname\", \"subject\"],\r\n * ifnonematch: 'W/\"468026\"',\r\n * includeAnnotations: \"OData.Community.Display.V1.FormattedValue\"\r\n *};\r\n *\r\n *const response = await dynamicsWebApi.retrieve(request);\r\n */\r\n retrieve = async (request: RetrieveRequest): Promise => Dataverse.retrieve(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to update a record.\r\n *\r\n * @param {DWARequest} request - An object that represents all possible options for a current request.\r\n * @template TData - Type of the data to be created.\r\n * @template TResponse - Type of the response to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n update = async (request: UpdateRequest): Promise => Dataverse.update(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to update a single value in the record.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TResponse - Type of the response to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n updateSingleProperty = async (request: UpdateSinglePropertyRequest): Promise =>\r\n Dataverse.updateSingleProperty(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to delete a record.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n deleteRecord = async (request: DeleteRequest): Promise => Dataverse.deleteRecord(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to upsert a record.\r\n *\r\n * @param {DWARequest} request - An object that represents all possible options for a current request.\r\n * @template TData - Type of the data to be created.\r\n * @template TResponse - Type of the response to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n upsert = async (request: UpsertRequest): Promise => Dataverse.upsert(request, this.#client);\r\n\r\n /**\r\n * Upload file to a File Attribute\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n */\r\n uploadFile = async (request: UploadRequest): Promise => Dataverse.uploadFile(request, this.#client);\r\n\r\n /**\r\n * Download a file from a File Attribute\r\n * @param request - An object that represents all possible options for a current request.\r\n */\r\n downloadFile = (request: DownloadRequest): Promise => Dataverse.downloadFile(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve records.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TValue - Type of the item returned in the \"value\" array.\r\n * @param {string} [nextPageLink] - Use the value of the @odata.nextLink property with a new GET request to return the next page of data. Pass null to retrieveMultipleOptions.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveMultiple = async (request: RetrieveMultipleRequest, nextPageLink?: string): Promise> =>\r\n Dataverse.retrieveMultiple(request, this.#client, nextPageLink);\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve all records.\r\n *\r\n * @param {DWARequest} request - An object that represents all possible options for a current request.\r\n * @template TValue - Type of the item returned in the \"value\" array.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveAll = (request: RetrieveMultipleRequest): Promise> => Dataverse.retrieveAll(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to count records. IMPORTANT! The count value does not represent the total number of entities in the system.\r\n * It is limited by the maximum number of entities that can be returned. Returns: Number\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n count = async (request: CountRequest): Promise => Dataverse.count(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to count records. Returns: Number\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n countAll = async (request: CountAllRequest): Promise => Dataverse.countAll(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to execute FetchXml to retrieve records. Returns: DWA.Types.FetchXmlResponse\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TValue - Type of the item returned in the \"value\" array.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n fetch = async (request: FetchXmlRequest): Promise> => Dataverse.fetchXml(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to execute FetchXml to retrieve all records.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TValue - Type of the item returned in the \"value\" array.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n fetchAll = async (request: FetchAllRequest): Promise> => Dataverse.fetchXmlAll(request, this.#client);\r\n\r\n /**\r\n * Associate for a collection-valued navigation property. (1:N or N:N)\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n associate = async (request: AssociateRequest): Promise => Dataverse.associate(request, this.#client);\r\n\r\n /**\r\n * Disassociate for a collection-valued navigation property.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n disassociate = async (request: DisassociateRequest): Promise => Dataverse.disassociate(request, this.#client);\r\n\r\n /**\r\n * Associate for a single-valued navigation property. (1:N)\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n associateSingleValued = async (request: AssociateSingleValuedRequest): Promise => Dataverse.associateSingleValued(request, this.#client);\r\n\r\n /**\r\n * Removes a reference to an entity for a single-valued navigation property. (1:N)\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n disassociateSingleValued = async (request: DisassociateSingleValuedRequest): Promise => Dataverse.disassociateSingleValued(request, this.#client);\r\n\r\n /**\r\n * Calls a Web API function\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TResponse - Type of the response to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n callFunction: CallFunction = async (request: string | BoundFunctionRequest | UnboundFunctionRequest): Promise =>\r\n Dataverse.callFunction(request, this.#client);\r\n\r\n /**\r\n * Calls a Web API action\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TResponse - Type of the response to be returned.\r\n * @template TAction - Type of the action to be executed.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n callAction: CallAction = async (request: BoundActionRequest | UnboundActionRequest): Promise =>\r\n Dataverse.callAction(request, this.#client);\r\n /**\r\n * Sends an asynchronous request to create an entity definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TResponse - Type of the metadata to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n createEntity = (request: CreateEntityRequest): Promise => Dataverse.createEntity(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to update an entity definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TResponse - Type of the metadata to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n updateEntity = (request: UpdateEntityRequest): Promise => Dataverse.updateEntity(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve a specific entity definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TResponse - Type of the metadata to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveEntity = (request: RetrieveEntityRequest): Promise => Dataverse.retrieveEntity(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve entity definitions.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TValue - Type of the item returned in the \"value\" array.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveEntities = (request?: RetrieveEntitiesRequest): Promise> =>\r\n Dataverse.retrieveEntities(this.#client, request);\r\n\r\n /**\r\n * Sends an asynchronous request to create an attribute.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TResponse - Type of the metadata to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n createAttribute = (request: CreateAttributeRequest): Promise => Dataverse.createAttribute(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to update an attribute.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TResponse - Type of the metadata to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n updateAttribute = (request: UpdateAttributeRequest): Promise => Dataverse.updateAttribute(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve attribute metadata for a specified entity definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TValue - Type of the item returned in the \"value\" array.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveAttributes = (request: RetrieveAttributesRequest): Promise> =>\r\n Dataverse.retrieveAttributes(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve a specific attribute metadata for a specified entity definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TResponse - Type of the metadata to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveAttribute = (request: RetrieveAttributeRequest): Promise => Dataverse.retrieveAttribute(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to create a relationship definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TResponse - Type of the metadata to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n createRelationship = (request: CreateRelationshipRequest): Promise => Dataverse.createRelationship(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to update a relationship definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TResponse - Type of the metadata to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n updateRelationship = (request: UpdateRelationshipRequest): Promise => Dataverse.updateRelationship(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to delete a relationship definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n deleteRelationship = (request: DeleteRelationshipRequest): Promise => Dataverse.deleteRelationship(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve relationship definitions.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TValue - Type of the item returned in the \"value\" array.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveRelationships = (request?: RetrieveRelationshipsRequest): Promise> =>\r\n Dataverse.retrieveRelationships(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve a specific relationship definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TResponse - Type of the metadata to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveRelationship = (request: RetrieveRelationshipRequest): Promise => Dataverse.retrieveRelationship(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to create a Global Option Set definition\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TResponse - Type of the metadata to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n createGlobalOptionSet = (request: CreateGlobalOptionSetRequest): Promise =>\r\n Dataverse.createGlobalOptionSet(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to update a Global Option Set.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TResponse - Type of the metadata to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n updateGlobalOptionSet = (request: UpdateGlobalOptionSetRequest): Promise =>\r\n Dataverse.updateGlobalOptionSet(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to delete a Global Option Set.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n deleteGlobalOptionSet = (request: DeleteGlobalOptionSetRequest): Promise => Dataverse.deleteGlobalOptionSet(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve Global Option Set definitions.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TResponse - Type of the metadata to be returned.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveGlobalOptionSet = (request: RetrieveGlobalOptionSetRequest): Promise =>\r\n Dataverse.retrieveGlobalOptionSet(request, this.#client);\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve Global Option Set definitions.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @template TValue - Type of the item returned in the \"value\" array.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveGlobalOptionSets = (request?: RetrieveGlobalOptionSetsRequest): Promise> =>\r\n Dataverse.retrieveGlobalOptionSets(request, this.#client);\r\n\r\n /**\r\n * Retrieves a CSDL Document Metadata\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} A raw CSDL $metadata document.\r\n */\r\n retrieveCsdlMetadata = async (request?: CsdlMetadataRequest): Promise => Dataverse.retrieveCsdlMetadata(request, this.#client);\r\n\r\n /**\r\n * @deprecated Use \"query\" instead.\r\n * Provides a search results page.\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise>} Search result.\r\n */\r\n search: SearchFunction = async (request: string | SearchRequest): Promise> =>\r\n //@ts-ignore Ignoring the type error issue, because SearchFunction is deprecated and it will return what needs to return with a conversion.\r\n Dataverse.query(request, this.#client);\r\n\r\n /**\r\n * The query operation returns search results based on a search term.\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} Query result.\r\n */\r\n query: QueryFunction = async (request: string | QueryRequest): Promise => Dataverse.query(request, this.#client);\r\n\r\n /**\r\n * Provides suggestions as the user enters text into a form field.\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise>} Suggestions result.\r\n */\r\n suggest: SuggestFunction = async (request: string | SuggestRequest): Promise> =>\r\n Dataverse.suggest(request, this.#client);\r\n\r\n /**\r\n * Provides autocompletion of input as the user enters text into a form field.\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} Result of an autocomplete.\r\n */\r\n autocomplete: AutocompleteFunction = async (request: string | AutocompleteRequest): Promise =>\r\n Dataverse.autocomplete(request, this.#client);\r\n\r\n /**\r\n * Sends a request to the status monitor resource.\r\n * @param backgroundOperationId - The ID of the background operation.\r\n * @returns {Promise} Background operation status.\r\n */\r\n getBackgroundOperationStatus = async (backgroundOperationId: string): Promise =>\r\n Dataverse.getBackgroundOperationStatus(backgroundOperationId, this.#client);\r\n\r\n /**\r\n * Cancels a background operation via the status monitor resource.\r\n * @param backgroundOperationId - The ID of the background operation.\r\n * @returns {Promise} Background operation status.\r\n */\r\n cancelBackgroundOperation = async (backgroundOperationId: string): Promise =>\r\n Dataverse.cancelBackgroundOperation(backgroundOperationId, this.#client);\r\n\r\n /**\r\n * Starts a batch request.\r\n */\r\n startBatch = (): void => Dataverse.startBatch(this.#client);\r\n\r\n /**\r\n * Executes a batch request. Please call DynamicsWebApi.startBatch() first to start a batch request.\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n executeBatch = async (request?: BatchRequest): Promise => Dataverse.executeBatch(request, this.#client);\r\n\r\n /**\r\n * Creates a new instance of DynamicsWebApi. If config is not provided, it is copied from a current instance.\r\n *\r\n * @param {Config} config configuration object.\r\n * @returns {DynamicsWebApi} A new instance of DynamicsWebApi\r\n */\r\n initializeInstance = (config?: Config): DynamicsWebApi => new DynamicsWebApi(config || this.#client.config);\r\n\r\n Utility = {\r\n /**\r\n * Searches for a collection name by provided entity name in a cached entity metadata.\r\n * The returned collection name can be null.\r\n *\r\n * @param {string} entityName entity name\r\n * @returns {string | null} collection name\r\n */\r\n getCollectionName: (entityName: string): string | null => getCollectionName(entityName),\r\n };\r\n}\r\n\r\n//have to put all types in here, so it is possible to export just a single d.ts file (there are no good solutions to automatically bundle all dts files currently)\r\n\r\nexport interface Expand {\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**Use the $filter system query option to set criteria for which entities will be returned. */\r\n filter?: string;\r\n /**Limit the number of results returned by using the $top system query option.Do not use $top with $count! */\r\n top?: number;\r\n /**An Array(of Strings) representing the order in which items are returned using the $orderby system query option.Use the asc or desc suffix to specify ascending or descending order respectively.The default is ascending if the suffix isn't applied. */\r\n orderBy?: string[];\r\n /**A name of a single-valued navigation property which needs to be expanded. */\r\n property?: string;\r\n /**An Array of Expand Objects representing the $expand Query Option value to control which related records need to be returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface BaseRequest {\r\n /**XHR requests only! Indicates whether the requests should be made synchronously or asynchronously.Default value is 'true'(asynchronously). */\r\n async?: boolean;\r\n /**Impersonates a user based on their systemuserid by adding \"MSCRMCallerID\" header.\r\n * A String representing the GUID value for the Dynamics 365 systemuserid. */\r\n impersonate?: string;\r\n /**Impersonates a user based on their Azure Active Directory (AAD) object id by passing that value along with the header \"CallerObjectId\". A String should represent a GUID value. */\r\n impersonateAAD?: string;\r\n /**If set to 'true', DynamicsWebApi adds a request header 'Cache-Control: no-cache'.Default value is 'false'. */\r\n noCache?: boolean;\r\n /** Authorization Token. If set, onTokenRefresh will not be called. */\r\n token?: string;\r\n /**Sets a number of milliseconds before a request times out. */\r\n timeout?: number;\r\n /**The AbortSignal interface represents a signal object that allows you to communicate with a DOM request and abort it if required via an AbortController object. */\r\n signal?: AbortSignal;\r\n /**Indicates if an operation must be included in a Change Set or not. Works in Batch Operations only.\r\n * By default, it's \"true\", except for GET operations - they are not allowed in Change Sets. */\r\n inChangeSet?: boolean;\r\n /**Headers to supply with a request. These headers will override configuraiton headers if the identical ones were set. */\r\n headers?: HeaderCollection;\r\n /**\r\n * Custom query parameters. Can be used to set parameter aliases for \"$filter\" and \"$orderBy\".\r\n * Important! These parameters ARE NOT URI encoded! */\r\n queryParams?: string[];\r\n /**\r\n * Use this parameter to include a shared variable value that is accessible within a plug-in.\r\n */\r\n tag?: string;\r\n}\r\n\r\nexport interface BatchRequest extends BaseRequest {\r\n /** Sets Prefer header to \"odata.continue-on-error\" that allows more requests be processed when errors occur. The batch request will return '200 OK' and individual response errors will be returned in the batch response body. */\r\n continueOnError?: boolean;\r\n}\r\n\r\nexport interface Request extends BaseRequest {\r\n /**A name of the Entity Collection or Entity Logical name. */\r\n collection?: string;\r\n}\r\n\r\nexport interface CRUDRequest extends Request {\r\n /**\r\n * A String representing collection record's Primary Key (GUID) or Alternate Key(s).\r\n * Can be ommitted in a Batch request when contentId is set.\r\n */\r\n key?: string;\r\n}\r\n\r\nexport interface CountRequest extends Request {\r\n /**Use the $filter system query option to set criteria for which entities will be returned. */\r\n filter?: string;\r\n}\r\n\r\nexport interface CountAllRequest extends CountRequest {\r\n /**A name of the Entity Collection or Entity Logical name. */\r\n collection: string;\r\n /**An Array (of strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n}\r\n\r\nexport interface FetchAllRequest extends Request {\r\n /**Sets FetchXML - a proprietary query language that provides capabilities to perform aggregation. */\r\n fetchXml: string;\r\n /**Sets Prefer header with value \"odata.include-annotations=\" and the specified annotation. Annotations provide additional information about lookups, options sets and other complex attribute types. For example: * or Microsoft.Dynamics.CRM.fetchxmlpagingcookie */\r\n includeAnnotations?: string;\r\n}\r\n\r\nexport interface FetchXmlRequest extends FetchAllRequest {\r\n /**Page number. */\r\n pageNumber?: number;\r\n /**Paging cookie. To retrive the first page, pagingCookie must be null. */\r\n pagingCookie?: string;\r\n}\r\n\r\nexport interface CreateRequest extends CRUDRequest {\r\n /**If set to true, the request bypasses custom business logic, all synchronous plug-ins and real-time workflows are disabled. Check for special exceptions in Microsft Docs. */\r\n bypassCustomPluginExecution?: boolean;\r\n /**Web API v9+ only! Boolean that enables duplicate detection. */\r\n duplicateDetection?: boolean;\r\n /**A JavaScript object with properties corresponding to the logical name of entity attributes(exceptions are lookups and single-valued navigation properties). */\r\n data?: TData;\r\n /**An array of Expand Objects representing the $expand OData System Query Option value to control which related records are also returned. Can also accept a string. */\r\n expand?: string | Expand[];\r\n /**Sets Prefer header with value \"odata.include-annotations=\" and the specified annotation.Annotations provide additional information about lookups, options sets and other complex attribute types. */\r\n includeAnnotations?: string;\r\n /**A String representing the name of a single - valued navigation property. Useful when needed to retrieve information about a related record in a single request. */\r\n navigationProperty?: string;\r\n /**A String representing navigation property's Primary Key (GUID) or Alternate Key(s). (For example, to retrieve Attribute Metadata). */\r\n navigationPropertyKey?: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**Sets Prefer header request with value \"return=representation\".Use this property to return just created or updated entity in a single request. */\r\n returnRepresentation?: boolean;\r\n /**BATCH REQUESTS ONLY! Sets Content-ID header or references request in a Change Set. */\r\n contentId?: string;\r\n /**A unique partition key value of a logical partition for non-relational custom entity data stored in NoSql tables of Azure heterogenous storage. */\r\n partitionId?: string;\r\n}\r\n\r\nexport interface CreateWithRepresentationRequest extends Omit, \"returnRepresentation\"> {\r\n returnRepresentation: true;\r\n}\r\n\r\nexport interface UpdateRequestBase extends CRUDRequest {\r\n /**If set to true, the request bypasses custom business logic, all synchronous plug-ins and real-time workflows are disabled. Check for special exceptions in Microsft Docs. */\r\n bypassCustomPluginExecution?: boolean;\r\n /**Web API v9+ only! Boolean that enables duplicate detection. */\r\n duplicateDetection?: boolean;\r\n /**A JavaScript object with properties corresponding to the logical name of entity attributes(exceptions are lookups and single-valued navigation properties). */\r\n data?: T;\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n /**Sets If-Match header value that enables to use conditional retrieval or optimistic concurrency in applicable requests.*/\r\n ifmatch?: string;\r\n /**Sets Prefer header with value \"odata.include-annotations=\" and the specified annotation.Annotations provide additional information about lookups, options sets and other complex attribute types. */\r\n includeAnnotations?: string;\r\n /**Sets Prefer header request with value \"return=representation\".Use this property to return just created or updated entity in a single request. */\r\n returnRepresentation?: boolean;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**BATCH REQUESTS ONLY! Sets Content-ID header or references request in a Change Set. */\r\n contentId?: string;\r\n /**Casts the AttributeMetadata to a specific type. (Used in requests to Attribute Metadata). */\r\n metadataAttributeType?: string;\r\n /**A String representing the name of a single - valued navigation property. Useful when needed to retrieve information about a related record in a single request. */\r\n navigationProperty?: string;\r\n /**A String representing navigation property's Primary Key (GUID) or Alternate Key(s). (For example, to retrieve Attribute Metadata). */\r\n navigationPropertyKey?: string;\r\n /**A unique partition key value of a logical partition for non-relational custom entity data stored in NoSql tables of Azure heterogenous storage. */\r\n partitionId?: string;\r\n}\r\n\r\nexport interface UpdateRequest extends UpdateRequestBase {\r\n /**If set to 'true', DynamicsWebApi adds a request header 'MSCRM.MergeLabels: true'. Default value is 'false' */\r\n mergeLabels?: boolean;\r\n}\r\n\r\nexport interface UpdateSinglePropertyRequest extends CRUDRequest {\r\n /**Object with a logical name of the field as a key and a value to update with. Example: {subject: \"Update Record\"} */\r\n fieldValuePair: { [key: string]: any };\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n /**Sets If-Match header value that enables to use conditional retrieval or optimistic concurrency in applicable requests.*/\r\n ifmatch?: string;\r\n /**Sets Prefer header with value \"odata.include-annotations=\" and the specified annotation.Annotations provide additional information about lookups, options sets and other complex attribute types. */\r\n includeAnnotations?: string;\r\n /**Sets Prefer header request with value \"return=representation\".Use this property to return just created or updated entity in a single request. */\r\n returnRepresentation?: boolean;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**BATCH REQUESTS ONLY! Sets Content-ID header or references request in a Change Set. */\r\n contentId?: string;\r\n}\r\n\r\nexport interface UpsertRequest extends UpdateRequestBase {\r\n /**Sets If-None-Match header value that enables to use conditional retrieval in applicable requests. */\r\n ifnonematch?: string;\r\n}\r\n\r\nexport interface DeleteRequest extends CRUDRequest {\r\n /**If set to true, the request bypasses custom business logic, all synchronous plug-ins and real-time workflows are disabled. Check for special exceptions in Microsft Docs. */\r\n bypassCustomPluginExecution?: boolean;\r\n /**Sets If-Match header value that enables to use conditional retrieval or optimistic concurrency in applicable requests.*/\r\n ifmatch?: string;\r\n /**BATCH REQUESTS ONLY! Sets Content-ID header or references request in a Change Set. */\r\n contentId?: string;\r\n /**\r\n * Field name that needs to be cleared (for example File Field)\r\n * @deprecated Use \"property\".\r\n */\r\n fieldName?: string;\r\n /**Single property that needs to be cleared (including the File property) */\r\n property?: string;\r\n}\r\n\r\nexport interface RetrieveRequest extends CRUDRequest {\r\n /**A name of the Entity Collection or Entity Logical name. */\r\n collection: string;\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n /**Sets If-Match header value that enables to use conditional retrieval or optimistic concurrency in applicable requests.*/\r\n ifmatch?: string;\r\n /**Sets If-None-Match header value that enables to use conditional retrieval in applicable requests. */\r\n ifnonematch?: string;\r\n /**Sets Prefer header with value \"odata.include-annotations=\" and the specified annotation.Annotations provide additional information about lookups, options sets and other complex attribute types. */\r\n includeAnnotations?: string;\r\n /**Casts the AttributeMetadata to a specific type. (Used in requests to Attribute Metadata). */\r\n metadataAttributeType?: string;\r\n /**A String representing the name of a single - valued navigation property. Useful when needed to retrieve information about a related record in a single request. */\r\n navigationProperty?: string;\r\n /**A String representing navigation property's Primary Key (GUID) or Alternate Key(s). (For example, to retrieve Attribute Metadata). */\r\n navigationPropertyKey?: string;\r\n /**A String representing the GUID value of the saved query. */\r\n savedQuery?: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**A String representing the GUID value of the user query. */\r\n userQuery?: string;\r\n /**A unique partition key value of a logical partition for non-relational custom entity data stored in NoSql tables of Azure heterogenous storage. */\r\n partitionId?: string;\r\n}\r\n\r\nexport interface RetrieveMultipleRequest extends Request {\r\n /**A name of the Entity Collection or Entity Logical name. */\r\n collection: string;\r\n /**Use the $apply to aggregate and group your data dynamically */\r\n apply?: string;\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n /**Boolean that sets the $count system query option with a value of true to include a count of entities that match the filter criteria up to 5000(per page).Do not use $top with $count! */\r\n count?: boolean;\r\n /**Use the $filter system query option to set criteria for which entities will be returned. */\r\n filter?: string;\r\n /**Sets Prefer header with value \"odata.include-annotations=\" and the specified annotation.Annotations provide additional information about lookups, options sets and other complex attribute types. */\r\n includeAnnotations?: string;\r\n /**Sets the odata.maxpagesize preference value to request the number of entities returned in the response. */\r\n maxPageSize?: number;\r\n /**An Array(of string) representing the order in which items are returned using the $orderby system query option.Use the asc or desc suffix to specify ascending or descending order respectively.The default is ascending if the suffix isn't applied. */\r\n orderBy?: string[];\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**Limit the number of results returned by using the $top system query option.Do not use $top with $count! */\r\n top?: number;\r\n /**Sets Prefer header with value 'odata.track-changes' to request that a delta link be returned which can subsequently be used to retrieve entity changes. */\r\n trackChanges?: boolean;\r\n /**A unique partition key value of a logical partition for non-relational custom entity data stored in NoSql tables of Azure heterogenous storage. */\r\n partitionId?: string;\r\n}\r\n\r\nexport interface AssociateRequest extends Request {\r\n /**\r\n * Primary entity record id/key.\r\n * Can be ommitted in a Batch request when contentId is set.\r\n */\r\n primaryKey?: string;\r\n /**Relationship name. */\r\n relationshipName: string;\r\n /**\r\n * Related name of the Entity Collection or Entity Logical name.\r\n * Can be omitted in a Batch request when relatedKey is set to a ContentId.\r\n */\r\n relatedCollection?: string;\r\n /**Related entity record id/key or a ContentId in a Batch request (e.g. $2). */\r\n relatedKey: string;\r\n /**v2.3.1+ BATCH REQUESTS ONLY! Sets Content-ID header or references request in a Change Set. */\r\n contentId?: string;\r\n}\r\n\r\nexport interface AssociateSingleValuedRequest extends Request {\r\n /**\r\n * Primary entity record id/key.\r\n * Can be ommitted in a Batch request when contentId is set.\r\n */\r\n primaryKey?: string;\r\n /**Navigation property name. */\r\n navigationProperty: string;\r\n /**\r\n * Related name of the Entity Collection or Entity Logical name.\r\n * Can be omitted in a Batch request when relatedKey is set to a ContentId.\r\n */\r\n relatedCollection?: string;\r\n /**Related entity record id/key or a ContentId in a Batch request (e.g. $2). */\r\n relatedKey: string;\r\n /**v2.3.1+ BATCH REQUESTS ONLY! Sets Content-ID header or references request in a Change Set. */\r\n contentId?: string;\r\n}\r\n\r\nexport interface DisassociateRequest extends Request {\r\n /**Primary entity record id/key. */\r\n primaryKey: string;\r\n /**Relationship name. */\r\n relationshipName: string;\r\n /**Related entity record id/key. */\r\n relatedKey: string;\r\n}\r\n\r\nexport interface DisassociateSingleValuedRequest extends Request {\r\n /**Primary entity record id/key. */\r\n primaryKey: string;\r\n /**Navigation property name. */\r\n navigationProperty: string;\r\n}\r\n\r\nexport interface UnboundFunctionRequest extends BaseRequest {\r\n /**\r\n * Name of the function.\r\n */\r\n name?: string;\r\n /**\r\n * Name of the function.\r\n * @deprecated Use \"name\" parameter.\r\n */\r\n functionName?: string;\r\n /**Function's input parameters. Example: { param1: \"test\", param2: 3 }. */\r\n parameters?: any;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**Use the $filter system query option to set criteria for which entities will be returned. */\r\n filter?: string;\r\n}\r\n\r\nexport interface BoundFunctionRequest extends UnboundFunctionRequest, Request {\r\n /**A String representing the GUID value for the record. */\r\n key?: string;\r\n}\r\n\r\nexport interface UnboundActionRequest extends BaseRequest {\r\n /**A name of the Web API action. */\r\n actionName: string;\r\n /**An object that represents a Dynamics 365 action. */\r\n action?: TAction;\r\n /**\r\n * A callback URL when the background operation is completed.\r\n * Dataverse uses this URL to send a POST request.\r\n */\r\n backgroundOperationCallbackUrl?: string;\r\n /**\r\n * Use background operations to send requests that Dataverse processes asynchronously.\r\n * Background operations are useful when you don't want to maintain a connection while a request runs.\r\n */\r\n respondAsync?: boolean;\r\n}\r\n\r\nexport interface BoundActionRequest extends UnboundActionRequest, Request {\r\n /**A String representing the GUID value for the record. */\r\n key?: string;\r\n}\r\n\r\nexport interface CreateEntityRequest extends BaseRequest {\r\n /**An object with properties corresponding to the logical name of entity attributes(exceptions are lookups and single-valued navigation properties). */\r\n data: any;\r\n}\r\n\r\nexport interface UpdateEntityRequest extends CRUDRequest {\r\n /**An object with properties corresponding to the logical name of entity attributes(exceptions are lookups and single-valued navigation properties). */\r\n data: any;\r\n /**Sets MSCRM.MergeLabels header that controls whether to overwrite the existing labels or merge your new label with any existing language labels. Default value is false. */\r\n mergeLabels?: boolean;\r\n}\r\n\r\nexport interface RetrieveEntityRequest extends BaseRequest {\r\n /**An Entity MetadataId or Alternate Key (such as LogicalName). */\r\n key: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface RetrieveEntitiesRequest extends BaseRequest {\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**Use the $filter system query option to set criteria for which entities will be returned. */\r\n filter?: string;\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface CreateAttributeRequest extends BaseRequest {\r\n /**An Entity MetadataId or Alternate Key (such as LogicalName). */\r\n entityKey: string;\r\n /**Attribute metadata object. */\r\n data: any;\r\n}\r\n\r\nexport interface UpdateAttributeRequest extends CreateAttributeRequest {\r\n /**Use this parameter to cast the Attribute to a specific type. */\r\n castType?: string;\r\n /**Sets MSCRM.MergeLabels header that controls whether to overwrite the existing labels or merge your new label with any existing language labels. Default value is false. */\r\n mergeLabels?: boolean;\r\n}\r\n\r\nexport interface RetrieveAttributesRequest extends BaseRequest {\r\n /**An Entity MetadataId or Alternate Key (such as LogicalName). */\r\n entityKey: string;\r\n /**Use this parameter to cast the Attribute to a specific type. */\r\n castType?: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**Use the $filter system query option to set criteria for which entities will be returned. */\r\n filter?: string;\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface RetrieveAttributeRequest extends BaseRequest {\r\n /**An Attribute MetadataId or Alternate Key (such as LogicalName). */\r\n attributeKey: string;\r\n /**An Entity MetadataId or Alternate Key (such as LogicalName). */\r\n entityKey: string;\r\n /**Use this parameter to cast the Attribute to a specific type. */\r\n castType?: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface CreateRelationshipRequest extends BaseRequest {\r\n /**Relationship Definition. */\r\n data: any;\r\n}\r\n\r\nexport interface UpdateRelationshipRequest extends CreateRelationshipRequest {\r\n /**Use this parameter to cast the Relationship metadata to a specific type. */\r\n castType?: string;\r\n /**Sets MSCRM.MergeLabels header that controls whether to overwrite the existing labels or merge your new label with any existing language labels. Default value is false. */\r\n mergeLabels?: boolean;\r\n}\r\n\r\nexport interface DeleteRelationshipRequest extends BaseRequest {\r\n /**A Relationship MetadataId or Alternate Key (such as LogicalName). */\r\n key: string;\r\n}\r\n\r\nexport interface RetrieveRelationshipsRequest extends BaseRequest {\r\n /**Use this parameter to cast the Relationship metadata to a specific type. */\r\n castType?: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**Use the $filter system query option to set criteria for which entities will be returned. */\r\n filter?: string;\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface RetrieveRelationshipRequest extends BaseRequest {\r\n /**A Relationship MetadataId or Alternate Key (such as LogicalName). */\r\n key: string;\r\n /**Use this parameter to cast the Relationship metadata to a specific type. */\r\n castType?: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface CreateGlobalOptionSetRequest extends BaseRequest {\r\n /**Global Option Set Definition. */\r\n data: any;\r\n}\r\n\r\nexport interface UpdateGlobalOptionSetRequest extends CreateRelationshipRequest {\r\n /**Use this parameter to cast the Global Option Set metadata to a specific type. */\r\n castType?: string;\r\n /**Sets MSCRM.MergeLabels header that controls whether to overwrite the existing labels or merge your new label with any existing language labels. Default value is false. */\r\n mergeLabels?: boolean;\r\n}\r\n\r\nexport interface DeleteGlobalOptionSetRequest extends BaseRequest {\r\n /**A Global Option Set MetadataId or Alternate Key (such as LogicalName). */\r\n key: string;\r\n}\r\n\r\nexport interface RetrieveGlobalOptionSetsRequest extends BaseRequest {\r\n /**Use this parameter to cast the Global Option Set metadata to a specific type. */\r\n castType?: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**Use the $filter system query option to set criteria for which entities will be returned. */\r\n filter?: string;\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface RetrieveGlobalOptionSetRequest extends BaseRequest {\r\n /**A Global Option Set MetadataId or Alternate Key (such as LogicalName). */\r\n key: string;\r\n /**Use this parameter to cast the Global Option Set metadata to a specific type. */\r\n castType?: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface UploadRequest extends CRUDRequest {\r\n /**Binary Buffer*/\r\n data: Uint8Array | Buffer;\r\n /**Name of the file */\r\n fileName: string;\r\n /**The name of File Column (field) */\r\n property?: string;\r\n /**\r\n * File Field Name\r\n * @deprecated Use \"property\".\r\n */\r\n fieldName?: string;\r\n}\r\n\r\nexport interface DownloadRequest extends CRUDRequest {\r\n /**The name of File Column (field) */\r\n property?: string;\r\n /**\r\n * File Field Name\r\n * @deprecated Use \"property\".\r\n */\r\n fieldName?: string;\r\n}\r\n\r\nexport interface CsdlMetadataRequest extends BaseRequest {\r\n /**If set to \"true\" the document will include many different kinds of annotations that can be useful. Most annotations are not included by default because they increase the total size of the document. */\r\n addAnnotations?: boolean;\r\n}\r\n\r\nexport type BackgroundOperationResponse = {\r\n /**\r\n * Location URL of the background operation.\r\n */\r\n location: string;\r\n /**\r\n * The ID of the background operation.\r\n */\r\n backgroundOperationId: string;\r\n};\r\n\r\nexport type SearchMode = \"any\" | \"all\";\r\nexport type SearchType = \"simple\" | \"full\";\r\n\r\nexport type SearchEntity = {\r\n /**Logical name of the table. Specifies scope of the query. */\r\n name: string;\r\n /**List of columns that needs to be projected when table documents are returned in response. If empty, only the table primary name is returned. */\r\n selectColumns?: string[];\r\n /**List of columns to scope the query on. If empty, only the table primary name is searched on.*/\r\n searchColumns?: string[];\r\n /**Filters applied on the entity.*/\r\n filter?: string;\r\n};\r\n\r\nexport type SearchOptions = Record & {\r\n /**Values can be simple or lucene. */\r\n queryType?: \"simple\" | \"lucene\";\r\n /**Enables intelligent query workflow to return probable set of results if no good matches are found for the search request terms.*/\r\n bestEffortSearchEnabled?: boolean;\r\n /**Enable ranking of results in the response optimized for display in search results pages where results are grouped by table.*/\r\n searchMode?: SearchMode;\r\n /**When specified as all the search terms must be matched in order to consider the document as a match. Setting its value to any defaults to matching any word in the search term.*/\r\n groupRankingEnabled?: boolean;\r\n};\r\n\r\nexport type SuggestOptions = Record & {\r\n /**Enables advanced suggestions for the search query. The default is false. */\r\n advancedSuggestEnabled?: boolean;\r\n};\r\n\r\nexport interface SearchQueryBase {\r\n /**The text to search with. It has a 100-character limit. For suggestions, min 3 characters in addition. */\r\n search: string;\r\n /**Limits the scope of search to a subset of tables. The default set is configured by your administrator when Dataverse search is enabled. */\r\n entities?: string[] | SearchEntity[] | string;\r\n /**Limits the scope of the search results returned. */\r\n filter?: string;\r\n}\r\n\r\nexport interface Query extends SearchQueryBase {\r\n /**V2. Specify true to return the total record count; otherwise false. The default is false. */\r\n count?: boolean;\r\n /**Facets support the ability to drill down into data results after they've been retrieved. */\r\n facets?: string | string[];\r\n /**\r\n * V1. Specify true to return the total record count; otherwise false. The default is false.\r\n * @deprecated Use \"count\".\r\n */\r\n returnTotalRecordCount?: boolean;\r\n /**Specifies the number of search results to skip. */\r\n skip?: number;\r\n /**Specifies the number of search results to retrieve. The default is 50, and the maximum value is 100. */\r\n top?: number;\r\n /**A list of clauses where each clause consists of a column name followed by 'asc' (ascending, which is the default) or 'desc' (descending). This list specifies how to order the results in order of precedence. */\r\n orderBy?: string | string[];\r\n /**V2. Options are settings configured to search a search term. */\r\n options?: string | SearchOptions;\r\n /**\r\n * V1. Specifies whether any or all the search terms must be matched to count the document as a match. The default is 'any'.\r\n * @deprecated Use \"options.searchmode\".\r\n */\r\n searchMode?: SearchMode;\r\n /**\r\n * V1. The search type specifies the syntax of a search query. Using 'simple' selects simple query syntax and 'full' selects Lucene query syntax. The default is 'simple'.\r\n * @deprecated Use \"options.querytype\".\r\n */\r\n searchType?: SearchType;\r\n}\r\n\r\n/**@deprecated Use Query instead */\r\nexport interface Search extends Query {}\r\n\r\nexport interface Suggest extends SearchQueryBase {\r\n /**Use fuzzy search to aid with misspellings. The default is false. */\r\n fuzzy?: boolean;\r\n /**\r\n * Use fuzzy search to aid with misspellings. The default is false.\r\n * @deprecated Use \"fuzzy\".\r\n */\r\n useFuzzy?: boolean;\r\n /**V2. Options are settings configured to search a search term. */\r\n options?: string | SuggestOptions;\r\n /**Number of suggestions to retrieve. The default is 5. */\r\n top?: number;\r\n /**A list of comma-separated clauses where each clause consists of a column name followed by 'asc' (ascending, which is the default) or 'desc' (descending). This list specifies how to order the results in order of precedence. */\r\n orderBy?: string | string[];\r\n}\r\n\r\nexport interface Autocomplete extends SearchQueryBase {\r\n /**Use fuzzy search to aid with misspellings. The default is false. */\r\n fuzzy?: boolean;\r\n /**\r\n * Use fuzzy search to aid with misspellings. The default is false.\r\n * @deprecated Use \"fuzzy\".\r\n */\r\n useFuzzy?: boolean;\r\n}\r\n\r\nexport interface QueryRequest extends BaseRequest {\r\n /**Search query object */\r\n query: Query;\r\n}\r\n\r\n/**@deprecated Use QueryRequest instead. */\r\nexport interface SearchRequest extends QueryRequest {}\r\n\r\nexport interface SuggestRequest extends BaseRequest {\r\n /**Suggestion query object */\r\n query: Suggest;\r\n}\r\n\r\nexport interface AutocompleteRequest extends BaseRequest {\r\n /**Autocomplete query object */\r\n query: Autocomplete;\r\n}\r\n\r\nexport type SearchApiOptions = {\r\n /**\r\n * Escapes the search string.\r\n * Special characters that require escaping include the following: + - & | ! ( ) { } [ ] ^ \" ~ * ? : \\ /.\r\n */\r\n escapeSpecialCharacters?: boolean;\r\n /**\r\n * Enables compatibility of the responses between v1 and v2.\r\n * Only enable this option temporarily, because it will force all response properties to be duplicated to achieve a full compatibility.\r\n */\r\n enableResponseCompatibility?: boolean;\r\n};\r\n\r\nexport interface ApiConfig {\r\n /** API Version to use, for example: \"9.2\" or \"1.0\". */\r\n version?: string;\r\n /** API Path, for example: \"data\" or \"search\". */\r\n path?: string;\r\n /** Specific API options. Currently it is only available for the Search API .*/\r\n options?: TOptions;\r\n}\r\n\r\nexport interface AccessToken {\r\n /** Access Token */\r\n accessToken: string;\r\n}\r\n\r\nexport interface Config {\r\n /**The url to Dataverse API server, for example: https://contoso.api.crm.dynamics.com/. It is required when used in Node.js application. */\r\n serverUrl?: string | null;\r\n /**Impersonates a user based on their systemuserid by adding \"MSCRMCallerID\" header. A String representing the GUID value for the Dynamics 365 systemuserid. */\r\n impersonate?: string | null;\r\n /**Impersonates a user based on their Azure Active Directory (AAD) object id by passing that value along with the header \"CallerObjectId\". A String should represent a GUID value. */\r\n impersonateAAD?: string | null;\r\n /**A function that is called when a security token needs to be refreshed. */\r\n onTokenRefresh?: (() => Promise) | null;\r\n /**Sets Prefer header with value \"odata.include-annotations=\" and the specified annotation.Annotations provide additional information about lookups, options sets and other complex attribute types.*/\r\n includeAnnotations?: string | null;\r\n /**Sets the odata.maxpagesize preference value to request the number of entities returned in the response. */\r\n maxPageSize?: number | null;\r\n /**Sets Prefer header request with value \"return=representation\".Use this property to return just created or updated entity in a single request.*/\r\n returnRepresentation?: boolean | null;\r\n /**Indicates whether to use Entity Logical Names instead of Collection Logical Names.*/\r\n useEntityNames?: boolean | null;\r\n /**Sets a number of milliseconds before a request times out. */\r\n timeout?: number | null;\r\n /**Proxy configuration object. */\r\n proxy?: ProxyConfig | null;\r\n /**Configuration object for Dataverse Web API (with path \"data\"). */\r\n dataApi?: ApiConfig;\r\n /**Configuration object for Dataverse Search API (with path \"search\"). */\r\n searchApi?: ApiConfig;\r\n /**Default headers to supply with each request. */\r\n headers?: HeaderCollection;\r\n /**\r\n * A default callback URL when the background operation is completed.\r\n * Dataverse uses this URL to send a POST request.\r\n * You can also set a callback URL per request.\r\n */\r\n backgroundOperationCallbackUrl?: string;\r\n}\r\n\r\n/**Header collection type */\r\nexport type HeaderCollection = Record;\r\n\r\nexport interface ProxyConfig {\r\n /**Proxy server url */\r\n url: string;\r\n /**Basic authentication credentials */\r\n auth?: {\r\n /**Username */\r\n username: string;\r\n /**Password */\r\n password: string;\r\n };\r\n}\r\n\r\n/** Callback with an acquired token called by DynamicsWebApi; \"token\" argument can be a string or an object with a property {accessToken: } */\r\n// export interface OnTokenAcquiredCallback {\r\n// (token: any): void;\r\n// }\r\n\r\nexport interface RequestError extends Error {\r\n /**The name of the error */\r\n name: string;\r\n /**This code is not related to the http status code and is frequently empty */\r\n code?: string;\r\n /**A message describing the error */\r\n message: string;\r\n /**HTTP status code */\r\n status?: number;\r\n /**HTTP status text. Frequently empty */\r\n statusText?: string;\r\n /**HTTP Response headers */\r\n headers?: any;\r\n /**Details about an error */\r\n innererror?: {\r\n /**A message describing the error, this is frequently the same as the outer message */\r\n message?: string;\r\n /**Microsoft.Crm.CrmHttpException */\r\n type?: string;\r\n /**Details from the server about where the error occurred */\r\n stacktrace?: string;\r\n };\r\n}\r\n\r\nexport interface MultipleResponse {\r\n /**Multiple respone entities */\r\n value: TValue[];\r\n oDataCount?: number;\r\n \"@odata.count\"?: number;\r\n oDataContext?: string;\r\n \"@odata.context\"?: number;\r\n}\r\n\r\nexport interface AllResponse extends MultipleResponse