@executor-js/plugin-openapi 1.5.21 → 2.0.0
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-SSXZBQEK.js → AddOpenApiSource-6PJZWRRZ.js} +17 -12
- package/dist/AddOpenApiSource-6PJZWRRZ.js.map +1 -0
- package/dist/{OpenApiAccountsPanel-U47OVLYG.js → OpenApiAccountsPanel-W6IMUY7Q.js} +4 -4
- package/dist/{UpdateSpecSection-FFYVB3VH.js → UpdateSpecSection-R2RF2QV2.js} +3 -3
- package/dist/api/group.d.ts +10 -0
- package/dist/api/index.d.ts +12 -0
- package/dist/{chunk-2RNIMASA.js → chunk-562TAVB2.js} +5 -3
- package/dist/chunk-562TAVB2.js.map +1 -0
- package/dist/{chunk-RCBR3QMJ.js → chunk-56PVOO6X.js} +10 -4
- package/dist/{chunk-RCBR3QMJ.js.map → chunk-56PVOO6X.js.map} +1 -1
- package/dist/{chunk-3O3PGRRG.js → chunk-DBA2BHE4.js} +287 -23
- package/dist/chunk-DBA2BHE4.js.map +1 -0
- package/dist/{chunk-QQFCICLX.js → chunk-HG5JB2UJ.js} +9 -1
- package/dist/{chunk-QQFCICLX.js.map → chunk-HG5JB2UJ.js.map} +1 -1
- package/dist/{chunk-MWF55JPY.js → chunk-IVRAOG3T.js} +5 -3
- package/dist/{chunk-MWF55JPY.js.map → chunk-IVRAOG3T.js.map} +1 -1
- package/dist/{chunk-R3X27XS6.js → chunk-WWZ7B34D.js} +35 -4
- package/dist/chunk-WWZ7B34D.js.map +1 -0
- package/dist/client.js +4 -4
- package/dist/core.js +4 -4
- package/dist/index.js +4 -4
- package/dist/react/AddOpenApiSource.d.ts +1 -0
- package/dist/react/AddOpenApiSource.test.d.ts +1 -0
- package/dist/react/atoms.d.ts +12 -0
- package/dist/react/client.d.ts +10 -0
- package/dist/sdk/config.d.ts +4 -0
- package/dist/sdk/plugin.d.ts +2 -0
- package/dist/sdk/preview.d.ts +16 -0
- package/package.json +3 -3
- package/dist/AddOpenApiSource-SSXZBQEK.js.map +0 -1
- package/dist/chunk-2RNIMASA.js.map +0 -1
- package/dist/chunk-3O3PGRRG.js.map +0 -1
- package/dist/chunk-R3X27XS6.js.map +0 -1
- /package/dist/{OpenApiAccountsPanel-U47OVLYG.js.map → OpenApiAccountsPanel-W6IMUY7Q.js.map} +0 -0
- /package/dist/{UpdateSpecSection-FFYVB3VH.js.map → UpdateSpecSection-R2RF2QV2.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sdk/config.ts","../src/sdk/store.ts","../src/sdk/invoke.ts","../src/sdk/backing.ts","../src/sdk/plugin.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 resource: Schema.optional(Schema.NullOr(Schema.String)),\n scopes: Schema.Array(Schema.String),\n supportsClientIdMetadataDocument: Schema.optional(Schema.Boolean),\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 /** 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, 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;\nconst OPERATION_KEY_VERSION = \"op\";\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 // Resolved tool description (operation description / summary / method+path\n // fallback), persisted so the serve path can rebuild the tool def without\n // re-parsing the spec. Optional: legacy rows predate it and resolve via the\n // parse fallback.\n description: Schema.optional(Schema.String),\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 /** Resolved tool description, persisted alongside the binding so the serve\n * path can rebuild the tool def without re-parsing the spec. */\n readonly description?: string;\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 ...(operation.description !== undefined ? { description: operation.description } : {}),\n };\n};\n\nconst stableKeyHash = (value: string): string => {\n let hash = 0xcbf29ce484222325n;\n const prime = 0x100000001b3n;\n const mask = 0xffffffffffffffffn;\n for (let index = 0; index < value.length; index += 1) {\n hash ^= BigInt(value.charCodeAt(index));\n hash = (hash * prime) & mask;\n }\n return hash.toString(36).padStart(13, \"0\");\n};\n\nconst operationKey = (integration: string, toolName: string): string =>\n `${OPERATION_KEY_VERSION}.${stableKeyHash(integration)}.${stableKeyHash(toolName)}`;\n\nconst legacyOperationKey = (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\n/** Blob key for a spec's compiled `#/$defs/*` schemas, keyed by the same\n * content hash as the spec. The serve path reads this instead of re-parsing\n * the (potentially multi-MB) spec to rebuild the shared `definitions`. */\nexport const defsBlobKey = (specHash: string): string => `defs/${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 /** Append operations without clearing existing ones. The caller is\n * responsible for `removeOperations` first when doing a full rebuild. Used\n * by the streaming compile path, which persists operations chunk by chunk so\n * a huge spec's bindings are never all materialized at once. */\n readonly appendOperations: (\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 /** Persist the compiled `#/$defs/*` JSON for a spec under its content hash.\n * Content-addressed like the spec blob; lets the serve path serve the shared\n * `definitions` without re-parsing the spec. */\n readonly putDefs: (specHash: string, defsJson: string) => Effect.Effect<void, StorageFailure>;\n /** Load the compiled `#/$defs/*` JSON by content hash; null when no blob\n * exists (legacy rows added before the defs blob). */\n readonly getDefs: (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 ...(operation.description !== undefined ? { description: operation.description } : {}),\n });\n\n const listRows = (integration: string) =>\n pluginStorage\n .list({ collection: OPERATION_COLLECTION })\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 const appendOperations = (integration: string, operations: readonly StoredOperation[]) =>\n 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 return {\n putOperations: (integration, operations) =>\n Effect.gen(function* () {\n yield* removeOperations(integration);\n yield* appendOperations(integration, operations);\n }),\n\n appendOperations,\n\n getOperation: (integration, toolName) =>\n Effect.gen(function* () {\n const row = yield* pluginStorage.get({\n collection: OPERATION_COLLECTION,\n key: operationKey(integration, toolName),\n });\n if (row) return rowToOperation(row);\n const legacyKey = legacyOperationKey(integration, toolName);\n if (legacyKey.length > 255) return null;\n const legacyRow = yield* pluginStorage.get({\n collection: OPERATION_COLLECTION,\n key: legacyKey,\n });\n return legacyRow ? rowToOperation(legacyRow) : null;\n }),\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 putDefs: (specHash, defsJson) =>\n blobs.put(defsBlobKey(specHash), defsJson, { owner: STORE_OWNER }),\n\n getDefs: (specHash) => blobs.get(defsBlobKey(specHash)),\n };\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\n// GitHub (and some other upstreams) reject requests that lack a User-Agent\n// header with a 403 (\"Request forbidden by administrative rules\"), which is\n// indistinguishable from a credential rejection downstream. Send a default so\n// those calls succeed. It is applied before operation header params and\n// resolved auth headers, so a spec- or connection-provided User-Agent wins.\nconst DEFAULT_USER_AGENT = \"executor\";\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\ntype DecodedBase64Body = { readonly ok: true; readonly bytes: Uint8Array } | { readonly ok: false };\n\nconst base64ToUint8Array = (value: string): Uint8Array | null => {\n let binary = \"\";\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: atob throws for invalid base64; invalid shapes are treated as non-byte input\n try {\n binary = atob(normalizeBase64(value, \"base64\"));\n } catch {\n return null;\n }\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 decodeBase64Body = (value: string): DecodedBase64Body => {\n const bytes = base64ToUint8Array(value);\n return bytes ? { ok: true, bytes } : { ok: false };\n};\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 readNestedBodyBase64 = (value: unknown): unknown =>\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.prototype.hasOwnProperty.call(value, \"bodyBase64\")\n ? (value as Record<string, unknown>).bodyBase64\n : undefined;\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 // Default first so operation header params and resolved auth headers below\n // can override it; the upstream still gets a User-Agent if nothing else sets one.\n request = HttpClientRequest.setHeader(request, \"User-Agent\", DEFAULT_USER_AGENT);\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 contentsOpt = Option.getOrUndefined(rb.contents);\n const requestedCt = typeof args.contentType === \"string\" ? args.contentType : undefined;\n const octetStreamContent = contentsOpt?.find((c) => isOctetStream(c.contentType));\n const bodyAcceptsOctetStream = Boolean(octetStreamContent) || isOctetStream(rb.contentType);\n const hasBodyBase64 = Object.prototype.hasOwnProperty.call(args, \"bodyBase64\");\n const bodyBase64Raw = args.bodyBase64;\n const bodyBase64 =\n typeof bodyBase64Raw === \"string\" ? decodeBase64Body(bodyBase64Raw) : undefined;\n\n if (hasBodyBase64 && typeof bodyBase64Raw !== \"string\") {\n return yield* new OpenApiInvocationError({\n message: \"`bodyBase64` must be a base64 string\",\n statusCode: Option.none(),\n });\n }\n if (bodyBase64?.ok === false) {\n return yield* new OpenApiInvocationError({\n message: \"`bodyBase64` is not valid base64\",\n statusCode: Option.none(),\n });\n }\n if (bodyBase64?.ok === true && !bodyAcceptsOctetStream) {\n return yield* new OpenApiInvocationError({\n message: \"`bodyBase64` requires an application/octet-stream request body\",\n statusCode: Option.none(),\n });\n }\n if (bodyBase64?.ok === true && requestedCt && !isOctetStream(requestedCt)) {\n return yield* new OpenApiInvocationError({\n message: \"`bodyBase64` requires an application/octet-stream contentType\",\n statusCode: Option.none(),\n });\n }\n\n const rawBodyValue = args.body ?? args.input;\n const nestedBodyBase64Raw = readNestedBodyBase64(rawBodyValue);\n const hasNestedBodyBase64 = nestedBodyBase64Raw !== undefined;\n const nestedBodyBase64 =\n typeof nestedBodyBase64Raw === \"string\" ? decodeBase64Body(nestedBodyBase64Raw) : undefined;\n\n if (hasNestedBodyBase64 && typeof nestedBodyBase64Raw !== \"string\") {\n return yield* new OpenApiInvocationError({\n message: \"`body.bodyBase64` must be a base64 string\",\n statusCode: Option.none(),\n });\n }\n if (nestedBodyBase64?.ok === false) {\n return yield* new OpenApiInvocationError({\n message: \"`body.bodyBase64` is not valid base64\",\n statusCode: Option.none(),\n });\n }\n if (nestedBodyBase64?.ok === true && !bodyAcceptsOctetStream) {\n return yield* new OpenApiInvocationError({\n message: \"`body.bodyBase64` requires an application/octet-stream request body\",\n statusCode: Option.none(),\n });\n }\n if (nestedBodyBase64?.ok === true && requestedCt && !isOctetStream(requestedCt)) {\n return yield* new OpenApiInvocationError({\n message: \"`body.bodyBase64` requires an application/octet-stream contentType\",\n statusCode: Option.none(),\n });\n }\n\n const binaryBody = bodyBase64?.ok === true ? bodyBase64 : nestedBodyBase64;\n const bodyValue = binaryBody?.ok === true ? binaryBody.bytes : rawBodyValue;\n if (rb.required && bodyValue === undefined) {\n return yield* new OpenApiInvocationError({\n message: bodyAcceptsOctetStream\n ? \"Missing required request body: provide `bodyBase64`\"\n : \"Missing required request body\",\n statusCode: Option.none(),\n });\n }\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 selected: MediaBinding | undefined =\n binaryBody?.ok === true && octetStreamContent\n ? octetStreamContent\n : contentsOpt && requestedCt\n ? contentsOpt.find((c) => c.contentType === requestedCt)\n : undefined;\n const chosenCt =\n binaryBody?.ok === true && !octetStreamContent && isOctetStream(rb.contentType)\n ? rb.contentType\n : (selected?.contentType ?? rb.contentType);\n if (isOctetStream(chosenCt) && toUint8Array(bodyValue) === null) {\n return yield* new OpenApiInvocationError({\n message: \"application/octet-stream request body must be bytes; provide `bodyBase64`\",\n statusCode: Option.none(),\n });\n }\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, Schema } from \"effect\";\nimport type { Layer } from \"effect\";\nimport { HttpClient } from \"effect/unstable/http\";\n\nimport {\n ToolFileJsonSchema,\n ToolName,\n ToolResult,\n authToolFailure,\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, OpenApiParseError } from \"./errors\";\nimport {\n buildInputSchema,\n extract,\n streamOperationBindings,\n streamOperationBindingsFromStructure,\n} from \"./extract\";\nimport { compileToolDefinitions, type ToolDefinition } from \"./definitions\";\nimport { annotationsForOperation, invokeWithLayer } from \"./invoke\";\nimport { parse, type ParsedDocument } from \"./parse\";\nimport { parseEntry, structuralSplit, type KeepPathItem, type SpecStructure } from \"./split\";\nimport { type OpenapiStore, type StoredOperation } from \"./store\";\nimport { OperationBinding } from \"./types\";\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\nexport const extractOpenApiUpstreamMessage = (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\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 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\n/** Rewrite OpenAPI `#/components/schemas/X` refs to standard `#/$defs/X`. */\nexport const 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\n/**\n * Copyable contract appended to the stored description of any tool whose\n * output is a ToolFile. Stored descriptions ride both `search` (the step a\n * model always walks) and `describe.tool`, so baking the emit instruction\n * here puts it in front of the agent before the first call, where the\n * output schema alone (dropped from the hot list projection) cannot.\n */\nconst FILE_OUTPUT_HINT =\n 'Returns a ToolFile: the file bytes already decoded into { _tag: \"ToolFile\", mimeType, encoding, data, byteLength }. ' +\n \"To display or forward it, pass the result's data straight to emit(result.data). \" +\n \"Do not rebuild the envelope or read upstream fields like size.\";\n\nconst withFileEmitHint = (description: string, returnsFile: boolean): string =>\n returnsFile ? `${description}\\n\\n${FILE_OUTPUT_HINT}` : description;\n\nexport interface CompiledOpenApiSpec {\n readonly definitions: readonly ToolDefinition[];\n readonly hoistedDefs: Record<string, unknown>;\n readonly title: string | undefined;\n readonly description: string | undefined;\n}\n\nexport const compileOpenApiDocument = (\n doc: ParsedDocument,\n): Effect.Effect<CompiledOpenApiSpec, OpenApiExtractionError> =>\n Effect.gen(function* () {\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\nexport const compileOpenApiSpec = (\n specText: string,\n): Effect.Effect<CompiledOpenApiSpec, OpenApiParseError | OpenApiExtractionError> =>\n Effect.gen(function* () {\n const doc = yield* parse(specText);\n return yield* compileOpenApiDocument(doc);\n });\n\nexport const openApiToolDefsFromCompiled = (compiled: CompiledOpenApiSpec): readonly ToolDef[] =>\n compiled.definitions.map((def): ToolDef => {\n const returnsFile = Option.match(def.operation.responseBody, {\n onNone: () => false,\n onSome: (responseBody) => Option.isSome(responseBody.fileHint),\n });\n return {\n name: ToolName.make(def.toolPath),\n description: withFileEmitHint(descriptionFor(def), returnsFile),\n inputSchema: normalizeOpenApiRefs(Option.getOrUndefined(def.operation.inputSchema)),\n outputSchema: returnsFile\n ? ToolFileJsonSchema\n : normalizeOpenApiRefs(Option.getOrUndefined(def.operation.outputSchema)),\n annotations: annotationsForOperation(def.operation.method, def.operation.pathTemplate),\n };\n });\n\nexport const openApiStoredOperationsFromCompiled = (\n integration: string,\n compiled: CompiledOpenApiSpec,\n): readonly StoredOperation[] =>\n compiled.definitions.map((def) => ({\n integration,\n toolName: def.toolPath,\n binding: toBinding(def),\n description: descriptionFor(def),\n }));\n\n/**\n * Serialize a document's `components.schemas` into the content-addressed defs\n * blob JSON (`{ \"<Name>\": <normalized schema>, ... }`), one schema at a time.\n * Normalizing + stringifying per entry keeps the whole normalized definition\n * tree from ever being co-resident with the parsed document, so the streaming\n * add path's peak stays near parse level. The serve path JSON-parses this blob\n * to rebuild the shared `definitions` instead of re-parsing the spec.\n */\nexport const buildDefsJson = (doc: ParsedDocument): string => {\n const schemas = doc.components?.schemas;\n if (!schemas) return \"{}\";\n let json = \"{\";\n let first = true;\n for (const [name, schema] of Object.entries(schemas)) {\n const serialized = JSON.stringify(normalizeOpenApiRefs(schema));\n if (serialized === undefined) continue;\n json += `${first ? \"\" : \",\"}${JSON.stringify(name)}:${serialized}`;\n first = false;\n }\n return `${json}}`;\n};\n\n/**\n * Streaming twin of `buildDefsJson`: serialize the content-addressed defs blob\n * from a `SpecStructure` by parsing each `components.schemas` entry in isolation\n * (indent-4 range) rather than from a whole-document parse. Used by the fully\n * streaming add path so the 37MB Microsoft Graph spec never builds its\n * ~300MB tree. The blob carries *all* source schemas (it is shared across every\n * tenant/selection on the same spec hash); extra unreferenced `$defs` are\n * harmless. Like `buildDefsJson`, normalizing + stringifying per entry keeps the\n * whole normalized tree from being co-resident with any parsed schema, and the\n * ConsString accumulation avoids the join-doubling of an array build.\n */\nexport const buildDefsJsonStreaming = (structure: SpecStructure): string => {\n let json = \"{\";\n let first = true;\n for (const range of structure.schemas) {\n const entry = parseEntry(structure.text, range, 4);\n if (!entry) continue;\n const [name, schema] = entry;\n const serialized = JSON.stringify(normalizeOpenApiRefs(schema));\n if (serialized === undefined) continue;\n json += `${first ? \"\" : \",\"}${JSON.stringify(name)}:${serialized}`;\n first = false;\n }\n return `${json}}`;\n};\n\nconst DefsJson = Schema.Record(Schema.String, Schema.Unknown);\n/** Decode the content-addressed defs blob back into the shared `definitions`\n * map. Returns `None` on a corrupt/non-object blob so the serve path falls\n * back to the spec re-parse rather than failing `tools/list`. */\nconst decodeDefsJson = Schema.decodeUnknownOption(Schema.fromJsonString(DefsJson));\n\n/** Rebuild a tool def from a stored operation binding, no spec parse. Mirrors\n * `openApiToolDefsFromCompiled` but sources its schemas from the persisted\n * binding (params/body/response carry `$ref`s into the shared defs blob). The\n * file-emit hint is applied here, at the same ToolDef projection step the\n * re-parse path applies it, so a file-returning op carries the contract\n * whether it is served fast (from the binding) or via the spec fallback. */\nconst toolDefFromStoredOperation = (op: StoredOperation): ToolDef => {\n const binding = op.binding;\n const returnsFile = Option.match(binding.responseBody, {\n onNone: () => false,\n onSome: (responseBody) => Option.isSome(responseBody.fileHint),\n });\n return {\n name: ToolName.make(op.toolName),\n description: withFileEmitHint(\n op.description ?? `${binding.method.toUpperCase()} ${binding.pathTemplate}`,\n returnsFile,\n ),\n inputSchema: normalizeOpenApiRefs(\n buildInputSchema(\n binding.parameters,\n Option.getOrUndefined(binding.requestBody),\n binding.servers ?? [],\n ),\n ),\n outputSchema: returnsFile\n ? ToolFileJsonSchema\n : Option.match(binding.responseBody, {\n onNone: () => undefined,\n onSome: (responseBody) =>\n normalizeOpenApiRefs(Option.getOrUndefined(responseBody.schema)),\n }),\n annotations: annotationsForOperation(binding.method, binding.pathTemplate),\n };\n};\n\nexport interface OpenApiPersistResult {\n readonly toolCount: number;\n readonly toolNames: readonly string[];\n}\n\n/**\n * Compile a parsed document straight to persisted operation bindings, streaming\n * in bounded chunks so a huge spec's bindings are never all co-resident with\n * the parsed tree. This is the memory-safe replacement for\n * `compileOpenApiDocument` + `openApiStoredOperationsFromCompiled` + `putOperations`\n * on the add/update path: it skips per-op input/output schema assembly (the\n * serve path rebuilds those on demand from the bindings). Clears existing\n * operations first, then appends each chunk. When `specHash` is given, also\n * stream-serializes the document's `#/$defs/*` into the content-addressed defs\n * blob so the serve path can resolve the shared `definitions` without\n * re-parsing the spec.\n */\nexport const compileAndPersistOpenApiOperations = ({\n doc,\n integration,\n storage,\n specHash,\n chunkSize,\n}: {\n readonly doc: ParsedDocument;\n readonly integration: string;\n readonly storage: OpenapiStore;\n readonly specHash?: string;\n readonly chunkSize?: number;\n}): Effect.Effect<OpenApiPersistResult, OpenApiExtractionError | StorageFailure> =>\n Effect.gen(function* () {\n yield* storage.removeOperations(integration);\n const result = yield* streamOperationBindings(doc, chunkSize ?? 500, (chunk) =>\n storage.appendOperations(\n integration,\n chunk.map((item) => ({\n integration,\n toolName: item.toolName,\n binding: item.binding,\n description: item.description,\n })),\n ),\n );\n if (specHash != null) {\n yield* storage.putDefs(specHash, buildDefsJson(doc));\n }\n return result;\n });\n\n/** Parse spec text, then stream-compile + persist its bindings (and, when\n * `specHash` is given, the content-addressed defs blob). */\nexport const compileAndPersistOpenApiSpec = ({\n specText,\n integration,\n storage,\n specHash,\n chunkSize,\n}: {\n readonly specText: string;\n readonly integration: string;\n readonly storage: OpenapiStore;\n readonly specHash?: string;\n readonly chunkSize?: number;\n}): Effect.Effect<\n OpenApiPersistResult,\n OpenApiParseError | OpenApiExtractionError | StorageFailure\n> =>\n Effect.gen(function* () {\n const doc = yield* parse(specText);\n return yield* compileAndPersistOpenApiOperations({\n doc,\n integration,\n storage,\n specHash,\n chunkSize,\n });\n });\n\n/**\n * Fully streaming add/update path: compile + persist operation bindings (and the\n * content-addressed defs blob) straight from spec *text*, without ever parsing\n * the whole document. The text is structurally split, then each path-item and\n * each schema is parsed in isolation and discarded, so peak memory stays near\n * one item rather than the ~300MB whole-tree parse that OOMs a 128MB Workers\n * isolate on the 37MB Microsoft Graph spec.\n *\n * There is deliberately no whole-parse fallback: a spec that does not present\n * the streamable block-YAML profile (no top-level `paths:` block) is a hard\n * `OpenApiExtractionError`, because the fallback is exactly the OOM this path\n * exists to avoid. `keepPathItem` optionally filters/trims path-items (the\n * Microsoft Graph scope selection), so the same primitive serves a full-spec\n * compile and a selection identically.\n */\nexport const compileAndPersistOpenApiSpecStreaming = ({\n specText,\n integration,\n storage,\n specHash,\n chunkSize,\n keepPathItem,\n}: {\n readonly specText: string;\n readonly integration: string;\n readonly storage: OpenapiStore;\n readonly specHash?: string;\n readonly chunkSize?: number;\n readonly keepPathItem?: KeepPathItem;\n}): Effect.Effect<OpenApiPersistResult, OpenApiExtractionError | StorageFailure> =>\n Effect.gen(function* () {\n const structure = structuralSplit(specText);\n if (!structure) {\n return yield* new OpenApiExtractionError({\n message:\n \"OpenAPI spec is not in the streamable block-YAML profile (no top-level `paths:` block); cannot stream-compile a spec this large in-band.\",\n });\n }\n yield* storage.removeOperations(integration);\n const result = yield* streamOperationBindingsFromStructure(\n structure,\n { chunkSize: chunkSize ?? 500, keepPathItem },\n (chunk) =>\n storage.appendOperations(\n integration,\n chunk.map((item) => ({\n integration,\n toolName: item.toolName,\n binding: item.binding,\n description: item.description,\n })),\n ),\n );\n if (specHash != null) {\n yield* storage.putDefs(specHash, buildDefsJsonStreaming(structure));\n }\n return result;\n });\n\nexport const loadOpenApiSpecText = (\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 * Resolve the tool defs + shared definitions for a connection refresh\n * (`tools/list`). Fast path: serve from the persisted operation bindings plus\n * the content-addressed defs blob, rebuilding each tool's input/output schema\n * on demand, so a 37MB spec is never re-parsed (the 2nd OOM site). The defs\n * blob is global per `specHash`, so the heavy normalize work is done once at\n * add time and shared across every tenant on the same spec. Falls back to the\n * spec re-parse for legacy rows persisted before the defs blob existed (or if\n * the blob is missing/corrupt).\n */\nexport const resolveOpenApiBackedTools = ({\n integration,\n config,\n storage,\n}: {\n readonly integration: { readonly slug: string };\n readonly config: unknown;\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 if (openApiConfig.specHash != null) {\n const defsJson = yield* storage.getDefs(openApiConfig.specHash);\n if (defsJson != null) {\n const definitions = Option.getOrNull(decodeDefsJson(defsJson));\n if (definitions != null) {\n const ops = yield* storage.listOperations(String(integration.slug));\n return { tools: ops.map(toolDefFromStoredOperation), definitions };\n }\n }\n }\n const specText = yield* loadOpenApiSpecText(storage, openApiConfig);\n if (specText == null) return { tools: [], definitions: {} };\n const compiled = yield* compileOpenApiSpec(specText).pipe(\n Effect.catch(() => Effect.succeed(null)),\n );\n if (!compiled) return { tools: [], definitions: {} };\n return {\n tools: openApiToolDefsFromCompiled(compiled),\n definitions: compiled.hoistedDefs,\n };\n });\n\nexport const invokeOpenApiBackedTool = (input: {\n readonly ctx: PluginCtx<OpenapiStore>;\n readonly toolRow: { readonly integration: string; readonly name: string };\n readonly credential: ToolInvocationCredential;\n readonly args: unknown;\n readonly httpClientLayer: Layer.Layer<HttpClient.HttpClient, never, never>;\n}) =>\n Effect.gen(function* () {\n const integration = input.toolRow.integration;\n const config = decodeOpenApiIntegrationConfig(input.credential.config);\n\n let binding = (yield* input.ctx.storage.getOperation(integration, input.toolRow.name))?.binding;\n // Only re-parse when the binding is entirely absent (a legacy row predating\n // persisted bindings). A present binding is authoritative even if it has no\n // responseBody: the persisted spec is now the *full* source (37MB for\n // Microsoft Graph), so re-parsing it here to \"enrich\" a binding would OOM\n // the isolate. A genuinely body-less operation must serve from its binding.\n if (!binding && config) {\n const specText = yield* loadOpenApiSpecText(input.ctx.storage, config).pipe(\n Effect.catch(() => Effect.succeed(null)),\n );\n const compiled =\n specText == null\n ? null\n : yield* compileOpenApiSpec(specText).pipe(Effect.catch(() => Effect.succeed(null)));\n binding = compiled\n ? openApiStoredOperationsFromCompiled(integration, compiled).find(\n (op) => op.toolName === input.toolRow.name,\n )?.binding\n : undefined;\n }\n if (!binding) {\n return yield* new OpenApiExtractionError({\n message: `No OpenAPI operation found for tool \"${input.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 const template = (config?.authenticationTemplate ?? []).find(\n (entry) => String(entry.slug) === String(input.credential.template),\n );\n if (template) {\n const missing = requiredTemplateVariables(template).filter((name) => {\n const value = input.credential.values[name];\n return value == null || value === \"\";\n });\n if (missing.length > 0) {\n return openApiAuthToolFailure({\n code:\n template.kind === \"oauth2\" ? \"oauth_connection_missing\" : \"connection_value_missing\",\n message: `Connection \"${input.credential.connection}\" for \"${integration}\" has no resolvable credential value. Re-authenticate or update the connection.`,\n owner: input.credential.owner,\n integration,\n connection: String(input.credential.connection),\n credentialKind: template.kind === \"oauth2\" ? \"oauth\" : \"secret\",\n });\n }\n const rendered = renderAuthTemplate(template, input.credential.values);\n Object.assign(headers, rendered.headers);\n Object.assign(queryParams, rendered.queryParams);\n }\n\n const result = yield* invokeWithLayer(\n binding,\n (input.args ?? {}) as Record<string, unknown>,\n config?.baseUrl ?? \"\",\n headers,\n queryParams,\n input.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 \"${input.credential.connection}\" before retrying this tool.`,\n owner: input.credential.owner,\n integration,\n connection: String(input.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: extractOpenApiUpstreamMessage(result.error, result.status),\n details: result.error,\n });\n }\n return ToolResult.ok(result.data, {\n http: { status: result.status, headers: result.headers },\n });\n });\n\nexport const resolveOpenApiBackedAnnotations = (input: {\n readonly ctx: PluginCtx<OpenapiStore>;\n readonly integration: string;\n readonly toolRows: readonly { readonly name: string }[];\n}) =>\n Effect.gen(function* () {\n const out: Record<string, ReturnType<typeof annotationsForOperation>> = {};\n for (const row of input.toolRows) {\n const operation = yield* input.ctx.storage.getOperation(input.integration, row.name);\n if (!operation) continue;\n out[row.name] = annotationsForOperation(\n operation.binding.method,\n operation.binding.pathTemplate,\n );\n }\n return out;\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 ToolResult,\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 StorageFailure,\n} from \"@executor-js/sdk/core\";\n\nimport { decodeOpenApiIntegrationConfig, type OpenApiIntegrationConfig } from \"./config\";\nimport { OpenApiExtractionError, OpenApiOAuthError, OpenApiParseError } from \"./errors\";\nimport { parse, resolveSpecText } from \"./parse\";\nimport { extract } from \"./extract\";\nimport {\n OAuth2AuthorizationCodeFlow,\n OAuth2Flows,\n OAuth2Preset,\n SecurityScheme,\n previewSpecText,\n type SpecPreview,\n} from \"./preview\";\nimport { deriveAuthenticationTemplateFromPreview, firstBaseUrlForPreview } from \"./derive-auth\";\nimport { openApiPresets } from \"./presets\";\nimport { makeDefaultOpenapiStore, type OpenapiStore } from \"./store\";\nimport type { Authentication } from \"./types\";\nimport { normalizeOpenApiAuthInputs, type AuthenticationInput } from \"./types\";\nimport { ApiKeyAuthTemplate, describeApiKeyAuthMethod } from \"@executor-js/sdk/http-auth\";\nimport {\n compileOpenApiSpec,\n invokeOpenApiBackedTool,\n openApiStoredOperationsFromCompiled,\n resolveOpenApiBackedAnnotations,\n resolveOpenApiBackedTools,\n} from \"./backing\";\nimport { resolveServerUrl } from \"./openapi-utils\";\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`. */\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 resource: Schema.NullOr(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 supportsClientIdMetadataDocument: Schema.optional(Schema.Boolean),\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]);\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 resource: Schema.optional(Schema.NullOr(Schema.String)),\n scopes: Schema.Array(Schema.String),\n supportsClientIdMetadataDocument: Schema.optional(Schema.Boolean),\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 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 resource: Option.getOrNull(preset.resource),\n refreshUrl: Option.getOrNull(preset.refreshUrl),\n scopes: preset.scopes,\n identityScopes: preset.identityScopes,\n supportsClientIdMetadataDocument: preset.supportsClientIdMetadataDocument,\n })),\n});\n\nconst specInputToSourceUrl = (spec: OpenApiSpecInput): string | undefined =>\n spec.kind === \"url\" ? spec.url : undefined;\n\nconst OAUTH_DISCOVERED_SCHEME_NAME = \"DiscoveredOAuth2\";\nconst OPENAPI_HTTP_METHODS = new Set([\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"patch\",\n \"head\",\n \"options\",\n \"trace\",\n]);\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst maybeUrl = (value: string): URL | null => {\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: URL parsing accepts user-pasted spec/base URLs\n try {\n return new URL(value);\n } catch {\n return null;\n }\n};\n\nconst addProbeCandidate = (candidates: string[], value: string | undefined): void => {\n const trimmed = value?.trim();\n if (!trimmed) return;\n const parsed = maybeUrl(trimmed);\n if (!parsed || (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\")) return;\n const normalized = parsed.toString();\n const origin = parsed.origin;\n if (!candidates.includes(normalized)) candidates.push(normalized);\n if (!candidates.includes(origin)) candidates.push(origin);\n};\n\nconst oauthProbeCandidates = (\n preview: SpecPreview,\n sourceUrl: string | undefined,\n baseUrl: string | undefined,\n): readonly string[] => {\n const candidates: string[] = [];\n addProbeCandidate(candidates, baseUrl);\n for (const server of preview.servers) {\n addProbeCandidate(\n candidates,\n resolveServerUrl(server.url, Option.getOrUndefined(server.variables), {}),\n );\n }\n addProbeCandidate(candidates, sourceUrl);\n return candidates;\n};\n\nconst securityRequirementScopes = (\n security: unknown,\n targetSchemes: ReadonlySet<string>,\n): readonly string[] => {\n if (!Array.isArray(security)) return [];\n const scopes = new Set<string>();\n for (const requirement of security) {\n if (!isRecord(requirement)) continue;\n for (const [scheme, rawScopes] of Object.entries(requirement)) {\n if (targetSchemes.size > 0 && !targetSchemes.has(scheme)) continue;\n if (!Array.isArray(rawScopes)) continue;\n for (const scope of rawScopes) {\n if (typeof scope === \"string\" && scope.trim().length > 0) scopes.add(scope.trim());\n }\n }\n }\n return [...scopes];\n};\n\nconst collectDeclaredSecurityScopes = (doc: unknown, targetSchemes: ReadonlySet<string>) => {\n const scopes = new Set<string>();\n if (!isRecord(doc)) return [] as readonly string[];\n\n for (const scope of securityRequirementScopes(doc.security, targetSchemes)) scopes.add(scope);\n\n const paths = doc.paths;\n if (!isRecord(paths)) return [...scopes].sort();\n for (const pathItem of Object.values(paths)) {\n if (!isRecord(pathItem)) continue;\n for (const [method, operation] of Object.entries(pathItem)) {\n if (!OPENAPI_HTTP_METHODS.has(method.toLowerCase()) || !isRecord(operation)) continue;\n for (const scope of securityRequirementScopes(operation.security, targetSchemes)) {\n scopes.add(scope);\n }\n }\n }\n return [...scopes].sort();\n};\n\nconst nonOAuthSecuritySchemeNames = (preview: SpecPreview): ReadonlySet<string> =>\n new Set(\n preview.securitySchemes\n .filter((scheme) => scheme.type === \"http\" || scheme.type === \"apiKey\")\n .map((scheme) => scheme.name),\n );\n\nconst discoveredOAuthPreview = (input: {\n readonly preview: SpecPreview;\n readonly authorizationUrl: string;\n readonly tokenUrl: string;\n readonly resource?: string | null;\n readonly scopes: readonly string[];\n readonly supportsClientIdMetadataDocument?: boolean;\n}): SpecPreview => {\n const scopes = Object.fromEntries(input.scopes.map((scope) => [scope, \"\"]));\n const flow = OAuth2AuthorizationCodeFlow.make({\n authorizationUrl: input.authorizationUrl,\n tokenUrl: input.tokenUrl,\n refreshUrl: Option.none(),\n scopes,\n });\n const flows = OAuth2Flows.make({\n authorizationCode: Option.some(flow),\n clientCredentials: Option.none(),\n });\n return {\n ...input.preview,\n securitySchemes: [\n ...input.preview.securitySchemes,\n SecurityScheme.make({\n name: OAUTH_DISCOVERED_SCHEME_NAME,\n type: \"oauth2\",\n scheme: Option.none(),\n bearerFormat: Option.none(),\n in: Option.none(),\n headerName: Option.none(),\n description: Option.some(\"Discovered from OAuth authorization-server metadata\"),\n flows: Option.some(flows),\n openIdConnectUrl: Option.none(),\n }),\n ],\n oauth2Presets: [\n ...input.preview.oauth2Presets,\n OAuth2Preset.make({\n label: `OAuth2 Authorization Code · ${OAUTH_DISCOVERED_SCHEME_NAME}`,\n securitySchemeName: OAUTH_DISCOVERED_SCHEME_NAME,\n flow: \"authorizationCode\",\n authorizationUrl: Option.some(input.authorizationUrl),\n tokenUrl: input.tokenUrl,\n resource: input.resource ? Option.some(input.resource) : Option.none(),\n refreshUrl: Option.none(),\n scopes,\n identityScopes: \"auto\",\n ...(input.supportsClientIdMetadataDocument === true\n ? { supportsClientIdMetadataDocument: true }\n : {}),\n }),\n ],\n };\n};\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 resource: template.resource ?? null,\n scopes: template.scopes,\n supportsClientIdMetadataDocument: template.supportsClientIdMetadataDocument,\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// Plugin factory\n// ---------------------------------------------------------------------------\n\nexport interface OpenApiPluginOptions {\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient, never, never>;\n}\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 },\n OpenApiParseError | OpenApiExtractionError | OpenApiOAuthError\n > =>\n Effect.gen(function* () {\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 enrichPreviewWithDiscoveredOAuth = (input: {\n readonly specText: string;\n readonly preview: SpecPreview;\n readonly sourceUrl?: string;\n readonly baseUrl?: string;\n }): Effect.Effect<SpecPreview, OpenApiParseError | OpenApiExtractionError> =>\n Effect.gen(function* () {\n if (input.preview.oauth2Presets.length > 0) return input.preview;\n\n const candidates = oauthProbeCandidates(input.preview, input.sourceUrl, input.baseUrl);\n if (candidates.length === 0) return input.preview;\n\n for (const candidate of candidates) {\n const oauth = yield* ctx.oauth.probe({ url: candidate }).pipe(\n Effect.map((result) => ({ ok: true as const, result })),\n Effect.catch(() => Effect.succeed({ ok: false as const, result: null })),\n );\n if (!oauth.ok) continue;\n\n const doc = yield* parse(input.specText);\n const declaredScopes = collectDeclaredSecurityScopes(\n doc,\n nonOAuthSecuritySchemeNames(input.preview),\n );\n const supportedScopes =\n oauth.result.scopesSupported && oauth.result.scopesSupported.length > 0\n ? new Set(oauth.result.scopesSupported)\n : null;\n const scopes = supportedScopes\n ? declaredScopes.filter((scope) => supportedScopes.has(scope))\n : declaredScopes;\n return discoveredOAuthPreview({\n preview: input.preview,\n authorizationUrl: oauth.result.authorizationUrl,\n tokenUrl: oauth.result.tokenUrl,\n resource: oauth.result.resource ?? null,\n scopes,\n supportsClientIdMetadataDocument:\n oauth.result.clientIdMetadataDocumentSupported === true,\n });\n }\n\n return input.preview;\n });\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* compileOpenApiSpec(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;\n const needsDerivedBaseUrl = explicitBaseUrl == null;\n const needsDerivedAuth = config.authenticationTemplate == null;\n const preview =\n needsDerivedBaseUrl || needsDerivedAuth\n ? yield* previewSpecText(resolved.specText).pipe(\n Effect.flatMap((rawPreview) =>\n enrichPreviewWithDiscoveredOAuth({\n specText: resolved.specText,\n preview: rawPreview,\n sourceUrl: specInputToSourceUrl(config.spec),\n baseUrl: config.baseUrl,\n }),\n ),\n )\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 // 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 derive from the\n // spec's declared security schemes.\n ...(config.authenticationTemplate\n ? {\n authenticationTemplate: normalizeOpenApiAuthInputs(config.authenticationTemplate),\n }\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 // The content-addressed defs blob lets the serve path resolve the\n // shared `definitions` without re-parsing the spec. Same idempotent,\n // outside-the-transaction rationale as the spec blob.\n yield* ctx.storage.putDefs(specHash, JSON.stringify(compiled.hoistedDefs));\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: specInputToSourceUrl(config.spec) != null,\n });\n yield* ctx.storage.putOperations(\n config.slug,\n openApiStoredOperationsFromCompiled(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 ?? (current.sourceUrl ? { kind: \"url\", url: current.sourceUrl } : 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* compileOpenApiSpec(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 yield* ctx.storage.putDefs(specHash, JSON.stringify(compiled.hoistedDefs));\n\n const nextConfig: OpenApiIntegrationConfig = {\n ...current,\n specHash,\n ...(specInputToSourceUrl(specInput) !== undefined\n ? { sourceUrl: specInputToSourceUrl(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 openApiStoredOperationsFromCompiled(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 = yield* resolveSpecText(previewInput.spec).pipe(\n Effect.provide(httpClientLayer),\n );\n const preview = yield* previewSpecText(specText);\n return yield* enrichPreviewWithDiscoveredOAuth({\n specText,\n preview,\n sourceUrl: maybeUrl(previewInput.spec.trim()) ? previewInput.spec.trim() : undefined,\n });\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: ({ integration, config, storage }) =>\n resolveOpenApiBackedTools({ integration, config, storage }),\n\n invokeTool: ({ ctx: invokeCtx, toolRow, credential, args }) => {\n const httpClientLayer = options?.httpClientLayer ?? invokeCtx.httpClientLayer;\n return invokeOpenApiBackedTool({\n ctx: invokeCtx,\n toolRow,\n credential,\n args,\n httpClientLayer,\n });\n },\n\n resolveAnnotations: ({ ctx: annotationsCtx, integration, toolRows }) =>\n resolveOpenApiBackedAnnotations({\n ctx: annotationsCtx,\n integration: String(integration),\n toolRows,\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 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"],"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,UAAU,OAAO,SAAS,OAAO,OAAO,OAAO,MAAM,CAAC;AAAA,EACtD,QAAQ,OAAO,MAAM,OAAO,MAAM;AAAA,EAClC,kCAAkC,OAAO,SAAS,OAAO,O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AK,QAAO;AACjB,YAAM,SAAS,OAAO,QAAQ,GAAG,EAAE,KAAKA,QAAO,MAAM,MAAMA,QAAO,QAAQ,IAAI,CAAC,CAAC;AAChF,UAAI,CAAC,OAAQ,QAAO;AACpB,YAAM,OAAOD,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","Schema","Schema","Option","Effect","Option","Option","Effect","bytes","Effect","Option","Schema","Schema","Option","message","changed","Effect","Effect","Option","Schema","ToolResult","Schema","AuthenticationSchema","ToolResult","Option","Effect"]}
|
|
@@ -56,6 +56,14 @@ var openApiOnlyPresets = [
|
|
|
56
56
|
icon: "https://svgl.app/library/sentry.svg",
|
|
57
57
|
featured: true
|
|
58
58
|
},
|
|
59
|
+
{
|
|
60
|
+
id: "posthog",
|
|
61
|
+
name: "PostHog",
|
|
62
|
+
summary: "Product analytics, events, feature flags, and insights.",
|
|
63
|
+
url: "https://us.posthog.com/api/schema/",
|
|
64
|
+
icon: "https://svgl.app/library/posthog.svg",
|
|
65
|
+
featured: true
|
|
66
|
+
},
|
|
59
67
|
{
|
|
60
68
|
id: "exa",
|
|
61
69
|
name: "Exa",
|
|
@@ -134,4 +142,4 @@ var openApiPresets = openApiOnlyPresets;
|
|
|
134
142
|
export {
|
|
135
143
|
openApiPresets
|
|
136
144
|
};
|
|
137
|
-
//# sourceMappingURL=chunk-
|
|
145
|
+
//# sourceMappingURL=chunk-HG5JB2UJ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sdk/presets.ts"],"sourcesContent":["export interface OpenApiPreset {\n readonly id: string;\n readonly name: string;\n readonly summary: string;\n readonly url?: string;\n readonly icon?: string;\n readonly featured?: boolean;\n}\n\nconst openApiOnlyPresets: readonly OpenApiPreset[] = [\n {\n id: \"stripe\",\n name: \"Stripe\",\n summary: \"Payments, subscriptions, customers, and invoices.\",\n url: \"https://raw.githubusercontent.com/stripe/openapi/master/openapi/spec3.json\",\n icon: \"https://stripe.com/favicon.ico\",\n featured: true,\n },\n {\n id: \"github-rest\",\n name: \"GitHub REST\",\n summary: \"Repos, issues, pull requests, actions, and users.\",\n url: \"https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.json\",\n icon: \"https://svgl.app/library/github_dark.svg\",\n featured: true,\n },\n {\n id: \"vercel\",\n name: \"Vercel\",\n summary: \"Deployments, domains, projects, and edge config.\",\n url: \"https://openapi.vercel.sh\",\n icon: \"https://vercel.com/favicon.ico\",\n featured: true,\n },\n {\n id: \"cloudflare\",\n name: \"Cloudflare\",\n summary: \"DNS, workers, pages, R2, and security rules.\",\n url: \"https://raw.githubusercontent.com/cloudflare/api-schemas/main/openapi.json\",\n icon: \"https://cloudflare.com/favicon.ico\",\n featured: true,\n },\n {\n id: \"neon\",\n name: \"Neon\",\n summary: \"Serverless Postgres: projects, branches, and endpoints.\",\n url: \"https://neon.tech/api_spec/release/v2.json\",\n icon: \"https://neon.tech/favicon/favicon.ico\",\n featured: true,\n },\n {\n id: \"openai\",\n name: \"OpenAI\",\n summary: \"Models, files, responses, and fine-tuning.\",\n url: \"https://app.stainless.com/api/spec/documented/openai/openapi.documented.yml\",\n icon: \"https://svgl.app/library/openai_dark.svg\",\n featured: true,\n },\n {\n id: \"sentry\",\n name: \"Sentry\",\n summary: \"Error tracking, performance monitoring, and releases.\",\n url: \"https://raw.githubusercontent.com/getsentry/sentry-api-schema/main/openapi-derefed.json\",\n icon: \"https://svgl.app/library/sentry.svg\",\n featured: true,\n },\n {\n id: \"exa\",\n name: \"Exa\",\n summary: \"Web search, similar links, content retrieval, and answers.\",\n url: \"https://raw.githubusercontent.com/exa-labs/openapi-spec/refs/heads/master/exa-openapi-spec.yaml\",\n icon: \"https://exa.ai/images/favicon-32x32.png\",\n featured: true,\n },\n {\n id: \"exa-websets\",\n name: \"Exa Websets\",\n summary: \"Websets, enrichments, webhooks, and monitors.\",\n url: \"https://raw.githubusercontent.com/exa-labs/openapi-spec/refs/heads/master/exa-websets-spec.yaml\",\n icon: \"https://exa.ai/images/favicon-32x32.png\",\n featured: true,\n },\n {\n id: \"axiom\",\n name: \"Axiom\",\n summary: \"Log ingestion, querying, datasets, and monitors.\",\n url: \"https://axiom.co/docs/restapi/versions/v2.json\",\n icon: \"https://axiom.co/favicon.ico\",\n },\n {\n id: \"asana\",\n name: \"Asana\",\n summary: \"Tasks, projects, teams, and workspace management.\",\n url: \"https://raw.githubusercontent.com/APIs-guru/openapi-directory/main/APIs/asana.com/1.0/openapi.yaml\",\n icon: \"https://asana.com/favicon.ico\",\n },\n {\n id: \"twilio\",\n name: \"Twilio\",\n summary: \"SMS, voice, video, and messaging APIs.\",\n url: \"https://raw.githubusercontent.com/twilio/twilio-oai/main/spec/json/twilio_api_v2010.json\",\n icon: \"https://twilio.com/favicon.ico\",\n },\n {\n id: \"digitalocean\",\n name: \"DigitalOcean\",\n summary: \"Droplets, Kubernetes, databases, and networking.\",\n url: \"https://raw.githubusercontent.com/digitalocean/openapi/main/specification/DigitalOcean-public.v2.yaml\",\n icon: \"https://assets.digitalocean.com/favicon.ico\",\n },\n {\n id: \"petstore\",\n name: \"Petstore\",\n summary: \"Classic OpenAPI demo, no auth required.\",\n url: \"https://petstore3.swagger.io/api/v3/openapi.json\",\n icon: \"https://petstore3.swagger.io/favicon-32x32.png\",\n },\n {\n id: \"val-town\",\n name: \"Val Town\",\n summary: \"Vals, runs, blobs, and email/web endpoints.\",\n url: \"https://api.val.town/openapi.json\",\n icon: \"https://www.val.town/favicon.svg\",\n },\n {\n id: \"resend\",\n name: \"Resend\",\n summary: \"Transactional email sending and domain management.\",\n url: \"https://raw.githubusercontent.com/resend/resend-openapi/main/resend.yaml\",\n icon: \"https://resend.com/static/favicons/favicon.ico\",\n },\n {\n id: \"spotify\",\n name: \"Spotify\",\n summary: \"Tracks, albums, playlists, library, and playback.\",\n url: \"https://raw.githubusercontent.com/sonallux/spotify-web-api/refs/heads/main/official-spotify-open-api.yml\",\n icon: \"https://svgl.app/library/spotify.svg\",\n },\n];\n\nexport const openApiPresets: readonly OpenApiPreset[] = openApiOnlyPresets;\n"],"mappings":";AASA,IAAM,qBAA+C;AAAA,EACnD;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,EACR;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,EACR;AACF;AAEO,IAAM,iBAA2C;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/sdk/presets.ts"],"sourcesContent":["export interface OpenApiPreset {\n readonly id: string;\n readonly name: string;\n readonly summary: string;\n readonly url?: string;\n readonly icon?: string;\n readonly featured?: boolean;\n}\n\nconst openApiOnlyPresets: readonly OpenApiPreset[] = [\n {\n id: \"stripe\",\n name: \"Stripe\",\n summary: \"Payments, subscriptions, customers, and invoices.\",\n url: \"https://raw.githubusercontent.com/stripe/openapi/master/openapi/spec3.json\",\n icon: \"https://stripe.com/favicon.ico\",\n featured: true,\n },\n {\n id: \"github-rest\",\n name: \"GitHub REST\",\n summary: \"Repos, issues, pull requests, actions, and users.\",\n url: \"https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.json\",\n icon: \"https://svgl.app/library/github_dark.svg\",\n featured: true,\n },\n {\n id: \"vercel\",\n name: \"Vercel\",\n summary: \"Deployments, domains, projects, and edge config.\",\n url: \"https://openapi.vercel.sh\",\n icon: \"https://vercel.com/favicon.ico\",\n featured: true,\n },\n {\n id: \"cloudflare\",\n name: \"Cloudflare\",\n summary: \"DNS, workers, pages, R2, and security rules.\",\n url: \"https://raw.githubusercontent.com/cloudflare/api-schemas/main/openapi.json\",\n icon: \"https://cloudflare.com/favicon.ico\",\n featured: true,\n },\n {\n id: \"neon\",\n name: \"Neon\",\n summary: \"Serverless Postgres: projects, branches, and endpoints.\",\n url: \"https://neon.tech/api_spec/release/v2.json\",\n icon: \"https://neon.tech/favicon/favicon.ico\",\n featured: true,\n },\n {\n id: \"openai\",\n name: \"OpenAI\",\n summary: \"Models, files, responses, and fine-tuning.\",\n url: \"https://app.stainless.com/api/spec/documented/openai/openapi.documented.yml\",\n icon: \"https://svgl.app/library/openai_dark.svg\",\n featured: true,\n },\n {\n id: \"sentry\",\n name: \"Sentry\",\n summary: \"Error tracking, performance monitoring, and releases.\",\n url: \"https://raw.githubusercontent.com/getsentry/sentry-api-schema/main/openapi-derefed.json\",\n icon: \"https://svgl.app/library/sentry.svg\",\n featured: true,\n },\n {\n id: \"posthog\",\n name: \"PostHog\",\n summary: \"Product analytics, events, feature flags, and insights.\",\n url: \"https://us.posthog.com/api/schema/\",\n icon: \"https://svgl.app/library/posthog.svg\",\n featured: true,\n },\n {\n id: \"exa\",\n name: \"Exa\",\n summary: \"Web search, similar links, content retrieval, and answers.\",\n url: \"https://raw.githubusercontent.com/exa-labs/openapi-spec/refs/heads/master/exa-openapi-spec.yaml\",\n icon: \"https://exa.ai/images/favicon-32x32.png\",\n featured: true,\n },\n {\n id: \"exa-websets\",\n name: \"Exa Websets\",\n summary: \"Websets, enrichments, webhooks, and monitors.\",\n url: \"https://raw.githubusercontent.com/exa-labs/openapi-spec/refs/heads/master/exa-websets-spec.yaml\",\n icon: \"https://exa.ai/images/favicon-32x32.png\",\n featured: true,\n },\n {\n id: \"axiom\",\n name: \"Axiom\",\n summary: \"Log ingestion, querying, datasets, and monitors.\",\n url: \"https://axiom.co/docs/restapi/versions/v2.json\",\n icon: \"https://axiom.co/favicon.ico\",\n },\n {\n id: \"asana\",\n name: \"Asana\",\n summary: \"Tasks, projects, teams, and workspace management.\",\n url: \"https://raw.githubusercontent.com/APIs-guru/openapi-directory/main/APIs/asana.com/1.0/openapi.yaml\",\n icon: \"https://asana.com/favicon.ico\",\n },\n {\n id: \"twilio\",\n name: \"Twilio\",\n summary: \"SMS, voice, video, and messaging APIs.\",\n url: \"https://raw.githubusercontent.com/twilio/twilio-oai/main/spec/json/twilio_api_v2010.json\",\n icon: \"https://twilio.com/favicon.ico\",\n },\n {\n id: \"digitalocean\",\n name: \"DigitalOcean\",\n summary: \"Droplets, Kubernetes, databases, and networking.\",\n url: \"https://raw.githubusercontent.com/digitalocean/openapi/main/specification/DigitalOcean-public.v2.yaml\",\n icon: \"https://assets.digitalocean.com/favicon.ico\",\n },\n {\n id: \"petstore\",\n name: \"Petstore\",\n summary: \"Classic OpenAPI demo, no auth required.\",\n url: \"https://petstore3.swagger.io/api/v3/openapi.json\",\n icon: \"https://petstore3.swagger.io/favicon-32x32.png\",\n },\n {\n id: \"val-town\",\n name: \"Val Town\",\n summary: \"Vals, runs, blobs, and email/web endpoints.\",\n url: \"https://api.val.town/openapi.json\",\n icon: \"https://www.val.town/favicon.svg\",\n },\n {\n id: \"resend\",\n name: \"Resend\",\n summary: \"Transactional email sending and domain management.\",\n url: \"https://raw.githubusercontent.com/resend/resend-openapi/main/resend.yaml\",\n icon: \"https://resend.com/static/favicons/favicon.ico\",\n },\n {\n id: \"spotify\",\n name: \"Spotify\",\n summary: \"Tracks, albums, playlists, library, and playback.\",\n url: \"https://raw.githubusercontent.com/sonallux/spotify-web-api/refs/heads/main/official-spotify-open-api.yml\",\n icon: \"https://svgl.app/library/spotify.svg\",\n },\n];\n\nexport const openApiPresets: readonly OpenApiPreset[] = openApiOnlyPresets;\n"],"mappings":";AASA,IAAM,qBAA+C;AAAA,EACnD;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,EACZ;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,MAAM;AAA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A,IACJ,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA,EACR;AACF;AAEO,IAAM,iBAA2C;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
resolveServerUrl
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-WWZ7B34D.js";
|
|
4
4
|
|
|
5
5
|
// src/sdk/derive-auth.ts
|
|
6
6
|
import * as Option from "effect/Option";
|
|
@@ -78,7 +78,9 @@ var oauthTemplateFromPreset = (preset, baseUrl, slug, scopes) => ({
|
|
|
78
78
|
baseUrl
|
|
79
79
|
),
|
|
80
80
|
tokenUrl: resolveOAuthUrl(preset.tokenUrl, baseUrl),
|
|
81
|
-
|
|
81
|
+
resource: Option.getOrUndefined(preset.resource) ?? null,
|
|
82
|
+
scopes: [...scopes],
|
|
83
|
+
...preset.supportsClientIdMetadataDocument === true ? { supportsClientIdMetadataDocument: true } : {}
|
|
82
84
|
});
|
|
83
85
|
var detectedAuthenticationTemplates = (headerPresets, oauth2Presets, baseUrl) => {
|
|
84
86
|
const templates = [];
|
|
@@ -115,4 +117,4 @@ export {
|
|
|
115
117
|
firstBaseUrlForPreview,
|
|
116
118
|
deriveAuthenticationTemplateFromPreview
|
|
117
119
|
};
|
|
118
|
-
//# sourceMappingURL=chunk-
|
|
120
|
+
//# sourceMappingURL=chunk-IVRAOG3T.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sdk/derive-auth.ts"],"sourcesContent":["// 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, SpecPreviewSummary } from \"./preview\";\nimport type { APIKeyAuthentication, Authentication } from \"./types\";\nimport { resolveServerUrl } from \"./openapi-utils\";\n\ntype PreviewAuthMetadata = SpecPreview | SpecPreviewSummary;\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). A single-header preset becomes an `apiKey`\n// template whose secret header value renders from the conventional `token`\n// input. A multi-header preset gets one input per header, matching OpenAPI's\n// security-strategy semantics where multiple schemes in one object are required\n// together. The oauth2 preset becomes an `oauth` template carrying the provider\n// 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 slugifyVariable = (name: string): string =>\n name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\nconst variablesForHeaders = (headerNames: readonly string[]): ReadonlyMap<string, string> => {\n const variables = new Map<string, string>();\n if (headerNames.length <= 1) return variables;\n\n const taken = new Set<string>();\n for (const headerName of headerNames) {\n const base = slugifyVariable(headerName) || \"input\";\n let variable = base;\n for (let suffix = 2; taken.has(variable); suffix += 1) {\n variable = `${base}_${suffix}`;\n }\n taken.add(variable);\n variables.set(headerName, variable);\n }\n return variables;\n};\n\nconst apiKeyTemplateFromHeaderPreset = (\n preset: HeaderPreset,\n slug: AuthTemplateSlug,\n): APIKeyAuthentication => {\n const variables = variablesForHeaders(preset.secretHeaders);\n return {\n slug,\n kind: \"apikey\",\n placements: preset.secretHeaders.map((headerName) => {\n const prefix = headerPrefix(preset, headerName);\n const variable = variables.get(headerName);\n return {\n carrier: \"header\" as const,\n name: headerName,\n ...(prefix ? { prefix } : {}),\n ...(variable ? { variable } : {}),\n };\n }),\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: PreviewAuthMetadata): 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: PreviewAuthMetadata,\n baseUrl: string | undefined,\n): readonly Authentication[] =>\n detectedAuthenticationTemplates(\n preview.headerPresets,\n preview.oauth2Presets,\n baseUrl ?? firstBaseUrlForPreview(preview),\n );\n"],"mappings":";;;;;AAOA,YAAY,YAAY;AAExB,SAAS,wBAAkD;AAapD,SAAS,gBAAgB,KAAa,SAAyB;AACpE,MAAI,CAAC,IAAK,QAAO;AAEjB,MAAI;AACF,QAAI,IAAI,GAAG;AACX,WAAO;AAAA,EACT,QAAQ;AACN,QAAI,CAAC,QAAS,QAAO;AAErB,QAAI;AACF,aAAO,IAAI,IAAI,KAAK,OAAO,EAAE,SAAS;AAAA,IACxC,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAEA,IAAM,6BAA6B,CAAC,UAAU,SAAS,SAAS;AAEhE,IAAM,0BAA0B,CAC9B,mBACsB;AACtB,MAAI,mBAAmB,MAAO,QAAO,CAAC;AACtC,SAAO,mBAAmB,SAAS,6BAA6B;AAClE;AAEO,I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AA,QAC3B,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;AAAA,MACjC;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAEA,IAAM,0BAA0B,CAC9B,QACA,SACA,MACA,YACyB;AAAA,EACzB;AAAA,EACA,MAAM;AAAA,EACN,kBAAkB;AAAA,IACT,iBAAU,OAAO,kBAAkB,MAAM,EAAE;AAAA,IAClD;AAAA,EACF;AAAA,EACA,UAAU,gBAAgB,OAAO,UAAU,OAAO;AAAA,EAClD,QAAQ,CAAC,GAAG,MAAM;
|
|
1
|
+
{"version":3,"sources":["../src/sdk/derive-auth.ts"],"sourcesContent":["// 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, SpecPreviewSummary } from \"./preview\";\nimport type { APIKeyAuthentication, Authentication } from \"./types\";\nimport { resolveServerUrl } from \"./openapi-utils\";\n\ntype PreviewAuthMetadata = SpecPreview | SpecPreviewSummary;\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). A single-header preset becomes an `apiKey`\n// template whose secret header value renders from the conventional `token`\n// input. A multi-header preset gets one input per header, matching OpenAPI's\n// security-strategy semantics where multiple schemes in one object are required\n// together. The oauth2 preset becomes an `oauth` template carrying the provider\n// 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 slugifyVariable = (name: string): string =>\n name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\nconst variablesForHeaders = (headerNames: readonly string[]): ReadonlyMap<string, string> => {\n const variables = new Map<string, string>();\n if (headerNames.length <= 1) return variables;\n\n const taken = new Set<string>();\n for (const headerName of headerNames) {\n const base = slugifyVariable(headerName) || \"input\";\n let variable = base;\n for (let suffix = 2; taken.has(variable); suffix += 1) {\n variable = `${base}_${suffix}`;\n }\n taken.add(variable);\n variables.set(headerName, variable);\n }\n return variables;\n};\n\nconst apiKeyTemplateFromHeaderPreset = (\n preset: HeaderPreset,\n slug: AuthTemplateSlug,\n): APIKeyAuthentication => {\n const variables = variablesForHeaders(preset.secretHeaders);\n return {\n slug,\n kind: \"apikey\",\n placements: preset.secretHeaders.map((headerName) => {\n const prefix = headerPrefix(preset, headerName);\n const variable = variables.get(headerName);\n return {\n carrier: \"header\" as const,\n name: headerName,\n ...(prefix ? { prefix } : {}),\n ...(variable ? { variable } : {}),\n };\n }),\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 resource: Option.getOrUndefined(preset.resource) ?? null,\n scopes: [...scopes],\n ...(preset.supportsClientIdMetadataDocument === true\n ? { supportsClientIdMetadataDocument: true }\n : {}),\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: PreviewAuthMetadata): 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: PreviewAuthMetadata,\n baseUrl: string | undefined,\n): readonly Authentication[] =>\n detectedAuthenticationTemplates(\n preview.headerPresets,\n preview.oauth2Presets,\n baseUrl ?? firstBaseUrlForPreview(preview),\n );\n"],"mappings":";;;;;AAOA,YAAY,YAAY;AAExB,SAAS,wBAAkD;AAapD,SAAS,gBAAgB,KAAa,SAAyB;AACpE,MAAI,CAAC,IAAK,QAAO;AAEjB,MAAI;AACF,QAAI,IAAI,GAAG;AACX,WAAO;AAAA,EACT,QAAQ;AACN,QAAI,CAAC,QAAS,QAAO;AAErB,QAAI;AACF,aAAO,IAAI,IAAI,KAAK,OAAO,EAAE,SAAS;AAAA,IACxC,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAEA,IAAM,6BAA6B,CAAC,UAAU,SAAS,SAAS;AAEhE,IAAM,0BAA0B,CAC9B,mBACsB;AACtB,MAAI,mBAAmB,MAAO,QAAO,CAAC;AACtC,SAAO,mBAAmB,SAAS,6BAA6B;AAClE;AAEO,IAAM,sBAAsB,CACjC,WACA,mBACa;AACb,QAAM,SAAS,IAAI,IAAI,SAAS;AAChC,aAAW,SAAS,wBAAwB,cAAc,EAAG,QAAO,IAAI,KAAK;AAC7E,SAAO,CAAC,GAAG,MAAM;AACnB;AAYA,IAAM,eAAe,CAAC,QAAsB,eAA2C;AACrF,QAAM,QAAQ,OAAO,MAAM,YAAY;AACvC,MAAI,WAAW,YAAY,MAAM,iBAAiB;AAChD,QAAI,MAAM,SAAS,QAAQ,EAAG,QAAO;AACrC,QAAI,MAAM,SAAS,OAAO,EAAG,QAAO;AAAA,EACtC;AACA,SAAO;AACT;AAEA,IAAM,kBAAkB,CAAC,SACvB,KACG,YAAY,EACZ,QAAQ,eAAe,GAAG,EAC1B,QAAQ,YAAY,E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