import g from "@arcgis/core/layers/FeatureLayer.js";
import te from "@arcgis/core/request.js";
import { p as ie } from "./utilities.js";
import re from "@arcgis/core/portal/PortalItem.js";
import se from "@arcgis/core/WebMap.js";
import ne from "@arcgis/core/WebScene.js";
import { isNotNull as v, isNotUndefined as k } from "@arcgis/toolkit/predicate";
import { addLtrMark as oe, setValuesInString as G } from "@arcgis/toolkit/string";
import { s as w, f as ae, a as m, m as le, b as ue } from "./fields.js";
import { CompletionItemKind as F, InsertTextFormat as x, InsertTextMode as P } from "vscode-languageserver-types";
import { getDeclaredVoxelMembers as pe, getDeclaredPixelMembers as ce } from "@arcgis/core/applications/Components/arcadeEditorUtils.js";
import { log as h } from "@arcgis/toolkit/log";
import { i as he } from "./monaco-importer.js";
import { g as fe } from "./runtime.js";
import { normalizeLocale as de } from "@arcgis/toolkit/intl";
import { filterApiLibraryForContext as ye } from "@arcgis/languages-api-utils";
import { Emitter as E, Uri as j } from "monaco-editor";
/*! All material copyright Esri, All Rights Reserved, unless otherwise specified.
See https://js.arcgis.com/5.0/esri/copyright.txt for details.
v5.0.0-next.125 */
function q(t) {
  return !!t && typeof t == "object" && "declaredClass" in t && typeof t.declaredClass == "string" && t.declaredClass.startsWith("esri.layers.") && D(t) && "queryFeatures" in t && typeof t.queryFeatures == "function";
}
function K(t) {
  return !!t && typeof t == "object" && "declaredClass" in t && typeof t.declaredClass == "string" && (t.declaredClass === "esri.Map" || t.declaredClass === "esri.WebMap" || t.declaredClass === "esri.WebScene");
}
function _e(t) {
  return !!t && typeof t == "object" && "loadAll" in t && typeof t.loadAll == "function";
}
function z(t) {
  return !!t && typeof t == "object" && "portalItem" in t && t.portalItem != null;
}
function H(t) {
  return !!t && typeof t == "object" && "portalItem" in t && t.portalItem != null;
}
function D(t) {
  return !!t && typeof t == "object" && "fields" in t && Array.isArray(t.fields);
}
function C(t) {
  return !!t && typeof t == "object" && "url" in t && typeof t.url == "string";
}
function be(t) {
  return C(t) && /\/(?:featureserver|mapserver)(?:\/|$)/iu.test(t.url ?? "");
}
function J(t) {
  return C(t) || D(t) || H(t);
}
function et(t) {
  return J(t) && "type" in t && t.type === "voxel";
}
function tt(t) {
  return J(t) && "type" in t && (t.type === "imagery" || t.type === "imagery-tile");
}
function it(t) {
  return C(t) || D(t) || H(t);
}
function rt(t) {
  return z(t) || K(t) || be(t);
}
function N(t) {
  return !!t && typeof t == "object" && "declaredClass" in t && t.declaredClass === "esri.layers.support.Subtype";
}
function S(t) {
  return !!t && typeof t == "object" && "declaredClass" in t && t.declaredClass === "esri.layers.support.CodedValueDomain";
}
function me(t) {
  return !!t && typeof t == "object" && "declaredClass" in t && t.declaredClass === "esri.layers.support.InheritedDomain";
}
function st(t) {
  return !!t && typeof t == "object" && "id" in t && typeof t.id == "string" && "definitions" in t && typeof t.definitions == "object" && !Array.isArray(t.definitions);
}
function f(t) {
  return !!t && typeof t == "object" && "title" in t && typeof t.title == "string";
}
function ge(t) {
  return !!t && typeof t == "object" && "url" in t && typeof t.url == "string";
}
function Q(t) {
  return !!t && typeof t == "object" && "layerId" in t && typeof t.layerId == "number";
}
function V(t) {
  return !!t && typeof t == "object" && "typeIdField" in t && "types" in t;
}
function U(t) {
  return !!t && typeof t == "object" && "getFieldDomain" in t && typeof t.getFieldDomain == "function";
}
function y(t) {
  return !!t && typeof t == "object" && "subtypeField" in t;
}
function we(t) {
  return y(t) && "subtypes" in t;
}
function De(t) {
  return !!t && typeof t == "object" && "portalItem" in t;
}
function Ce(t) {
  return Q(t) && "relationships" in t && "url" in t && Array.isArray(t.relationships) && typeof t.url == "string";
}
function Se(t) {
  return !!t && typeof t == "object" && "isTable" in t && typeof t.isTable == "boolean";
}
function ve(t) {
  if (t && typeof t == "object") {
    if (Se(t))
      return t.isTable || "type" in t && t.type === "table";
    if ("geometryType" in t)
      return t.geometryType === "" || t.geometryType === "esriGeometryNull" || t.geometryType === null;
  }
  return !1;
}
function Fe(t) {
  return !ve(t);
}
function xe(t) {
  return !!t && typeof t == "object" && "load" in t && typeof t.load == "function";
}
function Pe(t) {
  return !!t && typeof t == "object" && "type" in t && t.type === "voxel";
}
function B(t) {
  return !!t && typeof t == "object" && "type" in t && typeof t.type == "string" && ["imagery", "imagery-tile"].includes(t.type);
}
async function X(t) {
  if (!t)
    return null;
  let e;
  return D(t) ? e = t : e = new g(t), xe(e) && await e.load(), e;
}
async function Ve(t) {
  t += "/layers";
  const e = await te(t, { responseType: "json", query: { f: "json" } }), i = t.endsWith("MapServer/layers") ? "data" : "query", r = W(e.data?.layers, i), s = W(e.data?.tables, i);
  return { layers: r, tables: s };
}
function W(t, e) {
  return t ? t.filter((i) => {
    switch (i.type) {
      case "Feature Layer":
      case "Oriented Imagery Layer":
      case "Catalog Layer":
      case "Table":
        return (i.capabilities ? i.capabilities.toLowerCase().split(",").map((s) => s.trim()) : []).includes(e);
      default:
        return !1;
    }
  }) : [];
}
async function Ie(t, e) {
  const i = new g({ url: `${t.url}/${e.relatedTableId}` });
  return await i.load(), i;
}
function I(t) {
  return (e, i) => {
    if (e.type === "oid")
      return -1;
    if (i.type === "oid")
      return 1;
    if (y(t)) {
      if (e.name === t.subtypeField)
        return -1;
      if (i.name === t.subtypeField)
        return 1;
    }
    if (V(t)) {
      if (e.name === t.typeIdField)
        return -1;
      if (i.name === t.typeIdField)
        return 1;
    }
    return e.name.localeCompare(i.name, "en", { sensitivity: "base" });
  };
}
function R(t, e) {
  return t?.every((i) => i.domains?.[e.name]?.type === "inherited") ?? !1;
}
const Te = /^[a-z_$][a-z0-9_$]*$/giu;
function T(t, e = !0) {
  return t.match(Te) ? `${e ? "." : ""}${t}` : `["${t}"]`;
}
function Y(t, e) {
  return t ? `${t}${T(e)}` : e;
}
function O(t) {
  return De(t) ? t.portalItem : null;
}
function nt(t, e, i = !1) {
  let r = e;
  const s = [], n = [];
  return w(t).forEach((o) => {
    r && (r += `  
  
`), r += `**${o.name}** (${o.alias})  
${o.type}`, o.description && (r += `  
'${o.description}`);
    const c = ue(o), p = T(o.name, !1), b = m(o);
    if (s.push({
      name: o.name,
      description: b,
      type: c,
      completion: {
        label: o.name,
        detail: b,
        insertText: p,
        insertTextMode: P.asIs,
        insertTextFormat: x.PlainText,
        kind: F.Field
      }
    }), i) {
      if (!o.alias || o.alias.toLowerCase() === o.name.toLowerCase())
        return;
      let d = `**${o.alias}**  
${o.type}`;
      o.description && (d += `  
'${o.description}`), n.push({
        name: o.alias,
        description: o.name,
        type: c,
        completion: {
          label: o.alias,
          detail: o.name,
          insertText: p,
          insertTextMode: P.asIs,
          insertTextFormat: x.PlainText,
          kind: F.Field,
          documentation: { kind: "markdown", value: d }
        }
      });
    }
  }), [[...s, ...n], r];
}
function ot(t, e) {
  let i = e;
  const r = [];
  return t.forEach((s) => {
    i && (i += `  
  
`), i += `**${s.name}**  
${s.type}`, s.name && (i += `  
'${s.name}`), r.push({
      name: s.name,
      description: s.name,
      // pixel members are always arrays
      type: "array",
      completion: {
        label: s.name,
        detail: s.name,
        insertText: T(s.name, !1),
        insertTextMode: P.asIs,
        insertTextFormat: x.PlainText,
        kind: F.Field
      }
    });
  }), [r, i];
}
class Z {
  constructor(e, i, r) {
    this._profile = e, this._label = i, this.description = r, this.filterDescription = !1;
  }
  /**
   * Returns the label string.
   */
  getLabel() {
    return this._label == null ? "" : typeof this._label == "string" ? oe(this._label) : G(this._profile?.intlStrings[this._label.code], this._label.formatValues);
  }
  /**
   * Returns the description string.
   */
  getDescription() {
    return this.description == null ? "" : typeof this.description == "string" ? this.description : G(this._profile?.intlStrings[this.description.code], this.description.formatValues);
  }
  /**
   * Returns true if the item pass the filter test
   */
  passFilter(e) {
    return !e || e.test(this.getLabel()) ? !0 : this.filterDescription && e.test(this.getDescription());
  }
}
class M extends Z {
  constructor(e) {
    super(e.profile, e.label, e.description ?? e.declaration?.description), this.declaration = e.declaration ?? {}, this.name = e.declaration?.name ?? "", this.snippet = e.snippet ?? "", this.nonInteractive = e.nonInteractive ?? !1, this.filterDescription = e.filterDescription ?? !1, this.icon = e.icon;
  }
}
class l extends M {
  constructor(e) {
    super(e), this.type = "text", this.isCollection = !1, this.type = e.declaration?.type ?? "text";
  }
  getDescription() {
    return this.description == null ? this._profile?.intlStrings[this.type.toLowerCase()] ?? "" : super.getDescription();
  }
  toProfileVariableDefinition() {
    return { type: this.type, name: "", ...this.declaration };
  }
}
class Me extends M {
  constructor(e) {
    super(e), this.type = "array", this.isCollection = !1, this.elementType = e.declaration?.elementType ?? { type: "number", name: "number" };
  }
  getDescription() {
    return this.description == null ? this._profile?.intlStrings[this.type.toLowerCase()] ?? "" : super.getDescription();
  }
  toProfileVariableDefinition() {
    return { type: this.type, elementType: this.elementType, name: "", ...this.declaration };
  }
}
class $ extends M {
  constructor(e, i) {
    super(i), this.owner = e, this.isCollection = !0, this._loaded = !0, this.variables = [];
  }
  get breadcrumb() {
    if (this.owner) {
      const e = this.owner.breadcrumb;
      return e ? `${e} / ${this.name}` : this.name;
    }
    return this.name;
  }
  /**
   * Returns true if the collection has been loaded
   */
  get loaded() {
    return this._loaded;
  }
  /**
   * Returns an url to the associated information
   */
  get informationUrl() {
    return null;
  }
  get informationType() {
    return "";
  }
}
class u extends Z {
  constructor(e, i, r = [], s = !1) {
    super(e, i), this.variables = r, this.isHeader = s, this.type = "group", this.isCollection = !0;
  }
  passFilter() {
    return !0;
  }
}
class _ extends $ {
  constructor(e, i) {
    super(e, i), this.type = "dictionary", this.dictionaryVariables = [], this.loadPropertyDeclarations(i.declaration?.properties), this.snippet && this.dictionaryVariables.length && (this.variables = [new u(this._profile, this.snippet, this.dictionaryVariables)]);
  }
  async loadSource() {
  }
  loadPropertyDeclarations(e) {
    this.dictionaryVariables = this.createVariableInstances(e), this.variables = this.dictionaryVariables;
  }
  createVariableInstances(e) {
    if (!Array.isArray(e))
      return [];
    const i = [];
    return e.forEach((r) => {
      const s = this.createVariableInstance(r);
      s && i.push(s);
    }), i;
  }
  createVariableInstance(e) {
    const i = Y(this.snippet, e.name);
    switch (e.type) {
      case "number":
      case "text":
      case "boolean":
      case "date":
      case "dateOnly":
      case "time":
      case "geometry":
      case "knowledgeGraph":
        return new l({ profile: this._profile, declaration: e, label: i, snippet: i });
      case "pixel":
        return new Ae(this, { profile: this._profile, declaration: e, label: i, snippet: i });
      case "voxel":
        return new Le(this, { profile: this._profile, declaration: e, label: i, snippet: i });
      case "feature":
        return new $e(this, { profile: this._profile, declaration: e, label: i, snippet: i });
      case "featureSet":
        return new A(this, { profile: this._profile, declaration: e, label: i, snippet: i }, [
          new l({ profile: this._profile, label: i, description: "", snippet: i })
        ]);
      case "featureSetCollection":
        return new Ge(this, {
          profile: this._profile,
          declaration: e,
          label: i,
          snippet: i
        });
      case "dictionary":
        return new _(this, {
          profile: this._profile,
          declaration: e,
          label: i,
          snippet: i
        });
      case "array":
        return new Me({
          profile: this._profile,
          declaration: e,
          label: i,
          snippet: i
        });
      default:
        return h("error", "Editor profile", "Invalid profile variable", { detail: { declaration: e } }), null;
    }
  }
  toProfileVariableDefinition() {
    return {
      type: this.type,
      name: "",
      ...this.declaration,
      properties: this.dictionaryVariables.map((e) => e.toProfileVariableDefinition())
    };
  }
}
class ee extends $ {
  constructor(e, i, r) {
    super(e, i), this.relationshipsProperties = r, this._source = null, this._loaded = !1, this._definition = i.declaration?.definition;
  }
  get title() {
    return f(this._source) ? this._source.title ?? "" : "";
  }
  get url() {
    return ge(this._source) ? this._source.url ?? "" : "";
  }
  get informationUrl() {
    return !this.loaded || !this.url ? null : Q(this._source) ? `${this.url}/${this._source.layerId}` : this.url;
  }
  get informationType() {
    return this._profile?.intlStrings.layer ?? "layer";
  }
  async loadSource() {
    return v(this._loadPromise) && k(this._loadPromise) ? await this._loadPromise : (this._loadPromise = this._loadSource(), await this._loadPromise);
  }
  _getValueSnippet(e) {
    return ["feature", "voxel", "pixel"].includes(this.type) ? Y(this.snippet, e.name) : e.name;
  }
  _getSubtypeOrDomainNameSnippet(e) {
    return this.type !== "feature" ? null : y(this._source) && e.name === this._source.subtypeField ? `SubtypeName(${this.snippet})` : `DomainName(${this.snippet}, "${e.name}")`;
  }
  _getFieldProperty(e, i) {
    const r = this._getDomainDictionary(e);
    if (r)
      return r;
    const s = this._getValueSnippet(e);
    return new l({
      profile: this._profile,
      label: s,
      description: m(e),
      snippet: s,
      icon: ae(e, i),
      filterDescription: !0
    });
  }
  _getMemberProperty(e) {
    const i = this._getValueSnippet(e);
    return new l({
      profile: this._profile,
      label: i,
      description: e.name,
      snippet: i,
      icon: le(e),
      filterDescription: !0
    });
  }
  _getDomainDictionary(e) {
    return U(this._source) ? y(this._source) && this._source.subtypeField ? this._getSubtypeDomainDictionary(e) : V(this._source) && this._source.typeIdField ? this._getFeatureTypeDomainDictionary(e) : this._getFieldDomainDictionary(e) : null;
  }
  _getSubtypeDomainDictionary(e) {
    if (!y(this._source))
      return null;
    if (!we(this._source))
      return e.name === this._source.subtypeField ? null : this._getFieldDomainDictionary(e);
    if (e.name === this._source.subtypeField) {
      const s = this._createDomainDictionary(e);
      return s.icon = "subtype", s.variables.push(this._getTypeOrSubtypeDomainGroup(this._source.subtypes, e)), s;
    }
    if (R(this._source.subtypes, e))
      return this._getFieldDomainDictionary(e);
    const i = this._getDomainValuesGroup(this._source.subtypes, e);
    if (!i)
      return null;
    const r = this._createDomainDictionary(e);
    return r.variables.push(i), r;
  }
  _getFeatureTypeDomainDictionary(e) {
    if (!V(this._source))
      return null;
    if (e.name === this._source.typeIdField) {
      const s = this._createDomainDictionary(e);
      return s.variables.push(this._getTypeOrSubtypeDomainGroup(this._source.types, e)), s;
    }
    if (R(this._source.types, e))
      return this._getFieldDomainDictionary(e);
    const i = this._getDomainValuesGroup(this._source.types, e);
    if (!i)
      return null;
    const r = this._createDomainDictionary(e);
    return r.variables.push(i), r;
  }
  _getFieldDomainDictionary(e) {
    if (!U(this._source))
      return null;
    const i = this._source.getFieldDomain(e.name);
    if (!S(i))
      return null;
    const r = this._getCodedValueDomainGroup(i, {
      code: "domainvalues"
    }), s = this._createDomainDictionary(e);
    return s.variables.push(r), s;
  }
  _getTypeOrSubtypeDomainGroup(e, i) {
    if (S(i.domain))
      return this._getCodedValueDomainGroup(i.domain, { code: "subtypes" });
    const r = e?.map((s) => {
      const n = N(s) ? s.code : s.id;
      return new l({
        profile: this._profile,
        label: `${n}`,
        description: s.name,
        snippet: `"${n}"`
      });
    }) ?? [];
    return new u(this._profile, { code: "subtypes" }, r);
  }
  _getCodedValueDomainGroup(e, i) {
    const r = e.codedValues.map(
      (s) => new l({
        profile: this._profile,
        label: `${s.code}`,
        description: s.name,
        snippet: `"${s.code}"`,
        filterDescription: !0
      })
    );
    return new u(this._profile, i, r);
  }
  _getDomainValuesGroup(e, i) {
    const r = [];
    return !e || e.length === 0 || (e.forEach((s) => {
      const n = s.domains?.[i.name];
      if (!n || me(n) || !S(n))
        return;
      const a = m(i), o = this._getCodedValueDomainGroup(n, {
        code: "domainvaluesfortypeformat",
        formatValues: {
          fieldName: a,
          typeName: s.name
        }
      }), c = N(s) ? s.code : s.id, p = `${c}`, b = `"${c}""`, d = new _(this, {
        profile: this._profile,
        label: p,
        snippet: b,
        description: s.name,
        declaration: { name: a }
      });
      d.variables = [o], r.push(d);
    }), !r.length) ? null : new u(this._profile, { code: "domainvaluesbysubtypes" }, r);
  }
  _createDomainDictionary(e) {
    const i = this._getValueSnippet(e), r = m(e), s = new _(this, {
      profile: this._profile,
      label: i,
      description: r,
      snippet: i,
      icon: "form-dropdown",
      declaration: { name: e.name }
    }), n = new u(this._profile, r, [
      new l({
        profile: this._profile,
        label: i,
        description: "",
        snippet: i
      })
    ]);
    s.variables = [n];
    const a = this._getSubtypeOrDomainNameSnippet(e);
    return a && n.variables.push(
      new l({
        profile: this._profile,
        label: a,
        description: "",
        snippet: a
      })
    ), s;
  }
  async _getRelationshipsProperty() {
    if (!this.relationshipsProperties?.exposeRelationships || !this._profile?.supportFeatureSetFunctions)
      return null;
    const e = this._source;
    if (!Ce(e))
      return null;
    const i = new u(this._profile, { code: "relationships" }), r = await Promise.all(
      e.relationships?.map(async (s) => {
        const n = await Ie(e, s);
        if (!q(n) || s.relatedTableId === this.relationshipsProperties?.sourceTableId)
          return null;
        const a = `FeatureSetByRelationshipName(${this.snippet}, "${s.name}")`;
        return new A(
          this,
          {
            profile: this._profile,
            declaration: { definition: n },
            label: n.title,
            description: "",
            nonInteractive: !0
          },
          [new l({ profile: this._profile, label: a, description: "", snippet: a })],
          { exposeRelationships: !0, sourceTableId: e.layerId }
        );
      }) ?? []
    );
    return i.variables = r.filter(v), i.variables.length ? i : null;
  }
}
class L extends ee {
  constructor(e, i, r, s = { exposeRelationships: !0 }) {
    super(e, i, s), this.type = r;
  }
  get title() {
    return f(this._source) ? this._source.title ?? "" : { code: this.type };
  }
  toProfileVariableDefinition() {
    return { type: this.type, name: "", ...this.declaration };
  }
}
class $e extends L {
  constructor(e, i) {
    super(e, i, "feature", { exposeRelationships: !0 }), this.type = "feature";
  }
  async _loadSource() {
    if (this.loaded)
      return this._source;
    try {
      if (this._source = await X(this._definition), !this._source)
        throw new Error("Invalid definition");
      const e = f(this._source) ? this._source.title ?? "" : "";
      this.variables.push(
        new u(this._profile, e, [
          new l({
            profile: this._profile,
            label: this.snippet,
            description: "",
            snippet: this.snippet
          })
        ])
      );
      const i = new u(this._profile, { code: "values" });
      if (this.variables.push(i), Fe(this._source)) {
        const n = `Geometry(${this.snippet})`, a = new l({
          profile: this._profile,
          declaration: { name: n },
          label: n,
          description: "Geometry",
          snippet: n,
          icon: "shapes",
          filterDescription: !0
        });
        i.variables.push(a);
      }
      const r = this._source;
      w(this._source.fields).map((n) => r.fields.find((a) => a.name === n.name)).sort(I(r)).forEach((n) => {
        i.variables.push(this._getFieldProperty(n));
      });
      const s = await this._getRelationshipsProperty();
      s && this.variables.push(s);
    } catch (e) {
      h("error", "FeatureVariable", "Error with definition", { detail: { error: e, definition: this._definition } }), this._source = null;
    } finally {
      this._loaded = !0;
    }
    return this._source;
  }
}
class Le extends L {
  constructor(e, i) {
    super(e, i, "voxel", { exposeRelationships: !1 }), this.type = "voxel", this._source = null;
  }
  async _loadSource() {
    if (this.loaded)
      return this._source;
    try {
      if (!Pe(this._definition))
        throw new Error("Invalid definition - not a VoxelLayer");
      if (await this._definition.load(), this._source = this._definition, !this._source)
        throw new Error("Invalid definition");
      const e = f(this._source) ? this._source.title ?? "" : "";
      this.variables.push(
        new u(this._profile, e, [
          new l({
            profile: this._profile,
            label: this.snippet,
            description: "",
            snippet: this.snippet
          })
        ])
      );
      const i = new u(this._profile, { code: "values" });
      this.variables.push(i);
      const r = await pe(this._source), s = this._source;
      w(this._source.fields).map((n) => s.fields.find((a) => a.name === n.name)).sort(I(s)).forEach((n) => {
        i.variables.push(this._getFieldProperty(n, r));
      });
    } catch (e) {
      h("error", this.type, "Error with definition", { detail: { error: e, definition: this._definition } }), this._source = null;
    } finally {
      this._loaded = !0;
    }
    return this._source;
  }
}
class Ae extends L {
  constructor(e, i) {
    super(e, i, "pixel", { exposeRelationships: !1 }), this.type = "pixel", this._source = null;
  }
  async _loadSource() {
    if (this.loaded)
      return this._source;
    try {
      if (!B(this._definition))
        throw new Error("Invalid definition - not an ImageryLayer");
      if (await this._definition.load(), this._source = this._definition, !this._source)
        throw new Error("Invalid definition");
      const e = f(this._source) ? this._source.title ?? "" : "";
      this.variables.push(
        new u(this._profile, e, [
          new l({
            profile: this._profile,
            label: this.snippet,
            description: "",
            snippet: this.snippet
          })
        ])
      );
      const i = new u(this._profile, { code: "values" });
      if (this.variables.push(i), !B(this._source))
        throw new Error("Invalid definition - not an ImageryLayer");
      (await ce(this._source)).forEach((s) => {
        i.variables.push(this._getMemberProperty(s));
      });
    } catch (e) {
      h("error", this.type, "Error with definition", { detail: { error: e, definition: this._definition } }), this._source = null;
    } finally {
      this._loaded = !0;
    }
    return this._source;
  }
}
class A extends ee {
  constructor(e, i, r = [], s) {
    super(e, i, s), this.featureSetSnippets = r, this.type = "featureSet";
  }
  get title() {
    return f(this._source) ? this._source.title ?? "" : { code: "featureset" };
  }
  async _loadSource() {
    if (this.loaded)
      return this._source;
    try {
      if (this._source = await X(this._definition), !this._source)
        throw new Error("Invalid definition");
      this.variables.push(new u(this._profile, this.title, this.featureSetSnippets, !0));
      const e = new u(this._profile, { code: "fields" });
      this.variables.push(e), e.variables = w(this._source.fields).sort(I(this._source)).map((r) => this._getFieldProperty(r));
      const i = await this._getRelationshipsProperty();
      i && this.variables.push(i);
    } catch (e) {
      h("error", this.type, "Error with definition", { detail: { error: e, definition: this._definition } }), this._source = null;
    } finally {
      this._loaded = !0;
    }
    return this._source;
  }
  toProfileVariableDefinition() {
    return { type: this.type, name: "", ...this.declaration, definition: this._definition };
  }
}
class Ge extends $ {
  constructor(e, i) {
    super(e, i), this.type = "featureSetCollection", this._featureSetCollections = null, this._loaded = !1, this._definition = i.declaration?.definition;
  }
  get informationUrl() {
    return !this.loaded || !this._featureSetCollections ? null : typeof this._featureSetCollections.source != "string" ? ie(O(this._featureSetCollections.source)) : null;
  }
  get informationType() {
    if (!this.loaded || !this._featureSetCollections)
      return "";
    if (typeof this._featureSetCollections.source == "string")
      return this._profile?.intlStrings.featureservice ?? "featureservice";
    switch (this._featureSetCollections.source.declaredClass) {
      case "esri.WebMap":
        return this._profile?.intlStrings.webmap ?? "webmap";
      case "esri.WebScene":
        return this._profile?.intlStrings.webscene ?? "webscene";
      default:
        return this._profile?.intlStrings.map ?? "map";
    }
  }
  async loadSource() {
    return v(this._loadPromise) && k(this._loadPromise) ? await this._loadPromise : (this._loadPromise = this._loadSource(), await this._loadPromise);
  }
  async _loadSource() {
    if (this.loaded)
      return this._featureSetCollections;
    try {
      if (this._featureSetCollections = await this._featureSetCollectionsFromDefinition(), !this._featureSetCollections)
        throw new Error("Invalid definition");
      const e = typeof this._featureSetCollections.source == "string" ? { code: this._featureSetCollections.source.endsWith("FeatureServer") ? "featureservice" : "mapservice" } : {
        code: "webmapformat",
        formatValues: {
          webMapTitle: O(this._featureSetCollections.source)?.title || "Untitled map"
        }
      }, i = new u(this._profile, e, [
        new l({
          profile: this._profile,
          label: this.snippet,
          description: "",
          snippet: this.snippet
        })
      ]), r = new u(this._profile, { code: "layers" }, this._featureSetCollections.layers), s = new u(this._profile, { code: "tables" }, this._featureSetCollections.tables);
      this.variables.push(i, r, s);
    } catch (e) {
      h("error", this.type, "Error with definition", { detail: { error: e, definition: this._definition } }), this._featureSetCollections = null;
    } finally {
      this._loaded = !0;
    }
    return this._featureSetCollections;
  }
  async _featureSetCollectionsFromDefinition() {
    return this._definition ? K(this._definition) ? await this._featureSetCollectionFromMap(this._definition) : C(this._definition) ? await this._featureSetCollectionFromUrl(this._definition.url) : z(this._definition) ? await this._featureSetCollectionFromPortalItem(this._definition.portalItem) : null : null;
  }
  async _featureSetCollectionFromMap(e) {
    _e(e) && await e.loadAll(), await Promise.all(e.allTables.map(async (r) => await r.load()));
    const i = this._profile?.policy?.filterFsCollectionLayersFromMap ?? (() => !0);
    return {
      layers: this._convertWebMapLayersToVariables(e.allLayers.filter(i)),
      tables: this._convertWebMapLayersToVariables(e.allTables),
      source: e
    };
  }
  async _featureSetCollectionFromPortalItem(e) {
    const i = new re(e);
    switch (await i.load(), i.type) {
      case "Web Map": {
        const r = new se({ portalItem: i });
        return await this._featureSetCollectionFromMap(r);
      }
      case "Web Scene": {
        const r = new ne({ portalItem: i });
        return await this._featureSetCollectionFromMap(r);
      }
      case "Feature Service":
        return await this._featureSetCollectionFromUrl(i.url);
      default:
        return h("error", this.type, "Unsupported portal item", { detail: { definition: e } }), null;
    }
  }
  async _featureSetCollectionFromUrl(e) {
    let i = e?.replace(/\/featureserver\/[0-9]*/iu, "/FeatureServer");
    if (i = i?.replace(/\/mapserver\/[0-9]*/iu, "/MapServer"), i = i?.split("?")[0], !i)
      return null;
    const r = await Ve(i), s = Promise.all(
      r.layers.map(async (c) => {
        const p = new g({ url: `${i}/${c.id}` });
        return await p.load(), this._createFeatureSetVariable(p);
      })
    ), n = Promise.all(
      r.tables.map(async (c) => {
        const p = new g({ url: `${i}/${c.id}` });
        return await p.load(), this._createFeatureSetVariable(p);
      })
    ), [a, o] = await Promise.all([s, n]);
    return { layers: a, tables: o, source: i };
  }
  _convertWebMapLayersToVariables(e) {
    const i = [];
    return e.toArray().reverse().forEach((r) => {
      if (q(r)) {
        i.push(this._createFeatureSetVariable(r, !0));
        return;
      }
    }), i;
  }
  _createFeatureSetVariable(e, i = !1) {
    return new A(
      this,
      {
        profile: this._profile,
        declaration: { name: e.title ?? "", definition: e },
        label: i ? e.title : e.sourceJSON.name ?? e.title,
        description: "",
        nonInteractive: !0
      },
      this._makeFeatureSetSnippets(e, i)
    );
  }
  _makeFeatureSetSnippets(e, i = !1) {
    if (!this._profile?.supportFeatureSetFunctions)
      return [];
    if (i) {
      const r = `FeatureSetById(${this.snippet}, "${e.id}")`, s = `FeatureSetByName(${this.snippet}, "${e.title}")`;
      return [
        new l({ profile: this._profile, label: r, description: "", snippet: r }),
        new l({ profile: this._profile, label: s, description: "", snippet: s })
      ];
    } else {
      const r = `FeatureSetById(${this.snippet}, "${e.layerId}")`;
      return [new l({ profile: this._profile, label: r, description: "", snippet: r })];
    }
  }
  toProfileVariableDefinition() {
    return { type: this.type, name: "", ...this.declaration, definition: this._definition };
  }
}
class at extends _ {
  constructor(e, i, r = "en", s = {}) {
    super(void 0, {
      profile: null,
      declaration: { properties: [] }
    }), this.definition = e, this.intlStrings = i, this.locale = r, this.policy = s, this.variables = [], this._profile = this, this.loadPropertyDeclarations(e?.variables);
  }
  /**
   * Returns true if the profile supports feature set functions for snippets.
   */
  get supportFeatureSetFunctions() {
    return this.definition?.bundles?.includes("data-access") ?? !1;
  }
  /**
   * Returns the EditorProfile as a json. The EditorProfile may have been updated. This function allows to
   * get the new json representing mutations.
   */
  toEditorProfileDefinition() {
    return {
      ...this.definition,
      variables: this.dictionaryVariables.map((e) => e.toProfileVariableDefinition())
    };
  }
}
const Ee = {
  locale: "en"
};
class lt {
  // #endregion
  constructor(e, i) {
    this.languageId = e, this._apiConfig = i, this._onDidChange = new E(), this._modelToProfileMap = /* @__PURE__ */ new Map(), this._modelToApiContextMap = /* @__PURE__ */ new Map(), this._localeToApiLibraryPromiseMap = /* @__PURE__ */ new Map(), this._onModelContextDidChange = new E(), this._onDidModelContextChangeTimeout = -1, this.workerHost = {
      getApiLibrary: async (r) => await this.getApiLibrary(r)
    }, he().then((r) => {
      r.onWillDisposeModel((s) => {
        this.disposeForModel(s.uri);
      });
    });
  }
  // #region Protected methods
  _fireModelContextDidChange(e) {
    this._onDidModelContextChangeTimeout === -1 && (this._onDidModelContextChangeTimeout = window.setTimeout(() => {
      this._onDidModelContextChangeTimeout = -1, this._onModelContextDidChange.fire(e);
    }, 0));
  }
  _getApiKey(e) {
    return j.isUri(e) || (e = j.parse(e)), e.toString();
  }
  // #endregion
  // #region Public methods
  get onDidChange() {
    return this._onDidChange.event;
  }
  /**
   * Dispose any cached resources for the model
   */
  disposeForModel(e) {
    const i = this._getApiKey(e);
    this._modelToProfileMap.delete(i), this._modelToApiContextMap.delete(i) && this._fireModelContextDidChange(i);
  }
  /**
   * Returns the editor profile for the given model id.
   * @param modelId The model id for which to get the editor profile.
   * @returns The editor profile for the model.
   */
  getEditorProfileForModel(e) {
    return this._modelToProfileMap.get(this._getApiKey(e));
  }
  /**
   * Returns the API context for the given model id.
   * Returns the default context if the model has no context.
   * @param modelId The model id for which to get the API context.
   * @returns The API context for the model.
   */
  getApiContextForModel(e) {
    return this._modelToApiContextMap.get(this._getApiKey(e)) ?? Ee;
  }
  /**
   * Set or update api context for the given model id.
   * @param modelId The model id for which to set the context.
   * @param apiContext The api context to set.
   */
  updateApiContextForModel(e, i) {
    const r = this._getApiKey(e), s = this._modelToApiContextMap.get(r) ?? {};
    this._modelToApiContextMap.set(r, { ...s, ...i }), this._fireModelContextDidChange(r);
  }
  get onModelContextDidChange() {
    return this._onModelContextDidChange.event;
  }
  /**
   * Gets the API library for the given model id.
   * @param modelId The model id for which to get the API library.
   * @returns The API library for the model.
   */
  async getApiLibraryForModel(e) {
    const i = this.getApiContextForModel(e), r = this.getApiLibrary(i.locale ?? "en");
    return (await ye(r, i)).categories;
  }
  // #endregion
  //#region Private methods
  async fetchApiLibrary(e) {
    try {
      const { apiPath: i, apiPrefix: r } = this._apiConfig, s = fe(`${i}/${r}${e}.json`), n = await fetch(s);
      return n.ok ? await n.json() : [];
    } catch {
      return [];
    }
  }
  async getApiLibrary(e) {
    const i = de(e);
    return this._localeToApiLibraryPromiseMap.has(i) || this._localeToApiLibraryPromiseMap.set(i, this.fetchApiLibrary(i)), await this._localeToApiLibraryPromiseMap.get(i) ?? [];
  }
  // #endregion
}
export {
  at as E,
  lt as L,
  it as a,
  rt as b,
  et as c,
  tt as d,
  J as e,
  nt as f,
  q as g,
  st as i,
  ot as m
};
