@impro.social/impro-plugin 0.0.21 → 0.0.23

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 +1448 -0
  2. package/main.js +339 -76
  3. package/package.json +10 -4
package/main.js CHANGED
@@ -9,10 +9,36 @@
9
9
  * Paginated response from `getKnownFollowers`: `{ followers, cursor }`.
10
10
  * @typedef {Record<string, unknown>} RepoRecord
11
11
  * A raw repo record: `{ uri, cid, value }`.
12
+ * @typedef {{ did: string, collection: string, rkey: string }} BacklinkRecord
13
+ * A record that links to a queried subject.
12
14
  * @typedef {Record<string, unknown>} FeedItem
13
15
  * A `app.bsky.feed.defs#feedViewPost` (post + reply/repost context).
14
- * @typedef {Record<string, unknown>} RichTextToken
16
+ * @typedef {{ $type: string } & Record<string, unknown>} RichTextFacetFeature
17
+ * One feature of a facet; fields beyond `$type` vary by service.
18
+ * @typedef {{ index: { byteStart: number, byteEnd: number }, features?: RichTextFacetFeature[] }} RichTextFacet
19
+ * An `app.bsky.richtext.facet` — a byte range plus the features applying to it.
20
+ * @typedef {{ type: "text", value: string }} RichTextTextToken
21
+ * A run of plain text.
22
+ * @typedef {{ type: "facet", facet: RichTextFacet, text: string }} RichTextFacetToken
23
+ * The text covered by one facet; the host restores the original facet payload.
24
+ * @typedef {{ type: "inline" | "block", node: VirtualEl | Record<string, unknown>, pluginId?: string }} RichTextNodeToken
25
+ * Custom content the plugin renders itself — `block` on its own line, `inline` in the text flow.
26
+ * @typedef {RichTextTextToken | RichTextFacetToken | RichTextNodeToken} RichTextToken
15
27
  * One token in a rich-text stream — `text`, `facet`, `inline`, or `block`.
28
+ * @typedef {Record<string, string> | Headers | Map<string, string> | Iterable<[string, string], void, undefined>} PluginFetchHeaders
29
+ * Any header collection {@link fetch} accepts — read structurally, not by class.
30
+ * @typedef {{ method?: string, headers?: PluginFetchHeaders, body?: string }} PluginFetchInit
31
+ * Options for {@link fetch} — a subset of `RequestInit` the host proxy supports.
32
+ * @typedef {{ feedGenerator: Record<string, unknown> | null, feedContext: string | null, feedProxyUrl: string | null }} PostContextMenuMeta
33
+ * Where a post was seen, passed to `post-context-menu` listeners.
34
+ * @typedef {{ kind: "post" | "reply" | "quote", replyTo: PostView | null, replyRoot: PostView | null, quotedPost: PostView | null }} PostComposerContext
35
+ * What the composer is being opened for, passed to `post-composer-open` listeners.
36
+ * @typedef {{
37
+ * "post-context-menu": (menu: Menu, post: PostView, meta?: PostContextMenuMeta) => void,
38
+ * "profile-context-menu": (menu: Menu, profile: ProfileView) => void,
39
+ * "post-composer-open": (composer: Composer, context: PostComposerContext) => void,
40
+ * }} PluginEventMap
41
+ * The events {@link Plugin.on} accepts, and the listener each one takes.
16
42
  * @typedef {VirtualEl | null | undefined} RenderResult
17
43
  * What a render callback may return: a tree to render, or nothing.
18
44
  */
