'use strict';

var chunkOLISEQHS_cjs = require('./chunk-OLISEQHS.cjs');
var consola2 = require('consola');
var React = require('react');
var hooks = require('@djangocfg/ui-core/hooks');
var openapiSampler = require('openapi-sampler');
var jsxRuntime = require('react/jsx-runtime');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var consola2__default = /*#__PURE__*/_interopDefault(consola2);
var React__default = /*#__PURE__*/_interopDefault(React);

// src/tools/OpenapiViewer/utils/apiKeyManager.ts
function findApiKeyById(apiKeys, keyId) {
  return apiKeys.find((key) => key.id === keyId) || null;
}
chunkOLISEQHS_cjs.__name(findApiKeyById, "findApiKeyById");

// src/tools/OpenapiViewer/utils/codeSamples.ts
var CODE_SAMPLE_TARGETS = [
  { id: "curl", label: "cURL", prism: "bash" },
  { id: "fetch", label: "JavaScript", prism: "javascript" },
  { id: "axios", label: "Node (axios)", prism: "javascript" },
  { id: "python", label: "Python", prism: "python" },
  { id: "go", label: "Go", prism: "go" },
  { id: "php", label: "PHP", prism: "php" },
  { id: "ruby", label: "Ruby", prism: "ruby" },
  { id: "java", label: "Java", prism: "java" }
];
function goRawString(s) {
  return s.includes("`") ? JSON.stringify(s) : `\`${s}\``;
}
chunkOLISEQHS_cjs.__name(goRawString, "goRawString");
function rubyHeredoc(s) {
  return `<<~JSON
${s}
JSON`;
}
chunkOLISEQHS_cjs.__name(rubyHeredoc, "rubyHeredoc");
function phpHeredoc(s) {
  return `<<<JSON
${s}
JSON`;
}
chunkOLISEQHS_cjs.__name(phpHeredoc, "phpHeredoc");
function javaTextBlock(s) {
  if (s.includes('"""')) return JSON.stringify(s);
  return `"""
${s}
"""`;
}
chunkOLISEQHS_cjs.__name(javaTextBlock, "javaTextBlock");
function fullUrl(har) {
  if (!har.queryString.length) return har.url;
  const qs = har.queryString.map((p) => `${encodeURIComponent(p.name)}=${encodeURIComponent(p.value)}`).join("&");
  const sep = har.url.includes("?") ? "&" : "?";
  return `${har.url}${sep}${qs}`;
}
chunkOLISEQHS_cjs.__name(fullUrl, "fullUrl");
function shellEscape(value) {
  return `'${value.replace(/'/g, `'\\''`)}'`;
}
chunkOLISEQHS_cjs.__name(shellEscape, "shellEscape");
function renderCurl(har) {
  const lines = [`curl -X ${har.method} ${shellEscape(fullUrl(har))}`];
  for (const h of har.headers) {
    lines.push(`  -H ${shellEscape(`${h.name}: ${h.value}`)}`);
  }
  if (har.postData?.text) {
    lines.push(`  -d ${shellEscape(har.postData.text)}`);
  }
  return lines.join(" \\\n");
}
chunkOLISEQHS_cjs.__name(renderCurl, "renderCurl");
function jsHeadersLiteral(har, indent) {
  if (!har.headers.length) return "{}";
  const entries = har.headers.map((h) => `${indent}  ${JSON.stringify(h.name)}: ${JSON.stringify(h.value)}`).join(",\n");
  return `{
${entries},
${indent}}`;
}
chunkOLISEQHS_cjs.__name(jsHeadersLiteral, "jsHeadersLiteral");
function jsTemplateLiteral(s) {
  if (/[`$]/.test(s)) return JSON.stringify(s);
  return `\`${s}\``;
}
chunkOLISEQHS_cjs.__name(jsTemplateLiteral, "jsTemplateLiteral");
function renderFetch(har) {
  const url = fullUrl(har);
  const options = [`  method: ${JSON.stringify(har.method)}`];
  if (har.headers.length) {
    options.push(`  headers: ${jsHeadersLiteral(har, "  ")}`);
  }
  if (har.postData?.text) {
    options.push(`  body: ${jsTemplateLiteral(har.postData.text)}`);
  }
  return `const response = await fetch(${JSON.stringify(url)}, {
${options.join(",\n")},
});
const data = await response.json();`;
}
chunkOLISEQHS_cjs.__name(renderFetch, "renderFetch");
function renderAxios(har) {
  const url = fullUrl(har);
  const config = [
    `  method: ${JSON.stringify(har.method.toLowerCase())}`,
    `  url: ${JSON.stringify(url)}`
  ];
  if (har.headers.length) {
    config.push(`  headers: ${jsHeadersLiteral(har, "  ")}`);
  }
  if (har.postData?.text) {
    config.push(`  data: ${har.postData.text}`);
  }
  return `import axios from 'axios';

const { data } = await axios({
${config.join(",\n")},
});`;
}
chunkOLISEQHS_cjs.__name(renderAxios, "renderAxios");
function renderPython(har) {
  const lines = [`import requests`, ``];
  lines.push(`url = ${JSON.stringify(fullUrl(har))}`);
  if (har.headers.length) {
    const headerEntries = har.headers.map((h) => `    ${JSON.stringify(h.name)}: ${JSON.stringify(h.value)}`).join(",\n");
    lines.push(`headers = {
${headerEntries},
}`);
  }
  if (har.postData?.text) {
    lines.push(`payload = ${har.postData.text}`);
  }
  const args = [`url`];
  if (har.headers.length) args.push(`headers=headers`);
  if (har.postData?.text) args.push(`json=payload`);
  lines.push(``, `response = requests.${har.method.toLowerCase()}(${args.join(", ")})`);
  lines.push(`data = response.json()`);
  return lines.join("\n");
}
chunkOLISEQHS_cjs.__name(renderPython, "renderPython");
function renderGo(har) {
  const url = fullUrl(har);
  const lines = [
    `package main`,
    ``,
    `import (`,
    `    "fmt"`,
    `    "io"`
  ];
  if (har.postData?.text) lines.push(`    "strings"`);
  lines.push(`    "net/http"`);
  lines.push(`)`, ``, `func main() {`);
  if (har.postData?.text) {
    lines.push(`    payload := strings.NewReader(${goRawString(har.postData.text)})`);
    lines.push(`    req, _ := http.NewRequest(${JSON.stringify(har.method)}, ${JSON.stringify(url)}, payload)`);
  } else {
    lines.push(`    req, _ := http.NewRequest(${JSON.stringify(har.method)}, ${JSON.stringify(url)}, nil)`);
  }
  for (const h of har.headers) {
    lines.push(`    req.Header.Add(${JSON.stringify(h.name)}, ${JSON.stringify(h.value)})`);
  }
  lines.push(
    ``,
    `    res, _ := http.DefaultClient.Do(req)`,
    `    defer res.Body.Close()`,
    `    body, _ := io.ReadAll(res.Body)`,
    `    fmt.Println(string(body))`,
    `}`
  );
  return lines.join("\n");
}
chunkOLISEQHS_cjs.__name(renderGo, "renderGo");
function renderPhp(har) {
  const lines = [`<?php`, ``, `$curl = curl_init();`, ``, `curl_setopt_array($curl, [`];
  lines.push(`    CURLOPT_URL => ${JSON.stringify(fullUrl(har))},`);
  lines.push(`    CURLOPT_RETURNTRANSFER => true,`);
  lines.push(`    CURLOPT_CUSTOMREQUEST => ${JSON.stringify(har.method)},`);
  if (har.postData?.text) {
    lines.push(`    CURLOPT_POSTFIELDS => ${phpHeredoc(har.postData.text)},`);
  }
  if (har.headers.length) {
    const headerList = har.headers.map((h) => `        ${JSON.stringify(`${h.name}: ${h.value}`)}`).join(",\n");
    lines.push(`    CURLOPT_HTTPHEADER => [
${headerList},
    ],`);
  }
  lines.push(`]);`, ``, `$response = curl_exec($curl);`, `curl_close($curl);`, `echo $response;`);
  return lines.join("\n");
}
chunkOLISEQHS_cjs.__name(renderPhp, "renderPhp");
function renderRuby(har) {
  const lines = [
    `require 'net/http'`,
    `require 'uri'`,
    `require 'json'`,
    ``,
    `uri = URI(${JSON.stringify(fullUrl(har))})`,
    `http = Net::HTTP.new(uri.host, uri.port)`,
    `http.use_ssl = uri.scheme == 'https'`,
    ``
  ];
  const methodClass = har.method.charAt(0) + har.method.slice(1).toLowerCase();
  lines.push(`request = Net::HTTP::${methodClass}.new(uri)`);
  for (const h of har.headers) {
    lines.push(`request[${JSON.stringify(h.name)}] = ${JSON.stringify(h.value)}`);
  }
  if (har.postData?.text) {
    lines.push(`request.body = ${rubyHeredoc(har.postData.text)}`);
  }
  lines.push(``, `response = http.request(request)`, `puts response.body`);
  return lines.join("\n");
}
chunkOLISEQHS_cjs.__name(renderRuby, "renderRuby");
function renderJava(har) {
  const lines = [
    `OkHttpClient client = new OkHttpClient();`,
    ``
  ];
  if (har.postData?.text) {
    lines.push(
      `MediaType mediaType = MediaType.parse("application/json");`,
      `RequestBody body = RequestBody.create(mediaType, ${javaTextBlock(har.postData.text)});`,
      ``
    );
  }
  lines.push(`Request request = new Request.Builder()`);
  lines.push(`  .url(${JSON.stringify(fullUrl(har))})`);
  if (har.postData?.text) {
    lines.push(`  .method(${JSON.stringify(har.method)}, body)`);
  } else {
    lines.push(`  .method(${JSON.stringify(har.method)}, null)`);
  }
  for (const h of har.headers) {
    lines.push(`  .addHeader(${JSON.stringify(h.name)}, ${JSON.stringify(h.value)})`);
  }
  lines.push(`  .build();`, ``, `Response response = client.newCall(request).execute();`);
  return lines.join("\n");
}
chunkOLISEQHS_cjs.__name(renderJava, "renderJava");
var RENDERERS = {
  curl: renderCurl,
  fetch: renderFetch,
  axios: renderAxios,
  python: renderPython,
  go: renderGo,
  php: renderPhp,
  ruby: renderRuby,
  java: renderJava
};
function renderSnippet(har, targetId) {
  const renderer = RENDERERS[targetId];
  if (!renderer) return null;
  try {
    return renderer(har);
  } catch {
    return null;
  }
}
chunkOLISEQHS_cjs.__name(renderSnippet, "renderSnippet");

