@executor-js/plugin-openapi 0.0.1-beta.6 → 0.0.2

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 (41) hide show
  1. package/README.md +24 -23
  2. package/dist/api/group.d.ts +94 -37
  3. package/dist/api/handlers.d.ts +2 -2
  4. package/dist/chunk-ZZ7TQ4JC.js +2602 -0
  5. package/dist/chunk-ZZ7TQ4JC.js.map +1 -0
  6. package/dist/core.js +46 -50
  7. package/dist/core.js.map +1 -1
  8. package/dist/index.js +2 -5
  9. package/dist/index.js.map +1 -1
  10. package/dist/react/AddOpenApiSource.d.ts +13 -0
  11. package/dist/react/EditOpenApiSource.d.ts +2 -2
  12. package/dist/react/OpenApiSourceSummary.d.ts +3 -1
  13. package/dist/react/atoms.d.ts +129 -0
  14. package/dist/react/client.d.ts +421 -3
  15. package/dist/react/source-plugin.d.ts +1 -1
  16. package/dist/sdk/client-credentials-oauth.test.d.ts +1 -0
  17. package/dist/sdk/credential-status.d.ts +23 -0
  18. package/dist/sdk/credential-status.test.d.ts +1 -0
  19. package/dist/sdk/errors.d.ts +11 -10
  20. package/dist/sdk/form-urlencoded-body.test.d.ts +1 -0
  21. package/dist/sdk/index.d.ts +8 -10
  22. package/dist/sdk/invoke.d.ts +8 -17
  23. package/dist/sdk/multi-scope-bearer.test.d.ts +1 -0
  24. package/dist/sdk/multi-scope-oauth.test.d.ts +1 -0
  25. package/dist/sdk/non-json-body.test.d.ts +1 -0
  26. package/dist/sdk/oauth-refresh.test.d.ts +1 -0
  27. package/dist/sdk/openapi-utils.d.ts +35 -4
  28. package/dist/sdk/parse.d.ts +28 -4
  29. package/dist/sdk/plugin.d.ts +169 -22
  30. package/dist/sdk/preview-oauth2.test.d.ts +1 -0
  31. package/dist/sdk/preview.d.ts +89 -125
  32. package/dist/sdk/store.d.ts +201 -0
  33. package/dist/sdk/types.d.ts +234 -266
  34. package/package.json +11 -22
  35. package/dist/chunk-V3D5A6HA.js +0 -1224
  36. package/dist/chunk-V3D5A6HA.js.map +0 -1
  37. package/dist/promise.d.ts +0 -6
  38. package/dist/sdk/config-file-store.d.ts +0 -10
  39. package/dist/sdk/kv-operation-store.d.ts +0 -4
  40. package/dist/sdk/operation-store.d.ts +0 -35
  41. package/dist/sdk/stored-source.d.ts +0 -46
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sdk/errors.ts","../src/sdk/parse.ts","../src/sdk/openapi-utils.ts","../src/sdk/types.ts","../src/sdk/extract.ts","../src/sdk/invoke.ts","../src/sdk/preview.ts","../src/sdk/store.ts","../src/sdk/plugin.ts","../src/sdk/definitions.ts"],"sourcesContent":["import { Data, Schema } from \"effect\";\nimport type { Option } from \"effect\";\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","import type { OpenAPI, OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\nimport { Duration, Effect } from \"effect\";\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\";\nimport YAML from \"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` and\n * avoids json-schema-ref-parser's Node-polyfill http resolver, which hangs\n * in production. Bounded by a 20s 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(20)),\n Effect.mapError(\n (cause) =>\n new OpenApiParseError({\n message: `Failed to fetch OpenAPI document: ${cause instanceof Error ? cause.message : String(cause)}`,\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 return yield* response.text.pipe(\n Effect.mapError(\n (cause) =>\n new OpenApiParseError({\n message: `Failed to read OpenAPI document body: ${cause instanceof Error ? cause.message : String(cause)}`,\n }),\n ),\n );\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* Effect.try({\n try: () => parseTextToObject(text),\n catch: (error) =>\n new OpenApiParseError({\n message: `Failed to parse OpenAPI document: ${error instanceof Error ? error.message : String(error)}`,\n }),\n });\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): OpenAPI.Document => {\n const trimmed = text.trim();\n if (trimmed.length === 0) throw new Error(\"OpenAPI document is empty\");\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n parsed = YAML.parse(trimmed);\n }\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new Error(\"OpenAPI document must parse to an object\");\n }\n\n return parsed as OpenAPI.Document;\n};\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 { Option } from \"effect\";\nimport type { OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\nimport type { ParsedDocument } from \"./parse\";\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;\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 = (\n url: string,\n values: Record<string, string>,\n): 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\ntype ServerLike = {\n url: string;\n variables: import(\"effect/Option\").Option<\n Record<string, { default: string } | string>\n >;\n};\n\nexport const resolveBaseUrl = (servers: readonly ServerLike[]): string => {\n const server = servers[0];\n if (!server) return \"\";\n\n if (!Option.isSome(server.variables)) return server.url;\n\n const values: Record<string, string> = {};\n for (const [name, v] of Object.entries(server.variables.value)) {\n values[name] = typeof v === \"string\" ? v : v.default;\n }\n return substituteUrlVariables(server.url, 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 { ConnectionId, ScopeId, SecretBackedValue, SecretId } from \"@executor-js/sdk/core\";\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 class OperationParameter extends Schema.Class<OperationParameter>(\"OperationParameter\")({\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}) {}\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 class EncodingObject extends Schema.Class<EncodingObject>(\"EncodingObject\")({\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}) {}\n\nexport class MediaBinding extends Schema.Class<MediaBinding>(\"MediaBinding\")({\n contentType: Schema.String,\n schema: Schema.OptionFromOptional(Schema.Unknown),\n encoding: Schema.OptionFromOptional(Schema.Record(Schema.String, EncodingObject)),\n}) {}\n\nexport class OperationRequestBody extends Schema.Class<OperationRequestBody>(\n \"OperationRequestBody\",\n)({\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}) {}\n\nexport class ExtractedOperation extends Schema.Class<ExtractedOperation>(\"ExtractedOperation\")({\n operationId: OperationId,\n method: HttpMethod,\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 inputSchema: Schema.OptionFromOptional(Schema.Unknown),\n outputSchema: Schema.OptionFromOptional(Schema.Unknown),\n deprecated: Schema.Boolean,\n}) {}\n\nexport class ServerVariable extends Schema.Class<ServerVariable>(\"ServerVariable\")({\n default: Schema.String,\n enum: Schema.OptionFromOptional(Schema.Array(Schema.String)),\n description: Schema.OptionFromOptional(Schema.String),\n}) {}\n\nexport class ServerInfo extends Schema.Class<ServerInfo>(\"ServerInfo\")({\n url: Schema.String,\n description: Schema.OptionFromOptional(Schema.String),\n variables: Schema.OptionFromOptional(Schema.Record(Schema.String, ServerVariable)),\n}) {}\n\nexport class ExtractionResult extends Schema.Class<ExtractionResult>(\"ExtractionResult\")({\n title: Schema.OptionFromOptional(Schema.String),\n version: Schema.OptionFromOptional(Schema.String),\n servers: Schema.Array(ServerInfo),\n operations: Schema.Array(ExtractedOperation),\n}) {}\n\n// ---------------------------------------------------------------------------\n// Operation binding — minimal invocation data (no schemas/metadata)\n// ---------------------------------------------------------------------------\n\nexport class OperationBinding extends Schema.Class<OperationBinding>(\"OperationBinding\")({\n method: HttpMethod,\n pathTemplate: Schema.String,\n parameters: Schema.Array(OperationParameter),\n requestBody: Schema.OptionFromOptional(OperationRequestBody),\n}) {}\n\n// ---------------------------------------------------------------------------\n// Invocation\n// ---------------------------------------------------------------------------\n\n/**\n * A header value — either a static string or a reference to a secret.\n * Stored as JSON-serializable data.\n */\nexport const HeaderValue = SecretBackedValue;\nexport type HeaderValue = typeof HeaderValue.Type;\n\nexport class ConfiguredHeaderBinding extends Schema.Class<ConfiguredHeaderBinding>(\n \"OpenApiConfiguredHeaderBinding\",\n)({\n kind: Schema.Literal(\"binding\"),\n slot: Schema.String,\n prefix: Schema.optional(Schema.String),\n}) {}\n\nexport const ConfiguredHeaderValue = Schema.Union([Schema.String, ConfiguredHeaderBinding]);\nexport type ConfiguredHeaderValue = typeof ConfiguredHeaderValue.Type;\n\nexport const OpenApiSourceBindingValue = Schema.Union([\n Schema.Struct({\n kind: Schema.Literal(\"secret\"),\n secretId: SecretId,\n }),\n Schema.Struct({\n kind: Schema.Literal(\"connection\"),\n connectionId: ConnectionId,\n }),\n Schema.Struct({\n kind: Schema.Literal(\"text\"),\n text: Schema.String,\n }),\n]);\nexport type OpenApiSourceBindingValue = typeof OpenApiSourceBindingValue.Type;\n\nexport const OpenApiSourceBindingInputSchema = Schema.Struct({\n sourceId: Schema.String,\n sourceScope: ScopeId,\n scope: ScopeId,\n slot: Schema.String,\n value: OpenApiSourceBindingValue,\n});\n\nexport class OpenApiSourceBindingInput extends Schema.Class<OpenApiSourceBindingInput>(\n \"OpenApiSourceBindingInput\",\n)(OpenApiSourceBindingInputSchema.fields) {}\n\nexport class OpenApiSourceBindingRef extends Schema.Class<OpenApiSourceBindingRef>(\n \"OpenApiSourceBindingRef\",\n)({\n sourceId: Schema.String,\n sourceScopeId: ScopeId,\n scopeId: ScopeId,\n slot: Schema.String,\n value: OpenApiSourceBindingValue,\n createdAt: Schema.Date,\n updatedAt: Schema.Date,\n}) {}\n\n// ---------------------------------------------------------------------------\n// OAuth2 auth — points at the Connection that owns live tokens, and also\n// carries enough API-level config to kick off a fresh sign-in from the\n// source detail UI without needing the connection to still exist.\n//\n// Split of responsibilities:\n// - The Source owns: the OAuth config (tokenUrl, authorizationUrl,\n// client credential secret ids, scopes, flow, securitySchemeName).\n// Values are a property of the target API, identical for every user\n// signing into this source. Source-owned = reconnect works even if\n// the connection row has been removed.\n// - The Connection owns: live access/refresh tokens, token expiry,\n// provider state the refresh path reads from. The connection's\n// `providerState` caches the refresh-relevant bits of the config\n// so the refresh loop never reaches back into source storage.\n//\n// This is a deliberate small duplication (scopes + tokenUrl +\n// clientIdSecretId + clientSecretSecretId appear on both). The values\n// are static per source so the two copies can't drift.\n// ---------------------------------------------------------------------------\n\nexport const OAuth2Flow = Schema.Literals([\"authorizationCode\", \"clientCredentials\"]);\nexport type OAuth2Flow = typeof OAuth2Flow.Type;\n\nexport class OAuth2Auth extends Schema.Class<OAuth2Auth>(\"OpenApiOAuth2Auth\")({\n kind: Schema.Literal(\"oauth2\"),\n /** Id of the Connection that owns this sign-in. Points at the core\n * `connection` table; resolve via `ctx.connections.get(id)` or\n * `ctx.connections.accessToken(id)`. Updated when the user signs in\n * again from the source detail UI (a fresh connection is minted and\n * this pointer is rewritten). */\n connectionId: Schema.String,\n /** Key into `components.securitySchemes` this auth came from. Kept here\n * so a spec with multiple OAuth2 schemes can wire each one to its own\n * connection. */\n securitySchemeName: Schema.String,\n /** OAuth2 grant type used for this source. Determines which flow the\n * sign-in button runs (authorizationCode opens a browser popup;\n * clientCredentials is server-to-server). */\n flow: OAuth2Flow,\n /** Absolute token endpoint URL. */\n tokenUrl: Schema.String,\n /** Absolute authorization endpoint URL. Only used for authorizationCode\n * flows; clientCredentials has no user consent step. */\n authorizationUrl: Schema.NullOr(Schema.String),\n /** Expected issuer for ID token validation. Defaults to authorization origin. */\n issuerUrl: Schema.optional(Schema.NullOr(Schema.String)),\n /** Secret id holding the OAuth client_id. */\n clientIdSecretId: Schema.String,\n /** Secret id holding the OAuth client_secret. Optional for public\n * clients (PKCE-only authorizationCode). */\n clientSecretSecretId: Schema.NullOr(Schema.String),\n /** OAuth scopes requested on sign-in. Stored as a static list so the\n * sign-in button can re-request the same capabilities without having\n * to re-derive them from the OpenAPI spec. */\n scopes: Schema.Array(Schema.String),\n}) {}\n\nexport class OAuth2SourceConfig extends Schema.Class<OAuth2SourceConfig>(\n \"OpenApiOAuth2SourceConfig\",\n)({\n kind: Schema.Literal(\"oauth2\"),\n securitySchemeName: Schema.String,\n flow: OAuth2Flow,\n tokenUrl: Schema.String,\n authorizationUrl: Schema.NullOr(Schema.String),\n issuerUrl: Schema.optional(Schema.NullOr(Schema.String)),\n clientIdSlot: Schema.String,\n clientSecretSlot: Schema.NullOr(Schema.String),\n connectionSlot: Schema.String,\n scopes: Schema.Array(Schema.String),\n}) {}\n\nexport class InvocationConfig extends Schema.Class<InvocationConfig>(\"InvocationConfig\")({\n baseUrl: Schema.String,\n /** Headers applied to every request. Values can reference secrets. */\n headers: Schema.optional(Schema.Record(Schema.String, HeaderValue)),\n /**\n * Optional OAuth2 auth — if set, the invoker resolves/refreshes the\n * access token and injects `Authorization: Bearer <token>` on every\n * request. Coexists with `headers` but wins for the Authorization header.\n */\n oauth2: Schema.OptionFromOptional(OAuth2Auth),\n}) {}\n\nexport class InvocationResult extends Schema.Class<InvocationResult>(\"InvocationResult\")({\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}) {}\n","import { Effect, Option } from \"effect\";\n\nimport { OpenApiExtractionError } from \"./errors\";\nimport type { ParsedDocument } from \"./parse\";\nimport {\n declaredContents,\n DocResolver,\n preferredResponseContent,\n type OperationObject,\n type ParameterObject,\n type PathItemObject,\n type RequestBodyObject,\n type ResponseObject,\n} from \"./openapi-utils\";\nimport {\n EncodingObject,\n ExtractedOperation,\n ExtractionResult,\n type HttpMethod,\n MediaBinding,\n OperationId,\n OperationParameter,\n OperationRequestBody,\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(\n (p) =>\n new OperationParameter({\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] = new EncodingObject({\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(\n ({ mediaType, media }) =>\n new MediaBinding({\n contentType: mediaType,\n schema: Option.fromNullishOr(media.schema),\n encoding: Option.fromNullishOr(\n buildEncodingRecord(\n (media as { encoding?: Record<string, unknown> }).encoding,\n ),\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 new OperationRequestBody({\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 extractOutputSchema = (operation: OperationObject, r: DocResolver): unknown | 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) return content.media.schema;\n }\n\n return undefined;\n};\n\n// ---------------------------------------------------------------------------\n// Input schema builder\n// ---------------------------------------------------------------------------\n\nconst buildInputSchema = (\n parameters: readonly OperationParameter[],\n requestBody: OperationRequestBody | undefined,\n): Record<string, unknown> | undefined => {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\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 if (requestBody) {\n properties.body = Option.getOrElse(requestBody.schema, () => ({ type: \"object\" }));\n if (requestBody.required) required.push(\"body\");\n\n // When the spec declares multiple media types for this requestBody,\n // expose `contentType` so the model can pick. Default = first declared.\n // `body` schema tracks the default; the model is responsible for\n // supplying a body shape that matches whichever contentType it picks.\n const contents = Option.getOrUndefined(requestBody.contents);\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 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\n// ---------------------------------------------------------------------------\n// Server extraction\n// ---------------------------------------------------------------------------\n\nconst extractServers = (doc: ParsedDocument): ServerInfo[] =>\n (doc.servers ?? []).flatMap((server) => {\n if (!server.url) return [];\n const vars = server.variables\n ? Object.fromEntries(\n Object.entries(server.variables).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 new ServerVariable({\n default: String(v.default),\n enum:\n enumValues && enumValues.length > 0\n ? Option.some(enumValues)\n : Option.none(),\n description: Option.fromNullishOr(v.description),\n }),\n ],\n ];\n }),\n )\n : undefined;\n return [\n new ServerInfo({\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\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 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 inputSchema = buildInputSchema(parameters, requestBody);\n const outputSchema = extractOutputSchema(operation, r);\n const tags = (operation.tags ?? []).filter((t) => t.trim().length > 0);\n\n operations.push(\n new ExtractedOperation({\n operationId: OperationId.make(deriveOperationId(method, pathTemplate, operation)),\n method,\n pathTemplate,\n summary: Option.fromNullishOr(operation.summary),\n description: Option.fromNullishOr(operation.description),\n tags,\n parameters,\n requestBody: Option.fromNullishOr(requestBody),\n inputSchema: Option.fromNullishOr(inputSchema),\n outputSchema: Option.fromNullishOr(outputSchema),\n deprecated: operation.deprecated === true,\n }),\n );\n }\n }\n\n return new ExtractionResult({\n title: Option.fromNullishOr(doc.info?.title),\n version: Option.fromNullishOr(doc.info?.version),\n servers: extractServers(doc),\n operations,\n });\n});\n","import { Effect, Layer, Option } from \"effect\";\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\";\n\nimport type { SecretOwnedByConnectionError, StorageFailure } from \"@executor-js/sdk/core\";\n\nimport { OpenApiInvocationError } from \"./errors\";\nimport {\n type EncodingObject,\n type HeaderValue,\n type OperationBinding,\n InvocationResult,\n type MediaBinding,\n type OperationParameter,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Parameter reading\n// ---------------------------------------------------------------------------\n\nconst CONTAINER_KEYS: Record<string, readonly string[]> = {\n path: [\"path\", \"pathParams\", \"params\"],\n query: [\"query\", \"queryParams\", \"params\"],\n header: [\"headers\", \"header\"],\n cookie: [\"cookies\", \"cookie\"],\n};\n\nconst readParamValue = (args: Record<string, unknown>, param: OperationParameter): unknown => {\n const direct = args[param.name];\n if (direct !== undefined) return direct;\n\n for (const key of CONTAINER_KEYS[param.location] ?? []) {\n const container = args[key];\n if (typeof container === \"object\" && container !== null && !Array.isArray(container)) {\n const nested = (container as Record<string, unknown>)[param.name];\n if (nested !== undefined) return nested;\n }\n }\n\n return undefined;\n};\n\n// ---------------------------------------------------------------------------\n// Path resolution\n// ---------------------------------------------------------------------------\n\nconst resolvePath = Effect.fn(\"OpenApi.resolvePath\")(function* (\n pathTemplate: string,\n args: Record<string, unknown>,\n parameters: readonly OperationParameter[],\n) {\n let resolved = pathTemplate;\n\n for (const param of parameters) {\n if (param.location !== \"path\") continue;\n const value = readParamValue(args, param);\n if (value === undefined || value === null) {\n if (param.required) {\n return yield* new OpenApiInvocationError({\n message: `Missing required path parameter: ${param.name}`,\n statusCode: Option.none(),\n });\n }\n continue;\n }\n resolved = resolved.replaceAll(`{${param.name}}`, encodeURIComponent(String(value)));\n }\n\n const remaining = [...resolved.matchAll(/\\{([^{}]+)\\}/g)]\n .map((m) => m[1])\n .filter((v): v is string => typeof v === \"string\");\n\n for (const name of remaining) {\n const value = args[name];\n if (value !== undefined && value !== null) {\n resolved = resolved.replaceAll(`{${name}}`, encodeURIComponent(String(value)));\n }\n }\n\n const unresolved = [...resolved.matchAll(/\\{([^{}]+)\\}/g)]\n .map((m) => m[1])\n .filter((v): v is string => typeof v === \"string\");\n\n if (unresolved.length > 0) {\n return yield* new OpenApiInvocationError({\n message: `Unresolved path parameters: ${[...new Set(unresolved)].join(\", \")}`,\n statusCode: Option.none(),\n });\n }\n\n return resolved;\n});\n\n// ---------------------------------------------------------------------------\n// Header resolution — resolves secret refs at invocation time\n// ---------------------------------------------------------------------------\n\nexport const resolveHeaders = (\n headers: Record<string, HeaderValue>,\n secrets: {\n readonly get: (\n id: string,\n ) => Effect.Effect<string | null, SecretOwnedByConnectionError | StorageFailure>;\n },\n): Effect.Effect<Record<string, string>, OpenApiInvocationError | StorageFailure> => {\n const entries = Object.entries(headers);\n const secretCount = entries.reduce(\n (acc, [, value]) => (typeof value === \"string\" ? acc : acc + 1),\n 0,\n );\n return Effect.gen(function* () {\n // Fan out secret lookups: on every invocation, one or two headers\n // typically each hit the secret store. Resolving them in parallel\n // is a free wall-clock win — preserved order is only needed for\n // the final assembly, not the fetches.\n const values = yield* Effect.all(\n entries.map(([name, value]) =>\n typeof value === \"string\"\n ? Effect.succeed({ name, value })\n : secrets.get(value.secretId).pipe(\n Effect.mapError((err) =>\n \"_tag\" in err && err._tag === \"SecretOwnedByConnectionError\"\n ? new OpenApiInvocationError({\n message: `Failed to resolve secret \"${value.secretId}\" for header \"${name}\"`,\n statusCode: Option.none(),\n })\n : err,\n ),\n Effect.flatMap((secret) =>\n secret === null\n ? Effect.fail(\n new OpenApiInvocationError({\n message: `Failed to resolve secret \"${value.secretId}\" for header \"${name}\"`,\n statusCode: Option.none(),\n }),\n )\n : Effect.succeed({\n name,\n value: value.prefix ? `${value.prefix}${secret}` : secret,\n }),\n ),\n ),\n ),\n { concurrency: \"unbounded\" },\n );\n const resolved: Record<string, string> = {};\n for (const { name, value } of values) resolved[name] = value;\n return resolved;\n }).pipe(\n Effect.withSpan(\"plugin.openapi.secret.resolve\", {\n attributes: {\n \"plugin.openapi.headers.total\": entries.length,\n \"plugin.openapi.headers.secret_count\": secretCount,\n },\n }),\n );\n};\n\nconst applyHeaders = (\n request: HttpClientRequest.HttpClientRequest,\n headers: Record<string, string>,\n): HttpClientRequest.HttpClientRequest => {\n let req = request;\n for (const [name, value] of Object.entries(headers)) {\n req = HttpClientRequest.setHeader(req, name, value);\n }\n return req;\n};\n\n// ---------------------------------------------------------------------------\n// Response helpers\n// ---------------------------------------------------------------------------\n\nconst normalizeContentType = (ct: string | null | undefined): string =>\n ct?.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n\nconst isJsonContentType = (ct: string | null | undefined): boolean => {\n const normalized = normalizeContentType(ct);\n if (!normalized) return false;\n return (\n normalized === \"application/json\" || normalized.includes(\"+json\") || normalized.includes(\"json\")\n );\n};\n\nconst isFormUrlEncoded = (ct: string | null | undefined): boolean =>\n normalizeContentType(ct) === \"application/x-www-form-urlencoded\";\n\nconst isMultipartFormData = (ct: string | null | undefined): boolean =>\n normalizeContentType(ct).startsWith(\"multipart/form-data\");\n\nconst isXmlContentType = (ct: string | null | undefined): boolean => {\n const normalized = normalizeContentType(ct);\n if (!normalized) return false;\n return (\n normalized === \"application/xml\" ||\n normalized === \"text/xml\" ||\n normalized.endsWith(\"+xml\")\n );\n};\n\nconst isTextContentType = (ct: string | null | undefined): boolean =>\n normalizeContentType(ct).startsWith(\"text/\");\n\nconst isOctetStream = (ct: string | null | undefined): boolean =>\n normalizeContentType(ct) === \"application/octet-stream\";\n\nconst toUint8Array = (value: unknown): Uint8Array | null => {\n if (value instanceof Uint8Array) return value;\n if (value instanceof ArrayBuffer) return new Uint8Array(value);\n if (ArrayBuffer.isView(value)) {\n const view = value as ArrayBufferView;\n return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n }\n if (Array.isArray(value) && value.every((v) => typeof v === \"number\")) {\n return new Uint8Array(value as readonly number[]);\n }\n return null;\n};\n\ntype FormDataRecord = Parameters<typeof HttpClientRequest.bodyFormDataRecord>[1];\ntype FormDataCoercible = FormDataRecord[string];\n\n// Pull a plain ArrayBuffer out of a Uint8Array — `new Blob([u8])` rejects\n// views whose `.buffer` is `SharedArrayBuffer | ArrayBuffer` under strict\n// lib.dom typings.\nconst toArrayBuffer = (bytes: Uint8Array): ArrayBuffer => {\n const copy = new ArrayBuffer(bytes.byteLength);\n new Uint8Array(copy).set(bytes);\n return copy;\n};\n\n// ---------------------------------------------------------------------------\n// OpenAPI 3.x encoding — per-property style/explode/allowReserved/contentType\n// for multipart/form-data and application/x-www-form-urlencoded bodies.\n// Spec ref: https://spec.openapis.org/oas/v3.1.0#encoding-object\n// ---------------------------------------------------------------------------\n\ntype StyleExplode = {\n readonly style: string;\n readonly explode: boolean;\n readonly allowReserved: boolean;\n};\n\nconst DEFAULT_FORM_STYLE: StyleExplode = {\n style: \"form\",\n explode: true,\n allowReserved: false,\n};\n\nconst resolveStyleExplode = (e: EncodingObject | undefined): StyleExplode => {\n if (!e) return DEFAULT_FORM_STYLE;\n return {\n style: Option.getOrElse(e.style, () => DEFAULT_FORM_STYLE.style),\n explode: Option.getOrElse(e.explode, () => DEFAULT_FORM_STYLE.explode),\n allowReserved: Option.getOrElse(e.allowReserved, () => DEFAULT_FORM_STYLE.allowReserved),\n };\n};\n\n// RFC 3986 §2.2 reserved chars. `allowReserved: true` leaves these\n// unencoded; default OAS behavior encodes everything non-unreserved.\nconst RESERVED_UNENCODED_RE = /[A-Za-z0-9\\-._~:/?#[\\]@!$&'()*+,;=]/;\n\nconst encodeFormValue = (v: unknown, allowReserved: boolean): string => {\n const raw = typeof v === \"object\" && v !== null ? JSON.stringify(v) : String(v);\n if (!allowReserved) return encodeURIComponent(raw);\n // Walk char-by-char so the reserved set passes through as-is.\n let out = \"\";\n for (const ch of raw) {\n out += RESERVED_UNENCODED_RE.test(ch) ? ch : encodeURIComponent(ch);\n }\n return out;\n};\n\n/**\n * Serialize a record to application/x-www-form-urlencoded with OAS3 style\n * rules honored per-field. Supports `form` (default), `deepObject`,\n * `pipeDelimited`, `spaceDelimited` styles with `explode` true / false.\n */\nconst serializeFormUrlEncoded = (\n value: Record<string, unknown>,\n encoding: Record<string, EncodingObject> | undefined,\n): string => {\n const parts: string[] = [];\n for (const [key, raw] of Object.entries(value)) {\n if (raw === undefined || raw === null) continue;\n const { style, explode, allowReserved } = resolveStyleExplode(encoding?.[key]);\n const encKey = encodeURIComponent(key);\n\n if (Array.isArray(raw)) {\n if (explode) {\n for (const v of raw) {\n parts.push(`${encKey}=${encodeFormValue(v, allowReserved)}`);\n }\n } else {\n const sep =\n style === \"spaceDelimited\" ? \" \" : style === \"pipeDelimited\" ? \"|\" : \",\";\n parts.push(\n `${encKey}=${encodeFormValue(\n raw.map((v) => (typeof v === \"object\" ? JSON.stringify(v) : String(v))).join(sep),\n allowReserved,\n )}`,\n );\n }\n continue;\n }\n\n if (typeof raw === \"object\") {\n const entries = Object.entries(raw as Record<string, unknown>).filter(\n ([, v]) => v !== undefined && v !== null,\n );\n if (style === \"deepObject\") {\n for (const [subkey, subval] of entries) {\n // Encode the whole `key[subkey]` fragment so `[` / `]` become\n // `%5B` / `%5D`. Matches swagger-client's behaviour and remains\n // accepted by common server-side parsers (qs, Rails, etc.).\n parts.push(\n `${encodeURIComponent(`${key}[${subkey}]`)}=${encodeFormValue(\n subval,\n allowReserved,\n )}`,\n );\n }\n } else if (explode) {\n // form + explode=true on object: sub-keys become top-level fields.\n for (const [subkey, subval] of entries) {\n parts.push(\n `${encodeURIComponent(subkey)}=${encodeFormValue(subval, allowReserved)}`,\n );\n }\n } else {\n // form + explode=false on object: flatten to csv key,val,key,val.\n const flat = entries.flatMap(([k, v]) => [\n k,\n typeof v === \"object\" ? JSON.stringify(v) : String(v),\n ]);\n parts.push(`${encKey}=${encodeFormValue(flat.join(\",\"), allowReserved)}`);\n }\n continue;\n }\n\n parts.push(`${encKey}=${encodeFormValue(raw, allowReserved)}`);\n }\n return parts.join(\"&\");\n};\n\n/**\n * Best-effort build of a multipart FormData entry record.\n *\n * If `encoding[key].contentType` is declared (OAS3 §4.8.15), wrap the value\n * in a `Blob` with that type so the runtime multipart framer emits the\n * per-part `Content-Type` header (e.g. `application/json` for a metadata\n * part whose server expects parsed JSON).\n *\n * Otherwise: primitives pass through, arrays handle their item types, byte\n * shapes wrap as Blob, nested objects JSON-stringify (never `[object Object]`).\n */\nconst coerceFormDataRecord = (\n value: Record<string, unknown>,\n encoding: Record<string, EncodingObject> | undefined,\n): FormDataRecord => {\n const out: Record<string, FormDataCoercible> = {};\n for (const [key, raw] of Object.entries(value)) {\n if (raw === undefined || raw === null) continue;\n\n const partType = encoding?.[key]\n ? Option.getOrUndefined(encoding[key]!.contentType)\n : undefined;\n\n // Explicit per-part content type: wrap in a typed Blob so the framer\n // emits `Content-Type: <partType>` on this part. JSON types get the\n // value JSON-stringified first so the blob body is valid JSON.\n if (partType) {\n const isJson =\n partType.startsWith(\"application/json\") || partType.includes(\"+json\");\n const serialized =\n typeof raw === \"string\"\n ? raw\n : isJson\n ? JSON.stringify(raw)\n : typeof raw === \"object\"\n ? JSON.stringify(raw)\n : String(raw);\n out[key] = new Blob([serialized], { type: partType });\n continue;\n }\n\n if (\n typeof raw === \"string\" ||\n typeof raw === \"number\" ||\n typeof raw === \"boolean\" ||\n raw instanceof Blob ||\n (typeof File !== \"undefined\" && raw instanceof File)\n ) {\n out[key] = raw as FormDataCoercible;\n continue;\n }\n if (Array.isArray(raw)) {\n out[key] = raw.map((v) =>\n typeof v === \"string\" ||\n typeof v === \"number\" ||\n typeof v === \"boolean\" ||\n v instanceof Blob ||\n (typeof File !== \"undefined\" && v instanceof File)\n ? (v as FormDataCoercible)\n : JSON.stringify(v),\n ) as FormDataCoercible;\n continue;\n }\n const bytes = toUint8Array(raw);\n if (bytes) {\n out[key] = new Blob([toArrayBuffer(bytes)]);\n continue;\n }\n out[key] = JSON.stringify(raw);\n }\n return out;\n};\n\n// ---------------------------------------------------------------------------\n// Request body dispatch\n//\n// Dispatch is driven by the spec-declared content type first, JS type of\n// the provided body second. Servers that advertise a specific content type\n// almost always reject anything else (e.g. a multipart endpoint will hang\n// waiting for valid framing if it receives `application/json`), so the\n// content type wins.\n//\n// Within each content type we accept both pre-serialized strings (user\n// already produced the wire format) and structured JS values we can\n// serialize ourselves. The last-resort fallback is `JSON.stringify(body)`\n// — never `String(body)` (which produces the useless `[object Object]`).\n// ---------------------------------------------------------------------------\n\nconst applyRequestBody = (\n request: HttpClientRequest.HttpClientRequest,\n contentType: string,\n bodyValue: unknown,\n encoding: Record<string, EncodingObject> | undefined,\n): HttpClientRequest.HttpClientRequest => {\n if (isJsonContentType(contentType)) {\n // Pre-serialized JSON strings pass through with the declared media\n // type preserved (important for `application/vnd.foo+json` etc.).\n if (typeof bodyValue === \"string\") {\n return HttpClientRequest.bodyText(request, bodyValue, contentType);\n }\n return HttpClientRequest.bodyJsonUnsafe(request, bodyValue);\n }\n\n if (isFormUrlEncoded(contentType)) {\n if (typeof bodyValue === \"string\") {\n return HttpClientRequest.bodyText(request, bodyValue, contentType);\n }\n if (typeof bodyValue === \"object\" && bodyValue !== null && !Array.isArray(bodyValue)) {\n // Serialize ourselves so OAS3 encoding (style/explode/deepObject)\n // is honored. bodyUrlParams doesn't know about per-field style.\n const serialized = serializeFormUrlEncoded(\n bodyValue as Record<string, unknown>,\n encoding,\n );\n return HttpClientRequest.bodyText(request, serialized, contentType);\n }\n // Non-object body — fall back to platform helper (handles URLSearchParams).\n return HttpClientRequest.bodyUrlParams(\n request,\n bodyValue as Parameters<typeof HttpClientRequest.bodyUrlParams>[1],\n );\n }\n\n if (isMultipartFormData(contentType)) {\n if (bodyValue instanceof FormData) {\n return HttpClientRequest.bodyFormData(request, bodyValue);\n }\n if (typeof bodyValue === \"object\" && bodyValue !== null) {\n return HttpClientRequest.bodyFormDataRecord(\n request,\n coerceFormDataRecord(bodyValue as Record<string, unknown>, encoding),\n );\n }\n // String / primitive under multipart is almost certainly wrong on the\n // caller's end — send it as text with their declared content type and\n // let the server produce a useful error.\n return HttpClientRequest.bodyText(request, String(bodyValue), contentType);\n }\n\n if (isOctetStream(contentType)) {\n const bytes = toUint8Array(bodyValue);\n if (bytes) return HttpClientRequest.bodyUint8Array(request, bytes, contentType);\n if (typeof bodyValue === \"string\") {\n return HttpClientRequest.bodyText(request, bodyValue, contentType);\n }\n // Unknown shape — serialize as JSON so at least the payload is visible.\n return HttpClientRequest.bodyText(request, JSON.stringify(bodyValue), contentType);\n }\n\n if (isXmlContentType(contentType) || isTextContentType(contentType)) {\n if (typeof bodyValue === \"string\") {\n return HttpClientRequest.bodyText(request, bodyValue, contentType);\n }\n const bytes = toUint8Array(bodyValue);\n if (bytes) return HttpClientRequest.bodyUint8Array(request, bytes, contentType);\n // Object body under text/xml is unusual — stringify so the caller sees\n // their own payload instead of `[object Object]`.\n return HttpClientRequest.bodyText(request, JSON.stringify(bodyValue), contentType);\n }\n\n // Unknown content type: respect what the caller supplied.\n if (typeof bodyValue === \"string\") {\n return HttpClientRequest.bodyText(request, bodyValue, contentType);\n }\n const bytes = toUint8Array(bodyValue);\n if (bytes) return HttpClientRequest.bodyUint8Array(request, bytes, contentType);\n return HttpClientRequest.bodyText(request, JSON.stringify(bodyValue), contentType);\n};\n\n// ---------------------------------------------------------------------------\n// Public API — invoke a single operation\n// ---------------------------------------------------------------------------\n\nexport const invoke = Effect.fn(\"OpenApi.invoke\")(function* (\n operation: OperationBinding,\n args: Record<string, unknown>,\n resolvedHeaders: Record<string, string>,\n sourceQueryParams: Record<string, string> = {},\n) {\n const client = yield* HttpClient.HttpClient;\n\n yield* Effect.annotateCurrentSpan({\n \"http.method\": operation.method.toUpperCase(),\n \"http.route\": operation.pathTemplate,\n \"plugin.openapi.method\": operation.method.toUpperCase(),\n \"plugin.openapi.path_template\": operation.pathTemplate,\n \"plugin.openapi.headers.resolved_count\": Object.keys(resolvedHeaders).length,\n });\n\n const resolvedPath = yield* resolvePath(operation.pathTemplate, args, operation.parameters);\n\n const path = resolvedPath.startsWith(\"/\") ? resolvedPath : `/${resolvedPath}`;\n\n let request = HttpClientRequest.make(operation.method.toUpperCase() as \"GET\")(path);\n\n for (const [name, value] of Object.entries(sourceQueryParams)) {\n request = HttpClientRequest.setUrlParam(request, name, value);\n }\n\n for (const param of operation.parameters) {\n if (param.location !== \"query\") continue;\n const value = readParamValue(args, param);\n if (value === undefined || value === null) continue;\n request = HttpClientRequest.setUrlParam(request, param.name, String(value));\n }\n\n for (const param of operation.parameters) {\n if (param.location !== \"header\") continue;\n const value = readParamValue(args, param);\n if (value === undefined || value === null) continue;\n request = HttpClientRequest.setHeader(request, param.name, String(value));\n }\n\n if (Option.isSome(operation.requestBody)) {\n const rb = operation.requestBody.value;\n const bodyValue = args.body ?? args.input;\n if (bodyValue !== undefined) {\n // Resolve which declared media type to use. When the spec declares\n // multiple, the caller can override via `args.contentType`; otherwise\n // we use the first-declared (spec author's preferred ordering).\n const contentsOpt = Option.getOrUndefined(rb.contents);\n const requestedCt =\n typeof args.contentType === \"string\" ? args.contentType : undefined;\n const selected: MediaBinding | undefined =\n contentsOpt && requestedCt\n ? contentsOpt.find((c) => c.contentType === requestedCt)\n : undefined;\n const chosenCt = selected?.contentType ?? rb.contentType;\n const chosenEncoding = selected\n ? Option.getOrUndefined(selected.encoding)\n : contentsOpt && contentsOpt[0]\n ? Option.getOrUndefined(contentsOpt[0].encoding)\n : undefined;\n request = applyRequestBody(request, chosenCt, bodyValue, chosenEncoding);\n }\n }\n\n request = applyHeaders(request, resolvedHeaders);\n\n const response = yield* client.execute(request).pipe(\n Effect.mapError(\n (err) =>\n new OpenApiInvocationError({\n message: `HTTP request failed: ${err.message}`,\n statusCode: Option.none(),\n cause: err,\n }),\n ),\n );\n\n const status = response.status;\n yield* Effect.annotateCurrentSpan({\n \"http.status_code\": status,\n });\n const responseHeaders: Record<string, string> = { ...response.headers };\n\n const contentType = response.headers[\"content-type\"] ?? null;\n const mapBodyError = Effect.mapError(\n (err: { readonly message?: string }) =>\n new OpenApiInvocationError({\n message: `Failed to read response body: ${err.message ?? String(err)}`,\n statusCode: Option.some(status),\n cause: err,\n }),\n );\n const responseBody: unknown =\n status === 204\n ? null\n : isJsonContentType(contentType)\n ? yield* response.json.pipe(\n Effect.catch(() => response.text),\n mapBodyError,\n )\n : yield* response.text.pipe(mapBodyError);\n\n const ok = status >= 200 && status < 300;\n\n return new InvocationResult({\n status,\n headers: responseHeaders,\n data: ok ? responseBody : null,\n error: ok ? null : responseBody,\n });\n});\n\n// ---------------------------------------------------------------------------\n// Invoke with a provided HttpClient layer + optional baseUrl prefix\n// ---------------------------------------------------------------------------\n\nexport const invokeWithLayer = (\n operation: OperationBinding,\n args: Record<string, unknown>,\n baseUrl: string,\n resolvedHeaders: Record<string, string>,\n sourceQueryParams: Record<string, string>,\n httpClientLayer: Layer.Layer<HttpClient.HttpClient, never, never>,\n) => {\n const clientWithBaseUrl = baseUrl\n ? Layer.effect(\n HttpClient.HttpClient,\n Effect.map(\n Effect.service(HttpClient.HttpClient),\n HttpClient.mapRequest(HttpClientRequest.prependUrl(baseUrl)),\n ),\n ).pipe(Layer.provide(httpClientLayer))\n : httpClientLayer;\n\n return invoke(operation, args, resolvedHeaders, sourceQueryParams).pipe(\n Effect.provide(clientWithBaseUrl),\n Effect.withSpan(\"plugin.openapi.invoke\", {\n attributes: {\n \"plugin.openapi.method\": operation.method.toUpperCase(),\n \"plugin.openapi.path_template\": operation.pathTemplate,\n \"plugin.openapi.base_url\": baseUrl,\n },\n }),\n );\n};\n\n// ---------------------------------------------------------------------------\n// Derive annotations from HTTP method\n// ---------------------------------------------------------------------------\n\nconst REQUIRE_APPROVAL = new Set([\"post\", \"put\", \"patch\", \"delete\"]);\n\nexport const annotationsForOperation = (\n method: string,\n pathTemplate: string,\n): { requiresApproval?: boolean; approvalDescription?: string } => {\n const m = method.toLowerCase();\n if (!REQUIRE_APPROVAL.has(m)) return {};\n return {\n requiresApproval: true,\n approvalDescription: `${method.toUpperCase()} ${pathTemplate}`,\n };\n};\n","import { Effect, Option } 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);\n\nexport class OAuth2AuthorizationCodeFlow extends Schema.Class<OAuth2AuthorizationCodeFlow>(\n \"OAuth2AuthorizationCodeFlow\",\n)({\n authorizationUrl: Schema.String,\n tokenUrl: Schema.String,\n refreshUrl: Schema.OptionFromOptional(Schema.String),\n scopes: OAuth2Scopes,\n}) {}\n\nexport class OAuth2ClientCredentialsFlow extends Schema.Class<OAuth2ClientCredentialsFlow>(\n \"OAuth2ClientCredentialsFlow\",\n)({\n tokenUrl: Schema.String,\n refreshUrl: Schema.OptionFromOptional(Schema.String),\n scopes: OAuth2Scopes,\n}) {}\n\nexport class OAuth2Flows extends Schema.Class<OAuth2Flows>(\"OAuth2Flows\")({\n authorizationCode: Schema.OptionFromOptional(OAuth2AuthorizationCodeFlow),\n clientCredentials: Schema.OptionFromOptional(OAuth2ClientCredentialsFlow),\n}) {}\n\n// ---------------------------------------------------------------------------\n// Security scheme — what the spec declares it needs\n// ---------------------------------------------------------------------------\n\nexport class SecurityScheme extends Schema.Class<SecurityScheme>(\"SecurityScheme\")({\n /** Key name in components.securitySchemes (e.g. \"api_token\") */\n name: Schema.String,\n /** OpenAPI security scheme type */\n type: Schema.Literals([\"http\", \"apiKey\", \"oauth2\", \"openIdConnect\"]),\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}) {}\n\n// ---------------------------------------------------------------------------\n// Auth strategy — a valid combination of security schemes\n// ---------------------------------------------------------------------------\n\nexport class AuthStrategy extends Schema.Class<AuthStrategy>(\"AuthStrategy\")({\n /** The security schemes required together for this strategy */\n schemes: Schema.Array(Schema.String),\n}) {}\n\n// ---------------------------------------------------------------------------\n// Header preset — derived from an auth strategy\n// ---------------------------------------------------------------------------\n\nexport class HeaderPreset extends Schema.Class<HeaderPreset>(\"HeaderPreset\")({\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}) {}\n\n// ---------------------------------------------------------------------------\n// OAuth2 preset — derived from an oauth2 security scheme + a flow choice\n// ---------------------------------------------------------------------------\n\nexport class OAuth2Preset extends Schema.Class<OAuth2Preset>(\"OAuth2Preset\")({\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}) {}\n\n// ---------------------------------------------------------------------------\n// Preview operation — lightweight shape for the add-source UI list\n// ---------------------------------------------------------------------------\n\nexport class PreviewOperation extends Schema.Class<PreviewOperation>(\"PreviewOperation\")({\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}) {}\n\n// ---------------------------------------------------------------------------\n// Spec preview — everything the frontend needs\n// ---------------------------------------------------------------------------\n\nexport class SpecPreview extends Schema.Class<SpecPreview>(\"SpecPreview\")({\n title: 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}) {}\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\">(\n key: K,\n ): unknown => 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 new OAuth2AuthorizationCodeFlow({\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 new OAuth2ClientCredentialsFlow({\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(new OAuth2Flows({ 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 = scheme.type as string;\n if (![\"http\", \"apiKey\", \"oauth2\", \"openIdConnect\"].includes(type)) return [];\n\n return [\n new SecurityScheme({\n name,\n type: type as \"http\" | \"apiKey\" | \"oauth2\" | \"openIdConnect\",\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: type === \"oauth2\" ? extractFlows(scheme.flows) : Option.none(),\n openIdConnectUrl: Option.fromNullishOr(\n scheme.openIdConnectUrl as string | undefined,\n ),\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((s): s is SecurityScheme => s !== undefined);\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 {\n labelParts.push(scheme.name);\n }\n }\n\n if (Object.keys(headers).length === 0 && resolved.length > 0) {\n return [new HeaderPreset({ label: labelParts.join(\" + \"), headers: {}, secretHeaders: [] })];\n }\n\n return [new HeaderPreset({ label: labelParts.join(\" + \"), headers, secretHeaders })];\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 new OAuth2Preset({\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 }),\n );\n }\n\n if (Option.isSome(flows.clientCredentials)) {\n const flow = flows.clientCredentials.value;\n presets.push(\n new OAuth2Preset({\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 }),\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 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 const doc: ParsedDocument = yield* parse(specText);\n const result = yield* extract(doc);\n\n const resolver = new DocResolver(doc);\n const securitySchemes = extractSecuritySchemes(\n doc.components?.securitySchemes ?? {},\n resolver,\n );\n\n const rawSecurity = (doc.security ?? []) as Array<Record<string, unknown>>;\n const declaredStrategies = rawSecurity.map(\n (entry) => new AuthStrategy({ 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) => new AuthStrategy({ schemes: [scheme.name] }));\n\n return new SpecPreview({\n title: result.title,\n version: result.version,\n servers: result.servers,\n operationCount: result.operations.length,\n operations: result.operations.map(\n (op) =>\n new PreviewOperation({\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","import { Effect, Schema } from \"effect\";\n\nimport {\n defineSchema,\n ScopeId,\n StorageError,\n type StorageDeps,\n type StorageFailure,\n} from \"@executor-js/sdk/core\";\n\nimport {\n ConfiguredHeaderValue,\n ConfiguredHeaderBinding,\n HeaderValue,\n OAuth2Auth,\n OAuth2SourceConfig,\n OpenApiSourceBindingInput,\n OpenApiSourceBindingRef,\n OpenApiSourceBindingValue,\n OperationBinding,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Schema — three tables:\n// - openapi_source: one row per onboarded spec (baseUrl, headers, oauth2, ...)\n// - openapi_operation: one row per operation binding keyed by tool id\n// - openapi_source_binding: credential bindings for shared sources\n// ---------------------------------------------------------------------------\n\nexport const openapiSchema = defineSchema({\n openapi_source: {\n fields: {\n id: { type: \"string\", required: true },\n scope_id: { type: \"string\", required: true, index: true },\n name: { type: \"string\", required: true },\n spec: { type: \"string\", required: true },\n // Origin URL the spec was fetched from. Set when `addSpec` was\n // invoked with an http(s) URL; null when the caller passed raw\n // spec text. Drives `canRefresh` on the core source row and\n // is the address re-fetched on `refreshSource`.\n source_url: { type: \"string\", required: false },\n base_url: { type: \"string\", required: false },\n headers: { type: \"json\", required: false },\n query_params: { type: \"json\", required: false },\n oauth2: { type: \"json\", required: false },\n invocation_config: { type: \"json\", required: true },\n },\n },\n openapi_operation: {\n fields: {\n id: { type: \"string\", required: true },\n scope_id: { type: \"string\", required: true, index: true },\n source_id: { type: \"string\", required: true, index: true },\n binding: { type: \"json\", required: true },\n },\n },\n openapi_source_binding: {\n fields: {\n id: { type: \"string\", required: true },\n source_id: { type: \"string\", required: true, index: true },\n source_scope_id: { type: \"string\", required: true, index: true },\n // Intentionally NOT named `scope_id`: this row is visible across\n // scope stacks and is filtered manually by source/target scope.\n // The target scope is credential ownership data, not adapter row\n // ownership. Source owners must be able to delete all descendant\n // bindings when a shared source is removed.\n target_scope_id: { type: \"string\", required: true, index: true },\n slot: { type: \"string\", required: true, index: true },\n value: { type: \"json\", required: true },\n created_at: { type: \"date\", required: true },\n updated_at: { type: \"date\", required: true },\n },\n },\n});\n\nexport type OpenapiSchema = typeof openapiSchema;\n\n// ---------------------------------------------------------------------------\n// In-memory shapes\n// ---------------------------------------------------------------------------\n\nexport interface SourceConfig {\n readonly spec: string;\n /** Origin URL when the spec was fetched from http(s). Absent for\n * raw-text adds. Persisted so `refreshSource` can re-fetch. */\n readonly sourceUrl?: string;\n readonly baseUrl?: string;\n readonly namespace?: string;\n readonly headers?: Record<string, ConfiguredHeaderValue>;\n readonly queryParams?: Record<string, HeaderValue>;\n readonly specFetchCredentials?: OpenApiSpecFetchCredentials;\n readonly oauth2?: OAuth2SourceConfig;\n}\n\nexport interface OpenApiSpecFetchCredentials {\n readonly headers?: Record<string, HeaderValue>;\n readonly queryParams?: Record<string, HeaderValue>;\n}\n\nexport interface StoredSource {\n readonly namespace: string;\n /** Executor scope id this source row lives in. Writes stamp this on\n * `scope_id`; reads return whichever scope's row the adapter's\n * fall-through filter sees first. */\n readonly scope: string;\n readonly name: string;\n readonly config: SourceConfig;\n readonly legacy?: {\n readonly headers?: Record<string, HeaderValue>;\n readonly oauth2?: OAuth2Auth;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Schema-class mirror of StoredSource for the API layer, where we need\n// an encodable/decodable shape for HTTP responses.\n// ---------------------------------------------------------------------------\n\nexport class StoredSourceSchema extends Schema.Class<StoredSourceSchema>(\n \"OpenApiStoredSource\",\n)({\n namespace: Schema.String,\n name: Schema.String,\n config: Schema.Struct({\n spec: Schema.String,\n sourceUrl: Schema.optional(Schema.String),\n baseUrl: Schema.optional(Schema.String),\n namespace: Schema.optional(Schema.String),\n headers: Schema.optional(\n Schema.Record(Schema.String, ConfiguredHeaderValue),\n ),\n queryParams: Schema.optional(\n Schema.Record(Schema.String, HeaderValue),\n ),\n specFetchCredentials: Schema.optional(\n Schema.Struct({\n headers: Schema.optional(\n Schema.Record(Schema.String, HeaderValue),\n ),\n queryParams: Schema.optional(\n Schema.Record(Schema.String, HeaderValue),\n ),\n }),\n ),\n // Canonical source-owned OAuth config. Concrete client credentials\n // and connection ids live in OpenAPI-owned scoped binding rows.\n oauth2: Schema.optional(OAuth2SourceConfig),\n }),\n}) {}\n\nexport type StoredSourceSchemaType = typeof StoredSourceSchema.Type;\n\nexport interface StoredOperation {\n readonly toolId: string;\n readonly sourceId: string;\n readonly binding: OperationBinding;\n}\n\n// ---------------------------------------------------------------------------\n// Schema encode/decode — OperationBinding has Option fields, so we must use\n// Schema.encode/decode rather than plain JSON to round-trip correctly.\n// ---------------------------------------------------------------------------\n\nconst encodeBinding = Schema.encodeSync(OperationBinding);\nconst decodeBinding = Schema.decodeUnknownSync(OperationBinding);\n\nconst decodeOAuth2 = Schema.decodeUnknownSync(OAuth2Auth);\nconst encodeOAuth2SourceConfig = Schema.encodeSync(OAuth2SourceConfig);\nconst encodeSourceBindingValue = Schema.encodeSync(OpenApiSourceBindingValue);\nconst decodeSourceBindingValue = Schema.decodeUnknownSync(\n OpenApiSourceBindingValue,\n);\n\nconst asJsonObject = (value: unknown): Record<string, unknown> => {\n if (value == null) return {};\n if (typeof value === \"string\")\n return JSON.parse(value) as Record<string, unknown>;\n return value as Record<string, unknown>;\n};\n\nconst toJsonRecord = (value: unknown): Record<string, unknown> =>\n value as Record<string, unknown>;\n\nconst toConfiguredHeaderBinding = (value: {\n readonly slot?: unknown;\n readonly prefix?: unknown;\n}): ConfiguredHeaderBinding =>\n new ConfiguredHeaderBinding({\n kind: \"binding\",\n slot: String(value.slot ?? \"\"),\n ...(typeof value.prefix === \"string\" ? { prefix: value.prefix } : {}),\n });\n\nconst decodeHeaders = (value: unknown): Record<string, HeaderValue> => {\n if (value == null) return {};\n if (typeof value === \"string\")\n return JSON.parse(value) as Record<string, HeaderValue>;\n return value as Record<string, HeaderValue>;\n};\n\nconst slugifySlotPart = (value: string): string =>\n value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"default\";\n\nexport const headerBindingSlot = (headerName: string): string =>\n `header:${slugifySlotPart(headerName)}`;\n\nexport const oauth2ClientIdSlot = (securitySchemeName: string): string =>\n `oauth2:${slugifySlotPart(securitySchemeName)}:client-id`;\n\nexport const oauth2ClientSecretSlot = (securitySchemeName: string): string =>\n `oauth2:${slugifySlotPart(securitySchemeName)}:client-secret`;\n\nexport const oauth2ConnectionSlot = (securitySchemeName: string): string =>\n `oauth2:${slugifySlotPart(securitySchemeName)}:connection`;\n\nconst normalizeStoredHeaders = (\n value: unknown,\n): {\n readonly headers: Record<string, ConfiguredHeaderValue>;\n readonly legacy: Record<string, HeaderValue>;\n} => {\n const raw = decodeHeaders(value);\n const headers: Record<string, ConfiguredHeaderValue> = {};\n const legacy: Record<string, HeaderValue> = {};\n for (const [name, header] of Object.entries(raw)) {\n if (typeof header === \"string\") {\n headers[name] = header;\n legacy[name] = header;\n continue;\n }\n if (\n header &&\n typeof header === \"object\" &&\n \"kind\" in header &&\n (header as { kind?: unknown }).kind === \"binding\"\n ) {\n headers[name] = toConfiguredHeaderBinding(header);\n continue;\n }\n legacy[name] = header;\n headers[name] = new ConfiguredHeaderBinding({\n kind: \"binding\",\n slot: headerBindingSlot(name),\n prefix: header.prefix,\n });\n }\n return { headers, legacy };\n};\n\nconst normalizeStoredOAuth2 = (\n value: unknown,\n): {\n readonly oauth2?: OAuth2SourceConfig;\n readonly legacy?: OAuth2Auth;\n} => {\n if (value == null) return {};\n const parsed = typeof value === \"string\" ? JSON.parse(value) : value;\n if (parsed && typeof parsed === \"object\" && \"connectionSlot\" in parsed) {\n return {\n oauth2: Schema.decodeUnknownSync(OAuth2SourceConfig)(parsed),\n };\n }\n const legacy = decodeOAuth2(parsed);\n return {\n legacy,\n oauth2: new OAuth2SourceConfig({\n kind: \"oauth2\",\n securitySchemeName: legacy.securitySchemeName,\n flow: legacy.flow,\n tokenUrl: legacy.tokenUrl,\n authorizationUrl: legacy.authorizationUrl,\n clientIdSlot: oauth2ClientIdSlot(legacy.securitySchemeName),\n clientSecretSlot: legacy.clientSecretSecretId\n ? oauth2ClientSecretSlot(legacy.securitySchemeName)\n : null,\n connectionSlot: oauth2ConnectionSlot(legacy.securitySchemeName),\n scopes: [...legacy.scopes],\n }),\n };\n};\n\n// ---------------------------------------------------------------------------\n// Store interface\n// ---------------------------------------------------------------------------\n\n// Every method routes through the typed adapter (`ctx.storage.adapter`)\n// so the typed error channel is `StorageFailure`. Schema-decode failures\n// inside `Effect.gen` land as defects, not typed errors, and are caught\n// by the HTTP edge's observability middleware.\n//\n// Every read/write that targets a single row pins BOTH the natural id\n// (namespace, toolId, sessionId) AND the owning `scope_id`. The store\n// runs behind the scoped adapter (which auto-injects `scope_id IN\n// (stack)`), so a bare `{id}` filter resolves to any matching row in\n// the stack in adapter-iteration order. For shadowed rows (same id at\n// multiple scopes — e.g. an org-level openapi source with a per-user\n// override), that's a scope-isolation bug: updates and deletes can\n// land on the wrong scope's row. Callers thread the resolved scope in\n// (typically `path.scopeId` for HTTP, `toolRow.scope_id` /\n// `input.scope` for invokeTool/lifecycle) so every keyed mutation\n// targets exactly one row.\nexport interface OpenapiStore {\n readonly upsertSource: (\n input: StoredSource,\n operations: readonly StoredOperation[],\n ) => Effect.Effect<void, StorageFailure>;\n\n readonly updateSourceMeta: (\n namespace: string,\n scope: string,\n patch: {\n readonly name?: string;\n readonly baseUrl?: string;\n readonly headers?: Record<string, ConfiguredHeaderValue>;\n readonly queryParams?: Record<string, HeaderValue>;\n readonly oauth2?: OAuth2SourceConfig;\n },\n ) => Effect.Effect<void, StorageFailure>;\n\n readonly getSource: (\n namespace: string,\n scope: string,\n ) => Effect.Effect<StoredSource | null, StorageFailure>;\n\n readonly listSources: () => Effect.Effect<\n readonly StoredSource[],\n StorageFailure\n >;\n\n readonly getOperationByToolId: (\n toolId: string,\n scope: string,\n ) => Effect.Effect<StoredOperation | null, StorageFailure>;\n\n readonly listOperationsBySource: (\n sourceId: string,\n scope: string,\n ) => Effect.Effect<readonly StoredOperation[], StorageFailure>;\n\n readonly removeSource: (\n namespace: string,\n scope: string,\n ) => Effect.Effect<void, StorageFailure>;\n\n readonly listSourceBindings: (\n sourceId: string,\n sourceScope: string,\n ) => Effect.Effect<readonly OpenApiSourceBindingRef[], StorageFailure>;\n\n readonly resolveSourceBinding: (\n sourceId: string,\n sourceScope: string,\n slot: string,\n ) => Effect.Effect<OpenApiSourceBindingRef | null, StorageFailure>;\n\n readonly setSourceBinding: (\n input: OpenApiSourceBindingInput,\n ) => Effect.Effect<OpenApiSourceBindingRef, StorageFailure>;\n\n readonly removeSourceBinding: (\n sourceId: string,\n sourceScope: string,\n slot: string,\n scope: string,\n ) => Effect.Effect<void, StorageFailure>;\n}\n\n// ---------------------------------------------------------------------------\n// Default store implementation\n// ---------------------------------------------------------------------------\n\nexport const makeDefaultOpenapiStore = ({\n adapter,\n scopes,\n}: StorageDeps<OpenapiSchema>): OpenapiStore => {\n const scopeIds = scopes.map((scope) => scope.id as string);\n const scopePrecedence = new Map<string, number>();\n scopeIds.forEach((scope, index) => scopePrecedence.set(scope, index));\n const scopeRank = (scopeId: string): number =>\n scopePrecedence.get(scopeId) ?? Infinity;\n\n const encodeSyntheticRowIdPart = (value: string): string =>\n encodeURIComponent(value);\n\n const sourceBindingRowId = (\n sourceId: string,\n sourceScopeId: string,\n slot: string,\n scopeId: string,\n ) =>\n [\n \"openapi-source-binding\",\n encodeSyntheticRowIdPart(sourceScopeId),\n encodeSyntheticRowIdPart(sourceId),\n encodeSyntheticRowIdPart(slot),\n encodeSyntheticRowIdPart(scopeId),\n ].join(\"::\");\n\n const rowToSourceBinding = (\n row: Record<string, unknown>,\n ): OpenApiSourceBindingRef =>\n new OpenApiSourceBindingRef({\n sourceId: row.source_id as string,\n sourceScopeId: ScopeId.make(row.source_scope_id as string),\n scopeId: ScopeId.make(row.target_scope_id as string),\n slot: row.slot as string,\n value: decodeSourceBindingValue(asJsonObject(row.value)),\n createdAt:\n row.created_at instanceof Date\n ? row.created_at\n : new Date(row.created_at as string),\n updatedAt:\n row.updated_at instanceof Date\n ? row.updated_at\n : new Date(row.updated_at as string),\n });\n\n const validateBindingTarget = (params: {\n readonly sourceId: string;\n readonly sourceScope: string;\n readonly targetScope: string;\n }) =>\n Effect.gen(function* () {\n if (!scopeIds.includes(params.sourceScope)) {\n return yield* Effect.fail(\n new StorageError({\n message:\n `OpenAPI source binding references source scope \"${params.sourceScope}\" ` +\n `which is not in the executor's scope stack [${scopeIds.join(\", \")}].`,\n cause: undefined,\n }),\n );\n }\n if (!scopeIds.includes(params.targetScope)) {\n return yield* Effect.fail(\n new StorageError({\n message:\n `OpenAPI source binding targets scope \"${params.targetScope}\" which is not ` +\n `in the executor's scope stack [${scopeIds.join(\", \")}].`,\n cause: undefined,\n }),\n );\n }\n const source = yield* adapter.findOne({\n model: \"openapi_source\",\n where: [\n { field: \"id\", value: params.sourceId },\n { field: \"scope_id\", value: params.sourceScope },\n ],\n });\n if (!source) {\n return yield* Effect.fail(\n new StorageError({\n message: `OpenAPI source \"${params.sourceId}\" does not exist at scope \"${params.sourceScope}\"`,\n cause: undefined,\n }),\n );\n }\n if (scopeRank(params.targetScope) > scopeRank(params.sourceScope)) {\n return yield* Effect.fail(\n new StorageError({\n message:\n `OpenAPI source bindings for \"${params.sourceId}\" cannot be written at ` +\n `outer scope \"${params.targetScope}\" because the base source lives at ` +\n `\"${params.sourceScope}\"`,\n cause: undefined,\n }),\n );\n }\n return source;\n });\n\n const rowToSource = (row: Record<string, unknown>): StoredSource => {\n const normalizedHeaders = normalizeStoredHeaders(row.headers);\n const normalizedOAuth2 = normalizeStoredOAuth2(row.oauth2);\n const invocationConfig = asJsonObject(row.invocation_config);\n return {\n namespace: row.id as string,\n scope: row.scope_id as string,\n name: row.name as string,\n config: {\n spec: row.spec as string,\n sourceUrl: (row.source_url as string | null | undefined) ?? undefined,\n baseUrl: (row.base_url as string | null | undefined) ?? undefined,\n headers: normalizedHeaders.headers,\n queryParams: decodeHeaders(row.query_params),\n specFetchCredentials: invocationConfig.specFetchCredentials as\n | OpenApiSpecFetchCredentials\n | undefined,\n oauth2: normalizedOAuth2.oauth2,\n },\n legacy:\n Object.keys(normalizedHeaders.legacy).length > 0 ||\n normalizedOAuth2.legacy\n ? {\n ...(Object.keys(normalizedHeaders.legacy).length > 0\n ? { headers: normalizedHeaders.legacy }\n : {}),\n ...(normalizedOAuth2.legacy\n ? { oauth2: normalizedOAuth2.legacy }\n : {}),\n }\n : undefined,\n };\n };\n\n const rowToOperation = (row: Record<string, unknown>): StoredOperation => ({\n toolId: row.id as string,\n sourceId: row.source_id as string,\n binding: decodeBinding(\n typeof row.binding === \"string\" ? JSON.parse(row.binding) : row.binding,\n ),\n });\n\n const deleteSource = (\n namespace: string,\n scope: string,\n options?: { readonly includeBindings?: boolean },\n ) =>\n Effect.gen(function* () {\n yield* adapter.deleteMany({\n model: \"openapi_operation\",\n where: [\n { field: \"source_id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n yield* adapter.delete({\n model: \"openapi_source\",\n where: [\n { field: \"id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n if (options?.includeBindings) {\n yield* adapter.deleteMany({\n model: \"openapi_source_binding\",\n where: [\n { field: \"source_id\", value: namespace },\n { field: \"source_scope_id\", value: scope },\n ],\n });\n }\n });\n\n return {\n upsertSource: (input, operations) =>\n Effect.gen(function* () {\n yield* deleteSource(input.namespace, input.scope);\n yield* adapter.create({\n model: \"openapi_source\",\n data: {\n id: input.namespace,\n scope_id: input.scope,\n name: input.name,\n spec: input.config.spec,\n source_url: input.config.sourceUrl ?? undefined,\n base_url: input.config.baseUrl ?? undefined,\n headers: Object.fromEntries(\n Object.entries(input.config.headers ?? {}).map(\n ([name, value]) => [\n name,\n typeof value === \"string\"\n ? value\n : value.kind === \"binding\"\n ? {\n kind: value.kind,\n slot: value.slot,\n ...(value.prefix ? { prefix: value.prefix } : {}),\n }\n : value,\n ],\n ),\n ) as Record<string, unknown>,\n query_params: input.config.queryParams,\n oauth2: input.config.oauth2\n ? toJsonRecord(encodeOAuth2SourceConfig(input.config.oauth2))\n : undefined,\n invocation_config: {\n ...(input.config.specFetchCredentials\n ? { specFetchCredentials: input.config.specFetchCredentials }\n : {}),\n },\n },\n forceAllowId: true,\n });\n if (operations.length > 0) {\n yield* adapter.createMany({\n model: \"openapi_operation\",\n data: operations.map((op) => ({\n id: op.toolId,\n scope_id: input.scope,\n source_id: op.sourceId,\n binding: toJsonRecord(encodeBinding(op.binding)),\n })),\n forceAllowId: true,\n });\n }\n }),\n\n updateSourceMeta: (namespace, scope, patch) =>\n Effect.gen(function* () {\n const existingRow = yield* adapter.findOne({\n model: \"openapi_source\",\n where: [\n { field: \"id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n if (!existingRow) return;\n const existing = rowToSource(existingRow);\n\n const nextName = patch.name?.trim() || existing.name;\n const nextBaseUrl =\n patch.baseUrl !== undefined ? patch.baseUrl : existing.config.baseUrl;\n const nextHeaders =\n patch.headers !== undefined\n ? patch.headers\n : (existing.config.headers ?? {});\n const nextQueryParams =\n patch.queryParams !== undefined\n ? patch.queryParams\n : (existing.config.queryParams ?? {});\n const nextOAuth2 =\n patch.oauth2 !== undefined ? patch.oauth2 : existing.config.oauth2;\n\n yield* adapter.update({\n model: \"openapi_source\",\n where: [\n { field: \"id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n update: {\n name: nextName,\n base_url: nextBaseUrl ?? undefined,\n headers: Object.fromEntries(\n Object.entries(nextHeaders).map(([name, value]) => [\n name,\n typeof value === \"string\"\n ? value\n : {\n kind: value.kind,\n slot: value.slot,\n ...(value.prefix ? { prefix: value.prefix } : {}),\n },\n ]),\n ) as Record<string, unknown>,\n query_params: nextQueryParams,\n oauth2: nextOAuth2\n ? toJsonRecord(encodeOAuth2SourceConfig(nextOAuth2))\n : undefined,\n invocation_config: asJsonObject(existingRow.invocation_config),\n },\n });\n }),\n\n getSource: (namespace, scope) =>\n adapter\n .findOne({\n model: \"openapi_source\",\n where: [\n { field: \"id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n })\n .pipe(Effect.map((row) => (row ? rowToSource(row) : null))),\n\n listSources: () =>\n adapter\n .findMany({ model: \"openapi_source\" })\n .pipe(Effect.map((rows) => rows.map(rowToSource))),\n\n getOperationByToolId: (toolId, scope) =>\n adapter\n .findOne({\n model: \"openapi_operation\",\n where: [\n { field: \"id\", value: toolId },\n { field: \"scope_id\", value: scope },\n ],\n })\n .pipe(Effect.map((row) => (row ? rowToOperation(row) : null))),\n\n listOperationsBySource: (sourceId, scope) =>\n adapter\n .findMany({\n model: \"openapi_operation\",\n where: [\n { field: \"source_id\", value: sourceId },\n { field: \"scope_id\", value: scope },\n ],\n })\n .pipe(Effect.map((rows) => rows.map(rowToOperation))),\n\n removeSource: (namespace, scope) =>\n deleteSource(namespace, scope, { includeBindings: true }),\n\n listSourceBindings: (sourceId, sourceScope) =>\n Effect.gen(function* () {\n yield* validateBindingTarget({\n sourceId,\n sourceScope,\n targetScope: sourceScope,\n });\n const sourceScopeRank = scopeRank(sourceScope);\n const rows = yield* adapter.findMany({\n model: \"openapi_source_binding\",\n where: [\n { field: \"source_id\", value: sourceId },\n { field: \"source_scope_id\", value: sourceScope },\n ],\n });\n return rows\n .filter(\n (row) =>\n scopeRank(row.target_scope_id as string) <= sourceScopeRank,\n )\n .sort(\n (a, b) =>\n scopeRank(a.target_scope_id as string) -\n scopeRank(b.target_scope_id as string),\n )\n .map(rowToSourceBinding);\n }),\n\n resolveSourceBinding: (sourceId, sourceScope, slot) =>\n Effect.gen(function* () {\n yield* validateBindingTarget({\n sourceId,\n sourceScope,\n targetScope: sourceScope,\n });\n const rows = yield* adapter.findMany({\n model: \"openapi_source_binding\",\n where: [\n { field: \"source_id\", value: sourceId },\n { field: \"source_scope_id\", value: sourceScope },\n { field: \"slot\", value: slot },\n ],\n });\n const sourceScopeRank = scopeRank(sourceScope);\n const row = rows\n .filter(\n (candidate) =>\n scopeRank(candidate.target_scope_id as string) <= sourceScopeRank,\n )\n .sort(\n (a, b) =>\n scopeRank(a.target_scope_id as string) -\n scopeRank(b.target_scope_id as string),\n )[0];\n return row ? rowToSourceBinding(row) : null;\n }),\n\n setSourceBinding: (input) =>\n Effect.gen(function* () {\n yield* validateBindingTarget({\n sourceId: input.sourceId,\n sourceScope: input.sourceScope as string,\n targetScope: input.scope as string,\n });\n const id = sourceBindingRowId(\n input.sourceId,\n input.sourceScope as string,\n input.slot,\n input.scope as string,\n );\n const now = new Date();\n yield* adapter.delete({\n model: \"openapi_source_binding\",\n where: [{ field: \"id\", value: id }],\n });\n yield* adapter.create({\n model: \"openapi_source_binding\",\n data: {\n id,\n source_id: input.sourceId,\n source_scope_id: input.sourceScope as string,\n target_scope_id: input.scope as string,\n slot: input.slot,\n value: toJsonRecord(encodeSourceBindingValue(input.value)),\n created_at: now,\n updated_at: now,\n },\n forceAllowId: true,\n });\n return new OpenApiSourceBindingRef({\n sourceId: input.sourceId,\n sourceScopeId: input.sourceScope,\n scopeId: input.scope,\n slot: input.slot,\n value: input.value,\n createdAt: now,\n updatedAt: now,\n });\n }),\n\n removeSourceBinding: (sourceId, sourceScope, slot, scope) =>\n Effect.gen(function* () {\n yield* validateBindingTarget({\n sourceId,\n sourceScope,\n targetScope: scope,\n });\n yield* adapter.delete({\n model: \"openapi_source_binding\",\n where: [\n {\n field: \"id\",\n value: sourceBindingRowId(sourceId, sourceScope, slot, scope),\n },\n ],\n });\n }),\n };\n};\n","import { Effect, Option, Schema } from \"effect\";\nimport { FetchHttpClient, HttpClient } from \"effect/unstable/http\";\nimport type { Layer } from \"effect\";\n\nimport {\n ConnectionId,\n ScopeId,\n SecretId,\n SourceDetectionResult,\n definePlugin,\n resolveSecretBackedMap,\n type PluginCtx,\n type StorageFailure,\n type ToolAnnotations,\n type ToolRow,\n} from \"@executor-js/sdk/core\";\n\nimport {\n headersToConfigValues,\n type ConfigFileSink,\n type OpenApiSourceConfig,\n} from \"@executor-js/config\";\n\nimport { OpenApiExtractionError, OpenApiOAuthError, OpenApiParseError } from \"./errors\";\nimport { parse, resolveSpecText } from \"./parse\";\nimport { extract } from \"./extract\";\nimport { compileToolDefinitions, type ToolDefinition } from \"./definitions\";\nimport { annotationsForOperation, invokeWithLayer, resolveHeaders } from \"./invoke\";\nimport { resolveBaseUrl } from \"./openapi-utils\";\nimport { previewSpec, SpecPreview } from \"./preview\";\nimport {\n makeDefaultOpenapiStore,\n openapiSchema,\n type OpenapiStore,\n type SourceConfig,\n type StoredOperation,\n type StoredSource,\n} from \"./store\";\nimport {\n HeaderValue as HeaderValueSchema,\n ConfiguredHeaderBinding,\n OAuth2Auth,\n OAuth2SourceConfig,\n OpenApiSourceBindingInput,\n type OpenApiSourceBindingRef,\n type OpenApiSourceBindingValue,\n OperationBinding,\n type ConfiguredHeaderValue as ConfiguredHeaderValueValue,\n type HeaderValue as HeaderValueValue,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Plugin config\n// ---------------------------------------------------------------------------\n\nexport type HeaderValue = HeaderValueValue;\nexport type ConfiguredHeaderValue = ConfiguredHeaderValueValue;\nexport type OpenApiHeaderInput = HeaderValue | ConfiguredHeaderValue;\nexport type OpenApiOAuthInput = OAuth2Auth | OAuth2SourceConfig;\n\nexport interface OpenApiSpecFetchCredentials {\n readonly headers?: Record<string, HeaderValue>;\n readonly queryParams?: Record<string, HeaderValue>;\n}\n\nexport interface OpenApiPreviewInput {\n readonly spec: string;\n readonly specFetchCredentials?: OpenApiSpecFetchCredentials;\n}\n\nexport interface OpenApiSpecConfig {\n readonly spec: string;\n readonly specFetchCredentials?: OpenApiSpecFetchCredentials;\n /**\n * Executor scope id that owns this source row. Must be one of the\n * executor's configured scopes. Typical shape: an admin adds the\n * source at the outermost (organization) scope so it's visible to\n * every inner (per-user) scope via fall-through reads.\n */\n readonly scope: string;\n readonly name?: string;\n readonly baseUrl?: string;\n readonly namespace?: string;\n readonly headers?: Record<string, OpenApiHeaderInput>;\n readonly queryParams?: Record<string, HeaderValue>;\n readonly oauth2?: OpenApiOAuthInput;\n}\n\nexport interface OpenApiUpdateSourceInput {\n readonly name?: string;\n readonly baseUrl?: string;\n readonly headers?: Record<string, OpenApiHeaderInput>;\n readonly queryParams?: Record<string, HeaderValue>;\n /** Refresh the source's stored OAuth2 metadata after a successful\n * re-authenticate. */\n readonly oauth2?: OpenApiOAuthInput;\n}\n\n/**\n * Errors any OpenAPI extension method may surface. The first three are\n * plugin-domain tagged errors that flow directly to clients (4xx, each\n * carrying its own `HttpApiSchema` status). `StorageFailure` covers\n * raw backend failures (`StorageError`) plus `UniqueViolationError`;\n * the HTTP edge (`@executor-js/api`'s `withCapture`) translates\n * `StorageError` to the opaque `InternalError({ traceId })` at Layer\n * composition. `UniqueViolationError` passes through — plugins can\n * `Effect.catchTag` it if they want a friendlier user-facing error.\n */\nexport type OpenApiExtensionFailure =\n | OpenApiParseError\n | OpenApiExtractionError\n | OpenApiOAuthError\n | StorageFailure;\n\nexport interface OpenApiPluginExtension {\n readonly previewSpec: (\n input: string | OpenApiPreviewInput,\n ) => Effect.Effect<\n SpecPreview,\n OpenApiParseError | OpenApiExtractionError | OpenApiOAuthError | StorageFailure\n >;\n readonly addSpec: (\n config: OpenApiSpecConfig,\n ) => Effect.Effect<\n { readonly sourceId: string; readonly toolCount: number },\n OpenApiParseError | OpenApiExtractionError | OpenApiOAuthError | StorageFailure\n >;\n readonly removeSpec: (namespace: string, scope: string) => Effect.Effect<void, StorageFailure>;\n readonly getSource: (\n namespace: string,\n scope: string,\n ) => Effect.Effect<StoredSource | null, StorageFailure>;\n readonly updateSource: (\n namespace: string,\n scope: string,\n input: OpenApiUpdateSourceInput,\n ) => Effect.Effect<void, StorageFailure>;\n readonly listSourceBindings: (\n sourceId: string,\n sourceScope: string,\n ) => Effect.Effect<readonly OpenApiSourceBindingRef[], StorageFailure>;\n readonly setSourceBinding: (\n input: OpenApiSourceBindingInput,\n ) => Effect.Effect<OpenApiSourceBindingRef, StorageFailure>;\n readonly removeSourceBinding: (\n sourceId: string,\n sourceScope: string,\n slot: string,\n scope: string,\n ) => Effect.Effect<void, StorageFailure>;\n}\n\n// ---------------------------------------------------------------------------\n// Control-tool input/output schemas\n// ---------------------------------------------------------------------------\n\nconst PreviewSpecInputSchema = Schema.Struct({\n spec: Schema.String,\n specFetchCredentials: Schema.optional(\n Schema.Struct({\n headers: Schema.optional(Schema.Record(Schema.String, HeaderValueSchema)),\n queryParams: Schema.optional(Schema.Record(Schema.String, HeaderValueSchema)),\n }),\n ),\n});\ntype PreviewSpecInput = typeof PreviewSpecInputSchema.Type;\n\nconst AddSourceInputSchema = Schema.Struct({\n spec: Schema.String,\n baseUrl: Schema.optional(Schema.String),\n namespace: Schema.optional(Schema.String),\n headers: Schema.optional(Schema.Record(Schema.String, HeaderValueSchema)),\n queryParams: Schema.optional(Schema.Record(Schema.String, HeaderValueSchema)),\n specFetchCredentials: Schema.optional(\n Schema.Struct({\n headers: Schema.optional(Schema.Record(Schema.String, HeaderValueSchema)),\n queryParams: Schema.optional(Schema.Record(Schema.String, HeaderValueSchema)),\n }),\n ),\n});\ntype AddSourceInput = typeof AddSourceInputSchema.Type;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Rewrite OpenAPI `#/components/schemas/X` refs to standard `#/$defs/X`. */\nconst normalizeOpenApiRefs = (node: unknown): unknown => {\n if (node == null || typeof node !== \"object\") return node;\n if (Array.isArray(node)) {\n let changed = false;\n const out = node.map((item) => {\n const n = normalizeOpenApiRefs(item);\n if (n !== item) changed = true;\n return n;\n });\n return changed ? out : node;\n }\n\n const obj = node as Record<string, unknown>;\n\n if (typeof obj.$ref === \"string\") {\n const match = obj.$ref.match(/^#\\/components\\/schemas\\/(.+)$/);\n if (match) return { ...obj, $ref: `#/$defs/${match[1]}` };\n return obj;\n }\n\n let changed = false;\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) {\n const n = normalizeOpenApiRefs(v);\n if (n !== v) changed = true;\n result[k] = n;\n }\n return changed ? result : obj;\n};\n\nconst toBinding = (def: ToolDefinition): OperationBinding =>\n new OperationBinding({\n method: def.operation.method,\n pathTemplate: def.operation.pathTemplate,\n parameters: [...def.operation.parameters],\n requestBody: def.operation.requestBody,\n });\n\nconst descriptionFor = (def: ToolDefinition): string => {\n const op = def.operation;\n return Option.getOrElse(op.description, () =>\n Option.getOrElse(op.summary, () => `${op.method.toUpperCase()} ${op.pathTemplate}`),\n );\n};\n\nconst headerSlotFromName = (name: string): string =>\n `header:${\n name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"default\"\n }`;\n\nconst oauthClientIdSlot = (securitySchemeName: string): string =>\n `oauth2:${\n securitySchemeName\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"default\"\n }:client-id`;\n\nconst oauthClientSecretSlot = (securitySchemeName: string): string =>\n `oauth2:${\n securitySchemeName\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"default\"\n }:client-secret`;\n\nconst oauthConnectionSlot = (securitySchemeName: string): string =>\n `oauth2:${\n securitySchemeName\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"default\"\n }:connection`;\n\nconst canonicalizeHeaders = (\n headers: Record<string, OpenApiHeaderInput> | undefined,\n): {\n readonly headers: Record<string, ConfiguredHeaderValue>;\n readonly bindings: ReadonlyArray<{\n readonly slot: string;\n readonly value: OpenApiSourceBindingValue;\n }>;\n} => {\n const nextHeaders: Record<string, ConfiguredHeaderValue> = {};\n const bindings: Array<{ slot: string; value: OpenApiSourceBindingValue }> = [];\n for (const [name, value] of Object.entries(headers ?? {})) {\n if (typeof value === \"string\") {\n nextHeaders[name] = value;\n continue;\n }\n if (\"kind\" in value) {\n nextHeaders[name] = value;\n continue;\n }\n const slot = headerSlotFromName(name);\n nextHeaders[name] = new ConfiguredHeaderBinding({\n kind: \"binding\",\n slot,\n prefix: value.prefix,\n });\n bindings.push({\n slot,\n value: {\n kind: \"secret\",\n secretId: SecretId.make(value.secretId),\n },\n });\n }\n return { headers: nextHeaders, bindings };\n};\n\nconst canonicalizeOAuth2 = (\n oauth2: OpenApiOAuthInput | undefined,\n): {\n readonly oauth2?: OAuth2SourceConfig;\n readonly bindings: ReadonlyArray<{\n readonly slot: string;\n readonly value: OpenApiSourceBindingValue;\n }>;\n} => {\n if (!oauth2) return { bindings: [] };\n if (\"connectionSlot\" in oauth2) {\n return { oauth2, bindings: [] };\n }\n const bindings: Array<{ slot: string; value: OpenApiSourceBindingValue }> = [\n {\n slot: oauthClientIdSlot(oauth2.securitySchemeName),\n value: {\n kind: \"secret\",\n secretId: SecretId.make(oauth2.clientIdSecretId),\n },\n },\n ];\n if (oauth2.clientSecretSecretId) {\n bindings.push({\n slot: oauthClientSecretSlot(oauth2.securitySchemeName),\n value: {\n kind: \"secret\",\n secretId: SecretId.make(oauth2.clientSecretSecretId),\n },\n });\n }\n if (oauth2.connectionId) {\n bindings.push({\n slot: oauthConnectionSlot(oauth2.securitySchemeName),\n value: {\n kind: \"connection\",\n connectionId: ConnectionId.make(oauth2.connectionId),\n },\n });\n }\n return {\n oauth2: new OAuth2SourceConfig({\n kind: \"oauth2\",\n securitySchemeName: oauth2.securitySchemeName,\n flow: oauth2.flow,\n tokenUrl: oauth2.tokenUrl,\n authorizationUrl: oauth2.authorizationUrl,\n clientIdSlot: oauthClientIdSlot(oauth2.securitySchemeName),\n clientSecretSlot: oauth2.clientSecretSecretId\n ? oauthClientSecretSlot(oauth2.securitySchemeName)\n : null,\n connectionSlot: oauthConnectionSlot(oauth2.securitySchemeName),\n scopes: [...oauth2.scopes],\n }),\n bindings,\n };\n};\n\ninterface EffectiveSourceConfig {\n readonly config: SourceConfig;\n readonly headersSource: StoredSource;\n readonly oauth2Source: StoredSource;\n}\n\nconst resolveEffectiveSourceConfig = (\n ctx: PluginCtx<OpenapiStore>,\n base: StoredSource,\n): Effect.Effect<EffectiveSourceConfig, StorageFailure> =>\n Effect.gen(function* () {\n const rank = new Map(ctx.scopes.map((scope, index) => [scope.id as string, index] as const));\n const baseRank = rank.get(base.scope) ?? Infinity;\n let fallback: StoredSource | null = null;\n for (let index = baseRank + 1; index < ctx.scopes.length; index++) {\n const scope = ctx.scopes[index];\n if (!scope) continue;\n fallback = yield* ctx.storage.getSource(base.namespace, scope.id as string);\n if (fallback) break;\n }\n\n if (!fallback) {\n return {\n config: base.config,\n headersSource: base,\n oauth2Source: base,\n };\n }\n\n const hasBaseHeaders = Object.keys(base.config.headers ?? {}).length > 0;\n const hasBaseQueryParams = Object.keys(base.config.queryParams ?? {}).length > 0;\n return {\n config: {\n ...base.config,\n sourceUrl: base.config.sourceUrl ?? fallback.config.sourceUrl,\n baseUrl: base.config.baseUrl || fallback.config.baseUrl,\n namespace: base.config.namespace ?? fallback.config.namespace,\n headers: hasBaseHeaders ? base.config.headers : fallback.config.headers,\n queryParams: hasBaseQueryParams ? base.config.queryParams : fallback.config.queryParams,\n specFetchCredentials:\n base.config.specFetchCredentials ?? fallback.config.specFetchCredentials,\n oauth2: base.config.oauth2 ?? fallback.config.oauth2,\n },\n headersSource: hasBaseHeaders ? base : fallback,\n oauth2Source: base.config.oauth2 ? base : fallback,\n };\n });\n\nconst resolveConfiguredHeaders = (\n ctx: PluginCtx<OpenapiStore>,\n params: {\n readonly sourceId: string;\n readonly sourceScope: string;\n readonly headers: Record<string, ConfiguredHeaderValue>;\n readonly legacyHeaders?: Record<string, HeaderValue>;\n },\n): Effect.Effect<Record<string, string>, OpenApiOAuthError | StorageFailure> =>\n Effect.gen(function* () {\n const resolved: Record<string, string> = {};\n for (const [name, value] of Object.entries(params.headers)) {\n if (typeof value === \"string\") {\n resolved[name] = value;\n continue;\n }\n const binding = yield* ctx.storage.resolveSourceBinding(\n params.sourceId,\n params.sourceScope,\n value.slot,\n );\n if (binding?.value.kind === \"secret\") {\n const secret = yield* ctx.secrets.get(binding.value.secretId as string).pipe(\n Effect.mapError((err) =>\n \"_tag\" in err && err._tag === \"SecretOwnedByConnectionError\"\n ? new OpenApiOAuthError({\n message: `Secret not found for header \"${name}\"`,\n })\n : err,\n ),\n );\n if (secret === null) {\n return yield* new OpenApiOAuthError({\n message: `Missing secret \"${binding.value.secretId}\" for header \"${name}\"`,\n });\n }\n resolved[name] = value.prefix ? `${value.prefix}${secret}` : secret;\n continue;\n }\n if (binding?.value.kind === \"text\") {\n resolved[name] = value.prefix ? `${value.prefix}${binding.value.text}` : binding.value.text;\n continue;\n }\n const legacy = params.legacyHeaders?.[name];\n if (legacy) {\n const fallback = yield* resolveHeaders({ [name]: legacy }, ctx.secrets).pipe(\n Effect.map((headers) => headers[name]!),\n Effect.mapError((err) =>\n err instanceof OpenApiOAuthError\n ? err\n : new OpenApiOAuthError({ message: err.message }),\n ),\n );\n resolved[name] = fallback;\n continue;\n }\n return yield* new OpenApiOAuthError({\n message: `Missing binding for header \"${name}\"`,\n });\n }\n return resolved;\n });\n\nconst resolveHeaderValues = (\n ctx: PluginCtx<OpenapiStore>,\n values: Record<string, HeaderValue> | undefined,\n): Effect.Effect<Record<string, string>, OpenApiOAuthError | StorageFailure> =>\n resolveSecretBackedMap({\n values,\n getSecret: ctx.secrets.get,\n onMissing: (name) =>\n new OpenApiOAuthError({\n message: `Secret not found for \"${name}\"`,\n }),\n onError: (err, name) =>\n \"_tag\" in err && err._tag === \"SecretOwnedByConnectionError\"\n ? new OpenApiOAuthError({\n message: `Secret not found for \"${name}\"`,\n })\n : err,\n }).pipe(\n Effect.mapError((err) =>\n \"_tag\" in err && err._tag === \"SecretOwnedByConnectionError\"\n ? new OpenApiOAuthError({ message: \"Secret resolution failed\" })\n : err,\n ),\n Effect.map((resolved) => resolved ?? {}),\n );\n\nconst resolveOAuthConnectionId = (\n ctx: PluginCtx<OpenapiStore>,\n params: {\n readonly sourceId: string;\n readonly sourceScope: string;\n readonly oauth2: OAuth2SourceConfig;\n readonly legacyOAuth2?: OAuth2Auth;\n },\n): Effect.Effect<string | null, StorageFailure> =>\n Effect.gen(function* () {\n const binding = yield* ctx.storage.resolveSourceBinding(\n params.sourceId,\n params.sourceScope,\n params.oauth2.connectionSlot,\n );\n if (binding?.value.kind === \"connection\") {\n const connectionId = binding.value.connectionId as string;\n const connection = yield* ctx.connections.get(connectionId);\n return connection ? connectionId : null;\n }\n if (!params.legacyOAuth2?.connectionId) return null;\n const legacyConnection = yield* ctx.connections.get(params.legacyOAuth2.connectionId);\n return legacyConnection ? params.legacyOAuth2.connectionId : null;\n });\n\nconst resolveSpecFetchCredentials = (\n ctx: PluginCtx<OpenapiStore>,\n credentials: OpenApiSpecFetchCredentials | undefined,\n) =>\n Effect.gen(function* () {\n if (!credentials) return undefined;\n return {\n headers: yield* resolveHeaderValues(ctx, credentials.headers),\n queryParams: yield* resolveHeaderValues(ctx, credentials.queryParams),\n };\n });\n\n// ---------------------------------------------------------------------------\n// OAuth2 token exchange / refresh is owned by `ctx.oauth`, which registers\n// the canonical core `\"oauth2\"` ConnectionProvider. OpenAPI owns only the\n// source-specific semantics: slots for client credentials and the connection\n// binding that invocation resolves before calling `ctx.connections.accessToken`.\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Plugin factory\n// ---------------------------------------------------------------------------\n\nexport interface OpenApiPluginOptions {\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient, never, never>;\n /** If provided, source add/remove is mirrored to executor.jsonc\n * (best-effort — file errors are logged, not raised). */\n readonly configFile?: ConfigFileSink;\n}\n\nconst toOpenApiSourceConfig = (\n namespace: string,\n config: OpenApiSpecConfig,\n): OpenApiSourceConfig => {\n const legacyHeaders: Record<string, HeaderValueValue> = {};\n for (const [name, value] of Object.entries(config.headers ?? {})) {\n if (typeof value === \"string\" || !(\"kind\" in value)) {\n legacyHeaders[name] = value;\n }\n }\n return {\n kind: \"openapi\",\n spec: config.spec,\n baseUrl: config.baseUrl,\n namespace,\n headers: headersToConfigValues(\n Object.keys(legacyHeaders).length > 0 ? legacyHeaders : undefined,\n ),\n };\n};\n\nconst isHttpUrl = (s: string): boolean => s.startsWith(\"http://\") || s.startsWith(\"https://\");\n\nexport const openApiPlugin = definePlugin<\n \"openapi\",\n OpenApiPluginExtension,\n OpenapiStore,\n typeof openapiSchema,\n OpenApiPluginOptions\n>((options?: OpenApiPluginOptions) => {\n const httpClientLayer = options?.httpClientLayer ?? FetchHttpClient.layer;\n\n type RebuildInput = {\n readonly specText: string;\n readonly scope: string;\n readonly sourceUrl?: string;\n readonly name?: string;\n readonly baseUrl?: string;\n readonly namespace?: string;\n readonly headers?: Record<string, OpenApiHeaderInput>;\n readonly queryParams?: Record<string, HeaderValue>;\n readonly specFetchCredentials?: OpenApiSpecFetchCredentials;\n readonly oauth2?: OpenApiOAuthInput;\n };\n\n // ctx comes from the plugin runtime — the same instance is passed to\n // `extension(ctx)` and to every lifecycle hook (`refreshSource`, etc.),\n // so helpers parameterised on ctx can be called from either surface.\n const rebuildSource = (ctx: PluginCtx<OpenapiStore>, input: RebuildInput) =>\n Effect.gen(function* () {\n const doc = yield* parse(input.specText);\n const result = yield* extract(doc);\n\n const namespace =\n input.namespace ??\n Option.getOrElse(result.title, () => \"api\")\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\");\n\n const hoistedDefs: Record<string, unknown> = {};\n if (doc.components?.schemas) {\n for (const [k, v] of Object.entries(doc.components.schemas)) {\n hoistedDefs[k] = normalizeOpenApiRefs(v);\n }\n }\n\n const baseUrl = input.baseUrl ?? resolveBaseUrl(result.servers);\n const canonicalHeaders = canonicalizeHeaders(input.headers);\n const canonicalOAuth2 = canonicalizeOAuth2(input.oauth2);\n\n const definitions = compileToolDefinitions(result.operations);\n const sourceName = input.name ?? Option.getOrElse(result.title, () => namespace);\n\n const sourceConfig: SourceConfig = {\n spec: input.specText,\n sourceUrl: input.sourceUrl,\n baseUrl,\n namespace: input.namespace,\n headers: canonicalHeaders.headers,\n queryParams: input.queryParams,\n specFetchCredentials: input.specFetchCredentials,\n oauth2: canonicalOAuth2.oauth2,\n };\n\n const storedSource: StoredSource = {\n namespace,\n scope: input.scope,\n name: sourceName,\n config: sourceConfig,\n };\n\n const storedOps: StoredOperation[] = definitions.map((def) => ({\n toolId: `${namespace}.${def.toolPath}`,\n sourceId: namespace,\n binding: toBinding(def),\n }));\n\n yield* ctx.transaction(\n Effect.gen(function* () {\n yield* ctx.storage.upsertSource(storedSource, storedOps);\n yield* ctx.core.sources.register({\n id: namespace,\n scope: input.scope,\n kind: \"openapi\",\n name: sourceName,\n url: baseUrl || undefined,\n canRemove: true,\n // `canRefresh` reflects whether we still know the\n // origin URL — sources added from raw spec text have\n // nothing to re-fetch, so refresh stays disabled.\n canRefresh: input.sourceUrl != null,\n canEdit: true,\n tools: definitions.map((def) => ({\n name: def.toolPath,\n description: descriptionFor(def),\n inputSchema: normalizeOpenApiRefs(Option.getOrUndefined(def.operation.inputSchema)),\n outputSchema: normalizeOpenApiRefs(Option.getOrUndefined(def.operation.outputSchema)),\n })),\n });\n\n for (const binding of [...canonicalHeaders.bindings, ...canonicalOAuth2.bindings]) {\n yield* ctx.storage.setSourceBinding(\n new OpenApiSourceBindingInput({\n sourceId: namespace,\n sourceScope: ScopeId.make(input.scope),\n scope: ScopeId.make(input.scope),\n slot: binding.slot,\n value: binding.value,\n }),\n );\n }\n\n if (Object.keys(hoistedDefs).length > 0) {\n yield* ctx.core.definitions.register({\n sourceId: namespace,\n scope: input.scope,\n definitions: hoistedDefs,\n });\n }\n }),\n );\n\n return { sourceId: namespace, toolCount: definitions.length };\n });\n\n // No-op for missing sources and for sources added from raw spec\n // text (no URL to re-fetch from). UIs gate the action via\n // `canRefresh` on the source row; reaching here without a URL\n // means the caller bypassed that gate, so we stay quiet rather\n // than surface a 500 through the unwhitelisted error channel.\n const refreshSourceInternal = (ctx: PluginCtx<OpenapiStore>, sourceId: string, scope: string) =>\n Effect.gen(function* () {\n const existing = yield* ctx.storage.getSource(sourceId, scope);\n if (!existing) return;\n const effective = yield* resolveEffectiveSourceConfig(ctx, existing);\n const resolvedConfig = effective.config;\n const sourceUrl = resolvedConfig.sourceUrl;\n if (!sourceUrl) return;\n const credentials = yield* resolveSpecFetchCredentials(\n ctx,\n resolvedConfig.specFetchCredentials,\n );\n const specText = yield* resolveSpecText(sourceUrl, credentials).pipe(\n Effect.provide(httpClientLayer),\n );\n yield* rebuildSource(ctx, {\n specText,\n scope,\n sourceUrl,\n name: existing.name,\n baseUrl: resolvedConfig.baseUrl,\n namespace: existing.namespace,\n headers: existing.legacy?.headers ?? existing.config.headers,\n queryParams: existing.config.queryParams,\n specFetchCredentials: resolvedConfig.specFetchCredentials,\n oauth2: existing.legacy?.oauth2 ?? existing.config.oauth2,\n });\n });\n\n return {\n id: \"openapi\" as const,\n schema: openapiSchema,\n storage: (deps): OpenapiStore => makeDefaultOpenapiStore(deps),\n\n extension: (ctx) => {\n const addSpecInternal = (config: OpenApiSpecConfig) =>\n Effect.gen(function* () {\n // Resolve URL → text and parse BEFORE opening a transaction.\n // Holding `BEGIN` on the pool=1 Postgres connection across a\n // network fetch is the Hyperdrive deadlock path in production.\n const credentials = yield* resolveSpecFetchCredentials(ctx, config.specFetchCredentials);\n const specText = yield* resolveSpecText(config.spec, credentials).pipe(\n Effect.provide(httpClientLayer),\n );\n return yield* rebuildSource(ctx, {\n specText,\n scope: config.scope,\n sourceUrl: isHttpUrl(config.spec) ? config.spec : undefined,\n name: config.name,\n baseUrl: config.baseUrl,\n namespace: config.namespace,\n headers: config.headers,\n queryParams: config.queryParams,\n specFetchCredentials: config.specFetchCredentials,\n oauth2: config.oauth2,\n });\n });\n\n const configFile = options?.configFile;\n\n return {\n previewSpec: (input) =>\n Effect.gen(function* () {\n const previewInput = typeof input === \"string\" ? { spec: input } : input;\n const credentials = yield* resolveSpecFetchCredentials(\n ctx,\n previewInput.specFetchCredentials,\n );\n const specText = yield* resolveSpecText(previewInput.spec, credentials).pipe(\n Effect.provide(httpClientLayer),\n );\n return yield* previewSpec(specText).pipe(Effect.provide(httpClientLayer));\n }),\n\n addSpec: (config) =>\n Effect.gen(function* () {\n const result = yield* addSpecInternal(config);\n if (configFile) {\n yield* configFile.upsertSource(toOpenApiSourceConfig(result.sourceId, config));\n }\n return result;\n }),\n\n removeSpec: (namespace, scope) =>\n Effect.gen(function* () {\n yield* ctx.transaction(\n Effect.gen(function* () {\n yield* ctx.storage.removeSource(namespace, scope);\n yield* ctx.core.sources.unregister(namespace);\n }),\n );\n if (configFile) {\n yield* configFile.removeSource(namespace);\n }\n }),\n\n getSource: (namespace, scope) =>\n Effect.gen(function* () {\n const source = yield* ctx.storage.getSource(namespace, scope);\n if (!source) return null;\n const effective = yield* resolveEffectiveSourceConfig(ctx, source);\n return {\n ...source,\n config: effective.config,\n };\n }),\n\n updateSource: (namespace, scope, input) =>\n Effect.gen(function* () {\n const existing = yield* ctx.storage.getSource(namespace, scope);\n if (!existing) return;\n const canonicalHeaders =\n input.headers !== undefined\n ? canonicalizeHeaders(input.headers)\n : existing.legacy?.headers\n ? canonicalizeHeaders(existing.legacy.headers)\n : null;\n const canonicalOAuth2 =\n input.oauth2 !== undefined\n ? canonicalizeOAuth2(input.oauth2)\n : existing.legacy?.oauth2\n ? canonicalizeOAuth2(existing.legacy.oauth2)\n : null;\n yield* ctx.storage.updateSourceMeta(namespace, scope, {\n name: input.name?.trim() || undefined,\n baseUrl: input.baseUrl,\n headers: canonicalHeaders?.headers,\n queryParams: input.queryParams,\n oauth2: canonicalOAuth2?.oauth2,\n });\n for (const set of [canonicalHeaders?.bindings, canonicalOAuth2?.bindings]) {\n for (const binding of set ?? []) {\n yield* ctx.storage.setSourceBinding(\n new OpenApiSourceBindingInput({\n sourceId: namespace,\n sourceScope: ScopeId.make(scope),\n scope: ScopeId.make(scope),\n slot: binding.slot,\n value: binding.value,\n }),\n );\n }\n }\n }),\n\n listSourceBindings: (sourceId, sourceScope) =>\n ctx.storage.listSourceBindings(sourceId, sourceScope),\n\n setSourceBinding: (input) => ctx.storage.setSourceBinding(input),\n\n removeSourceBinding: (sourceId, sourceScope, slot, scope) =>\n ctx.storage.removeSourceBinding(sourceId, sourceScope, slot, scope),\n } satisfies OpenApiPluginExtension;\n },\n\n staticSources: (self) => [\n {\n id: \"openapi\",\n kind: \"control\",\n name: \"OpenAPI\",\n tools: [\n {\n name: \"previewSpec\",\n description: \"Preview an OpenAPI document before adding it as a source\",\n inputSchema: {\n type: \"object\",\n properties: {\n spec: { type: \"string\" },\n specFetchCredentials: { type: \"object\" },\n },\n required: [\"spec\"],\n },\n handler: ({ args }) => self.previewSpec(args as PreviewSpecInput),\n },\n {\n name: \"addSource\",\n description: \"Add an OpenAPI source and register its operations as tools\",\n inputSchema: {\n type: \"object\",\n properties: {\n spec: { type: \"string\" },\n name: { type: \"string\" },\n baseUrl: { type: \"string\" },\n namespace: { type: \"string\" },\n headers: { type: \"object\" },\n queryParams: { type: \"object\" },\n oauth2: { type: \"object\" },\n specFetchCredentials: { type: \"object\" },\n },\n required: [\"spec\"],\n },\n outputSchema: {\n type: \"object\",\n properties: {\n sourceId: { type: \"string\" },\n toolCount: { type: \"number\" },\n },\n required: [\"sourceId\", \"toolCount\"],\n },\n // Static-tool callers don't name a scope. Default to the\n // outermost scope in the executor's stack — for a single-\n // scope executor that's the only scope; for a per-user\n // stack `[user, org]` it writes at `org` so the source is\n // visible across every user.\n handler: ({ ctx, args }) =>\n self.addSpec({\n ...(args as AddSourceInput),\n scope: ctx.scopes.at(-1)!.id as string,\n }),\n },\n ],\n },\n ],\n\n invokeTool: ({ ctx, toolRow, args }) =>\n Effect.gen(function* () {\n // toolRow.scope_id is the resolved owning scope of the tool\n // (innermost-wins from the executor's stack). The matching\n // openapi_operation + openapi_source rows live at the same\n // scope, so pin every store lookup to it instead of relying\n // on the scoped adapter's stack-wide fall-through.\n const toolScope = toolRow.scope_id as string;\n const op = yield* ctx.storage.getOperationByToolId(toolRow.id, toolScope);\n if (!op) {\n return yield* Effect.fail(\n new Error(`No OpenAPI operation found for tool \"${toolRow.id}\"`),\n );\n }\n const source = yield* ctx.storage.getSource(op.sourceId, toolScope);\n if (!source) {\n return yield* Effect.fail(new Error(`No OpenAPI source found for \"${op.sourceId}\"`));\n }\n\n const effective = yield* resolveEffectiveSourceConfig(ctx, source);\n const config = effective.config;\n const resolvedHeaders = yield* resolveConfiguredHeaders(ctx, {\n sourceId: op.sourceId,\n sourceScope: effective.headersSource.scope,\n headers: config.headers ?? {},\n legacyHeaders: effective.headersSource.legacy?.headers,\n }).pipe(Effect.mapError((err) => new Error(err.message)));\n const resolvedQueryParams = yield* resolveHeaderValues(ctx, config.queryParams).pipe(\n Effect.mapError((err) => new Error(err.message)),\n );\n\n // If the source has OAuth2 auth, resolve a guaranteed-fresh\n // access token from the backing Connection and inject the\n // Authorization header (wins over a manually-set one). All the\n // refresh complexity lives in the SDK — the plugin just asks.\n if (config.oauth2) {\n const connectionId = yield* resolveOAuthConnectionId(ctx, {\n sourceId: op.sourceId,\n sourceScope: effective.oauth2Source.scope,\n oauth2: config.oauth2,\n legacyOAuth2: effective.oauth2Source.legacy?.oauth2,\n });\n if (!connectionId) {\n return yield* Effect.fail(\n new Error(`OAuth configuration for \"${op.sourceId}\" is missing a connection binding`),\n );\n }\n const accessToken = yield* ctx.connections\n .accessToken(connectionId)\n .pipe(\n Effect.mapError(\n (err) =>\n new Error(\n `OAuth connection resolution failed: ${\n \"message\" in err ? (err as { message: string }).message : String(err)\n }`,\n ),\n ),\n );\n resolvedHeaders.authorization = `Bearer ${accessToken}`;\n }\n\n const result = yield* invokeWithLayer(\n op.binding,\n (args ?? {}) as Record<string, unknown>,\n config.baseUrl ?? \"\",\n resolvedHeaders,\n resolvedQueryParams,\n httpClientLayer,\n );\n\n return result;\n }),\n\n resolveAnnotations: ({ ctx, sourceId, toolRows }) =>\n Effect.gen(function* () {\n // toolRows for a single (plugin_id, source_id) group can still\n // straddle multiple scopes when the source is shadowed (e.g. an\n // org-level openapi source plus a per-user override that\n // re-registers the same tool ids). Run one listOperationsBySource\n // per distinct scope so each lookup pins {source_id, scope_id}\n // and we don't fall through to the wrong scope's bindings.\n const scopes = new Set<string>();\n for (const row of toolRows as readonly ToolRow[]) {\n scopes.add(row.scope_id as string);\n }\n // One listOperationsBySource per scope is independent storage\n // work; run them in parallel so a shadowed source doesn't\n // serialise two ~200ms reads back-to-back in the caller's\n // `executor.tools.list.annotations` span.\n const entries = yield* Effect.forEach(\n [...scopes],\n (scope) =>\n Effect.gen(function* () {\n const ops = yield* ctx.storage.listOperationsBySource(sourceId, scope);\n const byId = new Map<string, OperationBinding>();\n for (const op of ops) byId.set(op.toolId, op.binding);\n return [scope, byId] as const;\n }),\n { concurrency: \"unbounded\" },\n );\n const byScope = new Map<string, Map<string, OperationBinding>>(entries);\n\n const out: Record<string, ToolAnnotations> = {};\n for (const row of toolRows as readonly ToolRow[]) {\n const binding = byScope.get(row.scope_id as string)?.get(row.id);\n if (binding) {\n out[row.id] = annotationsForOperation(binding.method, binding.pathTemplate);\n }\n }\n return out;\n }),\n\n removeSource: ({ ctx, sourceId, scope }) => ctx.storage.removeSource(sourceId, scope),\n\n // Re-fetch the spec from its origin URL (captured at addSpec time)\n // and replay the same parse → extract → upsertSource → register\n // path used by addSpec. Sources without a stored URL surface a\n // typed `OpenApiParseError` — the executor only dispatches refresh\n // when `canRefresh: true`, so a raw-text source reaching here\n // means stale UI state, which is worth surfacing to the caller.\n refreshSource: ({ ctx, sourceId, scope }) => refreshSourceInternal(ctx, sourceId, scope),\n\n detect: ({ url }) =>\n Effect.gen(function* () {\n const trimmed = url.trim();\n if (!trimmed) return null;\n const parsed = yield* Effect.try({\n try: () => new URL(trimmed),\n catch: (error) => error,\n }).pipe(Effect.option);\n if (Option.isNone(parsed)) return null;\n const specText = yield* resolveSpecText(trimmed).pipe(\n Effect.provide(httpClientLayer),\n Effect.catch(() => Effect.succeed(null)),\n );\n if (specText === null) return null;\n const doc = yield* parse(specText).pipe(Effect.catch(() => Effect.succeed(null)));\n if (!doc) return null;\n const result = yield* extract(doc).pipe(Effect.catch(() => Effect.succeed(null)));\n if (!result) return null;\n const namespace = Option.getOrElse(result.title, () => \"api\")\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\");\n const name = Option.getOrElse(result.title, () => namespace);\n return new SourceDetectionResult({\n kind: \"openapi\",\n confidence: \"high\",\n endpoint: trimmed,\n name,\n namespace,\n });\n }),\n };\n});\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 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// Collision resolution\n// ---------------------------------------------------------------------------\n\nconst resolveCollisions = (\n definitions: {\n toolPath: string;\n group: string;\n leaf: string;\n versionSegment: string | undefined;\n method: string;\n operationHash: string;\n operationIndex: number;\n operation: ExtractedOperation;\n }[],\n): ToolDefinition[] => {\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 operation: d.operation,\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 * Compile extracted operations into tool definitions with structured\n * `group.leaf` paths suitable for tree rendering.\n */\nexport const compileToolDefinitions = (\n operations: readonly ExtractedOperation[],\n): ToolDefinition[] => {\n const raw = operations.map((op, index) => {\n const operationId = op.operationId as string;\n const group = normalizeGroupSegment(op.tags[0]) ?? derivePathGroup(op.pathTemplate);\n const leaf = deriveLeaf(operationId, op.method, op.pathTemplate, group);\n const versionSegment = deriveVersionSegment(op.pathTemplate);\n const operationHash = stableHash({\n method: op.method,\n path: op.pathTemplate,\n operationId,\n });\n\n return {\n toolPath: `${group}.${leaf}`,\n group,\n leaf,\n versionSegment,\n method: op.method,\n operationHash,\n operationIndex: index,\n operation: op,\n };\n });\n\n return resolveCollisions(raw).sort((a, b) => a.toolPath.localeCompare(b.toolPath));\n};\n"],"mappings":";AAAA,SAAS,MAAM,cAAc;AAUtB,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;;;ACrCH,SAAS,UAAU,cAAc;AACjC,SAAS,YAAY,yBAAyB;AAC9C,OAAO,UAAU;AAYjB,IAAM,kCAAN,cAA8C,uBAAuB;AAAC;AAS/D,IAAM,gBAAgB,OAAO,GAAG,uBAAuB,EAAE,WAC9D,KACA,aACA;AACA,QAAM,SAAS,OAAO,WAAW;AACjC,QAAM,aAAa,IAAI,IAAI,GAAG;AAC9B,aAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,aAAa,eAAe,CAAC,CAAC,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,UAAI,CAAC,QAAS,QAAO;AACrB,YAAM,SAAS,OAAOA,QAAO,IAAI;AAAA,QAC/B,KAAK,MAAM,IAAI,IAAI,OAAO;AAAA,QAC1B,OAAO,CAAC,UAAU;AAAA,MACpB,CAAC,EAAE,KAAKA,QAAO,MAAM;AACrB,UAAIH,QAAO,OAAO,MAAM,EAAG,QAAO;AAClC,YAAM,WAAW,OAAO,gBAAgB,OAAO,EAAE;AAAA,QAC/CG,QAAO,QAAQ,eAAe;AAAA,QAC9BA,QAAO,MAAM,MAAMA,QAAO,QAAQ,IAAI,CAAC;AAAA,MACzC;AACA,UAAI,aAAa,KAAM,QAAO;AAC9B,YAAM,MAAM,OAAO,MAAM,QAAQ,EAAE,KAAKA,QAAO,MAAM,MAAMA,QAAO,QAAQ,IAAI,CAAC,CAAC;AAChF,UAAI,CAAC,IAAK,QAAO;AACjB,YAAM,SAAS,OAAO,QAAQ,GAAG,EAAE,KAAKA,QAAO,MAAM,MAAMA,QAAO,QAAQ,IAAI,CAAC,CAAC;AAChF,UAAI,CAAC,OAAQ,QAAO;AACpB,YAAM,YAAYH,QAAO,UAAU,OAAO,OAAO,MAAM,KAAK,EACzD,YAAY,EACZ,QAAQ,eAAe,GAAG;AAC7B,YAAM,OAAOA,QAAO,UAAU,OAAO,OAAO,MAAM,SAAS;AAC3D,aAAO,IAAI,sBAAsB;AAAA,QAC/B,MAAM;AAAA,QACN,YAAY;AAAA,QACZ,UAAU;AAAA,QACV;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH,CAAC;AAAA,EACL;AACF,CAAC;","names":["Schema","Effect","Option","Option","Effect","Effect","Option","HttpClient","HttpClientRequest","Effect","Option","HttpClientRequest","bytes","HttpClient","Effect","Option","Schema","Schema","Option","Effect","Effect","Schema","ScopeId","Schema","ScopeId","Effect","Effect","Option","Schema","ConnectionId","ScopeId","SecretId","Schema","changed","Option","SecretId","ConnectionId","Effect","ScopeId"]}