// @bun
var __create = Object.create;
var __getProtoOf = Object.getPrototypeOf;
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __hasOwnProp = Object.prototype.hasOwnProperty;
function __accessProp(key) {
  return this[key];
}
var __toESMCache_node;
var __toESMCache_esm;
var __toESM = (mod, isNodeMode, target) => {
  var canCache = mod != null && typeof mod === "object";
  if (canCache) {
    var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
    var cached = cache.get(mod);
    if (cached)
      return cached;
  }
  target = mod != null ? __create(__getProtoOf(mod)) : {};
  const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
  for (let key of __getOwnPropNames(mod))
    if (!__hasOwnProp.call(to, key))
      __defProp(to, key, {
        get: __accessProp.bind(mod, key),
        enumerable: true
      });
  if (canCache)
    cache.set(mod, to);
  return to;
};
var __toCommonJS = (from) => {
  var entry = (__moduleCache ??= new WeakMap).get(from), desc;
  if (entry)
    return entry;
  entry = __defProp({}, "__esModule", { value: true });
  if (from && typeof from === "object" || typeof from === "function") {
    for (var key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(entry, key))
        __defProp(entry, key, {
          get: __accessProp.bind(from, key),
          enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
        });
  }
  __moduleCache.set(from, entry);
  return entry;
};
var __moduleCache;
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __returnValue = (v) => v;
function __exportSetter(name, newValue) {
  this[name] = __returnValue.bind(null, newValue);
}
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, {
      get: all[name],
      enumerable: true,
      configurable: true,
      set: __exportSetter.bind(all, name)
    });
};
var __legacyDecorateClassTS = function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1;i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __legacyMetadataTS = (k, v) => {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
    return Reflect.metadata(k, v);
};
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __require = import.meta.require;

// src/core/islandManifest.ts
var toIslandFrameworkSegment = (framework) => framework[0]?.toUpperCase() + framework.slice(1), collectFrameworkIslands = (manifest, prefix) => {
  const entries = {};
  let found = false;
  for (const [key, value] of Object.entries(manifest)) {
    if (!key.startsWith(prefix))
      continue;
    const component = key.slice(prefix.length);
    if (!component)
      continue;
    entries[component] = value;
    found = true;
  }
  return found ? entries : undefined;
}, getIslandManifestEntries = (manifest) => {
  const islands = {};
  const frameworks = ["react", "svelte", "vue", "angular"];
  for (const framework of frameworks) {
    const prefix = `Island${toIslandFrameworkSegment(framework)}`;
    const entries = collectFrameworkIslands(manifest, prefix);
    if (entries)
      islands[framework] = entries;
  }
  return islands;
}, getIslandManifestKey = (framework, component) => `Island${toIslandFrameworkSegment(framework)}${component}`;

// src/core/islands.ts
function getIslandComponent(component) {
  if (isIslandComponentDefinition(component)) {
    return component.component;
  }
  return component;
}
var defineIslandComponent = (component, options) => ({
  component,
  export: options.export,
  source: options.source
}), defineIslandRegistry = (registry) => registry, isRecord = (value) => typeof value === "object" && value !== null, getIslandBuildReference = (component) => {
  if (!isIslandComponentDefinition(component))
    return null;
  return {
    export: component.export,
    source: component.source
  };
}, isIslandComponentDefinition = (value) => isRecord(value) && ("component" in value) && ("source" in value) && typeof value.source === "string", parseIslandProps = (rawProps) => {
  if (!rawProps)
    return {};
  return JSON.parse(rawProps);
}, serializeIslandProps = (props) => JSON.stringify(props ?? {});
var init_islands = () => {};

// src/angular/injectorPatch.ts
import { existsSync, readFileSync, writeFileSync } from "fs";
import { dirname, join, resolve } from "path";
var applyInjectorPatch = (chunkPath, content) => {
  if (content.includes('Symbol.for("angular.currentInjector")')) {
    return;
  }
  const original = [
    "let _currentInjector = undefined;",
    "function getCurrentInjector() {",
    "  return _currentInjector;",
    "}",
    "function setCurrentInjector(injector) {",
    "  const former = _currentInjector;",
    "  _currentInjector = injector;",
    "  return former;",
    "}"
  ].join(`
`);
  const replacement = [
    'const _injSym = Symbol.for("angular.currentInjector");',
    "if (!globalThis[_injSym]) globalThis[_injSym] = { v: undefined };",
    "function getCurrentInjector() {",
    "  return globalThis[_injSym].v;",
    "}",
    "function setCurrentInjector(injector) {",
    "  const former = globalThis[_injSym].v;",
    "  globalThis[_injSym].v = injector;",
    "  return former;",
    "}"
  ].join(`
`);
  const patched = content.replace(original, replacement);
  if (patched === content) {
    return;
  }
  writeFileSync(chunkPath, patched, "utf-8");
}, resolveAngularCoreDir = () => {
  const fromProject = resolve(process.cwd(), "node_modules/@angular/core");
  if (existsSync(join(fromProject, "package.json"))) {
    return fromProject;
  }
  return dirname(__require.resolve("@angular/core/package.json"));
}, patchAngularInjectorSingleton = () => {
  try {
    const coreDir = resolveAngularCoreDir();
    const chunkPath = join(coreDir, "fesm2022", "_not_found-chunk.mjs");
    const content = readFileSync(chunkPath, "utf-8");
    applyInjectorPatch(chunkPath, content);
  } catch {}
};
var init_injectorPatch = __esm(() => {
  patchAngularInjectorSingleton();
});

// src/angular/resolveAngularPackage.ts
import { existsSync as existsSync2 } from "fs";
import { resolve as resolve2 } from "path";
var resolveAngularPackage = (specifier) => {
  const fromProject = resolve2(process.cwd(), "node_modules", specifier);
  if (existsSync2(fromProject)) {
    return fromProject;
  }
  return specifier;
};
var init_resolveAngularPackage = () => {};

// src/angular/angularPatch.ts
var exports_angularPatch = {};
__export(exports_angularPatch, {
  applyPatches: () => applyPatches
});
var ensureHead = (doc) => {
  if (!doc || doc.head || !doc.documentElement) {
    return;
  }
  const head = doc.createElement("head");
  doc.documentElement.insertBefore(head, doc.documentElement.firstChild);
}, applyPatches = async () => {
  const { \u{275}DominoAdapter } = await import(resolveAngularPackage("@angular/platform-server"));
  if (!\u{275}DominoAdapter?.prototype) {
    console.warn("[Angular Patch] \u0275DominoAdapter not found, skipping patches");
    return false;
  }
  const proto = \u{275}DominoAdapter.prototype;
  const origGetBaseHref = proto.getBaseHref;
  proto.getBaseHref = function(doc) {
    if (!doc || !doc.head || typeof doc.head.children === "undefined") {
      return "";
    }
    return origGetBaseHref.call(this, doc);
  };
  const origCreateHtmlDocument = proto.createHtmlDocument;
  proto.createHtmlDocument = function() {
    const doc = origCreateHtmlDocument.call(this);
    ensureHead(doc);
    return doc;
  };
  const origGetDefaultDocument = proto.getDefaultDocument;
  proto.getDefaultDocument = function() {
    const doc = origGetDefaultDocument.call(this);
    ensureHead(doc);
    return doc;
  };
  return true;
};
var init_angularPatch = __esm(() => {
  init_resolveAngularPackage();
});

