import { createRequire as $createRequire } from "node:module";

const require = $createRequire(import.meta.url);

import { d as dedent, H as HighlightJS, c as createTwoFilesPatch, M as MarkdownIt, a as deflist_plugin } from './vendor-D4BVkQg8.mjs';
import path from 'node:path/posix';
import sp__default from 'node:path';
import 'crypto';
import crypto from 'node:crypto';
import 'node:child_process';
import fs__default from 'node:fs';
import { version } from 'vue';
import { g as generateCode } from './vue3-DtTC1eal.mjs';

function isDocumentPage(doc) {
  return doc.kind === "page";
}

function findDocument(haystack, needle) {
  const match = haystack.find((it) => {
    if (it.id === needle) {
      return true;
    }
    if (it.name === needle) {
      return true;
    }
    if (it.alias.includes(needle)) {
      return true;
    }
    return false;
  });
  return match ?? null;
}

function findTag(tags, tag) {
  const match = tags.find((it) => it === tag || it.startsWith(`${tag}=`));
  if (!match) {
    return null;
  }
  if (match === tag) {
    return { tag, value: null };
  } else {
    return { tag, value: match.slice(tag.length + 1) };
  }
}

const replacements = {
  \u00E5: "a",
  \u00E4: "a",
  \u00F6: "o"
};
function findVersion(text) {
  const match = /(\d+)\.(\d+)\.(\d+) \(\d+-\d+-\d+\)/.exec(text);
  if (match) {
    return [
      parseInt(match[1], 10),
      parseInt(match[2], 10),
      parseInt(match[3], 10)
    ];
  } else {
    return null;
  }
}
function generateId(text) {
  const version = findVersion(text);
  if (version) {
    return `v${version.join("-")}`;
  }
  return text.toLowerCase().trim().replace(/[åäö]/g, (m) => replacements[m]).replace(/[^a-z0-9]+/g, "_").replace(/^_+/, "").replace(/_+$/, "");
}

function getFingerprint(source) {
  return crypto.createHash("md5").update(source).digest("hex").slice(0, 6);
}

function normalizePath(...pathSegments) {
  const filePath = path.join(...pathSegments);
  return path.normalize(filePath).replace(/^([A-Z]):\\/, "/").replace(/\\/g, "/");
}

function getOutputFilePath(outputFolder, fileInfo) {
  const { path, outputName } = fileInfo;
  if (outputName === false) {
    return null;
  }
  return normalizePath(outputFolder, path, outputName);
}

function hasTag(tags, tag) {
  const match = tags.find((it) => it === tag || it.startsWith(`${tag}=`));
  return Boolean(match);
}

const replacement = {
  "<": `&lt;`,
  ">": `&gt;`,
  "&": `&amp;`,
  '"': `&quot;`,
  "'": `&apos;`
};
function htmlencode(text) {
  return text.replace(/[<>&"']/g, (m) => {
    return replacement[m];
  });
}

function parseImport(raw) {
  const comments = [];
  let stripped = raw;
  let previous;
  do {
    previous = stripped;
    stripped = stripped.replace(/<!--.*?-->/gms, (match) => {
      comments.push(match);
      return "";
    });
  } while (stripped !== previous);
  const filename = stripped.trim();
  const extension = sp__default.parse(filename).ext.slice(1);
  return {
    filename,
    extension,
    comments
  };
}

function getExampleName(filename) {
  return sp__default.parse(filename).name;
}

