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.0-beta.4 to 4.0.0-beta.5

6

dist/bundled/request.esm.min.js
/* @preserve
* @esri/arcgis-rest-request - v4.0.0-beta.3 - Apache-2.0
* @esri/arcgis-rest-request - v4.0.0-beta.4 - Apache-2.0
* Copyright (c) 2017-2022 Esri, Inc.
* Mon Mar 14 2022 21:04:42 GMT+0000 (Coordinated Universal Time)
* Wed Mar 16 2022 17:43:24 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 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 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 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 p(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 d(){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}`}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 k(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 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||"GWM_0003"===o||400===i&&"Unable to generate token."===r)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 k(t,r){const n=d(),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,p=Object.assign({f:"json"},i.params);let g=null;const k={method:o,credentials:i.credentials||"same-origin"};let m;if(i.headers&&i.headers["X-Esri-Auth-Client-Id"]&&t.indexOf("/oauth2/platformSelf")>-1&&(k.credentials="include"),"string"==typeof i.authentication){const e=i.authentication;m={portal:"https://www.arcgis.com/sharing/rest",getToken:()=>Promise.resolve(e)},i.authentication.startsWith("AAPK")||i.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 m=i.authentication;const w=t;return(m?m.getToken(t).catch((e=>(e.url=t,e.options=i,g=e,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(p.token=r),m&&m.getDomainCredentials&&(k.credentials=m.getDomainCredentials(t));const n={};if("GET"===k.method){p.token&&i.hideToken&&"undefined"==typeof window&&(n["X-Esri-Authorization"]=`Bearer ${p.token}`,delete p.token);const e=""===s(p)?t:t+"?"+s(p);i.maxUrlLength&&e.length>i.maxUrlLength||p.token&&i.hideToken?(k.method="POST",r.length&&i.hideToken&&(p.token=r,delete n["X-Esri-Authorization"])):t=e}const o=new RegExp("/items/.+/updateResources").test(t);return"POST"===k.method&&(k.body=a(p,o)),k.headers=Object.assign(Object.assign({},n),i.headers),"undefined"!=typeof window||k.headers.referer||(k.headers.referer="@esri/arcgis-rest-js"),e(p)||o||(k.headers["Content-Type"]="application/x-www-form-urlencoded"),globalThis.fetch?globalThis.fetch(t,k):l().then((({fetch:e})=>e(t,k)))})).then((e=>{if(!e.ok){const{status:r,statusText:s}=e;throw new h(s,`HTTP ${r}`,e,t,i)}if(u)return e;switch(p.f){case"json":case"geojson":return e.json();case"html":case"text":return e.text();default:return e.blob()}})).then((e=>{if("json"!==p.f&&"geojson"!==p.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 m(e,t={params:{f:"json"}}){return k(e,t).catch((e=>e instanceof g&&498===e.code&&"498: Invalid token."===e.message&&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])&&(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)),{})}class T extends Error{constructor(){super("The user has denied your authorization request.");const e=new.target.prototype;Object.setPrototypeOf(this,e),this.name="ArcGISAccessDeniedError"}}function _(e){return"string"!=typeof e||"/"===(e=e.trim())[e.length-1]&&(e=e.slice(0,-1)),e}function E(e){const[t,r]=e.split("=");return{key:decodeURIComponent(t),value:decodeURIComponent(r)}}function R(e){return!e||e.length<=0?{}:e.replace(/^#/,"").replace(/^\?/,"").split("&").reduce(((e,t)=>{const{key:r,value:s}=E(t);return e[r]=s,e}),{})}var x;!function(e){e.ArcGISRequestError="ArcGISRequestError",e.ArcGISAuthError="ArcGISAuthError",e.ArcGISAccessDeniedError="ArcGISAccessDeniedError"}(x||(x={}));function O(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-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 S{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 S(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 O(`${this.portal}/oauth2/token/`,t).then((e=>(this._pendingTokenRequest=null,this.token=e.token,this.expires=e.expires,e.token)))}refreshCredentials(){return this.refreshToken().then((()=>this))}}function v(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new S(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 I(e){return console.log("DEPRECATED:, 'ApiKey' is deprecated. Use 'ApiKeyManager' instead."),new y(e)}function A(e,t){const r=t;return"undefined"!=typeof window&&window.location&&window.location.host?r.params.referer=window.location.host:r.params.referer="@esri/arcgis-rest-js",m(e,r)}const b=/^https?:\/\/(\S+)\.arcgis\.com.+/;function D(e){return b.test(e)}function U(e){if(!b.test(e))return e;switch(j(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 j(e){if(!b.test(e))return null;const t=e.match(b)[1].split(".").pop();return t.includes("dev")?"dev":t.includes("qa")?"qa":"production"}function P(e,t){const r=_(U(t)).replace(/https?:\/\//,""),s=_(e).replace(/https?:\/\//,"");return new RegExp(s,"i").test(r)}function C(e,t){const r=D(e),s=D(t),n=j(e),i=j(t);return!(!r||!s||n!==i)}function $(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 N(e){const t=`${_(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 q(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 q(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?_(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.refreshTokenTTL=e.refreshTokenTTL||20160,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)}static beginOAuth2(e,t){!t&&window&&(t=window);const{portal:r,provider:n,clientId:i,expiration:o,redirectUri:a,popup:h,popupWindowFeatures:c,locale:l,params:u,style:p,pkce:d}=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",state:e.clientId,locale:"",style:"",pkce:!0},e),f=M(t),k=`ARCGIS_REST_JS_AUTH_STATE_${i}`;t.localStorage.setItem(k,f);let m=`${_(r)}/oauth2/authorize`;const w={client_id:i,response_type:d?"code":"token",expiration:o,redirect_uri:a,state:JSON.stringify({id:f,originalUrl:t.location.href}),locale:l,style:p};let E;if("arcgis"!==n&&(m=`${_(r)}/oauth2/social/authorize`,w.socialLoginProviderName=n,w.autoAccountCreateForSocial=!0),d){const e=M(t),r=`ARCGIS_REST_JS_CODE_VERIFIER_${i}`;t.localStorage.setItem(r,e),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=>q(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 E=Promise.resolve();return E.then((()=>(m=`${m}?${s(w)}`,u&&(m=`${m}&${s(u)}`),h?new Promise(((e,s)=>{t.addEventListener(`arcgis-rest-js-popup-auth-${i}`,(t=>{if("access_denied"===t.detail.error){const e=new T;return s(e),e}if(t.detail.error){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}))}),{once:!0}),t.open(m,"oauth-window",c),t.dispatchEvent(new CustomEvent("arcgis-rest-js-popup-auth-start"))})):void(t.location.href=m))))}static completeOAuth2(e,t){!t&&window&&(t=window);const{portal:r,clientId:s,popup:n,pkce:i}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",popup:!0,pkce:!0},e),o=`ARCGIS_REST_JS_AUTH_STATE_${s}`,a=t.localStorage.getItem(o),h=R(i?t.location.search.replace(/^\?/,""):t.location.hash.replace(/^#/,"")),c=h&&h.state?JSON.parse(h.state):void 0;function l(e,r,i){return t.localStorage.removeItem(o),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 T):Promise.reject(new g(e,r)))}function u(e,i){return t.localStorage.removeItem(o),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}))}if(!a||!c)return l("No authentication state was found, call `ArcGISIdentityManager.beginOAuth2(...)` to start the authentication process.","no-auth-state");if(c.id!==a)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,c.originalUrl)}if(i&&h.code){const e=_(`${r}/oauth2/token/`),n=`ARCGIS_REST_JS_CODE_VERIFIER_${s}`,i=t.localStorage.getItem(n);return t.localStorage.removeItem(n),O(e,{httpMethod:"POST",params:{client_id:s,code_verifier:i,grant_type:"authorization_code",redirect_uri:location.href.replace(location.search,""),code:h.code}}).then((e=>u(Object.assign(Object.assign({},e),c),c.originalUrl))).catch((e=>l(e.message,e.error,c.originalUrl)))}return!i&&h.access_token?Promise.resolve(u(Object.assign({token:h.access_token,expires:new Date(Date.now()+1e3*parseInt(h.expires_in,10)),ssl:"true"===h.ssl,username:h.username},c),c.originalUrl)):l("Unknown error","oauth-error",c.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:n,redirectUri:i}=Object.assign({portal:"https://arcgis.com/sharing/rest",expiration:20160},e);t.writeHead(301,{Location:`${r}/oauth2/authorize?client_id=${s}&expiration=${n}&response_type=code&redirect_uri=${encodeURIComponent(i)}`}),t.end()}static exchangeAuthorizationCode(e,t){const{portal:r,clientId:s,redirectUri:n,refreshTokenTTL:i}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",refreshTokenTTL:20160},e);return O(`${r}/oauth2/token`,{params:{grant_type:"authorization_code",client_id:s,redirect_uri:n,code:t}}).then((e=>new G({clientId:s,portal:r,ssl:e.ssl,redirectUri:n,refreshToken:e.refreshToken,refreshTokenTTL:i,refreshTokenExpires:new Date(Date.now()+60*(i-1)*1e3),token:e.token,tokenExpires:e.expires,username:e.username})))}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,refreshTokenTTL:t.refreshTokenTTL,server:t.server})}static fromCredential(e){const t=void 0===e.ssl||e.ssl,r=e.expires||Date.now()+72e5;return new G({portal:e.server.includes("sharing/rest")?e.server:e.server+"/sharing/rest",ssl:t,token:e.token,username:e.userId,tokenExpires:new Date(r)})}static parentMessageHandler(e){if("arcgis:auth:credential"===e.data.type)return G.fromCredential(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 N({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.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 C(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=>$(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,refreshTokenTTL:this.refreshTokenTTL,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 g("Unable to refresh token."))}getServerRootUrl(e){const[t]=_(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){const t=this.toCredential();t.server=t.server.replace("/sharing/rest",""),e={type:"arcgis:auth:credential",credential:t}}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((()=>m(`${r}/rest/info`,{credentials:this.getDomainCredentials(e)}).then((s=>{if(s.owningSystemUrl){if(P(s.owningSystemUrl,this.portal))return m(`${s.owningSystemUrl}/sharing/rest/info`,t);throw new g(`${e} is not federated with ${this.portal}.`,"NOT_FEDERATED")}if(s.authInfo&&void 0!==this.federatedServers[r])return Promise.resolve({authInfo:s.authInfo});throw new g(`${e} is not federated with any portal and is not explicitly trusted.`,"NOT_FEDERATED")})).then((e=>e.authInfo.tokenServicesUrl)).then((t=>this.token&&this.tokenExpires.getTime()>Date.now()?A(t,{params:{token:this.token,serverUrl:e,expiration:this.tokenDuration,client:"referer"}}):A(t,{params:{username:this.username,password:this.password,expiration:this.tokenDuration,client:"referer"}}).then((e=>(this.updateToken(e.token,new Date(e.expires)),e))))).then((e=>(this.federatedServers[r]={expires:new Date(e.expires),token:e.token},delete this._pendingTokenRequests[r],e.token)))))),this._pendingTokenRequests[r])}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((e=>(this._pendingTokenRequests[this.portal]=null,e.token)))),this._pendingTokenRequests[this.portal])}refreshWithUsernameAndPassword(e){const t=Object.assign({params:{username:this.username,password:this.password,expiration:this.tokenDuration}},e);return A(`${this.portal}/generateToken`,t).then((e=>(this.updateToken(e.token,new Date(e.expires)),this)))}refreshWithRefreshToken(e){if(this.refreshToken&&this.refreshTokenExpires&&this.refreshTokenExpires.getTime()<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 O(`${this.portal}/oauth2/token`,t).then((e=>this.updateToken(e.token,e.expires)))}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 O(`${this.portal}/oauth2/token`,t).then((e=>(this._token=e.token,this._tokenExpires=e.expires,this._refreshToken=e.refreshToken,this._refreshTokenExpires=new Date(Date.now()+60*(this.refreshTokenTTL-1)*1e3),this)))}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 L(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManagerOptions' instead."),new G(e)}function W(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))}function z(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"}})}export{I as ApiKey,y as ApiKeyManager,S as ApplicationCredentialsManager,v as ApplicationSession,T as ArcGISAccessDeniedError,g as ArcGISAuthError,G as ArcGISIdentityManager,h as ArcGISRequestError,o as Blob,x as ErrorTypes,i as File,n as FormData,u as NODEJS_DEFAULT_REFERER_HEADER,L as UserSession,w as appendCustomParams,C as canUseOnlineToken,f as checkForErrors,_ as cleanUrl,E as decodeParam,R as decodeQueryString,a as encodeFormData,r as encodeParam,s as encodeQueryString,W as exchangeToken,O as fetchToken,A as generateToken,d as getDefaultRequestOptions,l as getFetch,j as getOnlineEnvironment,k as internalRequest,P as isFederated,D as isOnline,U as normalizeOnlinePortalUrl,z as platformSelf,t as processParams,m as request,e as requiresFormData,N as revokeToken,p as setDefaultRequestOptions,$ as validateAppAccess,c as warn};
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 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 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 p(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 d(){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}`}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 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||"GWM_0003"===o||400===i&&"Unable to generate token."===r)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=d(),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,p=Object.assign({f:"json"},i.params);let g=null;const m={method:o,credentials:i.credentials||"same-origin"};let k;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;k={portal:"https://www.arcgis.com/sharing/rest",getToken:()=>Promise.resolve(e)},i.authentication.startsWith("AAPK")||i.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 k=i.authentication;const w=t;return(k?k.getToken(t).catch((e=>(e.url=t,e.options=i,g=e,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(p.token=r),k&&k.getDomainCredentials&&(m.credentials=k.getDomainCredentials(t));const n={};if("GET"===m.method){p.token&&i.hideToken&&"undefined"==typeof window&&(n["X-Esri-Authorization"]=`Bearer ${p.token}`,delete p.token);const e=""===s(p)?t:t+"?"+s(p);i.maxUrlLength&&e.length>i.maxUrlLength||p.token&&i.hideToken?(m.method="POST",r.length&&i.hideToken&&(p.token=r,delete n["X-Esri-Authorization"])):t=e}const o=new RegExp("/items/.+/updateResources").test(t);return"POST"===m.method&&(m.body=a(p,o)),m.headers=Object.assign(Object.assign({},n),i.headers),"undefined"!=typeof window||m.headers.referer||(m.headers.referer="@esri/arcgis-rest-js"),e(p)||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 h(s,`HTTP ${r}`,e,t,i)}if(u)return e;switch(p.f){case"json":case"geojson":return e.json();case"html":case"text":return e.text();default:return e.blob()}})).then((e=>{if("json"!==p.f&&"geojson"!==p.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 k(e,t={params:{f:"json"}}){return m(e,t).catch((e=>e instanceof g&&498===e.code&&"498: Invalid token."===e.message&&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])&&(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)),{})}class T extends Error{constructor(){super("The user has denied your authorization request.");const e=new.target.prototype;Object.setPrototypeOf(this,e),this.name="ArcGISAccessDeniedError"}}function _(e){return"string"!=typeof e||"/"===(e=e.trim())[e.length-1]&&(e=e.slice(0,-1)),e}function E(e){const[t,r]=e.split("=");return{key:decodeURIComponent(t),value:decodeURIComponent(r)}}function R(e){return!e||e.length<=0?{}:e.replace(/^#/,"").replace(/^\?/,"").split("&").reduce(((e,t)=>{const{key:r,value:s}=E(t);return e[r]=s,e}),{})}var x;!function(e){e.ArcGISRequestError="ArcGISRequestError",e.ArcGISAuthError="ArcGISAuthError",e.ArcGISAccessDeniedError="ArcGISAccessDeniedError"}(x||(x={}));function O(e,t){const r=t;return r.rawResponse=!1,k(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 S{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 S(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 O(`${this.portal}/oauth2/token/`,t).then((e=>(this._pendingTokenRequest=null,this.token=e.token,this.expires=e.expires,e.token)))}refreshCredentials(){return this.refreshToken().then((()=>this))}}function v(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new S(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 A(e){return console.log("DEPRECATED:, 'ApiKey' is deprecated. Use 'ApiKeyManager' instead."),new y(e)}function I(e,t){const r=t;return"undefined"!=typeof window&&window.location&&window.location.host?r.params.referer=window.location.host:r.params.referer="@esri/arcgis-rest-js",k(e,r)}const b=/^https?:\/\/(\S+)\.arcgis\.com.+/;function U(e){return b.test(e)}function D(e){if(!b.test(e))return e;switch(j(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 j(e){if(!b.test(e))return null;const t=e.match(b)[1].split(".").pop();return t.includes("dev")?"dev":t.includes("qa")?"qa":"production"}function P(e,t){const r=_(D(t)).replace(/https?:\/\//,""),s=_(e).replace(/https?:\/\//,"");return new RegExp(s,"i").test(r)}function C(e,t){const r=U(e),s=U(t),n=j(e),i=j(t);return!(!r||!s||n!==i)}function N(e,t,r="https://www.arcgis.com/sharing/rest"){return k(`${r}/oauth2/validateAppAccess`,{method:"POST",params:{f:"json",client_id:t,token:e}})}function $(e){const t=`${_(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 k(t,n).then((e=>{if(!e.success)throw new h("Unable to revoke token",500,e,t,n);return e}))}function q(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 q(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?_(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)}static beginOAuth2(e,t){!t&&window&&(t=window);const{portal:r,provider:n,clientId:i,expiration:o,redirectUri:a,popup:h,popupWindowFeatures:c,locale:l,params:u,style:p,pkce:d,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||M(t),k=`ARCGIS_REST_JS_AUTH_STATE_${i}`;t.localStorage.setItem(k,m);let w=`${_(r)}/oauth2/authorize`;const E={client_id:i,response_type:d?"code":"token",expiration:o,redirect_uri:a,state:JSON.stringify({id:m,originalUrl:t.location.href}),locale:l,style:p};let R;if("arcgis"!==n&&(w=`${_(r)}/oauth2/social/authorize`,E.socialLoginProviderName=n,E.autoAccountCreateForSocial=!0),d){const e=M(t),r=`ARCGIS_REST_JS_CODE_VERIFIER_${i}`;t.localStorage.setItem(r,e),R=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=>q(new Uint8Array(e),t)))}return Promise.resolve(null)}(e,t).then((function(t){E.code_challenge_method=t?"S256":"plain",E.code_challenge=t||e}))}else R=Promise.resolve();return R.then((()=>(w=`${w}?${s(E)}`,u&&(w=`${w}&${s(u)}`),h?new Promise(((e,s)=>{t.addEventListener(`arcgis-rest-js-popup-auth-${i}`,(t=>{if("access_denied"===t.detail.error){const e=new T;return s(e),e}if(t.detail.error){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}))}),{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:i}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",popup:!0,pkce:!0},e),o=`ARCGIS_REST_JS_AUTH_STATE_${s}`,a=t.localStorage.getItem(o),h=R(i?t.location.search.replace(/^\?/,""):t.location.hash.replace(/^#/,"")),c=h&&h.state?JSON.parse(h.state):void 0;function l(e,r,i){return t.localStorage.removeItem(o),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 T):Promise.reject(new g(e,r)))}function u(e,i){return t.localStorage.removeItem(o),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}))}if(!a||!c)return l("No authentication state was found, call `ArcGISIdentityManager.beginOAuth2(...)` to start the authentication process.","no-auth-state");if(c.id!==a)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,c.originalUrl)}if(i&&h.code){const e=_(`${r}/oauth2/token/`),n=`ARCGIS_REST_JS_CODE_VERIFIER_${s}`,i=t.localStorage.getItem(n);return t.localStorage.removeItem(n),O(e,{httpMethod:"POST",params:{client_id:s,code_verifier:i,grant_type:"authorization_code",redirect_uri:location.href.replace(location.search,""),code:h.code}}).then((e=>u(Object.assign(Object.assign({},e),c),c.originalUrl))).catch((e=>l(e.message,e.error,c.originalUrl)))}return!i&&h.access_token?Promise.resolve(u(Object.assign({token:h.access_token,expires:new Date(Date.now()+1e3*parseInt(h.expires_in,10)),ssl:"true"===h.ssl,username:h.username},c),c.originalUrl)):l("Unknown error","oauth-error",c.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:n,expiration:i,redirectUri:o,state:a}=Object.assign({portal:"https://arcgis.com/sharing/rest",expiration:20160},e),h={client_id:n,expiration:i,response_type:"code",redirect_uri:o};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 O(`${r}/oauth2/token`,{params:{grant_type:"authorization_code",client_id:s,redirect_uri:n,code:t}}).then((e=>new G({clientId:s,portal:r,ssl:e.ssl,redirectUri:n,refreshToken:e.refreshToken,refreshTokenExpires:e.refreshTokenExpires,token:e.token,tokenExpires:e.expires,username:e.username})))}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){const t=void 0===e.ssl||e.ssl,r=e.expires||Date.now()+72e5;return new G({portal:e.server.includes("sharing/rest")?e.server:e.server+"/sharing/rest",ssl:t,token:e.token,username:e.userId,tokenExpires:new Date(r)})}static parentMessageHandler(e){if("arcgis:auth:credential"===e.data.type)return G.fromCredential(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 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.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=k(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=k(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 C(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=>N(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 g("Unable to refresh token."))}getServerRootUrl(e){const[t]=_(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){const t=this.toCredential();t.server=t.server.replace("/sharing/rest",""),e={type:"arcgis:auth:credential",credential:t}}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((()=>k(`${r}/rest/info`,{credentials:this.getDomainCredentials(e)}).then((s=>{if(s.owningSystemUrl){if(P(s.owningSystemUrl,this.portal))return k(`${s.owningSystemUrl}/sharing/rest/info`,t);throw new g(`${e} is not federated with ${this.portal}.`,"NOT_FEDERATED")}if(s.authInfo&&void 0!==this.federatedServers[r])return Promise.resolve({authInfo:s.authInfo});throw new g(`${e} is not federated with any portal and is not explicitly trusted.`,"NOT_FEDERATED")})).then((e=>e.authInfo.tokenServicesUrl)).then((t=>this.token&&this.tokenExpires.getTime()>Date.now()?I(t,{params:{token:this.token,serverUrl:e,expiration:this.tokenDuration,client:"referer"}}):I(t,{params:{username:this.username,password:this.password,expiration:this.tokenDuration,client:"referer"}}).then((e=>(this.updateToken(e.token,new Date(e.expires)),e))))).then((e=>(this.federatedServers[r]={expires:new Date(e.expires),token:e.token},delete this._pendingTokenRequests[r],e.token)))))),this._pendingTokenRequests[r])}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((e=>(this._pendingTokenRequests[this.portal]=null,e.token)))),this._pendingTokenRequests[this.portal])}refreshWithUsernameAndPassword(e){const t=Object.assign({params:{username:this.username,password:this.password,expiration:this.tokenDuration}},e);return I(`${this.portal}/generateToken`,t).then((e=>(this.updateToken(e.token,new Date(e.expires)),this)))}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 O(`${this.portal}/oauth2/token`,t).then((e=>this.updateToken(e.token,e.expires)))}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 O(`${this.portal}/oauth2/token`,t).then((e=>(this._token=e.token,this._tokenExpires=e.expires,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this)))}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 W(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManagerOptions' instead."),new G(e)}function z(e,t,r="https://www.arcgis.com/sharing/rest"){return k(`${r}/oauth2/exchangeToken`,{method:"POST",params:{f:"json",client_id:t,token:e}}).then((e=>e.token))}function F(e,t,r="https://www.arcgis.com/sharing/rest"){return k(`${r}/oauth2/platformSelf?f=json`,{method:"POST",headers:{"X-Esri-Auth-Client-Id":e,"X-Esri-Auth-Redirect-Uri":t},params:{f:"json"}})}export{A as ApiKey,y as ApiKeyManager,S as ApplicationCredentialsManager,v as ApplicationSession,T as ArcGISAccessDeniedError,g as ArcGISAuthError,G as ArcGISIdentityManager,h as ArcGISRequestError,o as Blob,x as ErrorTypes,i as File,n as FormData,u as NODEJS_DEFAULT_REFERER_HEADER,W as UserSession,w as appendCustomParams,C as canUseOnlineToken,f as checkForErrors,_ as cleanUrl,E as decodeParam,R as decodeQueryString,a as encodeFormData,r as encodeParam,s as encodeQueryString,z as exchangeToken,O as fetchToken,I as generateToken,d as getDefaultRequestOptions,l as getFetch,j as getOnlineEnvironment,m as internalRequest,P as isFederated,U as isOnline,D as normalizeOnlinePortalUrl,F as platformSelf,t as processParams,k as request,e as requiresFormData,$ as revokeToken,p as setDefaultRequestOptions,N as validateAppAccess,c as warn};
//# sourceMappingURL=request.esm.min.js.map
/* @preserve
* @esri/arcgis-rest-request - v4.0.0-beta.3 - Apache-2.0
* @esri/arcgis-rest-request - v4.0.0-beta.4 - Apache-2.0
* Copyright (c) 2017-2022 Esri, Inc.
* Mon Mar 14 2022 21:04:42 GMT+0000 (Coordinated Universal Time)
* Wed Mar 16 2022 17:43:24 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 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 h(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 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 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 p="@esri/arcgis-rest-js";function d(){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}`}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||"GWM_0003"===o||400===i&&"Unable to generate token."===r)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(e,r){const s=d(),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 m=null;const k={method:o,credentials:i.credentials||"same-origin"};let w;if(i.headers&&i.headers["X-Esri-Auth-Client-Id"]&&e.indexOf("/oauth2/platformSelf")>-1&&(k.credentials="include"),"string"==typeof i.authentication){const e=i.authentication;w={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 w=i.authentication;const T=e;return(w?w.getToken(e).catch((t=>(t.url=e,t.options=i,m=t,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(g.token=r),w&&w.getDomainCredentials&&(k.credentials=w.getDomainCredentials(e));const s={};if("GET"===k.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?(k.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"===k.method&&(k.body=h(g,o)),k.headers=Object.assign(Object.assign({},s),i.headers),"undefined"!=typeof window||k.headers.referer||(k.headers.referer=p),t(g)||o||(k.headers["Content-Type"]="application/x-www-form-urlencoded"),globalThis.fetch?globalThis.fetch(e,k):u().then((({fetch:t})=>t(e,k)))})).then((t=>{if(!t.ok){const{status:r,statusText:s}=t;throw new c(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=f(t,T,0,i,m);if(m){const t=e.toLowerCase().split(/\/rest(\/admin)?\/services\//)[0];i.authentication.federatedServers[t]={token:[],expires:new Date(Date.now()+864e5)},m=null}return r}}))}function k(e,t={params:{f:"json"}}){return m(e,t).catch((e=>e instanceof g&&498===e.code&&"498: Invalid token."===e.message&&t.authentication&&"string"!=typeof t.authentication&&t.authentication.canRefresh&&t.authentication.refreshCredentials?e.retry((()=>t.authentication.refreshCredentials()),1):Promise.reject(e)))}class w extends Error{constructor(){super("The user has denied your authorization request.");const e=new.target.prototype;Object.setPrototypeOf(this,e),this.name="ArcGISAccessDeniedError"}}function T(e){return"string"!=typeof e||"/"===(e=e.trim())[e.length-1]&&(e=e.slice(0,-1)),e}function _(e){const[t,r]=e.split("=");return{key:decodeURIComponent(t),value:decodeURIComponent(r)}}function E(e){return!e||e.length<=0?{}:e.replace(/^#/,"").replace(/^\?/,"").split("&").reduce(((e,t)=>{const{key:r,value:s}=_(t);return e[r]=s,e}),{})}var R;e.ErrorTypes=void 0,(R=e.ErrorTypes||(e.ErrorTypes={})).ArcGISRequestError="ArcGISRequestError",R.ArcGISAuthError="ArcGISAuthError",R.ArcGISAccessDeniedError="ArcGISAccessDeniedError";const O=3e5;function S(e,t){const r=t;return r.rawResponse=!1,k(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 x{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 x(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 S(`${this.portal}/oauth2/token/`,t).then((e=>(this._pendingTokenRequest=null,this.token=e.token,this.expires=e.expires,e.token)))}refreshCredentials(){return this.refreshToken().then((()=>this))}}class v{constructor(e){this.portal="https://www.arcgis.com/sharing/rest",this.key=e.key}static fromKey(e){return new v({key:e})}getToken(e){return Promise.resolve(this.key)}}function y(e,t){const r=t;return"undefined"!=typeof window&&window.location&&window.location.host?r.params.referer=window.location.host:r.params.referer=p,k(e,r)}const A=/^https?:\/\/(\S+)\.arcgis\.com.+/;function I(e){return A.test(e)}function b(e){if(!A.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(!A.test(e))return null;const t=e.match(A)[1].split(".").pop();return t.includes("dev")?"dev":t.includes("qa")?"qa":"production"}function U(e,t){const r=T(b(t)).replace(/https?:\/\//,""),s=T(e).replace(/https?:\/\//,"");return new RegExp(s,"i").test(r)}function P(e,t){const r=I(e),s=I(t),n=D(e),i=D(t);return!(!r||!s||n!==i)}function j(e,t,r="https://www.arcgis.com/sharing/rest"){return k(`${r}/oauth2/validateAppAccess`,{method:"POST",params:{f:"json",client_id:t,token:e}})}function C(e){const t=`${T(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 k(t,n).then((e=>{if(!e.success)throw new c("Unable to revoke token",500,e,t,n);return e}))}function $(e,t=window){return!t&&window&&(t=window),t.btoa(String.fromCharCode.apply(null,e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function N(e){!e&&window&&(e=window);return $(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?T(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.refreshTokenTTL=e.refreshTokenTTL||20160,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)}static beginOAuth2(e,t){!t&&window&&(t=window);const{portal:r,provider:s,clientId:i,expiration:o,redirectUri:a,popup:h,popupWindowFeatures:c,locale:l,params:u,style:p,pkce:d}=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",state:e.clientId,locale:"",style:"",pkce:!0},e),f=N(t),m=`ARCGIS_REST_JS_AUTH_STATE_${i}`;t.localStorage.setItem(m,f);let k=`${T(r)}/oauth2/authorize`;const _={client_id:i,response_type:d?"code":"token",expiration:o,redirect_uri:a,state:JSON.stringify({id:f,originalUrl:t.location.href}),locale:l,style:p};let E;if("arcgis"!==s&&(k=`${T(r)}/oauth2/social/authorize`,_.socialLoginProviderName=s,_.autoAccountCreateForSocial=!0),d){const e=N(t),r=`ARCGIS_REST_JS_CODE_VERIFIER_${i}`;t.localStorage.setItem(r,e),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=>$(new Uint8Array(e),t)))}return Promise.resolve(null)}(e,t).then((function(t){_.code_challenge_method=t?"S256":"plain",_.code_challenge=t||e}))}else E=Promise.resolve();return E.then((()=>(k=`${k}?${n(_)}`,u&&(k=`${k}&${n(u)}`),h?new Promise(((e,s)=>{t.addEventListener(`arcgis-rest-js-popup-auth-${i}`,(t=>{if("access_denied"===t.detail.error){const e=new w;return s(e),e}if(t.detail.error){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}))}),{once:!0}),t.open(k,"oauth-window",c),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:i}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",popup:!0,pkce:!0},e),o=`ARCGIS_REST_JS_AUTH_STATE_${s}`,a=t.localStorage.getItem(o),h=E(i?t.location.search.replace(/^\?/,""):t.location.hash.replace(/^#/,"")),c=h&&h.state?JSON.parse(h.state):void 0;function l(e,r,i){return t.localStorage.removeItem(o),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 w):Promise.reject(new g(e,r)))}function u(e,i){return t.localStorage.removeItem(o),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}))}if(!a||!c)return l("No authentication state was found, call `ArcGISIdentityManager.beginOAuth2(...)` to start the authentication process.","no-auth-state");if(c.id!==a)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,c.originalUrl)}if(i&&h.code){const e=T(`${r}/oauth2/token/`),n=`ARCGIS_REST_JS_CODE_VERIFIER_${s}`,i=t.localStorage.getItem(n);return t.localStorage.removeItem(n),S(e,{httpMethod:"POST",params:{client_id:s,code_verifier:i,grant_type:"authorization_code",redirect_uri:location.href.replace(location.search,""),code:h.code}}).then((e=>u(Object.assign(Object.assign({},e),c),c.originalUrl))).catch((e=>l(e.message,e.error,c.originalUrl)))}return!i&&h.access_token?Promise.resolve(u(Object.assign({token:h.access_token,expires:new Date(Date.now()+1e3*parseInt(h.expires_in,10)),ssl:"true"===h.ssl,username:h.username},c),c.originalUrl)):l("Unknown error","oauth-error",c.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:s,expiration:n,redirectUri:i}=Object.assign({portal:"https://arcgis.com/sharing/rest",expiration:20160},e);t.writeHead(301,{Location:`${r}/oauth2/authorize?client_id=${s}&expiration=${n}&response_type=code&redirect_uri=${encodeURIComponent(i)}`}),t.end()}static exchangeAuthorizationCode(e,t){const{portal:r,clientId:s,redirectUri:n,refreshTokenTTL:i}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",refreshTokenTTL:20160},e);return S(`${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,refreshTokenTTL:i,refreshTokenExpires:new Date(Date.now()+60*(i-1)*1e3),token:e.token,tokenExpires:e.expires,username:e.username})))}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,refreshTokenTTL:t.refreshTokenTTL,server:t.server})}static fromCredential(e){const t=void 0===e.ssl||e.ssl,r=e.expires||Date.now()+72e5;return new q({portal:e.server.includes("sharing/rest")?e.server:e.server+"/sharing/rest",ssl:t,token:e.token,username:e.userId,tokenExpires:new Date(r)})}static parentMessageHandler(e){if("arcgis:auth:credential"===e.data.type)return q.fromCredential(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 C({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.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=k(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=k(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 P(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=>j(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,refreshTokenTTL:this.refreshTokenTTL,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 g("Unable to refresh token."))}getServerRootUrl(e){const[t]=T(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){const t=this.toCredential();t.server=t.server.replace("/sharing/rest",""),e={type:"arcgis:auth:credential",credential:t}}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((()=>k(`${r}/rest/info`,{credentials:this.getDomainCredentials(e)}).then((s=>{if(s.owningSystemUrl){if(U(s.owningSystemUrl,this.portal))return k(`${s.owningSystemUrl}/sharing/rest/info`,t);throw new g(`${e} is not federated with ${this.portal}.`,"NOT_FEDERATED")}if(s.authInfo&&void 0!==this.federatedServers[r])return Promise.resolve({authInfo:s.authInfo});throw new g(`${e} is not federated with any portal and is not explicitly trusted.`,"NOT_FEDERATED")})).then((e=>e.authInfo.tokenServicesUrl)).then((t=>this.token&&this.tokenExpires.getTime()>Date.now()?y(t,{params:{token:this.token,serverUrl:e,expiration:this.tokenDuration,client:"referer"}}):y(t,{params:{username:this.username,password:this.password,expiration:this.tokenDuration,client:"referer"}}).then((e=>(this.updateToken(e.token,new Date(e.expires)),e))))).then((e=>(this.federatedServers[r]={expires:new Date(e.expires),token:e.token},delete this._pendingTokenRequests[r],e.token)))))),this._pendingTokenRequests[r])}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((e=>(this._pendingTokenRequests[this.portal]=null,e.token)))),this._pendingTokenRequests[this.portal])}refreshWithUsernameAndPassword(e){const t=Object.assign({params:{username:this.username,password:this.password,expiration:this.tokenDuration}},e);return y(`${this.portal}/generateToken`,t).then((e=>(this.updateToken(e.token,new Date(e.expires)),this)))}refreshWithRefreshToken(e){if(this.refreshToken&&this.refreshTokenExpires&&this.refreshTokenExpires.getTime()<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 S(`${this.portal}/oauth2/token`,t).then((e=>this.updateToken(e.token,e.expires)))}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 S(`${this.portal}/oauth2/token`,t).then((e=>(this._token=e.token,this._tokenExpires=e.expires,this._refreshToken=e.refreshToken,this._refreshTokenExpires=new Date(Date.now()+60*(this.refreshTokenTTL-1)*1e3),this)))}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)))}}e.ApiKey=function(e){return console.log("DEPRECATED:, 'ApiKey' is deprecated. Use 'ApiKeyManager' instead."),new v(e)},e.ApiKeyManager=v,e.ApplicationCredentialsManager=x,e.ApplicationSession=function(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new x(e)},e.ArcGISAccessDeniedError=w,e.ArcGISAuthError=g,e.ArcGISIdentityManager=q,e.ArcGISRequestError=c,e.Blob=a,e.File=o,e.FormData=i,e.NODEJS_DEFAULT_REFERER_HEADER=p,e.UserSession=function(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManagerOptions' instead."),new q(e)},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])&&(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=P,e.checkForErrors=f,e.cleanUrl=T,e.decodeParam=_,e.decodeQueryString=E,e.encodeFormData=h,e.encodeParam=s,e.encodeQueryString=n,e.exchangeToken=function(e,t,r="https://www.arcgis.com/sharing/rest"){return k(`${r}/oauth2/exchangeToken`,{method:"POST",params:{f:"json",client_id:t,token:e}}).then((e=>e.token))},e.fetchToken=S,e.generateToken=y,e.getDefaultRequestOptions=d,e.getFetch=u,e.getOnlineEnvironment=D,e.internalRequest=m,e.isFederated=U,e.isOnline=I,e.normalizeOnlinePortalUrl=b,e.platformSelf=function(e,t,r="https://www.arcgis.com/sharing/rest"){return k(`${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=k,e.requiresFormData=t,e.revokeToken=C,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=j,e.warn=l,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 h(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 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 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 p="@esri/arcgis-rest-js";function d(){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}`}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||"GWM_0003"===o||400===i&&"Unable to generate token."===r)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(e,r){const s=d(),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 m=null;const k={method:o,credentials:i.credentials||"same-origin"};let w;if(i.headers&&i.headers["X-Esri-Auth-Client-Id"]&&e.indexOf("/oauth2/platformSelf")>-1&&(k.credentials="include"),"string"==typeof i.authentication){const e=i.authentication;w={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 w=i.authentication;const T=e;return(w?w.getToken(e).catch((t=>(t.url=e,t.options=i,m=t,Promise.resolve("")))):Promise.resolve("")).then((r=>{r.length&&(g.token=r),w&&w.getDomainCredentials&&(k.credentials=w.getDomainCredentials(e));const s={};if("GET"===k.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?(k.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"===k.method&&(k.body=h(g,o)),k.headers=Object.assign(Object.assign({},s),i.headers),"undefined"!=typeof window||k.headers.referer||(k.headers.referer=p),t(g)||o||(k.headers["Content-Type"]="application/x-www-form-urlencoded"),globalThis.fetch?globalThis.fetch(e,k):u().then((({fetch:t})=>t(e,k)))})).then((t=>{if(!t.ok){const{status:r,statusText:s}=t;throw new c(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=f(t,T,0,i,m);if(m){const t=e.toLowerCase().split(/\/rest(\/admin)?\/services\//)[0];i.authentication.federatedServers[t]={token:[],expires:new Date(Date.now()+864e5)},m=null}return r}}))}function k(e,t={params:{f:"json"}}){return m(e,t).catch((e=>e instanceof g&&498===e.code&&"498: Invalid token."===e.message&&t.authentication&&"string"!=typeof t.authentication&&t.authentication.canRefresh&&t.authentication.refreshCredentials?e.retry((()=>t.authentication.refreshCredentials()),1):Promise.reject(e)))}class w extends Error{constructor(){super("The user has denied your authorization request.");const e=new.target.prototype;Object.setPrototypeOf(this,e),this.name="ArcGISAccessDeniedError"}}function T(e){return"string"!=typeof e||"/"===(e=e.trim())[e.length-1]&&(e=e.slice(0,-1)),e}function _(e){const[t,r]=e.split("=");return{key:decodeURIComponent(t),value:decodeURIComponent(r)}}function E(e){return!e||e.length<=0?{}:e.replace(/^#/,"").replace(/^\?/,"").split("&").reduce(((e,t)=>{const{key:r,value:s}=_(t);return e[r]=s,e}),{})}var R;e.ErrorTypes=void 0,(R=e.ErrorTypes||(e.ErrorTypes={})).ArcGISRequestError="ArcGISRequestError",R.ArcGISAuthError="ArcGISAuthError",R.ArcGISAccessDeniedError="ArcGISAccessDeniedError";const O=3e5;function S(e,t){const r=t;return r.rawResponse=!1,k(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 x{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 x(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 S(`${this.portal}/oauth2/token/`,t).then((e=>(this._pendingTokenRequest=null,this.token=e.token,this.expires=e.expires,e.token)))}refreshCredentials(){return this.refreshToken().then((()=>this))}}class v{constructor(e){this.portal="https://www.arcgis.com/sharing/rest",this.key=e.key}static fromKey(e){return new v({key:e})}getToken(e){return Promise.resolve(this.key)}}function y(e,t){const r=t;return"undefined"!=typeof window&&window.location&&window.location.host?r.params.referer=window.location.host:r.params.referer=p,k(e,r)}const A=/^https?:\/\/(\S+)\.arcgis\.com.+/;function I(e){return A.test(e)}function b(e){if(!A.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(!A.test(e))return null;const t=e.match(A)[1].split(".").pop();return t.includes("dev")?"dev":t.includes("qa")?"qa":"production"}function U(e,t){const r=T(b(t)).replace(/https?:\/\//,""),s=T(e).replace(/https?:\/\//,"");return new RegExp(s,"i").test(r)}function P(e,t){const r=I(e),s=I(t),n=D(e),i=D(t);return!(!r||!s||n!==i)}function j(e,t,r="https://www.arcgis.com/sharing/rest"){return k(`${r}/oauth2/validateAppAccess`,{method:"POST",params:{f:"json",client_id:t,token:e}})}function C(e){const t=`${T(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 k(t,n).then((e=>{if(!e.success)throw new c("Unable to revoke token",500,e,t,n);return e}))}function N(e,t=window){return!t&&window&&(t=window),t.btoa(String.fromCharCode.apply(null,e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function $(e){!e&&window&&(e=window);return N(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?T(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)}static beginOAuth2(e,t){!t&&window&&(t=window);const{portal:r,provider:s,clientId:i,expiration:o,redirectUri:a,popup:h,popupWindowFeatures:c,locale:l,params:u,style:p,pkce:d,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||$(t),k=`ARCGIS_REST_JS_AUTH_STATE_${i}`;t.localStorage.setItem(k,m);let _=`${T(r)}/oauth2/authorize`;const E={client_id:i,response_type:d?"code":"token",expiration:o,redirect_uri:a,state:JSON.stringify({id:m,originalUrl:t.location.href}),locale:l,style:p};let R;if("arcgis"!==s&&(_=`${T(r)}/oauth2/social/authorize`,E.socialLoginProviderName=s,E.autoAccountCreateForSocial=!0),d){const e=$(t),r=`ARCGIS_REST_JS_CODE_VERIFIER_${i}`;t.localStorage.setItem(r,e),R=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=>N(new Uint8Array(e),t)))}return Promise.resolve(null)}(e,t).then((function(t){E.code_challenge_method=t?"S256":"plain",E.code_challenge=t||e}))}else R=Promise.resolve();return R.then((()=>(_=`${_}?${n(E)}`,u&&(_=`${_}&${n(u)}`),h?new Promise(((e,s)=>{t.addEventListener(`arcgis-rest-js-popup-auth-${i}`,(t=>{if("access_denied"===t.detail.error){const e=new w;return s(e),e}if(t.detail.error){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}))}),{once:!0}),t.open(_,"oauth-window",c),t.dispatchEvent(new CustomEvent("arcgis-rest-js-popup-auth-start"))})):void(t.location.href=_))))}static completeOAuth2(e,t){!t&&window&&(t=window);const{portal:r,clientId:s,popup:n,pkce:i}=Object.assign({portal:"https://www.arcgis.com/sharing/rest",popup:!0,pkce:!0},e),o=`ARCGIS_REST_JS_AUTH_STATE_${s}`,a=t.localStorage.getItem(o),h=E(i?t.location.search.replace(/^\?/,""):t.location.hash.replace(/^#/,"")),c=h&&h.state?JSON.parse(h.state):void 0;function l(e,r,i){return t.localStorage.removeItem(o),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 w):Promise.reject(new g(e,r)))}function u(e,i){return t.localStorage.removeItem(o),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}))}if(!a||!c)return l("No authentication state was found, call `ArcGISIdentityManager.beginOAuth2(...)` to start the authentication process.","no-auth-state");if(c.id!==a)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,c.originalUrl)}if(i&&h.code){const e=T(`${r}/oauth2/token/`),n=`ARCGIS_REST_JS_CODE_VERIFIER_${s}`,i=t.localStorage.getItem(n);return t.localStorage.removeItem(n),S(e,{httpMethod:"POST",params:{client_id:s,code_verifier:i,grant_type:"authorization_code",redirect_uri:location.href.replace(location.search,""),code:h.code}}).then((e=>u(Object.assign(Object.assign({},e),c),c.originalUrl))).catch((e=>l(e.message,e.error,c.originalUrl)))}return!i&&h.access_token?Promise.resolve(u(Object.assign({token:h.access_token,expires:new Date(Date.now()+1e3*parseInt(h.expires_in,10)),ssl:"true"===h.ssl,username:h.username},c),c.originalUrl)):l("Unknown error","oauth-error",c.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:s,expiration:i,redirectUri:o,state:a}=Object.assign({portal:"https://arcgis.com/sharing/rest",expiration:20160},e),h={client_id:s,expiration:i,response_type:"code",redirect_uri:o};a&&(h.state=a);const c=`${r}/oauth2/authorize?${n(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 S(`${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})))}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){const t=void 0===e.ssl||e.ssl,r=e.expires||Date.now()+72e5;return new q({portal:e.server.includes("sharing/rest")?e.server:e.server+"/sharing/rest",ssl:t,token:e.token,username:e.userId,tokenExpires:new Date(r)})}static parentMessageHandler(e){if("arcgis:auth:credential"===e.data.type)return q.fromCredential(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 C({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.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=k(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=k(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 P(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=>j(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 g("Unable to refresh token."))}getServerRootUrl(e){const[t]=T(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){const t=this.toCredential();t.server=t.server.replace("/sharing/rest",""),e={type:"arcgis:auth:credential",credential:t}}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((()=>k(`${r}/rest/info`,{credentials:this.getDomainCredentials(e)}).then((s=>{if(s.owningSystemUrl){if(U(s.owningSystemUrl,this.portal))return k(`${s.owningSystemUrl}/sharing/rest/info`,t);throw new g(`${e} is not federated with ${this.portal}.`,"NOT_FEDERATED")}if(s.authInfo&&void 0!==this.federatedServers[r])return Promise.resolve({authInfo:s.authInfo});throw new g(`${e} is not federated with any portal and is not explicitly trusted.`,"NOT_FEDERATED")})).then((e=>e.authInfo.tokenServicesUrl)).then((t=>this.token&&this.tokenExpires.getTime()>Date.now()?y(t,{params:{token:this.token,serverUrl:e,expiration:this.tokenDuration,client:"referer"}}):y(t,{params:{username:this.username,password:this.password,expiration:this.tokenDuration,client:"referer"}}).then((e=>(this.updateToken(e.token,new Date(e.expires)),e))))).then((e=>(this.federatedServers[r]={expires:new Date(e.expires),token:e.token},delete this._pendingTokenRequests[r],e.token)))))),this._pendingTokenRequests[r])}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((e=>(this._pendingTokenRequests[this.portal]=null,e.token)))),this._pendingTokenRequests[this.portal])}refreshWithUsernameAndPassword(e){const t=Object.assign({params:{username:this.username,password:this.password,expiration:this.tokenDuration}},e);return y(`${this.portal}/generateToken`,t).then((e=>(this.updateToken(e.token,new Date(e.expires)),this)))}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 S(`${this.portal}/oauth2/token`,t).then((e=>this.updateToken(e.token,e.expires)))}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 S(`${this.portal}/oauth2/token`,t).then((e=>(this._token=e.token,this._tokenExpires=e.expires,this._refreshToken=e.refreshToken,this._refreshTokenExpires=e.refreshTokenExpires,this)))}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)))}}e.ApiKey=function(e){return console.log("DEPRECATED:, 'ApiKey' is deprecated. Use 'ApiKeyManager' instead."),new v(e)},e.ApiKeyManager=v,e.ApplicationCredentialsManager=x,e.ApplicationSession=function(e){return console.log("DEPRECATED:, 'ApplicationSession' is deprecated. Use 'ApplicationCredentialsManager' instead."),new x(e)},e.ArcGISAccessDeniedError=w,e.ArcGISAuthError=g,e.ArcGISIdentityManager=q,e.ArcGISRequestError=c,e.Blob=a,e.File=o,e.FormData=i,e.NODEJS_DEFAULT_REFERER_HEADER=p,e.UserSession=function(e){return console.log("DEPRECATED:, 'UserSession' is deprecated. Use 'ArcGISIdentityManagerOptions' instead."),new q(e)},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])&&(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=P,e.checkForErrors=f,e.cleanUrl=T,e.decodeParam=_,e.decodeQueryString=E,e.encodeFormData=h,e.encodeParam=s,e.encodeQueryString=n,e.exchangeToken=function(e,t,r="https://www.arcgis.com/sharing/rest"){return k(`${r}/oauth2/exchangeToken`,{method:"POST",params:{f:"json",client_id:t,token:e}}).then((e=>e.token))},e.fetchToken=S,e.generateToken=y,e.getDefaultRequestOptions=d,e.getFetch=u,e.getOnlineEnvironment=D,e.internalRequest=m,e.isFederated=U,e.isOnline=I,e.normalizeOnlinePortalUrl=b,e.platformSelf=function(e,t,r="https://www.arcgis.com/sharing/rest"){return k(`${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=k,e.requiresFormData=t,e.revokeToken=C,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=j,e.warn=l,Object.defineProperty(e,"__esModule",{value:!0})}));
//# sourceMappingURL=request.umd.min.js.map

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

this.redirectUri = options.redirectUri;
this.refreshTokenTTL = options.refreshTokenTTL || 20160;
this.server = options.server;

@@ -129,3 +128,3 @@ this.federatedServers = {};

}
const { portal, provider, clientId, expiration, redirectUri, popup, popupWindowFeatures, locale, params, style, pkce } = Object.assign({
const { portal, provider, clientId, expiration, redirectUri, popup, popupWindowFeatures, locale, params, style, pkce, state } = Object.assign({
portal: "https://www.arcgis.com/sharing/rest",

@@ -136,3 +135,2 @@ provider: "arcgis",

popupWindowFeatures: "height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes",
state: options.clientId,
locale: "",

@@ -146,3 +144,3 @@ style: "",

*/
const stateId = (0, generate_random_string_js_1.generateRandomString)(win);
const stateId = state || (0, generate_random_string_js_1.generateRandomString)(win);
const stateStorageKey = `ARCGIS_REST_JS_AUTH_STATE_${clientId}`;

