@ractive-ch/tab-mcp-client 0.14.0 → 0.16.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.
Files changed (56) hide show
  1. package/README.md +538 -126
  2. package/always-allowed.d.ts +25 -6
  3. package/cdn/confirm-y30cx7e1.min.js +4 -0
  4. package/cdn/confirm-y30cx7e1.min.js.map +10 -0
  5. package/cdn/connect-bbhj2y7w.min.js +6 -0
  6. package/cdn/connect-bbhj2y7w.min.js.map +12 -0
  7. package/cdn/connection-0y7ngtq7.min.js +17 -0
  8. package/cdn/connection-0y7ngtq7.min.js.map +22 -0
  9. package/cdn/index-vt5zk9me.min.js +91 -0
  10. package/cdn/index-vt5zk9me.min.js.map +13 -0
  11. package/cdn/tab-mcp-client.min.js +3 -3
  12. package/cdn/tab-mcp-client.min.js.map +6 -6
  13. package/confirm-fgnjgd08.js +263 -0
  14. package/confirm-fgnjgd08.js.map +10 -0
  15. package/confirm.d.ts +54 -0
  16. package/connect-8jpb0k29.js +484 -0
  17. package/connect-8jpb0k29.js.map +10 -0
  18. package/connect.d.ts +40 -0
  19. package/{connection-eqsag07j.js → connection-1d8rxgbq.js} +515 -242
  20. package/connection-1d8rxgbq.js.map +16 -0
  21. package/connection.d.ts +9 -9
  22. package/dialog.d.ts +83 -0
  23. package/{index-nmn1j689.js → index-5jyqehpk.js} +14 -10
  24. package/index-5jyqehpk.js.map +11 -0
  25. package/index-jnz7w9xa.js +392 -0
  26. package/index-jnz7w9xa.js.map +12 -0
  27. package/index.d.ts +1 -1
  28. package/index.js +285 -244
  29. package/index.js.map +6 -6
  30. package/mapping.d.ts +37 -4
  31. package/mcp.d.ts +23 -8
  32. package/package.json +5 -1
  33. package/react.d.ts +13 -12
  34. package/react.js +20 -14
  35. package/react.js.map +3 -3
  36. package/registry.d.ts +12 -5
  37. package/secret.d.ts +5 -2
  38. package/serve.d.ts +68 -0
  39. package/setup.d.ts +15 -25
  40. package/setup.js +1 -1
  41. package/strings.d.ts +107 -0
  42. package/tab-mcp.d.ts +76 -36
  43. package/tunnel.d.ts +74 -0
  44. package/tunnel.js +263 -0
  45. package/tunnel.js.map +10 -0
  46. package/types.d.ts +206 -73
  47. package/webmcp.d.ts +13 -18
  48. package/cdn/connection-dweyrdbn.min.js +0 -12
  49. package/cdn/connection-dweyrdbn.min.js.map +0 -21
  50. package/cdn/ui-5zecjy7s.min.js +0 -86
  51. package/cdn/ui-5zecjy7s.min.js.map +0 -14
  52. package/connection-eqsag07j.js.map +0 -15
  53. package/index-nmn1j689.js.map +0 -11
  54. package/ui-4qv8d1a3.js +0 -781
  55. package/ui-4qv8d1a3.js.map +0 -11
  56. package/ui.d.ts +0 -83
package/index.js CHANGED
@@ -3,17 +3,28 @@ var NAME = /^[A-Za-z0-9_.-]{1,128}$/;
3
3
  function isPlainObject(v) {
4
4
  return typeof v === "object" && v !== null && !Array.isArray(v);
5
5
  }
