import {
  register
} from "../chunk.6Z6KE2FG.js";
import {
  LazyContext
} from "../chunk.KDX7KSFL.js";

// src/runtime/lazy/index.ts
import {
  Fragment,
  createElement,
  lazy,
  useContext
} from "react";
var resolvedPromise = Promise.resolve();
function lazy2(factory, options) {
  const lazyImport = factory.lazyImport;
  if (!lazyImport) {
    return lazy(factory);
  }
  return function LazyComponent(props, ...children) {
    const chunkManager = useContext(LazyContext);
    if (!chunkManager) {
      throw new Error(`Invariant violation: The LazyContext.Provider is not a parent component of a lazy component`);
    }
    let lazyComponentState = chunkManager.lazyComponentState.get(lazyImport);
    if (process.env.NOSTALGIE_BUILD_TARGET === "server") {
      if (factory.sync && !lazyComponentState) {
        const mod = factory();
        if (typeof mod.then === "function") {
          throw new Error("Invariant violation: The lazy component server factory produed a Thenable");
        }
        lazyComponentState = register(chunkManager, factory.chunk, lazyImport, mod);
      }
    }
    if (!lazyComponentState) {
      const loadingPromise = resolvedPromise.then(factory).then((mod) => {
        register(chunkManager, factory.chunk, lazyImport, mod);
      }, (error) => {
        chunkManager.lazyComponentState.set(lazyImport, {
          state: "error",
          error
        });
        throw error;
      });
      lazyComponentState = {
        state: "loading",
        loadingPromise
      };
      chunkManager.lazyComponentState.set(lazyImport, lazyComponentState);
    }
    switch (lazyComponentState.state) {
      case "loading":
        if (process.env.NOSTALGIE_BUILD_TARGET === "server") {
          return createElement(Fragment);
        }
        throw lazyComponentState.loadingPromise;
      case "error":
        throw lazyComponentState.error;
      case "loaded":
        return createElement(lazyComponentState.component, props, ...children);
    }
  };
}
export {
  lazy2 as lazy
};
