@geoscene/core 4.29.5 → 4.29.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/arcade/serviceAreaMetaData.js +1 -1
  2. package/assets/geoscene/core/workers/RemoteClient.js +1 -1
  3. package/assets/geoscene/core/workers/chunks/02a8f0cc511b810d29dd.js +1 -1
  4. package/assets/geoscene/core/workers/chunks/0b2f4079142b4c2a4ddf.js +1 -1
  5. package/assets/geoscene/core/workers/chunks/26f1ec6ce2720bcc1202.js +1 -1
  6. package/assets/geoscene/core/workers/chunks/348bcc57b99a975902a8.js +1 -1
  7. package/assets/geoscene/core/workers/chunks/54c8eea3a70e92842c6a.js +1 -1
  8. package/assets/geoscene/core/workers/chunks/5db9739e00f15613d1ea.js +1 -1
  9. package/assets/geoscene/core/workers/chunks/71fed2917f4bee173836.js +1 -1
  10. package/assets/geoscene/core/workers/chunks/851de06c5980b9b7362a.js +1 -1
  11. package/assets/geoscene/core/workers/chunks/9d8ce7eec9d80a038477.js +1 -1
  12. package/assets/geoscene/core/workers/chunks/b139cf91bc148aa84419.js +1 -1
  13. package/assets/geoscene/core/workers/chunks/c527692694688a5b3b07.js +2 -4
  14. package/assets/geoscene/core/workers/chunks/c556644bb0cf88770939.js +1 -1
  15. package/assets/geoscene/core/workers/chunks/cf3d5bd2c9115a3e0b79.js +1 -1
  16. package/assets/geoscene/core/workers/chunks/eceaa46f622f6fa31128.js +1 -1
  17. package/assets/geoscene/core/workers/chunks/f59b5ea05caca8a1a398.js +1 -1
  18. package/assets/geoscene/core/workers/chunks/f60e5dd0e712cf32f782.js +1 -1
  19. package/assets/geoscene/images/basemap/gray.jpg +0 -0
  20. package/assets/geoscene/themes/base/widgets/_BasemapGallery.scss +0 -1
  21. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace.json +1 -1
  22. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_ar.json +1 -1
  23. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_bg.json +1 -1
  24. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_bs.json +1 -1
  25. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_ca.json +1 -1
  26. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_cs.json +1 -1
  27. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_da.json +1 -1
  28. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_de.json +1 -1
  29. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_el.json +1 -1
  30. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_en.json +1 -1
  31. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_es.json +1 -1
  32. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_et.json +1 -1
  33. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_fi.json +1 -1
  34. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_fr.json +1 -1
  35. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_he.json +1 -1
  36. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_hr.json +1 -1
  37. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_hu.json +1 -1
  38. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_id.json +1 -1
  39. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_it.json +1 -1
  40. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_ja.json +1 -1
  41. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_ko.json +1 -1
  42. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_lt.json +1 -1
  43. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_lv.json +1 -1
  44. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_nb.json +1 -1
  45. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_nl.json +1 -1
  46. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_pl.json +1 -1
  47. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_pt-BR.json +1 -1
  48. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_pt-PT.json +1 -1
  49. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_ro.json +1 -1
  50. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_ru.json +1 -1
  51. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_sk.json +1 -1
  52. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_sl.json +1 -1
  53. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_sr.json +1 -1
  54. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_sv.json +1 -1
  55. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_th.json +1 -1
  56. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_tr.json +1 -1
  57. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_uk.json +1 -1
  58. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_vi.json +1 -1
  59. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_zh-CN.json +1 -1
  60. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_zh-HK.json +1 -1
  61. package/assets/geoscene/widgets/UtilityNetworkTrace/t9n/UtilityNetworkTrace_zh-TW.json +1 -1
  62. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology.json +1 -1
  63. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_ar.json +1 -1
  64. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_bg.json +1 -1
  65. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_bs.json +1 -1
  66. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_ca.json +1 -1
  67. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_cs.json +1 -1
  68. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_da.json +1 -1
  69. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_de.json +1 -1
  70. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_el.json +1 -1
  71. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_en.json +1 -1
  72. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_es.json +1 -1
  73. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_et.json +1 -1
  74. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_fi.json +1 -1
  75. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_fr.json +1 -1
  76. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_he.json +1 -1
  77. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_hr.json +1 -1
  78. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_hu.json +1 -1
  79. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_id.json +1 -1
  80. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_it.json +1 -1
  81. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_ja.json +1 -1
  82. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_ko.json +1 -1
  83. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_lt.json +1 -1
  84. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_lv.json +1 -1
  85. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_nb.json +1 -1
  86. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_nl.json +1 -1
  87. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_pl.json +1 -1
  88. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_pt-BR.json +1 -1
  89. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_pt-PT.json +1 -1
  90. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_ro.json +1 -1
  91. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_ru.json +1 -1
  92. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_sk.json +1 -1
  93. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_sl.json +1 -1
  94. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_sr.json +1 -1
  95. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_sv.json +1 -1
  96. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_th.json +1 -1
  97. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_tr.json +1 -1
  98. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_uk.json +1 -1
  99. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_vi.json +1 -1
  100. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_zh-CN.json +1 -1
  101. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_zh-HK.json +1 -1
  102. package/assets/geoscene/widgets/UtilityNetworkValidateTopology/t9n/UtilityNetworkValidateTopology_zh-TW.json +1 -1
  103. package/chunks/HUDMaterial.glsl.js +0 -1
  104. package/chunks/persistableUrlUtils.js +1 -1
  105. package/config.js +1 -1
  106. package/copyright.txt +1 -1
  107. package/core/devEnvironmentUtils.js +1 -1
  108. package/core/urlUtils.js +1 -1
  109. package/identity/IdentityManagerBase.js +1 -1
  110. package/identity/IdentityModal.js +1 -1
  111. package/layers/TileLayer.js +1 -1
  112. package/layers/VectorTileLayer.js +1 -1
  113. package/layers/support/arcgisLayerUrl.js +1 -1
  114. package/layers/support/arcgisLayers.js +1 -1
  115. package/package.json +1 -1
  116. package/portal/schemas/definitions.js +1 -1
  117. package/portal/support/urlUtils.js +1 -1
  118. package/request.js +1 -1
  119. package/rest/support/PlacesParameters.js +1 -1
  120. package/smartMapping/support/utils.js +1 -1
  121. package/support/BasemapStyle.js +1 -1
  122. package/support/apiKeyUtils.js +1 -1
  123. package/support/basemapDefinitions.js +1 -1
  124. package/support/basemapUtils.js +1 -1
  125. package/views/3d/webgl-engine/core/shaderLibrary/attributes/InstancedDoublePrecision.glsl.js +1 -1
  126. package/views/3d/webgl-engine/core/shaderLibrary/util/MixExternalColor.glsl.js +0 -2
  127. package/widgets/Editor/EditorViewModel.js +1 -1
  128. package/widgets/Legend/support/ActiveLayerInfo.js +1 -1
  129. package/widgets/Search/support/layerSearchUtils.js +1 -1
  130. package/assets/geoscene/core/workers/chunks/0af5d2f792b83f7dd0aa.js.LICENSE.txt +0 -5
  131. package/assets/geoscene/core/workers/chunks/5015d4fccf4854b9da1e.js.LICENSE.txt +0 -10
  132. package/assets/geoscene/core/workers/chunks/54c8eea3a70e92842c6a.js.LICENSE.txt +0 -16
  133. package/assets/geoscene/core/workers/chunks/804267fca0627d277286.js.LICENSE.txt +0 -5
  134. package/assets/geoscene/core/workers/chunks/87c4848dd48119fd75f9.js.LICENSE.txt +0 -5
  135. package/assets/geoscene/core/workers/chunks/8ec7475f19f8979dfaae.js.LICENSE.txt +0 -5
  136. package/assets/geoscene/core/workers/chunks/904b3e9c98e5de220650.js.LICENSE.txt +0 -11
  137. package/assets/geoscene/core/workers/chunks/c1f78653c70f6bde65b3.js.LICENSE.txt +0 -5
  138. package/assets/geoscene/core/workers/chunks/da21d31db537be097da9.js.LICENSE.txt +0 -5
  139. package/assets/geoscene/core/workers/chunks/e742cd41ab9b164ad974.js.LICENSE.txt +0 -5
