import{di as Fe,s as b,cz as Se,aL as ce,aM as de,f1 as Je,f2 as Xe,af as me,d as L,aK as Re,cJ as re,_ as ht,jP as ct,il as we,jQ as dt,jR as mt,bb as ee,jS as fe,g$ as Ke,h0 as te,er as ft,A as ne,B as be,C as gt,bk as _t,jT as le,gY as oe,D as pt,P as yt,jU as ge,bz as v,z as xt,jV as Tt,gx as Et,jW as It,jX as Ft,jY as St,jZ as Rt,cy as wt,J as bt,b$ as Ae,ep as Ce,aC as At,j_ as Ct,be as vt,bh as Nt,aW as ue,j$ as Ot,ba as Dt,as as Pt,aq as ve,al as Lt,fa as kt,eL as $t,bf as Qt,k0 as Vt}from"./index-b5c8f851.js";import{r as Mt}from"./featureConversionUtils-6aca8295.js";import{x as Ut}from"./WhereClause-08dab84b.js";import{a as B,h as Z,y as Ne,P as et,g as U,j as Gt,n as qt,S as Oe,v as z,t as zt,I as De}from"./timeSupport-b4d06407.js";import{j as Q,x as ye,b as jt}from"./projectionSupport-d15822a5.js";import{t as Bt}from"./QueryEngineCapabilities-85c4f1d0.js";import{m as Pe}from"./quantizationUtils-50e37a76.js";import{c as he,w as Zt,B as Ht,f as Yt,d as Le,p as ke,C as Wt,k as Jt,$ as Xt,E as Kt,P as es,U as ts,T as ss,v as is}from"./utils-10149227.js";import{I as C}from"./RenderState-1d6218ee.js";class as{constructor(e,t){this._cache=new Fe(e),this._invalidCache=new Fe(t)}get(e,t){const i=`${t.uid}:${e}`,a=this._cache.get(i);if(a)return a;if(this._invalidCache.get(i)!=null)return null;try{const s=Ut.create(e,t);return this._cache.put(i,s),s}catch(s){return this._invalidCache.put(i,s),null}}getError(e,t){const i=`${t.uid}:${e}`;return this._invalidCache.get(i)??null}}const tt=new as(50,500),H="unsupported-query",st=" as ",it=new Set(["esriFieldTypeOID","esriFieldTypeSmallInteger","esriFieldTypeBigInteger","esriFieldTypeInteger","esriFieldTypeSingle","esriFieldTypeDouble","esriFieldTypeLong"]),at=new Set(["esriFieldTypeDate","esriFieldTypeDateOnly","esriFieldTypeTimeOnly","esriFieldTypeTimestampOffset"]),rs=new Set(["esriFieldTypeString","esriFieldTypeGUID","esriFieldTypeGlobalID",...it,...at]);function xe(l,e,t={}){const i=V(e,l);if(!i){const s=tt.getError(e,l);throw new b(H,"invalid SQL expression",{expression:e,error:s})}const a=t.expressionName||"expression";if(t.validateStandardized&&!i.isStandardized)throw new b(H,`${a} is not standard`,{expression:e});if(t.validateAggregate&&!i.isAggregate)throw new b(H,`${a} does not contain a valid aggregate function`,{expression:e});return i.fieldNames}function ns(l,e,t,i){if(!t)return!0;const a="where clause";return k(l,e,xe(l,t,{validateStandardized:!0,expressionName:a}),{expressionName:a,query:i}),!0}function ls(l,e,t,i,a){if(!t)return!0;const s="having clause",r=xe(l,t,{validateAggregate:!0,expressionName:s});k(l,e,r,{expressionName:s,query:a});const n=V(t,l);if(!(n==null?void 0:n.getExpressions().every(u=>{var f;const{aggregateType:h,field:c}=u,m=(f=l.get(c))==null?void 0:f.name;return i.some(_=>{var F;const{onStatisticField:d,statisticType:E}=_;return((F=l.get(d))==null?void 0:F.name)===m&&E.toLowerCase().trim()===h})})))throw new b(H,"expressions in having clause should also exist in outStatistics",{having:t});return!0}function V(l,e){return l?tt.get(l,e):null}function rt(l){return/\((.*?)\)/.test(l)?l:l.split(st)[0]}function os(l){return l.split(st)[1]}function k(l,e,t,i={}){const a=new Map;if(us(a,l,e,i.allowedFieldTypes??rs,t),a.size){const s=i.expressionName??"expression";throw new b(H,`${s} contains invalid or missing fields`,{errors:Array.from(a.values()),query:i.query})}}function us(l,e,t,i,a){for(const s of a)if(s!=="*")if(e.get(s))$e(l,e,t,i,s);else try{const r=xe(e,rt(s),{validateStandardized:!0});for(const n of r)$e(l,e,t,i,n)}catch(r){l.set(s,{type:"expression-error",expression:s,error:r})}}function $e(l,e,t,i,a){if(a==="*")return;const s=e.get(a);s?t.has(s.name)?(i==null?void 0:i.has(s.type))===!1&&l.set(a,{type:"invalid-type",fieldName:s.name,fieldType:Se.fromJSON(s.type),allowedFieldTypes:Array.from(i,r=>Se.fromJSON(r))}):l.set(a,{type:"missing-field",fieldName:s.name}):l.set(a,{type:"invalid-field",fieldName:a})}let K=class{constructor(e,t,i){this._fieldDataCache=new Map,this._returnDistinctMap=new Map,this.returnDistinctValues=e.returnDistinctValues??!1,this.fieldsIndex=i,this.featureAdapter=t;const a=e.outFields;if(a&&!a.includes("*")){this.outFields=a;let s=0;for(const r of a){const n=rt(r),o=this.fieldsIndex.get(n),u=o?null:V(n,i),h=o?o.name:os(r)||"FIELD_EXP_"+s++;this._fieldDataCache.set(r,{alias:h,clause:u})}}}countDistinctValues(e){return this.returnDistinctValues?(e.forEach(t=>this.getAttributes(t)),this._returnDistinctMap.size):e.length}getAttributes(e){const t=this._processAttributesForOutFields(e);return this._processAttributesForDistinctValues(t)}getFieldValue(e,t,i){var r;const a=i?i.name:t;let s=null;return this._fieldDataCache.has(a)?s=(r=this._fieldDataCache.get(a))==null?void 0:r.clause:i||(s=V(t,this.fieldsIndex),this._fieldDataCache.set(a,{alias:a,clause:s})),i?this.featureAdapter.getAttribute(e,a):s==null?void 0:s.calculateValue(e,this.featureAdapter)}getDataValues(e,t,i=!0){const a=t.normalizationType,s=t.normalizationTotal,r=this.fieldsIndex.get(t.field),n=ce(r)||de(r),o=Je(r);return e.map(u=>{let h=t.field&&this.getFieldValue(u,t.field,this.fieldsIndex.get(t.field));if(t.field2?(h=`${he(h)}${t.fieldDelimiter}${he(this.getFieldValue(u,t.field2,this.fieldsIndex.get(t.field2)))}`,t.field3&&(h=`${h}${t.fieldDelimiter}${he(this.getFieldValue(u,t.field3,this.fieldsIndex.get(t.field3)))}`)):typeof h=="string"&&i&&(n?h=h?new Date(h).getTime():null:o&&(h=h?Zt(h):null)),a&&Number.isFinite(h)){const c=a==="field"&&t.normalizationField?this.getFieldValue(u,t.normalizationField,this.fieldsIndex.get(t.normalizationField)):null;h=Ht(h,a,c,s)}return h})}async getExpressionValues(e,t,i,a,s){const{arcadeUtils:r}=await Xe(),n=r.hasGeometryOperations(t);n&&await r.enableGeometryOperations();const o=r.createFunction(t),u=r.getViewInfo(i),h={fields:this.fieldsIndex.fields};return e.map(c=>{const m={attributes:this.featureAdapter.getAttributes(c),layer:h,geometry:n?{...B(a.geometryType,a.hasZ,a.hasM,this.featureAdapter.getGeometry(c)),spatialReference:i==null?void 0:i.spatialReference}:null},f=r.createExecContext(m,u,s);return r.executeFunction(o,f)})}validateItem(e,t){var i,a;return this._fieldDataCache.has(t)||this._fieldDataCache.set(t,{alias:t,clause:V(t,this.fieldsIndex)}),((a=(i=this._fieldDataCache.get(t))==null?void 0:i.clause)==null?void 0:a.testFeature(e,this.featureAdapter))??!1}validateItems(e,t){var i,a;return this._fieldDataCache.has(t)||this._fieldDataCache.set(t,{alias:t,clause:V(t,this.fieldsIndex)}),((a=(i=this._fieldDataCache.get(t))==null?void 0:i.clause)==null?void 0:a.testSet(e,this.featureAdapter))??!1}_processAttributesForOutFields(e){const t=this.outFields;if(!(t!=null&&t.length))return this.featureAdapter.getAttributes(e);const i={};for(const a of t){const{alias:s,clause:r}=this._fieldDataCache.get(a);i[s]=r?r.calculateValue(e,this.featureAdapter):this.featureAdapter.getAttribute(e,s)}return i}_processAttributesForDistinctValues(e){if(e==null||!this.returnDistinctValues)return e;const t=this.outFields,i=[];if(t)for(const r of t){const{alias:n}=this._fieldDataCache.get(r);i.push(e[n])}else for(const r in e)i.push(e[r]);const a=`${(t||["*"]).join(",")}=${i.join(",")}`;let s=this._returnDistinctMap.get(a)||0;return this._returnDistinctMap.set(a,++s),s>1?null:e}};function Qe(l,e,t){return{objectId:l,target:e,distance:t,type:"vertex"}}function hs(l,e,t,i,a,s=!1){return{objectId:l,target:e,distance:t,type:"edge",start:i,end:a,draped:s}}class w{constructor(e,t,i){this.items=e,this.query=t,this.geometryType=i.geometryType,this.hasM=i.hasM,this.hasZ=i.hasZ,this.fieldsIndex=i.fieldsIndex,this.objectIdField=i.objectIdField,this.spatialReference=i.spatialReference,this.featureAdapter=i.featureAdapter}get size(){return this.items.length}createQueryResponseForCount(){const e=new K(this.query,this.featureAdapter,this.fieldsIndex);if(!this.query.outStatistics)return e.countDistinctValues(this.items);const{groupByFieldsForStatistics:t,having:i,outStatistics:a}=this.query;if(!(t==null?void 0:t.length))return 1;const r=new Map,n=new Map,o=new Set;for(const u of a){const{statisticType:h}=u,c=h!=="exceedslimit"?u.onStatisticField:void 0;if(!n.has(c)){const f=[];for(const _ of t){const d=this._getAttributeValues(e,_,r);f.push(d)}n.set(c,this._calculateUniqueValues(f,e.returnDistinctValues))}const m=n.get(c);for(const f in m){const{data:_,items:d}=m[f],E=_.join(",");i&&!e.validateItems(d,i)||o.add(E)}}return o.size}async createQueryResponse(){let e;if(this.query.outStatistics?e=this.query.outStatistics.some(t=>t.statisticType==="exceedslimit")?this._createExceedsLimitQueryResponse(this.query):await this._createStatisticsQueryResponse(this.query):e=this._createFeatureQueryResponse(this.query),this.query.returnQueryGeometry){const t=this.query.geometry;me(this.query.outSR)&&!L(t.spatialReference,this.query.outSR)?e.queryGeometry=Z({spatialReference:this.query.outSR,...Q(t,t.spatialReference,this.query.outSR)}):e.queryGeometry=Z({spatialReference:this.query.outSR,...t})}return e}createSnappingResponse(e,t){const i=this.featureAdapter,a=Ve(this.hasZ,this.hasM),{point:s,mode:r}=e,n=typeof e.distance=="number"?e.distance:e.distance.x,o=typeof e.distance=="number"?e.distance:e.distance.y,u={candidates:[]},h=this.geometryType==="esriGeometryPolygon",c=this._getPointCreator(r,this.spatialReference,t),m=new Me(null,0),f=new Me(null,0),_={x:0,y:0,z:0};for(const d of this.items){const E=i.getGeometry(d);if(E==null)continue;const{coords:T,lengths:F}=E;if(m.coords=T,f.coords=T,e.returnEdge){let R=0;for(let y=0;yd.distance-E.distance),u}_getPointCreator(e,t,i){const a=i==null||L(t,i)?n=>n:n=>Q(n,t,i),{hasZ:s}=this,r=0;return e==="3d"?s?({x:n,y:o,z:u})=>a({x:n,y:o,z:u}):({x:n,y:o})=>a({x:n,y:o,z:r}):({x:n,y:o})=>a({x:n,y:o})}async createSummaryStatisticsResponse(e){const{field:t,valueExpression:i,normalizationField:a,normalizationType:s,normalizationTotal:r,minValue:n,maxValue:o,scale:u,timeZone:h}=e,c=this.fieldsIndex.get(t),m=Re(c)||ce(c)||de(c),f=await this._getDataValues({field:t,valueExpression:i,normalizationField:a,normalizationType:s,normalizationTotal:r,scale:u,timeZone:h}),_=Yt({normalizationType:s,normalizationField:a,minValue:n,maxValue:o}),d={value:.5,fieldType:c==null?void 0:c.type},E=re(c)?Le({values:f,supportsNullCount:_,percentileParams:d}):ke({values:f,minValue:n,maxValue:o,useSampleStdDev:!s,supportsNullCount:_,percentileParams:d});return Wt(E,m)}async createUniqueValuesResponse(e){const{field:t,valueExpression:i,domains:a,returnAllCodedValues:s,scale:r,timeZone:n}=e,o=await this._getDataValues({field:t,field2:e.field2,field3:e.field3,fieldDelimiter:e.fieldDelimiter,valueExpression:i,scale:r,timeZone:n},!1),u=Jt(o);return Xt(u,a,s,e.fieldDelimiter)}async createClassBreaksResponse(e){const{field:t,valueExpression:i,normalizationField:a,normalizationType:s,normalizationTotal:r,classificationMethod:n,standardDeviationInterval:o,minValue:u,maxValue:h,numClasses:c,scale:m,timeZone:f}=e,_=await this._getDataValues({field:t,valueExpression:i,normalizationField:a,normalizationType:s,normalizationTotal:r,scale:m,timeZone:f}),d=Kt(_,{field:t,normalizationField:a,normalizationType:s,normalizationTotal:r,classificationMethod:n,standardDeviationInterval:o,minValue:u,maxValue:h,numClasses:c});return es(d,n)}async createHistogramResponse(e){const{field:t,valueExpression:i,normalizationField:a,normalizationType:s,normalizationTotal:r,classificationMethod:n,standardDeviationInterval:o,minValue:u,maxValue:h,numBins:c,scale:m,timeZone:f}=e,_=await this._getDataValues({field:t,valueExpression:i,normalizationField:a,normalizationType:s,normalizationTotal:r,scale:m,timeZone:f});return ts(_,{field:t,normalizationField:a,normalizationType:s,normalizationTotal:r,classificationMethod:n,standardDeviationInterval:o,minValue:u,maxValue:h,numBins:c})}_sortFeatures(e,t,i){if(e.length>1&&(t!=null&&t.length))for(const a of t.reverse()){const s=a.split(" "),r=s[0],n=this.fieldsIndex.get(r),o=!!s[1]&&s[1].toLowerCase()==="desc",u=ss(n==null?void 0:n.type,o);e.sort((h,c)=>{const m=i(h,r,n),f=i(c,r,n);return u(m,f)})}}_createFeatureQueryResponse(e){const t=this.items,{geometryType:i,hasM:a,hasZ:s,objectIdField:r,spatialReference:n}=this,{outFields:o,outSR:u,quantizationParameters:h,resultRecordCount:c,resultOffset:m,returnZ:f,returnM:_}=e,d=c!=null&&t.length>(m||0)+c,E=o&&(o.includes("*")?[...this.fieldsIndex.fields]:o.map(T=>this.fieldsIndex.get(T)));return{exceededTransferLimit:d,features:this._createFeatures(e,t),fields:E,geometryType:i,hasM:a&&_,hasZ:s&&f,objectIdFieldName:r,spatialReference:Z(u||n),transform:h&&Pe(h)||null}}_createFeatures(e,t){const i=new K(e,this.featureAdapter,this.fieldsIndex),{hasM:a,hasZ:s}=this,{orderByFields:r,quantizationParameters:n,returnGeometry:o,returnCentroid:u,maxAllowableOffset:h,resultOffset:c,resultRecordCount:m,returnZ:f=!1,returnM:_=!1}=e,d=s&&f,E=a&&_;let T=[],F=0;const R=[...t];if(this._sortFeatures(R,r,(x,p,I)=>i.getFieldValue(x,p,I)),this.geometryType&&(o||u)){const x=Pe(n)??void 0;if(o&&!u)for(const p of R)T[F++]={attributes:i.getAttributes(p),geometry:B(this.geometryType,this.hasZ,this.hasM,this.featureAdapter.getGeometry(p),h,x,d,E)};else if(!o&&u)for(const p of R)T[F++]={attributes:i.getAttributes(p),centroid:Ne(this,this.featureAdapter.getCentroid(p,this),x)};else for(const p of R)T[F++]={attributes:i.getAttributes(p),centroid:Ne(this,this.featureAdapter.getCentroid(p,this),x),geometry:B(this.geometryType,this.hasZ,this.hasM,this.featureAdapter.getGeometry(p),h,x,d,E)}}else for(const x of R){const p=i.getAttributes(x);p&&(T[F++]={attributes:p})}const y=c||0;if(m!=null){const x=y+m;T=T.slice(y,Math.min(T.length,x))}return T}_createExceedsLimitQueryResponse(e){let t=!1,i=Number.POSITIVE_INFINITY,a=Number.POSITIVE_INFINITY,s=Number.POSITIVE_INFINITY;for(const r of e.outStatistics??[])if(r.statisticType==="exceedslimit"){i=r.maxPointCount!=null?r.maxPointCount:Number.POSITIVE_INFINITY,a=r.maxRecordCount!=null?r.maxRecordCount:Number.POSITIVE_INFINITY,s=r.maxVertexCount!=null?r.maxVertexCount:Number.POSITIVE_INFINITY;break}if(this.geometryType==="esriGeometryPoint")t=this.items.length>i;else if(this.items.length>a)t=!0;else{const r=Ve(this.hasZ,this.hasM),n=this.featureAdapter;t=this.items.reduce((o,u)=>{const h=n.getGeometry(u);return o+(h!=null&&h.coords.length||0)},0)/r>s}return{fields:[{name:"exceedslimit",type:"esriFieldTypeInteger",alias:"exceedslimit",sqlType:"sqlTypeInteger",domain:null,defaultValue:null}],features:[{attributes:{exceedslimit:Number(t)}}]}}async _createStatisticsQueryResponse(e){var R;const t={attributes:{}},i=[],a=new Map,s=new Map,r=new Map,n=new Map,o=new K(e,this.featureAdapter,this.fieldsIndex),u=e.outStatistics,{groupByFieldsForStatistics:h,having:c,orderByFields:m,resultRecordCount:f}=e,_=h==null?void 0:h.length,d=!!_,E=d?h[0]:null,T=d&&!this.fieldsIndex.get(E);for(const y of u??[]){const{outStatisticFieldName:x,statisticType:p}=y,I=y,S=p!=="exceedslimit"?y.onStatisticField:void 0,A=p==="percentile_disc"||p==="percentile_cont",O=p==="EnvelopeAggregate"||p==="CentroidAggregate"||p==="ConvexHullAggregate",Y=d&&_===1&&(S===E||T)&&p==="count";if(d){if(!r.has(S)){const J=[];for(const ae of h){const X=this._getAttributeValues(o,ae,a);J.push(X)}r.set(S,this._calculateUniqueValues(J,!O&&o.returnDistinctValues))}const D=r.get(S);if(!D)continue;const ie=Object.keys(D);for(const J of ie){const{count:ae,data:X,items:Te,itemPositions:lt}=D[J],Ee=X.join(",");if(!c||o.validateItems(Te,c)){const M=n.get(Ee)||{attributes:{}};if(O){M.aggregateGeometries||(M.aggregateGeometries={});const{aggregateGeometries:P,outStatisticFieldName:q}=await this._getAggregateGeometry(I,Te);M.aggregateGeometries[q]=P}else{let P=null;if(Y)P=ae;else{const q=this._getAttributeValues(o,S,a),Ie=lt.map(ut=>q[ut]);P=A&&"statisticParameters"in I?this._getPercentileValue(I,Ie):this._getStatisticValue(I,Ie,null,o.returnDistinctValues)}M.attributes[x]=P}let ot=0;h.forEach((P,q)=>M.attributes[this.fieldsIndex.get(P)?P:"EXPR_"+ ++ot]=X[q]),n.set(Ee,M)}}}else if(O){t.aggregateGeometries||(t.aggregateGeometries={});const{aggregateGeometries:D,outStatisticFieldName:ie}=await this._getAggregateGeometry(I,this.items);t.aggregateGeometries[ie]=D}else{const D=this._getAttributeValues(o,S,a);t.attributes[x]=A&&"statisticParameters"in I?this._getPercentileValue(I,D):this._getStatisticValue(I,D,s,o.returnDistinctValues)}const W=p!=="min"&&p!=="max"||!re(this.fieldsIndex.get(S))&&!this._isAnyDateField(S)?null:(R=this.fieldsIndex.get(S))==null?void 0:R.type;i.push({name:x,alias:x,type:W||"esriFieldTypeDouble"})}const F=d?Array.from(n.values()):[t];return this._sortFeatures(F,m,(y,x)=>y.attributes[x]),f&&(F.length=Math.min(f,F.length)),{fields:i,features:F}}_isAnyDateField(e){const t=this.fieldsIndex.get(e);return Re(t)||ce(t)||de(t)||Je(t)}async _getAggregateGeometry(e,t){const{convexHull:i,union:a}=await ht(()=>import("./geometryEngineJSON-a8df8ba1.js"),["assets/geometryEngineJSON-a8df8ba1.js","assets/geometryEngineBase-5b22cc12.js","assets/index-b5c8f851.js","assets/index-86716609.css","assets/geometryEngineJSON-9fc26574.js","assets/json-48e3ea08.js"]),{statisticType:s,outStatisticFieldName:r}=e,{featureAdapter:n,spatialReference:o,geometryType:u,hasZ:h,hasM:c}=this,m=t.map(d=>B(u,h,c,n.getGeometry(d))),f=i(o,m,!0)[0],_={aggregateGeometries:null,outStatisticFieldName:null};if(s==="EnvelopeAggregate"){const d=f?ct(f):we(a(o,m));_.aggregateGeometries={...d,spatialReference:o},_.outStatisticFieldName=r||"extent"}else if(s==="CentroidAggregate"){const d=f?dt(f):mt(we(a(o,m)));_.aggregateGeometries={x:d[0],y:d[1],spatialReference:o},_.outStatisticFieldName=r||"centroid"}else s==="ConvexHullAggregate"&&(_.aggregateGeometries=f,_.outStatisticFieldName=r||"convexHull");return _}_getStatisticValue(e,t,i,a){const{onStatisticField:s,statisticType:r}=e;let n=null;return n=i!=null&&i.has(s)?i.get(s):re(this.fieldsIndex.get(s))||this._isAnyDateField(s)?Le({values:t,returnDistinct:a}):ke({values:a?[...new Set(t)]:t,minValue:null,maxValue:null,useSampleStdDev:!0}),i&&i.set(s,n),n[r==="var"?"variance":r]}_getPercentileValue(e,t){const{onStatisticField:i,statisticParameters:a,statisticType:s}=e,{value:r,orderBy:n}=a,o=this.fieldsIndex.get(i);return is(t,{value:r,orderBy:n,fieldType:o==null?void 0:o.type,isDiscrete:s==="percentile_disc"})}_getAttributeValues(e,t,i){if(i.has(t))return i.get(t);const a=this.fieldsIndex.get(t),s=this.items.map(r=>e.getFieldValue(r,t,a));return i.set(t,s),s}_calculateUniqueValues(e,t){const i={},a=this.items,s=a.length;for(let r=0;rl)}function nt(l,e,t){const{outFields:i,orderByFields:a,returnDistinctValues:s,outStatistics:r}=t,n=r?r.map(o=>o.outStatisticFieldName&&o.outStatisticFieldName.toLowerCase()).filter(Boolean):[];if(a&&a.length>0){const o=" asc",u=" desc",h=a.map(c=>{const m=c.toLowerCase();return m.includes(o)?m.split(o)[0]:m.includes(u)?m.split(u)[0]:c}).filter(c=>!n.includes(c));k(l,e,h,{expressionName:"orderByFields",query:t})}if(i&&i.length>0)k(l,e,i,{expressionName:"outFields",query:t});else if(s)throw new b(G,"outFields should be specified for returnDistinctValues",{query:t});ns(l,e,t.where,t)}const ds=new Set([...it,...at]);function ms(l,e,t){const{outStatistics:i,groupByFieldsForStatistics:a,having:s}=t,r=a==null?void 0:a.length,n=i==null?void 0:i.length;if(s){if(!r||!n)throw new b(G,"outStatistics and groupByFieldsForStatistics should be specified with having",{query:t});ls(l,e,s,i,t)}if(n){if(!_s(i))return;const o=i.map(u=>u.onStatisticField).filter(Boolean);k(l,e,o,{expressionName:"onStatisticFields",query:t}),r&&k(l,e,a,{expressionName:"groupByFieldsForStatistics",query:t});for(const u of i){const{onStatisticField:h,statisticType:c}=u;if((c==="percentile_disc"||c==="percentile_cont")&&"statisticParameters"in u){const{statisticParameters:m}=u;if(!m)throw new b(G,"statisticParameters should be set for percentile type",{definition:u,query:t})}else l.get(h)&&c!=="count"&&c!=="min"&&c!=="max"&&k(l,e,[h],{expressionName:`outStatistics with '${c}' statistic type`,allowedFieldTypes:ds,query:t})}}}async function fs(l,e,{fieldsIndex:t,geometryType:i,spatialReference:a,availableFields:s}){if((l.distance??0)<0||l.geometryPrecision!=null||l.multipatchOption||l.pixelSize||l.relationParam||l.text||l.outStatistics||l.groupByFieldsForStatistics||l.having||l.orderByFields)throw new b(G,"Unsupported query options",{query:l});return nt(t,s,l),Promise.all([gs(t,s,e,l),et(l,i,a),ye(a,l.outSR)]).then(()=>l)}async function gs(l,e,t,i){let a=[];if(t.valueExpression){const{arcadeUtils:s}=await Xe();a=s.extractFieldNames(t.valueExpression)}if(t.field&&a.push(t.field),t.field2&&a.push(t.field2),t.field3&&a.push(t.field3),t.normalizationField&&a.push(t.normalizationField),!a.length&&!t.valueExpression)throw new b(G,"field or valueExpression is required",{params:t});k(l,e,a,{expressionName:"statistics",query:i})}function _s(l){return l!=null&&l.every(e=>e.statisticType!=="exceedslimit")}class ps{constructor(){this._tasks=new Array,this._running=fe(!1)}get length(){return this._tasks.length}get running(){return this._running.value}destroy(){this.cancelAll()}runTask(e){for(;!e.done&&this._process(e);)e.madeProgress()}push(e,t,i){return this._running.value=!0,new Promise((a,s)=>this._tasks.push(new Ge(a,s,e,t,i)))}unshift(e,t,i){return this._running.value=!0,new Promise((a,s)=>this._tasks.unshift(new Ge(a,s,e,t,i)))}_process(e){var i;if(this._tasks.length===0)return!1;const t=this._tasks.shift();try{const a=Ke(t.signal);if(a&&!t.abortCallback)t.reject(te());else{const s=a?(i=t.abortCallback)==null?void 0:i.call(t,te()):t.callback(e);ft(s)?s.then(t.resolve,t.reject):t.resolve(s)}}catch(a){t.reject(a)}return this._running.value=this._tasks.length>0,!0}cancelAll(){const e=te();for(const t of this._tasks)if(t.abortCallback){const i=t.abortCallback(e);t.resolve(i)}else t.reject(e);this._tasks.length=0,this._running.value=!1}}class Ge{constructor(e,t,i,a=void 0,s=void 0){this.resolve=e,this.reject=t,this.callback=i,this.signal=a,this.abortCallback=s}}let j=class extends _t{constructor(){super(...arguments),this.SCHEDULER_LOG_SLOW_TASKS=!1,this.FEATURE_SERVICE_SNAPPING_SOURCE_TILE_TREE_SHOW_TILES=!1}};ne([be()],j.prototype,"SCHEDULER_LOG_SLOW_TASKS",void 0),ne([be()],j.prototype,"FEATURE_SERVICE_SNAPPING_SOURCE_TILE_TREE_SHOW_TILES",void 0),j=ne([gt("esri.views.support.DebugFlags")],j);const ys=new j;var _e,g;(function(l){l[l.YIELD=1]="YIELD"})(_e||(_e={})),function(l){l.RESOURCE_CONTROLLER_IMMEDIATE="immediate",l.RESOURCE_CONTROLLER="schedule",l.SLIDE="slide",l.STREAM_DATA_LOADER="stream loader",l.ELEVATION_QUERY="elevation query",l.TERRAIN_SURFACE="terrain",l.SURFACE_GEOMETRY_UPDATES="surface geometry updates",l.LOD_RENDERER="LoD renderer",l.GRAPHICS_CORE="Graphics3D",l.I3S_CONTROLLER="I3S",l.POINT_CLOUD_LAYER="point cloud",l.FEATURE_TILE_FETCHER="feature fetcher",l.OVERLAY="overlay",l.STAGE="stage",l.GRAPHICS_DECONFLICTOR="graphics deconflictor",l.FILTER_VISIBILITY="Graphics3D filter visibility",l.SCALE_VISIBILITY="Graphics3D scale visibility",l.FRUSTUM_VISIBILITY="Graphics3D frustum visibility",l.POINT_OF_INTEREST_FREQUENT="POI frequent",l.POINT_OF_INTEREST_INFREQUENT="POI infrequent",l.LABELER="labeler",l.FEATURE_QUERY_ENGINE="feature query",l.FEATURE_TILE_TREE="feature tile tree",l.FEATURE_TILE_TREE_ACTIVE="fast feature tile tree",l.ELEVATION_ALIGNMENT="elevation alignment",l.TEXT_TEXTURE_ATLAS="text texture atlas",l.TEXTURE_UNLOAD="texture unload",l.LINE_OF_SIGHT_TOOL="line of sight tool",l.LINE_OF_SIGHT_TOOL_INTERACTIVE="interactive line of sight tool",l.ELEVATION_PROFILE="elevation profile",l.SNAPPING="snapping",l.SHADOW_ACCUMULATOR="shadow accumulator",l.CLOUDS_GENERATOR="clouds generator",l[l.NONE=0]="NONE",l[l.TEST_PRIO=1]="TEST_PRIO"}(g||(g={}));const N=0,qe=new Map([[g.RESOURCE_CONTROLLER_IMMEDIATE,N],[g.RESOURCE_CONTROLLER,4],[g.SLIDE,N],[g.STREAM_DATA_LOADER,N],[g.ELEVATION_QUERY,N],[g.TERRAIN_SURFACE,1],[g.SURFACE_GEOMETRY_UPDATES,1],[g.LOD_RENDERER,2],[g.GRAPHICS_CORE,2],[g.I3S_CONTROLLER,2],[g.POINT_CLOUD_LAYER,2],[g.FEATURE_TILE_FETCHER,2],[g.OVERLAY,4],[g.STAGE,4],[g.GRAPHICS_DECONFLICTOR,4],[g.FILTER_VISIBILITY,4],[g.SCALE_VISIBILITY,4],[g.FRUSTUM_VISIBILITY,4],[g.CLOUDS_GENERATOR,4],[g.POINT_OF_INTEREST_FREQUENT,6],[g.POINT_OF_INTEREST_INFREQUENT,30],[g.LABELER,8],[g.FEATURE_QUERY_ENGINE,8],[g.FEATURE_TILE_TREE,16],[g.FEATURE_TILE_TREE_ACTIVE,N],[g.ELEVATION_ALIGNMENT,12],[g.TEXT_TEXTURE_ATLAS,12],[g.TEXTURE_UNLOAD,12],[g.LINE_OF_SIGHT_TOOL,16],[g.LINE_OF_SIGHT_TOOL_INTERACTIVE,N],[g.SNAPPING,N],[g.SHADOW_ACCUMULATOR,30]]);function ze(l){return qe.has(l)?qe.get(l):typeof l=="number"?l:1}const je=v(6.5),Be=v(1),xs=v(30),Ze=v(1e3/30),He=v(100),Ye=.9;var pe,$;(function(l){let e=class{get updating(){return this._updating.value}_updatingChanged(){this._updating.value=this._tasks.some(s=>s.needsUpdate)}constructor(){this._updating=fe(!0),this._microTaskQueued=!1,this._frameNumber=0,this.performanceInfo={total:new le("total"),tasks:new Map},this._frameTaskTimes=new Map,this._budget=new i,this._state=C.INTERACTING,this._tasks=new oe,this._runQueue=new oe,this._load=0,this._idleStateCallbacks=new oe,this._idleUpdatesStartFired=!1,this._forceTask=!1,this._debug=!1,this._debugHandle=pt(()=>ys.SCHEDULER_LOG_SLOW_TASKS,r=>this._debug=r,yt);for(const r of Object.keys(g))this.performanceInfo.tasks.set(g[r],new le(g[r]));const s=this;this._test={FRAME_SAFETY_BUDGET:je,INTERACTING_BUDGET:Ze,IDLE_BUDGET:He,get availableBudget(){return s._budget.budget},usedBudget:0,getBudget:()=>s._budget,setBudget:r=>s._budget=r,updateTask:r=>this._updateTask(r),getState:r=>this._getState(r),getRuntime:r=>this._getRuntime(r),frameTaskTimes:this._frameTaskTimes,resetRuntimes:()=>this._resetRuntimes(),getRunning:()=>this._getRunning()}}destroy(){this._tasks.toArray().forEach(s=>s.remove()),this._tasks.clear(),ge(this._debugHandle),this._microTaskQueued=!1,this._updatingChanged()}taskRunningChanged(s){this._updatingChanged(),s&&this._budget.remaining>0&&!this._microTaskQueued&&(this._microTaskQueued=!0,queueMicrotask(()=>{this._microTaskQueued&&(this._microTaskQueued=!1,this._budget.remaining>0&&this._schedule()&&this.frame())}))}registerTask(s,r){const n=ze(s),o=new t(this,s,r,n);return this._tasks.push(o),this._updatingChanged(),this.performanceInfo.tasks.has(s)||this.performanceInfo.tasks.set(s,new le(s)),o}registerIdleStateCallbacks(s,r){const n={idleBegin:s,idleEnd:r};this._idleStateCallbacks.push(n),this.state===C.IDLE&&this._idleUpdatesStartFired&&n.idleBegin();const o=this;return{remove:()=>this._removeIdleStateCallbacks(n),set idleBegin(u){o._idleUpdatesStartFired&&(n.idleEnd(),o._state===C.IDLE&&u()),n.idleBegin=u},set idleEnd(u){n.idleEnd=u}}}get load(){return this._load}set state(s){this._state!==s&&(this._state=s,this.state!==C.IDLE&&this._idleUpdatesStartFired&&(this._idleUpdatesStartFired=!1,this._idleStateCallbacks.forAll(r=>r.idleEnd())))}get state(){return this._state}updateBudget(s){this._test.usedBudget=0,++this._frameNumber;let r=je,n=s.frameDuration,o=Be;switch(this.state){case C.IDLE:r=v(0),n=v(Math.max(He,s.frameDuration)),o=xs;break;case C.INTERACTING:n=v(Math.max(Ze,s.frameDuration));case C.ANIMATING:}return n=v(n-s.elapsedFrameTime-r),this.state!==C.IDLE&&ns.idleBegin())),this._runIdle();break;case C.INTERACTING:this._runInteracting();break;default:this._runAnimating()}this._test.usedBudget=this._budget.elapsed}stopFrame(){this._budget.reset(v(0),this._state),this._budget.madeProgress()}_removeIdleStateCallbacks(s){this._idleUpdatesStartFired&&s.idleEnd(),this._idleStateCallbacks.removeUnordered(s)}removeTask(s){this._tasks.removeUnordered(s),this._runQueue.removeUnordered(s),this._updatingChanged()}_updateTask(s){this._tasks.forAll(r=>{r.name===s&&r.setPriority(s)})}_getState(s){if(this._runQueue.some(n=>n.name===s))return $.SCHEDULED;let r=$.IDLE;return this._tasks.forAll(n=>{n.name===s&&n.needsUpdate&&(n.schedulePriority<=1?r=$.READY:r!==$.READY&&(r=$.WAITING))}),r}_getRuntime(s){let r=0;return this._tasks.forAll(n=>{n.name===s&&(r+=n.runtime)}),r}_resetRuntimes(){this._tasks.forAll(s=>s.runtime=0)}_getRunning(){const s=new Map;if(this._tasks.forAll(n=>{n.needsUpdate&&s.set(n.name,(s.get(n.name)||0)+1)}),s.size===0)return null;let r="";return s.forEach((n,o)=>{r+=n>1?` ${n}x ${o}`:` ${o}`}),r}_runIdle(){this._run()}_runInteracting(){this._run()}_runAnimating(){this._run()}_updateLoad(){const s=this._tasks.reduce((r,n)=>n.needsUpdate?++r:r,0);this._load=this._load*Ye+s*(1-Ye)}_schedule(){for(this._runQueue.filterInPlace(s=>!!s.needsUpdate||(s.schedulePriority=s.basePriority,!1)),this._tasks.forAll(s=>{s.basePriority===N&&s.needsUpdate&&!this._runQueue.includes(s)&&s.blockFrame!==this._frameNumber&&this._runQueue.unshift(s)});this._runQueue.length===0;){let s=!1,r=0;if(this._tasks.forAll(n=>{n.needsUpdate&&n.schedulePriority!==0&&n.basePriority!==N&&n.blockFrame!==this._frameNumber&&(s=!0,r=Math.max(r,n.basePriority),n.schedulePriority===1?(n.schedulePriority=0,this._runQueue.push(n)):--n.schedulePriority)}),!s)return this._updatingChanged(),!1}return this._updatingChanged(),!0}_run(){const s=this._budget.now();this._startFrameTaskTimes();do for(;this._runQueue.length>0;){const r=this._budget.now(),n=this._runQueue.pop();this._budget.resetProgress();try{n.task.runTask(this._budget)===_e.YIELD&&(n.blockFrame=this._frameNumber)}catch(u){xt.getLogger("esri.views.support.Scheduler").error(`Exception in task "${n.name}"`,u),n.blockFrame=this._frameNumber}!this._budget.hasProgressed&&n.blockFrame!==this._frameNumber&&n.needsUpdate&&(n.name,g.I3S_CONTROLLER,n.blockFrame=this._frameNumber),n.schedulePriority=n.basePriority;const o=this._budget.now()-r;if(n.runtime+=o,this._frameTaskTimes.set(n.priority,this._frameTaskTimes.get(n.priority)+o),this._debug&&o>2*this._budget.budget&&console.log("Task",n.name,"used",o,"of max",this._budget.budget,"ms"),this._budget.remaining<=0)return this._updatingChanged(),void this._recordFrameTaskTimes(this._budget.now()-s)}while(this._schedule());this._updatingChanged(),this._recordFrameTaskTimes(this._budget.now()-s)}_startFrameTaskTimes(){for(const s of Object.keys(g))this._frameTaskTimes.set(g[s],0)}_recordFrameTaskTimes(s){this._frameTaskTimes.forEach((r,n)=>this.performanceInfo.tasks.get(n).record(r)),this.performanceInfo.total.record(s)}get test(){return this._test}};l.Scheduler=e;class t{get task(){return this._task.value}get updating(){return this._queue.running}constructor(s,r,n,o){this._scheduler=s,this.name=r,this._basePriority=o,this.blockFrame=0,this.runtime=0,this._queue=new ps,this._handles=new Tt,this.schedulePriority=this._basePriority,this._task=fe(n??this._queue),this._handles.add(Et(()=>this.task.running,u=>s.taskRunningChanged(u)))}remove(){this.processQueue(se),this._scheduler.removeTask(this),this.schedule=We.schedule,this.reschedule=We.reschedule,this._handles.destroy()}get basePriority(){return this._basePriority}setPriority(s){this.name=s;const r=ze(s);this._basePriority!==N&&this.schedulePriority===0||(this.schedulePriority=r),this._basePriority=r}get priority(){return this.name}set priority(s){this.setPriority(s)}get needsUpdate(){return this.updating||this.task.running}schedule(s,r,n){return this._queue.push(s,r,n)}reschedule(s,r,n){return this._queue.unshift(s,r,n)}processQueue(s){this._queue.runTask(s)}}class i{constructor(){this._begin=typeof performance<"u"?performance.now():0,this._budget=0,this._state=C.IDLE,this._done=!1,this._progressed=!1,this._enabled=!0}run(s){return!this.done&&(s()===!0&&this.madeProgress(),!0)}get done(){return this._done}get budget(){return this._budget}madeProgress(){return this._progressed=!0,this._done=this.elapsed>=this._budget&&this._enabled,this._done}get state(){return this._state}get enabled(){return this._enabled}set enabled(s){this._enabled=s}reset(s,r){this._begin=this.now(),this._budget=s,this._state=r,this.resetProgress()}get remaining(){return Math.max(this._budget-this.elapsed,0)}now(){return performance.now()}get elapsed(){return performance.now()-this._begin}resetProgress(){this._progressed=!1,this._done=!1}get hasProgressed(){return this._progressed}}l.Budget=i})(pe||(pe={})),function(l){l.SCHEDULED="s",l.READY="r",l.WAITING="w",l.IDLE="i"}($||($={}));const se=(()=>{const l=new pe.Budget;return l.enabled=!1,l})();class Ts{remove(){}processQueue(){}schedule(e,t,i){try{if(Ke(t)){const a=te();return i?Promise.resolve(i(a)):Promise.reject(a)}return It(e(se))}catch(a){return Promise.reject(a)}}reschedule(e,t,i){return this.schedule(e,t,i)}}const We=new Ts,Es="unsupported-query",Is=new Ft(2e6);let Fs=0;class ks{constructor(e){this._geometryQueryCache=null,this._changeHandle=null,this.capabilities={query:Bt},this.geometryType=e.geometryType,this.hasM=!!e.hasM,this.hasZ=!!e.hasZ,this.objectIdField=e.objectIdField,this.spatialReference=e.spatialReference,this.definitionExpression=e.definitionExpression,this.featureStore=e.featureStore,this.aggregateAdapter=e.aggregateAdapter,this._changeHandle=this.featureStore.events.on("changed",()=>this.clearCache()),this.timeInfo=e.timeInfo,e.cacheSpatialQueries&&(this._geometryQueryCache=new St(Fs+++"$$",Is)),this.fieldsIndex=Rt(e.fieldsIndex)?e.fieldsIndex:wt.fromJSON(e.fieldsIndex),this.availableFields=e.availableFields==null?new Set(this.fieldsIndex.fields.map(t=>t.name)):new Set(e.availableFields.map(t=>{var i;return(i=this.fieldsIndex.get(t))==null?void 0:i.name}).filter(t=>t!=null)),e.scheduler&&e.priority&&(this._frameTask=e.scheduler.registerTask(e.priority))}destroy(){this._frameTask=ge(this._frameTask),this.clearCache(),bt(this._geometryQueryCache),this._changeHandle=ge(this._changeHandle)}get featureAdapter(){return this.featureStore.featureAdapter}clearCache(){var e;(e=this._geometryQueryCache)==null||e.clear(),this._allFeaturesPromise=null,this._timeExtentPromise=null,this._fullExtentPromise=null}async executeQuery(e,t){try{return(await this._executeQuery(e,{},t)).createQueryResponse()}catch(i){if(i!==U)throw i;return new w([],e,this).createQueryResponse()}}async executeQueryForCount(e={},t){try{return(await this._executeQuery(e,{returnGeometry:!1,returnCentroid:!1,outSR:null},t)).createQueryResponseForCount()}catch(i){if(i!==U)throw i;return 0}}async executeQueryForExtent(e,t){const i=e.outSR;try{const a=await this._executeQuery(e,{returnGeometry:!0,returnCentroid:!1,outSR:null},t),s=a.size;return s?{count:s,extent:await this._getBounds(a.items,a.spatialReference,i||this.spatialReference)}:{count:0,extent:null}}catch(a){if(a===U)return{count:0,extent:null};throw a}}async executeQueryForIds(e,t){return this.executeQueryForIdSet(e,t).then(i=>Array.from(i))}async executeQueryForIdSet(e,t){try{const i=await this._executeQuery(e,{returnGeometry:!0,returnCentroid:!1,outSR:null},t),a=i.items,s=new Set;return await this._reschedule(()=>{for(const r of a)s.add(i.featureAdapter.getObjectId(r))},t),s}catch(i){if(i===U)return new Set;throw i}}async executeQueryForSnapping(e,t){const{point:i,distance:a,returnEdge:s,vertexMode:r}=e;if(!s&&r==="none")return{candidates:[]};let n=ee(e.query);n=await this._schedule(()=>Gt(n,this.definitionExpression,this.spatialReference),t),n=await this._reschedule(()=>Ue(n,{availableFields:this.availableFields,fieldsIndex:this.fieldsIndex,geometryType:this.geometryType,spatialReference:this.spatialReference}),t);const o=!L(i.spatialReference,this.spatialReference);o&&await ye(i.spatialReference,this.spatialReference);const u=typeof a=="number"?a:a.x,h=typeof a=="number"?a:a.y,c={xmin:i.x-u,xmax:i.x+u,ymin:i.y-h,ymax:i.y+h,spatialReference:i.spatialReference},m=o?Q(c,this.spatialReference):c;if(!m)return{candidates:[]};const f=(await Ae(Ce(i),null,{signal:t}))[0],_=(await Ae(Ce(m),null,{signal:t}))[0];if(f==null||_==null)return{candidates:[]};const d=new w(await this._reschedule(()=>this._searchFeatures(this._getQueryBBoxes(_.toJSON())),t),n,this);await this._reschedule(()=>this._executeObjectIdsQuery(d),t),await this._reschedule(()=>this._executeTimeQuery(d),t),await this._reschedule(()=>this._executeAttributesQuery(d),t),await this._reschedule(()=>this._executeGeometryQueryForSnapping(d,t),t);const E=f.toJSON(),T=o?Q(E,this.spatialReference):E,F=o?Math.max(m.xmax-m.xmin,m.ymax-m.ymin)/2:a;return d.createSnappingResponse({...e,point:T,distance:F},i.spatialReference)}async executeQueryForLatestObservations(e,t){var i;if(!((i=this.timeInfo)!=null&&i.trackIdField))throw new b(Es,"Missing timeInfo or timeInfo.trackIdField",{query:e,timeInfo:this.timeInfo});try{const a=await this._executeQuery(e,{},t);return await this._reschedule(()=>this._filterLatest(a),t),a.createQueryResponse()}catch(a){if(a!==U)throw a;return new w([],e,this).createQueryResponse()}}async executeQueryForSummaryStatistics(e={},t,i){const{field:a,normalizationField:s,valueExpression:r}=t;return(await this._executeQueryForStatistics(e,{field:a,normalizationField:s,valueExpression:r},i)).createSummaryStatisticsResponse(t)}async executeQueryForUniqueValues(e={},t,i){const{field:a,field2:s,field3:r,valueExpression:n}=t;return(await this._executeQueryForStatistics(e,{field:a,field2:s,field3:r,valueExpression:n},i)).createUniqueValuesResponse(t)}async executeQueryForClassBreaks(e={},t,i){const{field:a,normalizationField:s,valueExpression:r}=t;return(await this._executeQueryForStatistics(e,{field:a,normalizationField:s,valueExpression:r},i)).createClassBreaksResponse(t)}async executeQueryForHistogram(e={},t,i){const{field:a,normalizationField:s,valueExpression:r}=t;return(await this._executeQueryForStatistics(e,{field:a,normalizationField:s,valueExpression:r},i)).createHistogramResponse(t)}async fetchRecomputedExtents(e){this._timeExtentPromise||(this._timeExtentPromise=qt(this.timeInfo,this.featureStore));const[t,i]=await Promise.all([this._getFullExtent(),this._timeExtentPromise]);return At(e),{fullExtent:t,timeExtent:i}}async _getBounds(e,t,i){const a=Ct(vt(),Qt);await this.featureStore.forEachBounds(e,n=>Nt(a,n));const s={xmin:a[0],ymin:a[1],xmax:a[3],ymax:a[4],spatialReference:Z(this.spatialReference)};this.hasZ&&isFinite(a[2])&&isFinite(a[5])&&(s.zmin=a[2],s.zmax=a[5]);const r=Q(s,t,i);if(r.spatialReference=Z(i),r.xmax-r.xmin==0){const n=ue(r.spatialReference);r.xmin-=n,r.xmax+=n}if(r.ymax-r.ymin==0){const n=ue(r.spatialReference);r.ymin-=n,r.ymax+=n}if(this.hasZ&&r.zmin!=null&&r.zmax!=null&&r.zmax-r.zmin==0){const n=ue(r.spatialReference);r.zmin-=n,r.zmax+=n}return r}_getFullExtent(){return this._fullExtentPromise||(this._fullExtentPromise="getFullExtent"in this.featureStore&&this.featureStore.getFullExtent?Promise.resolve(this.featureStore.getFullExtent(this.spatialReference)):this._getAllFeatures().then(e=>this._getBounds(e,this.spatialReference,this.spatialReference))),this._fullExtentPromise}async _schedule(e,t){return this._frameTask!=null?this._frameTask.schedule(e,t):e(se)}async _reschedule(e,t){return this._frameTask!=null?this._frameTask.reschedule(e,t):e(se)}async _getAllFeaturesQueryEngineResult(e){return new w(await this._getAllFeatures(),e,this)}async _getAllFeatures(){if(this._allFeaturesPromise==null){const i=[];this._allFeaturesPromise=(async()=>{await this.featureStore.forEach(a=>i.push(a))})().then(()=>i)}const e=this._allFeaturesPromise,t=await e;return e===this._allFeaturesPromise?t.slice():this._getAllFeatures()}async _executeQuery(e,t,i){e=ee(e),e=await this._schedule(()=>Oe(e,this.definitionExpression,this.spatialReference),i),e=await this._reschedule(()=>Ue(e,{availableFields:this.availableFields,fieldsIndex:this.fieldsIndex,geometryType:this.geometryType,spatialReference:this.spatialReference}),i),e={...e,...t};const a=await this._reschedule(()=>this._executeSceneFilterQuery(e,i),i),s=await this._reschedule(()=>this._executeGeometryQuery(e,a,i),i);return await this._reschedule(()=>this._executeAggregateIdsQuery(s),i),await this._reschedule(()=>this._executeObjectIdsQuery(s),i),await this._reschedule(()=>this._executeTimeQuery(s),i),await this._reschedule(()=>this._executeAttributesQuery(s),i),s}async _executeSceneFilterQuery(e,t){if(e.sceneFilter==null)return null;const{outSR:i,returnGeometry:a,returnCentroid:s}=e,r=this.featureStore.featureSpatialReference,n=e.sceneFilter.geometry,o=r==null||L(r,n.spatialReference)?n:Q(n,r);if(!o)return null;const u=a||s,h=me(i)&&!L(this.spatialReference,i)&&u?async d=>this._project(d,i):d=>d,c=this.featureAdapter,m=await this._reschedule(()=>this._searchFeatures(this._getQueryBBoxes(o)),t);if(e.sceneFilter.spatialRelationship==="disjoint"){if(!m.length)return null;const d=new Set;for(const F of m)d.add(c.getObjectId(F));const E=await this._reschedule(()=>this._getAllFeatures(),t),T=await this._reschedule(async()=>{const F=await z("esriSpatialRelDisjoint",o,this.geometryType,this.hasZ,this.hasM),R=x=>!d.has(c.getObjectId(x))||F(c.getGeometry(x)),y=await this._runSpatialFilter(E,R,t);return new w(y,e,this)},t);return h(T)}if(!m.length)return new w([],e,this);if(this._canExecuteSinglePass(o,e))return h(new w(m,e,this));const f=await z("esriSpatialRelContains",o,this.geometryType,this.hasZ,this.hasM),_=await this._runSpatialFilter(m,d=>f(c.getGeometry(d)),t);return h(new w(_,e,this))}async _executeGeometryQuery(e,t,i){if(t!=null&&t.items.length===0)return t;e=t!=null?t.query:e;const{geometry:a,outSR:s,spatialRel:r,returnGeometry:n,returnCentroid:o}=e,u=this.featureStore.featureSpatialReference,h=!a||u==null||L(u,a.spatialReference)?a:Q(a,u),c=n||o,m=me(s)&&!L(this.spatialReference,s),f=this._geometryQueryCache&&t==null?JSON.stringify(m&&c?{originalFilterGeometry:a,spatialRelationship:r,outSpatialReference:s}:{originalFilterGeometry:a,spatialRelationship:r}):null,_=f?this._geometryQueryCache.get(f):null;if(_!=null)return new w(_,e,this);const d=async y=>(m&&c&&await this._project(y,s),f&&this._geometryQueryCache.put(f,y.items,y.items.length+1),y);if(!h)return d(t??await this._getAllFeaturesQueryEngineResult(e));const E=this.featureAdapter;let T=await this._reschedule(()=>this._searchFeatures(this._getQueryBBoxes(a)),i);if(r==="esriSpatialRelDisjoint"){if(!T.length)return d(t??await this._getAllFeaturesQueryEngineResult(e));const y=new Set;for(const I of T)y.add(E.getObjectId(I));const x=t!=null?t.items:await this._reschedule(()=>this._getAllFeatures(),i),p=await this._reschedule(async()=>{const I=await z(r,h,this.geometryType,this.hasZ,this.hasM),S=O=>!y.has(E.getObjectId(O))||I(E.getGeometry(O)),A=await this._runSpatialFilter(x,S,i);return new w(A,e,this)},i);return d(p)}if(t!=null){const y=new Vt;T=T.filter(x=>Ot(t.items,x,t.items.length,y)>=0)}if(!T.length){const y=new w([],e,this);return f&&this._geometryQueryCache.put(f,y.items,1),y}if(this._canExecuteSinglePass(h,e))return d(new w(T,e,this));const F=await z(r,h,this.geometryType,this.hasZ,this.hasM),R=await this._runSpatialFilter(T,y=>F(E.getGeometry(y)),i);return d(new w(R,e,this))}async _executeGeometryQueryForSnapping(e,t){var n;const{query:i}=e,{spatialRel:a}=i;if(!((n=e==null?void 0:e.items)!=null&&n.length)||!i.geometry||!a)return;const s=await z(a,i.geometry,this.geometryType,this.hasZ,this.hasM),r=await this._runSpatialFilter(e.items,o=>s(o.geometry),t);e.items=r}_executeAggregateIdsQuery(e){var a;if(e.items.length===0||!((a=e.query.aggregateIds)!=null&&a.length)||this.aggregateAdapter==null)return;const t=new Set;for(const s of e.query.aggregateIds)this.aggregateAdapter.getFeatureObjectIds(s).forEach(r=>t.add(r));const i=this.featureAdapter.getObjectId;e.items=e.items.filter(s=>t.has(i(s)))}_executeObjectIdsQuery(e){var a;if(e.items.length===0||!((a=e.query.objectIds)!=null&&a.length))return;const t=new Set(e.query.objectIds),i=this.featureAdapter.getObjectId;e.items=e.items.filter(s=>t.has(i(s)))}_executeTimeQuery(e){if(e.items.length===0)return;const t=zt(this.timeInfo,e.query.timeExtent,this.featureAdapter);t!=null&&(e.items=e.items.filter(t))}_executeAttributesQuery(e){if(e.items.length===0)return;const t=V(e.query.where,this.fieldsIndex);if(t){if(!t.isStandardized)throw new TypeError("Where clause is not standardized");e.items=e.items.filter(i=>t.testFeature(i,this.featureAdapter))}}async _runSpatialFilter(e,t,i){if(!t)return e;if(this._frameTask==null)return e.filter(n=>t(n));let a=0;const s=new Array,r=async n=>{for(;ar(u),i)}};return this._reschedule(n=>r(n),i).then(()=>s)}_filterLatest(e){const{trackIdField:t,startTimeField:i,endTimeField:a}=this.timeInfo,s=a||i,r=new Map,n=this.featureAdapter.getAttribute;for(const o of e.items){const u=n(o,t),h=n(o,s),c=r.get(u);(!c||h>n(c,s))&&r.set(u,o)}e.items=Array.from(r.values())}_canExecuteSinglePass(e,t){const{spatialRel:i}=t;return De(e)&&(i==="esriSpatialRelEnvelopeIntersects"||this.geometryType==="esriGeometryPoint"&&(i==="esriSpatialRelIntersects"||i==="esriSpatialRelContains"))}async _project(e,t){if(!t||L(this.spatialReference,t))return e;const i=this.featureAdapter;let a;try{const r=await this._getFullExtent();a=Dt(this.spatialReference,t,r)}catch{}const s=await jt(e.items.map(r=>B(this.geometryType,this.hasZ,this.hasM,i.getGeometry(r))),this.spatialReference,t,a);return e.items=s.map((r,n)=>i.cloneWithGeometry(e.items[n],Mt(r,this.hasZ,this.hasM))),e}_getQueryBBoxes(e){if(De(e)){if(Pt(e))return[ve(Math.min(e.xmin,e.xmax),Math.min(e.ymin,e.ymax),Math.max(e.xmin,e.xmax),Math.max(e.ymin,e.ymax))];if(Lt(e))return e.rings.map(t=>ve(Math.min(t[0][0],t[2][0]),Math.min(t[0][1],t[2][1]),Math.max(t[0][0],t[2][0]),Math.max(t[0][1],t[2][1])))}return[kt($t(),e)]}async _searchFeatures(e){const t=new Set;await Promise.all(e.map(a=>this.featureStore.forEachInBounds(a,s=>t.add(s))));const i=Array.from(t.values());return t.clear(),i}async _executeQueryForStatistics(e,t,i){e=ee(e);try{e=await this._schedule(()=>Oe(e,this.definitionExpression,this.spatialReference),i),e=await this._reschedule(()=>fs(e,t,{availableFields:this.availableFields,fieldsIndex:this.fieldsIndex,geometryType:this.geometryType,spatialReference:this.spatialReference}),i);const a=await this._reschedule(()=>this._executeSceneFilterQuery(e,i),i),s=await this._reschedule(()=>this._executeGeometryQuery(e,a,i),i);return await this._reschedule(()=>this._executeAggregateIdsQuery(s),i),await this._reschedule(()=>this._executeObjectIdsQuery(s),i),await this._reschedule(()=>this._executeTimeQuery(s),i),await this._reschedule(()=>this._executeAttributesQuery(s),i),s}catch(a){if(a!==U)throw a;return new w([],e,this)}}}export{ks as W};