const vueMajor = parseInt(version.split(".", 2)[0], 10);
function vueGenerator() {
  switch (vueMajor) {
    case 2:
      throw new Error(
        "Vue 2 is no longer supported, upgrade to Vue 3 or downgrade docs-generator"
      );
    case 3:
      return generateCode;
  }
}
function generateExample(options) {
  const { language, fileMatcher } = options;
  if (language === "import") {
    const parsed = parseImport(options.source);
    const filename = fileMatcher(parsed.filename, "when importing example");
    const language2 = parsed.extension;
    const comments = parsed.comments;
    const content = fs__default.readFileSync(filename, "utf-8");
    const example = generateExample({
      ...options,
      source: content,
      language: language2,
      filename
    });
    return { ...example, comments };
  }
  switch (language) {
    case "vue":
      return generateVueExample(options);
    case "html":
      return generateStaticExample(options);
    default:
      return generateStaticExample(options);
  }
}
function generateVueExample(options) {
  const { filename, source, parent, setupPath, tags } = options;
  const fn = vueGenerator();
  const slug = getExampleName(filename);
  const fingerprint = getFingerprint(source);
  const { markup, sourcecode, output } = fn({
    filename,
    slug,
    fingerprint,
    code: source,
    setupPath
  });
  if (output) {
    return {
      source,
      language: options.language,
      comments: [],
      tags,
      markup,
      output,
      runtime: true,
      task: {
        outputFile: output,
        sourcecode,
        sourceFile: filename,
        parent
      }
    };
  } else {
    return {
      source: sourcecode,
      language: "plaintext",
      comments: [],
      tags,
      markup,
      output: null,
      runtime: true,
      task: null
    };
  }
}
function generateStaticExample(options) {
  const { filename, source, language, tags } = options;
  const slug = getExampleName(filename);
  const fingerprint = getFingerprint(source);
  const asset = `${slug}-${fingerprint}.${language}`;
  const runtimeLanguages = ["html"];
  const runtime = runtimeLanguages.includes(language);
  return {
    source,
    language: options.language,
    comments: [],
    tags,
    markup: source,
    output: runtime ? asset : null,
    runtime,
    task: null
  };
}

function normalizeLanguage(lang) {
  switch (lang) {
    case "ts":
      return "typescript";
    case "js":
      return "javascript";
    default:
      return lang;
  }
}

function parseInfostring(infostring) {
  const [rawLanguage, ...rawTags] = infostring.trim().split(/\s+/);
  return {
    language: normalizeLanguage(rawLanguage),
    tags: rawTags
  };
}

function removeLinesInline(lines, { begin, end }) {
  for (let i = begin; i <= end; i++) {
    lines[i] = "";
  }
  if (lines[begin - 1] === "\n") {
    lines[begin - 1] = "";
    begin--;
  }
  if (lines[end + 1] === "\n") {
    lines[end + 1] = "";
  }
  if (end === lines.length - 1 && begin > 0) {
    lines[begin - 1] = lines[begin - 1].slice(0, -1);
  }
}
function cutSnippets(code) {
  const lines = code.split(/\n/).map((it, index, lines2) => index < lines2.length - 1 ? `${it}
` : it);
  const directive = (
    /* eslint-disable-next-line sonarjs/regex-complexity -- not to bad for a regexp */
    /(?:\/\* +--- +cut (?<js>above|below|begin|end) +--- +\*\/|<!---? +cut (?<html>above|below|begin|end) +---?>)/
  );
  let buffer = -1;
  lines.forEach((line, index) => {
    const match = directive.exec(line);
    const { js, html } = match?.groups ?? { js: null, html: null };
    const instruction = js ?? html;
    if (!instruction) {
      return;
    }
    switch (instruction) {
      /* --- cut above --- */
      case "above":
        removeLinesInline(lines, {
          begin: 0,
          end: index
        });
        break;
      /* --- cut below --- */
      case "below":
        removeLinesInline(lines, {
          begin: index,
          end: lines.length - 1
        });
        break;
      /* --- cut begin --- */
      case "begin":
        if (buffer === -1) {
          buffer = index;
        }
        break;
      /* --- cut end --- */
      case "end":
        removeLinesInline(lines, {
          begin: Math.max(buffer, 0),
          end: index
        });
        buffer = -1;
        break;
    }
  });
  if (buffer >= 0) {
    removeLinesInline(lines, {
      begin: buffer,
      end: lines.length - 1
    });
  }
  return lines.join("");
}
function stripEslintComments(code) {
  const matchLine = /^[ \t]*(\/\* eslint-disable[^*]*\*\/|\/\/ eslint-disable.*)\n/gm;
  const matchEmbedded = /[ \t]*(\/\* eslint-disable[^*]*\*\/|\/\/ eslint-disable.*)/g;
  return code.replace(matchLine, "").replace(matchEmbedded, "");
}
function stripHtmlValidateComments(code) {
  const matchLine = /^[ \t]*(<!--\s*\[html-validate-[^\]]+]\s*-->)\n/gm;
  const matchEmbedded = /[ \t]*(<!--\s*\[html-validate-[^\]]+]\s*-->)/g;
  return code.replace(matchLine, "").replace(matchEmbedded, "");
}
function maybeDedent(value) {
  if (/^\s*$/.test(value)) {
    return value;
  }
  if (/^\s/.test(value)) {
    return dedent(value);
  } else {
    return value;
  }
}
const transformations = {
  html: [cutSnippets, stripHtmlValidateComments, maybeDedent],
  vue: [
    cutSnippets,
    stripEslintComments,
    stripHtmlValidateComments,
    maybeDedent
  ],
  javascript: [cutSnippets, stripEslintComments, maybeDedent],
  typescript: [cutSnippets, stripEslintComments, maybeDedent]
};
function transformCode(code, lang) {
  const normalizedLanguage = normalizeLanguage(lang);
  const fns = transformations[normalizedLanguage] ?? [];
  for (const fn of fns) {
    code = fn(code);
  }
  return code;
}

