@arcgis/core 6.0.0-next.5 → 6.0.0-next.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 (215) hide show
  1. package/analysis/AreaMeasurementAnalysis.d.ts +11 -1
  2. package/analysis/DirectLineMeasurementAnalysis.d.ts +11 -1
  3. package/analysis/DistanceMeasurementAnalysis.d.ts +8 -0
  4. package/arcade/functions/knowledgegraph.js +1 -1
  5. package/arcade/geometry/unitConversion.js +1 -1
  6. package/arcgisGlobal.d.ts +5 -5
  7. package/assets/esri/core/workers/RemoteClient.js +1 -1
  8. package/assets/esri/core/workers/chunks/{f09c9d9a554c33a753b4.js → 02253bdffbd580af22d8.js} +1 -1
  9. package/assets/esri/core/workers/chunks/{1ede8666d804c553803e.js → 0b6941781e35ce0f7274.js} +1 -1
  10. package/assets/esri/core/workers/chunks/0ccab50877b24f862d6e.js +1 -0
  11. package/assets/esri/core/workers/chunks/{a0d459bdb91ee892d4b6.js → 116293b1ee788a89ce1e.js} +1 -1
  12. package/assets/esri/core/workers/chunks/{8959a825f5e1ce6f38ac.js → 1c65ab9ed611c322ce27.js} +1 -1
  13. package/assets/esri/core/workers/chunks/257910cca66dc5df465e.js +1 -0
  14. package/assets/esri/core/workers/chunks/27da9ece2afaeec39f59.js +1 -0
  15. package/assets/esri/core/workers/chunks/{83589144eeeb08f45557.js → 2aeb5cc32284dd3e4d22.js} +1 -1
  16. package/assets/esri/core/workers/chunks/2c90f7a6432cd716db8b.js +1 -0
  17. package/assets/esri/core/workers/chunks/2e096537a3a5555a4a93.js +1 -0
  18. package/assets/esri/core/workers/chunks/{b612de42ee86c0d95247.js → 3d9d7d3a40b51eb7ee3d.js} +1 -1
  19. package/assets/esri/core/workers/chunks/3ffda5bf0b91700dc308.js +1 -0
  20. package/assets/esri/core/workers/chunks/{1317ecdfd0cfa683a493.js → 42323093827adffe56d3.js} +1 -1
  21. package/assets/esri/core/workers/chunks/4d3f97a48046021713a6.js +1 -0
  22. package/assets/esri/core/workers/chunks/505227797bcf2a1d908d.js +1 -0
  23. package/assets/esri/core/workers/chunks/518e8883b6ed613bf451.js +1 -0
  24. package/assets/esri/core/workers/chunks/{67ac6b326bf80fc3d33d.js → 53be85d04cd2da4f391d.js} +1 -1
  25. package/assets/esri/core/workers/chunks/54778dec1598818d93cb.js +1 -0
  26. package/assets/esri/core/workers/chunks/557671c897ca5563be6c.js +1 -0
  27. package/assets/esri/core/workers/chunks/56a24061589f4a968818.js +1 -0
  28. package/assets/esri/core/workers/chunks/{3ac9dcbb0571a2580236.js → 62c8c9ad09e0166207fd.js} +1 -1
  29. package/assets/esri/core/workers/chunks/6588725275c75fae0d9c.js +1 -0
  30. package/assets/esri/core/workers/chunks/{9232f57623e1fa3ccabc.js → 67e4b5651fd7ff7d8cf0.js} +1 -1
  31. package/assets/esri/core/workers/chunks/6ebe73f69ae822053b70.js +1 -0
  32. package/assets/esri/core/workers/chunks/{e521bb9ee2030245c3ce.js → 6f358116f79021ff9687.js} +1 -1
  33. package/assets/esri/core/workers/chunks/7038ead1fa1674416ab3.js +1 -0
  34. package/assets/esri/core/workers/chunks/70cc2d79653d66e85b58.js +1 -0
  35. package/assets/esri/core/workers/chunks/{8ba32d3a0df4a206ef1c.js → 7165d6f6a5078768bebb.js} +1 -1
  36. package/assets/esri/core/workers/chunks/76196c414e48834f7b92.js +1 -0
  37. package/assets/esri/core/workers/chunks/{cbe6c0f32608cb504695.js → 776ae25a34352d3468bc.js} +1 -1
  38. package/assets/esri/core/workers/chunks/801e9e66edb4961461eb.js +1 -0
  39. package/assets/esri/core/workers/chunks/{5078b66ba31b770b689f.js → 85908e6e9c50749cee60.js} +1 -1
  40. package/assets/esri/core/workers/chunks/943a0f140813ee4ab04a.js +1 -0
  41. package/assets/esri/core/workers/chunks/9ce91a909eccc4dfe388.js +1 -0
  42. package/assets/esri/core/workers/chunks/aba42885c5d6b2b5fe7f.js +1 -0
  43. package/assets/esri/core/workers/chunks/ad76f7ab2f3e6d5a5b3c.js +1 -0
  44. package/assets/esri/core/workers/chunks/ae40eac1eadd1a537bf4.js +1 -0
  45. package/assets/esri/core/workers/chunks/bbf993dba74850bbf9d7.js +1 -0
  46. package/assets/esri/core/workers/chunks/bfd85e8d54062a590f0e.js +1 -0
  47. package/assets/esri/core/workers/chunks/{ff3a53c3f00335552317.js → c29c474c4b1049352d3e.js} +1 -1
  48. package/assets/esri/core/workers/chunks/d21257d2e2a37266c0f7.js +1 -0
  49. package/assets/esri/core/workers/chunks/d90a3bfd45b5ed4092e0.js +1 -0
  50. package/assets/esri/core/workers/chunks/ddf0671976648f621269.js +1 -0
  51. package/assets/esri/core/workers/chunks/ecaac39dde7ec4213264.js +1 -0
  52. package/assets/esri/core/workers/chunks/f43a50d4bd9636e68ae5.js +1118 -0
  53. package/assets/esri/core/workers/chunks/fb444954be74c1962ced.js +1 -0
  54. package/assets/esri/core/workers/chunks/{fccbb902fe08448f91de.js → fd0a5c243f3426f2a0b5.js} +1 -1
  55. package/assets/esri/core/workers/chunks/fecaf0bc28aeea4d15db.js +1 -0
  56. package/assets/esri/themes/base/widgets/_FeatureFormUtilityNetworkAssociationSettings.scss +1 -1
  57. package/assets/esri/themes/base/widgets/_Features.scss +1 -1
  58. package/assets/esri/themes/base/widgets/_OrientedImageryViewer.scss +5 -9
  59. package/assets/esri/themes/base/widgets/_SelectionToolbar.scss +2 -4
  60. package/assets/esri/themes/base/widgets/_Tooltip.scss +1 -1
  61. package/assets/esri/themes/dark/main.css +1 -1
  62. package/assets/esri/themes/light/main.css +1 -1
  63. package/assets/esri/themes/light/view.css +1 -1
  64. package/assets/esri/widgets/BatchAttributeForm/t9n/messages.en.json +1 -1
  65. package/{basemaps/BasemapCollection.d.ts → basemapGallery/BasemapGalleryModel.d.ts} +8 -8
  66. package/{basemaps/BasemapCollection.js → basemapGallery/BasemapGalleryModel.js} +1 -1
  67. package/{basemaps → basemapGallery}/BasemapsSource.d.ts +1 -1
  68. package/{basemaps → basemapGallery}/BasemapsSource.js +1 -1
  69. package/{basemaps → basemapGallery}/LocalBasemapsSource.d.ts +2 -2
  70. package/{basemaps → basemapGallery}/LocalBasemapsSource.js +1 -1
  71. package/{basemaps → basemapGallery}/PortalBasemapsSource.d.ts +2 -2
  72. package/{basemaps → basemapGallery}/PortalBasemapsSource.js +1 -1
  73. package/{basemaps → basemapGallery}/support/BasemapItem.d.ts +2 -2
  74. package/{basemaps → basemapGallery}/support/BasemapItem.js +1 -1
  75. package/{basemaps → basemapGallery}/types.d.ts +2 -2
  76. package/chunks/GlobalIllumination.glsl.js +4 -2
  77. package/chunks/GlobalIlluminationBlur.glsl.js +3 -5
  78. package/chunks/GlobalIlluminationUpscale.glsl.js +1 -1
  79. package/config.js +1 -1
  80. package/core/colorUtils.js +1 -1
  81. package/core/has.js +1 -1
  82. package/core/units.js +1 -1
  83. package/core/workers/workerFactory.js +1 -1
  84. package/geometry/projectionUtils.js +1 -1
  85. package/geometry/support/wkt.js +2 -0
  86. package/kernel.js +1 -1
  87. package/layers/graphics/data/FeatureStore.js +1 -1
  88. package/layers/graphics/data/QueryEngineResult.js +1 -1
  89. package/layers/graphics/data/geometryUtils.js +1 -1
  90. package/layers/graphics/data/projectionSupport.js +1 -1
  91. package/layers/graphics/sources/FeatureLayerSource.js +1 -1
  92. package/layers/graphics/transferFeatures.js +1 -1
  93. package/layers/knowledgeGraph/layerUtils.js +1 -1
  94. package/layers/knowledgeGraph/nodeMovementUtils.js +1 -1
  95. package/layers/raster/datasets/TIFFRaster.js +1 -1
  96. package/package.json +2 -2
  97. package/symbols/cim/cimAnalyzer.js +1 -1
  98. package/views/2d/analysis/AreaMeasurementAnalysisView2D.d.ts +4 -4
  99. package/views/2d/analysis/DistanceMeasurementAnalysisView2D.d.ts +4 -4
  100. package/views/2d/layers/FeatureLikeLayerView2D.js +1 -1
  101. package/views/2d/layers/features/FeatureSourceEventLog.js +1 -1
  102. package/views/2d/layers/features/sources/strategies/AFeatureTileLoadStrategy.js +1 -1
  103. package/views/2d/layers/features/sources/strategies/FeatureDrillDownTileLoadStrategy.js +1 -1
  104. package/views/2d/layers/features/support/FeatureSetReader.js +1 -1
  105. package/views/2d/layers/features/support/FeatureSetReaderIndirect.js +1 -1
  106. package/views/2d/layers/features/support/FeatureSetReaderJSON.js +1 -1
  107. package/views/2d/layers/features/support/FeatureSetReaderPBF.js +1 -1
  108. package/views/2d/layers/features/support/FeatureSetReaderPBFHeader.js +1 -1
  109. package/views/3d/analysis/ViewshedAnalysisView3D.d.ts +3 -0
  110. package/views/3d/analysis/VolumeMeasurementAnalysisView3D.d.ts +2 -1
  111. package/views/3d/layers/support/FeatureMemory.js +1 -1
  112. package/views/3d/layers/support/FeatureTile.js +1 -1
  113. package/views/3d/layers/support/FeatureTileFetcher3D.js +1 -1
  114. package/views/3d/layers/support/ImageHighlightHelper3D.js +1 -1
  115. package/views/3d/layers/support/featureTileQuery3D.js +1 -1
  116. package/views/3d/support/PBFDecoder.js +1 -1
  117. package/views/3d/support/elevationUpdateUtils.js +1 -1
  118. package/views/3d/terrain/TerrainRenderer.js +1 -1
  119. package/views/3d/webgl-engine/core/shaderLibrary/shading/ReadGlobalIllumination.glsl.js +16 -11
  120. package/views/3d/webgl-engine/effects/globalIllumination/GlobalIllumination.js +1 -1
  121. package/views/3d/webgl-engine/effects/globalIllumination/GlobalIlluminationColorQuantization.glsl.js +2 -2
  122. package/views/SceneView.d.ts +4 -10
  123. package/views/View.d.ts +4 -12
  124. package/views/draw/Draw.d.ts +1 -1
  125. package/views/draw/support/InteractiveHandle.js +1 -1
  126. package/views/interactive/options/SnappingOptions.d.ts +29 -12
  127. package/views/interactive/options/TooltipOptions.d.ts +9 -1
  128. package/views/interactive/options/ValueOptions.d.ts +9 -2
  129. package/views/interactive/options/ViewOptions.d.ts +82 -6
  130. package/views/interactive/support/Units.d.ts +1 -0
  131. package/views/interactive/tooltip/components/DrawHeaderActions.js +1 -1
  132. package/views/interactive/tooltip/components/ElevationModeSelect.js +1 -1
  133. package/views/support/projectionUtils.js +1 -1
  134. package/widgets/BasemapGallery/BasemapGalleryViewModel.d.ts +2 -2
  135. package/widgets/BasemapGallery/BasemapGalleryViewModel.js +1 -1
  136. package/widgets/BasemapGallery/support/BasemapGalleryItem.d.ts +3 -3
  137. package/widgets/BasemapGallery/support/LocalBasemapsSource.d.ts +2 -2
  138. package/widgets/BasemapGallery/support/PortalBasemapsSource.d.ts +2 -2
  139. package/widgets/BasemapGallery/types.d.ts +3 -3
  140. package/widgets/BasemapLayerList.js +1 -1
  141. package/widgets/BatchAttributeForm.js +1 -1
  142. package/widgets/DirectionalPad.js +1 -1
  143. package/widgets/Editor/EditorViewModel.d.ts +13 -8
  144. package/widgets/Editor/components/UpdateFeaturePanelContent.js +1 -1
  145. package/widgets/Editor.d.ts +9 -9
  146. package/widgets/Expand.js +1 -1
  147. package/widgets/FeatureForm.js +1 -1
  148. package/widgets/FeatureTable/FieldColumn.js +1 -1
  149. package/widgets/FeatureTable.js +1 -1
  150. package/widgets/Features/FeaturesDrillIn.js +1 -1
  151. package/widgets/Features.js +1 -1
  152. package/widgets/OrientedImageryViewer/OrientedImageryViewerViewModel.js +1 -1
  153. package/widgets/OrientedImageryViewer/adapters/view/SceneViewAdapter.js +1 -1
  154. package/widgets/OrientedImageryViewer/components/SequentialNavigationUI.js +1 -1
  155. package/widgets/OrientedImageryViewer/components/SketchTools.js +1 -1
  156. package/widgets/PanoramicVideoViewer.js +1 -1
  157. package/widgets/Print.js +1 -1
  158. package/widgets/ScaleRangeSlider.js +1 -1
  159. package/widgets/Search/SearchResultRenderer.js +1 -1
  160. package/widgets/Sketch/SketchViewModel.d.ts +14 -9
  161. package/widgets/Sketch/support/ResponsiveToolbar/ResponsiveToolbar.js +1 -1
  162. package/widgets/Sketch.d.ts +10 -10
  163. package/widgets/Track/TrackViewModel.d.ts +1 -1
  164. package/widgets/UtilityNetworkAssociations.js +1 -1
  165. package/widgets/UtilityNetworkTrace/UtilityNetworkTraceFeature.js +1 -1
  166. package/widgets/UtilityNetworkTrace/UtilityNetworkTraceFeaturesDrillIn.js +1 -1
  167. package/widgets/UtilityNetworkTrace/types.d.ts +2 -2
  168. package/widgets/UtilityNetworkTrace.js +1 -1
  169. package/widgets/UtilityNetworkValidateTopology.js +1 -1
  170. package/widgets/ValuePicker.js +1 -1
  171. package/widgets/VideoPlayer/components/PlayerActionsGroup.js +1 -1
  172. package/widgets/VideoPlayer/components/PlayerControlsGroup.js +1 -1
  173. package/widgets/support/GridControls.js +1 -1
  174. package/widgets/support/PluginSettingsControls.js +1 -1
  175. package/widgets/support/SelectionToolbar.js +1 -1
  176. package/widgets/support/SnappingControls.js +1 -1
  177. package/widgets/support/componentsUtils.js +1 -1
  178. package/arcade/geometry/wkt.js +0 -2
  179. package/assets/esri/core/workers/chunks/02d4f91652a79d2b637e.js +0 -1
  180. package/assets/esri/core/workers/chunks/05d865b2736f452ad2aa.js +0 -1
  181. package/assets/esri/core/workers/chunks/107b025dc5b09465a78f.js +0 -1
  182. package/assets/esri/core/workers/chunks/1b551ef3d84d9c1e93f9.js +0 -1
  183. package/assets/esri/core/workers/chunks/1f43e06dcfe56229bb0f.js +0 -1
  184. package/assets/esri/core/workers/chunks/260dcb79dfd0f981949f.js +0 -1
  185. package/assets/esri/core/workers/chunks/2a570ce6b99dac6ee996.js +0 -1
  186. package/assets/esri/core/workers/chunks/303676d1b10676c9cab4.js +0 -1
  187. package/assets/esri/core/workers/chunks/33956f12505e72e60293.js +0 -1
  188. package/assets/esri/core/workers/chunks/3880d2c7fb14955d7f93.js +0 -1
  189. package/assets/esri/core/workers/chunks/512628db534605a2a93e.js +0 -1742
  190. package/assets/esri/core/workers/chunks/57970d43cdcc5cf57a30.js +0 -1
  191. package/assets/esri/core/workers/chunks/5e184fd47e76eb976fa9.js +0 -1
  192. package/assets/esri/core/workers/chunks/5f3ab77a79c408423fde.js +0 -1
  193. package/assets/esri/core/workers/chunks/5fd099ca1024707387b2.js +0 -1
  194. package/assets/esri/core/workers/chunks/65654e481cce9ae40e54.js +0 -1
  195. package/assets/esri/core/workers/chunks/68e24fa3f564c2a5c9fd.js +0 -1
  196. package/assets/esri/core/workers/chunks/6aebf7cfd294e88bf926.js +0 -1
  197. package/assets/esri/core/workers/chunks/71103472c45928bd730c.js +0 -1
  198. package/assets/esri/core/workers/chunks/73a87fb270818aa75fc5.js +0 -1
  199. package/assets/esri/core/workers/chunks/776565dd9741ba2ba151.js +0 -1
  200. package/assets/esri/core/workers/chunks/8b54589f173259c1ba55.js +0 -1
  201. package/assets/esri/core/workers/chunks/8e7a33cc1f83063043f2.js +0 -1
  202. package/assets/esri/core/workers/chunks/a23272a7a47a95f6ddea.js +0 -1
  203. package/assets/esri/core/workers/chunks/aa5b42e44d2959fdacd3.js +0 -1
  204. package/assets/esri/core/workers/chunks/bff767ec5bb4c0d6b324.js +0 -1
  205. package/assets/esri/core/workers/chunks/c906f984b2b6e7578c06.js +0 -1
  206. package/assets/esri/core/workers/chunks/cbdebdfa5f2cded29d0d.js +0 -1
  207. package/assets/esri/core/workers/chunks/d56780290e0218d3e9de.js +0 -1
  208. package/assets/esri/core/workers/chunks/d89fe41c71c9621c41ae.js +0 -1
  209. package/assets/esri/core/workers/chunks/de02a6a1f4810f99e9bb.js +0 -1
  210. package/assets/esri/core/workers/chunks/e22d45aeef293a5ffb78.js +0 -1
  211. package/assets/esri/core/workers/chunks/e5943f3a4bbc12c06c4d.js +0 -1
  212. package/assets/esri/core/workers/chunks/edf3be87a997f4f05b96.js +0 -1
  213. package/assets/esri/core/workers/chunks/f0aaa646b17ffdbdcefa.js +0 -1
  214. package/assets/esri/core/workers/chunks/f0c0c02730fe0d948fc1.js +0 -1
  215. /package/{basemaps → basemapGallery}/support/basemapCompatibilityUtils.js +0 -0
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
- import{insertSortedStableTopN as e}from"../../../core/arrayUtils.js";import{importLazily as t}from"../../../core/importUtils.js";import{clone as n}from"../../../core/lang.js";import r from"../../../geometry/SpatialReference.js";import{polygonCentroid as i,extentCentroid as a}from"../../../geometry/support/centroid.js";import{getPolygonExtent as o,getGeometryExtent as s,expandExtent as c}from"../../../geometry/support/extentUtils.js";import{toQuantizationTransform as l}from"../../../geometry/support/quantizationUtils.js";import{isValid as u,equals as d}from"../../../geometry/support/spatialReferenceUtils.js";import{closestPointOnCurve as f}from"../../../geometry/support/curves/closestPointOnCurve.js";import{getEndpoint as p,isCoordinate as m,cloneCurve as h}from"../../../geometry/support/curves/curveUtils.js";import g from"./AttributesBuilder.js";import{cleanFromGeometryEngine as _,getGeometry as v,transformCentroid as y}from"./geometryUtils.js";import{project as b}from"./projectionSupport.js";import{getDateInNumber as x}from"./queryUtils.js";import{SnappingCandidateEdge as S,SnappingCandidateVertex as C}from"./SnappingCandidate.js";import{isDateField as w,isDateOnlyField as T,isTimestampOffsetField as E,isStringField as D,isTimeOnlyField as O}from"../../support/fieldUtils.js";import k from"../../../rest/support/AutoIntervalBinParameters.js";import A from"../../../rest/support/DateBinParameters.js";import{unitsDict as j}from"../../../rest/support/DateBinUtils.js";import M from"../../../rest/support/FixedBoundariesBinParameters.js";import N from"../../../rest/support/FixedIntervalBinParameters.js";import{calculateStringStatistics as P,calculateStatistics as F,processSummaryStatisticsResult as I,calculateUniqueValuesCount as L,createUVResult as R,calculateClassBreaks as z,resolveCBResult as B,calculateHistogram as V,calculatePercentile as H,binIndex as U,getBinParams as W,isNullCountSupported as G,getAttributeComparator as K}from"../../../statistics/utils.js";import{utc as q}from"../../../time/constants.js";import{DateTime as J}from"luxon";const Y=t(()=>import(`../../../geometry/operators/json/convexHullOperator.js`));class X{constructor(e,t,n){this.items=e,this.query=t,this.geometryType=n.geometryType,this.hasZ=!!t.returnZ&&n.hasZ,this.hasM=!!t.returnM&&n.hasM,this.fieldsIndex=n.fieldsIndex,this.spatialReference=n.spatialReference,this.featureAdapter=n.featureAdapter,this.featureIdInfo=n.featureIdInfo}get size(){return this.items.length}createQueryResponseForCount(){let e=new g(this.query,this.featureAdapter,this.fieldsIndex);if(!this.query.outStatistics)return e.countDistinctValues(this.items);let{groupByFieldsForStatistics:t,having:n,outStatistics:r}=this.query;if(!t?.length)return 1;let i=new Map,a=new Map,o=new Set;for(let s of r){let{statisticType:r}=s,c=r===`exceedslimit`?void 0:s.onStatisticField;if(!a.has(c)){let n=[];for(let r of t){let t=this._getAttributeValues(e,r,this.items,i);n.push(t)}a.set(c,this._calculateUniqueValues(n,this.items,e.returnDistinctValues))}let l=a.get(c);for(let t in l){let{data:r,items:i}=l[t],a=r.join(`,`);(!n||e.validateItems(i,n))&&o.add(a)}}return o.size}async createQueryResponse(){let e;if(e=this.query.outStatistics?this.query.outStatistics.some(e=>e.statisticType===`exceedslimit`)?this._createExceedsLimitQueryResponse():await this._createStatisticsQueryResponse(this.query,this.items):this._createFeatureQueryResponse(this.query),this.query.returnQueryGeometry){let t=this.query.geometry;u(this.query.outSR)&&!d(t.spatialReference,this.query.outSR)?e.queryGeometry=_({spatialReference:this.query.outSR,...b(t,t.spatialReference,this.query.outSR)}):e.queryGeometry=_({spatialReference:this.query.outSR,...t})}return e}createSnappingResponse(e,t,n){let r=this.featureAdapter,{point:i}=e,a=typeof e.distance==`number`?e.distance:e.distance.x,o=typeof e.distance==`number`?e.distance:e.distance.y;function s(e,t){let n=(e-i.x)/a,r=(t-i.y)/o;return n*n+r*r}let c={candidates:[]},l=this.geometryType===`esriGeometryPolygon`,u=this.geometryType===`esriGeometryPolyline`||this.geometryType===`esriGeometryPoint`,d=this._getPointCreator(t,this.spatialReference,n),g=new Q(null,0),_=new Q(null,0),v={x:0,y:0,z:0};for(let e of this.items){let t=r.getObjectId(e),n=r.getGeometryWithCurves?.(e);if(n!=null){b(n,t);continue}let i=r.getGeometry(e);i!=null&&y(i,t)}return c.candidates.sort((e,t)=>e.distance-t.distance),c;function y(t,n){let{coords:r,stride:a}=t,o=t.isPoint?te:t.lengths;if(g.coords=r,_.coords=r,e.returnEdge){let e=0;for(let t=0;t<o.length;t++){let r=o[t],u=e;for(let t=0;t<r;t++,e+=a){if(!l&&t===r-1||(g.coordsIndex=e,_.coordsIndex=t===r-1?u:e+a,!ee(v,i,g,_)))continue;let o=s(v.x,v.y);o<=1&&c.candidates.push(new S(n,d(v),Math.sqrt(o),d(g),d(_)))}}}if(e.vertexMode===`all`){let e=0;for(let t=0;t<o.length;t++){let r=o[t],i=e,u=_;u.coordsIndex=i;for(let t=0;t<r;t++,e+=a){if(g.coordsIndex=e,l&&t===r-1&&g.x===u.x&&g.y===u.y)continue;let i=s(g.x,g.y);i<=1&&c.candidates.push(new C(n,d(g),Math.sqrt(i)))}}}else if(u&&e.vertexMode===`ends`){let e=0,t=[];for(let n=0;n<o.length;n++){t.push(e);let r=o[n];e+=r*a,r>1&&t.push(e-a)}for(let e of t){g.coordsIndex=e;let t=s(g.x,g.y);t<=1&&c.candidates.push(new C(n,d(g),Math.sqrt(t)))}}}function b(t,n){let{candidates:r}=c,a={x:0,y:0,z:0};if(e.returnEdge){let e=[i.x,i.y],o=new Q(e,0),c=new Q(e,0);for(let{segments:i}of t.parts)for(let{start:t,curve:l}of i){let{curvePoint:i}=f(t,l,e),u=s(...i);if(u>1)continue;[a.x,a.y]=i,o.coords=t,c.coords=p(l);let g=m(l)?null:h(l);r.push(new S(n,d(a),Math.sqrt(u),d(o),d(c),!1,g))}}function o(e){a.x=t.vertexXY[e*2],a.y=t.vertexXY[e*2+1];let i=s(a.x,a.y);i>1||(a.z=t.vertexZ?.[e]??0,r.push(new C(n,d(a),Math.sqrt(i))))}if(e.vertexMode===`all`){let{vertexCount:e}=t;for(let t=0;t<e;++t)o(t)}else if(e.vertexMode===`ends`)switch(t.type){case`point`:o(0);break;case`polyline`:for(let e=0;e<t.partCount;++e){let n=t.partOffsets[e],r=t.partOffsets[e+1]-1;o(n),r!==n&&o(r)}}}}_getPointCreator(e,t,n){let r=n!=null&&!d(t,n)?e=>b(e,t,n):e=>e,{hasZ:i}=this;return i&&e?({x:e,y:t,z:n})=>r({x:e,y:t,z:n}):({x:e,y:t})=>r({x:e,y:t,z:0})}async createSummaryStatisticsResponse(e){let{field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,minValue:o,maxValue:s,scale:c,timeZone:l,outStatisticTypes:u}=e,d=this.fieldsIndex.get(t),f=w(d)||T(d)||E(d),p=await this._getDataValues({field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,scale:c,timeZone:l},this.items),m=G({normalizationType:i,normalizationField:r,minValue:o,maxValue:s}),h={value:.5,fieldType:d?.type},g=D(d)?P({values:p,supportsNullCount:m,percentileParams:h,outStatisticTypes:u}):F({values:p,minValue:o,maxValue:s,useSampleStdDev:!i,supportsNullCount:m,percentileParams:h,outStatisticTypes:u});return I(g,u,f)}async createUniqueValuesResponse(e){let{field:t,valueExpression:n,domains:r,returnAllCodedValues:i,scale:a,timeZone:o}=e,s=await this._getDataValues({field:t,field2:e.field2,field3:e.field3,fieldDelimiter:e.fieldDelimiter,valueExpression:n,scale:a,timeZone:o},this.items,!1),c=L(s);return R(c,r,i,e.fieldDelimiter)}async createClassBreaksResponse(e){let{field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,classificationMethod:o,standardDeviationInterval:s,minValue:c,maxValue:l,numClasses:u,scale:d,timeZone:f}=e,p=await this._getDataValues({field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,scale:d,timeZone:f},this.items),m=z(p,{field:t,normalizationField:r,normalizationType:i,normalizationTotal:a,classificationMethod:o,standardDeviationInterval:s,minValue:c,maxValue:l,numClasses:u});return B(m,o)}async createHistogramResponse(e){let{field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,classificationMethod:o,standardDeviationInterval:s,minValue:c,maxValue:l,numBins:u,scale:d,timeZone:f}=e,p=await this._getDataValues({field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,scale:d,timeZone:f},this.items);return V(p,{field:t,normalizationField:r,normalizationType:i,normalizationTotal:a,classificationMethod:o,standardDeviationInterval:s,minValue:c,maxValue:l,numBins:u})}_sortFeatures(e,t,n){if(e.length>1&&t?.length)for(let r of t.slice().reverse()){let{compare:t,fieldOrExpression:i,fieldInfo:a}=$(r,this.fieldsIndex);e.sort((e,r)=>t(n(e,i,a),n(r,i,a)))}}_topNFeatures(t,n,r,i){if(t.length>1&&n?.length){let a=n.map(e=>{let{compare:t,fieldOrExpression:n,fieldInfo:r}=$(e,this.fieldsIndex);return(e,a)=>t(i(e,n,r),i(a,n,r))}).reduceRight((e,t)=>(n,r)=>{let i=t(n,r);return i!==0&&!Number.isNaN(i)?i:e(n,r)}),o=[];for(let n of t)e(o,n,r,a);return o}return t.slice(0,r)}_createFeatureQueryResponse(e){let{items:t,geometryType:n,hasM:r,hasZ:i,featureIdInfo:a,spatialReference:o}=this,{outFields:s,outSR:c,quantizationParameters:u,resultRecordCount:d,resultOffset:f,returnZ:p,returnM:m}=e,h=d!=null&&t.length>(f||0)+d,g=s&&(s.includes(`*`)?[...this.fieldsIndex.fields]:s.map(e=>this.fieldsIndex.get(e)));return{exceededTransferLimit:h,features:this._createFeatures(e,t),fields:g,geometryType:n,hasM:r&&m,hasZ:i&&p,objectIdFieldName:a.type===`object-id`?a.fieldName:null,spatialReference:_(c||o),transform:u&&l(u)||null}}_createFeatures(e,t){let n=new g(e,this.featureAdapter,this.fieldsIndex),{hasM:r,hasZ:i}=this,{orderByFields:a,quantizationParameters:o,returnGeometry:s,returnCentroid:c,maxAllowableOffset:u,resultOffset:d,resultRecordCount:f,returnZ:p=!1,returnM:m=!1}=e,h=i&&p,_=r&&m,b,x=d||0,S=f==null?null:x+f;S!=null&&S<=5e3&&S<t.length?b=this._topNFeatures(t,a,S,(e,t,r)=>n.getFieldValue(e,t,r)):(b=[...t],this._sortFeatures(b,a,(e,t,r)=>n.getFieldValue(e,t,r))),(x>0||S!=null)&&(b=b.slice(x,S??void 0));let C=[],w=0;if(!this.geometryType||!s&&!c)for(let e of b){let t=n.getAttributes(e);t&&(C[w++]=this._addFeatureJSONMetadata(e,{attributes:t}))}else{let e=l(o)??void 0,t=this.geometryType===`esriGeometryPolygon`||this.geometryType===`esriGeometryPolyline`;if(s&&!c)for(let r of b){let i=this.featureAdapter.getGeometry(r),a=this._addFeatureJSONMetadata(r,{attributes:n.getAttributes(r),geometry:v(this.geometryType,i,u,e,h,_)});t&&i&&!a.geometry&&(a.centroid=y(this,this.featureAdapter.getCentroid(r,this),e)),C[w++]=a}else if(!s&&c)for(let t of b)C[w++]=this._addFeatureJSONMetadata(t,{attributes:n.getAttributes(t),centroid:y(this,this.featureAdapter.getCentroid(t,this),e)});else for(let t of b)C[w++]=this._addFeatureJSONMetadata(t,{attributes:n.getAttributes(t),centroid:y(this,this.featureAdapter.getCentroid(t,this),e),geometry:v(this.geometryType,this.featureAdapter.getGeometry(t),u,e,h,_)})}return C}_addFeatureJSONMetadata(e,t){let n=this.featureAdapter.getMetadata?.(e);return n!==void 0&&(t.metadata=n),t}_createExceedsLimitQueryResponse(){let e=!1,t=1/0,n=1/0,r=1/0;for(let e of this.query.outStatistics??[])if(e.statisticType===`exceedslimit`){t=e.maxPointCount==null?1/0:e.maxPointCount,n=e.maxRecordCount==null?1/0:e.maxRecordCount,r=e.maxVertexCount==null?1/0:e.maxVertexCount;break}return e=this.geometryType===`esriGeometryPoint`?this.items.length>t:this.items.length>n||this.items.reduce((e,t)=>e+(this.featureAdapter.getGeometry(t)?.size??0),0)>r,{fields:[{name:`exceedslimit`,type:`esriFieldTypeInteger`,alias:`exceedslimit`,sqlType:`sqlTypeInteger`,domain:null,defaultValue:null}],features:[{attributes:{exceedslimit:Number(e)}}]}}async _createStatisticsQueryResponse(e,t,n={attributes:{}}){let r=[],i=new Map,a=new Map,o=new Map,s=new Map,c=new g(e,this.featureAdapter,this.fieldsIndex),l=e.outStatistics,{groupByFieldsForStatistics:u,having:d,orderByFields:f,resultRecordCount:p}=e,m=u?.length,h=!!m,_=h?u[0]:null,v=h&&!this.fieldsIndex.get(_);for(let f of l??[]){let{outStatisticFieldName:l,statisticType:p}=f,g=f,y=p===`exceedslimit`?void 0:f.onStatisticField,b=p===`percentile_disc`||p===`percentile_cont`,x=p===`EnvelopeAggregate`||p===`CentroidAggregate`||p===`ConvexHullAggregate`,S=h&&m===1&&(y===_||v)&&p===`count`;if(h){if(!o.has(y)){let e=[];for(let n of u){let r=this._getAttributeValues(c,n,t,i);e.push(r)}o.set(y,this._calculateUniqueValues(e,t,!x&&c.returnDistinctValues))}let n=o.get(y);if(!n)continue;let r=Object.keys(n);for(let a of r){let{count:r,data:o,items:f,itemPositions:p}=n[a],m=o.join(`,`);if(!d||c.validateItems(f,d)){let n=s.get(m)||{attributes:{}};if(e.returnAggIds&&(n.aggregateIds=f.map(e=>this.featureAdapter.getObjectId(e)).filter(e=>e!=null)),x){n.aggregateGeometries||={};let{aggregateGeometries:e,outStatisticFieldName:t}=await this._getAggregateGeometry(g,f);n.aggregateGeometries[t]=e}else{let e=null;if(S)e=r;else{let n=this._getAttributeValues(c,y,t,i),r=p.map(e=>n[e]);e=b&&`statisticParameters`in g?this._getPercentileValue(g,r):this._getStatisticValue(g,r,null,c.returnDistinctValues)}n.attributes[l]=e}let a=0;u.forEach((e,t)=>n.attributes[this.fieldsIndex.get(e)?e:`EXPR_${++a}`]=o[t]),s.set(m,n)}}}else if(x){n.aggregateGeometries||={};let{aggregateGeometries:e,outStatisticFieldName:r}=await this._getAggregateGeometry(g,t);n.aggregateGeometries[r]=e}else{let e=this._getAttributeValues(c,y,t,i);n.attributes[l]=b&&`statisticParameters`in g?this._getPercentileValue(g,e):this._getStatisticValue(g,e,a,c.returnDistinctValues)}let C=(p===`min`||p===`max`)&&(D(this.fieldsIndex.get(y))||this._isAnyDateField(y))?this.fieldsIndex.get(y)?.type:null;r.push({name:l,alias:l,type:C||`esriFieldTypeDouble`})}let y=h?Array.from(s.values()):[n];return this._sortFeatures(y,f,(e,t)=>e.attributes[t]),p&&(y.length=Math.min(p,y.length)),{fields:r,features:y}}_isAnyDateField(e){let t=this.fieldsIndex.get(e);return w(t)||T(t)||E(t)||O(t)}async _getAggregateGeometry(e,t){let{statisticType:n,outStatisticFieldName:r}=e,{featureAdapter:s,spatialReference:c,geometryType:l}=this,u=t.map(e=>v(l,s.getGeometry(e))),d={aggregateGeometries:null,outStatisticFieldName:null},{convexHullExecuteMany:f}=await Y.getImportPromise(),[p]=f(u,{merge:!0});if(p&&p.rings[0].length<=3&&(p=null),n===`EnvelopeAggregate`)d.aggregateGeometries={...p?o(p):Z(u),spatialReference:c},d.outStatisticFieldName=r||`extent`;else if(n===`CentroidAggregate`){let[e,t]=p?i(p):a(Z(u));d.aggregateGeometries={x:e,y:t,spatialReference:c},d.outStatisticFieldName=r||`centroid`}else n===`ConvexHullAggregate`&&(d.aggregateGeometries=p&&{...p,spatialReference:c},d.outStatisticFieldName=r||`convexHull`);return d}_getStatisticValue(e,t,n,r){let{onStatisticField:i,statisticType:a}=e,o=null;return o=n?.has(i)?n.get(i):D(this.fieldsIndex.get(i))||this._isAnyDateField(i)?P({values:t,returnDistinct:r}):F({values:r?[...new Set(t)]:t,minValue:null,maxValue:null,useSampleStdDev:!0}),n&&n.set(i,o),o[a===`var`?`variance`:a]}_getPercentileValue(e,t){let{onStatisticField:n,statisticParameters:r,statisticType:i}=e,{value:a,orderBy:o}=r,s={value:a,orderBy:o,fieldType:this.fieldsIndex.get(n)?.type,isDiscrete:i===`percentile_disc`};return H(t,s)}_getAttributeValues(e,t,n,r){if(r.has(t))return r.get(t);let i=this.fieldsIndex.get(t),a=n.map(n=>e.getFieldValue(n,t,i));return r.set(t,a),a}_calculateUniqueValues(e,t,n){let r={},i=t.length;for(let a=0;a<i;a++){let i=t[a],o=[];for(let t of e)o.push(t[a]);let s=o.join(`,`);r[s]==null?r[s]={count:1,data:o,items:[i],itemPositions:[a]}:(n||r[s].count++,r[s].items.push(i),r[s].itemPositions.push(a))}return r}async _getDataValues(e,t,i=!0){let a=new g(this.query,this.featureAdapter,this.fieldsIndex),{valueExpression:o,scale:s,timeZone:c}=e,l=r.fromJSON(this.query.outSR||this.spatialReference);return o?a.getExpressionValues(t,o,{viewingMode:`map`,scale:s,spatialReference:l},{geometryType:this.geometryType,hasZ:this.hasZ,hasM:this.hasM},c):a.getDataValues(t,n(e),i)}_calculateHistogramBins(e,t,n){if(t.min==null&&t.max==null)return[];let r=t.intervals,i=t.min??0,a=t.max??0,o=r.map(([e,t])=>({minValue:e,maxValue:t,count:0,items:[]}));for(let t=0;t<e.length;t++){let s=e[t],c=n[t];if(s!=null&&s>=i&&s<=a){let e=U(r,s);e>-1&&(o[e].count++,o[e].items.push(c))}}return o}async createQueryBinsResponse(e){let t=e.bin?.splitBy;if(!t)return this._createBinsResponse(e);let{value:n,outAlias:r,valueType:i}=t,a=[],o=[{name:r??n,alias:r??n,type:i??`esriFieldTypeString`},{name:`bin`,alias:`bin`,type:`esriFieldTypeInteger`}],s=new g(e,this.featureAdapter,this.fieldsIndex),c=new Map,l=[...this.items];this._sortFeatures(l,[n],(e,t,n)=>s.getFieldValue(e,t,n));let u=this._getAttributeValues(s,n,l,c),d=this._calculateUniqueValues([u],l,s.returnDistinctValues);for(let t in d){let{items:i}=d[t],s=await this._createBinsResponse(e,i);if(a.push(...s.features.map(e=>({...e,attributes:{...e.attributes,[r??n]:t}}))),s.fields)for(let e of s.fields)o.some(t=>t.name===e.name)||o.push(e)}return{fields:o,features:a}}async _createBinsResponse(e,t){let n=e.bin;switch(t??=this.items,n.type){case`autoIntervalBin`:return this._createAutoIntervalBinsResponse(k.fromJSON(n),e,t);case`dateBin`:return this._createDateBinsResponse(A.fromJSON(n),e,t);case`fixedBoundariesBin`:return this._createFixedBoundariesBinsResponse(M.fromJSON(n),e,t);case`fixedIntervalBin`:return this._createFixedIntervalBinsResponse(N.fromJSON(n),e,t)}}async _createAutoIntervalBinsResponse(e,t,n){let{field:r,normalizationField:i,numBins:a,normalizationType:o,normalizationTotal:s,start:c,end:l}=e,u=await this._getDataValues({field:e.field||e.expression,normalizationField:e.normalizationField,normalizationType:e.normalizationType,normalizationTotal:e.normalizationTotal,timeZone:t.outTimeReference?.ianaTimeZone},n),d=W(u,{field:r,normalizationField:i,normalizationType:o,normalizationTotal:s,numBins:a,minValue:x(o?e.normalizationMinValue:c,!1),maxValue:x(o?e.normalizationMaxValue:l,!1)}),f=this._calculateHistogramBins(u,d,n);return this._createFeaturesFromHistogramBins(f,t)}async _createDateBinsResponse(e,t,n){let{field:r,interval:i,start:a,end:o,snapToData:s,returnFullIntervalBin:c,offset:l,firstDayOfWeek:u}=e,d=i.unit,f=await this._getDataValues({field:r||e.expression,timeZone:t.outTimeReference?.ianaTimeZone},n),p=O(this.fieldsIndex.get(r)),m=j.toJSON(d),h=f.filter(Boolean).sort((e,t)=>e-t),g=a==null?h[0]:x(a,p),_=o==null?h[h.length-1]:x(o,p),v=[];if(g!=null&&_!=null){let e={zone:t.outTimeReference?.ianaTimeZone??q},n={[l?.unit?j.toJSON(l.unit):`milliseconds`]:l?.value||0},r=J.fromMillis(g,e).minus(n),a=J.fromMillis(_,e).minus(n),o=typeof u==`number`&&u>=1&&u<=7?u:7,d=(e,t)=>{let n=(e.weekday-t+7)%7;return e.minus({days:n}).startOf(`day`)},f=(e,t)=>d(e,t).plus({days:7});if(s===`last`){let e=m===`week`?f(a,o):a;for(;e>r;){let t=e.minus({[m]:i.value});if(t<r){v.unshift([c?t.plus(n).toMillis():r.plus(n).toMillis(),e.plus(n).toMillis()]);break}v.unshift([t.plus(n).toMillis(),e.plus(n).toMillis()]),e=t}}else{let e=s===`first`?r:m===`week`?d(r,o):r.startOf(m);for(;e<=a;){let t=e.plus({[m]:i.value});if(t>a){v.push([e.plus(n).toMillis(),c?t.plus(n).toMillis():a.plus(n).toMillis()]);break}v.push([e.plus(n).toMillis(),t.plus(n).toMillis()]),e=t}}}let y=this._calculateHistogramBins(f,{intervals:v,min:g,max:_},n);return this._createFeaturesFromHistogramBins(y,t)}async _createFixedBoundariesBinsResponse(e,t,n){let{field:r}=e,i=await this._getDataValues({field:r||e.expression,timeZone:t.outTimeReference?.ianaTimeZone},n),a=O(this.fieldsIndex.get(r)),o=e.boundaries.map(e=>x(e,a)).sort((e,t)=>e-t),s=[];for(let e=0;e<o.length-1;e++)s.push([o[e],o[e+1]]);let c={intervals:s,min:o.at(0),max:o.at(-1)},l=this._calculateHistogramBins(i,c,n);return this._createFeaturesFromHistogramBins(l,t)}async _createFixedIntervalBinsResponse(e,t,n){let{field:r,interval:i,normalizationType:a,start:o,end:s}=e,c=await this._getDataValues({field:r||e.expression,normalizationField:e.normalizationField,normalizationType:a,normalizationTotal:e.normalizationTotal,timeZone:t.outTimeReference?.ianaTimeZone},n),l=O(this.fieldsIndex.get(r)),u=W(c,{field:r,classificationMethod:`defined-interval`,definedInterval:i,minValue:x(a?e.normalizationMinValue:o,l),maxValue:x(a?e.normalizationMaxValue:s,l)},!0),d=this._calculateHistogramBins(c,u,n);return this._createFeaturesFromHistogramBins(d,t)}async _createFeaturesFromHistogramBins(e,t){let{upperBoundaryAlias:n,lowerBoundaryAlias:r}=t,i=r||`lowerBoundary`,a=n||`upperBoundary`,o=[],s=[{name:i,alias:i,type:`esriFieldTypeDouble`},{name:a,alias:a,type:`esriFieldTypeDouble`}],c=t.bin?.stackBy?.value,l=t.bin?.stackBy?.outAlias;c&&s.push({name:`bin`,alias:`bin`,type:`esriFieldTypeInteger`},{name:l??c,alias:l??c,type:`esriFieldTypeString`});let u=0,d=t.bin.type===`dateBin`,f=t.outTimeReference?.ianaTimeZone;for(let n of e){let{minValue:e,maxValue:r,items:p}=n,m={attributes:{}};m.attributes[i]=d&&f&&e!=null?J.fromMillis(e,{zone:f}).toISO():e,t.bin.hideUpperBound||(m.attributes[a]=d&&f&&r!=null?J.fromMillis(r,{zone:f}).toISO():r),t.returnAggIds&&(m.aggregateIds=p.map(e=>this.featureAdapter.getObjectId(e)).filter(e=>e!=null));let h;if(c?(h=await this._createStatisticsQueryResponse({...t,groupByFieldsForStatistics:[c],orderByFields:[c]},p),m.attributes.bin=++u,t.bin.jsonStyle===`flat`?o.push(...h.features.map(({attributes:{EXPR_1:e,...t},...n})=>({...n,attributes:l??e?{...t,[l??e]:e,...m.attributes}:{...t,...m.attributes}}))):(m.stackedAttributes=h.features.map(({attributes:{EXPR_1:e,...t}})=>l??e?{...t,[l??e]:e}:t),o.push(m))):(t.bin?.splitBy&&(m.attributes.bin=++u),h=await this._createStatisticsQueryResponse(t,p,m),o.push(m)),h.fields)for(let e of h.fields)s.some(t=>t.name===e.name)||s.push(e)}return t.binOrder===`desc`&&o.reverse(),{fields:s,features:o}}}function Z(e){let t=s(e[0]);for(let n of e.slice(1))c(t,s(n));return t}function ee(e,t,n,r){let i=r.x-n.x,a=r.y-n.y,o=t.x-n.x,s=t.y-n.y,c=i*i+a*a;if(c===0)return!1;let l=o*i+s*a,u=Math.min(1,Math.max(0,l/c));return e.x=n.x+i*u,e.y=n.y+a*u,!0}class Q{constructor(e,t){this.coords=e,this.coordsIndex=t}get x(){return this.coords[this.coordsIndex]}get y(){return this.coords[this.coordsIndex+1]}get z(){return this.coords[this.coordsIndex+2]}}const te=[1];function $(e,t){let n=e.split(` `),r=n[0],i=t.get(r),a=n[1]?n[1].toLowerCase()===`desc`:!1;return{compare:K(i?.type,a,`case-insensitive`),fieldOrExpression:r,fieldInfo:i}}export{X as QueryEngineResult};
2
+ import{insertSortedStableTopN as e}from"../../../core/arrayUtils.js";import{importLazily as t}from"../../../core/importUtils.js";import{clone as n}from"../../../core/lang.js";import r from"../../../geometry/SpatialReference.js";import{polygonCentroid as i,extentCentroid as a}from"../../../geometry/support/centroid.js";import{getPolygonExtent as o,getGeometryExtent as s,expandExtent as c}from"../../../geometry/support/extentUtils.js";import{toQuantizationTransform as l}from"../../../geometry/support/quantizationUtils.js";import{isValid as u,equals as d}from"../../../geometry/support/spatialReferenceUtils.js";import{closestPointOnCurve as f}from"../../../geometry/support/curves/closestPointOnCurve.js";import{getEndpoint as p,isCoordinate as m,cloneCurve as h}from"../../../geometry/support/curves/curveUtils.js";import g from"./AttributesBuilder.js";import{getGeometry as _,transformCentroid as v}from"./geometryUtils.js";import{project as y}from"./projectionSupport.js";import{getDateInNumber as b}from"./queryUtils.js";import{SnappingCandidateEdge as x,SnappingCandidateVertex as S}from"./SnappingCandidate.js";import{isDateField as C,isDateOnlyField as w,isTimestampOffsetField as T,isStringField as E,isTimeOnlyField as D}from"../../support/fieldUtils.js";import O from"../../../rest/support/AutoIntervalBinParameters.js";import k from"../../../rest/support/DateBinParameters.js";import{unitsDict as A}from"../../../rest/support/DateBinUtils.js";import j from"../../../rest/support/FixedBoundariesBinParameters.js";import M from"../../../rest/support/FixedIntervalBinParameters.js";import{calculateStringStatistics as N,calculateStatistics as P,processSummaryStatisticsResult as F,calculateUniqueValuesCount as I,createUVResult as L,calculateClassBreaks as R,resolveCBResult as z,calculateHistogram as B,calculatePercentile as V,binIndex as H,getBinParams as U,isNullCountSupported as W,getAttributeComparator as G}from"../../../statistics/utils.js";import{utc as K}from"../../../time/constants.js";import{DateTime as q}from"luxon";const J=t(()=>import(`../../../geometry/operators/json/convexHullOperator.js`));class Y{constructor(e,t,n){this.items=e,this.query=t,this.geometryType=n.geometryType,this.hasZ=!!t.returnZ&&n.hasZ,this.hasM=!!t.returnM&&n.hasM,this.fieldsIndex=n.fieldsIndex,this.spatialReference=n.spatialReference,this.featureAdapter=n.featureAdapter,this.featureIdInfo=n.featureIdInfo}get size(){return this.items.length}createQueryResponseForCount(){let e=new g(this.query,this.featureAdapter,this.fieldsIndex);if(!this.query.outStatistics)return e.countDistinctValues(this.items);let{groupByFieldsForStatistics:t,having:n,outStatistics:r}=this.query;if(!t?.length)return 1;let i=new Map,a=new Map,o=new Set;for(let s of r){let{statisticType:r}=s,c=r===`exceedslimit`?void 0:s.onStatisticField;if(!a.has(c)){let n=[];for(let r of t){let t=this._getAttributeValues(e,r,this.items,i);n.push(t)}a.set(c,this._calculateUniqueValues(n,this.items,e.returnDistinctValues))}let l=a.get(c);for(let t in l){let{data:r,items:i}=l[t],a=r.join(`,`);(!n||e.validateItems(i,n))&&o.add(a)}}return o.size}async createQueryResponse(){let e;if(e=this.query.outStatistics?this.query.outStatistics.some(e=>e.statisticType===`exceedslimit`)?this._createExceedsLimitQueryResponse():await this._createStatisticsQueryResponse(this.query,this.items):this._createFeatureQueryResponse(this.query),this.query.returnQueryGeometry){let t=this.query.geometry;e.queryGeometry={spatialReference:this.query.outSR,...u(this.query.outSR)&&!d(t.spatialReference,this.query.outSR)?y(t,t.spatialReference,this.query.outSR):t}}return e}createSnappingResponse(e,t,n){let r=this.featureAdapter,{point:i}=e,a=typeof e.distance==`number`?e.distance:e.distance.x,o=typeof e.distance==`number`?e.distance:e.distance.y;function s(e,t){let n=(e-i.x)/a,r=(t-i.y)/o;return n*n+r*r}let c={candidates:[]},l=this.geometryType===`esriGeometryPolygon`,u=this.geometryType===`esriGeometryPolyline`||this.geometryType===`esriGeometryPoint`,d=this._getPointCreator(t,this.spatialReference,n),g=new Q(null,0),_=new Q(null,0),v={x:0,y:0,z:0};for(let e of this.items){let t=r.getObjectId(e),n=r.getGeometryWithCurves?.(e);if(n!=null){b(n,t);continue}let i=r.getGeometry(e);i!=null&&y(i,t)}return c.candidates.sort((e,t)=>e.distance-t.distance),c;function y(t,n){let{coords:r,stride:a}=t,o=t.isPoint?ee:t.lengths;if(g.coords=r,_.coords=r,e.returnEdge){let e=0;for(let t=0;t<o.length;t++){let r=o[t],u=e;for(let t=0;t<r;t++,e+=a){if(!l&&t===r-1||(g.coordsIndex=e,_.coordsIndex=t===r-1?u:e+a,!Z(v,i,g,_)))continue;let o=s(v.x,v.y);o<=1&&c.candidates.push(new x(n,d(v),Math.sqrt(o),d(g),d(_)))}}}if(e.vertexMode===`all`){let e=0;for(let t=0;t<o.length;t++){let r=o[t],i=e,u=_;u.coordsIndex=i;for(let t=0;t<r;t++,e+=a){if(g.coordsIndex=e,l&&t===r-1&&g.x===u.x&&g.y===u.y)continue;let i=s(g.x,g.y);i<=1&&c.candidates.push(new S(n,d(g),Math.sqrt(i)))}}}else if(u&&e.vertexMode===`ends`){let e=0,t=[];for(let n=0;n<o.length;n++){t.push(e);let r=o[n];e+=r*a,r>1&&t.push(e-a)}for(let e of t){g.coordsIndex=e;let t=s(g.x,g.y);t<=1&&c.candidates.push(new S(n,d(g),Math.sqrt(t)))}}}function b(t,n){let{candidates:r}=c,a={x:0,y:0,z:0};if(e.returnEdge){let e=[i.x,i.y],o=new Q(e,0),c=new Q(e,0);for(let{segments:i}of t.parts)for(let{start:t,curve:l}of i){let{curvePoint:i}=f(t,l,e),u=s(...i);if(u>1)continue;[a.x,a.y]=i,o.coords=t,c.coords=p(l);let g=m(l)?null:h(l);r.push(new x(n,d(a),Math.sqrt(u),d(o),d(c),!1,g))}}function o(e){a.x=t.vertexXY[e*2],a.y=t.vertexXY[e*2+1];let i=s(a.x,a.y);i>1||(a.z=t.vertexZ?.[e]??0,r.push(new S(n,d(a),Math.sqrt(i))))}if(e.vertexMode===`all`){let{vertexCount:e}=t;for(let t=0;t<e;++t)o(t)}else if(e.vertexMode===`ends`)switch(t.type){case`point`:o(0);break;case`polyline`:for(let e=0;e<t.partCount;++e){let n=t.partOffsets[e],r=t.partOffsets[e+1]-1;o(n),r!==n&&o(r)}}}}_getPointCreator(e,t,n){let r=n!=null&&!d(t,n)?e=>y(e,t,n):e=>e,{hasZ:i}=this;return i&&e?({x:e,y:t,z:n})=>r({x:e,y:t,z:n}):({x:e,y:t})=>r({x:e,y:t,z:0})}async createSummaryStatisticsResponse(e){let{field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,minValue:o,maxValue:s,scale:c,timeZone:l,outStatisticTypes:u}=e,d=this.fieldsIndex.get(t),f=C(d)||w(d)||T(d),p=await this._getDataValues({field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,scale:c,timeZone:l},this.items),m=W({normalizationType:i,normalizationField:r,minValue:o,maxValue:s}),h={value:.5,fieldType:d?.type},g=E(d)?N({values:p,supportsNullCount:m,percentileParams:h,outStatisticTypes:u}):P({values:p,minValue:o,maxValue:s,useSampleStdDev:!i,supportsNullCount:m,percentileParams:h,outStatisticTypes:u});return F(g,u,f)}async createUniqueValuesResponse(e){let{field:t,valueExpression:n,domains:r,returnAllCodedValues:i,scale:a,timeZone:o}=e,s=await this._getDataValues({field:t,field2:e.field2,field3:e.field3,fieldDelimiter:e.fieldDelimiter,valueExpression:n,scale:a,timeZone:o},this.items,!1),c=I(s);return L(c,r,i,e.fieldDelimiter)}async createClassBreaksResponse(e){let{field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,classificationMethod:o,standardDeviationInterval:s,minValue:c,maxValue:l,numClasses:u,scale:d,timeZone:f}=e,p=await this._getDataValues({field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,scale:d,timeZone:f},this.items),m=R(p,{field:t,normalizationField:r,normalizationType:i,normalizationTotal:a,classificationMethod:o,standardDeviationInterval:s,minValue:c,maxValue:l,numClasses:u});return z(m,o)}async createHistogramResponse(e){let{field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,classificationMethod:o,standardDeviationInterval:s,minValue:c,maxValue:l,numBins:u,scale:d,timeZone:f}=e,p=await this._getDataValues({field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,scale:d,timeZone:f},this.items);return B(p,{field:t,normalizationField:r,normalizationType:i,normalizationTotal:a,classificationMethod:o,standardDeviationInterval:s,minValue:c,maxValue:l,numBins:u})}_sortFeatures(e,t,n){if(e.length>1&&t?.length)for(let r of t.slice().reverse()){let{compare:t,fieldOrExpression:i,fieldInfo:a}=$(r,this.fieldsIndex);e.sort((e,r)=>t(n(e,i,a),n(r,i,a)))}}_topNFeatures(t,n,r,i){if(t.length>1&&n?.length){let a=n.map(e=>{let{compare:t,fieldOrExpression:n,fieldInfo:r}=$(e,this.fieldsIndex);return(e,a)=>t(i(e,n,r),i(a,n,r))}).reduceRight((e,t)=>(n,r)=>{let i=t(n,r);return i!==0&&!Number.isNaN(i)?i:e(n,r)}),o=[];for(let n of t)e(o,n,r,a);return o}return t.slice(0,r)}_createFeatureQueryResponse(e){let{items:t,geometryType:n,hasM:r,hasZ:i,featureIdInfo:a,spatialReference:o}=this,{outFields:s,outSR:c,quantizationParameters:u,resultRecordCount:d,resultOffset:f,returnZ:p,returnM:m}=e,h=d!=null&&t.length>(f||0)+d,g=s&&(s.includes(`*`)?[...this.fieldsIndex.fields]:s.map(e=>this.fieldsIndex.get(e)));return{exceededTransferLimit:h,features:this._createFeatures(e,t),fields:g,geometryType:n,hasM:r&&m,hasZ:i&&p,objectIdFieldName:a.type===`object-id`?a.fieldName:null,spatialReference:c||o,transform:u&&l(u)||null}}_createFeatures(e,t){let n=new g(e,this.featureAdapter,this.fieldsIndex),{hasM:r,hasZ:i}=this,{orderByFields:a,quantizationParameters:o,returnGeometry:s,returnCentroid:c,maxAllowableOffset:u,resultOffset:d,resultRecordCount:f,returnZ:p=!1,returnM:m=!1}=e,h=i&&p,y=r&&m,b,x=d||0,S=f==null?null:x+f;S!=null&&S<=5e3&&S<t.length?b=this._topNFeatures(t,a,S,(e,t,r)=>n.getFieldValue(e,t,r)):(b=[...t],this._sortFeatures(b,a,(e,t,r)=>n.getFieldValue(e,t,r))),(x>0||S!=null)&&(b=b.slice(x,S??void 0));let C=[],w=0;if(!this.geometryType||!s&&!c)for(let e of b){let t=n.getAttributes(e);t&&(C[w++]=this._addFeatureJSONMetadata(e,{attributes:t}))}else{let e=l(o)??void 0,t=this.geometryType===`esriGeometryPolygon`||this.geometryType===`esriGeometryPolyline`;if(s&&!c)for(let r of b){let i=this.featureAdapter.getGeometry(r),a=this._addFeatureJSONMetadata(r,{attributes:n.getAttributes(r),geometry:_(this.geometryType,i,u,e,h,y)});t&&i&&!a.geometry&&(a.centroid=v(this,this.featureAdapter.getCentroid(r,this),e)),C[w++]=a}else if(!s&&c)for(let t of b)C[w++]=this._addFeatureJSONMetadata(t,{attributes:n.getAttributes(t),centroid:v(this,this.featureAdapter.getCentroid(t,this),e)});else for(let t of b)C[w++]=this._addFeatureJSONMetadata(t,{attributes:n.getAttributes(t),centroid:v(this,this.featureAdapter.getCentroid(t,this),e),geometry:_(this.geometryType,this.featureAdapter.getGeometry(t),u,e,h,y)})}return C}_addFeatureJSONMetadata(e,t){let n=this.featureAdapter.getMetadata?.(e);return n!==void 0&&(t.metadata=n),t}_createExceedsLimitQueryResponse(){let e=!1,t=1/0,n=1/0,r=1/0;for(let e of this.query.outStatistics??[])if(e.statisticType===`exceedslimit`){t=e.maxPointCount==null?1/0:e.maxPointCount,n=e.maxRecordCount==null?1/0:e.maxRecordCount,r=e.maxVertexCount==null?1/0:e.maxVertexCount;break}return e=this.geometryType===`esriGeometryPoint`?this.items.length>t:this.items.length>n||this.items.reduce((e,t)=>e+(this.featureAdapter.getGeometry(t)?.size??0),0)>r,{fields:[{name:`exceedslimit`,type:`esriFieldTypeInteger`,alias:`exceedslimit`,sqlType:`sqlTypeInteger`,domain:null,defaultValue:null}],features:[{attributes:{exceedslimit:Number(e)}}]}}async _createStatisticsQueryResponse(e,t,n={attributes:{}}){let r=[],i=new Map,a=new Map,o=new Map,s=new Map,c=new g(e,this.featureAdapter,this.fieldsIndex),l=e.outStatistics,{groupByFieldsForStatistics:u,having:d,orderByFields:f,resultRecordCount:p}=e,m=u?.length,h=!!m,_=h?u[0]:null,v=h&&!this.fieldsIndex.get(_);for(let f of l??[]){let{outStatisticFieldName:l,statisticType:p}=f,g=f,y=p===`exceedslimit`?void 0:f.onStatisticField,b=p===`percentile_disc`||p===`percentile_cont`,x=p===`EnvelopeAggregate`||p===`CentroidAggregate`||p===`ConvexHullAggregate`,S=h&&m===1&&(y===_||v)&&p===`count`;if(h){if(!o.has(y)){let e=[];for(let n of u){let r=this._getAttributeValues(c,n,t,i);e.push(r)}o.set(y,this._calculateUniqueValues(e,t,!x&&c.returnDistinctValues))}let n=o.get(y);if(!n)continue;let r=Object.keys(n);for(let a of r){let{count:r,data:o,items:f,itemPositions:p}=n[a],m=o.join(`,`);if(!d||c.validateItems(f,d)){let n=s.get(m)||{attributes:{}};if(e.returnAggIds&&(n.aggregateIds=f.map(e=>this.featureAdapter.getObjectId(e)).filter(e=>e!=null)),x){n.aggregateGeometries||={};let{aggregateGeometries:e,outStatisticFieldName:t}=await this._getAggregateGeometry(g,f);n.aggregateGeometries[t]=e}else{let e=null;if(S)e=r;else{let n=this._getAttributeValues(c,y,t,i),r=p.map(e=>n[e]);e=b&&`statisticParameters`in g?this._getPercentileValue(g,r):this._getStatisticValue(g,r,null,c.returnDistinctValues)}n.attributes[l]=e}let a=0;u.forEach((e,t)=>n.attributes[this.fieldsIndex.get(e)?e:`EXPR_${++a}`]=o[t]),s.set(m,n)}}}else if(x){n.aggregateGeometries||={};let{aggregateGeometries:e,outStatisticFieldName:r}=await this._getAggregateGeometry(g,t);n.aggregateGeometries[r]=e}else{let e=this._getAttributeValues(c,y,t,i);n.attributes[l]=b&&`statisticParameters`in g?this._getPercentileValue(g,e):this._getStatisticValue(g,e,a,c.returnDistinctValues)}let C=(p===`min`||p===`max`)&&(E(this.fieldsIndex.get(y))||this._isAnyDateField(y))?this.fieldsIndex.get(y)?.type:null;r.push({name:l,alias:l,type:C||`esriFieldTypeDouble`})}let y=h?Array.from(s.values()):[n];return this._sortFeatures(y,f,(e,t)=>e.attributes[t]),p&&(y.length=Math.min(p,y.length)),{fields:r,features:y}}_isAnyDateField(e){let t=this.fieldsIndex.get(e);return C(t)||w(t)||T(t)||D(t)}async _getAggregateGeometry(e,t){let{statisticType:n,outStatisticFieldName:r}=e,{featureAdapter:s,spatialReference:c,geometryType:l}=this,u=t.map(e=>_(l,s.getGeometry(e))),d={aggregateGeometries:null,outStatisticFieldName:null},{convexHullExecuteMany:f}=await J.getImportPromise(),[p]=f(u,{merge:!0});if(p&&p.rings[0].length<=3&&(p=null),n===`EnvelopeAggregate`)d.aggregateGeometries={...p?o(p):X(u),spatialReference:c},d.outStatisticFieldName=r||`extent`;else if(n===`CentroidAggregate`){let[e,t]=p?i(p):a(X(u));d.aggregateGeometries={x:e,y:t,spatialReference:c},d.outStatisticFieldName=r||`centroid`}else n===`ConvexHullAggregate`&&(d.aggregateGeometries=p&&{...p,spatialReference:c},d.outStatisticFieldName=r||`convexHull`);return d}_getStatisticValue(e,t,n,r){let{onStatisticField:i,statisticType:a}=e,o=null;return o=n?.has(i)?n.get(i):E(this.fieldsIndex.get(i))||this._isAnyDateField(i)?N({values:t,returnDistinct:r}):P({values:r?[...new Set(t)]:t,minValue:null,maxValue:null,useSampleStdDev:!0}),n&&n.set(i,o),o[a===`var`?`variance`:a]}_getPercentileValue(e,t){let{onStatisticField:n,statisticParameters:r,statisticType:i}=e,{value:a,orderBy:o}=r,s={value:a,orderBy:o,fieldType:this.fieldsIndex.get(n)?.type,isDiscrete:i===`percentile_disc`};return V(t,s)}_getAttributeValues(e,t,n,r){if(r.has(t))return r.get(t);let i=this.fieldsIndex.get(t),a=n.map(n=>e.getFieldValue(n,t,i));return r.set(t,a),a}_calculateUniqueValues(e,t,n){let r={},i=t.length;for(let a=0;a<i;a++){let i=t[a],o=[];for(let t of e)o.push(t[a]);let s=o.join(`,`);r[s]==null?r[s]={count:1,data:o,items:[i],itemPositions:[a]}:(n||r[s].count++,r[s].items.push(i),r[s].itemPositions.push(a))}return r}async _getDataValues(e,t,i=!0){let a=new g(this.query,this.featureAdapter,this.fieldsIndex),{valueExpression:o,scale:s,timeZone:c}=e,l=r.fromJSON(this.query.outSR||this.spatialReference);return o?a.getExpressionValues(t,o,{viewingMode:`map`,scale:s,spatialReference:l},{geometryType:this.geometryType,hasZ:this.hasZ,hasM:this.hasM},c):a.getDataValues(t,n(e),i)}_calculateHistogramBins(e,t,n){if(t.min==null&&t.max==null)return[];let r=t.intervals,i=t.min??0,a=t.max??0,o=r.map(([e,t])=>({minValue:e,maxValue:t,count:0,items:[]}));for(let t=0;t<e.length;t++){let s=e[t],c=n[t];if(s!=null&&s>=i&&s<=a){let e=H(r,s);e>-1&&(o[e].count++,o[e].items.push(c))}}return o}async createQueryBinsResponse(e){let t=e.bin?.splitBy;if(!t)return this._createBinsResponse(e);let{value:n,outAlias:r,valueType:i}=t,a=[],o=[{name:r??n,alias:r??n,type:i??`esriFieldTypeString`},{name:`bin`,alias:`bin`,type:`esriFieldTypeInteger`}],s=new g(e,this.featureAdapter,this.fieldsIndex),c=new Map,l=[...this.items];this._sortFeatures(l,[n],(e,t,n)=>s.getFieldValue(e,t,n));let u=this._getAttributeValues(s,n,l,c),d=this._calculateUniqueValues([u],l,s.returnDistinctValues);for(let t in d){let{items:i}=d[t],s=await this._createBinsResponse(e,i);if(a.push(...s.features.map(e=>({...e,attributes:{...e.attributes,[r??n]:t}}))),s.fields)for(let e of s.fields)o.some(t=>t.name===e.name)||o.push(e)}return{fields:o,features:a}}async _createBinsResponse(e,t){let n=e.bin;switch(t??=this.items,n.type){case`autoIntervalBin`:return this._createAutoIntervalBinsResponse(O.fromJSON(n),e,t);case`dateBin`:return this._createDateBinsResponse(k.fromJSON(n),e,t);case`fixedBoundariesBin`:return this._createFixedBoundariesBinsResponse(j.fromJSON(n),e,t);case`fixedIntervalBin`:return this._createFixedIntervalBinsResponse(M.fromJSON(n),e,t)}}async _createAutoIntervalBinsResponse(e,t,n){let{field:r,normalizationField:i,numBins:a,normalizationType:o,normalizationTotal:s,start:c,end:l}=e,u=await this._getDataValues({field:e.field||e.expression,normalizationField:e.normalizationField,normalizationType:e.normalizationType,normalizationTotal:e.normalizationTotal,timeZone:t.outTimeReference?.ianaTimeZone},n),d=U(u,{field:r,normalizationField:i,normalizationType:o,normalizationTotal:s,numBins:a,minValue:b(o?e.normalizationMinValue:c,!1),maxValue:b(o?e.normalizationMaxValue:l,!1)}),f=this._calculateHistogramBins(u,d,n);return this._createFeaturesFromHistogramBins(f,t)}async _createDateBinsResponse(e,t,n){let{field:r,interval:i,start:a,end:o,snapToData:s,returnFullIntervalBin:c,offset:l,firstDayOfWeek:u}=e,d=i.unit,f=await this._getDataValues({field:r||e.expression,timeZone:t.outTimeReference?.ianaTimeZone},n),p=D(this.fieldsIndex.get(r)),m=A.toJSON(d),h=f.filter(Boolean).sort((e,t)=>e-t),g=a==null?h[0]:b(a,p),_=o==null?h[h.length-1]:b(o,p),v=[];if(g!=null&&_!=null){let e={zone:t.outTimeReference?.ianaTimeZone??K},n={[l?.unit?A.toJSON(l.unit):`milliseconds`]:l?.value||0},r=q.fromMillis(g,e).minus(n),a=q.fromMillis(_,e).minus(n),o=typeof u==`number`&&u>=1&&u<=7?u:7,d=(e,t)=>{let n=(e.weekday-t+7)%7;return e.minus({days:n}).startOf(`day`)},f=(e,t)=>d(e,t).plus({days:7});if(s===`last`){let e=m===`week`?f(a,o):a;for(;e>r;){let t=e.minus({[m]:i.value});if(t<r){v.unshift([c?t.plus(n).toMillis():r.plus(n).toMillis(),e.plus(n).toMillis()]);break}v.unshift([t.plus(n).toMillis(),e.plus(n).toMillis()]),e=t}}else{let e=s===`first`?r:m===`week`?d(r,o):r.startOf(m);for(;e<=a;){let t=e.plus({[m]:i.value});if(t>a){v.push([e.plus(n).toMillis(),c?t.plus(n).toMillis():a.plus(n).toMillis()]);break}v.push([e.plus(n).toMillis(),t.plus(n).toMillis()]),e=t}}}let y=this._calculateHistogramBins(f,{intervals:v,min:g,max:_},n);return this._createFeaturesFromHistogramBins(y,t)}async _createFixedBoundariesBinsResponse(e,t,n){let{field:r}=e,i=await this._getDataValues({field:r||e.expression,timeZone:t.outTimeReference?.ianaTimeZone},n),a=D(this.fieldsIndex.get(r)),o=e.boundaries.map(e=>b(e,a)).sort((e,t)=>e-t),s=[];for(let e=0;e<o.length-1;e++)s.push([o[e],o[e+1]]);let c={intervals:s,min:o.at(0),max:o.at(-1)},l=this._calculateHistogramBins(i,c,n);return this._createFeaturesFromHistogramBins(l,t)}async _createFixedIntervalBinsResponse(e,t,n){let{field:r,interval:i,normalizationType:a,start:o,end:s}=e,c=await this._getDataValues({field:r||e.expression,normalizationField:e.normalizationField,normalizationType:a,normalizationTotal:e.normalizationTotal,timeZone:t.outTimeReference?.ianaTimeZone},n),l=D(this.fieldsIndex.get(r)),u=U(c,{field:r,classificationMethod:`defined-interval`,definedInterval:i,minValue:b(a?e.normalizationMinValue:o,l),maxValue:b(a?e.normalizationMaxValue:s,l)},!0),d=this._calculateHistogramBins(c,u,n);return this._createFeaturesFromHistogramBins(d,t)}async _createFeaturesFromHistogramBins(e,t){let{upperBoundaryAlias:n,lowerBoundaryAlias:r}=t,i=r||`lowerBoundary`,a=n||`upperBoundary`,o=[],s=[{name:i,alias:i,type:`esriFieldTypeDouble`},{name:a,alias:a,type:`esriFieldTypeDouble`}],c=t.bin?.stackBy?.value,l=t.bin?.stackBy?.outAlias;c&&s.push({name:`bin`,alias:`bin`,type:`esriFieldTypeInteger`},{name:l??c,alias:l??c,type:`esriFieldTypeString`});let u=0,d=t.bin.type===`dateBin`,f=t.outTimeReference?.ianaTimeZone;for(let n of e){let{minValue:e,maxValue:r,items:p}=n,m={attributes:{}};m.attributes[i]=d&&f&&e!=null?q.fromMillis(e,{zone:f}).toISO():e,t.bin.hideUpperBound||(m.attributes[a]=d&&f&&r!=null?q.fromMillis(r,{zone:f}).toISO():r),t.returnAggIds&&(m.aggregateIds=p.map(e=>this.featureAdapter.getObjectId(e)).filter(e=>e!=null));let h;if(c?(h=await this._createStatisticsQueryResponse({...t,groupByFieldsForStatistics:[c],orderByFields:[c]},p),m.attributes.bin=++u,t.bin.jsonStyle===`flat`?o.push(...h.features.map(({attributes:{EXPR_1:e,...t},...n})=>({...n,attributes:l??e?{...t,[l??e]:e,...m.attributes}:{...t,...m.attributes}}))):(m.stackedAttributes=h.features.map(({attributes:{EXPR_1:e,...t}})=>l??e?{...t,[l??e]:e}:t),o.push(m))):(t.bin?.splitBy&&(m.attributes.bin=++u),h=await this._createStatisticsQueryResponse(t,p,m),o.push(m)),h.fields)for(let e of h.fields)s.some(t=>t.name===e.name)||s.push(e)}return t.binOrder===`desc`&&o.reverse(),{fields:s,features:o}}}function X(e){let t=s(e[0]);for(let n of e.slice(1))c(t,s(n));return t}function Z(e,t,n,r){let i=r.x-n.x,a=r.y-n.y,o=t.x-n.x,s=t.y-n.y,c=i*i+a*a;if(c===0)return!1;let l=o*i+s*a,u=Math.min(1,Math.max(0,l/c));return e.x=n.x+i*u,e.y=n.y+a*u,!0}class Q{constructor(e,t){this.coords=e,this.coordsIndex=t}get x(){return this.coords[this.coordsIndex]}get y(){return this.coords[this.coordsIndex+1]}get z(){return this.coords[this.coordsIndex+2]}}const ee=[1];function $(e,t){let n=e.split(` `),r=n[0],i=t.get(r),a=n[1]?n[1].toLowerCase()===`desc`:!1;return{compare:G(i?.type,a,`case-insensitive`),fieldOrExpression:r,fieldInfo:i}}export{Y as QueryEngineResult};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
- import{generalizeOptimizedGeometry as e,quantizeOptimizedGeometry as t,convertToGeometry as n,convertToPoint as r}from"../featureConversionUtils.js";function i(e,n,i,a=e.hasZ,o=e.hasM){if(n==null)return null;let s=e.hasZ&&a,c=e.hasM&&o;if(i){let e=t(n,`esriGeometryPoint`,i,a,o);return r(e,s,c)}return r(n,s,c)}function a(r,i,a,o,s,c){if(i==null)return null;let l=`coords`in i?i:i.geometry;if(l==null)return null;let{hasZ:u,hasM:d}=l,f=u&&(s??=u),p=d&&(c??=d);if(a){let i=e(l,r,a,s,c);return o&&(i=t(i,r,o)),n(i,r,f,p)}if(o){let e=t(l,r,o,s,c);return n(e,r,f,p)}return n(l,r,f,p)}function o(e){return!e||!(s in e)?e:JSON.parse(JSON.stringify(e,c))}const s=`_geVersion`,c=(e,t)=>e===s?void 0:t;export{o as cleanFromGeometryEngine,a as getGeometry,i as transformCentroid};
2
+ import{generalizeOptimizedGeometry as e,quantizeOptimizedGeometry as t,convertToGeometry as n,convertToPoint as r}from"../featureConversionUtils.js";function i(e,n,i,a=e.hasZ,o=e.hasM){if(n==null)return null;let s=e.hasZ&&a,c=e.hasM&&o;if(i){let e=t(n,`esriGeometryPoint`,i,a,o);return r(e,s,c)}return r(n,s,c)}function a(r,i,a,o,s,c){if(i==null)return null;let l=`coords`in i?i:i.geometry;if(l==null)return null;let{hasZ:u,hasM:d}=l,f=u&&(s??=u),p=d&&(c??=d);if(a){let i=e(l,r,a,s,c);return o&&(i=t(i,r,o)),n(i,r,f,p)}if(o){let e=t(l,r,o,s,c);return n(e,r,f,p)}return n(l,r,f,p)}export{a as getGeometry,i as transformCentroid};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
- import{isSome as e}from"../../../core/arrayUtils.js";import{initializeProjection as t,projectMany as n}from"../../../geometry/projectionUtils.js";import{isPoint as r,isExtent as i,isPolygon as a,isPolyline as o,isMultipoint as s}from"../../../geometry/support/jsonTypeUtils.js";import{isValid as c,equals as l,isWebMercator as u}from"../../../geometry/support/spatialReferenceUtils.js";import{canProject as d,lngLatToXY as f,xyToLngLat as p}from"../../../geometry/support/webMercatorUtils.js";const m=[0,0];function h(e,t){let n=u(e)?f:p;if(r(t)){let e={x:0,y:0};return[e.x,e.y]=n(t.x,t.y,m),t.z!=null&&(e.z=t.z),t.m!=null&&(e.m=t.m),e}if(i(t)){let e={xmin:0,ymin:0,xmax:0,ymax:0};return[e.xmin,e.ymin]=n(t.xmin,t.ymin,m),[e.xmax,e.ymax]=n(t.xmax,t.ymax,m),t.hasZ&&(e.zmin=t.zmin,e.zmax=t.zmax,e.hasZ=!0),t.hasM&&(e.mmin=t.mmin,e.mmax=t.mmax,e.hasM=!0),e}if(a(t))return{rings:g(t.rings,n),hasM:t.hasM,hasZ:t.hasZ};if(o(t))return{paths:g(t.paths,n),hasM:t.hasM,hasZ:t.hasZ};if(s(t))return{points:_(t.points,n),hasM:t.hasM,hasZ:t.hasZ};throw Error()}function g(e,t){let n=[];for(let r of e)n.push(_(r,t));return n}function _(e,t){let n=[];for(let r of e){let e=t(r[0],r[1],[0,0]);n.push(e),r.length>2&&e.push(r[2]),r.length>3&&e.push(r[3])}return n}async function v(n,r){if(!n||!r)return;let i=Array.isArray(n)?n.map(e=>e.geometry==null?null:e.geometry.spatialReference).filter(e):[n];await t(i.map(e=>({source:e,dest:r})))}function y(e,t,r,i){if(!e)return null;if(r||(r=t,t=e.spatialReference),!c(t)||!c(r)||l(t,r))return e;if(d(t,r)){let t=h(r,e);return t.spatialReference=r,t}return n([e],t,r,i)[0]}class b{constructor(){this._jobs=[],this._timer=null,this._process=this._process.bind(this)}async push(e,t,n,r){if(!e?.length||!t||!n||l(t,n))return e;let i={geometries:e,inSpatialReference:t,outSpatialReference:n,options:r,resolve:Promise.withResolvers()};return this._jobs.push(i),this._timer??=setTimeout(this._process,10),i.resolve.promise}_process(){this._timer=null;let e=this._jobs.shift();if(!e)return;let{geometries:t,inSpatialReference:r,outSpatialReference:i,resolve:a,options:o}=e,s=t.filter(e=>e!=null),c;c=d(r,i)&&o?.extendedParams==null?s.map(e=>h(i,e)):n(s,r,i,o);let l=0,u=t.map(e=>e==null?null:c[l++]);a.resolve(u),this._jobs.length>0&&(this._timer=setTimeout(this._process,10))}}const x=new b;function S(e,t,n,r){return x.push(e,t,n,r)}export{v as checkProjectionSupport,y as project,S as projectMany};
2
+ import{isSome as e}from"../../../core/arrayUtils.js";import{initializeProjection as t,projectMany as n}from"../../../geometry/projectionUtils.js";import{isPoint as r,isExtent as i,isPolygon as a,isPolyline as o,isMultipoint as s}from"../../../geometry/support/jsonTypeUtils.js";import{isValid as c,equals as l,isWebMercator as u}from"../../../geometry/support/spatialReferenceUtils.js";import{canProject as d,lngLatToXY as f,xyToLngLat as p}from"../../../geometry/support/webMercatorUtils.js";const m=[0,0];function h(e,t){let n=u(e)?f:p;if(r(t)){let e={x:0,y:0};return[e.x,e.y]=n(t.x,t.y,m),t.z!=null&&(e.z=t.z),t.m!=null&&(e.m=t.m),e}if(i(t)){let e={xmin:0,ymin:0,xmax:0,ymax:0};return[e.xmin,e.ymin]=n(t.xmin,t.ymin,m),[e.xmax,e.ymax]=n(t.xmax,t.ymax,m),t.hasZ&&(e.zmin=t.zmin,e.zmax=t.zmax,e.hasZ=!0),t.hasM&&(e.mmin=t.mmin,e.mmax=t.mmax,e.hasM=!0),e}if(a(t))return{rings:g(t.rings,n),hasM:t.hasM,hasZ:t.hasZ};if(o(t))return{paths:g(t.paths,n),hasM:t.hasM,hasZ:t.hasZ};if(s(t))return{points:_(t.points,n),hasM:t.hasM,hasZ:t.hasZ};throw Error()}function g(e,t){let n=[];for(let r of e)n.push(_(r,t));return n}function _(e,t){let n=[];for(let r of e){let e=t(r[0],r[1],[0,0]);n.push(e),r.length>2&&e.push(r[2]),r.length>3&&e.push(r[3])}return n}async function v(n,r){if(!n||!r)return;let i=Array.isArray(n)?n.map(e=>e.geometry==null?null:e.geometry.spatialReference).filter(e):[n];await t(i.map(e=>({source:e,dest:r})))}function y(e,t,r,i){if(!e)return null;if(r||(r=t,t=e.spatialReference),!c(t)||!c(r)||l(t,r))return e;if(d(t,r)){let t=h(r,e);return t.spatialReference=r,t}let[a]=n([e],t,r,i);return a}class b{constructor(){this._jobs=[],this._timer=null,this._process=this._process.bind(this)}async push(e,t,n,r){if(!e?.length||!t||!n||l(t,n))return e;let i={geometries:e,inSpatialReference:t,outSpatialReference:n,options:r,resolve:Promise.withResolvers()};return this._jobs.push(i),this._timer??=setTimeout(this._process,10),i.resolve.promise}_process(){this._timer=null;let e=this._jobs.shift();if(!e)return;let{geometries:t,inSpatialReference:r,outSpatialReference:i,resolve:a,options:o}=e,s=t.filter(e=>e!=null),c;c=d(r,i)&&o?.extendedParams==null?s.map(e=>h(i,e)):n(s,r,i,o);let l=0,u=t.map(e=>e==null?null:c[l++]);a.resolve(u),this._jobs.length>0&&(this._timer=setTimeout(this._process,10))}}const x=new b;function S(e,t,n,r){return x.push(e,t,n,r)}export{v as checkProjectionSupport,y as project,S as projectMany};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import t from"../../../config.js";import n from"../../../request.js";import{isSome as r,remove as i}from"../../../core/arrayUtils.js";import a from"../../../core/Error.js";import has from"../../../core/has.js";import{JSONMap as o}from"../../../core/jsonMap.js";import{Loadable as s}from"../../../core/Loadable.js";import c from"../../../core/Logger.js";import{setDeepValue as l}from"../../../core/object.js";import{debounce as u,after as d,throwIfAbortError as f}from"../../../core/promiseUtils.js";import{watch as p}from"../../../core/reactiveUtils.js";import{join as m}from"../../../core/urlUtils.js";import{generateBracedUUID as h}from"../../../core/uuid.js";import{property as g,subclass as _}from"../../../core/accessorSupport/decorators.js";import v from"../../../geometry/Extent.js";import y from"../../../geometry/SpatialReference.js";import b from"../../../geometry/support/MeshGeoreferencedVertexSpace.js";import{isRelativeVertexSpace as x}from"../../../geometry/support/meshVertexSpaceUtils.js";import{isOriginalExternal as S}from"../../../geometry/support/meshUtils/External.js";import{createFeatureEditResult as C,getFeatureJSON as w,getFeatureIds as T,getAttachmentEditsJSON as E,isProtectedOrPrivateVersionError as D,unpackEditResultData as O,createEditedFeatures as k}from"../applyEditsUtils.js";import{createDrawingInfo as A}from"./support/clientSideDefaults.js";import j from"./support/QueryTask.js";import{isHostedAgolService as M}from"../../support/arcgisLayerUrl.js";import{ensureLayerCredential as N}from"../../support/featureLayerUtils.js";import{getAssetMapTable as P}from"../../support/infoFor3D.js";import{executeQueryJSON as F}from"../../../rest/query/executeQueryJSON.js";import{unapplyEditsZUnitScaling as I}from"../../../rest/query/operations/editsZScale.js";import L from"../../../rest/support/Query.js";import R from"../../../time/TimeExtent.js";import{isSafeToEditVersion as z,isVersionInEditSession as B,isHistoricVersion as V,currentSessionId as H}from"../../../versionManagement/support/versionManagementUtils.js";const U=new o({originalAndCurrentFeatures:`original-and-current-features`,none:`none`}),W=new o({Started:`published`,Publishing:`publishing`,Stopped:`unavailable`});let G=class extends s{constructor(e){super(e),this.type=`feature-layer`,this.supportedSourceTypes=new Set([`Feature Layer`,`Oriented Imagery Layer`,`Table`,`Catalog Layer`,`Annotation Layer`,`Dimension Layer`]),this.refresh=u(async()=>{await this.load();let e=this.sourceJSON.editingInfo?.lastEditDate;if(e==null)return{dataChanged:!0,updates:{}};try{await this._fetchService(null)}catch{return{dataChanged:!0,updates:{}}}let t=e!==this.sourceJSON.editingInfo?.lastEditDate;return{dataChanged:t,updates:t?{editingInfo:this.sourceJSON.editingInfo,extent:this.sourceJSON.extent}:null}}),this._ongoingAssetUploads=new Map}load(e){let t=this.layer.sourceJSON,n=this._fetchService(t,{...e}).then(()=>this.layer.setUserPrivileges(this.sourceJSON.serviceItemId,e)).then(()=>this._ensureLatestMetadata(e));return this.addResolvingPromise(n),Promise.resolve(this)}async reload(e){let t=this.layer.userHasUpdateItemPrivileges&&this.sourceJSON.cacheMaxAge>0;await this._fetchService(null,{...e,cacheBust:t})}initialize(){this.addHandles([p(()=>{let e=this.layer;return e&&`lastEditsEventDate`in e?e.lastEditsEventDate:null},e=>this._handleLastEditsEventChange(e))])}destroy(){this._removeEditInterceptor()}get queryTask(){let{capabilities:e,parsedUrl:t,gdbVersion:n,spatialReference:r,fieldsIndex:i,uniqueIdFields:a}=this.layer,o=`infoFor3D`in this.layer?this.layer.infoFor3D:null,s=`dynamicDataSource`in this.layer?this.layer.dynamicDataSource:null,c=has(`featurelayer-pbf`)&&e?.query.supportsFormatPBF&&o==null,l=c&&e?.query.supportsFormatPBFWithCurves,u=e?.operations?.supportsQueryAttachments??!1,d=e?.query?.relativeTimeBinWindow??0,f=t.path;return new j({dynamicDataSource:s,fieldsIndex:i,gdbVersion:n,infoFor3D:o,pbfSupported:c,pbfSupportedWithCurves:l,queryAttachmentsSupported:u,relativeTimeBinWindow:d,sourceSpatialReference:r,uniqueIdFields:a,url:f})}async addAttachment(e,t,r){await this.load();let{layer:i}=this;await N(i,`editing`);let a=e.attributes[i.objectIdField],o=i.parsedUrl.path+`/`+a+`/addAttachment`,s=this._getLayerRequestOptions({query:r}),c=this._getFormDataForAttachment(t,s.query);try{let e=await n(o,{body:c});return C(e.data.addAttachmentResult)}catch(e){throw this._createAttachmentErrorResult(a,e)}}async updateAttachment(e,t,r,i){await this.load();let{layer:a}=this;await N(a,`editing`);let o=e.attributes[a.objectIdField],s=a.parsedUrl.path+`/`+o+`/updateAttachment`,c=this._getLayerRequestOptions({query:{attachmentId:t,...i}}),l=this._getFormDataForAttachment(r,c.query);try{let e=await n(s,{body:l});return C(e.data.updateAttachmentResult)}catch(e){throw this._createAttachmentErrorResult(o,e)}}async applyEdits(e,t){await this.load();let{layer:i}=this;await N(i,`editing`);let o=`infoFor3D`in i?i.infoFor3D:null,s=o!=null,c=s||(t?.globalIdUsed??!1),l=s?await this._uploadMeshesAndGetAssetMapEditsJSON(e):null,u=e.addFeatures?.map(e=>w(this.layer,e,o))??[],d=(await Promise.all(u)).filter(r),f=e.updateFeatures?.map(e=>w(this.layer,e,o))??[],p=(await Promise.all(f)).filter(r),m=T(this.layer,e.deleteFeatures,c);I(d,p,i.spatialReference);let h=await E(this.layer,e),g=i.capabilities.editing.supportsAsyncApplyEdits&&s,_=t?.gdbVersion||i.gdbVersion,v={gdbVersion:_,rollbackOnFailure:t?.rollbackOnFailureEnabled,useGlobalIds:c,returnEditMoment:t?.returnEditMoment,trueCurveClient:t?.editsRespectTrueCurves,usePreviousEditMoment:t?.usePreviousEditMoment,async:g};await z(this.layer.url,_,!0);let y=B(this.layer.url,_||null);if(await V(i.url,_,i.historicMoment))throw new a(`feature-layer-source:historic-version`,`Editing a historic version is not allowed`);t?.returnServiceEditsOption?(v.edits=JSON.stringify([{id:i.layerId,adds:d.length?d:null,updates:p.length?p:null,deletes:m.length?m:null,attachments:h,assetMaps:l}]),v.returnServiceEditsOption=U.toJSON(t?.returnServiceEditsOption),v.returnServiceEditsInSourceSR=t?.returnServiceEditsInSourceSR):(v.adds=d.length?JSON.stringify(d):null,v.updates=p.length?JSON.stringify(p):null,v.deletes=m.length?c?JSON.stringify(m):m.join(`,`):null,v.attachments=h&&JSON.stringify(h),v.assetMaps=l==null?void 0:JSON.stringify(l));let b=this._getLayerRequestOptions({method:`post`,query:v});y&&(b.authMode=`immediate`,b.query.returnEditMoment=!0,b.query.sessionId=H);let x=t?.returnServiceEditsOption?i.url:i.parsedUrl.path,S;try{S=g?await this._asyncApplyEdits(x+`/applyEdits`,b):await n(x+`/applyEdits`,b)}catch(e){if(D(e))b.authMode=`immediate`,S=g?await this._asyncApplyEdits(x+`/applyEdits`,b):await n(x+`/applyEdits`,b);else throw e}return this._createEditsResult(S)}async deleteAttachments(e,t,r){await this.load();let{layer:i}=this;await N(i,`editing`);let a=e.attributes[i.objectIdField],o=i.parsedUrl.path+`/`+a+`/deleteAttachments`;try{return(await n(o,this._getLayerRequestOptions({query:{attachmentIds:t.join(`,`),...r},method:`post`}))).data.deleteAttachmentResults.map(C)}catch(e){throw this._createAttachmentErrorResult(a,e)}}fetchRecomputedExtents(e={}){let t=e.signal;return this.load({signal:t}).then(async()=>{let t=this._getLayerRequestOptions({...e,query:{returnUpdates:!0}}),{layerId:r,url:i}=this.layer,{data:a}=await n(`${i}/${r}`,t),{id:o,extent:s,fullExtent:c,timeExtent:l}=a,u=s||c;return{id:o,fullExtent:u&&v.fromJSON(u),timeExtent:l&&R.fromJSON({start:l[0],end:l[1]})}})}async queryAttachments(e,t={}){await this.load();let n=this._getLayerRequestOptions(t);return this.queryTask.executeAttachmentQuery(e,n)}async queryFeatures(e,t){await this.load();let n=await this.queryTask.execute(e,{...t,query:this._createRequestQueryOptions(t)});if(e.outStatistics?.length&&n.features.length){let t=new Map;if(n.features.forEach(n=>{let r=n.attributes;e.outStatistics?.forEach(({outStatisticFieldName:e})=>{if(e){let n=e.toLowerCase();n&&n in r&&e!==n&&(r[e]=r[n],delete r[n],t.set(n,e))}})}),n.fields!=null)for(let e of n.fields){let n=t.get(e.name.toLowerCase());n!=null&&(e.name=n)}}return n}async queryFeaturesJSON(e,t){return await this.load(),this.queryTask.executeJSON(e,{...t,query:this._createRequestQueryOptions(t)})}async queryObjectIds(e,t){return await this.load(),this.queryTask.executeForIds(e,{...t,query:this._createRequestQueryOptions(t)})}async queryFeatureCount(e,t){return await this.load(),this.queryTask.executeForCount(e,{...t,query:this._createRequestQueryOptions(t)})}async queryExtent(e,t){return await this.load(),this.queryTask.executeForExtent(e,{...t,query:this._createRequestQueryOptions(t)})}async queryRelatedFeatures(e,t){return await this.load(),this.queryTask.executeRelationshipQuery(e,{...t,query:this._createRequestQueryOptions(t)})}async queryRelatedFeaturesCount(e,t){return await this.load(),this.queryTask.executeRelationshipQueryForCount(e,{...t,query:this._createRequestQueryOptions(t)})}async queryPivot(e,t){return await this.load(),this.queryTask.executePivotQuery(e,{...t,query:this._createRequestQueryOptions(t)})}async queryTopFeatures(e,t){return await this.load(),this.queryTask.executeTopFeaturesQuery(e,{...t,query:this._createRequestQueryOptions(t)})}async queryAttributeBins(e,t){return await this.load(),this.queryTask.executeAttributeBinsQuery(e,{...t,query:this._createRequestQueryOptions(t)})}async queryTopObjectIds(e,t){return await this.load(),this.queryTask.executeForTopIds(e,{...t,query:this._createRequestQueryOptions(t)})}async queryTopExtents(e,t){return await this.load(),this.queryTask.executeForTopExtents(e,{...t,query:this._createRequestQueryOptions(t)})}async queryTopCount(e,t){return await this.load(),this.queryTask.executeForTopCount(e,{...t,query:this._createRequestQueryOptions(t)})}async fetchPublishingStatus(){if(!M(this.layer.url))return`unavailable`;let e=m(this.layer.url,`status`),t=await n(e,{query:{f:`json`}});return W.fromJSON(t.data.status)}async uploadAssets(e,t){let{uploadAssets:n}=await import(`./support/uploadAssets.js`);return n(e,{layer:this.layer,ongoingUploads:this._ongoingAssetUploads},t)}_handleLastEditsEventChange(e){let t=this.layer;if(e==null||!(`capabilities`in t)||!(`effectiveCapabilities`in t)||t.capabilities?.operations?.supportsEditing||!t.effectiveCapabilities?.operations?.supportsEditing)return;let n=t.url;if(n==null)return;`layerId`in t&&(n=m(n,t.layerId.toString()));let r=this._getOrCreateEditInterceptor(n);r.before=t=>{let n=t.requestOptions.method??`auto`;if(n===`auto`||n===`head`){let n=t.requestOptions.query??{};n._ts=e.getTime(),t.requestOptions.query=n}}}_getOrCreateEditInterceptor(e){return this._editInterceptor??(this._editInterceptor={urls:e},t.request.internalInterceptors.push(this._editInterceptor)),this._editInterceptor}_removeEditInterceptor(){this._editInterceptor!=null&&(i(t.request.internalInterceptors,this._editInterceptor),this._editInterceptor=null)}async _asyncApplyEdits(e,t){let r=(await n(e,t)).data.statusUrl;for(;;){let e=(await n(r,{query:{f:`json`},responseType:`json`})).data;switch(e.status){case`Completed`:return n(e.resultUrl,{query:{f:`json`},responseType:`json`});case`CompletedWithErrors`:throw new a(`async-applyEdits-failed`,`asynchronous applyEdits call failed.`);case`Failed ImportChanges`:case`InProgress`:case`Pending`:case`ExportAttachments`:case`ExportChanges`:case`ExportingData`:case`ExportingSnapshot`:case`ImportAttachments`:case`ProvisioningReplica`:case`UnRegisteringReplica`:break;default:throw new a(`async-applyEdits-failed`,`asynchronous applyEdits call failed (undefined response status)`)}await d(K)}}_createRequestQueryOptions(e){let t={...this.layer.customParameters,token:this.layer.apiKey,...e?.query};return this.layer.datesInUnknownTimezone&&(t.timeReferenceUnknownClient=!0),t}async _fetchService(e,t){if(!e){let r={};has(`featurelayer-advanced-symbols`)&&(r.returnAdvancedSymbols=!0),t?.cacheBust&&(r._ts=Date.now());let{data:i}=await n(this.layer.parsedUrl.path,this._getLayerRequestOptions({query:r,signal:t?.signal}));e=i}this.layer.applyPreferredHost(e),this.sourceJSON=await this._patchServiceJSON(e,t?.signal);let r=e.type;if(!this.supportedSourceTypes.has(r))throw new a(`feature-layer-source:unsupported-type`,`Source type "${r}" is not supported`)}async _patchServiceJSON(e,t){if(e.type!==`Table`&&e.geometryType&&!e?.drawingInfo?.renderer&&!e.defaultSymbol){let t=A(e.geometryType).renderer;l(`drawingInfo.renderer`,t,e)}if(e.geometryType===`esriGeometryMultiPatch`&&e.infoFor3D&&(e.geometryType=`mesh`),e.extent==null)try{let{data:r}=await n(this.layer.url,this._getLayerRequestOptions({signal:t}));r.spatialReference&&(e.extent={xmin:0,ymin:0,xmax:0,ymax:0,spatialReference:r.spatialReference})}catch(e){f(e)}return e}async _ensureLatestMetadata(e){if(this.layer.userHasUpdateItemPrivileges&&this.sourceJSON.cacheMaxAge>0)return this._fetchService(null,{...e,cacheBust:!0})}async _uploadMeshesAndGetAssetMapEditsJSON(e){let{addAssetFeatures:t}=e;if(!t?.length||await this._areAllAssetsAlreadyMapped(t))return null;let n=e.addFeatures.filter(e=>e.geometry);if(t.length!==n.length+e.updateFeatures.length)throw new a(`feature-layer-source:unsupported-mesh-edits`,`Mixing attribute only edits with mesh geometry edits is not currently supported`);let r=[],i=new Map;for(let e of t){let{geometry:t}=e,{vertexSpace:n}=t;if(x(n))r.push(t);else{let n=t.origin,{convertMeshVertexSpace:a}=await import(`../../../geometry/support/meshUtils/convertMeshVertexSpace.js`),o=await a(t,new b({origin:[n.x,n.y,n.z??0]}));i.set(o,t),e.geometry=o,r.push(o)}}await this.uploadAssets(r);for(let[e,t]of i)t.addExternalSources(e.metadata.externalSources.items);return{adds:this._getAssetMapEditsJSON(t),updates:[],deletes:[]}}_getAssetMapEditsJSON(e){let t=[],n=this.layer.globalIdField,r=this.layer.parsedUrl;for(let i of e){let{metadata:e}=i.geometry,a=e.getExternalSourcesOnService(r),o=i.getAttribute(n);if(a.length===0){c.getLogger(this).error(`Skipping feature ${o}. The mesh it is associated with has not been uploaded to the service and cannot be mapped to it.`);continue}let{source:s}=a.find(S)??a[0];for(let e of s.assets)e.parts.length===1?t.push({globalId:h(),parentGlobalId:o,assetName:e.assetName,assetHash:e.parts[0].partHash,flags:[]}):c.getLogger(this).error(`Skipping asset ${e.assetName}. It does not have exactly one part, so we cannot map it to a feature.`)}return t}_createEditsResult(e){let t=e.data,{layerId:n}=this.layer,r=[],i=null;if(Array.isArray(t))for(let e of t)r.push({id:e.id,editedFeatures:e.editedFeatures}),e.id===n&&(i={addResults:e.addResults??[],updateResults:e.updateResults??[],deleteResults:e.deleteResults??[],attachments:e.attachments,editMoment:e.editMoment});else i=t;let a=O(i);if(r.length>0){a.editedFeatureResults=[];for(let e of r){let{editedFeatures:t}=e,n=t?.spatialReference?new y(t.spatialReference):null;a.editedFeatureResults.push({layerId:e.id,editedFeatures:k(t,n)})}}return a}_createAttachmentErrorResult(e,t){let n=t.details.messages?.[0]||t.message,r=t.details.httpStatus||t.details.messageCode;return{objectId:e,globalId:null,error:new a(`feature-layer-source:attachment-failure`,n,{code:r})}}_getFormDataForAttachment(e,t){let n=e instanceof FormData?e:e&&e.elements?new FormData(e):null;if(n)for(let e in t){let r=t[e];r!=null&&(n.set?n.set(e,r):n.append(e,r))}return n}_getLayerRequestOptions(e={}){let{layer:t,layer:{parsedUrl:n,gdbVersion:r}}=this;return{...e,query:{gdbVersion:r,layer:`dynamicDataSource`in t&&t.dynamicDataSource?JSON.stringify({source:t.dynamicDataSource}):void 0,...n.query,f:`json`,...this._createRequestQueryOptions(e)},responseType:`json`}}async _areAllAssetsAlreadyMapped(e){let{layer:t}=this,{globalIdField:n,parsedUrl:i}=t,a=`infoFor3D`in t?t.infoFor3D:null;if(a==null||n==null)return!1;let o=P(a);if(o==null)return!1;let s=m(i.path,`../${o.id}`),c=[];for(let t of e)if(t.geometry.metadata.getExternalSourcesOnService(i).length>0)c.push(t);else return!1;let l=c.map(e=>e.getAttribute(n)).filter(r);if(l.length===0)return!1;let{assetMapFieldRoles:{parentGlobalId:u,assetHash:d}}=a,f=new L({where:`${u} IN (${l.map(e=>`'${e}'`)})`,outFields:[d,u],returnGeometry:!1}),{features:p}=await F(s,f);return p.length!==0&&!c.some(e=>{let t=e.getAttribute(n);if(!t)return!0;let{metadata:r}=e.geometry,a=p.filter(e=>e.getAttribute(u)===t);if(a.length===0)return!0;let o=a.map(e=>e.getAttribute(d));return r.getExternalSourcesOnService(i).flatMap(({source:e})=>e.assets.flatMap(e=>e.parts.map(e=>e.partHash))).some(e=>o.every(t=>e!==t))})}};e([g()],G.prototype,`type`,void 0),e([g({constructOnly:!0})],G.prototype,`layer`,void 0),e([g({constructOnly:!0})],G.prototype,`supportedSourceTypes`,void 0),e([g({readOnly:!0})],G.prototype,`queryTask`,null),G=e([_(`esri.layers.graphics.sources.FeatureLayerSource`)],G);const K=1e3;export{G as default};
2
+ import{__decorate as e}from"tslib";import t from"../../../config.js";import n from"../../../request.js";import{isSome as r,remove as i}from"../../../core/arrayUtils.js";import a from"../../../core/Error.js";import has from"../../../core/has.js";import{JSONMap as o}from"../../../core/jsonMap.js";import{Loadable as s}from"../../../core/Loadable.js";import c from"../../../core/Logger.js";import{setDeepValue as l}from"../../../core/object.js";import{debounce as u,after as d,throwIfAbortError as f}from"../../../core/promiseUtils.js";import{watch as p}from"../../../core/reactiveUtils.js";import{join as m}from"../../../core/urlUtils.js";import{generateBracedUUID as h}from"../../../core/uuid.js";import{property as g,subclass as _}from"../../../core/accessorSupport/decorators.js";import v from"../../../geometry/Extent.js";import y from"../../../geometry/SpatialReference.js";import b from"../../../geometry/support/MeshGeoreferencedVertexSpace.js";import{isRelativeVertexSpace as x}from"../../../geometry/support/meshVertexSpaceUtils.js";import{isOriginalExternal as S}from"../../../geometry/support/meshUtils/External.js";import{createFeatureEditResult as C,getFeatureJSON as w,getFeatureIds as T,getAttachmentEditsJSON as E,isProtectedOrPrivateVersionError as D,unpackEditResultData as O,createEditedFeatures as k}from"../applyEditsUtils.js";import{createDrawingInfo as A}from"./support/clientSideDefaults.js";import j from"./support/QueryTask.js";import{isHostedAgolService as M}from"../../support/arcgisLayerUrl.js";import{ensureLayerCredential as N}from"../../support/featureLayerUtils.js";import{getAssetMapTable as P}from"../../support/infoFor3D.js";import{executeQueryJSON as F}from"../../../rest/query/executeQueryJSON.js";import{unapplyEditsZUnitScaling as I}from"../../../rest/query/operations/editsZScale.js";import L from"../../../rest/support/Query.js";import R from"../../../time/TimeExtent.js";import{isSafeToEditVersion as z,isVersionInEditSession as B,isHistoricVersion as V,currentSessionId as H}from"../../../versionManagement/support/versionManagementUtils.js";const U=new o({originalAndCurrentFeatures:`original-and-current-features`,none:`none`}),W=new o({Started:`published`,Publishing:`publishing`,Stopped:`unavailable`});let G=class extends s{constructor(e){super(e),this.type=`feature-layer`,this.supportedSourceTypes=new Set([`Feature Layer`,`Oriented Imagery Layer`,`Table`,`Catalog Layer`,`Annotation Layer`,`Dimension Layer`]),this.refresh=u(async()=>{await this.load();let e=this.sourceJSON.editingInfo?.lastEditDate;if(e==null)return{dataChanged:!0,updates:{}};try{await this._fetchService(null)}catch{return{dataChanged:!0,updates:{}}}let t=e!==this.sourceJSON.editingInfo?.lastEditDate;return{dataChanged:t,updates:t?{editingInfo:this.sourceJSON.editingInfo,extent:this.sourceJSON.extent}:null}}),this._ongoingAssetUploads=new Map}load(e){let t=this.layer.sourceJSON,n=this._fetchService(t,{...e}).then(()=>this.layer.setUserPrivileges(this.sourceJSON.serviceItemId,e)).then(()=>this._ensureLatestMetadata(e));return this.addResolvingPromise(n),Promise.resolve(this)}async reload(e){let t=this.layer.userHasUpdateItemPrivileges&&this.sourceJSON.cacheMaxAge>0;await this._fetchService(null,{...e,cacheBust:t})}initialize(){this.addHandles([p(()=>{let e=this.layer;return e&&`lastEditsEventDate`in e?e.lastEditsEventDate:null},e=>this._handleLastEditsEventChange(e))])}destroy(){this._removeEditInterceptor()}get queryTask(){let{capabilities:e,parsedUrl:t,gdbVersion:n,spatialReference:r,fieldsIndex:i,uniqueIdFields:a}=this.layer,o=`infoFor3D`in this.layer?this.layer.infoFor3D:null,s=`dynamicDataSource`in this.layer?this.layer.dynamicDataSource:null,c=has(`featurelayer-pbf`)&&e?.query.supportsFormatPBF&&o==null,l=c&&e?.query.supportsFormatPBFWithCurves,u=e?.operations?.supportsQueryAttachments??!1,d=e?.query?.relativeTimeBinWindow??0,f=t.path;return new j({dynamicDataSource:s,fieldsIndex:i,gdbVersion:n,infoFor3D:o,pbfSupported:c,pbfSupportedWithCurves:l,queryAttachmentsSupported:u,relativeTimeBinWindow:d,sourceSpatialReference:r,uniqueIdFields:a,url:f})}async addAttachment(e,t,r){await this.load();let{layer:i}=this;await N(i,`editing`);let a=e.attributes[i.objectIdField],o=i.parsedUrl.path+`/`+a+`/addAttachment`,s=this._getLayerRequestOptions({query:r}),c=this._getFormDataForAttachment(t,s.query);try{let e=await n(o,{body:c});return C(e.data.addAttachmentResult)}catch(e){throw this._createAttachmentErrorResult(a,e)}}async updateAttachment(e,t,r,i){await this.load();let{layer:a}=this;await N(a,`editing`);let o=e.attributes[a.objectIdField],s=a.parsedUrl.path+`/`+o+`/updateAttachment`,c=this._getLayerRequestOptions({query:{attachmentId:t,...i}}),l=this._getFormDataForAttachment(r,c.query);try{let e=await n(s,{body:l});return C(e.data.updateAttachmentResult)}catch(e){throw this._createAttachmentErrorResult(o,e)}}async applyEdits(e,t){await this.load();let{layer:i}=this;await N(i,`editing`);let o=`infoFor3D`in i?i.infoFor3D:null,s=o!=null,c=s||(t?.globalIdUsed??!1),l=s?await this._uploadMeshesAndGetAssetMapEditsJSON(e):null,u=e.addFeatures?.map(e=>w(this.layer,e,o))??[],d=(await Promise.all(u)).filter(r),f=e.updateFeatures?.map(e=>w(this.layer,e,o))??[],p=(await Promise.all(f)).filter(r),m=T(this.layer,e.deleteFeatures,c);I(d,p,i.spatialReference);let h=await E(this.layer,e),g=i.capabilities.editing.supportsAsyncApplyEdits&&s,_=t?.gdbVersion||i.gdbVersion,v={gdbVersion:_,rollbackOnFailure:t?.rollbackOnFailureEnabled,useGlobalIds:c,returnEditMoment:t?.returnEditMoment,trueCurveClient:t?.editsRespectTrueCurves,usePreviousEditMoment:t?.usePreviousEditMoment,async:g};await z(this.layer.url,_,!0);let y=B(this.layer.url,_||null);if(await V(i.url,_,i.historicMoment))throw new a(`feature-layer-source:historic-version`,`Editing a historic version is not allowed`);t?.returnServiceEditsOption?(v.edits=JSON.stringify([{id:i.layerId,adds:d.length?d:null,updates:p.length?p:null,deletes:m.length?m:null,attachments:h,assetMaps:l}]),v.returnServiceEditsOption=U.toJSON(t?.returnServiceEditsOption),v.returnServiceEditsInSourceSR=t?.returnServiceEditsInSourceSR):(v.adds=d.length?JSON.stringify(d):null,v.updates=p.length?JSON.stringify(p):null,v.deletes=m.length?c?JSON.stringify(m):m.join(`,`):null,v.attachments=h&&JSON.stringify(h),v.assetMaps=l==null?void 0:JSON.stringify(l));let b=this._getLayerRequestOptions({method:`post`,query:v});y&&(b.authMode=`immediate`,b.query.returnEditMoment=!0,b.query.sessionId=H);let x=t?.returnServiceEditsOption?i.url:i.parsedUrl.path,S;try{S=g?await this._asyncApplyEdits(x+`/applyEdits`,b):await n(x+`/applyEdits`,b)}catch(e){if(D(e))b.authMode=`immediate`,S=g?await this._asyncApplyEdits(x+`/applyEdits`,b):await n(x+`/applyEdits`,b);else throw e}return this._createEditsResult(S)}async deleteAttachments(e,t,r){await this.load();let{layer:i}=this;await N(i,`editing`);let a=e.attributes[i.objectIdField],o=i.parsedUrl.path+`/`+a+`/deleteAttachments`;try{return(await n(o,this._getLayerRequestOptions({query:{attachmentIds:t.join(`,`),...r},method:`post`}))).data.deleteAttachmentResults.map(C)}catch(e){throw this._createAttachmentErrorResult(a,e)}}fetchRecomputedExtents(e={}){let t=e.signal;return this.load({signal:t}).then(async()=>{let t=this._getLayerRequestOptions({...e,query:{returnUpdates:!0}}),{layerId:r,url:i}=this.layer,{data:a}=await n(`${i}/${r}`,t),{id:o,extent:s,fullExtent:c,timeExtent:l}=a,u=s||c;return{id:o,fullExtent:u&&v.fromJSON(u),timeExtent:l&&R.fromJSON({start:l[0],end:l[1]})}})}async queryAttachments(e,t={}){await this.load();let n=this._getLayerRequestOptions(t);return this.queryTask.executeAttachmentQuery(e,n)}async queryFeatures(e,t){await this.load();let n=await this.queryTask.execute(e,{...t,query:this._createRequestQueryOptions(t)});if(e.outStatistics?.length&&n.features.length){let t=new Map;if(n.features.forEach(n=>{let r=n.attributes;e.outStatistics?.forEach(({outStatisticFieldName:e})=>{if(e){let n=e.toLowerCase();n&&n in r&&e!==n&&(r[e]=r[n],delete r[n],t.set(n,e))}})}),n.fields!=null)for(let e of n.fields){let n=t.get(e.name.toLowerCase());n!=null&&(e.name=n)}}return n}async queryFeaturesJSON(e,t){return await this.load(),this.queryTask.executeJSON(e,{...t,query:this._createRequestQueryOptions(t)})}async queryObjectIds(e,t){return await this.load(),this.queryTask.executeForIds(e,{...t,query:this._createRequestQueryOptions(t)})}async queryFeatureCount(e,t){return await this.load(),this.queryTask.executeForCount(e,{...t,query:this._createRequestQueryOptions(t)})}async queryExtent(e,t){return await this.load(),this.queryTask.executeForExtent(e,{...t,query:this._createRequestQueryOptions(t)})}async queryRelatedFeatures(e,t){return await this.load(),this.queryTask.executeRelationshipQuery(e,{...t,query:this._createRequestQueryOptions(t)})}async queryRelatedFeaturesCount(e,t){return await this.load(),this.queryTask.executeRelationshipQueryForCount(e,{...t,query:this._createRequestQueryOptions(t)})}async queryPivot(e,t){return await this.load(),this.queryTask.executePivotQuery(e,{...t,query:this._createRequestQueryOptions(t)})}async queryTopFeatures(e,t){return await this.load(),this.queryTask.executeTopFeaturesQuery(e,{...t,query:this._createRequestQueryOptions(t)})}async queryAttributeBins(e,t){return await this.load(),this.queryTask.executeAttributeBinsQuery(e,{...t,query:this._createRequestQueryOptions(t)})}async queryTopObjectIds(e,t){return await this.load(),this.queryTask.executeForTopIds(e,{...t,query:this._createRequestQueryOptions(t)})}async queryTopExtents(e,t){return await this.load(),this.queryTask.executeForTopExtents(e,{...t,query:this._createRequestQueryOptions(t)})}async queryTopCount(e,t){return await this.load(),this.queryTask.executeForTopCount(e,{...t,query:this._createRequestQueryOptions(t)})}async fetchPublishingStatus(){if(!M(this.layer.url))return`unavailable`;let e=m(this.layer.url,`status`),t=await n(e,{query:{f:`json`}});return W.fromJSON(t.data.status)}async uploadAssets(e,t){let{uploadAssets:n}=await import(`./support/uploadAssets.js`);return n(e,{layer:this.layer,ongoingUploads:this._ongoingAssetUploads},t)}_handleLastEditsEventChange(e){let t=this.layer;if(e==null||!(`capabilities`in t)||!(`effectiveCapabilities`in t)||t.capabilities?.operations?.supportsEditing||!t.effectiveCapabilities?.operations?.supportsEditing)return;let n=t.url;if(n==null)return;`layerId`in t&&(n=m(n,t.layerId.toString()));let r=this._getOrCreateEditInterceptor(n);r.before=t=>{let n=t.requestOptions.method??`auto`;if(n===`auto`||n===`head`){let n=t.requestOptions.query??{};n._ts=e.getTime(),t.requestOptions.query=n}}}_getOrCreateEditInterceptor(e){return this._editInterceptor??(this._editInterceptor={urls:e},t.request.internalInterceptors.push(this._editInterceptor)),this._editInterceptor}_removeEditInterceptor(){this._editInterceptor!=null&&(i(t.request.internalInterceptors,this._editInterceptor),this._editInterceptor=null)}async _asyncApplyEdits(e,t){let r=(await n(e,t)).data.statusUrl;for(;;){let e=(await n(r,{query:{f:`json`},responseType:`json`})).data;switch(e.status){case`Completed`:return n(e.resultUrl,{query:{f:`json`},responseType:`json`});case`CompletedWithErrors`:throw new a(`async-applyEdits-failed`,`asynchronous applyEdits call failed.`);case`Failed ImportChanges`:case`InProgress`:case`Pending`:case`ExportAttachments`:case`ExportChanges`:case`ExportingData`:case`ExportingSnapshot`:case`ImportAttachments`:case`ProvisioningReplica`:case`UnRegisteringReplica`:break;default:throw new a(`async-applyEdits-failed`,`asynchronous applyEdits call failed (undefined response status)`)}await d(K)}}_createRequestQueryOptions(e){let t={...this.layer.customParameters,token:this.layer.apiKey,...e?.query};return this.layer.datesInUnknownTimezone&&(t.timeReferenceUnknownClient=!0),t}async _fetchService(e,t){if(!e){let r={};has(`featurelayer-advanced-symbols`)&&(r.returnAdvancedSymbols=!0),t?.cacheBust&&(r._ts=Date.now());let{data:i}=await n(this.layer.parsedUrl.path,this._getLayerRequestOptions({query:r,signal:t?.signal}));e=i}this.layer.applyPreferredHost(e),this.sourceJSON=await this._patchServiceJSON(e,t?.signal);let r=e.type;if(!this.supportedSourceTypes.has(r))throw new a(`feature-layer-source:unsupported-type`,`Source type "${r}" is not supported`)}async _patchServiceJSON(e,t){if(e.type!==`Table`&&e.geometryType&&!e?.drawingInfo?.renderer&&!e.defaultSymbol){let t=A(e.geometryType).renderer;l(`drawingInfo.renderer`,t,e)}if(e.geometryType===`esriGeometryMultiPatch`&&e.infoFor3D&&(e.geometryType=`mesh`),e.extent==null)try{let{data:r}=await n(this.layer.url,this._getLayerRequestOptions({signal:t}));r.spatialReference&&(e.extent={xmin:0,ymin:0,xmax:0,ymax:0,spatialReference:r.spatialReference})}catch(e){f(e)}return e}async _ensureLatestMetadata(e){if(this.layer.userHasUpdateItemPrivileges&&this.sourceJSON.cacheMaxAge>0)return this._fetchService(null,{...e,cacheBust:!0})}async _uploadMeshesAndGetAssetMapEditsJSON(e){let{addAssetFeatures:t}=e;if(!t?.length||await this._areAllAssetsAlreadyMapped(t))return null;let n=e.addFeatures.filter(e=>e.geometry);if(t.length!==n.length+e.updateFeatures.length)throw new a(`feature-layer-source:unsupported-mesh-edits`,`Mixing attribute only edits with mesh geometry edits is not currently supported`);let r=[],i=new Map;for(let e of t){let{geometry:t}=e,{vertexSpace:n}=t;if(x(n))r.push(t);else{let n=t.origin,{convertMeshVertexSpace:a}=await import(`../../../geometry/support/meshUtils/convertMeshVertexSpace.js`),o=await a(t,new b({origin:[n.x,n.y,n.z??0]}));i.set(o,t),e.geometry=o,r.push(o)}}await this.uploadAssets(r);for(let[e,t]of i)t.addExternalSources(e.metadata.externalSources.items);return{adds:this._getAssetMapEditsJSON(t),updates:[],deletes:[]}}_getAssetMapEditsJSON(e){let t=[],n=this.layer.globalIdField,r=this.layer.parsedUrl;for(let i of e){let{metadata:e}=i.geometry,a=e.getExternalSourcesOnService(r),o=i.getAttribute(n);if(a.length===0){c.getLogger(this).error(`Skipping feature ${o}. The mesh it is associated with has not been uploaded to the service and cannot be mapped to it.`);continue}let{source:s}=a.find(S)??a[0];for(let e of s.assets)e.parts.length===1?t.push({globalId:h(),parentGlobalId:o,assetName:e.assetName,assetHash:e.parts[0].partHash,flags:[]}):c.getLogger(this).error(`Skipping asset ${e.assetName}. It does not have exactly one part, so we cannot map it to a feature.`)}return t}_createEditsResult(e){let t=e.data,{layerId:n}=this.layer,r=[],i=null;if(Array.isArray(t))for(let e of t)e.editedFeatures!=null&&r.push({id:e.id,editedFeatures:e.editedFeatures}),e.id===n&&(i={addResults:e.addResults??[],updateResults:e.updateResults??[],deleteResults:e.deleteResults??[],attachments:e.attachments,editMoment:e.editMoment});else i=t;let a=O(i);if(r.length>0){a.editedFeatureResults=[];for(let e of r){let{editedFeatures:t}=e,n=t?.spatialReference?new y(t.spatialReference):null;a.editedFeatureResults.push({layerId:e.id,editedFeatures:k(t,n)})}}return a}_createAttachmentErrorResult(e,t){let n=t.details.messages?.[0]||t.message,r=t.details.httpStatus||t.details.messageCode;return{objectId:e,globalId:null,error:new a(`feature-layer-source:attachment-failure`,n,{code:r})}}_getFormDataForAttachment(e,t){let n=e instanceof FormData?e:e&&e.elements?new FormData(e):null;if(n)for(let e in t){let r=t[e];r!=null&&(n.set?n.set(e,r):n.append(e,r))}return n}_getLayerRequestOptions(e={}){let{layer:t,layer:{parsedUrl:n,gdbVersion:r}}=this;return{...e,query:{gdbVersion:r,layer:`dynamicDataSource`in t&&t.dynamicDataSource?JSON.stringify({source:t.dynamicDataSource}):void 0,...n.query,f:`json`,...this._createRequestQueryOptions(e)},responseType:`json`}}async _areAllAssetsAlreadyMapped(e){let{layer:t}=this,{globalIdField:n,parsedUrl:i}=t,a=`infoFor3D`in t?t.infoFor3D:null;if(a==null||n==null)return!1;let o=P(a);if(o==null)return!1;let s=m(i.path,`../${o.id}`),c=[];for(let t of e)if(t.geometry.metadata.getExternalSourcesOnService(i).length>0)c.push(t);else return!1;let l=c.map(e=>e.getAttribute(n)).filter(r);if(l.length===0)return!1;let{assetMapFieldRoles:{parentGlobalId:u,assetHash:d}}=a,f=new L({where:`${u} IN (${l.map(e=>`'${e}'`)})`,outFields:[d,u],returnGeometry:!1}),{features:p}=await F(s,f);return p.length!==0&&!c.some(e=>{let t=e.getAttribute(n);if(!t)return!0;let{metadata:r}=e.geometry,a=p.filter(e=>e.getAttribute(u)===t);if(a.length===0)return!0;let o=a.map(e=>e.getAttribute(d));return r.getExternalSourcesOnService(i).flatMap(({source:e})=>e.assets.flatMap(e=>e.parts.map(e=>e.partHash))).some(e=>o.every(t=>e!==t))})}};e([g()],G.prototype,`type`,void 0),e([g({constructOnly:!0})],G.prototype,`layer`,void 0),e([g({constructOnly:!0})],G.prototype,`supportedSourceTypes`,void 0),e([g({readOnly:!0})],G.prototype,`queryTask`,null),G=e([_(`esri.layers.graphics.sources.FeatureLayerSource`)],G);const K=1e3;export{G as default};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
- function e(e,t,n){if(!e||e.type===`extent`||e.type===`mesh`)return e;if(e.type===`point`)return e.spatialReference=n,e;let{coords:r,lengths:i}=t,{hasZ:a,hasM:o}=e,s=2+Number(!!a)+Number(!!o),c=e.type===`multipoint`?[r.length/s]:i,l=[],u=0;if(s===2)for(let e of c){let t=[];for(let n=0;n<e;n++,u+=2)t.push([r[u],r[u+1]]);l.push(t)}else if(s===3)for(let e of c){let t=[];for(let n=0;n<e;n++,u+=3)t.push([r[u],r[u+1],r[u+2]]);l.push(t)}else for(let e of c){let t=[];for(let n=0;n<e;n++,u+=4)t.push([r[u],r[u+1],r[u+2],r[u+3]]);l.push(t)}return e.spatialReference=n,e.type===`multipoint`?e.points=l[0]:e.type===`polygon`?e.rings=l:e.paths=l,e}export{e as toDehydratedGeometry};
2
+ import{isPlainObject as e}from"../../core/lang.js";function t(e,t){if(c(e))return r(e,a,l(e),t)}function n(e,t,n){if(c(e)&&t)return r(t,e.type===`multipoint`?s:o,l(e),n)}function r(e,t,n,r){let i=t.vertexCount(e,n);if(i<1024)return;let a=t.partCount(e),o=`${r},${i},${a}`,s=Math.min(a,3),c=0,l=0;for(let r=0;r<s;++r){let i=s===1?0:Math.floor(r*(a-1)/(s-1));for(;c<i;)l+=t.partLength(e,c++,n)*n;let u=t.partLength(e,c,n);if(o+=`,${u}`,u>0)for(let r=0;r<3;++r){let i=r===0?0:r===1?Math.floor(u/2):Math.max(0,u-2);for(let r=0;r<n;++r){let a=t.coordinate(e,c,i,r,l,n);o+=`,${a.toFixed(5)}`}}}return o}function i(e,t,n){if(!e||!c(n)||!t)return!1;let{coords:r}=t,i=2+Number(!!e.hasZ)+Number(!!e.hasM),a=e.type===`multipoint`?s:o,l=u(n);if(a.partCount(t)!==l)return!1;let f=0;for(let e=0;e<l;++e){let o=d(n,e);if(a.partLength(t,e,i)!==o.length)return!1;for(let e of o)for(let t=0;t<i;++t)if(r[f++]!==e[t])return!1}return!0}const a={partCount:u,vertexCount(e){let t=0,n=u(e);for(let r=0;r<n;++r)t+=d(e,r).length;return t},partLength:(e,t)=>d(e,t).length,coordinate:(e,t,n,r)=>d(e,t)[n][r]},o={partCount:e=>e.lengths.length,vertexCount:(e,t)=>e.coords.length/t,partLength:(e,t)=>e.lengths[t],coordinate:(e,t,n,r,i,a)=>e.coords[i+n*a+r]},s={...o,partCount:()=>1,partLength:(e,t,n)=>e.coords.length/n};function c(t){return!!t&&e(t)&&(t.type===`polygon`||t.type===`polyline`||t.type===`multipoint`)&&!(t.type===`polygon`&&t.curveRings?.length)&&!(t.type===`polyline`&&t.curvePaths?.length)}function l(e){return 2+Number(!!e.hasZ)+Number(!!e.hasM)}function u(e){return e.type===`multipoint`?1:e.type===`polygon`?e.rings.length:e.paths.length}function d(e,t){return e.type===`multipoint`?e.points:e.type===`polygon`?e.rings[t]:e.paths[t]}function f(e,t,n){p(e.geometry,t,n)}function p(e,t,n){if(!e||(e.spatialReference=n,e.type===`extent`||e.type===`mesh`||e.type===`point`||!t))return;let{coords:r,lengths:i}=t,a=l(e),o=e.type===`multipoint`?[r.length/a]:i,s=[],c=0;if(a===2)for(let e of o){let t=[];for(let n=0;n<e;n++,c+=2)t.push([r[c],r[c+1]]);s.push(t)}else if(a===3)for(let e of o){let t=[];for(let n=0;n<e;n++,c+=3)t.push([r[c],r[c+1],r[c+2]]);s.push(t)}else for(let e of o){let t=[];for(let n=0;n<e;n++,c+=4)t.push([r[c],r[c+1],r[c+2],r[c+3]]);s.push(t)}e.type===`multipoint`?e.points=s[0]:e.type===`polygon`?e.rings=s:e.paths=s}export{f as completeDehydratedFeatureFromTransfer,p as completeDehydratedGeometryFromTransfer,t as geometryKey,i as identicalTransferGeometry,n as transferGeometryKey};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
- import e from"../../Color.js";import t from"../../config.js";import{id as n}from"../../kernel.js";import r from"../../core/Error.js";import{getOrCreateMapValue as i}from"../../core/MapUtils.js";import{throwIfAbortError as a}from"../../core/promiseUtils.js";import o from"../../form/FormTemplate.js";import s from"../../form/elements/FieldElement.js";import{initializeProjection as c,project as l}from"../../geometry/projectionUtils.js";import u from"../../geometry/SpatialReference.js";import{normalizeCentralMeridian as d}from"../../geometry/support/normalizeUtils.js";import{queryBinsCapabilities as f,queryCapabilities as p}from"../graphics/data/QueryEngineCapabilities.js";import{systemOidFieldName as m}from"./constants.js";import h from"../support/FeatureTemplate.js";import g from"../support/LabelClass.js";import _ from"../support/LabelExpressionInfo.js";import{isKnowledgeGraphSublayer as v,getOwningPortalUrl as y}from"../support/layerUtils.js";import b from"../../portal/PortalItem.js";import{getUserPrivileges as x}from"../../portal/support/portalItemUtils.js";import{executeQueryStreaming as S,fetchClientDataAtKeys as C}from"../../rest/knowledgeGraphService.js";import w from"../../rest/knowledgeGraph/Entity.js";import T from"../../rest/knowledgeGraph/GraphApplyEdits.js";import E from"../../rest/knowledgeGraph/Relationship.js";import{isGraphic as D}from"../../support/graphicInstanceUtils.js";import O from"../../symbols/CIMSymbol.js";import k from"../../symbols/TextSymbol.js";const A={initializeLayersFromClientData:async(e,t,n)=>{if(t||=[...e.layers,...e.tables].map(e=>e.graphTypeName),t?.length===0)return;let r=new Map;for(let n of t)r.set(n,j(e,n));let i=await C(e.dataManager.knowledgeGraph,Array.from(r.values()),{requestOptions:{signal:n?.signal}});for(let t of[...e.layers,...e.tables]){let n=t.objectType.name;if(n==null)continue;let r=i.get(j(e,n));if(r){let e=JSON.parse(r);typeof e==`object`&&e&&!e.hasOwnProperty(`showLabels`)&&(e.showLabels=!1),t.read(e,{origin:`service`})}}},getInclusionDefinitionFromCypherResults:async(e,t,n)=>{let r=Q(e.dataModel),i=(await S(e,t,n)).resultRowsStream.getReader();for(;;){let{done:e,value:t}=await i.read();if(e)break;for(let e of t)for(let t of e)$(t,r)}return r},getInclusionDefinitionFromIdTypePairs:(e,t)=>{let n=Q(e.dataModel);for(let{id:e,typeName:i}of t){let t=n.namedTypeDefinitions.get(i);if(!t)throw new r(`WebLinkChart:data-model-desync`,`The provided id-type pairs contained a named type not reflected in the provided knowledge graph data model.`);t.members?.set(e,{id:e})}return n},getUserKGSPrivileges:async(e,r,i)=>{let a=!0,o=!1,s=!1;if(!t.userPrivilegesApplied)return{edit:a,fullEdit:o,updateItem:s};let c=await y(r,i);if(!c||!n?.getCredential(`${c}/sharing`,{...i,prompt:!1}))return{edit:a,fullEdit:o,updateItem:s};let l=new b({id:e,portal:{url:c}});return await l.load(i),{features:{edit:a,fullEdit:o},content:{updateItem:s}}=x(l),{edit:a,fullEdit:o,updateItem:s}}},j=(e,t)=>e.type===`knowledge-graph`?`${t}/Map`:`${t}/LinkChart/LinkChartSubLayer`;async function M(e,t,n){return A.initializeLayersFromClientData(e,t,n)}async function N(e,t,n){return A.getInclusionDefinitionFromCypherResults(e,t,n)}function P(e,t){return A.getInclusionDefinitionFromIdTypePairs(e,t)}const F=`#4a0932.#b31515.#18382e.#a64f1b.#102432.#8c213f.#ed9310.#2c6954.#144d59.#ffc730.#75351e.#454f4b.#78b1c2.#191921.#8f8f82.#9be0c0.#dbb658.#87b051.#11495c.#c43541.#9c5596.#44498b.#ad9d63.#86afb3.#5c98ca.#b0bfa2.#73241f.#b86b53.#d9d78c.#3e756d.#f260a1.#a0d17d.#c27c30.#eb82eb.#ffdf3c.#ffb259.#ab52b3.#3cccb4.#0095ba.#d92b30`.split(`.`),I=`#8f8f82`;function L(t){return t<0||t>=F.length?new e(I):new e(F[t])}function R(e){let t=e.toArray();return new O({data:{type:`CIMSymbolReference`,symbol:{type:`CIMLineSymbol`,symbolLayers:[{type:`CIMSolidStroke`,enable:!0,style:`solid`,width:.75,color:t},{type:`CIMVectorMarker`,enable:!0,size:6,markerPlacement:{type:`CIMMarkerPlacementOnLine`,angleToLine:!0,relativeTo:`LineMiddle`},frame:{xmin:-10,ymin:-5,xmax:0,ymax:5},markerGraphics:[{type:`CIMMarkerGraphic`,geometry:{rings:[[[-12,-3.47],[-12,3.6],[1.96,-.03],[-12,-3.47]]]},symbol:{type:`CIMPolygonSymbol`,symbolLayers:[{type:`CIMSolidFill`,enable:!0,color:t}]}}]}]}}})}function z(e){let t=`ESRI__ID`,n=4;for(let r of e)if(r.name){if(r.name.toLowerCase()===`name`){t=r.name;break}r.name.toLowerCase().includes(`name`)?(t=r.name,n=2):r.fieldType===`esriFieldTypeString`&&n>3&&(t=r.name,n=3)}return t}function B(e,t,n){let r={color:[80,80,80],haloColor:[255,255,255],haloSize:.7,font:{size:10,weight:`normal`}},i=new g({labelExpressionInfo:new _({expression:n===`ESRI__ID`?`${t}`:`$feature.${n}`}),labelPlacement:`above-center`,symbol:new k(r)}),a=new g({labelExpressionInfo:new _({expression:`'${t}' + IIf($feature.ESRI__AggregationCount>1, ' (' + $feature.ESRI__AggregationCount + ')', '')`}),labelPlacement:`center-along`,labelPosition:`parallel`,repeatLabel:!1,symbol:new k({...r,yoffset:`12px`})});return e===`entity`?[i]:[a]}function V(e,t,n){let r={color:[255,255,255],haloColor:[0,0,0],haloSize:.7,font:{size:10,weight:`bold`}},i=n===`ESRI__ID`?`${e}`:`$feature.${n}`;return t===`point`?[new g({labelExpressionInfo:new _({expression:i}),labelPlacement:`above-center`,symbol:new k(r)})]:t===`polyline`?[new g({labelExpressionInfo:new _({expression:i}),labelPlacement:`center-along`,repeatLabel:!0,symbol:new k(r)})]:t===`polygon`?[new g({labelExpressionInfo:new _({expression:i}),labelPlacement:`always-horizontal`,symbol:new k(r)})]:null}async function H(e,t,n){return A.getUserKGSPrivileges(e,t,n).catch(e=>(a(e),{edit:!0,fullEdit:!1,updateItem:!1}))}const U={capabilities:[],allowGeometryUpdates:!1,serviceCapabilities:{geometryCapabilities:{supportsZValues:!1,supportsMValues:!1}}};function W(e){let{capabilities:t,allowGeometryUpdates:n,serviceCapabilities:{geometryCapabilities:{supportsZValues:r,supportsMValues:i}}}=e?.serviceDefinition||U,a=e?.dataModel.arcgisManaged?t:t.filter(e=>e===`Query`),o=new Set(a);return{analytics:{supportsCacheHint:!1},attachment:null,data:{isVersioned:!1,isBranchVersioned:!1,supportedCurveTypes:[],supportsAttachment:!1,supportsM:i,supportsTrueCurve:!1,supportsZ:r},metadata:{supportsAdvancedFieldProperties:!1},operations:{supportsCalculate:!1,supportsTruncate:!1,supportsValidateSql:!1,supportsAdd:o.has(`Create`),supportsDelete:o.has(`Delete`),supportsEditing:o.has(`Editing`),supportsChangeTracking:!1,supportsQuery:o.has(`Query`),supportsQueryBins:!1,supportsQueryPivot:!1,supportsQueryAnalytics:!1,supportsQueryAttachments:!1,supportsQueryTopFeatures:!1,supportsResizeAttachments:!1,supportsSync:!1,supportsUpdate:o.has(`Update`),supportsExceedsLimitStatistics:!1,supportsAsyncConvert3D:!1},query:p,queryRelated:{supportsCount:!1,supportsOrderBy:!1,supportsPagination:!1,supportsCacheHint:!1},queryTopFeatures:{supportsCacheHint:!1},queryAttributeBins:f,editing:{supportsGeometryUpdate:!!e?.dataModel.arcgisManaged&&n,supportsGlobalId:!1,supportsReturnServiceEditsInSourceSpatialReference:!1,supportsRollbackOnFailure:!1,supportsTrueCurveUpdate:!1,supportsTrueCurveUpdateByTrueCurveClientsOnly:!0,supportsUpdateWithoutM:!1,supportsUploadWithItemId:!1,supportsDeleteByAnonymous:!1,supportsDeleteByOthers:o.has(`Delete`),supportsUpdateByAnonymous:!1,supportsUpdateByOthers:o.has(`Update`),supportsAsyncApplyEdits:!1,zDefault:void 0}}}async function G(e,t,n){let r=new T,a=t.graphTypeName,o=t.graphType,s=n.type===`knowledge-graph`?t.geometryFieldName:null,f=!!t.fieldsIndex.get(s)?.editable,p=e=>{let n={...e};for(let e of t.fields)e.editable||delete n[e.name];for(let t of Object.keys(e))t.includes(`ESRI__`)&&delete n[t];return n},h=async e=>{await c(e.spatialReference,u.WGS84);let t=l(e,u.WGS84);return t.type===`point`?t.normalize():(await d(t))[0]};for(let t of e.addFeatures??[]){let e=p(t.attributes);v(t.sourceLayer)&&t.sourceLayer.graphTypeName===a&&(o===`entity`?(r.entityAdds||=[],s&&t.geometry&&(e[s]=await h(t.geometry)),r.entityAdds.push(new w({properties:e,typeName:a}))):(r.relationshipAdds||=[],r.relationshipAdds.push(new E({properties:e,typeName:a}))))}for(let t of e.updateFeatures??[]){let e=t.attributes[m],n=p(t.attributes);v(t.sourceLayer)&&t.sourceLayer.graphTypeName===a&&(o===`entity`?(r.entityUpdates||=[],s&&f&&t.geometry&&(n[s]=await h(t.geometry)),r.entityUpdates.push(new w({id:e,properties:n,typeName:a}))):(r.relationshipUpdates||=[],r.relationshipUpdates.push(new E({id:e,properties:n,typeName:a}))))}let g=new Map;for(let t of e.deleteFeatures??[])if(D(t)){let e=t,n=i(g,e.sourceLayer.graphTypeName,()=>({typeName:e.sourceLayer.graphTypeName,ids:[]}));e.sourceLayer.graphTypeName===a&&n.ids.push(e.attributes[m])}else t.objectId&&typeof t.objectId==`string`&&i(g,a,()=>({typeName:a,ids:[]})).ids.push(t.objectId);for(let e of g.values())e.ids.length>0&&(o===`entity`?(r.entityDeletes||=[],r.entityDeletes.push({typeName:e.typeName,ids:e.ids})):(r.relationshipDeletes||=[],r.relationshipDeletes.push({typeName:e.typeName,ids:e.ids})));return r}function K(e,t){let n={addFeatureResults:[],updateFeatureResults:[],deleteFeatureResults:[],addAttachmentResults:[],updateAttachmentResults:[],deleteAttachmentResults:[]};for(let r of e.editResults)if(r.typeName===t){for(let e of r.adds)n.addFeatureResults.push({objectId:e.id,globalId:e.id});for(let e of r.updates)n.updateFeatureResults.push({objectId:e.id,globalId:e.id});for(let e of r.deletes)n.deleteFeatureResults.push({objectId:e.id,globalId:e.id})}return n}function q(e){if(!e.objectType)return null;let t=[];for(let n of e.fields)!n.name.includes(`ESRI__`)&&n.editable&&n.type!==`geometry`&&t.push(new s({fieldName:n.name}));return new o({elements:t})}function J(e){if(!e.objectType)return null;let t=null;switch(e.geometryType){case`point`:case`multipoint`:t=`point`;break;case`polyline`:t=`line`;break;case`polygon`:t=`polygon`;break;default:t=null}return[new h({name:e.graphTypeName,drawingTool:t,prototype:{}})]}function Y(e){return!e||typeof e!=`object`||Array.isArray(e)?!1:`id`in e&&`typeName`in e}function X(e){return!e||typeof e!=`object`||Array.isArray(e)?!1:e&&`path`in e&&Array.isArray(e.path)}function Z(e){return!e||typeof e!=`object`||Array.isArray(e)||`id`in e?!1:`properties`in e&&typeof e.properties==`object`}function Q(e){let t={namedTypeDefinitions:new Map,generateAllSublayers:!1},{entityTypes:n,relationshipTypes:r}=e,i=[...n,...r];for(let e of i)t.namedTypeDefinitions.set(e.name,{useAllData:!1,members:new Map});return t}function $(e,t){if(e&&typeof e==`object`){if(Y(e)){let n=t.namedTypeDefinitions.get(e.typeName);if(!n)throw new r(`WebLinkChart:data-model-desync`,`The query result contained a named type not reflected in the provided knowledge graph data model.`);n.members.set(e.id,{id:e.id})}else if(X(e))for(let n of e.path)$(n,t);else if(Array.isArray(e))for(let n of e)$(n,t);else if(Z(e))for(let n of Object.values(e.properties??{}))$(n,t)}}const ee=e=>{let t=``,n=e.split(`/`),r=n.lastIndexOf(`KnowledgeGraphServer`);return r>0&&(t=n[r-1]),t};export{K as convertGraphEditsResultToFeatureEdits,G as convertLayerEditsToGraphEdits,W as createCapabilitiesFromKnowledgeGraph,J as createDefaultKGSLFeatureTemplates,q as createDefaultKGSLFormTemplate,$ as extractGraphNamedObjectsFromQueryValueRecursive,I as fallbackKGSublayerSymbolHexColor,R as getDefaultLCRelationshipSublayerSymbol,z as getDisplayLabelProperty,Q as getEmptyInclusionListFromDataModel,N as getInclusionDefinitionFromCypherResults,P as getInclusionDefinitionFromIdTypePairs,L as getKGSublayerSymbolColor,B as getLinkChartDefaultLabelingInfo,V as getMapDefaultLabelingInfo,ee as getTitleFromServerUrl,H as getUserKGSPrivileges,M as initializeLayersFromClientData,Y as isGraphNamedObject,Z as isGraphObject,X as isPathObject,A as layerUtils};
2
+ import e from"../../Color.js";import t from"../../config.js";import{id as n}from"../../kernel.js";import r from"../../core/Error.js";import{getOrCreateMapValue as i}from"../../core/MapUtils.js";import{throwIfAbortError as a}from"../../core/promiseUtils.js";import o from"../../form/FormTemplate.js";import s from"../../form/elements/FieldElement.js";import{assertNotMesh as c}from"../../geometry/asserts.js";import{initializeProjection as l,project as u}from"../../geometry/projectionUtils.js";import d from"../../geometry/SpatialReference.js";import{normalizeCentralMeridian as f}from"../../geometry/support/normalizeUtils.js";import{queryBinsCapabilities as p,queryCapabilities as m}from"../graphics/data/QueryEngineCapabilities.js";import{systemOidFieldName as h}from"./constants.js";import g from"../support/FeatureTemplate.js";import _ from"../support/LabelClass.js";import v from"../support/LabelExpressionInfo.js";import{isKnowledgeGraphSublayer as y,getOwningPortalUrl as ee}from"../support/layerUtils.js";import b from"../../portal/PortalItem.js";import{getUserPrivileges as x}from"../../portal/support/portalItemUtils.js";import{executeQueryStreaming as S,fetchClientDataAtKeys as C}from"../../rest/knowledgeGraphService.js";import w from"../../rest/knowledgeGraph/Entity.js";import T from"../../rest/knowledgeGraph/GraphApplyEdits.js";import E from"../../rest/knowledgeGraph/Relationship.js";import{isGraphic as D}from"../../support/graphicInstanceUtils.js";import O from"../../symbols/CIMSymbol.js";import k from"../../symbols/TextSymbol.js";const A={initializeLayersFromClientData:async(e,t,n)=>{if(t||=[...e.layers,...e.tables].map(e=>e.graphTypeName),t?.length===0)return;let r=new Map;for(let n of t)r.set(n,j(e,n));let i=await C(e.dataManager.knowledgeGraph,Array.from(r.values()),{requestOptions:{signal:n?.signal}});for(let t of[...e.layers,...e.tables]){let n=t.objectType.name;if(n==null)continue;let r=i.get(j(e,n));if(r){let e=JSON.parse(r);typeof e==`object`&&e&&!e.hasOwnProperty(`showLabels`)&&(e.showLabels=!1),t.read(e,{origin:`service`})}}},getInclusionDefinitionFromCypherResults:async(e,t,n)=>{let r=Q(e.dataModel),i=(await S(e,t,n)).resultRowsStream.getReader();for(;;){let{done:e,value:t}=await i.read();if(e)break;for(let e of t)for(let t of e)$(t,r)}return r},getInclusionDefinitionFromIdTypePairs:(e,t)=>{let n=Q(e.dataModel);for(let{id:e,typeName:i}of t){let t=n.namedTypeDefinitions.get(i);if(!t)throw new r(`WebLinkChart:data-model-desync`,`The provided id-type pairs contained a named type not reflected in the provided knowledge graph data model.`);t.members?.set(e,{id:e})}return n},getUserKGSPrivileges:async(e,r,i)=>{let a=!0,o=!1,s=!1;if(!t.userPrivilegesApplied)return{edit:a,fullEdit:o,updateItem:s};let c=await ee(r,i);if(!c||!n?.getCredential(`${c}/sharing`,{...i,prompt:!1}))return{edit:a,fullEdit:o,updateItem:s};let l=new b({id:e,portal:{url:c}});return await l.load(i),{features:{edit:a,fullEdit:o},content:{updateItem:s}}=x(l),{edit:a,fullEdit:o,updateItem:s}}},j=(e,t)=>e.type===`knowledge-graph`?`${t}/Map`:`${t}/LinkChart/LinkChartSubLayer`;async function M(e,t,n){return A.initializeLayersFromClientData(e,t,n)}async function N(e,t,n){return A.getInclusionDefinitionFromCypherResults(e,t,n)}function P(e,t){return A.getInclusionDefinitionFromIdTypePairs(e,t)}const F=`#4a0932.#b31515.#18382e.#a64f1b.#102432.#8c213f.#ed9310.#2c6954.#144d59.#ffc730.#75351e.#454f4b.#78b1c2.#191921.#8f8f82.#9be0c0.#dbb658.#87b051.#11495c.#c43541.#9c5596.#44498b.#ad9d63.#86afb3.#5c98ca.#b0bfa2.#73241f.#b86b53.#d9d78c.#3e756d.#f260a1.#a0d17d.#c27c30.#eb82eb.#ffdf3c.#ffb259.#ab52b3.#3cccb4.#0095ba.#d92b30`.split(`.`),I=`#8f8f82`;function L(t){return t<0||t>=F.length?new e(I):new e(F[t])}function R(e){let t=e.toArray();return new O({data:{type:`CIMSymbolReference`,symbol:{type:`CIMLineSymbol`,symbolLayers:[{type:`CIMSolidStroke`,enable:!0,style:`solid`,width:.75,color:t},{type:`CIMVectorMarker`,enable:!0,size:6,markerPlacement:{type:`CIMMarkerPlacementOnLine`,angleToLine:!0,relativeTo:`LineMiddle`},frame:{xmin:-10,ymin:-5,xmax:0,ymax:5},markerGraphics:[{type:`CIMMarkerGraphic`,geometry:{rings:[[[-12,-3.47],[-12,3.6],[1.96,-.03],[-12,-3.47]]]},symbol:{type:`CIMPolygonSymbol`,symbolLayers:[{type:`CIMSolidFill`,enable:!0,color:t}]}}]}]}}})}function z(e){let t=`ESRI__ID`,n=4;for(let r of e)if(r.name){if(r.name.toLowerCase()===`name`){t=r.name;break}r.name.toLowerCase().includes(`name`)?(t=r.name,n=2):r.fieldType===`esriFieldTypeString`&&n>3&&(t=r.name,n=3)}return t}function B(e,t,n){let r={color:[80,80,80],haloColor:[255,255,255],haloSize:.7,font:{size:10,weight:`normal`}},i=new _({labelExpressionInfo:new v({expression:n===`ESRI__ID`?`${t}`:`$feature.${n}`}),labelPlacement:`above-center`,symbol:new k(r)}),a=new _({labelExpressionInfo:new v({expression:`'${t}' + IIf($feature.ESRI__AggregationCount>1, ' (' + $feature.ESRI__AggregationCount + ')', '')`}),labelPlacement:`center-along`,labelPosition:`parallel`,repeatLabel:!1,symbol:new k({...r,yoffset:`12px`})});return e===`entity`?[i]:[a]}function V(e,t,n){let r={color:[255,255,255],haloColor:[0,0,0],haloSize:.7,font:{size:10,weight:`bold`}},i=n===`ESRI__ID`?`${e}`:`$feature.${n}`;return t===`point`?[new _({labelExpressionInfo:new v({expression:i}),labelPlacement:`above-center`,symbol:new k(r)})]:t===`polyline`?[new _({labelExpressionInfo:new v({expression:i}),labelPlacement:`center-along`,repeatLabel:!0,symbol:new k(r)})]:t===`polygon`?[new _({labelExpressionInfo:new v({expression:i}),labelPlacement:`always-horizontal`,symbol:new k(r)})]:null}async function H(e,t,n){return A.getUserKGSPrivileges(e,t,n).catch(e=>(a(e),{edit:!0,fullEdit:!1,updateItem:!1}))}const U={capabilities:[],allowGeometryUpdates:!1,serviceCapabilities:{geometryCapabilities:{supportsZValues:!1,supportsMValues:!1}}};function W(e){let{capabilities:t,allowGeometryUpdates:n,serviceCapabilities:{geometryCapabilities:{supportsZValues:r,supportsMValues:i}}}=e?.serviceDefinition||U,a=e?.dataModel.arcgisManaged?t:t.filter(e=>e===`Query`),o=new Set(a);return{analytics:{supportsCacheHint:!1},attachment:null,data:{isVersioned:!1,isBranchVersioned:!1,supportedCurveTypes:[],supportsAttachment:!1,supportsM:i,supportsTrueCurve:!1,supportsZ:r},metadata:{supportsAdvancedFieldProperties:!1},operations:{supportsCalculate:!1,supportsTruncate:!1,supportsValidateSql:!1,supportsAdd:o.has(`Create`),supportsDelete:o.has(`Delete`),supportsEditing:o.has(`Editing`),supportsChangeTracking:!1,supportsQuery:o.has(`Query`),supportsQueryBins:!1,supportsQueryPivot:!1,supportsQueryAnalytics:!1,supportsQueryAttachments:!1,supportsQueryTopFeatures:!1,supportsResizeAttachments:!1,supportsSync:!1,supportsUpdate:o.has(`Update`),supportsExceedsLimitStatistics:!1,supportsAsyncConvert3D:!1},query:m,queryRelated:{supportsCount:!1,supportsOrderBy:!1,supportsPagination:!1,supportsCacheHint:!1},queryTopFeatures:{supportsCacheHint:!1},queryAttributeBins:p,editing:{supportsGeometryUpdate:!!e?.dataModel.arcgisManaged&&n,supportsGlobalId:!1,supportsReturnServiceEditsInSourceSpatialReference:!1,supportsRollbackOnFailure:!1,supportsTrueCurveUpdate:!1,supportsTrueCurveUpdateByTrueCurveClientsOnly:!0,supportsUpdateWithoutM:!1,supportsUploadWithItemId:!1,supportsDeleteByAnonymous:!1,supportsDeleteByOthers:o.has(`Delete`),supportsUpdateByAnonymous:!1,supportsUpdateByOthers:o.has(`Update`),supportsAsyncApplyEdits:!1,zDefault:void 0}}}async function G(e,t,n){let r=new T,a=t.graphTypeName,o=t.graphType,s=n.type===`knowledge-graph`?t.geometryFieldName:null,p=!!t.fieldsIndex.get(s)?.editable,m=e=>{let n={...e};for(let e of t.fields)e.editable||delete n[e.name];for(let t of Object.keys(e))t.includes(`ESRI__`)&&delete n[t];return n},g=async e=>{await l(e.spatialReference,d.WGS84);let t=u(e,d.WGS84);if(t.type===`point`)return t.normalize();let[n]=await f(t);return n};for(let t of e.addFeatures??[]){let e=m(t.attributes);y(t.sourceLayer)&&t.sourceLayer.graphTypeName===a&&(o===`entity`?(r.entityAdds||=[],s&&t.geometry&&(c(t.geometry),e[s]=await g(t.geometry)),r.entityAdds.push(new w({properties:e,typeName:a}))):(r.relationshipAdds||=[],r.relationshipAdds.push(new E({properties:e,typeName:a}))))}for(let t of e.updateFeatures??[]){let e=t.attributes[h],n=m(t.attributes);y(t.sourceLayer)&&t.sourceLayer.graphTypeName===a&&(o===`entity`?(r.entityUpdates||=[],s&&p&&t.geometry&&(c(t.geometry),n[s]=await g(t.geometry)),r.entityUpdates.push(new w({id:e,properties:n,typeName:a}))):(r.relationshipUpdates||=[],r.relationshipUpdates.push(new E({id:e,properties:n,typeName:a}))))}let _=new Map;for(let t of e.deleteFeatures??[])if(D(t)){let e=t,n=i(_,e.sourceLayer.graphTypeName,()=>({typeName:e.sourceLayer.graphTypeName,ids:[]}));e.sourceLayer.graphTypeName===a&&n.ids.push(e.attributes[h])}else t.objectId&&typeof t.objectId==`string`&&i(_,a,()=>({typeName:a,ids:[]})).ids.push(t.objectId);for(let e of _.values())e.ids.length>0&&(o===`entity`?(r.entityDeletes||=[],r.entityDeletes.push({typeName:e.typeName,ids:e.ids})):(r.relationshipDeletes||=[],r.relationshipDeletes.push({typeName:e.typeName,ids:e.ids})));return r}function K(e,t){let n={addFeatureResults:[],updateFeatureResults:[],deleteFeatureResults:[],addAttachmentResults:[],updateAttachmentResults:[],deleteAttachmentResults:[]};for(let r of e.editResults)if(r.typeName===t){for(let e of r.adds)n.addFeatureResults.push({objectId:e.id,globalId:e.id});for(let e of r.updates)n.updateFeatureResults.push({objectId:e.id,globalId:e.id});for(let e of r.deletes)n.deleteFeatureResults.push({objectId:e.id,globalId:e.id})}return n}function q(e){if(!e.objectType)return null;let t=[];for(let n of e.fields)!n.name.includes(`ESRI__`)&&n.editable&&n.type!==`geometry`&&t.push(new s({fieldName:n.name}));return new o({elements:t})}function J(e){if(!e.objectType)return null;let t=null;switch(e.geometryType){case`point`:case`multipoint`:t=`point`;break;case`polyline`:t=`line`;break;case`polygon`:t=`polygon`;break;default:t=null}return[new g({name:e.graphTypeName,drawingTool:t,prototype:{}})]}function Y(e){return!e||typeof e!=`object`||Array.isArray(e)?!1:`id`in e&&`typeName`in e}function X(e){return!e||typeof e!=`object`||Array.isArray(e)?!1:e&&`path`in e&&Array.isArray(e.path)}function Z(e){return!e||typeof e!=`object`||Array.isArray(e)||`id`in e?!1:`properties`in e&&typeof e.properties==`object`}function Q(e){let t={namedTypeDefinitions:new Map,generateAllSublayers:!1},{entityTypes:n,relationshipTypes:r}=e,i=[...n,...r];for(let e of i)t.namedTypeDefinitions.set(e.name,{useAllData:!1,members:new Map});return t}function $(e,t){if(e&&typeof e==`object`){if(Y(e)){let n=t.namedTypeDefinitions.get(e.typeName);if(!n)throw new r(`WebLinkChart:data-model-desync`,`The query result contained a named type not reflected in the provided knowledge graph data model.`);n.members.set(e.id,{id:e.id})}else if(X(e))for(let n of e.path)$(n,t);else if(Array.isArray(e))for(let n of e)$(n,t);else if(Z(e))for(let n of Object.values(e.properties??{}))$(n,t)}}const te=e=>{let t=``,n=e.split(`/`),r=n.lastIndexOf(`KnowledgeGraphServer`);return r>0&&(t=n[r-1]),t};export{K as convertGraphEditsResultToFeatureEdits,G as convertLayerEditsToGraphEdits,W as createCapabilitiesFromKnowledgeGraph,J as createDefaultKGSLFeatureTemplates,q as createDefaultKGSLFormTemplate,$ as extractGraphNamedObjectsFromQueryValueRecursive,I as fallbackKGSublayerSymbolHexColor,R as getDefaultLCRelationshipSublayerSymbol,z as getDisplayLabelProperty,Q as getEmptyInclusionListFromDataModel,N as getInclusionDefinitionFromCypherResults,P as getInclusionDefinitionFromIdTypePairs,L as getKGSublayerSymbolColor,B as getLinkChartDefaultLabelingInfo,V as getMapDefaultLabelingInfo,te as getTitleFromServerUrl,H as getUserKGSPrivileges,M as initializeLayersFromClientData,Y as isGraphNamedObject,Z as isGraphObject,X as isPathObject,A as layerUtils};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
- import e from"../../core/Error.js";import{makeHandle as t}from"../../core/handleUtils.js";import{getOrCreateMapValue as n}from"../../core/MapUtils.js";import{floatEqualRelative as r}from"../../core/mathUtils.js";import i from"../../geometry/Point.js";import a from"../../geometry/Polyline.js";import{initializeProjection as o,project as s}from"../../geometry/projectionUtils.js";import c from"../../geometry/SpatialReference.js";import l from"../GraphicsLayer.js";import{convertToGeometry as u}from"../graphics/featureConversionUtils.js";import{kgRestServices as d}from"../../rest/knowledgeGraphService.js";import f from"../../rest/knowledgeGraph/GraphQueryStreaming.js";import p from"../../rest/knowledgeGraph/KnowledgeGraph.js";import m from"../../views/draw/support/Reshape.js";const h={newReshapeWrapper:async({getFeatureReshapeProvider:e,targetGraphic:t,reshapeGraphicsLayer:n,view:r,snappingManager:i})=>new m({connectedReshapeProviders:[{getFeatureReshapeProvider:e,getVertexReshapeProvider(){throw Error(`Link Charts do not support vertex (polyline) reshape at this time`)}}],enableMidpoints:!1,graphic:t,layer:n,view:r,snappingManager:i})},g=async({targetEntityId:n,targetEntityType:a,view:d,snappingManager:f})=>{await o(c.WGS84,d.spatialReference);let p=d.map?.activeLinkChartLayer?.layers.find(e=>e.objectType.name===a);if(!p)throw new e(`LinkChartView:target-layer-not-found`,`No layer found for target entity type ${a}`);let m=p.createQuery();m.objectIds=[n];let g=await p.queryFeatures(m);if(g.features.length===0)throw new e(`LinkChartView:no-matching-feature-found`,`No feature found with ID ${n} in layer ${p.title}`);let y=g.features[0].clone(),x=y.attributes.ESRI__ID;if(!y.sourceLayer)throw new e(`LinkChartView:no-source-layer`,`The target graphic does not have a source layer: ${x}`);let S=new l({listMode:`hide`,internal:!0});y.geometry=s(new i(u(y.attributes.ESRI__LayoutGeometry,`esriGeometryPoint`,!1,!1)),d.spatialReference),d.map.add(S),S.add(y);let C=y.sourceLayer,w=C.parent,T=new Map([[x,[]]]),E=new Map,D=new Map,O=await _(n,p,d),k=new Map;for(let e of w.layers)k.set(e.objectType.name,e);let A=new Map;for(let[e,t]of w.sublayerIdsCache)w.dataManager.relationshipTypeNames.has(e)&&A.set(e,Array.from(t));let j=await v(x,C.objectType.name,w.knowledgeGraph,A),M=w.entityLinkChartDiagramLookup.get(x);for(let e of j){let t=E.get(e.id);if(t||(t=w.relationshipLinkChartDiagramLookup.get(e.id),E.set(e.id,t??null)),t){let n=k.get(e.typeName);n&&r(t.coords[0],M.coords[0])&&r(t.coords[1],M.coords[1])?T.get(x)?.push({objectId:e.id,pathIndex:0,vertexIndex:0,associatedSublayer:n}):n&&r(t.coords.at(-2),M.coords[0])&&r(t.coords.at(-1),M.coords[1])&&T.get(x)?.push({objectId:e.id,pathIndex:0,vertexIndex:t.coords.length/2-1,associatedSublayer:n})}}let N=await h.newReshapeWrapper({getFeatureReshapeProvider:e=>new b(e,D,T,d),targetGraphic:y,reshapeGraphicsLayer:S,view:d,snappingManager:f});N.on(`move-stop`,e=>{d.emit(`node-movement-stop`,e)});let P=t(()=>{O.remove(),S.removeAll(),d.map.remove(S),S.destroy(),D.clear(),E.clear(),N.destroy()});return{currentReshapeGraphic:N.graphic,localEdits:D,originalRelationshipGeometries:E,teardownHandle:P}},_=async(e,t,n)=>{let r=await n.whenLayerView(t);return r.setVisibility(e,!1),{remove:()=>r.setVisibility(e,!0)}},v=async(e,t,n,r,i)=>{let a={sourceId:e},o=[],s=[];for(let[e,n]of r){let r=`${e}_ids`;a[r]=n,s.push(`Match (n:${t}) WHERE id(n) = $sourceId WITH n MATCH (n)-[r:${e}]-() WHERE ID(r) IN $${r} RETURN {id: ID(r), typeName: type(r)} as result`)}let c=s.join(` UNION `),l=(await d.executeQueryStreaming(new p(JSON.parse(JSON.stringify(n))),new f({openCypherQuery:c,bindParameters:a}),i)).resultRowsStream.getReader();for(;;){let{done:e,value:t}=await l.read();if(e)break;t.forEach(e=>{o.push(e[0].properties)})}return o};class y{constructor(e,t){this.modifiedFeatures=new Map,this.updating=!1,this._totalDx=0,this._totalDy=0,this._localEditsCache=e,this._view=t}async initializeModifiedFeatures(e){let t=new Map;for(let e of this._view.map?.activeLinkChartLayer?.layers??[]){let n=e;t.set(n.objectType.name,n)}let r=new Map;for(let t of e){let i=this._localEditsCache.get(t.objectId);i?this.initializeModifiedFeature(i,e):n(r,t.associatedSublayer.objectType.name,()=>[]).push(t.objectId)}for(let[n,i]of r){let r=t.get(n),a=r.createQuery();a.outFields=[`ESRI__ID`],a.objectIds=i,r.queryFeatures(a).then(t=>{for(let n of t.features)this.initializeModifiedFeature(this.makeModifiedFeature(n,r),e)})}}makeModifiedFeature(e,t){let n=e.attributes.ESRI__ID,r={graphic:e,layer:t,originalGraphic:e.clone(),uniqueId:n};return this._localEditsCache.set(n,r),r}initializeModifiedFeature(e,t){let n=t.filter(({objectId:t})=>t===e.uniqueId);this.modifiedFeatures.set(e,n);let r=e.graphic.geometry?s(e.graphic.geometry,this._view.spatialReference):void 0,i=e.graphic.sourceLayer,o=i.parent;if(!r&&i.graphType===`relationship`){let t=o.relationshipLinkChartDiagramLookup.get(e.uniqueId);r=s(new a(u(t,`esriGeometryPolyline`,!1,!1)),this._view.spatialReference)}let l=r.clone();for(let{pathIndex:e,vertexIndex:t}of n)l=this.getTranslatedGeometry(r,e,t,this._totalDx,this._totalDy);e.graphic.geometry=s(l,c.WGS84),o.relationshipLinkChartDiagramLookup.get(e.uniqueId)&&(o.relationshipLinkChartDiagramLookup.set(e.uniqueId,null),i.refreshCachedQueryEngine().then(()=>{i.emit(`refresh`,{dataChanged:!0})}))}translate(e,t){this._totalDx+=e,this._totalDy+=t;let n=new Set;for(let[r,i]of this.modifiedFeatures){let o=r.graphic.geometry?s(r.graphic.geometry,this._view.spatialReference):void 0,l=r.graphic.sourceLayer,d=l.parent;if(l&&!r.graphic.geometry&&l.graphType===`relationship`){let e=d.relationshipLinkChartDiagramLookup.get(r.uniqueId);o=s(new a(u(e,`esriGeometryPolyline`,!1,!1)),this._view.spatialReference)}for(let a of i){if(!o)continue;let i=this.getTranslatedGeometry(o,a.pathIndex,a.vertexIndex,e,t);r.graphic.geometry=s(i,c.WGS84),d.relationshipLinkChartDiagramLookup.get(r.uniqueId)&&(d.relationshipLinkChartDiagramLookup.set(r.uniqueId,null),n.add(l))}}for(let e of n)e.refreshCachedQueryEngine().then(()=>{e.emit(`refresh`,{dataChanged:!0})});return Array.from(this.modifiedFeatures.keys())}getTranslatedGeometry(e,t,n,r,i){let a=e.clone(),o=e.paths.slice();return o.at(t)?.at(n)==null||(o[t][n][0]+=r??0,o[t][n][1]+=i??0,a.paths=o),a}}class b extends y{constructor(e,t,n,r){super(t,r),this._connectedVerticesLookup=n;let i=[];for(let t of e){let e=this.getConnectedVerticesForFeature(t);for(let t of e)i.push(t)}this.initializeModifiedFeatures(i)}getConnectedVerticesForFeature(e){return this._connectedVerticesLookup.get(e.graphic.attributes.ESRI__ID)??[]}}export{b as ConnectedFeatureReshapeProvider,g as startNodeMovement,h as wrapperObject};
2
+ import e from"../../core/Error.js";import{makeHandle as t}from"../../core/handleUtils.js";import{getOrCreateMapValue as n}from"../../core/MapUtils.js";import{floatEqualRelative as r}from"../../core/mathUtils.js";import{assertNotMesh as i}from"../../geometry/asserts.js";import a from"../../geometry/Point.js";import o from"../../geometry/Polyline.js";import{initializeProjection as s,project as c}from"../../geometry/projectionUtils.js";import l from"../../geometry/SpatialReference.js";import u from"../GraphicsLayer.js";import{convertToGeometry as d}from"../graphics/featureConversionUtils.js";import{kgRestServices as f}from"../../rest/knowledgeGraphService.js";import p from"../../rest/knowledgeGraph/GraphQueryStreaming.js";import m from"../../rest/knowledgeGraph/KnowledgeGraph.js";import h from"../../views/draw/support/Reshape.js";const g={newReshapeWrapper:async({getFeatureReshapeProvider:e,targetGraphic:t,reshapeGraphicsLayer:n,view:r,snappingManager:i})=>new h({connectedReshapeProviders:[{getFeatureReshapeProvider:e,getVertexReshapeProvider(){throw Error(`Link Charts do not support vertex (polyline) reshape at this time`)}}],enableMidpoints:!1,graphic:t,layer:n,view:r,snappingManager:i})},_=async({targetEntityId:n,targetEntityType:i,view:o,snappingManager:f})=>{await s(l.WGS84,o.spatialReference);let p=o.map?.activeLinkChartLayer?.layers.find(e=>e.objectType.name===i);if(!p)throw new e(`LinkChartView:target-layer-not-found`,`No layer found for target entity type ${i}`);let m=p.createQuery();m.objectIds=[n];let h=await p.queryFeatures(m);if(h.features.length===0)throw new e(`LinkChartView:no-matching-feature-found`,`No feature found with ID ${n} in layer ${p.title}`);let _=h.features[0].clone(),b=_.attributes.ESRI__ID;if(!_.sourceLayer)throw new e(`LinkChartView:no-source-layer`,`The target graphic does not have a source layer: ${b}`);let S=new u({listMode:`hide`,internal:!0});_.geometry=c(new a(d(_.attributes.ESRI__LayoutGeometry,`esriGeometryPoint`,!1,!1)),o.spatialReference),o.map.add(S),S.add(_);let C=_.sourceLayer,w=C.parent,T=new Map([[b,[]]]),E=new Map,D=new Map,O=await v(n,p,o),k=new Map;for(let e of w.layers)k.set(e.objectType.name,e);let A=new Map;for(let[e,t]of w.sublayerIdsCache)w.dataManager.relationshipTypeNames.has(e)&&A.set(e,Array.from(t));let j=await y(b,C.objectType.name,w.knowledgeGraph,A),M=w.entityLinkChartDiagramLookup.get(b);for(let e of j){let t=E.get(e.id);if(t||(t=w.relationshipLinkChartDiagramLookup.get(e.id),E.set(e.id,t??null)),t){let n=k.get(e.typeName);n&&r(t.coords[0],M.coords[0])&&r(t.coords[1],M.coords[1])?T.get(b)?.push({objectId:e.id,pathIndex:0,vertexIndex:0,associatedSublayer:n}):n&&r(t.coords.at(-2),M.coords[0])&&r(t.coords.at(-1),M.coords[1])&&T.get(b)?.push({objectId:e.id,pathIndex:0,vertexIndex:t.coords.length/2-1,associatedSublayer:n})}}let N=await g.newReshapeWrapper({getFeatureReshapeProvider:e=>new x(e,D,T,o),targetGraphic:_,reshapeGraphicsLayer:S,view:o,snappingManager:f});N.on(`move-stop`,e=>{o.emit(`node-movement-stop`,e)});let P=t(()=>{O.remove(),S.removeAll(),o.map.remove(S),S.destroy(),D.clear(),E.clear(),N.destroy()});return{currentReshapeGraphic:N.graphic,localEdits:D,originalRelationshipGeometries:E,teardownHandle:P}},v=async(e,t,n)=>{let r=await n.whenLayerView(t);return r.setVisibility(e,!1),{remove:()=>r.setVisibility(e,!0)}},y=async(e,t,n,r,i)=>{let a={sourceId:e},o=[],s=[];for(let[e,n]of r){let r=`${e}_ids`;a[r]=n,s.push(`Match (n:${t}) WHERE id(n) = $sourceId WITH n MATCH (n)-[r:${e}]-() WHERE ID(r) IN $${r} RETURN {id: ID(r), typeName: type(r)} as result`)}let c=s.join(` UNION `),l=(await f.executeQueryStreaming(new m(JSON.parse(JSON.stringify(n))),new p({openCypherQuery:c,bindParameters:a}),i)).resultRowsStream.getReader();for(;;){let{done:e,value:t}=await l.read();if(e)break;t.forEach(e=>{o.push(e[0].properties)})}return o};class b{constructor(e,t){this.modifiedFeatures=new Map,this.updating=!1,this._totalDx=0,this._totalDy=0,this._localEditsCache=e,this._view=t}async initializeModifiedFeatures(e){let t=new Map;for(let e of this._view.map?.activeLinkChartLayer?.layers??[]){let n=e;t.set(n.objectType.name,n)}let r=new Map;for(let t of e){let i=this._localEditsCache.get(t.objectId);i?this.initializeModifiedFeature(i,e):n(r,t.associatedSublayer.objectType.name,()=>[]).push(t.objectId)}for(let[n,i]of r){let r=t.get(n),a=r.createQuery();a.outFields=[`ESRI__ID`],a.objectIds=i,r.queryFeatures(a).then(t=>{for(let n of t.features)this.initializeModifiedFeature(this.makeModifiedFeature(n,r),e)})}}makeModifiedFeature(e,t){let n=e.attributes.ESRI__ID,r={graphic:e,layer:t,originalGraphic:e.clone(),uniqueId:n};return this._localEditsCache.set(n,r),r}initializeModifiedFeature(e,t){let n=t.filter(({objectId:t})=>t===e.uniqueId);this.modifiedFeatures.set(e,n),i(e.graphic.geometry);let r=e.graphic.geometry?c(e.graphic.geometry,this._view.spatialReference):void 0,a=e.graphic.sourceLayer,s=a.parent;if(!r&&a.graphType===`relationship`){let t=s.relationshipLinkChartDiagramLookup.get(e.uniqueId);r=c(new o(d(t,`esriGeometryPolyline`,!1,!1)),this._view.spatialReference)}let u=r.clone();for(let{pathIndex:e,vertexIndex:t}of n)u=this.getTranslatedGeometry(r,e,t,this._totalDx,this._totalDy);e.graphic.geometry=c(u,l.WGS84),s.relationshipLinkChartDiagramLookup.get(e.uniqueId)&&(s.relationshipLinkChartDiagramLookup.set(e.uniqueId,null),a.refreshCachedQueryEngine().then(()=>{a.emit(`refresh`,{dataChanged:!0})}))}translate(e,t){this._totalDx+=e,this._totalDy+=t;let n=new Set;for(let[r,a]of this.modifiedFeatures){i(r.graphic.geometry);let s=r.graphic.geometry?c(r.graphic.geometry,this._view.spatialReference):void 0,u=r.graphic.sourceLayer,f=u.parent;if(u&&!r.graphic.geometry&&u.graphType===`relationship`){let e=f.relationshipLinkChartDiagramLookup.get(r.uniqueId);s=c(new o(d(e,`esriGeometryPolyline`,!1,!1)),this._view.spatialReference)}for(let i of a){if(!s)continue;let a=this.getTranslatedGeometry(s,i.pathIndex,i.vertexIndex,e,t);r.graphic.geometry=c(a,l.WGS84),f.relationshipLinkChartDiagramLookup.get(r.uniqueId)&&(f.relationshipLinkChartDiagramLookup.set(r.uniqueId,null),n.add(u))}}for(let e of n)e.refreshCachedQueryEngine().then(()=>{e.emit(`refresh`,{dataChanged:!0})});return Array.from(this.modifiedFeatures.keys())}getTranslatedGeometry(e,t,n,r,i){let a=e.clone(),o=e.paths.slice();return o.at(t)?.at(n)==null||(o[t][n][0]+=r??0,o[t][n][1]+=i??0,a.paths=o),a}}class x extends b{constructor(e,t,n,r){super(t,r),this._connectedVerticesLookup=n;let i=[];for(let t of e){let e=this.getConnectedVerticesForFeature(t);for(let t of e)i.push(t)}this.initializeModifiedFeatures(i)}getConnectedVerticesForFeature(e){return this._connectedVerticesLookup.get(e.graphic.attributes.ESRI__ID)??[]}}export{x as ConnectedFeatureReshapeProvider,_ as startNodeMovement,g as wrapperObject};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import t from"../../../core/Error.js";import"../../../core/has.js";import n from"../../../core/Logger.js";import{property as r,subclass as i}from"../../../core/accessorSupport/decorators.js";import a from"../../../geometry/Extent.js";import o from"../../../geometry/Point.js";import s from"../../../geometry/SpatialReference.js";import c from"./BaseRaster.js";import{parse as l}from"./DBFParser.js";import{parsePAMInfo as u,parseSpatialReference as d}from"./pamParser.js";import{parseSignature as f,getPyramidIFDs as p,getMaskIFDs as m,parseIFD as h,parseFieldValues as g,isBSQConfig as _,getTagNumericValues as v,getTagFirstNumericValue as y,getImageInfo as b}from"../formats/tiffParser.js";import{tiffTags as x,geoKeys as S}from"../formats/tiffTag.js";import{estimateStatisticsFromHistograms as C}from"../functions/stretchUtils.js";import w from"../transforms/PolynomialTransform.js";import T from"../../support/RasterInfo.js";import E from"../../support/RasterStorageInfo.js";import D from"../../../rest/support/FeatureSet.js";let O=class extends c{constructor(){super(...arguments),this._files=null,this._headerInfo=null,this._bufferSize=1048576,this._chunkSize=10*1024**2,this.datasetFormat=`TIFF`}async fetchRawTile(e,t,n,r={}){if(!this._headerInfo?.isSupported||this.isBlockOutside(e,t,n))return null;let i=await this._fetchRawTiffTile(e,t,n,!1,r);if(i!=null&&this._headerInfo.hasMaskBand){let a=await this._fetchRawTiffTile(e,t,n,!0,r);a!=null&&a.pixels[0]instanceof Uint8Array&&(i.mask=a.pixels[0])}return i}async _open(e){let r=e?e.signal:null,{data:i}=await this.request(this.url,{range:{from:0,to:this._bufferSize},responseType:`array-buffer`,signal:r});if(!i)throw new t(`tiffraster:open`,`failed to open url `+this.url);this.datasetName=this.url.slice(this.url.lastIndexOf(`/`)+1,this.url.lastIndexOf(`.`));let{littleEndian:a,firstIFDPos:o,isBigTiff:s}=f(i),c=[],l={fileChunk:i,posIFD:o,fileOffset:0};await this._readIFDs(c,l,a,s?8:4,r);let{imageInfo:u,rasterInfo:d}=k(c),h=p(c),g=m(c);if(this._headerInfo={littleEndian:a,isBigTiff:s,ifds:c,pyramidIFDs:h,maskIFDs:g,...u},this._set(`rasterInfo`,d),!u.isSupported)throw new t(`tiffraster:open`,`this tiff is not supported: `+u.message);if(!u.tileWidth)throw new t(`tiffraster:open`,`none-tiled tiff is not optimized for access, convert to COG and retry.`);d.isPseudoSpatialReference&&n.getLogger(this).warn(`The spatial reference for this tiff is unsupported. Only EPSG spatial reference codes and Esri WKTs are supported.`);let _=c[0].get(`PREDICTOR`)?.values?.[0];if(c[0].get(`SAMPLEFORMAT`)?.values?.[0]===3&&_===2)throw new t(`tiffraster:open`,`unsupported horizontal difference encoding. Predictor=3 is supported for floating point data`);let{skipMapInfo:v,skipExtensions:y=[]}=this.ioConfig;if(!y.includes(`aux.xml`)&&!v){let t=await this._fetchAuxiliaryMetaData(e);t!=null&&A(t,d)}!y.includes(`vat.dbf`)&&d.bandCount===1&&d.pixelType===`u8`&&!v&&(d.attributeTable=await this._fetchAuxiliaryTable(e),d.attributeTable!=null&&(d.keyProperties.DataType=`thematic`)),v&&this.updateImageSpaceRasterInfo(d),this.updateTileInfo()}async _validateOrFetchHeaderBuffer(e,t){let{fileChunk:n,fileOffset:r,posIFD:i}=e;return(i+8>=n.byteLength||i<0)&&(r=i+r,n=(await this.request(this.url,{range:{from:r,to:r+this._bufferSize},responseType:`array-buffer`,signal:t})).data,i=0),{fileChunk:n,fileOffset:r,posIFD:i}}async _readIFDs(e,n,r,i=4,a){if(!n.posIFD)return null;n=await this._validateOrFetchHeaderBuffer(n,a);let o=await this._readIFD(n,r,x,i,a);if(!o?.ifd)throw new t(`tiffraster:open`,`cannot parse tiff header. failed to open url `+this.url);if(e.push(o.ifd),!o.nextIFD)return null;n.posIFD=o.nextIFD-n.fileOffset,await this._readIFDs(e,n,r,i,a)}async _readIFD(e,t,n=x,r=4,i){let{fileChunk:a,posIFD:o,fileOffset:s}=e;if(!e.fileChunk)return null;let c=h(a,t,o,s,n,r);if(c.success){let e=[];if(c.ifd?.forEach(t=>{t.values||e.push(t)}),e.length>0&&await this._fillOffsets(e,t,c.nextIFD,i),c.ifd?.has(`GEOKEYDIRECTORY`)){let e=c.ifd.get(`GEOKEYDIRECTORY`),n=e?.values;if(n&&n.length>4){let r=n[0]+`.`+n[1]+`.`+n[2];o=e.valueOffset+6-s;let c=await this._validateOrFetchHeaderBuffer({fileChunk:a,posIFD:o,fileOffset:s},i);e.data=(await this._readIFD(c,t,S,2,i))?.ifd,e.data&&e.data.set(`GEOTIFFVersion`,{id:0,type:2,valueCount:1,valueOffset:null,values:[r]})}}return c}return c.requiredBufferSize?(a=(await this.request(this.url,{range:{from:s,to:s+o+c.requiredBufferSize+8},responseType:`array-buffer`,signal:i})).data,a.byteLength<o+c.requiredBufferSize?null:(e.fileChunk=a,e.fileOffset=s,this._readIFD(e,t,n,r,i))):null}async _fillOffsets(e,t,n,r){let i=e.filter(e=>e.offlineOffsetSize!=null);if(i.length===0)return;let a=i.map(e=>e.offlineOffsetSize),o=Math.min.apply(null,a.map(e=>e[0])),s=Math.max.apply(null,a.map(e=>e[0]+e[1])),c=a.length===1||s-o<=this._bufferSize;if(!c&&a.length>1&&(a.sort((e,t)=>e[0]-t[0]),c=a.reduce((e,t)=>e===t[0]?t[0]+t[1]:0,a[0][0])===s),c){let e=await this._fetchOffsets(o,Math.max(s,o+this._bufferSize),r);i.forEach(n=>g(e,t,n,o));return}let l=i.map(async e=>{let n=e.offlineOffsetSize,i=await this._fetchOffsets(n[0],n[1]+n[0],r);g(i,t,e,n[0])});await Promise.all(l)}async _fetchOffsets(e,t,n){let r=[],i=this._chunkSize,a=Math.ceil((t-e)/i),o=e;for(let e=0;e<a;e++)r.push(this.request(this.url,{range:{from:o,to:e===a-1?t:o+i-1},responseType:`array-buffer`,signal:n})),o+=i;let s=await Promise.all(r);if(a===1)return s[0].data;let c=new Uint8Array(t-e+1);for(let e=0;e<a;e++)c.set(new Uint8Array(s[e].data),e*i);return c.buffer}async _fetchRawTiffTile(e,t,n,r,i={}){let a=this._getTileLocation(e,t,n,r);if(!a)return null;let{ranges:o,actualTileWidth:s,actualTileHeight:c,ifd:l}=a,u=o.map(e=>this.request(this.url,{range:e,responseType:`array-buffer`,signal:i.signal})),d=await Promise.all(u),f=d.map(e=>e.data.byteLength).reduce((e,t)=>e+t),p=d.length===1?d[0].data:new ArrayBuffer(f),m=[0],h=[0];if(d.length>1){let e=new Uint8Array(p);for(let t=0,n=0;t<d.length;t++){let r=d[t].data;e.set(new Uint8Array(r),n),m[t]=n,n+=r.byteLength,h[t]=r.byteLength}}let{blockWidth:g,blockHeight:_}=this.getBlockWidthHeight(e),v=await this.decodePixelBlock(p,{format:`tiff`,customOptions:{headerInfo:this._headerInfo,ifd:l,offsets:m,sizes:h},width:g,height:_,planes:null,pixelType:null});if(v==null)return null;if(s!==g||c!==_){let e=v.mask;if(e)for(let t=0;t<_;t++){let n=t*g;if(t<c)for(let t=s;t<g;t++)e[n+t]=0;else for(let t=0;t<g;t++)e[n+t]=0}else{e=new Uint8Array(g*_),v.mask=e;for(let t=0;t<c;t++){let n=t*g;for(let t=0;t<s;t++)e[n+t]=1}}}return v}_getTileLocation(e,t,n,r=!1){let{firstPyramidLevel:i,blockBoundary:a}=this.rasterInfo.storageInfo,o=e===0?0:e-(i-1),{_headerInfo:s}=this;if(!s)return null;let c=r?s.maskIFDs[o]:o===0?s.ifds[0]:s.pyramidIFDs[o-1];if(!c)return null;let l=_(c,s),u=v(c,`TILEOFFSETS`),d=v(c,`TILEBYTECOUNTS`);if(!u?.length||!d?.length)return null;let{minRow:f,minCol:p,maxRow:m,maxCol:h}=a[o];if(t>m||n>h||t<f||n<p)return null;let g=y(c,`IMAGEWIDTH`),b=y(c,`IMAGELENGTH`),x=y(c,`TILEWIDTH`),S=y(c,`TILELENGTH`),C=[];if(l){let{bandCount:e}=this.rasterInfo;for(let r=0;r<e;r++){let e=r*(m+1)*(h+1)+t*(h+1)+n;C[r]={from:u[e],to:u[e]+d[e]-1}}}else{let e=t*(h+1)+n;C.push({from:u[e],to:u[e]+d[e]-1})}for(let e=0;e<C.length;e++)if(C[e].from==null||!C[e].to||C[e].to<0)return null;return{ranges:C,ifd:c,actualTileWidth:n===h&&g%x||x,actualTileHeight:t===m&&b%S||S}}async _fetchAuxiliaryMetaData(e){try{let{data:t}=await this.request(this.url+`.aux.xml`,{responseType:`xml`,signal:e?.signal});return u(t)}catch{return null}}async _fetchAuxiliaryTable(e){try{let{data:t}=await this.request(this.url+`.vat.dbf`,{responseType:`array-buffer`,signal:e?.signal}),n=l(t);return n?.recordSet?D.fromJSON(n.recordSet):null}catch{return null}}};e([r()],O.prototype,`_files`,void 0),e([r()],O.prototype,`_headerInfo`,void 0),e([r()],O.prototype,`_bufferSize`,void 0),e([r()],O.prototype,`_chunkSize`,void 0),e([r({type:String,json:{write:!0}})],O.prototype,`datasetFormat`,void 0),O=e([i(`esri.layers.raster.datasets.TIFFRaster`)],O);function k(e){let t=b(e),{width:n,height:r,tileWidth:i,tileHeight:c,planes:l,pixelType:u,compression:f,firstPyramidLevel:p,maximumPyramidLevel:m,pyramidBlockWidth:h,pyramidBlockHeight:g,pyramidResolutions:_,tileBoundary:v,affine:y,metadata:x,colormap:S}=t,C=t.extent.spatialReference?.wkt||t.extent.spatialReference?.wkid,D=d(C),O=!!t.isPseudoGeographic;D??=(O=!0,new s({wkid:3857}));let k=new a({...t.extent,spatialReference:D}),A=k?new o({x:k.xmin,y:k.ymax,spatialReference:D}):new o({x:0,y:0}),j=new E({blockWidth:i,blockHeight:c,pyramidBlockWidth:h,pyramidBlockHeight:g,compression:f,origin:A,firstPyramidLevel:p,maximumPyramidLevel:m,pyramidResolutions:_,blockBoundary:v}),M=new o({x:(k.xmax-k.xmin)/n,y:(k.ymax-k.ymin)/r,spatialReference:D}),N=x?{BandProperties:x.bandProperties,DataType:x.dataType}:{},P=new T({width:n,height:r,bandCount:l,pixelType:u,pixelSize:M,storageInfo:j,spatialReference:D,isPseudoSpatialReference:O,keyProperties:N,extent:k,colormap:S,statistics:x?x.statistics:null});if(y?.length&&(P.nativeExtent=new a({xmin:-.5,ymin:.5-r,xmax:n-.5,ymax:.5,spatialReference:D}),P.transform=new w({polynomialOrder:1,forwardCoefficients:[y[2]+y[0]/2,y[5]-y[3]/2,y[0],y[3],-y[1],-y[4]]}),P.extent=P.transform.forwardTransform(P.nativeExtent),P.pixelSize=new o({x:(k.xmax-k.xmin)/n,y:(k.ymax-k.ymin)/r,spatialReference:D}),j.origin.x=-.5,j.origin.y=.5),_){let{x:e,y:t}=P.pixelSize;_.forEach(n=>{n.x*=e,n.y*=t})}return{imageInfo:t,rasterInfo:P}}function A(e,t){if(t.statistics=e.statistics??t.statistics,t.histograms=e.histograms,e.histograms&&t.statistics==null&&(t.statistics=C(e.histograms)),e.transform&&t.transform==null){t.transform=e.transform,t.nativeExtent=t.extent;let n=t.transform.forwardTransform(t.nativeExtent);t.pixelSize=new o({x:(n.xmax-n.xmin)/t.width,y:(n.ymax-n.ymin)/t.height,spatialReference:t.spatialReference}),t.extent=n}t.isPseudoSpatialReference&&e.spatialReference&&(t.spatialReference=e.spatialReference,t.extent.spatialReference=t.nativeExtent.spatialReference=t.storageInfo.origin.spatialReference=t.spatialReference)}const j=O;export{j as default};
2
+ import{__decorate as e}from"tslib";import t from"../../../core/Error.js";import"../../../core/has.js";import n from"../../../core/Logger.js";import{property as r,subclass as i}from"../../../core/accessorSupport/decorators.js";import a from"../../../geometry/Extent.js";import o from"../../../geometry/Point.js";import s from"../../../geometry/SpatialReference.js";import c from"./BaseRaster.js";import{parse as l}from"./DBFParser.js";import{parsePAMInfo as u,parseSpatialReference as d}from"./pamParser.js";import{parseSignature as f,getPyramidIFDs as p,getMaskIFDs as m,parseIFD as h,parseFieldValues as g,isBSQConfig as _,getTagNumericValues as v,getTagFirstNumericValue as y,getImageInfo as b}from"../formats/tiffParser.js";import{tiffTags as x,geoKeys as S}from"../formats/tiffTag.js";import{estimateStatisticsFromHistograms as C}from"../functions/stretchUtils.js";import w from"../transforms/PolynomialTransform.js";import T from"../../support/RasterInfo.js";import E from"../../support/RasterStorageInfo.js";import D from"../../../rest/support/FeatureSet.js";const O=`none-tiled tiff is not optimized for access, convert to COG and retry.`;let k=class extends c{constructor(){super(...arguments),this._files=null,this._headerInfo=null,this._bufferSize=1048576,this._chunkSize=10*1024**2,this.datasetFormat=`TIFF`}async fetchRawTile(e,t,n,r={}){if(!this._headerInfo?.isSupported||this.isBlockOutside(e,t,n))return null;let i=await this._fetchRawTiffTile(e,t,n,!1,r);if(i!=null&&this._headerInfo.hasMaskBand){let a=await this._fetchRawTiffTile(e,t,n,!0,r);a!=null&&a.pixels[0]instanceof Uint8Array&&(i.mask=a.pixels[0])}return i}async _open(e){let r=e?e.signal:null,{data:i}=await this.request(this.url,{range:{from:0,to:this._bufferSize},responseType:`array-buffer`,signal:r});if(!i)throw new t(`tiffraster:open`,`failed to open url `+this.url);this.datasetName=this.url.slice(this.url.lastIndexOf(`/`)+1,this.url.lastIndexOf(`.`));let{littleEndian:a,firstIFDPos:o,isBigTiff:s}=f(i),c=[],l={fileChunk:i,posIFD:o,fileOffset:0};await this._readIFDs(c,l,a,s?8:4,r);let{imageInfo:u,rasterInfo:d}=A(c),h=p(c),g=m(c);if(this._headerInfo={littleEndian:a,isBigTiff:s,ifds:c,pyramidIFDs:h,maskIFDs:g,...u},this._set(`rasterInfo`,d),!u.isSupported)throw new t(`tiffraster:open`,`this tiff is not supported: `+u.message);if(!u.tileWidth||!u.tileHeight)throw new t(`tiffraster:open`,O);d.isPseudoSpatialReference&&n.getLogger(this).warn(`The spatial reference for this tiff is unsupported. Only EPSG spatial reference codes and Esri WKTs are supported.`);let _=c[0].get(`PREDICTOR`)?.values?.[0];if(c[0].get(`SAMPLEFORMAT`)?.values?.[0]===3&&_===2)throw new t(`tiffraster:open`,`unsupported horizontal difference encoding. Predictor=3 is supported for floating point data`);let{skipMapInfo:v,skipExtensions:y=[]}=this.ioConfig;if(!y.includes(`aux.xml`)&&!v){let t=await this._fetchAuxiliaryMetaData(e);t!=null&&j(t,d)}!y.includes(`vat.dbf`)&&d.bandCount===1&&d.pixelType===`u8`&&!v&&(d.attributeTable=await this._fetchAuxiliaryTable(e),d.attributeTable!=null&&(d.keyProperties.DataType=`thematic`)),v&&this.updateImageSpaceRasterInfo(d),this.updateTileInfo()}async _validateOrFetchHeaderBuffer(e,t){let{fileChunk:n,fileOffset:r,posIFD:i}=e;return(i+8>=n.byteLength||i<0)&&(r=i+r,n=(await this.request(this.url,{range:{from:r,to:r+this._bufferSize},responseType:`array-buffer`,signal:t})).data,i=0),{fileChunk:n,fileOffset:r,posIFD:i}}async _readIFDs(e,n,r,i=4,a){if(!n.posIFD)return null;n=await this._validateOrFetchHeaderBuffer(n,a);let o=await this._readIFD(n,r,x,i,a);if(!o?.ifd)throw new t(`tiffraster:open`,`cannot parse tiff header. failed to open url `+this.url);if(e.push(o.ifd),!o.nextIFD)return null;n.posIFD=o.nextIFD-n.fileOffset,await this._readIFDs(e,n,r,i,a)}async _readIFD(e,n,r=x,i=4,a){let{fileChunk:o,posIFD:s,fileOffset:c}=e;if(!e.fileChunk)return null;let l=h(o,n,s,c,r,i);if(l.success){let{ifd:e}=l;if(!e)throw new t(`tiffraster:open`,`cannot parse tiff header. failed to open url `+this.url);if(!this.ioConfig.loadFullMetadata&&r===x&&(!e.has(`TILEWIDTH`)||!e.has(`TILELENGTH`)))throw new t(`tiffraster:open`,O);let i=[];if(e.forEach(e=>{e.values||i.push(e)}),i.length>0&&await this._fillOffsets(i,n,l.nextIFD,a),e.has(`GEOKEYDIRECTORY`)){let t=e.get(`GEOKEYDIRECTORY`),r=t?.values;if(r&&r.length>4){let e=r[0]+`.`+r[1]+`.`+r[2];s=t.valueOffset+6-c;let i=await this._validateOrFetchHeaderBuffer({fileChunk:o,posIFD:s,fileOffset:c},a);t.data=(await this._readIFD(i,n,S,2,a))?.ifd,t.data&&t.data.set(`GEOTIFFVersion`,{id:0,type:2,valueCount:1,valueOffset:null,values:[e]})}}return l}return l.requiredBufferSize?(o=(await this.request(this.url,{range:{from:c,to:c+s+l.requiredBufferSize+8},responseType:`array-buffer`,signal:a})).data,o.byteLength<s+l.requiredBufferSize?null:(e.fileChunk=o,e.fileOffset=c,this._readIFD(e,n,r,i,a))):null}async _fillOffsets(e,t,n,r){let i=e.filter(e=>e.offlineOffsetSize!=null);if(i.length===0)return;let a=i.map(e=>e.offlineOffsetSize),o=Math.min.apply(null,a.map(e=>e[0])),s=Math.max.apply(null,a.map(e=>e[0]+e[1])),c=a.length===1||s-o<=this._bufferSize;if(!c&&a.length>1&&(a.sort((e,t)=>e[0]-t[0]),c=a.reduce((e,t)=>e===t[0]?t[0]+t[1]:0,a[0][0])===s),c){let e=await this._fetchOffsets(o,Math.max(s,o+this._bufferSize),r);i.forEach(n=>g(e,t,n,o));return}let l=i.map(async e=>{let n=e.offlineOffsetSize,i=await this._fetchOffsets(n[0],n[1]+n[0],r);g(i,t,e,n[0])});await Promise.all(l)}async _fetchOffsets(e,t,n){let r=[],i=this._chunkSize,a=Math.ceil((t-e)/i),o=e;for(let e=0;e<a;e++)r.push(this.request(this.url,{range:{from:o,to:e===a-1?t:o+i-1},responseType:`array-buffer`,signal:n})),o+=i;let s=await Promise.all(r);if(a===1)return s[0].data;let c=new Uint8Array(t-e+1);for(let e=0;e<a;e++)c.set(new Uint8Array(s[e].data),e*i);return c.buffer}async _fetchRawTiffTile(e,t,n,r,i={}){let a=this._getTileLocation(e,t,n,r);if(!a)return null;let{ranges:o,actualTileWidth:s,actualTileHeight:c,ifd:l}=a,u=o.map(e=>this.request(this.url,{range:e,responseType:`array-buffer`,signal:i.signal})),d=await Promise.all(u),f=d.map(e=>e.data.byteLength).reduce((e,t)=>e+t),p=d.length===1?d[0].data:new ArrayBuffer(f),m=[0],h=[0];if(d.length>1){let e=new Uint8Array(p);for(let t=0,n=0;t<d.length;t++){let r=d[t].data;e.set(new Uint8Array(r),n),m[t]=n,n+=r.byteLength,h[t]=r.byteLength}}let{blockWidth:g,blockHeight:_}=this.getBlockWidthHeight(e),v=await this.decodePixelBlock(p,{format:`tiff`,customOptions:{headerInfo:this._headerInfo,ifd:l,offsets:m,sizes:h},width:g,height:_,planes:null,pixelType:null});if(v==null)return null;if(s!==g||c!==_){let e=v.mask;if(e)for(let t=0;t<_;t++){let n=t*g;if(t<c)for(let t=s;t<g;t++)e[n+t]=0;else for(let t=0;t<g;t++)e[n+t]=0}else{e=new Uint8Array(g*_),v.mask=e;for(let t=0;t<c;t++){let n=t*g;for(let t=0;t<s;t++)e[n+t]=1}}}return v}_getTileLocation(e,t,n,r=!1){let{firstPyramidLevel:i,blockBoundary:a}=this.rasterInfo.storageInfo,o=e===0?0:e-(i-1),{_headerInfo:s}=this;if(!s)return null;let c=r?s.maskIFDs[o]:o===0?s.ifds[0]:s.pyramidIFDs[o-1];if(!c)return null;let l=_(c,s),u=v(c,`TILEOFFSETS`),d=v(c,`TILEBYTECOUNTS`);if(!u?.length||!d?.length)return null;let{minRow:f,minCol:p,maxRow:m,maxCol:h}=a[o];if(t>m||n>h||t<f||n<p)return null;let g=y(c,`IMAGEWIDTH`),b=y(c,`IMAGELENGTH`),x=y(c,`TILEWIDTH`),S=y(c,`TILELENGTH`),C=[];if(l){let{bandCount:e}=this.rasterInfo;for(let r=0;r<e;r++){let e=r*(m+1)*(h+1)+t*(h+1)+n;C[r]={from:u[e],to:u[e]+d[e]-1}}}else{let e=t*(h+1)+n;C.push({from:u[e],to:u[e]+d[e]-1})}for(let e=0;e<C.length;e++)if(C[e].from==null||!C[e].to||C[e].to<0)return null;return{ranges:C,ifd:c,actualTileWidth:n===h&&g%x||x,actualTileHeight:t===m&&b%S||S}}async _fetchAuxiliaryMetaData(e){try{let{data:t}=await this.request(this.url+`.aux.xml`,{responseType:`xml`,signal:e?.signal});return u(t)}catch{return null}}async _fetchAuxiliaryTable(e){try{let{data:t}=await this.request(this.url+`.vat.dbf`,{responseType:`array-buffer`,signal:e?.signal}),n=l(t);return n?.recordSet?D.fromJSON(n.recordSet):null}catch{return null}}};e([r()],k.prototype,`_files`,void 0),e([r()],k.prototype,`_headerInfo`,void 0),e([r()],k.prototype,`_bufferSize`,void 0),e([r()],k.prototype,`_chunkSize`,void 0),e([r({type:String,json:{write:!0}})],k.prototype,`datasetFormat`,void 0),k=e([i(`esri.layers.raster.datasets.TIFFRaster`)],k);function A(e){let t=b(e),{width:n,height:r,tileWidth:i,tileHeight:c,planes:l,pixelType:u,compression:f,firstPyramidLevel:p,maximumPyramidLevel:m,pyramidBlockWidth:h,pyramidBlockHeight:g,pyramidResolutions:_,tileBoundary:v,affine:y,metadata:x,colormap:S}=t,C=t.extent.spatialReference?.wkt||t.extent.spatialReference?.wkid,D=d(C),O=!!t.isPseudoGeographic;D??=(O=!0,new s({wkid:3857}));let k=new a({...t.extent,spatialReference:D}),A=k?new o({x:k.xmin,y:k.ymax,spatialReference:D}):new o({x:0,y:0}),j=new E({blockWidth:i,blockHeight:c,pyramidBlockWidth:h,pyramidBlockHeight:g,compression:f,origin:A,firstPyramidLevel:p,maximumPyramidLevel:m,pyramidResolutions:_,blockBoundary:v}),M=new o({x:(k.xmax-k.xmin)/n,y:(k.ymax-k.ymin)/r,spatialReference:D}),N=x?{BandProperties:x.bandProperties,DataType:x.dataType}:{},P=new T({width:n,height:r,bandCount:l,pixelType:u,pixelSize:M,storageInfo:j,spatialReference:D,isPseudoSpatialReference:O,keyProperties:N,extent:k,colormap:S,statistics:x?x.statistics:null});if(y?.length&&(P.nativeExtent=new a({xmin:-.5,ymin:.5-r,xmax:n-.5,ymax:.5,spatialReference:D}),P.transform=new w({polynomialOrder:1,forwardCoefficients:[y[2]+y[0]/2,y[5]-y[3]/2,y[0],y[3],-y[1],-y[4]]}),P.extent=P.transform.forwardTransform(P.nativeExtent),P.pixelSize=new o({x:(k.xmax-k.xmin)/n,y:(k.ymax-k.ymin)/r,spatialReference:D}),j.origin.x=-.5,j.origin.y=.5),_){let{x:e,y:t}=P.pixelSize;_.forEach(n=>{n.x*=e,n.y*=t})}return{imageInfo:t,rasterInfo:P}}function j(e,t){if(t.statistics=e.statistics??t.statistics,t.histograms=e.histograms,e.histograms&&t.statistics==null&&(t.statistics=C(e.histograms)),e.transform&&t.transform==null){t.transform=e.transform,t.nativeExtent=t.extent;let n=t.transform.forwardTransform(t.nativeExtent);t.pixelSize=new o({x:(n.xmax-n.xmin)/t.width,y:(n.ymax-n.ymin)/t.height,spatialReference:t.spatialReference}),t.extent=n}t.isPseudoSpatialReference&&e.spatialReference&&(t.spatialReference=e.spatialReference,t.extent.spatialReference=t.nativeExtent.spatialReference=t.storageInfo.origin.spatialReference=t.spatialReference)}const M=k;export{M as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arcgis/core",
3
- "version": "6.0.0-next.5",
3
+ "version": "6.0.0-next.7",
4
4
  "description": "ArcGIS Maps SDK for JavaScript: A complete 2D and 3D mapping and data visualization API",
5
5
  "keywords": [
6
6
  "ArcGIS",
@@ -20,7 +20,7 @@
20
20
  "license": "SEE LICENSE IN LICENSE.md",
21
21
  "dependencies": {
22
22
  "@amcharts/amcharts5": "~5.21.0",
23
- "@arcgis/toolkit": "6.0.0-next.5",
23
+ "@arcgis/toolkit": "6.0.0-next.7",
24
24
  "@esri/arcgis-html-sanitizer": "~4.2.0-next.2",
25
25
  "@esri/calcite-components": "^5.2.0-next.89",
26
26
  "@vaadin/grid": "~25.3.2",