// src/tools/OpenapiViewer/utils/operationToHar.ts
function buildUrl(endpoint, parameters, baseUrl) {
  const pathParamNames = new Set(
    (endpoint.parameters ?? []).filter((p) => endpoint.path.includes(`{${p.name}}`)).map((p) => p.name)
  );
  let path = endpoint.path;
  for (const name of pathParamNames) {
    const value = parameters[name];
    if (value === void 0 || value === "") continue;
    path = path.replaceAll(`{${name}}`, encodeURIComponent(value));
  }
  const queryString = [];
  for (const param of endpoint.parameters ?? []) {
    if (pathParamNames.has(param.name)) continue;
    const value = parameters[param.name];
    if (value === void 0 || value === "") continue;
    queryString.push({ name: param.name, value });
  }
  const url = baseUrl ? `${baseUrl.replace(/\/+$/, "")}${path.startsWith("/") ? path : `/${path}`}` : path;
  return { url, queryString };
}
chunkOLISEQHS_cjs.__name(buildUrl, "buildUrl");
function buildHarRequest(input) {
  const { endpoint, body, parameters = {}, headers = {}, baseUrl } = input;
  const { url, queryString } = buildUrl(endpoint, parameters, baseUrl);
  const hasBody = Boolean(body && body.trim().length > 0);
  const bodyMime = hasBody ? "application/json" : void 0;
  const mergedHeaders = {};
  if (hasBody && bodyMime) mergedHeaders["Content-Type"] = bodyMime;
  mergedHeaders["Accept"] = "application/json";
  for (const [k, v] of Object.entries(headers)) {
    if (v === void 0 || v === "") continue;
    mergedHeaders[k] = v;
  }
  const har = {
    method: endpoint.method.toUpperCase(),
    url,
    httpVersion: "HTTP/1.1",
    headers: Object.entries(mergedHeaders).map(([name, value]) => ({ name, value })),
    queryString,
    cookies: [],
    headersSize: -1,
    bodySize: hasBody ? new TextEncoder().encode(body).length : 0
  };
  if (hasBody && bodyMime) {
    har.postData = { mimeType: bodyMime, text: body };
  }
  return har;
}
chunkOLISEQHS_cjs.__name(buildHarRequest, "buildHarRequest");

