capable-kit 0.1.0-alpha.10 → 0.1.0-alpha.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +0 -106
- package/dist/ai-sdk.d.mts +3 -3
- package/dist/ai-sdk.mjs +7 -9
- package/dist/ai-sdk.mjs.map +1 -1
- package/dist/app.d.mts +2 -2
- package/dist/app.mjs +2 -2
- package/dist/bin.mjs +4 -4
- package/dist/cli.d.mts +1 -6
- package/dist/cli.mjs +1 -1
- package/dist/core.d.mts +3 -3
- package/dist/core.mjs +1 -1
- package/dist/eve.d.mts +3 -3
- package/dist/eve.mjs +7 -9
- package/dist/eve.mjs.map +1 -1
- package/dist/http.d.mts +1 -1
- package/dist/http.mjs +1 -1
- package/dist/{index-1A44jLuE.d.mts → index-D63DSGZG.d.mts} +17 -50
- package/dist/{index-CHuCLJIs.d.mts → index-D8DWjQ9f.d.mts} +3 -3
- package/dist/{index-D-NV4PiU.d.mts → index-DgxvtAmv.d.mts} +4 -4
- package/dist/{index-WiBWfyTn.d.mts → index-ftQx6OMr.d.mts} +16 -43
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +3 -3
- package/dist/mcp.d.mts +2 -7
- package/dist/mcp.mjs +1 -1
- package/dist/{mount-BmLHp349.mjs → mount-B9TrHWHh.mjs} +8 -16
- package/dist/mount-B9TrHWHh.mjs.map +1 -0
- package/dist/react-query.d.mts +2 -2
- package/dist/react-query.mjs +1 -1
- package/dist/react-query.mjs.map +1 -1
- package/dist/runtime-support.d.mts +1 -1
- package/dist/runtime-support.mjs +3 -3
- package/dist/server.d.mts +1 -1
- package/dist/server.mjs +1 -1
- package/dist/{src-DePlcG_t.mjs → src-B592M-6b.mjs} +105 -312
- package/dist/src-B592M-6b.mjs.map +1 -0
- package/dist/{src-B2WeUwUT.mjs → src-Bd1Vnze8.mjs} +31 -49
- package/dist/src-Bd1Vnze8.mjs.map +1 -0
- package/dist/{src-C5jGDnuu.mjs → src-CKC1BdXO.mjs} +3 -3
- package/dist/{src-C5jGDnuu.mjs.map → src-CKC1BdXO.mjs.map} +1 -1
- package/dist/{src-3LE9S4QE.mjs → src-CL9eA6_p.mjs} +17 -29
- package/dist/src-CL9eA6_p.mjs.map +1 -0
- package/dist/{src-_6OmFRYa.mjs → src-Hw9WBgEW.mjs} +10 -28
- package/dist/src-Hw9WBgEW.mjs.map +1 -0
- package/dist/{subscription-DPdwovhw.d.mts → subscription-DbnHcm7C.d.mts} +2 -2
- package/dist/swr.d.mts +2 -2
- package/dist/swr.mjs +1 -1
- package/dist/swr.mjs.map +1 -1
- package/docs/CONTEXT.md +11 -23
- package/docs/internal/architecture.md +14 -27
- package/docs/internal/capability-first-model.md +13 -99
- package/docs/internal/implementation-friction.md +0 -85
- package/docs/site/concepts/apps.mdx +1 -1
- package/docs/site/concepts/architecture.mdx +0 -8
- package/docs/site/concepts/capabilities.mdx +2 -2
- package/docs/site/concepts/presentations.mdx +0 -4
- package/docs/site/patterns/composition.mdx +5 -107
- package/docs/site/patterns/remote-apps.mdx +1 -5
- package/docs/site/patterns/subscriptions.mdx +32 -79
- package/docs/site/reference/packages-and-entry-points.mdx +2 -41
- package/docs/site/surfaces/cli.mdx +0 -11
- package/docs/site/surfaces/typescript.mdx +2 -2
- package/package.json +1 -1
- package/src/index.test.ts +0 -1
- package/src/index.ts +0 -5
- package/src/package.test.ts +0 -9
- package/dist/mount-BmLHp349.mjs.map +0 -1
- package/dist/src-3LE9S4QE.mjs.map +0 -1
- package/dist/src-B2WeUwUT.mjs.map +0 -1
- package/dist/src-DePlcG_t.mjs.map +0 -1
- package/dist/src-_6OmFRYa.mjs.map +0 -1
- package/docs/internal/adr/0003-capability-reference-customization.md +0 -68
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-B592M-6b.mjs","names":["samePath"],"sources":["../../app/src/manifest.ts","../../app/src/runtime.ts","../../app/src/composition.ts"],"sourcesContent":["import {\n isCapability,\n isCapabilityGroup,\n schemaToJsonSchema,\n type AnySchema,\n type AppDefinition,\n type LocatedCapability,\n} from \"@capable/core\";\n\nexport type JsonSchema = Readonly<Record<string, unknown>>;\n\nexport type ManifestError = {\n readonly message?: string;\n readonly data?: JsonSchema;\n readonly status?: number;\n readonly meta?: Readonly<Record<string, unknown>>;\n};\n\nexport type ManifestCapability = {\n readonly type: \"capability\";\n readonly id: string;\n readonly path: readonly string[];\n readonly title?: string;\n readonly description?: string;\n readonly deprecated: boolean;\n readonly effect?: \"read\" | \"write\" | \"destructive\";\n readonly subscription?: { readonly mode: \"replace\" };\n readonly input?: JsonSchema;\n readonly output?: JsonSchema;\n readonly errors: Readonly<Record<string, ManifestError>>;\n readonly meta: Readonly<Record<string, unknown>>;\n};\n\nexport type ManifestGroup = {\n readonly type: \"group\";\n readonly key: string;\n readonly title?: string;\n readonly description?: string;\n readonly meta: Readonly<Record<string, unknown>>;\n readonly children: readonly ManifestNode[];\n};\n\nexport type ManifestNode = ManifestGroup | ManifestCapability;\n\nexport type ApplicationManifest = {\n readonly protocol: \"capable.capabilities.v3\";\n readonly name: string;\n readonly version: string;\n readonly description?: string;\n readonly capabilities: readonly ManifestNode[];\n};\n\nexport function createAppManifest(\n definition: AppDefinition<any>,\n): ApplicationManifest {\n const byCapability = new Map(\n definition.locatedCapabilities.map((entry) => [entry.capability, entry]),\n );\n return Object.freeze({\n protocol: \"capable.capabilities.v3\",\n name: definition.name,\n version: definition.version,\n ...(definition.description ? { description: definition.description } : {}),\n capabilities: manifestNodes(definition.capabilities, byCapability),\n });\n}\n\nexport function validateManifest(\n manifest: ApplicationManifest,\n label: string,\n): void {\n if (manifest.protocol !== \"capable.capabilities.v3\") {\n throw new Error(`${label} uses unsupported protocol \"${manifest.protocol}\"`);\n }\n const capabilities = flattenManifestCapabilities(manifest.capabilities);\n const ids = new Map<string, ManifestCapability>();\n const paths = new Set<string>();\n for (const capability of capabilities) {\n const path = capability.path.join(\".\");\n const previous = ids.get(capability.id);\n if (previous && !sameCapabilityContract(previous, capability)) {\n throw new Error(\n `${label} contains conflicting definitions for Capability id \"${capability.id}\"`,\n );\n }\n if (paths.has(path)) {\n throw new Error(`${label} contains duplicate Capability path \"${path}\"`);\n }\n ids.set(capability.id, capability);\n paths.add(path);\n }\n validateManifestPaths(manifest.capabilities, [], label);\n}\n\nexport type ApplicationManifestSource = {\n readonly manifest: ApplicationManifest;\n readonly owner: object;\n};\n\nexport function composeApplicationManifests(\n sources: readonly ApplicationManifestSource[],\n): ApplicationManifest {\n const conflicts = collectManifestConflicts(sources);\n if (conflicts.length) {\n throw new Error(\n `Cannot compose Apps:\\n${conflicts.map((item) => `- ${item}`).join(\"\\n\")}`,\n );\n }\n const manifests = sources.map(({ manifest }) => manifest);\n const applications = sources.filter((source, index) =>\n sources.findIndex(({ owner }) => owner === source.owner) === index\n ).map(({ manifest }) => manifest);\n return Object.freeze({\n protocol: \"capable.capabilities.v3\",\n name: applications.map(({ name }) => name).join(\" + \"),\n version: applications.map(({ version }) => version).join(\" + \"),\n capabilities: mergeManifestNodes(\n manifests.flatMap(({ capabilities }) => capabilities),\n ),\n });\n}\n\nexport function selectManifest(\n source: ApplicationManifest,\n selection: {\n readonly include?: unknown;\n readonly exclude?: unknown;\n },\n): ApplicationManifest {\n validateSelectionTree(selection.include, source.capabilities, \"include\", []);\n validateSelectionTree(selection.exclude, source.capabilities, \"exclude\", []);\n return Object.freeze({\n ...source,\n capabilities: filterManifestNodes(source.capabilities, selection),\n });\n}\n\nfunction validateSelectionTree(\n tree: unknown,\n nodes: readonly ManifestNode[],\n label: \"include\" | \"exclude\",\n parent: readonly string[],\n): void {\n if (tree === undefined || tree === true) return;\n if (!tree || typeof tree !== \"object\" || Array.isArray(tree)) {\n throw new Error(\n `Application selection ${label} at \"${parent.join(\".\") || \"<root>\"}\" must be an object or true`,\n );\n }\n for (const [key, child] of Object.entries(tree)) {\n const path = [...parent, key];\n const node = nodes.find((candidate) =>\n candidate.type === \"group\"\n ? candidate.key === key\n : candidate.path.at(-1) === key\n );\n if (!node) {\n throw new Error(\n `Application selection ${label} references unknown path \"${path.join(\".\")}\"`,\n );\n }\n if (child === true) continue;\n if (node.type === \"capability\") {\n throw new Error(\n `Application selection ${label} at \"${path.join(\".\")}\" must be true`,\n );\n }\n validateSelectionTree(child, node.children, label, path);\n }\n}\n\nexport function flattenManifestCapabilities(\n nodes: readonly ManifestNode[],\n): readonly ManifestCapability[] {\n return nodes.flatMap((node) =>\n node.type === \"capability\"\n ? [node]\n : flattenManifestCapabilities(node.children)\n );\n}\n\nexport function findManifestCapability(\n nodes: readonly ManifestNode[],\n path: readonly string[],\n): ManifestCapability | undefined {\n let current = nodes;\n for (let index = 0; index < path.length; index++) {\n const key = path[index]!;\n const node = current.find((candidate) =>\n candidate.type === \"group\"\n ? candidate.key === key\n : candidate.path.at(-1) === key\n );\n if (!node) return undefined;\n if (node.type === \"capability\") {\n return index === path.length - 1 ? node : undefined;\n }\n current = node.children;\n }\n return undefined;\n}\n\nfunction manifestNodes(\n tree: Readonly<Record<string, unknown>>,\n located: ReadonlyMap<unknown, LocatedCapability>,\n): readonly ManifestNode[] {\n const nodes: ManifestNode[] = [];\n for (const [key, value] of Object.entries(tree)) {\n if (isCapability(value)) {\n const entry = located.get(value);\n if (entry) nodes.push(manifestCapability(entry));\n continue;\n }\n const decorated = isCapabilityGroup(value);\n const childTree = decorated\n ? value.capabilities\n : value as Readonly<Record<string, unknown>>;\n const children = manifestNodes(childTree, located);\n nodes.push(Object.freeze({\n type: \"group\",\n key,\n ...(decorated && value.title ? { title: value.title } : {}),\n ...(decorated && value.description\n ? { description: value.description }\n : {}),\n meta: decorated ? value.meta : {},\n children,\n } satisfies ManifestGroup));\n }\n return nodes;\n}\n\nfunction manifestCapability(entry: LocatedCapability): ManifestCapability {\n const capability = entry.capability;\n return Object.freeze({\n type: \"capability\",\n id: capability.id,\n path: entry.path,\n ...(capability.title ? { title: capability.title } : {}),\n ...(capability.description ? { description: capability.description } : {}),\n deprecated: capability.deprecated,\n ...(capability.effect ? { effect: capability.effect } : {}),\n ...(capability.subscribe\n ? { subscription: { mode: \"replace\" as const } }\n : {}),\n ...(capability.input\n ? { input: manifestJsonSchema(capability.input, \"input\") }\n : {}),\n ...(capability.output\n ? { output: manifestJsonSchema(capability.output, \"output\") }\n : {}),\n errors: Object.fromEntries(\n Object.entries(entry.errors).map(([code, definition]) => [\n code,\n {\n ...(definition.message ? { message: definition.message } : {}),\n ...(typeof definition.status === \"number\"\n ? { status: definition.status }\n : {}),\n ...(definition.data\n ? { data: manifestJsonSchema(definition.data, \"output\") }\n : {}),\n ...(definition.meta ? { meta: definition.meta } : {}),\n } satisfies ManifestError,\n ]),\n ),\n meta: capability.meta,\n });\n}\n\nfunction manifestJsonSchema(\n schema: AnySchema,\n direction: \"input\" | \"output\",\n): JsonSchema {\n return schemaToJsonSchema(schema, direction, {\n allowUnrepresentable: true,\n });\n}\n\nfunction validateManifestPaths(\n nodes: readonly ManifestNode[],\n parent: readonly string[],\n label: string,\n): void {\n for (const node of nodes) {\n if (node.type === \"group\") {\n validateManifestPaths(node.children, [...parent, node.key], label);\n continue;\n }\n if (!samePath(node.path, [...parent, node.path.at(-1)!])) {\n throw new Error(\n `${label} Capability \"${node.id}\" declares path \"${node.path.join(\".\")}\" that does not match its manifest placement`,\n );\n }\n }\n}\n\nfunction collectManifestConflicts(\n sources: readonly ApplicationManifestSource[],\n): readonly string[] {\n const conflicts: string[] = [];\n for (const { manifest } of sources) {\n try {\n validateManifest(manifest, manifest.name);\n } catch (error) {\n conflicts.push(error instanceof Error ? error.message : String(error));\n }\n }\n const capabilities = sources.flatMap(({ manifest, owner }, source) =>\n flattenManifestCapabilities(manifest.capabilities).map((capability) => ({\n capability,\n source,\n owner,\n label: manifest.name,\n }))\n );\n for (let leftIndex = 0; leftIndex < capabilities.length; leftIndex++) {\n for (\n let rightIndex = leftIndex + 1;\n rightIndex < capabilities.length;\n rightIndex++\n ) {\n const left = capabilities[leftIndex]!;\n const right = capabilities[rightIndex]!;\n if (left.source === right.source) continue;\n const sameId = left.capability.id === right.capability.id;\n const sameCapabilityPath = samePath(\n left.capability.path,\n right.capability.path,\n );\n if (sameCapabilityPath) {\n conflicts.push(\n sameId\n ? `Capability \"${left.capability.id}\" is placed twice at \"${left.capability.path.join(\".\")}\" by \"${left.label}\" and \"${right.label}\"`\n : `Path \"${left.capability.path.join(\".\")}\" contains both \"${left.capability.id}\" from \"${left.label}\" and \"${right.capability.id}\" from \"${right.label}\"`,\n );\n continue;\n }\n if (sameId) {\n if (left.owner !== right.owner) {\n conflicts.push(\n `Capability id \"${left.capability.id}\" is owned by different Apps at \"${left.capability.path.join(\".\")}\" in \"${left.label}\" and \"${right.capability.path.join(\".\")}\"`,\n );\n }\n }\n if (\n isPathPrefix(left.capability.path, right.capability.path) ||\n isPathPrefix(right.capability.path, left.capability.path)\n ) {\n const leaf = left.capability.path.length < right.capability.path.length\n ? left\n : right;\n const subtree = leaf === left ? right : left;\n conflicts.push(\n `Leaf \"${leaf.capability.path.join(\".\")}\" from \"${leaf.label}\" collides with subtree Capability \"${subtree.capability.path.join(\".\")}\" from \"${subtree.label}\"`,\n );\n }\n }\n }\n return [...new Set(conflicts)];\n}\n\nfunction sameCapabilityContract(\n left: ManifestCapability,\n right: ManifestCapability,\n): boolean {\n const { path: _leftPath, ...leftContract } = left;\n const { path: _rightPath, ...rightContract } = right;\n return JSON.stringify(leftContract) === JSON.stringify(rightContract);\n}\n\nfunction mergeManifestNodes(\n nodes: readonly ManifestNode[],\n): readonly ManifestNode[] {\n const merged = new Map<string, ManifestNode>();\n for (const node of nodes) {\n const key = node.type === \"group\" ? node.key : node.path.at(-1)!;\n const previous = merged.get(key);\n if (!previous) {\n merged.set(key, node);\n continue;\n }\n if (previous.type !== \"group\" || node.type !== \"group\") {\n throw new Error(`Manifest node collision at \"${key}\"`);\n }\n merged.set(key, Object.freeze({\n type: \"group\",\n key,\n ...mergeGroupField(\"title\", previous.title, node.title, key),\n ...mergeGroupField(\n \"description\",\n previous.description,\n node.description,\n key,\n ),\n meta: mergeGroupMeta(previous.meta, node.meta, key),\n children: mergeManifestNodes([...previous.children, ...node.children]),\n }));\n }\n return [...merged.values()];\n}\n\nfunction mergeGroupField(\n field: \"title\" | \"description\",\n left: string | undefined,\n right: string | undefined,\n path: string,\n): Record<string, string> {\n if (left && right && left !== right) {\n throw new Error(`Group \"${path}\" has conflicting ${field}`);\n }\n const value = left ?? right;\n return value ? { [field]: value } : {};\n}\n\nfunction mergeGroupMeta(\n left: Readonly<Record<string, unknown>>,\n right: Readonly<Record<string, unknown>>,\n path: string,\n): Readonly<Record<string, unknown>> {\n const merged: Record<string, unknown> = { ...left };\n for (const [key, value] of Object.entries(right)) {\n if (\n key in merged &&\n JSON.stringify(merged[key]) !== JSON.stringify(value)\n ) {\n throw new Error(\n `Group \"${path}\" has conflicting metadata for \"${key}\"`,\n );\n }\n merged[key] = value;\n }\n return Object.freeze(merged);\n}\n\nfunction filterManifestNodes(\n nodes: readonly ManifestNode[],\n selection: {\n readonly include?: unknown;\n readonly exclude?: unknown;\n },\n): readonly ManifestNode[] {\n const filtered: ManifestNode[] = [];\n for (const node of nodes) {\n if (node.type === \"capability\") {\n const included = selection.include\n ? matchesManifestSelection(selection.include, node.path)\n : true;\n if (\n included && !matchesManifestSelection(selection.exclude, node.path)\n ) {\n filtered.push(node);\n }\n continue;\n }\n const children = filterManifestNodes(node.children, selection);\n if (children.length) filtered.push(Object.freeze({ ...node, children }));\n }\n return filtered;\n}\n\nfunction matchesManifestSelection(\n tree: unknown,\n path: readonly string[],\n): boolean {\n let current = tree;\n for (const segment of path) {\n if (current === true) return true;\n if (!current || typeof current !== \"object\" || Array.isArray(current)) {\n return false;\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return current === true || (\n Boolean(current) && typeof current === \"object\" && !Array.isArray(current)\n );\n}\n\nfunction samePath(\n left: readonly string[],\n right: readonly string[],\n): boolean {\n return left.length === right.length &&\n left.every((segment, index) => segment === right[index]);\n}\n\nfunction isPathPrefix(\n prefix: readonly string[],\n path: readonly string[],\n): boolean {\n return prefix.length < path.length &&\n prefix.every((segment, index) => segment === path[index]);\n}\n","import {\n CapableError,\n executeLocatedCapability,\n normalizePresentation,\n subscribeLocatedCapability,\n type AnyCapability,\n type AnyObjectSchema,\n type AppDefinition,\n type AppContext,\n type InferSchemaInput,\n type LocatedCapability,\n type MaybePromise,\n type PresentationPart,\n type CapabilityDefinition,\n type CapabilityGroupDefinition,\n type CapabilityOutput,\n type CapabilityTree,\n type SubscribableCapability,\n} from \"@capable/core\";\nimport {\n createAppManifest,\n findManifestCapability,\n validateManifest,\n type ApplicationManifest,\n type ManifestCapability,\n} from \"./manifest.ts\";\n\nexport type CapabilityCall = {\n readonly id: string;\n readonly input?: unknown;\n readonly signal?: AbortSignal;\n readonly presentation?: boolean;\n};\n\nexport type CapabilityResult = {\n readonly output: unknown;\n readonly presentation?: readonly PresentationPart[];\n};\n\nexport interface ApplicationTransport {\n manifest(\n options?: { readonly signal?: AbortSignal },\n ): Promise<ApplicationManifest>;\n call(call: CapabilityCall): Promise<CapabilityResult>;\n subscribe(call: CapabilityCall): AsyncIterableIterator<CapabilityResult>;\n}\n\nexport type ResolvedCapability = {\n readonly capability: ManifestCapability;\n readonly transport: ApplicationTransport;\n};\n\n/** The in-process runtime can bind one path without resolving sibling Apps. */\nexport interface ApplicationRuntime extends ApplicationTransport {\n resolve(path: readonly string[]): Promise<ResolvedCapability | undefined>;\n}\n\nexport const APP_RUNTIME_SYMBOL: unique symbol = Symbol.for(\n \"capable.app.runtime\",\n) as never;\nexport const APP_CAPABILITIES_SYMBOL: unique symbol = Symbol.for(\n \"capable.app.capabilities\",\n) as never;\nconst APP_CALL_SYMBOL = Symbol.for(\"capable.app.call\");\n\ntype AppCapabilityType<TCapability extends AnyCapability> = {\n readonly \"~capable/capability\"?: TCapability;\n};\n\ntype AppCapabilityInput<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<any, infer TInput, any, any, any>\n ? TInput extends AnyObjectSchema\n ? InferSchemaInput<TInput>\n : Record<never, never>\n : never;\n\ntype AppCapabilityOutput<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<any, any, infer TOutput, any, any>\n ? TOutput\n : never;\n\ntype AppCapabilityOptions = { readonly signal?: AbortSignal };\n\ntype AppCapabilityArgs<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<any, infer TInput, any, any, any>\n ? TInput extends undefined\n ? [\n input?: Record<never, never>,\n options?: AppCapabilityOptions,\n ]\n : Record<never, never> extends AppCapabilityInput<TCapability>\n ? [\n input?: AppCapabilityInput<TCapability>,\n options?: AppCapabilityOptions,\n ]\n : [\n input: AppCapabilityInput<TCapability>,\n options?: AppCapabilityOptions,\n ]\n : never;\n\nexport type AppCapabilityCall<TCapability extends AnyCapability> = ((\n ...args: AppCapabilityArgs<TCapability>\n) => Promise<AppCapabilityOutput<TCapability>>) &\n AppCapabilityType<TCapability>;\n\nexport type AppCapabilityIsSubscribable<TCall> =\n TCall extends AppCapabilityType<infer TCapability>\n ? TCapability extends CapabilityDefinition<any, any, any, any, any, true>\n ? true\n : false\n : false;\n\nexport type CallableTree<TTree> =\n TTree extends AnyCapability\n ? AppCapabilityCall<TTree>\n : TTree extends CapabilityGroupDefinition<infer TCapabilities, any, any>\n ? CallableTree<TCapabilities>\n : TTree extends CapabilityTree\n ? { readonly [TKey in keyof TTree]: CallableTree<TTree[TKey]> }\n : never;\n\nexport type App<\n TCapabilities extends CapabilityTree = CapabilityTree,\n> = CallableTree<TCapabilities> & {\n readonly [APP_RUNTIME_SYMBOL]: ApplicationTransport;\n readonly [APP_CAPABILITIES_SYMBOL]?: TCapabilities;\n};\n\nexport type AnyApp = {\n readonly [APP_RUNTIME_SYMBOL]: ApplicationTransport;\n readonly [APP_CAPABILITIES_SYMBOL]?: CapabilityTree;\n};\n\ntype DefinitionCapabilities<TDefinition extends AppDefinition<any, any>> =\n TDefinition extends AppDefinition<infer TCapabilities>\n ? TCapabilities\n : never;\n\nexport type AppCapabilities<\n TApplication extends AnyApp,\n> = TApplication extends {\n readonly [APP_CAPABILITIES_SYMBOL]?: infer TCapabilities extends CapabilityTree;\n}\n ? TCapabilities\n : never;\n\nexport function getAppRuntime(\n app: AnyApp,\n): ApplicationTransport {\n return app[APP_RUNTIME_SYMBOL];\n}\n\n/** @internal Composition uses path bindings without exposing them to transports. */\nexport function getInternalAppRuntime(\n app: AnyApp,\n): ApplicationRuntime {\n const runtime = app[APP_RUNTIME_SYMBOL];\n if (!(\"resolve\" in runtime) || typeof runtime.resolve !== \"function\") {\n throw new TypeError(\"Capable App is missing its internal path resolver\");\n }\n return runtime as ApplicationRuntime;\n}\n\nexport function isApp(value: unknown): value is AnyApp {\n return Boolean(\n value &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n (value as Partial<AnyApp>)[APP_RUNTIME_SYMBOL],\n );\n}\n\nexport function appFromRuntime<\n TCapabilities extends CapabilityTree,\n>(\n runtime: ApplicationRuntime,\n): App<TCapabilities> {\n const read = (path: readonly string[], root: boolean, key: PropertyKey) => {\n if (root && key === APP_RUNTIME_SYMBOL) return runtime;\n if (!root && key === APP_CALL_SYMBOL) return { runtime, path };\n if (key === \"then\") return undefined;\n if (typeof key !== \"string\") return undefined;\n return proxy([...path, key], false);\n };\n\n const proxy = (path: readonly string[], root: boolean): unknown => {\n if (root) {\n return new Proxy({}, {\n get(_target, key) {\n return read(path, true, key);\n },\n });\n }\n return new Proxy(() => undefined, {\n get(_target, key) {\n return read(path, false, key);\n },\n async apply(_target, _this, args: [unknown?, { signal?: AbortSignal }?]) {\n const signal = args[1]?.signal;\n const binding = await runtime.resolve(path);\n if (!binding) {\n throw new Error(`No Capability exists at \"${path.join(\".\")}\"`);\n }\n const result = await binding.transport.call({\n id: binding.capability.id,\n input: args[0] ?? {},\n ...(signal ? { signal } : {}),\n });\n return result.output;\n },\n });\n };\n\n return proxy([], true) as App<TCapabilities>;\n}\n\nexport function subscribe<\n const TCapability extends SubscribableCapability,\n>(\n capabilityCall: AppCapabilityCall<TCapability>,\n ...args: AppCapabilityArgs<TCapability>\n): AsyncIterableIterator<CapabilityOutput<TCapability>> {\n const binding = (\n capabilityCall as unknown as Record<PropertyKey, unknown>\n )[APP_CALL_SYMBOL] as\n | {\n readonly runtime: ApplicationRuntime;\n readonly path: readonly string[];\n }\n | undefined;\n if (!binding) {\n throw new Error(\"subscribe() requires a Capability call from a Capable App\");\n }\n\n return (async function* () {\n const signal = args[1]?.signal;\n const resolved = await binding.runtime.resolve(binding.path);\n if (!resolved) {\n throw new Error(`No Capability exists at \"${binding.path.join(\".\")}\"`);\n }\n if (!resolved.capability.subscription) {\n throw new Error(\n `Capability \"${resolved.capability.id}\" is not subscribable`,\n );\n }\n const stream = resolved.transport.subscribe({\n id: resolved.capability.id,\n input: args[0] ?? {},\n ...(signal ? { signal } : {}),\n });\n try {\n for await (const result of stream) {\n yield result.output as CapabilityOutput<TCapability>;\n }\n } finally {\n await stream.return?.();\n }\n })();\n}\n\nexport type AppContextProvider<TContext> = (call: {\n readonly id: string;\n readonly signal?: AbortSignal;\n}) => MaybePromise<TContext>;\n\ntype CreateAppOptions<TContext> = {\n readonly context: AppContextProvider<TContext>;\n};\n\ntype CreateAppArgs<TContext> = [TContext] extends [undefined]\n ? [options?: Partial<CreateAppOptions<TContext>>]\n : [options: CreateAppOptions<TContext>];\n\nconst localManifestCache = new WeakMap<object, ApplicationManifest>();\nconst localCapabilityCache = new WeakMap<\n object,\n ReadonlyMap<string, LocatedCapability>\n>();\n\nexport function createApp<\n const TDefinition extends AppDefinition<any, any>,\n>(\n definition: TDefinition,\n ...[options]: CreateAppArgs<AppContext<TDefinition>>\n): App<DefinitionCapabilities<TDefinition>> {\n let manifest = localManifestCache.get(definition);\n if (!manifest) {\n manifest = createAppManifest(definition);\n localManifestCache.set(definition, manifest);\n }\n let byId = localCapabilityCache.get(definition);\n if (!byId) {\n byId = new Map(\n definition.locatedCapabilities.map((entry) => [entry.capability.id, entry]),\n );\n localCapabilityCache.set(definition, byId);\n }\n const runtime: ApplicationRuntime = Object.freeze({\n async manifest() {\n return manifest;\n },\n async resolve(path: readonly string[]) {\n const capability = findManifestCapability(manifest.capabilities, path);\n return capability ? { capability, transport: runtime } : undefined;\n },\n async call({ id, input = {}, signal, presentation: wantsPresentation }: CapabilityCall) {\n const located = byId.get(id);\n if (!located) throw new TransportError(\"NOT_FOUND\", { status: 404 });\n\n let context: unknown;\n try {\n context = options?.context\n ? await options.context({\n id,\n ...(signal ? { signal } : {}),\n })\n : undefined;\n } catch (cause) {\n throw new TransportError(\"INTERNAL_SERVER_ERROR\", { cause });\n }\n\n let output: unknown;\n try {\n output = await executeLocatedCapability(located, input, {\n context,\n ...(signal ? { signal } : {}),\n });\n } catch (error) {\n if (error instanceof CapableError) {\n throw new TransportError(error.code, {\n ...(error.message ? { message: error.message } : {}),\n ...(typeof error.status === \"number\"\n ? { status: error.status }\n : {}),\n ...(error.data === undefined ? {} : { data: error.data }),\n cause: error,\n });\n }\n throw new TransportError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n }\n\n const presentation = await materializePresentation(\n located.capability,\n output,\n context,\n wantsPresentation,\n );\n\n return {\n output,\n ...(presentation ? { presentation } : {}),\n };\n },\n async *subscribe({\n id,\n input = {},\n signal,\n presentation: wantsPresentation,\n }: CapabilityCall) {\n const located = byId.get(id);\n if (!located) throw new TransportError(\"NOT_FOUND\", { status: 404 });\n if (!located.capability.subscribe) {\n throw new TransportError(\"NOT_FOUND\", { status: 404 });\n }\n\n let context: unknown;\n try {\n context = options?.context\n ? await options.context({\n id,\n ...(signal ? { signal } : {}),\n })\n : undefined;\n } catch (cause) {\n throw new TransportError(\"INTERNAL_SERVER_ERROR\", { cause });\n }\n\n const stream = subscribeLocatedCapability(located, input, {\n context,\n ...(signal ? { signal } : {}),\n });\n try {\n for await (const output of stream) {\n const presentation = await materializePresentation(\n located.capability,\n output,\n context,\n wantsPresentation,\n );\n yield {\n output,\n ...(presentation ? { presentation } : {}),\n };\n }\n } catch (error) {\n throw toTransportError(error);\n } finally {\n await stream.return?.();\n }\n },\n });\n return appFromRuntime(runtime);\n}\n\nexport function createRemoteApp<\n TDefinition extends AppDefinition<any, any> = AppDefinition<CapabilityTree>,\n>(\n transport: ApplicationTransport,\n): App<DefinitionCapabilities<TDefinition>> {\n const manifest = createManifestResolver(async () => {\n const manifest = await transport.manifest();\n validateManifest(manifest, \"Remote App\");\n return manifest;\n });\n const runtime: ApplicationRuntime = Object.freeze({\n manifest,\n async resolve(path: readonly string[]) {\n const capability = findManifestCapability(\n (await manifest()).capabilities,\n path,\n );\n return capability ? { capability, transport } : undefined;\n },\n async call(call: CapabilityCall) {\n await manifest();\n return transport.call(call);\n },\n async *subscribe(call: CapabilityCall) {\n await manifest();\n yield* transport.subscribe(call);\n },\n });\n return appFromRuntime(runtime);\n}\n\nexport function createManifestResolver(\n load: () => Promise<ApplicationManifest>,\n): () => Promise<ApplicationManifest> {\n let cached: Promise<ApplicationManifest> | undefined;\n return () => {\n if (cached) return cached;\n const attempt = Promise.resolve().then(load);\n cached = attempt;\n void attempt.catch(() => {\n if (cached === attempt) cached = undefined;\n });\n return attempt;\n };\n}\n\nexport class TransportError extends Error {\n readonly code: string;\n readonly status: number | undefined;\n readonly data: unknown;\n\n constructor(\n code: string,\n options: {\n readonly message?: string;\n readonly status?: number;\n readonly data?: unknown;\n readonly cause?: unknown;\n } = {},\n ) {\n super(options.message ?? code, { cause: options.cause });\n this.name = \"TransportError\";\n this.code = code;\n this.status = options.status;\n this.data = options.data;\n }\n}\n\nasync function materializePresentation(\n capability: AnyCapability,\n output: unknown,\n context: unknown,\n requested: boolean | undefined,\n): Promise<readonly PresentationPart[] | undefined> {\n if (!requested || !capability.toPresentation) return undefined;\n try {\n const presentation = normalizePresentation(\n await capability.toPresentation(output, { context }),\n );\n return presentation.length > 0 ? presentation : undefined;\n } catch (cause) {\n throw new TransportError(\"INTERNAL_SERVER_ERROR\", { cause });\n }\n}\n\nfunction toTransportError(error: unknown): TransportError {\n if (error instanceof TransportError) return error;\n if (error instanceof CapableError) {\n return new TransportError(error.code, {\n ...(error.message ? { message: error.message } : {}),\n ...(typeof error.status === \"number\" ? { status: error.status } : {}),\n ...(error.data === undefined ? {} : { data: error.data }),\n cause: error,\n });\n }\n return new TransportError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n}\n","import type {\n AnyCapability,\n CapabilityGroupDefinition,\n CapabilityTree,\n} from \"@capable/core\";\nimport {\n appFromRuntime,\n createManifestResolver,\n getInternalAppRuntime,\n isApp,\n TransportError,\n type AnyApp,\n type App,\n type AppCapabilities,\n type ApplicationRuntime,\n type ApplicationTransport,\n type CapabilityCall,\n} from \"./runtime.ts\";\nimport {\n flattenManifestCapabilities,\n composeApplicationManifests,\n findManifestCapability,\n selectManifest,\n type ApplicationManifest,\n type ManifestNode,\n} from \"./manifest.ts\";\n\ntype UnionToIntersection<TValue> =\n (TValue extends unknown ? (value: TValue) => void : never) extends\n (value: infer TIntersection) => void ? TIntersection : never;\n\ntype AppComposition = AnyApp | {\n readonly [key: string]: AppComposition;\n};\n\ntype ComposedNode<TNode> = TNode extends AnyApp\n ? AppCapabilities<TNode>\n : TNode extends Readonly<Record<string, unknown>>\n ? { readonly [TKey in keyof TNode]: ComposedNode<TNode[TKey]> }\n : never;\n\ntype ComposedCapabilities<\n TNodes extends readonly AppComposition[],\n> = UnionToIntersection<ComposedNode<TNodes[number]>> extends\n infer TCapabilities extends CapabilityTree ? TCapabilities : never;\n\n/** Compose root Apps and tree-shaped App placements into one executable App. */\nexport function composeApps<\n const TNodes extends readonly [\n AppComposition,\n ...AppComposition[],\n ],\n>(\n ...nodes: TNodes\n): App<ComposedCapabilities<TNodes>> {\n const placements = nodes.flatMap((node) => collectPlacements(node, []));\n const uniquePlacements = placements.filter((placement, index) =>\n placements.findIndex((candidate) =>\n candidate.runtime === placement.runtime &&\n samePath(candidate.path, placement.path)\n ) === index\n );\n return appFromRuntime(\n createCompositionRuntime(uniquePlacements),\n ) as App<ComposedCapabilities<TNodes>>;\n}\n\ntype AppPlacement = {\n readonly path: readonly string[];\n readonly runtime: ApplicationRuntime;\n};\n\nfunction collectPlacements(\n node: AppComposition,\n path: readonly string[],\n): readonly AppPlacement[] {\n if (isApp(node)) {\n return [{ path: Object.freeze(path), runtime: getInternalAppRuntime(node) }];\n }\n if (!node || typeof node !== \"object\" || Array.isArray(node)) {\n throw new TypeError(\n \"composeApps() entries must be Apps or named object trees\",\n );\n }\n const entries = Object.entries(node);\n if (entries.length === 0) {\n throw new Error(\n `composeApps() contains an empty object at \"${path.join(\".\") || \"<root>\"}\"`,\n );\n }\n return entries.flatMap(([key, child]) => {\n if (!key) throw new Error(\"composeApps() keys must not be empty\");\n if (key === \"then\") {\n throw new Error('composeApps() uses reserved key \"then\"');\n }\n return collectPlacements(child, [...path, key]);\n });\n}\n\nfunction createCompositionRuntime(\n placements: readonly AppPlacement[],\n): ApplicationRuntime {\n let dispatch: ReadonlyMap<string, ApplicationTransport> | undefined;\n\n const resolve = createManifestResolver(async () => {\n const sources = await Promise.all(placements.map(async (placement) => ({\n manifest: placeManifest(\n placement.path,\n await placement.runtime.manifest(),\n ),\n owner: placement.runtime,\n })));\n const composed = composeApplicationManifests(sources);\n const nextDispatch = new Map<string, ApplicationTransport>();\n sources.forEach(({ manifest }, index) => {\n for (\n const capability of flattenManifestCapabilities(\n manifest.capabilities,\n )\n ) {\n nextDispatch.set(capability.id, placements[index]!.runtime);\n }\n });\n dispatch = nextDispatch;\n return composed;\n });\n\n return Object.freeze({\n manifest: resolve,\n async resolve(path: readonly string[]) {\n const matches = (await Promise.all(\n placements\n .filter((placement) => isPathPrefixOrEqual(placement.path, path))\n .map((placement) =>\n placement.runtime.resolve(path.slice(placement.path.length))\n ),\n )).filter((match) => match !== undefined).filter((match, index, all) =>\n all.findIndex((candidate) =>\n candidate.capability.id === match.capability.id &&\n candidate.transport === match.transport\n ) === index\n );\n if (matches.length === 0) return undefined;\n if (matches.length > 1) {\n throw new Error(`Cannot resolve ambiguous App path \"${path.join(\".\")}\"`);\n }\n return matches[0];\n },\n async call(call: CapabilityCall) {\n await resolve();\n const target = dispatch?.get(call.id);\n if (!target) throw new TransportError(\"NOT_FOUND\", { status: 404 });\n return target.call(call);\n },\n async *subscribe(call: CapabilityCall) {\n await resolve();\n const target = dispatch?.get(call.id);\n if (!target) throw new TransportError(\"NOT_FOUND\", { status: 404 });\n yield* target.subscribe(call);\n },\n });\n}\n\ntype SelectionNode<TTree> =\n TTree extends AnyCapability\n ? true\n : TTree extends CapabilityGroupDefinition<infer TCapabilities, any, any>\n ? true | SelectionNode<TCapabilities>\n : TTree extends CapabilityTree\n ? true | {\n readonly [TKey in keyof TTree]?: SelectionNode<TTree[TKey]>;\n }\n : never;\n\nexport type ApplicationSelection<\n TCapabilities extends CapabilityTree = CapabilityTree,\n> = {\n readonly include?: Exclude<SelectionNode<TCapabilities>, true>;\n readonly exclude?: Exclude<SelectionNode<TCapabilities>, true>;\n};\n\nexport function selectApp<\n const TCapabilities extends CapabilityTree,\n>(\n application: App<TCapabilities>,\n selection: ApplicationSelection<TCapabilities>,\n): App<TCapabilities> {\n const runtime = getInternalAppRuntime(application);\n let ids: ReadonlySet<string> | undefined;\n const manifest = createManifestResolver(async () => {\n const selected = selectManifest(await runtime.manifest(), selection);\n ids = new Set(\n flattenManifestCapabilities(selected.capabilities).map(\n (capability) => capability.id,\n ),\n );\n return selected;\n });\n const selectedRuntime: ApplicationRuntime = Object.freeze({\n manifest,\n async resolve(path: readonly string[]) {\n const selected = await manifest();\n if (!findManifestCapability(selected.capabilities, path)) {\n return undefined;\n }\n return runtime.resolve(path);\n },\n async call(call: CapabilityCall) {\n await manifest();\n if (!ids?.has(call.id)) {\n throw new TransportError(\"NOT_FOUND\", { status: 404 });\n }\n return runtime.call(call);\n },\n async *subscribe(call: CapabilityCall) {\n await manifest();\n if (!ids?.has(call.id)) {\n throw new TransportError(\"NOT_FOUND\", { status: 404 });\n }\n yield* runtime.subscribe(call);\n },\n });\n return appFromRuntime(selectedRuntime);\n}\n\nfunction placeManifest(\n path: readonly string[],\n source: ApplicationManifest,\n): ApplicationManifest {\n if (path.length === 0) return source;\n let capabilities = prefixManifestPaths(source.capabilities, path);\n for (let index = path.length - 1; index >= 0; index--) {\n const leaf = index === path.length - 1;\n capabilities = Object.freeze([Object.freeze({\n type: \"group\" as const,\n key: path[index]!,\n ...(leaf ? { title: source.name } : {}),\n ...(leaf && source.description\n ? { description: source.description }\n : {}),\n meta: Object.freeze({}),\n children: capabilities,\n })]);\n }\n return Object.freeze({\n ...source,\n capabilities,\n });\n}\n\nfunction prefixManifestPaths(\n nodes: readonly ManifestNode[],\n prefix: readonly string[],\n): readonly ManifestNode[] {\n return Object.freeze(nodes.map((node) =>\n node.type === \"capability\"\n ? Object.freeze({\n ...node,\n path: Object.freeze([...prefix, ...node.path]),\n })\n : Object.freeze({\n ...node,\n children: prefixManifestPaths(node.children, prefix),\n })\n ));\n}\n\nfunction isPathPrefixOrEqual(\n prefix: readonly string[],\n path: readonly string[],\n): boolean {\n return prefix.length <= path.length &&\n prefix.every((segment, index) => segment === path[index]);\n}\n\nfunction samePath(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length &&\n left.every((segment, index) => segment === right[index]);\n}\n"],"mappings":";;AAoDA,SAAgB,kBACd,YACqB;CACrB,MAAM,eAAe,IAAI,IACvB,WAAW,oBAAoB,KAAK,UAAU,CAAC,MAAM,YAAY,KAAK,CAAC,CACzE;CACA,OAAO,OAAO,OAAO;EACnB,UAAU;EACV,MAAM,WAAW;EACjB,SAAS,WAAW;EACpB,GAAI,WAAW,cAAc,EAAE,aAAa,WAAW,YAAY,IAAI,CAAC;EACxE,cAAc,cAAc,WAAW,cAAc,YAAY;CACnE,CAAC;AACH;AAEA,SAAgB,iBACd,UACA,OACM;CACN,IAAI,SAAS,aAAa,2BACxB,MAAM,IAAI,MAAM,GAAG,MAAM,8BAA8B,SAAS,SAAS,EAAE;CA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,OACA,QACyB;CACzB,OAAO,OAAO,OAAO,MAAM,KAAK,SAC9B,KAAK,SAAS,eACV,OAAO,OAAO;EACZ,GAAG;EACH,MAAM,OAAO,OAAO,CAAC,GAAG,QAAQ,GAAG,KAAK,IAAI,CAAC;CAC/C,CAAC,IACD,OAAO,OAAO;EACZ,GAAG;EACH,UAAU,oBAAoB,KAAK,UAAU,MAAM;CACrD,CAAC,CACP,CAAC;AACH;AAEA,SAAS,oBACP,QACA,MACS;CACT,OAAO,OAAO,UAAU,KAAK,UAC3B,OAAO,OAAO,SAAS,UAAU,YAAY,KAAK,MAAM;AAC5D;AAEA,SAAS,SAAS,MAAyB,OAAmC;CAC5E,OAAO,KAAK,WAAW,MAAM,UAC3B,KAAK,OAAO,SAAS,UAAU,YAAY,MAAM,MAAM;AAC3D"}
|
|
@@ -229,8 +229,8 @@ function createDemandIterator(produce) {
|
|
|
229
229
|
const demands = [];
|
|
230
230
|
const demandWaiters = [];
|
|
231
231
|
const cleanups = [];
|
|
232
|
-
const ready = deferred();
|
|
233
232
|
let activeDemand;
|
|
233
|
+
let started = false;
|
|
234
234
|
let closed = false;
|
|
235
235
|
let failure;
|
|
236
236
|
let hasFailure = false;
|
|
@@ -261,11 +261,7 @@ function createDemandIterator(produce) {
|
|
|
261
261
|
value
|
|
262
262
|
});
|
|
263
263
|
},
|
|
264
|
-
markReady() {
|
|
265
|
-
ready.resolve();
|
|
266
|
-
},
|
|
267
264
|
complete() {
|
|
268
|
-
stream.markReady();
|
|
269
265
|
closed = true;
|
|
270
266
|
activeDemand?.resolve({
|
|
271
267
|
done: true,
|
|
@@ -276,7 +272,6 @@ function createDemandIterator(produce) {
|
|
|
276
272
|
wakeProducer();
|
|
277
273
|
},
|
|
278
274
|
fail(error) {
|
|
279
|
-
ready.reject(error);
|
|
280
275
|
failure = error;
|
|
281
276
|
hasFailure = true;
|
|
282
277
|
closed = true;
|
|
@@ -293,8 +288,14 @@ function createDemandIterator(produce) {
|
|
|
293
288
|
cleanups.push(cleanup);
|
|
294
289
|
}
|
|
295
290
|
};
|
|
296
|
-
|
|
297
|
-
|
|
291
|
+
const start = () => {
|
|
292
|
+
if (started) return;
|
|
293
|
+
started = true;
|
|
294
|
+
task = produce(stream).then(() => {
|
|
295
|
+
if (!closed) stream.complete();
|
|
296
|
+
}, (error) => stream.fail(error));
|
|
297
|
+
};
|
|
298
|
+
return {
|
|
298
299
|
[Symbol.asyncIterator]() {
|
|
299
300
|
return this;
|
|
300
301
|
},
|
|
@@ -309,6 +310,7 @@ function createDemandIterator(produce) {
|
|
|
309
310
|
});
|
|
310
311
|
const demand = deferred();
|
|
311
312
|
demands.push(demand);
|
|
313
|
+
start();
|
|
312
314
|
wakeProducer();
|
|
313
315
|
return demand.promise;
|
|
314
316
|
},
|
|
@@ -331,13 +333,6 @@ function createDemandIterator(produce) {
|
|
|
331
333
|
};
|
|
332
334
|
}
|
|
333
335
|
};
|
|
334
|
-
task = produce(stream).then(() => {
|
|
335
|
-
if (!closed) stream.complete();
|
|
336
|
-
}, (error) => stream.fail(error));
|
|
337
|
-
return {
|
|
338
|
-
iterator,
|
|
339
|
-
ready: ready.promise
|
|
340
|
-
};
|
|
341
336
|
}
|
|
342
337
|
//#endregion
|
|
343
338
|
//#region packages/core/src/schema.ts
|
|
@@ -372,12 +367,9 @@ const capability = Object.assign(function capability(config) {
|
|
|
372
367
|
return config === void 0 ? createCapability : createCapability(config);
|
|
373
368
|
}, { withContext: capabilityWithContext });
|
|
374
369
|
function createCapability(config) {
|
|
375
|
-
const id = config.id;
|
|
376
370
|
if (!config.id) throw new Error("Capability id must not be empty");
|
|
377
|
-
if (config.subscribe && config.effect !== "read") throw new Error(`Capability "${id}" must declare effect "read" to subscribe`);
|
|
378
|
-
if (
|
|
379
|
-
if (config.subscribe !== void 0 && typeof config.subscribe !== "function") throw new Error(`Capability "${id}" subscribe must be a function`);
|
|
380
|
-
if (!config.handler && !config.subscribe) throw new Error(`Capability "${id}" requires a handler or subscribe`);
|
|
371
|
+
if (config.subscribe && config.effect !== "read") throw new Error(`Capability "${config.id}" must declare effect "read" to subscribe`);
|
|
372
|
+
if (typeof config.handler !== "function") throw new Error(`Capability "${config.id}" requires a handler`);
|
|
381
373
|
return Object.freeze({
|
|
382
374
|
[CAPABILITY_SYMBOL]: true,
|
|
383
375
|
id: config.id,
|
|
@@ -390,8 +382,7 @@ function createCapability(config) {
|
|
|
390
382
|
errors: config.errors ?? NO_ERRORS$1,
|
|
391
383
|
middleware: Object.freeze([...config.middleware ?? []]),
|
|
392
384
|
meta: Object.freeze({ ...config.meta ?? {} }),
|
|
393
|
-
|
|
394
|
-
...config.handler ? { handler: config.handler } : {},
|
|
385
|
+
handler: config.handler,
|
|
395
386
|
...config.subscribe ? { subscribe: config.subscribe } : {},
|
|
396
387
|
...config.toPresentation ? { toPresentation: config.toPresentation } : {}
|
|
397
388
|
});
|
|
@@ -410,11 +401,6 @@ async function executeCapability(capability, options) {
|
|
|
410
401
|
});
|
|
411
402
|
}
|
|
412
403
|
async function executeLocatedCapability(located, input, options) {
|
|
413
|
-
const handler = located.capability.handler;
|
|
414
|
-
if (!handler) throw new CapableError("METHOD_NOT_ALLOWED", {
|
|
415
|
-
status: 405,
|
|
416
|
-
message: `Capability "${located.capability.id}" only supports subscribe`
|
|
417
|
-
});
|
|
418
404
|
const parsedInput = await parseCapabilityInput(located.capability, input);
|
|
419
405
|
let rawOutput;
|
|
420
406
|
try {
|
|
@@ -427,7 +413,7 @@ async function executeLocatedCapability(located, input, options) {
|
|
|
427
413
|
input: parsedInput,
|
|
428
414
|
context: options.context,
|
|
429
415
|
...options.signal ? { signal: options.signal } : {}
|
|
430
|
-
}, () => handler({
|
|
416
|
+
}, () => located.capability.handler({
|
|
431
417
|
input: parsedInput,
|
|
432
418
|
context: options.context,
|
|
433
419
|
...options.signal ? { signal: options.signal } : {}
|
|
@@ -438,30 +424,30 @@ async function executeLocatedCapability(located, input, options) {
|
|
|
438
424
|
return validateCapabilityOutput(located.capability, rawOutput);
|
|
439
425
|
}
|
|
440
426
|
function subscribeCapability(capability, options) {
|
|
441
|
-
|
|
427
|
+
return subscribeLocatedCapability(Object.freeze({
|
|
442
428
|
path: Object.freeze([]),
|
|
443
429
|
groups: Object.freeze([]),
|
|
444
430
|
groupPaths: Object.freeze([]),
|
|
445
431
|
capability,
|
|
446
432
|
errors: Object.freeze({ ...errorDefinitions(capability.errors) }),
|
|
447
433
|
middleware: capability.middleware
|
|
434
|
+
}), options.input ?? {}, {
|
|
435
|
+
context: options.context,
|
|
436
|
+
...options.signal ? { signal: options.signal } : {}
|
|
448
437
|
});
|
|
449
|
-
return (async function* () {
|
|
450
|
-
yield* await subscribeLocatedCapability(located, options.input ?? {}, {
|
|
451
|
-
context: options.context,
|
|
452
|
-
...options.signal ? { signal: options.signal } : {}
|
|
453
|
-
});
|
|
454
|
-
})();
|
|
455
438
|
}
|
|
456
|
-
|
|
439
|
+
function subscribeLocatedCapability(located, input, options) {
|
|
457
440
|
const subscriber = located.capability.subscribe;
|
|
458
|
-
if (!subscriber) throw new
|
|
459
|
-
|
|
460
|
-
message: `Capability "${located.capability.id}" only supports call`
|
|
461
|
-
});
|
|
462
|
-
const parsedInput = await parseCapabilityInput(located.capability, input);
|
|
463
|
-
const subscription = createDemandIterator(async (stream) => {
|
|
441
|
+
if (!subscriber) throw new Error(`Capability "${located.capability.id}" is not subscribable`);
|
|
442
|
+
return createDemandIterator(async (stream) => {
|
|
464
443
|
let cleanupSource = async (_abort) => {};
|
|
444
|
+
let parsedInput;
|
|
445
|
+
try {
|
|
446
|
+
parsedInput = await parseCapabilityInput(located.capability, input);
|
|
447
|
+
} catch (error) {
|
|
448
|
+
stream.fail(error);
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
465
451
|
try {
|
|
466
452
|
const controller = new AbortController();
|
|
467
453
|
const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
|
|
@@ -493,19 +479,17 @@ async function subscribeLocatedCapability(located, input, options) {
|
|
|
493
479
|
if (!iterable || typeof iterable !== "object" || !(Symbol.asyncIterator in iterable)) throw new CapableError("INTERNAL_SERVER_ERROR", { message: `Capability "${located.capability.id}" subscribe must return an AsyncIterable` });
|
|
494
480
|
const sourceIterator = iterable[Symbol.asyncIterator]();
|
|
495
481
|
iterator = sourceIterator;
|
|
496
|
-
stream.markReady();
|
|
497
482
|
while (await stream.waitForDemand()) {
|
|
498
483
|
const result = await sourceIterator.next();
|
|
499
484
|
if (result.done) {
|
|
500
|
-
if (!emitted
|
|
485
|
+
if (!emitted) throw emptySubscriptionError(located.capability);
|
|
501
486
|
return;
|
|
502
487
|
}
|
|
503
488
|
emitted = true;
|
|
504
489
|
stream.emit(await validateCapabilityOutput(located.capability, result.value));
|
|
505
490
|
}
|
|
506
491
|
});
|
|
507
|
-
if (!emitted
|
|
508
|
-
stream.markReady();
|
|
492
|
+
if (!emitted) throw emptySubscriptionError(located.capability);
|
|
509
493
|
await cleanupSource(false);
|
|
510
494
|
stream.complete();
|
|
511
495
|
} catch (error) {
|
|
@@ -513,8 +497,6 @@ async function subscribeLocatedCapability(located, input, options) {
|
|
|
513
497
|
stream.fail(await normalizeCapabilityError(located, error));
|
|
514
498
|
}
|
|
515
499
|
});
|
|
516
|
-
await subscription.ready;
|
|
517
|
-
return subscription.iterator;
|
|
518
500
|
}
|
|
519
501
|
function emptySubscriptionError(capability) {
|
|
520
502
|
return new CapableError("INTERNAL_SERVER_ERROR", { message: `Capability "${capability.id}" subscription completed before yielding a value` });
|
|
@@ -704,4 +686,4 @@ function isRecord(value) {
|
|
|
704
686
|
//#endregion
|
|
705
687
|
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 };
|
|
706
688
|
|
|
707
|
-
//# sourceMappingURL=src-
|
|
689
|
+
//# sourceMappingURL=src-Bd1Vnze8.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-Bd1Vnze8.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 options: {\n readonly allowUnrepresentable?: boolean;\n } = {},\n): Readonly<Record<string, unknown>> {\n const projected = schema[\"~standard\"].jsonSchema[direction]({\n target: \"draft-2020-12\",\n ...(options.allowUnrepresentable\n ? { libraryOptions: { unrepresentable: \"any\" } }\n : {}),\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 capability: {\n readonly id: string;\n readonly effect: CapabilityEffect | undefined;\n };\n readonly mode: \"call\" | \"subscribe\";\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 TReturn,\n TErrors extends AnyDefinedErrors,\n TMeta extends OpenMeta<CapabilityMetaRegistry>,\n> = CapabilityBaseConfig<TContext, TInput, TErrors, TMeta> & {\n readonly output?: never;\n // Infer the full return union before awaiting it, including mixed sync/async branches.\n readonly handler: (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => TReturn;\n readonly toPresentation?: PresentationRenderer<Awaited<TReturn>, TContext>;\n readonly subscribe?: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n Awaited<TReturn>\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 TReturn = unknown,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: InferredOutputCapabilityConfig<\n TContext,\n TInput,\n TReturn,\n TErrors,\n TMeta\n > & {\n readonly subscribe: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n Awaited<TReturn>\n >;\n },\n ): CapabilityDefinition<\n TContext,\n TInput,\n Awaited<TReturn>,\n TErrors,\n TMeta,\n true\n >;\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n TReturn = unknown,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: InferredOutputCapabilityConfig<\n TContext,\n TInput,\n TReturn,\n TErrors,\n TMeta\n > & { readonly subscribe?: never },\n ): CapabilityDefinition<\n TContext,\n TInput,\n Awaited<TReturn>,\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 capability: Object.freeze({\n id: located.capability.id,\n effect: located.capability.effect,\n }),\n mode: \"call\",\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 capability: Object.freeze({\n id: located.capability.id,\n effect: located.capability.effect,\n }),\n mode: \"subscribe\",\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: Omit<CapabilityMiddlewareArgs<unknown>, \"next\">,\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 NoInfer<SharedContext<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 errors: AnyDefinedErrors;\n readonly middleware: readonly CapabilityMiddleware<any>[];\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 ? CapabilityTree extends TTree\n ? 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\ntype SharedContext<TCapabilities> =\n [Exclude<CapabilityTreeContext<TCapabilities>, undefined>] extends [never]\n ? undefined\n : UnionToIntersection<Exclude<CapabilityTreeContext<TCapabilities>, undefined>>;\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 errors?: AnyDefinedErrors;\n readonly middleware?: readonly CapabilityMiddleware<\n NoInfer<SharedContext<TCapabilities>>\n >[];\n readonly capabilities: TCapabilities;\n}): AppDefinition<\n TCapabilities,\n SharedContext<TCapabilities>\n> {\n assertCapabilityTree(config.capabilities, \"application.capabilities\");\n const errors = config.errors ?? NO_ERRORS;\n const middleware = Object.freeze([...(config.middleware ?? [])]);\n const located = locateCapabilities(\n config.capabilities,\n [],\n [],\n [],\n errorDefinitions(errors),\n middleware,\n );\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 errors,\n middleware,\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,YAAY,CAAC;CAC1D,MAAM,SAAuC,CAAC;CAE9C,KAAK,MAAM,CAAC,MAAM,eAAe,OAAO,QAAQ,iBAAiB,GAAG;EAClE,MAAM,WACJ,OACA,WACG;GACH,MAAM,UAAU,WAAW,SAAS,KAAA;GACpC,MAAM,OAAO,UAAU,QAAQ,KAAA;GAC/B,MAAM,UAAW,UAAU,SAAS;GAGpC,OAAO,IAAI,aAAa,MAAM;IAC5B,GAAI,WAAW,UAAU,EAAE,SAAS,WAAW,QAAQ,IAAI,CAAC;IAC5D,GAA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C;AACF;AAEA,SAAS,uBACP,WACA,YACA,OACM;CACN,MAAM,YAAY,OAAO,KAAK,UAAU,CAAC,CAAC,MAAM,SAAS,QAAQ,SAAS;CAC1E,IAAI,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,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { r as createProtocolHandler, t as createHttpHandler } from "./src-
|
|
1
|
+
import { n as selectApp, o as createApp } from "./src-B592M-6b.mjs";
|
|
2
|
+
import { r as createProtocolHandler, t as createHttpHandler } from "./src-Hw9WBgEW.mjs";
|
|
3
3
|
//#region packages/server/src/index.ts
|
|
4
4
|
function protocol(options = {}) {
|
|
5
5
|
return {
|
|
@@ -82,4 +82,4 @@ function normalizePath(value) {
|
|
|
82
82
|
//#endregion
|
|
83
83
|
export { http as n, protocol as r, createServer as t };
|
|
84
84
|
|
|
85
|
-
//# sourceMappingURL=src-
|
|
85
|
+
//# sourceMappingURL=src-CKC1BdXO.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"src-
|
|
1
|
+
{"version":3,"file":"src-CKC1BdXO.mjs","names":[],"sources":["../../server/src/index.ts"],"sourcesContent":["import type {\n AppDefinition,\n MaybePromise,\n} from \"@capable/core\";\nimport {\n createHttpHandler,\n createProtocolHandler,\n type ContextProvider,\n type CapabilitySelection,\n type ProtocolCodec,\n} from \"@capable/fetch\";\nimport {\n createApp,\n selectApp,\n type ApplicationSelection,\n} from \"@capable/app\";\n\nexport type ServerMount<TContext> = {\n readonly kind: \"capable.server.mount\";\n compile(\n app: AppDefinition<any, TContext>,\n context: ContextProvider<TContext> | undefined,\n onError?: (error: unknown) => void,\n ): CompiledServerMount;\n};\n\nexport type CompiledServerMount = {\n readonly name: string;\n readonly fetch: (request: Request) => MaybePromise<Response | undefined>;\n};\n\nexport function protocol<TContext = any>(\n options: {\n readonly path?: string;\n readonly selection?: ApplicationSelection;\n readonly codec?: ProtocolCodec;\n } = {},\n): ServerMount<TContext> {\n return {\n kind: \"capable.server.mount\",\n compile(app, context) {\n const protocol = createProtocolHandler(\n (request) => {\n const executable = createApp(\n app,\n context\n ? { context: () => context({ request }) }\n : undefined as never,\n );\n return options.selection\n ? selectApp(executable, options.selection)\n : executable;\n },\n {\n ...(options.path ? { basePath: options.path } : {}),\n ...(options.codec ? { codec: options.codec } : {}),\n },\n );\n const base = normalizePath(options.path ?? \"/~capable\");\n return {\n name: \"protocol\",\n async fetch(request) {\n if (!new URL(request.url).pathname.startsWith(`${base}/`)) {\n return undefined;\n }\n return protocol.fetch(request);\n },\n };\n },\n };\n}\n\nexport function http<TContext = any>(\n options: {\n readonly path?: string;\n readonly openapiPath?: string | false;\n readonly requireExplicitRoutes?: boolean;\n readonly selection?: CapabilitySelection;\n } = {},\n): ServerMount<TContext> {\n return {\n kind: \"capable.server.mount\",\n compile(app, context) {\n const handler = createHttpHandler(app, {\n ...(context ? { context } : {}),\n ...(options.path ? { basePath: options.path } : {}),\n ...(options.openapiPath !== undefined\n ? { openapiPath: options.openapiPath }\n : {}),\n ...(options.requireExplicitRoutes !== undefined\n ? { requireExplicitRoutes: options.requireExplicitRoutes }\n : {}),\n ...(options.selection ? { selection: options.selection } : {}),\n });\n const base = normalizePath(options.path ?? \"/api\");\n const openapiPath = options.openapiPath === false\n ? undefined\n : normalizePath(options.openapiPath ?? \"/openapi.json\");\n return {\n name: \"http\",\n async fetch(request) {\n const pathname = new URL(request.url).pathname;\n if (\n !pathname.startsWith(`${base}/`) &&\n pathname !== base &&\n pathname !== openapiPath\n ) {\n return undefined;\n }\n return handler.fetch(request);\n },\n };\n },\n };\n}\n\nexport type CapableServer = {\n readonly fetch: (request: Request) => Promise<Response>;\n};\n\nexport type ServerMiddleware = (args: {\n readonly request: Request;\n readonly next: (request?: Request) => Promise<Response>;\n}) => MaybePromise<Response>;\n\ntype CreateServerOptions<TContext> = {\n readonly context?: ContextProvider<TContext>;\n readonly mounts?: readonly ServerMount<TContext>[];\n readonly middleware?: ServerMiddleware;\n readonly onError?: (error: unknown) => void;\n};\n\ntype CreateServerArgs<TContext> = [TContext] extends [undefined]\n ? [options?: CreateServerOptions<TContext>]\n : [options: CreateServerOptions<TContext> & {\n readonly context: ContextProvider<TContext>;\n }];\n\nexport function createServer<TContext>(\n app: AppDefinition<any, TContext>,\n ...[providedOptions]: CreateServerArgs<TContext>\n): CapableServer {\n const options = (providedOptions ?? {}) as CreateServerOptions<TContext>;\n const mounts = (options.mounts ?? [protocol(), http()])\n .map((mount) => mount.compile(app, options.context, options.onError));\n\n async function dispatch(request: Request): Promise<Response> {\n for (const mount of mounts) {\n const response = await mount.fetch(request);\n if (response) return response;\n }\n return new Response(\"Not Found\", { status: 404 });\n }\n\n return Object.freeze({\n async fetch(request: Request) {\n try {\n return options.middleware\n ? await options.middleware({\n request,\n next: (nextRequest = request) => dispatch(nextRequest),\n })\n : await dispatch(request);\n } catch (error) {\n options.onError?.(error);\n return Response.json({\n ok: false,\n error: {\n code: \"INTERNAL_SERVER_ERROR\",\n message: \"Internal Server Error\",\n status: 500,\n },\n }, { status: 500 });\n }\n },\n });\n}\n\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n"],"mappings":";;;AA+BA,SAAgB,SACd,UAII,CAAC,GACkB;CACvB,OAAO;EACL,MAAM;EACN,QAAQ,KAAK,SAAS;GACpB,MAAM,WAAW,uBACd,YAAY;IACX,MAAM,aAAa,UACjB,KACA,UACI,EAAE,eAAe,QAAQ,EAAE,QAAQ,CAAC,EAAE,IACtC,KAAA,CACN;IACA,OAAO,QAAQ,YACX,UAAU,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