@coda-console/plugin-check 0.8.22 → 0.8.24

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.
@@ -7,6 +7,7 @@
7
7
  import { CORE_PROTOCOLS } from '@coda-console/protocol/protocol';
8
8
  import { pointProblem, valueProblem } from '@coda-console/protocol/validate';
9
9
  import { requireCondition as check } from '../../domain/errors.mjs';
10
+ import { payloadProblem } from '../protocols/protocol-events.mjs';
10
11
 
11
12
  const code = 'invalid_plugin';
12
13
 
@@ -97,7 +98,7 @@ export function implementsMissing(plugin, plugins, defined) {
97
98
  }
98
99
  // This Coda's API Level (docs/plugins.md「兼容」): what it offers plugins, counted. A manifest's `engines.coda` names the least
99
100
  // a plugin needs; one naming none needs 0, which any Coda has.
100
- export const API_LEVEL = 1;
101
+ export const API_LEVEL = 2;
101
102
  // The API Level a package's registry metadata asks for in its `engines`: a positive integer, or its digits as text (what
102
103
  // npm's registry may make of one); undefined when it asks for none, null when it is anything else. A manifest read from
103
104
  // its directory has the schema's shape (plugin-rules.mjs readPlugin).
@@ -107,12 +108,17 @@ export function wantedLevel(engines) {
107
108
  if (Number.isInteger(value) && value >= 1) return value;
108
109
  return typeof value === 'string' && /^[1-9][0-9]{0,8}$/.test(value) ? Number(value) : null;
109
110
  }
111
+ // The keys of `contributes` Coda once read and no longer does: a manifest still writing one was made for what Coda took away.
112
+ const RETIRED_CONTRIBUTES = ['endpoints', 'groups', 'events'];
113
+ // Those of them `contributes` writes, a manifest's or a version's registry metadata: what either is read with as its `retired`.
114
+ export const retiredContributes = contributes => RETIRED_CONTRIBUTES.filter(key => Object.hasOwn(contributes ?? {}, key));
110
115
  // Whether a plugin runs on this machine (docs/plugins.md「兼容」): the one judgment reading a source, installing, the store and
111
116
  // the catalog take. Null when it does; else what it needs (`need`), what is missing (`missing`) and why, as the user is
112
117
  // told (`error`). `host`: this machine — its API Level (`level`), its backend's channel, the catalog beside the plugin and
113
118
  // Coda's own protocols (`defined`, as usesMissing takes them). A Level above this Coda's is Coda's to catch up with
