capable-kit 0.0.1-alpha.3 → 0.0.1-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -3
- package/dist/ai-sdk.d.mts +2 -2
- package/dist/ai-sdk.mjs +1 -1
- package/dist/app.d.mts +1 -1
- package/dist/app.mjs +1 -1
- package/dist/bin.mjs +17 -16
- package/dist/bin.mjs.map +1 -1
- package/dist/cli.d.mts +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/core.d.mts +3 -3
- package/dist/core.mjs +2 -2
- package/dist/eve.d.mts +1 -1
- package/dist/eve.mjs +1 -1
- package/dist/http.d.mts +1 -1
- package/dist/http.mjs +1 -1
- package/dist/{index-BB5ogMv-.d.mts → index-Be8-UVBC.d.mts} +49 -8
- package/dist/{index-B2ru1zGQ.d.mts → index-D2CRRUzH.d.mts} +6 -6
- package/dist/{index-B_I9n6gN.d.mts → index-Dbc4g9WM.d.mts} +4 -3
- package/dist/{index-AqKbVZ8Z.d.mts → index-DwXlaTXI.d.mts} +4 -4
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +3 -3
- package/dist/mcp.d.mts +2 -2
- package/dist/mcp.mjs +1 -1
- package/dist/{mount--YHrgRHJ.mjs → mount-xvMsjz1B.mjs} +65 -27
- package/dist/mount-xvMsjz1B.mjs.map +1 -0
- package/dist/runtime-support.d.mts +1 -1
- package/dist/runtime-support.mjs +6 -6
- package/dist/runtime-support.mjs.map +1 -1
- package/dist/server.d.mts +2 -2
- package/dist/server.mjs +2 -2
- package/dist/{src-DX2xrplP.mjs → src-BF70JLxI.mjs} +24 -13
- package/dist/src-BF70JLxI.mjs.map +1 -0
- package/dist/{src-3UaBqI8H.mjs → src-C2MGIlT0.mjs} +17 -18
- package/dist/src-C2MGIlT0.mjs.map +1 -0
- package/dist/{src-DtSY5fzY.mjs → src-CDxL6w3d.mjs} +7 -7
- package/dist/{src-DtSY5fzY.mjs.map → src-CDxL6w3d.mjs.map} +1 -1
- package/dist/{src-BjBxOv7x.mjs → src-Db6-XSnU.mjs} +20 -12
- package/dist/src-Db6-XSnU.mjs.map +1 -0
- package/dist/{src-B53ZbNtC.mjs → src-DdV82An-.mjs} +137 -3
- package/dist/src-DdV82An-.mjs.map +1 -0
- package/dist/{subscription-McaLyHM2.d.mts → subscription-Bq792Ad2.d.mts} +2 -2
- package/docs/CONTEXT.md +113 -0
- package/docs/README.md +28 -0
- package/docs/internal/README.md +16 -0
- package/docs/internal/adr/0001-capability-is-the-semantic-boundary.md +24 -0
- package/docs/internal/architecture.md +134 -0
- package/docs/internal/capability-first-model.md +160 -0
- package/docs/internal/implementation-friction.md +705 -0
- package/docs/internal/why-capable.md +94 -0
- package/docs/site/capable-orpc-and-trpc.mdx +133 -0
- package/docs/site/concepts/apps.mdx +217 -0
- package/docs/site/concepts/architecture.mdx +83 -0
- package/docs/site/concepts/capabilities.mdx +249 -0
- package/docs/site/concepts/errors.mdx +93 -0
- package/docs/site/concepts/presentations.mdx +161 -0
- package/docs/site/hosting/any-fetch-host.mdx +74 -0
- package/docs/site/hosting/next-js.mdx +77 -0
- package/docs/site/hosting/standalone-server.mdx +94 -0
- package/docs/site/introduction.mdx +259 -0
- package/docs/site/patterns/composition.mdx +142 -0
- package/docs/site/patterns/remote-apps.mdx +117 -0
- package/docs/site/patterns/subscriptions.mdx +87 -0
- package/docs/site/quickstart.mdx +386 -0
- package/docs/site/reference/packages-and-entry-points.mdx +72 -0
- package/docs/site/reference/surface-metadata.mdx +84 -0
- package/docs/site/reference/the-cap-cli.mdx +81 -0
- package/docs/site/surfaces/ai-sdk.mdx +94 -0
- package/docs/site/surfaces/cli.mdx +138 -0
- package/docs/site/surfaces/eve.mdx +121 -0
- package/docs/site/surfaces/http-and-openapi.mdx +111 -0
- package/docs/site/surfaces/mcp.mdx +110 -0
- package/docs/site/surfaces/react-query.mdx +80 -0
- package/docs/site/surfaces/typescript.mdx +123 -0
- package/docs/site/surfaces.mdx +78 -0
- package/docs/site/why-capable.mdx +99 -0
- package/package.json +13 -3
- package/src/index.test.ts +1 -0
- package/src/index.ts +5 -1
- package/src/package.test.ts +102 -0
- package/dist/mount--YHrgRHJ.mjs.map +0 -1
- package/dist/src-3UaBqI8H.mjs.map +0 -1
- package/dist/src-B53ZbNtC.mjs.map +0 -1
- package/dist/src-BjBxOv7x.mjs.map +0 -1
- package/dist/src-DX2xrplP.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-Db6-XSnU.mjs","names":["kebabCase","renderMarkdown"],"sources":["../../cli/src/commands.ts","../../cli/src/style.ts","../../cli/src/help.ts","../../cli/src/presentation.ts","../../cli/src/index.ts"],"sourcesContent":["import type {\n ManifestGroup,\n ManifestNode,\n ManifestCapability,\n} from \"@capable/app\";\nimport type {\n CliGroupMeta,\n CliCapabilityMeta,\n} from \"./index.ts\";\n\nexport type CliCommand = {\n readonly command: readonly string[];\n readonly capability: ManifestCapability;\n readonly meta: Exclude<CliCapabilityMeta, false>;\n};\n\nexport type CliCommandGroup = {\n readonly command: readonly string[];\n readonly title?: string;\n readonly description?: string;\n};\n\nexport type CliCommandCatalog = {\n readonly commands: readonly CliCommand[];\n readonly groups: readonly CliCommandGroup[];\n};\n\nexport function collectCommands(\n nodes: readonly ManifestNode[],\n parent: readonly string[] = [],\n): CliCommandCatalog {\n const commands: CliCommand[] = [];\n const groups: CliCommandGroup[] = [];\n\n for (const node of nodes) {\n if (node.type === \"group\") {\n const meta = (node.meta.cli ?? {}) as CliGroupMeta;\n const command = [...parent, meta.name ?? node.key];\n groups.push(groupFrom(node, command));\n const children = collectCommands(node.children, command);\n commands.push(...children.commands);\n groups.push(...children.groups);\n continue;\n }\n\n const rawMeta = node.meta.cli as CliCapabilityMeta | undefined;\n if (rawMeta === false) continue;\n const meta = rawMeta ?? {};\n commands.push({\n command: meta.command ?? [...parent, meta.name ?? node.path.at(-1)!],\n capability: node,\n meta,\n });\n }\n\n return {\n commands: Object.freeze(commands),\n groups: Object.freeze(groups),\n };\n}\n\nfunction groupFrom(\n node: ManifestGroup,\n command: readonly string[],\n): CliCommandGroup {\n return Object.freeze({\n command: Object.freeze(command),\n ...(node.title ? { title: node.title } : {}),\n ...(node.description ? { description: node.description } : {}),\n });\n}\n","export type CliStyle = {\n readonly bold: (text: string) => string;\n readonly accent: (text: string) => string;\n readonly dim: (text: string) => string;\n};\n\nexport type CliRow = {\n readonly label: string;\n readonly description?: string;\n};\n\n/** Every help line hangs off this margin. */\nexport const MARGIN = \" \";\n\n/** Rows sit one step inside their section heading. */\nexport const ROW_INDENT = \" \";\n\n/** Widest label that still keeps descriptions in a single column. */\nconst MAX_LABEL_WIDTH = 30;\n\nconst LABEL_GAP = 2;\n\nexport function createCliStyle(color?: boolean): CliStyle {\n const enabled = color ?? supportsColor();\n return {\n bold: enabled\n ? (text: string) => `\\u001B[1m${text}\\u001B[22m`\n : identity,\n accent: enabled\n ? (text: string) => `\\u001B[36m${text}\\u001B[39m`\n : identity,\n dim: enabled\n ? (text: string) => `\\u001B[2m${text}\\u001B[22m`\n : identity,\n };\n}\n\nexport function supportsColor(\n env: Record<string, string | undefined> = process.env,\n isTTY: boolean = Boolean(process.stdout.isTTY),\n): boolean {\n if (\"NO_COLOR\" in env) return false;\n if (env.FORCE_COLOR !== undefined) return env.FORCE_COLOR !== \"0\";\n return isTTY && env.TERM !== \"dumb\";\n}\n\nexport function renderRows(\n rows: readonly CliRow[],\n style: CliStyle,\n options: {\n readonly indent?: string;\n /** Absolute column for descriptions, so sibling sections stay aligned. */\n readonly column?: number;\n } = {},\n): string {\n const indent = options.indent ?? ROW_INDENT;\n const width = Math.max(\n 0,\n (options.column ?? descriptionColumn(rows, indent)) - indent.length -\n LABEL_GAP,\n );\n return rows.map(({ label, description }) => {\n const line = `${indent}${style.accent(label)}`;\n if (!description) return line;\n return label.length > width\n ? `${line}\\n${indent}${\" \".repeat(width + LABEL_GAP)}${style.dim(description)}`\n : `${line}${\" \".repeat(width - label.length + LABEL_GAP)}${\n style.dim(description)\n }`;\n }).join(\"\\n\");\n}\n\n/** Shared description column so sibling sections stay visually aligned. */\nexport function descriptionColumn(\n rows: readonly CliRow[],\n indent: string = ROW_INDENT,\n): number {\n const labels = rows\n .filter(({ description }) => description !== undefined)\n .map(({ label }) => label.length)\n .filter((length) => length <= MAX_LABEL_WIDTH);\n return indent.length + LABEL_GAP + Math.max(0, ...labels);\n}\n\nexport function renderSection(\n title: string,\n body: string,\n style: CliStyle,\n): string {\n return `${MARGIN}${style.bold(title)}\\n\\n${body}`;\n}\n\nfunction identity(text: string): string {\n return text;\n}\n","import type {\n ApplicationManifest,\n JsonSchema,\n} from \"@capable/app\";\nimport type {\n CliCommand,\n CliCommandGroup,\n} from \"./commands.ts\";\nimport {\n descriptionColumn,\n MARGIN,\n renderRows,\n renderSection,\n ROW_INDENT,\n type CliRow,\n type CliStyle,\n} from \"./style.ts\";\n\nconst GLOBAL_OPTIONS: readonly CliRow[] = [\n { label: \"--json\", description: \"Print canonical JSON\" },\n { label: \"-h, --help\", description: \"Show help\" },\n];\n\nexport function renderRootHelp(\n manifest: Pick<ApplicationManifest, \"name\" | \"description\">,\n commands: readonly CliCommand[],\n groups: readonly CliCommandGroup[],\n invocationName: string,\n style: CliStyle,\n): string {\n const sections = commandSections(commands, groups);\n const nested = sections.some((section) => section.title !== undefined);\n const column = Math.max(\n descriptionColumn(\n sections.flatMap((section) => section.rows),\n nested ? `${ROW_INDENT}${MARGIN}` : ROW_INDENT,\n ),\n descriptionColumn(GLOBAL_OPTIONS),\n );\n return renderHelp([\n banner({\n title: manifest.name,\n ...(manifest.description ? { description: manifest.description } : {}),\n usage: `${invocationName} <command> [options]`,\n style,\n }),\n renderSection(\n \"Commands\",\n sections\n .map((section) =>\n [\n section.title ? `${ROW_INDENT}${style.dim(section.title)}` : undefined,\n renderRows(section.rows, style, {\n column,\n ...(section.title ? { indent: `${ROW_INDENT}${MARGIN}` } : {}),\n }),\n ].filter(Boolean).join(\"\\n\")\n )\n .join(\"\\n\\n\"),\n style,\n ),\n renderSection(\"Options\", renderRows(GLOBAL_OPTIONS, style, { column }), style),\n hint(`Run \\`${invocationName} <command> --help\\` for details on a command.`, style),\n ]);\n}\n\nexport function renderGroupHelp(\n group: CliCommandGroup,\n commands: readonly CliCommand[],\n invocationName: string,\n style: CliStyle,\n): string {\n const prefix = group.command.join(\" \");\n const rows = commands\n .filter((candidate) => startsWith(candidate.command, group.command))\n .map((candidate) => ({\n label: signature(candidate, candidate.command.slice(group.command.length)),\n ...describe(candidate),\n }));\n const column = descriptionColumn([...rows, ...GLOBAL_OPTIONS]);\n return renderHelp([\n banner({\n ...(group.title ? { title: group.title } : {}),\n ...(group.description ? { description: group.description } : {}),\n usage: `${invocationName} ${prefix} <command> [options]`,\n style,\n }),\n renderSection(\"Commands\", renderRows(rows, style, { column }), style),\n renderSection(\"Options\", renderRows(GLOBAL_OPTIONS, style, { column }), style),\n hint(\n `Run \\`${invocationName} ${prefix} <command> --help\\` for details on a command.`,\n style,\n ),\n ]);\n}\n\nexport function renderCommandHelp(\n command: CliCommand,\n invocationName: string,\n style: CliStyle,\n): string {\n const properties = fields(command);\n const required = requiredFields(command);\n const positionals = command.meta.positional ?? [];\n const argumentRows = positionals.map((name) => ({\n label: placeholder(name, required.has(name)),\n ...description(properties[name], { choices: true }),\n }));\n const optionRows = [\n ...Object.entries(properties)\n .filter(([name]) => !positionals.includes(name))\n .map(([name, schema]) => ({\n label: optionLabel(name, schema),\n ...description(schema, { required: required.has(name) }),\n })),\n ...(command.capability.subscription\n ? [{ label: \"--watch\", description: \"Stream updates until interrupted\" }]\n : []),\n ];\n const column = descriptionColumn([\n ...argumentRows,\n ...optionRows,\n ...GLOBAL_OPTIONS,\n ]);\n\n return renderHelp([\n banner({\n ...(command.capability.title ? { title: command.capability.title } : {}),\n ...(command.capability.description\n ? { description: command.capability.description }\n : {}),\n usage: [invocationName, signature(command), \"[options]\"].join(\" \"),\n style,\n }),\n argumentRows.length\n ? renderSection(\n \"Arguments\",\n renderRows(argumentRows, style, { column }),\n style,\n )\n : undefined,\n optionRows.length\n ? renderSection(\"Options\", renderRows(optionRows, style, { column }), style)\n : undefined,\n renderSection(\n optionRows.length ? \"Global Options\" : \"Options\",\n renderRows(GLOBAL_OPTIONS, style, { column }),\n style,\n ),\n ]);\n}\n\n/** Root commands are grouped under their top-level group, Vercel style. */\nfunction commandSections(\n commands: readonly CliCommand[],\n groups: readonly CliCommandGroup[],\n): readonly { readonly title?: string; readonly rows: readonly CliRow[] }[] {\n const roots = groups.filter((group) => group.command.length === 1);\n const loose = commands.filter((command) =>\n !roots.some((group) => startsWith(command.command, group.command))\n );\n const sections = roots.map((group) => ({\n ...(roots.length > 1 || loose.length\n ? { title: group.title ?? group.command.join(\" \") }\n : {}),\n rows: commands\n .filter((command) => startsWith(command.command, group.command))\n .map(row),\n })).filter((section) => section.rows.length > 0);\n return [\n ...sections,\n ...(loose.length\n ? [{\n ...(sections.length ? { title: \"General\" } : {}),\n rows: loose.map(row),\n }]\n : []),\n ];\n}\n\nfunction row(command: CliCommand): CliRow {\n return { label: signature(command), ...describe(command) };\n}\n\nfunction describe(command: CliCommand): { description?: string } {\n const text = command.capability.title ?? command.capability.description;\n return text ? { description: text } : {};\n}\n\n/** `todo delete <todoId>` — command path plus its positional slots. */\nfunction signature(\n command: CliCommand,\n path: readonly string[] = command.command,\n): string {\n const required = requiredFields(command);\n return [\n ...path,\n ...(command.meta.positional ?? []).map((name) =>\n placeholder(name, required.has(name))\n ),\n ].join(\" \");\n}\n\nfunction placeholder(name: string, required: boolean): string {\n return required ? `<${name}>` : `[${name}]`;\n}\n\n/** Title, prose, then the invocation line. No heading needed above it. */\nfunction banner(options: {\n readonly title?: string;\n readonly description?: string;\n readonly usage: string;\n readonly style: CliStyle;\n}): string {\n const { style } = options;\n return [\n [\n options.title ? `${MARGIN}${style.bold(options.title)}` : undefined,\n options.description\n ? `${MARGIN}${style.dim(options.description)}`\n : undefined,\n ].filter(Boolean).join(\"\\n\"),\n `${MARGIN}${style.accent(options.usage)}`,\n ].filter(Boolean).join(\"\\n\\n\");\n}\n\nfunction hint(text: string, style: CliStyle): string {\n return `${MARGIN}${style.dim(text)}`;\n}\n\nfunction fields(command: CliCommand): Record<string, JsonSchema> {\n return (command.capability.input?.properties as\n | Record<string, JsonSchema>\n | undefined) ?? {};\n}\n\nfunction requiredFields(command: CliCommand): ReadonlySet<string> {\n return new Set(\n command.capability.input?.required as readonly string[] | undefined,\n );\n}\n\nfunction optionLabel(name: string, schema: JsonSchema): string {\n const flag = `--${kebabCase(name)}`;\n if (schema.type === \"boolean\") return flag;\n if (Array.isArray(schema.enum)) {\n return `${flag} <${schema.enum.map(String).join(\"|\")}>`;\n }\n if (schema.type === \"array\" || schema.type === \"object\") {\n return `${flag} <json>`;\n }\n return `${flag} <${String(schema.type ?? \"value\")}>`;\n}\n\n/**\n * Descriptions stay one short line: prose first, then only the facts a reader\n * cannot guess from the label (requiredness, defaults, choices).\n */\nfunction description(\n schema: JsonSchema | undefined,\n options: { readonly required?: boolean; readonly choices?: boolean } = {},\n): { description?: string } {\n const prose = typeof schema?.description === \"string\"\n ? schema.description\n : undefined;\n const notes = [\n options.choices && Array.isArray(schema?.enum)\n ? `one of ${schema.enum.map(String).join(\", \")}`\n : undefined,\n schema?.default !== undefined\n ? `default: ${String(schema.default)}`\n : undefined,\n options.required ? \"required\" : undefined,\n ].filter(Boolean);\n const text = [prose, notes.length ? `(${notes.join(\", \")})` : undefined]\n .filter(Boolean)\n .join(\" \");\n return text ? { description: text } : {};\n}\n\nfunction startsWith(\n value: readonly string[],\n prefix: readonly string[],\n): boolean {\n return prefix.every((part, index) => value[index] === part);\n}\n\nfunction kebabCase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);\n}\n\nfunction renderHelp(sections: readonly (string | undefined)[]): string {\n return `\\n${sections.filter(Boolean).join(\"\\n\\n\")}\\n`;\n}\n","import type { CapabilityResult } from \"@capable/app\";\nimport { renderPresentationMarkdown } from \"@capable/core\";\nimport { render as renderMarkdown } from \"markdansi\";\n\nexport type CliPresentationOptions = {\n readonly color: boolean;\n readonly isTTY: boolean;\n readonly columns: number;\n};\n\nexport function renderCliCapabilityResult(\n result: CapabilityResult,\n options: CliPresentationOptions,\n): string {\n if (result.presentation !== undefined) {\n return renderCliMarkdown(\n renderPresentationMarkdown(result.presentation),\n options,\n );\n }\n return typeof result.output === \"string\"\n ? result.output\n : JSON.stringify(result.output, null, 2);\n}\n\nfunction renderCliMarkdown(\n markdown: string,\n options: CliPresentationOptions,\n): string {\n return options.isTTY\n ? renderMarkdown(markdown, {\n color: options.color,\n width: options.columns,\n })\n : markdown;\n}\n","import type {\n GroupMetaRegistry,\n CapabilityMetaRegistry,\n} from \"@capable/core\";\nimport {\n getAppRuntime,\n TransportError,\n type AnyApp,\n type JsonSchema,\n} from \"@capable/app\";\nimport {\n collectCommands,\n type CliCommand,\n type CliCommandGroup,\n} from \"./commands.ts\";\nimport {\n renderCommandHelp,\n renderGroupHelp,\n renderRootHelp,\n} from \"./help.ts\";\nimport {\n createCliStyle,\n supportsColor,\n} from \"./style.ts\";\nimport { renderCliCapabilityResult } from \"./presentation.ts\";\n\n/** Shared help layout, so every Capable surface prints the same shape. */\nexport {\n createCliStyle,\n descriptionColumn,\n MARGIN,\n renderRows,\n renderSection,\n ROW_INDENT,\n supportsColor,\n type CliRow,\n type CliStyle,\n} from \"./style.ts\";\n\nexport type CliCapabilityMeta =\n | false\n | {\n readonly name?: string;\n readonly command?: readonly string[];\n readonly positional?: readonly string[];\n };\n\nexport type CliGroupMeta = {\n readonly name?: string;\n};\n\ndeclare module \"@capable/core\" {\n interface CapabilityMetaRegistry {\n readonly cli?: CliCapabilityMeta;\n }\n\n interface GroupMetaRegistry {\n readonly cli?: CliGroupMeta;\n }\n}\n\nexport type CliIo = {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n};\n\nexport type CreateCliOptions = {\n readonly invocationName?: string;\n readonly color?: boolean;\n readonly isTTY?: boolean;\n readonly columns?: number;\n};\n\nexport function createCli(\n app: AnyApp,\n cliOptions: CreateCliOptions = {},\n): {\n run(\n argv: readonly string[],\n options?: { readonly io?: Partial<CliIo> },\n ): Promise<number>;\n} {\n return Object.freeze({\n run(argv, options = {}) {\n return runCli({\n app,\n argv,\n ...(cliOptions.invocationName\n ? { invocationName: cliOptions.invocationName }\n : {}),\n ...(cliOptions.color !== undefined ? { color: cliOptions.color } : {}),\n ...(cliOptions.isTTY !== undefined ? { isTTY: cliOptions.isTTY } : {}),\n ...(cliOptions.columns !== undefined\n ? { columns: cliOptions.columns }\n : {}),\n ...(options.io ? { io: options.io } : {}),\n });\n },\n });\n}\n\nexport async function runCli(options: {\n readonly app: AnyApp;\n readonly argv: readonly string[];\n readonly invocationName?: string;\n readonly color?: boolean;\n readonly isTTY?: boolean;\n readonly columns?: number;\n readonly io?: Partial<CliIo>;\n}): Promise<number> {\n const io: CliIo = {\n stdout: options.io?.stdout ??\n ((text) => process.stdout.write(withTrailingNewline(text))),\n stderr: options.io?.stderr ??\n ((text) => process.stderr.write(withTrailingNewline(text))),\n };\n const invocationName = options.invocationName ?? \"cap\";\n const isTTY = options.isTTY ?? Boolean(process.stdout.isTTY);\n const color = options.color ?? supportsColor(process.env, isTTY);\n const columns = options.columns ?? process.stdout.columns ?? 80;\n const style = createCliStyle(color);\n const runtime = getAppRuntime(options.app);\n let manifest;\n try {\n manifest = await runtime.manifest();\n } catch (error) {\n io.stderr(renderRuntimeError(error));\n return 1;\n }\n const catalog = collectCommands(manifest.capabilities);\n const json = options.argv.includes(\"--json\");\n const watch = options.argv.includes(\"--watch\");\n const wantsHelp = options.argv.includes(\"--help\") ||\n options.argv.includes(\"-h\");\n const argv = options.argv.filter((argument) =>\n ![\"--json\", \"--watch\", \"--help\", \"-h\"].includes(argument)\n );\n\n if (argv.length === 0) {\n io.stdout(renderRootHelp(\n manifest,\n catalog.commands,\n catalog.groups,\n invocationName,\n style,\n ));\n return 0;\n }\n\n const command = matchCommand(argv, catalog.commands);\n const group = exactGroup(argv, catalog.groups);\n if (wantsHelp) {\n if (command) {\n io.stdout(renderCommandHelp(command, invocationName, style));\n return 0;\n }\n if (group) {\n io.stdout(renderGroupHelp(\n group,\n catalog.commands,\n invocationName,\n style,\n ));\n return 0;\n }\n io.stderr(unknownCommand(argv, catalog.commands, invocationName));\n return 2;\n }\n\n if (!command) {\n if (group) {\n io.stderr(\n `Missing command after ${group.command.join(\" \")}\\n` +\n `Run \\`${invocationName} ${group.command.join(\" \")} --help\\` to list available commands.`,\n );\n return 2;\n }\n io.stderr(unknownCommand(argv, catalog.commands, invocationName));\n return 2;\n }\n\n try {\n if (watch && !command.capability.subscription) {\n throw new CliUsageError(\n `Option --watch is only available for subscribable Capabilities`,\n );\n }\n const input = parseArguments(\n argv.slice(command.command.length),\n command,\n invocationName,\n );\n if (watch) {\n return await runWatchedCommand({\n runtime,\n command,\n input,\n json,\n io,\n color,\n isTTY,\n columns,\n });\n }\n const result = await runtime.call({\n id: command.capability.id,\n input,\n ...(!json ? { presentation: true } : {}),\n });\n io.stdout(\n json\n ? JSON.stringify(result.output, null, 2)\n : renderCliCapabilityResult(result, {\n color,\n isTTY,\n columns,\n }),\n );\n return 0;\n } catch (error) {\n if (error instanceof CliUsageError) {\n io.stderr(error.message);\n return 2;\n }\n if (error instanceof TransportError) {\n io.stderr(renderRuntimeError(error));\n return 1;\n }\n io.stderr(error instanceof Error ? error.message : String(error));\n return 1;\n }\n}\n\nfunction withTrailingNewline(value: string): string {\n return value.endsWith(\"\\n\") ? value : `${value}\\n`;\n}\n\nasync function runWatchedCommand(options: {\n readonly runtime: ReturnType<typeof getAppRuntime>;\n readonly command: CliCommand;\n readonly input: Record<string, unknown>;\n readonly json: boolean;\n readonly io: CliIo;\n readonly color: boolean;\n readonly isTTY: boolean;\n readonly columns: number;\n}): Promise<number> {\n const controller = new AbortController();\n const abort = () => controller.abort();\n process.once(\"SIGINT\", abort);\n const stream = options.runtime.subscribe({\n id: options.command.capability.id,\n input: options.input,\n ...(!options.json ? { presentation: true } : {}),\n signal: controller.signal,\n });\n\n try {\n let frame = 0;\n let previousFrameLines = 0;\n for await (const result of stream) {\n if (options.json) {\n options.io.stdout(`${JSON.stringify(result.output)}\\n`);\n continue;\n }\n const presentation = renderCliCapabilityResult(result, options);\n options.io.stdout(formatWatchFrame(\n presentation,\n frame++,\n options.isTTY,\n previousFrameLines,\n ));\n previousFrameLines = countFrameLines(presentation);\n }\n return 0;\n } catch (error) {\n if (controller.signal.aborted || isAbortError(error)) return 0;\n throw error;\n } finally {\n process.off(\"SIGINT\", abort);\n await stream.return?.();\n }\n}\n\nfunction formatWatchFrame(\n value: string,\n index: number,\n isTTY: boolean,\n previousFrameLines: number,\n): string {\n const frame = value.endsWith(\"\\n\") ? value : `${value}\\n`;\n if (isTTY) {\n return index === 0\n ? frame\n : `\\u001B[${previousFrameLines}A\\r\\u001B[0J${frame}`;\n }\n return index === 0 ? frame : `\\n---\\n\\n${frame}`;\n}\n\nfunction countFrameLines(value: string): number {\n const frame = value.endsWith(\"\\n\") ? value : `${value}\\n`;\n return frame.split(\"\\n\").length - 1;\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof DOMException && error.name === \"AbortError\";\n}\n\nfunction parseArguments(\n argv: readonly string[],\n command: CliCommand,\n invocationName: string,\n): Record<string, unknown> {\n const capability = command.capability;\n const positional = command.meta.positional ?? [];\n const commandName = `${invocationName} ${command.command.join(\" \")}`;\n const schema = capability.input;\n const properties = schema?.properties as\n | Record<string, JsonSchema>\n | undefined;\n const input: Record<string, unknown> = {};\n let position = 0;\n\n for (let index = 0; index < argv.length; index++) {\n const token = argv[index]!;\n if (token.startsWith(\"--\")) {\n const [rawName, inline] = token.slice(2).split(\"=\", 2);\n const name = camelCase(rawName!);\n const field = properties?.[name];\n if (!field || positional.includes(name)) {\n const suggestion = nearest(\n rawName!,\n Object.keys(properties ?? {})\n .filter((candidate) => !positional.includes(candidate))\n .map(kebabCase),\n );\n throw new CliUsageError([\n `Unknown option --${rawName}`,\n ...(suggestion ? [`Did you mean \\`--${suggestion}\\`?`] : []),\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n ].join(\"\\n\"));\n }\n const boolean = field.type === \"boolean\";\n const raw = inline ?? (boolean ? \"true\" : argv[++index]);\n if (raw === undefined) {\n throw new CliUsageError(\n `Option --${rawName} requires a value\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n input[name] = coerce(raw, field, `--${rawName}`, commandName);\n continue;\n }\n const name = positional[position++];\n if (!name) {\n throw new CliUsageError(\n `Unexpected argument \"${token}\"\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n const field = properties?.[name];\n if (!field) {\n throw new CliUsageError(\n `CLI positional field \"${name}\" is not present in the input schema`,\n );\n }\n input[name] = coerce(token, field, `<${name}>`, commandName);\n }\n\n const required = schema?.required as readonly string[] | undefined;\n for (const name of required ?? []) {\n if (!(name in input)) {\n const label = positional.includes(name)\n ? `positional argument <${name}>`\n : `required option --${kebabCase(name)}`;\n throw new CliUsageError(\n `Missing ${label}\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n }\n return input;\n}\n\nfunction coerce(\n value: string,\n schema: JsonSchema,\n label: string,\n commandName: string,\n): unknown {\n if (schema.type === \"boolean\") return value !== \"false\";\n if (schema.type === \"integer\" || schema.type === \"number\") {\n const number = Number(value);\n if (!Number.isFinite(number)) {\n throw new CliUsageError(\n `Expected a number for ${label}, received \"${value}\"\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n return number;\n }\n return value;\n}\n\nclass CliUsageError extends Error {}\n\nfunction renderRuntimeError(error: unknown): string {\n return error instanceof TransportError\n ? `${error.code}: ${error.message}`\n : error instanceof Error\n ? error.message\n : String(error);\n}\n\nfunction matchCommand(\n argv: readonly string[],\n commands: readonly CliCommand[],\n): CliCommand | undefined {\n return commands\n .filter((candidate) =>\n candidate.command.every((token, index) => argv[index] === token)\n )\n .sort((left, right) => right.command.length - left.command.length)[0];\n}\n\nfunction exactGroup(\n argv: readonly string[],\n groups: readonly CliCommandGroup[],\n): CliCommandGroup | undefined {\n return groups.find((group) =>\n group.command.length === argv.length &&\n group.command.every((token, index) => argv[index] === token)\n );\n}\n\nfunction unknownCommand(\n argv: readonly string[],\n commands: readonly CliCommand[],\n invocationName: string,\n): string {\n const entered = argv.join(\" \");\n const suggestion = nearest(\n entered,\n commands.map((command) => command.command.join(\" \")),\n );\n return [\n `Unknown command: ${entered}`,\n ...(suggestion ? [`Did you mean \\`${suggestion}\\`?`] : []),\n `Run \\`${invocationName} --help\\` to list available commands.`,\n ].join(\"\\n\");\n}\n\nfunction nearest(\n value: string,\n candidates: readonly string[],\n): string | undefined {\n let match: { readonly candidate: string; readonly distance: number } | undefined;\n for (const candidate of new Set(candidates)) {\n const distance = editDistance(value, candidate);\n if (!match || distance < match.distance) {\n match = { candidate, distance };\n }\n }\n if (!match) return undefined;\n return match.distance <= Math.max(2, Math.floor(match.candidate.length / 3))\n ? match.candidate\n : undefined;\n}\n\nfunction editDistance(left: string, right: string): number {\n const previous = Array.from(\n { length: right.length + 1 },\n (_, index) => index,\n );\n for (let leftIndex = 1; leftIndex <= left.length; leftIndex++) {\n const current = [leftIndex];\n for (let rightIndex = 1; rightIndex <= right.length; rightIndex++) {\n current[rightIndex] = Math.min(\n current[rightIndex - 1]! + 1,\n previous[rightIndex]! + 1,\n previous[rightIndex - 1]! +\n (left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1),\n );\n }\n previous.splice(0, previous.length, ...current);\n }\n return previous[right.length]!;\n}\n\nfunction camelCase(value: string): string {\n return value.replace(/-([a-z])/g, (_, character: string) =>\n character.toUpperCase()\n );\n}\n\nfunction kebabCase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);\n}\n"],"mappings":";;;;AA2BA,SAAgB,gBACd,O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G,aAAa,KAAK,QAAQ,aAAa;EAC7D,MAAM,UAAU,CAAC,SAAS;EAC1B,KAAK,IAAI,aAAa,GAAG,cAAc,MAAM,QAAQ,cACnD,QAAQ,cAAc,KAAK,IACzB,QAAQ,aAAa,KAAM,GAC3B,SAAS,cAAe,GACxB,SAAS,aAAa,MACnB,KAAK,YAAY,OAAO,MAAM,aAAa,KAAK,IAAI,EACzD;EAEF,SAAS,OAAO,GAAG,SAAS,QAAQ,GAAG,OAAO;CAChD;CACA,OAAO,SAAS,MAAM;AACxB;AAEA,SAAS,UAAU,OAAuB;CACxC,OAAO,MAAM,QAAQ,cAAc,GAAG,cACpC,UAAU,YAAY,CACxB;AACF;AAEA,SAAS,UAAU,OAAuB;CACxC,OAAO,MAAM,QAAQ,WAAW,cAAc,IAAI,UAAU,YAAY,GAAG;AAC7E"}
|
|
@@ -51,6 +51,140 @@ function errorDefinitions(errors) {
|
|
|
51
51
|
return errors[CAPABILITY_ERROR_DEFINITIONS_SYMBOL];
|
|
52
52
|
}
|
|
53
53
|
//#endregion
|
|
54
|
+
//#region packages/core/src/presentation.ts
|
|
55
|
+
const present = Object.freeze({
|
|
56
|
+
table(options) {
|
|
57
|
+
return {
|
|
58
|
+
type: "table",
|
|
59
|
+
...options.caption !== void 0 ? { caption: options.caption } : {},
|
|
60
|
+
columns: options.columns,
|
|
61
|
+
rows: options.rows
|
|
62
|
+
};
|
|
63
|
+
},
|
|
64
|
+
image(options) {
|
|
65
|
+
return {
|
|
66
|
+
type: "image",
|
|
67
|
+
base64: options.base64,
|
|
68
|
+
mimeType: options.mimeType,
|
|
69
|
+
alt: options.alt
|
|
70
|
+
};
|
|
71
|
+
},
|
|
72
|
+
file(options) {
|
|
73
|
+
return {
|
|
74
|
+
type: "file",
|
|
75
|
+
url: options.url,
|
|
76
|
+
name: options.name,
|
|
77
|
+
...options.mimeType !== void 0 ? { mimeType: options.mimeType } : {},
|
|
78
|
+
...options.size !== void 0 ? { size: options.size } : {},
|
|
79
|
+
...options.description !== void 0 ? { description: options.description } : {}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
function normalizePresentation(value) {
|
|
84
|
+
return Object.freeze((Array.isArray(value) ? value : [value]).map((node, index) => {
|
|
85
|
+
if (typeof node === "string") return Object.freeze({
|
|
86
|
+
type: "markdown",
|
|
87
|
+
markdown: node
|
|
88
|
+
});
|
|
89
|
+
return normalizePresentationPart(node, index);
|
|
90
|
+
}));
|
|
91
|
+
}
|
|
92
|
+
function renderPresentationMarkdown(presentation) {
|
|
93
|
+
return (Array.isArray(presentation) ? presentation : [presentation]).map(renderPresentationPartMarkdown).join("\n\n");
|
|
94
|
+
}
|
|
95
|
+
function renderPresentationPartMarkdown(part) {
|
|
96
|
+
if (part.type === "markdown") return part.markdown;
|
|
97
|
+
if (part.type === "table") return renderTableMarkdown(part);
|
|
98
|
+
if (part.type === "image") return `[Image: ${part.alt}]`;
|
|
99
|
+
const metadata = [part.mimeType, part.size === void 0 ? void 0 : formatBytes(part.size)].filter(Boolean).join(", ");
|
|
100
|
+
return [
|
|
101
|
+
`[${escapeMarkdown(part.name)}](${part.url})`,
|
|
102
|
+
part.description,
|
|
103
|
+
metadata ? `(${metadata})` : void 0
|
|
104
|
+
].filter(Boolean).join(" — ");
|
|
105
|
+
}
|
|
106
|
+
function renderTableMarkdown(table) {
|
|
107
|
+
const lines = [
|
|
108
|
+
`| ${table.columns.map(escapeTableCell).join(" | ")} |`,
|
|
109
|
+
`| ${table.columns.map(() => "---").join(" | ")} |`,
|
|
110
|
+
...table.rows.map((row) => `| ${row.map((cell) => escapeTableCell(cell === null ? "" : String(cell))).join(" | ")} |`)
|
|
111
|
+
];
|
|
112
|
+
return table.caption === void 0 ? lines.join("\n") : `**${escapeMarkdown(table.caption)}**\n\n${lines.join("\n")}`;
|
|
113
|
+
}
|
|
114
|
+
function normalizePresentationPart(part, index) {
|
|
115
|
+
if (!part || typeof part !== "object") throw new Error(`Presentation part ${index} must be a string or object`);
|
|
116
|
+
if (part.type === "markdown") {
|
|
117
|
+
assertString(part.markdown, `Presentation part ${index} markdown`);
|
|
118
|
+
return Object.freeze({
|
|
119
|
+
type: "markdown",
|
|
120
|
+
markdown: part.markdown
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
if (part.type === "table") {
|
|
124
|
+
if (part.caption !== void 0) assertString(part.caption, `Presentation part ${index} caption`);
|
|
125
|
+
if (!Array.isArray(part.columns) || part.columns.length === 0) throw new Error(`Presentation part ${index} table requires columns`);
|
|
126
|
+
part.columns.forEach((column, columnIndex) => assertString(column, `Presentation part ${index} column ${columnIndex}`));
|
|
127
|
+
if (!Array.isArray(part.rows)) throw new Error(`Presentation part ${index} table rows must be an array`);
|
|
128
|
+
const rows = part.rows.map((row, rowIndex) => {
|
|
129
|
+
if (!Array.isArray(row) || row.length !== part.columns.length) throw new Error(`Presentation part ${index} row ${rowIndex} must have ${part.columns.length} cells`);
|
|
130
|
+
for (const cell of row) {
|
|
131
|
+
if (cell !== null && typeof cell !== "string" && typeof cell !== "number" && typeof cell !== "boolean") throw new Error(`Presentation part ${index} row ${rowIndex} has a non-scalar cell`);
|
|
132
|
+
if (typeof cell === "number" && !Number.isFinite(cell)) throw new Error(`Presentation part ${index} row ${rowIndex} has a non-finite number`);
|
|
133
|
+
}
|
|
134
|
+
return Object.freeze([...row]);
|
|
135
|
+
});
|
|
136
|
+
return Object.freeze({
|
|
137
|
+
type: "table",
|
|
138
|
+
...part.caption !== void 0 ? { caption: part.caption } : {},
|
|
139
|
+
columns: Object.freeze([...part.columns]),
|
|
140
|
+
rows: Object.freeze(rows)
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
if (part.type === "image") {
|
|
144
|
+
assertString(part.base64, `Presentation part ${index} image base64`);
|
|
145
|
+
assertString(part.mimeType, `Presentation part ${index} image MIME type`);
|
|
146
|
+
if (!part.mimeType.startsWith("image/")) throw new Error(`Presentation part ${index} image MIME type must start with "image/"`);
|
|
147
|
+
assertString(part.alt, `Presentation part ${index} image alt text`);
|
|
148
|
+
return Object.freeze({
|
|
149
|
+
type: "image",
|
|
150
|
+
base64: part.base64,
|
|
151
|
+
mimeType: part.mimeType,
|
|
152
|
+
alt: part.alt
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
if (part.type === "file") {
|
|
156
|
+
assertString(part.url, `Presentation part ${index} file URL`);
|
|
157
|
+
assertString(part.name, `Presentation part ${index} file name`);
|
|
158
|
+
if (part.mimeType !== void 0) assertString(part.mimeType, `Presentation part ${index} file MIME type`);
|
|
159
|
+
if (part.size !== void 0 && (!Number.isInteger(part.size) || part.size < 0)) throw new Error(`Presentation part ${index} file size must be a non-negative integer`);
|
|
160
|
+
if (part.description !== void 0) assertString(part.description, `Presentation part ${index} file description`);
|
|
161
|
+
return Object.freeze({
|
|
162
|
+
type: "file",
|
|
163
|
+
url: part.url,
|
|
164
|
+
name: part.name,
|
|
165
|
+
...part.mimeType !== void 0 ? { mimeType: part.mimeType } : {},
|
|
166
|
+
...part.size !== void 0 ? { size: part.size } : {},
|
|
167
|
+
...part.description !== void 0 ? { description: part.description } : {}
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
throw new Error(`Presentation part ${index} has unknown type "${String(part.type)}"`);
|
|
171
|
+
}
|
|
172
|
+
function escapeTableCell(value) {
|
|
173
|
+
return value.replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
|
|
174
|
+
}
|
|
175
|
+
function escapeMarkdown(value) {
|
|
176
|
+
return value.replace(/([\\`*_[\]<>])/g, "\\$1");
|
|
177
|
+
}
|
|
178
|
+
function formatBytes(value) {
|
|
179
|
+
if (value < 1e3) return `${value} B`;
|
|
180
|
+
if (value < 1e6) return `${(value / 1e3).toFixed(1)} kB`;
|
|
181
|
+
if (value < 1e9) return `${(value / 1e6).toFixed(1)} MB`;
|
|
182
|
+
return `${(value / 1e9).toFixed(1)} GB`;
|
|
183
|
+
}
|
|
184
|
+
function assertString(value, label) {
|
|
185
|
+
if (typeof value !== "string") throw new Error(`${label} must be a string`);
|
|
186
|
+
}
|
|
187
|
+
//#endregion
|
|
54
188
|
//#region packages/core/src/subscription.ts
|
|
55
189
|
/**
|
|
56
190
|
* Turn an invalidation source into a stream of complete replacement snapshots.
|
|
@@ -247,7 +381,7 @@ function createCapability(config) {
|
|
|
247
381
|
meta: Object.freeze({ ...config.meta ?? {} }),
|
|
248
382
|
handler: config.handler,
|
|
249
383
|
...config.subscribe ? { subscribe: config.subscribe } : {},
|
|
250
|
-
...config.
|
|
384
|
+
...config.toPresentation ? { toPresentation: config.toPresentation } : {}
|
|
251
385
|
});
|
|
252
386
|
}
|
|
253
387
|
async function executeCapability(capability, options) {
|
|
@@ -533,6 +667,6 @@ function isRecord(value) {
|
|
|
533
667
|
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
534
668
|
}
|
|
535
669
|
//#endregion
|
|
536
|
-
export {
|
|
670
|
+
export { defineErrors as S, normalizePresentation as _, isCapabilityGroup as a, CAPABILITY_ERRORS_SYMBOL as b, executeCapability as c, subscribeCapability as d, subscribeLocatedCapability as f, watchQuery as g, schemaToJsonSchema as h, group as i, executeLocatedCapability as l, parseSchema as m, CAPABILITY_GROUP_SYMBOL as n, CAPABILITY_SYMBOL as o, SchemaValidationError as p, defineApp as r, capability as s, APPLICATION_SYMBOL as t, isCapability as u, present as v, CapableError as x, renderPresentationMarkdown as y };
|
|
537
671
|
|
|
538
|
-
//# sourceMappingURL=src-
|
|
672
|
+
//# sourceMappingURL=src-DdV82An-.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-DdV82An-.mjs","names":["NO_ERRORS","isRecord"],"sources":["../../core/src/errors.ts","../../core/src/presentation.ts","../../core/src/subscription.ts","../../core/src/schema.ts","../../core/src/capability.ts","../../core/src/application.ts"],"sourcesContent":["import type {\n AnySchema,\n InferSchemaInput,\n InferSchemaOutput,\n} from \"./schema.ts\";\n\nexport const CAPABILITY_ERRORS_SYMBOL: unique symbol = Symbol.for(\n \"capable.capability-errors\",\n) as never;\nexport const CAPABILITY_ERROR_DEFINITIONS_SYMBOL: unique symbol = Symbol.for(\n \"capable.capability-error-definitions\",\n) as never;\n\nexport interface ErrorMetaRegistry {}\n\ntype OpenErrorMeta =\n & Partial<ErrorMetaRegistry>\n & Readonly<Record<string, unknown>>;\n\nexport type CapabilityErrorDefinition<\n TData extends AnySchema | undefined = AnySchema | undefined,\n> = {\n readonly message?: string;\n readonly status?: number;\n readonly data?: TData;\n readonly meta?: OpenErrorMeta;\n readonly [key: string]: unknown;\n};\n\nexport type CapabilityErrorContract = Readonly<\n Record<string, CapabilityErrorDefinition>\n>;\n\nexport class CapableError<\n TCode extends string = string,\n TData = unknown,\n> extends Error {\n readonly code: TCode;\n readonly status: number | undefined;\n readonly data: TData;\n\n constructor(\n code: TCode,\n options: {\n message?: string;\n status?: number;\n data?: TData;\n cause?: unknown;\n } = {},\n ) {\n super(options.message ?? code, { cause: options.cause });\n this.name = \"CapableError\";\n this.code = code;\n this.status = options.status;\n this.data = options.data as TData;\n }\n}\n\ntype ErrorDataSchema<TDefinition extends CapabilityErrorDefinition> =\n TDefinition extends { readonly data: infer TData extends AnySchema }\n ? TData\n : undefined;\n\ntype ErrorDataInput<TDefinition extends CapabilityErrorDefinition> =\n ErrorDataSchema<TDefinition> extends infer TData extends AnySchema\n ? InferSchemaInput<TData>\n : undefined;\n\ntype ErrorDataOutput<TDefinition extends CapabilityErrorDefinition> =\n ErrorDataSchema<TDefinition> extends infer TData extends AnySchema\n ? InferSchemaOutput<TData>\n : undefined;\n\ntype ErrorFactoryArgs<TDefinition extends CapabilityErrorDefinition> =\n ErrorDataSchema<TDefinition> extends AnySchema\n ? [\n data: ErrorDataInput<TDefinition>,\n options?: { readonly cause?: unknown },\n ]\n : [options?: { readonly cause?: unknown }];\n\nexport type CapabilityErrorFactory<\n TCode extends string,\n TDefinition extends CapabilityErrorDefinition,\n> = {\n (...args: ErrorFactoryArgs<TDefinition>): CapableError<\n TCode,\n ErrorDataOutput<TDefinition>\n >;\n readonly code: TCode;\n readonly definition: TDefinition;\n is(error: unknown): error is CapableError<\n TCode,\n ErrorDataOutput<TDefinition>\n >;\n};\n\nexport type DefinedErrors<\n TDefinitions extends CapabilityErrorContract,\n> = {\n readonly [TCode in keyof TDefinitions & string]: CapabilityErrorFactory<\n TCode,\n TDefinitions[TCode]\n >;\n} & {\n readonly [CAPABILITY_ERRORS_SYMBOL]: true;\n readonly [CAPABILITY_ERROR_DEFINITIONS_SYMBOL]: TDefinitions;\n};\n\nexport type AnyDefinedErrors = {\n readonly [CAPABILITY_ERRORS_SYMBOL]: true;\n readonly [CAPABILITY_ERROR_DEFINITIONS_SYMBOL]: CapabilityErrorContract;\n};\n\nexport function defineErrors<\n const TDefinitions extends CapabilityErrorContract,\n>(definitions: TDefinitions): DefinedErrors<TDefinitions> {\n const frozenDefinitions = Object.freeze({ ...definitions }) as TDefinitions;\n const result: Record<PropertyKey, unknown> = {};\n\n for (const [code, definition] of Object.entries(frozenDefinitions)) {\n const create = ((\n first?: unknown,\n second?: { readonly cause?: unknown },\n ) => {\n const hasData = definition.data !== undefined;\n const data = hasData ? first : undefined;\n const options = (hasData ? second : first) as\n | { readonly cause?: unknown }\n | undefined;\n return new CapableError(code, {\n ...(definition.message ? { message: definition.message } : {}),\n ...(typeof definition.status === \"number\"\n ? { status: definition.status }\n : {}),\n ...(hasData ? { data } : {}),\n ...(options &&\n typeof options === \"object\" &&\n \"cause\" in options\n ? { cause: options.cause }\n : {}),\n });\n }) as CapabilityErrorFactory<string, CapabilityErrorDefinition>;\n\n Object.defineProperties(create, {\n code: { value: code, enumerable: true },\n definition: { value: definition, enumerable: true },\n is: {\n value: (error: unknown) =>\n error instanceof Error &&\n \"code\" in error &&\n error.code === code,\n },\n });\n result[code] = Object.freeze(create);\n }\n\n Object.defineProperties(result, {\n [CAPABILITY_ERRORS_SYMBOL]: { value: true },\n [CAPABILITY_ERROR_DEFINITIONS_SYMBOL]: { value: frozenDefinitions },\n });\n return Object.freeze(result) as DefinedErrors<TDefinitions>;\n}\n\nexport function errorDefinitions(\n errors: AnyDefinedErrors,\n): CapabilityErrorContract {\n return errors[CAPABILITY_ERROR_DEFINITIONS_SYMBOL];\n}\n","import type { MaybePromise } from \"./projection.ts\";\n\nexport type PresentationTableCell = string | number | boolean | null;\n\nexport type MarkdownPresentationPart = {\n readonly type: \"markdown\";\n readonly markdown: string;\n};\n\nexport type TablePresentationPart = {\n readonly type: \"table\";\n readonly caption?: string;\n readonly columns: readonly string[];\n readonly rows: readonly (readonly PresentationTableCell[])[];\n};\n\nexport type ImagePresentationPart = {\n readonly type: \"image\";\n readonly base64: string;\n readonly mimeType: `image/${string}`;\n readonly alt: string;\n};\n\nexport type FilePresentationPart = {\n readonly type: \"file\";\n readonly url: string;\n readonly name: string;\n readonly mimeType?: string;\n readonly size?: number;\n readonly description?: string;\n};\n\nexport type PresentationPart =\n | MarkdownPresentationPart\n | TablePresentationPart\n | ImagePresentationPart\n | FilePresentationPart;\n\ntype PresentationNode = string | PresentationPart;\nexport type PresentationValue =\n | PresentationNode\n | readonly PresentationNode[];\n\nexport type PresentationRenderer<TOutput, TContext> = (\n output: TOutput,\n options: { readonly context: TContext },\n) => MaybePromise<PresentationValue>;\n\ntype TablePresentationOptions = Omit<TablePresentationPart, \"type\">;\ntype ImagePresentationOptions = Omit<ImagePresentationPart, \"type\">;\ntype FilePresentationOptions = Omit<FilePresentationPart, \"type\">;\n\ntype PresentationBuilders = Readonly<{\n table(options: TablePresentationOptions): TablePresentationPart;\n image(options: ImagePresentationOptions): ImagePresentationPart;\n file(options: FilePresentationOptions): FilePresentationPart;\n}>;\n\nexport const present: PresentationBuilders = Object.freeze({\n table(options) {\n return {\n type: \"table\",\n ...(options.caption !== undefined ? { caption: options.caption } : {}),\n columns: options.columns,\n rows: options.rows,\n };\n },\n image(options) {\n return {\n type: \"image\",\n base64: options.base64,\n mimeType: options.mimeType,\n alt: options.alt,\n };\n },\n file(options) {\n return {\n type: \"file\",\n url: options.url,\n name: options.name,\n ...(options.mimeType !== undefined ? { mimeType: options.mimeType } : {}),\n ...(options.size !== undefined ? { size: options.size } : {}),\n ...(options.description !== undefined\n ? { description: options.description }\n : {}),\n };\n },\n});\n\nexport function normalizePresentation(\n value: PresentationValue,\n): readonly PresentationPart[] {\n const nodes = Array.isArray(value) ? value : [value];\n return Object.freeze(nodes.map((node, index) => {\n if (typeof node === \"string\") {\n return Object.freeze({\n type: \"markdown\" as const,\n markdown: node,\n });\n }\n return normalizePresentationPart(node, index);\n }));\n}\n\nexport function renderPresentationMarkdown(\n presentation: PresentationPart | readonly PresentationPart[],\n): string {\n const parts = Array.isArray(presentation) ? presentation : [presentation];\n return parts.map(renderPresentationPartMarkdown).join(\"\\n\\n\");\n}\n\nfunction renderPresentationPartMarkdown(part: PresentationPart): string {\n if (part.type === \"markdown\") return part.markdown;\n if (part.type === \"table\") return renderTableMarkdown(part);\n if (part.type === \"image\") return `[Image: ${part.alt}]`;\n\n const metadata = [\n part.mimeType,\n part.size === undefined ? undefined : formatBytes(part.size),\n ].filter(Boolean).join(\", \");\n return [\n `[${escapeMarkdown(part.name)}](${part.url})`,\n part.description,\n metadata ? `(${metadata})` : undefined,\n ].filter(Boolean).join(\" — \");\n}\n\nfunction renderTableMarkdown(table: TablePresentationPart): string {\n const lines = [\n `| ${table.columns.map(escapeTableCell).join(\" | \")} |`,\n `| ${table.columns.map(() => \"---\").join(\" | \")} |`,\n ...table.rows.map((row) =>\n `| ${row.map((cell) => escapeTableCell(cell === null ? \"\" : String(cell))).join(\" | \")} |`\n ),\n ];\n return table.caption === undefined\n ? lines.join(\"\\n\")\n : `**${escapeMarkdown(table.caption)}**\\n\\n${lines.join(\"\\n\")}`;\n}\n\nfunction normalizePresentationPart(\n part: PresentationPart,\n index: number,\n): PresentationPart {\n if (!part || typeof part !== \"object\") {\n throw new Error(`Presentation part ${index} must be a string or object`);\n }\n if (part.type === \"markdown\") {\n assertString(part.markdown, `Presentation part ${index} markdown`);\n return Object.freeze({\n type: \"markdown\",\n markdown: part.markdown,\n });\n }\n if (part.type === \"table\") {\n if (part.caption !== undefined) {\n assertString(part.caption, `Presentation part ${index} caption`);\n }\n if (!Array.isArray(part.columns) || part.columns.length === 0) {\n throw new Error(`Presentation part ${index} table requires columns`);\n }\n part.columns.forEach((column, columnIndex) =>\n assertString(\n column,\n `Presentation part ${index} column ${columnIndex}`,\n )\n );\n if (!Array.isArray(part.rows)) {\n throw new Error(`Presentation part ${index} table rows must be an array`);\n }\n const rows = part.rows.map((row, rowIndex) => {\n if (!Array.isArray(row) || row.length !== part.columns.length) {\n throw new Error(\n `Presentation part ${index} row ${rowIndex} must have ${part.columns.length} cells`,\n );\n }\n for (const cell of row) {\n if (\n cell !== null &&\n typeof cell !== \"string\" &&\n typeof cell !== \"number\" &&\n typeof cell !== \"boolean\"\n ) {\n throw new Error(\n `Presentation part ${index} row ${rowIndex} has a non-scalar cell`,\n );\n }\n if (typeof cell === \"number\" && !Number.isFinite(cell)) {\n throw new Error(\n `Presentation part ${index} row ${rowIndex} has a non-finite number`,\n );\n }\n }\n return Object.freeze([...row]);\n });\n return Object.freeze({\n type: \"table\",\n ...(part.caption !== undefined ? { caption: part.caption } : {}),\n columns: Object.freeze([...part.columns]),\n rows: Object.freeze(rows),\n });\n }\n if (part.type === \"image\") {\n assertString(part.base64, `Presentation part ${index} image base64`);\n assertString(part.mimeType, `Presentation part ${index} image MIME type`);\n if (!part.mimeType.startsWith(\"image/\")) {\n throw new Error(\n `Presentation part ${index} image MIME type must start with \"image/\"`,\n );\n }\n assertString(part.alt, `Presentation part ${index} image alt text`);\n return Object.freeze({\n type: \"image\",\n base64: part.base64,\n mimeType: part.mimeType,\n alt: part.alt,\n });\n }\n if (part.type === \"file\") {\n assertString(part.url, `Presentation part ${index} file URL`);\n assertString(part.name, `Presentation part ${index} file name`);\n if (part.mimeType !== undefined) {\n assertString(part.mimeType, `Presentation part ${index} file MIME type`);\n }\n if (\n part.size !== undefined &&\n (!Number.isInteger(part.size) || part.size < 0)\n ) {\n throw new Error(\n `Presentation part ${index} file size must be a non-negative integer`,\n );\n }\n if (part.description !== undefined) {\n assertString(\n part.description,\n `Presentation part ${index} file description`,\n );\n }\n return Object.freeze({\n type: \"file\",\n url: part.url,\n name: part.name,\n ...(part.mimeType !== undefined ? { mimeType: part.mimeType } : {}),\n ...(part.size !== undefined ? { size: part.size } : {}),\n ...(part.description !== undefined\n ? { description: part.description }\n : {}),\n });\n }\n throw new Error(\n `Presentation part ${index} has unknown type \"${String((part as { type?: unknown }).type)}\"`,\n );\n}\n\nfunction escapeTableCell(value: string): string {\n return value.replace(/\\|/g, \"\\\\|\").replace(/\\r?\\n/g, \" \");\n}\n\nfunction escapeMarkdown(value: string): string {\n return value.replace(/([\\\\`*_[\\]<>])/g, \"\\\\$1\");\n}\n\nfunction formatBytes(value: number): string {\n if (value < 1_000) return `${value} B`;\n if (value < 1_000_000) return `${(value / 1_000).toFixed(1)} kB`;\n if (value < 1_000_000_000) {\n return `${(value / 1_000_000).toFixed(1)} MB`;\n }\n return `${(value / 1_000_000_000).toFixed(1)} GB`;\n}\n\nfunction assertString(value: unknown, label: string): asserts value is string {\n if (typeof value !== \"string\") throw new Error(`${label} must be a string`);\n}\n","import type { MaybePromise } from \"./projection.ts\";\n\nexport type WatchQueryOptions<TOutput> = {\n readonly snapshot: () => MaybePromise<TOutput>;\n readonly invalidations: () => AsyncIterable<unknown>;\n readonly signal?: AbortSignal;\n};\n\n/**\n * Turn an invalidation source into a stream of complete replacement snapshots.\n *\n * The invalidation iterator is pulled before the first snapshot is read. A\n * change racing with that read therefore causes another snapshot rather than\n * being missed.\n */\nexport async function* watchQuery<TOutput>(\n options: WatchQueryOptions<TOutput>,\n): AsyncIterableIterator<TOutput> {\n if (options.signal?.aborted) return;\n\n const iterator = options.invalidations()[Symbol.asyncIterator]();\n let pending = nextHandled(iterator);\n\n try {\n yield await options.snapshot();\n\n while (!options.signal?.aborted) {\n const result = await pending;\n if (result.done) return;\n pending = nextHandled(iterator);\n yield await options.snapshot();\n }\n } finally {\n await iterator.return?.();\n }\n}\n\nfunction nextHandled(iterator: AsyncIterator<unknown>) {\n const pending = iterator.next();\n void pending.catch(() => undefined);\n return pending;\n}\n\ntype Deferred<T> = {\n readonly promise: Promise<T>;\n resolve(value: T): void;\n reject(error: unknown): void;\n};\n\nfunction deferred<T>(): Deferred<T> {\n let resolve!: (value: T) => void;\n let reject!: (error: unknown) => void;\n const promise = new Promise<T>((onResolve, onReject) => {\n resolve = onResolve;\n reject = onReject;\n });\n return { promise, resolve, reject };\n}\n\nexport type DemandStream<T> = {\n waitForDemand(): Promise<boolean>;\n emit(value: T): void;\n complete(): void;\n fail(error: unknown): void;\n onCancel(cleanup: () => void | Promise<void>): void;\n};\n\nexport function createDemandIterator<T>(\n produce: (stream: DemandStream<T>) => Promise<void>,\n): AsyncIterableIterator<T> {\n const demands: Deferred<IteratorResult<T>>[] = [];\n const demandWaiters: Array<() => void> = [];\n const cleanups: Array<() => void | Promise<void>> = [];\n let activeDemand: Deferred<IteratorResult<T>> | undefined;\n let started = false;\n let closed = false;\n let failure: unknown;\n let hasFailure = false;\n let failureDelivered = false;\n let task: Promise<void> | undefined;\n\n const wakeProducer = () => demandWaiters.shift()?.();\n const finishPending = () => {\n for (const demand of demands.splice(0)) {\n if (hasFailure && !failureDelivered) {\n failureDelivered = true;\n demand.reject(failure);\n } else {\n demand.resolve({ done: true, value: undefined });\n }\n }\n };\n\n const stream: DemandStream<T> = {\n async waitForDemand() {\n while (!closed && demands.length === 0) {\n await new Promise<void>((resolve) => demandWaiters.push(resolve));\n }\n if (closed) return false;\n activeDemand = demands.shift();\n return Boolean(activeDemand);\n },\n emit(value) {\n const demand = activeDemand;\n activeDemand = undefined;\n demand?.resolve({ done: false, value });\n },\n complete() {\n closed = true;\n activeDemand?.resolve({ done: true, value: undefined });\n activeDemand = undefined;\n finishPending();\n wakeProducer();\n },\n fail(error) {\n failure = error;\n hasFailure = true;\n closed = true;\n const demand = activeDemand;\n activeDemand = undefined;\n if (demand) {\n failureDelivered = true;\n demand.reject(error);\n }\n finishPending();\n wakeProducer();\n },\n onCancel(cleanup) {\n cleanups.push(cleanup);\n },\n };\n\n const start = () => {\n if (started) return;\n started = true;\n task = produce(stream).then(\n () => {\n if (!closed) stream.complete();\n },\n (error) => stream.fail(error),\n );\n };\n\n return {\n [Symbol.asyncIterator]() {\n return this;\n },\n next() {\n if (hasFailure && !failureDelivered) {\n failureDelivered = true;\n return Promise.reject(failure);\n }\n if (closed) return Promise.resolve({ done: true, value: undefined });\n const demand = deferred<IteratorResult<T>>();\n demands.push(demand);\n start();\n wakeProducer();\n return demand.promise;\n },\n async return() {\n if (!closed) {\n closed = true;\n wakeProducer();\n activeDemand?.resolve({ done: true, value: undefined });\n activeDemand = undefined;\n finishPending();\n for (const cleanup of cleanups) await cleanup();\n }\n await task;\n return { done: true, value: undefined };\n },\n };\n}\n","import type {\n StandardJSONSchemaV1,\n StandardSchemaV1,\n} from \"@standard-schema/spec\";\n\nexport type Schema<TInput = unknown, TOutput = TInput> = {\n readonly \"~standard\":\n & StandardSchemaV1.Props<TInput, TOutput>\n & StandardJSONSchemaV1.Props<TInput, TOutput>;\n};\n\nexport type AnySchema = Schema<any, any>;\nexport type AnyObjectSchema = Schema<any, Record<string, unknown>>;\n\nexport type InferSchemaInput<TSchema extends AnySchema> =\n StandardSchemaV1.InferInput<TSchema>;\n\nexport type InferSchemaOutput<TSchema extends AnySchema> =\n StandardSchemaV1.InferOutput<TSchema>;\n\nexport async function parseSchema<TSchema extends AnySchema>(\n schema: TSchema,\n value: unknown,\n): Promise<InferSchemaOutput<TSchema>> {\n const result = await schema[\"~standard\"].validate(value);\n if (result.issues) {\n throw new SchemaValidationError(result.issues);\n }\n return result.value as InferSchemaOutput<TSchema>;\n}\n\nexport function schemaToJsonSchema(\n schema: AnySchema,\n direction: \"input\" | \"output\",\n): Readonly<Record<string, unknown>> {\n const projected = schema[\"~standard\"].jsonSchema[direction]({\n target: \"draft-2020-12\",\n });\n return JSON.parse(JSON.stringify(projected)) as Readonly<\n Record<string, unknown>\n >;\n}\n\nexport class SchemaValidationError extends Error {\n readonly issues: readonly StandardSchemaV1.Issue[];\n\n constructor(issues: readonly StandardSchemaV1.Issue[]) {\n super(\"Schema validation failed\");\n this.name = \"SchemaValidationError\";\n this.issues = issues;\n }\n}\n","import {\n defineErrors,\n errorDefinitions,\n CapableError,\n type AnyDefinedErrors,\n type DefinedErrors,\n type CapabilityErrorContract,\n} from \"./errors.ts\";\nimport {\n parseSchema,\n SchemaValidationError,\n type AnySchema,\n type AnyObjectSchema,\n type InferSchemaInput,\n type InferSchemaOutput,\n} from \"./schema.ts\";\nimport type { MaybePromise } from \"./projection.ts\";\nimport type { PresentationRenderer } from \"./presentation.ts\";\nimport { createDemandIterator } from \"./subscription.ts\";\nimport type { LocatedCapability } from \"./application.ts\";\n\nexport const CAPABILITY_SYMBOL: unique symbol = Symbol.for(\n \"capable.capability\",\n) as never;\n\nexport interface CapabilityMetaRegistry {}\ntype OpenMeta<TRegistry> = Partial<TRegistry> & Readonly<Record<string, unknown>>;\n\nexport type CapabilityEffect = \"read\" | \"write\" | \"destructive\";\n\ntype EmptyInput = Record<never, never>;\ntype DefinedNoErrors = DefinedErrors<{}>;\nconst NO_ERRORS = defineErrors({});\n\ntype ParsedInput<TInput extends AnyObjectSchema | undefined> =\n TInput extends AnySchema ? InferSchemaOutput<TInput> : EmptyInput;\n\ntype HandlerInput<TInput extends AnyObjectSchema | undefined> =\n TInput extends AnySchema ? InferSchemaInput<TInput> : EmptyInput;\n\nexport type CapabilityHandlerArgs<TContext, TInput> = {\n readonly input: TInput;\n readonly context: TContext;\n readonly signal?: AbortSignal;\n};\n\nexport type CapabilitySubscriberArgs<TContext, TInput> = {\n readonly input: TInput;\n readonly context: TContext;\n readonly signal: AbortSignal;\n};\n\nexport type CapabilitySubscriber<TContext, TInput, TOutput> = (\n args: CapabilitySubscriberArgs<TContext, TInput>,\n) => AsyncIterable<TOutput>;\n\nexport type CapabilityMiddlewareArgs<TContext, TInput = unknown> = {\n readonly input: TInput;\n readonly context: TContext;\n readonly signal?: AbortSignal;\n next(): Promise<unknown>;\n};\n\nexport type CapabilityMiddleware<TContext, TInput = unknown> = (\n args: CapabilityMiddlewareArgs<TContext, TInput>,\n) => MaybePromise<unknown>;\n\ntype AnyHandler = (...args: any[]) => any;\n\nexport type CapabilityDefinition<\n TContext = unknown,\n TInput extends AnyObjectSchema | undefined = AnyObjectSchema | undefined,\n TOutput = unknown,\n TErrors extends AnyDefinedErrors = AnyDefinedErrors,\n TMeta extends OpenMeta<CapabilityMetaRegistry> = OpenMeta<CapabilityMetaRegistry>,\n TSubscribable extends boolean = boolean,\n> = {\n readonly [CAPABILITY_SYMBOL]: true;\n readonly id: string;\n readonly title?: string;\n readonly description?: string;\n readonly deprecated: boolean;\n readonly effect?: CapabilityEffect;\n readonly input?: TInput;\n readonly output?: AnySchema;\n readonly errors: TErrors;\n readonly middleware: readonly CapabilityMiddleware<TContext, ParsedInput<TInput>>[];\n readonly meta: TMeta;\n readonly handler: (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => MaybePromise<TOutput>;\n readonly subscribe?: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n any\n >;\n readonly toPresentation?: PresentationRenderer<TOutput, TContext>;\n readonly \"~capable/context\"?: (context: TContext) => TContext;\n readonly \"~capable/input\"?: TInput;\n readonly \"~capable/output\"?: TOutput;\n readonly \"~capable/subscribable\"?: TSubscribable;\n};\n\nexport type AnyCapability = CapabilityDefinition<\n any,\n any,\n any,\n any,\n any,\n any\n>;\n\nexport type CapabilityInput<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<any, infer TInput, any, any, any>\n ? TInput extends AnyObjectSchema\n ? InferSchemaInput<TInput>\n : EmptyInput\n : never;\n\nexport type CapabilityOutput<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<any, any, infer TOutput, any, any>\n ? TOutput\n : never;\n\nexport type CapabilityContext<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<infer TContext, any, any, any, any>\n ? TContext\n : never;\n\nexport type SubscribableCapability = CapabilityDefinition<\n any,\n any,\n any,\n any,\n any,\n true\n>;\n\nexport type ExecuteCapabilityOptions<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<\n infer TContext,\n infer TInput,\n any,\n any,\n any\n >\n ? (TInput extends AnyObjectSchema\n ? { readonly input: InferSchemaInput<TInput> }\n : { readonly input?: EmptyInput }) &\n ([TContext] extends [undefined]\n ? { readonly context?: undefined }\n : { readonly context: TContext }) & {\n readonly signal?: AbortSignal;\n }\n : never;\n\ntype CapabilityBaseConfig<\n TContext,\n TInput extends AnyObjectSchema | undefined,\n TErrors extends AnyDefinedErrors,\n TMeta extends OpenMeta<CapabilityMetaRegistry>,\n> = {\n readonly id: string;\n readonly title?: string;\n readonly description?: string;\n readonly deprecated?: boolean;\n readonly effect?: CapabilityEffect;\n readonly input?: TInput;\n readonly errors?: TErrors;\n readonly middleware?: readonly CapabilityMiddleware<\n TContext,\n ParsedInput<TInput>\n >[];\n readonly meta?: TMeta;\n};\n\ntype ExplicitOutputCapabilityConfig<\n TContext,\n TInput extends AnyObjectSchema | undefined,\n TOutput extends AnySchema,\n TErrors extends AnyDefinedErrors,\n TMeta extends OpenMeta<CapabilityMetaRegistry>,\n> = CapabilityBaseConfig<TContext, TInput, TErrors, TMeta> & {\n readonly output: TOutput;\n readonly handler: (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => MaybePromise<InferSchemaInput<TOutput>>;\n readonly toPresentation?: PresentationRenderer<InferSchemaOutput<TOutput>, TContext>;\n readonly subscribe?: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n InferSchemaInput<TOutput>\n >;\n};\n\ntype InferredOutputCapabilityConfig<\n TContext,\n TInput extends AnyObjectSchema | undefined,\n THandler extends (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown,\n TErrors extends AnyDefinedErrors,\n TMeta extends OpenMeta<CapabilityMetaRegistry>,\n> = CapabilityBaseConfig<TContext, TInput, TErrors, TMeta> & {\n readonly output?: never;\n readonly handler: THandler;\n readonly toPresentation?: PresentationRenderer<Awaited<ReturnType<THandler>>, TContext>;\n readonly subscribe?: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n Awaited<ReturnType<THandler>>\n >;\n};\n\nexport type CapabilityFactory<TContext> = {\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n TOutput extends AnySchema = AnySchema,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: ExplicitOutputCapabilityConfig<\n TContext,\n TInput,\n TOutput,\n TErrors,\n TMeta\n > & {\n readonly subscribe: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n InferSchemaInput<TOutput>\n >;\n },\n ): CapabilityDefinition<\n TContext,\n TInput,\n InferSchemaOutput<TOutput>,\n TErrors,\n TMeta,\n true\n >;\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n TOutput extends AnySchema = AnySchema,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: ExplicitOutputCapabilityConfig<\n TContext,\n TInput,\n TOutput,\n TErrors,\n TMeta\n > & { readonly subscribe?: never },\n ): CapabilityDefinition<\n TContext,\n TInput,\n InferSchemaOutput<TOutput>,\n TErrors,\n TMeta,\n false\n >;\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n const THandler extends (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown = (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: InferredOutputCapabilityConfig<\n TContext,\n TInput,\n THandler,\n TErrors,\n TMeta\n > & {\n readonly subscribe: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n Awaited<ReturnType<THandler>>\n >;\n },\n ): CapabilityDefinition<\n TContext,\n TInput,\n Awaited<ReturnType<THandler>>,\n TErrors,\n TMeta,\n true\n >;\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n const THandler extends (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown = (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: InferredOutputCapabilityConfig<\n TContext,\n TInput,\n THandler,\n TErrors,\n TMeta\n > & { readonly subscribe?: never },\n ): CapabilityDefinition<\n TContext,\n TInput,\n Awaited<ReturnType<THandler>>,\n TErrors,\n TMeta,\n false\n >;\n};\n\ntype CapabilityFunction = CapabilityFactory<undefined> & {\n <TContext>(): CapabilityFactory<TContext>;\n withContext<TContext>(): CapabilityFactory<TContext>;\n};\n\nfunction capabilityWithContext<TContext>(): CapabilityFactory<TContext> {\n return createCapability as CapabilityFactory<TContext>;\n}\n\nexport const capability = Object.assign(\n function capability(\n config?:\n | ExplicitOutputCapabilityConfig<any, any, any, any, any>\n | InferredOutputCapabilityConfig<any, any, AnyHandler, any, any>,\n ): AnyCapability | CapabilityFactory<any> {\n return config === undefined\n ? createCapability as CapabilityFactory<any>\n : createCapability(config);\n },\n { withContext: capabilityWithContext },\n) as CapabilityFunction;\n\nfunction createCapability(\n config:\n | ExplicitOutputCapabilityConfig<any, any, any, any, any>\n | InferredOutputCapabilityConfig<any, any, AnyHandler, any, any>,\n): AnyCapability {\n if (!config.id) throw new Error(\"Capability id must not be empty\");\n if (config.subscribe && config.effect !== \"read\") {\n throw new Error(\n `Capability \"${config.id}\" must declare effect \"read\" to subscribe`,\n );\n }\n if (typeof config.handler !== \"function\") {\n throw new Error(`Capability \"${config.id}\" requires a handler`);\n }\n\n return Object.freeze({\n [CAPABILITY_SYMBOL]: true as const,\n id: config.id,\n ...(config.title ? { title: config.title } : {}),\n ...(config.description ? { description: config.description } : {}),\n deprecated: config.deprecated === true,\n ...(config.effect ? { effect: config.effect } : {}),\n ...(config.input ? { input: config.input } : {}),\n ...(config.output ? { output: config.output } : {}),\n errors: config.errors ?? NO_ERRORS,\n middleware: Object.freeze([...(config.middleware ?? [])]),\n meta: Object.freeze({ ...(config.meta ?? {}) }),\n handler: config.handler,\n ...(config.subscribe ? { subscribe: config.subscribe } : {}),\n ...(config.toPresentation\n ? { toPresentation: config.toPresentation }\n : {}),\n });\n}\n\nexport async function executeCapability<\n const TCapability extends AnyCapability,\n>(\n capability: TCapability,\n options: ExecuteCapabilityOptions<TCapability>,\n): Promise<CapabilityOutput<TCapability>> {\n const located: LocatedCapability = Object.freeze({\n path: Object.freeze([]),\n groups: Object.freeze([]),\n groupPaths: Object.freeze([]),\n capability,\n errors: Object.freeze({ ...errorDefinitions(capability.errors) }),\n middleware: capability.middleware,\n });\n return executeLocatedCapability(\n located,\n options.input ?? {},\n {\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n },\n ) as Promise<CapabilityOutput<TCapability>>;\n}\n\nexport async function executeLocatedCapability(\n located: LocatedCapability,\n input: unknown,\n options: { readonly context: unknown; readonly signal?: AbortSignal },\n): Promise<unknown> {\n const parsedInput = await parseCapabilityInput(located.capability, input);\n let rawOutput: unknown;\n try {\n rawOutput = await runCapabilityMiddleware(\n located.middleware,\n {\n input: parsedInput,\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n },\n () => located.capability.handler({\n input: parsedInput,\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n }),\n );\n } catch (error) {\n throw await normalizeCapabilityError(located, error);\n }\n\n return validateCapabilityOutput(located.capability, rawOutput);\n}\n\nexport type SubscribeCapabilityOptions<\n TCapability extends SubscribableCapability,\n> = ExecuteCapabilityOptions<TCapability>;\n\nexport function subscribeCapability<\n const TCapability extends SubscribableCapability,\n>(\n capability: TCapability,\n options: SubscribeCapabilityOptions<TCapability>,\n): AsyncIterableIterator<CapabilityOutput<TCapability>> {\n const located: LocatedCapability = Object.freeze({\n path: Object.freeze([]),\n groups: Object.freeze([]),\n groupPaths: Object.freeze([]),\n capability,\n errors: Object.freeze({ ...errorDefinitions(capability.errors) }),\n middleware: capability.middleware,\n });\n return subscribeLocatedCapability(\n located,\n options.input ?? {},\n {\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n },\n ) as AsyncIterableIterator<CapabilityOutput<TCapability>>;\n}\n\nexport function subscribeLocatedCapability(\n located: LocatedCapability,\n input: unknown,\n options: { readonly context: unknown; readonly signal?: AbortSignal },\n): AsyncIterableIterator<unknown> {\n const subscriber = located.capability.subscribe;\n if (!subscriber) {\n throw new Error(`Capability \"${located.capability.id}\" is not subscribable`);\n }\n\n return createDemandIterator(async (stream) => {\n let cleanupSource = async (_abort: boolean) => {};\n let parsedInput: Record<string, unknown>;\n try {\n parsedInput = await parseCapabilityInput(located.capability, input);\n } catch (error) {\n stream.fail(error);\n return;\n }\n\n try {\n const controller = new AbortController();\n const signal = options.signal\n ? AbortSignal.any([controller.signal, options.signal])\n : controller.signal;\n let iterator: AsyncIterator<unknown> | undefined;\n let cleaned = false;\n cleanupSource = async (abort: boolean) => {\n if (cleaned) return;\n cleaned = true;\n if (abort) controller.abort();\n await iterator?.return?.();\n };\n stream.onCancel(() => cleanupSource(true));\n\n let emitted = false;\n await runCapabilityMiddleware(\n located.middleware,\n {\n input: parsedInput,\n context: options.context,\n signal,\n },\n async () => {\n const iterable = subscriber({\n input: parsedInput,\n context: options.context,\n signal,\n });\n if (\n !iterable ||\n typeof iterable !== \"object\" ||\n !(Symbol.asyncIterator in iterable)\n ) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Capability \"${located.capability.id}\" subscribe must return an AsyncIterable`,\n });\n }\n const sourceIterator = iterable[Symbol.asyncIterator]();\n iterator = sourceIterator;\n\n while (await stream.waitForDemand()) {\n const result = await sourceIterator.next();\n if (result.done) {\n if (!emitted) throw emptySubscriptionError(located.capability);\n return;\n }\n emitted = true;\n stream.emit(\n await validateCapabilityOutput(\n located.capability,\n result.value,\n ),\n );\n }\n },\n );\n if (!emitted) throw emptySubscriptionError(located.capability);\n await cleanupSource(false);\n stream.complete();\n } catch (error) {\n await cleanupSource(false);\n stream.fail(await normalizeCapabilityError(located, error));\n }\n });\n}\n\nfunction emptySubscriptionError(capability: AnyCapability): CapableError {\n return new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Capability \"${capability.id}\" subscription completed before yielding a value`,\n });\n}\n\nasync function validateCapabilityOutput(\n capability: AnyCapability,\n rawOutput: unknown,\n): Promise<unknown> {\n if (!capability.output) return rawOutput;\n try {\n return await parseSchema(capability.output, rawOutput);\n } catch (error) {\n if (!(error instanceof SchemaValidationError)) throw error;\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Capability \"${capability.id}\" output validation failed`,\n data: { issues: error.issues },\n cause: error,\n });\n }\n}\n\nasync function parseCapabilityInput(\n capability: AnyCapability,\n input: unknown,\n): Promise<Record<string, unknown>> {\n if (!capability.input) {\n if (input === undefined) return {};\n if (isRecord(input) && Object.keys(input).length === 0) return {};\n throw new CapableError(\"BAD_REQUEST\", {\n status: 400,\n message: `Capability \"${capability.id}\" does not accept input`,\n });\n }\n try {\n const parsed = await parseSchema(capability.input, input);\n if (!isRecord(parsed)) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Capability \"${capability.id}\" input schema must produce an object`,\n });\n }\n return parsed;\n } catch (error) {\n if (error instanceof CapableError) throw error;\n if (!(error instanceof SchemaValidationError)) throw error;\n throw new CapableError(\"BAD_REQUEST\", {\n status: 400,\n message: `Invalid input for Capability \"${capability.id}\"`,\n data: { issues: error.issues },\n cause: error,\n });\n }\n}\n\nasync function runCapabilityMiddleware(\n middleware: readonly CapabilityMiddleware<any>[],\n args: {\n readonly input: unknown;\n readonly context: unknown;\n readonly signal?: AbortSignal;\n },\n handler: () => MaybePromise<unknown>,\n): Promise<unknown> {\n async function dispatch(index: number): Promise<unknown> {\n const current = middleware[index];\n if (!current) return handler();\n let called = false;\n return current({\n ...args,\n next: async () => {\n if (called) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Capability middleware called next() more than once\",\n });\n }\n called = true;\n return dispatch(index + 1);\n },\n });\n }\n return dispatch(0);\n}\n\nasync function normalizeCapabilityError(\n located: LocatedCapability,\n error: unknown,\n): Promise<unknown> {\n if (!(error instanceof CapableError)) {\n return new CapableError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n }\n const contract = located.errors[error.code];\n if (!contract) {\n return new CapableError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n }\n\n let data = error.data;\n if (contract.data) {\n try {\n data = await parseSchema(contract.data, error.data);\n } catch (cause) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Invalid error data for ${error.code}`,\n cause,\n });\n }\n }\n return new CapableError(error.code, {\n ...(typeof contract.status === \"number\" ? { status: contract.status } : {}),\n message: contract.message ?? error.code,\n data,\n cause: error,\n });\n}\n\nexport function isCapability(value: unknown): value is AnyCapability {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n (value as Partial<AnyCapability>)[CAPABILITY_SYMBOL] === true,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n","import {\n defineErrors,\n errorDefinitions,\n type AnyDefinedErrors,\n type DefinedErrors,\n type CapabilityErrorContract,\n} from \"./errors.ts\";\nimport {\n isCapability,\n type AnyCapability,\n type CapabilityDefinition,\n type CapabilityMiddleware,\n} from \"./capability.ts\";\n\nexport const CAPABILITY_GROUP_SYMBOL: unique symbol = Symbol.for(\n \"capable.capability-group\",\n) as never;\nexport const APPLICATION_SYMBOL: unique symbol = Symbol.for(\n \"capable.application\",\n) as never;\n\nexport interface GroupMetaRegistry {}\ntype OpenMeta<TRegistry> = Partial<TRegistry> & Readonly<Record<string, unknown>>;\ntype DefinedNoErrors = DefinedErrors<{}>;\nconst NO_ERRORS = defineErrors({});\n\nexport interface CapabilityTree {\n readonly [key: string]:\n | AnyCapability\n | CapabilityTree\n | AnyCapabilityGroup;\n}\n\nexport type CapabilityGroupDefinition<\n TCapabilities extends CapabilityTree = CapabilityTree,\n TErrors extends AnyDefinedErrors = AnyDefinedErrors,\n TMeta extends OpenMeta<GroupMetaRegistry> = OpenMeta<GroupMetaRegistry>,\n> = {\n readonly [CAPABILITY_GROUP_SYMBOL]: true;\n readonly title?: string;\n readonly description?: string;\n readonly errors: TErrors;\n readonly middleware: readonly CapabilityMiddleware<any>[];\n readonly meta: TMeta;\n readonly capabilities: TCapabilities;\n};\n\nexport type AnyCapabilityGroup = {\n readonly [CAPABILITY_GROUP_SYMBOL]: true;\n readonly title?: string;\n readonly description?: string;\n readonly errors: AnyDefinedErrors;\n readonly middleware: readonly CapabilityMiddleware<any>[];\n readonly meta: OpenMeta<GroupMetaRegistry>;\n readonly capabilities: CapabilityTree;\n};\n\nexport function group<\n const TCapabilities extends CapabilityTree,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<GroupMetaRegistry> = {},\n>(config: {\n readonly title?: string;\n readonly description?: string;\n readonly errors?: TErrors;\n readonly middleware?: readonly CapabilityMiddleware<\n CapabilityTreeContext<TCapabilities>\n >[];\n readonly meta?: TMeta;\n readonly capabilities: TCapabilities;\n}): CapabilityGroupDefinition<TCapabilities, TErrors, TMeta> {\n assertCapabilityTree(config.capabilities, \"group.capabilities\");\n return Object.freeze({\n [CAPABILITY_GROUP_SYMBOL]: true as const,\n ...(config.title ? { title: config.title } : {}),\n ...(config.description ? { description: config.description } : {}),\n errors: (config.errors ?? NO_ERRORS) as TErrors,\n middleware: Object.freeze([...(config.middleware ?? [])]),\n meta: Object.freeze({ ...(config.meta ?? {}) }) as TMeta,\n capabilities: config.capabilities,\n });\n}\n\nexport type LocatedCapability = {\n readonly path: readonly string[];\n readonly groups: readonly AnyCapabilityGroup[];\n readonly groupPaths: readonly (readonly string[])[];\n readonly capability: AnyCapability;\n readonly errors: CapabilityErrorContract;\n readonly middleware: readonly CapabilityMiddleware<any>[];\n};\n\nexport type AppDefinition<\n TCapabilities extends CapabilityTree = CapabilityTree,\n TContext = unknown,\n> = {\n readonly [APPLICATION_SYMBOL]: true;\n readonly name: string;\n readonly version: string;\n readonly description?: string;\n readonly capabilities: TCapabilities;\n readonly locatedCapabilities: readonly LocatedCapability[];\n readonly \"~capable/context\"?: TContext;\n};\n\ntype CapabilityTreeContext<TTree> =\n TTree extends CapabilityDefinition<infer TContext, any, any, any, any>\n ? TContext\n : TTree extends CapabilityGroupDefinition<infer TCapabilities, any, any>\n ? CapabilityTreeContext<TCapabilities>\n : TTree extends Readonly<Record<string, unknown>>\n ? CapabilityTreeContext<TTree[keyof TTree]>\n : never;\n\ntype UnionToIntersection<TValue> =\n (TValue extends unknown ? (value: TValue) => void : never) extends\n (value: infer TIntersection) => void ? TIntersection : never;\n\nexport type AppContext<\n TDefinition extends AppDefinition<any, any>,\n> = TDefinition extends AppDefinition<any, infer TContext>\n ? TContext\n : never;\n\nexport function defineApp<\n const TCapabilities extends CapabilityTree,\n>(config: {\n readonly name?: string;\n readonly version?: string;\n readonly description?: string;\n readonly capabilities: TCapabilities;\n}): AppDefinition<\n TCapabilities,\n UnionToIntersection<CapabilityTreeContext<TCapabilities>>\n> {\n assertCapabilityTree(config.capabilities, \"application.capabilities\");\n const located = locateCapabilities(config.capabilities);\n assertUniqueCapabilities(located);\n\n return Object.freeze({\n [APPLICATION_SYMBOL]: true as const,\n name: config.name ?? \"Capable application\",\n version: config.version ?? \"0.0.0\",\n ...(config.description ? { description: config.description } : {}),\n capabilities: config.capabilities,\n locatedCapabilities: Object.freeze(located),\n });\n}\n\nfunction locateCapabilities(\n tree: CapabilityTree,\n path: readonly string[] = [],\n groups: readonly AnyCapabilityGroup[] = [],\n groupPaths: readonly (readonly string[])[] = [],\n inheritedErrors: CapabilityErrorContract = {},\n inheritedMiddleware: readonly CapabilityMiddleware<any>[] = [],\n): LocatedCapability[] {\n const located: LocatedCapability[] = [];\n for (const [key, value] of Object.entries(tree)) {\n const nextPath = [...path, key];\n if (isCapability(value)) {\n const capabilityErrors = errorDefinitions(value.errors);\n assertAdditionalErrors(\n inheritedErrors,\n capabilityErrors,\n `Capability \"${value.id}\"`,\n );\n located.push(Object.freeze({\n path: Object.freeze(nextPath),\n groups: Object.freeze([...groups]),\n groupPaths: Object.freeze([...groupPaths]),\n capability: value,\n errors: Object.freeze({ ...inheritedErrors, ...capabilityErrors }),\n middleware: Object.freeze([\n ...inheritedMiddleware,\n ...value.middleware,\n ]),\n }));\n continue;\n }\n if (isCapabilityGroup(value)) {\n const groupErrors = errorDefinitions(value.errors);\n assertAdditionalErrors(\n inheritedErrors,\n groupErrors,\n `Group at \"${nextPath.join(\".\")}\"`,\n );\n located.push(...locateCapabilities(\n value.capabilities,\n nextPath,\n [...groups, value],\n [...groupPaths, nextPath],\n { ...inheritedErrors, ...groupErrors },\n [\n ...inheritedMiddleware,\n ...(value.middleware as readonly CapabilityMiddleware<any>[]),\n ],\n ));\n continue;\n }\n located.push(...locateCapabilities(\n value,\n nextPath,\n groups,\n groupPaths,\n inheritedErrors,\n inheritedMiddleware,\n ));\n }\n return located;\n}\n\nfunction assertCapabilityTree(\n value: unknown,\n label: string,\n): asserts value is CapabilityTree {\n if (!isRecord(value)) {\n throw new Error(\n `${label} must be a named object tree; arrays are not supported`,\n );\n }\n for (const [key, child] of Object.entries(value)) {\n if (!key) throw new Error(`${label} has an empty key`);\n if (key === \"then\") {\n throw new Error(`${label} uses reserved key \"then\"`);\n }\n if (isCapability(child)) continue;\n if (isCapabilityGroup(child)) {\n assertCapabilityTree(child.capabilities, `${label}.${key}.capabilities`);\n continue;\n }\n assertCapabilityTree(child, `${label}.${key}`);\n }\n}\n\nfunction assertUniqueCapabilities(\n located: readonly LocatedCapability[],\n): void {\n const ids = new Map<string, string>();\n const objects = new Map<AnyCapability, string>();\n for (const entry of located) {\n const path = entry.path.join(\".\");\n const previousIdPath = ids.get(entry.capability.id);\n if (previousIdPath) {\n throw new Error(\n `Duplicate Capability id \"${entry.capability.id}\" at \"${previousIdPath}\" and \"${path}\"`,\n );\n }\n const previousObjectPath = objects.get(entry.capability);\n if (previousObjectPath) {\n throw new Error(\n `Capability \"${entry.capability.id}\" is included at both \"${previousObjectPath}\" and \"${path}\"`,\n );\n }\n ids.set(entry.capability.id, path);\n objects.set(entry.capability, path);\n }\n}\n\nfunction assertAdditionalErrors(\n inherited: CapabilityErrorContract,\n additional: CapabilityErrorContract,\n label: string,\n): void {\n const duplicate = Object.keys(additional).find((code) => code in inherited);\n if (duplicate) {\n throw new Error(`${label} redeclares inherited error ${duplicate}`);\n }\n}\n\nexport function isCapabilityGroup(\n value: unknown,\n): value is AnyCapabilityGroup {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n (value as Partial<AnyCapabilityGroup>)[CAPABILITY_GROUP_SYMBOL] === true,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n"],"mappings":";AAMA,MAAa,2BAA0C,OAAO,IAC5D,2BACF;AACA,MAAa,sCAAqD,OAAO,IACvE,sCACF;AAsBA,IAAa,eAAb,cAGU,MAAM;CACd;CACA;CACA;CAEA,YACE,MACA,UAKI,CAAC,GACL;EACA,MAAM,QAAQ,WAAW,MAAM,EAAE,OAAO,QAAQ,MAAM,CAAC;EACvD,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS,QAAQ;EACtB,KAAK,OAAO,QAAQ;CACtB;AACF;AA0DA,SAAgB,aAEd,aAAwD;CACxD,MAAM,oBAAoB,OAAO,OAAO,EAAE,GAAG,YA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AAI,WACF,MAAM,IAAI,MAAM,GAAG,MAAM,8BAA8B,WAAW;AAEtE;AAEA,SAAgB,kBACd,OAC6B;CAC7B,OAAO,QACL,SACE,OAAO,UAAU,YAChB,MAAsC,6BAA6B,IACxE;AACF;AAEA,SAAS,SAAS,OAA8C;CAC9D,OAAO,QAAQ,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,CAAC;AAC5E"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { q as MaybePromise } from "./index-Be8-UVBC.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-Bq792Ad2.d.mts.map
|
package/docs/CONTEXT.md
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# Capable domain language
|
|
2
|
+
|
|
3
|
+
**Capability**: one typed capability with a canonical string ID, optional
|
|
4
|
+
object-shaped input, optional output schema, declared errors, middleware,
|
|
5
|
+
optional effect, unary handler, optional replacement subscriber, open surface
|
|
6
|
+
metadata, and optional `toPresentation`.
|
|
7
|
+
It has no canonical HTTP method or path.
|
|
8
|
+
|
|
9
|
+
**App Definition**: immutable named object nesting created by `defineApp()`
|
|
10
|
+
whose leaves are Capabilities. It carries no context provider or execution
|
|
11
|
+
placement. Its paths drive navigational interfaces and surface defaults.
|
|
12
|
+
|
|
13
|
+
**Group**: an anonymous decorated subtree created with `group()`. It has no ID.
|
|
14
|
+
It contributes semantic middleware and errors and exposes its metadata ancestry
|
|
15
|
+
to surface compilers.
|
|
16
|
+
|
|
17
|
+
**Capability ID**: canonical execution and transport identity. IDs are unique
|
|
18
|
+
within an Application.
|
|
19
|
+
|
|
20
|
+
**Application path**: the unique object path to a Capability, such as
|
|
21
|
+
`admin.users.create`. It drives direct App calls, CLI, and MCP navigation but
|
|
22
|
+
is not the Capability's identity.
|
|
23
|
+
|
|
24
|
+
**Effect**: optional `read`, `write`, or `destructive` intent. HTTP may derive
|
|
25
|
+
GET only from `read`; MCP may derive safety hints. Absence means unknown.
|
|
26
|
+
|
|
27
|
+
**Error set**: a branded contract created by `defineErrors()`. Its named,
|
|
28
|
+
callable members construct type-safe declared errors and narrow those errors
|
|
29
|
+
after local or remote execution. Groups may contribute inherited Error sets.
|
|
30
|
+
Any handler or middleware failure outside the located Capability's declared
|
|
31
|
+
sets becomes `INTERNAL_SERVER_ERROR`.
|
|
32
|
+
|
|
33
|
+
**Context declaration**: the `capabilities<TContext>()` factory used to bind
|
|
34
|
+
Capabilities to a context type without constructing that context.
|
|
35
|
+
|
|
36
|
+
**Context provider**: opt-in, boundary-owned context construction. A
|
|
37
|
+
context-free definition uses `createApp(definition)` with no options. When a
|
|
38
|
+
Capability declares context, local consumers must provide it through
|
|
39
|
+
`createApp()` and Fetch servers derive it from the incoming Request. An App
|
|
40
|
+
Definition derives any required context type from its Capability tree but
|
|
41
|
+
stores no provider.
|
|
42
|
+
|
|
43
|
+
**App**: a context-erased typed callable object tree. `createApp()` closes over
|
|
44
|
+
direct execution and its provider; `createRemoteApp()` wraps a transport
|
|
45
|
+
without performing I/O. Remote manifest discovery is lazy, validated, and
|
|
46
|
+
cached. `mergeApps()` returns the same shape. A low-level
|
|
47
|
+
`manifest() + call() + subscribe()` runtime lives behind internal symbols for
|
|
48
|
+
surfaces and composition.
|
|
49
|
+
|
|
50
|
+
**Application merge**: strict root-tree combination through `mergeApps()`.
|
|
51
|
+
Calls dispatch by immutable Capability ID. All path, ID, double-mount, and
|
|
52
|
+
leaf/subtree conflicts fail when the merged manifest first resolves.
|
|
53
|
+
|
|
54
|
+
**Capable transport**: an asynchronous boundary exposing `manifest()`,
|
|
55
|
+
`call()`, and `subscribe()`. `createRemoteApp()` wraps and caches it without
|
|
56
|
+
turning module evaluation into a network boundary. Its HTTP client/server
|
|
57
|
+
encoding lives in `@capable/fetch` as server plumbing, separate from authored
|
|
58
|
+
HTTP APIs and from transport-neutral App semantics.
|
|
59
|
+
|
|
60
|
+
**HTTP projection**: a server mount that derives routes from the Application
|
|
61
|
+
tree and `effect`, then applies optional `meta.http` overrides. It also owns
|
|
62
|
+
OpenAPI.
|
|
63
|
+
|
|
64
|
+
**AI SDK projection**: an asynchronous projection that resolves an executable
|
|
65
|
+
App manifest into typed AI SDK tools. It derives portable names and JSON
|
|
66
|
+
Schemas, then dispatches execution and cancellation through the App runtime.
|
|
67
|
+
|
|
68
|
+
**Surface metadata**: open Capability or Group metadata interpreted only by its
|
|
69
|
+
surface package. Core preserves ancestry and never performs generic merging.
|
|
70
|
+
|
|
71
|
+
**Selection**: tree-shaped `include` and `exclude` policy owned by an exposure
|
|
72
|
+
boundary. Omitted include means all; exclude wins.
|
|
73
|
+
`selectApp()` applies that policy before passing an App to a
|
|
74
|
+
surface.
|
|
75
|
+
|
|
76
|
+
**Canonical output**: handler output after optional output validation. It is the
|
|
77
|
+
only semantic result.
|
|
78
|
+
|
|
79
|
+
**Presentation**: an optional, ordered, JSON-serializable sequence of Markdown,
|
|
80
|
+
table, image, and file parts derived from Canonical Output by `toPresentation`.
|
|
81
|
+
Surfaces explicitly opt in to materializing it and decide how to lower parts
|
|
82
|
+
they support. An empty sequence is treated as no Presentation.
|
|
83
|
+
|
|
84
|
+
**Replacement subscription**: an optional pull-based execution mode on a
|
|
85
|
+
`read` Capability. It shares that Capability's ID, input, Canonical Output,
|
|
86
|
+
declared errors, middleware, placement, and representations. Every emitted
|
|
87
|
+
item is a complete replacement Canonical Output. `subscribe(appCall, input)`
|
|
88
|
+
keeps App navigation collision-free.
|
|
89
|
+
|
|
90
|
+
## Invariants
|
|
91
|
+
|
|
92
|
+
- `@capable/core` depends on no transport, host, CLI, MCP, or HTTP package.
|
|
93
|
+
- Application and Group capability collections are named object trees, never
|
|
94
|
+
arrays.
|
|
95
|
+
- `then` is reserved at every App path so callable proxies cannot become
|
|
96
|
+
promise-like values.
|
|
97
|
+
- App Definitions never carry context providers.
|
|
98
|
+
- A context-free `createApp()` needs no provider; a contextual one satisfies
|
|
99
|
+
and erases only its own context before merging.
|
|
100
|
+
- A Capability object and ID may each occur only once in an Application.
|
|
101
|
+
- Handlers receive only `{ input, context, signal }`.
|
|
102
|
+
- Semantic middleware and declared errors execute identically for every
|
|
103
|
+
surface.
|
|
104
|
+
- Subscription input is parsed once, every replacement is output-validated,
|
|
105
|
+
middleware encloses the complete iterator lifetime, and cancellation aborts
|
|
106
|
+
before iterator cleanup.
|
|
107
|
+
- Platform adapters only translate their host to Fetch Request/Response.
|
|
108
|
+
- HTTP is a projection and deployment concern, not Capability identity.
|
|
109
|
+
- Generic event streams, patches, buffering, replay, resumption, delivery
|
|
110
|
+
guarantees, and reconnection policy are not replacement subscription
|
|
111
|
+
semantics.
|
|
112
|
+
- Idempotence, approvals, and durable tasks remain deferred until a concrete
|
|
113
|
+
consumer proves their contract.
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Capable documentation
|
|
2
|
+
|
|
3
|
+
This directory is assembled from Capable's canonical documentation sources when
|
|
4
|
+
the npm package is packed. It matches the installed package version.
|
|
5
|
+
|
|
6
|
+
## For coding agents
|
|
7
|
+
|
|
8
|
+
Do not rely on remembered Capable APIs. Read the relevant bundled guide and
|
|
9
|
+
inspect `../src/` when you need a detail the guides do not cover.
|
|
10
|
+
|
|
11
|
+
Start here:
|
|
12
|
+
|
|
13
|
+
1. [Introduction](./site/introduction.mdx)
|
|
14
|
+
2. [Quickstart](./site/quickstart.mdx)
|
|
15
|
+
3. [Capabilities](./site/concepts/capabilities.mdx)
|
|
16
|
+
4. [Apps](./site/concepts/apps.mdx)
|
|
17
|
+
5. [Surfaces](./site/surfaces.mdx)
|
|
18
|
+
6. [Packages and entry points](./site/reference/packages-and-entry-points.mdx)
|
|
19
|
+
|
|
20
|
+
Public guides are grouped by section and named from their frontmatter titles.
|
|
21
|
+
To find a topic, search the files under `site/` or list its `.mdx` files.
|
|
22
|
+
|
|
23
|
+
- `site/` contains the canonical, human- and agent-readable MDX guides.
|
|
24
|
+
- `internal/` contains design notes for contributors.
|
|
25
|
+
- `CONTEXT.md` defines the framework's domain language and invariants.
|
|
26
|
+
|
|
27
|
+
The canonical sources live in `website/`, `docs/`, and `CONTEXT.md` in the
|
|
28
|
+
Capable repository. Edit those sources rather than the generated package copy.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Internal docs
|
|
2
|
+
|
|
3
|
+
User-facing documentation lives in the site under `website/` (`bun run
|
|
4
|
+
docs:dev`). This directory is for people working *on* Capable.
|
|
5
|
+
|
|
6
|
+
| Document | Contains |
|
|
7
|
+
| -------------------------------------------------------------- | --------------------------------------------------------------------- |
|
|
8
|
+
| [../CONTEXT.md](../CONTEXT.md) | The domain language and the invariants every change must preserve |
|
|
9
|
+
| [capability-first-model.md](./capability-first-model.md) | Normative rules of the model: identity, placement, errors, subscriptions |
|
|
10
|
+
| [architecture.md](./architecture.md) | How the packages are layered and why |
|
|
11
|
+
| [adr/](./adr) | Accepted decisions |
|
|
12
|
+
| [implementation-friction.md](./implementation-friction.md) | Live log of awkward or leaky implementation work |
|
|
13
|
+
| [why-capable.md](./why-capable.md) | The original internal argument for the project |
|
|
14
|
+
|
|
15
|
+
If a change contradicts CONTEXT.md, change CONTEXT.md in the same commit or do
|
|
16
|
+
not make the change.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
---
|
|
2
|
+
status: accepted
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
# Keep Capability as the application-semantic boundary
|
|
6
|
+
|
|
7
|
+
Capable defines protocol-neutral Capabilities and composes them into an Application
|
|
8
|
+
object tree. HTTP endpoints, CLI commands, MCP tools, clients, jobs, and future
|
|
9
|
+
workflows invoke the same Capability executor rather than introducing competing
|
|
10
|
+
business runtimes.
|
|
11
|
+
|
|
12
|
+
A Capability ID is canonical execution identity. The Application path is
|
|
13
|
+
navigational. HTTP method/path and other surface identities are projections.
|
|
14
|
+
|
|
15
|
+
Future approval or durable-task coordination wraps invocation before semantic
|
|
16
|
+
middleware and the handler. It may suspend and resume execution, but it does
|
|
17
|
+
not enter the handler contract or canonical output.
|
|
18
|
+
|
|
19
|
+
App Definitions do not own context provision. `createApp()` satisfies one
|
|
20
|
+
definition's context and erases it into a directly callable App;
|
|
21
|
+
`createRemoteApp()` returns the same callable shape while lazily discovering
|
|
22
|
+
and validating transport execution. `mergeApps()` combines these
|
|
23
|
+
context-erased Apps, so unrelated local contexts never become one giant merged
|
|
24
|
+
context.
|