@coda-console/plugin-check 0.8.20 → 0.8.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 (38) hide show
  1. package/README.md +3 -3
  2. package/check/agent.mjs +2 -1
  3. package/check/coda/adapters/call-limit.mjs +56 -0
  4. package/check/coda/adapters/clock.mjs +48 -0
  5. package/check/coda/adapters/plugin-command.mjs +171 -0
  6. package/check/coda/adapters/plugin-modules.mjs +505 -0
  7. package/check/coda/adapters/plugin-stream-services.mjs +53 -0
  8. package/check/coda/adapters/plugin-test-host.d.mts +316 -0
  9. package/check/coda/adapters/plugin-test-host.mjs +404 -0
  10. package/check/coda/adapters/process-relay.mjs +74 -0
  11. package/check/coda/adapters/provider-api.mjs +147 -40
  12. package/check/coda/application/contributions.mjs +1 -0
  13. package/check/coda/builtin.json +66 -67
  14. package/check/coda/components/composers/schemas.mjs +4 -2
  15. package/check/coda/components/concurrency-groups/schemas.mjs +102 -0
  16. package/check/coda/components/plugins/plugin-extensions.mjs +104 -10
  17. package/check/coda/components/plugins/plugin-rules.mjs +19 -1
  18. package/check/coda/components/plugins/plugin-source-rules.mjs +34 -14
  19. package/check/coda/components/plugins/process-contributions.mjs +9 -0
  20. package/check/coda/components/prompt-recovery/prompt-recovery.mjs +2 -49
  21. package/check/coda/components/protocols/record-rules.mjs +70 -0
  22. package/check/coda/components/protocols/types.mjs +22 -4
  23. package/check/coda/components/workflows/contributions.mjs +2 -6
  24. package/check/coda/contract.json +29 -21
  25. package/check/coda/domain/errors.mjs +5 -1
  26. package/check/coda/domain/resume-prompt.mjs +93 -0
  27. package/check/coda/domain/session-env.mjs +1 -1
  28. package/check/coda/resources/plugins/resources/panels/panels.mjs +26 -17
  29. package/check/coda/resources/plugins/resources/panels/rules.mjs +0 -4
  30. package/check/coda/resources/plugins/resources/panels/sign-in.mjs +32 -41
  31. package/check/manifest.mjs +0 -1
  32. package/check/panel.mjs +6 -5
  33. package/package.json +2 -2
  34. package/check/coda/adapters/admission-api.mjs +0 -22
  35. package/check/coda/components/protocols/creation.mjs +0 -19
  36. package/check/coda/domain/resource-admission.mjs +0 -15
  37. package/check/coda/resources/plugins/resources/panels/command.mjs +0 -46
  38. package/check/command.mjs +0 -48
