@executor-js/plugin-openapi 1.5.5 → 1.5.7

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 (58) hide show
  1. package/dist/{AddOpenApiSource-7M52SRUX.js → AddOpenApiSource-7O4LSD7C.js} +79 -241
  2. package/dist/AddOpenApiSource-7O4LSD7C.js.map +1 -0
  3. package/dist/{EditOpenApiSource-WTAMRJUK.js → EditOpenApiSource-GIN5RQPL.js} +3 -3
  4. package/dist/{OpenApiAccountsPanel-3VJJXNQF.js → OpenApiAccountsPanel-7XT6ZMD5.js} +30 -28
  5. package/dist/OpenApiAccountsPanel-7XT6ZMD5.js.map +1 -0
  6. package/dist/api/group.d.ts +38 -37
  7. package/dist/api/index.d.ts +39 -38
  8. package/dist/{chunk-YVRI7KRC.js → chunk-C3IJX4AN.js} +257 -219
  9. package/dist/chunk-C3IJX4AN.js.map +1 -0
  10. package/dist/{chunk-OSIFYIQP.js → chunk-C6PH4R7Q.js} +94 -5
  11. package/dist/chunk-C6PH4R7Q.js.map +1 -0
  12. package/dist/{chunk-BSLE6HCE.js → chunk-IB36ED7Y.js} +13 -27
  13. package/dist/chunk-IB36ED7Y.js.map +1 -0
  14. package/dist/chunk-RCBR3QMJ.js +73 -0
  15. package/dist/chunk-RCBR3QMJ.js.map +1 -0
  16. package/dist/{chunk-V7VCHYOY.js → chunk-WJQIWTZF.js} +97 -172
  17. package/dist/chunk-WJQIWTZF.js.map +1 -0
  18. package/dist/client.js +3 -3
  19. package/dist/core.js +133 -7
  20. package/dist/core.js.map +1 -1
  21. package/dist/index.js +7 -5
  22. package/dist/index.js.map +1 -1
  23. package/dist/react/AddOpenApiSource.d.ts +0 -1
  24. package/dist/react/OpenApiSourceDetailsFields.d.ts +3 -0
  25. package/dist/react/atoms.d.ts +40 -52
  26. package/dist/react/auth-method-config.d.ts +7 -4
  27. package/dist/react/client.d.ts +38 -37
  28. package/dist/sdk/config.d.ts +27 -27
  29. package/dist/sdk/derive-auth.d.ts +9 -0
  30. package/dist/sdk/extract.d.ts +11 -1
  31. package/dist/sdk/index.d.ts +6 -2
  32. package/dist/sdk/invoke.d.ts +11 -1
  33. package/dist/sdk/migrate-config.d.ts +4 -0
  34. package/dist/sdk/migrate-config.test.d.ts +1 -0
  35. package/dist/sdk/openapi-utils.d.ts +4 -8
  36. package/dist/sdk/output-schema-migration.d.ts +21 -0
  37. package/dist/sdk/output-schema-migration.test.d.ts +1 -0
  38. package/dist/sdk/plugin.d.ts +6 -4
  39. package/dist/sdk/preview.d.ts +77 -1
  40. package/dist/sdk/server-url-resolution.test.d.ts +1 -0
  41. package/dist/sdk/spec-blob-migration.d.ts +7 -0
  42. package/dist/sdk/spec-blob.test.d.ts +1 -0
  43. package/dist/sdk/store.d.ts +10 -1
  44. package/dist/sdk/tool-row-projection.test.d.ts +1 -0
  45. package/dist/sdk/types.d.ts +61 -36
  46. package/dist/testing/index.d.ts +1 -1
  47. package/dist/testing.js +4 -20
  48. package/dist/testing.js.map +1 -1
  49. package/package.json +3 -3
  50. package/dist/AddOpenApiSource-7M52SRUX.js.map +0 -1
  51. package/dist/OpenApiAccountsPanel-3VJJXNQF.js.map +0 -1
  52. package/dist/chunk-BSLE6HCE.js.map +0 -1
  53. package/dist/chunk-OSIFYIQP.js.map +0 -1
  54. package/dist/chunk-QSSRVK6M.js +0 -139
  55. package/dist/chunk-QSSRVK6M.js.map +0 -1
  56. package/dist/chunk-V7VCHYOY.js.map +0 -1
  57. package/dist/chunk-YVRI7KRC.js.map +0 -1
  58. /package/dist/{EditOpenApiSource-WTAMRJUK.js.map → EditOpenApiSource-GIN5RQPL.js.map} +0 -0
