@impro.social/impro-plugin 0.0.20 → 0.0.22

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 (3) hide show
  1. package/main.d.ts +1420 -0
  2. package/main.js +1107 -125
  3. package/package.json +13 -5
package/main.js CHANGED
@@ -1,3 +1,46 @@
1
+ /**
2
+ * @typedef {Record<string, unknown>} PostView
3
+ * Hydrated `app.bsky.feed.defs#postView` shape.
4
+ * @typedef {Record<string, unknown>} ProfileView
5
+ * Basic `app.bsky.actor.defs#profileView` shape.
6
+ * @typedef {Record<string, unknown>} DetailedProfileView
7
+ * Detailed profile view with viewer relationship fields.
8
+ * @typedef {Record<string, unknown>} KnownFollowersResponse
9
+ * Paginated response from `getKnownFollowers`: `{ followers, cursor }`.
10
+ * @typedef {Record<string, unknown>} RepoRecord
11
+ * A raw repo record: `{ uri, cid, value }`.
12
+ * @typedef {Record<string, unknown>} FeedItem
13
+ * A `app.bsky.feed.defs#feedViewPost` (post + reply/repost context).
14
+ * @typedef {{ $type: string } & Record<string, unknown>} RichTextFacetFeature
15
+ * One feature of a facet; fields beyond `$type` vary by service.
16
+ * @typedef {{ index: { byteStart: number, byteEnd: number }, features?: RichTextFacetFeature[] }} RichTextFacet
17
+ * An `app.bsky.richtext.facet` — a byte range plus the features applying to it.
18
+ * @typedef {{ type: "text", value: string }} RichTextTextToken
19
+ * A run of plain text.
20
+ * @typedef {{ type: "facet", facet: RichTextFacet, text: string }} RichTextFacetToken
21
+ * The text covered by one facet; the host restores the original facet payload.
22
+ * @typedef {{ type: "inline" | "block", node: VirtualEl | Record<string, unknown>, pluginId?: string }} RichTextNodeToken
23
+ * Custom content the plugin renders itself — `block` on its own line, `inline` in the text flow.
24
+ * @typedef {RichTextTextToken | RichTextFacetToken | RichTextNodeToken} RichTextToken
25
+ * One token in a rich-text stream — `text`, `facet`, `inline`, or `block`.
26
+ * @typedef {Record<string, string> | Headers | Map<string, string> | Iterable<[string, string], void, undefined>} PluginFetchHeaders
27
+ * Any header collection {@link fetch} accepts — read structurally, not by class.
28
+ * @typedef {{ method?: string, headers?: PluginFetchHeaders, body?: string }} PluginFetchInit
29
+ * Options for {@link fetch} — a subset of `RequestInit` the host proxy supports.
30
+ * @typedef {{ feedGenerator: Record<string, unknown> | null, feedContext: string | null, feedProxyUrl: string | null }} PostContextMenuMeta
31
+ * Where a post was seen, passed to `post-context-menu` listeners.
32
+ * @typedef {{ kind: "post" | "reply" | "quote", replyTo: PostView | null, replyRoot: PostView | null, quotedPost: PostView | null }} PostComposerContext
33
+ * What the composer is being opened for, passed to `post-composer-open` listeners.
34
+ * @typedef {{
35
+ * "post-context-menu": (menu: Menu, post: PostView, meta?: PostContextMenuMeta) => void,
36
+ * "profile-context-menu": (menu: Menu, profile: ProfileView) => void,
37
+ * "post-composer-open": (composer: Composer, context: PostComposerContext) => void,
38
+ * }} PluginEventMap
39
+ * The events {@link Plugin.on} accepts, and the listener each one takes.
40
+ * @typedef {VirtualEl | null | undefined} RenderResult
41
+ * What a render callback may return: a tree to render, or nothing.
42
+ */
43
+
1
44
  export class SimpleUUID {
2
45
  #id = 0;
3
46
  create() {
@@ -7,21 +50,45 @@ export class SimpleUUID {
7
50
 
8
51
  const uuid = new SimpleUUID();
9
52
 
53
+ /**
54
+ * Posts a message to the host. The only outbound channel, so every message
55
+ * is checked against {@link WorkerMessage}.
56
+ * @param {WorkerMessage} message
57
+ * @returns {void}
58
+ */
59
+ function post(message) {
60
+ self.postMessage(message);
61
+ }
62
+
63
+ /** @type {Map<number, (...args: any[]) => unknown>} */
10
64
  const callHandlers = new Map();
11
65
 
66
+ /** @type {Map<number, { resolve: (value: unknown) => void, reject: (reason: unknown) => void }>} */
12
67
  const pendingHostCalls = new Map();
13
68
 
69
+ /**
70
+ * @param {string} method
71
+ * @param {...Cloneable} args
72
+ * @returns {Promise<unknown>}
73
+ */
14
74
  function hostCall(method, ...args) {
15
75
  const hostCallId = uuid.create();
16
76
  return new Promise((resolve, reject) => {
17
77
  pendingHostCalls.set(hostCallId, { resolve, reject });
18
- self.postMessage({ type: "hostCall", method, hostCallId, args });
78
+ post({ type: "hostCall", method, hostCallId, args });
19
79
  });
20
80
  }
21
81
 
82
+ /** @type {Map<string, Set<(...args: any[]) => unknown>>} */
22
83
  const eventListeners = new Map();
23
84
  const registeredEvents = new Set();
24
85
 
86
+ /**
87
+ * @param {Iterable<(...args: any[]) => unknown>} listeners
88
+ * @param {string} event
89
+ * @param {unknown[]} args
90
+ * @returns {Promise<void>}
91
+ */
25
92
  async function invokeListeners(listeners, event, args) {
26
93
  for (const listener of listeners) {
27
94
  try {
@@ -32,6 +99,11 @@ async function invokeListeners(listeners, event, args) {
32
99
  }
33
100
  }
34
101
 
102
+ /**
103
+ * @param {string} event
104
+ * @param {unknown[]} args
105
+ * @returns {Promise<unknown>}
106
+ */
35
107
  async function dispatchEvent(event, args) {
36
108
  const listeners = eventListeners.get(event) ?? new Set();
37
109
  switch (event) {
@@ -52,6 +124,11 @@ async function dispatchEvent(event, args) {
52
124
  }
53
125
  }
54
126
 
127
+ /**
128
+ * @param {string} event
129
+ * @param {(...args: any[]) => unknown} listener
130
+ * @returns {void}
131
+ */
55
132
  function addEventListener(event, listener) {
56
133
  let listeners = eventListeners.get(event);
57
134
  if (!listeners) {
@@ -64,7 +141,7 @@ function addEventListener(event, listener) {
64
141
  registeredEvents.add(event);
65
142
  const handlerId = uuid.create();
66
143
  callHandlers.set(handlerId, (...args) => dispatchEvent(event, args));
67
- self.postMessage({
144
+ post({
68
145
  type: "register",
69
146
  target: "eventListener",
70
147
  event,
@@ -73,6 +150,11 @@ function addEventListener(event, listener) {
73
150
  }
74
151
  }
75
152
 
153
+ /**
154
+ * A single item in a {@link Menu}. Configure with the chained setters and
155
+ * an `onClick` handler. Not constructed directly — obtained via
156
+ * `Menu.addItem(builder)`.
157
+ */
76
158
  export class MenuItem {
77
159
  constructor() {
78
160
  this.title = "";
@@ -80,24 +162,51 @@ export class MenuItem {
80
162
  /** @internal */
81
163
  this._callback = () => {};
82
164
  }
165
+ /**
166
+ * Set the menu item's label.
167
+ * @param {string} title
168
+ * @returns {this}
169
+ */
83
170
  setTitle(title) {
84
171
  this.title = title;
85
172
  return this;
86
173
  }
174
+ /**
175
+ * Set the leading icon. Either a named icon (string) or a {@link VirtualEl}
176
+ * to render as the icon.
177
+ * @param {string | VirtualEl} icon
178
+ * @returns {this}
179
+ */
87
180
  setIcon(icon) {
88
181
  this.icon = icon;
89
182
  return this;
90
183
  }
184
+ /**
185
+ * Called when the user activates the item.
186
+ * @param {() => void} callback
187
+ * @returns {this}
188
+ */
91
189
  onClick(callback) {
92
190
  this._callback = callback;
93
191
  return this;
94
192
  }
95
193
  }
96
194
 
195
+ /**
196
+ * A context-menu builder passed as the first argument to
197
+ * `post-context-menu` and `profile-context-menu` event listeners. Call
198
+ * `addItem` to append menu entries.
199
+ */
97
200
  export class Menu {
98
201
  constructor() {
202
+ /** @type {MenuItem[]} */
99
203
  this.items = [];
100
204
  }
205
+ /**
206
+ * Append a menu item. The builder receives a {@link MenuItem} to configure.
207
+ * @param {(item: MenuItem) => void} builder
208
+ * @returns {this}
209
+ */
101
210
  addItem(builder) {
102
211
  const item = new MenuItem();
103
212
  builder(item);
@@ -116,21 +225,48 @@ export class Menu {
116
225
  }
117
226
  }
118
227
 
228
+ /**
229
+ * Builder passed as the first argument to `post-composer-open` event
230
+ * listeners. Queues text operations that the host applies to the composer once
231
+ * all listeners have run. operations from multiple plugins are applied in order.
232
+ */
119
233
  export class Composer {
234
+ /** @type {{ op: string, text: string }[]} */
120
235
  #ops = [];
236
+ /** @type {number | null} */
121
237
  #cursor = null;
238
+ /**
239
+ * Replace the composer's current text.
240
+ * @param {string} text
241
+ * @returns {this}
242
+ */
122
243
  setText(text) {
123
244
  this.#ops.push({ op: "set", text: String(text) });
124
245
  return this;
125
246
  }
247
+ /**
248
+ * Append text to the end of the composer.
249
+ * @param {string} text
250
+ * @returns {this}
251
+ */
126
252
  appendText(text) {
127
253
  this.#ops.push({ op: "append", text: String(text) });
128
254
  return this;
129
255
  }
256
+ /**
257
+ * Prepend text to the start of the composer.
258
+ * @param {string} text
259
+ * @returns {this}
260
+ */
130
261
  prependText(text) {
131
262
  this.#ops.push({ op: "prepend", text: String(text) });
132
263
  return this;
133
264
  }
265
+ /**
266
+ * Move the caret to the given character index in the final text.
267
+ * @param {number} index
268
+ * @returns {this}
269
+ */
134
270
  setCursor(index) {
135
271
  this.#cursor = index;
136
272
  return this;
@@ -141,92 +277,254 @@ export class Composer {
141
277
  }
142
278
  }
143
279
 
280
+ /**
281
+ * Read-only accessors for appview data with the current user as the viewer.
282
+ * Reached via {@link App.data} on the plugin's {@link App} instance.
283
+ */
144
284
  export class PluginData {
285
+ /**
286
+ * Fetch a hydrated post view by AT-URI, as seen by the current user.
287
+ * @param {string} uri
288
+ * @returns {Promise<PostView>}
289
+ */
145
290
  getPost(uri) {
146
- return hostCall("getPost", { uri });
291
+ return /** @type {Promise<PostView>} */ (hostCall("getPost", { uri }));
147
292
  }
293
+ /**
294
+ * Fetch the basic profile view for a DID.
295
+ * @param {string} did
296
+ * @returns {Promise<ProfileView>}
297
+ */
148
298
  getProfile(did) {
149
- return hostCall("getProfile", { did });
299
+ return /** @type {Promise<ProfileView>} */ (
300
+ hostCall("getProfile", { did })
301
+ );
150
302
  }
151
- // Like getProfile, but includes viewer relationship details not present
152
- // on the basic profile view: viewer.following, viewer.followedBy, and
153
- // viewer.knownFollowers (a summary of mutual followers).
303
+ /**
304
+ * Like {@link PluginData.getProfile}, but includes viewer relationship
305
+ * details not present on the basic profile view: `viewer.following`,
306
+ * `viewer.followedBy`, and `viewer.knownFollowers` (a summary of mutual
307
+ * followers).
308
+ * @param {string} did
309
+ * @returns {Promise<DetailedProfileView>}
310
+ */
154
311
  getDetailedProfile(did) {
155
- return hostCall("getDetailedProfile", { did });
312
+ return /** @type {Promise<DetailedProfileView>} */ (
313
+ hostCall("getDetailedProfile", { did })
314
+ );
156
315
  }
157
- // The full known-followers list for did (the summary on
158
- // getDetailedProfile's viewer.knownFollowers is capped to a handful).
316
+ /**
317
+ * The full known-followers list for `did`. The summary on
318
+ * {@link PluginData.getDetailedProfile}'s `viewer.knownFollowers` is
319
+ * capped to a handful; use this to paginate the complete list.
320
+ * @param {string} did
321
+ * @returns {Promise<KnownFollowersResponse>}
322
+ */
159
323
  getKnownFollowers(did) {
160
- return hostCall("getKnownFollowers", { did });
324
+ return /** @type {Promise<KnownFollowersResponse>} */ (
325
+ hostCall("getKnownFollowers", { did })
326
+ );
161
327
  }
328
+ /**
329
+ * Fetch a raw repo record by `(repo, collection, rkey)`.
330
+ * @param {string} repo
331
+ * @param {string} collection
332
+ * @param {string} rkey
333
+ * @returns {Promise<RepoRecord>}
334
+ */
162
335
  getRecord(repo, collection, rkey) {
163
- return hostCall("getRecord", { repo, collection, rkey });
336
+ return /** @type {Promise<RepoRecord>} */ (
337
+ hostCall("getRecord", { repo, collection, rkey })
338
+ );
164
339
  }
165
340
  }
166
341
 
342
+ /**
343
+ * The plugin's handle to the running impro app. Exposed as `this.app` on a
344
+ * {@link Plugin} instance. Owns event subscriptions, data accessors
345
+ * ({@link App.data}), and user-scoped actions.
346
+ */
167
347
  export class App {
168
348
  /** @internal */
169
349
  constructor() {
350
+ /**
351
+ * The signed-in user's basic profile, populated before `onload()` runs.
352
+ * Null when no session is active.
353
+ * @type {ProfileView | null}
354
+ */
170
355
  this.currentUser = null;
356
+ /** Read-only appview accessors — see {@link PluginData}. */
171
357
  this.data = new PluginData();
172
358
  }
359
+ /**
360
+ * Register an event listener. Supported events:
361
+ *
362
+ * - `"post-context-menu"` — `(menu: Menu, post) => void`, called when the
363
+ * user opens a post's context menu.
364
+ * - `"profile-context-menu"` — `(menu: Menu, profile) => void`, called
365
+ * when the user opens a profile's context menu.
366
+ * - `"post-composer-open"` — `(composer: Composer, context: { kind, replyTo, replyRoot, quotedPost }) => void`,
367
+ * called when the post composer opens; use `composer` to seed text.
368
+ *
369
+ * The `listener` signature varies per event — see {@link PluginEventMap}.
370
+ * @template {keyof PluginEventMap} K
371
+ * @param {K} event
372
+ * @param {PluginEventMap[K]} listener
373
+ * @returns {void}
374
+ */
173
375
  on(event, listener) {
174
376
  addEventListener(event, listener);
175
377
  }
176
378
 
379
+ /**
380
+ * Re-run registered feed filters. Pass a `feedURI` to limit the refresh
381
+ * to one feed, or omit/pass `null` to refresh every feed.
382
+ * @param {string | null} [feedURI]
383
+ * @returns {Promise<void>}
384
+ */
177
385
  refreshFeedFilters(feedURI = null) {
178
- return hostCall("refreshFeedFilters", feedURI);
386
+ return /** @type {Promise<void>} */ (
387
+ hostCall("refreshFeedFilters", feedURI)
388
+ );
179
389
  }
180
390
 
181
- // Actions on behalf of the signed-in user. Each method requires the
182
- // corresponding scope ("mute", "block", "feedFeedback") to be declared in
183
- // the plugin manifest's `permissions.actions` array, which the user must
184
- // grant at install time.
391
+ /**
392
+ * Mute an actor on behalf of the signed-in user. Requires the `"mute"`
393
+ * scope in the plugin manifest's `permissions.actions`.
394
+ * @param {string} did
395
+ * @returns {Promise<void>}
396
+ */
185
397
  muteActor(did) {
186
- return hostCall("muteActor", { did, mute: true });
398
+ return /** @type {Promise<void>} */ (
399
+ hostCall("muteActor", { did, mute: true })
400
+ );
187
401
  }
402
+ /**
403
+ * Unmute an actor. Requires the `"mute"` scope.
404
+ * @param {string} did
405
+ * @returns {Promise<void>}
406
+ */
188
407
  unmuteActor(did) {
189
- return hostCall("muteActor", { did, mute: false });
408
+ return /** @type {Promise<void>} */ (
409
+ hostCall("muteActor", { did, mute: false })
410
+ );
190
411
  }
412
+ /**
413
+ * Block an actor on behalf of the signed-in user. Requires the `"block"`
414
+ * scope in the plugin manifest's `permissions.actions`.
415
+ * @param {string} did
416
+ * @returns {Promise<void>}
417
+ */
191
418
  blockActor(did) {
192
- return hostCall("blockActor", { did, block: true });
419
+ return /** @type {Promise<void>} */ (
420
+ hostCall("blockActor", { did, block: true })
421
+ );
193
422
  }
423
+ /**
424
+ * Unblock an actor. Requires the `"block"` scope.
425
+ * @param {string} did
426
+ * @returns {Promise<void>}
427
+ */
194
428
  unblockActor(did) {
195
- return hostCall("blockActor", { did, block: false });
429
+ return /** @type {Promise<void>} */ (
430
+ hostCall("blockActor", { did, block: false })
431
+ );
196
432
  }
197
- // Acts like the user clicking "Show less like this": sends the requestLess
198
- // feedback signal to the feed that served the post and collapses the post
199
- // behind a feedback message in feeds.
433
+ /**
434
+ * Acts like the user clicking "Show less like this": sends the
435
+ * `requestLess` feedback signal to `feedUri` and collapses the post
436
+ * behind a feedback message in feeds. Requires the `"feedFeedback"`
437
+ * scope.
438
+ * @param {string} postUri
439
+ * @param {string} feedUri
440
+ * @returns {Promise<void>}
441
+ */
200
442
  showLessLikeThis(postUri, feedUri) {
201
- return hostCall("showLessLikeThis", { postUri, feedUri });
443
+ return /** @type {Promise<void>} */ (
444
+ hostCall("showLessLikeThis", { postUri, feedUri })
445
+ );
202
446
  }
447
+ /**
448
+ * Sends the `requestMore` feedback signal to `feedUri` for `postUri`.
449
+ * Requires the `"feedFeedback"` scope.
450
+ * @param {string} postUri
451
+ * @param {string} feedUri
452
+ * @returns {Promise<void>}
453
+ */
203
454
  showMoreLikeThis(postUri, feedUri) {
204
- return hostCall("showMoreLikeThis", { postUri, feedUri });
455
+ return /** @type {Promise<void>} */ (
456
+ hostCall("showMoreLikeThis", { postUri, feedUri })
457
+ );
205
458
  }
206
459
  }
207
460
 
461
+ /**
462
+ * Proxied fetch through the host. Requires the `"networkRequest"` permission
463
+ * scope and the target URL must be covered by the plugin's manifest allowlist.
464
+ * `init` accepts `method`, `headers` (plain object, `Headers`, `Map`, or
465
+ * `[name, value]` iterable), and a string `body`. Resolves to a
466
+ * {@link PluginResponse}.
467
+ * @param {string} url
468
+ * @param {PluginFetchInit} [init]
469
+ * @returns {Promise<PluginResponse>}
470
+ */
208
471
  export async function fetch(url, init = {}) {
209
- const result = await hostCall("fetch", {
210
- url,
211
- init: serializeFetchInit(init),
212
- });
472
+ const result = /** @type {SerializedFetchResponse} */ (
473
+ await hostCall("fetch", { url, init: serializeFetchInit(init) })
474
+ );
213
475
  return new PluginResponse(result);
214
476
  }
215
477
 
478
+ /**
479
+ * @param {unknown} value
480
+ * @returns {value is { forEach: (callback: (value: string, name: string) => void) => void }}
481
+ */
482
+ function hasForEach(value) {
483
+ return (
484
+ typeof value === "object" &&
485
+ value !== null &&
486
+ "forEach" in value &&
487
+ typeof value.forEach === "function"
488
+ );
489
+ }
490
+
491
+ /**
492
+ * @param {unknown} value
493
+ * @returns {value is Iterable<[string, string]>}
494
+ */
495
+ function isEntryIterable(value) {
496
+ return (
497
+ typeof value === "object" &&
498
+ value !== null &&
499
+ Symbol.iterator in value &&
500
+ typeof value[Symbol.iterator] === "function"
501
+ );
502
+ }
503
+
504
+ /**
505
+ * @param {PluginFetchInit} init
506
+ * @returns {SerializedFetchInit}
507
+ */
216
508
  function serializeFetchInit(init) {
509
+ /** @type {SerializedFetchInit} */
217
510
  const serialized = {};
218
511
  if (init.method != null) serialized.method = String(init.method);
219
512
  if (init.headers != null) {
513
+ /** @type {Record<string, string>} */
220
514
  const headers = {};
221
- if (typeof init.headers.forEach === "function") {
222
- // Headers, Map, and similar iterables expose forEach(value, name)
223
- init.headers.forEach((value, name) => {
515
+ // Probed structurally rather than by class, so any forEach-able or
516
+ // iterable header collection works. Iteration is tried first because
517
+ // Headers, Map, arrays and iterators all yield [name, value] pairs,
518
+ // whereas forEach passes (value, index) on an array or iterator.
519
+ const headersInit = init.headers;
520
+ if (isEntryIterable(headersInit)) {
521
+ for (const [name, value] of headersInit) headers[name] = value;
522
+ } else if (hasForEach(headersInit)) {
523
+ headersInit.forEach((value, name) => {
224
524
  headers[name] = value;
225
525
  });
226
- } else if (typeof init.headers[Symbol.iterator] === "function") {
227
- for (const [name, value] of init.headers) headers[name] = value;
228
526
  } else {
229
- Object.assign(headers, init.headers);
527
+ Object.assign(headers, headersInit);
230
528
  }
231
529
  serialized.headers = headers;
232
530
  }
@@ -234,29 +532,63 @@ function serializeFetchInit(init) {
234
532
  return serialized;
235
533
  }
236
534
 
535
+ /**
536
+ * Response returned from {@link fetch}. Body is buffered by the host and
537
+ * exposed as text or parsed JSON. `status`, `ok`, and `headers` (a `Map`)
538
+ * mirror the underlying HTTP response.
539
+ */
237
540
  export class PluginResponse {
238
541
  #body;
239
- /** @internal */
542
+ /**
543
+ * @internal
544
+ * @param {SerializedFetchResponse} response
545
+ */
240
546
  constructor({ status, ok, headers, body }) {
547
+ /** @type {number} */
241
548
  this.status = status;
549
+ /** @type {boolean} */
242
550
  this.ok = ok;
551
+ /** @type {Map<string, string>} */
243
552
  this.headers = new Map(Object.entries(headers ?? {}));
244
553
  this.#body = body;
245
554
  }
555
+ /**
556
+ * Resolves with the response body as a string.
557
+ * @returns {Promise<string>}
558
+ */
246
559
  async text() {
247
560
  return this.#body;
248
561
  }
562
+ /**
563
+ * Resolves with the response body parsed as JSON.
564
+ * @returns {Promise<unknown>}
565
+ */
249
566
  async json() {
250
567
  return JSON.parse(this.#body);
251
568
  }
252
569
  }
253
570
 
571
+ /**
572
+ * Shows a toast notification. `noticeEl` is a {@link VirtualEl} that can be
573
+ * mutated (e.g. `addClass`, appending children) synchronously after
574
+ * construction — the host serializes and renders the toast on a microtask, so
575
+ * any mutations made in the same task apply to the initial render. Mutations
576
+ * or `setMessage` calls made after that point do NOT propagate to the mounted
577
+ * toast; call {@link Notice.hide} and create a new `Notice` to change it.
578
+ */
254
579
  export class Notice {
255
580
  #toastId = uuid.create();
256
581
  #timeout;
257
582
  #hidden = false;
583
+ /**
584
+ * `timeout` is in milliseconds; `0` (the default) keeps the toast up until
585
+ * {@link Notice.hide} is called.
586
+ * @param {string} message
587
+ * @param {number} [timeout=0]
588
+ */
258
589
  constructor(message, timeout = 0) {
259
590
  this.#timeout = timeout;
591
+ /** @type {VirtualEl} */
260
592
  this.noticeEl = new VirtualEl("div");
261
593
  this.noticeEl.addClass("toast");
262
594
  this.noticeEl.setText(message);
@@ -269,10 +601,20 @@ export class Notice {
269
601
  });
270
602
  });
271
603
  }
604
+ /**
605
+ * Updates `noticeEl`'s text. Only takes effect if called synchronously
606
+ * before the microtask that snapshots the toast for the initial render.
607
+ * @param {string} message
608
+ * @returns {this}
609
+ */
272
610
  setMessage(message) {
273
611
  this.noticeEl.setText(message);
274
612
  return this;
275
613
  }
614
+ /**
615
+ * Dismisses the toast. No-op if already hidden.
616
+ * @returns {void}
617
+ */
276
618
  hide() {
277
619
  if (this.#hidden) return;
278
620
  this.#hidden = true;
@@ -280,20 +622,36 @@ export class Notice {
280
622
  }
281
623
  }
282
624
 
625
+ /**
626
+ * Injects a CSS block scoped to the plugin. The stylesheet is mounted by the
627
+ * host on the next microtask; snippets are automatically removed when the
628
+ * plugin unloads.
629
+ */
283
630
  export class StyleSnippet {
284
631
  #snippetId = uuid.create();
285
632
  #removed = false;
633
+ /**
634
+ * @param {string} cssText
635
+ */
286
636
  constructor(cssText) {
637
+ /**
638
+ * Resolves once the snippet has been applied by the host.
639
+ * @type {Promise<void>}
640
+ */
287
641
  this.ready = new Promise((resolve, reject) => {
288
642
  queueMicrotask(() => {
289
643
  if (this.#removed) return resolve();
290
644
  hostCall("applyStyleSnippet", {
291
645
  snippetId: this.#snippetId,
292
646
  cssText,
293
- }).then(resolve, reject);
647
+ }).then(() => resolve(), reject);
294
648
  });
295
649
  });
296
650
  }
651
+ /**
652
+ * Removes the snippet from the document. No-op if already removed.
653
+ * @returns {void}
654
+ */
297
655
  remove() {
298
656
  if (this.#removed) return;
299
657
  this.#removed = true;
@@ -303,16 +661,31 @@ export class StyleSnippet {
303
661
 
304
662
  let registered = false;
305
663
 
664
+ /**
665
+ * Base class for impro plugins. Subclass this and override {@link Plugin.onload}
666
+ * (and optionally {@link Plugin.onunload}) to wire up your plugin's extension
667
+ * points. `this.app` is the shared {@link App} instance for host actions and
668
+ * data. Call `MyPlugin.register()` at the top of your plugin's main.js to boot.
669
+ */
306
670
  export class Plugin {
307
- #settingTab = null;
671
+ /** @internal */
308
672
  constructor() {
673
+ /** @type {App} */
309
674
  this.app = new App();
310
675
  }
311
676
 
677
+ /**
678
+ * Adds an item to the impro sidebar. `icon` is a {@link VirtualEl} (typically
679
+ * an SVG) or a string; `callback` runs when the item is clicked.
680
+ * @param {string | VirtualEl} icon
681
+ * @param {string} title
682
+ * @param {() => void} [callback]
683
+ * @returns {void}
684
+ */
312
685
  addSidebarItem(icon, title, callback = () => {}) {
313
686
  const handlerId = uuid.create();
314
687
  callHandlers.set(handlerId, callback);
315
- self.postMessage({
688
+ post({
316
689
  type: "register",
317
690
  target: "sidebarItem",
318
691
  icon: icon instanceof VirtualEl ? icon._serialize() : icon,
@@ -321,26 +694,50 @@ export class Plugin {
321
694
  });
322
695
  }
323
696
 
697
+ /**
698
+ * Loads this plugin's account-synced JSON blob. Follows the user across
699
+ * devices via account preferences. Returns whatever was last saved, or null.
700
+ * @returns {Promise<unknown>}
701
+ */
324
702
  async loadData() {
325
703
  return hostCall("loadData");
326
704
  }
327
705
 
706
+ /**
707
+ * Persists `data` as this plugin's account-synced JSON blob.
708
+ * @param {Cloneable} data
709
+ * @returns {Promise<void>}
710
+ */
328
711
  async saveData(data) {
329
712
  await hostCall("saveData", { data });
330
713
  }
331
714
 
332
- // Device-local counterpart to loadData/saveData: never synced through the
333
- // user's account preferences, so it's the right place for anything that
334
- // shouldn't silently follow the plugin to another device (e.g. a locally
335
- // held secret key). Cleared on uninstall, same as loadData/saveData.
715
+ /**
716
+ * Device-local counterpart to {@link Plugin.loadData}: never synced through
717
+ * the user's account preferences, so it's the right place for anything that
718
+ * shouldn't silently follow the plugin to another device (e.g. a locally
719
+ * held secret key). Cleared on uninstall, same as loadData/saveData.
720
+ * @returns {Promise<unknown>}
721
+ */
336
722
  async loadLocalData() {
337
723
  return hostCall("loadLocalData");
338
724
  }
339
725
 
726
+ /**
727
+ * Device-local counterpart to {@link Plugin.saveData}.
728
+ * @param {Cloneable} data
729
+ * @returns {Promise<void>}
730
+ */
340
731
  async saveLocalData(data) {
341
732
  await hostCall("saveLocalData", { data });
342
733
  }
343
734
 
735
+ /**
736
+ * Registers a {@link PluginSettingTab} shown under this plugin's entry in
737
+ * the app's settings.
738
+ * @param {PluginSettingTab} tab
739
+ * @returns {void}
740
+ */
344
741
  addSettingTab(tab) {
345
742
  tab.plugin = this;
346
743
  const displayHandlerId = uuid.create();
@@ -349,31 +746,49 @@ export class Plugin {
349
746
  tab.display();
350
747
  return tab.containerEl._serialize();
351
748
  });
352
- self.postMessage({
749
+ post({
353
750
  type: "register",
354
751
  target: "settingTab",
355
752
  name: tab.name ?? null,
356
753
  displayHandlerId,
357
754
  });
358
- this.#settingTab = tab;
359
755
  }
360
756
 
361
- addFeedFilter(callback = () => {}) {
757
+ /**
758
+ * Registers a feed filter. `callback(feedUri, feedItems)` returns an object
759
+ * `{ [postUri]: false }` for posts to hide from the feed. Only `false` hides;
760
+ * any other value is ignored, so one plugin can't un-hide what another hid.
761
+ * @param {(feedUri: string, feedItems: FeedItem[]) => Record<string, boolean> | Promise<Record<string, boolean>>} callback
762
+ * @returns {void}
763
+ */
764
+ addFeedFilter(callback = () => ({})) {
362
765
  const handlerId = uuid.create();
363
766
  callHandlers.set(handlerId, callback);
364
- self.postMessage({
767
+ post({
365
768
  type: "register",
366
769
  target: "feedFilter",
367
770
  handlerId,
368
771
  });
369
772
  }
370
773
 
371
- // callback(tokens, context) receives the rich-text token stream for one
372
- // post and returns a new token array (or the input unchanged). The host
373
- // batches all posts of a render into one call per plugin.
374
- //
375
- // options.handlesFacetTypes: array of facet feature $type strings this
376
- // transform owns, to prevent render flash of fallback text
774
+ /**
775
+ * Registers a rich-text transform. `callback(tokens, context)` receives the
776
+ * token stream for one post and returns a new token array (or the input
777
+ * unchanged). Tokens are one of: `text` (plain string run), `facet` (linked
778
+ * text with an atproto facet feature), `inline` (a plugin-produced inline
779
+ * {@link VirtualEl}), or `block` (a plugin-produced block VirtualEl). See
780
+ * {@link FlattenedTokens} for pattern-matching across token boundaries.
781
+ *
782
+ * A node token's `node` is a {@link VirtualEl} when this transform creates it,
783
+ * but arrives in serialized form when an earlier transform produced it.
784
+ *
785
+ * `options.handlesFacetTypes` is an array of facet feature `$type` strings
786
+ * this transform owns, so the host can suppress fallback rendering flash
787
+ * while the transform runs.
788
+ * @param {(tokens: RichTextToken[], context: { uri: string, surface: string, source: { text: string } }) => RichTextToken[] | Promise<RichTextToken[]>} callback
789
+ * @param {{ handlesFacetTypes?: string[] }} [options]
790
+ * @returns {void}
791
+ */
377
792
  registerRichTextTransform(callback = (tokens) => tokens, options = {}) {
378
793
  const handlerId = uuid.create();
379
794
  callHandlers.set(handlerId, async (batch) => {
@@ -383,7 +798,7 @@ export class Plugin {
383
798
  const value = await callback(tokens, context);
384
799
  results.push({ value: serializeTransformTokens(value) });
385
800
  } catch (error) {
386
- results.push({ error: error?.message ?? String(error) });
801
+ results.push({ error: getErrorMessage(error) });
387
802
  }
388
803
  }
389
804
  return results;
@@ -391,7 +806,7 @@ export class Plugin {
391
806
  const handlesFacetTypes = Array.isArray(options.handlesFacetTypes)
392
807
  ? options.handlesFacetTypes.filter((type) => typeof type === "string")
393
808
  : [];
394
- self.postMessage({
809
+ post({
395
810
  type: "register",
396
811
  target: "richTextTransform",
397
812
  handlerId,
@@ -399,14 +814,25 @@ export class Plugin {
399
814
  });
400
815
  }
401
816
 
402
- // options.cacheKey: array of context fields. If provided, the host
403
- // will treat the slot content as a pure function of these fields
404
- // - omitting other fields in the callback and caching return values
405
- // until they're invalidated by refreshSlot(). An empty array declares
406
- // that the content depends on no context at all, so one cached result
407
- // serves every instance.
408
- //
409
- // The host batches all pending contexts of a render into one call.
817
+ /**
818
+ * Registers a slot renderer. `<plugin-slot name="...">` elements in the host
819
+ * UI (or other plugins' output) invoke `callback(context)`, where `context`
820
+ * is a flat string map of the slot element's attributes. The callback should
821
+ * return a {@link VirtualEl} or `null`.
822
+ *
823
+ * `options.cacheKey` is an array of context field names. If provided, the
824
+ * host treats the slot content as a pure function of these fields — omitting
825
+ * other fields from the callback's context and caching return values until
826
+ * invalidated by {@link Plugin.refreshSlot}. An empty array declares that
827
+ * the content depends on no context at all, so one cached result serves
828
+ * every instance.
829
+ *
830
+ * The host batches all pending contexts of a render into one call.
831
+ * @param {string} name
832
+ * @param {(context: Record<string, string>) => RenderResult | Promise<RenderResult>} callback
833
+ * @param {{ cacheKey?: string[] }} [options]
834
+ * @returns {void}
835
+ */
410
836
  registerSlot(name, callback = () => null, options = {}) {
411
837
  const handlerId = uuid.create();
412
838
  callHandlers.set(handlerId, async (batch) => {
@@ -417,7 +843,7 @@ export class Plugin {
417
843
  value: await getSlotContent(name, callback, context),
418
844
  });
419
845
  } catch (error) {
420
- results.push({ error: error?.message ?? String(error) });
846
+ results.push({ error: getErrorMessage(error) });
421
847
  }
422
848
  }
423
849
  return results;
@@ -425,7 +851,7 @@ export class Plugin {
425
851
  const cacheKey = Array.isArray(options.cacheKey)
426
852
  ? options.cacheKey.filter((field) => typeof field === "string")
427
853
  : null;
428
- self.postMessage({
854
+ post({
429
855
  type: "register",
430
856
  target: "slot",
431
857
  name,
@@ -435,20 +861,26 @@ export class Plugin {
435
861
  });
436
862
  }
437
863
 
864
+ /**
865
+ * Registers a full-page view reachable via {@link Plugin.openPage}. `display()`
866
+ * is called on navigation and must return a {@link VirtualEl}, or nothing to
867
+ * render an empty page.
868
+ * @param {{ id: string, title?: string | null, display?: () => RenderResult | Promise<RenderResult> }} options
869
+ * @returns {void}
870
+ */
438
871
  registerPage({ id, title = null, display = () => null }) {
439
872
  const displayHandlerId = uuid.create();
440
873
  callHandlers.set(displayHandlerId, async () => {
441
- const result = await display();
874
+ const result = /** @type {unknown} */ (await display());
442
875
  if (result == null) return null;
443
876
  if (!(result instanceof VirtualEl)) {
444
- const description = result?.constructor?.name ?? typeof result;
445
877
  throw new Error(
446
- `Page "${id}" must return a VirtualEl or null, got ${description}`,
878
+ `Page "${id}" must return a VirtualEl or null, got ${describeValue(result)}`,
447
879
  );
448
880
  }
449
881
  return result._serialize();
450
882
  });
451
- self.postMessage({
883
+ post({
452
884
  type: "register",
453
885
  target: "page",
454
886
  id,
@@ -457,65 +889,130 @@ export class Plugin {
457
889
  });
458
890
  }
459
891
 
460
- // Navigates the user to one of this plugin's registered pages.
892
+ /**
893
+ * Navigates the user to one of this plugin's registered pages.
894
+ * @param {string} pageId
895
+ * @returns {Promise<void>}
896
+ */
461
897
  openPage(pageId) {
462
- return hostCall("openPage", { pageId });
898
+ return /** @type {Promise<void>} */ (hostCall("openPage", { pageId }));
463
899
  }
464
900
 
465
- // Re-invokes a registered page's display callback if the page is open.
466
- // options.reset also discards the rendered tree instead of patching
901
+ /**
902
+ * Re-invokes a registered page's display callback if the page is open.
903
+ * `options.reset` also discards the rendered tree instead of patching it.
904
+ * @param {string} pageId
905
+ * @param {{ reset?: boolean }} [options]
906
+ * @returns {Promise<void>}
907
+ */
467
908
  refreshPage(pageId, { reset = false } = {}) {
468
- return hostCall("refreshPage", { pageId, reset });
469
- }
470
-
471
- // Makes mounted <plugin-slot name=...> instances re-invoke this plugin's
472
- // registered callback for that slot, and drops any cached results. Useful
473
- // when a slot's content depends on plugin state that changed after render.
474
- //
475
- // options.keys: array of matcher objects to be OR'd together,
476
- // e.g. [{ did: "..." }] - any matching slots will be invalidated / refreshed.
477
- // Omit to refresh every instance. A slot registered with a cacheKey can only
478
- // be matched on those declared fields, since its output depends on nothing
479
- // else.
909
+ return /** @type {Promise<void>} */ (
910
+ hostCall("refreshPage", { pageId, reset })
911
+ );
912
+ }
913
+
914
+ /**
915
+ * Makes mounted `<plugin-slot name=...>` instances re-invoke this plugin's
916
+ * registered callback for that slot, and drops any cached results. Useful
917
+ * when a slot's content depends on plugin state that changed after render.
918
+ *
919
+ * `options.keys` is an array of matcher objects OR'd together,
920
+ * e.g. `[{ did: "..." }]` — any matching slots are invalidated and refreshed.
921
+ * Omit to refresh every instance. A slot registered with a `cacheKey` can
922
+ * only be matched on those declared fields, since its output depends on
923
+ * nothing else.
924
+ * @param {string} name
925
+ * @param {{ keys?: Record<string, string>[] }} [options]
926
+ * @returns {Promise<void>}
927
+ */
480
928
  refreshSlot(name, options = {}) {
481
- return hostCall("refreshSlot", { name, keys: options.keys ?? null });
929
+ return /** @type {Promise<void>} */ (
930
+ hostCall("refreshSlot", { name, keys: options.keys ?? null })
931
+ );
482
932
  }
483
933
 
934
+ /**
935
+ * Override in your subclass. Runs after the plugin is loaded and the current user is resolved.
936
+ * @returns {void | Promise<void>}
937
+ */
484
938
  onload() {}
939
+ /**
940
+ * Override in your subclass. Runs when the plugin is being torn down (uninstall/reload).
941
+ * @returns {void | Promise<void>}
942
+ */
485
943
  onunload() {}
486
944
 
945
+ /**
946
+ * Boots the plugin. Call as `MyPlugin.register()` at the top of your plugin's
947
+ * main.js — instantiates the subclass, resolves the current user onto
948
+ * `app.currentUser`, then invokes {@link Plugin.onload}. Idempotent.
949
+ * @returns {void}
950
+ */
487
951
  static register() {
488
952
  if (registered) return;
489
953
  registered = true;
490
954
  const instance = new this();
491
- hostCall("getCurrentUser")
955
+ /** @type {Promise<ProfileView | null>} */ (hostCall("getCurrentUser"))
492
956
  .then((user) => {
493
957
  instance.app.currentUser = user;
494
958
  return instance.onload();
495
959
  })
496
960
  .then(
497
- () => self.postMessage({ type: "ready" }),
961
+ () => post({ type: "ready" }),
498
962
  (error) =>
499
- self.postMessage({
963
+ post({
500
964
  type: "ready",
501
- error: error?.message ?? String(error),
965
+ error: getErrorMessage(error),
502
966
  }),
503
967
  );
504
968
  }
505
969
  }
506
970
 
971
+ /**
972
+ * Extracts a message from a caught value, which need not be an Error.
973
+ * @param {unknown} error
974
+ * @returns {string}
975
+ */
976
+ function getErrorMessage(error) {
977
+ if (error instanceof Error) return error.message;
978
+ if (typeof error === "object" && error !== null && "message" in error) {
979
+ return String(error.message);
980
+ }
981
+ return String(error);
982
+ }
983
+
984
+ /**
985
+ * Names the type of an arbitrary value, for use in an error message.
986
+ * @param {unknown} value
987
+ * @returns {string}
988
+ */
989
+ function describeValue(value) {
990
+ if (value === null) return "null";
991
+ if (typeof value !== "object") return typeof value;
992
+ return value.constructor?.name ?? "object";
993
+ }
994
+
995
+ /**
996
+ * @param {string} name
997
+ * @param {(context: Record<string, string>) => RenderResult | Promise<RenderResult>} callback
998
+ * @param {Record<string, string>} context
999
+ * @returns {Promise<SerializedElement | null>}
1000
+ */
507
1001
  async function getSlotContent(name, callback, context) {
508
- const result = await callback(context);
1002
+ const result = /** @type {unknown} */ (await callback(context));
509
1003
  if (result == null) return null;
510
1004
  if (!(result instanceof VirtualEl)) {
511
- const description = result?.constructor?.name ?? typeof result;
512
1005
  throw new Error(
513
- `Slot "${name}" must return a VirtualEl or null, got ${description}`,
1006
+ `Slot "${name}" must return a VirtualEl or null, got ${describeValue(result)}`,
514
1007
  );
515
1008
  }
516
1009
  return result._serialize();
517
1010
  }
518
1011
 
1012
+ /**
1013
+ * @param {RichTextToken[]} tokens
1014
+ * @returns {SerializedRichTextToken[]}
1015
+ */
519
1016
  function serializeTransformTokens(tokens) {
520
1017
  if (!Array.isArray(tokens)) return tokens;
521
1018
  return tokens.map((token) => {
@@ -529,10 +1026,18 @@ function serializeTransformTokens(tokens) {
529
1026
  });
530
1027
  }
531
1028
 
532
- // Concatenates the renderable text of a token stream into a string with a position map,
533
- // so a transform can pattern-match across token boundaries and map matches back to tokens.
1029
+ /**
1030
+ * Flattens a rich-text token stream into a plain string with a position map,
1031
+ * so a {@link Plugin.registerRichTextTransform | rich-text transform} can
1032
+ * pattern-match (e.g. with a regex) across token boundaries and map matches
1033
+ * back to the original tokens.
1034
+ */
534
1035
  export class FlattenedTokens {
1036
+ /** @type {{ token: RichTextToken, start: number, end: number }[]} */
535
1037
  #segments = [];
1038
+ /**
1039
+ * @param {RichTextToken[]} tokens
1040
+ */
536
1041
  constructor(tokens) {
537
1042
  let text = "";
538
1043
  for (const token of tokens) {
@@ -543,16 +1048,30 @@ export class FlattenedTokens {
543
1048
  if (value != null) text += value;
544
1049
  this.#segments.push({ token, start, end: text.length });
545
1050
  }
1051
+ /** @type {string} */
546
1052
  this.text = text;
547
1053
  }
548
1054
 
549
- // emit an inert range (no facets)
1055
+ /**
1056
+ * Return the plain-text slice for `[start, end)` — inert, with no facets.
1057
+ * @param {number} start
1058
+ * @param {number} end
1059
+ * @returns {string}
1060
+ */
550
1061
  textFor(start, end) {
551
1062
  return this.text.slice(start, end);
552
1063
  }
553
1064
 
554
- // emit a live range, demoting partial facet tokens to text tokens
1065
+ /**
1066
+ * Return the tokens covering `[start, end)`. Facet tokens partially
1067
+ * overlapping the range are demoted to plain text tokens so the emitted
1068
+ * slice never carries a truncated facet.
1069
+ * @param {number} start
1070
+ * @param {number} end
1071
+ * @returns {RichTextToken[]}
1072
+ */
555
1073
  tokensFor(start, end) {
1074
+ /** @type {RichTextToken[]} */
556
1075
  const out = [];
557
1076
  for (const segment of this.#segments) {
558
1077
  if (segment.start === segment.end) {
@@ -575,24 +1094,41 @@ export class FlattenedTokens {
575
1094
  }
576
1095
  }
577
1096
 
1097
+ /**
1098
+ * Convenience wrapper that returns a new {@link FlattenedTokens} for `tokens`.
1099
+ * @param {RichTextToken[]} tokens
1100
+ * @returns {FlattenedTokens}
1101
+ */
578
1102
  export function flattenForScan(tokens) {
579
1103
  return new FlattenedTokens(tokens);
580
1104
  }
581
1105
 
1106
+ /** @type {Map<number, Modal>} */
582
1107
  const openModals = new Map();
583
1108
 
1109
+ /**
1110
+ * A dismissable modal dialog. Subclass and populate `contentEl` and
1111
+ * `titleEl` (both {@link VirtualEl}), typically inside {@link Modal.onOpen}.
1112
+ * Call `open()` to show and `close()` to hide.
1113
+ */
584
1114
  export class Modal {
585
1115
  #modalId = uuid.create();
586
1116
  constructor() {
1117
+ /** @type {VirtualEl} */
587
1118
  this.contentEl = new VirtualEl("div");
1119
+ /** @type {VirtualEl} */
588
1120
  this.titleEl = new VirtualEl("h2");
589
1121
  }
590
1122
 
1123
+ /**
1124
+ * Show the modal. Runs {@link Modal.onOpen} first, then mounts the current el state.
1125
+ * @returns {void}
1126
+ */
591
1127
  open() {
592
1128
  if (openModals.has(this.#modalId)) return;
593
1129
  openModals.set(this.#modalId, this);
594
1130
  this.onOpen();
595
- self.postMessage({
1131
+ post({
596
1132
  type: "hostCall",
597
1133
  method: "openModal",
598
1134
  args: [
@@ -605,9 +1141,13 @@ export class Modal {
605
1141
  });
606
1142
  }
607
1143
 
1144
+ /**
1145
+ * Re-render the open modal from the current `titleEl` / `contentEl` state. No-op if closed.
1146
+ * @returns {void}
1147
+ */
608
1148
  update() {
609
1149
  if (!openModals.has(this.#modalId)) return;
610
- self.postMessage({
1150
+ post({
611
1151
  type: "hostCall",
612
1152
  method: "updateModal",
613
1153
  args: [
@@ -620,10 +1160,14 @@ export class Modal {
620
1160
  });
621
1161
  }
622
1162
 
1163
+ /**
1164
+ * Hide the modal and fire {@link Modal.onClose}.
1165
+ * @returns {void}
1166
+ */
623
1167
  close() {
624
1168
  if (!openModals.has(this.#modalId)) return;
625
1169
  openModals.delete(this.#modalId);
626
- self.postMessage({
1170
+ post({
627
1171
  type: "hostCall",
628
1172
  method: "closeModal",
629
1173
  args: [{ modalId: this.#modalId }],
@@ -631,63 +1175,147 @@ export class Modal {
631
1175
  this.onClose();
632
1176
  }
633
1177
 
1178
+ /**
1179
+ * Lifecycle hook — override to populate `titleEl` / `contentEl` before the modal mounts.
1180
+ * @returns {void}
1181
+ */
634
1182
  onOpen() {}
1183
+ /**
1184
+ * Lifecycle hook — override to react to the modal being dismissed (by `close()` or the user).
1185
+ * @returns {void}
1186
+ */
635
1187
  onClose() {}
636
1188
  }
637
1189
 
1190
+ /**
1191
+ * A tab in the plugin's settings UI. Subclass and override {@link PluginSettingTab.display}
1192
+ * to render into `this.containerEl`. Pass the owning plugin to `super(plugin)`
1193
+ * and register with `plugin.addSettingTab(tab)`.
1194
+ */
638
1195
  export class PluginSettingTab {
639
- constructor() {
1196
+ /**
1197
+ * @param {Plugin} plugin The owning plugin, available as `this.plugin`.
1198
+ */
1199
+ constructor(plugin) {
1200
+ /** @type {Plugin} */
1201
+ this.plugin = plugin;
1202
+ /** @type {VirtualEl} */
640
1203
  this.containerEl = new VirtualEl("div");
1204
+ /** @type {string | null} */
641
1205
  this.name = null;
642
1206
  }
1207
+ /**
1208
+ * Set the tab's label.
1209
+ * @param {string} name
1210
+ * @returns {this}
1211
+ */
643
1212
  setName(name) {
644
1213
  this.name = name;
645
1214
  return this;
646
1215
  }
1216
+ /**
1217
+ * Override to render the tab's contents into `this.containerEl`.
1218
+ * @returns {void}
1219
+ */
647
1220
  display() {}
1221
+ /**
1222
+ * Re-invoke {@link PluginSettingTab.display}. `reset: true` also discards the rendered tree.
1223
+ * @param {{ reset?: boolean }} [options]
1224
+ * @returns {Promise<void>}
1225
+ */
648
1226
  refresh({ reset = false } = {}) {
649
- return hostCall("refreshSettingTab", { reset });
1227
+ return /** @type {Promise<void>} */ (
1228
+ hostCall("refreshSettingTab", { reset })
1229
+ );
650
1230
  }
651
1231
  }
652
1232
 
1233
+ /**
1234
+ * Fluent builder for a single labeled settings row. `new Setting(containerEl)`
1235
+ * appends a row (name + description + control area) to `containerEl` and
1236
+ * returns a builder for populating it.
1237
+ */
653
1238
  export class Setting {
1239
+ /**
1240
+ * @param {VirtualEl} containerEl
1241
+ */
654
1242
  constructor(containerEl) {
1243
+ /** @type {VirtualEl} */
655
1244
  this.settingEl = containerEl.createDiv({ cls: "setting-item" });
1245
+ /** @type {VirtualEl} */
656
1246
  this.infoEl = this.settingEl.createDiv({ cls: "setting-item-info" });
1247
+ /** @type {VirtualEl} */
657
1248
  this.nameEl = this.infoEl.createEl("h2", { cls: "setting-item-name" });
1249
+ /** @type {VirtualEl} */
658
1250
  this.descEl = this.infoEl.createEl("p", { cls: "setting-item-desc" });
1251
+ /** @type {VirtualEl} */
659
1252
  this.controlEl = this.settingEl.createDiv({
660
1253
  cls: "setting-item-control",
661
1254
  });
662
1255
  }
1256
+ /**
1257
+ * Set the row's name/label.
1258
+ * @param {string} text
1259
+ * @returns {this}
1260
+ */
663
1261
  setName(text) {
664
1262
  this.nameEl.setText(text);
665
1263
  return this;
666
1264
  }
1265
+ /**
1266
+ * Set the row's description text below the name.
1267
+ * @param {string} text
1268
+ * @returns {this}
1269
+ */
667
1270
  setDesc(text) {
668
1271
  this.descEl.setText(text);
669
1272
  return this;
670
1273
  }
1274
+ /**
1275
+ * Add a text input; the callback receives a {@link TextComponent}.
1276
+ * @param {(component: TextComponent) => void} callback
1277
+ * @returns {this}
1278
+ */
671
1279
  addText(callback) {
672
1280
  const component = new TextComponent(this.controlEl);
673
1281
  callback(component);
674
1282
  return this;
675
1283
  }
1284
+ /**
1285
+ * Add a multi-line text input; the callback receives a {@link TextAreaComponent}.
1286
+ * @param {(component: TextAreaComponent) => void} callback
1287
+ * @returns {this}
1288
+ */
676
1289
  addTextArea(callback) {
677
1290
  const component = new TextAreaComponent(this.controlEl);
678
1291
  callback(component);
679
1292
  return this;
680
1293
  }
1294
+ /**
1295
+ * Add a toggle switch; the callback receives a {@link ToggleComponent}.
1296
+ * @param {(component: ToggleComponent) => void} callback
1297
+ * @returns {this}
1298
+ */
681
1299
  addToggle(callback) {
682
1300
  const component = new ToggleComponent(this.controlEl);
683
1301
  callback(component);
684
1302
  return this;
685
1303
  }
1304
+ /**
1305
+ * Add a dropdown; the callback receives a {@link DropdownComponent}.
1306
+ * @param {(component: DropdownComponent) => void} callback
1307
+ * @returns {this}
1308
+ */
686
1309
  addDropdown(callback) {
687
1310
  const component = new DropdownComponent(this.controlEl);
688
1311
  callback(component);
689
1312
  return this;
690
1313
  }
1314
+ /**
1315
+ * Add a button; the callback receives a {@link ButtonComponent}.
1316
+ * @param {(component: ButtonComponent) => void} callback
1317
+ * @returns {this}
1318
+ */
691
1319
  addButton(callback) {
692
1320
  const component = new ButtonComponent(this.controlEl);
693
1321
  callback(component);
@@ -695,212 +1323,421 @@ export class Setting {
695
1323
  }
696
1324
  }
697
1325
 
1326
+ /** Single-line text input, built via {@link Setting.addText}. */
698
1327
  export class TextComponent {
699
- /** @internal */
1328
+ /**
1329
+ * @internal
1330
+ * @param {VirtualEl} containerEl
1331
+ */
700
1332
  constructor(containerEl) {
1333
+ /** @type {VirtualEl} */
701
1334
  this.el = containerEl.createEl("input", {
702
1335
  attr: { type: "text" },
703
1336
  cls: "setting-item-text-input",
704
1337
  });
705
1338
  }
1339
+ /**
1340
+ * Set the current value.
1341
+ * @param {string | null} value
1342
+ * @returns {this}
1343
+ */
706
1344
  setValue(value) {
707
1345
  this.el.setAttr("value", value == null ? "" : String(value));
708
1346
  return this;
709
1347
  }
1348
+ /**
1349
+ * Set the placeholder text shown when the input is empty.
1350
+ * @param {string} value
1351
+ * @returns {this}
1352
+ */
710
1353
  setPlaceholder(value) {
711
1354
  this.el.setAttr("placeholder", value);
712
1355
  return this;
713
1356
  }
1357
+ /**
1358
+ * Fires with the new string value on every change.
1359
+ * @param {(value: string) => void} callback
1360
+ * @returns {this}
1361
+ */
714
1362
  onChange(callback) {
715
- this.el.onChange((event) => callback(event.target.value));
1363
+ this.el.onChange((event) => callback(event.target.value ?? ""));
716
1364
  return this;
717
1365
  }
718
1366
  }
719
1367
 
1368
+ /** Multi-line text input, built via {@link Setting.addTextArea}. */
720
1369
  export class TextAreaComponent {
721
- /** @internal */
1370
+ /**
1371
+ * @internal
1372
+ * @param {VirtualEl} containerEl
1373
+ */
722
1374
  constructor(containerEl) {
1375
+ /** @type {VirtualEl} */
723
1376
  this.el = containerEl.createEl("textarea", {
724
1377
  cls: "setting-item-textarea",
725
1378
  });
726
1379
  }
1380
+ /**
1381
+ * Set the current value.
1382
+ * @param {string | null} value
1383
+ * @returns {this}
1384
+ */
727
1385
  setValue(value) {
728
1386
  this.el.setText(value == null ? "" : String(value));
729
1387
  return this;
730
1388
  }
1389
+ /**
1390
+ * Set the placeholder text shown when the input is empty.
1391
+ * @param {string} value
1392
+ * @returns {this}
1393
+ */
731
1394
  setPlaceholder(value) {
732
1395
  this.el.setAttr("placeholder", value);
733
1396
  return this;
734
1397
  }
1398
+ /**
1399
+ * Fires with the new string value on every change.
1400
+ * @param {(value: string) => void} callback
1401
+ * @returns {this}
1402
+ */
735
1403
  onChange(callback) {
736
- this.el.onChange((event) => callback(event.target.value));
1404
+ this.el.onChange((event) => callback(event.target.value ?? ""));
737
1405
  return this;
738
1406
  }
739
1407
  }
740
1408
 
1409
+ /** On/off toggle switch, built via {@link Setting.addToggle}. */
741
1410
  export class ToggleComponent {
742
- /** @internal */
1411
+ /**
1412
+ * @internal
1413
+ * @param {VirtualEl} containerEl
1414
+ */
743
1415
  constructor(containerEl) {
1416
+ /** @type {VirtualEl} */
744
1417
  this.el = containerEl.createEl("toggle-switch", {
745
1418
  cls: "setting-item-toggle",
746
1419
  });
747
1420
  }
1421
+ /**
1422
+ * Set the checked state.
1423
+ * @param {boolean} value
1424
+ * @returns {this}
1425
+ */
748
1426
  setValue(value) {
749
1427
  if (value) this.el.setAttr("checked", "");
750
1428
  else delete this.el.attrs.checked;
751
1429
  return this;
752
1430
  }
1431
+ /**
1432
+ * Fires with the new boolean value on every change.
1433
+ * @param {(checked: boolean) => void} callback
1434
+ * @returns {this}
1435
+ */
753
1436
  onChange(callback) {
754
- this.el.onChange((event) => callback(event.target.checked));
1437
+ this.el.onChange((event) => callback(event.target.checked ?? false));
755
1438
  return this;
756
1439
  }
757
1440
  }
758
1441
 
1442
+ /** Single-select dropdown, built via {@link Setting.addDropdown}. */
759
1443
  export class DropdownComponent {
760
- /** @internal */
1444
+ /**
1445
+ * @internal
1446
+ * @param {VirtualEl} containerEl
1447
+ */
761
1448
  constructor(containerEl) {
1449
+ /** @type {VirtualEl} */
762
1450
  this.el = containerEl.createEl("select", {
763
1451
  cls: "setting-item-dropdown",
764
1452
  });
765
1453
  }
1454
+ /**
1455
+ * Append one option.
1456
+ * @param {string} value
1457
+ * @param {string} label
1458
+ * @returns {this}
1459
+ */
766
1460
  addOption(value, label) {
767
1461
  this.el.createEl("option", { text: label, attr: { value } });
768
1462
  return this;
769
1463
  }
1464
+ /**
1465
+ * Append every `{ value: label }` entry as an option.
1466
+ * @param {Record<string, string>} map
1467
+ * @returns {this}
1468
+ */
770
1469
  addOptions(map) {
771
1470
  for (const [value, label] of Object.entries(map)) {
772
1471
  this.addOption(value, label);
773
1472
  }
774
1473
  return this;
775
1474
  }
1475
+ /**
1476
+ * Select the option whose value matches.
1477
+ * @param {string} value
1478
+ * @returns {this}
1479
+ */
776
1480
  setValue(value) {
777
1481
  for (const child of this.el.children) {
778
- if (child.attrs?.value === value) {
1482
+ if (!(child instanceof VirtualEl)) continue;
1483
+ if (child.attrs.value === value) {
779
1484
  child.attrs.selected = "";
780
- } else if (child.attrs) {
1485
+ } else {
781
1486
  delete child.attrs.selected;
782
1487
  }
783
1488
  }
784
1489
  return this;
785
1490
  }
1491
+ /**
1492
+ * Fires with the newly selected value on every change.
1493
+ * @param {(value: string) => void} callback
1494
+ * @returns {this}
1495
+ */
786
1496
  onChange(callback) {
787
- this.el.onChange((event) => callback(event.target.value));
1497
+ this.el.onChange((event) => callback(event.target.value ?? ""));
788
1498
  return this;
789
1499
  }
790
1500
  }
791
1501
 
1502
+ /** Clickable button, built via {@link Setting.addButton}. */
792
1503
  export class ButtonComponent {
793
- /** @internal */
1504
+ /**
1505
+ * @internal
1506
+ * @param {VirtualEl} containerEl
1507
+ */
794
1508
  constructor(containerEl) {
1509
+ /** @type {VirtualEl} */
795
1510
  this.el = containerEl.createEl("button", {
796
1511
  cls: "rounded-button",
797
1512
  });
798
1513
  }
1514
+ /**
1515
+ * Set the button's label.
1516
+ * @param {string} text
1517
+ * @returns {this}
1518
+ */
799
1519
  setButtonText(text) {
800
1520
  this.el.setText(text);
801
1521
  return this;
802
1522
  }
1523
+ /**
1524
+ * Style the button as the row's primary call-to-action.
1525
+ * @returns {this}
1526
+ */
803
1527
  setCta() {
804
1528
  this.el.addClass("rounded-button-primary");
805
1529
  return this;
806
1530
  }
1531
+ /**
1532
+ * Register a click handler.
1533
+ * @param {() => void} callback
1534
+ * @returns {this}
1535
+ */
807
1536
  onClick(callback) {
808
1537
  this.el.onClick(callback);
809
1538
  return this;
810
1539
  }
811
1540
  }
812
1541
 
1542
+ /** Renders a host-provided icon by name. Built via {@link VirtualEl.createIcon}. */
813
1543
  export class IconComponent {
814
- /** @internal */
1544
+ /**
1545
+ * @internal
1546
+ * @param {VirtualEl} containerEl
1547
+ */
815
1548
  constructor(containerEl) {
1549
+ /** @type {VirtualEl} */
816
1550
  this.el = containerEl.createEl("plugin-icon");
817
1551
  }
1552
+ /**
1553
+ * Set the icon name.
1554
+ * @param {string} name
1555
+ * @returns {this}
1556
+ */
818
1557
  setIcon(name) {
819
1558
  this.el.setAttr("icon", name);
820
1559
  return this;
821
1560
  }
822
1561
  }
823
1562
 
1563
+ /**
1564
+ * Renders a repo blob (by owning DID + blob CID) as an image. Built via
1565
+ * {@link VirtualEl.createBlobImage}.
1566
+ */
824
1567
  export class BlobImageComponent {
825
- /** @internal */
1568
+ /**
1569
+ * @internal
1570
+ * @param {VirtualEl} containerEl
1571
+ */
826
1572
  constructor(containerEl) {
1573
+ /** @type {VirtualEl} */
827
1574
  this.el = containerEl.createEl("plugin-blob-image");
828
1575
  }
1576
+ /**
1577
+ * DID of the repo the blob belongs to.
1578
+ * @param {string} did
1579
+ * @returns {this}
1580
+ */
829
1581
  setDid(did) {
830
1582
  this.el.setAttr("did", did);
831
1583
  return this;
832
1584
  }
1585
+ /**
1586
+ * CID of the blob to render.
1587
+ * @param {string} cid
1588
+ * @returns {this}
1589
+ */
833
1590
  setCid(cid) {
834
1591
  this.el.setAttr("cid", cid);
835
1592
  return this;
836
1593
  }
1594
+ /**
1595
+ * Set the image's alt text.
1596
+ * @param {string} alt
1597
+ * @returns {this}
1598
+ */
837
1599
  setAlt(alt) {
838
1600
  this.el.setAttr("alt", alt);
839
1601
  return this;
840
1602
  }
1603
+ /**
1604
+ * Override the CDN URL prefix used to fetch the blob.
1605
+ * @param {string} prefix
1606
+ * @returns {this}
1607
+ */
841
1608
  setCdnPrefix(prefix) {
842
1609
  this.el.setAttr("cdn-prefix", prefix);
843
1610
  return this;
844
1611
  }
845
1612
  }
846
1613
 
1614
+ /**
1615
+ * Renders a list of profiles from an array of DIDs, hydrated by the host.
1616
+ * Built via {@link VirtualEl.createProfilesList}.
1617
+ */
847
1618
  export class ProfilesListComponent {
848
- /** @internal */
1619
+ /**
1620
+ * @internal
1621
+ * @param {VirtualEl} containerEl
1622
+ */
849
1623
  constructor(containerEl) {
1624
+ /** @type {VirtualEl} */
850
1625
  this.el = containerEl.createEl("plugin-profiles-list");
851
1626
  }
1627
+ /**
1628
+ * Set the DIDs to render (array or comma-separated string).
1629
+ * @param {string[] | string} dids
1630
+ * @returns {this}
1631
+ */
852
1632
  setDids(dids) {
853
1633
  const value = Array.isArray(dids) ? dids.join(",") : String(dids ?? "");
854
1634
  this.el.setAttr("dids", value);
855
1635
  return this;
856
1636
  }
1637
+ /**
1638
+ * Message shown when the list is empty.
1639
+ * @param {string} message
1640
+ * @returns {this}
1641
+ */
857
1642
  setEmptyMessage(message) {
858
1643
  this.el.setAttr("empty-message", message);
859
1644
  return this;
860
1645
  }
861
1646
  }
862
1647
 
1648
+ /**
1649
+ * Renders a feed of posts from an array of post URIs, hydrated by the host.
1650
+ * Built via {@link VirtualEl.createPostsFeed}.
1651
+ */
863
1652
  export class PostsFeedComponent {
864
- /** @internal */
1653
+ /**
1654
+ * @internal
1655
+ * @param {VirtualEl} containerEl
1656
+ */
865
1657
  constructor(containerEl) {
1658
+ /** @type {VirtualEl} */
866
1659
  this.el = containerEl.createEl("plugin-posts-feed");
867
1660
  }
1661
+ /**
1662
+ * Set the post URIs to render (array or comma-separated string).
1663
+ * @param {string[] | string} uris
1664
+ * @returns {this}
1665
+ */
868
1666
  setUris(uris) {
869
1667
  const value = Array.isArray(uris) ? uris.join(",") : String(uris ?? "");
870
1668
  this.el.setAttr("uris", value);
871
1669
  return this;
872
1670
  }
1671
+ /**
1672
+ * Message shown when the feed is empty.
1673
+ * @param {string} message
1674
+ * @returns {this}
1675
+ */
873
1676
  setEmptyMessage(message) {
874
1677
  this.el.setAttr("empty-message", message);
875
1678
  return this;
876
1679
  }
877
1680
  }
878
1681
 
1682
+ /**
1683
+ * A text node in a {@link VirtualEl} tree. Null/undefined coerce to `""`.
1684
+ */
879
1685
  export class VirtualText {
1686
+ /**
1687
+ * @param {string | null | undefined} value
1688
+ */
880
1689
  constructor(value) {
1690
+ /** @type {string} */
881
1691
  this.value = value == null ? "" : String(value);
882
1692
  }
883
1693
 
884
- /** @internal */
1694
+ /**
1695
+ * @internal
1696
+ * @returns {SerializedText}
1697
+ */
885
1698
  _serialize() {
886
1699
  return { type: "text", value: this.value };
887
1700
  }
888
1701
  }
889
1702
 
1703
+ /**
1704
+ * Minimal DOM-builder node. Plugins run in a sandbox and cannot touch the real
1705
+ * DOM directly; instead they build a serializable {@link VirtualEl} tree that
1706
+ * the host renders and reconciles.
1707
+ */
890
1708
  export class VirtualEl {
1709
+ /**
1710
+ * @param {string} tag
1711
+ */
891
1712
  constructor(tag) {
1713
+ /** @type {string} */
892
1714
  this.tag = tag;
1715
+ /** @type {Record<string, string>} */
893
1716
  this.attrs = {};
1717
+ /** @type {Record<string, string>} */
894
1718
  this.styles = {};
1719
+ /** @type {(VirtualEl | VirtualText)[]} */
895
1720
  this.children = [];
1721
+ /** @type {Record<string, number>} */
896
1722
  this.events = {};
897
1723
  }
898
1724
 
1725
+ /**
1726
+ * Set an inline style.
1727
+ * @param {string} name
1728
+ * @param {string | null} value
1729
+ * @returns {this}
1730
+ */
899
1731
  setStyle(name, value) {
900
1732
  this.styles[String(name)] = value == null ? "" : String(value);
901
1733
  return this;
902
1734
  }
903
1735
 
1736
+ /**
1737
+ * Register a click handler.
1738
+ * @param {(event?: object) => void} fn
1739
+ * @returns {this}
1740
+ */
904
1741
  onClick(fn) {
905
1742
  const handlerId = uuid.create();
906
1743
  callHandlers.set(handlerId, fn);
@@ -908,6 +1745,11 @@ export class VirtualEl {
908
1745
  return this;
909
1746
  }
910
1747
 
1748
+ /**
1749
+ * Register a change handler (form controls).
1750
+ * @param {(event: { target: { value?: string, checked?: boolean } }) => void} fn
1751
+ * @returns {this}
1752
+ */
911
1753
  onChange(fn) {
912
1754
  const handlerId = uuid.create();
913
1755
  callHandlers.set(handlerId, fn);
@@ -915,6 +1757,11 @@ export class VirtualEl {
915
1757
  return this;
916
1758
  }
917
1759
 
1760
+ /**
1761
+ * Register an input handler (text inputs).
1762
+ * @param {(event: { target: { value?: string } }) => void} fn
1763
+ * @returns {this}
1764
+ */
918
1765
  onInput(fn) {
919
1766
  const handlerId = uuid.create();
920
1767
  callHandlers.set(handlerId, fn);
@@ -922,17 +1769,31 @@ export class VirtualEl {
922
1769
  return this;
923
1770
  }
924
1771
 
1772
+ /**
1773
+ * Replace all children with a single {@link VirtualText} node.
1774
+ * @param {string | null} text
1775
+ * @returns {this}
1776
+ */
925
1777
  setText(text) {
926
1778
  this.children = [];
927
1779
  if (text != null && text !== "") this.children.push(new VirtualText(text));
928
1780
  return this;
929
1781
  }
930
1782
 
1783
+ /**
1784
+ * Remove all children.
1785
+ * @returns {this}
1786
+ */
931
1787
  empty() {
932
1788
  this.children = [];
933
1789
  return this;
934
1790
  }
935
1791
 
1792
+ /**
1793
+ * Append a {@link VirtualEl} or {@link VirtualText}; throws on anything else.
1794
+ * @param {VirtualEl | VirtualText} child
1795
+ * @returns {this}
1796
+ */
936
1797
  appendChild(child) {
937
1798
  if (!(child instanceof VirtualEl) && !(child instanceof VirtualText)) {
938
1799
  throw new TypeError(
@@ -943,27 +1804,57 @@ export class VirtualEl {
943
1804
  return this;
944
1805
  }
945
1806
 
1807
+ /**
1808
+ * Append a {@link VirtualText} child.
1809
+ * @param {string} value
1810
+ * @returns {this}
1811
+ */
946
1812
  appendText(value) {
947
1813
  this.children.push(new VirtualText(value));
948
1814
  return this;
949
1815
  }
950
1816
 
1817
+ /**
1818
+ * Append and return a {@link VirtualText} child.
1819
+ * @param {string} value
1820
+ * @returns {VirtualText}
1821
+ */
951
1822
  createText(value) {
952
1823
  const node = new VirtualText(value);
953
1824
  this.children.push(node);
954
1825
  return node;
955
1826
  }
956
1827
 
1828
+ /**
1829
+ * Add a CSS class, whitespace-joined with any existing classes.
1830
+ * @param {string} cls
1831
+ * @returns {this}
1832
+ */
957
1833
  addClass(cls) {
958
1834
  this.attrs.class = this.attrs.class ? `${this.attrs.class} ${cls}` : cls;
959
1835
  return this;
960
1836
  }
961
1837
 
1838
+ /**
1839
+ * Set an attribute; `undefined` coerces to `""`.
1840
+ * @param {string} name
1841
+ * @param {string | undefined} value
1842
+ * @returns {this}
1843
+ */
962
1844
  setAttr(name, value) {
963
1845
  this.attrs[name] = value === undefined ? "" : value;
964
1846
  return this;
965
1847
  }
966
1848
 
1849
+ /**
1850
+ * Append a child element and return it. `options` accepts `text`,
1851
+ * `cls` (string or string[]), and `attr` (object). The optional callback
1852
+ * receives the new child for further building.
1853
+ * @param {string} tag
1854
+ * @param {{ text?: string, cls?: string | string[], attr?: Record<string, string> }} [options]
1855
+ * @param {(child: VirtualEl) => void} [callback]
1856
+ * @returns {VirtualEl}
1857
+ */
967
1858
  createEl(tag, options = {}, callback) {
968
1859
  const child = new VirtualEl(tag);
969
1860
  if (options.text != null) child.setText(options.text);
@@ -978,40 +1869,76 @@ export class VirtualEl {
978
1869
  return child;
979
1870
  }
980
1871
 
1872
+ /**
1873
+ * Shorthand for `createEl("div", ...)`.
1874
+ * @param {{ text?: string, cls?: string | string[], attr?: Record<string, string> }} [options]
1875
+ * @param {(child: VirtualEl) => void} [callback]
1876
+ * @returns {VirtualEl}
1877
+ */
981
1878
  createDiv(options = {}, callback) {
982
1879
  return this.createEl("div", options, callback);
983
1880
  }
984
1881
 
1882
+ /**
1883
+ * Shorthand for `createEl("span", ...)`.
1884
+ * @param {{ text?: string, cls?: string | string[], attr?: Record<string, string> }} [options]
1885
+ * @param {(child: VirtualEl) => void} [callback]
1886
+ * @returns {VirtualEl}
1887
+ */
985
1888
  createSpan(options = {}, callback) {
986
1889
  return this.createEl("span", options, callback);
987
1890
  }
988
1891
 
1892
+ /**
1893
+ * Append a profiles-list custom component and return its builder.
1894
+ * @param {(c: ProfilesListComponent) => void} [callback]
1895
+ * @returns {ProfilesListComponent}
1896
+ */
989
1897
  createProfilesList(callback) {
990
1898
  const component = new ProfilesListComponent(this);
991
1899
  if (typeof callback === "function") callback(component);
992
1900
  return component;
993
1901
  }
994
1902
 
1903
+ /**
1904
+ * Append a posts-feed custom component and return its builder.
1905
+ * @param {(c: PostsFeedComponent) => void} [callback]
1906
+ * @returns {PostsFeedComponent}
1907
+ */
995
1908
  createPostsFeed(callback) {
996
1909
  const component = new PostsFeedComponent(this);
997
1910
  if (typeof callback === "function") callback(component);
998
1911
  return component;
999
1912
  }
1000
1913
 
1914
+ /**
1915
+ * Append an icon custom component and return its builder.
1916
+ * @param {(c: IconComponent) => void} [callback]
1917
+ * @returns {IconComponent}
1918
+ */
1001
1919
  createIcon(callback) {
1002
1920
  const component = new IconComponent(this);
1003
1921
  if (typeof callback === "function") callback(component);
1004
1922
  return component;
1005
1923
  }
1006
1924
 
1925
+ /**
1926
+ * Append a blob-image custom component and return its builder.
1927
+ * @param {(c: BlobImageComponent) => void} [callback]
1928
+ * @returns {BlobImageComponent}
1929
+ */
1007
1930
  createBlobImage(callback) {
1008
1931
  const component = new BlobImageComponent(this);
1009
1932
  if (typeof callback === "function") callback(component);
1010
1933
  return component;
1011
1934
  }
1012
1935
 
1013
- /** @internal */
1936
+ /**
1937
+ * @internal
1938
+ * @returns {SerializedElement}
1939
+ */
1014
1940
  _serialize() {
1941
+ /** @type {SerializedElement} */
1015
1942
  const serialized = {
1016
1943
  type: "element",
1017
1944
  tag: this.tag,
@@ -1024,7 +1951,63 @@ export class VirtualEl {
1024
1951
  }
1025
1952
  }
1026
1953
 
1954
+ /**
1955
+ * @typedef {{ type: "text", value: string }} SerializedText
1956
+ * {@internal} The wire format of a {@link VirtualText} node.
1957
+ * @typedef {{ type: "element", tag: string, attrs: Record<string, string>, events: Record<string, number>, children: SerializedNode[], styles?: Record<string, string> }} SerializedElement
1958
+ * {@internal} The wire format of a {@link VirtualEl} node.
1959
+ * @typedef {SerializedText | SerializedElement} SerializedNode
1960
+ * {@internal} One node of the serialized tree the host renders and reconciles.
1961
+ * @typedef {{ [key: string]: Cloneable }} CloneableObject
1962
+ * An object whose values are all {@link Cloneable}.
1963
+ * @typedef {Cloneable[]} CloneableArray
1964
+ * An array of {@link Cloneable} values.
1965
+ * @typedef {null | undefined | boolean | number | string | CloneableArray | CloneableObject} Cloneable
1966
+ * JSON-shaped data — the only thing that can cross between a plugin and the
1967
+ * host. Functions, class instances, `Date`, `Map` and friends cannot.
1968
+ * @typedef {{ type: "register", target: "eventListener", event: string, handlerId: number }} RegisterEventListenerMessage
1969
+ * {@internal}
1970
+ * @typedef {{ type: "register", target: "sidebarItem", icon: string | SerializedElement, title: string, handlerId: number }} RegisterSidebarItemMessage
1971
+ * {@internal}
1972
+ * @typedef {{ type: "register", target: "settingTab", name: string | null, displayHandlerId: number }} RegisterSettingTabMessage
1973
+ * {@internal}
1974
+ * @typedef {{ type: "register", target: "feedFilter", handlerId: number }} RegisterFeedFilterMessage
1975
+ * {@internal}
1976
+ * @typedef {{ type: "register", target: "richTextTransform", handlerId: number, handlesFacetTypes: string[] }} RegisterRichTextTransformMessage
1977
+ * {@internal}
1978
+ * @typedef {{ type: "register", target: "slot", name: string, handlerId: number, cacheKey: string[] | null, batch: true }} RegisterSlotMessage
1979
+ * {@internal}
1980
+ * @typedef {{ type: "register", target: "page", id: string, title: string | null, displayHandlerId: number }} RegisterPageMessage
1981
+ * {@internal}
1982
+ * @typedef {RegisterEventListenerMessage | RegisterSidebarItemMessage | RegisterSettingTabMessage | RegisterFeedFilterMessage | RegisterRichTextTransformMessage | RegisterSlotMessage | RegisterPageMessage} RegisterMessage
1983
+ * {@internal} Announces an extension point this plugin provides.
1984
+ * @typedef {{ type: "hostCall", method: string, hostCallId?: number, args: Cloneable[] }} HostCallRequestMessage
1985
+ * {@internal} Calls a host method. Without a `hostCallId` it is fire-and-forget.
1986
+ * @typedef {{ type: "result", callId: number, value?: unknown, error?: string }} CallResultMessage
1987
+ * {@internal} Answers a {@link HostCallMessage}.
1988
+ * @typedef {{ type: "ready", error?: string }} ReadyMessage
1989
+ * {@internal} Reports the outcome of plugin load.
1990
+ * @typedef {RegisterMessage | HostCallRequestMessage | CallResultMessage | ReadyMessage} WorkerMessage
1991
+ * {@internal} Anything this worker may post to the host.
1992
+ * @typedef {{ type: "call", callId: number, handlerId: number, args: Cloneable[] }} HostCallMessage
1993
+ * {@internal} The host invoking a handler this worker registered.
1994
+ * @typedef {{ type: "hostResult", hostCallId: number, value?: Cloneable, error?: string }} HostResultMessage
1995
+ * {@internal} The host answering a {@link hostCall}.
1996
+ * @typedef {{ type: "event", event: "modalDismissed", data: { modalId: number } }} HostEventMessage
1997
+ * {@internal} An out-of-band notification from the host.
1998
+ * @typedef {HostCallMessage | HostResultMessage | HostEventMessage} HostMessage
1999
+ * {@internal} Anything the host may post to this worker.
2000
+ * @typedef {{ status: number, ok: boolean, headers: Record<string, string>, body: string }} SerializedFetchResponse
2001
+ * {@internal} The host's reply to a proxied {@link fetch}.
2002
+ * @typedef {{ method?: string, headers?: Record<string, string>, body?: string }} SerializedFetchInit
2003
+ * {@internal} A {@link PluginFetchInit} with its headers flattened for transfer.
2004
+ * @typedef {Record<string, unknown>} SerializedRichTextToken
2005
+ * {@internal} A {@link RichTextToken} whose `inline`/`block` node, if any, has
2006
+ * been replaced by its serialized form.
2007
+ */
2008
+
1027
2009
  self.onmessage = async (event) => {
2010
+ /** @type {HostMessage} */
1028
2011
  const message = event.data;
1029
2012
  if (!message || typeof message !== "object") return;
1030
2013
 
@@ -1032,7 +2015,7 @@ self.onmessage = async (event) => {
1032
2015
  if (message.type === "call") {
1033
2016
  const fn = callHandlers.get(message.handlerId);
1034
2017
  if (!fn) {
1035
- self.postMessage({
2018
+ post({
1036
2019
  type: "result",
1037
2020
  callId: message.callId,
1038
2021
  error: `unknown handler ${message.handlerId}`,
@@ -1041,12 +2024,12 @@ self.onmessage = async (event) => {
1041
2024
  }
1042
2025
  try {
1043
2026
  const value = await fn(...message.args);
1044
- self.postMessage({ type: "result", callId: message.callId, value });
2027
+ post({ type: "result", callId: message.callId, value });
1045
2028
  } catch (error) {
1046
- self.postMessage({
2029
+ post({
1047
2030
  type: "result",
1048
2031
  callId: message.callId,
1049
- error: error.message ?? String(error),
2032
+ error: getErrorMessage(error),
1050
2033
  });
1051
2034
  }
1052
2035
  return;
@@ -1074,6 +2057,5 @@ self.onmessage = async (event) => {
1074
2057
  return;
1075
2058
  }
1076
2059
  }
1077
- return;
1078
2060
  }
1079
2061
  };