// src/angular/angularDeps.ts
var initDominoAdapter = (platformServer) => {
  try {
    const DominoAdapter = platformServer.\u{275}DominoAdapter;
    DominoAdapter?.makeCurrent?.();
  } catch (err) {
    console.error("Failed to initialize DominoAdapter:", err);
  }
}, loadAngularDeps = async () => {
  patchAngularInjectorSingleton();
  await import(resolveAngularPackage("@angular/compiler"));
  const { applyPatches: applyPatches2 } = await Promise.resolve().then(() => (init_angularPatch(), exports_angularPatch));
  await applyPatches2();
  const [platformBrowser, platformServer, common, core] = await Promise.all([
    import(resolveAngularPackage("@angular/platform-browser")),
    import(resolveAngularPackage("@angular/platform-server")),
    import(resolveAngularPackage("@angular/common")),
    import(resolveAngularPackage("@angular/core"))
  ]);
  if (false) {}
  initDominoAdapter(platformServer);
  return {
    APP_BASE_HREF: common.APP_BASE_HREF,
    bootstrapApplication: platformBrowser.bootstrapApplication,
    DomSanitizer: platformBrowser.DomSanitizer,
    provideClientHydration: platformBrowser.provideClientHydration,
    provideServerRendering: platformServer.provideServerRendering,
    provideZonelessChangeDetection: core.provideZonelessChangeDetection,
    reflectComponentType: core.reflectComponentType,
    renderApplication: platformServer.renderApplication,
    Sanitizer: core.Sanitizer,
    SecurityContext: core.SecurityContext
  };
}, angularDeps = null, getAngularDeps = () => {
  if (!angularDeps) {
    angularDeps = loadAngularDeps();
  }
  return angularDeps;
};
var init_angularDeps = __esm(() => {
  init_injectorPatch();
  init_resolveAngularPackage();
});

// src/utils/stringModifiers.ts
var normalizeSlug = (str) => str.trim().replace(/\s+/g, "-").replace(/[^A-Za-z0-9\-_]+/g, "").replace(/[-_]{2,}/g, "-"), toKebab = (str) => normalizeSlug(str).replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase(), toPascal = (str) => {
  if (!str.includes("-") && !str.includes("_")) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }
  return normalizeSlug(str).split(/[-_]/).filter(Boolean).map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1).toLowerCase()).join("");
}, toScreamingSnake = (str) => str.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();

// src/utils/registerClientScript.ts
var scriptRegistry, requestCounter = 0, getRequestId = () => `req_${Date.now()}_${++requestCounter}`, ssrContextGetter = null, getSsrContextId = () => ssrContextGetter?.() || Object.getOwnPropertyDescriptor(globalThis, "__absolutejs_requestId")?.value, registerClientScript = (script, requestId) => {
  const id = requestId || getSsrContextId() || getRequestId();
  if (!scriptRegistry.has(id)) {
    scriptRegistry.set(id, new Set);
  }
  scriptRegistry.get(id)?.add(script);
  return id;
}, setSsrContextGetter = (getter) => {
  ssrContextGetter = getter;
}, clearAllClientScripts = () => {
  scriptRegistry.clear();
}, generateClientScriptCode = (scripts) => {
  if (scripts.length === 0) {
    return "";
  }
  const scriptCode = scripts.map((script, index) => {
    const funcString = script.toString();
    const bodyMatch = funcString.match(/\{([\s\S]*)\}/);
    if (!bodyMatch || !bodyMatch[1]) {
      return "";
    }
    const body = bodyMatch[1].trim();
    return `
	(function() {
		var executed = false;
		function executeScript_${index}() {
			if (executed) return;
			executed = true;
			${body}
		}

		if (document.readyState === 'complete' || document.readyState === 'interactive') {
			executeScript_${index}();
		} else {
			document.addEventListener('DOMContentLoaded', executeScript_${index});
		}

		// Watch for hydration-added elements
		var observer = new MutationObserver(function() {
			executeScript_${index}();
			if (executed) observer.disconnect();
		});
		if (!executed) {
			observer.observe(document.body || document.documentElement, { childList: true, subtree: true });
		}

		// Single fallback timeout
		setTimeout(function() {
			executeScript_${index}();
			observer.disconnect();
		}, 1000);
	})();`;
  }).join(`
`);
  return `<script>
(function() {
${scriptCode}
})();
</script>`;
}, getAndClearClientScripts = (requestId) => {
  const id = requestId || ssrContextGetter?.();
  if (!id)
    return [];
  const scripts = scriptRegistry.get(id);
  if (!scripts) {
    return [];
  }
  const scriptArray = Array.from(scripts);
  scriptRegistry.delete(id);
  return scriptArray;
};
var init_registerClientScript = __esm(() => {
  scriptRegistry = new Map;
  if (typeof globalThis !== "undefined") {
    Object.assign(globalThis, { registerClientScript });
  }
});

