var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import { t as __commonJSMin } from "./chunk-BNovOVIE.js";
import { _ as Logger } from "./button-Dj4BTre0.js";
import { t as require_compiler_runtime } from "./compiler-runtime-CEbnTgxf.js";
import { u as createLucideIcon } from "./dist-D3ZI9nhS.js";
import { r as KnownQueryParams } from "./constants-D0gkYoE2.js";
import { f as waitFor, p as isIslands, u as store, y as atom } from "./useTheme-DykuNHR2.js";
import { t as invariant } from "./invariant-UcGKQEhF.js";
var CircleQuestionMark = createLucideIcon("circle-question-mark", [
  ["circle", {
    cx: "12",
    cy: "12",
    r: "10",
    key: "1mglay"
  }],
  ["path", {
    d: "M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",
    key: "1u773s"
  }],
  ["path", {
    d: "M12 17h.01",
    key: "p32p05"
  }]
]);
function isWasm() {
  return typeof document < "u" && document.querySelector("marimo-wasm") !== null;
}
var Deferred = class {
  constructor() {
    __publicField(this, "status", "pending");
    __publicField(this, "value");
    this.promise = new Promise((e, b) => {
      this.reject = (e2) => {
        this.status = "rejected", b(e2);
      }, this.resolve = (b2) => {
        this.status = "resolved", isPromiseLike(b2) || (this.value = b2), e(b2);
      };
    });
  }
};
function isPromiseLike(e) {
  return typeof e == "object" && !!e && "then" in e && typeof e.then == "function";
}
const WebSocketState = {
  NOT_STARTED: "NOT_STARTED",
  CONNECTING: "CONNECTING",
  OPEN: "OPEN",
  CLOSING: "CLOSING",
  CLOSED: "CLOSED"
}, connectionAtom = atom({ state: WebSocketState.NOT_STARTED });
function waitForConnectionOpen() {
  return waitFor(connectionAtom, (e) => e.state === WebSocketState.OPEN);
}
atom((e) => e(connectionAtom).state === WebSocketState.CONNECTING), atom((e) => e(connectionAtom).state === WebSocketState.OPEN), atom((e) => {
  let b = e(connectionAtom);
  return b.state === WebSocketState.OPEN || b.state === WebSocketState.NOT_STARTED;
}), atom((e) => e(connectionAtom).state === WebSocketState.CLOSED), atom((e) => e(connectionAtom).state === WebSocketState.NOT_STARTED);
var require__u64 = /* @__PURE__ */ __commonJSMin(((e) => {
  Object.defineProperty(e, "__esModule", { value: true }), e.toBig = e.shrSL = e.shrSH = e.rotrSL = e.rotrSH = e.rotrBL = e.rotrBH = e.rotr32L = e.rotr32H = e.rotlSL = e.rotlSH = e.rotlBL = e.rotlBH = e.add5L = e.add5H = e.add4L = e.add4H = e.add3L = e.add3H = void 0, e.add = L, e.fromBig = S, e.split = C;
  var b = /* @__PURE__ */ BigInt(2 ** 32 - 1), x = /* @__PURE__ */ BigInt(32);
  function S(e2, S2 = false) {
    return S2 ? {
      h: Number(e2 & b),
      l: Number(e2 >> x & b)
    } : {
      h: Number(e2 >> x & b) | 0,
      l: Number(e2 & b) | 0
    };
  }
  function C(e2, b2 = false) {
    let x2 = e2.length, C2 = new Uint32Array(x2), w2 = new Uint32Array(x2);
    for (let T2 = 0; T2 < x2; T2++) {
      let { h: x3, l: E2 } = S(e2[T2], b2);
      [C2[T2], w2[T2]] = [x3, E2];
    }
    return [C2, w2];
  }
  var w = (e2, b2) => BigInt(e2 >>> 0) << x | BigInt(b2 >>> 0);
  e.toBig = w;
  var T = (e2, b2, x2) => e2 >>> x2;
  e.shrSH = T;
  var E = (e2, b2, x2) => e2 << 32 - x2 | b2 >>> x2;
  e.shrSL = E;
  var D = (e2, b2, x2) => e2 >>> x2 | b2 << 32 - x2;
  e.rotrSH = D;
  var O = (e2, b2, x2) => e2 << 32 - x2 | b2 >>> x2;
  e.rotrSL = O;
  var k = (e2, b2, x2) => e2 << 64 - x2 | b2 >>> x2 - 32;
  e.rotrBH = k;
  var A = (e2, b2, x2) => e2 >>> x2 - 32 | b2 << 64 - x2;
  e.rotrBL = A;
  var j = (e2, b2) => b2;
  e.rotr32H = j;
  var M = (e2, b2) => e2;
  e.rotr32L = M;
  var N = (e2, b2, x2) => e2 << x2 | b2 >>> 32 - x2;
  e.rotlSH = N;
  var P = (e2, b2, x2) => b2 << x2 | e2 >>> 32 - x2;
  e.rotlSL = P;
  var F = (e2, b2, x2) => b2 << x2 - 32 | e2 >>> 64 - x2;
  e.rotlBH = F;
  var I = (e2, b2, x2) => e2 << x2 - 32 | b2 >>> 64 - x2;
  e.rotlBL = I;
  function L(e2, b2, x2, S2) {
    let C2 = (b2 >>> 0) + (S2 >>> 0);
    return {
      h: e2 + x2 + (C2 / 2 ** 32 | 0) | 0,
      l: C2 | 0
    };
  }
  var R = (e2, b2, x2) => (e2 >>> 0) + (b2 >>> 0) + (x2 >>> 0);
  e.add3L = R;
  var z = (e2, b2, x2, S2) => b2 + x2 + S2 + (e2 / 2 ** 32 | 0) | 0;
  e.add3H = z;
  var B = (e2, b2, x2, S2) => (e2 >>> 0) + (b2 >>> 0) + (x2 >>> 0) + (S2 >>> 0);
  e.add4L = B;
  var V = (e2, b2, x2, S2, C2) => b2 + x2 + S2 + C2 + (e2 / 2 ** 32 | 0) | 0;
  e.add4H = V;
  var H = (e2, b2, x2, S2, C2) => (e2 >>> 0) + (b2 >>> 0) + (x2 >>> 0) + (S2 >>> 0) + (C2 >>> 0);
  e.add5L = H;
  var U = (e2, b2, x2, S2, C2, w2) => b2 + x2 + S2 + C2 + w2 + (e2 / 2 ** 32 | 0) | 0;
  e.add5H = U, e.default = {
    fromBig: S,
    split: C,
    toBig: w,
    shrSH: T,
    shrSL: E,
    rotrSH: D,
    rotrSL: O,
    rotrBH: k,
    rotrBL: A,
    rotr32H: j,
    rotr32L: M,
    rotlSH: N,
    rotlSL: P,
    rotlBH: F,
    rotlBL: I,
    add: L,
    add3L: R,
    add3H: z,
    add4L: B,
    add4H: V,
    add5H: U,
    add5L: H
  };
})), require_crypto = /* @__PURE__ */ __commonJSMin(((e) => {
  Object.defineProperty(e, "__esModule", { value: true }), e.crypto = void 0, e.crypto = typeof globalThis == "object" && "crypto" in globalThis ? globalThis.crypto : void 0;
})), require_utils = /* @__PURE__ */ __commonJSMin(((e) => {
  Object.defineProperty(e, "__esModule", { value: true }), e.wrapXOFConstructorWithOpts = e.wrapConstructorWithOpts = e.wrapConstructor = e.Hash = e.nextTick = e.swap32IfBE = e.byteSwapIfBE = e.swap8IfBE = e.isLE = void 0, e.isBytes = x, e.anumber = S, e.abytes = C, e.ahash = w, e.aexists = T, e.aoutput = E, e.u8 = D, e.u32 = O, e.clean = k, e.createView = A, e.rotr = j, e.rotl = M, e.byteSwap = N, e.byteSwap32 = P, e.bytesToHex = R, e.hexToBytes = V, e.asyncLoop = H, e.utf8ToBytes = U, e.bytesToUtf8 = W, e.toBytes = G, e.kdfInputToBytes = K, e.concatBytes = q, e.checkOpts = J, e.createHasher = Y, e.createOptHasher = X, e.createXOFer = Z, e.randomBytes = Q;
  var b = require_crypto();
  function x(e2) {
    return e2 instanceof Uint8Array || ArrayBuffer.isView(e2) && e2.constructor.name === "Uint8Array";
  }
  function S(e2) {
    if (!Number.isSafeInteger(e2) || e2 < 0) throw Error("positive integer expected, got " + e2);
  }
  function C(e2, ...b2) {
    if (!x(e2)) throw Error("Uint8Array expected");
    if (b2.length > 0 && !b2.includes(e2.length)) throw Error("Uint8Array expected of length " + b2 + ", got length=" + e2.length);
  }
  function w(e2) {
    if (typeof e2 != "function" || typeof e2.create != "function") throw Error("Hash should be wrapped by utils.createHasher");
    S(e2.outputLen), S(e2.blockLen);
  }
  function T(e2, b2 = true) {
    if (e2.destroyed) throw Error("Hash instance has been destroyed");
    if (b2 && e2.finished) throw Error("Hash#digest() has already been called");
  }
  function E(e2, b2) {
    C(e2);
    let x2 = b2.outputLen;
    if (e2.length < x2) throw Error("digestInto() expects output buffer of length at least " + x2);
  }
  function D(e2) {
    return new Uint8Array(e2.buffer, e2.byteOffset, e2.byteLength);
  }
  function O(e2) {
    return new Uint32Array(e2.buffer, e2.byteOffset, Math.floor(e2.byteLength / 4));
  }
  function k(...e2) {
    for (let b2 = 0; b2 < e2.length; b2++) e2[b2].fill(0);
  }
  function A(e2) {
    return new DataView(e2.buffer, e2.byteOffset, e2.byteLength);
  }
  function j(e2, b2) {
    return e2 << 32 - b2 | e2 >>> b2;
  }
  function M(e2, b2) {
    return e2 << b2 | e2 >>> 32 - b2 >>> 0;
  }
  e.isLE = (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
  function N(e2) {
    return e2 << 24 & 4278190080 | e2 << 8 & 16711680 | e2 >>> 8 & 65280 | e2 >>> 24 & 255;
  }
  e.swap8IfBE = e.isLE ? (e2) => e2 : (e2) => N(e2), e.byteSwapIfBE = e.swap8IfBE;
  function P(e2) {
    for (let b2 = 0; b2 < e2.length; b2++) e2[b2] = N(e2[b2]);
    return e2;
  }
  e.swap32IfBE = e.isLE ? (e2) => e2 : P;
  var F = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex == "function" && typeof Uint8Array.fromHex == "function")(), I = /* @__PURE__ */ Array.from({ length: 256 }, (e2, b2) => b2.toString(16).padStart(2, "0"));
  function R(e2) {
    if (C(e2), F) return e2.toHex();
    let b2 = "";
    for (let x2 = 0; x2 < e2.length; x2++) b2 += I[e2[x2]];
    return b2;
  }
  var z = {
    _0: 48,
    _9: 57,
    A: 65,
    F: 70,
    a: 97,
    f: 102
  };
  function B(e2) {
    if (e2 >= z._0 && e2 <= z._9) return e2 - z._0;
    if (e2 >= z.A && e2 <= z.F) return e2 - (z.A - 10);
    if (e2 >= z.a && e2 <= z.f) return e2 - (z.a - 10);
  }
  function V(e2) {
    if (typeof e2 != "string") throw Error("hex string expected, got " + typeof e2);
    if (F) return Uint8Array.fromHex(e2);
    let b2 = e2.length, x2 = b2 / 2;
    if (b2 % 2) throw Error("hex string expected, got unpadded hex of length " + b2);
    let S2 = new Uint8Array(x2);
    for (let b3 = 0, C2 = 0; b3 < x2; b3++, C2 += 2) {
      let x3 = B(e2.charCodeAt(C2)), w2 = B(e2.charCodeAt(C2 + 1));
      if (x3 === void 0 || w2 === void 0) {
        let b4 = e2[C2] + e2[C2 + 1];
        throw Error('hex string expected, got non-hex character "' + b4 + '" at index ' + C2);
      }
      S2[b3] = x3 * 16 + w2;
    }
    return S2;
  }
  e.nextTick = async () => {
  };
  async function H(b2, x2, S2) {
    let C2 = Date.now();
    for (let w2 = 0; w2 < b2; w2++) {
      S2(w2);
      let b3 = Date.now() - C2;
      b3 >= 0 && b3 < x2 || (await (0, e.nextTick)(), C2 += b3);
    }
  }
  function U(e2) {
    if (typeof e2 != "string") throw Error("string expected");
    return new Uint8Array(new TextEncoder().encode(e2));
  }
  function W(e2) {
    return new TextDecoder().decode(e2);
  }
  function G(e2) {
    return typeof e2 == "string" && (e2 = U(e2)), C(e2), e2;
  }
  function K(e2) {
    return typeof e2 == "string" && (e2 = U(e2)), C(e2), e2;
  }
  function q(...e2) {
    let b2 = 0;
    for (let x3 = 0; x3 < e2.length; x3++) {
      let S2 = e2[x3];
      C(S2), b2 += S2.length;
    }
    let x2 = new Uint8Array(b2);
    for (let b3 = 0, S2 = 0; b3 < e2.length; b3++) {
      let C2 = e2[b3];
      x2.set(C2, S2), S2 += C2.length;
    }
    return x2;
  }
  function J(e2, b2) {
    if (b2 !== void 0 && {}.toString.call(b2) !== "[object Object]") throw Error("options should be object or undefined");
    return Object.assign(e2, b2);
  }
  e.Hash = class {
  };
  function Y(e2) {
    let b2 = (b3) => e2().update(G(b3)).digest(), x2 = e2();
    return b2.outputLen = x2.outputLen, b2.blockLen = x2.blockLen, b2.create = () => e2(), b2;
  }
  function X(e2) {
    let b2 = (b3, x3) => e2(x3).update(G(b3)).digest(), x2 = e2({});
    return b2.outputLen = x2.outputLen, b2.blockLen = x2.blockLen, b2.create = (b3) => e2(b3), b2;
  }
  function Z(e2) {
    let b2 = (b3, x3) => e2(x3).update(G(b3)).digest(), x2 = e2({});
    return b2.outputLen = x2.outputLen, b2.blockLen = x2.blockLen, b2.create = (b3) => e2(b3), b2;
  }
  e.wrapConstructor = Y, e.wrapConstructorWithOpts = X, e.wrapXOFConstructorWithOpts = Z;
  function Q(e2 = 32) {
    if (b.crypto && typeof b.crypto.getRandomValues == "function") return b.crypto.getRandomValues(new Uint8Array(e2));
    if (b.crypto && typeof b.crypto.randomBytes == "function") return Uint8Array.from(b.crypto.randomBytes(e2));
    throw Error("crypto.getRandomValues must be defined");
  }
})), require_sha3 = /* @__PURE__ */ __commonJSMin(((e) => {
  Object.defineProperty(e, "__esModule", { value: true }), e.shake256 = e.shake128 = e.keccak_512 = e.keccak_384 = e.keccak_256 = e.keccak_224 = e.sha3_512 = e.sha3_384 = e.sha3_256 = e.sha3_224 = e.Keccak = void 0, e.keccakP = L;
  var b = require__u64(), x = require_utils(), S = BigInt(0), C = BigInt(1), w = BigInt(2), T = BigInt(7), E = BigInt(256), D = BigInt(113), O = [], k = [], A = [];
  for (let e2 = 0, b2 = C, x2 = 1, j2 = 0; e2 < 24; e2++) {
    [x2, j2] = [j2, (2 * x2 + 3 * j2) % 5], O.push(2 * (5 * j2 + x2)), k.push((e2 + 1) * (e2 + 2) / 2 % 64);
    let M2 = S;
    for (let e3 = 0; e3 < 7; e3++) b2 = (b2 << C ^ (b2 >> T) * D) % E, b2 & w && (M2 ^= C << (C << /* @__PURE__ */ BigInt(e3)) - C);
    A.push(M2);
  }
  var j = (0, b.split)(A, true), M = j[0], N = j[1], P = (e2, x2, S2) => S2 > 32 ? (0, b.rotlBH)(e2, x2, S2) : (0, b.rotlSH)(e2, x2, S2), F = (e2, x2, S2) => S2 > 32 ? (0, b.rotlBL)(e2, x2, S2) : (0, b.rotlSL)(e2, x2, S2);
  function L(e2, b2 = 24) {
    let S2 = new Uint32Array(10);
    for (let x2 = 24 - b2; x2 < 24; x2++) {
      for (let b4 = 0; b4 < 10; b4++) S2[b4] = e2[b4] ^ e2[b4 + 10] ^ e2[b4 + 20] ^ e2[b4 + 30] ^ e2[b4 + 40];
      for (let b4 = 0; b4 < 10; b4 += 2) {
        let x3 = (b4 + 8) % 10, C3 = (b4 + 2) % 10, w2 = S2[C3], T2 = S2[C3 + 1], E2 = P(w2, T2, 1) ^ S2[x3], D2 = F(w2, T2, 1) ^ S2[x3 + 1];
        for (let x4 = 0; x4 < 50; x4 += 10) e2[b4 + x4] ^= E2, e2[b4 + x4 + 1] ^= D2;
      }
      let b3 = e2[2], C2 = e2[3];
      for (let x3 = 0; x3 < 24; x3++) {
        let S3 = k[x3], w2 = P(b3, C2, S3), T2 = F(b3, C2, S3), E2 = O[x3];
        b3 = e2[E2], C2 = e2[E2 + 1], e2[E2] = w2, e2[E2 + 1] = T2;
      }
      for (let b4 = 0; b4 < 50; b4 += 10) {
        for (let x3 = 0; x3 < 10; x3++) S2[x3] = e2[b4 + x3];
        for (let x3 = 0; x3 < 10; x3++) e2[b4 + x3] ^= ~S2[(x3 + 2) % 10] & S2[(x3 + 4) % 10];
      }
      e2[0] ^= M[x2], e2[1] ^= N[x2];
    }
    (0, x.clean)(S2);
  }
  var z = class e2 extends x.Hash {
    constructor(e3, b2, S2, C2 = false, w2 = 24) {
      if (super(), this.pos = 0, this.posOut = 0, this.finished = false, this.destroyed = false, this.enableXOF = false, this.blockLen = e3, this.suffix = b2, this.outputLen = S2, this.enableXOF = C2, this.rounds = w2, (0, x.anumber)(S2), !(0 < e3 && e3 < 200)) throw Error("only keccak-f1600 function is supported");
      this.state = new Uint8Array(200), this.state32 = (0, x.u32)(this.state);
    }
    clone() {
      return this._cloneInto();
    }
    keccak() {
      (0, x.swap32IfBE)(this.state32), L(this.state32, this.rounds), (0, x.swap32IfBE)(this.state32), this.posOut = 0, this.pos = 0;
    }
    update(e3) {
      (0, x.aexists)(this), e3 = (0, x.toBytes)(e3), (0, x.abytes)(e3);
      let { blockLen: b2, state: S2 } = this, C2 = e3.length;
      for (let x2 = 0; x2 < C2; ) {
        let w2 = Math.min(b2 - this.pos, C2 - x2);
        for (let b3 = 0; b3 < w2; b3++) S2[this.pos++] ^= e3[x2++];
        this.pos === b2 && this.keccak();
      }
      return this;
    }
    finish() {
      if (this.finished) return;
      this.finished = true;
      let { state: e3, suffix: b2, pos: x2, blockLen: S2 } = this;
      e3[x2] ^= b2, b2 & 128 && x2 === S2 - 1 && this.keccak(), e3[S2 - 1] ^= 128, this.keccak();
    }
    writeInto(e3) {
      (0, x.aexists)(this, false), (0, x.abytes)(e3), this.finish();
      let b2 = this.state, { blockLen: S2 } = this;
      for (let x2 = 0, C2 = e3.length; x2 < C2; ) {
        this.posOut >= S2 && this.keccak();
        let w2 = Math.min(S2 - this.posOut, C2 - x2);
        e3.set(b2.subarray(this.posOut, this.posOut + w2), x2), this.posOut += w2, x2 += w2;
      }
      return e3;
    }
    xofInto(e3) {
      if (!this.enableXOF) throw Error("XOF is not possible for this instance");
      return this.writeInto(e3);
    }
    xof(e3) {
      return (0, x.anumber)(e3), this.xofInto(new Uint8Array(e3));
    }
    digestInto(e3) {
      if ((0, x.aoutput)(e3, this), this.finished) throw Error("digest() was already called");
      return this.writeInto(e3), this.destroy(), e3;
    }
    digest() {
      return this.digestInto(new Uint8Array(this.outputLen));
    }
    destroy() {
      this.destroyed = true, (0, x.clean)(this.state);
    }
    _cloneInto(b2) {
      let { blockLen: x2, suffix: S2, outputLen: C2, rounds: w2, enableXOF: T2 } = this;
      return b2 || (b2 = new e2(x2, S2, C2, T2, w2)), b2.state32.set(this.state32), b2.pos = this.pos, b2.posOut = this.posOut, b2.finished = this.finished, b2.rounds = w2, b2.suffix = S2, b2.outputLen = C2, b2.enableXOF = T2, b2.destroyed = this.destroyed, b2;
    }
  };
  e.Keccak = z;
  var B = (e2, b2, S2) => (0, x.createHasher)(() => new z(b2, e2, S2));
  e.sha3_224 = (() => B(6, 144, 224 / 8))(), e.sha3_256 = (() => B(6, 136, 256 / 8))(), e.sha3_384 = (() => B(6, 104, 384 / 8))(), e.sha3_512 = (() => B(6, 72, 512 / 8))(), e.keccak_224 = (() => B(1, 144, 224 / 8))(), e.keccak_256 = (() => B(1, 136, 256 / 8))(), e.keccak_384 = (() => B(1, 104, 384 / 8))(), e.keccak_512 = (() => B(1, 72, 512 / 8))();
  var V = (e2, b2, S2) => (0, x.createXOFer)((x2 = {}) => new z(b2, e2, x2.dkLen === void 0 ? S2 : x2.dkLen, true));
  e.shake128 = (() => V(31, 168, 128 / 8))(), e.shake256 = (() => V(31, 136, 256 / 8))();
})), require_src = /* @__PURE__ */ __commonJSMin(((e, b) => {
  var { sha3_512: x } = require_sha3(), S = 24, C = 32, w = (e2 = 4, b2 = Math.random) => {
    let x2 = "";
    for (; x2.length < e2; ) x2 += Math.floor(b2() * 36).toString(36);
    return x2;
  };
  function T(e2) {
    let b2 = 0n;
    for (let x2 of e2.values()) {
      let e3 = BigInt(x2);
      b2 = (b2 << 8n) + e3;
    }
    return b2;
  }
  var E = (e2 = "") => T(x(e2)).toString(36).slice(1), D = Array.from({ length: 26 }, (e2, b2) => String.fromCharCode(b2 + 97)), O = (e2) => D[Math.floor(e2() * D.length)], k = ({ globalObj: e2 = typeof global < "u" ? global : typeof window < "u" ? window : {}, random: b2 = Math.random } = {}) => {
    let x2 = Object.keys(e2).toString();
    return E(x2.length ? x2 + w(C, b2) : w(C, b2)).substring(0, C);
  }, A = (e2) => () => e2++, j = 476782367, M = ({ random: e2 = Math.random, counter: b2 = A(Math.floor(e2() * j)), length: x2 = S, fingerprint: C2 = k({ random: e2 }) } = {}) => function() {
    let S2 = O(e2), T2 = Date.now().toString(36), D2 = b2().toString(36);
    return `${S2 + E(`${T2 + w(x2, e2) + D2 + C2}`).substring(1, x2)}`;
  }, N = M(), P = (e2, { minLength: b2 = 2, maxLength: x2 = C } = {}) => {
    let S2 = e2.length, w2 = /^[0-9a-z]+$/;
    try {
      if (typeof e2 == "string" && S2 >= b2 && S2 <= x2 && w2.test(e2)) return true;
    } finally {
    }
    return false;
  };
  b.exports.getConstants = () => ({
    defaultLength: S,
    bigLength: C
  }), b.exports.init = M, b.exports.createId = N, b.exports.bufToBigInt = T, b.exports.createCounter = A, b.exports.createFingerprint = k, b.exports.isCuid = P;
})), require_cuid2 = /* @__PURE__ */ __commonJSMin(((e, b) => {
  var { createId: x, init: S, getConstants: C, isCuid: w } = require_src();
  b.exports.createId = x, b.exports.init = S, b.exports.getConstants = C, b.exports.isCuid = w;
}));
function updateQueryParams(e) {
  let b = new URL(window.location.href);
  e(b.searchParams), window.history.replaceState({}, "", b.toString());
}
var urlRegex = /^(https?:\/\/\S+)$/;
function isUrl(e) {
  return typeof e == "string" && urlRegex.test(e);
}
function appendQueryParams({ href: e, queryParams: b, keys: x }) {
  let S = typeof b == "string" ? new URLSearchParams(b) : b;
  if (S.size === 0 || e.startsWith("http://") || e.startsWith("https://")) return e;
  let C = e.startsWith("#"), w = C && e.includes("?");
  if (C && !w) {
    let b2 = x ? [...S.entries()].filter(([e2]) => x.includes(e2)) : [...S.entries()], C2 = new URLSearchParams();
    for (let [e2, x2] of b2) C2.set(e2, x2);
    let w2 = C2.toString();
    return w2 ? `/?${w2}${e}` : e;
  }
  let T = e, E = "", D = new URLSearchParams(), O = C ? 1 : 0, k = e.indexOf("#", O);
  k !== -1 && (E = e.slice(k), T = e.slice(0, k));
  let A = T.indexOf("?");
  A !== -1 && (D = new URLSearchParams(T.slice(A + 1)), T = T.slice(0, A));
  let j = new URLSearchParams(D), M = x ? [...S.entries()].filter(([e2]) => x.includes(e2)) : [...S.entries()];
  for (let [e2, b2] of M) j.set(e2, b2);
  let N = j.toString();
  return N ? `${T}?${N}${E}` : e;
}
var createId = (0, require_cuid2().init)({ length: 6 });
function generateSessionId() {
  return `s_${createId()}`;
}
function isSessionId(e) {
  return e ? /^s_[\da-z]{6}$/.test(e) : false;
}
var sessionId = (() => {
  let e = new URL(window.location.href).searchParams.get(KnownQueryParams.sessionId);
  return isSessionId(e) ? (updateQueryParams((e2) => {
    e2.has(KnownQueryParams.kiosk) || e2.delete(KnownQueryParams.sessionId);
  }), Logger.debug("Connecting to existing session", { sessionId: e }), e) : (Logger.debug("Starting a new session", { sessionId: e }), generateSessionId());
})();
function getSessionId() {
  return sessionId;
}
function isStringToStringRecord(e) {
  if (typeof e != "object" || !e || Array.isArray(e)) return false;
  for (let b of Object.values(e)) if (typeof b != "string") return false;
  return true;
}
function isMarimoStaticState(e) {
  if (typeof e != "object" || !e || Array.isArray(e)) return false;
  let b = e;
  return !(!isStringToStringRecord(b.files) || b.modelNotifications !== void 0 && !Array.isArray(b.modelNotifications));
}
function getMarimoStaticState() {
  let e = typeof window > "u" ? void 0 : window.__MARIMO_STATIC__;
  return isMarimoStaticState(e) ? e : void 0;
}
function isStaticNotebook() {
  return getMarimoStaticState() !== void 0;
}
function getStaticVirtualFiles() {
  let e = getMarimoStaticState();
  return invariant(e !== void 0, "Not a static notebook"), e.files;
}
var RuntimeManager = class {
  constructor(e, b = false) {
    __publicField(this, "initialHealthyCheck", new Deferred());
    this.config = e, this.lazy = b;
    try {
      new URL(this.config.url);
    } catch (e2) {
      throw Error(`Invalid runtime URL: ${this.config.url}. ${e2 instanceof Error ? e2.message : "Unknown error"}`, { cause: e2 });
    }
    this.lazy || this.init();
  }
  get isLazy() {
    return this.lazy;
  }
  get httpURL() {
    return new URL(this.config.url);
  }
  get isSameOrigin() {
    return this.httpURL.origin === window.location.origin;
  }
  get isServerless() {
    return isWasm() || isIslands() || isStaticNotebook();
  }
  formatHttpURL({ path: e = "", searchParams: b, restrictToKnownQueryParams: x = true }) {
    let S = this.httpURL, w = new URLSearchParams(window.location.search);
    if (b) for (let [e2, x2] of b.entries()) S.searchParams.set(e2, x2);
    for (let [e2, b2] of w.entries()) x && !Object.values(KnownQueryParams).includes(e2) || S.searchParams.set(e2, b2);
    return S.pathname = `${S.pathname.replace(/\/$/, "")}/${e.replace(/^\//, "")}`, S.hash = "", S;
  }
  formatWsURL(e, b) {
    let x = this.formatHttpURL({
      path: e,
      searchParams: b,
      restrictToKnownQueryParams: false
    });
    return !this.isSameOrigin && this.config.authToken && x.searchParams.set(KnownQueryParams.accessToken, this.config.authToken), asWsUrl(x.toString());
  }
  getWsURL(e) {
    let b = new URL(this.config.url), x = new URLSearchParams(b.search);
    return new URLSearchParams(window.location.search).forEach((e2, b2) => {
      x.has(b2) || x.set(b2, e2);
    }), x.set(KnownQueryParams.sessionId, e), this.formatWsURL("/ws", x);
  }
  getWsSyncURL(e) {
    let b = new URL(this.config.url), x = new URLSearchParams(b.search);
    return new URLSearchParams(window.location.search).forEach((e2, b2) => {
      x.has(b2) || x.set(b2, e2);
    }), x.set(KnownQueryParams.sessionId, e), this.formatWsURL("/ws_sync", x);
  }
  getTerminalWsURL() {
    return this.formatWsURL("/terminal/ws");
  }
  getLSPURL(e) {
    if (e === "copilot") {
      let b = this.formatWsURL(`/lsp/${e}`), x = b.searchParams.get(KnownQueryParams.accessToken);
      return b.search = "", x && b.searchParams.set(KnownQueryParams.accessToken, x), b;
    }
    return this.formatWsURL(`/lsp/${e}`);
  }
  getAiURL(e) {
    return this.formatHttpURL({ path: `/api/ai/${e}` });
  }
  healthURL() {
    return this.formatHttpURL({ path: "/health" });
  }
  async fetchHealth() {
    try {
      return await fetch(this.healthURL().toString());
    } catch (e) {
      return Logger.error(`Failed to check health: ${e instanceof Error ? e.message : "Unknown error"}`, { cause: e }), null;
    }
  }
  async reconcileFromHealth() {
    if (this.isServerless) return true;
    let e = await this.fetchHealth();
    if (!e) return false;
    if (e.redirected) {
      Logger.debug(`Runtime redirected to ${e.url}`);
      let x = new URL(e.url);
      x.pathname = x.pathname.replace(/\/health$/, ""), this.config.url = x.toString();
    }
    return e.ok && this.setDOMBaseUri(this.config.url), e.ok;
  }
  async probeHealth() {
    var _a;
    return this.isServerless ? true : ((_a = await this.fetchHealth()) == null ? void 0 : _a.ok) ?? false;
  }
  setDOMBaseUri(e) {
    e = e.split("?", 1)[0], e.endsWith("/") || (e += "/");
    let b = document.querySelector("base");
    b ? b.setAttribute("href", e) : (b = document.createElement("base"), b.setAttribute("href", e), document.head.append(b));
  }
  async init(e) {
    Logger.debug("Initializing runtime...");
    let x = 0;
    for (; !await this.reconcileFromHealth(); ) {
      if (x >= 25) {
        Logger.error("Failed to connect after 25 retries"), this.initialHealthyCheck.reject(/* @__PURE__ */ Error("Failed to connect after 25 retries"));
        return;
      }
      if (!(e == null ? void 0 : e.disableRetryDelay)) {
        let e2 = Math.min(100 * 1.2 ** x, 2e3);
        await new Promise((b) => setTimeout(b, e2));
      }
      x++;
    }
    Logger.debug("Runtime is healthy"), this.initialHealthyCheck.resolve();
  }
  async waitForHealthy() {
    return this.initialHealthyCheck.promise;
  }
  headers() {
    let e = {
      "Marimo-Session-Id": getSessionId(),
      "Marimo-Server-Token": this.config.serverToken ?? "",
      "x-runtime-url": this.httpURL.toString()
    };
    return this.config.authToken && (e.Authorization = `Bearer ${this.config.authToken}`), e;
  }
  sessionHeaders() {
    return { "Marimo-Session-Id": getSessionId() };
  }
};
function asWsUrl(e) {
  if (!e.startsWith("http")) {
    Logger.warn(`URL must start with http: ${e}`);
    let x = new URL(e);
    return x.protocol = "ws", x;
  }
  return new URL(e.replace(/^http/, "ws"));
}
require_compiler_runtime();
function getBaseURI() {
  let e = new URL(document.baseURI);
  return e.search = "", e.hash = "", e.toString();
}
const runtimeConfigAtom = atom({
  lazy: true,
  url: getBaseURI()
});
var runtimeManagerAtom = atom((e) => {
  let b = e(runtimeConfigAtom);
  return new RuntimeManager(b, b.lazy);
});
function getRuntimeManager() {
  return store.get(runtimeManagerAtom);
}
function asRemoteURL(e) {
  if (e.startsWith("http")) return new URL(e);
  let b = getRuntimeManager().httpURL.toString();
  return b.startsWith("blob:") && (b = b.replace("blob:", "")), new URL(e, b);
}
const millisecondsInWeek = 6048e5, millisecondsInDay = 864e5, millisecondsInMinute = 6e4, millisecondsInHour = 36e5, millisecondsInSecond = 1e3, secondsInDay = 3600 * 24;
secondsInDay * 7, secondsInDay * 365.2425;
const constructFromSymbol = /* @__PURE__ */ Symbol.for("constructDateFrom");
function constructFrom(e, b) {
  return typeof e == "function" ? e(b) : e && typeof e == "object" && constructFromSymbol in e ? e[constructFromSymbol](b) : e instanceof Date ? new e.constructor(b) : new Date(b);
}
function toDate(e, b) {
  return constructFrom(b || e, e);
}
export {
  isWasm as _,
  millisecondsInMinute as a,
  asRemoteURL as c,
  isStaticNotebook as d,
  appendQueryParams as f,
  Deferred as g,
  waitForConnectionOpen as h,
  millisecondsInHour as i,
  getRuntimeManager as l,
  require_cuid2 as m,
  constructFrom as n,
  millisecondsInSecond as o,
  isUrl as p,
  millisecondsInDay as r,
  millisecondsInWeek as s,
  toDate as t,
  getStaticVirtualFiles as u,
  CircleQuestionMark as v
};
