capable-kit 0.0.1-alpha.7 → 0.1.0-alpha.10
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/CHANGELOG.md +214 -0
- package/README.md +6 -0
- package/dist/ai-sdk.d.mts +3 -3
- package/dist/ai-sdk.mjs +9 -7
- package/dist/ai-sdk.mjs.map +1 -1
- package/dist/app.d.mts +2 -2
- package/dist/app.mjs +2 -2
- package/dist/bin.mjs +12 -9
- package/dist/bin.mjs.map +1 -1
- package/dist/cli.d.mts +9 -1
- package/dist/cli.mjs +1 -1
- package/dist/core.d.mts +3 -3
- package/dist/core.mjs +1 -1
- package/dist/eve.d.mts +82 -5
- package/dist/eve.mjs +364 -23
- package/dist/eve.mjs.map +1 -1
- package/dist/http.d.mts +2 -2
- package/dist/http.mjs +2 -2
- package/dist/{index-Dbc4g9WM.d.mts → index-1A44jLuE.d.mts} +54 -16
- package/dist/{index-DwXlaTXI.d.mts → index-CHuCLJIs.d.mts} +20 -4
- package/dist/{index-D2CRRUzH.d.mts → index-D-NV4PiU.d.mts} +6 -5
- package/dist/{index-Be8-UVBC.d.mts → index-WiBWfyTn.d.mts} +66 -27
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +3 -3
- package/dist/mcp.d.mts +40 -5
- package/dist/mcp.mjs +1 -1
- package/dist/mount-BmLHp349.mjs +235 -0
- package/dist/mount-BmLHp349.mjs.map +1 -0
- package/dist/react-query.d.mts +2 -2
- package/dist/react-query.mjs +1 -1
- package/dist/react-query.mjs.map +1 -1
- package/dist/runtime-support.d.mts +1 -1
- package/dist/runtime-support.mjs +8 -8
- package/dist/runtime-support.mjs.map +1 -1
- package/dist/server.d.mts +1 -1
- package/dist/server.mjs +1 -1
- package/dist/{src-Db6-XSnU.mjs → src-3LE9S4QE.mjs} +67 -38
- package/dist/src-3LE9S4QE.mjs.map +1 -0
- package/dist/{src-DdV82An-.mjs → src-B2WeUwUT.mjs} +69 -34
- package/dist/src-B2WeUwUT.mjs.map +1 -0
- package/dist/{src-CDxL6w3d.mjs → src-C5jGDnuu.mjs} +9 -6
- package/dist/src-C5jGDnuu.mjs.map +1 -0
- package/dist/src-DePlcG_t.mjs +787 -0
- package/dist/src-DePlcG_t.mjs.map +1 -0
- package/dist/{src-BF70JLxI.mjs → src-_6OmFRYa.mjs} +185 -38
- package/dist/src-_6OmFRYa.mjs.map +1 -0
- package/dist/{subscription-Bq792Ad2.d.mts → subscription-DPdwovhw.d.mts} +2 -2
- package/dist/swr.d.mts +2 -2
- package/dist/swr.mjs +1 -1
- package/dist/swr.mjs.map +1 -1
- package/docs/CONTEXT.md +42 -21
- package/docs/README.md +3 -0
- package/docs/internal/README.md +3 -0
- package/docs/internal/adr/0001-capability-is-the-semantic-boundary.md +1 -1
- package/docs/internal/adr/0002-version-the-capable-value-codec.md +24 -0
- package/docs/internal/adr/0003-capability-reference-customization.md +68 -0
- package/docs/internal/architecture.md +64 -19
- package/docs/internal/capability-first-model.md +127 -18
- package/docs/internal/eve-recovery-validation.md +86 -0
- package/docs/internal/feedback/v-ray/README.md +258 -0
- package/docs/internal/feedback/v-ray/inference.mjs +43 -0
- package/docs/internal/feedback/v-ray/reproduce.mjs +36 -0
- package/docs/internal/implementation-friction.md +481 -1
- package/docs/internal/releases.md +79 -0
- package/docs/site/capable-orpc-and-trpc.mdx +5 -5
- package/docs/site/concepts/apps.mdx +17 -8
- package/docs/site/concepts/architecture.mdx +10 -2
- package/docs/site/concepts/capabilities.mdx +41 -4
- package/docs/site/concepts/errors.mdx +11 -1
- package/docs/site/concepts/presentations.mdx +20 -0
- package/docs/site/hosting/any-fetch-host.mdx +2 -2
- package/docs/site/hosting/next-js.mdx +38 -4
- package/docs/site/hosting/standalone-server.mdx +2 -2
- package/docs/site/introduction.mdx +9 -6
- package/docs/site/patterns/composition.mdx +159 -11
- package/docs/site/patterns/remote-apps.mdx +68 -10
- package/docs/site/patterns/subscriptions.mdx +79 -32
- package/docs/site/quickstart.mdx +19 -14
- package/docs/site/reference/packages-and-entry-points.mdx +52 -5
- package/docs/site/reference/surface-metadata.mdx +7 -2
- package/docs/site/reference/the-cap-cli.mdx +2 -2
- package/docs/site/surfaces/ai-sdk.mdx +3 -3
- package/docs/site/surfaces/cli.mdx +47 -3
- package/docs/site/surfaces/eve.mdx +67 -20
- package/docs/site/surfaces/mcp.mdx +73 -5
- package/docs/site/surfaces/react-query.mdx +3 -3
- package/docs/site/surfaces/swr.mdx +3 -3
- package/docs/site/surfaces/typescript.mdx +8 -8
- package/docs/site/surfaces.mdx +1 -1
- package/package-docs.mjs +3 -0
- package/package.json +11 -11
- package/src/bin.ts +0 -0
- package/src/index.test.ts +2 -1
- package/src/index.ts +6 -1
- package/src/mcp.ts +4 -0
- package/src/package.test.ts +9 -0
- package/dist/mount-xvMsjz1B.mjs +0 -178
- package/dist/mount-xvMsjz1B.mjs.map +0 -1
- package/dist/src-BF70JLxI.mjs.map +0 -1
- package/dist/src-C2MGIlT0.mjs +0 -464
- package/dist/src-C2MGIlT0.mjs.map +0 -1
- package/dist/src-CDxL6w3d.mjs.map +0 -1
- package/dist/src-Db6-XSnU.mjs.map +0 -1
- package/dist/src-DdV82An-.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mount-xvMsjz1B.mjs","names":[],"sources":["../../mcp/src/index.ts","../../mcp/src/presentation.ts","../../mcp/src/mount.ts"],"sourcesContent":["import type { CapabilityMetaRegistry } from \"@capable/core\";\nimport {\n getAppRuntime,\n type AnyApp,\n type JsonSchema,\n type ManifestNode,\n type ManifestCapability,\n type CapabilityResult,\n} from \"@capable/app\";\n\nexport type McpCapabilityMeta =\n | false\n | {\n readonly name?: string;\n };\n\ndeclare module \"@capable/core\" {\n interface CapabilityMetaRegistry {\n readonly mcp?: McpCapabilityMeta;\n }\n}\n\nexport type McpTool = {\n readonly name: string;\n readonly title?: string;\n readonly description?: string;\n readonly inputSchema: JsonSchema;\n readonly outputSchema?: JsonSchema;\n readonly annotations: {\n readonly readOnlyHint: boolean;\n readonly destructiveHint: boolean;\n };\n call(\n input: unknown,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapabilityResult>;\n};\n\nexport async function createMcp(\n app: AnyApp,\n): Promise<readonly McpTool[]> {\n const runtime = getAppRuntime(app);\n const manifest = await runtime.manifest();\n const tools = flatten(manifest.capabilities)\n .filter((capability) => capability.meta.mcp !== false)\n .map((capability) => {\n const meta = capability.meta.mcp as Exclude<McpCapabilityMeta, false> | undefined;\n return Object.freeze({\n name: meta?.name ?? capability.path.join(\"__\"),\n ...(capability.title ? { title: capability.title } : {}),\n ...(capability.description ? { description: capability.description } : {}),\n inputSchema: capability.input ?? {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n ...(capability.output\n ? { outputSchema: mcpOutputSchema(capability.output) }\n : {}),\n annotations: {\n readOnlyHint: capability.effect === \"read\",\n destructiveHint: capability.effect === \"destructive\",\n },\n call(input: unknown, options?: { readonly signal?: AbortSignal }) {\n return runtime.call({\n id: capability.id,\n input,\n presentation: true,\n ...(options?.signal ? { signal: options.signal } : {}),\n });\n },\n });\n });\n const names = new Set<string>();\n for (const tool of tools) {\n if (names.has(tool.name)) {\n throw new Error(`Duplicate MCP tool name \"${tool.name}\"`);\n }\n names.add(tool.name);\n }\n return tools;\n}\n\nfunction mcpOutputSchema(schema: JsonSchema): JsonSchema {\n if (schema.type === \"object\") return schema;\n return {\n type: \"object\",\n properties: { value: schema },\n required: [\"value\"],\n additionalProperties: false,\n };\n}\n\nfunction flatten(nodes: readonly ManifestNode[]): readonly ManifestCapability[] {\n return nodes.flatMap((node) =>\n node.type === \"capability\" ? [node] : flatten(node.children)\n );\n}\n","import {\n renderPresentationMarkdown,\n type PresentationPart,\n} from \"@capable/core\";\nimport type { CallToolResult } from \"@modelcontextprotocol/server\";\n\nexport function toMcpContent(\n presentation: readonly PresentationPart[] | undefined,\n output: unknown,\n): CallToolResult[\"content\"] {\n if (!presentation?.length) {\n return [{ type: \"text\", text: stringify(output) }];\n }\n const content: CallToolResult[\"content\"] = [];\n for (const part of presentation) {\n if (part.type === \"markdown\") {\n content.push({ type: \"text\", text: renderPresentationMarkdown(part) });\n continue;\n }\n if (part.type === \"table\") {\n content.push({\n type: \"text\",\n text: renderPresentationMarkdown(part),\n });\n continue;\n }\n if (part.type === \"image\") {\n content.push(\n { type: \"text\", text: `[Image: ${part.alt}]` },\n {\n type: \"image\",\n data: part.base64,\n mimeType: part.mimeType,\n },\n );\n continue;\n }\n content.push({\n type: \"resource_link\",\n uri: part.url,\n name: part.name,\n ...(part.description ? { description: part.description } : {}),\n ...(part.mimeType ? { mimeType: part.mimeType } : {}),\n ...(part.size === undefined ? {} : { size: part.size }),\n });\n }\n return content;\n}\n\nfunction stringify(value: unknown): string {\n return typeof value === \"string\"\n ? value\n : JSON.stringify(value) ?? String(value);\n}\n","import type { ServerMount } from \"@capable/server\";\nimport { createApp, TransportError } from \"@capable/app\";\nimport {\n createMcpHandler,\n Server,\n type CallToolResult,\n type Tool,\n} from \"@modelcontextprotocol/server\";\nimport { createMcp, type McpTool } from \"./index.ts\";\nimport { toMcpContent } from \"./presentation.ts\";\n\nexport function mcp<TContext = any>(\n options: {\n readonly path?: string;\n readonly name?: string;\n readonly version?: string;\n } = {},\n): ServerMount<TContext> {\n const path = normalizePath(options.path ?? \"/mcp\");\n return {\n kind: \"capable.server.mount\",\n compile(app, context) {\n const handler = createMcpHandler(async ({ requestInfo }) => {\n if (!requestInfo) {\n throw new Error(\"The MCP HTTP handler requires request information\");\n }\n const executable = createApp(\n app,\n context\n ? { context: () => context({ request: requestInfo }) }\n : undefined as never,\n );\n const tools = await createMcp(executable);\n return createMcpServer(tools, {\n name: options.name ?? app.name ?? \"capable\",\n version: options.version ?? app.version ?? \"0.0.0\",\n });\n }, {\n legacy: \"stateless\",\n });\n return {\n name: \"mcp\",\n async fetch(request) {\n if (new URL(request.url).pathname !== path) return undefined;\n return handler.fetch(request);\n },\n };\n },\n };\n}\n\nfunction createMcpServer(\n tools: readonly McpTool[],\n info: { readonly name: string; readonly version: string },\n): Server {\n const server = new Server(info, {\n capabilities: { tools: {} },\n });\n server.setRequestHandler(\"tools/list\", () => ({\n tools: tools.map(toProtocolTool),\n }));\n server.setRequestHandler(\"tools/call\", async (request, context) => {\n const tool = tools.find(({ name }) => name === request.params.name);\n if (!tool) {\n return toolError(`Unknown tool \"${request.params.name}\"`);\n }\n try {\n const result = await tool.call(request.params.arguments ?? {}, {\n signal: context.mcpReq.signal,\n });\n return {\n content: toMcpContent(result.presentation, result.output),\n structuredContent: isRecord(result.output)\n ? result.output\n : { value: result.output },\n } satisfies CallToolResult;\n } catch (error) {\n if (!(error instanceof TransportError)) throw error;\n return toolError(error.message, {\n code: error.code,\n status: error.status,\n data: error.data,\n });\n }\n });\n return server;\n}\n\nfunction toProtocolTool(tool: McpTool): Tool {\n return {\n name: tool.name,\n ...(tool.title ? { title: tool.title } : {}),\n ...(tool.description ? { description: tool.description } : {}),\n inputSchema: tool.inputSchema as Tool[\"inputSchema\"],\n ...(tool.outputSchema\n ? { outputSchema: tool.outputSchema as Tool[\"outputSchema\"] }\n : {}),\n annotations: tool.annotations,\n };\n}\n\nfunction toolError(\n message: string,\n details?: Record<string, unknown>,\n): CallToolResult {\n return {\n isError: true,\n content: [{\n type: \"text\",\n text: details ? JSON.stringify({ message, ...details }) : message,\n }],\n };\n}\n\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n"],"mappings":";;;;AAsCA,eAAsB,UACpB,KAC6B;CAC7B,MAAM,UAAU,cAAc,GAAG;CAEjC,MAAM,QAAQ,SAAQ,MADC,QAAQ,SAAS,EAAA,CACT,YAAY,CAAC,CACzC,QAAQ,eAAe,WAAW,KAAK,QAAQ,KAAK,CAAC,CACrD,KAAK,eAAe;EACnB,MAAM,OA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AAC;EAC5D,aAAa,KAAK;EAClB,GAAI,KAAK,eACL,EAAE,cAAc,KAAK,aAAqC,IAC1D,CAAC;EACL,aAAa,KAAK;CACpB;AACF;AAEA,SAAS,UACP,SACA,SACgB;CAChB,OAAO;EACL,SAAS;EACT,SAAS,CAAC;GACR,MAAM;GACN,MAAM,UAAU,KAAK,UAAU;IAAE;IAAS,GAAG;GAAQ,CAAC,IAAI;EAC5D,CAAC;CACH;AACF;AAEA,SAAS,cAAc,OAAuB;CAC5C,OAAO,IAAI,MAAM,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;AACtD;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,QAAQ,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,CAAC;AAC5E"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"src-BF70JLxI.mjs","names":["normalizePath"],"sources":["../../fetch/src/error-response.ts","../../fetch/src/capable.ts","../../fetch/src/http.ts"],"sourcesContent":["import { CapableError } from \"@capable/core\";\nimport { TransportError } from \"@capable/app\";\n\nexport type CapabilityErrorData = {\n readonly code: string;\n readonly message: string;\n readonly status: number;\n readonly data?: unknown;\n};\n\nexport function capabilityErrorData(\n error: unknown,\n fallbackStatus = 500,\n): CapabilityErrorData {\n const capable = error instanceof CapableError || error instanceof TransportError\n ? error\n : new CapableError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n return {\n code: capable.code,\n message: capable.message,\n status: capable.status ?? fallbackStatus,\n ...(capable.data === undefined ? {} : { data: capable.data }),\n };\n}\n\nexport function capabilityErrorResponse(\n error: unknown,\n fallbackStatus = 500,\n): Response {\n const data = capabilityErrorData(error, fallbackStatus);\n return Response.json({\n ok: false,\n error: data,\n }, { status: data.status });\n}\n","import {\n getAppRuntime,\n isApp,\n TransportError,\n type ApplicationManifest,\n type ApplicationTransport,\n type AnyApp,\n type CapabilityCall,\n type CapabilityResult,\n} from \"@capable/app\";\nimport type { PresentationPart } from \"@capable/core\";\nimport {\n capabilityErrorData,\n capabilityErrorResponse,\n} from \"./error-response.ts\";\n\nexport type FetchHandler = (request: Request) => Response | Promise<Response>;\n\nexport function createProtocolHandler(\n application:\n | AnyApp\n | ((request: Request) => AnyApp | Promise<AnyApp>),\n options: {\n readonly basePath?: string;\n } = {},\n): {\n readonly fetch: FetchHandler;\n} {\n const basePath = normalizePath(options.basePath ?? \"/_capable\");\n\n const fetch: FetchHandler = async (request) => {\n const url = new URL(request.url);\n const app = isApp(application)\n ? application\n : await application(request);\n const runtime = getAppRuntime(app);\n if (url.pathname === `${basePath}/manifest` && request.method === \"GET\") {\n return Response.json(await runtime.manifest());\n }\n const subscribePrefix = `${basePath}/subscribe/`;\n if (\n url.pathname.startsWith(subscribePrefix) &&\n request.method === \"POST\"\n ) {\n const id = decodeURIComponent(\n url.pathname.slice(subscribePrefix.length),\n );\n const controller = new AbortController();\n let stream: AsyncIterableIterator<CapabilityResult> | undefined;\n try {\n const body = await request.json() as {\n readonly input?: unknown;\n readonly presentation?: boolean;\n };\n stream = runtime.subscribe({\n id,\n input: body.input ?? {},\n ...(body.presentation ? { presentation: true } : {}),\n signal: AbortSignal.any([request.signal, controller.signal]),\n });\n const first = await stream.next();\n return subscriptionResponse(stream, first, controller);\n } catch (error) {\n controller.abort();\n await stream?.return?.().catch(() => undefined);\n return capabilityErrorResponse(error);\n }\n }\n const callPrefix = `${basePath}/call/`;\n if (!url.pathname.startsWith(callPrefix) || request.method !== \"POST\") {\n return new Response(\"Not Found\", { status: 404 });\n }\n const id = decodeURIComponent(url.pathname.slice(callPrefix.length));\n try {\n const body = await request.json() as {\n readonly input?: unknown;\n readonly presentation?: boolean;\n };\n const result = await runtime.call({\n id,\n input: body.input ?? {},\n ...(body.presentation ? { presentation: true } : {}),\n signal: request.signal,\n });\n return Response.json({\n ok: true,\n ...result,\n });\n } catch (error) {\n return capabilityErrorResponse(error);\n }\n };\n\n return { fetch };\n}\n\nexport type TransportHeaders =\n | HeadersInit\n | (() => HeadersInit | Promise<HeadersInit>);\n\nexport function createHttpTransport(options: {\n readonly url: string | URL | (() => string | URL);\n readonly fetch?: (request: Request) => Response | Promise<Response>;\n readonly headers?: TransportHeaders;\n}): ApplicationTransport {\n const fetchImplementation = options.fetch ?? globalThis.fetch;\n\n async function request(\n path: string,\n init: RequestInit,\n ): Promise<Response> {\n const base = normalizeUrl(\n typeof options.url === \"function\" ? options.url() : options.url,\n );\n const configured = typeof options.headers === \"function\"\n ? await options.headers()\n : options.headers;\n const headers = new Headers(configured);\n new Headers(init.headers).forEach((value, name) => headers.set(name, value));\n return fetchImplementation(\n new Request(new URL(path, base), { ...init, headers }),\n );\n }\n\n return Object.freeze({\n async manifest(\n { signal }: { readonly signal?: AbortSignal } = {},\n ) {\n const response = await request(\"manifest\", {\n method: \"GET\",\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) throw await responseError(response);\n return await responseJson<ApplicationManifest>(\n response,\n \"Application manifest\",\n );\n },\n async call({\n id,\n input = {},\n signal,\n presentation,\n }: CapabilityCall) {\n const response = await request(`call/${encodeURIComponent(id)}`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ input, ...(presentation ? { presentation } : {}) }),\n ...(signal ? { signal } : {}),\n });\n const body = await response.json() as\n | {\n readonly ok: true;\n readonly output: unknown;\n readonly presentation?: readonly PresentationPart[];\n }\n | {\n readonly ok: false;\n readonly error: {\n readonly code: string;\n readonly message?: string;\n readonly status?: number;\n readonly data?: unknown;\n };\n };\n if (!body.ok) {\n throw new TransportError(body.error.code, body.error);\n }\n return {\n output: body.output,\n ...(body.presentation ? { presentation: body.presentation } : {}),\n };\n },\n async *subscribe({\n id,\n input = {},\n signal,\n presentation,\n }: CapabilityCall) {\n const response = await request(`subscribe/${encodeURIComponent(id)}`, {\n method: \"POST\",\n headers: {\n accept: \"text/event-stream\",\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({ input, ...(presentation ? { presentation } : {}) }),\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) throw await responseError(response);\n yield* decodeEventStream(response);\n },\n });\n}\n\nfunction subscriptionResponse(\n stream: AsyncIterableIterator<CapabilityResult>,\n first: IteratorResult<CapabilityResult>,\n subscriptionController: AbortController,\n): Response {\n const encoder = new TextEncoder();\n let initial: IteratorResult<CapabilityResult> | undefined = first;\n\n return new Response(new ReadableStream({\n async pull(controller) {\n try {\n const result = initial ?? await stream.next();\n initial = undefined;\n if (result.done) {\n subscriptionController.abort();\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(sseFrame(\"output\", result.value)));\n } catch (error) {\n subscriptionController.abort();\n controller.enqueue(encoder.encode(\n sseFrame(\"error\", capabilityErrorData(error)),\n ));\n controller.close();\n await stream.return?.();\n }\n },\n async cancel() {\n subscriptionController.abort();\n await stream.return?.();\n },\n }, {\n highWaterMark: 0,\n }), {\n headers: {\n \"cache-control\": \"no-cache\",\n \"content-type\": \"text/event-stream; charset=utf-8\",\n },\n });\n}\n\nasync function* decodeEventStream(\n response: Response,\n): AsyncIterableIterator<CapabilityResult> {\n if (!response.headers.get(\"content-type\")?.includes(\"text/event-stream\")) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: \"Subscription response is not an event stream\",\n });\n }\n if (!response.body) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: \"Subscription response has no body\",\n });\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n try {\n while (true) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value, { stream: !done });\n let boundary = eventBoundary(buffer);\n while (boundary) {\n const block = buffer.slice(0, boundary.index);\n buffer = buffer.slice(boundary.index + boundary.length);\n const event = parseEventBlock(block);\n if (event) {\n if (event.type === \"error\") {\n throw new TransportError(event.error.code, event.error);\n }\n yield event.result;\n }\n boundary = eventBoundary(buffer);\n }\n if (done) break;\n }\n } finally {\n await reader.cancel().catch(() => undefined);\n }\n}\n\nfunction eventBoundary(\n value: string,\n): { readonly index: number; readonly length: number } | undefined {\n const lf = value.indexOf(\"\\n\\n\");\n const crlf = value.indexOf(\"\\r\\n\\r\\n\");\n if (lf < 0 && crlf < 0) {\n return undefined;\n }\n if (crlf >= 0 && (lf < 0 || crlf < lf)) {\n return { index: crlf, length: 4 };\n }\n return { index: lf, length: 2 };\n}\n\nfunction parseEventBlock(block: string):\n | { readonly type: \"output\"; readonly result: CapabilityResult }\n | {\n readonly type: \"error\";\n readonly error: {\n readonly code: string;\n readonly message?: string;\n readonly status?: number;\n readonly data?: unknown;\n };\n }\n | undefined {\n let type = \"message\";\n const data: string[] = [];\n for (const line of block.replace(/\\r\\n/g, \"\\n\").split(\"\\n\")) {\n if (line.startsWith(\":\")) continue;\n if (line.startsWith(\"event:\")) type = line.slice(6).trim();\n if (line.startsWith(\"data:\")) data.push(line.slice(5).trimStart());\n }\n if (!data.length) return undefined;\n const value = JSON.parse(data.join(\"\\n\")) as any;\n return type === \"error\"\n ? { type: \"error\", error: value }\n : { type: \"output\", result: value };\n}\n\nfunction sseFrame(event: string, data: unknown): string {\n return `event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`;\n}\n\nfunction normalizeUrl(value: string | URL): URL {\n const url = new URL(value);\n if (!url.pathname.endsWith(\"/\")) url.pathname += \"/\";\n url.search = \"\";\n url.hash = \"\";\n return url;\n}\n\nasync function responseError(response: Response): Promise<TransportError> {\n const text = await response.text().catch(() => \"\");\n let data: unknown = text;\n try {\n data = JSON.parse(text);\n } catch {\n // Preserve the response text as transport diagnostics.\n }\n if (\n data &&\n typeof data === \"object\" &&\n \"ok\" in data &&\n data.ok === false &&\n \"error\" in data &&\n data.error &&\n typeof data.error === \"object\" &&\n \"code\" in data.error &&\n typeof data.error.code === \"string\"\n ) {\n const error = data.error as {\n readonly code: string;\n readonly message?: unknown;\n readonly status?: unknown;\n readonly data?: unknown;\n };\n return new TransportError(error.code, {\n ...(typeof error.message === \"string\"\n ? { message: error.message }\n : {}),\n status: typeof error.status === \"number\"\n ? error.status\n : response.status,\n ...(\"data\" in error ? { data: error.data } : {}),\n });\n }\n return new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: `Transport request failed with ${response.status}`,\n data,\n });\n}\n\nasync function responseJson<T>(\n response: Response,\n label: string,\n): Promise<T> {\n const contentType = response.headers.get(\"content-type\");\n if (!contentType?.toLowerCase().includes(\"json\")) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message:\n `${label} request returned ${contentType ?? \"a non-JSON response\"}${\n response.url ? ` from ${response.url}` : \"\"\n }`,\n });\n }\n try {\n return await response.json() as T;\n } catch (cause) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: `${label} response contained invalid JSON`,\n cause,\n });\n }\n}\n\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n","import {\n executeLocatedCapability,\n normalizePresentation,\n renderPresentationMarkdown,\n schemaToJsonSchema,\n type AppDefinition,\n type GroupMetaRegistry,\n type LocatedCapability,\n type CapabilityMetaRegistry,\n type CapabilityTree,\n} from \"@capable/core\";\nimport {\n type ApplicationSelection,\n type JsonSchema,\n} from \"@capable/app\";\nimport {\n capabilityErrorResponse,\n} from \"./error-response.ts\";\nimport type { FetchHandler } from \"./capable.ts\";\n\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\nexport type HttpCapabilityMeta =\n | false\n | {\n readonly method?: HttpMethod;\n readonly route?: string;\n readonly status?: number;\n };\n\nexport type HttpGroupMeta = {\n readonly prefix?: string;\n};\n\ndeclare module \"@capable/core\" {\n interface CapabilityMetaRegistry {\n readonly http?: HttpCapabilityMeta;\n }\n\n interface GroupMetaRegistry {\n readonly http?: HttpGroupMeta;\n }\n}\n\nexport type ContextProvider<TContext> = (args: {\n readonly request: Request;\n}) => TContext | Promise<TContext>;\n\nexport type CapabilitySelection<\n TTree extends CapabilityTree = CapabilityTree,\n> = ApplicationSelection<TTree>;\n\nexport type CompiledHttpRoute = {\n readonly method: HttpMethod;\n readonly path: string;\n readonly capability: LocatedCapability;\n};\n\nexport function createHttpHandler<\n const TCapabilities extends CapabilityTree,\n TContext,\n>(\n app: AppDefinition<TCapabilities, TContext>,\n options: {\n readonly context?: ContextProvider<TContext>;\n readonly basePath?: string;\n readonly openapiPath?: string | false;\n readonly requireExplicitRoutes?: boolean;\n readonly selection?: CapabilitySelection<TCapabilities>;\n } = {},\n): {\n readonly fetch: FetchHandler;\n readonly routes: readonly CompiledHttpRoute[];\n readonly openapi: Readonly<Record<string, unknown>>;\n} {\n const basePath = normalizePath(options.basePath ?? \"/api\");\n const selected = selectCapabilities(app.locatedCapabilities, options.selection)\n .filter((entry) => capabilityHttp(entry) !== false);\n const routes = selected.map((entry) => compileHttpRoute(entry, basePath));\n assertUniqueRoutes(routes);\n if (options.requireExplicitRoutes) {\n const implicit = selected.find((entry) => {\n const meta = capabilityHttp(entry);\n return !meta || !meta.method || !meta.route;\n });\n if (implicit) {\n throw new Error(\n `Capability \"${implicit.capability.id}\" requires an explicit HTTP method and route`,\n );\n }\n }\n const openapi = createOpenApi(app, routes);\n const openapiPath = options.openapiPath === false\n ? undefined\n : normalizePath(options.openapiPath ?? \"/openapi.json\");\n\n return {\n routes,\n openapi,\n async fetch(request) {\n const url = new URL(request.url);\n if (\n openapiPath &&\n url.pathname === openapiPath &&\n request.method === \"GET\"\n ) {\n return Response.json(openapi);\n }\n const match = routes\n .map((route) => ({ route, params: matchPath(route.path, url.pathname) }))\n .find(({ route, params }) => route.method === request.method && params);\n if (!match?.params) return new Response(\"Not Found\", { status: 404 });\n\n try {\n const input = await readHttpInput(\n request,\n match.params,\n match.route.capability.capability.input,\n );\n const context = options.context\n ? await options.context({ request })\n : undefined as TContext;\n const output = await executeLocatedCapability(match.route.capability, input, {\n context,\n signal: request.signal,\n });\n if (\n request.headers.get(\"accept\")?.includes(\"text/markdown\") &&\n match.route.capability.capability.toPresentation\n ) {\n const presentation = normalizePresentation(\n await match.route.capability.capability.toPresentation(output, {\n context,\n }),\n );\n if (presentation.length > 0) {\n return new Response(\n renderPresentationMarkdown(presentation),\n {\n status: httpSuccessStatus(match.route.capability),\n headers: { \"content-type\": \"text/markdown; charset=utf-8\" },\n },\n );\n }\n }\n return Response.json(output, {\n status: httpSuccessStatus(match.route.capability),\n });\n } catch (error) {\n return capabilityErrorResponse(error);\n }\n },\n };\n}\n\nfunction compileHttpRoute(\n entry: LocatedCapability,\n basePath: string,\n): CompiledHttpRoute {\n const meta = capabilityHttp(entry);\n const defaultPath = entry.path.flatMap((segment, index) => {\n const groupIndex = entry.groupPaths.findIndex(\n (path) => path.length === index + 1,\n );\n const prefix = groupIndex >= 0\n ? (entry.groups[groupIndex]?.meta.http as HttpGroupMeta | undefined)\n ?.prefix\n : undefined;\n return prefix ? prefix.split(\"/\").filter(Boolean) : [segment];\n }).join(\"/\");\n const groupPrefix = entry.groups.flatMap((group) => {\n const prefix = (group.meta.http as HttpGroupMeta | undefined)?.prefix;\n return prefix ? prefix.split(\"/\").filter(Boolean) : [];\n }).join(\"/\");\n const authoredRoute = meta && meta.route ? meta.route : defaultPath;\n assertPathParameters(entry, authoredRoute);\n return Object.freeze({\n method: meta && meta.method\n ? meta.method\n : entry.capability.effect === \"read\"\n ? \"GET\"\n : \"POST\",\n path: joinPath(\n basePath,\n meta && meta.route ? groupPrefix : \"\",\n authoredRoute,\n ),\n capability: entry,\n });\n}\n\nfunction capabilityHttp(entry: LocatedCapability): HttpCapabilityMeta | undefined {\n return entry.capability.meta.http as HttpCapabilityMeta | undefined;\n}\n\nfunction httpSuccessStatus(entry: LocatedCapability): number {\n const meta = capabilityHttp(entry);\n return meta && typeof meta.status === \"number\" ? meta.status : 200;\n}\n\nasync function readHttpInput(\n request: Request,\n params: Record<string, string>,\n schema: LocatedCapability[\"capability\"][\"input\"],\n): Promise<Record<string, unknown>> {\n const url = new URL(request.url);\n const jsonSchema = schema\n ? schemaToJsonSchema(schema, \"input\")\n : undefined;\n const properties = jsonSchema?.properties as\n | Record<string, Readonly<Record<string, unknown>>>\n | undefined;\n const coerceEntries = (entries: Iterable<readonly [string, string]>) =>\n Object.fromEntries(\n [...entries].map(([key, value]) => [\n key,\n coerceHttpValue(value, properties?.[key]),\n ]),\n );\n const rest: Record<string, unknown> =\n request.method === \"GET\"\n ? coerceEntries(url.searchParams)\n : request.headers.get(\"content-type\")?.includes(\"application/json\")\n ? await request.json() as Record<string, unknown>\n : {};\n return {\n ...rest,\n ...coerceEntries(Object.entries(params)),\n };\n}\n\nfunction coerceHttpValue(\n value: string,\n schema: Readonly<Record<string, unknown>> | undefined,\n): unknown {\n if (schema?.type === \"boolean\") return value === \"true\"\n ? true\n : value === \"false\"\n ? false\n : value;\n if (schema?.type === \"integer\" || schema?.type === \"number\") {\n const number = Number(value);\n return Number.isFinite(number) ? number : value;\n }\n return value;\n}\n\nfunction assertPathParameters(\n entry: LocatedCapability,\n path: string,\n): void {\n const parameters = [...path.matchAll(/:([^/]+)/g)].map((match) => match[1]!);\n if (parameters.length === 0) return;\n const schema = entry.capability.input\n ? schemaToJsonSchema(entry.capability.input, \"input\")\n : undefined;\n const properties = schema?.properties as\n | Record<string, unknown>\n | undefined;\n for (const parameter of parameters) {\n if (!properties?.[parameter]) {\n throw new Error(\n `HTTP path parameter \":${parameter}\" is not present in Capability \"${entry.capability.id}\" input`,\n );\n }\n }\n}\n\nfunction matchPath(\n pattern: string,\n pathname: string,\n): Record<string, string> | undefined {\n const expected = pattern.split(\"/\").filter(Boolean);\n const actual = pathname.split(\"/\").filter(Boolean);\n if (expected.length !== actual.length) return undefined;\n const params: Record<string, string> = {};\n for (let index = 0; index < expected.length; index++) {\n const token = expected[index]!;\n const value = actual[index]!;\n if (token.startsWith(\":\")) params[token.slice(1)] = decodeURIComponent(value);\n else if (token !== value) return undefined;\n }\n return params;\n}\n\nfunction createOpenApi(\n app: AppDefinition<any, any>,\n routes: readonly CompiledHttpRoute[],\n): Readonly<Record<string, unknown>> {\n const paths: Record<string, unknown> = {};\n for (const route of routes) {\n const method = route.method.toLowerCase();\n const path = route.path.replace(/:([^/]+)/g, \"{$1}\");\n const capability = route.capability.capability;\n const input = capability.input\n ? schemaToJsonSchema(capability.input, \"input\")\n : undefined;\n const properties = (input?.properties ?? {}) as Record<string, JsonSchema>;\n const required = new Set((input?.required ?? []) as readonly string[]);\n const pathNames = new Set(\n [...route.path.matchAll(/:([^/]+)/g)].map((match) => match[1]!),\n );\n const parameters = [...pathNames].map((name) => ({\n name,\n in: \"path\",\n required: true,\n schema: properties[name] ?? {},\n }));\n const remaining = Object.fromEntries(\n Object.entries(properties).filter(([name]) => !pathNames.has(name)),\n );\n if (route.method === \"GET\") {\n parameters.push(\n ...Object.entries(remaining).map(([name, schema]) => ({\n name,\n in: \"query\",\n required: required.has(name),\n schema,\n })),\n );\n }\n const responses: Record<string, unknown> = {\n [String(httpSuccessStatus(route.capability))]: {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: capability.output\n ? schemaToJsonSchema(capability.output, \"output\")\n : {},\n },\n },\n },\n };\n for (const [code, error] of Object.entries(route.capability.errors)) {\n const status = typeof error.status === \"number\"\n ? String(error.status)\n : \"default\";\n responses[status] ??= {\n description: error.message ?? code,\n };\n }\n const current = paths[path] as Record<string, unknown> | undefined ?? {};\n current[method] = {\n capabilityId: capability.id,\n ...(capability.title ? { summary: capability.title } : {}),\n ...(capability.description ? { description: capability.description } : {}),\n ...(parameters.length ? { parameters } : {}),\n ...(route.method !== \"GET\" && Object.keys(remaining).length\n ? {\n requestBody: {\n required: [...required].some((name) => !pathNames.has(name)),\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: remaining,\n required: [...required].filter((name) =>\n !pathNames.has(name)\n ),\n },\n },\n },\n },\n }\n : {}),\n responses,\n };\n paths[path] = current;\n }\n return {\n openapi: \"3.1.0\",\n info: { title: app.name, version: app.version },\n paths,\n };\n}\n\nfunction selectCapabilities(\n capabilities: readonly LocatedCapability[],\n selection: CapabilitySelection | undefined,\n): readonly LocatedCapability[] {\n return capabilities.filter((entry) => {\n const included = selection?.include\n ? matchesTree(selection.include, entry.path)\n : true;\n return included && !matchesTree(selection?.exclude, entry.path);\n });\n}\n\nfunction matchesTree(\n tree: Readonly<Record<string, unknown>> | undefined,\n path: readonly string[],\n): boolean {\n if (!tree) return false;\n let current: unknown = tree;\n for (const segment of path) {\n if (current === true) return true;\n if (!current || typeof current !== \"object\" || Array.isArray(current)) {\n return false;\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return current === true || (\n Boolean(current) && typeof current === \"object\" && !Array.isArray(current)\n );\n}\n\nfunction assertUniqueRoutes(routes: readonly CompiledHttpRoute[]): void {\n const seen = new Set<string>();\n for (const route of routes) {\n const identity = `${route.method} ${route.path}`;\n if (seen.has(identity)) throw new Error(`Duplicate HTTP route ${identity}`);\n seen.add(identity);\n }\n}\n\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n\nfunction joinPath(...parts: readonly string[]): string {\n return normalizePath(parts.join(\"/\"));\n}\n"],"mappings":";;;AAUA,SAAgB,oBACd,OACA,iBAAiB,KACI;CACrB,MAAM,UAAU,iBAAiB,gBAAgB,iBAAiB,iBAC9D,QACA,IAAI,aAAa,yBAAyB,EAAE,OAAO,MAAM,CAAC;CAC9D,OAAO;EACL,MAAM,QAAQ;EACd,SAAS,QAAQ;EACjB,QAAQ,QAAQ,UAAU;EAC1B,GAAI,QAAQ,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,QAAQ,KAAK;CAC7D;AACF;AAEA,SAAgB,wBACd,OACA,iBAAiB,KACP;CACV,MAAM,OAAO,oBAAoB,OAAO,cAAc;CACtD,OAAO,SAAS,KAAK;EACnB,IAAI;EACJ,OAAO;CACT,GAAG,EAAE,QAAQ,KAAK,OAAO,CAAC;AAC5B;;;AChBA,SAAgB,sBACd,aAGA,U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OAAO,aAAa,QAAQ,UAAU;EAIpC,QAHiB,WAAW,UACxB,YAAY,UAAU,SAAS,MAAM,IAAI,IACzC,SACe,CAAC,YAAY,WAAW,SAAS,MAAM,IAAI;CAChE,CAAC;AACH;AAEA,SAAS,YACP,MACA,MACS;CACT,IAAI,CAAC,MAAM,OAAO;CAClB,IAAI,UAAmB;CACvB,KAAK,MAAM,WAAW,MAAM;EAC1B,IAAI,YAAY,MAAM,OAAO;EAC7B,IAAI,CAAC,WAAW,OAAO,YAAY,YAAY,MAAM,QAAQ,OAAO,GAClE,OAAO;EAET,UAAW,QAAoC;CACjD;CACA,OAAO,YAAY,QACjB,QAAQ,OAAO,KAAK,OAAO,YAAY,YAAY,CAAC,MAAM,QAAQ,OAAO;AAE7E;AAEA,SAAS,mBAAmB,QAA4C;CACtE,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,GAAG,MAAM,OAAO,GAAG,MAAM;EAC1C,IAAI,KAAK,IAAI,QAAQ,GAAG,MAAM,IAAI,MAAM,wBAAwB,UAAU;EAC1E,KAAK,IAAI,QAAQ;CACnB;AACF;AAEA,SAAS,cAAc,OAAuB;CAC5C,OAAO,IAAI,MAAM,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;AACtD;AAEA,SAAS,SAAS,GAAG,OAAkC;CACrD,OAAO,cAAc,MAAM,KAAK,GAAG,CAAC;AACtC"}
|
package/dist/src-C2MGIlT0.mjs
DELETED
|
@@ -1,464 +0,0 @@
|
|
|
1
|
-
import { _ as normalizePresentation, a as isCapabilityGroup, f as subscribeLocatedCapability, h as schemaToJsonSchema, l as executeLocatedCapability, u as isCapability, x as CapableError } from "./src-DdV82An-.mjs";
|
|
2
|
-
//#region packages/app/src/manifest.ts
|
|
3
|
-
function createAppManifest(definition) {
|
|
4
|
-
const byCapability = new Map(definition.locatedCapabilities.map((entry) => [entry.capability, entry]));
|
|
5
|
-
return Object.freeze({
|
|
6
|
-
protocol: "capable.capabilities.v2",
|
|
7
|
-
name: definition.name,
|
|
8
|
-
version: definition.version,
|
|
9
|
-
...definition.description ? { description: definition.description } : {},
|
|
10
|
-
capabilities: manifestNodes(definition.capabilities, byCapability)
|
|
11
|
-
});
|
|
12
|
-
}
|
|
13
|
-
function validateManifest(manifest, label) {
|
|
14
|
-
if (manifest.protocol !== "capable.capabilities.v2") throw new Error(`${label} uses unsupported protocol "${manifest.protocol}"`);
|
|
15
|
-
const capabilities = flattenManifestCapabilities(manifest.capabilities);
|
|
16
|
-
const ids = /* @__PURE__ */ new Set();
|
|
17
|
-
const paths = /* @__PURE__ */ new Set();
|
|
18
|
-
for (const capability of capabilities) {
|
|
19
|
-
const path = capability.path.join(".");
|
|
20
|
-
if (ids.has(capability.id)) throw new Error(`${label} contains duplicate Capability id "${capability.id}"`);
|
|
21
|
-
if (paths.has(path)) throw new Error(`${label} contains duplicate Capability path "${path}"`);
|
|
22
|
-
ids.add(capability.id);
|
|
23
|
-
paths.add(path);
|
|
24
|
-
}
|
|
25
|
-
validateManifestPaths(manifest.capabilities, [], label);
|
|
26
|
-
}
|
|
27
|
-
function mergeApplicationManifests(manifests) {
|
|
28
|
-
const conflicts = collectManifestConflicts(manifests);
|
|
29
|
-
if (conflicts.length) throw new Error(`Cannot merge Apps:\n${conflicts.map((item) => `- ${item}`).join("\n")}`);
|
|
30
|
-
return Object.freeze({
|
|
31
|
-
protocol: "capable.capabilities.v2",
|
|
32
|
-
name: manifests.map(({ name }) => name).join(" + "),
|
|
33
|
-
version: manifests.map(({ version }) => version).join(" + "),
|
|
34
|
-
capabilities: mergeManifestNodes(manifests.flatMap(({ capabilities }) => capabilities))
|
|
35
|
-
});
|
|
36
|
-
}
|
|
37
|
-
function selectManifest(source, selection) {
|
|
38
|
-
return Object.freeze({
|
|
39
|
-
...source,
|
|
40
|
-
capabilities: filterManifestNodes(source.capabilities, selection)
|
|
41
|
-
});
|
|
42
|
-
}
|
|
43
|
-
function flattenManifestCapabilities(nodes) {
|
|
44
|
-
return nodes.flatMap((node) => node.type === "capability" ? [node] : flattenManifestCapabilities(node.children));
|
|
45
|
-
}
|
|
46
|
-
function findManifestCapability(nodes, path) {
|
|
47
|
-
let current = nodes;
|
|
48
|
-
for (let index = 0; index < path.length; index++) {
|
|
49
|
-
const key = path[index];
|
|
50
|
-
const node = current.find((candidate) => candidate.type === "group" ? candidate.key === key : candidate.path.at(-1) === key);
|
|
51
|
-
if (!node) return void 0;
|
|
52
|
-
if (node.type === "capability") return index === path.length - 1 ? node : void 0;
|
|
53
|
-
current = node.children;
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
function manifestNodes(tree, located) {
|
|
57
|
-
const nodes = [];
|
|
58
|
-
for (const [key, value] of Object.entries(tree)) {
|
|
59
|
-
if (isCapability(value)) {
|
|
60
|
-
const entry = located.get(value);
|
|
61
|
-
if (entry) nodes.push(manifestCapability(entry));
|
|
62
|
-
continue;
|
|
63
|
-
}
|
|
64
|
-
const decorated = isCapabilityGroup(value);
|
|
65
|
-
const children = manifestNodes(decorated ? value.capabilities : value, located);
|
|
66
|
-
nodes.push(Object.freeze({
|
|
67
|
-
type: "group",
|
|
68
|
-
key,
|
|
69
|
-
...decorated && value.title ? { title: value.title } : {},
|
|
70
|
-
...decorated && value.description ? { description: value.description } : {},
|
|
71
|
-
meta: decorated ? value.meta : {},
|
|
72
|
-
children
|
|
73
|
-
}));
|
|
74
|
-
}
|
|
75
|
-
return nodes;
|
|
76
|
-
}
|
|
77
|
-
function manifestCapability(entry) {
|
|
78
|
-
const capability = entry.capability;
|
|
79
|
-
return Object.freeze({
|
|
80
|
-
type: "capability",
|
|
81
|
-
id: capability.id,
|
|
82
|
-
path: entry.path,
|
|
83
|
-
...capability.title ? { title: capability.title } : {},
|
|
84
|
-
...capability.description ? { description: capability.description } : {},
|
|
85
|
-
deprecated: capability.deprecated,
|
|
86
|
-
...capability.effect ? { effect: capability.effect } : {},
|
|
87
|
-
...capability.subscribe ? { subscription: { mode: "replace" } } : {},
|
|
88
|
-
...capability.input ? { input: schemaToJsonSchema(capability.input, "input") } : {},
|
|
89
|
-
...capability.output ? { output: schemaToJsonSchema(capability.output, "output") } : {},
|
|
90
|
-
errors: Object.fromEntries(Object.entries(entry.errors).map(([code, definition]) => [code, {
|
|
91
|
-
...definition.message ? { message: definition.message } : {},
|
|
92
|
-
...typeof definition.status === "number" ? { status: definition.status } : {},
|
|
93
|
-
...definition.data ? { data: schemaToJsonSchema(definition.data, "output") } : {},
|
|
94
|
-
...definition.meta ? { meta: definition.meta } : {}
|
|
95
|
-
}])),
|
|
96
|
-
meta: capability.meta
|
|
97
|
-
});
|
|
98
|
-
}
|
|
99
|
-
function validateManifestPaths(nodes, parent, label) {
|
|
100
|
-
for (const node of nodes) {
|
|
101
|
-
if (node.type === "group") {
|
|
102
|
-
validateManifestPaths(node.children, [...parent, node.key], label);
|
|
103
|
-
continue;
|
|
104
|
-
}
|
|
105
|
-
if (!samePath(node.path, [...parent, node.path.at(-1)])) throw new Error(`${label} Capability "${node.id}" declares path "${node.path.join(".")}" that does not match its manifest placement`);
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
function collectManifestConflicts(manifests) {
|
|
109
|
-
const conflicts = [];
|
|
110
|
-
for (const manifest of manifests) try {
|
|
111
|
-
validateManifest(manifest, manifest.name);
|
|
112
|
-
} catch (error) {
|
|
113
|
-
conflicts.push(error instanceof Error ? error.message : String(error));
|
|
114
|
-
}
|
|
115
|
-
const capabilities = manifests.flatMap((manifest, source) => flattenManifestCapabilities(manifest.capabilities).map((capability) => ({
|
|
116
|
-
capability,
|
|
117
|
-
source,
|
|
118
|
-
label: manifest.name
|
|
119
|
-
})));
|
|
120
|
-
for (let leftIndex = 0; leftIndex < capabilities.length; leftIndex++) for (let rightIndex = leftIndex + 1; rightIndex < capabilities.length; rightIndex++) {
|
|
121
|
-
const left = capabilities[leftIndex];
|
|
122
|
-
const right = capabilities[rightIndex];
|
|
123
|
-
if (left.source === right.source) continue;
|
|
124
|
-
const sameId = left.capability.id === right.capability.id;
|
|
125
|
-
if (samePath(left.capability.path, right.capability.path)) {
|
|
126
|
-
conflicts.push(sameId ? `Capability "${left.capability.id}" is mounted twice at "${left.capability.path.join(".")}" by "${left.label}" and "${right.label}"` : `Path "${left.capability.path.join(".")}" contains both "${left.capability.id}" from "${left.label}" and "${right.capability.id}" from "${right.label}"`);
|
|
127
|
-
continue;
|
|
128
|
-
}
|
|
129
|
-
if (sameId) conflicts.push(`Capability id "${left.capability.id}" appears at both "${left.capability.path.join(".")}" in "${left.label}" and "${right.capability.path.join(".")}"`);
|
|
130
|
-
if (isPathPrefix(left.capability.path, right.capability.path) || isPathPrefix(right.capability.path, left.capability.path)) {
|
|
131
|
-
const leaf = left.capability.path.length < right.capability.path.length ? left : right;
|
|
132
|
-
const subtree = leaf === left ? right : left;
|
|
133
|
-
conflicts.push(`Leaf "${leaf.capability.path.join(".")}" from "${leaf.label}" collides with subtree Capability "${subtree.capability.path.join(".")}" from "${subtree.label}"`);
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
return [...new Set(conflicts)];
|
|
137
|
-
}
|
|
138
|
-
function mergeManifestNodes(nodes) {
|
|
139
|
-
const merged = /* @__PURE__ */ new Map();
|
|
140
|
-
for (const node of nodes) {
|
|
141
|
-
const key = node.type === "group" ? node.key : node.path.at(-1);
|
|
142
|
-
const previous = merged.get(key);
|
|
143
|
-
if (!previous) {
|
|
144
|
-
merged.set(key, node);
|
|
145
|
-
continue;
|
|
146
|
-
}
|
|
147
|
-
if (previous.type !== "group" || node.type !== "group") throw new Error(`Manifest node collision at "${key}"`);
|
|
148
|
-
merged.set(key, Object.freeze({
|
|
149
|
-
type: "group",
|
|
150
|
-
key,
|
|
151
|
-
...mergeGroupField("title", previous.title, node.title, key),
|
|
152
|
-
...mergeGroupField("description", previous.description, node.description, key),
|
|
153
|
-
meta: mergeGroupMeta(previous.meta, node.meta, key),
|
|
154
|
-
children: mergeManifestNodes([...previous.children, ...node.children])
|
|
155
|
-
}));
|
|
156
|
-
}
|
|
157
|
-
return [...merged.values()];
|
|
158
|
-
}
|
|
159
|
-
function mergeGroupField(field, left, right, path) {
|
|
160
|
-
if (left && right && left !== right) throw new Error(`Group "${path}" has conflicting ${field}`);
|
|
161
|
-
const value = left ?? right;
|
|
162
|
-
return value ? { [field]: value } : {};
|
|
163
|
-
}
|
|
164
|
-
function mergeGroupMeta(left, right, path) {
|
|
165
|
-
const merged = { ...left };
|
|
166
|
-
for (const [key, value] of Object.entries(right)) {
|
|
167
|
-
if (key in merged && JSON.stringify(merged[key]) !== JSON.stringify(value)) throw new Error(`Group "${path}" has conflicting metadata for "${key}"`);
|
|
168
|
-
merged[key] = value;
|
|
169
|
-
}
|
|
170
|
-
return Object.freeze(merged);
|
|
171
|
-
}
|
|
172
|
-
function filterManifestNodes(nodes, selection) {
|
|
173
|
-
const filtered = [];
|
|
174
|
-
for (const node of nodes) {
|
|
175
|
-
if (node.type === "capability") {
|
|
176
|
-
if ((selection.include ? matchesSelection(selection.include, node.path) : true) && !matchesSelection(selection.exclude, node.path)) filtered.push(node);
|
|
177
|
-
continue;
|
|
178
|
-
}
|
|
179
|
-
const children = filterManifestNodes(node.children, selection);
|
|
180
|
-
if (children.length) filtered.push(Object.freeze({
|
|
181
|
-
...node,
|
|
182
|
-
children
|
|
183
|
-
}));
|
|
184
|
-
}
|
|
185
|
-
return filtered;
|
|
186
|
-
}
|
|
187
|
-
function matchesSelection(tree, path) {
|
|
188
|
-
let current = tree;
|
|
189
|
-
for (const segment of path) {
|
|
190
|
-
if (current === true) return true;
|
|
191
|
-
if (!current || typeof current !== "object" || Array.isArray(current)) return false;
|
|
192
|
-
current = current[segment];
|
|
193
|
-
}
|
|
194
|
-
return current === true || Boolean(current) && typeof current === "object" && !Array.isArray(current);
|
|
195
|
-
}
|
|
196
|
-
function samePath(left, right) {
|
|
197
|
-
return left.length === right.length && left.every((segment, index) => segment === right[index]);
|
|
198
|
-
}
|
|
199
|
-
function isPathPrefix(prefix, path) {
|
|
200
|
-
return prefix.length < path.length && prefix.every((segment, index) => segment === path[index]);
|
|
201
|
-
}
|
|
202
|
-
//#endregion
|
|
203
|
-
//#region packages/app/src/runtime.ts
|
|
204
|
-
const APP_RUNTIME_SYMBOL = Symbol.for("capable.app.runtime");
|
|
205
|
-
const APP_CAPABILITIES_SYMBOL = Symbol.for("capable.app.capabilities");
|
|
206
|
-
const APP_CALL_SYMBOL = Symbol.for("capable.app.call");
|
|
207
|
-
function getAppRuntime(app) {
|
|
208
|
-
return app[APP_RUNTIME_SYMBOL];
|
|
209
|
-
}
|
|
210
|
-
function isApp(value) {
|
|
211
|
-
return Boolean(value && (typeof value === "object" || typeof value === "function") && value[APP_RUNTIME_SYMBOL]);
|
|
212
|
-
}
|
|
213
|
-
function appFromRuntime(runtime) {
|
|
214
|
-
const read = (path, root, key) => {
|
|
215
|
-
if (root && key === APP_RUNTIME_SYMBOL) return runtime;
|
|
216
|
-
if (!root && key === APP_CALL_SYMBOL) return {
|
|
217
|
-
runtime,
|
|
218
|
-
path
|
|
219
|
-
};
|
|
220
|
-
if (key === "then") return void 0;
|
|
221
|
-
if (typeof key !== "string") return void 0;
|
|
222
|
-
return proxy([...path, key], false);
|
|
223
|
-
};
|
|
224
|
-
const proxy = (path, root) => {
|
|
225
|
-
if (root) return new Proxy({}, { get(_target, key) {
|
|
226
|
-
return read(path, true, key);
|
|
227
|
-
} });
|
|
228
|
-
return new Proxy(() => void 0, {
|
|
229
|
-
get(_target, key) {
|
|
230
|
-
return read(path, false, key);
|
|
231
|
-
},
|
|
232
|
-
async apply(_target, _this, args) {
|
|
233
|
-
const capability = findManifestCapability((await runtime.manifest()).capabilities, path);
|
|
234
|
-
if (!capability) throw new Error(`No Capability exists at "${path.join(".")}"`);
|
|
235
|
-
return (await runtime.call({
|
|
236
|
-
id: capability.id,
|
|
237
|
-
input: args[0] ?? {},
|
|
238
|
-
...args[1]?.signal ? { signal: args[1].signal } : {}
|
|
239
|
-
})).output;
|
|
240
|
-
}
|
|
241
|
-
});
|
|
242
|
-
};
|
|
243
|
-
return proxy([], true);
|
|
244
|
-
}
|
|
245
|
-
function subscribe(capabilityCall, ...args) {
|
|
246
|
-
const binding = capabilityCall[APP_CALL_SYMBOL];
|
|
247
|
-
if (!binding) throw new Error("subscribe() requires a Capability call from a Capable App");
|
|
248
|
-
return (async function* () {
|
|
249
|
-
const capability = findManifestCapability((await binding.runtime.manifest()).capabilities, binding.path);
|
|
250
|
-
if (!capability) throw new Error(`No Capability exists at "${binding.path.join(".")}"`);
|
|
251
|
-
if (!capability.subscription) throw new Error(`Capability "${capability.id}" is not subscribable`);
|
|
252
|
-
const stream = binding.runtime.subscribe({
|
|
253
|
-
id: capability.id,
|
|
254
|
-
input: args[0] ?? {},
|
|
255
|
-
...args[1]?.signal ? { signal: args[1].signal } : {}
|
|
256
|
-
});
|
|
257
|
-
try {
|
|
258
|
-
for await (const result of stream) yield result.output;
|
|
259
|
-
} finally {
|
|
260
|
-
await stream.return?.();
|
|
261
|
-
}
|
|
262
|
-
})();
|
|
263
|
-
}
|
|
264
|
-
const localManifestCache = /* @__PURE__ */ new WeakMap();
|
|
265
|
-
const localCapabilityCache = /* @__PURE__ */ new WeakMap();
|
|
266
|
-
function createApp(definition, ...[options]) {
|
|
267
|
-
let manifest = localManifestCache.get(definition);
|
|
268
|
-
if (!manifest) {
|
|
269
|
-
manifest = createAppManifest(definition);
|
|
270
|
-
localManifestCache.set(definition, manifest);
|
|
271
|
-
}
|
|
272
|
-
let byId = localCapabilityCache.get(definition);
|
|
273
|
-
if (!byId) {
|
|
274
|
-
byId = new Map(definition.locatedCapabilities.map((entry) => [entry.capability.id, entry]));
|
|
275
|
-
localCapabilityCache.set(definition, byId);
|
|
276
|
-
}
|
|
277
|
-
return appFromRuntime(Object.freeze({
|
|
278
|
-
async manifest() {
|
|
279
|
-
return manifest;
|
|
280
|
-
},
|
|
281
|
-
async call({ id, input = {}, signal, presentation: wantsPresentation }) {
|
|
282
|
-
const located = byId.get(id);
|
|
283
|
-
if (!located) throw new TransportError("NOT_FOUND", { status: 404 });
|
|
284
|
-
let context;
|
|
285
|
-
try {
|
|
286
|
-
context = options?.context ? await options.context({
|
|
287
|
-
id,
|
|
288
|
-
...signal ? { signal } : {}
|
|
289
|
-
}) : void 0;
|
|
290
|
-
} catch (cause) {
|
|
291
|
-
throw new TransportError("INTERNAL_SERVER_ERROR", { cause });
|
|
292
|
-
}
|
|
293
|
-
let output;
|
|
294
|
-
try {
|
|
295
|
-
output = await executeLocatedCapability(located, input, {
|
|
296
|
-
context,
|
|
297
|
-
...signal ? { signal } : {}
|
|
298
|
-
});
|
|
299
|
-
} catch (error) {
|
|
300
|
-
if (error instanceof CapableError) throw new TransportError(error.code, {
|
|
301
|
-
...error.message ? { message: error.message } : {},
|
|
302
|
-
...typeof error.status === "number" ? { status: error.status } : {},
|
|
303
|
-
...error.data === void 0 ? {} : { data: error.data },
|
|
304
|
-
cause: error
|
|
305
|
-
});
|
|
306
|
-
throw new TransportError("INTERNAL_SERVER_ERROR", { cause: error });
|
|
307
|
-
}
|
|
308
|
-
const presentation = await materializePresentation(located.capability, output, context, wantsPresentation);
|
|
309
|
-
return {
|
|
310
|
-
output,
|
|
311
|
-
...presentation ? { presentation } : {}
|
|
312
|
-
};
|
|
313
|
-
},
|
|
314
|
-
async *subscribe({ id, input = {}, signal, presentation: wantsPresentation }) {
|
|
315
|
-
const located = byId.get(id);
|
|
316
|
-
if (!located) throw new TransportError("NOT_FOUND", { status: 404 });
|
|
317
|
-
if (!located.capability.subscribe) throw new TransportError("NOT_FOUND", { status: 404 });
|
|
318
|
-
let context;
|
|
319
|
-
try {
|
|
320
|
-
context = options?.context ? await options.context({
|
|
321
|
-
id,
|
|
322
|
-
...signal ? { signal } : {}
|
|
323
|
-
}) : void 0;
|
|
324
|
-
} catch (cause) {
|
|
325
|
-
throw new TransportError("INTERNAL_SERVER_ERROR", { cause });
|
|
326
|
-
}
|
|
327
|
-
const stream = subscribeLocatedCapability(located, input, {
|
|
328
|
-
context,
|
|
329
|
-
...signal ? { signal } : {}
|
|
330
|
-
});
|
|
331
|
-
try {
|
|
332
|
-
for await (const output of stream) {
|
|
333
|
-
const presentation = await materializePresentation(located.capability, output, context, wantsPresentation);
|
|
334
|
-
yield {
|
|
335
|
-
output,
|
|
336
|
-
...presentation ? { presentation } : {}
|
|
337
|
-
};
|
|
338
|
-
}
|
|
339
|
-
} catch (error) {
|
|
340
|
-
throw toTransportError(error);
|
|
341
|
-
} finally {
|
|
342
|
-
await stream.return?.();
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
}));
|
|
346
|
-
}
|
|
347
|
-
function createRemoteApp(transport) {
|
|
348
|
-
const manifest = createManifestResolver(async () => {
|
|
349
|
-
const manifest = await transport.manifest();
|
|
350
|
-
validateManifest(manifest, "Remote App");
|
|
351
|
-
return manifest;
|
|
352
|
-
});
|
|
353
|
-
return appFromRuntime(Object.freeze({
|
|
354
|
-
manifest,
|
|
355
|
-
async call(call) {
|
|
356
|
-
await manifest();
|
|
357
|
-
return transport.call(call);
|
|
358
|
-
},
|
|
359
|
-
async *subscribe(call) {
|
|
360
|
-
await manifest();
|
|
361
|
-
yield* transport.subscribe(call);
|
|
362
|
-
}
|
|
363
|
-
}));
|
|
364
|
-
}
|
|
365
|
-
function createManifestResolver(load) {
|
|
366
|
-
let cached;
|
|
367
|
-
return () => {
|
|
368
|
-
if (cached) return cached;
|
|
369
|
-
const attempt = Promise.resolve().then(load);
|
|
370
|
-
cached = attempt;
|
|
371
|
-
attempt.catch(() => {
|
|
372
|
-
if (cached === attempt) cached = void 0;
|
|
373
|
-
});
|
|
374
|
-
return attempt;
|
|
375
|
-
};
|
|
376
|
-
}
|
|
377
|
-
var TransportError = class extends Error {
|
|
378
|
-
code;
|
|
379
|
-
status;
|
|
380
|
-
data;
|
|
381
|
-
constructor(code, options = {}) {
|
|
382
|
-
super(options.message ?? code, { cause: options.cause });
|
|
383
|
-
this.name = "TransportError";
|
|
384
|
-
this.code = code;
|
|
385
|
-
this.status = options.status;
|
|
386
|
-
this.data = options.data;
|
|
387
|
-
}
|
|
388
|
-
};
|
|
389
|
-
async function materializePresentation(capability, output, context, requested) {
|
|
390
|
-
if (!requested || !capability.toPresentation) return void 0;
|
|
391
|
-
try {
|
|
392
|
-
const presentation = normalizePresentation(await capability.toPresentation(output, { context }));
|
|
393
|
-
return presentation.length > 0 ? presentation : void 0;
|
|
394
|
-
} catch (cause) {
|
|
395
|
-
throw new TransportError("INTERNAL_SERVER_ERROR", { cause });
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
function toTransportError(error) {
|
|
399
|
-
if (error instanceof TransportError) return error;
|
|
400
|
-
if (error instanceof CapableError) return new TransportError(error.code, {
|
|
401
|
-
...error.message ? { message: error.message } : {},
|
|
402
|
-
...typeof error.status === "number" ? { status: error.status } : {},
|
|
403
|
-
...error.data === void 0 ? {} : { data: error.data },
|
|
404
|
-
cause: error
|
|
405
|
-
});
|
|
406
|
-
return new TransportError("INTERNAL_SERVER_ERROR", { cause: error });
|
|
407
|
-
}
|
|
408
|
-
//#endregion
|
|
409
|
-
//#region packages/app/src/composition.ts
|
|
410
|
-
function mergeApps(...applications) {
|
|
411
|
-
const runtimes = applications.map(getAppRuntime);
|
|
412
|
-
let dispatch;
|
|
413
|
-
const resolve = createManifestResolver(async () => {
|
|
414
|
-
const manifests = await Promise.all(runtimes.map((runtime) => runtime.manifest()));
|
|
415
|
-
const nextDispatch = /* @__PURE__ */ new Map();
|
|
416
|
-
manifests.forEach((manifest, index) => {
|
|
417
|
-
for (const capability of flattenManifestCapabilities(manifest.capabilities)) nextDispatch.set(capability.id, runtimes[index]);
|
|
418
|
-
});
|
|
419
|
-
const merged = mergeApplicationManifests(manifests);
|
|
420
|
-
dispatch = nextDispatch;
|
|
421
|
-
return merged;
|
|
422
|
-
});
|
|
423
|
-
return appFromRuntime(Object.freeze({
|
|
424
|
-
manifest: resolve,
|
|
425
|
-
async call(call) {
|
|
426
|
-
await resolve();
|
|
427
|
-
const target = dispatch?.get(call.id);
|
|
428
|
-
if (!target) throw new TransportError("NOT_FOUND", { status: 404 });
|
|
429
|
-
return target.call(call);
|
|
430
|
-
},
|
|
431
|
-
async *subscribe(call) {
|
|
432
|
-
await resolve();
|
|
433
|
-
const target = dispatch?.get(call.id);
|
|
434
|
-
if (!target) throw new TransportError("NOT_FOUND", { status: 404 });
|
|
435
|
-
yield* target.subscribe(call);
|
|
436
|
-
}
|
|
437
|
-
}));
|
|
438
|
-
}
|
|
439
|
-
function selectApp(application, selection) {
|
|
440
|
-
const runtime = getAppRuntime(application);
|
|
441
|
-
let ids;
|
|
442
|
-
const manifest = createManifestResolver(async () => {
|
|
443
|
-
const selected = selectManifest(await runtime.manifest(), selection);
|
|
444
|
-
ids = new Set(flattenManifestCapabilities(selected.capabilities).map((capability) => capability.id));
|
|
445
|
-
return selected;
|
|
446
|
-
});
|
|
447
|
-
return appFromRuntime(Object.freeze({
|
|
448
|
-
manifest,
|
|
449
|
-
async call(call) {
|
|
450
|
-
await manifest();
|
|
451
|
-
if (!ids?.has(call.id)) throw new TransportError("NOT_FOUND", { status: 404 });
|
|
452
|
-
return runtime.call(call);
|
|
453
|
-
},
|
|
454
|
-
async *subscribe(call) {
|
|
455
|
-
await manifest();
|
|
456
|
-
if (!ids?.has(call.id)) throw new TransportError("NOT_FOUND", { status: 404 });
|
|
457
|
-
yield* runtime.subscribe(call);
|
|
458
|
-
}
|
|
459
|
-
}));
|
|
460
|
-
}
|
|
461
|
-
//#endregion
|
|
462
|
-
export { TransportError as a, getAppRuntime as c, createAppManifest as d, APP_RUNTIME_SYMBOL as i, isApp as l, selectApp as n, createApp as o, APP_CAPABILITIES_SYMBOL as r, createRemoteApp as s, mergeApps as t, subscribe as u };
|
|
463
|
-
|
|
464
|
-
//# sourceMappingURL=src-C2MGIlT0.mjs.map
|