capable-kit 0.0.1-alpha.0 → 0.0.1-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +58 -0
- package/dist/ai-sdk.d.mts +2 -2
- package/dist/ai-sdk.mjs +1 -1
- package/dist/app.d.mts +1 -1
- package/dist/app.mjs +1 -1
- package/dist/bin.mjs +396 -48
- package/dist/bin.mjs.map +1 -1
- package/dist/cli.d.mts +27 -2
- package/dist/cli.mjs +2 -2
- package/dist/core.d.mts +3 -3
- package/dist/core.mjs +1 -1
- package/dist/eve.d.mts +1 -1
- package/dist/eve.mjs +1 -1
- package/dist/http.d.mts +1 -1
- package/dist/http.mjs +1 -1
- package/dist/{index-DLcYNpfo.d.mts → index-BB5ogMv-.d.mts} +17 -14
- package/dist/{index-C9ZThFPN.d.mts → index-BxJhwhKm.d.mts} +2 -2
- package/dist/{index-BuXwkN8G.d.mts → index-CThfifn8.d.mts} +4 -4
- package/dist/{index-u9ZOETR5.d.mts → index-Dp-D73pf.d.mts} +3 -3
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +2 -2
- package/dist/mcp.d.mts +2 -2
- package/dist/mcp.mjs +1 -139
- package/dist/mount--YHrgRHJ.mjs +140 -0
- package/dist/mount--YHrgRHJ.mjs.map +1 -0
- package/dist/runtime-support.d.mts +19 -0
- package/dist/runtime-support.mjs +567 -0
- package/dist/runtime-support.mjs.map +1 -0
- package/dist/server.d.mts +1 -1
- package/dist/server.mjs +1 -81
- package/dist/{src-CT4fbWqb.mjs → src-3UaBqI8H.mjs} +26 -16
- package/dist/src-3UaBqI8H.mjs.map +1 -0
- package/dist/{src-DX-_J6l2.mjs → src-B53ZbNtC.mjs} +6 -7
- package/dist/src-B53ZbNtC.mjs.map +1 -0
- package/dist/{src-CvWOGyGW.mjs → src-BjBxOv7x.mjs} +148 -96
- package/dist/src-BjBxOv7x.mjs.map +1 -0
- package/dist/src-DpSA-hBO.mjs +82 -0
- package/dist/src-DpSA-hBO.mjs.map +1 -0
- package/dist/{src-DlSJtEhv.mjs → src-XRJ9hgYX.mjs} +7 -7
- package/dist/src-XRJ9hgYX.mjs.map +1 -0
- package/dist/{subscription-CBnnIU42.d.mts → subscription-McaLyHM2.d.mts} +2 -2
- package/package.json +59 -17
- package/src/ai-sdk.ts +1 -0
- package/src/app.ts +1 -0
- package/src/bin.ts +4 -0
- package/src/cli.ts +1 -0
- package/src/core.ts +1 -0
- package/src/eve.ts +1 -0
- package/src/http.ts +1 -0
- package/src/index.test.ts +56 -0
- package/src/index.ts +38 -0
- package/src/mcp.ts +2 -0
- package/src/runtime-support.ts +1 -0
- package/src/server.ts +1 -0
- package/dist/mcp.mjs.map +0 -1
- package/dist/server.mjs.map +0 -1
- package/dist/src-CT4fbWqb.mjs.map +0 -1
- package/dist/src-CvWOGyGW.mjs.map +0 -1
- package/dist/src-DX-_J6l2.mjs.map +0 -1
- package/dist/src-DlSJtEhv.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-XRJ9hgYX.mjs","names":["normalizePath"],"sources":["../../fetch/src/error-response.ts","../../fetch/src/standard.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 {\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 { readonly input?: unknown };\n stream = runtime.subscribe({\n id,\n input: body.input ?? {},\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 { readonly input?: unknown };\n const result = await runtime.call({\n id,\n input: body.input ?? {},\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 response.json() as ApplicationManifest;\n },\n async call({ id, input = {}, signal }: CapabilityCall) {\n const response = await request(`call/${encodeURIComponent(id)}`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ input }),\n ...(signal ? { signal } : {}),\n });\n const body = await response.json() as\n | {\n readonly ok: true;\n readonly output: unknown;\n readonly markdown?: string;\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.markdown ? { markdown: body.markdown } : {}),\n };\n },\n async *subscribe({\n id,\n input = {},\n signal,\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 }),\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\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n","import {\n executeLocatedCapability,\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 \"./standard.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.toMarkdown\n ) {\n return new Response(\n await match.route.capability.capability.toMarkdown(output, { context }),\n {\n status: httpSuccessStatus(match.route.capability),\n headers: { \"content-type\": \"text/markdown; charset=utf-8\" },\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;;;ACjBA,SAAgB,sBACd,aAGA,UAEI,CAAC,GAGL;CACA,MAAM,WAAWA,gBAAc,QAAQ,YAAY,WAAW;CAE9D,MAAM,QAAsB,OAAO,YAAY;EAC7C,MAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;EAI/B,MAAM,UAAU,cAHJ,MAAM,WAAW,IACzB,cACA,MAAM,YAAY,OAAO,CACI;EACjC,IAAI,IAAI,aAAa,GAAG,SAAS,cAAc,QAAQ,WAAW,OAChE,OAAO,SAAS,KAAK,MAAM,QAAQ,SAAS,CAAC;EAE/C,MAAM,kBAAkB,GAAG,SAAS;EACpC,IACE,IAAI,SAAS,WAAW,eAAe,KACvC,QAAQ,WAAW,QACnB;GACA,MAAM,KAAK,mBACT,IAAI,SAAS,MAAM,gBAAgB,MAAM,CAC3C;GACA,MAAM,aAAa,IAAI,gBAAgB;GACvC,IAAI;GACJ,IAAI;IACF,MAAM,OAAO,MAAM,QAAQ,K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iB,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"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { L as MaybePromise } from "./index-
|
|
1
|
+
import { L as MaybePromise } from "./index-BB5ogMv-.mjs";
|
|
2
2
|
//#region packages/core/src/subscription.d.ts
|
|
3
3
|
type WatchQueryOptions<TOutput> = {
|
|
4
4
|
readonly snapshot: () => MaybePromise<TOutput>;
|
|
@@ -15,4 +15,4 @@ type WatchQueryOptions<TOutput> = {
|
|
|
15
15
|
declare function watchQuery<TOutput>(options: WatchQueryOptions<TOutput>): AsyncIterableIterator<TOutput>;
|
|
16
16
|
//#endregion
|
|
17
17
|
export { watchQuery as n, WatchQueryOptions as t };
|
|
18
|
-
//# sourceMappingURL=subscription-
|
|
18
|
+
//# sourceMappingURL=subscription-McaLyHM2.d.mts.map
|
package/package.json
CHANGED
|
@@ -1,35 +1,77 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "capable-kit",
|
|
3
|
-
"version": "0.0.1-alpha.
|
|
3
|
+
"version": "0.0.1-alpha.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
|
-
"
|
|
6
|
+
"cap": "dist/bin.mjs",
|
|
7
|
+
"capable": "dist/bin.mjs"
|
|
7
8
|
},
|
|
8
9
|
"exports": {
|
|
9
|
-
".": {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
"./
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
"./
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.mts",
|
|
12
|
+
"import": "./dist/index.mjs"
|
|
13
|
+
},
|
|
14
|
+
"./ai-sdk": {
|
|
15
|
+
"types": "./dist/ai-sdk.d.mts",
|
|
16
|
+
"import": "./dist/ai-sdk.mjs"
|
|
17
|
+
},
|
|
18
|
+
"./app": {
|
|
19
|
+
"types": "./dist/app.d.mts",
|
|
20
|
+
"import": "./dist/app.mjs"
|
|
21
|
+
},
|
|
22
|
+
"./cli": {
|
|
23
|
+
"types": "./dist/cli.d.mts",
|
|
24
|
+
"import": "./dist/cli.mjs"
|
|
25
|
+
},
|
|
26
|
+
"./core": {
|
|
27
|
+
"types": "./dist/core.d.mts",
|
|
28
|
+
"import": "./dist/core.mjs"
|
|
29
|
+
},
|
|
30
|
+
"./eve": {
|
|
31
|
+
"types": "./dist/eve.d.mts",
|
|
32
|
+
"import": "./dist/eve.mjs"
|
|
33
|
+
},
|
|
34
|
+
"./http": {
|
|
35
|
+
"types": "./dist/http.d.mts",
|
|
36
|
+
"import": "./dist/http.mjs"
|
|
37
|
+
},
|
|
38
|
+
"./mcp": {
|
|
39
|
+
"types": "./dist/mcp.d.mts",
|
|
40
|
+
"import": "./dist/mcp.mjs"
|
|
41
|
+
},
|
|
42
|
+
"./server": {
|
|
43
|
+
"types": "./dist/server.d.mts",
|
|
44
|
+
"import": "./dist/server.mjs"
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
"files": [
|
|
48
|
+
"dist",
|
|
49
|
+
"src",
|
|
50
|
+
"README.md"
|
|
51
|
+
],
|
|
52
|
+
"engines": {
|
|
53
|
+
"node": ">=20"
|
|
54
|
+
},
|
|
55
|
+
"publishConfig": {
|
|
56
|
+
"access": "public",
|
|
57
|
+
"registry": "https://registry.npmjs.org/"
|
|
18
58
|
},
|
|
19
|
-
"files": ["dist"],
|
|
20
|
-
"engines": { "node": ">=20" },
|
|
21
59
|
"dependencies": {
|
|
60
|
+
"@standard-schema/spec": "^1.1.0",
|
|
22
61
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
23
62
|
"markdansi": "0.3.2",
|
|
24
|
-
"nitro": "3.0.260610-beta"
|
|
25
|
-
"zod": "^4.1.8"
|
|
63
|
+
"nitro": "3.0.260610-beta"
|
|
26
64
|
},
|
|
27
65
|
"peerDependencies": {
|
|
28
66
|
"ai": "^7.0.0",
|
|
29
67
|
"eve": ">=0.27.1"
|
|
30
68
|
},
|
|
31
69
|
"peerDependenciesMeta": {
|
|
32
|
-
"ai": {
|
|
33
|
-
|
|
70
|
+
"ai": {
|
|
71
|
+
"optional": true
|
|
72
|
+
},
|
|
73
|
+
"eve": {
|
|
74
|
+
"optional": true
|
|
75
|
+
}
|
|
34
76
|
}
|
|
35
77
|
}
|
package/src/ai-sdk.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "@capable/ai-sdk";
|
package/src/app.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "@capable/app";
|
package/src/bin.ts
ADDED
package/src/cli.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "@capable/cli";
|
package/src/core.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "@capable/core";
|
package/src/eve.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "@capable/eve";
|
package/src/http.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "@capable/fetch";
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { describe, expect, test } from "vitest";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import * as capable from "./index.ts";
|
|
4
|
+
import { createAiSdkTools } from "./ai-sdk.ts";
|
|
5
|
+
import { createCli } from "./cli.ts";
|
|
6
|
+
import { executeCapability } from "./core.ts";
|
|
7
|
+
import { createEveTools } from "./eve.ts";
|
|
8
|
+
import { createHttpHandler, createHttpTransport } from "./http.ts";
|
|
9
|
+
import { createMcp, mcp } from "./mcp.ts";
|
|
10
|
+
import { createServer } from "./server.ts";
|
|
11
|
+
|
|
12
|
+
describe("capable public entry points", () => {
|
|
13
|
+
test("ships cap as the primary command with the capable alias", async () => {
|
|
14
|
+
const manifest = JSON.parse(
|
|
15
|
+
await readFile(new URL("../package.json", import.meta.url), "utf8"),
|
|
16
|
+
) as {
|
|
17
|
+
readonly bin?: Readonly<Record<string, string>>;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
expect(manifest.bin).toEqual({
|
|
21
|
+
cap: "dist/bin.mjs",
|
|
22
|
+
capable: "dist/bin.mjs",
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test("keeps the root focused on authoring and App composition", () => {
|
|
27
|
+
expect(Object.keys(capable).sort()).toEqual([
|
|
28
|
+
"capability",
|
|
29
|
+
"createApp",
|
|
30
|
+
"createRemoteApp",
|
|
31
|
+
"defineApp",
|
|
32
|
+
"defineErrors",
|
|
33
|
+
"executeCapability",
|
|
34
|
+
"group",
|
|
35
|
+
"md",
|
|
36
|
+
"mergeApps",
|
|
37
|
+
"selectApp",
|
|
38
|
+
"subscribe",
|
|
39
|
+
"watchQuery",
|
|
40
|
+
]);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("resolves surface and advanced APIs from explicit subpaths", () => {
|
|
44
|
+
expect(typeof createAiSdkTools).toBe("function");
|
|
45
|
+
expect([
|
|
46
|
+
createCli,
|
|
47
|
+
executeCapability,
|
|
48
|
+
createEveTools,
|
|
49
|
+
createHttpHandler,
|
|
50
|
+
createMcp,
|
|
51
|
+
mcp,
|
|
52
|
+
createServer,
|
|
53
|
+
createHttpTransport,
|
|
54
|
+
].every((value) => typeof value === "function")).toBe(true);
|
|
55
|
+
});
|
|
56
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export {
|
|
2
|
+
defineApp,
|
|
3
|
+
defineErrors,
|
|
4
|
+
executeCapability,
|
|
5
|
+
group,
|
|
6
|
+
md,
|
|
7
|
+
capability,
|
|
8
|
+
watchQuery,
|
|
9
|
+
type AppContext,
|
|
10
|
+
type AppDefinition,
|
|
11
|
+
type DefinedErrors,
|
|
12
|
+
type ExecuteCapabilityOptions,
|
|
13
|
+
type MarkdownRenderer,
|
|
14
|
+
type CapabilityDefinition,
|
|
15
|
+
type CapabilityContext,
|
|
16
|
+
type CapabilityEffect,
|
|
17
|
+
type CapabilityFactory,
|
|
18
|
+
type CapabilityHandlerArgs,
|
|
19
|
+
type CapabilityInput,
|
|
20
|
+
type CapabilityMiddleware,
|
|
21
|
+
type CapabilityMiddlewareArgs,
|
|
22
|
+
type CapabilityOutput,
|
|
23
|
+
type CapabilitySubscriber,
|
|
24
|
+
type CapabilitySubscriberArgs,
|
|
25
|
+
type CapabilityTree,
|
|
26
|
+
type WatchQueryOptions,
|
|
27
|
+
} from "@capable/core";
|
|
28
|
+
export {
|
|
29
|
+
createApp,
|
|
30
|
+
createRemoteApp,
|
|
31
|
+
mergeApps,
|
|
32
|
+
selectApp,
|
|
33
|
+
subscribe,
|
|
34
|
+
type ApplicationSelection,
|
|
35
|
+
type App,
|
|
36
|
+
type AppContextProvider,
|
|
37
|
+
type AppCapabilityCall,
|
|
38
|
+
} from "@capable/app";
|
package/src/mcp.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "@capable/nitro-host/runtime-support";
|
package/src/server.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "@capable/server";
|
package/dist/mcp.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mcp.mjs","names":[],"sources":["../../mcp/src/index.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 ...(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 type { ServerMount } from \"@capable/server\";\nimport { createApp, TransportError } from \"@capable/app\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport {\n CallToolRequestSchema,\n type CallToolResult,\n ListToolsRequestSchema,\n type Tool,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { createMcp, type McpTool } from \"./index.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 return {\n name: \"mcp\",\n async fetch(request) {\n if (new URL(request.url).pathname !== path) return undefined;\n const executable = createApp(\n app,\n context\n ? { context: () => context({ request }) }\n : undefined as never,\n );\n const tools = await createMcp(executable);\n const server = createMcpServer(tools, {\n name: options.name ?? app.name ?? \"capable\",\n version: options.version ?? app.version ?? \"0.0.0\",\n });\n const transport = new WebStandardStreamableHTTPServerTransport({\n enableJsonResponse: true,\n });\n await server.connect(transport);\n try {\n return await transport.handleRequest(request);\n } finally {\n await transport.close();\n await server.close();\n }\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(ListToolsRequestSchema, () => ({\n tools: tools.map(toProtocolTool),\n }));\n server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\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: extra.signal,\n });\n return {\n content: [{\n type: \"text\",\n text: result.markdown ?? stringify(result.output),\n }],\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 stringify(value: unknown): string {\n return typeof value === \"string\"\n ? value\n : JSON.stringify(value) ?? String(value);\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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../../server/src/index.ts"],"sourcesContent":["import type {\n AppDefinition,\n MaybePromise,\n} from \"@capable/core\";\nimport {\n createHttpHandler,\n createProtocolHandler,\n type ContextProvider,\n type CapabilitySelection,\n} from \"@capable/fetch\";\nimport {\n createApp,\n selectApp,\n type ApplicationSelection,\n} from \"@capable/app\";\n\nexport type ServerMount<TContext> = {\n readonly kind: \"capable.server.mount\";\n compile(\n app: AppDefinition<any, TContext>,\n context: ContextProvider<TContext> | undefined,\n ): CompiledServerMount;\n};\n\nexport type CompiledServerMount = {\n readonly name: string;\n readonly fetch: (request: Request) => MaybePromise<Response | undefined>;\n};\n\nexport function standard<TContext = any>(\n options: {\n readonly path?: string;\n readonly selection?: ApplicationSelection;\n } = {},\n): ServerMount<TContext> {\n return {\n kind: \"capable.server.mount\",\n compile(app, context) {\n const protocol = createProtocolHandler(\n (request) => {\n const executable = createApp(\n app,\n context\n ? { context: () => context({ request }) }\n : undefined as never,\n );\n return options.selection\n ? selectApp(executable, options.selection)\n : executable;\n },\n {\n ...(options.path ? { basePath: options.path } : {}),\n },\n );\n const base = normalizePath(options.path ?? \"/_capable\");\n return {\n name: \"standard\",\n async fetch(request) {\n if (!new URL(request.url).pathname.startsWith(`${base}/`)) {\n return undefined;\n }\n return protocol.fetch(request);\n },\n };\n },\n };\n}\n\nexport function http<TContext = any>(\n options: {\n readonly path?: string;\n readonly openapiPath?: string | false;\n readonly requireExplicitRoutes?: boolean;\n readonly selection?: CapabilitySelection;\n } = {},\n): ServerMount<TContext> {\n return {\n kind: \"capable.server.mount\",\n compile(app, context) {\n const handler = createHttpHandler(app, {\n ...(context ? { context } : {}),\n ...(options.path ? { basePath: options.path } : {}),\n ...(options.openapiPath !== undefined\n ? { openapiPath: options.openapiPath }\n : {}),\n ...(options.requireExplicitRoutes !== undefined\n ? { requireExplicitRoutes: options.requireExplicitRoutes }\n : {}),\n ...(options.selection ? { selection: options.selection } : {}),\n });\n const base = normalizePath(options.path ?? \"/api\");\n const openapiPath = options.openapiPath === false\n ? undefined\n : normalizePath(options.openapiPath ?? \"/openapi.json\");\n return {\n name: \"http\",\n async fetch(request) {\n const pathname = new URL(request.url).pathname;\n if (\n !pathname.startsWith(`${base}/`) &&\n pathname !== base &&\n pathname !== openapiPath\n ) {\n return undefined;\n }\n return handler.fetch(request);\n },\n };\n },\n };\n}\n\nexport type CapableServer = {\n readonly fetch: (request: Request) => Promise<Response>;\n};\n\nexport type ServerMiddleware = (args: {\n readonly request: Request;\n readonly next: (request?: Request) => Promise<Response>;\n}) => MaybePromise<Response>;\n\ntype CreateServerOptions<TContext> = {\n readonly context?: ContextProvider<TContext>;\n readonly mounts?: readonly ServerMount<TContext>[];\n readonly middleware?: ServerMiddleware;\n readonly onError?: (error: unknown) => void;\n};\n\ntype CreateServerArgs<TContext> = [TContext] extends [undefined]\n ? [options?: CreateServerOptions<TContext>]\n : [options: CreateServerOptions<TContext> & {\n readonly context: ContextProvider<TContext>;\n }];\n\nexport function createServer<TContext>(\n app: AppDefinition<any, TContext>,\n ...[providedOptions]: CreateServerArgs<TContext>\n): CapableServer {\n const options = (providedOptions ?? {}) as CreateServerOptions<TContext>;\n const mounts = (options.mounts ?? [standard(), http()])\n .map((mount) => mount.compile(app, options.context));\n\n async function dispatch(request: Request): Promise<Response> {\n for (const mount of mounts) {\n const response = await mount.fetch(request);\n if (response) return response;\n }\n return new Response(\"Not Found\", { status: 404 });\n }\n\n return Object.freeze({\n async fetch(request: Request) {\n try {\n return options.middleware\n ? await options.middleware({\n request,\n next: (nextRequest = request) => dispatch(nextRequest),\n })\n : await dispatch(request);\n } catch (error) {\n options.onError?.(error);\n return Response.json({\n ok: false,\n error: {\n code: \"INTERNAL_SERVER_ERROR\",\n message: \"Internal Server Error\",\n status: 500,\n },\n }, { status: 500 });\n }\n },\n });\n}\n\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n"],"mappings":";;;AA6BA,SAAgB,SACd,UAGI,CAAC,GACkB;CACvB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AAS,WAAW,GAAG,KAAK,EAAE,KAC/B,aAAa,QACb,aAAa,aAEb;KAEF,OAAO,QAAQ,MAAM,OAAO;IAC9B;GACF;EACF;CACF;AACF;AAwBA,SAAgB,aACd,KACA,GAAG,CAAC,kBACW;CACf,MAAM,UAAW,mBAAmB,CAAC;CACrC,MAAM,UAAU,QAAQ,UAAU,CAAC,SAAS,GAAG,KAAK,CAAC,EAAA,CAClD,KAAK,UAAU,MAAM,QAAQ,KAAK,QAAQ,OAAO,CAAC;CAErD,eAAe,SAAS,SAAqC;EAC3D,KAAK,MAAM,SAAS,QAAQ;GAC1B,MAAM,WAAW,MAAM,MAAM,MAAM,OAAO;GAC1C,IAAI,UAAU,OAAO;EACvB;EACA,OAAO,IAAI,SAAS,aAAa,EAAE,QAAQ,IAAI,CAAC;CAClD;CAEA,OAAO,OAAO,OAAO,EACnB,MAAM,MAAM,SAAkB;EAC5B,IAAI;GACF,OAAO,QAAQ,aACX,MAAM,QAAQ,WAAW;IACzB;IACA,OAAO,cAAc,YAAY,SAAS,WAAW;GACvD,CAAC,IACC,MAAM,SAAS,OAAO;EAC5B,SAAS,OAAO;GACd,QAAQ,UAAU,KAAK;GACvB,OAAO,SAAS,KAAK;IACnB,IAAI;IACJ,OAAO;KACL,MAAM;KACN,SAAS;KACT,QAAQ;IACV;GACF,GAAG,EAAE,QAAQ,IAAI,CAAC;EACpB;CACF,EACF,CAAC;AACH;AAEA,SAAS,cAAc,OAAuB;CAC5C,OAAO,IAAI,MAAM,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;AACtD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"src-CT4fbWqb.mjs","names":[],"sources":["../../app/src/manifest.ts","../../app/src/runtime.ts","../../app/src/composition.ts"],"sourcesContent":["import {\n isCapability,\n isCapabilityGroup,\n schemaToJsonSchema,\n type AppDefinition,\n type LocatedCapability,\n} from \"@capable/core\";\n\nexport type JsonSchema = Readonly<Record<string, unknown>>;\n\nexport type ManifestError = {\n readonly message?: string;\n readonly data?: JsonSchema;\n readonly status?: number;\n readonly meta?: Readonly<Record<string, unknown>>;\n};\n\nexport type ManifestCapability = {\n readonly type: \"capability\";\n readonly id: string;\n readonly path: readonly string[];\n readonly title?: string;\n readonly description?: string;\n readonly deprecated: boolean;\n readonly effect?: \"read\" | \"write\" | \"destructive\";\n readonly subscription?: { readonly mode: \"replace\" };\n readonly input?: JsonSchema;\n readonly output?: JsonSchema;\n readonly errors: Readonly<Record<string, ManifestError>>;\n readonly meta: Readonly<Record<string, unknown>>;\n};\n\nexport type ManifestGroup = {\n readonly type: \"group\";\n readonly key: string;\n readonly title?: string;\n readonly description?: string;\n readonly meta: Readonly<Record<string, unknown>>;\n readonly children: readonly ManifestNode[];\n};\n\nexport type ManifestNode = ManifestGroup | ManifestCapability;\n\nexport type ApplicationManifest = {\n readonly protocol: \"capable.capabilities.v2\";\n readonly name: string;\n readonly version: string;\n readonly description?: string;\n readonly capabilities: readonly ManifestNode[];\n};\n\nexport function createAppManifest(\n definition: AppDefinition<any>,\n): ApplicationManifest {\n const byCapability = new Map(\n definition.locatedCapabilities.map((entry) => [entry.capability, entry]),\n );\n return Object.freeze({\n protocol: \"capable.capabilities.v2\",\n name: definition.name,\n version: definition.version,\n ...(definition.description ? { description: definition.description } : {}),\n capabilities: manifestNodes(definition.capabilities, byCapability),\n });\n}\n\nexport function validateManifest(\n manifest: ApplicationManifest,\n label: string,\n): void {\n if (manifest.protocol !== \"capable.capabilities.v2\") {\n throw new Error(`${label} uses unsupported protocol \"${manifest.protocol}\"`);\n }\n const capabilities = flattenManifestCapabilities(manifest.capabilities);\n const ids = new Set<string>();\n const paths = new Set<string>();\n for (const capability of capabilities) {\n const path = capability.path.join(\".\");\n if (ids.has(capability.id)) {\n throw new Error(\n `${label} contains duplicate Capability id \"${capability.id}\"`,\n );\n }\n if (paths.has(path)) {\n throw new Error(`${label} contains duplicate Capability path \"${path}\"`);\n }\n ids.add(capability.id);\n paths.add(path);\n }\n validateManifestPaths(manifest.capabilities, [], label);\n}\n\nexport function mergeApplicationManifests(\n manifests: readonly ApplicationManifest[],\n): ApplicationManifest {\n const conflicts = collectManifestConflicts(manifests);\n if (conflicts.length) {\n throw new Error(\n `Cannot merge Apps:\\n${conflicts.map((item) => `- ${item}`).join(\"\\n\")}`,\n );\n }\n return Object.freeze({\n protocol: \"capable.capabilities.v2\",\n name: manifests.map(({ name }) => name).join(\" + \"),\n version: manifests.map(({ version }) => version).join(\" + \"),\n capabilities: mergeManifestNodes(\n manifests.flatMap(({ capabilities }) => capabilities),\n ),\n });\n}\n\nexport function selectManifest(\n source: ApplicationManifest,\n selection: {\n readonly include?: unknown;\n readonly exclude?: unknown;\n },\n): ApplicationManifest {\n return Object.freeze({\n ...source,\n capabilities: filterManifestNodes(source.capabilities, selection),\n });\n}\n\nexport function flattenManifestCapabilities(\n nodes: readonly ManifestNode[],\n): readonly ManifestCapability[] {\n return nodes.flatMap((node) =>\n node.type === \"capability\"\n ? [node]\n : flattenManifestCapabilities(node.children)\n );\n}\n\nexport function findManifestCapability(\n nodes: readonly ManifestNode[],\n path: readonly string[],\n): ManifestCapability | undefined {\n let current = nodes;\n for (let index = 0; index < path.length; index++) {\n const key = path[index]!;\n const node = current.find((candidate) =>\n candidate.type === \"group\"\n ? candidate.key === key\n : candidate.path.at(-1) === key\n );\n if (!node) return undefined;\n if (node.type === \"capability\") {\n return index === path.length - 1 ? node : undefined;\n }\n current = node.children;\n }\n return undefined;\n}\n\nfunction manifestNodes(\n tree: Readonly<Record<string, unknown>>,\n located: ReadonlyMap<unknown, LocatedCapability>,\n): readonly ManifestNode[] {\n const nodes: ManifestNode[] = [];\n for (const [key, value] of Object.entries(tree)) {\n if (isCapability(value)) {\n const entry = located.get(value);\n if (entry) nodes.push(manifestCapability(entry));\n continue;\n }\n const decorated = isCapabilityGroup(value);\n const childTree = decorated\n ? value.capabilities\n : value as Readonly<Record<string, unknown>>;\n const children = manifestNodes(childTree, located);\n nodes.push(Object.freeze({\n type: \"group\",\n key,\n ...(decorated && value.title ? { title: value.title } : {}),\n ...(decorated && value.description\n ? { description: value.description }\n : {}),\n meta: decorated ? value.meta : {},\n children,\n } satisfies ManifestGroup));\n }\n return nodes;\n}\n\nfunction manifestCapability(entry: LocatedCapability): ManifestCapability {\n const capability = entry.capability;\n return Object.freeze({\n type: \"capability\",\n id: capability.id,\n path: entry.path,\n ...(capability.title ? { title: capability.title } : {}),\n ...(capability.description ? { description: capability.description } : {}),\n deprecated: capability.deprecated,\n ...(capability.effect ? { effect: capability.effect } : {}),\n ...(capability.subscribe\n ? { subscription: { mode: \"replace\" as const } }\n : {}),\n ...(capability.input\n ? { input: schemaToJsonSchema(capability.input) }\n : {}),\n ...(capability.output\n ? { output: schemaToJsonSchema(capability.output) }\n : {}),\n errors: Object.fromEntries(\n Object.entries(entry.errors).map(([code, definition]) => [\n code,\n {\n ...(definition.message ? { message: definition.message } : {}),\n ...(typeof definition.status === \"number\"\n ? { status: definition.status }\n : {}),\n ...(definition.data\n ? { data: schemaToJsonSchema(definition.data) }\n : {}),\n ...(definition.meta ? { meta: definition.meta } : {}),\n } satisfies ManifestError,\n ]),\n ),\n meta: capability.meta,\n });\n}\n\nfunction validateManifestPaths(\n nodes: readonly ManifestNode[],\n parent: readonly string[],\n label: string,\n): void {\n for (const node of nodes) {\n if (node.type === \"group\") {\n validateManifestPaths(node.children, [...parent, node.key], label);\n continue;\n }\n if (!samePath(node.path, [...parent, node.path.at(-1)!])) {\n throw new Error(\n `${label} Capability \"${node.id}\" declares path \"${node.path.join(\".\")}\" that does not match its manifest placement`,\n );\n }\n }\n}\n\nfunction collectManifestConflicts(\n manifests: readonly ApplicationManifest[],\n): readonly string[] {\n const conflicts: string[] = [];\n for (const manifest of manifests) {\n try {\n validateManifest(manifest, manifest.name);\n } catch (error) {\n conflicts.push(error instanceof Error ? error.message : String(error));\n }\n }\n const capabilities = manifests.flatMap((manifest, source) =>\n flattenManifestCapabilities(manifest.capabilities).map((capability) => ({\n capability,\n source,\n label: manifest.name,\n }))\n );\n for (let leftIndex = 0; leftIndex < capabilities.length; leftIndex++) {\n for (\n let rightIndex = leftIndex + 1;\n rightIndex < capabilities.length;\n rightIndex++\n ) {\n const left = capabilities[leftIndex]!;\n const right = capabilities[rightIndex]!;\n if (left.source === right.source) continue;\n const sameId = left.capability.id === right.capability.id;\n const sameCapabilityPath = samePath(\n left.capability.path,\n right.capability.path,\n );\n if (sameCapabilityPath) {\n conflicts.push(\n sameId\n ? `Capability \"${left.capability.id}\" is mounted twice at \"${left.capability.path.join(\".\")}\" by \"${left.label}\" and \"${right.label}\"`\n : `Path \"${left.capability.path.join(\".\")}\" contains both \"${left.capability.id}\" from \"${left.label}\" and \"${right.capability.id}\" from \"${right.label}\"`,\n );\n continue;\n }\n if (sameId) {\n conflicts.push(\n `Capability id \"${left.capability.id}\" appears at both \"${left.capability.path.join(\".\")}\" in \"${left.label}\" and \"${right.capability.path.join(\".\")}\"`,\n );\n }\n if (\n isPathPrefix(left.capability.path, right.capability.path) ||\n isPathPrefix(right.capability.path, left.capability.path)\n ) {\n const leaf = left.capability.path.length < right.capability.path.length\n ? left\n : right;\n const subtree = leaf === left ? right : left;\n conflicts.push(\n `Leaf \"${leaf.capability.path.join(\".\")}\" from \"${leaf.label}\" collides with subtree Capability \"${subtree.capability.path.join(\".\")}\" from \"${subtree.label}\"`,\n );\n }\n }\n }\n return [...new Set(conflicts)];\n}\n\nfunction mergeManifestNodes(\n nodes: readonly ManifestNode[],\n): readonly ManifestNode[] {\n const merged = new Map<string, ManifestNode>();\n for (const node of nodes) {\n const key = node.type === \"group\" ? node.key : node.path.at(-1)!;\n const previous = merged.get(key);\n if (!previous) {\n merged.set(key, node);\n continue;\n }\n if (previous.type !== \"group\" || node.type !== \"group\") {\n throw new Error(`Manifest node collision at \"${key}\"`);\n }\n merged.set(key, Object.freeze({\n type: \"group\",\n key,\n ...mergeGroupField(\"title\", previous.title, node.title, key),\n ...mergeGroupField(\n \"description\",\n previous.description,\n node.description,\n key,\n ),\n meta: mergeGroupMeta(previous.meta, node.meta, key),\n children: mergeManifestNodes([...previous.children, ...node.children]),\n }));\n }\n return [...merged.values()];\n}\n\nfunction mergeGroupField(\n field: \"title\" | \"description\",\n left: string | undefined,\n right: string | undefined,\n path: string,\n): Record<string, string> {\n if (left && right && left !== right) {\n throw new Error(`Group \"${path}\" has conflicting ${field}`);\n }\n const value = left ?? right;\n return value ? { [field]: value } : {};\n}\n\nfunction mergeGroupMeta(\n left: Readonly<Record<string, unknown>>,\n right: Readonly<Record<string, unknown>>,\n path: string,\n): Readonly<Record<string, unknown>> {\n const merged: Record<string, unknown> = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (\n key in merged &&\n JSON.stringify(merged[key]) !== JSON.stringify(value)\n ) {\n throw new Error(\n `Group \"${path}\" has conflicting metadata for \"${key}\"`,\n );\n }\n merged[key] = value;\n }\n return Object.freeze(merged);\n}\n\nfunction filterManifestNodes(\n nodes: readonly ManifestNode[],\n selection: {\n readonly include?: unknown;\n readonly exclude?: unknown;\n },\n): readonly ManifestNode[] {\n const filtered: ManifestNode[] = [];\n for (const node of nodes) {\n if (node.type === \"capability\") {\n const included = selection.include\n ? matchesSelection(selection.include, node.path)\n : true;\n if (included && !matchesSelection(selection.exclude, node.path)) {\n filtered.push(node);\n }\n continue;\n }\n const children = filterManifestNodes(node.children, selection);\n if (children.length) filtered.push(Object.freeze({ ...node, children }));\n }\n return filtered;\n}\n\nfunction matchesSelection(\n tree: unknown,\n path: readonly string[],\n): boolean {\n let current = 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 samePath(\n left: readonly string[],\n right: readonly string[],\n): boolean {\n return left.length === right.length &&\n left.every((segment, index) => segment === right[index]);\n}\n\nfunction isPathPrefix(\n prefix: readonly string[],\n path: readonly string[],\n): boolean {\n return prefix.length < path.length &&\n prefix.every((segment, index) => segment === path[index]);\n}\n","import {\n CapableError,\n executeLocatedCapability,\n subscribeLocatedCapability,\n type AnyCapability,\n type AnyObjectSchema,\n type AppDefinition,\n type AppContext,\n type InferSchemaInput,\n type LocatedCapability,\n type MaybePromise,\n type CapabilityDefinition,\n type CapabilityGroupDefinition,\n type CapabilityOutput,\n type CapabilityTree,\n type SubscribableCapability,\n} from \"@capable/core\";\nimport {\n createAppManifest,\n findManifestCapability,\n validateManifest,\n type ApplicationManifest,\n} from \"./manifest.ts\";\n\nexport type CapabilityCall = {\n readonly id: string;\n readonly input?: unknown;\n readonly signal?: AbortSignal;\n};\n\nexport type CapabilityResult = {\n readonly output: unknown;\n readonly markdown?: string;\n};\n\nexport interface ApplicationTransport {\n manifest(\n options?: { readonly signal?: AbortSignal },\n ): Promise<ApplicationManifest>;\n call(call: CapabilityCall): Promise<CapabilityResult>;\n subscribe(call: CapabilityCall): AsyncIterableIterator<CapabilityResult>;\n}\n\nexport const APP_RUNTIME_SYMBOL = Symbol.for(\"capable.app.runtime\");\nexport const APP_CAPABILITIES_SYMBOL = Symbol.for(\"capable.app.capabilities\");\nconst APP_CALL_SYMBOL = Symbol.for(\"capable.app.call\");\n\ntype AppCapabilityType<TCapability extends AnyCapability> = {\n readonly \"~capable/capability\"?: TCapability;\n};\n\ntype AppCapabilityInput<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<any, infer TInput, any, any, any>\n ? TInput extends AnyObjectSchema\n ? InferSchemaInput<TInput>\n : Record<never, never>\n : never;\n\ntype AppCapabilityOutput<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<any, any, infer TOutput, any, any>\n ? TOutput\n : never;\n\ntype AppCapabilityArgs<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<any, infer TInput, any, any, any>\n ? TInput extends undefined\n ? [\n input?: Record<never, never>,\n options?: { readonly signal?: AbortSignal },\n ]\n : [\n input: AppCapabilityInput<TCapability>,\n options?: { readonly signal?: AbortSignal },\n ]\n : never;\n\nexport type AppCapabilityCall<TCapability extends AnyCapability> = ((\n ...args: AppCapabilityArgs<TCapability>\n) => Promise<AppCapabilityOutput<TCapability>>) &\n AppCapabilityType<TCapability>;\n\nexport type AppCapabilityIsSubscribable<TCall> =\n TCall extends AppCapabilityType<infer TCapability>\n ? TCapability extends CapabilityDefinition<any, any, any, any, any, true>\n ? true\n : false\n : false;\n\nexport type CallableTree<TTree> =\n TTree extends AnyCapability\n ? AppCapabilityCall<TTree>\n : TTree extends CapabilityGroupDefinition<infer TCapabilities, any, any>\n ? CallableTree<TCapabilities>\n : TTree extends CapabilityTree\n ? { readonly [TKey in keyof TTree]: CallableTree<TTree[TKey]> }\n : never;\n\nexport type App<\n TCapabilities extends CapabilityTree = CapabilityTree,\n> = CallableTree<TCapabilities> & {\n readonly [APP_RUNTIME_SYMBOL]: ApplicationTransport;\n readonly [APP_CAPABILITIES_SYMBOL]?: TCapabilities;\n};\n\nexport type AnyApp = {\n readonly [APP_RUNTIME_SYMBOL]: ApplicationTransport;\n readonly [APP_CAPABILITIES_SYMBOL]?: CapabilityTree;\n};\n\ntype DefinitionCapabilities<TDefinition extends AppDefinition<any, any>> =\n TDefinition extends AppDefinition<infer TCapabilities>\n ? TCapabilities\n : never;\n\nexport type AppCapabilities<\n TApplication extends AnyApp,\n> = TApplication extends {\n readonly [APP_CAPABILITIES_SYMBOL]?: infer TCapabilities extends CapabilityTree;\n}\n ? TCapabilities\n : never;\n\nexport function getAppRuntime(\n app: AnyApp,\n): ApplicationTransport {\n return app[APP_RUNTIME_SYMBOL];\n}\n\nexport function isApp(value: unknown): value is AnyApp {\n return Boolean(\n value &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n (value as Partial<AnyApp>)[APP_RUNTIME_SYMBOL],\n );\n}\n\nexport function appFromRuntime<\n TCapabilities extends CapabilityTree,\n>(\n runtime: ApplicationTransport,\n): App<TCapabilities> {\n let manifestPromise: Promise<ApplicationManifest> | undefined;\n const manifest = () => manifestPromise ??= runtime.manifest();\n\n const read = (path: readonly string[], root: boolean, key: PropertyKey) => {\n if (root && key === APP_RUNTIME_SYMBOL) return runtime;\n if (!root && key === APP_CALL_SYMBOL) return { runtime, path };\n if (key === \"then\") return undefined;\n if (typeof key !== \"string\") return undefined;\n return proxy([...path, key], false);\n };\n\n const proxy = (path: readonly string[], root: boolean): unknown => {\n if (root) {\n return new Proxy({}, {\n get(_target, key) {\n return read(path, true, key);\n },\n });\n }\n return new Proxy(() => undefined, {\n get(_target, key) {\n return read(path, false, key);\n },\n async apply(_target, _this, args: [unknown?, { signal?: AbortSignal }?]) {\n const capability = findManifestCapability(\n (await manifest()).capabilities,\n path,\n );\n if (!capability) {\n throw new Error(`No Capability exists at \"${path.join(\".\")}\"`);\n }\n const result = await runtime.call({\n id: capability.id,\n input: args[0] ?? {},\n ...(args[1]?.signal ? { signal: args[1].signal } : {}),\n });\n return result.output;\n },\n });\n };\n\n return proxy([], true) as App<TCapabilities>;\n}\n\nexport function subscribe<\n const TCapability extends SubscribableCapability,\n>(\n capabilityCall: AppCapabilityCall<TCapability>,\n ...args: AppCapabilityArgs<TCapability>\n): AsyncIterableIterator<CapabilityOutput<TCapability>> {\n const binding = (\n capabilityCall as unknown as Record<PropertyKey, unknown>\n )[APP_CALL_SYMBOL] as\n | {\n readonly runtime: ApplicationTransport;\n readonly path: readonly string[];\n }\n | undefined;\n if (!binding) {\n throw new Error(\"subscribe() requires a Capability call from a Capable App\");\n }\n\n return (async function* () {\n const manifest = await binding.runtime.manifest();\n const capability = findManifestCapability(\n manifest.capabilities,\n binding.path,\n );\n if (!capability) {\n throw new Error(`No Capability exists at \"${binding.path.join(\".\")}\"`);\n }\n if (!capability.subscription) {\n throw new Error(`Capability \"${capability.id}\" is not subscribable`);\n }\n const stream = binding.runtime.subscribe({\n id: capability.id,\n input: args[0] ?? {},\n ...(args[1]?.signal ? { signal: args[1].signal } : {}),\n });\n try {\n for await (const result of stream) {\n yield result.output as CapabilityOutput<TCapability>;\n }\n } finally {\n await stream.return?.();\n }\n })();\n}\n\nexport type AppContextProvider<TContext> = (call: {\n readonly id: string;\n readonly signal?: AbortSignal;\n}) => MaybePromise<TContext>;\n\ntype CreateAppOptions<TContext> = {\n readonly context: AppContextProvider<TContext>;\n};\n\ntype CreateAppArgs<TContext> = [TContext] extends [undefined]\n ? [options?: Partial<CreateAppOptions<TContext>>]\n : [options: CreateAppOptions<TContext>];\n\nconst localManifestCache = new WeakMap<object, ApplicationManifest>();\nconst localCapabilityCache = new WeakMap<\n object,\n ReadonlyMap<string, LocatedCapability>\n>();\n\nexport function createApp<\n const TDefinition extends AppDefinition<any, any>,\n>(\n definition: TDefinition,\n ...[options]: CreateAppArgs<AppContext<TDefinition>>\n): App<DefinitionCapabilities<TDefinition>> {\n let manifest = localManifestCache.get(definition);\n if (!manifest) {\n manifest = createAppManifest(definition);\n localManifestCache.set(definition, manifest);\n }\n let byId = localCapabilityCache.get(definition);\n if (!byId) {\n byId = new Map(\n definition.locatedCapabilities.map((entry) => [entry.capability.id, entry]),\n );\n localCapabilityCache.set(definition, byId);\n }\n\n const runtime: ApplicationTransport = Object.freeze({\n async manifest() {\n return manifest;\n },\n async call({ id, input = {}, signal }: CapabilityCall) {\n const located = byId.get(id);\n if (!located) throw new TransportError(\"NOT_FOUND\", { status: 404 });\n\n let context: unknown;\n try {\n context = options?.context\n ? await options.context({\n id,\n ...(signal ? { signal } : {}),\n })\n : undefined;\n } catch (cause) {\n throw new TransportError(\"INTERNAL_SERVER_ERROR\", { cause });\n }\n\n let output: unknown;\n try {\n output = await executeLocatedCapability(located, input, {\n context,\n ...(signal ? { signal } : {}),\n });\n } catch (error) {\n if (error instanceof CapableError) {\n throw new TransportError(error.code, {\n ...(error.message ? { message: error.message } : {}),\n ...(typeof error.status === \"number\"\n ? { status: error.status }\n : {}),\n ...(error.data === undefined ? {} : { data: error.data }),\n cause: error,\n });\n }\n throw new TransportError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n }\n\n let markdown: string | undefined;\n try {\n markdown = located.capability.toMarkdown\n ? await located.capability.toMarkdown(output, { context })\n : undefined;\n } catch (cause) {\n throw new TransportError(\"INTERNAL_SERVER_ERROR\", { cause });\n }\n\n return {\n output,\n ...(markdown ? { markdown } : {}),\n };\n },\n async *subscribe({ id, input = {}, signal }: CapabilityCall) {\n const located = byId.get(id);\n if (!located) throw new TransportError(\"NOT_FOUND\", { status: 404 });\n if (!located.capability.subscribe) {\n throw new TransportError(\"NOT_FOUND\", { status: 404 });\n }\n\n let context: unknown;\n try {\n context = options?.context\n ? await options.context({\n id,\n ...(signal ? { signal } : {}),\n })\n : undefined;\n } catch (cause) {\n throw new TransportError(\"INTERNAL_SERVER_ERROR\", { cause });\n }\n\n const stream = subscribeLocatedCapability(located, input, {\n context,\n ...(signal ? { signal } : {}),\n });\n try {\n for await (const output of stream) {\n let markdown: string | undefined;\n try {\n markdown = located.capability.toMarkdown\n ? await located.capability.toMarkdown(output, { context })\n : undefined;\n } catch (cause) {\n throw new TransportError(\"INTERNAL_SERVER_ERROR\", { cause });\n }\n yield {\n output,\n ...(markdown ? { markdown } : {}),\n };\n }\n } catch (error) {\n throw toTransportError(error);\n } finally {\n await stream.return?.();\n }\n },\n });\n return appFromRuntime(runtime);\n}\n\nexport function createRemoteApp<\n TDefinition extends AppDefinition<any, any> = AppDefinition<CapabilityTree>,\n>(\n transport: ApplicationTransport,\n): App<DefinitionCapabilities<TDefinition>> {\n let resolved: Promise<ApplicationManifest> | undefined;\n const manifest = () =>\n resolved ??= transport.manifest().then((manifest) => {\n validateManifest(manifest, \"Remote App\");\n return manifest;\n });\n return appFromRuntime(Object.freeze({\n manifest,\n async call(call: CapabilityCall) {\n await manifest();\n return transport.call(call);\n },\n async *subscribe(call: CapabilityCall) {\n await manifest();\n yield* transport.subscribe(call);\n },\n }));\n}\n\nexport class TransportError extends Error {\n readonly code: string;\n readonly status: number | undefined;\n readonly data: unknown;\n\n constructor(\n code: string,\n options: {\n readonly message?: string;\n readonly status?: number;\n readonly data?: unknown;\n readonly cause?: unknown;\n } = {},\n ) {\n super(options.message ?? code, { cause: options.cause });\n this.name = \"TransportError\";\n this.code = code;\n this.status = options.status;\n this.data = options.data;\n }\n}\n\nfunction toTransportError(error: unknown): TransportError {\n if (error instanceof TransportError) return error;\n if (error instanceof CapableError) {\n return new TransportError(error.code, {\n ...(error.message ? { message: error.message } : {}),\n ...(typeof error.status === \"number\" ? { status: error.status } : {}),\n ...(error.data === undefined ? {} : { data: error.data }),\n cause: error,\n });\n }\n return new TransportError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n}\n","import type {\n AnyCapability,\n CapabilityGroupDefinition,\n CapabilityTree,\n} from \"@capable/core\";\nimport {\n appFromRuntime,\n getAppRuntime,\n TransportError,\n type AnyApp,\n type App,\n type AppCapabilities,\n type ApplicationTransport,\n type CapabilityCall,\n} from \"./runtime.ts\";\nimport {\n flattenManifestCapabilities,\n mergeApplicationManifests,\n selectManifest,\n type ApplicationManifest,\n} from \"./manifest.ts\";\n\ntype UnionToIntersection<TValue> =\n (TValue extends unknown ? (value: TValue) => void : never) extends\n (value: infer TIntersection) => void ? TIntersection : never;\n\ntype MergedCapabilities<\n TApplications extends readonly AnyApp[],\n> = UnionToIntersection<AppCapabilities<TApplications[number]>> &\n CapabilityTree;\n\nexport function mergeApps<\n const TApplications extends readonly [\n AnyApp,\n ...AnyApp[],\n ],\n>(\n ...applications: TApplications\n): App<MergedCapabilities<TApplications>> {\n const runtimes = applications.map(getAppRuntime);\n let manifestPromise: Promise<ApplicationManifest> | undefined;\n let dispatch: ReadonlyMap<string, ApplicationTransport> | undefined;\n\n const resolve = () =>\n manifestPromise ??= Promise.all(\n runtimes.map((runtime) => runtime.manifest()),\n ).then((manifests) => {\n const nextDispatch = new Map<string, ApplicationTransport>();\n manifests.forEach((manifest, index) => {\n for (\n const capability of flattenManifestCapabilities(\n manifest.capabilities,\n )\n ) {\n nextDispatch.set(capability.id, runtimes[index]!);\n }\n });\n dispatch = nextDispatch;\n return mergeApplicationManifests(manifests);\n });\n\n return appFromRuntime(Object.freeze({\n manifest: resolve,\n async call(call: CapabilityCall) {\n await resolve();\n const target = dispatch?.get(call.id);\n if (!target) throw new TransportError(\"NOT_FOUND\", { status: 404 });\n return target.call(call);\n },\n async *subscribe(call: CapabilityCall) {\n await resolve();\n const target = dispatch?.get(call.id);\n if (!target) throw new TransportError(\"NOT_FOUND\", { status: 404 });\n yield* target.subscribe(call);\n },\n }));\n}\n\ntype SelectionNode<TTree> =\n TTree extends AnyCapability\n ? true\n : TTree extends CapabilityGroupDefinition<infer TCapabilities, any, any>\n ? true | SelectionNode<TCapabilities>\n : TTree extends CapabilityTree\n ? true | {\n readonly [TKey in keyof TTree]?: SelectionNode<TTree[TKey]>;\n }\n : never;\n\nexport type ApplicationSelection<\n TCapabilities extends CapabilityTree = CapabilityTree,\n> = {\n readonly include?: Exclude<SelectionNode<TCapabilities>, true>;\n readonly exclude?: Exclude<SelectionNode<TCapabilities>, true>;\n};\n\nexport function selectApp<\n const TCapabilities extends CapabilityTree,\n>(\n application: App<TCapabilities>,\n selection: ApplicationSelection<TCapabilities>,\n): App<TCapabilities> {\n const runtime = getAppRuntime(application);\n let resolved: Promise<ApplicationManifest> | undefined;\n let ids: ReadonlySet<string> | undefined;\n const manifest = () =>\n resolved ??= runtime.manifest().then((source) => {\n const selected = selectManifest(source, selection);\n ids = new Set(\n flattenManifestCapabilities(selected.capabilities).map(\n (capability) => capability.id,\n ),\n );\n return selected;\n });\n return appFromRuntime(Object.freeze({\n manifest,\n async call(call: CapabilityCall) {\n await manifest();\n if (!ids?.has(call.id)) {\n throw new TransportError(\"NOT_FOUND\", { status: 404 });\n }\n return runtime.call(call);\n },\n async *subscribe(call: CapabilityCall) {\n await manifest();\n if (!ids?.has(call.id)) {\n throw new TransportError(\"NOT_FOUND\", { status: 404 });\n }\n yield* run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AC;AACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"src-CvWOGyGW.mjs","names":["kebabCase","renderMarkdown"],"sources":["../../cli/src/commands.ts","../../cli/src/style.ts","../../cli/src/help.ts","../../cli/src/index.ts"],"sourcesContent":["import type {\n ManifestGroup,\n ManifestNode,\n ManifestCapability,\n} from \"@capable/app\";\nimport type {\n CliGroupMeta,\n CliCapabilityMeta,\n} from \"./index.ts\";\n\nexport type CliCommand = {\n readonly command: readonly string[];\n readonly capability: ManifestCapability;\n readonly meta: Exclude<CliCapabilityMeta, false>;\n};\n\nexport type CliCommandGroup = {\n readonly command: readonly string[];\n readonly title?: string;\n readonly description?: string;\n};\n\nexport type CliCommandCatalog = {\n readonly commands: readonly CliCommand[];\n readonly groups: readonly CliCommandGroup[];\n};\n\nexport function collectCommands(\n nodes: readonly ManifestNode[],\n parent: readonly string[] = [],\n): CliCommandCatalog {\n const commands: CliCommand[] = [];\n const groups: CliCommandGroup[] = [];\n\n for (const node of nodes) {\n if (node.type === \"group\") {\n const meta = (node.meta.cli ?? {}) as CliGroupMeta;\n const command = [...parent, meta.name ?? node.key];\n groups.push(groupFrom(node, command));\n const children = collectCommands(node.children, command);\n commands.push(...children.commands);\n groups.push(...children.groups);\n continue;\n }\n\n const rawMeta = node.meta.cli as CliCapabilityMeta | undefined;\n if (rawMeta === false) continue;\n const meta = rawMeta ?? {};\n commands.push({\n command: meta.command ?? [...parent, meta.name ?? node.path.at(-1)!],\n capability: node,\n meta,\n });\n }\n\n return {\n commands: Object.freeze(commands),\n groups: Object.freeze(groups),\n };\n}\n\nfunction groupFrom(\n node: ManifestGroup,\n command: readonly string[],\n): CliCommandGroup {\n return Object.freeze({\n command: Object.freeze(command),\n ...(node.title ? { title: node.title } : {}),\n ...(node.description ? { description: node.description } : {}),\n });\n}\n","export type CliStyle = {\n readonly bold: (text: string) => string;\n readonly accent: (text: string) => string;\n readonly dim: (text: string) => string;\n};\n\nexport function createCliStyle(color?: boolean): CliStyle {\n const enabled = color ?? supportsColor();\n return {\n bold: enabled ? (text) => `\\u001B[1m${text}\\u001B[22m` : identity,\n accent: enabled ? (text) => `\\u001B[36m${text}\\u001B[39m` : identity,\n dim: enabled ? (text) => `\\u001B[2m${text}\\u001B[22m` : identity,\n };\n}\n\nexport function supportsColor(\n env: Record<string, string | undefined> = process.env,\n isTTY = Boolean(process.stdout.isTTY),\n): boolean {\n if (\"NO_COLOR\" in env) return false;\n if (env.FORCE_COLOR !== undefined) return env.FORCE_COLOR !== \"0\";\n return isTTY && env.TERM !== \"dumb\";\n}\n\nexport function renderRows(\n rows: readonly {\n readonly label: string;\n readonly description?: string;\n }[],\n style: CliStyle,\n): string {\n const width = Math.max(0, ...rows.map(({ label }) => label.length));\n return rows.map(({ label, description }) => {\n const styledLabel = style.accent(label);\n return description\n ? ` ${styledLabel}${\" \".repeat(width - label.length + 3)}${style.dim(description)}`\n : ` ${styledLabel}`;\n }).join(\"\\n\");\n}\n\nexport function renderSection(\n title: string,\n body: string,\n style: CliStyle,\n): string {\n return `${style.bold(title)}\\n${body}`;\n}\n\nfunction identity(text: string): string {\n return text;\n}\n","import type {\n ApplicationManifest,\n JsonSchema,\n} from \"@capable/app\";\nimport type {\n CliCommand,\n CliCommandGroup,\n} from \"./commands.ts\";\nimport {\n renderRows,\n renderSection,\n type CliStyle,\n} from \"./style.ts\";\n\nexport function renderRootHelp(\n manifest: Pick<ApplicationManifest, \"name\" | \"description\">,\n commands: readonly CliCommand[],\n invocationName: string,\n style: CliStyle,\n): string {\n return renderHelp([\n heading(manifest.name, manifest.description, style),\n renderSection(\n \"Usage\",\n ` ${style.accent(invocationName)} <command> [options]`,\n style,\n ),\n renderSection(\n \"Commands\",\n renderRows(commands.map((command) => ({\n label: commandLabel(command),\n ...(command.capability.title\n ? { description: command.capability.title }\n : {}),\n })), style),\n style,\n ),\n globalOptions(style),\n ]);\n}\n\nexport function renderGroupHelp(\n group: CliCommandGroup,\n commands: readonly CliCommand[],\n invocationName: string,\n style: CliStyle,\n): string {\n const children = commands\n .filter((candidate) => startsWith(candidate.command, group.command))\n .map((candidate) => {\n const suffix = candidate.command.slice(group.command.length);\n const positionals = candidate.meta.positional ?? [];\n return {\n label: [...suffix, ...positionals.map((name) => `<${name}>`)].join(\" \"),\n ...(candidate.capability.title\n ? { description: candidate.capability.title }\n : {}),\n };\n });\n return renderHelp([\n heading(\n group.title ?? group.command.at(-1)!,\n group.description,\n style,\n ),\n renderSection(\n \"Usage\",\n ` ${style.accent(`${invocationName} ${group.command.join(\" \")}`)} <command> [options]`,\n style,\n ),\n renderSection(\"Commands\", renderRows(children, style), style),\n globalOptions(style),\n ]);\n}\n\nexport function renderCommandHelp(\n command: CliCommand,\n invocationName: string,\n style: CliStyle,\n): string {\n const positionals = command.meta.positional ?? [];\n const properties = command.capability.input?.properties as\n | Record<string, JsonSchema>\n | undefined;\n const required = new Set(\n command.capability.input?.required as readonly string[] | undefined,\n );\n const argumentsRows = positionals.map((name) => ({\n label: `<${name}>`,\n description: describeField(properties?.[name], required.has(name)),\n }));\n const optionRows = Object.entries(properties ?? {})\n .filter(([name]) => !positionals.includes(name))\n .map(([name, schema]) => ({\n label: optionLabel(name, schema),\n description: describeField(schema, required.has(name)),\n }));\n const usage = [\n invocationName,\n ...command.command,\n ...positionals.map((name) => `<${name}>`),\n \"[options]\",\n ].join(\" \");\n\n return renderHelp([\n heading(\n command.capability.title ?? command.command.join(\" \"),\n command.capability.description,\n style,\n ),\n renderSection(\"Usage\", ` ${style.accent(usage)}`, style),\n argumentsRows.length\n ? renderSection(\"Arguments\", renderRows(argumentsRows, style), style)\n : undefined,\n renderSection(\"Options\", renderRows([\n ...optionRows,\n ...(command.capability.subscription\n ? [{\n label: \"--watch\",\n description: \"Stream updates until interrupted\",\n }]\n : []),\n { label: \"--json\", description: \"Print canonical JSON\" },\n { label: \"-h, --help\", description: \"Show command help\" },\n ], style), style),\n ]);\n}\n\nfunction globalOptions(style: CliStyle): string {\n return renderSection(\"Options\", renderRows([\n { label: \"--json\", description: \"Print canonical JSON\" },\n { label: \"-h, --help\", description: \"Show help\" },\n ], style), style);\n}\n\nfunction heading(\n title: string,\n description: string | undefined,\n style: CliStyle,\n): string {\n return description\n ? `${style.bold(title)}\\n\\n${style.dim(description)}`\n : style.bold(title);\n}\n\nfunction commandLabel(command: CliCommand): string {\n const positionals = (command.meta.positional ?? []).map((name) => `<${name}>`);\n return [...command.command, ...positionals].join(\" \");\n}\n\nfunction optionLabel(name: string, schema: JsonSchema): string {\n const flag = `--${kebabCase(name)}`;\n if (schema.type === \"boolean\") return flag;\n if (schema.type === \"array\" || schema.type === \"object\") {\n return `${flag} <json>`;\n }\n return `${flag} <${String(schema.type ?? \"value\")}>`;\n}\n\nfunction describeField(\n schema: JsonSchema | undefined,\n required: boolean,\n): string {\n const description = typeof schema?.description === \"string\"\n ? schema.description\n : undefined;\n const type = describeSchema(schema);\n return [\n description ? `${description} (${type})` : type,\n required ? \"required\" : undefined,\n schema?.default !== undefined ? `default: ${String(schema.default)}` : undefined,\n ].filter(Boolean).join(\", \");\n}\n\nfunction describeSchema(schema: JsonSchema | undefined): string {\n if (!schema) return \"value\";\n const type = schema.type === \"array\"\n ? `array<${String((schema.items as JsonSchema | undefined)?.type ?? \"value\")}>`\n : schema.type === \"object\"\n ? `object { ${Object.keys(\n schema.properties as Record<string, unknown> | undefined ?? {},\n ).join(\", \")} }`\n : String(schema.type ?? \"value\");\n const constraints: string[] = [];\n if (Array.isArray(schema.enum)) {\n constraints.push(`one of ${schema.enum.map(String).join(\", \")}`);\n }\n if (typeof schema.minLength === \"number\") {\n constraints.push(`minimum ${schema.minLength} characters`);\n }\n if (typeof schema.maxLength === \"number\") {\n constraints.push(`maximum ${schema.maxLength} characters`);\n }\n if (typeof schema.minimum === \"number\") {\n constraints.push(`minimum ${schema.minimum}`);\n }\n if (typeof schema.maximum === \"number\") {\n constraints.push(`maximum ${schema.maximum}`);\n }\n if (typeof schema.format === \"string\") {\n constraints.push(`format ${schema.format}`);\n }\n return [type, ...constraints].join(\", \");\n}\n\nfunction startsWith(\n value: readonly string[],\n prefix: readonly string[],\n): boolean {\n return prefix.every((part, index) => value[index] === part);\n}\n\nfunction kebabCase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);\n}\n\nfunction renderHelp(sections: readonly (string | undefined)[]): string {\n return `${sections.filter(Boolean).join(\"\\n\\n\")}\\n`;\n}\n","import type {\n GroupMetaRegistry,\n CapabilityMetaRegistry,\n} from \"@capable/core\";\nimport {\n getAppRuntime,\n TransportError,\n type AnyApp,\n type JsonSchema,\n type CapabilityResult,\n} from \"@capable/app\";\nimport { render as renderMarkdown } from \"markdansi\";\nimport {\n collectCommands,\n type CliCommand,\n type CliCommandGroup,\n} from \"./commands.ts\";\nimport {\n renderCommandHelp,\n renderGroupHelp,\n renderRootHelp,\n} from \"./help.ts\";\nimport {\n createCliStyle,\n supportsColor,\n} from \"./style.ts\";\n\nexport type CliCapabilityMeta =\n | false\n | {\n readonly name?: string;\n readonly command?: readonly string[];\n readonly positional?: readonly string[];\n };\n\nexport type CliGroupMeta = {\n readonly name?: string;\n};\n\ndeclare module \"@capable/core\" {\n interface CapabilityMetaRegistry {\n readonly cli?: CliCapabilityMeta;\n }\n\n interface GroupMetaRegistry {\n readonly cli?: CliGroupMeta;\n }\n}\n\nexport type CliIo = {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n};\n\nexport type CreateCliOptions = {\n readonly invocationName?: string;\n readonly color?: boolean;\n readonly isTTY?: boolean;\n readonly columns?: number;\n};\n\nexport function createCli(\n app: AnyApp,\n cliOptions: CreateCliOptions = {},\n): {\n run(\n argv: readonly string[],\n options?: { readonly io?: Partial<CliIo> },\n ): Promise<number>;\n} {\n return Object.freeze({\n run(argv, options = {}) {\n return runCli({\n app,\n argv,\n ...(cliOptions.invocationName\n ? { invocationName: cliOptions.invocationName }\n : {}),\n ...(cliOptions.color !== undefined ? { color: cliOptions.color } : {}),\n ...(cliOptions.isTTY !== undefined ? { isTTY: cliOptions.isTTY } : {}),\n ...(cliOptions.columns !== undefined\n ? { columns: cliOptions.columns }\n : {}),\n ...(options.io ? { io: options.io } : {}),\n });\n },\n });\n}\n\nexport async function runCli(options: {\n readonly app: AnyApp;\n readonly argv: readonly string[];\n readonly invocationName?: string;\n readonly color?: boolean;\n readonly isTTY?: boolean;\n readonly columns?: number;\n readonly io?: Partial<CliIo>;\n}): Promise<number> {\n const io: CliIo = {\n stdout: options.io?.stdout ??\n ((text) => process.stdout.write(withTrailingNewline(text))),\n stderr: options.io?.stderr ??\n ((text) => process.stderr.write(withTrailingNewline(text))),\n };\n const invocationName = options.invocationName ?? \"capable\";\n const isTTY = options.isTTY ?? Boolean(process.stdout.isTTY);\n const color = options.color ?? supportsColor(process.env, isTTY);\n const columns = options.columns ?? process.stdout.columns ?? 80;\n const style = createCliStyle(color);\n const runtime = getAppRuntime(options.app);\n let manifest;\n try {\n manifest = await runtime.manifest();\n } catch (error) {\n io.stderr(renderRuntimeError(error));\n return 1;\n }\n const catalog = collectCommands(manifest.capabilities);\n const json = options.argv.includes(\"--json\");\n const watch = options.argv.includes(\"--watch\");\n const wantsHelp = options.argv.includes(\"--help\") ||\n options.argv.includes(\"-h\");\n const argv = options.argv.filter((argument) =>\n ![\"--json\", \"--watch\", \"--help\", \"-h\"].includes(argument)\n );\n\n if (argv.length === 0) {\n io.stdout(renderRootHelp(\n manifest,\n catalog.commands,\n invocationName,\n style,\n ));\n return 0;\n }\n\n const command = matchCommand(argv, catalog.commands);\n const group = exactGroup(argv, catalog.groups);\n if (wantsHelp) {\n if (command) {\n io.stdout(renderCommandHelp(command, invocationName, style));\n return 0;\n }\n if (group) {\n io.stdout(renderGroupHelp(\n group,\n catalog.commands,\n invocationName,\n style,\n ));\n return 0;\n }\n io.stderr(unknownCommand(argv, catalog.commands, invocationName));\n return 2;\n }\n\n if (!command) {\n if (group) {\n io.stderr(\n `Missing command after ${group.command.join(\" \")}\\n` +\n `Run \\`${invocationName} ${group.command.join(\" \")} --help\\` to list available commands.`,\n );\n return 2;\n }\n io.stderr(unknownCommand(argv, catalog.commands, invocationName));\n return 2;\n }\n\n try {\n if (watch && !command.capability.subscription) {\n throw new CliUsageError(\n `Option --watch is only available for subscribable Capabilities`,\n );\n }\n const input = parseArguments(\n argv.slice(command.command.length),\n command,\n invocationName,\n );\n if (watch) {\n return await runWatchedCommand({\n runtime,\n command,\n input,\n json,\n io,\n color,\n isTTY,\n columns,\n });\n }\n const result = await runtime.call({\n id: command.capability.id,\n input,\n });\n io.stdout(\n json\n ? JSON.stringify(result.output, null, 2)\n : renderCapabilityResult(result, {\n color,\n isTTY,\n columns,\n }),\n );\n return 0;\n } catch (error) {\n if (error instanceof CliUsageError) {\n io.stderr(error.message);\n return 2;\n }\n if (error instanceof TransportError) {\n io.stderr(renderRuntimeError(error));\n return 1;\n }\n io.stderr(error instanceof Error ? error.message : String(error));\n return 1;\n }\n}\n\nfunction withTrailingNewline(value: string): string {\n return value.endsWith(\"\\n\") ? value : `${value}\\n`;\n}\n\nasync function runWatchedCommand(options: {\n readonly runtime: ReturnType<typeof getAppRuntime>;\n readonly command: CliCommand;\n readonly input: Record<string, unknown>;\n readonly json: boolean;\n readonly io: CliIo;\n readonly color: boolean;\n readonly isTTY: boolean;\n readonly columns: number;\n}): Promise<number> {\n const controller = new AbortController();\n const abort = () => controller.abort();\n process.once(\"SIGINT\", abort);\n const stream = options.runtime.subscribe({\n id: options.command.capability.id,\n input: options.input,\n signal: controller.signal,\n });\n\n try {\n let frame = 0;\n let previousFrameLines = 0;\n for await (const result of stream) {\n if (options.json) {\n options.io.stdout(`${JSON.stringify(result.output)}\\n`);\n continue;\n }\n const presentation = renderCapabilityResult(result, options);\n options.io.stdout(formatWatchFrame(\n presentation,\n frame++,\n options.isTTY,\n previousFrameLines,\n ));\n previousFrameLines = countFrameLines(presentation);\n }\n return 0;\n } catch (error) {\n if (controller.signal.aborted || isAbortError(error)) return 0;\n throw error;\n } finally {\n process.off(\"SIGINT\", abort);\n await stream.return?.();\n }\n}\n\nfunction renderCapabilityResult(\n result: CapabilityResult,\n options: {\n readonly color: boolean;\n readonly isTTY: boolean;\n readonly columns: number;\n },\n): string {\n if (result.markdown !== undefined) {\n return options.isTTY\n ? renderMarkdown(result.markdown, {\n color: options.color,\n width: options.columns,\n })\n : result.markdown;\n }\n return typeof result.output === \"string\"\n ? result.output\n : JSON.stringify(result.output, null, 2);\n}\n\nfunction formatWatchFrame(\n value: string,\n index: number,\n isTTY: boolean,\n previousFrameLines: number,\n): string {\n const frame = value.endsWith(\"\\n\") ? value : `${value}\\n`;\n if (isTTY) {\n return index === 0\n ? frame\n : `\\u001B[${previousFrameLines}A\\r\\u001B[0J${frame}`;\n }\n return index === 0 ? frame : `\\n---\\n\\n${frame}`;\n}\n\nfunction countFrameLines(value: string): number {\n const frame = value.endsWith(\"\\n\") ? value : `${value}\\n`;\n return frame.split(\"\\n\").length - 1;\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof DOMException && error.name === \"AbortError\";\n}\n\nfunction parseArguments(\n argv: readonly string[],\n command: CliCommand,\n invocationName: string,\n): Record<string, unknown> {\n const capability = command.capability;\n const positional = command.meta.positional ?? [];\n const commandName = `${invocationName} ${command.command.join(\" \")}`;\n const schema = capability.input;\n const properties = schema?.properties as\n | Record<string, JsonSchema>\n | undefined;\n const input: Record<string, unknown> = {};\n let position = 0;\n\n for (let index = 0; index < argv.length; index++) {\n const token = argv[index]!;\n if (token.startsWith(\"--\")) {\n const [rawName, inline] = token.slice(2).split(\"=\", 2);\n const name = camelCase(rawName!);\n const field = properties?.[name];\n if (!field || positional.includes(name)) {\n const suggestion = nearest(\n rawName!,\n Object.keys(properties ?? {})\n .filter((candidate) => !positional.includes(candidate))\n .map(kebabCase),\n );\n throw new CliUsageError([\n `Unknown option --${rawName}`,\n ...(suggestion ? [`Did you mean \\`--${suggestion}\\`?`] : []),\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n ].join(\"\\n\"));\n }\n const boolean = field.type === \"boolean\";\n const raw = inline ?? (boolean ? \"true\" : argv[++index]);\n if (raw === undefined) {\n throw new CliUsageError(\n `Option --${rawName} requires a value\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n input[name] = coerce(raw, field, `--${rawName}`, commandName);\n continue;\n }\n const name = positional[position++];\n if (!name) {\n throw new CliUsageError(\n `Unexpected argument \"${token}\"\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n const field = properties?.[name];\n if (!field) {\n throw new CliUsageError(\n `CLI positional field \"${name}\" is not present in the input schema`,\n );\n }\n input[name] = coerce(token, field, `<${name}>`, commandName);\n }\n\n const required = schema?.required as readonly string[] | undefined;\n for (const name of required ?? []) {\n if (!(name in input)) {\n const label = positional.includes(name)\n ? `positional argument <${name}>`\n : `required option --${kebabCase(name)}`;\n throw new CliUsageError(\n `Missing ${label}\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n }\n return input;\n}\n\nfunction coerce(\n value: string,\n schema: JsonSchema,\n label: string,\n commandName: string,\n): unknown {\n if (schema.type === \"boolean\") return value !== \"false\";\n if (schema.type === \"integer\" || schema.type === \"number\") {\n const number = Number(value);\n if (!Number.isFinite(number)) {\n throw new CliUsageError(\n `Expected a number for ${label}, received \"${value}\"\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n return number;\n }\n return value;\n}\n\nclass CliUsageError extends Error {}\n\nfunction renderRuntimeError(error: unknown): string {\n return error instanceof TransportError\n ? `${error.code}: ${error.message}`\n : error instanceof Error\n ? error.message\n : String(error);\n}\n\nfunction matchCommand(\n argv: readonly string[],\n commands: readonly CliCommand[],\n): CliCommand | undefined {\n return commands\n .filter((candidate) =>\n candidate.command.every((token, index) => argv[index] === token)\n )\n .sort((left, right) => right.command.length - left.command.length)[0];\n}\n\nfunction exactGroup(\n argv: readonly string[],\n groups: readonly CliCommandGroup[],\n): CliCommandGroup | undefined {\n return groups.find((group) =>\n group.command.length === argv.length &&\n group.command.every((token, index) => argv[index] === token)\n );\n}\n\nfunction unknownCommand(\n argv: readonly string[],\n commands: readonly CliCommand[],\n invocationName: string,\n): string {\n const entered = argv.join(\" \");\n const suggestion = nearest(\n entered,\n commands.map((command) => command.command.join(\" \")),\n );\n return [\n `Unknown command: ${entered}`,\n ...(suggestion ? [`Did you mean \\`${suggestion}\\`?`] : []),\n `Run \\`${invocationName} --help\\` to list available commands.`,\n ].join(\"\\n\");\n}\n\nfunction nearest(\n value: string,\n candidates: readonly string[],\n): string | undefined {\n let match: { readonly candidate: string; readonly distance: number } | undefined;\n for (const candidate of new Set(candidates)) {\n const distance = editDistance(value, candidate);\n if (!match || distance < match.distance) {\n match = { candidate, distance };\n }\n }\n if (!match) return undefined;\n return match.distance <= Math.max(2, Math.floor(match.candidate.length / 3))\n ? match.candidate\n : undefined;\n}\n\nfunction editDistance(left: string, right: string): number {\n const previous = Array.from(\n { length: right.length + 1 },\n (_, index) => index,\n );\n for (let leftIndex = 1; leftIndex <= left.length; leftIndex++) {\n const current = [leftIndex];\n for (let rightIndex = 1; rightIndex <= right.length; rightIndex++) {\n current[rightIndex] = Math.min(\n current[rightIndex - 1]! + 1,\n previous[rightIndex]! + 1,\n previous[rightIndex - 1]! +\n (left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1),\n );\n }\n previous.splice(0, previous.length, ...current);\n }\n return previous[right.length]!;\n}\n\nfunction camelCase(value: string): string {\n return value.replace(/-([a-z])/g, (_, character: string) =>\n character.toUpperCase()\n );\n}\n\nfunction kebabCase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);\n}\n"],"mappings":";;;AA2BA,SAAgB,gBACd,OACA,SAA4B,CAAC,GACV;CACnB,MAAM,WAAyB,CAAC;CAChC,MAAM,SAA4B,CAAC;CAEnC,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,KAAK,SAAS,SAAS;GACz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