@@ -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/preview.ts"],"sourcesContent":["import { Data, Schema } from \"effect\";\nimport type { Option } from \"effect\";\nimport type { AuthToolFailureCode } from \"@executor-js/sdk/core\";\n\n// HTTP status lives on the class declaration so HttpApiBuilder's error\n// encoder (which reads `ast.annotations` off the schema it stored on\n// `group.addError(...)`) finds it. Applying the annotation post-hoc\n// via `.annotate(...)` in group.ts produced a transform-wrapper AST\n// whose status was not picked up — the error then slipped the typed\n// channel and was captured as a 500 by the observability middleware,\n// spamming Sentry on user misconfig.\nexport class OpenApiParseError extends Schema.TaggedErrorClass<OpenApiParseError>()(\n \"OpenApiParseError\",\n {\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n\nexport class OpenApiExtractionError extends Schema.TaggedErrorClass<OpenApiExtractionError>()(\n \"OpenApiExtractionError\",\n {\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n\nexport class OpenApiInvocationError extends Data.TaggedError(\"OpenApiInvocationError\")<{\n readonly message: string;\n readonly statusCode: Option.Option<number>;\n readonly cause?: unknown;\n}> {}\n\nexport class OpenApiOAuthError extends Schema.TaggedErrorClass<OpenApiOAuthError>()(\n \"OpenApiOAuthError\",\n {\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n\n// ---------------------------------------------------------------------------\n// Auth required — v2 reframes this around the connection (owner/integration/\n// name) that supplies the missing credential, not v1's source/slot/secret.\n// ---------------------------------------------------------------------------\n\nexport class OpenApiAuthRequiredError extends Data.TaggedError(\"OpenApiAuthRequiredError\")<{\n readonly code: AuthToolFailureCode;\n readonly message: string;\n readonly owner: \"org\" | \"user\";\n readonly integration: string;\n readonly connection: string;\n readonly credentialKind: \"secret\" | \"oauth\" | \"upstream\";\n readonly credentialLabel?: string;\n readonly status?: number;\n readonly details?: unknown;\n readonly cause?: unknown;\n}> {}\n","import type { OpenAPI, OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\nimport { Duration, Effect, Schema } from \"effect\";\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\";\nimport 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`.\n * Bounded by a 60s timeout.\n */\nexport const fetchSpecText = Effect.fn(\"OpenApi.fetchSpecText\")(function* (\n url: string,\n credentials?: SpecFetchCredentials,\n) {\n const client = yield* HttpClient.HttpClient;\n const requestUrl = new URL(url);\n for (const [name, value] of Object.entries(credentials?.queryParams ?? {})) {\n requestUrl.searchParams.set(name, value);\n }\n let request = HttpClientRequest.get(requestUrl.toString()).pipe(\n HttpClientRequest.setHeader(\"Accept\", \"application/json, application/yaml, text/yaml, */*\"),\n );\n for (const [name, value] of Object.entries(credentials?.headers ?? {})) {\n request = HttpClientRequest.setHeader(request, name, value);\n }\n const response = yield* client.execute(request).pipe(\n Effect.timeout(Duration.seconds(60)),\n Effect.mapError(\n (_cause) =>\n new OpenApiParseError({\n message: \"Failed to fetch OpenAPI document\",\n }),\n ),\n );\n if (response.status < 200 || response.status >= 300) {\n return yield* new OpenApiParseError({\n message: `Failed to fetch OpenAPI document: HTTP ${response.status}`,\n });\n }\n return yield* response.text.pipe(\n Effect.mapError(\n (_cause) =>\n new OpenApiParseError({\n message: \"Failed to read OpenAPI document body\",\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* parseTextToObject(text);\n\n if (!isOpenApi3(api)) {\n return yield* new OpenApiExtractionErrorFromParse({\n message:\n \"Only OpenAPI 3.x documents are supported. Swagger 2.x documents should be converted first.\",\n });\n }\n\n return api as ParsedDocument;\n});\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\nconst isOpenApi3 = (doc: OpenAPI.Document): doc is OpenAPIV3.Document | OpenAPIV3_1.Document =>\n \"openapi\" in doc && typeof doc.openapi === \"string\" && doc.openapi.startsWith(\"3.\");\n\nconst parseTextToObject = (text: string): Effect.Effect<OpenAPI.Document, OpenApiParseError> =>\n Effect.gen(function* () {\n const trimmed = text.trim();\n if (trimmed.length === 0) {\n return yield* new OpenApiParseError({\n message: \"OpenAPI document is empty\",\n });\n }\n\n const parsed = yield* parseJsonLike(trimmed).pipe(\n Effect.mapError(\n () =>\n new OpenApiParseError({\n message: \"Failed to parse OpenAPI document\",\n }),\n ),\n );\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return yield* new OpenApiParseError({\n message: \"OpenAPI document must parse to an object\",\n });\n }\n\n return parsed as OpenAPI.Document;\n });\n\nconst parseJsonText = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));\n\nconst parseJsonLike = (text: string): Effect.Effect<unknown, unknown> => {\n const parseYaml = Effect.try({\n try: () => YAML.parse(text) as unknown,\n catch: () => \"YamlParseFailed\" as const,\n });\n if (!text.startsWith(\"{\") && !text.startsWith(\"[\")) return parseYaml;\n return parseJsonText(text).pipe(Effect.catch(() => parseYaml));\n};\n","// ---------------------------------------------------------------------------\n// OpenAPI type aliases and $ref resolution\n//\n// Wraps the openapi-types V3/V3_1 union mess and provides clean ref resolution.\n// ---------------------------------------------------------------------------\n\nimport type { OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\nimport type { ParsedDocument } from \"./parse\";\nimport type { ServerVariable } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Type aliases — collapse V3 / V3_1 unions into single names\n// ---------------------------------------------------------------------------\n\nexport type ParameterObject = OpenAPIV3.ParameterObject | OpenAPIV3_1.ParameterObject;\nexport type OperationObject = OpenAPIV3.OperationObject | OpenAPIV3_1.OperationObject;\nexport type PathItemObject = OpenAPIV3.PathItemObject | OpenAPIV3_1.PathItemObject;\nexport type RequestBodyObject = OpenAPIV3.RequestBodyObject | OpenAPIV3_1.RequestBodyObject;\nexport type ResponseObject = OpenAPIV3.ResponseObject | OpenAPIV3_1.ResponseObject;\nexport type MediaTypeObject = OpenAPIV3.MediaTypeObject | OpenAPIV3_1.MediaTypeObject;\nexport type ServerObject = OpenAPIV3.ServerObject | OpenAPIV3_1.ServerObject;\n\n// ---------------------------------------------------------------------------\n// DocResolver — wraps a parsed document for clean $ref resolution\n// ---------------------------------------------------------------------------\n\nexport class DocResolver {\n constructor(readonly doc: ParsedDocument) {}\n\n /** Resolve a value that might be a $ref, returning the resolved object */\n resolve<T>(value: T | OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject): T | null {\n if (isRef(value)) {\n const resolved = this.resolvePointer(value.$ref);\n return resolved as T | null;\n }\n return value as T;\n }\n\n private resolvePointer(ref: string): unknown {\n if (!ref.startsWith(\"#/\")) return null;\n const segments = ref.slice(2).split(\"/\");\n let current: unknown = this.doc;\n for (const segment of segments) {\n if (typeof current !== \"object\" || current === null) return null;\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n }\n}\n\nconst isRef = (value: unknown): value is { $ref: string } =>\n typeof value === \"object\" && value !== null && \"$ref\" in value;\n\n// ---------------------------------------------------------------------------\n// Server URL resolution\n// ---------------------------------------------------------------------------\n\n/** Substitute `{var}` placeholders in a templated URL using a plain map. */\nexport const substituteUrlVariables = (url: string, values: Record<string, string>): string => {\n let out = url;\n for (const [name, value] of Object.entries(values)) {\n out = out.replaceAll(`{${name}}`, value);\n }\n return out;\n};\n\n/** Resolve a templated server URL, filling each `{var}` from `overrides` when\n * non-empty, otherwise the variable's spec default. URLs without placeholders\n * pass through unchanged. */\nexport const resolveServerUrl = (\n templateUrl: string,\n variables: Record<string, ServerVariable> | undefined,\n overrides: Record<string, string>,\n): string => {\n const values: Record<string, string> = {};\n for (const [name, v] of Object.entries(variables ?? {})) values[name] = v.default;\n for (const [name, value] of Object.entries(overrides)) {\n if (value) values[name] = value;\n }\n return substituteUrlVariables(templateUrl, values);\n};\n\n// ---------------------------------------------------------------------------\n// Content negotiation\n// ---------------------------------------------------------------------------\n\n/**\n * Return all declared media entries in spec order. `Object.entries` on a\n * plain object preserves insertion order in modern engines, which matches\n * spec declaration order as the parser produced it.\n */\nexport const declaredContents = (\n content: Record<string, MediaTypeObject> | undefined,\n): ReadonlyArray<{ mediaType: string; media: MediaTypeObject }> => {\n if (!content) return [];\n return Object.entries(content).map(([mediaType, media]) => ({ mediaType, media }));\n};\n\n/**\n * Pick the default media type for a requestBody or response. Matches\n * swagger-client behaviour: **first declared wins** (not JSON-first). Spec\n * authors order content entries to signal intent (upload-heavy endpoints\n * declare multipart first, JSON second); respecting that order avoids\n * silently downgrading a multipart endpoint to JSON.\n *\n * For response bodies we still want a JSON preference because the server\n * picks the response content type, not the client — the old `application/\n * json` preference is preserved via `preferredResponseContent` below.\n */\nexport const preferredContent = (\n content: Record<string, MediaTypeObject> | undefined,\n): { mediaType: string; media: MediaTypeObject } | undefined => {\n const first = declaredContents(content)[0];\n return first ? first : undefined;\n};\n\n/** Response-side content picker — still JSON-first because the server\n * picks the response media type, so we want to advertise a preference. */\nexport const preferredResponseContent = (\n content: Record<string, MediaTypeObject> | undefined,\n): { mediaType: string; media: MediaTypeObject } | undefined => {\n if (!content) return undefined;\n const entries = Object.entries(content);\n const pick =\n entries.find(([mt]) => mt === \"application/json\") ??\n entries.find(([mt]) => mt.toLowerCase().includes(\"+json\")) ??\n entries.find(([mt]) => mt.toLowerCase().includes(\"json\")) ??\n entries[0];\n return pick ? { mediaType: pick[0], media: pick[1] } : undefined;\n};\n","import { Schema } from \"effect\";\nimport { AuthTemplateSlug, type OAuthAuthentication } from \"@executor-js/sdk/shared\";\nimport {\n apiKeyMethodFromAuthTemplate,\n isApiKeyAuthTemplate,\n type ApiKeyAuthMethod,\n type ApiKeyAuthTemplate,\n} from \"@executor-js/sdk/http-auth\";\n\n// ---------------------------------------------------------------------------\n// Auth-template model.\n//\n// The apiKey method is the SHARED placements model (`@executor-js/sdk/http-auth`,\n// the same shape the graphql/mcp plugins store): N header/query placements,\n// each rendered from its own credential input. The oauth template is\n// mechanism-intrinsic and comes from core (`OAuthAuthentication`, keyed\n// `kind: \"oauth2\"` with stored endpoints+scopes); an integration's\n// `Authentication` union composes the two. Client credentials\n// (clientId/secret) live on the core `OAuthClient`, not here.\n//\n// Pre-canonical stored templates (`type: \"apiKey\"` with `variable()`-templated\n// header/query records) are rewritten by the one-off config migration\n// (`migrate-config.ts`) — runtime code knows only this model.\n// ---------------------------------------------------------------------------\n\nexport { TOKEN_VARIABLE } from \"@executor-js/sdk/http-auth\";\n\nexport type APIKeyAuthentication = ApiKeyAuthMethod;\n\n/** Every method is keyed by `kind` — `kind: \"oauth2\"` | `kind: \"apikey\"`. */\nexport type Authentication = OAuthAuthentication | APIKeyAuthentication;\n\n/** What auth inputs accept: oauth templates (wire-typed: plain slug) plus the\n * request-shaped apikey dialect (`type: \"apiKey\"`, headers/queryParams\n * records) — the ONE apikey authoring shape. Stored configs and the catalog\n * read as canonical placements; `apiKeyAuthTemplateFromMethod` serializes\n * them back for read-modify-write flows. */\nexport type OAuthAuthenticationInput = Omit<OAuthAuthentication, \"slug\"> & {\n readonly slug: string;\n};\nexport type AuthenticationInput = OAuthAuthenticationInput | ApiKeyAuthTemplate;\n\n/** Expand the request-shaped dialect into canonical placements and brand the\n * oauth slugs. A dialect entry without a slug gets a blank one —\n * `mergeAuthTemplates` backfills `custom_<id>`. */\nexport const normalizeOpenApiAuthInputs = (\n inputs: readonly AuthenticationInput[],\n): readonly Authentication[] =>\n inputs.map((input): Authentication => {\n if (!isApiKeyAuthTemplate(input)) {\n return { ...input, slug: AuthTemplateSlug.make(input.slug) };\n }\n const method = apiKeyMethodFromAuthTemplate(input);\n return { ...method, slug: method.slug ?? \"\" };\n });\n\n// ---------------------------------------------------------------------------\n// Branded IDs\n// ---------------------------------------------------------------------------\n\nexport const OperationId = Schema.String.pipe(Schema.brand(\"OperationId\"));\nexport type OperationId = typeof OperationId.Type;\n\n// ---------------------------------------------------------------------------\n// HTTP\n// ---------------------------------------------------------------------------\n\nexport const HttpMethod = Schema.Literals([\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"patch\",\n \"head\",\n \"options\",\n \"trace\",\n]);\nexport type HttpMethod = typeof HttpMethod.Type;\n\nexport const ParameterLocation = Schema.Literals([\"path\", \"query\", \"header\", \"cookie\"]);\nexport type ParameterLocation = typeof ParameterLocation.Type;\n\n// ---------------------------------------------------------------------------\n// Extracted operation\n// ---------------------------------------------------------------------------\n\nexport const OperationParameter = Schema.Struct({\n name: Schema.String,\n location: ParameterLocation,\n required: Schema.Boolean,\n schema: Schema.OptionFromOptional(Schema.Unknown),\n style: Schema.OptionFromOptional(Schema.String),\n explode: Schema.OptionFromOptional(Schema.Boolean),\n allowReserved: Schema.OptionFromOptional(Schema.Boolean),\n description: Schema.OptionFromOptional(Schema.String),\n});\nexport type OperationParameter = typeof OperationParameter.Type;\n\n/**\n * OpenAPI 3.x `Encoding Object` (§4.8.15). Declared per-property inside a\n * multipart/form-data or application/x-www-form-urlencoded request body.\n *\n * - `contentType` — for multipart, overrides the per-part `Content-Type`\n * header (e.g. `application/json` for a JSON-encoded metadata part).\n * - `style` / `explode` / `allowReserved` — for form-urlencoded, control\n * array / object serialization the same way parameter-level style does.\n */\nexport const EncodingObject = Schema.Struct({\n contentType: Schema.OptionFromOptional(Schema.String),\n style: Schema.OptionFromOptional(Schema.String),\n explode: Schema.OptionFromOptional(Schema.Boolean),\n allowReserved: Schema.OptionFromOptional(Schema.Boolean),\n});\nexport type EncodingObject = typeof EncodingObject.Type;\n\nexport const MediaBinding = Schema.Struct({\n contentType: Schema.String,\n schema: Schema.OptionFromOptional(Schema.Unknown),\n encoding: Schema.OptionFromOptional(Schema.Record(Schema.String, EncodingObject)),\n});\nexport type MediaBinding = typeof MediaBinding.Type;\n\nexport const OperationRequestBody = Schema.Struct({\n required: Schema.Boolean,\n /** Default media type — first declared in spec order (not JSON-first).\n * Used when the caller does not override via the tool's `contentType` arg. */\n contentType: Schema.String,\n /** Schema of the default media type. Kept for backward compat with stored\n * bindings from before `contents` was added. */\n schema: Schema.OptionFromOptional(Schema.Unknown),\n /** All declared media types in spec order. Populated by `extract.ts`\n * going forward; older persisted bindings may have this unset and will\n * fall back to `{contentType, schema}`. */\n contents: Schema.OptionFromOptional(Schema.Array(MediaBinding)),\n});\nexport type OperationRequestBody = typeof OperationRequestBody.Type;\n\nexport const ServerVariable = Schema.Struct({\n default: Schema.String,\n enum: Schema.OptionFromOptional(Schema.Array(Schema.String)),\n description: Schema.OptionFromOptional(Schema.String),\n});\nexport type ServerVariable = typeof ServerVariable.Type;\n\nexport const ServerInfo = Schema.Struct({\n url: Schema.String,\n description: Schema.OptionFromOptional(Schema.String),\n variables: Schema.OptionFromOptional(Schema.Record(Schema.String, ServerVariable)),\n});\nexport type ServerInfo = typeof ServerInfo.Type;\n\nexport const ExtractedOperation = Schema.Struct({\n operationId: OperationId,\n toolPath: Schema.OptionFromOptional(Schema.String),\n method: HttpMethod,\n servers: Schema.Array(ServerInfo),\n pathTemplate: Schema.String,\n summary: Schema.OptionFromOptional(Schema.String),\n description: Schema.OptionFromOptional(Schema.String),\n tags: Schema.Array(Schema.String),\n parameters: Schema.Array(OperationParameter),\n requestBody: Schema.OptionFromOptional(OperationRequestBody),\n inputSchema: Schema.OptionFromOptional(Schema.Unknown),\n outputSchema: Schema.OptionFromOptional(Schema.Unknown),\n deprecated: Schema.Boolean,\n});\nexport type ExtractedOperation = typeof ExtractedOperation.Type;\n\nexport const ExtractionResult = Schema.Struct({\n title: Schema.OptionFromOptional(Schema.String),\n version: Schema.OptionFromOptional(Schema.String),\n servers: Schema.Array(ServerInfo),\n operations: Schema.Array(ExtractedOperation),\n});\nexport type ExtractionResult = typeof ExtractionResult.Type;\n\n// ---------------------------------------------------------------------------\n// Operation binding — minimal invocation data (no schemas/metadata)\n// ---------------------------------------------------------------------------\n\nexport const OperationBinding = Schema.Struct({\n method: HttpMethod,\n servers: Schema.optional(Schema.Array(ServerInfo)),\n pathTemplate: Schema.String,\n parameters: Schema.Array(OperationParameter),\n requestBody: Schema.OptionFromOptional(OperationRequestBody),\n});\nexport type OperationBinding = typeof OperationBinding.Type;\n\n// ---------------------------------------------------------------------------\n// Invocation\n// ---------------------------------------------------------------------------\n\nexport const InvocationResult = Schema.Struct({\n status: Schema.Number,\n headers: Schema.Record(Schema.String, Schema.String),\n data: Schema.NullOr(Schema.Unknown),\n error: Schema.NullOr(Schema.Unknown),\n});\nexport type InvocationResult = typeof InvocationResult.Type;\n","import { Effect, Option } from \"effect\";\n\nimport { 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 type ServerObject,\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((p) =>\n OperationParameter.make({\n name: p.name,\n location: p.in as ParameterLocation,\n required: p.in === \"path\" ? true : p.required === true,\n schema: Option.fromNullishOr(p.schema),\n style: Option.fromNullishOr(p.style),\n explode: Option.fromNullishOr(p.explode),\n allowReserved: Option.fromNullishOr(\"allowReserved\" in p ? p.allowReserved : undefined),\n description: Option.fromNullishOr(p.description),\n }),\n );\n};\n\n// ---------------------------------------------------------------------------\n// Request body extraction\n// ---------------------------------------------------------------------------\n\nconst buildEncodingRecord = (\n encoding: Record<string, unknown> | undefined,\n): Record<string, EncodingObject> | undefined => {\n if (!encoding) return undefined;\n const out: Record<string, EncodingObject> = {};\n for (const [prop, raw] of Object.entries(encoding)) {\n if (typeof raw !== \"object\" || raw === null) continue;\n const e = raw as {\n contentType?: string;\n style?: string;\n explode?: boolean;\n allowReserved?: boolean;\n };\n out[prop] = EncodingObject.make({\n contentType: Option.fromNullishOr(e.contentType),\n style: Option.fromNullishOr(e.style),\n explode: Option.fromNullishOr(e.explode),\n allowReserved: Option.fromNullishOr(e.allowReserved),\n });\n }\n return Object.keys(out).length > 0 ? out : undefined;\n};\n\nconst extractRequestBody = (\n operation: OperationObject,\n r: DocResolver,\n): OperationRequestBody | undefined => {\n if (!operation.requestBody) return undefined;\n\n const body = r.resolve<RequestBodyObject>(operation.requestBody);\n if (!body) return undefined;\n\n const contents = declaredContents(body.content).map(({ mediaType, media }) =>\n MediaBinding.make({\n contentType: mediaType,\n schema: Option.fromNullishOr(media.schema),\n encoding: Option.fromNullishOr(\n buildEncodingRecord((media as { encoding?: Record<string, unknown> }).encoding),\n ),\n }),\n );\n if (contents.length === 0) return undefined;\n\n // Default = first declared (spec author's preferred order). Callers can\n // override at invoke time with a `contentType` arg.\n const defaultContent = contents[0]!;\n\n return OperationRequestBody.make({\n required: body.required === true,\n contentType: defaultContent.contentType,\n schema: defaultContent.schema,\n contents: Option.some(contents),\n });\n};\n\n// ---------------------------------------------------------------------------\n// Response schema extraction\n// ---------------------------------------------------------------------------\n\nconst 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\n// Optional `server` input — host selection + server-URL variables. Undefined\n// when there's nothing to configure (a single server with no variables).\nconst buildServerInputProperty = (\n servers: readonly ServerInfo[],\n): Record<string, unknown> | undefined => {\n const variableDefs: Record<string, ServerVariable> = {};\n for (const server of servers) {\n for (const [name, v] of Object.entries(Option.getOrUndefined(server.variables) ?? {})) {\n if (!(name in variableDefs)) variableDefs[name] = v;\n }\n }\n const hasMultiple = servers.length > 1;\n const variableNames = Object.keys(variableDefs);\n if (!hasMultiple && variableNames.length === 0) return undefined;\n\n const properties: Record<string, unknown> = {};\n if (hasMultiple) {\n properties.url = {\n type: \"string\",\n enum: servers.map((server) => server.url),\n default: servers[0]!.url,\n description: \"Which of the spec's servers to send the request to.\",\n };\n }\n if (variableNames.length > 0) {\n properties.variables = {\n type: \"object\",\n additionalProperties: false,\n properties: Object.fromEntries(\n Object.entries(variableDefs).map(([name, v]) => [\n name,\n {\n type: \"string\",\n default: v.default,\n ...(Option.isSome(v.enum) ? { enum: v.enum.value } : {}),\n ...(Option.isSome(v.description) ? { description: v.description.value } : {}),\n },\n ]),\n ),\n description: \"Values for the server URL `{variables}`; spec defaults apply when omitted.\",\n };\n }\n return {\n type: \"object\",\n additionalProperties: false,\n properties,\n description: \"Optional host selection and server-URL variables for this request.\",\n };\n};\n\nconst buildInputSchema = (\n parameters: readonly OperationParameter[],\n requestBody: OperationRequestBody | undefined,\n servers: readonly ServerInfo[],\n): Record<string, unknown> | undefined => {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n\n for (const param of parameters) {\n properties[param.name] = Option.getOrElse(param.schema, () => ({ type: \"string\" }));\n if (param.required) required.push(param.name);\n }\n\n // A path/query parameter named `server` takes precedence over the host input.\n const serverProperty = buildServerInputProperty(servers);\n if (serverProperty && !(\"server\" in properties)) properties.server = serverProperty;\n\n if (requestBody) {\n 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\nconst explicitToolPath = (operation: OperationObject): string | undefined => {\n const value = (operation as Record<string, unknown>)[\"x-executor-toolPath\"];\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n};\n\nconst explicitPathTemplate = (operation: OperationObject): string | undefined => {\n const value = (operation as Record<string, unknown>)[\"x-executor-pathTemplate\"];\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n};\n\n// ---------------------------------------------------------------------------\n// Server extraction\n// ---------------------------------------------------------------------------\n\nconst extractServerList = (servers: readonly ServerObject[] | undefined): ServerInfo[] =>\n (servers ?? []).flatMap((server) => {\n if (!server.url) return [];\n const serverVariables = server.variables as\n | Record<\n string,\n {\n readonly default?: string;\n readonly enum?: readonly string[];\n readonly description?: string;\n }\n >\n | undefined;\n const vars = serverVariables\n ? Object.fromEntries(\n Object.entries(serverVariables).flatMap(([name, v]) => {\n if (v.default === undefined || v.default === null) return [];\n const enumValues = Array.isArray(v.enum)\n ? v.enum.filter((x): x is string => typeof x === \"string\")\n : undefined;\n return [\n [\n name,\n ServerVariable.make({\n default: String(v.default),\n enum:\n enumValues && enumValues.length > 0 ? Option.some(enumValues) : Option.none(),\n description: Option.fromNullishOr(v.description),\n }),\n ],\n ];\n }),\n )\n : undefined;\n return [\n ServerInfo.make({\n url: server.url,\n description: Option.fromNullishOr(server.description),\n variables: vars && Object.keys(vars).length > 0 ? Option.some(vars) : Option.none(),\n }),\n ];\n });\n\nconst extractServers = (doc: ParsedDocument): ServerInfo[] => extractServerList(doc.servers);\n\nconst operationServers = (\n pathItem: PathItemObject,\n operation: OperationObject,\n docServers: readonly ServerInfo[],\n): readonly ServerInfo[] => {\n const operationLevel = extractServerList(operation.servers);\n if (operationLevel.length > 0) return operationLevel;\n const pathLevel = extractServerList(pathItem.servers);\n if (pathLevel.length > 0) return pathLevel;\n return docServers;\n};\n\n// ---------------------------------------------------------------------------\n// Main extraction\n// ---------------------------------------------------------------------------\n\n/** Extract all operations from a bundled OpenAPI 3.x document */\nexport const extract = Effect.fn(\"OpenApi.extract\")(function* (doc: ParsedDocument) {\n const paths = doc.paths;\n if (!paths) {\n return yield* new OpenApiExtractionError({\n message: \"OpenAPI document has no paths defined\",\n });\n }\n\n const r = new DocResolver(doc);\n const docServers = extractServers(doc);\n const operations: ExtractedOperation[] = [];\n\n for (const [pathTemplate, pathItem] of Object.entries(paths).sort(([a], [b]) =>\n a.localeCompare(b),\n )) {\n if (!pathItem) continue;\n\n for (const method of HTTP_METHODS) {\n const operation = pathItem[method];\n if (!operation) continue;\n\n const parameters = extractParameters(pathItem, operation, r);\n const requestBody = extractRequestBody(operation, r);\n const servers = operationServers(pathItem, operation, docServers);\n const inputSchema = buildInputSchema(parameters, requestBody, servers);\n const outputSchema = extractOutputSchema(operation, r);\n const tags = (operation.tags ?? []).filter((t) => t.trim().length > 0);\n const operationPathTemplate = explicitPathTemplate(operation) ?? pathTemplate;\n\n operations.push(\n ExtractedOperation.make({\n operationId: OperationId.make(deriveOperationId(method, pathTemplate, operation)),\n toolPath: Option.fromNullishOr(explicitToolPath(operation)),\n method,\n servers,\n pathTemplate: operationPathTemplate,\n summary: Option.fromNullishOr(operation.summary),\n description: Option.fromNullishOr(operation.description),\n tags,\n parameters,\n requestBody: Option.fromNullishOr(requestBody),\n inputSchema: Option.fromNullishOr(inputSchema),\n outputSchema: Option.fromNullishOr(outputSchema),\n deprecated: operation.deprecated === true,\n }),\n );\n }\n }\n\n return ExtractionResult.make({\n title: Option.fromNullishOr(doc.info?.title),\n version: Option.fromNullishOr(doc.info?.version),\n servers: docServers,\n operations,\n });\n});\n","import { Effect, Option, Predicate } from \"effect\";\nimport { Schema } from \"effect\";\n\nimport { parse, resolveSpecText, type ParsedDocument } from \"./parse\";\nimport { extract } from \"./extract\";\nimport { DocResolver } from \"./openapi-utils\";\nimport { HttpMethod, ServerInfo, type ExtractionResult } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// OAuth 2.0 flows — one entry per supported grant type\n// ---------------------------------------------------------------------------\n\n/** Scopes declared by a flow: `{ scopeName: description }` */\nconst OAuth2Scopes = Schema.Record(Schema.String, Schema.String);\nconst SecuritySchemeType = Schema.Literals([\"http\", \"apiKey\", \"oauth2\", \"openIdConnect\"]);\ntype SecuritySchemeType = typeof SecuritySchemeType.Type;\n\nconst decodeSecuritySchemeType = Schema.decodeUnknownOption(SecuritySchemeType);\n\nexport const OAuth2AuthorizationCodeFlow = Schema.Struct({\n authorizationUrl: Schema.String,\n tokenUrl: Schema.String,\n refreshUrl: Schema.OptionFromOptional(Schema.String),\n scopes: OAuth2Scopes,\n});\nexport type OAuth2AuthorizationCodeFlow = typeof OAuth2AuthorizationCodeFlow.Type;\n\nexport const OAuth2ClientCredentialsFlow = Schema.Struct({\n tokenUrl: Schema.String,\n refreshUrl: Schema.OptionFromOptional(Schema.String),\n scopes: OAuth2Scopes,\n});\nexport type OAuth2ClientCredentialsFlow = typeof OAuth2ClientCredentialsFlow.Type;\n\nexport const OAuth2Flows = Schema.Struct({\n authorizationCode: Schema.OptionFromOptional(OAuth2AuthorizationCodeFlow),\n clientCredentials: Schema.OptionFromOptional(OAuth2ClientCredentialsFlow),\n});\nexport type OAuth2Flows = typeof OAuth2Flows.Type;\n\n// ---------------------------------------------------------------------------\n// Security scheme — what the spec declares it needs\n// ---------------------------------------------------------------------------\n\nexport const SecurityScheme = Schema.Struct({\n /** Key name in components.securitySchemes (e.g. \"api_token\") */\n name: Schema.String,\n /** OpenAPI security scheme type */\n type: SecuritySchemeType,\n /** For type: \"http\" — e.g. \"bearer\", \"basic\" */\n scheme: Schema.OptionFromOptional(Schema.String),\n /** For type: \"http\" with scheme \"bearer\" — e.g. \"JWT\" */\n bearerFormat: Schema.OptionFromOptional(Schema.String),\n /** For type: \"apiKey\" — where the key goes */\n in: Schema.OptionFromOptional(Schema.Literals([\"header\", \"query\", \"cookie\"])),\n /** For type: \"apiKey\" — the header/query/cookie name */\n headerName: Schema.OptionFromOptional(Schema.String),\n description: Schema.OptionFromOptional(Schema.String),\n /** For type: \"oauth2\" — declared flows (authorizationCode / clientCredentials only; implicit and password are deprecated). */\n flows: Schema.OptionFromOptional(OAuth2Flows),\n /** For type: \"openIdConnect\" — the discovery URL. */\n openIdConnectUrl: Schema.OptionFromOptional(Schema.String),\n});\nexport type SecurityScheme = typeof SecurityScheme.Type;\n\n// ---------------------------------------------------------------------------\n// Auth strategy — a valid combination of security schemes\n// ---------------------------------------------------------------------------\n\nexport const AuthStrategy = Schema.Struct({\n /** The security schemes required together for this strategy */\n schemes: Schema.Array(Schema.String),\n});\nexport type AuthStrategy = typeof AuthStrategy.Type;\n\n// ---------------------------------------------------------------------------\n// Header preset — derived from an auth strategy\n// ---------------------------------------------------------------------------\n\nexport const HeaderPreset = Schema.Struct({\n /** Human-readable label for the UI (e.g. \"Bearer Token\", \"API Key + Email\") */\n label: Schema.String,\n /** Headers this strategy needs. Value is null when the user must provide it. */\n headers: Schema.Record(Schema.String, Schema.NullOr(Schema.String)),\n /** Which headers should be stored as secrets */\n secretHeaders: Schema.Array(Schema.String),\n});\nexport type HeaderPreset = typeof HeaderPreset.Type;\n\n// ---------------------------------------------------------------------------\n// OAuth2 preset — derived from an oauth2 security scheme + a flow choice\n// ---------------------------------------------------------------------------\n\nexport const OAuth2Preset = Schema.Struct({\n /** Human-readable label for the UI (e.g. \"OAuth2 (Authorization Code) — oauth_app\") */\n label: Schema.String,\n /** The source security scheme this preset came from (components.securitySchemes key). */\n securitySchemeName: Schema.String,\n /** Which OAuth2 flow this preset uses. */\n flow: Schema.Literals([\"authorizationCode\", \"clientCredentials\"]),\n /** For authorizationCode: user-agent redirect URL (from the spec). */\n authorizationUrl: Schema.OptionFromOptional(Schema.String),\n /** Token endpoint to exchange the code / refresh. */\n tokenUrl: Schema.String,\n /** Optional refresh endpoint if the spec declares one separately. */\n refreshUrl: Schema.OptionFromOptional(Schema.String),\n /** Declared scopes for this flow: `{ scope: description }`. */\n scopes: Schema.Record(Schema.String, Schema.String),\n /** Identity scopes to request alongside API scopes. `\"auto\"` discovers standard OIDC scopes. */\n identityScopes: Schema.Union([\n Schema.Literal(\"auto\"),\n Schema.Literal(false),\n Schema.Array(Schema.String),\n ]),\n});\nexport type OAuth2Preset = typeof OAuth2Preset.Type;\n\n// ---------------------------------------------------------------------------\n// Preview operation — lightweight shape for the add-source UI list\n// ---------------------------------------------------------------------------\n\nexport const PreviewOperation = Schema.Struct({\n operationId: Schema.String,\n method: HttpMethod,\n path: Schema.String,\n summary: Schema.OptionFromOptional(Schema.String),\n tags: Schema.Array(Schema.String),\n deprecated: Schema.Boolean,\n});\nexport type PreviewOperation = typeof PreviewOperation.Type;\n\n// ---------------------------------------------------------------------------\n// Spec preview — everything the frontend needs\n// ---------------------------------------------------------------------------\n\nexport const SpecPreview = Schema.Struct({\n title: Schema.OptionFromOptional(Schema.String),\n version: Schema.OptionFromOptional(Schema.String),\n /** Reuses ServerInfo from extraction */\n servers: Schema.Array(ServerInfo),\n operationCount: Schema.Number,\n /** Lightweight operation list for the add-source UI */\n operations: Schema.Array(PreviewOperation),\n tags: Schema.Array(Schema.String),\n securitySchemes: Schema.Array(SecurityScheme),\n /** Valid auth strategies (each is a set of schemes used together) */\n authStrategies: Schema.Array(AuthStrategy),\n /** Pre-built header presets derived from auth strategies */\n headerPresets: Schema.Array(HeaderPreset),\n /** OAuth2 presets — one per (oauth2 scheme × supported flow) combination */\n oauth2Presets: Schema.Array(OAuth2Preset),\n});\nexport type SpecPreview = typeof SpecPreview.Type;\n\n// ---------------------------------------------------------------------------\n// Security scheme extraction\n// ---------------------------------------------------------------------------\n\nconst stringRecord = (value: unknown): Record<string, string> => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (typeof v === \"string\") out[k] = v;\n }\n return out;\n};\n\nconst extractFlows = (rawFlows: unknown): Option.Option<OAuth2Flows> => {\n if (!rawFlows || typeof rawFlows !== \"object\") return Option.none();\n const flows = rawFlows as Record<string, unknown>;\n\n const parseFlow = <K extends \"authorizationCode\" | \"clientCredentials\">(key: K): unknown =>\n flows[key];\n\n let authorizationCode: Option.Option<OAuth2AuthorizationCodeFlow> = Option.none();\n const authCodeRaw = parseFlow(\"authorizationCode\");\n if (authCodeRaw && typeof authCodeRaw === \"object\") {\n const f = authCodeRaw as Record<string, unknown>;\n const authUrl = typeof f.authorizationUrl === \"string\" ? f.authorizationUrl : null;\n const tokenUrl = typeof f.tokenUrl === \"string\" ? f.tokenUrl : null;\n if (authUrl && tokenUrl) {\n authorizationCode = Option.some(\n OAuth2AuthorizationCodeFlow.make({\n authorizationUrl: authUrl,\n tokenUrl,\n refreshUrl: Option.fromNullishOr(\n typeof f.refreshUrl === \"string\" ? f.refreshUrl : undefined,\n ),\n scopes: stringRecord(f.scopes),\n }),\n );\n }\n }\n\n let clientCredentials: Option.Option<OAuth2ClientCredentialsFlow> = Option.none();\n const ccRaw = parseFlow(\"clientCredentials\");\n if (ccRaw && typeof ccRaw === \"object\") {\n const f = ccRaw as Record<string, unknown>;\n const tokenUrl = typeof f.tokenUrl === \"string\" ? f.tokenUrl : null;\n if (tokenUrl) {\n clientCredentials = Option.some(\n OAuth2ClientCredentialsFlow.make({\n tokenUrl,\n refreshUrl: Option.fromNullishOr(\n typeof f.refreshUrl === \"string\" ? f.refreshUrl : undefined,\n ),\n scopes: stringRecord(f.scopes),\n }),\n );\n }\n }\n\n if (Option.isNone(authorizationCode) && Option.isNone(clientCredentials)) {\n return Option.none();\n }\n return Option.some(OAuth2Flows.make({ authorizationCode, clientCredentials }));\n};\n\nconst extractSecuritySchemes = (\n rawSchemes: Record<string, unknown>,\n resolver: DocResolver,\n): SecurityScheme[] =>\n Object.entries(rawSchemes).flatMap(([name, schemeOrRef]) => {\n if (!schemeOrRef || typeof schemeOrRef !== \"object\") return [];\n // Resolve $ref so schemes defined via `$ref` aren't silently dropped.\n const resolved = resolver.resolve<Record<string, unknown>>(\n schemeOrRef as Record<string, unknown>,\n );\n if (!resolved || typeof resolved !== \"object\") return [];\n const scheme = resolved;\n\n const type = decodeSecuritySchemeType(scheme.type);\n if (Option.isNone(type)) return [];\n const schemeType = type.value;\n\n return [\n SecurityScheme.make({\n name,\n type: schemeType,\n scheme: Option.fromNullishOr(scheme.scheme as string | undefined),\n bearerFormat: Option.fromNullishOr(scheme.bearerFormat as string | undefined),\n in: Option.fromNullishOr(scheme.in as \"header\" | \"query\" | \"cookie\" | undefined),\n headerName: Option.fromNullishOr(scheme.name as string | undefined),\n description: Option.fromNullishOr(scheme.description as string | undefined),\n flows: schemeType === \"oauth2\" ? extractFlows(scheme.flows) : Option.none(),\n openIdConnectUrl: Option.fromNullishOr(scheme.openIdConnectUrl as string | undefined),\n }),\n ];\n });\n\n// ---------------------------------------------------------------------------\n// Header preset builder\n// ---------------------------------------------------------------------------\n\nconst buildHeaderPresets = (\n schemes: readonly SecurityScheme[],\n strategies: readonly AuthStrategy[],\n): HeaderPreset[] => {\n const schemeMap = new Map(schemes.map((s) => [s.name, s]));\n\n return strategies.flatMap((strategy) => {\n const resolved = strategy.schemes\n .map((name) => schemeMap.get(name))\n .filter(Predicate.isNotUndefined);\n\n if (resolved.length === 0) return [];\n\n const headers: Record<string, string | null> = {};\n const secretHeaders: string[] = [];\n const labelParts: string[] = [];\n\n for (const scheme of resolved) {\n if (scheme.type === \"http\" && Option.getOrElse(scheme.scheme, () => \"\") === \"bearer\") {\n headers[\"Authorization\"] = null;\n secretHeaders.push(\"Authorization\");\n labelParts.push(\"Bearer Token\");\n } else if (scheme.type === \"http\" && Option.getOrElse(scheme.scheme, () => \"\") === \"basic\") {\n headers[\"Authorization\"] = null;\n secretHeaders.push(\"Authorization\");\n labelParts.push(\"Basic Auth\");\n } else if (scheme.type === \"apiKey\" && Option.getOrElse(scheme.in, () => \"\") === \"header\") {\n const headerName = Option.getOrElse(scheme.headerName, () => scheme.name);\n headers[headerName] = null;\n secretHeaders.push(headerName);\n labelParts.push(scheme.name);\n } else if (scheme.type === \"apiKey\") {\n labelParts.push(`${scheme.name} (${Option.getOrElse(scheme.in, () => \"unknown\")})`);\n } else if (scheme.type === \"oauth2\" || scheme.type === \"openIdConnect\") {\n return [];\n } else {\n labelParts.push(scheme.name);\n }\n }\n\n if (Object.keys(headers).length === 0 && resolved.length > 0) {\n return [\n HeaderPreset.make({\n label: labelParts.join(\" + \"),\n headers: {},\n secretHeaders: [],\n }),\n ];\n }\n\n return [\n HeaderPreset.make({\n label: labelParts.join(\" + \"),\n headers,\n secretHeaders,\n }),\n ];\n });\n};\n\n// ---------------------------------------------------------------------------\n// OAuth2 preset builder\n// ---------------------------------------------------------------------------\n\nconst buildOAuth2Presets = (schemes: readonly SecurityScheme[]): OAuth2Preset[] => {\n const presets: OAuth2Preset[] = [];\n for (const scheme of schemes) {\n if (scheme.type !== \"oauth2\") continue;\n if (Option.isNone(scheme.flows)) continue;\n const flows = scheme.flows.value;\n\n if (Option.isSome(flows.authorizationCode)) {\n const flow = flows.authorizationCode.value;\n presets.push(\n OAuth2Preset.make({\n label: `OAuth2 Authorization Code · ${scheme.name}`,\n securitySchemeName: scheme.name,\n flow: \"authorizationCode\",\n authorizationUrl: Option.some(flow.authorizationUrl),\n tokenUrl: flow.tokenUrl,\n refreshUrl: flow.refreshUrl,\n scopes: flow.scopes,\n identityScopes: \"auto\",\n }),\n );\n }\n\n if (Option.isSome(flows.clientCredentials)) {\n const flow = flows.clientCredentials.value;\n presets.push(\n OAuth2Preset.make({\n label: `OAuth2 Client Credentials · ${scheme.name}`,\n securitySchemeName: scheme.name,\n flow: \"clientCredentials\",\n authorizationUrl: Option.none(),\n tokenUrl: flow.tokenUrl,\n refreshUrl: flow.refreshUrl,\n scopes: flow.scopes,\n identityScopes: false,\n }),\n );\n }\n }\n return presets;\n};\n\n// ---------------------------------------------------------------------------\n// Collect unique tags from extraction result\n// ---------------------------------------------------------------------------\n\nconst collectTags = (result: ExtractionResult): string[] => {\n const tagSet = new Set<string>();\n for (const op of result.operations) {\n for (const tag of op.tags) tagSet.add(tag);\n }\n return [...tagSet].sort();\n};\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/** Preview already-resolved spec text — extract metadata without registering\n * anything and without any HTTP dependency. */\nexport const previewSpecText = Effect.fn(\"OpenApi.previewSpecText\")(function* (specText: string) {\n const doc: ParsedDocument = yield* parse(specText);\n const result = yield* extract(doc);\n\n const resolver = new DocResolver(doc);\n const securitySchemes = extractSecuritySchemes(doc.components?.securitySchemes ?? {}, resolver);\n\n const rawSecurity = (doc.security ?? []) as Array<Record<string, unknown>>;\n const declaredStrategies = rawSecurity.map((entry) =>\n AuthStrategy.make({ schemes: Object.keys(entry) }),\n );\n // Fall back to one strategy per scheme when the spec only declares schemes\n // under components (e.g. Sentry) so the user still sees auth options.\n const authStrategies =\n declaredStrategies.length > 0\n ? declaredStrategies\n : securitySchemes.map((scheme) => AuthStrategy.make({ schemes: [scheme.name] }));\n\n return SpecPreview.make({\n title: result.title,\n version: result.version,\n servers: result.servers,\n operationCount: result.operations.length,\n operations: result.operations.map((op) =>\n PreviewOperation.make({\n operationId: op.operationId,\n method: op.method,\n path: op.pathTemplate,\n summary: op.summary,\n tags: op.tags,\n deprecated: op.deprecated,\n }),\n ),\n tags: collectTags(result),\n securitySchemes,\n authStrategies,\n headerPresets: buildHeaderPresets(securitySchemes, authStrategies),\n oauth2Presets: buildOAuth2Presets(securitySchemes),\n });\n});\n\n/** Preview an OpenAPI spec — extract metadata without registering anything.\n * Accepts either a URL or raw JSON/YAML text. */\nexport const previewSpec = Effect.fn(\"OpenApi.previewSpec\")(function* (input: string) {\n const specText = yield* resolveSpecText(input);\n return yield* previewSpecText(specText);\n});\n"],"mappings":";AAAA,SAAS,MAAM,cAAc;AAWtB,IAAM,oBAAN,cAAgC,OAAO,iBAAoC;AAAA,EAChF;AAAA,EACA;AAAA,IACE,SAAS,OAAO;AAAA,EAClB;AAAA,EACA,EAAE,eAAe,IAAI;AACvB,EAAE;AAAC;AAEI,IAAM,yBAAN,cAAqC,OAAO,iBAAyC;AAAA,EAC1F;AAAA,EACA;AAAA,IACE,SAAS,OAAO;AAAA,EAClB;AAAA,EACA,EAAE,eAAe,IAAI;AACvB,EAAE;AAAC;AAEI,IAAM,yBAAN,cAAqC,KAAK,YAAY,wBAAwB,EAIlF;AAAC;AAEG,IAAM,oBAAN,cAAgC,OAAO,iBAAoC;AAAA,EAChF;AAAA,EACA;AAAA,IACE,SAAS,OAAO;AAAA,EAClB;AAAA,EACA,EAAE,eAAe,IAAI;AACvB,EAAE;AAAC;AAOI,IAAM,2BAAN,cAAuC,KAAK,YAAY,0BAA0B,EAWtF;AAAC;;;ACxDJ,SAAS,UAAU,QAAQ,UAAAA,eAAc;AACzC,SAAS,YAAY,yBAAyB;AAC9C,OAAO,UAAU;AAYjB,IAAM,kCAAN,cAA8C,uBAAuB;AAAC;AAQ/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,GAAG;AAC1E,eAAW,aAAa,IAAI,MAAM,KAAK;AAAA,EACzC;AACA,MAAI,UAAU,kBAAkB,IAAI,WAAW,SAAS,CAAC,EAAE;AAAA,IACzD,kBAAkB,UAAU,UAAU,oDAAoD;AAAA,EAC5F;AACA,aAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,aAAa,WAAW,CAAC,C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G,QAAQ;AAE9F,QAAM,cAAe,IAAI,YAAY,CAAC;AACtC,QAAM,qBAAqB,YAAY;AAAA,IAAI,CAAC,UAC1C,aAAa,KAAK,EAAE,SAAS,OAAO,KAAK,KAAK,EAAE,CAAC;AAAA,EACnD;AAGA,QAAM,iBACJ,mBAAmB,SAAS,IACxB,qBACA,gBAAgB,IAAI,CAAC,WAAW,aAAa,KAAK,EAAE,SAAS,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC;AAEnF,SAAO,YAAY,KAAK;AAAA,IACtB,OAAO,OAAO;AAAA,IACd,SAAS,OAAO;AAAA,IAChB,SAAS,OAAO;AAAA,IAChB,gBAAgB,OAAO,WAAW;AAAA,IAClC,YAAY,OAAO,WAAW;AAAA,MAAI,CAAC,OACjC,iBAAiB,KAAK;AAAA,QACpB,aAAa,GAAG;AAAA,QAChB,QAAQ,GAAG;AAAA,QACX,MAAM,GAAG;AAAA,QACT,SAAS,GAAG;AAAA,QACZ,MAAM,GAAG;AAAA,QACT,YAAY,GAAG;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,IACA,MAAM,YAAY,MAAM;AAAA,IACxB;AAAA,IACA;AAAA,IACA,eAAe,mBAAmB,iBAAiB,cAAc;AAAA,IACjE,eAAe,mBAAmB,eAAe;AAAA,EACnD,CAAC;AACH,CAAC;AAIM,IAAM,cAAcA,QAAO,GAAG,qBAAqB,EAAE,WAAW,OAAe;AACpF,QAAM,WAAW,OAAO,gBAAgB,KAAK;AAC7C,SAAO,OAAO,gBAAgB,QAAQ;AACxC,CAAC;","names":["Schema","Schema","Schema","Effect","Effect","Effect","Option","Schema","Schema","Option","Effect"]}
@@ -1,6 +1,7 @@
1
1
  import {
2
- OpenApiParseError
3
- } from "./chunk-YVRI7KRC.js";
2
+ OpenApiParseError,
3
+ resolveServerUrl
4
+ } from "./chunk-C3IJX4AN.js";
4
5
 
