Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@esri/arcgis-rest-request

Package Overview
Dependencies
Maintainers
6
Versions
130
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@esri/arcgis-rest-request - npm Package Compare versions

Comparing version 4.0.4 to 4.1.0

dist/cjs/job.js

6

dist/bundled/request.esm.min.js
/* @preserve
* @esri/arcgis-rest-request - v4.0.3 - Apache-2.0
* @esri/arcgis-rest-request - v4.0.4 - Apache-2.0
* Copyright (c) 2017-2022 Esri, Inc.
* Thu Sep 15 2022 20:30:17 GMT+0000 (Coordinated Universal Time)
* Wed Sep 28 2022 19:56:36 GMT+0000 (Coordinated Universal Time)
*/
function e(e){return Object.keys(e).some((t=>{let r=e[t];if(!r)return!1;r&&r.toParam&&(r=r.toParam());switch(r.constructor.name){case"Array":case"Object":case"Date":case"Function":case"Boolean":case"String":case"Number":return!1;default:return!0}}))}function t(e){const t={};return Object.keys(e).forEach((r=>{var s,n;let o=e[r];if(o&&o.toParam&&(o=o.toParam()),!o&&0!==o&&"boolean"!=typeof o&&"string"!=typeof o)return;let i;switch(o.constructor.name){case"Array":const e=null===(n=null===(s=o[0])||void 0===s?void 0:s.constructor)||void 0===n?void 0:n.name;i="Array"===e?o:"Object"===e?JSON.stringify(o):o.join(",");break;case"Object":i=JSON.stringify(o);break;case"Date":i=o.valueOf();break;case"Function":i=null;break;case"Boolean":i=o+"";break;default:i=o}(i||0===i||"string"==typeof i||Array.isArray(i))&&(t[r]=i)})),t}function r(e,t){return Array.isArray(t)&&t[0]&&Array.isArray(t[0])?t.map((t=>r(e,t))).join("&"):encodeURIComponent(e)+"="+encodeURIComponent(t)}function s(e){const s=t(e);return Object.keys(s).map((e=>r(e,s[e]))).join("&")}const n=globalThis.FormData,o=globalThis.File,i=globalThis.Blob;function a(r,o){const i=e(r)||o,a=t(r);if(i){const e=new n;return Object.keys(a).forEach((t=>{if("undefined"!=typeof Blob&&a[t]instanceof Blob){const r=a.fileName||a[t].name||t;e.append(t,a[t],r)}else e.append(t,a[t])})),e}return s(r)}class h extends Error{constructor(e,t,r,s,n){super(e);const o=new.target.prototype;Object.setPrototypeOf(this,o),e=e||"UNKNOWN_ERROR",t=t||"UNKNOWN_ERROR_CODE",this.name="ArcGISRequestError",this.message="UNKNOWN_ERROR_CODE"===t?e:`${t}: ${e}`,this.originalMessage=e,this.code=t,this.response=r,this.url=s,this.options=n}}function c(e){console&&console.warn&&console.warn.apply(console,[e])}function l(){return Promise.resolve({fetch:globalThis.fetch,Headers:globalThis.Headers,Response:globalThis.Response,Request:globalThis.Request})}const u="@esri/arcgis-rest-js";function d(e,t){e.authentication&&!t&&c("You should not set `authentication` as a default in a shared environment such as a web server which will process multiple users requests. You can call `setDefaultRequestOptions` with `true` as a second argument to disable this warning."),globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS=e}function p(){return globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS||{httpMethod:"POST",params:{f:"json"}}}class g extends h{constructor(e="AUTHENTICATION_ERROR",t="AUTHENTICATION_ERROR_CODE",r,s,n){super(e,t,r,s,n),this.name="ArcGISAuthError",this.message="AUTHENTICATION_ERROR_CODE"===t?e:`${t}: ${e}`;const o=new.target.prototype;Object.setPrototypeOf(this,o)}retry(e,t=1){let r=0;const s=(n,o)=>{r+=1,e(this.url,this.options).then((e=>{const t=Object.assign(Object.assign({},this.options),{authentication:e});return m(this.url,t)})).then((e=>{n(e)})).catch((e=>{"ArcGISAuthError"===e.name&&r<t?s(n,o):e.name===this.name&&e.message===this.message&&r>=t?o(this):o(e)}))};return new Promise(((e,t)=>{s(e,t)}))}}function f(e,t,r,s,n){if(e.code>=400){const{message:r,code:n}=e;throw new h(r,n,e,t,s)}if(e.error){const{message:r,code:o,messageCode:i}=e.error,a=i||o||"UNKNOWN_ERROR_CODE";if(498===o||499===o)throw n||new g(r,a,e,t,s);throw new h(r,a,e,t,s)}if("failed"===e.status||"failure"===e.status){let r,n="UNKNOWN_ERROR_CODE";try{r=JSON.parse(e.statusMessage).message,n=JSON.parse(e.statusMessage).code}catch(t){r=e.statusMessage||e.message}throw new h(r,n,e,t,s)}return e}function m(t,r){const n=p(),o=Object.assign(Object.assign(Object.assign({httpMethod:"POST"},n),r),{params:Object.assign(Object.assign({},n.params),r.params),headers:Object.assign(Object.assign({},n.headers),r.headers)}),{httpMethod:i,rawResponse:u}=o,d=Object.assign({f:"json"},o.params);let g=null;const m={method:i,signal:o.signal,credentials:o.credentials||"same-origin"};let E;if(o.headers&&o.headers["X-Esri-Auth-Client-Id"]&&t.indexOf("/oauth2/platformSelf")>-1&&(m.credentials="include"),"string"==typeof o.authentication){const e=o.authentication;E={portal:"https://www.arcgis.com/sharing/rest",getToken:()=>Promise.resolve(e)},o.authentication.startsWith("AAPK")||o.suppressWarnings||globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING||(c("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."),globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING=!0)}else E=o.authentication;const w=t;return(E?E.getToken(t).catch((e=>(e.url=t,e.options=o,g=e,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(d.token=r),E&&E.getDomainCredentials&&(m.credentials=E.getDomainCredentials(t));const n={};if("GET"===m.method){d.token&&o.hideToken&&"undefined"==typeof window&&(n["X-Esri-Authorization"]=`Bearer ${d.token}`,delete d.token);const e=""===s(d)?t:t+"?"+s(d);o.maxUrlLength&&e.length>o.maxUrlLength||d.token&&o.hideToken?(m.method="POST",r.length&&o.hideToken&&(d.token=r,delete n["X-Esri-Authorization"])):t=e}const i=new RegExp("/items/.+/updateResources").test(t);return"POST"===m.method&&(m.body=a(d,i)),m.headers=Object.assign(Object.assign({},n),o.headers),("undefined"==typeof window||window&&void 0===window.document)&&!m.headers.referer&&(m.headers.referer="@esri/arcgis-rest-js"),e(d)||i||(m.headers["Content-Type"]="application/x-www-form-urlencoded"),globalThis.fetch?globalThis.fetch(t,m):l().then((({fetch:e})=>e(t,m)))})).then((e=>{if(!e.ok){const{status:r,statusText:s}=e;throw new h(s,`HTTP ${r}`,e,t,o)}if(u)return e;switch(d.f){case"json":case"geojson":return e.json();case"html":case"text":return e.text();default:return e.blob()}})).then((e=>{if("json"!==d.f&&"geojson"!==d.f||u)return e;{const r=f(e,w,0,o,g);if(g){const e=t.toLowerCase().split(/\/rest(\/admin)?\/services\//)[0];o.authentication.federatedServers[e]={token:[],expires:new Date(Date.now()+864e5)},g=null}return r}}))}function E(e,t={params:{f:"json"}}){return m(e,t).catch((e=>e instanceof g&&t.authentication&&"string"!=typeof t.authentication&&t.authentication.canRefresh&&t.authentication.refreshCredentials?e.retry((()=>t.authentication.refreshCredentials()),1):Promise.reject(e)))}function w(e,t,r){const s=Object.assign(Object.assign({params:{}},r),e);return s.params=t.reduce(((t,r)=>((e[r]||"boolean"==typeof e[r]||"number"==typeof e[r]&&0===e[r])&&(t[r]=e[r]),t)),s.params),["params","httpMethod","rawResponse","authentication","portal","fetch","maxUrlLength","headers"].reduce(((e,t)=>(s[t]&&(e[t]=s[t]),e)),{})}var k,_;!function(e){e.TOKEN_REFRESH_FAILED="TOKEN_REFRESH_FAILED",e.GENERATE_TOKEN_FOR_SERVER_FAILED="GENERATE_TOKEN_FOR_SERVER_FAILED",e.REFRESH_TOKEN_EXCHANGE_FAILED="REFRESH_TOKEN_EXCHANGE_FAILED",e.NOT_FEDERATED="NOT_FEDERATED",e.UNKNOWN_ERROR_CODE="UNKNOWN_ERROR_CODE"}(k||(k={}));class T extends Error{constructor(e="UNKNOWN_ERROR",t=k.UNKNOWN_ERROR_CODE,r,s,n){super(e);const o=new.target.prototype;Object.setPrototypeOf(this,o),this.name="ArcGISTokenRequestError",this.message=`${t}: ${e}`,this.originalMessage=e,this.code=t,this.response=r,this.url=s,this.options=n}}class R extends Error{constructor(){super("The user has denied your authorization request.");const e=new.target.prototype;Object.setPrototypeOf(this,e),this.name="ArcGISAccessDeniedError"}}function O(e){return"string"!=typeof e||"/"===(e=e.trim())[e.length-1]&&(e=e.slice(0,-1)),e}function S(e){const[t,r]=e.split("=");return{key:decodeURIComponent(t),value:decodeURIComponent(r)}}function A(e){return!e||e.length<=0?{}:e.replace(/^#/,"").replace(/^\?/,"").split("&").reduce(((e,t)=>{const{key:r,value:s}=S(t);return e[r]=s,e}),{})}!function(e){e.ArcGISRequestError="ArcGISRequestError",e.ArcGISAuthError="ArcGISAuthError",e.ArcGISAccessDeniedError="ArcGISAccessDeniedError",e.ArcGISTokenRequestError="ArcGISTokenRequestError"}(_||(_={}));function I(e,t){const r=t;return r.rawResponse=!1,E(e,r).then((e=>{const t={token:e.access_token,username:e.username,expires:new Date(Date.now()+1e3*e.expires_in-3e5),ssl:!0===e.ssl};return e.refresh_token&&(t.refreshToken=e.refresh_token),e.refresh_token_expires_in&&(t.refreshTokenExpires=new Date(Date.now()+1e3*e.refresh_token_expires_in-3e5)),t}))}class v{constructor(e){this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.token=e.token,this.expires=e.expires,this.portal=e.portal||"https://www.arcgis.com/sharing/rest",this.duration=e.duration||7200}static fromCredentials(e){return new v(e)}getToken(e,t){return this.token&&this.expires&&this.expires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequest||(this._pendingTokenRequest=this.refreshToken(t)),this._pendingTokenRequest)}refreshToken(e){const t=Object.assign({params:{client_id:this.clientId,client_secret:this.clientSecret,grant_type:"client_credentials",expiration:this.duration}},e);return I(`${this.portal}/oauth2/token/`,t).then((e=>(this._pendingTokenRequest=null,this.token=e.token,this.expires=e.expires,e.token))).catch((e=>{throw new T(e.message,k.TOKEN_REFRESH_FAILED,e.response,e.url,e.options)}))}refreshCredentials(){return this.refreshToken().then((()=>this))}}function x(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new v(e)}class y{constructor(e){this.portal="https://www.arcgis.com/sharing/rest",this.key=e.key}static fromKey(e){return new y({key:e})}getToken(e){return Promise.resolve(this.key)}}function D(e){return console.log("DEPRECATED:, 'ApiKey' is deprecated. Use 'ApiKeyManager' instead."),new y(e)}const U=/^https?:\/\/(\S+)\.arcgis\.com.+/;function b(e){return U.test(e)}function C(e){if(!U.test(e))return e;switch(N(e)){case"dev":return"https://devext.arcgis.com/sharing/rest";case"qa":return"https://qaext.arcgis.com/sharing/rest";default:return"https://www.arcgis.com/sharing/rest"}}function N(e){if(!U.test(e))return null;const t=e.match(U)[1].split(".").pop();return t.includes("dev")?"dev":t.includes("qa")?"qa":"production"}function P(e,t){const r=O(C(t)).replace(/https?:\/\//,""),s=O(e).replace(/https?:\/\//,"");return new RegExp(s,"i").test(r)}function j(e,t){const r=b(e),s=b(t),n=N(e),o=N(t);return!(!r||!s||n!==o)}function F(e,t,r="https://www.arcgis.com/sharing/rest"){return E(`${r}/oauth2/validateAppAccess`,{method:"POST",params:{f:"json",client_id:t,token:e}})}function $(e){const t=`${O(e.portal||"https://www.arcgis.com/sharing/rest")}/oauth2/revokeToken/`,r=e.token,s=e.clientId;delete e.portal,delete e.clientId,delete e.token;const n=Object.assign(Object.assign({},e),{httpMethod:"POST",params:{client_id:s,auth_token:r}});return E(t,n).then((e=>{if(!e.success)throw new h("Unable to revoke token",500,e,t,n);return e}))}function G(e,t=window){return!t&&window&&(t=window),t.btoa(String.fromCharCode.apply(null,e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function q(e){!e&&window&&(e=window);return G(e.crypto.getRandomValues(new Uint8Array(32)))}class M{constructor(e){if(this.clientId=e.clientId,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this._username=e.username,this.password=e.password,this._token=e.token,this._tokenExpires=e.tokenExpires,this.portal=e.portal?O(e.portal):"https://www.arcgis.com/sharing/rest",this.ssl=e.ssl,this.provider=e.provider||"arcgis",this.tokenDuration=e.tokenDuration||20160,this.redirectUri=e.redirectUri,this.server=e.server,this.federatedServers={},this.trustedDomains=[],e.server){const t=this.getServerRootUrl(e.server);this.federatedServers[t]={token:e.token,expires:e.tokenExpires}}this._pendingTokenRequests={}}get token(){return this._token}get tokenExpires(){return this._tokenExpires}get refreshToken(){return this._refreshToken}get refreshTokenExpires(){return this._refreshTokenExpires}get username(){return this._username?this._username:this._user&&this._user.username?this._user.username:void 0}get canRefresh(){return!(!this.username||!this.password)||!!(this.clientId&&this.refreshToken&&this.redirectUri)}static beginOAuth2(e,t){!t&&window&&(t=window);const{portal:r,provider:n,clientId:o,expiration:i,redirectUri:a,popup:h,popupWindowFeatures:c,locale:l,params:u,style:d,pkce:p,state:f}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",provider:"arcgis",expiration:20160,popup:!0,popupWindowFeatures:"height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes",locale:"",style:"",pkce:!0},e),m=f||q(t),E=`ARCGIS_REST_JS_AUTH_STATE_${o}`;t.localStorage.setItem(E,m);let w=`${O(r)}/oauth2/authorize`;const k={client_id:o,response_type:p?"code":"token",expiration:i,redirect_uri:a,state:JSON.stringify({id:m,originalUrl:t.location.href}),locale:l,style:d};let _;if("arcgis"!==n&&(w=`${O(r)}/oauth2/social/authorize`,k.socialLoginProviderName=n,k.autoAccountCreateForSocial=!0),p){const e=q(t),r=`ARCGIS_REST_JS_CODE_VERIFIER_${o}`;t.localStorage.setItem(r,e),_=function(e,t=window){if(!t&&window&&(t=window),e&&t.isSecureContext&&t.crypto&&t.crypto.subtle){const r=(new t.TextEncoder).encode(e);return t.crypto.subtle.digest("SHA-256",r).then((e=>G(new Uint8Array(e),t)))}return Promise.resolve(null)}(e,t).then((function(t){k.code_challenge_method=t?"S256":"plain",k.code_challenge=t||e}))}else _=Promise.resolve();return _.then((()=>(w=`${w}?${s(k)}`,u&&(w=`${w}&${s(u)}`),h?new Promise(((e,s)=>{t.addEventListener(`arcgis-rest-js-popup-auth-${o}`,(t=>{if("access_denied"===t.detail.error){const e=new R;return s(e),e}if(t.detail.errorMessage){const e=new g(t.detail.errorMessage,t.detail.error);return s(e),e}e(new M({clientId:o,portal:r,ssl:t.detail.ssl,token:t.detail.token,tokenExpires:t.detail.expires,username:t.detail.username,refreshToken:t.detail.refreshToken,refreshTokenExpires:t.detail.refreshTokenExpires,redirectUri:a}))}),{once:!0}),t.open(w,"oauth-window",c),t.dispatchEvent(new CustomEvent("arcgis-rest-js-popup-auth-start"))})):void(t.location.href=w))))}static completeOAuth2(e,t){!t&&window&&(t=window);const{portal:r,clientId:s,popup:n,pkce:o,redirectUri:i}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",popup:!0,pkce:!0},e),a=`ARCGIS_REST_JS_AUTH_STATE_${s}`,h=t.localStorage.getItem(a),c=A(o?t.location.search.replace(/^\?/,""):t.location.hash.replace(/^#/,"")),l=c&&c.state?JSON.parse(c.state):void 0;function u(e,r,o){return t.localStorage.removeItem(a),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:{error:r,errorMessage:e}})),void t.close()):(o&&t.history.replaceState(t.history.state,"",o),"access_denied"===r?Promise.reject(new R):Promise.reject(new g(e,r)))}function d(e,o){return t.localStorage.removeItem(a),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:Object.assign({},e)})),void t.close()):(t.history.replaceState(t.history.state,"",o),new M({clientId:s,portal:r,ssl:e.ssl,token:e.token,tokenExpires:e.expires,username:e.username,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,redirectUri:i||location.href.replace(location.search,"")}))}if(!h||!l)return u("No authentication state was found, call `ArcGISIdentityManager.beginOAuth2(...)` to start the authentication process.","no-auth-state");if(l.id!==h)return u("Saved client state did not match server sent state.","mismatched-auth-state");if(c.error){const e=c.error;return u(c.error_description||"Unknown error",e,l.originalUrl)}if(o&&c.code){const e=O(`${r}/oauth2/token/`),n=`ARCGIS_REST_JS_CODE_VERIFIER_${s}`,o=t.localStorage.getItem(n);return t.localStorage.removeItem(n),I(e,{httpMethod:"POST",params:{client_id:s,code_verifier:o,grant_type:"authorization_code",redirect_uri:i||location.href.replace(location.search,""),code:c.code}}).then((e=>d(Object.assign(Object.assign({},e),l),l.originalUrl))).catch((e=>u(e.originalMessage,e.code,l.originalUrl)))}return!o&&c.access_token?Promise.resolve(d(Object.assign({token:c.access_token,expires:new Date(Date.now()+1e3*parseInt(c.expires_in,10)),ssl:"true"===c.ssl,username:c.username},l),l.originalUrl)):u("Unknown error","oauth-error",l.originalUrl)}static fromParent(e,t){let r;return!t&&window&&(t=window),new Promise(((s,n)=>{r=e=>{if(e.source===t.parent&&e.data)try{return s(M.parentMessageHandler(e))}catch(e){return n(e)}},t.addEventListener("message",r,!1),t.parent.postMessage({type:"arcgis:auth:requestCredential"},e)})).then((e=>(t.removeEventListener("message",r,!1),e)))}static authorize(e,t){const{portal:r,clientId:n,expiration:o,redirectUri:i,state:a}=Object.assign({portal:"https://arcgis.com/sharing/rest",expiration:20160},e),h={client_id:n,expiration:o,response_type:"code",redirect_uri:i};a&&(h.state=a);const c=`${r}/oauth2/authorize?${s(h)}`;t.writeHead(301,{Location:c}),t.end()}static exchangeAuthorizationCode(e,t){const{portal:r,clientId:s,redirectUri:n}=Object.assign({portal:"https://www.arcgis.com/sharing/rest"},e);return I(`${r}/oauth2/token`,{params:{grant_type:"authorization_code",client_id:s,redirect_uri:n,code:t}}).then((e=>new M({clientId:s,portal:r,ssl:e.ssl,redirectUri:n,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,token:e.token,tokenExpires:e.expires,username:e.username}))).catch((e=>{throw new T(e.message,k.REFRESH_TOKEN_EXCHANGE_FAILED,e.response,e.url,e.options)}))}static deserialize(e){const t=JSON.parse(e);return new M({clientId:t.clientId,refreshToken:t.refreshToken,refreshTokenExpires:t.refreshTokenExpires?new Date(t.refreshTokenExpires):void 0,username:t.username,password:t.password,token:t.token,tokenExpires:t.tokenExpires?new Date(t.tokenExpires):void 0,portal:t.portal,ssl:t.ssl,tokenDuration:t.tokenDuration,redirectUri:t.redirectUri,server:t.server})}static fromCredential(e,t){const r=void 0===e.ssl||e.ssl,s=e.expires||Date.now()+72e5;return t.hasServer?new M({server:e.server,ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)}):new M({portal:O(e.server.includes("sharing/rest")?e.server:e.server+"/sharing/rest"),ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)})}static parentMessageHandler(e){if("arcgis:auth:credential"===e.data.type)return new M(e.data.credential);if("arcgis:auth:error"===e.data.type){const t=new Error(e.data.error.message);throw t.name=e.data.error.name,t}throw new Error("Unknown message type.")}static destroy(e){return $({clientId:e.clientId,portal:e.portal,token:e.refreshToken||e.token})}static fromToken(e){const t=new M(e);return t.getUser().then((()=>t))}static signIn(e){const t=new M(e);return t.getUser().then((()=>t))}toCredential(){return{expires:this.tokenExpires.getTime(),server:this.server||this.portal,ssl:this.ssl,token:this.token,userId:this.username}}getUser(e){if(this._pendingUserRequest)return this._pendingUserRequest;if(this._user)return Promise.resolve(this._user);{const t=`${this.portal}/community/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingUserRequest=E(t,r).then((e=>(this._user=e,this._pendingUserRequest=null,e))),this._pendingUserRequest}}getPortal(e){if(this._pendingPortalRequest)return this._pendingPortalRequest;if(this._portalInfo)return Promise.resolve(this._portalInfo);{const t=`${this.portal}/portals/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingPortalRequest=E(t,r).then((e=>(this._portalInfo=e,this._pendingPortalRequest=null,e))),this._pendingPortalRequest}}getUsername(){return this.username?Promise.resolve(this.username):this.getUser().then((e=>e.username))}getToken(e,t){return j(this.portal,e)||new RegExp(this.portal,"i").test(e)?this.getFreshToken(t):this.getTokenForServer(e,t)}validateAppAccess(e){return this.getToken(this.portal).then((t=>F(t,e)))}toJSON(){return{clientId:this.clientId,refreshToken:this.refreshToken,refreshTokenExpires:this.refreshTokenExpires||void 0,username:this.username,password:this.password,token:this.token,tokenExpires:this.tokenExpires||void 0,portal:this.portal,ssl:this.ssl,tokenDuration:this.tokenDuration,redirectUri:this.redirectUri,server:this.server}}serialize(){return JSON.stringify(this)}enablePostMessageAuth(e,t){!t&&window&&(t=window),this._hostHandler=this.createPostMessageHandler(e),t.addEventListener("message",this._hostHandler,!1)}disablePostMessageAuth(e){!e&&window&&(e=window),e.removeEventListener("message",this._hostHandler,!1)}refreshCredentials(e){return this._user=null,this.username&&this.password?this.refreshWithUsernameAndPassword(e):this.clientId&&this.refreshToken?this.refreshWithRefreshToken():Promise.reject(new T("Unable to refresh token. No refresh token or password present.",k.TOKEN_REFRESH_FAILED))}getServerRootUrl(e){const[t]=O(e).split(/\/rest(\/admin)?\/services(?:\/|#|\?|$)/),[r,s,n]=t.match(/(https?:\/\/)(.+)/),[o,...i]=n.split("/");return`${s}${o.toLowerCase()}/${i.join("/")}`}getDomainCredentials(e){return this.trustedDomains&&this.trustedDomains.length&&this.trustedDomains.some((t=>e.startsWith(t)))?"include":"same-origin"}signOut(){return M.destroy(this)}createPostMessageHandler(e){return t=>{const r=e.indexOf(t.origin)>-1,s="arcgis:auth:requestCredential"===t.data.type,n=this.tokenExpires.getTime()>Date.now();if(r&&s){let e={};if(n){e={type:"arcgis:auth:credential",credential:this.toJSON()}}else e={type:"arcgis:auth:error",error:{name:"tokenExpiredError",message:"Token was expired, and not returned to the child application"}};t.source.postMessage(e,t.origin)}}}getTokenForServer(e,t){const r=this.getServerRootUrl(e),s=this.federatedServers[r];return s&&s.expires&&s.expires.getTime()>Date.now()?Promise.resolve(s.token):(this._pendingTokenRequests[r]||(this._pendingTokenRequests[r]=this.fetchAuthorizedDomains().then((()=>E(`${r}/rest/info`,{credentials:this.getDomainCredentials(e)}).then((s=>{if(s.owningSystemUrl){if(P(s.owningSystemUrl,this.portal))return E(`${s.owningSystemUrl}/sharing/rest/info`,t);throw new T(`${e} is not federated with ${this.portal}.`,k.NOT_FEDERATED)}if(s.authInfo&&void 0!==this.federatedServers[r])return Promise.resolve({authInfo:s.authInfo});throw new T(`${e} is not federated with any portal and is not explicitly trusted.`,k.NOT_FEDERATED)})).then((e=>this.token&&this.tokenExpires.getTime()<Date.now()?this.server?this.refreshCredentials().then((()=>({token:this.token,expires:this.tokenExpires}))):this.refreshCredentials().then((()=>this.generateTokenForServer(e.authInfo.tokenServicesUrl,r))):this.generateTokenForServer(e.authInfo.tokenServicesUrl,r))).then((e=>(this.federatedServers[r]=e,delete this._pendingTokenRequests[r],e.token)))))),this._pendingTokenRequests[r])}generateTokenForServer(e,t){return E(e,{params:{token:this.token,serverUrl:t,expiration:this.tokenDuration}}).then((e=>({token:e.token,expires:new Date(e.expires-3e5)}))).catch((e=>{throw new T(e.message,k.GENERATE_TOKEN_FOR_SERVER_FAILED,e.response,e.url,e.options)}))}getFreshToken(e){return this.token&&!this.tokenExpires||this.token&&this.tokenExpires&&this.tokenExpires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequests[this.portal]||(this._pendingTokenRequests[this.portal]=this.refreshCredentials(e).then((()=>(this._pendingTokenRequests[this.portal]=null,this.token)))),this._pendingTokenRequests[this.portal])}refreshWithUsernameAndPassword(e){const t={username:this.username,password:this.password,expiration:this.tokenDuration,client:"referer",referer:"undefined"!=typeof window&&void 0!==window.document&&window.location&&window.location.origin?window.location.origin:"@esri/arcgis-rest-js"};return(this.server?E(`${this.getServerRootUrl(this.server)}/rest/info`).then((r=>E(r.authInfo.tokenServicesUrl,Object.assign({params:t},e)))):E(`${this.portal}/generateToken`,Object.assign({params:t},e))).then((e=>(this.updateToken(e.token,new Date(e.expires)),this))).catch((e=>{throw new T(e.message,k.TOKEN_REFRESH_FAILED,e.response,e.url,e.options)}))}refreshWithRefreshToken(e){if(this.refreshToken&&this.refreshTokenExpires&&this.refreshTokenExpires.getTime()-864e5<Date.now())return this.exchangeRefreshToken(e);const t=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,grant_type:"refresh_token"}},e);return I(`${this.portal}/oauth2/token`,t).then((e=>this.updateToken(e.token,e.expires))).catch((e=>{throw new T(e.message,k.TOKEN_REFRESH_FAILED,e.response,e.url,e.options)}))}updateToken(e,t){return this._token=e,this._tokenExpires=t,this}exchangeRefreshToken(e){const t=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,redirect_uri:this.redirectUri,grant_type:"exchange_refresh_token"}},e);return I(`${this.portal}/oauth2/token`,t).then((e=>(this._token=e.token,this._tokenExpires=e.expires,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this))).catch((e=>{throw new T(e.message,k.REFRESH_TOKEN_EXCHANGE_FAILED,e.response,e.url,e.options)}))}fetchAuthorizedDomains(){return this.server||!this.portal?Promise.resolve(this):this.getPortal().then((e=>(e.authorizedCrossOriginDomains&&e.authorizedCrossOriginDomains.length&&(this.trustedDomains=e.authorizedCrossOriginDomains.filter((e=>!e.startsWith("http://"))).map((e=>e.startsWith("https://")?e:`https://${e}`))),this)))}}function H(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManager' instead."),new M(e)}function z(e,t,r="https://www.arcgis.com/sharing/rest"){return E(`${r}/oauth2/exchangeToken`,{method:"POST",params:{f:"json",client_id:t,token:e}}).then((e=>e.token))}function K(e,t,r="https://www.arcgis.com/sharing/rest"){return E(`${r}/oauth2/platformSelf?f=json`,{method:"POST",headers:{"X-Esri-Auth-Client-Id":e,"X-Esri-Auth-Redirect-Uri":t},params:{f:"json"}})}function L(e,t){return(...r)=>{const s="object"==typeof r[r.length-1]?Object.assign(Object.assign({},e),r.pop()):e;return t(...r,s)}}H.beginOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.beginOAuth2' is deprecated. Use 'ArcGISIdentityManager.beginOAuth2' instead."),M.beginOAuth2(...e)},H.completeOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.completeOAuth2()' is deprecated. Use 'ArcGISIdentityManager.completeOAuth2()' instead."),e.length<=1&&console.warn("WARNING:, 'UserSession.completeOAuth2()' is now async and returns a promise the resolves to an instance of `ArcGISIdentityManager`."),M.completeOAuth2(...e)},H.fromParent=function(...e){return console.warn("DEPRECATED:, 'UserSession.fromParent' is deprecated. Use 'ArcGISIdentityManager.fromParent' instead."),M.fromParent(...e)},H.authorize=function(...e){return console.warn("DEPRECATED:, 'UserSession.authorize' is deprecated. Use 'ArcGISIdentityManager.authorize' instead."),M.authorize(...e)},H.exchangeAuthorizationCode=function(...e){return console.warn("DEPRECATED:, 'UserSession.exchangeAuthorizationCode' is deprecated. Use 'ArcGISIdentityManager.exchangeAuthorizationCode' instead."),M.exchangeAuthorizationCode(...e)},H.fromCredential=function(...e){return console.log("DEPRECATED:, 'UserSession.fromCredential' is deprecated. Use 'ArcGISIdentityManager.fromCredential' instead."),console.warn("WARNING:, 'UserSession.fromCredential' now requires a `ServerInfo` object from the JS API as a second parameter."),M.fromCredential(...e)},H.deserialize=function(...e){return console.log("DEPRECATED:, 'UserSession.deserialize' is deprecated. Use 'ArcGISIdentityManager.deserialize' instead."),M.deserialize(...e)};export{D as ApiKey,y as ApiKeyManager,v as ApplicationCredentialsManager,x as ApplicationSession,R as ArcGISAccessDeniedError,g as ArcGISAuthError,M as ArcGISIdentityManager,h as ArcGISRequestError,T as ArcGISTokenRequestError,k as ArcGISTokenRequestErrorCodes,i as Blob,_ as ErrorTypes,o as File,n as FormData,u as NODEJS_DEFAULT_REFERER_HEADER,H as UserSession,w as appendCustomParams,j as canUseOnlineToken,f as checkForErrors,O as cleanUrl,S as decodeParam,A as decodeQueryString,a as encodeFormData,r as encodeParam,s as encodeQueryString,z as exchangeToken,I as fetchToken,p as getDefaultRequestOptions,l as getFetch,N as getOnlineEnvironment,m as internalRequest,P as isFederated,b as isOnline,C as normalizeOnlinePortalUrl,K as platformSelf,t as processParams,E as request,e as requiresFormData,$ as revokeToken,d as setDefaultRequestOptions,F as validateAppAccess,c as warn,L as withOptions};
function e(e){return Object.keys(e).some((t=>{let r=e[t];if(!r)return!1;r&&r.toParam&&(r=r.toParam());switch(r.constructor.name){case"Array":case"Object":case"Date":case"Function":case"Boolean":case"String":case"Number":return!1;default:return!0}}))}function t(e){const t={};return Object.keys(e).forEach((r=>{var s,n;let i=e[r];if(i&&i.toParam&&(i=i.toParam()),!i&&0!==i&&"boolean"!=typeof i&&"string"!=typeof i)return;let o;switch(i.constructor.name){case"Array":const e=null===(n=null===(s=i[0])||void 0===s?void 0:s.constructor)||void 0===n?void 0:n.name;o="Array"===e?i:"Object"===e?JSON.stringify(i):i.join(",");break;case"Object":o=JSON.stringify(i);break;case"Date":o=i.valueOf();break;case"Function":o=null;break;case"Boolean":o=i+"";break;default:o=i}(o||0===o||"string"==typeof o||Array.isArray(o))&&(t[r]=o)})),t}function r(e,t){return Array.isArray(t)&&t[0]&&Array.isArray(t[0])?t.map((t=>r(e,t))).join("&"):encodeURIComponent(e)+"="+encodeURIComponent(t)}function s(e){const s=t(e);return Object.keys(s).map((e=>r(e,s[e]))).join("&")}const n=globalThis.FormData,i=globalThis.File,o=globalThis.Blob;function a(r,i){const o=e(r)||i,a=t(r);if(o){const e=new n;return Object.keys(a).forEach((t=>{if("undefined"!=typeof Blob&&a[t]instanceof Blob){const r=a.fileName||a[t].name||t;e.append(t,a[t],r)}else e.append(t,a[t])})),e}return s(r)}class c extends Error{constructor(e,t,r,s,n){super(e);const i=new.target.prototype;Object.setPrototypeOf(this,i),e=e||"UNKNOWN_ERROR",t=t||"UNKNOWN_ERROR_CODE",this.name="ArcGISRequestError",this.message="UNKNOWN_ERROR_CODE"===t?e:`${t}: ${e}`,this.originalMessage=e,this.code=t,this.response=r,this.url=s,this.options=n}}function h(e){console&&console.warn&&console.warn.apply(console,[e])}function l(){return Promise.resolve({fetch:globalThis.fetch,Headers:globalThis.Headers,Response:globalThis.Response,Request:globalThis.Request})}const u="@esri/arcgis-rest-js";function d(e,t){e.authentication&&!t&&h("You should not set `authentication` as a default in a shared environment such as a web server which will process multiple users requests. You can call `setDefaultRequestOptions` with `true` as a second argument to disable this warning."),globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS=e}function p(){return globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS||{httpMethod:"POST",params:{f:"json"}}}class g extends c{constructor(e="AUTHENTICATION_ERROR",t="AUTHENTICATION_ERROR_CODE",r,s,n){super(e,t,r,s,n),this.name="ArcGISAuthError",this.message="AUTHENTICATION_ERROR_CODE"===t?e:`${t}: ${e}`;const i=new.target.prototype;Object.setPrototypeOf(this,i)}retry(e,t=1){let r=0;const s=(n,i)=>{r+=1,e(this.url,this.options).then((e=>{const t=Object.assign(Object.assign({},this.options),{authentication:e});return m(this.url,t)})).then((e=>{n(e)})).catch((e=>{"ArcGISAuthError"===e.name&&r<t?s(n,i):e.name===this.name&&e.message===this.message&&r>=t?i(this):i(e)}))};return new Promise(((e,t)=>{s(e,t)}))}}function f(e,t,r,s,n){if(e.code>=400){const{message:r,code:n}=e;throw new c(r,n,e,t,s)}if(e.error){const{message:r,code:i,messageCode:o}=e.error,a=o||i||"UNKNOWN_ERROR_CODE";if(498===i||499===i)throw n||new g(r,a,e,t,s);throw new c(r,a,e,t,s)}if("failed"===e.status||"failure"===e.status){let r,n="UNKNOWN_ERROR_CODE";try{r=JSON.parse(e.statusMessage).message,n=JSON.parse(e.statusMessage).code}catch(t){r=e.statusMessage||e.message}throw new c(r,n,e,t,s)}return e}function m(t,r){const n=p(),i=Object.assign(Object.assign(Object.assign({httpMethod:"POST"},n),r),{params:Object.assign(Object.assign({},n.params),r.params),headers:Object.assign(Object.assign({},n.headers),r.headers)}),{httpMethod:o,rawResponse:u}=i,d=Object.assign({f:"json"},i.params);let g=null;const m={method:o,signal:i.signal,credentials:i.credentials||"same-origin"};let E;if(i.headers&&i.headers["X-Esri-Auth-Client-Id"]&&t.indexOf("/oauth2/platformSelf")>-1&&(m.credentials="include"),"string"==typeof i.authentication){const e=i.authentication;E={portal:"https://www.arcgis.com/sharing/rest",getToken:()=>Promise.resolve(e)},i.authentication.startsWith("AAPK")||i.suppressWarnings||globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING||(h("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."),globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING=!0)}else E=i.authentication;const w=t;return(E?E.getToken(t).catch((e=>(e.url=t,e.options=i,g=e,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(d.token=r),E&&E.getDomainCredentials&&(m.credentials=E.getDomainCredentials(t));const n={};if("GET"===m.method){d.token&&i.hideToken&&"undefined"==typeof window&&(n["X-Esri-Authorization"]=`Bearer ${d.token}`,delete d.token);const e=""===s(d)?t:t+"?"+s(d);i.maxUrlLength&&e.length>i.maxUrlLength||d.token&&i.hideToken?(m.method="POST",r.length&&i.hideToken&&(d.token=r,delete n["X-Esri-Authorization"])):t=e}const o=new RegExp("/items/.+/updateResources").test(t);return"POST"===m.method&&(m.body=a(d,o)),m.headers=Object.assign(Object.assign({},n),i.headers),("undefined"==typeof window||window&&void 0===window.document)&&!m.headers.referer&&(m.headers.referer="@esri/arcgis-rest-js"),e(d)||o||(m.headers["Content-Type"]="application/x-www-form-urlencoded"),globalThis.fetch?globalThis.fetch(t,m):l().then((({fetch:e})=>e(t,m)))})).then((e=>{if(!e.ok){const{status:r,statusText:s}=e;throw new c(s,`HTTP ${r}`,e,t,i)}if(u)return e;switch(d.f){case"json":case"geojson":return e.json();case"html":case"text":return e.text();default:return e.blob()}})).then((e=>{if("json"!==d.f&&"geojson"!==d.f||u)return e;{const r=f(e,w,0,i,g);if(g){const e=t.toLowerCase().split(/\/rest(\/admin)?\/services\//)[0];i.authentication.federatedServers[e]={token:[],expires:new Date(Date.now()+864e5)},g=null}return r}}))}function E(e,t={params:{f:"json"}}){return m(e,t).catch((e=>e instanceof g&&t.authentication&&"string"!=typeof t.authentication&&t.authentication.canRefresh&&t.authentication.refreshCredentials?e.retry((()=>t.authentication.refreshCredentials()),1):Promise.reject(e)))}function w(e,t,r){const s=Object.assign(Object.assign({params:{}},r),e);return s.params=t.reduce(((t,r)=>((e[r]||"boolean"==typeof e[r]||"number"==typeof e[r]&&0===e[r])&&(t[r]=e[r]),t)),s.params),["params","httpMethod","rawResponse","authentication","portal","fetch","maxUrlLength","headers"].reduce(((e,t)=>(s[t]&&(e[t]=s[t]),e)),{})}var k,_;!function(e){e.TOKEN_REFRESH_FAILED="TOKEN_REFRESH_FAILED",e.GENERATE_TOKEN_FOR_SERVER_FAILED="GENERATE_TOKEN_FOR_SERVER_FAILED",e.REFRESH_TOKEN_EXCHANGE_FAILED="REFRESH_TOKEN_EXCHANGE_FAILED",e.NOT_FEDERATED="NOT_FEDERATED",e.UNKNOWN_ERROR_CODE="UNKNOWN_ERROR_CODE"}(k||(k={}));class T extends Error{constructor(e="UNKNOWN_ERROR",t=k.UNKNOWN_ERROR_CODE,r,s,n){super(e);const i=new.target.prototype;Object.setPrototypeOf(this,i),this.name="ArcGISTokenRequestError",this.message=`${t}: ${e}`,this.originalMessage=e,this.code=t,this.response=r,this.url=s,this.options=n}}class R extends Error{constructor(){super("The user has denied your authorization request.");const e=new.target.prototype;Object.setPrototypeOf(this,e),this.name="ArcGISAccessDeniedError"}}class O extends Error{constructor(e="Unknown error",t){super(e);const r=new.target.prototype;Object.setPrototypeOf(this,r),this.name="ArcGISJobError",this.message=`${t.status}: ${e}`,this.status=t.status,this.id=t.id,this.jobInfo=t}}function b(e){return"string"!=typeof e||"/"===(e=e.trim())[e.length-1]&&(e=e.slice(0,-1)),e}function S(e){const[t,r]=e.split("=");return{key:decodeURIComponent(t),value:decodeURIComponent(r)}}function I(e){return!e||e.length<=0?{}:e.replace(/^#/,"").replace(/^\?/,"").split("&").reduce(((e,t)=>{const{key:r,value:s}=S(t);return e[r]=s,e}),{})}!function(e){e.ArcGISRequestError="ArcGISRequestError",e.ArcGISAuthError="ArcGISAuthError",e.ArcGISAccessDeniedError="ArcGISAccessDeniedError",e.ArcGISTokenRequestError="ArcGISTokenRequestError"}(_||(_={}));function A(e,t){const r=t;return r.rawResponse=!1,E(e,r).then((e=>{const t={token:e.access_token,username:e.username,expires:new Date(Date.now()+1e3*e.expires_in-3e5),ssl:!0===e.ssl};return e.refresh_token&&(t.refreshToken=e.refresh_token),e.refresh_token_expires_in&&(t.refreshTokenExpires=new Date(Date.now()+1e3*e.refresh_token_expires_in-3e5)),t}))}class v{constructor(e){this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.token=e.token,this.expires=e.expires,this.portal=e.portal||"https://www.arcgis.com/sharing/rest",this.duration=e.duration||7200}static fromCredentials(e){return new v(e)}getToken(e,t){return this.token&&this.expires&&this.expires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequest||(this._pendingTokenRequest=this.refreshToken(t)),this._pendingTokenRequest)}refreshToken(e){const t=Object.assign({params:{client_id:this.clientId,client_secret:this.clientSecret,grant_type:"client_credentials",expiration:this.duration}},e);return A(`${this.portal}/oauth2/token/`,t).then((e=>(this._pendingTokenRequest=null,this.token=e.token,this.expires=e.expires,e.token))).catch((e=>{throw new T(e.message,k.TOKEN_REFRESH_FAILED,e.response,e.url,e.options)}))}refreshCredentials(){return this.refreshToken().then((()=>this))}}function x(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new v(e)}class y{constructor(e){this.portal="https://www.arcgis.com/sharing/rest",this.key=e.key}static fromKey(e){return new y({key:e})}getToken(e){return Promise.resolve(this.key)}}function U(e){return console.log("DEPRECATED:, 'ApiKey' is deprecated. Use 'ApiKeyManager' instead."),new y(e)}const j=/^https?:\/\/(\S+)\.arcgis\.com.+/;function D(e){return j.test(e)}function C(e){if(!j.test(e))return e;switch(N(e)){case"dev":return"https://devext.arcgis.com/sharing/rest";case"qa":return"https://qaext.arcgis.com/sharing/rest";default:return"https://www.arcgis.com/sharing/rest"}}function N(e){if(!j.test(e))return null;const t=e.match(j)[1].split(".").pop();return t.includes("dev")?"dev":t.includes("qa")?"qa":"production"}function P(e,t){const r=b(C(t)).replace(/https?:\/\//,""),s=b(e).replace(/https?:\/\//,"");return new RegExp(s,"i").test(r)}function M(e,t){const r=D(e),s=D(t),n=N(e),i=N(t);return!(!r||!s||n!==i)}function F(e,t,r="https://www.arcgis.com/sharing/rest"){return E(`${r}/oauth2/validateAppAccess`,{method:"POST",params:{f:"json",client_id:t,token:e}})}function $(e){const t=`${b(e.portal||"https://www.arcgis.com/sharing/rest")}/oauth2/revokeToken/`,r=e.token,s=e.clientId;delete e.portal,delete e.clientId,delete e.token;const n=Object.assign(Object.assign({},e),{httpMethod:"POST",params:{client_id:s,auth_token:r}});return E(t,n).then((e=>{if(!e.success)throw new c("Unable to revoke token",500,e,t,n);return e}))}function G(e,t=window){return!t&&window&&(t=window),t.btoa(String.fromCharCode.apply(null,e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function J(e){!e&&window&&(e=window);return G(e.crypto.getRandomValues(new Uint8Array(32)))}class q{constructor(e){if(this.clientId=e.clientId,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this._username=e.username,this.password=e.password,this._token=e.token,this._tokenExpires=e.tokenExpires,this.portal=e.portal?b(e.portal):"https://www.arcgis.com/sharing/rest",this.ssl=e.ssl,this.provider=e.provider||"arcgis",this.tokenDuration=e.tokenDuration||20160,this.redirectUri=e.redirectUri,this.server=e.server,this.federatedServers={},this.trustedDomains=[],e.server){const t=this.getServerRootUrl(e.server);this.federatedServers[t]={token:e.token,expires:e.tokenExpires}}this._pendingTokenRequests={}}get token(){return this._token}get tokenExpires(){return this._tokenExpires}get refreshToken(){return this._refreshToken}get refreshTokenExpires(){return this._refreshTokenExpires}get username(){return this._username?this._username:this._user&&this._user.username?this._user.username:void 0}get canRefresh(){return!(!this.username||!this.password)||!!(this.clientId&&this.refreshToken&&this.redirectUri)}static beginOAuth2(e,t){!t&&window&&(t=window);const{portal:r,provider:n,clientId:i,expiration:o,redirectUri:a,popup:c,popupWindowFeatures:h,locale:l,params:u,style:d,pkce:p,state:f}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",provider:"arcgis",expiration:20160,popup:!0,popupWindowFeatures:"height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes",locale:"",style:"",pkce:!0},e),m=f||J(t),E=`ARCGIS_REST_JS_AUTH_STATE_${i}`;t.localStorage.setItem(E,m);let w=`${b(r)}/oauth2/authorize`;const k={client_id:i,response_type:p?"code":"token",expiration:o,redirect_uri:a,state:JSON.stringify({id:m,originalUrl:t.location.href}),locale:l,style:d};let _;if("arcgis"!==n&&(w=`${b(r)}/oauth2/social/authorize`,k.socialLoginProviderName=n,k.autoAccountCreateForSocial=!0),p){const e=J(t),r=`ARCGIS_REST_JS_CODE_VERIFIER_${i}`;t.localStorage.setItem(r,e),_=function(e,t=window){if(!t&&window&&(t=window),e&&t.isSecureContext&&t.crypto&&t.crypto.subtle){const r=(new t.TextEncoder).encode(e);return t.crypto.subtle.digest("SHA-256",r).then((e=>G(new Uint8Array(e),t)))}return Promise.resolve(null)}(e,t).then((function(t){k.code_challenge_method=t?"S256":"plain",k.code_challenge=t||e}))}else _=Promise.resolve();return _.then((()=>(w=`${w}?${s(k)}`,u&&(w=`${w}&${s(u)}`),c?new Promise(((e,s)=>{t.addEventListener(`arcgis-rest-js-popup-auth-${i}`,(t=>{if("access_denied"===t.detail.error){const e=new R;return s(e),e}if(t.detail.errorMessage){const e=new g(t.detail.errorMessage,t.detail.error);return s(e),e}e(new q({clientId:i,portal:r,ssl:t.detail.ssl,token:t.detail.token,tokenExpires:t.detail.expires,username:t.detail.username,refreshToken:t.detail.refreshToken,refreshTokenExpires:t.detail.refreshTokenExpires,redirectUri:a}))}),{once:!0}),t.open(w,"oauth-window",h),t.dispatchEvent(new CustomEvent("arcgis-rest-js-popup-auth-start"))})):void(t.location.href=w))))}static completeOAuth2(e,t){!t&&window&&(t=window);const{portal:r,clientId:s,popup:n,pkce:i,redirectUri:o}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",popup:!0,pkce:!0},e),a=`ARCGIS_REST_JS_AUTH_STATE_${s}`,c=t.localStorage.getItem(a),h=I(i?t.location.search.replace(/^\?/,""):t.location.hash.replace(/^#/,"")),l=h&&h.state?JSON.parse(h.state):void 0;function u(e,r,i){return t.localStorage.removeItem(a),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:{error:r,errorMessage:e}})),void t.close()):(i&&t.history.replaceState(t.history.state,"",i),"access_denied"===r?Promise.reject(new R):Promise.reject(new g(e,r)))}function d(e,i){return t.localStorage.removeItem(a),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:Object.assign({},e)})),void t.close()):(t.history.replaceState(t.history.state,"",i),new q({clientId:s,portal:r,ssl:e.ssl,token:e.token,tokenExpires:e.expires,username:e.username,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,redirectUri:o||location.href.replace(location.search,"")}))}if(!c||!l)return u("No authentication state was found, call `ArcGISIdentityManager.beginOAuth2(...)` to start the authentication process.","no-auth-state");if(l.id!==c)return u("Saved client state did not match server sent state.","mismatched-auth-state");if(h.error){const e=h.error;return u(h.error_description||"Unknown error",e,l.originalUrl)}if(i&&h.code){const e=b(`${r}/oauth2/token/`),n=`ARCGIS_REST_JS_CODE_VERIFIER_${s}`,i=t.localStorage.getItem(n);return t.localStorage.removeItem(n),A(e,{httpMethod:"POST",params:{client_id:s,code_verifier:i,grant_type:"authorization_code",redirect_uri:o||location.href.replace(location.search,""),code:h.code}}).then((e=>d(Object.assign(Object.assign({},e),l),l.originalUrl))).catch((e=>u(e.originalMessage,e.code,l.originalUrl)))}return!i&&h.access_token?Promise.resolve(d(Object.assign({token:h.access_token,expires:new Date(Date.now()+1e3*parseInt(h.expires_in,10)),ssl:"true"===h.ssl,username:h.username},l),l.originalUrl)):u("Unknown error","oauth-error",l.originalUrl)}static fromParent(e,t){let r;return!t&&window&&(t=window),new Promise(((s,n)=>{r=e=>{if(e.source===t.parent&&e.data)try{return s(q.parentMessageHandler(e))}catch(e){return n(e)}},t.addEventListener("message",r,!1),t.parent.postMessage({type:"arcgis:auth:requestCredential"},e)})).then((e=>(t.removeEventListener("message",r,!1),e)))}static authorize(e,t){const{portal:r,clientId:n,expiration:i,redirectUri:o,state:a}=Object.assign({portal:"https://arcgis.com/sharing/rest",expiration:20160},e),c={client_id:n,expiration:i,response_type:"code",redirect_uri:o};a&&(c.state=a);const h=`${r}/oauth2/authorize?${s(c)}`;t.writeHead(301,{Location:h}),t.end()}static exchangeAuthorizationCode(e,t){const{portal:r,clientId:s,redirectUri:n}=Object.assign({portal:"https://www.arcgis.com/sharing/rest"},e);return A(`${r}/oauth2/token`,{params:{grant_type:"authorization_code",client_id:s,redirect_uri:n,code:t}}).then((e=>new q({clientId:s,portal:r,ssl:e.ssl,redirectUri:n,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,token:e.token,tokenExpires:e.expires,username:e.username}))).catch((e=>{throw new T(e.message,k.REFRESH_TOKEN_EXCHANGE_FAILED,e.response,e.url,e.options)}))}static deserialize(e){const t=JSON.parse(e);return new q({clientId:t.clientId,refreshToken:t.refreshToken,refreshTokenExpires:t.refreshTokenExpires?new Date(t.refreshTokenExpires):void 0,username:t.username,password:t.password,token:t.token,tokenExpires:t.tokenExpires?new Date(t.tokenExpires):void 0,portal:t.portal,ssl:t.ssl,tokenDuration:t.tokenDuration,redirectUri:t.redirectUri,server:t.server})}static fromCredential(e,t){const r=void 0===e.ssl||e.ssl,s=e.expires||Date.now()+72e5;return t.hasServer?new q({server:e.server,ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)}):new q({portal:b(e.server.includes("sharing/rest")?e.server:e.server+"/sharing/rest"),ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)})}static parentMessageHandler(e){if("arcgis:auth:credential"===e.data.type)return new q(e.data.credential);if("arcgis:auth:error"===e.data.type){const t=new Error(e.data.error.message);throw t.name=e.data.error.name,t}throw new Error("Unknown message type.")}static destroy(e){return $({clientId:e.clientId,portal:e.portal,token:e.refreshToken||e.token})}static fromToken(e){const t=new q(e);return t.getUser().then((()=>t))}static signIn(e){const t=new q(e);return t.getUser().then((()=>t))}toCredential(){return{expires:this.tokenExpires.getTime(),server:this.server||this.portal,ssl:this.ssl,token:this.token,userId:this.username}}getUser(e){if(this._pendingUserRequest)return this._pendingUserRequest;if(this._user)return Promise.resolve(this._user);{const t=`${this.portal}/community/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingUserRequest=E(t,r).then((e=>(this._user=e,this._pendingUserRequest=null,e))),this._pendingUserRequest}}getPortal(e){if(this._pendingPortalRequest)return this._pendingPortalRequest;if(this._portalInfo)return Promise.resolve(this._portalInfo);{const t=`${this.portal}/portals/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingPortalRequest=E(t,r).then((e=>(this._portalInfo=e,this._pendingPortalRequest=null,e))),this._pendingPortalRequest}}getUsername(){return this.username?Promise.resolve(this.username):this.getUser().then((e=>e.username))}getToken(e,t){return M(this.portal,e)||new RegExp(this.portal,"i").test(e)?this.getFreshToken(t):this.getTokenForServer(e,t)}validateAppAccess(e){return this.getToken(this.portal).then((t=>F(t,e)))}toJSON(){return{clientId:this.clientId,refreshToken:this.refreshToken,refreshTokenExpires:this.refreshTokenExpires||void 0,username:this.username,password:this.password,token:this.token,tokenExpires:this.tokenExpires||void 0,portal:this.portal,ssl:this.ssl,tokenDuration:this.tokenDuration,redirectUri:this.redirectUri,server:this.server}}serialize(){return JSON.stringify(this)}enablePostMessageAuth(e,t){!t&&window&&(t=window),this._hostHandler=this.createPostMessageHandler(e),t.addEventListener("message",this._hostHandler,!1)}disablePostMessageAuth(e){!e&&window&&(e=window),e.removeEventListener("message",this._hostHandler,!1)}refreshCredentials(e){return this._user=null,this.username&&this.password?this.refreshWithUsernameAndPassword(e):this.clientId&&this.refreshToken?this.refreshWithRefreshToken():Promise.reject(new T("Unable to refresh token. No refresh token or password present.",k.TOKEN_REFRESH_FAILED))}getServerRootUrl(e){const[t]=b(e).split(/\/rest(\/admin)?\/services(?:\/|#|\?|$)/),[r,s,n]=t.match(/(https?:\/\/)(.+)/),[i,...o]=n.split("/");return`${s}${i.toLowerCase()}/${o.join("/")}`}getDomainCredentials(e){return this.trustedDomains&&this.trustedDomains.length&&this.trustedDomains.some((t=>e.startsWith(t)))?"include":"same-origin"}signOut(){return q.destroy(this)}createPostMessageHandler(e){return t=>{const r=e.indexOf(t.origin)>-1,s="arcgis:auth:requestCredential"===t.data.type,n=this.tokenExpires.getTime()>Date.now();if(r&&s){let e={};if(n){e={type:"arcgis:auth:credential",credential:this.toJSON()}}else e={type:"arcgis:auth:error",error:{name:"tokenExpiredError",message:"Token was expired, and not returned to the child application"}};t.source.postMessage(e,t.origin)}}}getTokenForServer(e,t){const r=this.getServerRootUrl(e),s=this.federatedServers[r];return s&&s.expires&&s.expires.getTime()>Date.now()?Promise.resolve(s.token):(this._pendingTokenRequests[r]||(this._pendingTokenRequests[r]=this.fetchAuthorizedDomains().then((()=>E(`${r}/rest/info`,{credentials:this.getDomainCredentials(e)}).then((s=>{if(s.owningSystemUrl){if(P(s.owningSystemUrl,this.portal))return E(`${s.owningSystemUrl}/sharing/rest/info`,t);throw new T(`${e} is not federated with ${this.portal}.`,k.NOT_FEDERATED)}if(s.authInfo&&void 0!==this.federatedServers[r])return Promise.resolve({authInfo:s.authInfo});throw new T(`${e} is not federated with any portal and is not explicitly trusted.`,k.NOT_FEDERATED)})).then((e=>this.token&&this.tokenExpires.getTime()<Date.now()?this.server?this.refreshCredentials().then((()=>({token:this.token,expires:this.tokenExpires}))):this.refreshCredentials().then((()=>this.generateTokenForServer(e.authInfo.tokenServicesUrl,r))):this.generateTokenForServer(e.authInfo.tokenServicesUrl,r))).then((e=>(this.federatedServers[r]=e,delete this._pendingTokenRequests[r],e.token)))))),this._pendingTokenRequests[r])}generateTokenForServer(e,t){return E(e,{params:{token:this.token,serverUrl:t,expiration:this.tokenDuration}}).then((e=>({token:e.token,expires:new Date(e.expires-3e5)}))).catch((e=>{throw new T(e.message,k.GENERATE_TOKEN_FOR_SERVER_FAILED,e.response,e.url,e.options)}))}getFreshToken(e){return this.token&&!this.tokenExpires||this.token&&this.tokenExpires&&this.tokenExpires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequests[this.portal]||(this._pendingTokenRequests[this.portal]=this.refreshCredentials(e).then((()=>(this._pendingTokenRequests[this.portal]=null,this.token)))),this._pendingTokenRequests[this.portal])}refreshWithUsernameAndPassword(e){const t={username:this.username,password:this.password,expiration:this.tokenDuration,client:"referer",referer:"undefined"!=typeof window&&void 0!==window.document&&window.location&&window.location.origin?window.location.origin:"@esri/arcgis-rest-js"};return(this.server?E(`${this.getServerRootUrl(this.server)}/rest/info`).then((r=>E(r.authInfo.tokenServicesUrl,Object.assign({params:t},e)))):E(`${this.portal}/generateToken`,Object.assign({params:t},e))).then((e=>(this.updateToken(e.token,new Date(e.expires)),this))).catch((e=>{throw new T(e.message,k.TOKEN_REFRESH_FAILED,e.response,e.url,e.options)}))}refreshWithRefreshToken(e){if(this.refreshToken&&this.refreshTokenExpires&&this.refreshTokenExpires.getTime()-864e5<Date.now())return this.exchangeRefreshToken(e);const t=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,grant_type:"refresh_token"}},e);return A(`${this.portal}/oauth2/token`,t).then((e=>this.updateToken(e.token,e.expires))).catch((e=>{throw new T(e.message,k.TOKEN_REFRESH_FAILED,e.response,e.url,e.options)}))}updateToken(e,t){return this._token=e,this._tokenExpires=t,this}exchangeRefreshToken(e){const t=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,redirect_uri:this.redirectUri,grant_type:"exchange_refresh_token"}},e);return A(`${this.portal}/oauth2/token`,t).then((e=>(this._token=e.token,this._tokenExpires=e.expires,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this))).catch((e=>{throw new T(e.message,k.REFRESH_TOKEN_EXCHANGE_FAILED,e.response,e.url,e.options)}))}fetchAuthorizedDomains(){return this.server||!this.portal?Promise.resolve(this):this.getPortal().then((e=>(e.authorizedCrossOriginDomains&&e.authorizedCrossOriginDomains.length&&(this.trustedDomains=e.authorizedCrossOriginDomains.filter((e=>!e.startsWith("http://"))).map((e=>e.startsWith("https://")?e:`https://${e}`))),this)))}}function H(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManager' instead."),new q(e)}function z(e,t,r="https://www.arcgis.com/sharing/rest"){return E(`${r}/oauth2/exchangeToken`,{method:"POST",params:{f:"json",client_id:t,token:e}}).then((e=>e.token))}function K(e,t,r="https://www.arcgis.com/sharing/rest"){return E(`${r}/oauth2/platformSelf?f=json`,{method:"POST",headers:{"X-Esri-Auth-Client-Id":e,"X-Esri-Auth-Redirect-Uri":t},params:{f:"json"}})}var W;H.beginOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.beginOAuth2' is deprecated. Use 'ArcGISIdentityManager.beginOAuth2' instead."),q.beginOAuth2(...e)},H.completeOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.completeOAuth2()' is deprecated. Use 'ArcGISIdentityManager.completeOAuth2()' instead."),e.length<=1&&console.warn("WARNING:, 'UserSession.completeOAuth2()' is now async and returns a promise the resolves to an instance of `ArcGISIdentityManager`."),q.completeOAuth2(...e)},H.fromParent=function(...e){return console.warn("DEPRECATED:, 'UserSession.fromParent' is deprecated. Use 'ArcGISIdentityManager.fromParent' instead."),q.fromParent(...e)},H.authorize=function(...e){return console.warn("DEPRECATED:, 'UserSession.authorize' is deprecated. Use 'ArcGISIdentityManager.authorize' instead."),q.authorize(...e)},H.exchangeAuthorizationCode=function(...e){return console.warn("DEPRECATED:, 'UserSession.exchangeAuthorizationCode' is deprecated. Use 'ArcGISIdentityManager.exchangeAuthorizationCode' instead."),q.exchangeAuthorizationCode(...e)},H.fromCredential=function(...e){return console.log("DEPRECATED:, 'UserSession.fromCredential' is deprecated. Use 'ArcGISIdentityManager.fromCredential' instead."),console.warn("WARNING:, 'UserSession.fromCredential' now requires a `ServerInfo` object from the JS API as a second parameter."),q.fromCredential(...e)},H.deserialize=function(...e){return console.log("DEPRECATED:, 'UserSession.deserialize' is deprecated. Use 'ArcGISIdentityManager.deserialize' instead."),q.deserialize(...e)},function(e){e.Success="Succeeded",e.Failed="Failed",e.Waiting="Waiting",e.Cancelled="Cancelled",e.Cancelling="Cancelling",e.New="New",e.Executing="Executing",e.Submitted="Submitted",e.Failure="Failure",e.TimedOut="TimedOut",e.Error="Error",e.Status="Etatus",e.Unknown="Unknown"}(W||(W={}));const L={pollingRate:2e3,startMonitoring:!1};class X{constructor(e){this.executePoll=async()=>{let e;try{e=await this.getJobInfo()}catch(e){return void this.emitter.emit(W.Error,e)}this.emitter.emit(W.Status,e),this.emitter.emit(e.status,e)};const{url:t,id:r,pollingRate:s,authentication:n}=Object.assign(Object.assign({},L),e);var i;this.url=t,this.id=r,this.authentication=n,this._pollingRate=s,this.emitter={all:i=i||new Map,on:function(e,t){var r=i.get(e);r?r.push(t):i.set(e,[t])},off:function(e,t){var r=i.get(e);r&&(t?r.splice(r.indexOf(t)>>>0,1):i.set(e,[]))},emit:function(e,t){var r=i.get(e);r&&r.slice().map((function(e){e(t)})),(r=i.get("*"))&&r.slice().map((function(r){r(e,t)}))}},e.startMonitoring&&this.startEventMonitoring(s)}static deserialize(e,t){const r=Object.assign(Object.assign(Object.assign({},L),JSON.parse(e)),t);return E(`${r.url}/jobs/${r.id}`,{authentication:r.authentication}).then((()=>new X(r)))}static fromExistingJob(e){const t=Object.assign(Object.assign({},L),e);return E(`${b(t.url.replace(/\/submitJob\/?/,""))}/jobs/${t.id}`,{authentication:t.authentication}).then((()=>new X(t)))}static submitJob(e){const{url:t,params:r,authentication:s,pollingRate:n,startMonitoring:i}=Object.assign(Object.assign({},L),e),o=b(t.replace(/\/submitJob\/?/,""));return E(o+"/submitJob",{params:r,authentication:s}).then((e=>new X({url:o,authentication:s,id:e.jobId,startMonitoring:i,pollingRate:n})))}get jobUrl(){return`${this.url}/jobs/${this.id}`}get isMonitoring(){return!!this.setIntervalHandler}get pollingRate(){return this._pollingRate}set pollingRate(e){this.stopEventMonitoring(),this.startEventMonitoring(e)}getJobInfo(){return E(this.jobUrl,{authentication:this.authentication}).then((e=>{const t=Object.assign({id:e.jobId,status:void 0},e);switch(delete t.jobId,delete t.jobStatus,e.jobStatus){case"esriJobCancelled":t.status=W.Cancelled;break;case"esriJobCancelling":t.status=W.Cancelling;break;case"esriJobNew":t.status=W.New;break;case"esriJobWaiting":t.status=W.Waiting;break;case"esriJobExecuting":t.status=W.Executing;break;case"esriJobSubmitted":t.status=W.Submitted;break;case"esriJobTimedOut":t.status=W.TimedOut;break;case"esriJobFailed":t.status=W.Failed;break;case"expectedFailure":t.status=W.Failure;break;case"esriJobSucceeded":t.status=W.Success}return t}))}on(e,t){this.emitter.on(e,t)}once(e,t){const r=s=>{this.emitter.off(e,r),t(s)};this.emitter.on(e,r),t.__arcgis_job_once_original_function__=r}off(e,t){t.__arcgis_job_once_original_function__?this.emitter.off(e,t.__arcgis_job_once_original_function__):this.emitter.off(e,t)}async getResult(e){return this.waitForCompletion().then((t=>E(this.jobUrl+"/"+t.results[e].paramUrl,{authentication:this.authentication})))}toJSON(){return{id:this.id,url:this.url,startMonitoring:this.isMonitoring,pollingRate:this.pollingRate}}serialize(){return JSON.stringify(this)}async waitForCompletion(){const e=await this.getJobInfo();return e.status===W.Success?Promise.resolve(e):e.status===W.Cancelling||e.status===W.Cancelled||e.status===W.Failed||e.status===W.Failure||e.status===W.TimedOut?(this.stopInternalEventMonitoring(),Promise.reject(new O("Job cancelled or failed.",e))):new Promise(((e,t)=>{this.startInternalEventMonitoring(),this.once(W.Cancelled,(e=>{this.stopInternalEventMonitoring(),t(new O("Job cancelled.",e))})),this.once(W.TimedOut,(e=>{this.stopInternalEventMonitoring(),t(new O("Job timed out.",e))})),this.once(W.Failed,(e=>{this.stopInternalEventMonitoring(),t(new O("Job failed.",e))})),this.once(W.Success,(t=>{this.stopInternalEventMonitoring(),e(t)}))}))}async getAllResults(){return this.waitForCompletion().then((e=>{const t=Object.keys(e.results),r=t.map((t=>E(this.jobUrl+"/"+e.results[t].paramUrl,{authentication:this.authentication}).then((e=>e))));return Promise.all(r).then((e=>t.reduce(((r,s,n)=>(r[t[n]]=e[n],r)),{})))}))}cancelJob(){return E(this.jobUrl+"/cancel",{authentication:this.authentication,params:{id:this.id,returnMessages:!1}}).then((e=>(this.emitter.emit("cancelled",e),e)))}startInternalEventMonitoring(e=L.pollingRate){this._pollingRate=e,this.isMonitoring||(this.setIntervalHandler=setInterval(this.executePoll,this.pollingRate))}stopInternalEventMonitoring(){this.isMonitoring&&!this.didUserEnableMonitoring&&clearTimeout(this.setIntervalHandler)}startEventMonitoring(e=L.pollingRate){this._pollingRate=e,this.didUserEnableMonitoring=!0,this.isMonitoring||(this.setIntervalHandler=setInterval(this.executePoll,this.pollingRate))}stopEventMonitoring(){this.isMonitoring&&this.didUserEnableMonitoring&&clearTimeout(this.setIntervalHandler)}}function B(e,t){return(...r)=>{const s="object"==typeof r[r.length-1]?Object.assign(Object.assign({},e),r.pop()):e;return t(...r,s)}}export{U as ApiKey,y as ApiKeyManager,v as ApplicationCredentialsManager,x as ApplicationSession,R as ArcGISAccessDeniedError,g as ArcGISAuthError,q as ArcGISIdentityManager,O as ArcGISJobError,c as ArcGISRequestError,T as ArcGISTokenRequestError,k as ArcGISTokenRequestErrorCodes,o as Blob,_ as ErrorTypes,i as File,n as FormData,W as JOB_STATUSES,X as Job,u as NODEJS_DEFAULT_REFERER_HEADER,H as UserSession,w as appendCustomParams,M as canUseOnlineToken,f as checkForErrors,b as cleanUrl,S as decodeParam,I as decodeQueryString,a as encodeFormData,r as encodeParam,s as encodeQueryString,z as exchangeToken,A as fetchToken,p as getDefaultRequestOptions,l as getFetch,N as getOnlineEnvironment,m as internalRequest,P as isFederated,D as isOnline,C as normalizeOnlinePortalUrl,K as platformSelf,t as processParams,E as request,e as requiresFormData,$ as revokeToken,d as setDefaultRequestOptions,F as validateAppAccess,h as warn,B as withOptions};
//# sourceMappingURL=request.esm.min.js.map
/* @preserve
* @esri/arcgis-rest-request - v4.0.3 - Apache-2.0
* @esri/arcgis-rest-request - v4.0.4 - Apache-2.0
* Copyright (c) 2017-2022 Esri, Inc.
* Thu Sep 15 2022 20:30:17 GMT+0000 (Coordinated Universal Time)
* Wed Sep 28 2022 19:56:36 GMT+0000 (Coordinated Universal Time)
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).arcgisRest=e.arcgisRest||{})}(this,(function(e){"use strict";function t(e){return Object.keys(e).some((t=>{let r=e[t];if(!r)return!1;r&&r.toParam&&(r=r.toParam());switch(r.constructor.name){case"Array":case"Object":case"Date":case"Function":case"Boolean":case"String":case"Number":return!1;default:return!0}}))}function r(e){const t={};return Object.keys(e).forEach((r=>{var s,n;let o=e[r];if(o&&o.toParam&&(o=o.toParam()),!o&&0!==o&&"boolean"!=typeof o&&"string"!=typeof o)return;let i;switch(o.constructor.name){case"Array":const e=null===(n=null===(s=o[0])||void 0===s?void 0:s.constructor)||void 0===n?void 0:n.name;i="Array"===e?o:"Object"===e?JSON.stringify(o):o.join(",");break;case"Object":i=JSON.stringify(o);break;case"Date":i=o.valueOf();break;case"Function":i=null;break;case"Boolean":i=o+"";break;default:i=o}(i||0===i||"string"==typeof i||Array.isArray(i))&&(t[r]=i)})),t}function s(e,t){return Array.isArray(t)&&t[0]&&Array.isArray(t[0])?t.map((t=>s(e,t))).join("&"):encodeURIComponent(e)+"="+encodeURIComponent(t)}function n(e){const t=r(e);return Object.keys(t).map((e=>s(e,t[e]))).join("&")}const o=globalThis.FormData,i=globalThis.File,a=globalThis.Blob;function c(e,s){const i=t(e)||s,a=r(e);if(i){const e=new o;return Object.keys(a).forEach((t=>{if("undefined"!=typeof Blob&&a[t]instanceof Blob){const r=a.fileName||a[t].name||t;e.append(t,a[t],r)}else e.append(t,a[t])})),e}return n(e)}class h extends Error{constructor(e,t,r,s,n){super(e);const o=new.target.prototype;Object.setPrototypeOf(this,o),e=e||"UNKNOWN_ERROR",t=t||"UNKNOWN_ERROR_CODE",this.name="ArcGISRequestError",this.message="UNKNOWN_ERROR_CODE"===t?e:`${t}: ${e}`,this.originalMessage=e,this.code=t,this.response=r,this.url=s,this.options=n}}function u(e){console&&console.warn&&console.warn.apply(console,[e])}function l(){return Promise.resolve({fetch:globalThis.fetch,Headers:globalThis.Headers,Response:globalThis.Response,Request:globalThis.Request})}const d="@esri/arcgis-rest-js";function p(){return globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS||{httpMethod:"POST",params:{f:"json"}}}class g extends h{constructor(e="AUTHENTICATION_ERROR",t="AUTHENTICATION_ERROR_CODE",r,s,n){super(e,t,r,s,n),this.name="ArcGISAuthError",this.message="AUTHENTICATION_ERROR_CODE"===t?e:`${t}: ${e}`;const o=new.target.prototype;Object.setPrototypeOf(this,o)}retry(e,t=1){let r=0;const s=(n,o)=>{r+=1,e(this.url,this.options).then((e=>{const t=Object.assign(Object.assign({},this.options),{authentication:e});return E(this.url,t)})).then((e=>{n(e)})).catch((e=>{"ArcGISAuthError"===e.name&&r<t?s(n,o):e.name===this.name&&e.message===this.message&&r>=t?o(this):o(e)}))};return new Promise(((e,t)=>{s(e,t)}))}}function f(e,t,r,s,n){if(e.code>=400){const{message:r,code:n}=e;throw new h(r,n,e,t,s)}if(e.error){const{message:r,code:o,messageCode:i}=e.error,a=i||o||"UNKNOWN_ERROR_CODE";if(498===o||499===o)throw n||new g(r,a,e,t,s);throw new h(r,a,e,t,s)}if("failed"===e.status||"failure"===e.status){let r,n="UNKNOWN_ERROR_CODE";try{r=JSON.parse(e.statusMessage).message,n=JSON.parse(e.statusMessage).code}catch(t){r=e.statusMessage||e.message}throw new h(r,n,e,t,s)}return e}function E(e,r){const s=p(),o=Object.assign(Object.assign(Object.assign({httpMethod:"POST"},s),r),{params:Object.assign(Object.assign({},s.params),r.params),headers:Object.assign(Object.assign({},s.headers),r.headers)}),{httpMethod:i,rawResponse:a}=o,g=Object.assign({f:"json"},o.params);let E=null;const m={method:i,signal:o.signal,credentials:o.credentials||"same-origin"};let k;if(o.headers&&o.headers["X-Esri-Auth-Client-Id"]&&e.indexOf("/oauth2/platformSelf")>-1&&(m.credentials="include"),"string"==typeof o.authentication){const e=o.authentication;k={portal:"https://www.arcgis.com/sharing/rest",getToken:()=>Promise.resolve(e)},o.authentication.startsWith("AAPK")||o.suppressWarnings||globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING||(u("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."),globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING=!0)}else k=o.authentication;const w=e;return(k?k.getToken(e).catch((t=>(t.url=e,t.options=o,E=t,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(g.token=r),k&&k.getDomainCredentials&&(m.credentials=k.getDomainCredentials(e));const s={};if("GET"===m.method){g.token&&o.hideToken&&"undefined"==typeof window&&(s["X-Esri-Authorization"]=`Bearer ${g.token}`,delete g.token);const t=""===n(g)?e:e+"?"+n(g);o.maxUrlLength&&t.length>o.maxUrlLength||g.token&&o.hideToken?(m.method="POST",r.length&&o.hideToken&&(g.token=r,delete s["X-Esri-Authorization"])):e=t}const i=new RegExp("/items/.+/updateResources").test(e);return"POST"===m.method&&(m.body=c(g,i)),m.headers=Object.assign(Object.assign({},s),o.headers),("undefined"==typeof window||window&&void 0===window.document)&&!m.headers.referer&&(m.headers.referer=d),t(g)||i||(m.headers["Content-Type"]="application/x-www-form-urlencoded"),globalThis.fetch?globalThis.fetch(e,m):l().then((({fetch:t})=>t(e,m)))})).then((t=>{if(!t.ok){const{status:r,statusText:s}=t;throw new h(s,`HTTP ${r}`,t,e,o)}if(a)return t;switch(g.f){case"json":case"geojson":return t.json();case"html":case"text":return t.text();default:return t.blob()}})).then((t=>{if("json"!==g.f&&"geojson"!==g.f||a)return t;{const r=f(t,w,0,o,E);if(E){const t=e.toLowerCase().split(/\/rest(\/admin)?\/services\//)[0];o.authentication.federatedServers[t]={token:[],expires:new Date(Date.now()+864e5)},E=null}return r}}))}function m(e,t={params:{f:"json"}}){return E(e,t).catch((e=>e instanceof g&&t.authentication&&"string"!=typeof t.authentication&&t.authentication.canRefresh&&t.authentication.refreshCredentials?e.retry((()=>t.authentication.refreshCredentials()),1):Promise.reject(e)))}var k,w;e.ArcGISTokenRequestErrorCodes=void 0,(k=e.ArcGISTokenRequestErrorCodes||(e.ArcGISTokenRequestErrorCodes={})).TOKEN_REFRESH_FAILED="TOKEN_REFRESH_FAILED",k.GENERATE_TOKEN_FOR_SERVER_FAILED="GENERATE_TOKEN_FOR_SERVER_FAILED",k.REFRESH_TOKEN_EXCHANGE_FAILED="REFRESH_TOKEN_EXCHANGE_FAILED",k.NOT_FEDERATED="NOT_FEDERATED",k.UNKNOWN_ERROR_CODE="UNKNOWN_ERROR_CODE";class T extends Error{constructor(t="UNKNOWN_ERROR",r=e.ArcGISTokenRequestErrorCodes.UNKNOWN_ERROR_CODE,s,n,o){super(t);const i=new.target.prototype;Object.setPrototypeOf(this,i),this.name="ArcGISTokenRequestError",this.message=`${r}: ${t}`,this.originalMessage=t,this.code=r,this.response=s,this.url=n,this.options=o}}class _ extends Error{constructor(){super("The user has denied your authorization request.");const e=new.target.prototype;Object.setPrototypeOf(this,e),this.name="ArcGISAccessDeniedError"}}function R(e){return"string"!=typeof e||"/"===(e=e.trim())[e.length-1]&&(e=e.slice(0,-1)),e}function A(e){const[t,r]=e.split("=");return{key:decodeURIComponent(t),value:decodeURIComponent(r)}}function S(e){return!e||e.length<=0?{}:e.replace(/^#/,"").replace(/^\?/,"").split("&").reduce(((e,t)=>{const{key:r,value:s}=A(t);return e[r]=s,e}),{})}e.ErrorTypes=void 0,(w=e.ErrorTypes||(e.ErrorTypes={})).ArcGISRequestError="ArcGISRequestError",w.ArcGISAuthError="ArcGISAuthError",w.ArcGISAccessDeniedError="ArcGISAccessDeniedError",w.ArcGISTokenRequestError="ArcGISTokenRequestError";const O=3e5;function I(e,t){const r=t;return r.rawResponse=!1,m(e,r).then((e=>{const t={token:e.access_token,username:e.username,expires:new Date(Date.now()+1e3*e.expires_in-O),ssl:!0===e.ssl};return e.refresh_token&&(t.refreshToken=e.refresh_token),e.refresh_token_expires_in&&(t.refreshTokenExpires=new Date(Date.now()+1e3*e.refresh_token_expires_in-O)),t}))}class v{constructor(e){this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.token=e.token,this.expires=e.expires,this.portal=e.portal||"https://www.arcgis.com/sharing/rest",this.duration=e.duration||7200}static fromCredentials(e){return new v(e)}getToken(e,t){return this.token&&this.expires&&this.expires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequest||(this._pendingTokenRequest=this.refreshToken(t)),this._pendingTokenRequest)}refreshToken(t){const r=Object.assign({params:{client_id:this.clientId,client_secret:this.clientSecret,grant_type:"client_credentials",expiration:this.duration}},t);return I(`${this.portal}/oauth2/token/`,r).then((e=>(this._pendingTokenRequest=null,this.token=e.token,this.expires=e.expires,e.token))).catch((t=>{throw new T(t.message,e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED,t.response,t.url,t.options)}))}refreshCredentials(){return this.refreshToken().then((()=>this))}}class y{constructor(e){this.portal="https://www.arcgis.com/sharing/rest",this.key=e.key}static fromKey(e){return new y({key:e})}getToken(e){return Promise.resolve(this.key)}}const x=/^https?:\/\/(\S+)\.arcgis\.com.+/;function D(e){return x.test(e)}function U(e){if(!x.test(e))return e;switch(b(e)){case"dev":return"https://devext.arcgis.com/sharing/rest";case"qa":return"https://qaext.arcgis.com/sharing/rest";default:return"https://www.arcgis.com/sharing/rest"}}function b(e){if(!x.test(e))return null;const t=e.match(x)[1].split(".").pop();return t.includes("dev")?"dev":t.includes("qa")?"qa":"production"}function C(e,t){const r=R(U(t)).replace(/https?:\/\//,""),s=R(e).replace(/https?:\/\//,"");return new RegExp(s,"i").test(r)}function N(e,t){const r=D(e),s=D(t),n=b(e),o=b(t);return!(!r||!s||n!==o)}function P(e,t,r="https://www.arcgis.com/sharing/rest"){return m(`${r}/oauth2/validateAppAccess`,{method:"POST",params:{f:"json",client_id:t,token:e}})}function j(e){const t=`${R(e.portal||"https://www.arcgis.com/sharing/rest")}/oauth2/revokeToken/`,r=e.token,s=e.clientId;delete e.portal,delete e.clientId,delete e.token;const n=Object.assign(Object.assign({},e),{httpMethod:"POST",params:{client_id:s,auth_token:r}});return m(t,n).then((e=>{if(!e.success)throw new h("Unable to revoke token",500,e,t,n);return e}))}function G(e,t=window){return!t&&window&&(t=window),t.btoa(String.fromCharCode.apply(null,e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function q(e){!e&&window&&(e=window);return G(e.crypto.getRandomValues(new Uint8Array(32)))}class F{constructor(e){if(this.clientId=e.clientId,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this._username=e.username,this.password=e.password,this._token=e.token,this._tokenExpires=e.tokenExpires,this.portal=e.portal?R(e.portal):"https://www.arcgis.com/sharing/rest",this.ssl=e.ssl,this.provider=e.provider||"arcgis",this.tokenDuration=e.tokenDuration||20160,this.redirectUri=e.redirectUri,this.server=e.server,this.federatedServers={},this.trustedDomains=[],e.server){const t=this.getServerRootUrl(e.server);this.federatedServers[t]={token:e.token,expires:e.tokenExpires}}this._pendingTokenRequests={}}get token(){return this._token}get tokenExpires(){return this._tokenExpires}get refreshToken(){return this._refreshToken}get refreshTokenExpires(){return this._refreshTokenExpires}get username(){return this._username?this._username:this._user&&this._user.username?this._user.username:void 0}get canRefresh(){return!(!this.username||!this.password)||!!(this.clientId&&this.refreshToken&&this.redirectUri)}static beginOAuth2(e,t){!t&&window&&(t=window);const{portal:r,provider:s,clientId:o,expiration:i,redirectUri:a,popup:c,popupWindowFeatures:h,locale:u,params:l,style:d,pkce:p,state:f}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",provider:"arcgis",expiration:20160,popup:!0,popupWindowFeatures:"height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes",locale:"",style:"",pkce:!0},e),E=f||q(t),m=`ARCGIS_REST_JS_AUTH_STATE_${o}`;t.localStorage.setItem(m,E);let k=`${R(r)}/oauth2/authorize`;const w={client_id:o,response_type:p?"code":"token",expiration:i,redirect_uri:a,state:JSON.stringify({id:E,originalUrl:t.location.href}),locale:u,style:d};let T;if("arcgis"!==s&&(k=`${R(r)}/oauth2/social/authorize`,w.socialLoginProviderName=s,w.autoAccountCreateForSocial=!0),p){const e=q(t),r=`ARCGIS_REST_JS_CODE_VERIFIER_${o}`;t.localStorage.setItem(r,e),T=function(e,t=window){if(!t&&window&&(t=window),e&&t.isSecureContext&&t.crypto&&t.crypto.subtle){const r=(new t.TextEncoder).encode(e);return t.crypto.subtle.digest("SHA-256",r).then((e=>G(new Uint8Array(e),t)))}return Promise.resolve(null)}(e,t).then((function(t){w.code_challenge_method=t?"S256":"plain",w.code_challenge=t||e}))}else T=Promise.resolve();return T.then((()=>(k=`${k}?${n(w)}`,l&&(k=`${k}&${n(l)}`),c?new Promise(((e,s)=>{t.addEventListener(`arcgis-rest-js-popup-auth-${o}`,(t=>{if("access_denied"===t.detail.error){const e=new _;return s(e),e}if(t.detail.errorMessage){const e=new g(t.detail.errorMessage,t.detail.error);return s(e),e}e(new F({clientId:o,portal:r,ssl:t.detail.ssl,token:t.detail.token,tokenExpires:t.detail.expires,username:t.detail.username,refreshToken:t.detail.refreshToken,refreshTokenExpires:t.detail.refreshTokenExpires,redirectUri:a}))}),{once:!0}),t.open(k,"oauth-window",h),t.dispatchEvent(new CustomEvent("arcgis-rest-js-popup-auth-start"))})):void(t.location.href=k))))}static completeOAuth2(e,t){!t&&window&&(t=window);const{portal:r,clientId:s,popup:n,pkce:o,redirectUri:i}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",popup:!0,pkce:!0},e),a=`ARCGIS_REST_JS_AUTH_STATE_${s}`,c=t.localStorage.getItem(a),h=S(o?t.location.search.replace(/^\?/,""):t.location.hash.replace(/^#/,"")),u=h&&h.state?JSON.parse(h.state):void 0;function l(e,r,o){return t.localStorage.removeItem(a),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:{error:r,errorMessage:e}})),void t.close()):(o&&t.history.replaceState(t.history.state,"",o),"access_denied"===r?Promise.reject(new _):Promise.reject(new g(e,r)))}function d(e,o){return t.localStorage.removeItem(a),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:Object.assign({},e)})),void t.close()):(t.history.replaceState(t.history.state,"",o),new F({clientId:s,portal:r,ssl:e.ssl,token:e.token,tokenExpires:e.expires,username:e.username,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,redirectUri:i||location.href.replace(location.search,"")}))}if(!c||!u)return l("No authentication state was found, call `ArcGISIdentityManager.beginOAuth2(...)` to start the authentication process.","no-auth-state");if(u.id!==c)return l("Saved client state did not match server sent state.","mismatched-auth-state");if(h.error){const e=h.error;return l(h.error_description||"Unknown error",e,u.originalUrl)}if(o&&h.code){const e=R(`${r}/oauth2/token/`),n=`ARCGIS_REST_JS_CODE_VERIFIER_${s}`,o=t.localStorage.getItem(n);return t.localStorage.removeItem(n),I(e,{httpMethod:"POST",params:{client_id:s,code_verifier:o,grant_type:"authorization_code",redirect_uri:i||location.href.replace(location.search,""),code:h.code}}).then((e=>d(Object.assign(Object.assign({},e),u),u.originalUrl))).catch((e=>l(e.originalMessage,e.code,u.originalUrl)))}return!o&&h.access_token?Promise.resolve(d(Object.assign({token:h.access_token,expires:new Date(Date.now()+1e3*parseInt(h.expires_in,10)),ssl:"true"===h.ssl,username:h.username},u),u.originalUrl)):l("Unknown error","oauth-error",u.originalUrl)}static fromParent(e,t){let r;return!t&&window&&(t=window),new Promise(((s,n)=>{r=e=>{if(e.source===t.parent&&e.data)try{return s(F.parentMessageHandler(e))}catch(e){return n(e)}},t.addEventListener("message",r,!1),t.parent.postMessage({type:"arcgis:auth:requestCredential"},e)})).then((e=>(t.removeEventListener("message",r,!1),e)))}static authorize(e,t){const{portal:r,clientId:s,expiration:o,redirectUri:i,state:a}=Object.assign({portal:"https://arcgis.com/sharing/rest",expiration:20160},e),c={client_id:s,expiration:o,response_type:"code",redirect_uri:i};a&&(c.state=a);const h=`${r}/oauth2/authorize?${n(c)}`;t.writeHead(301,{Location:h}),t.end()}static exchangeAuthorizationCode(t,r){const{portal:s,clientId:n,redirectUri:o}=Object.assign({portal:"https://www.arcgis.com/sharing/rest"},t);return I(`${s}/oauth2/token`,{params:{grant_type:"authorization_code",client_id:n,redirect_uri:o,code:r}}).then((e=>new F({clientId:n,portal:s,ssl:e.ssl,redirectUri:o,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,token:e.token,tokenExpires:e.expires,username:e.username}))).catch((t=>{throw new T(t.message,e.ArcGISTokenRequestErrorCodes.REFRESH_TOKEN_EXCHANGE_FAILED,t.response,t.url,t.options)}))}static deserialize(e){const t=JSON.parse(e);return new F({clientId:t.clientId,refreshToken:t.refreshToken,refreshTokenExpires:t.refreshTokenExpires?new Date(t.refreshTokenExpires):void 0,username:t.username,password:t.password,token:t.token,tokenExpires:t.tokenExpires?new Date(t.tokenExpires):void 0,portal:t.portal,ssl:t.ssl,tokenDuration:t.tokenDuration,redirectUri:t.redirectUri,server:t.server})}static fromCredential(e,t){const r=void 0===e.ssl||e.ssl,s=e.expires||Date.now()+72e5;return t.hasServer?new F({server:e.server,ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)}):new F({portal:R(e.server.includes("sharing/rest")?e.server:e.server+"/sharing/rest"),ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)})}static parentMessageHandler(e){if("arcgis:auth:credential"===e.data.type)return new F(e.data.credential);if("arcgis:auth:error"===e.data.type){const t=new Error(e.data.error.message);throw t.name=e.data.error.name,t}throw new Error("Unknown message type.")}static destroy(e){return j({clientId:e.clientId,portal:e.portal,token:e.refreshToken||e.token})}static fromToken(e){const t=new F(e);return t.getUser().then((()=>t))}static signIn(e){const t=new F(e);return t.getUser().then((()=>t))}toCredential(){return{expires:this.tokenExpires.getTime(),server:this.server||this.portal,ssl:this.ssl,token:this.token,userId:this.username}}getUser(e){if(this._pendingUserRequest)return this._pendingUserRequest;if(this._user)return Promise.resolve(this._user);{const t=`${this.portal}/community/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingUserRequest=m(t,r).then((e=>(this._user=e,this._pendingUserRequest=null,e))),this._pendingUserRequest}}getPortal(e){if(this._pendingPortalRequest)return this._pendingPortalRequest;if(this._portalInfo)return Promise.resolve(this._portalInfo);{const t=`${this.portal}/portals/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingPortalRequest=m(t,r).then((e=>(this._portalInfo=e,this._pendingPortalRequest=null,e))),this._pendingPortalRequest}}getUsername(){return this.username?Promise.resolve(this.username):this.getUser().then((e=>e.username))}getToken(e,t){return N(this.portal,e)||new RegExp(this.portal,"i").test(e)?this.getFreshToken(t):this.getTokenForServer(e,t)}validateAppAccess(e){return this.getToken(this.portal).then((t=>P(t,e)))}toJSON(){return{clientId:this.clientId,refreshToken:this.refreshToken,refreshTokenExpires:this.refreshTokenExpires||void 0,username:this.username,password:this.password,token:this.token,tokenExpires:this.tokenExpires||void 0,portal:this.portal,ssl:this.ssl,tokenDuration:this.tokenDuration,redirectUri:this.redirectUri,server:this.server}}serialize(){return JSON.stringify(this)}enablePostMessageAuth(e,t){!t&&window&&(t=window),this._hostHandler=this.createPostMessageHandler(e),t.addEventListener("message",this._hostHandler,!1)}disablePostMessageAuth(e){!e&&window&&(e=window),e.removeEventListener("message",this._hostHandler,!1)}refreshCredentials(t){return this._user=null,this.username&&this.password?this.refreshWithUsernameAndPassword(t):this.clientId&&this.refreshToken?this.refreshWithRefreshToken():Promise.reject(new T("Unable to refresh token. No refresh token or password present.",e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED))}getServerRootUrl(e){const[t]=R(e).split(/\/rest(\/admin)?\/services(?:\/|#|\?|$)/),[r,s,n]=t.match(/(https?:\/\/)(.+)/),[o,...i]=n.split("/");return`${s}${o.toLowerCase()}/${i.join("/")}`}getDomainCredentials(e){return this.trustedDomains&&this.trustedDomains.length&&this.trustedDomains.some((t=>e.startsWith(t)))?"include":"same-origin"}signOut(){return F.destroy(this)}createPostMessageHandler(e){return t=>{const r=e.indexOf(t.origin)>-1,s="arcgis:auth:requestCredential"===t.data.type,n=this.tokenExpires.getTime()>Date.now();if(r&&s){let e={};if(n){e={type:"arcgis:auth:credential",credential:this.toJSON()}}else e={type:"arcgis:auth:error",error:{name:"tokenExpiredError",message:"Token was expired, and not returned to the child application"}};t.source.postMessage(e,t.origin)}}}getTokenForServer(t,r){const s=this.getServerRootUrl(t),n=this.federatedServers[s];return n&&n.expires&&n.expires.getTime()>Date.now()?Promise.resolve(n.token):(this._pendingTokenRequests[s]||(this._pendingTokenRequests[s]=this.fetchAuthorizedDomains().then((()=>m(`${s}/rest/info`,{credentials:this.getDomainCredentials(t)}).then((n=>{if(n.owningSystemUrl){if(C(n.owningSystemUrl,this.portal))return m(`${n.owningSystemUrl}/sharing/rest/info`,r);throw new T(`${t} is not federated with ${this.portal}.`,e.ArcGISTokenRequestErrorCodes.NOT_FEDERATED)}if(n.authInfo&&void 0!==this.federatedServers[s])return Promise.resolve({authInfo:n.authInfo});throw new T(`${t} is not federated with any portal and is not explicitly trusted.`,e.ArcGISTokenRequestErrorCodes.NOT_FEDERATED)})).then((e=>this.token&&this.tokenExpires.getTime()<Date.now()?this.server?this.refreshCredentials().then((()=>({token:this.token,expires:this.tokenExpires}))):this.refreshCredentials().then((()=>this.generateTokenForServer(e.authInfo.tokenServicesUrl,s))):this.generateTokenForServer(e.authInfo.tokenServicesUrl,s))).then((e=>(this.federatedServers[s]=e,delete this._pendingTokenRequests[s],e.token)))))),this._pendingTokenRequests[s])}generateTokenForServer(t,r){return m(t,{params:{token:this.token,serverUrl:r,expiration:this.tokenDuration}}).then((e=>({token:e.token,expires:new Date(e.expires-3e5)}))).catch((t=>{throw new T(t.message,e.ArcGISTokenRequestErrorCodes.GENERATE_TOKEN_FOR_SERVER_FAILED,t.response,t.url,t.options)}))}getFreshToken(e){return this.token&&!this.tokenExpires||this.token&&this.tokenExpires&&this.tokenExpires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequests[this.portal]||(this._pendingTokenRequests[this.portal]=this.refreshCredentials(e).then((()=>(this._pendingTokenRequests[this.portal]=null,this.token)))),this._pendingTokenRequests[this.portal])}refreshWithUsernameAndPassword(t){const r={username:this.username,password:this.password,expiration:this.tokenDuration,client:"referer",referer:"undefined"!=typeof window&&void 0!==window.document&&window.location&&window.location.origin?window.location.origin:d};return(this.server?m(`${this.getServerRootUrl(this.server)}/rest/info`).then((e=>m(e.authInfo.tokenServicesUrl,Object.assign({params:r},t)))):m(`${this.portal}/generateToken`,Object.assign({params:r},t))).then((e=>(this.updateToken(e.token,new Date(e.expires)),this))).catch((t=>{throw new T(t.message,e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED,t.response,t.url,t.options)}))}refreshWithRefreshToken(t){if(this.refreshToken&&this.refreshTokenExpires&&this.refreshTokenExpires.getTime()-864e5<Date.now())return this.exchangeRefreshToken(t);const r=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,grant_type:"refresh_token"}},t);return I(`${this.portal}/oauth2/token`,r).then((e=>this.updateToken(e.token,e.expires))).catch((t=>{throw new T(t.message,e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED,t.response,t.url,t.options)}))}updateToken(e,t){return this._token=e,this._tokenExpires=t,this}exchangeRefreshToken(t){const r=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,redirect_uri:this.redirectUri,grant_type:"exchange_refresh_token"}},t);return I(`${this.portal}/oauth2/token`,r).then((e=>(this._token=e.token,this._tokenExpires=e.expires,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this))).catch((t=>{throw new T(t.message,e.ArcGISTokenRequestErrorCodes.REFRESH_TOKEN_EXCHANGE_FAILED,t.response,t.url,t.options)}))}fetchAuthorizedDomains(){return this.server||!this.portal?Promise.resolve(this):this.getPortal().then((e=>(e.authorizedCrossOriginDomains&&e.authorizedCrossOriginDomains.length&&(this.trustedDomains=e.authorizedCrossOriginDomains.filter((e=>!e.startsWith("http://"))).map((e=>e.startsWith("https://")?e:`https://${e}`))),this)))}}function $(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManager' instead."),new F(e)}$.beginOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.beginOAuth2' is deprecated. Use 'ArcGISIdentityManager.beginOAuth2' instead."),F.beginOAuth2(...e)},$.completeOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.completeOAuth2()' is deprecated. Use 'ArcGISIdentityManager.completeOAuth2()' instead."),e.length<=1&&console.warn("WARNING:, 'UserSession.completeOAuth2()' is now async and returns a promise the resolves to an instance of `ArcGISIdentityManager`."),F.completeOAuth2(...e)},$.fromParent=function(...e){return console.warn("DEPRECATED:, 'UserSession.fromParent' is deprecated. Use 'ArcGISIdentityManager.fromParent' instead."),F.fromParent(...e)},$.authorize=function(...e){return console.warn("DEPRECATED:, 'UserSession.authorize' is deprecated. Use 'ArcGISIdentityManager.authorize' instead."),F.authorize(...e)},$.exchangeAuthorizationCode=function(...e){return console.warn("DEPRECATED:, 'UserSession.exchangeAuthorizationCode' is deprecated. Use 'ArcGISIdentityManager.exchangeAuthorizationCode' instead."),F.exchangeAuthorizationCode(...e)},$.fromCredential=function(...e){return console.log("DEPRECATED:, 'UserSession.fromCredential' is deprecated. Use 'ArcGISIdentityManager.fromCredential' instead."),console.warn("WARNING:, 'UserSession.fromCredential' now requires a `ServerInfo` object from the JS API as a second parameter."),F.fromCredential(...e)},$.deserialize=function(...e){return console.log("DEPRECATED:, 'UserSession.deserialize' is deprecated. Use 'ArcGISIdentityManager.deserialize' instead."),F.deserialize(...e)},e.ApiKey=function(e){return console.log("DEPRECATED:, 'ApiKey' is deprecated. Use 'ApiKeyManager' instead."),new y(e)},e.ApiKeyManager=y,e.ApplicationCredentialsManager=v,e.ApplicationSession=function(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new v(e)},e.ArcGISAccessDeniedError=_,e.ArcGISAuthError=g,e.ArcGISIdentityManager=F,e.ArcGISRequestError=h,e.ArcGISTokenRequestError=T,e.Blob=a,e.File=i,e.FormData=o,e.NODEJS_DEFAULT_REFERER_HEADER=d,e.UserSession=$,e.appendCustomParams=function(e,t,r){const s=Object.assign(Object.assign({params:{}},r),e);return s.params=t.reduce(((t,r)=>((e[r]||"boolean"==typeof e[r]||"number"==typeof e[r]&&0===e[r])&&(t[r]=e[r]),t)),s.params),["params","httpMethod","rawResponse","authentication","portal","fetch","maxUrlLength","headers"].reduce(((e,t)=>(s[t]&&(e[t]=s[t]),e)),{})},e.canUseOnlineToken=N,e.checkForErrors=f,e.cleanUrl=R,e.decodeParam=A,e.decodeQueryString=S,e.encodeFormData=c,e.encodeParam=s,e.encodeQueryString=n,e.exchangeToken=function(e,t,r="https://www.arcgis.com/sharing/rest"){return m(`${r}/oauth2/exchangeToken`,{method:"POST",params:{f:"json",client_id:t,token:e}}).then((e=>e.token))},e.fetchToken=I,e.getDefaultRequestOptions=p,e.getFetch=l,e.getOnlineEnvironment=b,e.internalRequest=E,e.isFederated=C,e.isOnline=D,e.normalizeOnlinePortalUrl=U,e.platformSelf=function(e,t,r="https://www.arcgis.com/sharing/rest"){return m(`${r}/oauth2/platformSelf?f=json`,{method:"POST",headers:{"X-Esri-Auth-Client-Id":e,"X-Esri-Auth-Redirect-Uri":t},params:{f:"json"}})},e.processParams=r,e.request=m,e.requiresFormData=t,e.revokeToken=j,e.setDefaultRequestOptions=function(e,t){e.authentication&&!t&&u("You should not set `authentication` as a default in a shared environment such as a web server which will process multiple users requests. You can call `setDefaultRequestOptions` with `true` as a second argument to disable this warning."),globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS=e},e.validateAppAccess=P,e.warn=u,e.withOptions=function(e,t){return(...r)=>{const s="object"==typeof r[r.length-1]?Object.assign(Object.assign({},e),r.pop()):e;return t(...r,s)}},Object.defineProperty(e,"__esModule",{value:!0})}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).arcgisRest=e.arcgisRest||{})}(this,(function(e){"use strict";function t(e){return Object.keys(e).some((t=>{let r=e[t];if(!r)return!1;r&&r.toParam&&(r=r.toParam());switch(r.constructor.name){case"Array":case"Object":case"Date":case"Function":case"Boolean":case"String":case"Number":return!1;default:return!0}}))}function r(e){const t={};return Object.keys(e).forEach((r=>{var s,n;let i=e[r];if(i&&i.toParam&&(i=i.toParam()),!i&&0!==i&&"boolean"!=typeof i&&"string"!=typeof i)return;let o;switch(i.constructor.name){case"Array":const e=null===(n=null===(s=i[0])||void 0===s?void 0:s.constructor)||void 0===n?void 0:n.name;o="Array"===e?i:"Object"===e?JSON.stringify(i):i.join(",");break;case"Object":o=JSON.stringify(i);break;case"Date":o=i.valueOf();break;case"Function":o=null;break;case"Boolean":o=i+"";break;default:o=i}(o||0===o||"string"==typeof o||Array.isArray(o))&&(t[r]=o)})),t}function s(e,t){return Array.isArray(t)&&t[0]&&Array.isArray(t[0])?t.map((t=>s(e,t))).join("&"):encodeURIComponent(e)+"="+encodeURIComponent(t)}function n(e){const t=r(e);return Object.keys(t).map((e=>s(e,t[e]))).join("&")}const i=globalThis.FormData,o=globalThis.File,a=globalThis.Blob;function c(e,s){const o=t(e)||s,a=r(e);if(o){const e=new i;return Object.keys(a).forEach((t=>{if("undefined"!=typeof Blob&&a[t]instanceof Blob){const r=a.fileName||a[t].name||t;e.append(t,a[t],r)}else e.append(t,a[t])})),e}return n(e)}class h extends Error{constructor(e,t,r,s,n){super(e);const i=new.target.prototype;Object.setPrototypeOf(this,i),e=e||"UNKNOWN_ERROR",t=t||"UNKNOWN_ERROR_CODE",this.name="ArcGISRequestError",this.message="UNKNOWN_ERROR_CODE"===t?e:`${t}: ${e}`,this.originalMessage=e,this.code=t,this.response=r,this.url=s,this.options=n}}function l(e){console&&console.warn&&console.warn.apply(console,[e])}function u(){return Promise.resolve({fetch:globalThis.fetch,Headers:globalThis.Headers,Response:globalThis.Response,Request:globalThis.Request})}const d="@esri/arcgis-rest-js";function p(){return globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS||{httpMethod:"POST",params:{f:"json"}}}class g extends h{constructor(e="AUTHENTICATION_ERROR",t="AUTHENTICATION_ERROR_CODE",r,s,n){super(e,t,r,s,n),this.name="ArcGISAuthError",this.message="AUTHENTICATION_ERROR_CODE"===t?e:`${t}: ${e}`;const i=new.target.prototype;Object.setPrototypeOf(this,i)}retry(e,t=1){let r=0;const s=(n,i)=>{r+=1,e(this.url,this.options).then((e=>{const t=Object.assign(Object.assign({},this.options),{authentication:e});return f(this.url,t)})).then((e=>{n(e)})).catch((e=>{"ArcGISAuthError"===e.name&&r<t?s(n,i):e.name===this.name&&e.message===this.message&&r>=t?i(this):i(e)}))};return new Promise(((e,t)=>{s(e,t)}))}}function E(e,t,r,s,n){if(e.code>=400){const{message:r,code:n}=e;throw new h(r,n,e,t,s)}if(e.error){const{message:r,code:i,messageCode:o}=e.error,a=o||i||"UNKNOWN_ERROR_CODE";if(498===i||499===i)throw n||new g(r,a,e,t,s);throw new h(r,a,e,t,s)}if("failed"===e.status||"failure"===e.status){let r,n="UNKNOWN_ERROR_CODE";try{r=JSON.parse(e.statusMessage).message,n=JSON.parse(e.statusMessage).code}catch(t){r=e.statusMessage||e.message}throw new h(r,n,e,t,s)}return e}function f(e,r){const s=p(),i=Object.assign(Object.assign(Object.assign({httpMethod:"POST"},s),r),{params:Object.assign(Object.assign({},s.params),r.params),headers:Object.assign(Object.assign({},s.headers),r.headers)}),{httpMethod:o,rawResponse:a}=i,g=Object.assign({f:"json"},i.params);let f=null;const m={method:o,signal:i.signal,credentials:i.credentials||"same-origin"};let T;if(i.headers&&i.headers["X-Esri-Auth-Client-Id"]&&e.indexOf("/oauth2/platformSelf")>-1&&(m.credentials="include"),"string"==typeof i.authentication){const e=i.authentication;T={portal:"https://www.arcgis.com/sharing/rest",getToken:()=>Promise.resolve(e)},i.authentication.startsWith("AAPK")||i.suppressWarnings||globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING||(l("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."),globalThis.ARCGIS_REST_JS_SUPPRESS_TOKEN_WARNING=!0)}else T=i.authentication;const k=e;return(T?T.getToken(e).catch((t=>(t.url=e,t.options=i,f=t,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(g.token=r),T&&T.getDomainCredentials&&(m.credentials=T.getDomainCredentials(e));const s={};if("GET"===m.method){g.token&&i.hideToken&&"undefined"==typeof window&&(s["X-Esri-Authorization"]=`Bearer ${g.token}`,delete g.token);const t=""===n(g)?e:e+"?"+n(g);i.maxUrlLength&&t.length>i.maxUrlLength||g.token&&i.hideToken?(m.method="POST",r.length&&i.hideToken&&(g.token=r,delete s["X-Esri-Authorization"])):e=t}const o=new RegExp("/items/.+/updateResources").test(e);return"POST"===m.method&&(m.body=c(g,o)),m.headers=Object.assign(Object.assign({},s),i.headers),("undefined"==typeof window||window&&void 0===window.document)&&!m.headers.referer&&(m.headers.referer=d),t(g)||o||(m.headers["Content-Type"]="application/x-www-form-urlencoded"),globalThis.fetch?globalThis.fetch(e,m):u().then((({fetch:t})=>t(e,m)))})).then((t=>{if(!t.ok){const{status:r,statusText:s}=t;throw new h(s,`HTTP ${r}`,t,e,i)}if(a)return t;switch(g.f){case"json":case"geojson":return t.json();case"html":case"text":return t.text();default:return t.blob()}})).then((t=>{if("json"!==g.f&&"geojson"!==g.f||a)return t;{const r=E(t,k,0,i,f);if(f){const t=e.toLowerCase().split(/\/rest(\/admin)?\/services\//)[0];i.authentication.federatedServers[t]={token:[],expires:new Date(Date.now()+864e5)},f=null}return r}}))}function m(e,t={params:{f:"json"}}){return f(e,t).catch((e=>e instanceof g&&t.authentication&&"string"!=typeof t.authentication&&t.authentication.canRefresh&&t.authentication.refreshCredentials?e.retry((()=>t.authentication.refreshCredentials()),1):Promise.reject(e)))}var T,k;e.ArcGISTokenRequestErrorCodes=void 0,(T=e.ArcGISTokenRequestErrorCodes||(e.ArcGISTokenRequestErrorCodes={})).TOKEN_REFRESH_FAILED="TOKEN_REFRESH_FAILED",T.GENERATE_TOKEN_FOR_SERVER_FAILED="GENERATE_TOKEN_FOR_SERVER_FAILED",T.REFRESH_TOKEN_EXCHANGE_FAILED="REFRESH_TOKEN_EXCHANGE_FAILED",T.NOT_FEDERATED="NOT_FEDERATED",T.UNKNOWN_ERROR_CODE="UNKNOWN_ERROR_CODE";class w extends Error{constructor(t="UNKNOWN_ERROR",r=e.ArcGISTokenRequestErrorCodes.UNKNOWN_ERROR_CODE,s,n,i){super(t);const o=new.target.prototype;Object.setPrototypeOf(this,o),this.name="ArcGISTokenRequestError",this.message=`${r}: ${t}`,this.originalMessage=t,this.code=r,this.response=s,this.url=n,this.options=i}}class S extends Error{constructor(){super("The user has denied your authorization request.");const e=new.target.prototype;Object.setPrototypeOf(this,e),this.name="ArcGISAccessDeniedError"}}class _ extends Error{constructor(e="Unknown error",t){super(e);const r=new.target.prototype;Object.setPrototypeOf(this,r),this.name="ArcGISJobError",this.message=`${t.status}: ${e}`,this.status=t.status,this.id=t.id,this.jobInfo=t}}function R(e){return"string"!=typeof e||"/"===(e=e.trim())[e.length-1]&&(e=e.slice(0,-1)),e}function O(e){const[t,r]=e.split("=");return{key:decodeURIComponent(t),value:decodeURIComponent(r)}}function A(e){return!e||e.length<=0?{}:e.replace(/^#/,"").replace(/^\?/,"").split("&").reduce(((e,t)=>{const{key:r,value:s}=O(t);return e[r]=s,e}),{})}e.ErrorTypes=void 0,(k=e.ErrorTypes||(e.ErrorTypes={})).ArcGISRequestError="ArcGISRequestError",k.ArcGISAuthError="ArcGISAuthError",k.ArcGISAccessDeniedError="ArcGISAccessDeniedError",k.ArcGISTokenRequestError="ArcGISTokenRequestError";const b=3e5;function I(e,t){const r=t;return r.rawResponse=!1,m(e,r).then((e=>{const t={token:e.access_token,username:e.username,expires:new Date(Date.now()+1e3*e.expires_in-b),ssl:!0===e.ssl};return e.refresh_token&&(t.refreshToken=e.refresh_token),e.refresh_token_expires_in&&(t.refreshTokenExpires=new Date(Date.now()+1e3*e.refresh_token_expires_in-b)),t}))}class v{constructor(e){this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.token=e.token,this.expires=e.expires,this.portal=e.portal||"https://www.arcgis.com/sharing/rest",this.duration=e.duration||7200}static fromCredentials(e){return new v(e)}getToken(e,t){return this.token&&this.expires&&this.expires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequest||(this._pendingTokenRequest=this.refreshToken(t)),this._pendingTokenRequest)}refreshToken(t){const r=Object.assign({params:{client_id:this.clientId,client_secret:this.clientSecret,grant_type:"client_credentials",expiration:this.duration}},t);return I(`${this.portal}/oauth2/token/`,r).then((e=>(this._pendingTokenRequest=null,this.token=e.token,this.expires=e.expires,e.token))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED,t.response,t.url,t.options)}))}refreshCredentials(){return this.refreshToken().then((()=>this))}}class U{constructor(e){this.portal="https://www.arcgis.com/sharing/rest",this.key=e.key}static fromKey(e){return new U({key:e})}getToken(e){return Promise.resolve(this.key)}}const y=/^https?:\/\/(\S+)\.arcgis\.com.+/;function x(e){return y.test(e)}function C(e){if(!y.test(e))return e;switch(D(e)){case"dev":return"https://devext.arcgis.com/sharing/rest";case"qa":return"https://qaext.arcgis.com/sharing/rest";default:return"https://www.arcgis.com/sharing/rest"}}function D(e){if(!y.test(e))return null;const t=e.match(y)[1].split(".").pop();return t.includes("dev")?"dev":t.includes("qa")?"qa":"production"}function j(e,t){const r=R(C(t)).replace(/https?:\/\//,""),s=R(e).replace(/https?:\/\//,"");return new RegExp(s,"i").test(r)}function N(e,t){const r=x(e),s=x(t),n=D(e),i=D(t);return!(!r||!s||n!==i)}function P(e,t,r="https://www.arcgis.com/sharing/rest"){return m(`${r}/oauth2/validateAppAccess`,{method:"POST",params:{f:"json",client_id:t,token:e}})}function F(e){const t=`${R(e.portal||"https://www.arcgis.com/sharing/rest")}/oauth2/revokeToken/`,r=e.token,s=e.clientId;delete e.portal,delete e.clientId,delete e.token;const n=Object.assign(Object.assign({},e),{httpMethod:"POST",params:{client_id:s,auth_token:r}});return m(t,n).then((e=>{if(!e.success)throw new h("Unable to revoke token",500,e,t,n);return e}))}function J(e,t=window){return!t&&window&&(t=window),t.btoa(String.fromCharCode.apply(null,e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function M(e){!e&&window&&(e=window);return J(e.crypto.getRandomValues(new Uint8Array(32)))}class G{constructor(e){if(this.clientId=e.clientId,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this._username=e.username,this.password=e.password,this._token=e.token,this._tokenExpires=e.tokenExpires,this.portal=e.portal?R(e.portal):"https://www.arcgis.com/sharing/rest",this.ssl=e.ssl,this.provider=e.provider||"arcgis",this.tokenDuration=e.tokenDuration||20160,this.redirectUri=e.redirectUri,this.server=e.server,this.federatedServers={},this.trustedDomains=[],e.server){const t=this.getServerRootUrl(e.server);this.federatedServers[t]={token:e.token,expires:e.tokenExpires}}this._pendingTokenRequests={}}get token(){return this._token}get tokenExpires(){return this._tokenExpires}get refreshToken(){return this._refreshToken}get refreshTokenExpires(){return this._refreshTokenExpires}get username(){return this._username?this._username:this._user&&this._user.username?this._user.username:void 0}get canRefresh(){return!(!this.username||!this.password)||!!(this.clientId&&this.refreshToken&&this.redirectUri)}static beginOAuth2(e,t){!t&&window&&(t=window);const{portal:r,provider:s,clientId:i,expiration:o,redirectUri:a,popup:c,popupWindowFeatures:h,locale:l,params:u,style:d,pkce:p,state:E}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",provider:"arcgis",expiration:20160,popup:!0,popupWindowFeatures:"height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes",locale:"",style:"",pkce:!0},e),f=E||M(t),m=`ARCGIS_REST_JS_AUTH_STATE_${i}`;t.localStorage.setItem(m,f);let T=`${R(r)}/oauth2/authorize`;const k={client_id:i,response_type:p?"code":"token",expiration:o,redirect_uri:a,state:JSON.stringify({id:f,originalUrl:t.location.href}),locale:l,style:d};let w;if("arcgis"!==s&&(T=`${R(r)}/oauth2/social/authorize`,k.socialLoginProviderName=s,k.autoAccountCreateForSocial=!0),p){const e=M(t),r=`ARCGIS_REST_JS_CODE_VERIFIER_${i}`;t.localStorage.setItem(r,e),w=function(e,t=window){if(!t&&window&&(t=window),e&&t.isSecureContext&&t.crypto&&t.crypto.subtle){const r=(new t.TextEncoder).encode(e);return t.crypto.subtle.digest("SHA-256",r).then((e=>J(new Uint8Array(e),t)))}return Promise.resolve(null)}(e,t).then((function(t){k.code_challenge_method=t?"S256":"plain",k.code_challenge=t||e}))}else w=Promise.resolve();return w.then((()=>(T=`${T}?${n(k)}`,u&&(T=`${T}&${n(u)}`),c?new Promise(((e,s)=>{t.addEventListener(`arcgis-rest-js-popup-auth-${i}`,(t=>{if("access_denied"===t.detail.error){const e=new S;return s(e),e}if(t.detail.errorMessage){const e=new g(t.detail.errorMessage,t.detail.error);return s(e),e}e(new G({clientId:i,portal:r,ssl:t.detail.ssl,token:t.detail.token,tokenExpires:t.detail.expires,username:t.detail.username,refreshToken:t.detail.refreshToken,refreshTokenExpires:t.detail.refreshTokenExpires,redirectUri:a}))}),{once:!0}),t.open(T,"oauth-window",h),t.dispatchEvent(new CustomEvent("arcgis-rest-js-popup-auth-start"))})):void(t.location.href=T))))}static completeOAuth2(e,t){!t&&window&&(t=window);const{portal:r,clientId:s,popup:n,pkce:i,redirectUri:o}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",popup:!0,pkce:!0},e),a=`ARCGIS_REST_JS_AUTH_STATE_${s}`,c=t.localStorage.getItem(a),h=A(i?t.location.search.replace(/^\?/,""):t.location.hash.replace(/^#/,"")),l=h&&h.state?JSON.parse(h.state):void 0;function u(e,r,i){return t.localStorage.removeItem(a),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:{error:r,errorMessage:e}})),void t.close()):(i&&t.history.replaceState(t.history.state,"",i),"access_denied"===r?Promise.reject(new S):Promise.reject(new g(e,r)))}function d(e,i){return t.localStorage.removeItem(a),n&&t.opener?(t.opener.dispatchEvent(new CustomEvent(`arcgis-rest-js-popup-auth-${s}`,{detail:Object.assign({},e)})),void t.close()):(t.history.replaceState(t.history.state,"",i),new G({clientId:s,portal:r,ssl:e.ssl,token:e.token,tokenExpires:e.expires,username:e.username,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,redirectUri:o||location.href.replace(location.search,"")}))}if(!c||!l)return u("No authentication state was found, call `ArcGISIdentityManager.beginOAuth2(...)` to start the authentication process.","no-auth-state");if(l.id!==c)return u("Saved client state did not match server sent state.","mismatched-auth-state");if(h.error){const e=h.error;return u(h.error_description||"Unknown error",e,l.originalUrl)}if(i&&h.code){const e=R(`${r}/oauth2/token/`),n=`ARCGIS_REST_JS_CODE_VERIFIER_${s}`,i=t.localStorage.getItem(n);return t.localStorage.removeItem(n),I(e,{httpMethod:"POST",params:{client_id:s,code_verifier:i,grant_type:"authorization_code",redirect_uri:o||location.href.replace(location.search,""),code:h.code}}).then((e=>d(Object.assign(Object.assign({},e),l),l.originalUrl))).catch((e=>u(e.originalMessage,e.code,l.originalUrl)))}return!i&&h.access_token?Promise.resolve(d(Object.assign({token:h.access_token,expires:new Date(Date.now()+1e3*parseInt(h.expires_in,10)),ssl:"true"===h.ssl,username:h.username},l),l.originalUrl)):u("Unknown error","oauth-error",l.originalUrl)}static fromParent(e,t){let r;return!t&&window&&(t=window),new Promise(((s,n)=>{r=e=>{if(e.source===t.parent&&e.data)try{return s(G.parentMessageHandler(e))}catch(e){return n(e)}},t.addEventListener("message",r,!1),t.parent.postMessage({type:"arcgis:auth:requestCredential"},e)})).then((e=>(t.removeEventListener("message",r,!1),e)))}static authorize(e,t){const{portal:r,clientId:s,expiration:i,redirectUri:o,state:a}=Object.assign({portal:"https://arcgis.com/sharing/rest",expiration:20160},e),c={client_id:s,expiration:i,response_type:"code",redirect_uri:o};a&&(c.state=a);const h=`${r}/oauth2/authorize?${n(c)}`;t.writeHead(301,{Location:h}),t.end()}static exchangeAuthorizationCode(t,r){const{portal:s,clientId:n,redirectUri:i}=Object.assign({portal:"https://www.arcgis.com/sharing/rest"},t);return I(`${s}/oauth2/token`,{params:{grant_type:"authorization_code",client_id:n,redirect_uri:i,code:r}}).then((e=>new G({clientId:n,portal:s,ssl:e.ssl,redirectUri:i,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,token:e.token,tokenExpires:e.expires,username:e.username}))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.REFRESH_TOKEN_EXCHANGE_FAILED,t.response,t.url,t.options)}))}static deserialize(e){const t=JSON.parse(e);return new G({clientId:t.clientId,refreshToken:t.refreshToken,refreshTokenExpires:t.refreshTokenExpires?new Date(t.refreshTokenExpires):void 0,username:t.username,password:t.password,token:t.token,tokenExpires:t.tokenExpires?new Date(t.tokenExpires):void 0,portal:t.portal,ssl:t.ssl,tokenDuration:t.tokenDuration,redirectUri:t.redirectUri,server:t.server})}static fromCredential(e,t){const r=void 0===e.ssl||e.ssl,s=e.expires||Date.now()+72e5;return t.hasServer?new G({server:e.server,ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)}):new G({portal:R(e.server.includes("sharing/rest")?e.server:e.server+"/sharing/rest"),ssl:r,token:e.token,username:e.userId,tokenExpires:new Date(s)})}static parentMessageHandler(e){if("arcgis:auth:credential"===e.data.type)return new G(e.data.credential);if("arcgis:auth:error"===e.data.type){const t=new Error(e.data.error.message);throw t.name=e.data.error.name,t}throw new Error("Unknown message type.")}static destroy(e){return F({clientId:e.clientId,portal:e.portal,token:e.refreshToken||e.token})}static fromToken(e){const t=new G(e);return t.getUser().then((()=>t))}static signIn(e){const t=new G(e);return t.getUser().then((()=>t))}toCredential(){return{expires:this.tokenExpires.getTime(),server:this.server||this.portal,ssl:this.ssl,token:this.token,userId:this.username}}getUser(e){if(this._pendingUserRequest)return this._pendingUserRequest;if(this._user)return Promise.resolve(this._user);{const t=`${this.portal}/community/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingUserRequest=m(t,r).then((e=>(this._user=e,this._pendingUserRequest=null,e))),this._pendingUserRequest}}getPortal(e){if(this._pendingPortalRequest)return this._pendingPortalRequest;if(this._portalInfo)return Promise.resolve(this._portalInfo);{const t=`${this.portal}/portals/self`,r=Object.assign(Object.assign({httpMethod:"GET",authentication:this},e),{rawResponse:!1});return this._pendingPortalRequest=m(t,r).then((e=>(this._portalInfo=e,this._pendingPortalRequest=null,e))),this._pendingPortalRequest}}getUsername(){return this.username?Promise.resolve(this.username):this.getUser().then((e=>e.username))}getToken(e,t){return N(this.portal,e)||new RegExp(this.portal,"i").test(e)?this.getFreshToken(t):this.getTokenForServer(e,t)}validateAppAccess(e){return this.getToken(this.portal).then((t=>P(t,e)))}toJSON(){return{clientId:this.clientId,refreshToken:this.refreshToken,refreshTokenExpires:this.refreshTokenExpires||void 0,username:this.username,password:this.password,token:this.token,tokenExpires:this.tokenExpires||void 0,portal:this.portal,ssl:this.ssl,tokenDuration:this.tokenDuration,redirectUri:this.redirectUri,server:this.server}}serialize(){return JSON.stringify(this)}enablePostMessageAuth(e,t){!t&&window&&(t=window),this._hostHandler=this.createPostMessageHandler(e),t.addEventListener("message",this._hostHandler,!1)}disablePostMessageAuth(e){!e&&window&&(e=window),e.removeEventListener("message",this._hostHandler,!1)}refreshCredentials(t){return this._user=null,this.username&&this.password?this.refreshWithUsernameAndPassword(t):this.clientId&&this.refreshToken?this.refreshWithRefreshToken():Promise.reject(new w("Unable to refresh token. No refresh token or password present.",e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED))}getServerRootUrl(e){const[t]=R(e).split(/\/rest(\/admin)?\/services(?:\/|#|\?|$)/),[r,s,n]=t.match(/(https?:\/\/)(.+)/),[i,...o]=n.split("/");return`${s}${i.toLowerCase()}/${o.join("/")}`}getDomainCredentials(e){return this.trustedDomains&&this.trustedDomains.length&&this.trustedDomains.some((t=>e.startsWith(t)))?"include":"same-origin"}signOut(){return G.destroy(this)}createPostMessageHandler(e){return t=>{const r=e.indexOf(t.origin)>-1,s="arcgis:auth:requestCredential"===t.data.type,n=this.tokenExpires.getTime()>Date.now();if(r&&s){let e={};if(n){e={type:"arcgis:auth:credential",credential:this.toJSON()}}else e={type:"arcgis:auth:error",error:{name:"tokenExpiredError",message:"Token was expired, and not returned to the child application"}};t.source.postMessage(e,t.origin)}}}getTokenForServer(t,r){const s=this.getServerRootUrl(t),n=this.federatedServers[s];return n&&n.expires&&n.expires.getTime()>Date.now()?Promise.resolve(n.token):(this._pendingTokenRequests[s]||(this._pendingTokenRequests[s]=this.fetchAuthorizedDomains().then((()=>m(`${s}/rest/info`,{credentials:this.getDomainCredentials(t)}).then((n=>{if(n.owningSystemUrl){if(j(n.owningSystemUrl,this.portal))return m(`${n.owningSystemUrl}/sharing/rest/info`,r);throw new w(`${t} is not federated with ${this.portal}.`,e.ArcGISTokenRequestErrorCodes.NOT_FEDERATED)}if(n.authInfo&&void 0!==this.federatedServers[s])return Promise.resolve({authInfo:n.authInfo});throw new w(`${t} is not federated with any portal and is not explicitly trusted.`,e.ArcGISTokenRequestErrorCodes.NOT_FEDERATED)})).then((e=>this.token&&this.tokenExpires.getTime()<Date.now()?this.server?this.refreshCredentials().then((()=>({token:this.token,expires:this.tokenExpires}))):this.refreshCredentials().then((()=>this.generateTokenForServer(e.authInfo.tokenServicesUrl,s))):this.generateTokenForServer(e.authInfo.tokenServicesUrl,s))).then((e=>(this.federatedServers[s]=e,delete this._pendingTokenRequests[s],e.token)))))),this._pendingTokenRequests[s])}generateTokenForServer(t,r){return m(t,{params:{token:this.token,serverUrl:r,expiration:this.tokenDuration}}).then((e=>({token:e.token,expires:new Date(e.expires-3e5)}))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.GENERATE_TOKEN_FOR_SERVER_FAILED,t.response,t.url,t.options)}))}getFreshToken(e){return this.token&&!this.tokenExpires||this.token&&this.tokenExpires&&this.tokenExpires.getTime()>Date.now()?Promise.resolve(this.token):(this._pendingTokenRequests[this.portal]||(this._pendingTokenRequests[this.portal]=this.refreshCredentials(e).then((()=>(this._pendingTokenRequests[this.portal]=null,this.token)))),this._pendingTokenRequests[this.portal])}refreshWithUsernameAndPassword(t){const r={username:this.username,password:this.password,expiration:this.tokenDuration,client:"referer",referer:"undefined"!=typeof window&&void 0!==window.document&&window.location&&window.location.origin?window.location.origin:d};return(this.server?m(`${this.getServerRootUrl(this.server)}/rest/info`).then((e=>m(e.authInfo.tokenServicesUrl,Object.assign({params:r},t)))):m(`${this.portal}/generateToken`,Object.assign({params:r},t))).then((e=>(this.updateToken(e.token,new Date(e.expires)),this))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED,t.response,t.url,t.options)}))}refreshWithRefreshToken(t){if(this.refreshToken&&this.refreshTokenExpires&&this.refreshTokenExpires.getTime()-864e5<Date.now())return this.exchangeRefreshToken(t);const r=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,grant_type:"refresh_token"}},t);return I(`${this.portal}/oauth2/token`,r).then((e=>this.updateToken(e.token,e.expires))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.TOKEN_REFRESH_FAILED,t.response,t.url,t.options)}))}updateToken(e,t){return this._token=e,this._tokenExpires=t,this}exchangeRefreshToken(t){const r=Object.assign({params:{client_id:this.clientId,refresh_token:this.refreshToken,redirect_uri:this.redirectUri,grant_type:"exchange_refresh_token"}},t);return I(`${this.portal}/oauth2/token`,r).then((e=>(this._token=e.token,this._tokenExpires=e.expires,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this))).catch((t=>{throw new w(t.message,e.ArcGISTokenRequestErrorCodes.REFRESH_TOKEN_EXCHANGE_FAILED,t.response,t.url,t.options)}))}fetchAuthorizedDomains(){return this.server||!this.portal?Promise.resolve(this):this.getPortal().then((e=>(e.authorizedCrossOriginDomains&&e.authorizedCrossOriginDomains.length&&(this.trustedDomains=e.authorizedCrossOriginDomains.filter((e=>!e.startsWith("http://"))).map((e=>e.startsWith("https://")?e:`https://${e}`))),this)))}}function q(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManager' instead."),new G(e)}var $;q.beginOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.beginOAuth2' is deprecated. Use 'ArcGISIdentityManager.beginOAuth2' instead."),G.beginOAuth2(...e)},q.completeOAuth2=function(...e){return console.warn("DEPRECATED:, 'UserSession.completeOAuth2()' is deprecated. Use 'ArcGISIdentityManager.completeOAuth2()' instead."),e.length<=1&&console.warn("WARNING:, 'UserSession.completeOAuth2()' is now async and returns a promise the resolves to an instance of `ArcGISIdentityManager`."),G.completeOAuth2(...e)},q.fromParent=function(...e){return console.warn("DEPRECATED:, 'UserSession.fromParent' is deprecated. Use 'ArcGISIdentityManager.fromParent' instead."),G.fromParent(...e)},q.authorize=function(...e){return console.warn("DEPRECATED:, 'UserSession.authorize' is deprecated. Use 'ArcGISIdentityManager.authorize' instead."),G.authorize(...e)},q.exchangeAuthorizationCode=function(...e){return console.warn("DEPRECATED:, 'UserSession.exchangeAuthorizationCode' is deprecated. Use 'ArcGISIdentityManager.exchangeAuthorizationCode' instead."),G.exchangeAuthorizationCode(...e)},q.fromCredential=function(...e){return console.log("DEPRECATED:, 'UserSession.fromCredential' is deprecated. Use 'ArcGISIdentityManager.fromCredential' instead."),console.warn("WARNING:, 'UserSession.fromCredential' now requires a `ServerInfo` object from the JS API as a second parameter."),G.fromCredential(...e)},q.deserialize=function(...e){return console.log("DEPRECATED:, 'UserSession.deserialize' is deprecated. Use 'ArcGISIdentityManager.deserialize' instead."),G.deserialize(...e)},e.JOB_STATUSES=void 0,($=e.JOB_STATUSES||(e.JOB_STATUSES={})).Success="Succeeded",$.Failed="Failed",$.Waiting="Waiting",$.Cancelled="Cancelled",$.Cancelling="Cancelling",$.New="New",$.Executing="Executing",$.Submitted="Submitted",$.Failure="Failure",$.TimedOut="TimedOut",$.Error="Error",$.Status="Etatus",$.Unknown="Unknown";const H={pollingRate:2e3,startMonitoring:!1};class z{constructor(t){this.executePoll=async()=>{let t;try{t=await this.getJobInfo()}catch(t){return void this.emitter.emit(e.JOB_STATUSES.Error,t)}this.emitter.emit(e.JOB_STATUSES.Status,t),this.emitter.emit(t.status,t)};const{url:r,id:s,pollingRate:n,authentication:i}=Object.assign(Object.assign({},H),t);var o;this.url=r,this.id=s,this.authentication=i,this._pollingRate=n,this.emitter={all:o=o||new Map,on:function(e,t){var r=o.get(e);r?r.push(t):o.set(e,[t])},off:function(e,t){var r=o.get(e);r&&(t?r.splice(r.indexOf(t)>>>0,1):o.set(e,[]))},emit:function(e,t){var r=o.get(e);r&&r.slice().map((function(e){e(t)})),(r=o.get("*"))&&r.slice().map((function(r){r(e,t)}))}},t.startMonitoring&&this.startEventMonitoring(n)}static deserialize(e,t){const r=Object.assign(Object.assign(Object.assign({},H),JSON.parse(e)),t);return m(`${r.url}/jobs/${r.id}`,{authentication:r.authentication}).then((()=>new z(r)))}static fromExistingJob(e){const t=Object.assign(Object.assign({},H),e);return m(`${R(t.url.replace(/\/submitJob\/?/,""))}/jobs/${t.id}`,{authentication:t.authentication}).then((()=>new z(t)))}static submitJob(e){const{url:t,params:r,authentication:s,pollingRate:n,startMonitoring:i}=Object.assign(Object.assign({},H),e),o=R(t.replace(/\/submitJob\/?/,""));return m(o+"/submitJob",{params:r,authentication:s}).then((e=>new z({url:o,authentication:s,id:e.jobId,startMonitoring:i,pollingRate:n})))}get jobUrl(){return`${this.url}/jobs/${this.id}`}get isMonitoring(){return!!this.setIntervalHandler}get pollingRate(){return this._pollingRate}set pollingRate(e){this.stopEventMonitoring(),this.startEventMonitoring(e)}getJobInfo(){return m(this.jobUrl,{authentication:this.authentication}).then((t=>{const r=Object.assign({id:t.jobId,status:void 0},t);switch(delete r.jobId,delete r.jobStatus,t.jobStatus){case"esriJobCancelled":r.status=e.JOB_STATUSES.Cancelled;break;case"esriJobCancelling":r.status=e.JOB_STATUSES.Cancelling;break;case"esriJobNew":r.status=e.JOB_STATUSES.New;break;case"esriJobWaiting":r.status=e.JOB_STATUSES.Waiting;break;case"esriJobExecuting":r.status=e.JOB_STATUSES.Executing;break;case"esriJobSubmitted":r.status=e.JOB_STATUSES.Submitted;break;case"esriJobTimedOut":r.status=e.JOB_STATUSES.TimedOut;break;case"esriJobFailed":r.status=e.JOB_STATUSES.Failed;break;case"expectedFailure":r.status=e.JOB_STATUSES.Failure;break;case"esriJobSucceeded":r.status=e.JOB_STATUSES.Success}return r}))}on(e,t){this.emitter.on(e,t)}once(e,t){const r=s=>{this.emitter.off(e,r),t(s)};this.emitter.on(e,r),t.__arcgis_job_once_original_function__=r}off(e,t){t.__arcgis_job_once_original_function__?this.emitter.off(e,t.__arcgis_job_once_original_function__):this.emitter.off(e,t)}async getResult(e){return this.waitForCompletion().then((t=>m(this.jobUrl+"/"+t.results[e].paramUrl,{authentication:this.authentication})))}toJSON(){return{id:this.id,url:this.url,startMonitoring:this.isMonitoring,pollingRate:this.pollingRate}}serialize(){return JSON.stringify(this)}async waitForCompletion(){const t=await this.getJobInfo();return t.status===e.JOB_STATUSES.Success?Promise.resolve(t):t.status===e.JOB_STATUSES.Cancelling||t.status===e.JOB_STATUSES.Cancelled||t.status===e.JOB_STATUSES.Failed||t.status===e.JOB_STATUSES.Failure||t.status===e.JOB_STATUSES.TimedOut?(this.stopInternalEventMonitoring(),Promise.reject(new _("Job cancelled or failed.",t))):new Promise(((t,r)=>{this.startInternalEventMonitoring(),this.once(e.JOB_STATUSES.Cancelled,(e=>{this.stopInternalEventMonitoring(),r(new _("Job cancelled.",e))})),this.once(e.JOB_STATUSES.TimedOut,(e=>{this.stopInternalEventMonitoring(),r(new _("Job timed out.",e))})),this.once(e.JOB_STATUSES.Failed,(e=>{this.stopInternalEventMonitoring(),r(new _("Job failed.",e))})),this.once(e.JOB_STATUSES.Success,(e=>{this.stopInternalEventMonitoring(),t(e)}))}))}async getAllResults(){return this.waitForCompletion().then((e=>{const t=Object.keys(e.results),r=t.map((t=>m(this.jobUrl+"/"+e.results[t].paramUrl,{authentication:this.authentication}).then((e=>e))));return Promise.all(r).then((e=>t.reduce(((r,s,n)=>(r[t[n]]=e[n],r)),{})))}))}cancelJob(){return m(this.jobUrl+"/cancel",{authentication:this.authentication,params:{id:this.id,returnMessages:!1}}).then((e=>(this.emitter.emit("cancelled",e),e)))}startInternalEventMonitoring(e=H.pollingRate){this._pollingRate=e,this.isMonitoring||(this.setIntervalHandler=setInterval(this.executePoll,this.pollingRate))}stopInternalEventMonitoring(){this.isMonitoring&&!this.didUserEnableMonitoring&&clearTimeout(this.setIntervalHandler)}startEventMonitoring(e=H.pollingRate){this._pollingRate=e,this.didUserEnableMonitoring=!0,this.isMonitoring||(this.setIntervalHandler=setInterval(this.executePoll,this.pollingRate))}stopEventMonitoring(){this.isMonitoring&&this.didUserEnableMonitoring&&clearTimeout(this.setIntervalHandler)}}e.ApiKey=function(e){return console.log("DEPRECATED:, 'ApiKey' is deprecated. Use 'ApiKeyManager' instead."),new U(e)},e.ApiKeyManager=U,e.ApplicationCredentialsManager=v,e.ApplicationSession=function(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new v(e)},e.ArcGISAccessDeniedError=S,e.ArcGISAuthError=g,e.ArcGISIdentityManager=G,e.ArcGISJobError=_,e.ArcGISRequestError=h,e.ArcGISTokenRequestError=w,e.Blob=a,e.File=o,e.FormData=i,e.Job=z,e.NODEJS_DEFAULT_REFERER_HEADER=d,e.UserSession=q,e.appendCustomParams=function(e,t,r){const s=Object.assign(Object.assign({params:{}},r),e);return s.params=t.reduce(((t,r)=>((e[r]||"boolean"==typeof e[r]||"number"==typeof e[r]&&0===e[r])&&(t[r]=e[r]),t)),s.params),["params","httpMethod","rawResponse","authentication","portal","fetch","maxUrlLength","headers"].reduce(((e,t)=>(s[t]&&(e[t]=s[t]),e)),{})},e.canUseOnlineToken=N,e.checkForErrors=E,e.cleanUrl=R,e.decodeParam=O,e.decodeQueryString=A,e.encodeFormData=c,e.encodeParam=s,e.encodeQueryString=n,e.exchangeToken=function(e,t,r="https://www.arcgis.com/sharing/rest"){return m(`${r}/oauth2/exchangeToken`,{method:"POST",params:{f:"json",client_id:t,token:e}}).then((e=>e.token))},e.fetchToken=I,e.getDefaultRequestOptions=p,e.getFetch=u,e.getOnlineEnvironment=D,e.internalRequest=f,e.isFederated=j,e.isOnline=x,e.normalizeOnlinePortalUrl=C,e.platformSelf=function(e,t,r="https://www.arcgis.com/sharing/rest"){return m(`${r}/oauth2/platformSelf?f=json`,{method:"POST",headers:{"X-Esri-Auth-Client-Id":e,"X-Esri-Auth-Redirect-Uri":t},params:{f:"json"}})},e.processParams=r,e.request=m,e.requiresFormData=t,e.revokeToken=F,e.setDefaultRequestOptions=function(e,t){e.authentication&&!t&&l("You should not set `authentication` as a default in a shared environment such as a web server which will process multiple users requests. You can call `setDefaultRequestOptions` with `true` as a second argument to disable this warning."),globalThis.DEFAULT_ARCGIS_REQUEST_OPTIONS=e},e.validateAppAccess=P,e.warn=l,e.withOptions=function(e,t){return(...r)=>{const s="object"==typeof r[r.length-1]?Object.assign(Object.assign({},e),r.pop()):e;return t(...r,s)}},Object.defineProperty(e,"__esModule",{value:!0})}));
//# sourceMappingURL=request.umd.min.js.map

@@ -11,2 +11,3 @@ "use strict";

(0, tslib_1.__exportStar)(require("./utils/ArcGISAccessDeniedError.js"), exports);
(0, tslib_1.__exportStar)(require("./utils/ArcGISJobError.js"), exports);
(0, tslib_1.__exportStar)(require("./utils/clean-url.js"), exports);

@@ -40,2 +41,3 @@ (0, tslib_1.__exportStar)(require("./utils/encode-form-data.js"), exports);

(0, tslib_1.__exportStar)(require("./revoke-token.js"), exports);
(0, tslib_1.__exportStar)(require("./job.js"), exports);
(0, tslib_1.__exportStar)(require("./utils/with-options.js"), exports);

@@ -48,4 +50,5 @@ (0, tslib_1.__exportStar)(require("./types/feature.js"), exports);

(0, tslib_1.__exportStar)(require("./types/user.js"), exports);
(0, tslib_1.__exportStar)(require("./types/job-statuses.js"), exports);
(0, tslib_1.__exportStar)(require("@esri/arcgis-rest-fetch"), exports);
(0, tslib_1.__exportStar)(require("@esri/arcgis-rest-form-data"), exports);
//# sourceMappingURL=index.js.map

@@ -6,2 +6,3 @@ export * from "./request.js";

export * from "./utils/ArcGISAccessDeniedError.js";
export * from "./utils/ArcGISJobError.js";
export * from "./utils/clean-url.js";

@@ -35,2 +36,3 @@ export * from "./utils/encode-form-data.js";

export * from "./revoke-token.js";
export * from "./job.js";
export * from "./utils/with-options.js";

@@ -43,3 +45,4 @@ export * from "./types/feature.js";

export * from "./types/user.js";
export * from "./types/job-statuses.js";
export * from "@esri/arcgis-rest-fetch";
export * from "@esri/arcgis-rest-form-data";

@@ -8,2 +8,3 @@ /* Copyright (c) 2018-2019 Environmental Systems Research Institute, Inc.

export * from "./utils/ArcGISAccessDeniedError.js";
export * from "./utils/ArcGISJobError.js";
export * from "./utils/clean-url.js";

@@ -37,2 +38,3 @@ export * from "./utils/encode-form-data.js";

export * from "./revoke-token.js";
export * from "./job.js";
export * from "./utils/with-options.js";

@@ -45,4 +47,5 @@ export * from "./types/feature.js";

export * from "./types/user.js";
export * from "./types/job-statuses.js";
export * from "@esri/arcgis-rest-fetch";
export * from "@esri/arcgis-rest-form-data";
//# sourceMappingURL=index.js.map
{
"name": "@esri/arcgis-rest-request",
"version": "4.0.4",
"version": "4.1.0",
"description": "Common methods and utilities for @esri/arcgis-rest-js packages.",

@@ -49,2 +49,3 @@ "license": "Apache-2.0",

"@esri/arcgis-rest-form-data": "^4.0.0",
"mitt": "^3.0.0",
"tslib": "^2.3.1"

@@ -74,3 +75,6 @@ },

]
},
"devDependencies": {
"@types/serialize-javascript": "^5.0.2"
}
}

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc