@executor-js/plugin-openapi 1.5.15 → 1.5.17
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.
- package/dist/AddOpenApiSource-U7AYB224.js +369 -0
- package/dist/AddOpenApiSource-U7AYB224.js.map +1 -0
- package/dist/{OpenApiAccountsPanel-X5Z5XKRM.js → OpenApiAccountsPanel-GHFHHE6P.js} +15 -39
- package/dist/OpenApiAccountsPanel-GHFHHE6P.js.map +1 -0
- package/dist/{UpdateSpecSection-Z2DEEWZW.js → UpdateSpecSection-PLCBUU4I.js} +4 -4
- package/dist/UpdateSpecSection-PLCBUU4I.js.map +1 -0
- package/dist/api/group.d.ts +0 -21
- package/dist/api/index.d.ts +0 -21
- package/dist/chunk-CKBX4SXK.js +95 -0
- package/dist/chunk-CKBX4SXK.js.map +1 -0
- package/dist/{chunk-NJ4Q3VF4.js → chunk-CPPTKUOW.js} +5 -14
- package/dist/chunk-CPPTKUOW.js.map +1 -0
- package/dist/{chunk-O54VFSWE.js → chunk-KVPUDOJZ.js} +18 -4
- package/dist/chunk-KVPUDOJZ.js.map +1 -0
- package/dist/{chunk-PAHWRRS3.js → chunk-QQFCICLX.js} +4 -13
- package/dist/chunk-QQFCICLX.js.map +1 -0
- package/dist/{chunk-ZTOOUP67.js → chunk-UEKOP6NZ.js} +544 -580
- package/dist/chunk-UEKOP6NZ.js.map +1 -0
- package/dist/client.js +4 -5
- package/dist/client.js.map +1 -1
- package/dist/core.js +25 -15
- package/dist/core.js.map +1 -1
- package/dist/index.js +4 -5
- package/dist/index.js.map +1 -1
- package/dist/react/atoms.d.ts +0 -22
- package/dist/react/client.d.ts +0 -21
- package/dist/react/index.d.ts +2 -0
- package/dist/sdk/backing.d.ts +54 -0
- package/dist/sdk/config.d.ts +0 -2
- package/dist/sdk/derive-auth.d.ts +5 -3
- package/dist/sdk/index.d.ts +2 -1
- package/dist/sdk/plugin.d.ts +4 -10
- package/dist/sdk/presets.d.ts +0 -1
- package/dist/sdk/preview.d.ts +79 -0
- package/dist/testing/index.d.ts +0 -6
- package/package.json +6 -5
- package/dist/AddOpenApiSource-IRMLVLDK.js +0 -765
- package/dist/AddOpenApiSource-IRMLVLDK.js.map +0 -1
- package/dist/OpenApiAccountsPanel-X5Z5XKRM.js.map +0 -1
- package/dist/UpdateSpecSection-Z2DEEWZW.js.map +0 -1
- package/dist/chunk-MZWZQ24W.js +0 -226
- package/dist/chunk-MZWZQ24W.js.map +0 -1
- package/dist/chunk-NJ4Q3VF4.js.map +0 -1
- package/dist/chunk-O54VFSWE.js.map +0 -1
- package/dist/chunk-PAHWRRS3.js.map +0 -1
- package/dist/chunk-UOLBAX5D.js +0 -712
- package/dist/chunk-UOLBAX5D.js.map +0 -1
- package/dist/chunk-ZTOOUP67.js.map +0 -1
- package/dist/react/GoogleProductPicker.d.ts +0 -9
- package/dist/sdk/google-discovery.d.ts +0 -43
- package/dist/sdk/google-oauth-batches.d.ts +0 -13
- package/dist/sdk/google-oauth-batches.test.d.ts +0 -1
- package/dist/sdk/google-oauth-scopes.d.ts +0 -3
- package/dist/sdk/google-oauth-scopes.test.d.ts +0 -1
- package/dist/sdk/google-presets.d.ts +0 -16
- package/dist/sdk/google-presets.test.d.ts +0 -1
- package/dist/sdk/google-product-picker-scopes.test.d.ts +0 -1
- /package/dist/sdk/{google-bundle.test.d.ts → request-user-agent.test.d.ts} +0 -0
- /package/dist/sdk/{google-discovery.test.d.ts → store.test.d.ts} +0 -0
|
@@ -1 +0,0 @@
|
|
|
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;AAC3B,QAAI,CAAC,WAAW,KAAK,IAAI,OAAO,EAAG;AACnC,SAAK,IAAI,OAAO;AAChB,YAAQ,KAAK,OAAO;AAAA,EACtB;AACA,SAAO;AACT;AAEO,IAAM,gCAAgC,CAAC,UAC5C,CAAC,+BAA+B,IAAI,KAAK,KACzC,CAAC,sCAAsC,KAAK,CAAC,WAAW,MAAM,WAAW,MAAM,CAAC;AAE3E,IAAM,qCAAqC,CAAC,WACjD,oBAAoB,MAAM,EAAE,OAAO,6BAA6B;AAE3D,IAAM,2BAA2B,CAAC,WAAuC;AAC9E,QAAM,UAAU,mCAAmC,C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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"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sdk/config.ts","../src/sdk/invoke.ts","../src/sdk/store.ts","../src/sdk/plugin.ts","../src/sdk/definitions.ts"],"sourcesContent":["import { Option, Schema } from \"effect\";\nimport {\n ApiKeyAuthMethod,\n TOKEN_VARIABLE,\n renderAuthPlacements,\n requiredPlacementVariables,\n} from \"@executor-js/sdk/http-auth\";\n\nimport type { Authentication } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// OpenAPI integration config — the opaque blob stored on the catalog\n// `integration.config` column (D1). Core never parses it; the plugin writes it\n// at register time and reads it back in `resolveTools` / `invokeTool`.\n//\n// In v2 there are NO credential bindings, NO per-source secret slots, and NO\n// StoredSource credential config. The config carries only:\n// - the content hash of the spec blob and/or the source URL to (re)fetch\n// from,\n// - the optional base URL override,\n// - the auth templates a connection's value is rendered through.\n// The resolved spec text itself lives in the plugin blob store, keyed\n// `spec/<specHash>` — it's a build input for resolveTools/refresh, not data\n// any list/invoke path should pay to load. Rows that predate the blob store\n// (inline `spec` text) are rewritten before this schema sees them: cloud by\n// the out-of-band migrate-specs-to-blobs script, the libSQL hosts by the\n// boot-time ledger migration.\n// ---------------------------------------------------------------------------\n\nconst OAuthAuthenticationSchema = 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\nexport const AuthenticationSchema = Schema.Union([OAuthAuthenticationSchema, ApiKeyAuthMethod]);\n\nexport const OpenApiIntegrationConfigSchema = Schema.Struct({\n /** Hex SHA-256 of the resolved spec text — the content address of the spec\n * blob (`spec/<hash>` in the plugin blob store). */\n specHash: Schema.optional(Schema.String),\n /** Origin URL the spec was fetched from, when known. Enables refresh. */\n sourceUrl: Schema.optional(Schema.String),\n /** Google Discovery bundle URLs, when the spec came from a Google bundle. */\n googleDiscoveryUrls: Schema.optional(Schema.Array(Schema.String)),\n /** Optional base URL override. */\n baseUrl: Schema.optional(Schema.String),\n /** Static headers applied to every request (no secret material). */\n headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n /** Static query params applied to every request (no secret material). */\n queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n /** The auth methods a connection's value can be applied through. */\n authenticationTemplate: Schema.optional(Schema.Array(AuthenticationSchema)),\n});\n\nexport type OpenApiIntegrationConfig = Omit<\n typeof OpenApiIntegrationConfigSchema.Type,\n \"authenticationTemplate\"\n> & {\n /** Branded over the schema's structural form so the template renderer can\n * treat `slug` as an `AuthTemplateSlug`. */\n readonly authenticationTemplate?: readonly Authentication[];\n};\n\nconst decodeConfig = Schema.decodeUnknownOption(OpenApiIntegrationConfigSchema);\n\n/** Decode the opaque integration config blob into the openapi shape.\n * Returns null when the blob is missing/incompatible. */\nexport const decodeOpenApiIntegrationConfig = (value: unknown): OpenApiIntegrationConfig | null =>\n Option.getOrNull(decodeConfig(value)) as OpenApiIntegrationConfig | null;\n\n// ---------------------------------------------------------------------------\n// Template rendering — \"auth state derived into the auth-template format\"\n// (D11). An apiKey method renders through the shared placements renderer; an\n// oauth template (no explicit placement) renders a bearer `authorization`\n// header from the `token` input (the access token).\n// ---------------------------------------------------------------------------\n\nexport interface RenderedAuth {\n readonly headers: Record<string, string>;\n readonly queryParams: Record<string, string>;\n}\n\n/** Render an auth template against a connection's resolved input `values`\n * (`variable → value`). Each placement substitutes from its own entry, so a\n * method with two distinct inputs (e.g. Datadog) fills each header from a\n * different value. */\nexport const renderAuthTemplate = (\n template: Authentication,\n values: Record<string, string | null>,\n): RenderedAuth => {\n if (template.kind === \"oauth2\") {\n return {\n headers: { authorization: `Bearer ${values[TOKEN_VARIABLE] ?? \"\"}` },\n queryParams: {},\n };\n }\n return renderAuthPlacements(template.placements, values);\n};\n\n/** The distinct input variables a template references — the inputs a connection\n * must supply. An oauth template needs `token`; an apiKey method needs every\n * variable across its placements. */\nexport const requiredTemplateVariables = (template: Authentication): readonly string[] => {\n if (template.kind === \"oauth2\") return [TOKEN_VARIABLE];\n return requiredPlacementVariables(template.placements);\n};\n","import { Effect, Layer, Option } from \"effect\";\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\";\nimport type { ToolFileValue } from \"@executor-js/sdk/core\";\n\nimport { OpenApiInvocationError } from \"./errors\";\nimport { resolveServerUrl } from \"./openapi-utils\";\nimport {\n type EncodingObject,\n type OperationFileHint,\n type OperationBinding,\n InvocationResult,\n type MediaBinding,\n type OperationParameter,\n type ServerInfo,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Parameter reading\n// ---------------------------------------------------------------------------\n\nconst CONTAINER_KEYS: Record<string, readonly string[]> = {\n path: [\"path\", \"pathParams\", \"params\"],\n query: [\"query\", \"queryParams\", \"params\"],\n header: [\"headers\", \"header\"],\n cookie: [\"cookies\", \"cookie\"],\n};\n\nconst readParamValue = (args: Record<string, unknown>, param: OperationParameter): unknown => {\n const direct = args[param.name];\n if (direct !== undefined) return direct;\n\n for (const key of CONTAINER_KEYS[param.location] ?? []) {\n const container = args[key];\n if (typeof container === \"object\" && container !== null && !Array.isArray(container)) {\n const nested = (container as Record<string, unknown>)[param.name];\n if (nested !== undefined) return nested;\n }\n }\n\n return undefined;\n};\n\nconst primitiveToString = (value: unknown): string =>\n typeof value === \"object\" && value !== null ? JSON.stringify(value) : String(value);\n\n// RFC 3986 §2.2 reserved chars. `allowReserved: true` leaves these\n// unencoded; default OAS behavior encodes everything non-unreserved.\nconst RESERVED_UNENCODED_RE = /[A-Za-z0-9\\-._~:/?#[\\]@!$&'()*+,;=]/;\n\nconst encodeReservedAware = (raw: string, allowReserved: boolean): string => {\n if (!allowReserved) return encodeURIComponent(raw);\n // Walk char-by-char so the reserved set passes through as-is.\n let out = \"\";\n for (const ch of raw) {\n out += RESERVED_UNENCODED_RE.test(ch) ? ch : encodeURIComponent(ch);\n }\n return out;\n};\n\nconst queryParamValues = (value: unknown, param: OperationParameter): string[] => {\n if (value === undefined || value === null) return [];\n if (!Array.isArray(value)) return [primitiveToString(value)];\n\n const style = Option.getOrUndefined(param.style) ?? \"form\";\n const explode = Option.getOrElse(param.explode, () => true);\n\n if (explode) return value.map(primitiveToString);\n\n const separator = style === \"spaceDelimited\" ? \" \" : style === \"pipeDelimited\" ? \"|\" : \",\";\n return [value.map(primitiveToString).join(separator)];\n};\n\n// ---------------------------------------------------------------------------\n// Path resolution\n// ---------------------------------------------------------------------------\n\nconst resolvePath = Effect.fn(\"OpenApi.resolvePath\")(function* (\n pathTemplate: string,\n args: Record<string, unknown>,\n parameters: readonly OperationParameter[],\n) {\n let resolved = pathTemplate;\n\n for (const param of parameters) {\n if (param.location !== \"path\") continue;\n const value = readParamValue(args, param);\n if (value === undefined || value === null) {\n if (param.required) {\n return yield* new OpenApiInvocationError({\n message: `Missing required path parameter: ${param.name}`,\n statusCode: Option.none(),\n });\n }\n continue;\n }\n const encoded = encodeReservedAware(\n String(value),\n Option.getOrElse(param.allowReserved, () => false),\n );\n resolved = resolved.replaceAll(`{${param.name}}`, encoded);\n resolved = resolved.replaceAll(`{+${param.name}}`, encoded);\n }\n\n const remaining = [...resolved.matchAll(/\\{([^{}]+)\\}/g)]\n .map((m) => m[1])\n .filter((v): v is string => typeof v === \"string\");\n\n for (const name of remaining) {\n const value = args[name];\n if (value !== undefined && value !== null) {\n resolved = resolved.replaceAll(`{${name}}`, encodeURIComponent(String(value)));\n }\n }\n\n const unresolved = [...resolved.matchAll(/\\{([^{}]+)\\}/g)]\n .map((m) => m[1])\n .filter((v): v is string => typeof v === \"string\");\n\n if (unresolved.length > 0) {\n return yield* new OpenApiInvocationError({\n message: `Unresolved path parameters: ${[...new Set(unresolved)].join(\", \")}`,\n statusCode: Option.none(),\n });\n }\n\n return resolved;\n});\n\nconst applyHeaders = (\n request: HttpClientRequest.HttpClientRequest,\n headers: Record<string, string>,\n): HttpClientRequest.HttpClientRequest => {\n let req = request;\n for (const [name, value] of Object.entries(headers)) {\n req = HttpClientRequest.setHeader(req, name, value);\n }\n return req;\n};\n\n// ---------------------------------------------------------------------------\n// Response helpers\n// ---------------------------------------------------------------------------\n\nconst normalizeContentType = (ct: string | null | undefined): string =>\n ct?.split(\";\")[0]?.trim().toLowerCase() ?? \"\";\n\nconst isJsonContentType = (ct: string | null | undefined): boolean => {\n const normalized = normalizeContentType(ct);\n if (!normalized) return false;\n return (\n normalized === \"application/json\" || normalized.includes(\"+json\") || normalized.includes(\"json\")\n );\n};\n\nconst isFormUrlEncoded = (ct: string | null | undefined): boolean =>\n normalizeContentType(ct) === \"application/x-www-form-urlencoded\";\n\nconst isMultipartFormData = (ct: string | null | undefined): boolean =>\n normalizeContentType(ct).startsWith(\"multipart/form-data\");\n\nconst isXmlContentType = (ct: string | null | undefined): boolean => {\n const normalized = normalizeContentType(ct);\n if (!normalized) return false;\n return (\n normalized === \"application/xml\" || normalized === \"text/xml\" || normalized.endsWith(\"+xml\")\n );\n};\n\nconst isTextContentType = (ct: string | null | undefined): boolean =>\n normalizeContentType(ct).startsWith(\"text/\");\n\nconst isOctetStream = (ct: string | null | undefined): boolean =>\n normalizeContentType(ct) === \"application/octet-stream\";\n\nconst bytesToBase64 = (bytes: Uint8Array): string => {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.length; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));\n }\n return btoa(binary);\n};\n\nconst normalizeBase64 = (value: string, encoding: \"base64\" | \"base64url\"): string => {\n const compact = value.replace(/\\s/g, \"\");\n const alphabet =\n encoding === \"base64url\" ? compact.replace(/-/g, \"+\").replace(/_/g, \"/\") : compact;\n const remainder = alphabet.length % 4;\n return remainder === 0 ? alphabet : `${alphabet}${\"=\".repeat(4 - remainder)}`;\n};\n\nconst byteLengthFromBase64 = (base64: string): number => {\n const compact = base64.replace(/\\s/g, \"\");\n const padding = compact.endsWith(\"==\") ? 2 : compact.endsWith(\"=\") ? 1 : 0;\n return Math.max(0, Math.floor((compact.length * 3) / 4) - padding);\n};\n\nconst isGenericMimeType = (mimeType: string): boolean =>\n normalizeContentType(mimeType) === \"application/octet-stream\";\n\nconst startsWithBytes = (bytes: Uint8Array, prefix: readonly number[]): boolean =>\n prefix.every((byte, index) => bytes[index] === byte);\n\nconst isLikelyUtf8Text = (bytes: Uint8Array): boolean => {\n if (bytes.length === 0) return false;\n let text: string;\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: TextDecoder throws while probing arbitrary binary content\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch {\n return false;\n }\n let suspicious = 0;\n for (let index = 0; index < text.length; index += 1) {\n const code = text.charCodeAt(index);\n const allowedControl = code === 0x09 || code === 0x0a || code === 0x0c || code === 0x0d;\n if (code === 0x00) return false;\n if (code < 0x20 && !allowedControl) suspicious += 1;\n }\n return suspicious / Math.max(1, text.length) <= 0.02;\n};\n\nconst sniffMimeType = (bytes: Uint8Array): string | null => {\n if (startsWithBytes(bytes, [0xff, 0xd8, 0xff])) return \"image/jpeg\";\n if (startsWithBytes(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) {\n return \"image/png\";\n }\n if (\n startsWithBytes(bytes, [0x47, 0x49, 0x46, 0x38, 0x37, 0x61]) ||\n startsWithBytes(bytes, [0x47, 0x49, 0x46, 0x38, 0x39, 0x61])\n ) {\n return \"image/gif\";\n }\n if (\n startsWithBytes(bytes, [0x52, 0x49, 0x46, 0x46]) &&\n bytes[8] === 0x57 &&\n bytes[9] === 0x45 &&\n bytes[10] === 0x42 &&\n bytes[11] === 0x50\n ) {\n return \"image/webp\";\n }\n if (startsWithBytes(bytes, [0x25, 0x50, 0x44, 0x46, 0x2d])) return \"application/pdf\";\n if (\n startsWithBytes(bytes, [0x50, 0x4b, 0x03, 0x04]) ||\n startsWithBytes(bytes, [0x50, 0x4b, 0x05, 0x06]) ||\n startsWithBytes(bytes, [0x50, 0x4b, 0x07, 0x08])\n ) {\n return \"application/zip\";\n }\n if (isLikelyUtf8Text(bytes)) return \"text/plain\";\n return null;\n};\n\nconst bytesFromBase64Prefix = (base64: string): Uint8Array => {\n const prefix = base64.slice(0, Math.min(base64.length, 64));\n const binary = atob(prefix);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n};\n\nconst sniffMimeTypeFromBase64 = (base64: string): string | null =>\n sniffMimeType(bytesFromBase64Prefix(base64));\n\nconst toUint8Array = (value: unknown): Uint8Array | null => {\n if (value instanceof Uint8Array) return value;\n if (value instanceof ArrayBuffer) return new Uint8Array(value);\n if (ArrayBuffer.isView(value)) {\n const view = value as ArrayBufferView;\n return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n }\n if (Array.isArray(value) && value.every((v) => typeof v === \"number\")) {\n return new Uint8Array(value as readonly number[]);\n }\n return null;\n};\n\nconst readHintString = (option: OperationFileHint[\"dataField\"], fallback: string): string =>\n Option.getOrElse(option, () => fallback);\n\nconst readHintMimeType = (hint: OperationFileHint, fallback: string): string =>\n Option.getOrElse(hint.mimeType, () => fallback);\n\nconst readHintEncoding = (hint: OperationFileHint): \"base64\" | \"base64url\" =>\n Option.getOrElse(hint.encoding, () => \"base64\");\n\nconst fileFromByteField = (body: unknown, hint: OperationFileHint): ToolFileValue | null => {\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) return null;\n const record = body as Record<string, unknown>;\n const dataField = readHintString(hint.dataField, \"data\");\n const rawData = record[dataField];\n if (typeof rawData !== \"string\") return null;\n\n const data = normalizeBase64(rawData, readHintEncoding(hint));\n const sizeField = Option.getOrUndefined(hint.sizeField);\n const byteLength =\n sizeField && typeof record[sizeField] === \"number\"\n ? record[sizeField]\n : byteLengthFromBase64(data);\n const hintedMimeType = readHintMimeType(hint, \"application/octet-stream\");\n\n return {\n _tag: \"ToolFile\",\n mimeType: isGenericMimeType(hintedMimeType)\n ? (sniffMimeTypeFromBase64(data) ?? hintedMimeType)\n : hintedMimeType,\n encoding: \"base64\",\n data,\n byteLength,\n };\n};\n\nconst fileFromBinaryBytes = (\n bytes: Uint8Array,\n hint: OperationFileHint,\n contentType: string | null | undefined,\n): ToolFileValue => {\n const hintedMimeType = contentType ?? readHintMimeType(hint, \"application/octet-stream\");\n return {\n _tag: \"ToolFile\",\n mimeType: isGenericMimeType(hintedMimeType)\n ? (sniffMimeType(bytes) ?? hintedMimeType)\n : hintedMimeType,\n encoding: \"base64\",\n data: bytesToBase64(bytes),\n byteLength: bytes.byteLength,\n };\n};\n\ntype FormDataRecord = Parameters<typeof HttpClientRequest.bodyFormDataRecord>[1];\ntype FormDataCoercible = FormDataRecord[string];\n\n// Pull a plain ArrayBuffer out of a Uint8Array — `new Blob([u8])` rejects\n// views whose `.buffer` is `SharedArrayBuffer | ArrayBuffer` under strict\n// lib.dom typings.\nconst toArrayBuffer = (bytes: Uint8Array): ArrayBuffer => {\n const copy = new ArrayBuffer(bytes.byteLength);\n new Uint8Array(copy).set(bytes);\n return copy;\n};\n\n// ---------------------------------------------------------------------------\n// OpenAPI 3.x encoding — per-property style/explode/allowReserved/contentType\n// for multipart/form-data and application/x-www-form-urlencoded bodies.\n// Spec ref: https://spec.openapis.org/oas/v3.1.0#encoding-object\n// ---------------------------------------------------------------------------\n\ntype StyleExplode = {\n readonly style: string;\n readonly explode: boolean;\n readonly allowReserved: boolean;\n};\n\nconst DEFAULT_FORM_STYLE: StyleExplode = {\n style: \"form\",\n explode: true,\n allowReserved: false,\n};\n\nconst resolveStyleExplode = (e: EncodingObject | undefined): StyleExplode => {\n if (!e) return DEFAULT_FORM_STYLE;\n return {\n style: Option.getOrElse(e.style, () => DEFAULT_FORM_STYLE.style),\n explode: Option.getOrElse(e.explode, () => DEFAULT_FORM_STYLE.explode),\n allowReserved: Option.getOrElse(e.allowReserved, () => DEFAULT_FORM_STYLE.allowReserved),\n };\n};\n\nconst encodeFormValue = (v: unknown, allowReserved: boolean): string => {\n const raw = typeof v === \"object\" && v !== null ? JSON.stringify(v) : String(v);\n return encodeReservedAware(raw, allowReserved);\n};\n\n/**\n * Serialize a record to application/x-www-form-urlencoded with OAS3 style\n * rules honored per-field. Supports `form` (default), `deepObject`,\n * `pipeDelimited`, `spaceDelimited` styles with `explode` true / false.\n */\nconst serializeFormUrlEncoded = (\n value: Record<string, unknown>,\n encoding: Record<string, EncodingObject> | undefined,\n): string => {\n const parts: string[] = [];\n for (const [key, raw] of Object.entries(value)) {\n if (raw === undefined || raw === null) continue;\n const { style, explode, allowReserved } = resolveStyleExplode(encoding?.[key]);\n const encKey = encodeURIComponent(key);\n\n if (Array.isArray(raw)) {\n if (explode) {\n for (const v of raw) {\n parts.push(`${encKey}=${encodeFormValue(v, allowReserved)}`);\n }\n } else {\n const sep = style === \"spaceDelimited\" ? \" \" : style === \"pipeDelimited\" ? \"|\" : \",\";\n parts.push(\n `${encKey}=${encodeFormValue(\n raw.map((v) => (typeof v === \"object\" ? JSON.stringify(v) : String(v))).join(sep),\n allowReserved,\n )}`,\n );\n }\n continue;\n }\n\n if (typeof raw === \"object\") {\n const entries = Object.entries(raw as Record<string, unknown>).filter(\n ([, v]) => v !== undefined && v !== null,\n );\n if (style === \"deepObject\") {\n for (const [subkey, subval] of entries) {\n // Encode the whole `key[subkey]` fragment so `[` / `]` become\n // `%5B` / `%5D`. Matches swagger-client's behaviour and remains\n // accepted by common server-side parsers (qs, Rails, etc.).\n parts.push(\n `${encodeURIComponent(`${key}[${subkey}]`)}=${encodeFormValue(subval, allowReserved)}`,\n );\n }\n } else if (explode) {\n // form + explode=true on object: sub-keys become top-level fields.\n for (const [subkey, subval] of entries) {\n parts.push(`${encodeURIComponent(subkey)}=${encodeFormValue(subval, allowReserved)}`);\n }\n } else {\n // form + explode=false on object: flatten to csv key,val,key,val.\n const flat = entries.flatMap(([k, v]) => [\n k,\n typeof v === \"object\" ? JSON.stringify(v) : String(v),\n ]);\n parts.push(`${encKey}=${encodeFormValue(flat.join(\",\"), allowReserved)}`);\n }\n continue;\n }\n\n parts.push(`${encKey}=${encodeFormValue(raw, allowReserved)}`);\n }\n return parts.join(\"&\");\n};\n\n/**\n * Best-effort build of a multipart FormData entry record.\n *\n * If `encoding[key].contentType` is declared (OAS3 §4.8.15), wrap the value\n * in a `Blob` with that type so the runtime multipart framer emits the\n * per-part `Content-Type` header (e.g. `application/json` for a metadata\n * part whose server expects parsed JSON).\n *\n * Otherwise: primitives pass through, arrays handle their item types, byte\n * shapes wrap as Blob, nested objects JSON-stringify (never `[object Object]`).\n */\nconst coerceFormDataRecord = (\n value: Record<string, unknown>,\n encoding: Record<string, EncodingObject> | undefined,\n): FormDataRecord => {\n const out: Record<string, FormDataCoercible> = {};\n for (const [key, raw] of Object.entries(value)) {\n if (raw === undefined || raw === null) continue;\n\n const partType = encoding?.[key]\n ? Option.getOrUndefined(encoding[key]!.contentType)\n : undefined;\n\n // Explicit per-part content type: wrap in a typed Blob so the framer\n // emits `Content-Type: <partType>` on this part. JSON types get the\n // value JSON-stringified first so the blob body is valid JSON.\n if (partType) {\n const isJson = partType.startsWith(\"application/json\") || partType.includes(\"+json\");\n const serialized =\n typeof raw === \"string\"\n ? raw\n : isJson\n ? JSON.stringify(raw)\n : typeof raw === \"object\"\n ? JSON.stringify(raw)\n : String(raw);\n out[key] = new Blob([serialized], { type: partType });\n continue;\n }\n\n if (\n typeof raw === \"string\" ||\n typeof raw === \"number\" ||\n typeof raw === \"boolean\" ||\n raw instanceof Blob ||\n (typeof File !== \"undefined\" && raw instanceof File)\n ) {\n out[key] = raw as FormDataCoercible;\n continue;\n }\n if (Array.isArray(raw)) {\n out[key] = raw.map((v) =>\n typeof v === \"string\" ||\n typeof v === \"number\" ||\n typeof v === \"boolean\" ||\n v instanceof Blob ||\n (typeof File !== \"undefined\" && v instanceof File)\n ? (v as FormDataCoercible)\n : JSON.stringify(v),\n ) as FormDataCoercible;\n continue;\n }\n const bytes = toUint8Array(raw);\n if (bytes) {\n out[key] = new Blob([toArrayBuffer(bytes)]);\n continue;\n }\n out[key] = JSON.stringify(raw);\n }\n return out;\n};\n\n// ---------------------------------------------------------------------------\n// Request body dispatch\n//\n// Dispatch is driven by the spec-declared content type first, JS type of\n// the provided body second. Servers that advertise a specific content type\n// almost always reject anything else (e.g. a multipart endpoint will hang\n// waiting for valid framing if it receives `application/json`), so the\n// content type wins.\n//\n// Within each content type we accept both pre-serialized strings (user\n// already produced the wire format) and structured JS values we can\n// serialize ourselves. The last-resort fallback is `JSON.stringify(body)`\n// — never `String(body)` (which produces the useless `[object Object]`).\n// ---------------------------------------------------------------------------\n\nconst applyRequestBody = (\n request: HttpClientRequest.HttpClientRequest,\n contentType: string,\n bodyValue: unknown,\n encoding: Record<string, EncodingObject> | undefined,\n): HttpClientRequest.HttpClientRequest => {\n if (isJsonContentType(contentType)) {\n // Pre-serialized JSON strings pass through with the declared media\n // type preserved (important for `application/vnd.foo+json` etc.).\n if (typeof bodyValue === \"string\") {\n return HttpClientRequest.bodyText(request, bodyValue, contentType);\n }\n return HttpClientRequest.bodyJsonUnsafe(request, bodyValue);\n }\n\n if (isFormUrlEncoded(contentType)) {\n if (typeof bodyValue === \"string\") {\n return HttpClientRequest.bodyText(request, bodyValue, contentType);\n }\n if (typeof bodyValue === \"object\" && bodyValue !== null && !Array.isArray(bodyValue)) {\n // Serialize ourselves so OAS3 encoding (style/explode/deepObject)\n // is honored. bodyUrlParams doesn't know about per-field style.\n const serialized = serializeFormUrlEncoded(bodyValue as Record<string, unknown>, encoding);\n return HttpClientRequest.bodyText(request, serialized, contentType);\n }\n // Non-object body — fall back to platform helper (handles URLSearchParams).\n return HttpClientRequest.bodyUrlParams(\n request,\n bodyValue as Parameters<typeof HttpClientRequest.bodyUrlParams>[1],\n );\n }\n\n if (isMultipartFormData(contentType)) {\n if (bodyValue instanceof FormData) {\n return HttpClientRequest.bodyFormData(request, bodyValue);\n }\n if (typeof bodyValue === \"object\" && bodyValue !== null) {\n return HttpClientRequest.bodyFormDataRecord(\n request,\n coerceFormDataRecord(bodyValue as Record<string, unknown>, encoding),\n );\n }\n // String / primitive under multipart is almost certainly wrong on the\n // caller's end — send it as text with their declared content type and\n // let the server produce a useful error.\n return HttpClientRequest.bodyText(request, String(bodyValue), contentType);\n }\n\n if (isOctetStream(contentType)) {\n const bytes = toUint8Array(bodyValue);\n if (bytes) return HttpClientRequest.bodyUint8Array(request, bytes, contentType);\n if (typeof bodyValue === \"string\") {\n return HttpClientRequest.bodyText(request, bodyValue, contentType);\n }\n // Unknown shape — serialize as JSON so at least the payload is visible.\n return HttpClientRequest.bodyText(request, JSON.stringify(bodyValue), contentType);\n }\n\n if (isXmlContentType(contentType) || isTextContentType(contentType)) {\n if (typeof bodyValue === \"string\") {\n return HttpClientRequest.bodyText(request, bodyValue, contentType);\n }\n const bytes = toUint8Array(bodyValue);\n if (bytes) return HttpClientRequest.bodyUint8Array(request, bytes, contentType);\n // Object body under text/xml is unusual — stringify so the caller sees\n // their own payload instead of `[object Object]`.\n return HttpClientRequest.bodyText(request, JSON.stringify(bodyValue), contentType);\n }\n\n // Unknown content type: respect what the caller supplied.\n if (typeof bodyValue === \"string\") {\n return HttpClientRequest.bodyText(request, bodyValue, contentType);\n }\n const bytes = toUint8Array(bodyValue);\n if (bytes) return HttpClientRequest.bodyUint8Array(request, bytes, contentType);\n return HttpClientRequest.bodyText(request, JSON.stringify(bodyValue), contentType);\n};\n\n// ---------------------------------------------------------------------------\n// Public API — invoke a single operation\n// ---------------------------------------------------------------------------\n\nexport const invoke = Effect.fn(\"OpenApi.invoke\")(function* (\n operation: OperationBinding,\n args: Record<string, unknown>,\n resolvedHeaders: Record<string, string>,\n sourceQueryParams: Record<string, string> = {},\n) {\n const client = yield* HttpClient.HttpClient;\n\n yield* Effect.annotateCurrentSpan({\n \"http.method\": operation.method.toUpperCase(),\n \"http.route\": operation.pathTemplate,\n \"plugin.openapi.method\": operation.method.toUpperCase(),\n \"plugin.openapi.path_template\": operation.pathTemplate,\n \"plugin.openapi.headers.resolved_count\": Object.keys(resolvedHeaders).length,\n });\n\n const resolvedPath = yield* resolvePath(operation.pathTemplate, args, operation.parameters);\n\n const path = resolvedPath.startsWith(\"/\") ? resolvedPath : `/${resolvedPath}`;\n\n let request = HttpClientRequest.make(operation.method.toUpperCase() as \"GET\")(path);\n\n for (const [name, value] of Object.entries(sourceQueryParams)) {\n request = HttpClientRequest.setUrlParam(request, name, value);\n }\n\n for (const param of operation.parameters) {\n if (param.location !== \"query\") continue;\n const value = readParamValue(args, param);\n for (const paramValue of queryParamValues(value, param)) {\n request = HttpClientRequest.appendUrlParam(request, param.name, paramValue);\n }\n }\n\n for (const param of operation.parameters) {\n if (param.location !== \"header\") continue;\n const value = readParamValue(args, param);\n if (value === undefined || value === null) continue;\n request = HttpClientRequest.setHeader(request, param.name, String(value));\n }\n\n if (Option.isSome(operation.requestBody)) {\n const rb = operation.requestBody.value;\n const bodyValue = args.body ?? args.input;\n if (bodyValue !== undefined) {\n // Resolve which declared media type to use. When the spec declares\n // multiple, the caller can override via `args.contentType`; otherwise\n // we use the first-declared (spec author's preferred ordering).\n const contentsOpt = Option.getOrUndefined(rb.contents);\n const requestedCt = typeof args.contentType === \"string\" ? args.contentType : undefined;\n const selected: MediaBinding | undefined =\n contentsOpt && requestedCt\n ? contentsOpt.find((c) => c.contentType === requestedCt)\n : undefined;\n const chosenCt = selected?.contentType ?? rb.contentType;\n const chosenEncoding = selected\n ? Option.getOrUndefined(selected.encoding)\n : contentsOpt && contentsOpt[0]\n ? Option.getOrUndefined(contentsOpt[0].encoding)\n : undefined;\n request = applyRequestBody(request, chosenCt, bodyValue, chosenEncoding);\n }\n }\n\n request = applyHeaders(request, resolvedHeaders);\n\n const response = yield* client.execute(request).pipe(\n Effect.mapError(\n (err) =>\n new OpenApiInvocationError({\n message: \"HTTP request failed\",\n statusCode: Option.none(),\n cause: err,\n }),\n ),\n );\n\n const status = response.status;\n yield* Effect.annotateCurrentSpan({\n \"http.status_code\": status,\n });\n const responseHeaders: Record<string, string> = { ...response.headers };\n\n const contentType = response.headers[\"content-type\"] ?? null;\n const mapBodyError = Effect.mapError(\n (err: unknown) =>\n new OpenApiInvocationError({\n message: \"Failed to read response body\",\n statusCode: Option.some(status),\n cause: err,\n }),\n );\n const responseBodyBinding = Option.getOrUndefined(operation.responseBody);\n const fileHint = responseBodyBinding\n ? Option.getOrUndefined(responseBodyBinding.fileHint)\n : undefined;\n const ok = status >= 200 && status < 300;\n const responseBody: unknown =\n status === 204\n ? null\n : ok && fileHint?.kind === \"binaryResponse\"\n ? fileFromBinaryBytes(\n new Uint8Array(yield* response.arrayBuffer.pipe(mapBodyError)),\n fileHint,\n contentType,\n )\n : isJsonContentType(contentType)\n ? yield* response.json.pipe(\n Effect.catch(() => response.text),\n mapBodyError,\n )\n : yield* response.text.pipe(mapBodyError);\n\n const dataBody =\n ok && fileHint?.kind === \"byteField\"\n ? (fileFromByteField(responseBody, fileHint) ?? responseBody)\n : responseBody;\n return InvocationResult.make({\n status,\n headers: responseHeaders,\n data: ok ? dataBody : null,\n error: ok ? null : responseBody,\n });\n});\n\n// Connection `baseUrl` wins; otherwise the call's chosen server (`server.url`, or\n// the first) resolved with its `{variables}` (call values, else spec defaults).\nconst resolveRequestHost = (\n servers: readonly ServerInfo[],\n serverArg: unknown,\n baseUrl: string,\n): string => {\n if (baseUrl) return baseUrl;\n if (servers.length === 0) return \"\";\n\n const arg = (\n typeof serverArg === \"object\" && serverArg !== null && !Array.isArray(serverArg)\n ? serverArg\n : {}\n ) as { url?: unknown; variables?: unknown };\n const chosen = servers.find((server) => server.url === arg.url) ?? servers[0]!;\n\n const overrides: Record<string, string> = {};\n if (typeof arg.variables === \"object\" && arg.variables !== null) {\n for (const [name, value] of Object.entries(arg.variables as Record<string, unknown>)) {\n if (value != null && value !== \"\") overrides[name] = String(value);\n }\n }\n return resolveServerUrl(chosen.url, Option.getOrUndefined(chosen.variables), overrides);\n};\n\n// ---------------------------------------------------------------------------\n// Invoke with a provided HttpClient layer + per-call host resolution\n// ---------------------------------------------------------------------------\n\nexport const invokeWithLayer = (\n operation: OperationBinding,\n args: Record<string, unknown>,\n baseUrl: string,\n resolvedHeaders: Record<string, string>,\n sourceQueryParams: Record<string, string>,\n httpClientLayer: Layer.Layer<HttpClient.HttpClient, never, never>,\n) => {\n const effectiveBaseUrl = resolveRequestHost(operation.servers ?? [], args.server, baseUrl);\n const clientWithBaseUrl = effectiveBaseUrl\n ? Layer.effect(\n HttpClient.HttpClient,\n Effect.map(\n Effect.service(HttpClient.HttpClient),\n HttpClient.mapRequest(HttpClientRequest.prependUrl(effectiveBaseUrl)),\n ),\n ).pipe(Layer.provide(httpClientLayer))\n : httpClientLayer;\n\n return invoke(operation, args, resolvedHeaders, sourceQueryParams).pipe(\n Effect.provide(clientWithBaseUrl),\n // `invoke` annotates http.status_code on ITS span (`OpenApi.invoke`,\n // via Effect.fn) — annotateCurrentSpan inside it never reaches this\n // wrapper span. Stamp the status here too so queries against\n // `plugin.openapi.invoke` see the upstream outcome directly.\n Effect.tap((result) => Effect.annotateCurrentSpan({ \"http.status_code\": result.status })),\n Effect.withSpan(\"plugin.openapi.invoke\", {\n attributes: {\n \"plugin.openapi.method\": operation.method.toUpperCase(),\n \"plugin.openapi.path_template\": operation.pathTemplate,\n \"plugin.openapi.base_url\": effectiveBaseUrl,\n },\n }),\n );\n};\n\n// ---------------------------------------------------------------------------\n// Derive annotations from HTTP method\n// ---------------------------------------------------------------------------\n\nconst REQUIRE_APPROVAL = new Set([\"post\", \"put\", \"patch\", \"delete\"]);\n\nexport const annotationsForOperation = (\n method: string,\n pathTemplate: string,\n): { requiresApproval?: boolean; approvalDescription?: string } => {\n const m = method.toLowerCase();\n if (!REQUIRE_APPROVAL.has(m)) return {};\n return {\n requiresApproval: true,\n approvalDescription: `${method.toUpperCase()} ${pathTemplate}`,\n };\n};\n","import { Effect, Option, Predicate, Schema } from \"effect\";\n\nimport {\n type PluginStorageEntry,\n type StorageDeps,\n type StorageFailure,\n} from \"@executor-js/sdk/core\";\n\nimport { OperationBinding } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// OpenAPI plugin store (v2). The catalog row (integration.config) owns the\n// auth templates plus the spec's content hash; the resolved spec text itself\n// lives in the plugin blob store under `spec/<hash>` (it's multi-MB and only\n// a build input). This store keeps the per-operation invocation bindings\n// (method / path / params), keyed by integration slug, so `invokeTool` can map\n// a tool name back to its HTTP operation without re-parsing the spec on every\n// call. There are NO credential bindings, slots, or StoredSource credential\n// config here — those concepts are gone in v2.\n//\n// Operations are spec-derived (identical for every connection on an\n// integration), so they live under the org owner (the integration catalog is\n// tenant-level). The plugin storage facade partitions by owner; \"org\" keeps a\n// single shared copy per integration.\n// ---------------------------------------------------------------------------\n\nconst OPERATION_COLLECTION = \"operation\";\nconst STORE_OWNER = \"org\" as const;\n\nconst encodeBinding = Schema.encodeSync(OperationBinding);\nconst decodeBinding = Schema.decodeUnknownSync(OperationBinding);\nconst decodeBindingJson = Schema.decodeUnknownSync(Schema.fromJsonString(OperationBinding));\n\nconst toJsonRecord = (value: unknown): Record<string, unknown> => value as Record<string, unknown>;\n\nconst OperationStorage = Schema.Struct({\n integration: Schema.String,\n toolName: Schema.String,\n binding: Schema.Unknown,\n});\nconst decodeOperationStorage = Schema.decodeUnknownOption(OperationStorage);\n\nexport interface StoredOperation {\n /** The integration slug this operation belongs to. */\n readonly integration: string;\n /** The tool name (the `<tool>` address segment) this operation backs. */\n readonly toolName: string;\n readonly binding: OperationBinding;\n}\n\nconst rowToOperation = (row: PluginStorageEntry): StoredOperation | null => {\n const decoded = decodeOperationStorage(row.data);\n if (Option.isNone(decoded)) return null;\n const operation = decoded.value;\n return {\n integration: operation.integration,\n toolName: operation.toolName,\n binding: decodeBinding(\n typeof operation.binding === \"string\"\n ? decodeBindingJson(operation.binding)\n : operation.binding,\n ),\n };\n};\n\nconst operationKey = (integration: string, toolName: string): string =>\n `${integration}.${toolName}`;\n\n/** Blob key for a spec's content hash. Content-addressed so re-puts are\n * idempotent and identical specs share one blob per partition. */\nexport const specBlobKey = (specHash: string): string => `spec/${specHash}`;\n\nexport interface OpenapiStore {\n /** Replace all stored operations for an integration. */\n readonly putOperations: (\n integration: string,\n operations: readonly StoredOperation[],\n ) => Effect.Effect<void, StorageFailure>;\n /** Look up one operation by integration + tool name. */\n readonly getOperation: (\n integration: string,\n toolName: string,\n ) => Effect.Effect<StoredOperation | null, StorageFailure>;\n /** List every stored operation for an integration. */\n readonly listOperations: (\n integration: string,\n ) => Effect.Effect<readonly StoredOperation[], StorageFailure>;\n /** Drop all stored operations for an integration. */\n readonly removeOperations: (integration: string) => Effect.Effect<void, StorageFailure>;\n /** Persist resolved spec text under its content hash. Org-owned and\n * content-addressed; never removed on integration removal because another\n * integration in the tenant may share the hash. */\n readonly putSpec: (specHash: string, specText: string) => Effect.Effect<void, StorageFailure>;\n /** Load spec text by content hash; null when no blob exists. */\n readonly getSpec: (specHash: string) => Effect.Effect<string | null, StorageFailure>;\n}\n\nexport const makeDefaultOpenapiStore = ({ pluginStorage, blobs }: StorageDeps): OpenapiStore => {\n const operationData = (operation: StoredOperation) => ({\n integration: operation.integration,\n toolName: operation.toolName,\n binding: toJsonRecord(encodeBinding(operation.binding)),\n });\n\n const listRows = (integration: string) =>\n pluginStorage\n .list({ collection: OPERATION_COLLECTION, keyPrefix: `${integration}.` })\n .pipe(\n Effect.map((rows: readonly PluginStorageEntry[]) =>\n rows.filter((row) => rowToOperation(row)?.integration === integration),\n ),\n );\n\n const removeOperations = (integration: string) =>\n Effect.gen(function* () {\n const rows = yield* listRows(integration);\n yield* pluginStorage.removeMany({\n owner: STORE_OWNER,\n entries: rows.map((row) => ({ collection: OPERATION_COLLECTION, key: row.key })),\n });\n });\n\n return {\n putOperations: (integration, operations) =>\n Effect.gen(function* () {\n yield* removeOperations(integration);\n yield* pluginStorage.putMany({\n owner: STORE_OWNER,\n entries: operations.map((operation) => ({\n collection: OPERATION_COLLECTION,\n key: operationKey(integration, operation.toolName),\n data: operationData(operation),\n })),\n });\n }),\n\n getOperation: (integration, toolName) =>\n pluginStorage\n .get({ collection: OPERATION_COLLECTION, key: operationKey(integration, toolName) })\n .pipe(Effect.map((row) => (row ? rowToOperation(row) : null))),\n\n listOperations: (integration) =>\n listRows(integration).pipe(\n Effect.map((rows) => rows.map(rowToOperation).filter(Predicate.isNotNull)),\n ),\n\n removeOperations,\n\n putSpec: (specHash, specText) =>\n blobs.put(specBlobKey(specHash), specText, { owner: STORE_OWNER }),\n\n getSpec: (specHash) => blobs.get(specBlobKey(specHash)),\n };\n};\n","import { Effect, Option, Schema } from \"effect\";\nimport type { Layer } from \"effect\";\nimport { HttpClient } from \"effect/unstable/http\";\n\nimport {\n IntegrationAlreadyExistsError,\n IntegrationDetectionResult,\n IntegrationNotFoundError,\n IntegrationSlug,\n ToolName,\n ToolFileJsonSchema,\n ToolResult,\n authToolFailure,\n definePlugin,\n mergeAuthTemplates,\n sha256Hex,\n tool,\n type AuthMethodDescriptor,\n type Integration,\n type IntegrationConfig,\n type IntegrationRecord,\n type PluginCtx,\n type ResolveToolsResult,\n type StorageFailure,\n type ToolDef,\n type ToolInvocationCredential,\n} from \"@executor-js/sdk/core\";\n\nimport {\n decodeOpenApiIntegrationConfig,\n renderAuthTemplate,\n requiredTemplateVariables,\n type OpenApiIntegrationConfig,\n} from \"./config\";\nimport { OpenApiExtractionError, OpenApiOAuthError, OpenApiParseError } from \"./errors\";\nimport { parse, resolveSpecText } from \"./parse\";\nimport {\n convertGoogleDiscoveryBundleToOpenApi,\n convertGoogleDiscoveryToOpenApi,\n fetchGoogleDiscoveryDocument,\n isGoogleDiscoveryUrl,\n} from \"./google-discovery\";\nimport { extract } from \"./extract\";\nimport { compileToolDefinitions, type ToolDefinition } from \"./definitions\";\nimport { annotationsForOperation, invokeWithLayer } from \"./invoke\";\nimport { previewSpec, previewSpecText, type SpecPreview } from \"./preview\";\nimport { deriveAuthenticationTemplateFromPreview, firstBaseUrlForPreview } from \"./derive-auth\";\nimport { openApiPresets } from \"./presets\";\nimport { makeDefaultOpenapiStore, type OpenapiStore, type StoredOperation } from \"./store\";\nimport type { Authentication } from \"./types\";\nimport { OperationBinding, normalizeOpenApiAuthInputs, type AuthenticationInput } from \"./types\";\nimport { ApiKeyAuthTemplate, describeApiKeyAuthMethod } from \"@executor-js/sdk/http-auth\";\n\n// ---------------------------------------------------------------------------\n// Plugin config\n// ---------------------------------------------------------------------------\n\nconst STRINGIFIED_BODY_CAP = 1024;\nconst UpstreamMessageBody = Schema.Struct({ message: Schema.String });\nconst UpstreamErrorMessageBody = Schema.Struct({ errorMessage: Schema.String });\nconst UpstreamNestedErrorBody = Schema.Struct({ error: UpstreamMessageBody });\nconst UpstreamErrorsArrayBody = Schema.Struct({\n errors: Schema.Array(\n Schema.Struct({\n detail: Schema.optional(Schema.String),\n message: Schema.optional(Schema.String),\n title: Schema.optional(Schema.String),\n }),\n ),\n});\nconst UpstreamDescriptionBody = Schema.Struct({\n detail: Schema.optional(Schema.String),\n title: Schema.optional(Schema.String),\n description: Schema.optional(Schema.String),\n});\n\nconst decodeUpstreamMessageBody = Schema.decodeUnknownOption(UpstreamMessageBody);\nconst decodeUpstreamErrorMessageBody = Schema.decodeUnknownOption(UpstreamErrorMessageBody);\nconst decodeUpstreamNestedErrorBody = Schema.decodeUnknownOption(UpstreamNestedErrorBody);\nconst decodeUpstreamErrorsArrayBody = Schema.decodeUnknownOption(UpstreamErrorsArrayBody);\nconst decodeUpstreamDescriptionBody = Schema.decodeUnknownOption(UpstreamDescriptionBody);\n\nconst clampedStringify = (value: unknown): string => {\n let s: string;\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: JSON.stringify may throw on cycles; fall back to String() so the upstream body can still be surfaced as ToolError.details fallback text\n try {\n s = JSON.stringify(value);\n } catch {\n s = String(value);\n }\n return s.length > STRINGIFIED_BODY_CAP ? `${s.slice(0, STRINGIFIED_BODY_CAP)}…` : s;\n};\n\nconst firstNonEmpty = (...values: readonly (string | undefined)[]): string | undefined =>\n values.find((value) => value !== undefined && value.length > 0);\n\n// Walk known upstream error-body shapes so ToolError.message stays concise\n// while ToolError.details preserves the original body.\nconst extractUpstreamMessage = (body: unknown, status: number): string => {\n if (typeof body === \"string\") {\n return body.length > 0 ? body : `Upstream returned HTTP ${status}`;\n }\n const nested = Option.getOrUndefined(decodeUpstreamNestedErrorBody(body));\n const messageBody = Option.getOrUndefined(decodeUpstreamMessageBody(body));\n const errorMessageBody = Option.getOrUndefined(decodeUpstreamErrorMessageBody(body));\n const errorsBody = Option.getOrUndefined(decodeUpstreamErrorsArrayBody(body));\n const descriptionBody = Option.getOrUndefined(decodeUpstreamDescriptionBody(body));\n const arrayMessage = errorsBody?.errors\n .map(\n ({\n detail,\n message: upstreamMessage,\n title,\n }: {\n detail?: string;\n message?: string;\n title?: string;\n }) => firstNonEmpty(detail, upstreamMessage, title),\n )\n .find((message: string | undefined) => message !== undefined);\n const message = firstNonEmpty(\n nested?.error.message,\n messageBody?.message,\n errorMessageBody?.errorMessage,\n arrayMessage,\n descriptionBody?.detail,\n descriptionBody?.title,\n descriptionBody?.description,\n );\n if (message !== undefined) return message;\n if (body !== null && typeof body === \"object\") {\n return clampedStringify(body);\n }\n return `Upstream returned HTTP ${status}`;\n};\n\n// ---------------------------------------------------------------------------\n// Extension input shapes\n// ---------------------------------------------------------------------------\n\nexport type OpenApiSpecInput = typeof OpenApiSpecInputSchema.Type;\n\nexport interface OpenApiPreviewInput {\n readonly spec: string;\n}\n\n/** Add an OpenAPI integration to the catalog. The integration is the API\n * surface; connections (the credentials) are attached separately and resolve\n * their value through the declared `authenticationTemplate`. */\nexport interface OpenApiSpecConfig {\n readonly spec: OpenApiSpecInput;\n /** The catalog slug for the new integration (the `<integration>` segment). */\n readonly slug: string;\n /** Display name (defaults to the spec title). */\n readonly name?: string;\n /** Agent-visible description (defaults to the spec's `info.description`,\n * then the title). */\n readonly description?: string;\n readonly baseUrl?: string;\n /** Static headers applied to every request (no secret material). */\n readonly headers?: Record<string, string>;\n /** Static query params applied to every request. */\n readonly queryParams?: Record<string, string>;\n /** Auth methods a connection's value renders through — canonical\n * placements or the request-shaped authoring dialect. */\n readonly authenticationTemplate?: readonly AuthenticationInput[];\n}\n\nexport interface OpenApiExtensionFailure {\n readonly _tag: string;\n}\n\n/** Add / merge custom auth methods onto an existing OpenAPI integration's\n * `authenticationTemplate`. Mirrors the GraphQL plugin's `configure`. */\nexport interface OpenApiConfigureInput {\n /** The auth methods to add. Each entry is appended to (or, when its `slug`\n * already exists, replaces) the integration's existing template array. A\n * custom apiKey method with no `slug` is assigned a generated `custom_<id>`\n * slug that is collision-checked against the existing template. */\n readonly authenticationTemplate: readonly AuthenticationInput[];\n readonly mode?: \"merge\" | \"replace\";\n}\n\n/** What changed in the tool catalog when a spec was updated in place. Tool\n * names, not addresses — the same diff applies to every connection. */\nexport interface UpdateSpecResult {\n readonly slug: IntegrationSlug;\n readonly toolCount: number;\n readonly addedTools: readonly string[];\n readonly removedTools: readonly string[];\n}\n\nexport interface OpenApiUpdateSpecInput {\n /** New spec source. Omit to re-fetch from the integration's stored\n * `sourceUrl` / Google Discovery bundle URLs. */\n readonly spec?: OpenApiSpecInput;\n}\n\nexport interface OpenApiPluginExtension {\n readonly previewSpec: (\n input: string | OpenApiPreviewInput,\n ) => Effect.Effect<\n SpecPreview,\n OpenApiParseError | OpenApiExtractionError | OpenApiOAuthError | StorageFailure\n >;\n readonly addSpec: (\n config: OpenApiSpecConfig,\n ) => Effect.Effect<\n { readonly slug: IntegrationSlug; readonly toolCount: number },\n | OpenApiParseError\n | OpenApiExtractionError\n | OpenApiOAuthError\n | IntegrationAlreadyExistsError\n | StorageFailure\n >;\n /** Re-resolve the integration's spec (from its stored source URL, or the\n * provided input) and rebuild its tools IN PLACE — connections,\n * credentials, policies, and the curated description are untouched. */\n readonly updateSpec: (\n slug: string,\n input?: OpenApiUpdateSpecInput,\n ) => Effect.Effect<\n UpdateSpecResult,\n | OpenApiParseError\n | OpenApiExtractionError\n | OpenApiOAuthError\n | IntegrationNotFoundError\n | StorageFailure\n >;\n readonly removeSpec: (slug: string) => Effect.Effect<void, StorageFailure>;\n readonly getIntegration: (slug: string) => Effect.Effect<Integration | null, StorageFailure>;\n /** Read the integration's full opaque config, including its\n * `authenticationTemplate`. Returns null when the integration is absent. */\n readonly getConfig: (\n slug: string,\n ) => Effect.Effect<OpenApiIntegrationConfig | null, StorageFailure>;\n /** Add / merge custom auth methods onto the integration's\n * `authenticationTemplate`. Returns the resulting template array. */\n readonly configure: (\n slug: string,\n input: OpenApiConfigureInput,\n ) => Effect.Effect<readonly Authentication[], StorageFailure>;\n}\n\n// ---------------------------------------------------------------------------\n// Control-tool input/output schemas\n// ---------------------------------------------------------------------------\n\nconst PreviewSpecInputSchema = Schema.Struct({\n spec: Schema.String,\n});\n\nconst StaticPreviewServerVariableSchema = Schema.Struct({\n default: Schema.String,\n enum: Schema.NullOr(Schema.Array(Schema.String)),\n description: Schema.NullOr(Schema.String),\n});\nconst StaticPreviewServerSchema = Schema.Struct({\n url: Schema.String,\n description: Schema.NullOr(Schema.String),\n variables: Schema.NullOr(Schema.Record(Schema.String, StaticPreviewServerVariableSchema)),\n});\nconst StaticPreviewOAuthAuthorizationCodeFlowSchema = Schema.Struct({\n authorizationUrl: Schema.String,\n tokenUrl: Schema.String,\n refreshUrl: Schema.NullOr(Schema.String),\n scopes: Schema.Record(Schema.String, Schema.String),\n});\nconst StaticPreviewOAuthClientCredentialsFlowSchema = Schema.Struct({\n tokenUrl: Schema.String,\n refreshUrl: Schema.NullOr(Schema.String),\n scopes: Schema.Record(Schema.String, Schema.String),\n});\nconst StaticPreviewOAuthFlowsSchema = Schema.Struct({\n authorizationCode: Schema.NullOr(StaticPreviewOAuthAuthorizationCodeFlowSchema),\n clientCredentials: Schema.NullOr(StaticPreviewOAuthClientCredentialsFlowSchema),\n});\nconst StaticPreviewSecuritySchemeSchema = Schema.Struct({\n name: Schema.String,\n type: Schema.Literals([\"http\", \"apiKey\", \"oauth2\", \"openIdConnect\"]),\n scheme: Schema.NullOr(Schema.String),\n bearerFormat: Schema.NullOr(Schema.String),\n in: Schema.NullOr(Schema.Literals([\"header\", \"query\", \"cookie\"])),\n headerName: Schema.NullOr(Schema.String),\n description: Schema.NullOr(Schema.String),\n flows: Schema.NullOr(StaticPreviewOAuthFlowsSchema),\n openIdConnectUrl: Schema.NullOr(Schema.String),\n});\nconst StaticPreviewOAuth2PresetSchema = Schema.Struct({\n label: Schema.String,\n securitySchemeName: Schema.String,\n flow: Schema.Literals([\"authorizationCode\", \"clientCredentials\"]),\n authorizationUrl: Schema.NullOr(Schema.String),\n tokenUrl: Schema.String,\n refreshUrl: Schema.NullOr(Schema.String),\n scopes: Schema.Record(Schema.String, Schema.String),\n identityScopes: Schema.Union([\n Schema.Literal(\"auto\"),\n Schema.Literal(false),\n Schema.Array(Schema.String),\n ]),\n});\nconst StaticPreviewSpecOutputSchema = Schema.Struct({\n title: Schema.NullOr(Schema.String),\n version: Schema.NullOr(Schema.String),\n servers: Schema.Array(StaticPreviewServerSchema),\n operationCount: Schema.Number,\n tags: Schema.Array(Schema.String),\n securitySchemes: Schema.Array(StaticPreviewSecuritySchemeSchema),\n authStrategies: Schema.Array(Schema.Struct({ schemes: Schema.Array(Schema.String) })),\n headerPresets: Schema.Array(\n Schema.Struct({\n label: Schema.String,\n headers: Schema.Record(Schema.String, Schema.NullOr(Schema.String)),\n secretHeaders: Schema.Array(Schema.String),\n }),\n ),\n oauth2Presets: Schema.Array(StaticPreviewOAuth2PresetSchema),\n});\ntype StaticPreviewSpecOutput = typeof StaticPreviewSpecOutputSchema.Type;\n\nconst OpenApiSpecInputSchema = 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 AuthenticationSchema = Schema.Union([\n 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 // Credential methods are authored request-shaped — the ONE apikey input\n // dialect: `{ type: \"apiKey\", headers: { Authorization: [\"Bearer \",\n // variable(\"token\")] }, queryParams: { … } }`.\n ApiKeyAuthTemplate,\n]);\n\nconst AddSourceInputSchema = Schema.Struct({\n spec: OpenApiSpecInputSchema,\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(AuthenticationSchema)),\n});\n\nconst AddSourceOutputSchema = Schema.Struct({\n slug: Schema.String,\n toolCount: Schema.Number,\n});\n\nconst PreviewSpecInputStandardSchema = Schema.toStandardSchemaV1(\n Schema.toStandardJSONSchemaV1(PreviewSpecInputSchema),\n);\nconst PreviewSpecOutputStandardSchema = Schema.toStandardSchemaV1(\n Schema.toStandardJSONSchemaV1(StaticPreviewSpecOutputSchema),\n);\nconst AddSourceInputStandardSchema = Schema.toStandardSchemaV1(\n Schema.toStandardJSONSchemaV1(AddSourceInputSchema),\n);\nconst AddSourceOutputStandardSchema = Schema.toStandardSchemaV1(\n Schema.toStandardJSONSchemaV1(AddSourceOutputSchema),\n);\n\nconst openApiToolFailure = (code: string, message: string, details?: unknown) =>\n ToolResult.fail({\n code,\n message,\n ...(details === undefined ? {} : { details }),\n });\n\nconst openApiAuthToolFailure = (failure: {\n readonly code: string;\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}) =>\n authToolFailure({\n // The auth-tool-failure helper's code set is shared with v1; keep the\n // string but reference the connection rather than v1's source/slot.\n code: failure.code as Parameters<typeof authToolFailure>[0][\"code\"],\n message: failure.message,\n source: { id: failure.integration, scope: failure.owner },\n credential: {\n kind: failure.credentialKind,\n ...(failure.credentialLabel ? { label: failure.credentialLabel } : {}),\n },\n ...(failure.status !== undefined ? { status: failure.status } : {}),\n ...(failure.details !== undefined\n ? {\n upstream: {\n ...(failure.status !== undefined ? { status: failure.status } : {}),\n details: failure.details,\n },\n }\n : {}),\n });\n\nconst staticPreviewOutput = (preview: SpecPreview): StaticPreviewSpecOutput => ({\n title: Option.getOrNull(preview.title),\n version: Option.getOrNull(preview.version),\n servers: preview.servers.map((server) => ({\n url: server.url,\n description: Option.getOrNull(server.description),\n variables: Option.getOrNull(server.variables)\n ? Object.fromEntries(\n Object.entries(Option.getOrNull(server.variables) ?? {}).map(([name, variable]) => [\n name,\n {\n default: variable.default,\n enum: Option.getOrNull(variable.enum),\n description: Option.getOrNull(variable.description),\n },\n ]),\n )\n : null,\n })),\n operationCount: preview.operationCount,\n tags: preview.tags,\n securitySchemes: preview.securitySchemes.map((scheme) => ({\n name: scheme.name,\n type: scheme.type,\n scheme: Option.getOrNull(scheme.scheme),\n bearerFormat: Option.getOrNull(scheme.bearerFormat),\n in: Option.getOrNull(scheme.in),\n headerName: Option.getOrNull(scheme.headerName),\n description: Option.getOrNull(scheme.description),\n flows: Option.isSome(scheme.flows)\n ? {\n authorizationCode: Option.isSome(scheme.flows.value.authorizationCode)\n ? {\n authorizationUrl: scheme.flows.value.authorizationCode.value.authorizationUrl,\n tokenUrl: scheme.flows.value.authorizationCode.value.tokenUrl,\n refreshUrl: Option.getOrNull(scheme.flows.value.authorizationCode.value.refreshUrl),\n scopes: scheme.flows.value.authorizationCode.value.scopes,\n }\n : null,\n clientCredentials: Option.isSome(scheme.flows.value.clientCredentials)\n ? {\n tokenUrl: scheme.flows.value.clientCredentials.value.tokenUrl,\n refreshUrl: Option.getOrNull(scheme.flows.value.clientCredentials.value.refreshUrl),\n scopes: scheme.flows.value.clientCredentials.value.scopes,\n }\n : null,\n }\n : null,\n openIdConnectUrl: Option.getOrNull(scheme.openIdConnectUrl),\n })),\n authStrategies: preview.authStrategies,\n headerPresets: preview.headerPresets,\n oauth2Presets: preview.oauth2Presets.map((preset) => ({\n label: preset.label,\n securitySchemeName: preset.securitySchemeName,\n flow: preset.flow,\n authorizationUrl: Option.getOrNull(preset.authorizationUrl),\n tokenUrl: preset.tokenUrl,\n refreshUrl: Option.getOrNull(preset.refreshUrl),\n scopes: preset.scopes,\n identityScopes: preset.identityScopes,\n })),\n});\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Rewrite OpenAPI `#/components/schemas/X` refs to standard `#/$defs/X`. */\nconst normalizeOpenApiRefs = (node: unknown): unknown => {\n if (node == null || typeof node !== \"object\") return node;\n if (Array.isArray(node)) {\n let changed = false;\n const out = node.map((item) => {\n const n = normalizeOpenApiRefs(item);\n if (n !== item) changed = true;\n return n;\n });\n return changed ? out : node;\n }\n\n const obj = node as Record<string, unknown>;\n\n if (typeof obj.$ref === \"string\") {\n const match = obj.$ref.match(/^#\\/components\\/schemas\\/(.+)$/);\n if (match) return { ...obj, $ref: `#/$defs/${match[1]}` };\n return obj;\n }\n\n let changed = false;\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) {\n const n = normalizeOpenApiRefs(v);\n if (n !== v) changed = true;\n result[k] = n;\n }\n return changed ? result : obj;\n};\n\nconst toBinding = (def: ToolDefinition): OperationBinding =>\n OperationBinding.make({\n method: def.operation.method,\n servers: def.operation.servers,\n pathTemplate: def.operation.pathTemplate,\n parameters: [...def.operation.parameters],\n requestBody: def.operation.requestBody,\n responseBody: def.operation.responseBody,\n });\n\nconst descriptionFor = (def: ToolDefinition): string => {\n const op = def.operation;\n return Option.getOrElse(op.description, () =>\n Option.getOrElse(op.summary, () => `${op.method.toUpperCase()} ${op.pathTemplate}`),\n );\n};\n\nconst specInputToSourceUrl = (spec: OpenApiSpecInput): string | undefined =>\n spec.kind === \"url\" || spec.kind === \"googleDiscovery\" ? spec.url : undefined;\n\nconst specInputToGoogleBundle = (spec: OpenApiSpecInput): readonly string[] | undefined =>\n spec.kind === \"googleDiscoveryBundle\" ? spec.urls : undefined;\n\n// ---------------------------------------------------------------------------\n// Declared auth methods — project the stored `authenticationTemplate` into the\n// catalog's plugin-agnostic `AuthMethodDescriptor[]`. This mirrors the client's\n// `authMethodsFromConfig` (in the React auth-method-config module) on the\n// server so the catalog field is consistent. apikey/none projection comes from\n// the shared model; the oauth method carries the stored endpoints + scopes.\n// ---------------------------------------------------------------------------\n\nexport const describeOpenApiAuthMethods = (\n record: IntegrationRecord,\n): readonly AuthMethodDescriptor[] => {\n const config = decodeOpenApiIntegrationConfig(record.config);\n if (!config) return [];\n return (config.authenticationTemplate ?? []).map(\n (template: Authentication): AuthMethodDescriptor => {\n if (template.kind === \"oauth2\") {\n return {\n id: String(template.slug),\n label: \"OAuth2\",\n kind: \"oauth\",\n template: String(template.slug),\n oauth: {\n authorizationUrl: template.authorizationUrl,\n tokenUrl: template.tokenUrl,\n scopes: template.scopes,\n },\n };\n }\n return describeApiKeyAuthMethod(template);\n },\n );\n};\n\nexport const describeOpenApiIntegrationDisplay = (\n record: IntegrationRecord,\n): { readonly url?: string } => {\n const config = decodeOpenApiIntegrationConfig(record.config);\n return { url: config?.baseUrl ?? config?.sourceUrl };\n};\n\n// ---------------------------------------------------------------------------\n// Spec text resolution — the stored config carries the spec's content hash\n// (`specHash` → blob `spec/<hash>`). Pre-blob rows that inlined the text are\n// rewritten by the spec-to-blob migrations before this code reads them.\n// ---------------------------------------------------------------------------\n\nconst loadSpecText = (\n storage: OpenapiStore,\n config: OpenApiIntegrationConfig,\n): Effect.Effect<string | null, StorageFailure> =>\n config.specHash != null ? storage.getSpec(config.specHash) : Effect.succeed(null);\n\n// ---------------------------------------------------------------------------\n// Spec → tool definitions (shared by addSpec, resolveTools, and detect)\n// ---------------------------------------------------------------------------\n\ninterface CompiledSpec {\n readonly definitions: readonly ToolDefinition[];\n readonly hoistedDefs: Record<string, unknown>;\n readonly title: string | undefined;\n /** The spec's `info.description`. */\n readonly description: string | undefined;\n}\n\nconst compileSpec = (\n specText: string,\n): Effect.Effect<CompiledSpec, OpenApiParseError | OpenApiExtractionError> =>\n Effect.gen(function* () {\n const doc = yield* parse(specText);\n const result = yield* extract(doc);\n const hoistedDefs: Record<string, unknown> = {};\n if (doc.components?.schemas) {\n for (const [k, v] of Object.entries(doc.components.schemas)) {\n hoistedDefs[k] = normalizeOpenApiRefs(v);\n }\n }\n return {\n definitions: compileToolDefinitions(result.operations),\n hoistedDefs,\n title: Option.getOrUndefined(result.title),\n description: Option.getOrUndefined(result.description),\n };\n });\n\n// A tool's name carries its structured `group.leaf` path verbatim (e.g.\n// `aliases.deleteAlias`). The address grammar\n// `tools.<integration>.<owner>.<connection>.<tool>` treats `<tool>` as the\n// trailing remainder (see parseToolAddress), so the dotted path needs no\n// flattening — it nests naturally as\n// `tools.<integration>.<owner>.<connection>.aliases.deleteAlias`, matching how\n// the sandbox `tools` proxy joins property access.\n\nconst toolDefsFromCompiled = (compiled: CompiledSpec): readonly ToolDef[] =>\n compiled.definitions.map(\n (def): ToolDef => ({\n name: ToolName.make(def.toolPath),\n description: descriptionFor(def),\n inputSchema: normalizeOpenApiRefs(Option.getOrUndefined(def.operation.inputSchema)),\n // The output schema is the upstream response body only — transport\n // status/headers live in the ToolResult `http` side channel, not the\n // payload (see the invoke handler).\n outputSchema: Option.match(def.operation.responseBody, {\n onNone: () => normalizeOpenApiRefs(Option.getOrUndefined(def.operation.outputSchema)),\n onSome: (responseBody) =>\n Option.isSome(responseBody.fileHint)\n ? ToolFileJsonSchema\n : normalizeOpenApiRefs(Option.getOrUndefined(def.operation.outputSchema)),\n }),\n annotations: annotationsForOperation(def.operation.method, def.operation.pathTemplate),\n }),\n );\n\nconst storedOperationsFromCompiled = (\n integration: string,\n compiled: CompiledSpec,\n): readonly StoredOperation[] =>\n compiled.definitions.map((def) => ({\n integration,\n toolName: def.toolPath,\n binding: toBinding(def),\n }));\n\n// ---------------------------------------------------------------------------\n// Plugin factory\n// ---------------------------------------------------------------------------\n\nexport interface OpenApiPluginOptions {\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient, never, never>;\n}\n\nconst fetchGoogleDiscoveryBundleConversion = (\n urls: readonly string[],\n httpClientLayer: Layer.Layer<HttpClient.HttpClient, never, never>,\n) =>\n Effect.forEach(\n urls,\n (url) =>\n fetchGoogleDiscoveryDocument(url).pipe(\n Effect.provide(httpClientLayer),\n Effect.map((documentText) => ({ discoveryUrl: url, documentText })),\n ),\n { concurrency: 4 },\n ).pipe(Effect.flatMap((documents) => convertGoogleDiscoveryBundleToOpenApi({ documents })));\n\nexport const openApiPlugin = definePlugin((options?: OpenApiPluginOptions) => {\n const resolveSpecForInput = (\n spec: OpenApiSpecInput,\n httpClientLayer: Layer.Layer<HttpClient.HttpClient, never, never>,\n ): Effect.Effect<\n {\n readonly specText: string;\n readonly baseUrl?: string;\n // The Google Discovery converters derive the `googleOAuth2` oauth template\n // straight from the spec's declared scopes. `addSpec` adopts it when the\n // caller didn't pass an explicit `authenticationTemplate` (the bundle add\n // path has no preview to detect auth from).\n readonly authenticationTemplate?: readonly Authentication[];\n },\n OpenApiParseError | OpenApiExtractionError | OpenApiOAuthError\n > =>\n Effect.gen(function* () {\n if (spec.kind === \"googleDiscovery\") {\n const conversion = yield* fetchGoogleDiscoveryDocument(spec.url).pipe(\n Effect.provide(httpClientLayer),\n Effect.flatMap((documentText) =>\n convertGoogleDiscoveryToOpenApi({\n discoveryUrl: spec.url,\n documentText,\n }),\n ),\n );\n return {\n specText: conversion.specText,\n baseUrl: conversion.baseUrl,\n ...(conversion.authenticationTemplate\n ? { authenticationTemplate: conversion.authenticationTemplate }\n : {}),\n };\n }\n if (spec.kind === \"googleDiscoveryBundle\") {\n const conversion = yield* fetchGoogleDiscoveryBundleConversion(spec.urls, httpClientLayer);\n return {\n specText: conversion.specText,\n baseUrl: conversion.baseUrl,\n ...(conversion.authenticationTemplate\n ? { authenticationTemplate: conversion.authenticationTemplate }\n : {}),\n };\n }\n if (spec.kind === \"url\") {\n const specText = yield* resolveSpecText(spec.url).pipe(Effect.provide(httpClientLayer));\n return { specText };\n }\n return { specText: spec.value };\n });\n\n return {\n id: \"openapi\" as const,\n packageName: \"@executor-js/plugin-openapi\",\n integrationPresets: openApiPresets.map((preset) => ({\n id: preset.id,\n name: preset.name,\n summary: preset.summary,\n ...(preset.url ? { url: preset.url } : {}),\n ...(preset.icon ? { icon: preset.icon } : {}),\n ...(preset.featured ? { featured: preset.featured } : {}),\n })),\n storage: (deps): OpenapiStore => makeDefaultOpenapiStore(deps),\n\n extension: (ctx: PluginCtx<OpenapiStore>) => {\n const httpClientLayer = options?.httpClientLayer ?? ctx.httpClientLayer;\n\n const addSpec = (config: OpenApiSpecConfig) =>\n Effect.gen(function* () {\n // Resolve URL → text and parse BEFORE opening a transaction. Holding\n // `BEGIN` across a network fetch is the Hyperdrive deadlock path.\n const resolved = yield* resolveSpecForInput(config.spec, httpClientLayer);\n const compiled = yield* compileSpec(resolved.specText);\n\n // Defaults the add page derives from its preview, applied here so\n // headless callers (MCP, API) get the same integration the UI's\n // add flow would produce — see e2e/scenarios/connect-handoff.test.ts:\n // - effectiveBaseUrl: the spec's first server, used to anchor the\n // derived auth template's absolute URLs. It is NOT stored as the\n // connection baseUrl — the request host is resolved per call from\n // the operation's extracted `servers`.\n // - authenticationTemplate: the spec's declared security schemes\n // (else the Add-connection modal is a dead \"No authentication\"\n // end with nowhere to paste a credential)\n // An explicit input always wins; for auth, an explicit EMPTY array\n // means \"no auth methods\" and suppresses the derivation.\n const explicitBaseUrl = config.baseUrl ?? resolved.baseUrl;\n const needsDerivedBaseUrl = explicitBaseUrl == null;\n const needsDerivedAuth =\n config.authenticationTemplate == null && resolved.authenticationTemplate == null;\n const preview =\n needsDerivedBaseUrl || needsDerivedAuth\n ? yield* previewSpecText(resolved.specText)\n : undefined;\n const derivedBaseUrl =\n needsDerivedBaseUrl && preview ? firstBaseUrlForPreview(preview) : undefined;\n const effectiveBaseUrl = explicitBaseUrl ?? (derivedBaseUrl || undefined);\n const derivedAuthenticationTemplate =\n needsDerivedAuth && preview\n ? deriveAuthenticationTemplateFromPreview(preview, effectiveBaseUrl)\n : undefined;\n\n const slug = IntegrationSlug.make(config.slug);\n\n // Block re-adding an existing slug. The core `integrations.register`\n // primitive upserts (so boot re-registration is idempotent), but an\n // explicit add must NOT silently clobber an existing integration's\n // tools, connections, and policies. To add more auth, update the\n // existing integration instead.\n const existing = yield* ctx.core.integrations.get(slug);\n if (existing) {\n return yield* new IntegrationAlreadyExistsError({ slug });\n }\n\n const specHash = yield* sha256Hex(resolved.specText);\n\n const integrationConfig: OpenApiIntegrationConfig = {\n specHash,\n ...(specInputToSourceUrl(config.spec) !== undefined\n ? { sourceUrl: specInputToSourceUrl(config.spec) }\n : {}),\n ...(specInputToGoogleBundle(config.spec) !== undefined\n ? { googleDiscoveryUrls: specInputToGoogleBundle(config.spec) }\n : {}),\n // baseUrl is an optional override only. The host is otherwise\n // resolved per call from the operation's `servers` (extracted from\n // the spec), so we never bake a derived base URL into the config.\n ...(config.baseUrl ? { baseUrl: config.baseUrl } : {}),\n ...(config.headers ? { headers: config.headers } : {}),\n ...(config.queryParams ? { queryParams: config.queryParams } : {}),\n // Prefer the caller's explicit template; otherwise adopt the one the\n // Google Discovery converter derived from the spec (the bundle add\n // path relies on this — it has no preview to detect auth from);\n // otherwise derive from the spec's declared security schemes.\n ...(config.authenticationTemplate\n ? {\n authenticationTemplate: normalizeOpenApiAuthInputs(config.authenticationTemplate),\n }\n : resolved.authenticationTemplate\n ? { authenticationTemplate: resolved.authenticationTemplate }\n : derivedAuthenticationTemplate && derivedAuthenticationTemplate.length > 0\n ? { authenticationTemplate: derivedAuthenticationTemplate }\n : {}),\n };\n\n // The spec blob is written OUTSIDE the transaction: it's\n // content-addressed (re-puts are idempotent) and an aborted register\n // leaves only an unreferenced blob behind — while blob backends like\n // R2 couldn't roll back with the transaction anyway.\n yield* ctx.storage.putSpec(specHash, resolved.specText);\n\n yield* ctx.transaction(\n Effect.gen(function* () {\n yield* ctx.core.integrations.register({\n slug,\n name: config.name?.trim() || compiled.title || config.slug,\n description:\n config.description ?? compiled.description ?? compiled.title ?? config.slug,\n config: integrationConfig satisfies OpenApiIntegrationConfig as IntegrationConfig,\n canRemove: true,\n canRefresh:\n specInputToSourceUrl(config.spec) != null ||\n specInputToGoogleBundle(config.spec) != null,\n });\n yield* ctx.storage.putOperations(\n config.slug,\n storedOperationsFromCompiled(config.slug, compiled),\n );\n }),\n );\n\n return { slug, toolCount: compiled.definitions.length };\n });\n\n // Update the spec IN PLACE: re-resolve (stored source URL / bundle, or a\n // caller-supplied new input), recompile, swap the stored operations, and\n // rebuild every connection's tools. Auth templates, base URL, headers,\n // the curated description, connections, and policies are all untouched —\n // this is the \"spec changed upstream\" path, not a re-add.\n const updateSpec = (rawSlug: string, input?: OpenApiUpdateSpecInput) =>\n Effect.gen(function* () {\n const slug = IntegrationSlug.make(rawSlug);\n const record = yield* ctx.core.integrations.get(slug);\n const current = record ? decodeOpenApiIntegrationConfig(record.config) : null;\n if (!record || !current) {\n return yield* new IntegrationNotFoundError({ slug });\n }\n\n // The new spec source: explicit input wins; otherwise re-fetch from\n // where the spec originally came from. A pasted-blob integration has\n // no origin, so updating it requires a new input.\n const specInput: OpenApiSpecInput | null =\n input?.spec ??\n (current.googleDiscoveryUrls\n ? { kind: \"googleDiscoveryBundle\", urls: current.googleDiscoveryUrls }\n : current.sourceUrl\n ? isGoogleDiscoveryUrl(current.sourceUrl)\n ? { kind: \"googleDiscovery\", url: current.sourceUrl }\n : { kind: \"url\", url: current.sourceUrl }\n : null);\n if (specInput === null) {\n return yield* new OpenApiParseError({\n message:\n \"This integration's spec was pasted inline and has no source URL to re-fetch. Provide the updated spec content.\",\n });\n }\n\n // Resolve + compile BEFORE the transaction (same Hyperdrive-deadlock\n // rule as addSpec: never hold BEGIN across a network fetch).\n const resolved = yield* resolveSpecForInput(specInput, httpClientLayer);\n const compiled = yield* compileSpec(resolved.specText);\n\n const previousOperations = yield* ctx.storage.listOperations(rawSlug);\n const previousNames = new Set(previousOperations.map((op) => op.toolName));\n const nextNames = new Set(compiled.definitions.map((def) => def.toolPath));\n\n // The resolved spec text lives in the plugin blob store keyed by its\n // content hash (`spec/<hash>`); the config carries only the hash. Put\n // the blob outside the transaction — re-puts are idempotent and an\n // aborted config update just leaves an unreferenced blob.\n const specHash = yield* sha256Hex(resolved.specText);\n yield* ctx.storage.putSpec(specHash, resolved.specText);\n\n const nextConfig: OpenApiIntegrationConfig = {\n ...current,\n specHash,\n ...(specInputToSourceUrl(specInput) !== undefined\n ? { sourceUrl: specInputToSourceUrl(specInput) }\n : {}),\n ...(specInputToGoogleBundle(specInput) !== undefined\n ? { googleDiscoveryUrls: specInputToGoogleBundle(specInput) }\n : {}),\n };\n\n yield* ctx.transaction(\n Effect.gen(function* () {\n yield* ctx.core.integrations.update(slug, {\n config: nextConfig satisfies OpenApiIntegrationConfig as IntegrationConfig,\n });\n yield* ctx.storage.putOperations(\n rawSlug,\n storedOperationsFromCompiled(rawSlug, compiled),\n );\n }),\n );\n\n // Rebuild each connection's tool rows from the new spec. Outside the\n // transaction: refresh opens its own, and a half-refreshed catalog\n // self-heals on the next refresh anyway.\n const connections = yield* ctx.connections.list({ integration: slug });\n yield* Effect.forEach(\n connections,\n (connection) =>\n ctx.connections\n .refresh({\n owner: connection.owner,\n integration: connection.integration,\n name: connection.name,\n })\n .pipe(Effect.catchTag(\"ConnectionNotFoundError\", () => Effect.succeed([]))),\n { discard: true },\n ).pipe(\n Effect.catchTag(\"IntegrationNotFoundError\", () => Effect.void),\n Effect.withSpan(\"openapi.plugin.update_spec.refresh_connections\", {\n attributes: { \"openapi.connection_count\": connections.length },\n }),\n );\n\n return {\n slug,\n toolCount: compiled.definitions.length,\n addedTools: [...nextNames].filter((name) => !previousNames.has(name)).sort(),\n removedTools: [...previousNames].filter((name) => !nextNames.has(name)).sort(),\n } satisfies UpdateSpecResult;\n }).pipe(\n Effect.withSpan(\"openapi.plugin.update_spec\", {\n attributes: { \"openapi.integration.slug\": rawSlug },\n }),\n );\n\n return {\n previewSpec: (input: string | OpenApiPreviewInput) =>\n Effect.gen(function* () {\n const previewInput = typeof input === \"string\" ? { spec: input } : input;\n const specText = isGoogleDiscoveryUrl(previewInput.spec)\n ? yield* fetchGoogleDiscoveryDocument(previewInput.spec).pipe(\n Effect.provide(httpClientLayer),\n Effect.flatMap((documentText) =>\n convertGoogleDiscoveryToOpenApi({\n discoveryUrl: previewInput.spec,\n documentText,\n }),\n ),\n Effect.map((conversion) => conversion.specText),\n )\n : yield* resolveSpecText(previewInput.spec).pipe(Effect.provide(httpClientLayer));\n return yield* previewSpec(specText).pipe(Effect.provide(httpClientLayer));\n }),\n\n addSpec,\n\n updateSpec,\n\n removeSpec: (slug: string) =>\n ctx.transaction(\n Effect.gen(function* () {\n yield* ctx.storage.removeOperations(slug);\n yield* ctx.core.integrations\n .remove(IntegrationSlug.make(slug))\n .pipe(Effect.catchTag(\"IntegrationRemovalNotAllowedError\", () => Effect.void));\n }),\n ),\n\n getIntegration: (slug: string) =>\n ctx.core.integrations.get(IntegrationSlug.make(slug)).pipe(\n Effect.map((record) =>\n record\n ? ({\n slug: record.slug,\n description: record.description,\n kind: record.kind,\n canRemove: record.canRemove,\n canRefresh: record.canRefresh,\n } as Integration)\n : null,\n ),\n ),\n\n getConfig: (slug: string): Effect.Effect<OpenApiIntegrationConfig | null, StorageFailure> =>\n ctx.core.integrations\n .get(IntegrationSlug.make(slug))\n .pipe(\n Effect.map((record) =>\n record ? decodeOpenApiIntegrationConfig(record.config) : null,\n ),\n ),\n\n configure: (\n slug: string,\n input: OpenApiConfigureInput,\n ): Effect.Effect<readonly Authentication[], StorageFailure> =>\n ctx.transaction(\n Effect.gen(function* () {\n const record = yield* ctx.core.integrations.get(IntegrationSlug.make(slug));\n if (!record) return [] as readonly Authentication[];\n const current = decodeOpenApiIntegrationConfig(record.config);\n if (!current) return [] as readonly Authentication[];\n\n const incoming = normalizeOpenApiAuthInputs(input.authenticationTemplate);\n const merged =\n input.mode === \"replace\"\n ? incoming\n : mergeAuthTemplates(current.authenticationTemplate ?? [], incoming);\n\n const next: OpenApiIntegrationConfig = {\n ...current,\n authenticationTemplate: merged,\n };\n\n yield* ctx.core.integrations.update(IntegrationSlug.make(slug), {\n config: next satisfies OpenApiIntegrationConfig as IntegrationConfig,\n });\n\n return merged;\n }),\n ),\n };\n },\n\n staticSources: (self: OpenApiPluginExtension) => [\n {\n id: \"openapi\",\n kind: \"executor\",\n name: \"OpenAPI\",\n tools: [\n tool({\n name: \"previewSpec\",\n description:\n \"Preview an OpenAPI document before adding it as an integration. Call this first when the user provides a spec URL/blob so you can inspect servers, auth schemes, operation count, and tags before `addSpec`. Do not collect API keys or OAuth client secrets in chat; use the connections tools for those values.\",\n inputSchema: PreviewSpecInputStandardSchema,\n outputSchema: PreviewSpecOutputStandardSchema,\n execute: (input: typeof PreviewSpecInputSchema.Type) =>\n self.previewSpec(input).pipe(\n Effect.map((preview) => ToolResult.ok(staticPreviewOutput(preview))),\n Effect.catchTags({\n OpenApiParseError: ({ message }: OpenApiParseError) =>\n Effect.succeed(openApiToolFailure(\"openapi_parse_failed\", message)),\n OpenApiExtractionError: ({ message }: OpenApiExtractionError) =>\n Effect.succeed(openApiToolFailure(\"openapi_extraction_failed\", message)),\n OpenApiOAuthError: ({ message }: OpenApiOAuthError) =>\n Effect.succeed(openApiToolFailure(\"openapi_oauth_failed\", message)),\n }),\n ),\n }),\n tool({\n name: \"addSpec\",\n description:\n \"Add an OpenAPI integration to the catalog and persist its operations as tools. Recommended flow: call `previewSpec`, choose a `slug`, then create a connection for that integration with the user's API key or via `oauth.start`. When `baseUrl` is omitted it defaults to the spec's first server; when `authenticationTemplate` is omitted the auth methods are derived from the spec's declared security schemes (pass an explicit template to override how a credential is applied — apiKey header/query, or oauth bearer — or an empty array for no auth methods).\",\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Add an OpenAPI integration\",\n },\n inputSchema: AddSourceInputStandardSchema,\n outputSchema: AddSourceOutputStandardSchema,\n execute: (input: typeof AddSourceInputSchema.Type) =>\n self\n .addSpec({\n spec: input.spec,\n slug: input.slug,\n description: input.description,\n baseUrl: input.baseUrl,\n headers: input.headers,\n queryParams: input.queryParams,\n authenticationTemplate: input.authenticationTemplate as\n | readonly AuthenticationInput[]\n | undefined,\n })\n .pipe(\n Effect.map((result) =>\n ToolResult.ok({\n slug: String(result.slug),\n toolCount: result.toolCount,\n }),\n ),\n Effect.catchTags({\n OpenApiParseError: ({ message }: OpenApiParseError) =>\n Effect.succeed(openApiToolFailure(\"openapi_parse_failed\", message)),\n OpenApiExtractionError: ({ message }: OpenApiExtractionError) =>\n Effect.succeed(openApiToolFailure(\"openapi_extraction_failed\", message)),\n OpenApiOAuthError: ({ message }: OpenApiOAuthError) =>\n Effect.succeed(openApiToolFailure(\"openapi_oauth_failed\", message)),\n IntegrationAlreadyExistsError: ({ slug }: IntegrationAlreadyExistsError) =>\n Effect.succeed(\n openApiToolFailure(\n \"integration_already_exists\",\n `Integration ${slug} already exists; update it instead of re-adding.`,\n ),\n ),\n }),\n ),\n }),\n ],\n },\n ],\n\n describeAuthMethods: describeOpenApiAuthMethods,\n describeIntegrationDisplay: describeOpenApiIntegrationDisplay,\n\n // Produce one tool per spec operation. Spec-derived, identical for every\n // connection on the integration — so `getValue` is never called here. The\n // operation bindings invokeTool needs are persisted at addSpec time; this\n // hook only shapes the per-connection ToolDefs from the spec blob the\n // catalog config points at.\n resolveTools: ({\n config,\n storage,\n }: {\n readonly integration: Integration;\n readonly config: IntegrationConfig;\n readonly storage: OpenapiStore;\n }): Effect.Effect<ResolveToolsResult, StorageFailure> =>\n Effect.gen(function* () {\n const openApiConfig = decodeOpenApiIntegrationConfig(config);\n if (!openApiConfig) return { tools: [], definitions: {} };\n const specText = yield* loadSpecText(storage, openApiConfig);\n if (specText == null) return { tools: [], definitions: {} };\n const compiled = yield* compileSpec(specText).pipe(\n Effect.catch(() => Effect.succeed(null)),\n );\n if (!compiled) return { tools: [], definitions: {} };\n return {\n tools: toolDefsFromCompiled(compiled),\n definitions: compiled.hoistedDefs,\n };\n }),\n\n invokeTool: ({\n ctx: invokeCtx,\n toolRow,\n credential,\n args,\n }: {\n readonly ctx: PluginCtx<OpenapiStore>;\n readonly toolRow: { readonly integration: string; readonly name: string };\n readonly credential: ToolInvocationCredential;\n readonly args: unknown;\n }) =>\n Effect.gen(function* () {\n const httpClientLayer = options?.httpClientLayer ?? invokeCtx.httpClientLayer;\n const integration = toolRow.integration;\n const config = decodeOpenApiIntegrationConfig(credential.config);\n\n // Resolve the operation binding from the plugin store; fall back to\n // re-deriving it from the spec blob when the store has no row (e.g. an\n // integration registered without going through addSpec). The fallback\n // is the ONLY invoke-path spec read — the hot path never loads it.\n const bindingFromSpec = config\n ? Effect.gen(function* () {\n const specText = yield* loadSpecText(invokeCtx.storage, config).pipe(\n Effect.catch(() => Effect.succeed(null)),\n );\n const compiled =\n specText == null\n ? null\n : yield* compileSpec(specText).pipe(Effect.catch(() => Effect.succeed(null)));\n return compiled\n ? storedOperationsFromCompiled(integration, compiled).find(\n (op) => op.toolName === toolRow.name,\n )?.binding\n : undefined;\n })\n : Effect.succeed(undefined);\n\n let binding = (yield* invokeCtx.storage.getOperation(integration, toolRow.name))?.binding;\n if ((!binding || Option.isNone(binding.responseBody)) && config) {\n binding = (yield* bindingFromSpec) ?? binding;\n }\n if (!binding) {\n return yield* new OpenApiExtractionError({\n message: `No OpenAPI operation found for tool \"${toolRow.name}\" on \"${integration}\"`,\n });\n }\n\n const headers: Record<string, string> = { ...(config?.headers ?? {}) };\n const queryParams: Record<string, string> = {\n ...(config?.queryParams ?? {}),\n };\n\n // Apply the auth template (D11): render the connection's resolved inputs\n // into the matching template's header/query slots (apiKey) or as a bearer\n // Authorization header (oauth). A method with two distinct inputs (e.g.\n // Datadog) renders each from its own value.\n const template = (config?.authenticationTemplate ?? []).find(\n (entry) => String(entry.slug) === String(credential.template),\n );\n if (template) {\n // Fail if ANY input the template requires is unresolved — not just the\n // primary `token` (a Datadog connection has no `token`, only its keys).\n const missing = requiredTemplateVariables(template).filter((name) => {\n const value = credential.values[name];\n return value == null || value === \"\";\n });\n if (missing.length > 0) {\n return openApiAuthToolFailure({\n code:\n template.kind === \"oauth2\"\n ? \"oauth_connection_missing\"\n : \"connection_value_missing\",\n message: `Connection \"${credential.connection}\" for \"${integration}\" has no resolvable credential value. Re-authenticate or update the connection.`,\n owner: credential.owner,\n integration,\n connection: String(credential.connection),\n credentialKind: template.kind === \"oauth2\" ? \"oauth\" : \"secret\",\n });\n }\n const rendered = renderAuthTemplate(template, credential.values);\n Object.assign(headers, rendered.headers);\n Object.assign(queryParams, rendered.queryParams);\n }\n\n const result = yield* invokeWithLayer(\n binding,\n (args ?? {}) as Record<string, unknown>,\n config?.baseUrl ?? \"\",\n headers,\n queryParams,\n httpClientLayer,\n );\n\n const ok = result.status >= 200 && result.status < 300;\n if (!ok) {\n if (result.status === 401 || result.status === 403) {\n return openApiAuthToolFailure({\n code: \"connection_rejected\",\n status: result.status,\n message: `Upstream rejected credentials for \"${integration}\" with HTTP ${result.status}. Re-authenticate or update the connection \"${credential.connection}\" before retrying this tool.`,\n owner: credential.owner,\n integration,\n connection: String(credential.connection),\n credentialKind: \"upstream\",\n credentialLabel: \"Upstream authorization\",\n details: result.error,\n });\n }\n return ToolResult.fail({\n code: \"upstream_http_error\",\n status: result.status,\n message: extractUpstreamMessage(result.error, result.status),\n details: result.error,\n });\n }\n // Payload-first: `data` is the upstream response body (matching the\n // graphql/mcp plugins); transport facts ride in the `http` side\n // channel so pagination/rate-limit headers stay reachable.\n return ToolResult.ok(result.data, {\n http: { status: result.status, headers: result.headers },\n });\n }),\n\n resolveAnnotations: ({\n ctx: annotationsCtx,\n integration,\n toolRows,\n }: {\n readonly ctx: PluginCtx<OpenapiStore>;\n readonly integration: string;\n readonly toolRows: readonly { readonly name: string }[];\n }) =>\n Effect.gen(function* () {\n const ops = yield* annotationsCtx.storage.listOperations(String(integration));\n const byName = new Map<string, OperationBinding>();\n for (const op of ops) byName.set(op.toolName, op.binding);\n const out: Record<string, ReturnType<typeof annotationsForOperation>> = {};\n for (const row of toolRows) {\n const binding = byName.get(row.name);\n if (binding) {\n out[row.name] = annotationsForOperation(binding.method, binding.pathTemplate);\n }\n }\n return out;\n }),\n\n removeConnection: () => Effect.void,\n\n detect: ({\n ctx: detectCtx,\n url,\n }: {\n readonly ctx: PluginCtx<OpenapiStore>;\n readonly url: string;\n }) =>\n Effect.gen(function* () {\n const httpClientLayer = options?.httpClientLayer ?? detectCtx.httpClientLayer;\n const trimmed = url.trim();\n if (!trimmed) return null;\n const parsed = yield* Effect.try({\n try: () => new URL(trimmed),\n catch: (error) => error,\n }).pipe(Effect.option);\n if (Option.isNone(parsed)) return null;\n if (isGoogleDiscoveryUrl(trimmed)) {\n const conversion = yield* fetchGoogleDiscoveryDocument(trimmed).pipe(\n Effect.provide(httpClientLayer),\n Effect.flatMap((documentText) =>\n convertGoogleDiscoveryToOpenApi({\n discoveryUrl: trimmed,\n documentText,\n }),\n ),\n Effect.catch(() => Effect.succeed(null)),\n );\n if (conversion) {\n return IntegrationDetectionResult.make({\n kind: \"openapi\",\n confidence: \"high\",\n endpoint: trimmed,\n name: conversion.title,\n slug:\n conversion.title\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\") || `google_${conversion.service}`,\n });\n }\n }\n const specText = yield* resolveSpecText(trimmed).pipe(\n Effect.provide(httpClientLayer),\n Effect.catch(() => Effect.succeed(null)),\n );\n if (specText === null) return null;\n const doc = yield* parse(specText).pipe(Effect.catch(() => Effect.succeed(null)));\n if (!doc) return null;\n const result = yield* extract(doc).pipe(Effect.catch(() => Effect.succeed(null)));\n if (!result) return null;\n const slug = Option.getOrElse(result.title, () => \"api\")\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\");\n const name = Option.getOrElse(result.title, () => slug);\n return IntegrationDetectionResult.make({\n kind: \"openapi\",\n confidence: \"high\",\n endpoint: trimmed,\n name,\n slug,\n });\n }),\n };\n // HTTP transport (routes/handlers/extensionService) is layered on by\n // the api-aware factory in `@executor-js/plugin-openapi/api`. Hosts that\n // want the HTTP surface import the plugin from there; SDK-only consumers\n // stay on this entry and avoid the server-only deps.\n});\n","/**\n * Derives structured `group.leaf` tool paths from extracted OpenAPI operations.\n *\n * Ported from the v3 executor's `definitions.ts`. Turns flat operation IDs like\n * `zones_listZones` into nested paths like `zones.listZones` that the tree UI\n * can render with proper nesting.\n */\n\nimport { Option } from \"effect\";\n\nimport type { ExtractedOperation } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Word / case utilities\n// ---------------------------------------------------------------------------\n\nconst splitWords = (value: string): string[] =>\n value\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/([A-Z]+)([A-Z][a-z0-9]+)/g, \"$1 $2\")\n .replace(/[^a-zA-Z0-9]+/g, \" \")\n .trim()\n .split(/\\s+/)\n .filter((part) => part.length > 0);\n\nconst normalizeWord = (value: string): string => value.toLowerCase();\n\nconst toCamelCase = (value: string): string => {\n const words = splitWords(value).map(normalizeWord);\n if (words.length === 0) return \"tool\";\n const [first, ...rest] = words;\n return `${first}${rest.map((p) => `${p[0]?.toUpperCase() ?? \"\"}${p.slice(1)}`).join(\"\")}`;\n};\n\nconst toPascalCase = (value: string): string => {\n const camel = toCamelCase(value);\n return `${camel[0]?.toUpperCase() ?? \"\"}${camel.slice(1)}`;\n};\n\n// ---------------------------------------------------------------------------\n// Path utilities\n// ---------------------------------------------------------------------------\n\nconst VERSION_SEGMENT_REGEX = /^v\\d+(?:[._-]\\d+)?$/i;\nconst IGNORED_PATH_SEGMENTS = new Set([\"api\"]);\n\nconst pathSegmentsFromTemplate = (pathTemplate: string): string[] =>\n pathTemplate\n .split(\"/\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n\nconst isPathParameterSegment = (segment: string): boolean =>\n segment.startsWith(\"{\") && segment.endsWith(\"}\");\n\nconst normalizeGroupSegment = (value: string | undefined): string | null => {\n const candidate = value?.trim();\n if (!candidate) return null;\n return toCamelCase(candidate);\n};\n\n// ---------------------------------------------------------------------------\n// Derivation\n// ---------------------------------------------------------------------------\n\nconst deriveVersionSegment = (pathTemplate: string): string | undefined =>\n pathSegmentsFromTemplate(pathTemplate)\n .map((s) => s.toLowerCase())\n .find((s) => VERSION_SEGMENT_REGEX.test(s));\n\nconst derivePathGroup = (pathTemplate: string): string => {\n for (const segment of pathSegmentsFromTemplate(pathTemplate)) {\n const lower = segment.toLowerCase();\n if (VERSION_SEGMENT_REGEX.test(lower)) continue;\n if (IGNORED_PATH_SEGMENTS.has(lower)) continue;\n if (isPathParameterSegment(segment)) continue;\n return normalizeGroupSegment(segment) ?? \"root\";\n }\n return \"root\";\n};\n\nconst splitOperationIdSegments = (value: string): string[] =>\n value\n .split(/[/.]+/)\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n\nconst deriveLeafSeed = (operationId: string, group: string): string => {\n const segments = splitOperationIdSegments(operationId);\n if (segments.length > 1) {\n const [first, ...rest] = segments;\n if ((normalizeGroupSegment(first) ?? first) === group && rest.length > 0) {\n return rest.join(\" \");\n }\n }\n return operationId;\n};\n\nconst fallbackLeafSeed = (method: string, pathTemplate: string, group: string): string => {\n const relevantSegments = pathSegmentsFromTemplate(pathTemplate)\n .filter((s) => !VERSION_SEGMENT_REGEX.test(s.toLowerCase()))\n .filter((s) => !IGNORED_PATH_SEGMENTS.has(s.toLowerCase()))\n .filter((s) => !isPathParameterSegment(s))\n .map((s) => normalizeGroupSegment(s) ?? s)\n .filter((s) => s !== group);\n\n const segmentSuffix = relevantSegments.map((s) => toPascalCase(s)).join(\"\");\n return `${method}${segmentSuffix || \"Operation\"}`;\n};\n\nconst deriveLeaf = (\n operationId: string,\n method: string,\n pathTemplate: string,\n group: string,\n): string => {\n const preferred = toCamelCase(deriveLeafSeed(operationId, group));\n if (preferred.length > 0 && preferred !== group) return preferred;\n return toCamelCase(fallbackLeafSeed(method, pathTemplate, group));\n};\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport interface ToolDefinition {\n /** Dot-separated path like `zones.listZones` */\n readonly toolPath: string;\n /** The group segment */\n readonly group: string;\n /** The leaf segment */\n readonly leaf: string;\n /** Index into the original operations array */\n readonly operationIndex: number;\n /** The original operation */\n readonly operation: ExtractedOperation;\n}\n\n// ---------------------------------------------------------------------------\n// Collision resolution\n// ---------------------------------------------------------------------------\n\nconst resolveCollisions = (\n definitions: {\n toolPath: string;\n group: string;\n leaf: string;\n versionSegment: string | undefined;\n method: string;\n operationHash: string;\n operationIndex: number;\n operation: ExtractedOperation;\n }[],\n): ToolDefinition[] => {\n // Mutable — we progressively refine toolPath on collision\n const staged = definitions.map((d) => ({ ...d }));\n\n const applyFactory = (items: typeof staged, factory: (d: (typeof staged)[number]) => string) => {\n const byPath = new Map<string, typeof staged>();\n for (const item of items) {\n const bucket = byPath.get(item.toolPath) ?? [];\n bucket.push(item);\n byPath.set(item.toolPath, bucket);\n }\n for (const bucket of byPath.values()) {\n if (bucket.length < 2) continue;\n for (const d of bucket) {\n d.toolPath = factory(d);\n }\n }\n };\n\n // Round 1: add version segment\n applyFactory(staged, (d) =>\n d.versionSegment ? `${d.group}.${d.versionSegment}.${d.leaf}` : d.toolPath,\n );\n\n // Round 2: add method suffix\n applyFactory(staged, (d) => {\n const prefix = d.versionSegment ? `${d.group}.${d.versionSegment}` : d.group;\n return `${prefix}.${d.leaf}${toPascalCase(d.method)}`;\n });\n\n // Round 3: add hash suffix\n applyFactory(staged, (d) => {\n const prefix = d.versionSegment ? `${d.group}.${d.versionSegment}` : d.group;\n return `${prefix}.${d.leaf}${toPascalCase(d.method)}${d.operationHash.slice(0, 8)}`;\n });\n\n return staged.map((d) => ({\n toolPath: d.toolPath,\n group: d.group,\n leaf: d.leaf,\n operationIndex: d.operationIndex,\n operation: d.operation,\n }));\n};\n\n// ---------------------------------------------------------------------------\n// Stable hash (simple, deterministic)\n// ---------------------------------------------------------------------------\n\nconst stableHash = (value: unknown): string => {\n const str = JSON.stringify(value, Object.keys(value as Record<string, unknown>).sort());\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) - hash + str.charCodeAt(i)) | 0;\n }\n return Math.abs(hash).toString(36).padStart(8, \"0\");\n};\n\n// ---------------------------------------------------------------------------\n// Main entry point\n// ---------------------------------------------------------------------------\n\n/**\n * Compile extracted operations into tool definitions with structured\n * `group.leaf` paths suitable for tree rendering.\n */\nexport const compileToolDefinitions = (\n operations: readonly ExtractedOperation[],\n): ToolDefinition[] => {\n const raw = operations.map((op, index) => {\n const operationId = op.operationId;\n const explicitToolPath = Option.getOrUndefined(op.toolPath);\n if (explicitToolPath) {\n const [group = \"root\", ...leafParts] = explicitToolPath.split(\".\").filter(Boolean);\n const leaf = leafParts.join(\".\") || group;\n const versionSegment = deriveVersionSegment(op.pathTemplate);\n const operationHash = stableHash({\n method: op.method,\n path: op.pathTemplate,\n operationId,\n });\n\n return {\n toolPath: explicitToolPath,\n group,\n leaf,\n versionSegment,\n method: op.method,\n operationHash,\n operationIndex: index,\n operation: op,\n };\n }\n\n const group = normalizeGroupSegment(op.tags[0]) ?? derivePathGroup(op.pathTemplate);\n const leaf = deriveLeaf(operationId, op.method, op.pathTemplate, group);\n const versionSegment = deriveVersionSegment(op.pathTemplate);\n const operationHash = stableHash({\n method: op.method,\n path: op.pathTemplate,\n operationId,\n });\n\n return {\n toolPath: `${group}.${leaf}`,\n group,\n leaf,\n versionSegment,\n method: op.method,\n operationHash,\n operationIndex: index,\n operation: op,\n };\n });\n\n return resolveCollisions(raw).sort((a, b) => a.toolPath.localeCompare(b.toolPath));\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,QAAQ,cAAc;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAuBP,IAAM,4BAA4B,OAAO,OAAO;AAAA,EAC9C,MAAM,OAAO;AAAA,EACb,MAAM,OAAO,QAAQ,QAAQ;AAAA,EAC7B,kBAAkB,OAAO;AAAA,EACzB,UAAU,OAAO;AAAA,EACjB,QAAQ,OAAO,MAAM,OAAO,MAAM;AACpC,CAAC;AAEM,IAAM,uBAAuB,OAAO,MAAM,CAAC,2BAA2B,gBAAgB,CAAC;AAEvF,IAAM,iCAAiC,OAAO,OAAO;AAAA;AAAA;AAAA,EAG1D,UAAU,OAAO,SAAS,OAAO,MAAM;AAAA;AAAA,EAEvC,WAAW,OAAO,SAAS,OAAO,MAAM;AAAA;AAAA,EAExC,qBAAqB,OAAO,SAAS,OAAO,MAAM,OAAO,MAAM,CAAC;AAAA;AAAA,EAEhE,SAAS,OAAO,SAAS,OAAO,MAAM;AAAA;AAAA,EAEtC,SAAS,OAAO,SAAS,OAAO,OAAO,OAAO,QAA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UAAU,WAAW,OAAO;AAAA,UAC9D,CAAC;AAAA,QACH;AAAA,MACF;AACA,YAAM,WAAW,OAAO,gBAAgB,OAAO,EAAE;AAAA,QAC/CA,QAAO,QAAQ,eAAe;AAAA,QAC9BA,QAAO,MAAM,MAAMA,QAAO,QAAQ,IAAI,CAAC;AAAA,MACzC;AACA,UAAI,aAAa,KAAM,QAAO;AAC9B,YAAM,MAAM,OAAO,MAAM,QAAQ,EAAE,KAAKA,QAAO,MAAM,MAAMA,QAAO,QAAQ,IAAI,CAAC,CAAC;AAChF,UAAI,CAAC,IAAK,QAAO;AACjB,YAAM,SAAS,OAAO,QAAQ,GAAG,EAAE,KAAKA,QAAO,MAAM,MAAMA,QAAO,QAAQ,IAAI,CAAC,CAAC;AAChF,UAAI,CAAC,OAAQ,QAAO;AACpB,YAAM,OAAOJ,QAAO,UAAU,OAAO,OAAO,MAAM,KAAK,EACpD,YAAY,EACZ,QAAQ,eAAe,GAAG;AAC7B,YAAM,OAAOA,QAAO,UAAU,OAAO,OAAO,MAAM,IAAI;AACtD,aAAO,2BAA2B,KAAK;AAAA,QACrC,MAAM;AAAA,QACN,YAAY;AAAA,QACZ,UAAU;AAAA,QACV;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH,CAAC;AAAA,EACL;AAKF,CAAC;","names":["Option","Option","bytes","Effect","Option","Schema","Schema","Option","Effect","Effect","Option","Schema","Option","group","leaf","versionSegment","operationHash","Schema","Option","message","AuthenticationSchema","changed","Effect"]}
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
type GoogleProductPickerProps = {
|
|
2
|
-
readonly selectedPresetIds: ReadonlySet<string>;
|
|
3
|
-
readonly onToggle: (presetId: string, checked: boolean) => void;
|
|
4
|
-
readonly customUrls: readonly string[];
|
|
5
|
-
readonly onAddCustomUrl: (url: string) => void;
|
|
6
|
-
readonly onRemoveCustomUrl: (url: string) => void;
|
|
7
|
-
};
|
|
8
|
-
export declare function GoogleProductPicker({ selectedPresetIds, onToggle, customUrls, onAddCustomUrl, onRemoveCustomUrl, }: GoogleProductPickerProps): import("react/jsx-runtime").JSX.Element;
|
|
9
|
-
export default GoogleProductPicker;
|
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
import { Effect } from "effect";
|
|
2
|
-
import { HttpClient } from "effect/unstable/http";
|
|
3
|
-
import { OpenApiParseError } from "./errors";
|
|
4
|
-
import type { SpecFetchCredentials } from "./parse";
|
|
5
|
-
import type { Authentication } from "./types";
|
|
6
|
-
export interface GoogleDiscoveryOpenApiConversion {
|
|
7
|
-
readonly specText: string;
|
|
8
|
-
readonly baseUrl: string;
|
|
9
|
-
readonly title: string;
|
|
10
|
-
readonly service: string;
|
|
11
|
-
readonly version: string;
|
|
12
|
-
readonly discoveryUrls?: readonly string[];
|
|
13
|
-
/** The v2 oauth auth template the converted integration declares, when the
|
|
14
|
-
* Discovery document advertises OAuth2 scopes. */
|
|
15
|
-
readonly authenticationTemplate?: readonly Authentication[];
|
|
16
|
-
}
|
|
17
|
-
export declare const isGoogleDiscoveryUrl: (url: string) => boolean;
|
|
18
|
-
export declare const fetchGoogleDiscoveryDocument: (discoveryUrl: string, credentials?: SpecFetchCredentials | undefined) => Effect.Effect<string, OpenApiParseError, HttpClient.HttpClient>;
|
|
19
|
-
export declare const convertGoogleDiscoveryToOpenApi: (input: {
|
|
20
|
-
readonly discoveryUrl: string;
|
|
21
|
-
readonly documentText: string;
|
|
22
|
-
}) => Effect.Effect<{
|
|
23
|
-
authenticationTemplate?: readonly Authentication[] | undefined;
|
|
24
|
-
specText: string;
|
|
25
|
-
baseUrl: string;
|
|
26
|
-
title: string;
|
|
27
|
-
service: string;
|
|
28
|
-
version: string;
|
|
29
|
-
}, OpenApiParseError, never>;
|
|
30
|
-
export declare const convertGoogleDiscoveryBundleToOpenApi: (input: {
|
|
31
|
-
readonly documents: readonly {
|
|
32
|
-
readonly discoveryUrl: string;
|
|
33
|
-
readonly documentText: string;
|
|
34
|
-
}[];
|
|
35
|
-
}) => Effect.Effect<{
|
|
36
|
-
authenticationTemplate?: readonly Authentication[] | undefined;
|
|
37
|
-
specText: string;
|
|
38
|
-
baseUrl: string;
|
|
39
|
-
title: string;
|
|
40
|
-
service: string;
|
|
41
|
-
version: string;
|
|
42
|
-
discoveryUrls: string[];
|
|
43
|
-
}, OpenApiParseError, never>;
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import type { GoogleOpenApiOAuthAudience } from "./google-presets";
|
|
2
|
-
export type GoogleOAuthBatchInput = {
|
|
3
|
-
readonly id: string;
|
|
4
|
-
readonly name: string;
|
|
5
|
-
readonly oauthAudience: GoogleOpenApiOAuthAudience;
|
|
6
|
-
readonly scopes: readonly string[];
|
|
7
|
-
};
|
|
8
|
-
export type GoogleOAuthConsentBatch = {
|
|
9
|
-
readonly id: string;
|
|
10
|
-
readonly label: string;
|
|
11
|
-
readonly apiScopes: readonly string[];
|
|
12
|
-
};
|
|
13
|
-
export declare const googleOAuthConsentBatches: (items: readonly GoogleOAuthBatchInput[]) => readonly GoogleOAuthConsentBatch[];
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|