(function() {
  "use strict";
  const TIME_SERIES_VALUE_FIELD_NAME = "Value";
  const TIME_SERIES_TIME_FIELD_NAME = "Time";
  function formatLabels(labels) {
    if (!labels) return "";
    return Object.entries(labels).filter(([, v]) => v != null && v !== "").map(([k, v]) => `${k}=${v}`).join(", ");
  }
  function getFieldDisplayName(field, frame, allFrames) {
    const name = calculateFieldDisplayName(field, frame, allFrames);
    if (field.state?.displayName !== name) {
      field.state = { ...field.state || {}, displayName: name };
    }
    return name;
  }
  function isGenericValueName(s) {
    const t = s.trim();
    if (!t || t === TIME_SERIES_VALUE_FIELD_NAME) return true;
    if (/^Value\s*\{/.test(t)) return true;
    return false;
  }
  function calculateFieldDisplayName(field, frame, allFrames) {
    const cfg = field.config ?? {};
    if (cfg.displayName && String(cfg.displayName).length && !isGenericValueName(String(cfg.displayName))) {
      return String(cfg.displayName);
    }
    if (cfg.displayNameFromDS && String(cfg.displayNameFromDS).length && !isGenericValueName(String(cfg.displayNameFromDS))) {
      return String(cfg.displayNameFromDS);
    }
    if (field.type === "time" && !field.labels) {
      return field.name || TIME_SERIES_TIME_FIELD_NAME;
    }
    const frames = allFrames?.length ? allFrames : frame ? [frame] : [];
    let frameNamesDiffer = false;
    if (frames.length > 1) {
      for (let i = 1; i < frames.length; i++) {
        if (frames[i].name !== frames[i - 1].name) {
          frameNamesDiffer = true;
          break;
        }
      }
    }
    const parts = [];
    let frameNameAdded = false;
    let labelsAdded = false;
    if (frameNamesDiffer && frame?.name) {
      parts.push(frame.name);
      frameNameAdded = true;
    }
    if (field.name && !isGenericValueName(field.name)) {
      parts.push(field.name);
    }
    if (field.labels && Object.keys(field.labels).length) {
      const singleLabel = getSingleLabelName(
        frames.length ? frames : frame ? [frame] : []
      );
      if (singleLabel && field.labels[singleLabel] != null && field.labels[singleLabel] !== "") {
        parts.push(String(field.labels[singleLabel]));
        labelsAdded = true;
      } else {
        const allLabels = formatLabels(field.labels);
        if (allLabels) {
          parts.push(allLabels);
          labelsAdded = true;
        }
      }
    }
    if (frame && !frameNameAdded && !labelsAdded && isGenericValueName(field.name || "")) {
      if (frame.name) {
        parts.push(frame.name);
        frameNameAdded = true;
      }
    }
    if (parts.length) return parts.join(" ");
    if (field.name) return field.name;
    if (frame?.name) return frame.name;
    return TIME_SERIES_VALUE_FIELD_NAME;
  }
  function getSingleLabelName(frames) {
    const keys = /* @__PURE__ */ new Set();
    for (const fr of frames) {
      for (const f of fr.fields) {
        if (!f.labels) continue;
        for (const k of Object.keys(f.labels)) keys.add(k);
        if (keys.size > 1) return null;
      }
    }
    if (keys.size === 1) return [...keys][0];
    return null;
  }
  const registry = /* @__PURE__ */ new Map();
  function getTransformer(id) {
    return registry.get(id);
  }
  const ALIASES = {
    // filterFieldsByName is first-class; filterByName is internal alias
    filterByName: "filterFieldsByName",
    filterFramesByRefId: "filterByRefId",
    seriesToColumns: "joinByField"
  };
  const DEFAULT_OPTIONS$1 = {
    limit: { limitField: 10 },
    sortBy: { sort: [] },
    reduce: { reducers: ["sum"] },
    histogram: { bucketCount: 10 },
    smoothing: { windowSize: 3 },
    filterByValue: { type: "include", filters: [] },
    prepareTimeSeries: { format: "multi" }
  };
  function resolveTransformerId(id) {
    return ALIASES[id] ?? id;
  }
  function deepCloneFrames(frames) {
    return frames.map((frame) => {
      const fields = frame.fields.map((f) => ({
        name: f.name,
        type: f.type,
        config: f.config ? { ...f.config } : {},
        values: f.values.slice(),
        labels: f.labels ? { ...f.labels } : void 0,
        state: f.state ? { ...f.state } : void 0
      }));
      return {
        refId: frame.refId,
        name: frame.name,
        meta: frame.meta ? { ...frame.meta } : void 0,
        fields,
        length: frame.length ?? fields[0]?.values.length ?? 0
      };
    });
  }
  function interpolateOptions(value, interpolate) {
    return value;
  }
  function patternFromFilterOptions(options) {
    if (options == null) return "";
    if (typeof options === "string" || typeof options === "number")
      return String(options);
    if (typeof options === "object") {
      const o = options;
      if (o.pattern != null) return String(o.pattern);
      if (o.refId != null) return String(o.refId);
      if (o.value != null) return String(o.value);
      if (Array.isArray(o.names))
        return o.names.map(String).join("|");
    }
    return String(options);
  }
  function compileMatcher(raw) {
    const s = raw.trim();
    if (!s) return () => true;
    const m = s.match(/^\/(.+)\/([gimsuy]*)$/);
    if (m) {
      try {
        const re = new RegExp(m[1], m[2]);
        return (v) => re.test(v);
      } catch {
        return (v) => v === s;
      }
    }
    try {
      const re = new RegExp(`^(?:${s})$`);
      return (v) => re.test(v);
    } catch {
      return (v) => v === s;
    }
  }
  function matchFrameFilter(frame, filter) {
    if (filter == null || filter === "") return true;
    if (typeof filter === "string") {
      const hit2 = compileMatcher(filter);
      return hit2(String(frame.refId ?? "")) || hit2(String(frame.name ?? ""));
    }
    const id = String(filter.id || "byRefId");
    const pattern = patternFromFilterOptions(filter.options);
    const hit = compileMatcher(pattern);
    if (id === "byName" || id === "byFrameName") {
      return hit(String(frame.name ?? ""));
    }
    if (id === "byRefId" || id === "byFrameRefID" || id === "byFrameRefId") {
      return hit(String(frame.refId ?? ""));
    }
    return hit(String(frame.refId ?? "")) || hit(String(frame.name ?? ""));
  }
  function applyWithFrameFilter(frames, filter, fn, options) {
    if (filter == null || filter === "") {
      return fn(frames, options);
    }
    const matched = [];
    const passthrough = /* @__PURE__ */ new Map();
    frames.forEach((f, i) => {
      if (matchFrameFilter(f, filter)) {
        matched.push(f);
      } else {
        passthrough.set(i, f);
      }
    });
    if (!matched.length) return frames;
    const transformed = fn(matched, options);
    const out = [];
    let inserted = false;
    for (let i = 0; i < frames.length; i++) {
      if (passthrough.has(i)) {
        out.push(passthrough.get(i));
      } else if (!inserted) {
        out.push(...transformed);
        inserted = true;
        transformed.length;
      }
    }
    if (!inserted) out.push(...transformed);
    return out;
  }
  function readLimitOption$1(options) {
    if (!options) return void 0;
    const raw = options.limit ?? options.limitField ?? options.limitValue;
    if (raw == null) return void 0;
    const n = Math.floor(Number(raw));
    return Number.isFinite(n) && n >= 0 ? n : void 0;
  }
  function tryFuseSortLimit$1(transformations, index) {
    const cur = transformations[index];
    const next = transformations[index + 1];
    if (!cur || !next) return null;
    if (cur.disabled || next.disabled) return null;
    const curId = resolveTransformerId(cur.id);
    const nextId = resolveTransformerId(next.id);
    if (curId !== "sortBy" || nextId !== "limit") return null;
    const f1 = cur.filter ?? null;
    const f2 = next.filter ?? null;
    if (JSON.stringify(f1) !== JSON.stringify(f2)) return null;
    const lim = readLimitOption$1(next.options);
    if (lim == null) return null;
    return {
      fusedOptions: { ...cur.options || {}, limit: lim, limitField: lim, limitValue: lim },
      skipNext: true
    };
  }
  function applyTransformations(frames, transformations = [], diagnostics, context) {
    let acc = deepCloneFrames(frames);
    if (!transformations.length) return acc;
    const localDiag = [];
    for (let i = 0; i < transformations.length; i++) {
      const t = transformations[i];
      if (t.disabled) continue;
      const resolvedId = resolveTransformerId(t.id);
      const fn = getTransformer(resolvedId) ?? getTransformer(t.id);
      if (!fn) {
        localDiag.push({
          id: t.id,
          level: "warn",
          message: `Unknown transformation: ${t.id}`
        });
        continue;
      }
      const defaults = DEFAULT_OPTIONS$1[resolvedId] ?? DEFAULT_OPTIONS$1[t.id] ?? {};
      const fuse = tryFuseSortLimit$1(transformations, i);
      const stepOptions = fuse ? { ...defaults, ...fuse.fusedOptions } : { ...defaults, ...t.options || {} };
      const merged = interpolateOptions(stepOptions);
      try {
        acc = applyWithFrameFilter(
          acc,
          t.filter,
          fn,
          merged
        );
        if (fuse?.skipNext) i += 1;
      } catch (e) {
        const msg = e instanceof Error ? e.message : String(e);
        localDiag.push({ id: t.id, level: "error", message: msg });
        throw e;
      }
    }
    return acc;
  }
  function stringStartsAsRegEx(str) {
    return Boolean(str) && str[0] === "/";
  }
  function stringToJsRegex(str) {
    if (!stringStartsAsRegEx(str)) {
      return new RegExp(`^${str}$`);
    }
    const match = str.match(/^\/(.*?)\/(g?i?m?y?s?)$/);
    if (!match) {
      throw new Error(`'${str}' is not a valid regular expression.`);
    }
    return new RegExp(match[1], match[2]);
  }
  function stringToJsRegexSafe(str) {
    try {
      const s = String(str ?? "");
      if (!s) return null;
      return stringToJsRegex(s);
    } catch {
      return null;
    }
  }
  var ReducerID = /* @__PURE__ */ ((ReducerID2) => {
    ReducerID2["sum"] = "sum";
    ReducerID2["max"] = "max";
    ReducerID2["min"] = "min";
    ReducerID2["mean"] = "mean";
    ReducerID2["last"] = "last";
    ReducerID2["first"] = "first";
    ReducerID2["count"] = "count";
    ReducerID2["lastNotNull"] = "lastNotNull";
    ReducerID2["firstNotNull"] = "firstNotNull";
    ReducerID2["range"] = "range";
    ReducerID2["diff"] = "diff";
    ReducerID2["diffperc"] = "diffperc";
    ReducerID2["delta"] = "delta";
    ReducerID2["step"] = "step";
    ReducerID2["variance"] = "variance";
    ReducerID2["stdDev"] = "stdDev";
    ReducerID2["median"] = "median";
    ReducerID2["allIsZero"] = "allIsZero";
    ReducerID2["allIsNull"] = "allIsNull";
    ReducerID2["changeCount"] = "changeCount";
    ReducerID2["distinctCount"] = "distinctCount";
    ReducerID2["logmin"] = "logmin";
    return ReducerID2;
  })(ReducerID || {});
  function numericValues(field) {
    return field.values.map((v) => v == null || v === "" ? null : Number(v)).filter((v) => v != null && !Number.isNaN(v));
  }
  function reduceField(field, reducers = [
    "lastNotNull"
    /* lastNotNull */
  ]) {
    const nums = numericValues(field);
    const out = {};
    for (const r of reducers) {
      if (r === "count") {
        out[r] = nums.length;
        continue;
      }
      if (r === "allIsNull") {
        out[r] = field.values.every((v) => v == null || v === "");
        continue;
      }
      if (r === "allIsZero") {
        out[r] = nums.length > 0 && nums.every((n) => n === 0);
        continue;
      }
      if (r === "distinctCount") {
        out[r] = new Set(nums).size;
        continue;
      }
      if (r === "changeCount") {
        let c = 0;
        for (let i = 1; i < nums.length; i++) if (nums[i] !== nums[i - 1]) c++;
        out[r] = c;
        continue;
      }
      if (!nums.length) {
        out[r] = null;
        continue;
      }
      switch (r) {
        case "last":
          out[r] = Number(field.values[field.values.length - 1]);
          break;
        case "lastNotNull":
          out[r] = nums[nums.length - 1];
          break;
        case "first":
          out[r] = Number(field.values[0]);
          break;
        case "firstNotNull":
          out[r] = nums[0];
          break;
        case "min":
          out[r] = Math.min(...nums);
          break;
        case "max":
          out[r] = Math.max(...nums);
          break;
        case "mean":
          out[r] = nums.reduce((a, b) => a + b, 0) / nums.length;
          break;
        case "sum":
          out[r] = nums.reduce((a, b) => a + b, 0);
          break;
        case "range":
          out[r] = Math.max(...nums) - Math.min(...nums);
          break;
        case "diff":
          out[r] = nums[nums.length - 1] - nums[0];
          break;
        case "diffperc": {
          const a = nums[0];
          out[r] = a === 0 ? null : (nums[nums.length - 1] - a) / Math.abs(a) * 100;
          break;
        }
        case "delta": {
          let d = 0;
          for (let i = 1; i < nums.length; i++) {
            const step = nums[i] - nums[i - 1];
            if (step > 0) d += step;
          }
          out[r] = d;
          break;
        }
        case "step": {
          let maxStep = 0;
          for (let i = 1; i < nums.length; i++)
            maxStep = Math.max(maxStep, Math.abs(nums[i] - nums[i - 1]));
          out[r] = maxStep;
          break;
        }
        case "variance": {
          const mean = nums.reduce((a, b) => a + b, 0) / nums.length;
          out[r] = nums.reduce((a, b) => a + (b - mean) ** 2, 0) / nums.length;
          break;
        }
        case "stdDev": {
          const mean = nums.reduce((a, b) => a + b, 0) / nums.length;
          const v = nums.reduce((a, b) => a + (b - mean) ** 2, 0) / nums.length;
          out[r] = Math.sqrt(v);
          break;
        }
        case "median": {
          const s = [...nums].sort((a, b) => a - b);
          const mid = Math.floor(s.length / 2);
          out[r] = s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
          break;
        }
        case "logmin": {
          const pos = nums.filter((n) => n > 0);
          out[r] = pos.length ? Math.min(...pos) : null;
          break;
        }
        default:
          out[r] = nums[nums.length - 1];
      }
    }
    return out;
  }
  function compareFieldValues(left, op, right) {
    const o = String(op).toLowerCase();
    const lv = left;
    const rv = right;
    switch (o) {
      case "eq":
      case "==":
        return lv == rv;
      case "neq":
      case "!=":
        return lv != rv;
      case "gt":
      case ">":
        return Number(lv) > Number(rv);
      case "gte":
      case ">=":
        return Number(lv) >= Number(rv);
      case "lt":
      case "<":
        return Number(lv) < Number(rv);
      case "lte":
      case "<=":
        return Number(lv) <= Number(rv);
      default:
        return lv == rv;
    }
  }
  function asNames(options) {
    if (Array.isArray(options)) return options.map(String);
    if (options && typeof options === "object" && Array.isArray(options.names)) {
      return options.names.map(String);
    }
    return String(options?.names ?? options ?? "").split(",").map((s) => s.trim()).filter(Boolean);
  }
  const MATCHERS = [
    {
      id: "byName",
      name: "字段名称为",
      pickerDefault: true,
      get: (options) => (field) => field.name === options
    },
    {
      id: "byNames",
      name: "字段名称为（列表）",
      pickerDefault: true,
      get: (options) => (field) => {
        const names = asNames(options);
        const hit = names.includes(field.name);
        const mode = typeof options === "object" && options && !Array.isArray(options) ? options.mode || "include" : "include";
        return mode === "exclude" ? !hit : hit;
      }
    },
    {
      id: "byRegexp",
      name: "字段名匹配正则",
      pickerDefault: true,
      get: (options) => {
        const re = stringToJsRegexSafe(options);
        return (field, frame, allFrames) => {
          if (!re) return false;
          const displayName = getFieldDisplayName(field, frame, allFrames);
          return re.test(displayName) || re.test(field.name);
        };
      }
    },
    {
      id: "byRegexpOrNames",
      name: "字段名匹配正则或列表",
      pickerDefault: false,
      get: (options) => {
        const opts = options;
        const pattern = typeof opts === "string" ? opts : opts?.pattern ?? "";
        const names = typeof opts === "object" && opts ? asNames(opts) : [];
        const re = stringToJsRegexSafe(pattern);
        return (field, frame, allFrames) => {
          if (names.includes(field.name)) return true;
          if (!re) return false;
          const displayName = getFieldDisplayName(field, frame, allFrames);
          return re.test(displayName) || re.test(field.name);
        };
      }
    },
    {
      id: "byType",
      name: "字段类型为",
      pickerDefault: true,
      get: (options) => (field) => field.type === options
    },
    {
      id: "byTypes",
      name: "字段类型为（列表）",
      pickerDefault: false,
      get: (options) => {
        const types = Array.isArray(options) ? options.map(String) : String(options ?? "").split(",").map((s) => s.trim()).filter(Boolean);
        return (field) => types.includes(String(field.type));
      }
    },
    {
      id: "byFrameRefID",
      name: "查询返回的字段",
      pickerDefault: true,
      get: (options) => (_field, frame) => (frame?.refId ?? "") === String(options ?? "")
    },
    {
      id: "byValue",
      name: "值为（reducer）",
      description: "将字段 reduce 为单值后与阈值比较（对齐 Grafana fieldValueMatcher）",
      pickerDefault: true,
      get: (options) => {
        const props = options ?? {};
        if (options != null && (typeof options === "number" || typeof options === "string")) {
          const target = options;
          return (field) => field.values.some((v) => {
            if (typeof target === "number") return Number(v) === target;
            return String(v) === String(target);
          });
        }
        const reducer = props.reducer;
        if (!reducer) return () => false;
        const op = props.op || "eq";
        const isBoolean = reducer === ReducerID.allIsNull || reducer === ReducerID.allIsZero || reducer === "allIsNull" || reducer === "allIsZero";
        return (field) => {
          const reduced = reduceField(field, [reducer]);
          const left = reduced[reducer];
          if (isBoolean) return Boolean(left);
          return compareFieldValues(left, op, props.value);
        };
      }
    },
    {
      id: "numeric",
      name: "数值字段",
      pickerDefault: false,
      get: () => (field) => field.type === "number"
    },
    {
      id: "time",
      name: "时间字段",
      pickerDefault: false,
      get: () => (field) => field.type === "time"
    },
    {
      id: "first",
      name: "第一个字段",
      pickerDefault: false,
      get: () => (field, frame) => !!frame && frame.fields[0] === field
    },
    {
      id: "firstTimeField",
      name: "第一个时间字段",
      pickerDefault: false,
      get: () => (field, frame) => {
        if (!frame) return field.type === "time";
        const first = frame.fields.find((f) => f.type === "time");
        return first === field;
      }
    }
  ];
  const byId = new Map(MATCHERS.map((m) => [m.id, m]));
  function getFieldMatcher(config) {
    const info = byId.get(config.id);
    if (!info) {
      return () => false;
    }
    return info.get(config.options);
  }
  function identity(v) {
    return v;
  }
  function numberOrUndefined(v) {
    if (v === "" || v === null || v === void 0) return void 0;
    const n = Number(v);
    return Number.isFinite(n) ? n : void 0;
  }
  const STANDARD_OVERRIDE_PROCESSORS = [
    {
      id: "unit",
      name: "单位",
      path: "unit",
      process: (v) => v == null || v === "" ? void 0 : String(v)
    },
    {
      id: "decimals",
      name: "小数位",
      path: "decimals",
      process: numberOrUndefined
    },
    { id: "min", name: "最小值", path: "min", process: numberOrUndefined },
    { id: "max", name: "最大值", path: "max", process: numberOrUndefined },
    {
      id: "fieldMinMax",
      name: "字段最小/最大",
      path: "fieldMinMax",
      process: (v) => v == null ? void 0 : Boolean(v)
    },
    {
      id: "displayName",
      name: "显示名称",
      path: "displayName",
      process: (v) => v == null || v === "" ? void 0 : String(v)
    },
    {
      id: "noValue",
      name: "空值显示",
      path: "noValue",
      process: (v) => v == null ? void 0 : String(v)
    },
    { id: "color", name: "颜色", path: "color", process: identity },
    { id: "thresholds", name: "阈值", path: "thresholds", process: identity },
    { id: "mappings", name: "值映射", path: "mappings", process: identity },
    { id: "links", name: "数据链接", path: "links", process: identity },
    { id: "actions", name: "动作", path: "actions", process: identity },
    {
      id: "filterable",
      name: "可过滤",
      path: "filterable",
      process: (v) => v == null ? void 0 : Boolean(v)
    }
  ];
  const processorById = new Map(
    STANDARD_OVERRIDE_PROCESSORS.map((p) => [p.id, p])
  );
  function getOverrideProcessor(id) {
    if (processorById.has(id)) return processorById.get(id);
    if (id.startsWith("custom.")) {
      return {
        id,
        name: id.slice(7),
        path: id,
        process: identity
      };
    }
    return {
      id,
      name: id,
      path: id,
      process: identity,
      shouldApply: () => false
    };
  }
  function processOverrideValue(id, value) {
    return getOverrideProcessor(id).process(value);
  }
  function isKnownOverrideProperty(id) {
    return processorById.has(id) || id.startsWith("custom.");
  }
  function applyProcessedProperty(config, id, raw) {
    const processor = getOverrideProcessor(id);
    if (processor.shouldApply === void 0 && !isKnownOverrideProperty(id) && !id.startsWith("custom.")) {
      return config;
    }
    const value = processor.process(raw);
    if (value === void 0) {
      const next = { ...config };
      if (id.startsWith("custom.")) {
        const custom = { ...config.custom ?? {} };
        delete custom[id.slice(7)];
        return { ...config, custom };
      }
      delete next[id];
      return next;
    }
    if (id.startsWith("custom.")) {
      const key = id.slice(7);
      return { ...config, custom: { ...config.custom ?? {}, [key]: value } };
    }
    if (id === "filterable") {
      return {
        ...config,
        filterable: value,
        custom: { ...config.custom ?? {}, filterable: value }
      };
    }
    return { ...config, [id]: value };
  }
  const compiledRulesCache = /* @__PURE__ */ new WeakMap();
  const compiledRulesLru = [];
  const COMPILED_RULES_LRU_MAX = 32;
  function defaultsCacheKey(defaults) {
    const unit = defaults.unit ?? "";
    const decimals = defaults.decimals ?? "";
    const displayName = defaults.displayName ?? "";
    const customKeys = defaults.custom ? Object.keys(defaults.custom).join(",") : "";
    return `${unit}|${decimals}|${displayName}|${customKeys}`;
  }
  function rulesSignature(overrides) {
    let s = String(overrides.length);
    for (let i = 0; i < overrides.length; i++) {
      const r = overrides[i];
      s += `|${r.matcher?.id}:${JSON.stringify(r.matcher?.options)}:${r.properties?.length ?? 0}`;
      for (const p of r.properties || []) s += `:${p.id}`;
    }
    return s;
  }
  function compileOverrideRules(overrides = []) {
    return overrides.map((rule) => ({
      matcher: rule.matcher,
      properties: rule.properties || [],
      match: getFieldMatcher(rule.matcher || { id: "" })
    }));
  }
  function getCompiledRules(overrides, defaults) {
    const dKey = defaultsCacheKey(defaults);
    const weakHit = compiledRulesCache.get(overrides);
    if (weakHit && weakHit.defaultsKey === dKey) return weakHit.rules;
    const sig = rulesSignature(overrides) + "::" + dKey;
    const lruHit = compiledRulesLru.find((e) => e.key === sig);
    if (lruHit) {
      compiledRulesCache.set(overrides, { rules: lruHit.rules, defaultsKey: dKey });
      return lruHit.rules;
    }
    const rules = compileOverrideRules(overrides);
    compiledRulesCache.set(overrides, { rules, defaultsKey: dKey });
    compiledRulesLru.unshift({ key: sig, rules });
    if (compiledRulesLru.length > COMPILED_RULES_LRU_MAX) compiledRulesLru.pop();
    return rules;
  }
  function normalizePropId(id) {
    if (id === "unit" || id === "decimals" || id === "displayName" || id === "min" || id === "max" || id === "noValue" || id === "fieldMinMax" || id === "filterable" || id === "color" || id === "thresholds" || id === "mappings" || id === "links" || id === "actions") {
      return id;
    }
    if (id.startsWith("standardOptions."))
      return id.slice("standardOptions.".length);
    if (id.startsWith("custom.")) return id;
    const customKeys = [
      "drawStyle",
      "lineInterpolation",
      "lineWidth",
      "fillOpacity",
      "gradientMode",
      "spanNulls",
      "showPoints",
      "pointSize",
      "stacking",
      "axisPlacement",
      "axisLabel",
      "axisSoftMin",
      "axisSoftMax",
      "axisCenteredZero",
      "hideFrom",
      "scaleDistribution",
      "thresholdsStyle",
      "barAlignment",
      "lineStyle",
      "insertNulls",
      "barWidthFactor"
    ];
    if (customKeys.includes(id)) return `custom.${id}`;
    return id;
  }
  function setNested(config, path, value) {
    if (path.startsWith("custom.")) {
      const rest = path.slice(7);
      const custom = { ...config.custom ?? {} };
      const parts = rest.split(".");
      let cur = custom;
      for (let i = 0; i < parts.length - 1; i++) {
        cur[parts[i]] = cur[parts[i]] && typeof cur[parts[i]] === "object" ? { ...cur[parts[i]] } : {};
        cur = cur[parts[i]];
      }
      cur[parts[parts.length - 1]] = value;
      return { ...config, custom };
    }
    if (path.includes(".")) {
      const parts = path.split(".");
      const root = { ...config };
      let cur = root;
      for (let i = 0; i < parts.length - 1; i++) {
        cur[parts[i]] = cur[parts[i]] && typeof cur[parts[i]] === "object" ? { ...cur[parts[i]] } : {};
        cur = cur[parts[i]];
      }
      cur[parts[parts.length - 1]] = value;
      return root;
    }
    return { ...config, [path]: value };
  }
  function applyFieldOverrides(frames, defaults = {}, overrides = []) {
    const compiled = getCompiledRules(overrides, defaults);
    return frames.map((frame) => ({
      ...frame,
      fields: frame.fields.map((field) => {
        const mergedCustom = {
          ...defaults.custom ?? {},
          ...field.config?.custom ?? {}
        };
        let config = {
          ...defaults,
          ...field.config,
          ...Object.keys(mergedCustom).length ? { custom: mergedCustom } : {}
        };
        for (let ri = 0; ri < compiled.length; ri++) {
          const rule = compiled[ri];
          if (!rule.match(field, frame, frames)) continue;
          const properties = overrides[ri]?.properties ?? rule.properties;
          for (const prop of properties) {
            const id = normalizePropId(prop.id);
            if (!isKnownOverrideProperty(id) && !id.includes(".")) {
              continue;
            }
            const processed = processOverrideValue(id, prop.value);
            if (id.startsWith("custom.") || !isKnownOverrideProperty(id)) {
              config = setNested(config, id, processed);
            } else {
              config = applyProcessedProperty(config, id, prop.value);
            }
            if (id === "color" && prop.value && typeof prop.value === "object" && prop.value.fixedColor) {
              config = {
                ...config,
                color: {
                  ...config.color,
                  ...prop.value,
                  mode: prop.value.mode ?? "fixed"
                }
              };
            }
          }
        }
        return { ...field, config };
      })
    }));
  }
  const DEFAULT_MAX_ENTRIES = 64;
  const DEFAULT_MAX_BYTES = 512 * 1024;
  const cache = /* @__PURE__ */ new Map();
  let cacheBytes = 0;
  let maxEntries = DEFAULT_MAX_ENTRIES;
  let maxBytes = DEFAULT_MAX_BYTES;
  const DEFAULT_OPTIONS = {
    limit: { limitField: 10 },
    sortBy: { sort: [] },
    reduce: { reducers: ["sum"] },
    histogram: { bucketCount: 10 },
    smoothing: { windowSize: 3 },
    filterByValue: { type: "include", filters: [] },
    prepareTimeSeries: { format: "multi" }
  };
  function readLimitOption(options) {
    if (!options) return void 0;
    const raw = options.limit ?? options.limitField ?? options.limitValue;
    if (raw == null) return void 0;
    const n = Math.floor(Number(raw));
    return Number.isFinite(n) && n >= 0 ? n : void 0;
  }
  function tryFuseSortLimit(steps, index) {
    const cur = steps[index];
    const next = steps[index + 1];
    if (!cur || !next) return null;
    if (cur.disabled || next.disabled) return null;
    const curId = resolveTransformerId(cur.id);
    const nextId = resolveTransformerId(next.id);
    if (curId !== "sortBy" || nextId !== "limit") return null;
    if (JSON.stringify(cur.filter ?? null) !== JSON.stringify(next.filter ?? null)) {
      return null;
    }
    const lim = readLimitOption(next.options);
    if (lim == null) return null;
    const defaults = DEFAULT_OPTIONS.sortBy ?? {};
    return {
      fused: {
        id: "sortBy",
        filter: cur.filter,
        options: {
          ...defaults,
          ...cur.options || {},
          limit: lim,
          limitField: lim,
          limitValue: lim
        }
      },
      skipNext: true
    };
  }
  function compileTransformSteps(transformations = []) {
    const out = [];
    const src = transformations ?? [];
    for (let i = 0; i < src.length; i++) {
      const t = src[i];
      if (t.disabled) continue;
      const fuse = tryFuseSortLimit(src, i);
      if (fuse) {
        out.push(fuse.fused);
        if (fuse.skipNext) i += 1;
        continue;
      }
      const resolvedId = resolveTransformerId(t.id);
      const defaults = DEFAULT_OPTIONS[resolvedId] ?? DEFAULT_OPTIONS[t.id] ?? {};
      out.push({
        id: resolvedId,
        filter: t.filter,
        options: { ...defaults, ...t.options || {} }
      });
    }
    return out;
  }
  function estimateConfigBytes(config) {
    let n = 128;
    const transforms = config.transformations ?? [];
    n += transforms.length * 64;
    for (const t of transforms) {
      n += String(t.id).length + 16;
      if (t.options) n += Object.keys(t.options).length * 24;
    }
    const overrides = config.fieldConfigOverrides ?? [];
    n += overrides.length * 96;
    for (const r of overrides) {
      n += String(r.matcher?.id ?? "").length;
      n += (r.properties?.length ?? 0) * 32;
    }
    const defaults = config.fieldConfigDefaults;
    if (defaults) n += Object.keys(defaults).length * 24 + 32;
    return n;
  }
  function pipelineConfigRevision(config) {
    const transforms = config.transformations ?? [];
    const overrides = config.fieldConfigOverrides ?? [];
    const defaults = config.fieldConfigDefaults ?? {};
    const parts = [`t${transforms.length}`, `o${overrides.length}`];
    for (let i = 0; i < transforms.length; i++) {
      const t = transforms[i];
      parts.push(
        `${t.disabled ? "D" : ""}${t.id}:${stableSmallJson(t.options)}:${stableSmallJson(t.filter)}`
      );
    }
    for (let i = 0; i < overrides.length; i++) {
      const r = overrides[i];
      const props = (r.properties || []).map((p) => `${p.id}=${stableSmallJson(p.value)}`).join(",");
      parts.push(
        `m${r.matcher?.id}:${stableSmallJson(r.matcher?.options)}:${props}`
      );
    }
    parts.push(`d:${stableSmallJson(defaults)}`);
    return parts.join("|");
  }
  function stableSmallJson(value) {
    if (value == null) return "";
    if (typeof value === "string") return value.length > 64 ? value.slice(0, 64) : value;
    if (typeof value === "number" || typeof value === "boolean") return String(value);
    try {
      const s = JSON.stringify(value);
      return s.length > 256 ? s.slice(0, 256) : s;
    } catch {
      return "?";
    }
  }
  function touch(revision, entry) {
    cache.delete(revision);
    cache.set(revision, entry);
  }
  function evictIfNeeded() {
    while ((cache.size > maxEntries || cacheBytes > maxBytes) && cache.size > 0) {
      const oldest = cache.keys().next().value;
      if (oldest == null) break;
      const e = cache.get(oldest);
      cache.delete(oldest);
      if (e) cacheBytes -= e.bytes;
    }
    if (cacheBytes < 0) cacheBytes = 0;
  }
  function getCompiledPipeline(config) {
    const revision = pipelineConfigRevision(config);
    const hit = cache.get(revision);
    if (hit) {
      touch(revision, hit);
      return hit.compiled;
    }
    const transformations = (config.transformations ?? []).map((t) => ({
      id: t.id,
      options: t.options ? { ...t.options } : void 0,
      disabled: t.disabled,
      filter: t.filter
    }));
    const defaults = { ...config.fieldConfigDefaults ?? {} };
    const overrides = (config.fieldConfigOverrides ?? []).map((r) => ({
      matcher: { ...r.matcher || { id: "" } },
      properties: (r.properties || []).map((p) => ({ ...p }))
    }));
    const fastSteps = compileTransformSteps(transformations);
    const compiledOverrides = compileOverrideRules(overrides);
    const estimatedBytes = estimateConfigBytes(config);
    const compiled = {
      revision,
      transformations,
      fastSteps,
      defaults,
      overrides,
      compiledOverrides,
      estimatedBytes
    };
    const bytes = Math.max(estimatedBytes, revision.length + 64);
    cacheBytes += bytes;
    cache.set(revision, { revision, compiled, bytes });
    evictIfNeeded();
    return compiled;
  }
  function runCompiledPipeline(frames, compiled, opts) {
    const transformed = applyTransformations(
      frames,
      compiled.fastSteps
    );
    const series = applyFieldOverrides(
      transformed,
      compiled.defaults,
      compiled.overrides
    );
    return { frames: series, steps: [], diagnostics: [] };
  }
  function canEncodeF64(values) {
    for (let i = 0; i < values.length; i++) {
      const v = values[i];
      if (v == null) continue;
      if (typeof v !== "number") return false;
    }
    return true;
  }
  function packFramesForTransfer(frames) {
    const transfer = [];
    const wire = (frames ?? []).map((frame) => {
      const fields = (frame.fields ?? []).map((f) => {
        const values = f.values ?? [];
        const type = f.type;
        const numericLike = (type === "number" || type === "time") && canEncodeF64(values);
        if (numericLike) {
          const f64 = new Float64Array(values.length);
          const nulls = new Uint8Array(values.length);
          for (let i = 0; i < values.length; i++) {
            const v = values[i];
            if (v == null) {
              nulls[i] = 1;
              f64[i] = 0;
            } else {
              nulls[i] = 0;
              f64[i] = v;
            }
          }
          transfer.push(f64.buffer, nulls.buffer);
          return {
            name: f.name,
            type,
            config: f.config ? { ...f.config } : {},
            labels: f.labels ? { ...f.labels } : void 0,
            encoding: "f64",
            f64,
            nulls
          };
        }
        return {
          name: f.name,
          type,
          config: f.config ? { ...f.config } : {},
          labels: f.labels ? { ...f.labels } : void 0,
          encoding: "clone",
          values: values.slice()
        };
      });
      const len = frame.length ?? fields[0]?.f64?.length ?? fields[0]?.values?.length ?? 0;
      return {
        refId: frame.refId,
        name: frame.name,
        meta: frame.meta ? { ...frame.meta } : void 0,
        length: len,
        fields
      };
    });
    return { frames: wire, transfer };
  }
  function unpackWireFrames(frames) {
    return (frames ?? []).map((frame) => {
      const fields = (frame.fields ?? []).map((f) => {
        if (f.encoding === "f64" && f.f64) {
          const n = f.f64.length;
          const values = new Array(n);
          const nulls = f.nulls;
          for (let i = 0; i < n; i++) {
            values[i] = nulls && nulls[i] ? null : f.f64[i];
          }
          return {
            name: f.name,
            type: f.type,
            config: f.config ?? {},
            values,
            labels: f.labels
          };
        }
        return {
          name: f.name,
          type: f.type,
          config: f.config ?? {},
          values: f.values ?? [],
          labels: f.labels
        };
      });
      return {
        refId: frame.refId,
        name: frame.name,
        meta: frame.meta,
        fields,
        length: frame.length ?? fields.reduce((m, field) => Math.max(m, field.values.length), 0)
      };
    });
  }
  const cancelled = /* @__PURE__ */ new Set();
  function handlePanelPipelineMessage(msg, post) {
    if (msg == null || msg.id == null) return;
    if (msg.type === "cancel") {
      cancelled.add(msg.id);
      return;
    }
    if (cancelled.has(msg.id)) {
      cancelled.delete(msg.id);
      post({
        id: msg.id,
        generation: msg.generation,
        ok: false,
        error: "aborted",
        aborted: true
      });
      return;
    }
    try {
      const series = unpackWireFrames(msg.frames ?? []);
      const compiled = getCompiledPipeline({
        transformations: msg.transformations ?? [],
        fieldConfigDefaults: msg.fieldConfigDefaults ?? {},
        fieldConfigOverrides: msg.fieldConfigOverrides ?? []
      });
      if (cancelled.has(msg.id)) {
        cancelled.delete(msg.id);
        post({
          id: msg.id,
          generation: msg.generation,
          ok: false,
          error: "aborted",
          aborted: true
        });
        return;
      }
      const out = runCompiledPipeline(series, compiled, { withTrace: false });
      if (cancelled.has(msg.id)) {
        cancelled.delete(msg.id);
        post({
          id: msg.id,
          generation: msg.generation,
          ok: false,
          error: "aborted",
          aborted: true
        });
        return;
      }
      const packed = packFramesForTransfer(out.frames);
      post(
        {
          id: msg.id,
          generation: msg.generation,
          ok: true,
          frames: packed.frames
        },
        packed.transfer
      );
    } catch (e) {
      post({
        id: msg.id,
        generation: msg.generation,
        ok: false,
        error: e instanceof Error ? e.message : String(e)
      });
    }
  }
  function onMessage(ev) {
    handlePanelPipelineMessage(ev.data, (res, transfer) => {
      const scope = self;
      if (transfer?.length) scope.postMessage(res, transfer);
      else scope.postMessage(res);
    });
  }
  const isDedicatedWorker = typeof WorkerGlobalScope !== "undefined" && typeof self !== "undefined" && self instanceof WorkerGlobalScope;
  if (isDedicatedWorker) {
    self.onmessage = onMessage;
  }
})();
//# sourceMappingURL=panelPipelineWorker-D7_wrugH.js.map
