@usebecky/extension 0.0.0-stage → 0.2.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.
Files changed (65) hide show
  1. package/README.md +223 -2
  2. package/dist/accounts.d.ts +85 -0
  3. package/dist/accounts.js +149 -0
  4. package/dist/cli/index.d.ts +2 -0
  5. package/dist/cli/index.js +9 -0
  6. package/dist/cli/run.d.ts +25 -0
  7. package/dist/cli/run.js +330 -0
  8. package/dist/cli/skill.d.ts +16 -0
  9. package/dist/cli/skill.js +106 -0
  10. package/dist/crypto.d.ts +12 -0
  11. package/dist/crypto.js +56 -0
  12. package/dist/dev/pages.d.ts +155 -0
  13. package/dist/dev/pages.js +243 -0
  14. package/dist/dev/plans.d.ts +45 -0
  15. package/dist/dev/plans.js +135 -0
  16. package/dist/dev/samples.d.ts +61 -0
  17. package/dist/dev/samples.js +191 -0
  18. package/dist/dev/server.d.ts +120 -0
  19. package/dist/dev/server.js +1657 -0
  20. package/dist/dev/tagging.d.ts +16 -0
  21. package/dist/dev/tagging.js +81 -0
  22. package/dist/dev/ui-render.d.ts +25 -0
  23. package/dist/dev/ui-render.js +256 -0
  24. package/dist/dev/wordmark.d.ts +1 -0
  25. package/dist/dev/wordmark.js +2 -0
  26. package/dist/errors.d.ts +98 -0
  27. package/dist/errors.js +110 -0
  28. package/dist/events.d.ts +92 -0
  29. package/dist/events.js +54 -0
  30. package/dist/extension.d.ts +214 -0
  31. package/dist/extension.js +497 -0
  32. package/dist/handlers.d.ts +39 -0
  33. package/dist/handlers.js +113 -0
  34. package/dist/identity.d.ts +99 -0
  35. package/dist/identity.js +134 -0
  36. package/dist/index.d.ts +14 -0
  37. package/dist/index.js +17 -0
  38. package/dist/jwt.d.ts +62 -0
  39. package/dist/jwt.js +152 -0
  40. package/dist/manifest.d.ts +42 -0
  41. package/dist/manifest.js +785 -0
  42. package/dist/node.d.ts +10 -0
  43. package/dist/node.js +56 -0
  44. package/dist/pkce.d.ts +9 -0
  45. package/dist/pkce.js +16 -0
  46. package/dist/stores.d.ts +100 -0
  47. package/dist/stores.js +159 -0
  48. package/dist/types.d.ts +346 -0
  49. package/dist/types.js +70 -0
  50. package/dist/ui/handler.d.ts +66 -0
  51. package/dist/ui/handler.js +105 -0
  52. package/dist/ui/schema.d.ts +423 -0
  53. package/dist/ui/schema.js +666 -0
  54. package/dist/webhooks.d.ts +26 -0
  55. package/dist/webhooks.js +99 -0
  56. package/package.json +57 -4
  57. package/skill/usebecky-extension/SKILL.md +181 -0
  58. package/skill/usebecky-extension/references/accounts.md +125 -0
  59. package/skill/usebecky-extension/references/dev-server.md +102 -0
  60. package/skill/usebecky-extension/references/manifest.md +104 -0
  61. package/skill/usebecky-extension/references/oauth-and-tokens.md +179 -0
  62. package/skill/usebecky-extension/references/partner-api.md +87 -0
  63. package/skill/usebecky-extension/references/submit-and-pricing.md +31 -0
  64. package/skill/usebecky-extension/references/ui.md +172 -0
  65. package/skill/usebecky-extension/references/webhooks.md +97 -0