@@ -412,5 +410,15 @@ win.localStorage.setItem(stateStorageKey, stateId);

static authorize(options, response) {
const { portal, clientId, expiration, redirectUri } = Object.assign({ portal: "https://arcgis.com/sharing/rest", expiration: 20160 }, options);
const { portal, clientId, expiration, redirectUri, state } = Object.assign({ portal: "https://arcgis.com/sharing/rest", expiration: 20160 }, options);
const queryParams = {
client_id: clientId,
expiration,
response_type: "code",
redirect_uri: redirectUri
};
if (state) {
queryParams.state = state;
}
const url = `${portal}/oauth2/authorize?${(0, encode_query_string_js_1.encodeQueryString)(queryParams)}`;
response.writeHead(301, {
Location: `${portal}/oauth2/authorize?client_id=${clientId}&expiration=${expiration}&response_type=code&redirect_uri=${encodeURIComponent(redirectUri)}`
Location: url
});

@@ -426,5 +434,4 @@ response.end();

static exchangeAuthorizationCode(options, authorizationCode) {
const { portal, clientId, redirectUri, refreshTokenTTL } = Object.assign({
portal: "https://www.arcgis.com/sharing/rest",
refreshTokenTTL: 20160
const { portal, clientId, redirectUri } = Object.assign({
portal: "https://www.arcgis.com/sharing/rest"
}, options);

@@ -445,4 +452,3 @@ return (0, fetch_token_js_1.fetchToken)(`${portal}/oauth2/token`, {

refreshToken: response.refreshToken,
refreshTokenTTL,
refreshTokenExpires: new Date(Date.now() + (refreshTokenTTL - 1) * 60 * 1000),
refreshTokenExpires: response.refreshTokenExpires,
token: response.token,

@@ -472,3 +478,2 @@ tokenExpires: response.expires,

redirectUri: options.redirectUri,
refreshTokenTTL: options.refreshTokenTTL,
server: options.server

@@ -693,3 +698,2 @@ });

redirectUri: this.redirectUri,
refreshTokenTTL: this.refreshTokenTTL,
server: this.server

@@ -961,5 +965,7 @@ };

refreshWithRefreshToken(requestOptions) {
// If our refresh token expires sometime in the next 24 hours then refresh the refresh token
const ONE_DAY_IN_MILLISECONDS = 1000 * 60 * 60 * 24;
if (this.refreshToken &&
this.refreshTokenExpires &&
this.refreshTokenExpires.getTime() < Date.now()) {
this.refreshTokenExpires.getTime() - ONE_DAY_IN_MILLISECONDS < Date.now()) {
return this.exchangeRefreshToken(requestOptions);

@@ -1004,3 +1010,3 @@ }

this._refreshToken = response.refreshToken;
this._refreshTokenExpires = new Date(Date.now() + (this.refreshTokenTTL - 1) * 60 * 1000);
this._refreshTokenExpires = response.refreshTokenExpires;
return this;

@@ -1007,0 +1013,0 @@ });

@@ -60,12 +60,10 @@ /// <reference types="node" />

/**
* The requested validity in minutes for a token. Defaults to 20160 (two weeks).
* The requested validity in minutes for a refresh token/access token. Defaults to 20160 (2 weeks).
*
* When using PKCE or server-based OAuth this will control the duration of the refresh token. In this scenario, access tokens will always have a 30 minute validity.
*
* When using implicit auth (`pkce: false`) in {@linkcode ArcGISIdentityManager.beginOAuth2}, this controls the duration of the access token and no refresh token will be granted.
*/
expiration?: number;
/**
* Duration (in minutes) that a token will be valid. Defaults to 20160 (two weeks).
*
* @deprecated use 'expiration' instead
*/
duration?: number;
/**
* If `true` will use the PKCE oAuth 2.0 extension spec in to authorize the user and obtain a token. A value of `false` will use the deprecated oAuth 2.0 implicit grant type.

@@ -89,8 +87,2 @@ *

/**
* Duration (in minutes) that a refresh token will be valid.
*
* @nodeOnly
*/
refreshTokenTTL?: number;
/**
* The locale assumed to render the login page.

@@ -105,2 +97,6 @@ *

style?: "" | "light" | "dark";
/**
* Custom value for oAuth 2.0 state. A random identifier will be generated if this is not passed.
*/
state?: string;
[key: string]: any;

@@ -164,6 +160,2 @@ }

/**
* Duration (in minutes) that a refresh token will be valid.
*/
refreshTokenTTL?: number;
/**
* An unfederated ArcGIS Server instance known to recognize credentials supplied manually.

@@ -334,6 +326,2 @@ * ```js

/**
* Duration of new OAuth 2.0 refresh token validity (in minutes).
*/
readonly refreshTokenTTL: number;
/**
* An unfederated ArcGIS Server instance known to recognize credentials supplied manually.

@@ -340,0 +328,0 @@ * ```js

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

this.redirectUri = options.redirectUri;
this.refreshTokenTTL = options.refreshTokenTTL || 20160;
this.server = options.server;

@@ -126,3 +125,3 @@ this.federatedServers = {};

}
const { portal, provider, clientId, expiration, redirectUri, popup, popupWindowFeatures, locale, params, style, pkce } = Object.assign({
const { portal, provider, clientId, expiration, redirectUri, popup, popupWindowFeatures, locale, params, style, pkce, state } = Object.assign({
portal: "https://www.arcgis.com/sharing/rest",

@@ -133,3 +132,2 @@ provider: "arcgis",

popupWindowFeatures: "height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes",
state: options.clientId,
locale: "",

@@ -143,3 +141,3 @@ style: "",

*/
const stateId = generateRandomString(win);
const stateId = state || generateRandomString(win);
const stateStorageKey = `ARCGIS_REST_JS_AUTH_STATE_${clientId}`;

@@ -409,5 +407,15 @@ win.localStorage.setItem(stateStorageKey, stateId);

static authorize(options, response) {
const { portal, clientId, expiration, redirectUri } = Object.assign({ portal: "https://arcgis.com/sharing/rest", expiration: 20160 }, options);
const { portal, clientId, expiration, redirectUri, state } = Object.assign({ portal: "https://arcgis.com/sharing/rest", expiration: 20160 }, options);
const queryParams = {
client_id: clientId,
expiration,
response_type: "code",
redirect_uri: redirectUri
};
if (state) {
queryParams.state = state;
}
const url = `${portal}/oauth2/authorize?${encodeQueryString(queryParams)}`;
response.writeHead(301, {
Location: `${portal}/oauth2/authorize?client_id=${clientId}&expiration=${expiration}&response_type=code&redirect_uri=${encodeURIComponent(redirectUri)}`
Location: url
});

@@ -423,5 +431,4 @@ response.end();

static exchangeAuthorizationCode(options, authorizationCode) {
const { portal, clientId, redirectUri, refreshTokenTTL } = Object.assign({
portal: "https://www.arcgis.com/sharing/rest",
refreshTokenTTL: 20160
const { portal, clientId, redirectUri } = Object.assign({
portal: "https://www.arcgis.com/sharing/rest"
}, options);

@@ -442,4 +449,3 @@ return fetchToken(`${portal}/oauth2/token`, {

refreshToken: response.refreshToken,
refreshTokenTTL,
refreshTokenExpires: new Date(Date.now() + (refreshTokenTTL - 1) * 60 * 1000),
refreshTokenExpires: response.refreshTokenExpires,
token: response.token,

@@ -469,3 +475,2 @@ tokenExpires: response.expires,

redirectUri: options.redirectUri,
refreshTokenTTL: options.refreshTokenTTL,
server: options.server

@@ -690,3 +695,2 @@ });

redirectUri: this.redirectUri,
refreshTokenTTL: this.refreshTokenTTL,
server: this.server

@@ -958,5 +962,7 @@ };

refreshWithRefreshToken(requestOptions) {
// If our refresh token expires sometime in the next 24 hours then refresh the refresh token
const ONE_DAY_IN_MILLISECONDS = 1000 * 60 * 60 * 24;
if (this.refreshToken &&
this.refreshTokenExpires &&
this.refreshTokenExpires.getTime() < Date.now()) {
this.refreshTokenExpires.getTime() - ONE_DAY_IN_MILLISECONDS < Date.now()) {
return this.exchangeRefreshToken(requestOptions);

@@ -1001,3 +1007,3 @@ }

this._refreshToken = response.refreshToken;
this._refreshTokenExpires = new Date(Date.now() + (this.refreshTokenTTL - 1) * 60 * 1000);
this._refreshTokenExpires = response.refreshTokenExpires;
return this;

@@ -1004,0 +1010,0 @@ });

{
"name": "@esri/arcgis-rest-request",
"version": "4.0.0-beta.4",
"version": "4.0.0-beta.5",
"description": "Common methods and utilities for @esri/arcgis-rest-js packages.",

@@ -5,0 +5,0 @@ "license": "Apache-2.0",

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

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