var exampleWorkerUrl = new URL("./worker-DUs54YZx.mjs", import.meta.url);

class SoftError extends Error {
  code;
  details;
  /**
   * @internal
   */
  constructor(code, message, ...args) {
    super(message);
    this.name = this.constructor.name;
    this.code = code;
    const [details] = args;
    this.details = details;
  }
}

function getRelativeUrl(from, to) {
  const fromResolved = getOutputFilePath(".", from.fileInfo);
  const toResolved = getOutputFilePath(".", to.fileInfo);
  if (!fromResolved || !toResolved) {
    throw new Error("Cannot create link to document with no output");
  }
  const fromDir = path.dirname(fromResolved);
  const toDir = path.dirname(toResolved);
  const relative = path.relative(fromDir, toResolved);
  if (fromDir === toDir) {
    return relative === "index.html" ? "./" : `./${relative}`;
  } else if (relative.endsWith("/index.html")) {
    return path.dirname(relative);
  } else {
    return relative;
  }
}
function getLinkTitle(doc, key, explicitTitle) {
  if (explicitTitle) {
    return explicitTitle.replace(/^[\\|]\s*/, "");
  }
  const { title, component } = doc.attributes;
  if (component?.some((it) => it.name === key)) {
    return `<code>${key}</code>`;
  } else {
    return title ?? doc.name;
  }
}
const linkTag = {
  name: "link",
  description: "Create a link to another document",
  handler(doc, docs, content) {
    const match = /^([^\s#]+)(#\S+)?\s*(.+)?$/.exec(content);
    if (!match) {
      throw new SoftError(
        "ELINKFORMAT",
        `Failed to parse link "${content}"`
      );
    }
    const key = match[1];
    const hash = match[2];
    const explicitTitle = match[3];
    if (key.startsWith("http://") || key.startsWith("https://")) {
      return `<a href="${key}${hash ?? ""}">${explicitTitle ?? key}</a>`;
    }
    const linked = findDocument(docs, key);
    if (!linked) {
      throw new SoftError(
        "ELINKTARGET",
        `Failed to find linked document "${key}"`,
        {
          key,
          hash,
          title: explicitTitle
        }
      );
    }
    if (!isDocumentPage(linked)) {
      throw new SoftError(
        "ELINKPARTIAL",
        `Cannot link to partial document "${key}"`,
        {
          key,
          hash,
          title: explicitTitle
        }
      );
    }
    const url = getRelativeUrl(doc, linked);
    const title = getLinkTitle(linked, key, explicitTitle);
    return `<a href="${url}${hash ?? ""}">${title}</a>`;
  }
};

const optionalTag = {
  name: "optional",
  description: "Create a tag for symbolize optional content",
  handler() {
    return `<span class="docs-tag docs-tag--default">Optional</span>`;
  }
};

const inlineTags = [linkTag, optionalTag];
var inline_tags_default = inlineTags;

function findTestId(tags) {
  const prefix = "test-id=";
  const tag = tags.find((it) => {
    return it.startsWith(prefix);
  });
  const match = tag?.match(/^test-id=(?:"([^"]+)"|'([^']+)'|([^'"]+))$/);
  if (!match) {
    return null;
  }
  return match.slice(1).find(Boolean) ?? null;
}

