@johnhenry/wsh 0.50.0 → 0.51.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.
@@ -0,0 +1,290 @@
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
+ if (op === 'call' && text.endsWith('(callback)')) { callbacks = true; text = text.slice(0, -'(callback)'.length); }
83
+ const segs = splitPath(text, `allow.${op} entry`);
84
+ 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`);
85
+ return { segs, callbacks, type, text };
86
+ }
87
+
88
+ class Node {
89
+ constructor() {
90
+ this.kids = new Map();
91
+ this.result = null; // the node of what a call of this one returns
92
+ this.wild = false; // a `*` or `**` below: the members are not enumerated
93
+ this.get = false; this.call = false; this.setKeys = new Set(); this.setWild = false; this.on = new Set();
94
+ }
95
+ }
96
+
97
+ /** The entries of one operation that belong to a root (or start with a wildcard), parsed. */
98
+ function entriesFor(root, allow, op) {
99
+ const list = allow[op] ?? [];
100
+ 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`);
101
+ const out = [];
102
+ for (const raw of list) {
103
+ const e = parseEntry(raw, op);
104
+ if (e.segs[0] === root || e.segs[0] === '*' || e.segs[0] === '**') out.push(e);
105
+ }
106
+ return out;
107
+ }
108
+
109
+ /** 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.) */
110
+ function fieldAllowed(entries, field, segs, eventType) {
111
+ if (field === 'data') return entries.on.some((e) => e.type === eventType && e.segs.length === segs.length && e.segs.every((s, i) => s === segs[i]));
112
+ if (field === 'value') return entries.get.some((e) => matches(e.segs, segs)) || entries.set.some((e) => matches(e.segs, segs));
113
+ return entries.call.some((e) => matches(e.segs, segs));
114
+ }
115
+
116
+ /**
117
+ * 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
118
+ * uses this for its `types` answer; the map itself was checked when the host was created.)
119
+ */
120
+ export function narrowTypes({ root, ops, allow, types }) {
121
+ const entries = Object.fromEntries(OPS.map((op) => [op, ops.includes(op) ? entriesFor(root, allow, op) : []]));
122
+ const out = {};
123
+ for (const [key, spec] of Object.entries(types ?? {})) {
124
+ const at = key.indexOf('@');
125
+ const segs = (at < 0 ? key : key.slice(0, at)).split('.');
126
+ if (segs[0] !== root) continue;
127
+ const kept = {};
128
+ for (const [field, text] of Object.entries(spec)) if (fieldAllowed(entries, field, segs, at < 0 ? undefined : key.slice(at + 1))) kept[field] = text;
129
+ if (Object.keys(kept).length) out[key] = kept;
130
+ }
131
+ return out;
132
+ }
133
+
134
+ /**
135
+ * Text of a `.d.ts` file for one root.
136
+ *
137
+ * @param {{
138
+ * root: string,
139
+ * ops?: Array<'get' | 'call' | 'set' | 'on'>,
140
+ * allow: { get?: string[], call?: string[], set?: string[], on?: string[] },
141
+ * eventFields?: Record<string, string[]>,
142
+ * types?: Record<string, { value?: string, args?: string, result?: string, data?: string }>,
143
+ * }} 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
144
+ * may do on this root (default: all four).
145
+ * @param {{ name?: string }} [options] - the name of the exported type (default: the root's name, capitalised, plus `Remote`)
146
+ * @returns {string}
147
+ */
148
+ export function describeRootTypes(description, { name } = {}) {
149
+ if (description === null || typeof description !== 'object' || Array.isArray(description)) throw bad('the description must be an object');
150
+ const { root } = description;
151
+ if (typeof root !== 'string' || !ROOT_NAME.test(root)) throw bad('root must be the name of a root');
152
+ const typeName = name ?? `${root.replace(/[^A-Za-z0-9_$]/g, '_').replace(/^./, (c) => c.toUpperCase())}Remote`;
153
+ 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`);
154
+ const ops = description.ops === undefined ? OPS : description.ops;
155
+ if (!Array.isArray(ops) || !ops.every((o) => OPS.includes(o))) throw bad('ops must list some of get, call, set, on');
156
+ const allow = description.allow;
157
+ if (allow === null || typeof allow !== 'object' || Array.isArray(allow)) throw bad('allow must be { get, call, set, on }');
158
+ for (const k of Object.keys(allow)) if (!OPS.includes(k)) throw bad(`allow.${k} is not an operation`);
159
+
160
+ // 1. The entries the key may use: an operation it was not granted contributes nothing.
161
+ const entries = { get: [], call: [], set: [], on: [] };
162
+ for (const op of OPS) {
163
+ entriesFor(root, allow, op); // shape of every list is checked, granted or not
164
+ if (ops.includes(op)) entries[op] = entriesFor(root, allow, op);
165
+ }
166
+
167
+ // 2. Event fields: only the ones for types the key may subscribe to.
168
+ const eventFields = {};
169
+ const rawFields = description.eventFields ?? {};
170
+ if (rawFields === null || typeof rawFields !== 'object' || Array.isArray(rawFields)) throw bad('eventFields must be { [type]: [names] }');
171
+ if (Object.keys(rawFields).length > OBJECTS_TYPES_LIMITS.maxEvents) throw bad('too many eventFields');
172
+ for (const [type, names] of Object.entries(rawFields)) {
173
+ if (type !== '*' && !EVENT_TYPE.test(type)) throw bad('an eventFields key must be an event type');
174
+ 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`);
175
+ eventFields[type] = [...new Set(names)].sort();
176
+ }
177
+
178
+ // 3. The type map: host-authored text, checked, and only for what an entry allows.
179
+ const typeMap = new Map();
180
+ const rawTypes = description.types ?? {};
181
+ if (rawTypes === null || typeof rawTypes !== 'object' || Array.isArray(rawTypes)) throw bad('types must be an object of paths');
182
+ if (Object.keys(rawTypes).length > TYPE_TEXT_LIMITS.maxEntries) throw bad(`types has more than ${TYPE_TEXT_LIMITS.maxEntries} entries`);
183
+ let total = 0;
184
+ for (const [key, spec] of Object.entries(rawTypes)) {
185
+ if (spec === null || typeof spec !== 'object' || Array.isArray(spec)) throw bad(`types[${JSON.stringify(key.slice(0, 60))}] must be an object`);
186
+ const at = key.indexOf('@');
187
+ const pathText = at < 0 ? key : key.slice(0, at);
188
+ const eventType = at < 0 ? undefined : key.slice(at + 1);
189
+ if (key.length > OBJECTS_TYPES_LIMITS.maxEntryChars) throw bad('a types path is too long');
190
+ const segs = splitPath(pathText, 'types path');
191
+ if (segs.some((s) => s.includes('*'))) throw bad(`types path ${JSON.stringify(pathText.slice(0, 60))} must be literal, with no wildcard`);
192
+ for (const field of Object.keys(spec)) {
193
+ 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`);
194
+ const text = checkTypeText(spec[field], `types[${JSON.stringify(key.slice(0, 60))}].${field}`);
195
+ total += text.length;
196
+ if (total > TYPE_TEXT_LIMITS.maxTotalChars) throw bad(`the type texts are over ${TYPE_TEXT_LIMITS.maxTotalChars} characters together`);
197
+ const op = field === 'value' ? 'get' : field === 'data' ? 'on' : 'call';
198
+ 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`);
199
+ 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)`);
200
+ }
201
+ typeMap.set(key, spec);
202
+ }
203
+
204
+ // 4. The tree the entries make.
205
+ let nodeCount = 0;
206
+ const fresh = () => { if (++nodeCount > OBJECTS_TYPES_LIMITS.maxNodes) throw bad(`the entries make more than ${OBJECTS_TYPES_LIMITS.maxNodes} nodes`); return new Node(); };
207
+ const top = fresh();
208
+ const reach = (segs) => {
209
+ let node = top;
210
+ // `root.a.b()`: the first segment is the root itself.
211
+ for (let i = 1; i < segs.length; i++) {
212
+ const s = segs[i];
213
+ if (s === '*' || s === '**') { node.wild = true; return { node, wild: true }; }
214
+ const call = s.endsWith('()') && s.length > 2;
215
+ const key = call ? s.slice(0, -2) : s;
216
+ let kid = node.kids.get(key);
217
+ if (!kid) { kid = fresh(); node.kids.set(key, kid); }
218
+ if (call) { kid.result ??= fresh(); node = kid.result; } else node = kid;
219
+ }
220
+ return { node, wild: false };
221
+ };
222
+ for (const op of OPS) {
223
+ for (const e of entries[op]) {
224
+ if (e.segs[0] !== root) { top.wild = true; continue; } // a pattern that starts with a wildcard: any root, any path
225
+ if (op === 'set') {
226
+ if (e.segs.length < 2) continue; // the root itself is not assigned
227
+ // The last segment is the property that may be assigned: it belongs to its parent's `set` brand.
228
+ const parentSegs = e.segs.slice(0, -1);
229
+ const last = e.segs[e.segs.length - 1];
230
+ const { node, wild } = reach(parentSegs.length ? parentSegs : [root]);
231
+ if (wild) continue;
232
+ if (last === '*' || last === '**') node.setWild = true; else node.setKeys.add(last.endsWith('()') ? last.slice(0, -2) : last);
233
+ continue;
234
+ }
235
+ const { node, wild } = reach(e.segs);
236
+ if (wild) { /* the pattern ends in a wildcard: its parent's members are not enumerated */ }
237
+ if (op === 'on') { if (!wild) node.on.add(e.type); continue; }
238
+ if (!wild || e.segs[e.segs.length - 1] === '**') node[op] = true;
239
+ }
240
+ }
241
+
242
+ // 5. The text.
243
+ const member = (key) => (IDENT.test(key) ? key : JSON.stringify(key));
244
+ const pathOf = (segs) => segs.join('.');
245
+ const eventFor = (type, path) => {
246
+ const spec = typeMap.get(`${path}@${type}`);
247
+ const fields = [...new Set([...(eventFields[type] ?? []), ...(eventFields['*'] ?? [])])].sort();
248
+ const fieldUnion = fields.length ? fields.map((f) => JSON.stringify(f)).join(' | ') : 'never';
249
+ const data = spec?.data ?? `RemoteEventData<${fieldUnion}>`;
250
+ return `${JSON.stringify(type)}: { data: ${data}; fields: ${fieldUnion} }`;
251
+ };
252
+ const render = (node, segs, indent) => {
253
+ const path = pathOf(segs);
254
+ const pad = ' '.repeat(indent + 1);
255
+ const parts = [];
256
+ const spec = typeMap.get(path);
257
+ if (node.get) parts.push(`RemoteValue<${spec?.value ?? 'unknown'}>`);
258
+ const members = [...node.kids.keys()].sort();
259
+ const lines = [];
260
+ for (const key of members) {
261
+ const kid = node.kids.get(key);
262
+ lines.push(`${pad}readonly ${member(key)}: ${render(kid, [...segs, key], indent + 1)};`);
263
+ }
264
+ if (node.wild) lines.push(`${pad}readonly [key: string]: RemoteUntyped;`);
265
+ if (lines.length) parts.push(`{\n${lines.join('\n')}\n${' '.repeat(indent)}}`);
266
+ if (node.on.size) parts.push(`WithEvents<{ ${[...node.on].sort().map((t) => eventFor(t, path)).join('; ')} }>`);
267
+ if (node.setWild) parts.push('WithSet<Record<string, unknown>>');
268
+ else if (node.setKeys.size) parts.push(`WithSet<{ ${[...node.setKeys].sort().map((k) => `${member(k)}: ${typeMap.get(`${path}.${k}`)?.value ?? 'unknown'}`).join('; ')} }>`);
269
+ if (node.call) {
270
+ const callSpec = typeMap.get(path);
271
+ const args = callSpec?.args ?? 'unknown[]';
272
+ const result = callSpec?.result ?? 'unknown';
273
+ const resultNode = node.result;
274
+ const members2 = resultNode ? render(resultNode, [...segs.slice(0, -1), `${segs[segs.length - 1]}()`], indent) : 'unknown';
275
+ parts.push(`RemoteCall<${args}, ${result}, ${members2}>`);
276
+ }
277
+ return parts.length ? parts.join(' & ') : '{}';
278
+ };
279
+ const body = render(top, [root], 0);
280
+
281
+ return [
282
+ `// 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:`,
283
+ '// 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).',
284
+ '// 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.',
285
+ "import type { RemoteValue, RemoteCall, RemoteUntyped, RemoteHandle, NonValue, WithEvents, WithSet, RemoteEventData } from '@johnhenry/wsh/objects';",
286
+ '',
287
+ `export type ${typeName} = ${body};`,
288
+ '',
289
+ ].join('\n');
290
+ }
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
- /** A reference that stands on a handle: `await use(handle).items.length`. Judged by the producing path extended by what you name. */
33
- export function use(handle: RemoteHandle): any;
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
 
