import {
  sample_match_termvaluesetting
} from "./chunk-YZK37YCC.js";
import {
  compute_bins
} from "./chunk-QH6W3NVF.js";
import {
  isNumeric
} from "./chunk-JNITUVXP.js";
import {
  __commonJS,
  __toESM
} from "./chunk-HFNDKYVF.js";

// ../node_modules/partjson/dist/partjson.umd.js
var require_partjson_umd = __commonJS({
  "../node_modules/partjson/dist/partjson.umd.js"(exports, module) {
    !(function(t, e) {
      "object" == typeof exports && "undefined" != typeof module ? module.exports = e() : "function" == typeof define && define.amd ? define(e) : (t = t || self).Partjson = e();
    })(exports, function() {
      "use strict";
      class t {
        constructor(t2) {
          this.Pj = t2, this.opts = ["@delimit", "@errmode"], this.contexts = ["@branch", "@parent", "@root", "@self", "@values", "@key"], this.filters = ["@split()", "@before()", "@join()", "@ignore()"], this.post = ["@after()", "@dist()", "@end()"], this.terms = [...this.opts, ...this.contexts, ...this.filters, ...this.post];
        }
        setFxn(t2, e2, s2, r2) {
          this[t2] ? s2[t2] = this[t2](r2, e2, s2) : e2.errors.push(["key", "UNRECOGNIZED-RESERVED-" + t2]);
        }
        trueFxn() {
          return true;
        }
        notDefined(t2) {
          return void 0 === t2;
        }
      }
      t.prototype["@split"] = function(t2) {
        const e2 = t2.slice(1, -2), s2 = this.Pj.opts["="][e2];
        if (!s2) throw `missing @split() function ${e2}`;
        this.Pj.split = s2;
      }, t.prototype["@before"] = function(t2, e2) {
        const s2 = t2.slice(1, -2), r2 = this.Pj.opts["="][s2];
        return r2 || (e2.errors.push(["val", "MISSING-" + e2.term + "-FXN", s2]), this.trueFxn);
      }, t.prototype["@after"] = t.prototype["@before"], t.prototype["@done"] = t.prototype["@before"], t.prototype["@join"] = function(t2, e2, s2) {
        return (s3, r2) => {
          let o2 = true;
          for (const i2 in t2) {
            const n2 = t2[i2].slice(1, -2), l2 = this.Pj.opts["="][n2];
            if (l2) {
              const t3 = l2(s3, r2, i2);
              t3 ? this.Pj.joins.set(i2, t3) : o2 = false;
            } else e2.errors.push(["val", "MISSING-@join-FXN", n2]);
          }
          return o2;
        };
      }, t.prototype["@dist"] = function(t2, e2) {
        const s2 = Array.isArray(t2) ? t2 : [t2], r2 = {};
        for (const t3 of s2) r2[t3] = this.Pj.converter.subs["@"](this.Pj, t3);
        return (t3) => {
          t3["@dist"] = ((s3) => {
            for (const o2 in r2) {
              const i2 = (0, r2[o2])(null, t3);
              i2 ? Array.isArray(i2) ? i2.includes(s3) || i2.push(s3) : t3.errors.push([e2, "NON-ARRAY-DIST-TARGET", o2]) : t3.errors.push([e2, "MISSING-DIST-TARGET", o2]);
            }
          });
        };
      }, t.prototype["@ignore"] = function(t2, e2, s2) {
        if (!t2["@ignore()"]) return e2;
        const r2 = Array.isArray(t2["@ignore()"]) || "string" == typeof t2["@ignore()"] || "object" != typeof t2["@ignore()"], o2 = r2 ? { "@": t2["@ignore()"] } : t2["@ignore()"], i2 = {};
        for (const t3 in o2) {
          const e3 = o2[t3];
          if (Array.isArray(e3)) i2[t3] = ((t4) => e3.includes(t4));
          else if ("string" == typeof e3 && "=" == e3[0]) {
            const r3 = this.Pj.opts["="][e3.slice(1, -2)];
            r3 ? i2[t3] = r3 : (s2.errors.push(["val", "MISSING-@ignore()-FXN", e3]), i2[t3] = this.notDefined);
          } else s2.errors.push(["val", "UNSUPPORTED-@ignore()-VALUE", e3]), i2[t3] = this.notDefined;
        }
        return r2 ? i2 : Object.assign({}, e2, i2);
      };
      class e {
        constructor(t2) {
          this.Pj = t2, this.allowedKeyTypes = /* @__PURE__ */ new Set(["string", "number"]);
        }
        getFxn(t2, e2) {
          const [s2, r2] = this.Pj.converter.default(this.Pj, t2, e2, t2.term);
          if (s2) return this[r2.conv](s2, t2);
        }
        getAllowedKeys(t2, e2, s2, r2) {
          if (!Array.isArray(t2)) return r2.errors.push(["key", "NON-ARRAY-KEYS", e2]), [];
          const o2 = [];
          for (const i2 of t2) s2.ignore(i2) || (this.allowedKeyTypes.has(typeof i2) ? o2.push(i2) : r2.errors.push([s2, "INVALID-RESULT-KEY", e2]));
          return o2;
        }
      }
      e.prototype[""] = function(t2, e2) {
        return (s2, r2) => this.getAllowedKeys([t2(s2, r2)], s2, e2, r2);
      }, e.prototype["()"] = e.prototype[""], e.prototype["[]"] = function(t2, e2) {
        return (s2, r2) => this.getAllowedKeys(t2(s2, r2), s2, e2, r2);
      }, e.prototype["(]"] = e.prototype["[]"];
      class s {
        constructor(t2) {
          this.Pj = t2;
        }
        getFxn(t2, e2) {
          return this[this.getValType(t2.templateVal) + "Filler"](t2, e2, t2.templateVal);
        }
        getValType(t2) {
          return "string" == typeof t2 ? "str" : Array.isArray(t2) ? "arr" : t2 && "object" == typeof t2 ? "obj" : "default";
        }
        strFiller(t2, e2, s2, r2) {
          const [o2, i2] = this.Pj.converter.default(this.Pj, t2, e2, s2);
          if (!o2) return;
          const n2 = (r2 || i2.aggr) + "," + i2.conv;
          return n2 in this ? this[n2](o2, t2) : void 0;
        }
        arrFiller(t2, e2, s2) {
          const r2 = this.getValType(s2[0]);
          return "str" == r2 ? this.strFiller(t2, e2, s2[0], "[]") : "arr" == r2 ? this["[[,]]"](s2[0], t2) : "obj" == r2 ? this["[{}]"](s2[0], t2) : this.defaultFiller(t2, e2, s2);
        }
        objFiller(t2, e2, s2) {
          return this.Pj.parseTemplate(s2, t2.inheritedIgnore, t2.lineage), (t3, e3, r2) => {
            this.Pj.setResultContext("{}", e3, r2), this.Pj.processRow(t3, s2, r2[e3]);
          };
        }
        defaultFiller(t2, e2, s2) {
          const r2 = JSON.stringify(s2);
          return (t3, e3, s3) => {
            s3[e3] = JSON.parse(r2);
          };
        }
        getArrSeed(t2) {
          const e2 = t2.templateVal && t2.templateVal.length > 1 ? t2.templateVal[1] : 1;
          if ("set" == e2) return (t3, e3, s2) => {
            e3 in t3 ? Array.isArray(t3[e3]) && (t3[e3] = new Set(t3[e3])) : t3[e3] = /* @__PURE__ */ new Set(), t3[e3].add(s2);
          };
          if (0 == e2) return (t3, e3, s2) => {
            e3 in t3 || (t3[e3] = []), t3[e3].push(s2);
          };
          if (this.isNumeric(e2)) {
            const t3 = /* @__PURE__ */ new Map();
            return (s2, r2, o2) => {
              r2 in s2 || (s2[r2] = []), t3.has(s2[r2]) || t3.set(s2[r2], /* @__PURE__ */ new Map());
              const i2 = t3.get(s2[r2]);
              i2.has(o2) || i2.set(o2, 0);
              const n2 = i2.get(o2);
              n2 < e2 && (s2[r2].push(o2), i2.set(o2, n2 + 1));
            };
          }
        }
        isNumeric(t2) {
          return !isNaN(parseFloat(t2)) && isFinite(t2) && "" !== t2;
        }
      }
      s.prototype[","] = function(t2, e2) {
        return (s2, r2, o2, i2) => {
          const n2 = t2(s2, i2);
          e2.ignore(n2, r2, s2) || (o2[r2] = n2);
        };
      }, s.prototype[",()"] = s.prototype[","], s.prototype[",[]"] = s.prototype[","], s.prototype[",(]"] = s.prototype[","], s.prototype["[],"] = function(t2, e2) {
        const s2 = this.getArrSeed(e2);
        if (s2) return (r2, o2, i2, n2) => {
          const l2 = t2(r2, n2);
          e2.ignore(l2, o2, r2, n2) || s2(i2, o2, l2);
        };
        e2.errors.push(["val", "INVALID-[]-OPTION"]);
      }, s.prototype["[],()"] = s.prototype["[],"], s.prototype["[],[]"] = function(t2, e2) {
        const s2 = this.getArrSeed(e2);
        return (r2, o2, i2, n2) => {
          const l2 = t2(r2, n2);
          if (Array.isArray(l2)) for (const t3 of l2) e2.ignore(t3, o2, r2, n2) || s2(i2, o2, t3);
          else n2.errors.push([e2, "NON-ARRAY-VALS", r2]);
        };
      }, s.prototype["[],(]"] = s.prototype["[],[]"], s.prototype["[{}]"] = function(t2, e2) {
        this.Pj.parseTemplate(t2, e2.inheritedIgnore, e2.lineage);
        const s2 = e2.templateVal && e2.templateVal.length > 1 ? e2.templateVal[1] : "";
        if (!s2) return (e3, s3, r2) => {
          this.Pj.setResultContext("[]", s3, r2);
          const o2 = this.Pj.setResultContext("{}", r2[s3].length, r2[s3]);
          this.Pj.processRow(e3, t2, o2);
        };
        if ("string" == typeof s2) {
          const [r2, o2] = this.Pj.converter.default(this.Pj, Object.assign({}, { templateVal: s2 }), e2.inheritedIgnore, s2);
          return o2.aggr || o2.skip || o2.timing ? void e2.errors.push(["val", "INVALID-[{}]-OPTION-TOKEN"]) : (o3, i2, n2, l2) => {
            const c2 = this.Pj.setResultContext("[]", i2, n2, true), p = this.Pj.contexts.get(c2).tracker, h = r2(o3, l2), u = "]" == s2.slice(-1) ? h : [h];
            if (Array.isArray(u)) for (const e3 of u) if (p.has(e3)) this.Pj.processRow(o3, t2, p.get(e3));
            else {
              const s3 = this.Pj.setResultContext("{}", c2.length, c2, false, e3, o3, t2);
              s3 && (p.set(e3, s3), this.Pj.processRow(o3, t2, s3));
            }
            else l2.errors.push([e2, "NON-ARRAY-VALS", o3]);
          };
        }
        e2.errors.push(["val", "INVALID-[{}]-OPTION"]);
      }, s.prototype["[[,]]"] = function(t2, e2) {
        const s2 = [];
        for (const r2 of t2) {
          const t3 = Object.assign({}, e2, { templateVal: r2 });
          s2.push(this.getFxn(t3, e2.inheritedIgnore));
        }
        return "map" != (e2.templateVal[1] ? e2.templateVal[1] : "") ? (t3, e3, r2) => {
          e3 in r2 || (r2[e3] = []);
          const o2 = [];
          for (const e4 in s2) s2[+e4](t3, +e4, o2);
          r2[e3].push(o2);
        } : (t3, e3, r2) => {
          e3 in r2 ? r2[e3] instanceof Map || (r2[e3] = new Map(r2[e3])) : r2[e3] = /* @__PURE__ */ new Map();
          const o2 = [];
          s2[0](t3, 0, o2), r2[e3].has(o2[0]) && (o2[1] = r2[e3].get(o2[0])), s2[1](t3, 1, o2), r2[e3].set(o2[0], o2[1]);
        };
      }, s.prototype["+,"] = function(t2, e2) {
        return (s2, r2, o2, i2) => {
          r2 in o2 || (o2[r2] = 0);
          const n2 = t2(s2, i2);
          e2.ignore(n2, r2, s2, i2) || (this.isNumeric(n2) ? o2[r2] += +n2 : i2.errors.push([e2, "NON-NUMERIC-INCREMENT", s2]));
        };
      }, s.prototype["+,()"] = s.prototype["+,"], s.prototype["+,[]"] = function(t2, e2) {
        return (s2, r2, o2, i2) => {
          r2 in o2 || (o2[r2] = 0);
          const n2 = t2(s2, i2);
          if (Array.isArray(n2)) for (const t3 of n2) e2.ignore(t3, r2, s2, i2) || (this.isNumeric(t3) ? o2[r2] += +t3 : i2.errors.push([e2, "NON-NUMERIC-INCREMENT", s2]));
          else e2.errors.push(["val", "NON-ARRAY-VALS", s2]);
        };
      }, s.prototype["+,(]"] = s.prototype["+,[]"], s.prototype["-,"] = function(t2, e2) {
        return (s2, r2, o2, i2) => {
          r2 in o2 || (o2[r2] = 0);
          const n2 = t2(s2, i2);
          e2.ignore(n2, r2, s2, i2) || (this.isNumeric(n2) ? o2[r2] += -n2 : i2.errors.push([e2, "NON-NUMERIC-DECREMENT", s2]));
        };
      }, s.prototype["-,()"] = s.prototype["-,"], s.prototype["-,[]"] = function(t2, e2) {
        return (s2, r2, o2, i2) => {
          const n2 = t2(s2, i2);
          if (Array.isArray(n2)) {
            r2 in o2 || (o2[r2] = 0);
            for (const t3 of n2) e2.ignore(t3, r2, s2, i2) || (o2[r2] += -t3);
          } else e2.errors.push(["val", "NON-ARRAY-VALS", s2]);
        };
      }, s.prototype["-,(]"] = s.prototype["-,[]"], s.prototype["<,"] = function(t2, e2) {
        return (s2, r2, o2, i2) => {
          const n2 = t2(s2, i2);
          if (e2.ignore(n2, r2, s2, i2)) return;
          const l2 = +n2;
          this.isNumeric(l2) ? r2 in o2 ? o2[r2] < l2 && (o2[r2] = l2) : o2[r2] = l2 : i2.errors.push([e2, "NON-NUMERIC-THAN", s2]);
        };
      }, s.prototype["<,()"] = s.prototype["<,"], s.prototype["<,[]"] = function(t2, e2) {
        return (s2, r2, o2, i2) => {
          const n2 = t2(s2, i2);
          if (Array.isArray(n2)) for (const t3 of n2) {
            if (e2.ignore(t3, r2, s2, i2)) return;
            if (!this.isNumeric(t3)) return void i2.errors.push([e2, "NON-NUMERIC-THAN", s2]);
            const n3 = +t3;
            r2 in o2 ? o2[r2] < n3 && (o2[r2] = n3) : o2[r2] = n3;
          }
          else e2.errors.push(["val", "NON-ARRAY-VALS", s2]);
        };
      }, s.prototype["<,(]"] = s.prototype["<,[]"], s.prototype[">,"] = function(t2, e2) {
        return (s2, r2, o2, i2) => {
          const n2 = t2(s2, i2);
          e2.ignore(n2, r2, s2, i2) || (this.isNumeric(n2) ? r2 in o2 ? o2[r2] > n2 && (o2[r2] = n2) : o2[r2] = n2 : i2.errors.push([e2, "NON-NUMERIC-THAN", s2]));
        };
      }, s.prototype[">,()"] = s.prototype[">,"], s.prototype[">,[]"] = function(t2, e2) {
        return (s2, r2, o2, i2) => {
          const n2 = t2(s2, i2);
          if (Array.isArray(n2)) for (const t3 of n2) {
            if (e2.ignore(t3, r2, s2, i2)) return;
            if (!this.isNumeric(t3)) return void i2.errors.push([e2, "NON-NUMERIC-THAN", s2]);
            const n3 = +t3;
            r2 in o2 ? o2[r2] > n3 && (o2[r2] = n3) : o2[r2] = n3;
          }
          else e2.errors.push(["val", "NON-ARRAY-VALS", s2]);
        };
      }, s.prototype[">,(]"] = s.prototype[">,[]"];
      class r {
        constructor(t2) {
          this.Pj = t2, this.allErrSet = /* @__PURE__ */ new Set(), this.allErrObj = /* @__PURE__ */ Object.create(null), this.mode = { input: "{}", result: "{}-", root: "", console: "{}" }, this.modeKeys = ["input", "result", "root", "console"], this.setMode();
        }
        setMode(t2 = {}) {
          Array.isArray(t2) ? this.modeKeys.forEach((e2, s2) => this.mode[e2] = t2[s2]) : "object" == typeof t2 && this.modeKeys.forEach((e2) => {
            e2 in t2 && (this.mode[e2] = t2[e2]);
          });
        }
        clear(t2 = {}) {
          this.allErrSet.clear(), this.allErrObj = /* @__PURE__ */ Object.create(null), this.setMode(t2);
        }
        markErrors(t2, e2) {
          if (!e2) return;
          const s2 = "[]" == this.mode.result.slice(0, 2) ? [] : {};
          for (const r2 in e2.filler.inputs) {
            const o2 = e2.filler.inputs[r2];
            for (const e3 of o2.errors) {
              const [r3, i2, n2] = e3;
              "key" == r3 ? (this.track(s2, e3, o2.lineage.join(this.Pj.delimit)), this.mode.input && (t2["{{ " + i2 + " }} " + o2.term] = o2.templateVal)) : "val" == r3 && (Array.isArray(o2.templateVal) ? (this.track(s2, e3, o2.templateVal[0]), this.mode.input && (t2[o2.term] = ["{{ " + i2 + " }} ", ...o2.templateVal])) : "string" == typeof o2.templateVal ? (this.track(s2, e3, o2.templateVal), this.mode.input && (t2[o2.term] = "{{ " + i2 + " }} " + o2.templateVal)) : (this.track(s2, e3, o2.templateVal), this.mode.input && (t2[o2.term] = "{{ " + i2 + " }} ")));
            }
          }
          if (e2.errors.length) {
            const r2 = {};
            t2["@errors"] = r2;
            for (const t3 of e2.errors) {
              const [e3, o2, i2] = t3;
              if (this.track(s2, t3, e3.term), !this.mode.input) continue;
              const n2 = "{{ " + o2 + " }} " + e3.term;
              n2 in r2 || (r2[n2] = 0), r2[n2] += 1;
            }
          }
          if (e2.filler.errors.length) for (const t3 of e2.filler.errors) this.track(s2, t3, t3[2], false);
          Object.keys(s2).length && this.mode.result && (t2["@errors"] = s2);
        }
        track(t2, e2, s2, r2 = true) {
          this.allErrSet.add(e2), this.trackAsObj(this.allErrObj, e2, s2), r2 && "-" == this.mode.result.slice(-1) || (Array.isArray(t2) ? t2.push(e2) : this.trackAsObj(t2, e2, s2));
        }
        trackAsObj(t2, e2, s2) {
          const [r2, o2, i2] = e2;
          o2 in t2 || (t2[o2] = /* @__PURE__ */ Object.create(null)), s2 in t2[o2] || (t2[o2][s2] = i2 ? [] : 0), i2 ? t2[o2][s2].includes(i2) || t2[o2][s2].push(i2) : t2[o2][s2] += 1;
        }
        log() {
          const t2 = [...this.allErrSet];
          if (t2.length) {
            if (this.mode.root) {
              const e2 = this.mode.root;
              this.Pj.tree["@errorsAll"] = "[]" == e2 ? t2 : this.allErrObj;
            }
            if (this.mode.console) {
              const e2 = this.mode.console.slice(0, 2);
              console.log("[]" == e2 ? t2 : this.allErrObj);
            }
          }
        }
      }
      function o(t2, e2) {
        const s2 = t2.skipSymbols.includes(e2[0]) ? e2[0] : "", r2 = e2.slice(s2.length, s2.length + 3), o2 = t2.timeSymbols.includes(r2) ? r2 : "", i2 = s2.length + o2.length, n2 = e2[i2], l2 = e2.slice(-2), c2 = t2.aggrSymbols.includes(n2) && n2 != e2 ? n2 : "", p = t2.convSymbols.includes(l2) && l2 != e2 ? l2 : "", h = c2 && p ? e2.slice(i2 + 1, -2) : c2 ? e2.slice(i2 + 1) : p ? e2.slice(i2, -2) : s2 || o2 ? e2.slice(i2) : e2, u = t2.subsSymbols.includes(h[0]) ? h[0] : "", a = c2 + u + p, f = u ? h.slice(1) : h;
        return [h, a, { skip: s2, time: o2, aggr: c2, subs: u, stem: f, conv: p, subterm: h }, t2.steps.indexOf(o2)];
      }
      const i = { "#": function(t2, e2, s2) {
        t2.commentedTerms.has(s2) || t2.commentedTerms.set(s2, []), t2.commentedTerms.get(s2).push(e2);
      }, "*": function(t2, e2, s2) {
        t2.focusTemplate[s2.term.slice(1)] = s2.templateVal;
      }, "": function(t2, e2, s2) {
        return t2.valFiller.isNumeric(e2) ? () => +e2 : () => e2;
      }, $: function(t2, e2, s2) {
        if ("$" == e2 || e2 == "$" + t2.delimit) return (t3) => t3;
        if (e2.includes(t2.delimit)) {
          const s3 = e2.slice(1).split(t2.delimit);
          "" == s3[0] && s3.shift();
          const r2 = (t3, e3) => t3 ? t3[e3] : void 0;
          return (t3) => s3.reduce(r2, t3);
        }
        {
          const t3 = e2.slice(1);
          return (e3) => e3[t3];
        }
      }, "=": function(t2, e2, s2) {
        const r2 = e2.slice(1).split(t2.delimit).reduce((t3, e3) => t3 && e3 in t3 ? t3[e3] : void 0, t2.opts["="]);
        if (r2) return (t3) => r2;
        s2.errors.push(["val", "MISSING-EXTERNAL-SUBS"]);
      }, "@": function(t2, e2, s2) {
        if (!t2.reserved.opts.includes(e2)) {
          if ("@" == e2 || e2 == "@" + t2.delimit) return (t3, e3) => e3.self;
          if (e2.includes(t2.delimit)) {
            const r2 = e2.split(t2.delimit), o2 = (r3, o3) => {
              if ("@" == o3[0] && o3.length > 1 && !t2.reserved.contexts.includes(o3)) return s2.errors.push(["val", "UNRECOGNIZED-CONTEXT-" + e2, s2.lineage.join(".") + "." + o3]), [null, null];
              const [i2, n2] = r3;
              return i2 && o3 ? "@" == o3 ? [n2.self, n2] : "@values" == o3 ? [Object.values(i2), n2] : "@" == o3[0] ? [n2[o3.slice(1)], t2.contexts.get(n2[o3.slice(1)])] : [i2[o3], t2.contexts.get(i2[o3])] : [null, null];
            };
            return (t3, e3) => r2.reduce(o2, [e3.self, e3])[0];
          }
          if (t2.reserved.contexts.includes(e2)) {
            const t3 = e2.slice(1);
            return (e3, s3) => s3[t3];
          }
          s2.errors.push(["val", "UNRECOGNIZED-CONTEXT-" + e2]);
        }
      }, "&": function(t2, e2, s2) {
        const r2 = e2.slice(1).split(t2.delimit), o2 = r2.shift();
        if (r2.length) {
          if (1 == r2.length) {
            const e3 = r2[0];
            return () => {
              const s3 = t2.joins.get(o2);
              return s3 ? s3[e3] : null;
            };
          }
          {
            const e3 = (t3, e4) => t3 ? t3[e4] : null;
            t2.joins.get(o2);
            return (s3) => r2.reduce(e3, t2.joins.get(o2));
          }
        }
        return () => t2.joins.get(o2);
      } }, n = { "": function(t2, e2, s2) {
        return t2;
      }, "()": function(t2, e2, s2) {
        if ("=" == s2.subs) {
          const r2 = t2();
          return "function" != typeof r2 ? void e2.errors.push(["val", "NOT-A-FUNCTION", s2.subs + s2.term + s2.conv]) : r2;
        }
        return (s3, r2) => {
          const o2 = t2(s3, r2);
          if ("function" == typeof o2) return o2(s3, r2);
          e2.errors.push(["val", "NOT-A-FUNCTION", s3]);
        };
      } };
      n["[]"] = n[""], n["(]"] = n["()"];
      var l = Object.freeze({ __proto__: null, default: function(t2, e2, s2, r2) {
        const [l2, c2, p] = o(t2, r2);
        if (t2.reserved.opts.includes(l2)) return [];
        const h = l2 + p.conv;
        if (e2.ignore = h in s2 ? s2[h] : s2["@"], p.skip && "~" != p.skip) return i[p.skip](t2, l2, e2), [];
        if (p.subs in i) {
          const s3 = i[p.subs](t2, l2, e2);
          return s3 ? [n[p.conv](s3, e2, p), p] : [];
        }
        return e2.errors.push(["val", "UNSUPPORTED-SYMBOL-" + p.subs]), [];
      }, parseTerm: o, subs: i, conv: n });
      class c {
        constructor(o2 = {}) {
          this.defaultOpts = { template: {}, seed: "{}", "=": {} }, this.opts = Object.assign(this.defaultOpts, o2), this.delimit = ".", this.subsSymbols = ["$", "=", "@", "&"], this.convSymbols = ["()", "[]", "(]"], this.aggrSymbols = ["+", "-", "<", ">"], this.timePost = ["_0:", "_1:", "_2:", "_3:", "_4:", "_5:", "_6:", "_7:", "_8:", "_9:"], this.timeSymbols = [":__", "_:_", "__:", ...this.timePost], this.skipSymbols = ["#", "*", "~"], this.steps = [":__", "", "_:_"], this.errors = new r(this), this.reserved = new t(this), this.keyFiller = new e(this), this.valFiller = new s(this), this.commentedTerms = /* @__PURE__ */ new Map(), this.joins = /* @__PURE__ */ new Map(), this.fillers = /* @__PURE__ */ new Map(), this.contexts = /* @__PURE__ */ new Map(), this.temps = /* @__PURE__ */ new Map(), this.refresh();
        }
        refresh(t2 = {}) {
          this.times = { start: +/* @__PURE__ */ new Date() }, Object.assign(this.opts, t2), "string" != typeof this.opts.template && (this.opts.template = JSON.stringify(this.opts.template));
          const e2 = JSON.parse(this.opts.template);
          this.errors.clear(e2["@errmode"]), e2["@delimit"] && (this.delimit = e2["@delimit"]), this.commentedTerms.clear(), this.joins.clear(), this.fillers.clear(), this.contexts.clear(), this.temps.clear(), delete this.tree, this.tree = this.setResultContext(this.opts.seed), this.focusTemplate = /* @__PURE__ */ Object.create(null), this.parseTemplate(e2, { "@": this.reserved.notDefined }), this.times.parse = +/* @__PURE__ */ new Date() - this.times.start, Object.keys(this.focusTemplate).length ? (this.parseTemplate(this.focusTemplate, { "@": this.reserved.notDefined }), this.template = this.focusTemplate) : this.template = e2, this.postLoopTerms = /* @__PURE__ */ Object.create(null), this.done = [], this.opts.data && this.add(this.opts.data, false), this.errors.log(this.fillers);
        }
        setResultContext(t2, e2 = null, s2 = null, r2 = false, o2, i2 = null, n2 = null) {
          const l2 = null !== e2 && e2 in s2 ? s2[e2] : JSON.parse(t2);
          if (this.contexts.has(l2)) return l2;
          const c2 = { branch: e2, parent: s2, context: this.contexts.get(s2), self: l2, root: this.tree ? this.tree : l2, joins: this.joins, errors: [], key: o2 };
          if (r2 && (c2.tracker = /* @__PURE__ */ new Map()), i2 && n2) {
            const t3 = this.fillers.get(n2);
            if (!t3["@before"](i2, c2)) return;
            if (t3["@join"] && !t3["@join"](i2, c2)) return;
          }
          return this.contexts.set(l2, c2), null !== e2 && (s2[e2] = l2), l2;
        }
        parseTemplate(t2, e2, s2 = []) {
          const r2 = /* @__PURE__ */ Object.create(null);
          r2.inputs = /* @__PURE__ */ Object.create(null), r2["@before"] = this.reserved.trueFxn, r2["@after"] = this.reserved.trueFxn, r2.postTerms = {}, r2.errors = [];
          const i2 = this.reserved["@ignore"](t2, e2, r2);
          r2["@ignore"] = i2, this.fillers.set(t2, r2);
          const n2 = this.steps.map((t3) => []);
          for (const e3 in t2) {
            const [l2, c2, p, h] = o(this, e3), u = t2[e3], a = r2.inputs[e3] = { term: e3, subterm: l2, symbols: c2, keyTokens: p, templateVal: u, lineage: [...s2, e3], inheritedIgnore: i2, errors: [] };
            "@()" == c2 ? this.reserved.setFxn(l2, a, r2, u) : (a.keyFxn = this.keyFiller.getFxn(a, i2), a.keyFxn && (a.valFxn = this.valFiller.getFxn(a, i2), "__:" == p.time || this.timePost.includes(p.time) ? (r2.postTerms[p.time] || (r2.postTerms[p.time] = []), r2.postTerms[p.time].includes(e3) || r2.postTerms[p.time].push(e3)) : n2[h].push(e3)));
          }
          r2.steps = n2.filter((t3) => t3.length);
        }
        add(t2, e2 = true) {
          this.times.start || (this.times.start = +/* @__PURE__ */ new Date()), e2 && this.errors.clear(), this.joins.clear();
          for (const e3 of t2) if (this.split) for (const t3 of this.split(e3)) this.processRow(t3, this.template, this.tree), this.joins.clear();
          else this.processRow(e3, this.template, this.tree), this.joins.clear();
          this.processResult(this.tree);
          for (const t3 of this.timePost) if (this.postLoopTerms[t3]) for (const e3 of this.postLoopTerms[t3]) this.postLoop(e3.self, e3, t3);
          for (const t3 of this.done) t3.done(t3.self, t3);
          for (const [t3, e3] of this.temps) for (const s2 of e3) delete t3[s2];
          this.times.total = +/* @__PURE__ */ new Date() - this.times.start, delete this.times.start, e2 && this.errors.log();
        }
        processRow(t2, e2, s2) {
          const r2 = this.contexts.get(s2), o2 = this.fillers.get(e2);
          if (r2.filler = o2, o2["@before"](t2, r2) && (!o2["@join"] || o2["@join"](t2, r2))) {
            for (const e3 of o2.steps) for (const i2 of e3) {
              const e4 = o2.inputs[i2];
              if (e4.keyFxn && e4.valFxn) {
                const o3 = e4.keyFxn(t2, r2);
                for (const i3 of o3) e4.valFxn(t2, i3, s2, r2), "~" == e4.keyTokens.skip && (this.temps.has(s2) || this.temps.set(s2, /* @__PURE__ */ new Set()), this.temps.get(s2).add(i3));
              }
            }
            o2["@after"](t2, r2), o2["@dist"] && o2["@dist"](r2), o2["@done"] && !this.done.includes(r2) && (r2.done = o2["@done"], this.done.push(r2));
            for (const t3 in o2.postTerms) this.postLoopTerms[t3] || (this.postLoopTerms[t3] = []), this.postLoopTerms[t3].includes(r2) || this.postLoopTerms[t3].push(r2);
            return true;
          }
        }
        postLoop(t2, e2, s2 = "__:") {
          if (e2 && e2.filler && e2.filler.postTerms[s2]) for (const r2 of e2.filler.postTerms[s2]) {
            const s3 = e2.filler.inputs[r2];
            if (s3.keyFxn && s3.valFxn) {
              const r3 = s3.keyFxn(null, e2);
              for (const o2 of r3) s3.valFxn(null, o2, t2, e2);
            }
          }
        }
        processResult(t2) {
          const e2 = this.contexts.get(t2);
          this.postLoop(t2, e2, "__:");
          for (const e3 in t2) {
            const s2 = t2[e3];
            if (s2) {
              if (Array.isArray(s2) || s2 instanceof Set || s2 instanceof Map) for (const t3 of s2) "object" == typeof t3 && this.processResult(t3);
              else if ("object" == typeof s2) {
                const t3 = this.contexts.get(s2);
                t3 && t3["@dist"] && t3["@dist"](s2), this.processResult(s2);
              }
            }
          }
          e2 && e2.filler && this.errors.markErrors(t2, e2);
        }
        copyResult(t2, e2 = {}) {
          if (arguments.length && void 0 === t2) return;
          const s2 = arguments.length ? t2 : this.tree;
          for (const t3 in s2) {
            const r2 = s2[t3];
            if (r2 instanceof Set || r2 instanceof Map) e2[t3] = [...r2];
            else if (Array.isArray(r2)) {
              e2[t3] = [];
              for (const s3 of r2) if (Array.isArray(s3)) {
                const r3 = [];
                e2[t3].push(r3), this.copyResult(s3, r3);
              } else if (s3 && "object" == typeof s3) {
                const r3 = /* @__PURE__ */ Object.create(null);
                e2[t3].push(r3), this.copyResult(s3, r3);
              } else e2[t3] = JSON.parse(JSON.stringify(r2));
            } else r2 && "object" == typeof r2 ? (e2[t3] = /* @__PURE__ */ Object.create(null), this.copyResult(r2, e2[t3])) : e2[t3] = JSON.parse(JSON.stringify(r2));
          }
          return e2;
        }
      }
      return c.prototype.converter = l, c;
    });
  }
});

