capable-kit 0.0.1-alpha.8 → 0.1.0-alpha.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +385 -0
- package/LICENSE +21 -0
- package/README.md +12 -0
- package/dist/ai-sdk.d.mts +3 -3
- package/dist/ai-sdk.mjs +9 -7
- package/dist/ai-sdk.mjs.map +1 -1
- package/dist/app.d.mts +2 -2
- package/dist/app.mjs +2 -2
- package/dist/bin.mjs +19 -15
- package/dist/bin.mjs.map +1 -1
- package/dist/cli.d.mts +9 -1
- package/dist/cli.mjs +1 -1
- package/dist/core.d.mts +3 -3
- package/dist/core.mjs +2 -2
- package/dist/eve.d.mts +92 -9
- package/dist/eve.mjs +606 -26
- package/dist/eve.mjs.map +1 -1
- package/dist/http.d.mts +1 -1
- package/dist/http.mjs +1 -1
- package/dist/{index-_qKFfWV4.d.mts → index-BIO_hbXJ.d.mts} +69 -26
- package/dist/{index-hdH_K5Zc.d.mts → index-C0tU5Y2n.d.mts} +4 -4
- package/dist/{index-Dl4NK9G0.d.mts → index-CwvjDizW.d.mts} +5 -3
- package/dist/{index-F4ba_olD.d.mts → index-F_eaksy8.d.mts} +58 -17
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +3 -3
- package/dist/mcp.d.mts +19 -4
- package/dist/mcp.mjs +2 -2
- package/dist/{mount-CEFAplR5.mjs → mount-pvIaehZC.mjs} +159 -107
- package/dist/mount-pvIaehZC.mjs.map +1 -0
- package/dist/react-query.d.mts +2 -2
- package/dist/react-query.mjs +1 -1
- package/dist/react-query.mjs.map +1 -1
- package/dist/runtime-support.d.mts +1 -1
- package/dist/runtime-support.mjs +3 -3
- package/dist/server.d.mts +1 -1
- package/dist/server.mjs +1 -1
- package/dist/{src-rkr5j_NH.mjs → src-Bk3lEhI7.mjs} +63 -25
- package/dist/src-Bk3lEhI7.mjs.map +1 -0
- package/dist/src-C2OEkZ3c.mjs +760 -0
- package/dist/src-C2OEkZ3c.mjs.map +1 -0
- package/dist/{src-BWxDO2Ua.mjs → src-DFrxQ_S6.mjs} +9 -7
- package/dist/src-DFrxQ_S6.mjs.map +1 -0
- package/dist/{src-D_0PIhqq.mjs → src-DklM1g7V.mjs} +69 -40
- package/dist/src-DklM1g7V.mjs.map +1 -0
- package/dist/{src-D-cm2gQ6.mjs → src-TCQGaWar.mjs} +119 -45
- package/dist/src-TCQGaWar.mjs.map +1 -0
- package/dist/{subscription-B-auXJbm.d.mts → subscription-fVgS4T8P.d.mts} +2 -2
- package/dist/swr.d.mts +2 -2
- package/dist/swr.mjs +1 -1
- package/dist/swr.mjs.map +1 -1
- package/docs/CONTEXT.md +44 -22
- package/docs/README.md +3 -0
- package/docs/internal/README.md +3 -0
- package/docs/internal/adr/0001-capability-is-the-semantic-boundary.md +1 -1
- package/docs/internal/adr/0003-capability-reference-customization.md +68 -0
- package/docs/internal/architecture.md +31 -17
- package/docs/internal/capability-first-model.md +126 -17
- package/docs/internal/eve-recovery-validation.md +87 -0
- package/docs/internal/feedback/v-ray/README.md +258 -0
- package/docs/internal/feedback/v-ray/inference.mjs +43 -0
- package/docs/internal/feedback/v-ray/reproduce.mjs +36 -0
- package/docs/internal/implementation-friction.md +445 -1
- package/docs/internal/releases.md +79 -0
- package/docs/site/capable-orpc-and-trpc.mdx +2 -2
- package/docs/site/concepts/apps.mdx +7 -1
- package/docs/site/concepts/architecture.mdx +9 -1
- package/docs/site/concepts/capabilities.mdx +41 -4
- package/docs/site/concepts/errors.mdx +26 -4
- package/docs/site/concepts/presentations.mdx +20 -0
- package/docs/site/hosting/standalone-server.mdx +2 -0
- package/docs/site/patterns/composition.mdx +152 -8
- package/docs/site/patterns/remote-apps.mdx +29 -3
- package/docs/site/patterns/subscriptions.mdx +79 -32
- package/docs/site/quickstart.mdx +3 -2
- package/docs/site/reference/packages-and-entry-points.mdx +52 -4
- package/docs/site/reference/the-cap-cli.mdx +2 -2
- package/docs/site/surfaces/cli.mdx +44 -0
- package/docs/site/surfaces/eve.mdx +67 -18
- package/docs/site/surfaces/mcp.mdx +84 -2
- package/docs/site/surfaces/typescript.mdx +3 -3
- package/package-docs.mjs +3 -0
- package/package.json +17 -12
- package/src/bin.ts +0 -0
- package/src/index.test.ts +2 -1
- package/src/index.ts +8 -1
- package/src/package.test.ts +15 -0
- package/dist/mount-CEFAplR5.mjs.map +0 -1
- package/dist/src-BWxDO2Ua.mjs.map +0 -1
- package/dist/src-D-cm2gQ6.mjs.map +0 -1
- package/dist/src-D_0PIhqq.mjs.map +0 -1
- package/dist/src-betOfnDL.mjs +0 -481
- package/dist/src-betOfnDL.mjs.map +0 -1
- package/dist/src-rkr5j_NH.mjs.map +0 -1
|
@@ -50,6 +50,28 @@ function defineErrors(definitions) {
|
|
|
50
50
|
function errorDefinitions(errors) {
|
|
51
51
|
return errors[CAPABILITY_ERROR_DEFINITIONS_SYMBOL];
|
|
52
52
|
}
|
|
53
|
+
const PUBLIC_ERRORS_SYMBOL = Symbol.for("capable.public-errors");
|
|
54
|
+
function publicErrors() {
|
|
55
|
+
const store = globalThis;
|
|
56
|
+
const existing = store[PUBLIC_ERRORS_SYMBOL];
|
|
57
|
+
if (existing instanceof WeakSet) return existing;
|
|
58
|
+
const created = /* @__PURE__ */ new WeakSet();
|
|
59
|
+
store[PUBLIC_ERRORS_SYMBOL] = created;
|
|
60
|
+
return created;
|
|
61
|
+
}
|
|
62
|
+
/** @internal Mark an error as validated for external wire serialization. */
|
|
63
|
+
function markPublicError(error) {
|
|
64
|
+
publicErrors().add(error);
|
|
65
|
+
return error;
|
|
66
|
+
}
|
|
67
|
+
/** @internal Revoke wire-serialization permission when an error escapes an unvalidated seam. */
|
|
68
|
+
function unmarkPublicError(error) {
|
|
69
|
+
if (error && typeof error === "object") publicErrors().delete(error);
|
|
70
|
+
}
|
|
71
|
+
/** @internal True only for errors explicitly validated or created at a public boundary. */
|
|
72
|
+
function isPublicError(error) {
|
|
73
|
+
return Boolean(error && typeof error === "object" && publicErrors().has(error));
|
|
74
|
+
}
|
|
53
75
|
//#endregion
|
|
54
76
|
//#region packages/core/src/presentation.ts
|
|
55
77
|
const present = Object.freeze({
|
|
@@ -229,8 +251,8 @@ function createDemandIterator(produce) {
|
|
|
229
251
|
const demands = [];
|
|
230
252
|
const demandWaiters = [];
|
|
231
253
|
const cleanups = [];
|
|
254
|
+
const ready = deferred();
|
|
232
255
|
let activeDemand;
|
|
233
|
-
let started = false;
|
|
234
256
|
let closed = false;
|
|
235
257
|
let failure;
|
|
236
258
|
let hasFailure = false;
|
|
@@ -261,7 +283,11 @@ function createDemandIterator(produce) {
|
|
|
261
283
|
value
|
|
262
284
|
});
|
|
263
285
|
},
|
|
286
|
+
markReady() {
|
|
287
|
+
ready.resolve();
|
|
288
|
+
},
|
|
264
289
|
complete() {
|
|
290
|
+
stream.markReady();
|
|
265
291
|
closed = true;
|
|
266
292
|
activeDemand?.resolve({
|
|
267
293
|
done: true,
|
|
@@ -272,6 +298,7 @@ function createDemandIterator(produce) {
|
|
|
272
298
|
wakeProducer();
|
|
273
299
|
},
|
|
274
300
|
fail(error) {
|
|
301
|
+
ready.reject(error);
|
|
275
302
|
failure = error;
|
|
276
303
|
hasFailure = true;
|
|
277
304
|
closed = true;
|
|
@@ -288,14 +315,8 @@ function createDemandIterator(produce) {
|
|
|
288
315
|
cleanups.push(cleanup);
|
|
289
316
|
}
|
|
290
317
|
};
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
started = true;
|
|
294
|
-
task = produce(stream).then(() => {
|
|
295
|
-
if (!closed) stream.complete();
|
|
296
|
-
}, (error) => stream.fail(error));
|
|
297
|
-
};
|
|
298
|
-
return {
|
|
318
|
+
ready.promise.catch(() => void 0);
|
|
319
|
+
const iterator = {
|
|
299
320
|
[Symbol.asyncIterator]() {
|
|
300
321
|
return this;
|
|
301
322
|
},
|
|
@@ -310,7 +331,6 @@ function createDemandIterator(produce) {
|
|
|
310
331
|
});
|
|
311
332
|
const demand = deferred();
|
|
312
333
|
demands.push(demand);
|
|
313
|
-
start();
|
|
314
334
|
wakeProducer();
|
|
315
335
|
return demand.promise;
|
|
316
336
|
},
|
|
@@ -333,6 +353,13 @@ function createDemandIterator(produce) {
|
|
|
333
353
|
};
|
|
334
354
|
}
|
|
335
355
|
};
|
|
356
|
+
task = produce(stream).then(() => {
|
|
357
|
+
if (!closed) stream.complete();
|
|
358
|
+
}, (error) => stream.fail(error));
|
|
359
|
+
return {
|
|
360
|
+
iterator,
|
|
361
|
+
ready: ready.promise
|
|
362
|
+
};
|
|
336
363
|
}
|
|
337
364
|
//#endregion
|
|
338
365
|
//#region packages/core/src/schema.ts
|
|
@@ -341,8 +368,18 @@ async function parseSchema(schema, value) {
|
|
|
341
368
|
if (result.issues) throw new SchemaValidationError(result.issues);
|
|
342
369
|
return result.value;
|
|
343
370
|
}
|
|
371
|
+
function missingStandardJsonSchemaMessage(vendor, direction) {
|
|
372
|
+
const missing = `Schema does not implement Standard JSON Schema v1: \`~standard.jsonSchema.${direction}\` is not a function.`;
|
|
373
|
+
const requirement = "@capable/core requires schemas that implement Standard JSON Schema v1.";
|
|
374
|
+
if (vendor === "zod") return `${missing} ${requirement} This schema reports vendor "zod"; if it is a Zod schema, zod >= 4.2 is required.`;
|
|
375
|
+
return `${missing} ${requirement} Update the schema library to a version that implements Standard JSON Schema v1.`;
|
|
376
|
+
}
|
|
344
377
|
function schemaToJsonSchema(schema, direction, options = {}) {
|
|
345
|
-
const
|
|
378
|
+
const standard = schema?.["~standard"];
|
|
379
|
+
const jsonSchema = standard?.jsonSchema;
|
|
380
|
+
const project = jsonSchema?.[direction];
|
|
381
|
+
if (typeof project !== "function") throw new Error(missingStandardJsonSchemaMessage(standard?.vendor, direction));
|
|
382
|
+
const projected = project.call(jsonSchema, {
|
|
346
383
|
target: "draft-2020-12",
|
|
347
384
|
...options.allowUnrepresentable ? { libraryOptions: { unrepresentable: "any" } } : {}
|
|
348
385
|
});
|
|
@@ -367,9 +404,12 @@ const capability = Object.assign(function capability(config) {
|
|
|
367
404
|
return config === void 0 ? createCapability : createCapability(config);
|
|
368
405
|
}, { withContext: capabilityWithContext });
|
|
369
406
|
function createCapability(config) {
|
|
407
|
+
const id = config.id;
|
|
370
408
|
if (!config.id) throw new Error("Capability id must not be empty");
|
|
371
|
-
if (config.subscribe && config.effect !== "read") throw new Error(`Capability "${
|
|
372
|
-
if (typeof config.handler !== "function") throw new Error(`Capability "${
|
|
409
|
+
if (config.subscribe && config.effect !== "read") throw new Error(`Capability "${id}" must declare effect "read" to subscribe`);
|
|
410
|
+
if (config.handler !== void 0 && typeof config.handler !== "function") throw new Error(`Capability "${id}" handler must be a function`);
|
|
411
|
+
if (config.subscribe !== void 0 && typeof config.subscribe !== "function") throw new Error(`Capability "${id}" subscribe must be a function`);
|
|
412
|
+
if (!config.handler && !config.subscribe) throw new Error(`Capability "${id}" requires a handler or subscribe`);
|
|
373
413
|
return Object.freeze({
|
|
374
414
|
[CAPABILITY_SYMBOL]: true,
|
|
375
415
|
id: config.id,
|
|
@@ -382,7 +422,8 @@ function createCapability(config) {
|
|
|
382
422
|
errors: config.errors ?? NO_ERRORS$1,
|
|
383
423
|
middleware: Object.freeze([...config.middleware ?? []]),
|
|
384
424
|
meta: Object.freeze({ ...config.meta ?? {} }),
|
|
385
|
-
|
|
425
|
+
execution: config.handler ? config.subscribe ? "live" : "unary" : "events",
|
|
426
|
+
...config.handler ? { handler: config.handler } : {},
|
|
386
427
|
...config.subscribe ? { subscribe: config.subscribe } : {},
|
|
387
428
|
...config.toPresentation ? { toPresentation: config.toPresentation } : {}
|
|
388
429
|
});
|
|
@@ -401,14 +442,24 @@ async function executeCapability(capability, options) {
|
|
|
401
442
|
});
|
|
402
443
|
}
|
|
403
444
|
async function executeLocatedCapability(located, input, options) {
|
|
445
|
+
const handler = located.capability.handler;
|
|
446
|
+
if (!handler) throw markPublicError(new CapableError("METHOD_NOT_ALLOWED", {
|
|
447
|
+
status: 405,
|
|
448
|
+
message: `Capability "${located.capability.id}" only supports subscribe`
|
|
449
|
+
}));
|
|
404
450
|
const parsedInput = await parseCapabilityInput(located.capability, input);
|
|
405
451
|
let rawOutput;
|
|
406
452
|
try {
|
|
407
453
|
rawOutput = await runCapabilityMiddleware(located.middleware, {
|
|
454
|
+
capability: Object.freeze({
|
|
455
|
+
id: located.capability.id,
|
|
456
|
+
effect: located.capability.effect
|
|
457
|
+
}),
|
|
458
|
+
mode: "call",
|
|
408
459
|
input: parsedInput,
|
|
409
460
|
context: options.context,
|
|
410
461
|
...options.signal ? { signal: options.signal } : {}
|
|
411
|
-
}, () =>
|
|
462
|
+
}, () => handler({
|
|
412
463
|
input: parsedInput,
|
|
413
464
|
context: options.context,
|
|
414
465
|
...options.signal ? { signal: options.signal } : {}
|
|
@@ -419,30 +470,30 @@ async function executeLocatedCapability(located, input, options) {
|
|
|
419
470
|
return validateCapabilityOutput(located.capability, rawOutput);
|
|
420
471
|
}
|
|
421
472
|
function subscribeCapability(capability, options) {
|
|
422
|
-
|
|
473
|
+
const located = Object.freeze({
|
|
423
474
|
path: Object.freeze([]),
|
|
424
475
|
groups: Object.freeze([]),
|
|
425
476
|
groupPaths: Object.freeze([]),
|
|
426
477
|
capability,
|
|
427
478
|
errors: Object.freeze({ ...errorDefinitions(capability.errors) }),
|
|
428
479
|
middleware: capability.middleware
|
|
429
|
-
}), options.input ?? {}, {
|
|
430
|
-
context: options.context,
|
|
431
|
-
...options.signal ? { signal: options.signal } : {}
|
|
432
480
|
});
|
|
481
|
+
return (async function* () {
|
|
482
|
+
yield* await subscribeLocatedCapability(located, options.input ?? {}, {
|
|
483
|
+
context: options.context,
|
|
484
|
+
...options.signal ? { signal: options.signal } : {}
|
|
485
|
+
});
|
|
486
|
+
})();
|
|
433
487
|
}
|
|
434
|
-
function subscribeLocatedCapability(located, input, options) {
|
|
488
|
+
async function subscribeLocatedCapability(located, input, options) {
|
|
435
489
|
const subscriber = located.capability.subscribe;
|
|
436
|
-
if (!subscriber) throw new
|
|
437
|
-
|
|
490
|
+
if (!subscriber) throw markPublicError(new CapableError("METHOD_NOT_ALLOWED", {
|
|
491
|
+
status: 405,
|
|
492
|
+
message: `Capability "${located.capability.id}" only supports call`
|
|
493
|
+
}));
|
|
494
|
+
const parsedInput = await parseCapabilityInput(located.capability, input);
|
|
495
|
+
const subscription = createDemandIterator(async (stream) => {
|
|
438
496
|
let cleanupSource = async (_abort) => {};
|
|
439
|
-
let parsedInput;
|
|
440
|
-
try {
|
|
441
|
-
parsedInput = await parseCapabilityInput(located.capability, input);
|
|
442
|
-
} catch (error) {
|
|
443
|
-
stream.fail(error);
|
|
444
|
-
return;
|
|
445
|
-
}
|
|
446
497
|
try {
|
|
447
498
|
const controller = new AbortController();
|
|
448
499
|
const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
|
|
@@ -457,6 +508,11 @@ function subscribeLocatedCapability(located, input, options) {
|
|
|
457
508
|
stream.onCancel(() => cleanupSource(true));
|
|
458
509
|
let emitted = false;
|
|
459
510
|
await runCapabilityMiddleware(located.middleware, {
|
|
511
|
+
capability: Object.freeze({
|
|
512
|
+
id: located.capability.id,
|
|
513
|
+
effect: located.capability.effect
|
|
514
|
+
}),
|
|
515
|
+
mode: "subscribe",
|
|
460
516
|
input: parsedInput,
|
|
461
517
|
context: options.context,
|
|
462
518
|
signal
|
|
@@ -469,17 +525,19 @@ function subscribeLocatedCapability(located, input, options) {
|
|
|
469
525
|
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` });
|
|
470
526
|
const sourceIterator = iterable[Symbol.asyncIterator]();
|
|
471
527
|
iterator = sourceIterator;
|
|
528
|
+
stream.markReady();
|
|
472
529
|
while (await stream.waitForDemand()) {
|
|
473
530
|
const result = await sourceIterator.next();
|
|
474
531
|
if (result.done) {
|
|
475
|
-
if (!emitted) throw emptySubscriptionError(located.capability);
|
|
532
|
+
if (!emitted && located.capability.execution === "live") throw emptySubscriptionError(located.capability);
|
|
476
533
|
return;
|
|
477
534
|
}
|
|
478
535
|
emitted = true;
|
|
479
536
|
stream.emit(await validateCapabilityOutput(located.capability, result.value));
|
|
480
537
|
}
|
|
481
538
|
});
|
|
482
|
-
if (!emitted) throw emptySubscriptionError(located.capability);
|
|
539
|
+
if (!emitted && located.capability.execution === "live") throw emptySubscriptionError(located.capability);
|
|
540
|
+
stream.markReady();
|
|
483
541
|
await cleanupSource(false);
|
|
484
542
|
stream.complete();
|
|
485
543
|
} catch (error) {
|
|
@@ -487,6 +545,8 @@ function subscribeLocatedCapability(located, input, options) {
|
|
|
487
545
|
stream.fail(await normalizeCapabilityError(located, error));
|
|
488
546
|
}
|
|
489
547
|
});
|
|
548
|
+
await subscription.ready;
|
|
549
|
+
return subscription.iterator;
|
|
490
550
|
}
|
|
491
551
|
function emptySubscriptionError(capability) {
|
|
492
552
|
return new CapableError("INTERNAL_SERVER_ERROR", { message: `Capability "${capability.id}" subscription completed before yielding a value` });
|
|
@@ -508,10 +568,10 @@ async function parseCapabilityInput(capability, input) {
|
|
|
508
568
|
if (!capability.input) {
|
|
509
569
|
if (input === void 0) return {};
|
|
510
570
|
if (isRecord$1(input) && Object.keys(input).length === 0) return {};
|
|
511
|
-
throw new CapableError("BAD_REQUEST", {
|
|
571
|
+
throw markPublicError(new CapableError("BAD_REQUEST", {
|
|
512
572
|
status: 400,
|
|
513
573
|
message: `Capability "${capability.id}" does not accept input`
|
|
514
|
-
});
|
|
574
|
+
}));
|
|
515
575
|
}
|
|
516
576
|
try {
|
|
517
577
|
const parsed = await parseSchema(capability.input, input);
|
|
@@ -520,12 +580,12 @@ async function parseCapabilityInput(capability, input) {
|
|
|
520
580
|
} catch (error) {
|
|
521
581
|
if (error instanceof CapableError) throw error;
|
|
522
582
|
if (!(error instanceof SchemaValidationError)) throw error;
|
|
523
|
-
throw new CapableError("BAD_REQUEST", {
|
|
583
|
+
throw markPublicError(new CapableError("BAD_REQUEST", {
|
|
524
584
|
status: 400,
|
|
525
585
|
message: `Invalid input for Capability "${capability.id}"`,
|
|
526
586
|
data: { issues: error.issues },
|
|
527
587
|
cause: error
|
|
528
|
-
});
|
|
588
|
+
}));
|
|
529
589
|
}
|
|
530
590
|
}
|
|
531
591
|
async function runCapabilityMiddleware(middleware, args, handler) {
|
|
@@ -545,24 +605,34 @@ async function runCapabilityMiddleware(middleware, args, handler) {
|
|
|
545
605
|
return dispatch(0);
|
|
546
606
|
}
|
|
547
607
|
async function normalizeCapabilityError(located, error) {
|
|
548
|
-
if (!(error instanceof CapableError))
|
|
608
|
+
if (!(error instanceof CapableError)) {
|
|
609
|
+
unmarkPublicError(error);
|
|
610
|
+
return error;
|
|
611
|
+
}
|
|
549
612
|
const contract = located.errors[error.code];
|
|
550
|
-
if (!contract)
|
|
613
|
+
if (!contract) {
|
|
614
|
+
unmarkPublicError(error);
|
|
615
|
+
return new CapableError("INTERNAL_SERVER_ERROR", { cause: error });
|
|
616
|
+
}
|
|
551
617
|
let data = error.data;
|
|
552
618
|
if (contract.data) try {
|
|
553
619
|
data = await parseSchema(contract.data, error.data);
|
|
554
620
|
} catch (cause) {
|
|
555
|
-
|
|
621
|
+
unmarkPublicError(error);
|
|
622
|
+
return new CapableError("INTERNAL_SERVER_ERROR", {
|
|
556
623
|
message: `Invalid error data for ${error.code}`,
|
|
557
624
|
cause
|
|
558
625
|
});
|
|
559
626
|
}
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
627
|
+
const status = typeof contract.status === "number" ? contract.status : void 0;
|
|
628
|
+
const message = contract.message ?? error.code;
|
|
629
|
+
if (error.status === status && error.message === message && error.data === data) return markPublicError(error);
|
|
630
|
+
return markPublicError(new CapableError(error.code, {
|
|
631
|
+
...status === void 0 ? {} : { status },
|
|
632
|
+
message,
|
|
563
633
|
data,
|
|
564
634
|
cause: error
|
|
565
|
-
});
|
|
635
|
+
}));
|
|
566
636
|
}
|
|
567
637
|
function isCapability(value) {
|
|
568
638
|
return Boolean(value && typeof value === "object" && value[CAPABILITY_SYMBOL] === true);
|
|
@@ -589,13 +659,17 @@ function group(config) {
|
|
|
589
659
|
}
|
|
590
660
|
function defineApp(config) {
|
|
591
661
|
assertCapabilityTree(config.capabilities, "application.capabilities");
|
|
592
|
-
const
|
|
662
|
+
const errors = config.errors ?? NO_ERRORS;
|
|
663
|
+
const middleware = Object.freeze([...config.middleware ?? []]);
|
|
664
|
+
const located = locateCapabilities(config.capabilities, [], [], [], errorDefinitions(errors), middleware);
|
|
593
665
|
assertUniqueCapabilities(located);
|
|
594
666
|
return Object.freeze({
|
|
595
667
|
[APPLICATION_SYMBOL]: true,
|
|
596
668
|
name: config.name ?? "Capable application",
|
|
597
669
|
version: config.version ?? "0.0.0",
|
|
598
670
|
...config.description ? { description: config.description } : {},
|
|
671
|
+
errors,
|
|
672
|
+
middleware,
|
|
599
673
|
capabilities: config.capabilities,
|
|
600
674
|
locatedCapabilities: Object.freeze(located)
|
|
601
675
|
});
|
|
@@ -670,6 +744,6 @@ function isRecord(value) {
|
|
|
670
744
|
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
671
745
|
}
|
|
672
746
|
//#endregion
|
|
673
|
-
export { defineErrors as S, normalizePresentation as _, isCapabilityGroup as a, CAPABILITY_ERRORS_SYMBOL as b, executeCapability as c, subscribeCapability as d, subscribeLocatedCapability as f, watchQuery as g, schemaToJsonSchema as h, group as i, executeLocatedCapability as l, parseSchema as m, CAPABILITY_GROUP_SYMBOL as n, CAPABILITY_SYMBOL as o, SchemaValidationError as p, defineApp as r, capability as s, APPLICATION_SYMBOL as t, isCapability as u, present as v, CapableError as x, renderPresentationMarkdown as y };
|
|
747
|
+
export { isPublicError as C, defineErrors as S, unmarkPublicError as T, normalizePresentation as _, isCapabilityGroup as a, CAPABILITY_ERRORS_SYMBOL as b, executeCapability as c, subscribeCapability as d, subscribeLocatedCapability as f, watchQuery as g, schemaToJsonSchema as h, group as i, executeLocatedCapability as l, parseSchema as m, CAPABILITY_GROUP_SYMBOL as n, CAPABILITY_SYMBOL as o, SchemaValidationError as p, defineApp as r, capability as s, APPLICATION_SYMBOL as t, isCapability as u, present as v, markPublicError as w, CapableError as x, renderPresentationMarkdown as y };
|
|
674
748
|
|
|
675
|
-
//# sourceMappingURL=src-
|
|
749
|
+
//# sourceMappingURL=src-TCQGaWar.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-TCQGaWar.mjs","names":["maybeSchema","NO_ERRORS","isRecord"],"sources":["../../core/src/errors.ts","../../core/src/presentation.ts","../../core/src/subscription.ts","../../core/src/schema.ts","../../core/src/capability.ts","../../core/src/application.ts"],"sourcesContent":["import type {\n AnySchema,\n InferSchemaInput,\n InferSchemaOutput,\n} from \"./schema.ts\";\n\nexport const CAPABILITY_ERRORS_SYMBOL: unique symbol = Symbol.for(\n \"capable.capability-errors\",\n) as never;\nexport const CAPABILITY_ERROR_DEFINITIONS_SYMBOL: unique symbol = Symbol.for(\n \"capable.capability-error-definitions\",\n) as never;\n\nexport interface ErrorMetaRegistry {}\n\ntype OpenErrorMeta =\n & Partial<ErrorMetaRegistry>\n & Readonly<Record<string, unknown>>;\n\nexport type CapabilityErrorDefinition<\n TData extends AnySchema | undefined = AnySchema | undefined,\n> = {\n readonly message?: string;\n readonly status?: number;\n readonly data?: TData;\n readonly meta?: OpenErrorMeta;\n readonly [key: string]: unknown;\n};\n\nexport type CapabilityErrorContract = Readonly<\n Record<string, CapabilityErrorDefinition>\n>;\n\nexport class CapableError<\n TCode extends string = string,\n TData = unknown,\n> extends Error {\n readonly code: TCode;\n readonly status: number | undefined;\n readonly data: TData;\n\n constructor(\n code: TCode,\n options: {\n message?: string;\n status?: number;\n data?: TData;\n cause?: unknown;\n } = {},\n ) {\n super(options.message ?? code, { cause: options.cause });\n this.name = \"CapableError\";\n this.code = code;\n this.status = options.status;\n this.data = options.data as TData;\n }\n}\n\ntype ErrorDataSchema<TDefinition extends CapabilityErrorDefinition> =\n TDefinition extends { readonly data: infer TData extends AnySchema }\n ? TData\n : undefined;\n\ntype ErrorDataInput<TDefinition extends CapabilityErrorDefinition> =\n ErrorDataSchema<TDefinition> extends infer TData extends AnySchema\n ? InferSchemaInput<TData>\n : undefined;\n\ntype ErrorDataOutput<TDefinition extends CapabilityErrorDefinition> =\n ErrorDataSchema<TDefinition> extends infer TData extends AnySchema\n ? InferSchemaOutput<TData>\n : undefined;\n\ntype ErrorFactoryArgs<TDefinition extends CapabilityErrorDefinition> =\n ErrorDataSchema<TDefinition> extends AnySchema\n ? [\n data: ErrorDataInput<TDefinition>,\n options?: { readonly cause?: unknown },\n ]\n : [options?: { readonly cause?: unknown }];\n\nexport type CapabilityErrorFactory<\n TCode extends string,\n TDefinition extends CapabilityErrorDefinition,\n> = {\n (...args: ErrorFactoryArgs<TDefinition>): CapableError<\n TCode,\n ErrorDataOutput<TDefinition>\n >;\n readonly code: TCode;\n readonly definition: TDefinition;\n is(error: unknown): error is CapableError<\n TCode,\n ErrorDataOutput<TDefinition>\n >;\n};\n\nexport type DefinedErrors<\n TDefinitions extends CapabilityErrorContract,\n> = {\n readonly [TCode in keyof TDefinitions & string]: CapabilityErrorFactory<\n TCode,\n TDefinitions[TCode]\n >;\n} & {\n readonly [CAPABILITY_ERRORS_SYMBOL]: true;\n readonly [CAPABILITY_ERROR_DEFINITIONS_SYMBOL]: TDefinitions;\n};\n\nexport type AnyDefinedErrors = {\n readonly [CAPABILITY_ERRORS_SYMBOL]: true;\n readonly [CAPABILITY_ERROR_DEFINITIONS_SYMBOL]: CapabilityErrorContract;\n};\n\nexport function defineErrors<\n const TDefinitions extends CapabilityErrorContract,\n>(definitions: TDefinitions): DefinedErrors<TDefinitions> {\n const frozenDefinitions = Object.freeze({ ...definitions }) as TDefinitions;\n const result: Record<PropertyKey, unknown> = {};\n\n for (const [code, definition] of Object.entries(frozenDefinitions)) {\n const create = ((\n first?: unknown,\n second?: { readonly cause?: unknown },\n ) => {\n const hasData = definition.data !== undefined;\n const data = hasData ? first : undefined;\n const options = (hasData ? second : first) as\n | { readonly cause?: unknown }\n | undefined;\n return new CapableError(code, {\n ...(definition.message ? { message: definition.message } : {}),\n ...(typeof definition.status === \"number\"\n ? { status: definition.status }\n : {}),\n ...(hasData ? { data } : {}),\n ...(options &&\n typeof options === \"object\" &&\n \"cause\" in options\n ? { cause: options.cause }\n : {}),\n });\n }) as CapabilityErrorFactory<string, CapabilityErrorDefinition>;\n\n Object.defineProperties(create, {\n code: { value: code, enumerable: true },\n definition: { value: definition, enumerable: true },\n is: {\n value: (error: unknown) =>\n error instanceof Error &&\n \"code\" in error &&\n error.code === code,\n },\n });\n result[code] = Object.freeze(create);\n }\n\n Object.defineProperties(result, {\n [CAPABILITY_ERRORS_SYMBOL]: { value: true },\n [CAPABILITY_ERROR_DEFINITIONS_SYMBOL]: { value: frozenDefinitions },\n });\n return Object.freeze(result) as DefinedErrors<TDefinitions>;\n}\n\nexport function errorDefinitions(\n errors: AnyDefinedErrors,\n): CapabilityErrorContract {\n return errors[CAPABILITY_ERROR_DEFINITIONS_SYMBOL];\n}\n\nconst PUBLIC_ERRORS_SYMBOL = Symbol.for(\"capable.public-errors\");\n\nfunction publicErrors(): WeakSet<object> {\n const store = globalThis as Record<PropertyKey, unknown>;\n const existing = store[PUBLIC_ERRORS_SYMBOL];\n if (existing instanceof WeakSet) return existing;\n const created = new WeakSet<object>();\n store[PUBLIC_ERRORS_SYMBOL] = created;\n return created;\n}\n\n/** @internal Mark an error as validated for external wire serialization. */\nexport function markPublicError<TError extends object>(error: TError): TError {\n publicErrors().add(error);\n return error;\n}\n\n/** @internal Revoke wire-serialization permission when an error escapes an unvalidated seam. */\nexport function unmarkPublicError(error: unknown): void {\n if (error && typeof error === \"object\") {\n publicErrors().delete(error);\n }\n}\n\n/** @internal True only for errors explicitly validated or created at a public boundary. */\nexport function isPublicError(error: unknown): boolean {\n return Boolean(error && typeof error === \"object\" && publicErrors().has(error));\n}\n","import type { MaybePromise } from \"./projection.ts\";\n\nexport type PresentationTableCell = string | number | boolean | null;\n\nexport type MarkdownPresentationPart = {\n readonly type: \"markdown\";\n readonly markdown: string;\n};\n\nexport type TablePresentationPart = {\n readonly type: \"table\";\n readonly caption?: string;\n readonly columns: readonly string[];\n readonly rows: readonly (readonly PresentationTableCell[])[];\n};\n\nexport type ImagePresentationPart = {\n readonly type: \"image\";\n readonly base64: string;\n readonly mimeType: `image/${string}`;\n readonly alt: string;\n};\n\nexport type FilePresentationPart = {\n readonly type: \"file\";\n readonly url: string;\n readonly name: string;\n readonly mimeType?: string;\n readonly size?: number;\n readonly description?: string;\n};\n\nexport type PresentationPart =\n | MarkdownPresentationPart\n | TablePresentationPart\n | ImagePresentationPart\n | FilePresentationPart;\n\ntype PresentationNode = string | PresentationPart;\nexport type PresentationValue =\n | PresentationNode\n | readonly PresentationNode[];\n\nexport type PresentationRenderer<TOutput, TContext> = (\n output: TOutput,\n options: { readonly context: TContext },\n) => MaybePromise<PresentationValue>;\n\ntype TablePresentationOptions = Omit<TablePresentationPart, \"type\">;\ntype ImagePresentationOptions = Omit<ImagePresentationPart, \"type\">;\ntype FilePresentationOptions = Omit<FilePresentationPart, \"type\">;\n\ntype PresentationBuilders = Readonly<{\n table(options: TablePresentationOptions): TablePresentationPart;\n image(options: ImagePresentationOptions): ImagePresentationPart;\n file(options: FilePresentationOptions): FilePresentationPart;\n}>;\n\nexport const present: PresentationBuilders = Object.freeze({\n table(options) {\n return {\n type: \"table\",\n ...(options.caption !== undefined ? { caption: options.caption } : {}),\n columns: options.columns,\n rows: options.rows,\n };\n },\n image(options) {\n return {\n type: \"image\",\n base64: options.base64,\n mimeType: options.mimeType,\n alt: options.alt,\n };\n },\n file(options) {\n return {\n type: \"file\",\n url: options.url,\n name: options.name,\n ...(options.mimeType !== undefined ? { mimeType: options.mimeType } : {}),\n ...(options.size !== undefined ? { size: options.size } : {}),\n ...(options.description !== undefined\n ? { description: options.description }\n : {}),\n };\n },\n});\n\nexport function normalizePresentation(\n value: PresentationValue,\n): readonly PresentationPart[] {\n const nodes = Array.isArray(value) ? value : [value];\n return Object.freeze(nodes.map((node, index) => {\n if (typeof node === \"string\") {\n return Object.freeze({\n type: \"markdown\" as const,\n markdown: node,\n });\n }\n return normalizePresentationPart(node, index);\n }));\n}\n\nexport function renderPresentationMarkdown(\n presentation: PresentationPart | readonly PresentationPart[],\n): string {\n const parts = Array.isArray(presentation) ? presentation : [presentation];\n return parts.map(renderPresentationPartMarkdown).join(\"\\n\\n\");\n}\n\nfunction renderPresentationPartMarkdown(part: PresentationPart): string {\n if (part.type === \"markdown\") return part.markdown;\n if (part.type === \"table\") return renderTableMarkdown(part);\n if (part.type === \"image\") return `[Image: ${part.alt}]`;\n\n const metadata = [\n part.mimeType,\n part.size === undefined ? undefined : formatBytes(part.size),\n ].filter(Boolean).join(\", \");\n return [\n `[${escapeMarkdown(part.name)}](${part.url})`,\n part.description,\n metadata ? `(${metadata})` : undefined,\n ].filter(Boolean).join(\" — \");\n}\n\nfunction renderTableMarkdown(table: TablePresentationPart): string {\n const lines = [\n `| ${table.columns.map(escapeTableCell).join(\" | \")} |`,\n `| ${table.columns.map(() => \"---\").join(\" | \")} |`,\n ...table.rows.map((row) =>\n `| ${row.map((cell) => escapeTableCell(cell === null ? \"\" : String(cell))).join(\" | \")} |`\n ),\n ];\n return table.caption === undefined\n ? lines.join(\"\\n\")\n : `**${escapeMarkdown(table.caption)}**\\n\\n${lines.join(\"\\n\")}`;\n}\n\nfunction normalizePresentationPart(\n part: PresentationPart,\n index: number,\n): PresentationPart {\n if (!part || typeof part !== \"object\") {\n throw new Error(`Presentation part ${index} must be a string or object`);\n }\n if (part.type === \"markdown\") {\n assertString(part.markdown, `Presentation part ${index} markdown`);\n return Object.freeze({\n type: \"markdown\",\n markdown: part.markdown,\n });\n }\n if (part.type === \"table\") {\n if (part.caption !== undefined) {\n assertString(part.caption, `Presentation part ${index} caption`);\n }\n if (!Array.isArray(part.columns) || part.columns.length === 0) {\n throw new Error(`Presentation part ${index} table requires columns`);\n }\n part.columns.forEach((column, columnIndex) =>\n assertString(\n column,\n `Presentation part ${index} column ${columnIndex}`,\n )\n );\n if (!Array.isArray(part.rows)) {\n throw new Error(`Presentation part ${index} table rows must be an array`);\n }\n const rows = part.rows.map((row, rowIndex) => {\n if (!Array.isArray(row) || row.length !== part.columns.length) {\n throw new Error(\n `Presentation part ${index} row ${rowIndex} must have ${part.columns.length} cells`,\n );\n }\n for (const cell of row) {\n if (\n cell !== null &&\n typeof cell !== \"string\" &&\n typeof cell !== \"number\" &&\n typeof cell !== \"boolean\"\n ) {\n throw new Error(\n `Presentation part ${index} row ${rowIndex} has a non-scalar cell`,\n );\n }\n if (typeof cell === \"number\" && !Number.isFinite(cell)) {\n throw new Error(\n `Presentation part ${index} row ${rowIndex} has a non-finite number`,\n );\n }\n }\n return Object.freeze([...row]);\n });\n return Object.freeze({\n type: \"table\",\n ...(part.caption !== undefined ? { caption: part.caption } : {}),\n columns: Object.freeze([...part.columns]),\n rows: Object.freeze(rows),\n });\n }\n if (part.type === \"image\") {\n assertString(part.base64, `Presentation part ${index} image base64`);\n assertString(part.mimeType, `Presentation part ${index} image MIME type`);\n if (!part.mimeType.startsWith(\"image/\")) {\n throw new Error(\n `Presentation part ${index} image MIME type must start with \"image/\"`,\n );\n }\n assertString(part.alt, `Presentation part ${index} image alt text`);\n return Object.freeze({\n type: \"image\",\n base64: part.base64,\n mimeType: part.mimeType,\n alt: part.alt,\n });\n }\n if (part.type === \"file\") {\n assertString(part.url, `Presentation part ${index} file URL`);\n assertString(part.name, `Presentation part ${index} file name`);\n if (part.mimeType !== undefined) {\n assertString(part.mimeType, `Presentation part ${index} file MIME type`);\n }\n if (\n part.size !== undefined &&\n (!Number.isInteger(part.size) || part.size < 0)\n ) {\n throw new Error(\n `Presentation part ${index} file size must be a non-negative integer`,\n );\n }\n if (part.description !== undefined) {\n assertString(\n part.description,\n `Presentation part ${index} file description`,\n );\n }\n return Object.freeze({\n type: \"file\",\n url: part.url,\n name: part.name,\n ...(part.mimeType !== undefined ? { mimeType: part.mimeType } : {}),\n ...(part.size !== undefined ? { size: part.size } : {}),\n ...(part.description !== undefined\n ? { description: part.description }\n : {}),\n });\n }\n throw new Error(\n `Presentation part ${index} has unknown type \"${String((part as { type?: unknown }).type)}\"`,\n );\n}\n\nfunction escapeTableCell(value: string): string {\n return value.replace(/\\|/g, \"\\\\|\").replace(/\\r?\\n/g, \" \");\n}\n\nfunction escapeMarkdown(value: string): string {\n return value.replace(/([\\\\`*_[\\]<>])/g, \"\\\\$1\");\n}\n\nfunction formatBytes(value: number): string {\n if (value < 1_000) return `${value} B`;\n if (value < 1_000_000) return `${(value / 1_000).toFixed(1)} kB`;\n if (value < 1_000_000_000) {\n return `${(value / 1_000_000).toFixed(1)} MB`;\n }\n return `${(value / 1_000_000_000).toFixed(1)} GB`;\n}\n\nfunction assertString(value: unknown, label: string): asserts value is string {\n if (typeof value !== \"string\") throw new Error(`${label} must be a string`);\n}\n","import type { MaybePromise } from \"./projection.ts\";\n\nexport type WatchQueryOptions<TOutput> = {\n readonly snapshot: () => MaybePromise<TOutput>;\n readonly invalidations: () => AsyncIterable<unknown>;\n readonly signal?: AbortSignal;\n};\n\n/**\n * Turn an invalidation source into a stream of complete replacement snapshots.\n *\n * The invalidation iterator is pulled before the first snapshot is read. A\n * change racing with that read therefore causes another snapshot rather than\n * being missed.\n */\nexport async function* watchQuery<TOutput>(\n options: WatchQueryOptions<TOutput>,\n): AsyncIterableIterator<TOutput> {\n if (options.signal?.aborted) return;\n\n const iterator = options.invalidations()[Symbol.asyncIterator]();\n let pending = nextHandled(iterator);\n\n try {\n yield await options.snapshot();\n\n while (!options.signal?.aborted) {\n const result = await pending;\n if (result.done) return;\n pending = nextHandled(iterator);\n yield await options.snapshot();\n }\n } finally {\n await iterator.return?.();\n }\n}\n\nfunction nextHandled(iterator: AsyncIterator<unknown>) {\n const pending = iterator.next();\n void pending.catch(() => undefined);\n return pending;\n}\n\ntype Deferred<T> = {\n readonly promise: Promise<T>;\n resolve(value: T): void;\n reject(error: unknown): void;\n};\n\nfunction deferred<T>(): Deferred<T> {\n let resolve!: (value: T) => void;\n let reject!: (error: unknown) => void;\n const promise = new Promise<T>((onResolve, onReject) => {\n resolve = onResolve;\n reject = onReject;\n });\n return { promise, resolve, reject };\n}\n\nexport type DemandStream<T> = {\n waitForDemand(): Promise<boolean>;\n emit(value: T): void;\n markReady(): void;\n complete(): void;\n fail(error: unknown): void;\n onCancel(cleanup: () => void | Promise<void>): void;\n};\n\nexport type DemandIterator<T> = {\n readonly iterator: AsyncIterableIterator<T>;\n readonly ready: Promise<void>;\n};\n\nexport function createDemandIterator<T>(\n produce: (stream: DemandStream<T>) => Promise<void>,\n): DemandIterator<T> {\n const demands: Deferred<IteratorResult<T>>[] = [];\n const demandWaiters: Array<() => void> = [];\n const cleanups: Array<() => void | Promise<void>> = [];\n const ready = deferred<void>();\n let activeDemand: Deferred<IteratorResult<T>> | undefined;\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 markReady() {\n ready.resolve();\n },\n complete() {\n stream.markReady();\n closed = true;\n activeDemand?.resolve({ done: true, value: undefined });\n activeDemand = undefined;\n finishPending();\n wakeProducer();\n },\n fail(error) {\n ready.reject(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 void ready.promise.catch(() => undefined);\n\n const iterator: AsyncIterableIterator<T> = {\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 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 task = produce(stream).then(\n () => {\n if (!closed) stream.complete();\n },\n (error) => stream.fail(error),\n );\n\n return { iterator, ready: ready.promise };\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\ntype MaybeStandardJsonSchema = {\n readonly \"~standard\"?: {\n readonly vendor?: unknown;\n readonly jsonSchema?: Partial<\n Record<\"input\" | \"output\", (options: unknown) => unknown>\n >;\n };\n};\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\nfunction missingStandardJsonSchemaMessage(\n vendor: unknown,\n direction: \"input\" | \"output\",\n): string {\n const missing =\n `Schema does not implement Standard JSON Schema v1: \\`~standard.jsonSchema.${direction}\\` is not a function.`;\n const requirement =\n \"@capable/core requires schemas that implement Standard JSON Schema v1.\";\n if (vendor === \"zod\") {\n return `${missing} ${requirement} This schema reports vendor \"zod\"; if it is a Zod schema, zod >= 4.2 is required.`;\n }\n return `${missing} ${requirement} Update the schema library to a version that implements Standard JSON Schema v1.`;\n}\n\nexport function schemaToJsonSchema(\n schema: AnySchema,\n direction: \"input\" | \"output\",\n options: {\n readonly allowUnrepresentable?: boolean;\n } = {},\n): Readonly<Record<string, unknown>> {\n const maybeSchema = schema as MaybeStandardJsonSchema | null | undefined;\n const standard = maybeSchema?.[\"~standard\"];\n const jsonSchema = standard?.jsonSchema;\n const project = jsonSchema?.[direction];\n if (typeof project !== \"function\") {\n throw new Error(\n missingStandardJsonSchemaMessage(standard?.vendor, direction),\n );\n }\n const projected = project.call(jsonSchema, {\n target: \"draft-2020-12\",\n ...(options.allowUnrepresentable\n ? { libraryOptions: { unrepresentable: \"any\" } }\n : {}),\n });\n return JSON.parse(JSON.stringify(projected)) as Readonly<\n Record<string, unknown>\n >;\n}\n\nexport class SchemaValidationError extends Error {\n readonly issues: readonly StandardSchemaV1.Issue[];\n\n constructor(issues: readonly StandardSchemaV1.Issue[]) {\n super(\"Schema validation failed\");\n this.name = \"SchemaValidationError\";\n this.issues = issues;\n }\n}\n","import {\n defineErrors,\n errorDefinitions,\n CapableError,\n markPublicError,\n unmarkPublicError,\n type AnyDefinedErrors,\n type DefinedErrors,\n type CapabilityErrorContract,\n} from \"./errors.ts\";\nimport {\n parseSchema,\n SchemaValidationError,\n type AnySchema,\n type AnyObjectSchema,\n type InferSchemaInput,\n type InferSchemaOutput,\n} from \"./schema.ts\";\nimport type { MaybePromise } from \"./projection.ts\";\nimport type {\n PresentationRenderer,\n PresentationValue,\n} from \"./presentation.ts\";\nimport { createDemandIterator } from \"./subscription.ts\";\nimport type { LocatedCapability } from \"./application.ts\";\n\nexport const CAPABILITY_SYMBOL: unique symbol = Symbol.for(\n \"capable.capability\",\n) as never;\n\nexport interface CapabilityMetaRegistry {}\ntype OpenMeta<TRegistry> = Partial<TRegistry> & Readonly<Record<string, unknown>>;\n\nexport type CapabilityEffect = \"read\" | \"write\" | \"destructive\";\n\ntype EmptyInput = Record<never, never>;\ntype DefinedNoErrors = DefinedErrors<{}>;\nconst NO_ERRORS = defineErrors({});\n\ntype ParsedInput<TInput extends AnyObjectSchema | undefined> =\n TInput extends AnySchema ? InferSchemaOutput<TInput> : EmptyInput;\n\ntype HandlerInput<TInput extends AnyObjectSchema | undefined> =\n TInput extends AnySchema ? InferSchemaInput<TInput> : EmptyInput;\n\nexport type CapabilityHandlerArgs<TContext, TInput> = {\n readonly input: TInput;\n readonly context: TContext;\n readonly signal?: AbortSignal;\n};\n\nexport type CapabilitySubscriberArgs<TContext, TInput> = {\n readonly input: TInput;\n readonly context: TContext;\n readonly signal: AbortSignal;\n};\n\nexport type CapabilitySubscriber<TContext, TInput, TOutput> = (\n args: CapabilitySubscriberArgs<TContext, TInput>,\n) => AsyncIterable<TOutput>;\n\nexport type CapabilityMiddlewareArgs<TContext, TInput = unknown> = {\n readonly capability: {\n readonly id: string;\n readonly effect: CapabilityEffect | undefined;\n };\n readonly mode: \"call\" | \"subscribe\";\n readonly input: TInput;\n readonly context: TContext;\n readonly signal?: AbortSignal;\n next(): Promise<unknown>;\n};\n\nexport type CapabilityMiddleware<TContext, TInput = unknown> = (\n args: CapabilityMiddlewareArgs<TContext, TInput>,\n) => MaybePromise<unknown>;\n\nexport type CapabilityExecution = \"unary\" | \"live\" | \"events\";\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 TExecution extends CapabilityExecution = CapabilityExecution,\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 // Method parameters remain assignable when an erased definition contains an\n // empty event stream whose inferred output is `never`.\n toPresentation?(\n output: TOutput,\n options: { readonly context: TContext },\n ): MaybePromise<PresentationValue>;\n readonly \"~capable/context\"?: (context: TContext) => TContext;\n readonly \"~capable/input\"?: TInput;\n readonly \"~capable/output\"?: TOutput;\n} & (TExecution extends \"events\"\n ? {\n readonly execution: \"events\";\n readonly handler?: never;\n readonly subscribe: CapabilitySubscriber<TContext, ParsedInput<TInput>, any>;\n }\n : TExecution extends \"live\"\n ? {\n readonly execution: \"live\";\n readonly handler: (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => MaybePromise<TOutput>;\n readonly subscribe: CapabilitySubscriber<TContext, ParsedInput<TInput>, any>;\n }\n : {\n readonly execution: \"unary\";\n readonly handler: (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => MaybePromise<TOutput>;\n readonly subscribe?: never;\n });\n\nexport type AnyCapability = CapabilityDefinition<\n any,\n any,\n any,\n any,\n any,\n CapabilityExecution\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 \"live\" | \"events\"\n>;\n\nexport type CallableCapability = CapabilityDefinition<\n any, any, any, any, any, \"unary\" | \"live\"\n>;\n\nexport type ExecuteCapabilityOptions<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<\n infer TContext,\n infer TInput,\n any,\n any,\n any\n >\n ? (TInput extends AnyObjectSchema\n ? { readonly input: InferSchemaInput<TInput> }\n : { readonly input?: EmptyInput }) &\n ([TContext] extends [undefined]\n ? { readonly context?: undefined }\n : { readonly context: TContext }) & {\n readonly signal?: AbortSignal;\n }\n : never;\n\ntype CapabilityBaseConfig<\n TContext,\n TInput extends AnyObjectSchema | undefined,\n TErrors extends AnyDefinedErrors,\n TMeta extends OpenMeta<CapabilityMetaRegistry>,\n> = {\n readonly id: string;\n readonly title?: string;\n readonly description?: string;\n readonly deprecated?: boolean;\n readonly effect?: CapabilityEffect;\n readonly input?: TInput;\n readonly errors?: TErrors;\n readonly middleware?: readonly CapabilityMiddleware<\n TContext,\n ParsedInput<TInput>\n >[];\n readonly meta?: TMeta;\n};\n\ntype ExplicitOutputCapabilityConfig<\n TContext,\n TInput extends AnyObjectSchema | undefined,\n TOutput extends AnySchema,\n TErrors extends AnyDefinedErrors,\n TMeta extends OpenMeta<CapabilityMetaRegistry>,\n> = CapabilityBaseConfig<TContext, TInput, TErrors, TMeta> & {\n readonly output: TOutput;\n readonly handler: (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => MaybePromise<InferSchemaInput<TOutput>>;\n readonly toPresentation?: PresentationRenderer<InferSchemaOutput<TOutput>, TContext>;\n readonly subscribe?: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n InferSchemaInput<TOutput>\n >;\n};\n\ntype InferredOutputCapabilityConfig<\n TContext,\n TInput extends AnyObjectSchema | undefined,\n TReturn,\n TErrors extends AnyDefinedErrors,\n TMeta extends OpenMeta<CapabilityMetaRegistry>,\n> = CapabilityBaseConfig<TContext, TInput, TErrors, TMeta> & {\n readonly output?: never;\n // Infer the full return union before awaiting it, including mixed sync/async branches.\n readonly handler: (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => TReturn;\n readonly toPresentation?: PresentationRenderer<Awaited<TReturn>, TContext>;\n readonly subscribe?: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n Awaited<TReturn>\n >;\n};\n\ntype ExplicitEventConfig<\n TContext,\n TInput extends AnyObjectSchema | undefined,\n TOutput extends AnySchema,\n TErrors extends AnyDefinedErrors,\n TMeta extends OpenMeta<CapabilityMetaRegistry>,\n> =\n Omit<\n ExplicitOutputCapabilityConfig<TContext, TInput, TOutput, TErrors, TMeta>,\n \"handler\" | \"subscribe\" | \"effect\"\n > & {\n readonly handler?: never;\n readonly effect: \"read\";\n readonly subscribe: CapabilitySubscriber<\n TContext, ParsedInput<TInput>, InferSchemaInput<TOutput>\n >;\n };\n\ntype InferredEventConfig<\n TContext,\n TInput extends AnyObjectSchema | undefined,\n TOutput,\n TErrors extends AnyDefinedErrors,\n TMeta extends OpenMeta<CapabilityMetaRegistry>,\n> =\n CapabilityBaseConfig<TContext, TInput, TErrors, TMeta> & {\n readonly handler?: never;\n readonly output?: never;\n readonly effect: \"read\";\n readonly subscribe: CapabilitySubscriber<TContext, ParsedInput<TInput>, TOutput>;\n readonly toPresentation?: PresentationRenderer<NoInfer<TOutput>, TContext>;\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: ExplicitEventConfig<TContext, TInput, TOutput, TErrors, TMeta>,\n ): CapabilityDefinition<\n TContext, TInput, InferSchemaOutput<TOutput>, TErrors, TMeta, \"events\"\n >;\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n TOutput = unknown,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: InferredEventConfig<TContext, TInput, TOutput, TErrors, TMeta>,\n ): CapabilityDefinition<TContext, TInput, TOutput, TErrors, TMeta, \"events\">;\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 \"live\"\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 \"unary\"\n >;\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n TReturn = unknown,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: InferredOutputCapabilityConfig<\n TContext,\n TInput,\n TReturn,\n TErrors,\n TMeta\n > & {\n readonly subscribe: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n Awaited<TReturn>\n >;\n },\n ): CapabilityDefinition<\n TContext,\n TInput,\n Awaited<TReturn>,\n TErrors,\n TMeta,\n \"live\"\n >;\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n TReturn = unknown,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: InferredOutputCapabilityConfig<\n TContext,\n TInput,\n TReturn,\n TErrors,\n TMeta\n > & { readonly subscribe?: never },\n ): CapabilityDefinition<\n TContext,\n TInput,\n Awaited<TReturn>,\n TErrors,\n TMeta,\n \"unary\"\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, any, any, any>\n | ExplicitEventConfig<any, any, any, any, any>\n | InferredEventConfig<any, any, any, 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, any, any, any>\n | ExplicitEventConfig<any, any, any, any, any>\n | InferredEventConfig<any, any, any, any, any>,\n): AnyCapability {\n const id = config.id;\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 \"${id}\" must declare effect \"read\" to subscribe`,\n );\n }\n if (config.handler !== undefined && typeof config.handler !== \"function\") {\n throw new Error(`Capability \"${id}\" handler must be a function`);\n }\n if (config.subscribe !== undefined && typeof config.subscribe !== \"function\") {\n throw new Error(`Capability \"${id}\" subscribe must be a function`);\n }\n if (!config.handler && !config.subscribe) {\n throw new Error(`Capability \"${id}\" requires a handler or subscribe`);\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 execution: config.handler ? (config.subscribe ? \"live\" : \"unary\") : \"events\",\n ...(config.handler ? { handler: config.handler } : {}),\n ...(config.subscribe ? { subscribe: config.subscribe } : {}),\n ...(config.toPresentation\n ? { toPresentation: config.toPresentation }\n : {}),\n }) as AnyCapability;\n}\n\nexport async function executeCapability<\n const TCapability extends CallableCapability,\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 handler = located.capability.handler;\n if (!handler) {\n throw markPublicError(new CapableError(\"METHOD_NOT_ALLOWED\", {\n status: 405,\n message: `Capability \"${located.capability.id}\" only supports subscribe`,\n }));\n }\n const parsedInput = await parseCapabilityInput(located.capability, input);\n let rawOutput: unknown;\n try {\n rawOutput = await runCapabilityMiddleware(\n located.middleware,\n {\n capability: Object.freeze({\n id: located.capability.id,\n effect: located.capability.effect,\n }),\n mode: \"call\",\n input: parsedInput,\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n },\n () => 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 (async function* () {\n const stream = await subscribeLocatedCapability(located, options.input ?? {}, {\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n });\n yield* stream;\n })() as AsyncIterableIterator<CapabilityOutput<TCapability>>;\n}\n\nexport async function subscribeLocatedCapability(\n located: LocatedCapability,\n input: unknown,\n options: { readonly context: unknown; readonly signal?: AbortSignal },\n): Promise<AsyncIterableIterator<unknown>> {\n const subscriber = located.capability.subscribe;\n if (!subscriber) {\n throw markPublicError(new CapableError(\"METHOD_NOT_ALLOWED\", {\n status: 405,\n message: `Capability \"${located.capability.id}\" only supports call`,\n }));\n }\n const parsedInput = await parseCapabilityInput(located.capability, input);\n\n const subscription = createDemandIterator(async (stream) => {\n let cleanupSource = async (_abort: boolean) => {};\n try {\n const controller = new AbortController();\n const signal = options.signal\n ? AbortSignal.any([controller.signal, options.signal])\n : controller.signal;\n let iterator: AsyncIterator<unknown> | undefined;\n let cleaned = false;\n cleanupSource = async (abort: boolean) => {\n if (cleaned) return;\n cleaned = true;\n if (abort) controller.abort();\n await iterator?.return?.();\n };\n stream.onCancel(() => cleanupSource(true));\n\n let emitted = false;\n await runCapabilityMiddleware(\n located.middleware,\n {\n capability: Object.freeze({\n id: located.capability.id,\n effect: located.capability.effect,\n }),\n mode: \"subscribe\",\n input: parsedInput,\n context: options.context,\n signal,\n },\n async () => {\n const iterable = subscriber({\n input: parsedInput,\n context: options.context,\n signal,\n });\n if (\n !iterable ||\n typeof iterable !== \"object\" ||\n !(Symbol.asyncIterator in iterable)\n ) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Capability \"${located.capability.id}\" subscribe must return an AsyncIterable`,\n });\n }\n const sourceIterator = iterable[Symbol.asyncIterator]();\n iterator = sourceIterator;\n stream.markReady();\n\n while (await stream.waitForDemand()) {\n const result = await sourceIterator.next();\n if (result.done) {\n if (!emitted && located.capability.execution === \"live\") {\n throw emptySubscriptionError(located.capability);\n }\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 && located.capability.execution === \"live\") {\n throw emptySubscriptionError(located.capability);\n }\n stream.markReady();\n await cleanupSource(false);\n stream.complete();\n } catch (error) {\n await cleanupSource(false);\n stream.fail(await normalizeCapabilityError(located, error));\n }\n });\n await subscription.ready;\n return subscription.iterator;\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 markPublicError(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 markPublicError(new CapableError(\"BAD_REQUEST\", {\n status: 400,\n message: `Invalid input for Capability \"${capability.id}\"`,\n data: { issues: error.issues },\n cause: error,\n }));\n }\n}\n\nasync function runCapabilityMiddleware(\n middleware: readonly CapabilityMiddleware<any>[],\n args: Omit<CapabilityMiddlewareArgs<unknown>, \"next\">,\n handler: () => MaybePromise<unknown>,\n): Promise<unknown> {\n async function dispatch(index: number): Promise<unknown> {\n const current = middleware[index];\n if (!current) return handler();\n let called = false;\n return current({\n ...args,\n next: async () => {\n if (called) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Capability middleware called next() more than once\",\n });\n }\n called = true;\n return dispatch(index + 1);\n },\n });\n }\n return dispatch(0);\n}\n\nasync function normalizeCapabilityError(\n located: LocatedCapability,\n error: unknown,\n): Promise<unknown> {\n if (!(error instanceof CapableError)) {\n unmarkPublicError(error);\n return error;\n }\n const contract = located.errors[error.code];\n if (!contract) {\n unmarkPublicError(error);\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 unmarkPublicError(error);\n return new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Invalid error data for ${error.code}`,\n cause,\n });\n }\n }\n const status = typeof contract.status === \"number\"\n ? contract.status\n : undefined;\n const message = contract.message ?? error.code;\n if (\n error.status === status &&\n error.message === message &&\n error.data === data\n ) {\n return markPublicError(error);\n }\n return markPublicError(new CapableError(error.code, {\n ...(status === undefined ? {} : { status }),\n message,\n data,\n cause: error,\n }));\n}\n\nexport function isCapability(value: unknown): value is AnyCapability {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n (value as Partial<AnyCapability>)[CAPABILITY_SYMBOL] === true,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n","import {\n defineErrors,\n errorDefinitions,\n type AnyDefinedErrors,\n type DefinedErrors,\n type CapabilityErrorContract,\n} from \"./errors.ts\";\nimport {\n isCapability,\n type AnyCapability,\n type CapabilityDefinition,\n type CapabilityMiddleware,\n} from \"./capability.ts\";\n\nexport const CAPABILITY_GROUP_SYMBOL: unique symbol = Symbol.for(\n \"capable.capability-group\",\n) as never;\nexport const APPLICATION_SYMBOL: unique symbol = Symbol.for(\n \"capable.application\",\n) as never;\n\nexport interface GroupMetaRegistry {}\ntype OpenMeta<TRegistry> = Partial<TRegistry> & Readonly<Record<string, unknown>>;\ntype DefinedNoErrors = DefinedErrors<{}>;\nconst NO_ERRORS = defineErrors({});\n\nexport interface CapabilityTree {\n readonly [key: string]:\n | AnyCapability\n | CapabilityTree\n | AnyCapabilityGroup;\n}\n\nexport type CapabilityGroupDefinition<\n TCapabilities extends CapabilityTree = CapabilityTree,\n TErrors extends AnyDefinedErrors = AnyDefinedErrors,\n TMeta extends OpenMeta<GroupMetaRegistry> = OpenMeta<GroupMetaRegistry>,\n> = {\n readonly [CAPABILITY_GROUP_SYMBOL]: true;\n readonly title?: string;\n readonly description?: string;\n readonly errors: TErrors;\n readonly middleware: readonly CapabilityMiddleware<any>[];\n readonly meta: TMeta;\n readonly capabilities: TCapabilities;\n};\n\nexport type AnyCapabilityGroup = {\n readonly [CAPABILITY_GROUP_SYMBOL]: true;\n readonly title?: string;\n readonly description?: string;\n readonly errors: AnyDefinedErrors;\n readonly middleware: readonly CapabilityMiddleware<any>[];\n readonly meta: OpenMeta<GroupMetaRegistry>;\n readonly capabilities: CapabilityTree;\n};\n\nexport function group<\n const TCapabilities extends CapabilityTree,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<GroupMetaRegistry> = {},\n>(config: {\n readonly title?: string;\n readonly description?: string;\n readonly errors?: TErrors;\n readonly middleware?: readonly CapabilityMiddleware<\n NoInfer<SharedContext<TCapabilities>>\n >[];\n readonly meta?: TMeta;\n readonly capabilities: TCapabilities;\n}): CapabilityGroupDefinition<TCapabilities, TErrors, TMeta> {\n assertCapabilityTree(config.capabilities, \"group.capabilities\");\n return Object.freeze({\n [CAPABILITY_GROUP_SYMBOL]: true as const,\n ...(config.title ? { title: config.title } : {}),\n ...(config.description ? { description: config.description } : {}),\n errors: (config.errors ?? NO_ERRORS) as TErrors,\n middleware: Object.freeze([...(config.middleware ?? [])]),\n meta: Object.freeze({ ...(config.meta ?? {}) }) as TMeta,\n capabilities: config.capabilities,\n });\n}\n\nexport type LocatedCapability = {\n readonly path: readonly string[];\n readonly groups: readonly AnyCapabilityGroup[];\n readonly groupPaths: readonly (readonly string[])[];\n readonly capability: AnyCapability;\n readonly errors: CapabilityErrorContract;\n readonly middleware: readonly CapabilityMiddleware<any>[];\n};\n\nexport type AppDefinition<\n TCapabilities extends CapabilityTree = CapabilityTree,\n TContext = unknown,\n> = {\n readonly [APPLICATION_SYMBOL]: true;\n readonly name: string;\n readonly version: string;\n readonly description?: string;\n readonly errors: AnyDefinedErrors;\n readonly middleware: readonly CapabilityMiddleware<any>[];\n readonly capabilities: TCapabilities;\n readonly locatedCapabilities: readonly LocatedCapability[];\n readonly \"~capable/context\"?: TContext;\n};\n\ntype CapabilityTreeContext<TTree> =\n TTree extends CapabilityDefinition<infer TContext, any, any, any, any>\n ? TContext\n : TTree extends CapabilityGroupDefinition<infer TCapabilities, any, any>\n ? CapabilityTreeContext<TCapabilities>\n : TTree extends Readonly<Record<string, unknown>>\n ? CapabilityTree extends TTree\n ? unknown\n : CapabilityTreeContext<TTree[keyof TTree]>\n : never;\n\ntype UnionToIntersection<TValue> =\n (TValue extends unknown ? (value: TValue) => void : never) extends\n (value: infer TIntersection) => void ? TIntersection : never;\n\ntype SharedContext<TCapabilities> =\n [Exclude<CapabilityTreeContext<TCapabilities>, undefined>] extends [never]\n ? undefined\n : UnionToIntersection<Exclude<CapabilityTreeContext<TCapabilities>, undefined>>;\n\nexport type AppContext<\n TDefinition extends AppDefinition<any, any>,\n> = TDefinition extends AppDefinition<any, infer TContext>\n ? TContext\n : never;\n\nexport function defineApp<\n const TCapabilities extends CapabilityTree,\n>(config: {\n readonly name?: string;\n readonly version?: string;\n readonly description?: string;\n readonly errors?: AnyDefinedErrors;\n readonly middleware?: readonly CapabilityMiddleware<\n NoInfer<SharedContext<TCapabilities>>\n >[];\n readonly capabilities: TCapabilities;\n}): AppDefinition<\n TCapabilities,\n SharedContext<TCapabilities>\n> {\n assertCapabilityTree(config.capabilities, \"application.capabilities\");\n const errors = config.errors ?? NO_ERRORS;\n const middleware = Object.freeze([...(config.middleware ?? [])]);\n const located = locateCapabilities(\n config.capabilities,\n [],\n [],\n [],\n errorDefinitions(errors),\n middleware,\n );\n assertUniqueCapabilities(located);\n\n return Object.freeze({\n [APPLICATION_SYMBOL]: true as const,\n name: config.name ?? \"Capable application\",\n version: config.version ?? \"0.0.0\",\n ...(config.description ? { description: config.description } : {}),\n errors,\n middleware,\n capabilities: config.capabilities,\n locatedCapabilities: Object.freeze(located),\n });\n}\n\nfunction locateCapabilities(\n tree: CapabilityTree,\n path: readonly string[] = [],\n groups: readonly AnyCapabilityGroup[] = [],\n groupPaths: readonly (readonly string[])[] = [],\n inheritedErrors: CapabilityErrorContract = {},\n inheritedMiddleware: readonly CapabilityMiddleware<any>[] = [],\n): LocatedCapability[] {\n const located: LocatedCapability[] = [];\n for (const [key, value] of Object.entries(tree)) {\n const nextPath = [...path, key];\n if (isCapability(value)) {\n const capabilityErrors = errorDefinitions(value.errors);\n assertAdditionalErrors(\n inheritedErrors,\n capabilityErrors,\n `Capability \"${value.id}\"`,\n );\n located.push(Object.freeze({\n path: Object.freeze(nextPath),\n groups: Object.freeze([...groups]),\n groupPaths: Object.freeze([...groupPaths]),\n capability: value,\n errors: Object.freeze({ ...inheritedErrors, ...capabilityErrors }),\n middleware: Object.freeze([\n ...inheritedMiddleware,\n ...value.middleware,\n ]),\n }));\n continue;\n }\n if (isCapabilityGroup(value)) {\n const groupErrors = errorDefinitions(value.errors);\n assertAdditionalErrors(\n inheritedErrors,\n groupErrors,\n `Group at \"${nextPath.join(\".\")}\"`,\n );\n located.push(...locateCapabilities(\n value.capabilities,\n nextPath,\n [...groups, value],\n [...groupPaths, nextPath],\n { ...inheritedErrors, ...groupErrors },\n [\n ...inheritedMiddleware,\n ...(value.middleware as readonly CapabilityMiddleware<any>[]),\n ],\n ));\n continue;\n }\n located.push(...locateCapabilities(\n value,\n nextPath,\n groups,\n groupPaths,\n inheritedErrors,\n inheritedMiddleware,\n ));\n }\n return located;\n}\n\nfunction assertCapabilityTree(\n value: unknown,\n label: string,\n): asserts value is CapabilityTree {\n if (!isRecord(value)) {\n throw new Error(\n `${label} must be a named object tree; arrays are not supported`,\n );\n }\n for (const [key, child] of Object.entries(value)) {\n if (!key) throw new Error(`${label} has an empty key`);\n if (key === \"then\") {\n throw new Error(`${label} uses reserved key \"then\"`);\n }\n if (isCapability(child)) continue;\n if (isCapabilityGroup(child)) {\n assertCapabilityTree(child.capabilities, `${label}.${key}.capabilities`);\n continue;\n }\n assertCapabilityTree(child, `${label}.${key}`);\n }\n}\n\nfunction assertUniqueCapabilities(\n located: readonly LocatedCapability[],\n): void {\n const ids = new Map<string, string>();\n const objects = new Map<AnyCapability, string>();\n for (const entry of located) {\n const path = entry.path.join(\".\");\n const previousIdPath = ids.get(entry.capability.id);\n if (previousIdPath) {\n throw new Error(\n `Duplicate Capability id \"${entry.capability.id}\" at \"${previousIdPath}\" and \"${path}\"`,\n );\n }\n const previousObjectPath = objects.get(entry.capability);\n if (previousObjectPath) {\n throw new Error(\n `Capability \"${entry.capability.id}\" is included at both \"${previousObjectPath}\" and \"${path}\"`,\n );\n }\n ids.set(entry.capability.id, path);\n objects.set(entry.capability, path);\n }\n}\n\nfunction assertAdditionalErrors(\n inherited: CapabilityErrorContract,\n additional: CapabilityErrorContract,\n label: string,\n): void {\n const duplicate = Object.keys(additional).find((code) => code in inherited);\n if (duplicate) {\n throw new Error(`${label} redeclares inherited error ${duplicate}`);\n }\n}\n\nexport function isCapabilityGroup(\n value: unknown,\n): value is AnyCapabilityGroup {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n (value as Partial<AnyCapabilityGroup>)[CAPABILITY_GROUP_SYMBOL] === true,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n"],"mappings":";AAMA,MAAa,2BAA0C,OAAO,IAC5D,2BACF;AACA,MAAa,sCAAqD,OAAO,IACvE,sCACF;AAsBA,IAAa,eAAb,cAGU,MAAM;CACd;CACA;CACA;CAEA,YACE,MACA,UAKI,CAAC,GACL;EACA,MAAM,QAAQ,WAAW,MAAM,EAAE,OAAO,QAAQ,MAAM,CAAC;EACvD,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS,QAAQ;EACtB,KAAK,OAAO,QAAQ;CACtB;AACF;AA0DA,SAAgB,aAEd,aAAwD;CACxD,MAAM,oBAAoB,OAAO,OAAO,EAAE,GAAG,YAAY,CAAC;CAC1D,MAAM,SAAuC,CAAC;CAE9C,KAAK,MAAM,CAAC,MAAM,eAAe,OAAO,QAAQ,iBAAiB,GAAG;EAClE,MAAM,WACJ,OACA,WACG;GACH,MAAM,UAAU,WAAW,SAAS,KAAA;GACpC,MAAM,OAAO,UAAU,QAAQ,KAAA;GAC/B,MAAM,UAAW,UAAU,SAAS;GAGpC,OAAO,IAAI,aAAa,MAAM;IAC5B,GAAI,WAAW,UAAU,EAAE,SAAS,WAAW,QAAQ,IAAI,CAAC;IAC5D,GAAI,OAAO,WAAW,WAAW,WAC7B,EAAE,QAAQ,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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,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Y as MaybePromise } from "./index-BIO_hbXJ.mjs";
|
|
2
2
|
//#region packages/core/src/subscription.d.ts
|
|
3
3
|
type WatchQueryOptions<TOutput> = {
|
|
4
4
|
readonly snapshot: () => MaybePromise<TOutput>;
|
|
@@ -15,4 +15,4 @@ type WatchQueryOptions<TOutput> = {
|
|
|
15
15
|
declare function watchQuery<TOutput>(options: WatchQueryOptions<TOutput>): AsyncIterableIterator<TOutput>;
|
|
16
16
|
//#endregion
|
|
17
17
|
export { watchQuery as n, WatchQueryOptions as t };
|
|
18
|
-
//# sourceMappingURL=subscription-
|
|
18
|
+
//# sourceMappingURL=subscription-fVgS4T8P.d.mts.map
|
package/dist/swr.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { _ as AppCapabilityReference, h as AppCapabilityIsLive } from "./index-F_eaksy8.mjs";
|
|
2
2
|
import { Fetcher, SWRConfiguration } from "swr";
|
|
3
3
|
import { MutationFetcher, SWRMutationConfiguration } from "swr/mutation";
|
|
4
4
|
import { SWRSubscription } from "swr/subscription";
|
|
@@ -26,7 +26,7 @@ type SWRLiveCapability<TCall extends CapabilityCall> = SWRCapability<TCall> & {
|
|
|
26
26
|
subscription(input: CapabilityInput<TCall>): readonly [key: CapabilitySWRKey, subscriber: SWRSubscription<CapabilitySWRKey, CapabilityOutput<TCall>, Error>];
|
|
27
27
|
subscription<const TOptions extends CapabilitySWRSubscriptionConfiguration<TCall>>(input: CapabilityInput<TCall>, options: TOptions): readonly [key: CapabilitySWRKey, subscriber: SWRSubscription<CapabilitySWRKey, CapabilityOutput<TCall>, Error>, options: TOptions];
|
|
28
28
|
};
|
|
29
|
-
type SWRNode<TValue> = TValue extends CapabilityCall ?
|
|
29
|
+
type SWRNode<TValue> = TValue extends CapabilityCall ? AppCapabilityIsLive<TValue> extends true ? SWRLiveCapability<TValue> : SWRCapability<TValue> : TValue extends object ? { readonly [TKey in Extract<keyof TValue, string> as TValue[TKey] extends AppCapabilityReference ? TValue[TKey] extends CapabilityCall ? TKey : never : TKey]: SWRNode<TValue[TKey]>; } : never;
|
|
30
30
|
type SWRApp<TApp extends object> = SWRNode<TApp>;
|
|
31
31
|
declare function createSWR<const TApp extends object>(app: TApp, options?: {
|
|
32
32
|
readonly keyPrefix?: readonly unknown[];
|
package/dist/swr.mjs
CHANGED
package/dist/swr.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swr.mjs","names":[],"sources":["../../swr/src/index.ts"],"sourcesContent":["import {\n subscribe,\n type
|
|
1
|
+
{"version":3,"file":"swr.mjs","names":[],"sources":["../../swr/src/index.ts"],"sourcesContent":["import {\n subscribe,\n type AppCapabilityIsLive,\n type AppCapabilityReference,\n} from \"@capable/app\";\nimport type {\n Fetcher,\n SWRConfiguration,\n} from \"swr\";\nimport type {\n MutationFetcher,\n SWRMutationConfiguration,\n} from \"swr/mutation\";\nimport type { SWRSubscription } from \"swr/subscription\";\n\ntype CapabilityCall = (...args: any[]) => Promise<any>;\n\nconst subscribeCall = subscribe as unknown as (\n capabilityCall: CapabilityCall,\n input: unknown,\n options: { readonly signal: AbortSignal },\n) => AsyncIterableIterator<unknown>;\n\ntype CapabilityInput<TCall extends CapabilityCall> =\n Exclude<Parameters<TCall>[0], undefined>;\n\ntype CapabilityVariables<TCall extends CapabilityCall> =\n undefined extends Parameters<TCall>[0]\n ? Exclude<Parameters<TCall>[0], undefined> | void\n : Parameters<TCall>[0];\n\ntype CapabilityOutput<TCall extends CapabilityCall> =\n Awaited<ReturnType<TCall>>;\n\nexport type CapabilitySWRKey = readonly [unknown, ...unknown[]];\n\ntype CapabilityFetcher<TCall extends CapabilityCall> = Fetcher<\n CapabilityOutput<TCall>,\n CapabilitySWRKey\n>;\n\ntype CapabilityMutationFetcher<TCall extends CapabilityCall> = MutationFetcher<\n CapabilityOutput<TCall>,\n CapabilitySWRKey,\n CapabilityVariables<TCall>\n>;\n\nexport type CapabilitySWRConfiguration<\n TCall extends CapabilityCall,\n> = Omit<\n SWRConfiguration<\n CapabilityOutput<TCall>,\n Error,\n CapabilityFetcher<TCall>\n >,\n \"fetcher\"\n>;\n\nexport type CapabilitySWRMutationConfiguration<\n TCall extends CapabilityCall,\n TSWRData = CapabilityOutput<TCall>,\n> = SWRMutationConfiguration<\n CapabilityOutput<TCall>,\n Error,\n CapabilitySWRKey,\n CapabilityVariables<TCall>,\n TSWRData\n> & {\n readonly throwOnError?: boolean;\n};\n\nexport type CapabilitySWRSubscriptionConfiguration<\n TCall extends CapabilityCall,\n> = SWRConfiguration<CapabilityOutput<TCall>, Error>;\n\nexport type SWRCapability<TCall extends CapabilityCall> = {\n key(input?: CapabilityInput<TCall>): CapabilitySWRKey;\n swr(input: CapabilityInput<TCall>): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityFetcher<TCall>,\n ];\n swr<const TOptions extends CapabilitySWRConfiguration<TCall>>(\n input: CapabilityInput<TCall>,\n options: TOptions,\n ): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityFetcher<TCall>,\n options: TOptions,\n ];\n mutation(): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityMutationFetcher<TCall>,\n ];\n mutation<TSWRData = CapabilityOutput<TCall>>(\n options: CapabilitySWRMutationConfiguration<TCall, TSWRData>,\n ): readonly [\n key: CapabilitySWRKey,\n fetcher: CapabilityMutationFetcher<TCall>,\n options: CapabilitySWRMutationConfiguration<TCall, TSWRData>,\n ];\n};\n\nexport type SWRLiveCapability<TCall extends CapabilityCall> =\n SWRCapability<TCall> & {\n subscription(input: CapabilityInput<TCall>): readonly [\n key: CapabilitySWRKey,\n subscriber: SWRSubscription<\n CapabilitySWRKey,\n CapabilityOutput<TCall>,\n Error\n >,\n ];\n subscription<\n const TOptions extends CapabilitySWRSubscriptionConfiguration<TCall>,\n >(\n input: CapabilityInput<TCall>,\n options: TOptions,\n ): readonly [\n key: CapabilitySWRKey,\n subscriber: SWRSubscription<\n CapabilitySWRKey,\n CapabilityOutput<TCall>,\n Error\n >,\n options: TOptions,\n ];\n };\n\ntype SWRNode<TValue> =\n TValue extends CapabilityCall\n ? AppCapabilityIsLive<TValue> extends true\n ? SWRLiveCapability<TValue>\n : SWRCapability<TValue>\n : TValue extends object\n ? {\n readonly [TKey in Extract<keyof TValue, string> as\n TValue[TKey] extends AppCapabilityReference\n ? TValue[TKey] extends CapabilityCall ? TKey : never\n : TKey]: SWRNode<TValue[TKey]>;\n }\n : never;\n\nexport type SWRApp<TApp extends object> = SWRNode<TApp>;\n\nexport function createSWR<const TApp extends object>(\n app: TApp,\n options: {\n readonly keyPrefix?: readonly unknown[];\n } = {},\n): SWRApp<TApp> {\n const keyPrefix = Object.freeze([...(options.keyPrefix ?? [\"capable\"])]);\n\n const callableAt = (path: readonly string[]): CapabilityCall => {\n let current: unknown = app;\n for (const segment of path) {\n current = (current as Record<string, unknown>)[segment];\n }\n return current as CapabilityCall;\n };\n\n const capabilityKey = (\n path: readonly string[],\n input?: unknown,\n ): CapabilitySWRKey => Object.freeze([\n ...keyPrefix,\n ...path,\n ...(input === undefined ? [] : [input]),\n ]) as CapabilitySWRKey;\n\n const withOptions = (\n key: CapabilitySWRKey,\n operation: (...args: any[]) => unknown,\n hookOptions: unknown,\n ): readonly unknown[] => hookOptions === undefined\n ? [key, operation]\n : [key, operation, hookOptions];\n\n const proxy = (path: readonly string[]): unknown =>\n new Proxy({}, {\n get(_target, key) {\n if (key === \"then\") return undefined;\n if (key === \"key\") {\n return (input?: unknown) => capabilityKey(path, input);\n }\n if (key === \"swr\") {\n return (input: unknown, swrOptions?: unknown) => withOptions(\n capabilityKey(path, input),\n () => callableAt(path)(input),\n swrOptions,\n );\n }\n if (key === \"mutation\") {\n return (mutationOptions?: unknown) => withOptions(\n capabilityKey(path),\n (_key: CapabilitySWRKey, { arg }: { readonly arg?: unknown }) =>\n callableAt(path)(arg),\n mutationOptions,\n );\n }\n if (key === \"subscription\") {\n return (input: unknown, subscriptionOptions?: unknown) => withOptions(\n capabilityKey(path, input),\n (\n _key: CapabilitySWRKey,\n { next }: {\n readonly next: (error?: Error | null, data?: unknown) => void;\n },\n ) => {\n const controller = new AbortController();\n\n void (async () => {\n try {\n for await (const output of subscribeCall(\n callableAt(path),\n input,\n { signal: controller.signal },\n )) {\n next(null, output);\n }\n } catch (error) {\n if (!controller.signal.aborted) {\n next(toError(error));\n }\n }\n })();\n\n return () => controller.abort();\n },\n subscriptionOptions,\n );\n }\n if (typeof key !== \"string\") return undefined;\n return proxy([...path, key]);\n },\n });\n\n return proxy([]) as SWRApp<TApp>;\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n"],"mappings":";;AAiBA,MAAM,gBAAgB;AA+HtB,SAAgB,UACd,KACA,UAEI,CAAC,GACS;CACd,MAAM,YAAY,OAAO,OAAO,CAAC,GAAI,QAAQ,aAAa,CAAC,SAAS,CAAE,CAAC;CAEvE,MAAM,cAAc,SAA4C;EAC9D,IAAI,UAAmB;EACvB,KAAK,MAAM,WAAW,MACpB,UAAW,QAAoC;EAEjD,OAAO;CACT;CAEA,MAAM,iBACJ,MACA,UACqB,OAAO,OAAO;EACnC,GAAG;EACH,GAAG;EACH,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,CAAC,KAAK;CACvC,CAAC;CAED,MAAM,eACJ,KACA,WACA,gBACuB,gBAAgB,KAAA,IACrC,CAAC,KAAK,SAAS,IACf;EAAC;EAAK;EAAW;CAAW;CAEhC,MAAM,SAAS,SACb,IAAI,MAAM,CAAC,GAAG,EACZ,IAAI,SAAS,KAAK;EAChB,IAAI,QAAQ,QAAQ,OAAO,KAAA;EAC3B,IAAI,QAAQ,OACV,QAAQ,UAAoB,cAAc,MAAM,KAAK;EAEvD,IAAI,QAAQ,OACV,QAAQ,OAAgB,eAAyB,YAC/C,cAAc,MAAM,KAAK,SACnB,WAAW,IAAI,CAAC,CAAC,KAAK,GAC5B,UACF;EAEF,IAAI,QAAQ,YACV,QAAQ,oBAA8B,YACpC,cAAc,IAAI,IACjB,MAAwB,EAAE,UACzB,WAAW,IAAI,CAAC,CAAC,GAAG,GACtB,eACF;EAEF,IAAI,QAAQ,gBACV,QAAQ,OAAgB,wBAAkC,YACxD,cAAc,MAAM,KAAK,IAEvB,MACA,EAAE,WAGC;GACH,MAAM,aAAa,IAAI,gBAAgB;GAEvC,CAAM,YAAY;IAChB,IAAI;KACF,WAAW,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