capable-kit 0.0.1-alpha.2 → 0.0.1-alpha.3

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.
@@ -1 +1 @@
1
- {"version":3,"file":"src-B53ZbNtC.mjs","names":["NO_ERRORS","isRecord"],"sources":["../../core/src/errors.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 = Symbol.for(\"capable.capability-errors\");\nexport const CAPABILITY_ERROR_DEFINITIONS_SYMBOL = Symbol.for(\n \"capable.capability-error-definitions\",\n);\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 WatchQueryOptions<TOutput> = {\n readonly snapshot: () => MaybePromise<TOutput>;\n readonly invalidations: () => AsyncIterable<unknown>;\n readonly signal?: AbortSignal;\n};\n\n/**\n * Turn an invalidation source into a stream of complete replacement snapshots.\n *\n * The invalidation iterator is pulled before the first snapshot is read. A\n * change racing with that read therefore causes another snapshot rather than\n * being missed.\n */\nexport async function* watchQuery<TOutput>(\n options: WatchQueryOptions<TOutput>,\n): AsyncIterableIterator<TOutput> {\n if (options.signal?.aborted) return;\n\n const iterator = options.invalidations()[Symbol.asyncIterator]();\n let pending = nextHandled(iterator);\n\n try {\n yield await options.snapshot();\n\n while (!options.signal?.aborted) {\n const result = await pending;\n if (result.done) return;\n pending = nextHandled(iterator);\n yield await options.snapshot();\n }\n } finally {\n await iterator.return?.();\n }\n}\n\nfunction nextHandled(iterator: AsyncIterator<unknown>) {\n const pending = iterator.next();\n void pending.catch(() => undefined);\n return pending;\n}\n\ntype Deferred<T> = {\n readonly promise: Promise<T>;\n resolve(value: T): void;\n reject(error: unknown): void;\n};\n\nfunction deferred<T>(): Deferred<T> {\n let resolve!: (value: T) => void;\n let reject!: (error: unknown) => void;\n const promise = new Promise<T>((onResolve, onReject) => {\n resolve = onResolve;\n reject = onReject;\n });\n return { promise, resolve, reject };\n}\n\nexport type DemandStream<T> = {\n waitForDemand(): Promise<boolean>;\n emit(value: T): void;\n complete(): void;\n fail(error: unknown): void;\n onCancel(cleanup: () => void | Promise<void>): void;\n};\n\nexport function createDemandIterator<T>(\n produce: (stream: DemandStream<T>) => Promise<void>,\n): AsyncIterableIterator<T> {\n const demands: Deferred<IteratorResult<T>>[] = [];\n const demandWaiters: Array<() => void> = [];\n const cleanups: Array<() => void | Promise<void>> = [];\n let activeDemand: Deferred<IteratorResult<T>> | undefined;\n let started = false;\n let closed = false;\n let failure: unknown;\n let hasFailure = false;\n let failureDelivered = false;\n let task: Promise<void> | undefined;\n\n const wakeProducer = () => demandWaiters.shift()?.();\n const finishPending = () => {\n for (const demand of demands.splice(0)) {\n if (hasFailure && !failureDelivered) {\n failureDelivered = true;\n demand.reject(failure);\n } else {\n demand.resolve({ done: true, value: undefined });\n }\n }\n };\n\n const stream: DemandStream<T> = {\n async waitForDemand() {\n while (!closed && demands.length === 0) {\n await new Promise<void>((resolve) => demandWaiters.push(resolve));\n }\n if (closed) return false;\n activeDemand = demands.shift();\n return Boolean(activeDemand);\n },\n emit(value) {\n const demand = activeDemand;\n activeDemand = undefined;\n demand?.resolve({ done: false, value });\n },\n complete() {\n closed = true;\n activeDemand?.resolve({ done: true, value: undefined });\n activeDemand = undefined;\n finishPending();\n wakeProducer();\n },\n fail(error) {\n failure = error;\n hasFailure = true;\n closed = true;\n const demand = activeDemand;\n activeDemand = undefined;\n if (demand) {\n failureDelivered = true;\n demand.reject(error);\n }\n finishPending();\n wakeProducer();\n },\n onCancel(cleanup) {\n cleanups.push(cleanup);\n },\n };\n\n const start = () => {\n if (started) return;\n started = true;\n task = produce(stream).then(\n () => {\n if (!closed) stream.complete();\n },\n (error) => stream.fail(error),\n );\n };\n\n return {\n [Symbol.asyncIterator]() {\n return this;\n },\n next() {\n if (hasFailure && !failureDelivered) {\n failureDelivered = true;\n return Promise.reject(failure);\n }\n if (closed) return Promise.resolve({ done: true, value: undefined });\n const demand = deferred<IteratorResult<T>>();\n demands.push(demand);\n start();\n wakeProducer();\n return demand.promise;\n },\n async return() {\n if (!closed) {\n closed = true;\n wakeProducer();\n activeDemand?.resolve({ done: true, value: undefined });\n activeDemand = undefined;\n finishPending();\n for (const cleanup of cleanups) await cleanup();\n }\n await task;\n return { done: true, value: undefined };\n },\n };\n}\n","import type {\n StandardJSONSchemaV1,\n StandardSchemaV1,\n} from \"@standard-schema/spec\";\n\nexport type Schema<TInput = unknown, TOutput = TInput> = {\n readonly \"~standard\":\n & StandardSchemaV1.Props<TInput, TOutput>\n & StandardJSONSchemaV1.Props<TInput, TOutput>;\n};\n\nexport type AnySchema = Schema<any, any>;\nexport type AnyObjectSchema = Schema<any, Record<string, unknown>>;\n\nexport type InferSchemaInput<TSchema extends AnySchema> =\n StandardSchemaV1.InferInput<TSchema>;\n\nexport type InferSchemaOutput<TSchema extends AnySchema> =\n StandardSchemaV1.InferOutput<TSchema>;\n\nexport async function parseSchema<TSchema extends AnySchema>(\n schema: TSchema,\n value: unknown,\n): Promise<InferSchemaOutput<TSchema>> {\n const result = await schema[\"~standard\"].validate(value);\n if (result.issues) {\n throw new SchemaValidationError(result.issues);\n }\n return result.value as InferSchemaOutput<TSchema>;\n}\n\nexport function schemaToJsonSchema(\n schema: AnySchema,\n direction: \"input\" | \"output\",\n): Readonly<Record<string, unknown>> {\n const projected = schema[\"~standard\"].jsonSchema[direction]({\n target: \"draft-2020-12\",\n });\n return JSON.parse(JSON.stringify(projected)) as Readonly<\n Record<string, unknown>\n >;\n}\n\nexport class SchemaValidationError extends Error {\n readonly issues: readonly StandardSchemaV1.Issue[];\n\n constructor(issues: readonly StandardSchemaV1.Issue[]) {\n super(\"Schema validation failed\");\n this.name = \"SchemaValidationError\";\n this.issues = issues;\n }\n}\n","import {\n defineErrors,\n errorDefinitions,\n CapableError,\n type AnyDefinedErrors,\n type DefinedErrors,\n type CapabilityErrorContract,\n} from \"./errors.ts\";\nimport {\n parseSchema,\n SchemaValidationError,\n type AnySchema,\n type AnyObjectSchema,\n type InferSchemaInput,\n type InferSchemaOutput,\n} from \"./schema.ts\";\nimport type { MaybePromise } from \"./projection.ts\";\nimport { createDemandIterator } from \"./subscription.ts\";\nimport type { LocatedCapability } from \"./application.ts\";\n\nexport const CAPABILITY_SYMBOL = Symbol.for(\"capable.capability\");\n\nexport interface CapabilityMetaRegistry {}\ntype OpenMeta<TRegistry> = Partial<TRegistry> & Readonly<Record<string, unknown>>;\n\nexport type CapabilityEffect = \"read\" | \"write\" | \"destructive\";\n\ntype EmptyInput = Record<never, never>;\ntype DefinedNoErrors = DefinedErrors<{}>;\nconst NO_ERRORS = defineErrors({});\n\ntype ParsedInput<TInput extends AnyObjectSchema | undefined> =\n TInput extends AnySchema ? InferSchemaOutput<TInput> : EmptyInput;\n\ntype HandlerInput<TInput extends AnyObjectSchema | undefined> =\n TInput extends AnySchema ? InferSchemaInput<TInput> : EmptyInput;\n\nexport type CapabilityHandlerArgs<TContext, TInput> = {\n readonly input: TInput;\n readonly context: TContext;\n readonly signal?: AbortSignal;\n};\n\nexport type CapabilitySubscriberArgs<TContext, TInput> = {\n readonly input: TInput;\n readonly context: TContext;\n readonly signal: AbortSignal;\n};\n\nexport type CapabilitySubscriber<TContext, TInput, TOutput> = (\n args: CapabilitySubscriberArgs<TContext, TInput>,\n) => AsyncIterable<TOutput>;\n\nexport type CapabilityMiddlewareArgs<TContext, TInput = unknown> = {\n readonly input: TInput;\n readonly context: TContext;\n readonly signal?: AbortSignal;\n next(): Promise<unknown>;\n};\n\nexport type CapabilityMiddleware<TContext, TInput = unknown> = (\n args: CapabilityMiddlewareArgs<TContext, TInput>,\n) => MaybePromise<unknown>;\n\nexport type MarkdownRenderer<TOutput, TContext> = (\n output: TOutput,\n options: { readonly context: TContext },\n) => MaybePromise<string>;\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 toMarkdown?: MarkdownRenderer<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 toMarkdown?: MarkdownRenderer<InferSchemaOutput<TOutput>, TContext>;\n readonly subscribe?: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n InferSchemaInput<TOutput>\n >;\n};\n\ntype InferredOutputCapabilityConfig<\n TContext,\n TInput extends AnyObjectSchema | undefined,\n THandler extends (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown,\n TErrors extends AnyDefinedErrors,\n TMeta extends OpenMeta<CapabilityMetaRegistry>,\n> = CapabilityBaseConfig<TContext, TInput, TErrors, TMeta> & {\n readonly output?: never;\n readonly handler: THandler;\n readonly toMarkdown?: MarkdownRenderer<Awaited<ReturnType<THandler>>, TContext>;\n readonly subscribe?: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n Awaited<ReturnType<THandler>>\n >;\n};\n\nexport type CapabilityFactory<TContext> = {\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n TOutput extends AnySchema = AnySchema,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: ExplicitOutputCapabilityConfig<\n TContext,\n TInput,\n TOutput,\n TErrors,\n TMeta\n > & {\n readonly subscribe: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n InferSchemaInput<TOutput>\n >;\n },\n ): CapabilityDefinition<\n TContext,\n TInput,\n InferSchemaOutput<TOutput>,\n TErrors,\n TMeta,\n true\n >;\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n TOutput extends AnySchema = AnySchema,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: ExplicitOutputCapabilityConfig<\n TContext,\n TInput,\n TOutput,\n TErrors,\n TMeta\n > & { readonly subscribe?: never },\n ): CapabilityDefinition<\n TContext,\n TInput,\n InferSchemaOutput<TOutput>,\n TErrors,\n TMeta,\n false\n >;\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n const THandler extends (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown = (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: InferredOutputCapabilityConfig<\n TContext,\n TInput,\n THandler,\n TErrors,\n TMeta\n > & {\n readonly subscribe: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n Awaited<ReturnType<THandler>>\n >;\n },\n ): CapabilityDefinition<\n TContext,\n TInput,\n Awaited<ReturnType<THandler>>,\n TErrors,\n TMeta,\n true\n >;\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n const THandler extends (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown = (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: InferredOutputCapabilityConfig<\n TContext,\n TInput,\n THandler,\n TErrors,\n TMeta\n > & { readonly subscribe?: never },\n ): CapabilityDefinition<\n TContext,\n TInput,\n Awaited<ReturnType<THandler>>,\n TErrors,\n TMeta,\n false\n >;\n};\n\ntype CapabilityFunction = CapabilityFactory<undefined> & {\n <TContext>(): CapabilityFactory<TContext>;\n withContext<TContext>(): CapabilityFactory<TContext>;\n};\n\nfunction capabilityWithContext<TContext>(): CapabilityFactory<TContext> {\n return createCapability as CapabilityFactory<TContext>;\n}\n\nexport const capability = Object.assign(\n function capability(\n config?:\n | ExplicitOutputCapabilityConfig<any, any, any, any, any>\n | InferredOutputCapabilityConfig<any, any, AnyHandler, any, any>,\n ): AnyCapability | CapabilityFactory<any> {\n return config === undefined\n ? createCapability as CapabilityFactory<any>\n : createCapability(config);\n },\n { withContext: capabilityWithContext },\n) as CapabilityFunction;\n\nfunction createCapability(\n config:\n | ExplicitOutputCapabilityConfig<any, any, any, any, any>\n | InferredOutputCapabilityConfig<any, any, AnyHandler, any, any>,\n): AnyCapability {\n if (!config.id) throw new Error(\"Capability id must not be empty\");\n if (config.subscribe && config.effect !== \"read\") {\n throw new Error(\n `Capability \"${config.id}\" must declare effect \"read\" to subscribe`,\n );\n }\n if (typeof config.handler !== \"function\") {\n throw new Error(`Capability \"${config.id}\" requires a handler`);\n }\n\n return Object.freeze({\n [CAPABILITY_SYMBOL]: true as const,\n id: config.id,\n ...(config.title ? { title: config.title } : {}),\n ...(config.description ? { description: config.description } : {}),\n deprecated: config.deprecated === true,\n ...(config.effect ? { effect: config.effect } : {}),\n ...(config.input ? { input: config.input } : {}),\n ...(config.output ? { output: config.output } : {}),\n errors: config.errors ?? NO_ERRORS,\n middleware: Object.freeze([...(config.middleware ?? [])]),\n meta: Object.freeze({ ...(config.meta ?? {}) }),\n handler: config.handler,\n ...(config.subscribe ? { subscribe: config.subscribe } : {}),\n ...(config.toMarkdown ? { toMarkdown: config.toMarkdown } : {}),\n });\n}\n\nexport async function executeCapability<\n const TCapability extends AnyCapability,\n>(\n capability: TCapability,\n options: ExecuteCapabilityOptions<TCapability>,\n): Promise<CapabilityOutput<TCapability>> {\n const located: LocatedCapability = Object.freeze({\n path: Object.freeze([]),\n groups: Object.freeze([]),\n groupPaths: Object.freeze([]),\n capability,\n errors: Object.freeze({ ...errorDefinitions(capability.errors) }),\n middleware: capability.middleware,\n });\n return executeLocatedCapability(\n located,\n options.input ?? {},\n {\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n },\n ) as Promise<CapabilityOutput<TCapability>>;\n}\n\nexport async function executeLocatedCapability(\n located: LocatedCapability,\n input: unknown,\n options: { readonly context: unknown; readonly signal?: AbortSignal },\n): Promise<unknown> {\n const parsedInput = await parseCapabilityInput(located.capability, input);\n let rawOutput: unknown;\n try {\n rawOutput = await runCapabilityMiddleware(\n located.middleware,\n {\n input: parsedInput,\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n },\n () => located.capability.handler({\n input: parsedInput,\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n }),\n );\n } catch (error) {\n throw await normalizeCapabilityError(located, error);\n }\n\n return validateCapabilityOutput(located.capability, rawOutput);\n}\n\nexport type SubscribeCapabilityOptions<\n TCapability extends SubscribableCapability,\n> = ExecuteCapabilityOptions<TCapability>;\n\nexport function subscribeCapability<\n const TCapability extends SubscribableCapability,\n>(\n capability: TCapability,\n options: SubscribeCapabilityOptions<TCapability>,\n): AsyncIterableIterator<CapabilityOutput<TCapability>> {\n const located: LocatedCapability = Object.freeze({\n path: Object.freeze([]),\n groups: Object.freeze([]),\n groupPaths: Object.freeze([]),\n capability,\n errors: Object.freeze({ ...errorDefinitions(capability.errors) }),\n middleware: capability.middleware,\n });\n return subscribeLocatedCapability(\n located,\n options.input ?? {},\n {\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n },\n ) as AsyncIterableIterator<CapabilityOutput<TCapability>>;\n}\n\nexport function subscribeLocatedCapability(\n located: LocatedCapability,\n input: unknown,\n options: { readonly context: unknown; readonly signal?: AbortSignal },\n): AsyncIterableIterator<unknown> {\n const subscriber = located.capability.subscribe;\n if (!subscriber) {\n throw new Error(`Capability \"${located.capability.id}\" is not subscribable`);\n }\n\n return createDemandIterator(async (stream) => {\n let cleanupSource = async (_abort: boolean) => {};\n let parsedInput: Record<string, unknown>;\n try {\n parsedInput = await parseCapabilityInput(located.capability, input);\n } catch (error) {\n stream.fail(error);\n return;\n }\n\n try {\n const controller = new AbortController();\n const signal = options.signal\n ? AbortSignal.any([controller.signal, options.signal])\n : controller.signal;\n let iterator: AsyncIterator<unknown> | undefined;\n let cleaned = false;\n cleanupSource = async (abort: boolean) => {\n if (cleaned) return;\n cleaned = true;\n if (abort) controller.abort();\n await iterator?.return?.();\n };\n stream.onCancel(() => cleanupSource(true));\n\n let emitted = false;\n await runCapabilityMiddleware(\n located.middleware,\n {\n input: parsedInput,\n context: options.context,\n signal,\n },\n async () => {\n const iterable = subscriber({\n input: parsedInput,\n context: options.context,\n signal,\n });\n if (\n !iterable ||\n typeof iterable !== \"object\" ||\n !(Symbol.asyncIterator in iterable)\n ) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Capability \"${located.capability.id}\" subscribe must return an AsyncIterable`,\n });\n }\n const sourceIterator = iterable[Symbol.asyncIterator]();\n iterator = sourceIterator;\n\n while (await stream.waitForDemand()) {\n const result = await sourceIterator.next();\n if (result.done) {\n if (!emitted) throw emptySubscriptionError(located.capability);\n return;\n }\n emitted = true;\n stream.emit(\n await validateCapabilityOutput(\n located.capability,\n result.value,\n ),\n );\n }\n },\n );\n if (!emitted) throw emptySubscriptionError(located.capability);\n await cleanupSource(false);\n stream.complete();\n } catch (error) {\n await cleanupSource(false);\n stream.fail(await normalizeCapabilityError(located, error));\n }\n });\n}\n\nfunction emptySubscriptionError(capability: AnyCapability): CapableError {\n return new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Capability \"${capability.id}\" subscription completed before yielding a value`,\n });\n}\n\nasync function validateCapabilityOutput(\n capability: AnyCapability,\n rawOutput: unknown,\n): Promise<unknown> {\n if (!capability.output) return rawOutput;\n try {\n return await parseSchema(capability.output, rawOutput);\n } catch (error) {\n if (!(error instanceof SchemaValidationError)) throw error;\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Capability \"${capability.id}\" output validation failed`,\n data: { issues: error.issues },\n cause: error,\n });\n }\n}\n\nasync function parseCapabilityInput(\n capability: AnyCapability,\n input: unknown,\n): Promise<Record<string, unknown>> {\n if (!capability.input) {\n if (input === undefined) return {};\n if (isRecord(input) && Object.keys(input).length === 0) return {};\n throw new CapableError(\"BAD_REQUEST\", {\n status: 400,\n message: `Capability \"${capability.id}\" does not accept input`,\n });\n }\n try {\n const parsed = await parseSchema(capability.input, input);\n if (!isRecord(parsed)) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Capability \"${capability.id}\" input schema must produce an object`,\n });\n }\n return parsed;\n } catch (error) {\n if (error instanceof CapableError) throw error;\n if (!(error instanceof SchemaValidationError)) throw error;\n throw new CapableError(\"BAD_REQUEST\", {\n status: 400,\n message: `Invalid input for Capability \"${capability.id}\"`,\n data: { issues: error.issues },\n cause: error,\n });\n }\n}\n\nasync function runCapabilityMiddleware(\n middleware: readonly CapabilityMiddleware<any>[],\n args: {\n readonly input: unknown;\n readonly context: unknown;\n readonly signal?: AbortSignal;\n },\n handler: () => MaybePromise<unknown>,\n): Promise<unknown> {\n async function dispatch(index: number): Promise<unknown> {\n const current = middleware[index];\n if (!current) return handler();\n let called = false;\n return current({\n ...args,\n next: async () => {\n if (called) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Capability middleware called next() more than once\",\n });\n }\n called = true;\n return dispatch(index + 1);\n },\n });\n }\n return dispatch(0);\n}\n\nasync function normalizeCapabilityError(\n located: LocatedCapability,\n error: unknown,\n): Promise<unknown> {\n if (!(error instanceof CapableError)) {\n return new CapableError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n }\n const contract = located.errors[error.code];\n if (!contract) {\n return new CapableError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n }\n\n let data = error.data;\n if (contract.data) {\n try {\n data = await parseSchema(contract.data, error.data);\n } catch (cause) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Invalid error data for ${error.code}`,\n cause,\n });\n }\n }\n return new CapableError(error.code, {\n ...(typeof contract.status === \"number\" ? { status: contract.status } : {}),\n message: contract.message ?? error.code,\n data,\n cause: error,\n });\n}\n\nexport function isCapability(value: unknown): value is AnyCapability {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n (value as Partial<AnyCapability>)[CAPABILITY_SYMBOL] === true,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n","import {\n defineErrors,\n errorDefinitions,\n type AnyDefinedErrors,\n type DefinedErrors,\n type CapabilityErrorContract,\n} from \"./errors.ts\";\nimport {\n isCapability,\n type AnyCapability,\n type CapabilityDefinition,\n type CapabilityMiddleware,\n} from \"./capability.ts\";\n\nexport const CAPABILITY_GROUP_SYMBOL = Symbol.for(\"capable.capability-group\");\nexport const APPLICATION_SYMBOL = Symbol.for(\"capable.application\");\n\nexport interface GroupMetaRegistry {}\ntype OpenMeta<TRegistry> = Partial<TRegistry> & Readonly<Record<string, unknown>>;\ntype DefinedNoErrors = DefinedErrors<{}>;\nconst NO_ERRORS = defineErrors({});\n\nexport interface CapabilityTree {\n readonly [key: string]:\n | AnyCapability\n | CapabilityTree\n | AnyCapabilityGroup;\n}\n\nexport type CapabilityGroupDefinition<\n TCapabilities extends CapabilityTree = CapabilityTree,\n TErrors extends AnyDefinedErrors = AnyDefinedErrors,\n TMeta extends OpenMeta<GroupMetaRegistry> = OpenMeta<GroupMetaRegistry>,\n> = {\n readonly [CAPABILITY_GROUP_SYMBOL]: true;\n readonly title?: string;\n readonly description?: string;\n readonly errors: TErrors;\n readonly middleware: readonly CapabilityMiddleware<any>[];\n readonly meta: TMeta;\n readonly capabilities: TCapabilities;\n};\n\nexport type AnyCapabilityGroup = {\n readonly [CAPABILITY_GROUP_SYMBOL]: true;\n readonly title?: string;\n readonly description?: string;\n readonly errors: AnyDefinedErrors;\n readonly middleware: readonly CapabilityMiddleware<any>[];\n readonly meta: OpenMeta<GroupMetaRegistry>;\n readonly capabilities: CapabilityTree;\n};\n\nexport function group<\n const TCapabilities extends CapabilityTree,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<GroupMetaRegistry> = {},\n>(config: {\n readonly title?: string;\n readonly description?: string;\n readonly errors?: TErrors;\n readonly middleware?: readonly CapabilityMiddleware<\n CapabilityTreeContext<TCapabilities>\n >[];\n readonly meta?: TMeta;\n readonly capabilities: TCapabilities;\n}): CapabilityGroupDefinition<TCapabilities, TErrors, TMeta> {\n assertCapabilityTree(config.capabilities, \"group.capabilities\");\n return Object.freeze({\n [CAPABILITY_GROUP_SYMBOL]: true as const,\n ...(config.title ? { title: config.title } : {}),\n ...(config.description ? { description: config.description } : {}),\n errors: (config.errors ?? NO_ERRORS) as TErrors,\n middleware: Object.freeze([...(config.middleware ?? [])]),\n meta: Object.freeze({ ...(config.meta ?? {}) }) as TMeta,\n capabilities: config.capabilities,\n });\n}\n\nexport type LocatedCapability = {\n readonly path: readonly string[];\n readonly groups: readonly AnyCapabilityGroup[];\n readonly groupPaths: readonly (readonly string[])[];\n readonly capability: AnyCapability;\n readonly errors: CapabilityErrorContract;\n readonly middleware: readonly CapabilityMiddleware<any>[];\n};\n\nexport type AppDefinition<\n TCapabilities extends CapabilityTree = CapabilityTree,\n TContext = unknown,\n> = {\n readonly [APPLICATION_SYMBOL]: true;\n readonly name: string;\n readonly version: string;\n readonly description?: string;\n readonly capabilities: TCapabilities;\n readonly locatedCapabilities: readonly LocatedCapability[];\n readonly \"~capable/context\"?: TContext;\n};\n\ntype CapabilityTreeContext<TTree> =\n TTree extends CapabilityDefinition<infer TContext, any, any, any, any>\n ? TContext\n : TTree extends CapabilityGroupDefinition<infer TCapabilities, any, any>\n ? CapabilityTreeContext<TCapabilities>\n : TTree extends Readonly<Record<string, unknown>>\n ? CapabilityTreeContext<TTree[keyof TTree]>\n : never;\n\ntype UnionToIntersection<TValue> =\n (TValue extends unknown ? (value: TValue) => void : never) extends\n (value: infer TIntersection) => void ? TIntersection : never;\n\nexport type AppContext<\n TDefinition extends AppDefinition<any, any>,\n> = TDefinition extends AppDefinition<any, infer TContext>\n ? TContext\n : never;\n\nexport function defineApp<\n const TCapabilities extends CapabilityTree,\n>(config: {\n readonly name?: string;\n readonly version?: string;\n readonly description?: string;\n readonly capabilities: TCapabilities;\n}): AppDefinition<\n TCapabilities,\n UnionToIntersection<CapabilityTreeContext<TCapabilities>>\n> {\n assertCapabilityTree(config.capabilities, \"application.capabilities\");\n const located = locateCapabilities(config.capabilities);\n assertUniqueCapabilities(located);\n\n return Object.freeze({\n [APPLICATION_SYMBOL]: true as const,\n name: config.name ?? \"Capable application\",\n version: config.version ?? \"0.0.0\",\n ...(config.description ? { description: config.description } : {}),\n capabilities: config.capabilities,\n locatedCapabilities: Object.freeze(located),\n });\n}\n\nfunction locateCapabilities(\n tree: CapabilityTree,\n path: readonly string[] = [],\n groups: readonly AnyCapabilityGroup[] = [],\n groupPaths: readonly (readonly string[])[] = [],\n inheritedErrors: CapabilityErrorContract = {},\n inheritedMiddleware: readonly CapabilityMiddleware<any>[] = [],\n): LocatedCapability[] {\n const located: LocatedCapability[] = [];\n for (const [key, value] of Object.entries(tree)) {\n const nextPath = [...path, key];\n if (isCapability(value)) {\n const capabilityErrors = errorDefinitions(value.errors);\n assertAdditionalErrors(\n inheritedErrors,\n capabilityErrors,\n `Capability \"${value.id}\"`,\n );\n located.push(Object.freeze({\n path: Object.freeze(nextPath),\n groups: Object.freeze([...groups]),\n groupPaths: Object.freeze([...groupPaths]),\n capability: value,\n errors: Object.freeze({ ...inheritedErrors, ...capabilityErrors }),\n middleware: Object.freeze([\n ...inheritedMiddleware,\n ...value.middleware,\n ]),\n }));\n continue;\n }\n if (isCapabilityGroup(value)) {\n const groupErrors = errorDefinitions(value.errors);\n assertAdditionalErrors(\n inheritedErrors,\n groupErrors,\n `Group at \"${nextPath.join(\".\")}\"`,\n );\n located.push(...locateCapabilities(\n value.capabilities,\n nextPath,\n [...groups, value],\n [...groupPaths, nextPath],\n { ...inheritedErrors, ...groupErrors },\n [\n ...inheritedMiddleware,\n ...(value.middleware as readonly CapabilityMiddleware<any>[]),\n ],\n ));\n continue;\n }\n located.push(...locateCapabilities(\n value,\n nextPath,\n groups,\n groupPaths,\n inheritedErrors,\n inheritedMiddleware,\n ));\n }\n return located;\n}\n\nfunction assertCapabilityTree(\n value: unknown,\n label: string,\n): asserts value is CapabilityTree {\n if (!isRecord(value)) {\n throw new Error(\n `${label} must be a named object tree; arrays are not supported`,\n );\n }\n for (const [key, child] of Object.entries(value)) {\n if (!key) throw new Error(`${label} has an empty key`);\n if (key === \"then\") {\n throw new Error(`${label} uses reserved key \"then\"`);\n }\n if (isCapability(child)) continue;\n if (isCapabilityGroup(child)) {\n assertCapabilityTree(child.capabilities, `${label}.${key}.capabilities`);\n continue;\n }\n assertCapabilityTree(child, `${label}.${key}`);\n }\n}\n\nfunction assertUniqueCapabilities(\n located: readonly LocatedCapability[],\n): void {\n const ids = new Map<string, string>();\n const objects = new Map<AnyCapability, string>();\n for (const entry of located) {\n const path = entry.path.join(\".\");\n const previousIdPath = ids.get(entry.capability.id);\n if (previousIdPath) {\n throw new Error(\n `Duplicate Capability id \"${entry.capability.id}\" at \"${previousIdPath}\" and \"${path}\"`,\n );\n }\n const previousObjectPath = objects.get(entry.capability);\n if (previousObjectPath) {\n throw new Error(\n `Capability \"${entry.capability.id}\" is included at both \"${previousObjectPath}\" and \"${path}\"`,\n );\n }\n ids.set(entry.capability.id, path);\n objects.set(entry.capability, path);\n }\n}\n\nfunction assertAdditionalErrors(\n inherited: CapabilityErrorContract,\n additional: CapabilityErrorContract,\n label: string,\n): void {\n const duplicate = Object.keys(additional).find((code) => code in inherited);\n if (duplicate) {\n throw new Error(`${label} redeclares inherited error ${duplicate}`);\n }\n}\n\nexport function isCapabilityGroup(\n value: unknown,\n): value is AnyCapabilityGroup {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n (value as Partial<AnyCapabilityGroup>)[CAPABILITY_GROUP_SYMBOL] === true,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n"],"mappings":";AAMA,MAAa,2BAA2B,OAAO,IAAI,2BAA2B;AAC9E,MAAa,sCAAsC,OAAO,IACxD,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,UAA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;GAC5B,qBAAqB,MAAM,cAAc,GAAG,MAAM,GAAG,IAAI,cAAc;GACvE;EACF;EACA,qBAAqB,OAAO,GAAG,MAAM,GAAG,KAAK;CAC/C;AACF;AAEA,SAAS,yBACP,SACM;CACN,MAAM,sBAAM,IAAI,IAAoB;CACpC,MAAM,0BAAU,IAAI,IAA2B;CAC/C,KAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,OAAO,MAAM,KAAK,KAAK,GAAG;EAChC,MAAM,iBAAiB,IAAI,IAAI,MAAM,WAAW,EAAE;EAClD,IAAI,gBACF,MAAM,IAAI,MACR,4BAA4B,MAAM,WAAW,GAAG,QAAQ,eAAe,SAAS,KAAK,EACvF;EAEF,MAAM,qBAAqB,QAAQ,IAAI,MAAM,UAAU;EACvD,IAAI,oBACF,MAAM,IAAI,MACR,eAAe,MAAM,WAAW,GAAG,yBAAyB,mBAAmB,SAAS,KAAK,EAC/F;EAEF,IAAI,IAAI,MAAM,WAAW,IAAI,IAAI;EACjC,QAAQ,IAAI,MAAM,YAAY,IAAI;CACpC;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
+ {"version":3,"file":"src-B53ZbNtC.mjs","names":["NO_ERRORS","isRecord"],"sources":["../../core/src/errors.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 WatchQueryOptions<TOutput> = {\n readonly snapshot: () => MaybePromise<TOutput>;\n readonly invalidations: () => AsyncIterable<unknown>;\n readonly signal?: AbortSignal;\n};\n\n/**\n * Turn an invalidation source into a stream of complete replacement snapshots.\n *\n * The invalidation iterator is pulled before the first snapshot is read. A\n * change racing with that read therefore causes another snapshot rather than\n * being missed.\n */\nexport async function* watchQuery<TOutput>(\n options: WatchQueryOptions<TOutput>,\n): AsyncIterableIterator<TOutput> {\n if (options.signal?.aborted) return;\n\n const iterator = options.invalidations()[Symbol.asyncIterator]();\n let pending = nextHandled(iterator);\n\n try {\n yield await options.snapshot();\n\n while (!options.signal?.aborted) {\n const result = await pending;\n if (result.done) return;\n pending = nextHandled(iterator);\n yield await options.snapshot();\n }\n } finally {\n await iterator.return?.();\n }\n}\n\nfunction nextHandled(iterator: AsyncIterator<unknown>) {\n const pending = iterator.next();\n void pending.catch(() => undefined);\n return pending;\n}\n\ntype Deferred<T> = {\n readonly promise: Promise<T>;\n resolve(value: T): void;\n reject(error: unknown): void;\n};\n\nfunction deferred<T>(): Deferred<T> {\n let resolve!: (value: T) => void;\n let reject!: (error: unknown) => void;\n const promise = new Promise<T>((onResolve, onReject) => {\n resolve = onResolve;\n reject = onReject;\n });\n return { promise, resolve, reject };\n}\n\nexport type DemandStream<T> = {\n waitForDemand(): Promise<boolean>;\n emit(value: T): void;\n complete(): void;\n fail(error: unknown): void;\n onCancel(cleanup: () => void | Promise<void>): void;\n};\n\nexport function createDemandIterator<T>(\n produce: (stream: DemandStream<T>) => Promise<void>,\n): AsyncIterableIterator<T> {\n const demands: Deferred<IteratorResult<T>>[] = [];\n const demandWaiters: Array<() => void> = [];\n const cleanups: Array<() => void | Promise<void>> = [];\n let activeDemand: Deferred<IteratorResult<T>> | undefined;\n let started = false;\n let closed = false;\n let failure: unknown;\n let hasFailure = false;\n let failureDelivered = false;\n let task: Promise<void> | undefined;\n\n const wakeProducer = () => demandWaiters.shift()?.();\n const finishPending = () => {\n for (const demand of demands.splice(0)) {\n if (hasFailure && !failureDelivered) {\n failureDelivered = true;\n demand.reject(failure);\n } else {\n demand.resolve({ done: true, value: undefined });\n }\n }\n };\n\n const stream: DemandStream<T> = {\n async waitForDemand() {\n while (!closed && demands.length === 0) {\n await new Promise<void>((resolve) => demandWaiters.push(resolve));\n }\n if (closed) return false;\n activeDemand = demands.shift();\n return Boolean(activeDemand);\n },\n emit(value) {\n const demand = activeDemand;\n activeDemand = undefined;\n demand?.resolve({ done: false, value });\n },\n complete() {\n closed = true;\n activeDemand?.resolve({ done: true, value: undefined });\n activeDemand = undefined;\n finishPending();\n wakeProducer();\n },\n fail(error) {\n failure = error;\n hasFailure = true;\n closed = true;\n const demand = activeDemand;\n activeDemand = undefined;\n if (demand) {\n failureDelivered = true;\n demand.reject(error);\n }\n finishPending();\n wakeProducer();\n },\n onCancel(cleanup) {\n cleanups.push(cleanup);\n },\n };\n\n const start = () => {\n if (started) return;\n started = true;\n task = produce(stream).then(\n () => {\n if (!closed) stream.complete();\n },\n (error) => stream.fail(error),\n );\n };\n\n return {\n [Symbol.asyncIterator]() {\n return this;\n },\n next() {\n if (hasFailure && !failureDelivered) {\n failureDelivered = true;\n return Promise.reject(failure);\n }\n if (closed) return Promise.resolve({ done: true, value: undefined });\n const demand = deferred<IteratorResult<T>>();\n demands.push(demand);\n start();\n wakeProducer();\n return demand.promise;\n },\n async return() {\n if (!closed) {\n closed = true;\n wakeProducer();\n activeDemand?.resolve({ done: true, value: undefined });\n activeDemand = undefined;\n finishPending();\n for (const cleanup of cleanups) await cleanup();\n }\n await task;\n return { done: true, value: undefined };\n },\n };\n}\n","import type {\n StandardJSONSchemaV1,\n StandardSchemaV1,\n} from \"@standard-schema/spec\";\n\nexport type Schema<TInput = unknown, TOutput = TInput> = {\n readonly \"~standard\":\n & StandardSchemaV1.Props<TInput, TOutput>\n & StandardJSONSchemaV1.Props<TInput, TOutput>;\n};\n\nexport type AnySchema = Schema<any, any>;\nexport type AnyObjectSchema = Schema<any, Record<string, unknown>>;\n\nexport type InferSchemaInput<TSchema extends AnySchema> =\n StandardSchemaV1.InferInput<TSchema>;\n\nexport type InferSchemaOutput<TSchema extends AnySchema> =\n StandardSchemaV1.InferOutput<TSchema>;\n\nexport async function parseSchema<TSchema extends AnySchema>(\n schema: TSchema,\n value: unknown,\n): Promise<InferSchemaOutput<TSchema>> {\n const result = await schema[\"~standard\"].validate(value);\n if (result.issues) {\n throw new SchemaValidationError(result.issues);\n }\n return result.value as InferSchemaOutput<TSchema>;\n}\n\nexport function schemaToJsonSchema(\n schema: AnySchema,\n direction: \"input\" | \"output\",\n): Readonly<Record<string, unknown>> {\n const projected = schema[\"~standard\"].jsonSchema[direction]({\n target: \"draft-2020-12\",\n });\n return JSON.parse(JSON.stringify(projected)) as Readonly<\n Record<string, unknown>\n >;\n}\n\nexport class SchemaValidationError extends Error {\n readonly issues: readonly StandardSchemaV1.Issue[];\n\n constructor(issues: readonly StandardSchemaV1.Issue[]) {\n super(\"Schema validation failed\");\n this.name = \"SchemaValidationError\";\n this.issues = issues;\n }\n}\n","import {\n defineErrors,\n errorDefinitions,\n CapableError,\n type AnyDefinedErrors,\n type DefinedErrors,\n type CapabilityErrorContract,\n} from \"./errors.ts\";\nimport {\n parseSchema,\n SchemaValidationError,\n type AnySchema,\n type AnyObjectSchema,\n type InferSchemaInput,\n type InferSchemaOutput,\n} from \"./schema.ts\";\nimport type { MaybePromise } from \"./projection.ts\";\nimport { createDemandIterator } from \"./subscription.ts\";\nimport type { LocatedCapability } from \"./application.ts\";\n\nexport const CAPABILITY_SYMBOL: unique symbol = Symbol.for(\n \"capable.capability\",\n) as never;\n\nexport interface CapabilityMetaRegistry {}\ntype OpenMeta<TRegistry> = Partial<TRegistry> & Readonly<Record<string, unknown>>;\n\nexport type CapabilityEffect = \"read\" | \"write\" | \"destructive\";\n\ntype EmptyInput = Record<never, never>;\ntype DefinedNoErrors = DefinedErrors<{}>;\nconst NO_ERRORS = defineErrors({});\n\ntype ParsedInput<TInput extends AnyObjectSchema | undefined> =\n TInput extends AnySchema ? InferSchemaOutput<TInput> : EmptyInput;\n\ntype HandlerInput<TInput extends AnyObjectSchema | undefined> =\n TInput extends AnySchema ? InferSchemaInput<TInput> : EmptyInput;\n\nexport type CapabilityHandlerArgs<TContext, TInput> = {\n readonly input: TInput;\n readonly context: TContext;\n readonly signal?: AbortSignal;\n};\n\nexport type CapabilitySubscriberArgs<TContext, TInput> = {\n readonly input: TInput;\n readonly context: TContext;\n readonly signal: AbortSignal;\n};\n\nexport type CapabilitySubscriber<TContext, TInput, TOutput> = (\n args: CapabilitySubscriberArgs<TContext, TInput>,\n) => AsyncIterable<TOutput>;\n\nexport type CapabilityMiddlewareArgs<TContext, TInput = unknown> = {\n readonly input: TInput;\n readonly context: TContext;\n readonly signal?: AbortSignal;\n next(): Promise<unknown>;\n};\n\nexport type CapabilityMiddleware<TContext, TInput = unknown> = (\n args: CapabilityMiddlewareArgs<TContext, TInput>,\n) => MaybePromise<unknown>;\n\nexport type MarkdownRenderer<TOutput, TContext> = (\n output: TOutput,\n options: { readonly context: TContext },\n) => MaybePromise<string>;\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 toMarkdown?: MarkdownRenderer<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 toMarkdown?: MarkdownRenderer<InferSchemaOutput<TOutput>, TContext>;\n readonly subscribe?: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n InferSchemaInput<TOutput>\n >;\n};\n\ntype InferredOutputCapabilityConfig<\n TContext,\n TInput extends AnyObjectSchema | undefined,\n THandler extends (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown,\n TErrors extends AnyDefinedErrors,\n TMeta extends OpenMeta<CapabilityMetaRegistry>,\n> = CapabilityBaseConfig<TContext, TInput, TErrors, TMeta> & {\n readonly output?: never;\n readonly handler: THandler;\n readonly toMarkdown?: MarkdownRenderer<Awaited<ReturnType<THandler>>, TContext>;\n readonly subscribe?: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n Awaited<ReturnType<THandler>>\n >;\n};\n\nexport type CapabilityFactory<TContext> = {\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n TOutput extends AnySchema = AnySchema,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: ExplicitOutputCapabilityConfig<\n TContext,\n TInput,\n TOutput,\n TErrors,\n TMeta\n > & {\n readonly subscribe: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n InferSchemaInput<TOutput>\n >;\n },\n ): CapabilityDefinition<\n TContext,\n TInput,\n InferSchemaOutput<TOutput>,\n TErrors,\n TMeta,\n true\n >;\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n TOutput extends AnySchema = AnySchema,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: ExplicitOutputCapabilityConfig<\n TContext,\n TInput,\n TOutput,\n TErrors,\n TMeta\n > & { readonly subscribe?: never },\n ): CapabilityDefinition<\n TContext,\n TInput,\n InferSchemaOutput<TOutput>,\n TErrors,\n TMeta,\n false\n >;\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n const THandler extends (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown = (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: InferredOutputCapabilityConfig<\n TContext,\n TInput,\n THandler,\n TErrors,\n TMeta\n > & {\n readonly subscribe: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n Awaited<ReturnType<THandler>>\n >;\n },\n ): CapabilityDefinition<\n TContext,\n TInput,\n Awaited<ReturnType<THandler>>,\n TErrors,\n TMeta,\n true\n >;\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n const THandler extends (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown = (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: InferredOutputCapabilityConfig<\n TContext,\n TInput,\n THandler,\n TErrors,\n TMeta\n > & { readonly subscribe?: never },\n ): CapabilityDefinition<\n TContext,\n TInput,\n Awaited<ReturnType<THandler>>,\n TErrors,\n TMeta,\n false\n >;\n};\n\ntype CapabilityFunction = CapabilityFactory<undefined> & {\n <TContext>(): CapabilityFactory<TContext>;\n withContext<TContext>(): CapabilityFactory<TContext>;\n};\n\nfunction capabilityWithContext<TContext>(): CapabilityFactory<TContext> {\n return createCapability as CapabilityFactory<TContext>;\n}\n\nexport const capability = Object.assign(\n function capability(\n config?:\n | ExplicitOutputCapabilityConfig<any, any, any, any, any>\n | InferredOutputCapabilityConfig<any, any, AnyHandler, any, any>,\n ): AnyCapability | CapabilityFactory<any> {\n return config === undefined\n ? createCapability as CapabilityFactory<any>\n : createCapability(config);\n },\n { withContext: capabilityWithContext },\n) as CapabilityFunction;\n\nfunction createCapability(\n config:\n | ExplicitOutputCapabilityConfig<any, any, any, any, any>\n | InferredOutputCapabilityConfig<any, any, AnyHandler, any, any>,\n): AnyCapability {\n if (!config.id) throw new Error(\"Capability id must not be empty\");\n if (config.subscribe && config.effect !== \"read\") {\n throw new Error(\n `Capability \"${config.id}\" must declare effect \"read\" to subscribe`,\n );\n }\n if (typeof config.handler !== \"function\") {\n throw new Error(`Capability \"${config.id}\" requires a handler`);\n }\n\n return Object.freeze({\n [CAPABILITY_SYMBOL]: true as const,\n id: config.id,\n ...(config.title ? { title: config.title } : {}),\n ...(config.description ? { description: config.description } : {}),\n deprecated: config.deprecated === true,\n ...(config.effect ? { effect: config.effect } : {}),\n ...(config.input ? { input: config.input } : {}),\n ...(config.output ? { output: config.output } : {}),\n errors: config.errors ?? NO_ERRORS,\n middleware: Object.freeze([...(config.middleware ?? [])]),\n meta: Object.freeze({ ...(config.meta ?? {}) }),\n handler: config.handler,\n ...(config.subscribe ? { subscribe: config.subscribe } : {}),\n ...(config.toMarkdown ? { toMarkdown: config.toMarkdown } : {}),\n });\n}\n\nexport async function executeCapability<\n const TCapability extends AnyCapability,\n>(\n capability: TCapability,\n options: ExecuteCapabilityOptions<TCapability>,\n): Promise<CapabilityOutput<TCapability>> {\n const located: LocatedCapability = Object.freeze({\n path: Object.freeze([]),\n groups: Object.freeze([]),\n groupPaths: Object.freeze([]),\n capability,\n errors: Object.freeze({ ...errorDefinitions(capability.errors) }),\n middleware: capability.middleware,\n });\n return executeLocatedCapability(\n located,\n options.input ?? {},\n {\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n },\n ) as Promise<CapabilityOutput<TCapability>>;\n}\n\nexport async function executeLocatedCapability(\n located: LocatedCapability,\n input: unknown,\n options: { readonly context: unknown; readonly signal?: AbortSignal },\n): Promise<unknown> {\n const parsedInput = await parseCapabilityInput(located.capability, input);\n let rawOutput: unknown;\n try {\n rawOutput = await runCapabilityMiddleware(\n located.middleware,\n {\n input: parsedInput,\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n },\n () => located.capability.handler({\n input: parsedInput,\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n }),\n );\n } catch (error) {\n throw await normalizeCapabilityError(located, error);\n }\n\n return validateCapabilityOutput(located.capability, rawOutput);\n}\n\nexport type SubscribeCapabilityOptions<\n TCapability extends SubscribableCapability,\n> = ExecuteCapabilityOptions<TCapability>;\n\nexport function subscribeCapability<\n const TCapability extends SubscribableCapability,\n>(\n capability: TCapability,\n options: SubscribeCapabilityOptions<TCapability>,\n): AsyncIterableIterator<CapabilityOutput<TCapability>> {\n const located: LocatedCapability = Object.freeze({\n path: Object.freeze([]),\n groups: Object.freeze([]),\n groupPaths: Object.freeze([]),\n capability,\n errors: Object.freeze({ ...errorDefinitions(capability.errors) }),\n middleware: capability.middleware,\n });\n return subscribeLocatedCapability(\n located,\n options.input ?? {},\n {\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n },\n ) as AsyncIterableIterator<CapabilityOutput<TCapability>>;\n}\n\nexport function subscribeLocatedCapability(\n located: LocatedCapability,\n input: unknown,\n options: { readonly context: unknown; readonly signal?: AbortSignal },\n): AsyncIterableIterator<unknown> {\n const subscriber = located.capability.subscribe;\n if (!subscriber) {\n throw new Error(`Capability \"${located.capability.id}\" is not subscribable`);\n }\n\n return createDemandIterator(async (stream) => {\n let cleanupSource = async (_abort: boolean) => {};\n let parsedInput: Record<string, unknown>;\n try {\n parsedInput = await parseCapabilityInput(located.capability, input);\n } catch (error) {\n stream.fail(error);\n return;\n }\n\n try {\n const controller = new AbortController();\n const signal = options.signal\n ? AbortSignal.any([controller.signal, options.signal])\n : controller.signal;\n let iterator: AsyncIterator<unknown> | undefined;\n let cleaned = false;\n cleanupSource = async (abort: boolean) => {\n if (cleaned) return;\n cleaned = true;\n if (abort) controller.abort();\n await iterator?.return?.();\n };\n stream.onCancel(() => cleanupSource(true));\n\n let emitted = false;\n await runCapabilityMiddleware(\n located.middleware,\n {\n input: parsedInput,\n context: options.context,\n signal,\n },\n async () => {\n const iterable = subscriber({\n input: parsedInput,\n context: options.context,\n signal,\n });\n if (\n !iterable ||\n typeof iterable !== \"object\" ||\n !(Symbol.asyncIterator in iterable)\n ) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Capability \"${located.capability.id}\" subscribe must return an AsyncIterable`,\n });\n }\n const sourceIterator = iterable[Symbol.asyncIterator]();\n iterator = sourceIterator;\n\n while (await stream.waitForDemand()) {\n const result = await sourceIterator.next();\n if (result.done) {\n if (!emitted) throw emptySubscriptionError(located.capability);\n return;\n }\n emitted = true;\n stream.emit(\n await validateCapabilityOutput(\n located.capability,\n result.value,\n ),\n );\n }\n },\n );\n if (!emitted) throw emptySubscriptionError(located.capability);\n await cleanupSource(false);\n stream.complete();\n } catch (error) {\n await cleanupSource(false);\n stream.fail(await normalizeCapabilityError(located, error));\n }\n });\n}\n\nfunction emptySubscriptionError(capability: AnyCapability): CapableError {\n return new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Capability \"${capability.id}\" subscription completed before yielding a value`,\n });\n}\n\nasync function validateCapabilityOutput(\n capability: AnyCapability,\n rawOutput: unknown,\n): Promise<unknown> {\n if (!capability.output) return rawOutput;\n try {\n return await parseSchema(capability.output, rawOutput);\n } catch (error) {\n if (!(error instanceof SchemaValidationError)) throw error;\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Capability \"${capability.id}\" output validation failed`,\n data: { issues: error.issues },\n cause: error,\n });\n }\n}\n\nasync function parseCapabilityInput(\n capability: AnyCapability,\n input: unknown,\n): Promise<Record<string, unknown>> {\n if (!capability.input) {\n if (input === undefined) return {};\n if (isRecord(input) && Object.keys(input).length === 0) return {};\n throw new CapableError(\"BAD_REQUEST\", {\n status: 400,\n message: `Capability \"${capability.id}\" does not accept input`,\n });\n }\n try {\n const parsed = await parseSchema(capability.input, input);\n if (!isRecord(parsed)) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Capability \"${capability.id}\" input schema must produce an object`,\n });\n }\n return parsed;\n } catch (error) {\n if (error instanceof CapableError) throw error;\n if (!(error instanceof SchemaValidationError)) throw error;\n throw new CapableError(\"BAD_REQUEST\", {\n status: 400,\n message: `Invalid input for Capability \"${capability.id}\"`,\n data: { issues: error.issues },\n cause: error,\n });\n }\n}\n\nasync function runCapabilityMiddleware(\n middleware: readonly CapabilityMiddleware<any>[],\n args: {\n readonly input: unknown;\n readonly context: unknown;\n readonly signal?: AbortSignal;\n },\n handler: () => MaybePromise<unknown>,\n): Promise<unknown> {\n async function dispatch(index: number): Promise<unknown> {\n const current = middleware[index];\n if (!current) return handler();\n let called = false;\n return current({\n ...args,\n next: async () => {\n if (called) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Capability middleware called next() more than once\",\n });\n }\n called = true;\n return dispatch(index + 1);\n },\n });\n }\n return dispatch(0);\n}\n\nasync function normalizeCapabilityError(\n located: LocatedCapability,\n error: unknown,\n): Promise<unknown> {\n if (!(error instanceof CapableError)) {\n return new CapableError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n }\n const contract = located.errors[error.code];\n if (!contract) {\n return new CapableError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n }\n\n let data = error.data;\n if (contract.data) {\n try {\n data = await parseSchema(contract.data, error.data);\n } catch (cause) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Invalid error data for ${error.code}`,\n cause,\n });\n }\n }\n return new CapableError(error.code, {\n ...(typeof contract.status === \"number\" ? { status: contract.status } : {}),\n message: contract.message ?? error.code,\n data,\n cause: error,\n });\n}\n\nexport function isCapability(value: unknown): value is AnyCapability {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n (value as Partial<AnyCapability>)[CAPABILITY_SYMBOL] === true,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n","import {\n defineErrors,\n errorDefinitions,\n type AnyDefinedErrors,\n type DefinedErrors,\n type CapabilityErrorContract,\n} from \"./errors.ts\";\nimport {\n isCapability,\n type AnyCapability,\n type CapabilityDefinition,\n type CapabilityMiddleware,\n} from \"./capability.ts\";\n\nexport const CAPABILITY_GROUP_SYMBOL: unique symbol = Symbol.for(\n \"capable.capability-group\",\n) as never;\nexport const APPLICATION_SYMBOL: unique symbol = Symbol.for(\n \"capable.application\",\n) as never;\n\nexport interface GroupMetaRegistry {}\ntype OpenMeta<TRegistry> = Partial<TRegistry> & Readonly<Record<string, unknown>>;\ntype DefinedNoErrors = DefinedErrors<{}>;\nconst NO_ERRORS = defineErrors({});\n\nexport interface CapabilityTree {\n readonly [key: string]:\n | AnyCapability\n | CapabilityTree\n | AnyCapabilityGroup;\n}\n\nexport type CapabilityGroupDefinition<\n TCapabilities extends CapabilityTree = CapabilityTree,\n TErrors extends AnyDefinedErrors = AnyDefinedErrors,\n TMeta extends OpenMeta<GroupMetaRegistry> = OpenMeta<GroupMetaRegistry>,\n> = {\n readonly [CAPABILITY_GROUP_SYMBOL]: true;\n readonly title?: string;\n readonly description?: string;\n readonly errors: TErrors;\n readonly middleware: readonly CapabilityMiddleware<any>[];\n readonly meta: TMeta;\n readonly capabilities: TCapabilities;\n};\n\nexport type AnyCapabilityGroup = {\n readonly [CAPABILITY_GROUP_SYMBOL]: true;\n readonly title?: string;\n readonly description?: string;\n readonly errors: AnyDefinedErrors;\n readonly middleware: readonly CapabilityMiddleware<any>[];\n readonly meta: OpenMeta<GroupMetaRegistry>;\n readonly capabilities: CapabilityTree;\n};\n\nexport function group<\n const TCapabilities extends CapabilityTree,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<GroupMetaRegistry> = {},\n>(config: {\n readonly title?: string;\n readonly description?: string;\n readonly errors?: TErrors;\n readonly middleware?: readonly CapabilityMiddleware<\n CapabilityTreeContext<TCapabilities>\n >[];\n readonly meta?: TMeta;\n readonly capabilities: TCapabilities;\n}): CapabilityGroupDefinition<TCapabilities, TErrors, TMeta> {\n assertCapabilityTree(config.capabilities, \"group.capabilities\");\n return Object.freeze({\n [CAPABILITY_GROUP_SYMBOL]: true as const,\n ...(config.title ? { title: config.title } : {}),\n ...(config.description ? { description: config.description } : {}),\n errors: (config.errors ?? NO_ERRORS) as TErrors,\n middleware: Object.freeze([...(config.middleware ?? [])]),\n meta: Object.freeze({ ...(config.meta ?? {}) }) as TMeta,\n capabilities: config.capabilities,\n });\n}\n\nexport type LocatedCapability = {\n readonly path: readonly string[];\n readonly groups: readonly AnyCapabilityGroup[];\n readonly groupPaths: readonly (readonly string[])[];\n readonly capability: AnyCapability;\n readonly errors: CapabilityErrorContract;\n readonly middleware: readonly CapabilityMiddleware<any>[];\n};\n\nexport type AppDefinition<\n TCapabilities extends CapabilityTree = CapabilityTree,\n TContext = unknown,\n> = {\n readonly [APPLICATION_SYMBOL]: true;\n readonly name: string;\n readonly version: string;\n readonly description?: string;\n readonly capabilities: TCapabilities;\n readonly locatedCapabilities: readonly LocatedCapability[];\n readonly \"~capable/context\"?: TContext;\n};\n\ntype CapabilityTreeContext<TTree> =\n TTree extends CapabilityDefinition<infer TContext, any, any, any, any>\n ? TContext\n : TTree extends CapabilityGroupDefinition<infer TCapabilities, any, any>\n ? CapabilityTreeContext<TCapabilities>\n : TTree extends Readonly<Record<string, unknown>>\n ? CapabilityTreeContext<TTree[keyof TTree]>\n : never;\n\ntype UnionToIntersection<TValue> =\n (TValue extends unknown ? (value: TValue) => void : never) extends\n (value: infer TIntersection) => void ? TIntersection : never;\n\nexport type AppContext<\n TDefinition extends AppDefinition<any, any>,\n> = TDefinition extends AppDefinition<any, infer TContext>\n ? TContext\n : never;\n\nexport function defineApp<\n const TCapabilities extends CapabilityTree,\n>(config: {\n readonly name?: string;\n readonly version?: string;\n readonly description?: string;\n readonly capabilities: TCapabilities;\n}): AppDefinition<\n TCapabilities,\n UnionToIntersection<CapabilityTreeContext<TCapabilities>>\n> {\n assertCapabilityTree(config.capabilities, \"application.capabilities\");\n const located = locateCapabilities(config.capabilities);\n assertUniqueCapabilities(located);\n\n return Object.freeze({\n [APPLICATION_SYMBOL]: true as const,\n name: config.name ?? \"Capable application\",\n version: config.version ?? \"0.0.0\",\n ...(config.description ? { description: config.description } : {}),\n capabilities: config.capabilities,\n locatedCapabilities: Object.freeze(located),\n });\n}\n\nfunction locateCapabilities(\n tree: CapabilityTree,\n path: readonly string[] = [],\n groups: readonly AnyCapabilityGroup[] = [],\n groupPaths: readonly (readonly string[])[] = [],\n inheritedErrors: CapabilityErrorContract = {},\n inheritedMiddleware: readonly CapabilityMiddleware<any>[] = [],\n): LocatedCapability[] {\n const located: LocatedCapability[] = [];\n for (const [key, value] of Object.entries(tree)) {\n const nextPath = [...path, key];\n if (isCapability(value)) {\n const capabilityErrors = errorDefinitions(value.errors);\n assertAdditionalErrors(\n inheritedErrors,\n capabilityErrors,\n `Capability \"${value.id}\"`,\n );\n located.push(Object.freeze({\n path: Object.freeze(nextPath),\n groups: Object.freeze([...groups]),\n groupPaths: Object.freeze([...groupPaths]),\n capability: value,\n errors: Object.freeze({ ...inheritedErrors, ...capabilityErrors }),\n middleware: Object.freeze([\n ...inheritedMiddleware,\n ...value.middleware,\n ]),\n }));\n continue;\n }\n if (isCapabilityGroup(value)) {\n const groupErrors = errorDefinitions(value.errors);\n assertAdditionalErrors(\n inheritedErrors,\n groupErrors,\n `Group at \"${nextPath.join(\".\")}\"`,\n );\n located.push(...locateCapabilities(\n value.capabilities,\n nextPath,\n [...groups, value],\n [...groupPaths, nextPath],\n { ...inheritedErrors, ...groupErrors },\n [\n ...inheritedMiddleware,\n ...(value.middleware as readonly CapabilityMiddleware<any>[]),\n ],\n ));\n continue;\n }\n located.push(...locateCapabilities(\n value,\n nextPath,\n groups,\n groupPaths,\n inheritedErrors,\n inheritedMiddleware,\n ));\n }\n return located;\n}\n\nfunction assertCapabilityTree(\n value: unknown,\n label: string,\n): asserts value is CapabilityTree {\n if (!isRecord(value)) {\n throw new Error(\n `${label} must be a named object tree; arrays are not supported`,\n );\n }\n for (const [key, child] of Object.entries(value)) {\n if (!key) throw new Error(`${label} has an empty key`);\n if (key === \"then\") {\n throw new Error(`${label} uses reserved key \"then\"`);\n }\n if (isCapability(child)) continue;\n if (isCapabilityGroup(child)) {\n assertCapabilityTree(child.capabilities, `${label}.${key}.capabilities`);\n continue;\n }\n assertCapabilityTree(child, `${label}.${key}`);\n }\n}\n\nfunction assertUniqueCapabilities(\n located: readonly LocatedCapability[],\n): void {\n const ids = new Map<string, string>();\n const objects = new Map<AnyCapability, string>();\n for (const entry of located) {\n const path = entry.path.join(\".\");\n const previousIdPath = ids.get(entry.capability.id);\n if (previousIdPath) {\n throw new Error(\n `Duplicate Capability id \"${entry.capability.id}\" at \"${previousIdPath}\" and \"${path}\"`,\n );\n }\n const previousObjectPath = objects.get(entry.capability);\n if (previousObjectPath) {\n throw new Error(\n `Capability \"${entry.capability.id}\" is included at both \"${previousObjectPath}\" and \"${path}\"`,\n );\n }\n ids.set(entry.capability.id, path);\n objects.set(entry.capability, path);\n }\n}\n\nfunction assertAdditionalErrors(\n inherited: CapabilityErrorContract,\n additional: CapabilityErrorContract,\n label: string,\n): void {\n const duplicate = Object.keys(additional).find((code) => code in inherited);\n if (duplicate) {\n throw new Error(`${label} redeclares inherited error ${duplicate}`);\n }\n}\n\nexport function isCapabilityGroup(\n value: unknown,\n): value is AnyCapabilityGroup {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n (value as Partial<AnyCapabilityGroup>)[CAPABILITY_GROUP_SYMBOL] === true,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n"],"mappings":";AAMA,MAAa,2BAA0C,OAAO,IAC5D,2BACF;AACA,MAAa,sCAAqD,OAAO,IACvE,sCACF;AAsBA,IAAa,eAAb,cAGU,MAAM;CACd;CACA;CACA;CAEA,YACE,MACA,UAKI,CAAC,GACL;EACA,MAAM,QAAQ,WAAW,MAAM,EAAE,OAAO,QAAQ,MAAM,CAAC;EACvD,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS,QAAQ;EACtB,KAAK,OAAO,QAAQ;CACtB;AACF;AA0DA,SAAgB,aAEd,aAAwD;CACxD,MAAM,oBAAoB,OAAO,OAAO,EAAE,GAAG,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,GAAI,OAAO,WAAW,WAAW,WAC7B,EAAE,QAAQ,WAAW,OAAO,IAC5B,CAAC;IACL,GAAI,UAAU,EAAE,KAAK,IAAI,CAAC;IAC1B,GAAI,WACA,OAAO,YAAY,YACnB,WAAW,UACX,EAAE,OAAO,QAAQ,MAAM,IACvB,CAAC;GACP,CAAC;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AAM,KAAK,KAAK,GAAG;EAChC,MAAM,iBAAiB,IAAI,IAAI,MAAM,WAAW,EAAE;EAClD,IAAI,gBACF,MAAM,IAAI,MACR,4BAA4B,MAAM,WAAW,GAAG,QAAQ,eAAe,SAAS,KAAK,EACvF;EAEF,MAAM,qBAAqB,QAAQ,IAAI,MAAM,UAAU;EACvD,IAAI,oBACF,MAAM,IAAI,MACR,eAAe,MAAM,WAAW,GAAG,yBAAyB,mBAAmB,SAAS,KAAK,EAC/F;EAEF,IAAI,IAAI,MAAM,WAAW,IAAI,IAAI;EACjC,QAAQ,IAAI,MAAM,YAAY,IAAI;CACpC;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 +1 @@
1
- {"version":3,"file":"src-BjBxOv7x.mjs","names":["kebabCase","renderMarkdown"],"sources":["../../cli/src/commands.ts","../../cli/src/style.ts","../../cli/src/help.ts","../../cli/src/index.ts"],"sourcesContent":["import type {\n ManifestGroup,\n ManifestNode,\n ManifestCapability,\n} from \"@capable/app\";\nimport type {\n CliGroupMeta,\n CliCapabilityMeta,\n} from \"./index.ts\";\n\nexport type CliCommand = {\n readonly command: readonly string[];\n readonly capability: ManifestCapability;\n readonly meta: Exclude<CliCapabilityMeta, false>;\n};\n\nexport type CliCommandGroup = {\n readonly command: readonly string[];\n readonly title?: string;\n readonly description?: string;\n};\n\nexport type CliCommandCatalog = {\n readonly commands: readonly CliCommand[];\n readonly groups: readonly CliCommandGroup[];\n};\n\nexport function collectCommands(\n nodes: readonly ManifestNode[],\n parent: readonly string[] = [],\n): CliCommandCatalog {\n const commands: CliCommand[] = [];\n const groups: CliCommandGroup[] = [];\n\n for (const node of nodes) {\n if (node.type === \"group\") {\n const meta = (node.meta.cli ?? {}) as CliGroupMeta;\n const command = [...parent, meta.name ?? node.key];\n groups.push(groupFrom(node, command));\n const children = collectCommands(node.children, command);\n commands.push(...children.commands);\n groups.push(...children.groups);\n continue;\n }\n\n const rawMeta = node.meta.cli as CliCapabilityMeta | undefined;\n if (rawMeta === false) continue;\n const meta = rawMeta ?? {};\n commands.push({\n command: meta.command ?? [...parent, meta.name ?? node.path.at(-1)!],\n capability: node,\n meta,\n });\n }\n\n return {\n commands: Object.freeze(commands),\n groups: Object.freeze(groups),\n };\n}\n\nfunction groupFrom(\n node: ManifestGroup,\n command: readonly string[],\n): CliCommandGroup {\n return Object.freeze({\n command: Object.freeze(command),\n ...(node.title ? { title: node.title } : {}),\n ...(node.description ? { description: node.description } : {}),\n });\n}\n","export type CliStyle = {\n readonly bold: (text: string) => string;\n readonly accent: (text: string) => string;\n readonly dim: (text: string) => string;\n};\n\nexport type CliRow = {\n readonly label: string;\n readonly description?: string;\n};\n\n/** Every help line hangs off this margin. */\nexport const MARGIN = \" \";\n\n/** Rows sit one step inside their section heading. */\nexport const ROW_INDENT = \" \";\n\n/** Widest label that still keeps descriptions in a single column. */\nconst MAX_LABEL_WIDTH = 30;\n\nconst LABEL_GAP = 2;\n\nexport function createCliStyle(color?: boolean): CliStyle {\n const enabled = color ?? supportsColor();\n return {\n bold: enabled ? (text) => `\\u001B[1m${text}\\u001B[22m` : identity,\n accent: enabled ? (text) => `\\u001B[36m${text}\\u001B[39m` : identity,\n dim: enabled ? (text) => `\\u001B[2m${text}\\u001B[22m` : identity,\n };\n}\n\nexport function supportsColor(\n env: Record<string, string | undefined> = process.env,\n isTTY = Boolean(process.stdout.isTTY),\n): boolean {\n if (\"NO_COLOR\" in env) return false;\n if (env.FORCE_COLOR !== undefined) return env.FORCE_COLOR !== \"0\";\n return isTTY && env.TERM !== \"dumb\";\n}\n\nexport function renderRows(\n rows: readonly CliRow[],\n style: CliStyle,\n options: {\n readonly indent?: string;\n /** Absolute column for descriptions, so sibling sections stay aligned. */\n readonly column?: number;\n } = {},\n): string {\n const indent = options.indent ?? ROW_INDENT;\n const width = Math.max(\n 0,\n (options.column ?? descriptionColumn(rows, indent)) - indent.length -\n LABEL_GAP,\n );\n return rows.map(({ label, description }) => {\n const line = `${indent}${style.accent(label)}`;\n if (!description) return line;\n return label.length > width\n ? `${line}\\n${indent}${\" \".repeat(width + LABEL_GAP)}${style.dim(description)}`\n : `${line}${\" \".repeat(width - label.length + LABEL_GAP)}${\n style.dim(description)\n }`;\n }).join(\"\\n\");\n}\n\n/** Shared description column so sibling sections stay visually aligned. */\nexport function descriptionColumn(\n rows: readonly CliRow[],\n indent: string = ROW_INDENT,\n): number {\n const labels = rows\n .filter(({ description }) => description !== undefined)\n .map(({ label }) => label.length)\n .filter((length) => length <= MAX_LABEL_WIDTH);\n return indent.length + LABEL_GAP + Math.max(0, ...labels);\n}\n\nexport function renderSection(\n title: string,\n body: string,\n style: CliStyle,\n): string {\n return `${MARGIN}${style.bold(title)}\\n\\n${body}`;\n}\n\nfunction identity(text: string): string {\n return text;\n}\n","import type {\n ApplicationManifest,\n JsonSchema,\n} from \"@capable/app\";\nimport type {\n CliCommand,\n CliCommandGroup,\n} from \"./commands.ts\";\nimport {\n descriptionColumn,\n MARGIN,\n renderRows,\n renderSection,\n ROW_INDENT,\n type CliRow,\n type CliStyle,\n} from \"./style.ts\";\n\nconst GLOBAL_OPTIONS: readonly CliRow[] = [\n { label: \"--json\", description: \"Print canonical JSON\" },\n { label: \"-h, --help\", description: \"Show help\" },\n];\n\nexport function renderRootHelp(\n manifest: Pick<ApplicationManifest, \"name\" | \"description\">,\n commands: readonly CliCommand[],\n groups: readonly CliCommandGroup[],\n invocationName: string,\n style: CliStyle,\n): string {\n const sections = commandSections(commands, groups);\n const nested = sections.some((section) => section.title !== undefined);\n const column = Math.max(\n descriptionColumn(\n sections.flatMap((section) => section.rows),\n nested ? `${ROW_INDENT}${MARGIN}` : ROW_INDENT,\n ),\n descriptionColumn(GLOBAL_OPTIONS),\n );\n return renderHelp([\n banner({\n title: manifest.name,\n ...(manifest.description ? { description: manifest.description } : {}),\n usage: `${invocationName} <command> [options]`,\n style,\n }),\n renderSection(\n \"Commands\",\n sections\n .map((section) =>\n [\n section.title ? `${ROW_INDENT}${style.dim(section.title)}` : undefined,\n renderRows(section.rows, style, {\n column,\n ...(section.title ? { indent: `${ROW_INDENT}${MARGIN}` } : {}),\n }),\n ].filter(Boolean).join(\"\\n\")\n )\n .join(\"\\n\\n\"),\n style,\n ),\n renderSection(\"Options\", renderRows(GLOBAL_OPTIONS, style, { column }), style),\n hint(`Run \\`${invocationName} <command> --help\\` for details on a command.`, style),\n ]);\n}\n\nexport function renderGroupHelp(\n group: CliCommandGroup,\n commands: readonly CliCommand[],\n invocationName: string,\n style: CliStyle,\n): string {\n const prefix = group.command.join(\" \");\n const rows = commands\n .filter((candidate) => startsWith(candidate.command, group.command))\n .map((candidate) => ({\n label: signature(candidate, candidate.command.slice(group.command.length)),\n ...describe(candidate),\n }));\n const column = descriptionColumn([...rows, ...GLOBAL_OPTIONS]);\n return renderHelp([\n banner({\n ...(group.title ? { title: group.title } : {}),\n ...(group.description ? { description: group.description } : {}),\n usage: `${invocationName} ${prefix} <command> [options]`,\n style,\n }),\n renderSection(\"Commands\", renderRows(rows, style, { column }), style),\n renderSection(\"Options\", renderRows(GLOBAL_OPTIONS, style, { column }), style),\n hint(\n `Run \\`${invocationName} ${prefix} <command> --help\\` for details on a command.`,\n style,\n ),\n ]);\n}\n\nexport function renderCommandHelp(\n command: CliCommand,\n invocationName: string,\n style: CliStyle,\n): string {\n const properties = fields(command);\n const required = requiredFields(command);\n const positionals = command.meta.positional ?? [];\n const argumentRows = positionals.map((name) => ({\n label: placeholder(name, required.has(name)),\n ...description(properties[name], { choices: true }),\n }));\n const optionRows = [\n ...Object.entries(properties)\n .filter(([name]) => !positionals.includes(name))\n .map(([name, schema]) => ({\n label: optionLabel(name, schema),\n ...description(schema, { required: required.has(name) }),\n })),\n ...(command.capability.subscription\n ? [{ label: \"--watch\", description: \"Stream updates until interrupted\" }]\n : []),\n ];\n const column = descriptionColumn([\n ...argumentRows,\n ...optionRows,\n ...GLOBAL_OPTIONS,\n ]);\n\n return renderHelp([\n banner({\n ...(command.capability.title ? { title: command.capability.title } : {}),\n ...(command.capability.description\n ? { description: command.capability.description }\n : {}),\n usage: [invocationName, signature(command), \"[options]\"].join(\" \"),\n style,\n }),\n argumentRows.length\n ? renderSection(\n \"Arguments\",\n renderRows(argumentRows, style, { column }),\n style,\n )\n : undefined,\n optionRows.length\n ? renderSection(\"Options\", renderRows(optionRows, style, { column }), style)\n : undefined,\n renderSection(\n optionRows.length ? \"Global Options\" : \"Options\",\n renderRows(GLOBAL_OPTIONS, style, { column }),\n style,\n ),\n ]);\n}\n\n/** Root commands are grouped under their top-level group, Vercel style. */\nfunction commandSections(\n commands: readonly CliCommand[],\n groups: readonly CliCommandGroup[],\n): readonly { readonly title?: string; readonly rows: readonly CliRow[] }[] {\n const roots = groups.filter((group) => group.command.length === 1);\n const loose = commands.filter((command) =>\n !roots.some((group) => startsWith(command.command, group.command))\n );\n const sections = roots.map((group) => ({\n ...(roots.length > 1 || loose.length\n ? { title: group.title ?? group.command.join(\" \") }\n : {}),\n rows: commands\n .filter((command) => startsWith(command.command, group.command))\n .map(row),\n })).filter((section) => section.rows.length > 0);\n return [\n ...sections,\n ...(loose.length\n ? [{\n ...(sections.length ? { title: \"General\" } : {}),\n rows: loose.map(row),\n }]\n : []),\n ];\n}\n\nfunction row(command: CliCommand): CliRow {\n return { label: signature(command), ...describe(command) };\n}\n\nfunction describe(command: CliCommand): { description?: string } {\n const text = command.capability.title ?? command.capability.description;\n return text ? { description: text } : {};\n}\n\n/** `todo delete <todoId>` — command path plus its positional slots. */\nfunction signature(\n command: CliCommand,\n path: readonly string[] = command.command,\n): string {\n const required = requiredFields(command);\n return [\n ...path,\n ...(command.meta.positional ?? []).map((name) =>\n placeholder(name, required.has(name))\n ),\n ].join(\" \");\n}\n\nfunction placeholder(name: string, required: boolean): string {\n return required ? `<${name}>` : `[${name}]`;\n}\n\n/** Title, prose, then the invocation line. No heading needed above it. */\nfunction banner(options: {\n readonly title?: string;\n readonly description?: string;\n readonly usage: string;\n readonly style: CliStyle;\n}): string {\n const { style } = options;\n return [\n [\n options.title ? `${MARGIN}${style.bold(options.title)}` : undefined,\n options.description\n ? `${MARGIN}${style.dim(options.description)}`\n : undefined,\n ].filter(Boolean).join(\"\\n\"),\n `${MARGIN}${style.accent(options.usage)}`,\n ].filter(Boolean).join(\"\\n\\n\");\n}\n\nfunction hint(text: string, style: CliStyle): string {\n return `${MARGIN}${style.dim(text)}`;\n}\n\nfunction fields(command: CliCommand): Record<string, JsonSchema> {\n return (command.capability.input?.properties as\n | Record<string, JsonSchema>\n | undefined) ?? {};\n}\n\nfunction requiredFields(command: CliCommand): ReadonlySet<string> {\n return new Set(\n command.capability.input?.required as readonly string[] | undefined,\n );\n}\n\nfunction optionLabel(name: string, schema: JsonSchema): string {\n const flag = `--${kebabCase(name)}`;\n if (schema.type === \"boolean\") return flag;\n if (Array.isArray(schema.enum)) {\n return `${flag} <${schema.enum.map(String).join(\"|\")}>`;\n }\n if (schema.type === \"array\" || schema.type === \"object\") {\n return `${flag} <json>`;\n }\n return `${flag} <${String(schema.type ?? \"value\")}>`;\n}\n\n/**\n * Descriptions stay one short line: prose first, then only the facts a reader\n * cannot guess from the label (requiredness, defaults, choices).\n */\nfunction description(\n schema: JsonSchema | undefined,\n options: { readonly required?: boolean; readonly choices?: boolean } = {},\n): { description?: string } {\n const prose = typeof schema?.description === \"string\"\n ? schema.description\n : undefined;\n const notes = [\n options.choices && Array.isArray(schema?.enum)\n ? `one of ${schema.enum.map(String).join(\", \")}`\n : undefined,\n schema?.default !== undefined\n ? `default: ${String(schema.default)}`\n : undefined,\n options.required ? \"required\" : undefined,\n ].filter(Boolean);\n const text = [prose, notes.length ? `(${notes.join(\", \")})` : undefined]\n .filter(Boolean)\n .join(\" \");\n return text ? { description: text } : {};\n}\n\nfunction startsWith(\n value: readonly string[],\n prefix: readonly string[],\n): boolean {\n return prefix.every((part, index) => value[index] === part);\n}\n\nfunction kebabCase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);\n}\n\nfunction renderHelp(sections: readonly (string | undefined)[]): string {\n return `\\n${sections.filter(Boolean).join(\"\\n\\n\")}\\n`;\n}\n","import type {\n GroupMetaRegistry,\n CapabilityMetaRegistry,\n} from \"@capable/core\";\nimport {\n getAppRuntime,\n TransportError,\n type AnyApp,\n type JsonSchema,\n type CapabilityResult,\n} from \"@capable/app\";\nimport { render as renderMarkdown } from \"markdansi\";\nimport {\n collectCommands,\n type CliCommand,\n type CliCommandGroup,\n} from \"./commands.ts\";\nimport {\n renderCommandHelp,\n renderGroupHelp,\n renderRootHelp,\n} from \"./help.ts\";\nimport {\n createCliStyle,\n supportsColor,\n} from \"./style.ts\";\n\n/** Shared help layout, so every Capable surface prints the same shape. */\nexport {\n createCliStyle,\n descriptionColumn,\n MARGIN,\n renderRows,\n renderSection,\n ROW_INDENT,\n supportsColor,\n type CliRow,\n type CliStyle,\n} from \"./style.ts\";\n\nexport type CliCapabilityMeta =\n | false\n | {\n readonly name?: string;\n readonly command?: readonly string[];\n readonly positional?: readonly string[];\n };\n\nexport type CliGroupMeta = {\n readonly name?: string;\n};\n\ndeclare module \"@capable/core\" {\n interface CapabilityMetaRegistry {\n readonly cli?: CliCapabilityMeta;\n }\n\n interface GroupMetaRegistry {\n readonly cli?: CliGroupMeta;\n }\n}\n\nexport type CliIo = {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n};\n\nexport type CreateCliOptions = {\n readonly invocationName?: string;\n readonly color?: boolean;\n readonly isTTY?: boolean;\n readonly columns?: number;\n};\n\nexport function createCli(\n app: AnyApp,\n cliOptions: CreateCliOptions = {},\n): {\n run(\n argv: readonly string[],\n options?: { readonly io?: Partial<CliIo> },\n ): Promise<number>;\n} {\n return Object.freeze({\n run(argv, options = {}) {\n return runCli({\n app,\n argv,\n ...(cliOptions.invocationName\n ? { invocationName: cliOptions.invocationName }\n : {}),\n ...(cliOptions.color !== undefined ? { color: cliOptions.color } : {}),\n ...(cliOptions.isTTY !== undefined ? { isTTY: cliOptions.isTTY } : {}),\n ...(cliOptions.columns !== undefined\n ? { columns: cliOptions.columns }\n : {}),\n ...(options.io ? { io: options.io } : {}),\n });\n },\n });\n}\n\nexport async function runCli(options: {\n readonly app: AnyApp;\n readonly argv: readonly string[];\n readonly invocationName?: string;\n readonly color?: boolean;\n readonly isTTY?: boolean;\n readonly columns?: number;\n readonly io?: Partial<CliIo>;\n}): Promise<number> {\n const io: CliIo = {\n stdout: options.io?.stdout ??\n ((text) => process.stdout.write(withTrailingNewline(text))),\n stderr: options.io?.stderr ??\n ((text) => process.stderr.write(withTrailingNewline(text))),\n };\n const invocationName = options.invocationName ?? \"cap\";\n const isTTY = options.isTTY ?? Boolean(process.stdout.isTTY);\n const color = options.color ?? supportsColor(process.env, isTTY);\n const columns = options.columns ?? process.stdout.columns ?? 80;\n const style = createCliStyle(color);\n const runtime = getAppRuntime(options.app);\n let manifest;\n try {\n manifest = await runtime.manifest();\n } catch (error) {\n io.stderr(renderRuntimeError(error));\n return 1;\n }\n const catalog = collectCommands(manifest.capabilities);\n const json = options.argv.includes(\"--json\");\n const watch = options.argv.includes(\"--watch\");\n const wantsHelp = options.argv.includes(\"--help\") ||\n options.argv.includes(\"-h\");\n const argv = options.argv.filter((argument) =>\n ![\"--json\", \"--watch\", \"--help\", \"-h\"].includes(argument)\n );\n\n if (argv.length === 0) {\n io.stdout(renderRootHelp(\n manifest,\n catalog.commands,\n catalog.groups,\n invocationName,\n style,\n ));\n return 0;\n }\n\n const command = matchCommand(argv, catalog.commands);\n const group = exactGroup(argv, catalog.groups);\n if (wantsHelp) {\n if (command) {\n io.stdout(renderCommandHelp(command, invocationName, style));\n return 0;\n }\n if (group) {\n io.stdout(renderGroupHelp(\n group,\n catalog.commands,\n invocationName,\n style,\n ));\n return 0;\n }\n io.stderr(unknownCommand(argv, catalog.commands, invocationName));\n return 2;\n }\n\n if (!command) {\n if (group) {\n io.stderr(\n `Missing command after ${group.command.join(\" \")}\\n` +\n `Run \\`${invocationName} ${group.command.join(\" \")} --help\\` to list available commands.`,\n );\n return 2;\n }\n io.stderr(unknownCommand(argv, catalog.commands, invocationName));\n return 2;\n }\n\n try {\n if (watch && !command.capability.subscription) {\n throw new CliUsageError(\n `Option --watch is only available for subscribable Capabilities`,\n );\n }\n const input = parseArguments(\n argv.slice(command.command.length),\n command,\n invocationName,\n );\n if (watch) {\n return await runWatchedCommand({\n runtime,\n command,\n input,\n json,\n io,\n color,\n isTTY,\n columns,\n });\n }\n const result = await runtime.call({\n id: command.capability.id,\n input,\n });\n io.stdout(\n json\n ? JSON.stringify(result.output, null, 2)\n : renderCapabilityResult(result, {\n color,\n isTTY,\n columns,\n }),\n );\n return 0;\n } catch (error) {\n if (error instanceof CliUsageError) {\n io.stderr(error.message);\n return 2;\n }\n if (error instanceof TransportError) {\n io.stderr(renderRuntimeError(error));\n return 1;\n }\n io.stderr(error instanceof Error ? error.message : String(error));\n return 1;\n }\n}\n\nfunction withTrailingNewline(value: string): string {\n return value.endsWith(\"\\n\") ? value : `${value}\\n`;\n}\n\nasync function runWatchedCommand(options: {\n readonly runtime: ReturnType<typeof getAppRuntime>;\n readonly command: CliCommand;\n readonly input: Record<string, unknown>;\n readonly json: boolean;\n readonly io: CliIo;\n readonly color: boolean;\n readonly isTTY: boolean;\n readonly columns: number;\n}): Promise<number> {\n const controller = new AbortController();\n const abort = () => controller.abort();\n process.once(\"SIGINT\", abort);\n const stream = options.runtime.subscribe({\n id: options.command.capability.id,\n input: options.input,\n signal: controller.signal,\n });\n\n try {\n let frame = 0;\n let previousFrameLines = 0;\n for await (const result of stream) {\n if (options.json) {\n options.io.stdout(`${JSON.stringify(result.output)}\\n`);\n continue;\n }\n const presentation = renderCapabilityResult(result, options);\n options.io.stdout(formatWatchFrame(\n presentation,\n frame++,\n options.isTTY,\n previousFrameLines,\n ));\n previousFrameLines = countFrameLines(presentation);\n }\n return 0;\n } catch (error) {\n if (controller.signal.aborted || isAbortError(error)) return 0;\n throw error;\n } finally {\n process.off(\"SIGINT\", abort);\n await stream.return?.();\n }\n}\n\nfunction renderCapabilityResult(\n result: CapabilityResult,\n options: {\n readonly color: boolean;\n readonly isTTY: boolean;\n readonly columns: number;\n },\n): string {\n if (result.markdown !== undefined) {\n return options.isTTY\n ? renderMarkdown(result.markdown, {\n color: options.color,\n width: options.columns,\n })\n : result.markdown;\n }\n return typeof result.output === \"string\"\n ? result.output\n : JSON.stringify(result.output, null, 2);\n}\n\nfunction formatWatchFrame(\n value: string,\n index: number,\n isTTY: boolean,\n previousFrameLines: number,\n): string {\n const frame = value.endsWith(\"\\n\") ? value : `${value}\\n`;\n if (isTTY) {\n return index === 0\n ? frame\n : `\\u001B[${previousFrameLines}A\\r\\u001B[0J${frame}`;\n }\n return index === 0 ? frame : `\\n---\\n\\n${frame}`;\n}\n\nfunction countFrameLines(value: string): number {\n const frame = value.endsWith(\"\\n\") ? value : `${value}\\n`;\n return frame.split(\"\\n\").length - 1;\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof DOMException && error.name === \"AbortError\";\n}\n\nfunction parseArguments(\n argv: readonly string[],\n command: CliCommand,\n invocationName: string,\n): Record<string, unknown> {\n const capability = command.capability;\n const positional = command.meta.positional ?? [];\n const commandName = `${invocationName} ${command.command.join(\" \")}`;\n const schema = capability.input;\n const properties = schema?.properties as\n | Record<string, JsonSchema>\n | undefined;\n const input: Record<string, unknown> = {};\n let position = 0;\n\n for (let index = 0; index < argv.length; index++) {\n const token = argv[index]!;\n if (token.startsWith(\"--\")) {\n const [rawName, inline] = token.slice(2).split(\"=\", 2);\n const name = camelCase(rawName!);\n const field = properties?.[name];\n if (!field || positional.includes(name)) {\n const suggestion = nearest(\n rawName!,\n Object.keys(properties ?? {})\n .filter((candidate) => !positional.includes(candidate))\n .map(kebabCase),\n );\n throw new CliUsageError([\n `Unknown option --${rawName}`,\n ...(suggestion ? [`Did you mean \\`--${suggestion}\\`?`] : []),\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n ].join(\"\\n\"));\n }\n const boolean = field.type === \"boolean\";\n const raw = inline ?? (boolean ? \"true\" : argv[++index]);\n if (raw === undefined) {\n throw new CliUsageError(\n `Option --${rawName} requires a value\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n input[name] = coerce(raw, field, `--${rawName}`, commandName);\n continue;\n }\n const name = positional[position++];\n if (!name) {\n throw new CliUsageError(\n `Unexpected argument \"${token}\"\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n const field = properties?.[name];\n if (!field) {\n throw new CliUsageError(\n `CLI positional field \"${name}\" is not present in the input schema`,\n );\n }\n input[name] = coerce(token, field, `<${name}>`, commandName);\n }\n\n const required = schema?.required as readonly string[] | undefined;\n for (const name of required ?? []) {\n if (!(name in input)) {\n const label = positional.includes(name)\n ? `positional argument <${name}>`\n : `required option --${kebabCase(name)}`;\n throw new CliUsageError(\n `Missing ${label}\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n }\n return input;\n}\n\nfunction coerce(\n value: string,\n schema: JsonSchema,\n label: string,\n commandName: string,\n): unknown {\n if (schema.type === \"boolean\") return value !== \"false\";\n if (schema.type === \"integer\" || schema.type === \"number\") {\n const number = Number(value);\n if (!Number.isFinite(number)) {\n throw new CliUsageError(\n `Expected a number for ${label}, received \"${value}\"\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n return number;\n }\n return value;\n}\n\nclass CliUsageError extends Error {}\n\nfunction renderRuntimeError(error: unknown): string {\n return error instanceof TransportError\n ? `${error.code}: ${error.message}`\n : error instanceof Error\n ? error.message\n : String(error);\n}\n\nfunction matchCommand(\n argv: readonly string[],\n commands: readonly CliCommand[],\n): CliCommand | undefined {\n return commands\n .filter((candidate) =>\n candidate.command.every((token, index) => argv[index] === token)\n )\n .sort((left, right) => right.command.length - left.command.length)[0];\n}\n\nfunction exactGroup(\n argv: readonly string[],\n groups: readonly CliCommandGroup[],\n): CliCommandGroup | undefined {\n return groups.find((group) =>\n group.command.length === argv.length &&\n group.command.every((token, index) => argv[index] === token)\n );\n}\n\nfunction unknownCommand(\n argv: readonly string[],\n commands: readonly CliCommand[],\n invocationName: string,\n): string {\n const entered = argv.join(\" \");\n const suggestion = nearest(\n entered,\n commands.map((command) => command.command.join(\" \")),\n );\n return [\n `Unknown command: ${entered}`,\n ...(suggestion ? [`Did you mean \\`${suggestion}\\`?`] : []),\n `Run \\`${invocationName} --help\\` to list available commands.`,\n ].join(\"\\n\");\n}\n\nfunction nearest(\n value: string,\n candidates: readonly string[],\n): string | undefined {\n let match: { readonly candidate: string; readonly distance: number } | undefined;\n for (const candidate of new Set(candidates)) {\n const distance = editDistance(value, candidate);\n if (!match || distance < match.distance) {\n match = { candidate, distance };\n }\n }\n if (!match) return undefined;\n return match.distance <= Math.max(2, Math.floor(match.candidate.length / 3))\n ? match.candidate\n : undefined;\n}\n\nfunction editDistance(left: string, right: string): number {\n const previous = Array.from(\n { length: right.length + 1 },\n (_, index) => index,\n );\n for (let leftIndex = 1; leftIndex <= left.length; leftIndex++) {\n const current = [leftIndex];\n for (let rightIndex = 1; rightIndex <= right.length; rightIndex++) {\n current[rightIndex] = Math.min(\n current[rightIndex - 1]! + 1,\n previous[rightIndex]! + 1,\n previous[rightIndex - 1]! +\n (left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1),\n );\n }\n previous.splice(0, previous.length, ...current);\n }\n return previous[right.length]!;\n}\n\nfunction camelCase(value: string): string {\n return value.replace(/-([a-z])/g, (_, character: string) =>\n character.toUpperCase()\n );\n}\n\nfunction kebabCase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);\n}\n"],"mappings":";;;AA2BA,SAAgB,gBACd,OACA,SAA4B,CAAC,GACV;CACnB,MAAM,WAAyB,CAAC;CAChC,MAAM,SAA4B,CAAC;CAEnC,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,KAAK,SAAS,SAAS;GACzB,MAAM,OAAQ,KAAK,KAAK,OAAO,CAAC;GAChC,MAAM,UAAU,CAAC,GAAG,QAAQ,KAAK,QAAQ,KAAK,GAAG;GACjD,OAAO,KAAK,UAAU,MAAM,OAAO,CAAC;GACpC,MAAM,WAAW,gBAAgB,KAAK,UAAU,OAAO;GACvD,SAAS,KAAK,GAAG,SAAS,QAAQ;GAClC,OAAO,KAAK,GAAG,SAAS,MAAM;GAC9B;EACF;EAEA,MAAM,UAAU,KAAK,KAAK;EAC1B,IAAI,YAAY,OAAO;EACvB,MAAM,OAAO,WAAW,CAAC;EACzB,SAAS,KAAK;GACZ,SAAS,KAAK,WAAW,CAAC,GAAG,QAAQ,KAAK,QAAQ,KAAK,KAAK,GAAG,EAAE,CAAE;GACnE,YAAY;GACZ;EACF,CAAC;CACH;CAEA,OAAO;EACL,UAAU,OAAO,OAAO,QAAQ;EAChC,QAAQ,OAAO,OAAO,MAAM;CAC9B;AACF;AAEA,SAAS,UACP,MACA,SACiB;CACjB,OAAO,OAAO,OAAO;EACnB,SAAS,OAAO,OAAO,OAAO;EAC9B,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;EAC1C,GAAI,KAAK,cAAc,EAAE,aAAa,KAAK,YAAY,IAAI,CAAC;CAC9D,CAAC;AACH;;;;AC1DA,MAAa,SAAS;;AAGtB,MAAa,aAAa;;AAG1B,MAAM,kBAAkB;AAExB,MAAM,YAAY;AAElB,SAAgB,eAAe,OAA2B;CACx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AQ,aAAa;EAC7D,MAAM,UAAU,CAAC,SAAS;EAC1B,KAAK,IAAI,aAAa,GAAG,cAAc,MAAM,QAAQ,cACnD,QAAQ,cAAc,KAAK,IACzB,QAAQ,aAAa,KAAM,GAC3B,SAAS,cAAe,GACxB,SAAS,aAAa,MACnB,KAAK,YAAY,OAAO,MAAM,aAAa,KAAK,IAAI,EACzD;EAEF,SAAS,OAAO,GAAG,SAAS,QAAQ,GAAG,OAAO;CAChD;CACA,OAAO,SAAS,MAAM;AACxB;AAEA,SAAS,UAAU,OAAuB;CACxC,OAAO,MAAM,QAAQ,cAAc,GAAG,cACpC,UAAU,YAAY,CACxB;AACF;AAEA,SAAS,UAAU,OAAuB;CACxC,OAAO,MAAM,QAAQ,WAAW,cAAc,IAAI,UAAU,YAAY,GAAG;AAC7E"}
1
+ {"version":3,"file":"src-BjBxOv7x.mjs","names":["kebabCase","renderMarkdown"],"sources":["../../cli/src/commands.ts","../../cli/src/style.ts","../../cli/src/help.ts","../../cli/src/index.ts"],"sourcesContent":["import type {\n ManifestGroup,\n ManifestNode,\n ManifestCapability,\n} from \"@capable/app\";\nimport type {\n CliGroupMeta,\n CliCapabilityMeta,\n} from \"./index.ts\";\n\nexport type CliCommand = {\n readonly command: readonly string[];\n readonly capability: ManifestCapability;\n readonly meta: Exclude<CliCapabilityMeta, false>;\n};\n\nexport type CliCommandGroup = {\n readonly command: readonly string[];\n readonly title?: string;\n readonly description?: string;\n};\n\nexport type CliCommandCatalog = {\n readonly commands: readonly CliCommand[];\n readonly groups: readonly CliCommandGroup[];\n};\n\nexport function collectCommands(\n nodes: readonly ManifestNode[],\n parent: readonly string[] = [],\n): CliCommandCatalog {\n const commands: CliCommand[] = [];\n const groups: CliCommandGroup[] = [];\n\n for (const node of nodes) {\n if (node.type === \"group\") {\n const meta = (node.meta.cli ?? {}) as CliGroupMeta;\n const command = [...parent, meta.name ?? node.key];\n groups.push(groupFrom(node, command));\n const children = collectCommands(node.children, command);\n commands.push(...children.commands);\n groups.push(...children.groups);\n continue;\n }\n\n const rawMeta = node.meta.cli as CliCapabilityMeta | undefined;\n if (rawMeta === false) continue;\n const meta = rawMeta ?? {};\n commands.push({\n command: meta.command ?? [...parent, meta.name ?? node.path.at(-1)!],\n capability: node,\n meta,\n });\n }\n\n return {\n commands: Object.freeze(commands),\n groups: Object.freeze(groups),\n };\n}\n\nfunction groupFrom(\n node: ManifestGroup,\n command: readonly string[],\n): CliCommandGroup {\n return Object.freeze({\n command: Object.freeze(command),\n ...(node.title ? { title: node.title } : {}),\n ...(node.description ? { description: node.description } : {}),\n });\n}\n","export type CliStyle = {\n readonly bold: (text: string) => string;\n readonly accent: (text: string) => string;\n readonly dim: (text: string) => string;\n};\n\nexport type CliRow = {\n readonly label: string;\n readonly description?: string;\n};\n\n/** Every help line hangs off this margin. */\nexport const MARGIN = \" \";\n\n/** Rows sit one step inside their section heading. */\nexport const ROW_INDENT = \" \";\n\n/** Widest label that still keeps descriptions in a single column. */\nconst MAX_LABEL_WIDTH = 30;\n\nconst LABEL_GAP = 2;\n\nexport function createCliStyle(color?: boolean): CliStyle {\n const enabled = color ?? supportsColor();\n return {\n bold: enabled\n ? (text: string) => `\\u001B[1m${text}\\u001B[22m`\n : identity,\n accent: enabled\n ? (text: string) => `\\u001B[36m${text}\\u001B[39m`\n : identity,\n dim: enabled\n ? (text: string) => `\\u001B[2m${text}\\u001B[22m`\n : identity,\n };\n}\n\nexport function supportsColor(\n env: Record<string, string | undefined> = process.env,\n isTTY: boolean = Boolean(process.stdout.isTTY),\n): boolean {\n if (\"NO_COLOR\" in env) return false;\n if (env.FORCE_COLOR !== undefined) return env.FORCE_COLOR !== \"0\";\n return isTTY && env.TERM !== \"dumb\";\n}\n\nexport function renderRows(\n rows: readonly CliRow[],\n style: CliStyle,\n options: {\n readonly indent?: string;\n /** Absolute column for descriptions, so sibling sections stay aligned. */\n readonly column?: number;\n } = {},\n): string {\n const indent = options.indent ?? ROW_INDENT;\n const width = Math.max(\n 0,\n (options.column ?? descriptionColumn(rows, indent)) - indent.length -\n LABEL_GAP,\n );\n return rows.map(({ label, description }) => {\n const line = `${indent}${style.accent(label)}`;\n if (!description) return line;\n return label.length > width\n ? `${line}\\n${indent}${\" \".repeat(width + LABEL_GAP)}${style.dim(description)}`\n : `${line}${\" \".repeat(width - label.length + LABEL_GAP)}${\n style.dim(description)\n }`;\n }).join(\"\\n\");\n}\n\n/** Shared description column so sibling sections stay visually aligned. */\nexport function descriptionColumn(\n rows: readonly CliRow[],\n indent: string = ROW_INDENT,\n): number {\n const labels = rows\n .filter(({ description }) => description !== undefined)\n .map(({ label }) => label.length)\n .filter((length) => length <= MAX_LABEL_WIDTH);\n return indent.length + LABEL_GAP + Math.max(0, ...labels);\n}\n\nexport function renderSection(\n title: string,\n body: string,\n style: CliStyle,\n): string {\n return `${MARGIN}${style.bold(title)}\\n\\n${body}`;\n}\n\nfunction identity(text: string): string {\n return text;\n}\n","import type {\n ApplicationManifest,\n JsonSchema,\n} from \"@capable/app\";\nimport type {\n CliCommand,\n CliCommandGroup,\n} from \"./commands.ts\";\nimport {\n descriptionColumn,\n MARGIN,\n renderRows,\n renderSection,\n ROW_INDENT,\n type CliRow,\n type CliStyle,\n} from \"./style.ts\";\n\nconst GLOBAL_OPTIONS: readonly CliRow[] = [\n { label: \"--json\", description: \"Print canonical JSON\" },\n { label: \"-h, --help\", description: \"Show help\" },\n];\n\nexport function renderRootHelp(\n manifest: Pick<ApplicationManifest, \"name\" | \"description\">,\n commands: readonly CliCommand[],\n groups: readonly CliCommandGroup[],\n invocationName: string,\n style: CliStyle,\n): string {\n const sections = commandSections(commands, groups);\n const nested = sections.some((section) => section.title !== undefined);\n const column = Math.max(\n descriptionColumn(\n sections.flatMap((section) => section.rows),\n nested ? `${ROW_INDENT}${MARGIN}` : ROW_INDENT,\n ),\n descriptionColumn(GLOBAL_OPTIONS),\n );\n return renderHelp([\n banner({\n title: manifest.name,\n ...(manifest.description ? { description: manifest.description } : {}),\n usage: `${invocationName} <command> [options]`,\n style,\n }),\n renderSection(\n \"Commands\",\n sections\n .map((section) =>\n [\n section.title ? `${ROW_INDENT}${style.dim(section.title)}` : undefined,\n renderRows(section.rows, style, {\n column,\n ...(section.title ? { indent: `${ROW_INDENT}${MARGIN}` } : {}),\n }),\n ].filter(Boolean).join(\"\\n\")\n )\n .join(\"\\n\\n\"),\n style,\n ),\n renderSection(\"Options\", renderRows(GLOBAL_OPTIONS, style, { column }), style),\n hint(`Run \\`${invocationName} <command> --help\\` for details on a command.`, style),\n ]);\n}\n\nexport function renderGroupHelp(\n group: CliCommandGroup,\n commands: readonly CliCommand[],\n invocationName: string,\n style: CliStyle,\n): string {\n const prefix = group.command.join(\" \");\n const rows = commands\n .filter((candidate) => startsWith(candidate.command, group.command))\n .map((candidate) => ({\n label: signature(candidate, candidate.command.slice(group.command.length)),\n ...describe(candidate),\n }));\n const column = descriptionColumn([...rows, ...GLOBAL_OPTIONS]);\n return renderHelp([\n banner({\n ...(group.title ? { title: group.title } : {}),\n ...(group.description ? { description: group.description } : {}),\n usage: `${invocationName} ${prefix} <command> [options]`,\n style,\n }),\n renderSection(\"Commands\", renderRows(rows, style, { column }), style),\n renderSection(\"Options\", renderRows(GLOBAL_OPTIONS, style, { column }), style),\n hint(\n `Run \\`${invocationName} ${prefix} <command> --help\\` for details on a command.`,\n style,\n ),\n ]);\n}\n\nexport function renderCommandHelp(\n command: CliCommand,\n invocationName: string,\n style: CliStyle,\n): string {\n const properties = fields(command);\n const required = requiredFields(command);\n const positionals = command.meta.positional ?? [];\n const argumentRows = positionals.map((name) => ({\n label: placeholder(name, required.has(name)),\n ...description(properties[name], { choices: true }),\n }));\n const optionRows = [\n ...Object.entries(properties)\n .filter(([name]) => !positionals.includes(name))\n .map(([name, schema]) => ({\n label: optionLabel(name, schema),\n ...description(schema, { required: required.has(name) }),\n })),\n ...(command.capability.subscription\n ? [{ label: \"--watch\", description: \"Stream updates until interrupted\" }]\n : []),\n ];\n const column = descriptionColumn([\n ...argumentRows,\n ...optionRows,\n ...GLOBAL_OPTIONS,\n ]);\n\n return renderHelp([\n banner({\n ...(command.capability.title ? { title: command.capability.title } : {}),\n ...(command.capability.description\n ? { description: command.capability.description }\n : {}),\n usage: [invocationName, signature(command), \"[options]\"].join(\" \"),\n style,\n }),\n argumentRows.length\n ? renderSection(\n \"Arguments\",\n renderRows(argumentRows, style, { column }),\n style,\n )\n : undefined,\n optionRows.length\n ? renderSection(\"Options\", renderRows(optionRows, style, { column }), style)\n : undefined,\n renderSection(\n optionRows.length ? \"Global Options\" : \"Options\",\n renderRows(GLOBAL_OPTIONS, style, { column }),\n style,\n ),\n ]);\n}\n\n/** Root commands are grouped under their top-level group, Vercel style. */\nfunction commandSections(\n commands: readonly CliCommand[],\n groups: readonly CliCommandGroup[],\n): readonly { readonly title?: string; readonly rows: readonly CliRow[] }[] {\n const roots = groups.filter((group) => group.command.length === 1);\n const loose = commands.filter((command) =>\n !roots.some((group) => startsWith(command.command, group.command))\n );\n const sections = roots.map((group) => ({\n ...(roots.length > 1 || loose.length\n ? { title: group.title ?? group.command.join(\" \") }\n : {}),\n rows: commands\n .filter((command) => startsWith(command.command, group.command))\n .map(row),\n })).filter((section) => section.rows.length > 0);\n return [\n ...sections,\n ...(loose.length\n ? [{\n ...(sections.length ? { title: \"General\" } : {}),\n rows: loose.map(row),\n }]\n : []),\n ];\n}\n\nfunction row(command: CliCommand): CliRow {\n return { label: signature(command), ...describe(command) };\n}\n\nfunction describe(command: CliCommand): { description?: string } {\n const text = command.capability.title ?? command.capability.description;\n return text ? { description: text } : {};\n}\n\n/** `todo delete <todoId>` — command path plus its positional slots. */\nfunction signature(\n command: CliCommand,\n path: readonly string[] = command.command,\n): string {\n const required = requiredFields(command);\n return [\n ...path,\n ...(command.meta.positional ?? []).map((name) =>\n placeholder(name, required.has(name))\n ),\n ].join(\" \");\n}\n\nfunction placeholder(name: string, required: boolean): string {\n return required ? `<${name}>` : `[${name}]`;\n}\n\n/** Title, prose, then the invocation line. No heading needed above it. */\nfunction banner(options: {\n readonly title?: string;\n readonly description?: string;\n readonly usage: string;\n readonly style: CliStyle;\n}): string {\n const { style } = options;\n return [\n [\n options.title ? `${MARGIN}${style.bold(options.title)}` : undefined,\n options.description\n ? `${MARGIN}${style.dim(options.description)}`\n : undefined,\n ].filter(Boolean).join(\"\\n\"),\n `${MARGIN}${style.accent(options.usage)}`,\n ].filter(Boolean).join(\"\\n\\n\");\n}\n\nfunction hint(text: string, style: CliStyle): string {\n return `${MARGIN}${style.dim(text)}`;\n}\n\nfunction fields(command: CliCommand): Record<string, JsonSchema> {\n return (command.capability.input?.properties as\n | Record<string, JsonSchema>\n | undefined) ?? {};\n}\n\nfunction requiredFields(command: CliCommand): ReadonlySet<string> {\n return new Set(\n command.capability.input?.required as readonly string[] | undefined,\n );\n}\n\nfunction optionLabel(name: string, schema: JsonSchema): string {\n const flag = `--${kebabCase(name)}`;\n if (schema.type === \"boolean\") return flag;\n if (Array.isArray(schema.enum)) {\n return `${flag} <${schema.enum.map(String).join(\"|\")}>`;\n }\n if (schema.type === \"array\" || schema.type === \"object\") {\n return `${flag} <json>`;\n }\n return `${flag} <${String(schema.type ?? \"value\")}>`;\n}\n\n/**\n * Descriptions stay one short line: prose first, then only the facts a reader\n * cannot guess from the label (requiredness, defaults, choices).\n */\nfunction description(\n schema: JsonSchema | undefined,\n options: { readonly required?: boolean; readonly choices?: boolean } = {},\n): { description?: string } {\n const prose = typeof schema?.description === \"string\"\n ? schema.description\n : undefined;\n const notes = [\n options.choices && Array.isArray(schema?.enum)\n ? `one of ${schema.enum.map(String).join(\", \")}`\n : undefined,\n schema?.default !== undefined\n ? `default: ${String(schema.default)}`\n : undefined,\n options.required ? \"required\" : undefined,\n ].filter(Boolean);\n const text = [prose, notes.length ? `(${notes.join(\", \")})` : undefined]\n .filter(Boolean)\n .join(\" \");\n return text ? { description: text } : {};\n}\n\nfunction startsWith(\n value: readonly string[],\n prefix: readonly string[],\n): boolean {\n return prefix.every((part, index) => value[index] === part);\n}\n\nfunction kebabCase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);\n}\n\nfunction renderHelp(sections: readonly (string | undefined)[]): string {\n return `\\n${sections.filter(Boolean).join(\"\\n\\n\")}\\n`;\n}\n","import type {\n GroupMetaRegistry,\n CapabilityMetaRegistry,\n} from \"@capable/core\";\nimport {\n getAppRuntime,\n TransportError,\n type AnyApp,\n type JsonSchema,\n type CapabilityResult,\n} from \"@capable/app\";\nimport { render as renderMarkdown } from \"markdansi\";\nimport {\n collectCommands,\n type CliCommand,\n type CliCommandGroup,\n} from \"./commands.ts\";\nimport {\n renderCommandHelp,\n renderGroupHelp,\n renderRootHelp,\n} from \"./help.ts\";\nimport {\n createCliStyle,\n supportsColor,\n} from \"./style.ts\";\n\n/** Shared help layout, so every Capable surface prints the same shape. */\nexport {\n createCliStyle,\n descriptionColumn,\n MARGIN,\n renderRows,\n renderSection,\n ROW_INDENT,\n supportsColor,\n type CliRow,\n type CliStyle,\n} from \"./style.ts\";\n\nexport type CliCapabilityMeta =\n | false\n | {\n readonly name?: string;\n readonly command?: readonly string[];\n readonly positional?: readonly string[];\n };\n\nexport type CliGroupMeta = {\n readonly name?: string;\n};\n\ndeclare module \"@capable/core\" {\n interface CapabilityMetaRegistry {\n readonly cli?: CliCapabilityMeta;\n }\n\n interface GroupMetaRegistry {\n readonly cli?: CliGroupMeta;\n }\n}\n\nexport type CliIo = {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n};\n\nexport type CreateCliOptions = {\n readonly invocationName?: string;\n readonly color?: boolean;\n readonly isTTY?: boolean;\n readonly columns?: number;\n};\n\nexport function createCli(\n app: AnyApp,\n cliOptions: CreateCliOptions = {},\n): {\n run(\n argv: readonly string[],\n options?: { readonly io?: Partial<CliIo> },\n ): Promise<number>;\n} {\n return Object.freeze({\n run(argv, options = {}) {\n return runCli({\n app,\n argv,\n ...(cliOptions.invocationName\n ? { invocationName: cliOptions.invocationName }\n : {}),\n ...(cliOptions.color !== undefined ? { color: cliOptions.color } : {}),\n ...(cliOptions.isTTY !== undefined ? { isTTY: cliOptions.isTTY } : {}),\n ...(cliOptions.columns !== undefined\n ? { columns: cliOptions.columns }\n : {}),\n ...(options.io ? { io: options.io } : {}),\n });\n },\n });\n}\n\nexport async function runCli(options: {\n readonly app: AnyApp;\n readonly argv: readonly string[];\n readonly invocationName?: string;\n readonly color?: boolean;\n readonly isTTY?: boolean;\n readonly columns?: number;\n readonly io?: Partial<CliIo>;\n}): Promise<number> {\n const io: CliIo = {\n stdout: options.io?.stdout ??\n ((text) => process.stdout.write(withTrailingNewline(text))),\n stderr: options.io?.stderr ??\n ((text) => process.stderr.write(withTrailingNewline(text))),\n };\n const invocationName = options.invocationName ?? \"cap\";\n const isTTY = options.isTTY ?? Boolean(process.stdout.isTTY);\n const color = options.color ?? supportsColor(process.env, isTTY);\n const columns = options.columns ?? process.stdout.columns ?? 80;\n const style = createCliStyle(color);\n const runtime = getAppRuntime(options.app);\n let manifest;\n try {\n manifest = await runtime.manifest();\n } catch (error) {\n io.stderr(renderRuntimeError(error));\n return 1;\n }\n const catalog = collectCommands(manifest.capabilities);\n const json = options.argv.includes(\"--json\");\n const watch = options.argv.includes(\"--watch\");\n const wantsHelp = options.argv.includes(\"--help\") ||\n options.argv.includes(\"-h\");\n const argv = options.argv.filter((argument) =>\n ![\"--json\", \"--watch\", \"--help\", \"-h\"].includes(argument)\n );\n\n if (argv.length === 0) {\n io.stdout(renderRootHelp(\n manifest,\n catalog.commands,\n catalog.groups,\n invocationName,\n style,\n ));\n return 0;\n }\n\n const command = matchCommand(argv, catalog.commands);\n const group = exactGroup(argv, catalog.groups);\n if (wantsHelp) {\n if (command) {\n io.stdout(renderCommandHelp(command, invocationName, style));\n return 0;\n }\n if (group) {\n io.stdout(renderGroupHelp(\n group,\n catalog.commands,\n invocationName,\n style,\n ));\n return 0;\n }\n io.stderr(unknownCommand(argv, catalog.commands, invocationName));\n return 2;\n }\n\n if (!command) {\n if (group) {\n io.stderr(\n `Missing command after ${group.command.join(\" \")}\\n` +\n `Run \\`${invocationName} ${group.command.join(\" \")} --help\\` to list available commands.`,\n );\n return 2;\n }\n io.stderr(unknownCommand(argv, catalog.commands, invocationName));\n return 2;\n }\n\n try {\n if (watch && !command.capability.subscription) {\n throw new CliUsageError(\n `Option --watch is only available for subscribable Capabilities`,\n );\n }\n const input = parseArguments(\n argv.slice(command.command.length),\n command,\n invocationName,\n );\n if (watch) {\n return await runWatchedCommand({\n runtime,\n command,\n input,\n json,\n io,\n color,\n isTTY,\n columns,\n });\n }\n const result = await runtime.call({\n id: command.capability.id,\n input,\n });\n io.stdout(\n json\n ? JSON.stringify(result.output, null, 2)\n : renderCapabilityResult(result, {\n color,\n isTTY,\n columns,\n }),\n );\n return 0;\n } catch (error) {\n if (error instanceof CliUsageError) {\n io.stderr(error.message);\n return 2;\n }\n if (error instanceof TransportError) {\n io.stderr(renderRuntimeError(error));\n return 1;\n }\n io.stderr(error instanceof Error ? error.message : String(error));\n return 1;\n }\n}\n\nfunction withTrailingNewline(value: string): string {\n return value.endsWith(\"\\n\") ? value : `${value}\\n`;\n}\n\nasync function runWatchedCommand(options: {\n readonly runtime: ReturnType<typeof getAppRuntime>;\n readonly command: CliCommand;\n readonly input: Record<string, unknown>;\n readonly json: boolean;\n readonly io: CliIo;\n readonly color: boolean;\n readonly isTTY: boolean;\n readonly columns: number;\n}): Promise<number> {\n const controller = new AbortController();\n const abort = () => controller.abort();\n process.once(\"SIGINT\", abort);\n const stream = options.runtime.subscribe({\n id: options.command.capability.id,\n input: options.input,\n signal: controller.signal,\n });\n\n try {\n let frame = 0;\n let previousFrameLines = 0;\n for await (const result of stream) {\n if (options.json) {\n options.io.stdout(`${JSON.stringify(result.output)}\\n`);\n continue;\n }\n const presentation = renderCapabilityResult(result, options);\n options.io.stdout(formatWatchFrame(\n presentation,\n frame++,\n options.isTTY,\n previousFrameLines,\n ));\n previousFrameLines = countFrameLines(presentation);\n }\n return 0;\n } catch (error) {\n if (controller.signal.aborted || isAbortError(error)) return 0;\n throw error;\n } finally {\n process.off(\"SIGINT\", abort);\n await stream.return?.();\n }\n}\n\nfunction renderCapabilityResult(\n result: CapabilityResult,\n options: {\n readonly color: boolean;\n readonly isTTY: boolean;\n readonly columns: number;\n },\n): string {\n if (result.markdown !== undefined) {\n return options.isTTY\n ? renderMarkdown(result.markdown, {\n color: options.color,\n width: options.columns,\n })\n : result.markdown;\n }\n return typeof result.output === \"string\"\n ? result.output\n : JSON.stringify(result.output, null, 2);\n}\n\nfunction formatWatchFrame(\n value: string,\n index: number,\n isTTY: boolean,\n previousFrameLines: number,\n): string {\n const frame = value.endsWith(\"\\n\") ? value : `${value}\\n`;\n if (isTTY) {\n return index === 0\n ? frame\n : `\\u001B[${previousFrameLines}A\\r\\u001B[0J${frame}`;\n }\n return index === 0 ? frame : `\\n---\\n\\n${frame}`;\n}\n\nfunction countFrameLines(value: string): number {\n const frame = value.endsWith(\"\\n\") ? value : `${value}\\n`;\n return frame.split(\"\\n\").length - 1;\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof DOMException && error.name === \"AbortError\";\n}\n\nfunction parseArguments(\n argv: readonly string[],\n command: CliCommand,\n invocationName: string,\n): Record<string, unknown> {\n const capability = command.capability;\n const positional = command.meta.positional ?? [];\n const commandName = `${invocationName} ${command.command.join(\" \")}`;\n const schema = capability.input;\n const properties = schema?.properties as\n | Record<string, JsonSchema>\n | undefined;\n const input: Record<string, unknown> = {};\n let position = 0;\n\n for (let index = 0; index < argv.length; index++) {\n const token = argv[index]!;\n if (token.startsWith(\"--\")) {\n const [rawName, inline] = token.slice(2).split(\"=\", 2);\n const name = camelCase(rawName!);\n const field = properties?.[name];\n if (!field || positional.includes(name)) {\n const suggestion = nearest(\n rawName!,\n Object.keys(properties ?? {})\n .filter((candidate) => !positional.includes(candidate))\n .map(kebabCase),\n );\n throw new CliUsageError([\n `Unknown option --${rawName}`,\n ...(suggestion ? [`Did you mean \\`--${suggestion}\\`?`] : []),\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n ].join(\"\\n\"));\n }\n const boolean = field.type === \"boolean\";\n const raw = inline ?? (boolean ? \"true\" : argv[++index]);\n if (raw === undefined) {\n throw new CliUsageError(\n `Option --${rawName} requires a value\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n input[name] = coerce(raw, field, `--${rawName}`, commandName);\n continue;\n }\n const name = positional[position++];\n if (!name) {\n throw new CliUsageError(\n `Unexpected argument \"${token}\"\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n const field = properties?.[name];\n if (!field) {\n throw new CliUsageError(\n `CLI positional field \"${name}\" is not present in the input schema`,\n );\n }\n input[name] = coerce(token, field, `<${name}>`, commandName);\n }\n\n const required = schema?.required as readonly string[] | undefined;\n for (const name of required ?? []) {\n if (!(name in input)) {\n const label = positional.includes(name)\n ? `positional argument <${name}>`\n : `required option --${kebabCase(name)}`;\n throw new CliUsageError(\n `Missing ${label}\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n }\n return input;\n}\n\nfunction coerce(\n value: string,\n schema: JsonSchema,\n label: string,\n commandName: string,\n): unknown {\n if (schema.type === \"boolean\") return value !== \"false\";\n if (schema.type === \"integer\" || schema.type === \"number\") {\n const number = Number(value);\n if (!Number.isFinite(number)) {\n throw new CliUsageError(\n `Expected a number for ${label}, received \"${value}\"\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n return number;\n }\n return value;\n}\n\nclass CliUsageError extends Error {}\n\nfunction renderRuntimeError(error: unknown): string {\n return error instanceof TransportError\n ? `${error.code}: ${error.message}`\n : error instanceof Error\n ? error.message\n : String(error);\n}\n\nfunction matchCommand(\n argv: readonly string[],\n commands: readonly CliCommand[],\n): CliCommand | undefined {\n return commands\n .filter((candidate) =>\n candidate.command.every((token, index) => argv[index] === token)\n )\n .sort((left, right) => right.command.length - left.command.length)[0];\n}\n\nfunction exactGroup(\n argv: readonly string[],\n groups: readonly CliCommandGroup[],\n): CliCommandGroup | undefined {\n return groups.find((group) =>\n group.command.length === argv.length &&\n group.command.every((token, index) => argv[index] === token)\n );\n}\n\nfunction unknownCommand(\n argv: readonly string[],\n commands: readonly CliCommand[],\n invocationName: string,\n): string {\n const entered = argv.join(\" \");\n const suggestion = nearest(\n entered,\n commands.map((command) => command.command.join(\" \")),\n );\n return [\n `Unknown command: ${entered}`,\n ...(suggestion ? [`Did you mean \\`${suggestion}\\`?`] : []),\n `Run \\`${invocationName} --help\\` to list available commands.`,\n ].join(\"\\n\");\n}\n\nfunction nearest(\n value: string,\n candidates: readonly string[],\n): string | undefined {\n let match: { readonly candidate: string; readonly distance: number } | undefined;\n for (const candidate of new Set(candidates)) {\n const distance = editDistance(value, candidate);\n if (!match || distance < match.distance) {\n match = { candidate, distance };\n }\n }\n if (!match) return undefined;\n return match.distance <= Math.max(2, Math.floor(match.candidate.length / 3))\n ? match.candidate\n : undefined;\n}\n\nfunction editDistance(left: string, right: string): number {\n const previous = Array.from(\n { length: right.length + 1 },\n (_, index) => index,\n );\n for (let leftIndex = 1; leftIndex <= left.length; leftIndex++) {\n const current = [leftIndex];\n for (let rightIndex = 1; rightIndex <= right.length; rightIndex++) {\n current[rightIndex] = Math.min(\n current[rightIndex - 1]! + 1,\n previous[rightIndex]! + 1,\n previous[rightIndex - 1]! +\n (left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1),\n );\n }\n previous.splice(0, previous.length, ...current);\n }\n return previous[right.length]!;\n}\n\nfunction camelCase(value: string): string {\n return value.replace(/-([a-z])/g, (_, character: string) =>\n character.toUpperCase()\n );\n}\n\nfunction kebabCase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);\n}\n"],"mappings":";;;AA2BA,SAAgB,gBACd,OACA,SAA4B,CAAC,GACV;CACnB,MAAM,WAAyB,CAAC;CAChC,MAAM,SAA4B,CAAC;CAEnC,KAAK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AS,QAAQ,GAAG,OAAO;CAChD;CACA,OAAO,SAAS,MAAM;AACxB;AAEA,SAAS,UAAU,OAAuB;CACxC,OAAO,MAAM,QAAQ,cAAc,GAAG,cACpC,UAAU,YAAY,CACxB;AACF;AAEA,SAAS,UAAU,OAAuB;CACxC,OAAO,MAAM,QAAQ,WAAW,cAAc,IAAI,UAAU,YAAY,GAAG;AAC7E"}
@@ -84,7 +84,7 @@ function createHttpTransport(options) {
84
84
  ...signal ? { signal } : {}
85
85
  });
86
86
  if (!response.ok) throw await responseError(response);
87
- return await response.json();
87
+ return await responseJson(response, "Application manifest");
88
88
  },
