var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {enumerable: true, configurable: true, writable: true, value}) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
  var target = {};
  for (var prop in source)
    if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
      target[prop] = source[prop];
  if (source != null && __getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(source)) {
      if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
        target[prop] = source[prop];
    }
  return target;
};
import shorthash from "shorthash";
import {extractDirectives, generateHydrateScript} from "./hydration.js";
import {serializeListValue} from "./util.js";
import {createMetadata} from "./metadata.js";
async function _render(child) {
  child = await child;
  if (Array.isArray(child)) {
    return (await Promise.all(child.map((value) => _render(value)))).join("\n");
  } else if (typeof child === "function") {
    return _render(child());
  } else if (typeof child === "string") {
    return child;
  } else if (!child && child !== 0) {
  } else if (child instanceof AstroComponent || child.toString() === "[object AstroComponent]") {
    return await renderAstroComponent(child);
  } else {
    return child;
  }
}
class AstroComponent {
  constructor(htmlParts, expressions) {
    this.htmlParts = htmlParts;
    this.expressions = expressions;
  }
  get [Symbol.toStringTag]() {
    return "AstroComponent";
  }
  *[Symbol.iterator]() {
    const {htmlParts, expressions} = this;
    for (let i = 0; i < htmlParts.length; i++) {
      const html = htmlParts[i];
      const expression = expressions[i];
      yield _render(html);
      yield _render(expression);
    }
  }
}
async function render(htmlParts, ...expressions) {
  return new AstroComponent(htmlParts, expressions);
}
function createComponent(cb) {
  cb.isAstroComponentFactory = true;
  return cb;
}
async function renderSlot(_result, slotted, fallback) {
  if (slotted) {
    return _render(slotted);
  }
  return fallback;
}
const Fragment = Symbol("Astro.Fragment");
async function renderComponent(result, displayName, Component, _props, slots = {}) {
  var _a;
  Component = await Component;
  const children = await renderSlot(result, slots == null ? void 0 : slots.default);
  const {renderers} = result._metadata;
  if (Component === Fragment) {
    return children;
  }
  if (Component && Component.isAstroComponentFactory) {
    const output = await renderToString(result, Component, _props, slots);
    return output;
  }
  let metadata = {displayName};
  if (Component == null) {
    throw new Error(`Unable to render ${metadata.displayName} because it is ${Component}!
Did you forget to import the component or is it possible there is a typo?`);
  }
  const {hydration, props} = extractDirectives(_props);
  let html = "";
  if (hydration) {
    metadata.hydrate = hydration.directive;
    metadata.hydrateArgs = hydration.value;
    metadata.componentExport = hydration.componentExport;
    metadata.componentUrl = hydration.componentUrl;
  }
  let renderer;
  for (const r of renderers) {
    if (await r.ssr.check(Component, props, children)) {
      renderer = r;
      break;
    }
  }
  if (!renderer) {
    if (typeof Component === "string") {
      html = await renderAstroComponent(await render`<${Component}${spreadAttributes(props)}>${children}</${Component}>`);
    } else {
      throw new Error(`Astro is unable to render ${metadata.displayName}!
Is there a renderer to handle this type of component defined in your Astro config?`);
    }
  } else {
    ({html} = await renderer.ssr.renderToStaticMarkup(Component, props, children));
  }
  if ((_a = renderer == null ? void 0 : renderer.polyfills) == null ? void 0 : _a.length) {
    let polyfillScripts = renderer.polyfills.map((src) => `<script type="module">import "${src}";</script>`).join("");
    html = html + polyfillScripts;
  }
  if (!hydration) {
    return html.replace(/\<\/?astro-fragment\>/g, "");
  }
  const astroId = shorthash.unique(`<!--${metadata.componentExport.value}:${metadata.componentUrl}-->
${html}`);
  result.scripts.add(await generateHydrateScript({renderer, astroId, props}, metadata));
  return `<astro-root uid="${astroId}">${html}</astro-root>`;
}
function createFetchContentFn(url) {
  const fetchContent = (importMetaGlobResult) => {
    let allEntries = [...Object.entries(importMetaGlobResult)];
    if (allEntries.length === 0) {
      throw new Error(`[${url.pathname}] Astro.fetchContent() no matches found.`);
    }
    return allEntries.map(([spec, mod]) => {
      if (!mod.frontmatter) {
        return;
      }
      const urlSpec = new URL(spec, url).pathname;
      return __spreadProps(__spreadValues({}, mod.frontmatter), {
        content: mod.metadata,
        file: new URL(spec, url),
        url: urlSpec.includes("/pages/") ? urlSpec.replace(/^.*\/pages\//, "/").replace(/(\/index)?\.md$/, "") : void 0
      });
    }).filter(Boolean);
  };
  return fetchContent;
}
function createAstro(fileURLStr, site) {
  const url = new URL(fileURLStr);
  const fetchContent = createFetchContentFn(url);
  return {
    site: new URL(site),
    fetchContent,
    resolve(...segments) {
      return segments.reduce((u, segment) => new URL(segment, u), url).pathname;
    }
  };
}
function addAttribute(value, key) {
  if (value == null || value === false) {
    return "";
  }
  if (key === "class:list") {
    return ` ${key.slice(0, -5)}="${serializeListValue(value)}"`;
  }
  return ` ${key}="${value}"`;
}
function spreadAttributes(values) {
  let output = "";
  for (const [key, value] of Object.entries(values)) {
    output += addAttribute(value, key);
  }
  return output;
}
function defineStyleVars(selector, vars) {
  let output = "\n";
  for (const [key, value] of Object.entries(vars)) {
    output += `  --${key}: ${value};
`;
  }
  return `${selector} {${output}}`;
}
function defineScriptVars(vars) {
  let output = "";
  for (const [key, value] of Object.entries(vars)) {
    output += `let ${key} = ${JSON.stringify(value)};
`;
  }
  return output;
}
async function renderToString(result, componentFactory, props, children) {
  const Component = await componentFactory(result, props, children);
  let template = await renderAstroComponent(Component);
  return template;
}
const uniqueElements = (item, index, all) => {
  const props = JSON.stringify(item.props);
  const children = item.children;
  return index === all.findIndex((i) => JSON.stringify(i.props) === props && i.children == children);
};
async function renderPage(result, Component, props, children) {
  const template = await renderToString(result, Component, props, children);
  const styles = Array.from(result.styles).filter(uniqueElements).map((style) => renderElement("style", style));
  const scripts = Array.from(result.scripts).filter(uniqueElements).map((script) => renderElement("script", script));
  return template.replace("</head>", styles.join("\n") + scripts.join("\n") + "</head>");
}
async function renderAstroComponent(component) {
  let template = "";
  for await (const value of component) {
    if (value || value === 0) {
      template += value;
    }
  }
  return template;
}
function renderElement(name, {props: _props, children = ""}) {
  const _a = _props, {lang: _, "data-astro-id": astroId, "define:vars": defineVars} = _a, props = __objRest(_a, ["lang", "data-astro-id", "define:vars"]);
  if (defineVars) {
    if (name === "style") {
      if (props.global) {
        children = defineStyleVars(`:root`, defineVars) + "\n" + children;
      } else {
        children = defineStyleVars(`.astro-${astroId}`, defineVars) + "\n" + children;
      }
      delete props.global;
    }
    if (name === "script") {
      delete props.hoist;
      children = defineScriptVars(defineVars) + "\n" + children;
    }
  }
  return `<${name}${spreadAttributes(props)}>${children}</${name}>`;
}
export {
  AstroComponent,
  Fragment,
  addAttribute,
  createAstro,
  createComponent,
  createMetadata,
  defineScriptVars,
  defineStyleVars,
  render,
  renderAstroComponent,
  renderComponent,
  renderPage,
  renderSlot,
  renderToString,
  spreadAttributes
};
//# sourceMappingURL=data:application/json;base64, 
