capable-kit 0.0.1-alpha.3 → 0.0.1-alpha.5
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 +21 -3
- 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 +17 -16
- package/dist/bin.mjs.map +1 -1
- package/dist/cli.d.mts +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/core.d.mts +3 -3
- package/dist/core.mjs +2 -2
- 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-BB5ogMv-.d.mts → index-Be8-UVBC.d.mts} +49 -8
- package/dist/{index-B2ru1zGQ.d.mts → index-D2CRRUzH.d.mts} +6 -6
- package/dist/{index-B_I9n6gN.d.mts → index-Dbc4g9WM.d.mts} +4 -3
- package/dist/{index-AqKbVZ8Z.d.mts → index-DwXlaTXI.d.mts} +4 -4
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +3 -3
- package/dist/mcp.d.mts +2 -2
- package/dist/mcp.mjs +1 -1
- package/dist/{mount--YHrgRHJ.mjs → mount-xvMsjz1B.mjs} +65 -27
- package/dist/mount-xvMsjz1B.mjs.map +1 -0
- package/dist/runtime-support.d.mts +1 -1
- package/dist/runtime-support.mjs +6 -6
- package/dist/runtime-support.mjs.map +1 -1
- package/dist/server.d.mts +2 -2
- package/dist/server.mjs +2 -2
- package/dist/{src-DX2xrplP.mjs → src-BF70JLxI.mjs} +24 -13
- package/dist/src-BF70JLxI.mjs.map +1 -0
- package/dist/{src-3UaBqI8H.mjs → src-C2MGIlT0.mjs} +17 -18
- package/dist/src-C2MGIlT0.mjs.map +1 -0
- package/dist/{src-DtSY5fzY.mjs → src-CDxL6w3d.mjs} +7 -7
- package/dist/{src-DtSY5fzY.mjs.map → src-CDxL6w3d.mjs.map} +1 -1
- package/dist/{src-BjBxOv7x.mjs → src-Db6-XSnU.mjs} +20 -12
- package/dist/src-Db6-XSnU.mjs.map +1 -0
- package/dist/{src-B53ZbNtC.mjs → src-DdV82An-.mjs} +137 -3
- package/dist/src-DdV82An-.mjs.map +1 -0
- package/dist/{subscription-McaLyHM2.d.mts → subscription-Bq792Ad2.d.mts} +2 -2
- package/docs/CONTEXT.md +113 -0
- package/docs/README.md +28 -0
- package/docs/internal/README.md +16 -0
- package/docs/internal/adr/0001-capability-is-the-semantic-boundary.md +24 -0
- package/docs/internal/architecture.md +134 -0
- package/docs/internal/capability-first-model.md +160 -0
- package/docs/internal/implementation-friction.md +705 -0
- package/docs/internal/why-capable.md +94 -0
- package/docs/site/capable-orpc-and-trpc.mdx +133 -0
- package/docs/site/concepts/apps.mdx +217 -0
- package/docs/site/concepts/architecture.mdx +83 -0
- package/docs/site/concepts/capabilities.mdx +249 -0
- package/docs/site/concepts/errors.mdx +93 -0
- package/docs/site/concepts/presentations.mdx +161 -0
- package/docs/site/hosting/any-fetch-host.mdx +74 -0
- package/docs/site/hosting/next-js.mdx +77 -0
- package/docs/site/hosting/standalone-server.mdx +94 -0
- package/docs/site/introduction.mdx +259 -0
- package/docs/site/patterns/composition.mdx +142 -0
- package/docs/site/patterns/remote-apps.mdx +117 -0
- package/docs/site/patterns/subscriptions.mdx +87 -0
- package/docs/site/quickstart.mdx +386 -0
- package/docs/site/reference/packages-and-entry-points.mdx +72 -0
- package/docs/site/reference/surface-metadata.mdx +84 -0
- package/docs/site/reference/the-cap-cli.mdx +81 -0
- package/docs/site/surfaces/ai-sdk.mdx +94 -0
- package/docs/site/surfaces/cli.mdx +138 -0
- package/docs/site/surfaces/eve.mdx +121 -0
- package/docs/site/surfaces/http-and-openapi.mdx +111 -0
- package/docs/site/surfaces/mcp.mdx +110 -0
- package/docs/site/surfaces/react-query.mdx +80 -0
- package/docs/site/surfaces/typescript.mdx +123 -0
- package/docs/site/surfaces.mdx +78 -0
- package/docs/site/why-capable.mdx +99 -0
- package/package.json +13 -3
- package/src/index.test.ts +1 -0
- package/src/index.ts +5 -1
- package/src/package.test.ts +102 -0
- package/dist/mount--YHrgRHJ.mjs.map +0 -1
- package/dist/src-3UaBqI8H.mjs.map +0 -1
- package/dist/src-B53ZbNtC.mjs.map +0 -1
- package/dist/src-BjBxOv7x.mjs.map +0 -1
- package/dist/src-DX2xrplP.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { h as schemaToJsonSchema, l as executeLocatedCapability,
|
|
2
|
-
import { a as TransportError, c as getAppRuntime, l as isApp } from "./src-
|
|
1
|
+
import { _ as normalizePresentation, h as schemaToJsonSchema, l as executeLocatedCapability, x as CapableError, y as renderPresentationMarkdown } from "./src-DdV82An-.mjs";
|
|
2
|
+
import { a as TransportError, c as getAppRuntime, l as isApp } from "./src-C2MGIlT0.mjs";
|
|
3
3
|
//#region packages/fetch/src/error-response.ts
|
|
4
4
|
function capabilityErrorData(error, fallbackStatus = 500) {
|
|
5
5
|
const capable = error instanceof CapableError || error instanceof TransportError ? error : new CapableError("INTERNAL_SERVER_ERROR", { cause: error });
|
|
@@ -18,7 +18,7 @@ function capabilityErrorResponse(error, fallbackStatus = 500) {
|
|
|
18
18
|
}, { status: data.status });
|
|
19
19
|
}
|
|
20
20
|
//#endregion
|
|
21
|
-
//#region packages/fetch/src/
|
|
21
|
+
//#region packages/fetch/src/capable.ts
|
|
22
22
|
function createProtocolHandler(application, options = {}) {
|
|
23
23
|
const basePath = normalizePath$1(options.basePath ?? "/_capable");
|
|
24
24
|
const fetch = async (request) => {
|
|
@@ -35,6 +35,7 @@ function createProtocolHandler(application, options = {}) {
|
|
|
35
35
|
stream = runtime.subscribe({
|
|
36
36
|
id,
|
|
37
37
|
input: body.input ?? {},
|
|
38
|
+
...body.presentation ? { presentation: true } : {},
|
|
38
39
|
signal: AbortSignal.any([request.signal, controller.signal])
|
|
39
40
|
});
|
|
40
41
|
const first = await stream.next();
|
|
@@ -53,6 +54,7 @@ function createProtocolHandler(application, options = {}) {
|
|
|
53
54
|
const result = await runtime.call({
|
|
54
55
|
id,
|
|
55
56
|
input: body.input ?? {},
|
|
57
|
+
...body.presentation ? { presentation: true } : {},
|
|
56
58
|
signal: request.signal
|
|
57
59
|
});
|
|
58
60
|
return Response.json({
|
|
@@ -86,27 +88,33 @@ function createHttpTransport(options) {
|
|
|
86
88
|
if (!response.ok) throw await responseError(response);
|
|
87
89
|
return await responseJson(response, "Application manifest");
|
|
88
90
|
},
|
|
89
|
-
async call({ id, input = {}, signal }) {
|
|
91
|
+
async call({ id, input = {}, signal, presentation }) {
|
|
90
92
|
const body = await (await request(`call/${encodeURIComponent(id)}`, {
|
|
91
93
|
method: "POST",
|
|
92
94
|
headers: { "content-type": "application/json" },
|
|
93
|
-
body: JSON.stringify({
|
|
95
|
+
body: JSON.stringify({
|
|
96
|
+
input,
|
|
97
|
+
...presentation ? { presentation } : {}
|
|
98
|
+
}),
|
|
94
99
|
...signal ? { signal } : {}
|
|
95
100
|
})).json();
|
|
96
101
|
if (!body.ok) throw new TransportError(body.error.code, body.error);
|
|
97
102
|
return {
|
|
98
103
|
output: body.output,
|
|
99
|
-
...body.
|
|
104
|
+
...body.presentation ? { presentation: body.presentation } : {}
|
|
100
105
|
};
|
|
101
106
|
},
|
|
102
|
-
async *subscribe({ id, input = {}, signal }) {
|
|
107
|
+
async *subscribe({ id, input = {}, signal, presentation }) {
|
|
103
108
|
const response = await request(`subscribe/${encodeURIComponent(id)}`, {
|
|
104
109
|
method: "POST",
|
|
105
110
|
headers: {
|
|
106
111
|
accept: "text/event-stream",
|
|
107
112
|
"content-type": "application/json"
|
|
108
113
|
},
|
|
109
|
-
body: JSON.stringify({
|
|
114
|
+
body: JSON.stringify({
|
|
115
|
+
input,
|
|
116
|
+
...presentation ? { presentation } : {}
|
|
117
|
+
}),
|
|
110
118
|
...signal ? { signal } : {}
|
|
111
119
|
});
|
|
112
120
|
if (!response.ok) throw await responseError(response);
|
|
@@ -291,10 +299,13 @@ function createHttpHandler(app, options = {}) {
|
|
|
291
299
|
context,
|
|
292
300
|
signal: request.signal
|
|
293
301
|
});
|
|
294
|
-
if (request.headers.get("accept")?.includes("text/markdown") && match.route.capability.capability.
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
302
|
+
if (request.headers.get("accept")?.includes("text/markdown") && match.route.capability.capability.toPresentation) {
|
|
303
|
+
const presentation = normalizePresentation(await match.route.capability.capability.toPresentation(output, { context }));
|
|
304
|
+
if (presentation.length > 0) return new Response(renderPresentationMarkdown(presentation), {
|
|
305
|
+
status: httpSuccessStatus(match.route.capability),
|
|
306
|
+
headers: { "content-type": "text/markdown; charset=utf-8" }
|
|
307
|
+
});
|
|
308
|
+
}
|
|
298
309
|
return Response.json(output, { status: httpSuccessStatus(match.route.capability) });
|
|
299
310
|
} catch (error) {
|
|
300
311
|
return capabilityErrorResponse(error);
|
|
@@ -454,4 +465,4 @@ function joinPath(...parts) {
|
|
|
454
465
|
//#endregion
|
|
455
466
|
export { createHttpTransport as n, createProtocolHandler as r, createHttpHandler as t };
|
|
456
467
|
|
|
457
|
-
//# sourceMappingURL=src-
|
|
468
|
+
//# sourceMappingURL=src-BF70JLxI.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-BF70JLxI.mjs","names":["normalizePath"],"sources":["../../fetch/src/error-response.ts","../../fetch/src/capable.ts","../../fetch/src/http.ts"],"sourcesContent":["import { CapableError } from \"@capable/core\";\nimport { TransportError } from \"@capable/app\";\n\nexport type CapabilityErrorData = {\n readonly code: string;\n readonly message: string;\n readonly status: number;\n readonly data?: unknown;\n};\n\nexport function capabilityErrorData(\n error: unknown,\n fallbackStatus = 500,\n): CapabilityErrorData {\n const capable = error instanceof CapableError || error instanceof TransportError\n ? error\n : new CapableError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n return {\n code: capable.code,\n message: capable.message,\n status: capable.status ?? fallbackStatus,\n ...(capable.data === undefined ? {} : { data: capable.data }),\n };\n}\n\nexport function capabilityErrorResponse(\n error: unknown,\n fallbackStatus = 500,\n): Response {\n const data = capabilityErrorData(error, fallbackStatus);\n return Response.json({\n ok: false,\n error: data,\n }, { status: data.status });\n}\n","import {\n getAppRuntime,\n isApp,\n TransportError,\n type ApplicationManifest,\n type ApplicationTransport,\n type AnyApp,\n type CapabilityCall,\n type CapabilityResult,\n} from \"@capable/app\";\nimport type { PresentationPart } from \"@capable/core\";\nimport {\n capabilityErrorData,\n capabilityErrorResponse,\n} from \"./error-response.ts\";\n\nexport type FetchHandler = (request: Request) => Response | Promise<Response>;\n\nexport function createProtocolHandler(\n application:\n | AnyApp\n | ((request: Request) => AnyApp | Promise<AnyApp>),\n options: {\n readonly basePath?: string;\n } = {},\n): {\n readonly fetch: FetchHandler;\n} {\n const basePath = normalizePath(options.basePath ?? \"/_capable\");\n\n const fetch: FetchHandler = async (request) => {\n const url = new URL(request.url);\n const app = isApp(application)\n ? application\n : await application(request);\n const runtime = getAppRuntime(app);\n if (url.pathname === `${basePath}/manifest` && request.method === \"GET\") {\n return Response.json(await runtime.manifest());\n }\n const subscribePrefix = `${basePath}/subscribe/`;\n if (\n url.pathname.startsWith(subscribePrefix) &&\n request.method === \"POST\"\n ) {\n const id = decodeURIComponent(\n url.pathname.slice(subscribePrefix.length),\n );\n const controller = new AbortController();\n let stream: AsyncIterableIterator<CapabilityResult> | undefined;\n try {\n const body = await request.json() as {\n readonly input?: unknown;\n readonly presentation?: boolean;\n };\n stream = runtime.subscribe({\n id,\n input: body.input ?? {},\n ...(body.presentation ? { presentation: true } : {}),\n signal: AbortSignal.any([request.signal, controller.signal]),\n });\n const first = await stream.next();\n return subscriptionResponse(stream, first, controller);\n } catch (error) {\n controller.abort();\n await stream?.return?.().catch(() => undefined);\n return capabilityErrorResponse(error);\n }\n }\n const callPrefix = `${basePath}/call/`;\n if (!url.pathname.startsWith(callPrefix) || request.method !== \"POST\") {\n return new Response(\"Not Found\", { status: 404 });\n }\n const id = decodeURIComponent(url.pathname.slice(callPrefix.length));\n try {\n const body = await request.json() as {\n readonly input?: unknown;\n readonly presentation?: boolean;\n };\n const result = await runtime.call({\n id,\n input: body.input ?? {},\n ...(body.presentation ? { presentation: true } : {}),\n signal: request.signal,\n });\n return Response.json({\n ok: true,\n ...result,\n });\n } catch (error) {\n return capabilityErrorResponse(error);\n }\n };\n\n return { fetch };\n}\n\nexport type TransportHeaders =\n | HeadersInit\n | (() => HeadersInit | Promise<HeadersInit>);\n\nexport function createHttpTransport(options: {\n readonly url: string | URL | (() => string | URL);\n readonly fetch?: (request: Request) => Response | Promise<Response>;\n readonly headers?: TransportHeaders;\n}): ApplicationTransport {\n const fetchImplementation = options.fetch ?? globalThis.fetch;\n\n async function request(\n path: string,\n init: RequestInit,\n ): Promise<Response> {\n const base = normalizeUrl(\n typeof options.url === \"function\" ? options.url() : options.url,\n );\n const configured = typeof options.headers === \"function\"\n ? await options.headers()\n : options.headers;\n const headers = new Headers(configured);\n new Headers(init.headers).forEach((value, name) => headers.set(name, value));\n return fetchImplementation(\n new Request(new URL(path, base), { ...init, headers }),\n );\n }\n\n return Object.freeze({\n async manifest(\n { signal }: { readonly signal?: AbortSignal } = {},\n ) {\n const response = await request(\"manifest\", {\n method: \"GET\",\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) throw await responseError(response);\n return await responseJson<ApplicationManifest>(\n response,\n \"Application manifest\",\n );\n },\n async call({\n id,\n input = {},\n signal,\n presentation,\n }: CapabilityCall) {\n const response = await request(`call/${encodeURIComponent(id)}`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ input, ...(presentation ? { presentation } : {}) }),\n ...(signal ? { signal } : {}),\n });\n const body = await response.json() as\n | {\n readonly ok: true;\n readonly output: unknown;\n readonly presentation?: readonly PresentationPart[];\n }\n | {\n readonly ok: false;\n readonly error: {\n readonly code: string;\n readonly message?: string;\n readonly status?: number;\n readonly data?: unknown;\n };\n };\n if (!body.ok) {\n throw new TransportError(body.error.code, body.error);\n }\n return {\n output: body.output,\n ...(body.presentation ? { presentation: body.presentation } : {}),\n };\n },\n async *subscribe({\n id,\n input = {},\n signal,\n presentation,\n }: CapabilityCall) {\n const response = await request(`subscribe/${encodeURIComponent(id)}`, {\n method: \"POST\",\n headers: {\n accept: \"text/event-stream\",\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({ input, ...(presentation ? { presentation } : {}) }),\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) throw await responseError(response);\n yield* decodeEventStream(response);\n },\n });\n}\n\nfunction subscriptionResponse(\n stream: AsyncIterableIterator<CapabilityResult>,\n first: IteratorResult<CapabilityResult>,\n subscriptionController: AbortController,\n): Response {\n const encoder = new TextEncoder();\n let initial: IteratorResult<CapabilityResult> | undefined = first;\n\n return new Response(new ReadableStream({\n async pull(controller) {\n try {\n const result = initial ?? await stream.next();\n initial = undefined;\n if (result.done) {\n subscriptionController.abort();\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(sseFrame(\"output\", result.value)));\n } catch (error) {\n subscriptionController.abort();\n controller.enqueue(encoder.encode(\n sseFrame(\"error\", capabilityErrorData(error)),\n ));\n controller.close();\n await stream.return?.();\n }\n },\n async cancel() {\n subscriptionController.abort();\n await stream.return?.();\n },\n }, {\n highWaterMark: 0,\n }), {\n headers: {\n \"cache-control\": \"no-cache\",\n \"content-type\": \"text/event-stream; charset=utf-8\",\n },\n });\n}\n\nasync function* decodeEventStream(\n response: Response,\n): AsyncIterableIterator<CapabilityResult> {\n if (!response.headers.get(\"content-type\")?.includes(\"text/event-stream\")) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: \"Subscription response is not an event stream\",\n });\n }\n if (!response.body) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: \"Subscription response has no body\",\n });\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n try {\n while (true) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value, { stream: !done });\n let boundary = eventBoundary(buffer);\n while (boundary) {\n const block = buffer.slice(0, boundary.index);\n buffer = buffer.slice(boundary.index + boundary.length);\n const event = parseEventBlock(block);\n if (event) {\n if (event.type === \"error\") {\n throw new TransportError(event.error.code, event.error);\n }\n yield event.result;\n }\n boundary = eventBoundary(buffer);\n }\n if (done) break;\n }\n } finally {\n await reader.cancel().catch(() => undefined);\n }\n}\n\nfunction eventBoundary(\n value: string,\n): { readonly index: number; readonly length: number } | undefined {\n const lf = value.indexOf(\"\\n\\n\");\n const crlf = value.indexOf(\"\\r\\n\\r\\n\");\n if (lf < 0 && crlf < 0) {\n return undefined;\n }\n if (crlf >= 0 && (lf < 0 || crlf < lf)) {\n return { index: crlf, length: 4 };\n }\n return { index: lf, length: 2 };\n}\n\nfunction parseEventBlock(block: string):\n | { readonly type: \"output\"; readonly result: CapabilityResult }\n | {\n readonly type: \"error\";\n readonly error: {\n readonly code: string;\n readonly message?: string;\n readonly status?: number;\n readonly data?: unknown;\n };\n }\n | undefined {\n let type = \"message\";\n const data: string[] = [];\n for (const line of block.replace(/\\r\\n/g, \"\\n\").split(\"\\n\")) {\n if (line.startsWith(\":\")) continue;\n if (line.startsWith(\"event:\")) type = line.slice(6).trim();\n if (line.startsWith(\"data:\")) data.push(line.slice(5).trimStart());\n }\n if (!data.length) return undefined;\n const value = JSON.parse(data.join(\"\\n\")) as any;\n return type === \"error\"\n ? { type: \"error\", error: value }\n : { type: \"output\", result: value };\n}\n\nfunction sseFrame(event: string, data: unknown): string {\n return `event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`;\n}\n\nfunction normalizeUrl(value: string | URL): URL {\n const url = new URL(value);\n if (!url.pathname.endsWith(\"/\")) url.pathname += \"/\";\n url.search = \"\";\n url.hash = \"\";\n return url;\n}\n\nasync function responseError(response: Response): Promise<TransportError> {\n const text = await response.text().catch(() => \"\");\n let data: unknown = text;\n try {\n data = JSON.parse(text);\n } catch {\n // Preserve the response text as transport diagnostics.\n }\n if (\n data &&\n typeof data === \"object\" &&\n \"ok\" in data &&\n data.ok === false &&\n \"error\" in data &&\n data.error &&\n typeof data.error === \"object\" &&\n \"code\" in data.error &&\n typeof data.error.code === \"string\"\n ) {\n const error = data.error as {\n readonly code: string;\n readonly message?: unknown;\n readonly status?: unknown;\n readonly data?: unknown;\n };\n return new TransportError(error.code, {\n ...(typeof error.message === \"string\"\n ? { message: error.message }\n : {}),\n status: typeof error.status === \"number\"\n ? error.status\n : response.status,\n ...(\"data\" in error ? { data: error.data } : {}),\n });\n }\n return new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: `Transport request failed with ${response.status}`,\n data,\n });\n}\n\nasync function responseJson<T>(\n response: Response,\n label: string,\n): Promise<T> {\n const contentType = response.headers.get(\"content-type\");\n if (!contentType?.toLowerCase().includes(\"json\")) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message:\n `${label} request returned ${contentType ?? \"a non-JSON response\"}${\n response.url ? ` from ${response.url}` : \"\"\n }`,\n });\n }\n try {\n return await response.json() as T;\n } catch (cause) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: `${label} response contained invalid JSON`,\n cause,\n });\n }\n}\n\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n","import {\n executeLocatedCapability,\n normalizePresentation,\n renderPresentationMarkdown,\n schemaToJsonSchema,\n type AppDefinition,\n type GroupMetaRegistry,\n type LocatedCapability,\n type CapabilityMetaRegistry,\n type CapabilityTree,\n} from \"@capable/core\";\nimport {\n type ApplicationSelection,\n type JsonSchema,\n} from \"@capable/app\";\nimport {\n capabilityErrorResponse,\n} from \"./error-response.ts\";\nimport type { FetchHandler } from \"./capable.ts\";\n\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\nexport type HttpCapabilityMeta =\n | false\n | {\n readonly method?: HttpMethod;\n readonly route?: string;\n readonly status?: number;\n };\n\nexport type HttpGroupMeta = {\n readonly prefix?: string;\n};\n\ndeclare module \"@capable/core\" {\n interface CapabilityMetaRegistry {\n readonly http?: HttpCapabilityMeta;\n }\n\n interface GroupMetaRegistry {\n readonly http?: HttpGroupMeta;\n }\n}\n\nexport type ContextProvider<TContext> = (args: {\n readonly request: Request;\n}) => TContext | Promise<TContext>;\n\nexport type CapabilitySelection<\n TTree extends CapabilityTree = CapabilityTree,\n> = ApplicationSelection<TTree>;\n\nexport type CompiledHttpRoute = {\n readonly method: HttpMethod;\n readonly path: string;\n readonly capability: LocatedCapability;\n};\n\nexport function createHttpHandler<\n const TCapabilities extends CapabilityTree,\n TContext,\n>(\n app: AppDefinition<TCapabilities, TContext>,\n options: {\n readonly context?: ContextProvider<TContext>;\n readonly basePath?: string;\n readonly openapiPath?: string | false;\n readonly requireExplicitRoutes?: boolean;\n readonly selection?: CapabilitySelection<TCapabilities>;\n } = {},\n): {\n readonly fetch: FetchHandler;\n readonly routes: readonly CompiledHttpRoute[];\n readonly openapi: Readonly<Record<string, unknown>>;\n} {\n const basePath = normalizePath(options.basePath ?? \"/api\");\n const selected = selectCapabilities(app.locatedCapabilities, options.selection)\n .filter((entry) => capabilityHttp(entry) !== false);\n const routes = selected.map((entry) => compileHttpRoute(entry, basePath));\n assertUniqueRoutes(routes);\n if (options.requireExplicitRoutes) {\n const implicit = selected.find((entry) => {\n const meta = capabilityHttp(entry);\n return !meta || !meta.method || !meta.route;\n });\n if (implicit) {\n throw new Error(\n `Capability \"${implicit.capability.id}\" requires an explicit HTTP method and route`,\n );\n }\n }\n const openapi = createOpenApi(app, routes);\n const openapiPath = options.openapiPath === false\n ? undefined\n : normalizePath(options.openapiPath ?? \"/openapi.json\");\n\n return {\n routes,\n openapi,\n async fetch(request) {\n const url = new URL(request.url);\n if (\n openapiPath &&\n url.pathname === openapiPath &&\n request.method === \"GET\"\n ) {\n return Response.json(openapi);\n }\n const match = routes\n .map((route) => ({ route, params: matchPath(route.path, url.pathname) }))\n .find(({ route, params }) => route.method === request.method && params);\n if (!match?.params) return new Response(\"Not Found\", { status: 404 });\n\n try {\n const input = await readHttpInput(\n request,\n match.params,\n match.route.capability.capability.input,\n );\n const context = options.context\n ? await options.context({ request })\n : undefined as TContext;\n const output = await executeLocatedCapability(match.route.capability, input, {\n context,\n signal: request.signal,\n });\n if (\n request.headers.get(\"accept\")?.includes(\"text/markdown\") &&\n match.route.capability.capability.toPresentation\n ) {\n const presentation = normalizePresentation(\n await match.route.capability.capability.toPresentation(output, {\n context,\n }),\n );\n if (presentation.length > 0) {\n return new Response(\n renderPresentationMarkdown(presentation),\n {\n status: httpSuccessStatus(match.route.capability),\n headers: { \"content-type\": \"text/markdown; charset=utf-8\" },\n },\n );\n }\n }\n return Response.json(output, {\n status: httpSuccessStatus(match.route.capability),\n });\n } catch (error) {\n return capabilityErrorResponse(error);\n }\n },\n };\n}\n\nfunction compileHttpRoute(\n entry: LocatedCapability,\n basePath: string,\n): CompiledHttpRoute {\n const meta = capabilityHttp(entry);\n const defaultPath = entry.path.flatMap((segment, index) => {\n const groupIndex = entry.groupPaths.findIndex(\n (path) => path.length === index + 1,\n );\n const prefix = groupIndex >= 0\n ? (entry.groups[groupIndex]?.meta.http as HttpGroupMeta | undefined)\n ?.prefix\n : undefined;\n return prefix ? prefix.split(\"/\").filter(Boolean) : [segment];\n }).join(\"/\");\n const groupPrefix = entry.groups.flatMap((group) => {\n const prefix = (group.meta.http as HttpGroupMeta | undefined)?.prefix;\n return prefix ? prefix.split(\"/\").filter(Boolean) : [];\n }).join(\"/\");\n const authoredRoute = meta && meta.route ? meta.route : defaultPath;\n assertPathParameters(entry, authoredRoute);\n return Object.freeze({\n method: meta && meta.method\n ? meta.method\n : entry.capability.effect === \"read\"\n ? \"GET\"\n : \"POST\",\n path: joinPath(\n basePath,\n meta && meta.route ? groupPrefix : \"\",\n authoredRoute,\n ),\n capability: entry,\n });\n}\n\nfunction capabilityHttp(entry: LocatedCapability): HttpCapabilityMeta | undefined {\n return entry.capability.meta.http as HttpCapabilityMeta | undefined;\n}\n\nfunction httpSuccessStatus(entry: LocatedCapability): number {\n const meta = capabilityHttp(entry);\n return meta && typeof meta.status === \"number\" ? meta.status : 200;\n}\n\nasync function readHttpInput(\n request: Request,\n params: Record<string, string>,\n schema: LocatedCapability[\"capability\"][\"input\"],\n): Promise<Record<string, unknown>> {\n const url = new URL(request.url);\n const jsonSchema = schema\n ? schemaToJsonSchema(schema, \"input\")\n : undefined;\n const properties = jsonSchema?.properties as\n | Record<string, Readonly<Record<string, unknown>>>\n | undefined;\n const coerceEntries = (entries: Iterable<readonly [string, string]>) =>\n Object.fromEntries(\n [...entries].map(([key, value]) => [\n key,\n coerceHttpValue(value, properties?.[key]),\n ]),\n );\n const rest: Record<string, unknown> =\n request.method === \"GET\"\n ? coerceEntries(url.searchParams)\n : request.headers.get(\"content-type\")?.includes(\"application/json\")\n ? await request.json() as Record<string, unknown>\n : {};\n return {\n ...rest,\n ...coerceEntries(Object.entries(params)),\n };\n}\n\nfunction coerceHttpValue(\n value: string,\n schema: Readonly<Record<string, unknown>> | undefined,\n): unknown {\n if (schema?.type === \"boolean\") return value === \"true\"\n ? true\n : value === \"false\"\n ? false\n : value;\n if (schema?.type === \"integer\" || schema?.type === \"number\") {\n const number = Number(value);\n return Number.isFinite(number) ? number : value;\n }\n return value;\n}\n\nfunction assertPathParameters(\n entry: LocatedCapability,\n path: string,\n): void {\n const parameters = [...path.matchAll(/:([^/]+)/g)].map((match) => match[1]!);\n if (parameters.length === 0) return;\n const schema = entry.capability.input\n ? schemaToJsonSchema(entry.capability.input, \"input\")\n : undefined;\n const properties = schema?.properties as\n | Record<string, unknown>\n | undefined;\n for (const parameter of parameters) {\n if (!properties?.[parameter]) {\n throw new Error(\n `HTTP path parameter \":${parameter}\" is not present in Capability \"${entry.capability.id}\" input`,\n );\n }\n }\n}\n\nfunction matchPath(\n pattern: string,\n pathname: string,\n): Record<string, string> | undefined {\n const expected = pattern.split(\"/\").filter(Boolean);\n const actual = pathname.split(\"/\").filter(Boolean);\n if (expected.length !== actual.length) return undefined;\n const params: Record<string, string> = {};\n for (let index = 0; index < expected.length; index++) {\n const token = expected[index]!;\n const value = actual[index]!;\n if (token.startsWith(\":\")) params[token.slice(1)] = decodeURIComponent(value);\n else if (token !== value) return undefined;\n }\n return params;\n}\n\nfunction createOpenApi(\n app: AppDefinition<any, any>,\n routes: readonly CompiledHttpRoute[],\n): Readonly<Record<string, unknown>> {\n const paths: Record<string, unknown> = {};\n for (const route of routes) {\n const method = route.method.toLowerCase();\n const path = route.path.replace(/:([^/]+)/g, \"{$1}\");\n const capability = route.capability.capability;\n const input = capability.input\n ? schemaToJsonSchema(capability.input, \"input\")\n : undefined;\n const properties = (input?.properties ?? {}) as Record<string, JsonSchema>;\n const required = new Set((input?.required ?? []) as readonly string[]);\n const pathNames = new Set(\n [...route.path.matchAll(/:([^/]+)/g)].map((match) => match[1]!),\n );\n const parameters = [...pathNames].map((name) => ({\n name,\n in: \"path\",\n required: true,\n schema: properties[name] ?? {},\n }));\n const remaining = Object.fromEntries(\n Object.entries(properties).filter(([name]) => !pathNames.has(name)),\n );\n if (route.method === \"GET\") {\n parameters.push(\n ...Object.entries(remaining).map(([name, schema]) => ({\n name,\n in: \"query\",\n required: required.has(name),\n schema,\n })),\n );\n }\n const responses: Record<string, unknown> = {\n [String(httpSuccessStatus(route.capability))]: {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: capability.output\n ? schemaToJsonSchema(capability.output, \"output\")\n : {},\n },\n },\n },\n };\n for (const [code, error] of Object.entries(route.capability.errors)) {\n const status = typeof error.status === \"number\"\n ? String(error.status)\n : \"default\";\n responses[status] ??= {\n description: error.message ?? code,\n };\n }\n const current = paths[path] as Record<string, unknown> | undefined ?? {};\n current[method] = {\n capabilityId: capability.id,\n ...(capability.title ? { summary: capability.title } : {}),\n ...(capability.description ? { description: capability.description } : {}),\n ...(parameters.length ? { parameters } : {}),\n ...(route.method !== \"GET\" && Object.keys(remaining).length\n ? {\n requestBody: {\n required: [...required].some((name) => !pathNames.has(name)),\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: remaining,\n required: [...required].filter((name) =>\n !pathNames.has(name)\n ),\n },\n },\n },\n },\n }\n : {}),\n responses,\n };\n paths[path] = current;\n }\n return {\n openapi: \"3.1.0\",\n info: { title: app.name, version: app.version },\n paths,\n };\n}\n\nfunction selectCapabilities(\n capabilities: readonly LocatedCapability[],\n selection: CapabilitySelection | undefined,\n): readonly LocatedCapability[] {\n return capabilities.filter((entry) => {\n const included = selection?.include\n ? matchesTree(selection.include, entry.path)\n : true;\n return included && !matchesTree(selection?.exclude, entry.path);\n });\n}\n\nfunction matchesTree(\n tree: Readonly<Record<string, unknown>> | undefined,\n path: readonly string[],\n): boolean {\n if (!tree) return false;\n let current: unknown = tree;\n for (const segment of path) {\n if (current === true) return true;\n if (!current || typeof current !== \"object\" || Array.isArray(current)) {\n return false;\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return current === true || (\n Boolean(current) && typeof current === \"object\" && !Array.isArray(current)\n );\n}\n\nfunction assertUniqueRoutes(routes: readonly CompiledHttpRoute[]): void {\n const seen = new Set<string>();\n for (const route of routes) {\n const identity = `${route.method} ${route.path}`;\n if (seen.has(identity)) throw new Error(`Duplicate HTTP route ${identity}`);\n seen.add(identity);\n }\n}\n\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n\nfunction joinPath(...parts: readonly string[]): string {\n return normalizePath(parts.join(\"/\"));\n}\n"],"mappings":";;;AAUA,SAAgB,oBACd,OACA,iBAAiB,KACI;CACrB,MAAM,UAAU,iBAAiB,gBAAgB,iBAAiB,iBAC9D,QACA,IAAI,aAAa,yBAAyB,EAAE,OAAO,MAAM,CAAC;CAC9D,OAAO;EACL,MAAM,QAAQ;EACd,SAAS,QAAQ;EACjB,QAAQ,QAAQ,UAAU;EAC1B,GAAI,QAAQ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a as isCapabilityGroup, f as subscribeLocatedCapability, h as schemaToJsonSchema, l as executeLocatedCapability, u as isCapability,
|
|
1
|
+
import { _ as normalizePresentation, a as isCapabilityGroup, f as subscribeLocatedCapability, h as schemaToJsonSchema, l as executeLocatedCapability, u as isCapability, x as CapableError } from "./src-DdV82An-.mjs";
|
|
2
2
|
//#region packages/app/src/manifest.ts
|
|
3
3
|
function createAppManifest(definition) {
|
|
4
4
|
const byCapability = new Map(definition.locatedCapabilities.map((entry) => [entry.capability, entry]));
|
|
@@ -278,7 +278,7 @@ function createApp(definition, ...[options]) {
|
|
|
278
278
|
async manifest() {
|
|
279
279
|
return manifest;
|
|
280
280
|
},
|
|
281
|
-
async call({ id, input = {}, signal }) {
|
|
281
|
+
async call({ id, input = {}, signal, presentation: wantsPresentation }) {
|
|
282
282
|
const located = byId.get(id);
|
|
283
283
|
if (!located) throw new TransportError("NOT_FOUND", { status: 404 });
|
|
284
284
|
let context;
|
|
@@ -305,18 +305,13 @@ function createApp(definition, ...[options]) {
|
|
|
305
305
|
});
|
|
306
306
|
throw new TransportError("INTERNAL_SERVER_ERROR", { cause: error });
|
|
307
307
|
}
|
|
308
|
-
|
|
309
|
-
try {
|
|
310
|
-
markdown = located.capability.toMarkdown ? await located.capability.toMarkdown(output, { context }) : void 0;
|
|
311
|
-
} catch (cause) {
|
|
312
|
-
throw new TransportError("INTERNAL_SERVER_ERROR", { cause });
|
|
313
|
-
}
|
|
308
|
+
const presentation = await materializePresentation(located.capability, output, context, wantsPresentation);
|
|
314
309
|
return {
|
|
315
310
|
output,
|
|
316
|
-
...
|
|
311
|
+
...presentation ? { presentation } : {}
|
|
317
312
|
};
|
|
318
313
|
},
|
|
319
|
-
async *subscribe({ id, input = {}, signal }) {
|
|
314
|
+
async *subscribe({ id, input = {}, signal, presentation: wantsPresentation }) {
|
|
320
315
|
const located = byId.get(id);
|
|
321
316
|
if (!located) throw new TransportError("NOT_FOUND", { status: 404 });
|
|
322
317
|
if (!located.capability.subscribe) throw new TransportError("NOT_FOUND", { status: 404 });
|
|
@@ -335,15 +330,10 @@ function createApp(definition, ...[options]) {
|
|
|
335
330
|
});
|
|
336
331
|
try {
|
|
337
332
|
for await (const output of stream) {
|
|
338
|
-
|
|
339
|
-
try {
|
|
340
|
-
markdown = located.capability.toMarkdown ? await located.capability.toMarkdown(output, { context }) : void 0;
|
|
341
|
-
} catch (cause) {
|
|
342
|
-
throw new TransportError("INTERNAL_SERVER_ERROR", { cause });
|
|
343
|
-
}
|
|
333
|
+
const presentation = await materializePresentation(located.capability, output, context, wantsPresentation);
|
|
344
334
|
yield {
|
|
345
335
|
output,
|
|
346
|
-
...
|
|
336
|
+
...presentation ? { presentation } : {}
|
|
347
337
|
};
|
|
348
338
|
}
|
|
349
339
|
} catch (error) {
|
|
@@ -396,6 +386,15 @@ var TransportError = class extends Error {
|
|
|
396
386
|
this.data = options.data;
|
|
397
387
|
}
|
|
398
388
|
};
|
|
389
|
+
async function materializePresentation(capability, output, context, requested) {
|
|
390
|
+
if (!requested || !capability.toPresentation) return void 0;
|
|
391
|
+
try {
|
|
392
|
+
const presentation = normalizePresentation(await capability.toPresentation(output, { context }));
|
|
393
|
+
return presentation.length > 0 ? presentation : void 0;
|
|
394
|
+
} catch (cause) {
|
|
395
|
+
throw new TransportError("INTERNAL_SERVER_ERROR", { cause });
|
|
396
|
+
}
|
|
397
|
+
}
|
|
399
398
|
function toTransportError(error) {
|
|
400
399
|
if (error instanceof TransportError) return error;
|
|
401
400
|
if (error instanceof CapableError) return new TransportError(error.code, {
|
|
@@ -462,4 +461,4 @@ function selectApp(application, selection) {
|
|
|
462
461
|
//#endregion
|
|
463
462
|
export { TransportError as a, getAppRuntime as c, createAppManifest as d, APP_RUNTIME_SYMBOL as i, isApp as l, selectApp as n, createApp as o, APP_CAPABILITIES_SYMBOL as r, createRemoteApp as s, mergeApps as t, subscribe as u };
|
|
464
463
|
|
|
465
|
-
//# sourceMappingURL=src-
|
|
464
|
+
//# sourceMappingURL=src-C2MGIlT0.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-C2MGIlT0.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, \"input\") }\n : {}),\n ...(capability.output\n ? { output: schemaToJsonSchema(capability.output, \"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, \"output\") }\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 normalizePresentation,\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 PresentationPart,\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 readonly presentation?: boolean;\n};\n\nexport type CapabilityResult = {\n readonly output: unknown;\n readonly presentation?: readonly PresentationPart[];\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: unique symbol = Symbol.for(\n \"capable.app.runtime\",\n) as never;\nexport const APP_CAPABILITIES_SYMBOL: unique symbol = Symbol.for(\n \"capable.app.capabilities\",\n) as never;\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 AppCapabilityOptions = { readonly signal?: AbortSignal };\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?: AppCapabilityOptions,\n ]\n : Record<never, never> extends AppCapabilityInput<TCapability>\n ? [\n input?: AppCapabilityInput<TCapability>,\n options?: AppCapabilityOptions,\n ]\n : [\n input: AppCapabilityInput<TCapability>,\n options?: AppCapabilityOptions,\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 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 runtime.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, presentation: wantsPresentation }: 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 const presentation = await materializePresentation(\n located.capability,\n output,\n context,\n wantsPresentation,\n );\n\n return {\n output,\n ...(presentation ? { presentation } : {}),\n };\n },\n async *subscribe({\n id,\n input = {},\n signal,\n presentation: wantsPresentation,\n }: 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 const presentation = await materializePresentation(\n located.capability,\n output,\n context,\n wantsPresentation,\n );\n yield {\n output,\n ...(presentation ? { presentation } : {}),\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 const manifest = createManifestResolver(async () => {\n const manifest = await transport.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 function createManifestResolver(\n load: () => Promise<ApplicationManifest>,\n): () => Promise<ApplicationManifest> {\n let cached: Promise<ApplicationManifest> | undefined;\n return () => {\n if (cached) return cached;\n const attempt = Promise.resolve().then(load);\n cached = attempt;\n void attempt.catch(() => {\n if (cached === attempt) cached = undefined;\n });\n return attempt;\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\nasync function materializePresentation(\n capability: AnyCapability,\n output: unknown,\n context: unknown,\n requested: boolean | undefined,\n): Promise<readonly PresentationPart[] | undefined> {\n if (!requested || !capability.toPresentation) return undefined;\n try {\n const presentation = normalizePresentation(\n await capability.toPresentation(output, { context }),\n );\n return presentation.length > 0 ? presentation : undefined;\n } catch (cause) {\n throw new TransportError(\"INTERNAL_SERVER_ERROR\", { cause });\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 createManifestResolver,\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} 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 dispatch: ReadonlyMap<string, ApplicationTransport> | undefined;\n\n const resolve = createManifestResolver(async () => {\n const manifests = await Promise.all(\n runtimes.map((runtime) => runtime.manifest()),\n );\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 const merged = mergeApplicationManifests(manifests);\n dispatch = nextDispatch;\n return merged;\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 ids: ReadonlySet<string> | undefined;\n const manifest = createManifestResolver(async () => {\n const selected = selectManifest(await runtime.manifest(), 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* runtime.subscribe(call);\n },\n }));\n}\n"],"mappings":";;AAmDA,SAAgB,kBACd,YACqB;CACrB,MAAM,eAAe,IAAI,IACvB,WAAW,oBAAoB,KAAK,UAAU,CAAC,MAAM,YAAY,KAAK,CAAC,CACzE;CACA,OAAO,OAAO,OAAO;EACnB,UAAU;EACV,MAAM,WAAW;EACjB,SAAS,WAAW;EACpB,GAAI,WAAW,cAAc,EAAE,aAAa,WAAW,YAAY,IAAI,CAAC;EACxE,cAAc,cAAc,WAAW,cAAc,YAAY;CACnE,CAAC;AACH;AAEA,SAAgB,iBACd,UACA,OACM;CACN,IAAI,SAAS,aAAa,2BACxB,MAAM,IAAI,MAAM,GAAG,MAAM,8BAA8B,SAAS,SAAS,EAAE;CAE7E,MAAM,eAAe,4BAA4B,SAAS,YAAY;CACtE,MAAM,sBAAM,IAAI,IAAY;CAC5B,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,MAAM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AU,MAAsB;GACrC,MAAM,QAAQ;GACd,MAAM,SAAS,UAAU,IAAI,KAAK,EAAE;GACpC,IAAI,CAAC,QAAQ,MAAM,IAAI,eAAe,aAAa,EAAE,QAAQ,IAAI,CAAC;GAClE,OAAO,OAAO,UAAU,IAAI;EAC9B;CACF,CAAC,CAAC;AACJ;AAoBA,SAAgB,UAGd,aACA,WACoB;CACpB,MAAM,UAAU,cAAc,WAAW;CACzC,IAAI;CACJ,MAAM,WAAW,uBAAuB,YAAY;EAClD,MAAM,WAAW,eAAe,MAAM,QAAQ,SAAS,GAAG,SAAS;EACnE,MAAM,IAAI,IACR,4BAA4B,SAAS,YAAY,CAAC,CAAC,KAChD,eAAe,WAAW,EAC7B,CACF;EACA,OAAO;CACT,CAAC;CACD,OAAO,eAAe,OAAO,OAAO;EAClC;EACA,MAAM,KAAK,MAAsB;GAC/B,MAAM,SAAS;GACf,IAAI,CAAC,KAAK,IAAI,KAAK,EAAE,GACnB,MAAM,IAAI,eAAe,aAAa,EAAE,QAAQ,IAAI,CAAC;GAEvD,OAAO,QAAQ,KAAK,IAAI;EAC1B;EACA,OAAO,UAAU,MAAsB;GACrC,MAAM,SAAS;GACf,IAAI,CAAC,KAAK,IAAI,KAAK,EAAE,GACnB,MAAM,IAAI,eAAe,aAAa,EAAE,QAAQ,IAAI,CAAC;GAEvD,OAAO,QAAQ,UAAU,IAAI;EAC/B;CACF,CAAC,CAAC;AACJ"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as selectApp, o as createApp } from "./src-
|
|
2
|
-
import { r as createProtocolHandler, t as createHttpHandler } from "./src-
|
|
1
|
+
import { n as selectApp, o as createApp } from "./src-C2MGIlT0.mjs";
|
|
2
|
+
import { r as createProtocolHandler, t as createHttpHandler } from "./src-BF70JLxI.mjs";
|
|
3
3
|
//#region packages/server/src/index.ts
|
|
4
|
-
function
|
|
4
|
+
function protocol(options = {}) {
|
|
5
5
|
return {
|
|
6
6
|
kind: "capable.server.mount",
|
|
7
7
|
compile(app, context) {
|
|
@@ -11,7 +11,7 @@ function standard(options = {}) {
|
|
|
11
11
|
}, { ...options.path ? { basePath: options.path } : {} });
|
|
12
12
|
const base = normalizePath(options.path ?? "/_capable");
|
|
13
13
|
return {
|
|
14
|
-
name: "
|
|
14
|
+
name: "protocol",
|
|
15
15
|
async fetch(request) {
|
|
16
16
|
if (!new URL(request.url).pathname.startsWith(`${base}/`)) return;
|
|
17
17
|
return protocol.fetch(request);
|
|
@@ -46,7 +46,7 @@ function http(options = {}) {
|
|
|
46
46
|
}
|
|
47
47
|
function createServer(app, ...[providedOptions]) {
|
|
48
48
|
const options = providedOptions ?? {};
|
|
49
|
-
const mounts = (options.mounts ?? [
|
|
49
|
+
const mounts = (options.mounts ?? [protocol(), http()]).map((mount) => mount.compile(app, options.context));
|
|
50
50
|
async function dispatch(request) {
|
|
51
51
|
for (const mount of mounts) {
|
|
52
52
|
const response = await mount.fetch(request);
|
|
@@ -77,6 +77,6 @@ function normalizePath(value) {
|
|
|
77
77
|
return `/${value.split("/").filter(Boolean).join("/")}`;
|
|
78
78
|
}
|
|
79
79
|
//#endregion
|
|
80
|
-
export { http as n,
|
|
80
|
+
export { http as n, protocol as r, createServer as t };
|
|
81
81
|
|
|
82
|
-
//# sourceMappingURL=src-
|
|
82
|
+
//# sourceMappingURL=src-CDxL6w3d.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"src-
|
|
1
|
+
{"version":3,"file":"src-CDxL6w3d.mjs","names":[],"sources":["../../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 protocol<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: \"protocol\",\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 ?? [protocol(), 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,OAAO;EACL,MAAM;EACN,QAAQ,KAAK,SAAS;GACpB,MAAM,WAAW,uBACd,YAAY;IACX,MAAM,aAAa,UACjB,KACA,UACI,EAAE,eAAe,QAAQ,EAAE,QAAQ,CAAC,EAAE,IACtC,KAAA,CACN;IACA,OAAO,QAAQ,YACX,UAAU,YAAY,QAAQ,SAAS,IACvC;GACN,GACA,EACE,GAAI,QAAQ,OAAO,EAAE,UAAU,QAAQ,KAAK,IA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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,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { y as renderPresentationMarkdown } from "./src-DdV82An-.mjs";
|
|
2
|
+
import { a as TransportError, c as getAppRuntime } from "./src-C2MGIlT0.mjs";
|
|
2
3
|
import { render } from "markdansi";
|
|
3
4
|
//#region packages/cli/src/commands.ts
|
|
4
5
|
function collectCommands(nodes, parent = []) {
|
|
@@ -236,6 +237,18 @@ function renderHelp(sections) {
|
|
|
236
237
|
return `\n${sections.filter(Boolean).join("\n\n")}\n`;
|
|
237
238
|
}
|
|
238
239
|
//#endregion
|
|
240
|
+
//#region packages/cli/src/presentation.ts
|
|
241
|
+
function renderCliCapabilityResult(result, options) {
|
|
242
|
+
if (result.presentation !== void 0) return renderCliMarkdown(renderPresentationMarkdown(result.presentation), options);
|
|
243
|
+
return typeof result.output === "string" ? result.output : JSON.stringify(result.output, null, 2);
|
|
244
|
+
}
|
|
245
|
+
function renderCliMarkdown(markdown, options) {
|
|
246
|
+
return options.isTTY ? render(markdown, {
|
|
247
|
+
color: options.color,
|
|
248
|
+
width: options.columns
|
|
249
|
+
}) : markdown;
|
|
250
|
+
}
|
|
251
|
+
//#endregion
|
|
239
252
|
//#region packages/cli/src/index.ts
|
|
240
253
|
function createCli(app, cliOptions = {}) {
|
|
241
254
|
return Object.freeze({ run(argv, options = {}) {
|
|
@@ -319,9 +332,10 @@ async function runCli(options) {
|
|
|
319
332
|
});
|
|
320
333
|
const result = await runtime.call({
|
|
321
334
|
id: command.capability.id,
|
|
322
|
-
input
|
|
335
|
+
input,
|
|
336
|
+
...!json ? { presentation: true } : {}
|
|
323
337
|
});
|
|
324
|
-
io.stdout(json ? JSON.stringify(result.output, null, 2) :
|
|
338
|
+
io.stdout(json ? JSON.stringify(result.output, null, 2) : renderCliCapabilityResult(result, {
|
|
325
339
|
color,
|
|
326
340
|
isTTY,
|
|
327
341
|
columns
|
|
@@ -350,6 +364,7 @@ async function runWatchedCommand(options) {
|
|
|
350
364
|
const stream = options.runtime.subscribe({
|
|
351
365
|
id: options.command.capability.id,
|
|
352
366
|
input: options.input,
|
|
367
|
+
...!options.json ? { presentation: true } : {},
|
|
353
368
|
signal: controller.signal
|
|
354
369
|
});
|
|
355
370
|
try {
|
|
@@ -360,7 +375,7 @@ async function runWatchedCommand(options) {
|
|
|
360
375
|
options.io.stdout(`${JSON.stringify(result.output)}\n`);
|
|
361
376
|
continue;
|
|
362
377
|
}
|
|
363
|
-
const presentation =
|
|
378
|
+
const presentation = renderCliCapabilityResult(result, options);
|
|
364
379
|
options.io.stdout(formatWatchFrame(presentation, frame++, options.isTTY, previousFrameLines));
|
|
365
380
|
previousFrameLines = countFrameLines(presentation);
|
|
366
381
|
}
|
|
@@ -373,13 +388,6 @@ async function runWatchedCommand(options) {
|
|
|
373
388
|
await stream.return?.();
|
|
374
389
|
}
|
|
375
390
|
}
|
|
376
|
-
function renderCapabilityResult(result, options) {
|
|
377
|
-
if (result.markdown !== void 0) return options.isTTY ? render(result.markdown, {
|
|
378
|
-
color: options.color,
|
|
379
|
-
width: options.columns
|
|
380
|
-
}) : result.markdown;
|
|
381
|
-
return typeof result.output === "string" ? result.output : JSON.stringify(result.output, null, 2);
|
|
382
|
-
}
|
|
383
391
|
function formatWatchFrame(value, index, isTTY, previousFrameLines) {
|
|
384
392
|
const frame = value.endsWith("\n") ? value : `${value}\n`;
|
|
385
393
|
if (isTTY) return index === 0 ? frame : `\u001B[${previousFrameLines}A\r\u001B[0J${frame}`;
|
|
@@ -487,4 +495,4 @@ function kebabCase(value) {
|
|
|
487
495
|
//#endregion
|
|
488
496
|
export { createCliStyle as a, renderSection as c, ROW_INDENT as i, supportsColor as l, runCli as n, descriptionColumn as o, MARGIN as r, renderRows as s, createCli as t };
|
|
489
497
|
|
|
490
|
-
//# sourceMappingURL=src-
|
|
498
|
+
//# sourceMappingURL=src-Db6-XSnU.mjs.map
|