5
6
  // src/sdk/google-discovery.ts
6
7
  import { Effect, Option, Predicate, Schema, SchemaGetter } from "effect";
@@ -410,7 +411,7 @@ var googleOauthTemplate = (scopes) => (
410
411
  [
411
412
  {
412
413
  slug: AuthTemplateSlug.make(GOOGLE_OAUTH_SECURITY_SCHEME),
413
- type: "oauth",
414
+ kind: "oauth2",
414
415
  authorizationUrl: GOOGLE_OAUTH_AUTHORIZATION_URL,
415
416
  tokenUrl: GOOGLE_OAUTH_TOKEN_URL,
416
417
  scopes: Object.keys(scopes)
@@ -613,11 +614,99 @@ var convertGoogleDiscoveryBundleToOpenApi = Effect.fn(
613
614
  };
614
615
  });
615
616
 
617
+ // src/sdk/derive-auth.ts
618
+ import * as Option2 from "effect/Option";
619
+ import { AuthTemplateSlug as AuthTemplateSlug2 } from "@executor-js/sdk/shared";
620
+ function resolveOAuthUrl(url, baseUrl) {
621
+ if (!url) return url;
622
+ try {
623
+ new URL(url);
624
+ return url;
625
+ } catch {
626
+ if (!baseUrl) return url;
627
+ try {
628
+ return new URL(url, baseUrl).toString();
629
+ } catch {
630
+ return url;
631
+ }
632
+ }
633
+ }
634
+ var standardOidcIdentityScopes = ["openid", "email", "profile"];
635
+ var identityScopesForPreset = (identityScopes) => {
636
+ if (identityScopes === false) return [];
637
+ return identityScopes === "auto" ? standardOidcIdentityScopes : identityScopes;
638
+ };
639
+ var resolvedOAuthScopes = (apiScopes, identityScopes) => {
640
+ const merged = new Set(apiScopes);
641
+ for (const scope of identityScopesForPreset(identityScopes)) merged.add(scope);
642
+ return [...merged];
643
+ };
644
+ var headerPrefix = (preset, headerName) => {
645
+ const label = preset.label.toLowerCase();
646
+ if (headerName.toLowerCase() === "authorization") {
647
+ if (label.includes("bearer")) return "Bearer ";
648
+ if (label.includes("basic")) return "Basic ";
649
+ }
650
+ return void 0;
651
+ };
652
+ var apiKeyTemplateFromHeaderPreset = (preset, slug) => ({
653
+ slug,
654
+ kind: "apikey",
655
+ // Every secret header shares the one credential input (the canonical
656
+ // `token`, stored as an absent placement variable).
657
+ placements: preset.secretHeaders.map((headerName) => {
658
+ const prefix = headerPrefix(preset, headerName);
659
+ return { carrier: "header", name: headerName, ...prefix ? { prefix } : {} };
660
+ })
661
+ });
662
+ var oauthTemplateFromPreset = (preset, baseUrl, slug, scopes) => ({
663
+ slug,
664
+ kind: "oauth2",
665
+ authorizationUrl: resolveOAuthUrl(
666
+ Option2.getOrElse(preset.authorizationUrl, () => ""),
667
+ baseUrl
668
+ ),
669
+ tokenUrl: resolveOAuthUrl(preset.tokenUrl, baseUrl),
670
+ scopes: [...scopes]
671
+ });
672
+ var detectedAuthenticationTemplates = (headerPresets, oauth2Presets, baseUrl) => {
673
+ const templates = [];
674
+ headerPresets.forEach((preset, index) => {
675
+ templates.push(
676
+ apiKeyTemplateFromHeaderPreset(preset, AuthTemplateSlug2.make(`apikey-${index}`))
677
+ );
678
+ });
679
+ for (const preset of oauth2Presets) {
680
+ const scopes = resolvedOAuthScopes(Object.keys(preset.scopes), preset.identityScopes);
681
+ templates.push(
682
+ oauthTemplateFromPreset(
683
+ preset,
684
+ baseUrl,
685
+ AuthTemplateSlug2.make(`oauth-${preset.securitySchemeName}`),
686
+ scopes
687
+ )
688
+ );
689
+ }
690
+ return templates;
691
+ };
692
+ var firstBaseUrlForPreview = (preview) => {
693
+ const firstServer = preview.servers[0];
694
+ return firstServer ? resolveServerUrl(firstServer.url, Option2.getOrUndefined(firstServer.variables), {}) : "";
695
+ };
696
+ var deriveAuthenticationTemplateFromPreview = (preview, baseUrl) => detectedAuthenticationTemplates(
697
+ preview.headerPresets,
698
+ preview.oauth2Presets,
699
+ baseUrl ?? firstBaseUrlForPreview(preview)
700
+ );
701
+
616
702
  export {
617
703
  compactGoogleOAuthScopes,
618
704
  isGoogleDiscoveryUrl,
619
705
  fetchGoogleDiscoveryDocument,
620
706
  convertGoogleDiscoveryToOpenApi,
621
- convertGoogleDiscoveryBundleToOpenApi
707
+ convertGoogleDiscoveryBundleToOpenApi,
708
+ detectedAuthenticationTemplates,
709
+ firstBaseUrlForPreview,
710
+ deriveAuthenticationTemplateFromPreview
622
711
  };
623
- //# sourceMappingURL=chunk-OSIFYIQP.js.map
712
+ //# sourceMappingURL=chunk-C6PH4R7Q.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sdk/google-discovery.ts","../src/sdk/google-oauth-scopes.ts","../src/sdk/derive-auth.ts"],"sourcesContent":["// Converts Google Discovery documents directly into OpenAPI 3.x. Public\n// Discovery converters currently target Swagger 2.0 or a broad conversion\n// pipeline; this adapter emits the shape Executor parses while preserving\n// Executor-specific tool ids and query semantics.\nimport { Effect, Option, Predicate, Schema, SchemaGetter } from \"effect\";\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\";\n\nimport { OpenApiParseError } from \"./errors\";\nimport { compactGoogleOAuthScopes } from \"./google-oauth-scopes\";\nimport type { SpecFetchCredentials } from \"./parse\";\nimport type { Authentication } from \"./types\";\nimport { AuthTemplateSlug } from \"@executor-js/sdk/shared\";\n\nconst DISCOVERY_SERVICE_HOST = \"https://www.googleapis.com/discovery/v1/apis\";\nconst GOOGLE_BUNDLE_BASE_URL = \"https://www.googleapis.com/\";\nconst GOOGLE_OAUTH_AUTHORIZATION_URL = \"https://accounts.google.com/o/oauth2/v2/auth\";\nconst GOOGLE_OAUTH_TOKEN_URL = \"https://oauth2.googleapis.com/token\";\nconst OPENAPI_SCHEMA_TYPES = new Set([\n \"array\",\n \"boolean\",\n \"integer\",\n \"null\",\n \"number\",\n \"object\",\n \"string\",\n]);\n\ntype JsonPrimitive = string | number | boolean | null;\ntype JsonValue = JsonPrimitive | readonly JsonValue[] | { readonly [key: string]: JsonValue };\n\ntype OpenApiSchemaObject = {\n readonly $ref?: string;\n readonly type?: \"array\" | \"boolean\" | \"integer\" | \"null\" | \"number\" | \"object\" | \"string\";\n readonly description?: string;\n readonly title?: string;\n readonly format?: string;\n readonly readOnly?: boolean;\n readonly default?: JsonValue;\n readonly enum?: readonly JsonValue[];\n readonly items?: OpenApiSchemaObject;\n readonly properties?: Record<string, OpenApiSchemaObject>;\n readonly required?: readonly string[];\n readonly additionalProperties?: boolean | OpenApiSchemaObject;\n};\n\ntype OpenApiParameterObject = {\n readonly name: string;\n readonly in: \"path\" | \"query\" | \"header\";\n readonly required: boolean;\n readonly description?: string;\n readonly schema: OpenApiSchemaObject;\n readonly style?: \"form\";\n readonly explode?: boolean;\n readonly allowReserved?: boolean;\n};\n\ntype OpenApiOperationObject = {\n readonly operationId: string;\n readonly \"x-executor-toolPath\": string;\n readonly \"x-executor-pathTemplate\"?: string;\n readonly tags?: readonly string[];\n readonly description?: string;\n readonly servers?: readonly { readonly url: string }[];\n readonly parameters: readonly OpenApiParameterObject[];\n readonly requestBody?: {\n readonly required: false;\n readonly content: {\n readonly \"application/json\": {\n readonly schema: OpenApiSchemaObject;\n };\n };\n };\n readonly responses: {\n readonly \"200\": {\n readonly description: \"Successful response\";\n readonly content: {\n readonly \"application/json\": {\n readonly schema: OpenApiSchemaObject;\n };\n };\n };\n };\n readonly security?: readonly Record<string, readonly string[]>[];\n readonly \"x-google-scopes\": readonly string[];\n};\n\ntype OpenApiDocument = {\n readonly openapi: \"3.1.0\";\n readonly info: {\n readonly title: string;\n readonly version: string;\n };\n readonly servers: readonly { readonly url: string }[];\n readonly paths: Record<string, Record<string, OpenApiOperationObject>>;\n readonly components: {\n readonly schemas: Record<string, OpenApiSchemaObject>;\n readonly securitySchemes?: Record<\n string,\n {\n readonly type: \"oauth2\";\n readonly flows: {\n readonly authorizationCode: {\n readonly authorizationUrl: string;\n readonly tokenUrl: string;\n readonly scopes: Record<string, string>;\n };\n };\n }\n >;\n };\n readonly security?: readonly Record<string, readonly string[]>[];\n readonly \"x-executor-origin\":\n | {\n readonly kind: \"googleDiscovery\";\n readonly discoveryUrl: string;\n readonly service: string;\n readonly version: string;\n }\n | {\n readonly kind: \"googleDiscoveryBundle\";\n readonly services: readonly {\n readonly discoveryUrl: string;\n readonly service: string;\n readonly version: string;\n }[];\n };\n};\n\nconst TextOption = Schema.OptionFromOptional(Schema.Trim).pipe(\n Schema.decode({\n decode: SchemaGetter.transform((value) => Option.filter(value, (text) => text.length > 0)),\n encode: SchemaGetter.transform((value) => value),\n }),\n Schema.withDecodingDefaultType(Effect.succeed(Option.none())),\n);\nconst TextArray = Schema.optional(Schema.Array(Schema.String)).pipe(\n Schema.withDecodingDefaultType(Effect.succeed([] as string[])),\n);\nconst UnknownRecord = Schema.Record(Schema.String, Schema.Unknown);\nconst UnknownRecordWithDefault = Schema.optional(UnknownRecord).pipe(\n Schema.withDecodingDefaultType(Effect.succeed({})),\n);\n\nconst DiscoveryParameter = Schema.Struct({\n type: Schema.optional(Schema.String),\n description: TextOption,\n properties: UnknownRecordWithDefault,\n items: Schema.optional(Schema.Unknown),\n additionalProperties: Schema.optional(Schema.Union([Schema.Boolean, Schema.Unknown])),\n enum: TextArray,\n format: Schema.optional(Schema.String),\n readOnly: Schema.optional(Schema.Boolean),\n default: Schema.optional(Schema.Union([Schema.String, Schema.Number, Schema.Boolean])),\n $ref: Schema.optional(Schema.String),\n location: Schema.optional(Schema.Literals([\"path\", \"query\", \"header\"])),\n required: Schema.optional(Schema.Boolean),\n repeated: Schema.optional(Schema.Boolean),\n});\ntype DiscoveryParameter = typeof DiscoveryParameter.Type;\n\nconst DiscoveryRef = Schema.Struct({\n $ref: Schema.optional(Schema.String),\n});\n\nconst DiscoveryMethod = Schema.Struct({\n id: TextOption,\n description: TextOption,\n httpMethod: Schema.optional(Schema.String),\n path: TextOption,\n parameters: UnknownRecordWithDefault,\n request: Schema.optional(DiscoveryRef),\n response: Schema.optional(DiscoveryRef),\n scopes: TextArray,\n});\ntype DiscoveryMethod = typeof DiscoveryMethod.Type;\n\nconst DiscoveryResource = Schema.Struct({\n methods: UnknownRecordWithDefault,\n resources: UnknownRecordWithDefault,\n});\n\nconst DiscoveryDocument = Schema.Struct({\n name: TextOption,\n version: TextOption,\n title: TextOption,\n rootUrl: TextOption,\n servicePath: Schema.optional(Schema.Trim).pipe(\n Schema.withDecodingDefaultType(Effect.succeed(\"\")),\n ),\n parameters: UnknownRecordWithDefault,\n methods: UnknownRecordWithDefault,\n resources: UnknownRecordWithDefault,\n schemas: UnknownRecordWithDefault,\n auth: Schema.optional(\n Schema.Struct({\n oauth2: Schema.optional(\n Schema.Struct({\n scopes: Schema.optional(\n Schema.Record(\n Schema.String,\n Schema.Struct({\n description: TextOption,\n }),\n ),\n ).pipe(Schema.withDecodingDefaultType(Effect.succeed({}))),\n }),\n ),\n }),\n ),\n});\ntype DiscoveryDocument = typeof DiscoveryDocument.Type;\n\nexport interface GoogleDiscoveryOpenApiConversion {\n readonly specText: string;\n readonly baseUrl: string;\n readonly title: string;\n readonly service: string;\n readonly version: string;\n readonly discoveryUrls?: readonly string[];\n /** The v2 oauth auth template the converted integration declares, when the\n * Discovery document advertises OAuth2 scopes. */\n readonly authenticationTemplate?: readonly Authentication[];\n}\n\nconst decodeDiscoveryDocument = Schema.decodeUnknownSync(DiscoveryDocument);\nconst decodeDiscoveryParameter = Schema.decodeUnknownSync(DiscoveryParameter);\nconst decodeDiscoveryMethod = Schema.decodeUnknownSync(DiscoveryMethod);\nconst decodeDiscoveryResource = Schema.decodeUnknownSync(DiscoveryResource);\nconst parseJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));\n\nconst normalizeDiscoveryUrl = (discoveryUrl: string): string => {\n const trimmed = discoveryUrl.trim();\n if (!URL.canParse(trimmed)) return trimmed;\n const parsed = new URL(trimmed);\n if (parsed.pathname !== \"/$discovery/rest\") return trimmed;\n const version = parsed.searchParams.get(\"version\")?.trim();\n if (!version) return trimmed;\n const host = parsed.hostname.toLowerCase();\n if (!host.endsWith(\".googleapis.com\")) return trimmed;\n const rawService = host.slice(0, -\".googleapis.com\".length);\n const service =\n rawService === \"calendar-json\"\n ? \"calendar\"\n : rawService.endsWith(\"-json\")\n ? rawService.slice(0, -5)\n : rawService;\n return service ? `${DISCOVERY_SERVICE_HOST}/${service}/${version}/rest` : trimmed;\n};\n\nexport const isGoogleDiscoveryUrl = (url: string): boolean => {\n const trimmed = url.trim();\n if (!URL.canParse(trimmed)) return false;\n const parsed = new URL(trimmed);\n const host = parsed.hostname.toLowerCase();\n if (!host.endsWith(\"googleapis.com\")) return false;\n return parsed.pathname.includes(\"/discovery/\") || parsed.pathname.includes(\"$discovery\");\n};\n\nexport const fetchGoogleDiscoveryDocument = Effect.fn(\"OpenApi.fetchGoogleDiscoveryDocument\")(\n function* (discoveryUrl: string, credentials?: SpecFetchCredentials) {\n const client = yield* HttpClient.HttpClient;\n const requestUrl = new URL(discoveryUrl);\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, */*\"),\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.mapError(\n () =>\n new OpenApiParseError({\n message: \"Failed to fetch Google Discovery document\",\n }),\n ),\n );\n if (response.status < 200 || response.status >= 300) {\n return yield* new OpenApiParseError({\n message: `Failed to fetch Google Discovery document: HTTP ${response.status}`,\n });\n }\n return yield* response.text.pipe(\n Effect.mapError(\n () =>\n new OpenApiParseError({\n message: \"Failed to read Google Discovery document body\",\n }),\n ),\n );\n },\n);\n\nconst schemaRef = (name: string) => `#/components/schemas/${name}`;\n\nconst identitySchemaName = (name: string): string => name;\n\nconst schemaComponentPart = (value: string): string =>\n value\n .trim()\n .replace(/[^A-Za-z0-9._-]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\") || \"schema\";\n\nconst normalizeDiscoveryPathTemplate = (pathTemplate: string): string =>\n pathTemplate.replaceAll(/\\{\\+([^{}]+)\\}/g, \"{$1}\");\n\nconst pathUsesReservedExpansion = (pathTemplate: string, parameterName: string): boolean =>\n pathTemplate.includes(`{+${parameterName}}`);\n\nconst uniquePathKey = (\n paths: Record<string, Record<string, OpenApiOperationObject>>,\n preferredPath: string,\n method: string,\n toolPath: string,\n): string => {\n if (!paths[preferredPath]?.[method]) return preferredPath;\n const disambiguated = `/${toolPath.replace(/[^A-Za-z0-9._~-]+/g, \"/\")}`;\n if (!paths[disambiguated]?.[method]) return disambiguated;\n let index = 2;\n while (paths[`${disambiguated}/${index}`]?.[method]) index += 1;\n return `${disambiguated}/${index}`;\n};\n\nconst discoveryDescription = (value: unknown): string | undefined =>\n typeof value === \"string\"\n ? value\n : Option.isOption(value) && Option.isSome(value)\n ? typeof value.value === \"string\"\n ? value.value\n : undefined\n : undefined;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst jsonValue = (value: unknown): JsonValue | undefined => {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return value;\n }\n if (Array.isArray(value)) {\n const values = value.map(jsonValue);\n return values.every(Predicate.isNotUndefined) ? values : undefined;\n }\n if (!isRecord(value)) return undefined;\n const entries = Object.entries(value).flatMap(([key, item]) => {\n const converted = jsonValue(item);\n return converted === undefined ? [] : [[key, converted] as const];\n });\n return Object.fromEntries(entries);\n};\n\nconst stringArray = (value: unknown): readonly string[] | undefined => {\n if (!Array.isArray(value)) return undefined;\n const strings = value.filter((item): item is string => typeof item === \"string\");\n return strings.length === value.length ? strings : undefined;\n};\n\nconst schemaType = (value: unknown): OpenApiSchemaObject[\"type\"] | undefined =>\n typeof value === \"string\" && OPENAPI_SCHEMA_TYPES.has(value)\n ? (value as OpenApiSchemaObject[\"type\"])\n : undefined;\n\nconst discoverySchemaToOpenApiSchema = (\n raw: unknown,\n schemaNameForRef: (name: string) => string = identitySchemaName,\n): OpenApiSchemaObject => {\n if (!isRecord(raw)) return {};\n const schema = raw;\n if (typeof schema.$ref === \"string\") return { $ref: schemaRef(schemaNameForRef(schema.$ref)) };\n\n const description = discoveryDescription(schema.description);\n const title = discoveryDescription(schema.title);\n const defaultValue = jsonValue(schema.default);\n const enumValues = Array.isArray(schema.enum)\n ? schema.enum.map(jsonValue).filter(Predicate.isNotUndefined)\n : [];\n const format = typeof schema.format === \"string\" ? schema.format : undefined;\n const readOnly = typeof schema.readOnly === \"boolean\" ? schema.readOnly : undefined;\n const type = schemaType(schema.type);\n\n const base = {\n ...(description !== undefined ? { description } : {}),\n ...(title !== undefined ? { title } : {}),\n ...(format !== undefined ? { format } : {}),\n ...(readOnly !== undefined ? { readOnly } : {}),\n ...(defaultValue !== undefined ? { default: defaultValue } : {}),\n ...(enumValues.length > 0 ? { enum: enumValues } : {}),\n } satisfies OpenApiSchemaObject;\n\n if (type === \"array\") {\n return {\n ...base,\n type: \"array\",\n items: discoverySchemaToOpenApiSchema(schema.items, schemaNameForRef),\n };\n }\n\n const properties = schema.properties;\n if (\n type === \"object\" ||\n (isRecord(properties) && Object.keys(properties).length > 0) ||\n schema.additionalProperties !== undefined\n ) {\n const convertedProperties = isRecord(properties)\n ? Object.fromEntries(\n Object.entries(properties).map(([name, value]) => [\n name,\n discoverySchemaToOpenApiSchema(value, schemaNameForRef),\n ]),\n )\n : undefined;\n const required = stringArray(schema.required);\n const additionalProperties =\n schema.additionalProperties === undefined\n ? undefined\n : typeof schema.additionalProperties === \"boolean\"\n ? schema.additionalProperties\n : discoverySchemaToOpenApiSchema(schema.additionalProperties, schemaNameForRef);\n return {\n ...base,\n type: \"object\",\n ...(convertedProperties && Object.keys(convertedProperties).length > 0\n ? { properties: convertedProperties }\n : {}),\n ...(required && required.length > 0 ? { required } : {}),\n ...(additionalProperties !== undefined ? { additionalProperties } : {}),\n };\n }\n\n return type !== undefined ? { ...base, type } : base;\n};\n\nconst parameterSchema = (\n parameter: DiscoveryParameter,\n schemaNameForRef: (name: string) => string = identitySchemaName,\n): OpenApiSchemaObject => {\n const base = discoverySchemaToOpenApiSchema(parameter, schemaNameForRef);\n return parameter.repeated\n ? {\n type: \"array\",\n items: base,\n }\n : base;\n};\n\nconst methodToolPath = (service: string, methodId: string): string =>\n methodId.startsWith(`${service}.`) ? methodId.slice(service.length + 1) : methodId;\n\nconst collectMethods = (resource: unknown): DiscoveryMethod[] => {\n const decoded = decodeDiscoveryResource(resource);\n const direct = Object.values(decoded.methods ?? {}).map((raw) => decodeDiscoveryMethod(raw));\n const nested = Object.values(decoded.resources ?? {}).flatMap(collectMethods);\n return [...direct, ...nested];\n};\n\nconst discoveryScopes = (document: DiscoveryDocument): Record<string, string> =>\n Object.fromEntries(\n Object.entries(document.auth?.oauth2?.scopes ?? {}).map(([scope, value]) => [\n scope,\n Option.getOrElse(value.description, () => \"\"),\n ]),\n );\n\n// The scope set the converted integration DECLARES (and that `oauth.start`\n// requests at connect) must match the consent the picker previews. Both run the\n// raw Discovery union through `compactGoogleOAuthScopes`, which drops scopes a\n// user OAuth consent screen can't show (`chat.bot`/`chat.app.*`/`keep`) and\n// collapses sub-scopes under their broad parent (`gmail.*` → `mail.google.com`,\n// `userinfo.email` → `email`). Descriptions are preserved where the raw map had\n// them; compaction-introduced identity scopes (`email`/`profile`) fall back to\n// the broad parent's description. Per-operation `x-google-scopes`/`security`\n// stay RAW — they describe which scope each method needs, not consent.\nconst compactDiscoveryScopeMap = (raw: Record<string, string>): Record<string, string> => {\n const descriptionFor = (scope: string): string => {\n if (raw[scope] !== undefined) return raw[scope];\n if (scope === \"email\") return raw[\"https://www.googleapis.com/auth/userinfo.email\"] ?? \"\";\n if (scope === \"profile\") return raw[\"https://www.googleapis.com/auth/userinfo.profile\"] ?? \"\";\n return \"\";\n };\n return Object.fromEntries(\n compactGoogleOAuthScopes(Object.keys(raw)).map((scope) => [scope, descriptionFor(scope)]),\n );\n};\n\nconst allDiscoveryMethods = (document: DiscoveryDocument): DiscoveryMethod[] => [\n ...Object.values(document.methods ?? {}).map((raw) => decodeDiscoveryMethod(raw)),\n ...Object.values(document.resources ?? {}).flatMap(collectMethods),\n];\n\ntype DiscoveryDocumentInfo = {\n readonly discoveryUrl: string;\n readonly document: DiscoveryDocument;\n readonly service: string;\n readonly version: string;\n readonly rootUrl: string;\n readonly baseUrl: string;\n readonly title: string;\n};\n\nconst discoveryDocumentInfo = (\n document: DiscoveryDocument,\n discoveryUrl: string,\n): Effect.Effect<DiscoveryDocumentInfo, OpenApiParseError> =>\n Effect.gen(function* () {\n const service = Option.getOrUndefined(document.name);\n const version = Option.getOrUndefined(document.version);\n const rootUrl = Option.getOrUndefined(document.rootUrl);\n if (!service || !version || !rootUrl) {\n return yield* new OpenApiParseError({\n message: \"Google Discovery document is missing one of: name, version, rootUrl\",\n });\n }\n\n return {\n discoveryUrl,\n document,\n service,\n version,\n rootUrl,\n baseUrl: new URL(document.servicePath || \"\", rootUrl).toString(),\n title: Option.getOrElse(document.title, () => `${service} ${version}`),\n };\n });\n\nconst buildDiscoveryOperation = (input: {\n readonly document: DiscoveryDocument;\n readonly method: DiscoveryMethod;\n readonly toolPath: string;\n readonly pathTemplate: string;\n readonly schemaNameForRef?: (name: string) => string;\n readonly serverUrl?: string;\n readonly tags?: readonly string[];\n}): OpenApiOperationObject => {\n const mergedParameters = new Map<string, DiscoveryParameter>();\n for (const [name, raw] of Object.entries(input.document.parameters ?? {})) {\n const parameter = decodeDiscoveryParameter(raw);\n if (parameter.location) mergedParameters.set(name, parameter);\n }\n for (const [name, raw] of Object.entries(input.method.parameters ?? {})) {\n const parameter = decodeDiscoveryParameter(raw);\n if (parameter.location) mergedParameters.set(name, parameter);\n }\n\n const methodScopes = input.method.scopes ?? [];\n const methodDescription = Option.getOrUndefined(input.method.description);\n const schemaNameForRef = input.schemaNameForRef ?? identitySchemaName;\n\n return {\n operationId: input.toolPath,\n \"x-executor-toolPath\": input.toolPath,\n \"x-executor-pathTemplate\": input.pathTemplate,\n ...(input.tags && input.tags.length > 0 ? { tags: input.tags } : {}),\n ...(methodDescription !== undefined ? { description: methodDescription } : {}),\n ...(input.serverUrl ? { servers: [{ url: input.serverUrl }] } : {}),\n parameters: [...mergedParameters.entries()].flatMap(([name, parameter]) => {\n const location = parameter.location;\n if (!location) return [];\n const description = Option.getOrUndefined(parameter.description);\n const allowReserved =\n location === \"path\" && pathUsesReservedExpansion(input.pathTemplate, name);\n return [\n {\n name,\n in: location,\n required: location === \"path\" ? true : parameter.required === true,\n ...(description !== undefined ? { description } : {}),\n schema: parameterSchema(parameter, schemaNameForRef),\n ...(location === \"query\"\n ? { style: \"form\" as const, explode: parameter.repeated === true }\n : {}),\n ...(allowReserved ? { allowReserved: true } : {}),\n },\n ];\n }),\n ...(input.method.request?.$ref\n ? {\n requestBody: {\n required: false,\n content: {\n \"application/json\": {\n schema: { $ref: schemaRef(schemaNameForRef(input.method.request.$ref)) },\n },\n },\n },\n }\n : {}),\n responses: {\n \"200\": {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: input.method.response?.$ref\n ? { $ref: schemaRef(schemaNameForRef(input.method.response.$ref)) }\n : {},\n },\n },\n },\n },\n ...(methodScopes.length > 0 ? { security: [{ googleOAuth2: methodScopes }] } : {}),\n \"x-google-scopes\": methodScopes,\n };\n};\n\nconst GOOGLE_OAUTH_SECURITY_SCHEME = \"googleOAuth2\";\n\n/** The v2 oauth auth template for a Google-discovery integration. The spec\n * itself carries the matching `securitySchemes.googleOAuth2` entry; this is the\n * catalog-level template a connection's access token renders through. */\nconst googleOauthTemplate = (scopes: Record<string, string>): readonly Authentication[] =>\n // A Google-discovery integration is ALWAYS OAuth, so it ALWAYS declares its\n // oauth method — even when the compacted scope set is empty (e.g. a bundle of\n // only limited-consent APIs like Google Keep, whose scopes Google won't grant\n // through standard consent). Without this the integration declares no auth\n // method and the \"Add account\" / \"Add a connection\" actions are disabled, so\n // you can't even start the flow. Empty `scopes` just requests no scope.\n [\n {\n slug: AuthTemplateSlug.make(GOOGLE_OAUTH_SECURITY_SCHEME),\n kind: \"oauth2\",\n authorizationUrl: GOOGLE_OAUTH_AUTHORIZATION_URL,\n tokenUrl: GOOGLE_OAUTH_TOKEN_URL,\n scopes: Object.keys(scopes),\n },\n ];\n\nexport const convertGoogleDiscoveryToOpenApi = Effect.fn(\"OpenApi.convertGoogleDiscovery\")(\n function* (input: { readonly discoveryUrl: string; readonly documentText: string }) {\n const parsed = yield* parseJson(input.documentText).pipe(\n Effect.mapError(\n () =>\n new OpenApiParseError({\n message: \"Failed to parse Google Discovery document\",\n }),\n ),\n );\n const document = yield* Effect.try({\n try: () => decodeDiscoveryDocument(parsed),\n catch: () =>\n new OpenApiParseError({\n message: \"Failed to decode Google Discovery document\",\n }),\n });\n\n const info = yield* discoveryDocumentInfo(document, input.discoveryUrl);\n const { service, version, baseUrl, title } = info;\n const paths: Record<string, Record<string, OpenApiOperationObject>> = {};\n\n for (const method of allDiscoveryMethods(document)) {\n const methodId = Option.getOrUndefined(method.id);\n const pathTemplate = Option.getOrUndefined(method.path);\n if (!methodId || !pathTemplate || !method.httpMethod) continue;\n\n const toolPath = methodToolPath(service, methodId);\n const path = normalizeDiscoveryPathTemplate(\n pathTemplate.startsWith(\"/\") ? pathTemplate : `/${pathTemplate}`,\n );\n const methodKey = method.httpMethod.toLowerCase();\n const pathKey = uniquePathKey(paths, path, methodKey, toolPath);\n\n paths[pathKey] ??= {};\n paths[pathKey]![methodKey] = buildDiscoveryOperation({\n document,\n method,\n toolPath,\n pathTemplate: pathTemplate.startsWith(\"/\") ? pathTemplate : `/${pathTemplate}`,\n });\n }\n\n const scopes = compactDiscoveryScopeMap(discoveryScopes(document));\n const authenticationTemplate = googleOauthTemplate(scopes);\n\n const spec: OpenApiDocument = {\n openapi: \"3.1.0\",\n info: {\n title,\n version,\n },\n servers: [{ url: baseUrl }],\n paths,\n components: {\n schemas: Object.fromEntries(\n Object.entries(document.schemas ?? {}).map(([name, schema]) => [\n name,\n discoverySchemaToOpenApiSchema(schema),\n ]),\n ),\n ...(authenticationTemplate\n ? {\n securitySchemes: {\n googleOAuth2: {\n type: \"oauth2\",\n flows: {\n authorizationCode: {\n authorizationUrl: GOOGLE_OAUTH_AUTHORIZATION_URL,\n tokenUrl: GOOGLE_OAUTH_TOKEN_URL,\n scopes,\n },\n },\n },\n },\n }\n : {}),\n },\n ...(authenticationTemplate ? { security: [{ googleOAuth2: Object.keys(scopes) }] } : {}),\n \"x-executor-origin\": {\n kind: \"googleDiscovery\",\n discoveryUrl: normalizeDiscoveryUrl(input.discoveryUrl),\n service,\n version,\n },\n };\n\n return {\n // @effect-diagnostics-next-line preferSchemaOverJson:off\n specText: JSON.stringify(spec),\n baseUrl,\n title,\n service,\n version,\n ...(authenticationTemplate ? { authenticationTemplate } : {}),\n };\n },\n);\n\nexport const convertGoogleDiscoveryBundleToOpenApi = Effect.fn(\n \"OpenApi.convertGoogleDiscoveryBundle\",\n)(function* (input: {\n readonly documents: readonly { readonly discoveryUrl: string; readonly documentText: string }[];\n}) {\n if (input.documents.length === 0) {\n return yield* new OpenApiParseError({\n message: \"Google Discovery bundle requires at least one document\",\n });\n }\n\n const infos = yield* Effect.forEach(input.documents, ({ discoveryUrl, documentText }) =>\n Effect.gen(function* () {\n const parsed = yield* parseJson(documentText).pipe(\n Effect.mapError(\n () =>\n new OpenApiParseError({\n message: \"Failed to parse Google Discovery document\",\n }),\n ),\n );\n const document = yield* Effect.try({\n try: () => decodeDiscoveryDocument(parsed),\n catch: () =>\n new OpenApiParseError({\n message: \"Failed to decode Google Discovery document\",\n }),\n });\n return yield* discoveryDocumentInfo(document, discoveryUrl);\n }),\n );\n\n const paths: Record<string, Record<string, OpenApiOperationObject>> = {};\n const schemas: Record<string, OpenApiSchemaObject> = {};\n const rawScopes: Record<string, string> = {};\n\n for (const info of infos) {\n const schemaPrefix = schemaComponentPart(`${info.service}_${info.version}`);\n const schemaNameForRef = (name: string) => `${schemaPrefix}_${schemaComponentPart(name)}`;\n\n for (const [scope, description] of Object.entries(discoveryScopes(info.document))) {\n rawScopes[scope] ??= description;\n }\n\n for (const [name, schema] of Object.entries(info.document.schemas ?? {})) {\n schemas[schemaNameForRef(name)] = discoverySchemaToOpenApiSchema(schema, schemaNameForRef);\n }\n\n for (const method of allDiscoveryMethods(info.document)) {\n const methodId = Option.getOrUndefined(method.id);\n const rawPathTemplate = Option.getOrUndefined(method.path);\n if (!methodId || !rawPathTemplate || !method.httpMethod) continue;\n\n const toolPath = methodId;\n const wirePath = rawPathTemplate.startsWith(\"/\") ? rawPathTemplate : `/${rawPathTemplate}`;\n const openApiPath = normalizeDiscoveryPathTemplate(wirePath);\n const methodKey = method.httpMethod.toLowerCase();\n const pathKey = uniquePathKey(paths, openApiPath, methodKey, toolPath);\n\n paths[pathKey] ??= {};\n paths[pathKey]![methodKey] = buildDiscoveryOperation({\n document: info.document,\n method,\n toolPath,\n pathTemplate: wirePath,\n schemaNameForRef,\n serverUrl: info.baseUrl,\n tags: [info.title],\n });\n }\n }\n\n const scopes = compactDiscoveryScopeMap(rawScopes);\n const authenticationTemplate = googleOauthTemplate(scopes);\n const spec: OpenApiDocument = {\n openapi: \"3.1.0\",\n info: {\n title: \"Google\",\n version: \"google-discovery-bundle\",\n },\n servers: [{ url: GOOGLE_BUNDLE_BASE_URL }],\n paths,\n components: {\n schemas,\n ...(authenticationTemplate\n ? {\n securitySchemes: {\n googleOAuth2: {\n type: \"oauth2\",\n flows: {\n authorizationCode: {\n authorizationUrl: GOOGLE_OAUTH_AUTHORIZATION_URL,\n tokenUrl: GOOGLE_OAUTH_TOKEN_URL,\n scopes,\n },\n },\n },\n },\n }\n : {}),\n },\n ...(authenticationTemplate ? { security: [{ googleOAuth2: Object.keys(scopes) }] } : {}),\n \"x-executor-origin\": {\n kind: \"googleDiscoveryBundle\",\n services: infos.map((info) => ({\n discoveryUrl: normalizeDiscoveryUrl(info.discoveryUrl),\n service: info.service,\n version: info.version,\n })),\n },\n };\n\n return {\n // @effect-diagnostics-next-line preferSchemaOverJson:off\n specText: JSON.stringify(spec),\n baseUrl: GOOGLE_BUNDLE_BASE_URL,\n title: \"Google\",\n service: \"google\",\n version: \"google-discovery-bundle\",\n discoveryUrls: infos.map((info) => normalizeDiscoveryUrl(info.discoveryUrl)),\n ...(authenticationTemplate ? { authenticationTemplate } : {}),\n };\n});\n","const googleUserConsentBlockedScopes = new Set([\n \"https://www.googleapis.com/auth/chat.bot\",\n \"https://www.googleapis.com/auth/chat.import\",\n \"https://www.googleapis.com/auth/keep\",\n \"https://www.googleapis.com/auth/keep.readonly\",\n]);\n\nconst googleUserConsentBlockedScopePrefixes = [\"https://www.googleapis.com/auth/chat.app.\"];\n\nconst googleBroadScopeGroups: readonly {\n readonly broad: string;\n readonly prefixes: readonly string[];\n}[] = [\n {\n broad: \"https://mail.google.com/\",\n prefixes: [\"https://www.googleapis.com/auth/gmail.\"],\n },\n {\n broad: \"https://www.googleapis.com/auth/calendar\",\n prefixes: [\"https://www.googleapis.com/auth/calendar.\"],\n },\n {\n broad: \"https://www.googleapis.com/auth/drive\",\n prefixes: [\"https://www.googleapis.com/auth/drive.\"],\n },\n];\n\nconst normalizeGoogleIdentityScope = (scope: string): string =>\n scope === \"https://www.googleapis.com/auth/userinfo.email\"\n ? \"email\"\n : scope === \"https://www.googleapis.com/auth/userinfo.profile\"\n ? \"profile\"\n : scope;\n\nconst orderedUniqueScopes = (scopes: Iterable<string>): string[] => {\n const ordered: string[] = [];\n const seen = new Set<string>();\n for (const scope of scopes) {\n const trimmed = scope.trim();\n if (!trimmed || seen.has(trimmed)) continue;\n seen.add(trimmed);\n ordered.push(trimmed);\n }\n return ordered;\n};\n\nexport const isGoogleUserConsentOAuthScope = (scope: string): boolean =>\n !googleUserConsentBlockedScopes.has(scope) &&\n !googleUserConsentBlockedScopePrefixes.some((prefix) => scope.startsWith(prefix));\n\nexport const filterGoogleUserConsentOAuthScopes = (scopes: Iterable<string>): string[] =>\n orderedUniqueScopes(scopes).filter(isGoogleUserConsentOAuthScope);\n\nexport const compactGoogleOAuthScopes = (scopes: Iterable<string>): string[] => {\n const ordered = filterGoogleUserConsentOAuthScopes([...scopes].map(normalizeGoogleIdentityScope));\n const present = new Set(ordered);\n return ordered.filter(\n (scope) =>\n !googleBroadScopeGroups.some(\n (group) =>\n scope !== group.broad &&\n present.has(group.broad) &&\n group.prefixes.some((prefix) => scope.startsWith(prefix)),\n ),\n );\n};\n","// Spec-detected auth → stored `Authentication` templates, shared by every add\n// path. The React add flow derives templates from the preview before calling\n// `addSpec`; `addSpec` itself falls back to the same derivation when the\n// caller omits `authenticationTemplate` (the agentic/API path has no client\n// to do it). One implementation so the web UI and headless callers cannot\n// drift: an integration added over MCP gets the same auth methods the add\n// page would have produced.\nimport * as Option from \"effect/Option\";\n\nimport { AuthTemplateSlug, type OAuthAuthentication } from \"@executor-js/sdk/shared\";\n\nimport type { HeaderPreset, OAuth2Preset, SpecPreview } from \"./preview\";\nimport type { APIKeyAuthentication, Authentication } from \"./types\";\nimport { resolveServerUrl } from \"./openapi-utils\";\n\n// ---------------------------------------------------------------------------\n// OpenAPI url helpers — specs sometimes ship relative OAuth endpoints; resolve\n// them against the chosen base URL so the stored auth template is absolute.\n// ---------------------------------------------------------------------------\n\nexport function resolveOAuthUrl(url: string, baseUrl: string): string {\n if (!url) return url;\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: URL constructor normalizes provider metadata URLs\n try {\n new URL(url);\n return url;\n } catch {\n if (!baseUrl) return url;\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: URL constructor resolves relative provider metadata URLs\n try {\n return new URL(url, baseUrl).toString();\n } catch {\n return url;\n }\n }\n}\n\nconst standardOidcIdentityScopes = [\"openid\", \"email\", \"profile\"] as const;\n\nconst identityScopesForPreset = (\n identityScopes: OAuth2Preset[\"identityScopes\"],\n): readonly string[] => {\n if (identityScopes === false) return [];\n return identityScopes === \"auto\" ? standardOidcIdentityScopes : identityScopes;\n};\n\nexport const resolvedOAuthScopes = (\n apiScopes: Iterable<string>,\n identityScopes: OAuth2Preset[\"identityScopes\"],\n): string[] => {\n const merged = new Set(apiScopes);\n for (const scope of identityScopesForPreset(identityScopes)) merged.add(scope);\n return [...merged];\n};\n\n// ---------------------------------------------------------------------------\n// Auth-template builders — turn a preview preset into the integration's stored\n// `Authentication` template (v2). The header preset becomes an `apiKey` template\n// whose secret header value renders the resolved credential via `variable(token)`;\n// the oauth2 preset becomes an `oauth` template carrying the provider endpoints.\n// ---------------------------------------------------------------------------\n\nconst headerPrefix = (preset: HeaderPreset, headerName: string): string | undefined => {\n const label = preset.label.toLowerCase();\n if (headerName.toLowerCase() === \"authorization\") {\n if (label.includes(\"bearer\")) return \"Bearer \";\n if (label.includes(\"basic\")) return \"Basic \";\n }\n return undefined;\n};\n\nconst apiKeyTemplateFromHeaderPreset = (\n preset: HeaderPreset,\n slug: AuthTemplateSlug,\n): APIKeyAuthentication => ({\n slug,\n kind: \"apikey\",\n // Every secret header shares the one credential input (the canonical\n // `token`, stored as an absent placement variable).\n placements: preset.secretHeaders.map((headerName) => {\n const prefix = headerPrefix(preset, headerName);\n return { carrier: \"header\" as const, name: headerName, ...(prefix ? { prefix } : {}) };\n }),\n});\n\nconst oauthTemplateFromPreset = (\n preset: OAuth2Preset,\n baseUrl: string,\n slug: AuthTemplateSlug,\n scopes: readonly string[],\n): OAuthAuthentication => ({\n slug,\n kind: \"oauth2\",\n authorizationUrl: resolveOAuthUrl(\n Option.getOrElse(preset.authorizationUrl, () => \"\"),\n baseUrl,\n ),\n tokenUrl: resolveOAuthUrl(preset.tokenUrl, baseUrl),\n scopes: [...scopes],\n});\n\n// ---------------------------------------------------------------------------\n// All spec-detected auth methods → the union of stored `Authentication`\n// templates. Header presets become apiKey templates; each oauth2 preset becomes\n// an oauth template (with its declared API scopes plus, for auth-code flows,\n// the standard identity scopes). Slugs stay deterministic per method so the\n// stored template is stable across previews of the same spec.\n// ---------------------------------------------------------------------------\n\nexport const detectedAuthenticationTemplates = (\n headerPresets: readonly HeaderPreset[],\n oauth2Presets: readonly OAuth2Preset[],\n baseUrl: string,\n): readonly Authentication[] => {\n const templates: Authentication[] = [];\n headerPresets.forEach((preset, index) => {\n templates.push(\n apiKeyTemplateFromHeaderPreset(preset, AuthTemplateSlug.make(`apikey-${index}`)),\n );\n });\n for (const preset of oauth2Presets) {\n const scopes = resolvedOAuthScopes(Object.keys(preset.scopes), preset.identityScopes);\n templates.push(\n oauthTemplateFromPreset(\n preset,\n baseUrl,\n AuthTemplateSlug.make(`oauth-${preset.securitySchemeName}`),\n scopes,\n ),\n );\n }\n return templates;\n};\n\nexport const firstBaseUrlForPreview = (preview: SpecPreview): string => {\n const firstServer = preview.servers[0];\n return firstServer\n ? resolveServerUrl(firstServer.url, Option.getOrUndefined(firstServer.variables), {})\n : \"\";\n};\n\n/** The fallback `addSpec` uses when no explicit template was passed: every\n * spec-detected method, resolved against the integration's base URL. */\nexport const deriveAuthenticationTemplateFromPreview = (\n preview: SpecPreview,\n baseUrl: string | undefined,\n): readonly Authentication[] =>\n detectedAuthenticationTemplates(\n preview.headerPresets,\n preview.oauth2Presets,\n baseUrl ?? firstBaseUrlForPreview(preview),\n );\n"],"mappings":";;;;;;AAIA,SAAS,QAAQ,QAAQ,WAAW,QAAQ,oBAAoB;AAChE,SAAS,YAAY,yBAAyB;;;ACL9C,IAAM,iCAAiC,oBAAI,IAAI;AAAA,EAC7C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,wCAAwC,CAAC,2CAA2C;AAE1F,IAAM,yBAGA;AAAA,EACJ;AAAA,IACE,OAAO;AAAA,IACP,UAAU,CAAC,wCAAwC;AAAA,EACrD;AAAA,EACA;AAAA,IACE,OAAO;AAAA,IACP,UAAU,CAAC,2CAA2C;AAAA,EACxD;AAAA,EACA;AAAA,IACE,OAAO;AAAA,IACP,UAAU,CAAC,wCAAwC;AAAA,EACrD;AACF;AAEA,IAAM,+BAA+B,CAAC,UACpC,UAAU,mDACN,UACA,UAAU,qDACR,YACA;AAER,IAAM,sBAAsB,CAAC,WAAuC;AAClE,QAAM,UAAoB,CAAC;AAC3B,QAAM,OAAO,oBAAI,IAAY;AAC7B,aAAW,SAAS,QAAQ;AAC1B,UAAM,UAAU,MAAM,KAAK;A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AAE;AAAA,IAClD;AAAA,EACF;AAAA,EACA,UAAU,gBAAgB,OAAO,UAAU,OAAO;AAAA,EAClD,QAAQ,CAAC,GAAG,MAAM;AACpB;AAUO,IAAM,kCAAkC,CAC7C,eACA,eACA,YAC8B;AAC9B,QAAM,YAA8B,CAAC;AACrC,gBAAc,QAAQ,CAAC,QAAQ,UAAU;AACvC,cAAU;AAAA,MACR,+BAA+B,QAAQC,kBAAiB,KAAK,UAAU,KAAK,EAAE,CAAC;AAAA,IACjF;AAAA,EACF,CAAC;AACD,aAAW,UAAU,eAAe;AAClC,UAAM,SAAS,oBAAoB,OAAO,KAAK,OAAO,MAAM,GAAG,OAAO,cAAc;AACpF,cAAU;AAAA,MACR;AAAA,QACE;AAAA,QACA;AAAA,QACAA,kBAAiB,KAAK,SAAS,OAAO,kBAAkB,EAAE;AAAA,QAC1D;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEO,IAAM,yBAAyB,CAAC,YAAiC;AACtE,QAAM,cAAc,QAAQ,QAAQ,CAAC;AACrC,SAAO,cACH,iBAAiB,YAAY,KAAY,uBAAe,YAAY,SAAS,GAAG,CAAC,CAAC,IAClF;AACN;AAIO,IAAM,0CAA0C,CACrD,SACA,YAEA;AAAA,EACE,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,WAAW,uBAAuB,OAAO;AAC3C;","names":["Option","AuthTemplateSlug","AuthTemplateSlug"]}
@@ -3,7 +3,7 @@ import {
3
3
  OpenApiOAuthError,
4
4
  OpenApiParseError,
5
5
  SpecPreview
6
- } from "./chunk-YVRI7KRC.js";
6
+ } from "./chunk-C3IJX4AN.js";
7
7
 