// src/angular/ssrRender.ts
var routePropsCache, cacheRouteData = (pagePath, data) => {
  const cacheKey = pagePath.split("?")[0] ?? pagePath;
  routePropsCache.set(cacheKey, data);
}, getCachedRouteData = (pagePath) => routePropsCache.get(pagePath), selectorCache, buildDeps = (ssrResult, baseDeps) => {
  if (!ssrResult?.core) {
    return baseDeps;
  }
  const { common, core, platformBrowser, platformServer } = ssrResult;
  return {
    APP_BASE_HREF: common?.APP_BASE_HREF ?? baseDeps.APP_BASE_HREF,
    bootstrapApplication: platformBrowser?.bootstrapApplication ?? baseDeps.bootstrapApplication,
    DomSanitizer: platformBrowser?.DomSanitizer ?? baseDeps.DomSanitizer,
    provideClientHydration: platformBrowser?.provideClientHydration ?? baseDeps.provideClientHydration,
    provideServerRendering: platformServer?.provideServerRendering ?? baseDeps.provideServerRendering,
    provideZonelessChangeDetection: core.provideZonelessChangeDetection,
    reflectComponentType: core.reflectComponentType,
    renderApplication: platformServer?.renderApplication ?? baseDeps.renderApplication,
    Sanitizer: core.Sanitizer,
    SecurityContext: core.SecurityContext
  };
}, buildProviders = (deps, sanitizer, maybeProps, tokenMap) => {
  const providers = [
    deps.provideServerRendering(),
    deps.provideClientHydration(),
    deps.provideZonelessChangeDetection(),
    { provide: deps.APP_BASE_HREF, useValue: "/" },
    {
      provide: deps.DomSanitizer,
      useValue: sanitizer
    },
    { provide: deps.Sanitizer, useValue: sanitizer }
  ];
  if (!maybeProps) {
    return providers;
  }
  const propProviders = Object.entries(maybeProps).map(([propName, propValue]) => ({
    token: tokenMap.get(toScreamingSnake(propName)),
    value: propValue
  })).filter((entry) => entry.token).map((entry) => ({ provide: entry.token, useValue: entry.value }));
  return [...providers, ...propProviders];
}, clearSelectorCache = () => selectorCache.clear(), isInjectionToken = (value) => {
  if (!value || typeof value !== "object") {
    return false;
  }
  return "ngMetadataName" in value && value.ngMetadataName === "InjectionToken";
}, discoverTokens = (pageModule) => new Map(Object.entries(pageModule).filter(([, value]) => isInjectionToken(value))), loadSsrDeps = async (pagePath) => {
  const ssrDepsPath = (pagePath.split("?")[0] ?? pagePath).replace(/\.js$/, ".ssr-deps.js");
  try {
    const ssrDeps = await import(ssrDepsPath);
    const result = {
      common: ssrDeps.__angularCommon,
      core: ssrDeps.__angularCore,
      platformBrowser: ssrDeps.__angularPlatformBrowser,
      platformServer: ssrDeps.__angularPlatformServer
    };
    return result;
  } catch {
    return null;
  }
}, resolveSelector = (deps, pagePath, PageComponent) => {
  const cached = selectorCache.get(pagePath);
  if (cached) {
    return cached;
  }
  const selector = deps.reflectComponentType(PageComponent)?.selector ?? "ng-app";
  selectorCache.set(pagePath, selector);
  return selector;
}, injectBeforeClose = (html, snippet) => {
  if (html.includes("</body>")) {
    return html.replace("</body>", `${snippet}</body>`);
  }
  if (html.includes("</html>")) {
    return html.replace("</html>", `${snippet}</html>`);
  }
  return html + snippet;
}, injectSsrScripts = (html, requestId, indexPath, props) => {
  let result = html;
  const registeredScripts = getAndClearClientScripts(requestId);
  if (registeredScripts.length > 0) {
    result = injectBeforeClose(result, generateClientScriptCode(registeredScripts));
  }
  if (props) {
    result = injectBeforeClose(result, `<script>window.__ABS_ANGULAR_PAGE_PROPS__ = ${JSON.stringify(props)};</script>`);
  }
  if (indexPath) {
    const escapedIndexPath = JSON.stringify(indexPath);
    result = injectBeforeClose(result, `<script>import(${escapedIndexPath});</script>`);
  }
  return result;
}, renderAngularApp = async (deps, PageComponent, providers, document) => {
  const bootstrap = (context) => deps.bootstrapApplication(PageComponent, { providers }, context);
  return withSuppressedAngularDevLogs(() => deps.renderApplication(bootstrap, {
    document,
    platformProviders: [],
    url: "/"
  }));
}, withSuppressedAngularDevLogs = async (render) => {
  const origLog = console.log;
  console.log = (...args) => {
    if (typeof args[0] === "string" && args[0].includes("development mode")) {
      return;
    }
    origLog.apply(console, args);
  };
  try {
    return await render();
  } finally {
    console.log = origLog;
  }
};
var init_ssrRender = __esm(() => {
  init_registerClientScript();
  routePropsCache = new Map;
  selectorCache = new Map;
});

// src/angular/islands.ts
var angularIslandSelector = "abs-angular-island", getAngularIslandSelector = (_islandId) => angularIslandSelector, getSelectorFromRenderedIsland = (rootElement) => {
  const firstChild = rootElement.firstElementChild;
  if (!(firstChild instanceof HTMLElement)) {
    return null;
  }
  const selector = firstChild.tagName.toLowerCase();
  return selector.length > 0 ? selector : null;
}, getClientAngularComponentSelector = (component) => {
  const maybeDef = Reflect.get(component, "\u0275cmp");
  if (typeof maybeDef !== "object" || maybeDef === null) {
    return null;
  }
  const maybeSelectors = Reflect.get(maybeDef, "selectors");
  if (!Array.isArray(maybeSelectors)) {
    return null;
  }
  const [firstSelectorGroup] = maybeSelectors;
  if (!Array.isArray(firstSelectorGroup)) {
    return null;
  }
  const [selector] = firstSelectorGroup;
  return typeof selector === "string" && selector.length > 0 ? selector : null;
}, createAngularIslandApp = async () => {
  const { EnvironmentInjector, provideZonelessChangeDetection } = await import("@angular/core");
  const { createApplication } = await import("@angular/platform-browser");
  const app = await createApplication({
    providers: [provideZonelessChangeDetection()]
  });
  const environmentInjector = app.injector.get(EnvironmentInjector);
  return { app, environmentInjector };
}, angularIslandAppPromise = null, getAngularIslandApp = async () => {
  if (!angularIslandAppPromise) {
    angularIslandAppPromise = createAngularIslandApp();
  }
  return angularIslandAppPromise;
}, wrapperMetadataCache, requestRenderCache, getRequestRenderCache = () => {
  const requestId = getSsrContextId();
  if (!requestId) {
    return null;
  }
  const cached = requestRenderCache.get(requestId);
  if (cached) {
    return cached;
  }
  const renderCache = new Map;
  requestRenderCache.set(requestId, renderCache);
  return renderCache;
}, getAngularIslandWrapperKey = (component, _islandId) => {
  const componentName = typeof component.name === "string" && component.name.length > 0 ? component.name : "AngularIsland";
  return `${componentName}:${angularIslandSelector}`;
}, getIslandRenderCacheKey = (component, props) => {
  const componentName = typeof component.name === "string" && component.name.length > 0 ? component.name : "AngularIsland";
  return `${componentName}:${JSON.stringify(props)}`;
}, buildAngularIslandWrapperMetadata = async (component, islandId, wrapperKey) => {
  const { Component, InjectionToken, inject } = await import("@angular/core");
  const { NgComponentOutlet } = await import("@angular/common");
  const deps = await getAngularDeps();
  const selector = getAngularIslandSelector(islandId);
  const propsToken = new InjectionToken(`${wrapperKey}:props`);

  class AngularIslandWrapperComponent {
    component = component;
    props = inject(propsToken);
  }
  return {
    deps,
    propsToken,
    selector,
    WrapperComponent: Component({
      imports: [NgComponentOutlet, component],
      selector,
      standalone: true,
      template: '<ng-container *ngComponentOutlet="component; inputs: props"></ng-container>'
    })(AngularIslandWrapperComponent)
  };
}, createAngularIslandWrapper = async (component, islandId) => {
  const wrapperKey = getAngularIslandWrapperKey(component, islandId);
  const cached = wrapperMetadataCache.get(wrapperKey);
  if (cached) {
    return cached;
  }
  const metadataPromise = buildAngularIslandWrapperMetadata(component, islandId, wrapperKey);
  wrapperMetadataCache.set(wrapperKey, metadataPromise);
  return metadataPromise;
}, extractAngularIslandRoot = (html, selector) => {
  const openTag = `<${selector}`;
  const start = html.indexOf(openTag);
  if (start < 0) {
    throw new Error(`Could not find Angular island root "${selector}".`);
  }
  const endTag = `</${selector}>`;
  const end = html.indexOf(endTag, start);
  if (end < 0) {
    throw new Error(`Could not close Angular island root "${selector}".`);
  }
  return html.slice(start, end + endTag.length);
}, mountAngularIsland = async (component, element, props, islandId) => {
  await import("@angular/compiler");
  const { createComponent, inputBinding } = await import("@angular/core");
  const selector = getAngularIslandSelector(islandId);
  const { app, environmentInjector } = await getAngularIslandApp();
  let rootElement = element.querySelector(selector);
  if (!(rootElement instanceof HTMLElement)) {
    element.innerHTML = `<${selector}></${selector}>`;
    rootElement = element.querySelector(selector);
  }
  if (!(rootElement instanceof HTMLElement))
    return app;
  const componentSelector = getClientAngularComponentSelector(component) ?? getSelectorFromRenderedIsland(rootElement);
  if (!componentSelector)
    return app;
  rootElement.innerHTML = `<${componentSelector}></${componentSelector}>`;
  const hostElement = rootElement.querySelector(componentSelector);
  if (!(hostElement instanceof HTMLElement))
    return app;
  const bindings = Object.entries(props).map(([key, value]) => inputBinding(key, () => value));
  const componentRef = createComponent(component, {
    bindings,
    environmentInjector,
    hostElement
  });
  app.attachView(componentRef.hostView);
  componentRef.changeDetectorRef.detectChanges();
  window.__ABS_ANGULAR_ISLAND_APPS__ ??= [];
  window.__ABS_ANGULAR_ISLAND_APPS__.push(app);
  return app;
}, renderAngularIslandToHtml = async (component, props, islandId) => {
  const requestCache = getRequestRenderCache();
  const renderCacheKey = getIslandRenderCacheKey(component, props);
  const cachedHtml = requestCache?.get(renderCacheKey);
  if (cachedHtml) {
    return cachedHtml;
  }
  const { deps, propsToken, selector, WrapperComponent } = await createAngularIslandWrapper(component, islandId);
  const providers = [
    deps.provideServerRendering(),
    deps.provideZonelessChangeDetection(),
    { provide: deps.APP_BASE_HREF, useValue: "/" },
    { provide: propsToken, useValue: props }
  ];
  const document = `<!DOCTYPE html><html><body><${selector}></${selector}></body></html>`;
  const html = await withSuppressedAngularDevLogs(() => deps.renderApplication((context) => deps.bootstrapApplication(WrapperComponent, { providers }, context), {
    document,
    platformProviders: [],
    url: "/"
  }));
  const islandHtml = extractAngularIslandRoot(html, selector);
  requestCache?.set(renderCacheKey, islandHtml);
  return islandHtml;
};
var init_islands2 = __esm(() => {
  init_angularDeps();
  init_ssrRender();
  init_registerClientScript();
  wrapperMetadataCache = new Map;
  requestRenderCache = new Map;
});