// src/tools/OpenapiViewer/utils/versionManager.ts
var API_VERSIONS = [
  {
    id: "v1",
    name: "v1",
    description: "Current stable version",
    isDefault: true
  }
];
var detectEndpointVersion = /* @__PURE__ */ chunkOLISEQHS_cjs.__name((path) => {
  const versionMatch = path.match(/\/api\/[^/]+\/(v\d+)\//);
  if (versionMatch && versionMatch[1]) {
    return versionMatch[1];
  }
  return "v1";
}, "detectEndpointVersion");
var isEndpointInVersion = /* @__PURE__ */ chunkOLISEQHS_cjs.__name((endpoint, version) => {
  const endpointVersion = detectEndpointVersion(endpoint.path);
  return endpointVersion === version;
}, "isEndpointInVersion");
var deduplicateEndpoints = /* @__PURE__ */ chunkOLISEQHS_cjs.__name((endpoints, preferredVersion) => {
  const endpointMap = /* @__PURE__ */ new Map();
  const groupedEndpoints = /* @__PURE__ */ new Map();
  endpoints.forEach((endpoint) => {
    const normalizedPath = normalizeEndpointPath(endpoint.path);
    if (!groupedEndpoints.has(normalizedPath)) {
      groupedEndpoints.set(normalizedPath, []);
    }
    groupedEndpoints.get(normalizedPath).push(endpoint);
  });
  groupedEndpoints.forEach((endpointGroup, normalizedPath) => {
    let selectedEndpoint = null;
    const versionEndpoint = endpointGroup.find((ep) => isEndpointInVersion(ep, preferredVersion));
    if (versionEndpoint) {
      selectedEndpoint = versionEndpoint;
    } else if (endpointGroup.length > 0) {
      selectedEndpoint = endpointGroup[0] || null;
    }
    if (selectedEndpoint) {
      endpointMap.set(normalizedPath, selectedEndpoint);
    }
  });
  return Array.from(endpointMap.values());
}, "deduplicateEndpoints");
var normalizeEndpointPath = /* @__PURE__ */ chunkOLISEQHS_cjs.__name((path) => {
  return path.replace(/\/v\d+\//, "/");
}, "normalizeEndpointPath");
var getDefaultVersion = /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => {
  const defaultVersion = API_VERSIONS.find((v) => v.isDefault);
  if (defaultVersion) {
    return defaultVersion;
  }
  if (API_VERSIONS.length > 0 && API_VERSIONS[0]) {
    return API_VERSIONS[0];
  }
  throw new Error("No API versions defined");
}, "getDefaultVersion");

// src/tools/OpenapiViewer/utils/formatters.ts
var isValidJson = /* @__PURE__ */ chunkOLISEQHS_cjs.__name((str) => {
  if (!str || typeof str !== "string") return false;
  try {
    JSON.parse(str);
    return true;
  } catch {
    return false;
  }
}, "isValidJson");
var parseRequestHeaders = /* @__PURE__ */ chunkOLISEQHS_cjs.__name((headersString) => {
  if (!headersString || typeof headersString !== "string") {
    return { "Content-Type": "application/json" };
  }
  try {
    const parsed = JSON.parse(headersString);
    return typeof parsed === "object" && parsed !== null ? parsed : { "Content-Type": "application/json" };
  } catch {
    return { "Content-Type": "application/json" };
  }
}, "parseRequestHeaders");
function sampleSchema(schema, options = {}, spec) {
  if (!schema) return null;
  try {
    return openapiSampler.sample(schema, options, spec);
  } catch (err) {
    consola2__default.default.warn("[OpenapiViewer] sampleSchema failed:", err, { schema });
    return null;
  }
}
chunkOLISEQHS_cjs.__name(sampleSchema, "sampleSchema");
function sampleSchemaJson(schema, options = {}, spec) {
  const value = sampleSchema(schema, options, spec);
  if (value === null || value === void 0) return void 0;
  try {
    return JSON.stringify(value, null, 2);
  } catch {
    return void 0;
  }
}
chunkOLISEQHS_cjs.__name(sampleSchemaJson, "sampleSchemaJson");

// src/tools/OpenapiViewer/utils/url.ts
var PATH_PARAM_RE = /\{([^{}]+)\}/g;
function extractPathPlaceholders(template) {
  const seen = /* @__PURE__ */ new Set();
  const out = [];
  for (const match of template.matchAll(PATH_PARAM_RE)) {
    const name = match[1];
    if (!seen.has(name)) {
      seen.add(name);
      out.push(name);
    }
  }
  return out;
}
chunkOLISEQHS_cjs.__name(extractPathPlaceholders, "extractPathPlaceholders");
function substitutePath(template, values) {
  return template.replace(PATH_PARAM_RE, (whole, name) => {
    const v = values[name];
    return v && v.trim() !== "" ? encodeURIComponent(v) : whole;
  });
}
chunkOLISEQHS_cjs.__name(substitutePath, "substitutePath");
function unfilledPlaceholders(template, values) {
  return extractPathPlaceholders(template).filter(
    (name) => !(values[name] ?? "").trim()
  );
}
chunkOLISEQHS_cjs.__name(unfilledPlaceholders, "unfilledPlaceholders");
function appendQuery(url, values, pathTemplate) {
  const pathNames = new Set(extractPathPlaceholders(pathTemplate));
  const queryEntries = Object.entries(values).filter(
    ([name, value]) => !pathNames.has(name) && value && value.trim() !== ""
  );
  if (queryEntries.length === 0) return url;
  const [base, existingQuery = ""] = url.split("?", 2);
  const params = new URLSearchParams(existingQuery);
  for (const [k, v] of queryEntries) params.set(k, v);
  const qs = params.toString();
  return qs ? `${base}?${qs}` : base ?? url;
}
chunkOLISEQHS_cjs.__name(appendQuery, "appendQuery");
function resolveAbsolute(url) {
  if (!url) return url;
  if (/^https?:\/\//i.test(url)) return url;
  if (typeof window === "undefined") return url;
  if (url.startsWith("//")) return `${window.location.protocol}${url}`;
  if (url.startsWith("/")) return `${window.location.origin}${url}`;
  return url;
}
chunkOLISEQHS_cjs.__name(resolveAbsolute, "resolveAbsolute");
function relativePath(url) {
  try {
    return new URL(url).pathname.replace(/%7B/gi, "{").replace(/%7D/gi, "}");
  } catch {
    return url;
  }
}
chunkOLISEQHS_cjs.__name(relativePath, "relativePath");
function joinUrl(...parts) {
  const filtered = parts.filter((p) => p !== void 0 && p !== null && p !== "");
  return filtered.map((p, i) => {
    const s = String(p);
    if (i === 0) return s.replace(/\/+$/, "");
    const stripped = s.replace(/^\/+/, "");
    if (i === filtered.length - 1) return stripped;
    return stripped.replace(/\/+$/, "");
  }).filter((p) => p !== "").join("/");
}
chunkOLISEQHS_cjs.__name(joinUrl, "joinUrl");
function resolveBaseUrl(sources) {
  return sources.schemaSource || sources.config || sources.fromServers || "";
}
chunkOLISEQHS_cjs.__name(resolveBaseUrl, "resolveBaseUrl");
var _UrlBuilder = class _UrlBuilder {
  constructor(endpoint, parameters) {
    this.endpoint = endpoint;
    this.parameters = parameters;
  }
  /** What ``fetch()`` receives: substituted path + query string. Origin
   *  is whatever the endpoint template already had (relative paths
   *  stay relative so the browser resolves them against the page). */
  build() {
    const substituted = substitutePath(this.endpoint.path, this.parameters);
    return appendQuery(substituted, this.parameters, this.endpoint.path);
  }
  /** Same as ``build()`` but guaranteed absolute — for curl snippets
   *  and anywhere the URL leaves the browser context. */
  buildAbsolute() {
    return resolveAbsolute(this.build());
  }
  /** Names of required path/query params still empty. */
  missingRequired() {
    if (!this.endpoint.parameters) return [];
    return this.endpoint.parameters.filter((p) => p.required && !(this.parameters[p.name] ?? "").trim()).map((p) => p.name);
  }
  /** Placeholders in the template with no matching value. Usually a
   *  superset of ``missingRequired`` — catches schemas that forgot
   *  to flag a path param as required. */
  unfilledPlaceholders() {
    return unfilledPlaceholders(this.endpoint.path, this.parameters);
  }
};
chunkOLISEQHS_cjs.__name(_UrlBuilder, "UrlBuilder");
var UrlBuilder = _UrlBuilder;

// src/tools/OpenapiViewer/utils/schemaExport.ts
function dereferenceSchema(schema, maxDepth = 10) {
  const root = schema;
  function resolveRef(ref) {
    if (!ref.startsWith("#/")) return null;
    const parts = ref.slice(2).split("/");
    let node = root;
    for (const part of parts) {
      if (node && typeof node === "object" && part in node) {
        node = node[part];
      } else {
        return null;
      }
    }
    return node;
  }
  chunkOLISEQHS_cjs.__name(resolveRef, "resolveRef");
  function walk(value, depth) {
    if (depth > maxDepth) return value;
    if (Array.isArray(value)) return value.map((v) => walk(v, depth + 1));
    if (value && typeof value === "object") {
      const obj = value;
      if (typeof obj.$ref === "string") {
        const resolved = resolveRef(obj.$ref);
        if (resolved === null) return obj;
        return walk(resolved, depth + 1);
      }
      const out = {};
      for (const [k, v] of Object.entries(obj)) out[k] = walk(v, depth + 1);
      return out;
    }
    return value;
  }
  chunkOLISEQHS_cjs.__name(walk, "walk");
  return walk(schema, 0);
}
chunkOLISEQHS_cjs.__name(dereferenceSchema, "dereferenceSchema");
var NOISY_KEYS = /* @__PURE__ */ new Set(["xml", "example", "examples", "externalDocs"]);
var MAX_DESCRIPTION_LEN = 500;
function pruneForCompact(value) {
  if (Array.isArray(value)) return value.map(pruneForCompact);
  if (value && typeof value === "object") {
    const out = {};
    for (const [k, v] of Object.entries(value)) {
      if (NOISY_KEYS.has(k)) continue;
      if (k === "description" && typeof v === "string" && v.length > MAX_DESCRIPTION_LEN) {
        out[k] = v.slice(0, MAX_DESCRIPTION_LEN).trimEnd() + "\u2026";
        continue;
      }
      out[k] = pruneForCompact(v);
    }
    return out;
  }
  return value;
}
chunkOLISEQHS_cjs.__name(pruneForCompact, "pruneForCompact");
function withResolvedBaseUrl(schema, baseUrl) {
  if (!baseUrl) return schema;
  return { ...schema, servers: [{ url: baseUrl }] };
}
chunkOLISEQHS_cjs.__name(withResolvedBaseUrl, "withResolvedBaseUrl");
function toRawJson(schema, baseUrl) {
  return JSON.stringify(withResolvedBaseUrl(schema, baseUrl), null, 2);
}
chunkOLISEQHS_cjs.__name(toRawJson, "toRawJson");
function toCompactJson(schema, baseUrl) {
  const resolved = dereferenceSchema(withResolvedBaseUrl(schema, baseUrl));
  const pruned = pruneForCompact(resolved);
  return JSON.stringify(pruned);
}
chunkOLISEQHS_cjs.__name(toCompactJson, "toCompactJson");
function endpointToMarkdown(ep) {
  const lines = [];
  lines.push(`### ${ep.method} ${ep.path}`);
  if (ep.description) lines.push(ep.description);
  const pathParams = ep.parameters?.filter((p) => ep.path.includes(`{${p.name}}`)) ?? [];
  const queryParams = ep.parameters?.filter((p) => !ep.path.includes(`{${p.name}}`)) ?? [];
  if (pathParams.length > 0) {
    lines.push("", "**Path parameters**");
    for (const p of pathParams) {
      const req = p.required ? " (required)" : "";
      const desc = p.description ? ` \u2014 ${p.description}` : "";
      lines.push(`- \`${p.name}\`: ${p.type}${req}${desc}`);
    }
  }
  if (queryParams.length > 0) {
    lines.push("", "**Query parameters**");
    for (const p of queryParams) {
      const req = p.required ? " (required)" : "";
      const desc = p.description ? ` \u2014 ${p.description}` : "";
      lines.push(`- \`${p.name}\`: ${p.type}${req}${desc}`);
    }
  }
  if (ep.requestBody) {
    const desc = ep.requestBody.description ? ` \u2014 ${ep.requestBody.description}` : "";
    lines.push("", `**Request body:** ${ep.requestBody.type}${desc}`);
  }
  if (ep.responses && ep.responses.length > 0) {
    lines.push("", "**Responses**");
    for (const r of ep.responses) {
      lines.push(`- \`${r.code}\` \u2014 ${r.description}`);
    }
  }
  return lines.join("\n");
}
chunkOLISEQHS_cjs.__name(endpointToMarkdown, "endpointToMarkdown");
function toMarkdown(schema, endpoints, baseUrl) {
  const lines = [];
  const info = schema.info;
  const resolvedBase = resolveBaseUrl({
    config: baseUrl,
    fromServers: schema.servers?.[0]?.url
  });
  lines.push(`# ${info?.title ?? "API"}${info?.version ? ` (v${info.version})` : ""}`);
  if (resolvedBase) lines.push("", `**Base URL:** \`${resolvedBase}\``);
  if (info?.description) lines.push("", info.description.trim());
  const grouped = /* @__PURE__ */ new Map();
  for (const ep of endpoints) {
    const arr = grouped.get(ep.category) ?? [];
    arr.push(ep);
    grouped.set(ep.category, arr);
  }
  const categories = Array.from(grouped.keys()).sort((a, b) => {
    if (a === "Other") return 1;
    if (b === "Other") return -1;
    return a.localeCompare(b);
  });
  for (const category of categories) {
    lines.push("", `## ${category}`);
    const list = grouped.get(category);
    for (const ep of list) {
      const displayPath = relativePath(ep.path);
      const sub = endpointToMarkdown({ ...ep, path: displayPath });
      lines.push("", sub);
    }
  }
  return lines.join("\n");
}
chunkOLISEQHS_cjs.__name(toMarkdown, "toMarkdown");
function formatBytes(s) {
  const bytes = new Blob([s]).size;
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
}
chunkOLISEQHS_cjs.__name(formatBytes, "formatBytes");
var AUTH_KEY_STORAGE = "openapi-playground:auth:apiKeyId";
var AUTH_BEARER_STORAGE = "openapi-playground:auth:bearer";
var createInitialState = /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => ({
  currentStep: "endpoints",
  steps: ["endpoints", "request", "response"],
  selectedEndpoint: null,
  selectedCategory: "All",
  searchTerm: "",
  selectedVersion: getDefaultVersion().id,
  requestUrl: "",
  requestMethod: "GET",
  requestHeaders: '{\n  "Content-Type": "application/json"\n}',
  requestBody: "",
  selectedApiKey: null,
  manualApiToken: "",
  parameters: {},
  response: null,
  loading: false,
  sidebarOpen: false,
  activeSchemaId: null
}), "createInitialState");
function reducer(state, action) {
  switch (action.type) {
    case "SET_STEP":
      return { ...state, currentStep: action.step };
    case "NEXT_STEP": {
      const i = state.steps.indexOf(state.currentStep);
      return i < state.steps.length - 1 ? { ...state, currentStep: state.steps[i + 1] } : state;
    }
    case "PREV_STEP": {
      const i = state.steps.indexOf(state.currentStep);
      return i > 0 ? { ...state, currentStep: state.steps[i - 1] } : state;
    }
    case "SELECT_ENDPOINT": {
      if (!action.endpoint) return { ...state, selectedEndpoint: null };
      const same = state.selectedEndpoint?.method === action.endpoint.method && state.selectedEndpoint?.path === action.endpoint.path;
      const exampleBody = action.endpoint.requestBody?.example ?? "";
      return {
        ...state,
        selectedEndpoint: action.endpoint,
        requestMethod: action.endpoint.method,
        requestUrl: action.endpoint.path,
        parameters: same ? state.parameters : {},
        requestBody: same ? state.requestBody : exampleBody,
        // Switching to a different endpoint: the previous response no
        // longer belongs here. Clear it so the playground panel collapses
        // back to single-column until the user sends a new request.
        response: same ? state.response : null,
        currentStep: "request"
      };
    }
    case "SET_CATEGORY":
      return { ...state, selectedCategory: action.category };
    case "SET_SEARCH":
      return { ...state, searchTerm: action.term };
    case "SET_VERSION":
      return { ...state, selectedVersion: action.version };
    case "SET_REQUEST_URL":
      return { ...state, requestUrl: action.url };
    case "SET_REQUEST_METHOD":
      return { ...state, requestMethod: action.method };
    case "SET_REQUEST_HEADERS":
      return { ...state, requestHeaders: action.headers };
    case "SET_REQUEST_BODY":
      return { ...state, requestBody: action.body };
    case "SET_API_KEY":
      return { ...state, selectedApiKey: action.apiKeyId };
    case "SET_MANUAL_TOKEN":
      return { ...state, manualApiToken: action.token };
    case "SET_PARAMETERS":
      return { ...state, parameters: action.parameters };
    case "SET_RESPONSE":
      return { ...state, response: action.response };
    case "SET_LOADING":
      return { ...state, loading: action.loading };
    case "REQUEST_START":
      return { ...state, loading: true, response: null };
    case "REQUEST_SUCCESS":
      return { ...state, loading: false, response: action.response, currentStep: "response" };
    case "REQUEST_ERROR":
      return { ...state, loading: false, response: action.response };
    case "SET_SIDEBAR":
      return { ...state, sidebarOpen: action.open };
    case "SET_ACTIVE_SCHEMA_ID":
      return { ...state, activeSchemaId: action.id };
    case "SYNC_API_KEY_HEADER":
      return { ...state, requestHeaders: action.headers };
    case "CLEAR_API_KEY_SELECTION":
      return { ...state, selectedApiKey: null };
    case "SYNC_URL":
      return { ...state, requestUrl: action.url };
    case "RESET":
      return createInitialState();
    default:
      return state;
  }
}
chunkOLISEQHS_cjs.__name(reducer, "reducer");
var PlaygroundContext = React.createContext(void 0);
var usePlaygroundContext = /* @__PURE__ */ chunkOLISEQHS_cjs.__name(() => {
  const context = React.useContext(PlaygroundContext);
  if (!context) throw new Error("usePlaygroundContext must be used within a PlaygroundProvider");
  return context;
}, "usePlaygroundContext");
var PlaygroundProvider = /* @__PURE__ */ chunkOLISEQHS_cjs.__name(({ children, config }) => {
  const [state, dispatch] = React.useReducer(reducer, void 0, createInitialState);
  const abortControllerRef = React.useRef(null);
  const apiKeys = React__default.default.useMemo(
    () => config.apiKeys ?? [],
    [config.apiKeys]
  );
  const isLoadingApiKeys = config.apiKeysLoading ?? false;
  const [storedApiKeyId, setStoredApiKeyId] = hooks.useSessionStorage(
    AUTH_KEY_STORAGE,
    null
  );
  const [storedBearer, setStoredBearer] = hooks.useSessionStorage(
    AUTH_BEARER_STORAGE,
    ""
  );
  const hasHydratedAuthRef = React.useRef(false);
  React.useEffect(() => {
    if (hasHydratedAuthRef.current) return;
    hasHydratedAuthRef.current = true;
    if (storedApiKeyId) dispatch({ type: "SET_API_KEY", apiKeyId: storedApiKeyId });
    if (storedBearer) dispatch({ type: "SET_MANUAL_TOKEN", token: storedBearer });
  }, []);
  React.useEffect(() => {
    if (!hasHydratedAuthRef.current) return;
    setStoredApiKeyId(state.selectedApiKey);
  }, [state.selectedApiKey, setStoredApiKeyId]);
  React.useEffect(() => {
    if (!hasHydratedAuthRef.current) return;
    setStoredBearer(state.manualApiToken);
  }, [state.manualApiToken, setStoredBearer]);
  React.useEffect(() => {
    if (!hasHydratedAuthRef.current) return;
    if (!isLoadingApiKeys && apiKeys.length > 0 && !state.selectedApiKey && !storedApiKeyId) {
      dispatch({ type: "SET_API_KEY", apiKeyId: apiKeys[0]?.id || null });
    }
  }, [apiKeys, isLoadingApiKeys, state.selectedApiKey, storedApiKeyId]);
  React.useEffect(() => {
    try {
      const headers = parseRequestHeaders(state.requestHeaders);
      if (state.selectedApiKey) {
        const apiKey = apiKeys.find((k) => k.id === state.selectedApiKey);
        if (!apiKey) {
          dispatch({ type: "CLEAR_API_KEY_SELECTION" });
          return;
        }
        const keyValue = apiKey.secret || apiKey.id;
        if (headers["X-API-Key"] !== keyValue) {
          headers["X-API-Key"] = keyValue;
          dispatch({ type: "SYNC_API_KEY_HEADER", headers: JSON.stringify(headers, null, 2) });
        }
      } else if (headers["X-API-Key"]) {
        delete headers["X-API-Key"];
        dispatch({ type: "SYNC_API_KEY_HEADER", headers: JSON.stringify(headers, null, 2) });
      }
    } catch (error) {
      consola2__default.default.error("Error updating headers:", error);
    }
  }, [state.selectedApiKey, apiKeys]);
  React.useEffect(() => {
    if (!state.selectedEndpoint) return;
    const updated = new UrlBuilder(state.selectedEndpoint, state.parameters).build();
    if (updated !== state.requestUrl) {
      dispatch({ type: "SYNC_URL", url: updated });
    }
  }, [state.parameters, state.selectedEndpoint]);
  const setCurrentStep = React.useCallback((step) => dispatch({ type: "SET_STEP", step }), []);
  const goToNextStep = React.useCallback(() => dispatch({ type: "NEXT_STEP" }), []);
  const goToPreviousStep = React.useCallback(() => dispatch({ type: "PREV_STEP" }), []);
  const setSelectedEndpoint = React.useCallback((endpoint) => dispatch({ type: "SELECT_ENDPOINT", endpoint }), []);
  const setSelectedCategory = React.useCallback((category) => dispatch({ type: "SET_CATEGORY", category }), []);
  const setSearchTerm = React.useCallback((term) => dispatch({ type: "SET_SEARCH", term }), []);
  const setSelectedVersion = React.useCallback((version) => dispatch({ type: "SET_VERSION", version }), []);
  const setRequestUrl = React.useCallback((url) => dispatch({ type: "SET_REQUEST_URL", url }), []);
  const setRequestMethod = React.useCallback((method) => dispatch({ type: "SET_REQUEST_METHOD", method }), []);
  const setRequestHeaders = React.useCallback((headers) => dispatch({ type: "SET_REQUEST_HEADERS", headers }), []);
  const setRequestBody = React.useCallback((body) => dispatch({ type: "SET_REQUEST_BODY", body }), []);
  const setSelectedApiKey = React.useCallback((apiKeyId) => dispatch({ type: "SET_API_KEY", apiKeyId }), []);
  const setManualApiToken = React.useCallback((token) => dispatch({ type: "SET_MANUAL_TOKEN", token }), []);
  const setParameters = React.useCallback((parameters) => dispatch({ type: "SET_PARAMETERS", parameters }), []);
  const setResponse = React.useCallback((response) => dispatch({ type: "SET_RESPONSE", response }), []);
  const setLoading = React.useCallback((loading) => dispatch({ type: "SET_LOADING", loading }), []);
  const setSidebarOpen = React.useCallback((open) => dispatch({ type: "SET_SIDEBAR", open }), []);
  const setActiveSchemaId = React.useCallback((id) => dispatch({ type: "SET_ACTIVE_SCHEMA_ID", id }), []);
  const clearAll = React.useCallback(() => dispatch({ type: "RESET" }), []);
  const sendRequest = React.useCallback(async () => {
    if (!state.requestUrl) {
      consola2__default.default.error("No URL provided");
      return;
    }
    abortControllerRef.current?.abort();
    const controller = new AbortController();
    abortControllerRef.current = controller;
    dispatch({ type: "REQUEST_START" });
    const startTime = Date.now();
    try {
      const headers = parseRequestHeaders(state.requestHeaders);
      let bearerToken = null;
      if (state.manualApiToken) {
        bearerToken = state.manualApiToken;
      } else if (typeof window !== "undefined") {
        bearerToken = window.localStorage.getItem("auth_token");
      }
      if (bearerToken) headers["Authorization"] = `Bearer ${bearerToken}`;
      const requestOptions = {
        method: state.requestMethod,
        headers,
        signal: controller.signal
      };
      if (state.requestBody && state.requestMethod !== "GET") {
        requestOptions.body = state.requestBody;
      }
      const response = await fetch(state.requestUrl, requestOptions);
      const duration = Date.now() - startTime;
      const responseText = await response.text();
      let responseData;
      try {
        responseData = JSON.parse(responseText);
      } catch {
        responseData = responseText;
      }
      dispatch({
        type: "REQUEST_SUCCESS",
        response: {
          status: response.status,
          statusText: response.statusText,
          headers: Object.fromEntries(response.headers.entries()),
          data: responseData,
          duration
        }
      });
      consola2__default.default.success(`${state.requestMethod} ${state.requestUrl} \u2192 ${response.status} (${duration}ms)`);
    } catch (error) {
      if (error instanceof DOMException && error.name === "AbortError") return;
      consola2__default.default.error("Request failed:", error);
      dispatch({
        type: "REQUEST_ERROR",
        response: {
          error: error instanceof Error ? error.message : "Request failed",
          duration: Date.now() - startTime
        }
      });
    }
  }, [state.requestUrl, state.requestHeaders, state.manualApiToken, state.requestMethod, state.requestBody]);
  const contextValue = {
    state,
    config,
    apiKeys,
    apiKeysLoading: isLoadingApiKeys,
    setCurrentStep,
    goToNextStep,
    goToPreviousStep,
    setSelectedEndpoint,
    setSelectedCategory,
    setSearchTerm,
    setSelectedVersion,
    setRequestUrl,
    setRequestMethod,
    setRequestHeaders,
    setRequestBody,
    setSelectedApiKey,
    setManualApiToken,
    setParameters,
    setResponse,
    setLoading,
    setSidebarOpen,
    setActiveSchemaId,
    clearAll,
    sendRequest
  };
  return /* @__PURE__ */ jsxRuntime.jsx(PlaygroundContext.Provider, { value: contextValue, children });
}, "PlaygroundProvider");

exports.CODE_SAMPLE_TARGETS = CODE_SAMPLE_TARGETS;
exports.PlaygroundProvider = PlaygroundProvider;
exports.UrlBuilder = UrlBuilder;
exports.buildHarRequest = buildHarRequest;
exports.deduplicateEndpoints = deduplicateEndpoints;
exports.dereferenceSchema = dereferenceSchema;
exports.endpointToMarkdown = endpointToMarkdown;
exports.findApiKeyById = findApiKeyById;
exports.formatBytes = formatBytes;
exports.isValidJson = isValidJson;
exports.joinUrl = joinUrl;
exports.parseRequestHeaders = parseRequestHeaders;
exports.relativePath = relativePath;
exports.renderSnippet = renderSnippet;
exports.resolveAbsolute = resolveAbsolute;
exports.resolveBaseUrl = resolveBaseUrl;
exports.sampleSchemaJson = sampleSchemaJson;
exports.toCompactJson = toCompactJson;
exports.toMarkdown = toMarkdown;
exports.toRawJson = toRawJson;
exports.usePlaygroundContext = usePlaygroundContext;
//# sourceMappingURL=chunk-7EYHNP3E.cjs.map
//# sourceMappingURL=chunk-7EYHNP3E.cjs.map