@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
package/src/objects-core.mjs
CHANGED
|
@@ -25,6 +25,8 @@
|
|
|
25
25
|
*/
|
|
26
26
|
|
|
27
27
|
import { callerIdentity } from './key-names.mjs';
|
|
28
|
+
import { describeRootTypes, narrowTypes } from './objects-types.mjs';
|
|
29
|
+
import { buildMcpTools } from './objects-mcp.mjs';
|
|
28
30
|
|
|
29
31
|
export const OBJECTS_PROTOCOL = 'wsh-objects';
|
|
30
32
|
|
|
@@ -72,6 +74,15 @@ export const OBJECTS_DEFAULT_LIMITS = Object.freeze({
|
|
|
72
74
|
maxCallbacksPerSecond: 20,
|
|
73
75
|
/** Bytes of the arguments of one callback call; a bigger one is dropped and counted. */
|
|
74
76
|
maxCallbackBytes: 16 * 1024,
|
|
77
|
+
/**
|
|
78
|
+
* Callbacks whose entry says `(callback:returns)`: the longest the page's stub waits for the far side's answer, from the call (queueing included). After it the
|
|
79
|
+
* promise the stub returned is settled with `undefined`. At most 30000.
|
|
80
|
+
*/
|
|
81
|
+
callbackReturnTimeoutMs: 2000,
|
|
82
|
+
/** Calls of returning callbacks waiting for an answer, per channel; a call beyond it is dropped and counted, never sent. At most 64. */
|
|
83
|
+
maxPendingCallbackReturns: 8,
|
|
84
|
+
/** Bytes of the value a far-side callback answers with; a bigger one (or one that is not plain data) becomes `undefined` for the page and is counted. */
|
|
85
|
+
maxCallbackResultBytes: 16 * 1024,
|
|
75
86
|
/** Event subscriptions per channel. */
|
|
76
87
|
maxSubscriptions: 16,
|
|
77
88
|
/** Events delivered per second, per subscription; the rest are dropped and counted. */
|
|
@@ -102,6 +113,10 @@ export const NEEDS_LISTING = Object.freeze([
|
|
|
102
113
|
|
|
103
114
|
const KEY_MAX = 256;
|
|
104
115
|
const CALLBACK_SUFFIX = '(callback)';
|
|
116
|
+
/** The ceilings of the bounds a host may set for callbacks that return a value: the page's wait is bounded whatever the host asks for. */
|
|
117
|
+
const RETURN_CEILINGS = Object.freeze({ callbackReturnTimeoutMs: 30_000, maxPendingCallbackReturns: 64 });
|
|
118
|
+
/** The end of a call entry that accepts callbacks: `(callback)` one-way, `(callback:returns)` every function may answer, `(callback:returns=0,2)` the functions at those argument positions may. */
|
|
119
|
+
const CALLBACK_NOTATION = /\(callback(?::returns(?:=(\d{1,2}(?:,\d{1,2})*))?)?\)$/;
|
|
105
120
|
const B64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
106
121
|
/** On a root with handles: members that lead from a node back up to the document or window graph. Refused until an allow-list entry names them, nodes opt-in or not. */
|
|
107
122
|
const GRAPH_MEMBERS = Object.freeze(['ownerDocument', 'defaultView', 'parentNode', 'parentElement', 'getRootNode', 'contentWindow', 'contentDocument', 'self', 'window', 'top', 'parent', 'frames', 'opener', 'globalThis']);
|
|
@@ -123,15 +138,19 @@ function compileList(list, kind) {
|
|
|
123
138
|
return list.map((original) => {
|
|
124
139
|
if (typeof original !== 'string' || original === '') throw new TypeError(`exposeObjects: allow.${kind} entries must be non-empty strings`);
|
|
125
140
|
// A call entry that ends in `(callback)` says the call accepts functions as arguments (they arrive as stubs the page can call, one-way).
|
|
141
|
+
// `(callback:returns)` (every function it takes may answer) and `(callback:returns=0,2)` (the functions at those argument positions) also let the stub return the far side's value.
|
|
126
142
|
let entry = original;
|
|
127
143
|
let callbacks = false;
|
|
128
|
-
|
|
144
|
+
let returns = null;
|
|
145
|
+
const notation = CALLBACK_NOTATION.exec(entry);
|
|
146
|
+
if (notation) {
|
|
129
147
|
if (kind !== 'call') throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(original)}: only a call entry can accept callbacks`);
|
|
130
|
-
entry = entry.slice(0,
|
|
148
|
+
entry = entry.slice(0, notation.index);
|
|
131
149
|
callbacks = true;
|
|
150
|
+
if (notation[0] !== CALLBACK_SUFFIX) returns = notation[1] === undefined ? true : new Set(notation[1].split(',').map(Number));
|
|
132
151
|
}
|
|
133
|
-
if (entry.includes(
|
|
134
|
-
const segs = Object.assign(entry.split('.'), { callbacks });
|
|
152
|
+
if (entry.includes('(callback')) throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(original)}: "(callback)", "(callback:returns)" or "(callback:returns=N,M)" ends an entry`);
|
|
153
|
+
const segs = Object.assign(entry.split('.'), { callbacks, returns });
|
|
135
154
|
for (const s of segs) {
|
|
136
155
|
if (s === '') throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(entry)} has an empty segment`);
|
|
137
156
|
if (ALWAYS_REFUSED.has(s)) throw new TypeError(`exposeObjects: allow.${kind} entry ${JSON.stringify(entry)} names "${s}", which is never reachable`);
|
|
@@ -368,7 +387,7 @@ function isPromiseLike(v) {
|
|
|
368
387
|
* @param {() => number} [options.now]
|
|
369
388
|
*/
|
|
370
389
|
export function createObjectsServer(options = {}) {
|
|
371
|
-
const { roots, mode = 'values', allow = {}, authorize, limits: limitOptions = {}, guard, timers = null, eventFields = {}, handles = {}, random = null, now = () => Date.now() } = options;
|
|
390
|
+
const { roots, mode = 'values', allow = {}, authorize, limits: limitOptions = {}, guard, timers = null, eventFields = {}, handles = {}, random = null, types = {}, mcp, now = () => Date.now() } = options;
|
|
372
391
|
if (mode === 'handles') throw new TypeError("exposeObjects: handles are chosen per root, not for the host: use handles: { window: {} } (and nodes: true on a root that may hand out nodes)");
|
|
373
392
|
if (mode !== 'values') throw new TypeError("exposeObjects: mode must be 'values' (handles are chosen per root with handles: { ROOT: {} })");
|
|
374
393
|
if (typeof allow === 'string') throw new TypeError('exposeObjects: allow must be { get, call, set, on }: a wide-open string is not accepted, and the allow-lists apply to handles too');
|
|
@@ -403,6 +422,7 @@ export function createObjectsServer(options = {}) {
|
|
|
403
422
|
for (const [k, v] of Object.entries(limitOptions)) {
|
|
404
423
|
if (!(k in OBJECTS_DEFAULT_LIMITS)) throw new TypeError(`exposeObjects: unknown limit ${JSON.stringify(k)} (${Object.keys(OBJECTS_DEFAULT_LIMITS).join(', ')})`);
|
|
405
424
|
if (!Number.isSafeInteger(v) || v < 1) throw new TypeError(`exposeObjects: limits.${k} must be a positive integer`);
|
|
425
|
+
if (k in RETURN_CEILINGS && v > RETURN_CEILINGS[k]) throw new TypeError(`exposeObjects: limits.${k} is at most ${RETURN_CEILINGS[k]}: the page's wait for a callback's answer is bounded whatever the host asks for`);
|
|
406
426
|
limits[k] = v;
|
|
407
427
|
}
|
|
408
428
|
// `on` entries are `path@type` (`'window.app.bus@ready'`): the source and the event type, both named exactly (no wildcard in either); each is compiled as a path with its type attached.
|
|
@@ -422,6 +442,9 @@ export function createObjectsServer(options = {}) {
|
|
|
422
442
|
};
|
|
423
443
|
const lists = { get: compileList(allow.get, 'get'), call: compileList(allow.call, 'call'), set: compileList(allow.set, 'set'), on: compileOn(allow.on) };
|
|
424
444
|
const every = [...lists.get, ...lists.call, ...lists.set, ...lists.on];
|
|
445
|
+
// A callback that returns a value makes the page wait for the far side, so it needs a clock to cut the wait: this module reaches for no global.
|
|
446
|
+
const anyReturns = lists.call.some((p) => p.returns);
|
|
447
|
+
if (anyReturns && !timers) throw new TypeError('exposeObjects: an entry that says (callback:returns) needs timers ({ setTimeout, clearTimeout }): the page\'s wait for the far side\'s answer is bounded by a timer');
|
|
425
448
|
// With handles, a wildcard in `call` or `set` lets a caller hold and reuse every object under it: the root says so (`wideEntries: true`) or lists the paths.
|
|
426
449
|
for (const [name, mode] of handleRoots) {
|
|
427
450
|
if (mode.wideEntries) continue;
|
|
@@ -431,6 +454,21 @@ export function createObjectsServer(options = {}) {
|
|
|
431
454
|
}
|
|
432
455
|
}
|
|
433
456
|
|
|
457
|
+
// Types for the far side's `.d.ts` (`types: { 'window.app.cart.add': { args: '[item: { sku: string }]', result: 'number' } }`): host-authored text that is sent to the far side.
|
|
458
|
+
// It is checked when the host is created (a conservative type syntax, bounded, and only for a path that an allow-list entry names), so a bad text is a TypeError here, not something the far side finds.
|
|
459
|
+
if (!types || typeof types !== 'object' || Array.isArray(types)) throw new TypeError('exposeObjects: types must be { [path]: { value?, args?, result?, data? } }');
|
|
460
|
+
const typesByRoot = new Map();
|
|
461
|
+
for (const [key, spec] of Object.entries(types)) {
|
|
462
|
+
const root = key.split(/[.@]/, 1)[0];
|
|
463
|
+
if (!rootNames.includes(root)) throw new TypeError(`exposeObjects: types names ${JSON.stringify(key.slice(0, 60))}, which is not under a root`);
|
|
464
|
+
if (!typesByRoot.has(root)) typesByRoot.set(root, {});
|
|
465
|
+
typesByRoot.get(root)[key] = spec;
|
|
466
|
+
}
|
|
467
|
+
const allowStrings = { get: allow.get ?? [], call: allow.call ?? [], set: allow.set ?? [], on: allow.on ?? [] };
|
|
468
|
+
for (const [root, map] of typesByRoot) {
|
|
469
|
+
try { describeRootTypes({ root, allow: allowStrings, eventFields, types: map }); } catch (e) { throw new TypeError(String(e?.message ?? e).replace(/^describeRootTypes:/, 'exposeObjects:')); }
|
|
470
|
+
}
|
|
471
|
+
|
|
434
472
|
/** The checks every operation passes, in order. `terminal` ones need the operation's own list; the rest need only to walk toward something allowed. */
|
|
435
473
|
async function check(kind, root, segs, ctx, { terminal, type, callbacks = 0 }) {
|
|
436
474
|
const who = ctx.who;
|
|
@@ -438,6 +476,19 @@ export function createObjectsServer(options = {}) {
|
|
|
438
476
|
if (gone) throw refuse('gone', `refused: ${gone}`);
|
|
439
477
|
// 0. what the caller's key may do on this root, if the transport says (`ctx.permit(root, op)`, asked afresh: an expiry holds at call time)
|
|
440
478
|
permitted(ctx, root, kind === 'get' && !terminal ? 'walk' : kind === 'construct' ? 'call' : kind === 'describe' || kind === 'snapshot' ? 'get' : kind);
|
|
479
|
+
staticCheck(kind, root, segs, { terminal, type, callbacks });
|
|
480
|
+
if (terminal && authorize) {
|
|
481
|
+
let ok = false;
|
|
482
|
+
try { ok = (await authorize(who ?? {}, { kind, root, path: segs.slice(1), text: segs.join('.'), ...(type !== undefined ? { type } : {}), ...(callbacks ? { callbacks } : {}) })) === true; } catch { ok = false; }
|
|
483
|
+
if (!ok) throw refuse('authorize', `refused: ${kind} of ${segs.join('.')} was not authorized`, { path: segs.join('.'), op: kind });
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* The part of `check` that needs nothing of the caller: the allow-lists and the names that need listing. It is what makes an MCP tool for a path possible when the host is
|
|
489
|
+
* configured (the path must pass it for its operation), and it is the same code every call passes.
|
|
490
|
+
*/
|
|
491
|
+
function staticCheck(kind, root, segs, { terminal, type, callbacks = 0 }) {
|
|
441
492
|
const rel = segs.slice(1).map(bareName);
|
|
442
493
|
const own = lists[kind === 'construct' ? 'call' : kind === 'describe' || kind === 'snapshot' ? 'get' : kind];
|
|
443
494
|
// 1. the allow-list: the operation's own list for the operation itself, any list for walking toward something
|
|
@@ -455,11 +506,6 @@ export function createObjectsServer(options = {}) {
|
|
|
455
506
|
const listed = terminal ? own.some((p) => matchPath(p, segs) && patternNames(p, seq)) : every.some((p) => prefixPath(p, segs) && patternNames(p, seq));
|
|
456
507
|
if (!listed) throw refuse('needs-listing', `refused: "${rel.join('.')}" is refused until an allow-list entry names ${seq.join('.')} (a wildcard does not)`, { path: segs.join('.') });
|
|
457
508
|
}
|
|
458
|
-
if (terminal && authorize) {
|
|
459
|
-
let ok = false;
|
|
460
|
-
try { ok = (await authorize(who ?? {}, { kind, root, path: segs.slice(1), text: segs.join('.'), ...(type !== undefined ? { type } : {}), ...(callbacks ? { callbacks } : {}) })) === true; } catch { ok = false; }
|
|
461
|
-
if (!ok) throw refuse('authorize', `refused: ${kind} of ${segs.join('.')} was not authorized`, { path: segs.join('.'), op: kind });
|
|
462
|
-
}
|
|
463
509
|
}
|
|
464
510
|
|
|
465
511
|
/** What the transport says the caller's key may do (`ctx.permit(root, op)`): anything but `true`, and a throw, is no. No `permit`: the transport does not limit. */
|
|
@@ -539,7 +585,7 @@ export function createObjectsServer(options = {}) {
|
|
|
539
585
|
const clean = fromWire(args, limits);
|
|
540
586
|
const made = [];
|
|
541
587
|
try {
|
|
542
|
-
for (const [index, id] of spec) { const had = ctx.session.callbacks.has(id); const stub = makeCallback(ctx.session, id); if (!had) made.push(id); clean[index] = stub; }
|
|
588
|
+
for (const [index, id] of spec) { const had = ctx.session.callbacks.has(id); const stub = makeCallback(ctx.session, id, returnsAt(next, index)); if (!had) made.push(id); clean[index] = stub; }
|
|
543
589
|
} catch (e) { for (const id of made) killCallback(ctx.session, id); throw e; }
|
|
544
590
|
if (kind === 'call' && isTimerCallee(key) && typeof clean[0] === 'string') throw refuse('always-refused', `refused: ${key} with a string would evaluate it`);
|
|
545
591
|
let fn;
|
|
@@ -613,6 +659,13 @@ export function createObjectsServer(options = {}) {
|
|
|
613
659
|
async function releaseHandle(params, ctx) {
|
|
614
660
|
const { session } = ctx;
|
|
615
661
|
if (typeof params.handle !== 'string' || !session.handles.delete(params.handle)) throw invalid('no such handle (it was released, belongs to another session, or never existed)');
|
|
662
|
+
// The event subscriptions made through the handle end with it: the listeners leave the page's sources, and what they had queued is dropped.
|
|
663
|
+
for (const [id, sub] of [...session.subs]) {
|
|
664
|
+
if (sub.handle !== params.handle) continue;
|
|
665
|
+
session.subs.delete(id);
|
|
666
|
+
removeSub(sub);
|
|
667
|
+
session.queue = session.queue.filter((q) => q.sub !== sub);
|
|
668
|
+
}
|
|
616
669
|
return { ok: true };
|
|
617
670
|
}
|
|
618
671
|
|
|
@@ -746,10 +799,10 @@ export function createObjectsServer(options = {}) {
|
|
|
746
799
|
session.pumping = true;
|
|
747
800
|
try {
|
|
748
801
|
while (session.queue.length && !session.closed) {
|
|
749
|
-
const { sub, cb, data, dropped } = session.queue.shift();
|
|
750
|
-
const message = cb ? { id: cb.id, seq: ++cb.seq, args: data, ...(dropped ? { dropped } : {}) } : { id: sub.id, seq: ++sub.seq, data, ...(dropped ? { dropped } : {}) };
|
|
802
|
+
const { sub, cb, data, dropped, rid } = session.queue.shift();
|
|
803
|
+
const message = cb ? { id: cb.id, seq: ++cb.seq, args: data, ...(dropped ? { dropped } : {}), ...(rid ? { rid } : {}) } : { id: sub.id, seq: ++sub.seq, data, ...(dropped ? { dropped } : {}) };
|
|
751
804
|
// The write waits for the transport (credit): events and callback calls behind it queue, to `maxQueuedEvents`, and beyond that are dropped and counted.
|
|
752
|
-
try { await session.peer.notify(cb ? 'callback' : 'event', message); } catch { /* the channel is going away */ }
|
|
805
|
+
try { await session.peer.notify(cb ? 'callback' : 'event', message); } catch { if (rid) finishReturn(session, rid, undefined, 'failed'); /* the channel is going away */ }
|
|
753
806
|
}
|
|
754
807
|
} finally { session.pumping = false; }
|
|
755
808
|
}
|
|
@@ -759,14 +812,35 @@ export function createObjectsServer(options = {}) {
|
|
|
759
812
|
// values (what cannot be cloned is null; never a handle), bounds them, queues a notification through the channel's credit, and returns undefined at once, so
|
|
760
813
|
// the page cannot be made to wait for the far side and learns nothing of it. After the channel ends, or after a release, a call is a no-op that is counted.
|
|
761
814
|
|
|
762
|
-
|
|
763
|
-
|
|
815
|
+
//
|
|
816
|
+
// `(callback:returns)` (or `=N,M`, per argument position) is the one exception, and only where the host wrote it: the stub then returns a PROMISE, never a block. It is
|
|
817
|
+
// settled with the far side's return value if that arrives within `callbackReturnTimeoutMs` (counted from the call; 2 s, at most 30 s), as plain data within
|
|
818
|
+
// `maxCallbackResultBytes`, and with `undefined` in every other case: a timeout, an error on the far side (its text stays there), a result that is too big or is not plain
|
|
819
|
+
// data, a full table (`maxPendingCallbackReturns`), a call dropped by the rate or size bound, a dead channel, a released callback, and a far side that did not say it can
|
|
820
|
+
// answer (an older client): the page never waits on a peer that cannot answer. The answer comes as a `callbackResult` request for a request id the host gave, once.
|
|
821
|
+
|
|
822
|
+
/** Does an entry that matches `segs` let the function at argument `index` answer? (Any matching entry that says so: the allow-list is a union, as everywhere.) */
|
|
823
|
+
function returnsAt(segs, index) {
|
|
824
|
+
return lists.call.some((p) => p.callbacks && p.returns && matchPath(p, segs) && (p.returns === true || p.returns.has(index)));
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
function makeCallback(session, id, returns = false) {
|
|
828
|
+
// The same function sent again (an id the channel already has) is the same stub. A returning stub that is also sent to an entry that says only (callback) stops returning.
|
|
764
829
|
const existing = session.callbacks.get(id);
|
|
765
|
-
if (existing) return existing.stub;
|
|
830
|
+
if (existing) { if (!returns) existing.returns = false; return existing.stub; }
|
|
766
831
|
if (session.callbacks.size >= limits.maxCallbacks) throw limitError('maxCallbacks', limits.maxCallbacks, 'too many callbacks on this channel: release some');
|
|
767
|
-
const cb = { id, seq: 0, stamps: [], dropped: 0, dead: false, stub: null };
|
|
832
|
+
const cb = { id, seq: 0, stamps: [], dropped: 0, dead: false, stub: null, returns };
|
|
768
833
|
cb.stub = function callback(...args) {
|
|
769
|
-
|
|
834
|
+
if (!cb.returns) {
|
|
835
|
+
try { deliverCallback(session, cb, args, null); } catch { cb.dropped++; }
|
|
836
|
+
return undefined;
|
|
837
|
+
}
|
|
838
|
+
// Always a promise, settled at the latest `callbackReturnTimeoutMs` after this call, whatever the far side does.
|
|
839
|
+
return new Promise((resolve) => {
|
|
840
|
+
let waiting = false;
|
|
841
|
+
try { waiting = deliverCallback(session, cb, args, resolve); } catch { cb.dropped++; session.returnStats.dropped++; }
|
|
842
|
+
if (!waiting) resolve(undefined);
|
|
843
|
+
});
|
|
770
844
|
};
|
|
771
845
|
session.callbacks.set(id, cb);
|
|
772
846
|
return cb.stub;
|
|
@@ -774,25 +848,57 @@ export function createObjectsServer(options = {}) {
|
|
|
774
848
|
|
|
775
849
|
function killCallback(session, id) {
|
|
776
850
|
const cb = session.callbacks.get(id);
|
|
777
|
-
if (cb) {
|
|
851
|
+
if (cb) {
|
|
852
|
+
cb.dead = true;
|
|
853
|
+
session.callbacks.delete(id);
|
|
854
|
+
for (const [rid, p] of [...session.pendingReturns]) if (p.cb === cb) finishReturn(session, rid, undefined, 'failed');
|
|
855
|
+
}
|
|
778
856
|
return !!cb;
|
|
779
857
|
}
|
|
780
858
|
|
|
781
|
-
|
|
782
|
-
|
|
859
|
+
/** Settle one waiting call (once) with `value`, and take its timer away. `outcome` is the counter it adds to. Returns whether anything was waiting. */
|
|
860
|
+
function finishReturn(session, rid, value, outcome) {
|
|
861
|
+
const p = session.pendingReturns.get(rid);
|
|
862
|
+
if (!p) return false;
|
|
863
|
+
session.pendingReturns.delete(rid);
|
|
864
|
+
if (p.timer !== null) timers?.clearTimeout(p.timer);
|
|
865
|
+
session.returnStats[outcome]++;
|
|
866
|
+
p.resolve(value);
|
|
867
|
+
return true;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
/** The channel ended: nobody can answer any more. */
|
|
871
|
+
function finishAllReturns(session) {
|
|
872
|
+
for (const rid of [...session.pendingReturns.keys()]) finishReturn(session, rid, undefined, 'failed');
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
/** Returns whether a call is now waiting for an answer (then `resolve` is called later, by `finishReturn`); else the caller resolves `undefined` at once. */
|
|
876
|
+
function deliverCallback(session, cb, args, resolve) {
|
|
877
|
+
if (session.closed || cb.dead || guard?.()) { session.deadCalls++; return false; }
|
|
783
878
|
const t = now();
|
|
784
879
|
while (cb.stamps.length && t - cb.stamps[0] >= 1000) cb.stamps.shift();
|
|
880
|
+
const dropOne = () => { cb.dropped++; if (resolve) session.returnStats.dropped++; return false; };
|
|
785
881
|
// Rate and room first, copy after: a dropped call costs a counter.
|
|
786
|
-
if (cb.stamps.length >= limits.maxCallbacksPerSecond || session.queue.length >= limits.maxQueuedEvents)
|
|
882
|
+
if (cb.stamps.length >= limits.maxCallbacksPerSecond || session.queue.length >= limits.maxQueuedEvents) return dropOne();
|
|
883
|
+
// A call that would have to wait but has no room to: dropped, not sent (a far side cannot make the table grow).
|
|
884
|
+
const answerable = resolve !== null && session.clientReturns;
|
|
885
|
+
if (answerable && session.pendingReturns.size >= limits.maxPendingCallbackReturns) return dropOne();
|
|
787
886
|
let copy;
|
|
788
887
|
try {
|
|
789
888
|
copy = args.slice(0, limits.maxArgs).map((a) => { const w = toWire(a, { maxDepth: 4, maxBytes: limits.maxCallbackBytes }); return 'v' in w ? w.v : null; });
|
|
790
889
|
toWire(copy, { maxDepth: 6, maxBytes: limits.maxCallbackBytes });
|
|
791
|
-
} catch {
|
|
890
|
+
} catch { return dropOne(); }
|
|
792
891
|
cb.stamps.push(t);
|
|
793
|
-
|
|
892
|
+
let rid;
|
|
893
|
+
if (answerable) {
|
|
894
|
+
rid = session.nextRid++;
|
|
895
|
+
const timer = timers.setTimeout(() => { finishReturn(session, rid, undefined, 'timedOut'); }, limits.callbackReturnTimeoutMs);
|
|
896
|
+
session.pendingReturns.set(rid, { cb, resolve, timer });
|
|
897
|
+
}
|
|
898
|
+
session.queue.push({ cb, data: copy, dropped: cb.dropped, ...(rid ? { rid } : {}) });
|
|
794
899
|
cb.dropped = 0;
|
|
795
900
|
void pump(session);
|
|
901
|
+
return rid !== undefined;
|
|
796
902
|
}
|
|
797
903
|
|
|
798
904
|
async function releaseCallback(params, ctx) {
|
|
@@ -826,7 +932,12 @@ export function createObjectsServer(options = {}) {
|
|
|
826
932
|
|
|
827
933
|
async function subscribe(params, ctx) {
|
|
828
934
|
const { session } = ctx;
|
|
829
|
-
|
|
935
|
+
// Where the source is looked for starts at a root, or at a handle of THIS channel: a handle stands at the path that produced it, and what is subscribed to is that
|
|
936
|
+
// path extended by `params.path`, judged exactly as a path subscription for it (its own `allow.on` entry naming the type, the key's `on`, `authorize`).
|
|
937
|
+
const start = startOf(params, ctx);
|
|
938
|
+
const { root } = start;
|
|
939
|
+
const handleId = params.handle;
|
|
940
|
+
const handleRec = handleId === undefined ? null : session.handles.get(handleId);
|
|
830
941
|
const type = params.type;
|
|
831
942
|
if (typeof type !== 'string' || !EVENT_TYPE_RE.test(type)) throw invalid('an event type is a name of letters, digits and _ $ : . - (up to 128)');
|
|
832
943
|
const id = params.id;
|
|
@@ -836,11 +947,16 @@ export function createObjectsServer(options = {}) {
|
|
|
836
947
|
const offered = [...(eventFields[type] ?? []), ...(eventFields['*'] ?? [])];
|
|
837
948
|
for (const f of asked) if (!offered.includes(f)) throw refuse('not-allowed', `refused: the field "${f}" of ${type} events is not offered by this host`, { field: f, type });
|
|
838
949
|
if (session.subs.size >= limits.maxSubscriptions) throw limitError('maxSubscriptions', limits.maxSubscriptions, 'too many event subscriptions on this channel');
|
|
839
|
-
const { cur: source, segs } = await walk(
|
|
950
|
+
const { cur: source, segs } = await walk(start, params.path ?? [], ctx);
|
|
840
951
|
await check('on', root, segs, ctx, { terminal: true, type });
|
|
952
|
+
// The checks above may have waited (`authorize`): the handle may have been released, the channel may have ended, another subscribe may have taken the last place.
|
|
953
|
+
if (session.closed) throw refuse('gone', 'refused: the channel ended');
|
|
954
|
+
if (handleRec &&session.handles.get(handleId) !== handleRec) throw invalid('no such handle (it was released, belongs to another session, or never existed)');
|
|
955
|
+
if (session.subs.has(id)) throw invalid('a subscription id is a whole number the channel has not used');
|
|
956
|
+
if (session.subs.size >= limits.maxSubscriptions) throw limitError('maxSubscriptions', limits.maxSubscriptions, 'too many event subscriptions on this channel');
|
|
841
957
|
const kind = sourceMethods(source);
|
|
842
958
|
if (!kind) throw new ObjectsError(OBJECTS_ERROR.FAILED, `${segs.join('.')} is not an event source (it needs addEventListener, or on and off)`, { reason: 'not-an-event-source' });
|
|
843
|
-
const sub = { id, type, kind: kind.kind, fields: [...new Set(asked)], source, stamps: [], dropped: 0, seq: 0, remove: kind.remove, listener: null };
|
|
959
|
+
const sub = { id, type, kind: kind.kind, fields: [...new Set(asked)], source, stamps: [], dropped: 0, seq: 0, remove: kind.remove, listener: null, handle: handleRec ? handleId : undefined };
|
|
844
960
|
sub.listener = (...args) => deliver(session, sub, args);
|
|
845
961
|
try { Reflect.apply(Reflect.get(Object(source), kind.add, source), source, [type, sub.listener]); } catch (e) { throw wrapThrown(e, `${segs.join('.')}.${kind.add}`); }
|
|
846
962
|
session.subs.set(id, sub);
|
|
@@ -868,7 +984,11 @@ export function createObjectsServer(options = {}) {
|
|
|
868
984
|
function attach(peer, { who } = {}) {
|
|
869
985
|
if (typeof peer?.onRequest !== 'function') throw new TypeError('attach: the peer needs onRequest(method, handler)');
|
|
870
986
|
const defaultWho = callerIdentity(who);
|
|
871
|
-
const session = {
|
|
987
|
+
const session = {
|
|
988
|
+
peer, subs: new Map(), queue: [], pumping: false, closed: false, handles: new Map(), callbacks: new Map(), deadCalls: 0,
|
|
989
|
+
// Callbacks that return a value: the calls waiting for an answer by request id, whether the far side said it answers, and what became of the calls.
|
|
990
|
+
pendingReturns: new Map(), nextRid: 1, clientReturns: false, returnStats: { answered: 0, timedOut: 0, failed: 0, refused: 0, dropped: 0 },
|
|
991
|
+
};
|
|
872
992
|
// The end of the channel (the peer left, Stop, a navigation, a revoke) takes every listener out of the page's sources.
|
|
873
993
|
const prior = peer.onClose;
|
|
874
994
|
peer.onClose = (reason) => {
|
|
@@ -879,14 +999,29 @@ export function createObjectsServer(options = {}) {
|
|
|
879
999
|
session.handles.clear(); // the end of the channel (leaving, Stop, navigation, revoke) releases every handle
|
|
880
1000
|
for (const cb of session.callbacks.values()) cb.dead = true; // and kills every callback stub
|
|
881
1001
|
session.callbacks.clear();
|
|
1002
|
+
finishAllReturns(session); // a page that is waiting for a far side that has gone is told `undefined` now, and its timers go
|
|
882
1003
|
try { prior?.(reason); } catch { /* ignore */ }
|
|
883
1004
|
};
|
|
884
1005
|
const stamps = [];
|
|
885
|
-
const
|
|
1006
|
+
const spendRequest = () => {
|
|
886
1007
|
const t = now();
|
|
887
1008
|
while (stamps.length && t - stamps[0] >= 1000) stamps.shift();
|
|
888
1009
|
if (stamps.length >= limits.maxRequestsPerSecond) throw limitError('maxRequestsPerSecond', limits.maxRequestsPerSecond, 'too many requests in a second');
|
|
889
1010
|
stamps.push(t);
|
|
1011
|
+
};
|
|
1012
|
+
// The far side's answer to a callback that returns a value. It completes a call the host is already waiting on (by a request id this channel gave, once), so it
|
|
1013
|
+
// takes nothing from the request rate; an answer nobody waits for does, and is the only way to spend it with no effect.
|
|
1014
|
+
peer.onRequest('callbackResult', async (params) => {
|
|
1015
|
+
if (params === null || typeof params !== 'object' || Array.isArray(params) || !Number.isSafeInteger(params.rid) || params.rid < 1) throw invalid('callbackResult needs { rid }');
|
|
1016
|
+
if (!session.pendingReturns.has(params.rid)) { spendRequest(); return { ok: false }; }
|
|
1017
|
+
if (params.error === true) { finishReturn(session, params.rid, undefined, 'failed'); return { ok: true }; }
|
|
1018
|
+
let value;
|
|
1019
|
+
try { value = params.value === undefined ? undefined : fromWire(params.value, { maxDepth: 4, maxBytes: limits.maxCallbackResultBytes }); } catch { finishReturn(session, params.rid, undefined, 'refused'); return { ok: true }; }
|
|
1020
|
+
finishReturn(session, params.rid, value, 'answered');
|
|
1021
|
+
return { ok: true };
|
|
1022
|
+
});
|
|
1023
|
+
const method = (name, fn) => peer.onRequest(name, async (params, ctx = {}) => {
|
|
1024
|
+
spendRequest();
|
|
890
1025
|
// A value is kept under what the transport carries in one message, with room for the envelope.
|
|
891
1026
|
const maxBytes = Math.min(limits.maxValueBytes, Math.max(1024, (peer.maxMessageBytes ?? Infinity) - 4096));
|
|
892
1027
|
const call = { ...ctx, signal: ctx.signal, who: ctx.who === undefined || ctx.who === null ? defaultWho : callerIdentity(ctx.who), maxBytes, session };
|
|
@@ -895,10 +1030,32 @@ export function createObjectsServer(options = {}) {
|
|
|
895
1030
|
});
|
|
896
1031
|
// A key that may use only some roots is told of those only.
|
|
897
1032
|
// The host also says what it supports (additive: an older client ignores it), so a client does not send a function to a host that would drop it, nor misread a handle.
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
1033
|
+
// A client that answers a callback says so here (`features: ['callback-returns']`): an older one does not, and a returning stub then never waits for it.
|
|
1034
|
+
method('roots', async (params, call) => {
|
|
1035
|
+
session.clientReturns = anyReturns && Array.isArray(params.features) && params.features.includes('callback-returns');
|
|
1036
|
+
return {
|
|
1037
|
+
roots: rootNames.filter((name) => keyMay(call, name, 'walk')),
|
|
1038
|
+
features: ['events', 'callbacks', ...(anyReturns ? ['callback-returns'] : []), 'types', ...(handleRoots.size ? ['handles', 'handle-events'] : [])],
|
|
1039
|
+
};
|
|
1040
|
+
});
|
|
1041
|
+
// What this key may do on one root, as data a far side turns into a `.d.ts` (`describeRootTypes`): the allow-list entries of that root for the operations the key's
|
|
1042
|
+
// capabilities grant, the host's type map for them, the event fields of the types it may subscribe to. Nothing of another root, and nothing that is not allowed.
|
|
1043
|
+
method('types', async (params, call) => {
|
|
1044
|
+
const root = requireRoot(params);
|
|
1045
|
+
permitted(call, root, 'walk');
|
|
1046
|
+
const ops = ['get', 'call', 'set', 'on'].filter((op) => keyMay(call, root, op));
|
|
1047
|
+
const mine = (list) => (Array.isArray(list) ? list : []).filter((entry) => { const first = String(entry).split(/[.@]/, 1)[0]; return first === root || first === '*' || first === '**'; });
|
|
1048
|
+
// An entry that lets a callback return is told as `(callback)`: a client that predates the notation parses only that, and the types do not describe a return.
|
|
1049
|
+
const told = (op, entry) => (op === 'call' ? String(entry).replace(CALLBACK_NOTATION, '(callback)') : entry);
|
|
1050
|
+
const lists = Object.fromEntries(['get', 'call', 'set', 'on'].map((op) => [op, ops.includes(op) ? mine(allowStrings[op]).map((e) => told(op, e)) : []]));
|
|
1051
|
+
const typeMap = narrowTypes({ root, ops, allow: allowStrings, types: typesByRoot.get(root) ?? {} });
|
|
1052
|
+
const offered = new Set(lists.on.map((entry) => entry.slice(entry.indexOf('@') + 1)));
|
|
1053
|
+
const fields = Object.fromEntries(Object.entries(eventFields).filter(([type]) => type === '*' ? offered.size > 0 : offered.has(type)));
|
|
1054
|
+
const answer = { version: 1, root, ops, allow: lists, eventFields: fields, types: typeMap, handles: handleRoots.has(root) };
|
|
1055
|
+
const size = toWire(answer, { maxDepth: 6, maxBytes: call.maxBytes ?? limits.maxValueBytes });
|
|
1056
|
+
if (!('v' in size)) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'the description could not be written', { reason: 'bad-reply' });
|
|
1057
|
+
return size.v;
|
|
1058
|
+
});
|
|
902
1059
|
method('resolve', resolve);
|
|
903
1060
|
method('set', setValue);
|
|
904
1061
|
method('describe', describe);
|
|
@@ -907,10 +1064,39 @@ export function createObjectsServer(options = {}) {
|
|
|
907
1064
|
method('unsubscribe', unsubscribe);
|
|
908
1065
|
method('release', releaseHandle);
|
|
909
1066
|
method('releaseCallback', releaseCallback);
|
|
910
|
-
return {
|
|
1067
|
+
return {
|
|
1068
|
+
limits, handleCount: () => session.handles.size, callbackCount: () => session.callbacks.size, deadCallbackCalls: () => session.deadCalls,
|
|
1069
|
+
/** What became of the calls of callbacks that return a value: `pending` now, and since the channel began `answered`, `timedOut`, `failed` (the far side's error, a write that failed, the channel ending, a release), `refused` (too big or not plain data) and `dropped` (the rate, the size, a full table). */
|
|
1070
|
+
callbackReturnStats: () => ({ pending: session.pendingReturns.size, ...session.returnStats }),
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
/**
|
|
1075
|
+
* One `get` or `call` of a named path (`path` starts with the root: `['window', 'app', 'cart', 'add']`), through the same checks as an objects call: the key's grants
|
|
1076
|
+
* (`permit(root, op)`), the allow-lists, the names that need listing, `authorize` and the window guard. No session: nothing here makes a handle or takes a callback, and the
|
|
1077
|
+
* answer is the wire value (`{ v }`, or a named non-value `{ u }`). `args` are plain data, copied and bounded like the arguments of a call. This is what an MCP tool runs.
|
|
1078
|
+
* @param {{ kind: 'get' | 'call', path: string[], args?: unknown[] }} request
|
|
1079
|
+
* @param {{ who?: object, permit?: (root: string, op: string) => boolean, signal?: AbortSignal }} [ctx]
|
|
1080
|
+
*/
|
|
1081
|
+
async function invoke({ kind, path, args = [] } = {}, { who, permit, signal } = {}) {
|
|
1082
|
+
if (kind !== 'get' && kind !== 'call') throw invalid('invoke: kind must be get or call');
|
|
1083
|
+
if (!Array.isArray(path) || path.length < 2 || !path.every((s) => typeof s === 'string')) throw invalid('invoke: path must be a root and at least one member');
|
|
1084
|
+
if (!Array.isArray(args)) throw invalid('invoke: args must be an array');
|
|
1085
|
+
const root = requireRoot({ root: path[0] });
|
|
1086
|
+
const last = path.length - 2;
|
|
1087
|
+
const ops = path.slice(1).map((key, i) => (kind === 'call' && i === last ? { call: key, args } : { get: key }));
|
|
1088
|
+
return resolve({ root, ops }, { who: callerIdentity(who) ?? undefined, permit, signal, maxBytes: limits.maxValueBytes });
|
|
911
1089
|
}
|
|
912
1090
|
|
|
913
|
-
|
|
1091
|
+
// The MCP face (#219): tools for named allow-listed paths, built from the host's `mcp: { tools }`. Empty unless the host wrote it.
|
|
1092
|
+
const mcpTools = buildMcpTools({
|
|
1093
|
+
mcp,
|
|
1094
|
+
rootNames,
|
|
1095
|
+
allows: (kind, root, segs) => staticCheck(kind, root, segs, { terminal: true }),
|
|
1096
|
+
invoke,
|
|
1097
|
+
});
|
|
1098
|
+
|
|
1099
|
+
return { attach, invoke, limits: Object.freeze({ ...limits }), rootNames: rootNames.slice(), mcpTools, mcpToolNames: mcpTools.map((t) => t.name) };
|
|
914
1100
|
}
|
|
915
1101
|
|
|
916
1102
|
// ── A bare duplex as a peer ─────────────────────────────────────────────────────────────────────────────────────────
|
|
@@ -1196,13 +1382,14 @@ export async function on(ref, type, listener, { fields, onError } = {}) {
|
|
|
1196
1382
|
const { state, keys } = pathOf(ref, 'on');
|
|
1197
1383
|
if (typeof listener !== 'function') throw new TypeError('on needs a listener function: listener(data, { type, seq, dropped })');
|
|
1198
1384
|
const { session } = state;
|
|
1199
|
-
if (state.handle !== undefined) throw new TypeError('events are not offered through a handle: name the source by its path');
|
|
1200
1385
|
if (!session.features?.includes('events')) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'this host does not support events (it did not say so)', { reason: 'unsupported' });
|
|
1386
|
+
// Through a handle: a host before 0.51.0 would not know the request, so it is not sent unless the host said it supports it.
|
|
1387
|
+
if (state.handle !== undefined && !session.features.includes('handle-events')) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'this host does not support events through a handle (it did not say so): name the source by its path instead', { reason: 'unsupported' });
|
|
1201
1388
|
const id = session.nextSub++;
|
|
1202
1389
|
// Registered before the request: an event can follow the answer at once.
|
|
1203
|
-
session.subs.set(id, { listener, onError, type });
|
|
1390
|
+
session.subs.set(id, { listener, onError, type, handle: state.handle });
|
|
1204
1391
|
try {
|
|
1205
|
-
await session.peer.request('subscribe', { id,
|
|
1392
|
+
await session.peer.request('subscribe', { id, ...target(state), path: keys, type, ...(fields ? { fields } : {}) });
|
|
1206
1393
|
} catch (e) { session.subs.delete(id); throw asObjectsError(e, session); }
|
|
1207
1394
|
return async function off() {
|
|
1208
1395
|
if (!session.subs.delete(id)) return;
|
|
@@ -1216,12 +1403,48 @@ export async function off(unsubscribe) {
|
|
|
1216
1403
|
await unsubscribe();
|
|
1217
1404
|
}
|
|
1218
1405
|
|
|
1406
|
+
/**
|
|
1407
|
+
* What this key may do on a root, as data: `{ version, root, ops, allow, eventFields, types, handles }` (the host's allow-list entries for the root, narrowed by the key's
|
|
1408
|
+
* capabilities, and the host's type map for them). Give it to `describeRootTypes` from `@johnhenry/wsh/objects-types` for the text of a `.d.ts`; nothing is written or evaluated here.
|
|
1409
|
+
* Takes a root as `openObjects()` returns it (`page.window`), not a path or a handle.
|
|
1410
|
+
*/
|
|
1411
|
+
export async function rootDescription(ref, { signal } = {}) {
|
|
1412
|
+
const state = stateOf(ref);
|
|
1413
|
+
if (state.ops.length > 0 || state.handle !== undefined) throw new TypeError('rootDescription takes a root (page.window), not a path or a handle');
|
|
1414
|
+
if (!state.session.features?.includes('types')) throw new ObjectsError(OBJECTS_ERROR.FAILED, 'this host does not support types (it did not say so): it is older than 0.51.0', { reason: 'unsupported' });
|
|
1415
|
+
try { return await state.session.peer.request('types', { root: state.root }, { signal }); } catch (e) { throw asObjectsError(e, state.session); }
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1219
1418
|
/** The shape of an object, for a REPL or completion: `{ type, keys: [{ key, type, own }] }`. Only names the allow-list could walk to are told. */
|
|
1220
1419
|
export async function describe(ref, { signal } = {}) {
|
|
1221
1420
|
const { state, keys } = pathOf(ref, 'describe');
|
|
1222
1421
|
try { return await state.session.peer.request('describe', { ...target(state), path: keys }, { signal }); } catch (e) { throw asObjectsError(e, state.session); }
|
|
1223
1422
|
}
|
|
1224
1423
|
|
|
1424
|
+
/**
|
|
1425
|
+
* Answer a host that asked for a callback's return value: plain data within the bound, or an error mark (the text of an error never travels). Never throws: the host bounds
|
|
1426
|
+
* its own wait, so an answer that cannot be sent costs the page `undefined`, nothing more.
|
|
1427
|
+
*/
|
|
1428
|
+
async function answerCallback(session, rid, threw, out, onCallbackError) {
|
|
1429
|
+
let body;
|
|
1430
|
+
try {
|
|
1431
|
+
if (threw) body = { rid, error: true };
|
|
1432
|
+
else {
|
|
1433
|
+
const value = await out;
|
|
1434
|
+
if (value === undefined) body = { rid };
|
|
1435
|
+
else if (typeof value === 'function' || value instanceof RemoteHandle) body = { rid, error: true };
|
|
1436
|
+
else {
|
|
1437
|
+
const w = toWire(value, { maxDepth: 4, maxBytes: OBJECTS_DEFAULT_LIMITS.maxValueBytes });
|
|
1438
|
+
body = 'v' in w ? { rid, value: w.v } : { rid, error: true };
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
} catch (e) {
|
|
1442
|
+
try { onCallbackError?.(e); } catch { /* ours */ }
|
|
1443
|
+
body = { rid, error: true };
|
|
1444
|
+
}
|
|
1445
|
+
try { await session.peer.request('callbackResult', body); } catch { /* the channel is going away, or the host gave up */ }
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1225
1448
|
/**
|
|
1226
1449
|
* The client half over any peer: asks for the roots and returns them as lazy references, `{ window }`.
|
|
1227
1450
|
* @param {object} peer
|
|
@@ -1236,7 +1459,10 @@ export async function createObjectsClient(peer, { timeoutMs, onCallbackError, on
|
|
|
1236
1459
|
const fn = session.callbacks.get(params?.id);
|
|
1237
1460
|
if (!fn || !Array.isArray(params.args)) return;
|
|
1238
1461
|
if (Number.isSafeInteger(params.dropped) && params.dropped > 0) { try { onCallbackDropped?.({ dropped: params.dropped, fn }); } catch { /* ours */ } }
|
|
1239
|
-
|
|
1462
|
+
let out; let threw = false;
|
|
1463
|
+
try { out = fn(...params.args); } catch (e) { threw = true; try { onCallbackError?.(e); } catch { /* ours */ } }
|
|
1464
|
+
// The host asked for the return value (`rid`: only a host whose entry says (callback:returns), and only because the roots request below said this side answers).
|
|
1465
|
+
if (Number.isSafeInteger(params.rid) && params.rid >= 1) void answerCallback(session, params.rid, threw, out, onCallbackError);
|
|
1240
1466
|
});
|
|
1241
1467
|
// An event the host delivers: to the listener that asked, in this process. A listener that throws is this side's business and goes to its `onError`: it never travels back.
|
|
1242
1468
|
peer.onNotification?.('event', (params) => {
|
|
@@ -1249,7 +1475,8 @@ export async function createObjectsClient(peer, { timeoutMs, onCallbackError, on
|
|
|
1249
1475
|
peer.onNotification?.('closing', (params) => { session.closing = typeof params?.reason === 'string' ? clip(params.reason, TEXT_MAX) : 'closing'; });
|
|
1250
1476
|
let roots;
|
|
1251
1477
|
try {
|
|
1252
|
-
|
|
1478
|
+
// This side answers a callback's return value when a host asks for it: a host that predates the notation ignores the field, and one that has no such entry never asks.
|
|
1479
|
+
const answer = await peer.request('roots', { features: ['callback-returns'] });
|
|
1253
1480
|
roots = answer?.roots;
|
|
1254
1481
|
// What the host says it supports; a host that says nothing (before 0.48.0) supports none of the three.
|
|
1255
1482
|
session.features = Array.isArray(answer?.features) ? answer.features.filter((f) => typeof f === 'string') : [];
|
|
@@ -1284,6 +1511,8 @@ export async function release(handle) {
|
|
|
1284
1511
|
if (!rec) throw new TypeError('release needs a handle, or a function that was passed as a callback');
|
|
1285
1512
|
if (rec.released) return;
|
|
1286
1513
|
rec.released = true;
|
|
1514
|
+
// The host ends the subscriptions made through the handle with it: forget them here too.
|
|
1515
|
+
for (const [id, sub] of [...rec.session.subs]) if (sub.handle === rec.id) rec.session.subs.delete(id);
|
|
1287
1516
|
try { await rec.session.peer.request('release', { handle: rec.id }); } catch (e) { throw asObjectsError(e, rec.session); }
|
|
1288
1517
|
}
|
|
1289
1518
|
|