@@ -0,0 +1,666 @@
1
+ // Extension pages in usebecky: the blocks an extension's server answers with, and the checks usebecky applies to them.
2
+ // usebecky draws these blocks with its own dashboard components (never the extension's code, never an iframe), so every
3
+ // extension looks and behaves like the rest of usebecky. Design: docs/ops/extensions/ui.md.
4
+ //
5
+ // THE source. scripts/sync-ui-schema.mjs copies this file (GENERATED header) to the server
6
+ // (packages/server/src/modules/extensions/ui-schema.ts) and the dashboard (apps/dashboard/src/lib/extension-ui-schema.ts);
7
+ // the kit's tests fail while a copy is out of date. Keep it self-contained: no imports, erasable TypeScript only.
8
+ // ---- Limits ------------------------------------------------------------------------------------------------------
9
+ export const UI_LIMITS = {
10
+ /** Answer size, bytes (usebecky reads no more). */
11
+ responseBytes: 512 * 1024,
12
+ /** Blocks, buttons, items, rows and fields in one view, counted together. */
13
+ nodes: 1500,
14
+ /** Lists of blocks inside each other: the view's, a section's, a column's (sections and columns nest at most twice). */
15
+ depth: 3,
16
+ /** Blocks in one list (the view's, a section's, one column's). */
17
+ blocks: 60,
18
+ /** Short text: labels, titles, values, cells. */
19
+ short: 500,
20
+ /** A text block or a notice. */
21
+ text: 5000,
22
+ /** A code block. */
23
+ code: 20_000,
24
+ title: 80,
25
+ description: 300,
26
+ label: 60,
27
+ viewActions: 3,
28
+ stats: 8,
29
+ series: 6,
30
+ points: 400,
31
+ bars: 50,
32
+ listItems: 50,
33
+ columns: 12,
34
+ rows: 100,
35
+ rowActions: 3,
36
+ bulkActions: 3,
37
+ filters: 3,
38
+ filterOptions: 50,
39
+ fields: 30,
40
+ options: 100,
41
+ buttons: 6,
42
+ tabs: 8,
43
+ columnsMin: 2,
44
+ columnsMax: 3,
45
+ params: 10,
46
+ paramValue: 200,
47
+ url: 2000,
48
+ toast: 200,
49
+ /** Rows sent with one bulk action. */
50
+ selectedRows: 100,
51
+ /** Characters of one form value sent to the extension. */
52
+ value: 10_000,
53
+ /** The largest number a chart, bar, stat change or total may hold (bigger ones break axes and formats). */
54
+ number: 1e15,
55
+ /** View.refresh_seconds: the dashboard asks for the page again every 5 to 60 seconds while it is open and in view, */
56
+ refreshMin: 5,
57
+ refreshMax: 60,
58
+ /** and stops after 30 minutes. */
59
+ refreshStopMs: 30 * 60_000,
60
+ };
61
+ /** Sidebar groups an extension's page may sit in (the dashboard's NAV_SECTIONS minus Home's). */
62
+ export const UI_SECTIONS = ['backend', 'website', 'messages', 'project'];
63
+ /** The view on the extension's own page under Extensions (listing `ui.settings: true`). */
64
+ export const SETTINGS_PAGE = 'settings';
65
+ export const PAGE_ID = /^[a-z][a-z0-9-]{0,31}$/;
66
+ export const ACTION_ID = /^[a-z][a-z0-9_-]{0,39}$/;
67
+ export const PARAM_KEY = /^[a-z][a-z0-9_]{0,31}$/;
68
+ export const FIELD_KEY = /^[a-z][a-z0-9_]{0,39}$/;
69
+ /** A price plan's id in the listing's pricing ("monthly" for a monthly listing's one plan). */
70
+ export const PLAN_ID = /^[a-z0-9-]{1,30}$/;
71
+ const CURRENCY = /^[A-Z]{3}$/;
72
+ /** Names that already mean something on every JavaScript object ("constructor", "toString"…): never a key or a param. */
73
+ export function isReservedName(name) {
74
+ return name in Object.prototype;
75
+ }
76
+ export const UI_EVENT_TYPE = 'extension.ui';
77
+ /**
78
+ * The little markup text blocks and notices understand: **bold**, `code` and [label](https://…). Nothing nests and
79
+ * nothing else is markup; a link that isn't https stays plain text. The dashboard and the dev server draw these tokens,
80
+ * never HTML from the extension.
81
+ */
82
+ export function inlineTokens(s) {
83
+ const out = [];
84
+ // Every part stops at the next character that could start another one, so a long text is read once (no backtracking).
85
+ const re = /\*\*([^*\n]{1,500})\*\*|`([^`\n]{1,500})`|\[([^[\]\n]{1,200})\]\(([^()\s]{1,2000})\)/g;
86
+ let last = 0;
87
+ for (let m = re.exec(s); m; m = re.exec(s)) {
88
+ if (m.index > last)
89
+ out.push({ t: 'text', v: s.slice(last, m.index) });
90
+ if (m[1] !== undefined)
91
+ out.push({ t: 'bold', v: m[1] });
92
+ else if (m[2] !== undefined)
93
+ out.push({ t: 'code', v: m[2] });
94
+ else if (isHttpsUrl(m[4]))
95
+ out.push({ t: 'link', v: m[3], href: m[4] });
96
+ else
97
+ out.push({ t: 'text', v: m[0] });
98
+ last = m.index + m[0].length;
99
+ }
100
+ if (last < s.length)
101
+ out.push({ t: 'text', v: s.slice(last) });
102
+ return out;
103
+ }
104
+ export function isHttpsUrl(v) {
105
+ if (typeof v !== 'string' || v.length > UI_LIMITS.url)
106
+ return false;
107
+ try {
108
+ const u = new URL(v);
109
+ return u.protocol === 'https:' && !u.username && !u.password;
110
+ }
111
+ catch {
112
+ return false;
113
+ }
114
+ }
115
+ class Problem extends Error {
116
+ path;
117
+ constructor(path, message) {
118
+ super(message);
119
+ this.path = path;
120
+ }
121
+ }
122
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
123
+ const at = (path, key) => (path ? `${path}.${key}` : String(key));
124
+ const where = (path) => (path ? ` in ${path}` : '');
125
+ function count(w, path) {
126
+ if (++w.nodes > UI_LIMITS.nodes)
127
+ throw new Problem(path, `The page has too many parts (more than ${UI_LIMITS.nodes} blocks, rows, items, buttons and fields together). Show fewer rows a page and let people page through them (next_cursor).`);
128
+ }
129
+ function keys(path, o, allowed, what) {
130
+ for (const k of Object.keys(o)) {
131
+ if (!allowed.includes(k))
132
+ throw new Problem(at(path, k), `Unknown property "${k}"${where(path)} (${what}). Use ${allowed.map((a) => `"${a}"`).join(', ')}.`);
133
+ }
134
+ }
135
+ function obj(path, v, what) {
136
+ if (!isObj(v))
137
+ throw new Problem(path, `${path || 'The answer'} must be an object (${what}).`);
138
+ return v;
139
+ }
140
+ function list(path, v, max, what, min = 0) {
141
+ if (!Array.isArray(v))
142
+ throw new Problem(path, `${path} must be a list of ${what}.`);
143
+ if (v.length > max)
144
+ throw new Problem(path, `${path} has ${v.length} ${what}; at most ${max}.`);
145
+ if (v.length < min)
146
+ throw new Problem(path, `${path} needs at least ${min} ${what}.`);
147
+ return v;
148
+ }
149
+ function str(path, v, max, opts = {}) {
150
+ if (v === undefined && opts.optional)
151
+ return undefined;
152
+ if (typeof v !== 'string') {
153
+ const got = v === undefined ? 'nothing' : v === null ? 'null' : typeof v === 'number' ? 'a number' : Array.isArray(v) ? 'a list' : typeof v;
154
+ throw new Problem(path, `${path} must be text (got ${got}).${typeof v === 'number' ? ' Format numbers the way they should show, like "1,204".' : ''}`);
155
+ }
156
+ if (!opts.empty && !v.trim())
157
+ throw new Problem(path, `${path} can't be empty.`);
158
+ if (v.length > max)
159
+ throw new Problem(path, `${path} is too long (${v.length} characters, at most ${max}).`);
160
+ return v;
161
+ }
162
+ function num(path, v, opts = {}) {
163
+ if (v === undefined && opts.optional)
164
+ return undefined;
165
+ if (typeof v !== 'number' || !Number.isFinite(v))
166
+ throw new Problem(path, `${path} must be a number.`);
167
+ if (Math.abs(v) > UI_LIMITS.number)
168
+ throw new Problem(path, `${path} is too large (at most ${UI_LIMITS.number.toExponential()} either way).`);
169
+ if (opts.min !== undefined && v < opts.min)
170
+ throw new Problem(path, `${path} can't be below ${opts.min}.`);
171
+ return v;
172
+ }
173
+ function bool(path, v) {
174
+ if (v !== undefined && typeof v !== 'boolean')
175
+ throw new Problem(path, `${path} must be true or false.`);
176
+ }
177
+ function oneOf(path, v, options, opts = {}) {
178
+ if (v === undefined && opts.optional)
179
+ return undefined;
180
+ if (!options.includes(v))
181
+ throw new Problem(path, `${path} must be ${options.map((o) => `"${o}"`).join(', ').replace(/, ([^,]*)$/, ' or $1')}.`);
182
+ return v;
183
+ }
184
+ function url(path, v) {
185
+ if (!isHttpsUrl(v))
186
+ throw new Problem(path, `${path} must be a full https:// address (no username or password, at most ${UI_LIMITS.url} characters).`);
187
+ }
188
+ function page(path, v, w) {
189
+ if (typeof v !== 'string' || !PAGE_ID.test(v))
190
+ throw new Problem(path, `${path} must be a page id: lowercase letters, digits and dashes, like "reviews".`);
191
+ if (w.pages && !w.pages.includes(v))
192
+ throw new Problem(path, `${path} opens the page "${v}", which isn't in the listing's ui.pages${w.pages.includes(SETTINGS_PAGE) ? ' (or "settings")' : ''}.`);
193
+ }
194
+ export function checkParams(path, v) {
195
+ const o = obj(path, v, 'text values by name, like {"tab": "open"}');
196
+ const entries = Object.entries(o);
197
+ if (entries.length > UI_LIMITS.params)
198
+ throw new Problem(path, `${path} has ${entries.length} values; at most ${UI_LIMITS.params}.`);
199
+ for (const [k, val] of entries) {
200
+ if (!PARAM_KEY.test(k))
201
+ throw new Problem(at(path, k), `"${k}" can't be a parameter name: lowercase letters, digits and underscores, starting with a letter.`);
202
+ if (isReservedName(k))
203
+ throw new Problem(at(path, k), `"${k}" is a reserved name; pick another parameter name.`);
204
+ str(at(path, k), val, UI_LIMITS.paramValue, { empty: true });
205
+ }
206
+ return o;
207
+ }
208
+ function variant(path, v) {
209
+ oneOf(at(path, 'variant'), v, ['primary', 'secondary', 'danger'], { optional: true });
210
+ }
211
+ function button(path, v, w, opts = {}) {
212
+ count(w, path);
213
+ const o = obj(path, v, 'a button: {"label", and "action", "page", "url" or "plan"}');
214
+ str(at(path, 'label'), o.label, UI_LIMITS.label);
215
+ variant(path, o.variant);
216
+ const kinds = ['action', 'page', 'url', 'plan'].filter((k) => o[k] !== undefined);
217
+ if (opts.actionOnly && (kinds.length !== 1 || kinds[0] !== 'action'))
218
+ throw new Problem(path, `${path} must run an action: {"label": "Archive", "action": "archive"}.`);
219
+ if (kinds.length !== 1)
220
+ throw new Problem(path, `${path} needs exactly one of "action" (runs an action), "page" (opens one of your pages), "url" (opens an address in a new tab) or "plan" (opens usebecky's plan dialog).`);
221
+ if (o.action !== undefined) {
222
+ keys(path, o, ['label', 'action', 'row', 'variant', 'confirm'], 'an action button');
223
+ if (typeof o.action !== 'string' || !ACTION_ID.test(o.action))
224
+ throw new Problem(at(path, 'action'), `${at(path, 'action')} must be an action id: lowercase letters, digits, "-" and "_", like "approve".`);
225
+ str(at(path, 'row'), o.row, UI_LIMITS.short, { optional: true });
226
+ str(at(path, 'confirm'), o.confirm, UI_LIMITS.short, { optional: true });
227
+ }
228
+ else if (o.page !== undefined) {
229
+ keys(path, o, ['label', 'page', 'params', 'variant'], 'a page button');
230
+ page(at(path, 'page'), o.page, w);
231
+ if (o.params !== undefined)
232
+ checkParams(at(path, 'params'), o.params);
233
+ }
234
+ else if (o.plan !== undefined) {
235
+ keys(path, o, ['label', 'plan', 'variant'], 'a plan button');
236
+ if (typeof o.plan !== 'string' || !PLAN_ID.test(o.plan))
237
+ throw new Problem(at(path, 'plan'), `${at(path, 'plan')} must be the id of one of your listing's plans: 1 to 30 lowercase letters, digits and dashes, like "pro".`);
238
+ }
239
+ else {
240
+ keys(path, o, ['label', 'url', 'variant'], 'a link button');
241
+ url(at(path, 'url'), o.url);
242
+ }
243
+ }
244
+ function buttons(path, v, max, w, opts = {}) {
245
+ const items = list(path, v, max, 'buttons');
246
+ items.forEach((b, i) => button(at(path, i), b, w, opts));
247
+ if (items.filter((b) => isObj(b) && b.variant === 'primary').length > 1)
248
+ throw new Problem(path, `${path} has more than one primary button. Keep one main action; make the others "secondary".`);
249
+ }
250
+ function textOf(path, v, max) {
251
+ const s = str(path, v, max);
252
+ // A link that isn't https would show as plain text: say so instead.
253
+ for (const m of s.matchAll(/\[([^[\]\n]{1,200})\]\(([^()\s]{1,2000})\)/g)) {
254
+ if (!isHttpsUrl(m[2]))
255
+ throw new Problem(path, `${path} links to "${m[2].slice(0, 60)}": links must be full https:// addresses.`);
256
+ }
257
+ }
258
+ function cell(path, v, w) {
259
+ if (v === null || typeof v === 'number') {
260
+ if (typeof v === 'number' && (!Number.isFinite(v) || Math.abs(v) > UI_LIMITS.number))
261
+ throw new Problem(path, `${path} must be a number of at most ${UI_LIMITS.number.toExponential()} either way.`);
262
+ return;
263
+ }
264
+ if (typeof v === 'string') {
265
+ str(path, v, UI_LIMITS.short, { empty: true });
266
+ return;
267
+ }
268
+ const o = obj(path, v, 'text, a number, null, {"text", "tone"}, {"text", "url"} or {"text", "page"}');
269
+ str(at(path, 'text'), o.text, UI_LIMITS.short);
270
+ if (o.tone !== undefined) {
271
+ keys(path, o, ['text', 'tone'], 'a badge');
272
+ oneOf(at(path, 'tone'), o.tone, ['neutral', 'info', 'success', 'warning', 'danger']);
273
+ }
274
+ else if (o.url !== undefined) {
275
+ keys(path, o, ['text', 'url'], 'a link');
276
+ url(at(path, 'url'), o.url);
277
+ }
278
+ else if (o.page !== undefined) {
279
+ keys(path, o, ['text', 'page', 'params'], 'a link to one of your pages');
280
+ page(at(path, 'page'), o.page, w);
281
+ if (o.params !== undefined)
282
+ checkParams(at(path, 'params'), o.params);
283
+ }
284
+ else {
285
+ throw new Problem(path, `${path} needs "tone" (a badge), "url" (a link) or "page" (a link to one of your pages) next to "text".`);
286
+ }
287
+ }
288
+ function options(path, v, max) {
289
+ const items = list(path, v, max, 'options', 1);
290
+ const seen = new Set();
291
+ items.forEach((x, i) => {
292
+ const p = at(path, i);
293
+ const o = obj(p, x, '{"value", "label"}');
294
+ keys(p, o, ['value', 'label'], 'an option');
295
+ const value = str(at(p, 'value'), o.value, UI_LIMITS.paramValue, { empty: true });
296
+ if (seen.has(value))
297
+ throw new Problem(at(p, 'value'), `Two options of ${path} have the value "${value}".`);
298
+ seen.add(value);
299
+ str(at(p, 'label'), o.label, UI_LIMITS.label);
300
+ });
301
+ }
302
+ function field(path, v, seen, w) {
303
+ count(w, path);
304
+ const o = obj(path, v, 'a form field: {"key", "label", "type"}');
305
+ keys(path, o, ['key', 'label', 'type', 'help', 'placeholder', 'required', 'options', 'min', 'max', 'max_length'], 'a form field');
306
+ if (typeof o.key !== 'string' || !FIELD_KEY.test(o.key))
307
+ throw new Problem(at(path, 'key'), `${at(path, 'key')} must be 1 to 40 characters: lowercase letters, digits and underscores, starting with a letter.`);
308
+ if (isReservedName(o.key))
309
+ throw new Problem(at(path, 'key'), `"${o.key}" is a reserved name; pick another key.`);
310
+ if (seen.has(o.key))
311
+ throw new Problem(at(path, 'key'), `Two fields use the key "${o.key}".`);
312
+ seen.add(o.key);
313
+ str(at(path, 'label'), o.label, UI_LIMITS.label);
314
+ const type = oneOf(at(path, 'type'), o.type, ['text', 'textarea', 'number', 'email', 'url', 'password', 'select', 'checkbox']);
315
+ str(at(path, 'help'), o.help, UI_LIMITS.short, { optional: true });
316
+ str(at(path, 'placeholder'), o.placeholder, UI_LIMITS.label, { optional: true });
317
+ bool(at(path, 'required'), o.required);
318
+ if (type === 'select')
319
+ options(at(path, 'options'), o.options, UI_LIMITS.options);
320
+ else if (o.options !== undefined)
321
+ throw new Problem(at(path, 'options'), `Only "select" fields have options.`);
322
+ if (type === 'number') {
323
+ num(at(path, 'min'), o.min, { optional: true });
324
+ num(at(path, 'max'), o.max, { optional: true });
325
+ if (typeof o.min === 'number' && typeof o.max === 'number' && o.min > o.max)
326
+ throw new Problem(at(path, 'max'), `${at(path, 'max')} is below min.`);
327
+ }
328
+ else if (o.min !== undefined || o.max !== undefined) {
329
+ throw new Problem(at(path, o.min !== undefined ? 'min' : 'max'), 'Only "number" fields have min and max.');
330
+ }
331
+ if (o.max_length !== undefined) {
332
+ if (type === 'number' || type === 'select' || type === 'checkbox')
333
+ throw new Problem(at(path, 'max_length'), `A "${type}" field has no max_length.`);
334
+ if (!Number.isInteger(o.max_length) || o.max_length < 1 || o.max_length > UI_LIMITS.value)
335
+ throw new Problem(at(path, 'max_length'), `${at(path, 'max_length')} must be a whole number from 1 to ${UI_LIMITS.value}.`);
336
+ }
337
+ if (type === 'checkbox' && o.placeholder !== undefined)
338
+ throw new Problem(at(path, 'placeholder'), 'A checkbox has no placeholder.');
339
+ }
340
+ function fieldValue(path, v) {
341
+ if (v === null || typeof v === 'boolean')
342
+ return;
343
+ if (typeof v === 'number') {
344
+ if (!Number.isFinite(v))
345
+ throw new Problem(path, `${path} must be a finite number.`);
346
+ return;
347
+ }
348
+ str(path, v, UI_LIMITS.value, { empty: true });
349
+ }
350
+ function blocks(path, v, depth, w) {
351
+ if (depth > UI_LIMITS.depth)
352
+ throw new Problem(path, `Blocks are nested too deep${where(path)}: sections and columns go at most two levels deep, like a section with columns in it.`);
353
+ list(path, v, UI_LIMITS.blocks, 'blocks').forEach((b, i) => block(at(path, i), b, depth, w));
354
+ }
355
+ const BLOCK_TYPES = ['text', 'heading', 'notice', 'stats', 'chart', 'bars', 'table', 'list', 'form', 'buttons', 'code', 'empty', 'tabs', 'section', 'columns'];
356
+ function block(path, v, depth, w) {
357
+ count(w, path);
358
+ const o = obj(path, v, 'a block with a "type"');
359
+ const type = o.type;
360
+ if (typeof type !== 'string' || !BLOCK_TYPES.includes(type)) {
361
+ throw new Problem(at(path, 'type'), `${at(path, 'type')} ${type === undefined ? 'is missing' : `"${String(type).slice(0, 40)}" is not a block type`}. Use ${BLOCK_TYPES.map((t) => `"${t}"`).join(', ')}.`);
362
+ }
363
+ const what = `a "${type}" block`;
364
+ switch (type) {
365
+ case 'text':
366
+ keys(path, o, ['type', 'text', 'tone'], what);
367
+ textOf(at(path, 'text'), o.text, UI_LIMITS.text);
368
+ oneOf(at(path, 'tone'), o.tone, ['muted'], { optional: true });
369
+ return;
370
+ case 'heading':
371
+ keys(path, o, ['type', 'text'], what);
372
+ str(at(path, 'text'), o.text, UI_LIMITS.title);
373
+ return;
374
+ case 'notice':
375
+ keys(path, o, ['type', 'tone', 'title', 'text', 'action'], what);
376
+ oneOf(at(path, 'tone'), o.tone, ['info', 'success', 'warning', 'danger']);
377
+ str(at(path, 'title'), o.title, UI_LIMITS.title, { optional: true });
378
+ textOf(at(path, 'text'), o.text, UI_LIMITS.text);
379
+ if (o.action !== undefined)
380
+ button(at(path, 'action'), o.action, w);
381
+ return;
382
+ case 'stats':
383
+ keys(path, o, ['type', 'items'], what);
384
+ list(at(path, 'items'), o.items, UI_LIMITS.stats, 'stat tiles', 1).forEach((x, i) => {
385
+ const p = at(at(path, 'items'), i);
386
+ count(w, p);
387
+ const s = obj(p, x, 'a stat tile: {"label", "value"}');
388
+ keys(p, s, ['label', 'value', 'change', 'good', 'hint'], 'a stat tile');
389
+ str(at(p, 'label'), s.label, UI_LIMITS.label);
390
+ str(at(p, 'value'), s.value, UI_LIMITS.label);
391
+ num(at(p, 'change'), s.change, { optional: true });
392
+ oneOf(at(p, 'good'), s.good, ['up', 'down'], { optional: true });
393
+ str(at(p, 'hint'), s.hint, UI_LIMITS.label, { optional: true });
394
+ });
395
+ return;
396
+ case 'chart': {
397
+ keys(path, o, ['type', 'kind', 'title', 'labels', 'series', 'format', 'currency'], what);
398
+ oneOf(at(path, 'kind'), o.kind, ['line', 'column']);
399
+ str(at(path, 'title'), o.title, UI_LIMITS.title, { optional: true });
400
+ const labels = list(at(path, 'labels'), o.labels, UI_LIMITS.points, 'labels', 1);
401
+ labels.forEach((l, i) => str(at(at(path, 'labels'), i), l, UI_LIMITS.label, { empty: true }));
402
+ list(at(path, 'series'), o.series, UI_LIMITS.series, 'series', 1).forEach((x, i) => {
403
+ const p = at(at(path, 'series'), i);
404
+ count(w, p);
405
+ const s = obj(p, x, 'a series: {"name", "values"}');
406
+ keys(p, s, ['name', 'values'], 'a series');
407
+ str(at(p, 'name'), s.name, UI_LIMITS.label);
408
+ const values = list(at(p, 'values'), s.values, UI_LIMITS.points, 'values');
409
+ if (values.length !== labels.length)
410
+ throw new Problem(at(p, 'values'), `${at(p, 'values')} has ${values.length} values for ${labels.length} labels: give one value per label (null for a gap).`);
411
+ values.forEach((n, j) => {
412
+ if (n !== null && (typeof n !== 'number' || !Number.isFinite(n)))
413
+ throw new Problem(at(at(p, 'values'), j), `${at(at(p, 'values'), j)} must be a number or null.`);
414
+ if (typeof n === 'number' && Math.abs(n) > UI_LIMITS.number)
415
+ throw new Problem(at(at(p, 'values'), j), `${at(at(p, 'values'), j)} is too large (at most ${UI_LIMITS.number.toExponential()} either way).`);
416
+ });
417
+ });
418
+ const format = oneOf(at(path, 'format'), o.format, ['number', 'percent', 'currency'], { optional: true });
419
+ if (format === 'currency' && (typeof o.currency !== 'string' || !CURRENCY.test(o.currency)))
420
+ throw new Problem(at(path, 'currency'), `A "currency" chart needs "currency": a three-letter code like "EUR" or "USD".`);
421
+ if (format !== 'currency' && o.currency !== undefined)
422
+ throw new Problem(at(path, 'currency'), `"currency" only goes with "format": "currency".`);
423
+ return;
424
+ }
425
+ case 'bars':
426
+ keys(path, o, ['type', 'title', 'label_header', 'value_header', 'items'], what);
427
+ str(at(path, 'title'), o.title, UI_LIMITS.title, { optional: true });
428
+ str(at(path, 'label_header'), o.label_header, UI_LIMITS.label, { optional: true });
429
+ str(at(path, 'value_header'), o.value_header, UI_LIMITS.label, { optional: true });
430
+ list(at(path, 'items'), o.items, UI_LIMITS.bars, 'bars').forEach((x, i) => {
431
+ const p = at(at(path, 'items'), i);
432
+ count(w, p);
433
+ const b = obj(p, x, 'a bar: {"label", "value"}');
434
+ keys(p, b, ['label', 'value', 'display'], 'a bar');
435
+ str(at(p, 'label'), b.label, UI_LIMITS.short);
436
+ num(at(p, 'value'), b.value, { min: 0 });
437
+ str(at(p, 'display'), b.display, UI_LIMITS.label, { optional: true });
438
+ });
439
+ return;
440
+ case 'table': {
441
+ keys(path, o, ['type', 'columns', 'rows', 'empty', 'search', 'filters', 'sort', 'next_cursor', 'prev_cursor', 'total', 'bulk'], what);
442
+ const colKeys = new Set();
443
+ list(at(path, 'columns'), o.columns, UI_LIMITS.columns, 'columns', 1).forEach((x, i) => {
444
+ const p = at(at(path, 'columns'), i);
445
+ const c = obj(p, x, 'a column: {"key", "label"}');
446
+ keys(p, c, ['key', 'label', 'align', 'sortable'], 'a column');
447
+ if (typeof c.key !== 'string' || !FIELD_KEY.test(c.key))
448
+ throw new Problem(at(p, 'key'), `${at(p, 'key')} must be 1 to 40 characters: lowercase letters, digits and underscores, starting with a letter.`);
449
+ if (isReservedName(c.key))
450
+ throw new Problem(at(p, 'key'), `"${c.key}" is a reserved name; pick another key.`);
451
+ if (colKeys.has(c.key))
452
+ throw new Problem(at(p, 'key'), `Two columns use the key "${c.key}".`);
453
+ colKeys.add(c.key);
454
+ str(at(p, 'label'), c.label, UI_LIMITS.label);
455
+ oneOf(at(p, 'align'), c.align, ['left', 'right'], { optional: true });
456
+ bool(at(p, 'sortable'), c.sortable);
457
+ });
458
+ const rowIds = new Set();
459
+ list(at(path, 'rows'), o.rows, UI_LIMITS.rows, 'rows').forEach((x, i) => {
460
+ const p = at(at(path, 'rows'), i);
461
+ count(w, p);
462
+ const r = obj(p, x, 'a row: {"id", "cells"}');
463
+ keys(p, r, ['id', 'cells', 'actions'], 'a row');
464
+ const id = str(at(p, 'id'), r.id, UI_LIMITS.short);
465
+ if (rowIds.has(id))
466
+ throw new Problem(at(p, 'id'), `Two rows have the id "${id.slice(0, 60)}".`);
467
+ rowIds.add(id);
468
+ const cells = obj(at(p, 'cells'), r.cells, 'the row\'s values by column key');
469
+ for (const [k, c] of Object.entries(cells)) {
470
+ if (!colKeys.has(k))
471
+ throw new Problem(at(at(p, 'cells'), k), `${at(p, 'cells')} has "${k}", which isn't one of the columns.`);
472
+ cell(at(at(p, 'cells'), k), c, w);
473
+ }
474
+ if (r.actions !== undefined)
475
+ buttons(at(p, 'actions'), r.actions, UI_LIMITS.rowActions, w);
476
+ });
477
+ str(at(path, 'empty'), o.empty, UI_LIMITS.short, { optional: true });
478
+ if (o.search !== undefined) {
479
+ const p = at(path, 'search');
480
+ const s = obj(p, o.search, '{"param"?, "placeholder"?}');
481
+ keys(p, s, ['param', 'placeholder'], 'the search box');
482
+ if (s.param !== undefined && (typeof s.param !== 'string' || !PARAM_KEY.test(s.param) || isReservedName(s.param)))
483
+ throw new Problem(at(p, 'param'), `${at(p, 'param')} must be a parameter name like "q".`);
484
+ str(at(p, 'placeholder'), s.placeholder, UI_LIMITS.label, { optional: true });
485
+ }
486
+ if (o.filters !== undefined) {
487
+ list(at(path, 'filters'), o.filters, UI_LIMITS.filters, 'filters').forEach((x, i) => {
488
+ const p = at(at(path, 'filters'), i);
489
+ const f = obj(p, x, 'a filter: {"param", "label", "options"}');
490
+ keys(p, f, ['param', 'label', 'options'], 'a filter');
491
+ if (typeof f.param !== 'string' || !PARAM_KEY.test(f.param) || isReservedName(f.param))
492
+ throw new Problem(at(p, 'param'), `${at(p, 'param')} must be a parameter name like "status".`);
493
+ str(at(p, 'label'), f.label, UI_LIMITS.label);
494
+ options(at(p, 'options'), f.options, UI_LIMITS.filterOptions);
495
+ });
496
+ }
497
+ if (o.sort !== undefined) {
498
+ const p = at(path, 'sort');
499
+ const s = obj(p, o.sort, '{"column", "direction"}');
500
+ keys(p, s, ['column', 'direction'], 'the sort');
501
+ if (typeof s.column !== 'string' || !colKeys.has(s.column))
502
+ throw new Problem(at(p, 'column'), `${at(p, 'column')} must be the key of one of the columns.`);
503
+ oneOf(at(p, 'direction'), s.direction, ['asc', 'desc']);
504
+ }
505
+ str(at(path, 'next_cursor'), o.next_cursor, UI_LIMITS.paramValue, { optional: true });
506
+ str(at(path, 'prev_cursor'), o.prev_cursor, UI_LIMITS.paramValue, { optional: true });
507
+ if (o.total !== undefined && (!Number.isInteger(o.total) || o.total < 0 || o.total > UI_LIMITS.number))
508
+ throw new Problem(at(path, 'total'), `${at(path, 'total')} must be a whole number, 0 or more.`);
509
+ if (o.bulk !== undefined)
510
+ buttons(at(path, 'bulk'), o.bulk, UI_LIMITS.bulkActions, w, { actionOnly: true });
511
+ return;
512
+ }
513
+ case 'list':
514
+ keys(path, o, ['type', 'items'], what);
515
+ list(at(path, 'items'), o.items, UI_LIMITS.listItems, 'items', 1).forEach((x, i) => {
516
+ const p = at(at(path, 'items'), i);
517
+ count(w, p);
518
+ const it = obj(p, x, 'an item: {"label", "value"}');
519
+ keys(p, it, ['label', 'value', 'copy'], 'a list item');
520
+ str(at(p, 'label'), it.label, UI_LIMITS.label);
521
+ str(at(p, 'value'), it.value, UI_LIMITS.short, { empty: true });
522
+ bool(at(p, 'copy'), it.copy);
523
+ });
524
+ return;
525
+ case 'form': {
526
+ keys(path, o, ['type', 'action', 'fields', 'submit', 'values'], what);
527
+ if (typeof o.action !== 'string' || !ACTION_ID.test(o.action))
528
+ throw new Problem(at(path, 'action'), `${at(path, 'action')} must be an action id: lowercase letters, digits, "-" and "_", like "save".`);
529
+ const seen = new Set();
530
+ list(at(path, 'fields'), o.fields, UI_LIMITS.fields, 'fields', 1).forEach((f, i) => field(at(at(path, 'fields'), i), f, seen, w));
531
+ str(at(path, 'submit'), o.submit, UI_LIMITS.label);
532
+ if (o.values !== undefined) {
533
+ const values = obj(at(path, 'values'), o.values, 'the fields\' current values by key');
534
+ for (const [k, val] of Object.entries(values)) {
535
+ if (!seen.has(k))
536
+ throw new Problem(at(at(path, 'values'), k), `${at(path, 'values')} has "${k}", which isn't one of the fields.`);
537
+ fieldValue(at(at(path, 'values'), k), val);
538
+ }
539
+ }
540
+ return;
541
+ }
542
+ case 'buttons':
543
+ keys(path, o, ['type', 'items'], what);
544
+ buttons(at(path, 'items'), o.items, UI_LIMITS.buttons, w);
545
+ if (!o.items.length)
546
+ throw new Problem(at(path, 'items'), `${at(path, 'items')} needs at least one button.`);
547
+ return;
548
+ case 'code':
549
+ keys(path, o, ['type', 'text', 'copy'], what);
550
+ str(at(path, 'text'), o.text, UI_LIMITS.code);
551
+ bool(at(path, 'copy'), o.copy);
552
+ return;
553
+ case 'empty':
554
+ keys(path, o, ['type', 'title', 'text', 'action'], what);
555
+ str(at(path, 'title'), o.title, UI_LIMITS.title);
556
+ str(at(path, 'text'), o.text, UI_LIMITS.short, { optional: true });
557
+ if (o.action !== undefined)
558
+ button(at(path, 'action'), o.action, w);
559
+ return;
560
+ case 'tabs': {
561
+ keys(path, o, ['type', 'param', 'items', 'active'], what);
562
+ if (typeof o.param !== 'string' || !PARAM_KEY.test(o.param) || isReservedName(o.param))
563
+ throw new Problem(at(path, 'param'), `${at(path, 'param')} must be a parameter name like "tab".`);
564
+ const ids = new Set();
565
+ list(at(path, 'items'), o.items, UI_LIMITS.tabs, 'tabs', 2).forEach((x, i) => {
566
+ const p = at(at(path, 'items'), i);
567
+ count(w, p);
568
+ const t = obj(p, x, 'a tab: {"id", "label"}');
569
+ keys(p, t, ['id', 'label'], 'a tab');
570
+ const id = str(at(p, 'id'), t.id, UI_LIMITS.paramValue);
571
+ if (ids.has(id))
572
+ throw new Problem(at(p, 'id'), `Two tabs have the id "${id.slice(0, 60)}".`);
573
+ ids.add(id);
574
+ str(at(p, 'label'), t.label, UI_LIMITS.label);
575
+ });
576
+ if (typeof o.active !== 'string' || !ids.has(o.active))
577
+ throw new Problem(at(path, 'active'), `${at(path, 'active')} must be the id of one of the tabs.`);
578
+ return;
579
+ }
580
+ case 'section':
581
+ keys(path, o, ['type', 'title', 'description', 'blocks'], what);
582
+ str(at(path, 'title'), o.title, UI_LIMITS.title, { optional: true });
583
+ str(at(path, 'description'), o.description, UI_LIMITS.description, { optional: true });
584
+ blocks(at(path, 'blocks'), o.blocks, depth + 1, w);
585
+ return;
586
+ case 'columns': {
587
+ keys(path, o, ['type', 'columns'], what);
588
+ list(at(path, 'columns'), o.columns, UI_LIMITS.columnsMax, 'columns', UI_LIMITS.columnsMin).forEach((c, i) => blocks(at(at(path, 'columns'), i), c, depth + 1, w));
589
+ return;
590
+ }
591
+ }
592
+ }
593
+ function view(path, v, w) {
594
+ const o = obj(path, v, 'a view: {"title"?, "description"?, "actions"?, "blocks", "refresh_seconds"?}');
595
+ keys(path, o, ['title', 'description', 'actions', 'blocks', 'refresh_seconds'], 'a view');
596
+ str(at(path, 'title'), o.title, UI_LIMITS.title, { optional: true });
597
+ str(at(path, 'description'), o.description, UI_LIMITS.description, { optional: true });
598
+ if (o.actions !== undefined)
599
+ buttons(at(path, 'actions'), o.actions, UI_LIMITS.viewActions, w);
600
+ blocks(at(path, 'blocks'), o.blocks, 1, w);
601
+ const r = o.refresh_seconds;
602
+ if (r !== undefined && (typeof r !== 'number' || !Number.isInteger(r) || r < UI_LIMITS.refreshMin || r > UI_LIMITS.refreshMax)) {
603
+ throw new Problem(at(path, 'refresh_seconds'), `${at(path, 'refresh_seconds')} must be a whole number of seconds from ${UI_LIMITS.refreshMin} to ${UI_LIMITS.refreshMax}.`);
604
+ }
605
+ return o;
606
+ }
607
+ function run(fn) {
608
+ try {
609
+ return { ok: true, value: fn() };
610
+ }
611
+ catch (err) {
612
+ if (err instanceof Problem)
613
+ return { ok: false, problem: { path: err.path, message: err.message } };
614
+ throw err;
615
+ }
616
+ }
617
+ /** A render answer: `{ "view": { … } }`. */
618
+ export function checkRenderAnswer(input, options = {}) {
619
+ return run(() => {
620
+ const o = obj('', input, 'like {"view": {"blocks": […]}}');
621
+ keys('', o, ['view'], 'a page');
622
+ if (o.view === undefined)
623
+ throw new Problem('view', 'The answer has no "view". Answer {"view": {"blocks": […]}}.');
624
+ return view('view', o.view, { nodes: 0, pages: options.pages });
625
+ });
626
+ }
627
+ /** A view on its own (the kit checks what a page handler returns). */
628
+ export function checkView(input, options = {}) {
629
+ return run(() => view('', input, { nodes: 0, pages: options.pages }));
630
+ }
631
+ /** An action's answer: any of view, toast, errors, go; `{}` shows the page again. */
632
+ export function checkActionAnswer(input, options = {}) {
633
+ return run(() => {
634
+ const w = { nodes: 0, pages: options.pages };
635
+ const o = obj('', input, 'like {"toast": "Saved."} or {"errors": {"email": "…"}}');
636
+ keys('', o, ['view', 'toast', 'errors', 'go'], 'an action result');
637
+ if (o.view !== undefined)
638
+ view('view', o.view, w);
639
+ str('toast', o.toast, UI_LIMITS.toast, { optional: true });
640
+ if (o.errors !== undefined) {
641
+ const errors = obj('errors', o.errors, 'messages by field key, like {"email": "Enter an email address."}');
642
+ const entries = Object.entries(errors);
643
+ if (entries.length > UI_LIMITS.fields)
644
+ throw new Problem('errors', `errors has ${entries.length} messages; at most ${UI_LIMITS.fields}.`);
645
+ for (const [k, m] of entries) {
646
+ if (!FIELD_KEY.test(k) || isReservedName(k))
647
+ throw new Problem(at('errors', k), `"${k}" isn't a field key.`);
648
+ str(at('errors', k), m, UI_LIMITS.short);
649
+ }
650
+ }
651
+ if (o.go !== undefined) {
652
+ const g = obj('go', o.go, '{"page", "params"?}');
653
+ keys('go', g, ['page', 'params'], 'where to go');
654
+ page('go.page', g.page, w);
655
+ if (g.params !== undefined)
656
+ checkParams('go.params', g.params);
657
+ }
658
+ if (o.view !== undefined && o.go !== undefined)
659
+ throw new Problem('go', 'Answer either "view" (show this now) or "go" (open another page), not both.');
660
+ return o;
661
+ });
662
+ }
663
+ /** The params usebecky sends (from the dashboard's address): a check usebecky makes before asking the extension. */
664
+ export function checkRequestParams(input) {
665
+ return run(() => checkParams('params', input));
666
+ }