@johnhenry/wsh 0.50.0 → 0.52.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/README.md +148 -19
- package/bin/wsh-objects-types.mjs +98 -0
- package/package.json +7 -2
- package/spec/gateway-fail.vectors.json +14 -0
- package/spec/objects.md +212 -0
- package/spec/wsh-v1.yaml +12 -9
- package/src/duplex.mjs +2 -1
- package/src/gateway-client.mjs +6 -2
- package/src/gateway-errors.mjs +12 -5
- package/src/index.d.ts +11 -4
- package/src/objects-core.mjs +270 -41
- package/src/objects-mcp.mjs +130 -0
- package/src/objects-schema.mjs +143 -0
- package/src/objects-type-text.mjs +95 -0
- package/src/objects-types.d.ts +38 -0
- package/src/objects-types.mjs +292 -0
- package/src/objects.d.ts +127 -7
- package/src/objects.mjs +4 -1
- package/src/page-host.d.ts +26 -5
- package/src/page-host.mjs +53 -16
- package/src/webmcp.mjs +17 -4
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@johnhenry/wsh/objects-types` -- TypeScript declarations for a root of `wsh-objects`, so the far side's Proxy is typed.
|
|
3
|
+
*
|
|
4
|
+
* `describeRootTypes(description, { name })` is a PURE function: it takes what a host says one key may do on one root (the host's `types` answer, which
|
|
5
|
+
* `rootDescription(page.window)` fetches, or the allow-lists a host holds) and returns the text of a `.d.ts` file. It reads nothing, writes nothing,
|
|
6
|
+
* evaluates nothing, and throws on anything it does not understand. What it writes:
|
|
7
|
+
*
|
|
8
|
+
* - **Only what the key may do.** A path appears only if one of the key's allow-list entries (for an operation the key's `objects:ROOT:OP` capabilities
|
|
9
|
+
* grant) names it. A path in no entry, an operation not granted, and a member the host refuses are not in the file, not even as `never`.
|
|
10
|
+
* - **Value types limited to what can be known.** A plain value is `RemoteValue<unknown>` unless the host supplied a type for the path; a call is
|
|
11
|
+
* `(...args: unknown[]) => PromiseLike<unknown>`; a wildcard (`*`, `**`) is `RemoteUntyped` (`any`): the file does not guess the members behind it.
|
|
12
|
+
* An event source carries typed `on` overloads from `allow.on` and `eventFields`; a path that may be set carries a typed `set`.
|
|
13
|
+
* - **Host-supplied types are untrusted text.** They pass `checkTypeText` (a conservative subset, see `objects-type-text.mjs`), must belong to a path an
|
|
14
|
+
* entry allows, and are bounded; they are copied into the file and never evaluated.
|
|
15
|
+
* - **Advisory.** A type is erased before anything runs. It does not widen what the host allows, and `authorize`, the always-refused names and the paths that
|
|
16
|
+
* must be named still refuse at call time whatever the file says.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { checkTypeText, TYPE_TEXT_LIMITS } from './objects-type-text.mjs';
|
|
20
|
+
|
|
21
|
+
export { checkTypeText, TYPE_TEXT_LIMITS };
|
|
22
|
+
|
|
23
|
+
export const OBJECTS_TYPES_LIMITS = Object.freeze({
|
|
24
|
+
/** Entries in one allow list of a description. */
|
|
25
|
+
maxEntries: 1000,
|
|
26
|
+
/** Characters of one allow-list entry. */
|
|
27
|
+
maxEntryChars: 512,
|
|
28
|
+
/** Nodes of the tree the entries make. */
|
|
29
|
+
maxNodes: 4000,
|
|
30
|
+
/** Event types and fields in one description. */
|
|
31
|
+
maxEvents: 256,
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
const OPS = ['get', 'call', 'set', 'on'];
|
|
35
|
+
const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
36
|
+
const ROOT_NAME = /^[A-Za-z_$][A-Za-z0-9_$-]{0,63}$/;
|
|
37
|
+
const EVENT_TYPE = /^[A-Za-z0-9_$:.-]{1,128}$/;
|
|
38
|
+
const FIELD_NAME = /^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/;
|
|
39
|
+
const SEGMENT = /^[\x21-\x7e][\x20-\x7e]{0,255}$/;
|
|
40
|
+
const RESERVED = new Set([
|
|
41
|
+
'any', 'unknown', 'never', 'string', 'number', 'boolean', 'object', 'symbol', 'void', 'null', 'undefined', 'bigint', 'Promise', 'PromiseLike', 'Record', 'Array',
|
|
42
|
+
'RemoteValue', 'RemoteCall', 'RemoteUntyped', 'RemoteHandle', 'NonValue', 'WithEvents', 'WithSet', 'RemoteEventData',
|
|
43
|
+
'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'enum', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'import', 'in',
|
|
44
|
+
'instanceof', 'new', 'return', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'while', 'with', 'yield', 'let', 'static', 'implements', 'interface', 'package', 'private',
|
|
45
|
+
'protected', 'public', 'await', 'async', 'of', 'type', 'declare', 'module', 'namespace', 'global', 'require',
|
|
46
|
+
]);
|
|
47
|
+
|
|
48
|
+
const bad = (message) => new TypeError(`describeRootTypes: ${message}`);
|
|
49
|
+
|
|
50
|
+
/** Does a literal path match a pattern (`*` one segment, `**` any number, also none)? */
|
|
51
|
+
function matches(pattern, path) {
|
|
52
|
+
const rec = (i, j) => {
|
|
53
|
+
if (i === pattern.length) return j === path.length;
|
|
54
|
+
if (pattern[i] === '**') return rec(i + 1, j) || (j < path.length && rec(i, j + 1));
|
|
55
|
+
return j < path.length && (pattern[i] === '*' || pattern[i] === path[j]) && rec(i + 1, j + 1);
|
|
56
|
+
};
|
|
57
|
+
return rec(0, 0);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function splitPath(text, what) {
|
|
61
|
+
const segs = text.split('.');
|
|
62
|
+
for (const s of segs) {
|
|
63
|
+
if (!SEGMENT.test(s)) throw bad(`${what} ${JSON.stringify(text.slice(0, 80))} has a path segment that is empty or not printable ASCII`);
|
|
64
|
+
if (/\*/.test(s) && s !== '*' && s !== '**') throw bad(`${what} ${JSON.stringify(text.slice(0, 80))}: a wildcard must be a whole segment`);
|
|
65
|
+
}
|
|
66
|
+
return segs;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** One entry of an allow list: `{ segs, callbacks, type? }`. */
|
|
70
|
+
function parseEntry(raw, op) {
|
|
71
|
+
if (typeof raw !== 'string' || raw === '' || raw.length > OBJECTS_TYPES_LIMITS.maxEntryChars) throw bad(`an allow.${op} entry must be a string of 1 to ${OBJECTS_TYPES_LIMITS.maxEntryChars} characters`);
|
|
72
|
+
let text = raw;
|
|
73
|
+
let type;
|
|
74
|
+
let callbacks = false;
|
|
75
|
+
if (op === 'on') {
|
|
76
|
+
const at = text.indexOf('@');
|
|
77
|
+
if (at < 0) throw bad(`allow.on entry ${JSON.stringify(raw.slice(0, 80))} must be "path@type"`);
|
|
78
|
+
type = text.slice(at + 1);
|
|
79
|
+
text = text.slice(0, at);
|
|
80
|
+
if (!EVENT_TYPE.test(type)) throw bad(`allow.on entry ${JSON.stringify(raw.slice(0, 80))}: the event type is not a name`);
|
|
81
|
+
}
|
|
82
|
+
// `(callback)`, and the notations that also let the far side's function return a value (`(callback:returns)`, `(callback:returns=0,2)`): the types do not describe a return.
|
|
83
|
+
const callbackEnd = op === 'call' ? /\(callback(?::returns(?:=\d{1,2}(?:,\d{1,2})*)?)?\)$/.exec(text) : null;
|
|
84
|
+
if (callbackEnd) { callbacks = true; text = text.slice(0, callbackEnd.index); }
|
|
85
|
+
const segs = splitPath(text, `allow.${op} entry`);
|
|
86
|
+
if (op === 'on' && segs.some((s) => s.includes('*'))) throw bad(`allow.on entry ${JSON.stringify(raw.slice(0, 80))}: an event source is named exactly`);
|
|
87
|
+
return { segs, callbacks, type, text };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
class Node {
|
|
91
|
+
constructor() {
|
|
92
|
+
this.kids = new Map();
|
|
93
|
+
this.result = null; // the node of what a call of this one returns
|
|
94
|
+
this.wild = false; // a `*` or `**` below: the members are not enumerated
|
|
95
|
+
this.get = false; this.call = false; this.setKeys = new Set(); this.setWild = false; this.on = new Set();
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The entries of one operation that belong to a root (or start with a wildcard), parsed. */
|
|
100
|
+
function entriesFor(root, allow, op) {
|
|
101
|
+
const list = allow[op] ?? [];
|
|
102
|
+
if (!Array.isArray(list) || list.length > OBJECTS_TYPES_LIMITS.maxEntries) throw bad(`allow.${op} must be an array of at most ${OBJECTS_TYPES_LIMITS.maxEntries} entries`);
|
|
103
|
+
const out = [];
|
|
104
|
+
for (const raw of list) {
|
|
105
|
+
const e = parseEntry(raw, op);
|
|
106
|
+
if (e.segs[0] === root || e.segs[0] === '*' || e.segs[0] === '**') out.push(e);
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Is one field of a type-map entry for a path that some entry allows? (`value`: a get or set entry; `args` and `result`: a call entry; `data`: the exact event entry.) */
|
|
112
|
+
function fieldAllowed(entries, field, segs, eventType) {
|
|
113
|
+
if (field === 'data') return entries.on.some((e) => e.type === eventType && e.segs.length === segs.length && e.segs.every((s, i) => s === segs[i]));
|
|
114
|
+
if (field === 'value') return entries.get.some((e) => matches(e.segs, segs)) || entries.set.some((e) => matches(e.segs, segs));
|
|
115
|
+
return entries.call.some((e) => matches(e.segs, segs));
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The part of a host's type map that a key with `ops` may be told: a field is kept only if an entry of an operation the key holds allows its path. (The host
|
|
120
|
+
* uses this for its `types` answer; the map itself was checked when the host was created.)
|
|
121
|
+
*/
|
|
122
|
+
export function narrowTypes({ root, ops, allow, types }) {
|
|
123
|
+
const entries = Object.fromEntries(OPS.map((op) => [op, ops.includes(op) ? entriesFor(root, allow, op) : []]));
|
|
124
|
+
const out = {};
|
|
125
|
+
for (const [key, spec] of Object.entries(types ?? {})) {
|
|
126
|
+
const at = key.indexOf('@');
|
|
127
|
+
const segs = (at < 0 ? key : key.slice(0, at)).split('.');
|
|
128
|
+
if (segs[0] !== root) continue;
|
|
129
|
+
const kept = {};
|
|
130
|
+
for (const [field, text] of Object.entries(spec)) if (fieldAllowed(entries, field, segs, at < 0 ? undefined : key.slice(at + 1))) kept[field] = text;
|
|
131
|
+
if (Object.keys(kept).length) out[key] = kept;
|
|
132
|
+
}
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Text of a `.d.ts` file for one root.
|
|
138
|
+
*
|
|
139
|
+
* @param {{
|
|
140
|
+
* root: string,
|
|
141
|
+
* ops?: Array<'get' | 'call' | 'set' | 'on'>,
|
|
142
|
+
* allow: { get?: string[], call?: string[], set?: string[], on?: string[] },
|
|
143
|
+
* eventFields?: Record<string, string[]>,
|
|
144
|
+
* types?: Record<string, { value?: string, args?: string, result?: string, data?: string }>,
|
|
145
|
+
* }} description - the host's `types` answer for one root (paths qualified with the root, as in `allow`), or the allow-lists a host holds. `ops` is what the key
|
|
146
|
+
* may do on this root (default: all four).
|
|
147
|
+
* @param {{ name?: string }} [options] - the name of the exported type (default: the root's name, capitalised, plus `Remote`)
|
|
148
|
+
* @returns {string}
|
|
149
|
+
*/
|
|
150
|
+
export function describeRootTypes(description, { name } = {}) {
|
|
151
|
+
if (description === null || typeof description !== 'object' || Array.isArray(description)) throw bad('the description must be an object');
|
|
152
|
+
const { root } = description;
|
|
153
|
+
if (typeof root !== 'string' || !ROOT_NAME.test(root)) throw bad('root must be the name of a root');
|
|
154
|
+
const typeName = name ?? `${root.replace(/[^A-Za-z0-9_$]/g, '_').replace(/^./, (c) => c.toUpperCase())}Remote`;
|
|
155
|
+
if (typeof typeName !== 'string' || !IDENT.test(typeName) || typeName.length > 64 || RESERVED.has(typeName)) throw bad(`name ${JSON.stringify(String(typeName).slice(0, 40))} is not a usable type name`);
|
|
156
|
+
const ops = description.ops === undefined ? OPS : description.ops;
|
|
157
|
+
if (!Array.isArray(ops) || !ops.every((o) => OPS.includes(o))) throw bad('ops must list some of get, call, set, on');
|
|
158
|
+
const allow = description.allow;
|
|
159
|
+
if (allow === null || typeof allow !== 'object' || Array.isArray(allow)) throw bad('allow must be { get, call, set, on }');
|
|
160
|
+
for (const k of Object.keys(allow)) if (!OPS.includes(k)) throw bad(`allow.${k} is not an operation`);
|
|
161
|
+
|
|
162
|
+
// 1. The entries the key may use: an operation it was not granted contributes nothing.
|
|
163
|
+
const entries = { get: [], call: [], set: [], on: [] };
|
|
164
|
+
for (const op of OPS) {
|
|
165
|
+
entriesFor(root, allow, op); // shape of every list is checked, granted or not
|
|
166
|
+
if (ops.includes(op)) entries[op] = entriesFor(root, allow, op);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// 2. Event fields: only the ones for types the key may subscribe to.
|
|
170
|
+
const eventFields = {};
|
|
171
|
+
const rawFields = description.eventFields ?? {};
|
|
172
|
+
if (rawFields === null || typeof rawFields !== 'object' || Array.isArray(rawFields)) throw bad('eventFields must be { [type]: [names] }');
|
|
173
|
+
if (Object.keys(rawFields).length > OBJECTS_TYPES_LIMITS.maxEvents) throw bad('too many eventFields');
|
|
174
|
+
for (const [type, names] of Object.entries(rawFields)) {
|
|
175
|
+
if (type !== '*' && !EVENT_TYPE.test(type)) throw bad('an eventFields key must be an event type');
|
|
176
|
+
if (!Array.isArray(names) || names.length > 64 || !names.every((n) => typeof n === 'string' && FIELD_NAME.test(n))) throw bad(`eventFields[${JSON.stringify(type.slice(0, 40))}] must be an array of property names`);
|
|
177
|
+
eventFields[type] = [...new Set(names)].sort();
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// 3. The type map: host-authored text, checked, and only for what an entry allows.
|
|
181
|
+
const typeMap = new Map();
|
|
182
|
+
const rawTypes = description.types ?? {};
|
|
183
|
+
if (rawTypes === null || typeof rawTypes !== 'object' || Array.isArray(rawTypes)) throw bad('types must be an object of paths');
|
|
184
|
+
if (Object.keys(rawTypes).length > TYPE_TEXT_LIMITS.maxEntries) throw bad(`types has more than ${TYPE_TEXT_LIMITS.maxEntries} entries`);
|
|
185
|
+
let total = 0;
|
|
186
|
+
for (const [key, spec] of Object.entries(rawTypes)) {
|
|
187
|
+
if (spec === null || typeof spec !== 'object' || Array.isArray(spec)) throw bad(`types[${JSON.stringify(key.slice(0, 60))}] must be an object`);
|
|
188
|
+
const at = key.indexOf('@');
|
|
189
|
+
const pathText = at < 0 ? key : key.slice(0, at);
|
|
190
|
+
const eventType = at < 0 ? undefined : key.slice(at + 1);
|
|
191
|
+
if (key.length > OBJECTS_TYPES_LIMITS.maxEntryChars) throw bad('a types path is too long');
|
|
192
|
+
const segs = splitPath(pathText, 'types path');
|
|
193
|
+
if (segs.some((s) => s.includes('*'))) throw bad(`types path ${JSON.stringify(pathText.slice(0, 60))} must be literal, with no wildcard`);
|
|
194
|
+
for (const field of Object.keys(spec)) {
|
|
195
|
+
if (!['value', 'args', 'result', 'data'].includes(field)) throw bad(`types[${JSON.stringify(key.slice(0, 60))}].${field} is not one of value, args, result, data`);
|
|
196
|
+
const text = checkTypeText(spec[field], `types[${JSON.stringify(key.slice(0, 60))}].${field}`);
|
|
197
|
+
total += text.length;
|
|
198
|
+
if (total > TYPE_TEXT_LIMITS.maxTotalChars) throw bad(`the type texts are over ${TYPE_TEXT_LIMITS.maxTotalChars} characters together`);
|
|
199
|
+
const op = field === 'value' ? 'get' : field === 'data' ? 'on' : 'call';
|
|
200
|
+
if ((field === 'data') !== (eventType !== undefined)) throw bad(`types[${JSON.stringify(key.slice(0, 60))}]: "data" belongs to an event ("path@type"), the other fields to a path`);
|
|
201
|
+
if (!fieldAllowed(entries, field, segs, eventType)) throw bad(`types[${JSON.stringify(key.slice(0, 60))}].${field}: no ${op === 'get' ? 'get or set' : op} entry allows that path (a type is written only for what the key may do)`);
|
|
202
|
+
}
|
|
203
|
+
typeMap.set(key, spec);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// 4. The tree the entries make.
|
|
207
|
+
let nodeCount = 0;
|
|
208
|
+
const fresh = () => { if (++nodeCount > OBJECTS_TYPES_LIMITS.maxNodes) throw bad(`the entries make more than ${OBJECTS_TYPES_LIMITS.maxNodes} nodes`); return new Node(); };
|
|
209
|
+
const top = fresh();
|
|
210
|
+
const reach = (segs) => {
|
|
211
|
+
let node = top;
|
|
212
|
+
// `root.a.b()`: the first segment is the root itself.
|
|
213
|
+
for (let i = 1; i < segs.length; i++) {
|
|
214
|
+
const s = segs[i];
|
|
215
|
+
if (s === '*' || s === '**') { node.wild = true; return { node, wild: true }; }
|
|
216
|
+
const call = s.endsWith('()') && s.length > 2;
|
|
217
|
+
const key = call ? s.slice(0, -2) : s;
|
|
218
|
+
let kid = node.kids.get(key);
|
|
219
|
+
if (!kid) { kid = fresh(); node.kids.set(key, kid); }
|
|
220
|
+
if (call) { kid.result ??= fresh(); node = kid.result; } else node = kid;
|
|
221
|
+
}
|
|
222
|
+
return { node, wild: false };
|
|
223
|
+
};
|
|
224
|
+
for (const op of OPS) {
|
|
225
|
+
for (const e of entries[op]) {
|
|
226
|
+
if (e.segs[0] !== root) { top.wild = true; continue; } // a pattern that starts with a wildcard: any root, any path
|
|
227
|
+
if (op === 'set') {
|
|
228
|
+
if (e.segs.length < 2) continue; // the root itself is not assigned
|
|
229
|
+
// The last segment is the property that may be assigned: it belongs to its parent's `set` brand.
|
|
230
|
+
const parentSegs = e.segs.slice(0, -1);
|
|
231
|
+
const last = e.segs[e.segs.length - 1];
|
|
232
|
+
const { node, wild } = reach(parentSegs.length ? parentSegs : [root]);
|
|
233
|
+
if (wild) continue;
|
|
234
|
+
if (last === '*' || last === '**') node.setWild = true; else node.setKeys.add(last.endsWith('()') ? last.slice(0, -2) : last);
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
const { node, wild } = reach(e.segs);
|
|
238
|
+
if (wild) { /* the pattern ends in a wildcard: its parent's members are not enumerated */ }
|
|
239
|
+
if (op === 'on') { if (!wild) node.on.add(e.type); continue; }
|
|
240
|
+
if (!wild || e.segs[e.segs.length - 1] === '**') node[op] = true;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// 5. The text.
|
|
245
|
+
const member = (key) => (IDENT.test(key) ? key : JSON.stringify(key));
|
|
246
|
+
const pathOf = (segs) => segs.join('.');
|
|
247
|
+
const eventFor = (type, path) => {
|
|
248
|
+
const spec = typeMap.get(`${path}@${type}`);
|
|
249
|
+
const fields = [...new Set([...(eventFields[type] ?? []), ...(eventFields['*'] ?? [])])].sort();
|
|
250
|
+
const fieldUnion = fields.length ? fields.map((f) => JSON.stringify(f)).join(' | ') : 'never';
|
|
251
|
+
const data = spec?.data ?? `RemoteEventData<${fieldUnion}>`;
|
|
252
|
+
return `${JSON.stringify(type)}: { data: ${data}; fields: ${fieldUnion} }`;
|
|
253
|
+
};
|
|
254
|
+
const render = (node, segs, indent) => {
|
|
255
|
+
const path = pathOf(segs);
|
|
256
|
+
const pad = ' '.repeat(indent + 1);
|
|
257
|
+
const parts = [];
|
|
258
|
+
const spec = typeMap.get(path);
|
|
259
|
+
if (node.get) parts.push(`RemoteValue<${spec?.value ?? 'unknown'}>`);
|
|
260
|
+
const members = [...node.kids.keys()].sort();
|
|
261
|
+
const lines = [];
|
|
262
|
+
for (const key of members) {
|
|
263
|
+
const kid = node.kids.get(key);
|
|
264
|
+
lines.push(`${pad}readonly ${member(key)}: ${render(kid, [...segs, key], indent + 1)};`);
|
|
265
|
+
}
|
|
266
|
+
if (node.wild) lines.push(`${pad}readonly [key: string]: RemoteUntyped;`);
|
|
267
|
+
if (lines.length) parts.push(`{\n${lines.join('\n')}\n${' '.repeat(indent)}}`);
|
|
268
|
+
if (node.on.size) parts.push(`WithEvents<{ ${[...node.on].sort().map((t) => eventFor(t, path)).join('; ')} }>`);
|
|
269
|
+
if (node.setWild) parts.push('WithSet<Record<string, unknown>>');
|
|
270
|
+
else if (node.setKeys.size) parts.push(`WithSet<{ ${[...node.setKeys].sort().map((k) => `${member(k)}: ${typeMap.get(`${path}.${k}`)?.value ?? 'unknown'}`).join('; ')} }>`);
|
|
271
|
+
if (node.call) {
|
|
272
|
+
const callSpec = typeMap.get(path);
|
|
273
|
+
const args = callSpec?.args ?? 'unknown[]';
|
|
274
|
+
const result = callSpec?.result ?? 'unknown';
|
|
275
|
+
const resultNode = node.result;
|
|
276
|
+
const members2 = resultNode ? render(resultNode, [...segs.slice(0, -1), `${segs[segs.length - 1]}()`], indent) : 'unknown';
|
|
277
|
+
parts.push(`RemoteCall<${args}, ${result}, ${members2}>`);
|
|
278
|
+
}
|
|
279
|
+
return parts.length ? parts.join(' & ') : '{}';
|
|
280
|
+
};
|
|
281
|
+
const body = render(top, [root], 0);
|
|
282
|
+
|
|
283
|
+
return [
|
|
284
|
+
`// Generated by describeRootTypes of @johnhenry/wsh for the root ${JSON.stringify(root)}. It describes what ONE key may do on this root and nothing more:`,
|
|
285
|
+
'// a path that is not here is refused, an operation that is not here is refused, and a type is advisory (it is erased before anything runs).',
|
|
286
|
+
'// Values are unknown unless the host supplied a type; the host\'s type texts are copied as written and never evaluated. Do not edit: fetch it again.',
|
|
287
|
+
"import type { RemoteValue, RemoteCall, RemoteUntyped, RemoteHandle, NonValue, WithEvents, WithSet, RemoteEventData } from '@johnhenry/wsh/objects';",
|
|
288
|
+
'',
|
|
289
|
+
`export type ${typeName} = ${body};`,
|
|
290
|
+
'',
|
|
291
|
+
].join('\n');
|
|
292
|
+
}
|
package/src/objects.d.ts
CHANGED
|
@@ -22,15 +22,63 @@ export class ObjectsError extends Error {
|
|
|
22
22
|
* What a value that cannot be cloned arrives as on a root that opted in to handles: an opaque token, nothing of it enumerable, not thenable, not an argument.
|
|
23
23
|
* It stands at the path that produced it: `use(handle)` makes a reference that continues that path; `release(handle)` gives its place back.
|
|
24
24
|
*/
|
|
25
|
-
export class RemoteHandle {
|
|
25
|
+
export class RemoteHandle<T = any> {
|
|
26
26
|
readonly kind: 'function' | 'object';
|
|
27
27
|
/** The class name, or a function's name. */
|
|
28
28
|
readonly type?: string;
|
|
29
29
|
/** Up to 8 member names, only if a `get` entry names the handle's path. */
|
|
30
30
|
readonly preview?: { keys: string[] };
|
|
31
|
+
/** Type-only: the shape of the value behind the handle, for `use` (a host's type map, or a type you write). Not there at run time. */
|
|
32
|
+
readonly [handleShape]?: T;
|
|
31
33
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
+
declare const handleShape: unique symbol;
|
|
35
|
+
declare const eventsBrand: unique symbol;
|
|
36
|
+
declare const setBrand: unique symbol;
|
|
37
|
+
|
|
38
|
+
// ── Typed remotes (#219) ────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
39
|
+
// A reference is a lazy path whose `await` is the value: it is `PromiseLike` (not a `Promise`: there is no `catch` or `finally` on it, and `ref.catch` would be a
|
|
40
|
+
// remote property named "catch"). `describeRootTypes` (from `@johnhenry/wsh/objects-types`) writes types for one root out of these pieces; you can write them by hand.
|
|
41
|
+
|
|
42
|
+
/** Anything: what a wildcard in an allow-list entry is typed as (the members behind it are not guessed). */
|
|
43
|
+
export type RemoteUntyped = any;
|
|
44
|
+
/** A path whose `await` is a `V` (a get). */
|
|
45
|
+
export type RemoteValue<V = unknown> = PromiseLike<V>;
|
|
46
|
+
/** A method: calling it gives a reference whose `await` is an `R` and that continues as `M` (`window.app.makeBus().ping`). Arguments are plain data. */
|
|
47
|
+
export type RemoteCall<A extends unknown[] = unknown[], R = unknown, M = unknown> = (...args: A) => PromiseLike<R> & M;
|
|
48
|
+
/** What a listener receives: an Event as `{ type, timeStamp, isTrusted, ...the fields you asked for }`, an emitter's as `{ type, args }`. */
|
|
49
|
+
export type RemoteEventData<F extends string = never> = { type: string; timeStamp?: number; isTrusted?: boolean; args?: unknown[] } & { [K in F]?: unknown };
|
|
50
|
+
/** The events a source offers, as `{ [type]: { data, fields } }`: it makes `on(ref, type, listener)` check the type, the data and the fields. */
|
|
51
|
+
export type WithEvents<E extends Record<string, { data: unknown; fields: string }>> = { readonly [eventsBrand]: E };
|
|
52
|
+
/** The properties of a node that may be assigned, as `{ [key]: valueType }`: it makes `set(ref, key, value)` check the key and the value. */
|
|
53
|
+
export type WithSet<S extends Record<string, unknown>> = { readonly [setBrand]: S };
|
|
54
|
+
|
|
55
|
+
type IsAny<T> = 0 extends 1 & T ? true : false;
|
|
56
|
+
type EventMapOf<R> = IsAny<R> extends true ? never : R extends { readonly [eventsBrand]: infer E } ? E : never;
|
|
57
|
+
type EventTypeOf<R> = [EventMapOf<R>] extends [never] ? string : Extract<keyof EventMapOf<R>, string>;
|
|
58
|
+
type EventDataOf<R, K> = [EventMapOf<R>] extends [never] ? any : K extends keyof EventMapOf<R> ? (EventMapOf<R>[K] extends { data: infer D } ? D : any) : any;
|
|
59
|
+
type EventFieldsOf<R, K> = [EventMapOf<R>] extends [never] ? string : K extends keyof EventMapOf<R> ? (EventMapOf<R>[K] extends { fields: infer F extends string } ? F : string) : string;
|
|
60
|
+
type SetMapOf<R> = IsAny<R> extends true ? never : R extends { readonly [setBrand]: infer S } ? S : never;
|
|
61
|
+
type SetKeyOf<R> = [SetMapOf<R>] extends [never] ? string | number : Extract<keyof SetMapOf<R>, string>;
|
|
62
|
+
type SetValueOf<R, K> = [SetMapOf<R>] extends [never] ? unknown : K extends keyof SetMapOf<R> ? SetMapOf<R>[K] : unknown;
|
|
63
|
+
|
|
64
|
+
type RemotePrimitive = string | number | boolean | bigint | symbol | null | undefined;
|
|
65
|
+
/**
|
|
66
|
+
* The reference type of a value type you write: `Remote<{ cart: { add(item: Item): number; items: Item[] } }>` is what `await`s to the value, has the members as references,
|
|
67
|
+
* and has methods that return references. Hand-written `T` says what you believe the host exposes; the host's allow-lists still decide. Arguments stay plain data.
|
|
68
|
+
*/
|
|
69
|
+
export type Remote<T> =
|
|
70
|
+
0 extends 1 & T ? any
|
|
71
|
+
: T extends RemotePrimitive ? PromiseLike<T>
|
|
72
|
+
: T extends (...args: infer A) => infer R ? (...args: A) => Remote<Awaited<R>>
|
|
73
|
+
: T extends Uint8Array | ArrayBuffer ? PromiseLike<T>
|
|
74
|
+
: T extends readonly (infer U)[] ? PromiseLike<T> & { readonly length: PromiseLike<number>; readonly [index: number]: Remote<U> }
|
|
75
|
+
: T extends object ? PromiseLike<T> & WithSet<{ [K in keyof T]: T[K] }> & { readonly [K in keyof T]: Remote<T[K]> }
|
|
76
|
+
: PromiseLike<T>;
|
|
77
|
+
/** The roots as `openObjects` returns them, for value types you write: `client.openObjects<RemoteRoots<{ window: MyWindow }>>()`. A generated `{ window: WindowRemote }` is already remote-shaped. */
|
|
78
|
+
export type RemoteRoots<T> = { readonly [K in keyof T]: Remote<T[K]> };
|
|
79
|
+
|
|
80
|
+
/** A reference that stands on a handle: `await use(handle).items.length`. Judged by the producing path extended by what you name. With a typed handle (`RemoteHandle<Cart>`), a `Remote<Cart>`. */
|
|
81
|
+
export function use<T = any>(handle: RemoteHandle<T>): 0 extends 1 & T ? any : Remote<T>;
|
|
34
82
|
/** Give a handle's place back (releasing a released handle does nothing); or kill the stub of a function that was passed as a callback. */
|
|
35
83
|
export function release(handleOrCallback: RemoteHandle | ((...args: any[]) => unknown)): Promise<void>;
|
|
36
84
|
|
|
@@ -76,6 +124,12 @@ export interface ObjectsLimits {
|
|
|
76
124
|
maxCallbacksPerSecond: number;
|
|
77
125
|
/** Bytes of the arguments of one callback call; a bigger one is dropped and counted. Default 16384. */
|
|
78
126
|
maxCallbackBytes: number;
|
|
127
|
+
/** The longest the page's stub waits for a far-side function that returns (`(callback:returns)`), from the call; then its promise is settled with `undefined`. Default 2000, at most 30000. */
|
|
128
|
+
callbackReturnTimeoutMs: number;
|
|
129
|
+
/** Calls of returning callbacks waiting for an answer per channel; a call beyond it is dropped and counted, never sent. Default 8, at most 64. */
|
|
130
|
+
maxPendingCallbackReturns: number;
|
|
131
|
+
/** Bytes of the value a far-side callback answers with; a bigger one, or one that is not plain data, is `undefined` for the page. Default 16384. */
|
|
132
|
+
maxCallbackResultBytes: number;
|
|
79
133
|
}
|
|
80
134
|
export const OBJECTS_DEFAULT_LIMITS: Readonly<ObjectsLimits>;
|
|
81
135
|
|
|
@@ -85,7 +139,9 @@ export const NEEDS_LISTING: ReadonlyArray<readonly string[]>;
|
|
|
85
139
|
/** Allow-lists by operation: path patterns from a root (`'window.document.title'`, `'window.app.**'`; `*` is one segment, `**` any number). `call` covers `construct`. Nothing is allowed by default. */
|
|
86
140
|
export interface ObjectsAllow {
|
|
87
141
|
get?: string[];
|
|
88
|
-
// (`call` entries may end in `(callback)`: the call accepts functions as arguments, which reach the page as one-way stubs.)
|
|
142
|
+
// (`call` entries may end in `(callback)`: the call accepts functions as arguments, which reach the page as one-way stubs. `(callback:returns)` also lets the stub return a
|
|
143
|
+
// promise of the far side's return value, `(callback:returns=0,2)` only for the functions at those argument positions; the wait is bounded by `callbackReturnTimeoutMs`
|
|
144
|
+
// and every other outcome is `undefined`. It needs `timers` (`exposeObjects` and `createPageHost` supply them).)
|
|
89
145
|
call?: string[];
|
|
90
146
|
set?: string[];
|
|
91
147
|
/** Event sources, as `path@type` (`'window.app.bus@ready'`; the source and the type are named exactly, a wildcard in either is refused). Never implied by the other lists. */
|
|
@@ -133,6 +189,14 @@ export interface ObjectsServerOptions {
|
|
|
133
189
|
limits?: Partial<ObjectsLimits>;
|
|
134
190
|
/** Extra event fields a subscriber may ask for, by event type (`'*'`: any type): property names read from the event and copied as plain data (a node is left out). */
|
|
135
191
|
eventFields?: Record<string, string[]>;
|
|
192
|
+
/**
|
|
193
|
+
* Types for the far side's `.d.ts`, by qualified path (`'window.app.cart.add': { args: '[item: { sku: string }]', result: 'number' }`; `value` for a get, `data` for an
|
|
194
|
+
* event `'window.app.bus@ready'`). Host-authored text that is sent to the far side: checked when the host is created (a conservative type syntax, bounded, only for a path
|
|
195
|
+
* an allow-list entry names), copied into a file there and never evaluated. A bad text or an unlisted path is a `TypeError` here.
|
|
196
|
+
*/
|
|
197
|
+
types?: Record<string, { value?: string; args?: string; result?: string; data?: string }>;
|
|
198
|
+
/** An MCP face for named paths, off unless written: `{ tools: [{ name, description, call: 'window.app.cart.add', inputSchema }, { name, description, get: 'window.document.title' }] }`. */
|
|
199
|
+
mcp?: { tools: ObjectsMcpTool[] };
|
|
136
200
|
/** Why nothing may be served any more (the window left), else null. */
|
|
137
201
|
guard?: () => string | null;
|
|
138
202
|
/** For `callTimeoutMs`. */
|
|
@@ -154,11 +218,54 @@ export interface ObjectsPeer {
|
|
|
154
218
|
/** The transport-neutral server half: roots, allow-lists and limits, attachable to any peer. Knows nothing about wsh. */
|
|
155
219
|
export function createObjectsServer(options: ObjectsServerOptions): {
|
|
156
220
|
/** `who`: the identity of every call unless the peer gives one per call (`ctx.who`); one that names two keys, or is not an identity, throws a `TypeError` here. */
|
|
157
|
-
attach(peer: Pick<ObjectsPeer, 'onRequest' | 'maxMessageBytes'>, options?: { who?: ObjectsIdentity }): {
|
|
221
|
+
attach(peer: Pick<ObjectsPeer, 'onRequest' | 'maxMessageBytes'>, options?: { who?: ObjectsIdentity }): {
|
|
222
|
+
limits: ObjectsLimits;
|
|
223
|
+
/** What became of the calls of callbacks that return: `pending` now, and in total `answered`, `timedOut`, `failed`, `refused` and `dropped`. */
|
|
224
|
+
callbackReturnStats(): { pending: number; answered: number; timedOut: number; failed: number; refused: number; dropped: number };
|
|
225
|
+
};
|
|
226
|
+
/**
|
|
227
|
+
* One `get` or `call` of a named path (`path` starts with the root), through the same checks as an objects call (the key's grants as `permit(root, op)`, the allow-lists,
|
|
228
|
+
* the names that need listing, `authorize`, the window guard). No session, so no handle and no callback; resolves with the wire value (`{ v }`, or a named non-value `{ u }`).
|
|
229
|
+
*/
|
|
230
|
+
invoke(request: { kind: 'get' | 'call'; path: string[]; args?: unknown[] }, ctx?: { who?: ObjectsIdentity; permit?: (root: string, op: string) => boolean; signal?: AbortSignal }): Promise<{ v: unknown } | { u: string; type?: string; text?: string }>;
|
|
158
231
|
readonly limits: Readonly<ObjectsLimits>;
|
|
159
232
|
readonly rootNames: string[];
|
|
233
|
+
/** The tools the host named in `mcp: { tools }` (none unless written), as definitions for `webmcpTools({ tools })`. */
|
|
234
|
+
readonly mcpTools: ObjectsMcpToolDefinition[];
|
|
235
|
+
readonly mcpToolNames: string[];
|
|
160
236
|
};
|
|
161
237
|
|
|
238
|
+
/**
|
|
239
|
+
* One path made into an MCP tool (#219). Nothing is a tool by being allowed: the host writes each one. Exactly one of `call` (a method, as the objects client would call it) and `get`
|
|
240
|
+
* (a value) names the path, a literal one that the allow-lists name for that operation. `inputSchema` is a small subset of JSON Schema (an unsupported keyword is refused when the host is made)
|
|
241
|
+
* that the far side's arguments are checked against before the person is asked and before the page runs anything; with none, the tool takes no arguments.
|
|
242
|
+
*/
|
|
243
|
+
export interface ObjectsMcpTool {
|
|
244
|
+
/** 1-128 characters of letters, digits, `_`, `-` and `.`. */
|
|
245
|
+
name: string;
|
|
246
|
+
title?: string;
|
|
247
|
+
/** What the far side reads to decide when to call it: written by the host. */
|
|
248
|
+
description: string;
|
|
249
|
+
/** A method path from a root, qualified (`'window.app.cart.add'`) in `exposeObjects`; relative to the root (`'app.cart.add'`) in `createPageHost({ expose })`. */
|
|
250
|
+
call?: string;
|
|
251
|
+
/** A value path, as for `call`. Read-only by default. */
|
|
252
|
+
get?: string;
|
|
253
|
+
inputSchema?: Record<string, unknown>;
|
|
254
|
+
/** For a call: `'object'` (the validated input is the one argument) or the property names to pass, in order. Default: `'object'` when the schema lists properties, else none. */
|
|
255
|
+
args?: 'object' | string[];
|
|
256
|
+
/** `true` marks the tool read-only; with nothing said, neither a get nor a call is (a getter can have effects). A tool not marked read-only asks the person at the page first (the WebMCP bridge's approval). */
|
|
257
|
+
readOnly?: boolean;
|
|
258
|
+
}
|
|
259
|
+
/** A tool as `webmcpTools({ tools })` takes it (what `exposeObjects` builds from an `ObjectsMcpTool`). */
|
|
260
|
+
export interface ObjectsMcpToolDefinition {
|
|
261
|
+
name: string;
|
|
262
|
+
title?: string;
|
|
263
|
+
description: string;
|
|
264
|
+
inputSchema: Record<string, unknown>;
|
|
265
|
+
annotations: { readOnlyHint: boolean };
|
|
266
|
+
execute(input: Record<string, any>, options?: { signal?: AbortSignal; who?: ObjectsIdentity; permits?: (request: { kind: string; [k: string]: unknown }) => boolean }): Promise<unknown>;
|
|
267
|
+
}
|
|
268
|
+
|
|
162
269
|
/**
|
|
163
270
|
* A peer over `send(message)` and `receive(message)`: the same protocol over any duplex that is not wsh. `who` is who is on the far side, as an
|
|
164
271
|
* identity object (a pod id goes in `podId`, not in a field named `fingerprint`); `permit(root, op)` is the transport's own capability check
|
|
@@ -182,6 +289,9 @@ export interface ObjectsHandler {
|
|
|
182
289
|
closeSessions(reason: string, fingerprint?: string): Promise<number>;
|
|
183
290
|
readonly rootNames: string[];
|
|
184
291
|
readonly limits: Readonly<ObjectsLimits>;
|
|
292
|
+
/** The MCP face (#219): the tools named in `mcp: { tools }`, for `webmcpTools({ window, tools: handler.mcpTools, allow: handler.mcpToolNames })`. Empty unless written. */
|
|
293
|
+
readonly mcpTools: ObjectsMcpToolDefinition[];
|
|
294
|
+
readonly mcpToolNames: string[];
|
|
185
295
|
}
|
|
186
296
|
export function exposeObjects(options: ObjectsServerOptions): ObjectsHandler;
|
|
187
297
|
|
|
@@ -201,7 +311,7 @@ declare module './index.js' {
|
|
|
201
311
|
/** The value at a reference, or at a property of it: `await get(ref, 'then')` reaches a property that `ref.then` cannot. */
|
|
202
312
|
export function get(ref: any, ...keys: Array<string | number>): Promise<any>;
|
|
203
313
|
/** Assign a property of a remote object (not `=`: that throws). The reference must be a plain path. */
|
|
204
|
-
export function set(ref:
|
|
314
|
+
export function set<R, K extends SetKeyOf<R>>(ref: R, key: K, value: SetValueOf<R, K>): Promise<void>;
|
|
205
315
|
/** Call a method reached by name, with plain-data arguments. */
|
|
206
316
|
export function call(ref: any, ...args: unknown[]): Promise<any>;
|
|
207
317
|
/** `new` a constructor reached by name. */
|
|
@@ -212,7 +322,17 @@ export function snapshot(ref: any, options?: { depth?: number; maxBytes?: number
|
|
|
212
322
|
* Listen for an event of a remote source named by the host's `allow.on`. `data` is plain: an Event as `{ type, timeStamp, isTrusted, ...fields }`, an emitter's as
|
|
213
323
|
* `{ type, args }`. `dropped` counts events the host dropped before this one. Resolves to the function that unsubscribes. Never an event object, never a handle.
|
|
214
324
|
*/
|
|
215
|
-
|
|
325
|
+
/**
|
|
326
|
+
* `ref` is a path reached from a root, or a reference that stands on a handle (`use(handle).bus`): the source is then the handle's producing path extended as
|
|
327
|
+
* written, and needs its own `allow.on` entry naming the type, the key's `objects:ROOT:on` and `authorize`. The subscription ends when the handle is released.
|
|
328
|
+
* A host before 0.51.0 does not say it supports this (`unsupported`).
|
|
329
|
+
*/
|
|
330
|
+
export function on<R, K extends EventTypeOf<R>>(ref: R, type: K, listener: (data: EventDataOf<R, K>, info: { type: string; seq: number; dropped: number }) => void, options?: { fields?: Array<EventFieldsOf<R, K>>; onError?: (error: unknown) => void }): Promise<() => Promise<void>>;
|
|
331
|
+
/**
|
|
332
|
+
* What this key may do on a root, as data (`{ version, root, ops, allow, eventFields, types }`): the host's allow-list entries for the root narrowed by the key's capabilities,
|
|
333
|
+
* and the host's type map for them. Pass it to `describeRootTypes` (`@johnhenry/wsh/objects-types`) for the text of a `.d.ts`. A host before 0.51.0 does not say it supports this (`unsupported`).
|
|
334
|
+
*/
|
|
335
|
+
export function rootDescription(root: unknown, options?: { signal?: AbortSignal }): Promise<import('./objects-types.js').RootDescription & { version: number; ops: Array<'get' | 'call' | 'set' | 'on'>; handles: boolean }>;
|
|
216
336
|
/** Stop a subscription: what `on` resolved to. */
|
|
217
337
|
export function off(unsubscribe: () => Promise<void>): Promise<void>;
|
|
218
338
|
/** The shape of an object, for completion: the names and types the allow-list could walk to. */
|
package/src/objects.mjs
CHANGED
|
@@ -29,7 +29,7 @@ import {
|
|
|
29
29
|
export {
|
|
30
30
|
OBJECTS_PROTOCOL, OBJECTS_ERROR, OBJECTS_DEFAULT_LIMITS, NEEDS_LISTING, ObjectsError, NonValue,
|
|
31
31
|
createObjectsServer, createObjectsClient, createDuplexPeer, matchPath, toWire, fromWire,
|
|
32
|
-
get, set, call, construct, snapshot, describe, on, off, use, release, RemoteHandle, closeObjects,
|
|
32
|
+
get, set, call, construct, snapshot, describe, on, off, use, release, RemoteHandle, closeObjects, rootDescription,
|
|
33
33
|
} from './objects-core.mjs';
|
|
34
34
|
|
|
35
35
|
/** Timers for `callTimeoutMs` where the embedder gave none: this module is the Node-or-browser adapter, not the page entry point. */
|
|
@@ -93,6 +93,9 @@ export function exposeObjects(options = {}) {
|
|
|
93
93
|
handler.capabilityScoped = true;
|
|
94
94
|
handler.rootNames = server.rootNames;
|
|
95
95
|
handler.limits = server.limits;
|
|
96
|
+
// The MCP face (#219): the tools the host named in `mcp: { tools }` (none unless written), for `webmcpTools({ tools: handler.mcpTools, allow: handler.mcpToolNames })`.
|
|
97
|
+
handler.mcpTools = server.mcpTools;
|
|
98
|
+
handler.mcpToolNames = server.mcpToolNames;
|
|
96
99
|
return handler;
|
|
97
100
|
}
|
|
98
101
|
|
package/src/page-host.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { RpcChannel } from './index.js';
|
|
2
2
|
import type { WshRpcContext } from './server/index.js';
|
|
3
3
|
import type { WshOnRefused } from './host.js';
|
|
4
|
-
import type { ObjectsAllow, ObjectsWho, ObjectsOperation, ObjectsLimits } from './objects.js';
|
|
4
|
+
import type { ObjectsAllow, ObjectsWho, ObjectsOperation, ObjectsLimits, ObjectsMcpTool } from './objects.js';
|
|
5
5
|
|
|
6
6
|
export { exposeObjects } from './objects.js';
|
|
7
7
|
|
|
@@ -195,11 +195,10 @@ export interface WshPageIndicatorCallbacks {
|
|
|
195
195
|
disconnected(who: { username: string; fingerprint: string }): void;
|
|
196
196
|
}
|
|
197
197
|
|
|
198
|
-
|
|
198
|
+
/** The options every form of the page host takes (where it dials is `relay` or `connect`, see `WshPageHostOptions` and `WshPageDialOutOptions`). */
|
|
199
|
+
export interface WshPageHostBaseOptions {
|
|
199
200
|
/** The realm to serve: required, and the only thing read. Passing it exposes nothing by itself. */
|
|
200
201
|
window: WshPageWindow;
|
|
201
|
-
/** A pipe relay (`@johnhenry/wsh/pipe-relay`): its `ws://` / `wss://` URL, or `{ url, id }` with a rendezvous id of your own. */
|
|
202
|
-
relay: string | { url: string; id?: string };
|
|
203
202
|
/** What this tab is called: shown in the indicator, the `serverInfo.name` of the MCP server. */
|
|
204
203
|
name: string;
|
|
205
204
|
/** Who may log in: `authorized_keys` lines (options such as `capabilities="mcp:search"` apply) or raw 32-byte keys. Required. */
|
|
@@ -211,7 +210,7 @@ export interface WshPageHostOptions {
|
|
|
211
210
|
* `'document.title'`, `'app.**'`; nothing allowed by default). A root named `window` is the window that was passed; another name needs `object`.
|
|
212
211
|
* `mode: 'handles'` is this root's own opt-in to handles (`nodes: true` a second, for nodes and the window graph). See `@johnhenry/wsh/objects`.
|
|
213
212
|
*/
|
|
214
|
-
expose?: Record<string, { mode?: 'values' | 'handles'; nodes?: boolean; wideEntries?: boolean; allow?: ObjectsAllow; authorize?: (who: ObjectsWho, op: ObjectsOperation) => boolean | Promise<boolean>; limits?: Partial<ObjectsLimits>; object?: object; eventFields?: Record<string, string[]
|
|
213
|
+
expose?: Record<string, { mode?: 'values' | 'handles'; nodes?: boolean; wideEntries?: boolean; allow?: ObjectsAllow; authorize?: (who: ObjectsWho, op: ObjectsOperation) => boolean | Promise<boolean>; limits?: Partial<ObjectsLimits>; object?: object; eventFields?: Record<string, string[]>; /** Host-authored type texts for the far side's `.d.ts`, by path relative to the root (`'app.cart.add'`, `'app.bus@ready'`, `'@hashchange'`); checked, bounded, never evaluated. */ types?: Record<string, { value?: string; args?: string; result?: string; data?: string }>; /** An MCP face for named paths of this root (paths relative to it), served on the `mcp` channel beside the WebMCP tools: nothing is a tool by being allowed. */ mcp?: { tools: ObjectsMcpTool[] } }>;
|
|
215
214
|
/** `true` (default): the badge in `window.document`. Callbacks: for a context with no document, or your own UI. `false` needs `unattended: true`. */
|
|
216
215
|
indicator?: boolean | WshPageIndicatorCallbacks;
|
|
217
216
|
/** Nobody is in front of this window. Allows `indicator: false` and a window with no document; what needs approval is then denied unless `mcp.prompt` answers. */
|
|
@@ -232,6 +231,23 @@ export interface WshPageHostOptions {
|
|
|
232
231
|
onLog?: (line: string) => void;
|
|
233
232
|
}
|
|
234
233
|
|
|
234
|
+
/** The default form: the page dials a pipe relay and the operator dials the same relay. */
|
|
235
|
+
export interface WshPageHostOptions extends WshPageHostBaseOptions {
|
|
236
|
+
/** A pipe relay (`@johnhenry/wsh/pipe-relay`): its `ws://` / `wss://` URL, or `{ url, id }` with a rendezvous id of your own. */
|
|
237
|
+
relay: string | { url: string; id?: string };
|
|
238
|
+
connect?: never;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* The dial-out form, off unless written: the page dials an operator that WAITS (a process that listens and logs in as the client over what it accepts, for example
|
|
243
|
+
* with `connectWshOverDuplex`) instead of a relay. Not together with `relay`. The URL is dialled exactly as written (no role or rendezvous id is added), must be
|
|
244
|
+
* `ws://` or `wss://` with no user name, password or fragment, and is never logged. The login, the sealed session, the approval, the indicator and Stop are the same.
|
|
245
|
+
*/
|
|
246
|
+
export interface WshPageDialOutOptions extends WshPageHostBaseOptions {
|
|
247
|
+
connect: string | { url: string };
|
|
248
|
+
relay?: never;
|
|
249
|
+
}
|
|
250
|
+
|
|
235
251
|
export interface WshPageHost {
|
|
236
252
|
/** The URL an operator dials. Its rendezvous id is the secret that pairs the operator with this page. */
|
|
237
253
|
readonly operatorUrl: string;
|
|
@@ -251,7 +267,12 @@ export interface WshPageHost {
|
|
|
251
267
|
close(): Promise<void>;
|
|
252
268
|
}
|
|
253
269
|
|
|
270
|
+
/** What `createPageHost` gives for the dial-out form: nobody dials this page, so there is no `operatorUrl` and no rendezvous id. */
|
|
271
|
+
export type WshPageDialOutHost = Omit<WshPageHost, 'operatorUrl' | 'rendezvousId'> & { readonly operatorUrl: null; readonly rendezvousId: null };
|
|
272
|
+
|
|
254
273
|
/** A page (or any window-shaped realm) as a host behind a pipe relay it chose: key login only, sealed sessions only, the window's WebMCP tools as MCP. */
|
|
255
274
|
export function createPageHost(options: WshPageHostOptions): Promise<WshPageHost>;
|
|
275
|
+
/** The dial-out form: the page dials an operator that listens (`connect`). */
|
|
276
|
+
export function createPageHost(options: WshPageDialOutOptions): Promise<WshPageDialOutHost>;
|
|
256
277
|
|
|
257
278
|
export type { RpcChannel, WshRpcContext };
|