@coda-console/plugin-check 0.8.26 → 0.8.28

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.
@@ -1,6 +1,9 @@
1
- // 「运行时间」资源类型的取数命令:Coda 在打开资源页或点「刷新」时用 `sh -c` 运行它,标准输出就是资源的 JSON
2
- // (docs/plugins.md「资源」)。`node` 是 Coda 后端自己的 Node;只用 Node 自带的模块。
3
- // 读不懂的键会让这次读取失败;格式里没有说明性的字段,每个资源只有名字、读数、一行错误和按钮。
1
+ #!/usr/bin/env node
2
+ // 「运行时间」资源类型的记录命令(`coda/resource@1` 的记录,清单的 contributes.records):Coda 在启动、更新、设置改动、
3
+ // 动作之后与资源页打开、点「刷新」时运行它(清单里写 `every` 才另按周期运行)。标准输出是这个插件在这台机器上这一类的
4
+ // 整组记录:`[{ key, spec }]`,key 是类型 ID,spec.type 与它相同。`node` 是 Coda 后端自己的 Node;只用 Node 自带的模块。
5
+ // 读不懂的键会让这次写入失败;记录里没有说明性的字段,每个资源只有名字、读数、一行错误和按钮。
6
+ // 命令失败(退出 1,标准错误的最后一行写原因)就保留 Coda 已有的记录,不写空的。
4
7
  import { execFileSync } from 'node:child_process';
5
8
  import { readFileSync } from 'node:fs';
6
9
  import { cpus, loadavg, uptime } from 'node:os';
@@ -19,7 +22,7 @@ const since = seconds => {
19
22
  const days = Math.floor(seconds / 86400), hours = Math.floor(seconds % 86400 / 3600), minutes = Math.floor(seconds % 3600 / 60);
20
23
  return days ? `${days} 天 ${hours} 小时` : hours ? `${hours} 小时 ${minutes} 分钟` : `${minutes} 分钟`;
21
24
  };
22
- // 按钮动作记下的时刻,存在插件的状态目录里(CODA_PLUGIN_STATE,跨读取、跨版本保留)。
25
+ // 按钮动作(scripts/act.mjs)记下的时刻,存在插件的状态目录里(CODA_PLUGIN_STATE,跨读取、跨版本保留)。
23
26
  function marked() {
24
27
  try { return JSON.parse(readFileSync(join(process.env.CODA_PLUGIN_STATE, 'mark.json'), 'utf8')).at; } catch { return null; }
25
28
  }
@@ -32,4 +35,6 @@ const values = [
32
35
  { label: '已开机', value: since(up), time: new Date(Date.now() - up * 1000).toISOString() },
33
36
  ...(mark ? [{ label: '距上次记下', value: since((Date.now() - Date.parse(mark)) / 1000) }] : []),
34
37
  ];