114
- // (`coda`); short of that, a channel it is not for, or a protocol or permission group it uses or a protocol it implements
115
- // that is not here, is the plugin's to update (`update`): Coda no longer offers what it was made for.
119
+ // (`coda`); short of that, a channel it is not for, a key of `contributes` Coda retired, or a protocol or permission group
120
+ // it uses or a protocol it implements that is not here, is the plugin's to update (`update`): Coda no longer offers what it
121
+ // was made for.
116
122
  export function compatibility(plugin, { catalog = new Map(), defined = () => null, ...here }) {
117
123
  const own = ownIncompatibility(plugin, here);
118
124
  if (own) return own;
@@ -123,10 +129,13 @@ export function compatibility(plugin, { catalog = new Map(), defined = () => nul
123
129
  : coda ? `本机的 Coda 已不提供协议 ${protocol},插件需要更新` : `${used ? '用到' : '实现'}的协议 ${protocol} 不在这台机器上,也不随它一起装`;
124
130
  return { need: 'update', missing, error };
125
131
  }
126
- // What of that a plugin answers by itself, whatever else is here: the API Level it needs, the channels it is for.
132
+ // What of that a plugin answers by itself, whatever else is here: the API Level it needs, the channels it is for, the keys of
133
+ // `contributes` Coda retired it still writes (`retired`).
127
134
  export function ownIncompatibility(plugin, { level = API_LEVEL, channel = null }) {
128
135
  const wanted = plugin.engines?.coda ?? 0;
129
136
  if (wanted > level) return { need: 'coda', missing: { level: wanted }, error: `这个版本要 Coda API Level ≥ ${wanted}(本机 ${level}),请先升级 Coda` };
137
+ const retired = plugin.retired?.[0];
138
+ if (retired) return { need: 'update', missing: { contribution: retired }, error: `本机的 Coda 已不提供 contributes.${retired},插件需要更新` };
130
139
  const channelProblem = pluginChannelProblem(plugin, channel);
131
140
  return channelProblem ? { need: 'update', missing: { channel }, error: channelProblem } : null;
132
141
  }
@@ -141,13 +150,45 @@ export function installingIncompatibility(catalog, installed, id, here) {
141
150
  }
142
151
  return null;
143
152
  }
153
+ // Whether plugin `plugin` (its catalog entry) defines kind `kind` or implements it: what it may reach of it and the events it may publish.
154
+ export const ownsProtocol = (plugin, kind) =>
155
+ (plugin.protocols ?? []).some(one => one.name === kind) || (plugin.protocolImplementations ?? []).some(one => one.kind === kind);
156
+ // What an event is about: `<kind>:<ID>`, at most 500 characters.
157
+ const SUBJECT = /^(?=.{3,500}$)[a-z][a-z0-9_-]*:\S+$/;
158
+ // Why plugin `plugin` (its catalog entry) may not publish (by `how`: publish-event, coda event, coda.emit) event `name`
159
+ // about `subject`, saying `payload`, or null — `event` the event of that name on this machine (components/protocols/
160
+ // protocol-events.mjs), or none: it is one of a protocol the plugin defines or implements and not Coda's own (`codaOnly`:
161
+ // application/host-protocols.mjs; a plugin implementing coda/thread@1 publishes no session's), about a subject it names (not a
162
+ // session's: `thread:` is Coda's), saying a JSON object its payload schema has, no more than 100 KB of it and nothing of
163
+ // `coda` (Coda's, beside it in a run). Where it is published is the backend's to check, as the backend and the plugin host
164
+ // for a plugin's tests (adapters/plugin-test-host.mjs) both check the rest.
165
+ export function publishedProblem(how, plugin, event, { name, subject, payload }) {
166
+ if (!event || !ownsProtocol(plugin, event.kind)) return `插件 ${plugin.id} 定义或实现的协议里没有事件 ${name}`;
167
+ if (event.codaOnly) return `插件 ${plugin.id} 不能发布事件 ${name}:它是 Coda 自己的协议 ${event.kind} 的,只由 Coda 发布`;
168
+ if (typeof subject !== 'string' || !SUBJECT.test(subject) || subject.startsWith('thread:'))
169
+ return `${how} 的 subject 须为「<种类>:<标识>」(如 pull_request:<地址>),不超过 500 个字符;thread: 是会话的,由 Coda 发布`;
170
+ if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) return `${how} 的 payload 须为 JSON 对象`;
171
+ if (JSON.stringify(payload).length > 100_000) return `${how} 的 payload 不能超过 100 KB`;
172
+ if (Object.hasOwn(payload, 'coda')) return `${how} 的 payload 顶层不能有 coda,那是 Coda 的`;
173
+ const problem = payloadProblem(event, payload);
174
+ return problem && `${how} 的 payload ${problem}`;
175
+ }
176
+ // The events plugin `plugin` (its catalog entry) subscribes to: those of the event groups it uses of the protocols this
177
+ // machine has with `plugins` (the catalog) and Coda's own (`defined`, as `protocolDefinition` takes them). What its module
178
+ // may handle (`coda.on`), as the backend delivers them (./plugin-events.mjs) and the plugin host for a plugin's tests has it.
179
+ export function subscribed(plugin, plugins, defined) {
180
+ return Object.entries(plugin.uses ?? {}).flatMap(([kind, groups]) => {
181
+ const permissions = protocolDefinition(kind, plugins, defined)?.permissions ?? {};
182
+ return groups.flatMap(group => permissions[group]?.events ?? []);
183
+ });
184
+ }
144
185
  // Why plugin `plugin` (its catalog entry) may not reach kind `kind` as `need` says — an operation of it (`{ operation }`),
145
186
  // a stream of its records (`{ stream }`), or reading its records (`'read'`; writing them is the implementer's alone) —
146
187
  // `definition` its protocol's (`protocolDefinition`), or null (docs/plugins.md「用到的权限」). The plugin that implements or
147
188
  // defines the kind may; any other, a built-in one too, only by a group of the kind's it uses that has the operation or the
148
189
  // stream, or reads its records. An operation or a stream in no group is open to no plugin.
