Pipeline.19b42575.js 87 KB

123456789101112
  1. import{al as Pe,gF as Ft,g as ye,gG as Tt,eS as Ae,t as C,c0 as Ee,aB as P,a as y,c7 as Ct,ea as Qe,u as Mt,s as he,h as E,gH as kt,k as oe,gi as Be,c3 as qt,gI as at,gJ as At,N as Re,D as Et,cN as de,bX as le,dL as Rt,e6 as ge,gK as Ut,cV as Ot,gL as $t,cq as Lt,x as Ce,l as B,b5 as nt,m as me,U as Gt,V as Pt,R as Me,gt as Qt,az as ke,gM as ot,gN as ht,aC as Bt,q as qe,b7 as Dt,b2 as De,b6 as ut,gd as zt,ch as dt,aL as te,ce as Ue,gO as jt,eW as ct,eV as lt,b4 as re,gP as ee,ar as gt,cA as pt,ap as ft,gQ as Nt,_ as G,$ as j,a0 as _t,dh as yt,a8 as Vt,ca as Xt,d8 as ue,gR as Yt,bC as Ht,cB as Zt,db as Jt,gS as Wt}from"./index.6c049565.js";import{Y as ze}from"./QueryEngine.05824aeb.js";import{r as Kt,c as mt,u as It,l as es}from"./FeatureStore2D.de2275d3.js";import{s as vt}from"./quantizationUtils.4f3ed95a.js";import{q as je}from"./ogcFeatureUtils.536fc84d.js";import{b as Ne,c as Q,r as ts,v as ss}from"./ComputedAttributeStorage.dc79b701.js";import{s as pe}from"./CircularArray.415a06a8.js";import{createConnection as rs}from"./createConnection.39af598d.js";import{g as ne,f as bt}from"./projectionSupport.2b4a8796.js";import{s as is,a as Ve}from"./visualVariablesUtils.4b17aac7.js";import{Q as z}from"./enums.0295eb81.js";import"./QueryEngineResult.fe74257f.js";import"./WhereClause.39c9a123.js";import"./utils.5216fcae.js";import"./generateRendererUtils.03b1f269.js";import"./utils.9592ea84.js";import"./QueryEngineCapabilities.78217f95.js";import"./timeSupport.4d8d3d9b.js";import"./geojson.eccb99e5.js";import"./clientSideDefaults.e21714f1.js";import"./centroid.0c969b82.js";import"./Utils.e8554a0e.js";import"./enums.2d9e6f64.js";import"./Texture.8e8dfb11.js";import"./VertexElementDescriptor.1fdca6da.js";import"./json.879c9adc.js";import"./visualVariablesUtils.88ca310b.js";function as(a){return a==="heatmap"?Pe(()=>import("./HeatmapProcessor.1289faf1.js"),["assets/HeatmapProcessor.1289faf1.js","assets/index.6c049565.js","assets/index.cf071e35.css","assets/enums.0295eb81.js","assets/BaseProcessor.693ac1c5.js","assets/tileUtils.a1e62810.js"]):Pe(()=>import("./SymbolProcessor.eaa92b93.js"),["assets/SymbolProcessor.eaa92b93.js","assets/index.6c049565.js","assets/index.cf071e35.css","assets/ExpandedCIM.64535143.js","assets/BidiEngine.d8bba3fc.js","assets/enums.0295eb81.js","assets/MaterialKey.bbaab8f1.js","assets/Utils.e8554a0e.js","assets/enums.2d9e6f64.js","assets/Texture.8e8dfb11.js","assets/VertexElementDescriptor.1fdca6da.js","assets/Rect.95b0fd2e.js","assets/quantizationUtils.4f3ed95a.js","assets/GeometryUtils.4f19e772.js","assets/floatRGBA.c5518572.js","assets/visualVariablesUtils.4b17aac7.js","assets/visualVariablesUtils.88ca310b.js","assets/Matcher.d9c9cebd.js","assets/tileUtils.a1e62810.js","assets/TileClipper.7297efa2.js","assets/Geometry.d049a63c.js","assets/GeometryUtils.51c4032a.js","assets/earcut.afc1d357.js","assets/devEnvironmentUtils.d8d0484c.js","assets/BaseProcessor.693ac1c5.js"])}const ve=268435455;class ns{constructor(){this.fieldMap=new Map,this.fields=[],this.hasFeatures=!1,this.exceededTransferLimit=!1,this.fieldCount=0,this.featureCount=0,this.objectIdFieldIndex=0,this.vertexCount=0,this.offsets={attributes:new Array,geometry:new Array},this.centroid=new Array}hasField(e){return this.fieldMap.has(e)}isDateField(e){var t,s;return(s=(t=this.fieldMap.get(e))==null?void 0:t.isDate)!=null?s:!1}getFieldIndex(e){var t;return(t=this.fieldMap.get(e))==null?void 0:t.index}}function os(a){const s=a.asUnsafe(),r=s.getLength(),i=s.pos()+r,n={name:"",isDate:!1};for(;s.pos()<i&&s.next();)switch(s.tag()){case 1:n.name=s.getString();break;case 2:Tt(s.getEnum())==="esriFieldTypeDate"&&(n.isDate=!0);break;default:s.skip()}return n}function hs(a){return a.toLowerCase().trim()}function us(a,e,t=!1){const h=a.asUnsafe(),c=h.pos(),d=new ns;let l=0,g=0;const p=1,f=2,_=4,v=3;let m=null,b=null,I=null,x=!1;for(;h.next();)switch(h.tag()){case 1:m=h.getString();break;case 3:b=h.getString();break;case 12:I=h.processMessage(Ft);break;case 9:if(d.exceededTransferLimit=h.getBool(),d.exceededTransferLimit){d.offsets.geometry=t?new Float64Array(8e3):new Int32Array(8e3),d.centroid=t?new Float64Array(16e3):new Int32Array(16e3);for(let S=0;S<d.centroid.length;S++)d.centroid[S]=ve}break;case 13:{const S=os(a),k=S.name,q=hs(S.name),w={fieldName:k,index:l++,isDate:S.isDate};d.fields.push(w),d.fieldMap.set(S.name,w),d.fieldMap.set(q,w);break}case 15:{const S=h.getLength(),k=h.pos()+S;if(!d.exceededTransferLimit){const w=d.offsets.geometry,T=d.centroid;w.push(0),T.push(ve),T.push(ve)}!x&&d.exceededTransferLimit&&(x=!0,d.offsets.attributes=t?new Float64Array(8e3*l):new Uint32Array(8e3*l));let q=g*l;for(;h.pos()<k&&h.next();)switch(h.tag()){case p:{x?d.offsets.attributes[q++]=h.pos():d.offsets.attributes.push(h.pos());const w=h.getLength();h.skipLen(w);break}case f:if(e){const w=h.getLength(),T=h.pos()+w;for(;h.pos()<T&&h.next();)switch(h.tag()){case v:{h.getUInt32();const M=h.getSInt64(),A=h.getSInt64();d.centroid[2*g]=M,d.centroid[2*g+1]=A;break}default:h.skip()}}else{d.offsets.geometry[g]=h.pos();const w=h.getLength();d.vertexCount+=w,h.skipLen(w)}break;case _:{const w=h.getLength(),T=h.pos()+w;for(;h.pos()<T&&h.next();)switch(h.tag()){case v:{h.getUInt32();const M=h.getSInt64(),A=h.getSInt64();d.centroid[2*g]=M,d.centroid[2*g+1]=A;break}default:h.skip()}break}default:h.skip()}g++,d.hasFeatures=!0;break}default:h.skip()}const F=m||b;if(!F)throw new ye("FeatureSet has no objectId or globalId field name");return d.featureCount=g,d.fieldCount=l,d.objectIdFieldIndex=d.getFieldIndex(F),d.transform=I,d.displayIds=new Uint32Array(d.featureCount),d.groupIds=new Uint16Array(d.featureCount),h.move(c),d}const ds=!0,be=268435455,Xe=128,Ye=128e3,ie={small:{delta:new Int32Array(Xe),decoded:new Int32Array(Xe)},large:{delta:new Int32Array(Ye),decoded:new Int32Array(Ye)}};function He(a){return a<=ie.small.delta.length?ie.small:(a<=ie.large.delta.length||(ie.large.delta=new Int32Array(Math.round(1.25*a)),ie.large.decoded=new Int32Array(Math.round(1.25*a))),ie.large)}function Ze(a){return a.toLowerCase().trim()}function cs(a){try{const t=new Mt(new Uint8Array(a),new DataView(a));for(;t.next();){if(t.tag()===2)return ls(t.getMessage());t.skip()}}catch(e){const t=new ye("query:parsing-pbf","Error while parsing FeatureSet PBF payload",{error:e});he.getLogger("esri.view.2d.layers.features.support.FeatureSetReaderPBF").error(t)}return null}function ls(a){for(;a.next();){if(a.tag()===1)return a.getMessage();a.skip()}return null}function gs(a){const c=a.getLength(),d=a.pos()+c;for(;a.pos()<d&&a.next();)switch(a.tag()){case 1:return a.getString();case 2:return a.getFloat();case 3:return a.getDouble();case 4:return a.getSInt32();case 5:return a.getUInt32();case 6:return a.getInt64();case 7:return a.getUInt64();case 8:return a.getSInt64();case 9:return a.getBool();default:return a.skip(),null}return null}function ps(a,e,t,s,r,i){return .5*Math.abs(a*s+t*i+r*e-a*i-t*e-r*s)}function xe(a,e,t,s){return a*s-t*e===0&&a*t+e*s>0}class fe extends Ne{constructor(e,t,s,r){super(e,r),this._hasNext=!1,this._isPoints=!1,this._featureIndex=-1,this._featureOffset=0,this._cache={area:0,unquantGeometry:void 0,geometry:void 0,centroid:void 0,legacyFeature:void 0,optFeature:void 0},this._geometryType=r.geometryType,this._reader=t,this._header=s,this._hasNext=s.hasFeatures,this._isPoints=r.geometryType==="esriGeometryPoint"}static fromBuffer(e,t,s=!1){const r=t.geometryType,i=cs(e),n=us(i,r==="esriGeometryPoint",s),o=Ne.createInstance();return new fe(o,i,n,t)}get geometryType(){return this._geometryType}get _size(){return this._header.featureCount}get hasZ(){return!1}get hasM(){return!1}get stride(){return 2+(this.hasZ?1:0)+(this.hasM?1:0)}get hasFeatures(){return this._header.hasFeatures}get hasNext(){return this._hasNext}get exceededTransferLimit(){return this._header.exceededTransferLimit}hasField(e){return this._header.hasField(e)||this._header.hasField(Ze(e))}getFieldNames(){return this._header.fields.map(e=>e.fieldName)}getSize(){return this._size}getQuantizationTransform(){return this._header.transform}getCursor(){return this.copy()}getIndex(){return this._featureIndex}setIndex(e){this._cache.area=0,this._cache.unquantGeometry=void 0,this._cache.geometry=void 0,this._cache.centroid=void 0,this._cache.legacyFeature=void 0,this._cache.optFeature=void 0,this._featureIndex=e}getAttributeHash(){let e="";return this._header.fields.forEach(({index:t})=>{e+=this._readAttributeAtIndex(t)+"."}),e}getObjectId(){return this._readAttributeAtIndex(this._header.objectIdFieldIndex)}getDisplayId(){return this._header.displayIds[this._featureIndex]}setDisplayId(e){this._header.displayIds[this._featureIndex]=e}getGroupId(){return this._header.groupIds[this._featureIndex]}setGroupId(e){this._header.groupIds[this._featureIndex]=e}readLegacyFeature(){var e;if(this._cache.legacyFeature===void 0){const t=this.readCentroid(),s={attributes:this.readAttributes(),geometry:this._isPoints?this.readLegacyPointGeometry():this.readLegacyGeometry(),centroid:(e=t&&{x:t.coords[0],y:t.coords[1]})!=null?e:null};return this._cache.legacyFeature=s,s}return this._cache.legacyFeature}readOptimizedFeature(){if(this._cache.optFeature===void 0){const e=new Ae(this.readGeometry(),this.readAttributes(),this.readCentroid());return e.objectId=this.getObjectId(),e.displayId=this.getDisplayId(),this._cache.optFeature=e,e}return this._cache.optFeature}getXHydrated(){const e=this._header.centroid[2*this._featureIndex],t=this.getQuantizationTransform();return C(t)?e:e*t.scale[0]+t.translate[0]}getYHydrated(){const e=this._header.centroid[2*this._featureIndex+1],t=this.getQuantizationTransform();return C(t)?e:t.translate[1]-e*t.scale[1]}getX(){return this._header.centroid[2*this._featureIndex]*this._sx+this._tx}getY(){return this._header.centroid[2*this._featureIndex+1]*this._sy+this._ty}readLegacyPointGeometry(){return{x:this.getX(),y:this.getY()}}readLegacyGeometry(e){const t=this.readGeometry(e);return Ee(t,this.geometryType,!1,!1)}readLegacyCentroid(){const e=this.readCentroid();if(!e)return null;const[t,s]=e.coords;return{x:t,y:s}}readGeometryArea(){return this._cache.area||this.readGeometry(!0),this._cache.area}readUnquantizedGeometry(e=!1){if(this._cache.unquantGeometry===void 0){const t=this.readGeometry(e);if(!t)return this._cache.unquantGeometry=void 0,null;const s=He(t.coords.length).decoded,r=t.clone(s),i=r.coords;let n=0;for(const o of r.lengths){for(let u=1;u<o;u++){const h=2*(n+u),c=2*(n+u-1);i[h]+=i[c],i[h+1]+=i[c+1]}n+=o}return this._cache.unquantGeometry=r,r}return this._cache.unquantGeometry}readHydratedGeometry(){if(this._isPoints){if(this._header.centroid[2*this._featureIndex]===be)return null;const r=this.getXHydrated(),i=this.getYHydrated();return new P([],[r,i])}const e=this.readGeometry();if(!e)return null;const t=e.clone(),s=this.getQuantizationTransform();return y(s)&&Ct(t,t,this.hasZ,this.hasM,s),t}readGeometry(e=!1){if(this._cache.geometry===void 0){let t=null;if(this._isPoints){if(this._header.centroid[2*this._featureIndex]===be)return null;const s=this.getX(),r=this.getY();t=new P([],[s,r])}else{const s=this._header.offsets.geometry[this._featureIndex],r=this._reader;if(s===0){const i=this._readServerCentroid();if(!i)return null;const[n,o]=i.coords;return this.createQuantizedExtrudedQuad(n,o)}r.move(s);try{if(t=e?this._parseGeometryForDisplay(r):this._parseGeometry(r),t===null){const i=this._readServerCentroid();if(!i)return null;const[n,o]=i.coords;return this.createQuantizedExtrudedQuad(n,o)}}catch(i){return console.error("Failed to parse geometry!",i),null}}return this._cache.geometry=t,t}return this._cache.geometry}readCentroid(){if(this._cache.centroid===void 0){let e;return e=this._computeCentroid(),e||(e=this._readServerCentroid()),this._cache.centroid=e!=null?e:void 0,e!=null?e:null}return this._cache.centroid}copy(){const e=this._reader.clone(),t=new fe(this.instance,e,this._header,this.fullSchema());return this.copyInto(t),t}next(){for(this._cache.area=0,this._cache.unquantGeometry=void 0,this._cache.geometry=void 0,this._cache.centroid=void 0,this._cache.legacyFeature=void 0,this._cache.optFeature=void 0;++this._featureIndex<this._size&&!this._getExists(););return this._featureIndex<this._size}_readAttribute(e,t){const s=this._header.hasField(e)?e:Ze(e),r=this._header.getFieldIndex(s);if(r==null)return;const i=this._readAttributeAtIndex(r);return!t||i==null?i:this._header.isDateField(s)?new Date(i):i}_readAttributes(){const e={};return this._header.fields.forEach(({fieldName:t,index:s})=>{e[t]=this._readAttributeAtIndex(s)}),e}copyInto(e){super.copyInto(e),e._featureIndex=this._featureIndex,e._featureOffset=this._featureOffset,e._hasNext=this._hasNext}_readAttributeAtIndex(e){const t=this._header.offsets.attributes[this._featureIndex*this._header.fieldCount+e],s=this._reader;return s.move(t),gs(s)}_readServerCentroid(){const e=this._header.centroid[2*this._featureIndex]+this._tx,t=this._header.centroid[2*this._featureIndex+1]+this._ty;return e===be?null:new P([],[e,t])}_parseGeometry(e){const r=e.asUnsafe(),i=r.getLength(),n=r.pos()+i,o=[],u=[];for(;r.pos()<n&&r.next();)switch(r.tag()){case 2:{const h=r.getUInt32(),c=r.pos()+h;for(;r.pos()<c;)u.push(r.getUInt32());break}case 3:{const h=r.getUInt32(),c=r.pos()+h;for(o.push(r.getSInt32()+this._tx),o.push(r.getSInt32()+this._ty),this.hasZ&&r.getSInt32(),this.hasM&&r.getSInt32();r.pos()<c;)o.push(r.getSInt32()),o.push(r.getSInt32()),this.hasZ&&r.getSInt32(),this.hasM&&r.getSInt32();break}default:r.skip()}return new P(u,o)}_parseGeometryForDisplay(e){const r=e.asUnsafe(),i=r.getLength(),n=r.pos()+i,o=[],u=[];let h=0,c=0,d=null,l=0;const g=this.geometryType==="esriGeometryPolygon";for(;r.pos()<n&&r.next();)switch(r.tag()){case 2:{const p=r.getUInt32(),f=r.pos()+p;for(;r.pos()<f;){const _=r.getUInt32();o.push(_),h+=_}d=He(2*h).delta;break}case 3:{r.getUInt32();const p=2+(this.hasZ?1:0)+(this.hasM?1:0);Qe(d);for(const f of o)if(c+p*f>d.length)for(let _=0;_<f;_++)r.getSInt32(),r.getSInt32(),this.hasZ&&r.getSInt32(),this.hasM&&r.getSInt32();else if(g&&ds){const _=this.getAreaSimplificationThreshold(f,this._header.vertexCount);let v=2,m=1;const b=!1;let I=r.getSInt32(),x=r.getSInt32();d[c++]=I,d[c++]=x,this.hasZ&&r.getSInt32(),this.hasM&&r.getSInt32();let F=r.getSInt32(),S=r.getSInt32();for(this.hasZ&&r.getSInt32(),this.hasM&&r.getSInt32();v<f;){let k=r.getSInt32(),q=r.getSInt32();this.hasZ&&r.getSInt32(),this.hasM&&r.getSInt32();const w=I+F,T=x+S;ps(I,x,w,T,w+k,T+q)>=_?(l+=-.5*(w-I)*(T+x),m>1&&xe(d[c-2],d[c-1],F,S)?(d[c-2]+=F,d[c-1]+=S):(d[c++]=F,d[c++]=S,m++),I=w,x=T):(k+=F,q+=S),F=k,S=q,v++}m<3||b?c-=2*m:(l+=-.5*(I+F-I)*(x+S+x),xe(d[c-2],d[c-1],F,S)?(d[c-2]+=F,d[c-1]+=S,u.push(m)):(d[c++]=F,d[c++]=S,u.push(++m)))}else{let _=0,v=r.getSInt32(),m=r.getSInt32();this.hasZ&&r.getSInt32(),this.hasM&&r.getSInt32(),d[c++]=v,d[c++]=m,_+=1;for(let b=1;b<f;b++){const I=r.getSInt32(),x=r.getSInt32(),F=v+I,S=m+x;l+=-.5*(F-v)*(S+m),this.hasZ&&r.getSInt32(),this.hasM&&r.getSInt32(),b>2&&xe(d[c-2],d[c-1],I,x)?(d[c-2]+=I,d[c-1]+=x):(d[c++]=I,d[c++]=x,_+=1),v=F,m=S}u.push(_)}break}default:r.skip()}if(this._cache.area=l,!u.length)return null;if(this._tx||this._ty){let p=0;Qe(d);for(const f of u)d[2*p]+=this._tx,d[2*p+1]+=this._ty,p+=f}return new P(u,d)}}class Ie{constructor(e){this.service=e}destroy(){}}function fs(a){return Array.isArray(a.source)}function _s(a){return(a==null?void 0:a.type)==="ogc-source"}function ys(a){const{capabilities:e}=a;return _s(a.source)?new xs(a):fs(a)?new Is(a):e.query.supportsFormatPBF&&E("featurelayer-pbf")?new vs(a):new bs(a)}async function ms(a){const e=new At;return await e.open(a,{}),e}class Is extends Ie{constructor(e){super(e),this._portsOpen=ms(e.source).then(t=>this.client=t)}destroy(){this.client.close(),this.client=null}async executeQuery(e,t){await this._portsOpen;const s=await this.client.invoke("queryFeatures",e.toJSON(),t);return Q.fromFeatureSet(s,this.service)}}class vs extends Ie{async executeQuery(e,t){const{data:s}=await kt(this.service.source,e,t),r=!e.quantizationParameters;return fe.fromBuffer(s,this.service,r)}}class bs extends Ie{async executeQuery(e,t){var h;const{source:s,capabilities:r,spatialReference:i,objectIdField:n,geometryType:o}=this.service;if(y(e.quantizationParameters)&&!r.query.supportsQuantization){const c=e.clone(),d=vt(oe(c.quantizationParameters));c.quantizationParameters=null;const{data:l}=await Be(s,c,i,t),g=qt(l,n);return at(d,g),Q.fromOptimizedFeatureSet(g,this.service)}const{data:u}=await Be(s,e,this.service.spatialReference,t);return o==="esriGeometryPoint"&&(u.features=(h=u.features)==null?void 0:h.filter(c=>{if(y(c.geometry)){const d=c.geometry;return Number.isFinite(d.x)&&Number.isFinite(d.y)}return!0})),Q.fromFeatureSet(u,this.service)}}class xs extends Ie{async executeQuery(e,t){const{capabilities:s}=this.service;if(e.quantizationParameters&&!s.query.supportsQuantization){const i=e.clone(),n=vt(oe(i.quantizationParameters));i.quantizationParameters=null;const o=await je(this.service.source,e,t);return at(n,o),Q.fromOptimizedFeatureSet(o,this.service)}const r=await je(this.service.source,e,t);return Q.fromOptimizedFeatureSet(r,this.service)}}class R{constructor(){this.version=0,this.source=!1,this.targets={feature:!1,aggregate:!1},this.storage={filters:!1,data:!1},this.mesh=!1,this.queryFilter=!1,this.why={mesh:[],source:[]}}static create(e){const t=new R;for(const s in e){const r=e[s];if(typeof r=="object")for(const i in r){const n=r[i];t[s][i]=n}t[s]=r}return t}static empty(){return R.create({})}static all(){return R.create({source:!0,targets:{feature:!0,aggregate:!0},storage:{filters:!0,data:!0},mesh:!0})}unset(e){this.version=e.version,e.source&&(this.source=!1),e.targets.feature&&(this.targets.feature=!1),e.targets.aggregate&&(this.targets.aggregate=!1),e.storage.filters&&(this.storage.filters=!1),e.storage.data&&(this.storage.data=!1),e.mesh&&(this.mesh=!1),e.queryFilter&&(this.queryFilter=!1)}any(){return this.source||this.mesh||this.storage.filters||this.storage.data||this.targets.feature||this.targets.aggregate||this.queryFilter}describe(){let e=0,t="";if(this.mesh){e+=20,t+=`-> (20) Mesh needs update
  2. `;for(const r of this.why.mesh)t+=` + ${r}
  3. `}if(this.source){e+=10,t+=`-> (10) The source needs update
  4. `;for(const r of this.why.source)t+=` + ${r}
  5. `}this.targets.feature&&(e+=5,t+=`-> (5) Feature target parameters changed
  6. `),this.storage.filters&&(e+=5,t+=`-> (5) Feature filter parameters changed
  7. `),this.targets.aggregate&&(e+=4,t+=`-> (4) Aggregate target parameters changed
  8. `),this.storage.data&&(e+=1,t+="-> (1) Texture storage parameters changed");const s=e<5?"Fastest":e<10?"Fast":e<15?"Moderate":e<20?"Slow":"Very Slow";console.debug(`Applying ${s} update of cost ${e}/45 `),console.debug(t)}toJSON(){return{queryFilter:this.queryFilter,source:this.source,targets:this.targets,storage:this.storage,mesh:this.mesh}}}class Ss{constructor(e,t){this.requests={done:new Array,stream:new pe(10)},this._edits=null,this._abortController=new AbortController,this._version=0,this._done=!1,this.didSend=!1,this.tile=e,this._version=t}get signal(){return this._abortController.signal}get options(){return{signal:this._abortController.signal}}get empty(){return!this.requests.done.length}get edits(){return this._edits}get done(){return this._done}end(){this._done=!0}clear(){this.requests.done=[]}applyUpdate(e){this.requests.done.forEach(t=>t.message.status.unset(e)),this._version=e.version,y(this._edits)&&this._edits.status.unset(e)}add(e){var t;e.message.status=(t=e.message.status)!=null?t:R.empty(),e.message.status.version=this._version,E("esri-2d-update-debug")&&console.debug(this.tile.id,"DataTileSubscription:add",this._version),e.message.end&&this.requests.done.forEach(s=>{y(s.message)&&s.message.end&&(s.message.end=!1)}),this.requests.done.push(e)}edit(e,t){const s=e.getQuantizationTransform(),r=e.fullSchema(),i=Array.from(e.features()),n=[...t,...i.map(o=>o.objectId)];if(this.removeIds(n),this._invalidate(),C(this._edits))return void(this._edits={type:"append",addOrUpdate:Q.fromOptimizedFeatures(i,r,oe(s)),id:this.tile.id,status:R.empty(),end:!0});this.requests.done.forEach(o=>o.message.end=!1),oe(this._edits.addOrUpdate).append(e.features())}*readers(){for(const{message:e}of this.requests.done)y(e.addOrUpdate)&&(yield e.addOrUpdate);y(this._edits)&&y(this._edits.addOrUpdate)&&(yield this._edits.addOrUpdate)}_invalidate(){for(const e of this.requests.done)e.message.status=R.empty();y(this._edits)&&(this._edits.status=R.empty())}removeIds(e){this._invalidate();for(const{message:t}of this.requests.done){const s=t.addOrUpdate;y(s)&&(s.removeIds(e),s.isEmpty&&(t.addOrUpdate=null))}y(this._edits)&&y(this._edits.addOrUpdate)&&this._edits.addOrUpdate.removeIds(e),this.requests.done=this.requests.done.filter(t=>t.message.addOrUpdate||t.message.end)}abort(){this._abortController.abort()}}function ws(a,e){const t=new Set;return a&&a.forEach(s=>t.add(s)),e&&e.forEach(s=>t.add(s)),t.has("*")?["*"]:Array.from(t)}class xt{constructor(e){this.events=new Re,this._resolver=Et(),this._didEdit=!1,this._subscriptions=new Map,this._outSR=e.outSR,this._serviceInfo=e.serviceInfo,this._onTileUpdateMessage=e.onMessage}destroy(){}async _onMessage(e){var r,i;const t=this._subscriptions.get(e.id);if(!t)return;const s={...e,remove:(r=e.remove)!=null?r:[],status:(i=e.status)!=null?i:R.empty()};return de(this._onTileUpdateMessage(s,t.options))}update(e,t){var u;const s=t.fields.length;t.outFields=ws((u=this._schema)==null?void 0:u.outFields,t.outFields),t.outFields=t.outFields.length>=.75*s?["*"]:t.outFields,t.outFields.sort();const r=le(this._schema,t);if(!r)return;E("esri-2d-update-debug")&&console.debug("Applying Update - Source:",r);const i="orderByFields"in this._serviceInfo&&this._serviceInfo.orderByFields?this._serviceInfo.orderByFields:this._serviceInfo.objectIdField+" ASC",n={returnCentroid:this._serviceInfo.geometryType==="esriGeometryPolygon",returnGeometry:!0,timeReferenceUnknownClient:this._serviceInfo.type!=="stream"&&this._serviceInfo.timeReferenceUnknownClient,outFields:t.outFields,outSpatialReference:this._outSR,orderByFields:[i],where:t.definitionExpression||"1=1",gdbVersion:t.gdbVersion,historicMoment:t.historicMoment,timeExtent:Rt.fromJSON(t.timeExtent)},o=this._schema&&ge(r,"outFields");this._schema&&Ut(r,["timeExtent","definitionExpression","gdbVersion","historicMoment","customParameters"])&&(e.why.mesh.push("Layer filter and/or custom parameters changed"),e.why.source.push("Layer filter and/or custom parameters changed"),e.mesh=!0,e.source=!0,e.queryFilter=!0),o&&(e.why.source.push("Layer required fields changed"),e.source=!0),le(n,this._queryInfo)&&(this._queryInfo=n),this._schema=t,this._resolver.resolve()}whenInitialized(){return this._resolver.promise}async applyUpdate(e){if(e.queryFilter||e.source&&this._didEdit)return this.refresh(e.version),void(this._didEdit=!1);this._subscriptions.forEach(t=>t.applyUpdate(e)),await this.resend()}refresh(e,t){for(const s of this._tiles())this.unsubscribe(s),this.subscribe(s,e)}subscribe(e,t){const s=new Ss(e,t);this._subscriptions.set(e.id,s)}unsubscribe(e){const t=this.get(e.id);y(t)&&t.abort(),this._subscriptions.delete(e.id)}createQuery(e={}){const t=this._queryInfo.historicMoment?new Date(this._queryInfo.historicMoment):null;return new Ot({...this._queryInfo,historicMoment:t,...e})}get(e){return this._subscriptions.has(e)?this._subscriptions.get(e):null}async queryLastEditDate(){throw new Error("Service does not support query type")}async query(e){throw new Error("Service does not support query")}*_tiles(){const e=Array.from(this._subscriptions.values());for(const t of e)yield t.tile}async edit(e,t){const s=Array.from(this._subscriptions.values()),r=s.map(({tile:i})=>i);for(const i of s)i.removeIds(t);if(e.length){const i=r.map(o=>{const u=this.createTileQuery(o);return u.objectIds=e,{tile:o,query:u}}).map(async({tile:o,query:u})=>({tile:o,result:await this.query(u),query:u})),n=(await $t(i)).map(async({tile:o,result:u})=>{if(!u.hasFeatures&&!t.length&&!e.length)return;const h=this._subscriptions.get(o.key.id);h&&h.edit(u,e)});await Lt(n)}this._didEdit=!0}}const Fs=4;class Oe extends xt{constructor(e){super(e),this.type="feature",this.mode="on-demand",this._adapter=ys(e.serviceInfo),this._queue=new Ce({concurrency:8,process:async t=>{if(B(t),y(t.tile)){const s=t.tile.key.id,{signal:r}=t,i=E("esri-tiles-debug")?{tile:s.replace(/\//g,"."),depth:t.depth}:void 0,n=await this._adapter.executeQuery(t.query,{signal:r,query:{...i,...this._schema.customParameters}});return n.level=t.tile.key.level,n}return this._adapter.executeQuery(t.query,{...t,query:this._schema.customParameters})}}),this._patchQueue=new Ce({concurrency:8,process:async t=>{if(B(t),y(t.tile)){const s=t.tile.key.id,{signal:r}=t,i=E("esri-tiles-debug")?{tile:s.replace(/\//g,"."),depth:t.depth}:void 0,n=await this._adapter.executeQuery(t.query,{signal:r,query:{...i,...this._schema.customParameters}});return n.level=t.tile.key.level,n}return this._adapter.executeQuery(t.query,{...t,query:this._schema.customParameters})}})}destroy(){super.destroy(),this._adapter.destroy(),this._queue.destroy(),this._patchQueue.destroy()}get updating(){return!!this._queue.length||Array.from(this._subscriptions.values()).some(e=>!e.done)}get maxRecordCountFactor(){const{query:e}=this._serviceInfo.capabilities;return e.supportsMaxRecordCountFactor?Fs:null}get maxPageSize(){var t;const{query:e}=this._serviceInfo.capabilities;return((t=e.maxRecordCount)!=null?t:8e3)*nt(this.maxRecordCountFactor,1)}get pageSize(){return Math.min(8e3,this.maxPageSize)}enableEvent(e,t){}subscribe(e,t){super.subscribe(e,t);const s=this._subscriptions.get(e.id);this._fetchDataTile(e).catch(r=>{me(r)||he.getLogger("esri.views.2d.layers.features.sources.BaseFeatureSource").error(new ye("mapview-query-error","Encountered error when fetching tile",{tile:e,error:r}))}).then(()=>s.end())}unsubscribe(e){super.unsubscribe(e)}readers(e){return this._subscriptions.get(e).readers()}async query(e){return this._adapter.executeQuery(e,{query:this._schema.customParameters})}async queryLastEditDate(){const e=this._serviceInfo.source,t={...e.query,f:"json"};return(await Gt(e.path,{query:t,responseType:"json"})).data.editingInfo.lastEditDate}createTileQuery(e,t={}){var n;const s=this._serviceInfo.geometryType,r=this.createQuery(t);r.quantizationParameters=(n=t.quantizationParameters)!=null?n:e.getQuantizationParameters(),r.resultType="tile",r.geometry=e.extent,this._serviceInfo.capabilities.query.supportsQuantization?s==="esriGeometryPolyline"&&(r.maxAllowableOffset=e.resolution*E("feature-polyline-generalization-factor")):s!=="esriGeometryPolyline"&&s!=="esriGeometryPolygon"||(r.maxAllowableOffset=e.resolution,s==="esriGeometryPolyline"&&(r.maxAllowableOffset*=E("feature-polyline-generalization-factor")));const i=this._serviceInfo.capabilities.query;return r.defaultSpatialReferenceEnabled=i.supportsDefaultSpatialReference,r.compactGeometryEnabled=i.supportsCompactGeometry,r}async _executePatchQuery(e,t,s,r){const i=t.clone();i.outFields=[this._serviceInfo.objectIdField,...s],i.returnCentroid=!1,i.returnGeometry=!1;const n=y(i.start)?i.start/8e3:0,o=r.signal;return this._patchQueue.push({tile:e,query:i,signal:o,depth:n})}async _resend(e,t){const{query:s,message:r}=e,i=y(s.outFields)?s.outFields:[],n=this._queryInfo.outFields,o=n.filter(u=>!i.includes(u));if(C(r.addOrUpdate))this._onMessage({...r,type:"append"});else if(o.length)try{const u=this._subscriptions.get(r.id).tile,h=await this._executePatchQuery(u,s,o,t);B(t),s.outFields=n,r.addOrUpdate.joinAttributes(h),this._onMessage({...r,end:r.end,type:"append"})}catch{}else this._onMessage({...r,type:"append"})}async _resendSubscription(e){if(E("esri-2d-update-debug")&&console.debug(e.tile.id,"Resend Subscription"),e.empty)return this._onMessage({id:e.tile.id,addOrUpdate:null,end:!1,type:"append"});const t=e.signal;for(const s of e.requests.done)await this._resend(s,{signal:t});return y(e.edits)?this._onMessage(e.edits):void 0}async resend(){const e=Array.from(this._subscriptions.values());await Promise.all(e.map(t=>this._resendSubscription(t)))}}const Je=E("esri-mobile"),We={maxDrillLevel:Je?1:4,maxRecordCountFactor:Je?1:3};class Ts extends Oe{constructor(e){super(e)}async _fetchDataTile(e){const t=this._serviceInfo.capabilities.query.supportsMaxRecordCountFactor,s=this._subscriptions.get(e.key.id),r=s.signal,i=e.getQuantizationParameters();let n=0;const o=async(u,h)=>{const c=this._queryInfo,d=this.createTileQuery(u,{maxRecordCountFactor:t?We.maxRecordCountFactor:void 0,returnExceededLimitFeatures:!1,quantizationParameters:i});n++;try{const l=await this._queue.push({tile:e,query:d,signal:r,depth:h});if(n--,B(r),!l)return;if(c!==this._queryInfo)return void o(u,h);if(l.exceededTransferLimit&&h<We.maxDrillLevel){for(const p of u.createChildTiles())o(p,h+1);return}const g={id:e.id,addOrUpdate:l,end:n===0,type:"append"};s.add({query:d,message:g}),this._onMessage(g)}catch(l){me(l)||this._onMessage({id:e.id,addOrUpdate:null,end:!0,type:"append"})}};o(e,0)}}const Cs="__esri_stream_id__",Ke="__esri_timestamp__",et=1e3;class Ms{constructor(e,t,s,r,i=128){this._trackIdToObservations=new Map,this._idCounter=0,this._lastPurge=performance.now(),this._addOrUpdated=new Map,this._removed=[],this._maxAge=0,this._timeInfo=s,this._purgeOptions=r,this.store=e,this.objectIdField=t,this.purgeInterval=i,this._useGeneratedIds=this.objectIdField===Cs}add(e){if(this._useGeneratedIds){const r=this._nextId();e.attributes[this.objectIdField]=r,e.objectId=r}else e.objectId=e.attributes[this.objectIdField];if(this._addOrUpdated.set(e.objectId,e),this._maxAge=Math.max(this._maxAge,e.attributes[this._timeInfo.startTimeField]),!this._timeInfo.trackIdField)return C(this._trackIdLessObservations)&&(this._trackIdLessObservations=new pe(1e5)),void this._trackIdLessObservations.enqueue(e.objectId);const t=e.attributes[this._timeInfo.trackIdField];if(!this._trackIdToObservations.has(t)){const r=y(this._purgeOptions)&&this._purgeOptions.maxObservations!=null?this._purgeOptions.maxObservations:et,i=Pt(r,0,et);this._trackIdToObservations.set(t,new pe(i))}const s=this._trackIdToObservations.get(t).enqueue(e.objectId);y(s)&&(this._addOrUpdated.has(s)?this._addOrUpdated.delete(s):this._removed.push(s))}checkForUpdates(){const e=this._getToAdd(),t=this._getToRemove(),s=performance.now();s-this._lastPurge>=this.purgeInterval&&(this._purge(s),this._lastPurge=s);const r=[];if(y(t))for(const i of t){const n=this.store.removeById(i);y(n)&&r.push(n)}if(y(e))for(const i of e)i.attributes[Ke]=s,this.store.add(i);(e||(r==null?void 0:r.length))&&this.store.update(e,r)}_getToAdd(){if(!this._addOrUpdated.size)return null;const e=new Array(this._addOrUpdated.size);let t=0;return this._addOrUpdated.forEach(s=>e[t++]=s),this._addOrUpdated.clear(),e}_getToRemove(){const e=this._removed;return this._removed.length?(this._removed=[],e):null}_nextId(){const e=this._idCounter;return this._idCounter=(this._idCounter+1)%4294967294+1,e}_purge(e){const t=this._purgeOptions;y(t)&&(this._purgeSomeByDisplayCount(t),this._purgeByAge(t),this._purgeByAgeReceived(e,t),this._purgeTracks())}_purgeSomeByDisplayCount(e){if(!e.displayCount)return;let t=this.store.size;if(t>e.displayCount){if(this._timeInfo.trackIdField){for(const s of this._trackIdToObservations.values())if(t>e.displayCount&&s.size){const r=oe(s.dequeue());this._removed.push(r),t--}}if(y(this._trackIdLessObservations)){let s=t-e.displayCount;for(;s-- >0;){const r=this._trackIdLessObservations.dequeue();y(r)&&this._removed.push(r)}}}}_purgeByAge(e){var r;if(!e.age||!((r=this._timeInfo)!=null&&r.startTimeField))return;const t=60*e.age*1e3,s=this._maxAge-t;this.store.forEach(i=>{i.attributes[this._timeInfo.startTimeField]<s&&this._removed.push(i.objectId)})}_purgeByAgeReceived(e,t){if(!t.ageReceived)return;const s=e-60*t.ageReceived*1e3;this.store.forEach(r=>{r.attributes[Ke]<s&&this._removed.push(r.objectId)})}_purgeTracks(){this._trackIdToObservations.forEach((e,t)=>{e.size===0&&this._trackIdToObservations.delete(t)})}}const ks=2500;function qs(a,e){const t=a.weakClone();if(y(a.geometry)){const s=ot(e,a.geometry.coords[0]),r=ht(e,a.geometry.coords[1]);t.geometry=new P([],[s,r])}return t}function As(a){return a==="esriGeometryPoint"?qs:(e,t)=>{const s=e.weakClone(),r=new P,i=!1,n=!1,o=ke(r,e.geometry,i,n,a,t,!1,!1);return s.geometry=o,s}}function Es(a){return a==="esriGeometryPoint"?e=>y(e.geometry)?{minX:e.geometry.coords[0],minY:e.geometry.coords[1],maxX:e.geometry.coords[0],maxY:e.geometry.coords[1]}:{minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}:e=>{let t=1/0,s=1/0,r=-1/0,i=-1/0;return y(e.geometry)&&e.geometry.forEachVertex((n,o)=>{t=Math.min(t,n),s=Math.min(s,o),r=Math.max(r,n),i=Math.max(i,o)}),{minX:t,minY:s,maxX:r,maxY:i}}}function Rs(a,e){const t=Bt(9,Es(e));return t.load(a),t}function Us(a,e){return a.search({minX:e.bounds[0],minY:e.bounds[1],maxX:e.bounds[2],maxY:e.bounds[3]})}class Os{constructor(e,t){this.onUpdate=e,this._geometryType=t,this._objectIdToFeature=new Map}get _features(){const e=[];return this._objectIdToFeature.forEach(t=>e.push(t)),e}add(e){this._objectIdToFeature.set(e.objectId,e),this._index=null}get(e){return this._objectIdToFeature.has(e)?this._objectIdToFeature.get(e):null}forEach(e){this._objectIdToFeature.forEach(e)}search(e){return this._index||(this._index=Rs(this._features,this._geometryType)),Us(this._index,e)}removeById(e){const t=this._objectIdToFeature.get(e);return t?(this._objectIdToFeature.delete(e),this._index=null,t):null}update(e,t){this.onUpdate(e,t)}get size(){return this._objectIdToFeature.size}}class $s extends xt{constructor(e){super(e),this.type="geoevent",this._dataReceiveEventEnabled=!1,this._level=0,this._updateInfo={websocket:0,client:0},this._inUpdate=!1;const{outSR:t}=e,{geometryType:s,objectIdField:r,timeInfo:i,purgeOptions:n,source:o,spatialReference:u,serviceFilter:h,maxReconnectionAttempts:c,maxReconnectionInterval:d,updateInterval:l,enableDataReceived:g,customParameters:p}=e.serviceInfo,f=new Os(this._onUpdate.bind(this),s),_=new Ms(f,r,i,n),v=rs(o,u,t,s,h,c,d,p);this._store=f,this._manager=_,this._connection=v,this._quantize=As(s),this._dataReceiveEventEnabled=g,this._handles=[this._connection.on("data-received",m=>this._onFeature(m)),Me(()=>v.connectionStatus,m=>this.events.emit("connectionStatus",m)),Me(()=>v.errorString,m=>this.events.emit("errorString",m))],this._initUpdateInterval=()=>{let m=performance.now();this._updateIntervalId=setInterval(()=>{const b=performance.now(),I=b-m;if(I>ks){m=b;const x=Math.round(this._updateInfo.client/(I/1e3)),F=Math.round(this._updateInfo.websocket/(I/1e3));this._updateInfo.client=0,this._updateInfo.websocket=0,this.events.emit("updateRate",{client:x,websocket:F})}e.canAcceptRequest()&&!this._inUpdate&&this._manager.checkForUpdates()},l)},this._initUpdateInterval()}destroy(){super.destroy(),this._clearUpdateInterval(),this._handles.forEach(e=>e.remove()),this._connection.destroy()}_fetchDataTile(){}pauseStream(){this._clearUpdateInterval()}resumeStream(){this._initUpdateInterval()}enableEvent(e,t){e==="data-received"&&(this._dataReceiveEventEnabled=t)}get updating(){return!1}subscribe(e,t){super.subscribe(e,t);const s=this._subscriptions.get(e.id);this._level=e.level;const r=this._getTileFeatures(e);this._onMessage({type:"append",id:e.key.id,addOrUpdate:r,end:!0}),s.didSend=!0}unsubscribe(e){super.unsubscribe(e)}*readers(e){const t=this._subscriptions.get(e),{tile:s}=t;yield this._getTileFeatures(s);for(const r of t.requests.stream.entries)y(r)&&y(r.addOrUpdate)&&(yield r.addOrUpdate)}createTileQuery(e){throw new Error("Service does not support tile queries")}async resend(){this._subscriptions.forEach(e=>{const{tile:t}=e,s={type:"append",id:t.id,addOrUpdate:this._getTileFeatures(t),end:!0};this._onMessage(s)})}_getTileFeatures(e){const t=this._store.search(e).map(s=>this._quantize(s,e.transform));return Q.fromOptimizedFeatures(t,this._serviceInfo,e.transform)}_onFeature(e){this._updateInfo.websocket++;try{this._dataReceiveEventEnabled&&this.events.emit("data-received",e);const t=Qt(e,this._serviceInfo.geometryType,!1,!1,this._serviceInfo.objectIdField);this._manager.add(t)}catch{}}_clearUpdateInterval(){clearInterval(this._updateIntervalId),this._updateIntervalId=0}async _onUpdate(e,t){this._inUpdate=!0;try{y(e)&&(this._updateInfo.client+=e.length),this._subscriptions.forEach((r,i)=>{r.didSend&&r.tile.level===this._level&&this._onMessage({type:"append",id:i,addOrUpdate:null,clear:!0,end:!1})});const s=[];this._subscriptions.forEach((r,i)=>{if(!r.didSend||r.tile.level!==this._level)return;const n=r.tile,o={type:"append",id:i,addOrUpdate:this._getTileFeatures(n),remove:[],end:!1,status:R.empty()};r.requests.stream.enqueue(o),s.push(this._onMessage(o))}),await Promise.all(s),this._subscriptions.forEach((r,i)=>{r.didSend&&r.tile.level===this._level&&this._onMessage({type:"append",id:i,addOrUpdate:null,end:!0})})}catch{}this._inUpdate=!1}}class Ls extends Oe{constructor(e){super(e)}async _fetchDataTile(e){const r=this._subscriptions.get(e.key.id);let i=!1,n=0,o=0;const u=(d,l)=>{o--,B(r);const g=e.id,p=d.reader,f=d.query;if(!p.exceededTransferLimit){if(i=!0,l!==0&&!p.hasFeatures){const m={id:g,addOrUpdate:p,end:o===0,type:"append"};return r.add({message:m,query:f}),void this._onMessage(m)}const v={id:g,addOrUpdate:p,end:o===0,type:"append"};return r.add({message:v,query:f}),void this._onMessage(v)}const _={id:g,addOrUpdate:p,end:i&&o===0,type:"append"};r.add({message:_,query:f}),this._onMessage(_)};let h=0,c=0;for(;!i&&c++<20;){let d;for(let l=0;l<h+1;l++){const g=n++;o++,d=this._fetchDataTilePage(e,g,r).then(p=>p&&u(p,g)).catch(p=>{i=!0,me(p)||(he.getLogger("esri.views.2d.layers.features.sources.PagedFeatureSource").error(new ye("mapview-query-error","Encountered error when fetching tile",{tile:e,error:p})),this._onMessage({id:e.id,addOrUpdate:null,end:i,type:"append"}))})}await d,B(r),h=Math.min(h+2,6)}}async _fetchDataTilePage(e,t,s){B(s);const r=this._queryInfo,i={start:this.pageSize*t,num:this.pageSize,returnExceededLimitFeatures:!0,quantizationParameters:e.getQuantizationParameters()};y(this.maxRecordCountFactor)&&(i.maxRecordCountFactor=this.maxRecordCountFactor);const n=this.createTileQuery(e,i);try{const o=s.signal,u=await this._queue.push({tile:e,query:n,signal:o,depth:t});return B(s),u?r!==this._queryInfo?this._fetchDataTilePage(e,t,s):{reader:u,query:n}:null}catch(o){return qe(o),null}}}function Gs(a,e,t){const s=a.getXHydrated(),r=a.getYHydrated(),i=e.getColumnForX(s),n=Math.floor(e.normalizeCol(i));return`${t}/${Math.floor(e.getRowForY(r))}/${n}`}function Se(a,e){if(C(a))return null;const t=e.transform,s=a.getQuantizationTransform();if(C(s)){const[_,v]=t.scale,[m,b]=t.translate,I=-m/_,x=1/_,F=b/v,S=1/-v;return a.transform(I,F,x,S)}const[r,i]=s.scale,[n,o]=s.translate,[u,h]=t.scale,[c,d]=t.translate,l=r/u,g=(n-c)/u,p=i/h,f=(-o+d)/h;return a.transform(g,f,l,p)}class Ps extends Oe{constructor(e){super(e),this.mode="snapshot",this._loading=!0,this._controller=new AbortController,this._downloadPromise=null,this._didSendEnd=!1,this._queries=new Array,this._invalidated=!1,this._hasAggregates=!1,this._random=new Dt(1e3),this._store=e.store,this._markedIdsBufId=this._store.storage.createBitset()}destroy(){super.destroy(),this._controller.abort()}get loading(){return this._loading}get _signal(){return this._controller.signal}update(e,t){super.update(e,t),this._featureCount==null&&(this._featureCount=t.initialFeatureCount),y(t.changedFeatureCount)&&(this._featureCount=t.changedFeatureCount),this._hasAggregates=e.targets.aggregate}async resend(e=!1){if(await this._downloadPromise,this._invalidated||e){const s=De(this._featureCount,"Expected featureCount to be defined");return this._invalidated=!1,this._subscriptions.forEach(r=>r.clear()),this._downloadPromise=this._download(s),void await this._downloadPromise}const t=this._queries.map(({query:s,reader:r})=>this._sendPatchQuery(s,r));await Promise.all(t),this._subscriptions.forEach(s=>{s.requests.done.forEach(r=>this._onMessage(r.message))})}async refresh(e,t){t&&(this._featureCount=t.featureCount),await this.resend(!0)}async _sendPatchQuery(e,t){const s=y(e.outFields)?e.outFields:[],r=this._queryInfo.outFields,i=r.filter(h=>!s.includes(h));if(!i.length)return;const n=e.clone(),o=this._signal;n.returnGeometry=!1,n.returnCentroid=!1,n.outFields=i,e.outFields=r;const u=await this._queue.push({query:n,depth:0,signal:o});B({signal:o}),t.joinAttributes(u)}async _fetchDataTile(e){if(!this._downloadPromise){const u=De(this._featureCount,"Expected featureCount to be defined");this._downloadPromise=this._download(u)}const t=this._store.search(e),s=this._subscriptions.get(e.key.id),r=t.length-1;for(let u=0;u<r;u++){const h=Se(t[u],e),c={type:"append",id:e.id,addOrUpdate:h,end:!1,status:R.empty()};s.add({query:null,message:c}),this._hasAggregates||await ut(1),this._onMessage(c)}const i=Se(r>=0?t[r]:null,e),n=this._didSendEnd,o={type:"append",id:e.id,addOrUpdate:i,end:n,status:R.empty()};s.add({query:null,message:o}),this._onMessage(o)}async _download(e){try{await this.whenInitialized();const t=this._store.storage.getBitset(this._markedIdsBufId),s=new Set;t.clear();const r=Math.ceil(e/this.pageSize),i=Array.from({length:r},(n,o)=>o).sort((n,o)=>this._random.getInt()-this._random.getInt()).map(n=>this._downloadPage(n,t,s));await Promise.all(i),this._store.sweepFeatures(t,this._store.storage),this._store.sweepFeatureSets(s)}catch(t){he.getLogger("esri.views.2d.layers.features.sources.SnapshotFeatureSource").error("mapview-snapshot-source","Encountered and error when downloading feature snapshot",t)}this._sendEnd(),this._loading=!1}async _downloadPage(e,t,s){const r=this.pageSize,i={start:e*r,num:r,cacheHint:!0};y(this.maxRecordCountFactor)&&(i.maxRecordCountFactor=this.maxRecordCountFactor);const n=this.createQuery(i),o=this._signal,u=await this._queue.push({query:n,depth:e,signal:o});B({signal:o}),this._queries.push({query:n,reader:u}),this._store.insert(u),s.add(u.instance);const h=u.getCursor();for(;h.next();)t.set(h.getDisplayId());this._send(u)}_send(e){if(!this._subscriptions.size)return;let t=null;const s=new Map,r=new Set,i=new Map;this._subscriptions.forEach(n=>{var l;const o=n.tile;s.set(o.key.id,null),t=o.tileInfoView,r.add(o.level);const{row:u,col:h}=o.key,c=`${o.level}/${u}/${h}`,d=(l=i.get(c))!=null?l:[];d.push(n),i.set(c,d)});for(const n of r){const o=t.getLODInfoAt(n),u=e.getCursor();for(;u.next();){const h=Gs(u,o,n),c=u.getIndex();if(i.has(h))for(const d of i.get(h)){const l=d.tile.id;let g=s.get(l);C(g)&&(g=[],s.set(l,g)),g.push(c)}}}s.forEach((n,o)=>{if(y(n)){const u=this._subscriptions.get(o),h={type:"append",id:o,addOrUpdate:Se(Kt.from(e,n),u.tile),end:!1,status:R.empty()};u.add({query:null,message:h}),this._onMessage(h)}})}_sendEnd(){this._subscriptions.forEach(e=>{const t={type:"append",id:e.tile.id,addOrUpdate:null,end:!0,status:R.empty()};e.add({query:null,message:t}),this._onMessage(t)}),this._didSendEnd=!0}}function Qs(a,e,t,s,r,i){const n=Bs(a,e,t,s,r,i);switch(n.type){case"feature":switch(n.origin){case"hosted":case"local":return new Ls(n);case"snapshot":return new Ps(n);case"unknown":return new Ts(n)}case"geoevent":return new $s(n)}}function Bs(a,e,t,s,r,i){switch(a.type){case"snapshot":return{type:"feature",origin:"snapshot",featureCount:nt(a.featureCount,0),serviceInfo:a,onMessage:s,outSR:e,tileInfoView:t,canAcceptRequest:r,store:i};case"stream":return{type:"geoevent",serviceInfo:a,onMessage:s,outSR:e,canAcceptRequest:r};case"memory":case"on-demand":return{type:"feature",serviceInfo:a,onMessage:s,outSR:e,origin:n(a.source),tileInfoView:t,canAcceptRequest:r}}function n(o){return Array.isArray(o)?"local":"path"in o&&zt(o.path)?"hosted":"unknown"}}function Ds(a,e){let t=-90,s=90,r=-180,i=180;for(let n=0;n<e;n++){const o=Math.ceil((n+1)/2),u=Math.floor((n+1)/2),h=1-n%2,c=30-(3*o+2*u),d=30-(2*o+3*u),l=3*h+2*(1-h),g=2*h+3*(1-h),p=3*h+7*(1-h)<<d,f=(7*h+3*(1-h)<<c&a.geohashX)>>c,_=(p&a.geohashY)>>d;for(let v=l-1;v>=0;v--){const m=(r+i)/2,b=f&1<<v?1:0;r=(1-b)*r+b*m,i=(1-b)*m+b*i}for(let v=g-1;v>=0;v--){const m=(t+s)/2,b=_&1<<v?1:0;t=(1-b)*t+b*m,s=(1-b)*m+b*s}}return[r,t,i,s]}function ce(a,e,t,s){s%2&&(s+=1);let r=0,i=0,n=-90,o=90,u=-180,h=180;for(let c=0;c<s/2;c++){for(let d=0;d<5;d++){const l=(u+h)/2,g=t>l?1:0;r|=g<<29-(d+5*c),u=(1-g)*u+g*l,h=(1-g)*l+g*h}for(let d=0;d<5;d++){const l=(n+o)/2,g=e>l?1:0;i|=g<<29-(d+5*c),n=(1-g)*n+g*l,o=(1-g)*l+g*o}}a.geohashX=r,a.geohashY=i}function _e(a,e,t,s,r){r%2&&(r+=1);let i=0,n=0,o=-90,u=90,h=-180,c=180;for(let d=0;d<r/2;d++){for(let l=0;l<5;l++){const g=(h+c)/2,p=s>g?1:0;i|=p<<29-(l+5*d),h=(1-p)*h+p*g,c=(1-p)*g+p*c}for(let l=0;l<5;l++){const g=(o+u)/2,p=t>g?1:0;n|=p<<29-(l+5*d),o=(1-p)*o+p*g,u=(1-p)*g+p*u}}a[2*e]=i,a[2*e+1]=n}class St{constructor(e=[],t,s=8096){this.onRelease=r=>{},this._nodes=0,this._root=new we(this,0,0,0),this._statisticFields=e,this._pool=s?new pe(8096):null,this._serviceInfo=t}destroy(){this.clear()}_acquire(e,t,s){this._nodes++;let r=null;return y(this._pool)&&(r=this._pool.dequeue()),y(r)?r.realloc(e,t,s):r=new we(this,e,t,s),r}_release(e){this.onRelease(e),this._nodes--,y(this._pool)&&this._pool.enqueue(e)}get count(){return this._root.count}get size(){return this._nodes}get poolSize(){return dt(this._pool,0,e=>e.size)}get depth(){let e=0;return this.forEach(t=>e=Math.max(e,t.depth)),e}dropLevels(e){this.forEach(t=>{if(t.depth>=e)for(let s=0;s<t.children.length;s++){const r=t.children[s];r&&this._release(r)}}),this.forEach(t=>{if(t.depth>=e)for(let s=0;s<t.children.length;s++)t.children[s]=null})}clear(){this.forEach(e=>this._release(e)),this._root=new we(this,0,0,0)}insert(e,t,s=0){const r=Q.fromOptimizedFeatures([e],this._serviceInfo).getCursor();r.next();const i=r.readGeometry();if(!i)return;const[n,o]=i.coords,u=e.geohashX,h=e.geohashY;this.insertCursor(r,e.displayId,n,o,u,h,t,s)}insertCursor(e,t,s,r,i,n,o,u=0){let h=this._root,c=0,d=0,l=0;for(;h!==null;){if(h.depth>=u&&(h.count+=1,h.xTotal+=s,h.yTotal+=r,h.xGeohashTotal+=i,h.yGeohashTotal+=n,h.referenceId=t,this._updateStatisticsCursor(e,h,1)),c>=o)return void h.add(t);const g=Math.ceil((c+1)/2),p=Math.floor((c+1)/2),f=1-c%2,_=30-(3*g+2*p),v=30-(2*g+3*p),m=(i&7*f+3*(1-f)<<_)>>_,b=(n&3*f+7*(1-f)<<v)>>v,I=m+b*(8*f+4*(1-f));d=d<<3*f+2*(1-f)|m,l=l<<2*f+3*(1-f)|b,h.children[I]==null&&(h.children[I]=this._acquire(d,l,c+1)),c+=1,h=h.children[I]}}remove(e,t){const s=Q.fromOptimizedFeatures([e],this._serviceInfo).getCursor();s.next();const r=s.readGeometry();if(!r)return;const[i,n]=r.coords,o=e.geohashX,u=e.geohashY;this.removeCursor(s,i,n,o,u,t)}removeCursor(e,t,s,r,i,n){let o=this._root,u=0;for(;o!==null;){if(o.count-=1,o.xTotal-=t,o.yTotal-=s,o.xGeohashTotal-=r,o.yGeohashTotal-=i,this._updateStatisticsCursor(e,o,-1),u>=n)return void o.remove(e.getDisplayId());const h=Math.ceil((u+1)/2),c=Math.floor((u+1)/2),d=1-u%2,l=30-(3*h+2*c),g=30-(2*h+3*c),p=((r&7*d+3*(1-d)<<l)>>l)+((i&3*d+7*(1-d)<<g)>>g)*(8*d+4*(1-d)),f=o.children[p];(f==null?void 0:f.count)===1&&(this._release(f),o.children[p]=null),u+=1,o=f}}forEach(e){let t=this._root;for(;t!==null;){const s=this._linkChildren(t)||t.next;e(t),t=s}}find(e,t,s){return this._root.find(e,t,s,0,0,0)}findIf(e){let t=null;return this.forEach(s=>{e(s)&&(t=s)}),t}findAllIf(e){const t=[];return this.forEach(s=>{e(s)&&t.push(s)}),t}findSingleOccupancyNode(e,t,s,r,i){let n=this._root;for(;n!==null;){const o=n.depth,u=n.xNode,h=n.yNode,c=1-o%2,d=n.xGeohashTotal/n.count,l=n.yGeohashTotal/n.count;if(n.count===1&&e<d&&d<=s&&t<l&&l<=r)return n;if(o>=i){n=n.next;continue}const g=Math.ceil((o+1)/2),p=Math.floor((o+1)/2),f=30-(3*g+2*p),_=30-(2*g+3*p),v=~((1<<f)-1),m=~((1<<_)-1),b=(e&v)>>f,I=(t&m)>>_,x=(s&v)>>f,F=(r&m)>>_,S=u<<3*c+2*(1-c),k=h<<2*c+3*(1-c),q=S+8*c+4*(1-c),w=k+4*c+8*(1-c),T=Math.max(S,b),M=Math.max(k,I),A=Math.min(q,x),L=Math.min(w,F);let D=null,Y=null;for(let U=M;U<=L;U++)for(let X=T;X<=A;X++){const N=X-S+(U-k)*(8*c+4*(1-c)),O=n.children[N];O&&(D||(D=O,D.next=n.next),Y&&(Y.next=O),Y=O,O.next=n.next)}n=D||n.next}return null}getRegionDisplayIds(e){let t=this._root;const{bounds:s,geohashBounds:r,level:i}=e,[n,o,u,h]=s,c=[];for(;t!==null;){const d=t.depth,l=t.xNode,g=t.yNode;if(d>=i){const N=t.xTotal/t.count,O=t.yTotal/t.count;N>=n&&N<=u&&O>=o&&O<=h&&t.displayIds.forEach(Z=>c.push(Z)),t=t.next;continue}const p=Math.ceil((d+1)/2),f=Math.floor((d+1)/2),_=1-d%2,v=30-(3*p+2*f),m=30-(2*p+3*f),b=~((1<<v)-1),I=~((1<<m)-1),x=(r.xLL&b)>>v,F=(r.yLL&I)>>m,S=(r.xTR&b)>>v,k=(r.yTR&I)>>m,q=l<<3*_+2*(1-_),w=g<<2*_+3*(1-_),T=q+8*_+4*(1-_),M=w+4*_+8*(1-_),A=Math.max(q,x),L=Math.max(w,F),D=Math.min(T,S),Y=Math.min(M,k);let U=null,X=null;for(let N=L;N<=Y;N++)for(let O=A;O<=D;O++){const Z=O-q+(N-w)*(8*_+4*(1-_)),H=t.children[Z];H&&(U||(U=H,U.next=t.next),X&&(X.next=H),X=H,H.next=t.next)}t=U||t.next}return c}getRegionStatistics(e){let t=this._root,s=0,r=0,i=0;const n={},{bounds:o,geohashBounds:u,level:h}=e,[c,d,l,g]=o;let p=0;for(;t!==null;){const f=t.depth,_=t.xNode,v=t.yNode;if(f>=h){const J=t.xTotal/t.count,W=t.yTotal/t.count;J>c&&J<=l&&W>d&&W<=g&&(s+=t.count,r+=t.xTotal,i+=t.yTotal,t.count===1&&(p=t.referenceId),this._aggregateStatistics(n,t.statistics)),t=t.next;continue}const m=Math.ceil((f+1)/2),b=Math.floor((f+1)/2),I=1-f%2,x=30-(3*m+2*b),F=30-(2*m+3*b),S=~((1<<x)-1),k=~((1<<F)-1),q=(u.xLL&S)>>x,w=(u.yLL&k)>>F,T=(u.xTR&S)>>x,M=(u.yTR&k)>>F,A=_<<3*I+2*(1-I),L=v<<2*I+3*(1-I),D=A+8*I+4*(1-I),Y=L+4*I+8*(1-I),U=Math.max(A,q),X=Math.max(L,w),N=Math.min(D,T),O=Math.min(Y,M);let Z=null,H=null;for(let J=X;J<=O;J++)for(let W=U;W<=N;W++){const wt=W-A+(J-L)*(8*I+4*(1-I)),$=t.children[wt];if($){if(J!==X&&J!==O&&W!==U&&W!==N){const Le=$.xTotal/$.count,Ge=$.yTotal/$.count;Le>c&&Le<=l&&Ge>d&&Ge<=g&&(s+=$.count,r+=$.xTotal,i+=$.yTotal,$.count===1&&(p=$.referenceId),this._aggregateStatistics(n,$.statistics));continue}Z||(Z=$,Z.next=t.next),H&&(H.next=$),H=$,$.next=t.next}}t=Z||t.next}return{count:s,attributes:this.normalizeStatistics(n,s),xTotal:r,yTotal:i,referenceId:p}}getBins(e){const t=[],{geohashBounds:s,level:r}=e;let i=this._root;for(;i!==null;){const n=i.depth,o=i.xNode,u=i.yNode;if(n>=r){t.push(i),i=i.next;continue}const h=Math.ceil((n+1)/2),c=Math.floor((n+1)/2),d=1-n%2,l=30-(3*h+2*c),g=30-(2*h+3*c),p=~((1<<l)-1),f=~((1<<g)-1),_=(s.xLL&p)>>l,v=(s.yLL&f)>>g,m=(s.xTR&p)>>l,b=(s.yTR&f)>>g,I=o<<3*d+2*(1-d),x=u<<2*d+3*(1-d),F=I+8*d+4*(1-d),S=x+4*d+8*(1-d),k=Math.max(I,_),q=Math.max(x,v),w=Math.min(F,m),T=Math.min(S,b);let M=null,A=null;for(let L=q;L<=T;L++)for(let D=k;D<=w;D++){const Y=D-I+(L-x)*(8*d+4*(1-d)),U=i.children[Y];U&&(M||(M=U,M.next=i.next),A&&(A.next=U),A=U,U.next=i.next)}i=M||i.next}return t}_linkChildren(e){let t=null,s=null;for(let r=0;r<=e.children.length;r++){const i=e.children[r];i&&(t||(t=i,t.next=e.next),s&&(s.next=i),s=i,i.next=e.next)}return t}_updateStatisticsCursor(e,t,s){var r,i;for(const n of this._statisticFields){const o=n.name,u=n.inField?e.readAttribute(n.inField):e.getComputedNumericAtIndex(n.inFieldIndex);switch(n.statisticType){case"min":{if(isNaN(u))break;if(!t.statistics[o]){t.statistics[o]={value:u};break}const h=t.statistics[o].value;t.statistics[o].value=Math.min(h,u);break}case"max":{if(isNaN(u))break;if(!t.statistics[o]){t.statistics[o]={value:u};break}const h=t.statistics[o].value;t.statistics[o].value=Math.max(h,u);break}case"count":break;case"sum":case"avg":{t.statistics[o]||(t.statistics[o]={value:0,nanCount:0});const h=t.statistics[o].value,c=(r=t.statistics[o].nanCount)!=null?r:0;u==null||isNaN(u)?t.statistics[o].nanCount=c+s:t.statistics[o].value=h+s*u;break}case"avg_angle":{t.statistics[o]||(t.statistics[o]={x:0,y:0,nanCount:0});const h=t.statistics[o].x,c=t.statistics[o].y,d=(i=t.statistics[o].nanCount)!=null?i:0,l=Math.PI/180;u==null||isNaN(u)?t.statistics[o].nanCount=d+s:(t.statistics[o].x=h+s*Math.cos(u*l),t.statistics[o].y=c+s*Math.sin(u*l));break}case"mode":{t.statistics[o]||(t.statistics[o]={});const h=t.statistics[o][u]||0;t.statistics[o][u]=h+s;break}}}}_aggregateStatistics(e,t){for(const s of this._statisticFields){const r=s.name;switch(s.statisticType){case"min":{if(!e[r]){e[r]={value:t[r].value};break}const i=e[r].value;e[r].value=Math.min(i,t[r].value);break}case"max":{if(!e[r]){e[r]={value:t[r].value};break}const i=e[r].value;e[r].value=Math.max(i,t[r].value);break}case"count":break;case"sum":case"avg":case"avg_angle":case"mode":e[r]||(e[r]={});for(const i in t[r]){const n=e[r][i]||0;e[r][i]=n+t[r][i]}}}}normalizeStatistics(e,t){const s={};for(const r of this._statisticFields){const i=r.name;switch(r.statisticType){case"min":case"max":{const n=e[i];if(!t||!n)break;s[i]=n.value;break}case"count":if(!t)break;s[i]=t;break;case"sum":{if(!t)break;const{value:n,nanCount:o}=e[i];if(!(t-o))break;s[i]=n;break}case"avg":{if(!t)break;const{value:n,nanCount:o}=e[i];if(!(t-o))break;s[i]=n/(t-o);break}case"avg_angle":{if(!t)break;const{x:n,y:o,nanCount:u}=e[i];if(!(t-u))break;const h=n/(t-u),c=o/(t-u),d=180/Math.PI,l=Math.atan2(c,h)*d;s[i]=l;break}case"mode":{const n=e[i];let o=0,u=0,h=null;for(const c in n){const d=n[c];d===o?u+=1:d>o&&(o=d,u=1,h=c)}s[i]=h==="null"||u>1?null:h;break}}}return s}}class we{constructor(e,t,s,r){this.count=0,this.xTotal=0,this.yTotal=0,this.statistics={},this.displayId=0,this.referenceId=0,this.displayIds=new Set,this.next=null,this.depth=0,this.xNode=0,this.yNode=0,this.xGeohashTotal=0,this.yGeohashTotal=0,this._tree=e,this.children=new Array(32);for(let i=0;i<this.children.length;i++)this.children[i]=null;this.xNode=t,this.yNode=s,this.depth=r}realloc(e,t,s){for(let r=0;r<this.children.length;r++)this.children[r]=null;return this.xNode=e,this.yNode=t,this.depth=s,this.next=null,this.xGeohashTotal=0,this.yGeohashTotal=0,this.displayId=0,this.referenceId=0,this.xTotal=0,this.yTotal=0,this.count=0,this.statistics={},this.displayIds.clear(),this}get id(){return`${this.xNode}.${this.yNode}`}add(e){this.displayIds.add(e)}remove(e){this.displayIds.delete(e)}getAttributes(){const e=this._tree.normalizeStatistics(this.statistics,this.count);return e.referenceId=null,e.aggregateId=this.id,e.aggregateCount=this.count,e}getGeometry(e,t){const s=this.getLngLatBounds(),[r,i,n,o]=s,u=ne({rings:[[[r,i],[r,o],[n,o],[n,i],[r,i]]]},te.WGS84,e),h=Ue(new P,u,!1,!1);return y(t)?ke(new P,h,!1,!1,"esriGeometryPolygon",t,!1,!1):h}getGeometryCentroid(e,t){const s=this.getLngLatBounds(),[r,i,n,o]=s,u=ne({x:(r+n)/2,y:(i+o)/2},te.WGS84,e),h=jt(new P,u);return y(t)?ke(new P,h,!1,!1,"esriGeometryPoint",t,!1,!1):h}getLngLatBounds(){const e=this.depth,t=Math.ceil(e/2),s=Math.floor(e/2),r=30-(3*t+2*s),i=30-(2*t+3*s),n=this.xNode<<r,o=this.yNode<<i;return Ds({geohashX:n,geohashY:o},this.depth)}find(e,t,s,r,i,n){if(r>=s)return this;const o=1-r%2,u=3*o+2*(1-o),h=2*o+3*(1-o),c=30-i-u,d=30-n-h,l=((e&7*o+3*(1-o)<<c)>>c)+((t&3*o+7*(1-o)<<d)>>d)*(8*o+4*(1-o)),g=this.children[l];return g==null?null:g.find(e,t,s,r+1,i+u,n+h)}}const Fe=he.getLogger("esri.view.2d.layers.features.support.BinStore"),tt=12,zs=64,js=5;function st(a){return 57.29577951308232*a}class Ns extends mt{constructor(e,t,s,r){super(e,s),this.type="bin",this.events=new Re,this.objectIdField="aggregateId",this.featureAdapter=It,this._geohashLevel=js,this._geohashBuf=[],this._serviceInfo=r,this.geometryInfo=e.geometryInfo,this._spatialReference=t,this._projectionSupportCheck=bt(t,te.WGS84),this._bitsets.geohash=s.getBitset(s.createBitset()),this._bitsets.inserted=s.getBitset(s.createBitset())}destroy(){this._tree&&this._tree.destroy()}get featureSpatialReference(){return this._spatialReference}get fields(){return this._fields}async updateSchema(e,t){const s=this._schema;try{await super.updateSchema(e,t),await this._projectionSupportCheck}catch{}this._fields=this._schema.params.fields;const r=le(s,t);t&&(!C(r)||e.source||e.storage.filters)?((ge(r,"params.fields")||ge(r,"params")||!this._tree||e.source)&&(this._tree&&this._tree.destroy(),this._tree=new St(this._statisticFields,this._serviceInfo),this._tree.onRelease=i=>i.displayId&&this._storage.releaseDisplayId(i.displayId),this._geohashLevel=this._schema.params.fixedBinLevel,this._rebuildTree(),E("esri-2d-update-debug")&&Fe.info("Aggregate mesh needs update due to tree changing")),E("esri-2d-update-debug")&&Fe.info("Aggregate mesh needs update due to tree changing"),e.targets[t.name]=!0,e.mesh=!1):s&&(e.mesh=!0)}clear(){this._rebuildTree()}sweepFeatures(e,t){this._bitsets.inserted.forEachSet(s=>{if(!e.has(s)){const r=t.lookupByDisplayIdUnsafe(s);this._remove(r)}})}sweepAggregates(e,t,s){}onTileData(e,t,s,r,i=!0){if(!this._schema||C(t.addOrUpdate))return t;this.events.emit("changed");const n=this._getTransforms(e,this._spatialReference);{const u=t.addOrUpdate.getCursor();for(;u.next();)this._update(u,r)}if(t.status.mesh||!i)return t;const o=new Array;this._getBinsForTile(o,e,n,s),t.addOrUpdate=Q.fromOptimizedFeatures(o,{...this._serviceInfo,geometryType:"esriGeometryPolygon"}),t.addOrUpdate.attachStorage(s),t.end=!0,t.isRepush||(t.clear=!0);{const u=t.addOrUpdate.getCursor();for(;u.next();){const h=u.getDisplayId();this._bitsets.computed.unset(h),this.setComputedAttributes(s,u,h,e.scale)}}return t}forEachBin(e){this._tree.forEach(e)}forEach(e){this._tree.forEach(t=>{if(t.depth!==this._geohashLevel)return;const s=this._toFeatureJSON(t),r=Q.fromFeatures([s],{objectIdField:this.objectIdField,globalIdField:null,geometryType:this.geometryInfo.geometryType,fields:this.fields}).getCursor();r.next(),e(r)})}forEachInBounds(e,t){}forEachBounds(e,t,s){const{hasM:r,hasZ:i}=this.geometryInfo;for(const n of e){const o=ct([0,0,0,0],n.readGeometry(),i,r);C(o)||t(lt(s,o))}}toArray(){const e=[];return this.forEach(t=>e.push(t)),e}onTileUpdate(e){}getAggregate(e){const t=is(e,!0),s=this._tree.findIf(r=>r.displayId===t);return re(s,r=>this._toFeatureJSON(r))}getAggregates(){return this._tree.findAllIf(e=>e.depth===this._geohashLevel).map(this._toFeatureJSON.bind(this))}getDisplayId(e){const t=this._tree.findIf(s=>s.id===e);return re(t,s=>s.displayId)}getFeatureDisplayIdsForAggregate(e){const t=this._tree.findIf(s=>s.id===e);return dt(t,[],s=>Array.from(s.displayIds))}getDisplayIdForReferenceId(e){const t=this._tree.findIf(s=>s.displayIds.size===1&&s.displayIds.has(e));return re(t,s=>s.displayId)}_toFeatureJSON(e){const t=this._spatialReference;return{displayId:e.displayId,attributes:e.getAttributes(),geometry:Ee(e.getGeometry(t),"esriGeometryPolygon",!1,!1),centroid:null}}_rebuildTree(){this._bitsets.computed.clear(),this._bitsets.inserted.clear(),this._tree&&this._tree.clear()}_remove(e){const t=e.getDisplayId(),s=e.getXHydrated(),r=e.getYHydrated(),i=this._geohashBuf[2*t],n=this._geohashBuf[2*t+1];this._bitsets.inserted.has(t)&&(this._bitsets.inserted.unset(t),this._tree.removeCursor(e,s,r,i,n,this._geohashLevel))}_update(e,t){const s=e.getDisplayId(),r=this._bitsets.inserted,i=t.isVisible(s);if(i===r.has(s))return;if(!i)return void this._remove(e);const n=e.getXHydrated(),o=e.getYHydrated();if(!this._setGeohash(s,n,o))return;const u=this._geohashBuf[2*s],h=this._geohashBuf[2*s+1];this._tree.insertCursor(e,s,n,o,u,h,this._geohashLevel),r.set(s)}_setGeohash(e,t,s){if(this._bitsets.geohash.has(e))return!0;const r=this._geohashBuf;if(this._spatialReference.isWebMercator){const i=st(t/ee.radius),n=i-360*Math.floor((i+180)/360),o=st(Math.PI/2-2*Math.atan(Math.exp(-s/ee.radius)));_e(r,e,o,n,tt)}else{const i=ne({x:t,y:s},this._spatialReference,te.WGS84);if(!i)return!1;_e(r,e,i.y,i.x,tt)}return this._bitsets.geohash.set(e),!0}_getBinsForTile(e,t,s,r){try{const i=this._getGeohashBounds(t),n=this._tree.getBins(i);for(const o of n){o.displayId||(o.displayId=r.createDisplayId(!0));let u=null;const h=o.getGeometry(this._spatialReference,s.tile);h||(u=o.getGeometryCentroid(this._spatialReference,s.tile));const c=new Ae(h,o.getAttributes(),u);c.objectId=o.id,c.displayId=o.displayId,e.push(c)}}catch{return void Fe.error("Unable to get bins for tile",t.key.id)}}_getGeohash(e,t,s){const r={geohashX:0,geohashY:0};return ce(r,t,e,s),r}_getGeohashBounds(e){const t=this._getGeohashLevel(e.key.level),s=[e.extent.xmin,e.extent.ymin,e.extent.xmax,e.extent.ymax],r=gt.fromExtent(pt.fromBounds(s,this._spatialReference)),i=ne(r,this._spatialReference,te.WGS84,{densificationStep:e.resolution*zs}),n=Ue(new P,i,!1,!1),o=n.coords.filter((f,_)=>!(_%2)),u=n.coords.filter((f,_)=>_%2),h=Math.min(...o),c=Math.min(...u),d=Math.max(...o),l=Math.max(...u),g=this._getGeohash(h,c,t),p=this._getGeohash(d,l,t);return{bounds:s,geohashBounds:{xLL:g.geohashX,yLL:g.geohashY,xTR:p.geohashX,yTR:p.geohashY},level:t}}_getGeohashLevel(e){return this._schema.params.fixedBinLevel}_getTransforms(e,t){const s={originPosition:"upperLeft",scale:[e.resolution,e.resolution],translate:[e.bounds[0],e.bounds[3]]},r=ft(t);if(!r)return{tile:s,left:null,right:null};const[i,n]=r.valid;return{tile:s,left:{...s,translate:[n,e.bounds[3]]},right:{...s,translate:[i-n+e.bounds[0],e.bounds[3]]}}}}const Te=12,Vs=64,rt=1;class $e extends Nt{constructor(e,t,s,r,i){super(new P([],[t,s]),r,null,e),this.geohashBoundsInfo=i}get count(){return this.attributes.cluster_count}static create(e,t,s,r,i,n,o,u){const h=new $e(t,s,r,n,o);return h.displayId=e.createDisplayId(!0),h.referenceId=u,h.tileLevel=i,h}update(e,t,s,r,i,n){return this.geometry.coords[0]=e,this.geometry.coords[1]=t,this.tileLevel=s,this.attributes=r,this.geohashBoundsInfo=i,this.referenceId=null,this.referenceId=n,this}toJSON(){return{attributes:{...this.attributes,aggregateId:this.objectId,referenceId:this.attributes.cluster_count===1?this.referenceId:null},geometry:{x:this.geometry.coords[0],y:this.geometry.coords[1]}}}}function ae(a){return 57.29577951308232*a}class Xs extends mt{constructor(e,t,s,r){super(e,s),this.type="cluster",this.events=new Re,this.objectIdField="aggregateId",this.featureAdapter=It,this._geohashLevel=0,this._tileLevel=0,this._aggregateValueRanges={},this._aggregateValueRangesChanged=!1,this._geohashBuf=[],this._clusters=new Map,this._tiles=new Map,this._serviceInfo=r,this.geometryInfo=e.geometryInfo,this._spatialReference=t,this._projectionSupportCheck=bt(t,te.WGS84),this._bitsets.geohash=s.getBitset(s.createBitset()),this._bitsets.inserted=s.getBitset(s.createBitset())}destroy(){this._tree.destroy()}get featureSpatialReference(){return this._spatialReference}get fields(){return this._fields}async updateSchema(e,t){const s=this._schema;try{await super.updateSchema(e,t),await this._projectionSupportCheck}catch{}this._fields=this._schema.params.fields;const r=le(s,t);t&&(!C(r)||e.source||e.storage.filters)?((ge(r,"params.fields")||!this._tree||e.source)&&(this._tree&&this._tree.destroy(),this._tree=new St(this._statisticFields,this._serviceInfo),this._rebuildTree(),E("esri-2d-update-debug")&&console.debug("Aggregate mesh needs update due to tree changing")),E("esri-2d-update-debug")&&console.debug("Applying Update - ClusterStore:",r),e.targets[t.name]=!0,e.mesh=!1,this._aggregateValueRanges={}):s&&(e.mesh=!0)}clear(){this._rebuildTree()}sweepFeatures(e,t){this._bitsets.inserted.forEachSet(s=>{if(!e.has(s)){const r=t.lookupByDisplayIdUnsafe(s);this._remove(r)}})}sweepAggregates(e,t,s){this._clusters.forEach((r,i)=>{r&&r.tileLevel!==s&&(e.releaseDisplayId(r.displayId),t.unsetAttributeData(r.displayId),this._clusters.delete(i))})}onTileData(e,t,s,r,i=!0){if(!this._schema||C(t.addOrUpdate))return t;this.events.emit("changed");const n=this._getTransforms(e,this._spatialReference);{const h=t.addOrUpdate.getCursor();for(;h.next();)this._update(h,r)}if(t.status.mesh||!i)return t;const o=new Array,u=this._schema.params.clusterRadius;this._getClustersForTile(o,e,u,s,n),t.addOrUpdate=Q.fromOptimizedFeatures(o,this._serviceInfo),t.addOrUpdate.attachStorage(s),t.clear=!0,t.end=!0;{const h=t.addOrUpdate.getCursor();for(;h.next();){const c=h.getDisplayId();this._bitsets.computed.unset(c),this.setComputedAttributes(s,h,c,e.scale)}}return this._aggregateValueRangesChanged&&t.end&&(this.events.emit("valueRangesChanged",{valueRanges:this._aggregateValueRanges}),this._aggregateValueRangesChanged=!1),t}onTileUpdate({added:e,removed:t}){if(e.length){const r=e[0].level;this._tileLevel=r,this._setGeohashLevel(r)}if(!this._schema)return;const s=this._schema.params.clusterRadius;t.forEach(r=>{this._tiles.delete(r.key.id),this._markTileClustersForDeletion(r,s)})}getAggregate(e){for(const t of this._clusters.values())if(((t==null?void 0:t.displayId)&Ve)==(e&Ve))return t.toJSON();return null}getAggregates(){const e=[];for(const t of this._clusters.values())(t==null?void 0:t.tileLevel)===this._tileLevel&&e.push(t.toJSON());return e}getDisplayId(e){const t=this._clusters.get(e);return t?t.displayId:null}getFeatureDisplayIdsForAggregate(e){const t=this._clusters.get(e);return t?this._tree.getRegionDisplayIds(t.geohashBoundsInfo):[]}getDisplayIdForReferenceId(e){for(const t of this._clusters.values())if((t==null?void 0:t.referenceId)===e)return t.displayId;return null}getAggregateValueRanges(){return this._aggregateValueRanges}forEach(e){this._clusters.forEach(t=>{if(!t)return;const s=t.toJSON(),r=Q.fromFeatures([s],{objectIdField:this.objectIdField,globalIdField:null,geometryType:this.geometryInfo.geometryType,fields:this.fields}).getCursor();r.next(),e(r)})}forEachInBounds(e,t){}forEachBounds(e,t,s){const{hasM:r,hasZ:i}=this.geometryInfo;for(const n of e){const o=ct([0,0,0,0],n.readGeometry(),i,r);C(o)||t(lt(s,o))}}toArray(){const e=[];return this.forEach(t=>e.push(t)),e}size(){let e=0;return this.forEach(t=>e++),e}_rebuildTree(){this._bitsets.computed.clear(),this._bitsets.inserted.clear(),this._tree&&this._tree.clear()}_remove(e){const t=e.getDisplayId(),s=e.getXHydrated(),r=e.getYHydrated(),i=this._geohashBuf[2*t],n=this._geohashBuf[2*t+1];this._bitsets.inserted.has(t)&&(this._bitsets.inserted.unset(t),this._tree.removeCursor(e,s,r,i,n,this._geohashLevel))}_update(e,t){const s=e.getDisplayId(),r=this._bitsets.inserted,i=t.isVisible(s);if(i===r.has(s))return;if(!i)return void this._remove(e);const n=e.getXHydrated(),o=e.getYHydrated();if(!this._setGeohash(s,n,o))return;const u=this._geohashBuf[2*s],h=this._geohashBuf[2*s+1];this._tree.insertCursor(e,s,n,o,u,h,this._geohashLevel),r.set(s)}_setGeohash(e,t,s){if(this._bitsets.geohash.has(e))return!0;const r=this._geohashBuf;if(this._spatialReference.isWebMercator){const i=ae(t/ee.radius),n=i-360*Math.floor((i+180)/360),o=ae(Math.PI/2-2*Math.atan(Math.exp(-s/ee.radius)));_e(r,e,o,n,Te)}else{const i=ne({x:t,y:s},this._spatialReference,te.WGS84);if(!i)return!1;_e(r,e,i.y,i.x,Te)}return this._bitsets.geohash.set(e),!0}_getClustersForTile(e,t,s,r,i,n=!0){const o=this._schema.params.clusterPixelBuffer,u=2*s,h=Math.ceil(2**t.key.level*z/u)+1,c=Math.ceil(o/u)+0,d=Math.ceil(z/u),{row:l,col:g}=t.key,p=g*z,f=l*z,_=Math.floor(p/u)-c,v=Math.floor(f/u)-c,m=_+d+2*c,b=v+d+2*c,I=t.tileInfoView.getLODInfoAt(t.key.level);for(let x=_;x<=m;x++)for(let F=v;F<=b;F++){let S=x;I.wrap&&(S=x<0?x+h:x%h);const k=I.wrap&&x<0,q=I.wrap&&x%h!==x,w=this._lookupCluster(r,I,t.key.level,S,F,t);if(y(w)){const T=re(i,M=>k?M.left:q?M.right:M.tile);if(n&&C(T)||!w.count)continue;if(y(T)&&n){const M=w.geometry.clone();let A=w.attributes;M.coords[0]=ot(T,M.coords[0]),M.coords[1]=ht(T,M.coords[1]),w.count===1&&y(w.referenceId)&&(A={...w.attributes,referenceId:w.referenceId});const L=new Ae(M,A);L.displayId=w.displayId,e.push(L)}}}}_getGeohashLevel(e){return Math.min(Math.ceil(e/2+2),Te)}_setGeohashLevel(e){const t=this._getGeohashLevel(e),s=(Math.floor(t/rt)+1)*rt-1;if(this._geohashLevel!==s)return this._geohashLevel=s,this._rebuildTree(),void this._bitsets.geohash.clear()}_getTransforms(e,t){const s={originPosition:"upperLeft",scale:[e.resolution,e.resolution],translate:[e.bounds[0],e.bounds[3]]},r=ft(t);if(!r)return{tile:s,left:null,right:null};const[i,n]=r.valid;return{tile:s,left:{...s,translate:[n,e.bounds[3]]},right:{...s,translate:[i-n+e.bounds[0],e.bounds[3]]}}}_getClusterId(e,t,s){return(15&e)<<28|(16383&t)<<14|16383&s}_markForDeletion(e,t,s){const r=this._getClusterId(e,t,s);this._clusters.delete(r)}_getClusterBounds(e,t,s){const r=this._schema.params.clusterRadius,i=2*r;let n=s%2?t*i:t*i-r;const o=s*i;let u=n+i;const h=o-i,c=2**e.level*z;e.wrap&&n<0&&(n=0),e.wrap&&u>c&&(u=c);const d=n/z,l=o/z,g=u/z,p=h/z;return[e.getXForColumn(d),e.getYForRow(l),e.getXForColumn(g),e.getYForRow(p)]}_getGeohash(e,t,s){const r={geohashX:0,geohashY:0};return ce(r,t,e,s),r}_getGeohashBounds(e,t){const s=this._getGeohashLevel(e.key.level);if(this._spatialReference.isWebMercator){const[f,_,v,m]=t,b={x:f,y:_},I={x:v,y:m};let x=0,F=0,S=0,k=0;{const T=ae(b.x/ee.radius);x=T-360*Math.floor((T+180)/360),F=ae(Math.PI/2-2*Math.atan(Math.exp(-b.y/ee.radius)))}{const T=ae(I.x/ee.radius);S=T-360*Math.floor((T+180)/360),k=ae(Math.PI/2-2*Math.atan(Math.exp(-I.y/ee.radius)))}const q={geohashX:0,geohashY:0},w={geohashX:0,geohashY:0};return ce(q,F,x,s),ce(w,k,S,s),{bounds:[f,_,v,m],geohashBounds:{xLL:q.geohashX,yLL:q.geohashY,xTR:w.geohashX,yTR:w.geohashY},level:s}}const r=gt.fromExtent(pt.fromBounds(t,this._spatialReference)),i=ne(r,this._spatialReference,te.WGS84,{densificationStep:e.resolution*Vs});if(!i)return null;const n=Ue(new P,i,!1,!1),o=n.coords.filter((f,_)=>!(_%2)),u=n.coords.filter((f,_)=>_%2),h=Math.min(...o),c=Math.min(...u),d=Math.max(...o),l=Math.max(...u),g=this._getGeohash(h,c,s),p=this._getGeohash(d,l,s);return{bounds:t,geohashBounds:{xLL:g.geohashX,yLL:g.geohashY,xTR:p.geohashX,yTR:p.geohashY},level:s}}_lookupCluster(e,t,s,r,i,n){const o=this._getClusterId(s,r,i),u=this._clusters.get(o),h=this._getClusterBounds(t,r,i),c=this._getGeohashBounds(n,h);if(C(c))return null;const d=this._tree.getRegionStatistics(c),{count:l,xTotal:g,yTotal:p,referenceId:f}=d,_=l?g/l:0,v=l?p/l:0;if(l===0)return this._clusters.set(o,null),null;const m={cluster_count:l,...d.attributes},b=y(u)?u.update(_,v,s,m,c,f):$e.create(e,o,_,v,s,m,c,f);if(l===0){const[I,x,F,S]=h;b.geometry.coords[0]=(I+F)/2,b.geometry.coords[1]=(x+S)/2}return this._clusters.set(o,b),this._updateAggregateValueRangeForCluster(b,b.tileLevel),b}_updateAggregateValueRangeForCluster(e,t){const s=this._aggregateValueRanges[t]||{minValue:1/0,maxValue:0},r=s.minValue,i=s.maxValue;s.minValue=Math.min(r,e.count),s.maxValue=Math.max(i,e.count),this._aggregateValueRanges[t]=s,r===s.minValue&&i===s.maxValue||(this._aggregateValueRangesChanged=!0)}_markTileClustersForDeletion(e,t){const s=2*t,r=Math.ceil(z/s),{row:i,col:n}=e.key,o=n*z,u=i*z,h=Math.floor(o/s),c=Math.floor(u/s);for(let d=h;d<h+r;d++)for(let l=c;l<c+r;l++)this._markForDeletion(e.key.level,d,l)}}const Ys=5e3,Hs="tileRenderer.featuresView.attributeView.initialize",Zs="tileRenderer.featuresView.attributeView.requestUpdate",Js="tileRenderer.featuresView.requestRender";function Ws(a){return a.name==="worker:port-closed"}function K(a){if(!me(a)&&!Ws(a))throw a}function it(a){return a.type==="feature"&&a.mode==="snapshot"}let V=class extends yt{constructor(){super(...arguments),this._storage=new ts,this._markedIdsBufId=this._storage.createBitset(),this._lastCleanup=performance.now(),this._cleanupNeeded=!1,this._invalidated=!1,this._tileToResolver=new Map,this._didEdit=!1,this._updateVersion=1,this.tileStore=null,this.config=null,this.processor=null,this.remoteClient=null,this.service=null}initialize(){this._initStores(),this._initSource(),this._updateQueue=new Ce({concurrency:this._source.type==="geoevent"?1:4,process:(a,e)=>this._onTileMessage(a,{signal:e})}),this.handles.add([this.tileStore.on("update",this.onTileUpdate.bind(this)),Vt(()=>!this.updating,()=>this.onIdle())]),this._checkUpdating=setInterval(()=>this.notifyChange("updating"),300)}_initSource(){const a=this.tileStore.tileScheme,e=()=>this._updateQueue.length<50,t=(s,r)=>(this._invalidated=!0,this._patchTile(s,r));this._source=Qs(this.service,this.spatialReference,a,t,e,this.featureStore),this._proxyEvents()}_proxyEvents(){if(this._source.type==="geoevent"){const a=this._source.events;this.handles.add([a.on("connectionStatus",e=>this.remoteClient.invoke("setProperty",{propertyName:"connectionStatus",value:e}).catch(K)),a.on("errorString",e=>this.remoteClient.invoke("setProperty",{propertyName:"errorString",value:e}).catch(K)),a.on("data-received",e=>this.remoteClient.invoke("emitEvent",{name:"data-received",event:{attributes:e.attributes,centroid:e.centroid,geometry:e.geometry}}).catch(K)),a.on("updateRate",e=>this.remoteClient.invoke("emitEvent",{name:"update-rate",event:{...e}}).catch(K))])}}_initAttributeStore(a){this.attributeStore||(this.attributeStore=new ss({type:"remote",initialize:(e,t)=>de(this.remoteClient.invoke(Hs,e,{signal:t}).catch(K)),update:(e,t)=>de(this.remoteClient.invoke(Zs,e,{signal:t}).catch(K)),render:e=>de(this.remoteClient.invoke(Js,void 0,{signal:e}).catch(K))},a,()=>this.notifyChange("updating")))}_initStores(){const a=this.service.type==="snapshot"?"snapshot":"on-demand",e={geometryInfo:{geometryType:this.service.geometryType,hasM:!1,hasZ:!1},spatialReference:this.spatialReference,fieldsIndex:this.fieldsIndex,fields:this.service.fields};this.featureStore=new es(e,this._storage,a)}_initQueryEngine(a){var t;const e=this;(t=this.featureQueryEngine)==null||t.destroy(),this.featureQueryEngine=new ze({definitionExpression:a.schema.source.definitionExpression,fields:this.service.fields,geometryType:this.service.geometryType,objectIdField:this.service.objectIdField,hasM:!1,hasZ:!1,spatialReference:this.spatialReference.toJSON(),cacheSpatialQueries:!0,featureStore:this.featureStore,aggregateAdapter:{getFeatureObjectIds(s){return C(e.aggregateStore)?[]:e.aggregateStore.getFeatureDisplayIdsForAggregate(s).map(r=>e.getObjectId(r))}},timeInfo:this.service.timeInfo})}_initAggregateQueryEngine(a,e){var s;if((s=this.aggregateQueryEngine)==null||s.destroy(),C(a))return;const t=e.targets.aggregate.params.fields.slice();this.aggregateQueryEngine=new ze({definitionExpression:null,fields:t,geometryType:a.geometryInfo.geometryType,objectIdField:a.objectIdField,hasM:a.geometryInfo.hasM,hasZ:a.geometryInfo.hasZ,spatialReference:this.spatialReference.toJSON(),cacheSpatialQueries:!1,featureStore:a,aggregateAdapter:{getFeatureObjectIds:r=>[]}})}destroy(){var a,e,t;this._updateQueue.destroy(),this._source.destroy(),(a=this.featureQueryEngine)==null||a.destroy(),(e=this.aggregateQueryEngine)==null||e.destroy(),(t=this.attributeStore)==null||t.destroy();for(const s of this.tileStore.tiles)this._source.unsubscribe(s);clearInterval(this._checkUpdating)}get fieldsIndex(){return new Xt(this.service.fields)}get spatialReference(){return this.tileStore.tileScheme.spatialReference}get updating(){return this.isUpdating()}isUpdating(){const a=this._source.updating,e=!!this._updateQueue.length,t=!this.attributeStore||this.attributeStore.isUpdating(),s=a||e||t;return E("esri-2d-log-updating")&&console.log(`Updating FeatureController2D: ${s}
  9. -> updatingSource ${a}
  10. -> updateQueue ${e}
  11. -> updatingAttributeStore ${t}
  12. `),s}enableEvent(a){this._source.enableEvent(a.name,a.value)}pause(){this._updateQueue.pause(),this._updateQueue.clear()}resume(){this._updateQueue.resume()}pauseStream(){this._source.type==="geoevent"&&this._source.pauseStream()}resumeStream(){this._source.type==="geoevent"&&this._source.resumeStream()}_initAggregateStore(a){var s,r;const e=(r=(s=a.schema.targets)==null?void 0:s.aggregate)==null?void 0:r.type;if(re(this.config,i=>{var n,o;return(o=(n=i.schema.targets)==null?void 0:n.aggregate)==null?void 0:o.type})!==e&&(y(this.aggregateStore)&&(this.handles.remove("valueRangesChanged"),this.aggregateStore.destroy(),this.aggregateStore=null),e)){switch(e){case"cluster":{const i={geometryInfo:{geometryType:"esriGeometryPoint",hasM:!1,hasZ:!1},spatialReference:this.spatialReference,fieldsIndex:this.fieldsIndex,fields:this.service.fields};this.aggregateStore=new Xs(i,this.spatialReference,this._storage,this.service),this.handles.add(this.aggregateStore.events.on("valueRangesChanged",n=>{this.remoteClient.invoke("emitEvent",{name:"valueRangesChanged",event:{valueRanges:n.valueRanges}}).catch(K)}),"valueRangesChanged");break}case"bin":{const i={geometryInfo:{geometryType:"esriGeometryPolygon",hasM:!1,hasZ:!1},spatialReference:this.spatialReference,fieldsIndex:this.fieldsIndex,fields:this.service.fields};this.aggregateStore=new Ns(i,this.spatialReference,this._storage,this.service);break}}this.aggregateStore.onTileUpdate({added:this.tileStore.tiles,removed:[]})}}async update(a,e){this._updateVersion++,this._initQueryEngine(e),this._initAttributeStore(e),this.pause(),await Promise.all([this._source.update(a,e.schema.source),this.featureStore.updateSchema(a,e.schema.targets.feature),this.attributeStore.update(a,e),this.attributeStore.updateFilters(a,e,this)]),this._initAggregateStore(e),y(this.aggregateStore)&&await this.aggregateStore.updateSchema(a,e.schema.targets.aggregate),this._initAggregateQueryEngine(this.aggregateStore,e.schema),E("esri-2d-update-debug")&&a.describe(),this._set("config",e)}async applyUpdate(a){a.version=this._updateVersion,E("esri-2d-update-debug")&&console.debug(`Applying update ${a.version}`),a.mesh&&this.clearTiles(),this._updateQueue.resume(),await this._source.applyUpdate(a),this.notifyChange("updating"),await ue(()=>!this.updating),y(this.aggregateStore)&&(await ut(10),await ue(()=>!this.updating))}async onEdits({edits:a}){E("esri-2d-update-debug")&&console.debug("Applying Edit:",a),this._didEdit=!0;try{const e=a.removed.map(s=>s.objectId&&s.objectId!==-1?s.objectId:this._lookupObjectIdByGlobalId(s.globalId)),t=a.addOrModified.map(({objectId:s})=>s);this.featureStore.invalidate(),await this._source.edit(t,e),this.clearTiles(),this.notifyChange("updating"),y(this.aggregateStore)&&this.aggregateStore.clear(),await this._source.resend(),await ue(()=>!this.updating)}catch{}}async refresh(a){if(!a.dataChanged){const e=R.empty();return e.storage.filters=!0,this.applyUpdate(e)}this.featureStore.invalidate(),this.clearTiles(),this._source.refresh(this._updateVersion,a),this._cleanupNeeded=!0,this.notifyChange("updating"),await ue(()=>!this.updating)}clearTiles(){for(const a of this.tileStore.tiles)this.processor.onTileClear(a)}onTileUpdate(a){y(this.aggregateStore)&&this.aggregateStore.onTileUpdate(a);for(const e of a.added)this._source.subscribe(e,this._updateVersion),this._level=e.level;for(const e of a.removed)this._source.unsubscribe(e),this._cleanupNeeded=!0,this._tileToResolver.has(e.id)&&(this._tileToResolver.get(e.id).resolve(),this._tileToResolver.delete(e.id));this.notifyChange("updating")}async onIdle(){this._invalidated&&(this._invalidated=!1,(y(this.aggregateStore)||this.processor.type==="heatmap")&&await this._repushCurrentLevelTiles()),this._markAndSweep()}async querySummaryStatistics({query:a,params:e}){return this.featureQueryEngine.executeQueryForSummaryStatistics(a,e)}async queryAggregateSummaryStatistics({query:a,params:e}){return this.aggregateQueryEngine.executeQueryForSummaryStatistics(a,e)}async queryUniqueValues({query:a,params:e}){return this.featureQueryEngine.executeQueryForUniqueValues(a,e)}async queryAggregateUniqueValues({query:a,params:e}){return this.aggregateQueryEngine.executeQueryForUniqueValues(a,e)}async queryClassBreaks({query:a,params:e}){return this.featureQueryEngine.executeQueryForClassBreaks(a,e)}async queryAggregateClassBreaks({query:a,params:e}){return this.aggregateQueryEngine.executeQueryForClassBreaks(a,e)}async queryHistogram({query:a,params:e}){return this.featureQueryEngine.executeQueryForHistogram(a,e)}async queryAggregateHistogram({query:a,params:e}){return this.aggregateQueryEngine.executeQueryForHistogram(a,e)}queryExtent(a){return this.featureQueryEngine.executeQueryForExtent(a)}queryAggregates(a){return this.aggregateQueryEngine.executeQuery(a)}queryAggregateCount(a){return this.aggregateQueryEngine.executeQueryForCount(a)}queryAggregateIds(a){return this.aggregateQueryEngine.executeQueryForIds(a)}queryFeatures(a){return this.featureQueryEngine.executeQuery(a)}async queryVisibleFeatures(a){const e=await this.featureQueryEngine.executeQuery(a),t=e.objectIdFieldName;return e.features=e.features.filter(s=>{const r=s.attributes[t],i=this.getDisplayId(r);return re(i,n=>this.attributeStore.isVisible(n))}),e}queryFeatureCount(a){return this.featureQueryEngine.executeQueryForCount(a)}queryLatestObservations(a){return this.featureQueryEngine.executeQueryForLatestObservations(a)}queryObjectIds(a){return this.featureQueryEngine.executeQueryForIds(a)}async queryStatistics(){return this.featureStore.storeStatistics}getObjectId(a){return this.featureStore.lookupObjectId(a,this._storage)}getDisplayId(a){if(y(this.aggregateStore)){const e=this.aggregateStore.getDisplayId(a);if(C(e)){const t=this.featureStore.lookupDisplayId(a);return this.aggregateStore.getDisplayIdForReferenceId(t)}return e}return this.featureStore.lookupDisplayId(a)}getFeatures(a){const e=[],t=[];for(const s of a){const r=y(this.aggregateStore)?this.getAggregate(s):null;if(y(r))if(y(r.attributes.referenceId)){const i=this.getFeature(r.attributes.referenceId);y(i)&&e.push(i)}else t.push(r);else{const i=this.getFeature(s);y(i)&&e.push(i)}}return{features:e,aggregates:t}}getFeature(a){const e=this.featureStore.lookupFeatureByDisplayId(a,this._storage);if(C(e))return null;const t=e.readHydratedGeometry(),s=Ee(t,e.geometryType,e.hasZ,e.hasM);return{attributes:e.readAttributes(),geometry:s}}getAggregate(a){return C(this.aggregateStore)?null:this.aggregateStore.getAggregate(a)}getAggregates(){return C(this.aggregateStore)?[]:this.aggregateStore.getAggregates()}async setHighlight(a){const e=Yt(a.map(t=>this.getDisplayId(t)));return this.attributeStore.setHighlight(a,e)}_lookupObjectIdByGlobalId(a){const e=this.service.globalIdField;if(C(e))throw new Error("Expected globalIdField to be defined");let t=null;if(this.featureStore.forEach(s=>{a===s.readAttribute(e)&&(t=s.getObjectId())}),C(t))throw new Error(`Expected to find a feature with globalId ${a}`);return t}async _repushCurrentLevelTiles(){const a=this.tileStore.tiles.filter(t=>t.level===this._level);a.map(async t=>this._patchTile({type:"append",id:t.key.id,clear:!0,addOrUpdate:null,end:!1}));const e=a.map(async t=>this._patchTile({type:"append",id:t.key.id,addOrUpdate:Q.fromOptimizedFeatures([],this.service),remove:[],end:!0,isRepush:!0,status:R.empty()}));await Promise.all(e)}_maybeForceCleanup(){performance.now()-this._lastCleanup>Ys&&this._markAndSweep()}_patchTile(a,e){const t=this._updateQueue.push(a,e).then(()=>{this.notifyChange("updating")}).catch(s=>{this.notifyChange("updating")});return this.notifyChange("updating"),t}async _onTileMessage(a,e){if(B(e),E("esri-2d-update-debug")){const i=re(a.addOrUpdate,n=>n.hasFeatures);console.debug(a.id,`FeatureController:onTileMessage: [clear:${a.clear}, end:${a.end}, features: ${i}]`)}const t=this.tileStore.get(a.id);if(!t)return;if(a.clear)return this.processor.onTileClear(t);const s=a.status;this._cleanupNeeded=!0;const r=[];for(const i of a.remove){const n=this.featureStore.lookupDisplayId(i);n&&r.push(n)}a.remove=r;try{if(C(a.addOrUpdate))return void this.processor.onTileMessage(t,{...a,addOrUpdate:null},y(this.aggregateStore),e).catch(qe);if(a.addOrUpdate.setArcadeSpatialReference(this.spatialReference),this.featureStore.hasInstance(a.addOrUpdate.instance)&&s.targets.feature||(s.targets.feature=!0,this.featureStore.onTileData(t,a)),(!s.storage.data||!s.storage.filters)&&(s.storage.data=!0,s.storage.filters=!0,this.attributeStore.onTileData(t,a),this._source.type==="geoevent"||this._didEdit?(await this.attributeStore.sendUpdates(),B(e)):this.attributeStore.sendUpdates()),y(this.aggregateStore)&&!s.targets.aggregate){s.targets.aggregate=!0;const i=it(this._source)&&this._source.loading,n=!it(this._source)||i||a.end;if(this.aggregateStore.onTileData(t,a,this._storage,this.attributeStore,n),!n)return;s.mesh||(this.attributeStore.onTileData(t,a),await this.attributeStore.sendUpdates())}if(!s.mesh){s.mesh=!0;const i=y(this.aggregateStore)&&this.aggregateStore.type==="cluster";await this.processor.onTileMessage(t,a,i,e),B(e)}this._maybeForceCleanup()}catch(i){qe(i)}}_mark(a,e,t){const s=(4294901760&this._storage.getInstanceId(a))>>>16;a&&(e.add(s),t.set(a))}_markAndSweep(){if(this._lastCleanup=performance.now(),!(!(this._source.type==="feature"&&this._source.mode==="snapshot")&&(this._source.type==="geoevent"||this._cleanupNeeded)))return;this._cleanupNeeded=!1;const a=this._storage.getBitset(this._markedIdsBufId),e=new Set;a.clear();for(const t of this.tileStore.tiles)for(const s of this._source.readers(t.id)){const r=s.getCursor();for(;r.next();){let i=r.getDisplayId();if(!i){const n=r.getObjectId();i=this.featureStore.lookupDisplayId(n)}this._mark(i,e,a)}}this.processor.type==="symbol"&&this.processor.forEachBufferId(t=>{this._mark(t,e,a)}),this._updateQueue.forEach(t=>{for(const s of t.remove){const r=this.featureStore.lookupDisplayId(s);this._mark(r,e,a)}}),y(this.aggregateStore)&&(this.aggregateStore.sweepFeatures(a,this.featureStore),"sweepAggregates"in this.aggregateStore&&this.aggregateStore.sweepAggregates(this._storage,this.attributeStore,this._level)),this.featureStore.sweepFeatures(a,this._storage,this.attributeStore),this.featureStore.sweepFeatureSets(e)}};G([j({constructOnly:!0})],V.prototype,"tileStore",void 0),G([j()],V.prototype,"config",void 0),G([j({readOnly:!0})],V.prototype,"fieldsIndex",null),G([j()],V.prototype,"processor",void 0),G([j({constructOnly:!0})],V.prototype,"remoteClient",void 0),G([j({constructOnly:!0})],V.prototype,"service",void 0),G([j()],V.prototype,"spatialReference",null),G([j()],V.prototype,"updating",null),V=G([_t("esri.views.2d.layers.features.controllers.FeatureController2D")],V);const Ks=V;let se=class extends yt{constructor(){super(...arguments),this.controller=null,this.processor=null,this.remoteClient=null,this.tileStore=null,this.service=null,this.viewState=null,this._paused=!1,this._pendingTileUpdates=[]}initialize(){this.handles.add(Me(()=>this.updating,a=>{this.remoteClient.invoke("setUpdating",a).catch(e=>{})}))}destroy(){var a,e;this.stop(),(a=this.controller)==null||a.destroy(),(e=this.processor)==null||e.destroy(),this.controller=this.processor=this.tileStore=this.remoteClient=null}get updating(){return!this.controller||this.controller.updating}stop(){var a,e,t;this._paused=!0,Array.isArray((a=this.service)==null?void 0:a.source)&&(this.service.source.forEach(s=>s.close()),this.service.source.length=0),(e=this.tileStore)==null||e.updateTiles({added:[],removed:this.tileStore.tiles.map(s=>s.id)}),(t=this.tileStore)==null||t.destroy(),this.tileStore=null,this._pendingTileUpdates.length=0}async startup({service:a,config:e,tileInfo:t,tiles:s}){var r,i,n;if(this._paused=!0,Array.isArray((r=this.service)==null?void 0:r.source)&&(this.service.source.forEach(o=>o.close()),this.service.source.length=0),this.service=a,!this.tileStore||!Ht(this.tileStore.tileScheme.spatialReference,t.spatialReference)){const o=new Zt(Jt.fromJSON(t));s.added.length=s.removed.length=0,(i=this.tileStore)==null||i.updateTiles({added:[],removed:this.tileStore.tiles.map(u=>u.id)}),(n=this.tileStore)==null||n.destroy(),this.tileStore=new Wt(o),this._pendingTileUpdates.length=0}for(await this._createProcessorAndController(e),await this.update({config:e}),this.controller.resume(),this.tileStore.clear(),this.tileStore.updateTiles(s),this._paused=!1;this._pendingTileUpdates.length;)this.tileStore.updateTiles(this._pendingTileUpdates.pop())}async updateTiles(a){this._paused?this._pendingTileUpdates.push(a):this.tileStore.updateTiles(a)}async update({config:a}){const e=R.empty();return await Promise.all([this.processor.update(e,a),this.controller.update(e,a)]),e.toJSON()}async applyUpdate(a){return this.controller.applyUpdate(R.create(a))}async _createProcessorAndController(a){await Promise.all([this._handleControllerConfig(a),this._handleProcessorConfig(a)]),this.controller.processor=this.processor}async _handleControllerConfig(a){return this._createController(this.service,a)}async _handleProcessorConfig(a){return this._createProcessor(this.service,a)}async _createController(a,e){this.controller&&this.controller.destroy();const{tileStore:t,remoteClient:s}=this,r=new Ks({service:a,tileStore:t,remoteClient:s});return this.controller=r,r}async _createProcessor(a,e){const t=e.schema.processors[0].type,s=(await as(t)).default,{remoteClient:r,tileStore:i}=this,n=new s({service:a,config:e,tileStore:i,remoteClient:r});return this.processor&&this.processor.destroy(),this.processor=n,n}};G([j()],se.prototype,"controller",void 0),G([j()],se.prototype,"processor",void 0),G([j()],se.prototype,"updating",null),G([j()],se.prototype,"viewState",void 0),se=G([_t("esri.views.2d.layers.features.Pipeline")],se);const Cr=se;export{Cr as default};