@@ -2,4 +2,4 @@
2
2
  All material copyright GeoScene, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.geoscene.cn/4.29/geoscene/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../chunks/tslib.es6.js";import t from"../config.js";import{id as r}from"../kernel.js";import s from"../request.js";import i from"../core/Error.js";import n from"../core/Evented.js";import{on as o}from"../core/events.js";import{fixJson as a}from"../core/lang.js";import{getDeepValue as h}from"../core/object.js";import{createResolver as l,onAbort as c,isAborted as d}from"../core/promiseUtils.js";import{urlToObject as u,hasSameOrigin as p,Url as _,queryToObject as g,base64UrlEncode as f,objectToQuery as m,normalize as v,getProxyRule as S,makeAbsolute as w,addQueryParameters as I}from"../core/urlUtils.js";import{property as A}from"../core/accessorSupport/decorators/property.js";import"../core/has.js";import"../core/Logger.js";import{subclass as k}from"../core/accessorSupport/decorators/subclass.js";import y from"./IdentityModal.js";import U from"./OAuthCredential.js";import T from"./OAuthInfo.js";import x from"./ServerInfo.js";import{isSecureProxyService as O}from"../portal/support/urlUtils.js";const P={},R=e=>{const t=new _(e.owningSystemUrl).host,r=new _(e.server).host,s=/.+\.arcgis\.com$/i;return s.test(t)&&s.test(r)},C=(e,t)=>!!(R(e)&&t&&t.some((t=>t.test(e.server))));let b=null,D=null;try{b=window.localStorage,D=window.sessionStorage}catch{}class q extends n{constructor(){super(),this._portalConfig=globalThis.esriGeowConfig,this.serverInfos=[],this.oAuthInfos=[],this.credentials=[],this._soReqs=[],this._xoReqs=[],this._portals=[],this._defaultOAuthInfo=null,this._defaultTokenValidity=60,this.dialog=null,this.tokenValidity=null,this.normalizeWebTierAuth=!1,this._appOrigin="null"!==window.origin?window.origin:window.location.origin,this._appUrlObj=u(window.location.href),this._busy=null,this._rejectOnPersistedPageShow=!1,this._oAuthLocationParams=null,this._gwTokenUrl="/sharing/rest/generateToken",this._agsRest="/rest/services",this._agsPortal=/\/sharing(\/|$)/i,this._agsAdmin=/(https?:\/\/[^\/]+\/[^\/]+)\/admin\/?(\/.*)?$/i,this._adminSvcs=/\/rest\/admin\/services(\/|$)/i,this._gwDomains=[{customBaseUrl: "www.geosceneonline.cn",regex: /^https?:\/\/www\.geosceneonline\.cn/i,tokenServiceUrl: "https://www.geosceneonline.cn/geoscene/sharing/rest/generateToken"},{regex:/^https?:\/\/www\.arcgis\.com/i,customBaseUrl:"maps.arcgis.com",tokenServiceUrl:"https://www.arcgis.com/sharing/rest/generateToken"},{regex:/^https?:\/\/(?:dev|[a-z\d-]+\.mapsdev)\.arcgis\.com/i,customBaseUrl:"mapsdev.arcgis.com",tokenServiceUrl:"https://dev.arcgis.com/sharing/rest/generateToken"},{regex:/^https?:\/\/(?:devext|[a-z\d-]+\.mapsdevext)\.arcgis\.com/i,customBaseUrl:"mapsdevext.arcgis.com",tokenServiceUrl:"https://devext.arcgis.com/sharing/rest/generateToken"},{regex:/^https?:\/\/(?:qaext|[a-z\d-]+\.mapsqa)\.arcgis\.com/i,customBaseUrl:"mapsqa.arcgis.com",tokenServiceUrl:"https://qaext.arcgis.com/sharing/rest/generateToken"},{regex:/^https?:\/\/[a-z\d-]+\.maps\.arcgis\.com/i,customBaseUrl:"maps.arcgis.com",tokenServiceUrl:"https://www.arcgis.com/sharing/rest/generateToken"}],this._legacyFed=[],this._regexSDirUrl=/http.+\/rest\/services\/?/gi,this._regexServerType=/(\/(FeatureServer|GPServer|GeoDataServer|GeocodeServer|GeoenrichmentServer|GeometryServer|GlobeServer|ImageServer|KnowledgeGraphServer|MapServer|MissionServer|MobileServer|NAServer|NetworkDiagramServer|OGCFeatureServer|ParcelFabricServer|RelationalCatalogServer|SceneServer|StreamServer|UtilityNetworkServer|ValidationServer|VectorTileServer|VersionManagementServer|VideoServer)).*/gi,this._gwUser=/http.+\/users\/([^\/]+)\/?.*/i,this._gwItem=/http.+\/items\/([^\/]+)\/?.*/i,this._gwGroup=/http.+\/groups\/([^\/]+)\/?.*/i,this._rePortalTokenSvc=/\/sharing(\/rest)?\/generatetoken/i,this._createDefaultOAuthInfo=!0,this._hasTestedIfAppIsOnPortal=!1,this._getOAuthLocationParams(),window.addEventListener("pageshow",(e=>{this._pageShowHandler(e)}))}registerServers(e){const t=this.serverInfos;t?(e=e.filter((e=>!this.findServerInfo(e.server))),this.serverInfos=t.concat(e)):this.serverInfos=e,e.forEach((e=>{e.owningSystemUrl&&this._portals.push(e.owningSystemUrl),e.hasPortal&&this._portals.push(e.server)}))}registerOAuthInfos(e){const t=this.oAuthInfos;if(t){for(const r of e){const e=this.findOAuthInfo(r.portalUrl);e&&t.splice(t.indexOf(e),1)}this.oAuthInfos=t.concat(e)}else this.oAuthInfos=e}registerToken(e){e={...e};const t=this._sanitizeUrl(e.server),r=this._isServerRsrc(t);let s,i=this.findServerInfo(t),n=!0;i||(i=new x,i.server=this._getServerInstanceRoot(t),r?i.hasServer=!0:(i.tokenServiceUrl=this._getTokenSvcUrl(t),i.hasPortal=!0),this.registerServers([i])),s=this._findCredential(t),s?(delete e.server,Object.assign(s,e),n=!1):(s=new j({userId:e.userId,server:i.server,token:e.token,expires:e.expires,ssl:e.ssl,scope:r?"server":"portal"}),s.resources=[t],this.credentials.push(s)),s.emitTokenChange(!1),n||s.refreshServerTokens()}toJSON(){return a({serverInfos:this.serverInfos.map((e=>e.toJSON())),oAuthInfos:this.oAuthInfos.map((e=>e.toJSON())),credentials:this.credentials.map((e=>e.toJSON()))})}initialize(e){if(!e)return;"string"==typeof e&&(e=JSON.parse(e));const t=e.serverInfos,r=e.oAuthInfos,s=e.credentials;if(t){const e=[];t.forEach((t=>{t.server&&t.tokenServiceUrl&&e.push(t.declaredClass?t:new x(t))})),e.length&&this.registerServers(e)}if(r){const e=[];r.forEach((t=>{t.appId&&e.push(t.declaredClass?t:new T(t))})),e.length&&this.registerOAuthInfos(e)}s&&s.forEach((e=>{e.server&&e.token&&e.expires&&e.expires>Date.now()&&((e=e.declaredClass?e:new j(e)).emitTokenChange(),this.credentials.push(e))}))}findServerInfo(e){let t;e=this._sanitizeUrl(e);for(const r of this.serverInfos)if(this._hasSameServerInstance(r.server,e)){t=r;break}return t}findOAuthInfo(e){let t;e=this._sanitizeUrl(e);for(const r of this.oAuthInfos)if(this._hasSameServerInstance(r.portalUrl,e)){t=r;break}return t}findCredential(e,t){if(!e)return;let r;e=this._sanitizeUrl(e);const s=this._isServerRsrc(e)?"server":"portal";if(t){for(const i of this.credentials)if(this._hasSameServerInstance(i.server,e)&&t===i.userId&&i.scope===s){r=i;break}}else for(const i of this.credentials)if(this._hasSameServerInstance(i.server,e)&&-1!==this._getIdenticalSvcIdx(e,i)&&i.scope===s){r=i;break}return r}getCredential(e,t){let r,s,n=!0;t&&(r=!!t.token,s=t.error,n=!1!==t.prompt),t={...t},e=this._sanitizeUrl(e);const o=new AbortController,a=l();if(t.signal&&c(t.signal,(()=>{o.abort()})),c(o,(()=>{a.reject(new i("identity-manager:user-aborted","ABORTED"))})),d(o))return a.promise;t.signal=o.signal;const h=this._isAdminResource(e),u=r?this.findCredential(e):null;let _;if(u&&s&&s.details&&498===s.details.httpStatus)u.destroy();else if(u)return _=new i("identity-manager:not-authorized","You are currently signed in as: '"+u.userId+"'. You do not have access to this resource: "+e,{error:s}),a.reject(_),a.promise;const g=this._findCredential(e,t);if(g)return a.resolve(g),a.promise;let f=this.findServerInfo(e);if(f)!f.hasPortal&&f.server&&f.owningSystemUrl&&this._hasSameServerInstance(f.server,f.owningSystemUrl)&&(f.hasPortal=!0),!f.hasServer&&this._isServerRsrc(e)&&(f._restInfoPms=this._getTokenSvcUrl(e),f.hasServer=!0);else{const t=this._getTokenSvcUrl(e);if(!t)return _=new i("identity-manager:unknown-resource","Unknown resource - could not find token service endpoint."),a.reject(_),a.promise;f=new x,f.server=this._getServerInstanceRoot(e),"string"==typeof t?(f.tokenServiceUrl=t,f.hasPortal=!0):(f._restInfoPms=t,f.hasServer=!0),this.registerServers([f])}return f.hasPortal&&void 0===f._selfReq&&(n||p(f.tokenServiceUrl,this._appOrigin)||this._gwDomains.some((e=>e.tokenServiceUrl===f.tokenServiceUrl)))&&(f._selfReq={owningTenant:t?.owningTenant,selfDfd:this._getPortalSelf(f.tokenServiceUrl.replace(this._rePortalTokenSvc,"/sharing/rest/portals/self"),e)}),this._enqueue(e,f,t,a,h)}getResourceName(e){return this._isRESTService(e)?e.replace(this._regexSDirUrl,"").replace(this._regexServerType,"")||"":this._gwUser.test(e)&&e.replace(this._gwUser,"$1")||this._gwItem.test(e)&&e.replace(this._gwItem,"$1")||this._gwGroup.test(e)&&e.replace(this._gwGroup,"$1")||""}generateToken(e,t,r){const n=this._rePortalTokenSvc.test(e.tokenServiceUrl),o=new _(this._appOrigin),a=e.shortLivedTokenValidity;let h,l,c,d,u,g,f,m;t&&(m=this.tokenValidity||a||this._defaultTokenValidity,m>a&&a>0&&(m=a)),r&&(h=r.isAdmin,l=r.serverUrl,c=r.token,g=r.signal,f=r.ssl,e.customParameters=r.customParameters),h?d=e.adminTokenServiceUrl:(d=e.tokenServiceUrl,u=new _(d.toLowerCase()),e.webTierAuth&&r?.serverUrl&&!f&&"http"===o.scheme&&(p(o.uri,d,!0)||"https"===u.scheme&&o.host===u.host&&"7080"===o.port&&"7443"===u.port)&&(d=d.replace(/^https:/i,"http:").replace(/:7443/i,":7080")));const v={query:{request:"getToken",username:t?.username,password:t?.password,serverUrl:l,token:c,expiration:m,referer:h||n?this._appOrigin:null,client:h?"referer":null,f:"json",...e.customParameters},method:"post",authMode:"anonymous",useProxy:this._useProxy(e,r),signal:g,...r?.ioArgs};n||(v.withCredentials=!1);return s(d,v).then((r=>{const s=r.data;if(!s?.token)return new i("identity-manager:authentication-failed","Unable to generate token");const n=e.server;return P[n]||(P[n]={}),t&&(P[n][t.username]=t.password),s.validity=m,s}))}isBusy(){return!!this._busy}checkSignInStatus(e){return this.checkAppAccess(e,"").then((e=>e.credential))}checkAppAccess(e,t,r){let n=!1;return this.getCredential(e,{prompt:!1}).then((o=>{let a;const h={f:"json"};if("portal"===o.scope)if(t&&(this._doPortalSignIn(e)||r?.force))a=o.server+"/sharing/rest/oauth2/validateAppAccess",h.client_id=t;else{if(!o.token)return{credential:o};a=o.server+"/sharing/rest"}else{if(!o.token)return{credential:o};a=o.server+"/rest/services"}return o.token&&(h.token=o.token),s(a,{query:h,authMode:"anonymous"}).then((e=>{if(!1===e.data.valid)throw new i("identity-manager:not-authorized",`You are currently signed in as: '${o.userId}'.`,e.data);return n=!!e.data.viewOnlyUserTypeApp,{credential:o}})).catch((e=>{if("identity-manager:not-authorized"===e.name)throw e;const t=e.details?.httpStatus;if(498===t)throw o.destroy(),new i("identity-manager:not-authenticated","User is not signed in.");if(400===t)throw new i("identity-manager:invalid-request");return{credential:o}}))})).then((e=>({credential:e.credential,viewOnly:n})))}setOAuthResponseHash(e){e&&("#"===e.charAt(0)&&(e=e.substring(1)),this._processOAuthPopupParams(g(e)))}setOAuthRedirectionHandler(e){this._oAuthRedirectFunc=e}setProtocolErrorHandler(e){this._protocolFunc=e}signIn(e,t,r={}){const s=l(),n=()=>{h?.remove(),d?.remove(),this.dialog?.destroy(),this.dialog=h=d=null},o=()=>{n(),this._oAuthDfd=null,s.reject(new i("identity-manager:user-aborted","ABORTED"))};r.signal&&c(r.signal,(()=>{o()}));const a=new y({open:!0,resource:this.getResourceName(e),server:t.server});this.dialog=a,this.emit("dialog-create");let h=a.on("cancel",o),d=a.on("submit",(e=>{this.generateToken(t,e,{isAdmin:r.isAdmin,signal:r.signal}).then((i=>{n();const o=new j({userId:e.username,server:t.server,token:i.token,expires:null!=i.expires?Number(i.expires):null,ssl:!!i.ssl,isAdmin:r.isAdmin,validity:i.validity});s.resolve(o)})).catch((e=>{a.error=e,a.signingIn=!1}))}));return s.promise}oAuthSignIn(e,t,r,s){this._oAuthDfd=l();const n=this._oAuthDfd;let o;s?.signal&&c(s.signal,(()=>{const e=this._oAuthDfd&&this._oAuthDfd.oAuthWin_;e&&!e.closed?e.close():this.dialog&&u()})),n.resUrl_=e,n.sinfo_=t,n.oinfo_=r;const a=r._oAuthCred;if(a.storage&&("authorization-code"===r.flowType||"auto"===r.flowType&&t.currentVersion>=8.4)){let e=crypto.getRandomValues(new Uint8Array(32));o=f(e),a.codeVerifier=o,e=crypto.getRandomValues(new Uint8Array(32)),a.stateUID=f(e),a.save()||(a.codeVerifier=o=null)}else a.codeVerifier=null;let h,d;this._getCodeChallenge(o).then((i=>{const n=!s||!1!==s.oAuthPopupConfirmation;if(!r.popup||!n)return void this._doOAuthSignIn(e,t,r,i);const o=new y({oAuthPrompt:!0,server:t.server,open:!0});this.dialog=o,this.emit("dialog-create"),h=o.on("cancel",u),d=o.on("submit",(()=>{p(),this._doOAuthSignIn(e,t,r,i)}))}));const u=()=>{p(),this._oAuthDfd=null,n.reject(new i("identity-manager:user-aborted","ABORTED"))},p=()=>{h?.remove(),d?.remove(),this.dialog?.destroy(),this.dialog=null};return n.promise}destroyCredentials(){if(this.credentials){this.credentials.slice().forEach((e=>{e.destroy()}))}this.emit("credentials-destroy")}enablePostMessageAuth(e="https://www.geosceneonline.cn/geoscene/sharing/rest"){this._postMessageAuthHandle&&this._postMessageAuthHandle.remove(),this._postMessageAuthHandle=o(window,"message",(t=>{if((t.origin===this._appOrigin||t.origin.endsWith(".arcgis.com"))&&"arcgis:auth:requestCredential"===t.data?.type){const r=t.source;this.getCredential(e).then((e=>{r.postMessage({type:"arcgis:auth:credential",credential:{expires:e.expires,server:e.server,ssl:e.ssl,token:e.token,userId:e.userId}},t.origin)})).catch((e=>{r.postMessage({type:"arcgis:auth:error",error:{name:e.name,message:e.message}},t.origin)}))}}))}disablePostMessageAuth(){this._postMessageAuthHandle&&(this._postMessageAuthHandle.remove(),this._postMessageAuthHandle=null)}_getOAuthLocationParams(){let e=window.location.hash;if(e){"#"===e.charAt(0)&&(e=e.substring(1));const t=g(e);let r=!1;if(t.access_token&&t.expires_in&&t.state&&t.hasOwnProperty("username"))try{t.state=JSON.parse(t.state),t.state.portalUrl&&(this._oAuthLocationParams=t,r=!0)}catch{}else if(t.error&&t.error_description&&(console.log("IdentityManager OAuth Error: ",t.error," - ",t.error_description),"access_denied"===t.error&&(r=!0,t.state)))try{t.state=JSON.parse(t.state)}catch{}r&&(window.location.hash=t.state?.hash||"")}let t=window.location.search;if(t){"?"===t.charAt(0)&&(t=t.substring(1));const e=g(t);let r=!1;if(e.code&&e.state)try{e.state=JSON.parse(e.state),e.state.portalUrl&&e.state.uid&&(this._oAuthLocationParams=e,r=!0)}catch{}else if(e.error&&e.error_description&&(console.log("IdentityManager OAuth Error: ",e.error," - ",e.error_description),"access_denied"===e.error&&(r=!0,e.state)))try{e.state=JSON.parse(e.state)}catch{}if(r){const t={...e};["code","error","error_description","message_code","persist","state"].forEach((e=>{delete t[e]}));const r=m(t),s=window.location.pathname+(r?`?${r}`:"")+(e.state?.hash||"");window.history.replaceState(window.history.state,"",s)}}}_getOAuthToken(e,t,r,i,n){return e=e.replace(/^http:/i,"https:"),s(`${e}/sharing/rest/oauth2/token`,{authMode:"anonymous",method:"post",query:i&&n?{grant_type:"authorization_code",code:t,redirect_uri:i,client_id:r,code_verifier:n}:{grant_type:"refresh_token",refresh_token:t,client_id:r}}).then((e=>e.data))}_getCodeChallenge(e){if(e&&globalThis.isSecureContext){const t=(new TextEncoder).encode(e);return crypto.subtle.digest("SHA-256",t).then((e=>f(new Uint8Array(e))))}return Promise.resolve(null)}_pageShowHandler(e){if(e.persisted&&this.isBusy()&&this._rejectOnPersistedPageShow){const e=new i("identity-manager:user-aborted","ABORTED");this._errbackFunc(e)}}_findCredential(e,t){let r,s,i,n,o=-1;const a=t?.token,h=t?.resource,l=this._isServerRsrc(e)?"server":"portal",c=this.credentials.filter((t=>this._hasSameServerInstance(t.server,e)&&t.scope===l));if(e=h||e,c.length)if(1===c.length){if(r=c[0],i=this.findServerInfo(r.server),s=i?.owningSystemUrl,n=s?this.findCredential(s,r.userId):void 0,o=this._getIdenticalSvcIdx(e,r),!a)return-1===o&&r.resources.push(e),this._addResource(e,n),r;-1!==o&&(r.resources.splice(o,1),this._removeResource(e,n))}else{let t,r;if(c.some((a=>(r=this._getIdenticalSvcIdx(e,a),-1!==r&&(t=a,i=this.findServerInfo(t.server),s=i?.owningSystemUrl,n=s?this.findCredential(s,t.userId):void 0,o=r,!0)))),a)t&&(t.resources.splice(o,1),this._removeResource(e,n));else if(t)return this._addResource(e,n),t}}_findOAuthInfo(e){let t=this.findOAuthInfo(e);if(!t)for(const r of this.oAuthInfos)if(this._isIdProvider(r.portalUrl,e)){t=r;break}return t}_addResource(e,t){t&&-1===this._getIdenticalSvcIdx(e,t)&&t.resources.push(e)}_removeResource(e,t){let r=-1;t&&(r=this._getIdenticalSvcIdx(e,t),r>-1&&t.resources.splice(r,1))}_useProxy(e,t){return t?.isAdmin&&!p(e.adminTokenServiceUrl,this._appOrigin)||!this._isPortalDomain(e.tokenServiceUrl)&&"10.1"===String(e.currentVersion)&&!p(e.tokenServiceUrl,this._appOrigin)}_getOrigin(e){const t=new _(e);return t.scheme+"://"+t.host+(null!=t.port?":"+t.port:"")}_getServerInstanceRoot(e){const t=e.toLowerCase();let r=t.indexOf(this._agsRest);return-1===r&&this._isAdminResource(e)&&(r=this._agsAdmin.test(e)?e.replace(this._agsAdmin,"$1").length:e.search(this._adminSvcs)),-1!==r||O(t)||(r=t.indexOf("/sharing")),-1===r&&"/"===t.substr(-1)&&(r=t.length-1),r>-1?e.substring(0,r):e}_hasSameServerInstance(e,t){return"/"===e.substr(-1)&&(e=e.slice(0,-1)),e=e.toLowerCase(),t=this._getServerInstanceRoot(t).toLowerCase(),e=this._normalizeAGOLorgDomain(e),t=this._normalizeAGOLorgDomain(t),(e=e.substr(e.indexOf(":")))===(t=t.substr(t.indexOf(":")))}_normalizeAGOLorgDomain(e){const t=/^https?:\/\/(?:cdn|[a-z\d-]+\.maps)\.arcgis\.com/i,r=/^https?:\/\/(?:cdndev|[a-z\d-]+\.mapsdevext)\.arcgis\.com/i,s=/^https?:\/\/(?:cdnqa|[a-z\d-]+\.mapsqa)\.arcgis\.com/i;return t.test(e)?e=e.replace(t,"https://www.geosceneonline.cn/geoscene"):r.test(e)?e=e.replace(r,"https://devext.geoscene.cn"):s.test(e)&&(e=e.replace(s,"https://qaext.geoscene.cn")),e}_sanitizeUrl(e){const r=(t.request.proxyUrl||"").toLowerCase(),s=r?e.toLowerCase().indexOf(r+"?"):-1;return-1!==s&&(e=e.substring(s+r.length+1)),e=v(e),u(e).path}_isRESTService(e){return e.includes(this._agsRest)}_isAdminResource(e){return this._agsAdmin.test(e)||this._adminSvcs.test(e)}_isServerRsrc(e){return this._isRESTService(e)||this._isAdminResource(e)}_isIdenticalService(e,t){let r=!1;if(this._isRESTService(e)&&this._isRESTService(t)){const s=this._getSuffix(e).toLowerCase(),i=this._getSuffix(t).toLowerCase();if(r=s===i,!r){const e=/(.*)\/(MapServer|FeatureServer|UtilityNetworkServer).*/gi;r=s.replaceAll(e,"$1")===i.replaceAll(e,"$1")}}else this._isAdminResource(e)&&this._isAdminResource(t)?r=!0:this._isServerRsrc(e)||this._isServerRsrc(t)||!this._isPortalDomain(e)||(r=!0);return r}_isPortalDomain(e){const r=new _(e.toLowerCase()),s=this._portalConfig;let i=this._gwDomains.some((e=>e.regex.test(r.uri)));return!i&&s&&(i=this._hasSameServerInstance(this._getServerInstanceRoot(s.restBaseUrl),r.uri)),i||t.portalUrl&&(i=p(r,t.portalUrl,!0)),i||(i=this._portals.some((e=>this._hasSameServerInstance(e,r.uri)))),i=i||this._agsPortal.test(r.path),i}_isIdProvider(e,t){let r=-1,s=-1;this._gwDomains.forEach(((i,n)=>{-1===r&&i.regex.test(e)&&(r=n),-1===s&&i.regex.test(t)&&(s=n)}));let i=!1;if(r>-1&&s>-1&&(0===r||4===r?0!==s&&4!==s||(i=!0):1===r?1!==s&&2!==s||(i=!0):2===r?2===s&&(i=!0):3===r&&3===s&&(i=!0)),!i){const r=this.findServerInfo(t),s=r?.owningSystemUrl;s&&R(r)&&this._isPortalDomain(s)&&this._isIdProvider(e,s)&&(i=!0)}return i}_getIdenticalSvcIdx(e,t){let r=-1;for(let s=0;s<t.resources.length;s++){const i=t.resources[s];if(this._isIdenticalService(e,i)){r=s;break}}return r}_getSuffix(e){return e.replace(this._regexSDirUrl,"").replace(this._regexServerType,"$1")}_getTokenSvcUrl(e){let t,r,i;if(this._isRESTService(e)||this._isAdminResource(e)){const i=this._getServerInstanceRoot(e);return t=i+"/admin/generateToken",r=s(e=i+"/rest/info",{query:{f:"json"}}).then((e=>e.data)),{adminUrl:t,promise:r}}if(this._isPortalDomain(e)){let t="";if(this._gwDomains.some((r=>(r.regex.test(e)&&(t=r.tokenServiceUrl),!!t))),t||this._portals.some((r=>(this._hasSameServerInstance(r,e)&&(t=r+this._gwTokenUrl),!!t))),t||(i=e.toLowerCase().indexOf("/sharing"),-1!==i&&(t=e.substring(0,i)+this._gwTokenUrl)),t||(t=this._getOrigin(e)+this._gwTokenUrl),t){const r=new _(e).port;/^http:\/\//i.test(e)&&"7080"===r&&(t=t.replace(/:7080/i,":7443")),t=t.replace(/http:/i,"https:")}return t}if(e.toLowerCase().includes("premium.geosceneonline.com"))return"https://premium.geosceneonline.com/server/tokens"}_processOAuthResponseParams(e,t,r){const s=t._oAuthCred;if(e.code){const i=s.codeVerifier;return s.codeVerifier=null,s.stateUID=null,s.save(),this._getOAuthToken(r.server,e.code,t.appId,this._getRedirectURI(t,!0),i).then((i=>{const n=new j({userId:i.username,server:r.server,token:i.access_token,expires:Date.now()+1e3*i.expires_in,ssl:i.ssl,oAuthState:e.state,_oAuthCred:s});return t.userId=n.userId,s.storage=i.persist?b:D,s.refreshToken=i.refresh_token,s.token=null,s.expires=i.refresh_token_expires_in?Date.now()+1e3*i.refresh_token_expires_in:null,s.userId=n.userId,s.ssl=n.ssl,s.save(),n}))}const i=new j({userId:e.username,server:r.server,token:e.access_token,expires:Date.now()+1e3*Number(e.expires_in),ssl:"true"===e.ssl,oAuthState:e.state,_oAuthCred:s});return t.userId=i.userId,s.storage=e.persist?b:D,s.refreshToken=null,s.token=i.token,s.expires=i.expires,s.userId=i.userId,s.ssl=i.ssl,s.save(),Promise.resolve(i)}_processOAuthPopupParams(e){const t=this._oAuthDfd;if(this._oAuthDfd=null,t)if(clearInterval(this._oAuthIntervalId),this._oAuthOnPopupHandle?.remove(),e.error){const r="access_denied"===e.error,s=new i(r?"identity-manager:user-aborted":"identity-manager:authentication-failed",r?"ABORTED":"OAuth: "+e.error+" - "+e.error_description);t.reject(s)}else this._processOAuthResponseParams(e,t.oinfo_,t.sinfo_).then((e=>{t.resolve(e)})).catch((e=>{t.reject(e)}))}_setOAuthResponseQueryString(e){e&&("?"===e.charAt(0)&&(e=e.substring(1)),this._processOAuthPopupParams(g(e)))}_exchangeToken(e,t,r){return s(`${e}/sharing/rest/oauth2/exchangeToken`,{authMode:"anonymous",method:"post",query:{f:"json",client_id:t,token:r}}).then((e=>e.data.token))}_getPlatformSelf(e,t){return e=e.replace(/^http:/i,"https:"),s(`${e}/sharing/rest/oauth2/platformSelf`,{authMode:"anonymous",headers:{"X-Esri-Auth-Client-Id":t,"X-Esri-Auth-Redirect-Uri":window.location.href.replace(/#.*$/,"")},method:"post",query:{f:"json",expiration:30},withCredentials:!0}).then((e=>e.data))}_getPortalSelf(e,t){let r;if(this._gwDomains.some((t=>(t.regex.test(e)&&(r=t.customBaseUrl),!!r))),r)return Promise.resolve({allSSL:!0,currentVersion:"8.4",customBaseUrl:r,portalMode:"multitenant",supportsOAuth:!0});this._appOrigin.startsWith("https:")?e=e.replace(/^http:/i,"https:").replace(/:7080/i,":7443"):/^http:/i.test(t)&&(e=e.replace(/^https:/i,"http:").replace(/:7443/i,":7080"));return s(e,{query:{f:"json"},authMode:"anonymous",withCredentials:!0}).then((e=>e.data))}_doPortalSignIn(e){const t=this._portalConfig,r=window.location.href,s=this.findServerInfo(e);return!(!t&&!this._isPortalDomain(r)||!(s?s.hasPortal||s.owningSystemUrl&&this._isPortalDomain(s.owningSystemUrl):this._isPortalDomain(e))||!(this._isIdProvider(r,e)||t&&(this._hasSameServerInstance(this._getServerInstanceRoot(t.restBaseUrl),e)||this._isIdProvider(t.restBaseUrl,e))||p(r,e,!0)))}_checkProtocol(e,t,r,s){let n=!0;const o=s?t.adminTokenServiceUrl:t.tokenServiceUrl;if(o.trim().toLowerCase().startsWith("https:")&&!this._appOrigin.startsWith("https:")&&S(o)&&(n=!!this._protocolFunc&&!!this._protocolFunc({resourceUrl:e,serverInfo:t}),!n)){r(new i("identity-manager:aborted","Aborted the Sign-In process to avoid sending password over insecure connection."))}return n}_enqueue(e,t,r,s,i,n){return s||(s=l()),s.resUrl_=e,s.sinfo_=t,s.options_=r,s.admin_=i,s.refresh_=n,this._busy?this._hasSameServerInstance(this._getServerInstanceRoot(e),this._busy.resUrl_)?(this._oAuthDfd&&this._oAuthDfd.oAuthWin_&&this._oAuthDfd.oAuthWin_.focus(),this._soReqs.push(s)):this._xoReqs.push(s):this._doSignIn(s),s.promise}_doSignIn(e){this._busy=e,this._rejectOnPersistedPageShow=!1;const t=t=>{const r=e.options_?.resource,s=e.resUrl_,i=e.refresh_;let n=!1;this.credentials.includes(t)||(i&&this.credentials.includes(i)?(i.userId=t.userId,i.token=t.token,i.expires=t.expires,i.validity=t.validity,i.ssl=t.ssl,i.creationTime=t.creationTime,n=!0,t=i):this.credentials.push(t)),t.resources||(t.resources=[]),t.resources.includes(r||s)||t.resources.push(r||s),t.scope=this._isServerRsrc(s)?"server":"portal",t.emitTokenChange();const o=this._soReqs,a={};this._soReqs=[],o.forEach((e=>{if(!this._isIdenticalService(s,e.resUrl_)){const r=this._getSuffix(e.resUrl_);a[r]||(a[r]=!0,t.resources.push(e.resUrl_))}})),e.resolve(t),o.forEach((e=>{this._hasSameServerInstance(this._getServerInstanceRoot(s),e.resUrl_)?e.resolve(t):this._soReqs.push(e)})),this._busy=e.resUrl_=e.sinfo_=e.refresh_=null,n||this.emit("credential-create",{credential:t}),this._soReqs.length?this._doSignIn(this._soReqs.shift()):this._xoReqs.length&&this._doSignIn(this._xoReqs.shift())},r=t=>{e.reject(t),this._busy=e.resUrl_=e.sinfo_=e.refresh_=null,this._soReqs.length?this._doSignIn(this._soReqs.shift()):this._xoReqs.length&&this._doSignIn(this._xoReqs.shift())},s=(n,a,h,l)=>{const d=e.sinfo_,u=!e.options_||!1!==e.options_.prompt,_=d.hasPortal&&this._findOAuthInfo(e.resUrl_);let g,f;if(n)t(new j({userId:n,server:d.server,token:h||null,expires:null!=l?Number(l):null,ssl:!!a}));else if(window!==window.parent&&this._appUrlObj.query?.["arcgis-auth-origin"]&&this._appUrlObj.query?.["arcgis-auth-portal"]&&this._hasSameServerInstance(this._getServerInstanceRoot(this._appUrlObj.query["arcgis-auth-portal"]),e.resUrl_)){window.parent.postMessage({type:"arcgis:auth:requestCredential"},this._appUrlObj.query["arcgis-auth-origin"]);const s=o(window,"message",(e=>{e.source===window.parent&&e.data&&("arcgis:auth:credential"===e.data.type?(s.remove(),e.data.credential.expires<Date.now()?r(new i("identity-manager:credential-request-failed","Parent application's token has expired.")):t(new j(e.data.credential))):"arcgis:auth:error"===e.data.type&&(s.remove(),"tokenExpiredError"===e.data.error.name?r(new i("identity-manager:credential-request-failed","Parent application's token has expired.")):r(i.fromJSON(e.data.error))))}));c(e.options_?.signal,(()=>{s.remove()}))}else if(_){let n=_._oAuthCred;if(!n){const e=new U(_,b),t=new U(_,D);e.isValid()&&t.isValid()?e.expires>t.expires?(n=e,t.destroy()):(n=t,e.destroy()):n=e.isValid()?e:t,_._oAuthCred=n}if(n.isValid()){g=new j({userId:n.userId,server:d.server,token:n.token,expires:n.expires,ssl:n.ssl,_oAuthCred:n});const r=_.appId!==n.appId&&this._doPortalSignIn(e.resUrl_);r||n.refreshToken?(e._pendingDfd=n.refreshToken?this._getOAuthToken(d.server,n.refreshToken,n.appId).then((e=>(g.expires=Date.now()+1e3*e.expires_in,g.token=e.access_token,g))):Promise.resolve(g),e._pendingDfd.then((e=>r?this._exchangeToken(e.server,_.appId,e.token).then((t=>(e.token=t,e))).catch((()=>e)):e)).then((e=>{t(e)})).catch((()=>{n?.destroy(),s()}))):t(g)}else if(this._oAuthLocationParams&&this._hasSameServerInstance(_.portalUrl,this._oAuthLocationParams.state.portalUrl)&&(this._oAuthLocationParams.access_token||this._oAuthLocationParams.code&&this._oAuthLocationParams.state.uid===n.stateUID&&n.codeVerifier)){const s=this._oAuthLocationParams;this._oAuthLocationParams=null,e._pendingDfd=this._processOAuthResponseParams(s,_,d).then((e=>{t(e)})).catch(r)}else{const s=()=>{u?e._pendingDfd=this.oAuthSignIn(e.resUrl_,d,_,e.options_).then(t,r):(f=new i("identity-manager:not-authenticated","User is not signed in."),r(f))};this._doPortalSignIn(e.resUrl_)?e._pendingDfd=this._getPlatformSelf(d.server,_.appId).then((e=>{p(e.portalUrl,this._appOrigin,!0)?(g=new j({userId:e.username,server:d.server,expires:Date.now()+1e3*e.expires_in,token:e.token}),t(g)):s()})).catch(s):s()}}else if(u){if(this._checkProtocol(e.resUrl_,d,r,e.admin_)){let s=e.options_;e.admin_&&(s=s||{},s.isAdmin=!0),e._pendingDfd=this.signIn(e.resUrl_,d,s).then(t,r)}}else f=new i("identity-manager:not-authenticated","User is not signed in."),r(f)},n=()=>{const s=e.sinfo_,i=s.owningSystemUrl,n=e.options_;let o,a,h,l;if(n&&(o=n.token,a=n.error,h=n.prompt),l=this._findCredential(i,{token:o,resource:e.resUrl_}),!l)for(const e of this.credentials)if(this._isIdProvider(i,e.server)){l=e;break}if(l){const i=this.findCredential(e.resUrl_,l.userId);if(i)t(i);else if(C(s,this._legacyFed)){const e=l.toJSON();e.server=s.server,e.resources=null,t(new j(e))}else{(e._pendingDfd=this.generateToken(this.findServerInfo(l.server),null,{serverUrl:e.resUrl_,token:l.token,signal:e.options_.signal,ssl:l.ssl})).then((r=>{t(new j({userId:l?.userId,server:s.server,token:r.token,expires:null!=r.expires?Number(r.expires):null,ssl:!!r.ssl,isAdmin:e.admin_,validity:r.validity}))}),r)}}else{this._busy=null,o&&(e.options_.token=null);(e._pendingDfd=this.getCredential(i.replace(/\/?$/,"/sharing"),{resource:e.resUrl_,owningTenant:s.owningTenant,signal:e.options_.signal,token:o,error:a,prompt:h})).then((()=>{this._enqueue(e.resUrl_,e.sinfo_,e.options_,e,e.admin_)}),(t=>{e.resUrl_=e.sinfo_=e.refresh_=null,e.reject(t)}))}};this._errbackFunc=r;const a=e.sinfo_.owningSystemUrl,l=this._isServerRsrc(e.resUrl_),d=e.sinfo_._restInfoPms;d?d.promise.then((t=>{const r=e.sinfo_;if(r._restInfoPms){r.adminTokenServiceUrl=r._restInfoPms.adminUrl,r._restInfoPms=null,r.tokenServiceUrl=(h("authInfo.tokenServicesUrl",t)||h("authInfo.tokenServiceUrl",t)||h("tokenServiceUrl",t))??null,r.shortLivedTokenValidity=h("authInfo.shortLivedTokenValidity",t)??null,r.currentVersion=t.currentVersion,r.owningTenant=t.owningTenant;const e=r.owningSystemUrl=t.owningSystemUrl;e&&this._portals.push(e)}l&&r.owningSystemUrl?n():s()}),(()=>{e.sinfo_._restInfoPms=null;const t=new i("identity-manager:server-identification-failed","Unknown resource - could not find token service endpoint.");r(t)})):l&&a?n():e.sinfo_._selfReq?e.sinfo_._selfReq.selfDfd.then((t=>{const r={};let s,i,n,o;return t&&(s=t.user?.username,r.username=s,r.allSSL=t.allSSL,i=t.supportsOAuth,o=parseFloat(t.currentVersion),"multitenant"===t.portalMode&&(n=t.customBaseUrl),e.sinfo_.currentVersion=o),e.sinfo_.webTierAuth=!!s,s&&this.normalizeWebTierAuth?this.generateToken(e.sinfo_,null,{ssl:r.allSSL}).catch((()=>null)).then((e=>(r.portalToken=e&&e.token,r.tokenExpiration=e&&e.expires,r))):!s&&i&&o>=4.4&&!this._findOAuthInfo(e.resUrl_)?this._generateOAuthInfo({portalUrl:e.sinfo_.server,customBaseUrl:n,owningTenant:e.sinfo_._selfReq.owningTenant}).catch((()=>null)).then((()=>r)):r})).catch((()=>null)).then((t=>{e.sinfo_._selfReq=null,t?s(t.username,t.allSSL,t.portalToken,t.tokenExpiration):s()})):s()}_generateOAuthInfo(e){let t,r=null,i=e.portalUrl;const n=e.customBaseUrl,o=e.owningTenant,a=!this._defaultOAuthInfo&&this._createDefaultOAuthInfo&&!this._hasTestedIfAppIsOnPortal;if(a){r=window.location.href;let e=r.indexOf("?");e>-1&&(r=r.slice(0,e)),e=r.search(/\/(apps|home)\//),r=e>-1?r.slice(0,e):null}return a&&r?(this._hasTestedIfAppIsOnPortal=!0,t=s(r+"/sharing/rest",{query:{f:"json"}}).then((()=>{this._defaultOAuthInfo=new T({appId:"arcgisonline",popupCallbackUrl:r+"/home/oauth-callback.html"})}))):t=Promise.resolve(),t.then((()=>{if(this._defaultOAuthInfo)return i=i.replace(/^http:/i,"https:"),s(i+"/sharing/rest/oauth2/validateRedirectUri",{query:{accountId:o,client_id:this._defaultOAuthInfo.appId,redirect_uri:w(this._defaultOAuthInfo.popupCallbackUrl),f:"json"}}).then((e=>{if(e.data.valid){const t=this._defaultOAuthInfo.clone();e.data.urlKey&&n?t.portalUrl="https://"+e.data.urlKey.toLowerCase()+"."+n:t.portalUrl=i,t.popup=window!==window.top||!(p(i,this._appOrigin)||this._gwDomains.some((e=>e.regex.test(i)&&e.regex.test(this._appOrigin)))),this.oAuthInfos.push(t)}}))}))}_doOAuthSignIn(e,t,r,s){const n=r._oAuthCred,a={portalUrl:r.portalUrl};!r.popup&&r.preserveUrlHash&&window.location.hash&&(a.hash=window.location.hash),n.stateUID&&(a.uid=n.stateUID);const h={client_id:r.appId,response_type:n.codeVerifier?"code":"token",state:JSON.stringify(a),expiration:r.expiration,locale:r.locale,redirect_uri:this._getRedirectURI(r,!!n.codeVerifier)};r.forceLogin&&(h.force_login=!0),r.forceUserId&&r.userId&&(h.prepopulatedusername=r.userId),!r.popup&&this._doPortalSignIn(e)&&(h.redirectToUserOrgUrl=!0),n.codeVerifier&&(h.code_challenge=s||n.codeVerifier,h.code_challenge_method=s?"S256":"plain");const l=r.portalUrl.replace(/^http:/i,"https:")+"/sharing/oauth2/authorize",c=l+"?"+m(h);if(r.popup){const e=window.open(c,"esriJSAPIOAuth",r.popupWindowFeatures);if(e)e.focus(),this._oAuthDfd.oAuthWin_=e,this._oAuthIntervalId=setInterval((()=>{if(e.closed){clearInterval(this._oAuthIntervalId),this._oAuthOnPopupHandle.remove();const e=this._oAuthDfd;if(e){const t=new i("identity-manager:user-aborted","ABORTED");e.reject(t)}}}),500),this._oAuthOnPopupHandle=o(window,["arcgis:auth:hash","arcgis:auth:location:search"],(e=>{"arcgis:auth:hash"===e.type?this.setOAuthResponseHash(e.detail):this._setOAuthResponseQueryString(e.detail)}));else{const e=new i("identity-manager:popup-blocked","ABORTED");this._oAuthDfd.reject(e)}}else this._rejectOnPersistedPageShow=!0,this._oAuthRedirectFunc?this._oAuthRedirectFunc({authorizeParams:h,authorizeUrl:l,resourceUrl:e,serverInfo:t,oAuthInfo:r}):window.location.href=c}_getRedirectURI(e,t){const r=window.location.href.replace(/#.*$/,"");if(e.popup)return w(e.popupCallbackUrl);if(t){const e=u(r);return e.query&&["code","error","error_description","message_code","persist","state"].forEach((t=>{delete e.query[t]})),I(e.path,e.query)}return r}}q.prototype.declaredClass="geoscene.identity.IdentityManagerBase";let j=class extends n.EventedAccessor{constructor(e){super(e),this._oAuthCred=null,this.tokenRefreshBuffer=2,e?._oAuthCred&&(this._oAuthCred=e._oAuthCred)}initialize(){this.resources=this.resources||[],null==this.creationTime&&(this.creationTime=Date.now())}refreshToken(){const e=r.findServerInfo(this.server),t=e?.owningSystemUrl,s=!!t&&"server"===this.scope,i=s&&C(e,r._legacyFed),n=e.webTierAuth,o=n&&r.normalizeWebTierAuth,a=P[this.server],h=a?.[this.userId];let l,c=this.resources&&this.resources[0],d=s?r.findServerInfo(t):null,u={username:this.userId,password:h};if(n&&!o)return;s&&!d&&r.serverInfos.some((e=>(r._isIdProvider(t,e.server)&&(d=e),!!d)));const p=d?r.findCredential(d.server,this.userId):null;if(!s||p){if(!i){if(s)l={serverUrl:c,token:p?.token,ssl:p&&p.ssl};else if(o)u=null,l={ssl:this.ssl};else{if(!h){let t;return c&&(c=r._sanitizeUrl(c),this._enqueued=1,t=r._enqueue(c,e,null,null,this.isAdmin,this),t.then((()=>{this._enqueued=0,this.refreshServerTokens()})).catch((()=>{this._enqueued=0}))),t}this.isAdmin&&(l={isAdmin:!0})}return r.generateToken(s?d:e,s?null:u,l).then((e=>{this.token=e.token,this.expires=null!=e.expires?Number(e.expires):null,this.creationTime=Date.now(),this.validity=e.validity,this.emitTokenChange(),this.refreshServerTokens()})).catch((()=>{}))}p?.refreshToken()}}refreshServerTokens(){"portal"===this.scope&&r.credentials.forEach((e=>{const t=r.findServerInfo(e.server),s=t?.owningSystemUrl;e!==this&&e.userId===this.userId&&s&&"server"===e.scope&&(r._hasSameServerInstance(this.server,s)||r._isIdProvider(s,this.server))&&(C(t,r._legacyFed)?(e.token=this.token,e.expires=this.expires,e.creationTime=this.creationTime,e.validity=this.validity,e.emitTokenChange()):e.refreshToken())}))}emitTokenChange(e){clearTimeout(this._refreshTimer);const t=this.server?r.findServerInfo(this.server):null,s=t?.owningSystemUrl,i=s?r.findServerInfo(s):null;!1===e||s&&"portal"!==this.scope&&(!i?.webTierAuth||r.normalizeWebTierAuth)||null==this.expires&&null==this.validity||this._startRefreshTimer(),this.emit("token-change")}destroy(){this.userId=this.server=this.token=this.expires=this.validity=this.resources=this.creationTime=null,this._oAuthCred&&(this._oAuthCred.destroy(),this._oAuthCred=null);const e=r.credentials.indexOf(this);e>-1&&r.credentials.splice(e,1),this.emitTokenChange(),this.emit("destroy")}toJSON(){const e=a({userId:this.userId,server:this.server,token:this.token,expires:this.expires,validity:this.validity,ssl:this.ssl,isAdmin:this.isAdmin,creationTime:this.creationTime,scope:this.scope}),t=this.resources;return t&&t.length>0&&(e.resources=t.slice()),e}_startRefreshTimer(){clearTimeout(this._refreshTimer);const e=6e4*this.tokenRefreshBuffer,t=2**31-1;let r=(this.validity?this.creationTime+6e4*this.validity:this.expires)-Date.now();r<0?r=0:r>t&&(r=t),this._refreshTimer=setTimeout(this.refreshToken.bind(this),r>e?r-e:r)}};e([A()],j.prototype,"creationTime",void 0),e([A()],j.prototype,"expires",void 0),e([A()],j.prototype,"isAdmin",void 0),e([A()],j.prototype,"oAuthState",void 0),e([A()],j.prototype,"resources",void 0),e([A()],j.prototype,"scope",void 0),e([A()],j.prototype,"server",void 0),e([A()],j.prototype,"ssl",void 0),e([A()],j.prototype,"token",void 0),e([A()],j.prototype,"tokenRefreshBuffer",void 0),e([A()],j.prototype,"userId",void 0),e([A()],j.prototype,"validity",void 0),j=e([k("geoscene.identity.Credential")],j);export{j as Credential,q as IdentityManagerBase};
