@ignite-ember/extension-bridge 0.0.0-stage → 0.2.1

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 (69) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +364 -2
  4. package/dist/bridge.d.ts +37 -0
  5. package/dist/bridge.d.ts.map +1 -0
  6. package/dist/bridge.js +96 -0
  7. package/dist/bridge.js.map +1 -0
  8. package/dist/channel.d.ts +26 -0
  9. package/dist/channel.d.ts.map +1 -0
  10. package/dist/channel.js +36 -0
  11. package/dist/channel.js.map +1 -0
  12. package/dist/contract.d.ts +137 -0
  13. package/dist/contract.d.ts.map +1 -0
  14. package/dist/contract.js +9 -0
  15. package/dist/contract.js.map +1 -0
  16. package/dist/correlator.d.ts +37 -0
  17. package/dist/correlator.d.ts.map +1 -0
  18. package/dist/correlator.js +75 -0
  19. package/dist/correlator.js.map +1 -0
  20. package/dist/guestBridge.d.ts +63 -0
  21. package/dist/guestBridge.d.ts.map +1 -0
  22. package/dist/guestBridge.js +156 -0
  23. package/dist/guestBridge.js.map +1 -0
  24. package/dist/hostModel.d.ts +159 -0
  25. package/dist/hostModel.d.ts.map +1 -0
  26. package/dist/hostModel.generated.d.ts +2373 -0
  27. package/dist/hostModel.generated.d.ts.map +1 -0
  28. package/dist/hostModel.generated.js +1746 -0
  29. package/dist/hostModel.generated.js.map +1 -0
  30. package/dist/hostModel.js +172 -0
  31. package/dist/hostModel.js.map +1 -0
  32. package/dist/index.d.ts +12 -0
  33. package/dist/index.d.ts.map +1 -0
  34. package/dist/index.js +12 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/protocol.d.ts +348 -0
  37. package/dist/protocol.d.ts.map +1 -0
  38. package/dist/protocol.js +145 -0
  39. package/dist/protocol.js.map +1 -0
  40. package/dist/service.d.ts +168 -0
  41. package/dist/service.d.ts.map +1 -0
  42. package/dist/service.js +196 -0
  43. package/dist/service.js.map +1 -0
  44. package/dist/signals.d.ts +21 -0
  45. package/dist/signals.d.ts.map +1 -0
  46. package/dist/signals.js +52 -0
  47. package/dist/signals.js.map +1 -0
  48. package/dist/tokens.d.ts +101 -0
  49. package/dist/tokens.d.ts.map +1 -0
  50. package/dist/tokens.js +164 -0
  51. package/dist/tokens.js.map +1 -0
  52. package/dist/watchers.d.ts +12 -0
  53. package/dist/watchers.d.ts.map +1 -0
  54. package/dist/watchers.js +18 -0
  55. package/dist/watchers.js.map +1 -0
  56. package/package.json +53 -4
  57. package/src/bridge.ts +116 -0
  58. package/src/channel.ts +48 -0
  59. package/src/contract.ts +157 -0
  60. package/src/correlator.ts +88 -0
  61. package/src/guestBridge.ts +261 -0
  62. package/src/hostModel.generated.ts +3155 -0
  63. package/src/hostModel.ts +213 -0
  64. package/src/index.ts +11 -0
  65. package/src/protocol.ts +485 -0
  66. package/src/service.ts +278 -0
  67. package/src/signals.ts +65 -0
  68. package/src/tokens.ts +171 -0
  69. package/src/watchers.ts +18 -0