const HTML_ESCAPE_REPLACE_RE = /[&<>"]/g;
const HTML_REPLACEMENTS = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;"
};
function escapeHtml(str) {
  return str.replace(HTML_ESCAPE_REPLACE_RE, (ch) => HTML_REPLACEMENTS[ch]);
}
function wrap(content, language) {
  const markup = (
    /* HTML */
    `
        <code class="hljs lang-${language}" tabindex="0">${content}</code>
    `
  );
  return markup.trim();
}
function highlight({
  source,
  language
}) {
  switch (language) {
    case "":
    case "import":
    case "mermaid":
    case "plaintext":
      return `<code>${escapeHtml(source)}</code>`;
    case "vue":
      return highlight({ source, language: "html" });
  }
  try {
    const { value } = HighlightJS.highlight(source, { language });
    return wrap(value, language);
  } catch (err) {
    return wrap(String(err), language);
  }
}

function replaceAtLink(text) {
  return text.replace(
    /{@link [^}]+[$}]/g,
    (match) => match.replace(/^{/, "&lcub;").replace(/}$/, "&rcub;")
  );
}

function getClassModifier(tags) {
  if (tags.includes("borderless")) {
    return "code-preview--borderless";
  }
  return "code-preview--default";
}
function getStandalonePath(output) {
  if (!output) {
    return null;
  }
  const { dir, name } = sp__default.parse(output);
  return sp__default.join(dir, `${name}.html`);
}
function ensureTrailingNewline(text) {
  if (text.endsWith("\n")) {
    return text;
  } else {
    return `${text}
`;
  }
}
function codePreview(options) {
  const { generateExample, getImportedSource } = options;
  return (md) => {
    md.renderer.rules.fence = fence.bind(void 0, md);
  };
  function getSource(content, language, tags, env) {
    const { namedExamples } = env;
    if (language === "import") {
      const parsed = parseImport(content);
      const importedContent = getImportedSource(parsed.filename);
      return getSource(importedContent, parsed.extension, tags, env);
    }
    const compare = findTag(tags, "compare");
    if (compare && compare.value !== null) {
      const { value: context } = findTag(tags, "context") ?? {};
      const reference = namedExamples.get(compare.value);
      if (!reference) {
        throw new Error(
          `Failed to find referenced example "${compare.value}"`
        );
      }
      const a = ensureTrailingNewline(
        transformCode(reference.content, reference.language)
      );
      const b = ensureTrailingNewline(transformCode(content, language));
      const diff = createTwoFilesPatch("a", "b", a, b, "", "", {
        context: context ? parseInt(context, 10) : 3,
        ignoreWhitespace: true
      }).split("\n").slice(4).join("\n");
      return {
        source: diff,
        language: "diff"
      };
    }
    return { source: content, language };
  }
  function fence(_md, tokens, idx, _options, env) {
    const { fileInfo } = env;
    const { content: rawContent, info, map } = tokens[idx];
    const { language: rawLanguage, tags: rawTags } = parseInfostring(info);
    const { source, language } = getSource(
      rawContent,
      rawLanguage,
      rawTags,
      env
    );
    const name = findTag(rawTags, "name")?.value;
    if (name) {
      env.namedExamples.set(name, {
        name,
        tags: rawTags,
        /* store original raw content unless it is an imported example */
        content: rawLanguage === "import" ? source : rawContent,
        language: rawLanguage === "import" ? language : rawLanguage
      });
    }
    if (hasTag(rawTags, "hidden")) {
      return "";
    }
    if (rawLanguage === "mermaid") {
      return (
        /* HTML */
        `
                <pre class="mermaid">${htmlencode(rawContent)}</pre>
            `
      );
    }
    const needOriginalSource = language !== "diff" && rawLanguage === "import";
    const example = generateExample({
      source: needOriginalSource ? rawContent : source,
      language: needOriginalSource ? rawLanguage : language,
      filename: fileInfo.fullPath,
      tags: rawTags
    });
    const { tags } = example;
    const hashContent = `${String(map?.[0])}:${String(map?.[1])}:${info}:${rawContent}`;
    const fingerprint = getFingerprint(hashContent);
    const transformedCode = transformCode(example.source, example.language);
    const highlightedCode = replaceAtLink(
      highlight({ source: transformedCode, language: example.language })
    );
    const testId = findTestId(tags) ?? findTag(tags, "name")?.value;
    const liveExample = tags.includes("live-example");
    const staticCode = example.runtime === false || tags.includes("static");
    const noMarkup = tags.includes("nomarkup");
    const fullscreen = tags.includes("fullscreen");
    const modifier = getClassModifier(tags);
    const standalonePath = getStandalonePath(example.output);
    const showFullscreen = Boolean(standalonePath) && fullscreen;
    const testIdAttr = testId ? `data-test="${testId}"` : "";
    const filteredTags = tags.filter((it) => {
      if (it.startsWith("test-id=") || it.startsWith("name") || it.startsWith("compare")) {
        return false;
      }
      return true;
    });
    const dataTagsAttr = filteredTags.length > 0 ? `data-tags="${htmlencode(filteredTags.join(" "))}"` : "";
    if (liveExample) {
      return (
        /* HTML */
        `
                <div
                    id="example-${fingerprint}"
                    class="code-preview code-preview--borderless"
                    ${testIdAttr}
                    ${dataTagsAttr}
                    data-language="${example.language}"
                >
                    ${example.markup}
                </div>
            `
      );
    }
    if (staticCode) {
      return (
        /* HTML */
        `
                <div
                    id="example-${fingerprint}"
                    class="code-preview ${modifier}"
                    ${testIdAttr}
                    ${dataTagsAttr}
                    data-language="${example.language}"
                >
                    ${example.comments.join("\n")}
                    <pre class="code-preview__markup">${highlightedCode}</pre>
                </div>
            `
      );
    }
    if (noMarkup) {
      return (
        /* HTML */
        `
                <div
                    id="example-${fingerprint}"
                    class="code-preview ${modifier}"
                    ${testIdAttr}
                    ${dataTagsAttr}
                    data-language="${example.language}"
                >
                    ${example.comments.join("\n")}
                    <div class="code-preview__preview user-background">
                        ${example.markup}
                    </div>
                </div>
            `
      );
    }
    const toggleMarkup = (
      /* HTML */
      `
            <button
                type="button"
                class="button button--discrete code-preview__toggle-markup"
                aria-expanded="false"
                onclick="toggleMarkup(this)"
            >
                <i class="icon icon--code"></i>
                Visa kod
            </button>
        `
    );
    const toggleFullscreen = showFullscreen ? (
      /* HTML */
      `
                  <a
                      href="${standalonePath ?? ""}"
                      class="code-preview__fullscreen"
                  >
                      <i class="icon icon--fullscreen"></i>
                      Helsk\xE4rm
                  </a>
              `
    ) : "";
    return (
      /* HTML */
      `
            <div
                id="example-${fingerprint}"
                class="code-preview ${modifier}"
                ${testIdAttr}
                ${dataTagsAttr}
                data-language="${example.language}"
            >
                ${example.comments.join("\n")}
                <div class="code-preview__preview user-background">
                    ${example.markup}
                </div>
                <div>${toggleMarkup} ${toggleFullscreen}</div>
                <div
                    class="code-preview__expand animate-expand"
                    style="height: 0px;"
                    hidden
                >
                    <pre class="code-preview__markup">${highlightedCode}</pre>
                </div>
            </div>
        `
    );
  }
}

