@vertigis/arcgis-extensions 47.0.1 → 47.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/AccessDeniedError.js +1 -1
- package/AppConfig.schema.json +6 -2
- package/NotFoundError.js +1 -1
- package/data/ArcGISServiceTableExtension.js +1 -1
- package/data/Feature.d.ts +7 -7
- package/data/Feature.js +1 -1
- package/data/FeatureList.js +1 -1
- package/data/FeatureSaveError.js +1 -1
- package/data/FieldExtension.js +1 -1
- package/data/Schema.js +1 -1
- package/data/convert.d.ts +6 -2
- package/data/convert.js +1 -1
- package/docs/html/assets/navigation.js +1 -1
- package/docs/html/assets/search.js +1 -1
- package/docs/html/classes/data_Feature.Feature.html +6 -6
- package/docs/html/classes/support_FormatSettings.FormatSettings.html +10 -5
- package/docs/html/classes/support_Serializable.SerializableBase.html +1 -1
- package/docs/html/classes/utilities_Time.Time.html +11 -0
- package/docs/html/classes/{utilities_date.DateFormatter.html → utilities_format_date.DateFormatter.html} +57 -56
- package/docs/html/classes/{utilities_number.NumberFormatter.html → utilities_format_number.NumberFormatter.html} +54 -54
- package/docs/html/classes/utilities_format_string.StringFormatter.html +49 -0
- package/docs/html/classes/utilities_format_time.TimeFormatter.html +137 -0
- package/docs/html/enums/{utilities_date.DateFormat.html → utilities_format_formats.DateFormat.html} +12 -11
- package/docs/html/enums/{utilities_number.NumberFormat.html → utilities_format_formats.NumberFormat.html} +9 -8
- package/docs/html/enums/utilities_format_formats.TimeFormat.html +16 -0
- package/docs/html/functions/utilities_field.isNumericFieldType.html +1 -0
- package/docs/html/functions/{utilities_date.ERR_TIME_ZONE_INVALID.html → utilities_format_date.ERR_TIME_ZONE_INVALID.html} +1 -1
- package/docs/html/functions/{utilities_date.esriFormatToGeocortexFormat.html → utilities_format_date.esriFormatToGeocortexFormat.html} +2 -2
- package/docs/html/functions/{utilities_date.format.html → utilities_format_date.format.html} +3 -3
- package/docs/html/functions/{utilities_date.isValid.html → utilities_format_date.isValid.html} +1 -1
- package/docs/html/functions/{utilities_date.isValidTimeZone.html → utilities_format_date.isValidTimeZone.html} +1 -1
- package/docs/html/functions/{utilities_date.parse.html → utilities_format_date.parse.html} +3 -3
- package/docs/html/functions/{utilities_date.parseUtc.html → utilities_format_date.parseUtc.html} +3 -3
- package/docs/html/functions/{utilities_number.format.html → utilities_format_number.format.html} +3 -3
- package/docs/html/functions/{utilities_number.parse.html → utilities_format_number.parse.html} +3 -3
- package/docs/html/functions/{utilities_string.format.html → utilities_format_string.format.html} +3 -3
- package/docs/html/functions/utilities_format_time.esriFormatToGeocortexFormat.html +5 -0
- package/docs/html/functions/utilities_format_time.format.html +9 -0
- package/docs/html/functions/utilities_format_time.parse.html +15 -0
- package/docs/html/hierarchy.html +1 -1
- package/docs/html/interfaces/data_Feature.FormatOptions.html +21 -13
- package/docs/html/interfaces/data_convert.FromCsvOptions.html +6 -3
- package/docs/html/interfaces/data_convert.FromShapefileOptions.html +6 -3
- package/docs/html/interfaces/data_convert.FromXLSXOptions.html +6 -3
- package/docs/html/interfaces/data_convert.ToCsvOptions.html +6 -3
- package/docs/html/interfaces/data_convert.ToShapefileOptions.html +6 -3
- package/docs/html/interfaces/data_convert.ToXLSXOptions.html +6 -3
- package/docs/html/interfaces/data_convert.UploadDataOptions.html +6 -3
- package/docs/html/interfaces/json_FeatureLayerJson.FeatureLayerJson.html +2 -2
- package/docs/html/interfaces/json_StreamLayerJson.StreamLayerJson.html +2 -2
- package/docs/html/interfaces/mapping_FeatureLayerExtension.FeatureLayerProperties.html +2 -2
- package/docs/html/interfaces/mapping_FeatureLayerExtensionBase.FeatureLayerBaseProperties.html +2 -2
- package/docs/html/interfaces/support_FormatSettings.FormatSettingsProperties.html +10 -6
- package/docs/html/interfaces/utilities_format_FormatSettings.FormatSettings.html +21 -0
- package/docs/html/interfaces/{utilities_date.DateFormatterProperties.html → utilities_format_date.DateFormatterProperties.html} +12 -11
- package/docs/html/interfaces/{utilities_date.DateSettings.html → utilities_format_date.DateSettings.html} +6 -5
- package/docs/html/interfaces/utilities_format_date.FormatOptions.html +12 -0
- package/docs/html/interfaces/utilities_format_date.ParseOptions.html +14 -0
- package/docs/html/interfaces/{utilities_number.FormatOptions.html → utilities_format_number.FormatOptions.html} +9 -8
- package/docs/html/interfaces/{utilities_number.NumberFormatterProperties.html → utilities_format_number.NumberFormatterProperties.html} +13 -13
- package/docs/html/interfaces/{utilities_number.NumberSettings.html → utilities_format_number.NumberSettings.html} +7 -7
- package/docs/html/interfaces/{utilities_number.ParseOptions.html → utilities_format_number.ParseOptions.html} +4 -4
- package/docs/html/interfaces/utilities_format_string.FormatOptions.html +30 -0
- package/docs/html/interfaces/utilities_format_time.FormatOptions.html +7 -0
- package/docs/html/interfaces/utilities_format_time.ParseOptions.html +9 -0
- package/docs/html/interfaces/utilities_format_time.TimeFormatterProperties.html +14 -0
- package/docs/html/interfaces/utilities_format_time.TimeSettings.html +10 -0
- package/docs/html/interfaces/utilities_log.LogOptions.html +16 -12
- package/docs/html/modules/utilities_FormatSettings.html +3 -3
- package/docs/html/modules/utilities_Time.html +2 -0
- package/docs/html/modules/utilities_date.html +18 -18
- package/docs/html/modules/utilities_format_FormatSettings.html +3 -0
- package/docs/html/modules/utilities_format__utils.html +1 -0
- package/docs/html/modules/utilities_format_date.html +16 -0
- package/docs/html/modules/utilities_format_formats.html +4 -0
- package/docs/html/modules/utilities_format_number.html +9 -0
- package/docs/html/modules/utilities_format_string.html +5 -0
- package/docs/html/modules/utilities_format_time.html +11 -0
- package/docs/html/modules/utilities_number.html +11 -11
- package/docs/html/modules/utilities_string.html +5 -5
- package/docs/html/types/json_FieldJson.FieldJsonType.html +1 -1
- package/docs/html/types/json_PopupInfoJson.DateFormatJsonType.html +1 -1
- package/docs/html/variables/utilities_format_FormatSettings.settings.html +3 -0
- package/docs/html/variables/{utilities_date.DEFAULT_PARSING_FORMATS.html → utilities_format_date.DEFAULT_PARSING_FORMATS.html} +1 -1
- package/docs/html/variables/{utilities_date.INVALID_DATE.html → utilities_format_date.INVALID_DATE.html} +1 -1
- package/docs/html/variables/{utilities_date.settings.html → utilities_format_date.settings.html} +1 -1
- package/docs/html/variables/{utilities_FormatSettings.settings.html → utilities_format_number.settings.html} +1 -2
- package/docs/html/variables/utilities_format_time.DEFAULT_PARSING_FORMATS.html +2 -0
- package/docs/html/variables/{utilities_number.settings.html → utilities_format_time.settings.html} +1 -1
- package/docs/html/variables/version.version.html +1 -1
- package/json/FieldJson.d.ts +1 -1
- package/json/PopupInfoJson.d.ts +1 -1
- package/locale/language.d.ts +1 -1
- package/locale/language.js +1 -1
- package/mapping/ArcGISSublayerExtension.js +1 -1
- package/mapping/FeatureLayerExtensionBase.js +1 -1
- package/mapping/SubtypeGroupLayerExtension.js +1 -1
- package/mapping/SubtypeSublayerExtension.js +1 -1
- package/mapping/_SublayerExtension.js +1 -1
- package/mapping/support/featureService.js +1 -1
- package/package.json +3 -2
- package/portal/Field.d.ts +1 -1
- package/portal/Field.js +1 -1
- package/portal/Format.d.ts +2 -2
- package/support/FormatSettings.d.ts +21 -7
- package/support/FormatSettings.js +1 -1
- package/support/InitializeError.js +1 -1
- package/tasks/identify/IdentifyError.js +1 -1
- package/tasks/query/QueryError.js +1 -1
- package/tasks/search/SearchError.js +1 -1
- package/tasks/search/_utilities.js +1 -1
- package/tasks/search/support/_querySearchProviderUtils.js +1 -1
- package/utilities/FormatSettings.d.ts +6 -31
- package/utilities/FormatSettings.js +1 -1
- package/utilities/GeometryServiceError.js +1 -1
- package/utilities/Time.d.ts +22 -0
- package/utilities/Time.js +1 -0
- package/utilities/_wkt.js +1 -1
- package/utilities/date.d.ts +35 -349
- package/utilities/date.js +1 -1
- package/utilities/field.d.ts +2 -0
- package/utilities/field.js +1 -1
- package/utilities/format/FormatSettings.d.ts +41 -0
- package/utilities/format/FormatSettings.js +1 -0
- package/utilities/format/_utils.d.ts +1 -0
- package/utilities/format/_utils.js +1 -0
- package/utilities/format/date.d.ts +336 -0
- package/utilities/format/date.js +1 -0
- package/utilities/format/formats.d.ts +127 -0
- package/utilities/format/formats.js +1 -0
- package/utilities/format/number.d.ts +193 -0
- package/utilities/format/number.js +1 -0
- package/utilities/format/string.d.ts +96 -0
- package/utilities/format/string.js +1 -0
- package/utilities/format/time.d.ts +206 -0
- package/utilities/format/time.js +1 -0
- package/utilities/log.d.ts +2 -2
- package/utilities/number.d.ts +25 -218
- package/utilities/number.js +1 -1
- package/utilities/string.d.ts +16 -81
- package/utilities/string.js +1 -1
- package/version.d.ts +1 -1
- package/version.js +1 -1
- package/docs/html/classes/utilities_string.StringFormatter.html +0 -42
- package/docs/html/interfaces/utilities_FormatSettings.FormatSettings.html +0 -17
- package/docs/html/interfaces/utilities_date.FormatOptions.html +0 -9
- package/docs/html/interfaces/utilities_date.ParseOptions.html +0 -11
- package/docs/html/interfaces/utilities_string.FormatOptions.html +0 -22
package/AccessDeniedError.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{format as r}from"./utilities/string.js";export class AccessDeniedError extends Error{constructor(e,...s){super(e&&r(e,...s)||"Access denied."),this.name="AccessDeniedError"}}
|
|
1
|
+
import{format as r}from"./utilities/format/string.js";export class AccessDeniedError extends Error{constructor(e,...s){super(e&&r(e,...s)||"Access denied."),this.name="AccessDeniedError"}}
|
package/AppConfig.schema.json
CHANGED
|
@@ -834,7 +834,7 @@
|
|
|
834
834
|
"type": "string"
|
|
835
835
|
},
|
|
836
836
|
"dateFormat": {
|
|
837
|
-
"description": "The default format for date values. Either a\n{@link utilities /
|
|
837
|
+
"description": "The default format for date values. Either a\n{@link utilities /format/formats!DateFormat} constant, or a custom date\nformat string.",
|
|
838
838
|
"type": "string"
|
|
839
839
|
},
|
|
840
840
|
"fractionalDigits": {
|
|
@@ -846,7 +846,11 @@
|
|
|
846
846
|
"type": "string"
|
|
847
847
|
},
|
|
848
848
|
"numberFormat": {
|
|
849
|
-
"description": "The default format for number values. Either a\n{@link utilities /
|
|
849
|
+
"description": "The default format for number values. Either a\n{@link utilities /format/formats!NumberFormat} constant, or a custom number\nformat string.",
|
|
850
|
+
"type": "string"
|
|
851
|
+
},
|
|
852
|
+
"timeFormat": {
|
|
853
|
+
"description": "The default format for time values. Either a\n{@link utilities /format/formats!DateFormat} constant, or a custom time\nformat string.",
|
|
850
854
|
"type": "string"
|
|
851
855
|
},
|
|
852
856
|
"timeZone": {
|
package/NotFoundError.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{format as r}from"./utilities/string.js";export class NotFoundError extends Error{constructor(o,...
|
|
1
|
+
import{format as r}from"./utilities/format/string.js";export class NotFoundError extends Error{constructor(o,...t){super(o&&r(o,...t)||"The requested resource does not exist or could not be found."),this.name="NotFoundError"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__decorate as e}from"tslib";import t from"@arcgis/core/core/Collection";import
|
|
1
|
+
import{__decorate as e}from"tslib";import t from"@arcgis/core/core/Collection";import r from"@arcgis/core/rest/support/AttachmentQuery.js";import{InvalidOperationError as s}from"../InvalidOperationError.js";import{toAttachment as i}from"../data/Attachment.js";import{PopupTemplateFeatureSettings as a}from"../mapping/support/PopupTemplateFeatureSettings.js";import{DefaultArcGISRequestHelper as l}from"../support/ArcGISRequestHelper.js";import{serializable as o}from"../support/Serializable.js";import{ArcGISRelationshipCollection as n}from"../support/_ArcGISRelationshipCollection.js";import{applyEdits as u}from"../support/_featureEdit.js";import{ReadOnlyCollection as p}from"../utilities/ReadOnlyCollection.js";import{getGdbVersion as c}from"../utilities/_version.js";import{isArcGISServiceTableExtension as h}from"../utilities/extensions.js";import{parse as m}from"../utilities/format/number.js";import{isFeatureLayer as d,isMapImageSublayer as b,isSubtypeGroupLayer as y}from"../utilities/layers.js";import{isNumeric as _}from"../utilities/number.js";import{TableExtension as f,TableSchema as g}from"./_TableExtension.js";import{addAttachment as w,deleteAttachments as I,supportsAttachmentEditing as j}from"./support/attachments.js";let x=class extends f{attachmentTypes;get requestHelper(){return this._requestHelper||(this._requestHelper=new l),this._requestHelper}set requestHelper(e){this._requestHelper=e}get capabilities(){const e=j(this.table);return this.table?.capabilities?.operations?{...this.table.capabilities.operations,supportsAttachmentEditing:e,supportsStandardizedQueries:this.table.capabilities?.query?.supportsStandardizedQueriesOnly}:{...super.capabilities,supportsAttachmentEditing:e}}get canChangeDefinitionExpression(){return!0}_requestHelper;async _getAttachments(e){if(!this.table?.capabilities?.data?.supportsAttachment)return[];const t=+e.primaryKey,s=this.table?.gdbVersion??c(this.table?.customParameters),a=new r({objectIds:[t]}),l=await this.table.queryAttachments(a);return l?.[t]?.length?l[t].map((e=>i(e,{gdbVersion:s}))):[]}async _addAttachment(e,t){return w(e,this.table,t,{attachmentTypes:this.attachmentTypes})}async _deleteAttachments(e,t){return I(e,this.table,t)}get _layerUrl(){return _(this.table.layerId)?`${this.table.url}/${this.table.layerId}`:this.table.url}async*_getFeatures(e,t){const r=this.table.createQuery();r.objectIds=e.map((e=>m(e))),r.where=void 0,r.outFields=t.outFields,r.returnGeometry=t.returnGeometry,yield*(await import("../support/_query.js")).executeQuery(r,this,this.table,t.cancelToken)}async _addFeatures(e,t){await u({adds:e},this.table,t)}async _updateFeatures(e,t){await u({updates:e},this.table,t)}async _deleteFeatures(e,t){await u({deletes:e},this.table,t)}async _onInitialize(){await super._onInitialize(),await this.relationships.initialize()}_isSupportedTable(e){return!e.loaded||e.isTable}_createFeatureSettings(){return new E(this)}_createRelationships(){return new z(this)}_createSchema(){return new T(this)}_getSerializableProperties(){const e=super._getSerializableProperties();return{...e,attachmentTypes:["initial"],table:{...this._toPropertyDef(e.table),default:{}},requestHelper:{serialize:!1}}}};x=e([o],x);export{x as ArcGISServiceTableExtension};class S extends p{constructor(e){if(super(),e.table)this._onTableResolved(e.table);else{this._collection=new t;const r=e.watch("table",(()=>{this._onTableResolved(e.table),r.remove()}),!0)}}_onTableResolved(e){this._collection=new t(e.types)}}let T=class extends g{_typeCollection;constructor(e){super(e),this._typeCollection=new S(e),this._bindSettingToTableProperty("displayField"),this._bindSettingToTableProperty("typeIdField")}get types(){return this._typeCollection}_setSetting(e,t){if(this._tableBindings.has(e))throw new s("This schema property is read-only.");super._setSetting(e,t)}_createFieldCollection(){return new p(super._createFieldCollection())}};T=e([o],T);let E=class extends a{};E=e([o],E);class z extends n{get _sourceUrl(){if(this._source.table?.url)return _(this._source.table.layerId)?`${this._source.table.url}/${this._source.table.layerId}`:this._source.table.url}get _sourceLayerId(){return this._source.table?.layerId}_findRelatedSource(e){if(!this._source.mapExtension||!this._source.table?.url)return;const t=this._source.mapExtension.tableExtensions.initializedItems.find((t=>h(t)&&t.table.url===this._source.table.url&&t.table.layerId===e));if(t)return t;for(const t of this._source.mapExtension.allLayerExtensions.initializedItems.toArray()){const r=t.allSublayerExtensions.initializedItems.find((t=>b(t.sublayer)&&t.sublayer.layer.url===this._source.table.url&&t.sublayer.id===e));if(r)return r}return this._source.mapExtension.allLayerExtensions.initializedItems.find((t=>(d(t.layer)||y(t.layer))&&t.layer.url===this._source.table.url&&t.layer.layerId===e))}}
|
package/data/Feature.d.ts
CHANGED
|
@@ -12,7 +12,7 @@ import type { WatchCallback } from "../support/esri.js";
|
|
|
12
12
|
import { CaseInsensitiveObservableMap } from "../utilities/CaseInsensitiveObservableMap.js";
|
|
13
13
|
import { ObservableMap } from "../utilities/ObservableMap.js";
|
|
14
14
|
import { ReadOnlyMap } from "../utilities/ReadOnlyMap.js";
|
|
15
|
-
import { type FormatOptions as FormatOptionsBase } from "../utilities/string.js";
|
|
15
|
+
import { type FormatOptions as FormatOptionsBase } from "../utilities/format/string.js";
|
|
16
16
|
import type { Attachment, AttachmentProperties } from "./Attachment.js";
|
|
17
17
|
import type { FeatureSet } from "./FeatureSet.js";
|
|
18
18
|
import type { FeatureSettingsProperties } from "./FeatureSettings.js";
|
|
@@ -196,9 +196,9 @@ export declare class Feature extends EntityBase<FeatureProperties> {
|
|
|
196
196
|
private readonly _initializedRelationships;
|
|
197
197
|
constructor(properties?: FeatureProperties);
|
|
198
198
|
/**
|
|
199
|
-
* Same as {@link utilities/string!StringFormatter.format}, except
|
|
200
|
-
* format string may also contain field format items, which have
|
|
201
|
-
* syntax: `{field-name[:format]}`.
|
|
199
|
+
* Same as {@link utilities/format/string!StringFormatter.format}, except
|
|
200
|
+
* that the format string may also contain field format items, which have
|
|
201
|
+
* this syntax: `{field-name[:format]}`.
|
|
202
202
|
*
|
|
203
203
|
* These items will be substituted with the appropriate field value. Null
|
|
204
204
|
* and undefined values will be converted into empty strings.
|
|
@@ -207,9 +207,9 @@ export declare class Feature extends EntityBase<FeatureProperties> {
|
|
|
207
207
|
*/
|
|
208
208
|
format(format: string, ...args: unknown[]): string;
|
|
209
209
|
/**
|
|
210
|
-
* Same as {@link utilities/string!StringFormatter.format}, except
|
|
211
|
-
* format string may also contain field format items, which have
|
|
212
|
-
* syntax: `{field-name[:format]}`.
|
|
210
|
+
* Same as {@link utilities/format/string!StringFormatter.format}, except
|
|
211
|
+
* that the format string may also contain field format items, which have
|
|
212
|
+
* this syntax: `{field-name[:format]}`.
|
|
213
213
|
*
|
|
214
214
|
* These items will be substituted with the appropriate field value. Null
|
|
215
215
|
* and undefined values will be converted into empty strings.
|
package/data/Feature.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__decorate as e}from"tslib";import t from"@arcgis/core/Graphic";import s from"@arcgis/core/core/Collection";import{fromJSON as i}from"@arcgis/core/geometry/support/jsonUtils";import{EntityBase as r}from"../Entity.js";import{Hyperlink as a}from"../Hyperlink.js";import{InvalidOperationError as n}from"../InvalidOperationError.js";import{ItemType as o}from"../ItemType.js";import{serializable as l}from"../support/Serializable.js";import{CaseInsensitiveObservableMap as h}from"../utilities/CaseInsensitiveObservableMap.js";import{MapTransformCollection as u}from"../utilities/MapTransformCollection.js";import{ObservableMap as p}from"../utilities/ObservableMap.js";import{ReadOnlyMap as c}from"../utilities/ReadOnlyMap.js";import{flatten as m,groupBy as f}from"../utilities/array.js";import{checkArg as d}from"../utilities/checkArg.js";import{compare as g}from"../utilities/collection.js";import{parse as y,esriFormatToGeocortexFormat as _}from"../utilities/date.js";import{isCodedValueDomain as b,isGeometry as x}from"../utilities/esri.js";import{getArcadeExpressionFromField as w,getRelationshipFromField as F,isArcadeExpressionField as v}from"../utilities/field.js";import{map as I,find as S}from"../utilities/iterable.js";import{getLogger as z}from"../utilities/log.js";import{parse as A,NumberFormat as E}from"../utilities/number.js";import{map as j}from"../utilities/promise.js";import{caseInsensitiveEquals as T}from"../utilities/string.js";import{format as k}from"../utilities/string.js";import{onCollectionPropertyChange as R}from"../utilities/watch.js";import{FeatureSettings as C}from"./FeatureSettings.js";import{Schema as O}from"./Schema.js";const M=z("geocortex.api.data.Feature");export const SCORE_FIELD="_score";export const SCORE_FIELD_ORIGINAL="_score_original";let N=class extends r{attributes;get geometry(){return this._geometry}set geometry(e){this.notifyChange("geometryType"),this._geometry=x(e)||!e?e:i(e),this.schema.spatialReference=this._geometry?.spatialReference}settings;schema;attachments;expressionFieldValues;_itemType=o.FEATURE;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.schema.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),this.notifyChange("attachmentsInitialized"),this.notifyChange("relatedFeaturesInitialized")}get primaryKey(){const e=this.attributes.get(this.schema.primaryKeyField);return null!=e?`${e}`:void 0}get hasGlobalId(){return!!this.schema.fields.find((e=>"global-id"===e.type))}get globalId(){const e=this.schema.fields.find((e=>"global-id"===e.type));return e?this.attributes.get(e.name):void 0}set globalId(e){const t=this.schema.fields.find((e=>"global-id"===e.type));if(!t)throw new n("Cannot set global ID on feature -- no global ID field.");this.attributes.set(t.name,e)}get presentableAttributes(){return this._presentableAttributes=this._presentableAttributes||new U(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 J(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 attachmentsInitialized(){return!this.source||this._attachmentsInitialized}get relatedFeaturesInitialized(){return!this.source||this.source.relationships.every((e=>this._initializedRelationships.has(e)))}get expressionsInitialized(){return!this.settings.popupTemplate?.expressionInfos?.length||this._expressionsInitialized}get _hydrationStatus(){return this._featureHydrationStatus?this._featureHydrationStatus:this.source?.capabilities?.supportsQuery&&1===this.attributes.size&&void 0!==this.primaryKey?"dehydrated":"hydrated"}set _hydrationStatus(e){this._featureHydrationStatus=e}get _key(){return`${this.source?.id}//${this.primaryKey??this.globalId??this.id}`}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(){if(this.settings.popupTemplate?.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""}_geometry;_source;_presentableAttributes;_hyperlinks;_featureHydrationStatus;_relatedFeatures;_expressionFieldValues=new p;_expressionValuesUpdatePending=!1;_attachmentsInitialized=!1;_expressionsInitialized=!1;_initializedRelationships=new WeakSet;constructor(e){super(e),this.settings=new C,this.settings._setFeature(this),this.schema=new O,this.schema._featureSettings=this.settings,this.attachments=new s,this.attributes=new h,this._relatedFeatures=new p,this.expressionFieldValues=new D(this._expressionFieldValues,this),R(this,"source.relationships",(()=>{this.notifyChange("relatedFeaturesInitialized")}),!0),this.settings.watch("popupTemplate",((e,t)=>{e!==t&&(this._expressionsInitialized=!1,this.notifyChange("expressionsInitialized"))}),!0)}format(e,...t){let s="string"==typeof e?{format:e}:e;d("options",s).isNotMissing();const{format:i}=s;d("format",i).isNotMissing();let r=s.format.replace(Z,$);return r=r.replace(G,((e,t,i,r,a)=>B(this,t||i,r,{...s,format:a?`{0:${a}}`:"{0}"}))),r=r.replace(H,"{{"),s={...s},s.format=r,k(s,...t)}clearExpressionInfos(){this._expressionFieldValues.clear()}toGraphic(){return toGraphic(this)}async fetchExpressionInfos(e=!1){const{expressionInfos:t}=this.settings.popupTemplate??{};if(!t)return;const{runAsyncArcadeExpression:s}=await import("../utilities/arcade.js");if(await Promise.all(t.map((async e=>{try{const t=this.source?.layer??this.source?.sublayer;let i=this.source?.mapExtension;if(!i){const e=this.source?.layerExtension;i=e?.mapExtension}this._expressionFieldValues.set(e.name,await s(e.expression,{layer:t,map:i?.map,feature:this,spatialReference:this.schema.spatialReference}))}catch(t){t instanceof Error&&M.error({message:"Error evaluating expression '{0}': {1}.",error:t},e.name,t.message),this._expressionFieldValues.set(e.name,K)}}))),e)return this.attributes.on("change",(async e=>{this._expressionValuesUpdatePending||(this._expressionValuesUpdatePending=!0,setTimeout((async()=>{this._expressionValuesUpdatePending=!1,await this.fetchExpressionInfos()}),0))}));this._expressionsInitialized=!0,this.notifyChange("expressionsInitialized")}async fetchRelatedFeatures(e,t){if(!this.source)return;let s=[];if(e){const t=new Set(Array.isArray(e)?e:[e]);for(const e of t){const t="string"==typeof e?this.source.relationships.find((t=>t.id===e)):e;if(!t||!this.source.relationships.includes(t))throw new n("Relationship not found in feature source.");s.push(t)}}else s=this.source.relationships.toArray();const i=await j(s,(async e=>[e,await(async()=>{const s=await e.getRelatedFeatures(this,t);return this._initializedRelationships.add(e),s})()]));for(const e of i)this._relatedFeatures.set(e[0],e[1]);this.notifyChange("relatedFeaturesInitialized")}async fetchAttachments(){if(this.source){const e=await this.source.getAttachments(this);g(this.attachments,e,{equals:(e,t)=>e.id===t.id,onMissing:(e,t)=>this.attachments.remove(e),onNew:(e,t)=>{this.attachments.add(e)},onMatch:(e,t,s,i)=>{this.attachments.splice(s,1,t)}}),this._attachmentsInitialized=!0,this.notifyChange("attachmentsInitialized")}}async addAttachment(e){return this.source?.addAttachment(this,e)}async deleteAttachments(e){return this.source?.deleteAttachments(this,e)}_getSerializableProperties(){return{...super._getSerializableProperties(),attributes:{serializeModes:["project"],serialize:e=>{const t={};if("project"===e&&this.primaryKey&&(this.source?.capabilities).supportsQuery)t[this.schema.primaryKeyField]=this.primaryKey;else for(const[e,s]of this.attributes.entries())t[e]=s;return t},deserialize:e=>{if(this.attributes.clear(),e instanceof Map)e.forEach(((e,t)=>{this.attributes.set(t,e)}));else for(const[t,s]of Object.entries(e))this.attributes.set(t,s)}},geometry:{serializeModes:["project"],serialize:e=>"project"===e&&(this.source?.capabilities).supportsQuery?this.getDefault("geometry"):this.geometry?.toJSON(),deserialize:e=>{this.geometry=e}},settings:{serializeModes:["project"],serialize:e=>"project"===e&&(this.source?.capabilities).supportsQuery?this.getDefault("settings"):this.settings.toJSON(e)},schema:{serializeModes:["project"],serialize:e=>"project"===e&&(this.source?.capabilities).supportsQuery?this.getDefault("schema"):this.schema.toJSON(e)},source:["project"]}}_watchProperty(e,t,s,i){if("title"===e||"description"===e){const r=super._watchProperty(e,t,s,i),a="title"===e?"settings.popupTemplate.title":"settings.popupTemplate.content",n=this.watch(a,(()=>{this.notifyChange(e)})),o=this.presentableAttributes.on("change",(()=>{this.notifyChange(e)}));return{remove(){r.remove(),n.remove(),o.remove()}}}return super._watchProperty(e,t,s,i)}async _onInitialize(){const e=this._findRelationshipIds(this._title,this._description),t=this.source?this.source.relationships.map((e=>e.id)).toArray():[],s=[];for(const i of e)t.includes(i)?s.push(this.fetchRelatedFeatures(i)):M.error("Could not find relationship '{0}' referenced in feature title or description.",i);await Promise.all(s)}_findRelationshipIds(...e){const t=[];for(const s of e){let e;const i=s.replace(Z,$);for(;e=L.exec(i),null!==e;){const s=e[0];t.includes(s)||t.push(e[1])}}return t}};N=e([l],N);export{N as Feature};export function toFeature(e,t){const s=new N(t);if(e.attributes)for(const t of Object.keys(e.attributes))s.attributes.set(t,e.attributes[t]);return s.geometry=e.geometry,e.popupTemplate&&(s.settings.popupTemplate=e.popupTemplate),s}export function toGraphic(e){const s=new t;s.attributes={};for(const t of e.attributes.keys())s.attributes[t]=e.attributes.get(t);return e.source?.layer&&(s.layer=e.source?.layer),s.geometry=e.geometry,e.settings.popupTemplate&&(s.popupTemplate=e.settings.popupTemplate),s}const V="Presentable attributes are read-only.",P="Feature hyperlinks are read-only. Modify the feature's hyperlink templates instead.";class D extends c{_feature;_pending=new Set;constructor(e,t){super(e),this._feature=t}get(e){return super.has(e)||this._calcExpressionValue(e),super.get(e)}async _calcExpressionValue(e){if(!this._pending.has(e)){this._pending.add(e);try{const{spatialReference:t}=this._feature.schema,s=this._feature.settings.popupTemplate?.expressionInfos?.find((t=>t.name===e));if(!s)return;const{isArcadeScriptAsync:i,runAsyncArcadeExpression:r,arcadeScriptUsesGeometry:a,runArcadeExpression:n}=await import("../utilities/arcade.js");try{if(i(s.expression,t)){const i=this._feature.source?.layer??this._feature.source?.sublayer;let a=this._feature.source?.mapExtension;if(!a){const e=this._feature.source?.layerExtension;a=e?.mapExtension}this._originalMap.set(e,await r(s.expression,{feature:this._feature,layer:i,map:a?.map,spatialReference:t}))}else{if(a(s.expression,t)){const{enableGeometrySupport:e}=await import("@arcgis/core/arcade/arcade");await e()}this._originalMap.set(e,n(s.expression,{feature:this._feature,spatialReference:t}))}}catch(t){t instanceof Error&&M.error({message:"Error evaluating expression '{0}': {1}.",error:t},e,t.message),this._originalMap.set(e,K)}}finally{this._pending.delete(e)}}}}class U extends c{[Symbol.toStringTag];get size(){return this._feature.attributes.size+this._feature.schema.fields._expressionFieldsLength}_feature;_numObservers;_onAllObserversRemoved;constructor(e){super(new h),this._feature=e}clear(){throw new n(V)}delete(e){throw new n(V)}forEach(e,t){d("callback",e).isNotMissing();for(const s of this.keys())e.call(t,this.get(s),s,this)}get(e){const t=this._getFieldExtensionFormat(e);return this._formatAttribute(e,t)}has(e){for(const t of this.keys())if(T(t,e))return!0;return!1}set(...e){throw new n(V)}*entries(){yield*I(this.keys(),(e=>[e,this.get(e)]))}*keys(){yield*this._feature.attributes.keys();for(const e of this._feature.schema.fields.expressionFields)yield e.name;if(null!=this._feature.source?.relationships)for(const e of this._feature.source.relationships)if("one-to-one"===e.cardinality||"many-to-one"===e.cardinality)for(const t of e.relatedSource.schema.fields)yield`relationships/${e.id}/${t.name}`}*values(){yield*I(this.keys(),(e=>this.get(e)))}[Symbol.iterator](){return this.entries()}toJSON(){return Array.from(this.entries())}on(e,t){if(d("callback",t).isNotMissing(),!this._numObservers){const e=new Map,t=new Set,s=()=>{for(const e of t)e.remove();t.clear()};let i;const r=()=>{const t=()=>{i&&(window.clearTimeout(i),i=void 0)};t(),i=window.setTimeout((()=>{const s=[],i=[];for(const[t,i]of this.entries())i!==e.get(t)&&s.push([t,i]);for(const[t,s]of e.entries())this.has(t)&&s===this.get(t)||i.push([t,s]);if(s.length||i.length){const e={added:s,removed:i,target:this};this.emit("change",e),a()}t()}))},a=()=>{e.clear(),s();for(const s of this.keys()){const i=this._getFieldExtension(s);let a="{0}";if(i){const e=i.watch("format",r);t.add(e),i.format&&(a=i.format)}e.set(s,this._formatAttribute(s,a))}};a();const n=this._feature.attributes.on("change",r),o=this._feature.schema.fieldExtensions.on("change",r),l=this._feature.settings.formatSettings.watch(["numberFormat","dateFormat","locale"],r),h=this._feature.expressionFieldValues.on("change",r),u=this._feature.schema.fields.on("change",(e=>{(e.added?.some((e=>v(e.name)))||e.removed?.some((e=>v(e.name))))&&r()})),p=this._feature.settings.watch("popupTemplate",r);this._onAllObserversRemoved=()=>{h.remove(),n.remove(),o.remove(),u.remove(),l.remove(),p.remove(),e.clear(),s()}}const s=super.on("change",t);return this._numObservers++,{remove:()=>{s.remove(),this._numObservers--,this._numObservers||this._onAllObserversRemoved()}}}watch(e,t){if("size"===e){const e=this._feature.attributes.watch("size",((e,s)=>{t(e+this._feature.schema.fields._expressionFieldsLength,s+this._feature.schema.fields._expressionFieldsLength,"size",this)})),s=this._feature.schema.fields.watch("_expressionFieldsLength",((e,s)=>{t(e+this._feature.attributes.size,s+this._feature.attributes.size,"size",this)}));return{remove:()=>{e.remove(),s.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 s=w(e);if(null!=s)return B(this._feature,"expression",s,{format:t});const[i,r]=F(e);return null!=i?B(this._feature,i,r,{format:t}):B(this._feature,void 0,e,{format:t})}}const G=/\{(?:relationships[\\/]([\w-]*)[\\/])?(?:(expression)[\\/])?([_a-zA-ZÀ-ÖØ-öø-ÿ][._a-zA-ZÀ-ÖØ-öø-ÿ0-9]*)(?::([^}]*))?\}/gi,L=/\{relationships\/([\w-]*)[\\/]([^}]*)\}/gi,Z=/{{/g,$="\0MAGIC\0",H=new RegExp($,"g"),K="#INVALID";class J extends u{_feature;_hyperlinks;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 Q(this._feature,e)),this._hyperlinks.get(e)}}let Q=class extends a{get url(){return this._template.url?this._feature.format(this._template.url):this._template.url}set url(e){throw new n(P)}get text(){return this._template.text?this._feature.format(this._template.text):this._template.text}set text(e){throw new n(P)}get iconUrl(){return this._template.iconUrl?this._feature.format(this._template.iconUrl):this._template.iconUrl}set iconUrl(e){throw new n(P)}get target(){return this._template.target?this._feature.format(this._template.target):this._template.target}set target(e){throw new n(P)}get tooltip(){return this._template.tooltip?this._feature.format(this._template.tooltip):this._template.tooltip}set tooltip(e){throw new n(P)}_feature;_template;constructor(e,t){super(t.toJSON()),this._feature=e,this._template=t}_watchProperty(e,t,s,i){const r=super._watchProperty(e,t,s,i),a=this._template.watch(e,(()=>{this.notifyChange(e)})),n=this._feature.presentableAttributes.on("change",(()=>{this.notifyChange(e)})),o=this._feature.relatedFeatures.on("change",(()=>{this.notifyChange(e)}));return{remove:()=>{r.remove(),a.remove(),n.remove(),o.remove()}}}_getSerializableProperties(){return{}}};function B(e,t,s,i={format:"{0}"}){if(!T(t,"expression")){if(t){const r=S(e.relatedFeatures.keys(),(e=>T(e.id,t)));if(!r)return M.debug("Could not resolve related field '{0}/{1}",t,s),K;const a=Array.from(e.relatedFeatures.get(r));return"many-to-one"===r.cardinality||"one-to-one"===r.cardinality?a.length<1?(M.debug("Could not resolve related field '{0}/{1}",t,s),K):W(a[0],s,i):a.map((e=>W(e,s,i))).filter((e=>""!==e)).join(",")}return W(e,s,i)}if(!e.settings.popupTemplate?.expressionInfos?.find((e=>T(e.name,s))))return M.debug("Could not find expression '{0}'.",s),K;try{const t=e.expressionFieldValues.get(s)??i.defaultExpressionValue??"",r=e.schema.findFieldByName(`expression/${s}`),a=null==r?void 0:e.schema.fieldExtensions.forField(r);return q(e,t,s,a?.formatSettings,i)}catch(e){if(e instanceof Error)return M.error({message:"Error evaluating expression '{0}': {1}.",error:e},s,e.message),K;throw e}}function W(e,t,s){let i=e.attributes.get(t);if(null==i)return"";const r=e.schema.findFieldByName(t),a=e.type?.domains?.[r?.name??t],n=e=>e.codedValues?.find((e=>e.code.toString()===i.toString()))?.name??i;let o;if(T(t,e.schema.typeIdField)){const t=a&&"inherited"!==a.type?a:r?.domain;i="coded-value"===t?.type?n(t):e.type?.name??i}else if(a&&b(a))i=n(a);else if(r?.domain&&b(r.domain))i=n(r.domain);else if(r){switch(r.type){case"integer":case"small-integer":case"single":case"double":i=A(i);break;case"date":i=y({timeZone:e.schema.timeZone},i);break;default:i=`${i.toString()}`}const t=e.schema.fieldExtensions.forField(r);t&&(o=t.formatSettings)}return q(e,i,t,o,s)}function q(e,t,s,i,r){if("string"==typeof t&&(null==r.format||"{0}"===r.format))return t;const a={...r};if("number"==typeof t||t instanceof Date){null==a.locale&&(a.locale=i?.locale??e.settings.formatSettings.locale);const r=e.settings.popupTemplate?.fieldInfos?.find((e=>T(e.fieldName,s)))?.format;"number"==typeof t?function(e,t,s,i){null==e.currency&&(e.currency=t?.currency??i.settings.formatSettings.currency);null==e.numberFormat&&(e.numberFormat=t?.numberFormat,null==e.numberFormat&&(e.numberFormat=null==s?i.settings.formatSettings.numberFormat:s.digitSeparator?E.NUMBER:E.FIXED_POINT));null==e.fractionalDigits&&(e.fractionalDigits=t?.fractionalDigits,null==e.fractionalDigits&&(e.fractionalDigits=null==s?i.settings.formatSettings.fractionalDigits:s.places))}(a,i,r,e):function(e,t,s,i){null==e.dateFormat&&(e.dateFormat=t?.dateFormat,null==e.dateFormat&&(e.dateFormat=null==s?i.settings.formatSettings.dateFormat:_(s.dateFormat)));null==e.timeZone&&(e.timeZone=t?.timeZone??i.settings.formatSettings.timeZone)}(a,i,r,e)}return k(a,t)}Q=e([l],Q);export async function resolveRelatedFeatures(e){const t=f(e,(e=>e.source));await Promise.all(m([...t.keys()].map((e=>e.relationships.toArray()))).map((e=>(async e=>{[...(await e.getAllRelatedFeatures(t.get(e.source))).entries()].forEach((([t,s])=>{t.relatedFeatures.set(e,s)}))})(e))))}
|
|
1
|
+
import{__decorate as e}from"tslib";import t from"@arcgis/core/Graphic";import s from"@arcgis/core/core/Collection";import{fromJSON as i}from"@arcgis/core/geometry/support/jsonUtils";import{EntityBase as r}from"../Entity.js";import{Hyperlink as a}from"../Hyperlink.js";import{InvalidOperationError as o}from"../InvalidOperationError.js";import{ItemType as n}from"../ItemType.js";import{serializable as l}from"../support/Serializable.js";import{CaseInsensitiveObservableMap as h}from"../utilities/CaseInsensitiveObservableMap.js";import{MapTransformCollection as u}from"../utilities/MapTransformCollection.js";import{ObservableMap as p}from"../utilities/ObservableMap.js";import{ReadOnlyMap as c}from"../utilities/ReadOnlyMap.js";import{Time as m}from"../utilities/Time.js";import{flatten as f,groupBy as d}from"../utilities/array.js";import{checkArg as g}from"../utilities/checkArg.js";import{compare as y}from"../utilities/collection.js";import{isCodedValueDomain as _,isGeometry as b}from"../utilities/esri.js";import{getArcadeExpressionFromField as x,getRelationshipFromField as F,isArcadeExpressionField as w}from"../utilities/field.js";import{parse as v,esriFormatToGeocortexFormat as I}from"../utilities/format/date.js";import{NumberFormat as S}from"../utilities/format/formats.js";import{parse as z}from"../utilities/format/number.js";import{format as A}from"../utilities/format/string.js";import{parse as E,esriFormatToGeocortexFormat as j}from"../utilities/format/time.js";import{map as T,find as k}from"../utilities/iterable.js";import{getLogger as R}from"../utilities/log.js";import{map as O}from"../utilities/promise.js";import{caseInsensitiveEquals as C}from"../utilities/string.js";import{onCollectionPropertyChange as M}from"../utilities/watch.js";import{FeatureSettings as N}from"./FeatureSettings.js";import{Schema as D}from"./Schema.js";const V=R("geocortex.api.data.Feature");export const SCORE_FIELD="_score";export const SCORE_FIELD_ORIGINAL="_score_original";let P=class extends r{attributes;get geometry(){return this._geometry}set geometry(e){this.notifyChange("geometryType"),this._geometry=b(e)||!e?e:i(e),this.schema.spatialReference=this._geometry?.spatialReference}settings;schema;attachments;expressionFieldValues;_itemType=n.FEATURE;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.schema.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),this.notifyChange("attachmentsInitialized"),this.notifyChange("relatedFeaturesInitialized")}get primaryKey(){const e=this.attributes.get(this.schema.primaryKeyField);return null!=e?`${e}`:void 0}get hasGlobalId(){return!!this.schema.fields.find((e=>"global-id"===e.type))}get globalId(){const e=this.schema.fields.find((e=>"global-id"===e.type));return e?this.attributes.get(e.name):void 0}set globalId(e){const t=this.schema.fields.find((e=>"global-id"===e.type));if(!t)throw new o("Cannot set global ID on feature -- no global ID field.");this.attributes.set(t.name,e)}get presentableAttributes(){return this._presentableAttributes=this._presentableAttributes||new Z(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 W(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 attachmentsInitialized(){return!this.source||this._attachmentsInitialized}get relatedFeaturesInitialized(){return!this.source||this.source.relationships.every((e=>this._initializedRelationships.has(e)))}get expressionsInitialized(){return!this.settings.popupTemplate?.expressionInfos?.length||this._expressionsInitialized}get _hydrationStatus(){return this._featureHydrationStatus?this._featureHydrationStatus:this.source?.capabilities?.supportsQuery&&1===this.attributes.size&&void 0!==this.primaryKey?"dehydrated":"hydrated"}set _hydrationStatus(e){this._featureHydrationStatus=e}get _key(){return`${this.source?.id}//${this.primaryKey??this.globalId??this.id}`}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(){if(this.settings.popupTemplate?.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""}_geometry;_source;_presentableAttributes;_hyperlinks;_featureHydrationStatus;_relatedFeatures;_expressionFieldValues=new p;_expressionValuesUpdatePending=!1;_attachmentsInitialized=!1;_expressionsInitialized=!1;_initializedRelationships=new WeakSet;constructor(e){super(e),this.settings=new N,this.settings._setFeature(this),this.schema=new D,this.schema._featureSettings=this.settings,this.attachments=new s,this.attributes=new h,this._relatedFeatures=new p,this.expressionFieldValues=new L(this._expressionFieldValues,this),M(this,"source.relationships",(()=>{this.notifyChange("relatedFeaturesInitialized")}),!0),this.settings.watch("popupTemplate",((e,t)=>{e!==t&&(this._expressionsInitialized=!1,this.notifyChange("expressionsInitialized"))}),!0)}format(e,...t){let s="string"==typeof e?{format:e}:e;g("options",s).isNotMissing();const{format:i}=s;g("format",i).isNotMissing();let r=s.format.replace(K,J);return r=r.replace($,((e,t,i,r,a)=>X(this,t||i,r,{...s,format:a?`{0:${a}}`:"{0}"}))),r=r.replace(Q,"{{"),s={...s},s.format=r,A(s,...t)}clearExpressionInfos(){this._expressionFieldValues.clear()}toGraphic(){return toGraphic(this)}async fetchExpressionInfos(e=!1){const{expressionInfos:t}=this.settings.popupTemplate??{};if(!t)return;const{runAsyncArcadeExpression:s}=await import("../utilities/arcade.js");if(await Promise.all(t.map((async e=>{try{const t=this.source?.layer??this.source?.sublayer;let i=this.source?.mapExtension;if(!i){const e=this.source?.layerExtension;i=e?.mapExtension}this._expressionFieldValues.set(e.name,await s(e.expression,{layer:t,map:i?.map,feature:this,spatialReference:this.schema.spatialReference}))}catch(t){t instanceof Error&&V.error({message:"Error evaluating expression '{0}': {1}.",error:t},e.name,t.message),this._expressionFieldValues.set(e.name,B)}}))),e)return this.attributes.on("change",(async e=>{this._expressionValuesUpdatePending||(this._expressionValuesUpdatePending=!0,setTimeout((async()=>{this._expressionValuesUpdatePending=!1,await this.fetchExpressionInfos()}),0))}));this._expressionsInitialized=!0,this.notifyChange("expressionsInitialized")}async fetchRelatedFeatures(e,t){if(!this.source)return;let s=[];if(e){const t=new Set(Array.isArray(e)?e:[e]);for(const e of t){const t="string"==typeof e?this.source.relationships.find((t=>t.id===e)):e;if(!t||!this.source.relationships.includes(t))throw new o("Relationship not found in feature source.");s.push(t)}}else s=this.source.relationships.toArray();const i=await O(s,(async e=>[e,await(async()=>{const s=await e.getRelatedFeatures(this,t);return this._initializedRelationships.add(e),s})()]));for(const e of i)this._relatedFeatures.set(e[0],e[1]);this.notifyChange("relatedFeaturesInitialized")}async fetchAttachments(){if(this.source){const e=await this.source.getAttachments(this);y(this.attachments,e,{equals:(e,t)=>e.id===t.id,onMissing:(e,t)=>this.attachments.remove(e),onNew:(e,t)=>{this.attachments.add(e)},onMatch:(e,t,s,i)=>{this.attachments.splice(s,1,t)}}),this._attachmentsInitialized=!0,this.notifyChange("attachmentsInitialized")}}async addAttachment(e){return this.source?.addAttachment(this,e)}async deleteAttachments(e){return this.source?.deleteAttachments(this,e)}_getSerializableProperties(){return{...super._getSerializableProperties(),attributes:{serializeModes:["project"],serialize:e=>{const t={};if("project"===e&&this.primaryKey&&(this.source?.capabilities).supportsQuery)t[this.schema.primaryKeyField]=this.primaryKey;else for(const[e,s]of this.attributes.entries())t[e]=s;return t},deserialize:e=>{if(this.attributes.clear(),e instanceof Map)e.forEach(((e,t)=>{this.attributes.set(t,e)}));else for(const[t,s]of Object.entries(e))this.attributes.set(t,s)}},geometry:{serializeModes:["project"],serialize:e=>"project"===e&&(this.source?.capabilities).supportsQuery?this.getDefault("geometry"):this.geometry?.toJSON(),deserialize:e=>{this.geometry=e}},settings:{serializeModes:["project"],serialize:e=>"project"===e&&(this.source?.capabilities).supportsQuery?this.getDefault("settings"):this.settings.toJSON(e)},schema:{serializeModes:["project"],serialize:e=>"project"===e&&(this.source?.capabilities).supportsQuery?this.getDefault("schema"):this.schema.toJSON(e)},source:["project"]}}_watchProperty(e,t,s,i){if("title"===e||"description"===e){const r=super._watchProperty(e,t,s,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(){r.remove(),o.remove(),n.remove()}}}return super._watchProperty(e,t,s,i)}async _onInitialize(){const e=this._findRelationshipIds(this._title,this._description),t=this.source?this.source.relationships.map((e=>e.id)).toArray():[],s=[];for(const i of e)t.includes(i)?s.push(this.fetchRelatedFeatures(i)):V.error("Could not find relationship '{0}' referenced in feature title or description.",i);await Promise.all(s)}_findRelationshipIds(...e){const t=[];for(const s of e){let e;const i=s.replace(K,J);for(;e=H.exec(i),null!==e;){const s=e[0];t.includes(s)||t.push(e[1])}}return t}};P=e([l],P);export{P as Feature};export function toFeature(e,t){const s=new P(t);if(e.attributes)for(const t of Object.keys(e.attributes))s.attributes.set(t,e.attributes[t]);return s.geometry=e.geometry,e.popupTemplate&&(s.settings.popupTemplate=e.popupTemplate),s}export function toGraphic(e){const s=new t;s.attributes={};for(const t of e.attributes.keys())s.attributes[t]=e.attributes.get(t);return e.source?.layer&&(s.layer=e.source?.layer),s.geometry=e.geometry,e.settings.popupTemplate&&(s.popupTemplate=e.settings.popupTemplate),s}const U="Presentable attributes are read-only.",G="Feature hyperlinks are read-only. Modify the feature's hyperlink templates instead.";class L extends c{_feature;_pending=new Set;constructor(e,t){super(e),this._feature=t}get(e){return super.has(e)||this._calcExpressionValue(e),super.get(e)}async _calcExpressionValue(e){if(!this._pending.has(e)){this._pending.add(e);try{const{spatialReference:t}=this._feature.schema,s=this._feature.settings.popupTemplate?.expressionInfos?.find((t=>t.name===e));if(!s)return;const{isArcadeScriptAsync:i,runAsyncArcadeExpression:r,arcadeScriptUsesGeometry:a,runArcadeExpression:o}=await import("../utilities/arcade.js");try{if(i(s.expression,t)){const i=this._feature.source?.layer??this._feature.source?.sublayer;let a=this._feature.source?.mapExtension;if(!a){const e=this._feature.source?.layerExtension;a=e?.mapExtension}this._originalMap.set(e,await r(s.expression,{feature:this._feature,layer:i,map:a?.map,spatialReference:t}))}else{if(a(s.expression,t)){const{enableGeometrySupport:e}=await import("@arcgis/core/arcade/arcade");await e()}this._originalMap.set(e,o(s.expression,{feature:this._feature,spatialReference:t}))}}catch(t){t instanceof Error&&V.error({message:"Error evaluating expression '{0}': {1}.",error:t},e,t.message),this._originalMap.set(e,B)}}finally{this._pending.delete(e)}}}}class Z extends c{[Symbol.toStringTag];get size(){return this._feature.attributes.size+this._feature.schema.fields._expressionFieldsLength}_feature;_numObservers;_onAllObserversRemoved;constructor(e){super(new h),this._feature=e}clear(){throw new o(U)}delete(e){throw new o(U)}forEach(e,t){g("callback",e).isNotMissing();for(const s of this.keys())e.call(t,this.get(s),s,this)}get(e){const t=this._getFieldExtensionFormat(e);return this._formatAttribute(e,t)}has(e){for(const t of this.keys())if(C(t,e))return!0;return!1}set(...e){throw new o(U)}*entries(){yield*T(this.keys(),(e=>[e,this.get(e)]))}*keys(){yield*this._feature.attributes.keys();for(const e of this._feature.schema.fields.expressionFields)yield e.name;if(null!=this._feature.source?.relationships)for(const e of this._feature.source.relationships)if("one-to-one"===e.cardinality||"many-to-one"===e.cardinality)for(const t of e.relatedSource.schema.fields)yield`relationships/${e.id}/${t.name}`}*values(){yield*T(this.keys(),(e=>this.get(e)))}[Symbol.iterator](){return this.entries()}toJSON(){return Array.from(this.entries())}on(e,t){if(g("callback",t).isNotMissing(),!this._numObservers){const e=new Map,t=new Set,s=()=>{for(const e of t)e.remove();t.clear()};let i;const r=()=>{const t=()=>{i&&(window.clearTimeout(i),i=void 0)};t(),i=window.setTimeout((()=>{const s=[],i=[];for(const[t,i]of this.entries())i!==e.get(t)&&s.push([t,i]);for(const[t,s]of e.entries())this.has(t)&&s===this.get(t)||i.push([t,s]);if(s.length||i.length){const e={added:s,removed:i,target:this};this.emit("change",e),a()}t()}))},a=()=>{e.clear(),s();for(const s of this.keys()){const i=this._getFieldExtension(s);let a="{0}";if(i){const e=i.watch("format",r);t.add(e),i.format&&(a=i.format)}e.set(s,this._formatAttribute(s,a))}};a();const o=this._feature.attributes.on("change",r),n=this._feature.schema.fieldExtensions.on("change",r),l=this._feature.settings.formatSettings.watch(["numberFormat","dateFormat","timeFormat","locale"],r),h=this._feature.expressionFieldValues.on("change",r),u=this._feature.schema.fields.on("change",(e=>{(e.added?.some((e=>w(e.name)))||e.removed?.some((e=>w(e.name))))&&r()})),p=this._feature.settings.watch("popupTemplate",r);this._onAllObserversRemoved=()=>{h.remove(),o.remove(),n.remove(),u.remove(),l.remove(),p.remove(),e.clear(),s()}}const s=super.on("change",t);return this._numObservers++,{remove:()=>{s.remove(),this._numObservers--,this._numObservers||this._onAllObserversRemoved()}}}watch(e,t){if("size"===e){const e=this._feature.attributes.watch("size",((e,s)=>{t(e+this._feature.schema.fields._expressionFieldsLength,s+this._feature.schema.fields._expressionFieldsLength,"size",this)})),s=this._feature.schema.fields.watch("_expressionFieldsLength",((e,s)=>{t(e+this._feature.attributes.size,s+this._feature.attributes.size,"size",this)}));return{remove:()=>{e.remove(),s.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 s=x(e);if(null!=s)return X(this._feature,"expression",s,{format:t});const[i,r]=F(e);return null!=i?X(this._feature,i,r,{format:t}):X(this._feature,void 0,e,{format:t})}}const $=/\{(?:relationships[\\/]([\w-]*)[\\/])?(?:(expression)[\\/])?([_a-zA-ZÀ-ÖØ-öø-ÿ][._a-zA-ZÀ-ÖØ-öø-ÿ0-9]*)(?::([^}]*))?\}/gi,H=/\{relationships\/([\w-]*)[\\/]([^}]*)\}/gi,K=/{{/g,J="\0MAGIC\0",Q=new RegExp(J,"g"),B="#INVALID";class W extends u{_feature;_hyperlinks;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 q(this._feature,e)),this._hyperlinks.get(e)}}let q=class extends a{get url(){return this._template.url?this._feature.format(this._template.url):this._template.url}set url(e){throw new o(G)}get text(){return this._template.text?this._feature.format(this._template.text):this._template.text}set text(e){throw new o(G)}get iconUrl(){return this._template.iconUrl?this._feature.format(this._template.iconUrl):this._template.iconUrl}set iconUrl(e){throw new o(G)}get target(){return this._template.target?this._feature.format(this._template.target):this._template.target}set target(e){throw new o(G)}get tooltip(){return this._template.tooltip?this._feature.format(this._template.tooltip):this._template.tooltip}set tooltip(e){throw new o(G)}_feature;_template;constructor(e,t){super(t.toJSON()),this._feature=e,this._template=t}_watchProperty(e,t,s,i){const r=super._watchProperty(e,t,s,i),a=this._template.watch(e,(()=>{this.notifyChange(e)})),o=this._feature.presentableAttributes.on("change",(()=>{this.notifyChange(e)})),n=this._feature.relatedFeatures.on("change",(()=>{this.notifyChange(e)}));return{remove:()=>{r.remove(),a.remove(),o.remove(),n.remove()}}}_getSerializableProperties(){return{}}};function X(e,t,s,i={format:"{0}"}){if(!C(t,"expression")){if(t){const r=k(e.relatedFeatures.keys(),(e=>C(e.id,t)));if(!r)return V.debug("Could not resolve related field '{0}/{1}",t,s),B;const a=Array.from(e.relatedFeatures.get(r));return"many-to-one"===r.cardinality||"one-to-one"===r.cardinality?a.length<1?(V.debug("Could not resolve related field '{0}/{1}",t,s),B):Y(a[0],s,i):a.map((e=>Y(e,s,i))).filter((e=>""!==e)).join(",")}return Y(e,s,i)}if(!e.settings.popupTemplate?.expressionInfos?.find((e=>C(e.name,s))))return V.debug("Could not find expression '{0}'.",s),B;try{const t=e.expressionFieldValues.get(s)??i.defaultExpressionValue??"",r=e.schema.findFieldByName(`expression/${s}`),a=null==r?void 0:e.schema.fieldExtensions.forField(r);return ee(e,t,s,a?.formatSettings,i)}catch(e){if(e instanceof Error)return V.error({message:"Error evaluating expression '{0}': {1}.",error:e},s,e.message),B;throw e}}function Y(e,t,s){let i;if(i=e.attributes.get(t),null==i)return"";const r=e.schema.findFieldByName(t),a=e.type?.domains?.[r?.name??t],o=e=>e.codedValues?.find((e=>e.code.toString()===i.toString()))?.name??i;let n;if(C(t,e.schema.typeIdField)){const t=a&&"inherited"!==a.type?a:r?.domain;i="coded-value"===t?.type?o(t):e.type?.name??i}else if(a&&_(a))i=o(a);else if(r?.domain&&_(r.domain))i=o(r.domain);else if(r){switch(r.type){case"integer":case"small-integer":case"big-integer":case"single":case"double":i=z(i);break;case"date":i=v({timeZone:e.schema.timeZone},i);break;case"timestamp-offset":case"date-only":i=v({},i),"date-only"===r.type&&(s.isDateOnly=!0);break;case"time-only":i=E(i);break;default:i=`${i.toString()}`}const t=e.schema.fieldExtensions.forField(r);t&&(n=t.formatSettings)}return ee(e,i,t,n,s)}function ee(e,t,s,i,r){if("string"==typeof t&&(null==r.format||"{0}"===r.format))return t;const a={...r};if("number"==typeof t||t instanceof Date||t instanceof m){null==a.locale&&(a.locale=i?.locale??e.settings.formatSettings.locale);const r=e.settings.popupTemplate?.fieldInfos?.find((e=>C(e.fieldName,s)))?.format;"number"==typeof t?function(e,t,s,i){null==e.currency&&(e.currency=t?.currency??i.settings.formatSettings.currency);null==e.numberFormat&&(e.numberFormat=t?.numberFormat,null==e.numberFormat&&(e.numberFormat=null==s?i.settings.formatSettings.numberFormat:s.digitSeparator?S.NUMBER:S.FIXED_POINT));null==e.fractionalDigits&&(e.fractionalDigits=t?.fractionalDigits,null==e.fractionalDigits&&(e.fractionalDigits=null==s?i.settings.formatSettings.fractionalDigits:s.places))}(a,i,r,e):t instanceof Date?function(e,t,s,i){null==e.dateFormat&&(e.dateFormat=t?.dateFormat,null==e.dateFormat&&(e.dateFormat=null==s?i.settings.formatSettings.dateFormat:I(s.dateFormat)));null==e.timeZone&&(e.timeZone=t?.timeZone??i.settings.formatSettings.timeZone)}(a,i,r,e):function(e,t,s,i){null==e.timeFormat&&(e.timeFormat=t?.timeFormat,null==e.timeFormat&&(e.timeFormat=null==s?i.settings.formatSettings.timeFormat:j(s.dateFormat)))}(a,i,r,e)}return A(a,t)}q=e([l],q);export async function resolveRelatedFeatures(e){const t=d(e,(e=>e.source));await Promise.all(f([...t.keys()].map((e=>e.relationships.toArray()))).map((e=>(async e=>{[...(await e.getAllRelatedFeatures(t.get(e.source))).entries()].forEach((([t,s])=>{t.relatedFeatures.set(e,s)}))})(e))))}
|
package/data/FeatureList.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__decorate as e}from"tslib";import t from"@arcgis/core/core/Collection.js";import i from"@arcgis/core/layers/support/Field";import{ArgumentError as r}from"../ArgumentError.js";import{generateId as s}from"../Entity.js";import{isFeatureSet as n,ItemType as o}from"../ItemType.js";import{assignProperties as a,assignPropertiesAsync as l,filterJSONProperties as c,getDefaults as u,getSerializableProperties as f,serializable as h}from"../support/Serializable.js";import{getSearchableValue as
|
|
1
|
+
import{__decorate as e}from"tslib";import t from"@arcgis/core/core/Collection.js";import i from"@arcgis/core/layers/support/Field";import{ArgumentError as r}from"../ArgumentError.js";import{generateId as s}from"../Entity.js";import{isFeatureSet as n,ItemType as o}from"../ItemType.js";import{assignProperties as a,assignPropertiesAsync as l,filterJSONProperties as c,getDefaults as u,getSerializableProperties as f,serializable as h}from"../support/Serializable.js";import{getSearchableValue as m}from"../tasks/search/_utilities.js";import{ReadOnlyCollection as d}from"../utilities/ReadOnlyCollection.js";import{isCodedValueDomain as g}from"../utilities/esri.js";import{parse as _}from"../utilities/format/date.js";import{parse as p}from"../utilities/format/number.js";import{parse as F}from"../utilities/format/time.js";import{escapeRegExp as S}from"../utilities/string.js";import{FeatureSet as y}from"./FeatureSet.js";let b=class extends d{id;title;featureSet;_sortFunc;_filterFunc;get itemType(){return o.FEATURE_LIST}constructor(e){if(super(new t),this.id=e?.id??s(),n(e))this.featureSet=e;else if(e){const t=e;Array.isArray(t.featureSet)?this.featureSet=new y({features:t.featureSet}):n(t.featureSet)?this.featureSet=t.featureSet:this.featureSet=new y(t.featureSet)}else this.featureSet=new y;for(const e of this.featureSet)this._collection.add(e);this.featureSet.on("change",(e=>this._onFeatureSetChange(e)))}toItemUri(){return`item://${encodeURIComponent(o.FEATURE_LIST)}/${encodeURIComponent(this.id)}`}assignProperties(e){a(this._getSerializableProperties(),this,e)}async assignPropertiesAsync(e){return l(this._getSerializableProperties(),this,e)}async finishAssignProperties(){}toJSON(e="all"){return c(this._getSerializableProperties(),this,e)}getDefaults(){return u(this._getSerializableProperties())}getDefault(e){return this.getDefaults()[e]}sort(e){if("function"==typeof e)this._sortFunc=e;else if(Array.isArray(e))this._sortFunc=this._createSortFunc(e);else if("object"==typeof e&&e.field)this._sortFunc=this._createSortFunc([e]);else{if("string"!=typeof e)throw new r("criteria","Invalid sort criteria.");this._sortFunc=this._createSortFunc([{field:e}])}return this._sortFunc=this._stabilizeSortFunc(this._sortFunc),this._sort(this._sortFunc),this.emit("change",{moved:this._collection.toArray(),target:this}),this}applyFilter(e){if(e)if("function"==typeof e)this._filterFunc=e;else if(Array.isArray(e))this._filterFunc=this._createFilterFunc(e);else if("object"==typeof e&&e.field)this._filterFunc=this._createFilterFunc([e]);else{if("string"!=typeof e)throw new r("criteria","Invalid filter criteria.");{const t=this.featureSet.schema.fieldExtensions.initializedItems.filter((e=>e.searchable)).map((t=>({field:t.field.name,match:e}))).toArray();this._filterFunc=this._createFilterFunc(t)}}else delete this._filterFunc;const t=new Set,i=[],s=[];let n=0;for(;n<this._collection.length;){const e=this._collection.getItemAt(n);this._filterFunc&&!this._filterFunc(e)?(i.push(e),this._collection.removeAt(n)):(t.add(e),n++)}for(const e of this.featureSet)t.has(e)||this._filterFunc&&!this._filterFunc(e)||(this._collection.add(e),s.push(e));this._sortFunc&&s.length&&(s.length<=10?this._insertionSort(this._sortFunc):this._sort(this._sortFunc)),(s.length||i.length)&&this.emit("change",{added:s,removed:i,target:this})}removeFilter(){this.applyFilter(void 0)}getSerializableProperties(e="all"){return f(this._getSerializableProperties(),e)}_getSerializableProperties(){return{title:["project"],featureSet:{serializeModes:["project"],deserialize:e=>{n(e)?this.featureSet.assignProperties({title:e.title,features:[...e]}):Array.isArray(e)?this.featureSet.assignProperties({features:e}):this.featureSet.assignProperties(e)}}}}_onFeatureSetChange(e){if(e.removed?.length&&this._collection.removeMany(e.removed),e.added?.length){const t=this._filterFunc?e.added.filter(this._filterFunc):e.added;t.length&&(this._collection.addMany(t),this._sortFunc&&(t.length<=10?this._insertionSort(this._sortFunc):this._sort(this._sortFunc)))}}_createSortFunc(e){return(t,i)=>{for(let s of e){if("string"==typeof s&&(s={field:s}),!s.field)throw new r("criteria","Invalid sort criteria.");const e=this._getField(s.field),n=this._getSortValue(t,e),o=this._getSortValue(i,e);let a="string"==typeof n?n.localeCompare(o):n-o;if("desc"===s.direction&&(a*=-1),0!==a)return a}return 0}}_stabilizeSortFunc(e){return(t,i)=>{const r=e(t,i);return 0===r?this._collection.indexOf(t)-this._collection.indexOf(i):r}}_createFilterFunc(e){const t=new Map;for(const i of e){if(!i.field)throw new r("criteria","Invalid sort criteria.");if(!i.match)continue;const e=this._getField(i.field),s=this._getFilterRegex(i.match,e);t.set(e.name,s)}return t.size?e=>{for(const i of t.keys()){const r=this._getField(i),s=m(e,r),n=t.get(i);let o=n[0];if(n.length>1&&"string"!==r.type&&g(e.type?.domains?.[r.name])&&(o=n[1]),o.exec(s))return!0}return!1}:()=>!0}_getSortValue(e,t){if(g(e.type?.domains?.[t.name])||g(t.domain))return e.presentableAttributes.get(t.name);switch(t.type){case"integer":case"small-integer":case"big-integer":case"double":case"single":case"oid":{const i=e.attributes.get(t.name);return null==i||isNaN(i)?Number.MIN_VALUE:p(i)}case"date":{const i=_(e.attributes.get(t.name)).getTime();return isNaN(i)?0:i}case"timestamp-offset":case"date-only":{const i=_({},e.attributes.get(t.name)).getTime();return isNaN(i)?0:i}case"time-only":{const i=F(e.attributes.get(t.name)).toDate().getTime();return isNaN(i)?0:i}default:return e.presentableAttributes.get(t.name)??""}}_getFilterRegex(e,t){if(t.domain&&"coded-value"===t.domain.type)return[new RegExp(`${S(e)}`,"i")];switch(t.type){case"integer":case"small-integer":case"big-integer":case"double":case"single":case"oid":{const i=new RegExp(`(^|${w})${S(e)}`,"i");return this.featureSet.schema.types.some((e=>g(e.domains?.[t.name])))?[i,new RegExp(`${S(e)}`,"i")]:[i]}default:return[new RegExp(`${S(e)}`,"i")]}}_getField(e){let t=this.featureSet.schema.findFieldByName(e);return t||(t=new i({name:e,type:this._inferFieldType(e),editable:!1}),this.featureSet.schema.fields.add(t)),t}_inferFieldType(e){for(const t of this.featureSet.values()){const i=t.attributes.get(e);if(null!=i)return"number"==typeof i?"double":i instanceof Date?"date":"string"}return"string"}_sort(e){this._collection._items.sort(e)}_insertionSort(e){const t=this._collection._items;for(let i=1;i<this.length;i++){const r=t[i];let s=i-1;for(;s>=0&&e(t[s],r)>0;)t[s+1]=t[s],s--;t[s+1]=r}}};b=e([h],b);export{b as FeatureList};const w="\t";
|
package/data/FeatureSaveError.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{format as r}from"../utilities/string.js";export class FeatureSaveError extends Error{errors;constructor(e,...o){super(e&&r(e,...o)||"One or more features could not be saved."),this.name="FeatureSaveError",this.errors=new Map}}
|
|
1
|
+
import{format as r}from"../utilities/format/string.js";export class FeatureSaveError extends Error{errors;constructor(e,...o){super(e&&r(e,...o)||"One or more features could not be saved."),this.name="FeatureSaveError",this.errors=new Map}}
|
package/data/FieldExtension.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e;import{__decorate as i}from"tslib";import t from"@arcgis/core/layers/support/Field";import{EntityBase as s}from"../Entity.js";import{InvalidOperationError as r}from"../InvalidOperationError.js";import{isFieldExtension as o,ItemType as f}from"../ItemType.js";import{FormatSettings as a}from"../support/FormatSettings.js";import{serializable as n}from"../support/Serializable.js";import{
|
|
1
|
+
var e;import{__decorate as i}from"tslib";import t from"@arcgis/core/layers/support/Field";import{EntityBase as s}from"../Entity.js";import{InvalidOperationError as r}from"../InvalidOperationError.js";import{isFieldExtension as o,ItemType as f}from"../ItemType.js";import{FormatSettings as a}from"../support/FormatSettings.js";import{serializable as n}from"../support/Serializable.js";import{isField as d}from"../utilities/esri.js";import{isArcadeExpressionField as l}from"../utilities/field.js";import{esriFormatToGeocortexFormat as h}from"../utilities/format/date.js";import{NumberFormat as m}from"../utilities/format/formats.js";import{esriFormatToGeocortexFormat as _}from"../utilities/format/time.js";import{deepClone as p}from"../utilities/object.js";import{caseInsensitiveEquals as F}from"../utilities/string.js";export const _fieldExtensionMap=new WeakMap;let c=e=class extends s{get field(){return this._field}get schema(){return this._schema}get fieldInfo(){if(this._fieldInfo)return this._fieldInfo;if(!this.field?.name)return;const e=this._schema?._featureSettings?.popupTemplate,i=e?.fieldInfos||[];return this._fieldInfo=i.find((e=>F(e.fieldName,this.field.name))),this._fieldInfo}format="{0}";formatSettings=new g(this);searchable=!0;_itemType=f.FIELD_EXTENSION;_field;_fieldInfo;_schema;_deferredFieldProperties;_originalRef;constructor(e){super(e);const{field:i}=e??{};d(i)?this._setField(i):"string"==typeof i?this._deferredFieldProperties={$ref:i}:i?i.$ref?this._deferredFieldProperties=i:this._setField(t.fromJSON(i)):this._setField(new t),this.watch("_schema.featureSource",(()=>this.notifyChange("fieldInfo"))),this.watch("_schema._featureSettings",(e=>{this.formatSettings.parent=e?e.formatSettings:void 0}),!0)}static matchesRef(e,i){return o(e)?F(e.field?.name??e._deferredFieldProperties?.$ref,i.$ref??i.name):F(e.name,i.$ref??i.name)}_switchField(e){e&&this._field!==e&&(this._field=e,_fieldExtensionMap.set(e,this))}_setSchema(e){this._schema=e,this._resolveField(),this.notifyChange("schema"),this.notifyChange("fieldInfo")}_resolveField(){if(this._field||!this._deferredFieldProperties||!this._schema)return;const i=this._schema.fields.find((i=>e.matchesRef(i,this._deferredFieldProperties)));i&&(this._setField(i),this.assignProperties({field:this._deferredFieldProperties}),this._originalRef=this._deferredFieldProperties.$ref,delete this._deferredFieldProperties,_fieldExtensionMap.set(i,this))}_getSerializableProperties(){return{...super._getSerializableProperties(),field:{serializeModes:["initial"],serialize:()=>this.field?this._originalRef?{$ref:this._originalRef}:this._schema?.fields.includes(this._field)&&this.field.name?{$ref:this.field.name}:this.field.toJSON():this._deferredFieldProperties?p(this._deferredFieldProperties):void 0,deserialize:e=>{if(d(e)&&e!==this.field)throw new Error("Property 'field' is read-only.")}},searchable:{serializeModes:["initial"],isDefault:e=>e!==l(this._field?.name)},format:{serializeModes:["initial"],default:"{0}"},formatSettings:"initial"}}async _onInitialize(){if(this._resolveField(),!this._field){const e=this._deferredFieldProperties.$ref;throw this._schema?new r(`Field not found with name: ${e}. Field does not exist.`):new r(`Field not found with name: ${e}. Field does not have a parent schema.`)}}_setField(e){this._field=e,l(this._field?.name)&&(this.searchable=!1),this.notifyChange("field"),this.notifyChange("fieldInfo")}};c=e=i([n],c);export{c as FieldExtension};let g=class extends a{fieldExtension;constructor(e,i){super(i),this.fieldExtension=e,e.watch("fieldInfo.format.places",(()=>this.notifyChange("fractionalDigits"))),e.watch("fieldInfo.format.digitSeparator",(()=>this.notifyChange("numberFormat"))),e.watch("fieldInfo.format.dateFormat",(()=>{this.notifyChange("dateFormat"),this.notifyChange("timeFormat")}))}get fractionalDigits(){const e=this.fieldExtension.fieldInfo?.format?.places;return!this.isModified("fractionalDigits")&&this.useFieldInfo&&e?e:this._getSetting("fractionalDigits")}set fractionalDigits(e){this._setSetting("fractionalDigits",e)}get numberFormat(){const e=this.fieldExtension.fieldInfo?.format?.digitSeparator;return!this.isModified("numberFormat")&&this.useFieldInfo&&e?e?m.NUMBER:m.FIXED_POINT:this._getSetting("numberFormat")}set numberFormat(e){this._setSetting("numberFormat",e)}get dateFormat(){const e=this.fieldExtension.fieldInfo?.format?.dateFormat;return!this.isModified("dateFormat")&&this.useFieldInfo&&e?h(e):this._getSetting("dateFormat")}set dateFormat(e){this._setSetting("dateFormat",e)}get timeFormat(){const e=this.fieldExtension.fieldInfo?.format?.dateFormat;return!this.isModified("timeFormat")&&this.useFieldInfo&&e&&"time-only"===this.fieldExtension.field.type?_(e):this._getSetting("timeFormat")}set timeFormat(e){this._setSetting("timeFormat",e)}};g=i([n],g);
|
package/data/Schema.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e;import{__decorate as i}from"tslib";import t from"@arcgis/core/PopupTemplate";import s from"@arcgis/core/core/Collection";import o from"@arcgis/core/layers/support/FeatureType";import l from"@arcgis/core/layers/support/Field";import n from"@arcgis/core/popup/FieldInfo";import{InvalidOperationError as r}from"../InvalidOperationError.js";import{isFieldExtension as d}from"../ItemType.js";import{jsonToGeometryType as a}from"../json/GeometryJson.js";import{InitializableCollectionProxy as h}from"../support/InitializableCollectionProxy.js";import{filterJSONProperties as p,isDefault as m,serializable as f,shouldExcludeDefaults as c}from"../support/Serializable.js";import{Settings as _}from"../support/Settings.js";import{CaseInsensitiveObservableMap as u}from"../utilities/CaseInsensitiveObservableMap.js";import{CollectionProxy as g}from"../utilities/CollectionProxy.js";import{checkArg as y}from"../utilities/checkArg.js";import{compare as F}from"../utilities/collection.js";import{isValidTimeZone as x,ERR_TIME_ZONE_INVALID as b}from"../utilities/date.js";import{isFeatureType as v,isField as T}from"../utilities/esri.js";import{fieldWithArcadeXRegex as S,fieldWithRelationshipRegex as I,getArcadeExpressionFromField as z}from"../utilities/field.js";import{objectKeys as w}from"../utilities/object.js";import{caseInsensitiveEquals as N}from"../utilities/string.js";import{onCollectionPropertyChange as E}from"../utilities/watch.js";import{_fieldExtensionMap as C,FieldExtension as j}from"./FieldExtension.js";const k=new Map;k.set("objectid","oid"),k.set("oid","oid"),k.set("fid","oid"),k.set("shape","geometry"),k.set("shape__length","double"),k.set("shape_length","double"),k.set("shape__area","double"),k.set("shape_area","double"),k.set("area","double"),k.set("perimeter","double"),k.set("length","double"),k.set("fnode_","double"),k.set("tnode_","double"),k.set("lpoly_","double"),k.set("rpoly_","double"),k.set("cover_","integer"),k.set("cover_id","integer"),k.set("idtic","integer"),k.set("xtic","double"),k.set("ytic","double"),k.set("xmin","double"),k.set("ymin","double"),k.set("xmax","double"),k.set("ymax","double"),k.set("arc_","double"),k.set("subclass_","integer"),k.set("subclass_id","integer"),k.set("routelink","integer"),k.set("arclink","integer"),k.set("f_meas","double"),k.set("t_meas","double"),k.set("f_pos","double"),k.set("t_pos","double"),k.set("f_meas","double"),k.set("globalid","global-id"),k.set("guid","guid");export{S as fieldWithArcadeXRegex,I as fieldWithRelationshipRegex};const M=new WeakMap;let A=e=class extends _{fieldExtensions;fields;get spatialReference(){return this._getSetting("spatialReference")}set spatialReference(e){this._setSetting("spatialReference",e)}get primaryKeyField(){const e=this._getSetting("primaryKeyField");if(!e){const e=this.fields.filter((e=>"oid"===e.type));if(1===e.length)return e.getItemAt(0).name}return e}set primaryKeyField(e){this._setSetting("primaryKeyField",e)}get displayField(){return this._getSetting("displayField",this.primaryKeyField)}set displayField(e){!this._featureSettings?.popupTemplate||this._featureSettings.popupTemplate.title&&this._featureSettings.popupTemplate.title!==`{${this.displayField}}`||(this._featureSettings.popupTemplate.title=`{${e}}`),this._setSetting("displayField",e)}get geometryType(){return this._getSetting("geometryType")}set geometryType(e){this._setSetting("geometryType",e)}get hasGeometry(){return void 0!==this.geometryType&&null!==this.geometryType}get timeZone(){return this._getSetting("timeZone","UTC")}set timeZone(e){y("timeZone",e).satisfies((e=>x(e)),b(e)),this._setSetting("timeZone",e)}get typeIdField(){return this._getSetting("typeIdField")}set typeIdField(e){this._setSetting("typeIdField",e)}get types(){return this._getCollectionSetting("types")}get _fields(){return this._getCollectionSetting("_fields")}_featureSettings;_alwaysSerializeFieldExtensions;constructor(e){super(e),this.fieldExtensions=new O(this),this.fields=new L(this)}static createFieldInfoFromField(e){let i=!0;const t=e.name.toLowerCase();return("oid"===e.type||"geometry"===e.type||k.has(t)&&k.get(t)===e.type)&&(i=!1),new n({visible:i,fieldName:e.name,format:void 0,label:e.alias,stringFieldOption:void 0,tooltip:void 0,isEditable:e.editable})}findFieldByName(e){return this.fields.findFieldByName(e)}toJSON(e="all"){const i=p(this._getSerializableProperties(),this,e)||{};let t=i.fieldExtensions;this.parent&&(t=t?.filter((e=>{const i=this.parent;return!i?.fieldExtensions?.some((i=>i.id===e.id))})));const{fields:s}=i;if(i)for(const e of w(i))this.isModified(e)||delete i[e];if(s&&(i.fields=s),t?.length&&(i.fieldExtensions=t),!c(e)||!m(i))return i}createPopupTemplate(){const e=this.createAllFieldInfos();return new t({fieldInfos:e,content:[{type:"fields"},{type:"attachments"}]})}createAllFieldInfos(){return this.fields.toArray().filter((e=>!!e.name)).map((i=>e.createFieldInfoFromField(i)))}_getSerializableProperties(){return{geometryType:{serialize:!1,deserialize:e=>{this.geometryType=e?a(e):void 0}},spatialReference:{serialize:!1},primaryKeyField:{serialize:!1},displayField:{serialize:!1},typeIdField:{serialize:!1},fields:{serializeModes:["initial"],serialize:()=>this.isModified("_fields")?this.fields.toArray().map((e=>e.toJSON())):void 0,deserialize:e=>{if(!e)return;const i=e.map((e=>T(e)?e:l.fromJSON(e)));F(this.fields,i,{onNew:(e,i)=>{this.fields.add(e,i)},onMatch:(e,i,t,s)=>{e!==i&&(e.alias=i.alias,e.editable=i.editable,e.length=i.length,e.nullable=i.nullable,e.type=i.type),t!==s&&this.fields.reorder(e,s)},onMissing:e=>{this.fields.remove(e)},equals:(e,i)=>N(e.name,i.name)})}},fieldExtensions:{serializeModes:["initial"],serialize:e=>this.fieldExtensions.toArray().map((i=>i.toJSON(e))).filter((e=>this._alwaysSerializeFieldExtensions||!(e&&2===Object.keys(e).length&&e.id&&e.field))),deserialize:e=>{e&&F(this.fieldExtensions,e,{onNew:(e,i)=>{this.fieldExtensions.add(d(e)?e:new j(e),i)},onMatch:(e,i,t,s)=>{d(i)||e.assignProperties(i),t!==s&&this.fieldExtensions.reorder(e,s)},onMissing:e=>{this._alwaysSerializeFieldExtensions&&this.fieldExtensions.remove(e)},equals:(e,i)=>d(i)?i===e:!(!i?.field||!j.matchesRef(e,i.field))||e.id===i.id})}},types:{serialize:!1,deserialize:e=>{if(!e)return;const i=e.map((e=>v(e)||!e?e:o.fromJSON(e)));F(this.types,i,{onNew:(e,i)=>{this.types.add(e,i)},onMatch:(e,i,t,s)=>{e!==i&&(e.name=i.name,e.templates=i.templates?[...i.templates]:[],e.domains=i.domains),t!==s&&this.types.reorder(e,s)},onMissing:e=>{this.types.remove(e)},equals:(e,i)=>e.id===i.id})}},timeZone:{serialize:!1,deserialize:e=>{e&&(this.timeZone=e)}}}}};A=e=i([f],A);export{A as Schema};class L extends g{_schema;_schemaFieldsHandle;_fieldNameToField;_backingCollection;_expressionFields;get _expressionFieldsLength(){return this.expressionFields.length}get expressionFields(){return null==this._expressionFields&&this._generateExpressionFields(),this._expressionFields}get _collection(){return null==this._backingCollection&&this._generateCollection(),this._backingCollection}get _popupTemplate(){return this._schema._featureSettings?this._schema._featureSettings.popupTemplate:void 0}constructor(e){super(),this._schema=e,E(this._schema,"_fields",(e=>{this.emit("change",e)})),e.watch("_fields.length",(()=>{this.notifyChange("length")})),e.watch(["_featureSettings.popupTemplate.fieldInfos","_featureSettings.popupTemplate.expressionInfos"],(()=>{this._resetLookups()}),!0),null!=e._fields&&(this._schemaFieldsHandle=e._fields.on("after-changes",(()=>{this._resetLookups()}))),e.watch("_fields",(e=>{this._schemaFieldsHandle?.remove(),this._schemaFieldsHandle=e?.on("after-changes",(()=>{this._resetLookups()})),this._resetLookups()}),!0)}clone(){return new L(this._schema)}add(e,i){y("field",e).isNotMissing(),this._backingCollection=void 0,this._fieldNameToField=void 0;const t=z(e.name);if(t){if(!this._popupTemplate)throw new r("Cannot create a field that references an arcade expression without a feature source and popup template.");const i=this._popupTemplate.expressionInfos.find((e=>N(e.name,t)));if(!i)throw new r("Cannot create a field that references a non-existent arcade expression.");this._popupTemplate.fieldInfos||(this._popupTemplate.fieldInfos=[]);let s=this._popupTemplate.fieldInfos.find((i=>N(i.fieldName,e.name)));s||(s=new n({fieldName:e.name,label:i.title}),this._popupTemplate.fieldInfos.push(s));const o=M.get(s);M.set(s,e),null!=this._expressionFields&&(this._expressionFields.remove(o),this._expressionFields.includes(e)||this._expressionFields.add(e));const l={added:[e],moved:[],removed:o?[o]:[],target:this};this.emit("change",l),this.notifyChange("length"),this.notifyChange("_expressionFieldsLength")}else this._schema._fields.add(e,i);return this}removeAt(e){y("index",e).isNotMissing();const i=this.getItemAt(e);if(!i)return;this._backingCollection=void 0,this._fieldNameToField=void 0;if(z(i.name)){const e=this._popupTemplate.fieldInfos.findIndex((e=>N(e.fieldName,i.name)));this._popupTemplate.fieldInfos.splice(e,1),this._expressionFields?.remove(i);const t={added:[],moved:[],removed:[i],target:this};this.emit("change",t),this.notifyChange("length"),this.notifyChange("_expressionFieldsLength")}else this._schema._fields.remove(i);return i}reorder(e,i){if(e&&this._schema._fields.includes(e))return this._backingCollection=void 0,this._schema._fields.reorder(e,i),e}sort(e){return this._backingCollection=void 0,this._schema._fields.sort(e),this}findFieldByName(e){return null==this._fieldNameToField&&this._generateNameLookup(),this._fieldNameToField.get(e)}_generateExpressionFields(){if(this._expressionFields=new s,this._popupTemplate?.fieldInfos&&this._popupTemplate?.expressionInfos)for(const e of this._popupTemplate.fieldInfos){const i=z(e.fieldName);if(null==i)continue;const t=this._popupTemplate.expressionInfos.find((e=>N(e.name,i)));if(null==t)continue;if(M.has(e)){this._expressionFields.add(M.get(e));continue}const s=new l({name:e.fieldName,alias:e.label||t.title||e.fieldName,type:"number"===t.returnType?"double":"string",editable:!1});M.set(e,s),this._expressionFields.add(M.get(e))}}_generateCollection(){this._backingCollection=this._schema._fields.concat(this.expressionFields)}_generateNameLookup(){const e=new u;for(const i of this._collection)e.set(i.name,i);this._fieldNameToField=e}_resetLookups(){this._backingCollection=void 0,this._expressionFields=void 0,this._fieldNameToField=void 0}}class O extends h{get _collection(){return this._schema.fields.map((e=>this._forField(e))).concat(Array.from(this._uninitializedFieldExtensions))}_schema;_uninitializedFieldExtensions=new Set;constructor(e){super(),this._schema=e,E(this._schema,"fields",(e=>{const i={added:(e.added||[]).map((e=>this._forField(e))),moved:(e.moved||[]).map((e=>this._forField(e))),removed:(e.removed||[]).map((e=>this._forField(e))),target:this};this.emit("change",i)})),e.watch("fields.length",(()=>this.notifyChange("length")))}forField(e){if(y("field",e).isNotMissing(),this._schema.fields.includes(e))return this._forField(e)}add(e,i){if(y("fieldX",e).isNotMissing(),e.schema&&e.schema.fieldExtensions.remove(e),e._setSchema(this._schema),e.field){const t=C.get(e.field);if(C.set(e.field,e),t&&t!==e&&this._onRemoved(t),this._schema.fields.includes(e.field))if(void 0===i){const i={added:[e],moved:[],removed:t?[t]:[],target:this};this.emit("change",i)}else this._schema.fields.reorder(e.field,i);else this._schema.fields.add(e.field,i)}else{this._uninitializedFieldExtensions.add(e);const i={added:[e],moved:[],removed:[],target:this};this.emit("change",i)}return this._onAdded(e),this}removeAt(e){const i=this.getItemAt(e);if(void 0!==i){if(this._uninitializedFieldExtensions.has(i)){this._uninitializedFieldExtensions.delete(i);const e={added:[],moved:[],removed:[i],target:this};this.emit("change",e)}else this._schema.fields.remove(i.field);return this._onRemoved(i),i}}reorder(e,i){if(e&&this._schema.fields.includes(e.field))return this._schema.fields.reorder(e.field,i),e}sort(e){return this._schema.fields.sort(((i,t)=>e(this._forField(i),this._forField(t)))),this}_itemIsInitialized(e){return super._itemIsInitialized(e)&&!!e.field}_onAdded(e){}_onRemoved(e){e.schema===this._schema&&e._setSchema(void 0)}_forField(e){if(this._uninitializedFieldExtensions.size)for(const e of this._uninitializedFieldExtensions)e._resolveField(),e.field&&(C.set(e.field,e),this._uninitializedFieldExtensions.delete(e));if(!C.has(e)){const i=new j({field:e});C.set(e,i),i._setSchema(this._schema),this._onAdded(i)}return C.get(e)}}
|
|
1
|
+
var e;import{__decorate as i}from"tslib";import t from"@arcgis/core/PopupTemplate";import s from"@arcgis/core/core/Collection";import o from"@arcgis/core/layers/support/FeatureType";import l from"@arcgis/core/layers/support/Field";import n from"@arcgis/core/popup/FieldInfo";import{InvalidOperationError as r}from"../InvalidOperationError.js";import{isFieldExtension as d}from"../ItemType.js";import{jsonToGeometryType as a}from"../json/GeometryJson.js";import{InitializableCollectionProxy as h}from"../support/InitializableCollectionProxy.js";import{filterJSONProperties as p,isDefault as m,serializable as f,shouldExcludeDefaults as c}from"../support/Serializable.js";import{Settings as _}from"../support/Settings.js";import{CaseInsensitiveObservableMap as u}from"../utilities/CaseInsensitiveObservableMap.js";import{CollectionProxy as g}from"../utilities/CollectionProxy.js";import{checkArg as y}from"../utilities/checkArg.js";import{compare as F}from"../utilities/collection.js";import{isFeatureType as x,isField as b}from"../utilities/esri.js";import{fieldWithArcadeXRegex as v,fieldWithRelationshipRegex as T,getArcadeExpressionFromField as S}from"../utilities/field.js";import{isValidTimeZone as I,ERR_TIME_ZONE_INVALID as z}from"../utilities/format/date.js";import{objectKeys as w}from"../utilities/object.js";import{caseInsensitiveEquals as N}from"../utilities/string.js";import{onCollectionPropertyChange as E}from"../utilities/watch.js";import{_fieldExtensionMap as C,FieldExtension as j}from"./FieldExtension.js";const k=new Map;k.set("objectid","oid"),k.set("oid","oid"),k.set("fid","oid"),k.set("shape","geometry"),k.set("shape__length","double"),k.set("shape_length","double"),k.set("shape__area","double"),k.set("shape_area","double"),k.set("area","double"),k.set("perimeter","double"),k.set("length","double"),k.set("fnode_","double"),k.set("tnode_","double"),k.set("lpoly_","double"),k.set("rpoly_","double"),k.set("cover_","integer"),k.set("cover_id","integer"),k.set("idtic","integer"),k.set("xtic","double"),k.set("ytic","double"),k.set("xmin","double"),k.set("ymin","double"),k.set("xmax","double"),k.set("ymax","double"),k.set("arc_","double"),k.set("subclass_","integer"),k.set("subclass_id","integer"),k.set("routelink","integer"),k.set("arclink","integer"),k.set("f_meas","double"),k.set("t_meas","double"),k.set("f_pos","double"),k.set("t_pos","double"),k.set("f_meas","double"),k.set("globalid","global-id"),k.set("guid","guid");export{v as fieldWithArcadeXRegex,T as fieldWithRelationshipRegex};const M=new WeakMap;let A=e=class extends _{fieldExtensions;fields;get spatialReference(){return this._getSetting("spatialReference")}set spatialReference(e){this._setSetting("spatialReference",e)}get primaryKeyField(){const e=this._getSetting("primaryKeyField");if(!e){const e=this.fields.filter((e=>"oid"===e.type));if(1===e.length)return e.getItemAt(0).name}return e}set primaryKeyField(e){this._setSetting("primaryKeyField",e)}get displayField(){return this._getSetting("displayField",this.primaryKeyField)}set displayField(e){!this._featureSettings?.popupTemplate||this._featureSettings.popupTemplate.title&&this._featureSettings.popupTemplate.title!==`{${this.displayField}}`||(this._featureSettings.popupTemplate.title=`{${e}}`),this._setSetting("displayField",e)}get geometryType(){return this._getSetting("geometryType")}set geometryType(e){this._setSetting("geometryType",e)}get hasGeometry(){return void 0!==this.geometryType&&null!==this.geometryType}get timeZone(){return this._getSetting("timeZone","UTC")}set timeZone(e){y("timeZone",e).satisfies((e=>I(e)),z(e)),this._setSetting("timeZone",e)}get typeIdField(){return this._getSetting("typeIdField")}set typeIdField(e){this._setSetting("typeIdField",e)}get types(){return this._getCollectionSetting("types")}get _fields(){return this._getCollectionSetting("_fields")}_featureSettings;_alwaysSerializeFieldExtensions;constructor(e){super(e),this.fieldExtensions=new O(this),this.fields=new L(this)}static createFieldInfoFromField(e){let i=!0;const t=e.name.toLowerCase();return("oid"===e.type||"geometry"===e.type||k.has(t)&&k.get(t)===e.type)&&(i=!1),new n({visible:i,fieldName:e.name,format:void 0,label:e.alias,stringFieldOption:void 0,tooltip:void 0,isEditable:e.editable})}findFieldByName(e){return this.fields.findFieldByName(e)}toJSON(e="all"){const i=p(this._getSerializableProperties(),this,e)||{};let t=i.fieldExtensions;this.parent&&(t=t?.filter((e=>{const i=this.parent;return!i?.fieldExtensions?.some((i=>i.id===e.id))})));const{fields:s}=i;if(i)for(const e of w(i))this.isModified(e)||delete i[e];if(s&&(i.fields=s),t?.length&&(i.fieldExtensions=t),!c(e)||!m(i))return i}createPopupTemplate(){const e=this.createAllFieldInfos();return new t({fieldInfos:e,content:[{type:"fields"},{type:"attachments"}]})}createAllFieldInfos(){return this.fields.toArray().filter((e=>!!e.name)).map((i=>e.createFieldInfoFromField(i)))}_getSerializableProperties(){return{geometryType:{serialize:!1,deserialize:e=>{this.geometryType=e?a(e):void 0}},spatialReference:{serialize:!1},primaryKeyField:{serialize:!1},displayField:{serialize:!1},typeIdField:{serialize:!1},fields:{serializeModes:["initial"],serialize:()=>this.isModified("_fields")?this.fields.toArray().map((e=>e.toJSON())):void 0,deserialize:e=>{if(!e)return;const i=e.map((e=>b(e)?e:l.fromJSON(e)));F(this.fields,i,{onNew:(e,i)=>{this.fields.add(e,i)},onMatch:(e,i,t,s)=>{e!==i&&(e.alias=i.alias,e.editable=i.editable,e.length=i.length,e.nullable=i.nullable,e.type=i.type),t!==s&&this.fields.reorder(e,s)},onMissing:e=>{this.fields.remove(e)},equals:(e,i)=>N(e.name,i.name)})}},fieldExtensions:{serializeModes:["initial"],serialize:e=>this.fieldExtensions.toArray().map((i=>i.toJSON(e))).filter((e=>this._alwaysSerializeFieldExtensions||!(e&&2===Object.keys(e).length&&e.id&&e.field))),deserialize:e=>{e&&F(this.fieldExtensions,e,{onNew:(e,i)=>{this.fieldExtensions.add(d(e)?e:new j(e),i)},onMatch:(e,i,t,s)=>{d(i)||e.assignProperties(i),t!==s&&this.fieldExtensions.reorder(e,s)},onMissing:e=>{this._alwaysSerializeFieldExtensions&&this.fieldExtensions.remove(e)},equals:(e,i)=>d(i)?i===e:!(!i?.field||!j.matchesRef(e,i.field))||e.id===i.id})}},types:{serialize:!1,deserialize:e=>{if(!e)return;const i=e.map((e=>x(e)||!e?e:o.fromJSON(e)));F(this.types,i,{onNew:(e,i)=>{this.types.add(e,i)},onMatch:(e,i,t,s)=>{e!==i&&(e.name=i.name,e.templates=i.templates?[...i.templates]:[],e.domains=i.domains),t!==s&&this.types.reorder(e,s)},onMissing:e=>{this.types.remove(e)},equals:(e,i)=>e.id===i.id})}},timeZone:{serialize:!1,deserialize:e=>{e&&(this.timeZone=e)}}}}};A=e=i([f],A);export{A as Schema};class L extends g{_schema;_schemaFieldsHandle;_fieldNameToField;_backingCollection;_expressionFields;get _expressionFieldsLength(){return this.expressionFields.length}get expressionFields(){return null==this._expressionFields&&this._generateExpressionFields(),this._expressionFields}get _collection(){return null==this._backingCollection&&this._generateCollection(),this._backingCollection}get _popupTemplate(){return this._schema._featureSettings?this._schema._featureSettings.popupTemplate:void 0}constructor(e){super(),this._schema=e,E(this._schema,"_fields",(e=>{this.emit("change",e)})),e.watch("_fields.length",(()=>{this.notifyChange("length")})),e.watch(["_featureSettings.popupTemplate.fieldInfos","_featureSettings.popupTemplate.expressionInfos"],(()=>{this._resetLookups()}),!0),null!=e._fields&&(this._schemaFieldsHandle=e._fields.on("after-changes",(()=>{this._resetLookups()}))),e.watch("_fields",(e=>{this._schemaFieldsHandle?.remove(),this._schemaFieldsHandle=e?.on("after-changes",(()=>{this._resetLookups()})),this._resetLookups()}),!0)}clone(){return new L(this._schema)}add(e,i){y("field",e).isNotMissing(),this._backingCollection=void 0,this._fieldNameToField=void 0;const t=S(e.name);if(t){if(!this._popupTemplate)throw new r("Cannot create a field that references an arcade expression without a feature source and popup template.");const i=this._popupTemplate.expressionInfos.find((e=>N(e.name,t)));if(!i)throw new r("Cannot create a field that references a non-existent arcade expression.");this._popupTemplate.fieldInfos||(this._popupTemplate.fieldInfos=[]);let s=this._popupTemplate.fieldInfos.find((i=>N(i.fieldName,e.name)));s||(s=new n({fieldName:e.name,label:i.title}),this._popupTemplate.fieldInfos.push(s));const o=M.get(s);M.set(s,e),null!=this._expressionFields&&(this._expressionFields.remove(o),this._expressionFields.includes(e)||this._expressionFields.add(e));const l={added:[e],moved:[],removed:o?[o]:[],target:this};this.emit("change",l),this.notifyChange("length"),this.notifyChange("_expressionFieldsLength")}else this._schema._fields.add(e,i);return this}removeAt(e){y("index",e).isNotMissing();const i=this.getItemAt(e);if(!i)return;this._backingCollection=void 0,this._fieldNameToField=void 0;if(S(i.name)){const e=this._popupTemplate.fieldInfos.findIndex((e=>N(e.fieldName,i.name)));this._popupTemplate.fieldInfos.splice(e,1),this._expressionFields?.remove(i);const t={added:[],moved:[],removed:[i],target:this};this.emit("change",t),this.notifyChange("length"),this.notifyChange("_expressionFieldsLength")}else this._schema._fields.remove(i);return i}reorder(e,i){if(e&&this._schema._fields.includes(e))return this._backingCollection=void 0,this._schema._fields.reorder(e,i),e}sort(e){return this._backingCollection=void 0,this._schema._fields.sort(e),this}findFieldByName(e){return null==this._fieldNameToField&&this._generateNameLookup(),this._fieldNameToField.get(e)}_generateExpressionFields(){if(this._expressionFields=new s,this._popupTemplate?.fieldInfos&&this._popupTemplate?.expressionInfos)for(const e of this._popupTemplate.fieldInfos){const i=S(e.fieldName);if(null==i)continue;const t=this._popupTemplate.expressionInfos.find((e=>N(e.name,i)));if(null==t)continue;if(M.has(e)){this._expressionFields.add(M.get(e));continue}const s=new l({name:e.fieldName,alias:e.label||t.title||e.fieldName,type:"number"===t.returnType?"double":"string",editable:!1});M.set(e,s),this._expressionFields.add(M.get(e))}}_generateCollection(){this._backingCollection=this._schema._fields.concat(this.expressionFields)}_generateNameLookup(){const e=new u;for(const i of this._collection)e.set(i.name,i);this._fieldNameToField=e}_resetLookups(){this._backingCollection=void 0,this._expressionFields=void 0,this._fieldNameToField=void 0}}class O extends h{get _collection(){return this._schema.fields.map((e=>this._forField(e))).concat(Array.from(this._uninitializedFieldExtensions))}_schema;_uninitializedFieldExtensions=new Set;constructor(e){super(),this._schema=e,E(this._schema,"fields",(e=>{const i={added:(e.added||[]).map((e=>this._forField(e))),moved:(e.moved||[]).map((e=>this._forField(e))),removed:(e.removed||[]).map((e=>this._forField(e))),target:this};this.emit("change",i)})),e.watch("fields.length",(()=>this.notifyChange("length")))}forField(e){if(y("field",e).isNotMissing(),this._schema.fields.includes(e))return this._forField(e)}add(e,i){if(y("fieldX",e).isNotMissing(),e.schema&&e.schema.fieldExtensions.remove(e),e._setSchema(this._schema),e.field){const t=C.get(e.field);if(C.set(e.field,e),t&&t!==e&&this._onRemoved(t),this._schema.fields.includes(e.field))if(void 0===i){const i={added:[e],moved:[],removed:t?[t]:[],target:this};this.emit("change",i)}else this._schema.fields.reorder(e.field,i);else this._schema.fields.add(e.field,i)}else{this._uninitializedFieldExtensions.add(e);const i={added:[e],moved:[],removed:[],target:this};this.emit("change",i)}return this._onAdded(e),this}removeAt(e){const i=this.getItemAt(e);if(void 0!==i){if(this._uninitializedFieldExtensions.has(i)){this._uninitializedFieldExtensions.delete(i);const e={added:[],moved:[],removed:[i],target:this};this.emit("change",e)}else this._schema.fields.remove(i.field);return this._onRemoved(i),i}}reorder(e,i){if(e&&this._schema.fields.includes(e.field))return this._schema.fields.reorder(e.field,i),e}sort(e){return this._schema.fields.sort(((i,t)=>e(this._forField(i),this._forField(t)))),this}_itemIsInitialized(e){return super._itemIsInitialized(e)&&!!e.field}_onAdded(e){}_onRemoved(e){e.schema===this._schema&&e._setSchema(void 0)}_forField(e){if(this._uninitializedFieldExtensions.size)for(const e of this._uninitializedFieldExtensions)e._resolveField(),e.field&&(C.set(e.field,e),this._uninitializedFieldExtensions.delete(e));if(!C.has(e)){const i=new j({field:e});C.set(e,i),i._setSchema(this._schema),this._onAdded(i)}return C.get(e)}}
|
package/data/convert.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import SpatialReference from "@arcgis/core/geometry/SpatialReference";
|
|
2
|
-
import { DateFormat } from "../utilities/
|
|
3
|
-
import { NumberFormat } from "../utilities/number.js";
|
|
2
|
+
import { DateFormat, NumberFormat, TimeFormat } from "../utilities/format/formats.js";
|
|
4
3
|
import { FeatureSet } from "./FeatureSet.js";
|
|
5
4
|
export declare const FIELD_NAME_REGEX: RegExp;
|
|
6
5
|
/**
|
|
@@ -229,6 +228,11 @@ interface ConversionFormatOptions {
|
|
|
229
228
|
* format string.
|
|
230
229
|
*/
|
|
231
230
|
dateFormat?: DateFormat | "timestamp" | string;
|
|
231
|
+
/**
|
|
232
|
+
* The format for time-only fields. The default is TimeFormat.ROUND_TRIP.
|
|
233
|
+
* This can be a defined TimeFormat string, or a custom format string.
|
|
234
|
+
*/
|
|
235
|
+
timeFormat?: TimeFormat | "timestamp" | string;
|
|
232
236
|
/**
|
|
233
237
|
* The format for numbers. The default is NumberFormat.ROUND_TRIP.
|
|
234
238
|
*/
|
package/data/convert.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"@arcgis/core/geometry/Point";import t from"@arcgis/core/geometry/SpatialReference";import{geometryTypeToJson as r}from"../json/GeometryJson.js";import{translate as o}from"../locale/language.js";import{INVARIANT as n}from"../locale.js";import{checkArg as a,assertNever as i}from"../utilities/checkArg.js";import{parse as s,format as c,DEFAULT_PARSING_FORMATS as m,DateFormat as l,INVALID_DATE as u}from"../utilities/date.js";import{isPoint as f,isMultipoint as d,isPolyline as p,isPolygon as y,isExtent as g}from"../utilities/esri.js";import{project as w,esriToWKT as h,wktToEsri as F,esriWkidToWkt as N,esriWktToWkid as S,esriToGeoJSON as O,geoJSONToEsri as T}from"../utilities/geometry.js";import{getLogger as R}from"../utilities/log.js";import{isNumeric as D,parse as G,format as b,NumberFormat as A}from"../utilities/number.js";import{caseInsensitiveEquals as E}from"../utilities/string.js";import{Feature as x}from"./Feature.js";import{FeatureSet as M}from"./FeatureSet.js";const I=["=","-","+","@"],_='"',v="\r\n",L="\n",P=[...m.map(pe),"M/d/yy"],C=/(\w+)_(point|multipoint|polyline|polygon)z?/;var U;function $(){return R("geocortex.api.data.convert")}!function(e){e.DATE="D",e.NUMBER="N",e.STRING="C",e.BOOLEAN="L"}(U||(U={}));export const FIELD_NAME_REGEX=/[^a-zA-Z\d_]/g;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 const geometryTypeHeaders={[GeometryFormat.XYZ]:[["x","y","z"]],[GeometryFormat.XY]:[["x","y"]],[GeometryFormat.LAT_LON]:[["latitude","longitude"],["lat","lon"],["lat","long"]],[GeometryFormat.ARCGIS_JSON]:[["geometry"]],[GeometryFormat.GEO_JSON]:[["geometry"]],[GeometryFormat.WKT]:[["geometry"]]};const j=[[GeometryFormat.ARCGIS_JSON,ne],[GeometryFormat.GEO_JSON,ae],[GeometryFormat.WKT,ie]],J=new Map(j);export async function uploadDataToFeatureSet(t){const n=await async function(t){const{data:r,includeHeaderRow:o,geometryFormat:n,geometryFields:a,locale:s,numberFormat:c,inSpatialReference:m}=t,l=o?r.slice(1):r;if(n===GeometryFormat.NONE)return{columnIndices:[]};const u=e=>me(e,s,c),f=(t,r)=>{const o=r===GeometryFormat.XYZ,n=r===GeometryFormat.LAT_LON;return{columnIndices:t,geometries:l.map((r=>{if(r.length>=Math.max(...t)&&D(r[t[0]]?.raw,s)&&D(r[t[1]]?.raw,s)&&(!o||D(r[t[2]]?.raw,s)))return new e({x:u(n?r[t[1]].raw:r[t[0]].raw),y:u(n?r[t[0]].raw:r[t[1]].raw),z:o?u(r[t[2]].raw):0,spatialReference:m})}))}},d=async(e,t)=>({columnIndices:[e],geometries:await Promise.all(l.map((t=>t[e])).map((e=>{if(e?.raw)return t(e.raw.toString(),m)})))}),p=async(e,t)=>{switch(t){case GeometryFormat.NONE:return{columnIndices:[0]};case GeometryFormat.LAT_LON:case GeometryFormat.XYZ:case GeometryFormat.XY:return f(e,t);case GeometryFormat.ARCGIS_JSON:return d(e[0],ne);case GeometryFormat.GEO_JSON:return d(e[0],ae);case GeometryFormat.WKT:return d(e[0],ie);default:return i(t,new Error(`Unknown geometry format "${t}".`))}};if(n){const e=se(o?r[0]:r[0].map(((e,t)=>({raw:t.toString()}))),n,o?a:a.map((e=>""+(parseInt(e.match(/\d+/g)[0])-1))));if(o&&void 0===e)throw new Error(`Error parsing file data: Expected geometry columns ${geometryTypeHeaders[n][0].join(",")} are missing for GeometryType.${n}`);return p(e??[0],n)}const[y,g]=await le(r,m,o);if(y===GeometryFormat.NONE)return{columnIndices:[]};return g.length>1?f(g,y):d(g[0],J.get(y))}(t),a=function(e,t){const{data:n,displayField:a,includeHeaderRow:i,inSpatialReference:s,outSpatialReference:c,generatePrimaryKey:m}=e,l={fields:[]},u=e=>!(!t.columnIndices||0===t.columnIndices.length)&&t.columnIndices.includes(e);let{primaryKeyField:f}=e,d=0;for(let t=0;t<n[0].length;t++){if(u(t))continue;const r=fe(e,t,!m&&!f&&!l.fields.find((e=>"esriFieldTypeOID"===e.type)));let a=n[0][t]?.raw?.toString(),s=a?.replace(FIELD_NAME_REGEX,"_");i&&s||(s="field"+ ++d,a=o("gcx.api.data.convert.import-field-alias",d)),l.fields.push({alias:a,name:s,type:r}),"esriFieldTypeOID"===r&&(f=s)}if(l.spatialReference=c??t.geometries?.[0]?.spatialReference??s,t.geometries?.length){const e=t.geometries.filter((e=>void 0!==e)).map((e=>e.type)),o=e[0];l.geometryType=e.every((e=>e===o))?r(o):void 0}if(!l.fields.find((e=>"esriFieldTypeOID"===e.type))){const e=l.fields.length+1,t=!!l.fields.find((e=>"objectid"===e.name.toLowerCase()));f=t?`OBJECTID_${e}`:"OBJECTID",l.fields.push({name:f,alias:f,type:"esriFieldTypeOID"})}return l.displayField=a??l.fields.find((e=>!E(e.name,f)&&"esriFieldTypeString"===e.type))?.name??l.fields.find((e=>!E(e.name,f)))?.name??f,l.primaryKeyField=f,l}(t,n),s=await async function(e,t,r){const{data:o,includeHeaderRow:n,outFields:a,escapeFormulaChars:i,locale:s,numberFormat:c,dateFormat:m}=e,{spatialReference:l}=r,u=[],f=n?o.slice(1):o,d=(e,r)=>!t.columnIndices||0===t.columnIndices.length||!t.columnIndices.includes(r);return await Promise.all(f.map((async(e,o)=>{const n=new x;for(let t=0;t<r.fields.length;t++){const l=r.fields[t],u=e.filter(d);if(a.includes("*")||a.filter((e=>E(e,l.name))).length>0){let e=await de(u[t]?.raw,l,{escapeFormulaChars:i,dateFormat:m,numberFormat:c,locale:s});"esriFieldTypeOID"===l.type&&null===e&&(e=o),n.attributes.set(l.name,e)}}t.geometries&&(n.geometry=await K(t.geometries[o],l)),u.push(n)}))),u}(t,n,a);return new M({features:s,schema:a})}export async function toCsv(e,r){a("featureSet",e).isNotMissing();const o=Array.from(e),n={...{useFormattedValues:!1,alwaysQuote:!1,escapeFormulaChars:!0,delimiter:",",dateFormat:l.ROUND_TRIP,geometryFormat:o.some((e=>void 0!==e.geometry&&null!==e.geometry))?GeometryFormat.WKT:GeometryFormat.NONE,includeByteOrderMark:!0,outSpatialReference:t.WGS84,includeHeaderRow:!0,outFields:B(e.source),rowDelimiter:navigator.platform.startsWith("Win")?v:L},...r},{includeByteOrderMark:i,includeHeaderRow:s,delimiter:c,outFields:m,rowDelimiter:u}=n,f=[];i&&f.push("\ufeff");const d=Y(o,n),p=k(o,m,e.schema,!0),y=k(o,m,e.schema,!1);if(s){const e=[];for(const t of d)e.push(V(t,n));for(const t of p)e.push(V(t,n));for(const t of y)e.push(V(t,n));const t=e.join(c)+u;f.push(t)}await Promise.all(o.map((async e=>{const t=[],r=(t,r)=>V(q(Q(e,t,r),r),r);t.push(...await async function(e,t){let r=await Z(e,t);t.geometryFormat!==GeometryFormat.XYZ&&t.geometryFormat!==GeometryFormat.XY&&t.geometryFormat!==GeometryFormat.LAT_LON||(r=r.map((e=>void 0===e?"":q(e,t))));return r.map((e=>""===e?"":V(e,t)))}(e.geometry,n)),t.push(...p.map((e=>r(e,n)))),t.push(...y.map((e=>r(e,n))));const o=`${t.join(c)}${u}`;f.push(o)})));return new Blob(f,{type:"text/plain",endings:u===L||u===v?"transparent":"native"})}export async function csvToUploadData(e,t){let r;if(a("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 i=z(t),s=i.rowDelimiter||function(e){let t=L;return oe(e,v,((r,o)=>(0===r&&o===e.length||(t=v),!1))),t}(r),c=i.delimiter??function(e,t,r){const o=",";if(0===e.length)return o;const a=[];if(oe(e,t,((t,r)=>(r!==e.length||t!==r)&&(a.push(e.substring(t,r)),a.length<3))),0===a.length)return o;let i=[{delimiter:",",rowsDelimiterOccurrences:[],rowsNumberAdjacentOccurrences:[]},{delimiter:";",rowsDelimiterOccurrences:[]},{delimiter:"|",rowsDelimiterOccurrences:[]},{delimiter:"\t",rowsDelimiterOccurrences:[]},{delimiter:" ",rowsDelimiterOccurrences:[]}].filter((e=>a[0].includes(e.delimiter)));if(0===i.length)return o;for(const e of a)for(const t of i){let o=0,n=0;oe(e,t.delimiter,((a,i)=>{if(i!==e.length&&o++,","===t.delimiter){const t=e.charAt(i-1),o=e.charAt(i+1);D(t,r)&&D(o,r)&&n++}return!0})),t.rowsDelimiterOccurrences.push(o),","===t.delimiter&&t.rowsNumberAdjacentOccurrences.push(n)}if(i=i.filter((e=>e.rowsDelimiterOccurrences.every((t=>e.rowsDelimiterOccurrences[0]===t)))).sort(((e,t)=>t.rowsDelimiterOccurrences[0]-e.rowsDelimiterOccurrences[0])),i.length>1&&","===i[0].delimiter&&null!=r&&r!==n){const e=i[0];if(null!=e&&","===e.delimiter&&","===Intl.NumberFormat(r).formatToParts(1.1).find((e=>"decimal"===e.type))?.value)for(let t=0;t<e.rowsDelimiterOccurrences.length;t++)if(e.rowsDelimiterOccurrences[t]<=e.rowsNumberAdjacentOccurrences[t]){i=i.filter((e=>","!==e.delimiter));break}}if(0===i.length)return o;return i[0].delimiter}(r,s,t.locale),m=function(e,t,r){const o=[],n=(e,t)=>{const o=[];return oe(e,r,((r,n)=>{const a=e.substring(r,n);return o.push({raw:re(a,t,o.length)}),!0})),o};if(oe(e,t,((t,r)=>{const a=e.substring(t,r);return a.length>0&&o.push(n(a,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}(r,s,c);let{geometryFormat:l,geometryFields:u}=t;if(!l){const[e,t]=await le(m,i.inSpatialReference,i.includeHeaderRow);l=e,u=t.map((e=>i.includeHeaderRow?m[0][e]?.raw??o("gcx.api.data.convert.import-field-alias",(e+1).toString()):o("gcx.api.data.convert.import-field-alias",(e+1).toString())))}return{data:m,...i,geometryFormat:l,geometryFields:u}}export async function csvToFeatureSet(e,t){const r=z(t);return uploadDataToFeatureSet(await csvToUploadData(e,r))}export async function toXLSX(e,r){a("featureSet",e).isNotMissing();const o=Array.from(e),n={...{useFormattedValues:!1,includeHeaderRow:!0,escapeFormulaChars:!0,geometryFormat:o.some((e=>void 0!==e.geometry&&null!==e.geometry))?GeometryFormat.WKT:GeometryFormat.NONE,outFields:B(e.source),outSpatialReference:t.WGS84,dateFormat:l.DEFAULT,numberFormat:A.DEFAULT,sheetName:"sheet1"},...r},{outFields:i,includeHeaderRow:s,dateFormat:c,numberFormat:m}=n,u=[],f=Y(o,n),d=k(o,i,e.schema,!0),p=k(o,i,e.schema,!1);if(s){const t=f.concat(d).concat(function(e,t){const r=t?.schema?.fieldExtensions.initializedItems.map((e=>e.field));return e.map((e=>r?.find((t=>E(t.name,e)))?.alias??e))}(p,e.source));u.push(t)}await Promise.all(o.map((async e=>{const t=[];t.push(...await Z(e.geometry,n));for(const r of d){const o=ge(e.attributes.get(r),n);t.push(o)}for(const r of p){const o=ge(Q(e,r,n),n);t.push(o)}t.every((e=>"string"!=typeof e||e.length<=32767))?u.push(t):$().warn(`toXLSX cell limit exceeded, feature (${e.primaryKey??e.id}) omitted.`)})));const y=await import("xlsx"),g={SheetNames:[],Sheets:{}},w=y.utils.aoa_to_sheet(u,{cellDates:!0});for(const e of Object.keys(w).filter((e=>!e.startsWith("!")))){const t=w[e];"d"===t.t?t.z=pe(c??l.ROUND_TRIP):"n"===t.t&&(t.z=ye(m))}g.SheetNames.push(n.sheetName),g.Sheets[n.sheetName]=w;const h=y.write(g,{type:"binary",bookType:"xlsx",compression:!0,bookSST:!0,cellDates:!0}),F=new Uint8Array(h.length);for(let e=0;e<h.length;e++)F[e]=h.charCodeAt(e);return new Blob([F.buffer],{type:"text/plain"})}export async function xlsxToUploadData(e,t){a("xlsxData",e).isNotMissing();const r=H(t),n=await async function(e,t){const r=await import("xlsx"),o=new Promise(((o,n)=>{const a=new FileReader;a.onload=()=>{const e=new Uint8Array(a.result);let n="";for(const t of e)n+=String.fromCharCode(t);const i=r.read(n,{type:"binary",cellDates:!0}),s=t.sheetName||i.SheetNames[0],c=i.Sheets[s];o(c)},a.onerror=()=>{n(a.error)},a.readAsArrayBuffer(e)})),n=await o,a=r.utils.decode_range(n["!ref"]),i=[];for(let e=a.s.r;e<=a.e.r;e++){const t=[];for(let o=a.s.c;o<=a.e.c;o++){const a=n[`${r.utils.encode_cell({r:e,c:o})}`];a&&"d"===a.t&&a.v instanceof Date&&(a.v=new Date(a.v.getTime()+6e4*a.v.getTimezoneOffset())),t.push(a?{raw:a.v,formatted:"s"===a.t?void 0:a.w}:{raw:""})}i.push(t)}return i}(e,r);let{geometryFormat:i,geometryFields:s}=t;if(!i){const[e,t]=await le(n,r.inSpatialReference,r.includeHeaderRow);i=e,s=t.map((e=>r.includeHeaderRow?n[0][e]?.raw.toString()??o("gcx.api.data.convert.import-field-alias",(e+1).toString()):o("gcx.api.data.convert.import-field-alias",(e+1).toString())))}return{data:n,...r,geometryFormat:i,geometryFields:s}}export async function xlsxToFeatureSet(e,t){a("xlsxData",e).isNotMissing();const r=H(t);return uploadDataToFeatureSet(await xlsxToUploadData(e,r))}export async function toShapefile(e,r){a("featureSet",e).isNotMissing();const[{default:o},n]=await Promise.all([import("jszip"),import("../forked-libs/shp-write/index.js")]),i=Array.from(e),s={...{useFormattedValues:!1,outFields:B(e.source),fileName:e.title||"export"},...r},{outFields:c,outSpatialReference:m,fileName:l}=s,u=e=>e.geometry.hasZ||e.geometry.hasM,w=new Map,h=i.filter((e=>f(e.geometry)));w.set("POINTZ",h.filter(u)),w.set("POINT",h.filter((e=>!u(e))));const F=i.filter((e=>d(e.geometry)));w.set("MULTIPOINTZ",F.filter(u)),w.set("MULTIPOINT",F.filter((e=>!u(e))));const S=i.filter((e=>p(e.geometry)));w.set("POLYLINEZ",S.filter(u)),w.set("POLYLINE",S.filter((e=>!u(e))));const O=i.filter((e=>y(e.geometry)||g(e.geometry)));w.set("POLYGONZ",O.filter(u)),w.set("POLYGON",O.filter((e=>!u(e))));const T=k(i,c,e.schema,!0);let R=k(i,c,e.schema,!1);R=T.concat(R);const D=new o,G=Array.from(w.keys()).filter((e=>w.get(e).length>0));await Promise.all(G.map((async r=>{const o=w.get(r),a=await Promise.all(o.map((e=>K(e.geometry,m)))),i=await async function(e){const{wkid:r,wkt:o}=e[0].spatialReference;if(!e.every((e=>e.spatialReference.wkid===r&&e.spatialReference.wkt===o)))throw new Error("Cannot create shapefile that contains geometries with different spatial references.");return o??await N(r??t.WGS84.wkid)}(a),c=s.useFormattedValues?Object.assign({},...R.map((e=>({[e]:U.STRING})))):function(e,t,r,o){const n={};for(const a of t){if(e.some((e=>ee(e,a)))){n[a]=U.STRING;continue}const t=r?r.fields.find((e=>E(e.name,a))):void 0;if(t){switch(t.type){case"oid":case"double":case"integer":case"single":case"small-integer":n[a]=U.NUMBER;break;case"date":n[a]=o?U.NUMBER:U.DATE;break;default:n[a]=U.STRING}continue}const i=(e,t)=>e.attributes.get(t)??e.presentableAttributes.get(t);e.every((e=>i(e,a)instanceof Date||void 0===i(e,a)))&&e.some((e=>i(e,a)instanceof Date))?n[a]=o?U.NUMBER:U.DATE:e.every((e=>"number"==typeof i(e,a)||void 0===i(e,a)))&&e.some((e=>"number"==typeof i(e,a)))?n[a]=U.NUMBER:e.every((e=>"boolean"==typeof i(e,a)||void 0===i(e,a)))&&e.some((e=>"boolean"==typeof i(e,a)))?n[a]=U.BOOLEAN:n[a]=U.STRING}return n}(o,R,e.schema,"timestamp"===s.dateFormat),u=function(e){return e.map((e=>{if(f(e)){const{x:t,y:r,z:o,m:n}=e,a=[t,r];return e.hasZ&&a.push(o),e.hasM&&a.push(n),we(a,e)}if(d(e))return he(e.points,e);if(p(e))return Fe(e.paths,e);if(y(e))return Fe(e.rings,e);if(g(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.")}))}(a),h=function(e,t,r,o){const n=[];for(const a of e){const e={};for(const n of t){let t=Q(a,n,o);if(null==t&&(t=""),o.useFormattedValues)t=t.toString();else{t=Ne(t,r[n],o)}e[n]=t}n.push(e)}return n}(o,R,c,s);n.write(h,r,u,((e,t)=>{const o=G.length>1?`${l}_${r.toLowerCase()}`:l;D.file(`${o}.shp`,t.shp.buffer,{binary:!0}),D.file(`${o}.shx`,t.shx.buffer,{binary:!0}),D.file(`${o}.dbf`,t.dbf.buffer,{binary:!0}),D.file(`${o}.prj`,i)}))})));const b=await D.generateAsync({type:"uint8array"});return new Blob([b.buffer],{type:"text/plain"})}export async function shapefileToUploadData(r,o){a("shapefileData",r).isNotMissing();const n=X(o),i=new Promise(((e,t)=>{const o=new FileReader;o.onload=()=>{e(o.result)},o.onerror=()=>{t(o.error)},o.readAsArrayBuffer(r)})),[{default:s},{default:c}]=await Promise.all([import("jszip"),import("shpjs")]),m=await i,l=await s.loadAsync(new Uint8Array(m)),u=l.filter((()=>!0)).map((e=>e.name));let d,p=u.filter((e=>e.endsWith(".shp"))).map((e=>e.substring(0,e.length-4)));if(p=function(e){if(!e.length)return[];let t=e[0];const r=t.match(C);return r?(t=r[1],e.filter((e=>{const r=e.match(C);return r&&r[1]===t}))):[t]}(p),u.some((e=>e.endsWith(".prj")))&&!p.every((e=>u.includes(`${e}.prj`))))throw new Error("Shapefile zip must contain the same prj file for each separate shapefile");await Promise.all(u.filter((e=>e.endsWith(".prj"))).map((async e=>{const t=await l.file(e).async("string");if(d){if(t!==d)throw new Error("Shapefile zip must contain the same prj file for each separate shapefile")}else d=t})));let y=[],g=[];for(const e of p){if(!u.includes(`${e}.shx`)||!u.includes(`${e}.dbf`))throw new Error("Shapefile must contain shp, shx, and dbf files.");const t=await l.file(`${e}.shp`).async("uint8array"),r=c.parseShp(t),o=await l.file(`${e}.dbf`).async("uint8array"),n=c.parseDbf(o);if(n.length!==r.length)throw new Error("Shapefile must contain shp, shx, and dbf files.");y=y.concat(n),g=g.concat(r)}const w=await Promise.all(g.map((r=>async function(r,o){const n=f(r)?function(r){a("geometry.coordinates",r.type).matches("Point"),a("geometry.coordinates",r.coordinates).satisfies((e=>"number"==typeof e||Array.isArray(e)));const[o,n,i]=r.coordinates,s=new e({x:o,y:n,spatialReference:t.WGS84});if(Array.isArray(i)){const[e,t]=i;!e&&!t||e?s.z=e:s.m=t}return s}(r):await T(r);if(o){let e;try{const r=await S(o);e=new t({wkid:G(r)})}catch{}e||(e=new t({wkt:o})),n.spatialReference=e}return n}(r,d)))),h=geometryTypeHeaders[GeometryFormat.ARCGIS_JSON][0][0];y.forEach(((e,t)=>e[h]=JSON.stringify(w[t].toJSON())));return{data:function(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]})))))]}(y),...n,includeHeaderRow:!0,geometryFormat:GeometryFormat.ARCGIS_JSON,geometryFields:[h],inSpatialReference:w[0]?.spatialReference??t.fromJSON({wkid:4326})}}export async function shapefileToFeatureSet(e,t){a("shapefileData",e).isNotMissing();const r=X(t);return uploadDataToFeatureSet(await shapefileToUploadData(e,r))}function W(e){return{escapeFormulaChars:!0,outFields:["*"],generatePrimaryKey:!1,locale:n,detectOid:!e?.primaryKeyField}}function z(e){return{...{includeHeaderRow:!0,inSpatialReference:t.WGS84,...W(e)},...e}}function H(e){return{...{includeHeaderRow:!0,inSpatialReference:t.WGS84,...W(e)},...e}}function X(e){return{...{...W(e)},...e}}function Y(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 k(e,t,r,o){const n=r.fields.filter((e=>"oid"===e.type)).map((e=>e.name)).toArray();if(o)return n;if(t&&!t.includes("*"))return t.filter((e=>!n.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)||n.includes(e)||o.includes(e)||o.push(e);return o=o.sort(),t.concat(o)}}function B(e){if(!e)return["*"];const t=e.featureSettings.popupTemplate?.content;return(Array.isArray(t)?t.find((e=>"fields"===e.type))?.fieldInfos?.filter((e=>e.visible))?.map((e=>e.fieldName)):void 0)??e.featureSettings.popupTemplate?.fieldInfos?.filter((e=>e.visible))?.map((e=>e.fieldName))??["*"]}async function Z(e,t){const r=await K(e,t.outSpatialReference);if(t.geometryFormat===GeometryFormat.XYZ){if(!r)return["","",""];if(!f(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(!f(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(!f(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(r.toJSON())]:[""]:t.geometryFormat===GeometryFormat.WKT?r?[await h(r)]:[""]:t.geometryFormat===GeometryFormat.GEO_JSON?r?[JSON.stringify(await O(r))]:[""]:[]}async function K(e,t){return e?.spatialReference&&!e.spatialReference.equals(t)&&t?(await w([e],t))[0]:e}function V(e,t){const r=[t.delimiter,_,"\r","\n",t.rowDelimiter];if(t.alwaysQuote||r.some((t=>e.includes(t)))){const t=e.replace(new RegExp(_,"g"),`${_}${_}`);return`${_}${t}${_}`}return e}function q(e,t){if(null==e)return"";if(!t.useFormattedValues){if("number"==typeof e){const r=t.numberFormat||A.ROUND_TRIP;return b(r,e)}if(e instanceof Date)return"timestamp"===t.dateFormat?e.getTime().toString():c({format:t.dateFormat,timeZone:"UTC"},e)}let r=e.toString();return t.escapeFormulaChars&&(r=te(r)),r}function Q(e,t,r){if(r.useFormattedValues||ee(e,t))return e.presentableAttributes.get(t)??e.attributes.get(t);if("date"===e.schema.findFieldByName(t)?.type){const r=s(e.attributes.get(t));if(!isNaN(r.getTime()))return r}return e.attributes.get(t)??e.presentableAttributes.get(t)}function ee(e,t){return!!E(t,e.schema.typeIdField)||("coded-value"===e.type?.domains?.[t]?.type||"coded-value"===e.schema.findFieldByName(t)?.domain?.type)}function te(e){for(const t of I)if(e.startsWith(t))return`\t${e}`;return e}function re(e,t,r){const o=e.startsWith(_),n=e.endsWith(_);if(o&&!n||!o&&n)throw new Error(`Detected invalid CSV: Missing opening or closing quote for value at row:${t} column:${r}`);const a=o?e.substring(_.length,e.length-_.length):e;let i=-1;return oe(a,_,((e,o)=>{if(o===a.length)return!0;if(i<0){if(o!==a.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}`)})),a.replace(new RegExp(`${_}${_}`,"g"),_)}function oe(e,t,r){let o,n=!1,a=0,i=0;for(;o=e.indexOf(t,a),!(o<0);){for(let t=a;t<o;)e.substring(t).startsWith(_)?(n=!n,t+=_.length):t++;const s=o+t.length;if(!n){const e=r(i,o);if(i=s,!e)return}a=s}r(i,e.length)}async function ne(e,t){const r=JSON.parse(e),o=(await import("@arcgis/core/geometry/support/jsonUtils")).fromJSON(r);return r.spatialReference||(o.spatialReference=t),o}async function ae(e,t){const r=await T(JSON.parse(e));return r.spatialReference=t,r}async function ie(e,t){const r=await F(e);return r.spatialReference=t,r}function se(e,t,r){const o=r?[r]:geometryTypeHeaders[t];for(const t of o){const r=t.map((t=>e.map((e=>e?.raw?.toString().trim().toLowerCase())).indexOf(t.trim().toLowerCase())));if(r.every((e=>e>=0)))return r}}async function ce(e,t){return(await Promise.all(e.map((async(e,r)=>{const o=e?.raw;if("string"==typeof o&&""!==o)try{return await t(o,void 0),r}catch{return}})))).find((e=>void 0!==e))}function me(e,t,r){return"inv"===t?"string"==typeof e?parseFloat(e.replaceAll(",","")):e:G({locale:t,format:r},e)}async function le(e,t,r){const o=r?e.slice(1):e;if(r){const r=se(e[0],GeometryFormat.ARCGIS_JSON);if(void 0!==r)for(const[e,n]of j){try{await ue(r[0],n,t,o)}catch(e){continue}return[e,[r[0]]]}const n=[GeometryFormat.XYZ,GeometryFormat.XY,GeometryFormat.LAT_LON];for(const t of n){const r=se(e[0],t);if(void 0!==r)return[t,r]}}for(const[e,r]of j){const n=await ce(o[0],r);if(void 0!==n){try{await ue(n,r,t,o)}catch(e){continue}return[e,[n]]}}return[GeometryFormat.NONE,[]]}async function ue(e,t,r,o){return{columnIndices:[e],geometries:await Promise.all(o.map((t=>t[e])).map((e=>{if(e?.raw)return t(e.raw.toString(),r)})))}}function fe(e,t,r){let o=!1,n=!0,a=!0,i=!0;const c=new Set,{data:l,includeHeaderRow:f,dateFormat:d,primaryKeyField:p,locale:y}=e,g=f?l[0]:[],w=f?l.slice(1):l;for(const e of w){const r=e[t];r?.raw&&(c.add(r.raw),o=!0,n&&(n=D(r.raw,y)||Number.isNaN(r.raw)),a&&(a=r.raw instanceof Date||s(d||m,r.raw)!==u),i&&(i=s(d||P,r.formatted)!==u))}const h=c.size===w.length;return p&&g[t]?.raw===p||r&&o&&h&&n?"esriFieldTypeOID":o&&i?"esriFieldTypeDate":o&&n?"esriFieldTypeDouble":o&&a?"esriFieldTypeDate":"esriFieldTypeString"}async function de(e,t,r){const{escapeFormulaChars:o,locale:n,numberFormat:a,dateFormat:i}=r;if("esriFieldTypeDouble"===t.type||"esriFieldTypeOID"===t.type)return"number"==typeof e?e:e?me(e,n,a):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:s({locale:n,format:i},e).getTime()}const c=e?.toString()??"";if(o&&c.startsWith("\t"))for(const e of I)if(c.length>1&&c.charAt(1)===e)return c.substring(1);return c}function pe(e){switch(e){case l.DATE_SHORT:return"dd/MM/yyyy";case l.DATE_LONG:return"MMMM d, yyyy";case l.TIME_SHORT:return"h:mm AM/PM";case l.TIME_LONG:return"h:mm:ss AM/PM";case l.DATE_TIME_SHORT:case l.DEFAULT:return"MMM d yyyy h:mm AM/PM";case l.DATE_TIME_LONG:return"MMMM d yyyy h:mm AM/PM";case l.FULL:return"dddd, MMMM d yyyy h:mm AM/PM";case l.ISO_8601:case l.ROUND_TRIP:return'yyyy-MM-dd"T"HH:mm:ss';default:{const t=e.replace(/tt/g,"AM/PM");return t.includes("z")&&$().warn("Warning: Excel will not recognize timezone format 'z', 'zz', or 'zzz'"),t.includes("h")&&!t.includes("AM/PM")&&$().warn("Warning: Excel will interpret 'h' as 'H' if the format does not have an AM/PM designator"),t}}}function ye(e){switch(e){case A.ACCOUNTING:return'_("$"* #,##0.00_);_("$"* (#,##0.00);_("$"* "-"??_);_(@_)';case A.CURRENCY:return'"$"#,##0.00';case A.FIXED_POINT:case A.DEFAULT:return"0.0000";case A.NUMBER:return"#,##0.0000";case A.PERCENT:return"0%";case A.ROUND_TRIP:return"0.00000";default:return e}}function ge(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=te(r)),r}function we(e,t){return 3===e.length&&!t.hasZ&&t.hasM?[e[0],e[1],void 0,e[2]]:e}function he(e,t){return e.map((e=>we(e,t)))}function Fe(e,t){return e.map((e=>he(e,t)))}function Ne(e,t,r){switch(t){case U.NUMBER:return e instanceof Date?e.getTime():G(e);case U.STRING:return e instanceof Date?c({format:r.dateFormat??l.ROUND_TRIP,timeZone:"UTC"},e):"number"==typeof e?b(r.numberFormat??A.DEFAULT,e):e.toString();case U.BOOLEAN:return!!e;case U.DATE:return s(e);default:return e.toString()}}
|
|
1
|
+
import e from"@arcgis/core/geometry/Point";import t from"@arcgis/core/geometry/SpatialReference";import{geometryTypeToJson as r}from"../json/GeometryJson.js";import{translate as a}from"../locale/language.js";import{INVARIANT as n}from"../locale.js";import{Time as o}from"../utilities/Time.js";import{checkArg as i,assertNever as s}from"../utilities/checkArg.js";import{isPoint as c,isMultipoint as m,isPolyline as l,isPolygon as u,isExtent as f}from"../utilities/esri.js";import{parse as d,format as y,DEFAULT_PARSING_FORMATS as p,INVALID_DATE as g}from"../utilities/format/date.js";import{DateFormat as h,NumberFormat as w,TimeFormat as F}from"../utilities/format/formats.js";import{parse as S,format as T}from"../utilities/format/number.js";import{parse as N,format as O,DEFAULT_PARSING_FORMATS as R}from"../utilities/format/time.js";import{project as D,esriToWKT as M,wktToEsri as A,esriWkidToWkt as E,esriWktToWkid as G,esriToGeoJSON as _,geoJSONToEsri as b}from"../utilities/geometry.js";import{getLogger as x}from"../utilities/log.js";import{isNumeric as I}from"../utilities/number.js";import{caseInsensitiveEquals as v}from"../utilities/string.js";import{Feature as L}from"./Feature.js";import{FeatureSet as P}from"./FeatureSet.js";const U=["=","-","+","@"],C='"',$="\r\n",j="\n",H=[...p.map(Se),"M/d/yy"],z=[...R.map(Ne).map((e=>e.replace("AM/PM","tt")))],J=/(\w+)_(point|multipoint|polyline|polygon)z?/;var W;function B(){return x("geocortex.api.data.convert")}!function(e){e.DATE="D",e.NUMBER="N",e.STRING="C",e.BOOLEAN="L"}(W||(W={}));export const FIELD_NAME_REGEX=/[^a-zA-Z\d_]/g;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 const geometryTypeHeaders={[GeometryFormat.XYZ]:[["x","y","z"]],[GeometryFormat.XY]:[["x","y"]],[GeometryFormat.LAT_LON]:[["latitude","longitude"],["lat","lon"],["lat","long"]],[GeometryFormat.ARCGIS_JSON]:[["geometry"]],[GeometryFormat.GEO_JSON]:[["geometry"]],[GeometryFormat.WKT]:[["geometry"]]};const X=[[GeometryFormat.ARCGIS_JSON,le],[GeometryFormat.GEO_JSON,ue],[GeometryFormat.WKT,fe]],Y=new Map(X);export async function uploadDataToFeatureSet(t){const n=await async function(t){const{data:r,includeHeaderRow:a,geometryFormat:n,geometryFields:o,locale:i,numberFormat:c,inSpatialReference:m}=t,l=a?r.slice(1):r;if(n===GeometryFormat.NONE)return{columnIndices:[]};const u=e=>pe(e,i,c),f=(t,r)=>{const a=r===GeometryFormat.XYZ,n=r===GeometryFormat.LAT_LON;return{columnIndices:t,geometries:l.map((r=>{if(r.length>=Math.max(...t)&&I(r[t[0]]?.raw,i)&&I(r[t[1]]?.raw,i)&&(!a||I(r[t[2]]?.raw,i)))return new e({x:u(n?r[t[1]].raw:r[t[0]].raw),y:u(n?r[t[0]].raw:r[t[1]].raw),z:a?u(r[t[2]].raw):0,spatialReference:m})}))}},d=async(e,t)=>({columnIndices:[e],geometries:await Promise.all(l.map((t=>t[e])).map((e=>{if(e?.raw)return t(e.raw.toString(),m)})))}),y=async(e,t)=>{switch(t){case GeometryFormat.NONE:return{columnIndices:[0]};case GeometryFormat.LAT_LON:case GeometryFormat.XYZ:case GeometryFormat.XY:return f(e,t);case GeometryFormat.ARCGIS_JSON:return d(e[0],le);case GeometryFormat.GEO_JSON:return d(e[0],ue);case GeometryFormat.WKT:return d(e[0],fe);default:return s(t,new Error(`Unknown geometry format "${t}".`))}};if(n){const e=de(a?r[0]:r[0].map(((e,t)=>({raw:t.toString()}))),n,a?o:o.map((e=>""+(parseInt(e.match(/\d+/g)[0])-1))));if(a&&void 0===e)throw new Error(`Error parsing file data: Expected geometry columns ${geometryTypeHeaders[n][0].join(",")} are missing for GeometryType.${n}`);return y(e??[0],n)}const[p,g]=await ge(r,m,a);if(p===GeometryFormat.NONE)return{columnIndices:[]};return g.length>1?f(g,p):d(g[0],Y.get(p))}(t),o=function(e,t){const{data:n,displayField:o,includeHeaderRow:i,inSpatialReference:s,outSpatialReference:c,generatePrimaryKey:m}=e,l={fields:[]},u=e=>!(!t.columnIndices||0===t.columnIndices.length)&&t.columnIndices.includes(e);let{primaryKeyField:f}=e,d=0;for(let t=0;t<n[0].length;t++){if(u(t))continue;const r=we(e,t,!m&&!f&&!l.fields.find((e=>"esriFieldTypeOID"===e.type)));let o=n[0][t]?.raw?.toString(),s=o?.replace(FIELD_NAME_REGEX,"_");i&&s||(s="field"+ ++d,o=a("gcx.api.data.convert.import-field-alias",d)),l.fields.push({alias:o,name:s,type:r}),"esriFieldTypeOID"===r&&(f=s)}if(l.spatialReference=c??t.geometries?.[0]?.spatialReference??s,t.geometries?.length){const e=t.geometries.filter((e=>void 0!==e)).map((e=>e.type)),a=e[0];l.geometryType=e.every((e=>e===a))?r(a):void 0}if(!l.fields.find((e=>"esriFieldTypeOID"===e.type))){const e=l.fields.length+1,t=!!l.fields.find((e=>"objectid"===e.name.toLowerCase()));f=t?`OBJECTID_${e}`:"OBJECTID",l.fields.push({name:f,alias:f,type:"esriFieldTypeOID"})}return l.displayField=o??l.fields.find((e=>!v(e.name,f)&&"esriFieldTypeString"===e.type))?.name??l.fields.find((e=>!v(e.name,f)))?.name??f,l.primaryKeyField=f,l}(t,n),i=await async function(e,t,r){const{data:a,includeHeaderRow:n,outFields:o,escapeFormulaChars:i,locale:s,numberFormat:c,dateFormat:m,timeFormat:l}=e,{spatialReference:u}=r,f=[],d=n?a.slice(1):a,y=(e,r)=>!t.columnIndices||0===t.columnIndices.length||!t.columnIndices.includes(r);return await Promise.all(d.map((async(e,a)=>{const n=new L;for(let t=0;t<r.fields.length;t++){const u=r.fields[t],f=e.filter(y);if(o.includes("*")||o.filter((e=>v(e,u.name))).length>0){let e=await Fe(f[t]?.raw,u,{escapeFormulaChars:i,dateFormat:m,numberFormat:c,timeFormat:l,locale:s});"esriFieldTypeOID"===u.type&&null===e&&(e=a),n.attributes.set(u.name,e)}}t.geometries&&(n.geometry=await re(t.geometries[a],u)),f.push(n)}))),f}(t,n,o);return new P({features:i,schema:o})}export async function toCsv(e,r){i("featureSet",e).isNotMissing();const a=Array.from(e),n={...{useFormattedValues:!1,alwaysQuote:!1,escapeFormulaChars:!0,delimiter:",",dateFormat:h.ROUND_TRIP,timeFormat:F.ROUND_TRIP,geometryFormat:a.some((e=>void 0!==e.geometry&&null!==e.geometry))?GeometryFormat.WKT:GeometryFormat.NONE,includeByteOrderMark:!0,outSpatialReference:t.WGS84,includeHeaderRow:!0,outFields:ee(e.source),rowDelimiter:navigator.platform.startsWith("Win")?$:j},...r},{includeByteOrderMark:o,includeHeaderRow:s,delimiter:c,outFields:m,rowDelimiter:l}=n,u=[];o&&u.push("\ufeff");const f=q(a,n),d=Q(a,m,e.schema,!0),y=Q(a,m,e.schema,!1);if(s){const e=[];for(const t of f)e.push(ae(t,n));for(const t of d)e.push(ae(t,n));for(const t of y)e.push(ae(t,n));const t=e.join(c)+l;u.push(t)}await Promise.all(a.map((async e=>{const t=[],r=(t,r)=>{const a=oe(e,t,r),n=e.schema.findFieldByName(t)?.type;return ae(ne(a,{...r,isDateOnly:"date-only"===n}),r)};t.push(...await async function(e,t){let r=await te(e,t);t.geometryFormat!==GeometryFormat.XYZ&&t.geometryFormat!==GeometryFormat.XY&&t.geometryFormat!==GeometryFormat.LAT_LON||(r=r.map((e=>void 0===e?"":ne(e,t))));return r.map((e=>""===e?"":ae(e,t)))}(e.geometry,n)),t.push(...d.map((e=>r(e,n)))),t.push(...y.map((e=>r(e,n))));const a=`${t.join(c)}${l}`;u.push(a)})));return new Blob(u,{type:"text/plain",endings:l===j||l===$?"transparent":"native"})}export async function csvToUploadData(e,t){let r;if(i("csvData",e).isNotMissing(),e instanceof Blob){const t=new Promise(((t,r)=>{const a=new FileReader;a.onload=()=>{t(a.result)},a.onerror=()=>{r(a.error)},a.readAsText(e)}));r=await t}else r=e;const o=Z(t),s=o.rowDelimiter||function(e){let t=j;return me(e,$,((r,a)=>(0===r&&a===e.length||(t=$),!1))),t}(r),c=o.delimiter??function(e,t,r){const a=",";if(0===e.length)return a;const o=[];if(me(e,t,((t,r)=>(r!==e.length||t!==r)&&(o.push(e.substring(t,r)),o.length<3))),0===o.length)return a;let i=[{delimiter:",",rowsDelimiterOccurrences:[],rowsNumberAdjacentOccurrences:[]},{delimiter:";",rowsDelimiterOccurrences:[]},{delimiter:"|",rowsDelimiterOccurrences:[]},{delimiter:"\t",rowsDelimiterOccurrences:[]},{delimiter:" ",rowsDelimiterOccurrences:[]}].filter((e=>o[0].includes(e.delimiter)));if(0===i.length)return a;for(const e of o)for(const t of i){let a=0,n=0;me(e,t.delimiter,((o,i)=>{if(i!==e.length&&a++,","===t.delimiter){const t=e.charAt(i-1),a=e.charAt(i+1);I(t,r)&&I(a,r)&&n++}return!0})),t.rowsDelimiterOccurrences.push(a),","===t.delimiter&&t.rowsNumberAdjacentOccurrences.push(n)}if(i=i.filter((e=>e.rowsDelimiterOccurrences.every((t=>e.rowsDelimiterOccurrences[0]===t)))).sort(((e,t)=>t.rowsDelimiterOccurrences[0]-e.rowsDelimiterOccurrences[0])),i.length>1&&","===i[0].delimiter&&null!=r&&r!==n){const e=i[0];if(null!=e&&","===e.delimiter&&","===Intl.NumberFormat(r).formatToParts(1.1).find((e=>"decimal"===e.type))?.value)for(let t=0;t<e.rowsDelimiterOccurrences.length;t++)if(e.rowsDelimiterOccurrences[t]<=e.rowsNumberAdjacentOccurrences[t]){i=i.filter((e=>","!==e.delimiter));break}}if(0===i.length)return a;return i[0].delimiter}(r,s,t.locale),m=function(e,t,r){const a=[],n=(e,t)=>{const a=[];return me(e,r,((r,n)=>{const o=e.substring(r,n);return a.push({raw:ce(o,t,a.length)}),!0})),a};if(me(e,t,((t,r)=>{const o=e.substring(t,r);return o.length>0&&a.push(n(o,a.length)),!0})),a.length){const e=a[0].length;a.forEach(((t,r)=>{if(t.length!==e)throw new Error(`Detected invalid CSV: Row ${r} does not have expected number of columns: ${e}`)}))}return a}(r,s,c);let{geometryFormat:l,geometryFields:u}=t;if(!l){const[e,t]=await ge(m,o.inSpatialReference,o.includeHeaderRow);l=e,u=t.map((e=>o.includeHeaderRow?m[0][e]?.raw??a("gcx.api.data.convert.import-field-alias",(e+1).toString()):a("gcx.api.data.convert.import-field-alias",(e+1).toString())))}return{data:m,...o,geometryFormat:l,geometryFields:u}}export async function csvToFeatureSet(e,t){const r=Z(t);return uploadDataToFeatureSet(await csvToUploadData(e,r))}export async function toXLSX(e,r){i("featureSet",e).isNotMissing();const a=Array.from(e),n={...{useFormattedValues:!1,includeHeaderRow:!0,escapeFormulaChars:!0,geometryFormat:a.some((e=>void 0!==e.geometry&&null!==e.geometry))?GeometryFormat.WKT:GeometryFormat.NONE,outFields:ee(e.source),outSpatialReference:t.WGS84,dateFormat:h.DEFAULT,timeFormat:F.DEFAULT,numberFormat:w.DEFAULT,sheetName:"sheet1"},...r},{outFields:s,includeHeaderRow:c,dateFormat:m,timeFormat:l,numberFormat:u}=n,f=q(a,n),d=Q(a,s,e.schema,!0),y=Q(a,s,e.schema,!1),p=await import("xlsx"),g=p.utils.sheet_new();let S=!1;if(c){const t=f.concat(d).concat(function(e,t){const r=t?.schema?.fieldExtensions.initializedItems.map((e=>e.field));return e.map((e=>r?.find((t=>v(t.name,e)))?.alias??e))}(y,e.source));S=!0,p.utils.sheet_add_aoa(g,[t],{cellDates:!0})}await Promise.all(a.map((async e=>{const t=[],r=new Set,a=new Set;t.push(...await te(e.geometry,n));for(const r of d){const a=Re(e.attributes.get(r),n);t.push(a)}for(const i of y){const s=oe(e,i,n);if(s instanceof o){const a=e.schema.findFieldByName(i);"time-only"===a?.type&&r.add(t.length)}else if(s instanceof Date){const r=e.schema.findFieldByName(i);"date-only"===r?.type&&a.add(t.length)}const c=Re(s,n);t.push(c)}if(!t.every((e=>"string"!=typeof e||e.length<=32767)))return void B().warn(`toXLSX cell limit exceeded, feature (${e.primaryKey??e.id}) omitted.`);p.utils.sheet_add_aoa(g,[t],{cellDates:!0,origin:S?-1:void 0}),S=!0;const i=p.utils.decode_range(g["!ref"]);for(let e=i.s.c;e<=i.e.c;e++){const t=g[p.utils.encode_cell({r:i.e.r,c:e})];"d"===t.t?r.has(e)?t.z=Ne(l??F.ROUND_TRIP):a.has(e)?t.z=Te(m??h.ROUND_TRIP):t.z=Se(m??h.ROUND_TRIP):"n"===t.t&&(t.z=Oe(u))}})));const T={SheetNames:[],Sheets:{}};T.SheetNames.push(n.sheetName),T.Sheets[n.sheetName]=g;const N=p.write(T,{type:"binary",bookType:"xlsx",compression:!0,bookSST:!0,cellDates:!0}),O=new Uint8Array(N.length);for(let e=0;e<N.length;e++)O[e]=N.charCodeAt(e);return new Blob([O.buffer],{type:"text/plain"})}export async function xlsxToUploadData(e,t){i("xlsxData",e).isNotMissing();const r=K(t),n=await async function(e,t){const r=await import("xlsx"),a=new Promise(((a,n)=>{const o=new FileReader;o.onload=()=>{const e=new Uint8Array(o.result);let n="";for(const t of e)n+=String.fromCharCode(t);const i=r.read(n,{type:"binary",cellDates:!0}),s=t.sheetName||i.SheetNames[0],c=i.Sheets[s];a(c)},o.onerror=()=>{n(o.error)},o.readAsArrayBuffer(e)})),n=await a,o=r.utils.decode_range(n["!ref"]),i=[];for(let e=o.s.r;e<=o.e.r;e++){const t=[];for(let a=o.s.c;a<=o.e.c;a++){const o=n[`${r.utils.encode_cell({r:e,c:a})}`];o&&"d"===o.t&&o.v instanceof Date&&(o.v=new Date(o.v.getTime()+6e4*o.v.getTimezoneOffset())),t.push(o?{raw:o.v,formatted:"s"===o.t?void 0:o.w}:{raw:""})}i.push(t)}return i}(e,r);let{geometryFormat:o,geometryFields:s}=t;if(!o){const[e,t]=await ge(n,r.inSpatialReference,r.includeHeaderRow);o=e,s=t.map((e=>r.includeHeaderRow?n[0][e]?.raw.toString()??a("gcx.api.data.convert.import-field-alias",(e+1).toString()):a("gcx.api.data.convert.import-field-alias",(e+1).toString())))}return{data:n,...r,geometryFormat:o,geometryFields:s}}export async function xlsxToFeatureSet(e,t){i("xlsxData",e).isNotMissing();const r=K(t);return uploadDataToFeatureSet(await xlsxToUploadData(e,r))}export async function toShapefile(e,r){i("featureSet",e).isNotMissing();const[{default:a},n]=await Promise.all([import("jszip"),import("../forked-libs/shp-write/index.js")]),o=Array.from(e),s={...{useFormattedValues:!1,outFields:ee(e.source),fileName:e.title||"export"},...r},{outFields:d,outSpatialReference:y,fileName:p}=s,g=e=>e.geometry.hasZ||e.geometry.hasM,h=new Map,w=o.filter((e=>c(e.geometry)));h.set("POINTZ",w.filter(g)),h.set("POINT",w.filter((e=>!g(e))));const F=o.filter((e=>m(e.geometry)));h.set("MULTIPOINTZ",F.filter(g)),h.set("MULTIPOINT",F.filter((e=>!g(e))));const S=o.filter((e=>l(e.geometry)));h.set("POLYLINEZ",S.filter(g)),h.set("POLYLINE",S.filter((e=>!g(e))));const T=o.filter((e=>u(e.geometry)||f(e.geometry)));h.set("POLYGONZ",T.filter(g)),h.set("POLYGON",T.filter((e=>!g(e))));const N=Q(o,d,e.schema,!0);let O=Q(o,d,e.schema,!1);O=N.concat(O);const R=new a,D=Array.from(h.keys()).filter((e=>h.get(e).length>0));await Promise.all(D.map((async r=>{const a=h.get(r),o=await Promise.all(a.map((e=>re(e.geometry,y)))),i=await async function(e){const{wkid:r,wkt:a}=e[0].spatialReference;if(!e.every((e=>e.spatialReference.wkid===r&&e.spatialReference.wkt===a)))throw new Error("Cannot create shapefile that contains geometries with different spatial references.");return a??await E(r??t.WGS84.wkid)}(o),d=s.useFormattedValues?Object.assign({},...O.map((e=>({[e]:W.STRING})))):function(e,t,r,a){const n={};for(const o of t){if(e.some((e=>ie(e,o)))){n[o]=W.STRING;continue}const t=r?r.fields.find((e=>v(e.name,o))):void 0;if(t){switch(t.type){case"oid":case"double":case"integer":case"single":case"small-integer":case"big-integer":n[o]=W.NUMBER;break;case"date":case"timestamp-offset":n[o]=a?W.NUMBER:W.DATE;break;default:n[o]=W.STRING}continue}const i=(e,t)=>e.attributes.get(t)??e.presentableAttributes.get(t);e.every((e=>i(e,o)instanceof Date||void 0===i(e,o)))&&e.some((e=>i(e,o)instanceof Date))?n[o]=a?W.NUMBER:W.DATE:e.every((e=>"number"==typeof i(e,o)||void 0===i(e,o)))&&e.some((e=>"number"==typeof i(e,o)))?n[o]=W.NUMBER:e.every((e=>"boolean"==typeof i(e,o)||void 0===i(e,o)))&&e.some((e=>"boolean"==typeof i(e,o)))?n[o]=W.BOOLEAN:n[o]=W.STRING}return n}(a,O,e.schema,"timestamp"===s.dateFormat),g=function(e){return e.map((e=>{if(c(e)){const{x:t,y:r,z:a,m:n}=e,o=[t,r];return e.hasZ&&o.push(a),e.hasM&&o.push(n),De(o,e)}if(m(e))return Me(e.points,e);if(l(e))return Ae(e.paths,e);if(u(e))return Ae(e.rings,e);if(f(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.")}))}(o),w=function(e,t,r,a){const n=[];for(const o of e){const e={};for(const n of t){let t=oe(o,n,a);if(null==t&&(t=""),a.useFormattedValues)t=t.toString();else{t=Ee(t,r[n],{...a,isDateOnly:"date-only"===o.schema.findFieldByName(n)?.type})}e[n]=t}n.push(e)}return n}(a,O,d,s);n.write(w,r,g,((e,t)=>{const a=D.length>1?`${p}_${r.toLowerCase()}`:p;R.file(`${a}.shp`,t.shp.buffer,{binary:!0}),R.file(`${a}.shx`,t.shx.buffer,{binary:!0}),R.file(`${a}.dbf`,t.dbf.buffer,{binary:!0}),R.file(`${a}.prj`,i)}))})));const M=await R.generateAsync({type:"uint8array"});return new Blob([M.buffer],{type:"text/plain"})}export async function shapefileToUploadData(r,a){i("shapefileData",r).isNotMissing();const n=V(a),o=new Promise(((e,t)=>{const a=new FileReader;a.onload=()=>{e(a.result)},a.onerror=()=>{t(a.error)},a.readAsArrayBuffer(r)})),[{default:s},{default:m}]=await Promise.all([import("jszip"),import("shpjs")]),l=await o,u=await s.loadAsync(new Uint8Array(l)),f=u.filter((()=>!0)).map((e=>e.name));let d,y=f.filter((e=>e.endsWith(".shp"))).map((e=>e.substring(0,e.length-4)));if(y=function(e){if(!e.length)return[];let t=e[0];const r=t.match(J);return r?(t=r[1],e.filter((e=>{const r=e.match(J);return r&&r[1]===t}))):[t]}(y),f.some((e=>e.endsWith(".prj")))&&!y.every((e=>f.includes(`${e}.prj`))))throw new Error("Shapefile zip must contain the same prj file for each separate shapefile");await Promise.all(f.filter((e=>e.endsWith(".prj"))).map((async e=>{const t=await u.file(e).async("string");if(d){if(t!==d)throw new Error("Shapefile zip must contain the same prj file for each separate shapefile")}else d=t})));let p=[],g=[];for(const e of y){if(!f.includes(`${e}.shx`)||!f.includes(`${e}.dbf`))throw new Error("Shapefile must contain shp, shx, and dbf files.");const t=await u.file(`${e}.shp`).async("uint8array"),r=m.parseShp(t),a=await u.file(`${e}.dbf`).async("uint8array"),n=m.parseDbf(a);if(n.length!==r.length)throw new Error("Shapefile must contain shp, shx, and dbf files.");p=p.concat(n),g=g.concat(r)}const h=await Promise.all(g.map((r=>async function(r,a){const n=c(r)?function(r){i("geometry.coordinates",r.type).matches("Point"),i("geometry.coordinates",r.coordinates).satisfies((e=>"number"==typeof e||Array.isArray(e)));const[a,n,o]=r.coordinates,s=new e({x:a,y:n,spatialReference:t.WGS84});if(Array.isArray(o)){const[e,t]=o;!e&&!t||e?s.z=e:s.m=t}return s}(r):await b(r);if(a){let e;try{const r=await G(a);e=new t({wkid:S(r)})}catch{}e||(e=new t({wkt:a})),n.spatialReference=e}return n}(r,d)))),w=geometryTypeHeaders[GeometryFormat.ARCGIS_JSON][0][0];p.forEach(((e,t)=>e[w]=JSON.stringify(h[t].toJSON())));return{data:function(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]})))))]}(p),...n,includeHeaderRow:!0,geometryFormat:GeometryFormat.ARCGIS_JSON,geometryFields:[w],inSpatialReference:h[0]?.spatialReference??t.fromJSON({wkid:4326})}}export async function shapefileToFeatureSet(e,t){i("shapefileData",e).isNotMissing();const r=V(t);return uploadDataToFeatureSet(await shapefileToUploadData(e,r))}function k(e){return{escapeFormulaChars:!0,outFields:["*"],generatePrimaryKey:!1,locale:n,detectOid:!e?.primaryKeyField}}function Z(e){return{...{includeHeaderRow:!0,inSpatialReference:t.WGS84,...k(e)},...e}}function K(e){return{...{includeHeaderRow:!0,inSpatialReference:t.WGS84,...k(e)},...e}}function V(e){return{...{...k(e)},...e}}function q(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 Q(e,t,r,a){const n=r.fields.filter((e=>"oid"===e.type)).map((e=>e.name)).toArray();if(a)return n;if(t&&!t.includes("*"))return t.filter((e=>!n.includes(e)));{const t=r.fields.filter((e=>"oid"!==e.type)).map((e=>e.name)).toArray();let a=[];for(const r of e)for(const e of r.attributes.keys())t.includes(e)||n.includes(e)||a.includes(e)||a.push(e);return a=a.sort(),t.concat(a)}}function ee(e){if(!e)return["*"];const t=e.featureSettings.popupTemplate?.content;return(Array.isArray(t)?t.find((e=>"fields"===e.type))?.fieldInfos?.filter((e=>e.visible))?.map((e=>e.fieldName)):void 0)??e.featureSettings.popupTemplate?.fieldInfos?.filter((e=>e.visible))?.map((e=>e.fieldName))??["*"]}async function te(e,t){const r=await re(e,t.outSpatialReference);if(t.geometryFormat===GeometryFormat.XYZ){if(!r)return["","",""];if(!c(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(!c(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(!c(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(r.toJSON())]:[""]:t.geometryFormat===GeometryFormat.WKT?r?[await M(r)]:[""]:t.geometryFormat===GeometryFormat.GEO_JSON?r?[JSON.stringify(await _(r))]:[""]:[]}async function re(e,t){return e?.spatialReference&&!e.spatialReference.equals(t)&&t?(await D([e],t))[0]:e}function ae(e,t){const r=[t.delimiter,C,"\r","\n",t.rowDelimiter];if(t.alwaysQuote||r.some((t=>e.includes(t)))){const t=e.replace(new RegExp(C,"g"),`${C}${C}`);return`${C}${t}${C}`}return e}function ne(e,t){if(null==e)return"";if(!t.useFormattedValues){if("number"==typeof e){const r=t.numberFormat||w.ROUND_TRIP;return T(r,e)}if(e instanceof Date)return"timestamp"===t.dateFormat?e.getTime().toString():y({format:t.dateFormat,timeZone:"UTC",isDateOnly:t.isDateOnly},e);if(e instanceof o)return O({format:t.timeFormat},e)}let r=e.toString();return t.escapeFormulaChars&&(r=se(r)),r}function oe(e,t,r){if(r.useFormattedValues||ie(e,t))return e.presentableAttributes.get(t)??e.attributes.get(t);const a=e.schema.findFieldByName(t)?.type;if(null!=a)switch(a){case"date":case"date-only":case"timestamp-offset":{const r=d(e.attributes.get(t));if(!isNaN(r.getTime()))return r;break}case"time-only":{const r=N(e.attributes.get(t));if(r.isValid)return r;break}}return e.attributes.get(t)??e.presentableAttributes.get(t)}function ie(e,t){return!!v(t,e.schema.typeIdField)||("coded-value"===e.type?.domains?.[t]?.type||"coded-value"===e.schema.findFieldByName(t)?.domain?.type)}function se(e){for(const t of U)if(e.startsWith(t))return`\t${e}`;return e}function ce(e,t,r){const a=e.startsWith(C),n=e.endsWith(C);if(a&&!n||!a&&n)throw new Error(`Detected invalid CSV: Missing opening or closing quote for value at row:${t} column:${r}`);const o=a?e.substring(C.length,e.length-C.length):e;let i=-1;return me(o,C,((e,a)=>{if(a===o.length)return!0;if(i<0){if(a!==o.length)return i=a,!0}else if(a===i+C.length)return i=-1,!0;throw new Error(`Detected invalid CSV: Non-escaped quote for value at row:${t} column:${r}`)})),o.replace(new RegExp(`${C}${C}`,"g"),C)}function me(e,t,r){let a,n=!1,o=0,i=0;for(;a=e.indexOf(t,o),!(a<0);){for(let t=o;t<a;)e.substring(t).startsWith(C)?(n=!n,t+=C.length):t++;const s=a+t.length;if(!n){const e=r(i,a);if(i=s,!e)return}o=s}r(i,e.length)}async function le(e,t){const r=JSON.parse(e),a=(await import("@arcgis/core/geometry/support/jsonUtils")).fromJSON(r);return r.spatialReference||(a.spatialReference=t),a}async function ue(e,t){const r=await b(JSON.parse(e));return r.spatialReference=t,r}async function fe(e,t){const r=await A(e);return r.spatialReference=t,r}function de(e,t,r){const a=r?[r]:geometryTypeHeaders[t];for(const t of a){const r=t.map((t=>e.map((e=>e?.raw?.toString().trim().toLowerCase())).indexOf(t.trim().toLowerCase())));if(r.every((e=>e>=0)))return r}}async function ye(e,t){return(await Promise.all(e.map((async(e,r)=>{const a=e?.raw;if("string"==typeof a&&""!==a)try{return await t(a,void 0),r}catch{return}})))).find((e=>void 0!==e))}function pe(e,t,r){return"inv"===t?"string"==typeof e?parseFloat(e.replaceAll(",","")):e:S({locale:t,format:r},e)}async function ge(e,t,r){const a=r?e.slice(1):e;if(r){const r=de(e[0],GeometryFormat.ARCGIS_JSON);if(void 0!==r)for(const[e,n]of X){try{await he(r[0],n,t,a)}catch(e){continue}return[e,[r[0]]]}const n=[GeometryFormat.XYZ,GeometryFormat.XY,GeometryFormat.LAT_LON];for(const t of n){const r=de(e[0],t);if(void 0!==r)return[t,r]}}for(const[e,r]of X){const n=await ye(a[0],r);if(void 0!==n){try{await he(n,r,t,a)}catch(e){continue}return[e,[n]]}}return[GeometryFormat.NONE,[]]}async function he(e,t,r,a){return{columnIndices:[e],geometries:await Promise.all(a.map((t=>t[e])).map((e=>{if(e?.raw)return t(e.raw.toString(),r)})))}}function we(e,t,r){let a=!1,n=!0,i=!0,s=!0,c=!0,m=!0;const l=new Set,{data:u,includeHeaderRow:f,dateFormat:y,timeFormat:h,primaryKeyField:w,locale:F}=e,S=f?u[0]:[],T=f?u.slice(1):u;for(const e of T){const r=e[t];r?.raw&&(l.add(r.raw),a=!0,n&&(n=I(r.raw,F)||Number.isNaN(r.raw)),i&&(i=r.raw instanceof Date||d(y||p,r.raw)!==g),c&&(c=d(y||H,r.formatted)!==g),s&&(s=r.raw instanceof o||N(h||R,r.raw).isValid),m&&(m=N({format:h||z,locale:"en"},r.formatted).isValid))}const O=l.size===T.length;return w&&S[t]?.raw===w||r&&a&&O&&n?"esriFieldTypeOID":a&&m?"esriFieldTypeTimeOnly":a&&c?"esriFieldTypeDate":a&&n?"esriFieldTypeDouble":a&&s?"esriFieldTypeTimeOnly":a&&i?"esriFieldTypeDate":"esriFieldTypeString"}async function Fe(e,t,r){const{escapeFormulaChars:a,locale:n,numberFormat:i,dateFormat:s,timeFormat:c}=r;if("esriFieldTypeDouble"===t.type||"esriFieldTypeOID"===t.type)return"number"==typeof e?e:e?pe(e,n,i):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:d({locale:n,format:s},e).getTime()}if("esriFieldTypeTimeOnly"===t.type){if(e instanceof o)return e.toString();if(e instanceof Date)return new o(e).toString();if("number"==typeof e){const t=(await import("xlsx")).SSF.parse_date_code(e);return t?new o(`${t.H.toString().padStart(2,"0")}:${t.M.toString().padStart(2,"0")}:${t.S.toString().padStart(2,"0")}`).toString():void 0}return""===e?null:N({locale:n,format:c},e).toString()}const m=e?.toString()??"";if(a&&m.startsWith("\t"))for(const e of U)if(m.length>1&&m.charAt(1)===e)return m.substring(1);return m}function Se(e){switch(e){case h.DATE_SHORT:return"dd/MM/yyyy";case h.DATE_LONG:return"MMMM d, yyyy";case h.TIME_SHORT:return"h:mm AM/PM";case h.TIME_LONG:return"h:mm:ss AM/PM";case h.DATE_TIME_SHORT:case h.DEFAULT:return"MMM d yyyy h:mm AM/PM";case h.DATE_TIME_LONG:return"MMMM d yyyy h:mm AM/PM";case h.FULL:return"dddd, MMMM d yyyy h:mm AM/PM";case h.ISO_8601:case h.ROUND_TRIP:return'yyyy-MM-dd"T"HH:mm:ss';default:{const t=e.replace(/tt/g,"AM/PM");return t.includes("z")&&B().warn("Warning: Excel will not recognize timezone format 'z', 'zz', or 'zzz'"),t.includes("h")&&!t.includes("AM/PM")&&B().warn("Warning: Excel will interpret 'h' as 'H' if the format does not have an AM/PM designator"),t}}}function Te(e){switch(e){case h.DATE_SHORT:return"dd/MM/yyyy";case h.DATE_LONG:return"MMMM d, yyyy";case h.DATE_TIME_SHORT:case h.DEFAULT:return"MMM d yyyy";case h.DATE_TIME_LONG:return"MMMM d yyyy";case h.FULL:return"dddd, MMMM d yyyy";case h.ISO_8601:case h.ROUND_TRIP:return"yyyy-MM-dd";default:return e.replace(/TtZzHhmSsUua/g,"")}}function Ne(e){switch(e){case F.TIME_SHORT:return"h:mm AM/PM";case F.TIME_LONG:return"h:mm:ss AM/PM";case F.ISO_8601:case F.ROUND_TRIP:return"HH:mm:ss";default:{const t=e.replace(/tt/g,"AM/PM");return t.includes("h")&&!t.includes("AM/PM")&&B().warn("Warning: Excel will interpret 'h' as 'H' if the format does not have an AM/PM designator"),t}}}function Oe(e){switch(e){case w.ACCOUNTING:return'_("$"* #,##0.00_);_("$"* (#,##0.00);_("$"* "-"??_);_(@_)';case w.CURRENCY:return'"$"#,##0.00';case w.FIXED_POINT:case w.DEFAULT:return"0.0000";case w.NUMBER:return"#,##0.0000";case w.PERCENT:return"0%";case w.ROUND_TRIP:return"0.00000";default:return e}}function Re(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;if(e instanceof o)return e.toDate()}let r=e.toString();return t.escapeFormulaChars&&(r=se(r)),r}function De(e,t){return 3===e.length&&!t.hasZ&&t.hasM?[e[0],e[1],void 0,e[2]]:e}function Me(e,t){return e.map((e=>De(e,t)))}function Ae(e,t){return e.map((e=>Me(e,t)))}function Ee(e,t,r){switch(t){case W.NUMBER:return e instanceof Date?e.getTime():S(e);case W.STRING:return e instanceof Date?y({format:r.dateFormat??h.ROUND_TRIP,timeZone:"UTC",isDateOnly:r.isDateOnly},e):e instanceof o?O({format:r.timeFormat??F.ROUND_TRIP},e):"number"==typeof e?T(r.numberFormat??w.DEFAULT,e):e.toString();case W.BOOLEAN:return!!e;case W.DATE:return d(e);default:return e.toString()}}
|