@esri/telemetry-amazon 3.0.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4971,72 +4971,6 @@
4971
4971
  return t;
4972
4972
  }
4973
4973
 
4974
- /*! *****************************************************************************
4975
- Copyright (c) Microsoft Corporation.
4976
-
4977
- Permission to use, copy, modify, and/or distribute this software for any
4978
- purpose with or without fee is hereby granted.
4979
-
4980
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
4981
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
4982
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
4983
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
4984
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
4985
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
4986
- PERFORMANCE OF THIS SOFTWARE.
4987
- ***************************************************************************** */
4988
-
4989
- var __assign$1 = function() {
4990
- __assign$1 = Object.assign || function __assign(t) {
4991
- for (var s, i = 1, n = arguments.length; i < n; i++) {
4992
- s = arguments[i];
4993
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
4994
- }
4995
- return t;
4996
- };
4997
- return __assign$1.apply(this, arguments);
4998
- };
4999
-
5000
- /*! *****************************************************************************
5001
- Copyright (c) Microsoft Corporation.
5002
-
5003
- Permission to use, copy, modify, and/or distribute this software for any
5004
- purpose with or without fee is hereby granted.
5005
-
5006
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
5007
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
5008
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
5009
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
5010
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
5011
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
5012
- PERFORMANCE OF THIS SOFTWARE.
5013
- ***************************************************************************** */
5014
- /* global Reflect, Promise */
5015
-
5016
- var extendStatics = function(d, b) {
5017
- extendStatics = Object.setPrototypeOf ||
5018
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5019
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
5020
- return extendStatics(d, b);
5021
- };
5022
-
5023
- function __extends(d, b) {
5024
- extendStatics(d, b);
5025
- function __() { this.constructor = d; }
5026
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5027
- }
5028
-
5029
- var __assign = function() {
5030
- __assign = Object.assign || function __assign(t) {
5031
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5032
- s = arguments[i];
5033
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
5034
- }
5035
- return t;
5036
- };
5037
- return __assign.apply(this, arguments);
5038
- };
5039
-
5040
4974
  /* Copyright (c) 2017 Environmental Systems Research Institute, Inc.
5041
4975
  * Apache-2.0 */
5042
4976
  /**
@@ -5045,15 +4979,15 @@
5045
4979
  * @return A boolean indicating if FormData will be required.
5046
4980
  */