@@ -0,0 +1,157 @@
1
+ /**
2
+ * What an extension's page is handed by `connect()`.
3
+ *
4
+ * `P` and `S` are the extension's own launch parameters and settings:
5
+ * the host sends whatever the extension's links and manifest put there,
6
+ * so the extension is the one that can name them.
7
+ */
8
+
9
+ import type { HostError, Signal } from "./hostModel.js";
10
+ import type { Host } from "./hostModel.generated.js";
11
+ import type {
12
+ ExtensionSettings,
13
+ LaunchParams,
14
+ LocationState,
15
+ RpcArgs,
16
+ } from "./protocol.js";
17
+ import type { ServiceBridge } from "./service.js";
18
+ import type { ThemeTokens } from "./tokens.js";
19
+
20
+ /** What an extension's page is handed. */
21
+ export interface Bridge<
22
+ P extends LaunchParams = LaunchParams,
23
+ S extends ExtensionSettings = ExtensionSettings,
24
+ > {
25
+ /** The id this frame is, as the host named it. */
26
+ readonly extensionId: string;
27
+ /** Launch parameters, as the host passed them. */
28
+ readonly params: P;
29
+ /**
30
+ * What `contributes.settings` is configured to.
31
+ *
32
+ * Fixed for the life of this frame — a change applies at the next
33
+ * mount, so there is no `onSettings`. Separate from {@link params}
34
+ * because that is *where you are* and this is *how you are set
35
+ * up*; one namespace for both would make a setting and a query
36
+ * key with the same name the same thing.
37
+ */
38
+ readonly settings: S;
39
+ /** The host's theme now. Use `onTheme` to follow it. */
40
+ readonly theme: string;
41
+ /**
42
+ * The published design tokens, already applied to this document's
43
+ * root. Here as a reading for anything that needs a value rather
44
+ * than a CSS variable — a canvas, a chart library.
45
+ */
46
+ readonly tokens: ThemeTokens;
47
+ /**
48
+ * Call a backend RPC. Rejects with the host's refusal, as a sentence.
49
+ *
50
+ * @param method — the method to call, as `ext.<extension-id>.<method>`
51
+ * names it.
52
+ * @param args — the method's arguments, by name.
53
+ * @param timeoutMs — how long to wait for the answer before giving up,
54
+ * in milliseconds. The host has a timeout of its own, and the
55
+ * shorter of the two is the one that fires.
56
+ */
57
+ rpc<T = unknown>(
58
+ method: string,
59
+ args?: RpcArgs,
60
+ timeoutMs?: number,
61
+ ): Promise<T>;
62
+ /**
63
+ * Ask the host app to navigate. It decides whether to.
64
+ *
65
+ * @param to — the page to go to; the host decides whether it exists.
66
+ */
67
+ navigate(to: string): void;
68
+ /** Tell the host this surface is finished. */
69
+ close(): void;
70
+ /**
71
+ * Follow the host's theme. Returns an unsubscribe.
72
+ *
73
+ * @param fn — called with the theme whenever it changes.
74
+ */
75
+ onTheme(fn: (theme: string) => void): () => void;
76
+ /**
77
+ * Follow the launch parameters.
78
+ *
79
+ * They arrive in `hello` and can change afterwards — a link
80
+ * resolved while this frame was already mounted, or the host
81
+ * restoring a saved location. Without this the host would have to
82
+ * rebuild the frame to deliver a changed parameter, losing
83
+ * whatever state it held.
84
+ *
85
+ * Fires only on change, never for the initial value; read
86
+ * {@link params} for that.
87
+ *
88
+ * @param fn — called with the parameters whenever they change.
89
+ */
90
+ onParams(fn: (params: P) => void): () => void;
91
+ /**
92
+ * Tell the host where inside this extension the user now is.
93
+ *
94
+ * Not a navigation — {@link navigate} is that. This says "still
95
+ * here, and here is now this". The host folds it into its own URL
96
+ * and replays it in the next `hello`, which is the only way an
97
+ * extension can be linked to or restored: the frame cannot write
98
+ * the address bar, and its `localStorage` dies with the ephemeral
99
+ * port it was served from.
100
+ *
101
+ * Strings only, and keep it small — it ends up in the host's URL.
102
+ * Call it when the user lands somewhere worth returning to, not on
103
+ * every keystroke.
104
+ *
105
+ * @param state — where inside the extension the user is now, in
106
+ * strings, for the host to fold into its own URL.
107
+ */
108
+ setLocation(state: LocationState): void;
109
+
110
+ /**
111
+ * igni, as this extension sees it: the host object model
112
+ * (igni-core's `docs/HOST_OBJECT_MODEL.md` (https://github.com/ignite-ember/igni-core/blob/main/docs/HOST_OBJECT_MODEL.md)). The same model the
113
+ * extension's process reaches as `ext.host`.
114
+ *
115
+ * const busy = await bridge.host.chat.processing.get();
116
+ * await bridge.host.chat.post("Two issues in the files you changed.");
117
+ *
118
+ * A page's `host.ui` is the window it is framed in. Every object needs
119
+ * its grant in the manifest's `permissions.host`; one that is not
120
+ * granted rejects with a `HostError` whose `code` is `not_granted`.
121
+ */
122
+ readonly host: Host;
123
+
124
+ /**
125
+ * Handle a host signal: `bridge.on(bridge.host.chat.run_completed, fn)`.
126
+ *
127
+ * The first handler of a signal subscribes to it; removing the last
128
+ * one unsubscribes. A signal whose object is not granted never
129
+ * arrives; the refusal goes to `onRefused`, or to the console when
130
+ * there is none. Returns an unsubscribe.
131
+ *
132
+ * @param signal — the host signal to follow.
133
+ * @param fn — called with the signal's value each time it arrives.
134
+ * @param onRefused — called with the refusal when the host will not
135
+ * grant the signal; without one the refusal goes to the console.
136
+ */
137
+ on<T>(
138
+ signal: Signal<T>,
139
+ fn: (value: T) => void,
140
+ onRefused?: (error: HostError) => void,
141
+ ): () => void;
142
+
143
+ /**
144
+ * The extension's own service, reached directly, as the signed-in
145
+ * person.
146
+ *
147
+ * const res = await bridge.service.fetch("/v1/notes");
148
+ * const socket = await bridge.service.websocket("/v1/rooms/a");
149
+ *
150
+ * The host fetches a token whose audience is this extension's service
151
+ * and nothing else; it is kept and renewed before it expires. No
152
+ * `permissions.host` grant: having a service is the grant — see
153
+ * igni-core's `docs/HOST_OBJECT_MODEL.md` (https://github.com/ignite-ember/igni-core/blob/main/docs/HOST_OBJECT_MODEL.md). `url` is `null` when the
154
+ * extension has none.
155
+ */
156
+ readonly service: ServiceBridge;
157
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Requests the guest sent and is waiting on, matched to their replies by
3
+ * id.
4
+ *
5
+ * Each kind of request the guest makes — an RPC call, a host-model
6
+ * request, a service token — has its own `Correlator`, so a reply of
7
+ * one kind can never settle a request of another.
8
+ */
9
+
10
+ interface Waiter {
11
+ resolve: (value: unknown) => void;
12
+ reject: (error: Error) => void;
13
+ /** `undefined` for a request with no limit (one the person answers). */
14
+ timer: ReturnType<typeof setTimeout> | undefined;
15
+ }
16
+
17
+ export class Correlator {
18
+ private readonly waiting = new Map<string, Waiter>();
19
+
20
+ /**
21
+ * `prefix` tells this correlator's ids apart from another's in a log;
22
+ * `nextNumber` numbers them. A bridge's correlators share one counter,
23
+ * so its ids run 1, h2, s3 across every kind, as they always have.
24
+ */
25
+ constructor(
26
+ private readonly prefix: string,
27
+ private readonly nextNumber: () => number,
28
+ ) {}
29
+
30
+ /**
31
+ * Send one request and wait for its reply.
32
+ *
33
+ * `timeoutMs` null waits for as long as the reply takes; otherwise the
34
+ * request is given up on with `timedOut()` and a late reply is ignored.
35
+ */
36
+ send<T>(
37
+ timeoutMs: number | null,
38
+ timedOut: () => Error,
39
+ post: (id: string) => void,
40
+ ): Promise<T> {
41
+ const id = `${this.prefix}${this.nextNumber()}`;
42
+ return new Promise<T>((resolve, reject) => {
43
+ const timer =
44
+ timeoutMs === null
45
+ ? undefined
46
+ : setTimeout(() => {
47
+ this.waiting.delete(id);
48
+ reject(timedOut());
49
+ }, timeoutMs);
50
+ this.waiting.set(id, {
51
+ resolve: resolve as (value: unknown) => void,
52
+ reject,
53
+ timer,
54
+ });
55
+ try {
56
+ post(id);
57
+ } catch (error) {
58
+ // Nothing was sent, so no reply will come: do not leave the
59
+ // waiter and its timer behind for a request that never left.
60
+ this.take(id);
61
+ throw error;
62
+ }
63
+ });
64
+ }
65
+
66
+ /** The reply to `id` succeeded. */
67
+ resolve(id: string, value: unknown): void {
68
+ this.take(id)?.resolve(value);
69
+ }
70
+
71
+ /** The reply to `id` refused. */
72
+ reject(id: string, error: Error): void {
73
+ this.take(id)?.reject(error);
74
+ }
75
+
76
+ /**
77
+ * Stop waiting on `id`. An id nobody is waiting on is either a late
78
+ * reply to something that timed out, or noise; either way there is no
79
+ * one to tell.
80
+ */
81
+ private take(id: string): Waiter | undefined {
82
+ const waiter = this.waiting.get(id);
83
+ if (waiter === undefined) return undefined;
84
+ this.waiting.delete(id);
85
+ clearTimeout(waiter.timer);
86
+ return waiter;
87
+ }
88
+ }
@@ -0,0 +1,261 @@
1
+ /**
2
+ * The bridge an extension's page holds once the host has said hello.
3
+ *
4
+ * It owns everything the page learned from the host — params, theme,
5
+ * tokens — and the three kinds of request it can be waiting on, each
6
+ * with its own {@link Correlator}. Messages from the host are routed by
7
+ * kind through one table, {@link GuestBridge.handlers}.
8
+ */
9
+
10
+ import type { HostChannel } from "./channel.js";
11
+ import type { Bridge } from "./contract.js";
12
+ import { Correlator } from "./correlator.js";
13
+ import { HostError, type HostLink, type Signal } from "./hostModel.js";
14
+ import { Host } from "./hostModel.generated.js";
15
+ import type {
16
+ ExtensionSettings,
17
+ HelloMessage,
18
+ HostMessage,
19
+ HostReplyMessage,
20
+ HostRequestMessage,
21
+ LaunchParams,
22
+ LocationState,
23
+ ParamsMessage,
24
+ ResultMessage,
25
+ RpcArgs,
26
+ ServiceTokenReplyMessage,
27
+ ThemeMessage,
28
+ } from "./protocol.js";
29
+ import { type IssuedToken, ServiceError, ServiceLink } from "./service.js";
30
+ import { SignalSubscriptions } from "./signals.js";
31
+ import { applyThemeTokens, type ThemeTokens } from "./tokens.js";
32
+ import { Watchers } from "./watchers.js";
33
+
34
+ /** How long a request waits before giving up. The host has its own. */
35
+ export const DEFAULT_TIMEOUT_MS = 30_000;
36
+
37
+ /** Members whose answer is the person's, so no timeout applies to them. */
38
+ const WAITS_ON_THE_PERSON = new Set(["ui.show_dialog"]);
39
+
40
+ /** One handler per kind of message the host sends. */
41
+ type HostMessageHandlers = {
42
+ [K in HostMessage["kind"]]: (
43
+ message: Extract<HostMessage, { kind: K }>,
44
+ ) => void;
45
+ };
46
+
47
+ /** A host-model request, without the envelope and the id. */
48
+ type HostRequestBody = Omit<
49
+ HostRequestMessage,
50
+ "igni" | "kind" | "nonce" | "id"
51
+ >;
52
+
53
+ export class GuestBridge<
54
+ P extends LaunchParams,
55
+ S extends ExtensionSettings,
56
+ > implements Bridge<P, S> {
57
+ readonly extensionId: string;
58
+ readonly settings: S;
59
+ readonly host: Host;
60
+ readonly service: ServiceLink;
61
+
62
+ private currentParams: P;
63
+ private currentTheme: string;
64
+ private currentTokens: ThemeTokens;
65
+ private readonly themeWatchers = new Watchers<string>();
66
+ private readonly paramWatchers = new Watchers<P>();
67
+ /** One numbering for every request, whatever its kind. */
68
+ private requestCount = 0;
69
+ private readonly nextRequest = () => ++this.requestCount;
70
+ private readonly calls = new Correlator("", this.nextRequest);
71
+ private readonly hostRequests = new Correlator("h", this.nextRequest);
72
+ private readonly tokenRequests = new Correlator("s", this.nextRequest);
73
+ private readonly signals = new SignalSubscriptions((op, signal) =>
74
+ this.hostRequest({ op, path: "", signals: [signal] }),
75
+ );
76
+
77
+ private readonly handlers: HostMessageHandlers = {
78
+ // Connecting already consumed the greeting; a repeat changes nothing.
79
+ hello: () => {},
80
+ theme: (message) => this.applyTheme(message),
81
+ params: (message) => this.applyParams(message),
82
+ signal: (message) => this.signals.deliver(message),
83
+ "host-reply": (message) => this.settleHostRequest(message),
84
+ "service-token-reply": (message) => this.settleTokenRequest(message),
85
+ result: (message) => this.settleCall(message),
86
+ };
87
+
88
+ /**
89
+ * `params` and `settings` are the extension's to name (`P`, `S`): the
90
+ * host sends what the extension's own links and manifest put there.
91
+ */
92
+ constructor(
93
+ private readonly channel: HostChannel,
94
+ hello: HelloMessage,
95
+ ) {
96
+ this.extensionId = hello.extensionId;
97
+ this.settings = (hello.settings ?? {}) as S;
98
+ this.currentParams = hello.params as P;
99
+ this.currentTheme = hello.theme;
100
+ this.currentTokens = hello.tokens;
101
+ const link: HostLink = {
102
+ request: (op, path, options) =>
103
+ this.hostRequest({
104
+ op,
105
+ path,
106
+ window: options.window ?? null,
107
+ ...(options.session ? { session: options.session } : {}),
108
+ ...(options.params !== undefined ? { params: options.params } : {}),
109
+ ...(op === "set" ? { value: options.value } : {}),
110
+ }),
111
+ };
112
+ this.host = new Host(link);
113
+ this.service = new ServiceLink(hello.serviceUrl ?? null, () => this.askForToken());
114
+ // Applied before the page renders anything, so an extension never
115
+ // paints once in the fallback palette and again in the real one.
116
+ applyThemeTokens(this.currentTokens, document.documentElement);
117
+ }
118
+
119
+ get params(): P {
120
+ return this.currentParams;
121
+ }
122
+
123
+ get theme(): string {
124
+ return this.currentTheme;
125
+ }
126
+
127
+ get tokens(): ThemeTokens {
128
+ return this.currentTokens;
129
+ }
130
+
131
+ /** Act on one message the host sent. */
132
+ receive(message: HostMessage): void {
133
+ // The table is keyed by kind, so this handler takes this message;
134
+ // TypeScript cannot follow that correlation through an index.
135
+ const handle = this.handlers[message.kind] as (
136
+ message: HostMessage,
137
+ ) => void;
138
+ handle(message);
139
+ }
140
+
141
+ rpc<T = unknown>(
142
+ method: string,
143
+ args: RpcArgs = {},
144
+ timeoutMs: number = DEFAULT_TIMEOUT_MS,
145
+ ): Promise<T> {
146
+ // `Number`, not `timeoutMs` as it is: null means "no limit" to a
147
+ // correlator, but an untyped caller's null (or "500") reaches a
148
+ // call's timer the way `setTimeout` always read it — as 0 (or 500).
149
+ return this.calls.send<T>(
150
+ Number(timeoutMs),
151
+ () => new Error(`igni bridge: ${method} timed out after ${timeoutMs}ms`),
152
+ (id) => this.channel.post({ kind: "call", id, method, args }),
153
+ );
154
+ }
155
+
156
+ navigate(to: string): void {
157
+ this.channel.post({ kind: "navigate", to });
158
+ }
159
+
160
+ close(): void {
161
+ this.channel.post({ kind: "close" });
162
+ }
163
+
164
+ onTheme(fn: (theme: string) => void): () => void {
165
+ return this.themeWatchers.add(fn);
166
+ }
167
+
168
+ onParams(fn: (params: P) => void): () => void {
169
+ return this.paramWatchers.add(fn);
170
+ }
171
+
172
+ setLocation(state: LocationState): void {
173
+ this.channel.post({ kind: "location", state });
174
+ }
175
+
176
+ on<T>(
177
+ signal: Signal<T>,
178
+ fn: (value: T) => void,
179
+ onRefused?: (error: HostError) => void,
180
+ ): () => void {
181
+ return this.signals.on(signal, fn, onRefused);
182
+ }
183
+
184
+ private applyTheme(message: ThemeMessage): void {
185
+ this.currentTheme = message.theme;
186
+ this.currentTokens = message.tokens;
187
+ applyThemeTokens(this.currentTokens, document.documentElement);
188
+ this.themeWatchers.emit(this.currentTheme);
189
+ }
190
+
191
+ private applyParams(message: ParamsMessage): void {
192
+ this.currentParams = message.params as P;
193
+ this.paramWatchers.emit(this.currentParams);
194
+ }
195
+
196
+ private hostRequest(body: HostRequestBody): Promise<unknown> {
197
+ // A dialog waits on the person, for as long as they take.
198
+ const waits = WAITS_ON_THE_PERSON.has(body.path);
199
+ return this.hostRequests.send(
200
+ waits ? null : DEFAULT_TIMEOUT_MS,
201
+ () =>
202
+ new HostError(
203
+ "failed",
204
+ `igni bridge: host.${body.path || body.op} timed out after ${DEFAULT_TIMEOUT_MS}ms`,
205
+ ),
206
+ (id) => this.channel.post({ kind: "host", id, ...body }),
207
+ );
208
+ }
209
+
210
+ /** One token request to the host, which asks igni as this extension. */
211
+ private askForToken(): Promise<IssuedToken> {
212
+ return this.tokenRequests.send<IssuedToken>(
213
+ DEFAULT_TIMEOUT_MS,
214
+ () =>
215
+ new ServiceError(
216
+ "failed",
217
+ `igni bridge: no service token within ${DEFAULT_TIMEOUT_MS}ms`,
218
+ ),
219
+ (id) => this.channel.post({ kind: "service-token", id }),
220
+ );
221
+ }
222
+
223
+ private settleCall(reply: ResultMessage): void {
224
+ if (reply.ok) this.calls.resolve(reply.id, reply.value);
225
+ else
226
+ this.calls.reject(
227
+ reply.id,
228
+ new Error(
229
+ reply.error || "the host refused the call without saying why",
230
+ ),
231
+ );
232
+ }
233
+
234
+ private settleHostRequest(reply: HostReplyMessage): void {
235
+ if (reply.ok) this.hostRequests.resolve(reply.id, reply.result);
236
+ else
237
+ this.hostRequests.reject(
238
+ reply.id,
239
+ new HostError(
240
+ reply.error?.code ?? "failed",
241
+ reply.error?.message ?? "the host refused without saying why",
242
+ ),
243
+ );
244
+ }
245
+
246
+ private settleTokenRequest(reply: ServiceTokenReplyMessage): void {
247
+ if (reply.ok && typeof reply.token === "string")
248
+ this.tokenRequests.resolve(reply.id, {
249
+ token: reply.token,
250
+ expiresIn: reply.expiresIn ?? 0,
251
+ });
252
+ else
253
+ this.tokenRequests.reject(
254
+ reply.id,
255
+ new ServiceError(
256
+ "refused",
257
+ reply.error || "igni gave no token for this extension's service",
258
+ ),
259
+ );
260
+ }
261
+ }