paseo-plugin-genui 0.1.6 → 0.1.8

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.
@@ -17,8 +17,8 @@ export type Token =
17
17
  | (Pos & { readonly t: "eof" });
18
18
 
19
19
  const PUNCTUATION = [
20
- "===", "!==",
21
- "==", "!=", "<=", ">=", "&&", "||", "??", "=>", "**",
20
+ "===", "!==", "...",
21
+ "?.", "==", "!=", "<=", ">=", "&&", "||", "??", "=>", "**",
22
22
  "(", ")", "[", "]", "{", "}", ",", ":", ".", "?", "<", ">", "+", "-", "*", "/", "%", "!", "=",
23
23
  ];
24
24
 
@@ -28,7 +28,7 @@ const CONTINUES_AFTER: Record<string, true> = {
28
28
  "==": true, "!=": true, "===": true, "!==": true,
29
29
  "<": true, "<=": true, ">": true, ">=": true,
30
30
  "&&": true, "||": true, "??": true, "?": true, ":": true,
31
- ".": true, "=": true, "=>": true,
31
+ ".": true, "?.": true, "=": true, "=>": true,
32
32
  };
33
33
 
34
34
  /** A line starting with one of these continues the previous line (none can start an expression). */
@@ -37,7 +37,7 @@ const CONTINUES_BEFORE: Record<string, true> = {
37
37
  "==": true, "!=": true, "===": true, "!==": true,
38
38
  "<": true, "<=": true, ">": true, ">=": true,
39
39
  "&&": true, "||": true, "??": true, "?": true, ":": true,
40
- ".": true, "=>": true,
40
+ ".": true, "?.": true, "=>": true,
41
41
  };
42
42
 
43
43
  const NUMBER = /\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d+)?/y;
@@ -8,13 +8,36 @@ const PRECEDENCE: Record<string, number> = {
8
8
  "||": 2,
9
9
  "&&": 3,
10
10
  "==": 4, "!=": 4, "===": 4, "!==": 4,
11
- "<": 5, "<=": 5, ">": 5, ">=": 5,
11
+ "<": 5, "<=": 5, ">": 5, ">=": 5, in: 5,
12
12
  "+": 6, "-": 6,
13
13
  "*": 7, "/": 7, "%": 7,
14
14
  };
15
15
 
16
16
  const KEYWORDS: Record<string, true | false | null> = { true: true, false: false, null: null };
17
17
 
18
+ /**
19
+ * `Math.round(x)` and `Object.entries(o)` are how models write the built-ins;
20
+ * they parse as the plain calls `round(x)` and `entries(o)`. `JSON.stringify`
21
+ * and `Date.now` keep their dotted names, which no written name can shadow.
22
+ */
23
+ const NAMESPACES: Record<string, string> = { Math: "", Object: "", JSON: "JSON.", Date: "Date." };
24
+
25
+ const BLOCK_WORDS: Record<string, true> = { return: true, const: true, let: true, var: true };
26
+
27
+ /** A parameter or `const` target: a name, or `{a, b: c}` / `[a, b]` destructuring with optional `= fallback`s. */
28
+ type Pattern =
29
+ | { readonly kind: "name"; readonly name: string; readonly pos: Pos }
30
+ | {
31
+ readonly kind: "object";
32
+ readonly props: readonly { readonly key: string; readonly target: Pattern; readonly fallback: Expr | null }[];
33
+ readonly pos: Pos;
34
+ }
35
+ | {
36
+ readonly kind: "array";
37
+ readonly items: readonly ({ readonly target: Pattern; readonly fallback: Expr | null } | null)[];
38
+ readonly pos: Pos;
39
+ };
40
+
18
41
  /** AST depth beyond this is rejected so later tree walks cannot overflow the stack. */
19
42
  const MAX_NESTING = 100;
20
43
 
@@ -76,6 +99,8 @@ interface ParserFields {
76
99
  i: number;
77
100
  tokens: readonly Token[];
78
101
  depth: number;
102
+ /** Counter for the names destructuring binds its intermediate values to. */
103
+ hidden: number;
79
104
  }
80
105
 
