// @bun
// src/components/docs/generated/docs-index.generated.ts
var DOCS_INDEX_MANIFEST = "docs-index.manifest.json";

// src/components/docs/generated/loader.ts
import { readFile } from "fs/promises";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
var baseDir = dirname(fileURLToPath(import.meta.url));
var manifestPromise = null;
var docsPromise = null;
var chunkCache = new Map;
function chunkKeyForId(id) {
  if (!id)
    return "_common";
  if (id.includes("/")) {
    const [prefix] = id.split("/");
    return prefix || "_common";
  }
  return "_common";
}
async function loadManifest() {
  if (!manifestPromise) {
    manifestPromise = readFile(join(baseDir, DOCS_INDEX_MANIFEST), "utf8").then((content) => JSON.parse(content));
  }
  return manifestPromise;
}
function resolveContentRoot(manifest) {
  const root = manifest.contentRoot ?? ".";
  return join(baseDir, root);
}
async function loadChunk(fileName) {
  const cached = chunkCache.get(fileName);
  if (cached)
    return cached;
  const load = readFile(join(baseDir, fileName), "utf8").then((content) => JSON.parse(content));
  chunkCache.set(fileName, load);
  return load;
}
async function listGeneratedDocs() {
  if (!docsPromise) {
    docsPromise = (async () => {
      const manifest = await loadManifest();
      const chunks = await Promise.all(manifest.chunks.map((chunk) => loadChunk(chunk.file)));
      return chunks.flat();
    })();
  }
  return docsPromise;
}
async function getDocsIndexManifest() {
  return loadManifest();
}
async function getGeneratedDocById(id) {
  const manifest = await loadManifest();
  const key = chunkKeyForId(id);
  const chunk = manifest.chunks.find((item) => item.key === key);
  if (!chunk)
    return null;
  const entries = await loadChunk(chunk.file);
  const entry = entries.find((doc) => doc.id === id);
  if (!entry || !entry.contentPath)
    return null;
  const contentPath = join(resolveContentRoot(manifest), entry.contentPath);
  try {
    const content = await readFile(contentPath, "utf8");
    return { entry, content };
  } catch {
    return null;
  }
}

// src/components/docs/reference/DocsReferenceIndexClient.tsx
import { useMemo, useState } from "react";
import {
  DataViewList,
  formRenderer,
  StatusChip
} from "@contractspec/lib.design-system";
import { VStack, HStack } from "@contractspec/lib.ui-kit-web/ui/stack";
import { H1, Muted } from "@contractspec/lib.ui-kit-web/ui/typography";
import {
  DocsIndexDataView,
  DocsSearchForm
} from "@contractspec/lib.contracts-spec/docs";
import { jsx, jsxs } from "react/jsx-runtime";
"use client";
function cleanSummary(summary) {
  if (!summary)
    return;
  return summary.replace(/<!--.*?-->/g, "").replace(/[ \t]+/g, " ").replace(/\n{3,}/g, `

`).trim();
}
function normalizeEntry(entry) {
  const summary = cleanSummary(entry.summary);
  const kind = entry.kind ?? (entry.source === "generated" ? "reference" : undefined);
  const visibility = entry.visibility ?? (entry.source === "generated" ? "public" : undefined);
  return {
    ...entry,
    summary,
    kind,
    visibility
  };
}
function matchesQuery(entry, query) {
  if (!query)
    return true;
  const haystack = [entry.title, entry.summary, entry.id, ...entry.tags ?? []].filter(Boolean).join(" ").toLowerCase();
  return haystack.includes(query.toLowerCase());
}
function DocsReferenceIndexClient({
  entries
}) {
  const [filters, setFilters] = useState({});
  const normalizedEntries = useMemo(() => entries.map(normalizeEntry), [entries]);
  const filteredEntries = useMemo(() => {
    const query = filters.query?.trim() ?? "";
    return normalizedEntries.filter((entry) => {
      if (filters.kind && entry.kind !== filters.kind)
        return false;
      if (filters.visibility && entry.visibility !== filters.visibility)
        return false;
      return matchesQuery(entry, query);
    });
  }, [filters, normalizedEntries]);
  const searchForm = formRenderer.render(DocsSearchForm, {
    defaultValues: {
      query: filters.query ?? "",
      visibility: filters.visibility ?? "",
      kind: filters.kind ?? ""
    },
    overrides: {
      onSubmitOverride: (values) => {
        const submitted = values;
        setFilters({
          query: submitted.query ?? "",
          visibility: submitted.visibility ?? "",
          kind: submitted.kind ?? ""
        });
      }
    }
  });
  return /* @__PURE__ */ jsxs(VStack, {
    gap: "xl",
    children: [
      /* @__PURE__ */ jsxs(VStack, {
        gap: "sm",
        children: [
          /* @__PURE__ */ jsx(H1, {
            children: "Contract Reference"
          }),
          /* @__PURE__ */ jsx(Muted, {
            children: "Auto-generated reference docs for operations, events, forms, data views, and presentations."
          })
        ]
      }),
      /* @__PURE__ */ jsx(VStack, {
        gap: "sm",
        className: "max-w-2xl",
        children: searchForm
      }),
      /* @__PURE__ */ jsx(DataViewList, {
        spec: DocsIndexDataView,
        items: filteredEntries,
        emptyState: /* @__PURE__ */ jsx(Muted, {
          children: "No reference docs match your filters."
        }),
        onSelect: (entry) => {
          if (entry.route) {
            window.location.assign(entry.route);
          }
        },
        renderActions: (entry) => {
          return /* @__PURE__ */ jsxs(HStack, {
            gap: "xs",
            justify: "end",
            children: [
              entry.kind ? /* @__PURE__ */ jsx(StatusChip, {
                size: "sm",
                label: entry.kind
              }) : null,
              entry.visibility ? /* @__PURE__ */ jsx(StatusChip, {
                size: "sm",
                label: entry.visibility
              }) : null,
              entry.version ? /* @__PURE__ */ jsx(StatusChip, {
                size: "sm",
                label: `v${entry.version}`
              }) : null
            ]
          });
        }
      })
    ]
  });
}