@@ -0,0 +1,505 @@
1
+ // The plugin host's modules (docs/plugins.md「插件宿主」): each plugin's that has a `main`, loaded the first time anything
2
+ // of it is needed, or when the backend says to, and given a `coda` of its own. What the runner (adapters/plugin-host-runner.mjs)
3
+ // runs over Node's IPC channel with the backend, and the test host (adapters/plugin-test-host.mjs) over a channel of its own:
4
+ // `send(message)` to the backend, `receive(message)` from it. `adopt(plugin, token)`: a plugin's `coda` made with no module
5
+ // loaded, for whoever holds it to activate a module with; `stop()`: each module loaded ends what it started (`deactivate`).
6
+ //
7
+ // From the backend: `start { api: { url }, parts }`, `activate { plugin, token }` (before anything else of the plugin's),
8
+ // `open { instance, plugin, view, context, caller }`, `query { plugin, request, deadline }`, `run { plugin, call }` and
9
+ // `resume { plugin, call }`, and `cancel { id, reason }` of any of them, `mode { plugin, mode, hook, context }` (a request
10
+ // each), and `message`, `callProgress { id, value }` (a `call`'s progress, by the request's ID), `context`, `close { instance, … }`, `changed { watch, events }`, `settingsChanged { plugin,
11
+ // settings }` (a notice, no answer: the plugin's own settings, as `Plugins.setSettings` wrote them), and `output`, `exited`
12
+ // of a process it started (adapters/process-relay.mjs). To it: `post { instance, message }`, `change { instance,
13
+ // collection, type, id, object }`, `unwatch { watch }`, `cancel { id }` of a `query` or a `question`, `progress { run,
14
+ // value }` of a `run`, `drained`, `kill` of a process, and the requests `environment { of, project }`, `settings`
15
+ // (the plugin's own, as they are now), `watch { collection, selector }`, `tell { session, text }`, `part { part, method,
16
+ // args }`, `provider { method, args }`, `serviceRegister { id, port, secret }`, `serviceUnregister { id }`, `query { record,
17
+ // operation, input, timeout, deadline }`, `call { record, operation, input, id, timeout, deadline, under, progress }`, `spawn { under, process, command, args, cwd, env, name }`, each with the
18
+ // module's `token`, by which the backend knows the plugin it is of, never by what it names; and `question { run,
19
+ // question }` and `input` of a process. A query's
20
+ // failure crosses as `failureOf` says it, as one that did nothing (`none`); a run's end, and a resume's, as its outcome, or a resume's as null when the
21
+ // module has none.
22
+ import { join } from 'node:path';
23
+ import { Readable, Writable } from 'node:stream';
24
+ import { pluginServices } from './plugin-stream-services.mjs';
25
+ import { pathToFileURL } from 'node:url';
26
+ import { callingAPI, canceled, codaError, failed, failureOf, givenUp, providerAPI, queryingAPI } from './provider-api.mjs';
27
+ import { queryId } from './plugin-command.mjs';
28
+
29
+ export function pluginModules({ send }) {
30
+ // This machine's Coda, as `start` gives it: its address only. Each module reaches it with its own plugin's token, given
31
+ // with `activate` and kept in its own `coda` only.
32
+ let api = null;
33
+ // The parts of `coda` others provide (components/plugins/plugin-host.mjs provide), as `start` names them: each made of the
34
+ // calls it asks by what its module exports (`make`).
35
+ let parts = Promise.resolve([]);
36
+ const loading = new Map(), instances = new Map(), asked = new Map(), watches = new Map();
37
+ // The queries and doing calls being handled, by the backend's request: each called off with the reason the backend gives
38
+ // (`cancel`).
39
+ const cancels = new Map();
40
+ // What a handler of a call is given beside its input (coda#2749 3.1): the call's ID, its record, its `signal`, which goes
41
+ // off as the backend calls it off, its `deadline` (milliseconds on the backend's clock, or none), `query`, queries made
42
+ // under it, and `spawn`, processes started for it, the backend's request `under` which the call came; a doing call's
43
+ // handler (`run`, `resume`), `call` too, doing calls it makes (`doingOf`).
44
+ const contextOf = ({ id, record, deadline }, signal, { querying, spawnFor }, under) =>
45
+ ({ id, record, signal, deadline, query: querying.within(signal, deadline), spawn: spawnFor(under, signal) });
46
+ const doingOf = (call, signal, made, under) => ({ ...contextOf(call, signal, made, under), call: made.calling.within(signal, call.deadline, under) });
47
+ // The processes the modules started through the backend (`spawn`), by the key this host gave each, until they have
48
+ // exited or the host stops.
49
+ const processes = new Map();
50
+ let nextProcess = 0;
51
+ // A doing call handed to its operation's handler (`run`, `resume`), as `fn(handler, signal, made)` hands it, its
52
+ // `signal` going off as the backend calls it off (`cancel`), or, `halted` (as `cancel`'s reason crosses), before the
53
+ // handler is called.
54
+ async function handling(plugin, call, id, fn, halted = null) {
55
+ const controller = new AbortController();
56
+ if (halted) controller.abort(canceled(halted));
57
+ cancels.set(id, controller);
58
+ try {
59
+ const made = await activated(plugin);
60
+ return await fn(made.operations.get(JSON.stringify([call.record.kind, call.operation])), controller.signal, made);
61
+ } finally { cancels.delete(id); }
62
+ }
63
+ // How a doing call's handler ended it: completed with what it returned, as it crosses the channel, JSON (one that is not,
64
+ // a BigInt, a cycle, fails as the handler's error, as anything it throws does, an error or not); failed as it threw
65
+ // (`failureOf`); or, thrown the reason its `signal` went off with as the call was cancelled, cancelled.
66
+ async function ending(handled, signal) {
67
+ try { return { outcome: 'completed', result: JSON.parse(JSON.stringify(await handled()) ?? 'null') }; } catch (error) {
68
+ return signal.aborted && error === signal.reason && error.name === 'AbortError' ? { outcome: 'canceled' } : { outcome: 'failed', error: failureOf(error) };
69
+ }
70
+ }
71
+ // A module's collections (docs/plugins.md「集合」): names and IDs as the page takes them; a change at most as a message is,
72
+ // measured as the backend measures what it passes on (components/plugins/plugin-host.mjs deliver).
73
+ const NAME = /^[a-z][a-z0-9-]{0,39}$/, CHANGE_LIMIT = 128 * 1024;
74
+ let next = 0;
75
+ // Asked of the backend; given up on with `signal`, the backend is told to give it up too, and it fails with the signal's
76
+ // reason (`givenUp`), as one that may have been done — a query as one that did nothing. What the backend says of how it goes (`callProgress`) is given to `progress`.
77
+ const ask = (method, params, signal = null, progress = null) => new Promise((resolve, reject) => {
78
+ const id = ++next;
79
+ const given = () => {
80
+ if (!asked.delete(id)) return;
81
+ send({ method: 'cancel', params: { id } });
82
+ reject(givenUp(signal, method === 'query' ? 'none' : 'unknown'));
83
+ };
84
+ const settled = fn => value => { signal?.removeEventListener('abort', given); fn(value); };
85
+ asked.set(id, { resolve: settled(resolve), reject: settled(reject), progress });
86
+ send({ id, method, params });
87
+ signal?.addEventListener('abort', given, { once: true });
88
+ });
89
+ const fire = (listeners, value) => {
90
+ for (const fn of listeners) {
91
+ try { Promise.resolve(fn(value)).catch(e => console.error('插件出错:', e)); } catch (e) { console.error('插件出错:', e); }
92
+ }
93
+ };
94
+ const listen = set => fn => { set.add(fn); return { dispose: () => set.delete(fn) }; };
95
+ // One of Coda's collections, whole or as `selector` has it (a session's runs), watched once for each plugin (`plugin`)
96
+ // however many of its modules' watchers watch it, asked with its token (`asks`): `fn` is given every object as `ADDED`
97
+ // first, then each change. Done once the first are given. The last watcher gone, the backend stops reading it. A kind's
98
+ // records (coda#2749 3.7, `{ scope?, id?, labels? }` as `list` takes them) are each told as an entry, as `get` and `list` give it
99
+ // to the plugin (its own with their keys), by its ID: `{ type, id, entry }`.
100
+ // A change as a watcher is told it: of a kind, its entry by the record's ID; the backend tells it by its holder's too.
101
+ const told = (watched, type, id, object) => watched.entries ? { type, id: object.id, entry: object } : { type, id, object };
102
+ async function watch(asks, plugin, name, fn, selector = null) {
103
+ if (typeof name !== 'string' || typeof fn !== 'function') throw new TypeError('watch(集合, fn, 筛选?)');
104
+ if (selector !== null && (typeof selector !== 'object' || Array.isArray(selector))) throw new TypeError('筛选须为对象');
105
+ // Named as the backend names it.
106
+ const key = JSON.stringify([name, selector, plugin]);
107
+ let watched = watches.get(key);
108
+ if (!watched) {
109
+ watched = { objects: new Map(), listeners: new Set(), ready: null, entries: false };
110
+ watched.ready = asks('watch', { collection: name, selector }).then(({ items, entries }) => {
111
+ watched.entries = !!entries;
112
+ for (const { id, object } of items) watched.objects.set(id, object);
113
+ });
114
+ watches.set(key, watched);
115
+ watched.ready.catch(() => watches.delete(key));
116
+ }
117
+ await watched.ready;
118
+ watched.listeners.add(fn);
119
+ for (const [id, object] of watched.objects) fire([fn], told(watched, 'ADDED', id, object));
120
+ return {
121
+ dispose: () => {
122
+ watched.listeners.delete(fn);
123
+ if (watched.listeners.size || watches.get(key) !== watched) return;
124
+ watches.delete(key);
125
+ send({ method: 'unwatch', params: { watch: key } });
126
+ },
127
+ };
128
+ }
129
+
130
+ // A process the backend starts for a module (coda#2749 3.8, docs/plugins.md「起进程」), as Node's ChildProcess has the
131
+ // most of it: `stdin` written to it, `stdout` and `stderr` read from it, as they cross the channel (adapters/
132
+ // process-relay.mjs: what the module reads of each it says it has, `drained`, for the backend to send more), and
133
+ // `exited`, its exit code and signal once both outputs have ended. The host stopping (its channel gone) ends its
134
+ // outputs as they are and fails `exited` (`interrupted`): the backend ends the process. A named one (not `piped`) has
135
+ // no streams, as a ChildProcess started with its stdio elsewhere: its output is in its log.
136
+ function processHandle(key, piped) {
137
+ let settle;
138
+ const exited = new Promise((resolve, reject) => { settle = { resolve, reject }; });
139
+ exited.catch(() => {});
140
+ const output = name => {
141
+ let owed = 0, ended = false;
142
+ const drained = () => {
143
+ if (!owed) return;
144
+ send({ method: 'drained', params: { process: key, stream: name, bytes: owed } });
145
+ owed = 0;
146
+ };
147
+ const stream = new Readable({ read: drained });
148
+ return { stream, take(data) {
149
+ if (ended) return;
150
+ if (data === null) { ended = true; stream.push(null); return; }
151
+ const chunk = Buffer.from(String(data), 'base64');
152
+ owed += chunk.length;
153
+ if (stream.push(chunk)) drained();
154
+ } };
155
+ };
156
+ const outputs = piped ? { stdout: output('stdout'), stderr: output('stderr') } : {};
157
+ const stdin = piped ? new Writable({
158
+ write(chunk, _encoding, done) { ask('input', { process: key, data: chunk.toString('base64') }).then(() => done(), done); },
159
+ final(done) { ask('input', { process: key, end: true }).then(() => done(), done); },
160
+ }) : null;
161
+ const value = { pid: null, stdin, stdout: outputs.stdout?.stream ?? null, stderr: outputs.stderr?.stream ?? null, exited,
162
+ kill(signal = 'SIGTERM') { send({ method: 'kill', params: { process: key, signal } }); } };
163
+ const over = () => {
164
+ processes.delete(key);
165
+ for (const each of Object.values(outputs)) each.take(null);
166
+ stdin?.destroy();
167
+ };
168
+ const entry = {
169
+ value,
170
+ output(stream, data) { outputs[stream]?.take(data); },
171
+ exit({ code = null, signal = null }) { over(); settle.resolve({ code, signal }); },
172
+ interrupt() { over(); settle.reject(codaError('interrupted', '插件宿主停了,进程由后端收掉', { effects: 'unknown' })); },
173
+ };
174
+ processes.set(key, entry);
175
+ return entry;
176
+ }
177
+ // `spawn(command, args?, { cwd, env, name }?)` of a plugin's: started by the backend with the plugin's processes'
178
+ // environment (`env` added over it), for the call whose request is `under` (`ctx.spawn`) or for the module (`coda.spawn`,
179
+ // `under` null), or, `name` given, as the process of that name the plugin's manifest declares (`contributes.processes`).
180
+ // One for a call ends as `signal` goes off; a named one does not. Fails as the backend could not start it.
181
+ const spawning = (asks, under, signal) => async (command, args = [], options = {}) => {
182
+ if (typeof command !== 'string' || !command || !Array.isArray(args) || args.some(arg => typeof arg !== 'string') || !options || typeof options !== 'object') {
183
+ throw new TypeError('spawn(命令, 参数?, { cwd, env, name }?)');
184
+ }
185
+ const { cwd = null, env = {}, name = null } = options, bound = name === null ? signal : null;
186
+ bound?.throwIfAborted();
187
+ const key = String(++nextProcess), entry = processHandle(key, name === null);
188
+ try { entry.value.pid = (await asks('spawn', { under, process: key, command, args, cwd, env, name })).pid; }
189
+ catch (error) { processes.delete(key); throw error; }
190
+ if (bound) {
191
+ const end = () => entry.value.kill();
192
+ if (bound.aborted) end(); else bound.addEventListener('abort', end, { once: true });
193
+ entry.value.exited.catch(() => {}).finally(() => bound.removeEventListener('abort', end));
194
+ }
195
+ return entry.value;
196
+ };
197
+
198
+ // What a plugin's module is given: this plugin's own, and the environment of another's it runs a command of; and the parts
199
+ // others provide, each asking the backend under its name. `token`: this plugin's for this host process, brought with
200
+ // every request it asks (`asks`).
201
+ function codaFor(plugin, provided, token) {
202
+ const views = new Map(), protocols = new Map(), operations = new Map();
203
+ const asks = (method, params, signal = null, progress = null) => ask(method, { ...params, token }, signal, progress);
204
+ const services = pluginServices(asks);
205
+ const environment = (project = null, options = {}) => asks('environment', { of: options?.plugin ?? null, project });
206
+ // The listeners of `settings.onChange`: this plugin's own settings only, told as they are written.
207
+ const settingsChanges = new Set();
208
+ // A query through the backend's unified call, the caller this plugin by its token.
209
+ const querying = queryingAPI({ send: (request, signal) => asks('query', request, signal), plugin, operations });
210
+ // A doing call through the call kernel, from this plugin's address (docs/plugins.md「做事的调用」).
211
+ const calling = callingAPI((request, signal, progress) => asks('call', request, signal, progress));
212
+ const spawnFor = (under, signal) => spawning(asks, under, signal);
213
+ const watching = (name, fn, selector) => watch(asks, plugin.id, name, fn, selector);
214
+ // The records this plugin holds (coda#2749 3.7), written one after another as the module said them, whatever became of
215
+ // the one before: each answered once it is in this machine's record directory, or refused with its code.
216
+ let writing = Promise.resolve();
217
+ const write = (method, args) => {
218
+ const written = writing.then(() => asks('provider', { method, args }));
219
+ writing = written.catch(() => {});
220
+ return written;
221
+ };
222
+ const coda = Object.freeze({
223
+ plugin: Object.freeze({ id: plugin.id, path: plugin.path, state: plugin.state }),
224
+ // Queries (docs/plugins.md「调用」): one of a protocol the plugin implements handled, one of its own processes' handled
225
+ // (`self.handle`), one of any record's made, a failure said.
226
+ handle: querying.handle, self: querying.self, query: querying.query, error: querying.error,
227
+ // A doing call of any record's (docs/plugins.md「做事的调用」).
228
+ call: calling.call,
229
+ // A process of this module's own, until the module stops (docs/plugins.md「起进程」).
230
+ spawn: spawnFor(null, null),
231
+ services: services.api,
232
+ // `put({ kind, key }, { spec, status?, labels? })` made or replaced (a status not given kept), answered with its entry,
233
+ // `delete({ kind, key })`, and `replace(kind, entries)`, every one of a kind the plugin holds given (`[{ key, spec,
234
+ // status?, labels? }]`), those it no longer gives gone, answered with the entries given, in their order: each named by
235
+ // the plugin's own key, its ID the host's. `get({ kind, id })`, one record or null, and `list(kind, { scope?, id?, labels? })`,
236
+ // the records of any kind, each an entry `{ owner, location, id, plugin, key?, local, spec, status, labels, version }`, `key`
237
+ // only of this plugin's own here: read after what this module wrote before.
238
+ get: record => writing.then(() => asks('provider', { method: 'getRecord', args: [record] })),
239
+ list: (kind, filter) => writing.then(() => asks('provider', { method: 'listRecords', args: [kind, filter ?? null] })),
240
+ put: (record, value) => write('putRecord', [record, value]),
241
+ delete: record => write('deleteRecord', [record]),
242
+ replace: (kind, entries) => write('replaceRecords', [kind, entries]),
243
+ ...Object.fromEntries(provided.map(([name, make]) => [name, Object.freeze(make((method, args) => asks('part', { part: name, method, args })))])),
244
+ views: Object.freeze({
245
+ register(id, provider) {
246
+ if (typeof id !== 'string' || typeof provider?.open !== 'function') throw new TypeError('views.register(视图 ID, { open(view) })');
247
+ views.set(id, provider);
248
+ return { dispose: () => { if (views.get(id) === provider) views.delete(id); } };
249
+ },
250
+ }),
251
+ protocols: Object.freeze({
252
+ ...providerAPI({ call: (method, args) => asks('provider', { method, args }), connection: () => api && { url: api.url, token } }),
253
+ register(kind, key, handler) {
254
+ if (typeof kind !== 'string' || !kind || typeof key !== 'string' || !key || typeof handler !== 'function') throw new TypeError('protocols.register(类型, key, handler)');
255
+ const id = JSON.stringify([kind, key]);
256
+ if (protocols.has(id)) throw new TypeError(`协议参与者已登记:${kind}/${key}`);
257
+ protocols.set(id, handler);
258
+ return { dispose: () => { if (protocols.get(id) === handler) protocols.delete(id); } };
259
+ },
260
+ }),
261
+ // Something for a session's agent to know, told with its next turn (docs/session-contracts.md「顺带告诉」).
262
+ tell: (session, text) => asks('tell', { session, text }),
263
+ // This machine's Coda, as its clients reach it: GET without a body, POST with one.
264
+ async api(path, body) {
265
+ if (!api) throw new Error('Coda 还在启动,稍后再试');
266
+ const response = await fetch(`${api.url}/v1/${String(path).replace(/^\/+/, '')}`, {
267
+ method: body === undefined ? 'GET' : 'POST',
268
+ headers: { authorization: `Bearer ${token}`, ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
269
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
270
+ });
271
+ const value = await response.json().catch(() => null);
272
+ if (!response.ok) throw new Error(value?.error?.message ?? `Coda 回答 ${response.status}`);
273
+ return value;
274
+ },
275
+ // What Coda gives every process of the plugin's (docs/plugins.md「插件进程的环境」), for one the module starts itself
276
+ // (Node's child_process, as a VS Code extension starts its language server); `{ plugin }`, another installed plugin's,
277
+ // for a command of its the module runs.
278
+ environment,
279
+ // This plugin's own settings (docs/plugins.md「设置」): as they are now, asked of the backend each time, and told to
280
+ // `onChange` as they are written, while the module runs. Secrets are not among them.
281
+ settings: Object.freeze({
282
+ get: () => asks('settings', {}),
283
+ onChange: listen(settingsChanges),
284
+ }),
285
+ // Coda's own collections, as a page watches the module's (`threads`: the sessions this machine lists), or a kind's
286
+ // records by its protocol's name.
287
+ watch: watching,
288
+ });
289
+ return { coda, views, protocols, operations, services, querying, calling, spawnFor, settingsChanges };
290
+ }
291
+
292
+ // Loaded once, as the backend activates it (`activate`, the first time anything of it is needed); what else comes for it
293
+ // waits for the same. One that does not load is activated again, with another token.
294
+ function load(plugin, token) {
295
+ if (!loading.has(plugin.id)) {
296
+ const loaded = (async () => {
297
+ const made = codaFor(plugin, await parts, token);
298
+ try {
299
+ const module = await import(pathToFileURL(join(plugin.path, plugin.main)).href);
300
+ if (typeof module.activate !== 'function') throw new Error(`${plugin.main} 没有导出 activate`);
301
+ await module.activate(made.coda);
302
+ return { ...made, module };
303
+ } catch (error) { await made.services.close(); throw error; }
304
+ })();
305
+ loading.set(plugin.id, loaded);
306
+ loaded.catch(() => loading.delete(plugin.id));
307
+ }
308
+ return loading.get(plugin.id);
309
+ }
310
+ const activated = plugin => loading.get(plugin.id) ?? Promise.reject(new Error(`插件 ${plugin.id} 还没有激活`));
311
+
312
+ const handlers = {
313
+ start(params) {
314
+ api = params.api;
315
+ parts = Promise.all(params.parts.map(async ({ name, module, make }) => [name, (await import(module))[make]]));
316
+ },
317
+ // A plugin's module, loaded the first time anything of it is needed, or as soon as the backend has started.
318
+ async activate({ plugin, token }) { await load(plugin, token); },
319
+ async open({ instance, plugin, view, context, caller }) {
320
+ const { views } = await activated(plugin);
321
+ const provider = views.get(view);
322
+ if (!provider) throw new Error(`插件 ${plugin.id} 没有注册视图 ${view}`);
323
+ const listeners = { message: new Set(), context: new Set(), close: new Set() }, collections = new Map();
324
+ // A collection of the page's: each object set whole, the page told whether it is new, changed or gone.
325
+ const collection = name => {
326
+ if (typeof name !== 'string' || !NAME.test(name)) throw new TypeError('集合名是小写字母、数字和「-」,以字母开头,至多 40 个字符');
327
+ if (!collections.has(name)) collections.set(name, new Map());
328
+ const objects = collections.get(name);
329
+ const tell = (type, id, object) => send({ method: 'change', params: { instance, collection: name, type, id, object } });
330
+ const key = id => {
331
+ if (typeof id !== 'string' || !id || id.length > 200) throw new TypeError('对象的 id 须为不超过 200 字的字符串');
332
+ return id;
333
+ };
334
+ return Object.freeze({
335
+ set(id, object) {
336
+ key(id);
337
+ if (!object || typeof object !== 'object' || Array.isArray(object)) throw new TypeError('对象须为 JSON 对象');
338
+ const json = JSON.stringify(object);
339
+ // Sized as its longest change, so that whatever it later is told as (changed, gone) reaches the page; refused
340
+ // before it is kept, so that setting it again is no change it never sent.
341
+ if (JSON.stringify({ change: { collection: name, type: 'MODIFIED', id, object } }).length > CHANGE_LIMIT) {
342
+ throw new RangeError(`对象过大:连同集合名与 id 超过 ${CHANGE_LIMIT / 1024} KiB`);
343
+ }
344
+ if (!instances.has(instance) || objects.get(id) === json) return false;
345
+ const type = objects.has(id) ? 'MODIFIED' : 'ADDED';
346
+ objects.set(id, json);
347
+ tell(type, id, JSON.parse(json));
348
+ return true;
349
+ },
350
+ delete(id) {
351
+ key(id);
352
+ if (!instances.has(instance) || !objects.has(id)) return false;
353
+ const json = objects.get(id);
354
+ objects.delete(id);
355
+ tell('DELETED', id, JSON.parse(json));
356
+ return true;
357
+ },
358
+ get: id => objects.has(id) ? JSON.parse(objects.get(id)) : undefined,
359
+ keys: () => [...objects.keys()],
360
+ });
361
+ };
362
+ const value = {
363
+ id: instance, view, context, caller: Object.freeze(caller ?? { local: true }),
364
+ postMessage(message) {
365
+ if (!instances.has(instance)) return false;
366
+ send({ method: 'post', params: { instance, message } });
367
+ return true;
368
+ },
369
+ onMessage: listen(listeners.message), onContext: listen(listeners.context), onClose: listen(listeners.close),
370
+ collection,
371
+ };
372
+ instances.set(instance, { value, listeners });
373
+ try { await provider.open(value); } catch (e) { instances.delete(instance); throw e; }
374
+ },
375
+ async contribute({ plugin, kind, key, object }) {
376
+ const { protocols } = await activated(plugin);
377
+ const handler = protocols.get(JSON.stringify([kind, key]));
378
+ if (!handler) throw new Error(`插件 ${plugin.id} 没有协议参与者 ${kind}/${key}`);
379
+ return handler(object, key);
380
+ },
381
+ // A query of a protocol the plugin implements (docs/plugins.md「调用」), by the unified call: its ID one of its caller's
382
+ // (`parent`) and request ID. Not handled, nothing was handed to the module.
383
+ async query({ plugin, request, deadline }, id) {
384
+ const controller = new AbortController();
385
+ cancels.set(id, controller);
386
+ try {
387
+ const made = await activated(plugin);
388
+ const handler = made.operations.get(JSON.stringify([request?.record?.kind, request?.operation]));
389
+ if (!handler) throw codaError('not_found', `插件 ${plugin.id} 没有实现 ${request?.record?.kind}/${request?.operation}`, { effects: 'none' });
390
+ return await handler.run(request.input,
391
+ contextOf({ id: queryId(request), record: request.record, deadline }, controller.signal, made, id));
392
+ } finally { cancels.delete(id); }
393
+ },
394
+ // A doing call of a protocol the plugin implements (docs/plugins.md「做事的操作」), as the backend hosts it
395
+ // (components/plugins/hosted-calls.mjs): `call` is `{ id, ref, record, operation, input, deadline }`, `ref` the call's on the call
396
+ // kernel (`{ from, id }`), which the doing calls its handler makes are made by. Its handler is given
397
+ // besides `progress`, said to the backend as it comes, and `ask`, answered as the backend passes the answer on (one at
398
+ // a time, as the backend has it: components/plugins/hosted-calls.mjs `question`). It ends with the call's outcome (`ending`). Not handled, nothing was done.
399
+ run({ plugin, call }, id) {
400
+ return handling(plugin, call, id, async (handler, signal, made) => {
401
+ if (!handler) return { outcome: 'failed', error: failureOf(codaError('not_found', `插件 ${plugin.id} 没有登记 ${call.record.kind}/${call.operation} 的处理函数`, { effects: 'none' })) };
402
+ const ctx = { ...doingOf(call, signal, made, id),
403
+ progress: value => send({ method: 'progress', params: { run: id, value } }),
404
+ async ask(question) {
405
+ signal.throwIfAborted();
406
+ // Given up as the call is: with the reason it goes off with, the backend told (`cancel`). What listens for that
407
+ // goes once the question is answered, the call's signal left as it was.
408
+ let given;
409
+ const off = new Promise((_, reject) => signal.addEventListener('abort', given = () => reject(signal.reason), { once: true }));
410
+ try { return await Promise.race([off, ask('question', { run: id, question }, signal)]); } finally {
411
+ signal.removeEventListener('abort', given);
412
+ }
413
+ } };
414
+ return ending(() => handler.run(call.input, ctx), signal);
415
+ });
416
+ },
417
+ // A doing call left by a host process that ended before its handler did (coda#2749 3.6), handed to its operation's
418
+ // `resume` in this one: `call` is `{ id, ref, record, operation, input, deadline, progress, canceled, halted }`, `halted`
419
+ // why its `ctx.signal` has gone off already (asked to be cancelled, or past its deadline, as `cancel`'s reason
420
+ // crosses), or none. `resume` is given the call as `Interrupted` and a `ctx` as a query's handler is with `call`, and ends it as
421
+ // `run` does; with none, null, for the backend to end it as it does then. Its `ctx.call` makes calls as the call's, as `run`'s
422
+ // does: one made again by the same `id` is the one it made before the process ended.
423
+ resume({ plugin, call }, id) {
424
+ return handling(plugin, call, id, async (handler, signal, made) => {
425
+ if (!handler?.resume) return null;
426
+ const { id: callId, record, operation: op, input, progress, canceled } = call;
427
+ return ending(() => handler.resume({ id: callId, record, op, input, progress, canceled, children: [] }, doingOf(call, signal, made, id)), signal);
428
+ }, call.halted);
429
+ },
430
+ // Called off: a query is let go at once, its handler's answer, if one comes, dropped by the backend; a doing call is
431
+ // given the time the backend gives it to end.
432
+ cancel({ id, reason }) {
433
+ const controller = cancels.get(id);
434
+ cancels.delete(id);
435
+ controller?.abort(canceled(reason));
436
+ },
437
+ // How a doing call the module made goes, as its callee says (`call`'s `progress`).
438
+ callProgress({ id, value }) { asked.get(id)?.progress?.(value); },
439
+ message({ instance, message }) {
440
+ const shown = instances.get(instance);
441
+ if (shown) fire(shown.listeners.message, message);
442
+ },
443
+ context({ instance, context }) {
444
+ const shown = instances.get(instance);
445
+ if (shown) { shown.value.context = context; fire(shown.listeners.context, context); }
446
+ },
447
+ // The plugin's settings were written: told to its module's listeners, once it has activated (one that did not has none).
448
+ async settingsChanged({ plugin, settings }) {
449
+ const made = await loading.get(plugin)?.catch(() => null);
450
+ if (made) fire(made.settingsChanges, settings);
451
+ },
452
+ close({ instance }) {
453
+ const shown = instances.get(instance);
454
+ if (shown) { instances.delete(instance); fire(shown.listeners.close); }
455
+ },
456
+ // Of a process a module started: its output, and its end (adapters/process-relay.mjs).
457
+ output({ process, stream, data, end }) { processes.get(process)?.output(stream, end ? null : data); },
458
+ exited({ process, code, signal }) { processes.get(process)?.exit({ code, signal }); },
459
+ // Coda's objects moved: each watcher told, in turn.
460
+ changed({ watch: key, events }) {
461
+ const watched = watches.get(key);
462
+ if (!watched || !Array.isArray(events)) return;
463
+ for (const event of events) {
464
+ if (event.type === 'DELETED') watched.objects.delete(event.id); else watched.objects.set(event.id, event.object);
465
+ fire(watched.listeners, told(watched, event.type, event.id, event.object));
466
+ }
467
+ },
468
+ };
469
+
470
+ async function receive(message) {
471
+ if (!message || typeof message !== 'object') return;
472
+ // An answer to what this host asked.
473
+ if (!message.method) {
474
+ const waiting = asked.get(message.id);
475
+ asked.delete(message.id);
476
+ if (message.error !== undefined) waiting?.reject(failed(message.error)); else waiting?.resolve(message.result);
477
+ return;
478
+ }
479
+ const { id, method, params } = message;
480
+ try {
481
+ const handler = handlers[method];
482
+ if (!handler) throw new Error(`插件宿主不认识 ${method}`);
483
+ const result = await handler(params ?? {}, id);
484
+ if (id !== undefined) send({ id, result: result ?? null });
485
+ } catch (e) {
486
+ if (id !== undefined) send({ id, error: method === 'query' ? failureOf(e, 'none') : String(e?.message ?? e) }); else console.error(e);
487
+ }
488
+ }
489
+ // Each module loaded ends what it started that is not in the host's group (`deactivate`, as VS Code's), once; the
490
+ // processes the backend started for them are the backend's to end, and their handles here end at once.
491
+ let stopping = null;
492
+ const stop = () => stopping ??= Promise.allSettled([...processes.values()].map(entry => entry.interrupt())
493
+ .concat([...loading.values()].map(async loaded => {
494
+ const { module, services, settingsChanges } = await loaded;
495
+ settingsChanges.clear();
496
+ await services.close(false);
497
+ if (typeof module?.deactivate === 'function') await module.deactivate();
498
+ })));
499
+ function adopt(plugin, token) {
500
+ const made = codaFor(plugin, [], token);
501
+ loading.set(plugin.id, Promise.resolve(made));
502
+ return made.coda;
503
+ }
504
+ return { receive, stop, adopt };
505
+ }
@@ -0,0 +1,53 @@
1
+ import { createServer } from 'node:http';
2
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
3
+ import { checkServiceId } from '../domain/plugin-services.mjs';
4
+
5
+ // One plugin's local handlers. Only connection metadata crosses the host's IPC, asked as the plugin (`ask`, with its token).
6
+ export function pluginServices(ask) {
7
+ const services = new Map();
8
+ let closed = false;
9
+ async function register(id, handler) {
10
+ if (closed) throw new Error('插件服务已关闭');
11
+ checkServiceId(id);
12
+ if (typeof handler !== 'function') throw new TypeError('services.register(id, handler)');
13
+ if (services.has(id)) throw new TypeError(`服务已登记:${id}`);
14
+ const secret = randomBytes(32).toString('hex'), expected = Buffer.from(`Bearer ${secret}`);
15
+ const server = createServer(async (req, res) => {
16
+ const auth = Buffer.from(req.headers.authorization ?? '');
17
+ if (auth.length !== expected.length || !timingSafeEqual(auth, expected)) { res.writeHead(401); res.end(); return; }
18
+ let caller;
19
+ try { caller = JSON.parse(Buffer.from(req.headers['x-coda-caller'] ?? '', 'base64url').toString()); }
20
+ catch { res.writeHead(400); res.end(); return; }
21
+ delete req.headers.authorization; delete req.headers['x-coda-caller'];
22
+ try { await handler(req, res, Object.freeze(caller)); }
23
+ catch (error) {
24
+ console.error('插件流式服务出错:', error);
25
+ if (!res.headersSent) { res.writeHead(500); res.end(); } else res.destroy();
26
+ }
27
+ });
28
+ // Streams have no endpoint command deadline. The backend still bounds headers.
29
+ server.requestTimeout = 0;
30
+ const close = () => { server.closeAllConnections(); return new Promise(resolve => server.close(resolve)); };
31
+ services.set(id, close);
32
+ try {
33
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
34
+ await ask('serviceRegister', { id, port: server.address().port, secret });
35
+ } catch (error) { services.delete(id); await close(); throw error; }
36
+ let disposed = false;
37
+ return { async dispose() {
38
+ if (disposed || closed) return;
39
+ disposed = true;
40
+ await ask('serviceUnregister', { id });
41
+ services.delete(id);
42
+ await close();
43
+ } };
44
+ }
45
+ return { api: Object.freeze({ register }), async close(unregister = true) {
46
+ closed = true;
47
+ for (const [id, close] of services) {
48
+ if (unregister) await ask('serviceUnregister', { id });
49
+ await close();
50
+ }
51
+ services.clear();
52
+ } };
53
+ }