@open-artifact/host-plugin 0.0.0-stage → 0.13.0

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.
@@ -0,0 +1,1000 @@
1
+ /**
2
+ * `@open-artifact/host-plugin/contract`: the rules of the plugin API that the host and the test kit share, so a plugin
3
+ * that passes its tests under the kit loads and behaves the same on the host.
4
+ *
5
+ * - {@link checkPlugin}: what a plugin object must look like (its `id`, `apiVersion`, hooks), what is reported and
6
+ * ignored (unknown keys and hooks), and what refuses it.
7
+ * - {@link validateConfig}: the operator's settings against the plugin's schema, `{"env": "NAME"}` references
8
+ * resolved, defaults filled in, secrets never echoed.
9
+ * - The answer checks of every hook (`check*`): an answer of the wrong shape counts as a failure.
10
+ * - {@link withTimeLimit}: one hook call under its time limit.
11
+ * - The key-value store's limits ({@link KV_LIMITS}), route path matching and the same-origin rule for writes.
12
+ *
13
+ * Plugin authors do not need this module; it is public so the rules are written down in one place.
14
+ */
15
+ import { PLUGIN_API_VERSION, } from "./index.js";
16
+ // ---------------------------------------------------------------------------
17
+ // Names
18
+ /** The plugin API versions this release runs (the current one first). A version here but not current runs through an adapter. */
19
+ export const SUPPORTED_API_VERSIONS = [PLUGIN_API_VERSION];
20
+ /** Every event of API version 1, in the order the documentation lists them. */
21
+ export const EVENT_NAMES = [
22
+ 'user.created',
23
+ 'user.signed_in',
24
+ 'artifact.created',
25
+ 'artifact.changed',
26
+ 'artifact.trashed',
27
+ 'artifact.restored',
28
+ 'artifact.deleted',
29
+ 'share.changed',
30
+ 'share.invited',
31
+ 'agent.requested',
32
+ 'audit',
33
+ ];
34
+ /** Every guarded action of API version 1. */
35
+ export const GUARD_ACTIONS = [
36
+ 'artifact.create',
37
+ 'artifact.import',
38
+ 'artifact.delete',
39
+ 'artifact.export',
40
+ 'share.change',
41
+ 'link.connect',
42
+ 'link.publish',
43
+ 'mcp.connect',
44
+ 'agent.ask',
45
+ ];
46
+ /** The hooks of API version 1 besides the event handlers (`on.<event>`). */
47
+ export const HOOK_NAMES = [
48
+ 'auth.authenticate',
49
+ 'auth.signIn',
50
+ 'auth.identity',
51
+ 'auth.signOutUrl',
52
+ 'authz.role',
53
+ 'authz.artifacts',
54
+ 'guard',
55
+ 'wake.deliver',
56
+ 'routes',
57
+ 'ui',
58
+ ];
59
+ /** The members of `ctx` (for `ctx.host.supports('ctx.kv')`). */
60
+ export const CONTEXT_FEATURES = [
61
+ 'ctx.config',
62
+ 'ctx.log',
63
+ 'ctx.fetch',
64
+ 'ctx.kv',
65
+ 'ctx.now',
66
+ 'ctx.signal',
67
+ 'ctx.host.users',
68
+ 'ctx.host.artifacts',
69
+ 'ctx.host.artifacts.list',
70
+ 'ctx.host.access',
71
+ 'ctx.host.audit',
72
+ ];
73
+ /** `ctx.host.artifacts.list`: the page size unless the plugin asks for another, and the most one call answers. */
74
+ export const ARTIFACT_LIST_DEFAULT = 50;
75
+ export const ARTIFACT_LIST_MAX = 200;
76
+ /** `ctx.host.artifacts.list`'s options checked: a TypeError for a wrong one, the limit clamped to the cap. */
77
+ export function artifactListOptions(options) {
78
+ if (options === undefined || options === null)
79
+ return { limit: ARTIFACT_LIST_DEFAULT };
80
+ if (typeof options !== 'object' || Array.isArray(options))
81
+ throw new TypeError('artifacts.list takes {owner?, limit?, after?}.');
82
+ const { owner, limit, after } = options;
83
+ if (owner !== undefined && (typeof owner !== 'string' || owner === ''))
84
+ throw new TypeError('artifacts.list: owner is a user id.');
85
+ if (after !== undefined && (typeof after !== 'string' || after === ''))
86
+ throw new TypeError("artifacts.list: after is the page before's next.");
87
+ if (limit !== undefined && (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 1))
88
+ throw new TypeError('artifacts.list: limit is a whole number from 1.');
89
+ return { ...(owner !== undefined ? { owner } : {}), ...(after !== undefined ? { after } : {}), limit: Math.min(limit ?? ARTIFACT_LIST_DEFAULT, ARTIFACT_LIST_MAX) };
90
+ }
91
+ /** Everything `ctx.host.supports` answers true for on a host that runs all of API version 1. */
92
+ export const ALL_FEATURES = [
93
+ ...HOOK_NAMES,
94
+ ...EVENT_NAMES.map((name) => `on.${name}`),
95
+ ...GUARD_ACTIONS.map((name) => `guard.${name}`),
96
+ ...CONTEXT_FEATURES,
97
+ ];
98
+ /** Which kind of failure policy a hook has (decision: sign-in, permission and guard hooks fail closed). */
99
+ export function failsClosed(hook) {
100
+ return hook.startsWith('auth.') || hook.startsWith('authz.') || hook === 'guard';
101
+ }
102
+ // ---------------------------------------------------------------------------
103
+ // Limits
104
+ /** Each hook call's time limit unless the operator sets `timeoutMs`, ms. */
105
+ export const DEFAULT_TIMEOUT_MS = 5000;
106
+ /** The longest `timeoutMs` an operator may set, ms. */
107
+ export const MAX_TIMEOUT_MS = 60_000;
108
+ /** How long the host reuses a plugin's role answers unless it sets `authz.cacheSeconds`. */
109
+ export const DEFAULT_CACHE_SECONDS = 30;
110
+ /** The longest `authz.cacheSeconds` the host honours (a day). */
111
+ export const MAX_CACHE_SECONDS = 86_400;
112
+ /**
113
+ * The key-value store's limits, per plugin. Keys up to 512 bytes (room for a prefix and an id or URL); values up to
114
+ * 64 KiB of JSON (a cached answer or a queued webhook, well under every database's row limit, D1's 1 MB included);
115
+ * 10,000 live keys (bounds what one plugin can put in the site's catalog: at most ~640 MB in the worst case, and
116
+ * typically far less); a listing returns at most 1000 entries at a time.
117
+ */
118
+ export const KV_LIMITS = { maxKeyBytes: 512, maxValueBytes: 64 * 1024, maxKeys: 10_000, maxList: 1000, defaultList: 100 };
119
+ /** Lower-case letters, digits and single `-` between them; at most 64 characters. */
120
+ export const PLUGIN_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
121
+ export const MAX_PLUGIN_ID = 64;
122
+ // ---------------------------------------------------------------------------
123
+ // Messages
124
+ /** `"x"` for a name in a message. */
125
+ const q = (name) => JSON.stringify(name);
126
+ /** Edit distance, for "did you mean". */
127
+ function distance(a, b) {
128
+ const row = Array.from({ length: b.length + 1 }, (_, i) => i);
129
+ for (let i = 1; i <= a.length; i++) {
130
+ let prev = row[0];
131
+ row[0] = i;
132
+ for (let j = 1; j <= b.length; j++) {
133
+ const next = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
134
+ prev = row[j];
135
+ row[j] = next;
136
+ }
137
+ }
138
+ return row[b.length];
139
+ }
140
+ /** ` Did you mean "x"?` when a known name is close to `name`, else ``. */
141
+ export function didYouMean(name, known) {
142
+ let best;
143
+ let bestDistance = Infinity;
144
+ for (const candidate of known) {
145
+ const d = distance(name.toLowerCase(), candidate.toLowerCase());
146
+ if (d < bestDistance) {
147
+ best = candidate;
148
+ bestDistance = d;
149
+ }
150
+ }
151
+ return best !== undefined && bestDistance <= Math.max(2, Math.floor(name.length / 4)) ? ` Did you mean ${q(best)}?` : '';
152
+ }
153
+ /** What a value is, for a message, without showing it. */
154
+ export function kindOf(value) {
155
+ if (value === null)
156
+ return 'null';
157
+ if (Array.isArray(value))
158
+ return 'a list';
159
+ switch (typeof value) {
160
+ case 'string':
161
+ return 'a string';
162
+ case 'number':
163
+ return 'a number';
164
+ case 'boolean':
165
+ return 'true or false';
166
+ case 'object':
167
+ return 'an object';
168
+ default:
169
+ return typeof value;
170
+ }
171
+ }
172
+ /** A short rendering of a non-secret value, for a message. */
173
+ function shown(value) {
174
+ const text = JSON.stringify(value) ?? String(value);
175
+ return text.length > 40 ? `${text.slice(0, 37)}...` : text;
176
+ }
177
+ /**
178
+ * Why a plugin's `apiVersion` keeps it from running here, or null when it may run. The messages say what to do:
179
+ * update the host for a newer version, update the plugin for one this host no longer runs.
180
+ */
181
+ export function apiVersionProblem(label, version, hostVersion) {
182
+ const host = hostVersion ? `this host (Open Artifact ${hostVersion})` : 'this host';
183
+ const current = SUPPORTED_API_VERSIONS[0];
184
+ if (version === undefined)
185
+ return `${label} does not say which plugin API it was written for: add apiVersion: ${current} to the plugin object.`;
186
+ if (typeof version !== 'number' || !Number.isInteger(version) || version < 1)
187
+ return `${label} has apiVersion ${shown(version)}, which is not a plugin API version: it should be ${current}.`;
188
+ if (SUPPORTED_API_VERSIONS.includes(version))
189
+ return null;
190
+ if (version > current) {
191
+ return `${label} needs plugin API version ${version}, but ${host} runs version ${current}. Update Open Artifact to a release that runs plugin API ${version}, or use a release of the plugin written for API ${current}.`;
192
+ }
193
+ return `${label} was written for plugin API version ${version}, which ${host} no longer runs (it runs ${SUPPORTED_API_VERSIONS.join(', ')}). Update the plugin to a release written for API ${current}.`;
194
+ }
195
+ const TOP_KEYS = ['id', 'apiVersion', 'name', 'version', 'description', 'config', 'validate', 'auth', 'authz', 'guard', 'on', 'wake', 'routes', 'ui'];
196
+ const AUTH_KEYS = ['authenticate', 'recheck', 'signIn', 'identity', 'signOutUrl'];
197
+ const SIGN_IN_KEYS = ['label', 'start', 'finish'];
198
+ const AUTHZ_KEYS = ['role', 'cacheSeconds', 'artifacts'];
199
+ const WAKE_KEYS = ['deliver'];
200
+ const ROUTE_KEYS = ['method', 'path', 'public', 'handler'];
201
+ const UI_KEYS = ['links', 'brand'];
202
+ const LINK_KEYS = ['label', 'href', 'where'];
203
+ const BRAND_KEYS = ['name', 'logoUrl'];
204
+ const FIELD_KEYS = ['type', 'required', 'default', 'description'];
205
+ const FIELD_TYPES = ['string', 'number', 'boolean', 'string[]', 'secret', 'map', 'json'];
206
+ const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', '*'];
207
+ const SETTING_NAME = /^[A-Za-z][A-Za-z0-9_]*$/;
208
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
209
+ const isFunction = (value) => typeof value === 'function';
210
+ /** Whether `href` is a link the host may show: an `https:`/`http:` URL, or a path on the site. */
211
+ export function isSafeHref(href) {
212
+ if (typeof href !== 'string' || href.length === 0 || href.length > 2048)
213
+ return false;
214
+ if (href.startsWith('/'))
215
+ return !href.startsWith('//') && !href.startsWith('/\\');
216
+ try {
217
+ const url = new URL(href);
218
+ return url.protocol === 'https:' || url.protocol === 'http:';
219
+ }
220
+ catch {
221
+ return false;
222
+ }
223
+ }
224
+ function checkSchema(label, value, errors, warnings) {
225
+ if (value === undefined)
226
+ return {};
227
+ if (!isRecord(value)) {
228
+ errors.push(`${label}: config must be an object of settings ({name: {type, required?, default?, description?}}), not ${kindOf(value)}.`);
229
+ return {};
230
+ }
231
+ const schema = {};
232
+ for (const [name, field] of Object.entries(value)) {
233
+ const where = `${label}, setting ${q(name)}`;
234
+ if (!SETTING_NAME.test(name)) {
235
+ errors.push(`${where}: a setting's name is letters, digits and _ (starting with a letter).`);
236
+ continue;
237
+ }
238
+ if (!isRecord(field)) {
239
+ errors.push(`${where}: must be {type, required?, default?, description?}, not ${kindOf(field)}.`);
240
+ continue;
241
+ }
242
+ for (const key of Object.keys(field))
243
+ if (!FIELD_KEYS.includes(key))
244
+ warnings.push(`${where}: unknown key ${q(key)} ignored.${didYouMean(key, FIELD_KEYS)}`);
245
+ if (!FIELD_TYPES.includes(field.type)) {
246
+ errors.push(`${where}: type must be one of ${FIELD_TYPES.join(', ')}.`);
247
+ continue;
248
+ }
249
+ const type = field.type;
250
+ if (field.required !== undefined && typeof field.required !== 'boolean')
251
+ errors.push(`${where}: required must be true or false.`);
252
+ if (field.description !== undefined && typeof field.description !== 'string')
253
+ errors.push(`${where}: description must be a string.`);
254
+ if (field.default !== undefined && convert(type, field.default) === undefined)
255
+ errors.push(`${where}: its default is not a ${type}.`);
256
+ schema[name] = {
257
+ type,
258
+ ...(field.required === true ? { required: true } : {}),
259
+ ...(field.default !== undefined ? { default: field.default } : {}),
260
+ ...(typeof field.description === 'string' ? { description: field.description } : {}),
261
+ };
262
+ }
263
+ return schema;
264
+ }
265
+ /** Records the unknown keys of `value` once, as warnings. */
266
+ function unknownKeys(where, value, known, warnings) {
267
+ for (const key of Object.keys(value)) {
268
+ if (!known.includes(key))
269
+ warnings.push(`${where}: unknown ${q(key)} ignored (this host does not know it).${didYouMean(key, known)}`);
270
+ }
271
+ }
272
+ /** Splits a route path into segments, or says why it is not one. */
273
+ function routeSegments(path) {
274
+ if (typeof path !== 'string' || !path.startsWith('/'))
275
+ return 'its path must be a string starting with /';
276
+ const segments = path.split('/').filter((s) => s !== '');
277
+ const star = segments.indexOf('*');
278
+ if (star !== -1 && star !== segments.length - 1)
279
+ return "a '*' must end its path";
280
+ for (const segment of segments)
281
+ if (segment.startsWith(':') && segment.length === 1)
282
+ return 'a parameter needs a name (:name)';
283
+ return segments;
284
+ }
285
+ /**
286
+ * Checks a plugin object (a module's default export). `label` names it in messages (the `use` of its entry).
287
+ *
288
+ * Refused (`errors`): not an object; a bad `id`; an `apiVersion` this host does not run; a hook that is not a
289
+ * function where one must be; a bad config schema, route or UI link. Reported once and ignored (`warnings`): keys
290
+ * and hooks this host does not know, at any level, and events it does not know under `on`.
291
+ */
292
+ export function checkPlugin(value, label, options = {}) {
293
+ const errors = [];
294
+ const warnings = [];
295
+ if (isFunction(value))
296
+ return { plugin: null, errors: [`${label} exports a function: export the plugin object itself (export default {id, apiVersion, …}).`], warnings };
297
+ if (!isRecord(value))
298
+ return { plugin: null, errors: [`${label} does not export a plugin: its default export is ${kindOf(value)}, not an object.`], warnings };
299
+ const id = value.id;
300
+ if (typeof id !== 'string' || !PLUGIN_ID.test(id) || id.length > MAX_PLUGIN_ID) {
301
+ errors.push(`${label}: the plugin's id must be lower-case letters, digits and - (e.g. "acme-sso"), at most ${MAX_PLUGIN_ID} characters${typeof id === 'string' ? `, not ${q(id)}` : ''}.`);
302
+ }
303
+ const named = typeof id === 'string' && PLUGIN_ID.test(id) ? `Plugin ${q(id)}` : label;
304
+ const apiProblem = apiVersionProblem(named, value.apiVersion, options.hostVersion);
305
+ if (apiProblem)
306
+ errors.push(apiProblem);
307
+ unknownKeys(named, value, TOP_KEYS, warnings);
308
+ for (const key of ['name', 'version', 'description']) {
309
+ if (value[key] !== undefined && typeof value[key] !== 'string')
310
+ errors.push(`${named}: ${key} must be a string.`);
311
+ }
312
+ const schema = checkSchema(named, value.config, errors, warnings);
313
+ if (value.validate !== undefined && !isFunction(value.validate))
314
+ errors.push(`${named}: validate must be a function, not ${kindOf(value.validate)}.`);
315
+ const hooks = [];
316
+ const mustBeFunction = (where, fn, hook) => {
317
+ if (fn === undefined)
318
+ return;
319
+ if (isFunction(fn))
320
+ hooks.push(hook);
321
+ else
322
+ errors.push(`${named}: ${where} must be a function, not ${kindOf(fn)}.`);
323
+ };
324
+ let recheck = true;
325
+ if (value.auth !== undefined) {
326
+ if (!isRecord(value.auth))
327
+ errors.push(`${named}: auth must be an object of hooks.`);
328
+ else {
329
+ unknownKeys(`${named}, auth`, value.auth, AUTH_KEYS, warnings);
330
+ mustBeFunction('auth.authenticate', value.auth.authenticate, 'auth.authenticate');
331
+ if (value.auth.recheck !== undefined) {
332
+ if (typeof value.auth.recheck !== 'boolean')
333
+ errors.push(`${named}: auth.recheck must be true or false.`);
334
+ else
335
+ recheck = value.auth.recheck;
336
+ }
337
+ if (value.auth.signIn !== undefined) {
338
+ const signIn = value.auth.signIn;
339
+ if (!isRecord(signIn))
340
+ errors.push(`${named}: auth.signIn must be {label, start, finish}.`);
341
+ else {
342
+ unknownKeys(`${named}, auth.signIn`, signIn, SIGN_IN_KEYS, warnings);
343
+ if (typeof signIn.label !== 'string' || !signIn.label.trim() || signIn.label.length > 80)
344
+ errors.push(`${named}: auth.signIn.label must be a button label (1-80 characters).`);
345
+ if (!isFunction(signIn.start) || !isFunction(signIn.finish))
346
+ errors.push(`${named}: auth.signIn needs both start and finish functions.`);
347
+ else
348
+ hooks.push('auth.signIn');
349
+ }
350
+ }
351
+ mustBeFunction('auth.identity', value.auth.identity, 'auth.identity');
352
+ mustBeFunction('auth.signOutUrl', value.auth.signOutUrl, 'auth.signOutUrl');
353
+ }
354
+ }
355
+ let cacheSeconds = DEFAULT_CACHE_SECONDS;
356
+ if (value.authz !== undefined) {
357
+ if (!isRecord(value.authz))
358
+ errors.push(`${named}: authz must be an object of hooks.`);
359
+ else {
360
+ unknownKeys(`${named}, authz`, value.authz, AUTHZ_KEYS, warnings);
361
+ mustBeFunction('authz.role', value.authz.role, 'authz.role');
362
+ mustBeFunction('authz.artifacts', value.authz.artifacts, 'authz.artifacts');
363
+ const seconds = value.authz.cacheSeconds;
364
+ if (seconds !== undefined) {
365
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds < 0)
366
+ errors.push(`${named}: authz.cacheSeconds must be a number of seconds, 0 or more.`);
367
+ else
368
+ cacheSeconds = Math.min(Math.floor(seconds), MAX_CACHE_SECONDS);
369
+ }
370
+ }
371
+ }
372
+ mustBeFunction('guard', value.guard, 'guard');
373
+ if (value.on !== undefined) {
374
+ if (!isRecord(value.on))
375
+ errors.push(`${named}: on must be an object of event handlers ({'share.invited': handler}).`);
376
+ else {
377
+ for (const [event, handler] of Object.entries(value.on)) {
378
+ if (!EVENT_NAMES.includes(event)) {
379
+ warnings.push(`${named}: unknown event ${q(event)} ignored (this host does not send it).${didYouMean(event, EVENT_NAMES)}`);
380
+ continue;
381
+ }
382
+ mustBeFunction(`on[${q(event)}]`, handler, `on.${event}`);
383
+ }
384
+ }
385
+ }
386
+ if (value.wake !== undefined) {
387
+ if (!isRecord(value.wake))
388
+ errors.push(`${named}: wake must be {deliver}.`);
389
+ else {
390
+ unknownKeys(`${named}, wake`, value.wake, WAKE_KEYS, warnings);
391
+ mustBeFunction('wake.deliver', value.wake.deliver, 'wake.deliver');
392
+ }
393
+ }
394
+ const routes = [];
395
+ if (value.routes !== undefined) {
396
+ if (!Array.isArray(value.routes))
397
+ errors.push(`${named}: routes must be a list of {method, path, handler, public?}.`);
398
+ else {
399
+ const seen = new Set();
400
+ value.routes.forEach((route, index) => {
401
+ const where = `${named}, routes[${index}]`;
402
+ if (!isRecord(route))
403
+ return void errors.push(`${where}: must be {method, path, handler, public?}.`);
404
+ unknownKeys(where, route, ROUTE_KEYS, warnings);
405
+ const method = typeof route.method === 'string' ? route.method.toUpperCase() : '';
406
+ if (!METHODS.includes(method))
407
+ return void errors.push(`${where}: method must be one of ${METHODS.join(', ')}.`);
408
+ const segments = routeSegments(route.path);
409
+ if (typeof segments === 'string')
410
+ return void errors.push(`${where}: ${segments}.`);
411
+ if (!isFunction(route.handler))
412
+ return void errors.push(`${where}: handler must be a function.`);
413
+ if (route.public !== undefined && typeof route.public !== 'boolean')
414
+ return void errors.push(`${where}: public must be true or false.`);
415
+ const key = `${method} /${segments.join('/')}`;
416
+ if (seen.has(key))
417
+ warnings.push(`${where}: ${key} is already a route of this plugin; the first one answers.`);
418
+ seen.add(key);
419
+ routes.push({ method, path: `/${segments.join('/')}`, segments, public: route.public === true, index });
420
+ });
421
+ if (routes.length > 0)
422
+ hooks.push('routes');
423
+ }
424
+ }
425
+ const ui = { links: [], brand: null };
426
+ if (value.ui !== undefined) {
427
+ if (!isRecord(value.ui))
428
+ errors.push(`${named}: ui must be {links?, brand?}.`);
429
+ else {
430
+ unknownKeys(`${named}, ui`, value.ui, UI_KEYS, warnings);
431
+ if (value.ui.links !== undefined) {
432
+ if (!Array.isArray(value.ui.links))
433
+ errors.push(`${named}: ui.links must be a list of {label, href, where}.`);
434
+ else
435
+ value.ui.links.forEach((link, index) => {
436
+ const where = `${named}, ui.links[${index}]`;
437
+ if (!isRecord(link))
438
+ return void errors.push(`${where}: must be {label, href, where}.`);
439
+ unknownKeys(where, link, LINK_KEYS, warnings);
440
+ if (typeof link.label !== 'string' || !link.label.trim() || link.label.length > 80)
441
+ return void errors.push(`${where}: label must be 1-80 characters.`);
442
+ if (!isSafeHref(link.href))
443
+ return void errors.push(`${where}: href must be an https: or http: address, or a path starting with /.`);
444
+ if (link.where !== 'account-menu' && link.where !== 'home')
445
+ return void warnings.push(`${where}: where ${shown(link.where)} is not a place this host knows (account-menu, home); the link is not shown.`);
446
+ ui.links.push({ label: link.label.trim(), href: link.href, where: link.where });
447
+ });
448
+ }
449
+ if (value.ui.brand !== undefined) {
450
+ const brand = value.ui.brand;
451
+ if (!isRecord(brand))
452
+ errors.push(`${named}: ui.brand must be {name?, logoUrl?}.`);
453
+ else {
454
+ unknownKeys(`${named}, ui.brand`, brand, BRAND_KEYS, warnings);
455
+ if (brand.name !== undefined && (typeof brand.name !== 'string' || brand.name.length > 80))
456
+ errors.push(`${named}: ui.brand.name must be a string of at most 80 characters.`);
457
+ else if (brand.logoUrl !== undefined && !isSafeHref(brand.logoUrl))
458
+ errors.push(`${named}: ui.brand.logoUrl must be an https: or http: address, or a path starting with /.`);
459
+ else {
460
+ ui.brand = {
461
+ ...(typeof brand.name === 'string' && brand.name.trim() ? { name: brand.name.trim() } : {}),
462
+ ...(typeof brand.logoUrl === 'string' ? { logoUrl: brand.logoUrl } : {}),
463
+ };
464
+ }
465
+ }
466
+ }
467
+ if (ui.links.length > 0 || ui.brand)
468
+ hooks.push('ui');
469
+ }
470
+ }
471
+ if (errors.length > 0)
472
+ return { plugin: null, errors, warnings };
473
+ return {
474
+ plugin: {
475
+ id: id,
476
+ apiVersion: value.apiVersion,
477
+ name: typeof value.name === 'string' && value.name.trim() ? value.name.trim() : id,
478
+ version: typeof value.version === 'string' ? value.version : null,
479
+ description: typeof value.description === 'string' ? value.description : null,
480
+ source: value,
481
+ schema,
482
+ hooks,
483
+ cacheSeconds,
484
+ recheck,
485
+ routes,
486
+ ui,
487
+ },
488
+ errors,
489
+ warnings,
490
+ };
491
+ }
492
+ // ---------------------------------------------------------------------------
493
+ // Settings
494
+ /** A value converted to a field's type, or undefined when it is not one. Strings (from the environment) are parsed. */
495
+ function convert(type, value, fromEnv = false) {
496
+ if (fromEnv && (type === 'map' || type === 'json') && typeof value === 'string') {
497
+ try {
498
+ return convert(type, JSON.parse(value));
499
+ }
500
+ catch {
501
+ return undefined;
502
+ }
503
+ }
504
+ switch (type) {
505
+ case 'map': {
506
+ if (!isRecord(value))
507
+ return undefined;
508
+ const map = {};
509
+ for (const [key, v] of Object.entries(value)) {
510
+ if (typeof v !== 'string')
511
+ return undefined;
512
+ map[key] = v;
513
+ }
514
+ return map;
515
+ }
516
+ case 'json':
517
+ return isJson(value, 0) ? structuredCloneJson(value) : undefined;
518
+ case 'string':
519
+ case 'secret':
520
+ return typeof value === 'string' ? value : undefined;
521
+ case 'number': {
522
+ if (typeof value === 'number')
523
+ return Number.isFinite(value) ? value : undefined;
524
+ if (fromEnv && typeof value === 'string' && value.trim() !== '') {
525
+ const n = Number(value.trim());
526
+ return Number.isFinite(n) ? n : undefined;
527
+ }
528
+ return undefined;
529
+ }
530
+ case 'boolean': {
531
+ if (typeof value === 'boolean')
532
+ return value;
533
+ if (fromEnv && typeof value === 'string') {
534
+ const v = value.trim().toLowerCase();
535
+ if (['true', '1', 'yes', 'on'].includes(v))
536
+ return true;
537
+ if (['false', '0', 'no', 'off'].includes(v))
538
+ return false;
539
+ }
540
+ return undefined;
541
+ }
542
+ case 'string[]': {
543
+ if (Array.isArray(value))
544
+ return value.every((v) => typeof v === 'string') ? [...value] : undefined;
545
+ if (fromEnv && typeof value === 'string') {
546
+ const text = value.trim();
547
+ if (text.startsWith('[')) {
548
+ try {
549
+ return convert('string[]', JSON.parse(text));
550
+ }
551
+ catch {
552
+ return undefined;
553
+ }
554
+ }
555
+ return text.split(',').map((s) => s.trim()).filter((s) => s !== '');
556
+ }
557
+ return undefined;
558
+ }
559
+ }
560
+ }
561
+ /** What a field's type is called in a message. */
562
+ function typeWords(type) {
563
+ switch (type) {
564
+ case 'string':
565
+ case 'secret':
566
+ return 'a string';
567
+ case 'number':
568
+ return 'a number';
569
+ case 'boolean':
570
+ return 'true or false';
571
+ case 'string[]':
572
+ return 'a list of strings';
573
+ case 'map':
574
+ return 'an object of strings ({"name": "value"})';
575
+ case 'json':
576
+ return 'a JSON value';
577
+ }
578
+ }
579
+ /** Whether `value` is plain JSON (no functions, no cycles, at most 32 levels deep). */
580
+ function isJson(value, depth) {
581
+ if (depth > 32)
582
+ return false;
583
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
584
+ return true;
585
+ if (typeof value === 'number')
586
+ return Number.isFinite(value);
587
+ if (Array.isArray(value))
588
+ return value.every((v) => isJson(v, depth + 1));
589
+ if (isRecord(value))
590
+ return Object.values(value).every((v) => isJson(v, depth + 1));
591
+ return false;
592
+ }
593
+ /** A deep copy of a JSON value, so a plugin cannot change the operator's configuration under the host. */
594
+ function structuredCloneJson(value) {
595
+ return JSON.parse(JSON.stringify(value));
596
+ }
597
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
598
+ /**
599
+ * The operator's settings for a plugin, checked against its schema:
600
+ *
601
+ * - every value of the right type (a `{"env": "NAME"}` value is read from `env` and parsed: numbers, `true`/`false`,
602
+ * a JSON list or a comma-separated one); a variable that is not set (or empty) is an error naming the plugin, the
603
+ * setting and the variable;
604
+ * - required settings present (an empty string does not count); defaults filled in;
605
+ * - a setting the schema does not have is an error (a typo must not pass silently), with a suggestion;
606
+ * - a `secret` written into the configuration instead of `{"env": …}` is a warning.
607
+ *
608
+ * No message ever shows a secret's value, nor the value of a setting it does not know (it may be a mistyped secret).
609
+ */
610
+ export function validateConfig(pluginId, schema, values, env = {}) {
611
+ const errors = [];
612
+ const warnings = [];
613
+ const secrets = [];
614
+ const config = {};
615
+ const label = `Plugin ${q(pluginId)}`;
616
+ const names = Object.keys(schema);
617
+ if (values !== undefined && values !== null && !isRecord(values)) {
618
+ return { config, errors: [`${label}: config must be an object of settings, not ${kindOf(values)}.`], warnings, secrets };
619
+ }
620
+ const given = (values ?? {});
621
+ for (const name of Object.keys(given)) {
622
+ if (!(name in schema)) {
623
+ errors.push(names.length === 0
624
+ ? `${label} takes no settings, but the configuration sets ${q(name)}.`
625
+ : `${label}: unknown setting ${q(name)}.${didYouMean(name, names)} Its settings are: ${names.join(', ')}.`);
626
+ }
627
+ }
628
+ for (const [name, field] of Object.entries(schema)) {
629
+ const where = `${label}, setting ${q(name)}`;
630
+ const about = field.description ? ` (${field.description})` : '';
631
+ let raw = given[name];
632
+ let fromEnv = false;
633
+ let variable;
634
+ if (isRecord(raw) && 'env' in raw) {
635
+ const keys = Object.keys(raw);
636
+ if (keys.length !== 1 || typeof raw.env !== 'string' || !ENV_NAME.test(raw.env)) {
637
+ errors.push(`${where}: an environment reference is {"env": "NAME"}, with NAME letters, digits and _.`);
638
+ continue;
639
+ }
640
+ variable = raw.env;
641
+ const read = env[variable];
642
+ if (read === undefined || read === '') {
643
+ errors.push(`${where}: the environment variable ${variable} is not set.`);
644
+ continue;
645
+ }
646
+ raw = read;
647
+ fromEnv = true;
648
+ }
649
+ else if (raw !== undefined && field.type === 'secret') {
650
+ warnings.push(`${where}: the secret is written into the configuration; give it as {"env": "NAME"} to keep it out of the file.`);
651
+ }
652
+ if (raw === undefined || raw === null) {
653
+ if (field.default !== undefined)
654
+ config[name] = convert(field.type, field.default);
655
+ else if (field.required)
656
+ errors.push(`${where} is required${about}.`);
657
+ continue;
658
+ }
659
+ const value = convert(field.type, raw, fromEnv);
660
+ if (value === undefined) {
661
+ const source = variable ? `the environment variable ${variable} holds` : 'got';
662
+ const what = field.type === 'secret' || fromEnv ? (fromEnv ? 'something else' : kindOf(raw)) : `${kindOf(raw)} ${shown(raw)}`;
663
+ errors.push(`${where}: expected ${typeWords(field.type)}, ${source} ${what}.`);
664
+ continue;
665
+ }
666
+ if (field.required && (value === '' || (Array.isArray(value) && value.length === 0) || (field.type === 'map' && isRecord(value) && Object.keys(value).length === 0))) {
667
+ errors.push(`${where} is required${about}, and it is empty.`);
668
+ continue;
669
+ }
670
+ if (field.type === 'secret' && typeof value === 'string' && value !== '')
671
+ secrets.push(value);
672
+ config[name] = value;
673
+ }
674
+ return { config: Object.freeze(config), errors, warnings, secrets };
675
+ }
676
+ /** Replaces every secret in `text` with `[secret]`. */
677
+ export function redact(text, secrets) {
678
+ let out = text;
679
+ for (const secret of secrets)
680
+ if (secret.length >= 4)
681
+ out = out.split(secret).join('[secret]');
682
+ return out;
683
+ }
684
+ // ---------------------------------------------------------------------------
685
+ // Answers
686
+ const ROLES = ['owner', 'editor', 'commenter', 'viewer'];
687
+ /** Whether a value is an artifact role. */
688
+ export function isArtifactRole(value) {
689
+ return typeof value === 'string' && ROLES.includes(value);
690
+ }
691
+ const LIMITS = { subject: 256, email: 320, name: 200, avatar: 2048, groups: 200, group: 200 };
692
+ /** An identity a plugin answered, cleaned (unknown fields dropped), or null when it is not one. */
693
+ export function checkIdentity(value) {
694
+ if (!isRecord(value))
695
+ return null;
696
+ const { subject, email, emailVerified, name, avatar, groups } = value;
697
+ if (typeof subject !== 'string' || subject.length === 0 || subject.length > LIMITS.subject)
698
+ return null;
699
+ if (email !== undefined && (typeof email !== 'string' || email.length > LIMITS.email || (email !== '' && !email.includes('@'))))
700
+ return null;
701
+ if (emailVerified !== undefined && typeof emailVerified !== 'boolean')
702
+ return null;
703
+ if (name !== undefined && (typeof name !== 'string' || name.length > LIMITS.name))
704
+ return null;
705
+ if (avatar !== undefined && (typeof avatar !== 'string' || avatar.length > LIMITS.avatar))
706
+ return null;
707
+ if (groups !== undefined && (!Array.isArray(groups) || groups.length > LIMITS.groups || !groups.every((g) => typeof g === 'string' && g.length > 0 && g.length <= LIMITS.group)))
708
+ return null;
709
+ return {
710
+ subject,
711
+ ...(typeof email === 'string' && email !== '' ? { email } : {}),
712
+ ...(emailVerified !== undefined ? { emailVerified } : {}),
713
+ ...(typeof name === 'string' && name !== '' ? { name } : {}),
714
+ ...(typeof avatar === 'string' && avatar !== '' ? { avatar } : {}),
715
+ ...(groups !== undefined ? { groups: [...groups] } : {}),
716
+ };
717
+ }
718
+ /** A sentence a plugin gave (a refusal, a denial), trimmed and cut to 500 characters, or null when it is not one. */
719
+ export function checkSentence(value) {
720
+ if (typeof value !== 'string')
721
+ return null;
722
+ const text = value.trim();
723
+ return text ? (text.length > 500 ? `${text.slice(0, 497)}...` : text) : null;
724
+ }
725
+ /** Whether a value is a `Response` (also one made by another copy of the Fetch API). */
726
+ export function isResponse(value) {
727
+ if (value instanceof Response)
728
+ return true;
729
+ return isRecord(value) && typeof value.status === 'number' && value.headers instanceof Headers && 'body' in value && typeof value.arrayBuffer === 'function';
730
+ }
731
+ /** The path to return to after a sign-in: a path on the site, else `/`. */
732
+ export function safePath(value) {
733
+ return typeof value === 'string' && value.startsWith('/') && !value.startsWith('//') && !value.startsWith('/\\') ? value : '/';
734
+ }
735
+ /**
736
+ * Runs `fn` with a time limit: the outcome of the call, or `timeout` when it takes longer than `ms`. `controller`
737
+ * is aborted at the limit (the hook's `ctx.signal`). A hook that hangs keeps running in the background; nobody
738
+ * waits for it.
739
+ */
740
+ export async function withTimeLimit(fn, ms, controller) {
741
+ let timer;
742
+ const expired = new Promise((resolve) => {
743
+ timer = setTimeout(() => {
744
+ controller?.abort(new Error(`the hook took longer than ${ms} ms`));
745
+ resolve({ ok: false, reason: 'timeout', error: new Error(`took longer than ${ms} ms`) });
746
+ }, ms);
747
+ });
748
+ const run = (async () => {
749
+ try {
750
+ return { ok: true, value: await fn() };
751
+ }
752
+ catch (error) {
753
+ return { ok: false, reason: 'threw', error };
754
+ }
755
+ })();
756
+ try {
757
+ return await Promise.race([run, expired]);
758
+ }
759
+ finally {
760
+ clearTimeout(timer);
761
+ }
762
+ }
763
+ /** A failure's message for the log. */
764
+ export function messageOf(error) {
765
+ return error instanceof Error ? error.message : String(error);
766
+ }
767
+ // ---------------------------------------------------------------------------
768
+ // Routes and writes
769
+ /** The parameters of `path` under a route's segments, or null when it does not match. */
770
+ export function matchRoute(segments, path) {
771
+ const params = {};
772
+ for (let i = 0; i < segments.length; i++) {
773
+ const want = segments[i];
774
+ if (want === '*') {
775
+ params['*'] = path.slice(i).join('/');
776
+ return params;
777
+ }
778
+ const got = path[i];
779
+ if (got === undefined)
780
+ return null;
781
+ if (want.startsWith(':')) {
782
+ try {
783
+ params[want.slice(1)] = decodeURIComponent(got);
784
+ }
785
+ catch {
786
+ return null;
787
+ }
788
+ }
789
+ else if (want !== got) {
790
+ return null;
791
+ }
792
+ }
793
+ return path.length === segments.length ? params : null;
794
+ }
795
+ const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
796
+ /**
797
+ * The host's same-origin rule for writes, as it applies to plugin routes that are not `public`: reads always pass;
798
+ * a write passes with `Sec-Fetch-Site: same-origin` (or `none` without cookies), or, from a client that sends no
799
+ * `Sec-Fetch-Site`, with no `Origin` or the site's own.
800
+ */
801
+ export function isSameOriginWrite(request, appOrigin) {
802
+ if (SAFE_METHODS.has(request.method.toUpperCase()))
803
+ return true;
804
+ const site = request.headers.get('sec-fetch-site');
805
+ if (site !== null) {
806
+ const value = site.trim().toLowerCase();
807
+ if (value === 'same-origin')
808
+ return true;
809
+ return value === 'none' && !request.headers.has('cookie');
810
+ }
811
+ const origin = request.headers.get('origin');
812
+ return origin === null || origin === appOrigin;
813
+ }
814
+ // ---------------------------------------------------------------------------
815
+ // The key-value store
816
+ /** The UTF-8 length of a string. */
817
+ export function byteLength(text) {
818
+ return new TextEncoder().encode(text).byteLength;
819
+ }
820
+ /** Checks a key; throws a `TypeError` the plugin sees. */
821
+ export function checkKvKey(key) {
822
+ if (typeof key !== 'string' || key.length === 0)
823
+ throw new TypeError('kv: a key is a non-empty string.');
824
+ if (byteLength(key) > KV_LIMITS.maxKeyBytes)
825
+ throw new TypeError(`kv: a key is at most ${KV_LIMITS.maxKeyBytes} bytes.`);
826
+ return key;
827
+ }
828
+ /** A value as stored (JSON); throws a `TypeError` the plugin sees. */
829
+ export function encodeKvValue(value) {
830
+ let text;
831
+ try {
832
+ text = JSON.stringify(value);
833
+ }
834
+ catch (error) {
835
+ throw new TypeError(`kv: the value cannot be stored as JSON (${messageOf(error)}).`);
836
+ }
837
+ if (text === undefined)
838
+ throw new TypeError('kv: the value cannot be stored as JSON (use null, not undefined).');
839
+ if (byteLength(text) > KV_LIMITS.maxValueBytes)
840
+ throw new TypeError(`kv: a value is at most ${KV_LIMITS.maxValueBytes} bytes of JSON.`);
841
+ return text;
842
+ }
843
+ /** When a value set now with `ttlSeconds` expires (ISO-8601), or null; throws a `TypeError` for a bad TTL. */
844
+ export function kvExpiry(now, ttlSeconds) {
845
+ if (ttlSeconds === undefined)
846
+ return null;
847
+ if (typeof ttlSeconds !== 'number' || !Number.isFinite(ttlSeconds) || ttlSeconds <= 0)
848
+ throw new TypeError('kv: ttlSeconds is a number of seconds above 0.');
849
+ return new Date(now.getTime() + Math.ceil(ttlSeconds * 1000)).toISOString();
850
+ }
851
+ /** A listing's limit: default 100, at most 1000. */
852
+ export function kvListLimit(limit) {
853
+ if (limit === undefined)
854
+ return KV_LIMITS.defaultList;
855
+ if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 1)
856
+ throw new TypeError('kv: limit is a whole number above 0.');
857
+ return Math.min(limit, KV_LIMITS.maxList);
858
+ }
859
+ /** The error for a store that is full. */
860
+ export function kvFull() {
861
+ return new RangeError(`kv: this plugin already keeps ${KV_LIMITS.maxKeys} keys; delete some (or give them a ttlSeconds) first.`);
862
+ }
863
+ /** Calls a hook under its time limit and checks its answer. Never throws. */
864
+ export async function runHook(fn, check, ms, controller) {
865
+ const outcome = await withTimeLimit(fn, ms, controller);
866
+ if (!outcome.ok)
867
+ return { ok: false, reason: outcome.reason, message: messageOf(outcome.error), error: outcome.error };
868
+ const checked = check(outcome.value);
869
+ return checked.ok ? checked : { ok: false, reason: 'shape', message: checked.message };
870
+ }
871
+ const good = (value) => ({ ok: true, value });
872
+ const bad = (message) => ({ ok: false, message });
873
+ /**
874
+ * The answer check of every hook: what an answer means, or why it is not one the hook may give. An answer of the
875
+ * wrong shape is a failure (closed or open by the hook's kind, see {@link failsClosed}).
876
+ */
877
+ export const answers = {
878
+ /** `auth.authenticate`: an identity, or null (nothing: null too). */
879
+ authenticate(answer) {
880
+ if (answer === undefined || answer === null)
881
+ return good(null);
882
+ const identity = checkIdentity(answer);
883
+ return identity ? good(identity) : bad('answered something that is not an identity ({subject, email?, emailVerified?, name?, avatar?, groups?}) or null');
884
+ },
885
+ /** `auth.signIn.start`: a Response. */
886
+ signInStart(answer) {
887
+ return isResponse(answer) ? good(answer) : bad('must answer a Response (usually a redirect)');
888
+ },
889
+ /** `auth.signIn.finish`: `{identity, returnTo?}` (returnTo made a path on the site). */
890
+ signInFinish(answer) {
891
+ if (!isRecord(answer))
892
+ return bad('must answer {identity, returnTo?}');
893
+ const identity = checkIdentity(answer.identity);
894
+ if (!identity)
895
+ return bad('answered {identity} with something that is not an identity');
896
+ if (answer.returnTo !== undefined && typeof answer.returnTo !== 'string')
897
+ return bad('answered a returnTo that is not a string');
898
+ return good({ identity, ...(answer.returnTo !== undefined ? { returnTo: safePath(answer.returnTo) } : {}) });
899
+ },
900
+ /** `auth.identity`: the same person (same `subject`) changed, `{reject}`, or nothing (`keep`). */
901
+ identity(answer, subject) {
902
+ if (answer === undefined || answer === null)
903
+ return good({ keep: true });
904
+ if (isRecord(answer) && 'reject' in answer) {
905
+ const sentence = checkSentence(answer.reject);
906
+ return sentence ? good({ reject: sentence }) : bad('answered {reject} without a sentence');
907
+ }
908
+ const identity = checkIdentity(answer);
909
+ if (!identity)
910
+ return bad('answered something that is not an identity, {reject: sentence} or nothing');
911
+ if (identity.subject !== subject)
912
+ return bad('changed the identity\'s subject, which it may not (it would sign the person in as someone else)');
913
+ return good({ identity });
914
+ },
915
+ /** `auth.signOutUrl`: an `https:`/`http:` URL or a path, or nothing (null). */
916
+ signOutUrl(answer) {
917
+ if (answer === undefined || answer === null)
918
+ return good(null);
919
+ return isSafeHref(answer) ? good(answer) : bad('answered something that is not an https: or http: address or a path');
920
+ },
921
+ /** `authz.role`: a role, null (no access), or nothing (`opinion: false`). */
922
+ role(answer) {
923
+ if (answer === undefined)
924
+ return good({ opinion: false });
925
+ if (answer === null)
926
+ return good({ opinion: true, role: null });
927
+ return isArtifactRole(answer) ? good({ opinion: true, role: answer }) : bad(`answered ${shown(answer)}, which is not a role (owner, editor, commenter, viewer), null or nothing`);
928
+ },
929
+ /** `authz.artifacts`: artifact ids (nothing: none). */
930
+ artifacts(answer) {
931
+ if (answer === undefined || answer === null)
932
+ return good([]);
933
+ if (!Array.isArray(answer) || !answer.every((id) => typeof id === 'string'))
934
+ return bad('must answer a list of artifact ids (strings)');
935
+ if (answer.length > 10_000)
936
+ return bad('answered more than 10000 artifact ids');
937
+ return good([...new Set(answer)]);
938
+ },
939
+ /** `guard`: nothing (allowed) or `{deny: sentence}`. */
940
+ guard(answer) {
941
+ if (answer === undefined || answer === null)
942
+ return good(null);
943
+ if (isRecord(answer) && 'deny' in answer) {
944
+ const sentence = checkSentence(answer.deny);
945
+ return sentence ? good({ deny: sentence }) : bad('answered {deny} without a sentence');
946
+ }
947
+ return bad('must answer nothing (allowed) or {deny: sentence}');
948
+ },
949
+ /** `wake.deliver`: `{delivered: true}` (true), or nothing (false). */
950
+ deliver(answer) {
951
+ if (answer === undefined || answer === null)
952
+ return good(false);
953
+ if (isRecord(answer) && answer.delivered === true)
954
+ return good(true);
955
+ if (isRecord(answer) && answer.delivered === false)
956
+ return good(false);
957
+ return bad('must answer {delivered: true} or nothing');
958
+ },
959
+ /** A route handler: a Response. */
960
+ route(answer) {
961
+ return isResponse(answer) ? good(answer) : bad('must answer a Response');
962
+ },
963
+ /** An event handler: anything (its answer is not used). */
964
+ event() {
965
+ return good(null);
966
+ },
967
+ };
968
+ /** Whether an error is the plugin API's `HttpError` (also from another copy of this package): a route's chosen status. */
969
+ export function httpErrorOf(error) {
970
+ if (!(error instanceof Error) || error.name !== 'HttpError')
971
+ return null;
972
+ const status = error.status;
973
+ return typeof status === 'number' && status >= 400 && status <= 599 ? { status, message: error.message } : null;
974
+ }
975
+ /**
976
+ * Runs a plugin's `validate(config)` the way every host does: once, after {@link validateConfig} passed. Returns the
977
+ * problems, each naming the plugin (`Plugin "acme": …`); an exception counts as one problem with its message.
978
+ */
979
+ export function runValidate(plugin, config) {
980
+ const validate = plugin.source.validate;
981
+ if (typeof validate !== 'function')
982
+ return [];
983
+ const label = `Plugin ${q(plugin.id)}`;
984
+ let answer;
985
+ try {
986
+ answer = validate.call(plugin.source, config);
987
+ }
988
+ catch (error) {
989
+ return [`${label}: ${messageOf(error)}`];
990
+ }
991
+ if (answer === undefined || answer === null)
992
+ return [];
993
+ if (typeof answer === 'string')
994
+ return answer.trim() ? [`${label}: ${answer.trim()}`] : [];
995
+ if (Array.isArray(answer))
996
+ return answer.filter((m) => typeof m === 'string' && m.trim() !== '').map((m) => `${label}: ${m.trim()}`);
997
+ if (typeof answer.then === 'function')
998
+ return [`${label}: validate must answer at once (it returned a promise); check settings without waiting.`];
999
+ return [`${label}: validate answered ${kindOf(answer)}; it returns nothing, a sentence or a list of sentences.`];
1000
+ }