@vertigis/arcgis-extensions 34.0.1 → 34.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AppConfig.schema.json +16 -0
- package/data/Feature.js +1 -1
- package/data/_TableExtension.js +1 -1
- package/data/convert.js +1 -1
- package/docs/html/assets/js/search.js +1 -1
- package/docs/html/classes/data__tableextension.tableextension.html +8 -8
- package/docs/html/classes/data__tableextension.tablefeaturesettings.html +10 -10
- package/docs/html/classes/data__tableextension.tableschema.html +13 -13
- package/docs/html/classes/data_arcgisservicetableextension.arcgisservicetableextension.html +3 -3
- package/docs/html/classes/layer_preset_layerpreset.layerpreset.html +9 -9
- package/docs/html/classes/layer_preset_layerpresetsettings.layerpresetsetting.html +91 -9
- package/docs/html/classes/mapping__layerextension.arraywrappedcollection.html +2 -2
- package/docs/html/classes/mapping__layerextension.layerextension.html +95 -41
- package/docs/html/classes/mapping__layerextension.layerextensionschema.html +6 -6
- package/docs/html/classes/mapping__sublayerextension.sublayerextension.html +60 -32
- package/docs/html/classes/mapping__sublayerextension.sublayerschema.html +4 -4
- package/docs/html/classes/mapping__sublayerextension.subsublayerextensioncollection.html +6 -6
- package/docs/html/classes/mapping_arcgissublayerextension.arcgissublayerextension.html +47 -19
- package/docs/html/classes/mapping_arcgissublayerextension.arcgissublayerschema.html +2 -2
- package/docs/html/classes/mapping_buildingcomponentsublayerextension.buildingcomponentsublayerextension.html +48 -20
- package/docs/html/classes/mapping_buildingcomponentsublayerextension.buildingcomponentsublayerschema.html +2 -2
- package/docs/html/classes/mapping_buildinggroupsublayerextension.buildinggroupsublayerextension.html +50 -22
- package/docs/html/classes/mapping_buildinggroupsublayerextension.buildinggroupsublayerschema.html +4 -4
- package/docs/html/classes/mapping_buildingscenelayerextension.buildingscenelayerextension.html +86 -32
- package/docs/html/classes/mapping_buildingscenelayerextension.buildingscenelayerreadonlyschema.html +4 -4
- package/docs/html/classes/mapping_buildingsublayerextension.buildingsublayerextension.html +56 -28
- package/docs/html/classes/mapping_buildingsublayerextension.buildingsublayerschema.html +3 -3
- package/docs/html/classes/mapping_csvlayerextension.csvlayerextension.html +93 -39
- package/docs/html/classes/mapping_elevationlayerextension.elevationlayerextension.html +99 -41
- package/docs/html/classes/mapping_featurecollectionlayerextension.featurecollectionlayerextension.html +87 -33
- package/docs/html/classes/mapping_featurelayerextension.featurelayerextension.html +89 -35
- package/docs/html/classes/mapping_featurelayerextensionbase.featurelayerextensionbase.html +91 -37
- package/docs/html/classes/mapping_featurelayerextensionbase.featurelayerschema.html +4 -4
- package/docs/html/classes/mapping_georsslayerextension.georsslayerextension.html +91 -37
- package/docs/html/classes/mapping_graphicslayerextension.graphicslayerextension.html +86 -32
- package/docs/html/classes/mapping_grouplayerextension.grouplayerextension.html +99 -45
- package/docs/html/classes/mapping_grouplayerextension.grouplayerextensioncollection.html +6 -6
- package/docs/html/classes/mapping_imagerylayerextension.imagerylayerextension.html +91 -37
- package/docs/html/classes/mapping_imagerytilelayerextension.imagerytilelayerextension.html +88 -34
- package/docs/html/classes/mapping_integratedmeshlayerextension.integratedmeshlayerextension.html +100 -42
- package/docs/html/classes/mapping_kmllayerextension.kmllayerextension.html +88 -34
- package/docs/html/classes/mapping_kmlsublayerextension.kmlsublayerextension.html +63 -31
- package/docs/html/classes/mapping_mapimagelayerextension.mapimagelayerextension.html +89 -35
- package/docs/html/classes/mapping_mapimagesublayerextension.mapimagesublayerextension.html +44 -16
- package/docs/html/classes/mapping_openstreetmaplayerextension.openstreetmaplayerextension.html +93 -39
- package/docs/html/classes/mapping_pointcloudlayerextension.pointcloudlayerextension.html +101 -43
- package/docs/html/classes/mapping_scenelayerextension.scenelayerextension.html +91 -37
- package/docs/html/classes/mapping_streamlayerextension.streamlayerextension.html +92 -38
- package/docs/html/classes/mapping_streamlayerextension.streamlayerschema.html +4 -4
- package/docs/html/classes/mapping_support_layerlistsettings.extensionbaselayerlistsettings.html +139 -16
- package/docs/html/classes/mapping_support_layerlistsettings.layerlistsettings.html +138 -9
- package/docs/html/classes/mapping_support_layerlistsettings.layerlistsettingsproperties.html +3 -3
- package/docs/html/classes/mapping_tilelayerextension.tilelayerextension.html +87 -33
- package/docs/html/classes/mapping_tilesublayerextension.tilesublayerextension.html +51 -19
- package/docs/html/classes/mapping_vectortilelayerextension.vectortilelayerextension.html +90 -36
- package/docs/html/classes/mapping_webtilelayerextension.webtilelayerextension.html +93 -39
- package/docs/html/classes/mapping_wmslayerextension.wmslayerextension.html +88 -34
- package/docs/html/classes/mapping_wmssublayerextension.wmssublayerextension.html +62 -30
- package/docs/html/classes/mapping_wmtslayerextension.wmtslayerextension.html +88 -34
- package/docs/html/classes/mapping_wmtssublayerextension.wmtssublayerextension.html +62 -30
- package/docs/html/interfaces/layer_preset_layerpreset.layerpresetproperties.html +5 -5
- package/docs/html/interfaces/layer_preset_layerpresetsettings.layerpresetsettingproperties.html +77 -1
- package/docs/html/modules/data_convert.html +1 -1
- package/docs/html/modules/data_feature.html +2 -2
- package/docs/html/modules/mapping__layerextension.html +1 -1
- package/docs/html/modules/mapping_support_layerlistsettings.html +1 -1
- package/docs/html/modules/version.html +1 -1
- package/layer-preset/LayerPreset.js +1 -1
- package/layer-preset/LayerPresetSettings.d.ts +41 -3
- package/layer-preset/LayerPresetSettings.js +1 -1
- package/mapping/ElevationLayerExtension.d.ts +4 -0
- package/mapping/ElevationLayerExtension.js +1 -1
- package/mapping/GroupLayerExtension.d.ts +4 -0
- package/mapping/GroupLayerExtension.js +1 -1
- package/mapping/IntegratedMeshLayerExtension.d.ts +4 -0
- package/mapping/IntegratedMeshLayerExtension.js +1 -1
- package/mapping/KMLSublayerExtension.d.ts +4 -0
- package/mapping/KMLSublayerExtension.js +1 -1
- package/mapping/PointCloudLayerExtension.d.ts +4 -0
- package/mapping/PointCloudLayerExtension.js +1 -1
- package/mapping/TileSublayerExtension.d.ts +4 -0
- package/mapping/TileSublayerExtension.js +1 -1
- package/mapping/WMSSublayerExtension.d.ts +4 -0
- package/mapping/WMSSublayerExtension.js +1 -1
- package/mapping/WMTSSublayerExtension.d.ts +4 -0
- package/mapping/WMTSSublayerExtension.js +1 -1
- package/mapping/_LayerExtension.d.ts +10 -0
- package/mapping/_LayerExtension.js +1 -1
- package/mapping/_SublayerExtension.d.ts +6 -0
- package/mapping/_SublayerExtension.js +1 -1
- package/mapping/support/LayerListSettings.d.ts +18 -5
- package/mapping/support/LayerListSettings.js +1 -1
- package/package.json +3 -2
- package/version.d.ts +1 -1
- package/version.js +1 -1
package/AppConfig.schema.json
CHANGED
|
@@ -3646,10 +3646,26 @@
|
|
|
3646
3646
|
"layer-preset.LayerPresetSettings.LayerPresetSettingProperties": {
|
|
3647
3647
|
"description": "Properties that can be passed into the constructor for\n{@link LayerPresetSetting}.",
|
|
3648
3648
|
"properties": {
|
|
3649
|
+
"childrenIncludedInLayerList": {
|
|
3650
|
+
"description": "See {@link LayerPresetSetting.childrenIncludedInLayerList}.",
|
|
3651
|
+
"type": "boolean"
|
|
3652
|
+
},
|
|
3649
3653
|
"expanded": {
|
|
3650
3654
|
"description": "See {@link LayerPresetSetting.expanded}.",
|
|
3651
3655
|
"type": "boolean"
|
|
3652
3656
|
},
|
|
3657
|
+
"includedInLayerList": {
|
|
3658
|
+
"description": "See {@link LayerPresetSetting.includedInLayerList}.",
|
|
3659
|
+
"type": "boolean"
|
|
3660
|
+
},
|
|
3661
|
+
"maxScale": {
|
|
3662
|
+
"description": "See {@link LayerPresetSetting.maxScale}.",
|
|
3663
|
+
"type": "number"
|
|
3664
|
+
},
|
|
3665
|
+
"minScale": {
|
|
3666
|
+
"description": "See {@link LayerPresetSetting.minScale}.",
|
|
3667
|
+
"type": "number"
|
|
3668
|
+
},
|
|
3653
3669
|
"opacity": {
|
|
3654
3670
|
"description": "See {@link LayerPresetSetting.opacity}.",
|
|
3655
3671
|
"type": "number"
|
package/data/Feature.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import Graphic from"@arcgis/core/Graphic";import*as Arcade from"@arcgis/core/arcade/arcade";import{EntityBase}from"../Entity.js";import{Hyperlink}from"../Hyperlink.js";import{InvalidOperationError}from"../InvalidOperationError.js";import{ItemType}from"../ItemType.js";import{toEsriApiGeometry,toPortalGeometry}from"../portal/Geometry.js";import{serializable}from"../support/Serializable.js";import{MapTransformCollection}from"../utilities/MapTransformCollection.js";import{ObservableMap}from"../utilities/ObservableMap.js";import{ReadOnlyMap}from"../utilities/ReadOnlyMap.js";import{arcadeScriptUsesGeometry,isArcadeScriptAsync,runArcadeExpression,runAsyncArcadeExpression}from"../utilities/arcade.js";import{flatten,groupBy}from"../utilities/array.js";import{checkArg}from"../utilities/checkArg.js";import{Collection}from"../utilities/collection.js";import{parse as parseDate,esriFormatToGeocortexFormat}from"../utilities/date.js";import{isCodedValueDomain}from"../utilities/esri.js";import{some,map as mapIterable,concat,forEach,find}from"../utilities/iterable.js";import{getLogger}from"../utilities/log.js";import{parse as parseNumber,NumberFormat}from"../utilities/number.js";import{map as promiseMap}from"../utilities/promise.js";import{format as formatString}from"../utilities/string.js";import{FeatureSettings}from"./FeatureSettings.js";import{_fieldWithArcadeXRegex,_fieldWithRelationshipRegex,Schema}from"./Schema.js";const log=getLogger("geocortex.api.data.Feature");export const SCORE_FIELD="_score";export const SCORE_FIELD_ORIGINAL="_score_original";let Feature=class extends EntityBase{constructor(e){super(e),this._itemType=ItemType.FEATURE,this._expressionFieldValues=new ObservableMap,this._expressionValuesUpdatePending=!1,this.settings=new FeatureSettings,this.settings._setFeature(this),this.schema=new Schema,this.schema._featureSettings=this.settings,this.attachments=new Collection,this.attributes=new ObservableMap,this._relatedFeatures=new ObservableMap,this.expressionFieldValues=new ExpressionFieldsValuesImpl(this._expressionFieldValues,this)}get geometry(){return this._geometry}set geometry(e){var t;this._notifyChange("geometryType"),this._geometry=toEsriApiGeometry(e),this.schema.spatialReference=null===(t=this._geometry)||void 0===t?void 0:t.spatialReference}get geometryType(){return this.geometry?this.geometry.type:void 0}get source(){return this._source}set source(e){this._source&&this.settings.parent===this._source.featureSettings&&(this.settings.parent=void 0),this._source&&this.schema.parent===this._source.schema&&(this.settings.parent=void 0),this._source=e,this.settings.parent||(this.settings.parent=e?e.featureSettings:void 0),this.schema.parent||(this.schema.parent=e?e.schema:void 0)}get primaryKey(){const e=this.attributes.get(this.schema.primaryKeyField);return null!=e?`${e}`:void 0}get presentableAttributes(){return this._presentableAttributes=this._presentableAttributes||new PresentableAttributesImpl(this),this._presentableAttributes}get title(){return this.format(this._title||"")}get description(){return this.format(this._description)}get hyperlinks(){return this._hyperlinks||(this._hyperlinks=new HyperlinksCollection(this))}get relatedFeatures(){return this._relatedFeatures}get type(){if(this.schema.typeIdField&&this.attributes.has(this.schema.typeIdField)){const e=this.attributes.get(this.schema.typeIdField);return this.schema.types.find((t=>t.id===e))}}get _hydrationStatus(){var e,t;return this._featureHydrationStatus?this._featureHydrationStatus:(null===(t=null===(e=this.source)||void 0===e?void 0:e.capabilities)||void 0===t?void 0:t.supportsQuery)&&1===this.attributes.size&&void 0!==this.primaryKey?"dehydrated":"hydrated"}set _hydrationStatus(e){this._featureHydrationStatus=e}get _title(){let e;return this.settings.popupTemplate&&(e="function"==typeof this.settings.popupTemplate.title?this.settings.popupTemplate.title():this.settings.popupTemplate.title),e||this.schema.displayField&&this.presentableAttributes.get(this.schema.displayField)||""}get _description(){var e;if(null===(e=this.settings.popupTemplate)||void 0===e?void 0:e.content){if("string"==typeof this.settings.popupTemplate.content)return this.settings.popupTemplate.content;if(Array.isArray(this.settings.popupTemplate.content)){const e=this.settings.popupTemplate.content.find((e=>"text"===e.type));if(e)return e.text}}return""}format(e,...t){let r="string"==typeof e?{format:e}:e;checkArg("options",r).isNotMissing();const{format:i}=r;checkArg("format",i).isNotMissing();let s=r.format.replace(escapedBraceRegex,escapedBracePlaceholder);return s=s.replace(fieldTokenRegex,((e,t,i,s,a)=>formatAttribute(this,t||i,s,{...r,format:a?`{0:${a}}`:"{0}"}))),s=s.replace(escapedBracePlaceholderRegex,"{{"),r={...r},r.format=s,formatString(r,...t)}clearExpressionInfos(){this._expressionFieldValues.clear()}async fetchExpressionInfos(e=!1){var t;const{expressionInfos:r}=null!==(t=this.settings.popupTemplate)&&void 0!==t?t:{};if(r)return await Promise.all(r.map((async e=>{var t,r,i,s,a;try{const o=null!==(r=null===(t=this.source)||void 0===t?void 0:t.layer)&&void 0!==r?r:null===(i=this.source)||void 0===i?void 0:i.sublayer;let n=null===(s=this.source)||void 0===s?void 0:s.mapExtension;if(!n){const e=null===(a=this.source)||void 0===a?void 0:a.layerExtension;n=null==e?void 0:e.mapExtension}this._expressionFieldValues.set(e.name,await runAsyncArcadeExpression(e.expression,{layer:o,map:null==n?void 0:n.map,feature:this,spatialReference:this.schema.spatialReference}))}catch(t){t instanceof Error&&log.error({message:"Error evaluating expression '{0}': {1}.",error:t},e.name,t.message),this._expressionFieldValues.set(e.name,invalidRelationshipOrExpression)}}))),e?this.attributes.on("change",(async e=>{this._expressionValuesUpdatePending||(this._expressionValuesUpdatePending=!0,setTimeout((async()=>{this._expressionValuesUpdatePending=!1,await this.fetchExpressionInfos()}),0))})):void 0}async fetchRelatedFeatures(e){if(!this.source)return;let t;if(e){const r="string"==typeof e?this.source.relationships.find((t=>t.id===e)):e;if(!r||!this.source.relationships.includes(r))throw new InvalidOperationError("Relationship not found in feature source.");t=[r]}else t=this.source.relationships.toArray();const r=await promiseMap(t,(async e=>[e,await e.getRelatedFeatures(this)]));for(const e of r)this._relatedFeatures.set(e[0],e[1])}async fetchAttachments(){if(this.source){const e=await this.source.getAttachments(this);for(const t of e){const e=this.attachments.findIndex((e=>e.id===t.id));e>=0?this.attachments.splice(e,1,t):this.attachments.add(t)}}}_getSerializableProperties(){return{...super._getSerializableProperties(),attributes:{serializeModes:["project"],serialize:e=>{var t;const r={};if("project"===e&&this.primaryKey&&(null===(t=this.source)||void 0===t?void 0:t.capabilities).supportsQuery)r[this.schema.primaryKeyField]=this.primaryKey;else for(const[e,t]of this.attributes.entries())r[e]=t;return r},deserialize:e=>{if(this.attributes.clear(),e instanceof Map)e.forEach(((e,t)=>{this.attributes.set(t,e)}));else for(const[t,r]of Object.entries(e))this.attributes.set(t,r)}},geometry:{serializeModes:["project"],serialize:e=>{var t;return"project"===e&&(null===(t=this.source)||void 0===t?void 0:t.capabilities).supportsQuery?this.getDefault("geometry"):toPortalGeometry(this.geometry)},deserialize:e=>this.geometry=toEsriApiGeometry(e)},settings:{serializeModes:["project"],serialize:e=>{var t;return"project"===e&&(null===(t=this.source)||void 0===t?void 0:t.capabilities).supportsQuery?this.getDefault("settings"):this.settings.toJSON(e)}},schema:{serializeModes:["project"],serialize:e=>{var t;return"project"===e&&(null===(t=this.source)||void 0===t?void 0:t.capabilities).supportsQuery?this.getDefault("schema"):this.schema.toJSON(e)}},source:["project"]}}_watchProperty(e,t,r,i){if("title"===e||"description"===e){const s=super._watchProperty(e,t,r,i),a="title"===e?"settings.popupTemplate.title":"settings.popupTemplate.content",o=this.watch(a,(()=>{this._notifyChange(e)})),n=this.presentableAttributes.on("change",(()=>{this._notifyChange(e)}));return{remove(){s.remove(),o.remove(),n.remove()}}}return super._watchProperty(e,t,r,i)}async _onInitialize(){const e=this._findRelationshipIds(this._title,this._description),t=this.source?this.source.relationships.map((e=>e.id)).toArray():[],r=[];for(const i of e)t.includes(i)?r.push(this.fetchRelatedFeatures(i)):log.error("Could not find relationship '{0}' referenced in feature title or description.",i);await Promise.all(r)}_findRelationshipIds(...e){const t=[];for(const r of e){let e;const i=r.replace(escapedBraceRegex,escapedBracePlaceholder);for(;e=relationshipIdRegex.exec(i),null!==e;){const r=e[0];t.includes(r)||t.push(e[1])}}return t}};Feature=__decorate([serializable],Feature);export{Feature};export function toFeature(e,t){const r=new Feature(t);for(const t of Object.keys(e.attributes))r.attributes.set(t,e.attributes[t]);return r.geometry=e.geometry,e.popupTemplate&&(r.settings.popupTemplate=e.popupTemplate),r}export function toGraphic(e){var t,r;const i=new Graphic;i.attributes={};for(const t of e.attributes.keys())i.attributes[t]=e.attributes.get(t);return(null===(t=e.source)||void 0===t?void 0:t.layer)&&(i.layer=null===(r=e.source)||void 0===r?void 0:r.layer),i.geometry=e.geometry,e.settings.popupTemplate&&(i.popupTemplate=e.settings.popupTemplate),i}const ERR_PRESENTABLE_ATTRIBUTES_READONLY="Presentable attributes are read-only.",ERR_HYPERLINK_READONLY="Feature hyperlinks are read-only. Modify the feature's hyperlink templates instead.";class ExpressionFieldsValuesImpl extends ReadOnlyMap{constructor(e,t){super(e),this._feature=t}get(e){var t,r;if(!super.has(e)){const{spatialReference:i}=this._feature.schema,s=null===(r=null===(t=this._feature.settings.popupTemplate)||void 0===t?void 0:t.expressionInfos)||void 0===r?void 0:r.find((t=>t.name===e));if(!s)return;(async()=>{var t,r,a,o,n;try{if(isArcadeScriptAsync(s.expression,i)){const l=null!==(r=null===(t=this._feature.source)||void 0===t?void 0:t.layer)&&void 0!==r?r:null===(a=this._feature.source)||void 0===a?void 0:a.sublayer;let p=null===(o=this._feature.source)||void 0===o?void 0:o.mapExtension;if(!p){const e=null===(n=this._feature.source)||void 0===n?void 0:n.layerExtension;p=null==e?void 0:e.mapExtension}this._originalMap.set(e,await runAsyncArcadeExpression(s.expression,{feature:this._feature,layer:l,map:null==p?void 0:p.map,spatialReference:i}))}else arcadeScriptUsesGeometry(s.expression,i)&&await Arcade.enableGeometrySupport(),this._originalMap.set(e,runArcadeExpression(s.expression,{feature:this._feature,spatialReference:i}))}catch(t){t instanceof Error&&log.error({message:"Error evaluating expression '{0}': {1}.",error:t},e,t.message),this._originalMap.set(e,invalidRelationshipOrExpression)}})()}return super.get(e)}}class PresentableAttributesImpl extends ReadOnlyMap{constructor(e){super(new ObservableMap),this._feature=e}get size(){return this._feature.attributes.size+this._feature.schema.fields._expressionFieldsLength}clear(){throw new InvalidOperationError(ERR_PRESENTABLE_ATTRIBUTES_READONLY)}delete(e){throw new InvalidOperationError(ERR_PRESENTABLE_ATTRIBUTES_READONLY)}forEach(e,t){checkArg("callback",e).isNotMissing();for(const r of this.keys())e.call(t,this.get(r),r,this)}get(e){const t=this._getFieldExtensionFormat(e);return this._formatAttribute(e,t)}has(e){return some(this.keys(),(t=>t===e))}set(...e){throw new InvalidOperationError(ERR_PRESENTABLE_ATTRIBUTES_READONLY)}*entries(){yield*mapIterable(this.keys(),(e=>[e,this.get(e)]))}*keys(){var e;const t=this._feature.schema.fields.expressionFields.map((e=>e.name)),r=[];(null===(e=this._feature.source)||void 0===e?void 0:e.relationships)&&this._feature.source.relationships.filter((e=>"one-to-one"===e.cardinality||"many-to-one"===e.cardinality)).forEach((e=>r.push(...e.relatedSource.schema.fields.map((t=>`relationships/${e.id}/${t.name}`)).toArray()))),yield*concat(this._feature.attributes.keys(),t.toArray(),r)}*values(){yield*mapIterable(this.keys(),(e=>this.get(e)))}[Symbol.iterator](){return this.entries()}toJSON(){return Array.from(this.entries())}on(e,t){if(checkArg("callback",t).isNotMissing(),!this._numObservers){const e=new Map,t=new Set,r=()=>{t.forEach((e=>e.remove())),t.clear()},i=()=>{const t={added:Array.from(this.entries()).filter((t=>t[1]!==e.get(t[0]))),removed:Array.from(e.entries()).filter((e=>!this.has(e[0])||e[1]!==this.get(e[0]))),target:this};(t.added.length||t.removed.length)&&(this.emit("change",t),s())},s=()=>{e.clear(),r(),forEach(this.keys(),(r=>{const s=this._getFieldExtension(r);let a="{0}";if(s){const e=s.watch("format",(()=>{i()}));t.add(e),s.format&&(a=s.format)}e.set(r,this._formatAttribute(r,a))}))};s();const a=this._feature.attributes.on("change",(()=>{i()})),o=this._feature.schema.fieldExtensions.on("change",(()=>{i()})),n=this._feature.settings.formatSettings.watch(["numberFormat","dateFormat","locale"],(()=>{i()})),l=this._feature.expressionFieldValues.on("change",(()=>{i()})),p=this._feature.schema.fields.on("change",(e=>{var t,r;((null===(t=e.added)||void 0===t?void 0:t.some((e=>null!==e.name.match(_fieldWithArcadeXRegex))))||(null===(r=e.removed)||void 0===r?void 0:r.some((e=>null!==e.name.match(_fieldWithArcadeXRegex)))))&&i()})),u=this._feature.settings.watch("popupTemplate",(()=>{i()}));this._onAllObserversRemoved=()=>{l.remove(),a.remove(),o.remove(),p.remove(),n.remove(),u.remove(),e.clear(),r()}}const r=super.on("change",t);return this._numObservers++,{remove:()=>{r.remove(),this._numObservers--,this._numObservers||this._onAllObserversRemoved()}}}watch(e,t){if("size"===e){const e=this._feature.attributes.watch("size",((e,r)=>{t(e+this._feature.schema.fields._expressionFieldsLength,r+this._feature.schema.fields._expressionFieldsLength,"size",this)})),r=this._feature.schema.fields.watch("_expressionFieldsLength",((e,r)=>{t(e+this._feature.attributes.size,r+this._feature.attributes.size,"size",this)}));return{remove:()=>{e.remove(),r.remove()}}}return super.watch(e,t)}_getFieldExtension(e){const t=this._feature.schema.findFieldByName(e);if(t)return this._feature.schema.fieldExtensions.forField(t)}_getFieldExtensionFormat(e){const t=this._getFieldExtension(e);return t?t.format:"{0}"}_formatAttribute(e,t){const r=e.match(_fieldWithArcadeXRegex),i=e.match(_fieldWithRelationshipRegex);if(r)return formatAttribute(this._feature,"expression",r[1],{format:t});if(i){const[,e,r]=i;return formatAttribute(this._feature,e,r,{format:t})}return formatAttribute(this._feature,void 0,e,{format:t})}}const fieldTokenRegex=/\{(?:relationships[\\/](\w\w*)[\\/])?(?:(expression)[\\/])?([a-zA-Z][.\w]*)(?::([^}]*))?\}/g,relationshipIdRegex=/\{relationships\/(\w\w*)[\\/]([^}]*)\}/g,escapedBraceRegex=/{{/g,escapedBracePlaceholder="\0MAGIC\0",escapedBracePlaceholderRegex=new RegExp(escapedBracePlaceholder,"g"),invalidRelationshipOrExpression="#INVALID";class HyperlinksCollection extends MapTransformCollection{constructor(e){super(e.settings.hyperlinkTemplates,(e=>this._getHyperlink(e))),this._feature=e}_getHyperlink(e){return this._hyperlinks=this._hyperlinks||new WeakMap,this._hyperlinks.has(e)||this._hyperlinks.set(e,new FeatureHyperlink(this._feature,e)),this._hyperlinks.get(e)}}let FeatureHyperlink=class extends Hyperlink{constructor(e,t){super(t.toJSON()),this._feature=e,this._template=t}get url(){return this._template.url?this._feature.format(this._template.url):this._template.url}set url(e){throw new InvalidOperationError(ERR_HYPERLINK_READONLY)}get text(){return this._template.text?this._feature.format(this._template.text):this._template.text}set text(e){throw new InvalidOperationError(ERR_HYPERLINK_READONLY)}get iconUrl(){return this._template.iconUrl?this._feature.format(this._template.iconUrl):this._template.iconUrl}set iconUrl(e){throw new InvalidOperationError(ERR_HYPERLINK_READONLY)}get target(){return this._template.target?this._feature.format(this._template.target):this._template.target}set target(e){throw new InvalidOperationError(ERR_HYPERLINK_READONLY)}get tooltip(){return this._template.tooltip?this._feature.format(this._template.tooltip):this._template.tooltip}set tooltip(e){throw new InvalidOperationError(ERR_HYPERLINK_READONLY)}_watchProperty(e,t,r,i){const s=super._watchProperty(e,t,r,i),a=this._template.watch(e,(()=>{this._notifyChange(e)})),o=this._feature.presentableAttributes.on("change",(()=>{this._notifyChange(e)}));return{remove:()=>{s.remove(),a.remove(),o.remove()}}}_getSerializableProperties(){return{}}};function formatAttribute(e,t,r,i={format:"{0}"}){var s,a,o,n;if("expression"!==t){if(t){const s=find(e.relatedFeatures.keys(),(e=>e.id===t));if(!s)return log.debug("Could not resolve related field '{0}/{1}",t,r),invalidRelationshipOrExpression;const a=Array.from(e.relatedFeatures.get(s));return"many-to-one"===s.cardinality||"one-to-one"===s.cardinality?a.length<1?(log.debug("Could not resolve related field '{0}/{1}",t,r),invalidRelationshipOrExpression):formatAttributeValue(a[0],r,i):a.map((e=>formatAttributeValue(e,r,i))).filter((e=>""!==e)).join(",")}return formatAttributeValue(e,r,i)}if(!(null===(a=null===(s=e.settings.popupTemplate)||void 0===s?void 0:s.expressionInfos)||void 0===a?void 0:a.find((e=>e.name===r))))return log.debug("Could not find expression '{0}'.",r),invalidRelationshipOrExpression;try{const t=null!==(n=null!==(o=e.expressionFieldValues.get(r))&&void 0!==o?o:i.defaultExpressionValue)&&void 0!==n?n:"",s=e.schema.findFieldByName(`expression/${r}`);let a=i;if(s){const t=e.schema.fieldExtensions.forField(s);a=formatOptionsForField(e,r,formatOptionsFromSettings(t.formatSettings),a)}return formatValue(e,t,a)}catch(e){if(e instanceof Error)return log.error({message:"Error evaluating expression '{0}': {1}.",error:e},r,e.message),invalidRelationshipOrExpression;throw e}}function formatAttributeValue(e,t,r){var i,s;let a=e.attributes.get(t);if(null==a)return"";const o=e.schema.findFieldByName(t);let n={format:"{0}"};const l=null===(s=null===(i=e.type)||void 0===i?void 0:i.domains)||void 0===s?void 0:s[t];if(t===e.schema.typeIdField)a=e.type?e.type.name:a;else if(isCodedValueDomain(l)){const e=l.codedValues.find((e=>`${e.code}`==`${a.toString()}`));a=e?e.name:a}else if(o)if(isCodedValueDomain(o.domain)){const e=o.domain.codedValues.find((e=>`${e.code}`==`${a.toString()}`));e&&(a=e.name)}else{switch(o.type){case"integer":case"small-integer":case"single":case"double":a=parseNumber(a);break;case"date":a=parseDate({timeZone:e.schema.timeZone},a);break;default:a=`${a.toString()}`}n=formatOptionsFromSettings(e.schema.fieldExtensions.forField(o).formatSettings)}return formatValue(e,a,formatOptionsForField(e,t,n,r))}function formatValue(e,t,r){let i=r;if("number"==typeof t||t instanceof Date){i={...formatOptionsFromSettings(e.settings.formatSettings),...r}}return"{0}"===i.format&&"string"==typeof t?t:formatString(i,t)}function formatOptionsFromSettings(e){return{format:"{0}",dateFormat:e.dateFormat,numberFormat:e.numberFormat,currency:e.currency,fractionalDigits:e.fractionalDigits,locale:e.locale,timeZone:e.timeZone}}function formatOptionsForField(e,t,r,i){const{popupTemplate:s}=e.settings,a=(null==s?void 0:s.fieldInfos)?s.fieldInfos.find((e=>e.fieldName===t)):void 0,o=a?a.format:void 0;let n;return o&&(n={format:"{0}",numberFormat:o.digitSeparator?NumberFormat.NUMBER:NumberFormat.FIXED_POINT,dateFormat:esriFormatToGeocortexFormat(o.dateFormat),fractionalDigits:o.places}),{...n,...r,...i}}FeatureHyperlink=__decorate([serializable],FeatureHyperlink);export async function resolveRelatedFeatures(e){const t=groupBy(e,(e=>e.source));await Promise.all(flatten([...t.keys()].map((e=>e.relationships.toArray()))).map((e=>(async e=>{[...(await e.getAllRelatedFeatures(t.get(e.source))).entries()].forEach((([t,r])=>{t.relatedFeatures.set(e,r)}))})(e))))}
|
|
1
|
+
import{__decorate}from"tslib";import Graphic from"@arcgis/core/Graphic";import*as Arcade from"@arcgis/core/arcade/arcade";import{EntityBase}from"../Entity.js";import{Hyperlink}from"../Hyperlink.js";import{InvalidOperationError}from"../InvalidOperationError.js";import{ItemType}from"../ItemType.js";import{toEsriApiGeometry,toPortalGeometry}from"../portal/Geometry.js";import{serializable}from"../support/Serializable.js";import{MapTransformCollection}from"../utilities/MapTransformCollection.js";import{ObservableMap}from"../utilities/ObservableMap.js";import{ReadOnlyMap}from"../utilities/ReadOnlyMap.js";import{arcadeScriptUsesGeometry,isArcadeScriptAsync,runArcadeExpression,runAsyncArcadeExpression}from"../utilities/arcade.js";import{flatten,groupBy}from"../utilities/array.js";import{checkArg}from"../utilities/checkArg.js";import{Collection}from"../utilities/collection.js";import{parse as parseDate,esriFormatToGeocortexFormat}from"../utilities/date.js";import{isCodedValueDomain}from"../utilities/esri.js";import{some,map as mapIterable,concat,forEach,find}from"../utilities/iterable.js";import{getLogger}from"../utilities/log.js";import{parse as parseNumber,NumberFormat}from"../utilities/number.js";import{map as promiseMap}from"../utilities/promise.js";import{format as formatString}from"../utilities/string.js";import{FeatureSettings}from"./FeatureSettings.js";import{_fieldWithArcadeXRegex,_fieldWithRelationshipRegex,Schema}from"./Schema.js";const log=getLogger("geocortex.api.data.Feature");export const SCORE_FIELD="_score";export const SCORE_FIELD_ORIGINAL="_score_original";let Feature=class extends EntityBase{constructor(e){super(e),this._itemType=ItemType.FEATURE,this._expressionFieldValues=new ObservableMap,this._expressionValuesUpdatePending=!1,this.settings=new FeatureSettings,this.settings._setFeature(this),this.schema=new Schema,this.schema._featureSettings=this.settings,this.attachments=new Collection,this.attributes=new ObservableMap,this._relatedFeatures=new ObservableMap,this.expressionFieldValues=new ExpressionFieldsValuesImpl(this._expressionFieldValues,this)}get geometry(){return this._geometry}set geometry(e){var t;this._notifyChange("geometryType"),this._geometry=toEsriApiGeometry(e),this.schema.spatialReference=null===(t=this._geometry)||void 0===t?void 0:t.spatialReference}get geometryType(){return this.geometry?this.geometry.type:void 0}get source(){return this._source}set source(e){this._source&&this.settings.parent===this._source.featureSettings&&(this.settings.parent=void 0),this._source&&this.schema.parent===this._source.schema&&(this.settings.parent=void 0),this._source=e,this.settings.parent||(this.settings.parent=e?e.featureSettings:void 0),this.schema.parent||(this.schema.parent=e?e.schema:void 0)}get primaryKey(){const e=this.attributes.get(this.schema.primaryKeyField);return null!=e?`${e}`:void 0}get presentableAttributes(){return this._presentableAttributes=this._presentableAttributes||new PresentableAttributesImpl(this),this._presentableAttributes}get title(){return this.format(this._title||"")}get description(){return this.format(this._description)}get hyperlinks(){return this._hyperlinks||(this._hyperlinks=new HyperlinksCollection(this))}get relatedFeatures(){return this._relatedFeatures}get type(){if(this.schema.typeIdField&&this.attributes.has(this.schema.typeIdField)){const e=this.attributes.get(this.schema.typeIdField);return this.schema.types.find((t=>t.id===e))}}get _hydrationStatus(){var e,t;return this._featureHydrationStatus?this._featureHydrationStatus:(null===(t=null===(e=this.source)||void 0===e?void 0:e.capabilities)||void 0===t?void 0:t.supportsQuery)&&1===this.attributes.size&&void 0!==this.primaryKey?"dehydrated":"hydrated"}set _hydrationStatus(e){this._featureHydrationStatus=e}get _title(){let e;return this.settings.popupTemplate&&(e="function"==typeof this.settings.popupTemplate.title?this.settings.popupTemplate.title():this.settings.popupTemplate.title),e||this.schema.displayField&&this.presentableAttributes.get(this.schema.displayField)||""}get _description(){var e;if(null===(e=this.settings.popupTemplate)||void 0===e?void 0:e.content){if("string"==typeof this.settings.popupTemplate.content)return this.settings.popupTemplate.content;if(Array.isArray(this.settings.popupTemplate.content)){const e=this.settings.popupTemplate.content.find((e=>"text"===e.type));if(e)return e.text}}return""}format(e,...t){let r="string"==typeof e?{format:e}:e;checkArg("options",r).isNotMissing();const{format:i}=r;checkArg("format",i).isNotMissing();let s=r.format.replace(escapedBraceRegex,escapedBracePlaceholder);return s=s.replace(fieldTokenRegex,((e,t,i,s,a)=>formatAttribute(this,t||i,s,{...r,format:a?`{0:${a}}`:"{0}"}))),s=s.replace(escapedBracePlaceholderRegex,"{{"),r={...r},r.format=s,formatString(r,...t)}clearExpressionInfos(){this._expressionFieldValues.clear()}async fetchExpressionInfos(e=!1){var t;const{expressionInfos:r}=null!==(t=this.settings.popupTemplate)&&void 0!==t?t:{};if(r)return await Promise.all(r.map((async e=>{var t,r,i,s,a;try{const o=null!==(r=null===(t=this.source)||void 0===t?void 0:t.layer)&&void 0!==r?r:null===(i=this.source)||void 0===i?void 0:i.sublayer;let n=null===(s=this.source)||void 0===s?void 0:s.mapExtension;if(!n){const e=null===(a=this.source)||void 0===a?void 0:a.layerExtension;n=null==e?void 0:e.mapExtension}this._expressionFieldValues.set(e.name,await runAsyncArcadeExpression(e.expression,{layer:o,map:null==n?void 0:n.map,feature:this,spatialReference:this.schema.spatialReference}))}catch(t){t instanceof Error&&log.error({message:"Error evaluating expression '{0}': {1}.",error:t},e.name,t.message),this._expressionFieldValues.set(e.name,invalidRelationshipOrExpression)}}))),e?this.attributes.on("change",(async e=>{this._expressionValuesUpdatePending||(this._expressionValuesUpdatePending=!0,setTimeout((async()=>{this._expressionValuesUpdatePending=!1,await this.fetchExpressionInfos()}),0))})):void 0}async fetchRelatedFeatures(e){if(!this.source)return;let t;if(e){const r="string"==typeof e?this.source.relationships.find((t=>t.id===e)):e;if(!r||!this.source.relationships.includes(r))throw new InvalidOperationError("Relationship not found in feature source.");t=[r]}else t=this.source.relationships.toArray();const r=await promiseMap(t,(async e=>[e,await e.getRelatedFeatures(this)]));for(const e of r)this._relatedFeatures.set(e[0],e[1])}async fetchAttachments(){if(this.source){const e=await this.source.getAttachments(this);for(const t of e){const e=this.attachments.findIndex((e=>e.id===t.id));e>=0?this.attachments.splice(e,1,t):this.attachments.add(t)}}}_getSerializableProperties(){return{...super._getSerializableProperties(),attributes:{serializeModes:["project"],serialize:e=>{var t;const r={};if("project"===e&&this.primaryKey&&(null===(t=this.source)||void 0===t?void 0:t.capabilities).supportsQuery)r[this.schema.primaryKeyField]=this.primaryKey;else for(const[e,t]of this.attributes.entries())r[e]=t;return r},deserialize:e=>{if(this.attributes.clear(),e instanceof Map)e.forEach(((e,t)=>{this.attributes.set(t,e)}));else for(const[t,r]of Object.entries(e))this.attributes.set(t,r)}},geometry:{serializeModes:["project"],serialize:e=>{var t;return"project"===e&&(null===(t=this.source)||void 0===t?void 0:t.capabilities).supportsQuery?this.getDefault("geometry"):toPortalGeometry(this.geometry)},deserialize:e=>this.geometry=toEsriApiGeometry(e)},settings:{serializeModes:["project"],serialize:e=>{var t;return"project"===e&&(null===(t=this.source)||void 0===t?void 0:t.capabilities).supportsQuery?this.getDefault("settings"):this.settings.toJSON(e)}},schema:{serializeModes:["project"],serialize:e=>{var t;return"project"===e&&(null===(t=this.source)||void 0===t?void 0:t.capabilities).supportsQuery?this.getDefault("schema"):this.schema.toJSON(e)}},source:["project"]}}_watchProperty(e,t,r,i){if("title"===e||"description"===e){const s=super._watchProperty(e,t,r,i),a="title"===e?"settings.popupTemplate.title":"settings.popupTemplate.content",o=this.watch(a,(()=>{this._notifyChange(e)})),n=this.presentableAttributes.on("change",(()=>{this._notifyChange(e)}));return{remove(){s.remove(),o.remove(),n.remove()}}}return super._watchProperty(e,t,r,i)}async _onInitialize(){const e=this._findRelationshipIds(this._title,this._description),t=this.source?this.source.relationships.map((e=>e.id)).toArray():[],r=[];for(const i of e)t.includes(i)?r.push(this.fetchRelatedFeatures(i)):log.error("Could not find relationship '{0}' referenced in feature title or description.",i);await Promise.all(r)}_findRelationshipIds(...e){const t=[];for(const r of e){let e;const i=r.replace(escapedBraceRegex,escapedBracePlaceholder);for(;e=relationshipIdRegex.exec(i),null!==e;){const r=e[0];t.includes(r)||t.push(e[1])}}return t}};Feature=__decorate([serializable],Feature);export{Feature};export function toFeature(e,t){const r=new Feature(t);if(e.attributes)for(const t of Object.keys(e.attributes))r.attributes.set(t,e.attributes[t]);return r.geometry=e.geometry,e.popupTemplate&&(r.settings.popupTemplate=e.popupTemplate),r}export function toGraphic(e){var t,r;const i=new Graphic;i.attributes={};for(const t of e.attributes.keys())i.attributes[t]=e.attributes.get(t);return(null===(t=e.source)||void 0===t?void 0:t.layer)&&(i.layer=null===(r=e.source)||void 0===r?void 0:r.layer),i.geometry=e.geometry,e.settings.popupTemplate&&(i.popupTemplate=e.settings.popupTemplate),i}const ERR_PRESENTABLE_ATTRIBUTES_READONLY="Presentable attributes are read-only.",ERR_HYPERLINK_READONLY="Feature hyperlinks are read-only. Modify the feature's hyperlink templates instead.";class ExpressionFieldsValuesImpl extends ReadOnlyMap{constructor(e,t){super(e),this._feature=t}get(e){var t,r;if(!super.has(e)){const{spatialReference:i}=this._feature.schema,s=null===(r=null===(t=this._feature.settings.popupTemplate)||void 0===t?void 0:t.expressionInfos)||void 0===r?void 0:r.find((t=>t.name===e));if(!s)return;(async()=>{var t,r,a,o,n;try{if(isArcadeScriptAsync(s.expression,i)){const l=null!==(r=null===(t=this._feature.source)||void 0===t?void 0:t.layer)&&void 0!==r?r:null===(a=this._feature.source)||void 0===a?void 0:a.sublayer;let p=null===(o=this._feature.source)||void 0===o?void 0:o.mapExtension;if(!p){const e=null===(n=this._feature.source)||void 0===n?void 0:n.layerExtension;p=null==e?void 0:e.mapExtension}this._originalMap.set(e,await runAsyncArcadeExpression(s.expression,{feature:this._feature,layer:l,map:null==p?void 0:p.map,spatialReference:i}))}else arcadeScriptUsesGeometry(s.expression,i)&&await Arcade.enableGeometrySupport(),this._originalMap.set(e,runArcadeExpression(s.expression,{feature:this._feature,spatialReference:i}))}catch(t){t instanceof Error&&log.error({message:"Error evaluating expression '{0}': {1}.",error:t},e,t.message),this._originalMap.set(e,invalidRelationshipOrExpression)}})()}return super.get(e)}}class PresentableAttributesImpl extends ReadOnlyMap{constructor(e){super(new ObservableMap),this._feature=e}get size(){return this._feature.attributes.size+this._feature.schema.fields._expressionFieldsLength}clear(){throw new InvalidOperationError(ERR_PRESENTABLE_ATTRIBUTES_READONLY)}delete(e){throw new InvalidOperationError(ERR_PRESENTABLE_ATTRIBUTES_READONLY)}forEach(e,t){checkArg("callback",e).isNotMissing();for(const r of this.keys())e.call(t,this.get(r),r,this)}get(e){const t=this._getFieldExtensionFormat(e);return this._formatAttribute(e,t)}has(e){return some(this.keys(),(t=>t===e))}set(...e){throw new InvalidOperationError(ERR_PRESENTABLE_ATTRIBUTES_READONLY)}*entries(){yield*mapIterable(this.keys(),(e=>[e,this.get(e)]))}*keys(){var e;const t=this._feature.schema.fields.expressionFields.map((e=>e.name)),r=[];(null===(e=this._feature.source)||void 0===e?void 0:e.relationships)&&this._feature.source.relationships.filter((e=>"one-to-one"===e.cardinality||"many-to-one"===e.cardinality)).forEach((e=>r.push(...e.relatedSource.schema.fields.map((t=>`relationships/${e.id}/${t.name}`)).toArray()))),yield*concat(this._feature.attributes.keys(),t.toArray(),r)}*values(){yield*mapIterable(this.keys(),(e=>this.get(e)))}[Symbol.iterator](){return this.entries()}toJSON(){return Array.from(this.entries())}on(e,t){if(checkArg("callback",t).isNotMissing(),!this._numObservers){const e=new Map,t=new Set,r=()=>{t.forEach((e=>e.remove())),t.clear()},i=()=>{const t={added:Array.from(this.entries()).filter((t=>t[1]!==e.get(t[0]))),removed:Array.from(e.entries()).filter((e=>!this.has(e[0])||e[1]!==this.get(e[0]))),target:this};(t.added.length||t.removed.length)&&(this.emit("change",t),s())},s=()=>{e.clear(),r(),forEach(this.keys(),(r=>{const s=this._getFieldExtension(r);let a="{0}";if(s){const e=s.watch("format",(()=>{i()}));t.add(e),s.format&&(a=s.format)}e.set(r,this._formatAttribute(r,a))}))};s();const a=this._feature.attributes.on("change",(()=>{i()})),o=this._feature.schema.fieldExtensions.on("change",(()=>{i()})),n=this._feature.settings.formatSettings.watch(["numberFormat","dateFormat","locale"],(()=>{i()})),l=this._feature.expressionFieldValues.on("change",(()=>{i()})),p=this._feature.schema.fields.on("change",(e=>{var t,r;((null===(t=e.added)||void 0===t?void 0:t.some((e=>null!==e.name.match(_fieldWithArcadeXRegex))))||(null===(r=e.removed)||void 0===r?void 0:r.some((e=>null!==e.name.match(_fieldWithArcadeXRegex)))))&&i()})),u=this._feature.settings.watch("popupTemplate",(()=>{i()}));this._onAllObserversRemoved=()=>{l.remove(),a.remove(),o.remove(),p.remove(),n.remove(),u.remove(),e.clear(),r()}}const r=super.on("change",t);return this._numObservers++,{remove:()=>{r.remove(),this._numObservers--,this._numObservers||this._onAllObserversRemoved()}}}watch(e,t){if("size"===e){const e=this._feature.attributes.watch("size",((e,r)=>{t(e+this._feature.schema.fields._expressionFieldsLength,r+this._feature.schema.fields._expressionFieldsLength,"size",this)})),r=this._feature.schema.fields.watch("_expressionFieldsLength",((e,r)=>{t(e+this._feature.attributes.size,r+this._feature.attributes.size,"size",this)}));return{remove:()=>{e.remove(),r.remove()}}}return super.watch(e,t)}_getFieldExtension(e){const t=this._feature.schema.findFieldByName(e);if(t)return this._feature.schema.fieldExtensions.forField(t)}_getFieldExtensionFormat(e){const t=this._getFieldExtension(e);return t?t.format:"{0}"}_formatAttribute(e,t){const r=e.match(_fieldWithArcadeXRegex),i=e.match(_fieldWithRelationshipRegex);if(r)return formatAttribute(this._feature,"expression",r[1],{format:t});if(i){const[,e,r]=i;return formatAttribute(this._feature,e,r,{format:t})}return formatAttribute(this._feature,void 0,e,{format:t})}}const fieldTokenRegex=/\{(?:relationships[\\/](\w\w*)[\\/])?(?:(expression)[\\/])?([a-zA-Z][.\w]*)(?::([^}]*))?\}/g,relationshipIdRegex=/\{relationships\/(\w\w*)[\\/]([^}]*)\}/g,escapedBraceRegex=/{{/g,escapedBracePlaceholder="\0MAGIC\0",escapedBracePlaceholderRegex=new RegExp(escapedBracePlaceholder,"g"),invalidRelationshipOrExpression="#INVALID";class HyperlinksCollection extends MapTransformCollection{constructor(e){super(e.settings.hyperlinkTemplates,(e=>this._getHyperlink(e))),this._feature=e}_getHyperlink(e){return this._hyperlinks=this._hyperlinks||new WeakMap,this._hyperlinks.has(e)||this._hyperlinks.set(e,new FeatureHyperlink(this._feature,e)),this._hyperlinks.get(e)}}let FeatureHyperlink=class extends Hyperlink{constructor(e,t){super(t.toJSON()),this._feature=e,this._template=t}get url(){return this._template.url?this._feature.format(this._template.url):this._template.url}set url(e){throw new InvalidOperationError(ERR_HYPERLINK_READONLY)}get text(){return this._template.text?this._feature.format(this._template.text):this._template.text}set text(e){throw new InvalidOperationError(ERR_HYPERLINK_READONLY)}get iconUrl(){return this._template.iconUrl?this._feature.format(this._template.iconUrl):this._template.iconUrl}set iconUrl(e){throw new InvalidOperationError(ERR_HYPERLINK_READONLY)}get target(){return this._template.target?this._feature.format(this._template.target):this._template.target}set target(e){throw new InvalidOperationError(ERR_HYPERLINK_READONLY)}get tooltip(){return this._template.tooltip?this._feature.format(this._template.tooltip):this._template.tooltip}set tooltip(e){throw new InvalidOperationError(ERR_HYPERLINK_READONLY)}_watchProperty(e,t,r,i){const s=super._watchProperty(e,t,r,i),a=this._template.watch(e,(()=>{this._notifyChange(e)})),o=this._feature.presentableAttributes.on("change",(()=>{this._notifyChange(e)}));return{remove:()=>{s.remove(),a.remove(),o.remove()}}}_getSerializableProperties(){return{}}};function formatAttribute(e,t,r,i={format:"{0}"}){var s,a,o,n;if("expression"!==t){if(t){const s=find(e.relatedFeatures.keys(),(e=>e.id===t));if(!s)return log.debug("Could not resolve related field '{0}/{1}",t,r),invalidRelationshipOrExpression;const a=Array.from(e.relatedFeatures.get(s));return"many-to-one"===s.cardinality||"one-to-one"===s.cardinality?a.length<1?(log.debug("Could not resolve related field '{0}/{1}",t,r),invalidRelationshipOrExpression):formatAttributeValue(a[0],r,i):a.map((e=>formatAttributeValue(e,r,i))).filter((e=>""!==e)).join(",")}return formatAttributeValue(e,r,i)}if(!(null===(a=null===(s=e.settings.popupTemplate)||void 0===s?void 0:s.expressionInfos)||void 0===a?void 0:a.find((e=>e.name===r))))return log.debug("Could not find expression '{0}'.",r),invalidRelationshipOrExpression;try{const t=null!==(n=null!==(o=e.expressionFieldValues.get(r))&&void 0!==o?o:i.defaultExpressionValue)&&void 0!==n?n:"",s=e.schema.findFieldByName(`expression/${r}`);let a=i;if(s){const t=e.schema.fieldExtensions.forField(s);a=formatOptionsForField(e,r,formatOptionsFromSettings(t.formatSettings),a)}return formatValue(e,t,a)}catch(e){if(e instanceof Error)return log.error({message:"Error evaluating expression '{0}': {1}.",error:e},r,e.message),invalidRelationshipOrExpression;throw e}}function formatAttributeValue(e,t,r){var i,s;let a=e.attributes.get(t);if(null==a)return"";const o=e.schema.findFieldByName(t);let n={format:"{0}"};const l=null===(s=null===(i=e.type)||void 0===i?void 0:i.domains)||void 0===s?void 0:s[t];if(t===e.schema.typeIdField)a=e.type?e.type.name:a;else if(isCodedValueDomain(l)){const e=l.codedValues.find((e=>`${e.code}`==`${a.toString()}`));a=e?e.name:a}else if(o)if(isCodedValueDomain(o.domain)){const e=o.domain.codedValues.find((e=>`${e.code}`==`${a.toString()}`));e&&(a=e.name)}else{switch(o.type){case"integer":case"small-integer":case"single":case"double":a=parseNumber(a);break;case"date":a=parseDate({timeZone:e.schema.timeZone},a);break;default:a=`${a.toString()}`}n=formatOptionsFromSettings(e.schema.fieldExtensions.forField(o).formatSettings)}return formatValue(e,a,formatOptionsForField(e,t,n,r))}function formatValue(e,t,r){let i=r;if("number"==typeof t||t instanceof Date){i={...formatOptionsFromSettings(e.settings.formatSettings),...r}}return"{0}"===i.format&&"string"==typeof t?t:formatString(i,t)}function formatOptionsFromSettings(e){return{format:"{0}",dateFormat:e.dateFormat,numberFormat:e.numberFormat,currency:e.currency,fractionalDigits:e.fractionalDigits,locale:e.locale,timeZone:e.timeZone}}function formatOptionsForField(e,t,r,i){const{popupTemplate:s}=e.settings,a=(null==s?void 0:s.fieldInfos)?s.fieldInfos.find((e=>e.fieldName===t)):void 0,o=a?a.format:void 0;let n;return o&&(n={format:"{0}",numberFormat:o.digitSeparator?NumberFormat.NUMBER:NumberFormat.FIXED_POINT,dateFormat:esriFormatToGeocortexFormat(o.dateFormat),fractionalDigits:o.places}),{...n,...r,...i}}FeatureHyperlink=__decorate([serializable],FeatureHyperlink);export async function resolveRelatedFeatures(e){const t=groupBy(e,(e=>e.source));await Promise.all(flatten([...t.keys()].map((e=>e.relationships.toArray()))).map((e=>(async e=>{[...(await e.getAllRelatedFeatures(t.get(e.source))).entries()].forEach((([t,r])=>{t.relatedFeatures.set(e,r)}))})(e))))}
|
package/data/_TableExtension.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import Collection from"@arcgis/core/core/Collection";import{InvalidOperationError}from"../InvalidOperationError.js";import{ItemType}from"../ItemType.js";import{applyToEsriTable,fromEsriTable,toEsriApiTable}from"../portal/Table.js";import{serializable}from"../support/Serializable.js";import{CollectionProxy}from"../utilities/CollectionProxy.js";import{isFeatureLayer,isLayer}from"../utilities/_layers.js";import{checkArg}from"../utilities/checkArg.js";import{deepClone}from"../utilities/object.js";import{FeatureSettings}from"./FeatureSettings.js";import{FeatureSourceBase}from"./FeatureSourceBase.js";import{Schema}from"./Schema.js";const ERR_INVALID_TABLE_TYPE="Invalid type of table for this type of table extension.",ERR_SPATIAL_SETTINGS_NOT_SUPPORTED="Spatial settings are not supported for tables.",DEFAULT_CAPABILITIES=Object.freeze({supportsAdd:!1,supportsUpdate:!1,supportsDelete:!1,supportsEditing:!1,supportsQuery:!1});export class TableExtension extends FeatureSourceBase{constructor(e){super(e),this._itemType=ItemType.TABLE_EXTENSION;const{table:t}={...this.getDefaults(),...e};if(isLayer(t))checkArg("properties.table",t).satisfies((e=>isFeatureLayer(e)),ERR_INVALID_TABLE_TYPE),this._setTable(t);else{if(!t)throw new Error("Missing 'table' property.");this._deferredTableProperties=t}}get mapExtension(){return this._mapExtension}get table(){return this._table}get capabilities(){return DEFAULT_CAPABILITIES}get title(){return this.table?this.
|
|
1
|
+
import{__decorate}from"tslib";import Collection from"@arcgis/core/core/Collection";import{InvalidOperationError}from"../InvalidOperationError.js";import{ItemType}from"../ItemType.js";import{applyToEsriTable,fromEsriTable,toEsriApiTable}from"../portal/Table.js";import{serializable}from"../support/Serializable.js";import{CollectionProxy}from"../utilities/CollectionProxy.js";import{isFeatureLayer,isLayer}from"../utilities/_layers.js";import{checkArg}from"../utilities/checkArg.js";import{deepClone}from"../utilities/object.js";import{FeatureSettings}from"./FeatureSettings.js";import{FeatureSourceBase}from"./FeatureSourceBase.js";import{Schema}from"./Schema.js";const ERR_INVALID_TABLE_TYPE="Invalid type of table for this type of table extension.",ERR_SPATIAL_SETTINGS_NOT_SUPPORTED="Spatial settings are not supported for tables.",DEFAULT_CAPABILITIES=Object.freeze({supportsAdd:!1,supportsUpdate:!1,supportsDelete:!1,supportsEditing:!1,supportsQuery:!1});export class TableExtension extends FeatureSourceBase{constructor(e){super(e),this._itemType=ItemType.TABLE_EXTENSION;const{table:t}={...this.getDefaults(),...e};if(isLayer(t))checkArg("properties.table",t).satisfies((e=>isFeatureLayer(e)),ERR_INVALID_TABLE_TYPE),this._setTable(t);else{if(!t)throw new Error("Missing 'table' property.");this._deferredTableProperties=t}}get mapExtension(){return this._mapExtension}get table(){return this._table}get capabilities(){return DEFAULT_CAPABILITIES}get title(){var e,t,i,r,s,a,l,o,n,d,b,h;return null!==(h=null!==(r=null!==(t=null===(e=this.table)||void 0===e?void 0:e.title)&&void 0!==t?t:null===(i=this._deferredTableProperties)||void 0===i?void 0:i.title)&&void 0!==r?r:"string"==typeof(null===(s=this._deferredTableProperties)||void 0===s?void 0:s.$ref)?null===(a=this._deferredTableProperties)||void 0===a?void 0:a.$ref:null!==(n=null===(o=null===(l=this._deferredTableProperties)||void 0===l?void 0:l.$ref)||void 0===o?void 0:o.title)&&void 0!==n?n:null===(b=null===(d=this._deferredTableProperties)||void 0===d?void 0:d.$ref)||void 0===b?void 0:b.id)&&void 0!==h?h:"Table"}static create(e){if(!TableExtension.factory)throw new InvalidOperationError("Cannot create table extension: no table extension factory has been registered.");return TableExtension.factory.create(e)}static _matchesRef(e,t){var i,r,s,a;if(!e||!t)return!1;const l=null!==(r=null===(i=e.table)||void 0===i?void 0:i.id)&&void 0!==r?r:e._deferredTableProperties.id,o=null!==(a=null===(s=e.table)||void 0===s?void 0:s.title)&&void 0!==a?a:e._deferredTableProperties.title,n=t.$ref;return"string"==typeof n?l===n||o===n:!!n&&(l===n.id||o===n.title)}async _createBackingTable(){this.table||this._deferredTableProperties&&this._deferredTableProperties.$ref||(this._setTable(await toEsriApiTable(this._deferredTableProperties)),await this.table.load(),checkArg("properties.table",this.table).satisfies((e=>this._isSupportedTable(e)),ERR_INVALID_TABLE_TYPE),this._deferredTableProperties=void 0)}_setMapExtension(e){const t=this.mapExtension;this._mapExtension=e,t&&this.featureSettings.formatSettings.parent===t.formatSettings&&(this.featureSettings.formatSettings.parent=void 0),e&&(this.featureSettings.formatSettings.parent||(this.featureSettings.formatSettings.parent=e.formatSettings)),this._resolveTable(),this.notifyChange("mapExtension")}_resolveTable(){var e,t;if(this._table||!this._deferredTableProperties||!this.mapExtension)return;let i;i="string"==typeof this._deferredTableProperties.$ref?{id:this._deferredTableProperties.$ref,title:this._deferredTableProperties.$ref}:this._deferredTableProperties.$ref;let r=null===(e=this._mapExtension.map)||void 0===e?void 0:e.tables.find((e=>e.id===i.id));if(r||(r=null===(t=this._mapExtension.map)||void 0===t?void 0:t.tables.find((e=>e.title===i.title))),r&&this._isSupportedTable(r)){this._setTable(r);const e={table:this._deferredTableProperties};this.assignProperties(e),this._originalRef=this._deferredTableProperties.$ref,this._deferredTableProperties=void 0}}_getSerializableProperties(){return{...super._getSerializableProperties(),table:{serializeModes:["initial","project"],serialize:()=>this.table?this._mapExtension&&(this.table.id||this.table.title)?this._originalRef?{$ref:this._originalRef}:{$ref:{id:this.table.id,title:this.table.title}}:fromEsriTable(this.table):this._deferredTableProperties?deepClone(this._deferredTableProperties):void 0,deserialize:e=>{if(isLayer(e)){if(e!==this.table)throw new Error("Property 'table' is read-only.")}else this.table?applyToEsriTable(e,this.table):this._deferredTableProperties&&(this._deferredTableProperties={...this._deferredTableProperties,...e})}}}}async _onInitialize(){if(await super._onInitialize(),await this._createBackingTable(),this._resolveTable(),!this.table){const e=this._deferredTableProperties.$ref;throw this._mapExtension?new InvalidOperationError(`No table found matching reference "${null==e?void 0:e.toString()}".`):new InvalidOperationError("Cannot resolve table reference: missing parent map extension.")}await this.table.load()}_createSchema(){return new TableSchema(this)}_createFeatureSettings(){return new TableFeatureSettings}_setTable(e){this._table=e,this.notifyChange("table"),this.notifyChange("title"),this.notifyChange("capabilities")}}let TableSchema=class extends Schema{constructor(e){if(super(),this._tableBindings=new Map,this._tableExtension=e,this._bindSettingToTableProperty("primaryKeyField","objectIdField"),this._fieldCollection=this._createFieldCollection(),e.table)this._onTableResolved(e.table);else{const t=e.watch("table",(()=>{this._onTableResolved(e.table),t.remove()}),!0)}}get _fields(){return this._fieldCollection}get geometryType(){}set geometryType(e){throw new InvalidOperationError("Tables do not support a geometry type.")}get spatialReference(){}set spatialReference(e){throw new InvalidOperationError("Tables do not support a spatial reference.")}_getSetting(e,t){return this._tableBindings.has(e)&&this._tableExtension.table?this._tableExtension.table[this._tableBindings.get(e)]:super._getSetting(e,t)}_setSetting(e,t){this._tableBindings.has(e)&&this._tableExtension.table?this._tableExtension.table[this._tableBindings.get(e)]=t:super._setSetting(e,t)}_bindSettingToTableProperty(e,t){const i=null!=t?t:e;this._tableBindings.set(e,i),this._tableExtension.watch(`table.${i}`,(()=>this.notifyChange(e)),!0)}_onTableResolved(e){for(const t of this._tableBindings.keys())this.isModified(t)&&(e[t]=this[t],this.reset(t))}_createFieldCollection(){return new FieldCollection(this._tableExtension)}};TableSchema=__decorate([serializable],TableSchema);export{TableSchema};class FieldCollection extends CollectionProxy{constructor(e){super(),this._tableResolved=!1;const t=e.table;if(null==t?void 0:t.fields)this._onTableResolved(e.table);else{this._collection=new Collection;const t=e.watch(["table","table.loaded"],(()=>{const i=e.table;(null==i?void 0:i.fields)&&(this._onTableResolved(e.table),t.remove())}),!0)}}_onTableResolved(e){if(!this._tableResolved){this._tableResolved=!0;const t=e;this.length&&(t.fields.length=0,t.fields.push(...this.toArray())),t.fields||(t.fields=[]),this._collection=wrapArrayWithCollection(t.fields)}}}function wrapArrayWithCollection(e){const t=new Collection;return Object.defineProperty(t,"_items",{get:()=>e}),Object.defineProperty(t,"length",{get:()=>e.length,set:t=>e.length=t}),t}let TableFeatureSettings=class extends FeatureSettings{get returnGeometry(){}set returnGeometry(e){throw new InvalidOperationError(ERR_SPATIAL_SETTINGS_NOT_SUPPORTED)}get outSpatialReference(){}set outSpatialReference(e){throw new InvalidOperationError(ERR_SPATIAL_SETTINGS_NOT_SUPPORTED)}get maxAllowableOffset(){}set maxAllowableOffset(e){throw new InvalidOperationError(ERR_SPATIAL_SETTINGS_NOT_SUPPORTED)}get zoomScale(){}set zoomScale(e){throw new InvalidOperationError(ERR_SPATIAL_SETTINGS_NOT_SUPPORTED)}get zoomFactor(){}set zoomFactor(e){throw new InvalidOperationError(ERR_SPATIAL_SETTINGS_NOT_SUPPORTED)}};TableFeatureSettings=__decorate([serializable],TableFeatureSettings);export{TableFeatureSettings};
|
package/data/convert.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import Point from"@arcgis/core/geometry/Point";import SpatialReference from"@arcgis/core/geometry/SpatialReference";import{translate}from"../locale/language.js";import{toEsriApiGeometry,toPortalGeometry}from"../portal/Geometry.js";import{checkArg,assertNever}from"../utilities/checkArg.js";import{parse as parseDate,format as formatDate,DEFAULT_PARSING_FORMATS,DateFormat,INVALID_DATE}from"../utilities/date.js";import{esriToWKT,esriToGeoJSON,geoJSONToEsri,wktToEsri,esriWkidToWkt,esriWktToWkid,project,isPoint,isMultipoint,isPolyline,isPolygon,isExtent}from"../utilities/geometry.js";import{getLogger}from"../utilities/log.js";import{parse as parseNumber,format as formatNumber,NumberFormat,isNumeric}from"../utilities/number.js";import{Feature}from"./Feature.js";import{FeatureSet}from"./FeatureSet.js";const FORMULA_TRIGGER_CHARS=["=","-","+","@"],QUOTE='"',FIELD_NAME_REGEX=/[^a-zA-Z\d_]/g,DEFAULT_WINDOWS_ROW_DELIMITER="\r\n",DEFAULT_UNIX_ROW_DELIMITER="\n",DEFAULT_SHEET_NAME="sheet1",DEFAULT_EXCEL_DATE_FORMATS=[...DEFAULT_PARSING_FORMATS.map(_convertToExcelDateFormatString),"M/d/yy"],shapefileNameRegex=/(\w+)_(point|multipoint|polyline|polygon)z?/;var DBaseTypes;function _getConvertLogger(){return getLogger("geocortex.api.data.convert")}!function(e){e.DATE="D",e.NUMBER="N",e.STRING="C",e.BOOLEAN="L"}(DBaseTypes||(DBaseTypes={}));export var GeometryFormat;!function(e){e.NONE="NONE",e.WKT="WKT",e.XY="XY",e.XYZ="XYZ",e.LAT_LON="LAT_LONG",e.GEO_JSON="GEO_JSON",e.ARCGIS_JSON="ARCGIS_JSON"}(GeometryFormat||(GeometryFormat={}));export async function toCsv(e,t){checkArg("featureSet",e).isNotMissing();const r=Array.from(e),o={...{useFormattedValues:!1,alwaysQuote:!1,escapeFormulaChars:!0,delimiter:",",dateFormat:DateFormat.ROUND_TRIP,geometryFormat:r.some((e=>void 0!==e.geometry&&null!==e.geometry))?GeometryFormat.WKT:GeometryFormat.NONE,includeByteOrderMark:!0,outSpatialReference:SpatialReference.WGS84,includeHeaderRow:!0,outFields:_getDefaultOutFields(e.source),rowDelimiter:navigator.platform.startsWith("Win")?"\r\n":"\n"},...t},{includeByteOrderMark:a,includeHeaderRow:n,delimiter:i,outFields:s,rowDelimiter:m}=o,l=[];a&&l.push("\ufeff");const u=_getGeometryColumns(r,o),c=_getAttributeColumns(r,s,e.schema,!0),f=_getAttributeColumns(r,s,e.schema,!1);if(n){const e=[];for(const t of u)e.push(_quotify(t,o));for(const t of c)e.push(_quotify(t,o));for(const t of f)e.push(_quotify(t,o));const t=e.join(i)+m;l.push(t)}await Promise.all(r.map((async e=>{const t=[],r=(t,r)=>_quotify(_stringify(_getAttributeValue(e,t,r),r),r);t.push(...await _getCSVGeometry(e.geometry,o)),t.push(...c.map((e=>r(e,o)))),t.push(...f.map((e=>r(e,o))));const a=`${t.join(i)}${m}`;l.push(a)})));return new Blob(l,{type:"text/plain",endings:"\n"===m||"\r\n"===m?"transparent":"native"})}export async function csvToFeatureSet(e,t){let r;if(checkArg("csvData",e).isNotMissing(),e instanceof Blob){const t=new Promise(((t,r)=>{const o=new FileReader;o.onload=()=>{t(o.result)},o.onerror=()=>{r(o.error)},o.readAsText(e)}));r=await t}else r=e;const o={...{delimiter:",",escapeFormulaChars:!0,includeHeaderRow:!0,outFields:["*"],inSpatialReference:SpatialReference.WGS84,generatePrimaryKey:!0,primaryKeyField:"OBJECTID"},...t,detectOid:!(null==t?void 0:t.primaryKeyField)},a=_parseCSV(r,o.rowDelimiter||_parseRowDelimiter(r),o.delimiter),n=_parseGeometries(a,o),i=_parseSchema(a,n,o),s=await _parseFeatures(a,n,i,o);return new FeatureSet({features:s,schema:i})}export async function toXLSX(e,t){var r;checkArg("featureSet",e).isNotMissing();const o=Array.from(e),a={...{useFormattedValues:!1,includeHeaderRow:!0,escapeFormulaChars:!0,geometryFormat:o.some((e=>void 0!==e.geometry&&null!==e.geometry))?GeometryFormat.WKT:GeometryFormat.NONE,outFields:_getDefaultOutFields(e.source),outSpatialReference:SpatialReference.WGS84,dateFormat:DateFormat.DEFAULT,numberFormat:NumberFormat.DEFAULT,sheetName:"sheet1"},...t},{outFields:n,includeHeaderRow:i,numberFormat:s}=a,m=[],l=_getGeometryColumns(o,a),u=_getAttributeColumns(o,n,e.schema,!0),c=_getAttributeColumns(o,n,e.schema,!1);if(i){const t=l.concat(u).concat(_getXlsxColumnName(c,e.source));m.push(t)}await Promise.all(o.map((async e=>{const t=[];t.push(...await _getGeometry(e.geometry,a));for(const r of u){const o=_toXLSXValue(e.attributes.get(r),a);t.push(o)}for(const r of c){const o=_toXLSXValue(_getAttributeValue(e,r,a),a);t.push(o)}m.push(t)})));const f=await import("xlsx"),p={SheetNames:[],Sheets:{}},d=f.utils.aoa_to_sheet(m,{cellDates:!0});for(const e of Object.keys(d).filter((e=>!e.startsWith("!")))){const t=d[e];"d"===t.t?t.z=_convertToExcelDateFormatString(null!==(r=a.dateFormat)&&void 0!==r?r:DateFormat.ROUND_TRIP):"n"===t.t&&(t.z=_convertToExcelNumberFormatString(s))}p.SheetNames.push(a.sheetName),p.Sheets[a.sheetName]=d;const y=f.write(p,{type:"binary",bookType:"xlsx",compression:!0,bookSST:!0,cellDates:!0}),g=new Uint8Array(y.length);for(let e=0;e<y.length;e++)g[e]=y.charCodeAt(e);return new Blob([g.buffer],{type:"text/plain"})}export async function xlsxToFeatureSet(e,t){checkArg("xlsxData",e).isNotMissing();const r={...{includeHeaderRow:!0,escapeFormulaChars:!0,outFields:["*"],inSpatialReference:SpatialReference.WGS84,generatePrimaryKey:!0,primaryKeyField:"OBJECTID"},...t,detectOid:!(null==t?void 0:t.primaryKeyField)},o=await _parseXLSX(e,r),a=_parseGeometries(o,r),n=_parseSchema(o,a,r),i=await _parseFeatures(o,a,n,r);return new FeatureSet({features:i,schema:n})}export async function toShapefile(e,t){checkArg("featureSet",e).isNotMissing();const[{default:r},o]=await Promise.all([import("jszip"),import("../forked-libs/shp-write/index.js")]),a=Array.from(e),n={...{useFormattedValues:!1,outFields:_getDefaultOutFields(e.source),fileName:e.title||"export"},...t},{outFields:i,outSpatialReference:s,fileName:m}=n,l=new Map,u=a.filter((e=>isPoint(e.geometry)));l.set(u.some((e=>e.geometry.hasZ||e.geometry.hasM))?"POINTZ":"POINT",u);const c=a.filter((e=>isMultipoint(e.geometry)));l.set(c.some((e=>e.geometry.hasZ||e.geometry.hasM))?"MULTIPOINTZ":"MULTIPOINT",c);const f=a.filter((e=>isPolyline(e.geometry)));l.set(f.some((e=>e.geometry.hasZ||e.geometry.hasM))?"POLYLINEZ":"POLYLINE",f);const p=a.filter((e=>isPolygon(e.geometry)||isExtent(e.geometry)));l.set(p.some((e=>e.geometry.hasZ||e.geometry.hasM))?"POLYGONZ":"POLYGON",p);const d=_getAttributeColumns(a,i,e.schema,!0);let y=_getAttributeColumns(a,i,e.schema,!1);y=d.concat(y);const g=new r,h=Array.from(l.keys()).filter((e=>l.get(e).length>0));await Promise.all(h.map((async t=>{const r=l.get(t),a=await Promise.all(r.map((e=>_projectGeometry(e.geometry,s)))),i=await _getDBaseSpatialReferenceWKT(a),u=n.useFormattedValues?Object.assign({},...y.map((e=>({[e]:DBaseTypes.STRING})))):_getDBaseColumnTypes(r,y,e.schema,"timestamp"===n.dateFormat),c=_getDBaseGeometries(a),f=_getDbaseValues(r,y,u,n);o.write(f,t,c,((e,r)=>{const o=h.length>1?`${m}_${t.toLowerCase()}`:m;g.file(`${o}.shp`,r.shp.buffer,{binary:!0}),g.file(`${o}.shx`,r.shx.buffer,{binary:!0}),g.file(`${o}.dbf`,r.dbf.buffer,{binary:!0}),g.file(`${o}.prj`,i)}))})));const F=await g.generateAsync({type:"uint8array"});return new Blob([F.buffer],{type:"text/plain"})}export async function shapefileToFeatureSet(e,t){checkArg("shapefileData",e).isNotMissing();const r={outFields:["*"],includeHeaderRow:!0,generatePrimaryKey:!0,primaryKeyField:"OBJECTID",...t,detectOid:!(null==t?void 0:t.primaryKeyField)},o=new Promise(((t,r)=>{const o=new FileReader;o.onload=()=>{t(o.result)},o.onerror=()=>{r(o.error)},o.readAsArrayBuffer(e)})),[{default:a},n]=await Promise.all([import("jszip"),import("shpjs")]),i=await o,s=await a.loadAsync(new Uint8Array(i)),m=s.filter((()=>!0)).map((e=>e.name));let l,u=m.filter((e=>e.endsWith(".shp"))).map((e=>e.substring(0,e.length-4)));if(u=_parseShapefileNames(u),m.some((e=>e.endsWith(".prj")))&&!u.every((e=>m.includes(`${e}.prj`))))throw new Error("Shapefile zip must contain the same prj file for each separate shapefile");await Promise.all(m.filter((e=>e.endsWith(".prj"))).map((async e=>{const t=await s.file(e).async("string");if(l){if(t!==l)throw new Error("Shapefile zip must contain the same prj file for each separate shapefile")}else l=t})));const c={geometries:[],columnCount:0,columnIndex:0};let f=[];for(const e of u){if(!m.includes(`${e}.shx`)||!m.includes(`${e}.dbf`))throw new Error("Shapefile must contain shp, shx, and dbf files.");const t=await s.file(`${e}.shp`).async("uint8array"),r=n.parseShp(t),o=await s.file(`${e}.dbf`).async("uint8array"),a=n.parseDbf(o);if(a.length!==r.length)throw new Error("Shapefile must contain shp, shx, and dbf files.");const i=await Promise.all(r.map((e=>_parseShpGeometry(e,l))));c.geometries=c.geometries.concat(i),f=f.concat(a)}const p=_parseDBaseData(f),d=_parseSchema(p,c,r),y=await _parseFeatures(p,c,d,r);return new FeatureSet({features:y,schema:d})}function _getGeometryColumns(e,t){return t.geometryFormat===GeometryFormat.XYZ?["x","y","z"]:t.geometryFormat===GeometryFormat.XY?["x","y"]:t.geometryFormat===GeometryFormat.LAT_LON?["latitude","longitude"]:t.geometryFormat===GeometryFormat.NONE?[]:["geometry"]}function _getAttributeColumns(e,t,r,o){const a=r.fields.filter((e=>"oid"===e.type)).map((e=>e.name)).toArray();if(o)return a;if(t&&!t.includes("*"))return t.filter((e=>!a.includes(e)));{const t=r.fields.filter((e=>"oid"!==e.type)).map((e=>e.name)).toArray();let o=[];for(const r of e)for(const e of r.attributes.keys())t.includes(e)||a.includes(e)||o.includes(e)||o.push(e);return o=o.sort(),t.concat(o)}}function _getXlsxColumnName(e,t){var r;const o=null===(r=null==t?void 0:t.schema)||void 0===r?void 0:r.fieldExtensions.initializedItems.map((e=>e.field));return e.map((e=>{var t,r;return null!==(r=null===(t=null==o?void 0:o.find((t=>t.name===e)))||void 0===t?void 0:t.alias)&&void 0!==r?r:e}))}function _getDefaultOutFields(e){var t,r,o,a,n,i,s,m;if(!e)return["*"];const l=null===(t=e.featureSettings.popupTemplate)||void 0===t?void 0:t.content,u=Array.isArray(l)?null===(a=null===(o=null===(r=l.find((e=>"fields"===e.type)))||void 0===r?void 0:r.fieldInfos)||void 0===o?void 0:o.filter((e=>e.visible)))||void 0===a?void 0:a.map((e=>e.fieldName)):void 0;return null!==(m=null!=u?u:null===(s=null===(i=null===(n=e.featureSettings.popupTemplate)||void 0===n?void 0:n.fieldInfos)||void 0===i?void 0:i.filter((e=>e.visible)))||void 0===s?void 0:s.map((e=>e.fieldName)))&&void 0!==m?m:["*"]}async function _getCSVGeometry(e,t){let r=await _getGeometry(e,t);return t.geometryFormat!==GeometryFormat.XYZ&&t.geometryFormat!==GeometryFormat.XY&&t.geometryFormat!==GeometryFormat.LAT_LON||(r=r.map((e=>void 0===e?"":_stringify(e,t)))),r.map((e=>""===e?"":_quotify(e,t)))}async function _getGeometry(e,t){const r=await _projectGeometry(e,t.outSpatialReference);if(t.geometryFormat===GeometryFormat.XYZ){if(!r)return["","",""];if(!isPoint(r))throw new Error("Cannot use geometry format XYZ with non-point geometry");return[r.x,r.y,r.z]}if(t.geometryFormat===GeometryFormat.XY){if(!r)return["",""];if(!isPoint(r))throw new Error("Cannot use geometry format XY with non-point geometry");return[r.x,r.y]}if(t.geometryFormat===GeometryFormat.LAT_LON){if(!r)return["",""];if(!isPoint(r))throw new Error("Cannot use geometry format LAT_LONG with non-point geometry");return[r.y,r.x]}return t.geometryFormat===GeometryFormat.ARCGIS_JSON?r?[JSON.stringify(toPortalGeometry(r))]:[""]:t.geometryFormat===GeometryFormat.WKT?r?[esriToWKT(r)]:[""]:t.geometryFormat===GeometryFormat.GEO_JSON?r?[JSON.stringify(esriToGeoJSON(r))]:[""]:[]}async function _projectGeometry(e,t){return(null==e?void 0:e.spatialReference)&&!e.spatialReference.equals(t)&&t?(await project([e],t))[0]:e}function _quotify(e,t){const r=[t.delimiter,'"',"\r","\n",t.rowDelimiter];if(t.alwaysQuote||r.some((t=>e.includes(t)))){return`"${e.replace(new RegExp('"',"g"),'""')}"`}return e}function _stringify(e,t){if(null==e)return"";if(!t.useFormattedValues){if("number"==typeof e){const r=t.numberFormat||NumberFormat.ROUND_TRIP;return formatNumber(r,e)}if(e instanceof Date)return"timestamp"===t.dateFormat?e.getTime().toString():formatDate({format:t.dateFormat,timeZone:"UTC"},e)}let r=e.toString();return t.escapeFormulaChars&&(r=escapeFormulaChars(r)),r}function _getAttributeValue(e,t,r){var o,a,n;if(r.useFormattedValues||_hasCodedDomain(e,t))return null!==(o=e.presentableAttributes.get(t))&&void 0!==o?o:e.attributes.get(t);if("date"===(null===(a=e.schema.findFieldByName(t))||void 0===a?void 0:a.type)){const r=parseDate(e.attributes.get(t));if(!isNaN(r.getTime()))return r}return null!==(n=e.attributes.get(t))&&void 0!==n?n:e.presentableAttributes.get(t)}function _hasCodedDomain(e,t){var r,o,a,n,i;return t===e.schema.typeIdField||("coded-value"===(null===(a=null===(o=null===(r=e.type)||void 0===r?void 0:r.domains)||void 0===o?void 0:o[t])||void 0===a?void 0:a.type)||"coded-value"===(null===(i=null===(n=e.schema.findFieldByName(t))||void 0===n?void 0:n.domain)||void 0===i?void 0:i.type))}function escapeFormulaChars(e){for(const t of FORMULA_TRIGGER_CHARS)if(e.startsWith(t))return`\t${e}`;return e}function _parseRowDelimiter(e){let t="\n";return _forDelimiter(e,"\r\n",((r,o)=>(0===r&&o===e.length||(t="\r\n"),!1))),t}function _parseCSV(e,t,r){const o=[];if(_forDelimiter(e,t,((t,a)=>{const n=e.substring(t,a);return n.length>0&&o.push(((e,t)=>{const o=[];return _forDelimiter(e,r,((r,a)=>{const n=e.substring(r,a);return o.push({raw:_parseQuotes(n,t,o.length)}),!0})),o})(n,o.length)),!0})),o.length){const e=o[0].length;o.forEach(((t,r)=>{if(t.length!==e)throw new Error(`Detected invalid CSV: Row ${r} does not have expected number of columns: ${e}`)}))}return o}function _parseQuotes(e,t,r){const o=e.startsWith('"'),a=e.endsWith('"');if(o&&!a||!o&&a)throw new Error(`Detected invalid CSV: Missing opening or closing quote for value at row:${t} column:${r}`);const n=o?e.substring('"'.length,e.length-'"'.length):e;let i=-1;return _forDelimiter(n,'"',((e,o)=>{if(o===n.length)return!0;if(i<0){if(o!==n.length)return i=o,!0}else if(o===i+'"'.length)return i=-1,!0;throw new Error(`Detected invalid CSV: Non-escaped quote for value at row:${t} column:${r}`)})),n.replace(new RegExp('""',"g"),'"')}function _forDelimiter(e,t,r){let o,a=!1,n=0,i=0;for(;o=e.indexOf(t,n),!(o<0);){for(let t=n;t<o;)e.substring(t).startsWith('"')?(a=!a,t+='"'.length):t++;const s=o+t.length;if(!a){const e=r(i,o);if(i=s,!e)break}n=s}r(i,e.length)}const geometryTypeHeaders={[GeometryFormat.XYZ]:[["x","y","z"]],[GeometryFormat.XY]:[["x","y"]],[GeometryFormat.LAT_LON]:[["lat","lon"],["lat","long"],["latitude","longitude"]],[GeometryFormat.ARCGIS_JSON]:[["geometry"]],[GeometryFormat.GEO_JSON]:[["geometry"]],[GeometryFormat.WKT]:[["geometry"]]};function _parseArcGisJson(e,t){const r=JSON.parse(e),o=toEsriApiGeometry(r);return r.spatialReference||(o.spatialReference=t),o}function _parseGeoJson(e,t){const r=geoJSONToEsri(JSON.parse(e));return r.spatialReference=t,r}function _parseWkt(e,t){const r=wktToEsri(e);return r.spatialReference=t,r}function _findGeometryFormatIndex(e,t){const r=geometryTypeHeaders[t];for(const t of r){const r=e.findIndex(((r,o)=>!(o+t.length>e.length)&&t.every(((t,r)=>e[o+r].raw.toString().toLowerCase()===t))));if(-1!==r)return r}}function _detectGeometry(e,t){return e.map(((e,r)=>{const o=null==e?void 0:e.raw;if("string"==typeof o&&""!==o)try{return t(o,void 0),r}catch{return}})).find((e=>void 0!==e))}function _parseGeometries(e,t){const r=t.includeHeaderRow?e.slice(1):e;if(t.geometryFormat===GeometryFormat.NONE)return{columnCount:0,columnIndex:0};const o=(e,o)=>{const a=o===GeometryFormat.XYZ,n=o===GeometryFormat.LAT_LON,i=a?3:2;return{columnCount:i,columnIndex:e,geometries:r.map((r=>{if(r.length>=e+i&&isNumeric(r[e+0].raw)&&isNumeric(r[e+1].raw)&&(!a||isNumeric(r[e+2].raw)))return new Point({x:parseNumber(n?r[e+1].raw:r[e+0].raw),y:parseNumber(n?r[e+0].raw:r[e+1].raw),z:a?parseNumber(r[e+2].raw):0,spatialReference:t.inSpatialReference})}))}},a=(e,o)=>({columnCount:1,columnIndex:e,geometries:r.map((t=>t[e])).map((e=>{if(""!==e.raw)return o(e.raw.toString(),t.inSpatialReference)}))});if(t.geometryFormat){const r=_findGeometryFormatIndex(e[0],t.geometryFormat);if(t.includeHeaderRow&&void 0===r)throw new Error(`Error parsing CSV: Expected geometry columns ${geometryTypeHeaders[t.geometryFormat][0].join(",")} are missing for GeometryType.${t.geometryFormat}`);return((e,t)=>{switch(t){case GeometryFormat.NONE:return{columnCount:0,columnIndex:0};case GeometryFormat.LAT_LON:case GeometryFormat.XYZ:case GeometryFormat.XY:return o(e,t);case GeometryFormat.ARCGIS_JSON:return a(e,_parseArcGisJson);case GeometryFormat.GEO_JSON:return a(e,_parseGeoJson);case GeometryFormat.WKT:return a(e,_parseWkt);default:return assertNever(t,new Error(`Unknown geometry format "${t}".`))}})(null!=r?r:0,t.geometryFormat)}if(t.includeHeaderRow){const t=_findGeometryFormatIndex(e[0],GeometryFormat.ARCGIS_JSON);if(void 0!==t)for(const e of[_parseArcGisJson,_parseGeoJson,_parseWkt])try{return a(t,e)}catch(e){}const r=[GeometryFormat.XYZ,GeometryFormat.XY,GeometryFormat.LAT_LON];for(const t of r){const r=_findGeometryFormatIndex(e[0],t);if(void 0!==r)return o(r,t)}}for(const e of[_parseArcGisJson,_parseGeoJson,_parseWkt])try{const t=_detectGeometry(r[0],e);return a(t,e)}catch(e){}return{columnCount:0,columnIndex:0}}function _parseSchema(e,t,r){var o;const a={fields:[]};let n=0;for(let o=t.columnCount;o<e[0].length;o++){if(i=o,0!==t.columnCount&&i>=t.columnIndex&&i<t.columnIndex+t.columnCount)continue;const s=_parseFieldType(e,o,r);let m=e[0][o].raw.toString(),l=m.replace(FIELD_NAME_REGEX,"_");if(r.includeHeaderRow||(l="field"+ ++n,m=translate("gcx.api.data.convert.import-field-alias",n)),!l)throw new Error("Error parsing CSV or XLSX: Header cannot contain blank values");a.fields.push({alias:m,name:l,type:s})}var i;if(a.spatialReference=r.outSpatialReference,null===(o=t.geometries)||void 0===o?void 0:o.length){const e=t.geometries.filter((e=>void 0!==e)).map((e=>e.type)),r=e[0];a.geometryType=e.every((e=>e===r))?r:void 0}if(r.generatePrimaryKey&&!a.fields.find((e=>"esriFieldTypeOID"===e.type))){const e=a.fields.length+1,t=!!a.fields.find((e=>"id"===e.name.toLowerCase()));a.fields.push({name:t?`field${e}`:"id",alias:t?translate("gcx.api.data.convert.import-field-alias",e):"id",type:"esriFieldTypeOID"})}return a}function _parseFieldType(e,t,r){var o;let a=!1,n=!0,i=!0,s=!0;const m=new Set,l=r.includeHeaderRow?e[0]:[],u=r.includeHeaderRow?e.slice(1):e;for(const e of u){const o=e[t];""!==o.raw&&(m.add(o.raw),a=!0,n&&(n=isNumeric(o.raw)||Number.isNaN(o.raw)),i&&(i=o.raw instanceof Date||parseDate(r.dateFormat||DEFAULT_PARSING_FORMATS,o.raw)!==INVALID_DATE),s&&(s=parseDate(r.dateFormat||DEFAULT_EXCEL_DATE_FORMATS,o.formatted)!==INVALID_DATE))}const c=m.size===u.length;return r.primaryKeyField&&(null===(o=l[t])||void 0===o?void 0:o.raw)===r.primaryKeyField||r.detectOid&&a&&c&&n?(r.detectOid=!1,"esriFieldTypeOID"):a&&s?"esriFieldTypeDate":a&&n?"esriFieldTypeDouble":a&&i?"esriFieldTypeDate":"esriFieldTypeString"}async function _parseFeatures(e,t,r,o){const a=[],n=o.includeHeaderRow?e.slice(1):e,i=(e,r)=>0===t.columnCount||(r<t.columnIndex||r>=t.columnIndex+t.columnCount);return await Promise.all(n.map((async(e,n)=>{var s;const m=new Feature;for(let t=0;t<r.fields.length;t++){const a=r.fields[t],l=e.filter(i);if(o.outFields.includes("*")||o.outFields.includes(a.name)){let e=await _parseValue(null===(s=l[t])||void 0===s?void 0:s.raw,a,o);"esriFieldTypeOID"===a.type&&null===e&&(e=n),m.attributes.set(a.name,e)}}t.geometries&&(m.geometry=await _projectGeometry(t.geometries[n],o.outSpatialReference)),a.push(m)}))),a}async function _parseValue(e,t,r){if("esriFieldTypeDouble"===t.type||"esriFieldTypeOID"===t.type)return"number"==typeof e?e:e?parseNumber(e):null;if("esriFieldTypeDate"===t.type){if(e instanceof Date)return e.getTime();if("number"==typeof e){const t=(await import("xlsx")).SSF.parse_date_code(e);return t?new Date(t.y,t.m-1,t.d,t.H,t.M,t.S).getTime():void 0}return""===e?null:parseDate(e).getTime()}const o=e.toString();if(r.escapeFormulaChars&&o.startsWith("\t"))for(const e of FORMULA_TRIGGER_CHARS)if(o.length>1&&o.charAt(1)===e)return o.substring(1);return o}function _convertToExcelDateFormatString(e){switch(e){case DateFormat.DATE_SHORT:return"dd/MM/yyyy";case DateFormat.DATE_LONG:return"MMMM d, yyyy";case DateFormat.TIME_SHORT:return"h:mm AM/PM";case DateFormat.TIME_LONG:return"h:mm:ss AM/PM";case DateFormat.DATE_TIME_SHORT:case DateFormat.DEFAULT:return"MMM d yyyy h:mm AM/PM";case DateFormat.DATE_TIME_LONG:return"MMMM d yyyy h:mm AM/PM";case DateFormat.FULL:return"dddd, MMMM d yyyy h:mm AM/PM";case DateFormat.ISO_8601:case DateFormat.ROUND_TRIP:return'yyyy-MM-dd"T"HH:mm:ss';default:{const t=e.replace(/tt/g,"AM/PM");return t.includes("z")&&_getConvertLogger().warn("Warning: Excel will not recognize timezone format 'z', 'zz', or 'zzz'"),t.includes("h")&&!t.includes("AM/PM")&&_getConvertLogger().warn("Warning: Excel will interpret 'h' as 'H' if the format does not have an AM/PM designator"),t}}}function _convertToExcelNumberFormatString(e){switch(e){case NumberFormat.ACCOUNTING:return'_("$"* #,##0.00_);_("$"* (#,##0.00);_("$"* "-"??_);_(@_)';case NumberFormat.CURRENCY:return'"$"#,##0.00';case NumberFormat.FIXED_POINT:case NumberFormat.DEFAULT:return"0.0000";case NumberFormat.NUMBER:return"#,##0.0000";case NumberFormat.PERCENT:return"0%";case NumberFormat.ROUND_TRIP:return"0.00000";default:return e}}function _toXLSXValue(e,t){if(null==e)return"";if(!t.useFormattedValues){if("number"==typeof e)return e;if(e instanceof Date)return"timestamp"===t.dateFormat?e.getTime():e}let r=e.toString();return t.escapeFormulaChars&&(r=escapeFormulaChars(r)),r}async function _parseXLSX(e,t){const r=await import("xlsx"),o=new Promise(((o,a)=>{const n=new FileReader;n.onload=()=>{const e=new Uint8Array(n.result);let a="";for(const t of e)a+=String.fromCharCode(t);const i=r.read(a,{type:"binary",cellDates:!0}),s=t.sheetName||i.SheetNames[0],m=i.Sheets[s];o(m)},n.onerror=()=>{a(n.error)},n.readAsArrayBuffer(e)})),a=await o,n=r.utils.decode_range(a["!ref"]),i=[];for(let e=n.s.r;e<=n.e.r;e++){const t=[];for(let o=n.s.c;o<=n.e.c;o++){const n=a[`${r.utils.encode_cell({r:e,c:o})}`];t.push(n?{raw:n.v,formatted:"s"===n.t?void 0:n.w}:{raw:""})}i.push(t)}return i}async function _getDBaseSpatialReferenceWKT(e){let t;for(const r of e)if(t){if(r.spatialReference.wkid!==t)throw new Error("Cannot create shapefile that contains geometries with different spatial references.")}else t=r.spatialReference.wkid;return t||(t=SpatialReference.WGS84.wkid),esriWkidToWkt(t)}function _getDBaseColumnTypes(e,t,r,o){const a={};for(const n of t){if(e.some((e=>_hasCodedDomain(e,n)))){a[n]=DBaseTypes.STRING;continue}const t=r?r.fields.find((e=>e.name===n)):void 0;if(t){switch(t.type){case"oid":case"double":case"integer":case"single":case"small-integer":a[n]=DBaseTypes.NUMBER;break;case"date":a[n]=o?DBaseTypes.NUMBER:DBaseTypes.DATE;break;default:a[n]=DBaseTypes.STRING}continue}const i=(e,t)=>{var r;return null!==(r=e.attributes.get(t))&&void 0!==r?r:e.presentableAttributes.get(t)};e.every((e=>i(e,n)instanceof Date||void 0===i(e,n)))&&e.some((e=>i(e,n)instanceof Date))?a[n]=o?DBaseTypes.NUMBER:DBaseTypes.DATE:e.every((e=>"number"==typeof i(e,n)||void 0===i(e,n)))&&e.some((e=>"number"==typeof i(e,n)))?a[n]=DBaseTypes.NUMBER:e.every((e=>"boolean"==typeof i(e,n)||void 0===i(e,n)))&&e.some((e=>"boolean"==typeof i(e,n)))?a[n]=DBaseTypes.BOOLEAN:a[n]=DBaseTypes.STRING}return a}function _getDBaseGeometries(e){return e.map((e=>{if(isPoint(e)){const{x:t,y:r,z:o,m:a}=e,n=[t,r];return e.hasZ&&n.push(o),e.hasM&&n.push(a),_padZValues(n,e)}if(isMultipoint(e))return _padZValuesArray(e.points,e);if(isPolyline(e))return _padZValues2DArray(e.paths,e);if(isPolygon(e))return _padZValues2DArray(e.rings,e);if(isExtent(e)){const t=[e.xmin,e.ymax];return[[t,[e.xmax,e.ymax],[e.xmax,e.ymin],[e.xmin,e.ymin],t]]}throw new Error("Unsupported geometry type.")}))}function _padZValues(e,t){return 3===e.length&&!t.hasZ&&t.hasM?[e[0],e[1],void 0,e[2]]:e}function _padZValuesArray(e,t){return e.map((e=>_padZValues(e,t)))}function _padZValues2DArray(e,t){return e.map((e=>_padZValuesArray(e,t)))}function _getDbaseValues(e,t,r,o){const a=[];for(const n of e){const e={};for(const a of t){let t=_getAttributeValue(n,a,o);if(null==t&&(t=""),o.useFormattedValues)t=t.toString();else{t=getDbaseValue(t,r[a],o)}e[a]=t}a.push(e)}return a}function getDbaseValue(e,t,r){var o,a;switch(t){case DBaseTypes.NUMBER:return e instanceof Date?e.getTime():parseNumber(e);case DBaseTypes.STRING:return e instanceof Date?formatDate({format:null!==(o=r.dateFormat)&&void 0!==o?o:DateFormat.ROUND_TRIP,timeZone:"UTC"},e):"number"==typeof e?formatNumber(null!==(a=r.numberFormat)&&void 0!==a?a:NumberFormat.DEFAULT,e):e.toString();case DBaseTypes.BOOLEAN:return!!e;case DBaseTypes.DATE:return parseDate(e);default:return e.toString()}}function _parseShapefileNames(e){if(!e.length)return[];let t=e[0];const r=t.match(shapefileNameRegex);return r?(t=r[1],e.filter((e=>{const r=e.match(shapefileNameRegex);return r&&r[1]===t}))):[t]}function _parseDBaseData(e){const t=e.map((e=>Object.keys(e))).reduce(((e,t)=>e.concat(t.filter((t=>!e.includes(t))))),[]);return[t.map((e=>({raw:e}))),...e.map((e=>t.map((t=>({raw:e[t]})))))]}function _parseShpPointGeometry(e){checkArg("geometry.coordinates",e.type).matches("Point"),checkArg("geometry.coordinates",e.coordinates).satisfies((e=>"number"==typeof e||Array.isArray(e)));const[t,r,o]=e.coordinates,a=new Point({x:t,y:r,spatialReference:SpatialReference.WGS84});if(Array.isArray(o)){const[e,t]=o;!e&&!t||e?a.z=e:a.m=t}return a}async function _parseShpGeometry(e,t){const r=isPoint(e)?_parseShpPointGeometry(e):geoJSONToEsri(e);if(t){let e;const o=await esriWktToWkid(t);if(o&&(e=new SpatialReference({wkid:parseNumber(o)})),!e)throw new Error(`Could go find wkid that matches wkt: ${t}`);r.spatialReference=e}return r}
|
|
1
|
+
import Point from"@arcgis/core/geometry/Point";import SpatialReference from"@arcgis/core/geometry/SpatialReference";import{translate}from"../locale/language.js";import{toEsriApiGeometry,toPortalGeometry}from"../portal/Geometry.js";import{checkArg,assertNever}from"../utilities/checkArg.js";import{parse as parseDate,format as formatDate,DEFAULT_PARSING_FORMATS,DateFormat,INVALID_DATE}from"../utilities/date.js";import{esriToWKT,esriToGeoJSON,geoJSONToEsri,wktToEsri,esriWkidToWkt,esriWktToWkid,project,isPoint,isMultipoint,isPolyline,isPolygon,isExtent}from"../utilities/geometry.js";import{getLogger}from"../utilities/log.js";import{parse as parseNumber,format as formatNumber,NumberFormat,isNumeric}from"../utilities/number.js";import{Feature}from"./Feature.js";import{FeatureSet}from"./FeatureSet.js";const FORMULA_TRIGGER_CHARS=["=","-","+","@"],QUOTE='"',FIELD_NAME_REGEX=/[^a-zA-Z\d_]/g,DEFAULT_WINDOWS_ROW_DELIMITER="\r\n",DEFAULT_UNIX_ROW_DELIMITER="\n",DEFAULT_SHEET_NAME="sheet1",DEFAULT_EXCEL_DATE_FORMATS=[...DEFAULT_PARSING_FORMATS.map(_convertToExcelDateFormatString),"M/d/yy"],shapefileNameRegex=/(\w+)_(point|multipoint|polyline|polygon)z?/;var DBaseTypes;function _getConvertLogger(){return getLogger("geocortex.api.data.convert")}!function(e){e.DATE="D",e.NUMBER="N",e.STRING="C",e.BOOLEAN="L"}(DBaseTypes||(DBaseTypes={}));export var GeometryFormat;!function(e){e.NONE="NONE",e.WKT="WKT",e.XY="XY",e.XYZ="XYZ",e.LAT_LON="LAT_LONG",e.GEO_JSON="GEO_JSON",e.ARCGIS_JSON="ARCGIS_JSON"}(GeometryFormat||(GeometryFormat={}));export async function toCsv(e,t){checkArg("featureSet",e).isNotMissing();const r=Array.from(e),o={...{useFormattedValues:!1,alwaysQuote:!1,escapeFormulaChars:!0,delimiter:",",dateFormat:DateFormat.ROUND_TRIP,geometryFormat:r.some((e=>void 0!==e.geometry&&null!==e.geometry))?GeometryFormat.WKT:GeometryFormat.NONE,includeByteOrderMark:!0,outSpatialReference:SpatialReference.WGS84,includeHeaderRow:!0,outFields:_getDefaultOutFields(e.source),rowDelimiter:navigator.platform.startsWith("Win")?"\r\n":"\n"},...t},{includeByteOrderMark:a,includeHeaderRow:n,delimiter:i,outFields:s,rowDelimiter:m}=o,l=[];a&&l.push("\ufeff");const u=_getGeometryColumns(r,o),c=_getAttributeColumns(r,s,e.schema,!0),f=_getAttributeColumns(r,s,e.schema,!1);if(n){const e=[];for(const t of u)e.push(_quotify(t,o));for(const t of c)e.push(_quotify(t,o));for(const t of f)e.push(_quotify(t,o));const t=e.join(i)+m;l.push(t)}await Promise.all(r.map((async e=>{const t=[],r=(t,r)=>_quotify(_stringify(_getAttributeValue(e,t,r),r),r);t.push(...await _getCSVGeometry(e.geometry,o)),t.push(...c.map((e=>r(e,o)))),t.push(...f.map((e=>r(e,o))));const a=`${t.join(i)}${m}`;l.push(a)})));return new Blob(l,{type:"text/plain",endings:"\n"===m||"\r\n"===m?"transparent":"native"})}export async function csvToFeatureSet(e,t){let r;if(checkArg("csvData",e).isNotMissing(),e instanceof Blob){const t=new Promise(((t,r)=>{const o=new FileReader;o.onload=()=>{t(o.result)},o.onerror=()=>{r(o.error)},o.readAsText(e)}));r=await t}else r=e;const o={...{delimiter:",",escapeFormulaChars:!0,includeHeaderRow:!0,outFields:["*"],inSpatialReference:SpatialReference.WGS84,generatePrimaryKey:!0,primaryKeyField:"OBJECTID"},...t,detectOid:!(null==t?void 0:t.primaryKeyField)},a=_parseCSV(r,o.rowDelimiter||_parseRowDelimiter(r),o.delimiter),n=_parseGeometries(a,o),i=_parseSchema(a,n,o),s=await _parseFeatures(a,n,i,o);return new FeatureSet({features:s,schema:i})}export async function toXLSX(e,t){var r;checkArg("featureSet",e).isNotMissing();const o=Array.from(e),a={...{useFormattedValues:!1,includeHeaderRow:!0,escapeFormulaChars:!0,geometryFormat:o.some((e=>void 0!==e.geometry&&null!==e.geometry))?GeometryFormat.WKT:GeometryFormat.NONE,outFields:_getDefaultOutFields(e.source),outSpatialReference:SpatialReference.WGS84,dateFormat:DateFormat.DEFAULT,numberFormat:NumberFormat.DEFAULT,sheetName:"sheet1"},...t},{outFields:n,includeHeaderRow:i,numberFormat:s}=a,m=[],l=_getGeometryColumns(o,a),u=_getAttributeColumns(o,n,e.schema,!0),c=_getAttributeColumns(o,n,e.schema,!1);if(i){const t=l.concat(u).concat(_getXlsxColumnName(c,e.source));m.push(t)}await Promise.all(o.map((async e=>{const t=[];t.push(...await _getGeometry(e.geometry,a));for(const r of u){const o=_toXLSXValue(e.attributes.get(r),a);t.push(o)}for(const r of c){const o=_toXLSXValue(_getAttributeValue(e,r,a),a);t.push(o)}m.push(t)})));const f=await import("xlsx"),p={SheetNames:[],Sheets:{}},d=f.utils.aoa_to_sheet(m,{cellDates:!0});for(const e of Object.keys(d).filter((e=>!e.startsWith("!")))){const t=d[e];"d"===t.t?t.z=_convertToExcelDateFormatString(null!==(r=a.dateFormat)&&void 0!==r?r:DateFormat.ROUND_TRIP):"n"===t.t&&(t.z=_convertToExcelNumberFormatString(s))}p.SheetNames.push(a.sheetName),p.Sheets[a.sheetName]=d;const y=f.write(p,{type:"binary",bookType:"xlsx",compression:!0,bookSST:!0,cellDates:!0}),g=new Uint8Array(y.length);for(let e=0;e<y.length;e++)g[e]=y.charCodeAt(e);return new Blob([g.buffer],{type:"text/plain"})}export async function xlsxToFeatureSet(e,t){checkArg("xlsxData",e).isNotMissing();const r={...{includeHeaderRow:!0,escapeFormulaChars:!0,outFields:["*"],inSpatialReference:SpatialReference.WGS84,generatePrimaryKey:!0,primaryKeyField:"OBJECTID"},...t,detectOid:!(null==t?void 0:t.primaryKeyField)},o=await _parseXLSX(e,r),a=_parseGeometries(o,r),n=_parseSchema(o,a,r),i=await _parseFeatures(o,a,n,r);return new FeatureSet({features:i,schema:n})}export async function toShapefile(e,t){checkArg("featureSet",e).isNotMissing();const[{default:r},o]=await Promise.all([import("jszip"),import("../forked-libs/shp-write/index.js")]),a=Array.from(e),n={...{useFormattedValues:!1,outFields:_getDefaultOutFields(e.source),fileName:e.title||"export"},...t},{outFields:i,outSpatialReference:s,fileName:m}=n,l=e=>e.geometry.hasZ||e.geometry.hasM,u=new Map,c=a.filter((e=>isPoint(e.geometry)));u.set("POINTZ",c.filter(l)),u.set("POINT",c.filter((e=>!l(e))));const f=a.filter((e=>isMultipoint(e.geometry)));u.set("MULTIPOINTZ",f.filter(l)),u.set("MULTIPOINT",f.filter((e=>!l(e))));const p=a.filter((e=>isPolyline(e.geometry)));u.set("POLYLINEZ",p.filter(l)),u.set("POLYLINE",p.filter((e=>!l(e))));const d=a.filter((e=>isPolygon(e.geometry)||isExtent(e.geometry)));u.set("POLYGONZ",d.filter(l)),u.set("POLYGON",d.filter((e=>!l(e))));const y=_getAttributeColumns(a,i,e.schema,!0);let g=_getAttributeColumns(a,i,e.schema,!1);g=y.concat(g);const h=new r,F=Array.from(u.keys()).filter((e=>u.get(e).length>0));await Promise.all(F.map((async t=>{const r=u.get(t),a=await Promise.all(r.map((e=>_projectGeometry(e.geometry,s)))),i=await _getDBaseSpatialReferenceWKT(a),l=n.useFormattedValues?Object.assign({},...g.map((e=>({[e]:DBaseTypes.STRING})))):_getDBaseColumnTypes(r,g,e.schema,"timestamp"===n.dateFormat),c=_getDBaseGeometries(a),f=_getDbaseValues(r,g,l,n);o.write(f,t,c,((e,r)=>{const o=F.length>1?`${m}_${t.toLowerCase()}`:m;h.file(`${o}.shp`,r.shp.buffer,{binary:!0}),h.file(`${o}.shx`,r.shx.buffer,{binary:!0}),h.file(`${o}.dbf`,r.dbf.buffer,{binary:!0}),h.file(`${o}.prj`,i)}))})));const _=await h.generateAsync({type:"uint8array"});return new Blob([_.buffer],{type:"text/plain"})}export async function shapefileToFeatureSet(e,t){checkArg("shapefileData",e).isNotMissing();const r={outFields:["*"],includeHeaderRow:!0,generatePrimaryKey:!0,primaryKeyField:"OBJECTID",...t,detectOid:!(null==t?void 0:t.primaryKeyField)},o=new Promise(((t,r)=>{const o=new FileReader;o.onload=()=>{t(o.result)},o.onerror=()=>{r(o.error)},o.readAsArrayBuffer(e)})),[{default:a},n]=await Promise.all([import("jszip"),import("shpjs")]),i=await o,s=await a.loadAsync(new Uint8Array(i)),m=s.filter((()=>!0)).map((e=>e.name));let l,u=m.filter((e=>e.endsWith(".shp"))).map((e=>e.substring(0,e.length-4)));if(u=_parseShapefileNames(u),m.some((e=>e.endsWith(".prj")))&&!u.every((e=>m.includes(`${e}.prj`))))throw new Error("Shapefile zip must contain the same prj file for each separate shapefile");await Promise.all(m.filter((e=>e.endsWith(".prj"))).map((async e=>{const t=await s.file(e).async("string");if(l){if(t!==l)throw new Error("Shapefile zip must contain the same prj file for each separate shapefile")}else l=t})));const c={geometries:[],columnCount:0,columnIndex:0};let f=[];for(const e of u){if(!m.includes(`${e}.shx`)||!m.includes(`${e}.dbf`))throw new Error("Shapefile must contain shp, shx, and dbf files.");const t=await s.file(`${e}.shp`).async("uint8array"),r=n.parseShp(t),o=await s.file(`${e}.dbf`).async("uint8array"),a=n.parseDbf(o);if(a.length!==r.length)throw new Error("Shapefile must contain shp, shx, and dbf files.");const i=await Promise.all(r.map((e=>_parseShpGeometry(e,l))));c.geometries=c.geometries.concat(i),f=f.concat(a)}const p=_parseDBaseData(f),d=_parseSchema(p,c,r),y=await _parseFeatures(p,c,d,r);return new FeatureSet({features:y,schema:d})}function _getGeometryColumns(e,t){return t.geometryFormat===GeometryFormat.XYZ?["x","y","z"]:t.geometryFormat===GeometryFormat.XY?["x","y"]:t.geometryFormat===GeometryFormat.LAT_LON?["latitude","longitude"]:t.geometryFormat===GeometryFormat.NONE?[]:["geometry"]}function _getAttributeColumns(e,t,r,o){const a=r.fields.filter((e=>"oid"===e.type)).map((e=>e.name)).toArray();if(o)return a;if(t&&!t.includes("*"))return t.filter((e=>!a.includes(e)));{const t=r.fields.filter((e=>"oid"!==e.type)).map((e=>e.name)).toArray();let o=[];for(const r of e)for(const e of r.attributes.keys())t.includes(e)||a.includes(e)||o.includes(e)||o.push(e);return o=o.sort(),t.concat(o)}}function _getXlsxColumnName(e,t){var r;const o=null===(r=null==t?void 0:t.schema)||void 0===r?void 0:r.fieldExtensions.initializedItems.map((e=>e.field));return e.map((e=>{var t,r;return null!==(r=null===(t=null==o?void 0:o.find((t=>t.name===e)))||void 0===t?void 0:t.alias)&&void 0!==r?r:e}))}function _getDefaultOutFields(e){var t,r,o,a,n,i,s,m;if(!e)return["*"];const l=null===(t=e.featureSettings.popupTemplate)||void 0===t?void 0:t.content,u=Array.isArray(l)?null===(a=null===(o=null===(r=l.find((e=>"fields"===e.type)))||void 0===r?void 0:r.fieldInfos)||void 0===o?void 0:o.filter((e=>e.visible)))||void 0===a?void 0:a.map((e=>e.fieldName)):void 0;return null!==(m=null!=u?u:null===(s=null===(i=null===(n=e.featureSettings.popupTemplate)||void 0===n?void 0:n.fieldInfos)||void 0===i?void 0:i.filter((e=>e.visible)))||void 0===s?void 0:s.map((e=>e.fieldName)))&&void 0!==m?m:["*"]}async function _getCSVGeometry(e,t){let r=await _getGeometry(e,t);return t.geometryFormat!==GeometryFormat.XYZ&&t.geometryFormat!==GeometryFormat.XY&&t.geometryFormat!==GeometryFormat.LAT_LON||(r=r.map((e=>void 0===e?"":_stringify(e,t)))),r.map((e=>""===e?"":_quotify(e,t)))}async function _getGeometry(e,t){const r=await _projectGeometry(e,t.outSpatialReference);if(t.geometryFormat===GeometryFormat.XYZ){if(!r)return["","",""];if(!isPoint(r))throw new Error("Cannot use geometry format XYZ with non-point geometry");return[r.x,r.y,r.z]}if(t.geometryFormat===GeometryFormat.XY){if(!r)return["",""];if(!isPoint(r))throw new Error("Cannot use geometry format XY with non-point geometry");return[r.x,r.y]}if(t.geometryFormat===GeometryFormat.LAT_LON){if(!r)return["",""];if(!isPoint(r))throw new Error("Cannot use geometry format LAT_LONG with non-point geometry");return[r.y,r.x]}return t.geometryFormat===GeometryFormat.ARCGIS_JSON?r?[JSON.stringify(toPortalGeometry(r))]:[""]:t.geometryFormat===GeometryFormat.WKT?r?[esriToWKT(r)]:[""]:t.geometryFormat===GeometryFormat.GEO_JSON?r?[JSON.stringify(esriToGeoJSON(r))]:[""]:[]}async function _projectGeometry(e,t){return(null==e?void 0:e.spatialReference)&&!e.spatialReference.equals(t)&&t?(await project([e],t))[0]:e}function _quotify(e,t){const r=[t.delimiter,'"',"\r","\n",t.rowDelimiter];if(t.alwaysQuote||r.some((t=>e.includes(t)))){return`"${e.replace(new RegExp('"',"g"),'""')}"`}return e}function _stringify(e,t){if(null==e)return"";if(!t.useFormattedValues){if("number"==typeof e){const r=t.numberFormat||NumberFormat.ROUND_TRIP;return formatNumber(r,e)}if(e instanceof Date)return"timestamp"===t.dateFormat?e.getTime().toString():formatDate({format:t.dateFormat,timeZone:"UTC"},e)}let r=e.toString();return t.escapeFormulaChars&&(r=escapeFormulaChars(r)),r}function _getAttributeValue(e,t,r){var o,a,n;if(r.useFormattedValues||_hasCodedDomain(e,t))return null!==(o=e.presentableAttributes.get(t))&&void 0!==o?o:e.attributes.get(t);if("date"===(null===(a=e.schema.findFieldByName(t))||void 0===a?void 0:a.type)){const r=parseDate(e.attributes.get(t));if(!isNaN(r.getTime()))return r}return null!==(n=e.attributes.get(t))&&void 0!==n?n:e.presentableAttributes.get(t)}function _hasCodedDomain(e,t){var r,o,a,n,i;return t===e.schema.typeIdField||("coded-value"===(null===(a=null===(o=null===(r=e.type)||void 0===r?void 0:r.domains)||void 0===o?void 0:o[t])||void 0===a?void 0:a.type)||"coded-value"===(null===(i=null===(n=e.schema.findFieldByName(t))||void 0===n?void 0:n.domain)||void 0===i?void 0:i.type))}function escapeFormulaChars(e){for(const t of FORMULA_TRIGGER_CHARS)if(e.startsWith(t))return`\t${e}`;return e}function _parseRowDelimiter(e){let t="\n";return _forDelimiter(e,"\r\n",((r,o)=>(0===r&&o===e.length||(t="\r\n"),!1))),t}function _parseCSV(e,t,r){const o=[];if(_forDelimiter(e,t,((t,a)=>{const n=e.substring(t,a);return n.length>0&&o.push(((e,t)=>{const o=[];return _forDelimiter(e,r,((r,a)=>{const n=e.substring(r,a);return o.push({raw:_parseQuotes(n,t,o.length)}),!0})),o})(n,o.length)),!0})),o.length){const e=o[0].length;o.forEach(((t,r)=>{if(t.length!==e)throw new Error(`Detected invalid CSV: Row ${r} does not have expected number of columns: ${e}`)}))}return o}function _parseQuotes(e,t,r){const o=e.startsWith('"'),a=e.endsWith('"');if(o&&!a||!o&&a)throw new Error(`Detected invalid CSV: Missing opening or closing quote for value at row:${t} column:${r}`);const n=o?e.substring('"'.length,e.length-'"'.length):e;let i=-1;return _forDelimiter(n,'"',((e,o)=>{if(o===n.length)return!0;if(i<0){if(o!==n.length)return i=o,!0}else if(o===i+'"'.length)return i=-1,!0;throw new Error(`Detected invalid CSV: Non-escaped quote for value at row:${t} column:${r}`)})),n.replace(new RegExp('""',"g"),'"')}function _forDelimiter(e,t,r){let o,a=!1,n=0,i=0;for(;o=e.indexOf(t,n),!(o<0);){for(let t=n;t<o;)e.substring(t).startsWith('"')?(a=!a,t+='"'.length):t++;const s=o+t.length;if(!a){const e=r(i,o);if(i=s,!e)break}n=s}r(i,e.length)}const geometryTypeHeaders={[GeometryFormat.XYZ]:[["x","y","z"]],[GeometryFormat.XY]:[["x","y"]],[GeometryFormat.LAT_LON]:[["lat","lon"],["lat","long"],["latitude","longitude"]],[GeometryFormat.ARCGIS_JSON]:[["geometry"]],[GeometryFormat.GEO_JSON]:[["geometry"]],[GeometryFormat.WKT]:[["geometry"]]};function _parseArcGisJson(e,t){const r=JSON.parse(e),o=toEsriApiGeometry(r);return r.spatialReference||(o.spatialReference=t),o}function _parseGeoJson(e,t){const r=geoJSONToEsri(JSON.parse(e));return r.spatialReference=t,r}function _parseWkt(e,t){const r=wktToEsri(e);return r.spatialReference=t,r}function _findGeometryFormatIndex(e,t){const r=geometryTypeHeaders[t];for(const t of r){const r=e.findIndex(((r,o)=>!(o+t.length>e.length)&&t.every(((t,r)=>e[o+r].raw.toString().toLowerCase()===t))));if(-1!==r)return r}}function _detectGeometry(e,t){return e.map(((e,r)=>{const o=null==e?void 0:e.raw;if("string"==typeof o&&""!==o)try{return t(o,void 0),r}catch{return}})).find((e=>void 0!==e))}function _parseGeometries(e,t){const r=t.includeHeaderRow?e.slice(1):e;if(t.geometryFormat===GeometryFormat.NONE)return{columnCount:0,columnIndex:0};const o=(e,o)=>{const a=o===GeometryFormat.XYZ,n=o===GeometryFormat.LAT_LON,i=a?3:2;return{columnCount:i,columnIndex:e,geometries:r.map((r=>{if(r.length>=e+i&&isNumeric(r[e+0].raw)&&isNumeric(r[e+1].raw)&&(!a||isNumeric(r[e+2].raw)))return new Point({x:parseNumber(n?r[e+1].raw:r[e+0].raw),y:parseNumber(n?r[e+0].raw:r[e+1].raw),z:a?parseNumber(r[e+2].raw):0,spatialReference:t.inSpatialReference})}))}},a=(e,o)=>({columnCount:1,columnIndex:e,geometries:r.map((t=>t[e])).map((e=>{if(""!==e.raw)return o(e.raw.toString(),t.inSpatialReference)}))});if(t.geometryFormat){const r=_findGeometryFormatIndex(e[0],t.geometryFormat);if(t.includeHeaderRow&&void 0===r)throw new Error(`Error parsing CSV: Expected geometry columns ${geometryTypeHeaders[t.geometryFormat][0].join(",")} are missing for GeometryType.${t.geometryFormat}`);return((e,t)=>{switch(t){case GeometryFormat.NONE:return{columnCount:0,columnIndex:0};case GeometryFormat.LAT_LON:case GeometryFormat.XYZ:case GeometryFormat.XY:return o(e,t);case GeometryFormat.ARCGIS_JSON:return a(e,_parseArcGisJson);case GeometryFormat.GEO_JSON:return a(e,_parseGeoJson);case GeometryFormat.WKT:return a(e,_parseWkt);default:return assertNever(t,new Error(`Unknown geometry format "${t}".`))}})(null!=r?r:0,t.geometryFormat)}if(t.includeHeaderRow){const t=_findGeometryFormatIndex(e[0],GeometryFormat.ARCGIS_JSON);if(void 0!==t)for(const e of[_parseArcGisJson,_parseGeoJson,_parseWkt])try{return a(t,e)}catch(e){}const r=[GeometryFormat.XYZ,GeometryFormat.XY,GeometryFormat.LAT_LON];for(const t of r){const r=_findGeometryFormatIndex(e[0],t);if(void 0!==r)return o(r,t)}}for(const e of[_parseArcGisJson,_parseGeoJson,_parseWkt])try{const t=_detectGeometry(r[0],e);return a(t,e)}catch(e){}return{columnCount:0,columnIndex:0}}function _parseSchema(e,t,r){var o;const a={fields:[]};let n=0;for(let o=t.columnCount;o<e[0].length;o++){if(i=o,0!==t.columnCount&&i>=t.columnIndex&&i<t.columnIndex+t.columnCount)continue;const s=_parseFieldType(e,o,r);let m=e[0][o].raw.toString(),l=m.replace(FIELD_NAME_REGEX,"_");if(r.includeHeaderRow||(l="field"+ ++n,m=translate("gcx.api.data.convert.import-field-alias",n)),!l)throw new Error("Error parsing CSV or XLSX: Header cannot contain blank values");a.fields.push({alias:m,name:l,type:s})}var i;if(a.spatialReference=r.outSpatialReference,null===(o=t.geometries)||void 0===o?void 0:o.length){const e=t.geometries.filter((e=>void 0!==e)).map((e=>e.type)),r=e[0];a.geometryType=e.every((e=>e===r))?r:void 0}if(r.generatePrimaryKey&&!a.fields.find((e=>"esriFieldTypeOID"===e.type))){const e=a.fields.length+1,t=!!a.fields.find((e=>"id"===e.name.toLowerCase()));a.fields.push({name:t?`field${e}`:"id",alias:t?translate("gcx.api.data.convert.import-field-alias",e):"id",type:"esriFieldTypeOID"})}return a}function _parseFieldType(e,t,r){var o;let a=!1,n=!0,i=!0,s=!0;const m=new Set,l=r.includeHeaderRow?e[0]:[],u=r.includeHeaderRow?e.slice(1):e;for(const e of u){const o=e[t];""!==o.raw&&(m.add(o.raw),a=!0,n&&(n=isNumeric(o.raw)||Number.isNaN(o.raw)),i&&(i=o.raw instanceof Date||parseDate(r.dateFormat||DEFAULT_PARSING_FORMATS,o.raw)!==INVALID_DATE),s&&(s=parseDate(r.dateFormat||DEFAULT_EXCEL_DATE_FORMATS,o.formatted)!==INVALID_DATE))}const c=m.size===u.length;return r.primaryKeyField&&(null===(o=l[t])||void 0===o?void 0:o.raw)===r.primaryKeyField||r.detectOid&&a&&c&&n?(r.detectOid=!1,"esriFieldTypeOID"):a&&s?"esriFieldTypeDate":a&&n?"esriFieldTypeDouble":a&&i?"esriFieldTypeDate":"esriFieldTypeString"}async function _parseFeatures(e,t,r,o){const a=[],n=o.includeHeaderRow?e.slice(1):e,i=(e,r)=>0===t.columnCount||(r<t.columnIndex||r>=t.columnIndex+t.columnCount);return await Promise.all(n.map((async(e,n)=>{var s;const m=new Feature;for(let t=0;t<r.fields.length;t++){const a=r.fields[t],l=e.filter(i);if(o.outFields.includes("*")||o.outFields.includes(a.name)){let e=await _parseValue(null===(s=l[t])||void 0===s?void 0:s.raw,a,o);"esriFieldTypeOID"===a.type&&null===e&&(e=n),m.attributes.set(a.name,e)}}t.geometries&&(m.geometry=await _projectGeometry(t.geometries[n],o.outSpatialReference)),a.push(m)}))),a}async function _parseValue(e,t,r){if("esriFieldTypeDouble"===t.type||"esriFieldTypeOID"===t.type)return"number"==typeof e?e:e?parseNumber(e):null;if("esriFieldTypeDate"===t.type){if(e instanceof Date)return e.getTime();if("number"==typeof e){const t=(await import("xlsx")).SSF.parse_date_code(e);return t?new Date(t.y,t.m-1,t.d,t.H,t.M,t.S).getTime():void 0}return""===e?null:parseDate(e).getTime()}const o=e.toString();if(r.escapeFormulaChars&&o.startsWith("\t"))for(const e of FORMULA_TRIGGER_CHARS)if(o.length>1&&o.charAt(1)===e)return o.substring(1);return o}function _convertToExcelDateFormatString(e){switch(e){case DateFormat.DATE_SHORT:return"dd/MM/yyyy";case DateFormat.DATE_LONG:return"MMMM d, yyyy";case DateFormat.TIME_SHORT:return"h:mm AM/PM";case DateFormat.TIME_LONG:return"h:mm:ss AM/PM";case DateFormat.DATE_TIME_SHORT:case DateFormat.DEFAULT:return"MMM d yyyy h:mm AM/PM";case DateFormat.DATE_TIME_LONG:return"MMMM d yyyy h:mm AM/PM";case DateFormat.FULL:return"dddd, MMMM d yyyy h:mm AM/PM";case DateFormat.ISO_8601:case DateFormat.ROUND_TRIP:return'yyyy-MM-dd"T"HH:mm:ss';default:{const t=e.replace(/tt/g,"AM/PM");return t.includes("z")&&_getConvertLogger().warn("Warning: Excel will not recognize timezone format 'z', 'zz', or 'zzz'"),t.includes("h")&&!t.includes("AM/PM")&&_getConvertLogger().warn("Warning: Excel will interpret 'h' as 'H' if the format does not have an AM/PM designator"),t}}}function _convertToExcelNumberFormatString(e){switch(e){case NumberFormat.ACCOUNTING:return'_("$"* #,##0.00_);_("$"* (#,##0.00);_("$"* "-"??_);_(@_)';case NumberFormat.CURRENCY:return'"$"#,##0.00';case NumberFormat.FIXED_POINT:case NumberFormat.DEFAULT:return"0.0000";case NumberFormat.NUMBER:return"#,##0.0000";case NumberFormat.PERCENT:return"0%";case NumberFormat.ROUND_TRIP:return"0.00000";default:return e}}function _toXLSXValue(e,t){if(null==e)return"";if(!t.useFormattedValues){if("number"==typeof e)return e;if(e instanceof Date)return"timestamp"===t.dateFormat?e.getTime():e}let r=e.toString();return t.escapeFormulaChars&&(r=escapeFormulaChars(r)),r}async function _parseXLSX(e,t){const r=await import("xlsx"),o=new Promise(((o,a)=>{const n=new FileReader;n.onload=()=>{const e=new Uint8Array(n.result);let a="";for(const t of e)a+=String.fromCharCode(t);const i=r.read(a,{type:"binary",cellDates:!0}),s=t.sheetName||i.SheetNames[0],m=i.Sheets[s];o(m)},n.onerror=()=>{a(n.error)},n.readAsArrayBuffer(e)})),a=await o,n=r.utils.decode_range(a["!ref"]),i=[];for(let e=n.s.r;e<=n.e.r;e++){const t=[];for(let o=n.s.c;o<=n.e.c;o++){const n=a[`${r.utils.encode_cell({r:e,c:o})}`];t.push(n?{raw:n.v,formatted:"s"===n.t?void 0:n.w}:{raw:""})}i.push(t)}return i}async function _getDBaseSpatialReferenceWKT(e){const{wkid:t,wkt:r}=e[0].spatialReference;if(!e.every((e=>e.spatialReference.wkid===t&&e.spatialReference.wkt===r)))throw new Error("Cannot create shapefile that contains geometries with different spatial references.");return null!=r?r:esriWkidToWkt(null!=t?t:SpatialReference.WGS84.wkid)}function _getDBaseColumnTypes(e,t,r,o){const a={};for(const n of t){if(e.some((e=>_hasCodedDomain(e,n)))){a[n]=DBaseTypes.STRING;continue}const t=r?r.fields.find((e=>e.name===n)):void 0;if(t){switch(t.type){case"oid":case"double":case"integer":case"single":case"small-integer":a[n]=DBaseTypes.NUMBER;break;case"date":a[n]=o?DBaseTypes.NUMBER:DBaseTypes.DATE;break;default:a[n]=DBaseTypes.STRING}continue}const i=(e,t)=>{var r;return null!==(r=e.attributes.get(t))&&void 0!==r?r:e.presentableAttributes.get(t)};e.every((e=>i(e,n)instanceof Date||void 0===i(e,n)))&&e.some((e=>i(e,n)instanceof Date))?a[n]=o?DBaseTypes.NUMBER:DBaseTypes.DATE:e.every((e=>"number"==typeof i(e,n)||void 0===i(e,n)))&&e.some((e=>"number"==typeof i(e,n)))?a[n]=DBaseTypes.NUMBER:e.every((e=>"boolean"==typeof i(e,n)||void 0===i(e,n)))&&e.some((e=>"boolean"==typeof i(e,n)))?a[n]=DBaseTypes.BOOLEAN:a[n]=DBaseTypes.STRING}return a}function _getDBaseGeometries(e){return e.map((e=>{if(isPoint(e)){const{x:t,y:r,z:o,m:a}=e,n=[t,r];return e.hasZ&&n.push(o),e.hasM&&n.push(a),_padZValues(n,e)}if(isMultipoint(e))return _padZValuesArray(e.points,e);if(isPolyline(e))return _padZValues2DArray(e.paths,e);if(isPolygon(e))return _padZValues2DArray(e.rings,e);if(isExtent(e)){const t=[e.xmin,e.ymax];return[[t,[e.xmax,e.ymax],[e.xmax,e.ymin],[e.xmin,e.ymin],t]]}throw new Error("Unsupported geometry type.")}))}function _padZValues(e,t){return 3===e.length&&!t.hasZ&&t.hasM?[e[0],e[1],void 0,e[2]]:e}function _padZValuesArray(e,t){return e.map((e=>_padZValues(e,t)))}function _padZValues2DArray(e,t){return e.map((e=>_padZValuesArray(e,t)))}function _getDbaseValues(e,t,r,o){const a=[];for(const n of e){const e={};for(const a of t){let t=_getAttributeValue(n,a,o);if(null==t&&(t=""),o.useFormattedValues)t=t.toString();else{t=getDbaseValue(t,r[a],o)}e[a]=t}a.push(e)}return a}function getDbaseValue(e,t,r){var o,a;switch(t){case DBaseTypes.NUMBER:return e instanceof Date?e.getTime():parseNumber(e);case DBaseTypes.STRING:return e instanceof Date?formatDate({format:null!==(o=r.dateFormat)&&void 0!==o?o:DateFormat.ROUND_TRIP,timeZone:"UTC"},e):"number"==typeof e?formatNumber(null!==(a=r.numberFormat)&&void 0!==a?a:NumberFormat.DEFAULT,e):e.toString();case DBaseTypes.BOOLEAN:return!!e;case DBaseTypes.DATE:return parseDate(e);default:return e.toString()}}function _parseShapefileNames(e){if(!e.length)return[];let t=e[0];const r=t.match(shapefileNameRegex);return r?(t=r[1],e.filter((e=>{const r=e.match(shapefileNameRegex);return r&&r[1]===t}))):[t]}function _parseDBaseData(e){const t=e.map((e=>Object.keys(e))).reduce(((e,t)=>e.concat(t.filter((t=>!e.includes(t))))),[]);return[t.map((e=>({raw:e}))),...e.map((e=>t.map((t=>({raw:e[t]})))))]}function _parseShpPointGeometry(e){checkArg("geometry.coordinates",e.type).matches("Point"),checkArg("geometry.coordinates",e.coordinates).satisfies((e=>"number"==typeof e||Array.isArray(e)));const[t,r,o]=e.coordinates,a=new Point({x:t,y:r,spatialReference:SpatialReference.WGS84});if(Array.isArray(o)){const[e,t]=o;!e&&!t||e?a.z=e:a.m=t}return a}async function _parseShpGeometry(e,t){const r=isPoint(e)?_parseShpPointGeometry(e):geoJSONToEsri(e);if(t){let e;try{const r=await esriWktToWkid(t);e=new SpatialReference({wkid:parseNumber(r)})}catch{}e||(e=new SpatialReference({wkt:t})),r.spatialReference=e}return r}
|