import {
  __commonJS,
  __toESM
} from "./chunk-Z67LV52D.js";

// ../../node_modules/fractional-indexing/index.js
var require_fractional_indexing = __commonJS({
  "../../node_modules/fractional-indexing/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.generateNKeysBetween = exports.generateKeyBetween = exports.BASE_62_DIGITS = void 0;
    exports.BASE_62_DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    var SMALLEST_INTEGER = "A00000000000000000000000000";
    var INTEGER_ZERO = "a0";
    function midpoint(a, b, digits) {
      if (b !== null && a >= b) {
        throw new Error(a + " >= " + b);
      }
      if (a.slice(-1) === "0" || b && b.slice(-1) === "0") {
        throw new Error("trailing zero");
      }
      if (b) {
        let n = 0;
        while ((a[n] || "0") === b[n]) {
          n++;
        }
        if (n > 0) {
          return b.slice(0, n) + midpoint(a.slice(n), b.slice(n), digits);
        }
      }
      const digitA = a ? digits.indexOf(a[0]) : 0;
      const digitB = b !== null ? digits.indexOf(b[0]) : digits.length;
      if (digitB - digitA > 1) {
        const midDigit = Math.round(0.5 * (digitA + digitB));
        return digits[midDigit];
      } else {
        if (b && b.length > 1) {
          return b.slice(0, 1);
        } else {
          return digits[digitA] + midpoint(a.slice(1), null, digits);
        }
      }
    }
    function validateInteger(int) {
      if (int.length !== getIntegerLength(int[0])) {
        throw new Error("invalid integer part of order key: " + int);
      }
    }
    function getIntegerLength(head) {
      if (head >= "a" && head <= "z") {
        return head.charCodeAt(0) - "a".charCodeAt(0) + 2;
      } else if (head >= "A" && head <= "Z") {
        return "Z".charCodeAt(0) - head.charCodeAt(0) + 2;
      } else {
        throw new Error("invalid order key head: " + head);
      }
    }
    function getIntegerPart(key) {
      const integerPartLength = getIntegerLength(key[0]);
      if (integerPartLength > key.length) {
        throw new Error("invalid order key: " + key);
      }
      return key.slice(0, integerPartLength);
    }
    function validateOrderKey(key) {
      if (key === SMALLEST_INTEGER) {
        throw new Error("invalid order key: " + key);
      }
      const i = getIntegerPart(key);
      const f = key.slice(i.length);
      if (f.slice(-1) === "0") {
        throw new Error("invalid order key: " + key);
      }
    }
    function incrementInteger(x, digits) {
      validateInteger(x);
      const [head, ...digs] = x.split("");
      let carry = true;
      for (let i = digs.length - 1; carry && i >= 0; i--) {
        const d = digits.indexOf(digs[i]) + 1;
        if (d === digits.length) {
          digs[i] = "0";
        } else {
          digs[i] = digits[d];
          carry = false;
        }
      }
      if (carry) {
        if (head === "Z") {
          return "a0";
        }
        if (head === "z") {
          return null;
        }
        const h = String.fromCharCode(head.charCodeAt(0) + 1);
        if (h > "a") {
          digs.push("0");
        } else {
          digs.pop();
        }
        return h + digs.join("");
      } else {
        return head + digs.join("");
      }
    }
    function decrementInteger(x, digits) {
      validateInteger(x);
      const [head, ...digs] = x.split("");
      let borrow = true;
      for (let i = digs.length - 1; borrow && i >= 0; i--) {
        const d = digits.indexOf(digs[i]) - 1;
        if (d === -1) {
          digs[i] = digits.slice(-1);
        } else {
          digs[i] = digits[d];
          borrow = false;
        }
      }
      if (borrow) {
        if (head === "a") {
          return "Z" + digits.slice(-1);
        }
        if (head === "A") {
          return null;
        }
        const h = String.fromCharCode(head.charCodeAt(0) - 1);
        if (h < "Z") {
          digs.push(digits.slice(-1));
        } else {
          digs.pop();
        }
        return h + digs.join("");
      } else {
        return head + digs.join("");
      }
    }
    function generateKeyBetween2(a, b, digits = exports.BASE_62_DIGITS) {
      if (a !== null) {
        validateOrderKey(a);
      }
      if (b !== null) {
        validateOrderKey(b);
      }
      if (a !== null && b !== null && a >= b) {
        throw new Error(a + " >= " + b);
      }
      if (a === null) {
        if (b === null) {
          return INTEGER_ZERO;
        }
        const ib2 = getIntegerPart(b);
        const fb2 = b.slice(ib2.length);
        if (ib2 === SMALLEST_INTEGER) {
          return ib2 + midpoint("", fb2, digits);
        }
        if (ib2 < b) {
          return ib2;
        }
        const res = decrementInteger(ib2, digits);
        if (res === null) {
          throw new Error("cannot decrement any more");
        }
        return res;
      }
      if (b === null) {
        const ia2 = getIntegerPart(a);
        const fa2 = a.slice(ia2.length);
        const i2 = incrementInteger(ia2, digits);
        return i2 === null ? ia2 + midpoint(fa2, null, digits) : i2;
      }
      const ia = getIntegerPart(a);
      const fa = a.slice(ia.length);
      const ib = getIntegerPart(b);
      const fb = b.slice(ib.length);
      if (ia === ib) {
        return ia + midpoint(fa, fb, digits);
      }
      const i = incrementInteger(ia, digits);
      if (i === null) {
        throw new Error("cannot increment any more");
      }
      if (i < b) {
        return i;
      }
      return ia + midpoint(fa, null, digits);
    }
    exports.generateKeyBetween = generateKeyBetween2;
    function generateNKeysBetween(a, b, n, digits = exports.BASE_62_DIGITS) {
      if (n === 0) {
        return [];
      }
      if (n === 1) {
        return [generateKeyBetween2(a, b, digits)];
      }
      if (b === null) {
        let c2 = generateKeyBetween2(a, b, digits);
        const result = [c2];
        for (let i = 0; i < n - 1; i++) {
          c2 = generateKeyBetween2(c2, b, digits);
          result.push(c2);
        }
        return result;
      }
      if (a === null) {
        let c2 = generateKeyBetween2(a, b, digits);
        const result = [c2];
        for (let i = 0; i < n - 1; i++) {
          c2 = generateKeyBetween2(a, c2, digits);
          result.push(c2);
        }
        result.reverse();
        return result;
      }
      const mid = Math.floor(n / 2);
      const c = generateKeyBetween2(a, b, digits);
      return [
        ...generateNKeysBetween(a, c, mid, digits),
        c,
        ...generateNKeysBetween(c, b, n - mid - 1, digits)
      ];
    }
    exports.generateNKeysBetween = generateNKeysBetween;
  }
});