// plots/barchart.data.js
var import_partjson = __toESM(require_partjson_umd(), 1);
function getBarchartData(_q, data) {
  const q = JSON.parse(JSON.stringify(_q));
  if (!q.term1) q.term1 = q.term ? q.term : {};
  if (!q.term1_q) q.term1_q = {};
  if (!q.term0) q.term0 = {};
  if (!q.term0_q) q.term0_q = {};
  if (!q.term2) q.term2 = {};
  if (!q.term2_q) q.term2_q = {};
  if (!q.filter) q.filter = { type: "tvslst", join: "", lst: [] };
  const pj = getCharts(q, data);
  return pj.tree.results;
}
var templateBar = JSON.stringify({
  "@before()": "=prep()",
  "@join()": {
    idVal: "=idVal()"
  },
  results: {
    "_2:maxAcrossCharts": "=maxAcrossCharts()",
    charts: [
      {
        chartId: "@key",
        total: "+1",
        "_1:maxSeriesTotal": "=maxSeriesTotal()",
        "@done()": "=filterEmptySeries()",
        serieses: [
          {
            total: "+1",
            seriesId: "@key",
            max: "<&idVal.dataVal",
            // needed by client-side boxplot renderer
            "~values": ["&idVal.dataVal", 0],
            "~sum": "+&idVal.dataVal",
            "__:boxplot": "=boxplot()",
            "~samples": ["$sample", "set"],
            //'__:AF': '=getAF()',
            data: [
              {
                dataId: "@key",
                total: "+1"
                //samples: ['$sample']
              },
              "&idVal.dataId[]"
            ]
          },
          "&idVal.seriesId[]"
        ]
      },
      "&idVal.chartId[]"
    ],
    "~sum": "+&idVal.seriesVal",
    "~values": ["&idVal.seriesVal", 0],
    "__:boxplot": "=boxplot()",
    refs: {
      cols: ["&idVal.seriesId[]"],
      colgrps: ["-"],
      rows: ["&idVal.dataId[]"],
      rowgrps: ["-"],
      col2name: {
        "&idVal.seriesId[]": {
          name: "@branch",
          grp: "-"
        }
      },
      row2name: {
        "&idVal.dataId[]": {
          name: "@branch",
          grp: "-"
        }
      },
      "__:useColOrder": "=useColOrder()",
      "__:useRowOrder": "=useRowOrder()",
      "__:bins": "=bins()",
      //'__:q': '=q()',
      "@done()": "=sortColsRows()"
    },
    "@done()": "=sortCharts()"
  }
});
function getCharts(q, data) {
  const idValFxns = {
    categorical: getCategoricalIdVal,
    integer: getNumericIdVal,
    float: getNumericIdVal,
    undefined: getUndefinedIdVal
    // NOTE: condition terms are not currently supported for frontend vocab
  };
  return new import_partjson.default({
    data,
    seed: `{"values": []}`,
    // result seed
    template: templateBar,
    "=": {
      idVal(row, context) {
        const [chartId, chartVal] = idValFxns[q.term0.type](row.data, q.term0, q.term0_q, data);
        const [seriesId, seriesVal] = idValFxns[q.term1.type](row.data, q.term1, q.term1_q, data);
        const [dataId, dataVal] = idValFxns[q.term2.type](row.data, q.term2, q.term2_q, data);
        return {
          chartId,
          chartVal,
          seriesId,
          seriesVal,
          dataId,
          dataVal
        };
      },
      prep(row) {
        return sample_match_termvaluesetting(row.data, q.filter);
      },
      maxSeriesTotal(row, context) {
        let maxSeriesTotal = 0;
        for (const grp of context.self.serieses) {
          if (grp && grp.total > maxSeriesTotal) {
            maxSeriesTotal = grp.total;
          }
        }
        return maxSeriesTotal;
      },
      maxAcrossCharts(row, context) {
        let maxAcrossCharts = 0;
        for (const chart of context.self.charts) {
          if (chart.maxSeriesTotal > maxAcrossCharts) {
            maxAcrossCharts = chart.maxSeriesTotal;
          }
        }
        return maxAcrossCharts;
      },
      boxplot(row, context) {
        if (!context.self.values || !context.self.values.length) return;
        const values = context.self.values.filter((d) => d !== null && !isNaN(d));
        if (!values.length) return;
        values.sort((i, j) => i - j);
        const stat = boxplot_getvalue(
          values.map((v) => {
            return { value: +v };
          })
        );
        stat.mean = context.self.sum / values.length;
        let s = 0;
        for (const v of values) {
          s += Math.pow(v - stat.mean, 2);
        }
        stat.sd = Math.sqrt(s / (values.length - 1));
        if (isNaN(stat.sd)) stat.sd = null;
        return stat;
      },
      numSamples(row, context) {
        return context.self.samples.size;
      },
      filterEmptySeries(result) {
        const nonempty = result.serieses.filter((series) => series.total);
        result.serieses.splice(0, result.serieses.length, ...nonempty);
      },
      sortColsRows(result) {
        if (q.term1_q.orderedLabels) {
          const labels = q.term1_q.orderedLabels;
          result.cols.sort((a, b) => labels.indexOf(a) - labels.indexOf(b));
        }
        if (q.term2.orderedLabels) {
          const labels = q.term2_q.orderedLabels;
          result.rows.sort((a, b) => labels.indexOf(a) - labels.indexOf(b));
        }
      },
      sortCharts(result) {
      },
      useColOrder() {
        return q.term1_q.orderedLabels && q.term1_q.orderedLabels.length > 0;
      },
      useRowOrder() {
        return q.term2_q.orderedLabels && q.term2_q.orderedLabels.length > 0;
      },
      bins() {
        return [q.term0_q, q.term1_q, q.term2_q].map((d) => d.computed_bins);
      },
      q() {
      }
    }
  });
}
function getCategoricalIdVal(d, term) {
  const id = "id" in term ? d[term.id] : "-";
  const value = "id" in term && isNumeric(d[term.id]) ? +d[term.id] : 0;
  return [[id], value];
}
function getNumericIdVal(d, term, q, rows) {
  if (!("id" in term) || !(term.id in d)) return [[], void 0];
  if (!q.computed_bins) {
    const summary = {};
    rows.map((row) => {
      if (!isNumeric(row.data[term.id])) return;
      const v2 = +row.data[term.id];
      if (!("min" in summary) || summary.min > v2) summary.min = v2;
      if (!("max" in summary) || summary.max < v2) summary.max = v2;
    });
    q.computed_bins = compute_bins(q, (percentiles) => summary);
    q.orderedLabels = q.computed_bins.map((d2) => d2.label);
  }
  const v = d[term.id];
  if (term.values && v in term.values && term.values[v].uncomputable) {
    return [[term.values[v].label], void 0];
  }
  if (isNumeric(d[term.id])) {
    const ids = [];
    for (const b of q.computed_bins) {
      if (b.startunbounded) {
        if (v < b.stop) {
          ids.push(b.label);
        } else if (b.stopinclusive && v === b.stop) {
          ids.push(b.label);
        }
      } else if (b.stopunbounded) {
        if (v > b.start) {
          ids.push(b.label);
        } else if (b.stopinclusive && v === b.start) {
          ids.push(b.label);
        }
      } else if ((v > b.start || v === b.start && b.startinclusive) && (v < b.stop || v === b.stop && b.stopinclusive)) {
        ids.push(b.label);
      }
      if (ids.length) break;
    }
    return [ids, v];
  }
  return [[], void 0];
}
function getUndefinedIdVal() {
  return [["-"], void 0];
}
function boxplot_getvalue(lst) {
  const l = lst.length;
  if (l < 5) {
    return { out: lst };
  }
  const p50 = lst[Math.floor(l / 2)].value;
  const p25 = lst[Math.floor(l / 4)].value;
  const p75 = lst[Math.floor(l * 3 / 4)].value;
  const p05 = lst[Math.floor(l * 0.05)].value;
  const p95 = lst[Math.floor(l * 0.95)].value;
  const p01 = lst[Math.floor(l * 0.01)].value;
  const iqr = p75 - p25;
  let w1, w2;
  if (iqr == 0) {
    w1 = 0;
    w2 = 0;
  } else {
    const i = lst.findIndex((i2) => i2.value > p25 - iqr * 1.5);
    w1 = lst[i == -1 ? 0 : i].value;
    const j = lst.findIndex((i2) => i2.value > p75 + iqr * 1.5);
    w2 = lst[j == -1 ? l - 1 : Math.max(0, j - 1)].value;
  }
  const out = lst.filter((i) => i.value < p25 - iqr * 1.5 || i.value > p75 + iqr * 1.5);
  return { w1, w2, p05, p25, p50, p75, p95, iqr, out };
}
function getCategoryData(q, data) {
  if (!data || !data.length) {
    return {
      lst: Object.keys(q.term.values).map((k) => {
        return { key: k, label: q.term.values[k].label, value: k };
      })
    };
  }
  const pj = new import_partjson.default({
    data,
    template: JSON.stringify({
      "@before()": "=prep()",
      "@join()": {
        idVal: "=idVal()"
      },
      results: {
        "&idVal.id": {
          samplecount: "+1",
          ":__key": "&idVal.id",
          ":__label": "&idVal.id",
          ":__value": "&idVal.id"
        }
      }
    }),
    "=": {
      prep(row) {
        return sample_match_termvaluesetting(row.data, q.filter);
      },
      idVal(row, context) {
        const [id, value] = getCategoricalIdVal(row.data, q.term);
        return { id: id[0], value };
      }
    }
  });
  return { lst: Object.values(pj.tree.results) };
}

export {
  require_partjson_umd,
  getBarchartData,
  getCategoryData
};
//# sourceMappingURL=chunk-UI7OCM2A.js.map
