-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdiscoverable.ts
More file actions
81 lines (78 loc) · 2.54 KB
/
discoverable.ts
File metadata and controls
81 lines (78 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { makeExo } from '@endo/exo';
import type { Methods } from '@endo/exo';
import type { InterfaceGuard } from '@endo/patterns';
import { mergeDisjointRecords } from '@metamask/kernel-utils';
import { makeDefaultInterface } from './exo.ts';
import type { MethodSchema } from './schema.ts';
/**
* A discoverable exo object that extends a base exo interface with a `describe` method
* for runtime introspection of method schemas.
*/
export type DiscoverableExo<
Interface extends Methods = Record<string, (...args: unknown[]) => unknown>,
Schema extends Record<keyof Interface, MethodSchema> = Record<
keyof Interface,
MethodSchema
>,
> = ReturnType<
typeof makeExo<
Interface & {
/**
* Describe the methods of the discoverable.
*
* @returns A schema of the methods.
*/
describe: () => Schema;
}
>
>;
/**
* Shorthand for creating a discoverable `@endo/exo` remotable with default guards set to 'passable'.
* The keys of the schema must match the keys of the methods. By convention, the schema is exhaustive.
* In other words, the schema is a complete description of the interface. In practice, it may be incomplete.
*
* @param name - The name of the discoverable.
* @param methods - The methods of the discoverable.
* @param schema - The schema of the discoverable, with method schemas including descriptions, arguments, and return types.
* @param interfaceGuard - The interface guard of the discoverable.
* @returns A discoverable exo.
*/
export const makeDiscoverableExo = <
Interface extends Methods,
Schema extends Record<keyof Interface, MethodSchema> = Record<
keyof Interface,
MethodSchema
>,
>(
name: string,
methods: Interface,
schema: Schema,
interfaceGuard: InterfaceGuard = makeDefaultInterface(name),
): DiscoverableExo<Interface, Schema> => {
try {
// @ts-expect-error We're intentionally not specifying method-specific interface guards.
return makeExo(
name,
interfaceGuard,
// @ts-expect-error We're intentionally not specifying method-specific interface guards.
mergeDisjointRecords(methods, {
/**
* Describe the methods of the discoverable.
*
* @returns A schema of the methods.
*/
describe: () => schema,
}),
);
} catch (error) {
if (
error instanceof Error &&
error.message.includes('Duplicate keys in records: describe')
) {
throw new Error(
'The `describe` method name is reserved for discoverable exos.',
);
}
throw error;
}
};