function getTokensText(tokens) {
  return tokens.filter((token) => ["text", "code_inline"].includes(token.type)).map((token) => token.content).join("");
}
function headingLevel(options) {
  const { initialLevel } = options;
  const offset = initialLevel - 1;
  let counter = 1;
  return function(md) {
    md.renderer.rules.heading_open = function(tokens, idx, _options, env) {
      const { ids } = env;
      const { tag } = tokens[idx];
      const title = getTokensText(tokens[idx + 1]?.children ?? []);
      let id = generateId(title);
      if (ids.has(id)) {
        id += `--${String(counter++)}`;
      }
      ids.add(id);
      return tag.replace(/h(\d)/, (_, n) => {
        const level = parseInt(n, 10) + offset;
        env.currentHeading = level;
        return `<h${String(level)} id="${id}"><a class="header-anchor" href="#${id}">`;
      });
    };
    md.renderer.rules.heading_close = function(tokens, idx) {
      const { tag } = tokens[idx];
      return tag.replace(/h(\d)/, (_, n) => {
        const level = parseInt(n, 10) + offset;
        return `</a></h${String(level)}>`;
      });
    };
  };
}

function computeHash(source) {
  return crypto.createHash("md5").update(source).digest("hex");
}
function getFilename(fileInfo, src) {
  const key = [fileInfo.fullPath, src].join("-");
  const hash = computeHash(key);
  const { ext } = path.parse(src);
  return `images/${hash}${ext}`;
}
function imageResources(options) {
  const { addResource } = options;
  function imageResource(tokens, index, options2, env, self) {
    const { fileInfo } = env;
    const token = tokens[index];
    token.attrs ??= [];
    const srcAttr = token.attrGet("src");
    if (srcAttr) {
      const dst = getFilename(fileInfo, srcAttr);
      const src = path.join(path.dirname(fileInfo.fullPath), srcAttr);
      const url = path.relative(fileInfo.path, path.join("assets", dst));
      addResource(dst, src);
      token.attrs[token.attrIndex("src")][1] = url;
    }
    token.attrs[token.attrIndex("alt")][1] = self.renderInlineAsText(
      /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- from upstream code */
      token.children,
      options2,
      env
    );
    return self.renderToken(tokens, index, options2);
  }
  return function(md) {
    md.renderer.rules.image = imageResource;
  };
}