5
+ import{_ as e}from"../chunks/tslib.es6.js";import t from"../config.js";import{id as r}from"../kernel.js";import s from"../request.js";import i from"../core/Error.js";import n from"../core/Evented.js";import{on as o}from"../core/events.js";import{fixJson as a}from"../core/lang.js";import{getDeepValue as h}from"../core/object.js";import{createResolver as l,onAbort as c,isAborted as d}from"../core/promiseUtils.js";import{urlToObject as u,hasSameOrigin as p,Url as _,queryToObject as g,base64UrlEncode as f,objectToQuery as m,normalize as v,getProxyRule as S,makeAbsolute as w,addQueryParameters as I}from"../core/urlUtils.js";import{property as A}from"../core/accessorSupport/decorators/property.js";import"../core/has.js";import"../core/Logger.js";import{subclass as k}from"../core/accessorSupport/decorators/subclass.js";import y from"./IdentityModal.js";import U from"./OAuthCredential.js";import T from"./OAuthInfo.js";import x from"./ServerInfo.js";import{isSecureProxyService as O}from"../portal/support/urlUtils.js";const P={},R=e=>{const t=new _(e.owningSystemUrl).host,r=new _(e.server).host,s=/.+\.Grcgis\.cn$/i;return s.test(t)&&s.test(r)},C=(e,t)=>!!(R(e)&&t&&t.some((t=>t.test(e.server))));let b=null,D=null;try{b=window.localStorage,D=window.sessionStorage}catch{}class q extends n{constructor(){super(),this._portalConfig=globalThis.esriGeowConfig,this.serverInfos=[],this.oAuthInfos=[],this.credentials=[],this._soReqs=[],this._xoReqs=[],this._portals=[],this._defaultOAuthInfo=null,this._defaultTokenValidity=60,this.dialog=null,this.tokenValidity=null,this.normalizeWebTierAuth=!1,this._appOrigin="null"!==window.origin?window.origin:window.location.origin,this._appUrlObj=u(window.location.href),this._busy=null,this._rejectOnPersistedPageShow=!1,this._oAuthLocationParams=null,this._gwTokenUrl="/sharing/rest/generateToken",this._agsRest="/rest/services",this._agsPortal=/\/sharing(\/|$)/i,this._agsAdmin=/(https?:\/\/[^\/]+\/[^\/]+)\/admin\/?(\/.*)?$/i,this._adminSvcs=/\/rest\/admin\/services(\/|$)/i,this._gwDomains=[{customBaseUrl: "www.geosceneonline.cn",regex: /^https?:\/\/www\.geosceneonline\.cn/i,tokenServiceUrl: "https://www.geosceneonline.cn/geoscene/sharing/rest/generateToken"}],this._legacyFed=[],this._regexSDirUrl=/http.+\/rest\/services\/?/gi,this._regexServerType=/(\/(FeatureServer|GPServer|GeoDataServer|GeocodeServer|GeoenrichmentServer|GeometryServer|GlobeServer|ImageServer|KnowledgeGraphServer|MapServer|MissionServer|MobileServer|NAServer|NetworkDiagramServer|OGCFeatureServer|ParcelFabricServer|RelationalCatalogServer|SceneServer|StreamServer|UtilityNetworkServer|ValidationServer|VectorTileServer|VersionManagementServer|VideoServer)).*/gi,this._gwUser=/http.+\/users\/([^\/]+)\/?.*/i,this._gwItem=/http.+\/items\/([^\/]+)\/?.*/i,this._gwGroup=/http.+\/groups\/([^\/]+)\/?.*/i,this._rePortalTokenSvc=/\/sharing(\/rest)?\/generatetoken/i,this._createDefaultOAuthInfo=!0,this._hasTestedIfAppIsOnPortal=!1,this._getOAuthLocationParams(),window.addEventListener("pageshow",(e=>{this._pageShowHandler(e)}))}registerServers(e){const t=this.serverInfos;t?(e=e.filter((e=>!this.findServerInfo(e.server))),this.serverInfos=t.concat(e)):this.serverInfos=e,e.forEach((e=>{e.owningSystemUrl&&this._portals.push(e.owningSystemUrl),e.hasPortal&&this._portals.push(e.server)}))}registerOAuthInfos(e){const t=this.oAuthInfos;if(t){for(const r of e){const e=this.findOAuthInfo(r.portalUrl);e&&t.splice(t.indexOf(e),1)}this.oAuthInfos=t.concat(e)}else this.oAuthInfos=e}registerToken(e){e={...e};const t=this._sanitizeUrl(e.server),r=this._isServerRsrc(t);let s,i=this.findServerInfo(t),n=!0;i||(i=new x,i.server=this._getServerInstanceRoot(t),r?i.hasServer=!0:(i.tokenServiceUrl=this._getTokenSvcUrl(t),i.hasPortal=!0),this.registerServers([i])),s=this._findCredential(t),s?(delete e.server,Object.assign(s,e),n=!1):(s=new j({userId:e.userId,server:i.server,token:e.token,expires:e.expires,ssl:e.ssl,scope:r?"server":"portal"}),s.resources=[t],this.credentials.push(s)),s.emitTokenChange(!1),n||s.refreshServerTokens()}toJSON(){return a({serverInfos:this.serverInfos.map((e=>e.toJSON())),oAuthInfos:this.oAuthInfos.map((e=>e.toJSON())),credentials:this.credentials.map((e=>e.toJSON()))})}initialize(e){if(!e)return;"string"==typeof e&&(e=JSON.parse(e));const t=e.serverInfos,r=e.oAuthInfos,s=e.credentials;if(t){const e=[];t.forEach((t=>{t.server&&t.tokenServiceUrl&&e.push(t.declaredClass?t:new x(t))})),e.length&&this.registerServers(e)}if(r){const e=[];r.forEach((t=>{t.appId&&e.push(t.declaredClass?t:new T(t))})),e.length&&this.registerOAuthInfos(e)}s&&s.forEach((e=>{e.server&&e.token&&e.expires&&e.expires>Date.now()&&((e=e.declaredClass?e:new j(e)).emitTokenChange(),this.credentials.push(e))}))}findServerInfo(e){let t;e=this._sanitizeUrl(e);for(const r of this.serverInfos)if(this._hasSameServerInstance(r.server,e)){t=r;break}return t}findOAuthInfo(e){let t;e=this._sanitizeUrl(e);for(const r of this.oAuthInfos)if(this._hasSameServerInstance(r.portalUrl,e)){t=r;break}return t}findCredential(e,t){if(!e)return;let r;e=this._sanitizeUrl(e);const s=this._isServerRsrc(e)?"server":"portal";if(t){for(const i of this.credentials)if(this._hasSameServerInstance(i.server,e)&&t===i.userId&&i.scope===s){r=i;break}}else for(const i of this.credentials)if(this._hasSameServerInstance(i.server,e)&&-1!==this._getIdenticalSvcIdx(e,i)&&i.scope===s){r=i;break}return r}getCredential(e,t){let r,s,n=!0;t&&(r=!!t.token,s=t.error,n=!1!==t.prompt),t={...t},e=this._sanitizeUrl(e);const o=new AbortController,a=l();if(t.signal&&c(t.signal,(()=>{o.abort()})),c(o,(()=>{a.reject(new i("identity-manager:user-aborted","ABORTED"))})),d(o))return a.promise;t.signal=o.signal;const h=this._isAdminResource(e),u=r?this.findCredential(e):null;let _;if(u&&s&&s.details&&498===s.details.httpStatus)u.destroy();else if(u)return _=new i("identity-manager:not-authorized","You are currently signed in as: '"+u.userId+"'. You do not have access to this resource: "+e,{error:s}),a.reject(_),a.promise;const g=this._findCredential(e,t);if(g)return a.resolve(g),a.promise;let f=this.findServerInfo(e);if(f)!f.hasPortal&&f.server&&f.owningSystemUrl&&this._hasSameServerInstance(f.server,f.owningSystemUrl)&&(f.hasPortal=!0),!f.hasServer&&this._isServerRsrc(e)&&(f._restInfoPms=this._getTokenSvcUrl(e),f.hasServer=!0);else{const t=this._getTokenSvcUrl(e);if(!t)return _=new i("identity-manager:unknown-resource","Unknown resource - could not find token service endpoint."),a.reject(_),a.promise;f=new x,f.server=this._getServerInstanceRoot(e),"string"==typeof t?(f.tokenServiceUrl=t,f.hasPortal=!0):(f._restInfoPms=t,f.hasServer=!0),this.registerServers([f])}return f.hasPortal&&void 0===f._selfReq&&(n||p(f.tokenServiceUrl,this._appOrigin)||this._gwDomains.some((e=>e.tokenServiceUrl===f.tokenServiceUrl)))&&(f._selfReq={owningTenant:t?.owningTenant,selfDfd:this._getPortalSelf(f.tokenServiceUrl.replace(this._rePortalTokenSvc,"/sharing/rest/portals/self"),e)}),this._enqueue(e,f,t,a,h)}getResourceName(e){return this._isRESTService(e)?e.replace(this._regexSDirUrl,"").replace(this._regexServerType,"")||"":this._gwUser.test(e)&&e.replace(this._gwUser,"$1")||this._gwItem.test(e)&&e.replace(this._gwItem,"$1")||this._gwGroup.test(e)&&e.replace(this._gwGroup,"$1")||""}generateToken(e,t,r){const n=this._rePortalTokenSvc.test(e.tokenServiceUrl),o=new _(this._appOrigin),a=e.shortLivedTokenValidity;let h,l,c,d,u,g,f,m;t&&(m=this.tokenValidity||a||this._defaultTokenValidity,m>a&&a>0&&(m=a)),r&&(h=r.isAdmin,l=r.serverUrl,c=r.token,g=r.signal,f=r.ssl,e.customParameters=r.customParameters),h?d=e.adminTokenServiceUrl:(d=e.tokenServiceUrl,u=new _(d.toLowerCase()),e.webTierAuth&&r?.serverUrl&&!f&&"http"===o.scheme&&(p(o.uri,d,!0)||"https"===u.scheme&&o.host===u.host&&"7080"===o.port&&"7443"===u.port)&&(d=d.replace(/^https:/i,"http:").replace(/:7443/i,":7080")));const v={query:{request:"getToken",username:t?.username,password:t?.password,serverUrl:l,token:c,expiration:m,referer:h||n?this._appOrigin:null,client:h?"referer":null,f:"json",...e.customParameters},method:"post",authMode:"anonymous",useProxy:this._useProxy(e,r),signal:g,...r?.ioArgs};n||(v.withCredentials=!1);return s(d,v).then((r=>{const s=r.data;if(!s?.token)return new i("identity-manager:authentication-failed","Unable to generate token");const n=e.server;return P[n]||(P[n]={}),t&&(P[n][t.username]=t.password),s.validity=m,s}))}isBusy(){return!!this._busy}checkSignInStatus(e){return this.checkAppAccess(e,"").then((e=>e.credential))}checkAppAccess(e,t,r){let n=!1;return this.getCredential(e,{prompt:!1}).then((o=>{let a;const h={f:"json"};if("portal"===o.scope)if(t&&(this._doPortalSignIn(e)||r?.force))a=o.server+"/sharing/rest/oauth2/validateAppAccess",h.client_id=t;else{if(!o.token)return{credential:o};a=o.server+"/sharing/rest"}else{if(!o.token)return{credential:o};a=o.server+"/rest/services"}return o.token&&(h.token=o.token),s(a,{query:h,authMode:"anonymous"}).then((e=>{if(!1===e.data.valid)throw new i("identity-manager:not-authorized",`You are currently signed in as: '${o.userId}'.`,e.data);return n=!!e.data.viewOnlyUserTypeApp,{credential:o}})).catch((e=>{if("identity-manager:not-authorized"===e.name)throw e;const t=e.details?.httpStatus;if(498===t)throw o.destroy(),new i("identity-manager:not-authenticated","User is not signed in.");if(400===t)throw new i("identity-manager:invalid-request");return{credential:o}}))})).then((e=>({credential:e.credential,viewOnly:n})))}setOAuthResponseHash(e){e&&("#"===e.charAt(0)&&(e=e.substring(1)),this._processOAuthPopupParams(g(e)))}setOAuthRedirectionHandler(e){this._oAuthRedirectFunc=e}setProtocolErrorHandler(e){this._protocolFunc=e}signIn(e,t,r={}){const s=l(),n=()=>{h?.remove(),d?.remove(),this.dialog?.destroy(),this.dialog=h=d=null},o=()=>{n(),this._oAuthDfd=null,s.reject(new i("identity-manager:user-aborted","ABORTED"))};r.signal&&c(r.signal,(()=>{o()}));const a=new y({open:!0,resource:this.getResourceName(e),server:t.server});this.dialog=a,this.emit("dialog-create");let h=a.on("cancel",o),d=a.on("submit",(e=>{this.generateToken(t,e,{isAdmin:r.isAdmin,signal:r.signal}).then((i=>{n();const o=new j({userId:e.username,server:t.server,token:i.token,expires:null!=i.expires?Number(i.expires):null,ssl:!!i.ssl,isAdmin:r.isAdmin,validity:i.validity});s.resolve(o)})).catch((e=>{a.error=e,a.signingIn=!1}))}));return s.promise}oAuthSignIn(e,t,r,s){this._oAuthDfd=l();const n=this._oAuthDfd;let o;s?.signal&&c(s.signal,(()=>{const e=this._oAuthDfd&&this._oAuthDfd.oAuthWin_;e&&!e.closed?e.close():this.dialog&&u()})),n.resUrl_=e,n.sinfo_=t,n.oinfo_=r;const a=r._oAuthCred;if(a.storage&&("authorization-code"===r.flowType||"auto"===r.flowType&&t.currentVersion>=8.4)){let e=crypto.getRandomValues(new Uint8Array(32));o=f(e),a.codeVerifier=o,e=crypto.getRandomValues(new Uint8Array(32)),a.stateUID=f(e),a.save()||(a.codeVerifier=o=null)}else a.codeVerifier=null;let h,d;this._getCodeChallenge(o).then((i=>{const n=!s||!1!==s.oAuthPopupConfirmation;if(!r.popup||!n)return void this._doOAuthSignIn(e,t,r,i);const o=new y({oAuthPrompt:!0,server:t.server,open:!0});this.dialog=o,this.emit("dialog-create"),h=o.on("cancel",u),d=o.on("submit",(()=>{p(),this._doOAuthSignIn(e,t,r,i)}))}));const u=()=>{p(),this._oAuthDfd=null,n.reject(new i("identity-manager:user-aborted","ABORTED"))},p=()=>{h?.remove(),d?.remove(),this.dialog?.destroy(),this.dialog=null};return n.promise}destroyCredentials(){if(this.credentials){this.credentials.slice().forEach((e=>{e.destroy()}))}this.emit("credentials-destroy")}enablePostMessageAuth(e="https://www.geosceneonline.cn/geoscene/sharing/rest"){this._postMessageAuthHandle&&this._postMessageAuthHandle.remove(),this._postMessageAuthHandle=o(window,"message",(t=>{if((t.origin===this._appOrigin)&&"arcgis:auth:requestCredential"===t.data?.type){const r=t.source;this.getCredential(e).then((e=>{r.postMessage({type:"arcgis:auth:credential",credential:{expires:e.expires,server:e.server,ssl:e.ssl,token:e.token,userId:e.userId}},t.origin)})).catch((e=>{r.postMessage({type:"arcgis:auth:error",error:{name:e.name,message:e.message}},t.origin)}))}}))}disablePostMessageAuth(){this._postMessageAuthHandle&&(this._postMessageAuthHandle.remove(),this._postMessageAuthHandle=null)}_getOAuthLocationParams(){let e=window.location.hash;if(e){"#"===e.charAt(0)&&(e=e.substring(1));const t=g(e);let r=!1;if(t.access_token&&t.expires_in&&t.state&&t.hasOwnProperty("username"))try{t.state=JSON.parse(t.state),t.state.portalUrl&&(this._oAuthLocationParams=t,r=!0)}catch{}else if(t.error&&t.error_description&&(console.log("IdentityManager OAuth Error: ",t.error," - ",t.error_description),"access_denied"===t.error&&(r=!0,t.state)))try{t.state=JSON.parse(t.state)}catch{}r&&(window.location.hash=t.state?.hash||"")}let t=window.location.search;if(t){"?"===t.charAt(0)&&(t=t.substring(1));const e=g(t);let r=!1;if(e.code&&e.state)try{e.state=JSON.parse(e.state),e.state.portalUrl&&e.state.uid&&(this._oAuthLocationParams=e,r=!0)}catch{}else if(e.error&&e.error_description&&(console.log("IdentityManager OAuth Error: ",e.error," - ",e.error_description),"access_denied"===e.error&&(r=!0,e.state)))try{e.state=JSON.parse(e.state)}catch{}if(r){const t={...e};["code","error","error_description","message_code","persist","state"].forEach((e=>{delete t[e]}));const r=m(t),s=window.location.pathname+(r?`?${r}`:"")+(e.state?.hash||"");window.history.replaceState(window.history.state,"",s)}}}_getOAuthToken(e,t,r,i,n){return e=e.replace(/^http:/i,"https:"),s(`${e}/sharing/rest/oauth2/token`,{authMode:"anonymous",method:"post",query:i&&n?{grant_type:"authorization_code",code:t,redirect_uri:i,client_id:r,code_verifier:n}:{grant_type:"refresh_token",refresh_token:t,client_id:r}}).then((e=>e.data))}_getCodeChallenge(e){if(e&&globalThis.isSecureContext){const t=(new TextEncoder).encode(e);return crypto.subtle.digest("SHA-256",t).then((e=>f(new Uint8Array(e))))}return Promise.resolve(null)}_pageShowHandler(e){if(e.persisted&&this.isBusy()&&this._rejectOnPersistedPageShow){const e=new i("identity-manager:user-aborted","ABORTED");this._errbackFunc(e)}}_findCredential(e,t){let r,s,i,n,o=-1;const a=t?.token,h=t?.resource,l=this._isServerRsrc(e)?"server":"portal",c=this.credentials.filter((t=>this._hasSameServerInstance(t.server,e)&&t.scope===l));if(e=h||e,c.length)if(1===c.length){if(r=c[0],i=this.findServerInfo(r.server),s=i?.owningSystemUrl,n=s?this.findCredential(s,r.userId):void 0,o=this._getIdenticalSvcIdx(e,r),!a)return-1===o&&r.resources.push(e),this._addResource(e,n),r;-1!==o&&(r.resources.splice(o,1),this._removeResource(e,n))}else{let t,r;if(c.some((a=>(r=this._getIdenticalSvcIdx(e,a),-1!==r&&(t=a,i=this.findServerInfo(t.server),s=i?.owningSystemUrl,n=s?this.findCredential(s,t.userId):void 0,o=r,!0)))),a)t&&(t.resources.splice(o,1),this._removeResource(e,n));else if(t)return this._addResource(e,n),t}}_findOAuthInfo(e){let t=this.findOAuthInfo(e);if(!t)for(const r of this.oAuthInfos)if(this._isIdProvider(r.portalUrl,e)){t=r;break}return t}_addResource(e,t){t&&-1===this._getIdenticalSvcIdx(e,t)&&t.resources.push(e)}_removeResource(e,t){let r=-1;t&&(r=this._getIdenticalSvcIdx(e,t),r>-1&&t.resources.splice(r,1))}_useProxy(e,t){return t?.isAdmin&&!p(e.adminTokenServiceUrl,this._appOrigin)||!this._isPortalDomain(e.tokenServiceUrl)&&"10.1"===String(e.currentVersion)&&!p(e.tokenServiceUrl,this._appOrigin)}_getOrigin(e){const t=new _(e);return t.scheme+"://"+t.host+(null!=t.port?":"+t.port:"")}_getServerInstanceRoot(e){const t=e.toLowerCase();let r=t.indexOf(this._agsRest);return-1===r&&this._isAdminResource(e)&&(r=this._agsAdmin.test(e)?e.replace(this._agsAdmin,"$1").length:e.search(this._adminSvcs)),-1!==r||O(t)||(r=t.indexOf("/sharing")),-1===r&&"/"===t.substr(-1)&&(r=t.length-1),r>-1?e.substring(0,r):e}_hasSameServerInstance(e,t){return"/"===e.substr(-1)&&(e=e.slice(0,-1)),e=e.toLowerCase(),t=this._getServerInstanceRoot(t).toLowerCase(),e=this._normalizeAGOLorgDomain(e),t=this._normalizeAGOLorgDomain(t),(e=e.substr(e.indexOf(":")))===(t=t.substr(t.indexOf(":")))}_normalizeAGOLorgDomain(e){const t=/^https?:\/\/(?:cdn|[a-z\d-]+\.maps)\.geoscene\.cn/i,r=/^https?:\/\/(?:cdndev|[a-z\d-]+\.mapsdevext)\.geoscene\.cn/i,s=/^https?:\/\/(?:cdnqa|[a-z\d-]+\.>mapsqa)\.geoscene\.cn/i;return t.test(e)?e=e.replace(t,"https://www.geosceneonline.cn/geoscene"):r.test(e)?e=e.replace(r,"https://devext.geoscene.cn"):s.test(e)&&(e=e.replace(s,"https://qaext.geoscene.cn")),e}_sanitizeUrl(e){const r=(t.request.proxyUrl||"").toLowerCase(),s=r?e.toLowerCase().indexOf(r+"?"):-1;return-1!==s&&(e=e.substring(s+r.length+1)),e=v(e),u(e).path}_isRESTService(e){return e.includes(this._agsRest)}_isAdminResource(e){return this._agsAdmin.test(e)||this._adminSvcs.test(e)}_isServerRsrc(e){return this._isRESTService(e)||this._isAdminResource(e)}_isIdenticalService(e,t){let r=!1;if(this._isRESTService(e)&&this._isRESTService(t)){const s=this._getSuffix(e).toLowerCase(),i=this._getSuffix(t).toLowerCase();if(r=s===i,!r){const e=/(.*)\/(MapServer|FeatureServer|UtilityNetworkServer).*/gi;r=s.replaceAll(e,"$1")===i.replaceAll(e,"$1")}}else this._isAdminResource(e)&&this._isAdminResource(t)?r=!0:this._isServerRsrc(e)||this._isServerRsrc(t)||!this._isPortalDomain(e)||(r=!0);return r}_isPortalDomain(e){const r=new _(e.toLowerCase()),s=this._portalConfig;let i=this._gwDomains.some((e=>e.regex.test(r.uri)));return!i&&s&&(i=this._hasSameServerInstance(this._getServerInstanceRoot(s.restBaseUrl),r.uri)),i||t.portalUrl&&(i=p(r,t.portalUrl,!0)),i||(i=this._portals.some((e=>this._hasSameServerInstance(e,r.uri)))),i=i||this._agsPortal.test(r.path),i}_isIdProvider(e,t){let r=-1,s=-1;this._gwDomains.forEach(((i,n)=>{-1===r&&i.regex.test(e)&&(r=n),-1===s&&i.regex.test(t)&&(s=n)}));let i=!1;if(r>-1&&s>-1&&(0===r||4===r?0!==s&&4!==s||(i=!0):1===r?1!==s&&2!==s||(i=!0):2===r?2===s&&(i=!0):3===r&&3===s&&(i=!0)),!i){const r=this.findServerInfo(t),s=r?.owningSystemUrl;s&&R(r)&&this._isPortalDomain(s)&&this._isIdProvider(e,s)&&(i=!0)}return i}_getIdenticalSvcIdx(e,t){let r=-1;for(let s=0;s<t.resources.length;s++){const i=t.resources[s];if(this._isIdenticalService(e,i)){r=s;break}}return r}_getSuffix(e){return e.replace(this._regexSDirUrl,"").replace(this._regexServerType,"$1")}_getTokenSvcUrl(e){let t,r,i;if(this._isRESTService(e)||this._isAdminResource(e)){const i=this._getServerInstanceRoot(e);return t=i+"/admin/generateToken",r=s(e=i+"/rest/info",{query:{f:"json"}}).then((e=>e.data)),{adminUrl:t,promise:r}}if(this._isPortalDomain(e)){let t="";if(this._gwDomains.some((r=>(r.regex.test(e)&&(t=r.tokenServiceUrl),!!t))),t||this._portals.some((r=>(this._hasSameServerInstance(r,e)&&(t=r+this._gwTokenUrl),!!t))),t||(i=e.toLowerCase().indexOf("/sharing"),-1!==i&&(t=e.substring(0,i)+this._gwTokenUrl)),t||(t=this._getOrigin(e)+this._gwTokenUrl),t){const r=new _(e).port;/^http:\/\//i.test(e)&&"7080"===r&&(t=t.replace(/:7080/i,":7443")),t=t.replace(/http:/i,"https:")}return t}if(e.toLowerCase().includes("premium.geosceneonline.com"))return"https://premium.geosceneonline.com/server/tokens"}_processOAuthResponseParams(e,t,r){const s=t._oAuthCred;if(e.code){const i=s.codeVerifier;return s.codeVerifier=null,s.stateUID=null,s.save(),this._getOAuthToken(r.server,e.code,t.appId,this._getRedirectURI(t,!0),i).then((i=>{const n=new j({userId:i.username,server:r.server,token:i.access_token,expires:Date.now()+1e3*i.expires_in,ssl:i.ssl,oAuthState:e.state,_oAuthCred:s});return t.userId=n.userId,s.storage=i.persist?b:D,s.refreshToken=i.refresh_token,s.token=null,s.expires=i.refresh_token_expires_in?Date.now()+1e3*i.refresh_token_expires_in:null,s.userId=n.userId,s.ssl=n.ssl,s.save(),n}))}const i=new j({userId:e.username,server:r.server,token:e.access_token,expires:Date.now()+1e3*Number(e.expires_in),ssl:"true"===e.ssl,oAuthState:e.state,_oAuthCred:s});return t.userId=i.userId,s.storage=e.persist?b:D,s.refreshToken=null,s.token=i.token,s.expires=i.expires,s.userId=i.userId,s.ssl=i.ssl,s.save(),Promise.resolve(i)}_processOAuthPopupParams(e){const t=this._oAuthDfd;if(this._oAuthDfd=null,t)if(clearInterval(this._oAuthIntervalId),this._oAuthOnPopupHandle?.remove(),e.error){const r="access_denied"===e.error,s=new i(r?"identity-manager:user-aborted":"identity-manager:authentication-failed",r?"ABORTED":"OAuth: "+e.error+" - "+e.error_description);t.reject(s)}else this._processOAuthResponseParams(e,t.oinfo_,t.sinfo_).then((e=>{t.resolve(e)})).catch((e=>{t.reject(e)}))}_setOAuthResponseQueryString(e){e&&("?"===e.charAt(0)&&(e=e.substring(1)),this._processOAuthPopupParams(g(e)))}_exchangeToken(e,t,r){return s(`${e}/sharing/rest/oauth2/exchangeToken`,{authMode:"anonymous",method:"post",query:{f:"json",client_id:t,token:r}}).then((e=>e.data.token))}_getPlatformSelf(e,t){return e=e.replace(/^http:/i,"https:"),s(`${e}/sharing/rest/oauth2/platformSelf`,{authMode:"anonymous",headers:{"X-Esri-Auth-Client-Id":t,"X-Esri-Auth-Redirect-Uri":window.location.href.replace(/#.*$/,"")},method:"post",query:{f:"json",expiration:30},withCredentials:!0}).then((e=>e.data))}_getPortalSelf(e,t){let r;if(this._gwDomains.some((t=>(t.regex.test(e)&&(r=t.customBaseUrl),!!r))),r)return Promise.resolve({allSSL:!0,currentVersion:"8.4",customBaseUrl:r,portalMode:"multitenant",supportsOAuth:!0});this._appOrigin.startsWith("https:")?e=e.replace(/^http:/i,"https:").replace(/:7080/i,":7443"):/^http:/i.test(t)&&(e=e.replace(/^https:/i,"http:").replace(/:7443/i,":7080"));return s(e,{query:{f:"json"},authMode:"anonymous",withCredentials:!0}).then((e=>e.data))}_doPortalSignIn(e){const t=this._portalConfig,r=window.location.href,s=this.findServerInfo(e);return!(!t&&!this._isPortalDomain(r)||!(s?s.hasPortal||s.owningSystemUrl&&this._isPortalDomain(s.owningSystemUrl):this._isPortalDomain(e))||!(this._isIdProvider(r,e)||t&&(this._hasSameServerInstance(this._getServerInstanceRoot(t.restBaseUrl),e)||this._isIdProvider(t.restBaseUrl,e))||p(r,e,!0)))}_checkProtocol(e,t,r,s){let n=!0;const o=s?t.adminTokenServiceUrl:t.tokenServiceUrl;if(o.trim().toLowerCase().startsWith("https:")&&!this._appOrigin.startsWith("https:")&&S(o)&&(n=!!this._protocolFunc&&!!this._protocolFunc({resourceUrl:e,serverInfo:t}),!n)){r(new i("identity-manager:aborted","Aborted the Sign-In process to avoid sending password over insecure connection."))}return n}_enqueue(e,t,r,s,i,n){return s||(s=l()),s.resUrl_=e,s.sinfo_=t,s.options_=r,s.admin_=i,s.refresh_=n,this._busy?this._hasSameServerInstance(this._getServerInstanceRoot(e),this._busy.resUrl_)?(this._oAuthDfd&&this._oAuthDfd.oAuthWin_&&this._oAuthDfd.oAuthWin_.focus(),this._soReqs.push(s)):this._xoReqs.push(s):this._doSignIn(s),s.promise}_doSignIn(e){this._busy=e,this._rejectOnPersistedPageShow=!1;const t=t=>{const r=e.options_?.resource,s=e.resUrl_,i=e.refresh_;let n=!1;this.credentials.includes(t)||(i&&this.credentials.includes(i)?(i.userId=t.userId,i.token=t.token,i.expires=t.expires,i.validity=t.validity,i.ssl=t.ssl,i.creationTime=t.creationTime,n=!0,t=i):this.credentials.push(t)),t.resources||(t.resources=[]),t.resources.includes(r||s)||t.resources.push(r||s),t.scope=this._isServerRsrc(s)?"server":"portal",t.emitTokenChange();const o=this._soReqs,a={};this._soReqs=[],o.forEach((e=>{if(!this._isIdenticalService(s,e.resUrl_)){const r=this._getSuffix(e.resUrl_);a[r]||(a[r]=!0,t.resources.push(e.resUrl_))}})),e.resolve(t),o.forEach((e=>{this._hasSameServerInstance(this._getServerInstanceRoot(s),e.resUrl_)?e.resolve(t):this._soReqs.push(e)})),this._busy=e.resUrl_=e.sinfo_=e.refresh_=null,n||this.emit("credential-create",{credential:t}),this._soReqs.length?this._doSignIn(this._soReqs.shift()):this._xoReqs.length&&this._doSignIn(this._xoReqs.shift())},r=t=>{e.reject(t),this._busy=e.resUrl_=e.sinfo_=e.refresh_=null,this._soReqs.length?this._doSignIn(this._soReqs.shift()):this._xoReqs.length&&this._doSignIn(this._xoReqs.shift())},s=(n,a,h,l)=>{const d=e.sinfo_,u=!e.options_||!1!==e.options_.prompt,_=d.hasPortal&&this._findOAuthInfo(e.resUrl_);let g,f;if(n)t(new j({userId:n,server:d.server,token:h||null,expires:null!=l?Number(l):null,ssl:!!a}));else if(window!==window.parent&&this._appUrlObj.query?.["arcgis-auth-origin"]&&this._appUrlObj.query?.["arcgis-auth-portal"]&&this._hasSameServerInstance(this._getServerInstanceRoot(this._appUrlObj.query["arcgis-auth-portal"]),e.resUrl_)){window.parent.postMessage({type:"arcgis:auth:requestCredential"},this._appUrlObj.query["arcgis-auth-origin"]);const s=o(window,"message",(e=>{e.source===window.parent&&e.data&&("arcgis:auth:credential"===e.data.type?(s.remove(),e.data.credential.expires<Date.now()?r(new i("identity-manager:credential-request-failed","Parent application's token has expired.")):t(new j(e.data.credential))):"arcgis:auth:error"===e.data.type&&(s.remove(),"tokenExpiredError"===e.data.error.name?r(new i("identity-manager:credential-request-failed","Parent application's token has expired.")):r(i.fromJSON(e.data.error))))}));c(e.options_?.signal,(()=>{s.remove()}))}else if(_){let n=_._oAuthCred;if(!n){const e=new U(_,b),t=new U(_,D);e.isValid()&&t.isValid()?e.expires>t.expires?(n=e,t.destroy()):(n=t,e.destroy()):n=e.isValid()?e:t,_._oAuthCred=n}if(n.isValid()){g=new j({userId:n.userId,server:d.server,token:n.token,expires:n.expires,ssl:n.ssl,_oAuthCred:n});const r=_.appId!==n.appId&&this._doPortalSignIn(e.resUrl_);r||n.refreshToken?(e._pendingDfd=n.refreshToken?this._getOAuthToken(d.server,n.refreshToken,n.appId).then((e=>(g.expires=Date.now()+1e3*e.expires_in,g.token=e.access_token,g))):Promise.resolve(g),e._pendingDfd.then((e=>r?this._exchangeToken(e.server,_.appId,e.token).then((t=>(e.token=t,e))).catch((()=>e)):e)).then((e=>{t(e)})).catch((()=>{n?.destroy(),s()}))):t(g)}else if(this._oAuthLocationParams&&this._hasSameServerInstance(_.portalUrl,this._oAuthLocationParams.state.portalUrl)&&(this._oAuthLocationParams.access_token||this._oAuthLocationParams.code&&this._oAuthLocationParams.state.uid===n.stateUID&&n.codeVerifier)){const s=this._oAuthLocationParams;this._oAuthLocationParams=null,e._pendingDfd=this._processOAuthResponseParams(s,_,d).then((e=>{t(e)})).catch(r)}else{const s=()=>{u?e._pendingDfd=this.oAuthSignIn(e.resUrl_,d,_,e.options_).then(t,r):(f=new i("identity-manager:not-authenticated","User is not signed in."),r(f))};this._doPortalSignIn(e.resUrl_)?e._pendingDfd=this._getPlatformSelf(d.server,_.appId).then((e=>{p(e.portalUrl,this._appOrigin,!0)?(g=new j({userId:e.username,server:d.server,expires:Date.now()+1e3*e.expires_in,token:e.token}),t(g)):s()})).catch(s):s()}}else if(u){if(this._checkProtocol(e.resUrl_,d,r,e.admin_)){let s=e.options_;e.admin_&&(s=s||{},s.isAdmin=!0),e._pendingDfd=this.signIn(e.resUrl_,d,s).then(t,r)}}else f=new i("identity-manager:not-authenticated","User is not signed in."),r(f)},n=()=>{const s=e.sinfo_,i=s.owningSystemUrl,n=e.options_;let o,a,h,l;if(n&&(o=n.token,a=n.error,h=n.prompt),l=this._findCredential(i,{token:o,resource:e.resUrl_}),!l)for(const e of this.credentials)if(this._isIdProvider(i,e.server)){l=e;break}if(l){const i=this.findCredential(e.resUrl_,l.userId);if(i)t(i);else if(C(s,this._legacyFed)){const e=l.toJSON();e.server=s.server,e.resources=null,t(new j(e))}else{(e._pendingDfd=this.generateToken(this.findServerInfo(l.server),null,{serverUrl:e.resUrl_,token:l.token,signal:e.options_.signal,ssl:l.ssl})).then((r=>{t(new j({userId:l?.userId,server:s.server,token:r.token,expires:null!=r.expires?Number(r.expires):null,ssl:!!r.ssl,isAdmin:e.admin_,validity:r.validity}))}),r)}}else{this._busy=null,o&&(e.options_.token=null);(e._pendingDfd=this.getCredential(i.replace(/\/?$/,"/sharing"),{resource:e.resUrl_,owningTenant:s.owningTenant,signal:e.options_.signal,token:o,error:a,prompt:h})).then((()=>{this._enqueue(e.resUrl_,e.sinfo_,e.options_,e,e.admin_)}),(t=>{e.resUrl_=e.sinfo_=e.refresh_=null,e.reject(t)}))}};this._errbackFunc=r;const a=e.sinfo_.owningSystemUrl,l=this._isServerRsrc(e.resUrl_),d=e.sinfo_._restInfoPms;d?d.promise.then((t=>{const r=e.sinfo_;if(r._restInfoPms){r.adminTokenServiceUrl=r._restInfoPms.adminUrl,r._restInfoPms=null,r.tokenServiceUrl=(h("authInfo.tokenServicesUrl",t)||h("authInfo.tokenServiceUrl",t)||h("tokenServiceUrl",t))??null,r.shortLivedTokenValidity=h("authInfo.shortLivedTokenValidity",t)??null,r.currentVersion=t.currentVersion,r.owningTenant=t.owningTenant;const e=r.owningSystemUrl=t.owningSystemUrl;e&&this._portals.push(e)}l&&r.owningSystemUrl?n():s()}),(()=>{e.sinfo_._restInfoPms=null;const t=new i("identity-manager:server-identification-failed","Unknown resource - could not find token service endpoint.");r(t)})):l&&a?n():e.sinfo_._selfReq?e.sinfo_._selfReq.selfDfd.then((t=>{const r={};let s,i,n,o;return t&&(s=t.user?.username,r.username=s,r.allSSL=t.allSSL,i=t.supportsOAuth,o=parseFloat(t.currentVersion),"multitenant"===t.portalMode&&(n=t.customBaseUrl),e.sinfo_.currentVersion=o),e.sinfo_.webTierAuth=!!s,s&&this.normalizeWebTierAuth?this.generateToken(e.sinfo_,null,{ssl:r.allSSL}).catch((()=>null)).then((e=>(r.portalToken=e&&e.token,r.tokenExpiration=e&&e.expires,r))):!s&&i&&o>=4.4&&!this._findOAuthInfo(e.resUrl_)?this._generateOAuthInfo({portalUrl:e.sinfo_.server,customBaseUrl:n,owningTenant:e.sinfo_._selfReq.owningTenant}).catch((()=>null)).then((()=>r)):r})).catch((()=>null)).then((t=>{e.sinfo_._selfReq=null,t?s(t.username,t.allSSL,t.portalToken,t.tokenExpiration):s()})):s()}_generateOAuthInfo(e){let t,r=null,i=e.portalUrl;const n=e.customBaseUrl,o=e.owningTenant,a=!this._defaultOAuthInfo&&this._createDefaultOAuthInfo&&!this._hasTestedIfAppIsOnPortal;if(a){r=window.location.href;let e=r.indexOf("?");e>-1&&(r=r.slice(0,e)),e=r.search(/\/(apps|home)\//),r=e>-1?r.slice(0,e):null}return a&&r?(this._hasTestedIfAppIsOnPortal=!0,t=s(r+"/sharing/rest",{query:{f:"json"}}).then((()=>{this._defaultOAuthInfo=new T({appId:"arcgisonline",popupCallbackUrl:r+"/home/oauth-callback.html"})}))):t=Promise.resolve(),t.then((()=>{if(this._defaultOAuthInfo)return i=i.replace(/^http:/i,"https:"),s(i+"/sharing/rest/oauth2/validateRedirectUri",{query:{accountId:o,client_id:this._defaultOAuthInfo.appId,redirect_uri:w(this._defaultOAuthInfo.popupCallbackUrl),f:"json"}}).then((e=>{if(e.data.valid){const t=this._defaultOAuthInfo.clone();e.data.urlKey&&n?t.portalUrl="https://"+e.data.urlKey.toLowerCase()+"."+n:t.portalUrl=i,t.popup=window!==window.top||!(p(i,this._appOrigin)||this._gwDomains.some((e=>e.regex.test(i)&&e.regex.test(this._appOrigin)))),this.oAuthInfos.push(t)}}))}))}_doOAuthSignIn(e,t,r,s){const n=r._oAuthCred,a={portalUrl:r.portalUrl};!r.popup&&r.preserveUrlHash&&window.location.hash&&(a.hash=window.location.hash),n.stateUID&&(a.uid=n.stateUID);const h={client_id:r.appId,response_type:n.codeVerifier?"code":"token",state:JSON.stringify(a),expiration:r.expiration,locale:r.locale,redirect_uri:this._getRedirectURI(r,!!n.codeVerifier)};r.forceLogin&&(h.force_login=!0),r.forceUserId&&r.userId&&(h.prepopulatedusername=r.userId),!r.popup&&this._doPortalSignIn(e)&&(h.redirectToUserOrgUrl=!0),n.codeVerifier&&(h.code_challenge=s||n.codeVerifier,h.code_challenge_method=s?"S256":"plain");const l=r.portalUrl.replace(/^http:/i,"https:")+"/sharing/oauth2/authorize",c=l+"?"+m(h);if(r.popup){const e=window.open(c,"esriJSAPIOAuth",r.popupWindowFeatures);if(e)e.focus(),this._oAuthDfd.oAuthWin_=e,this._oAuthIntervalId=setInterval((()=>{if(e.closed){clearInterval(this._oAuthIntervalId),this._oAuthOnPopupHandle.remove();const e=this._oAuthDfd;if(e){const t=new i("identity-manager:user-aborted","ABORTED");e.reject(t)}}}),500),this._oAuthOnPopupHandle=o(window,["arcgis:auth:hash","arcgis:auth:location:search"],(e=>{"arcgis:auth:hash"===e.type?this.setOAuthResponseHash(e.detail):this._setOAuthResponseQueryString(e.detail)}));else{const e=new i("identity-manager:popup-blocked","ABORTED");this._oAuthDfd.reject(e)}}else this._rejectOnPersistedPageShow=!0,this._oAuthRedirectFunc?this._oAuthRedirectFunc({authorizeParams:h,authorizeUrl:l,resourceUrl:e,serverInfo:t,oAuthInfo:r}):window.location.href=c}_getRedirectURI(e,t){const r=window.location.href.replace(/#.*$/,"");if(e.popup)return w(e.popupCallbackUrl);if(t){const e=u(r);return e.query&&["code","error","error_description","message_code","persist","state"].forEach((t=>{delete e.query[t]})),I(e.path,e.query)}return r}}q.prototype.declaredClass="geoscene.identity.IdentityManagerBase";let j=class extends n.EventedAccessor{constructor(e){super(e),this._oAuthCred=null,this.tokenRefreshBuffer=2,e?._oAuthCred&&(this._oAuthCred=e._oAuthCred)}initialize(){this.resources=this.resources||[],null==this.creationTime&&(this.creationTime=Date.now())}refreshToken(){const e=r.findServerInfo(this.server),t=e?.owningSystemUrl,s=!!t&&"server"===this.scope,i=s&&C(e,r._legacyFed),n=e.webTierAuth,o=n&&r.normalizeWebTierAuth,a=P[this.server],h=a?.[this.userId];let l,c=this.resources&&this.resources[0],d=s?r.findServerInfo(t):null,u={username:this.userId,password:h};if(n&&!o)return;s&&!d&&r.serverInfos.some((e=>(r._isIdProvider(t,e.server)&&(d=e),!!d)));const p=d?r.findCredential(d.server,this.userId):null;if(!s||p){if(!i){if(s)l={serverUrl:c,token:p?.token,ssl:p&&p.ssl};else if(o)u=null,l={ssl:this.ssl};else{if(!h){let t;return c&&(c=r._sanitizeUrl(c),this._enqueued=1,t=r._enqueue(c,e,null,null,this.isAdmin,this),t.then((()=>{this._enqueued=0,this.refreshServerTokens()})).catch((()=>{this._enqueued=0}))),t}this.isAdmin&&(l={isAdmin:!0})}return r.generateToken(s?d:e,s?null:u,l).then((e=>{this.token=e.token,this.expires=null!=e.expires?Number(e.expires):null,this.creationTime=Date.now(),this.validity=e.validity,this.emitTokenChange(),this.refreshServerTokens()})).catch((()=>{}))}p?.refreshToken()}}refreshServerTokens(){"portal"===this.scope&&r.credentials.forEach((e=>{const t=r.findServerInfo(e.server),s=t?.owningSystemUrl;e!==this&&e.userId===this.userId&&s&&"server"===e.scope&&(r._hasSameServerInstance(this.server,s)||r._isIdProvider(s,this.server))&&(C(t,r._legacyFed)?(e.token=this.token,e.expires=this.expires,e.creationTime=this.creationTime,e.validity=this.validity,e.emitTokenChange()):e.refreshToken())}))}emitTokenChange(e){clearTimeout(this._refreshTimer);const t=this.server?r.findServerInfo(this.server):null,s=t?.owningSystemUrl,i=s?r.findServerInfo(s):null;!1===e||s&&"portal"!==this.scope&&(!i?.webTierAuth||r.normalizeWebTierAuth)||null==this.expires&&null==this.validity||this._startRefreshTimer(),this.emit("token-change")}destroy(){this.userId=this.server=this.token=this.expires=this.validity=this.resources=this.creationTime=null,this._oAuthCred&&(this._oAuthCred.destroy(),this._oAuthCred=null);const e=r.credentials.indexOf(this);e>-1&&r.credentials.splice(e,1),this.emitTokenChange(),this.emit("destroy")}toJSON(){const e=a({userId:this.userId,server:this.server,token:this.token,expires:this.expires,validity:this.validity,ssl:this.ssl,isAdmin:this.isAdmin,creationTime:this.creationTime,scope:this.scope}),t=this.resources;return t&&t.length>0&&(e.resources=t.slice()),e}_startRefreshTimer(){clearTimeout(this._refreshTimer);const e=6e4*this.tokenRefreshBuffer,t=2**31-1;let r=(this.validity?this.creationTime+6e4*this.validity:this.expires)-Date.now();r<0?r=0:r>t&&(r=t),this._refreshTimer=setTimeout(this.refreshToken.bind(this),r>e?r-e:r)}};e([A()],j.prototype,"creationTime",void 0),e([A()],j.prototype,"expires",void 0),e([A()],j.prototype,"isAdmin",void 0),e([A()],j.prototype,"oAuthState",void 0),e([A()],j.prototype,"resources",void 0),e([A()],j.prototype,"scope",void 0),e([A()],j.prototype,"server",void 0),e([A()],j.prototype,"ssl",void 0),e([A()],j.prototype,"token",void 0),e([A()],j.prototype,"tokenRefreshBuffer",void 0),e([A()],j.prototype,"userId",void 0),e([A()],j.prototype,"validity",void 0),j=e([k("geoscene.identity.Credential")],j);export{j as Credential,q as IdentityManagerBase};
@@ -2,4 +2,4 @@
2
2
  All material copyright GeoScene, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.geoscene.cn/4.29/geoscene/copyright.txt for details.
4
4
  */
5
- import{_ as t}from"../chunks/tslib.es6.js";import"../intl.js";import{property as e}from"../core/accessorSupport/decorators/property.js";import"../core/has.js";import"../core/Logger.js";import"../core/RandomLCG.js";import{subclass as s}from"../core/accessorSupport/decorators/subclass.js";import o from"../widgets/Widget.js";import{loadCalciteComponents as i}from"../widgets/support/componentsUtils.js";import"../widgets/support/widgetUtils.js";import{messageBundle as n}from"../widgets/support/decorators/messageBundle.js";import{tsx as r}from"../widgets/support/jsxFactory.js";import{getCalciteThemeClass as l}from"../support/themeUtils.js";import{substitute as a}from"../intl/substitute.js";const c="geoscene-identity-modal",p={base:c,info:`${c}__info`,notice:`${c}__notice`},d="GeoScene Online";let u=class extends o{constructor(t,e){super(t,e),this.container=document.createElement("div"),this.error=null,this.oAuthPrompt=!1,this.open=!1,this.signingIn=!1,this.server=null,this.resource=null,this._usernameInputNode=null,this._passwordInputNode=null,document.body.appendChild(this.container)}loadDependencies(){return i({button:()=>import("@esri/calcite-components/dist/components/calcite-button.js"),input:()=>import("@esri/calcite-components/dist/components/calcite-input.js"),label:()=>import("@esri/calcite-components/dist/components/calcite-label.js"),modal:()=>import("@esri/calcite-components/dist/components/calcite-modal.js"),notice:()=>import("@esri/calcite-components/dist/components/calcite-notice.js")})}get title(){return this.commonMessages?.auth.signIn}render(){const{open:t,title:e,messages:s,signingIn:o,oAuthPrompt:i,server:n,resource:c,error:u}=this,{info:m,oAuthInfo:h,lblItem:g,invalidUser:b,noAuthService:v,lblUser:y,lblPwd:f,lblCancel:_,lblSigning:I,lblOk:j}=s;return r("div",{class:this.classes(p.base,l())},r("form",{bind:this,onsubmit:this._submit},r("calcite-modal",{bind:this,open:t,outsideCloseDisabled:!0,scale:"s",widthScale:"s",onCalciteModalClose:this._cancel,onCalciteModalOpen:this._focusUsernameInput},r("div",{slot:"header"},e),r("div",{slot:"content"},r("div",{class:p.info},a(i?h:m,{server:n&&/\.arcgis\.com/i.test(n)?d:n,resource:`(${c||g})`})),u?r("calcite-notice",{class:p.notice,icon:"exclamation-mark-triangle",kind:"danger",open:!0},r("div",{slot:"message"},u.details?.httpStatus?b:v)):null,i?null:[r("calcite-label",null,y,r("calcite-input",{afterCreate:t=>this._usernameInputNode=t,autocomplete:"off",bind:this,name:"username",required:!0,spellcheck:!1,type:"text",value:""})),r("calcite-label",null,f,r("calcite-input",{afterCreate:t=>this._passwordInputNode=t,bind:this,name:"password",required:!0,type:"password",value:""}))]),r("calcite-button",{appearance:"outline",bind:this,onclick:this._cancel,slot:"secondary",type:"button",width:"full"},_),r("calcite-button",{loading:!!o,slot:"primary",type:"submit",width:"full"},o?I:j))))}_focusUsernameInput(){requestAnimationFrame((()=>{this._usernameInputNode?.setFocus()}))}_cancel(){this._set("signingIn",!1),this.open=!1,this._usernameInputNode&&(this._usernameInputNode.value=""),this._passwordInputNode&&(this._passwordInputNode.value=""),this.emit("cancel")}_submit(t){t.preventDefault(),this._set("signingIn",!0);const e=this.oAuthPrompt?{}:{username:this._usernameInputNode?.value,password:this._passwordInputNode?.value};this.emit("submit",e)}};t([e({readOnly:!0})],u.prototype,"container",void 0),t([e(),n("geoscene/t9n/common")],u.prototype,"commonMessages",void 0),t([e()],u.prototype,"error",void 0),t([e(),n("geoscene/identity/t9n/identity")],u.prototype,"messages",void 0),t([e()],u.prototype,"oAuthPrompt",void 0),t([e()],u.prototype,"open",void 0),t([e()],u.prototype,"signingIn",void 0),t([e()],u.prototype,"server",void 0),t([e({readOnly:!0})],u.prototype,"title",null),t([e()],u.prototype,"resource",void 0),u=t([s("geoscene.identity.IdentityModal")],u);const m=u;export{m as default};
5
+ import{_ as t}from"../chunks/tslib.es6.js";import"../intl.js";import{property as e}from"../core/accessorSupport/decorators/property.js";import"../core/has.js";import"../core/Logger.js";import"../core/RandomLCG.js";import{subclass as s}from"../core/accessorSupport/decorators/subclass.js";import o from"../widgets/Widget.js";import{loadCalciteComponents as i}from"../widgets/support/componentsUtils.js";import"../widgets/support/widgetUtils.js";import{messageBundle as n}from"../widgets/support/decorators/messageBundle.js";import{tsx as r}from"../widgets/support/jsxFactory.js";import{getCalciteThemeClass as l}from"../support/themeUtils.js";import{substitute as a}from"../intl/substitute.js";const c="geoscene-identity-modal",p={base:c,info:`${c}__info`,notice:`${c}__notice`},d="GeoScene Online";let u=class extends o{constructor(t,e){super(t,e),this.container=document.createElement("div"),this.error=null,this.oAuthPrompt=!1,this.open=!1,this.signingIn=!1,this.server=null,this.resource=null,this._usernameInputNode=null,this._passwordInputNode=null,document.body.appendChild(this.container)}loadDependencies(){return i({button:()=>import("@esri/calcite-components/dist/components/calcite-button.js"),input:()=>import("@esri/calcite-components/dist/components/calcite-input.js"),label:()=>import("@esri/calcite-components/dist/components/calcite-label.js"),modal:()=>import("@esri/calcite-components/dist/components/calcite-modal.js"),notice:()=>import("@esri/calcite-components/dist/components/calcite-notice.js")})}get title(){return this.commonMessages?.auth.signIn}render(){const{open:t,title:e,messages:s,signingIn:o,oAuthPrompt:i,server:n,resource:c,error:u}=this,{info:m,oAuthInfo:h,lblItem:g,invalidUser:b,noAuthService:v,lblUser:y,lblPwd:f,lblCancel:_,lblSigning:I,lblOk:j}=s;return r("div",{class:this.classes(p.base,l())},r("form",{bind:this,onsubmit:this._submit},r("calcite-modal",{bind:this,open:t,outsideCloseDisabled:!0,scale:"s",widthScale:"s",onCalciteModalClose:this._cancel,onCalciteModalOpen:this._focusUsernameInput},r("div",{slot:"header"},e),r("div",{slot:"content"},r("div",{class:p.info},a(i?h:m,{server:n&&/\.geoscene\.cn/i.test(n)?d:n,resource:`(${c||g})`})),u?r("calcite-notice",{class:p.notice,icon:"exclamation-mark-triangle",kind:"danger",open:!0},r("div",{slot:"message"},u.details?.httpStatus?b:v)):null,i?null:[r("calcite-label",null,y,r("calcite-input",{afterCreate:t=>this._usernameInputNode=t,autocomplete:"off",bind:this,name:"username",required:!0,spellcheck:!1,type:"text",value:""})),r("calcite-label",null,f,r("calcite-input",{afterCreate:t=>this._passwordInputNode=t,bind:this,name:"password",required:!0,type:"password",value:""}))]),r("calcite-button",{appearance:"outline",bind:this,onclick:this._cancel,slot:"secondary",type:"button",width:"full"},_),r("calcite-button",{loading:!!o,slot:"primary",type:"submit",width:"full"},o?I:j))))}_focusUsernameInput(){requestAnimationFrame((()=>{this._usernameInputNode?.setFocus()}))}_cancel(){this._set("signingIn",!1),this.open=!1,this._usernameInputNode&&(this._usernameInputNode.value=""),this._passwordInputNode&&(this._passwordInputNode.value=""),this.emit("cancel")}_submit(t){t.preventDefault(),this._set("signingIn",!0);const e=this.oAuthPrompt?{}:{username:this._usernameInputNode?.value,password:this._passwordInputNode?.value};this.emit("submit",e)}};t([e({readOnly:!0})],u.prototype,"container",void 0),t([e(),n("geoscene/t9n/common")],u.prototype,"commonMessages",void 0),t([e()],u.prototype,"error",void 0),t([e(),n("geoscene/identity/t9n/identity")],u.prototype,"messages",void 0),t([e()],u.prototype,"oAuthPrompt",void 0),t([e()],u.prototype,"open",void 0),t([e()],u.prototype,"signingIn",void 0),t([e()],u.prototype,"server",void 0),t([e({readOnly:!0})],u.prototype,"title",null),t([e()],u.prototype,"resource",void 0),u=t([s("geoscene.identity.IdentityModal")],u);const m=u;export{m as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright GeoScene, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.geoscene.cn/4.29/geoscene/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../chunks/tslib.es6.js";import r from"../request.js";import t from"../core/Error.js";import{loadAll as s}from"../core/loadAll.js";import{MultiOriginJSONMixin as i}from"../core/MultiOriginJSONSupport.js";import{throwIfAbortError as o}from"../core/promiseUtils.js";import{urlToObject as a,objectToQuery as l,makeAbsolute as n}from"../core/urlUtils.js";import{property as p}from"../core/accessorSupport/decorators/property.js";import{cast as c}from"../core/accessorSupport/decorators/cast.js";import"../core/RandomLCG.js";import"../core/has.js";import{reader as u}from"../core/accessorSupport/decorators/reader.js";import{subclass as m}from"../core/accessorSupport/decorators/subclass.js";import{writer as h}from"../core/accessorSupport/decorators/writer.js";import d from"../geometry/SpatialReference.js";import y from"./Layer.js";import{APIKeyMixin as f}from"./mixins/APIKeyMixin.js";import{ArcGISCachedService as v}from"./mixins/ArcGISCachedService.js";import{ArcGISMapService as g}from"./mixins/ArcGISMapService.js";import{ArcGISService as S}from"./mixins/ArcGISService.js";import{BlendLayer as _}from"./mixins/BlendLayer.js";import{CustomParametersMixin as j}from"./mixins/CustomParametersMixin.js";import{OperationalLayer as T}from"./mixins/OperationalLayer.js";import{PortalLayer as b}from"./mixins/PortalLayer.js";import{RefreshableLayer as w}from"./mixins/RefreshableLayer.js";import{ScaleRangeLayer as O}from"./mixins/ScaleRangeLayer.js";import{SublayersOwner as L}from"./mixins/SublayersOwner.js";import{parse as R,isHostedAgolService as U,isArcGISUrl as P}from"./support/arcgisLayerUrl.js";import{url as x}from"./support/commonProperties.js";import{createTileBitmap as A}from"./support/imageBitmapUtils.js";import M from"./support/Sublayer.js";var W;const I=["Canvas/World_Dark_Gray_Base","Canvas/World_Dark_Gray_Reference","Canvas/World_Light_Gray_Base","Canvas/World_Light_Gray_Reference","Elevation/World_Hillshade","Elevation/World_Hillshade_Dark","Ocean/World_Ocean_Base","Ocean/World_Ocean_Reference","Ocean_Basemap","Reference/World_Boundaries_and_Places","Reference/World_Boundaries_and_Places_Alternate","Reference/World_Transportation","World_Imagery","World_Street_Map","World_Topo_Map"];let B=W=class extends(_(O(L(v(g(T(b(S(i(w(f(j(y))))))))))))){constructor(...e){super(...e),this.listMode="show",this.isReference=null,this.operationalLayerType="ArcGISTiledMapServiceLayer",this.resampling=!0,this.sourceJSON=null,this.spatialReference=null,this.path=null,this.sublayers=null,this.type="tile",this.url=null}normalizeCtorArgs(e,r){return"string"==typeof e?{url:e,...r}:e}load(e){const r=null!=e?e.signal:null;return this.addResolvingPromise(this.loadFromPortal({supportedTypes:["Map Service"]},e).catch(o).then((()=>this._fetchService(r)))),Promise.resolve(this)}get attributionDataUrl(){const e=this.parsedUrl?.path.toLowerCase();return e?this._getDefaultAttribution(this._getMapName(e)):null}readSpatialReference(e,r){return(e=e||r.tileInfo?.spatialReference)&&d.fromJSON(e)}writeSublayers(e,r,t,s){if(!this.loaded||!e)return;const i=e.slice().reverse().flatten((({sublayers:e})=>e&&e.toArray().reverse())).toArray(),o=[],a={writeSublayerStructure:!1,...s};i.forEach((e=>{const r=e.write({},a);o.push(r)}));o.some((e=>Object.keys(e).length>1))&&(r.layers=o)}get tileServers(){return this._getDefaultTileServers(this.parsedUrl?.path)}castTileServers(e){return Array.isArray(e)?e.map((e=>a(e).path)):null}fetchTile(e,t,s,i={}){const{signal:o}=i,a=this.getTileUrl(e,t,s),l={responseType:"image",signal:o,query:{...this.refreshParameters}};return r(a,l).then((e=>e.data))}async fetchImageBitmapTile(e,t,s,i={}){const{signal:o}=i;if(this.fetchTile!==W.prototype.fetchTile){const r=await this.fetchTile(e,t,s,i);return A(r,e,t,s,o)}const a=this.getTileUrl(e,t,s),l={responseType:"blob",signal:o,query:{...this.refreshParameters}},{data:n}=await r(a,l);return A(n,e,t,s,o)}getTileUrl(e,r,t){const s=!this.capabilities.operations.supportsTileMap&&this.supportsBlankTile,i=l({...this.parsedUrl?.query,blankTile:!s&&null,...this.customParameters,token:this.apiKey}),o=this.tileServers;return`${o&&o.length?o[r%o.length]:this.parsedUrl?.path}/tile/${e}/${r}/${t}${i?"?"+i:""}`}loadAll(){return s(this,(e=>{e(this.allSublayers)}))}_fetchService(e){return new Promise(((s,i)=>{if(this.sourceJSON){if(null!=this.sourceJSON.bandCount&&null!=this.sourceJSON.pixelSizeX)throw new t("tile-layer:unsupported-url","use ImageryTileLayer to open a tiled image service");return void s({data:this.sourceJSON})}if(!this.parsedUrl)throw new t("tile-layer:undefined-url","layer's url is not defined");const o=R(this.parsedUrl.path);if(null!=o&&"ImageServer"===o.serverType)throw new t("tile-layer:unsupported-url","use ImageryTileLayer to open a tiled image service");r(this.parsedUrl.path,{query:{f:"json",...this.parsedUrl.query,...this.customParameters,token:this.apiKey},responseType:"json",signal:e}).then(s,i)})).then((r=>{let t=this.url;if(r.ssl&&(t=this.url=t.replace(/^http:/i,"https:")),this.sourceJSON=r.data,this.read(r.data,{origin:"service",url:this.parsedUrl}),10.1===this.version&&!U(t))return this._fetchServerVersion(t,e).then((e=>{this.read({currentVersion:e})})).catch((()=>{}))}))}_fetchServerVersion(e,s){if(!P(e))return Promise.reject();const i=e.replace(/(.*\/rest)\/.*/i,"$1")+"/info";return r(i,{query:{f:"json",...this.customParameters,token:this.apiKey},responseType:"json",signal:s}).then((e=>{if(e.data&&e.data.currentVersion)return e.data.currentVersion;throw new t("tile-layer:version-not-available")}))}_getMapName(e){const r=e.match(/^(?:https?:)?\/\/(server\.arcgisonline\.com|services\.arcgisonline\.com|ibasemaps-api\.arcgis\.com)\/arcgis\/rest\/services\/([^\/]+(\/[^\/]+)*)\/mapserver/i);return r?r[2]:void 0}_getDefaultAttribution(e){if(null==e)return null;let r;e=e.toLowerCase();for(let t=0,s=I.length;t<s;t++)if(r=I[t],r.toLowerCase().includes(e))return n("//static.arcgis.com/attribution/"+r);return null}_getDefaultTileServers(e){if(null==e)return[];const r=-1!==e.search(/^(?:https?:)?\/\/server\.arcgisonline\.com/i),t=-1!==e.search(/^(?:https?:)?\/\/services\.arcgisonline\.com/i);return r||t?[e,e.replace(r?/server\.arcgisonline/i:/services\.arcgisonline/i,r?"services.arcgisonline":"server.arcgisonline")]:[]}get hasOverriddenFetchTile(){return!this.fetchTile[C]}};e([p({readOnly:!0})],B.prototype,"attributionDataUrl",null),e([p({type:["show","hide","hide-children"]})],B.prototype,"listMode",void 0),e([p({json:{read:!0,write:!0}})],B.prototype,"blendMode",void 0),e([p({type:Boolean,json:{read:!1,write:{enabled:!0,overridePolicy:()=>({enabled:!1})}}})],B.prototype,"isReference",void 0),e([p({readOnly:!0,type:["ArcGISTiledMapServiceLayer"]})],B.prototype,"operationalLayerType",void 0),e([p({type:Boolean})],B.prototype,"resampling",void 0),e([p()],B.prototype,"sourceJSON",void 0),e([p({type:d})],B.prototype,"spatialReference",void 0),e([u("spatialReference",["spatialReference","tileInfo"])],B.prototype,"readSpatialReference",null),e([p({type:String,json:{origins:{"web-scene":{read:!0,write:!0}},read:!1}})],B.prototype,"path",void 0),e([p({readOnly:!0})],B.prototype,"sublayers",void 0),e([h("sublayers",{layers:{type:[M]}})],B.prototype,"writeSublayers",null),e([p({json:{read:!1,write:!1}})],B.prototype,"popupEnabled",void 0),e([p()],B.prototype,"tileServers",null),e([c("tileServers")],B.prototype,"castTileServers",null),e([p({readOnly:!0,json:{read:!1}})],B.prototype,"type",void 0),e([p(x)],B.prototype,"url",void 0),B=W=e([m("geoscene.layers.TileLayer")],B);const C=Symbol("default-fetch-tile");B.prototype.fetchTile[C]=!0;const N=B;export{N as default};
5
+ import{_ as e}from"../chunks/tslib.es6.js";import r from"../request.js";import t from"../core/Error.js";import{loadAll as s}from"../core/loadAll.js";import{MultiOriginJSONMixin as i}from"../core/MultiOriginJSONSupport.js";import{throwIfAbortError as o}from"../core/promiseUtils.js";import{urlToObject as a,objectToQuery as l,makeAbsolute as n}from"../core/urlUtils.js";import{property as p}from"../core/accessorSupport/decorators/property.js";import{cast as c}from"../core/accessorSupport/decorators/cast.js";import"../core/RandomLCG.js";import"../core/has.js";import{reader as u}from"../core/accessorSupport/decorators/reader.js";import{subclass as m}from"../core/accessorSupport/decorators/subclass.js";import{writer as h}from"../core/accessorSupport/decorators/writer.js";import d from"../geometry/SpatialReference.js";import y from"./Layer.js";import{APIKeyMixin as f}from"./mixins/APIKeyMixin.js";import{ArcGISCachedService as v}from"./mixins/ArcGISCachedService.js";import{ArcGISMapService as g}from"./mixins/ArcGISMapService.js";import{ArcGISService as S}from"./mixins/ArcGISService.js";import{BlendLayer as _}from"./mixins/BlendLayer.js";import{CustomParametersMixin as j}from"./mixins/CustomParametersMixin.js";import{OperationalLayer as T}from"./mixins/OperationalLayer.js";import{PortalLayer as b}from"./mixins/PortalLayer.js";import{RefreshableLayer as w}from"./mixins/RefreshableLayer.js";import{ScaleRangeLayer as O}from"./mixins/ScaleRangeLayer.js";import{SublayersOwner as L}from"./mixins/SublayersOwner.js";import{parse as R,isHostedAgolService as U,isArcGISUrl as P}from"./support/arcgisLayerUrl.js";import{url as x}from"./support/commonProperties.js";import{createTileBitmap as A}from"./support/imageBitmapUtils.js";import M from"./support/Sublayer.js";var W;const I=["Canvas/World_Dark_Gray_Base","Canvas/World_Dark_Gray_Reference","Canvas/World_Light_Gray_Base","Canvas/World_Light_Gray_Reference","Elevation/World_Hillshade","Elevation/World_Hillshade_Dark","Ocean/World_Ocean_Base","Ocean/World_Ocean_Reference","Ocean_Basemap","Reference/World_Boundaries_and_Places","Reference/World_Boundaries_and_Places_Alternate","Reference/World_Transportation","World_Imagery","World_Street_Map","World_Topo_Map"];let B=W=class extends(_(O(L(v(g(T(b(S(i(w(f(j(y))))))))))))){constructor(...e){super(...e),this.listMode="show",this.isReference=null,this.operationalLayerType="ArcGISTiledMapServiceLayer",this.resampling=!0,this.sourceJSON=null,this.spatialReference=null,this.path=null,this.sublayers=null,this.type="tile",this.url=null}normalizeCtorArgs(e,r){return"string"==typeof e?{url:e,...r}:e}load(e){const r=null!=e?e.signal:null;return this.addResolvingPromise(this.loadFromPortal({supportedTypes:["Map Service"]},e).catch(o).then((()=>this._fetchService(r)))),Promise.resolve(this)}get attributionDataUrl(){const e=this.parsedUrl?.path.toLowerCase();return e?this._getDefaultAttribution(this._getMapName(e)):null}readSpatialReference(e,r){return(e=e||r.tileInfo?.spatialReference)&&d.fromJSON(e)}writeSublayers(e,r,t,s){if(!this.loaded||!e)return;const i=e.slice().reverse().flatten((({sublayers:e})=>e&&e.toArray().reverse())).toArray(),o=[],a={writeSublayerStructure:!1,...s};i.forEach((e=>{const r=e.write({},a);o.push(r)}));o.some((e=>Object.keys(e).length>1))&&(r.layers=o)}get tileServers(){return this._getDefaultTileServers(this.parsedUrl?.path)}castTileServers(e){return Array.isArray(e)?e.map((e=>a(e).path)):null}fetchTile(e,t,s,i={}){const{signal:o}=i,a=this.getTileUrl(e,t,s),l={responseType:"image",signal:o,query:{...this.refreshParameters}};return r(a,l).then((e=>e.data))}async fetchImageBitmapTile(e,t,s,i={}){const{signal:o}=i;if(this.fetchTile!==W.prototype.fetchTile){const r=await this.fetchTile(e,t,s,i);return A(r,e,t,s,o)}const a=this.getTileUrl(e,t,s),l={responseType:"blob",signal:o,query:{...this.refreshParameters}},{data:n}=await r(a,l);return A(n,e,t,s,o)}getTileUrl(e,r,t){const s=!this.capabilities.operations.supportsTileMap&&this.supportsBlankTile,i=l({...this.parsedUrl?.query,blankTile:!s&&null,...this.customParameters,token:this.apiKey}),o=this.tileServers;return`${o&&o.length?o[r%o.length]:this.parsedUrl?.path}/tile/${e}/${r}/${t}${i?"?"+i:""}`}loadAll(){return s(this,(e=>{e(this.allSublayers)}))}_fetchService(e){return new Promise(((s,i)=>{if(this.sourceJSON){if(null!=this.sourceJSON.bandCount&&null!=this.sourceJSON.pixelSizeX)throw new t("tile-layer:unsupported-url","use ImageryTileLayer to open a tiled image service");return void s({data:this.sourceJSON})}if(!this.parsedUrl)throw new t("tile-layer:undefined-url","layer's url is not defined");const o=R(this.parsedUrl.path);if(null!=o&&"ImageServer"===o.serverType)throw new t("tile-layer:unsupported-url","use ImageryTileLayer to open a tiled image service");r(this.parsedUrl.path,{query:{f:"json",...this.parsedUrl.query,...this.customParameters,token:this.apiKey},responseType:"json",signal:e}).then(s,i)})).then((r=>{let t=this.url;if(r.ssl&&(t=this.url=t.replace(/^http:/i,"https:")),this.sourceJSON=r.data,this.read(r.data,{origin:"service",url:this.parsedUrl}),10.1===this.version&&!U(t))return this._fetchServerVersion(t,e).then((e=>{this.read({currentVersion:e})})).catch((()=>{}))}))}_fetchServerVersion(e,s){if(!P(e))return Promise.reject();const i=e.replace(/(.*\/rest)\/.*/i,"$1")+"/info";return r(i,{query:{f:"json",...this.customParameters,token:this.apiKey},responseType:"json",signal:s}).then((e=>{if(e.data&&e.data.currentVersion)return e.data.currentVersion;throw new t("tile-layer:version-not-available")}))}_getMapName(e){return void 0}_getDefaultAttribution(e){return null;let r;e=e.toLowerCase();for(let t=0,s=I.length;t<s;t++)if(r=I[t],r.toLowerCase().includes(e))return n("//static.Grcgis.cn/attribution/"+r);return null}_getDefaultTileServers(e){if(null==e)return[];const r=-1!==e.search(/^(?:https?:)?\/\/server\.arcgisonline\.com/i),t=-1!==e.search(/^(?:https?:)?\/\/services\.arcgisonline\.com/i);return r||t?[e,e.replace(r?/server\.arcgisonline/i:/services\.arcgisonline/i,r?"services.arcgisonline":"server.arcgisonline")]:[]}get hasOverriddenFetchTile(){return!this.fetchTile[C]}};e([p({readOnly:!0})],B.prototype,"attributionDataUrl",null),e([p({type:["show","hide","hide-children"]})],B.prototype,"listMode",void 0),e([p({json:{read:!0,write:!0}})],B.prototype,"blendMode",void 0),e([p({type:Boolean,json:{read:!1,write:{enabled:!0,overridePolicy:()=>({enabled:!1})}}})],B.prototype,"isReference",void 0),e([p({readOnly:!0,type:["ArcGISTiledMapServiceLayer"]})],B.prototype,"operationalLayerType",void 0),e([p({type:Boolean})],B.prototype,"resampling",void 0),e([p()],B.prototype,"sourceJSON",void 0),e([p({type:d})],B.prototype,"spatialReference",void 0),e([u("spatialReference",["spatialReference","tileInfo"])],B.prototype,"readSpatialReference",null),e([p({type:String,json:{origins:{"web-scene":{read:!0,write:!0}},read:!1}})],B.prototype,"path",void 0),e([p({readOnly:!0})],B.prototype,"sublayers",void 0),e([h("sublayers",{layers:{type:[M]}})],B.prototype,"writeSublayers",null),e([p({json:{read:!1,write:!1}})],B.prototype,"popupEnabled",void 0),e([p()],B.prototype,"tileServers",null),e([c("tileServers")],B.prototype,"castTileServers",null),e([p({readOnly:!0,json:{read:!1}})],B.prototype,"type",void 0),e([p(x)],B.prototype,"url",void 0),B=W=e([m("geoscene.layers.TileLayer")],B);const C=Symbol("default-fetch-tile");B.prototype.fetchTile[C]=!0;const N=B;export{N as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright GeoScene, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.geoscene.cn/4.29/geoscene/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../chunks/tslib.es6.js";import t from"../request.js";import{createTask as r}from"../core/asyncUtils.js";import i from"../core/Error.js";import{clone as o}from"../core/lang.js";import{MultiOriginJSONMixin as s}from"../core/MultiOriginJSONSupport.js";import{throwIfAbortError as l}from"../core/promiseUtils.js";import{urlToObject as a,addQueryParameters as n,isProtocolRelative as p,normalize as y}from"../core/urlUtils.js";import{property as u}from"../core/accessorSupport/decorators/property.js";import"../core/has.js";import"../core/Logger.js";import{reader as c}from"../core/accessorSupport/decorators/reader.js";import{subclass as m}from"../core/accessorSupport/decorators/subclass.js";import{writer as h}from"../core/accessorSupport/decorators/writer.js";import d from"../geometry/Extent.js";import S from"../geometry/SpatialReference.js";import f from"./Layer.js";import{APIKeyMixin as g}from"./mixins/APIKeyMixin.js";import{ArcGISCachedService as v}from"./mixins/ArcGISCachedService.js";import{ArcGISService as j}from"./mixins/ArcGISService.js";import{BlendLayer as _}from"./mixins/BlendLayer.js";import{CustomParametersMixin as w}from"./mixins/CustomParametersMixin.js";import{OperationalLayer as b}from"./mixins/OperationalLayer.js";import{PortalLayer as T}from"./mixins/PortalLayer.js";import{ScaleRangeLayer as U}from"./mixins/ScaleRangeLayer.js";import{checkWebPSupport as x}from"./support/imageUtils.js";import L from"./support/SpriteSource.js";import I from"./support/TileInfo.js";import{TilemapCache as R}from"./support/TilemapCache.js";import{loadMetadata as O}from"./support/vectorTileLayerLoader.js";import{createForItemRead as P}from"../portal/support/jsonContext.js";import{parseKnownArcGISOnlineDomain as M}from"../portal/support/urlUtils.js";import{e as C}from"../chunks/persistableUrlUtils.js";import{areSchemasOverlapping as V,unionTileInfos as D}from"../views/2d/engine/vectorTiles/tileInfoUtils.js";import k from"../views/2d/engine/vectorTiles/style/StyleRepository.js";import{getWebGLCapabilities as E}from"../views/webgl/capabilities.js";let N=class extends(_(U(v(j(b(T(w(g(s(f)))))))))){constructor(...e){super(...e),this._spriteSourceMap=new Map,this.currentStyleInfo=null,this.isReference=null,this.operationalLayerType="VectorTileLayer",this.style=null,this.tilemapCache=null,this.type="vector-tile",this.url=null,this.path=null}normalizeCtorArgs(e,t){return"string"==typeof e?{url:e,...t}:e}destroy(){if(this.sourceNameToSource)for(const e of Object.values(this.sourceNameToSource))e?.destroy();this.primarySource?.destroy(),this._spriteSourceMap.clear()}async prefetchResources(e){await this.loadSpriteSource(globalThis.devicePixelRatio||1,e)}load(e){const r=this.loadFromPortal({supportedTypes:["Vector Tile Service"],supportsData:!1},e).catch(l).then((async()=>{if(!this.portalItem?.id)return;const r=`${this.portalItem.itemCdnUrl}/resources/styles/root.json`;(await t(r,{...e,query:{f:"json",...this.customParameters,token:this.apiKey}})).data&&this.read({url:r},P(this.portalItem,"portal-item"))})).catch(l).then((()=>this._loadStyle(e)));return this.addResolvingPromise(r),Promise.resolve(this)}get attributionDataUrl(){const e=this.currentStyleInfo,t=e?.serviceUrl&&a(e.serviceUrl);if(!t)return null;const r=this._getDefaultAttribution(t.path);return r?n(r,{...this.customParameters,token:this.apiKey}):null}get capabilities(){const e=this.primarySource;return e?e.capabilities:{operations:{supportsExportTiles:!1,supportsTileMap:!1},exportTiles:null}}get fullExtent(){return this.primarySource?.fullExtent||null}get initialExtent(){return this.primarySource?.initialExtent||null}get parsedUrl(){return this.serviceUrl?a(this.serviceUrl):null}get serviceUrl(){return this.currentStyleInfo?.serviceUrl||null}get spatialReference(){return this.tileInfo?.spatialReference??null}get styleUrl(){return this.currentStyleInfo?.styleUrl||null}writeStyleUrl(e,t){e&&p(e)&&(e=`https:${e}`);const r=M(e);t.styleUrl=C(e,r)}get tileInfo(){const e=[];for(const r in this.sourceNameToSource)e.push(this.sourceNameToSource[r]);let t=this.primarySource?.tileInfo||new I;if(e.length>1)for(let r=0;r<e.length;r++)V(t,e[r].tileInfo)&&(t=D(t,e[r].tileInfo));return t}readTilemapCache(e,t){const r=t.capabilities?.includes("Tilemap");return r?new R({layer:this}):null}readVersion(e,t){return t.version?parseFloat(t.version):parseFloat(t.currentVersion)}async loadSpriteSource(e=1,t){if(!this._spriteSourceMap.has(e)){const r=E().maxTextureSize,i=this.currentStyleInfo?.spriteUrl?n(this.currentStyleInfo.spriteUrl,{...this.customParameters,token:this.apiKey}):null,o=new L({type:"url",spriteUrl:i,pixelRatio:e,spriteFormat:this.currentStyleInfo?.spriteFormat},r);await o.load(t),this._spriteSourceMap.set(e,o)}return this._spriteSourceMap.get(e)}async setSpriteSource(e,t){if(!e)return null;const r=E().maxTextureSize,i=e.spriteUrl,o=i?n(i,{...this.customParameters,token:this.apiKey}):null;if(!o&&"url"===e.type)return null;const s=new L(e,r);try{await s.load(t);const r=e.pixelRatio||1;return this._spriteSourceMap.clear(),this._spriteSourceMap.set(r,s),o&&this.currentStyleInfo&&(this.currentStyleInfo.spriteUrl=o),this.emit("spriteSource-change",{spriteSource:s}),s}catch(a){l(a)}return null}async loadStyle(e,t){const i=e||this.style||this.url;return this._loadingTask&&"string"==typeof i&&this.url===i||(this._loadingTask?.abort(),this._loadingTask=r((e=>(this._spriteSourceMap.clear(),this._getSourceAndStyle(i,{signal:e}))),t)),this._loadingTask.promise}getStyleLayerId(e){return this.styleRepository.getStyleLayerId(e)}getStyleLayerIndex(e){return this.styleRepository.getStyleLayerIndex(e)}getPaintProperties(e){return o(this.styleRepository?.getPaintProperties(e))}setPaintProperties(e,t){const r=this.styleRepository.isPainterDataDriven(e);this.styleRepository.setPaintProperties(e,t);const i=this.styleRepository.isPainterDataDriven(e);this.emit("paint-change",{layer:e,paint:t,isDataDriven:r||i})}getStyleLayer(e){return o(this.styleRepository.getStyleLayer(e))}setStyleLayer(e,t){this.styleRepository.setStyleLayer(e,t),this.emit("style-layer-change",{layer:e,index:t})}deleteStyleLayer(e){this.styleRepository.deleteStyleLayer(e),this.emit("delete-style-layer",{layer:e})}getLayoutProperties(e){return o(this.styleRepository.getLayoutProperties(e))}setLayoutProperties(e,t){this.styleRepository.setLayoutProperties(e,t),this.emit("layout-change",{layer:e,layout:t})}setStyleLayerVisibility(e,t){this.styleRepository.setStyleLayerVisibility(e,t),this.emit("style-layer-visibility-change",{layer:e,visibility:t})}getStyleLayerVisibility(e){return this.styleRepository.getStyleLayerVisibility(e)}write(e,t){return t?.origin&&!this.styleUrl?(t.messages&&t.messages.push(new i("vectortilelayer:unsupported",`VectorTileLayer (${this.title}, ${this.id}) with style defined by JSON only are not supported`,{layer:this})),null):super.write(e,t)}getTileUrl(e,t,r){return null}async _getSourceAndStyle(e,t){if(!e)throw new Error("invalid style!");const r=await O(e,{...t,query:{...this.customParameters,token:this.apiKey}});if("webp"===r.spriteFormat){await x("lossy")||(r.spriteFormat="png")}this._set("currentStyleInfo",{...r}),"string"==typeof e?(this.url=e,this.style=null):(this.url=null,this.style=e),this._set("sourceNameToSource",r.sourceNameToSource),this._set("primarySource",r.sourceNameToSource[r.primarySourceName]),this._set("styleRepository",new k(r.style)),this.read(r.layerDefinition,{origin:"service"}),this.emit("load-style")}_getDefaultAttribution(e){const t=e.match(/^https?:\/\/(?:basemaps|basemapsbeta|basemapsdev)(?:-api)?\.arcgis\.com(\/[^\/]+)?\/arcgis\/rest\/services\/([^\/]+(\/[^\/]+)*)\/vectortileserver/i),r=["OpenStreetMap_v2","OpenStreetMap_Daylight_v2","OpenStreetMap_Export_v2","OpenStreetMap_FTS_v2","OpenStreetMap_GCS_v2","World_Basemap","World_Basemap_v2","World_Basemap_Export_v2","World_Basemap_GCS_v2","World_Basemap_WGS84","World_Contours_v2"];if(!t)return;const i=t[2]&&t[2].toLowerCase();if(!i)return;const o=t[1]||"";for(const s of r)if(s.toLowerCase().includes(i))return y(`//static.arcgis.com/attribution/Vector${o}/${s}`)}async _loadStyle(e){return this._loadingTask?.promise??this.loadStyle(null,e)}};e([u({readOnly:!0})],N.prototype,"attributionDataUrl",null),e([u({type:["show","hide"]})],N.prototype,"listMode",void 0),e([u({json:{read:!0,write:!0}})],N.prototype,"blendMode",void 0),e([u({readOnly:!0,json:{read:!1}})],N.prototype,"capabilities",null),e([u({readOnly:!0})],N.prototype,"currentStyleInfo",void 0),e([u({json:{read:!1},readOnly:!0,type:d})],N.prototype,"fullExtent",null),e([u({json:{read:!1},readOnly:!0,type:d})],N.prototype,"initialExtent",null),e([u({type:Boolean,json:{read:!1,write:{enabled:!0,overridePolicy:()=>({enabled:!1})}}})],N.prototype,"isReference",void 0),e([u({type:["VectorTileLayer"]})],N.prototype,"operationalLayerType",void 0),e([u({readOnly:!0})],N.prototype,"parsedUrl",null),e([u()],N.prototype,"style",void 0),e([u({readOnly:!0})],N.prototype,"serviceUrl",null),e([u({type:S,readOnly:!0})],N.prototype,"spatialReference",null),e([u({readOnly:!0})],N.prototype,"styleRepository",void 0),e([u({readOnly:!0})],N.prototype,"sourceNameToSource",void 0),e([u({readOnly:!0})],N.prototype,"primarySource",void 0),e([u({type:String,readOnly:!0,json:{write:{ignoreOrigin:!0},origins:{"web-document":{write:{ignoreOrigin:!0,isRequired:!0}}}}})],N.prototype,"styleUrl",null),e([h(["portal-item","web-document"],"styleUrl")],N.prototype,"writeStyleUrl",null),e([u({json:{read:!1,origins:{service:{read:!1}}},readOnly:!0,type:I})],N.prototype,"tileInfo",null),e([u()],N.prototype,"tilemapCache",void 0),e([c("service","tilemapCache",["capabilities","tileInfo"])],N.prototype,"readTilemapCache",null),e([u({json:{read:!1},readOnly:!0,value:"vector-tile"})],N.prototype,"type",void 0),e([u({json:{origins:{"web-document":{read:{source:"styleUrl"}},"portal-item":{read:{source:"url"}}},write:!1,read:!1}})],N.prototype,"url",void 0),e([u({readOnly:!0})],N.prototype,"version",void 0),e([c("version",["version","currentVersion"])],N.prototype,"readVersion",null),e([u({type:String,json:{origins:{"web-scene":{read:!0,write:!0}},read:!1}})],N.prototype,"path",void 0),N=e([m("geoscene.layers.VectorTileLayer")],N);const A=N;export{A as default};
5
+ import{_ as e}from"../chunks/tslib.es6.js";import t from"../request.js";import{createTask as r}from"../core/asyncUtils.js";import i from"../core/Error.js";import{clone as o}from"../core/lang.js";import{MultiOriginJSONMixin as s}from"../core/MultiOriginJSONSupport.js";import{throwIfAbortError as l}from"../core/promiseUtils.js";import{urlToObject as a,addQueryParameters as n,isProtocolRelative as p,normalize as y}from"../core/urlUtils.js";import{property as u}from"../core/accessorSupport/decorators/property.js";import"../core/has.js";import"../core/Logger.js";import{reader as c}from"../core/accessorSupport/decorators/reader.js";import{subclass as m}from"../core/accessorSupport/decorators/subclass.js";import{writer as h}from"../core/accessorSupport/decorators/writer.js";import d from"../geometry/Extent.js";import S from"../geometry/SpatialReference.js";import f from"./Layer.js";import{APIKeyMixin as g}from"./mixins/APIKeyMixin.js";import{ArcGISCachedService as v}from"./mixins/ArcGISCachedService.js";import{ArcGISService as j}from"./mixins/ArcGISService.js";import{BlendLayer as _}from"./mixins/BlendLayer.js";import{CustomParametersMixin as w}from"./mixins/CustomParametersMixin.js";import{OperationalLayer as b}from"./mixins/OperationalLayer.js";import{PortalLayer as T}from"./mixins/PortalLayer.js";import{ScaleRangeLayer as U}from"./mixins/ScaleRangeLayer.js";import{checkWebPSupport as x}from"./support/imageUtils.js";import L from"./support/SpriteSource.js";import I from"./support/TileInfo.js";import{TilemapCache as R}from"./support/TilemapCache.js";import{loadMetadata as O}from"./support/vectorTileLayerLoader.js";import{createForItemRead as P}from"../portal/support/jsonContext.js";import{parseKnownOnlineDomain as M}from"../portal/support/urlUtils.js";import{e as C}from"../chunks/persistableUrlUtils.js";import{areSchemasOverlapping as V,unionTileInfos as D}from"../views/2d/engine/vectorTiles/tileInfoUtils.js";import k from"../views/2d/engine/vectorTiles/style/StyleRepository.js";import{getWebGLCapabilities as E}from"../views/webgl/capabilities.js";let N=class extends(_(U(v(j(b(T(w(g(s(f)))))))))){constructor(...e){super(...e),this._spriteSourceMap=new Map,this.currentStyleInfo=null,this.isReference=null,this.operationalLayerType="VectorTileLayer",this.style=null,this.tilemapCache=null,this.type="vector-tile",this.url=null,this.path=null}normalizeCtorArgs(e,t){return"string"==typeof e?{url:e,...t}:e}destroy(){if(this.sourceNameToSource)for(const e of Object.values(this.sourceNameToSource))e?.destroy();this.primarySource?.destroy(),this._spriteSourceMap.clear()}async prefetchResources(e){await this.loadSpriteSource(globalThis.devicePixelRatio||1,e)}load(e){const r=this.loadFromPortal({supportedTypes:["Vector Tile Service"],supportsData:!1},e).catch(l).then((async()=>{if(!this.portalItem?.id)return;const r=`${this.portalItem.itemCdnUrl}/resources/styles/root.json`;(await t(r,{...e,query:{f:"json",...this.customParameters,token:this.apiKey}})).data&&this.read({url:r},P(this.portalItem,"portal-item"))})).catch(l).then((()=>this._loadStyle(e)));return this.addResolvingPromise(r),Promise.resolve(this)}get attributionDataUrl(){const e=this.currentStyleInfo,t=e?.serviceUrl&&a(e.serviceUrl);if(!t)return null;const r=this._getDefaultAttribution(t.path);return r?n(r,{...this.customParameters,token:this.apiKey}):null}get capabilities(){const e=this.primarySource;return e?e.capabilities:{operations:{supportsExportTiles:!1,supportsTileMap:!1},exportTiles:null}}get fullExtent(){return this.primarySource?.fullExtent||null}get initialExtent(){return this.primarySource?.initialExtent||null}get parsedUrl(){return this.serviceUrl?a(this.serviceUrl):null}get serviceUrl(){return this.currentStyleInfo?.serviceUrl||null}get spatialReference(){return this.tileInfo?.spatialReference??null}get styleUrl(){return this.currentStyleInfo?.styleUrl||null}writeStyleUrl(e,t){e&&p(e)&&(e=`https:${e}`);const r=M(e);t.styleUrl=C(e,r)}get tileInfo(){const e=[];for(const r in this.sourceNameToSource)e.push(this.sourceNameToSource[r]);let t=this.primarySource?.tileInfo||new I;if(e.length>1)for(let r=0;r<e.length;r++)V(t,e[r].tileInfo)&&(t=D(t,e[r].tileInfo));return t}readTilemapCache(e,t){const r=t.capabilities?.includes("Tilemap");return r?new R({layer:this}):null}readVersion(e,t){return t.version?parseFloat(t.version):parseFloat(t.currentVersion)}async loadSpriteSource(e=1,t){if(!this._spriteSourceMap.has(e)){const r=E().maxTextureSize,i=this.currentStyleInfo?.spriteUrl?n(this.currentStyleInfo.spriteUrl,{...this.customParameters,token:this.apiKey}):null,o=new L({type:"url",spriteUrl:i,pixelRatio:e,spriteFormat:this.currentStyleInfo?.spriteFormat},r);await o.load(t),this._spriteSourceMap.set(e,o)}return this._spriteSourceMap.get(e)}async setSpriteSource(e,t){if(!e)return null;const r=E().maxTextureSize,i=e.spriteUrl,o=i?n(i,{...this.customParameters,token:this.apiKey}):null;if(!o&&"url"===e.type)return null;const s=new L(e,r);try{await s.load(t);const r=e.pixelRatio||1;return this._spriteSourceMap.clear(),this._spriteSourceMap.set(r,s),o&&this.currentStyleInfo&&(this.currentStyleInfo.spriteUrl=o),this.emit("spriteSource-change",{spriteSource:s}),s}catch(a){l(a)}return null}async loadStyle(e,t){const i=e||this.style||this.url;return this._loadingTask&&"string"==typeof i&&this.url===i||(this._loadingTask?.abort(),this._loadingTask=r((e=>(this._spriteSourceMap.clear(),this._getSourceAndStyle(i,{signal:e}))),t)),this._loadingTask.promise}getStyleLayerId(e){return this.styleRepository.getStyleLayerId(e)}getStyleLayerIndex(e){return this.styleRepository.getStyleLayerIndex(e)}getPaintProperties(e){return o(this.styleRepository?.getPaintProperties(e))}setPaintProperties(e,t){const r=this.styleRepository.isPainterDataDriven(e);this.styleRepository.setPaintProperties(e,t);const i=this.styleRepository.isPainterDataDriven(e);this.emit("paint-change",{layer:e,paint:t,isDataDriven:r||i})}getStyleLayer(e){return o(this.styleRepository.getStyleLayer(e))}setStyleLayer(e,t){this.styleRepository.setStyleLayer(e,t),this.emit("style-layer-change",{layer:e,index:t})}deleteStyleLayer(e){this.styleRepository.deleteStyleLayer(e),this.emit("delete-style-layer",{layer:e})}getLayoutProperties(e){return o(this.styleRepository.getLayoutProperties(e))}setLayoutProperties(e,t){this.styleRepository.setLayoutProperties(e,t),this.emit("layout-change",{layer:e,layout:t})}setStyleLayerVisibility(e,t){this.styleRepository.setStyleLayerVisibility(e,t),this.emit("style-layer-visibility-change",{layer:e,visibility:t})}getStyleLayerVisibility(e){return this.styleRepository.getStyleLayerVisibility(e)}write(e,t){return t?.origin&&!this.styleUrl?(t.messages&&t.messages.push(new i("vectortilelayer:unsupported",`VectorTileLayer (${this.title}, ${this.id}) with style defined by JSON only are not supported`,{layer:this})),null):super.write(e,t)}getTileUrl(e,t,r){return null}async _getSourceAndStyle(e,t){if(!e)throw new Error("invalid style!");const r=await O(e,{...t,query:{...this.customParameters,token:this.apiKey}});if("webp"===r.spriteFormat){await x("lossy")||(r.spriteFormat="png")}this._set("currentStyleInfo",{...r}),"string"==typeof e?(this.url=e,this.style=null):(this.url=null,this.style=e),this._set("sourceNameToSource",r.sourceNameToSource),this._set("primarySource",r.sourceNameToSource[r.primarySourceName]),this._set("styleRepository",new k(r.style)),this.read(r.layerDefinition,{origin:"service"}),this.emit("load-style")}_getDefaultAttribution(e){const t=e.match(/^https?:\/\/(?:basemaps|basemapsbeta|basemapsdev)(?:-api)?\.geoscene\.cn(\/[^\/]+)?\/arcgis\/rest\/services\/([^\/]+(\/[^\/]+)*)\/vectortileserver/i),r=["OpenStreetMap_v2","OpenStreetMap_Daylight_v2","OpenStreetMap_Export_v2","OpenStreetMap_FTS_v2","OpenStreetMap_GCS_v2","World_Basemap","World_Basemap_v2","World_Basemap_Export_v2","World_Basemap_GCS_v2","World_Basemap_WGS84","World_Contours_v2"];if(!t)return;const i=t[2]&&t[2].toLowerCase();if(!i)return;const o=t[1]||"";for(const s of r)if(s.toLowerCase().includes(i))return y(`//static.Grcgis.cn/attribution/Vector${o}/${s}`)}async _loadStyle(e){return this._loadingTask?.promise??this.loadStyle(null,e)}};e([u({readOnly:!0})],N.prototype,"attributionDataUrl",null),e([u({type:["show","hide"]})],N.prototype,"listMode",void 0),e([u({json:{read:!0,write:!0}})],N.prototype,"blendMode",void 0),e([u({readOnly:!0,json:{read:!1}})],N.prototype,"capabilities",null),e([u({readOnly:!0})],N.prototype,"currentStyleInfo",void 0),e([u({json:{read:!1},readOnly:!0,type:d})],N.prototype,"fullExtent",null),e([u({json:{read:!1},readOnly:!0,type:d})],N.prototype,"initialExtent",null),e([u({type:Boolean,json:{read:!1,write:{enabled:!0,overridePolicy:()=>({enabled:!1})}}})],N.prototype,"isReference",void 0),e([u({type:["VectorTileLayer"]})],N.prototype,"operationalLayerType",void 0),e([u({readOnly:!0})],N.prototype,"parsedUrl",null),e([u()],N.prototype,"style",void 0),e([u({readOnly:!0})],N.prototype,"serviceUrl",null),e([u({type:S,readOnly:!0})],N.prototype,"spatialReference",null),e([u({readOnly:!0})],N.prototype,"styleRepository",void 0),e([u({readOnly:!0})],N.prototype,"sourceNameToSource",void 0),e([u({readOnly:!0})],N.prototype,"primarySource",void 0),e([u({type:String,readOnly:!0,json:{write:{ignoreOrigin:!0},origins:{"web-document":{write:{ignoreOrigin:!0,isRequired:!0}}}}})],N.prototype,"styleUrl",null),e([h(["portal-item","web-document"],"styleUrl")],N.prototype,"writeStyleUrl",null),e([u({json:{read:!1,origins:{service:{read:!1}}},readOnly:!0,type:I})],N.prototype,"tileInfo",null),e([u()],N.prototype,"tilemapCache",void 0),e([c("service","tilemapCache",["capabilities","tileInfo"])],N.prototype,"readTilemapCache",null),e([u({json:{read:!1},readOnly:!0,value:"vector-tile"})],N.prototype,"type",void 0),e([u({json:{origins:{"web-document":{read:{source:"styleUrl"}},"portal-item":{read:{source:"url"}}},write:!1,read:!1}})],N.prototype,"url",void 0),e([u({readOnly:!0})],N.prototype,"version",void 0),e([c("version",["version","currentVersion"])],N.prototype,"readVersion",null),e([u({type:String,json:{origins:{"web-scene":{read:!0,write:!0}},read:!1}})],N.prototype,"path",void 0),N=e([m("geoscene.layers.VectorTileLayer")],N);const A=N;export{A as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright GeoScene, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.geoscene.cn/4.29/geoscene/copyright.txt for details.
4
4
  */
5
- import{urlToObject as e,removeTrailingSlash as r,removeQueryParameters as t,join as s,Url as n,makeAbsolute as l}from"../../core/urlUtils.js";import{w as u}from"../../chunks/persistableUrlUtils.js";const i={mapserver:"MapServer",imageserver:"ImageServer",featureserver:"FeatureServer",sceneserver:"SceneServer",streamserver:"StreamServer",vectortileserver:"VectorTileServer","3dtilesserver":"3DTilesServer"},o=Object.values(i),c=new RegExp(`^((?:https?:)?\\/\\/\\S+?\\/rest\\/services\\/(.+?)\\/(${o.join("|")}))(?:\\/(?:layers\\/)?(\\d+))?`,"i"),a=new RegExp(`^((?:https?:)?\\/\\/\\S+?\\/([^\\/\\n]+)\\/(${o.join("|")}))(?:\\/(?:layers\\/)?(\\d+))?`,"i"),f=/(.*?)\/(?:layers\/)?(\d+)\/?$/i;function v(e){return!!c.test(e)}function p(r){if(null==r)return null;const t=e(r),s=t?.path.match(c)||t?.path.match(a);if(!s)return null;const[,n,l,u,o]=s,f=l.indexOf("/");return{title:m(-1!==f?l.slice(f+1):l),serverType:i[u.toLowerCase()],sublayer:null!=o&&""!==o?parseInt(o,10):null,url:{path:n}}}function d(r){const t=e(r).path.match(f);return t?{serviceUrl:t[1],sublayerId:Number(t[2])}:null}function m(e){return(e=e.replaceAll(/\s*[/_]+\s*/g," "))[0].toUpperCase()+e.slice(1)}function h(e,r){const t=[];if(e){const r=p(e);null!=r&&r.title&&t.push(r.title)}if(r){const e=m(r);t.push(e)}if(2===t.length){if(t[0].toLowerCase().includes(t[1].toLowerCase()))return t[0];if(t[1].toLowerCase().includes(t[0].toLowerCase()))return t[1]}return t.join(" - ")}function w(e){if(!e)return!1;const r=".arcgis.com/",t="//services",s="//tiles",n="//features",l=(e=e.toLowerCase()).includes(r),u=e.includes(t)||e.includes(s)||e.includes(n);return l&&u}function y(e,s){return e?r(t(e,s)):e}function g(s){let{url:n}=s;if(!n)return{url:n};n=t(n,s.logger);const l=e(n),u=p(l.path);let i;if(null!=u)null!=u.sublayer&&null==s.layer.layerId&&(i=u.sublayer),n=u.url.path;else if(s.nonStandardUrlAllowed){const e=d(l.path);null!=e&&(n=e.serviceUrl,i=e.sublayerId)}return{url:r(n),layerId:i}}function S(e,r,t,n,l){u(r,n,"url",l),n.url&&null!=e.layerId&&(n.url=s(n.url,t,e.layerId.toString()))}function C(e){if(!e)return!1;const r=e.toLowerCase(),t=r.includes("/services/"),s=r.includes("/mapserver/wmsserver"),n=r.includes("/imageserver/wmsserver"),l=r.includes("/wmsserver");return t&&(s||n||l)}function b(e){if(!e)return!1;const r=new n(l(e)),t=r.authority?.toLowerCase();return"server.arcgisonline.com"===t||"services.arcgisonline.com"===t}export{m as cleanTitle,v as isArcGISUrl,w as isHostedAgolService,b as isServerOrServicesAGOLUrl,C as isWmsServer,p as parse,d as parseNonStandardSublayerUrl,y as sanitizeUrl,g as sanitizeUrlWithLayerId,o as serverTypes,h as titleFromUrlAndName,S as writeUrlWithLayerId};
5
+ import{urlToObject as e,removeTrailingSlash as r,removeQueryParameters as t,join as s,Url as n,makeAbsolute as l}from"../../core/urlUtils.js";import{w as u}from"../../chunks/persistableUrlUtils.js";const i={mapserver:"MapServer",imageserver:"ImageServer",featureserver:"FeatureServer",sceneserver:"SceneServer",streamserver:"StreamServer",vectortileserver:"VectorTileServer","3dtilesserver":"3DTilesServer"},o=Object.values(i),c=new RegExp(`^((?:https?:)?\\/\\/\\S+?\\/rest\\/services\\/(.+?)\\/(${o.join("|")}))(?:\\/(?:layers\\/)?(\\d+))?`,"i"),a=new RegExp(`^((?:https?:)?\\/\\/\\S+?\\/([^\\/\\n]+)\\/(${o.join("|")}))(?:\\/(?:layers\\/)?(\\d+))?`,"i"),f=/(.*?)\/(?:layers\/)?(\d+)\/?$/i;function v(e){return!!c.test(e)}function p(r){if(null==r)return null;const t=e(r),s=t?.path.match(c)||t?.path.match(a);if(!s)return null;const[,n,l,u,o]=s,f=l.indexOf("/");return{title:m(-1!==f?l.slice(f+1):l),serverType:i[u.toLowerCase()],sublayer:null!=o&&""!==o?parseInt(o,10):null,url:{path:n}}}function d(r){const t=e(r).path.match(f);return t?{serviceUrl:t[1],sublayerId:Number(t[2])}:null}function m(e){return(e=e.replaceAll(/\s*[/_]+\s*/g," "))[0].toUpperCase()+e.slice(1)}function h(e,r){const t=[];if(e){const r=p(e);null!=r&&r.title&&t.push(r.title)}if(r){const e=m(r);t.push(e)}if(2===t.length){if(t[0].toLowerCase().includes(t[1].toLowerCase()))return t[0];if(t[1].toLowerCase().includes(t[0].toLowerCase()))return t[1]}return t.join(" - ")}function w(e){if(!e)return!1;const r=".Grcgis.cn/",t="//services",s="//tiles",n="//features",l=(e=e.toLowerCase()).includes(r),u=e.includes(t)||e.includes(s)||e.includes(n);return l&&u}function y(e,s){return e?r(t(e,s)):e}function g(s){let{url:n}=s;if(!n)return{url:n};n=t(n,s.logger);const l=e(n),u=p(l.path);let i;if(null!=u)null!=u.sublayer&&null==s.layer.layerId&&(i=u.sublayer),n=u.url.path;else if(s.nonStandardUrlAllowed){const e=d(l.path);null!=e&&(n=e.serviceUrl,i=e.sublayerId)}return{url:r(n),layerId:i}}function S(e,r,t,n,l){u(r,n,"url",l),n.url&&null!=e.layerId&&(n.url=s(n.url,t,e.layerId.toString()))}function C(e){if(!e)return!1;const r=e.toLowerCase(),t=r.includes("/services/"),s=r.includes("/mapserver/wmsserver"),n=r.includes("/imageserver/wmsserver"),l=r.includes("/wmsserver");return t&&(s||n||l)}function b(e){if(!e)return!1;const r=new n(l(e)),t=r.authority?.toLowerCase();return"server.Grcgisonline.cn"===t||"services.Grcgisonline.cn"===t}export{m as cleanTitle,v as isArcGISUrl,w as isHostedAgolService,b as isServerOrServicesAGOLUrl,C as isWmsServer,p as parse,d as parseNonStandardSublayerUrl,y as sanitizeUrl,g as sanitizeUrlWithLayerId,o as serverTypes,h as titleFromUrlAndName,S as writeUrlWithLayerId};
@@ -2,4 +2,4 @@
2
2
  All material copyright GeoScene, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.geoscene.cn/4.29/geoscene/copyright.txt for details.
4
4
  */
5
- import e from"../../core/Error.js";import{getFilename as r,urlToObject as a}from"../../core/urlUtils.js";import{parse as t,parseNonStandardSublayerUrl as s}from"./arcgisLayerUrl.js";import{findAssociatedFeatureService as n}from"./associatedFeatureServiceUtils.js";import{fetchFeatureService as l}from"./fetchService.js";import{sceneServiceLayerTypeToClassName as o}from"./layerUtils.js";import{layerLookupMap as i}from"./lazyLayerLoader.js";import{fetchArcGISServiceJSON as u}from"../../support/requestPresets.js";const c={FeatureLayer:!0,SceneLayer:!0};async function y(e){const r=e.properties?.customParameters,a=await p(e.url,r),t={...e.properties,url:e.url};if(a.layers.length+a.tables.length===0)return null!=a.layerId&&(t.layerId=a.layerId),null!=a.sourceJSON&&(t.sourceJSON=a.sourceJSON),new a.Constructor(t);const s=new(0,(await import("../GroupLayer.js")).default)({title:a.parsedUrl.title});return await m(s,a,t),s}function f(e,r){return e?e.find((e=>e.id===r)):null}async function m(e,r,a){function t(e,r,t,s){const n={...a,layerId:r,sublayerTitleMode:"service-name"};return null!=e&&(n.url=e),null!=t&&(n.sourceJSON=t),s(n)}const s=r.sublayerConstructorProvider;for(const{id:n,serverUrl:l}of r.layers){const a=f(r.sublayerInfos,n),o=(a&&s?.(a))??r.Constructor,i=t(l,n,a,(e=>new o(e)));e.add(i)}if(r.tables.length){const a=await h("FeatureLayer");r.tables.forEach((({id:s,serverUrl:n})=>{const l=t(n,s,f(r.tableInfos,s),(e=>new a(e)));e.tables.add(l)}))}}async function p(r,a){let s=t(r);if(null==s&&(s=await d(r,a)),null==s)throw new e("arcgis-layers:url-mismatch","The url '${url}' is not a valid arcgis resource",{url:r});const{serverType:n,sublayer:l}=s;let i;const y={FeatureServer:"FeatureLayer",StreamServer:"StreamLayer",VectorTileServer:"VectorTileLayer"},f="FeatureServer"===n,m="SceneServer"===n,p={parsedUrl:s,Constructor:null,layerId:f||m?l??void 0:void 0,layers:[],tables:[]};switch(n){case"MapServer":if(null!=l)i="FeatureLayer";else{i=await b(r,a)?"TileLayer":"MapImageLayer"}break;case"ImageServer":{const e=await u(r,{customParameters:a}),{tileInfo:t,cacheType:s}=e;i=t?"LERC"!==t?.format?.toUpperCase()||s&&"elevation"!==s.toLowerCase()?"ImageryTileLayer":"ElevationLayer":"ImageryLayer";break}case"SceneServer":{const e=await u(s.url.path,{customParameters:a});if(i="SceneLayer",e){const r=e?.layers;if("Voxel"===e?.layerType)i="VoxelLayer";else if(r?.length){const e=r[0]?.layerType;null!=e&&null!=o[e]&&(i=o[e])}}break}case"3DTilesServer":throw new e("arcgis-layers:unsupported","fromUrl() not supported for 3DTiles layers");case"FeatureServer":if(i="FeatureLayer",null!=l){const e=await u(r,{customParameters:a});p.sourceJSON=e,"Oriented Imagery Layer"===e.type&&(i="OrientedImageryLayer")}break;default:i=y[n]}if(c[i]&&null==l){const e=await S(r,n,a);f&&(p.sublayerInfos=e.layerInfos,p.tableInfos=e.tableInfos);if(1!==e.layers.length+e.tables.length)p.layers=e.layers,p.tables=e.tables,f&&e.layerInfos?.length&&(p.sublayerConstructorProvider=await I(e.layerInfos));else if(f||m){const r=e.layerInfos?.[0]??e.tableInfos?.[0];p.layerId=e.layers[0]?.id??e.tables[0]?.id,p.sourceJSON=r,f&&"Oriented Imagery Layer"===r?.type&&(i="OrientedImageryLayer")}}return p.Constructor=await h(i),p}async function d(e,t){const n=await u(e,{customParameters:t});let l=null,o=null;const i=n.type;if("Feature Layer"===i||"Table"===i?(l="FeatureServer",o=n.id??null):"indexedVector"===i?l="VectorTileServer":n.hasOwnProperty("mapName")?l="MapServer":n.hasOwnProperty("bandCount")&&n.hasOwnProperty("pixelSizeX")?l="ImageServer":n.hasOwnProperty("maxRecordCount")&&n.hasOwnProperty("allowGeometryUpdates")?l="FeatureServer":n.hasOwnProperty("streamUrls")?l="StreamServer":v(n)?(l="SceneServer",o=n.id):n.hasOwnProperty("layers")&&v(n.layers?.[0])&&(l="SceneServer"),!l)return null;const c=null!=o?s(e):null;return{title:null!=c&&n.name||r(e),serverType:l,sublayer:o,url:{path:null!=c?c.serviceUrl:a(e).path}}}function v(e){return null!=e&&e.hasOwnProperty("store")&&e.hasOwnProperty("id")&&"number"==typeof e.id}async function S(e,r,a){let t,s,n=!1;switch(r){case"FeatureServer":{const r=await l(e,{customParameters:a});n=!!r.layersJSON,t=r.layersJSON||r.serviceJSON;break}case"SceneServer":{const r=await w(e,a);t=r.serviceInfo,s=r.tableServerUrl;break}default:t=await u(e,{customParameters:a})}const o=t?.layers,i=t?.tables;return{layers:o?.map((e=>({id:e.id}))).reverse()||[],tables:i?.map((e=>({serverUrl:s,id:e.id}))).reverse()||[],layerInfos:n?o:[],tableInfos:n?i:[]}}async function w(e,r){const a=await u(e,{customParameters:r}),t=a.layers?.[0];if(!t)return{serviceInfo:a};try{const{serverUrl:t}=await n(e),s=await u(t,{customParameters:r}).catch((()=>null));return s&&(a.tables=s.tables),{serviceInfo:a,tableServerUrl:t}}catch{return{serviceInfo:a}}}async function h(e){return(0,i[e])()}async function b(e,r){return(await u(e,{customParameters:r})).tileInfo}async function I(e){const r=[],a=[];if(e.forEach((e=>{const{type:t}=e;"Oriented Imagery Layer"===t?(r.push(t),a.push(h("OrientedImageryLayer"))):(r.push(t),a.push(h("FeatureLayer")))})),!a.length)return;const t=await Promise.all(a),s=new Map;return r.forEach(((e,r)=>{s.set(e,t[r])})),e=>s.get(e.type)}export{y as fromUrl};
5
+ import e from"../../core/Error.js";import{getFilename as r,urlToObject as a}from"../../core/urlUtils.js";import{parse as t,parseNonStandardSublayerUrl as s}from"./arcgisLayerUrl.js";import{findAssociatedFeatureService as n}from"./associatedFeatureServiceUtils.js";import{fetchFeatureService as l}from"./fetchService.js";import{sceneServiceLayerTypeToClassName as o}from"./layerUtils.js";import{layerLookupMap as i}from"./lazyLayerLoader.js";import{fetchArcGISServiceJSON as u}from"../../support/requestPresets.js";const c={FeatureLayer:!0,SceneLayer:!0};async function y(e){const r=e.properties?.customParameters,a=await p(e.url,r),t={...e.properties,url:e.url};if(a.layers.length+a.tables.length===0)return null!=a.layerId&&(t.layerId=a.layerId),null!=a.sourceJSON&&(t.sourceJSON=a.sourceJSON),new a.Constructor(t);const s=new(0,(await import("../GroupLayer.js")).default)({title:a.parsedUrl.title});return await m(s,a,t),s}function f(e,r){return e?e.find((e=>e.id===r)):null}async function m(e,r,a){function t(e,r,t,s){const n={...a,layerId:r,sublayerTitleMode:"service-name"};return null!=e&&(n.url=e),null!=t&&(n.sourceJSON=t),s(n)}const s=r.sublayerConstructorProvider;for(const{id:n,serverUrl:l}of r.layers){const a=f(r.sublayerInfos,n),o=(a&&s?.(a))??r.Constructor,i=t(l,n,a,(e=>new o(e)));e.add(i)}if(r.tables.length){const a=await h("FeatureLayer");r.tables.forEach((({id:s,serverUrl:n})=>{const l=t(n,s,f(r.tableInfos,s),(e=>new a(e)));e.tables.add(l)}))}}async function p(r,a){let s=t(r);if(null==s&&(s=await d(r,a)),null==s)throw new e("arcgis-layers:url-mismatch","The url '${url}' is not a valid GeoScene resource",{url:r});const{serverType:n,sublayer:l}=s;let i;const y={FeatureServer:"FeatureLayer",StreamServer:"StreamLayer",VectorTileServer:"VectorTileLayer"},f="FeatureServer"===n,m="SceneServer"===n,p={parsedUrl:s,Constructor:null,layerId:f||m?l??void 0:void 0,layers:[],tables:[]};switch(n){case"MapServer":if(null!=l)i="FeatureLayer";else{i=await b(r,a)?"TileLayer":"MapImageLayer"}break;case"ImageServer":{const e=await u(r,{customParameters:a}),{tileInfo:t,cacheType:s}=e;i=t?"LERC"!==t?.format?.toUpperCase()||s&&"elevation"!==s.toLowerCase()?"ImageryTileLayer":"ElevationLayer":"ImageryLayer";break}case"SceneServer":{const e=await u(s.url.path,{customParameters:a});if(i="SceneLayer",e){const r=e?.layers;if("Voxel"===e?.layerType)i="VoxelLayer";else if(r?.length){const e=r[0]?.layerType;null!=e&&null!=o[e]&&(i=o[e])}}break}case"3DTilesServer":throw new e("arcgis-layers:unsupported","fromUrl() not supported for 3DTiles layers");case"FeatureServer":if(i="FeatureLayer",null!=l){const e=await u(r,{customParameters:a});p.sourceJSON=e,"Oriented Imagery Layer"===e.type&&(i="OrientedImageryLayer")}break;default:i=y[n]}if(c[i]&&null==l){const e=await S(r,n,a);f&&(p.sublayerInfos=e.layerInfos,p.tableInfos=e.tableInfos);if(1!==e.layers.length+e.tables.length)p.layers=e.layers,p.tables=e.tables,f&&e.layerInfos?.length&&(p.sublayerConstructorProvider=await I(e.layerInfos));else if(f||m){const r=e.layerInfos?.[0]??e.tableInfos?.[0];p.layerId=e.layers[0]?.id??e.tables[0]?.id,p.sourceJSON=r,f&&"Oriented Imagery Layer"===r?.type&&(i="OrientedImageryLayer")}}return p.Constructor=await h(i),p}async function d(e,t){const n=await u(e,{customParameters:t});let l=null,o=null;const i=n.type;if("Feature Layer"===i||"Table"===i?(l="FeatureServer",o=n.id??null):"indexedVector"===i?l="VectorTileServer":n.hasOwnProperty("mapName")?l="MapServer":n.hasOwnProperty("bandCount")&&n.hasOwnProperty("pixelSizeX")?l="ImageServer":n.hasOwnProperty("maxRecordCount")&&n.hasOwnProperty("allowGeometryUpdates")?l="FeatureServer":n.hasOwnProperty("streamUrls")?l="StreamServer":v(n)?(l="SceneServer",o=n.id):n.hasOwnProperty("layers")&&v(n.layers?.[0])&&(l="SceneServer"),!l)return null;const c=null!=o?s(e):null;return{title:null!=c&&n.name||r(e),serverType:l,sublayer:o,url:{path:null!=c?c.serviceUrl:a(e).path}}}function v(e){return null!=e&&e.hasOwnProperty("store")&&e.hasOwnProperty("id")&&"number"==typeof e.id}async function S(e,r,a){let t,s,n=!1;switch(r){case"FeatureServer":{const r=await l(e,{customParameters:a});n=!!r.layersJSON,t=r.layersJSON||r.serviceJSON;break}case"SceneServer":{const r=await w(e,a);t=r.serviceInfo,s=r.tableServerUrl;break}default:t=await u(e,{customParameters:a})}const o=t?.layers,i=t?.tables;return{layers:o?.map((e=>({id:e.id}))).reverse()||[],tables:i?.map((e=>({serverUrl:s,id:e.id}))).reverse()||[],layerInfos:n?o:[],tableInfos:n?i:[]}}async function w(e,r){const a=await u(e,{customParameters:r}),t=a.layers?.[0];if(!t)return{serviceInfo:a};try{const{serverUrl:t}=await n(e),s=await u(t,{customParameters:r}).catch((()=>null));return s&&(a.tables=s.tables),{serviceInfo:a,tableServerUrl:t}}catch{return{serviceInfo:a}}}async function h(e){return(0,i[e])()}async function b(e,r){return(await u(e,{customParameters:r})).tileInfo}async function I(e){const r=[],a=[];if(e.forEach((e=>{const{type:t}=e;"Oriented Imagery Layer"===t?(r.push(t),a.push(h("OrientedImageryLayer"))):(r.push(t),a.push(h("FeatureLayer")))})),!a.length)return;const t=await Promise.all(a),s=new Map;return r.forEach(((e,r)=>{s.set(e,t[r])})),e=>s.get(e.type)}export{y as fromUrl};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geoscene/core",
3
- "version": "4.29.5",
3
+ "version": "4.29.7",
4
4
  "homepage": "https://js.geoscene.cn",
5
5
  "description": "GeoScene Maps SDK for JavaScript: A complete 2D and 3D mapping and data visualization API",
6
6
  "keywords": [