8
8
  // src/react/atoms.ts
9
9
  import * as Atom from "effect/unstable/reactivity/Atom";
@@ -19,6 +19,7 @@ import {
19
19
  // src/api/group.ts
20
20
  import { HttpApiEndpoint, HttpApiGroup } from "effect/unstable/httpapi";
21
21
  import { Schema } from "effect";
22
+ import { ApiKeyAuthMethod, ApiKeyAuthTemplate } from "@executor-js/sdk/http-auth";
22
23
  import {
23
24
  InternalError,
24
25
  IntegrationAlreadyExistsError,
@@ -46,29 +47,15 @@ var OpenApiSpecInputPayload = Schema.Union([
46
47
  urls: Schema.Array(Schema.String)
47
48
  })
48
49
  ]);
49
- var AuthenticationVariablePayload = Schema.Struct({
50
- type: Schema.Literal("variable"),
51
- name: Schema.String
50
+ var OAuthTemplatePayload = Schema.Struct({
51
+ slug: Schema.String,
52
+ kind: Schema.Literal("oauth2"),
53
+ authorizationUrl: Schema.String,
54
+ tokenUrl: Schema.String,
55
+ scopes: Schema.Array(Schema.String)
52
56
  });
53
- var AuthenticationTemplateValuePayload = Schema.Union([
54
- Schema.String,
55
- Schema.Array(Schema.Union([Schema.String, AuthenticationVariablePayload]))
56
- ]);
57
- var AuthenticationPayload = Schema.Union([
58
- Schema.Struct({
59
- slug: Schema.String,
60
- type: Schema.Literal("apiKey"),
61
- headers: Schema.optional(Schema.Record(Schema.String, AuthenticationTemplateValuePayload)),
62
- queryParams: Schema.optional(Schema.Record(Schema.String, AuthenticationTemplateValuePayload))
63
- }),
64
- Schema.Struct({
65
- slug: Schema.String,
66
- type: Schema.Literal("oauth"),
67
- authorizationUrl: Schema.String,
68
- tokenUrl: Schema.String,
69
- scopes: Schema.Array(Schema.String)
70
- })
71
- ]);
57
+ var AuthenticationPayload = Schema.Union([OAuthTemplatePayload, ApiKeyAuthTemplate]);
58
+ var AuthenticationResponse = Schema.Union([OAuthTemplatePayload, ApiKeyAuthMethod]);
72
59
  var AddSpecPayload = Schema.Struct({
73
60
  spec: OpenApiSpecInputPayload,
74
61
  slug: Schema.String,
@@ -97,16 +84,15 @@ var IntegrationView = Schema.Struct({
97
84
  canRefresh: Schema.Boolean
98
85
  });
99
86
  var OpenApiConfigView = Schema.Struct({
100
- spec: Schema.String,
101
87
  sourceUrl: Schema.optional(Schema.String),
102
88
  googleDiscoveryUrls: Schema.optional(Schema.Array(Schema.String)),
103
89
  baseUrl: Schema.optional(Schema.String),
104
90
  headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),
105
91
  queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),
106
- authenticationTemplate: Schema.optional(Schema.Array(AuthenticationPayload))
92
+ authenticationTemplate: Schema.optional(Schema.Array(AuthenticationResponse))
107
93
  });
108
94
  var ConfigureResponse = Schema.Struct({
109
- authenticationTemplate: Schema.Array(AuthenticationPayload)
95
+ authenticationTemplate: Schema.Array(AuthenticationResponse)
110
96
  });
111
97
  var OpenApiGroup = HttpApiGroup.make("openapi").add(
112
98
  HttpApiEndpoint.post("previewSpec", "/openapi/preview", {
@@ -178,4 +164,4 @@ export {
178
164
  addOpenApiSpec,
179
165
  openapiConfigure
180
166
  };
181
- //# sourceMappingURL=chunk-BSLE6HCE.js.map
167
+ //# sourceMappingURL=chunk-IB36ED7Y.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/react/atoms.ts","../src/react/client.ts","../src/api/group.ts"],"sourcesContent":["import type { IntegrationSlug } from \"@executor-js/sdk/shared\";\nimport * as Atom from \"effect/unstable/reactivity/Atom\";\nimport { ReactivityKey } from \"@executor-js/react/api/reactivity-keys\";\nimport { OpenApiClient } from \"./client\";\n\n// ---------------------------------------------------------------------------\n// Query atoms — v2: the integration catalog is the unit of identity (the v1\n// per-scope `source` row is gone). `getIntegration` returns the catalog entry\n// (slug/description/kind/canRemove/canRefresh); credentials are owner-scoped\n// connections read from the shared `connections` API, not bound per source.\n// ---------------------------------------------------------------------------\n\nexport const openApiIntegrationAtom = (slug: IntegrationSlug) =>\n OpenApiClient.query(\"openapi\", \"getIntegration\", {\n params: { slug },\n timeToLive: \"15 seconds\",\n reactivityKeys: [ReactivityKey.integrations, ReactivityKey.tools],\n });\n\n// The full opaque config (including `authenticationTemplate`), used by the\n// configure UX to render existing auth methods and add custom ones.\nexport const openApiConfigAtom = (slug: IntegrationSlug) =>\n OpenApiClient.query(\"openapi\", \"getConfig\", {\n params: { slug },\n timeToLive: \"15 seconds\",\n reactivityKeys: [ReactivityKey.integrations, ReactivityKey.tools],\n });\n\n// ---------------------------------------------------------------------------\n// Mutation atoms\n// ---------------------------------------------------------------------------\n\nexport const previewOpenApiSpec = OpenApiClient.mutation(\"openapi\", \"previewSpec\");\n\nexport const addOpenApiSpec = OpenApiClient.mutation(\"openapi\", \"addSpec\");\n\nexport const removeOpenApiSpec = OpenApiClient.mutation(\"openapi\", \"removeSpec\");\n\n// Add / merge custom auth methods onto an integration's `authenticationTemplate`.\nexport const openapiConfigure = OpenApiClient.mutation(\"openapi\", \"configure\");\n\n// `getIntegration` is read-only; the atom family lets a caller pass a slug.\nexport const openApiIntegrationFamily = Atom.family(openApiIntegrationAtom);\n\n// `getConfig` is read-only; the atom family lets a caller pass a slug.\nexport const openApiConfigFamily = Atom.family(openApiConfigAtom);\n","import { createPluginAtomClient } from \"@executor-js/sdk/client\";\nimport {\n getExecutorApiBaseUrl,\n getExecutorServerAuthorizationHeader,\n} from \"@executor-js/react/api/server-connection\";\nimport { OpenApiGroup } from \"../api/group\";\n\nexport const OpenApiClient = createPluginAtomClient(OpenApiGroup, {\n baseUrl: getExecutorApiBaseUrl,\n authorizationHeader: getExecutorServerAuthorizationHeader,\n});\n","import { HttpApiEndpoint, HttpApiGroup } from \"effect/unstable/httpapi\";\nimport { Schema } from \"effect\";\nimport { ApiKeyAuthMethod, ApiKeyAuthTemplate } from \"@executor-js/sdk/http-auth\";\nimport {\n InternalError,\n IntegrationAlreadyExistsError,\n IntegrationSlug,\n} from \"@executor-js/sdk/shared\";\n\nimport { OpenApiParseError, OpenApiExtractionError, OpenApiOAuthError } from \"../sdk/errors\";\nimport { SpecPreview } from \"../sdk/preview\";\n\n// ---------------------------------------------------------------------------\n// Errors — the plugin-domain tagged errors flow directly to clients\n// (4xx, each carrying its own `httpApiStatus`). `InternalError` is the shared\n// opaque 500 surface; `StorageError` → `InternalError` translation happens at\n// service wiring time. `IntegrationAlreadyExistsError` (409) blocks re-adding\n// an existing slug — see addSpec.\n// ---------------------------------------------------------------------------\n\nconst DomainErrors = [\n InternalError,\n OpenApiParseError,\n OpenApiExtractionError,\n OpenApiOAuthError,\n IntegrationAlreadyExistsError,\n] as const;\n\nconst SlugParams = {\n slug: Schema.String,\n};\n\n// ---------------------------------------------------------------------------\n// Payloads\n// ---------------------------------------------------------------------------\n\nconst OpenApiSpecInputPayload = Schema.Union([\n Schema.Struct({ kind: Schema.Literal(\"url\"), url: Schema.String }),\n Schema.Struct({ kind: Schema.Literal(\"blob\"), value: Schema.String }),\n Schema.Struct({\n kind: Schema.Literal(\"googleDiscovery\"),\n url: Schema.String,\n }),\n Schema.Struct({\n kind: Schema.Literal(\"googleDiscoveryBundle\"),\n urls: Schema.Array(Schema.String),\n }),\n]);\n\nconst OAuthTemplatePayload = Schema.Struct({\n slug: Schema.String,\n kind: Schema.Literal(\"oauth2\"),\n authorizationUrl: Schema.String,\n tokenUrl: Schema.String,\n scopes: Schema.Array(Schema.String),\n});\n\n/** Auth INPUTS: oauth templates + the request-shaped apikey dialect. */\nconst AuthenticationPayload = Schema.Union([OAuthTemplatePayload, ApiKeyAuthTemplate]);\n\n/** Auth in RESPONSES: the canonical stored shapes (placements). */\nconst AuthenticationResponse = Schema.Union([OAuthTemplatePayload, ApiKeyAuthMethod]);\n\nconst AddSpecPayload = Schema.Struct({\n spec: OpenApiSpecInputPayload,\n slug: Schema.String,\n description: Schema.optional(Schema.String),\n baseUrl: Schema.optional(Schema.String),\n headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n authenticationTemplate: Schema.optional(Schema.Array(AuthenticationPayload)),\n});\n\nconst PreviewSpecPayload = Schema.Struct({\n spec: Schema.String,\n});\n\n// The `configure` payload — the new/updated auth methods to merge onto the\n// integration's `authenticationTemplate`. Reuses the same `AuthenticationPayload`\n// schema as `addSpec` so a custom apiKey method round-trips identically.\nconst ConfigurePayload = Schema.Struct({\n authenticationTemplate: Schema.Array(AuthenticationPayload),\n mode: Schema.optional(Schema.Literals([\"merge\", \"replace\"])),\n});\n\n// ---------------------------------------------------------------------------\n// Responses\n// ---------------------------------------------------------------------------\n\nconst AddSpecResponse = Schema.Struct({\n slug: IntegrationSlug,\n toolCount: Schema.Number,\n});\n\nconst IntegrationView = Schema.Struct({\n slug: IntegrationSlug,\n description: Schema.String,\n kind: Schema.String,\n canRemove: Schema.Boolean,\n canRefresh: Schema.Boolean,\n});\n\n// The integration config surfaced for the configure UX. Unlike\n// `IntegrationView` (catalog identity only), this carries the\n// `authenticationTemplate` the configure flow reads/writes. The spec text is\n// deliberately NOT served: it's a multi-MB build artifact in the plugin blob\n// store, and no client reads it (the configure UI only touches the template).\nconst OpenApiConfigView = Schema.Struct({\n sourceUrl: Schema.optional(Schema.String),\n googleDiscoveryUrls: Schema.optional(Schema.Array(Schema.String)),\n baseUrl: Schema.optional(Schema.String),\n headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n authenticationTemplate: Schema.optional(Schema.Array(AuthenticationResponse)),\n});\n\n// The configure result — the merged `authenticationTemplate` after the new\n// custom methods were appended/replaced.\nconst ConfigureResponse = Schema.Struct({\n authenticationTemplate: Schema.Array(AuthenticationResponse),\n});\n\n// ---------------------------------------------------------------------------\n// Group — addSpec/preview/get/remove over the integration catalog.\n// ---------------------------------------------------------------------------\n\nexport const OpenApiGroup = HttpApiGroup.make(\"openapi\")\n .add(\n HttpApiEndpoint.post(\"previewSpec\", \"/openapi/preview\", {\n payload: PreviewSpecPayload,\n success: SpecPreview,\n error: DomainErrors,\n }),\n )\n .add(\n HttpApiEndpoint.post(\"addSpec\", \"/openapi/specs\", {\n payload: AddSpecPayload,\n success: AddSpecResponse,\n error: DomainErrors,\n }),\n )\n .add(\n HttpApiEndpoint.get(\"getIntegration\", \"/openapi/integrations/:slug\", {\n params: SlugParams,\n success: Schema.NullOr(IntegrationView),\n error: DomainErrors,\n }),\n )\n .add(\n HttpApiEndpoint.get(\"getConfig\", \"/openapi/integrations/:slug/config\", {\n params: SlugParams,\n success: Schema.NullOr(OpenApiConfigView),\n error: DomainErrors,\n }),\n )\n .add(\n HttpApiEndpoint.post(\"configure\", \"/openapi/integrations/:slug/config\", {\n params: SlugParams,\n payload: ConfigurePayload,\n success: ConfigureResponse,\n error: DomainErrors,\n }),\n )\n .add(\n HttpApiEndpoint.delete(\"removeSpec\", \"/openapi/integrations/:slug\", {\n params: SlugParams,\n success: Schema.Void,\n error: DomainErrors,\n }),\n );\n"],"mappings":";;;;;;;;AACA,YAAY,UAAU;AACtB,SAAS,qBAAqB;;;ACF9B,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,OACK;;;ACJP,SAAS,iBAAiB,oBAAoB;AAC9C,SAAS,cAAc;AACvB,SAAS,kBAAkB,0BAA0B;AACrD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAaP,IAAM,eAAe;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,aAAa;AAAA,EACjB,MAAM,OAAO;AACf;AAMA,IAAM,0BAA0B,OAAO,MAAM;AAAA,EAC3C,OAAO,OAAO,EAAE,MAAM,OAAO,QAAQ,KAAK,GAAG,KAAK,OAAO,OAAO,CAAC;AAAA,EACjE,OAAO,OAAO,EAAE,MAAM,OAAO,QAAQ,MAAM,GAAG,OAAO,OAAO,OAAO,CAAC;AAAA,EACpE,OAAO,OAAO;AAAA,IACZ,MAAM,OAAO,QAAQ,iBAAiB;AAAA,IACtC,KAAK,OAAO;AAAA,EACd,CAAC;AAAA,EACD,OAAO,OAAO;AAAA,IACZ,MAAM,OAAO,QAAQ,uBAAuB;AAAA,IAC5C,MAAM,OAAO,MAAM,OAAO,MAAM;AAAA,EAClC,CAAC;AACH,CAAC;AAED,IAAM,uBAAuB,OAAO,OAAO;AAAA,EACzC,MAAM,OAAO;AAAA,EACb,MAAM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