import htmlparser2 from "htmlparser2";
function injectTags(html, tags) {
  let output = html;
  if (!tags.length)
    return output;
  const pos = { "head-prepend": -1, head: -1, "body-prepend": -1, body: -1 };
  const parser = new htmlparser2.Parser({
    onopentag(tagname) {
      if (tagname === "head")
        pos["head-prepend"] = parser.endIndex + 1;
      if (tagname === "body")
        pos["body-prepend"] = parser.endIndex + 1;
    },
    onclosetag(tagname) {
      if (tagname === "head")
        pos["head"] = parser.startIndex;
      if (tagname === "body")
        pos["body"] = parser.startIndex;
    }
  });
  parser.write(html);
  parser.end();
  const lastToFirst = Object.entries(pos).sort((a, b) => b[1] - a[1]);
  lastToFirst.forEach(([name, i]) => {
    if (i === -1) {
      return;
    }
    let selected = tags.filter(({ injectTo }) => {
      if (name === "head-prepend" && !injectTo) {
        return true;
      } else {
        return injectTo === name;
      }
    });
    if (!selected.length)
      return;
    output = output.substring(0, i) + serializeTags(selected) + html.substring(i);
  });
  return output;
}
function collectResources(html) {
  let resources = [];
  const parser = new htmlparser2.Parser({
    onopentag(tagname, attrs) {
      if (tagname === "link")
        resources.push(attrs);
    }
  });
  parser.write(html);
  parser.end();
  return resources;
}
const unaryTags = new Set(["link", "meta", "base"]);
function serializeTag({ tag, attrs, children }, indent = "") {
  if (unaryTags.has(tag)) {
    return `<${tag}${serializeAttrs(attrs)}>`;
  } else {
    return `<${tag}${serializeAttrs(attrs)}>${serializeTags(children, incrementIndent(indent))}</${tag}>`;
  }
}
function serializeTags(tags, indent = "") {
  if (typeof tags === "string") {
    return tags;
  } else if (tags && tags.length) {
    return tags.map((tag) => `${indent}${serializeTag(tag, indent)}
`).join("");
  }
  return "";
}
function serializeAttrs(attrs) {
  let res = "";
  for (const key in attrs) {
    if (typeof attrs[key] === "boolean") {
      res += attrs[key] ? ` ${key}` : ``;
    } else {
      res += ` ${key}=${JSON.stringify(attrs[key])}`;
    }
  }
  return res;
}
function incrementIndent(indent = "") {
  return `${indent}${indent[0] === "	" ? "	" : "  "}`;
}
export {
  collectResources,
  inj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