// src/components/docs/reference/DocsReferenceIndexPage.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
async function DocsReferenceIndexPage() {
  const entries = await listGeneratedDocs();
  return /* @__PURE__ */ jsx2(DocsReferenceIndexClient, {
    entries
  });
}

// src/components/docs/reference/docsMarkdownParser.ts
var METADATA_SECTION = /^##\s+Metadata[\s\S]*?(?=^##\s|^#\s|Z)/m;
function stripMetadata(content) {
  const withoutTitle = content.replace(/^#\s+.*\n+/m, "");
  return withoutTitle.replace(METADATA_SECTION, "");
}
function isBlockStart(line) {
  return /^#{1,4}\s+/.test(line) || /^```/.test(line) || /^\s*[-*]\s+/.test(line) || /^\s*\d+\.\s+/.test(line) || /^>\s+/.test(line);
}
function parseDocsMarkdown(content) {
  const lines = stripMetadata(content).split(/\r?\n/);
  const blocks = [];
  let i = 0;
  while (i < lines.length) {
    const line = lines[i] ?? "";
    if (line.startsWith("<!-- @generated")) {
      i += 1;
      continue;
    }
    const trimmed = line.trim();
    if (!trimmed) {
      i += 1;
      continue;
    }
    if (trimmed.startsWith("```")) {
      const language = trimmed.slice(3).trim();
      const codeLines = [];
      i += 1;
      while (i < lines.length && !(lines[i] ?? "").trim().startsWith("```")) {
        codeLines.push(lines[i] ?? "");
        i += 1;
      }
      i += 1;
      blocks.push({
        type: "code",
        language: language || "text",
        code: codeLines.join(`
`)
      });
      continue;
    }
    if (/^#{1,4}\s+/.test(trimmed)) {
      const level = trimmed.match(/^#{1,4}/)?.[0].length ?? 2;
      blocks.push({
        type: "heading",
        level,
        text: trimmed.replace(/^#{1,4}\s+/, "")
      });
      i += 1;
      continue;
    }
    if (/^>\s+/.test(trimmed)) {
      const quoteLines = [];
      while (i < lines.length && /^>\s+/.test((lines[i] ?? "").trim())) {
        quoteLines.push((lines[i] ?? "").trim().replace(/^>\s+/, ""));
        i += 1;
      }
      blocks.push({ type: "quote", text: quoteLines.join(" ") });
      continue;
    }
    if (/^[-*]\s+/.test(trimmed) || /^\d+\.\s+/.test(trimmed)) {
      const ordered = /^\d+\.\s+/.test(trimmed);
      const items = [];
      while (i < lines.length && isBlockStart((lines[i] ?? "").trim())) {
        const itemLine = (lines[i] ?? "").trim();
        if (ordered && /^\d+\.\s+/.test(itemLine)) {
          items.push(itemLine.replace(/^\d+\.\s+/, ""));
        } else if (!ordered && /^[-*]\s+/.test(itemLine)) {
          items.push(itemLine.replace(/^[-*]\s+/, ""));
        } else {
          break;
        }
        i += 1;
      }
      blocks.push({ type: "list", ordered, items });
      continue;
    }
    const paragraphLines = [];
    while (i < lines.length && !isBlockStart((lines[i] ?? "").trim())) {
      const paragraphLine = (lines[i] ?? "").trim();
      if (!paragraphLine)
        break;
      paragraphLines.push(paragraphLine);
      i += 1;
    }
    blocks.push({ type: "paragraph", text: paragraphLines.join(" ") });
  }
  return blocks;
}

// src/components/docs/reference/DocsMarkdownContent.tsx
import { CodeBlock } from "@contractspec/lib.design-system";
import { VStack as VStack2, HStack as HStack2 } from "@contractspec/lib.ui-kit-web/ui/stack";
import {
  BlockQuote,
  H2,
  H3,
  H4,
  Muted as Muted2,
  P
} from "@contractspec/lib.ui-kit-web/ui/typography";
import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
"use client";
var CODE_LANGUAGES = new Set([
  "typescript",
  "tsx",
  "javascript",
  "jsx",
  "bash",
  "shell",
  "json",
  "yaml",
  "graphql",
  "sql",
  "python",
  "go",
  "rust",
  "css",
  "scss",
  "html",
  "markdown",
  "text"
]);
function toCodeLanguage(language) {
  if (!language)
    return "text";
  const normalized = language.toLowerCase();
  return CODE_LANGUAGES.has(normalized) ? normalized : "text";
}
function renderHeading(level, text) {
  if (level <= 2)
    return /* @__PURE__ */ jsx3(H2, {
      children: text
    });
  if (level === 3)
    return /* @__PURE__ */ jsx3(H3, {
      children: text
    });
  return /* @__PURE__ */ jsx3(H4, {
    children: text
  });
}
function DocsMarkdownContent({ content }) {
  const blocks = parseDocsMarkdown(content);
  if (!blocks.length) {
    return /* @__PURE__ */ jsx3(Muted2, {
      children: "No reference content available."
    });
  }
  return /* @__PURE__ */ jsx3(VStack2, {
    gap: "md",
    children: blocks.map((block, index) => {
      switch (block.type) {
        case "heading":
          return /* @__PURE__ */ jsx3(VStack2, {
            children: renderHeading(block.level, block.text)
          }, index);
        case "paragraph":
          return /* @__PURE__ */ jsx3(P, {
            children: block.text
          }, index);
        case "quote":
          return /* @__PURE__ */ jsx3(BlockQuote, {
            children: block.text
          }, index);
        case "code":
          return /* @__PURE__ */ jsx3(CodeBlock, {
            language: toCodeLanguage(block.language),
            code: block.code
          }, index);
        case "list":
          return /* @__PURE__ */ jsx3(VStack2, {
            gap: "xs",
            children: block.items.map((item, itemIndex) => /* @__PURE__ */ jsxs2(HStack2, {
              gap: "sm",
              align: "start",
              children: [
                /* @__PURE__ */ jsx3(Muted2, {
                  children: block.ordered ? `${itemIndex + 1}.` : "\u2022"
                }),
                /* @__PURE__ */ jsx3(P, {
                  className: "leading-relaxed",
                  children: item
                })
              ]
            }, itemIndex))
          }, index);
        default:
          return null;
      }
    })
  });
}

// src/components/docs/reference/DocsReferenceContent.tsx
import { DataViewRenderer } from "@contractspec/lib.design-system";
import { VStack as VStack3 } from "@contractspec/lib.ui-kit-web/ui/stack";
import { ContractReferenceDataView } from "@contractspec/lib.contracts-spec/docs";
import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
"use client";
function extractMeta(content, label) {
  const match = content.match(new RegExp(`- \\*\\*${label}\\*\\*: (.+)`, "i"));
  return match?.[1]?.trim();
}
function cleanSummary2(summary) {
  if (!summary)
    return;
  return summary.replace(/<!--.*?-->/g, "").replace(/[ \t]+/g, " ").replace(/\n{3,}/g, `

`).trim();
}
function DocsReferenceContent({
  entry,
  content
}) {
  const summary = cleanSummary2(entry.summary);
  const type = extractMeta(content, "Type");
  const version = extractMeta(content, "Version") ?? entry.version;
  const tags = extractMeta(content, "Tags")?.split(",").map((tag) => tag.trim()).filter(Boolean);
  const owners = extractMeta(content, "Owners")?.split(",").map((owner) => owner.trim()).filter(Boolean);
  const stability = extractMeta(content, "Stability") ?? entry.visibility;
  const referenceItem = {
    reference: {
      key: entry.title ?? entry.id,
      version,
      type,
      title: entry.title ?? entry.id,
      description: summary,
      tags: tags ?? entry.tags,
      owners: owners ?? entry.owners,
      stability
    }
  };
  const detailSpec = {
    ...ContractReferenceDataView,
    meta: {
      ...ContractReferenceDataView.meta,
      title: entry.title ?? ContractReferenceDataView.meta.title,
      description: summary ?? ContractReferenceDataView.meta.description
    }
  };
  return /* @__PURE__ */ jsxs3(VStack3, {
    gap: "xl",
    children: [
      /* @__PURE__ */ jsx4(DataViewRenderer, {
        spec: detailSpec,
        item: referenceItem
      }),
      /* @__PURE__ */ jsx4(DocsMarkdownContent, {
        content
      })
    ]
  });
}

// src/components/docs/reference/DocsReferencePage.tsx
import { jsx as jsx5 } from "react/jsx-runtime";
function DocsReferencePage({ entry, content }) {
  return /* @__PURE__ */ jsx5(DocsReferenceContent, {
    entry,
    content
  });
}
export {
  DocsReferencePage,
  DocsReferenceIndexPage
};
