import { warn as u } from "./accelbyte-widgets736.mjs";
import { createStringifyContext as d } from "./accelbyte-widgets740.mjs";
import { isAlias as a, isSeq as S, isScalar as g, isMap as y, isNode as b } from "./accelbyte-widgets711.mjs";
import { Scalar as p } from "./accelbyte-widgets651.mjs";
import { toJS as f } from "./accelbyte-widgets716.mjs";
const l = "<<";
function m(r, e, { key: i, value: o }) {
  if (r != null && r.doc.schema.merge && M(i))
    if (o = a(o) ? o.resolve(r.doc) : o, S(o))
      for (const n of o.items)
        c(r, e, n);
    else if (Array.isArray(o))
      for (const n of o)
        c(r, e, n);
    else
      c(r, e, o);
  else {
    const n = f(i, "", r);
    if (e instanceof Map)
      e.set(n, f(o, n, r));
    else if (e instanceof Set)
      e.add(n);
    else {
      const t = h(i, n, r), s = f(o, t, r);
      t in e ? Object.defineProperty(e, t, {
        value: s,
        writable: !0,
        enumerable: !0,
        configurable: !0
      }) : e[t] = s;
    }
  }
  return e;
}
const M = (r) => r === l || g(r) && r.value === l && (!r.type || r.type === p.PLAIN);
function c(r, e, i) {
  const o = r && a(i) ? i.resolve(r.doc) : i;
  if (!y(o))
    throw new Error("Merge sources must be maps or map aliases");
  const n = o.toJSON(null, r, Map);
  for (const [t, s] of n)
    e instanceof Map ? e.has(t) || e.set(t, s) : e instanceof Set ? e.add(t) : Object.prototype.hasOwnProperty.call(e, t) || Object.defineProperty(e, t, {
      value: s,
      writable: !0,
      enumerable: !0,
      configurable: !0
    });
  return e;
}
function h(r, e, i) {
  if (e === null)
    return "";
  if (typeof e != "object")
    return String(e);
  if (b(r) && i && i.doc) {
    const o = d(i.doc, {});
    o.anchors = /* @__PURE__ */ new Set();
    for (const t of i.anchors.keys())
      o.anchors.add(t.anchor);
    o.inFlow = !0, o.inStringifyKey = !0;
    const n = r.toString(o);
    if (!i.mapKeyWarned) {
      let t = JSON.stringify(n);
      t.length > 40 && (t = t.substring(0, 36) + '..."'), u(i.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${t}. Set mapAsMap: true to use object keys.`), i.mapKeyWarned = !0;
    }
    return n;
  }
  return JSON.stringify(e);
}
export {
  m as addPairToJSMap
};
