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};
  try {
    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);
    });
  } catch (err) {
  }
  return output;
}
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 {
  injectTags
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vLi4vLi4vc3JjL2NvcmUvc3NyL2h0bW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