@@ -26,21 +52,45 @@ export class SimpleUUID {
26
52
 
27
53
  const uuid = new SimpleUUID();
28
54
 
55
+ /**
56
+ * Posts a message to the host. The only outbound channel, so every message
57
+ * is checked against {@link WorkerMessage}.
58
+ * @param {WorkerMessage} message
59
+ * @returns {void}
60
+ */
61
+ function post(message) {
62
+ self.postMessage(message);
63
+ }
64
+
65
+ /** @type {Map<number, (...args: any[]) => unknown>} */
29
66
  const callHandlers = new Map();
30
67
 
68
+ /** @type {Map<number, { resolve: (value: unknown) => void, reject: (reason: unknown) => void }>} */
31
69
  const pendingHostCalls = new Map();
32
70
 
71
+ /**
72
+ * @param {string} method
73
+ * @param {...Cloneable} args
74
+ * @returns {Promise<unknown>}
75
+ */
33
76
  function hostCall(method, ...args) {
34
77
  const hostCallId = uuid.create();
35
78
  return new Promise((resolve, reject) => {
36
79
  pendingHostCalls.set(hostCallId, { resolve, reject });
37
- self.postMessage({ type: "hostCall", method, hostCallId, args });
80
+ post({ type: "hostCall", method, hostCallId, args });
38
81
  });
39
82
  }
40
83
 
84
+ /** @type {Map<string, Set<(...args: any[]) => unknown>>} */
41
85
  const eventListeners = new Map();
42
86
  const registeredEvents = new Set();
43
87
 
88
+ /**
89
+ * @param {Iterable<(...args: any[]) => unknown>} listeners
90
+ * @param {string} event
91
+ * @param {unknown[]} args
92
+ * @returns {Promise<void>}
93
+ */
44
94
  async function invokeListeners(listeners, event, args) {
45
95
  for (const listener of listeners) {
46
96
  try {
@@ -51,6 +101,11 @@ async function invokeListeners(listeners, event, args) {
51
101
  }
52
102
  }
53
103
 
104
+ /**
105
+ * @param {string} event
106
+ * @param {unknown[]} args
107
+ * @returns {Promise<unknown>}
108
+ */
54
109
  async function dispatchEvent(event, args) {
55
110
  const listeners = eventListeners.get(event) ?? new Set();
56
111
  switch (event) {
@@ -71,6 +126,11 @@ async function dispatchEvent(event, args) {
71
126
  }
72
127
  }
73
128
 
129
+ /**
130
+ * @param {string} event
131
+ * @param {(...args: any[]) => unknown} listener
132
+ * @returns {void}
133
+ */
74
134
  function addEventListener(event, listener) {
75
135
  let listeners = eventListeners.get(event);
76
136
  if (!listeners) {
@@ -83,7 +143,7 @@ function addEventListener(event, listener) {
83
143
  registeredEvents.add(event);
84
144
  const handlerId = uuid.create();
85
145
  callHandlers.set(handlerId, (...args) => dispatchEvent(event, args));
86
- self.postMessage({
146
+ post({
87
147
  type: "register",
88
148
  target: "eventListener",
89
149
  event,
@@ -173,6 +233,7 @@ export class Menu {
173
233
  * all listeners have run. operations from multiple plugins are applied in order.
174
234
  */
175
235
  export class Composer {
236
+ /** @type {{ op: string, text: string }[]} */
176
237
  #ops = [];
177
238
  /** @type {number | null} */
178
239
  #cursor = null;
@@ -229,7 +290,7 @@ export class PluginData {
229
290
  * @returns {Promise<PostView>}
230
291
  */
231
292
  getPost(uri) {
232
- return hostCall("getPost", { uri });
293
+ return /** @type {Promise<PostView>} */ (hostCall("getPost", { uri }));
233
294
  }
234
295
  /**
235
296
  * Fetch the basic profile view for a DID.
@@ -237,7 +298,9 @@ export class PluginData {
237
298
  * @returns {Promise<ProfileView>}
238
299
  */
239
300
  getProfile(did) {
240
- return hostCall("getProfile", { did });
301
+ return /** @type {Promise<ProfileView>} */ (
302
+ hostCall("getProfile", { did })
303
+ );
241
304
  }
242
305
  /**
243
306
  * Like {@link PluginData.getProfile}, but includes viewer relationship
@@ -248,7 +311,9 @@ export class PluginData {
248
311
  * @returns {Promise<DetailedProfileView>}
249
312
  */
250
313
  getDetailedProfile(did) {
251
- return hostCall("getDetailedProfile", { did });
314
+ return /** @type {Promise<DetailedProfileView>} */ (
315
+ hostCall("getDetailedProfile", { did })
316
+ );
252
317
  }
253
318
  /**
254
319
  * The full known-followers list for `did`. The summary on
@@ -258,7 +323,9 @@ export class PluginData {
258
323
  * @returns {Promise<KnownFollowersResponse>}
259
324
  */
260
325
  getKnownFollowers(did) {
261
- return hostCall("getKnownFollowers", { did });
326
+ return /** @type {Promise<KnownFollowersResponse>} */ (
327
+ hostCall("getKnownFollowers", { did })
328
+ );
262
329
  }
263
330
  /**
264
331
  * Fetch a raw repo record by `(repo, collection, rkey)`.
@@ -268,7 +335,27 @@ export class PluginData {
268
335
  * @returns {Promise<RepoRecord>}
269
336
  */
270
337
  getRecord(repo, collection, rkey) {
271
- return hostCall("getRecord", { repo, collection, rkey });
338
+ return /** @type {Promise<RepoRecord>} */ (
339
+ hostCall("getRecord", { repo, collection, rkey })
340
+ );
341
+ }
342
+ /**
343
+ * Get records that link to `subject`, from a backlink
344
+ * index of public records.
345
+ *
346
+ * `subject` is an AT-URI or a DID; `source` names the linking field as
347
+ * `<collection>:<dot.path.to.field>` (e.g.
348
+ * `"app.bsky.graph.listitem:list"`). The host paginates for you, up to
349
+ * `limit` records (max 1000 per call — page by making further calls
350
+ * with a narrower subject).
351
+ *
352
+ * @param {{ subject: string, source: string, limit?: number }} params
353
+ * @returns {Promise<BacklinkRecord[]>}
354
+ */
355
+ getBacklinks({ subject, source, limit = 100 }) {
356
+ return /** @type {Promise<BacklinkRecord[]>} */ (
357
+ hostCall("getBacklinks", { subject, source, limit })
358
+ );
272
359
  }
273
360
  }
274
361
 
@@ -299,9 +386,11 @@ export class App {
299
386
  * - `"post-composer-open"` — `(composer: Composer, context: { kind, replyTo, replyRoot, quotedPost }) => void`,
300
387
  * called when the post composer opens; use `composer` to seed text.
301
388
  *
302
- * The `listener` signature varies per event (see above).
303
- * @param {string} event
304
- * @param {Function} listener
389
+ * The `listener` signature varies per event — see {@link PluginEventMap}.
390
+ * @template {keyof PluginEventMap} K
391
+ * @param {K} event
392
+ * @param {PluginEventMap[K]} listener
393
+ * @returns {void}
305
394
  */
306
395
  on(event, listener) {
307
396
  addEventListener(event, listener);
@@ -314,7 +403,9 @@ export class App {
314
403
  * @returns {Promise<void>}
315
404
  */
316
405
  refreshFeedFilters(feedURI = null) {
317
- return hostCall("refreshFeedFilters", feedURI);
406
+ return /** @type {Promise<void>} */ (
407
+ hostCall("refreshFeedFilters", feedURI)
408
+ );
318
409
  }
319
410
 
320
411
  /**
@@ -324,7 +415,9 @@ export class App {
324
415
  * @returns {Promise<void>}
325
416
  */
326
417
  muteActor(did) {
327
- return hostCall("muteActor", { did, mute: true });
418
+ return /** @type {Promise<void>} */ (
419
+ hostCall("muteActor", { did, mute: true })
420
+ );
328
421
  }
329
422
  /**
330
423
  * Unmute an actor. Requires the `"mute"` scope.
@@ -332,7 +425,9 @@ export class App {
332
425
  * @returns {Promise<void>}
333
426
  */
334
427
  unmuteActor(did) {
335
- return hostCall("muteActor", { did, mute: false });
428
+ return /** @type {Promise<void>} */ (
429
+ hostCall("muteActor", { did, mute: false })
430
+ );
336
431
  }
337
432
  /**
338
433
  * Block an actor on behalf of the signed-in user. Requires the `"block"`
@@ -341,7 +436,9 @@ export class App {
341
436
  * @returns {Promise<void>}
342
437
  */
343
438
  blockActor(did) {
344
- return hostCall("blockActor", { did, block: true });
439
+ return /** @type {Promise<void>} */ (
440
+ hostCall("blockActor", { did, block: true })
441
+ );
345
442
  }
346
443
  /**
347
444
  * Unblock an actor. Requires the `"block"` scope.
@@ -349,7 +446,9 @@ export class App {
349
446
  * @returns {Promise<void>}
350
447
  */
351
448
  unblockActor(did) {
352
- return hostCall("blockActor", { did, block: false });
449
+ return /** @type {Promise<void>} */ (
450
+ hostCall("blockActor", { did, block: false })
451
+ );
353
452
  }
354
453
  /**
355
454
  * Acts like the user clicking "Show less like this": sends the
@@ -361,7 +460,9 @@ export class App {
361
460
  * @returns {Promise<void>}
362
461
  */
363
462
  showLessLikeThis(postUri, feedUri) {
364
- return hostCall("showLessLikeThis", { postUri, feedUri });
463
+ return /** @type {Promise<void>} */ (
464
+ hostCall("showLessLikeThis", { postUri, feedUri })
465
+ );
365
466
  }
366
467
  /**
367
468
  * Sends the `requestMore` feedback signal to `feedUri` for `postUri`.
@@ -371,7 +472,9 @@ export class App {
371
472
  * @returns {Promise<void>}
372
473
  */
373
474
  showMoreLikeThis(postUri, feedUri) {
374
- return hostCall("showMoreLikeThis", { postUri, feedUri });
475
+ return /** @type {Promise<void>} */ (
476
+ hostCall("showMoreLikeThis", { postUri, feedUri })
477
+ );
375
478
  }
376
479
  }
377
480
 
@@ -382,31 +485,66 @@ export class App {
382
485
  * `[name, value]` iterable), and a string `body`. Resolves to a
383
486
  * {@link PluginResponse}.
384
487
  * @param {string} url
385
- * @param {{ method?: string, headers?: Record<string, string> | Headers | Map<string, string> | Iterable<[string, string], void, undefined>, body?: string }} [init]
488
+ * @param {PluginFetchInit} [init]
386
489
  * @returns {Promise<PluginResponse>}
387
490
  */
388
491
  export async function fetch(url, init = {}) {
389
- const result = await hostCall("fetch", {
390
- url,
391
- init: serializeFetchInit(init),
392
- });
492
+ const result = /** @type {SerializedFetchResponse} */ (
493
+ await hostCall("fetch", { url, init: serializeFetchInit(init) })
494
+ );
393
495
  return new PluginResponse(result);
394
496
  }
395
497
 
498
+ /**
499
+ * @param {unknown} value
500
+ * @returns {value is { forEach: (callback: (value: string, name: string) => void) => void }}
501
+ */
502
+ function hasForEach(value) {
503
+ return (
504
+ typeof value === "object" &&
505
+ value !== null &&
506
+ "forEach" in value &&
507
+ typeof value.forEach === "function"
508
+ );
509
+ }
510
+
511
+ /**
512
+ * @param {unknown} value
513
+ * @returns {value is Iterable<[string, string]>}
514
+ */
515
+ function isEntryIterable(value) {
516
+ return (
517
+ typeof value === "object" &&
518
+ value !== null &&
519
+ Symbol.iterator in value &&
520
+ typeof value[Symbol.iterator] === "function"
521
+ );
522
+ }
523
+
524
+ /**
525
+ * @param {PluginFetchInit} init
526
+ * @returns {SerializedFetchInit}
527
+ */
396
528
  function serializeFetchInit(init) {
529
+ /** @type {SerializedFetchInit} */
397
530
  const serialized = {};
398
531
  if (init.method != null) serialized.method = String(init.method);
399
532
  if (init.headers != null) {
533
+ /** @type {Record<string, string>} */
400
534
  const headers = {};
401
- if (typeof init.headers.forEach === "function") {
402
- // Headers, Map, and similar iterables expose forEach(value, name)
403
- init.headers.forEach((value, name) => {
535
+ // Probed structurally rather than by class, so any forEach-able or
536
+ // iterable header collection works. Iteration is tried first because
537
+ // Headers, Map, arrays and iterators all yield [name, value] pairs,
538
+ // whereas forEach passes (value, index) on an array or iterator.
539
+ const headersInit = init.headers;
540
+ if (isEntryIterable(headersInit)) {
541
+ for (const [name, value] of headersInit) headers[name] = value;
542
+ } else if (hasForEach(headersInit)) {
543
+ headersInit.forEach((value, name) => {
404
544
  headers[name] = value;
405
545
  });
406
- } else if (typeof init.headers[Symbol.iterator] === "function") {
407
- for (const [name, value] of init.headers) headers[name] = value;
408
546
  } else {
409
- Object.assign(headers, init.headers);
547
+ Object.assign(headers, headersInit);
410
548
  }
411
549
  serialized.headers = headers;
412
550
  }
@@ -421,7 +559,10 @@ function serializeFetchInit(init) {
421
559
  */
422
560
  export class PluginResponse {
423
561
  #body;
424
- /** @internal */
562
+ /**
563
+ * @internal
564
+ * @param {SerializedFetchResponse} response
565
+ */
425
566
  constructor({ status, ok, headers, body }) {
426
567
  /** @type {number} */
427
568
  this.status = status;
@@ -523,7 +664,7 @@ export class StyleSnippet {
523
664
  hostCall("applyStyleSnippet", {
524
665
  snippetId: this.#snippetId,
525
666
  cssText,
526
- }).then(resolve, reject);
667
+ }).then(() => resolve(), reject);
527
668
  });
528
669
  });
529
670
  }
@@ -547,8 +688,6 @@ let registered = false;
547
688
  * data. Call `MyPlugin.register()` at the top of your plugin's main.js to boot.
548
689
  */
549
690
  export class Plugin {
550
- /** @type {PluginSettingTab | null} */
551
- #settingTab = null;
552
691
  /** @internal */
553
692
  constructor() {
554
693
  /** @type {App} */
@@ -566,7 +705,7 @@ export class Plugin {
566
705
  addSidebarItem(icon, title, callback = () => {}) {
567
706
  const handlerId = uuid.create();
568
707
  callHandlers.set(handlerId, callback);
569
- self.postMessage({
708
+ post({
570
709
  type: "register",
571
710
  target: "sidebarItem",
572
711
  icon: icon instanceof VirtualEl ? icon._serialize() : icon,
@@ -586,7 +725,7 @@ export class Plugin {
586
725
 
587
726
  /**
588
727
  * Persists `data` as this plugin's account-synced JSON blob.
589
- * @param {unknown} data
728
+ * @param {Cloneable} data
590
729
  * @returns {Promise<void>}
591
730
  */
592
731
  async saveData(data) {
@@ -606,7 +745,7 @@ export class Plugin {
606
745
 
607
746
  /**
608
747
  * Device-local counterpart to {@link Plugin.saveData}.
609
- * @param {unknown} data
748
+ * @param {Cloneable} data
610
749
  * @returns {Promise<void>}
611
750
  */
612
751
  async saveLocalData(data) {
@@ -627,13 +766,12 @@ export class Plugin {
627
766
  tab.display();
628
767
  return tab.containerEl._serialize();
629
768
  });
630
- self.postMessage({
769
+ post({
631
770
  type: "register",
632
771
  target: "settingTab",
633
772
  name: tab.name ?? null,
634
773
  displayHandlerId,
635
774
  });
636
- this.#settingTab = tab;
637
775
  }
638
776
 
639
777
  /**
@@ -646,7 +784,7 @@ export class Plugin {
646
784
  addFeedFilter(callback = () => ({})) {
647
785
  const handlerId = uuid.create();
648
786
  callHandlers.set(handlerId, callback);
649
- self.postMessage({
787
+ post({
650
788
  type: "register",
651
789
  target: "feedFilter",
652
790
  handlerId,
@@ -661,6 +799,9 @@ export class Plugin {
661
799
  * {@link VirtualEl}), or `block` (a plugin-produced block VirtualEl). See
662
800
  * {@link FlattenedTokens} for pattern-matching across token boundaries.
663
801
  *
802
+ * A node token's `node` is a {@link VirtualEl} when this transform creates it,
803
+ * but arrives in serialized form when an earlier transform produced it.
804
+ *
664
805
  * `options.handlesFacetTypes` is an array of facet feature `$type` strings
665
806
  * this transform owns, so the host can suppress fallback rendering flash
666
807
  * while the transform runs.
@@ -677,7 +818,7 @@ export class Plugin {
677
818
  const value = await callback(tokens, context);
678
819
  results.push({ value: serializeTransformTokens(value) });
679
820
  } catch (error) {
680
- results.push({ error: error?.message ?? String(error) });
821
+ results.push({ error: getErrorMessage(error) });
681
822
  }
682
823
  }
683
824
  return results;
@@ -685,7 +826,7 @@ export class Plugin {
685
826
  const handlesFacetTypes = Array.isArray(options.handlesFacetTypes)
686
827
  ? options.handlesFacetTypes.filter((type) => typeof type === "string")
687
828
  : [];
688
- self.postMessage({
829
+ post({
689
830
  type: "register",
690
831
  target: "richTextTransform",
691
832
  handlerId,
@@ -722,7 +863,7 @@ export class Plugin {
722
863
  value: await getSlotContent(name, callback, context),
723
864
  });
724
865
  } catch (error) {
725
- results.push({ error: error?.message ?? String(error) });
866
+ results.push({ error: getErrorMessage(error) });
726
867
  }
727
868
  }
728
869
  return results;
@@ -730,7 +871,7 @@ export class Plugin {
730
871
  const cacheKey = Array.isArray(options.cacheKey)
731
872
  ? options.cacheKey.filter((field) => typeof field === "string")
732
873
  : null;
733
- self.postMessage({
874
+ post({
734
875
  type: "register",
735
876
  target: "slot",
736
877
  name,
@@ -759,7 +900,7 @@ export class Plugin {
759
900
  }
760
901
  return result._serialize();
761
902
  });
762
- self.postMessage({
903
+ post({
763
904
  type: "register",
764
905
  target: "page",
765
906
  id,
@@ -774,7 +915,7 @@ export class Plugin {
774
915
  * @returns {Promise<void>}
775
916
  */
776
917
  openPage(pageId) {
777
- return hostCall("openPage", { pageId });
918
+ return /** @type {Promise<void>} */ (hostCall("openPage", { pageId }));
778
919
  }
779
920
 
780
921
  /**
@@ -785,7 +926,9 @@ export class Plugin {
785
926
  * @returns {Promise<void>}
786
927
  */
787
928
  refreshPage(pageId, { reset = false } = {}) {
788
- return hostCall("refreshPage", { pageId, reset });
929
+ return /** @type {Promise<void>} */ (
930
+ hostCall("refreshPage", { pageId, reset })
931
+ );
789
932
  }
790
933
 
791
934
  /**
@@ -803,7 +946,9 @@ export class Plugin {
803
946
  * @returns {Promise<void>}
804
947
  */
805
948
  refreshSlot(name, options = {}) {
806
- return hostCall("refreshSlot", { name, keys: options.keys ?? null });
949
+ return /** @type {Promise<void>} */ (
950
+ hostCall("refreshSlot", { name, keys: options.keys ?? null })
951
+ );
807
952
  }
808
953
 
809
954
  /**
@@ -827,22 +972,35 @@ export class Plugin {
827
972
  if (registered) return;
828
973
  registered = true;
829
974
  const instance = new this();
830
- hostCall("getCurrentUser")
975
+ /** @type {Promise<ProfileView | null>} */ (hostCall("getCurrentUser"))
831
976
  .then((user) => {
832
977
  instance.app.currentUser = user;
833
978
  return instance.onload();
834
979
  })
835
980
  .then(
836
- () => self.postMessage({ type: "ready" }),
981
+ () => post({ type: "ready" }),
837
982
  (error) =>
838
- self.postMessage({
983
+ post({
839
984
  type: "ready",
840
- error: error?.message ?? String(error),
985
+ error: getErrorMessage(error),
841
986
  }),
842
987
  );
843
988
  }
844
989
  }
845
990
 
991
+ /**
992
+ * Extracts a message from a caught value, which need not be an Error.
993
+ * @param {unknown} error
994
+ * @returns {string}
995
+ */
996
+ function getErrorMessage(error) {
997
+ if (error instanceof Error) return error.message;
998
+ if (typeof error === "object" && error !== null && "message" in error) {
999
+ return String(error.message);
1000
+ }
1001
+ return String(error);
1002
+ }
1003
+
846
1004
  /**
847
1005
  * Names the type of an arbitrary value, for use in an error message.
848
1006
  * @param {unknown} value
@@ -854,6 +1012,12 @@ function describeValue(value) {
854
1012
  return value.constructor?.name ?? "object";
855
1013
  }
856
1014
 
1015
+ /**
1016
+ * @param {string} name
1017
+ * @param {(context: Record<string, string>) => RenderResult | Promise<RenderResult>} callback
1018
+ * @param {Record<string, string>} context
1019
+ * @returns {Promise<SerializedElement | null>}
1020
+ */
857
1021
  async function getSlotContent(name, callback, context) {
858
1022
  const result = /** @type {unknown} */ (await callback(context));
859
1023
  if (result == null) return null;
@@ -865,6 +1029,10 @@ async function getSlotContent(name, callback, context) {
865
1029
  return result._serialize();
866
1030
  }
867
1031
 
1032
+ /**
1033
+ * @param {RichTextToken[]} tokens
1034
+ * @returns {SerializedRichTextToken[]}
1035
+ */
868
1036
  function serializeTransformTokens(tokens) {
869
1037
  if (!Array.isArray(tokens)) return tokens;
870
1038
  return tokens.map((token) => {
@@ -885,6 +1053,7 @@ function serializeTransformTokens(tokens) {
885
1053
  * back to the original tokens.
886
1054
  */
887
1055
  export class FlattenedTokens {
1056
+ /** @type {{ token: RichTextToken, start: number, end: number }[]} */
888
1057
  #segments = [];
889
1058
  /**
890
1059
  * @param {RichTextToken[]} tokens
@@ -922,6 +1091,7 @@ export class FlattenedTokens {
922
1091
  * @returns {RichTextToken[]}
923
1092
  */
924
1093
  tokensFor(start, end) {
1094
+ /** @type {RichTextToken[]} */
925
1095
  const out = [];
926
1096
  for (const segment of this.#segments) {
927
1097
  if (segment.start === segment.end) {
@@ -953,6 +1123,7 @@ export function flattenForScan(tokens) {
953
1123
  return new FlattenedTokens(tokens);
954
1124
  }
955
1125
 
1126
+ /** @type {Map<number, Modal>} */
956
1127
  const openModals = new Map();
957
1128
 
958
1129
  /**
@@ -977,7 +1148,7 @@ export class Modal {
977
1148
  if (openModals.has(this.#modalId)) return;
978
1149
  openModals.set(this.#modalId, this);
979
1150
  this.onOpen();
980
- self.postMessage({
1151
+ post({
981
1152
  type: "hostCall",
982
1153
  method: "openModal",
983
1154
  args: [
@@ -996,7 +1167,7 @@ export class Modal {
996
1167
  */
997
1168
  update() {
998
1169
  if (!openModals.has(this.#modalId)) return;
999
- self.postMessage({
1170
+ post({
1000
1171
  type: "hostCall",
1001
1172
  method: "updateModal",
1002
1173
  args: [
@@ -1016,7 +1187,7 @@ export class Modal {
1016
1187
  close() {
1017
1188
  if (!openModals.has(this.#modalId)) return;
1018
1189
  openModals.delete(this.#modalId);
1019
- self.postMessage({
1190
+ post({
1020
1191
  type: "hostCall",
1021
1192
  method: "closeModal",
1022
1193
  args: [{ modalId: this.#modalId }],
@@ -1038,15 +1209,16 @@ export class Modal {
1038
1209
 
1039
1210
  /**
1040
1211
  * A tab in the plugin's settings UI. Subclass and override {@link PluginSettingTab.display}
1041
- * to render into `this.containerEl`. Register with `plugin.addSettingTab(tab)`.
1212
+ * to render into `this.containerEl`. Pass the owning plugin to `super(plugin)`
1213
+ * and register with `plugin.addSettingTab(tab)`.
1042
1214
  */
1043
1215
  export class PluginSettingTab {
1044
1216
  /**
1045
- * The owning plugin. Set by the host in {@link Plugin.addSettingTab}.
1046
- * @type {Plugin}
1217
+ * @param {Plugin} plugin The owning plugin, available as `this.plugin`.
1047
1218
  */
1048
- plugin;
1049
- constructor() {
1219
+ constructor(plugin) {
1220
+ /** @type {Plugin} */
1221
+ this.plugin = plugin;
1050
1222
  /** @type {VirtualEl} */
1051
1223
  this.containerEl = new VirtualEl("div");
1052
1224
  /** @type {string | null} */
@@ -1072,7 +1244,9 @@ export class PluginSettingTab {
1072
1244
  * @returns {Promise<void>}
1073
1245
  */
1074
1246
  refresh({ reset = false } = {}) {
1075
- return hostCall("refreshSettingTab", { reset });
1247
+ return /** @type {Promise<void>} */ (
1248
+ hostCall("refreshSettingTab", { reset })
1249
+ );
1076
1250
  }
1077
1251
  }
1078
1252
 
@@ -1171,7 +1345,10 @@ export class Setting {
1171
1345
 
1172
1346
  /** Single-line text input, built via {@link Setting.addText}. */
1173
1347
  export class TextComponent {
1174
- /** @internal */
1348
+ /**
1349
+ * @internal
1350
+ * @param {VirtualEl} containerEl
1351
+ */
1175
1352
  constructor(containerEl) {
1176
1353
  /** @type {VirtualEl} */
1177
1354
  this.el = containerEl.createEl("input", {
@@ -1210,7 +1387,10 @@ export class TextComponent {
1210
1387
 
1211
1388
  /** Multi-line text input, built via {@link Setting.addTextArea}. */
1212
1389
  export class TextAreaComponent {
1213
- /** @internal */
1390
+ /**
1391
+ * @internal
1392
+ * @param {VirtualEl} containerEl
1393
+ */
1214
1394
  constructor(containerEl) {
1215
1395
  /** @type {VirtualEl} */
1216
1396
  this.el = containerEl.createEl("textarea", {
@@ -1248,7 +1428,10 @@ export class TextAreaComponent {
1248
1428
 
1249
1429
  /** On/off toggle switch, built via {@link Setting.addToggle}. */
1250
1430
  export class ToggleComponent {
1251
- /** @internal */
1431
+ /**
1432
+ * @internal
1433
+ * @param {VirtualEl} containerEl
1434
+ */
1252
1435
  constructor(containerEl) {
1253
1436
  /** @type {VirtualEl} */
1254
1437
  this.el = containerEl.createEl("toggle-switch", {
@@ -1278,7 +1461,10 @@ export class ToggleComponent {
1278
1461
 
1279
1462
  /** Single-select dropdown, built via {@link Setting.addDropdown}. */
1280
1463
  export class DropdownComponent {
1281
- /** @internal */
1464
+ /**
1465
+ * @internal
1466
+ * @param {VirtualEl} containerEl
1467
+ */
1282
1468
  constructor(containerEl) {
1283
1469
  /** @type {VirtualEl} */
1284
1470
  this.el = containerEl.createEl("select", {
@@ -1335,7 +1521,10 @@ export class DropdownComponent {
1335
1521
 
1336
1522
  /** Clickable button, built via {@link Setting.addButton}. */
1337
1523
  export class ButtonComponent {
1338
- /** @internal */
1524
+ /**
1525
+ * @internal
1526
+ * @param {VirtualEl} containerEl
1527
+ */
1339
1528
  constructor(containerEl) {
1340
1529
  /** @type {VirtualEl} */
1341
1530
  this.el = containerEl.createEl("button", {
@@ -1372,7 +1561,10 @@ export class ButtonComponent {
1372
1561
 
1373
1562
  /** Renders a host-provided icon by name. Built via {@link VirtualEl.createIcon}. */
1374
1563
  export class IconComponent {
1375
- /** @internal */
1564
+ /**
1565
+ * @internal
1566
+ * @param {VirtualEl} containerEl
1567
+ */
1376
1568
  constructor(containerEl) {
1377
1569
  /** @type {VirtualEl} */
1378
1570
  this.el = containerEl.createEl("plugin-icon");
@@ -1393,7 +1585,10 @@ export class IconComponent {
1393
1585
  * {@link VirtualEl.createBlobImage}.
1394
1586
  */
1395
1587
  export class BlobImageComponent {
1396
- /** @internal */
1588
+ /**
1589
+ * @internal
1590
+ * @param {VirtualEl} containerEl
1591
+ */
1397
1592
  constructor(containerEl) {
1398
1593
  /** @type {VirtualEl} */
1399
1594
  this.el = containerEl.createEl("plugin-blob-image");
@@ -1441,7 +1636,10 @@ export class BlobImageComponent {
1441
1636
  * Built via {@link VirtualEl.createProfilesList}.
1442
1637
  */
1443
1638
  export class ProfilesListComponent {
1444
- /** @internal */
1639
+ /**
1640
+ * @internal
1641
+ * @param {VirtualEl} containerEl
1642
+ */
1445
1643
  constructor(containerEl) {
1446
1644
  /** @type {VirtualEl} */
1447
1645
  this.el = containerEl.createEl("plugin-profiles-list");
@@ -1472,7 +1670,10 @@ export class ProfilesListComponent {
1472
1670
  * Built via {@link VirtualEl.createPostsFeed}.
1473
1671
  */
1474
1672
  export class PostsFeedComponent {
1475
- /** @internal */
1673
+ /**
1674
+ * @internal
1675
+ * @param {VirtualEl} containerEl
1676
+ */
1476
1677
  constructor(containerEl) {
1477
1678
  /** @type {VirtualEl} */
1478
1679
  this.el = containerEl.createEl("plugin-posts-feed");
@@ -1510,7 +1711,10 @@ export class VirtualText {
1510
1711
  this.value = value == null ? "" : String(value);
1511
1712
  }
1512
1713
 
1513
- /** @internal */
1714
+ /**
1715
+ * @internal
1716
+ * @returns {SerializedText}
1717
+ */
1514
1718
  _serialize() {
1515
1719
  return { type: "text", value: this.value };
1516
1720
  }
@@ -1749,8 +1953,12 @@ export class VirtualEl {
1749
1953
  return component;
1750
1954
  }
1751
1955
 
1752
- /** @internal */
1956
+ /**
1957
+ * @internal
1958
+ * @returns {SerializedElement}
1959
+ */
1753
1960
  _serialize() {
1961
+ /** @type {SerializedElement} */
1754
1962
  const serialized = {
1755
1963
  type: "element",
1756
1964
  tag: this.tag,
@@ -1763,7 +1971,63 @@ export class VirtualEl {
1763
1971
  }
1764
1972
  }
1765
1973
 
1974
+ /**
1975
+ * @typedef {{ type: "text", value: string }} SerializedText
1976
+ * {@internal} The wire format of a {@link VirtualText} node.
1977
+ * @typedef {{ type: "element", tag: string, attrs: Record<string, string>, events: Record<string, number>, children: SerializedNode[], styles?: Record<string, string> }} SerializedElement
1978
+ * {@internal} The wire format of a {@link VirtualEl} node.
1979
+ * @typedef {SerializedText | SerializedElement} SerializedNode
1980
+ * {@internal} One node of the serialized tree the host renders and reconciles.
1981
+ * @typedef {{ [key: string]: Cloneable }} CloneableObject
1982
+ * An object whose values are all {@link Cloneable}.
1983
+ * @typedef {Cloneable[]} CloneableArray
1984
+ * An array of {@link Cloneable} values.
1985
+ * @typedef {null | undefined | boolean | number | string | CloneableArray | CloneableObject} Cloneable
1986
+ * JSON-shaped data — the only thing that can cross between a plugin and the
1987
+ * host. Functions, class instances, `Date`, `Map` and friends cannot.
1988
+ * @typedef {{ type: "register", target: "eventListener", event: string, handlerId: number }} RegisterEventListenerMessage
1989
+ * {@internal}
1990
+ * @typedef {{ type: "register", target: "sidebarItem", icon: string | SerializedElement, title: string, handlerId: number }} RegisterSidebarItemMessage
1991
+ * {@internal}
1992
+ * @typedef {{ type: "register", target: "settingTab", name: string | null, displayHandlerId: number }} RegisterSettingTabMessage
1993
+ * {@internal}
1994
+ * @typedef {{ type: "register", target: "feedFilter", handlerId: number }} RegisterFeedFilterMessage
1995
+ * {@internal}
1996
+ * @typedef {{ type: "register", target: "richTextTransform", handlerId: number, handlesFacetTypes: string[] }} RegisterRichTextTransformMessage
1997
+ * {@internal}
1998
+ * @typedef {{ type: "register", target: "slot", name: string, handlerId: number, cacheKey: string[] | null, batch: true }} RegisterSlotMessage
1999
+ * {@internal}
2000
+ * @typedef {{ type: "register", target: "page", id: string, title: string | null, displayHandlerId: number }} RegisterPageMessage
2001
+ * {@internal}
2002
+ * @typedef {RegisterEventListenerMessage | RegisterSidebarItemMessage | RegisterSettingTabMessage | RegisterFeedFilterMessage | RegisterRichTextTransformMessage | RegisterSlotMessage | RegisterPageMessage} RegisterMessage
2003
+ * {@internal} Announces an extension point this plugin provides.
2004
+ * @typedef {{ type: "hostCall", method: string, hostCallId?: number, args: Cloneable[] }} HostCallRequestMessage
2005
+ * {@internal} Calls a host method. Without a `hostCallId` it is fire-and-forget.
2006
+ * @typedef {{ type: "result", callId: number, value?: unknown, error?: string }} CallResultMessage
2007
+ * {@internal} Answers a {@link HostCallMessage}.
2008
+ * @typedef {{ type: "ready", error?: string }} ReadyMessage
2009
+ * {@internal} Reports the outcome of plugin load.
2010
+ * @typedef {RegisterMessage | HostCallRequestMessage | CallResultMessage | ReadyMessage} WorkerMessage
2011
+ * {@internal} Anything this worker may post to the host.
2012
+ * @typedef {{ type: "call", callId: number, handlerId: number, args: Cloneable[] }} HostCallMessage
2013
+ * {@internal} The host invoking a handler this worker registered.
2014
+ * @typedef {{ type: "hostResult", hostCallId: number, value?: Cloneable, error?: string }} HostResultMessage
2015
+ * {@internal} The host answering a {@link hostCall}.
2016
+ * @typedef {{ type: "event", event: "modalDismissed", data: { modalId: number } }} HostEventMessage
2017
+ * {@internal} An out-of-band notification from the host.
2018
+ * @typedef {HostCallMessage | HostResultMessage | HostEventMessage} HostMessage
2019
+ * {@internal} Anything the host may post to this worker.
2020
+ * @typedef {{ status: number, ok: boolean, headers: Record<string, string>, body: string }} SerializedFetchResponse
2021
+ * {@internal} The host's reply to a proxied {@link fetch}.
2022
+ * @typedef {{ method?: string, headers?: Record<string, string>, body?: string }} SerializedFetchInit
2023
+ * {@internal} A {@link PluginFetchInit} with its headers flattened for transfer.
2024
+ * @typedef {Record<string, unknown>} SerializedRichTextToken
2025
+ * {@internal} A {@link RichTextToken} whose `inline`/`block` node, if any, has
2026
+ * been replaced by its serialized form.
2027
+ */
2028
+
1766
2029
  self.onmessage = async (event) => {
2030
+ /** @type {HostMessage} */
1767
2031
  const message = event.data;
1768
2032
  if (!message || typeof message !== "object") return;
1769
2033
 
@@ -1771,7 +2035,7 @@ self.onmessage = async (event) => {
1771
2035
  if (message.type === "call") {
1772
2036
  const fn = callHandlers.get(message.handlerId);
1773
2037
  if (!fn) {
1774
- self.postMessage({
2038
+ post({
1775
2039
  type: "result",
1776
2040
  callId: message.callId,
1777
2041
  error: `unknown handler ${message.handlerId}`,
@@ -1780,12 +2044,12 @@ self.onmessage = async (event) => {
1780
2044
  }
1781
2045
  try {
1782
2046
  const value = await fn(...message.args);
1783
- self.postMessage({ type: "result", callId: message.callId, value });
2047
+ post({ type: "result", callId: message.callId, value });
1784
2048
  } catch (error) {
1785
- self.postMessage({
2049
+ post({
1786
2050
  type: "result",
1787
2051
  callId: message.callId,
1788
- error: error.message ?? String(error),
2052
+ error: getErrorMessage(error),
1789
2053
  });
1790
2054
  }
1791
2055
  return;
@@ -1813,6 +2077,5 @@ self.onmessage = async (event) => {
1813
2077
  return;
1814
2078
  }
1815
2079
  }
1816
- return;
1817
2080
  }
1818
2081
  };