// ../../node_modules/cuid/lib/pad.js
var require_pad = __commonJS({
  "../../node_modules/cuid/lib/pad.js"(exports, module) {
    module.exports = function pad(num, size) {
      var s = "000000000" + num;
      return s.substr(s.length - size);
    };
  }
});

// ../../node_modules/cuid/lib/fingerprint.browser.js
var require_fingerprint_browser = __commonJS({
  "../../node_modules/cuid/lib/fingerprint.browser.js"(exports, module) {
    var pad = require_pad();
    var env = typeof window === "object" ? window : self;
    var globalCount = Object.keys(env).length;
    var mimeTypesLength = navigator.mimeTypes ? navigator.mimeTypes.length : 0;
    var clientId = pad((mimeTypesLength + navigator.userAgent.length).toString(36) + globalCount.toString(36), 4);
    module.exports = function fingerprint() {
      return clientId;
    };
  }
});

// ../../node_modules/cuid/lib/getRandomValue.browser.js
var require_getRandomValue_browser = __commonJS({
  "../../node_modules/cuid/lib/getRandomValue.browser.js"(exports, module) {
    var getRandomValue;
    var crypto = typeof window !== "undefined" && (window.crypto || window.msCrypto) || typeof self !== "undefined" && self.crypto;
    if (crypto) {
      lim = Math.pow(2, 32) - 1;
      getRandomValue = function() {
        return Math.abs(crypto.getRandomValues(new Uint32Array(1))[0] / lim);
      };
    } else {
      getRandomValue = Math.random;
    }
    var lim;
    module.exports = getRandomValue;
  }
});

// ../../node_modules/cuid/index.js
var require_cuid = __commonJS({
  "../../node_modules/cuid/index.js"(exports, module) {
    var fingerprint = require_fingerprint_browser();
    var pad = require_pad();
    var getRandomValue = require_getRandomValue_browser();
    var c = 0;
    var blockSize = 4;
    var base = 36;
    var discreteValues = Math.pow(base, blockSize);
    function randomBlock() {
      return pad((getRandomValue() * discreteValues << 0).toString(base), blockSize);
    }
    function safeCounter() {
      c = c < discreteValues ? c : 0;
      c++;
      return c - 1;
    }
    function cuid2() {
      var letter = "c", timestamp = new Date().getTime().toString(base), counter = pad(safeCounter().toString(base), blockSize), print = fingerprint(), random = randomBlock() + randomBlock();
      return letter + timestamp + counter + print + random;
    }
    cuid2.slug = function slug() {
      var date = new Date().getTime().toString(36), counter = safeCounter().toString(36).slice(-4), print = fingerprint().slice(0, 1) + fingerprint().slice(-1), random = randomBlock().slice(-2);
      return date.slice(-2) + counter + print + random;
    };
    cuid2.isCuid = function isCuid(stringToCheck) {
      if (typeof stringToCheck !== "string")
        return false;
      if (stringToCheck.startsWith("c"))
        return true;
      return false;
    };
    cuid2.isSlug = function isSlug(stringToCheck) {
      if (typeof stringToCheck !== "string")
        return false;
      var stringLength = stringToCheck.length;
      if (stringLength >= 7 && stringLength <= 10)
        return true;
      return false;
    };
    cuid2.fingerprint = fingerprint;
    module.exports = cuid2;
  }
});