function altContainer(context) {
  const { md, env, docs } = context;
  return (tokens, index) => {
    const token = tokens[index];
    const needle = token.info;
    const tags = token.info.trim().split(/\s+/);
    const doc = findDocument(docs, needle);
    if (doc?.format === "markdown") {
      const body = typeof doc.body === "string" ? doc.body : doc.body(tags);
      return md.render(body, env);
    }
    return md.render(token.content, env);
  };
}

function apiContainer(context) {
  const { md, env, docs, included, handleSoftError } = context;
  return (tokens, index) => {
    const token = tokens[index];
    const needle = token.content.trim();
    const tags = token.info.trim().split(/\s+/);
    const doc = findDocument(docs, needle);
    if (!doc) {
      return handleSoftError(
        new SoftError(
          "EINCLUDETARGET",
          `No document matches "${needle}" when trying to include content`,
          { id: needle }
        )
      );
    }
    const key = [doc.id, ...tags].join("|");
    const loop = included.get(doc.id);
    if (loop && loop !== context.doc.id) {
      return handleSoftError(
        new SoftError(
          "EINCLUDERECURSION",
          `Recursion detected when including document "${doc.id}"`
        )
      );
    }
    included.set(key, context.doc.id);
    const body = typeof doc.body === "string" ? doc.body : doc.body(tags);
    if (doc.format === "html") {
      return body.replace(
        /* replace `<next-heading-level>` and `</next-heading-level>` with actual h-tags */
        /(?<=<\/?)next-heading-level/g,
        `h${String(env.currentHeading + 1)}`
      );
    }
    const content = md.render(body, env);
    return (
      /* HTML */
      ` <div>${content}</div> `
    );
  };
}

function detailsContainer(context, options) {
  const { md, env } = context;
  function parseInfo(info) {
    const customTitle = info ? info.split(" ") : [];
    if (customTitle.length > 0) {
      return customTitle.join(" ");
    } else {
      return options.title.details ?? "Details";
    }
  }
  return (tokens, index) => {
    const token = tokens[index];
    const title = parseInfo(token.info);
    const text = token.content.trim();
    return (
      /* HTML */
      `
            <details class="docs-messagebox docs-messagebox--details">
                <summary class="docs-messagebox__title">
                    ${md.renderInline(title, env)}
                </summary>
                ${md.render(text, env)}
            </details>
        `
    );
  };
}