@@ -133,6 +181,14 @@ export interface ObjectsServerOptions {
133
181
  limits?: Partial<ObjectsLimits>;
134
182
  /** 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
183
  eventFields?: Record<string, string[]>;
184
+ /**
185
+ * 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
186
+ * 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
187
+ * an allow-list entry names), copied into a file there and never evaluated. A bad text or an unlisted path is a `TypeError` here.
188
+ */
189
+ types?: Record<string, { value?: string; args?: string; result?: string; data?: string }>;
190
+ /** An MCP face for named paths, off unless written: `{ tools: [{ name, description, call: 'window.app.cart.add', inputSchema }, { name, description, get: 'window.document.title' }] }`. */
191
+ mcp?: { tools: ObjectsMcpTool[] };
136
192
  /** Why nothing may be served any more (the window left), else null. */
137
193
  guard?: () => string | null;
138
194
  /** For `callTimeoutMs`. */
@@ -155,10 +211,49 @@ export interface ObjectsPeer {
155
211
  export function createObjectsServer(options: ObjectsServerOptions): {
156
212
  /** `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
213
  attach(peer: Pick<ObjectsPeer, 'onRequest' | 'maxMessageBytes'>, options?: { who?: ObjectsIdentity }): { limits: ObjectsLimits };
214
+ /**
215
+ * 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,
216
+ * 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 }`).
217
+ */
218
+ 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
219
  readonly limits: Readonly<ObjectsLimits>;
159
220
  readonly rootNames: string[];
221
+ /** The tools the host named in `mcp: { tools }` (none unless written), as definitions for `webmcpTools({ tools })`. */
222
+ readonly mcpTools: ObjectsMcpToolDefinition[];
223
+ readonly mcpToolNames: string[];
160
224
  };
161
225
 
226
+ /**
227
+ * 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`
228
+ * (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)
229
+ * 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.
230
+ */
231
+ export interface ObjectsMcpTool {
232
+ /** 1-128 characters of letters, digits, `_`, `-` and `.`. */
233
+ name: string;
234
+ title?: string;
235
+ /** What the far side reads to decide when to call it: written by the host. */
236
+ description: string;
237
+ /** A method path from a root, qualified (`'window.app.cart.add'`) in `exposeObjects`; relative to the root (`'app.cart.add'`) in `createPageHost({ expose })`. */
238
+ call?: string;
239
+ /** A value path, as for `call`. Read-only by default. */
240
+ get?: string;
241
+ inputSchema?: Record<string, unknown>;
242
+ /** 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. */
243
+ args?: 'object' | string[];
244
+ /** `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). */
245
+ readOnly?: boolean;
246
+ }
247
+ /** A tool as `webmcpTools({ tools })` takes it (what `exposeObjects` builds from an `ObjectsMcpTool`). */
248
+ export interface ObjectsMcpToolDefinition {
249
+ name: string;
250
+ title?: string;
251
+ description: string;
252
+ inputSchema: Record<string, unknown>;
253
+ annotations: { readOnlyHint: boolean };
254
+ execute(input: Record<string, any>, options?: { signal?: AbortSignal; who?: ObjectsIdentity; permits?: (request: { kind: string; [k: string]: unknown }) => boolean }): Promise<unknown>;
255
+ }
256
+
162
257
  /**
163
258
  * 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
259
  * 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 +277,9 @@ export interface ObjectsHandler {
182
277
  closeSessions(reason: string, fingerprint?: string): Promise<number>;
183
278
  readonly rootNames: string[];
184
279
  readonly limits: Readonly<ObjectsLimits>;
280
+ /** The MCP face (#219): the tools named in `mcp: { tools }`, for `webmcpTools({ window, tools: handler.mcpTools, allow: handler.mcpToolNames })`. Empty unless written. */
281
+ readonly mcpTools: ObjectsMcpToolDefinition[];
282
+ readonly mcpToolNames: string[];
185
283
  }
186
284
  export function exposeObjects(options: ObjectsServerOptions): ObjectsHandler;
187
285
 
@@ -201,7 +299,7 @@ declare module './index.js' {
201
299
  /** The value at a reference, or at a property of it: `await get(ref, 'then')` reaches a property that `ref.then` cannot. */
202
300
  export function get(ref: any, ...keys: Array<string | number>): Promise<any>;
203
301
  /** Assign a property of a remote object (not `=`: that throws). The reference must be a plain path. */
204
- export function set(ref: any, key: string | number, value: unknown): Promise<void>;
302
+ export function set<R, K extends SetKeyOf<R>>(ref: R, key: K, value: SetValueOf<R, K>): Promise<void>;
205
303
  /** Call a method reached by name, with plain-data arguments. */
206
304
  export function call(ref: any, ...args: unknown[]): Promise<any>;
207
305
  /** `new` a constructor reached by name. */
@@ -212,7 +310,17 @@ export function snapshot(ref: any, options?: { depth?: number; maxBytes?: number
212
310
  * 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
311
  * `{ 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
312
  */
215
- export function on(ref: any, type: string, listener: (data: any, info: { type: string; seq: number; dropped: number }) => void, options?: { fields?: string[]; onError?: (error: unknown) => void }): Promise<() => Promise<void>>;
313
+ /**
314
+ * `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
315
+ * 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.
316
+ * A host before 0.51.0 does not say it supports this (`unsupported`).
317
+ */
318
+ 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>>;
319
+ /**
320
+ * 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,
321
+ * 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`).
322
+ */
323
+ 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
324
  /** Stop a subscription: what `on` resolved to. */
217
325
  export function off(unsubscribe: () => Promise<void>): Promise<void>;
218
326
  /** 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
 
@@ -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
 
@@ -211,7 +211,7 @@ export interface WshPageHostOptions {
211
211
  * `'document.title'`, `'app.**'`; nothing allowed by default). A root named `window` is the window that was passed; another name needs `object`.
212
212
  * `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
213
  */
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[]> }>;
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[]>; /** 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
215
  /** `true` (default): the badge in `window.document`. Callbacks: for a context with no document, or your own UI. `false` needs `unattended: true`. */
216
216
  indicator?: boolean | WshPageIndicatorCallbacks;
217
217
  /** 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. */
package/src/page-host.mjs CHANGED
@@ -75,6 +75,8 @@ function exposedRoots(window, expose) {
75
75
  const authorizers = new Map();
76
76
  const eventFields = {};
77
77
  const handles = {};
78
+ const types = {};
79
+ const mcpTools = [];
78
80
  let limits;
79
81
  for (const name of names) {
80
82
  const cfg = expose[name];
@@ -97,12 +99,25 @@ function exposedRoots(window, expose) {
97
99
  allow[op].push(op === 'on' && entry.startsWith('@') ? `${name}${entry}` : `${name}.${entry}`);
98
100
  }
99
101
  }
102
+ // Type texts for the far side's `.d.ts`, with the same relative paths (`'app.cart.add'`, `'app.bus@ready'`, `'@hashchange'` for the root itself): host-authored text, checked by `exposeObjects`.
103
+ if (cfg.types !== undefined && !isObj(cfg.types)) throw new TypeError(`createPageHost: expose.${name}.types must be an object of paths`);
104
+ for (const [path, spec] of Object.entries(cfg.types ?? {})) types[path.startsWith('@') ? `${name}${path}` : `${name}.${path}`] = spec;
100
105
  for (const [type, fields] of Object.entries(cfg.eventFields ?? {})) eventFields[type] = [...new Set([...(eventFields[type] ?? []), ...(Array.isArray(fields) ? fields : [])])];
101
106
  if (cfg.authorize !== undefined) { if (typeof cfg.authorize !== 'function') throw new TypeError(`createPageHost: expose.${name}.authorize must be a function`); authorizers.set(name, cfg.authorize); }
102
107
  if (cfg.limits !== undefined) limits = { ...limits, ...cfg.limits };
108
+ // An MCP face for named paths of this root (#219): `mcp: { tools: [{ name, description, call: 'app.cart.add', inputSchema }, { name, description, get: 'document.title' }] }`, paths relative to the root.
109
+ // Off unless written; each tool names one path that the allow-lists above also name. It is served on the `mcp` channel beside the page's WebMCP tools.
110
+ if (cfg.mcp !== undefined) {
111
+ if (!isObj(cfg.mcp) || Object.keys(cfg.mcp).some((k) => k !== 'tools') || !Array.isArray(cfg.mcp.tools)) throw new TypeError(`createPageHost: expose.${name}.mcp must be { tools: [...] }: name each path that becomes a tool (nothing is a tool by being allowed)`);
112
+ for (const tool of cfg.mcp.tools) {
113
+ if (!isObj(tool)) throw new TypeError(`createPageHost: expose.${name}.mcp.tools entries must be objects`);
114
+ const qualify = (v) => (typeof v === 'string' ? `${name}.${v}` : v);
115
+ mcpTools.push({ ...tool, ...(tool.call !== undefined ? { call: qualify(tool.call) } : {}), ...(tool.get !== undefined ? { get: qualify(tool.get) } : {}) });
116
+ }
117
+ }
103
118
  }
104
119
  const authorize = authorizers.size ? (who, op) => (authorizers.has(op.root) ? authorizers.get(op.root)(who, { ...op, path: op.path }) : true) : undefined;
105
- return { roots, allow, authorize, limits, eventFields, handles };
120
+ return { roots, allow, authorize, limits, eventFields, handles, types, mcp: mcpTools.length ? { tools: mcpTools } : undefined };
106
121
  }
107
122
 
108
123
  /**
@@ -215,7 +230,7 @@ export async function createPageHost(options = {}) {
215
230
  if (!unattended) throw new TypeError('createPageHost: this window has no document to draw the indicator in: supply indicator callbacks, or say unattended: true');
216
231
  }
217
232
  if (!doc && !unattended && !callbacks) throw new TypeError('createPageHost: this window has no document: supply indicator callbacks, or say unattended: true');
218
- if (mcp && (mcp.approve ?? 'consequential') !== 'never' && !doc && !mcp.prompt && !unattended) {
233
+ if ((mcp || exposed?.mcp) && (mcp?.approve ?? 'consequential') !== 'never' && !doc && !mcp?.prompt && !unattended) {
219
234
  throw new TypeError("createPageHost: this window has no document to ask the person in: supply mcp.prompt, mcp.approve: 'never', or unattended: true");
220
235
  }
221
236
  if (typeof window.WebSocket !== 'function') throw new TypeError('createPageHost: window.WebSocket is needed to dial the relay');
@@ -258,18 +273,23 @@ export async function createPageHost(options = {}) {
258
273
  let watch = null;
259
274
  let unlisten = null;
260
275
 
261
- const mcpHandler = mcp ? webmcpTools({
262
- ...mcp, window, timers: options.timers, server: { name, ...(mcp.server ?? {}) },
263
- // Nobody is in front of an unattended window: without a prompt of the embedder's, what needs approval is denied.
264
- prompt: mcp.prompt ?? (unattended ? () => false : undefined),
265
- guard: () => gone() ?? mcp.guard?.() ?? null,
266
- }) : null;
267
276
  const objectsHandler = exposed ? exposeObjects({
268
- roots: exposed.roots, allow: exposed.allow, authorize: exposed.authorize, limits: exposed.limits, eventFields: exposed.eventFields, handles: exposed.handles, timers,
277
+ roots: exposed.roots, allow: exposed.allow, authorize: exposed.authorize, limits: exposed.limits, eventFields: exposed.eventFields, handles: exposed.handles, types: exposed.types, mcp: exposed.mcp, timers,
269
278
  // Handle ids come from the served window's own CSPRNG.
270
279
  random: (n) => window.crypto.getRandomValues(new Uint8Array(n)),
271
280
  guard: () => gone(),
272
281
  }) : null;
282
+ // The tools of the `mcp` channel: the page's WebMCP tools (`mcp.allow`) and the paths the host named as tools (`expose.ROOT.mcp.tools`). One handler, so one approval, one set of
283
+ // bounds, one label; a tool made from a path is allowed by being named in `expose`, and still needs the key's `mcp:TOOL` and `objects:ROOT:OP` capabilities.
284
+ const objectTools = objectsHandler?.mcpTools ?? [];
285
+ const mcpHandler = mcp || objectTools.length ? webmcpTools({
286
+ ...(mcp ?? {}), window, timers: options.timers, server: { name, ...(mcp?.server ?? {}) },
287
+ allow: [...(mcp?.allow ?? []), ...(objectsHandler?.mcpToolNames ?? [])],
288
+ tools: [...(mcp?.tools ?? []), ...objectTools],
289
+ // Nobody is in front of an unattended window: without a prompt of the embedder's, what needs approval is denied.
290
+ prompt: mcp?.prompt ?? (unattended ? () => false : undefined),
291
+ guard: () => gone() ?? mcp?.guard?.() ?? null,
292
+ }) : null;
273
293
  /** What each handler tells and ends: the sessions of a key, or all of them. */
274
294
  const closeSessions = async (reason, fingerprint) => {
275
295
  const counts = await Promise.all([mcpHandler, objectsHandler].filter(Boolean).map((h) => h.closeSessions(reason, fingerprint).catch(() => 0)));