// src/core/islandSsr.ts
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { render as renderSvelte } from "svelte/server";
import { createSSRApp, h } from "vue";
import { renderToString as renderVueToString } from "vue/server-renderer";
var renderReactIslandToHtml = (component, props) => renderToStaticMarkup(createElement(component, props)), renderSvelteIslandToHtml = (component, props) => {
  const { body } = renderSvelte(component, { props });
  return body;
}, renderVueIslandToHtml = (component, props) => {
  const app = createSSRApp({
    render: () => h(component, props)
  });
  return renderVueToString(app);
};
var init_islandSsr = __esm(() => {
  init_islands2();
});

// src/build/resolvePackageImport.ts
import { resolve as resolve3, join as join2 } from "path";
import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
var resolveExportPath = (entry, conditions) => {
  if (typeof entry === "string")
    return entry;
  if (!entry || typeof entry !== "object")
    return null;
  for (const condition of conditions) {
    const target = Reflect.get(entry, condition);
    if (typeof target === "string") {
      return target;
    }
  }
  return null;
}, resolvePackageImport = (specifier, conditions = ["import"]) => {
  if (specifier.startsWith(".") || specifier.startsWith("/"))
    return null;
  const parts = specifier.split("/");
  const isScoped = specifier.startsWith("@");
  const packageName = isScoped ? `${parts[0]}/${parts[1]}` : parts[0];
  const subpath = isScoped ? parts.slice(2).join("/") : parts.slice(1).join("/");
  const exportKey = subpath ? `./${subpath}` : ".";
  const currentPackageJsonPath = resolve3(process.cwd(), "package.json");
  const currentPackageJson = existsSync3(currentPackageJsonPath) ? JSON.parse(readFileSync2(currentPackageJsonPath, "utf-8")) : null;
  const currentPackageDir = currentPackageJson?.name === packageName ? process.cwd() : null;
  const packageDir = currentPackageDir ?? resolve3(process.cwd(), "node_modules", packageName ?? "");
  const packageJsonPath = join2(packageDir, "package.json");
  if (!existsSync3(packageJsonPath))
    return null;
  try {
    const packageJson = currentPackageDir && currentPackageJson ? currentPackageJson : JSON.parse(readFileSync2(packageJsonPath, "utf-8"));
    const { exports } = packageJson;
    if (!exports)
      return null;
    const entry = exports[exportKey];
    if (!entry)
      return null;
    const importPath = resolveExportPath(entry, conditions);
    if (!importPath)
      return null;
    if (currentPackageDir && importPath.startsWith("./dist/")) {
      const sourceCandidate = resolve3(packageDir, importPath.replace(/^\.\/dist\//, "./src/"));
      if (existsSync3(sourceCandidate)) {
        return sourceCandidate;
      }
    }
    const resolved = resolve3(packageDir, importPath);
    return existsSync3(resolved) ? resolved : null;
  } catch {
    return null;
  }
};
var init_resolvePackageImport = () => {};

// src/constants.ts
var ANGULAR_INIT_TIMEOUT_MS = 500, ANSI_ESCAPE_LENGTH = 3, ASCII_SPACE = 32, BASE_36_RADIX = 36, BUN_BUILD_WARNING_SUPPRESSION = "wildcard sideEffects are not supported yet", BODY_SLICE_LENGTH = 2000, BYTES_PER_KILOBYTE = 1024, CLI_ARGS_OFFSET = 3, CSS_ERROR_RESOLVE_DELAY_MS = 50, CSS_MAX_CHECK_ATTEMPTS = 10, CSS_MAX_PARSE_TIMEOUT_MS = 500, CSS_SHEET_READY_TIMEOUT_MS = 100, DEFAULT_CHUNK_SIZE = 16384, DEFAULT_DEBOUNCE_MS = 15, DEFAULT_PORT = 3000, DEV_SERVER_RESTART_DEBOUNCE_MS = 100, DOM_UPDATE_DELAY_MS = 50, FILE_PROTOCOL_PREFIX_LENGTH = 7, FOCUS_ID_PREFIX_LENGTH = 3, FOCUS_IDX_PREFIX_LENGTH = 4, FOCUS_NAME_PREFIX_LENGTH = 5, HMR_UPDATE_TIMEOUT_MS = 2000, HOOK_SIGNATURE_LENGTH = 12, EXCLUDE_LAST_OFFSET = -1, HOURS_IN_DAY = 24, HOURS_IN_HALF_DAY = 12, MAX_ERROR_LENGTH = 200, MAX_RECONNECT_ATTEMPTS = 60, MILLISECONDS_IN_A_SECOND = 1000, MINUTES_IN_AN_HOUR = 60, SECONDS_IN_A_MINUTE = 60, MILLISECONDS_IN_A_MINUTE, MILLISECONDS_IN_A_DAY, OVERLAY_FADE_DURATION_MS = 150, PING_INTERVAL_MS = 30000, RAF_BATCH_COUNT = 3, RANDOM_ID_END_INDEX = 11, REBUILD_BATCH_DELAY_MS = 10, REBUILD_RELOAD_DELAY_MS = 200, RECONNECT_INITIAL_DELAY_MS = 500, RECONNECT_POLL_INTERVAL_MS = 300, SIGINT_EXIT_CODE = 130, SIGTERM_EXIT_CODE = 143, SVELTE_CSS_LOAD_TIMEOUT_MS = 500, TIME_PRECISION = 2, TWO_THIRDS, UNFOUND_INDEX = -1, WEBSOCKET_NORMAL_CLOSURE = 1000;
var init_constants = __esm(() => {
  MILLISECONDS_IN_A_MINUTE = MILLISECONDS_IN_A_SECOND * SECONDS_IN_A_MINUTE;
  MILLISECONDS_IN_A_DAY = MILLISECONDS_IN_A_SECOND * SECONDS_IN_A_MINUTE * MINUTES_IN_AN_HOUR * HOURS_IN_DAY;
  TWO_THIRDS = 2 / 3;
});

// src/svelte/lowerIslandSyntax.ts
var ISLAND_TAG_RE, extractBracedExpression = (text, braceStart) => {
  let depth = 0;
  for (let index = braceStart;index < text.length; index += 1) {
    const char = text[index];
    if (char === "{")
      depth += 1;
    if (char === "}")
      depth -= 1;
    if (depth === 0) {
      return text.slice(braceStart + 1, index).trim();
    }
  }
  return null;
}, extractIslandAttribute = (attributeString, name) => {
  const quotedMatch = attributeString.match(new RegExp(`\\b${name}\\s*=\\s*["']([^"']+)["']`));
  if (quotedMatch?.[1]) {
    return { expression: JSON.stringify(quotedMatch[1]), found: true };
  }
  const attributeIndex = attributeString.search(new RegExp(`\\b${name}\\s*=\\s*\\{`));
  if (attributeIndex < 0) {
    return { expression: "", found: false };
  }
  const braceStart = attributeString.indexOf("{", attributeIndex);
  if (braceStart < 0) {
    return { expression: "", found: false };
  }
  const expression = extractBracedExpression(attributeString, braceStart);
  if (expression === null) {
    return { expression: "", found: false };
  }
  return { expression, found: true };
}, lowerSvelteIslandSyntax = (source, _mode = "server") => {
  if (!source.includes("<Island")) {
    return { code: source, transformed: false };
  }
  let islandIndex = 0;
  const transformedMarkup = source.replace(ISLAND_TAG_RE, (fullMatch, attributeString) => {
    const framework = extractIslandAttribute(attributeString, "framework");
    const component = extractIslandAttribute(attributeString, "component");
    if (!framework.found || !component.found) {
      return fullMatch;
    }
    const hydrate = extractIslandAttribute(attributeString, "hydrate");
    const props = extractIslandAttribute(attributeString, "props");
    const slotId = `absolute-svelte-island-${islandIndex.toString(BASE_36_RADIX)}`;
    islandIndex += 1;
    const resolveExpression = `await __absoluteResolveIslandHtml(${JSON.stringify(slotId)}, { component: ${component.expression}, framework: ${framework.expression}, hydrate: ${hydrate.found ? hydrate.expression : JSON.stringify("load")}, props: ${props.found ? props.expression : "{}"} })`;
    return `<div data-absolute-island-slot="${slotId}" style="display: contents">{@html ${resolveExpression}}</div>`;
  });
  const importLine = 'import { resolveIslandHtml as __absoluteResolveIslandHtml } from "@absolutejs/absolute/svelte";';
  if (transformedMarkup.includes("<script")) {
    return {
      code: transformedMarkup.replace(/<script(\s[^>]*)?>/, (match) => `${match}
${importLine}
`),
      transformed: true
    };
  }
  return {
    code: `<script lang="ts">
${importLine}
</script>
${transformedMarkup}`,
    transformed: true
  };
};
var init_lowerIslandSyntax = __esm(() => {
  init_constants();
  ISLAND_TAG_RE = /<Island\b([\s\S]*?)\/>/g;
});

// src/svelte/lowerAwaitSlotSyntax.ts
var AWAIT_BLOCK_RE, escapeTemplateLiteral = (value) => value.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${"), markupToTemplateLiteral = (markup) => {
  const escaped = escapeTemplateLiteral(markup.trim());
  const withExpressions = escaped.replace(/\{([^{}]+)\}/g, (_, expression) => `\${${String(expression).trim()}}`);
  return `\`${withExpressions}\``;
}, lowerSvelteAwaitSlotSyntax = (source) => {
  if (!source.includes("{#await")) {
    return { code: source, transformed: false };
  }
  let awaitIndex = 0;
  let transformed = false;
  const lowered = source.replace(AWAIT_BLOCK_RE, (fullMatch, awaitExpression, pendingMarkup, thenIdentifier, thenMarkup, catchIdentifier, catchMarkup) => {
    const trimmedAwaitExpression = awaitExpression.trim();
    if (!trimmedAwaitExpression) {
      return fullMatch;
    }
    const slotId = `absolute-svelte-await-${awaitIndex.toString(BASE_36_RADIX)}`;
    awaitIndex += 1;
    transformed = true;
    const thenValueIdentifier = thenIdentifier?.trim() || "__awaitValue";
    const catchValueIdentifier = catchIdentifier?.trim() || "__awaitError";
    const fallbackHtml = markupToTemplateLiteral(pendingMarkup);
    const resolvedHtml = markupToTemplateLiteral(thenMarkup);
    const rejectedHtml = typeof catchMarkup === "string" ? markupToTemplateLiteral(catchMarkup) : null;
    const catchBranch = rejectedHtml ? `catch (${catchValueIdentifier}) { return ${rejectedHtml}; }` : "catch (_absoluteAwaitError) { throw _absoluteAwaitError; }";
    return `<AbsoluteAwaitSlot id="${slotId}" fallbackHtml={${fallbackHtml}} resolve={async () => { try { const ${thenValueIdentifier} = await (${trimmedAwaitExpression}); return ${resolvedHtml}; } ${catchBranch} }} />`;
  });
  if (!transformed) {
    return { code: source, transformed: false };
  }
  const importLine = 'import AbsoluteAwaitSlot from "@absolutejs/absolute/svelte/components/AwaitSlot.svelte";';
  if (lowered.includes("<script")) {
    return {
      code: lowered.replace(/<script(\s[^>]*)?>/, (match) => `${match}
${importLine}
`),
      transformed: true
    };
  }
  return {
    code: `<script lang="ts">
${importLine}
</script>
${lowered}`,
    transformed: true
  };
};
var init_lowerAwaitSlotSyntax = __esm(() => {
  init_constants();
  AWAIT_BLOCK_RE = /\{#await\s+([^}]+)\}([\s\S]*?)\{:then(?:\s+([A-Za-z_$][\w$]*))?\}([\s\S]*?)(?:\{:catch(?:\s+([A-Za-z_$][\w$]*))?\}([\s\S]*?))?\{\/await\}/g;
});

// src/core/svelteServerModule.ts
import { mkdir, readdir } from "fs/promises";
import { basename, dirname as dirname2, extname, join as join3, relative, resolve as resolve4 } from "path";
var serverCacheRoot, compiledModuleCache, originalSourcePathCache, transpiler, ensureRelativeImportPath = (from, target) => {
  const importPath = relative(dirname2(from), target).replace(/\\/g, "/");
  return importPath.startsWith(".") ? importPath : `./${importPath}`;
}, processDirectoryEntries = (entries, dir, targetFileName, stack) => {
  for (const entry of entries) {
    const entryPath = join3(dir, entry.name);
    if (entry.isDirectory())
      stack.push(entryPath);
    if (entry.isFile() && entry.name === targetFileName) {
      return entryPath;
    }
  }
  return null;
}, searchDirectoryLevel = async (dirs, targetFileName) => {
  if (dirs.length === 0)
    return null;
  const nextStack = [];
  const dirEntries = await Promise.all(dirs.map(async (dir) => ({
    dir,
    entries: await readdir(dir, {
      encoding: "utf-8",
      withFileTypes: true
    })
  })));
  for (const { dir, entries } of dirEntries) {
    const found = processDirectoryEntries(entries, dir, targetFileName, nextStack);
    if (found)
      return found;
  }
  return searchDirectoryLevel(nextStack, targetFileName);
}, findSourceFileByBasename = async (searchRoot, targetFileName) => searchDirectoryLevel([searchRoot], targetFileName), normalizeBuiltSvelteFileName = (sourcePath) => basename(sourcePath).replace(/-[a-z0-9]{6,}(?=\.svelte$)/i, ""), resolveOriginalSourcePath = async (sourcePath) => {
  const cachedPath = originalSourcePathCache.get(sourcePath);
  if (cachedPath !== undefined) {
    return cachedPath;
  }
  if (!sourcePath.includes(`${join3(process.cwd(), "build")}${process.platform === "win32" ? "" : "/"}`) && !sourcePath.includes("/build/")) {
    originalSourcePathCache.set(sourcePath, sourcePath);
    return sourcePath;
  }
  const resolvedSourcePath = await findSourceFileByBasename(join3(process.cwd(), "src"), normalizeBuiltSvelteFileName(sourcePath));
  const nextPath = resolvedSourcePath ?? sourcePath;
  originalSourcePathCache.set(sourcePath, nextPath);
  return nextPath;
}, resolveRelativeModule = async (spec, from) => {
  if (!spec.startsWith(".")) {
    return null;
  }
  const basePath = resolve4(dirname2(from), spec);
  const candidates = [
    basePath,
    `${basePath}.ts`,
    `${basePath}.js`,
    `${basePath}.mjs`,
    `${basePath}.cjs`,
    `${basePath}.json`,
    join3(basePath, "index.ts"),
    join3(basePath, "index.js"),
    join3(basePath, "index.mjs"),
    join3(basePath, "index.cjs"),
    join3(basePath, "index.json")
  ];
  const existResults = await Promise.all(candidates.map((candidate) => Bun.file(candidate).exists()));
  const foundIndex = existResults.indexOf(true);
  return foundIndex >= 0 ? candidates[foundIndex] ?? null : null;
}, getCachedModulePath = (sourcePath) => {
  const relativeSourcePath = relative(process.cwd(), sourcePath).replace(/\\/g, "/");
  const normalizedSourcePath = relativeSourcePath.startsWith("..") ? sourcePath.replace(/[:\\/]/g, "_") : relativeSourcePath;
  return join3(serverCacheRoot, `${normalizedSourcePath}.server.js`);
}, resolveSvelteImport = async (spec, from) => {
  if (!spec.startsWith(".") && !spec.startsWith("/")) {
    const resolved = resolvePackageImport(spec);
    return resolved && resolved.endsWith(".svelte") ? resolved : null;
  }
  if (spec.startsWith("/")) {
    return spec;
  }
  if (!spec.startsWith(".")) {
    return null;
  }
  const explicitPath = resolve4(dirname2(from), spec);
  if (extname(explicitPath) === ".svelte") {
    return explicitPath;
  }
  const candidate = `${explicitPath}.svelte`;
  if (await Bun.file(candidate).exists() === true) {
    return candidate;
  }
  return null;
}, writeIfChanged = async (path, content) => {
  const targetFile = Bun.file(path);
  const exists = await targetFile.exists();
  if (exists) {
    const currentContent = await targetFile.text();
    if (currentContent === content) {
      return;
    }
  }
  await Bun.write(path, content);
}, compileSvelteServerModule = async (sourcePath) => {
  const cachedModulePath = compiledModuleCache.get(sourcePath);
  if (cachedModulePath) {
    return cachedModulePath;
  }
  const resolutionSourcePath = await resolveOriginalSourcePath(sourcePath);
  const source = await Bun.file(sourcePath).text();
  const { compile, preprocess } = await import("svelte/compiler");
  const loweredAwaitSource = lowerSvelteAwaitSlotSyntax(source);
  const loweredSource = lowerSvelteIslandSyntax(loweredAwaitSource.code, "server");
  const preprocessed = await preprocess(loweredSource.code, {});
  let transpiled = sourcePath.endsWith(".ts") || sourcePath.endsWith(".svelte.ts") ? transpiler.transformSync(preprocessed.code) : preprocessed.code;
  const childImportSpecs = Array.from(transpiled.matchAll(/from\s+['"]([^'"]+)['"]/g)).map((match) => match[1]).filter((value) => value !== undefined);
  const resolvedChildModules = await Promise.all(childImportSpecs.map((spec) => resolveSvelteImport(spec, resolutionSourcePath)));
  const resolvedModuleImports = await Promise.all(childImportSpecs.map((spec) => resolveRelativeModule(spec, resolutionSourcePath)));
  const childModulePaths = new Map;
  const rewrittenModulePaths = new Map;
  const compiledChildren = await Promise.all(childImportSpecs.map(async (spec, index) => {
    const resolvedChild = resolvedChildModules[index];
    if (!spec || !resolvedChild)
      return null;
    return {
      compiledPath: await compileSvelteServerModule(resolvedChild),
      resolvedChild,
      spec
    };
  }));
  for (const result of compiledChildren) {
    if (!result)
      continue;
    childModulePaths.set(result.spec, result.compiledPath);
    childModulePaths.set(result.resolvedChild, result.compiledPath);
  }
  for (let index = 0;index < childImportSpecs.length; index += 1) {
    const spec = childImportSpecs[index];
    const resolvedModuleImport = resolvedModuleImports[index];
    if (!spec || !resolvedModuleImport)
      continue;
    if (resolvedChildModules[index])
      continue;
    rewrittenModulePaths.set(spec, ensureRelativeImportPath(getCachedModulePath(sourcePath), resolvedModuleImport));
  }
  for (const [spec, resolvedModuleImport] of rewrittenModulePaths) {
    transpiled = transpiled.replaceAll(spec, resolvedModuleImport);
  }
  let compiledCode = compile(transpiled, {
    css: "injected",
    experimental: {
      async: loweredAwaitSource.transformed || loweredSource.transformed
    },
    filename: resolutionSourcePath,
    generate: "server"
  }).js.code;
  for (const [spec, compiledChildPath] of childModulePaths) {
    compiledCode = compiledCode.replaceAll(spec, ensureRelativeImportPath(getCachedModulePath(sourcePath), compiledChildPath));
  }
  for (const [spec, resolvedModuleImport] of rewrittenModulePaths) {
    compiledCode = compiledCode.replaceAll(spec, resolvedModuleImport);
  }
  const compiledModulePath = getCachedModulePath(sourcePath);
  await mkdir(dirname2(compiledModulePath), { recursive: true });
  await writeIfChanged(compiledModulePath, compiledCode);
  compiledModuleCache.set(sourcePath, compiledModulePath);
  return compiledModulePath;
};
var init_svelteServerModule = __esm(() => {
  init_resolvePackageImport();
  init_lowerIslandSyntax();
  init_lowerAwaitSlotSyntax();
  serverCacheRoot = join3(process.cwd(), ".absolutejs", "islands", "svelte");
  compiledModuleCache = new Map;
  originalSourcePathCache = new Map;
  transpiler = new Bun.Transpiler({
    loader: "ts",
    target: "browser"
  });
});

// src/core/islandMarkupAttributes.ts
var getIslandMarkerAttributes = (props, islandId) => ({
  "data-component": props.component,
  "data-framework": props.framework,
  "data-hydrate": props.hydrate ?? "load",
  "data-island": "true",
  ...islandId ? { "data-island-id": islandId } : {},
  "data-props": serializeIslandProps(props.props)
}), escapeHtmlAttribute = (value) => value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"), serializeIslandAttributes = (attributes) => Object.entries(attributes).map(([key, value]) => `${key}="${escapeHtmlAttribute(value)}"`).join(" ");
var init_islandMarkupAttributes = __esm(() => {
  init_islands();
});

// src/core/renderIslandMarkup.ts
var islandSequence = 0, resolvedServerComponentCache, resolvedServerBuildComponentCache, nextIslandId = () => {
  islandSequence += 1;
  return `island-${islandSequence}`;
}, isRecord2 = (value) => typeof value === "object" && value !== null, isReactServerIslandComponent = (value) => typeof value === "function", isSvelteServerIslandComponent = (value) => typeof value === "function", isVueServerIslandComponent = (value) => typeof value === "function" || isRecord2(value), isAngularServerIslandComponent = (value) => typeof value === "function", resolveBuildReferencePath = (source, registryPath) => {
  if (source.startsWith("file://"))
    return new URL(source).pathname;
  if (source.startsWith("."))
    return new URL(source, registryPath).pathname;
  return source;
}, loadAndCompileServerBuildComponent = async (buildReferencePath) => {
  const compiledModulePath = await compileSvelteServerModule(buildReferencePath);
  const loadedModule = await import(compiledModulePath);
  return "default" in loadedModule ? loadedModule.default : loadedModule;
}, loadServerBuildComponent = async (buildReferencePath) => {
  const cachedBuildComponent = resolvedServerBuildComponentCache.get(buildReferencePath);
  if (cachedBuildComponent) {
    return cachedBuildComponent;
  }
  const loadPromise = loadAndCompileServerBuildComponent(buildReferencePath);
  resolvedServerBuildComponentCache.set(buildReferencePath, loadPromise);
  return loadPromise;
}, loadServerImportComponent = async (resolvedComponent) => {
  const resolvedModulePath = resolvedComponent.startsWith(".") ? new URL(resolvedComponent, import.meta.url).pathname : resolvedComponent;
  const importTarget = resolvedModulePath.endsWith(".svelte") ? await compileSvelteServerModule(resolvedModulePath) : resolvedModulePath;
  const loadedModule = await import(importTarget);
  return "default" in loadedModule ? loadedModule.default : loadedModule;
}, resolveIslandComponent = async (component) => {
  const buildReference = getIslandBuildReference(component);
  const buildReferencePath = buildReference?.source ? resolveBuildReferencePath(buildReference.source, import.meta.url) : null;
  if (buildReferencePath?.endsWith(".svelte")) {
    return loadServerBuildComponent(buildReferencePath);
  }
  const resolvedComponent = getIslandComponent(component);
  if (typeof resolvedComponent !== "string") {
    return resolvedComponent;
  }
  return loadServerImportComponent(resolvedComponent);
}, resolveServerIslandComponent = async (component) => {
  const cachedResolvedComponent = resolvedServerComponentCache.get(component);
  if (cachedResolvedComponent) {
    return cachedResolvedComponent;
  }
  const resolutionPromise = resolveIslandComponent(component);
  resolvedServerComponentCache.set(component, resolutionPromise);
  return resolutionPromise;
}, resolveReactServerIslandComponent = async (component) => {
  const resolvedComponent = await resolveServerIslandComponent(component);
  if (!isReactServerIslandComponent(resolvedComponent)) {
    throw new Error("Resolved React island is not a valid React component.");
  }
  return resolvedComponent;
}, resolveSvelteServerIslandComponent = async (component) => {
  const resolvedComponent = await resolveServerIslandComponent(component);
  if (!isSvelteServerIslandComponent(resolvedComponent)) {
    throw new Error("Resolved Svelte island is not a valid Svelte component.");
  }
  return resolvedComponent;
}, resolveVueServerIslandComponent = async (component) => {
  const resolvedComponent = await resolveServerIslandComponent(component);
  if (!isVueServerIslandComponent(resolvedComponent)) {
    throw new Error("Resolved Vue island is not a valid Vue component.");
  }
  return resolvedComponent;
}, resolveAngularServerIslandComponent = async (component) => {
  const resolvedComponent = await resolveServerIslandComponent(component);
  if (!isAngularServerIslandComponent(resolvedComponent)) {
    throw new Error("Resolved Angular island is not a valid Angular component.");
  }
  return resolvedComponent;
}, renderIslandMarkup = async (registry, props) => {
  const result = await renderIslandResult(registry, props);
  return `<div ${serializeIslandAttributes(result.attributes)}>${result.html}</div>`;
}, renderIslandResult = async (registry, props) => {
  const islandId = nextIslandId();
  const attributes = getIslandMarkerAttributes(props);
  if (props.framework === "react") {
    const entry = registry.react?.[props.component];
    if (!entry) {
      throw new Error(`Island component "${props.component}" is not registered for framework "react".`);
    }
    const component = await resolveReactServerIslandComponent(entry);
    const html = renderReactIslandToHtml(component, props.props);
    return { attributes, html };
  }
  if (props.framework === "svelte") {
    const entry = registry.svelte?.[props.component];
    if (!entry) {
      throw new Error(`Island component "${props.component}" is not registered for framework "svelte".`);
    }
    const component = await resolveSvelteServerIslandComponent(entry);
    const html = renderSvelteIslandToHtml(component, props.props);
    return { attributes, html };
  }
  if (props.framework === "vue") {
    const entry = registry.vue?.[props.component];
    if (!entry) {
      throw new Error(`Island component "${props.component}" is not registered for framework "vue".`);
    }
    const component = await resolveVueServerIslandComponent(entry);
    const html = await renderVueIslandToHtml(component, props.props);
    return { attributes, html };
  }
  if (props.framework === "angular") {
    const entry = registry.angular?.[props.component];
    if (!entry) {
      throw new Error(`Island component "${props.component}" is not registered for framework "angular".`);
    }
    const component = await resolveAngularServerIslandComponent(entry);
    const html = await renderAngularIslandToHtml(component, props.props, islandId);
    return {
      attributes: {
        ...getIslandMarkerAttributes(props, islandId)
      },
      html
    };
  }
  throw new Error(`Framework "${props.framework}" is not implemented in this prototype.`);
};
var init_renderIslandMarkup = __esm(() => {
  init_islandSsr();
  init_svelteServerModule();
  init_islandMarkupAttributes();
  init_islands();
  resolvedServerComponentCache = new Map;
  resolvedServerBuildComponentCache = new Map;
});

// src/islands/index.ts
init_islands();
init_renderIslandMarkup();

// node_modules/zustand/esm/vanilla.mjs
var createStoreImpl = (createState) => {
  let state;
  const listeners = /* @__PURE__ */ new Set;
  const setState = (partial, replace) => {
    const nextState = typeof partial === "function" ? partial(state) : partial;
    if (!Object.is(nextState, state)) {
      const previousState = state;
      state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
      listeners.forEach((listener) => listener(state, previousState));
    }
  };
  const getState = () => state;
  const getInitialState = () => initialState;
  const subscribe = (listener) => {
    listeners.add(listener);
    return () => listeners.delete(listener);
  };
  const api = { setState, getState, getInitialState, subscribe };
  const initialState = state = createState(setState, getState, api);
  return api;
};
var createStore = (createState) => createState ? createStoreImpl(createState) : createStoreImpl;

// node_modules/zustand/esm/middleware.mjs
function combine(initialState, create) {
  return (...args) => Object.assign({}, initialState, create(...args));
}

// src/client/islandStore.ts
var getIslandStoreSnapshot = () => {
  globalThis.__ABS_ISLAND_STATE__ ??= {};
  return globalThis.__ABS_ISLAND_STATE__;
};
var getIslandStores = () => {
  globalThis.__ABS_ISLAND_STORES__ ??= new Map;
  return globalThis.__ABS_ISLAND_STORES__;
};
var isSerializableValue = (value) => typeof value !== "function" && value !== undefined;
var toSerializableState = (state) => Object.fromEntries(Object.entries(state).filter(([, value]) => isSerializableValue(value)));
var applySnapshot = (store, snapshot) => {
  if (!snapshot) {
    return;
  }
  store.setState({
    ...store.getState(),
    ...snapshot
  });
};
var getPeerStores = (storeInstances, ownerStore) => [...storeInstances].filter((peer) => peer.store !== ownerStore);
var syncIslandSnapshot = (storeId, state, storeInstances, ownerStore) => {
  const nextSnapshot = toSerializableState(state);
  getIslandStoreSnapshot()[storeId] = nextSnapshot;
  for (const peerStore of getPeerStores(storeInstances, ownerStore)) {
    peerStore.applyExternalSnapshot(nextSnapshot);
  }
};
var createIslandStore = (storeId, initialState, createState) => {
  const store = createStore(combine(initialState, createState));
  const stores = getIslandStores();
  const storeInstances = stores.get(storeId) ?? new Set;
  const initialSnapshot = getIslandStoreSnapshot()[storeId];
  applySnapshot(store, initialSnapshot);
  let isApplyingExternalSnapshot = false;
  const applyExternalSnapshot = (snapshot) => {
    isApplyingExternalSnapshot = true;
    applySnapshot(store, snapshot);
  };
  storeInstances.add({
    applyExternalSnapshot,
    store
  });
  stores.set(storeId, storeInstances);
  syncIslandSnapshot(storeId, store.getState(), storeInstances, store);
  store.subscribe((state) => {
    if (isApplyingExternalSnapshot) {
      isApplyingExternalSnapshot = false;
      return;
    }
    syncIslandSnapshot(storeId, state, storeInstances, store);
  });
  return store;
};
var getIslandStoreServerSnapshot = (store, selector) => selector(store.getInitialState());
var applySnapshotToStoreInstances = (storeId, instances, snapshot) => {
  for (const instance of instances) {
    instance.applyExternalSnapshot(snapshot[storeId] ?? {});
  }
};
var initializeIslandStores = (state) => {
  const currentSnapshot = getIslandStoreSnapshot();
  const nextSnapshot = {
    ...state,
    ...currentSnapshot
  };
  globalThis.__ABS_ISLAND_STATE__ = nextSnapshot;
  for (const [storeId, store] of getIslandStores()) {
    applySnapshotToStoreInstances(storeId, store, nextSnapshot);
  }
};
var readIslandStore = (store, selector) => selector(store.getState());
var subscribeIslandStore = (store, selector, listener) => {
  let currentSelection = selector(store.getState());
  return store.subscribe((state) => {
    const nextSelection = selector(state);
    if (Object.is(nextSelection, currentSelection)) {
      return;
    }
    currentSelection = nextSelection;
    listener(nextSelection);
  });
};
export {
  renderIslandMarkup,
  defineIslandRegistry,
  createIslandStore
};

//# debugId=2CEB635FFB9534A364756E2164756E21
//# sourceMappingURL=index.js.map
