@vestra-player/sdk 1.7.2 → 1.7.4

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,974 @@
1
+ /**
2
+ * The types of the properties a plugin's Slint files declare, and the
3
+ * player's check of a value written to one (`ui_values::set`: Slint's
4
+ * `check_and_coerce`, the refusal in words of `ui_values::refusal`).
5
+ *
6
+ * The player sets each value on the compiled component, and Slint refuses
7
+ * one of another type: a string where the declaration has a brush, a row
8
+ * whose struct has a field the declared struct does not. Without this the
9
+ * test host kept every value as plain JSON and such a plugin passed its
10
+ * tests, then failed in the player when its window opened.
11
+ *
12
+ * A small parser of declarations only: `import`, `export`, `struct`,
13
+ * `enum`, and the `property` declarations directly in a `component` or
14
+ * `global` body; everything else is skipped. What it cannot resolve (a
15
+ * type of `std-widgets.slint`, a file it cannot read) is taken as any
16
+ * value, so a check here never refuses what the player takes. Each file
17
+ * is parsed once while it is unchanged.
18
+ *
19
+ * Part of `TestHost` (`./index.ts`). Internal to the SDK; not exported
20
+ * from `@vestra-player/sdk/testing`.
21
+ */
22
+ import { readFileSync, statSync } from "node:fs";
23
+ import { dirname, resolve } from "node:path";
24
+ import { fileURLToPath } from "node:url";
25
+ /** The package directory of the plugin a host runs (set by `startPlugin`). */
26
+ export const packageDirectories = new WeakMap();
27
+ /** The SDK's Slint library (`@vestra/…`), as the player's `vestra` library path. */
28
+ const LIBRARY = fileURLToPath(new URL("../../../slint/vestra/", import.meta.url));
29
+ /**
30
+ * Slint's `normalize_identifier`: `_` is `-` except as the first
31
+ * character, where `-` is `_`.
32
+ */
33
+ export const normalize = (name) => name.replace(/^-/, "_").replace(/(?<!^)_/g, "-");
34
+ function tokenize(text) {
35
+ const out = [];
36
+ const n = text.length;
37
+ let i = 0;
38
+ // A string literal from its opening quote; `\{ … }` interpolations may
39
+ // hold braces and strings of their own.
40
+ const string = () => {
41
+ const start = ++i;
42
+ while (i < n) {
43
+ const c = text[i];
44
+ if (c === "\\") {
45
+ if (text[i + 1] === "{") {
46
+ i += 2;
47
+ let depth = 1;
48
+ while (i < n && depth > 0) {
49
+ if (text[i] === '"') {
50
+ string();
51
+ continue;
52
+ }
53
+ if (text[i] === "{")
54
+ depth++;
55
+ else if (text[i] === "}")
56
+ depth--;
57
+ i++;
58
+ }
59
+ continue;
60
+ }
61
+ i += 2;
62
+ continue;
63
+ }
64
+ if (c === '"')
65
+ return text.slice(start, i++);
66
+ i++;
67
+ }
68
+ return text.slice(start);
69
+ };
70
+ while (i < n) {
71
+ const c = text[i];
72
+ if (/\s/.test(c)) {
73
+ i++;
74
+ }
75
+ else if (c === "/" && text[i + 1] === "/") {
76
+ while (i < n && text[i] !== "\n")
77
+ i++;
78
+ }
79
+ else if (c === "/" && text[i + 1] === "*") {
80
+ let depth = 0;
81
+ while (i < n) {
82
+ if (text[i] === "/" && text[i + 1] === "*") {
83
+ depth++;
84
+ i += 2;
85
+ }
86
+ else if (text[i] === "*" && text[i + 1] === "/") {
87
+ depth--;
88
+ i += 2;
89
+ if (depth === 0)
90
+ break;
91
+ }
92
+ else
93
+ i++;
94
+ }
95
+ }
96
+ else if (c === '"') {
97
+ out.push({ t: "str", v: string() });
98
+ }
99
+ else if (/[A-Za-z_]/.test(c)) {
100
+ const start = i;
101
+ while (i < n && /[A-Za-z0-9_-]/.test(text[i]))
102
+ i++;
103
+ out.push({ t: "id", v: text.slice(start, i) });
104
+ }
105
+ else if (/[0-9]/.test(c)) {
106
+ const start = i;
107
+ while (i < n && /[A-Za-z0-9_.%]/.test(text[i]))
108
+ i++;
109
+ out.push({ t: "num", v: text.slice(start, i) });
110
+ }
111
+ else if (text.startsWith("<=>", i)) {
112
+ out.push({ t: "p", v: "<=>" });
113
+ i += 3;
114
+ }
115
+ else if (text.startsWith(":=", i)) {
116
+ out.push({ t: "p", v: ":=" });
117
+ i += 2;
118
+ }
119
+ else {
120
+ out.push({ t: "p", v: c });
121
+ i++;
122
+ }
123
+ }
124
+ return out;
125
+ }
126
+ // ----------------------------------------------------------------- parser
127
+ const OPEN = new Set(["{", "[", "("]);
128
+ const CLOSE = new Set(["}", "]", ")"]);
129
+ const VISIBILITY = {
130
+ in: "in",
131
+ out: "out",
132
+ "in-out": "in-out",
133
+ in_out: "in-out",
134
+ private: "private",
135
+ };
136
+ /** The import path as the player's compiler resolves it. */
137
+ function importPath(from, spec) {
138
+ if (spec.startsWith("@vestra/"))
139
+ return resolve(LIBRARY, spec.slice(8));
140
+ if (spec.startsWith("@") || spec === "std-widgets.slint")
141
+ return null;
142
+ if (!spec.endsWith(".slint"))
143
+ return null;
144
+ return resolve(dirname(from), spec);
145
+ }
146
+ function parse(path, text) {
147
+ const file = {
148
+ path,
149
+ structs: new Map(),
150
+ enums: new Set(),
151
+ elements: new Map(),
152
+ imports: new Map(),
153
+ exports: new Map(),
154
+ stars: [],
155
+ };
156
+ const tokens = tokenize(text);
157
+ let p = 0;
158
+ const at = (offset = 0) => tokens[p + offset];
159
+ const is = (v, offset = 0) => at(offset)?.v === v;
160
+ const fail = () => {
161
+ throw new Error("unexpected");
162
+ };
163
+ const expect = (v) => {
164
+ if (!is(v))
165
+ fail();
166
+ p++;
167
+ };
168
+ const identifier = () => {
169
+ const token = at();
170
+ if (token?.t !== "id")
171
+ fail();
172
+ p++;
173
+ return token.v;
174
+ };
175
+ /** Past the bracket that closes the one at `p`. */
176
+ const skipBlock = () => {
177
+ let depth = 0;
178
+ do {
179
+ const v = at()?.v;
180
+ if (v === undefined)
181
+ return;
182
+ if (OPEN.has(v))
183
+ depth++;
184
+ else if (CLOSE.has(v))
185
+ depth--;
186
+ p++;
187
+ } while (depth > 0);
188
+ };
189
+ const type = () => {
190
+ if (is("[")) {
191
+ p++;
192
+ const inner = type();
193
+ expect("]");
194
+ return { array: inner };
195
+ }
196
+ if (is("{")) {
197
+ p++;
198
+ const fields = [];
199
+ while (!is("}")) {
200
+ const name = identifier();
201
+ expect(":");
202
+ fields.push([normalize(name), type()]);
203
+ if (is(","))
204
+ p++;
205
+ else if (!is("}"))
206
+ fail();
207
+ }
208
+ p++;
209
+ return { fields };
210
+ }
211
+ return { name: normalize(identifier()) };
212
+ };
213
+ /** `{ a, b as c }` of an import or export: [name, local name]. */
214
+ const names = () => {
215
+ const list = [];
216
+ expect("{");
217
+ while (!is("}")) {
218
+ const name = identifier();
219
+ let alias = name;
220
+ if (is("as")) {
221
+ p++;
222
+ alias = identifier();
223
+ }
224
+ list.push([normalize(name), normalize(alias)]);
225
+ if (is(","))
226
+ p++;
227
+ else if (!is("}"))
228
+ fail();
229
+ }
230
+ p++;
231
+ return list;
232
+ };
233
+ const body = (kind, base) => {
234
+ const element = { kind, base, members: new Map() };
235
+ expect("{");
236
+ let depth = 0;
237
+ while (at() !== undefined) {
238
+ const v = at().v;
239
+ // A declaration directly in the body, wherever it stands (after a
240
+ // `states [...]`, `transitions [...]` or `@children` too): `property`
241
+ // (after its visibility) followed by `<` or by a name and `<=>`.
242
+ if (depth === 0 && at().t === "id") {
243
+ let visibility = "private";
244
+ let offset = 0;
245
+ if (VISIBILITY[v] && is("property", 1)) {
246
+ visibility = VISIBILITY[v];
247
+ offset = 1;
248
+ }
249
+ if (is("property", offset) &&
250
+ (is("<", offset + 1) ||
251
+ (at(offset + 1)?.t === "id" && is("<=>", offset + 2)))) {
252
+ p += offset + 1;
253
+ let declared = null;
254
+ if (is("<")) {
255
+ p++;
256
+ declared = type();
257
+ expect(">");
258
+ }
259
+ const name = normalize(identifier());
260
+ const rows = is(":") && is("[", 1) && !is("]", 2);
261
+ const initial = is(":") ? literal() : is("<=>") ? undefined : null;
262
+ element.members.set(name, {
263
+ visibility,
264
+ type: declared,
265
+ rows,
266
+ initial,
267
+ });
268
+ continue;
269
+ }
270
+ }
271
+ if (OPEN.has(v))
272
+ depth++;
273
+ else if (CLOSE.has(v)) {
274
+ if (depth === 0) {
275
+ p++;
276
+ break;
277
+ }
278
+ depth--;
279
+ }
280
+ p++;
281
+ }
282
+ return element;
283
+ };
284
+ /** The literal after `:` that ends the binding (`;`), or `undefined`. */
285
+ const literal = () => {
286
+ // A negative number is `-` and the number.
287
+ const negative = is("-", 1) ? 1 : 0;
288
+ const value = at(1 + negative);
289
+ let end = 2 + negative;
290
+ let result;
291
+ // A plain number, or logical pixels and milliseconds (the units the
292
+ // player's value holds as written).
293
+ const number = value?.t === "num" && /^(\d+(?:\.\d+)?)(px|ms)?$/.exec(value.v);
294
+ if (number)
295
+ result = (negative ? -1 : 1) * Number(number[1]);
296
+ else if (negative)
297
+ result = undefined;
298
+ else if (value?.t === "str" && !value.v.includes("\\"))
299
+ result = value.v;
300
+ else if (value?.v === "true" || value?.v === "false")
301
+ result = value.v === "true";
302
+ else if (value?.v === "[" && is("]", 2)) {
303
+ result = [];
304
+ end = 3;
305
+ }
306
+ return result !== undefined && is(";", end) ? result : undefined;
307
+ };
308
+ const declaration = (exported) => {
309
+ const keyword = at().v;
310
+ p++;
311
+ const name = normalize(identifier());
312
+ if (exported)
313
+ file.exports.set(name, { name });
314
+ if (keyword === "struct") {
315
+ if (is(":="))
316
+ p++;
317
+ const shape = type();
318
+ if (!("fields" in shape))
319
+ fail();
320
+ file.structs.set(name, shape.fields);
321
+ }
322
+ else if (keyword === "enum") {
323
+ file.enums.add(name);
324
+ skipBlock();
325
+ }
326
+ else if (keyword === "global") {
327
+ if (is(":="))
328
+ p++;
329
+ file.elements.set(name, body("global", null));
330
+ }
331
+ else {
332
+ let base = null;
333
+ if (is("inherits")) {
334
+ p++;
335
+ base = normalize(identifier());
336
+ }
337
+ file.elements.set(name, body("component", base));
338
+ }
339
+ };
340
+ const DECLARATIONS = new Set(["struct", "enum", "global", "component"]);
341
+ while (p < tokens.length) {
342
+ const start = p;
343
+ try {
344
+ if (is("import") && is("{", 1)) {
345
+ p++;
346
+ const list = names();
347
+ expect("from");
348
+ const spec = at();
349
+ if (spec?.t !== "str")
350
+ fail();
351
+ p++;
352
+ const from = importPath(path, spec.v);
353
+ for (const [name, local] of list)
354
+ file.imports.set(local, { from, name });
355
+ }
356
+ else if (is("export") && is("{", 1)) {
357
+ p++;
358
+ const list = names();
359
+ let from;
360
+ if (is("from")) {
361
+ p++;
362
+ const spec = at();
363
+ if (spec?.t !== "str")
364
+ fail();
365
+ p++;
366
+ from = importPath(path, spec.v);
367
+ }
368
+ for (const [name, alias] of list)
369
+ file.exports.set(alias, from === undefined ? { name } : { name, from });
370
+ }
371
+ else if (is("export") && is("*", 1) && is("from", 2)) {
372
+ p += 3;
373
+ const spec = at();
374
+ if (spec?.t !== "str")
375
+ fail();
376
+ p++;
377
+ file.stars.push(importPath(path, spec.v));
378
+ }
379
+ else if (is("export") && DECLARATIONS.has(at(1)?.v ?? "")) {
380
+ p++;
381
+ declaration(true);
382
+ }
383
+ else if (DECLARATIONS.has(at().v) && at(1)?.t === "id") {
384
+ declaration(false);
385
+ }
386
+ else if (OPEN.has(at().v)) {
387
+ skipBlock();
388
+ }
389
+ else {
390
+ p++;
391
+ }
392
+ }
393
+ catch {
394
+ // Not a declaration this parser reads: go on after its first token.
395
+ p = start + 1;
396
+ }
397
+ }
398
+ return file;
399
+ }
400
+ // ------------------------------------------------------------- resolution
401
+ const files = new Map();
402
+ /** The files read while a view's types are resolved (`viewTypes`). */
403
+ let reading = null;
404
+ const mtimeOf = (path) => {
405
+ try {
406
+ return statSync(path).mtimeMs;
407
+ }
408
+ catch {
409
+ return -1;
410
+ }
411
+ };
412
+ /** A file, parsed once while it is unchanged; `null` if it cannot be read. */
413
+ function load(path) {
414
+ if (!path)
415
+ return null;
416
+ reading?.add(path);
417
+ const mtime = mtimeOf(path);
418
+ if (mtime < 0)
419
+ return null;
420
+ const cached = files.get(path);
421
+ if (cached && cached.mtime === mtime)
422
+ return cached.file;
423
+ let file = null;
424
+ try {
425
+ file = parse(path, readFileSync(path, "utf8"));
426
+ }
427
+ catch {
428
+ file = null;
429
+ }
430
+ files.set(path, { mtime, file });
431
+ return file;
432
+ }
433
+ /**
434
+ * What `name` exported from `file` is. `seen`: the (file, name) pairs
435
+ * already asked on this lookup, so that files exporting each other
436
+ * (`export * from`) end it.
437
+ */
438
+ function exportOf(file, name, seen = new Set()) {
439
+ if (!file)
440
+ return null;
441
+ const key = `${file.path}\u0000${name}`;
442
+ if (seen.has(key))
443
+ return null;
444
+ seen.add(key);
445
+ const entry = file.exports.get(name);
446
+ if (entry)
447
+ return entry.from === undefined
448
+ ? local(file, entry.name, seen)
449
+ : exportOf(load(entry.from), entry.name, seen);
450
+ for (const star of file.stars) {
451
+ const found = exportOf(load(star), name, seen);
452
+ if (found)
453
+ return found;
454
+ }
455
+ return null;
456
+ }
457
+ /** What `name` is in the scope of `file`: declared there or imported. */
458
+ function local(file, name, seen = new Set()) {
459
+ const struct = file.structs.get(name);
460
+ if (struct)
461
+ return { struct, name, file };
462
+ if (file.enums.has(name))
463
+ return { enum: true };
464
+ const element = file.elements.get(name);
465
+ if (element)
466
+ return { element, file };
467
+ const imported = file.imports.get(name);
468
+ if (imported)
469
+ return exportOf(load(imported.from), imported.name, seen);
470
+ return null;
471
+ }
472
+ const BUILTIN = {
473
+ int: "number",
474
+ float: "number",
475
+ length: "number",
476
+ "physical-length": "number",
477
+ "relative-font-size": "number",
478
+ duration: "number",
479
+ angle: "number",
480
+ percent: "number",
481
+ string: "string",
482
+ bool: "bool",
483
+ image: "image",
484
+ color: "brush",
485
+ brush: "brush",
486
+ easing: "other",
487
+ };
488
+ /**
489
+ * Each named struct resolved once per view read (`viewTypes`), by file
490
+ * and name. A struct that holds itself (Slint refuses it; the test host
491
+ * must not loop or expand it without end) is `any` where it recurs.
492
+ */
493
+ let structs = new Map();
494
+ function resolveType(file, expr) {
495
+ if ("array" in expr)
496
+ return { k: "array", of: resolveType(file, expr.array) };
497
+ if ("fields" in expr)
498
+ return structType(file, expr.fields);
499
+ const builtin = BUILTIN[expr.name];
500
+ if (builtin)
501
+ return { k: builtin };
502
+ const found = local(file, expr.name);
503
+ if (found && "struct" in found) {
504
+ const key = `${found.file.path}\u0000${found.name}`;
505
+ const known = structs.get(key);
506
+ // `null`: being resolved, so this is a cycle.
507
+ if (known === null)
508
+ return { k: "any" };
509
+ if (known)
510
+ return known;
511
+ structs.set(key, null);
512
+ const type = structType(found.file, found.struct);
513
+ structs.set(key, type);
514
+ return type;
515
+ }
516
+ if (found && "enum" in found)
517
+ return { k: "enum" };
518
+ return { k: "any" };
519
+ }
520
+ function structType(file, fields) {
521
+ return {
522
+ k: "struct",
523
+ fields: new Map(fields.map(([name, type]) => [name, resolveType(file, type)])),
524
+ };
525
+ }
526
+ /** A view's types, and the files they were read from with their times. */
527
+ const views = new Map();
528
+ /**
529
+ * The properties of the view `file` (relative to `directory`) shows: its
530
+ * one exported component (a window), or the exported `global` (a panel or
531
+ * settings page). `null` when the file cannot be read or the view cannot
532
+ * be found: then nothing is checked. Kept while none of the files it was
533
+ * read from (the view's and those it imports) changed.
534
+ */
535
+ export function viewTypes(directory, file, global) {
536
+ const path = resolve(directory, file);
537
+ const key = `${path}\u0000${global ?? ""}`;
538
+ const cached = views.get(key);
539
+ if (cached &&
540
+ [...cached.files].every(([each, mtime]) => mtimeOf(each) === mtime))
541
+ return cached.view;
542
+ reading = new Set();
543
+ structs = new Map();
544
+ let view = null;
545
+ try {
546
+ view = readView(path, global);
547
+ }
548
+ finally {
549
+ const read = reading;
550
+ reading = null;
551
+ structs = new Map();
552
+ views.set(key, {
553
+ files: new Map([...read].map((each) => [each, mtimeOf(each)])),
554
+ view,
555
+ });
556
+ }
557
+ return view;
558
+ }
559
+ function readView(path, global) {
560
+ const parsed = load(path);
561
+ if (!parsed)
562
+ return null;
563
+ let found = null;
564
+ if (global !== undefined) {
565
+ found = exportOf(parsed, normalize(global));
566
+ if (!found || !("element" in found) || found.element.kind !== "global")
567
+ found = null;
568
+ }
569
+ else {
570
+ const components = [...parsed.exports.keys()]
571
+ .map((name) => exportOf(parsed, name))
572
+ .filter((each) => each !== null &&
573
+ "element" in each &&
574
+ each.element.kind === "component");
575
+ found = components.length === 1 ? components[0] : null;
576
+ }
577
+ if (!found || !("element" in found))
578
+ return null;
579
+ const { element, file: owner } = found;
580
+ const properties = new Map();
581
+ for (const [name, member] of element.members) {
582
+ const type = member.type ? resolveType(owner, member.type) : anyType;
583
+ properties.set(name, {
584
+ visibility: member.visibility,
585
+ type,
586
+ rows: member.rows,
587
+ // Only an `out` property's value is ever compared (`refusal`).
588
+ initial: member.visibility !== "out"
589
+ ? undefined
590
+ : member.initial === null
591
+ ? jsonDefault(type)
592
+ : member.initial,
593
+ });
594
+ }
595
+ // A component of the plugin's own as the base, or one it imports (from
596
+ // std-widgets.slint too): its properties are not read here.
597
+ const base = element.base;
598
+ const open = base !== null && (owner.elements.has(base) || owner.imports.has(base));
599
+ return { properties, open };
600
+ }
601
+ const anyType = { k: "any" };
602
+ /**
603
+ * A type's default as the player's `to_json` writes it (`0`, `""`,
604
+ * `false`, `[]`, a struct of those); `undefined` where it has none (an
605
+ * image, a brush, an enum, a type not known here). Each struct type once:
606
+ * a struct used in many places shares one default.
607
+ */
608
+ const jsonDefaults = new WeakMap();
609
+ function jsonDefault(type) {
610
+ if (type.k !== "struct")
611
+ return leafDefault(type);
612
+ if (jsonDefaults.has(type))
613
+ return jsonDefaults.get(type);
614
+ const out = {};
615
+ let known = true;
616
+ for (const [name, field] of type.fields) {
617
+ const value = jsonDefault(field);
618
+ if (value === undefined) {
619
+ known = false;
620
+ break;
621
+ }
622
+ out[name] = value;
623
+ }
624
+ const result = known ? out : undefined;
625
+ jsonDefaults.set(type, result);
626
+ return result;
627
+ }
628
+ function leafDefault(type) {
629
+ switch (type.k) {
630
+ case "number":
631
+ return 0;
632
+ case "string":
633
+ return "";
634
+ case "bool":
635
+ return false;
636
+ case "array":
637
+ return [];
638
+ default:
639
+ return undefined;
640
+ }
641
+ }
642
+ // ------------------------------------------------------------------ check
643
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
644
+ /** The player's image reference (`ui_image::reference`). */
645
+ const isImage = (value) => isObject(value) &&
646
+ "$vestraImage" in value &&
647
+ Object.keys(value).every((key) => key === "$vestraImage" || key === "ref" || key === "maxSide");
648
+ /** A Markdown document (`ui_markdown::reference`): rows of blocks. */
649
+ const isDocument = (value) => isObject(value) &&
650
+ "$vestraMarkdown" in value &&
651
+ Object.keys(value).every((key) => key === "$vestraMarkdown" || key === "ref");
652
+ /** A field holding styled text (a Markdown row's `text`): no JSON value is one. */
653
+ const STYLED = Object.freeze({});
654
+ const isStruct = (value) => value !== STYLED && isObject(value) && !isImage(value) && !isDocument(value);
655
+ /**
656
+ * One row of a converted Markdown document, as the player builds it
657
+ * (`ui_markdown::row_value`, a `MarkdownBlock`): every block has these
658
+ * fields, its lists empty or not.
659
+ */
660
+ const MARKDOWN_ROW = {
661
+ kind: "",
662
+ level: 0,
663
+ indent: 0,
664
+ quote: 0,
665
+ marker: "",
666
+ task: 0,
667
+ aligns: [],
668
+ text: STYLED,
669
+ plain: "",
670
+ links: [],
671
+ code: "",
672
+ alt: "",
673
+ "has-image": false,
674
+ image: { $vestraImage: "" },
675
+ "image-width": 0,
676
+ "image-height": 0,
677
+ rows: [],
678
+ };
679
+ /**
680
+ * The rows a Markdown document converts to, as far as the type check sees
681
+ * them: blocks of the shape above, none for an empty text.
682
+ */
683
+ function documentRows(value) {
684
+ const doc = value
685
+ .$vestraMarkdown;
686
+ const text = typeof doc?.text === "string" ? doc.text : "";
687
+ return text.trim() === "" ? [] : [MARKDOWN_ROW];
688
+ }
689
+ /** A Markdown document anywhere in `value`. */
690
+ const hasDocument = (value) => isDocument(value) ||
691
+ (Array.isArray(value)
692
+ ? value.some(hasDocument)
693
+ : isObject(value) &&
694
+ !isImage(value) &&
695
+ Object.values(value).some(hasDocument));
696
+ /**
697
+ * The player converts an array without documents to plain rows
698
+ * (`ui_values::plain_rows`), where `null` is an empty image
699
+ * (`ui_rows::Plain::to_value`); anywhere else `null` stays null, which
700
+ * no declared type takes.
701
+ */
702
+ const plainRows = (value) => Array.isArray(value) && !hasDocument(value);
703
+ /**
704
+ * The kind of the Slint value the player converts `value` to (`kind`);
705
+ * `plain`: inside plain rows.
706
+ */
707
+ function kind(value, plain = false) {
708
+ if (value === STYLED)
709
+ return "a value";
710
+ if (value === null)
711
+ return plain ? "an image" : "null";
712
+ if (typeof value === "boolean")
713
+ return "a bool";
714
+ if (typeof value === "number")
715
+ return "a number";
716
+ if (typeof value === "string")
717
+ return "a string";
718
+ if (Array.isArray(value) || isDocument(value))
719
+ return "an array";
720
+ if (isImage(value))
721
+ return "an image";
722
+ return "a struct";
723
+ }
724
+ /** Slint's `check_and_coerce`: whether `type` takes `value` (`plain`: inside plain rows). */
725
+ function takes(type, value, plain) {
726
+ switch (type.k) {
727
+ case "any":
728
+ return true;
729
+ case "number":
730
+ return typeof value === "number";
731
+ case "string":
732
+ return typeof value === "string";
733
+ case "bool":
734
+ return typeof value === "boolean";
735
+ case "image":
736
+ return isImage(value) || (plain && value === null);
737
+ case "array":
738
+ // A document's rows are checked like any other (`MarkdownBlock`
739
+ // structs).
740
+ if (isDocument(value))
741
+ return documentRows(value).every((row) => takes(type.of, row, false));
742
+ return (Array.isArray(value) && value.every((row) => takes(type.of, row, plain)));
743
+ case "struct":
744
+ return (isStruct(value) &&
745
+ Object.entries(value).every(([name, field]) => {
746
+ const declared = type.fields.get(normalize(name));
747
+ return declared !== undefined && takes(declared, field, plain);
748
+ }));
749
+ // Brushes, colors, enumerations and easings: no JSON value is one.
750
+ default:
751
+ return false;
752
+ }
753
+ }
754
+ const LEAF = {
755
+ number: "a number",
756
+ string: "a string",
757
+ bool: "a bool",
758
+ image: "an image",
759
+ brush: "a brush",
760
+ enum: "an enum value",
761
+ other: "a value",
762
+ any: "?",
763
+ };
764
+ /** Slint's default value of `type` (`default_value_for_type`). */
765
+ function defaultOf(type, rows = false) {
766
+ if (type.k === "struct") {
767
+ const fields = type.fields;
768
+ return {
769
+ k: "struct",
770
+ names: () => [...fields.keys()],
771
+ field: (name) => {
772
+ const field = fields.get(name);
773
+ return field && defaultOf(field);
774
+ },
775
+ };
776
+ }
777
+ // An array literal with rows: its rows have the declared struct's fields.
778
+ if (type.k === "array")
779
+ return { k: "array", first: rows ? defaultOf(type.of) : null };
780
+ return { k: "leaf", kind: LEAF[type.k] };
781
+ }
782
+ /**
783
+ * The value a property holds after `value` was set: a struct gets the
784
+ * declared fields it left out (`check_and_coerce` fills them, `fill`), the
785
+ * rows of an array stay as written.
786
+ */
787
+ function heldOf(type, value, fill, plain) {
788
+ if (Array.isArray(value) || isDocument(value)) {
789
+ const document = isDocument(value);
790
+ const rows = document ? documentRows(value) : value;
791
+ const of = type.k === "array" ? type.of : { k: "any" };
792
+ return {
793
+ k: "array",
794
+ first: rows.length
795
+ ? heldOf(of, rows[0], false, plain && !document)
796
+ : null,
797
+ };
798
+ }
799
+ if (isStruct(value)) {
800
+ const declared = type.k === "struct" ? type.fields : undefined;
801
+ const fields = new Map();
802
+ for (const [name, field] of Object.entries(value)) {
803
+ const key = normalize(name);
804
+ fields.set(key, heldOf(declared?.get(key) ?? { k: "any" }, field, fill, plain));
805
+ }
806
+ // Filled: the declared fields it left out hold their defaults.
807
+ const filled = fill && declared ? declared : undefined;
808
+ return {
809
+ k: "struct",
810
+ names: () => [...new Set([...fields.keys(), ...(filled?.keys() ?? [])])],
811
+ field: (name) => {
812
+ const given = fields.get(name);
813
+ if (given)
814
+ return given;
815
+ const field = filled?.get(name);
816
+ return field && defaultOf(field);
817
+ },
818
+ };
819
+ }
820
+ return { k: "leaf", kind: kind(value, plain) };
821
+ }
822
+ const heldKind = (held) => held.k === "struct"
823
+ ? "a struct"
824
+ : held.k === "array"
825
+ ? "an array"
826
+ : held.kind;
827
+ /** `ui_values::mismatch`: the first place `next` differs from `current`. */
828
+ function mismatch(path, current, next, plain) {
829
+ if (current.k === "struct" && isStruct(next)) {
830
+ const fields = Object.keys(next)
831
+ .map((name) => [normalize(name), next[name]])
832
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
833
+ for (const [name, value] of fields) {
834
+ const field = `${path}.${name}`;
835
+ const declared = current.field(name);
836
+ if (!declared)
837
+ return `${field} is not a field of the declared struct (${current
838
+ .names()
839
+ .sort()
840
+ .join(", ")})`;
841
+ const found = mismatch(field, declared, value, plain);
842
+ if (found)
843
+ return found;
844
+ }
845
+ return null;
846
+ }
847
+ if (current.k === "array" && (Array.isArray(next) || isDocument(next))) {
848
+ if (!current.first)
849
+ return null;
850
+ const document = isDocument(next);
851
+ const rows = document ? documentRows(next) : next;
852
+ for (const [index, row] of rows.entries()) {
853
+ const found = mismatch(`${path}[${index}]`, current.first, row, plain && !document);
854
+ if (found)
855
+ return found;
856
+ }
857
+ return null;
858
+ }
859
+ const declared = heldKind(current);
860
+ const given = kind(next, plain);
861
+ if (declared === "?" || declared === given)
862
+ return null;
863
+ return `${path} is ${given} where the declaration has ${declared}`;
864
+ }
865
+ /**
866
+ * The player's refusal of `value` for `property` of a view of `types`, or
867
+ * `null` when it takes it. `current`: what the property holds (the last
868
+ * value it took; none: its default), which the words of a type refusal
869
+ * describe the declaration by, as the player's do.
870
+ */
871
+ export function refusal(types, property, value, current, options = {}) {
872
+ const declared = types.properties.get(normalize(property));
873
+ if (!declared || declared.visibility === "private") {
874
+ if (types.open && !declared)
875
+ return null;
876
+ return { why: "missing", message: `${property}: no such property` };
877
+ }
878
+ // A write that compares first (`ui_values::reconcile_in`: `ui.set`, a
879
+ // panel, a settings page; not `ui.open`) does nothing when the value is
880
+ // what the property holds, for an `out` one too.
881
+ if (declared.visibility === "out" &&
882
+ options.reconciles &&
883
+ declared.initial !== undefined &&
884
+ sameJson(declared.initial, value))
885
+ return null;
886
+ if (declared.visibility === "out")
887
+ return {
888
+ why: "readonly",
889
+ message: `${property}: not writable (an out property)`,
890
+ };
891
+ const plain = plainRows(value);
892
+ if (takes(declared.type, value, plain))
893
+ return null;
894
+ const held = current === undefined
895
+ ? defaultOf(declared.type, declared.rows)
896
+ : heldOf(declared.type, current, true, plainRows(current));
897
+ const detail = mismatch(property, held, value, plain) ??
898
+ `${property} is ${kind(value)} that does not match the declared ${heldKind(held)} type`;
899
+ return { why: "type", message: `${property}: wrong type: ${detail}` };
900
+ }
901
+ /**
902
+ * Two values the player's `to_json` writes alike (numbers by value);
903
+ * `null` in an array is an image there, which has no JSON: never alike.
904
+ */
905
+ function sameJson(a, b, inArray = false) {
906
+ if (a === null || b === null)
907
+ return a === b && !inArray;
908
+ if (Array.isArray(a) || Array.isArray(b))
909
+ return (Array.isArray(a) &&
910
+ Array.isArray(b) &&
911
+ a.length === b.length &&
912
+ a.every((item, index) => sameJson(item, b[index], true)));
913
+ if (isObject(a) || isObject(b)) {
914
+ if (!isStruct(a) || !isStruct(b))
915
+ return false;
916
+ const keys = Object.keys(a);
917
+ return (keys.length === Object.keys(b).length &&
918
+ keys.every((key) => key in b && sameJson(a[key], b[key], inArray)));
919
+ }
920
+ return a === b;
921
+ }
922
+ /** Rust's `{:?}` of a string: quoted, with its escapes. */
923
+ function debugQuoted(text) {
924
+ let out = '"';
925
+ for (const char of text) {
926
+ const code = char.codePointAt(0);
927
+ if (char === '"' || char === "\\")
928
+ out += "\\" + char;
929
+ else if (char === "\n")
930
+ out += "\\n";
931
+ else if (char === "\r")
932
+ out += "\\r";
933
+ else if (char === "\t")
934
+ out += "\\t";
935
+ else if (code === 0)
936
+ out += "\\0";
937
+ else if (code < 0x20 || code === 0x7f)
938
+ out += `\\u{${code.toString(16)}}`;
939
+ else
940
+ out += char;
941
+ }
942
+ return out + '"';
943
+ }
944
+ const byName = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
945
+ /**
946
+ * The player's conversion refuses a struct field name not in Slint's
947
+ * canonical spelling (`ui_values`: no `-` first, no `_` after the first
948
+ * character), whatever the declaration says: the first such name in the
949
+ * order the player meets them (fields by name, a field's value before its
950
+ * name), in its words; `null` when there is none. Image references and
951
+ * Markdown documents are not structs.
952
+ */
953
+ export function spellingProblem(value) {
954
+ if (isDocument(value) || isImage(value))
955
+ return null;
956
+ if (Array.isArray(value)) {
957
+ for (const row of value) {
958
+ const found = spellingProblem(row);
959
+ if (found)
960
+ return found;
961
+ }
962
+ return null;
963
+ }
964
+ if (!isObject(value))
965
+ return null;
966
+ for (const name of Object.keys(value).sort(byName)) {
967
+ const found = spellingProblem(value[name]);
968
+ if (found)
969
+ return found;
970
+ if (name.startsWith("-") || name.slice(1).includes("_"))
971
+ return `UI object field ${debugQuoted(name)} is not in Slint canonical spelling`;
972
+ }
973
+ return null;
974
+ }