81
106
  const Parser = defineClass(
@@ -83,6 +108,7 @@ const Parser = defineClass(
83
108
  this.tokens = tokens;
84
109
  this.depth = depth;
85
110
  this.i = 0;
111
+ this.hidden = 0;
86
112
  },
87
113
  {
88
114
  peek(offset = 0): Token {
@@ -154,32 +180,142 @@ const Parser = defineClass(
154
180
  return expr;
155
181
  },
156
182
 
183
+ /** `x =>`, or a bracketed group followed by `=>`. */
157
184
  isArrowStart(): boolean {
158
185
  if (this.peek().t === "ident") return this.isPunct("=>", 1);
159
186
  if (!this.isPunct("(")) return false;
160
- let offset = 1;
161
- if (this.peek(offset).t === "ident") {
162
- offset++;
163
- while (this.isPunct(",", offset) && this.peek(offset + 1).t === "ident") offset += 2;
187
+ let depth = 0;
188
+ for (let offset = 0; ; offset++) {
189
+ const token = this.peek(offset);
190
+ if (token.t === "eof" || token.t === "sep") return false;
191
+ if (token.t !== "punct") continue;
192
+ if (token.value === "(" || token.value === "[" || token.value === "{") depth++;
193
+ if ((token.value === ")" || token.value === "]" || token.value === "}") && --depth === 0) {
194
+ return this.isPunct("=>", offset + 1);
195
+ }
164
196
  }
165
- return this.isPunct(")", offset) && this.isPunct("=>", offset + 1);
166
197
  },
167
198
 
168
199
  arrow(): Expr {
169
200
  const start = this.peek();
170
- const params: string[] = [];
201
+ const patterns: Pattern[] = [];
171
202
  if (this.eat("(")) {
172
203
  while (!this.eat(")")) {
173
- params.push(this.ident("a parameter name").value);
174
- this.eat(",");
204
+ patterns.push(this.pattern());
205
+ if (!this.eat(",")) {
206
+ this.close(")", start, "`,` or ");
207
+ break;
208
+ }
175
209
  }
176
210
  } else {
177
- params.push(this.ident("a parameter name").value);
211
+ patterns.push(this.pattern());
178
212
  }
179
- const keyword = params.find((name) => Object.hasOwn(KEYWORDS, name));
180
- if (keyword !== undefined) throw new ParseError(start, `\`${keyword}\` cannot be a parameter name`);
181
213
  this.i++; // `=>`, guaranteed by isArrowStart
182
- return { type: "arrow", params, body: this.expr(), pos: start };
214
+ let body = this.isBlockStart() ? this.block() : this.expr();
215
+ const params = patterns.map((pattern, index) => (pattern.kind === "name" ? pattern.name : `#p${index}`));
216
+ for (let index = patterns.length - 1; index >= 0; index--) {
217
+ if (patterns[index].kind !== "name") body = this.bind(patterns[index], { type: "ident", name: params[index], pos: start }, body);
218
+ }
219
+ return { type: "arrow", params, body, pos: start };
220
+ },
221
+
222
+ pattern(): Pattern {
223
+ const open = this.peek();
224
+ if (this.eat("{")) {
225
+ const props: { key: string; target: Pattern; fallback: Expr | null }[] = [];
226
+ while (!this.eat("}")) {
227
+ const key = this.peek();
228
+ if (key.t !== "ident" && key.t !== "str") {
229
+ throw new ParseError(key, `expected a property name to destructure, found ${describe(key)}`);
230
+ }
231
+ this.i++;
232
+ const target: Pattern = this.eat(":") ? this.pattern() : this.patternName(key);
233
+ props.push({ key: key.value, target, fallback: this.eat("=") ? this.expr() : null });
234
+ if (!this.eat(",")) {
235
+ this.close("}", open, "`,` or ");
236
+ break;
237
+ }
238
+ }
239
+ return { kind: "object", props, pos: open };
240
+ }
241
+ if (this.eat("[")) {
242
+ const items: ({ target: Pattern; fallback: Expr | null } | null)[] = [];
243
+ while (!this.eat("]")) {
244
+ if (this.eat(",")) {
245
+ items.push(null);
246
+ continue;
247
+ }
248
+ const target = this.pattern();
249
+ items.push({ target, fallback: this.eat("=") ? this.expr() : null });
250
+ if (!this.eat(",")) {
251
+ this.close("]", open, "`,` or ");
252
+ break;
253
+ }
254
+ }
255
+ return { kind: "array", items, pos: open };
256
+ }
257
+ return this.patternName(this.ident("a parameter name"));
258
+ },
259
+
260
+ patternName(token: Pos & { readonly value: string }): Pattern {
261
+ if (Object.hasOwn(KEYWORDS, token.value) || Object.hasOwn(BLOCK_WORDS, token.value)) {
262
+ throw new ParseError(token, `\`${token.value}\` cannot be a parameter name`);
263
+ }
264
+ return { kind: "name", name: token.value, pos: token };
265
+ },
266
+
267
+ /** `body` with `pattern`'s names bound from `source`; a missing value is null, or its fallback. */
268
+ bind(pattern: Pattern, source: Expr, body: Expr): Expr {
269
+ if (pattern.kind === "name") return { type: "let", name: pattern.name, value: source, body, pos: pattern.pos };
270
+ const holder = `#d${this.hidden++}`;
271
+ const from: Expr = { type: "ident", name: holder, pos: pattern.pos };
272
+ const parts =
273
+ pattern.kind === "object"
274
+ ? pattern.props.map((prop) => ({ ...prop, key: prop.key as string | number }))
275
+ : pattern.items.flatMap((item, index) => (item === null ? [] : [{ ...item, key: index as string | number }]));
276
+ let inner = body;
277
+ for (let index = parts.length - 1; index >= 0; index--) {
278
+ const { key, target, fallback } = parts[index];
279
+ let value: Expr = { type: "index", object: from, index: { type: "literal", value: key, pos: pattern.pos }, pos: pattern.pos };
280
+ if (fallback !== null) value = { type: "binary", op: "??", left: value, right: fallback, pos: pattern.pos };
281
+ inner = this.bind(target, value, inner);
282
+ }
283
+ return { type: "let", name: holder, value: source, body: inner, pos: pattern.pos };
284
+ },
285
+
286
+ isBlockStart(): boolean {
287
+ const next = this.peek(1);
288
+ // `if` is no block word, but a body starting with it is meant as one; block() explains what is allowed.
289
+ return this.isPunct("{") && next.t === "ident" && (Object.hasOwn(BLOCK_WORDS, next.value) || next.value === "if");
290
+ },
291
+
292
+ /** `{ const a = ...; return ... }`: declarations, then one return. */
293
+ block(): Expr {
294
+ const open = this.tokens[this.i++];
295
+ const decls: { pattern: Pattern; value: Expr }[] = [];
296
+ for (;;) {
297
+ while (this.peek().t === "sep") this.i++;
298
+ const word = this.peek();
299
+ if (word.t === "ident" && (word.value === "const" || word.value === "let" || word.value === "var")) {
300
+ this.i++;
301
+ const pattern = this.pattern();
302
+ if (!this.eat("=")) throw new ParseError(this.peek(), `expected \`=\` after the \`${word.value}\` name, found ${describe(this.peek())}`);
303
+ decls.push({ pattern, value: this.expr() });
304
+ continue;
305
+ }
306
+ if (word.t === "ident" && word.value === "return") {
307
+ this.i++;
308
+ let body = this.expr();
309
+ while (this.peek().t === "sep") this.i++;
310
+ this.close("}", open);
311
+ for (let index = decls.length - 1; index >= 0; index--) body = this.bind(decls[index].pattern, decls[index].value, body);
312
+ return body;
313
+ }
314
+ throw new ParseError(
315
+ word,
316
+ `a \`{ }\` function body holds \`const name = ...\` lines and one \`return ...\`; found ${describe(word)}. Use \`?:\` for conditions`,
317
+ );
318
+ }
183
319
  },
184
320
 
185
321
  conditional(): Expr {
@@ -198,13 +334,14 @@ const Parser = defineClass(
198
334
  let left = this.unary();
199
335
  for (;;) {
200
336
  const token = this.peek();
201
- if (token.t !== "punct") break;
202
- const precedence = PRECEDENCE[token.value];
203
- if (precedence === undefined || precedence < minPrecedence) break;
337
+ const op = token.t === "punct" || (token.t === "ident" && token.value === "in") ? token.value : null;
338
+ if (op === null || !Object.hasOwn(PRECEDENCE, op)) break;
339
+ const precedence = PRECEDENCE[op];
340
+ if (precedence < minPrecedence) break;
204
341
  this.nest(token);
205
342
  this.i++;
206
343
  const right = this.binary(precedence + 1);
207
- left = { type: "binary", op: token.value as BinaryOperator, left, right, pos: token };
344
+ left = { type: "binary", op: op as BinaryOperator, left, right, pos: token };
208
345
  }
209
346
  this.depth = saved;
210
347
  return left;
@@ -213,7 +350,7 @@ const Parser = defineClass(
213
350
  unary(): Expr {
214
351
  const saved = this.depth;
215
352
  const operators: Token[] = [];
216
- while (this.isPunct("!") || this.isPunct("-")) {
353
+ while (this.isPunct("!") || this.isPunct("-") || this.isTypeof()) {
217
354
  this.nest(this.peek());
218
355
  operators.push(this.tokens[this.i++]);
219
356
  }
@@ -228,29 +365,39 @@ const Parser = defineClass(
228
365
  }
229
366
  for (let k = operators.length - 1; k >= 0; k--) {
230
367
  const token = operators[k];
231
- expr = { type: "unary", op: token.t === "punct" && token.value === "!" ? "!" : "-", operand: expr, pos: token };
368
+ const op = token.t === "ident" ? "typeof" : token.t === "punct" && token.value === "!" ? "!" : "-";
369
+ expr = { type: "unary", op, operand: expr, pos: token };
232
370
  }
233
371
  this.depth = saved;
234
372
  return expr;
235
373
  },
236
374
 
375
+ /** `typeof` followed by something that starts an expression. */
376
+ isTypeof(): boolean {
377
+ const token = this.peek();
378
+ if (token.t !== "ident" || token.value !== "typeof") return false;
379
+ const next = this.peek(1);
380
+ if (next.t === "punct") return ["(", "[", "{", "!", "-"].includes(next.value);
381
+ return next.t !== "sep" && next.t !== "eof";
382
+ },
383
+
237
384
  postfix(): Expr {
238
385
  let expr = this.primary();
386
+ // Reading a property of null gives null already; after a `?.`, so does calling a method on it.
387
+ let optional = false;
239
388
  for (;;) {
240
- if (this.isPunct(".") || this.isPunct("[") || this.isPunct("(")) this.nest(this.peek());
241
- if (this.eat(".")) {
242
- const name = this.ident("a property or method name after `.`");
243
- if (this.isPunct("(")) {
244
- // `Math.round(x)` and `Object.entries(o)` are how models write the
245
- // built-ins; they parse as the plain calls `round(x)` and `entries(o)`.
246
- expr =
247
- expr.type === "ident" && (expr.name === "Math" || expr.name === "Object")
248
- ? { type: "call", name: name.value, ...this.args(), pos: name }
249
- : { type: "method", object: expr, name: name.value, ...this.args(), pos: name };
250
- } else {
251
- expr = { type: "member", object: expr, name: name.value, pos: name };
389
+ if (this.isPunct(".") || this.isPunct("?.") || this.isPunct("[") || this.isPunct("(")) this.nest(this.peek());
390
+ if (this.eat("?.")) {
391
+ optional = true;
392
+ if (!this.isPunct("[")) {
393
+ expr = this.property(expr, optional);
394
+ continue;
252
395
  }
253
- } else if (this.isPunct("[")) {
396
+ } else if (this.eat(".")) {
397
+ expr = this.property(expr, optional);
398
+ continue;
399
+ }
400
+ if (this.isPunct("[")) {
254
401
  const open = this.tokens[this.i++];
255
402
  const index = this.expr();
256
403
  this.close("]", open);
@@ -266,6 +413,23 @@ const Parser = defineClass(
266
413
  }
267
414
  },
268
415
 
416
+ /** `.name` or `.name(...)` after `object`. */
417
+ property(object: Expr, optional: boolean): Expr {
418
+ const name = this.ident("a property or method name after `.`");
419
+ if (!this.isPunct("(")) return { type: "member", object, name: name.value, pos: name };
420
+ if (object.type === "ident" && Object.hasOwn(NAMESPACES, object.name)) {
421
+ return { type: "call", name: NAMESPACES[object.name] + name.value, ...this.args(), pos: name };
422
+ }
423
+ return { type: "method", object, name: name.value, ...this.args(), optional, pos: name };
424
+ },
425
+
426
+ /** An expression, or `...expr` where a list item or argument may spread. */
427
+ item(): Expr {
428
+ const token = this.peek();
429
+ if (!this.eat("...")) return this.expr();
430
+ return { type: "spread", value: this.expr(), pos: token };
431
+ },
432
+
269
433
  args(): { args: Expr[]; named: NamedArg[] } {
270
434
  const open = this.tokens[this.i++];
271
435
  const args: Expr[] = [];
@@ -279,7 +443,7 @@ const Parser = defineClass(
279
443
  if (named.length > 0) {
280
444
  throw new ParseError(token, "positional arguments must come before named ones");
281
445
  }
282
- args.push(this.expr());
446
+ args.push(this.item());
283
447
  }
284
448
  if (!this.eat(",")) {
285
449
  this.close(")", open, "`,` or ");
@@ -327,7 +491,7 @@ const Parser = defineClass(
327
491
  this.i++;
328
492
  const items: Expr[] = [];
329
493
  while (!this.eat("]")) {
330
- items.push(this.expr());
494
+ items.push(this.item());
331
495
  if (!this.eat(",")) {
332
496
  this.close("]", token, "`,` or ");
333
497
  break;
@@ -343,13 +507,41 @@ const Parser = defineClass(
343
507
 
344
508
  object(open: Token): Expr {
345
509
  this.i++;
346
- const entries: { key: string; value: Expr; pos: Pos }[] = [];
510
+ const entries: { key: string | Expr | null; value: Expr; pos: Pos }[] = [];
347
511
  while (!this.eat("}")) {
348
512
  const key = this.peek();
513
+ if (this.eat("...")) {
514
+ entries.push({ key: null, value: this.expr(), pos: key });
515
+ if (!this.eat(",")) {
516
+ this.close("}", open, "`,` or ");
517
+ break;
518
+ }
519
+ continue;
520
+ }
521
+ if (this.eat("[")) {
522
+ const computed = this.expr();
523
+ this.close("]", key);
524
+ if (!this.eat(":")) throw new ParseError(this.peek(), `expected \`:\` after the object key, found ${describe(this.peek())}`);
525
+ entries.push({ key: computed, value: this.expr(), pos: key });
526
+ if (!this.eat(",")) {
527
+ this.close("}", open, "`,` or ");
528
+ break;
529
+ }
530
+ continue;
531
+ }
349
532
  if (key.t !== "ident" && key.t !== "str") {
350
- throw new ParseError(key, `expected an object key (a name or a string), found ${describe(key)}`);
533
+ throw new ParseError(key, `expected an object key (a name, a string or [expression]), found ${describe(key)}`);
351
534
  }
352
535
  this.i++;
536
+ // `{name}` is `{name: name}`.
537
+ if (key.t === "ident" && (this.isPunct(",") || this.isPunct("}"))) {
538
+ entries.push({ key: key.value, value: { type: "ident", name: key.value, pos: key }, pos: key });
539
+ if (!this.eat(",")) {
540
+ this.close("}", open, "`,` or ");
541
+ break;
542
+ }
543
+ continue;
544
+ }
353
545
  // `{Good for: …}`: models write labels as bare words; nothing else may follow a key, so read them as one.
354
546
  let name = key.value;
355
547
  if (key.t === "ident") {
@@ -1,4 +1,4 @@
1
- import type { CallExpr, Decl, Expr, Program, Statement } from "./ast";
1
+ import type { ArrowExpr, CallExpr, Decl, Expr, Program, Statement } from "./ast";
2
2
  import {
3
3
  ACTIONS,
4
4
  COMPONENTS,
@@ -24,7 +24,25 @@ export const ACTION_SPECS: ReadonlyMap<string, ComponentSpec> = new Map(Object.e
24
24
  type MethodName = (typeof METHODS)[keyof typeof METHODS][number];
25
25
 
26
26
  /** Methods whose single argument is an arrow `(item, index?) => ...`. */
27
- export const LAMBDA_METHODS: ReadonlySet<string> = new Set(["map", "filter", "find", "some", "every"]);
27
+ export const LAMBDA_METHODS: ReadonlySet<string> = new Set(["map", "filter", "find", "some", "every", "findIndex", "flatMap"]);
28
+
29
+ /** What a method's function receives, for those that take one. */
30
+ export const FUNCTION_PARAMS: ReadonlyMap<string, readonly string[]> = new Map([
31
+ ...[...LAMBDA_METHODS].map((name): [string, readonly string[]] => [name, ["item", "index"]]),
32
+ ["sort", ["a", "b"]],
33
+ ["reduce", ["total", "item", "index"]],
34
+ ]);
35
+
36
+ /** A method's function argument; a declared function's name, as in `rows.map(row)`, becomes `(a, b) => row(a, b)`. */
37
+ export function functionArg(arg: Expr, named: ReadonlyMap<string, Decl>, method: string, params: readonly string[] = []): Expr {
38
+ if (arg.type !== "ident" || params.includes(arg.name)) return arg;
39
+ const own = named.get(arg.name)?.value;
40
+ if (own?.type !== "arrow") return arg;
41
+ // `#` cannot appear in a written name, so these never shadow anything.
42
+ const names = own.params.slice(0, FUNCTION_PARAMS.get(method)?.length ?? 2).map((_, index) => `#${index}`);
43
+ const args = names.map((name): Expr => ({ type: "ident", name, pos: arg.pos }));
44
+ return { type: "arrow", params: names, body: { type: "call", name: arg.name, args, named: [], pos: arg.pos }, pos: arg.pos } satisfies ArrowExpr;
45
+ }
28
46
 
29
47
  type Arity = readonly [min: number, max: number];
30
48
 
@@ -32,8 +50,11 @@ const METHOD_ARITY: ReadonlyMap<string, Arity> = new Map(
32
50
  Object.entries({
33
51
  map: [1, 1], filter: [1, 1], find: [1, 1], some: [1, 1], every: [1, 1],
34
52
  join: [0, 1], slice: [0, 2], includes: [1, 1], indexOf: [1, 1], concat: [1, Infinity], sort: [0, 1],
53
+ reduce: [1, 2], flatMap: [1, 1], flat: [0, 1], at: [1, 1], findIndex: [1, 1], lastIndexOf: [1, 1], reverse: [0, 0],
35
54
  split: [1, 1], trim: [0, 0], toUpperCase: [0, 0], toLowerCase: [0, 0],
36
- startsWith: [1, 1], endsWith: [1, 1], replace: [2, 2], replaceAll: [2, 2], toFixed: [0, 1],
55
+ startsWith: [1, 1], endsWith: [1, 1], replace: [2, 2], replaceAll: [2, 2],
56
+ charAt: [1, 1], substring: [1, 2], padStart: [1, 2], padEnd: [1, 2], repeat: [1, 1], trimStart: [0, 0], trimEnd: [0, 0],
57
+ toFixed: [0, 1], toLocaleString: [0, 0], toString: [0, 1],
37
58
  } satisfies Record<MethodName, Arity>),
38
59
  );
39
60
 
@@ -41,12 +62,13 @@ const FUNCTION_ARITY: ReadonlyMap<string, Arity> = new Map(
41
62
  Object.entries({
42
63
  round: [1, 2], fmt: [1, 2], sum: [1, 1], min: [1, Infinity], max: [1, Infinity], abs: [1, 1], Load: [1, 1],
43
64
  keys: [1, 1], values: [1, 1], entries: [1, 1], floor: [1, 1], ceil: [1, 1], sqrt: [1, 1], pow: [2, 2],
65
+ Number: [1, 1], String: [1, 1], parseInt: [1, 2], parseFloat: [1, 1], "JSON.stringify": [1, 3], "Date.now": [0, 0],
44
66
  } satisfies Record<FunctionName, Arity>),
45
67
  );
46
68
 
47
69
  const ACTION_LIST = [...ACTION_SPECS].map(([name, spec]) => signature(name, spec)).join(", ");
48
70
  const ARROW_ONLY =
49
- "arrow functions can only be declared as a named function (`share = p => ...`) or passed to map, filter, find, some, every or sort";
71
+ "arrow functions can only be declared as a named function (`share = p => ...`) or passed to a list method such as map, filter, reduce or sort";
50
72
 
51
73
  /** The type of a value, as named in diagnostics. */
52
74
  export type Kind = "null" | "boolean" | "number" | "string" | "list" | "object" | "node" | "action" | "binding";
@@ -136,6 +158,10 @@ function signature(name: string, spec: ComponentSpec): string {
136
158
  return `${name}(${params.join(", ")})`;
137
159
  }
138
160
 
161
+ function isSpread(arg: Expr): boolean {
162
+ return arg.type === "spread";
163
+ }
164
+
139
165
  function arityText([min, max]: Arity): string {
140
166
  if (max === Infinity) return `at least ${min} argument${min === 1 ? "" : "s"}`;
141
167
  if (min === max) return `${min} argument${min === 1 ? "" : "s"}`;
@@ -366,10 +392,18 @@ const Validator = defineClass(
366
392
  return;
367
393
  case "object":
368
394
  for (const entry of expr.entries) {
369
- this.forbidden(entry.key, entry.pos);
395
+ if (typeof entry.key === "string") this.forbidden(entry.key, entry.pos);
396
+ else if (entry.key !== null) this.check(entry.key, params, refs);
370
397
  this.check(entry.value, params, refs);
371
398
  }
372
399
  return;
400
+ case "spread":
401
+ this.check(expr.value, params, refs);
402
+ return;
403
+ case "let":
404
+ this.check(expr.value, params, refs);
405
+ this.check(expr.body, [...params, expr.name], refs);
406
+ return;
373
407
  case "unary":
374
408
  this.check(expr.operand, params, refs);
375
409
  return;
@@ -428,20 +462,24 @@ const Validator = defineClass(
428
462
  expr.pos,
429
463
  `\`.${expr.name}()\` is not an allowed method.${hint} Lists: ${METHODS.list.join(", ")}. Text: ${METHODS.string.join(", ")}. Numbers: ${METHODS.number.join(", ")}.`,
430
464
  );
431
- } else if (expr.args.length < arity[0] || expr.args.length > arity[1]) {
465
+ } else if (!expr.args.some(isSpread) && (expr.args.length < arity[0] || expr.args.length > arity[1])) {
432
466
  this.diagnostics.report(expr.pos, `\`.${expr.name}()\` takes ${arityText(arity)}`);
433
467
  }
434
- const [first, ...rest] = expr.args;
435
- const sort = expr.name === "sort";
436
- if ((LAMBDA_METHODS.has(expr.name) || sort) && first !== undefined) {
468
+ const [written, ...rest] = expr.args;
469
+ const passes = FUNCTION_PARAMS.get(expr.name);
470
+ const first = written !== undefined && passes !== undefined ? functionArg(written, this.named, expr.name, params) : written;
471
+ if (passes !== undefined && first !== undefined) {
437
472
  if (first.type !== "arrow") {
438
- const example = sort ? "(a, b) => a.price - b.price" : "x => x.price";
473
+ const example =
474
+ expr.name === "sort" ? "(a, b) => a.price - b.price" : expr.name === "reduce" ? "(total, x) => total + x.price, 0" : "x => x.price";
439
475
  this.diagnostics.report(first.pos, `\`.${expr.name}()\` takes a function, as in \`${example}\``);
440
476
  this.check(first, params, refs);
441
477
  } else {
442
- if (first.params.length > 2) {
443
- const passes = sort ? "(a, b)" : "(item, index)";
444
- this.diagnostics.report(first.pos, `\`.${expr.name}()\` passes ${passes}; use at most 2 parameters`);
478
+ if (first.params.length > passes.length) {
479
+ this.diagnostics.report(
480
+ first.pos,
481
+ `\`.${expr.name}()\` passes (${passes.join(", ")}); use at most ${passes.length} parameters`,
482
+ );
445
483
  }
446
484
  this.check(first.body, [...params, ...first.params], refs);
447
485
  }
@@ -460,7 +498,7 @@ const Validator = defineClass(
460
498
  if (expr.named.length > 0) {
461
499
  this.diagnostics.report(expr.named[0].pos, `\`${expr.name}\` takes positional arguments only`);
462
500
  }
463
- if (expr.args.length > own.params.length) {
501
+ if (!expr.args.some(isSpread) && expr.args.length > own.params.length) {
464
502
  const count = own.params.length;
465
503
  this.diagnostics.report(expr.pos, `\`${expr.name}\` takes ${count} argument${count === 1 ? "" : "s"}`);
466
504
  }
@@ -473,7 +511,7 @@ const Validator = defineClass(
473
511
  if (expr.named.length > 0) {
474
512
  this.diagnostics.report(expr.named[0].pos, `\`${expr.name}\` takes positional arguments only`);
475
513
  }
476
- if (expr.args.length < arity[0] || expr.args.length > arity[1]) {
514
+ if (!expr.args.some(isSpread) && (expr.args.length < arity[0] || expr.args.length > arity[1])) {
477
515
  this.diagnostics.report(expr.pos, `\`${expr.name}\` takes ${arityText(arity)}: ${FUNCTIONS[expr.name as FunctionName]}`);
478
516
  } else if (expr.name === "Load") {
479
517
  this.literalPath(expr.args[0], "Load");
@@ -516,6 +554,9 @@ const Validator = defineClass(
516
554
  /** Maps arguments onto catalog params and checks what is knowable before evaluation. */
517
555
  catalogCall(expr: CallExpr, spec: ComponentSpec): void {
518
556
  const sig = signature(expr.name, spec);
557
+ for (const arg of expr.args.filter(isSpread)) {
558
+ this.diagnostics.report(arg.pos, `\`...\` cannot spread into ${expr.name}; pass the list or object itself`);
559
+ }
519
560
  const slots: (Expr | undefined)[] = spec.params.map((_, index) => expr.args[index]);
520
561
  if (expr.args.length > spec.params.length) {
521
562
  this.diagnostics.report(expr.args[spec.params.length].pos, `too many arguments: ${sig}`);
@@ -1,7 +1,8 @@
1
1
  import { mkdir, rm, symlink, writeFile } from "node:fs/promises";
2
+ import os from "node:os";
2
3
  import path from "node:path";
3
4
  import { describe, expect, it } from "vitest";
4
- import type { PaseoApi } from "@getpaseo/client";
5
+ import type { PluginHandlerContext } from "@getpaseo/plugin/server";
5
6
  import {
6
7
  collectLoads,
7
8
  compile,
@@ -26,8 +27,11 @@ import {
26
27
  loadAgentImage,
27
28
  loadGalleryFile,
28
29
  readGallerySpec,
30
+ setExtraLoadFolders,
29
31
  } from "../server/data-source";
30
32
 
33
+ type PaseoApi = PluginHandlerContext["paseo"];
34
+
31
35
  describe("paseo-plugin-genui core, instructions, and gallery", () => {
32
36
  it("compiles every example in the agent instructions cleanly", () => {
33
37
  for (const section of [
@@ -81,6 +85,25 @@ describe("paseo-plugin-genui core, instructions, and gallery", () => {
81
85
  expect(roots.map((root) => root.props.text)).toEqual(["a b b", "a$&!b"]);
82
86
  });
83
87
 
88
+ it("accepts a declared function's name as a list method's function", () => {
89
+ const compiled = compile(
90
+ [
91
+ "items = [{n: \"x\", v: 3}, {n: \"y\", v: 1}, {n: \"z\", v: 2}]",
92
+ "label = (p, i) => `${i}:${p.n}`",
93
+ "big = p => p.v > 1",
94
+ "byV = (a, b) => a.v - b.v",
95
+ "Text(items.filter(big).map(label).join(\",\"))",
96
+ "Text(items.sort(byV).map(p => p.n).join(\",\"))",
97
+ "row = p => [p.n, p.v]",
98
+ "Table([\"n\", \"v\"], items.map(row))",
99
+ ].join("\n"),
100
+ );
101
+ expect(compiled.diagnostics).toEqual([]);
102
+ const { roots } = evaluate(compiled.program!, initialState(compiled.program!));
103
+ expect(roots.slice(0, 2).map((root) => root.props.text)).toEqual(["0:x,1:z", "y,z,x"]);
104
+ expect(roots[2].props.rows).toEqual([["x", 3], ["y", 1], ["z", 2]]);
105
+ });
106
+
84
107
  it("covers all 86 catalog components in the gallery and compiles + evaluates every gallery spec", async () => {
85
108
  const files = await listGallery();
86
109
  expect(files.length).toBeGreaterThanOrEqual(170);
@@ -215,4 +238,26 @@ describe("paseo-plugin-genui core, instructions, and gallery", () => {
215
238
  await rm(testRoot, { recursive: true, force: true });
216
239
  }
217
240
  });
241
+ it("loads files from extra folders only once they are added in settings", async () => {
242
+ const folder = path.join(os.homedir(), `.genui-extra-folder-test-${Date.now()}`);
243
+ await mkdir(folder, { recursive: true });
244
+ try {
245
+ const file = path.join(folder, "notes.txt");
246
+ await writeFile(file, "scratch-line\n", "utf8");
247
+ const mockPaseo = {
248
+ agents: { ref: () => ({ current: () => ({ cwd: "/nonexistent-workspace" }), refresh: async () => null }) },
249
+ } as unknown as PaseoApi;
250
+ const tilde = `~/${path.basename(folder)}/notes.txt`;
251
+
252
+ expect((await loadAgentFile(mockPaseo, "agent_extra_test", file, { raw: true })).ok).toBe(false);
253
+
254
+ setExtraLoadFolders([`~/${path.basename(folder)}`]);
255
+ expect(await loadAgentFile(mockPaseo, "agent_extra_test", file, { raw: true })).toEqual({ ok: true, value: "scratch-line\n" });
256
+ expect(await loadAgentFile(mockPaseo, "agent_extra_test", tilde, { raw: true })).toEqual({ ok: true, value: "scratch-line\n" });
257
+ expect((await loadAgentFile(mockPaseo, "agent_extra_test", path.join(os.homedir(), ".bashrc"), { raw: true })).ok).toBe(false);
258
+ } finally {
259
+ setExtraLoadFolders([]);
260
+ await rm(folder, { recursive: true, force: true });
261
+ }
262
+ });
218
263
  });
@@ -24,11 +24,11 @@ export const REFERENCE_MORE_GROUPS: readonly ComponentGroup[] = ["Inputs", "Widg
24
24
 
25
25
  export const UI_REFERENCE = `# Inline UI reference
26
26
  The \`\`\`ui language used by the Inline UI section below.
27
- Syntax: one statement per line. \`$x = 8\` is state inputs bind to; \`name = expr\` names a value and \`f = (a, b) => expr\` a function; each bare expression renders. JS expressions incl. ** ?: ?? \`\${x}\` [lists] {objects} x.y map/filter/find/sort/concat/join/replace/length, plus round(x, d), fmt(x, d), sum, min, max, abs, entries, Load(path). Named args go last: Slider($n, 0, 10, label: "N").
27
+ Syntax: one statement per line. \`$x = 8\` is state inputs bind to; \`name = expr\` names a value and \`f = (a, b) => expr\` a function; each bare expression renders. JS expressions incl. ** ?: ?? ?. ...spread, destructuring, \`x => { const y = ...; return y }\`, \`\${x}\`, the common list and text methods, Math.*, Object.keys/entries, Number(), String(), JSON.stringify; plus round(x, d), fmt(x, d), sum, Load(path). No if, for or reassignment. Named args go last: Slider($n, 0, 10, label: "N").
28
28
  Components (? optional; tone: neutral|good|warn|bad|info if meaningful; more in the next section):
29
29
  ${componentLines(REFERENCE_GROUPS)}
30
30
  Actions: ${actionList}; a list runs in order; Send posts as the user.
31
- Data: Load("path") reads JSON/CSV/TSV/JSONL from the workspace, "$BB_THREAD_STORAGE/x.json" or /tmp into lists and objects, and other files (a log, tsc output) as text; never retype values a file or command output holds. Snippet and Image read files the same way.
31
+ Data: Load("path") reads JSON/CSV/TSV/JSONL from the workspace, "$BB_THREAD_STORAGE/x.json" or /tmp into lists and objects, and other files (a log, tsc output) as text; never retype values a file or command output holds. Snippet and Image read files the same way. Any other path fails to load: copy the file into $BB_THREAD_STORAGE first.
32
32
  Games, simulations, custom visuals: write \`\`\`app, a self-contained HTML page (inline CSS/JS, CSS vars --foreground --muted-foreground --border --primary --card; sandboxed, no network).`;
33
33
 
34
34
  export const UI_REFERENCE_MORE = `# Inline UI reference, continued
@@ -133,10 +133,11 @@ export const AGENT_INSTRUCTIONS_WEB_OFF = AGENT_INSTRUCTIONS.replace(MAP_EXAMPLE
133
133
 
134
134
  export const GENUI_MARKER = "[paseo-plugin-genui]";
135
135
 
136
- export function buildFullInstructions(webLookups: boolean): string {
136
+ export function buildFullInstructions(webLookups: boolean, extraFolders: readonly string[] = []): string {
137
137
  return [
138
138
  GENUI_MARKER,
139
139
  UI_REFERENCE,
140
+ ...(extraFolders.length > 0 ? [`Load, Snippet and Image also read absolute paths under: ${extraFolders.join(", ")}.`] : []),
140
141
  UI_REFERENCE_MORE,
141
142
  CODE_WORK_INSTRUCTIONS,
142
143
  webLookups ? AGENT_INSTRUCTIONS : AGENT_INSTRUCTIONS_WEB_OFF,