capable-kit 0.0.1-alpha.3 → 0.0.1-alpha.4
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/bin.mjs +14 -13
- package/dist/bin.mjs.map +1 -1
- package/dist/http.d.mts +1 -1
- package/dist/http.mjs +1 -1
- package/dist/{index-AqKbVZ8Z.d.mts → index-DCrxWCTv.d.mts} +2 -2
- package/dist/{index-B2ru1zGQ.d.mts → index-DJ--zcWG.d.mts} +4 -4
- package/dist/mcp.d.mts +1 -1
- package/dist/mcp.mjs +1 -1
- package/dist/{mount--YHrgRHJ.mjs → mount-BEBJ2Tss.mjs} +13 -19
- package/dist/mount-BEBJ2Tss.mjs.map +1 -0
- package/dist/runtime-support.d.mts +1 -1
- package/dist/runtime-support.mjs +5 -5
- package/dist/runtime-support.mjs.map +1 -1
- package/dist/server.d.mts +2 -2
- package/dist/server.mjs +2 -2
- package/dist/{src-DtSY5fzY.mjs → src-ChDFqZaE.mjs} +6 -6
- package/dist/{src-DtSY5fzY.mjs.map → src-ChDFqZaE.mjs.map} +1 -1
- package/dist/{src-DX2xrplP.mjs → src-D9pLpfeO.mjs} +2 -2
- package/dist/src-D9pLpfeO.mjs.map +1 -0
- package/docs/CONTEXT.md +108 -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 +126 -0
- package/docs/internal/capability-first-model.md +154 -0
- package/docs/internal/implementation-friction.md +674 -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 +75 -0
- package/docs/site/concepts/capabilities.mdx +249 -0
- package/docs/site/concepts/errors.mdx +93 -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 +142 -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 +293 -0
- package/docs/site/reference/packages-and-entry-points.mdx +70 -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 +97 -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/package.test.ts +101 -0
- package/dist/mount--YHrgRHJ.mjs.map +0 -1
- package/dist/src-DX2xrplP.mjs.map +0 -1
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "Surfaces"
|
|
3
|
+
description: "A surface is a projection of an app. You choose which ones exist."
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
import { DocsPage, docMetadata } from "../_components/docs-page";
|
|
7
|
+
|
|
8
|
+
export const metadata = docMetadata("/surfaces", frontmatter);
|
|
9
|
+
|
|
10
|
+
<DocsPage href="/surfaces" frontmatter={frontmatter}>
|
|
11
|
+
|
|
12
|
+
Surfaces are the only place where presentation lives. They read the app manifest and the metadata relevant to them, and they never change what a capability means.
|
|
13
|
+
|
|
14
|
+
## Two kinds of surface [#kinds]
|
|
15
|
+
|
|
16
|
+
Some surfaces are network mounts on a server. Others are projections of an app inside a process. Both consume the same app.
|
|
17
|
+
|
|
18
|
+
```ts title="capable.server.ts"
|
|
19
|
+
import { mcp } from "capable-kit/mcp";
|
|
20
|
+
import { protocol, createServer, http } from "capable-kit/server";
|
|
21
|
+
import definition from "./capable.app";
|
|
22
|
+
|
|
23
|
+
export default createServer(definition, {
|
|
24
|
+
context: ({ request }) => contextFromRequest(request),
|
|
25
|
+
mounts: [
|
|
26
|
+
protocol({ path: "/_capable" }),
|
|
27
|
+
http({ path: "/api", openapiPath: "/openapi.json" }),
|
|
28
|
+
mcp({ path: "/mcp" }),
|
|
29
|
+
],
|
|
30
|
+
});
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
A projection needs no server at all. It takes an executable app and returns commands, tools, or query options.
|
|
34
|
+
|
|
35
|
+
```ts title="tools.ts"
|
|
36
|
+
import { createCli } from "capable-kit/cli";
|
|
37
|
+
import { createAiSdkTools } from "capable-kit/ai-sdk";
|
|
38
|
+
import { createEveTools } from "capable-kit/eve";
|
|
39
|
+
import { createReactQuery } from "@capable/react-query";
|
|
40
|
+
|
|
41
|
+
createCli(app); // process-level command tree
|
|
42
|
+
await createAiSdkTools(app); // typed AI SDK tools
|
|
43
|
+
createEveTools(app); // durable in-process agent tools
|
|
44
|
+
createReactQuery(app); // query keys and options for a UI
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Choosing surfaces [#choose]
|
|
48
|
+
|
|
49
|
+
| Surface | Use it when | Entry point |
|
|
50
|
+
| --- | --- | --- |
|
|
51
|
+
| [TypeScript](/surfaces/typescript) | Code calls the capability directly, here or over a transport | `capable` |
|
|
52
|
+
| [HTTP and OpenAPI](/surfaces/http) | Third parties or other services call you | `capable/server` |
|
|
53
|
+
| Capable transport | A Capable client, CLI, or another app calls you | `capable/server` |
|
|
54
|
+
| [CLI](/surfaces/cli) | People or scripts drive it from a terminal | `capable/cli` |
|
|
55
|
+
| [MCP](/surfaces/mcp) | External agents connect over the network | `capable/mcp` |
|
|
56
|
+
| [Eve](/surfaces/eve) | An agent runs in your process | `capable/eve` |
|
|
57
|
+
| [AI SDK](/surfaces/ai-sdk) | An AI SDK model or agent calls your app | `capable/ai-sdk` |
|
|
58
|
+
| [React Query](/surfaces/react-query) | A React UI reads and mutates the app | `@capable/react-query` |
|
|
59
|
+
|
|
60
|
+
> **Nothing is implicit**
|
|
61
|
+
>
|
|
62
|
+
> A capability does not become a route, a command, or a tool until a surface is mounted or projected. Use [selectApp()](/patterns/composition) when a surface should see less than the whole app.
|
|
63
|
+
|
|
64
|
+
## Metadata belongs to one surface [#metadata]
|
|
65
|
+
|
|
66
|
+
`meta.http` only affects HTTP, `meta.cli` only affects the CLI, and so on. Metadata can rename, reroute, or hide a capability on its surface; it can never change validation, errors, or the result. The full list is in the [metadata reference](/reference/metadata).
|
|
67
|
+
|
|
68
|
+
## Surface guides [#pages]
|
|
69
|
+
|
|
70
|
+
- [**TypeScript**](/surfaces/typescript) — Typed calls, cancellation, errors, and streaming reads.
|
|
71
|
+
- [**HTTP and OpenAPI**](/surfaces/http) — Derived routes, authored routes, and the generated document.
|
|
72
|
+
- [**CLI**](/surfaces/cli) — Commands, flags, help, and remote invocation.
|
|
73
|
+
- [**MCP**](/surfaces/mcp) — Tools, names, and safety hints for external agents.
|
|
74
|
+
- [**AI SDK**](/surfaces/ai-sdk) — Typed tools for generateText, streamText, and agents.
|
|
75
|
+
- [**Eve**](/surfaces/eve) — Native in-process tools with approvals.
|
|
76
|
+
- [**React Query**](/surfaces/react-query) — Query keys, mutations, and live queries.
|
|
77
|
+
|
|
78
|
+
</DocsPage>
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "Why Capable"
|
|
3
|
+
description: "What it costs to hand-write the same capability for every interface, and what changes when you stop."
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
import { DocsPage, docMetadata } from "../_components/docs-page";
|
|
7
|
+
|
|
8
|
+
export const metadata = docMetadata("/why-capable", frontmatter);
|
|
9
|
+
|
|
10
|
+
<DocsPage href="/why-capable" frontmatter={frontmatter}>
|
|
11
|
+
|
|
12
|
+
One capability, four callers: the product UI, an HTTP API, a terminal, and an agent. Capable exists because writing that capability four times is the normal way to do it, and it does not hold up.
|
|
13
|
+
|
|
14
|
+
## One surface is not a product [#assumption]
|
|
15
|
+
|
|
16
|
+
Agents now take part in workflows that used to be clicks. Teams reach for a terminal for the things a dashboard is bad at. MCP turned "can another agent call this?" into a routine requirement.
|
|
17
|
+
|
|
18
|
+
So the interesting question is not how to ship the first interface. It is what the second and third cost you.
|
|
19
|
+
|
|
20
|
+
## The second surface is where it stalls [#cost]
|
|
21
|
+
|
|
22
|
+
Ask an AI for a todo app and you get a good Next.js app with no API in it. A server component reads the database, a server action writes to it, the session comes from a cookie, and the input shape lives in a form. That is reachable from a browser and from nowhere else.
|
|
23
|
+
|
|
24
|
+
```ts title="app/actions.ts"
|
|
25
|
+
// app/actions.ts — what you actually get from a prompt
|
|
26
|
+
"use server";
|
|
27
|
+
|
|
28
|
+
export async function createTodo(formData: FormData) {
|
|
29
|
+
const { userId } = await auth(); // cookie session
|
|
30
|
+
await db.insert(todos).values({
|
|
31
|
+
userId,
|
|
32
|
+
title: String(formData.get("title")), // no schema anywhere
|
|
33
|
+
});
|
|
34
|
+
revalidatePath("/todos");
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
A CLI is not a view of that app. It is a separate program on the far side of a network boundary, so "add a CLI" is really five tasks, and only the capable one is the CLI.
|
|
39
|
+
|
|
40
|
+
```ts title="by hand"
|
|
41
|
+
// 1. an API that did not exist before
|
|
42
|
+
export async function POST(request: Request) {
|
|
43
|
+
const { userId } = await authFromBearerToken(request); // 2. non-cookie auth
|
|
44
|
+
const input = TodoInput.parse(await request.json()); // 3. a schema, finally
|
|
45
|
+
return Response.json(await createTodo(userId, input));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// 4. the CLI, restating the same schema a second time
|
|
49
|
+
program
|
|
50
|
+
.command("create <title>")
|
|
51
|
+
.option("--due-date <date>")
|
|
52
|
+
.action(async (title, options) => {
|
|
53
|
+
const res = await fetch(`${baseUrl}/api/todos`, { /* ... */ });
|
|
54
|
+
if (!res.ok) printError(await res.json()); // 5. a second error format
|
|
55
|
+
});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
A command framework helps with the argument parsing and nothing else. You still extract the API, invent token auth, describe the input twice, and map errors twice. None of it is hard, which is the problem: it is a pile of low-information code that has to be redone whenever the capability changes. That is also why asking a generator for "a web app, a CLI, and an MCP server" gives you three things that disagree by the second change.
|
|
59
|
+
|
|
60
|
+
## Put the capability under the interfaces [#model]
|
|
61
|
+
|
|
62
|
+
In Capable the capability owns the semantics and each surface only decides how it is presented.
|
|
63
|
+
|
|
64
|
+
| Concern | Owner |
|
|
65
|
+
| --- | --- |
|
|
66
|
+
| Input, output, errors, middleware, handler | The capability |
|
|
67
|
+
| Execution placement and context | The app |
|
|
68
|
+
| Method, command name, tool name, query key | The surface |
|
|
69
|
+
| Requests, deployment, runtime | The host |
|
|
70
|
+
|
|
71
|
+
Because the capability is the API, there is nothing to extract when the second caller shows up. The whole CLI becomes the file below: commands, flags, help text, validation, and errors come from the same capabilities the HTTP surface serves, so a command cannot accept input the route rejects.
|
|
72
|
+
|
|
73
|
+
```ts title="cli.ts"
|
|
74
|
+
#!/usr/bin/env bun
|
|
75
|
+
import { createApp } from "capable-kit";
|
|
76
|
+
import { createCli } from "capable-kit/cli";
|
|
77
|
+
import definition from "./capable.app";
|
|
78
|
+
|
|
79
|
+
const app = createApp(definition, { context: createContext });
|
|
80
|
+
process.exit(await createCli(app, { invocationName: "todo" }).run(process.argv.slice(2)));
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Swap `createApp` for `createRemoteApp` and that same file drives a deployed server. The same definition is also the MCP server, the OpenAPI document, and the typed client.
|
|
84
|
+
|
|
85
|
+
## When not to use it [#tradeoffs]
|
|
86
|
+
|
|
87
|
+
- **One caller, forever.** A single webhook receiver is simpler as a plain route handler.
|
|
88
|
+
- **No schemas.** Ad-hoc payloads do not project into commands or tools.
|
|
89
|
+
- **No appetite for vocabulary.** Capabilities, apps, surfaces, and placement are concepts your team has to learn.
|
|
90
|
+
|
|
91
|
+
## Adopting it gradually [#adopt]
|
|
92
|
+
|
|
93
|
+
Capable is not a rewrite. Define one capability, mount it in the server you already run, add surfaces when you need them.
|
|
94
|
+
|
|
95
|
+
- [**Keep your host**](/hosting/next) — Mount a fetch handler in Next.js, Hono, H3, or Bun.
|
|
96
|
+
- [**Choose surfaces**](/surfaces) — Nothing is exposed until you mount or project it.
|
|
97
|
+
- [**Compose later**](/patterns/composition) — Merge local and remote apps once more than one exists.
|
|
98
|
+
|
|
99
|
+
</DocsPage>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "capable-kit",
|
|
3
|
-
"version": "0.0.1-alpha.
|
|
3
|
+
"version": "0.0.1-alpha.4",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
6
|
"cap": "dist/bin.mjs",
|
|
@@ -45,10 +45,20 @@
|
|
|
45
45
|
}
|
|
46
46
|
},
|
|
47
47
|
"files": [
|
|
48
|
-
"dist",
|
|
48
|
+
"dist/*.d.mts",
|
|
49
|
+
"dist/*.mjs",
|
|
50
|
+
"dist/*.mjs.map",
|
|
51
|
+
"docs",
|
|
49
52
|
"src",
|
|
50
53
|
"README.md"
|
|
51
54
|
],
|
|
55
|
+
"directories": {
|
|
56
|
+
"doc": "./docs"
|
|
57
|
+
},
|
|
58
|
+
"scripts": {
|
|
59
|
+
"prepack": "node package-docs.mjs",
|
|
60
|
+
"postpack": "node package-docs.mjs --clean"
|
|
61
|
+
},
|
|
52
62
|
"engines": {
|
|
53
63
|
"node": ">=20"
|
|
54
64
|
},
|
|
@@ -58,7 +68,7 @@
|
|
|
58
68
|
},
|
|
59
69
|
"dependencies": {
|
|
60
70
|
"@standard-schema/spec": "^1.1.0",
|
|
61
|
-
"@modelcontextprotocol/
|
|
71
|
+
"@modelcontextprotocol/server": "^2.0.0",
|
|
62
72
|
"markdansi": "0.3.2",
|
|
63
73
|
"nitro": "3.0.260610-beta"
|
|
64
74
|
},
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdtempSync, rmSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { describe, expect, test } from "vitest";
|
|
7
|
+
|
|
8
|
+
const packageDirectory = fileURLToPath(new URL("../", import.meta.url));
|
|
9
|
+
|
|
10
|
+
type PackFile = {
|
|
11
|
+
readonly path: string;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
type PackResult = {
|
|
15
|
+
readonly filename: string;
|
|
16
|
+
readonly files: readonly PackFile[];
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
describe("published package", () => {
|
|
20
|
+
test("includes the public and internal documentation", () => {
|
|
21
|
+
const destination = mkdtempSync(join(tmpdir(), "capable-pack-"));
|
|
22
|
+
|
|
23
|
+
try {
|
|
24
|
+
const output = execFileSync(
|
|
25
|
+
"pnpm",
|
|
26
|
+
["pack", "--json", "--pack-destination", destination],
|
|
27
|
+
{
|
|
28
|
+
cwd: packageDirectory,
|
|
29
|
+
encoding: "utf8",
|
|
30
|
+
},
|
|
31
|
+
);
|
|
32
|
+
const result = JSON.parse(output) as PackResult;
|
|
33
|
+
const paths = new Set(result.files.map((file) => file.path));
|
|
34
|
+
const manifest = JSON.parse(
|
|
35
|
+
execFileSync(
|
|
36
|
+
"tar",
|
|
37
|
+
["-xOzf", result.filename, "package/package.json"],
|
|
38
|
+
{ encoding: "utf8" },
|
|
39
|
+
),
|
|
40
|
+
) as {
|
|
41
|
+
readonly directories?: { readonly doc?: string };
|
|
42
|
+
readonly scripts?: Record<string, string>;
|
|
43
|
+
};
|
|
44
|
+
const quickstart = execFileSync(
|
|
45
|
+
"tar",
|
|
46
|
+
[
|
|
47
|
+
"-xOzf",
|
|
48
|
+
result.filename,
|
|
49
|
+
"package/docs/site/quickstart.mdx",
|
|
50
|
+
],
|
|
51
|
+
{ encoding: "utf8" },
|
|
52
|
+
);
|
|
53
|
+
|
|
54
|
+
expect(paths).toContain("docs/README.md");
|
|
55
|
+
expect(paths).toContain("docs/CONTEXT.md");
|
|
56
|
+
expect(paths).toContain("docs/internal/architecture.md");
|
|
57
|
+
expect(paths).toContain(
|
|
58
|
+
"docs/internal/adr/0001-capability-is-the-semantic-boundary.md",
|
|
59
|
+
);
|
|
60
|
+
expect(paths).toContain("docs/site/quickstart.mdx");
|
|
61
|
+
expect(paths).toContain(
|
|
62
|
+
"docs/site/reference/packages-and-entry-points.mdx",
|
|
63
|
+
);
|
|
64
|
+
expect(
|
|
65
|
+
[...paths].filter(
|
|
66
|
+
(path) =>
|
|
67
|
+
path.startsWith("docs/site/") && path.endsWith(".mdx"),
|
|
68
|
+
),
|
|
69
|
+
).toHaveLength(25);
|
|
70
|
+
expect(paths).toContain("docs/site/introduction.mdx");
|
|
71
|
+
expect(
|
|
72
|
+
[...paths].some(
|
|
73
|
+
(path) =>
|
|
74
|
+
path.startsWith("docs/site/") &&
|
|
75
|
+
(path.endsWith("/page.tsx") || path.endsWith("/page.mdx")),
|
|
76
|
+
),
|
|
77
|
+
).toBe(false);
|
|
78
|
+
expect(paths).not.toContain("docs/site/globals.css");
|
|
79
|
+
expect(
|
|
80
|
+
[...paths].some(
|
|
81
|
+
(path) => path.startsWith("dist/package/") || path.endsWith(".tgz"),
|
|
82
|
+
),
|
|
83
|
+
).toBe(false);
|
|
84
|
+
expect(paths).not.toContain("package-docs.mjs");
|
|
85
|
+
expect(manifest.directories?.doc).toBe("./docs");
|
|
86
|
+
expect(manifest.scripts?.prepack).toBeUndefined();
|
|
87
|
+
expect(manifest.scripts?.postpack).toBeUndefined();
|
|
88
|
+
expect(quickstart).toMatch(
|
|
89
|
+
/^---\ntitle: "Quickstart"\ndescription: ".+"\n---/,
|
|
90
|
+
);
|
|
91
|
+
|
|
92
|
+
expect(existsSync(new URL("../docs/", import.meta.url))).toBe(false);
|
|
93
|
+
} finally {
|
|
94
|
+
rmSync(destination, { force: true, recursive: true });
|
|
95
|
+
rmSync(new URL("../docs/", import.meta.url), {
|
|
96
|
+
force: true,
|
|
97
|
+
recursive: true,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"mount--YHrgRHJ.mjs","names":[],"sources":["../../mcp/src/index.ts","../../mcp/src/mount.ts"],"sourcesContent":["import type { CapabilityMetaRegistry } from \"@capable/core\";\nimport {\n getAppRuntime,\n type AnyApp,\n type JsonSchema,\n type ManifestNode,\n type ManifestCapability,\n type CapabilityResult,\n} from \"@capable/app\";\n\nexport type McpCapabilityMeta =\n | false\n | {\n readonly name?: string;\n };\n\ndeclare module \"@capable/core\" {\n interface CapabilityMetaRegistry {\n readonly mcp?: McpCapabilityMeta;\n }\n}\n\nexport type McpTool = {\n readonly name: string;\n readonly title?: string;\n readonly description?: string;\n readonly inputSchema: JsonSchema;\n readonly outputSchema?: JsonSchema;\n readonly annotations: {\n readonly readOnlyHint: boolean;\n readonly destructiveHint: boolean;\n };\n call(\n input: unknown,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapabilityResult>;\n};\n\nexport async function createMcp(\n app: AnyApp,\n): Promise<readonly McpTool[]> {\n const runtime = getAppRuntime(app);\n const manifest = await runtime.manifest();\n const tools = flatten(manifest.capabilities)\n .filter((capability) => capability.meta.mcp !== false)\n .map((capability) => {\n const meta = capability.meta.mcp as Exclude<McpCapabilityMeta, false> | undefined;\n return Object.freeze({\n name: meta?.name ?? capability.path.join(\"__\"),\n ...(capability.title ? { title: capability.title } : {}),\n ...(capability.description ? { description: capability.description } : {}),\n inputSchema: capability.input ?? {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n ...(capability.output\n ? { outputSchema: mcpOutputSchema(capability.output) }\n : {}),\n annotations: {\n readOnlyHint: capability.effect === \"read\",\n destructiveHint: capability.effect === \"destructive\",\n },\n call(input: unknown, options?: { readonly signal?: AbortSignal }) {\n return runtime.call({\n id: capability.id,\n input,\n ...(options?.signal ? { signal: options.signal } : {}),\n });\n },\n });\n });\n const names = new Set<string>();\n for (const tool of tools) {\n if (names.has(tool.name)) {\n throw new Error(`Duplicate MCP tool name \"${tool.name}\"`);\n }\n names.add(tool.name);\n }\n return tools;\n}\n\nfunction mcpOutputSchema(schema: JsonSchema): JsonSchema {\n if (schema.type === \"object\") return schema;\n return {\n type: \"object\",\n properties: { value: schema },\n required: [\"value\"],\n additionalProperties: false,\n };\n}\n\nfunction flatten(nodes: readonly ManifestNode[]): readonly ManifestCapability[] {\n return nodes.flatMap((node) =>\n node.type === \"capability\" ? [node] : flatten(node.children)\n );\n}\n","import type { ServerMount } from \"@capable/server\";\nimport { createApp, TransportError } from \"@capable/app\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport {\n CallToolRequestSchema,\n type CallToolResult,\n ListToolsRequestSchema,\n type Tool,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { createMcp, type McpTool } from \"./index.ts\";\n\nexport function mcp<TContext = any>(\n options: {\n readonly path?: string;\n readonly name?: string;\n readonly version?: string;\n } = {},\n): ServerMount<TContext> {\n const path = normalizePath(options.path ?? \"/mcp\");\n return {\n kind: \"capable.server.mount\",\n compile(app, context) {\n return {\n name: \"mcp\",\n async fetch(request) {\n if (new URL(request.url).pathname !== path) return undefined;\n const executable = createApp(\n app,\n context\n ? { context: () => context({ request }) }\n : undefined as never,\n );\n const tools = await createMcp(executable);\n const server = createMcpServer(tools, {\n name: options.name ?? app.name ?? \"capable\",\n version: options.version ?? app.version ?? \"0.0.0\",\n });\n const transport = new WebStandardStreamableHTTPServerTransport({\n enableJsonResponse: true,\n });\n await server.connect(transport);\n try {\n return await transport.handleRequest(request);\n } finally {\n await transport.close();\n await server.close();\n }\n },\n };\n },\n };\n}\n\nfunction createMcpServer(\n tools: readonly McpTool[],\n info: { readonly name: string; readonly version: string },\n): Server {\n const server = new Server(info, {\n capabilities: { tools: {} },\n });\n server.setRequestHandler(ListToolsRequestSchema, () => ({\n tools: tools.map(toProtocolTool),\n }));\n server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n const tool = tools.find(({ name }) => name === request.params.name);\n if (!tool) {\n return toolError(`Unknown tool \"${request.params.name}\"`);\n }\n try {\n const result = await tool.call(request.params.arguments ?? {}, {\n signal: extra.signal,\n });\n return {\n content: [{\n type: \"text\",\n text: result.markdown ?? stringify(result.output),\n }],\n structuredContent: isRecord(result.output)\n ? result.output\n : { value: result.output },\n } satisfies CallToolResult;\n } catch (error) {\n if (!(error instanceof TransportError)) throw error;\n return toolError(error.message, {\n code: error.code,\n status: error.status,\n data: error.data,\n });\n }\n });\n return server;\n}\n\nfunction toProtocolTool(tool: McpTool): Tool {\n return {\n name: tool.name,\n ...(tool.title ? { title: tool.title } : {}),\n ...(tool.description ? { description: tool.description } : {}),\n inputSchema: tool.inputSchema as Tool[\"inputSchema\"],\n ...(tool.outputSchema\n ? { outputSchema: tool.outputSchema as Tool[\"outputSchema\"] }\n : {}),\n annotations: tool.annotations,\n };\n}\n\nfunction toolError(\n message: string,\n details?: Record<string, unknown>,\n): CallToolResult {\n return {\n isError: true,\n content: [{\n type: \"text\",\n text: details ? JSON.stringify({ message, ...details }) : message,\n }],\n };\n}\n\nfunction stringify(value: unknown): string {\n return typeof value === \"string\"\n ? value\n : JSON.stringify(value) ?? String(value);\n}\n\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n"],"mappings":";;;;;AAsCA,eAAsB,UACpB,KAC6B;CAC7B,MAAM,UAAU,cAAc,GAAG;CAEjC,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,YAAY,UAAU,OAAO,MAAM;IAClD,CAAC;IACD,mBAAmB,SAAS,OAAO,MAAM,IACrC,OAAO,SACP,EAAE,OAAO,OAAO,OAAO;GAC7B;EACF,SAAS,OAAO;GACd,IAAI,EAAE,iBAAiB,iBAAiB,MAAM;GAC9C,OAAO,UAAU,MAAM,SAAS;IAC9B,MAAM,MAAM;IACZ,QAAQ,MAAM;IACd,MAAM,MAAM;GACd,CAAC;EACH;CACF,CAAC;CACD,OAAO;AACT;AAEA,SAAS,eAAe,MAAqB;CAC3C,OAAO;EACL,MAAM,KAAK;EACX,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;EAC1C,GAAI,KAAK,cAAc,EAAE,aAAa,KAAK,YAAY,IAAI,CAAC;EAC5D,aAAa,KAAK;EAClB,GAAI,KAAK,eACL,EAAE,cAAc,KAAK,aAAqC,IAC1D,CAAC;EACL,aAAa,KAAK;CACpB;AACF;AAEA,SAAS,UACP,SACA,SACgB;CAChB,OAAO;EACL,SAAS;EACT,SAAS,CAAC;GACR,MAAM;GACN,MAAM,UAAU,KAAK,UAAU;IAAE;IAAS,GAAG;GAAQ,CAAC,IAAI;EAC5D,CAAC;CACH;AACF;AAEA,SAAS,UAAU,OAAwB;CACzC,OAAO,OAAO,UAAU,WACpB,QACA,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK;AAC3C;AAEA,SAAS,cAAc,OAAuB;CAC5C,OAAO,IAAI,MAAM,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;AACtD;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,QAAQ,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,CAAC;AAC5E"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"src-DX2xrplP.mjs","names":["normalizePath"],"sources":["../../fetch/src/error-response.ts","../../fetch/src/standard.ts","../../fetch/src/http.ts"],"sourcesContent":["import { CapableError } from \"@capable/core\";\nimport { TransportError } from \"@capable/app\";\n\nexport type CapabilityErrorData = {\n readonly code: string;\n readonly message: string;\n readonly status: number;\n readonly data?: unknown;\n};\n\nexport function capabilityErrorData(\n error: unknown,\n fallbackStatus = 500,\n): CapabilityErrorData {\n const capable = error instanceof CapableError || error instanceof TransportError\n ? error\n : new CapableError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n return {\n code: capable.code,\n message: capable.message,\n status: capable.status ?? fallbackStatus,\n ...(capable.data === undefined ? {} : { data: capable.data }),\n };\n}\n\nexport function capabilityErrorResponse(\n error: unknown,\n fallbackStatus = 500,\n): Response {\n const data = capabilityErrorData(error, fallbackStatus);\n return Response.json({\n ok: false,\n error: data,\n }, { status: data.status });\n}\n","import {\n getAppRuntime,\n isApp,\n TransportError,\n type ApplicationManifest,\n type ApplicationTransport,\n type AnyApp,\n type CapabilityCall,\n type CapabilityResult,\n} from \"@capable/app\";\nimport {\n capabilityErrorData,\n capabilityErrorResponse,\n} from \"./error-response.ts\";\n\nexport type FetchHandler = (request: Request) => Response | Promise<Response>;\n\nexport function createProtocolHandler(\n application:\n | AnyApp\n | ((request: Request) => AnyApp | Promise<AnyApp>),\n options: {\n readonly basePath?: string;\n } = {},\n): {\n readonly fetch: FetchHandler;\n} {\n const basePath = normalizePath(options.basePath ?? \"/_capable\");\n\n const fetch: FetchHandler = async (request) => {\n const url = new URL(request.url);\n const app = isApp(application)\n ? application\n : await application(request);\n const runtime = getAppRuntime(app);\n if (url.pathname === `${basePath}/manifest` && request.method === \"GET\") {\n return Response.json(await runtime.manifest());\n }\n const subscribePrefix = `${basePath}/subscribe/`;\n if (\n url.pathname.startsWith(subscribePrefix) &&\n request.method === \"POST\"\n ) {\n const id = decodeURIComponent(\n url.pathname.slice(subscribePrefix.length),\n );\n const controller = new AbortController();\n let stream: AsyncIterableIterator<CapabilityResult> | undefined;\n try {\n const body = await request.json() as { readonly input?: unknown };\n stream = runtime.subscribe({\n id,\n input: body.input ?? {},\n signal: AbortSignal.any([request.signal, controller.signal]),\n });\n const first = await stream.next();\n return subscriptionResponse(stream, first, controller);\n } catch (error) {\n controller.abort();\n await stream?.return?.().catch(() => undefined);\n return capabilityErrorResponse(error);\n }\n }\n const callPrefix = `${basePath}/call/`;\n if (!url.pathname.startsWith(callPrefix) || request.method !== \"POST\") {\n return new Response(\"Not Found\", { status: 404 });\n }\n const id = decodeURIComponent(url.pathname.slice(callPrefix.length));\n try {\n const body = await request.json() as { readonly input?: unknown };\n const result = await runtime.call({\n id,\n input: body.input ?? {},\n signal: request.signal,\n });\n return Response.json({\n ok: true,\n ...result,\n });\n } catch (error) {\n return capabilityErrorResponse(error);\n }\n };\n\n return { fetch };\n}\n\nexport type TransportHeaders =\n | HeadersInit\n | (() => HeadersInit | Promise<HeadersInit>);\n\nexport function createHttpTransport(options: {\n readonly url: string | URL | (() => string | URL);\n readonly fetch?: (request: Request) => Response | Promise<Response>;\n readonly headers?: TransportHeaders;\n}): ApplicationTransport {\n const fetchImplementation = options.fetch ?? globalThis.fetch;\n\n async function request(\n path: string,\n init: RequestInit,\n ): Promise<Response> {\n const base = normalizeUrl(\n typeof options.url === \"function\" ? options.url() : options.url,\n );\n const configured = typeof options.headers === \"function\"\n ? await options.headers()\n : options.headers;\n const headers = new Headers(configured);\n new Headers(init.headers).forEach((value, name) => headers.set(name, value));\n return fetchImplementation(\n new Request(new URL(path, base), { ...init, headers }),\n );\n }\n\n return Object.freeze({\n async manifest(\n { signal }: { readonly signal?: AbortSignal } = {},\n ) {\n const response = await request(\"manifest\", {\n method: \"GET\",\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) throw await responseError(response);\n return await responseJson<ApplicationManifest>(\n response,\n \"Application manifest\",\n );\n },\n async call({ id, input = {}, signal }: CapabilityCall) {\n const response = await request(`call/${encodeURIComponent(id)}`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ input }),\n ...(signal ? { signal } : {}),\n });\n const body = await response.json() as\n | {\n readonly ok: true;\n readonly output: unknown;\n readonly markdown?: string;\n }\n | {\n readonly ok: false;\n readonly error: {\n readonly code: string;\n readonly message?: string;\n readonly status?: number;\n readonly data?: unknown;\n };\n };\n if (!body.ok) {\n throw new TransportError(body.error.code, body.error);\n }\n return {\n output: body.output,\n ...(body.markdown ? { markdown: body.markdown } : {}),\n };\n },\n async *subscribe({\n id,\n input = {},\n signal,\n }: CapabilityCall) {\n const response = await request(`subscribe/${encodeURIComponent(id)}`, {\n method: \"POST\",\n headers: {\n accept: \"text/event-stream\",\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({ input }),\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) throw await responseError(response);\n yield* decodeEventStream(response);\n },\n });\n}\n\nfunction subscriptionResponse(\n stream: AsyncIterableIterator<CapabilityResult>,\n first: IteratorResult<CapabilityResult>,\n subscriptionController: AbortController,\n): Response {\n const encoder = new TextEncoder();\n let initial: IteratorResult<CapabilityResult> | undefined = first;\n\n return new Response(new ReadableStream({\n async pull(controller) {\n try {\n const result = initial ?? await stream.next();\n initial = undefined;\n if (result.done) {\n subscriptionController.abort();\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(sseFrame(\"output\", result.value)));\n } catch (error) {\n subscriptionController.abort();\n controller.enqueue(encoder.encode(\n sseFrame(\"error\", capabilityErrorData(error)),\n ));\n controller.close();\n await stream.return?.();\n }\n },\n async cancel() {\n subscriptionController.abort();\n await stream.return?.();\n },\n }, {\n highWaterMark: 0,\n }), {\n headers: {\n \"cache-control\": \"no-cache\",\n \"content-type\": \"text/event-stream; charset=utf-8\",\n },\n });\n}\n\nasync function* decodeEventStream(\n response: Response,\n): AsyncIterableIterator<CapabilityResult> {\n if (!response.headers.get(\"content-type\")?.includes(\"text/event-stream\")) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: \"Subscription response is not an event stream\",\n });\n }\n if (!response.body) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: \"Subscription response has no body\",\n });\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n try {\n while (true) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value, { stream: !done });\n let boundary = eventBoundary(buffer);\n while (boundary) {\n const block = buffer.slice(0, boundary.index);\n buffer = buffer.slice(boundary.index + boundary.length);\n const event = parseEventBlock(block);\n if (event) {\n if (event.type === \"error\") {\n throw new TransportError(event.error.code, event.error);\n }\n yield event.result;\n }\n boundary = eventBoundary(buffer);\n }\n if (done) break;\n }\n } finally {\n await reader.cancel().catch(() => undefined);\n }\n}\n\nfunction eventBoundary(\n value: string,\n): { readonly index: number; readonly length: number } | undefined {\n const lf = value.indexOf(\"\\n\\n\");\n const crlf = value.indexOf(\"\\r\\n\\r\\n\");\n if (lf < 0 && crlf < 0) {\n return undefined;\n }\n if (crlf >= 0 && (lf < 0 || crlf < lf)) {\n return { index: crlf, length: 4 };\n }\n return { index: lf, length: 2 };\n}\n\nfunction parseEventBlock(block: string):\n | { readonly type: \"output\"; readonly result: CapabilityResult }\n | {\n readonly type: \"error\";\n readonly error: {\n readonly code: string;\n readonly message?: string;\n readonly status?: number;\n readonly data?: unknown;\n };\n }\n | undefined {\n let type = \"message\";\n const data: string[] = [];\n for (const line of block.replace(/\\r\\n/g, \"\\n\").split(\"\\n\")) {\n if (line.startsWith(\":\")) continue;\n if (line.startsWith(\"event:\")) type = line.slice(6).trim();\n if (line.startsWith(\"data:\")) data.push(line.slice(5).trimStart());\n }\n if (!data.length) return undefined;\n const value = JSON.parse(data.join(\"\\n\")) as any;\n return type === \"error\"\n ? { type: \"error\", error: value }\n : { type: \"output\", result: value };\n}\n\nfunction sseFrame(event: string, data: unknown): string {\n return `event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`;\n}\n\nfunction normalizeUrl(value: string | URL): URL {\n const url = new URL(value);\n if (!url.pathname.endsWith(\"/\")) url.pathname += \"/\";\n url.search = \"\";\n url.hash = \"\";\n return url;\n}\n\nasync function responseError(response: Response): Promise<TransportError> {\n const text = await response.text().catch(() => \"\");\n let data: unknown = text;\n try {\n data = JSON.parse(text);\n } catch {\n // Preserve the response text as transport diagnostics.\n }\n if (\n data &&\n typeof data === \"object\" &&\n \"ok\" in data &&\n data.ok === false &&\n \"error\" in data &&\n data.error &&\n typeof data.error === \"object\" &&\n \"code\" in data.error &&\n typeof data.error.code === \"string\"\n ) {\n const error = data.error as {\n readonly code: string;\n readonly message?: unknown;\n readonly status?: unknown;\n readonly data?: unknown;\n };\n return new TransportError(error.code, {\n ...(typeof error.message === \"string\"\n ? { message: error.message }\n : {}),\n status: typeof error.status === \"number\"\n ? error.status\n : response.status,\n ...(\"data\" in error ? { data: error.data } : {}),\n });\n }\n return new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: `Transport request failed with ${response.status}`,\n data,\n });\n}\n\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 schemaToJsonSchema,\n type AppDefinition,\n type GroupMetaRegistry,\n type LocatedCapability,\n type CapabilityMetaRegistry,\n type CapabilityTree,\n} from \"@capable/core\";\nimport {\n type ApplicationSelection,\n type JsonSchema,\n} from \"@capable/app\";\nimport {\n capabilityErrorResponse,\n} from \"./error-response.ts\";\nimport type { FetchHandler } from \"./standard.ts\";\n\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\nexport type HttpCapabilityMeta =\n | false\n | {\n readonly method?: HttpMethod;\n readonly route?: string;\n readonly status?: number;\n };\n\nexport type HttpGroupMeta = {\n readonly prefix?: string;\n};\n\ndeclare module \"@capable/core\" {\n interface CapabilityMetaRegistry {\n readonly http?: HttpCapabilityMeta;\n }\n\n interface GroupMetaRegistry {\n readonly http?: HttpGroupMeta;\n }\n}\n\nexport type ContextProvider<TContext> = (args: {\n readonly request: Request;\n}) => TContext | Promise<TContext>;\n\nexport type CapabilitySelection<\n TTree extends CapabilityTree = CapabilityTree,\n> = ApplicationSelection<TTree>;\n\nexport type CompiledHttpRoute = {\n readonly method: HttpMethod;\n readonly path: string;\n readonly capability: LocatedCapability;\n};\n\nexport function createHttpHandler<\n const TCapabilities extends CapabilityTree,\n TContext,\n>(\n app: AppDefinition<TCapabilities, TContext>,\n options: {\n readonly context?: ContextProvider<TContext>;\n readonly basePath?: string;\n readonly openapiPath?: string | false;\n readonly requireExplicitRoutes?: boolean;\n readonly selection?: CapabilitySelection<TCapabilities>;\n } = {},\n): {\n readonly fetch: FetchHandler;\n readonly routes: readonly CompiledHttpRoute[];\n readonly openapi: Readonly<Record<string, unknown>>;\n} {\n const basePath = normalizePath(options.basePath ?? \"/api\");\n const selected = selectCapabilities(app.locatedCapabilities, options.selection)\n .filter((entry) => capabilityHttp(entry) !== false);\n const routes = selected.map((entry) => compileHttpRoute(entry, basePath));\n assertUniqueRoutes(routes);\n if (options.requireExplicitRoutes) {\n const implicit = selected.find((entry) => {\n const meta = capabilityHttp(entry);\n return !meta || !meta.method || !meta.route;\n });\n if (implicit) {\n throw new Error(\n `Capability \"${implicit.capability.id}\" requires an explicit HTTP method and route`,\n );\n }\n }\n const openapi = createOpenApi(app, routes);\n const openapiPath = options.openapiPath === false\n ? undefined\n : normalizePath(options.openapiPath ?? \"/openapi.json\");\n\n return {\n routes,\n openapi,\n async fetch(request) {\n const url = new URL(request.url);\n if (\n openapiPath &&\n url.pathname === openapiPath &&\n request.method === \"GET\"\n ) {\n return Response.json(openapi);\n }\n const match = routes\n .map((route) => ({ route, params: matchPath(route.path, url.pathname) }))\n .find(({ route, params }) => route.method === request.method && params);\n if (!match?.params) return new Response(\"Not Found\", { status: 404 });\n\n try {\n const input = await readHttpInput(\n request,\n match.params,\n match.route.capability.capability.input,\n );\n const context = options.context\n ? await options.context({ request })\n : undefined as TContext;\n const output = await executeLocatedCapability(match.route.capability, input, {\n context,\n signal: request.signal,\n });\n if (\n request.headers.get(\"accept\")?.includes(\"text/markdown\") &&\n match.route.capability.capability.toMarkdown\n ) {\n return new Response(\n await match.route.capability.capability.toMarkdown(output, { context }),\n {\n status: httpSuccessStatus(match.route.capability),\n headers: { \"content-type\": \"text/markdown; charset=utf-8\" },\n },\n );\n }\n return Response.json(output, {\n status: httpSuccessStatus(match.route.capability),\n });\n } catch (error) {\n return capabilityErrorResponse(error);\n }\n },\n };\n}\n\nfunction compileHttpRoute(\n entry: LocatedCapability,\n basePath: string,\n): CompiledHttpRoute {\n const meta = capabilityHttp(entry);\n const defaultPath = entry.path.flatMap((segment, index) => {\n const groupIndex = entry.groupPaths.findIndex(\n (path) => path.length === index + 1,\n );\n const prefix = groupIndex >= 0\n ? (entry.groups[groupIndex]?.meta.http as HttpGroupMeta | undefined)\n ?.prefix\n : undefined;\n return prefix ? prefix.split(\"/\").filter(Boolean) : [segment];\n }).join(\"/\");\n const groupPrefix = entry.groups.flatMap((group) => {\n const prefix = (group.meta.http as HttpGroupMeta | undefined)?.prefix;\n return prefix ? prefix.split(\"/\").filter(Boolean) : [];\n }).join(\"/\");\n const authoredRoute = meta && meta.route ? meta.route : defaultPath;\n assertPathParameters(entry, authoredRoute);\n return Object.freeze({\n method: meta && meta.method\n ? meta.method\n : entry.capability.effect === \"read\"\n ? \"GET\"\n : \"POST\",\n path: joinPath(\n basePath,\n meta && meta.route ? groupPrefix : \"\",\n authoredRoute,\n ),\n capability: entry,\n });\n}\n\nfunction capabilityHttp(entry: LocatedCapability): HttpCapabilityMeta | undefined {\n return entry.capability.meta.http as HttpCapabilityMeta | undefined;\n}\n\nfunction httpSuccessStatus(entry: LocatedCapability): number {\n const meta = capabilityHttp(entry);\n return meta && typeof meta.status === \"number\" ? meta.status : 200;\n}\n\nasync function readHttpInput(\n request: Request,\n params: Record<string, string>,\n schema: LocatedCapability[\"capability\"][\"input\"],\n): Promise<Record<string, unknown>> {\n const url = new URL(request.url);\n const jsonSchema = schema\n ? schemaToJsonSchema(schema, \"input\")\n : undefined;\n const properties = jsonSchema?.properties as\n | Record<string, Readonly<Record<string, unknown>>>\n | undefined;\n const coerceEntries = (entries: Iterable<readonly [string, string]>) =>\n Object.fromEntries(\n [...entries].map(([key, value]) => [\n key,\n coerceHttpValue(value, properties?.[key]),\n ]),\n );\n const rest: Record<string, unknown> =\n request.method === \"GET\"\n ? coerceEntries(url.searchParams)\n : request.headers.get(\"content-type\")?.includes(\"application/json\")\n ? await request.json() as Record<string, unknown>\n : {};\n return {\n ...rest,\n ...coerceEntries(Object.entries(params)),\n };\n}\n\nfunction coerceHttpValue(\n value: string,\n schema: Readonly<Record<string, unknown>> | undefined,\n): unknown {\n if (schema?.type === \"boolean\") return value === \"true\"\n ? true\n : value === \"false\"\n ? false\n : value;\n if (schema?.type === \"integer\" || schema?.type === \"number\") {\n const number = Number(value);\n return Number.isFinite(number) ? number : value;\n }\n return value;\n}\n\nfunction assertPathParameters(\n entry: LocatedCapability,\n path: string,\n): void {\n const parameters = [...path.matchAll(/:([^/]+)/g)].map((match) => match[1]!);\n if (parameters.length === 0) return;\n const schema = entry.capability.input\n ? schemaToJsonSchema(entry.capability.input, \"input\")\n : undefined;\n const properties = schema?.properties as\n | Record<string, unknown>\n | undefined;\n for (const parameter of parameters) {\n if (!properties?.[parameter]) {\n throw new Error(\n `HTTP path parameter \":${parameter}\" is not present in Capability \"${entry.capability.id}\" input`,\n );\n }\n }\n}\n\nfunction matchPath(\n pattern: string,\n pathname: string,\n): Record<string, string> | undefined {\n const expected = pattern.split(\"/\").filter(Boolean);\n const actual = pathname.split(\"/\").filter(Boolean);\n if (expected.length !== actual.length) return undefined;\n const params: Record<string, string> = {};\n for (let index = 0; index < expected.length; index++) {\n const token = expected[index]!;\n const value = actual[index]!;\n if (token.startsWith(\":\")) params[token.slice(1)] = decodeURIComponent(value);\n else if (token !== value) return undefined;\n }\n return params;\n}\n\nfunction createOpenApi(\n app: AppDefinition<any, any>,\n routes: readonly CompiledHttpRoute[],\n): Readonly<Record<string, unknown>> {\n const paths: Record<string, unknown> = {};\n for (const route of routes) {\n const method = route.method.toLowerCase();\n const path = route.path.replace(/:([^/]+)/g, \"{$1}\");\n const capability = route.capability.capability;\n const input = capability.input\n ? schemaToJsonSchema(capability.input, \"input\")\n : undefined;\n const properties = (input?.properties ?? {}) as Record<string, JsonSchema>;\n const required = new Set((input?.required ?? []) as readonly string[]);\n const pathNames = new Set(\n [...route.path.matchAll(/:([^/]+)/g)].map((match) => match[1]!),\n );\n const parameters = [...pathNames].map((name) => ({\n name,\n in: \"path\",\n required: true,\n schema: properties[name] ?? {},\n }));\n const remaining = Object.fromEntries(\n Object.entries(properties).filter(([name]) => !pathNames.has(name)),\n );\n if (route.method === \"GET\") {\n parameters.push(\n ...Object.entries(remaining).map(([name, schema]) => ({\n name,\n in: \"query\",\n required: required.has(name),\n schema,\n })),\n );\n }\n const responses: Record<string, unknown> = {\n [String(httpSuccessStatus(route.capability))]: {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: capability.output\n ? schemaToJsonSchema(capability.output, \"output\")\n : {},\n },\n },\n },\n };\n for (const [code, error] of Object.entries(route.capability.errors)) {\n const status = typeof error.status === \"number\"\n ? String(error.status)\n : \"default\";\n responses[status] ??= {\n description: error.message ?? code,\n };\n }\n const current = paths[path] as Record<string, unknown> | undefined ?? {};\n current[method] = {\n capabilityId: capability.id,\n ...(capability.title ? { summary: capability.title } : {}),\n ...(capability.description ? { description: capability.description } : {}),\n ...(parameters.length ? { parameters } : {}),\n ...(route.method !== \"GET\" && Object.keys(remaining).length\n ? {\n requestBody: {\n required: [...required].some((name) => !pathNames.has(name)),\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: remaining,\n required: [...required].filter((name) =>\n !pathNames.has(name)\n ),\n },\n },\n },\n },\n }\n : {}),\n responses,\n };\n paths[path] = current;\n }\n return {\n openapi: \"3.1.0\",\n info: { title: app.name, version: app.version },\n paths,\n };\n}\n\nfunction selectCapabilities(\n capabilities: readonly LocatedCapability[],\n selection: CapabilitySelection | undefined,\n): readonly LocatedCapability[] {\n return capabilities.filter((entry) => {\n const included = selection?.include\n ? matchesTree(selection.include, entry.path)\n : true;\n return included && !matchesTree(selection?.exclude, entry.path);\n });\n}\n\nfunction matchesTree(\n tree: Readonly<Record<string, unknown>> | undefined,\n path: readonly string[],\n): boolean {\n if (!tree) return false;\n let current: unknown = tree;\n for (const segment of path) {\n if (current === true) return true;\n if (!current || typeof current !== \"object\" || Array.isArray(current)) {\n return false;\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return current === true || (\n Boolean(current) && typeof current === \"object\" && !Array.isArray(current)\n );\n}\n\nfunction assertUniqueRoutes(routes: readonly CompiledHttpRoute[]): void {\n const seen = new Set<string>();\n for (const route of routes) {\n const identity = `${route.method} ${route.path}`;\n if (seen.has(identity)) throw new Error(`Duplicate HTTP route ${identity}`);\n seen.add(identity);\n }\n}\n\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n\nfunction joinPath(...parts: readonly string[]): string {\n return normalizePath(parts.join(\"/\"));\n}\n"],"mappings":";;;AAUA,SAAgB,oBACd,OACA,iBAAiB,KACI;CACrB,MAAM,UAAU,iBAAiB,gBAAgB,iBAAiB,iBAC9D,QACA,IAAI,aAAa,yBAAyB,EAAE,OAAO,MAAM,CAAC;CAC9D,OAAO;EACL,MAAM,QAAQ;EACd,SAAS,QAAQ;EACjB,QAAQ,QAAQ,UAAU;EAC1B,GAAI,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