89
89
  async call({ id, input = {}, signal }) {
90
90
  const body = await (await request(`call/${encodeURIComponent(id)}`, {
@@ -238,6 +238,22 @@ async function responseError(response) {
238
238
  data
239
239
  });
240
240
  }
241
+ async function responseJson(response, label) {
242
+ const contentType = response.headers.get("content-type");
243
+ if (!contentType?.toLowerCase().includes("json")) throw new TransportError("TRANSPORT_ERROR", {
244
+ status: response.status,
245
+ message: `${label} request returned ${contentType ?? "a non-JSON response"}${response.url ? ` from ${response.url}` : ""}`
246
+ });
247
+ try {
248
+ return await response.json();
249
+ } catch (cause) {
250
+ throw new TransportError("TRANSPORT_ERROR", {
251
+ status: response.status,
252
+ message: `${label} response contained invalid JSON`,
253
+ cause
254
+ });
255
+ }
256
+ }
241
257
  function normalizePath$1(value) {
242
258
  return `/${value.split("/").filter(Boolean).join("/")}`;
243
259
  }
@@ -438,4 +454,4 @@ function joinPath(...parts) {
438
454
  //#endregion
439
455
  export { createHttpTransport as n, createProtocolHandler as r, createHttpHandler as t };
440
456
 
441
- //# sourceMappingURL=src-XRJ9hgYX.mjs.map
457
+ //# sourceMappingURL=src-DX2xrplP.mjs.map