35
- process.stdout.write(JSON.stringify({ resources: [{ values, actions: [{ label: '记下此刻', action: 'mark' }] }] }));
38
+ // 按钮调 `act` 操作(scripts/act.mjs)做 `mark`;confirm 是执行前问的话。
39
+ const buttons = [{ label: '记下此刻', action: 'mark', confirm: '记下此刻?\n之后显示距这次记下过了多久。' }];
40
+ process.stdout.write(JSON.stringify([{ key: 'uptime', spec: { type: 'uptime', title: '运行时间', resources: [{ values, buttons }] } }]));
@@ -1,313 +0,0 @@
1
- // The resource types installed plugins bring to this machine's resources page (docs/plugins.md「资源」), read and acted on
2
- // here, in the resources plugin's module: what each plugin declares comes from Coda's collection of the installed plugins
3
- // (`coda.watch("plugins")`), and each command runs with that plugin's own environment (`coda.environment(null, { plugin })`),
4
- // as Coda gives every process of the plugin's, with no token of its (docs/plugins.md「令牌」: a module never holds another
5
- // plugin's; the host is to run them, coda#2749 H9). A plugin declaring `resources` has those; one still declaring the panels
6
- // before them has its panels, read as they were (`format`), for the page to take as resources (docs/plugins.md「旧的面板」).
7
- // A type is read when a page asks (opening it, refreshing, an action), or, for a kind declaring `report`, on its period
8
- // while this machine shows it; nothing else is read in the background, and no reading is kept on disk.
9
- // What every type gets from here and not from its plugin: one reading at a time (a second ask joins it), the last good
10
- // reading shown again within the type's `maxAge` and listed with it, and on failure the last good one kept and marked as
11
- // such. The machine keeps which it shows and which not, in this plugin's state; their order is their plugins'
12
- // (docs/resources-page.md「顺序」). Inside, a type is still called a panel, as the page's view and its messages are.
13
- import { spawn, spawnSync } from 'node:child_process';
14
- import { readFileSync, writeFileSync, renameSync } from 'node:fs';
15
- import { tmpdir } from 'node:os';
16
- import { join } from 'node:path';
17
- import { runPluginCommand, settle } from '../../../../adapters/plugin-command.mjs';
18
- import { PanelError, panelDeclarations, panelItems, resourceItems, actionArgs, shownItems, displayOptions, keepMissingMetrics } from './rules.mjs';
19
- import { SignIn, authorizationLink, deviceCode } from './sign-in.mjs';
20
-
21
- const fail = (code, message) => { throw new PanelError(code, message); };
22
- // How a command starts here, in the plugin host's tree, whose root is registered: in a process group of its own, as the
23
- // backend's registry door starts one (adapters/process-start.mjs), registering nothing.
24
- const start = { spawn: (_owner, _entry, file, args, options) => spawn(file, args, { ...options, detached: true }), remove: () => {} };
25
-
26
- export class Panels {
27
- // `onChange(key)`: a panel moved (its reading, its login, whether it is hidden); none for the list as a whole.
28
- // `run`: how a command runs (adapters/plugin-command.mjs runPluginCommand, from its plugin's directory with its environment,
29
- // started here); `now()`: the time, as readings are dated by it.
30
- constructor(coda, { run = runPluginCommand, now = Date.now, readTimeoutMs = 30_000, actionTimeoutMs = 10 * 60_000, timer = true } = {}) {
31
- this.coda = coda; this.run = run; this.now = now; this.readTimeoutMs = readTimeoutMs; this.actionTimeoutMs = actionTimeoutMs; this.timerOn = timer;
32
- // `last`: each panel's last good items, for a failed reading to show again; `shown`: what its last reading answered.
33
- this.plugins = new Map(); this.last = new Map(); this.shown = new Map(); this.reading = new Map(); this.acting = new Map(); this.failures = new Map();
34
- this.logins = new Map(); this.envs = new Map(); this.listeners = new Set(); this.closing = new AbortController();
35
- this.file = join(coda.plugin.state ?? tmpdir(), 'hidden.json');
36
- this.hides = Promise.resolve();
37
- // The kind types this module reported, by kind (`{ plugin, type }`), and why an upload last failed, said once.
38
- this.reportedKinds = new Map(); this.reportSaid = new Map(); this.reportedAt = new Map(); this.timer = null;
39
- }
40
- listen(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn); }
41
- // Nothing is told before the plugins' environments are there (`ready`): what a login says of whether its program is
42
- // installed is checked with its plugin's own.
43
- changed(key = null) { if (this.ready) for (const fn of this.listeners) try { fn(key); } catch {} }
44
- // Once: the installed plugins watched, what this machine shows and hides, and the environment of each plugin whose panels sign in.
45
- start() {
46
- this.started ??= (async () => {
47
- this.choices = this.readHidden();
48
- const watched = await this.coda.watch('plugins', ({ type, id, object }) => {
49
- if (type === 'DELETED') this.plugins.delete(id); else this.plugins.set(id, object);
50
- // Another version (another directory, another environment): what was checked with the last is checked again.
51
- this.envs.delete(id);
52
- for (const [key, login] of this.logins) if (key.startsWith(`${id}/`)) login.recheck();
53
- // A login of a panel gone (its plugin removed, or a version without it) goes with it.
54
- const keys = new Set(this.installed().map(e => e.key));
55
- for (const [key, login] of this.logins) if (!keys.has(key)) { login.close(); this.logins.delete(key); }
56
- if (this.ready) this.prepare().then(() => { this.dropMissing(); this.forgetHidden(); this.changed(); });
57
- });
58
- this.unwatch = () => watched.dispose();
59
- await this.prepare();
60
- this.ready = true;
61
- // A kind declaring a report is read on its own period while this machine shows it (none before it is chosen).
62
- this.forgetHidden();
63
- if (this.timerOn) { this.timer = setInterval(() => this.tick(), 1000); this.timer.unref?.(); }
64
- })();
65
- return this.started;
66
- }
67
- // What the machine was told to hide or show, by panel: none when nothing is, or what is cannot be read. Kept before as
68
- // the list of those hidden.
69
- readHidden() {
70
- try {
71
- const kept = JSON.parse(readFileSync(this.file, 'utf8'));
72
- return Array.isArray(kept) ? Object.fromEntries(kept.map(key => [key, true])) : kept && typeof kept === 'object' ? kept : {};
73
- } catch { return {}; }
74
- }
75
- keepHidden(choices) {
76
- const next = `${this.file}.next`;
77
- writeFileSync(next, JSON.stringify(Object.fromEntries(Object.entries(choices).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))));
78
- renameSync(next, this.file);
79
- }
80
- // Whether the machine hides it: as it was told, else as its type says (`hidden`, shown only once chosen).
81
- hiddenOf({ key, panel }) { return this.choices[key] ?? !!panel.hidden; }
82
- // The installed plugins' types, by plugin id, each plugin's in the order it declares them: its resource types, or the
83
- // panels of one that declares none. A project disabling a plugin does not take them away: the page is the machine's,
84
- // not a project's.
85
- installed() {
86
- return [...this.plugins.values()].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0).flatMap(plugin => {
87
- const format = plugin.contributes?.resources ? 'resources' : 'panels';
88
- return panelDeclarations(plugin.contributes?.[format]).map(panel => ({ plugin, panel, key: `${plugin.id}/${panel.id}`, format }));
89
- });
90
- }
91
- find(key) {
92
- return this.installed().find(e => e.key === key) ?? fail('not_found', `没有面板 ${key}`);
93
- }
94
- // Before a list is shown: the environment of each plugin whose panels sign in, for whether what they sign in to is there.
95
- async prepare() {
96
- const plugins = new Set(this.installed().filter(e => e.panel.signIn && !this.envs.has(e.plugin.id)).map(e => e.plugin.id));
97
- await Promise.all([...plugins].map(id => this.env(id).catch(() => {})));
98
- }
99
- // What a page shows of a panel: what it is, whether the machine hides it, what was last read and how that stands now.
100
- view(entry, index) {
101
- const { plugin, panel, key, format } = entry, shown = this.shown.get(key), acting = this.acting.get(key);
102
- return { plugin: plugin.id, pluginName: plugin.name, panel: panel.id, title: panel.title, format, version: plugin.version ?? '', source: plugin.source ?? { kind: 'builtin' },
103
- ...(panel.kind ? { kind: panel.kind } : {}),
104
- actions: Object.fromEntries(Object.entries(panel.actions ?? {}).map(([name, a]) => [name, a.confirm ? { confirm: a.confirm } : {}])),
105
- configurable: !!panel.displaySetting, signsIn: !!panel.signIn, hidden: this.hiddenOf(entry), index,
106
- signIn: panel.signIn ? this.login(entry).view() : null,
107
- reading: shown ? this.present(entry, shown) : null,
108
- busy: this.reading.has(key), failure: this.failures.get(key) ?? null,
109
- // The action under way, by its button; or why the last one did not go through, with the button it was.
110
- acting: acting && !acting.error ? acting.button : null, actionError: acting?.error ?? null, failedButton: acting?.error ? acting.button : null };
111
- }
112
- list() { return this.installed().map((entry, index) => [entry.key, this.view(entry, index)]); }
113
- // One panel's, as `list` has it; none for one no longer installed.
114
- viewOf(key) {
115
- const listed = this.installed(), index = listed.findIndex(e => e.key === key);
116
- return index < 0 ? null : this.view(listed[index], index);
117
- }
118
- // The plugin's environment, as Coda gives every process of it, read again for each command: what it holds (its
119
- // settings, the concurrency groups now) is of the moment.
120
- async env(plugin, extra = {}) {
121
- const env = { ...(await this.coda.environment(null, { plugin })), ...extra };
122
- this.envs.set(plugin, env);
123
- return env;
124
- }
125
- settingsOf(plugin) {
126
- try { return JSON.parse(this.envs.get(plugin)?.CODA_PLUGIN_SETTINGS ?? '{}'); } catch { return {}; }
127
- }
128
- present({ plugin, panel }, reading) {
129
- if (!panel.displaySetting) return reading;
130
- const values = this.settingsOf(plugin.id)[panel.displaySetting] ?? {};
131
- return { ...reading, items: shownItems(reading.items, values), display: { setting: panel.displaySetting, options: displayOptions(reading.items, values) } };
132
- }
133
- // `{ resources, readAt }` (a panel's `{ items, readAt }`), or with `error` when this reading failed: then the last good
134
- // one with `stale`, or none.
135
- read(key, { force = false } = {}) {
136
- const entry = this.find(key);
137
- const pending = this.reading.get(key);
138
- if (pending) return pending;
139
- const last = this.last.get(key);
140
- if (!force && last && entry.panel.maxAgeMs && this.now() - last.at < entry.panel.maxAgeMs && !this.shown.get(key)?.error) return Promise.resolve(this.present(entry, { ...last.content, readAt: last.at }));
141
- const reading = this.fetch(entry).finally(() => { this.reading.delete(key); this.changed(key); });
142
- this.reading.set(key, reading);
143
- this.changed(key);
144
- return reading;
145
- }
146
- async fetch(entry) {
147
- const { plugin, panel, key } = entry;
148
- if (panel.reportMs) this.reportedAt.set(key, this.now());
149
- let failure;
150
- try {
151
- const env = await this.env(plugin.id);
152
- const ran = await this.run(panel.command, { start, cwd: env.CODA_PLUGIN_PATH, env, input: '{}', timeoutMs: this.readTimeoutMs, signal: this.closing.signal });
153
- const { error } = settle(ran, { what: '读取' });
154
- if (!error) {
155
- const content = this.content(entry, ran.stdout), at = this.now();
156
- this.last.set(key, { content, at }); this.failures.delete(key);
157
- this.shown.set(key, { ...content, readAt: at });
158
- // A kind's reading is what this machine reports of it: a failed one reports nothing, so the last good objects stay.
159
- if (entry.panel.kind) await this.report(entry, content.resources, at);
160
- return this.present(entry, { ...content, readAt: at });
161
- }
162
- failure = error.message;
163
- } catch (e) {
164
- if (!(e instanceof PanelError)) { this.failures.set(key, e.message); throw e; }
165
- failure = `输出无效:${e.message}`;
166
- }
167
- const last = this.last.get(key);
168
- const reading = last ? { ...last.content, readAt: last.at, stale: true, error: failure } : { [entry.format === 'resources' ? 'resources' : 'items']: [], error: failure };
169
- this.shown.set(key, reading);
170
- return this.present(entry, reading);
171
- }
172
- // What a command printed, as its format has it: resources, or a panel's items (those it chooses among keeping their places).
173
- content({ plugin, panel, key, format }, output) {
174
- if (format === 'resources') return { resources: resourceItems(output, panel, plugin.views ?? []) };
175
- const items = panelItems(output, panel, plugin.views ?? []);
176
- return { items: panel.displaySetting ? keepMissingMetrics(items, this.last.get(key)?.content.items ?? []) : items };
177
- }
178
- // A kind's reading reported to this machine's backend (GET /v1/resources gives it back to the page and explain): the
179
- // fields Coda keeps are the name, the outside identity it is, its values, what is wrong, and when it was read. Buttons
180
- // and what they send stay here; a failure reports nothing, so the last good objects stay.
181
- async report(entry, resources, at) {
182
- const { plugin, panel } = entry;
183
- const body = { plugin: plugin.id, type: panel.id, kind: panel.kind, observedAt: new Date(at).toISOString(),
184
- resources: resources.map(({ name, identity, values, error }) => ({ ...(name !== undefined ? { name } : {}), ...(identity !== undefined ? { identity } : {}),
185
- values: values ?? [], ...(error !== undefined ? { error } : {}) })) };
186
- try {
187
- await this.coda.api('resource-reports', body);
188
- this.reportedKinds.set(panel.kind, { plugin: plugin.id, type: panel.id });
189
- this.reportSaid.delete(entry.key);
190
- } catch (e) {
191
- if (this.reportSaid.get(entry.key) === e.message) return;
192
- this.reportSaid.set(entry.key, e.message);
193
- console.error(`[资源] ${panel.title} 没有上报读数:${e.message}`);
194
- }
195
- }
196
- // This machine no longer shows or has the type: its objects go, and it is not read on its period.
197
- // This machine no longer shows or has the type: its objects go, and it is not read on its period. Asked whether this
198
- // module reported it or not: after a restart neither it nor the backend remembers, while the kernel still has them.
199
- forgetKind(kind) {
200
- if (!kind) return Promise.resolve();
201
- return this.coda.api('resource-reports/forget', { kind }).then(() => { this.reportedKinds.delete(kind); }, e => {
202
- const said = `forget ${kind}`;
203
- if (this.reportSaid.get(said) === e.message) return;
204
- this.reportSaid.set(said, e.message);
205
- console.error(`[资源] ${kind} 没有停止上报:${e.message}`);
206
- });
207
- }
208
- // The kinds this machine hides now: their objects go once the module starts (and when they are hidden), even when this
209
- // module has no memory of reading them.
210
- forgetHidden() {
211
- for (const entry of this.installed()) if (entry.panel.kind && this.hiddenOf(entry)) void this.forgetKind(entry.panel.kind);
212
- }
213
- // Kinds no longer declared by an installed plugin: their objects go.
214
- dropMissing() {
215
- const kinds = new Set(this.installed().filter(entry => entry.panel.kind).map(entry => entry.panel.kind));
216
- for (const kind of [...this.reportedKinds.keys()]) if (!kinds.has(kind)) void this.forgetKind(kind);
217
- }
218
- // The kinds due to report now: each shown one with a report period, read again (and so reported once it ends).
219
- tick() {
220
- if (!this.ready) return;
221
- const now = this.now();
222
- for (const entry of this.installed()) {
223
- const { panel } = entry;
224
- if (!panel.kind || !panel.reportMs || this.hiddenOf(entry)) continue;
225
- const last = this.reportedAt.get(entry.key);
226
- if (last !== undefined && now - last < panel.reportMs) continue;
227
- this.reportedAt.set(entry.key, now);
228
- this.read(entry.key, { force: true }).catch(() => {});
229
- }
230
- }
231
- // Runs one of a panel's actions with what its button sent, then reads the panel again. One action of a panel at a time;
232
- // one under way goes on to its end even when whoever asked has gone.
233
- async act(key, name, args, button = name) {
234
- const entry = this.find(key), { plugin, panel } = entry, now = this.acting.get(key);
235
- if (now && !now.error) fail('panel_busy', `${panel.title} 正在进行另一项操作`);
236
- // What went wrong is said under the panel, whatever it was.
237
- try {
238
- const action = panel.actions?.[name] ?? fail('not_found', `面板 ${panel.title} 没有动作 ${name}`);
239
- const given = actionArgs(args);
240
- this.acting.set(key, { button }); this.changed(key);
241
- const env = await this.env(plugin.id, { CODA_PANEL_ARGS: JSON.stringify(given) });
242
- const ran = await this.run(action.command, { start, cwd: env.CODA_PLUGIN_PATH, env, input: JSON.stringify(given), timeoutMs: this.actionTimeoutMs, signal: this.closing.signal });
243
- // What an action prints is what it says, not a result: ending with 0 is all of it.
244
- const { error } = settle(ran, { answers: false, what: '操作' });
245
- if (error) fail(error.code, error.message);
246
- this.acting.delete(key);
247
- } catch (e) {
248
- this.acting.set(key, { button, error: e.message }); this.changed(key);
249
- throw e;
250
- }
251
- // A reading that began before the action ended may not show what it did.
252
- await this.reading.get(key);
253
- return this.read(key, { force: true });
254
- }
255
- // One type hidden or shown on this machine, the others as they were: one change at a time.
256
- hide(key, hidden) {
257
- const entry = this.installed().find(e => e.key === key);
258
- const change = this.hides.then(async () => {
259
- const next = { ...this.choices, [key]: !!hidden };
260
- this.keepHidden(next);
261
- this.choices = next;
262
- // Hidden, a kind is neither read nor reported: what it gave the kernel goes.
263
- if (hidden && entry?.panel.kind) await this.forgetKind(entry.panel.kind);
264
- this.changed(key);
265
- });
266
- this.hides = change.catch(() => {});
267
- return change;
268
- }
269
- // A panel's login from Coda (docs/plugins.md「面板的登录」), one per panel at a time. Signed in, the panel is read anew;
270
- // its CLI installed, the plugin's setup is run again (docs/plugins.md「准备运行环境」; `coda.pluginSetup`, asked as this
271
- // plugin), which done well has Coda read its agents again: what they offer may be readable now.
272
- login(entry) {
273
- const { plugin, panel, key } = entry, known = this.logins.get(key);
274
- const declared = panel.signIn ?? fail('not_found', `${panel.title} 不能从 Coda 登录`);
275
- if (known?.declared === JSON.stringify(declared)) return known;
276
- known?.close();
277
- const env = () => this.envs.get(plugin.id) ?? process.env;
278
- // Whether it is there: a quick check with the plugin's own environment, asked again after a moment at most. Without
279
- // one, it always is; without the environment yet, it is not checked, and nothing is kept of it.
280
- let checkedAt = 0, there = false;
281
- const installed = (fresh = false) => {
282
- if (!declared.installed) return true;
283
- const given = this.envs.get(plugin.id);
284
- if (!given) return false;
285
- if (fresh || Date.now() - checkedAt > 2000) { there = spawnSync('/bin/sh', ['-c', declared.installed], { cwd: given.CODA_PLUGIN_PATH, env: given, stdio: 'ignore', timeout: 2000 }).status === 0; checkedAt = Date.now(); }
286
- return there;
287
- };
288
- const login = new SignIn({ provider: key, name: panel.title, command: declared.command, installed, install: declared.install ?? null,
289
- readCode: declared.input ? authorizationLink : deviceCode, input: !!declared.input, note: declared.note ?? null },
290
- { start, env, onChange: () => this.changed(key),
291
- onSignedIn: () => { this.read(key, { force: true }).catch(() => {}); },
292
- onInstalled: () => { checkedAt = 0; this.coda.pluginSetup.retry(plugin.id).catch(() => {}); } });
293
- login.declared = JSON.stringify(declared);
294
- login.recheck = () => { checkedAt = 0; };
295
- this.logins.set(key, login);
296
- return login;
297
- }
298
- async signIn(key, what, body = {}) {
299
- const entry = this.find(key);
300
- // The command runs with the plugin's environment as it is now.
301
- await this.env(entry.plugin.id);
302
- const login = this.login(entry);
303
- switch (what) {
304
- case 'signIn': return login.start();
305
- case 'install': return login.install();
306
- case 'cancelSignIn': return login.cancel();
307
- case 'submitSignIn': return login.submit(body);
308
- default: return login.view();
309
- }
310
- }
311
- // The module going (the plugin host stopping): what runs in a process group of its own is made to end, as nothing would later.
312
- close() { this.closing.abort(); clearInterval(this.timer); this.unwatch?.(); for (const login of this.logins.values()) login.close('SIGKILL'); }
313
- }
@@ -1,232 +0,0 @@
1
- // What a resource type is (docs/plugins.md「资源」): how a plugin declares one (`contributes.resources`, of the schema the
2
- // resources plugin declares for its point, resources.schema.json, checked where the plugin is installed) and what its
3
- // command may print, checked here, where the types are read. Nothing here knows what a resource is about: CPU, an account's
4
- // quota and a disk are all names and values. A plugin still declaring the panels before them (`contributes.panels`,
5
- // schema.json) has them read as they were, for the page to take as resources (docs/plugins.md「旧的面板」).
6
-
7
- // What is not as it must be: the panel says so where it would show.
8
- export class PanelError extends Error {
9
- constructor(code, message) { super(message); this.code = code; }
10
- }
11
- function check(condition, code, message) {
12
- if (!condition) throw new PanelError(code, message);
13
- return condition;
14
- }
15
- // An ISO 8601 duration as panels write their `maxAge` (`PT5M`, `P1D`), in milliseconds: weeks, days and time.
16
- const DURATION = /^P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/;
17
- function durationMs(text) {
18
- const [, w = 0, d = 0, h = 0, min = 0, s = 0] = DURATION.exec(text);
19
- return ((((+w * 7 + +d) * 24 + +h) * 60 + +min) * 60 + +s) * 1000;
20
- }
21
-
22
- export const ITEM_TYPES = ['card', 'meter', 'stat', 'markdown', 'button', 'error'];
23
- // How many resources a reading lists, and how many values and buttons one has.
24
- const RESOURCES = 50, VALUES = 8, ACTIONS = 8;
25
- export const ARGS_LIMIT = 4 * 1024;
26
- const ITEMS = 50, CARD_ITEMS = 20, LABEL = 80, IDENTITY = 200, MARKDOWN = 4000, ERROR = 500, CONFIRM = 200, LINK = 2000;
27
- const fail = (code, message) => check(false, code, message);
28
- const keys = (value, allowed, where, code) => {
29
- const extra = Object.keys(value).filter(k => !allowed.includes(k));
30
- check(!extra.length, code, `${where} 里有 Coda 不支持的键:${extra.join('、')}`);
31
- };
32
- const text = (value, max, where, code, { need = true, line = true } = {}) => {
33
- if (value === undefined && !need) return undefined;
34
- check(typeof value === 'string' && value.trim() && [...value].length <= max && !value.includes('\0') && (!line || !/[\r\n]/.test(value)), code,
35
- `${where} 须为不超过 ${max} 字的${line ? '一行' : ''}文本`);
36
- return value;
37
- };
38
- const object = (value, where, code) => check(value && typeof value === 'object' && !Array.isArray(value), code, `${where} 须为对象`);
39
-
40
- // ---- Declarations (`contributes.resources`, or the panels before them) ----
41
- // A plugin's types as it declares them, in its order, each with the actions its buttons may take (none when it declares
42
- // none), how long a reading may be shown again without asking (`maxAge`), and how often a kind's reading is reported.
43
- export function panelDeclarations(raw = []) {
44
- return raw.map(panel => ({ ...panel, actions: panel.actions ?? {}, ...(panel.maxAge ? { maxAgeMs: durationMs(panel.maxAge) } : {}),
45
- ...(panel.report ? { reportMs: durationMs(panel.report) } : {}) }));
46
- }
47
-
48
- // ---- What a panel's command prints ----
49
- // `{ items: [...] }`, each item one of ITEM_TYPES; a card holds the others. A button names one of the panel's actions,
50
- // or one of its plugin's views for the client to open (docs/plugins.md「视图」). `scope`: `{ actions, views }`, what the
51
- // panel declares and the ids of its plugin's views. Returned as the clients get it: only the keys each type has.
52
- function item(raw, where, scope, inCard) {
53
- object(raw, where, 'invalid_panel');
54
- const { display, ...content } = raw;
55
- const out = plainItem(content, where, scope, inCard);
56
- if (display !== undefined) {
57
- object(display, `${where}.display`, 'invalid_panel');
58
- keys(display, ['id', 'default'], `${where}.display`, 'invalid_panel');
59
- check(['meter', 'stat'].includes(out.type), 'invalid_panel', '只有数值项可以声明 display');
60
- check(typeof display.default === 'boolean', 'invalid_panel', 'display.default 须为开或关');
61
- out.display = { id: text(display.id, 200, 'display.id', 'invalid_panel'), default: display.default };
62
- }
63
- return out;
64
- }
65
- function plainItem(raw, where, scope, inCard) {
66
- const code = 'invalid_panel';
67
- object(raw, where, code);
68
- check(ITEM_TYPES.includes(raw.type), code, `${where} 的 type 只能是 ${ITEM_TYPES.join('、')}`);
69
- check(!(inCard && raw.type === 'card'), code, `${where}:卡片里不能再放卡片`);
70
- switch (raw.type) {
71
- case 'card': {
72
- keys(raw, ['type', 'title', 'subtitle', 'identity', 'items'], where, code);
73
- check(Array.isArray(raw.items) && raw.items.length <= CARD_ITEMS, code, `${where} 的 items 须为不超过 ${CARD_ITEMS} 项的数组`);
74
- // The outside identity it shows (an account), compared and nothing else: a group view shows cards naming the same
75
- // one once for the machines that have them.
76
- return { type: 'card', title: text(raw.title, LABEL, `${where} 的 title`, code),
77
- ...(raw.subtitle !== undefined ? { subtitle: text(raw.subtitle, LABEL, `${where} 的 subtitle`, code) } : {}),
78
- ...(raw.identity !== undefined ? { identity: text(raw.identity, IDENTITY, `${where} 的 identity`, code) } : {}),
79
- items: raw.items.map((r, i) => item(r, `${where}.items[${i}]`, scope, true)) };
80
- }
81
- case 'meter': {
82
- keys(raw, ['type', 'label', 'value', 'fraction', 'note', 'time', 'timeLabel'], where, code);
83
- // Unknown is said by leaving the fraction out, never by a zero.
84
- check(raw.fraction === undefined || raw.fraction === null || (typeof raw.fraction === 'number' && raw.fraction >= 0 && raw.fraction <= 1), code,
85
- `${where} 的 fraction 须在 0–1 之间,不知道时不写`);
86
- check(raw.time === undefined || (typeof raw.time === 'string' && Number.isFinite(Date.parse(raw.time))), code, `${where} 的 time 须为 ISO 8601 时间`);
87
- return { type: 'meter', label: text(raw.label, LABEL, `${where} 的 label`, code),
88
- ...(raw.value !== undefined ? { value: text(raw.value, LABEL, `${where} 的 value`, code) } : {}),
89
- ...(typeof raw.fraction === 'number' ? { fraction: raw.fraction } : {}),
90
- ...(raw.note !== undefined ? { note: text(raw.note, LABEL, `${where} 的 note`, code) } : {}),
91
- ...(raw.time !== undefined ? { time: new Date(raw.time).toISOString() } : {}),
92
- ...(raw.timeLabel !== undefined ? { timeLabel: text(raw.timeLabel, LABEL, `${where} 的 timeLabel`, code) } : {}) };
93
- }
94
- case 'stat':
95
- keys(raw, ['type', 'label', 'value'], where, code);
96
- return { type: 'stat', label: text(raw.label, LABEL, `${where} 的 label`, code), value: text(raw.value, LABEL, `${where} 的 value`, code) };
97
- case 'markdown':
98
- keys(raw, ['type', 'text'], where, code);
99
- return { type: 'markdown', text: text(raw.text, MARKDOWN, `${where} 的 text`, code, { line: false }) };
100
- case 'error':
101
- keys(raw, ['type', 'text'], where, code);
102
- return { type: 'error', text: text(raw.text, ERROR, `${where} 的 text`, code, { line: false }) };
103
- case 'button':
104
- keys(raw, ['type', ...BUTTON_KEYS], where, code);
105
- return { type: 'button', ...button(raw, where, scope) };
106
- }
107
- return fail(code, `${where} 的 type 不受支持`);
108
- }
109
- const BUTTON_KEYS = ['label', 'action', 'view', 'args', 'disabled', 'confirm'];
110
- // What a button does: run one of the type's actions here, open one of its plugin's views in the client, or (a resource's,
111
- // `url` among `keys`) open a web page on the device.
112
- function button(raw, where, scope, keys = BUTTON_KEYS) {
113
- const code = 'invalid_panel';
114
- const does = ['action', 'view', 'url'].filter(k => keys.includes(k) && raw[k] !== undefined);
115
- check(does.length === 1, code, `${where} 须有 ${keys.includes('url') ? 'action、view 或 url' : 'action 或 view'} 之一`);
116
- const [kind] = does;
117
- if (kind === 'view') check(typeof raw.view === 'string' && scope.views.includes(raw.view), code, `${where} 的 view 须是插件声明的视图:${raw.view}`);
118
- else if (kind === 'action') check(typeof raw.action === 'string' && Object.hasOwn(scope.actions, raw.action), code, `${where} 的 action 须是声明的动作:${raw.action}`);
119
- else check(typeof raw.url === 'string' && raw.url.length <= LINK && /^https:\/\/[^\s]+$/.test(raw.url), code, `${where} 的 url 须为不超过 ${LINK} 字的 https 地址`);
120
- check(kind !== 'url' || (raw.args === undefined && raw.confirm === undefined), code, `${where}:打开网页的按钮不带 args 与 confirm`);
121
- check(raw.args === undefined || (raw.args && typeof raw.args === 'object' && !Array.isArray(raw.args) && JSON.stringify(raw.args).length <= ARGS_LIMIT), code,
122
- `${where} 的 args 须为不超过 ${ARGS_LIMIT} 字节的对象`);
123
- check(raw.disabled === undefined || typeof raw.disabled === 'boolean', code, `${where} 的 disabled 须为开或关`);
124
- // Its own question, for what this one button does (which account, which credit), in place of its action's.
125
- return { label: text(raw.label, LABEL, `${where} 的 label`, code), [kind]: raw[kind],
126
- ...(raw.args ? { args: raw.args } : {}), ...(raw.disabled ? { disabled: true } : {}),
127
- ...(raw.confirm !== undefined ? { confirm: text(raw.confirm, CONFIRM, `${where} 的 confirm`, code, { line: false }) } : {}) };
128
- }
129
- // A panel's reading from what its command printed. Anything it cannot be fails the reading, with where. `views`: the ids
130
- // of its plugin's views, which a button may open.
131
- export function panelItems(output, panel, views = []) {
132
- const code = 'invalid_panel';
133
- let value;
134
- try { value = JSON.parse(output); } catch { return fail(code, '输出不是 JSON'); }
135
- object(value, '输出', code);
136
- keys(value, ['items'], '输出', code);
137
- check(Array.isArray(value.items) && value.items.length <= ITEMS, code, `输出的 items 须为不超过 ${ITEMS} 项的数组`);
138
- const items = value.items.map((r, i) => item(r, `items[${i}]`, { actions: panel.actions, views }, false));
139
- const ids = items.flatMap(i => i.type === 'card' ? i.items : [i]).filter(i => i.display).map(i => i.display.id);
140
- check(!ids.length || panel.displaySetting, code, '数值项的 display 需要面板声明 displaySetting');
141
- check(new Set(ids).size === ids.length, code, 'display.id 不能重复');
142
- return items;
143
- }
144
- // A type's reading from what its command printed: `{ resources: [...] }`, each a name, the outside identity it is (an
145
- // account, compared and nothing else), its values, one line of what is wrong with it, and its buttons. Nothing that
146
- // explains: a value is a name and what it reads (docs/plugins.md「资源」). Anything else fails the reading, with where.
147
- export function resourceItems(output, type, views = []) {
148
- const code = 'invalid_panel';
149
- let value;
150
- try { value = JSON.parse(output); } catch { return fail(code, '输出不是 JSON'); }
151
- object(value, '输出', code);
152
- keys(value, ['resources'], '输出', code);
153
- check(Array.isArray(value.resources) && value.resources.length <= RESOURCES, code, `输出的 resources 须为不超过 ${RESOURCES} 项的数组`);
154
- return value.resources.map((r, i) => resource(r, `resources[${i}]`, { actions: type.actions, views }));
155
- }
156
- function resource(raw, where, scope) {
157
- const code = 'invalid_panel';
158
- object(raw, where, code);
159
- keys(raw, ['name', 'identity', 'values', 'error', 'actions'], where, code);
160
- const list = (value, max, name) => {
161
- check(value === undefined || (Array.isArray(value) && value.length <= max), code, `${where} 的 ${name} 须为不超过 ${max} 项的数组`);
162
- return value ?? [];
163
- };
164
- const name = text(raw.name, LABEL, `${where} 的 name`, code, { need: false });
165
- const values = list(raw.values, VALUES, 'values').map((v, i) => reading(v, `${where}.values[${i}]`));
166
- const actions = list(raw.actions, ACTIONS, 'actions').map((b, i) => {
167
- const at = `${where}.actions[${i}]`;
168
- object(b, at, code);
169
- keys(b, [...BUTTON_KEYS, 'url'], at, code);
170
- return button(b, at, scope, [...BUTTON_KEYS, 'url']);
171
- });
172
- check(name !== undefined || values.length, code, `${where} 须有 name 或 values`);
173
- return { ...(name !== undefined ? { name } : {}),
174
- ...(raw.identity !== undefined ? { identity: text(raw.identity, IDENTITY, `${where} 的 identity`, code) } : {}),
175
- values, ...(raw.error !== undefined ? { error: text(raw.error, LABEL, `${where} 的 error`, code) } : {}), actions };
176
- }
177
- // One value: what it is called (left out where its resource has only it), what it reads, how much of it is left (0–1,
178
- // left out when not known: never drawn as empty), and a time it comes with (when a quota is back).
179
- function reading(raw, where) {
180
- const code = 'invalid_panel';
181
- object(raw, where, code);
182
- keys(raw, ['label', 'value', 'fraction', 'time'], where, code);
183
- check(raw.fraction === undefined || raw.fraction === null || (typeof raw.fraction === 'number' && raw.fraction >= 0 && raw.fraction <= 1), code,
184
- `${where} 的 fraction 须在 0–1 之间,不知道时不写`);
185
- check(raw.time === undefined || (typeof raw.time === 'string' && Number.isFinite(Date.parse(raw.time))), code, `${where} 的 time 须为 ISO 8601 时间`);
186
- check(raw.value !== undefined || typeof raw.fraction === 'number', code, `${where} 须有 value 或 fraction`);
187
- return { ...(raw.label !== undefined ? { label: text(raw.label, LABEL, `${where} 的 label`, code) } : {}),
188
- ...(raw.value !== undefined ? { value: text(raw.value, LABEL, `${where} 的 value`, code) } : {}),
189
- ...(typeof raw.fraction === 'number' ? { fraction: raw.fraction } : {}),
190
- ...(raw.time !== undefined ? { time: new Date(raw.time).toISOString() } : {}) };
191
- }
192
- // What a button sends: an object the action's command reads as JSON.
193
- export function actionArgs(value) {
194
- if (value === undefined || value === null) return {};
195
- check(typeof value === 'object' && !Array.isArray(value) && JSON.stringify(value).length <= ARGS_LIMIT, 'invalid_input', `args 须为不超过 ${ARGS_LIMIT} 字节的对象`);
196
- return value;
197
- }
198
-
199
- // A reading keeps all measurements in memory; display choices are ordinary plugin settings, applied at read time.
200
- export function shownItems(items, choices = {}) {
201
- return items.flatMap(({ display, ...item }) => {
202
- if (display && !(choices[display.id] ?? display.default)) return [];
203
- if (item.type === 'card') {
204
- item.items = shownItems(item.items, choices);
205
- if (!item.items.length) return [];
206
- }
207
- return [item];
208
- });
209
- }
210
- export function displayOptions(items, values = {}) {
211
- return items.flatMap(item => (item.type === 'card' ? item.items : [item]).filter(i => i.display).map(i => ({
212
- id: i.display.id, label: i.label, group: item.type === 'card' ? item.title : '',
213
- enabled: values[i.display.id] ?? i.display.default, default: i.display.default,
214
- })));
215
- }
216
-
217
- // A disconnected device keeps its place for this backend's lifetime, with no old number presented as current.
218
- export function keepMissingMetrics(items, previous) {
219
- const ids = new Set(items.flatMap(i => i.type === 'card' ? i.items : [i]).flatMap(i => i.display ? [i.display.id] : []));
220
- const result = [...items];
221
- for (const old of previous) {
222
- const missing = (old.type === 'card' ? old.items : [old]).filter(i => i.display && !ids.has(i.display.id))
223
- .map(i => ({ type: 'stat', label: i.label, value: '暂不可读', display: i.display }));
224
- if (!missing.length) continue;
225
- if (old.type === 'card') {
226
- const same = result.find(i => i.type === 'card' && i.title === old.title);
227
- if (same) same.items = [...same.items, ...missing].slice(0, 20);
228
- else if (result.length < 50) result.push({ ...old, items: missing });
229
- } else if (result.length < 50) result.push(...missing);
230
- }
231
- return result;
232
- }