const defaultTitle = {
  info: "INFO",
  warning: "WARNING",
  danger: "DANGER"
};
function messageboxContainer(context, options, alias) {
  const { md, env } = context;
  function getTitle(variant, customTitle) {
    if (customTitle && customTitle.length > 0) {
      return customTitle.join(" ");
    } else {
      return options.title[variant] ?? defaultTitle[variant] ?? "";
    }
  }
  function parseInfo(info) {
    if (alias) {
      const variant = alias;
      const customTitle = info ? info.split(" ") : [];
      const title = getTitle(variant, customTitle);
      return { variant, title };
    } else {
      const [variant = "info", ...customTitle] = info ? info.split(" ") : [];
      const title = getTitle(variant, customTitle);
      return { variant, title };
    }
  }
  return (tokens, index) => {
    const token = tokens[index];
    const { variant, title } = parseInfo(token.info);
    const text = token.content.trim();
    return (
      /* HTML */
      `
            <div class="docs-messagebox docs-messagebox--${variant}">
                ${title ? `<p class="docs-messagebox__title">${md.renderInline(
        title,
        env
      )}</p>` : ""}
                ${md.render(text, env)}
            </div>
        `
    );
  };
}

const markerStr = ":";
const markerChar = markerStr.charCodeAt(0);
function containerParser(md, options) {
  function container(state, startLine, endLine, silent) {
    let pos = state.bMarks[startLine] + state.tShift[startLine];
    let max = state.eMarks[startLine];
    if (state.sCount[startLine] - state.blkIndent >= 4) {
      return false;
    }
    if (pos + 3 > max) {
      return false;
    }
    const marker = state.src.charCodeAt(pos);
    if (marker !== markerChar) {
      return false;
    }
    let mem = pos;
    pos = state.skipChars(pos, marker);
    let len = pos - mem;
    if (len < 3) {
      return false;
    }
    const markup = state.src.slice(mem, pos);
    const params = state.src.slice(pos, max).trim().split(/\s+/);
    const kind = params[0];
    const info = params.slice(1).join(" ");
    if (silent) {
      return true;
    }
    let nextLine = startLine;
    let haveEndMarker = false;
    for (; ; ) {
      nextLine++;
      if (nextLine >= endLine) {
        break;
      }
      pos = mem = state.bMarks[nextLine] + state.tShift[nextLine];
      max = state.eMarks[nextLine];
      if (pos < max && state.sCount[nextLine] < state.blkIndent) {
        break;
      }
      if (state.src.charCodeAt(pos) !== marker) {
        continue;
      }
      if (state.sCount[nextLine] - state.blkIndent >= 4) {
        continue;
      }
      pos = state.skipChars(pos, marker);
      if (pos - mem < len) {
        continue;
      }
      pos = state.skipSpaces(pos);
      if (pos < max) {
        continue;
      }
      haveEndMarker = true;
      break;
    }
    len = state.sCount[startLine];
    state.line = nextLine + (haveEndMarker ? 1 : 0);
    const token = state.push(`doc_${kind}`, "div", 0);
    token.info = info.trim();
    token.content = state.getLines(startLine + 1, nextLine, len, true);
    token.markup = markup;
    token.map = [startLine, state.line];
    return true;
  }
  md.block.ruler.before("fence", "container_include", container, {
    alt: ["paragraph", "reference", "blockquote", "list"]
  });
  for (const [kind, fn] of Object.entries(options)) {
    md.renderer.rules[`doc_${kind}`] = fn;
  }
}
function containerRenderer(doc, docs, env, included, handleSoftError, options) {
  return function(md) {
    const context = {
      md,
      env,
      get doc() {
        return doc();
      },
      docs,
      included,
      handleSoftError
    };
    md.use(containerParser, {
      alt: altContainer(context),
      api: apiContainer(context),
      details: detailsContainer(context, options.messagebox),
      messagebox: messageboxContainer(context, options.messagebox),
      /* aliases for messagebox containers */
      info: messageboxContainer(context, options.messagebox, "info"),
      tip: messageboxContainer(context, options.messagebox, "tip"),
      warning: messageboxContainer(
        context,
        options.messagebox,
        "warning"
      ),
      danger: messageboxContainer(context, options.messagebox, "danger")
    });
  };
}

