@executor-js/plugin-openapi 1.5.22 → 1.5.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/{AddOpenApiSource-26V6EZD4.js → AddOpenApiSource-6PJZWRRZ.js} +17 -12
  2. package/dist/AddOpenApiSource-6PJZWRRZ.js.map +1 -0
  3. package/dist/{OpenApiAccountsPanel-XNDADPBL.js → OpenApiAccountsPanel-W6IMUY7Q.js} +4 -4
  4. package/dist/{UpdateSpecSection-MWC5DBXF.js → UpdateSpecSection-R2RF2QV2.js} +3 -3
  5. package/dist/api/group.d.ts +10 -0
  6. package/dist/api/index.d.ts +12 -0
  7. package/dist/{chunk-UYPLGACO.js → chunk-562TAVB2.js} +5 -3
  8. package/dist/chunk-562TAVB2.js.map +1 -0
  9. package/dist/{chunk-RCBR3QMJ.js → chunk-56PVOO6X.js} +10 -4
  10. package/dist/{chunk-RCBR3QMJ.js.map → chunk-56PVOO6X.js.map} +1 -1
  11. package/dist/{chunk-5YG34JIY.js → chunk-DBA2BHE4.js} +194 -18
  12. package/dist/chunk-DBA2BHE4.js.map +1 -0
  13. package/dist/{chunk-QQFCICLX.js → chunk-HG5JB2UJ.js} +9 -1
  14. package/dist/{chunk-QQFCICLX.js.map → chunk-HG5JB2UJ.js.map} +1 -1
  15. package/dist/{chunk-W6DGFLYT.js → chunk-IVRAOG3T.js} +5 -3
  16. package/dist/{chunk-W6DGFLYT.js.map → chunk-IVRAOG3T.js.map} +1 -1
  17. package/dist/{chunk-XFJWX2CY.js → chunk-WWZ7B34D.js} +8 -2
  18. package/dist/{chunk-XFJWX2CY.js.map → chunk-WWZ7B34D.js.map} +1 -1
  19. package/dist/client.js +4 -4
  20. package/dist/core.js +4 -4
  21. package/dist/index.js +4 -4
  22. package/dist/react/AddOpenApiSource.d.ts +1 -0
  23. package/dist/react/AddOpenApiSource.test.d.ts +1 -0
  24. package/dist/react/atoms.d.ts +12 -0
  25. package/dist/react/client.d.ts +10 -0
  26. package/dist/sdk/config.d.ts +4 -0
  27. package/dist/sdk/plugin.d.ts +2 -0
  28. package/dist/sdk/preview.d.ts +16 -0
  29. package/package.json +3 -3
  30. package/dist/AddOpenApiSource-26V6EZD4.js.map +0 -1
  31. package/dist/chunk-5YG34JIY.js.map +0 -1
  32. package/dist/chunk-UYPLGACO.js.map +0 -1
  33. /package/dist/{OpenApiAccountsPanel-XNDADPBL.js.map → OpenApiAccountsPanel-W6IMUY7Q.js.map} +0 -0
  34. /package/dist/{UpdateSpecSection-MWC5DBXF.js.map → UpdateSpecSection-R2RF2QV2.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sdk/errors.ts","../src/sdk/parse.ts","../src/sdk/split.ts","../src/sdk/openapi-utils.ts","../src/sdk/types.ts","../src/sdk/extract.ts","../src/sdk/definitions.ts","../src/sdk/preview.ts"],"sourcesContent":["import { Data, Schema } from \"effect\";\nimport type { Option } from \"effect\";\nimport type { AuthToolFailureCode } from \"@executor-js/sdk/core\";\n\n// HTTP status lives on the class declaration so HttpApiBuilder's error\n// encoder (which reads `ast.annotations` off the schema it stored on\n// `group.addError(...)`) finds it. Applying the annotation post-hoc\n// via `.annotate(...)` in group.ts produced a transform-wrapper AST\n// whose status was not picked up — the error then slipped the typed\n// channel and was captured as a 500 by the observability middleware,\n// spamming Sentry on user misconfig.\nexport class OpenApiParseError extends Schema.TaggedErrorClass<OpenApiParseError>()(\n \"OpenApiParseError\",\n {\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n\nexport class OpenApiExtractionError extends Schema.TaggedErrorClass<OpenApiExtractionError>()(\n \"OpenApiExtractionError\",\n {\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n\nexport class OpenApiInvocationError extends Data.TaggedError(\"OpenApiInvocationError\")<{\n readonly message: string;\n readonly statusCode: Option.Option<number>;\n readonly cause?: unknown;\n}> {}\n\nexport class OpenApiOAuthError extends Schema.TaggedErrorClass<OpenApiOAuthError>()(\n \"OpenApiOAuthError\",\n {\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n\n// ---------------------------------------------------------------------------\n// Auth required — v2 reframes this around the connection (owner/integration/\n// name) that supplies the missing credential, not v1's source/slot/secret.\n// ---------------------------------------------------------------------------\n\nexport class OpenApiAuthRequiredError extends Data.TaggedError(\"OpenApiAuthRequiredError\")<{\n readonly code: AuthToolFailureCode;\n readonly message: string;\n readonly owner: \"org\" | \"user\";\n readonly integration: string;\n readonly connection: string;\n readonly credentialKind: \"secret\" | \"oauth\" | \"upstream\";\n readonly credentialLabel?: string;\n readonly status?: number;\n readonly details?: unknown;\n readonly cause?: unknown;\n}> {}\n","import type { OpenAPI, OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\nimport { Duration, Effect, Schema } from \"effect\";\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\";\nimport { JSON_SCHEMA, load as parseYamlDocument } from \"js-yaml\";\n\nimport { OpenApiExtractionError, OpenApiParseError } from \"./errors\";\n\nexport type ParsedDocument = OpenAPIV3.Document | OpenAPIV3_1.Document;\n\nexport interface SpecFetchCredentials {\n readonly headers?: Record<string, string>;\n readonly queryParams?: Record<string, string>;\n}\n\n// ExtractionError subclass raised from parse() for non-3.x specs\nclass OpenApiExtractionErrorFromParse extends OpenApiExtractionError {}\n\n/**\n * Fetch an OpenAPI spec URL and return its body text. Uses the Effect\n * HttpClient so the caller chooses the transport via layer — in Cloudflare\n * Workers, `FetchHttpClient.layer` binds to the Workers-native `fetch`.\n * Bounded by a 60s timeout.\n */\nexport const fetchSpecText = Effect.fn(\"OpenApi.fetchSpecText\")(function* (\n url: string,\n credentials?: SpecFetchCredentials,\n) {\n const client = yield* HttpClient.HttpClient;\n const requestUrl = new URL(url);\n for (const [name, value] of Object.entries(credentials?.queryParams ?? {})) {\n requestUrl.searchParams.set(name, value);\n }\n let request = HttpClientRequest.get(requestUrl.toString()).pipe(\n HttpClientRequest.setHeader(\"Accept\", \"application/json, application/yaml, text/yaml, */*\"),\n );\n for (const [name, value] of Object.entries(credentials?.headers ?? {})) {\n request = HttpClientRequest.setHeader(request, name, value);\n }\n const response = yield* client.execute(request).pipe(\n Effect.timeout(Duration.seconds(60)),\n Effect.mapError(\n (_cause) =>\n new OpenApiParseError({\n message: \"Failed to fetch OpenAPI document\",\n }),\n ),\n );\n if (response.status < 200 || response.status >= 300) {\n return yield* new OpenApiParseError({\n message: `Failed to fetch OpenAPI document: HTTP ${response.status}`,\n });\n }\n const specText = yield* response.text.pipe(\n Effect.mapError(\n (_cause) =>\n new OpenApiParseError({\n message: \"Failed to read OpenAPI document body\",\n }),\n ),\n );\n return specText;\n});\n\n/**\n * Resolve an input string to spec text — if it's a URL, fetch it via\n * HttpClient; otherwise return it as-is.\n */\nexport const resolveSpecText = (input: string, credentials?: SpecFetchCredentials) =>\n input.startsWith(\"http://\") || input.startsWith(\"https://\")\n ? fetchSpecText(input, credentials)\n : Effect.succeed(input);\n\n/**\n * Parse an OpenAPI document from spec text and validate it's OpenAPI 3.x.\n *\n * NOTE: does NOT resolve `$ref`s. `DocResolver` + `normalizeOpenApiRefs`\n * downstream work on refs lazily, so inlining them here would just waste\n * memory — and for big specs (e.g. Cloudflare's API) that blows through\n * the 128MB Cloudflare Workers memory cap.\n */\nexport const parse = Effect.fn(\"OpenApi.parse\")(function* (text: string) {\n const api = yield* parseTextToObject(text);\n\n if (!isOpenApi3(api)) {\n return yield* new OpenApiExtractionErrorFromParse({\n message:\n \"Only OpenAPI 3.x documents are supported. Swagger 2.x documents should be converted first.\",\n });\n }\n\n return api as ParsedDocument;\n});\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\nconst isOpenApi3 = (doc: OpenAPI.Document): doc is OpenAPIV3.Document | OpenAPIV3_1.Document =>\n \"openapi\" in doc && typeof doc.openapi === \"string\" && doc.openapi.startsWith(\"3.\");\n\nconst parseTextToObject = (text: string): Effect.Effect<OpenAPI.Document, OpenApiParseError> =>\n Effect.gen(function* () {\n const trimmed = text.trim();\n if (trimmed.length === 0) {\n return yield* new OpenApiParseError({\n message: \"OpenAPI document is empty\",\n });\n }\n\n const parsed = yield* parseJsonLike(trimmed).pipe(\n Effect.mapError(\n () =>\n new OpenApiParseError({\n message: \"Failed to parse OpenAPI document\",\n }),\n ),\n );\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return yield* new OpenApiParseError({\n message: \"OpenAPI document must parse to an object\",\n });\n }\n\n return parsed as OpenAPI.Document;\n });\n\nconst parseJsonText = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));\n\nconst parseJsonLike = (text: string): Effect.Effect<unknown, unknown> => {\n const parseYaml = Effect.try({\n try: () => parseYamlDocument(text, { json: true, schema: JSON_SCHEMA }) as unknown,\n catch: () => \"YamlParseFailed\" as const,\n });\n if (!text.startsWith(\"{\") && !text.startsWith(\"[\")) return parseYaml;\n return parseJsonText(text).pipe(Effect.catch(() => parseYaml));\n};\n","/**\n * Structural splitter for large OpenAPI documents written in clean block YAML.\n *\n * The whole-document parse of a 37MB spec (Microsoft Graph: 16.5k operations,\n * 8.2k schemas) builds a ~300MB JS tree that OOMs the 128MB Cloudflare Workers\n * isolate. This splitter avoids ever holding that tree: it scans the text once,\n * recording the byte range of each top-level key, each path-item (the indent-2\n * entries under `paths:`), and each schema (the indent-4 entries under\n * `components.schemas:`). The streaming compile then slices one item at a time,\n * de-indents it back to column 0, hands the isolated fragment to a real YAML\n * parser, and discards the result before moving on. Peak memory stays near the\n * size of the largest single item plus the raw text, not the parsed whole.\n *\n * This is not a YAML reimplementation: it extracts safe byte ranges from a\n * constrained document shape, then defers every actual parse to `js-yaml`. It\n * is only valid for the block-YAML profile `isStreamableSpec` accepts (2-space\n * block maps, top-level keys at column 0, no anchors/aliases/merge keys). Block\n * scalars (`|` / `>`) in descriptions are tracked so their indented content is\n * never mistaken for structure.\n */\n\nimport { JSON_SCHEMA, load as parseYamlDocument } from \"js-yaml\";\n\nexport interface ByteRange {\n readonly start: number;\n readonly end: number;\n}\n\nexport interface SpecStructure {\n /** Raw spec text. Every range below indexes into this string. */\n readonly text: string;\n /** Byte ranges of the top-level keys that are not `paths` / `components`\n * (openapi, info, servers, tags, security, ...). Concatenated and parsed as\n * one small document for the head (servers, info). */\n readonly headRanges: readonly ByteRange[];\n /** One range per path-item: the indent-2 entries under `paths:`. */\n readonly pathItems: readonly ByteRange[];\n /** One range per schema entry: the indent-4 entries under\n * `components.schemas:`. */\n readonly schemas: readonly ByteRange[];\n /** Ranges of the indent-2 `components` subkeys we keep whole because they are\n * small and may be `$ref`'d by a kept operation (parameters / requestBodies /\n * responses / headers / links / securitySchemes). Excludes the huge `schemas`\n * (streamed and pruned separately) and `examples` (never referenced by a\n * binding). */\n readonly smallComponentRanges: readonly ByteRange[];\n}\n\nconst SPACE = 32;\nconst HASH = 35;\nconst DASH = 45;\n\n/** `components` subkeys kept whole during a reduce: small, and a kept operation\n * may `$ref` into any of them. `schemas` is streamed/pruned separately and\n * `examples` is dropped (large, never referenced by a binding). */\nconst SMALL_COMPONENT_SECTIONS = new Set([\n \"parameters\",\n \"requestBodies\",\n \"responses\",\n \"headers\",\n \"links\",\n \"securitySchemes\",\n]);\n\n/** Count of leading spaces on the line starting at `lineStart`. */\nconst indentOf = (text: string, lineStart: number, lineEnd: number): number => {\n let i = lineStart;\n while (i < lineEnd && text.charCodeAt(i) === SPACE) i++;\n return i - lineStart;\n};\n\n/** True for a blank (whitespace-only) or comment line. */\nconst isBlankOrComment = (text: string, contentStart: number, lineEnd: number): boolean =>\n contentStart >= lineEnd || text.charCodeAt(contentStart) === HASH;\n\n/**\n * True when the line opens a block scalar (`key: |`, `key: >-`, etc.), meaning\n * every following more-indented line is literal content, not structure.\n */\nconst opensBlockScalar = (line: string): boolean =>\n /:\\s*[|>][+-]?\\d*\\s*(#.*)?$/.test(line) || /^\\s*[|>][+-]?\\d*\\s*(#.*)?$/.test(line);\n\ninterface LineCursor {\n readonly lineStart: number;\n readonly lineEnd: number;\n readonly nextStart: number;\n readonly indent: number;\n readonly contentStart: number;\n}\n\n/** Advance to the next significant line at offset `from`, returning null at EOF.\n * Blank lines, comments, and block-scalar content (lines indented deeper than\n * the scalar key, tracked by the caller) are still returned; the caller skips\n * them. */\nconst lineAt = (text: string, from: number, limit: number): LineCursor | null => {\n if (from >= limit) return null;\n let lineEnd = text.indexOf(\"\\n\", from);\n if (lineEnd === -1 || lineEnd > limit) lineEnd = limit;\n const indent = indentOf(text, from, lineEnd);\n const contentStart = from + indent;\n return {\n lineStart: from,\n lineEnd,\n nextStart: lineEnd + 1,\n indent,\n contentStart,\n };\n};\n\n/**\n * Find the start offset of every key line at exactly `indent` within\n * `[start, end)`, skipping blank/comment lines, deeper child lines, and\n * block-scalar content. Sequence items (`- `) at the target indent are not\n * treated as keys. Returns offsets in document order.\n */\nconst keyLineStartsAtIndent = (\n text: string,\n start: number,\n end: number,\n indent: number,\n): number[] => {\n const starts: number[] = [];\n let blockScalarIndent = -1;\n let pos = start;\n while (pos < end) {\n const line = lineAt(text, pos, end);\n if (!line) break;\n pos = line.nextStart;\n if (isBlankOrComment(text, line.contentStart, line.lineEnd)) continue;\n if (blockScalarIndent >= 0) {\n if (line.indent > blockScalarIndent) continue;\n blockScalarIndent = -1;\n }\n if (line.indent === indent && text.charCodeAt(line.contentStart) !== DASH) {\n starts.push(line.lineStart);\n }\n if (line.indent <= indent && opensBlockScalar(text.slice(line.contentStart, line.lineEnd))) {\n blockScalarIndent = line.indent;\n }\n }\n return starts;\n};\n\n/** Contiguous ranges from a sorted list of block-start offsets within\n * `[blockStart, blockEnd)`: each range runs to the next start (or blockEnd). */\nconst rangesFromStarts = (starts: readonly number[], blockEnd: number): ByteRange[] =>\n starts.map((s, i) => ({ start: s, end: i + 1 < starts.length ? starts[i + 1]! : blockEnd }));\n\n/** The simple (unquoted) key name on a key line, e.g. `paths`, `schemas`. */\nconst keyNameAt = (text: string, lineStart: number, lineEnd: number): string => {\n const indent = indentOf(text, lineStart, lineEnd);\n const colon = text.indexOf(\":\", lineStart + indent);\n const keyEnd = colon === -1 || colon > lineEnd ? lineEnd : colon;\n return text.slice(lineStart + indent, keyEnd).trim();\n};\n\n/**\n * Scan a document into its structural ranges. Pure and synchronous; never\n * parses. Returns null when the document does not present the expected shape\n * (no `paths:` block), so the caller can fall back to a whole-document parse.\n */\nexport const structuralSplit = (text: string): SpecStructure | null => {\n const len = text.length;\n\n // Top-level keys (column 0). Record each key's start + name, respecting\n // block scalars whose content could sit at column >= 1.\n const topStarts: number[] = [];\n const topNames: string[] = [];\n {\n let blockScalarIndent = -1;\n let pos = 0;\n while (pos < len) {\n const line = lineAt(text, pos, len);\n if (!line) break;\n pos = line.nextStart;\n if (isBlankOrComment(text, line.contentStart, line.lineEnd)) continue;\n if (blockScalarIndent >= 0) {\n if (line.indent > blockScalarIndent) continue;\n blockScalarIndent = -1;\n }\n if (line.indent === 0) {\n topStarts.push(line.lineStart);\n topNames.push(keyNameAt(text, line.lineStart, line.lineEnd));\n }\n if (opensBlockScalar(text.slice(line.contentStart, line.lineEnd))) {\n blockScalarIndent = line.indent;\n }\n }\n }\n\n const topRanges = rangesFromStarts(topStarts, len);\n const pathsIdx = topNames.indexOf(\"paths\");\n if (pathsIdx === -1) return null;\n const componentsIdx = topNames.indexOf(\"components\");\n\n const headRanges: ByteRange[] = [];\n for (let i = 0; i < topRanges.length; i++) {\n if (i === pathsIdx || i === componentsIdx) continue;\n headRanges.push(topRanges[i]!);\n }\n\n // Path-items: indent-2 keys inside the `paths:` block (after its key line).\n const pathsRange = topRanges[pathsIdx]!;\n const pathsBodyStart =\n lineAt(text, pathsRange.start, pathsRange.end)?.nextStart ?? pathsRange.end;\n const pathItems = rangesFromStarts(\n keyLineStartsAtIndent(text, pathsBodyStart, pathsRange.end, 2),\n pathsRange.end,\n );\n\n const schemas: ByteRange[] = [];\n const smallComponentRanges: ByteRange[] = [];\n if (componentsIdx !== -1) {\n const componentsRange = topRanges[componentsIdx]!;\n const componentsBodyStart =\n lineAt(text, componentsRange.start, componentsRange.end)?.nextStart ?? componentsRange.end;\n const subStarts = keyLineStartsAtIndent(text, componentsBodyStart, componentsRange.end, 2);\n const subRanges = rangesFromStarts(subStarts, componentsRange.end);\n for (const range of subRanges) {\n const name = keyNameAt(text, range.start, lineAt(text, range.start, range.end)!.lineEnd);\n if (name === \"schemas\") {\n const bodyStart = lineAt(text, range.start, range.end)?.nextStart ?? range.end;\n for (const s of rangesFromStarts(\n keyLineStartsAtIndent(text, bodyStart, range.end, 4),\n range.end,\n )) {\n schemas.push(s);\n }\n } else if (SMALL_COMPONENT_SECTIONS.has(name)) {\n smallComponentRanges.push(range);\n }\n // `examples` and any other subkey are intentionally dropped: no binding\n // field references them, and they can be large.\n }\n }\n\n return { text, headRanges, pathItems, schemas, smallComponentRanges };\n};\n\n/** Strip exactly `indent` leading spaces from every line of `fragment`, lifting\n * an indent-N block back to column 0 so it parses as a standalone document. */\nconst dedent = (fragment: string, indent: number): string =>\n indent === 0 ? fragment : fragment.replace(new RegExp(`^ {1,${indent}}`, \"gm\"), \"\");\n\nconst parseYaml = (text: string): unknown =>\n parseYamlDocument(text, { json: true, schema: JSON_SCHEMA });\n\n/**\n * Parse a single indent-N entry range (a path-item or a schema) in isolation.\n * Returns `[name, value]` where `name` is the entry's key and `value` its\n * parsed body, or null when the fragment does not parse to a single-key map.\n */\nexport const parseEntry = (\n text: string,\n range: ByteRange,\n indent: number,\n): readonly [string, unknown] | null => {\n const parsed = parseYaml(dedent(text.slice(range.start, range.end), indent));\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n const entries = Object.entries(parsed as Record<string, unknown>);\n if (entries.length !== 1) return null;\n return entries[0]!;\n};\n\n/** Parse the concatenation of the head ranges into the document head (openapi,\n * info, servers, tags). Small; safe to materialize whole. */\nexport const parseHead = (structure: SpecStructure): Record<string, unknown> => {\n const text = structure.headRanges.map((r) => structure.text.slice(r.start, r.end)).join(\"\");\n const parsed = parseYaml(text);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n};\n\n/** Parse the small component subkeys (parameters / requestBodies / responses)\n * into a `components`-shaped object for `$ref` resolution. */\nexport const parseSmallComponents = (structure: SpecStructure): Record<string, unknown> => {\n if (structure.smallComponentRanges.length === 0) return {};\n const body = structure.smallComponentRanges\n .map((r) => structure.text.slice(r.start, r.end))\n .join(\"\");\n const parsed = parseYaml(`components:\\n${body}`);\n const components =\n parsed && typeof parsed === \"object\" ? (parsed as Record<string, unknown>).components : null;\n return components && typeof components === \"object\"\n ? (components as Record<string, unknown>)\n : {};\n};\n\n/**\n * Accept only the block-YAML profile the splitter can safely slice: no tabs, no\n * anchors/aliases, no merge keys, and a `paths:` block present. Block scalars\n * are allowed (tracked during the scan). Conservative by design: a false\n * negative just routes a spec through the whole-document parse.\n */\nexport const isStreamableSpec = (text: string): boolean => {\n if (text.indexOf(\"\\t\") !== -1) return false;\n // Anchors/aliases/merge keys: cheap substring rejects before structural work.\n if (/(^|\\s)[&*][A-Za-z0-9_]/m.test(text)) return false;\n if (/<<\\s*:/.test(text)) return false;\n return /^paths:/m.test(text);\n};\n\nconst SCHEMA_REF_PREFIX = \"#/components/schemas/\";\n\n/** Map each `components.schemas` entry name to its byte range, reading only the\n * key line (never parsing the schema body). The schema name is the raw YAML\n * key, which matches the trailing segment of a `#/components/schemas/<name>`\n * reference. */\nexport const indexSchemas = (structure: SpecStructure): ReadonlyMap<string, ByteRange> => {\n const index = new Map<string, ByteRange>();\n for (const range of structure.schemas) {\n const line = lineAt(structure.text, range.start, range.end);\n if (!line) continue;\n const name = keyNameAt(structure.text, range.start, line.lineEnd);\n if (name) index.set(name, range);\n }\n return index;\n};\n\n/** Decode a `#/components/schemas/<segment>` name segment. Schema names are raw\n * YAML keys, so only JSON-pointer tilde escaping can appear (no `%`-encoding\n * in the wild specs we target); decode `~1`/`~0` and leave the rest verbatim. */\nconst decodeSchemaRefName = (segment: string): string =>\n segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n\n/** Collect the names of every `#/components/schemas/X` reference reachable in\n * `value`, without resolving them. */\nconst collectSchemaRefNames = (value: unknown, into: Set<string>): void => {\n if (typeof value === \"string\") {\n if (value.startsWith(SCHEMA_REF_PREFIX)) {\n const name = decodeSchemaRefName(value.slice(SCHEMA_REF_PREFIX.length));\n if (name.length > 0) into.add(name);\n }\n return;\n }\n if (Array.isArray(value)) {\n for (const item of value) collectSchemaRefNames(item, into);\n return;\n }\n if (value !== null && typeof value === \"object\") {\n for (const item of Object.values(value as Record<string, unknown>)) {\n collectSchemaRefNames(item, into);\n }\n }\n};\n\n/**\n * Resolve the transitive closure of schemas referenced by `roots`, parsing each\n * referenced schema once from its byte range (BFS over `$ref`s). Schemas not\n * reachable from `roots` are never parsed, so peak memory tracks the kept\n * subset rather than the full `components.schemas` map.\n */\nexport const collectReferencedSchemas = (\n structure: SpecStructure,\n index: ReadonlyMap<string, ByteRange>,\n roots: readonly unknown[],\n): Record<string, unknown> => {\n const result: Record<string, unknown> = {};\n const wanted = new Set<string>();\n for (const root of roots) collectSchemaRefNames(root, wanted);\n\n const queue = [...wanted];\n for (let i = 0; i < queue.length; i += 1) {\n const name = queue[i]!;\n if (Object.prototype.hasOwnProperty.call(result, name)) continue;\n const range = index.get(name);\n if (!range) continue;\n const entry = parseEntry(structure.text, range, 4);\n if (!entry) continue;\n result[name] = entry[1];\n const next = new Set<string>();\n collectSchemaRefNames(entry[1], next);\n for (const ref of next) {\n if (!Object.prototype.hasOwnProperty.call(result, ref)) queue.push(ref);\n }\n }\n return result;\n};\n\n/** A path-item filter for the streaming compile: given a parsed path-item,\n * return the (possibly trimmed) value to keep, or null to drop the path\n * entirely. Applied per path-item by `streamOperationBindingsFromStructure`. */\nexport type KeepPathItem = (\n path: string,\n pathItem: Record<string, unknown>,\n) => Record<string, unknown> | null;\n","// ---------------------------------------------------------------------------\n// OpenAPI type aliases and $ref resolution\n//\n// Wraps the openapi-types V3/V3_1 union mess and provides clean ref resolution.\n// ---------------------------------------------------------------------------\n\nimport type { OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\nimport type { ParsedDocument } from \"./parse\";\nimport type { ServerVariable } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Type aliases — collapse V3 / V3_1 unions into single names\n// ---------------------------------------------------------------------------\n\nexport type ParameterObject = OpenAPIV3.ParameterObject | OpenAPIV3_1.ParameterObject;\nexport type OperationObject = OpenAPIV3.OperationObject | OpenAPIV3_1.OperationObject;\nexport type PathItemObject = OpenAPIV3.PathItemObject | OpenAPIV3_1.PathItemObject;\nexport type RequestBodyObject = OpenAPIV3.RequestBodyObject | OpenAPIV3_1.RequestBodyObject;\nexport type ResponseObject = OpenAPIV3.ResponseObject | OpenAPIV3_1.ResponseObject;\nexport type MediaTypeObject = OpenAPIV3.MediaTypeObject | OpenAPIV3_1.MediaTypeObject;\nexport type ServerObject = OpenAPIV3.ServerObject | OpenAPIV3_1.ServerObject;\n\n// ---------------------------------------------------------------------------\n// DocResolver — wraps a parsed document for clean $ref resolution\n// ---------------------------------------------------------------------------\n\nexport class DocResolver {\n constructor(readonly doc: ParsedDocument) {}\n\n /** Resolve a value that might be a $ref, returning the resolved object */\n resolve<T>(value: T | OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject): T | null {\n if (isRef(value)) {\n const resolved = this.resolvePointer(value.$ref);\n return resolved as T | null;\n }\n return value as T;\n }\n\n private resolvePointer(ref: string): unknown {\n if (!ref.startsWith(\"#/\")) return null;\n const segments = ref.slice(2).split(\"/\");\n let current: unknown = this.doc;\n for (const segment of segments) {\n if (typeof current !== \"object\" || current === null) return null;\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n }\n}\n\nconst isRef = (value: unknown): value is { $ref: string } =>\n typeof value === \"object\" && value !== null && \"$ref\" in value;\n\n// ---------------------------------------------------------------------------\n// Server URL resolution\n// ---------------------------------------------------------------------------\n\n/** Substitute `{var}` placeholders in a templated URL using a plain map. */\nexport const substituteUrlVariables = (url: string, values: Record<string, string>): string => {\n let out = url;\n for (const [name, value] of Object.entries(values)) {\n out = out.replaceAll(`{${name}}`, value);\n }\n return out;\n};\n\n/** Resolve a templated server URL, filling each `{var}` from `overrides` when\n * non-empty, otherwise the variable's spec default. URLs without placeholders\n * pass through unchanged. */\nexport const resolveServerUrl = (\n templateUrl: string,\n variables: Record<string, ServerVariable> | undefined,\n overrides: Record<string, string>,\n): string => {\n const values: Record<string, string> = {};\n for (const [name, v] of Object.entries(variables ?? {})) values[name] = v.default;\n for (const [name, value] of Object.entries(overrides)) {\n if (value) values[name] = value;\n }\n return substituteUrlVariables(templateUrl, values);\n};\n\n// ---------------------------------------------------------------------------\n// Content negotiation\n// ---------------------------------------------------------------------------\n\n/**\n * Return all declared media entries in spec order. `Object.entries` on a\n * plain object preserves insertion order in modern engines, which matches\n * spec declaration order as the parser produced it.\n */\nexport const declaredContents = (\n content: Record<string, MediaTypeObject> | undefined,\n): ReadonlyArray<{ mediaType: string; media: MediaTypeObject }> => {\n if (!content) return [];\n return Object.entries(content).map(([mediaType, media]) => ({ mediaType, media }));\n};\n\n/**\n * Pick the default media type for a requestBody or response. Matches\n * swagger-client behaviour: **first declared wins** (not JSON-first). Spec\n * authors order content entries to signal intent (upload-heavy endpoints\n * declare multipart first, JSON second); respecting that order avoids\n * silently downgrading a multipart endpoint to JSON.\n *\n * For response bodies we still want a JSON preference because the server\n * picks the response content type, not the client — the old `application/\n * json` preference is preserved via `preferredResponseContent` below.\n */\nexport const preferredContent = (\n content: Record<string, MediaTypeObject> | undefined,\n): { mediaType: string; media: MediaTypeObject } | undefined => {\n const first = declaredContents(content)[0];\n return first ? first : undefined;\n};\n\n/** Response-side content picker — still JSON-first because the server\n * picks the response media type, so we want to advertise a preference. */\nexport const preferredResponseContent = (\n content: Record<string, MediaTypeObject> | undefined,\n): { mediaType: string; media: MediaTypeObject } | undefined => {\n if (!content) return undefined;\n const entries = Object.entries(content);\n const pick =\n entries.find(([mt]) => mt === \"application/json\") ??\n entries.find(([mt]) => mt.toLowerCase().includes(\"+json\")) ??\n entries.find(([mt]) => mt.toLowerCase().includes(\"json\")) ??\n entries[0];\n return pick ? { mediaType: pick[0], media: pick[1] } : undefined;\n};\n","import { Schema } from \"effect\";\nimport { AuthTemplateSlug, type OAuthAuthentication } from \"@executor-js/sdk/shared\";\nimport {\n apiKeyMethodFromAuthTemplate,\n isApiKeyAuthTemplate,\n type ApiKeyAuthMethod,\n type ApiKeyAuthTemplate,\n} from \"@executor-js/sdk/http-auth\";\n\n// ---------------------------------------------------------------------------\n// Auth-template model.\n//\n// The apiKey method is the SHARED placements model (`@executor-js/sdk/http-auth`,\n// the same shape the graphql/mcp plugins store): N header/query placements,\n// each rendered from its own credential input. The oauth template is\n// mechanism-intrinsic and comes from core (`OAuthAuthentication`, keyed\n// `kind: \"oauth2\"` with stored endpoints+scopes); an integration's\n// `Authentication` union composes the two. Client credentials\n// (clientId/secret) live on the core `OAuthClient`, not here.\n//\n// Pre-canonical stored templates (`type: \"apiKey\"` with `variable()`-templated\n// header/query records) are rewritten by the one-off config migration\n// (`migrate-config.ts`) — runtime code knows only this model.\n// ---------------------------------------------------------------------------\n\nexport { TOKEN_VARIABLE } from \"@executor-js/sdk/http-auth\";\n\nexport type APIKeyAuthentication = ApiKeyAuthMethod;\n\n/** Every method is keyed by `kind` — `kind: \"oauth2\"` | `kind: \"apikey\"`. */\nexport type Authentication = OAuthAuthentication | APIKeyAuthentication;\n\n/** What auth inputs accept: oauth templates (wire-typed: plain slug) plus the\n * request-shaped apikey dialect (`type: \"apiKey\"`, headers/queryParams\n * records) — the ONE apikey authoring shape. Stored configs and the catalog\n * read as canonical placements; `apiKeyAuthTemplateFromMethod` serializes\n * them back for read-modify-write flows. */\nexport type OAuthAuthenticationInput = Omit<OAuthAuthentication, \"slug\"> & {\n readonly slug: string;\n};\nexport type AuthenticationInput = OAuthAuthenticationInput | ApiKeyAuthTemplate;\n\n/** Expand the request-shaped dialect into canonical placements and brand the\n * oauth slugs. A dialect entry without a slug gets a blank one —\n * `mergeAuthTemplates` backfills `custom_<id>`. */\nexport const normalizeOpenApiAuthInputs = (\n inputs: readonly AuthenticationInput[],\n): readonly Authentication[] =>\n inputs.map((input): Authentication => {\n if (!isApiKeyAuthTemplate(input)) {\n return { ...input, slug: AuthTemplateSlug.make(input.slug) };\n }\n const method = apiKeyMethodFromAuthTemplate(input);\n return { ...method, slug: method.slug ?? \"\" };\n });\n\n// ---------------------------------------------------------------------------\n// Branded IDs\n// ---------------------------------------------------------------------------\n\nexport const OperationId = Schema.String.pipe(Schema.brand(\"OperationId\"));\nexport type OperationId = typeof OperationId.Type;\n\n// ---------------------------------------------------------------------------\n// HTTP\n// ---------------------------------------------------------------------------\n\nexport const HttpMethod = Schema.Literals([\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"patch\",\n \"head\",\n \"options\",\n \"trace\",\n]);\nexport type HttpMethod = typeof HttpMethod.Type;\n\nexport const ParameterLocation = Schema.Literals([\"path\", \"query\", \"header\", \"cookie\"]);\nexport type ParameterLocation = typeof ParameterLocation.Type;\n\n// ---------------------------------------------------------------------------\n// Extracted operation\n// ---------------------------------------------------------------------------\n\nexport const OperationParameter = Schema.Struct({\n name: Schema.String,\n location: ParameterLocation,\n required: Schema.Boolean,\n schema: Schema.OptionFromOptional(Schema.Unknown),\n style: Schema.OptionFromOptional(Schema.String),\n explode: Schema.OptionFromOptional(Schema.Boolean),\n allowReserved: Schema.OptionFromOptional(Schema.Boolean),\n description: Schema.OptionFromOptional(Schema.String),\n});\nexport type OperationParameter = typeof OperationParameter.Type;\n\n/**\n * OpenAPI 3.x `Encoding Object` (§4.8.15). Declared per-property inside a\n * multipart/form-data or application/x-www-form-urlencoded request body.\n *\n * - `contentType` — for multipart, overrides the per-part `Content-Type`\n * header (e.g. `application/json` for a JSON-encoded metadata part).\n * - `style` / `explode` / `allowReserved` — for form-urlencoded, control\n * array / object serialization the same way parameter-level style does.\n */\nexport const EncodingObject = Schema.Struct({\n contentType: Schema.OptionFromOptional(Schema.String),\n style: Schema.OptionFromOptional(Schema.String),\n explode: Schema.OptionFromOptional(Schema.Boolean),\n allowReserved: Schema.OptionFromOptional(Schema.Boolean),\n});\nexport type EncodingObject = typeof EncodingObject.Type;\n\nexport const MediaBinding = Schema.Struct({\n contentType: Schema.String,\n schema: Schema.OptionFromOptional(Schema.Unknown),\n encoding: Schema.OptionFromOptional(Schema.Record(Schema.String, EncodingObject)),\n});\nexport type MediaBinding = typeof MediaBinding.Type;\n\nexport const OperationRequestBody = Schema.Struct({\n required: Schema.Boolean,\n /** Default media type — first declared in spec order (not JSON-first).\n * Used when the caller does not override via the tool's `contentType` arg. */\n contentType: Schema.String,\n /** Schema of the default media type. Kept for backward compat with stored\n * bindings from before `contents` was added. */\n schema: Schema.OptionFromOptional(Schema.Unknown),\n /** All declared media types in spec order. Populated by `extract.ts`\n * going forward; older persisted bindings may have this unset and will\n * fall back to `{contentType, schema}`. */\n contents: Schema.OptionFromOptional(Schema.Array(MediaBinding)),\n});\nexport type OperationRequestBody = typeof OperationRequestBody.Type;\n\nexport const OperationFileHint = Schema.Struct({\n kind: Schema.Literals([\"binaryResponse\", \"byteField\"]),\n mimeType: Schema.OptionFromOptional(Schema.String),\n dataField: Schema.OptionFromOptional(Schema.String),\n sizeField: Schema.OptionFromOptional(Schema.String),\n encoding: Schema.OptionFromOptional(Schema.Literals([\"base64\", \"base64url\"])),\n});\nexport type OperationFileHint = typeof OperationFileHint.Type;\n\nexport const OperationResponseBody = Schema.Struct({\n contentType: Schema.String,\n schema: Schema.OptionFromOptional(Schema.Unknown),\n fileHint: Schema.OptionFromOptional(OperationFileHint),\n});\nexport type OperationResponseBody = typeof OperationResponseBody.Type;\n\nexport const ServerVariable = Schema.Struct({\n default: Schema.String,\n enum: Schema.OptionFromOptional(Schema.Array(Schema.String)),\n description: Schema.OptionFromOptional(Schema.String),\n});\nexport type ServerVariable = typeof ServerVariable.Type;\n\nexport const ServerInfo = Schema.Struct({\n url: Schema.String,\n description: Schema.OptionFromOptional(Schema.String),\n variables: Schema.OptionFromOptional(Schema.Record(Schema.String, ServerVariable)),\n});\nexport type ServerInfo = typeof ServerInfo.Type;\n\nexport const ExtractedOperation = Schema.Struct({\n operationId: OperationId,\n toolPath: Schema.OptionFromOptional(Schema.String),\n method: HttpMethod,\n servers: Schema.Array(ServerInfo),\n pathTemplate: Schema.String,\n summary: Schema.OptionFromOptional(Schema.String),\n description: Schema.OptionFromOptional(Schema.String),\n tags: Schema.Array(Schema.String),\n parameters: Schema.Array(OperationParameter),\n requestBody: Schema.OptionFromOptional(OperationRequestBody),\n responseBody: Schema.OptionFromOptional(OperationResponseBody),\n inputSchema: Schema.OptionFromOptional(Schema.Unknown),\n outputSchema: Schema.OptionFromOptional(Schema.Unknown),\n deprecated: Schema.Boolean,\n});\nexport type ExtractedOperation = typeof ExtractedOperation.Type;\n\nexport const ExtractionResult = Schema.Struct({\n title: Schema.OptionFromOptional(Schema.String),\n /** The spec's `info.description` — the author's own summary of the API. */\n description: Schema.OptionFromOptional(Schema.String),\n version: Schema.OptionFromOptional(Schema.String),\n servers: Schema.Array(ServerInfo),\n operations: Schema.Array(ExtractedOperation),\n});\nexport type ExtractionResult = typeof ExtractionResult.Type;\n\n// ---------------------------------------------------------------------------\n// Operation binding — minimal invocation data (no schemas/metadata)\n// ---------------------------------------------------------------------------\n\nexport const OperationBinding = Schema.Struct({\n method: HttpMethod,\n servers: Schema.optional(Schema.Array(ServerInfo)),\n pathTemplate: Schema.String,\n parameters: Schema.Array(OperationParameter),\n requestBody: Schema.OptionFromOptional(OperationRequestBody),\n responseBody: Schema.OptionFromOptional(OperationResponseBody),\n});\nexport type OperationBinding = typeof OperationBinding.Type;\n\n// ---------------------------------------------------------------------------\n// Invocation\n// ---------------------------------------------------------------------------\n\nexport const InvocationResult = Schema.Struct({\n status: Schema.Number,\n headers: Schema.Record(Schema.String, Schema.String),\n data: Schema.NullOr(Schema.Unknown),\n error: Schema.NullOr(Schema.Unknown),\n});\nexport type InvocationResult = typeof InvocationResult.Type;\n","import { Effect, Option } from \"effect\";\n\nimport { planToolPaths, type OperationPathInput, type PlannedToolPath } from \"./definitions\";\nimport { OpenApiExtractionError } from \"./errors\";\nimport type { ParsedDocument } from \"./parse\";\nimport {\n parseEntry,\n parseHead,\n parseSmallComponents,\n type ByteRange,\n type KeepPathItem,\n type SpecStructure,\n} from \"./split\";\nimport {\n declaredContents,\n DocResolver,\n preferredResponseContent,\n type OperationObject,\n type ParameterObject,\n type PathItemObject,\n type RequestBodyObject,\n type ResponseObject,\n type ServerObject,\n} from \"./openapi-utils\";\nimport {\n EncodingObject,\n ExtractedOperation,\n ExtractionResult,\n type HttpMethod,\n MediaBinding,\n OperationBinding,\n OperationFileHint,\n OperationId,\n OperationParameter,\n OperationRequestBody,\n OperationResponseBody,\n type ParameterLocation,\n ServerInfo,\n ServerVariable,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst HTTP_METHODS: readonly HttpMethod[] = [\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"patch\",\n \"head\",\n \"options\",\n \"trace\",\n];\n\nconst VALID_PARAM_LOCATIONS = new Set<string>([\"path\", \"query\", \"header\", \"cookie\"]);\n\n// ---------------------------------------------------------------------------\n// Parameter extraction\n// ---------------------------------------------------------------------------\n\nconst extractParameters = (\n pathItem: PathItemObject,\n operation: OperationObject,\n r: DocResolver,\n): OperationParameter[] => {\n const merged = new Map<string, ParameterObject>();\n\n for (const raw of pathItem.parameters ?? []) {\n const p = r.resolve<ParameterObject>(raw);\n if (!p) continue;\n merged.set(`${p.in}:${p.name}`, p);\n }\n for (const raw of operation.parameters ?? []) {\n const p = r.resolve<ParameterObject>(raw);\n if (!p) continue;\n merged.set(`${p.in}:${p.name}`, p);\n }\n\n return [...merged.values()]\n .filter((p) => VALID_PARAM_LOCATIONS.has(p.in))\n .map((p) =>\n OperationParameter.make({\n name: p.name,\n location: p.in as ParameterLocation,\n required: p.in === \"path\" ? true : p.required === true,\n schema: Option.fromNullishOr(p.schema),\n style: Option.fromNullishOr(p.style),\n explode: Option.fromNullishOr(p.explode),\n allowReserved: Option.fromNullishOr(\"allowReserved\" in p ? p.allowReserved : undefined),\n description: Option.fromNullishOr(p.description),\n }),\n );\n};\n\n// ---------------------------------------------------------------------------\n// Request body extraction\n// ---------------------------------------------------------------------------\n\nconst buildEncodingRecord = (\n encoding: Record<string, unknown> | undefined,\n): Record<string, EncodingObject> | undefined => {\n if (!encoding) return undefined;\n const out: Record<string, EncodingObject> = {};\n for (const [prop, raw] of Object.entries(encoding)) {\n if (typeof raw !== \"object\" || raw === null) continue;\n const e = raw as {\n contentType?: string;\n style?: string;\n explode?: boolean;\n allowReserved?: boolean;\n };\n out[prop] = EncodingObject.make({\n contentType: Option.fromNullishOr(e.contentType),\n style: Option.fromNullishOr(e.style),\n explode: Option.fromNullishOr(e.explode),\n allowReserved: Option.fromNullishOr(e.allowReserved),\n });\n }\n return Object.keys(out).length > 0 ? out : undefined;\n};\n\nconst extractRequestBody = (\n operation: OperationObject,\n r: DocResolver,\n): OperationRequestBody | undefined => {\n if (!operation.requestBody) return undefined;\n\n const body = r.resolve<RequestBodyObject>(operation.requestBody);\n if (!body) return undefined;\n\n const contents = declaredContents(body.content).map(({ mediaType, media }) =>\n MediaBinding.make({\n contentType: mediaType,\n schema: Option.fromNullishOr(media.schema),\n encoding: Option.fromNullishOr(\n buildEncodingRecord((media as { encoding?: Record<string, unknown> }).encoding),\n ),\n }),\n );\n if (contents.length === 0) return undefined;\n\n // Default = first declared (spec author's preferred order). Callers can\n // override at invoke time with a `contentType` arg.\n const defaultContent = contents[0]!;\n\n return OperationRequestBody.make({\n required: body.required === true,\n contentType: defaultContent.contentType,\n schema: defaultContent.schema,\n contents: Option.some(contents),\n });\n};\n\n// ---------------------------------------------------------------------------\n// Response schema extraction\n// ---------------------------------------------------------------------------\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst stringType = (schema: Record<string, unknown>): boolean =>\n schema.type === \"string\" || (Array.isArray(schema.type) && schema.type.includes(\"string\"));\n\nconst numericType = (schema: Record<string, unknown>): boolean =>\n schema.type === \"integer\" ||\n schema.type === \"number\" ||\n (Array.isArray(schema.type) &&\n (schema.type.includes(\"integer\") || schema.type.includes(\"number\")));\n\nconst normalizedMediaType = (mediaType: string): string =>\n mediaType.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n\nconst isJsonMediaType = (mediaType: string): boolean => {\n const normalized = normalizedMediaType(mediaType);\n return (\n normalized === \"application/json\" || normalized.includes(\"+json\") || normalized.includes(\"json\")\n );\n};\n\nconst binaryStringSchema = (schema: Record<string, unknown>): boolean =>\n stringType(schema) && (schema.format === \"binary\" || schema.format === \"byte\");\n\nconst base64EncodingFromDescription = (schema: Record<string, unknown>): \"base64\" | \"base64url\" =>\n typeof schema.description === \"string\" &&\n /base64url|base64-url|url[- ]safe/i.test(schema.description)\n ? \"base64url\"\n : \"base64\";\n\nconst detectFileHint = (\n schema: unknown,\n mediaType: string,\n r: DocResolver,\n): OperationFileHint | undefined => {\n const resolved = isRecord(schema) ? r.resolve<Record<string, unknown>>(schema) : null;\n if (!resolved) return undefined;\n\n if (!isJsonMediaType(mediaType) && binaryStringSchema(resolved)) {\n return OperationFileHint.make({\n kind: \"binaryResponse\",\n mimeType: Option.some(mediaType),\n dataField: Option.none(),\n sizeField: Option.none(),\n encoding: Option.none(),\n });\n }\n\n if (!isJsonMediaType(mediaType)) return undefined;\n\n const properties = resolved.properties;\n if (!isRecord(properties)) return undefined;\n const data = properties.data;\n const dataSchema = isRecord(data) ? r.resolve<Record<string, unknown>>(data) : null;\n if (!dataSchema || !binaryStringSchema(dataSchema)) return undefined;\n\n const size = properties.size;\n const sizeSchema = isRecord(size) ? r.resolve<Record<string, unknown>>(size) : null;\n const sizeField = sizeSchema && numericType(sizeSchema) ? \"size\" : undefined;\n\n return OperationFileHint.make({\n kind: \"byteField\",\n mimeType: Option.some(\"application/octet-stream\"),\n dataField: Option.some(\"data\"),\n sizeField: sizeField ? Option.some(sizeField) : Option.none(),\n encoding: Option.some(base64EncodingFromDescription(dataSchema)),\n });\n};\n\nconst extractResponseBody = (\n operation: OperationObject,\n r: DocResolver,\n): OperationResponseBody | undefined => {\n if (!operation.responses) return undefined;\n\n const entries = Object.entries(operation.responses);\n const preferred = [\n ...entries.filter(([s]) => /^2\\d\\d$/.test(s)).sort(([a], [b]) => a.localeCompare(b)),\n ...entries.filter(([s]) => s === \"default\"),\n ];\n\n for (const [, ref] of preferred) {\n const resp = r.resolve<ResponseObject>(ref);\n if (!resp) continue;\n const content = preferredResponseContent(resp.content);\n if (content?.media.schema) {\n return OperationResponseBody.make({\n contentType: content.mediaType,\n schema: Option.some(content.media.schema),\n fileHint: Option.fromNullishOr(detectFileHint(content.media.schema, content.mediaType, r)),\n });\n }\n }\n\n return undefined;\n};\n\n// ---------------------------------------------------------------------------\n// Input schema builder\n// ---------------------------------------------------------------------------\n\n// Optional `server` input — host selection + server-URL variables. Undefined\n// when there's nothing to configure (a single server with no variables).\nconst buildServerInputProperty = (\n servers: readonly ServerInfo[],\n): Record<string, unknown> | undefined => {\n const variableDefs: Record<string, ServerVariable> = {};\n for (const server of servers) {\n for (const [name, v] of Object.entries(Option.getOrUndefined(server.variables) ?? {})) {\n if (!(name in variableDefs)) variableDefs[name] = v;\n }\n }\n const hasMultiple = servers.length > 1;\n const variableNames = Object.keys(variableDefs);\n if (!hasMultiple && variableNames.length === 0) return undefined;\n\n const properties: Record<string, unknown> = {};\n if (hasMultiple) {\n properties.url = {\n type: \"string\",\n enum: servers.map((server) => server.url),\n default: servers[0]!.url,\n description: \"Which of the spec's servers to send the request to.\",\n };\n }\n if (variableNames.length > 0) {\n properties.variables = {\n type: \"object\",\n additionalProperties: false,\n properties: Object.fromEntries(\n Object.entries(variableDefs).map(([name, v]) => [\n name,\n {\n type: \"string\",\n default: v.default,\n ...(Option.isSome(v.enum) ? { enum: v.enum.value } : {}),\n ...(Option.isSome(v.description) ? { description: v.description.value } : {}),\n },\n ]),\n ),\n description: \"Values for the server URL `{variables}`; spec defaults apply when omitted.\",\n };\n }\n return {\n type: \"object\",\n additionalProperties: false,\n properties,\n description: \"Optional host selection and server-URL variables for this request.\",\n };\n};\n\nexport const buildInputSchema = (\n parameters: readonly OperationParameter[],\n requestBody: OperationRequestBody | undefined,\n servers: readonly ServerInfo[],\n): Record<string, unknown> | undefined => {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n let requiredBodyAlternatives: readonly { readonly required: readonly string[] }[] | undefined;\n\n for (const param of parameters) {\n properties[param.name] = Option.getOrElse(param.schema, () => ({ type: \"string\" }));\n if (param.required) required.push(param.name);\n }\n\n // A path/query parameter named `server` takes precedence over the host input.\n const serverProperty = buildServerInputProperty(servers);\n if (serverProperty && !(\"server\" in properties)) properties.server = serverProperty;\n\n if (requestBody) {\n // When the spec declares multiple media types for this requestBody,\n // expose `contentType` so the model can pick. Default = first declared.\n // For mixed bodies, `body` schema tracks the default; the model is\n // responsible for supplying a body shape that matches whichever\n // contentType it picks. Octet-only operations use `bodyBase64` instead.\n const contents = Option.getOrUndefined(requestBody.contents);\n const defaultIsOctetStream =\n requestBody.contentType.split(\";\")[0]?.trim().toLowerCase() === \"application/octet-stream\";\n const acceptsOctetStream =\n defaultIsOctetStream ||\n contents?.some(\n (content) =>\n content.contentType.split(\";\")[0]?.trim().toLowerCase() === \"application/octet-stream\",\n ) === true;\n const acceptsBody =\n !defaultIsOctetStream ||\n contents?.some(\n (content) =>\n content.contentType.split(\";\")[0]?.trim().toLowerCase() !== \"application/octet-stream\",\n ) === true;\n if (acceptsBody) {\n properties.body = Option.getOrElse(requestBody.schema, () => ({ type: \"object\" }));\n }\n if (acceptsOctetStream) {\n properties.bodyBase64 = {\n type: \"string\",\n contentEncoding: \"base64\",\n contentMediaType: \"application/octet-stream\",\n description:\n \"Base64-encoded bytes for application/octet-stream request bodies. When contentType is omitted, this selects application/octet-stream.\",\n };\n }\n if (requestBody.required) {\n if (acceptsOctetStream && acceptsBody) {\n requiredBodyAlternatives = [{ required: [\"body\"] }, { required: [\"bodyBase64\"] }];\n } else {\n required.push(acceptsOctetStream ? \"bodyBase64\" : \"body\");\n }\n }\n if (contents && contents.length > 1) {\n properties.contentType = {\n type: \"string\",\n enum: contents.map((c) => c.contentType),\n default: requestBody.contentType,\n description:\n \"Content-Type for the request body. Declared media types for this operation, in spec order.\",\n };\n }\n }\n\n if (Object.keys(properties).length === 0) return undefined;\n\n return {\n type: \"object\",\n properties,\n ...(required.length > 0 ? { required } : {}),\n ...(requiredBodyAlternatives ? { anyOf: requiredBodyAlternatives } : {}),\n additionalProperties: false,\n };\n};\n\n// ---------------------------------------------------------------------------\n// Operation ID derivation\n// ---------------------------------------------------------------------------\n\nconst deriveOperationId = (\n method: HttpMethod,\n pathTemplate: string,\n operation: OperationObject,\n): string =>\n operation.operationId ??\n (`${method}_${pathTemplate.replace(/[^a-zA-Z0-9]+/g, \"_\")}`.replace(/^_+|_+$/g, \"\") ||\n `${method}_operation`);\n\nconst explicitToolPath = (operation: OperationObject): string | undefined => {\n const value = (operation as Record<string, unknown>)[\"x-executor-toolPath\"];\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n};\n\nconst explicitPathTemplate = (operation: OperationObject): string | undefined => {\n const value = (operation as Record<string, unknown>)[\"x-executor-pathTemplate\"];\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n};\n\n// ---------------------------------------------------------------------------\n// Server extraction\n// ---------------------------------------------------------------------------\n\nconst extractServerList = (servers: readonly ServerObject[] | undefined): ServerInfo[] =>\n (servers ?? []).flatMap((server) => {\n if (!server.url) return [];\n const serverVariables = server.variables as\n | Record<\n string,\n {\n readonly default?: string;\n readonly enum?: readonly string[];\n readonly description?: string;\n }\n >\n | undefined;\n const vars = serverVariables\n ? Object.fromEntries(\n Object.entries(serverVariables).flatMap(([name, v]) => {\n if (v.default === undefined || v.default === null) return [];\n const enumValues = Array.isArray(v.enum)\n ? v.enum.filter((x): x is string => typeof x === \"string\")\n : undefined;\n return [\n [\n name,\n ServerVariable.make({\n default: String(v.default),\n enum:\n enumValues && enumValues.length > 0 ? Option.some(enumValues) : Option.none(),\n description: Option.fromNullishOr(v.description),\n }),\n ],\n ];\n }),\n )\n : undefined;\n return [\n ServerInfo.make({\n url: server.url,\n description: Option.fromNullishOr(server.description),\n variables: vars && Object.keys(vars).length > 0 ? Option.some(vars) : Option.none(),\n }),\n ];\n });\n\nconst extractServers = (doc: ParsedDocument): ServerInfo[] => extractServerList(doc.servers);\n\nconst operationServers = (\n pathItem: PathItemObject,\n operation: OperationObject,\n docServers: readonly ServerInfo[],\n): readonly ServerInfo[] => {\n const operationLevel = extractServerList(operation.servers);\n if (operationLevel.length > 0) return operationLevel;\n const pathLevel = extractServerList(pathItem.servers);\n if (pathLevel.length > 0) return pathLevel;\n return docServers;\n};\n\n// ---------------------------------------------------------------------------\n// Main extraction\n// ---------------------------------------------------------------------------\n\n/** Extract all operations from a bundled OpenAPI 3.x document */\nexport const extract = Effect.fn(\"OpenApi.extract\")(function* (doc: ParsedDocument) {\n const paths = doc.paths;\n if (!paths) {\n return yield* new OpenApiExtractionError({\n message: \"OpenAPI document has no paths defined\",\n });\n }\n\n const r = new DocResolver(doc);\n const docServers = extractServers(doc);\n const operations: ExtractedOperation[] = [];\n\n for (const [pathTemplate, pathItem] of Object.entries(paths).sort(([a], [b]) =>\n a.localeCompare(b),\n )) {\n if (!pathItem) continue;\n\n for (const method of HTTP_METHODS) {\n const operation = pathItem[method];\n if (!operation) continue;\n\n const parameters = extractParameters(pathItem, operation, r);\n const requestBody = extractRequestBody(operation, r);\n const responseBody = extractResponseBody(operation, r);\n const servers = operationServers(pathItem, operation, docServers);\n const inputSchema = buildInputSchema(parameters, requestBody, servers);\n const outputSchema = responseBody ? Option.getOrUndefined(responseBody.schema) : undefined;\n const tags = (operation.tags ?? []).filter((t) => t.trim().length > 0);\n const operationPathTemplate = explicitPathTemplate(operation) ?? pathTemplate;\n\n operations.push(\n ExtractedOperation.make({\n operationId: OperationId.make(deriveOperationId(method, pathTemplate, operation)),\n toolPath: Option.fromNullishOr(explicitToolPath(operation)),\n method,\n servers,\n pathTemplate: operationPathTemplate,\n summary: Option.fromNullishOr(operation.summary),\n description: Option.fromNullishOr(operation.description),\n tags,\n parameters,\n requestBody: Option.fromNullishOr(requestBody),\n responseBody: Option.fromNullishOr(responseBody),\n inputSchema: Option.fromNullishOr(inputSchema),\n outputSchema: Option.fromNullishOr(outputSchema),\n deprecated: operation.deprecated === true,\n }),\n );\n }\n }\n\n return ExtractionResult.make({\n title: Option.fromNullishOr(doc.info?.title),\n description: Option.fromNullishOr(doc.info?.description),\n version: Option.fromNullishOr(doc.info?.version),\n servers: docServers,\n operations,\n });\n});\n\n// ---------------------------------------------------------------------------\n// Streaming binding extraction\n// ---------------------------------------------------------------------------\n\n/** One persisted invocation binding plus the tool name and description it\n * backs. The description is the resolved operation description / summary /\n * method+path fallback, persisted so the serve path needs no re-parse. */\nexport interface OperationBindingChunk {\n readonly toolName: string;\n readonly description: string;\n readonly binding: OperationBinding;\n}\n\ninterface OperationRef {\n readonly pathItem: PathItemObject;\n readonly operation: OperationObject;\n readonly method: HttpMethod;\n /** Resolved path template (`x-executor-pathTemplate` override or the key). */\n readonly pathTemplate: string;\n}\n\n/**\n * Stream invocation bindings out of a parsed document in bounded chunks,\n * persisting each chunk via `onChunk` before building the next.\n *\n * This is the memory-safe compile path for huge specs (e.g. Microsoft Graph,\n * 16.5k operations / 37MB). It differs from `extract` + `compileToolDefinitions`\n * in two ways that keep peak memory at parse level rather than ~doubling it:\n *\n * 1. It never builds `hoistedDefs` or per-operation `inputSchema`/`outputSchema`\n * (the add path only needs invocation bindings, which carry `$ref`s, not\n * inlined schemas).\n * 2. It never holds all bindings at once. Tool-path planning needs a global\n * view, but only of lightweight metadata (`planToolPaths`, schema-free);\n * the heavy per-operation bindings are built, flushed, and dropped one\n * chunk at a time.\n *\n * Bindings reference subtrees of the parsed document rather than copying them,\n * so `onChunk` must sever those references (its storage layer JSON-serializes\n * the binding) before the chunk is dropped. Returns the resolved tool names in\n * sorted order, matching `compileToolDefinitions`.\n */\nexport const streamOperationBindings = <E, R>(\n doc: ParsedDocument,\n chunkSize: number,\n onChunk: (chunk: readonly OperationBindingChunk[]) => Effect.Effect<void, E, R>,\n): Effect.Effect<\n { readonly toolCount: number; readonly toolNames: readonly string[] },\n OpenApiExtractionError | E,\n R\n> =>\n Effect.gen(function* () {\n const paths = doc.paths;\n if (!paths) {\n return yield* new OpenApiExtractionError({\n message: \"OpenAPI document has no paths defined\",\n });\n }\n\n const r = new DocResolver(doc);\n const docServers = extractServers(doc);\n\n // Pass 1 (light): collect schema-free path metadata + a parallel array of\n // references back into the tree. Both are small (no schemas copied).\n const inputs: OperationPathInput[] = [];\n const opRefs: OperationRef[] = [];\n for (const [pathTemplate, pathItem] of Object.entries(paths).sort(([a], [b]) =>\n a.localeCompare(b),\n )) {\n if (!pathItem) continue;\n for (const method of HTTP_METHODS) {\n const operation = pathItem[method];\n if (!operation) continue;\n const resolvedPathTemplate = explicitPathTemplate(operation) ?? pathTemplate;\n const tags = (operation.tags ?? []).filter((t) => t.trim().length > 0);\n inputs.push({\n operationId: deriveOperationId(method, pathTemplate, operation),\n explicitToolPath: explicitToolPath(operation),\n method,\n pathTemplate: resolvedPathTemplate,\n tag0: tags[0],\n });\n opRefs.push({ pathItem, operation, method, pathTemplate: resolvedPathTemplate });\n }\n }\n\n // Global, schema-free collision resolution + sort. Cheap relative to the\n // parsed tree; returns plans sorted by toolPath with an index back into\n // `opRefs`.\n const plans = planToolPaths(inputs);\n\n // Pass 2 (heavy, streamed): build a binding per operation, flush a chunk\n // once it fills, then drop it. Bindings reference tree subtrees; `onChunk`\n // serializes them, so peak stays at parse level.\n let chunk: OperationBindingChunk[] = [];\n for (const plan of plans) {\n const ref = opRefs[plan.operationIndex]!;\n const parameters = extractParameters(ref.pathItem, ref.operation, r);\n const requestBody = extractRequestBody(ref.operation, r);\n const responseBody = extractResponseBody(ref.operation, r);\n const servers = operationServers(ref.pathItem, ref.operation, docServers);\n chunk.push({\n toolName: plan.toolPath,\n description:\n ref.operation.description ??\n ref.operation.summary ??\n `${ref.method.toUpperCase()} ${ref.pathTemplate}`,\n binding: OperationBinding.make({\n method: ref.method,\n servers,\n pathTemplate: ref.pathTemplate,\n parameters,\n requestBody: Option.fromNullishOr(requestBody),\n responseBody: Option.fromNullishOr(responseBody),\n }),\n });\n if (chunk.length >= chunkSize) {\n yield* onChunk(chunk);\n chunk = [];\n }\n }\n if (chunk.length > 0) yield* onChunk(chunk);\n\n return { toolCount: plans.length, toolNames: plans.map((plan) => plan.toolPath) };\n }).pipe(Effect.withSpan(\"OpenApi.streamOperationBindings\"));\n\nconst isPathItemValue = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n/**\n * Stream invocation bindings straight from a `SpecStructure` (the structural\n * split of a large spec) without ever materializing the whole-document tree.\n *\n * This is the fully-streaming compile path: it never parses the spec whole.\n * Each path-item is parsed in isolation twice (pass 1 for light tool-path\n * planning metadata, pass 2 to build the heavy binding) and discarded, so peak\n * memory stays near the size of a single path-item plus the raw text, even for\n * the 37MB / 16.5k-operation Microsoft Graph spec that OOMs a whole-tree parse.\n * Re-parsing in pass 2 (rather than holding pass-1 tree references) is the\n * deliberate CPU-for-memory trade that keeps peak at one-path-item level.\n *\n * `keepPathItem`, when given, filters (and may trim) each path-item, so the same\n * primitive serves both a full-spec compile (no filter) and a selection (e.g.\n * the Microsoft Graph scope filter) with identical streaming guarantees. It is\n * applied identically in both passes so the per-operation index stays aligned.\n *\n * Schemas are never resolved here: parameter / requestBody / response component\n * `$ref`s resolve against the small (schema-free) components built from the\n * structure; `#/components/schemas/X` refs stay as strings in the binding and\n * are normalized + served from the content-addressed defs blob. Returns the\n * resolved tool names in sorted order, matching `compileToolDefinitions`.\n */\nexport const streamOperationBindingsFromStructure = <E, R>(\n structure: SpecStructure,\n options: { readonly chunkSize: number; readonly keepPathItem?: KeepPathItem },\n onChunk: (chunk: readonly OperationBindingChunk[]) => Effect.Effect<void, E, R>,\n): Effect.Effect<{ readonly toolCount: number; readonly toolNames: readonly string[] }, E, R> =>\n Effect.gen(function* () {\n const { chunkSize, keepPathItem } = options;\n\n // Parse one path-item range to its kept (optionally trimmed) value, applying\n // `keepPathItem` identically in both passes so the operation index aligns.\n const keptPathItem = (range: ByteRange): readonly [string, PathItemObject] | null => {\n const entry = parseEntry(structure.text, range, 2);\n if (!entry) return null;\n const [path, rawValue] = entry;\n if (!isPathItemValue(rawValue)) return null;\n if (!keepPathItem) return [path, rawValue as PathItemObject];\n const kept = keepPathItem(path, rawValue);\n return kept ? [path, kept as PathItemObject] : null;\n };\n\n // Pass 1 (light): collect schema-free tool-path planning metadata in\n // document order. No bindings, no schemas; one path-item resident at a time.\n const inputs: OperationPathInput[] = [];\n for (const range of structure.pathItems) {\n const kept = keptPathItem(range);\n if (!kept) continue;\n const [path, pathItem] = kept;\n for (const method of HTTP_METHODS) {\n const operation = pathItem[method];\n if (!operation) continue;\n const resolvedPathTemplate = explicitPathTemplate(operation) ?? path;\n const tags = (operation.tags ?? []).filter((t) => t.trim().length > 0);\n inputs.push({\n operationId: deriveOperationId(method, path, operation),\n explicitToolPath: explicitToolPath(operation),\n method,\n pathTemplate: resolvedPathTemplate,\n tag0: tags[0],\n });\n }\n }\n\n // Global, schema-free collision resolution + sort. `plan.operationIndex`\n // indexes back into `inputs` (document order), so a flat array recovers each\n // operation's assigned tool path during the document-order pass 2.\n const plans = planToolPaths(inputs);\n const planByOpIndex: (PlannedToolPath | undefined)[] = new Array(inputs.length);\n for (const plan of plans) planByOpIndex[plan.operationIndex] = plan;\n\n // Pass 2 (heavy, streamed): re-parse each path-item in the same document\n // order, build a binding per operation, flush a chunk once it fills, then\n // drop it. The resolver is schema-free (small components only); schema refs\n // stay as `$ref` strings in the bindings.\n // oxlint-disable-next-line executor/no-double-cast -- boundary: parseHead/parseSmallComponents return Record<string, unknown>, which does not structurally match the OpenAPIV3 Document union; the schema-free resolver doc (head + small components, empty paths) is only read for .servers (extractServers) and .components ($ref resolution).\n const resolverDoc = {\n ...parseHead(structure),\n paths: {},\n components: parseSmallComponents(structure),\n } as unknown as ParsedDocument;\n const r = new DocResolver(resolverDoc);\n const docServers = extractServers(resolverDoc);\n\n let opIndex = 0;\n let chunk: OperationBindingChunk[] = [];\n for (const range of structure.pathItems) {\n const kept = keptPathItem(range);\n if (!kept) continue;\n const [path, pathItem] = kept;\n for (const method of HTTP_METHODS) {\n const operation = pathItem[method];\n if (!operation) continue;\n const plan = planByOpIndex[opIndex];\n opIndex += 1;\n if (!plan) continue;\n const resolvedPathTemplate = explicitPathTemplate(operation) ?? path;\n const parameters = extractParameters(pathItem, operation, r);\n const requestBody = extractRequestBody(operation, r);\n const responseBody = extractResponseBody(operation, r);\n const servers = operationServers(pathItem, operation, docServers);\n chunk.push({\n toolName: plan.toolPath,\n description:\n operation.description ??\n operation.summary ??\n `${method.toUpperCase()} ${resolvedPathTemplate}`,\n binding: OperationBinding.make({\n method,\n servers,\n pathTemplate: resolvedPathTemplate,\n parameters,\n requestBody: Option.fromNullishOr(requestBody),\n responseBody: Option.fromNullishOr(responseBody),\n }),\n });\n if (chunk.length >= chunkSize) {\n yield* onChunk(chunk);\n chunk = [];\n }\n }\n }\n if (chunk.length > 0) yield* onChunk(chunk);\n\n return { toolCount: plans.length, toolNames: plans.map((plan) => plan.toolPath) };\n }).pipe(Effect.withSpan(\"OpenApi.streamOperationBindingsFromStructure\"));\n","/**\n * Derives structured `group.leaf` tool paths from extracted OpenAPI operations.\n *\n * Ported from the v3 executor's `definitions.ts`. Turns flat operation IDs like\n * `zones_listZones` into nested paths like `zones.listZones` that the tree UI\n * can render with proper nesting.\n */\n\nimport { Option } from \"effect\";\n\nimport type { ExtractedOperation } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Word / case utilities\n// ---------------------------------------------------------------------------\n\nconst splitWords = (value: string): string[] =>\n value\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/([A-Z]+)([A-Z][a-z0-9]+)/g, \"$1 $2\")\n .replace(/[^a-zA-Z0-9]+/g, \" \")\n .trim()\n .split(/\\s+/)\n .filter((part) => part.length > 0);\n\nconst normalizeWord = (value: string): string => value.toLowerCase();\n\nconst toCamelCase = (value: string): string => {\n const words = splitWords(value).map(normalizeWord);\n if (words.length === 0) return \"tool\";\n const [first, ...rest] = words;\n return `${first}${rest.map((p) => `${p[0]?.toUpperCase() ?? \"\"}${p.slice(1)}`).join(\"\")}`;\n};\n\nconst toPascalCase = (value: string): string => {\n const camel = toCamelCase(value);\n return `${camel[0]?.toUpperCase() ?? \"\"}${camel.slice(1)}`;\n};\n\n// ---------------------------------------------------------------------------\n// Path utilities\n// ---------------------------------------------------------------------------\n\nconst VERSION_SEGMENT_REGEX = /^v\\d+(?:[._-]\\d+)?$/i;\nconst IGNORED_PATH_SEGMENTS = new Set([\"api\"]);\n\nconst pathSegmentsFromTemplate = (pathTemplate: string): string[] =>\n pathTemplate\n .split(\"/\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n\nconst isPathParameterSegment = (segment: string): boolean =>\n segment.startsWith(\"{\") && segment.endsWith(\"}\");\n\nconst normalizeGroupSegment = (value: string | undefined): string | null => {\n const candidate = value?.trim();\n if (!candidate) return null;\n return toCamelCase(candidate);\n};\n\n// ---------------------------------------------------------------------------\n// Derivation\n// ---------------------------------------------------------------------------\n\nconst deriveVersionSegment = (pathTemplate: string): string | undefined =>\n pathSegmentsFromTemplate(pathTemplate)\n .map((s) => s.toLowerCase())\n .find((s) => VERSION_SEGMENT_REGEX.test(s));\n\nconst derivePathGroup = (pathTemplate: string): string => {\n for (const segment of pathSegmentsFromTemplate(pathTemplate)) {\n const lower = segment.toLowerCase();\n if (VERSION_SEGMENT_REGEX.test(lower)) continue;\n if (IGNORED_PATH_SEGMENTS.has(lower)) continue;\n if (isPathParameterSegment(segment)) continue;\n return normalizeGroupSegment(segment) ?? \"root\";\n }\n return \"root\";\n};\n\nconst splitOperationIdSegments = (value: string): string[] =>\n value\n .split(/[/.]+/)\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n\nconst deriveLeafSeed = (operationId: string, group: string): string => {\n const segments = splitOperationIdSegments(operationId);\n if (segments.length > 1) {\n const [first, ...rest] = segments;\n if ((normalizeGroupSegment(first) ?? first) === group && rest.length > 0) {\n return rest.join(\" \");\n }\n }\n return operationId;\n};\n\nconst fallbackLeafSeed = (method: string, pathTemplate: string, group: string): string => {\n const relevantSegments = pathSegmentsFromTemplate(pathTemplate)\n .filter((s) => !VERSION_SEGMENT_REGEX.test(s.toLowerCase()))\n .filter((s) => !IGNORED_PATH_SEGMENTS.has(s.toLowerCase()))\n .filter((s) => !isPathParameterSegment(s))\n .map((s) => normalizeGroupSegment(s) ?? s)\n .filter((s) => s !== group);\n\n const segmentSuffix = relevantSegments.map((s) => toPascalCase(s)).join(\"\");\n return `${method}${segmentSuffix || \"Operation\"}`;\n};\n\nconst deriveLeaf = (\n operationId: string,\n method: string,\n pathTemplate: string,\n group: string,\n): string => {\n const preferred = toCamelCase(deriveLeafSeed(operationId, group));\n if (preferred.length > 0 && preferred !== group) return preferred;\n return toCamelCase(fallbackLeafSeed(method, pathTemplate, group));\n};\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport interface ToolDefinition {\n /** Dot-separated path like `zones.listZones` */\n readonly toolPath: string;\n /** The group segment */\n readonly group: string;\n /** The leaf segment */\n readonly leaf: string;\n /** Index into the original operations array */\n readonly operationIndex: number;\n /** The original operation */\n readonly operation: ExtractedOperation;\n}\n\n/**\n * The minimal per-operation metadata the tool-path planner needs. Kept\n * deliberately light (no schemas) so the streaming compile path can plan paths\n * for tens of thousands of operations without holding the full extracted\n * operations in memory.\n */\nexport interface OperationPathInput {\n readonly operationId: string;\n readonly explicitToolPath: string | undefined;\n readonly method: string;\n readonly pathTemplate: string;\n /** The first non-empty tag, used to seed the group segment. */\n readonly tag0: string | undefined;\n}\n\n/** A resolved tool path plus its index back into the input operations array. */\nexport interface PlannedToolPath {\n readonly toolPath: string;\n readonly group: string;\n readonly leaf: string;\n readonly operationIndex: number;\n}\n\n// ---------------------------------------------------------------------------\n// Collision resolution\n// ---------------------------------------------------------------------------\n\ninterface RawToolPath {\n toolPath: string;\n group: string;\n leaf: string;\n versionSegment: string | undefined;\n method: string;\n operationHash: string;\n operationIndex: number;\n}\n\nconst resolveCollisions = (definitions: RawToolPath[]): PlannedToolPath[] => {\n // Mutable — we progressively refine toolPath on collision\n const staged = definitions.map((d) => ({ ...d }));\n\n const applyFactory = (items: typeof staged, factory: (d: (typeof staged)[number]) => string) => {\n const byPath = new Map<string, typeof staged>();\n for (const item of items) {\n const bucket = byPath.get(item.toolPath) ?? [];\n bucket.push(item);\n byPath.set(item.toolPath, bucket);\n }\n for (const bucket of byPath.values()) {\n if (bucket.length < 2) continue;\n for (const d of bucket) {\n d.toolPath = factory(d);\n }\n }\n };\n\n // Round 1: add version segment\n applyFactory(staged, (d) =>\n d.versionSegment ? `${d.group}.${d.versionSegment}.${d.leaf}` : d.toolPath,\n );\n\n // Round 2: add method suffix\n applyFactory(staged, (d) => {\n const prefix = d.versionSegment ? `${d.group}.${d.versionSegment}` : d.group;\n return `${prefix}.${d.leaf}${toPascalCase(d.method)}`;\n });\n\n // Round 3: add hash suffix\n applyFactory(staged, (d) => {\n const prefix = d.versionSegment ? `${d.group}.${d.versionSegment}` : d.group;\n return `${prefix}.${d.leaf}${toPascalCase(d.method)}${d.operationHash.slice(0, 8)}`;\n });\n\n return staged.map((d) => ({\n toolPath: d.toolPath,\n group: d.group,\n leaf: d.leaf,\n operationIndex: d.operationIndex,\n }));\n};\n\n// ---------------------------------------------------------------------------\n// Stable hash (simple, deterministic)\n// ---------------------------------------------------------------------------\n\nconst stableHash = (value: unknown): string => {\n const str = JSON.stringify(value, Object.keys(value as Record<string, unknown>).sort());\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) - hash + str.charCodeAt(i)) | 0;\n }\n return Math.abs(hash).toString(36).padStart(8, \"0\");\n};\n\n// ---------------------------------------------------------------------------\n// Main entry point\n// ---------------------------------------------------------------------------\n\n/**\n * Plan structured `group.leaf` tool paths from lightweight per-operation\n * metadata. Path derivation + collision resolution need a global view of every\n * operation, but only its name/method/path/tag, never its schemas. Keeping this\n * pass schema-free lets the streaming compile path plan paths for a 16k-op spec\n * without materializing the full extracted operations.\n *\n * The returned `operationIndex` points back into the `inputs` array.\n */\nexport const planToolPaths = (inputs: readonly OperationPathInput[]): PlannedToolPath[] => {\n const raw: RawToolPath[] = inputs.map((op, index) => {\n const operationId = op.operationId;\n const operationHash = stableHash({\n method: op.method,\n path: op.pathTemplate,\n operationId,\n });\n const versionSegment = deriveVersionSegment(op.pathTemplate);\n\n if (op.explicitToolPath) {\n const [group = \"root\", ...leafParts] = op.explicitToolPath.split(\".\").filter(Boolean);\n const leaf = leafParts.join(\".\") || group;\n return {\n toolPath: op.explicitToolPath,\n group,\n leaf,\n versionSegment,\n method: op.method,\n operationHash,\n operationIndex: index,\n };\n }\n\n const group = normalizeGroupSegment(op.tag0) ?? derivePathGroup(op.pathTemplate);\n const leaf = deriveLeaf(operationId, op.method, op.pathTemplate, group);\n return {\n toolPath: `${group}.${leaf}`,\n group,\n leaf,\n versionSegment,\n method: op.method,\n operationHash,\n operationIndex: index,\n };\n });\n\n return resolveCollisions(raw).sort((a, b) => a.toolPath.localeCompare(b.toolPath));\n};\n\n/**\n * Compile extracted operations into tool definitions with structured\n * `group.leaf` paths suitable for tree rendering. Thin wrapper over\n * `planToolPaths` that re-attaches each operation by index.\n */\nexport const compileToolDefinitions = (\n operations: readonly ExtractedOperation[],\n): ToolDefinition[] => {\n const plans = planToolPaths(\n operations.map((op) => ({\n operationId: op.operationId,\n explicitToolPath: Option.getOrUndefined(op.toolPath),\n method: op.method,\n pathTemplate: op.pathTemplate,\n tag0: op.tags[0],\n })),\n );\n\n return plans.map((plan) => ({\n toolPath: plan.toolPath,\n group: plan.group,\n leaf: plan.leaf,\n operationIndex: plan.operationIndex,\n operation: operations[plan.operationIndex]!,\n }));\n};\n","import { Effect, Option, Predicate } from \"effect\";\nimport { Schema } from \"effect\";\n\nimport { parse, resolveSpecText, type ParsedDocument } from \"./parse\";\nimport { extract } from \"./extract\";\nimport { DocResolver } from \"./openapi-utils\";\nimport { HttpMethod, ServerInfo, type ExtractionResult } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// OAuth 2.0 flows — one entry per supported grant type\n// ---------------------------------------------------------------------------\n\n/** Scopes declared by a flow: `{ scopeName: description }` */\nconst OAuth2Scopes = Schema.Record(Schema.String, Schema.String);\nconst SecuritySchemeType = Schema.Literals([\"http\", \"apiKey\", \"oauth2\", \"openIdConnect\"]);\ntype SecuritySchemeType = typeof SecuritySchemeType.Type;\n\nconst decodeSecuritySchemeType = Schema.decodeUnknownOption(SecuritySchemeType);\n\nexport const OAuth2AuthorizationCodeFlow = Schema.Struct({\n authorizationUrl: Schema.String,\n tokenUrl: Schema.String,\n refreshUrl: Schema.OptionFromOptional(Schema.String),\n scopes: OAuth2Scopes,\n});\nexport type OAuth2AuthorizationCodeFlow = typeof OAuth2AuthorizationCodeFlow.Type;\n\nexport const OAuth2ClientCredentialsFlow = Schema.Struct({\n tokenUrl: Schema.String,\n refreshUrl: Schema.OptionFromOptional(Schema.String),\n scopes: OAuth2Scopes,\n});\nexport type OAuth2ClientCredentialsFlow = typeof OAuth2ClientCredentialsFlow.Type;\n\nexport const OAuth2Flows = Schema.Struct({\n authorizationCode: Schema.OptionFromOptional(OAuth2AuthorizationCodeFlow),\n clientCredentials: Schema.OptionFromOptional(OAuth2ClientCredentialsFlow),\n});\nexport type OAuth2Flows = typeof OAuth2Flows.Type;\n\n// ---------------------------------------------------------------------------\n// Security scheme — what the spec declares it needs\n// ---------------------------------------------------------------------------\n\nexport const SecurityScheme = Schema.Struct({\n /** Key name in components.securitySchemes (e.g. \"api_token\") */\n name: Schema.String,\n /** OpenAPI security scheme type */\n type: SecuritySchemeType,\n /** For type: \"http\" — e.g. \"bearer\", \"basic\" */\n scheme: Schema.OptionFromOptional(Schema.String),\n /** For type: \"http\" with scheme \"bearer\" — e.g. \"JWT\" */\n bearerFormat: Schema.OptionFromOptional(Schema.String),\n /** For type: \"apiKey\" — where the key goes */\n in: Schema.OptionFromOptional(Schema.Literals([\"header\", \"query\", \"cookie\"])),\n /** For type: \"apiKey\" — the header/query/cookie name */\n headerName: Schema.OptionFromOptional(Schema.String),\n description: Schema.OptionFromOptional(Schema.String),\n /** For type: \"oauth2\" — declared flows (authorizationCode / clientCredentials only; implicit and password are deprecated). */\n flows: Schema.OptionFromOptional(OAuth2Flows),\n /** For type: \"openIdConnect\" — the discovery URL. */\n openIdConnectUrl: Schema.OptionFromOptional(Schema.String),\n});\nexport type SecurityScheme = typeof SecurityScheme.Type;\n\n// ---------------------------------------------------------------------------\n// Auth strategy — a valid combination of security schemes\n// ---------------------------------------------------------------------------\n\nexport const AuthStrategy = Schema.Struct({\n /** The security schemes required together for this strategy */\n schemes: Schema.Array(Schema.String),\n});\nexport type AuthStrategy = typeof AuthStrategy.Type;\n\n// ---------------------------------------------------------------------------\n// Header preset — derived from an auth strategy\n// ---------------------------------------------------------------------------\n\nexport const HeaderPreset = Schema.Struct({\n /** Human-readable label for the UI (e.g. \"Bearer Token\", \"API Key + Email\") */\n label: Schema.String,\n /** Headers this strategy needs. Value is null when the user must provide it. */\n headers: Schema.Record(Schema.String, Schema.NullOr(Schema.String)),\n /** Which headers should be stored as secrets */\n secretHeaders: Schema.Array(Schema.String),\n});\nexport type HeaderPreset = typeof HeaderPreset.Type;\n\n// ---------------------------------------------------------------------------\n// OAuth2 preset — derived from an oauth2 security scheme + a flow choice\n// ---------------------------------------------------------------------------\n\nexport const OAuth2Preset = Schema.Struct({\n /** Human-readable label for the UI (e.g. \"OAuth2 (Authorization Code) — oauth_app\") */\n label: Schema.String,\n /** The source security scheme this preset came from (components.securitySchemes key). */\n securitySchemeName: Schema.String,\n /** Which OAuth2 flow this preset uses. */\n flow: Schema.Literals([\"authorizationCode\", \"clientCredentials\"]),\n /** For authorizationCode: user-agent redirect URL (from the spec). */\n authorizationUrl: Schema.OptionFromOptional(Schema.String),\n /** Token endpoint to exchange the code / refresh. */\n tokenUrl: Schema.String,\n /** Optional refresh endpoint if the spec declares one separately. */\n refreshUrl: Schema.OptionFromOptional(Schema.String),\n /** Declared scopes for this flow: `{ scope: description }`. */\n scopes: Schema.Record(Schema.String, Schema.String),\n /** Identity scopes to request alongside API scopes. `\"auto\"` discovers standard OIDC scopes. */\n identityScopes: Schema.Union([\n Schema.Literal(\"auto\"),\n Schema.Literal(false),\n Schema.Array(Schema.String),\n ]),\n});\nexport type OAuth2Preset = typeof OAuth2Preset.Type;\n\n// ---------------------------------------------------------------------------\n// Preview operation — lightweight shape for the add-source UI list\n// ---------------------------------------------------------------------------\n\nexport const PreviewOperation = Schema.Struct({\n operationId: Schema.String,\n method: HttpMethod,\n path: Schema.String,\n summary: Schema.OptionFromOptional(Schema.String),\n tags: Schema.Array(Schema.String),\n deprecated: Schema.Boolean,\n});\nexport type PreviewOperation = typeof PreviewOperation.Type;\n\n// ---------------------------------------------------------------------------\n// Spec preview — everything the frontend needs\n// ---------------------------------------------------------------------------\n\nexport const SpecPreview = Schema.Struct({\n title: Schema.OptionFromOptional(Schema.String),\n /** The spec's `info.description` — prefills the add form's description field. */\n description: Schema.OptionFromOptional(Schema.String),\n version: Schema.OptionFromOptional(Schema.String),\n /** Reuses ServerInfo from extraction */\n servers: Schema.Array(ServerInfo),\n operationCount: Schema.Number,\n /** Lightweight operation list for the add-source UI */\n operations: Schema.Array(PreviewOperation),\n tags: Schema.Array(Schema.String),\n securitySchemes: Schema.Array(SecurityScheme),\n /** Valid auth strategies (each is a set of schemes used together) */\n authStrategies: Schema.Array(AuthStrategy),\n /** Pre-built header presets derived from auth strategies */\n headerPresets: Schema.Array(HeaderPreset),\n /** OAuth2 presets — one per (oauth2 scheme × supported flow) combination */\n oauth2Presets: Schema.Array(OAuth2Preset),\n});\nexport type SpecPreview = typeof SpecPreview.Type;\n\n// HTTP/UI preview deliberately omits the per-operation list. Graph-sized specs\n// can define 16k+ operations, while the add flow only needs counts, tags,\n// servers, and auth metadata before registration.\nexport const SpecPreviewSummary = Schema.Struct({\n title: Schema.OptionFromOptional(Schema.String),\n description: Schema.OptionFromOptional(Schema.String),\n version: Schema.OptionFromOptional(Schema.String),\n servers: Schema.Array(ServerInfo),\n operationCount: Schema.Number,\n tags: Schema.Array(Schema.String),\n securitySchemes: Schema.Array(SecurityScheme),\n authStrategies: Schema.Array(AuthStrategy),\n headerPresets: Schema.Array(HeaderPreset),\n oauth2Presets: Schema.Array(OAuth2Preset),\n});\nexport type SpecPreviewSummary = typeof SpecPreviewSummary.Type;\n\nexport const specPreviewSummary = (preview: SpecPreview): SpecPreviewSummary =>\n SpecPreviewSummary.make({\n title: preview.title,\n description: preview.description,\n version: preview.version,\n servers: preview.servers,\n operationCount: preview.operationCount,\n tags: preview.tags,\n securitySchemes: preview.securitySchemes,\n authStrategies: preview.authStrategies,\n headerPresets: preview.headerPresets,\n oauth2Presets: preview.oauth2Presets,\n });\n\n// ---------------------------------------------------------------------------\n// Security scheme extraction\n// ---------------------------------------------------------------------------\n\nconst stringRecord = (value: unknown): Record<string, string> => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (typeof v === \"string\") out[k] = v;\n }\n return out;\n};\n\nconst extractFlows = (rawFlows: unknown): Option.Option<OAuth2Flows> => {\n if (!rawFlows || typeof rawFlows !== \"object\") return Option.none();\n const flows = rawFlows as Record<string, unknown>;\n\n const parseFlow = <K extends \"authorizationCode\" | \"clientCredentials\">(key: K): unknown =>\n flows[key];\n\n let authorizationCode: Option.Option<OAuth2AuthorizationCodeFlow> = Option.none();\n const authCodeRaw = parseFlow(\"authorizationCode\");\n if (authCodeRaw && typeof authCodeRaw === \"object\") {\n const f = authCodeRaw as Record<string, unknown>;\n const authUrl = typeof f.authorizationUrl === \"string\" ? f.authorizationUrl : null;\n const tokenUrl = typeof f.tokenUrl === \"string\" ? f.tokenUrl : null;\n if (authUrl && tokenUrl) {\n authorizationCode = Option.some(\n OAuth2AuthorizationCodeFlow.make({\n authorizationUrl: authUrl,\n tokenUrl,\n refreshUrl: Option.fromNullishOr(\n typeof f.refreshUrl === \"string\" ? f.refreshUrl : undefined,\n ),\n scopes: stringRecord(f.scopes),\n }),\n );\n }\n }\n\n let clientCredentials: Option.Option<OAuth2ClientCredentialsFlow> = Option.none();\n const ccRaw = parseFlow(\"clientCredentials\");\n if (ccRaw && typeof ccRaw === \"object\") {\n const f = ccRaw as Record<string, unknown>;\n const tokenUrl = typeof f.tokenUrl === \"string\" ? f.tokenUrl : null;\n if (tokenUrl) {\n clientCredentials = Option.some(\n OAuth2ClientCredentialsFlow.make({\n tokenUrl,\n refreshUrl: Option.fromNullishOr(\n typeof f.refreshUrl === \"string\" ? f.refreshUrl : undefined,\n ),\n scopes: stringRecord(f.scopes),\n }),\n );\n }\n }\n\n if (Option.isNone(authorizationCode) && Option.isNone(clientCredentials)) {\n return Option.none();\n }\n return Option.some(OAuth2Flows.make({ authorizationCode, clientCredentials }));\n};\n\nconst extractSecuritySchemes = (\n rawSchemes: Record<string, unknown>,\n resolver: DocResolver,\n): SecurityScheme[] =>\n Object.entries(rawSchemes).flatMap(([name, schemeOrRef]) => {\n if (!schemeOrRef || typeof schemeOrRef !== \"object\") return [];\n // Resolve $ref so schemes defined via `$ref` aren't silently dropped.\n const resolved = resolver.resolve<Record<string, unknown>>(\n schemeOrRef as Record<string, unknown>,\n );\n if (!resolved || typeof resolved !== \"object\") return [];\n const scheme = resolved;\n\n const type = decodeSecuritySchemeType(scheme.type);\n if (Option.isNone(type)) return [];\n const schemeType = type.value;\n\n return [\n SecurityScheme.make({\n name,\n type: schemeType,\n scheme: Option.fromNullishOr(scheme.scheme as string | undefined),\n bearerFormat: Option.fromNullishOr(scheme.bearerFormat as string | undefined),\n in: Option.fromNullishOr(scheme.in as \"header\" | \"query\" | \"cookie\" | undefined),\n headerName: Option.fromNullishOr(scheme.name as string | undefined),\n description: Option.fromNullishOr(scheme.description as string | undefined),\n flows: schemeType === \"oauth2\" ? extractFlows(scheme.flows) : Option.none(),\n openIdConnectUrl: Option.fromNullishOr(scheme.openIdConnectUrl as string | undefined),\n }),\n ];\n });\n\n// ---------------------------------------------------------------------------\n// Header preset builder\n// ---------------------------------------------------------------------------\n\nconst buildHeaderPresets = (\n schemes: readonly SecurityScheme[],\n strategies: readonly AuthStrategy[],\n): HeaderPreset[] => {\n const schemeMap = new Map(schemes.map((s) => [s.name, s]));\n\n return strategies.flatMap((strategy) => {\n const resolved = strategy.schemes\n .map((name) => schemeMap.get(name))\n .filter(Predicate.isNotUndefined);\n\n if (resolved.length === 0) return [];\n\n const headers: Record<string, string | null> = {};\n const secretHeaders: string[] = [];\n const labelParts: string[] = [];\n\n for (const scheme of resolved) {\n if (scheme.type === \"http\" && Option.getOrElse(scheme.scheme, () => \"\") === \"bearer\") {\n headers[\"Authorization\"] = null;\n secretHeaders.push(\"Authorization\");\n labelParts.push(\"Bearer Token\");\n } else if (scheme.type === \"http\" && Option.getOrElse(scheme.scheme, () => \"\") === \"basic\") {\n headers[\"Authorization\"] = null;\n secretHeaders.push(\"Authorization\");\n labelParts.push(\"Basic Auth\");\n } else if (scheme.type === \"apiKey\" && Option.getOrElse(scheme.in, () => \"\") === \"header\") {\n const headerName = Option.getOrElse(scheme.headerName, () => scheme.name);\n headers[headerName] = null;\n secretHeaders.push(headerName);\n labelParts.push(scheme.name);\n } else if (scheme.type === \"apiKey\") {\n labelParts.push(`${scheme.name} (${Option.getOrElse(scheme.in, () => \"unknown\")})`);\n } else if (scheme.type === \"oauth2\" || scheme.type === \"openIdConnect\") {\n return [];\n } else {\n labelParts.push(scheme.name);\n }\n }\n\n if (Object.keys(headers).length === 0 && resolved.length > 0) {\n return [\n HeaderPreset.make({\n label: labelParts.join(\" + \"),\n headers: {},\n secretHeaders: [],\n }),\n ];\n }\n\n return [\n HeaderPreset.make({\n label: labelParts.join(\" + \"),\n headers,\n secretHeaders,\n }),\n ];\n });\n};\n\n// ---------------------------------------------------------------------------\n// OAuth2 preset builder\n// ---------------------------------------------------------------------------\n\nconst buildOAuth2Presets = (schemes: readonly SecurityScheme[]): OAuth2Preset[] => {\n const presets: OAuth2Preset[] = [];\n for (const scheme of schemes) {\n if (scheme.type !== \"oauth2\") continue;\n if (Option.isNone(scheme.flows)) continue;\n const flows = scheme.flows.value;\n\n if (Option.isSome(flows.authorizationCode)) {\n const flow = flows.authorizationCode.value;\n presets.push(\n OAuth2Preset.make({\n label: `OAuth2 Authorization Code · ${scheme.name}`,\n securitySchemeName: scheme.name,\n flow: \"authorizationCode\",\n authorizationUrl: Option.some(flow.authorizationUrl),\n tokenUrl: flow.tokenUrl,\n refreshUrl: flow.refreshUrl,\n scopes: flow.scopes,\n identityScopes: \"auto\",\n }),\n );\n }\n\n if (Option.isSome(flows.clientCredentials)) {\n const flow = flows.clientCredentials.value;\n presets.push(\n OAuth2Preset.make({\n label: `OAuth2 Client Credentials · ${scheme.name}`,\n securitySchemeName: scheme.name,\n flow: \"clientCredentials\",\n authorizationUrl: Option.none(),\n tokenUrl: flow.tokenUrl,\n refreshUrl: flow.refreshUrl,\n scopes: flow.scopes,\n identityScopes: false,\n }),\n );\n }\n }\n return presets;\n};\n\n// ---------------------------------------------------------------------------\n// Collect unique tags from extraction result\n// ---------------------------------------------------------------------------\n\nconst collectTags = (result: ExtractionResult): string[] => {\n const tagSet = new Set<string>();\n for (const op of result.operations) {\n for (const tag of op.tags) tagSet.add(tag);\n }\n return [...tagSet].sort();\n};\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/** Preview already-resolved spec text — extract metadata without registering\n * anything and without any HTTP dependency. */\nexport const previewSpecText = Effect.fn(\"OpenApi.previewSpecText\")(function* (specText: string) {\n const doc: ParsedDocument = yield* parse(specText);\n const result = yield* extract(doc);\n\n const resolver = new DocResolver(doc);\n const securitySchemes = extractSecuritySchemes(doc.components?.securitySchemes ?? {}, resolver);\n\n const rawSecurity = (doc.security ?? []) as Array<Record<string, unknown>>;\n const declaredStrategies = rawSecurity.map((entry) =>\n AuthStrategy.make({ schemes: Object.keys(entry) }),\n );\n // Fall back to one strategy per scheme when the spec only declares schemes\n // under components (e.g. Sentry) so the user still sees auth options.\n const authStrategies =\n declaredStrategies.length > 0\n ? declaredStrategies\n : securitySchemes.map((scheme) => AuthStrategy.make({ schemes: [scheme.name] }));\n\n return SpecPreview.make({\n title: result.title,\n description: result.description,\n version: result.version,\n servers: result.servers,\n operationCount: result.operations.length,\n operations: result.operations.map((op) =>\n PreviewOperation.make({\n operationId: op.operationId,\n method: op.method,\n path: op.pathTemplate,\n summary: op.summary,\n tags: op.tags,\n deprecated: op.deprecated,\n }),\n ),\n tags: collectTags(result),\n securitySchemes,\n authStrategies,\n headerPresets: buildHeaderPresets(securitySchemes, authStrategies),\n oauth2Presets: buildOAuth2Presets(securitySchemes),\n });\n});\n\n/** Preview an OpenAPI spec — extract metadata without registering anything.\n * Accepts either a URL or raw JSON/YAML text. */\nexport const previewSpec = Effect.fn(\"OpenApi.previewSpec\")(function* (input: string) {\n const specText = yield* resolveSpecText(input);\n return yield* previewSpecText(specText);\n});\n"],"mappings":";AAAA,SAAS,MAAM,cAAc;AAWtB,IAAM,oBAAN,cAAgC,OAAO,iBAAoC;AAAA,EAChF;AAAA,EACA;AAAA,IACE,SAAS,OAAO;AAAA,EAClB;AAAA,EACA,EAAE,eAAe,IA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C,UAC1C,aAAa,KAAK,EAAE,SAAS,OAAO,KAAK,KAAK,EAAE,CAAC;AAAA,EACnD;AAGA,QAAM,iBACJ,mBAAmB,SAAS,IACxB,qBACA,gBAAgB,IAAI,CAAC,WAAW,aAAa,KAAK,EAAE,SAAS,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC;AAEnF,SAAO,YAAY,KAAK;AAAA,IACtB,OAAO,OAAO;AAAA,IACd,aAAa,OAAO;AAAA,IACpB,SAAS,OAAO;AAAA,IAChB,SAAS,OAAO;AAAA,IAChB,gBAAgB,OAAO,WAAW;AAAA,IAClC,YAAY,OAAO,WAAW;AAAA,MAAI,CAAC,OACjC,iBAAiB,KAAK;AAAA,QACpB,aAAa,GAAG;AAAA,QAChB,QAAQ,GAAG;AAAA,QACX,MAAM,GAAG;AAAA,QACT,SAAS,GAAG;AAAA,QACZ,MAAM,GAAG;AAAA,QACT,YAAY,GAAG;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,IACA,MAAM,YAAY,MAAM;AAAA,IACxB;AAAA,IACA;AAAA,IACA,eAAe,mBAAmB,iBAAiB,cAAc;AAAA,IACjE,eAAe,mBAAmB,eAAe;AAAA,EACnD,CAAC;AACH,CAAC;AAIM,IAAM,cAAcA,QAAO,GAAG,qBAAqB,EAAE,WAAW,OAAe;AACpF,QAAM,WAAW,OAAO,gBAAgB,KAAK;AAC7C,SAAO,OAAO,gBAAgB,QAAQ;AACxC,CAAC;","names":["Schema","Schema","parseYaml","JSON_SCHEMA","parseYamlDocument","Schema","Effect","Option","group","leaf","Option","Effect","Effect","Option","Schema","Schema","Option","Effect"]}