5047
4981
  function requiresFormData(params) {
5048
- return Object.keys(params).some(function (key) {
5049
- var value = params[key];
4982
+ return Object.keys(params).some((key) => {
4983
+ let value = params[key];
5050
4984
  if (!value) {
5051
4985
  return false;
5052
4986
  }
5053
4987
  if (value && value.toParam) {
5054
4988
  value = value.toParam();
5055
4989
  }
5056
- var type = value.constructor.name;
4990
+ const type = value.constructor.name;
5057
4991
  switch (type) {
5058
4992
  case "Array":
5059
4993
  return false;
@@ -5080,10 +5014,10 @@
5080
5014
  * @return A new object with properly encoded values.
5081
5015
  */
5082
5016
  function processParams(params) {
5083
- var newParams = {};
5084
- Object.keys(params).forEach(function (key) {
5017
+ const newParams = {};
5018
+ Object.keys(params).forEach((key) => {
5085
5019
  var _a, _b;
5086
- var param = params[key];
5020
+ let param = params[key];
5087
5021
  if (param && param.toParam) {
5088
5022
  param = param.toParam();
5089
5023
  }
@@ -5093,8 +5027,8 @@
5093
5027
  typeof param !== "string") {
5094
5028
  return;
5095
5029
  }
5096
- var type = param.constructor.name;
5097
- var value;
5030
+ const type = param.constructor.name;
5031
+ let value;
5098
5032
  // properly encodes objects, arrays and dates for arcgis.com and other services.
5099
5033
  // ported from https://github.com/Esri/esri-leaflet/blob/master/src/Request.js#L22-L30
5100
5034
  // also see https://github.com/Esri/arcgis-rest-js/issues/18:
@@ -5104,11 +5038,13 @@
5104
5038
  // Based on the first element of the array, classify array as an array of arrays, an array of objects
5105
5039
  // to be stringified, or an array of non-objects to be comma-separated
5106
5040
  // eslint-disable-next-line no-case-declarations
5107
- var firstElementType = (_b = (_a = param[0]) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name;
5041
+ const firstElementType = (_b = (_a = param[0]) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name;
5108
5042
  value =
5109
- firstElementType === "Array" ? param : // pass thru array of arrays
5110
- firstElementType === "Object" ? JSON.stringify(param) : // stringify array of objects
5111
- param.join(","); // join other types of array elements
5043
+ firstElementType === "Array"
5044
+ ? param // pass thru array of arrays
5045
+ : firstElementType === "Object"
5046
+ ? JSON.stringify(param) // stringify array of objects
5047
+ : param.join(","); // join other types of array elements
5112
5048
  break;
5113
5049
  case "Object":
5114
5050
  value = JSON.stringify(param);
@@ -5126,7 +5062,10 @@
5126
5062
  value = param;
5127
5063
  break;
5128
5064
  }
5129
- if (value || value === 0 || typeof value === "string" || Array.isArray(value)) {
5065
+ if (value ||
5066
+ value === 0 ||
5067
+ typeof value === "string" ||
5068
+ Array.isArray(value)) {
5130
5069
  newParams[key] = value;
5131
5070
  }
5132
5071
  });
@@ -5145,7 +5084,9 @@
5145
5084
  function encodeParam(key, value) {
5146
5085
  // For array of arrays, repeat key=value for each element of containing array
5147
5086
  if (Array.isArray(value) && value[0] && Array.isArray(value[0])) {
5148
- return value.map(function (arrayElem) { return encodeParam(key, arrayElem); }).join("&");
5087
+ return value
5088
+ .map((arrayElem) => encodeParam(key, arrayElem))
5089
+ .join("&");
5149
5090
  }
5150
5091
  return encodeURIComponent(key) + "=" + encodeURIComponent(value);
5151
5092
  }
@@ -5156,14 +5097,16 @@
5156
5097
  * @returns An encoded query string.
5157
5098
  */
5158
5099
  function encodeQueryString(params) {
5159
- var newParams = processParams(params);
5100
+ const newParams = processParams(params);
5160
5101
  return Object.keys(newParams)
5161
- .map(function (key) {
5102
+ .map((key) => {
5162
5103
  return encodeParam(key, newParams[key]);
5163
5104
  })
5164
5105
  .join("&");
5165
5106
  }
5166
5107
 
5108
+ const FormData = globalThis.FormData;
5109
+
5167
5110
  /* Copyright (c) 2017 Environmental Systems Research Institute, Inc.
5168
5111
  * Apache-2.0 */
5169
5112
  /**
@@ -5174,25 +5117,25 @@
5174
5117
  */
5175
5118
  function encodeFormData(params, forceFormData) {
5176
5119
  // see https://github.com/Esri/arcgis-rest-js/issues/499 for more info.
5177
- var useFormData = requiresFormData(params) || forceFormData;
5178
- var newParams = processParams(params);
5120
+ const useFormData = requiresFormData(params) || forceFormData;
5121
+ const newParams = processParams(params);
5179
5122
  if (useFormData) {
5180
- var formData_1 = new FormData();
5181
- Object.keys(newParams).forEach(function (key) {
5123
+ const formData = new FormData();
5124
+ Object.keys(newParams).forEach((key) => {
5182
5125
  if (typeof Blob !== "undefined" && newParams[key] instanceof Blob) {
5183
5126
  /* To name the Blob:
5184
5127
  1. look to an alternate request parameter called 'fileName'
5185
5128
  2. see if 'name' has been tacked onto the Blob manually
5186
5129
  3. if all else fails, use the request parameter
5187
5130
  */
5188
- var filename = newParams["fileName"] || newParams[key].name || key;
5189
- formData_1.append(key, newParams[key], filename);
5131
+ const filename = newParams["fileName"] || newParams[key].name || key;
5132
+ formData.append(key, newParams[key], filename);
5190
5133
  }
5191
5134
  else {
5192
- formData_1.append(key, newParams[key]);
5135
+ formData.append(key, newParams[key]);
5193
5136
  }
5194
5137
  });
5195
- return formData_1;
5138
+ return formData;
5196
5139
  }
5197
5140
  else {
5198
5141
  return encodeQueryString(params);
@@ -5201,11 +5144,20 @@
5201
5144
 
5202
5145
  /* Copyright (c) 2017 Environmental Systems Research Institute, Inc.
5203
5146
  * Apache-2.0 */
5204
- // TypeScript 2.1 no longer allows you to extend built in types. See https://github.com/Microsoft/TypeScript/issues/12790#issuecomment-265981442
5205
- // and https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
5206
- //
5207
- // This code is from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types.
5208
- var ArcGISRequestError = /** @class */ (function () {
5147
+ /**
5148
+ * This represents a generic error from an ArcGIS endpoint. There will be details about the error in the {@linkcode ArcGISRequestError.message}, {@linkcode ArcGISRequestError.originalMessage} properties on the error. You
5149
+ * can also access the original server response at {@linkcode ArcGISRequestError.response} which may have additional details.
5150
+ *
5151
+ * ```js
5152
+ * request(someUrl, someOptions).catch(e => {
5153
+ * if(e.name === "ArcGISRequestError") {
5154
+ * console.log("Something went wrong with the request:", e);
5155
+ * console.log("Full server response", e.response);
5156
+ * }
5157
+ * })
5158
+ * ```
5159
+ */
5160
+ class ArcGISRequestError extends Error {
5209
5161
  /**
5210
5162
  * Create a new `ArcGISRequestError` object.
5211
5163
  *
@@ -5215,34 +5167,82 @@
5215
5167
  * @param url - The original url of the request
5216
5168
  * @param options - The original options and parameters of the request
5217
5169
  */
5218
- function ArcGISRequestError(message, code, response, url, options) {
5170
+ constructor(message, code, response, url, options) {
5171
+ // 'Error' breaks prototype chain here
5172
+ super(message);
5173
+ // restore prototype chain, see https://stackoverflow.com/questions/41102060/typescript-extending-error-class
5174
+ // we don't need to check for Object.setPrototypeOf as in the answers because we are ES2017 now.
5175
+ // Also see https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
5176
+ // and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#custom_error_types
5177
+ const actualProto = new.target.prototype;
5178
+ Object.setPrototypeOf(this, actualProto);
5219
5179
  message = message || "UNKNOWN_ERROR";
5220
5180
  code = code || "UNKNOWN_ERROR_CODE";
5221
5181
  this.name = "ArcGISRequestError";
5222
5182
  this.message =
5223
- code === "UNKNOWN_ERROR_CODE" ? message : code + ": " + message;
5183
+ code === "UNKNOWN_ERROR_CODE" ? message : `${code}: ${message}`;
5224
5184
  this.originalMessage = message;
5225
5185
  this.code = code;
5226
5186
  this.response = response;
5227
5187
  this.url = url;
5228
5188
  this.options = options;
5229
5189
  }
5230
- return ArcGISRequestError;
5231
- }());
5232
- ArcGISRequestError.prototype = Object.create(Error.prototype);
5233
- ArcGISRequestError.prototype.constructor = ArcGISRequestError;
5190
+ }
5234
5191
 
5235
5192
  /* Copyright (c) 2017-2018 Environmental Systems Research Institute, Inc.
5236
5193
  * Apache-2.0 */
5237
- var NODEJS_DEFAULT_REFERER_HEADER = "@esri/arcgis-rest-js";
5238
- var DEFAULT_ARCGIS_REQUEST_OPTIONS = {
5239
- httpMethod: "POST",
5240
- params: {
5241
- f: "json",
5242
- },
5243
- };
5244
- var ArcGISAuthError = /** @class */ (function (_super) {
5245
- __extends(ArcGISAuthError, _super);
5194
+ /**
5195
+ * Method used internally to surface messages to developers.
5196
+ */
5197
+ function warn(message) {
5198
+ if (console && console.warn) {
5199
+ console.warn.apply(console, [message]);
5200
+ }
5201
+ }
5202
+
5203
+ function getFetch() {
5204
+ return Promise.resolve({
5205
+ fetch: globalThis.fetch,
5206
+ Headers: globalThis.Headers,
5207
+ Response: globalThis.Response,
5208
+ Request: globalThis.Request
5209
+ });
5210
+ }
5211
+
5212
+ /* Copyright (c) 2017-2018 Environmental Systems Research Institute, Inc.
5213
+ * Apache-2.0 */
5214
+ const NODEJS_DEFAULT_REFERER_HEADER = `@esri/arcgis-rest-js`;
5215
+ function getDefaultRequestOptions() {
5216
+ return (globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS || {
5217
+ httpMethod: "POST",
5218
+ params: {
5219
+ f: "json"
5220
+ }
5221
+ });
5222
+ }
5223
+ /**
5224
+ * This error is thrown when a request encounters an invalid token error. Requests that use {@linkcode ArcGISIdentityManager} or
5225
+ * {@linkcode ApplicationCredentialsManager} in the `authentication` option the authentication manager will automatically try to generate
5226
+ * a fresh token using either {@linkcode ArcGISIdentityManager.refreshCredentials} or
5227
+ * {@linkcode ApplicationCredentialsManager.refreshCredentials}. If the request with the new token fails you will receive an `ArcGISAuthError`
5228
+ * if refreshing the token fails you will receive an instance of {@linkcode ArcGISTokenRequestError}.
5229
+ *
5230
+ * ```js
5231
+ * request(someUrl, {
5232
+ * authentication: identityManager,
5233
+ * // some additional options...
5234
+ * }).catch(e => {
5235
+ * if(e.name === "ArcGISAuthError") {
5236
+ * console.log("Request with a new token failed you might want to have the user authorize again.")
5237
+ * }
5238
+ *
5239
+ * if(e.name === "ArcGISTokenRequestError") {
5240
+ * console.log("There was an error refreshing the token you might want to have the user authorize again.")
5241
+ * }
5242
+ * })
5243
+ * ```
5244
+ */
5245
+ class ArcGISAuthError extends ArcGISRequestError {
5246
5246
  /**
5247
5247
  * Create a new `ArcGISAuthError` object.
5248
5248
  *
@@ -5252,47 +5252,49 @@
5252
5252
  * @param url - The original url of the request
5253
5253
  * @param options - The original options of the request
5254
5254
  */
5255
- function ArcGISAuthError(message, code, response, url, options) {
5256
- if (message === void 0) { message = "AUTHENTICATION_ERROR"; }
5257
- if (code === void 0) { code = "AUTHENTICATION_ERROR_CODE"; }
5258
- var _this = _super.call(this, message, code, response, url, options) || this;
5259
- _this.name = "ArcGISAuthError";
5260
- _this.message =
5261
- code === "AUTHENTICATION_ERROR_CODE" ? message : code + ": " + message;
5262
- return _this;
5255
+ constructor(message = "AUTHENTICATION_ERROR", code = "AUTHENTICATION_ERROR_CODE", response, url, options) {
5256
+ super(message, code, response, url, options);
5257
+ this.name = "ArcGISAuthError";
5258
+ this.message =
5259
+ code === "AUTHENTICATION_ERROR_CODE" ? message : `${code}: ${message}`;
5260
+ // restore prototype chain, see https://stackoverflow.com/questions/41102060/typescript-extending-error-class
5261
+ // we don't need to check for Object.setPrototypeOf as in the answers because we are ES2017 now.
5262
+ // Also see https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
5263
+ // and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#custom_error_types
5264
+ const actualProto = new.target.prototype;
5265
+ Object.setPrototypeOf(this, actualProto);
5263
5266
  }
5264
- ArcGISAuthError.prototype.retry = function (getSession, retryLimit) {
5265
- var _this = this;
5266
- if (retryLimit === void 0) { retryLimit = 3; }
5267
- var tries = 0;
5268
- var retryRequest = function (resolve, reject) {
5269
- getSession(_this.url, _this.options)
5270
- .then(function (session) {
5271
- var newOptions = __assign(__assign({}, _this.options), { authentication: session });
5272
- tries = tries + 1;
5273
- return request(_this.url, newOptions);
5267
+ retry(getSession, retryLimit = 1) {
5268
+ let tries = 0;
5269
+ const retryRequest = (resolve, reject) => {
5270
+ tries = tries + 1;
5271
+ getSession(this.url, this.options)
5272
+ .then((session) => {
5273
+ const newOptions = Object.assign(Object.assign({}, this.options), { authentication: session });
5274
+ return internalRequest(this.url, newOptions);
5274
5275
  })
5275
- .then(function (response) {
5276
+ .then((response) => {
5276
5277
  resolve(response);
5277
5278
  })
5278
- .catch(function (e) {
5279
+ .catch((e) => {
5279
5280
  if (e.name === "ArcGISAuthError" && tries < retryLimit) {
5280
5281
  retryRequest(resolve, reject);
5281
5282
  }
5282
- else if (e.name === "ArcGISAuthError" && tries >= retryLimit) {
5283
- reject(_this);
5283
+ else if (e.name === this.name &&
5284
+ e.message === this.message &&
5285
+ tries >= retryLimit) {
5286
+ reject(this);
5284
5287
  }
5285
5288
  else {
5286
5289
  reject(e);
5287
5290
  }
5288
5291
  });
5289
5292
  };
5290
- return new Promise(function (resolve, reject) {
5293
+ return new Promise((resolve, reject) => {
5291
5294
  retryRequest(resolve, reject);
5292
5295
  });
5293
- };
5294
- return ArcGISAuthError;
5295
- }(ArcGISRequestError));
5296
+ }
5297
+ }
5296
5298
  /**
5297
5299
  * Checks for errors in a JSON response from the ArcGIS REST API. If there are no errors, it will return the `data` passed in. If there is an error, it will throw an `ArcGISRequestError` or `ArcGISAuthError`.
5298
5300
  *
@@ -5305,17 +5307,14 @@
5305
5307
  function checkForErrors(response, url, params, options, originalAuthError) {
5306
5308
  // this is an error message from billing.arcgis.com backend
5307
5309
  if (response.code >= 400) {
5308
- var message = response.message, code = response.code;
5310
+ const { message, code } = response;
5309
5311
  throw new ArcGISRequestError(message, code, response, url, options);
5310
5312
  }
5311
5313
  // error from ArcGIS Online or an ArcGIS Portal or server instance.
5312
5314
  if (response.error) {
5313
- var _a = response.error, message = _a.message, code = _a.code, messageCode = _a.messageCode;
5314
- var errorCode = messageCode || code || "UNKNOWN_ERROR_CODE";
5315
- if (code === 498 ||
5316
- code === 499 ||
5317
- messageCode === "GWM_0003" ||
5318
- (code === 400 && message === "Unable to generate token.")) {
5315
+ const { message, code, messageCode } = response.error;
5316
+ const errorCode = messageCode || code || "UNKNOWN_ERROR_CODE";
5317
+ if (code === 498 || code === 499) {
5319
5318
  if (originalAuthError) {
5320
5319
  throw originalAuthError;
5321
5320
  }
@@ -5327,8 +5326,8 @@
5327
5326
  }
5328
5327
  // error from a status check
5329
5328
  if (response.status === "failed" || response.status === "failure") {
5330
- var message = void 0;
5331
- var code = "UNKNOWN_ERROR_CODE";
5329
+ let message;
5330
+ let code = "UNKNOWN_ERROR_CODE";
5332
5331
  try {
5333
5332
  message = JSON.parse(response.statusMessage).message;
5334
5333
  code = JSON.parse(response.statusMessage).code;
@@ -5341,64 +5340,29 @@
5341
5340
  return response;
5342
5341
  }
5343
5342
  /**
5344
- * ```js
5345
- * import { request } from '@esri/arcgis-rest-request';
5346
- * //
5347
- * request('https://www.arcgis.com/sharing/rest')
5348
- * .then(response) // response.currentVersion === 5.2
5349
- * //
5350
- * request('https://www.arcgis.com/sharing/rest', {
5351
- * httpMethod: "GET"
5352
- * })
5353
- * //
5354
- * request('https://www.arcgis.com/sharing/rest/search', {
5355
- * params: { q: 'parks' }
5356
- * })
5357
- * .then(response) // response.total => 78379
5358
- * ```
5359
- * Generic method for making HTTP requests to ArcGIS REST API endpoints.
5343
+ * This is the internal implementation of `request` without the automatic retry behavior to prevent
5344
+ * infinite loops when a server continues to return invalid token errors.
5360
5345
  *
5361
5346
  * @param url - The URL of the ArcGIS REST API endpoint.
5362
5347
  * @param requestOptions - Options for the request, including parameters relevant to the endpoint.
5363
5348
  * @returns A Promise that will resolve with the data from the response.
5349
+ * @internal
5364
5350
  */
5365
- function request(url, requestOptions) {
5366
- if (requestOptions === void 0) { requestOptions = { params: { f: "json" } }; }
5367
- var options = __assign(__assign(__assign({ httpMethod: "POST" }, DEFAULT_ARCGIS_REQUEST_OPTIONS), requestOptions), {
5368
- params: __assign(__assign({}, DEFAULT_ARCGIS_REQUEST_OPTIONS.params), requestOptions.params),
5369
- headers: __assign(__assign({}, DEFAULT_ARCGIS_REQUEST_OPTIONS.headers), requestOptions.headers),
5351
+ function internalRequest(url, requestOptions) {
5352
+ const defaults = getDefaultRequestOptions();
5353
+ const options = Object.assign(Object.assign(Object.assign({ httpMethod: "POST" }, defaults), requestOptions), {
5354
+ params: Object.assign(Object.assign({}, defaults.params), requestOptions.params),
5355
+ headers: Object.assign(Object.assign({}, defaults.headers), requestOptions.headers)
5370
5356
  });
5371
- var missingGlobals = [];
5372
- var recommendedPackages = [];
5373
- // don't check for a global fetch if a custom implementation was passed through
5374
- if (!options.fetch && typeof fetch !== "undefined") {
5375
- options.fetch = fetch.bind(Function("return this")());
5376
- }
5377
- else {
5378
- missingGlobals.push("`fetch`");
5379
- recommendedPackages.push("`node-fetch`");
5380
- }
5381
- if (typeof Promise === "undefined") {
5382
- missingGlobals.push("`Promise`");
5383
- recommendedPackages.push("`es6-promise`");
5384
- }
5385
- if (typeof FormData === "undefined") {
5386
- missingGlobals.push("`FormData`");
5387
- recommendedPackages.push("`isomorphic-form-data`");
5388
- }
5389
- if (!options.fetch ||
5390
- typeof Promise === "undefined" ||
5391
- typeof FormData === "undefined") {
5392
- throw new Error("`arcgis-rest-request` requires a `fetch` implementation and global variables for `Promise` and `FormData` to be present in the global scope. You are missing " + missingGlobals.join(", ") + ". We recommend installing the " + recommendedPackages.join(", ") + " modules at the root of your application to add these to the global scope. See https://bit.ly/2KNwWaJ for more info.");
5393
- }
5394
- var httpMethod = options.httpMethod, authentication = options.authentication, rawResponse = options.rawResponse;
5395
- var params = __assign({ f: "json" }, options.params);
5396
- var originalAuthError = null;
5397
- var fetchOptions = {
5357
+ const { httpMethod, rawResponse } = options;
5358
+ const params = Object.assign({ f: "json" }, options.params);
5359
+ let originalAuthError = null;
5360
+ const fetchOptions = {
5398
5361
  method: httpMethod,
5362
+ signal: options.signal,
5399
5363
  /* ensures behavior mimics XMLHttpRequest.
5400
5364
  needed to support sending IWA cookies */
5401
- credentials: options.credentials || "same-origin",
5365
+ credentials: options.credentials || "same-origin"
5402
5366
  };
5403
5367
  // the /oauth2/platformSelf route will add X-Esri-Auth-Client-Id header
5404
5368
  // and that request needs to send cookies cross domain
@@ -5408,8 +5372,35 @@
5408
5372
  url.indexOf("/oauth2/platformSelf") > -1) {
5409
5373
  fetchOptions.credentials = "include";
5410
5374
  }
5375
+ let authentication;
5376
+ // Check to see if this is a raw token as a string and create a IAuthenticationManager like object for it.
5377
+ // Otherwise this just assumes that options.authentication is an IAuthenticationManager.
5378
+ if (typeof options.authentication === "string") {
5379
+ const rawToken = options.authentication;
5380
+ authentication = {
5381
+ portal: "https://www.arcgis.com/sharing/rest",
5382
+ getToken: () => {
5383
+ return Promise.resolve(rawToken);
5384
+ }
5385
+ };
5386
+ /* istanbul ignore else - we don't need to test NOT warning people */
5387
+ if (!options.authentication.startsWith("AAPK") &&
5388
+ !options.authentication.startsWith("AATK") && // doesn't look like an API Key
5389
+ !options.suppressWarnings && // user doesn't want to suppress warnings for this request
5390
+ !globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING // we haven't shown the user this warning yet
5391
+ ) {
5392
+ warn(`Using an oAuth 2.0 access token directly in the token option is discouraged. Consider using ArcGISIdentityManager or Application session. See https://esriurl.com/arcgis-rest-js-direct-token-warning for more information.`);
5393
+ globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING = true;
5394
+ }
5395
+ }
5396
+ else {
5397
+ authentication = options.authentication;
5398
+ }
5399
+ // for errors in GET requests we want the URL passed to the error to be the URL before
5400
+ // query params are applied.
5401
+ const originalUrl = url;
5411
5402
  return (authentication
5412
- ? authentication.getToken(url, { fetch: options.fetch }).catch(function (err) {
5403
+ ? authentication.getToken(url).catch((err) => {
5413
5404
  /**
5414
5405
  * append original request url and requestOptions
5415
5406
  * to the error thrown by getToken()
@@ -5426,7 +5417,7 @@
5426
5417
  return Promise.resolve("");
5427
5418
  })
5428
5419
  : Promise.resolve(""))
5429
- .then(function (token) {
5420
+ .then((token) => {
5430
5421
  if (token.length) {
5431
5422
  params.token = token;
5432
5423
  }
@@ -5434,7 +5425,7 @@
5434
5425
  fetchOptions.credentials = authentication.getDomainCredentials(url);
5435
5426
  }
5436
5427
  // Custom headers to add to request. IRequestOptions.headers with merge over requestHeaders.
5437
- var requestHeaders = {};
5428
+ const requestHeaders = {};
5438
5429
  if (fetchOptions.method === "GET") {
5439
5430
  // Prevents token from being passed in query params when hideToken option is used.
5440
5431
  /* istanbul ignore if - window is always defined in a browser. Test case is covered by Jasmine in node test */
@@ -5442,13 +5433,13 @@
5442
5433
  options.hideToken &&
5443
5434
  // Sharing API does not support preflight check required by modern browsers https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
5444
5435
  typeof window === "undefined") {
5445
- requestHeaders["X-Esri-Authorization"] = "Bearer " + params.token;
5436
+ requestHeaders["X-Esri-Authorization"] = `Bearer ${params.token}`;
5446
5437
  delete params.token;
5447
5438
  }
5448
5439
  // encode the parameters into the query string
5449
- var queryParams = encodeQueryString(params);
5440
+ const queryParams = encodeQueryString(params);
5450
5441
  // dont append a '?' unless parameters are actually present
5451
- var urlWithQueryString = queryParams === "" ? url : url + "?" + encodeQueryString(params);
5442
+ const urlWithQueryString = queryParams === "" ? url : url + "?" + encodeQueryString(params);
5452
5443
  if (
5453
5444
  // This would exceed the maximum length for URLs specified by the consumer and requires POST
5454
5445
  (options.maxUrlLength &&
@@ -5473,14 +5464,18 @@
5473
5464
  /* updateResources currently requires FormData even when the input parameters dont warrant it.
5474
5465
  https://developers.arcgis.com/rest/users-groups-and-items/update-resources.htm
5475
5466
  see https://github.com/Esri/arcgis-rest-js/pull/500 for more info. */
5476
- var forceFormData = new RegExp("/items/.+/updateResources").test(url);
5467
+ const forceFormData = new RegExp("/items/.+/updateResources").test(url);
5477
5468
  if (fetchOptions.method === "POST") {
5478
5469
  fetchOptions.body = encodeFormData(params, forceFormData);
5479
5470
  }
5480
5471
  // Mixin headers from request options
5481
- fetchOptions.headers = __assign(__assign({}, requestHeaders), options.headers);
5472
+ fetchOptions.headers = Object.assign(Object.assign({}, requestHeaders), options.headers);
5473
+ // This should have the same conditional for Node JS as ArcGISIdentityManager.refreshWithUsernameAndPassword()
5474
+ // to ensure that generated tokens have the same referer when used in Node with a username and password.
5482
5475
  /* istanbul ignore next - karma reports coverage on browser tests only */
5483
- if (typeof window === "undefined" && !fetchOptions.headers.referer) {
5476
+ if ((typeof window === "undefined" ||
5477
+ (window && typeof window.document === "undefined")) &&
5478
+ !fetchOptions.headers.referer) {
5484
5479
  fetchOptions.headers.referer = NODEJS_DEFAULT_REFERER_HEADER;
5485
5480
  }
5486
5481
  /* istanbul ignore else blob responses are difficult to make cross platform we will just have to trust the isomorphic fetch will do its job */
@@ -5488,13 +5483,40 @@
5488
5483
  fetchOptions.headers["Content-Type"] =
5489
5484
  "application/x-www-form-urlencoded";
5490
5485
  }
5491
- return options.fetch(url, fetchOptions);
5486
+ /**
5487
+ * Check for a global fetch first and use it if available. This allows us to use the default
5488
+ * configuration of fetch-mock in tests.
5489
+ */
5490
+ /* istanbul ignore next coverage is based on browser code and we don't test for the absence of global fetch so we can skip the else here. */
5491
+ return globalThis.fetch
5492
+ ? globalThis.fetch(url, fetchOptions)
5493
+ : getFetch().then(({ fetch }) => {
5494
+ return fetch(url, fetchOptions);
5495
+ });
5492
5496
  })
5493
- .then(function (response) {
5497
+ .then((response) => {
5498
+ // the request got back an error status code (4xx, 5xx)
5494
5499
  if (!response.ok) {
5495
- // server responded w/ an actual error (404, 500, etc)
5496
- var status_1 = response.status, statusText = response.statusText;
5497
- throw new ArcGISRequestError(statusText, "HTTP " + status_1, response, url, options);
5500
+ // we need to determine if the server returned a JSON body with more details.
5501
+ // this is the format used by newer services such as the Places and Style service.
5502
+ return response
5503
+ .json()
5504
+ .then((jsonError) => {
5505
+ // The body can be parsed as JSON
5506
+ const { status, statusText } = response;
5507
+ const { message, details } = jsonError.error;
5508
+ const formattedMessage = `${message}. ${details ? details.join(" ") : ""}`.trim();
5509
+ throw new ArcGISRequestError(formattedMessage, `HTTP ${status} ${statusText}`, jsonError, url, options);
5510
+ })
5511
+ .catch((e) => {
5512
+ // if we already were about to format this as an ArcGISRequestError throw that error
5513
+ if (e.name === "ArcGISRequestError") {
5514
+ throw e;
5515
+ }
5516
+ // server responded w/ an actual error (404, 500, etc) but we could not parse it as JSON
5517
+ const { status, statusText } = response;
5518
+ throw new ArcGISRequestError(statusText, `HTTP ${status}`, response, url, options);
5519
+ });
5498
5520
  }
5499
5521
  if (rawResponse) {
5500
5522
  return response;
@@ -5513,21 +5535,23 @@
5513
5535
  return response.blob();
5514
5536
  }
5515
5537
  })
5516
- .then(function (data) {
5538
+ .then((data) => {
5539
+ // Check for an error in the JSON body of a successful response.
5540
+ // Most ArcGIS Server services will return a successful status code but include an error in the response body.
5517
5541
  if ((params.f === "json" || params.f === "geojson") && !rawResponse) {
5518
- var response = checkForErrors(data, url, params, options, originalAuthError);
5542
+ const response = checkForErrors(data, originalUrl, params, options, originalAuthError);
5519
5543
  if (originalAuthError) {
5520
5544
  /* If the request was made to an unfederated service that
5521
5545
  didn't require authentication, add the base url and a dummy token
5522
5546
  to the list of trusted servers to avoid another federation check
5523
5547
  in the event of a repeat request */
5524
- var truncatedUrl = url
5548
+ const truncatedUrl = url
5525
5549
  .toLowerCase()
5526
5550
  .split(/\/rest(\/admin)?\/services\//)[0];
5527
5551
  options.authentication.federatedServers[truncatedUrl] = {
5528
5552
  token: [],
5529
5553
  // default to 24 hours
5530
- expires: new Date(Date.now() + 86400 * 1000),
5554
+ expires: new Date(Date.now() + 86400 * 1000)
5531
5555
  };
5532
5556
  originalAuthError = null;
5533
5557
  }
@@ -5538,6 +5562,45 @@
5538
5562
  }
5539
5563
  });
5540
5564
  }
5565
+ /**
5566
+ * Generic method for making HTTP requests to ArcGIS REST API endpoints.
5567
+ *
5568
+ * ```js
5569
+ * import { request } from '@esri/arcgis-rest-request';
5570
+ *
5571
+ * request('https://www.arcgis.com/sharing/rest')
5572
+ * .then(response) // response.currentVersion === 5.2
5573
+ *
5574
+ * request('https://www.arcgis.com/sharing/rest', {
5575
+ * httpMethod: "GET"
5576
+ * })
5577
+ *
5578
+ * request('https://www.arcgis.com/sharing/rest/search', {
5579
+ * params: { q: 'parks' }
5580
+ * })
5581
+ * .then(response) // response.total => 78379
5582
+ * ```
5583
+ *
5584
+ * @param url - The URL of the ArcGIS REST API endpoint.
5585
+ * @param requestOptions - Options for the request, including parameters relevant to the endpoint.
5586
+ * @returns A Promise that will resolve with the data from the response.
5587
+ */
5588
+ function request(url, requestOptions = { params: { f: "json" } }) {
5589
+ return internalRequest(url, requestOptions).catch((e) => {
5590
+ if (e instanceof ArcGISAuthError &&
5591
+ requestOptions.authentication &&
5592
+ typeof requestOptions.authentication !== "string" &&
5593
+ requestOptions.authentication.canRefresh &&
5594
+ requestOptions.authentication.refreshCredentials) {
5595
+ return e.retry(() => {
5596
+ return requestOptions.authentication.refreshCredentials();
5597
+ }, 1);
5598
+ }
5599
+ else {
5600
+ return Promise.reject(e);
5601
+ }
5602
+ });
5603
+ }
5541
5604
 
5542
5605
  /* Copyright (c) 2018 Environmental Systems Research Institute, Inc.
5543
5606
  * Apache-2.0 */
@@ -5568,14 +5631,14 @@
5568
5631
  * @param requestOptions - Request options that may have authentication manager
5569
5632
  * @returns Portal url to be used in API requests
5570
5633
  */
5571
- function getPortalUrl(requestOptions) {
5572
- if (requestOptions === void 0) { requestOptions = {}; }
5634
+ function getPortalUrl(requestOptions = {}) {
5573
5635
  // use portal in options if specified
5574
5636
  if (requestOptions.portal) {
5575
5637
  return cleanUrl(requestOptions.portal);
5576
5638
  }
5577
5639
  // if auth was passed, use that portal
5578
- if (requestOptions.authentication) {
5640
+ if (requestOptions.authentication &&
5641
+ typeof requestOptions.authentication !== "string") {
5579
5642
  // the portal url is already scrubbed in the auth package
5580
5643
  return requestOptions.authentication.portal;
5581
5644
  }
@@ -5585,27 +5648,6 @@
5585
5648
 
5586
5649
  /* Copyright (c) 2017-2018 Environmental Systems Research Institute, Inc.
5587
5650
  * Apache-2.0 */
5588
- /**
5589
- * Serialize an item and its data into a json format accepted by the Portal API for create and update operations
5590
- *
5591
- * @param item Item to be serialized
5592
- * @returns a formatted json object to be sent to Portal
5593
- */
5594
- function serializeItem(item) {
5595
- // create a clone so we're not messing with the original
5596
- var clone = JSON.parse(JSON.stringify(item));
5597
- // binary data needs POSTed as a `file`
5598
- // JSON object literals should be passed as `text`.
5599
- if (clone.data) {
5600
- (typeof Blob !== "undefined" && item.data instanceof Blob) ||
5601
- // Node.js doesn't implement Blob
5602
- item.data.constructor.name === "ReadStream"
5603
- ? (clone.file = item.data)
5604
- : (clone.text = item.data);
5605
- delete clone.data;
5606
- }
5607
- return clone;
5608
- }
5609
5651
  /**
5610
5652
  * `requestOptions.owner` is given priority, `requestOptions.item.owner` will be checked next. If neither are present, `authentication.getUserName()` will be used instead.
5611
5653
  */
@@ -5647,9 +5689,11 @@
5647
5689
  /* Copyright (c) 2018 Environmental Systems Research Institute, Inc.
5648
5690
  * Apache-2.0 */
5649
5691
  /**
5692
+ * Update an Item. See the [REST Documentation](https://developers.arcgis.com/rest/users-groups-and-items/update-item.htm) for more information.
5693
+ *
5650
5694
  * ```js
5651
5695
  * import { updateItem } from "@esri/arcgis-rest-portal";
5652
- * //
5696
+ *
5653
5697
  * updateItem({
5654
5698
  * item: {
5655
5699
  * id: "3ef",
@@ -5659,18 +5703,17 @@
5659
5703
  * })
5660
5704
  * .then(response)
5661
5705
  * ```
5662
- * Update an Item. See the [REST Documentation](https://developers.arcgis.com/rest/users-groups-and-items/update-item.htm) for more information.
5663
5706
  *
5664
5707
  * @param requestOptions - Options for the request.
5665
5708
  * @returns A Promise that updates an item.
5666
5709
  */
5667
5710
  function updateItem(requestOptions) {
5668
- return determineOwner(requestOptions).then(function (owner) {
5669
- var url = requestOptions.folderId
5670
- ? getPortalUrl(requestOptions) + "/content/users/" + owner + "/" + requestOptions.folderId + "/items/" + requestOptions.item.id + "/update"
5671
- : getPortalUrl(requestOptions) + "/content/users/" + owner + "/items/" + requestOptions.item.id + "/update";
5711
+ return determineOwner(requestOptions).then((owner) => {
5712
+ const url = requestOptions.folderId
5713
+ ? `${getPortalUrl(requestOptions)}/content/users/${owner}/${requestOptions.folderId}/items/${requestOptions.item.id}/update`
5714
+ : `${getPortalUrl(requestOptions)}/content/users/${owner}/items/${requestOptions.item.id}/update`;
5672
5715
  // serialize the item into something Portal will accept
5673
- requestOptions.params = __assign$1(__assign$1({}, requestOptions.params), serializeItem(requestOptions.item));
5716
+ requestOptions.params = Object.assign(Object.assign({}, requestOptions.params), requestOptions.item);
5674
5717
  // convert extent, if present, into a string from bbox
5675
5718
  // processParams was previously doing this sort of work,
5676
5719
  // however now we need to let array of arrays through
@@ -5701,9 +5744,9 @@
5701
5744
  * @returns A Promise that will resolve with the data from the response.
5702
5745
  */
5703
5746
  function getItem(id, requestOptions) {
5704
- var url = getItemBaseUrl(id, requestOptions);
5747
+ const url = getItemBaseUrl(id, requestOptions);
5705
5748
  // default to a GET request
5706
- var options = __assign$1({ httpMethod: "GET" }, requestOptions);
5749
+ const options = Object.assign({ httpMethod: "GET" }, requestOptions);
5707
5750
  return request(url, options);
5708
5751
  }
5709
5752
  /**
@@ -5712,11 +5755,11 @@
5712
5755
  * @param portalUrlOrRequestOptions a portal URL or request options
5713
5756
  * @returns URL to the item's REST end point, defaults to `https://www.arcgis.com/sharing/rest/content/items/{id}`
5714
5757
  */
5715
- var getItemBaseUrl = function (id, portalUrlOrRequestOptions) {
5716
- var portalUrl = typeof portalUrlOrRequestOptions === "string"
5758
+ const getItemBaseUrl = (id, portalUrlOrRequestOptions) => {
5759
+ const portalUrl = typeof portalUrlOrRequestOptions === "string"
5717
5760
  ? portalUrlOrRequestOptions
5718
5761
  : getPortalUrl(portalUrlOrRequestOptions);
5719
- return portalUrl + "/content/items/" + id;
5762
+ return `${portalUrl}/content/items/${id}`;
5720
5763
  };
5721
5764
 
5722
5765
  function buildAccessProperties(username, currentAccessProperties, accessChangeset) {