function paragraph() {
  const renderToken = (...args) => {
    const [tokens, idx, options, , self] = args;
    return self.renderToken(tokens, idx, options);
  };
  return function(md) {
    const renderRule = md.renderer.rules.paragraph_open ?? renderToken;
    md.renderer.rules.paragraph_open = (tokens, idx, index, env, self) => {
      tokens[idx].attrJoin("class", "docs-paragraph");
      return renderRule(tokens, idx, index, env, self);
    };
  };
}

function table() {
  return function(md) {
    md.renderer.rules.table_open = () => `<table class="table">
`;
    md.renderer.rules.tr_open = () => `<tr class="table__row">
`;
    md.renderer.rules.th_open = () => `<th class="table__column table__column--text" scope="col">`;
    md.renderer.rules.td_open = () => `<td class="table__column table__column--text">`;
  };
}

function codeInline() {
  return function(md) {
    const original = md.renderer.rules.code_inline;
    md.renderer.rules.code_inline = (...args) => {
      const tmp = original(...args);
      return replaceAtLink(tmp);
    };
  };
}

function processInlineTags(tags, doc, docs, text, handleSoftError) {
  return text.replace(
    /{@(@?)([^{}]+)}/g,
    (_, escape, content) => {
      if (escape) {
        return `{@${content}}`;
      }
      const match = /^(\S+)($|\s[^]+)$/.exec(content);
      if (!match) {
        return `{@${content}}`;
      }
      const [, name, text2] = match;
      const tag = tags.find((it) => it.name === name);
      if (!tag) {
        return handleSoftError(
          new SoftError(
            "ETAGMISSING",
            `No inline tag registered with the name "${name}"`
          )
        );
      }
      try {
        return tag.handler(doc, docs, text2.trim());
      } catch (err) {
        if (err instanceof SoftError) {
          return handleSoftError(err);
        } else {
          throw err;
        }
      }
    }
  );
}

function createMarkdownRenderer(options) {
  const { docs } = options;
  const env = {
    fileInfo: {
      fullPath: "",
      name: "",
      path: "",
      outputName: false
    },
    ids: /* @__PURE__ */ new Set(),
    currentHeading: 1,
    namedExamples: /* @__PURE__ */ new Map()
  };
  let currentDoc = null;
  const getCurrentDocument = () => {
    if (!currentDoc) {
      throw new Error(
        "Internal error: getting current document before rendering has started"
      );
    }
    return currentDoc;
  };
  const included = /* @__PURE__ */ new Map();
  const md = MarkdownIt({
    html: true
  });
  md.use(deflist_plugin);
  md.use(
    codePreview({
      generateExample: options.generateExample,
      getImportedSource: options.getImportedSource
    })
  );
  md.use(headingLevel({ initialLevel: 1 }));
  md.use(
    imageResources({
      addResource: options.addResource
    })
  );
  md.use(
    containerRenderer(
      getCurrentDocument,
      docs,
      env,
      included,
      options.handleSoftError,
      {
        messagebox: { title: {}, ...options.messagebox }
      }
    )
  );
  md.use(paragraph());
  md.use(table());
  md.use(codeInline());
  return {
    render(doc, content) {
      currentDoc = doc;
      included.clear();
      included.set(doc.id, doc.id);
      env.fileInfo = doc.fileInfo;
      env.ids = /* @__PURE__ */ new Set();
      const html = md.render(content, env);
      return processInlineTags(
        inline_tags_default,
        doc,
        docs,
        html,
        options.handleSoftError
      );
    }
  };
}

export { SoftError as S, getFingerprint as a, getOutputFilePath as b, createMarkdownRenderer as c, htmlencode as d, exampleWorkerUrl as e, findTag as f, generateId as g, hasTag as h, isDocumentPage as i, generateExample as j, normalizePath as n, parseInfostring as p };
//# sourceMappingURL=create-markdown-renderer-Ci_APMYD.mjs.map