1
+ {"version":3,"sources":["../src/sdk/errors.ts","../src/sdk/parse.ts","../src/sdk/split.ts","../src/sdk/openapi-utils.ts","../src/sdk/types.ts","../src/sdk/extract.ts","../src/sdk/definitions.ts","../src/sdk/preview.ts"],"sourcesContent":["import { Data, Schema } from \"effect\";\nimport type { Option } from \"effect\";\nimport type { AuthToolFailureCode } from \"@executor-js/sdk/core\";\n\n// HTTP status lives on the class declaration so HttpApiBuilder's error\n// encoder (which reads `ast.annotations` off the schema it stored on\n// `group.addError(...)`) finds it. Applying the annotation post-hoc\n// via `.annotate(...)` in group.ts produced a transform-wrapper AST\n// whose status was not picked up — the error then slipped the typed\n// channel and was captured as a 500 by the observability middleware,\n// spamming Sentry on user misconfig.\nexport class OpenApiParseError extends Schema.TaggedErrorClass<OpenApiParseError>()(\n \"OpenApiParseError\",\n {\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n\nexport class OpenApiExtractionError extends Schema.TaggedErrorClass<OpenApiExtractionError>()(\n \"OpenApiExtractionError\",\n {\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n\nexport class OpenApiInvocationError extends Data.TaggedError(\"OpenApiInvocationError\")<{\n readonly message: string;\n readonly statusCode: Option.Option<number>;\n readonly cause?: unknown;\n}> {}\n\nexport class OpenApiOAuthError extends Schema.TaggedErrorClass<OpenApiOAuthError>()(\n \"OpenApiOAuthError\",\n {\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n\n// ---------------------------------------------------------------------------\n// Auth required — v2 reframes this around the connection (owner/integration/\n// name) that supplies the missing credential, not v1's source/slot/secret.\n// ---------------------------------------------------------------------------\n\nexport class OpenApiAuthRequiredError extends Data.TaggedError(\"OpenApiAuthRequiredError\")<{\n readonly code: AuthToolFailureCode;\n readonly message: string;\n readonly owner: \"org\" | \"user\";\n readonly integration: string;\n readonly connection: string;\n readonly credentialKind: \"secret\" | \"oauth\" | \"upstream\";\n readonly credentialLabel?: string;\n readonly status?: number;\n readonly details?: unknown;\n readonly cause?: unknown;\n}> {}\n","import type { OpenAPI, OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\nimport { Duration, Effect, Schema } from \"effect\";\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\";\nimport { JSON_SCHEMA, load as parseYamlDocument } from \"js-yaml\";\n\nimport { OpenApiExtractionError, OpenApiParseError } from \"./errors\";\n\nexport type ParsedDocument = OpenAPIV3.Document | OpenAPIV3_1.Document;\n\nexport interface SpecFetchCredentials {\n readonly headers?: Record<string, string>;\n readonly queryParams?: Record<string, string>;\n}\n\n// ExtractionError subclass raised from parse() for non-3.x specs\nclass OpenApiExtractionErrorFromParse extends OpenApiExtractionError {}\n\n/**\n * Fetch an OpenAPI spec URL and return its body text. Uses the Effect\n * HttpClient so the caller chooses the transport via layer — in Cloudflare\n * Workers, `FetchHttpClient.layer` binds to the Workers-native `fetch`.\n * Bounded by a 60s timeout.\n */\nexport const fetchSpecText = Effect.fn(\"OpenApi.fetchSpecText\")(function* (\n url: string,\n credentials?: SpecFetchCredentials,\n) {\n const client = yield* HttpClient.HttpClient;\n const requestUrl = new URL(url);\n for (const [name, value] of Object.entries(credentials?.queryParams ?? {})) {\n requestUrl.searchParams.set(name, value);\n }\n let request = HttpClientRequest.get(requestUrl.toString()).pipe(\n HttpClientRequest.setHeader(\"Accept\", \"application/json, application/yaml, text/yaml, */*\"),\n );\n for (const [name, value] of Object.entries(credentials?.headers ?? {})) {\n request = HttpClientRequest.setHeader(request, name, value);\n }\n const response = yield* client.execute(request).pipe(\n Effect.timeout(Duration.seconds(60)),\n Effect.mapError(\n (_cause) =>\n new OpenApiParseError({\n message: \"Failed to fetch OpenAPI document\",\n }),\n ),\n );\n if (response.status < 200 || response.status >= 300) {\n return yield* new OpenApiParseError({\n message: `Failed to fetch OpenAPI document: HTTP ${response.status}`,\n });\n }\n const specText = yield* response.text.pipe(\n Effect.mapError(\n (_cause) =>\n new OpenApiParseError({\n message: \"Failed to read OpenAPI document body\",\n }),\n ),\n );\n return specText;\n});\n\n/**\n * Resolve an input string to spec text — if it's a URL, fetch it via\n * HttpClient; otherwise return it as-is.\n */\nexport const resolveSpecText = (input: string, credentials?: SpecFetchCredentials) =>\n input.startsWith(\"http://\") || input.startsWith(\"https://\")\n ? fetchSpecText(input, credentials)\n : Effect.succeed(input);\n\n/**\n * Parse an OpenAPI document from spec text and validate it's OpenAPI 3.x.\n *\n * NOTE: does NOT resolve `$ref`s. `DocResolver` + `normalizeOpenApiRefs`\n * downstream work on refs lazily, so inlining them here would just waste\n * memory — and for big specs (e.g. Cloudflare's API) that blows through\n * the 128MB Cloudflare Workers memory cap.\n */\nexport const parse = Effect.fn(\"OpenApi.parse\")(function* (text: string) {\n const api = yield* parseTextToObject(text);\n\n if (!isOpenApi3(api)) {\n return yield* new OpenApiExtractionErrorFromParse({\n message:\n \"Only OpenAPI 3.x documents are supported. Swagger 2.x documents should be converted first.\",\n });\n }\n\n return api as ParsedDocument;\n});\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\nconst isOpenApi3 = (doc: OpenAPI.Document): doc is OpenAPIV3.Document | OpenAPIV3_1.Document =>\n \"openapi\" in doc && typeof doc.openapi === \"string\" && doc.openapi.startsWith(\"3.\");\n\nconst parseTextToObject = (text: string): Effect.Effect<OpenAPI.Document, OpenApiParseError> =>\n Effect.gen(function* () {\n const trimmed = text.trim();\n if (trimmed.length === 0) {\n return yield* new OpenApiParseError({\n message: \"OpenAPI document is empty\",\n });\n }\n\n const parsed = yield* parseJsonLike(trimmed).pipe(\n Effect.mapError(\n () =>\n new OpenApiParseError({\n message: \"Failed to parse OpenAPI document\",\n }),\n ),\n );\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return yield* new OpenApiParseError({\n message: \"OpenAPI document must parse to an object\",\n });\n }\n\n return parsed as OpenAPI.Document;\n });\n\nconst parseJsonText = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));\n\nconst parseJsonLike = (text: string): Effect.Effect<unknown, unknown> => {\n const parseYaml = Effect.try({\n try: () => parseYamlDocument(text, { json: true, schema: JSON_SCHEMA }) as unknown,\n catch: () => \"YamlParseFailed\" as const,\n });\n if (!text.startsWith(\"{\") && !text.startsWith(\"[\")) return parseYaml;\n return parseJsonText(text).pipe(Effect.catch(() => parseYaml));\n};\n","/**\n * Structural splitter for large OpenAPI documents written in clean block YAML.\n *\n * The whole-document parse of a 37MB spec (Microsoft Graph: 16.5k operations,\n * 8.2k schemas) builds a ~300MB JS tree that OOMs the 128MB Cloudflare Workers\n * isolate. This splitter avoids ever holding that tree: it scans the text once,\n * recording the byte range of each top-level key, each path-item (the indent-2\n * entries under `paths:`), and each schema (the indent-4 entries under\n * `components.schemas:`). The streaming compile then slices one item at a time,\n * de-indents it back to column 0, hands the isolated fragment to a real YAML\n * parser, and discards the result before moving on. Peak memory stays near the\n * size of the largest single item plus the raw text, not the parsed whole.\n *\n * This is not a YAML reimplementation: it extracts safe byte ranges from a\n * constrained document shape, then defers every actual parse to `js-yaml`. It\n * is only valid for the block-YAML profile `isStreamableSpec` accepts (2-space\n * block maps, top-level keys at column 0, no anchors/aliases/merge keys). Block\n * scalars (`|` / `>`) in descriptions are tracked so their indented content is\n * never mistaken for structure.\n */\n\nimport { JSON_SCHEMA, load as parseYamlDocument } from \"js-yaml\";\n\nexport interface ByteRange {\n readonly start: number;\n readonly end: number;\n}\n\nexport interface SpecStructure {\n /** Raw spec text. Every range below indexes into this string. */\n readonly text: string;\n /** Byte ranges of the top-level keys that are not `paths` / `components`\n * (openapi, info, servers, tags, security, ...). Concatenated and parsed as\n * one small document for the head (servers, info). */\n readonly headRanges: readonly ByteRange[];\n /** One range per path-item: the indent-2 entries under `paths:`. */\n readonly pathItems: readonly ByteRange[];\n /** One range per schema entry: the indent-4 entries under\n * `components.schemas:`. */\n readonly schemas: readonly ByteRange[];\n /** Ranges of the indent-2 `components` subkeys we keep whole because they are\n * small and may be `$ref`'d by a kept operation (parameters / requestBodies /\n * responses / headers / links / securitySchemes). Excludes the huge `schemas`\n * (streamed and pruned separately) and `examples` (never referenced by a\n * binding). */\n readonly smallComponentRanges: readonly ByteRange[];\n}\n\nconst SPACE = 32;\nconst HASH = 35;\nconst DASH = 45;\n\n/** `components` subkeys kept whole during a reduce: small, and a kept operation\n * may `$ref` into any of them. `schemas` is streamed/pruned separately and\n * `examples` is dropped (large, never referenced by a binding). */\nconst SMALL_COMPONENT_SECTIONS = new Set([\n \"parameters\",\n \"requestBodies\",\n \"responses\",\n \"headers\",\n \"links\",\n \"securitySchemes\",\n]);\n\n/** Count of leading spaces on the line starting at `lineStart`. */\nconst indentOf = (text: string, lineStart: number, lineEnd: number): number => {\n let i = lineStart;\n while (i < lineEnd && text.charCodeAt(i) === SPACE) i++;\n return i - lineStart;\n};\n\n/** True for a blank (whitespace-only) or comment line. */\nconst isBlankOrComment = (text: string, contentStart: number, lineEnd: number): boolean =>\n contentStart >= lineEnd || text.charCodeAt(contentStart) === HASH;\n\n/**\n * True when the line opens a block scalar (`key: |`, `key: >-`, etc.), meaning\n * every following more-indented line is literal content, not structure.\n */\nconst opensBlockScalar = (line: string): boolean =>\n /:\\s*[|>][+-]?\\d*\\s*(#.*)?$/.test(line) || /^\\s*[|>][+-]?\\d*\\s*(#.*)?$/.test(line);\n\ninterface LineCursor {\n readonly lineStart: number;\n readonly lineEnd: number;\n readonly nextStart: number;\n readonly indent: number;\n readonly contentStart: number;\n}\n\n/** Advance to the next significant line at offset `from`, returning null at EOF.\n * Blank lines, comments, and block-scalar content (lines indented deeper than\n * the scalar key, tracked by the caller) are still returned; the caller skips\n * them. */\nconst lineAt = (text: string, from: number, limit: number): LineCursor | null => {\n if (from >= limit) return null;\n let lineEnd = text.indexOf(\"\\n\", from);\n if (lineEnd === -1 || lineEnd > limit) lineEnd = limit;\n const indent = indentOf(text, from, lineEnd);\n const contentStart = from + indent;\n return {\n lineStart: from,\n lineEnd,\n nextStart: lineEnd + 1,\n indent,\n contentStart,\n };\n};\n\n/**\n * Find the start offset of every key line at exactly `indent` within\n * `[start, end)`, skipping blank/comment lines, deeper child lines, and\n * block-scalar content. Sequence items (`- `) at the target indent are not\n * treated as keys. Returns offsets in document order.\n */\nconst keyLineStartsAtIndent = (\n text: string,\n start: number,\n end: number,\n indent: number,\n): number[] => {\n const starts: number[] = [];\n let blockScalarIndent = -1;\n let pos = start;\n while (pos < end) {\n const line = lineAt(text, pos, end);\n if (!line) break;\n pos = line.nextStart;\n if (isBlankOrComment(text, line.contentStart, line.lineEnd)) continue;\n if (blockScalarIndent >= 0) {\n if (line.indent > blockScalarIndent) continue;\n blockScalarIndent = -1;\n }\n if (line.indent === indent && text.charCodeAt(line.contentStart) !== DASH) {\n starts.push(line.lineStart);\n }\n if (line.indent <= indent && opensBlockScalar(text.slice(line.contentStart, line.lineEnd))) {\n blockScalarIndent = line.indent;\n }\n }\n return starts;\n};\n\n/** Contiguous ranges from a sorted list of block-start offsets within\n * `[blockStart, blockEnd)`: each range runs to the next start (or blockEnd). */\nconst rangesFromStarts = (starts: readonly number[], blockEnd: number): ByteRange[] =>\n starts.map((s, i) => ({ start: s, end: i + 1 < starts.length ? starts[i + 1]! : blockEnd }));\n\n/** The simple (unquoted) key name on a key line, e.g. `paths`, `schemas`. */\nconst keyNameAt = (text: string, lineStart: number, lineEnd: number): string => {\n const indent = indentOf(text, lineStart, lineEnd);\n const colon = text.indexOf(\":\", lineStart + indent);\n const keyEnd = colon === -1 || colon > lineEnd ? lineEnd : colon;\n return text.slice(lineStart + indent, keyEnd).trim();\n};\n\n/**\n * Scan a document into its structural ranges. Pure and synchronous; never\n * parses. Returns null when the document does not present the expected shape\n * (no `paths:` block), so the caller can fall back to a whole-document parse.\n */\nexport const structuralSplit = (text: string): SpecStructure | null => {\n const len = text.length;\n\n // Top-level keys (column 0). Record each key's start + name, respecting\n // block scalars whose content could sit at column >= 1.\n const topStarts: number[] = [];\n const topNames: string[] = [];\n {\n let blockScalarIndent = -1;\n let pos = 0;\n while (pos < len) {\n const line = lineAt(text, pos, len);\n if (!line) break;\n pos = line.nextStart;\n if (isBlankOrComment(text, line.contentStart, line.lineEnd)) continue;\n if (blockScalarIndent >= 0) {\n if (line.indent > blockScalarIndent) continue;\n blockScalarIndent = -1;\n }\n if (line.indent === 0) {\n topStarts.push(line.lineStart);\n topNames.push(keyNameAt(text, line.lineStart, line.lineEnd));\n }\n if (opensBlockScalar(text.slice(line.contentStart, line.lineEnd))) {\n blockScalarIndent = line.indent;\n }\n }\n }\n\n const topRanges = rangesFromStarts(topStarts, len);\n const pathsIdx = topNames.indexOf(\"paths\");\n if (pathsIdx === -1) return null;\n const componentsIdx = topNames.indexOf(\"components\");\n\n const headRanges: ByteRange[] = [];\n for (let i = 0; i < topRanges.length; i++) {\n if (i === pathsIdx || i === componentsIdx) continue;\n headRanges.push(topRanges[i]!);\n }\n\n // Path-items: indent-2 keys inside the `paths:` block (after its key line).\n const pathsRange = topRanges[pathsIdx]!;\n const pathsBodyStart =\n lineAt(text, pathsRange.start, pathsRange.end)?.nextStart ?? pathsRange.end;\n const pathItems = rangesFromStarts(\n keyLineStartsAtIndent(text, pathsBodyStart, pathsRange.end, 2),\n pathsRange.end,\n );\n\n const schemas: ByteRange[] = [];\n const smallComponentRanges: ByteRange[] = [];\n if (componentsIdx !== -1) {\n const componentsRange = topRanges[componentsIdx]!;\n const componentsBodyStart =\n lineAt(text, componentsRange.start, componentsRange.end)?.nextStart ?? componentsRange.end;\n const subStarts = keyLineStartsAtIndent(text, componentsBodyStart, componentsRange.end, 2);\n const subRanges = rangesFromStarts(subStarts, componentsRange.end);\n for (const range of subRanges) {\n const name = keyNameAt(text, range.start, lineAt(text, range.start, range.end)!.lineEnd);\n if (name === \"schemas\") {\n const bodyStart = lineAt(text, range.start, range.end)?.nextStart ?? range.end;\n for (const s of rangesFromStarts(\n keyLineStartsAtIndent(text, bodyStart, range.end, 4),\n range.end,\n )) {\n schemas.push(s);\n }\n } else if (SMALL_COMPONENT_SECTIONS.has(name)) {\n smallComponentRanges.push(range);\n }\n // `examples` and any other subkey are intentionally dropped: no binding\n // field references them, and they can be large.\n }\n }\n\n return { text, headRanges, pathItems, schemas, smallComponentRanges };\n};\n\n/** Strip exactly `indent` leading spaces from every line of `fragment`, lifting\n * an indent-N block back to column 0 so it parses as a standalone document. */\nconst dedent = (fragment: string, indent: number): string =>\n indent === 0 ? fragment : fragment.replace(new RegExp(`^ {1,${indent}}`, \"gm\"), \"\");\n\nconst parseYaml = (text: string): unknown =>\n parseYamlDocument(text, { json: true, schema: JSON_SCHEMA });\n\n/**\n * Parse a single indent-N entry range (a path-item or a schema) in isolation.\n * Returns `[name, value]` where `name` is the entry's key and `value` its\n * parsed body, or null when the fragment does not parse to a single-key map.\n */\nexport const parseEntry = (\n text: string,\n range: ByteRange,\n indent: number,\n): readonly [string, unknown] | null => {\n const parsed = parseYaml(dedent(text.slice(range.start, range.end), indent));\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n const entries = Object.entries(parsed as Record<string, unknown>);\n if (entries.length !== 1) return null;\n return entries[0]!;\n};\n\n/** Parse the concatenation of the head ranges into the document head (openapi,\n * info, servers, tags). Small; safe to materialize whole. */\nexport const parseHead = (structure: SpecStructure): Record<string, unknown> => {\n const text = structure.headRanges.map((r) => structure.text.slice(r.start, r.end)).join(\"\");\n const parsed = parseYaml(text);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n};\n\n/** Parse the small component subkeys (parameters / requestBodies / responses)\n * into a `components`-shaped object for `$ref` resolution. */\nexport const parseSmallComponents = (structure: SpecStructure): Record<string, unknown> => {\n if (structure.smallComponentRanges.length === 0) return {};\n const body = structure.smallComponentRanges\n .map((r) => structure.text.slice(r.start, r.end))\n .join(\"\");\n const parsed = parseYaml(`components:\\n${body}`);\n const components =\n parsed && typeof parsed === \"object\" ? (parsed as Record<string, unknown>).components : null;\n return components && typeof components === \"object\"\n ? (components as Record<string, unknown>)\n : {};\n};\n\n/**\n * Accept only the block-YAML profile the splitter can safely slice: no tabs, no\n * anchors/aliases, no merge keys, and a `paths:` block present. Block scalars\n * are allowed (tracked during the scan). Conservative by design: a false\n * negative just routes a spec through the whole-document parse.\n */\nexport const isStreamableSpec = (text: string): boolean => {\n if (text.indexOf(\"\\t\") !== -1) return false;\n // Anchors/aliases/merge keys: cheap substring rejects before structural work.\n if (/(^|\\s)[&*][A-Za-z0-9_]/m.test(text)) return false;\n if (/<<\\s*:/.test(text)) return false;\n return /^paths:/m.test(text);\n};\n\nconst SCHEMA_REF_PREFIX = \"#/components/schemas/\";\n\n/** Map each `components.schemas` entry name to its byte range, reading only the\n * key line (never parsing the schema body). The schema name is the raw YAML\n * key, which matches the trailing segment of a `#/components/schemas/<name>`\n * reference. */\nexport const indexSchemas = (structure: SpecStructure): ReadonlyMap<string, ByteRange> => {\n const index = new Map<string, ByteRange>();\n for (const range of structure.schemas) {\n const line = lineAt(structure.text, range.start, range.end);\n if (!line) continue;\n const name = keyNameAt(structure.text, range.start, line.lineEnd);\n if (name) index.set(name, range);\n }\n return index;\n};\n\n/** Decode a `#/components/schemas/<segment>` name segment. Schema names are raw\n * YAML keys, so only JSON-pointer tilde escaping can appear (no `%`-encoding\n * in the wild specs we target); decode `~1`/`~0` and leave the rest verbatim. */\nconst decodeSchemaRefName = (segment: string): string =>\n segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n\n/** Collect the names of every `#/components/schemas/X` reference reachable in\n * `value`, without resolving them. */\nconst collectSchemaRefNames = (value: unknown, into: Set<string>): void => {\n if (typeof value === \"string\") {\n if (value.startsWith(SCHEMA_REF_PREFIX)) {\n const name = decodeSchemaRefName(value.slice(SCHEMA_REF_PREFIX.length));\n if (name.length > 0) into.add(name);\n }\n return;\n }\n if (Array.isArray(value)) {\n for (const item of value) collectSchemaRefNames(item, into);\n return;\n }\n if (value !== null && typeof value === \"object\") {\n for (const item of Object.values(value as Record<string, unknown>)) {\n collectSchemaRefNames(item, into);\n }\n }\n};\n\n/**\n * Resolve the transitive closure of schemas referenced by `roots`, parsing each\n * referenced schema once from its byte range (BFS over `$ref`s). Schemas not\n * reachable from `roots` are never parsed, so peak memory tracks the kept\n * subset rather than the full `components.schemas` map.\n */\nexport const collectReferencedSchemas = (\n structure: SpecStructure,\n index: ReadonlyMap<string, ByteRange>,\n roots: readonly unknown[],\n): Record<string, unknown> => {\n const result: Record<string, unknown> = {};\n const wanted = new Set<string>();\n for (const root of roots) collectSchemaRefNames(root, wanted);\n\n const queue = [...wanted];\n for (let i = 0; i < queue.length; i += 1) {\n const name = queue[i]!;\n if (Object.prototype.hasOwnProperty.call(result, name)) continue;\n const range = index.get(name);\n if (!range) continue;\n const entry = parseEntry(structure.text, range, 4);\n if (!entry) continue;\n result[name] = entry[1];\n const next = new Set<string>();\n collectSchemaRefNames(entry[1], next);\n for (const ref of next) {\n if (!Object.prototype.hasOwnProperty.call(result, ref)) queue.push(ref);\n }\n }\n return result;\n};\n\n/** A path-item filter for the streaming compile: given a parsed path-item,\n * return the (possibly trimmed) value to keep, or null to drop the path\n * entirely. Applied per path-item by `streamOperationBindingsFromStructure`. */\nexport type KeepPathItem = (\n path: string,\n pathItem: Record<string, unknown>,\n) => Record<string, unknown> | null;\n","// ---------------------------------------------------------------------------\n// OpenAPI type aliases and $ref resolution\n//\n// Wraps the openapi-types V3/V3_1 union mess and provides clean ref resolution.\n// ---------------------------------------------------------------------------\n\nimport type { OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\nimport type { ParsedDocument } from \"./parse\";\nimport type { ServerVariable } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Type aliases — collapse V3 / V3_1 unions into single names\n// ---------------------------------------------------------------------------\n\nexport type ParameterObject = OpenAPIV3.ParameterObject | OpenAPIV3_1.ParameterObject;\nexport type OperationObject = OpenAPIV3.OperationObject | OpenAPIV3_1.OperationObject;\nexport type PathItemObject = OpenAPIV3.PathItemObject | OpenAPIV3_1.PathItemObject;\nexport type RequestBodyObject = OpenAPIV3.RequestBodyObject | OpenAPIV3_1.RequestBodyObject;\nexport type ResponseObject = OpenAPIV3.ResponseObject | OpenAPIV3_1.ResponseObject;\nexport type MediaTypeObject = OpenAPIV3.MediaTypeObject | OpenAPIV3_1.MediaTypeObject;\nexport type ServerObject = OpenAPIV3.ServerObject | OpenAPIV3_1.ServerObject;\n\n// ---------------------------------------------------------------------------\n// DocResolver — wraps a parsed document for clean $ref resolution\n// ---------------------------------------------------------------------------\n\nexport class DocResolver {\n constructor(readonly doc: ParsedDocument) {}\n\n /** Resolve a value that might be a $ref, returning the resolved object */\n resolve<T>(value: T | OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject): T | null {\n if (isRef(value)) {\n const resolved = this.resolvePointer(value.$ref);\n return resolved as T | null;\n }\n return value as T;\n }\n\n private resolvePointer(ref: string): unknown {\n if (!ref.startsWith(\"#/\")) return null;\n const segments = ref.slice(2).split(\"/\");\n let current: unknown = this.doc;\n for (const segment of segments) {\n if (typeof current !== \"object\" || current === null) return null;\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n }\n}\n\nconst isRef = (value: unknown): value is { $ref: string } =>\n typeof value === \"object\" && value !== null && \"$ref\" in value;\n\n// ---------------------------------------------------------------------------\n// Server URL resolution\n// ---------------------------------------------------------------------------\n\n/** Substitute `{var}` placeholders in a templated URL using a plain map. */\nexport const substituteUrlVariables = (url: string, values: Record<string, string>): string => {\n let out = url;\n for (const [name, value] of Object.entries(values)) {\n out = out.replaceAll(`{${name}}`, value);\n }\n return out;\n};\n\n/** Resolve a templated server URL, filling each `{var}` from `overrides` when\n * non-empty, otherwise the variable's spec default. URLs without placeholders\n * pass through unchanged. */\nexport const resolveServerUrl = (\n templateUrl: string,\n variables: Record<string, ServerVariable> | undefined,\n overrides: Record<string, string>,\n): string => {\n const values: Record<string, string> = {};\n for (const [name, v] of Object.entries(variables ?? {})) values[name] = v.default;\n for (const [name, value] of Object.entries(overrides)) {\n if (value) values[name] = value;\n }\n return substituteUrlVariables(templateUrl, values);\n};\n\n// ---------------------------------------------------------------------------\n// Content negotiation\n// ---------------------------------------------------------------------------\n\n/**\n * Return all declared media entries in spec order. `Object.entries` on a\n * plain object preserves insertion order in modern engines, which matches\n * spec declaration order as the parser produced it.\n */\nexport const declaredContents = (\n content: Record<string, MediaTypeObject> | undefined,\n): ReadonlyArray<{ mediaType: string; media: MediaTypeObject }> => {\n if (!content) return [];\n return Object.entries(content).map(([mediaType, media]) => ({ mediaType, media }));\n};\n\n/**\n * Pick the default media type for a requestBody or response. Matches\n * swagger-client behaviour: **first declared wins** (not JSON-first). Spec\n * authors order content entries to signal intent (upload-heavy endpoints\n * declare multipart first, JSON second); respecting that order avoids\n * silently downgrading a multipart endpoint to JSON.\n *\n * For response bodies we still want a JSON preference because the server\n * picks the response content type, not the client — the old `application/\n * json` preference is preserved via `preferredResponseContent` below.\n */\nexport const preferredContent = (\n content: Record<string, MediaTypeObject> | undefined,\n): { mediaType: string; media: MediaTypeObject } | undefined => {\n const first = declaredContents(content)[0];\n return first ? first : undefined;\n};\n\n/** Response-side content picker — still JSON-first because the server\n * picks the response media type, so we want to advertise a preference. */\nexport const preferredResponseContent = (\n content: Record<string, MediaTypeObject> | undefined,\n): { mediaType: string; media: MediaTypeObject } | undefined => {\n if (!content) return undefined;\n const entries = Object.entries(content);\n const pick =\n entries.find(([mt]) => mt === \"application/json\") ??\n entries.find(([mt]) => mt.toLowerCase().includes(\"+json\")) ??\n entries.find(([mt]) => mt.toLowerCase().includes(\"json\")) ??\n entries[0];\n return pick ? { mediaType: pick[0], media: pick[1] } : undefined;\n};\n","import { Schema } from \"effect\";\nimport { AuthTemplateSlug, type OAuthAuthentication } from \"@executor-js/sdk/shared\";\nimport {\n apiKeyMethodFromAuthTemplate,\n isApiKeyAuthTemplate,\n type ApiKeyAuthMethod,\n type ApiKeyAuthTemplate,\n} from \"@executor-js/sdk/http-auth\";\n\n// ---------------------------------------------------------------------------\n// Auth-template model.\n//\n// The apiKey method is the SHARED placements model (`@executor-js/sdk/http-auth`,\n// the same shape the graphql/mcp plugins store): N header/query placements,\n// each rendered from its own credential input. The oauth template is\n// mechanism-intrinsic and comes from core (`OAuthAuthentication`, keyed\n// `kind: \"oauth2\"` with stored endpoints+scopes); an integration's\n// `Authentication` union composes the two. Client credentials\n// (clientId/secret) live on the core `OAuthClient`, not here.\n//\n// Pre-canonical stored templates (`type: \"apiKey\"` with `variable()`-templated\n// header/query records) are rewritten by the one-off config migration\n// (`migrate-config.ts`) — runtime code knows only this model.\n// ---------------------------------------------------------------------------\n\nexport { TOKEN_VARIABLE } from \"@executor-js/sdk/http-auth\";\n\nexport type APIKeyAuthentication = ApiKeyAuthMethod;\n\n/** Every method is keyed by `kind` — `kind: \"oauth2\"` | `kind: \"apikey\"`. */\nexport type Authentication = OAuthAuthentication | APIKeyAuthentication;\n\n/** What auth inputs accept: oauth templates (wire-typed: plain slug) plus the\n * request-shaped apikey dialect (`type: \"apiKey\"`, headers/queryParams\n * records) — the ONE apikey authoring shape. Stored configs and the catalog\n * read as canonical placements; `apiKeyAuthTemplateFromMethod` serializes\n * them back for read-modify-write flows. */\nexport type OAuthAuthenticationInput = Omit<OAuthAuthentication, \"slug\"> & {\n readonly slug: string;\n};\nexport type AuthenticationInput = OAuthAuthenticationInput | ApiKeyAuthTemplate;\n\n/** Expand the request-shaped dialect into canonical placements and brand the\n * oauth slugs. A dialect entry without a slug gets a blank one —\n * `mergeAuthTemplates` backfills `custom_<id>`. */\nexport const normalizeOpenApiAuthInputs = (\n inputs: readonly AuthenticationInput[],\n): readonly Authentication[] =>\n inputs.map((input): Authentication => {\n if (!isApiKeyAuthTemplate(input)) {\n return { ...input, slug: AuthTemplateSlug.make(input.slug) };\n }\n const method = apiKeyMethodFromAuthTemplate(input);\n return { ...method, slug: method.slug ?? \"\" };\n });\n\n// ---------------------------------------------------------------------------\n// Branded IDs\n// ---------------------------------------------------------------------------\n\nexport const OperationId = Schema.String.pipe(Schema.brand(\"OperationId\"));\nexport type OperationId = typeof OperationId.Type;\n\n// ---------------------------------------------------------------------------\n// HTTP\n// ---------------------------------------------------------------------------\n\nexport const HttpMethod = Schema.Literals([\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"patch\",\n \"head\",\n \"options\",\n \"trace\",\n]);\nexport type HttpMethod = typeof HttpMethod.Type;\n\nexport const ParameterLocation = Schema.Literals([\"path\", \"query\", \"header\", \"cookie\"]);\nexport type ParameterLocation = typeof ParameterLocation.Type;\n\n// ---------------------------------------------------------------------------\n// Extracted operation\n// ---------------------------------------------------------------------------\n\nexport const OperationParameter = Schema.Struct({\n name: Schema.String,\n location: ParameterLocation,\n required: Schema.Boolean,\n schema: Schema.OptionFromOptional(Schema.Unknown),\n style: Schema.OptionFromOptional(Schema.String),\n explode: Schema.OptionFromOptional(Schema.Boolean),\n allowReserved: Schema.OptionFromOptional(Schema.Boolean),\n description: Schema.OptionFromOptional(Schema.String),\n});\nexport type OperationParameter = typeof OperationParameter.Type;\n\n/**\n * OpenAPI 3.x `Encoding Object` (§4.8.15). Declared per-property inside a\n * multipart/form-data or application/x-www-form-urlencoded request body.\n *\n * - `contentType` — for multipart, overrides the per-part `Content-Type`\n * header (e.g. `application/json` for a JSON-encoded metadata part).\n * - `style` / `explode` / `allowReserved` — for form-urlencoded, control\n * array / object serialization the same way parameter-level style does.\n */\nexport const EncodingObject = Schema.Struct({\n contentType: Schema.OptionFromOptional(Schema.String),\n style: Schema.OptionFromOptional(Schema.String),\n explode: Schema.OptionFromOptional(Schema.Boolean),\n allowReserved: Schema.OptionFromOptional(Schema.Boolean),\n});\nexport type EncodingObject = typeof EncodingObject.Type;\n\nexport const MediaBinding = Schema.Struct({\n contentType: Schema.String,\n schema: Schema.OptionFromOptional(Schema.Unknown),\n encoding: Schema.OptionFromOptional(Schema.Record(Schema.String, EncodingObject)),\n});\nexport type MediaBinding = typeof MediaBinding.Type;\n\nexport const OperationRequestBody = Schema.Struct({\n required: Schema.Boolean,\n /** Default media type — first declared in spec order (not JSON-first).\n * Used when the caller does not override via the tool's `contentType` arg. */\n contentType: Schema.String,\n /** Schema of the default media type. Kept for backward compat with stored\n * bindings from before `contents` was added. */\n schema: Schema.OptionFromOptional(Schema.Unknown),\n /** All declared media types in spec order. Populated by `extract.ts`\n * going forward; older persisted bindings may have this unset and will\n * fall back to `{contentType, schema}`. */\n contents: Schema.OptionFromOptional(Schema.Array(MediaBinding)),\n});\nexport type OperationRequestBody = typeof OperationRequestBody.Type;\n\nexport const OperationFileHint = Schema.Struct({\n kind: Schema.Literals([\"binaryResponse\", \"byteField\"]),\n mimeType: Schema.OptionFromOptional(Schema.String),\n dataField: Schema.OptionFromOptional(Schema.String),\n sizeField: Schema.OptionFromOptional(Schema.String),\n encoding: Schema.OptionFromOptional(Schema.Literals([\"base64\", \"base64url\"])),\n});\nexport type OperationFileHint = typeof OperationFileHint.Type;\n\nexport const OperationResponseBody = Schema.Struct({\n contentType: Schema.String,\n schema: Schema.OptionFromOptional(Schema.Unknown),\n fileHint: Schema.OptionFromOptional(OperationFileHint),\n});\nexport type OperationResponseBody = typeof OperationResponseBody.Type;\n\nexport const ServerVariable = Schema.Struct({\n default: Schema.String,\n enum: Schema.OptionFromOptional(Schema.Array(Schema.String)),\n description: Schema.OptionFromOptional(Schema.String),\n});\nexport type ServerVariable = typeof ServerVariable.Type;\n\nexport const ServerInfo = Schema.Struct({\n url: Schema.String,\n description: Schema.OptionFromOptional(Schema.String),\n variables: Schema.OptionFromOptional(Schema.Record(Schema.String, ServerVariable)),\n});\nexport type ServerInfo = typeof ServerInfo.Type;\n\nexport const ExtractedOperation = Schema.Struct({\n operationId: OperationId,\n toolPath: Schema.OptionFromOptional(Schema.String),\n method: HttpMethod,\n servers: Schema.Array(ServerInfo),\n pathTemplate: Schema.String,\n summary: Schema.OptionFromOptional(Schema.String),\n description: Schema.OptionFromOptional(Schema.String),\n tags: Schema.Array(Schema.String),\n parameters: Schema.Array(OperationParameter),\n requestBody: Schema.OptionFromOptional(OperationRequestBody),\n responseBody: Schema.OptionFromOptional(OperationResponseBody),\n inputSchema: Schema.OptionFromOptional(Schema.Unknown),\n outputSchema: Schema.OptionFromOptional(Schema.Unknown),\n deprecated: Schema.Boolean,\n});\nexport type ExtractedOperation = typeof ExtractedOperation.Type;\n\nexport const ExtractionResult = Schema.Struct({\n title: Schema.OptionFromOptional(Schema.String),\n /** The spec's `info.description` — the author's own summary of the API. */\n description: Schema.OptionFromOptional(Schema.String),\n version: Schema.OptionFromOptional(Schema.String),\n servers: Schema.Array(ServerInfo),\n operations: Schema.Array(ExtractedOperation),\n});\nexport type ExtractionResult = typeof ExtractionResult.Type;\n\n// ---------------------------------------------------------------------------\n// Operation binding — minimal invocation data (no schemas/metadata)\n// ---------------------------------------------------------------------------\n\nexport const OperationBinding = Schema.Struct({\n method: HttpMethod,\n servers: Schema.optional(Schema.Array(ServerInfo)),\n pathTemplate: Schema.String,\n parameters: Schema.Array(OperationParameter),\n requestBody: Schema.OptionFromOptional(OperationRequestBody),\n responseBody: Schema.OptionFromOptional(OperationResponseBody),\n});\nexport type OperationBinding = typeof OperationBinding.Type;\n\n// ---------------------------------------------------------------------------\n// Invocation\n// ---------------------------------------------------------------------------\n\nexport const InvocationResult = Schema.Struct({\n status: Schema.Number,\n headers: Schema.Record(Schema.String, Schema.String),\n data: Schema.NullOr(Schema.Unknown),\n error: Schema.NullOr(Schema.Unknown),\n});\nexport type InvocationResult = typeof InvocationResult.Type;\n","import { Effect, Option } from \"effect\";\n\nimport { planToolPaths, type OperationPathInput, type PlannedToolPath } from \"./definitions\";\nimport { OpenApiExtractionError } from \"./errors\";\nimport type { ParsedDocument } from \"./parse\";\nimport {\n parseEntry,\n parseHead,\n parseSmallComponents,\n type ByteRange,\n type KeepPathItem,\n type SpecStructure,\n} from \"./split\";\nimport {\n declaredContents,\n DocResolver,\n preferredResponseContent,\n type OperationObject,\n type ParameterObject,\n type PathItemObject,\n type RequestBodyObject,\n type ResponseObject,\n type ServerObject,\n} from \"./openapi-utils\";\nimport {\n EncodingObject,\n ExtractedOperation,\n ExtractionResult,\n type HttpMethod,\n MediaBinding,\n OperationBinding,\n OperationFileHint,\n OperationId,\n OperationParameter,\n OperationRequestBody,\n OperationResponseBody,\n type ParameterLocation,\n ServerInfo,\n ServerVariable,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst HTTP_METHODS: readonly HttpMethod[] = [\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"patch\",\n \"head\",\n \"options\",\n \"trace\",\n];\n\nconst VALID_PARAM_LOCATIONS = new Set<string>([\"path\", \"query\", \"header\", \"cookie\"]);\n\n// ---------------------------------------------------------------------------\n// Parameter extraction\n// ---------------------------------------------------------------------------\n\nconst extractParameters = (\n pathItem: PathItemObject,\n operation: OperationObject,\n r: DocResolver,\n): OperationParameter[] => {\n const merged = new Map<string, ParameterObject>();\n\n for (const raw of pathItem.parameters ?? []) {\n const p = r.resolve<ParameterObject>(raw);\n if (!p) continue;\n merged.set(`${p.in}:${p.name}`, p);\n }\n for (const raw of operation.parameters ?? []) {\n const p = r.resolve<ParameterObject>(raw);\n if (!p) continue;\n merged.set(`${p.in}:${p.name}`, p);\n }\n\n return [...merged.values()]\n .filter((p) => VALID_PARAM_LOCATIONS.has(p.in))\n .map((p) =>\n OperationParameter.make({\n name: p.name,\n location: p.in as ParameterLocation,\n required: p.in === \"path\" ? true : p.required === true,\n schema: Option.fromNullishOr(p.schema),\n style: Option.fromNullishOr(p.style),\n explode: Option.fromNullishOr(p.explode),\n allowReserved: Option.fromNullishOr(\"allowReserved\" in p ? p.allowReserved : undefined),\n description: Option.fromNullishOr(p.description),\n }),\n );\n};\n\n// ---------------------------------------------------------------------------\n// Request body extraction\n// ---------------------------------------------------------------------------\n\nconst buildEncodingRecord = (\n encoding: Record<string, unknown> | undefined,\n): Record<string, EncodingObject> | undefined => {\n if (!encoding) return undefined;\n const out: Record<string, EncodingObject> = {};\n for (const [prop, raw] of Object.entries(encoding)) {\n if (typeof raw !== \"object\" || raw === null) continue;\n const e = raw as {\n contentType?: string;\n style?: string;\n explode?: boolean;\n allowReserved?: boolean;\n };\n out[prop] = EncodingObject.make({\n contentType: Option.fromNullishOr(e.contentType),\n style: Option.fromNullishOr(e.style),\n explode: Option.fromNullishOr(e.explode),\n allowReserved: Option.fromNullishOr(e.allowReserved),\n });\n }\n return Object.keys(out).length > 0 ? out : undefined;\n};\n\nconst extractRequestBody = (\n operation: OperationObject,\n r: DocResolver,\n): OperationRequestBody | undefined => {\n if (!operation.requestBody) return undefined;\n\n const body = r.resolve<RequestBodyObject>(operation.requestBody);\n if (!body) return undefined;\n\n const contents = declaredContents(body.content).map(({ mediaType, media }) =>\n MediaBinding.make({\n contentType: mediaType,\n schema: Option.fromNullishOr(media.schema),\n encoding: Option.fromNullishOr(\n buildEncodingRecord((media as { encoding?: Record<string, unknown> }).encoding),\n ),\n }),\n );\n if (contents.length === 0) return undefined;\n\n // Default = first declared (spec author's preferred order). Callers can\n // override at invoke time with a `contentType` arg.\n const defaultContent = contents[0]!;\n\n return OperationRequestBody.make({\n required: body.required === true,\n contentType: defaultContent.contentType,\n schema: defaultContent.schema,\n contents: Option.some(contents),\n });\n};\n\n// ---------------------------------------------------------------------------\n// Response schema extraction\n// ---------------------------------------------------------------------------\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst stringType = (schema: Record<string, unknown>): boolean =>\n schema.type === \"string\" || (Array.isArray(schema.type) && schema.type.includes(\"string\"));\n\nconst numericType = (schema: Record<string, unknown>): boolean =>\n schema.type === \"integer\" ||\n schema.type === \"number\" ||\n (Array.isArray(schema.type) &&\n (schema.type.includes(\"integer\") || schema.type.includes(\"number\")));\n\nconst normalizedMediaType = (mediaType: string): string =>\n mediaType.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n\nconst isJsonMediaType = (mediaType: string): boolean => {\n const normalized = normalizedMediaType(mediaType);\n return (\n normalized === \"application/json\" || normalized.includes(\"+json\") || normalized.includes(\"json\")\n );\n};\n\nconst binaryStringSchema = (schema: Record<string, unknown>): boolean =>\n stringType(schema) && (schema.format === \"binary\" || schema.format === \"byte\");\n\nconst base64EncodingFromDescription = (schema: Record<string, unknown>): \"base64\" | \"base64url\" =>\n typeof schema.description === \"string\" &&\n /base64url|base64-url|url[- ]safe/i.test(schema.description)\n ? \"base64url\"\n : \"base64\";\n\nconst detectFileHint = (\n schema: unknown,\n mediaType: string,\n r: DocResolver,\n): OperationFileHint | undefined => {\n const resolved = isRecord(schema) ? r.resolve<Record<string, unknown>>(schema) : null;\n if (!resolved) return undefined;\n\n if (!isJsonMediaType(mediaType) && binaryStringSchema(resolved)) {\n return OperationFileHint.make({\n kind: \"binaryResponse\",\n mimeType: Option.some(mediaType),\n dataField: Option.none(),\n sizeField: Option.none(),\n encoding: Option.none(),\n });\n }\n\n if (!isJsonMediaType(mediaType)) return undefined;\n\n const properties = resolved.properties;\n if (!isRecord(properties)) return undefined;\n const data = properties.data;\n const dataSchema = isRecord(data) ? r.resolve<Record<string, unknown>>(data) : null;\n if (!dataSchema || !binaryStringSchema(dataSchema)) return undefined;\n\n const size = properties.size;\n const sizeSchema = isRecord(size) ? r.resolve<Record<string, unknown>>(size) : null;\n const sizeField = sizeSchema && numericType(sizeSchema) ? \"size\" : undefined;\n\n return OperationFileHint.make({\n kind: \"byteField\",\n mimeType: Option.some(\"application/octet-stream\"),\n dataField: Option.some(\"data\"),\n sizeField: sizeField ? Option.some(sizeField) : Option.none(),\n encoding: Option.some(base64EncodingFromDescription(dataSchema)),\n });\n};\n\nconst extractResponseBody = (\n operation: OperationObject,\n r: DocResolver,\n): OperationResponseBody | undefined => {\n if (!operation.responses) return undefined;\n\n const entries = Object.entries(operation.responses);\n const preferred = [\n ...entries.filter(([s]) => /^2\\d\\d$/.test(s)).sort(([a], [b]) => a.localeCompare(b)),\n ...entries.filter(([s]) => s === \"default\"),\n ];\n\n for (const [, ref] of preferred) {\n const resp = r.resolve<ResponseObject>(ref);\n if (!resp) continue;\n const content = preferredResponseContent(resp.content);\n if (content?.media.schema) {\n return OperationResponseBody.make({\n contentType: content.mediaType,\n schema: Option.some(content.media.schema),\n fileHint: Option.fromNullishOr(detectFileHint(content.media.schema, content.mediaType, r)),\n });\n }\n }\n\n return undefined;\n};\n\n// ---------------------------------------------------------------------------\n// Input schema builder\n// ---------------------------------------------------------------------------\n\n// Optional `server` input — host selection + server-URL variables. Undefined\n// when there's nothing to configure (a single server with no variables).\nconst buildServerInputProperty = (\n servers: readonly ServerInfo[],\n): Record<string, unknown> | undefined => {\n const variableDefs: Record<string, ServerVariable> = {};\n for (const server of servers) {\n for (const [name, v] of Object.entries(Option.getOrUndefined(server.variables) ?? {})) {\n if (!(name in variableDefs)) variableDefs[name] = v;\n }\n }\n const hasMultiple = servers.length > 1;\n const variableNames = Object.keys(variableDefs);\n if (!hasMultiple && variableNames.length === 0) return undefined;\n\n const properties: Record<string, unknown> = {};\n if (hasMultiple) {\n properties.url = {\n type: \"string\",\n enum: servers.map((server) => server.url),\n default: servers[0]!.url,\n description: \"Which of the spec's servers to send the request to.\",\n };\n }\n if (variableNames.length > 0) {\n properties.variables = {\n type: \"object\",\n additionalProperties: false,\n properties: Object.fromEntries(\n Object.entries(variableDefs).map(([name, v]) => [\n name,\n {\n type: \"string\",\n default: v.default,\n ...(Option.isSome(v.enum) ? { enum: v.enum.value } : {}),\n ...(Option.isSome(v.description) ? { description: v.description.value } : {}),\n },\n ]),\n ),\n description: \"Values for the server URL `{variables}`; spec defaults apply when omitted.\",\n };\n }\n return {\n type: \"object\",\n additionalProperties: false,\n properties,\n description: \"Optional host selection and server-URL variables for this request.\",\n };\n};\n\nexport const buildInputSchema = (\n parameters: readonly OperationParameter[],\n requestBody: OperationRequestBody | undefined,\n servers: readonly ServerInfo[],\n): Record<string, unknown> | undefined => {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n let requiredBodyAlternatives: readonly { readonly required: readonly string[] }[] | undefined;\n\n for (const param of parameters) {\n properties[param.name] = Option.getOrElse(param.schema, () => ({ type: \"string\" }));\n if (param.required) required.push(param.name);\n }\n\n // A path/query parameter named `server` takes precedence over the host input.\n const serverProperty = buildServerInputProperty(servers);\n if (serverProperty && !(\"server\" in properties)) properties.server = serverProperty;\n\n if (requestBody) {\n // When the spec declares multiple media types for this requestBody,\n // expose `contentType` so the model can pick. Default = first declared.\n // For mixed bodies, `body` schema tracks the default; the model is\n // responsible for supplying a body shape that matches whichever\n // contentType it picks. Octet-only operations use `bodyBase64` instead.\n const contents = Option.getOrUndefined(requestBody.contents);\n const defaultIsOctetStream =\n requestBody.contentType.split(\";\")[0]?.trim().toLowerCase() === \"application/octet-stream\";\n const acceptsOctetStream =\n defaultIsOctetStream ||\n contents?.some(\n (content) =>\n content.contentType.split(\";\")[0]?.trim().toLowerCase() === \"application/octet-stream\",\n ) === true;\n const acceptsBody =\n !defaultIsOctetStream ||\n contents?.some(\n (content) =>\n content.contentType.split(\";\")[0]?.trim().toLowerCase() !== \"application/octet-stream\",\n ) === true;\n if (acceptsBody) {\n properties.body = Option.getOrElse(requestBody.schema, () => ({ type: \"object\" }));\n }\n if (acceptsOctetStream) {\n properties.bodyBase64 = {\n type: \"string\",\n contentEncoding: \"base64\",\n contentMediaType: \"application/octet-stream\",\n description:\n \"Base64-encoded bytes for application/octet-stream request bodies. When contentType is omitted, this selects application/octet-stream.\",\n };\n }\n if (requestBody.required) {\n if (acceptsOctetStream && acceptsBody) {\n requiredBodyAlternatives = [{ required: [\"body\"] }, { required: [\"bodyBase64\"] }];\n } else {\n required.push(acceptsOctetStream ? \"bodyBase64\" : \"body\");\n }\n }\n if (contents && contents.length > 1) {\n properties.contentType = {\n type: \"string\",\n enum: contents.map((c) => c.contentType),\n default: requestBody.contentType,\n description:\n \"Content-Type for the request body. Declared media types for this operation, in spec order.\",\n };\n }\n }\n\n if (Object.keys(properties).length === 0) return undefined;\n\n return {\n type: \"object\",\n properties,\n ...(required.length > 0 ? { required } : {}),\n ...(requiredBodyAlternatives ? { anyOf: requiredBodyAlternatives } : {}),\n additionalProperties: false,\n };\n};\n\n// ---------------------------------------------------------------------------\n// Operation ID derivation\n// ---------------------------------------------------------------------------\n\nconst deriveOperationId = (\n method: HttpMethod,\n pathTemplate: string,\n operation: OperationObject,\n): string =>\n operation.operationId ??\n (`${method}_${pathTemplate.replace(/[^a-zA-Z0-9]+/g, \"_\")}`.replace(/^_+|_+$/g, \"\") ||\n `${method}_operation`);\n\nconst explicitToolPath = (operation: OperationObject): string | undefined => {\n const value = (operation as Record<string, unknown>)[\"x-executor-toolPath\"];\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n};\n\nconst explicitPathTemplate = (operation: OperationObject): string | undefined => {\n const value = (operation as Record<string, unknown>)[\"x-executor-pathTemplate\"];\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n};\n\n// ---------------------------------------------------------------------------\n// Server extraction\n// ---------------------------------------------------------------------------\n\nconst extractServerList = (servers: readonly ServerObject[] | undefined): ServerInfo[] =>\n (servers ?? []).flatMap((server) => {\n if (!server.url) return [];\n const serverVariables = server.variables as\n | Record<\n string,\n {\n readonly default?: string;\n readonly enum?: readonly string[];\n readonly description?: string;\n }\n >\n | undefined;\n const vars = serverVariables\n ? Object.fromEntries(\n Object.entries(serverVariables).flatMap(([name, v]) => {\n if (v.default === undefined || v.default === null) return [];\n const enumValues = Array.isArray(v.enum)\n ? v.enum.filter((x): x is string => typeof x === \"string\")\n : undefined;\n return [\n [\n name,\n ServerVariable.make({\n default: String(v.default),\n enum:\n enumValues && enumValues.length > 0 ? Option.some(enumValues) : Option.none(),\n description: Option.fromNullishOr(v.description),\n }),\n ],\n ];\n }),\n )\n : undefined;\n return [\n ServerInfo.make({\n url: server.url,\n description: Option.fromNullishOr(server.description),\n variables: vars && Object.keys(vars).length > 0 ? Option.some(vars) : Option.none(),\n }),\n ];\n });\n\nconst extractServers = (doc: ParsedDocument): ServerInfo[] => extractServerList(doc.servers);\n\nconst operationServers = (\n pathItem: PathItemObject,\n operation: OperationObject,\n docServers: readonly ServerInfo[],\n): readonly ServerInfo[] => {\n const operationLevel = extractServerList(operation.servers);\n if (operationLevel.length > 0) return operationLevel;\n const pathLevel = extractServerList(pathItem.servers);\n if (pathLevel.length > 0) return pathLevel;\n return docServers;\n};\n\n// ---------------------------------------------------------------------------\n// Main extraction\n// ---------------------------------------------------------------------------\n\n/** Extract all operations from a bundled OpenAPI 3.x document */\nexport const extract = Effect.fn(\"OpenApi.extract\")(function* (doc: ParsedDocument) {\n const paths = doc.paths;\n if (!paths) {\n return yield* new OpenApiExtractionError({\n message: \"OpenAPI document has no paths defined\",\n });\n }\n\n const r = new DocResolver(doc);\n const docServers = extractServers(doc);\n const operations: ExtractedOperation[] = [];\n\n for (const [pathTemplate, pathItem] of Object.entries(paths).sort(([a], [b]) =>\n a.localeCompare(b),\n )) {\n if (!pathItem) continue;\n\n for (const method of HTTP_METHODS) {\n const operation = pathItem[method];\n if (!operation) continue;\n\n const parameters = extractParameters(pathItem, operation, r);\n const requestBody = extractRequestBody(operation, r);\n const responseBody = extractResponseBody(operation, r);\n const servers = operationServers(pathItem, operation, docServers);\n const inputSchema = buildInputSchema(parameters, requestBody, servers);\n const outputSchema = responseBody ? Option.getOrUndefined(responseBody.schema) : undefined;\n const tags = (operation.tags ?? []).filter((t) => t.trim().length > 0);\n const operationPathTemplate = explicitPathTemplate(operation) ?? pathTemplate;\n\n operations.push(\n ExtractedOperation.make({\n operationId: OperationId.make(deriveOperationId(method, pathTemplate, operation)),\n toolPath: Option.fromNullishOr(explicitToolPath(operation)),\n method,\n servers,\n pathTemplate: operationPathTemplate,\n summary: Option.fromNullishOr(operation.summary),\n description: Option.fromNullishOr(operation.description),\n tags,\n parameters,\n requestBody: Option.fromNullishOr(requestBody),\n responseBody: Option.fromNullishOr(responseBody),\n inputSchema: Option.fromNullishOr(inputSchema),\n outputSchema: Option.fromNullishOr(outputSchema),\n deprecated: operation.deprecated === true,\n }),\n );\n }\n }\n\n return ExtractionResult.make({\n title: Option.fromNullishOr(doc.info?.title),\n description: Option.fromNullishOr(doc.info?.description),\n version: Option.fromNullishOr(doc.info?.version),\n servers: docServers,\n operations,\n });\n});\n\n// ---------------------------------------------------------------------------\n// Streaming binding extraction\n// ---------------------------------------------------------------------------\n\n/** One persisted invocation binding plus the tool name and description it\n * backs. The description is the resolved operation description / summary /\n * method+path fallback, persisted so the serve path needs no re-parse. */\nexport interface OperationBindingChunk {\n readonly toolName: string;\n readonly description: string;\n readonly binding: OperationBinding;\n}\n\ninterface OperationRef {\n readonly pathItem: PathItemObject;\n readonly operation: OperationObject;\n readonly method: HttpMethod;\n /** Resolved path template (`x-executor-pathTemplate` override or the key). */\n readonly pathTemplate: string;\n}\n\n/**\n * Stream invocation bindings out of a parsed document in bounded chunks,\n * persisting each chunk via `onChunk` before building the next.\n *\n * This is the memory-safe compile path for huge specs (e.g. Microsoft Graph,\n * 16.5k operations / 37MB). It differs from `extract` + `compileToolDefinitions`\n * in two ways that keep peak memory at parse level rather than ~doubling it:\n *\n * 1. It never builds `hoistedDefs` or per-operation `inputSchema`/`outputSchema`\n * (the add path only needs invocation bindings, which carry `$ref`s, not\n * inlined schemas).\n * 2. It never holds all bindings at once. Tool-path planning needs a global\n * view, but only of lightweight metadata (`planToolPaths`, schema-free);\n * the heavy per-operation bindings are built, flushed, and dropped one\n * chunk at a time.\n *\n * Bindings reference subtrees of the parsed document rather than copying them,\n * so `onChunk` must sever those references (its storage layer JSON-serializes\n * the binding) before the chunk is dropped. Returns the resolved tool names in\n * sorted order, matching `compileToolDefinitions`.\n */\nexport const streamOperationBindings = <E, R>(\n doc: ParsedDocument,\n chunkSize: number,\n onChunk: (chunk: readonly OperationBindingChunk[]) => Effect.Effect<void, E, R>,\n): Effect.Effect<\n { readonly toolCount: number; readonly toolNames: readonly string[] },\n OpenApiExtractionError | E,\n R\n> =>\n Effect.gen(function* () {\n const paths = doc.paths;\n if (!paths) {\n return yield* new OpenApiExtractionError({\n message: \"OpenAPI document has no paths defined\",\n });\n }\n\n const r = new DocResolver(doc);\n const docServers = extractServers(doc);\n\n // Pass 1 (light): collect schema-free path metadata + a parallel array of\n // references back into the tree. Both are small (no schemas copied).\n const inputs: OperationPathInput[] = [];\n const opRefs: OperationRef[] = [];\n for (const [pathTemplate, pathItem] of Object.entries(paths).sort(([a], [b]) =>\n a.localeCompare(b),\n )) {\n if (!pathItem) continue;\n for (const method of HTTP_METHODS) {\n const operation = pathItem[method];\n if (!operation) continue;\n const resolvedPathTemplate = explicitPathTemplate(operation) ?? pathTemplate;\n const tags = (operation.tags ?? []).filter((t) => t.trim().length > 0);\n inputs.push({\n operationId: deriveOperationId(method, pathTemplate, operation),\n explicitToolPath: explicitToolPath(operation),\n method,\n pathTemplate: resolvedPathTemplate,\n tag0: tags[0],\n });\n opRefs.push({ pathItem, operation, method, pathTemplate: resolvedPathTemplate });\n }\n }\n\n // Global, schema-free collision resolution + sort. Cheap relative to the\n // parsed tree; returns plans sorted by toolPath with an index back into\n // `opRefs`.\n const plans = planToolPaths(inputs);\n\n // Pass 2 (heavy, streamed): build a binding per operation, flush a chunk\n // once it fills, then drop it. Bindings reference tree subtrees; `onChunk`\n // serializes them, so peak stays at parse level.\n let chunk: OperationBindingChunk[] = [];\n for (const plan of plans) {\n const ref = opRefs[plan.operationIndex]!;\n const parameters = extractParameters(ref.pathItem, ref.operation, r);\n const requestBody = extractRequestBody(ref.operation, r);\n const responseBody = extractResponseBody(ref.operation, r);\n const servers = operationServers(ref.pathItem, ref.operation, docServers);\n chunk.push({\n toolName: plan.toolPath,\n description:\n ref.operation.description ??\n ref.operation.summary ??\n `${ref.method.toUpperCase()} ${ref.pathTemplate}`,\n binding: OperationBinding.make({\n method: ref.method,\n servers,\n pathTemplate: ref.pathTemplate,\n parameters,\n requestBody: Option.fromNullishOr(requestBody),\n responseBody: Option.fromNullishOr(responseBody),\n }),\n });\n if (chunk.length >= chunkSize) {\n yield* onChunk(chunk);\n chunk = [];\n }\n }\n if (chunk.length > 0) yield* onChunk(chunk);\n\n return { toolCount: plans.length, toolNames: plans.map((plan) => plan.toolPath) };\n }).pipe(Effect.withSpan(\"OpenApi.streamOperationBindings\"));\n\nconst isPathItemValue = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n/**\n * Stream invocation bindings straight from a `SpecStructure` (the structural\n * split of a large spec) without ever materializing the whole-document tree.\n *\n * This is the fully-streaming compile path: it never parses the spec whole.\n * Each path-item is parsed in isolation twice (pass 1 for light tool-path\n * planning metadata, pass 2 to build the heavy binding) and discarded, so peak\n * memory stays near the size of a single path-item plus the raw text, even for\n * the 37MB / 16.5k-operation Microsoft Graph spec that OOMs a whole-tree parse.\n * Re-parsing in pass 2 (rather than holding pass-1 tree references) is the\n * deliberate CPU-for-memory trade that keeps peak at one-path-item level.\n *\n * `keepPathItem`, when given, filters (and may trim) each path-item, so the same\n * primitive serves both a full-spec compile (no filter) and a selection (e.g.\n * the Microsoft Graph scope filter) with identical streaming guarantees. It is\n * applied identically in both passes so the per-operation index stays aligned.\n *\n * Schemas are never resolved here: parameter / requestBody / response component\n * `$ref`s resolve against the small (schema-free) components built from the\n * structure; `#/components/schemas/X` refs stay as strings in the binding and\n * are normalized + served from the content-addressed defs blob. Returns the\n * resolved tool names in sorted order, matching `compileToolDefinitions`.\n */\nexport const streamOperationBindingsFromStructure = <E, R>(\n structure: SpecStructure,\n options: { readonly chunkSize: number; readonly keepPathItem?: KeepPathItem },\n onChunk: (chunk: readonly OperationBindingChunk[]) => Effect.Effect<void, E, R>,\n): Effect.Effect<{ readonly toolCount: number; readonly toolNames: readonly string[] }, E, R> =>\n Effect.gen(function* () {\n const { chunkSize, keepPathItem } = options;\n\n // Parse one path-item range to its kept (optionally trimmed) value, applying\n // `keepPathItem` identically in both passes so the operation index aligns.\n const keptPathItem = (range: ByteRange): readonly [string, PathItemObject] | null => {\n const entry = parseEntry(structure.text, range, 2);\n if (!entry) return null;\n const [path, rawValue] = entry;\n if (!isPathItemValue(rawValue)) return null;\n if (!keepPathItem) return [path, rawValue as PathItemObject];\n const kept = keepPathItem(path, rawValue);\n return kept ? [path, kept as PathItemObject] : null;\n };\n\n // Pass 1 (light): collect schema-free tool-path planning metadata in\n // document order. No bindings, no schemas; one path-item resident at a time.\n const inputs: OperationPathInput[] = [];\n for (const range of structure.pathItems) {\n const kept = keptPathItem(range);\n if (!kept) continue;\n const [path, pathItem] = kept;\n for (const method of HTTP_METHODS) {\n const operation = pathItem[method];\n if (!operation) continue;\n const resolvedPathTemplate = explicitPathTemplate(operation) ?? path;\n const tags = (operation.tags ?? []).filter((t) => t.trim().length > 0);\n inputs.push({\n operationId: deriveOperationId(method, path, operation),\n explicitToolPath: explicitToolPath(operation),\n method,\n pathTemplate: resolvedPathTemplate,\n tag0: tags[0],\n });\n }\n }\n\n // Global, schema-free collision resolution + sort. `plan.operationIndex`\n // indexes back into `inputs` (document order), so a flat array recovers each\n // operation's assigned tool path during the document-order pass 2.\n const plans = planToolPaths(inputs);\n const planByOpIndex: (PlannedToolPath | undefined)[] = new Array(inputs.length);\n for (const plan of plans) planByOpIndex[plan.operationIndex] = plan;\n\n // Pass 2 (heavy, streamed): re-parse each path-item in the same document\n // order, build a binding per operation, flush a chunk once it fills, then\n // drop it. The resolver is schema-free (small components only); schema refs\n // stay as `$ref` strings in the bindings.\n // oxlint-disable-next-line executor/no-double-cast -- boundary: parseHead/parseSmallComponents return Record<string, unknown>, which does not structurally match the OpenAPIV3 Document union; the schema-free resolver doc (head + small components, empty paths) is only read for .servers (extractServers) and .components ($ref resolution).\n const resolverDoc = {\n ...parseHead(structure),\n paths: {},\n components: parseSmallComponents(structure),\n } as unknown as ParsedDocument;\n const r = new DocResolver(resolverDoc);\n const docServers = extractServers(resolverDoc);\n\n let opIndex = 0;\n let chunk: OperationBindingChunk[] = [];\n for (const range of structure.pathItems) {\n const kept = keptPathItem(range);\n if (!kept) continue;\n const [path, pathItem] = kept;\n for (const method of HTTP_METHODS) {\n const operation = pathItem[method];\n if (!operation) continue;\n const plan = planByOpIndex[opIndex];\n opIndex += 1;\n if (!plan) continue;\n const resolvedPathTemplate = explicitPathTemplate(operation) ?? path;\n const parameters = extractParameters(pathItem, operation, r);\n const requestBody = extractRequestBody(operation, r);\n const responseBody = extractResponseBody(operation, r);\n const servers = operationServers(pathItem, operation, docServers);\n chunk.push({\n toolName: plan.toolPath,\n description:\n operation.description ??\n operation.summary ??\n `${method.toUpperCase()} ${resolvedPathTemplate}`,\n binding: OperationBinding.make({\n method,\n servers,\n pathTemplate: resolvedPathTemplate,\n parameters,\n requestBody: Option.fromNullishOr(requestBody),\n responseBody: Option.fromNullishOr(responseBody),\n }),\n });\n if (chunk.length >= chunkSize) {\n yield* onChunk(chunk);\n chunk = [];\n }\n }\n }\n if (chunk.length > 0) yield* onChunk(chunk);\n\n return { toolCount: plans.length, toolNames: plans.map((plan) => plan.toolPath) };\n }).pipe(Effect.withSpan(\"OpenApi.streamOperationBindingsFromStructure\"));\n","/**\n * Derives structured `group.leaf` tool paths from extracted OpenAPI operations.\n *\n * Ported from the v3 executor's `definitions.ts`. Turns flat operation IDs like\n * `zones_listZones` into nested paths like `zones.listZones` that the tree UI\n * can render with proper nesting.\n */\n\nimport { Option } from \"effect\";\n\nimport type { ExtractedOperation } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Word / case utilities\n// ---------------------------------------------------------------------------\n\nconst splitWords = (value: string): string[] =>\n value\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/([A-Z]+)([A-Z][a-z0-9]+)/g, \"$1 $2\")\n .replace(/[^a-zA-Z0-9]+/g, \" \")\n .trim()\n .split(/\\s+/)\n .filter((part) => part.length > 0);\n\nconst normalizeWord = (value: string): string => value.toLowerCase();\n\nconst toCamelCase = (value: string): string => {\n const words = splitWords(value).map(normalizeWord);\n if (words.length === 0) return \"tool\";\n const [first, ...rest] = words;\n return `${first}${rest.map((p) => `${p[0]?.toUpperCase() ?? \"\"}${p.slice(1)}`).join(\"\")}`;\n};\n\nconst toPascalCase = (value: string): string => {\n const camel = toCamelCase(value);\n return `${camel[0]?.toUpperCase() ?? \"\"}${camel.slice(1)}`;\n};\n\n// ---------------------------------------------------------------------------\n// Path utilities\n// ---------------------------------------------------------------------------\n\nconst VERSION_SEGMENT_REGEX = /^v\\d+(?:[._-]\\d+)?$/i;\nconst IGNORED_PATH_SEGMENTS = new Set([\"api\"]);\n\nconst pathSegmentsFromTemplate = (pathTemplate: string): string[] =>\n pathTemplate\n .split(\"/\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n\nconst isPathParameterSegment = (segment: string): boolean =>\n segment.startsWith(\"{\") && segment.endsWith(\"}\");\n\nconst normalizeGroupSegment = (value: string | undefined): string | null => {\n const candidate = value?.trim();\n if (!candidate) return null;\n return toCamelCase(candidate);\n};\n\n// ---------------------------------------------------------------------------\n// Derivation\n// ---------------------------------------------------------------------------\n\nconst deriveVersionSegment = (pathTemplate: string): string | undefined =>\n pathSegmentsFromTemplate(pathTemplate)\n .map((s) => s.toLowerCase())\n .find((s) => VERSION_SEGMENT_REGEX.test(s));\n\nconst derivePathGroup = (pathTemplate: string): string => {\n for (const segment of pathSegmentsFromTemplate(pathTemplate)) {\n const lower = segment.toLowerCase();\n if (VERSION_SEGMENT_REGEX.test(lower)) continue;\n if (IGNORED_PATH_SEGMENTS.has(lower)) continue;\n if (isPathParameterSegment(segment)) continue;\n return normalizeGroupSegment(segment) ?? \"root\";\n }\n return \"root\";\n};\n\nconst splitOperationIdSegments = (value: string): string[] =>\n value\n .split(/[/.]+/)\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n\nconst deriveLeafSeed = (operationId: string, group: string): string => {\n const segments = splitOperationIdSegments(operationId);\n if (segments.length > 1) {\n const [first, ...rest] = segments;\n if ((normalizeGroupSegment(first) ?? first) === group && rest.length > 0) {\n return rest.join(\" \");\n }\n }\n return operationId;\n};\n\nconst fallbackLeafSeed = (method: string, pathTemplate: string, group: string): string => {\n const relevantSegments = pathSegmentsFromTemplate(pathTemplate)\n .filter((s) => !VERSION_SEGMENT_REGEX.test(s.toLowerCase()))\n .filter((s) => !IGNORED_PATH_SEGMENTS.has(s.toLowerCase()))\n .filter((s) => !isPathParameterSegment(s))\n .map((s) => normalizeGroupSegment(s) ?? s)\n .filter((s) => s !== group);\n\n const segmentSuffix = relevantSegments.map((s) => toPascalCase(s)).join(\"\");\n return `${method}${segmentSuffix || \"Operation\"}`;\n};\n\nconst deriveLeaf = (\n operationId: string,\n method: string,\n pathTemplate: string,\n group: string,\n): string => {\n const preferred = toCamelCase(deriveLeafSeed(operationId, group));\n if (preferred.length > 0 && preferred !== group) return preferred;\n return toCamelCase(fallbackLeafSeed(method, pathTemplate, group));\n};\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport interface ToolDefinition {\n /** Dot-separated path like `zones.listZones` */\n readonly toolPath: string;\n /** The group segment */\n readonly group: string;\n /** The leaf segment */\n readonly leaf: string;\n /** Index into the original operations array */\n readonly operationIndex: number;\n /** The original operation */\n readonly operation: ExtractedOperation;\n}\n\n/**\n * The minimal per-operation metadata the tool-path planner needs. Kept\n * deliberately light (no schemas) so the streaming compile path can plan paths\n * for tens of thousands of operations without holding the full extracted\n * operations in memory.\n */\nexport interface OperationPathInput {\n readonly operationId: string;\n readonly explicitToolPath: string | undefined;\n readonly method: string;\n readonly pathTemplate: string;\n /** The first non-empty tag, used to seed the group segment. */\n readonly tag0: string | undefined;\n}\n\n/** A resolved tool path plus its index back into the input operations array. */\nexport interface PlannedToolPath {\n readonly toolPath: string;\n readonly group: string;\n readonly leaf: string;\n readonly operationIndex: number;\n}\n\n// ---------------------------------------------------------------------------\n// Collision resolution\n// ---------------------------------------------------------------------------\n\ninterface RawToolPath {\n toolPath: string;\n group: string;\n leaf: string;\n versionSegment: string | undefined;\n method: string;\n operationHash: string;\n operationIndex: number;\n}\n\nconst resolveCollisions = (definitions: RawToolPath[]): PlannedToolPath[] => {\n // Mutable — we progressively refine toolPath on collision\n const staged = definitions.map((d) => ({ ...d }));\n\n const applyFactory = (items: typeof staged, factory: (d: (typeof staged)[number]) => string) => {\n const byPath = new Map<string, typeof staged>();\n for (const item of items) {\n const bucket = byPath.get(item.toolPath) ?? [];\n bucket.push(item);\n byPath.set(item.toolPath, bucket);\n }\n for (const bucket of byPath.values()) {\n if (bucket.length < 2) continue;\n for (const d of bucket) {\n d.toolPath = factory(d);\n }\n }\n };\n\n // Round 1: add version segment\n applyFactory(staged, (d) =>\n d.versionSegment ? `${d.group}.${d.versionSegment}.${d.leaf}` : d.toolPath,\n );\n\n // Round 2: add method suffix\n applyFactory(staged, (d) => {\n const prefix = d.versionSegment ? `${d.group}.${d.versionSegment}` : d.group;\n return `${prefix}.${d.leaf}${toPascalCase(d.method)}`;\n });\n\n // Round 3: add hash suffix\n applyFactory(staged, (d) => {\n const prefix = d.versionSegment ? `${d.group}.${d.versionSegment}` : d.group;\n return `${prefix}.${d.leaf}${toPascalCase(d.method)}${d.operationHash.slice(0, 8)}`;\n });\n\n return staged.map((d) => ({\n toolPath: d.toolPath,\n group: d.group,\n leaf: d.leaf,\n operationIndex: d.operationIndex,\n }));\n};\n\n// ---------------------------------------------------------------------------\n// Stable hash (simple, deterministic)\n// ---------------------------------------------------------------------------\n\nconst stableHash = (value: unknown): string => {\n const str = JSON.stringify(value, Object.keys(value as Record<string, unknown>).sort());\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) - hash + str.charCodeAt(i)) | 0;\n }\n return Math.abs(hash).toString(36).padStart(8, \"0\");\n};\n\n// ---------------------------------------------------------------------------\n// Main entry point\n// ---------------------------------------------------------------------------\n\n/**\n * Plan structured `group.leaf` tool paths from lightweight per-operation\n * metadata. Path derivation + collision resolution need a global view of every\n * operation, but only its name/method/path/tag, never its schemas. Keeping this\n * pass schema-free lets the streaming compile path plan paths for a 16k-op spec\n * without materializing the full extracted operations.\n *\n * The returned `operationIndex` points back into the `inputs` array.\n */\nexport const planToolPaths = (inputs: readonly OperationPathInput[]): PlannedToolPath[] => {\n const raw: RawToolPath[] = inputs.map((op, index) => {\n const operationId = op.operationId;\n const operationHash = stableHash({\n method: op.method,\n path: op.pathTemplate,\n operationId,\n });\n const versionSegment = deriveVersionSegment(op.pathTemplate);\n\n if (op.explicitToolPath) {\n const [group = \"root\", ...leafParts] = op.explicitToolPath.split(\".\").filter(Boolean);\n const leaf = leafParts.join(\".\") || group;\n return {\n toolPath: op.explicitToolPath,\n group,\n leaf,\n versionSegment,\n method: op.method,\n operationHash,\n operationIndex: index,\n };\n }\n\n const group = normalizeGroupSegment(op.tag0) ?? derivePathGroup(op.pathTemplate);\n const leaf = deriveLeaf(operationId, op.method, op.pathTemplate, group);\n return {\n toolPath: `${group}.${leaf}`,\n group,\n leaf,\n versionSegment,\n method: op.method,\n operationHash,\n operationIndex: index,\n };\n });\n\n return resolveCollisions(raw).sort((a, b) => a.toolPath.localeCompare(b.toolPath));\n};\n\n/**\n * Compile extracted operations into tool definitions with structured\n * `group.leaf` paths suitable for tree rendering. Thin wrapper over\n * `planToolPaths` that re-attaches each operation by index.\n */\nexport const compileToolDefinitions = (\n operations: readonly ExtractedOperation[],\n): ToolDefinition[] => {\n const plans = planToolPaths(\n operations.map((op) => ({\n operationId: op.operationId,\n explicitToolPath: Option.getOrUndefined(op.toolPath),\n method: op.method,\n pathTemplate: op.pathTemplate,\n tag0: op.tags[0],\n })),\n );\n\n return plans.map((plan) => ({\n toolPath: plan.toolPath,\n group: plan.group,\n leaf: plan.leaf,\n operationIndex: plan.operationIndex,\n operation: operations[plan.operationIndex]!,\n }));\n};\n","import { Effect, Option, Predicate } from \"effect\";\nimport { Schema } from \"effect\";\n\nimport { parse, resolveSpecText, type ParsedDocument } from \"./parse\";\nimport { extract } from \"./extract\";\nimport { DocResolver } from \"./openapi-utils\";\nimport { HttpMethod, ServerInfo, type ExtractionResult } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// OAuth 2.0 flows — one entry per supported grant type\n// ---------------------------------------------------------------------------\n\n/** Scopes declared by a flow: `{ scopeName: description }` */\nconst OAuth2Scopes = Schema.Record(Schema.String, Schema.String);\nconst SecuritySchemeType = Schema.Literals([\"http\", \"apiKey\", \"oauth2\", \"openIdConnect\"]);\ntype SecuritySchemeType = typeof SecuritySchemeType.Type;\n\nconst decodeSecuritySchemeType = Schema.decodeUnknownOption(SecuritySchemeType);\n\nexport const OAuth2AuthorizationCodeFlow = Schema.Struct({\n authorizationUrl: Schema.String,\n tokenUrl: Schema.String,\n refreshUrl: Schema.OptionFromOptional(Schema.String),\n scopes: OAuth2Scopes,\n});\nexport type OAuth2AuthorizationCodeFlow = typeof OAuth2AuthorizationCodeFlow.Type;\n\nexport const OAuth2ClientCredentialsFlow = Schema.Struct({\n tokenUrl: Schema.String,\n refreshUrl: Schema.OptionFromOptional(Schema.String),\n scopes: OAuth2Scopes,\n});\nexport type OAuth2ClientCredentialsFlow = typeof OAuth2ClientCredentialsFlow.Type;\n\nexport const OAuth2Flows = Schema.Struct({\n authorizationCode: Schema.OptionFromOptional(OAuth2AuthorizationCodeFlow),\n clientCredentials: Schema.OptionFromOptional(OAuth2ClientCredentialsFlow),\n});\nexport type OAuth2Flows = typeof OAuth2Flows.Type;\n\n// ---------------------------------------------------------------------------\n// Security scheme — what the spec declares it needs\n// ---------------------------------------------------------------------------\n\nexport const SecurityScheme = Schema.Struct({\n /** Key name in components.securitySchemes (e.g. \"api_token\") */\n name: Schema.String,\n /** OpenAPI security scheme type */\n type: SecuritySchemeType,\n /** For type: \"http\" — e.g. \"bearer\", \"basic\" */\n scheme: Schema.OptionFromOptional(Schema.String),\n /** For type: \"http\" with scheme \"bearer\" — e.g. \"JWT\" */\n bearerFormat: Schema.OptionFromOptional(Schema.String),\n /** For type: \"apiKey\" — where the key goes */\n in: Schema.OptionFromOptional(Schema.Literals([\"header\", \"query\", \"cookie\"])),\n /** For type: \"apiKey\" — the header/query/cookie name */\n headerName: Schema.OptionFromOptional(Schema.String),\n description: Schema.OptionFromOptional(Schema.String),\n /** For type: \"oauth2\" — declared flows (authorizationCode / clientCredentials only; implicit and password are deprecated). */\n flows: Schema.OptionFromOptional(OAuth2Flows),\n /** For type: \"openIdConnect\" — the discovery URL. */\n openIdConnectUrl: Schema.OptionFromOptional(Schema.String),\n});\nexport type SecurityScheme = typeof SecurityScheme.Type;\n\n// ---------------------------------------------------------------------------\n// Auth strategy — a valid combination of security schemes\n// ---------------------------------------------------------------------------\n\nexport const AuthStrategy = Schema.Struct({\n /** The security schemes required together for this strategy */\n schemes: Schema.Array(Schema.String),\n});\nexport type AuthStrategy = typeof AuthStrategy.Type;\n\n// ---------------------------------------------------------------------------\n// Header preset — derived from an auth strategy\n// ---------------------------------------------------------------------------\n\nexport const HeaderPreset = Schema.Struct({\n /** Human-readable label for the UI (e.g. \"Bearer Token\", \"API Key + Email\") */\n label: Schema.String,\n /** Headers this strategy needs. Value is null when the user must provide it. */\n headers: Schema.Record(Schema.String, Schema.NullOr(Schema.String)),\n /** Which headers should be stored as secrets */\n secretHeaders: Schema.Array(Schema.String),\n});\nexport type HeaderPreset = typeof HeaderPreset.Type;\n\n// ---------------------------------------------------------------------------\n// OAuth2 preset — derived from an oauth2 security scheme + a flow choice\n// ---------------------------------------------------------------------------\n\nexport const OAuth2Preset = Schema.Struct({\n /** Human-readable label for the UI (e.g. \"OAuth2 (Authorization Code) — oauth_app\") */\n label: Schema.String,\n /** The source security scheme this preset came from (components.securitySchemes key). */\n securitySchemeName: Schema.String,\n /** Which OAuth2 flow this preset uses. */\n flow: Schema.Literals([\"authorizationCode\", \"clientCredentials\"]),\n /** For authorizationCode: user-agent redirect URL (from the spec). */\n authorizationUrl: Schema.OptionFromOptional(Schema.String),\n /** Token endpoint to exchange the code / refresh. */\n tokenUrl: Schema.String,\n /** RFC 8707 resource indicator discovered from protected-resource metadata. */\n resource: Schema.OptionFromOptional(Schema.String),\n /** Optional refresh endpoint if the spec declares one separately. */\n refreshUrl: Schema.OptionFromOptional(Schema.String),\n /** Declared scopes for this flow: `{ scope: description }`. */\n scopes: Schema.Record(Schema.String, Schema.String),\n /** Identity scopes to request alongside API scopes. `\"auto\"` discovers standard OIDC scopes. */\n identityScopes: Schema.Union([\n Schema.Literal(\"auto\"),\n Schema.Literal(false),\n Schema.Array(Schema.String),\n ]),\n /** Provider metadata advertised Client ID Metadata Document support. */\n supportsClientIdMetadataDocument: Schema.optional(Schema.Boolean),\n});\nexport type OAuth2Preset = typeof OAuth2Preset.Type;\n\n// ---------------------------------------------------------------------------\n// Preview operation — lightweight shape for the add-source UI list\n// ---------------------------------------------------------------------------\n\nexport const PreviewOperation = Schema.Struct({\n operationId: Schema.String,\n method: HttpMethod,\n path: Schema.String,\n summary: Schema.OptionFromOptional(Schema.String),\n tags: Schema.Array(Schema.String),\n deprecated: Schema.Boolean,\n});\nexport type PreviewOperation = typeof PreviewOperation.Type;\n\n// ---------------------------------------------------------------------------\n// Spec preview — everything the frontend needs\n// ---------------------------------------------------------------------------\n\nexport const SpecPreview = Schema.Struct({\n title: Schema.OptionFromOptional(Schema.String),\n /** The spec's `info.description` — prefills the add form's description field. */\n description: Schema.OptionFromOptional(Schema.String),\n version: Schema.OptionFromOptional(Schema.String),\n /** Reuses ServerInfo from extraction */\n servers: Schema.Array(ServerInfo),\n operationCount: Schema.Number,\n /** Lightweight operation list for the add-source UI */\n operations: Schema.Array(PreviewOperation),\n tags: Schema.Array(Schema.String),\n securitySchemes: Schema.Array(SecurityScheme),\n /** Valid auth strategies (each is a set of schemes used together) */\n authStrategies: Schema.Array(AuthStrategy),\n /** Pre-built header presets derived from auth strategies */\n headerPresets: Schema.Array(HeaderPreset),\n /** OAuth2 presets — one per (oauth2 scheme × supported flow) combination */\n oauth2Presets: Schema.Array(OAuth2Preset),\n});\nexport type SpecPreview = typeof SpecPreview.Type;\n\n// HTTP/UI preview deliberately omits the per-operation list. Graph-sized specs\n// can define 16k+ operations, while the add flow only needs counts, tags,\n// servers, and auth metadata before registration.\nexport const SpecPreviewSummary = Schema.Struct({\n title: Schema.OptionFromOptional(Schema.String),\n description: Schema.OptionFromOptional(Schema.String),\n version: Schema.OptionFromOptional(Schema.String),\n servers: Schema.Array(ServerInfo),\n operationCount: Schema.Number,\n tags: Schema.Array(Schema.String),\n securitySchemes: Schema.Array(SecurityScheme),\n authStrategies: Schema.Array(AuthStrategy),\n headerPresets: Schema.Array(HeaderPreset),\n oauth2Presets: Schema.Array(OAuth2Preset),\n});\nexport type SpecPreviewSummary = typeof SpecPreviewSummary.Type;\n\nexport const specPreviewSummary = (preview: SpecPreview): SpecPreviewSummary =>\n SpecPreviewSummary.make({\n title: preview.title,\n description: preview.description,\n version: preview.version,\n servers: preview.servers,\n operationCount: preview.operationCount,\n tags: preview.tags,\n securitySchemes: preview.securitySchemes,\n authStrategies: preview.authStrategies,\n headerPresets: preview.headerPresets,\n oauth2Presets: preview.oauth2Presets,\n });\n\n// ---------------------------------------------------------------------------\n// Security scheme extraction\n// ---------------------------------------------------------------------------\n\nconst stringRecord = (value: unknown): Record<string, string> => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (typeof v === \"string\") out[k] = v;\n }\n return out;\n};\n\nconst extractFlows = (rawFlows: unknown): Option.Option<OAuth2Flows> => {\n if (!rawFlows || typeof rawFlows !== \"object\") return Option.none();\n const flows = rawFlows as Record<string, unknown>;\n\n const parseFlow = <K extends \"authorizationCode\" | \"clientCredentials\">(key: K): unknown =>\n flows[key];\n\n let authorizationCode: Option.Option<OAuth2AuthorizationCodeFlow> = Option.none();\n const authCodeRaw = parseFlow(\"authorizationCode\");\n if (authCodeRaw && typeof authCodeRaw === \"object\") {\n const f = authCodeRaw as Record<string, unknown>;\n const authUrl = typeof f.authorizationUrl === \"string\" ? f.authorizationUrl : null;\n const tokenUrl = typeof f.tokenUrl === \"string\" ? f.tokenUrl : null;\n if (authUrl && tokenUrl) {\n authorizationCode = Option.some(\n OAuth2AuthorizationCodeFlow.make({\n authorizationUrl: authUrl,\n tokenUrl,\n refreshUrl: Option.fromNullishOr(\n typeof f.refreshUrl === \"string\" ? f.refreshUrl : undefined,\n ),\n scopes: stringRecord(f.scopes),\n }),\n );\n }\n }\n\n let clientCredentials: Option.Option<OAuth2ClientCredentialsFlow> = Option.none();\n const ccRaw = parseFlow(\"clientCredentials\");\n if (ccRaw && typeof ccRaw === \"object\") {\n const f = ccRaw as Record<string, unknown>;\n const tokenUrl = typeof f.tokenUrl === \"string\" ? f.tokenUrl : null;\n if (tokenUrl) {\n clientCredentials = Option.some(\n OAuth2ClientCredentialsFlow.make({\n tokenUrl,\n refreshUrl: Option.fromNullishOr(\n typeof f.refreshUrl === \"string\" ? f.refreshUrl : undefined,\n ),\n scopes: stringRecord(f.scopes),\n }),\n );\n }\n }\n\n if (Option.isNone(authorizationCode) && Option.isNone(clientCredentials)) {\n return Option.none();\n }\n return Option.some(OAuth2Flows.make({ authorizationCode, clientCredentials }));\n};\n\nconst extractSecuritySchemes = (\n rawSchemes: Record<string, unknown>,\n resolver: DocResolver,\n): SecurityScheme[] =>\n Object.entries(rawSchemes).flatMap(([name, schemeOrRef]) => {\n if (!schemeOrRef || typeof schemeOrRef !== \"object\") return [];\n // Resolve $ref so schemes defined via `$ref` aren't silently dropped.\n const resolved = resolver.resolve<Record<string, unknown>>(\n schemeOrRef as Record<string, unknown>,\n );\n if (!resolved || typeof resolved !== \"object\") return [];\n const scheme = resolved;\n\n const type = decodeSecuritySchemeType(scheme.type);\n if (Option.isNone(type)) return [];\n const schemeType = type.value;\n\n return [\n SecurityScheme.make({\n name,\n type: schemeType,\n scheme: Option.fromNullishOr(scheme.scheme as string | undefined),\n bearerFormat: Option.fromNullishOr(scheme.bearerFormat as string | undefined),\n in: Option.fromNullishOr(scheme.in as \"header\" | \"query\" | \"cookie\" | undefined),\n headerName: Option.fromNullishOr(scheme.name as string | undefined),\n description: Option.fromNullishOr(scheme.description as string | undefined),\n flows: schemeType === \"oauth2\" ? extractFlows(scheme.flows) : Option.none(),\n openIdConnectUrl: Option.fromNullishOr(scheme.openIdConnectUrl as string | undefined),\n }),\n ];\n });\n\n// ---------------------------------------------------------------------------\n// Header preset builder\n// ---------------------------------------------------------------------------\n\nconst buildHeaderPresets = (\n schemes: readonly SecurityScheme[],\n strategies: readonly AuthStrategy[],\n): HeaderPreset[] => {\n const schemeMap = new Map(schemes.map((s) => [s.name, s]));\n\n return strategies.flatMap((strategy) => {\n const resolved = strategy.schemes\n .map((name) => schemeMap.get(name))\n .filter(Predicate.isNotUndefined);\n\n if (resolved.length === 0) return [];\n\n const headers: Record<string, string | null> = {};\n const secretHeaders: string[] = [];\n const labelParts: string[] = [];\n\n for (const scheme of resolved) {\n if (scheme.type === \"http\" && Option.getOrElse(scheme.scheme, () => \"\") === \"bearer\") {\n headers[\"Authorization\"] = null;\n secretHeaders.push(\"Authorization\");\n labelParts.push(\"Bearer Token\");\n } else if (scheme.type === \"http\" && Option.getOrElse(scheme.scheme, () => \"\") === \"basic\") {\n headers[\"Authorization\"] = null;\n secretHeaders.push(\"Authorization\");\n labelParts.push(\"Basic Auth\");\n } else if (scheme.type === \"apiKey\" && Option.getOrElse(scheme.in, () => \"\") === \"header\") {\n const headerName = Option.getOrElse(scheme.headerName, () => scheme.name);\n headers[headerName] = null;\n secretHeaders.push(headerName);\n labelParts.push(scheme.name);\n } else if (scheme.type === \"apiKey\") {\n labelParts.push(`${scheme.name} (${Option.getOrElse(scheme.in, () => \"unknown\")})`);\n } else if (scheme.type === \"oauth2\" || scheme.type === \"openIdConnect\") {\n return [];\n } else {\n labelParts.push(scheme.name);\n }\n }\n\n if (Object.keys(headers).length === 0 && resolved.length > 0) {\n return [\n HeaderPreset.make({\n label: labelParts.join(\" + \"),\n headers: {},\n secretHeaders: [],\n }),\n ];\n }\n\n return [\n HeaderPreset.make({\n label: labelParts.join(\" + \"),\n headers,\n secretHeaders,\n }),\n ];\n });\n};\n\n// ---------------------------------------------------------------------------\n// OAuth2 preset builder\n// ---------------------------------------------------------------------------\n\nconst buildOAuth2Presets = (schemes: readonly SecurityScheme[]): OAuth2Preset[] => {\n const presets: OAuth2Preset[] = [];\n for (const scheme of schemes) {\n if (scheme.type !== \"oauth2\") continue;\n if (Option.isNone(scheme.flows)) continue;\n const flows = scheme.flows.value;\n\n if (Option.isSome(flows.authorizationCode)) {\n const flow = flows.authorizationCode.value;\n presets.push(\n OAuth2Preset.make({\n label: `OAuth2 Authorization Code · ${scheme.name}`,\n securitySchemeName: scheme.name,\n flow: \"authorizationCode\",\n authorizationUrl: Option.some(flow.authorizationUrl),\n tokenUrl: flow.tokenUrl,\n resource: Option.none(),\n refreshUrl: flow.refreshUrl,\n scopes: flow.scopes,\n identityScopes: \"auto\",\n }),\n );\n }\n\n if (Option.isSome(flows.clientCredentials)) {\n const flow = flows.clientCredentials.value;\n presets.push(\n OAuth2Preset.make({\n label: `OAuth2 Client Credentials · ${scheme.name}`,\n securitySchemeName: scheme.name,\n flow: \"clientCredentials\",\n authorizationUrl: Option.none(),\n tokenUrl: flow.tokenUrl,\n resource: Option.none(),\n refreshUrl: flow.refreshUrl,\n scopes: flow.scopes,\n identityScopes: false,\n }),\n );\n }\n }\n return presets;\n};\n\n// ---------------------------------------------------------------------------\n// Collect unique tags from extraction result\n// ---------------------------------------------------------------------------\n\nconst collectTags = (result: ExtractionResult): string[] => {\n const tagSet = new Set<string>();\n for (const op of result.operations) {\n for (const tag of op.tags) tagSet.add(tag);\n }\n return [...tagSet].sort();\n};\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/** Preview already-resolved spec text — extract metadata without registering\n * anything and without any HTTP dependency. */\nexport const previewSpecText = Effect.fn(\"OpenApi.previewSpecText\")(function* (specText: string) {\n const doc: ParsedDocument = yield* parse(specText);\n const result = yield* extract(doc);\n\n const resolver = new DocResolver(doc);\n const securitySchemes = extractSecuritySchemes(doc.components?.securitySchemes ?? {}, resolver);\n\n const rawSecurity = (doc.security ?? []) as Array<Record<string, unknown>>;\n const declaredStrategies = rawSecurity.map((entry) =>\n AuthStrategy.make({ schemes: Object.keys(entry) }),\n );\n // Fall back to one strategy per scheme when the spec only declares schemes\n // under components (e.g. Sentry) so the user still sees auth options.\n const authStrategies =\n declaredStrategies.length > 0\n ? declaredStrategies\n : securitySchemes.map((scheme) => AuthStrategy.make({ schemes: [scheme.name] }));\n\n return SpecPreview.make({\n title: result.title,\n description: result.description,\n version: result.version,\n servers: result.servers,\n operationCount: result.operations.length,\n operations: result.operations.map((op) =>\n PreviewOperation.make({\n operationId: op.operationId,\n method: op.method,\n path: op.pathTemplate,\n summary: op.summary,\n tags: op.tags,\n deprecated: op.deprecated,\n }),\n ),\n tags: collectTags(result),\n securitySchemes,\n authStrategies,\n headerPresets: buildHeaderPresets(securitySchemes, authStrategies),\n oauth2Presets: buildOAuth2Presets(securitySchemes),\n });\n});\n\n/** Preview an OpenAPI spec — extract metadata without registering anything.\n * Accepts either a URL or raw JSON/YAML text. */\nexport const previewSpec = Effect.fn(\"OpenApi.previewSpec\")(function* (input: string) {\n const specText = yield* resolveSpecText(input);\n return yield* previewSpecText(specText);\n});\n"],"mappings":";AAAA,SAAS,MAAM,cAAc;AAWtB,IAAM,oBAAN,cAAgC,OAAO,iBAAoC;AAAA,EAChF;AAAA,EACA;AAAA,IACE,SAAS,OAAO;AAAA,EAClB;AAAA,EACA,EAAE,eAAe,IAAI;AACvB,EAAE;AAAC;AAEI,IAAM,yBAAN,cAAqC,OAAO,iBAAyC;AAAA,EAC1F;AAAA,EACA;AAAA,IACE,SAAS,OAAO;AAAA,EAClB;AAAA,EACA,EAAE,eAAe,IAAI;AACvB,EAAE;AAAC;AAEI,IAAM,yBAAN,cAAqC,KAAK,YAAY,wBAAwB,EAIlF;AAAC;AAEG,IAAM,oBAAN,cAAgC,OAAO,iBAAoC;AAAA,EAChF;AAAA,EACA;AAAA,IACE,SAAS,OAAO;AAAA,EAClB;AAAA,EACA,EAAE,eAAe,IAAI;AACvB,EAAE;AAAC;AAOI,IAAM,2BAAN,cAAuC,KAAK,YAAY,0BAA0B,EAWtF;AAAC;;;ACxDJ,SAAS,UAAU,QAAQ,UAAAA,eAAc;AACzC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B,SAAS,OAAO;AAAA,IAChB,gBAAgB,OAAO,WAAW;AAAA,IAClC,YAAY,OAAO,WAAW;AAAA,MAAI,CAAC,OACjC,iBAAiB,KAAK;AAAA,QACpB,aAAa,GAAG;AAAA,QAChB,QAAQ,GAAG;AAAA,QACX,MAAM,GAAG;AAAA,QACT,SAAS,GAAG;AAAA,QACZ,MAAM,GAAG;AAAA,QACT,YAAY,GAAG;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,IACA,MAAM,YAAY,MAAM;AAAA,IACxB;AAAA,IACA;AAAA,IACA,eAAe,mBAAmB,iBAAiB,cAAc;AAAA,IACjE,eAAe,mBAAmB,eAAe;AAAA,EACnD,CAAC;AACH,CAAC;AAIM,IAAM,cAAcA,QAAO,GAAG,qBAAqB,EAAE,WAAW,OAAe;AACpF,QAAM,WAAW,OAAO,gBAAgB,KAAK;AAC7C,SAAO,OAAO,gBAAgB,QAAQ;AACxC,CAAC;","names":["Schema","Schema","parseYaml","JSON_SCHEMA","parseYamlDocument","Schema","Effect","Option","group","leaf","Option","Effect","Effect","Option","Schema","Schema","Option","Effect"]}