capable-kit 0.0.1-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai-sdk.d.mts +40 -0
- package/dist/ai-sdk.mjs +58 -0
- package/dist/ai-sdk.mjs.map +1 -0
- package/dist/app.d.mts +2 -0
- package/dist/app.mjs +2 -0
- package/dist/bin.d.mts +1 -0
- package/dist/bin.mjs +447 -0
- package/dist/bin.mjs.map +1 -0
- package/dist/cli.d.mts +45 -0
- package/dist/cli.mjs +2 -0
- package/dist/core.d.mts +3 -0
- package/dist/core.mjs +3 -0
- package/dist/eve.d.mts +28 -0
- package/dist/eve.mjs +61 -0
- package/dist/eve.mjs.map +1 -0
- package/dist/http.d.mts +2 -0
- package/dist/http.mjs +2 -0
- package/dist/index-BuXwkN8G.d.mts +42 -0
- package/dist/index-C9ZThFPN.d.mts +125 -0
- package/dist/index-DLcYNpfo.d.mts +252 -0
- package/dist/index-u9ZOETR5.d.mts +57 -0
- package/dist/index.d.mts +4 -0
- package/dist/index.mjs +4 -0
- package/dist/mcp.d.mts +36 -0
- package/dist/mcp.mjs +140 -0
- package/dist/mcp.mjs.map +1 -0
- package/dist/projection-Cgq2u0Wt.mjs +18 -0
- package/dist/projection-Cgq2u0Wt.mjs.map +1 -0
- package/dist/server.d.mts +2 -0
- package/dist/server.mjs +82 -0
- package/dist/server.mjs.map +1 -0
- package/dist/src-CT4fbWqb.mjs +455 -0
- package/dist/src-CT4fbWqb.mjs.map +1 -0
- package/dist/src-CvWOGyGW.mjs +438 -0
- package/dist/src-CvWOGyGW.mjs.map +1 -0
- package/dist/src-DX-_J6l2.mjs +539 -0
- package/dist/src-DX-_J6l2.mjs.map +1 -0
- package/dist/src-DlSJtEhv.mjs +441 -0
- package/dist/src-DlSJtEhv.mjs.map +1 -0
- package/dist/subscription-CBnnIU42.d.mts +18 -0
- package/package.json +35 -0
|
@@ -0,0 +1,539 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
//#region packages/core/src/errors.ts
|
|
3
|
+
const CAPABILITY_ERRORS_SYMBOL = Symbol.for("capable.capability-errors");
|
|
4
|
+
const CAPABILITY_ERROR_DEFINITIONS_SYMBOL = Symbol.for("capable.capability-error-definitions");
|
|
5
|
+
var CapableError = class extends Error {
|
|
6
|
+
code;
|
|
7
|
+
status;
|
|
8
|
+
data;
|
|
9
|
+
constructor(code, options = {}) {
|
|
10
|
+
super(options.message ?? code, { cause: options.cause });
|
|
11
|
+
this.name = "CapableError";
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.status = options.status;
|
|
14
|
+
this.data = options.data;
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
function defineErrors(definitions) {
|
|
18
|
+
const frozenDefinitions = Object.freeze({ ...definitions });
|
|
19
|
+
const result = {};
|
|
20
|
+
for (const [code, definition] of Object.entries(frozenDefinitions)) {
|
|
21
|
+
const create = ((first, second) => {
|
|
22
|
+
const hasData = definition.data !== void 0;
|
|
23
|
+
const data = hasData ? first : void 0;
|
|
24
|
+
const options = hasData ? second : first;
|
|
25
|
+
return new CapableError(code, {
|
|
26
|
+
...definition.message ? { message: definition.message } : {},
|
|
27
|
+
...typeof definition.status === "number" ? { status: definition.status } : {},
|
|
28
|
+
...hasData ? { data } : {},
|
|
29
|
+
...options && typeof options === "object" && "cause" in options ? { cause: options.cause } : {}
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
Object.defineProperties(create, {
|
|
33
|
+
code: {
|
|
34
|
+
value: code,
|
|
35
|
+
enumerable: true
|
|
36
|
+
},
|
|
37
|
+
definition: {
|
|
38
|
+
value: definition,
|
|
39
|
+
enumerable: true
|
|
40
|
+
},
|
|
41
|
+
is: { value: (error) => error instanceof Error && "code" in error && error.code === code }
|
|
42
|
+
});
|
|
43
|
+
result[code] = Object.freeze(create);
|
|
44
|
+
}
|
|
45
|
+
Object.defineProperties(result, {
|
|
46
|
+
[CAPABILITY_ERRORS_SYMBOL]: { value: true },
|
|
47
|
+
[CAPABILITY_ERROR_DEFINITIONS_SYMBOL]: { value: frozenDefinitions }
|
|
48
|
+
});
|
|
49
|
+
return Object.freeze(result);
|
|
50
|
+
}
|
|
51
|
+
function errorDefinitions(errors) {
|
|
52
|
+
return errors[CAPABILITY_ERROR_DEFINITIONS_SYMBOL];
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region packages/core/src/subscription.ts
|
|
56
|
+
/**
|
|
57
|
+
* Turn an invalidation source into a stream of complete replacement snapshots.
|
|
58
|
+
*
|
|
59
|
+
* The invalidation iterator is pulled before the first snapshot is read. A
|
|
60
|
+
* change racing with that read therefore causes another snapshot rather than
|
|
61
|
+
* being missed.
|
|
62
|
+
*/
|
|
63
|
+
async function* watchQuery(options) {
|
|
64
|
+
if (options.signal?.aborted) return;
|
|
65
|
+
const iterator = options.invalidations()[Symbol.asyncIterator]();
|
|
66
|
+
let pending = nextHandled(iterator);
|
|
67
|
+
try {
|
|
68
|
+
yield await options.snapshot();
|
|
69
|
+
while (!options.signal?.aborted) {
|
|
70
|
+
if ((await pending).done) return;
|
|
71
|
+
pending = nextHandled(iterator);
|
|
72
|
+
yield await options.snapshot();
|
|
73
|
+
}
|
|
74
|
+
} finally {
|
|
75
|
+
await iterator.return?.();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function nextHandled(iterator) {
|
|
79
|
+
const pending = iterator.next();
|
|
80
|
+
pending.catch(() => void 0);
|
|
81
|
+
return pending;
|
|
82
|
+
}
|
|
83
|
+
function deferred() {
|
|
84
|
+
let resolve;
|
|
85
|
+
let reject;
|
|
86
|
+
return {
|
|
87
|
+
promise: new Promise((onResolve, onReject) => {
|
|
88
|
+
resolve = onResolve;
|
|
89
|
+
reject = onReject;
|
|
90
|
+
}),
|
|
91
|
+
resolve,
|
|
92
|
+
reject
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
function createDemandIterator(produce) {
|
|
96
|
+
const demands = [];
|
|
97
|
+
const demandWaiters = [];
|
|
98
|
+
const cleanups = [];
|
|
99
|
+
let activeDemand;
|
|
100
|
+
let started = false;
|
|
101
|
+
let closed = false;
|
|
102
|
+
let failure;
|
|
103
|
+
let hasFailure = false;
|
|
104
|
+
let failureDelivered = false;
|
|
105
|
+
let task;
|
|
106
|
+
const wakeProducer = () => demandWaiters.shift()?.();
|
|
107
|
+
const finishPending = () => {
|
|
108
|
+
for (const demand of demands.splice(0)) if (hasFailure && !failureDelivered) {
|
|
109
|
+
failureDelivered = true;
|
|
110
|
+
demand.reject(failure);
|
|
111
|
+
} else demand.resolve({
|
|
112
|
+
done: true,
|
|
113
|
+
value: void 0
|
|
114
|
+
});
|
|
115
|
+
};
|
|
116
|
+
const stream = {
|
|
117
|
+
async waitForDemand() {
|
|
118
|
+
while (!closed && demands.length === 0) await new Promise((resolve) => demandWaiters.push(resolve));
|
|
119
|
+
if (closed) return false;
|
|
120
|
+
activeDemand = demands.shift();
|
|
121
|
+
return Boolean(activeDemand);
|
|
122
|
+
},
|
|
123
|
+
emit(value) {
|
|
124
|
+
const demand = activeDemand;
|
|
125
|
+
activeDemand = void 0;
|
|
126
|
+
demand?.resolve({
|
|
127
|
+
done: false,
|
|
128
|
+
value
|
|
129
|
+
});
|
|
130
|
+
},
|
|
131
|
+
complete() {
|
|
132
|
+
closed = true;
|
|
133
|
+
activeDemand?.resolve({
|
|
134
|
+
done: true,
|
|
135
|
+
value: void 0
|
|
136
|
+
});
|
|
137
|
+
activeDemand = void 0;
|
|
138
|
+
finishPending();
|
|
139
|
+
wakeProducer();
|
|
140
|
+
},
|
|
141
|
+
fail(error) {
|
|
142
|
+
failure = error;
|
|
143
|
+
hasFailure = true;
|
|
144
|
+
closed = true;
|
|
145
|
+
const demand = activeDemand;
|
|
146
|
+
activeDemand = void 0;
|
|
147
|
+
if (demand) {
|
|
148
|
+
failureDelivered = true;
|
|
149
|
+
demand.reject(error);
|
|
150
|
+
}
|
|
151
|
+
finishPending();
|
|
152
|
+
wakeProducer();
|
|
153
|
+
},
|
|
154
|
+
onCancel(cleanup) {
|
|
155
|
+
cleanups.push(cleanup);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
const start = () => {
|
|
159
|
+
if (started) return;
|
|
160
|
+
started = true;
|
|
161
|
+
task = produce(stream).then(() => {
|
|
162
|
+
if (!closed) stream.complete();
|
|
163
|
+
}, (error) => stream.fail(error));
|
|
164
|
+
};
|
|
165
|
+
return {
|
|
166
|
+
[Symbol.asyncIterator]() {
|
|
167
|
+
return this;
|
|
168
|
+
},
|
|
169
|
+
next() {
|
|
170
|
+
if (hasFailure && !failureDelivered) {
|
|
171
|
+
failureDelivered = true;
|
|
172
|
+
return Promise.reject(failure);
|
|
173
|
+
}
|
|
174
|
+
if (closed) return Promise.resolve({
|
|
175
|
+
done: true,
|
|
176
|
+
value: void 0
|
|
177
|
+
});
|
|
178
|
+
const demand = deferred();
|
|
179
|
+
demands.push(demand);
|
|
180
|
+
start();
|
|
181
|
+
wakeProducer();
|
|
182
|
+
return demand.promise;
|
|
183
|
+
},
|
|
184
|
+
async return() {
|
|
185
|
+
if (!closed) {
|
|
186
|
+
closed = true;
|
|
187
|
+
wakeProducer();
|
|
188
|
+
activeDemand?.resolve({
|
|
189
|
+
done: true,
|
|
190
|
+
value: void 0
|
|
191
|
+
});
|
|
192
|
+
activeDemand = void 0;
|
|
193
|
+
finishPending();
|
|
194
|
+
for (const cleanup of cleanups) await cleanup();
|
|
195
|
+
}
|
|
196
|
+
await task;
|
|
197
|
+
return {
|
|
198
|
+
done: true,
|
|
199
|
+
value: void 0
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
//#endregion
|
|
205
|
+
//#region packages/core/src/schema.ts
|
|
206
|
+
async function parseSchema(schema, value) {
|
|
207
|
+
const result = await schema.safeParseAsync(value);
|
|
208
|
+
if (!result.success) throw new SchemaValidationError(result.error.issues);
|
|
209
|
+
return result.data;
|
|
210
|
+
}
|
|
211
|
+
function schemaToJsonSchema(schema) {
|
|
212
|
+
const projected = z.toJSONSchema(schema, { unrepresentable: "any" });
|
|
213
|
+
return JSON.parse(JSON.stringify(projected));
|
|
214
|
+
}
|
|
215
|
+
var SchemaValidationError = class extends Error {
|
|
216
|
+
issues;
|
|
217
|
+
constructor(issues) {
|
|
218
|
+
super("Schema validation failed");
|
|
219
|
+
this.name = "SchemaValidationError";
|
|
220
|
+
this.issues = issues;
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
//#endregion
|
|
224
|
+
//#region packages/core/src/capability.ts
|
|
225
|
+
const CAPABILITY_SYMBOL = Symbol.for("capable.capability");
|
|
226
|
+
const NO_ERRORS$1 = defineErrors({});
|
|
227
|
+
function capabilityWithContext() {
|
|
228
|
+
return createCapability;
|
|
229
|
+
}
|
|
230
|
+
const capability = Object.assign(function capability(config) {
|
|
231
|
+
return config === void 0 ? createCapability : createCapability(config);
|
|
232
|
+
}, { withContext: capabilityWithContext });
|
|
233
|
+
function createCapability(config) {
|
|
234
|
+
if (!config.id) throw new Error("Capability id must not be empty");
|
|
235
|
+
if (config.subscribe && config.effect !== "read") throw new Error(`Capability "${config.id}" must declare effect "read" to subscribe`);
|
|
236
|
+
if (typeof config.handler !== "function") throw new Error(`Capability "${config.id}" requires a handler`);
|
|
237
|
+
return Object.freeze({
|
|
238
|
+
[CAPABILITY_SYMBOL]: true,
|
|
239
|
+
id: config.id,
|
|
240
|
+
...config.title ? { title: config.title } : {},
|
|
241
|
+
...config.description ? { description: config.description } : {},
|
|
242
|
+
deprecated: config.deprecated === true,
|
|
243
|
+
...config.effect ? { effect: config.effect } : {},
|
|
244
|
+
...config.input ? { input: config.input } : {},
|
|
245
|
+
...config.output ? { output: config.output } : {},
|
|
246
|
+
errors: config.errors ?? NO_ERRORS$1,
|
|
247
|
+
middleware: Object.freeze([...config.middleware ?? []]),
|
|
248
|
+
meta: Object.freeze({ ...config.meta ?? {} }),
|
|
249
|
+
handler: config.handler,
|
|
250
|
+
...config.subscribe ? { subscribe: config.subscribe } : {},
|
|
251
|
+
...config.toMarkdown ? { toMarkdown: config.toMarkdown } : {}
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
async function executeCapability(capability, options) {
|
|
255
|
+
return executeLocatedCapability(Object.freeze({
|
|
256
|
+
path: Object.freeze([]),
|
|
257
|
+
groups: Object.freeze([]),
|
|
258
|
+
groupPaths: Object.freeze([]),
|
|
259
|
+
capability,
|
|
260
|
+
errors: Object.freeze({ ...errorDefinitions(capability.errors) }),
|
|
261
|
+
middleware: capability.middleware
|
|
262
|
+
}), options.input ?? {}, {
|
|
263
|
+
context: options.context,
|
|
264
|
+
...options.signal ? { signal: options.signal } : {}
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
async function executeLocatedCapability(located, input, options) {
|
|
268
|
+
const parsedInput = await parseCapabilityInput(located.capability, input);
|
|
269
|
+
let rawOutput;
|
|
270
|
+
try {
|
|
271
|
+
rawOutput = await runCapabilityMiddleware(located.middleware, {
|
|
272
|
+
input: parsedInput,
|
|
273
|
+
context: options.context,
|
|
274
|
+
...options.signal ? { signal: options.signal } : {}
|
|
275
|
+
}, () => located.capability.handler({
|
|
276
|
+
input: parsedInput,
|
|
277
|
+
context: options.context,
|
|
278
|
+
...options.signal ? { signal: options.signal } : {}
|
|
279
|
+
}));
|
|
280
|
+
} catch (error) {
|
|
281
|
+
throw await normalizeCapabilityError(located, error);
|
|
282
|
+
}
|
|
283
|
+
return validateCapabilityOutput(located.capability, rawOutput);
|
|
284
|
+
}
|
|
285
|
+
function subscribeCapability(capability, options) {
|
|
286
|
+
return subscribeLocatedCapability(Object.freeze({
|
|
287
|
+
path: Object.freeze([]),
|
|
288
|
+
groups: Object.freeze([]),
|
|
289
|
+
groupPaths: Object.freeze([]),
|
|
290
|
+
capability,
|
|
291
|
+
errors: Object.freeze({ ...errorDefinitions(capability.errors) }),
|
|
292
|
+
middleware: capability.middleware
|
|
293
|
+
}), options.input ?? {}, {
|
|
294
|
+
context: options.context,
|
|
295
|
+
...options.signal ? { signal: options.signal } : {}
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
function subscribeLocatedCapability(located, input, options) {
|
|
299
|
+
const subscriber = located.capability.subscribe;
|
|
300
|
+
if (!subscriber) throw new Error(`Capability "${located.capability.id}" is not subscribable`);
|
|
301
|
+
return createDemandIterator(async (stream) => {
|
|
302
|
+
let cleanupSource = async (_abort) => {};
|
|
303
|
+
let parsedInput;
|
|
304
|
+
try {
|
|
305
|
+
parsedInput = await parseCapabilityInput(located.capability, input);
|
|
306
|
+
} catch (error) {
|
|
307
|
+
stream.fail(error);
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
try {
|
|
311
|
+
const controller = new AbortController();
|
|
312
|
+
const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
|
|
313
|
+
let iterator;
|
|
314
|
+
let cleaned = false;
|
|
315
|
+
cleanupSource = async (abort) => {
|
|
316
|
+
if (cleaned) return;
|
|
317
|
+
cleaned = true;
|
|
318
|
+
if (abort) controller.abort();
|
|
319
|
+
await iterator?.return?.();
|
|
320
|
+
};
|
|
321
|
+
stream.onCancel(() => cleanupSource(true));
|
|
322
|
+
let emitted = false;
|
|
323
|
+
await runCapabilityMiddleware(located.middleware, {
|
|
324
|
+
input: parsedInput,
|
|
325
|
+
context: options.context,
|
|
326
|
+
signal
|
|
327
|
+
}, async () => {
|
|
328
|
+
const iterable = subscriber({
|
|
329
|
+
input: parsedInput,
|
|
330
|
+
context: options.context,
|
|
331
|
+
signal
|
|
332
|
+
});
|
|
333
|
+
if (!iterable || typeof iterable !== "object" || !(Symbol.asyncIterator in iterable)) throw new CapableError("INTERNAL_SERVER_ERROR", { message: `Capability "${located.capability.id}" subscribe must return an AsyncIterable` });
|
|
334
|
+
const sourceIterator = iterable[Symbol.asyncIterator]();
|
|
335
|
+
iterator = sourceIterator;
|
|
336
|
+
while (await stream.waitForDemand()) {
|
|
337
|
+
const result = await sourceIterator.next();
|
|
338
|
+
if (result.done) {
|
|
339
|
+
if (!emitted) throw emptySubscriptionError(located.capability);
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
emitted = true;
|
|
343
|
+
stream.emit(await validateCapabilityOutput(located.capability, result.value));
|
|
344
|
+
}
|
|
345
|
+
});
|
|
346
|
+
if (!emitted) throw emptySubscriptionError(located.capability);
|
|
347
|
+
await cleanupSource(false);
|
|
348
|
+
stream.complete();
|
|
349
|
+
} catch (error) {
|
|
350
|
+
await cleanupSource(false);
|
|
351
|
+
stream.fail(await normalizeCapabilityError(located, error));
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
function emptySubscriptionError(capability) {
|
|
356
|
+
return new CapableError("INTERNAL_SERVER_ERROR", { message: `Capability "${capability.id}" subscription completed before yielding a value` });
|
|
357
|
+
}
|
|
358
|
+
async function validateCapabilityOutput(capability, rawOutput) {
|
|
359
|
+
if (!capability.output) return rawOutput;
|
|
360
|
+
try {
|
|
361
|
+
return await parseSchema(capability.output, rawOutput);
|
|
362
|
+
} catch (error) {
|
|
363
|
+
if (!(error instanceof SchemaValidationError)) throw error;
|
|
364
|
+
throw new CapableError("INTERNAL_SERVER_ERROR", {
|
|
365
|
+
message: `Capability "${capability.id}" output validation failed`,
|
|
366
|
+
data: { issues: error.issues },
|
|
367
|
+
cause: error
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
async function parseCapabilityInput(capability, input) {
|
|
372
|
+
if (!capability.input) {
|
|
373
|
+
if (input === void 0) return {};
|
|
374
|
+
if (isRecord$1(input) && Object.keys(input).length === 0) return {};
|
|
375
|
+
throw new CapableError("BAD_REQUEST", {
|
|
376
|
+
status: 400,
|
|
377
|
+
message: `Capability "${capability.id}" does not accept input`
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
try {
|
|
381
|
+
const parsed = await parseSchema(capability.input, input);
|
|
382
|
+
if (!isRecord$1(parsed)) throw new CapableError("INTERNAL_SERVER_ERROR", { message: `Capability "${capability.id}" input schema must produce an object` });
|
|
383
|
+
return parsed;
|
|
384
|
+
} catch (error) {
|
|
385
|
+
if (error instanceof CapableError) throw error;
|
|
386
|
+
if (!(error instanceof SchemaValidationError)) throw error;
|
|
387
|
+
throw new CapableError("BAD_REQUEST", {
|
|
388
|
+
status: 400,
|
|
389
|
+
message: `Invalid input for Capability "${capability.id}"`,
|
|
390
|
+
data: { issues: error.issues },
|
|
391
|
+
cause: error
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
async function runCapabilityMiddleware(middleware, args, handler) {
|
|
396
|
+
async function dispatch(index) {
|
|
397
|
+
const current = middleware[index];
|
|
398
|
+
if (!current) return handler();
|
|
399
|
+
let called = false;
|
|
400
|
+
return current({
|
|
401
|
+
...args,
|
|
402
|
+
next: async () => {
|
|
403
|
+
if (called) throw new CapableError("INTERNAL_SERVER_ERROR", { message: "Capability middleware called next() more than once" });
|
|
404
|
+
called = true;
|
|
405
|
+
return dispatch(index + 1);
|
|
406
|
+
}
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
return dispatch(0);
|
|
410
|
+
}
|
|
411
|
+
async function normalizeCapabilityError(located, error) {
|
|
412
|
+
if (!(error instanceof CapableError)) return new CapableError("INTERNAL_SERVER_ERROR", { cause: error });
|
|
413
|
+
const contract = located.errors[error.code];
|
|
414
|
+
if (!contract) return new CapableError("INTERNAL_SERVER_ERROR", { cause: error });
|
|
415
|
+
let data = error.data;
|
|
416
|
+
if (contract.data) try {
|
|
417
|
+
data = await parseSchema(contract.data, error.data);
|
|
418
|
+
} catch (cause) {
|
|
419
|
+
throw new CapableError("INTERNAL_SERVER_ERROR", {
|
|
420
|
+
message: `Invalid error data for ${error.code}`,
|
|
421
|
+
cause
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
return new CapableError(error.code, {
|
|
425
|
+
...typeof contract.status === "number" ? { status: contract.status } : {},
|
|
426
|
+
message: contract.message ?? error.code,
|
|
427
|
+
data,
|
|
428
|
+
cause: error
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
function isCapability(value) {
|
|
432
|
+
return Boolean(value && typeof value === "object" && value[CAPABILITY_SYMBOL] === true);
|
|
433
|
+
}
|
|
434
|
+
function isRecord$1(value) {
|
|
435
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
436
|
+
}
|
|
437
|
+
//#endregion
|
|
438
|
+
//#region packages/core/src/application.ts
|
|
439
|
+
const CAPABILITY_GROUP_SYMBOL = Symbol.for("capable.capability-group");
|
|
440
|
+
const APPLICATION_SYMBOL = Symbol.for("capable.application");
|
|
441
|
+
const NO_ERRORS = defineErrors({});
|
|
442
|
+
function group(config) {
|
|
443
|
+
assertCapabilityTree(config.capabilities, "group.capabilities");
|
|
444
|
+
return Object.freeze({
|
|
445
|
+
[CAPABILITY_GROUP_SYMBOL]: true,
|
|
446
|
+
...config.title ? { title: config.title } : {},
|
|
447
|
+
...config.description ? { description: config.description } : {},
|
|
448
|
+
errors: config.errors ?? NO_ERRORS,
|
|
449
|
+
middleware: Object.freeze([...config.middleware ?? []]),
|
|
450
|
+
meta: Object.freeze({ ...config.meta ?? {} }),
|
|
451
|
+
capabilities: config.capabilities
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
function defineApp(config) {
|
|
455
|
+
assertCapabilityTree(config.capabilities, "application.capabilities");
|
|
456
|
+
const located = locateCapabilities(config.capabilities);
|
|
457
|
+
assertUniqueCapabilities(located);
|
|
458
|
+
return Object.freeze({
|
|
459
|
+
[APPLICATION_SYMBOL]: true,
|
|
460
|
+
name: config.name ?? "Capable application",
|
|
461
|
+
version: config.version ?? "0.0.0",
|
|
462
|
+
...config.description ? { description: config.description } : {},
|
|
463
|
+
capabilities: config.capabilities,
|
|
464
|
+
locatedCapabilities: Object.freeze(located)
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
function locateCapabilities(tree, path = [], groups = [], groupPaths = [], inheritedErrors = {}, inheritedMiddleware = []) {
|
|
468
|
+
const located = [];
|
|
469
|
+
for (const [key, value] of Object.entries(tree)) {
|
|
470
|
+
const nextPath = [...path, key];
|
|
471
|
+
if (isCapability(value)) {
|
|
472
|
+
const capabilityErrors = errorDefinitions(value.errors);
|
|
473
|
+
assertAdditionalErrors(inheritedErrors, capabilityErrors, `Capability "${value.id}"`);
|
|
474
|
+
located.push(Object.freeze({
|
|
475
|
+
path: Object.freeze(nextPath),
|
|
476
|
+
groups: Object.freeze([...groups]),
|
|
477
|
+
groupPaths: Object.freeze([...groupPaths]),
|
|
478
|
+
capability: value,
|
|
479
|
+
errors: Object.freeze({
|
|
480
|
+
...inheritedErrors,
|
|
481
|
+
...capabilityErrors
|
|
482
|
+
}),
|
|
483
|
+
middleware: Object.freeze([...inheritedMiddleware, ...value.middleware])
|
|
484
|
+
}));
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
if (isCapabilityGroup(value)) {
|
|
488
|
+
const groupErrors = errorDefinitions(value.errors);
|
|
489
|
+
assertAdditionalErrors(inheritedErrors, groupErrors, `Group at "${nextPath.join(".")}"`);
|
|
490
|
+
located.push(...locateCapabilities(value.capabilities, nextPath, [...groups, value], [...groupPaths, nextPath], {
|
|
491
|
+
...inheritedErrors,
|
|
492
|
+
...groupErrors
|
|
493
|
+
}, [...inheritedMiddleware, ...value.middleware]));
|
|
494
|
+
continue;
|
|
495
|
+
}
|
|
496
|
+
located.push(...locateCapabilities(value, nextPath, groups, groupPaths, inheritedErrors, inheritedMiddleware));
|
|
497
|
+
}
|
|
498
|
+
return located;
|
|
499
|
+
}
|
|
500
|
+
function assertCapabilityTree(value, label) {
|
|
501
|
+
if (!isRecord(value)) throw new Error(`${label} must be a named object tree; arrays are not supported`);
|
|
502
|
+
for (const [key, child] of Object.entries(value)) {
|
|
503
|
+
if (!key) throw new Error(`${label} has an empty key`);
|
|
504
|
+
if (key === "then") throw new Error(`${label} uses reserved key "then"`);
|
|
505
|
+
if (isCapability(child)) continue;
|
|
506
|
+
if (isCapabilityGroup(child)) {
|
|
507
|
+
assertCapabilityTree(child.capabilities, `${label}.${key}.capabilities`);
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
assertCapabilityTree(child, `${label}.${key}`);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
function assertUniqueCapabilities(located) {
|
|
514
|
+
const ids = /* @__PURE__ */ new Map();
|
|
515
|
+
const objects = /* @__PURE__ */ new Map();
|
|
516
|
+
for (const entry of located) {
|
|
517
|
+
const path = entry.path.join(".");
|
|
518
|
+
const previousIdPath = ids.get(entry.capability.id);
|
|
519
|
+
if (previousIdPath) throw new Error(`Duplicate Capability id "${entry.capability.id}" at "${previousIdPath}" and "${path}"`);
|
|
520
|
+
const previousObjectPath = objects.get(entry.capability);
|
|
521
|
+
if (previousObjectPath) throw new Error(`Capability "${entry.capability.id}" is included at both "${previousObjectPath}" and "${path}"`);
|
|
522
|
+
ids.set(entry.capability.id, path);
|
|
523
|
+
objects.set(entry.capability, path);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
function assertAdditionalErrors(inherited, additional, label) {
|
|
527
|
+
const duplicate = Object.keys(additional).find((code) => code in inherited);
|
|
528
|
+
if (duplicate) throw new Error(`${label} redeclares inherited error ${duplicate}`);
|
|
529
|
+
}
|
|
530
|
+
function isCapabilityGroup(value) {
|
|
531
|
+
return Boolean(value && typeof value === "object" && value[CAPABILITY_GROUP_SYMBOL] === true);
|
|
532
|
+
}
|
|
533
|
+
function isRecord(value) {
|
|
534
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
535
|
+
}
|
|
536
|
+
//#endregion
|
|
537
|
+
export { CAPABILITY_ERRORS_SYMBOL as _, isCapabilityGroup as a, executeCapability as c, subscribeCapability as d, subscribeLocatedCapability as f, watchQuery as g, schemaToJsonSchema as h, group as i, executeLocatedCapability as l, parseSchema as m, CAPABILITY_GROUP_SYMBOL as n, CAPABILITY_SYMBOL as o, SchemaValidationError as p, defineApp as r, capability as s, APPLICATION_SYMBOL as t, isCapability as u, CapableError as v, defineErrors as y };
|
|
538
|
+
|
|
539
|
+
//# sourceMappingURL=src-DX-_J6l2.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-DX-_J6l2.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 { z } from \"zod\";\n\nexport type AnySchema = z.ZodType;\nexport type AnyObjectSchema = z.ZodObject;\n\nexport type InferSchemaInput<TSchema> = TSchema extends AnySchema\n ? z.input<TSchema>\n : never;\n\nexport type InferSchemaOutput<TSchema> = TSchema extends AnySchema\n ? z.output<TSchema>\n : never;\n\nexport async function parseSchema<TSchema extends AnySchema>(\n schema: TSchema,\n value: unknown,\n): Promise<InferSchemaOutput<TSchema>> {\n const result = await schema.safeParseAsync(value);\n if (!result.success) {\n throw new SchemaValidationError(result.error.issues);\n }\n return result.data as InferSchemaOutput<TSchema>;\n}\n\nexport function schemaToJsonSchema(schema: AnySchema): Readonly<Record<string, unknown>> {\n const projected = z.toJSONSchema(schema, { unrepresentable: \"any\" });\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 z.core.$ZodIssue[];\n\n constructor(issues: readonly z.core.$ZodIssue[]) {\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 const TInput extends AnyObjectSchema | undefined = undefined,\n const 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 const TInput extends AnyObjectSchema | undefined = undefined,\n const 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 const 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 const 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,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,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