149
190
  export function usesRefusal(plugin, kind, need, definition) {
150
- if ((plugin.protocols ?? []).some(one => one.name === kind) || (plugin.protocolImplementations ?? []).some(one => one.kind === kind)) return null;
191
+ if (ownsProtocol(plugin, kind)) return null;
151
192
  const groups = Object.entries(definition?.permissions ?? {}), used = new Set(plugin.uses?.[kind] ?? []);
152
193
  const covers = ([, group]) => typeof need === 'string' ? group[need] === true
153
194
  : need.stream !== undefined ? (group.streams ?? []).includes(need.stream) : (group.operations ?? []).includes(need.operation);
@@ -9,23 +9,21 @@
9
9
  // gives), and that its settings are named under it.
10
10
  // A secret (`writeOnly`) is a text written and never read back, kept in a file beside the database and given to the
11
11
  // plugin's processes as that file's path (`CODA_PLUGIN_SECRETS`).
12
- import { readFileSync, readdirSync, existsSync } from 'node:fs';
12
+ import { readFileSync, readdirSync, existsSync, statSync } from 'node:fs';
13
13
  import { join, normalize, posix } from 'node:path';
14
14
  import { fileURLToPath } from 'node:url';
15
15
  import { requireCondition as check, ContractError } from '../../domain/errors.mjs';
16
- import { isDuration } from '../../domain/duration.mjs';
16
+ import { durationMs, isDuration } from '../../domain/duration.mjs';
17
17
  import { AGENT_ID } from '../../domain/values.mjs';
18
18
  import { THREAD_ENV, TOKEN_ENV } from '../../domain/session-env.mjs';
19
19
  import { iconFiles } from './plugin-icons.mjs';
20
- import { checkCatalog, extensionsFor } from './plugin-extensions.mjs';
20
+ import { checkCatalog, extensionsFor, retiredContributes } from './plugin-extensions.mjs';
21
21
  import { contributionProblem, manifestProblem, TYPES } from '@coda-console/protocol/validate';
22
22
  import { ownedProtocolsProblem } from '@coda-console/protocol/protocol';
23
23
  import { claims, COMMIT, INTEGRITY, NPM_VERSION, npmPluginId, repoAddress, sourcePath } from './plugin-source-rules.mjs';
24
24
  import { CONTRIBUTION_POINTS } from './contribution-points.mjs';
25
25
 
26
26
  const ID = /^[a-z][a-z0-9-]{0,39}$/;
27
- // The domains of the events Coda publishes itself; a plugin's are of a domain of its own (schemas/events.json).
28
- export const CODA_EVENT_DOMAINS = ['workflow', 'session', 'user'];
29
27
  // Plugins that ship with Coda, as VS Code's built-in extensions ship with it: updated with Coda itself.
30
28
  export const BUILTIN_DIR = fileURLToPath(new URL('../../resources/plugins/', import.meta.url));
31
29
  // The package the backend runs from (the runtime clone's, or the release's), whose npm dependencies may be built-in plugins
@@ -35,6 +33,8 @@ const PACKAGE_ROOT = fileURLToPath(new URL('../../../', import.meta.url));
35
33
  // contribution point's (contribution-points.mjs), or for a point another plugin declares to take it (the resources
36
34
  // plugin's `panels`), refused when neither does.
37
35
  export const CONTRIBUTES = TYPES;
36
+ // The shortest a kind's records are given again by its command on their own (`contributes.records`' `every`).
37
+ const EVERY_LEAST = 60_000;
38
38
  export const MODEL_PROVIDER = /^[a-z][a-z0-9-]{0,39}\/[a-z][a-z0-9-]{0,39}$/;
39
39
  // How many model services a setting of several may name.
40
40
  const MODEL_PROVIDERS_AT_MOST = 20;
@@ -116,6 +116,7 @@ export function readPlugin(dir, source, points = CONTRIBUTION_POINTS) {
116
116
  const contributes = manifest.contributes ?? {}, configuration = contributes.configuration ?? {};
117
117
  const protocolsProblem = ownedProtocolsProblem({ id, contributes: { protocols: contributes.protocols } });
118
118
  check(!protocolsProblem, 'invalid_plugin', protocolsProblem);
119
+ const records = recordCommands(contributes, dir), self = selfCommands(contributes, dir), retired = retiredContributes(contributes);
119
120
  const properties = Object.fromEntries(Object.entries(configuration.properties ?? {}).map(([key, value]) => {
120
121
  check(key.split('.')[0] === id, 'invalid_plugin', `设置名须以「${id}.」开头:${key}`);
121
122
  return [key, setting(value, key)];
@@ -133,6 +134,7 @@ export function readPlugin(dir, source, points = CONTRIBUTION_POINTS) {
133
134
  ...(manifest.coda !== undefined ? { coda: manifest.coda } : {}),
134
135
  // The API Level it needs (plugin-extensions.mjs compatibility).
135
136
  ...(manifest.engines?.coda !== undefined ? { engines: { coda: manifest.engines.coda } } : {}),
137
+ ...(retired.length ? { retired } : {}),
136
138
  // The permission groups of others' protocols it uses (docs/plugins.md「用到的权限」), by protocol: checked against the
137
139
  // catalog it is installed into, and whenever the catalog is read (plugin-extensions.mjs compatibility).
138
140
  ...(manifest.uses && Object.keys(manifest.uses).length ? { uses: structuredClone(manifest.uses) } : {}),
@@ -140,13 +142,14 @@ export function readPlugin(dir, source, points = CONTRIBUTION_POINTS) {
140
142
  ...(required.length ? { required: [...required] } : {}), workflows: files('.coda/workflows'),
141
143
  services: [...(contributes.services ?? [])],
142
144
  ...read,
143
- endpoints: (contributes.endpoints ?? []).map(e => ({ id: e.id, command: e.command })),
144
145
  // The entry as one path in its directory (`./view/a.html`, `view//a.html` are `view/a.html`): the clients load it by that.
145
146
  views: (contributes.views ?? []).map(v => ({ id: v.id, title: v.title, entry: posix.normalize(v.entry), ...(v.in?.length ? { in: [...v.in] } : {}),
146
147
  ...(v.icon ? { icon: v.icon } : {}), ...(v.handles?.length ? { handles: [...v.handles] } : {}), ...(v.readout ? { readout: v.readout } : {}),
147
148
  ...(v.checkout ? { checkout: v.checkout } : {}), ...(v.frame ? { frame: v.frame } : {}), ...(v.provides?.length ? { provides: [...v.provides] } : {}) })),
148
149
  ...(contributes.protocols?.length ? { protocols: structuredClone(contributes.protocols) } : {}),
149
150
  ...(contributes.protocolImplementations?.length ? { protocolImplementations: implementations(contributes.protocolImplementations) } : {}),
151
+ ...(records.length ? { records } : {}),
152
+ ...(Object.keys(self).length ? { self } : {}),
150
153
  ...(Object.keys(offers).length ? { offers } : {}),
151
154
  dependencies: [...dependencies], extensionPoints: extensionPoints(contributes.extensionPoints, dir),
152
155
  extensions: Object.entries(contributes.extensions ?? {}).map(([key, value]) => { const [plugin, point] = key.split('/'); return { plugin, point, command: value.command }; }),
@@ -292,6 +295,38 @@ export function pluginEnv({ catalog, installed, id, stateDir = () => null, setti
292
295
  // (docs/plugins.md「用命令实现操作」). The test host (adapters/plugin-test-host.mjs) reads a manifest's with it too.
293
296
  export const implementations = entries => entries
294
297
  .map(entry => typeof entry === 'string' ? { kind: entry, commands: {} } : { kind: entry.kind, commands: { ...entry.commands } });
298
+ // A manifest's `contributes.records` as Coda keeps it (docs/plugins.md「命令写记录」), each `{ kind, command, every? }`, `every`
299
+ // in milliseconds: the kinds its commands give the records of, each one it implements (`protocolImplementations`, as only
300
+ // a plugin implementing a kind holds its records), given again no oftener than EVERY_LEAST. The file is one it runs itself (`runnable`).
301
+ function recordCommands(contributes, dir) {
302
+ const implemented = new Set(implementations(contributes.protocolImplementations ?? []).map(entry => entry.kind));
303
+ return (contributes.records ?? []).map(({ kind, command, every }, i) => {
304
+ const where = `contributes.records 第 ${i + 1} 项(${kind})`;
305
+ check(implemented.has(kind), 'invalid_plugin', `contributes.records 第 ${i + 1} 项的种类 ${kind} 不在这个插件的 protocolImplementations 里`);
306
+ let ms = null;
307
+ if (every !== undefined) {
308
+ try { ms = durationMs(every); } catch { ms = NaN; }
309
+ check(Number.isSafeInteger(ms), 'invalid_plugin', `${where}的 every ${every} 不是能用的时长`);
310
+ }
311
+ runnable(dir, command, where);
312
+ check(ms === null || ms >= EVERY_LEAST, 'invalid_plugin', `${where}的 every ${every} 短于 PT1M`);
313
+ return { kind, command, ...(ms === null ? {} : { every: ms }) };
314
+ });
315
+ }
316
+ // A manifest's `contributes.self` as Coda keeps it (docs/plugins.md「只给自己用的查询」): by name, the file in its directory
317
+ // that answers its own query of that name, before its module (plugin-host.mjs `querySelf`); each one it runs itself (`runnable`).
318
+ function selfCommands(contributes, dir) {
319
+ const self = { ...contributes.self };
320
+ for (const [name, command] of Object.entries(self)) runnable(dir, command, `contributes.self「${name}」`);
321
+ return self;
322
+ }
323
+ // A file of a plugin's that Coda runs itself (adapters/plugin-command.mjs fileCommand), there in its directory as the schema
324
+ // checks: executable, starting with `#!`; refused naming `where` it is written.
325
+ function runnable(dir, command, where) {
326
+ const path = join(dir, command);
327
+ check(statSync(path).mode & 0o111, 'invalid_plugin', `${where}的 ${command} 不可执行`);
328
+ check(readFileSync(path).subarray(0, 2).toString('latin1') === '#!', 'invalid_plugin', `${where}的 ${command} 不以 #! 开头`);
329
+ }
295
330
  // The file in its directory that implements an operation of a protocol the plugin implements (`protocolImplementations`'
296
331
  // `commands`), or null: its module's, or not the plugin's at all.
297
332
  export function commandOf(plugin, kind, operation) {
@@ -9,6 +9,7 @@ import { normalize } from 'node:path';
9
9
  import { requireCondition as check } from '../../domain/errors.mjs';
10
10
  import { installingIncompatibility, offerPoint, offeredCommands, offerProblem, protocolDefinition, withDependencies } from './plugin-extensions.mjs';
11
11
  import { CONTRIBUTION_POINTS } from './contribution-points.mjs';
12
+ import { definedEvents, eventsProblem } from '../protocols/protocol-events.mjs';
12
13
 
13
14
  export const COMMIT = /^[0-9a-f]{40}$/;
14
15
  const ID = /^[a-z][a-z0-9-]{0,39}$/;
@@ -266,7 +267,7 @@ export const claims = plugin => [...[...CONTRIBUTION_POINTS.values()].flatMap(po
266
267
  // Why a plugin cannot sit beside those this machine has (`catalog`: built-in and installed, by ID; `builtin`: the plugins
267
268
  // Coda ships, by ID), or null: an installed built-in one's ID from another source (builtinProblem), what a component's
268
269
  // contribution point lets only a built-in plugin bring (its `builtinOnly`, of the plugin read: why, none when it brings none
269
- // of it), or what only one plugin may declare (claims) another plugin declares. What it needs of the others — the plugins it depends on,
270
+ // of it), or what only one plugin may declare (claims), a protocol or an event of one, another plugin declares. What it needs of the others — the plugins it depends on,
270
271
  // the points it plugs into or writes for (plugin-extensions.mjs offerProblem) — is checked once all of them are there.
271
272
  export function catalogProblem(plugin, catalog, builtin, installed) {
272
273
  const named = builtinProblem(plugin.id, plugin.source, builtin, installed);
@@ -285,7 +286,14 @@ export function catalogProblem(plugin, catalog, builtin, installed) {
285
286
  const owner = [...catalog.values()].find(p => p.id !== plugin.id && p.protocols?.some(other => other.name === definition.name));
286
287
  if (owner) return `协议 ${definition.name} 已由插件 ${owner.displayName} 定义`;
287
288
  }
288
- return null;
289
+ // An event is known by its name on this machine (components/protocols/protocol-events.mjs): one protocol's alone.
290
+ const events = definedEvents(plugin), again = events.find((name, i) => events.indexOf(name) !== i);
291
+ if (again) return `事件 ${again} 在插件的两个协议里都定义了`;
292
+ for (const name of events) {
293
+ const owner = [...catalog.values()].find(p => p.id !== plugin.id && definedEvents(p).includes(name));
294
+ if (owner) return `事件 ${name} 已由插件 ${owner.displayName} 的协议定义`;
295
+ }
296
+ return eventsProblem(plugin);
289
297
  }
290
298
  // What installing a plugin from a repository brings along, in the order installing does it (components/plugins/plugin-extensions.mjs
291
299
  // withDependencies, as components/plugins/plugins.mjs installFrom): what this version of it needs, directly or through another,
@@ -311,7 +319,8 @@ export function catalogAfter(plugin, { catalog, siblings }) {
311
319
  // What installing it brings, as the confirmation lists it: every command it runs, word for word (those it plugs into
312
320
  // another plugin's points too, which that plugin runs — those it writes for a point under a key of `contributes`, where
313
321
  // the point says, the catalog beside it (`catalog`) declaring it —, those it puts on every session's PATH, those
314
- // answering clients' requests, those implementing operations of its protocols (by kind, operation and file), and the one that makes each
322
+ // answering clients' requests, those implementing operations of its protocols (by kind, operation and file), those giving
323
+ // the records of its kinds and answering its own queries, and the one that makes each
315
324
  // machine ready for it, run as it is installed or updated), what a component's contribution point confirms (its
316
325
  // `confirm`: its agents and the commands it puts on sessions' PATH, the Agent Skills it lays into projects, the MCP
317
326
  // servers their agents start and what it tells every agent; the groups it brings, what it calls its capabilities; the
@@ -327,9 +336,12 @@ export function contributions(plugin, catalog = new Map(), defined = () => null)
327
336
  // directories it puts on their PATH.
328
337
  ...(plugin.environment?.length ? { environment: plugin.environment.map(({ name, value }) => ({ name, value })) } : {}),
329
338
  ...(plugin.path?.length ? { path: plugin.path } : {}),
330
- ...(plugin.endpoints?.length ? { endpoints: plugin.endpoints.map(e => ({ id: e.id, command: e.command })) } : {}),
331
339
  // The files in its directory the backend runs as Coda calls an operation of a protocol it implements (docs/plugins.md「用命令实现操作」).
332
340
  ...(operationCommands(plugin).length ? { operations: operationCommands(plugin) } : {}),
341
+ // The files it runs to give the records of a kind it implements (docs/plugins.md「命令写记录」), by kind, and those
342
+ // answering its own queries (docs/plugins.md「只给自己用的查询」), by name.
343
+ ...(plugin.records?.length ? { records: plugin.records.map(({ kind, command }) => ({ kind, command })) } : {}),
344
+ ...(plugin.self ? { self: Object.entries(plugin.self).map(([name, command]) => ({ name, command })) } : {}),
333
345
  // Its module the plugin host runs (docs/plugins.md「插件宿主」): code of its own in Coda's Node on this machine.
334
346
  ...(plugin.main ? { main: plugin.main } : {}),
335
347
  // The pages it opens in the clients, by name, with where they stay and their icon there: they run in the client's
@@ -0,0 +1,49 @@
1
+ // The events of this machine's protocols (docs/plugins.md「事件」), each as its protocol's definition says it (`events`,
2
+ // @coda-console/protocol definition.json): those of Coda's own definitions (application/host-protocols.mjs),
3
+ // and those the plugins of the catalog define. An event is known by its name, one on this machine: a plugin defining one
4
+ // another plugin's protocol has is refused as it is installed (components/plugins/plugin-source-rules.mjs catalogProblem).
5
+ // Its version is its protocol's major version.
6
+ import { newAjv } from '@coda-console/protocol/validate';
7
+
8
+ // The events of protocol `kind` (`events` as its definition has them), each `{ name, kind, payload, starts, ends, codaOnly }`:
9
+ // `payload`, the JSON Schema of what it says; `starts`, whether it may start a workflow's run (false: only handed to those
10
+ // going for its subject already); `ends`, whether it ends its subject; `codaOnly`, whether the protocol is Coda's own, its
11
+ // events Coda's alone to publish.
12
+ const eventsOf = (kind, events = {}, codaOnly = false) => Object.entries(events).map(([name, event]) =>
13
+ ({ name, kind, payload: event.payload, starts: event.starts !== false, ends: event.ends === true, codaOnly }));
14
+
15
+ // The names of the events a plugin's own protocols define.
16
+ export const definedEvents = plugin => (plugin.protocols ?? []).flatMap(definition => Object.keys(definition.events ?? {}));
17
+
18
+ // Every event on this machine, by name: of Coda's definitions `coda` (each `{ kind, events }`) and those of
19
+ // the plugins of `catalog` (plugin ID → its catalog entry). Coda's own are never another's: a definition of the same name
20
+ // does not take one of them over.
21
+ export function protocolEvents(catalog, coda = []) {
22
+ return new Map([...[...catalog.values()].flatMap(plugin => (plugin.protocols ?? []).flatMap(({ name, events }) => eventsOf(name, events))),
23
+ ...[...coda].flatMap(({ kind, events }) => eventsOf(kind, events, true))]
24
+ .map(event => [event.name, event]));
25
+ }
26
+
27
+ // The check of what an event says (`payload`, its JSON Schema), compiled the one way it is here, as the protocol package
28
+ // compiles a definition's schemas (@coda-console/protocol protocol.mjs definitionProblem): as installing it and reading
29
+ // the catalog again check (eventsProblem), as it is published (payloadProblem). Once each, as long as it is read; throws
30
+ // when it does not compile.
31
+ const ajv = newAjv({ ownProperties: true, addUsedSchema: false, strict: false }), compiled = new WeakMap();
32
+ function payloadCheck(payload) {
33
+ if (typeof payload !== 'object') return ajv.compile(payload);
34
+ if (!compiled.has(payload)) compiled.set(payload, ajv.compile(payload));
35
+ return compiled.get(payload);
36
+ }
37
+ // Why the payload schema of an event of a plugin's protocols does not compile here, or null.
38
+ export function eventsProblem(plugin) {
39
+ for (const { name, events = {} } of plugin.protocols ?? []) for (const [event, { payload }] of Object.entries(events)) {
40
+ try { payloadCheck(payload); } catch (e) { return `协议 ${name} 的事件 ${event} 的 payload 不是可用的 JSON Schema:${e.message}`; }
41
+ }
42
+ return null;
43
+ }
44
+ // Why what an event says is not as its payload schema has it, or null: the schema not compiling too.
45
+ export function payloadProblem(event, value) {
46
+ let check;
47
+ try { check = payloadCheck(event.payload); } catch (e) { return `没法按事件 ${event.name}(${event.kind})的格式查:它的 payload schema 编不过(${e.message})`; }
48
+ return check(value) ? null : `不合事件 ${event.name}(${event.kind})的格式:${ajv.errorsText(check.errors, { dataVar: 'payload' })}`;
49
+ }
@@ -1,5 +1,6 @@
1
1
  // What workflows take of plugins (components/plugins/contribution-points.mjs): the capabilities a plugin's workflows
2
- // stand for (schemas/capabilities.json) and the events it publishes (schemas/events.json), defined as this module loads.
2
+ // stand for (schemas/capabilities.json), defined as this module loads. The events it publishes are its protocols'
3
+ // (components/protocols/protocol-events.mjs).
3
4
  // Its concurrency groups are its coda/group@1 records (components/concurrency-groups/schemas.mjs), not of its manifest.
4
5
  // Descriptions only: nothing here imports a component, for the plugins read with them are read before any is made.
5
6
  import { defineContributionPoint } from '../plugins/contribution-points.mjs';
@@ -7,4 +8,3 @@ import { SCHEMAS } from '@coda-console/protocol/validate';
7
8
 
8
9
  defineContributionPoint({ key: 'capabilities', schema: SCHEMAS['capabilities.json'], read: (raw = []) => ({ capabilities: [...raw].sort() }),
9
10
  confirm: plugin => ({ capabilities: plugin.capabilities }) });
10
- defineContributionPoint({ key: 'events', schema: SCHEMAS['events.json'], read: raw => raw?.length ? { events: raw.map(e => ({ name: e.name, starts: e.starts !== false, ...(e.ends ? { ends: true } : {}) })) } : {} });