6
- function usesMcpHeader(schema, depth = 0) {
7
- if (depth > 64 || typeof schema !== "object" || schema === null)
8
- return false;
9
- if (!Array.isArray(schema) && "x-mcp-header" in schema)
10
- return true;
11
- return Object.values(schema).some((v) => usesMcpHeader(v, depth + 1));
6
+ var DATA = /^(default|examples|const|enum)$/;
7
+ var NAMED = /^(properties|patternProperties|\$defs|definitions|dependentSchemas)$/;
8
+ function eachSchema(node, visit, depth = 0, map = false) {
9
+ if (depth > 64 || typeof node !== "object" || node === null)
10
+ return;
11
+ map ||= Array.isArray(node);
12
+ if (!map)
13
+ visit(node);
14
+ for (const [key, value] of Object.entries(node))
15
+ if (map || !DATA.test(key))
16
+ eachSchema(value, visit, depth + 1, !map && NAMED.test(key));
12
17
  }
13
18
  function resolvePointer(root, pointer) {
14
19
  let node = root;
15
20
  for (const raw of pointer.split("/").slice(1)) {
16
- const key = decodeURIComponent(raw).replaceAll("~1", "/").replaceAll("~0", "~");
21
+ let key;
22
+ try {
23
+ key = decodeURIComponent(raw);
24
+ } catch {
25
+ return;
26
+ }
27
+ key = key.replaceAll("~1", "/").replaceAll("~0", "~");
17
28
  if (typeof node !== "object" || node === null || !Object.hasOwn(node, key))
18
29
  return;
19
30
  node = node[key];
@@ -24,25 +35,22 @@ function schemaProblem(root) {
24
35
  const anchors = new Set;
25
36
  const refs = [];
26
37
  const patterns = [];
27
- const walk = (node, depth) => {
28
- if (depth > 64 || typeof node !== "object" || node === null)
29
- return;
30
- if (!Array.isArray(node)) {
31
- const o = node;
32
- if (typeof o["$anchor"] === "string")
33
- anchors.add(o["$anchor"]);
34
- if (typeof o["$ref"] === "string")
35
- refs.push(o["$ref"]);
36
- if (typeof o["pattern"] === "string")
37
- patterns.push(o["pattern"]);
38
- const pp = o["patternProperties"];
39
- if (typeof pp === "object" && pp !== null)
40
- patterns.push(...Object.keys(pp));
41
- }
42
- for (const v of Object.values(node))
43
- walk(v, depth + 1);
44
- };
45
- walk(root, 0);
38
+ let header = false;
39
+ eachSchema(root, (o) => {
40
+ if (typeof o["$anchor"] === "string")
41
+ anchors.add(o["$anchor"]);
42
+ if (typeof o["$ref"] === "string")
43
+ refs.push(o["$ref"]);
44
+ if (typeof o["pattern"] === "string")
45
+ patterns.push(o["pattern"]);
46
+ const pp = o["patternProperties"];
47
+ if (isPlainObject(pp))
48
+ patterns.push(...Object.keys(pp));
49
+ if ("x-mcp-header" in o)
50
+ header = true;
51
+ });
52
+ if (header)
53
+ return "x-mcp-header is not supported by tab-mcp";
46
54
  for (const p of patterns) {
47
55
  try {
48
56
  new RegExp(p, "u");
@@ -63,7 +71,15 @@ function schemaProblem(root) {
63
71
  function validateTool(tool) {
64
72
  if (!isPlainObject(tool))
65
73
  throw new TypeError("registerTool: the tool must be an object");
66
- const { name, title, description, inputSchema, execute, annotations } = tool;
74
+ const {
75
+ name,
76
+ title,
77
+ description,
78
+ inputSchema,
79
+ outputSchema,
80
+ execute,
81
+ annotations
82
+ } = tool;
67
83
  if (typeof name !== "string" || !NAME.test(name)) {
68
84
  throw new TypeError(`registerTool: the name must be 1–128 characters of A–Z, a–z, 0–9, "_", "-" or "." (got ${JSON.stringify(name)})`);
69
85
  }
@@ -76,23 +92,22 @@ function validateTool(tool) {
76
92
  if (typeof execute !== "function") {
77
93
  throw new TypeError(`registerTool: tool ${name} needs an execute function`);
78
94
  }
79
- const schema = inputSchema ?? { type: "object" };
80
- if (!isPlainObject(schema) || schema["type"] !== "object") {
81
- throw new TypeError(`registerTool: the inputSchema of ${name} must be a JSON Schema object with "type": "object"`);
82
- }
83
- if (usesMcpHeader(schema)) {
84
- throw new TypeError(`registerTool: ${name} uses x-mcp-header, which tab-mcp does not support`);
85
- }
86
- const problem = schemaProblem(schema);
87
- if (problem !== undefined) {
88
- throw new TypeError(`registerTool: the inputSchema of ${name}: ${problem}`);
89
- }
90
- let copied;
91
- try {
92
- copied = JSON.parse(JSON.stringify(schema));
93
- } catch {
94
- throw new TypeError(`registerTool: the inputSchema of ${name} must be JSON`);
95
- }
95
+ const copy = (schema, what) => {
96
+ if (!isPlainObject(schema) || schema["type"] !== "object") {
97
+ throw new TypeError(`registerTool: the ${what} of ${name} must be a JSON Schema object with "type": "object"`);
98
+ }
99
+ let copied;
100
+ try {
101
+ copied = JSON.parse(JSON.stringify(schema));
102
+ } catch {
103
+ throw new TypeError(`registerTool: the ${what} of ${name} must be JSON`);
104
+ }
105
+ const problem = schemaProblem(copied);
106
+ if (problem !== undefined)
107
+ throw new TypeError(`registerTool: the ${what} of ${name}: ${problem}`);
108
+ return copied;
109
+ };
110
+ const copied = copy(inputSchema ?? { type: "object" }, "inputSchema");
96
111
  if (annotations !== undefined && !isPlainObject(annotations)) {
97
112
  throw new TypeError(`registerTool: the annotations of ${name} must be an object`);
98
113
  }
@@ -100,12 +115,15 @@ function validateTool(tool) {
100
115
  for (const [key, value] of Object.entries(annotations ?? {})) {
101
116
  if (typeof value === "boolean")
102
117
  hints[key] = value;
118
+ else if (value !== undefined && /Hint$|^debugging$/.test(key))
119
+ throw new TypeError(`registerTool: ${key} of ${name} must be a boolean`);
103
120
  }
104
121
  return {
105
122
  name,
106
123
  title,
107
124
  description,
108
125
  inputSchema: copied,
126
+ outputSchema: outputSchema === undefined ? undefined : copy(outputSchema, "outputSchema"),
109
127
  annotations: hints,
110
128
  execute
111
129
  };
@@ -116,10 +134,16 @@ class ToolRegistry {
116
134
  #listeners = new Set;
117
135
  #compile;
118
136
  register(tool, options = {}) {
119
- const { signal, webmcp } = options;
120
- const registered = { ...validateTool(tool), webmcp };
121
- if (signal?.aborted)
122
- return;
137
+ const { signal, exposedTo } = options;
138
+ const callers = options.callers && [...options.callers];
139
+ if ("webmcp" in options || callers?.some((c) => !/^(relay|local|webmcp)$/.test(c)))
140
+ throw new TypeError('registerTool: callers must be "relay", "local" or "webmcp"; option webmcp is gone');
141
+ const registered = {
142
+ ...validateTool(tool),
143
+ callers,
144
+ exposedTo
145
+ };
146
+ signal?.throwIfAborted();
123
147
  if (this.#tools.has(registered.name)) {
124
148
  throw new DOMException(`registerTool: a tool named ${registered.name} is already registered`, "InvalidStateError");
125
149
  }
@@ -187,7 +211,7 @@ class SecretStore {
187
211
  this.#oldKey = oldKey;
188
212
  this.#claimKey = oldKey === undefined ? undefined : `${oldKey}#moved`;
189
213
  }
190
- get() {
214
+ current() {
191
215
  let stored = null;
192
216
  try {
193
217
  stored = this.#storage?.getItem(this.#key) ?? null;
@@ -203,7 +227,7 @@ class SecretStore {
203
227
  this.#memory = stored;
204
228
  return stored;
205
229
  }
206
- return this.#memory ?? this.rotate();
230
+ return this.#memory;
207
231
  }
208
232
  rotate() {
209
233
  const secret = newSecret();
@@ -220,25 +244,16 @@ class SecretStore {
220
244
  }
221
245
  }
222
246
  // package.json
223
- var version = "0.14.0";
247
+ var version = "0.16.0";
224
248
 
225
249
  // src/version.ts
226
250
  var LIBRARY_NAME = "@ractive-ch/tab-mcp-client";
227
251
  var VERSION = version;
228
252
 
229
253
  // src/webmcp.ts
230
- var g = globalThis;
231
- var getContext;
232
- var Native;
233
- function capture() {
234
- getContext = g.Document && Object.getOwnPropertyDescriptor(g.Document.prototype, "modelContext")?.get;
235
- Native = g.ModelContext;
236
- }
237
- capture();
238
254
  function nativeContext() {
239
255
  try {
240
- const context = getContext?.call(g.document);
241
- return Native !== undefined && context instanceof Native ? context : undefined;
256
+ return Object.getOwnPropertyDescriptor(Document.prototype, "modelContext")?.get?.call(document);
242
257
  } catch {
243
258
  return;
244
259
  }
@@ -249,62 +264,46 @@ var HINTS = [
249
264
  "consequentialHint",
250
265
  "debugging"
251
266
  ];
252
- var ATTRIBUTE = "data-tab-mcp-webmcp";
253
- var listed = new Set;
254
- function writeAttribute() {
255
- g.document?.documentElement?.setAttribute(ATTRIBUTE, [...listed].map((m) => m.name).join(" "));
256
- }
257
- function mirror(registry, context, offered, call) {
267
+ function mirror(registry, context, call) {
258
268
  const mirrors = new Map;
259
269
  const warned = new Set;
260
- const register = (tool, entry, retry) => {
261
- const annotations = {};
262
- for (const key of HINTS) {
263
- const value = tool.annotations[key];
264
- if (value !== undefined)
265
- annotations[key] = value;
266
- }
267
- const native = {
268
- name: tool.name,
269
- title: tool.title,
270
- description: tool.description,
271
- inputSchema: tool.inputSchema,
272
- annotations,
273
- execute: (input, options) => call(tool, input, options?.signal)
274
- };
275
- const { signal } = entry.controller;
276
- Promise.resolve().then(() => signal.aborted || context.registerTool(native, { signal })).catch((error) => {
277
- if (signal.aborted)
278
- return;
279
- if (retry) {
280
- setTimeout(() => register(tool, entry, false));
281
- return;
282
- }
283
- listed.delete(entry);
284
- writeAttribute();
285
- if (warned.has(tool.name))
286
- return;
287
- warned.add(tool.name);
288
- console.warn(`tab-mcp: ${tool.name} is not offered through WebMCP:`, error);
289
- });
290
- };
291
270
  const sync = () => {
292
- for (const [tool, entry] of mirrors) {
271
+ for (const [tool, controller] of mirrors) {
293
272
  if (registry.get(tool.name) === tool)
294
273
  continue;
295
- entry.controller.abort();
274
+ controller.abort();
296
275
  mirrors.delete(tool);
297
- listed.delete(entry);
298
276
  }
299
277
  for (const tool of registry.list()) {
300
- if (mirrors.has(tool) || !offered(tool))
278
+ const { annotations, callers } = tool;
279
+ const consequential = annotations.consequentialHint ?? annotations.destructiveHint;
280
+ if (mirrors.has(tool) || !(callers?.includes("webmcp") ?? !consequential))
301
281
  continue;
302
- const entry = { name: tool.name, controller: new AbortController };
303
- mirrors.set(tool, entry);
304
- listed.add(entry);
305
- register(tool, entry, true);
282
+ const controller = new AbortController;
283
+ mirrors.set(tool, controller);
284
+ const hints = {
285
+ consequentialHint: consequential
286
+ };
287
+ for (const key of HINTS)
288
+ hints[key] ??= annotations[key];
289
+ const { signal } = controller;
290
+ Promise.resolve().then(() => signal.aborted || context.registerTool({
291
+ name: tool.name,
292
+ title: tool.title,
293
+ description: tool.description,
294
+ inputSchema: tool.inputSchema,
295
+ outputSchema: tool.outputSchema,
296
+ annotations: hints,
297
+ execute: (input, options) => call(tool, input, options?.signal)
298
+ }, { signal, exposedTo: tool.exposedTo })).catch((error) => {
299
+ if (signal.aborted)
300
+ return;
301
+ if (warned.has(tool.name))
302
+ return;
303
+ warned.add(tool.name);
304
+ console.warn(`tab-mcp: ${tool.name} is not offered through WebMCP:`, error);
305
+ });
306
306
  }
307
- writeAttribute();
308
307
  };
309
308
  registry.onChange(sync);
310
309
  sync();
@@ -312,31 +311,15 @@ function mirror(registry, context, offered, call) {
312
311
 
313
312
  // src/tab-mcp.ts
314
313
  var LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
315
- var RECONNECT_DELAYS_MS = [5000, 1e4, 20000, 40000, 60000];
314
+ var timing = {
315
+ reconnectDelaysMs: [5000, 1e4, 20000, 40000, 60000],
316
+ answerTimeoutMs: 15000
317
+ };
316
318
  var RECONNECT_REASONS = new Set([
317
319
  "network",
318
320
  "heartbeat",
319
321
  "shutdown"
320
322
  ]);
321
- function reconnectDelays(option) {
322
- if (option === false)
323
- return;
324
- if (option === undefined || option === true)
325
- return RECONNECT_DELAYS_MS;
326
- const delays = option.delaysMs ?? RECONNECT_DELAYS_MS;
327
- if (!Array.isArray(delays) || delays.length === 0 || !delays.every((d) => typeof d === "number" && d >= 0 && d < 2 ** 31)) {
328
- throw new TypeError("TabMcp: reconnect.delaysMs: a non-empty list of ms");
329
- }
330
- return [...delays];
331
- }
332
- function delayOption(name, value) {
333
- if (value === undefined)
334
- return;
335
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value >= 2 ** 31) {
336
- throw new TypeError(`TabMcp: ${name} must be a number of milliseconds`);
337
- }
338
- return value;
339
- }
340
323
  function frozenGrant(grant) {
341
324
  return Object.freeze({
342
325
  ...grant,
@@ -391,23 +374,29 @@ function sessionInfo(m) {
391
374
  info.appName = m.appName;
392
375
  return info;
393
376
  }
377
+ function noRelay() {
378
+ return Promise.reject(new TypeError("TabMcp: this TabMcp has no relay"));
379
+ }
380
+ function notConnected() {
381
+ return Promise.reject(new DOMException("TabMcp: not connected", "InvalidStateError"));
382
+ }
394
383
 
395
384
  class TabMcp extends EventTarget {
396
385
  #registry = new ToolRegistry;
397
386
  #server;
398
387
  #appName;
399
388
  #onConfirm;
400
- #confirmDelayMs;
401
389
  #alwaysAllow;
390
+ #ui;
402
391
  #relayUrl;
403
392
  #secrets;
404
393
  #tabs;
405
- #takenOver = false;
394
+ #stayOn = false;
395
+ #renewing;
406
396
  #identityAssertion;
407
397
  #identity = "none";
408
398
  #identityMessage;
409
399
  #identityRound = 0;
410
- #identityTimeoutMs;
411
400
  #state = "disconnected";
412
401
  #session;
413
402
  #grants = Object.freeze([]);
@@ -416,11 +405,10 @@ class TabMcp extends EventTarget {
416
405
  #connection;
417
406
  #connecting;
418
407
  #generation = 0;
419
- #reconnectDelays;
408
+ #reconnect;
420
409
  #reconnecting;
421
410
  #reconnectTimer;
422
411
  #unwatch;
423
- #pageWaits = false;
424
412
  #connectDialog;
425
413
  #calls = {
426
414
  registry: this.#registry,
@@ -430,30 +418,31 @@ class TabMcp extends EventTarget {
430
418
  };
431
419
  constructor(options) {
432
420
  super();
433
- const { url, origin } = tabUrl(options.relay);
434
421
  const { server, appName } = options;
422
+ const relay = options.relay === undefined ? undefined : tabUrl(options.relay);
435
423
  if (typeof server?.name !== "string" || typeof server.version !== "string") {
436
424
  throw new TypeError("TabMcp: server needs a name and a version");
437
425
  }
438
426
  if (appName !== undefined && !isAppName(appName)) {
439
427
  throw new TypeError("TabMcp: appName must be 1-64 characters without control characters");
440
428
  }
441
- this.#relayUrl = url;
429
+ this.#relayUrl = relay?.url;
442
430
  this.#server = { ...server };
443
431
  this.#appName = appName;
444
432
  this.#onConfirm = options.onConfirm;
445
- this.#confirmDelayMs = delayOption("confirmDelayMs", options.confirmDelayMs);
446
433
  this.#alwaysAllow = options.alwaysAllow === true;
434
+ this.#ui = options.ui;
447
435
  this.#identityAssertion = options.identityAssertion;
448
- this.#identityTimeoutMs = delayOption("identityTimeoutMs", options.identityTimeoutMs) ?? 15000;
449
- this.#reconnectDelays = reconnectDelays(options.reconnect);
450
- const key = options.storageKey ?? `tab-mcp:secret:${origin}:${encodeURIComponent(server.name)}`;
451
- this.#secrets = new SecretStore(options.storage, key, options.storageKey === undefined ? `tab-mcp:secret:${origin}` : undefined);
452
- this.#tabs = options.storage === null ? undefined : `${key}#tabs`;
436
+ this.#reconnect = options.reconnect !== false;
437
+ if (relay !== undefined) {
438
+ const key = options.storageKey ?? `tab-mcp:secret:${relay.origin}:${encodeURIComponent(server.name)}`;
439
+ this.#secrets = new SecretStore(options.storage, key, options.storageKey === undefined ? `tab-mcp:secret:${relay.origin}` : undefined);
440
+ this.#tabs = options.storage === null ? undefined : `${key}#tabs`;
441
+ }
453
442
  this.#registry.onChange(() => this.#emit("toolschange", { tools: this.tools }));
454
443
  const context = options.webmcp === true ? nativeContext() : undefined;
455
444
  if (context !== undefined)
456
- mirror(this.#registry, context, (tool) => tool.webmcp ?? tool.annotations.consequentialHint !== true, (tool, input, signal) => this.#load().then((lazy) => lazy.callFromWebMcp(this.#calls, tool, input, signal)));
445
+ mirror(this.#registry, context, (tool, input, signal) => this.#load().then((lazy) => lazy.callFromWebMcp(this.#calls, tool, input, signal)));
457
446
  }
458
447
  registerTool(tool, options = {}) {
459
448
  try {
@@ -472,12 +461,6 @@ class TabMcp extends EventTarget {
472
461
  get session() {
473
462
  return this.#session;
474
463
  }
475
- get address() {
476
- return this.#session?.address;
477
- }
478
- get appName() {
479
- return this.#session?.appName ?? this.#appName;
480
- }
481
464
  get grants() {
482
465
  return this.#grants;
483
466
  }
@@ -493,9 +476,10 @@ class TabMcp extends EventTarget {
493
476
  refreshIdentity() {
494
477
  const session = this.#session;
495
478
  const ask = this.#identityAssertion;
496
- if (this.#state !== "connected" || session === undefined || ask === undefined) {
497
- return Promise.resolve(false);
498
- }
479
+ if (ask === undefined)
480
+ return Promise.reject(new TypeError("TabMcp: no identityAssertion"));
481
+ if (session === undefined)
482
+ return notConnected();
499
483
  const round = ++this.#identityRound;
500
484
  const connection = this.#connection;
501
485
  this.#setIdentity("pending");
@@ -504,14 +488,15 @@ class TabMcp extends EventTarget {
504
488
  return;
505
489
  this.#identityRound++;
506
490
  this.#setIdentity("none");
507
- }, this.#identityTimeoutMs);
491
+ }, timing.answerTimeoutMs);
508
492
  return new Promise((resolve) => {
509
493
  const settle = (event) => {
510
- if (event.detail.state === "pending")
494
+ const { identity } = event.detail;
495
+ if (identity === "pending")
511
496
  return;
512
497
  this.removeEventListener("identitychange", settle);
513
498
  clearTimeout(timer);
514
- resolve(event.detail.state === "bound");
499
+ resolve(identity);
515
500
  };
516
501
  this.addEventListener("identitychange", settle);
517
502
  Promise.resolve().then(() => ask({ address: session.address, sessionId: session.sessionId })).then((assertion) => {
@@ -537,36 +522,31 @@ class TabMcp extends EventTarget {
537
522
  signOut() {
538
523
  this.#identityRound++;
539
524
  this.#setIdentity("none");
540
- if (this.#state !== "connected")
541
- return false;
542
- return this.#connection?.send({ type: "identity.logout" }) === true;
543
- }
544
- get pairing() {
545
- return this.#pairing;
525
+ return this.#session?.pairing === "oidc" ? this.#ask({ type: "identity.logout" }, () => !this.#grants.length) : notConnected();
546
526
  }
547
527
  get pairingCode() {
548
528
  return this.#pairingCode;
549
529
  }
550
530
  connect(options = {}) {
531
+ if (this.#relayUrl === undefined)
532
+ return noRelay();
551
533
  if (this.#state === "connected" && this.#session !== undefined) {
552
534
  return Promise.resolve(this.#session);
553
535
  }
554
- if (this.#connecting !== undefined) {
555
- if (this.#reconnecting !== undefined)
556
- this.#pageWaits = true;
536
+ if (this.#connecting !== undefined)
557
537
  return this.#connecting;
558
- }
559
538
  if (this.#reconnecting !== undefined)
560
- return this.#attemptReconnect(true);
539
+ return this.#attemptReconnect();
561
540
  const activation = globalThis.navigator?.userActivation;
562
541
  if (options.resume !== true && activation !== undefined && !activation.isActive) {
563
542
  return Promise.reject(new DOMException("connect() must be called from a user action, such as a click", "NotAllowedError"));
564
543
  }
565
- return this.#start();
544
+ return this.#renewing ? this.#renewing.then(() => this.connect({ resume: true })) : this.#start();
566
545
  }
567
- #start(revokeAll) {
568
- this.#setState("connecting");
569
- const connecting = this.#open(this.#generation, revokeAll);
546
+ #start() {
547
+ if (!this.#reconnecting)
548
+ this.#setState("connecting");
549
+ const connecting = this.#open(this.#generation);
570
550
  this.#connecting = connecting;
571
551
  connecting.then(() => {
572
552
  if (this.#connecting === connecting)
@@ -576,56 +556,89 @@ class TabMcp extends EventTarget {
576
556
  return;
577
557
  this.#connecting = undefined;
578
558
  this.#connection = undefined;
579
- this.#setState("disconnected");
559
+ if (!this.#reconnecting)
560
+ this.#setState("disconnected");
580
561
  });
581
562
  return connecting;
582
563
  }
583
564
  async#load() {
584
- const lazy = await import("./connection-eqsag07j.js");
565
+ const lazy = await import("./connection-1d8rxgbq.js");
585
566
  for (const error of lazy.compileRegistry(this.#registry))
586
567
  this.#emit("error", { error });
587
568
  return lazy;
588
569
  }
589
- async#open(generation, revokeAll) {
570
+ async#open(generation, takeBack) {
590
571
  const { openConnection, addressIdOf, withAddress } = await this.#load();
591
- const secret = this.#secrets.get();
572
+ const relayUrl = this.#relayUrl;
573
+ if (relayUrl === undefined || this.#secrets === undefined)
574
+ return noRelay();
575
+ const secret = takeBack ?? this.#secrets.current() ?? this.#secrets.rotate();
592
576
  const address = await addressIdOf(secret);
593
577
  if (generation !== this.#generation) {
594
578
  throw new DOMException("The connection was cancelled", "AbortError");
595
579
  }
596
580
  const ref = {};
597
- const connection = openConnection(this.#host(ref), withAddress(this.#relayUrl, address), secret, revokeAll);
598
- ref.connection = connection;
581
+ const connection = openConnection(this.#host(ref), withAddress(relayUrl, address), secret, { address, revokeAll: !!takeBack });
582
+ if (!takeBack)
583
+ ref.connection = connection;
599
584
  this.#connection = connection;
600
585
  return connection.ready;
601
586
  }
587
+ get hasRelay() {
588
+ return this.#relayUrl !== undefined;
589
+ }
590
+ serve(port, options) {
591
+ return this.#load().then((lazy) => lazy.servePort({
592
+ ...this.#calls,
593
+ server: this.#server,
594
+ error: (error) => this.#emit("error", { error })
595
+ }, port, options));
596
+ }
602
597
  disconnect() {
603
598
  this.#end("user");
604
599
  }
605
600
  newAddress() {
606
- if (this.#takenOver) {
607
- this.#end("new_address");
608
- return this.#start(true).then(() => this.#renew(true), (error) => {
609
- this.#takenOver = true;
610
- throw error;
611
- });
612
- }
613
- return this.#renew(false);
601
+ const secrets = this.#secrets;
602
+ if (!secrets)
603
+ return noRelay();
604
+ return this.#renewing ??= this.#renew(secrets).finally(() => {
605
+ this.#renewing = undefined;
606
+ });
614
607
  }
615
- #renew(on) {
616
- const wasOn = on || this.#state !== "disconnected" || this.#reconnecting !== undefined;
617
- if (this.#state === "connected")
618
- this.#connection?.send({ type: "grants.revokeAll" });
608
+ async#renew(secrets) {
609
+ const wasOn = this.#state !== "disconnected" || this.#stayOn;
610
+ const old = secrets.current();
619
611
  this.#end("new_address");
620
- this.#secrets.rotate();
621
- this.#takenOver = false;
622
- return wasOn ? this.connect({ resume: true }) : Promise.resolve(undefined);
612
+ const generation = this.#generation;
613
+ if (old) {
614
+ this.#setState("connecting");
615
+ try {
616
+ await this.#open(generation, old);
617
+ } catch (error) {
618
+ if (generation === this.#generation) {
619
+ this.#setState("disconnected");
620
+ this.#stayOn = wasOn;
621
+ }
622
+ throw error;
623
+ } finally {
624
+ if (generation === this.#generation) {
625
+ this.#connection?.close("new_address");
626
+ this.#connection = undefined;
627
+ }
628
+ }
629
+ }
630
+ secrets.rotate();
631
+ this.#setGrants([]);
632
+ if (wasOn)
633
+ await this.#start();
634
+ else
635
+ this.#setState("disconnected");
623
636
  }
624
637
  #end(reason) {
625
638
  this.#stopReconnecting();
639
+ this.#stayOn = false;
626
640
  this.#generation++;
627
641
  const connection = this.#connection;
628
- const wasConnected = this.#state === "connected";
629
642
  this.#connection = undefined;
630
643
  this.#connecting = undefined;
631
644
  connection?.close(reason);
@@ -635,42 +648,41 @@ class TabMcp extends EventTarget {
635
648
  this.#setPairingCode(undefined);
636
649
  this.#identityRound++;
637
650
  this.#setIdentity("none");
638
- this.#setState("disconnected");
639
- if (wasConnected)
640
- this.#emit("disconnected", { reason, code: 1000 });
651
+ this.#setState("disconnected", reason);
641
652
  }
642
653
  #scheduleReconnect(reason, attempt) {
643
- const delays = this.#reconnectDelays;
644
- if (delays === undefined)
645
- return;
646
- const delay = delays[Math.min(attempt, delays.length) - 1] ?? 0;
654
+ const delays = timing.reconnectDelaysMs;
655
+ const delay = (delays[Math.min(attempt, delays.length) - 1] ?? 0) * (0.8 + 0.4 * Math.random());
647
656
  clearTimeout(this.#reconnectTimer);
648
657
  this.#reconnectTimer = setTimeout(() => {
649
658
  this.#attemptReconnect().catch(() => {});
650
659
  }, delay);
651
660
  this.#watch();
652
661
  this.#reconnecting = { reason, attempt, at: Date.now() + delay };
653
- this.#emit("reconnecting", this.#reconnecting);
662
+ this.#setState("reconnecting", attempt > 1 ? undefined : reason);
654
663
  }
655
- #attemptReconnect(byPage = false) {
664
+ #attemptReconnect() {
656
665
  clearTimeout(this.#reconnectTimer);
657
666
  this.#reconnectTimer = undefined;
658
667
  if (this.#connecting !== undefined)
659
668
  return this.#connecting;
660
- const info = this.#reconnecting;
661
- this.#pageWaits = byPage;
662
669
  const attempt = this.#start();
663
670
  attempt.catch((error) => {
664
- const pageWaits = this.#pageWaits;
665
- this.#pageWaits = false;
666
- if (info === undefined || this.#reconnecting !== info)
671
+ const info = this.#reconnecting;
672
+ if (info === undefined || this.#connecting !== undefined)
667
673
  return;
668
674
  const reason = error?.reason;
669
675
  if (reason === undefined || RECONNECT_REASONS.has(reason)) {
670
676
  this.#scheduleReconnect(info.reason, info.attempt + 1);
671
677
  return;
672
678
  }
673
- this.#stopReconnecting(pageWaits ? undefined : error instanceof Error ? error : new Error(String(error)));
679
+ this.#stopReconnecting();
680
+ this.#state = "disconnected";
681
+ this.#emit("error", {
682
+ error: error instanceof Error ? error : new Error(String(error))
683
+ });
684
+ if (this.#state === "disconnected")
685
+ this.#emit("statechange", { state: "disconnected" });
674
686
  });
675
687
  return attempt;
676
688
  }
@@ -694,17 +706,12 @@ class TabMcp extends EventTarget {
694
706
  g.removeEventListener?.("online", now);
695
707
  };
696
708
  }
697
- #stopReconnecting(why) {
709
+ #stopReconnecting() {
698
710
  clearTimeout(this.#reconnectTimer);
699
711
  this.#reconnectTimer = undefined;
700
712
  this.#unwatch?.();
701
713
  this.#unwatch = undefined;
702
- if (this.#reconnecting === undefined)
703
- return;
704
714
  this.#reconnecting = undefined;
705
- if (why !== undefined)
706
- this.#emit("error", { error: why });
707
- this.#emit("reconnecting", null);
708
715
  }
709
716
  startPairing() {
710
717
  if (this.#pairing)
@@ -722,11 +729,41 @@ class TabMcp extends EventTarget {
722
729
  this.#setPairingCode(undefined);
723
730
  }
724
731
  revoke(grantId) {
725
- if (this.#state !== "connected")
726
- return false;
727
- return this.#connection?.send({ type: "grant.revoke", grantId }) === true;
732
+ const gone = () => !this.#grants.some((g) => g.grantId === grantId);
733
+ return gone() ? Promise.resolve() : this.#ask({ type: "grant.revoke", grantId }, gone);
734
+ }
735
+ #ask(message, done) {
736
+ if (!this.#session || this.#connection?.send(message) !== true)
737
+ return notConnected();
738
+ return new Promise((resolve, reject) => {
739
+ const types = ["grantschange", "statechange", "error"];
740
+ const settle = (error) => {
741
+ clearTimeout(timer);
742
+ for (const type of types)
743
+ this.removeEventListener(type, check);
744
+ if (error)
745
+ reject(error);
746
+ else
747
+ resolve();
748
+ };
749
+ const check = (event) => {
750
+ const error = event?.detail?.error;
751
+ if (done())
752
+ settle();
753
+ else if (error?.code === "store_unavailable" || error?.code === "unknown_id")
754
+ settle(error);
755
+ else if (this.#state !== "connected")
756
+ settle(new DOMException("TabMcp: not connected", "InvalidStateError"));
757
+ };
758
+ const timer = setTimeout(() => settle(new DOMException("TabMcp: the relay did not answer", "TimeoutError")), timing.answerTimeoutMs);
759
+ for (const type of types)
760
+ this.addEventListener(type, check);
761
+ check();
762
+ });
728
763
  }
729
764
  showConnectDialog(options = {}) {
765
+ if (this.#relayUrl === undefined)
766
+ return noRelay();
730
767
  const doc = options.document ?? globalThis.document;
731
768
  const open = this.#connectDialog;
732
769
  if (open !== undefined) {
@@ -742,8 +779,8 @@ class TabMcp extends EventTarget {
742
779
  async#showConnectDialog(doc) {
743
780
  const connecting = this.connect();
744
781
  connecting.catch(() => {});
745
- const { showConnectDialog } = await import("./ui-4qv8d1a3.js");
746
- await showConnectDialog(this, connecting, doc, this.#server.name);
782
+ const { showConnectDialog } = await import("./connect-8jpb0k29.js");
783
+ await showConnectDialog(this, connecting, doc, this.#server.name, this.#ui);
747
784
  }
748
785
  addEventListener(type, listener, options) {
749
786
  super.addEventListener(type, listener, options);
@@ -754,24 +791,27 @@ class TabMcp extends EventTarget {
754
791
  #emit(type, detail) {
755
792
  this.dispatchEvent(new CustomEvent(type, { detail }));
756
793
  }
757
- #setState(state) {
758
- if (this.#state === state)
794
+ #setState(state, reason) {
795
+ if (this.#state === state && state !== "reconnecting")
759
796
  return;
760
797
  this.#state = state;
761
- this.#emit("statechange", { state });
798
+ this.#emit("statechange", reason ? { state, reason } : { state });
762
799
  }
763
- #setIdentity(state, message) {
764
- if (this.#identity === state && message === undefined)
800
+ #setIdentity(identity, message) {
801
+ if (this.#identity === identity && message === undefined)
765
802
  return;
766
- this.#identity = state;
767
- this.#identityMessage = state === "refused" ? message : undefined;
768
- this.#emit("identitychange", message === undefined ? { state } : { state, message });
803
+ this.#identity = identity;
804
+ this.#identityMessage = identity === "refused" ? message : undefined;
805
+ this.#emit("identitychange", {
806
+ identity,
807
+ identityMessage: this.#identityMessage
808
+ });
769
809
  }
770
- #setPairingCode(code) {
771
- if (this.#pairingCode === undefined && code === undefined)
810
+ #setPairingCode(pairingCode) {
811
+ if (this.#pairingCode === undefined && pairingCode === undefined)
772
812
  return;
773
- this.#pairingCode = code;
774
- this.#emit("pairingcode", code ?? null);
813
+ this.#pairingCode = pairingCode;
814
+ this.#emit("pairingcode", { pairingCode });
775
815
  }
776
816
  #setGrants(grants) {
777
817
  this.#grants = Object.freeze(grants.map(frozenGrant));
@@ -784,13 +824,13 @@ class TabMcp extends EventTarget {
784
824
  }
785
825
  return this.confirmInPage(request);
786
826
  }
787
- confirmInPage(request) {
788
- const doc = globalThis.document;
827
+ confirmInPage(request, options = {}) {
828
+ const doc = options.document ?? globalThis.document;
789
829
  if (doc === undefined)
790
830
  return Promise.resolve(false);
791
- return import("./ui-4qv8d1a3.js").then((ui) => ui.confirmInPage(this, request, doc, {
792
- allowDelayMs: this.#confirmDelayMs,
793
- alwaysAllow: this.#alwaysAllow
831
+ return import("./confirm-fgnjgd08.js").then((ui) => ui.confirmInPage(this, request, doc, {
832
+ alwaysAllow: this.#alwaysAllow,
833
+ ui: this.#ui
794
834
  }));
795
835
  }
796
836
  #host(ref) {
@@ -819,14 +859,13 @@ class TabMcp extends EventTarget {
819
859
  if (!current())
820
860
  return session;
821
861
  this.#session = session;
822
- this.#takenOver = false;
862
+ this.#stayOn = false;
823
863
  this.#stopReconnecting();
824
- this.#setState("connected");
825
864
  this.#setGrants([...m.grants]);
826
865
  if (this.#pairing)
827
866
  this.#connection?.send({ type: "pairing.start" });
828
- this.#emit("connected", session);
829
- if (session.pairing === "oidc")
867
+ this.#setState("connected");
868
+ if (session.pairing === "oidc" && this.#identityAssertion)
830
869
  this.refreshIdentity();
831
870
  return session;
832
871
  },
@@ -865,21 +904,23 @@ class TabMcp extends EventTarget {
865
904
  if (current())
866
905
  this.#emit("error", { error });
867
906
  },
868
- closed: (reason, code) => {
907
+ closed: (reason) => {
869
908
  if (!current())
870
909
  return;
871
910
  if (reason === "replaced")
872
- this.#takenOver = replacedHere = true;
873
- const generation = this.#generation;
911
+ this.#stayOn = replacedHere = true;
874
912
  this.#connection = undefined;
875
913
  this.#session = undefined;
914
+ const generation = this.#generation;
876
915
  this.#setPairingCode(undefined);
877
916
  this.#identityRound++;
878
917
  this.#setIdentity("none");
879
- this.#setState("disconnected");
880
- this.#emit("disconnected", { reason, code });
881
- if (RECONNECT_REASONS.has(reason) && this.#generation === generation && this.#state === "disconnected" && this.#connecting === undefined)
918
+ if (generation !== this.#generation)
919
+ return;
920
+ if (this.#reconnect && RECONNECT_REASONS.has(reason))
882
921
  this.#scheduleReconnect(reason, 1);
922
+ else
923
+ this.#setState("disconnected", reason);
883
924
  }
884
925
  };
885
926
  }
@@ -889,5 +930,5 @@ export {
889
930
  VERSION
890
931
  };
891
932
 
892
- //# debugId=44223BB9C5F01CE164756E2164756E21
933
+ //# debugId=6E29CB68C279C2FB64756E2164756E21
893
934
  //# sourceMappingURL=index.js.map