capable-kit 0.0.1-alpha.7 → 0.1.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +214 -0
- package/README.md +6 -0
- package/dist/ai-sdk.d.mts +3 -3
- package/dist/ai-sdk.mjs +9 -7
- package/dist/ai-sdk.mjs.map +1 -1
- package/dist/app.d.mts +2 -2
- package/dist/app.mjs +2 -2
- package/dist/bin.mjs +12 -9
- package/dist/bin.mjs.map +1 -1
- package/dist/cli.d.mts +9 -1
- package/dist/cli.mjs +1 -1
- package/dist/core.d.mts +3 -3
- package/dist/core.mjs +1 -1
- package/dist/eve.d.mts +82 -5
- package/dist/eve.mjs +364 -23
- package/dist/eve.mjs.map +1 -1
- package/dist/http.d.mts +2 -2
- package/dist/http.mjs +2 -2
- package/dist/{index-Dbc4g9WM.d.mts → index-1A44jLuE.d.mts} +54 -16
- package/dist/{index-DwXlaTXI.d.mts → index-CHuCLJIs.d.mts} +20 -4
- package/dist/{index-D2CRRUzH.d.mts → index-D-NV4PiU.d.mts} +6 -5
- package/dist/{index-Be8-UVBC.d.mts → index-WiBWfyTn.d.mts} +66 -27
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +3 -3
- package/dist/mcp.d.mts +40 -5
- package/dist/mcp.mjs +1 -1
- package/dist/mount-BmLHp349.mjs +235 -0
- package/dist/mount-BmLHp349.mjs.map +1 -0
- package/dist/react-query.d.mts +2 -2
- package/dist/react-query.mjs +1 -1
- package/dist/react-query.mjs.map +1 -1
- package/dist/runtime-support.d.mts +1 -1
- package/dist/runtime-support.mjs +8 -8
- package/dist/runtime-support.mjs.map +1 -1
- package/dist/server.d.mts +1 -1
- package/dist/server.mjs +1 -1
- package/dist/{src-Db6-XSnU.mjs → src-3LE9S4QE.mjs} +67 -38
- package/dist/src-3LE9S4QE.mjs.map +1 -0
- package/dist/{src-DdV82An-.mjs → src-B2WeUwUT.mjs} +69 -34
- package/dist/src-B2WeUwUT.mjs.map +1 -0
- package/dist/{src-CDxL6w3d.mjs → src-C5jGDnuu.mjs} +9 -6
- package/dist/src-C5jGDnuu.mjs.map +1 -0
- package/dist/src-DePlcG_t.mjs +787 -0
- package/dist/src-DePlcG_t.mjs.map +1 -0
- package/dist/{src-BF70JLxI.mjs → src-_6OmFRYa.mjs} +185 -38
- package/dist/src-_6OmFRYa.mjs.map +1 -0
- package/dist/{subscription-Bq792Ad2.d.mts → subscription-DPdwovhw.d.mts} +2 -2
- package/dist/swr.d.mts +2 -2
- package/dist/swr.mjs +1 -1
- package/dist/swr.mjs.map +1 -1
- package/docs/CONTEXT.md +42 -21
- package/docs/README.md +3 -0
- package/docs/internal/README.md +3 -0
- package/docs/internal/adr/0001-capability-is-the-semantic-boundary.md +1 -1
- package/docs/internal/adr/0002-version-the-capable-value-codec.md +24 -0
- package/docs/internal/adr/0003-capability-reference-customization.md +68 -0
- package/docs/internal/architecture.md +64 -19
- package/docs/internal/capability-first-model.md +127 -18
- package/docs/internal/eve-recovery-validation.md +86 -0
- package/docs/internal/feedback/v-ray/README.md +258 -0
- package/docs/internal/feedback/v-ray/inference.mjs +43 -0
- package/docs/internal/feedback/v-ray/reproduce.mjs +36 -0
- package/docs/internal/implementation-friction.md +481 -1
- package/docs/internal/releases.md +79 -0
- package/docs/site/capable-orpc-and-trpc.mdx +5 -5
- package/docs/site/concepts/apps.mdx +17 -8
- package/docs/site/concepts/architecture.mdx +10 -2
- package/docs/site/concepts/capabilities.mdx +41 -4
- package/docs/site/concepts/errors.mdx +11 -1
- package/docs/site/concepts/presentations.mdx +20 -0
- package/docs/site/hosting/any-fetch-host.mdx +2 -2
- package/docs/site/hosting/next-js.mdx +38 -4
- package/docs/site/hosting/standalone-server.mdx +2 -2
- package/docs/site/introduction.mdx +9 -6
- package/docs/site/patterns/composition.mdx +159 -11
- package/docs/site/patterns/remote-apps.mdx +68 -10
- package/docs/site/patterns/subscriptions.mdx +79 -32
- package/docs/site/quickstart.mdx +19 -14
- package/docs/site/reference/packages-and-entry-points.mdx +52 -5
- package/docs/site/reference/surface-metadata.mdx +7 -2
- package/docs/site/reference/the-cap-cli.mdx +2 -2
- package/docs/site/surfaces/ai-sdk.mdx +3 -3
- package/docs/site/surfaces/cli.mdx +47 -3
- package/docs/site/surfaces/eve.mdx +67 -20
- package/docs/site/surfaces/mcp.mdx +73 -5
- package/docs/site/surfaces/react-query.mdx +3 -3
- package/docs/site/surfaces/swr.mdx +3 -3
- package/docs/site/surfaces/typescript.mdx +8 -8
- package/docs/site/surfaces.mdx +1 -1
- package/package-docs.mjs +3 -0
- package/package.json +11 -11
- package/src/bin.ts +0 -0
- package/src/index.test.ts +2 -1
- package/src/index.ts +6 -1
- package/src/mcp.ts +4 -0
- package/src/package.test.ts +9 -0
- package/dist/mount-xvMsjz1B.mjs +0 -178
- package/dist/mount-xvMsjz1B.mjs.map +0 -1
- package/dist/src-BF70JLxI.mjs.map +0 -1
- package/dist/src-C2MGIlT0.mjs +0 -464
- package/dist/src-C2MGIlT0.mjs.map +0 -1
- package/dist/src-CDxL6w3d.mjs.map +0 -1
- package/dist/src-Db6-XSnU.mjs.map +0 -1
- package/dist/src-DdV82An-.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-_6OmFRYa.mjs","names":["normalizePath"],"sources":["../../fetch/src/error-response.ts","../../fetch/src/codec.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 SuperJSON, {\n type SuperJSONResult,\n type SuperJSONValue,\n} from \"superjson\";\n\nexport type JsonValue =\n | null\n | boolean\n | number\n | string\n | readonly JsonValue[]\n | { readonly [key: string]: JsonValue };\n\nexport type ProtocolCodec = {\n /** Stable identity used to reject mismatched protocol peers. */\n readonly id: string;\n /** Converts a runtime value into JSON-compatible protocol data. */\n encode(value: unknown): JsonValue;\n /** Restores a runtime value from JSON-compatible protocol data. */\n decode(value: JsonValue): unknown;\n};\n\nexport function defineProtocolCodec(\n codec: ProtocolCodec,\n): ProtocolCodec {\n if (!codec.id.trim()) throw new Error(\"Protocol codec id must not be empty\");\n return Object.freeze({\n id: codec.id,\n encode: codec.encode,\n decode: codec.decode,\n });\n}\n\nconst richJson = new SuperJSON();\n\nexport const capableRichJsonCodec: ProtocolCodec = defineProtocolCodec({\n id: \"capable.rich-json.v1\",\n encode(value) {\n return richJson.serialize(value as SuperJSONValue) as unknown as JsonValue;\n },\n decode(value) {\n return richJson.deserialize(value as unknown as SuperJSONResult);\n },\n});\n","import {\n getAppRuntime,\n isApp,\n TransportError,\n flattenManifestCapabilities,\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 { capabilityErrorData } from \"./error-response.ts\";\nimport {\n capableRichJsonCodec,\n type JsonValue,\n type ProtocolCodec,\n} from \"./codec.ts\";\n\nexport type FetchHandler = (request: Request) => Response | Promise<Response>;\n\nconst PROTOCOL_CODEC_HEADER = \"capable-codec\";\n\nexport function createProtocolHandler(\n application:\n | AnyApp\n | ((request: Request) => AnyApp | Promise<AnyApp>),\n options: {\n readonly basePath?: string;\n readonly codec?: ProtocolCodec;\n } = {},\n): {\n readonly fetch: FetchHandler;\n} {\n const basePath = normalizePath(options.basePath ?? \"/~capable\");\n const codec = options.codec ?? capableRichJsonCodec;\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 headers: { [PROTOCOL_CODEC_HEADER]: codec.id },\n });\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 protocolRequestJson(request, codec) as {\n readonly input?: unknown;\n readonly presentation?: boolean;\n };\n const execution = flattenManifestCapabilities(\n (await runtime.manifest()).capabilities,\n ).find((candidate) => candidate.id === id)?.execution;\n stream = await runtime.subscribe({\n id,\n input: body.input ?? {},\n ...(body.presentation ? { presentation: true } : {}),\n signal: AbortSignal.any([request.signal, controller.signal]),\n });\n let first: IteratorResult<CapabilityResult> | undefined;\n if (execution === \"live\") {\n first = await stream.next();\n }\n return subscriptionResponse(stream, first, controller, codec);\n } catch (error) {\n controller.abort();\n await stream?.return?.().catch(() => undefined);\n return protocolErrorResponse(error, codec);\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 protocolRequestJson(request, codec) 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 protocolResponse(codec, {\n ok: true,\n ...result,\n });\n } catch (error) {\n return protocolErrorResponse(error, codec);\n }\n };\n\n return { fetch };\n}\n\nasync function protocolRequestJson(\n request: Request,\n codec: ProtocolCodec,\n): Promise<Record<string, unknown>> {\n const received = request.headers.get(PROTOCOL_CODEC_HEADER);\n if (received !== codec.id) {\n throw new TransportError(\"UNSUPPORTED_CODEC\", {\n status: 415,\n message:\n `Protocol codec mismatch: expected \"${codec.id}\", received \"${received ?? \"none\"}\"`,\n data: { expected: codec.id, received },\n });\n }\n let decoded: unknown;\n try {\n decoded = codec.decode(await request.json() as JsonValue);\n } catch (cause) {\n throw new TransportError(\"BAD_REQUEST\", {\n status: 400,\n message: \"Protocol request could not be decoded\",\n cause,\n });\n }\n if (!decoded || typeof decoded !== \"object\" || Array.isArray(decoded)) {\n throw new TransportError(\"BAD_REQUEST\", {\n status: 400,\n message: \"Protocol request must decode to an object\",\n });\n }\n return decoded as Record<string, unknown>;\n}\n\nfunction protocolResponse(\n codec: ProtocolCodec,\n value: unknown,\n init: ResponseInit = {},\n): Response {\n const headers = new Headers(init.headers);\n headers.set(PROTOCOL_CODEC_HEADER, codec.id);\n return Response.json(codec.encode(value), { ...init, headers });\n}\n\nfunction protocolErrorResponse(\n error: unknown,\n codec: ProtocolCodec,\n): Response {\n const data = capabilityErrorData(error);\n return protocolResponse(codec, {\n ok: false,\n error: data,\n }, { status: data.status });\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 readonly codec?: ProtocolCodec;\n}): ApplicationTransport {\n const fetchImplementation = options.fetch ?? globalThis.fetch;\n const codec = options.codec ?? capableRichJsonCodec;\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 headers: { [PROTOCOL_CODEC_HEADER]: codec.id },\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) throw await responseError(response);\n if (response.headers.get(\"content-type\")?.includes(\"json\")) {\n assertResponseCodec(response, codec);\n }\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: {\n \"content-type\": \"application/json\",\n [PROTOCOL_CODEC_HEADER]: codec.id,\n },\n body: JSON.stringify(codec.encode({\n input,\n ...(presentation ? { presentation } : {}),\n })),\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) throw await responseError(response, codec);\n const body = await protocolResponseJson<\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 >(response, codec, \"Capability call\");\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 [PROTOCOL_CODEC_HEADER]: codec.id,\n },\n body: JSON.stringify(codec.encode({\n input,\n ...(presentation ? { presentation } : {}),\n })),\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) throw await responseError(response, codec);\n assertResponseCodec(response, codec);\n return decodeEventStream(response, codec);\n },\n });\n}\n\nfunction subscriptionResponse(\n stream: AsyncIterableIterator<CapabilityResult>,\n first: IteratorResult<CapabilityResult> | undefined,\n subscriptionController: AbortController,\n codec: ProtocolCodec,\n): Response {\n const encoder = new TextEncoder();\n let initial: IteratorResult<CapabilityResult> | undefined = first;\n let cancelled = false;\n\n return new Response(new ReadableStream({\n start(controller) {\n // Flush headers through HTTP hosts without manufacturing a canonical event.\n if (!first) controller.enqueue(encoder.encode(\": capable\\n\\n\"));\n },\n async pull(controller) {\n try {\n const result = initial ?? await stream.next();\n initial = undefined;\n if (cancelled) return;\n if (result.done) {\n subscriptionController.abort();\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(\n sseFrame(\"output\", result.value, codec),\n ));\n } catch (error) {\n if (cancelled) return;\n subscriptionController.abort();\n controller.enqueue(encoder.encode(\n sseFrame(\"error\", capabilityErrorData(error), codec),\n ));\n controller.close();\n await stream.return?.();\n }\n },\n async cancel() {\n cancelled = true;\n subscriptionController.abort();\n await stream.return?.();\n },\n }, {\n highWaterMark: 0,\n }), {\n headers: {\n \"cache-control\": \"no-cache\",\n [PROTOCOL_CODEC_HEADER]: codec.id,\n \"content-type\": \"text/event-stream; charset=utf-8\",\n },\n });\n}\n\nfunction decodeEventStream(\n response: Response,\n codec: ProtocolCodec,\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 return decodeEventStreamBody(response.body, codec);\n}\n\nasync function* decodeEventStreamBody(\n body: ReadableStream<Uint8Array>,\n codec: ProtocolCodec,\n): AsyncIterableIterator<CapabilityResult> {\n const reader = 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, codec);\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, codec: ProtocolCodec):\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 let value: any;\n try {\n value = codec.decode(JSON.parse(data.join(\"\\n\")) as JsonValue);\n } catch (cause) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n message: \"Subscription event could not be decoded\",\n cause,\n });\n }\n return type === \"error\"\n ? { type: \"error\", error: value }\n : { type: \"output\", result: value };\n}\n\nfunction sseFrame(\n event: string,\n data: unknown,\n codec: ProtocolCodec,\n): string {\n return `event: ${event}\\ndata: ${JSON.stringify(codec.encode(data))}\\n\\n`;\n}\n\nfunction normalizeUrl(value: string | URL): URL {\n let url: URL;\n try {\n url = typeof window === \"undefined\"\n ? new URL(value)\n : new URL(value, window.location.origin);\n } catch (cause) {\n throw new TypeError(\n \"Capable transport URLs must be absolute when no browser origin is \" +\n \"available. Pass an absolute URL or return one from the `url` function.\",\n { cause },\n );\n }\n if (!url.pathname.endsWith(\"/\")) url.pathname += \"/\";\n url.search = \"\";\n url.hash = \"\";\n return url;\n}\n\nfunction assertResponseCodec(\n response: Response,\n codec: ProtocolCodec,\n): void {\n const received = response.headers.get(PROTOCOL_CODEC_HEADER);\n if (received === codec.id) return;\n throw new TransportError(\"UNSUPPORTED_CODEC\", {\n status: response.status,\n message:\n `Protocol codec mismatch: expected \"${codec.id}\", received \"${received ?? \"none\"}\"`,\n data: { expected: codec.id, received },\n });\n}\n\nasync function protocolResponseJson<T>(\n response: Response,\n codec: ProtocolCodec,\n label: string,\n): Promise<T> {\n assertResponseCodec(response, codec);\n const encoded = await responseJson<JsonValue>(response, label);\n try {\n return codec.decode(encoded) as T;\n } catch (cause) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: `${label} response could not be decoded`,\n cause,\n });\n }\n}\n\nasync function responseError(\n response: Response,\n codec?: ProtocolCodec,\n): Promise<TransportError> {\n if (codec) {\n try {\n assertResponseCodec(response, codec);\n } catch (error) {\n return error as TransportError;\n }\n }\n const text = await response.text().catch(() => \"\");\n let data: unknown = text;\n let parsed = false;\n try {\n data = JSON.parse(text);\n parsed = true;\n } catch {\n // Preserve the response text as transport diagnostics.\n }\n if (codec && parsed) {\n try {\n data = codec.decode(data as JsonValue);\n } catch (cause) {\n return new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: \"Transport error response could not be decoded\",\n cause,\n });\n }\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 type { ApplicationSelection, JsonSchema } 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) => {\n const meta = capabilityHttp(entry);\n if (meta === false) return false;\n if (entry.capability.execution !== \"events\") return true;\n if (meta !== undefined) {\n throw new Error(\n `Event Capability \"${entry.capability.id}\" cannot be exposed as a unary HTTP route`,\n );\n }\n return false;\n });\n const routes = selected.map((entry) => compileHttpRoute(entry, basePath));\n assertUniqueRoutes(routes);\n if (options.requireExplicitRoutes) {\n const implicit = selected.find((entry) => {\n const meta = capabilityHttp(entry);\n return !meta || !meta.method || !meta.route;\n });\n if (implicit) {\n throw new Error(\n `Capability \"${implicit.capability.id}\" requires an explicit HTTP method and route`,\n );\n }\n }\n const openapi = createOpenApi(app, routes);\n const openapiPath = options.openapiPath === false\n ? undefined\n : normalizePath(options.openapiPath ?? \"/openapi.json\");\n\n return {\n routes,\n openapi,\n async fetch(request) {\n const url = new URL(request.url);\n if (\n openapiPath &&\n url.pathname === openapiPath &&\n request.method === \"GET\"\n ) {\n return Response.json(openapi);\n }\n const match = routes\n .map((route) => ({ route, params: matchPath(route.path, url.pathname) }))\n .find(({ route, params }) => route.method === request.method && params);\n if (!match?.params) return new Response(\"Not Found\", { status: 404 });\n\n try {\n const input = await readHttpInput(\n request,\n match.params,\n match.route.capability.capability.input,\n );\n const context = options.context\n ? await options.context({ request })\n : undefined as TContext;\n const output = await executeLocatedCapability(match.route.capability, input, {\n context,\n signal: request.signal,\n });\n if (\n request.headers.get(\"accept\")?.includes(\"text/markdown\") &&\n match.route.capability.capability.toPresentation\n ) {\n const presentation = normalizePresentation(\n await match.route.capability.capability.toPresentation(output, {\n context,\n }),\n );\n if (presentation.length > 0) {\n return new Response(\n renderPresentationMarkdown(presentation),\n {\n status: httpSuccessStatus(match.route.capability),\n headers: { \"content-type\": \"text/markdown; charset=utf-8\" },\n },\n );\n }\n }\n return Response.json(output, {\n status: httpSuccessStatus(match.route.capability),\n });\n } catch (error) {\n return capabilityErrorResponse(error);\n }\n },\n };\n}\n\nfunction compileHttpRoute(\n entry: LocatedCapability,\n basePath: string,\n): CompiledHttpRoute {\n const meta = capabilityHttp(entry);\n const defaultPath = entry.path.flatMap((segment, index) => {\n const groupIndex = entry.groupPaths.findIndex(\n (path) => path.length === index + 1,\n );\n const prefix = groupIndex >= 0\n ? (entry.groups[groupIndex]?.meta.http as HttpGroupMeta | undefined)\n ?.prefix\n : undefined;\n return prefix ? prefix.split(\"/\").filter(Boolean) : [segment];\n }).join(\"/\");\n const groupPrefix = entry.groups.flatMap((group) => {\n const prefix = (group.meta.http as HttpGroupMeta | undefined)?.prefix;\n return prefix ? prefix.split(\"/\").filter(Boolean) : [];\n }).join(\"/\");\n const authoredRoute = meta && meta.route ? meta.route : defaultPath;\n assertPathParameters(entry, authoredRoute);\n return Object.freeze({\n method: meta && meta.method\n ? meta.method\n : entry.capability.effect === \"read\"\n ? \"GET\"\n : \"POST\",\n path: joinPath(\n basePath,\n meta && meta.route ? groupPrefix : \"\",\n authoredRoute,\n ),\n capability: entry,\n });\n}\n\nfunction capabilityHttp(entry: LocatedCapability): HttpCapabilityMeta | undefined {\n return entry.capability.meta.http as HttpCapabilityMeta | undefined;\n}\n\nfunction httpSuccessStatus(entry: LocatedCapability): number {\n const meta = capabilityHttp(entry);\n return meta && typeof meta.status === \"number\" ? meta.status : 200;\n}\n\nasync function readHttpInput(\n request: Request,\n params: Record<string, string>,\n schema: LocatedCapability[\"capability\"][\"input\"],\n): Promise<Record<string, unknown>> {\n const url = new URL(request.url);\n const jsonSchema = schema\n ? schemaToJsonSchema(schema, \"input\")\n : undefined;\n const properties = jsonSchema?.properties as\n | Record<string, Readonly<Record<string, unknown>>>\n | undefined;\n const coerceEntries = (entries: Iterable<readonly [string, string]>) =>\n Object.fromEntries(\n [...entries].map(([key, value]) => [\n key,\n coerceHttpValue(value, properties?.[key]),\n ]),\n );\n const rest: Record<string, unknown> =\n request.method === \"GET\"\n ? coerceEntries(url.searchParams)\n : request.headers.get(\"content-type\")?.includes(\"application/json\")\n ? await request.json() as Record<string, unknown>\n : {};\n return {\n ...rest,\n ...coerceEntries(Object.entries(params)),\n };\n}\n\nfunction coerceHttpValue(\n value: string,\n schema: Readonly<Record<string, unknown>> | undefined,\n): unknown {\n if (schema?.type === \"boolean\") return value === \"true\"\n ? true\n : value === \"false\"\n ? false\n : value;\n if (schema?.type === \"integer\" || schema?.type === \"number\") {\n const number = Number(value);\n return Number.isFinite(number) ? number : value;\n }\n return value;\n}\n\nfunction assertPathParameters(\n entry: LocatedCapability,\n path: string,\n): void {\n const parameters = [...path.matchAll(/:([^/]+)/g)].map((match) => match[1]!);\n if (parameters.length === 0) return;\n const schema = entry.capability.input\n ? schemaToJsonSchema(entry.capability.input, \"input\")\n : undefined;\n const properties = schema?.properties as\n | Record<string, unknown>\n | undefined;\n for (const parameter of parameters) {\n if (!properties?.[parameter]) {\n throw new Error(\n `HTTP path parameter \":${parameter}\" is not present in Capability \"${entry.capability.id}\" input`,\n );\n }\n }\n}\n\nfunction matchPath(\n pattern: string,\n pathname: string,\n): Record<string, string> | undefined {\n const expected = pattern.split(\"/\").filter(Boolean);\n const actual = pathname.split(\"/\").filter(Boolean);\n if (expected.length !== actual.length) return undefined;\n const params: Record<string, string> = {};\n for (let index = 0; index < expected.length; index++) {\n const token = expected[index]!;\n const value = actual[index]!;\n if (token.startsWith(\":\")) params[token.slice(1)] = decodeURIComponent(value);\n else if (token !== value) return undefined;\n }\n return params;\n}\n\nfunction createOpenApi(\n app: AppDefinition<any, any>,\n routes: readonly CompiledHttpRoute[],\n): Readonly<Record<string, unknown>> {\n const paths: Record<string, unknown> = {};\n for (const route of routes) {\n const method = route.method.toLowerCase();\n const path = route.path.replace(/:([^/]+)/g, \"{$1}\");\n const capability = route.capability.capability;\n const input = capability.input\n ? schemaToJsonSchema(capability.input, \"input\")\n : undefined;\n const properties = (input?.properties ?? {}) as Record<string, JsonSchema>;\n const required = new Set((input?.required ?? []) as readonly string[]);\n const pathNames = new Set(\n [...route.path.matchAll(/:([^/]+)/g)].map((match) => match[1]!),\n );\n const parameters = [...pathNames].map((name) => ({\n name,\n in: \"path\",\n required: true,\n schema: properties[name] ?? {},\n }));\n const remaining = Object.fromEntries(\n Object.entries(properties).filter(([name]) => !pathNames.has(name)),\n );\n if (route.method === \"GET\") {\n parameters.push(\n ...Object.entries(remaining).map(([name, schema]) => ({\n name,\n in: \"query\",\n required: required.has(name),\n schema,\n })),\n );\n }\n const responses: Record<string, unknown> = {\n [String(httpSuccessStatus(route.capability))]: {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: capability.output\n ? schemaToJsonSchema(capability.output, \"output\")\n : {},\n },\n },\n },\n };\n for (const [code, error] of Object.entries(route.capability.errors)) {\n const status = typeof error.status === \"number\"\n ? String(error.status)\n : \"default\";\n responses[status] ??= {\n description: error.message ?? code,\n };\n }\n const current = paths[path] as Record<string, unknown> | undefined ?? {};\n current[method] = {\n capabilityId: capability.id,\n ...(capability.title ? { summary: capability.title } : {}),\n ...(capability.description ? { description: capability.description } : {}),\n ...(parameters.length ? { parameters } : {}),\n ...(route.method !== \"GET\" && Object.keys(remaining).length\n ? {\n requestBody: {\n required: [...required].some((name) => !pathNames.has(name)),\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: remaining,\n required: [...required].filter((name) =>\n !pathNames.has(name)\n ),\n },\n },\n },\n },\n }\n : {}),\n responses,\n };\n paths[path] = current;\n }\n return {\n openapi: \"3.1.0\",\n info: { title: app.name, version: app.version },\n paths,\n };\n}\n\nfunction selectCapabilities(\n capabilities: readonly LocatedCapability[],\n selection: CapabilitySelection | undefined,\n): readonly LocatedCapability[] {\n return capabilities.filter((entry) => {\n const included = selection?.include\n ? matchesTree(selection.include, entry.path)\n : true;\n return included && !matchesTree(selection?.exclude, entry.path);\n });\n}\n\nfunction matchesTree(\n tree: Readonly<Record<string, unknown>> | undefined,\n path: readonly string[],\n): boolean {\n if (!tree) return false;\n let current: unknown = tree;\n for (const segment of path) {\n if (current === true) return true;\n if (!current || typeof current !== \"object\" || Array.isArray(current)) {\n return false;\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return current === true || (\n Boolean(current) && typeof current === \"object\" && !Array.isArray(current)\n );\n}\n\nfunction assertUniqueRoutes(routes: readonly CompiledHttpRoute[]): void {\n const seen = new Set<string>();\n for (const route of routes) {\n const identity = `${route.method} ${route.path}`;\n if (seen.has(identity)) throw new Error(`Duplicate HTTP route ${identity}`);\n seen.add(identity);\n }\n}\n\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n\nfunction joinPath(...parts: readonly string[]): string {\n return normalizePath(parts.join(\"/\"));\n}\n"],"mappings":";;;;AAUA,SAAgB,oBACd,OACA,iBAAiB,KACI;CACrB,MAAM,UAAU,iBAAiB,gBAAgB,iBAAiB,iBAC9D,QACA,IAAI,aAAa,yBAAyB,EAAE,OAAO,MAAM,CAAC;CAC9D,OAAO;EACL,MAAM,QAAQ;EACd,SAAS,QAAQ;EACjB,QAAQ,QAAQ,UAAU;EAC1B,GAAI,QAAQ,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,QAAQ,KAAK;CAC7D;AACF;AAEA,SAAgB,wBACd,OACA,iBAAiB,KACP;CACV,MAAM,OAAO,oBAAoB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,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 {
|
|
1
|
+
import { Y as MaybePromise } from "./index-WiBWfyTn.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-DPdwovhw.d.mts.map
|
package/dist/swr.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { _ as AppCapabilityReference, h as AppCapabilityIsLive } from "./index-1A44jLuE.mjs";
|
|
2
2
|
import { Fetcher, SWRConfiguration } from "swr";
|
|
3
3
|
import { MutationFetcher, SWRMutationConfiguration } from "swr/mutation";
|
|
4
4
|
import { SWRSubscription } from "swr/subscription";
|
|
@@ -26,7 +26,7 @@ type SWRLiveCapability<TCall extends CapabilityCall> = SWRCapability<TCall> & {
|
|
|
26
26
|
subscription(input: CapabilityInput<TCall>): readonly [key: CapabilitySWRKey, subscriber: SWRSubscription<CapabilitySWRKey, CapabilityOutput<TCall>, Error>];
|
|
27
27
|
subscription<const TOptions extends CapabilitySWRSubscriptionConfiguration<TCall>>(input: CapabilityInput<TCall>, options: TOptions): readonly [key: CapabilitySWRKey, subscriber: SWRSubscription<CapabilitySWRKey, CapabilityOutput<TCall>, Error>, options: TOptions];
|
|
28
28
|
};
|
|
29
|
-
type SWRNode<TValue> = TValue extends CapabilityCall ?
|
|
29
|
+
type SWRNode<TValue> = TValue extends CapabilityCall ? AppCapabilityIsLive<TValue> extends true ? SWRLiveCapability<TValue> : SWRCapability<TValue> : TValue extends object ? { readonly [TKey in Extract<keyof TValue, string> as TValue[TKey] extends AppCapabilityReference ? TValue[TKey] extends CapabilityCall ? TKey : never : TKey]: SWRNode<TValue[TKey]>; } : never;
|
|
30
30
|
type SWRApp<TApp extends object> = SWRNode<TApp>;
|
|
31
31
|
declare function createSWR<const TApp extends object>(app: TApp, options?: {
|
|
32
32
|
readonly keyPrefix?: readonly unknown[];
|
package/dist/swr.mjs
CHANGED
package/dist/swr.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swr.mjs","names":[],"sources":["../../swr/src/index.ts"],"sourcesContent":["import {\n subscribe,\n type
|
|
1
|
+
{"version":3,"file":"swr.mjs","names":[],"sources":["../../swr/src/index.ts"],"sourcesContent":["import {\n subscribe,\n type AppCapabilityIsLive,\n type AppCapabilityReference,\n} from \"@capable/app\";\nimport type {\n Fetcher,\n SWRConfiguration,\n} from \"swr\";\nimport type {\n MutationFetcher,\n SWRMutationConfiguration,\n} from \"swr/mutation\";\nimport type { SWRSubscription } from \"swr/subscription\";\n\ntype CapabilityCall = (...args: any[]) => Promise<any>;\n\nconst subscribeCall = subscribe as unknown as (\n capabilityCall: CapabilityCall,\n input: unknown,\n options: { readonly signal: AbortSignal },\n) => AsyncIterableIterator<unknown>;\n\ntype CapabilityInput<TCall extends CapabilityCall> =\n Exclude<Parameters<TCall>[0], undefined>;\n\ntype CapabilityVariables<TCall extends CapabilityCall> =\n undefined extends Parameters<TCall>[0]\n ? Exclude<Parameters<TCall>[0], undefined> | void\n : Parameters<TCall>[0];\n\ntype CapabilityOutput<TCall extends CapabilityCall> =\n Awaited<ReturnType<TCall>>;\n\nexport type CapabilitySWRKey = readonly [unknown, ...unknown[]];\n\ntype CapabilityFetcher<TCall extends CapabilityCall> = Fetcher<\n CapabilityOutput<TCall>,\n CapabilitySWRKey\n>;\n\ntype CapabilityMutationFetcher<TCall extends CapabilityCall> = MutationFetcher<\n CapabilityOutput<TCall>,\n CapabilitySWRKey,\n CapabilityVariables<TCall>\n>;\n\nexport type CapabilitySWRConfiguration<\n TCall extends CapabilityCall,\n> = Omit<\n SWRConfiguration<\n CapabilityOutput<TCall>,\n Error,\n CapabilityFetcher<TCall>\n >,\n \"fetcher\"\n>;\n\nexport type CapabilitySWRMutationConfiguration<\n TCall extends CapabilityCall,\n TSWRData = CapabilityOutput<TCall>,\n> = SWRMutationConfiguration<\n CapabilityOutput<TCall>,\n Error,\n CapabilitySWRKey,\n CapabilityVariables<TCall>,\n TSWRData\n> & {\n readonly throwOnError?: boolean;\n};\n\nexport type CapabilitySWRSubscriptionConfiguration<\n TCall extends CapabilityCall,\n> = SWRConfiguration<CapabilityOutput<TCall>, Error>;\n\nexport type SWRCapability<TCall extends CapabilityCall> = {\n key(input?: CapabilityInput<TCall>): CapabilitySWRKey;\n swr(input: CapabilityInput<TCall>): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityFetcher<TCall>,\n ];\n swr<const TOptions extends CapabilitySWRConfiguration<TCall>>(\n input: CapabilityInput<TCall>,\n options: TOptions,\n ): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityFetcher<TCall>,\n options: TOptions,\n ];\n mutation(): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityMutationFetcher<TCall>,\n ];\n mutation<TSWRData = CapabilityOutput<TCall>>(\n options: CapabilitySWRMutationConfiguration<TCall, TSWRData>,\n ): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityMutationFetcher<TCall>,\n options: CapabilitySWRMutationConfiguration<TCall, TSWRData>,\n ];\n};\n\nexport type SWRLiveCapability<TCall extends CapabilityCall> =\n SWRCapability<TCall> & {\n subscription(input: CapabilityInput<TCall>): readonly [\n key: CapabilitySWRKey,\n subscriber: SWRSubscription<\n CapabilitySWRKey,\n CapabilityOutput<TCall>,\n Error\n >,\n ];\n subscription<\n const TOptions extends CapabilitySWRSubscriptionConfiguration<TCall>,\n >(\n input: CapabilityInput<TCall>,\n options: TOptions,\n ): readonly [\n key: CapabilitySWRKey,\n subscriber: SWRSubscription<\n CapabilitySWRKey,\n CapabilityOutput<TCall>,\n Error\n >,\n options: TOptions,\n ];\n };\n\ntype SWRNode<TValue> =\n TValue extends CapabilityCall\n ? AppCapabilityIsLive<TValue> extends true\n ? SWRLiveCapability<TValue>\n : SWRCapability<TValue>\n : TValue extends object\n ? {\n readonly [TKey in Extract<keyof TValue, string> as\n TValue[TKey] extends AppCapabilityReference\n ? TValue[TKey] extends CapabilityCall ? TKey : never\n : TKey]: SWRNode<TValue[TKey]>;\n }\n : never;\n\nexport type SWRApp<TApp extends object> = SWRNode<TApp>;\n\nexport function createSWR<const TApp extends object>(\n app: TApp,\n options: {\n readonly keyPrefix?: readonly unknown[];\n } = {},\n): SWRApp<TApp> {\n const keyPrefix = Object.freeze([...(options.keyPrefix ?? [\"capable\"])]);\n\n const callableAt = (path: readonly string[]): CapabilityCall => {\n let current: unknown = app;\n for (const segment of path) {\n current = (current as Record<string, unknown>)[segment];\n }\n return current as CapabilityCall;\n };\n\n const capabilityKey = (\n path: readonly string[],\n input?: unknown,\n ): CapabilitySWRKey => Object.freeze([\n ...keyPrefix,\n ...path,\n ...(input === undefined ? [] : [input]),\n ]) as CapabilitySWRKey;\n\n const withOptions = (\n key: CapabilitySWRKey,\n operation: (...args: any[]) => unknown,\n hookOptions: unknown,\n ): readonly unknown[] => hookOptions === undefined\n ? [key, operation]\n : [key, operation, hookOptions];\n\n const proxy = (path: readonly string[]): unknown =>\n new Proxy({}, {\n get(_target, key) {\n if (key === \"then\") return undefined;\n if (key === \"key\") {\n return (input?: unknown) => capabilityKey(path, input);\n }\n if (key === \"swr\") {\n return (input: unknown, swrOptions?: unknown) => withOptions(\n capabilityKey(path, input),\n () => callableAt(path)(input),\n swrOptions,\n );\n }\n if (key === \"mutation\") {\n return (mutationOptions?: unknown) => withOptions(\n capabilityKey(path),\n (_key: CapabilitySWRKey, { arg }: { readonly arg?: unknown }) =>\n callableAt(path)(arg),\n mutationOptions,\n );\n }\n if (key === \"subscription\") {\n return (input: unknown, subscriptionOptions?: unknown) => withOptions(\n capabilityKey(path, input),\n (\n _key: CapabilitySWRKey,\n { next }: {\n readonly next: (error?: Error | null, data?: unknown) => void;\n },\n ) => {\n const controller = new AbortController();\n\n void (async () => {\n try {\n for await (const output of subscribeCall(\n callableAt(path),\n input,\n { signal: controller.signal },\n )) {\n next(null, output);\n }\n } catch (error) {\n if (!controller.signal.aborted) {\n next(toError(error));\n }\n }\n })();\n\n return () => controller.abort();\n },\n subscriptionOptions,\n );\n }\n if (typeof key !== \"string\") return undefined;\n return proxy([...path, key]);\n },\n });\n\n return proxy([]) as SWRApp<TApp>;\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n"],"mappings":";;AAiBA,MAAM,gBAAgB;AA+HtB,SAAgB,UACd,KACA,UAEI,CAAC,GACS;CACd,MAAM,YAAY,OAAO,OAAO,CAAC,GAAI,QAAQ,aAAa,CAAC,SAAS,CAAE,CAAC;CAEvE,MAAM,cAAc,SAA4C;EAC9D,IAAI,UAAmB;EACvB,KAAK,MAAM,WAAW,MACpB,UAAW,QAAoC;EAEjD,OAAO;CACT;CAEA,MAAM,iBACJ,MACA,UACqB,OAAO,OAAO;EACnC,GAAG;EACH,GAAG;EACH,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,CAAC,KAAK;CACvC,CAAC;CAED,MAAM,eACJ,KACA,WACA,gBACuB,gBAAgB,KAAA,IACrC,CAAC,KAAK,SAAS,IACf;EAAC;EAAK;EAAW;CAAW;CAEhC,MAAM,SAAS,SACb,IAAI,MAAM,CAAC,GAAG,EACZ,IAAI,SAAS,KAAK;EAChB,IAAI,QAAQ,QAAQ,OAAO,KAAA;EAC3B,IAAI,QAAQ,OACV,QAAQ,UAAoB,cAAc,MAAM,KAAK;EAEvD,IAAI,QAAQ,OACV,QAAQ,OAAgB,eAAyB,YAC/C,cAAc,MAAM,KAAK,SACnB,WAAW,IAAI,CAAC,CAAC,KAAK,GAC5B,UACF;EAEF,IAAI,QAAQ,YACV,QAAQ,oBAA8B,YACpC,cAAc,IAAI,IACjB,MAAwB,EAAE,UACzB,WAAW,IAAI,CAAC,CAAC,GAAG,GACtB,eACF;EAEF,IAAI,QAAQ,gBACV,QAAQ,OAAgB,wBAAkC,YACxD,cAAc,MAAM,KAAK,IAEvB,MACA,EAAE,WAGC;GACH,MAAM,aAAa,IAAI,gBAAgB;GAEvC,CAAM,YAAY;IAChB,IAAI;KACF,WAAW,MAAM,UAAU,cACzB,WAAW,IAAI,GACf,OACA,EAAE,QAAQ,WAAW,OAAO,CAC9B,GACE,KAAK,MAAM,MAAM;IAErB,SAAS,OAAO;KACd,IAAI,CAAC,WAAW,OAAO,SACrB,KAAK,QAAQ,KAAK,CAAC;IAEvB;GACF,EAAA,CAAG;GAEH,aAAa,WAAW,MAAM;EAChC,GACA,mBACF;EAEF,IAAI,OAAO,QAAQ,UAAU,OAAO,KAAA;EACpC,OAAO,MAAM,CAAC,GAAG,MAAM,GAAG,CAAC;CAC7B,EACF,CAAC;CAEH,OAAO,MAAM,CAAC,CAAC;AACjB;AAEA,SAAS,QAAQ,OAAuB;CACtC,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACjE"}
|
package/docs/CONTEXT.md
CHANGED
|
@@ -2,24 +2,27 @@
|
|
|
2
2
|
|
|
3
3
|
**Capability**: one typed capability with a canonical string ID, optional
|
|
4
4
|
object-shaped input, optional output schema, declared errors, middleware,
|
|
5
|
-
optional effect,
|
|
6
|
-
|
|
5
|
+
optional effect, a handler and/or subscriber, open surface metadata, and optional
|
|
6
|
+
`toPresentation`. A handler alone is unary; a handler with a subscriber provides
|
|
7
|
+
replacement snapshots; a subscriber alone provides individual events.
|
|
7
8
|
It has no canonical HTTP method or path.
|
|
8
9
|
|
|
9
10
|
**App Definition**: immutable named object nesting created by `defineApp()`
|
|
10
11
|
whose leaves are Capabilities. It carries no context provider or execution
|
|
11
|
-
placement.
|
|
12
|
+
placement. It can contribute app-wide middleware and declared errors. Its paths
|
|
13
|
+
drive navigational interfaces and surface defaults.
|
|
12
14
|
|
|
13
15
|
**Group**: an anonymous decorated subtree created with `group()`. It has no ID.
|
|
14
16
|
It contributes semantic middleware and errors and exposes its metadata ancestry
|
|
15
17
|
to surface compilers.
|
|
16
18
|
|
|
17
|
-
**Capability ID**: canonical execution and transport identity.
|
|
18
|
-
within an Application.
|
|
19
|
+
**Capability ID**: canonical execution and transport identity. One ID has one
|
|
20
|
+
execution owner within an Application.
|
|
19
21
|
|
|
20
|
-
**Application path**:
|
|
22
|
+
**Application path**: an object path to a Capability, such as
|
|
21
23
|
`admin.users.create`. It drives direct App calls, CLI, and MCP navigation but
|
|
22
|
-
is not the Capability's identity.
|
|
24
|
+
is not the Capability's identity. One Capability may have multiple paths when
|
|
25
|
+
the same App runtime is deliberately composed under aliases.
|
|
23
26
|
|
|
24
27
|
**Effect**: optional `read`, `write`, or `destructive` intent. HTTP may derive
|
|
25
28
|
GET only from `read`; MCP may derive safety hints. Absence means unknown.
|
|
@@ -40,22 +43,30 @@ Capability declares context, local consumers must provide it through
|
|
|
40
43
|
Definition derives any required context type from its Capability tree but
|
|
41
44
|
stores no provider.
|
|
42
45
|
|
|
43
|
-
**App**: a context-erased typed
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
46
|
+
**Executable App**: a context-erased typed tree of callable operations and
|
|
47
|
+
event references in which every Capability has an execution owner and the
|
|
48
|
+
caller has no unresolved provider obligation. `createApp()` closes over direct
|
|
49
|
+
execution and its provider; `createRemoteApp()` wraps a transport without
|
|
50
|
+
performing I/O. Remote manifest discovery is lazy, validated, and cached.
|
|
51
|
+
`composeApps()` returns the same shape. The public TypeScript type remains
|
|
52
|
+
`App`. A low-level
|
|
47
53
|
`manifest() + call() + subscribe()` runtime lives behind internal symbols for
|
|
48
54
|
surfaces and composition.
|
|
49
55
|
|
|
50
|
-
**Application
|
|
51
|
-
|
|
52
|
-
|
|
56
|
+
**Application composition**: strict tree-shaped combination through
|
|
57
|
+
`composeApps()`. App arguments contribute at the root; object keys place Apps
|
|
58
|
+
beneath navigational branches. Calls dispatch by immutable Capability ID. One
|
|
59
|
+
ID has exactly one execution owner but may appear at multiple paths through
|
|
60
|
+
aliases. Conflicting ownership, path, and leaf/subtree conflicts fail when the
|
|
61
|
+
composed manifest first resolves.
|
|
53
62
|
|
|
54
63
|
**Capable transport**: an asynchronous boundary exposing `manifest()`,
|
|
55
64
|
`call()`, and `subscribe()`. `createRemoteApp()` wraps and caches it without
|
|
56
65
|
turning module evaluation into a network boundary. Its HTTP client/server
|
|
57
66
|
encoding lives in `@capable/fetch` as server plumbing, separate from authored
|
|
58
|
-
HTTP APIs and from transport-neutral App semantics.
|
|
67
|
+
HTTP APIs and from transport-neutral App semantics. Its versioned value codec
|
|
68
|
+
preserves runtime values across calls, errors, and subscriptions; custom codecs
|
|
69
|
+
must identify themselves and match on both peers.
|
|
59
70
|
|
|
60
71
|
**HTTP projection**: a server mount that derives routes from the Application
|
|
61
72
|
tree and `effect`, then applies optional `meta.http` overrides. It also owns
|
|
@@ -73,7 +84,7 @@ boundary. Omitted include means all; exclude wins.
|
|
|
73
84
|
`selectApp()` applies that policy before passing an App to a
|
|
74
85
|
surface.
|
|
75
86
|
|
|
76
|
-
**Canonical output**: handler
|
|
87
|
+
**Canonical output**: a handler result or subscription value after optional output validation. It is the
|
|
77
88
|
only semantic result.
|
|
78
89
|
|
|
79
90
|
**Presentation**: an optional, ordered, JSON-serializable sequence of Markdown,
|
|
@@ -87,6 +98,11 @@ declared errors, middleware, placement, and representations. Every emitted
|
|
|
87
98
|
item is a complete replacement Canonical Output. `subscribe(appCall, input)`
|
|
88
99
|
keeps App navigation collision-free.
|
|
89
100
|
|
|
101
|
+
**Event subscription**: a pull-based execution mode on a `read` Capability with
|
|
102
|
+
`subscribe` and no `handler`. It yields individual events, may complete without
|
|
103
|
+
yielding, and has no unary operation. `toPresentation` describes each event;
|
|
104
|
+
the CLI appends it. Event subscriptions do not imply buffering or replay.
|
|
105
|
+
|
|
90
106
|
## Invariants
|
|
91
107
|
|
|
92
108
|
- `@capable/core` depends on no transport, host, CLI, MCP, or HTTP package.
|
|
@@ -97,17 +113,22 @@ keeps App navigation collision-free.
|
|
|
97
113
|
- App Definitions never carry context providers.
|
|
98
114
|
- A context-free `createApp()` needs no provider; a contextual one satisfies
|
|
99
115
|
and erases only its own context before merging.
|
|
100
|
-
- A Capability
|
|
116
|
+
- A Capability ID has exactly one execution owner in an Application. Reusing
|
|
117
|
+
that App runtime at another path creates an alias; another runtime claiming
|
|
118
|
+
the same ID is invalid.
|
|
101
119
|
- Handlers receive only `{ input, context, signal }`.
|
|
102
120
|
- Semantic middleware and declared errors execute identically for every
|
|
103
121
|
surface.
|
|
104
|
-
- Subscription input is parsed once, every
|
|
122
|
+
- Subscription input is parsed once, every emitted value is output-validated,
|
|
105
123
|
middleware encloses the complete iterator lifetime, and cancellation aborts
|
|
106
124
|
before iterator cleanup.
|
|
125
|
+
- Opening a transport subscription parses input, resolves context, enters
|
|
126
|
+
middleware, and invokes the subscriber before its promise resolves. An event
|
|
127
|
+
transport awaits that promise before committing its streaming response.
|
|
128
|
+
Async-generator bodies still start on the first iterator pull.
|
|
107
129
|
- Platform adapters only translate their host to Fetch Request/Response.
|
|
108
130
|
- HTTP is a projection and deployment concern, not Capability identity.
|
|
109
|
-
-
|
|
110
|
-
|
|
111
|
-
semantics.
|
|
131
|
+
- Patches, buffering, replay, resumption, delivery guarantees, and reconnection
|
|
132
|
+
policy are not subscription semantics.
|
|
112
133
|
- Idempotence, approvals, and durable tasks remain deferred until a concrete
|
|
113
134
|
consumer proves their contract.
|
package/docs/README.md
CHANGED
|
@@ -8,6 +8,9 @@ the npm package is packed. It matches the installed package version.
|
|
|
8
8
|
Do not rely on remembered Capable APIs. Read the relevant bundled guide and
|
|
9
9
|
inspect `../src/` when you need a detail the guides do not cover.
|
|
10
10
|
|
|
11
|
+
Before upgrading, read [the versioned changelog](../CHANGELOG.md). Apply all
|
|
12
|
+
entries after the installed version through the target version, oldest first.
|
|
13
|
+
|
|
11
14
|
Start here:
|
|
12
15
|
|
|
13
16
|
1. [Introduction](./site/introduction.mdx)
|
package/docs/internal/README.md
CHANGED
|
@@ -10,7 +10,10 @@ docs:dev`). This directory is for people working *on* Capable.
|
|
|
10
10
|
| [architecture.md](./architecture.md) | How the packages are layered and why |
|
|
11
11
|
| [adr/](./adr) | Accepted decisions |
|
|
12
12
|
| [implementation-friction.md](./implementation-friction.md) | Live log of awkward or leaky implementation work |
|
|
13
|
+
| [feedback/v-ray/](./feedback/v-ray/README.md) | Reproduced migration feedback, compiler matrix, and prioritized proposals |
|
|
13
14
|
| [why-capable.md](./why-capable.md) | The original internal argument for the project |
|
|
14
15
|
|
|
15
16
|
If a change contradicts CONTEXT.md, change CONTEXT.md in the same commit or do
|
|
16
17
|
not make the change.
|
|
18
|
+
|
|
19
|
+
See [Releases](./releases.md) for changesets, alpha publishing, and migration notes.
|
|
@@ -19,6 +19,6 @@ not enter the handler contract or canonical output.
|
|
|
19
19
|
App Definitions do not own context provision. `createApp()` satisfies one
|
|
20
20
|
definition's context and erases it into a directly callable App;
|
|
21
21
|
`createRemoteApp()` returns the same callable shape while lazily discovering
|
|
22
|
-
and validating transport execution. `
|
|
22
|
+
and validating transport execution. `composeApps()` combines these
|
|
23
23
|
context-erased Apps, so unrelated local contexts never become one giant merged
|
|
24
24
|
context.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
---
|
|
2
|
+
status: accepted
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
# Version the Capable transport value codec
|
|
6
|
+
|
|
7
|
+
The private Capable HTTP transport encodes calls, results, declared-error data,
|
|
8
|
+
and subscription frames with a versioned value codec. Its default codec is
|
|
9
|
+
`capable.rich-json.v1`, implemented with an isolated SuperJSON instance. This
|
|
10
|
+
preserves runtime values such as `Date` without teaching `@capable/core` about a
|
|
11
|
+
wire format or maintaining a home-grown metadata protocol.
|
|
12
|
+
|
|
13
|
+
The client sends the codec ID and the server repeats it in the
|
|
14
|
+
`capable-codec` header. Peers reject a missing or different ID instead of
|
|
15
|
+
silently interpreting another encoding. Changing the default wire format
|
|
16
|
+
requires a new codec ID and Capable manifest protocol version.
|
|
17
|
+
|
|
18
|
+
`defineProtocolCodec()` is the extension seam. A custom codec is configured on
|
|
19
|
+
both `protocol({ codec })` and `createHttpTransport({ codec })`; Capable owns the
|
|
20
|
+
HTTP and SSE framing while the codec owns only JSON-compatible value
|
|
21
|
+
transformation.
|
|
22
|
+
|
|
23
|
+
Authored HTTP routes and OpenAPI remain ordinary JSON projections. Their
|
|
24
|
+
interoperability contract is separate from the private remote-App protocol.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# Capability references and presentation customization
|
|
2
|
+
|
|
3
|
+
Status: accepted
|
|
4
|
+
|
|
5
|
+
An Executable App, one of its subtrees, or one of its Capability references may
|
|
6
|
+
appear in `composeApps()`. The source runtime and path identify executable
|
|
7
|
+
behavior; the destination path identifies navigation. These are one placement
|
|
8
|
+
operation with the App root represented by an empty source path. Composition
|
|
9
|
+
does not reconstruct a core Capability or add an execution lifecycle. Local
|
|
10
|
+
definitions must be bound with `createApp()` first.
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
const app = composeApps({
|
|
14
|
+
stop: customize(desktop.plugins.stop, {
|
|
15
|
+
description: "Stop a running desktop instance.",
|
|
16
|
+
meta: { cli: { positional: ["instanceId"] } },
|
|
17
|
+
}),
|
|
18
|
+
debug: { status: desktop.plugins.status, screenshot: local.screenshot },
|
|
19
|
+
});
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
`customize()` returns a non-callable Capability placement. It accepts title,
|
|
23
|
+
description, and surface metadata registered in the global
|
|
24
|
+
`CapableCustomizationMeta` interface.
|
|
25
|
+
CLI and MCP opt in initially. It never changes schemas, effect, errors,
|
|
26
|
+
middleware, context, handlers, subscriptions, or output presentation renderers.
|
|
27
|
+
A standalone function avoids reserving `with` or another command name in the
|
|
28
|
+
lazy App proxy.
|
|
29
|
+
|
|
30
|
+
The manifest retains the authored capability contract. Individual reference
|
|
31
|
+
placements carry a `customization.navigation: "destination"` marker, plus any
|
|
32
|
+
overrides supplied by the caller. CLI/MCP then derive names from the curated
|
|
33
|
+
path unless explicitly overridden in that field. A placed App or Group gets its
|
|
34
|
+
outer name from the destination key; navigation and presentation inside that
|
|
35
|
+
subtree remain authored. Alias contract comparison ignores path and
|
|
36
|
+
customization, but still compares original metadata. Surfaces
|
|
37
|
+
explicitly read display fields using `getCapabilityDisplay()`; executors and
|
|
38
|
+
policy callbacks continue to receive the original contract. HTTP/OpenAPI still
|
|
39
|
+
derive from core definitions and do not consume these overrides.
|
|
40
|
+
|
|
41
|
+
`customization` is an optional field in the v4 manifest. Clients may ignore it
|
|
42
|
+
and continue to execute the source contract, but must understand the field to
|
|
43
|
+
display overrides or compare customized aliases correctly.
|
|
44
|
+
|
|
45
|
+
Overrides are copied as immutable JSON. An outer customization wins for each
|
|
46
|
+
supplied title, description, or metadata namespace. Namespaces are replaced,
|
|
47
|
+
not recursively merged. A leaf reference carries its own metadata but not its
|
|
48
|
+
source groups' presentation ancestry. Backend group middleware and errors still
|
|
49
|
+
apply because calls retain the source runtime.
|
|
50
|
+
|
|
51
|
+
The ownership rule follows the terminal execution transport. Referencing the
|
|
52
|
+
same operation through nested compositions or multiple wrappers over one
|
|
53
|
+
transport creates aliases. Independently bound local Apps and distinct
|
|
54
|
+
transports cannot claim the same ID. Identical placements are deduplicated;
|
|
55
|
+
different customizations at the same path conflict. All fields needed for
|
|
56
|
+
display survive manifest serialization and nesting. Offline discovery is the
|
|
57
|
+
transport's responsibility, not a separate composition cache API.
|
|
58
|
+
|
|
59
|
+
`selectApp()` remains useful for filtering a tree at its existing paths. Curated
|
|
60
|
+
reference trees serve a different purpose: explicit selection and relocation.
|
|
61
|
+
|
|
62
|
+
MCP customization includes the namespace's annotation hints. These are surface
|
|
63
|
+
hints; `effect` remains authoritative for read-only and destructive annotations.
|
|
64
|
+
|
|
65
|
+
Composition changes navigation and opted-in presentation only. It never adds
|
|
66
|
+
middleware, errors, context requirements, providers, or another execution
|
|
67
|
+
lifecycle. A local wrapper around a remote invocation is a new Capability with
|
|
68
|
+
its own ID and schema; its handler may call the remote reference explicitly.
|
|
@@ -8,7 +8,7 @@ Capability definitions
|
|
|
8
8
|
│
|
|
9
9
|
▼
|
|
10
10
|
App Definition ──────────────► createServer(definition, { mounts })
|
|
11
|
-
│ ├─ protocol()
|
|
11
|
+
│ ├─ protocol() /~capable/* manifest, call, subscribe
|
|
12
12
|
│ ├─ http() /api/* routes + /openapi.json
|
|
13
13
|
│ └─ mcp() /mcp Streamable HTTP tools
|
|
14
14
|
│ │
|
|
@@ -17,10 +17,10 @@ App Definition ──────────────► createServer(defini
|
|
|
17
17
|
└─ createRemoteApp(transport)
|
|
18
18
|
│ lazy manifest discovery
|
|
19
19
|
│
|
|
20
|
-
|
|
20
|
+
composeApps / selectApp
|
|
21
21
|
│
|
|
22
22
|
▼
|
|
23
|
-
App (typed
|
|
23
|
+
App (typed Capability reference tree)
|
|
24
24
|
│
|
|
25
25
|
┌─────────────┼──────────────┬────────────────────┐
|
|
26
26
|
▼ ▼ ▼ ▼
|
|
@@ -40,13 +40,13 @@ as `capable-kit/server`, `capable-kit/next`, and `capable-kit/swr`.
|
|
|
40
40
|
| ------------------- | -------------------------------------------------------------------- |
|
|
41
41
|
| `capable-kit` | Public facade and the user-installed `cap` command |
|
|
42
42
|
| `@capable/core` | Authoring, tree composition, validation, middleware, errors, execution |
|
|
43
|
-
| `@capable/app` |
|
|
43
|
+
| `@capable/app` | Typed local and remote Apps, composition, selection, manifests |
|
|
44
44
|
| `@capable/fetch` | Capable transport encoding and the HTTP/OpenAPI projection |
|
|
45
45
|
| `@capable/server` | Fetch server composition and protocol mounts |
|
|
46
46
|
| `@capable/cli` | Command derivation, parsing, help, and rendering |
|
|
47
47
|
| `@capable/mcp` | Tool derivation and the Streamable HTTP mount |
|
|
48
48
|
| `@capable/ai-sdk` | Typed AI SDK v7 tool projection |
|
|
49
|
-
| `@capable/eve` | Native
|
|
49
|
+
| `@capable/eve` | Native Eve tool projection and caller-scoped agent lifecycle Apps |
|
|
50
50
|
| `@capable/react-query` | Query keys, query options, mutations, live queries |
|
|
51
51
|
| `@capable/swr` | SWR keys, fetchers, mutations, and subscriptions |
|
|
52
52
|
| `@capable/next` | Method-export translation for the App Router |
|
|
@@ -58,7 +58,7 @@ and the complete execution lifecycle, `application.ts` owns Groups, App
|
|
|
58
58
|
Definitions, placement, and uniqueness. Keeping execution beside authoring
|
|
59
59
|
preserves the Capability seam from [ADR-0001](./adr/0001-capability-is-the-semantic-boundary.md).
|
|
60
60
|
|
|
61
|
-
The App package is transport-neutral: `runtime.ts` owns
|
|
61
|
+
The App package is transport-neutral: `runtime.ts` owns typed local and
|
|
62
62
|
remote Apps, `composition.ts` owns merge and selection, `manifest.ts` owns
|
|
63
63
|
manifest construction and tree invariants, and `index.ts` is only a facade.
|
|
64
64
|
|
|
@@ -73,10 +73,10 @@ interface ApplicationTransport {
|
|
|
73
73
|
output: unknown;
|
|
74
74
|
presentation?: readonly PresentationPart[];
|
|
75
75
|
}>;
|
|
76
|
-
subscribe({ id, input, signal, presentation }): AsyncIterableIterator<{
|
|
76
|
+
subscribe({ id, input, signal, presentation }): Promise<AsyncIterableIterator<{
|
|
77
77
|
output: unknown;
|
|
78
78
|
presentation?: readonly PresentationPart[];
|
|
79
|
-
}
|
|
79
|
+
}>>;
|
|
80
80
|
}
|
|
81
81
|
```
|
|
82
82
|
|
|
@@ -98,26 +98,71 @@ Its HTTP encoding lives in `@capable/fetch` — `createHttpTransport()` and
|
|
|
98
98
|
`createProtocolHandler()` — giving request, response, and SSE encoding one home,
|
|
99
99
|
separate from authored HTTP APIs and from transport-neutral App semantics.
|
|
100
100
|
|
|
101
|
-
|
|
101
|
+
That private protocol defaults to the versioned `capable.rich-json.v1` codec,
|
|
102
|
+
which preserves runtime values such as `Date` in inputs, outputs, declared-error
|
|
103
|
+
data, and subscription values. The codec ID crosses the boundary in the
|
|
104
|
+
`capable-codec` header, so mismatched peers fail before decoding. A deployment
|
|
105
|
+
can replace the value encoding without replacing HTTP or SSE framing:
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
import {
|
|
109
|
+
createHttpTransport,
|
|
110
|
+
defineProtocolCodec,
|
|
111
|
+
} from "capable-kit/http";
|
|
112
|
+
import { createServer, protocol } from "capable-kit/server";
|
|
113
|
+
|
|
114
|
+
const codec = defineProtocolCodec({
|
|
115
|
+
id: "acme.protocol-values.v1",
|
|
116
|
+
encode: (value) => acmeValues.encode(value),
|
|
117
|
+
decode: (value) => acmeValues.decode(value),
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
const server = createServer(definition, {
|
|
121
|
+
mounts: [protocol({ codec })],
|
|
122
|
+
});
|
|
123
|
+
const transport = createHttpTransport({
|
|
124
|
+
url: "https://api.example.com/~capable/",
|
|
125
|
+
codec,
|
|
126
|
+
});
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Only the Capable protocol uses this codec. Authored HTTP routes and their
|
|
130
|
+
OpenAPI contracts remain ordinary JSON.
|
|
131
|
+
|
|
132
|
+
Subscriptions are encoded at `POST /~capable/subscribe/:id` as SSE. Errors before
|
|
102
133
|
the first replacement are ordinary HTTP errors; a terminal error after streaming
|
|
103
|
-
began uses a typed SSE error frame.
|
|
134
|
+
began uses a typed SSE error frame. Event-only subscriptions establish without
|
|
135
|
+
waiting for their first value, flushing an SSE comment that does not become a
|
|
136
|
+
canonical event. Input parsing, context resolution, middleware entry, subscriber
|
|
137
|
+
invocation, and AsyncIterable validation complete before that response is
|
|
138
|
+
committed, so their failures retain ordinary HTTP statuses. Failures inside an
|
|
139
|
+
async-generator body happen after establishment and use typed SSE error frames.
|
|
140
|
+
|
|
141
|
+
Manifest protocol `capable.capabilities.v4` requires an `execution` field on each
|
|
142
|
+
Capability: `unary`, `live`, or `events`. This replaces the optional
|
|
143
|
+
`subscription: { mode: "replace" }` field. Clients and servers must upgrade
|
|
144
|
+
together; the value codec remains `capable.rich-json.v1`.
|
|
104
145
|
|
|
105
146
|
## Composition
|
|
106
147
|
|
|
107
|
-
`
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
148
|
+
`composeApps(a, b, { remote })` places executable Apps, their subtrees, and
|
|
149
|
+
individual Capability references into one tree. An App is the source subtree at
|
|
150
|
+
its root; a Group or Capability reference uses a deeper source path. App and
|
|
151
|
+
subtree arguments contribute their children at the root; object keys select
|
|
152
|
+
destination branches. Composition adds navigation and opted-in presentation,
|
|
153
|
+
with no semantic middleware or provider lifecycle. It returns synchronously and
|
|
154
|
+
resolves its inputs together when its complete manifest is first needed. Path
|
|
155
|
+
and ID conflicts therefore fail at that discovery boundary. A direct call under
|
|
156
|
+
a named branch resolves only placements that can contribute to that path:
|
|
112
157
|
|
|
113
158
|
```ts
|
|
114
|
-
const remote = createRemoteApp<
|
|
115
|
-
const app =
|
|
116
|
-
remote,
|
|
159
|
+
const remote = createRemoteApp<AppDefinition>(transport);
|
|
160
|
+
const app = composeApps(
|
|
117
161
|
createApp(localDefinition, { context: createLocalContext }),
|
|
162
|
+
{ remote, tools: remote.admin },
|
|
118
163
|
);
|
|
119
164
|
|
|
120
|
-
await app.
|
|
165
|
+
await app.remote.todos.list();
|
|
121
166
|
```
|
|
122
167
|
|
|
123
168
|
## Surface compilation
|