// src/constants.ts
var HTML_ID_APP_ROOT = "root";
var HTML_ID_TOOLPAD_APP_RENDER_PARAMS = "toolpad-dom";

// src/appDom.ts
var import_fractional_indexing = __toESM(require_fractional_indexing());
var import_cuid = __toESM(require_cuid());
function compareFractionalIndex(index1, index2) {
  if (index1 === index2) {
    return 0;
  }
  return index1 > index2 ? 1 : -1;
}
function isType(node, type) {
  return node.type === type;
}
function assertIsType(node, type) {
  if (!isType(node, type)) {
    throw new Error(`Invariant: expected node type "${type}" but got "${node.type}"`);
  }
}
function getMaybeNode(dom, nodeId, type) {
  const node = dom.nodes[nodeId];
  if (!node) {
    return null;
  }
  if (type) {
    assertIsType(node, type);
  }
  return node;
}
function getNode(dom, nodeId, type) {
  const node = getMaybeNode(dom, nodeId, type);
  if (!node) {
    throw new Error(`Node "${nodeId}" not found`);
  }
  return node;
}
function assertIsApp(node) {
  assertIsType(node, "app");
}
function isElement(node) {
  return isType(node, "element");
}
function isQueryState(node) {
  return isType(node, "queryState");
}
function getApp(dom) {
  const rootNode = getNode(dom, dom.root);
  assertIsApp(rootNode);
  return rootNode;
}
var childrenMemo = /* @__PURE__ */ new WeakMap();
function getChildNodes(dom, parent) {
  let domChildrenMemo = childrenMemo.get(dom);
  if (!domChildrenMemo) {
    domChildrenMemo = /* @__PURE__ */ new Map();
    childrenMemo.set(dom, domChildrenMemo);
  }
  let result = domChildrenMemo.get(parent.id);
  if (!result) {
    result = {};
    domChildrenMemo.set(parent.id, result);
    const allNodeChildren = Object.values(dom.nodes).filter((node) => node.parentId === parent.id);
    for (const child of allNodeChildren) {
      const prop = child.parentProp || "children";
      let existing = result[prop];
      if (!existing) {
        existing = [];
        result[prop] = existing;
      }
      existing.push(child);
    }
    for (const childArray of Object.values(result)) {
      childArray == null ? void 0 : childArray.sort((node1, node2) => {
        if (!node1.parentIndex || !node2.parentIndex) {
          throw new Error(`Invariant: nodes inside the dom should have a parentIndex if they have a parent`);
        }
        return compareFractionalIndex(node1.parentIndex, node2.parentIndex);
      });
    }
  }
  return result;
}
function getDescendants(dom, node) {
  const children = Object.values(getChildNodes(dom, node)).flat().filter(Boolean);
  return [...children, ...children.flatMap((child) => getDescendants(dom, child))];
}
function fromConstPropValue(prop) {
  if (!prop) {
    return void 0;
  }
  if (prop.type !== "const") {
    throw new Error(`trying to unbox a non-constant prop value`);
  }
  return prop.value;
}
function fromConstPropValues(props) {
  const result = {};
  Object.entries(props).forEach(([name, prop]) => {
    if (prop) {
      result[name] = fromConstPropValue(prop);
    }
  });
  return result;
}

// runtime/pageEditor/AppThemeProvider.tsx
import * as React from "react";
import { createTheme, ThemeProvider } from "@mui/material";
import * as colors from "@mui/material/colors";
function createThemeOptions(toolpadTheme) {
  const palette = {};
  const primary = toolpadTheme["palette.primary.main"];
  if (primary) {
    palette.primary = colors[primary];
  }
  const secondary = toolpadTheme["palette.secondary.main"];
  if (secondary) {
    palette.secondary = colors[secondary];
  }
  return { palette };
}
function createToolpadTheme(themeNode) {
  const options = themeNode ? createThemeOptions(fromConstPropValues(themeNode.theme)) : {};
  return createTheme(options);
}
function AppThemeProvider({ node, children }) {
  const theme = React.useMemo(() => createToolpadTheme(node), [node]);
  return /* @__PURE__ */ React.createElement(ThemeProvider, {
    theme
  }, children);
}

export {
  HTML_ID_APP_ROOT,
  HTML_ID_TOOLPAD_APP_RENDER_PARAMS,
  getNode,
  isElement,
  isQueryState,
  getApp,
  getChildNodes,
  getDescendants,
  AppThemeProvider
};
