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.
- package/OVERVIEW.md +3 -3
- package/client/settings.tsx +22 -1
- package/index.server.ts +10 -4
- package/package.json +1 -1
- package/server/data-source.ts +19 -4
- package/server/project.ts +3 -1
- package/shared/core/ast.ts +12 -5
- package/shared/core/catalog.ts +25 -1
- package/shared/core/data.ts +11 -1
- package/shared/core/evaluate.ts +176 -26
- package/shared/core/lexer.ts +4 -4
- package/shared/core/parser.ts +228 -36
- package/shared/core/validate.ts +56 -15
- package/shared/genui.test.ts +46 -1
- package/shared/instructions.ts +4 -3
- package/shared/js-idioms.test.ts +114 -0
- package/shared/settings.ts +8 -0
package/OVERVIEW.md
CHANGED
|
@@ -11,11 +11,11 @@ When automatic instructions are enabled, new agents receive the Generative UI co
|
|
|
11
11
|
## Capabilities and data access
|
|
12
12
|
|
|
13
13
|
- **86 components in 10 groups**: Layout, Content, Data, Media, Inputs, Widgets, Project, Dev, Manage, and Evidence.
|
|
14
|
-
- **Confined file reading**: `Load(path)`, `Snippet(path, from, to)`, and `Image(path)` read JSON, CSV, TSV, logs, test reports (Vitest, Jest, JUnit), coverage (`lcov`, Istanbul, `coverage.py`, Go), lint and typecheck findings (ESLint, SARIF, `tsc`, Ruff), HAR traces, and benchmarks. Reads are strictly confined to the agent's workspace directory, its per-agent thread storage directory (`/tmp/opencode/genui-storage/<agentId>`), and
|
|
14
|
+
- **Confined file reading**: `Load(path)`, `Snippet(path, from, to)`, and `Image(path)` read JSON, CSV, TSV, logs, test reports (Vitest, Jest, JUnit), coverage (`lcov`, Istanbul, `coverage.py`, Go), lint and typecheck findings (ESLint, SARIF, `tsc`, Ruff), HAR traces, and benchmarks. Reads are strictly confined to the agent's workspace directory, its per-agent thread storage directory (`/tmp/opencode/genui-storage/<agentId>`), `/tmp`, and any extra folders added in settings.
|
|
15
15
|
- **Live workspace and git state**: `Changes()`, `Commits()`, `PullRequest()`, `Threads()`, and `Environments()` read the workspace's git diff, commits, pull request status, subagents, and worktrees on the daemon host.
|
|
16
16
|
- **Sandboxed mini-apps**: `app` blocks run self-contained HTML and JavaScript inside a sandboxed iframe (`sandbox="allow-scripts"`) with a network-blocking Content Security Policy on desktop and web clients.
|
|
17
|
-
- **Settings and web lookups**: Under **Settings -> Plugins -> Generative UI**, you can toggle automatic agent instructions for new sessions and toggle server-side web lookups. When web lookups are on, the daemon fetches photo searches from Wikimedia Commons (`commons.wikimedia.org` / `upload.wikimedia.org`), geocoding from Photon (`photon.komoot.io`), map tiles from OpenStreetMap (`tile.openstreetmap.org`), and HTTPS images through an address-checked proxy that rejects loopback, private, and link-local IP addresses. No cookies, credentials, or conversation text beyond the specific search query or place name are sent. Turning web lookups off disables all external network requests.
|
|
17
|
+
- **Settings and web lookups**: Under **Settings -> Plugins -> Generative UI**, you can toggle automatic agent instructions for new sessions and toggle server-side web lookups, and add extra folders (for example `~/dev/scratch`) that file reads may use. When web lookups are on, the daemon fetches photo searches from Wikimedia Commons (`commons.wikimedia.org` / `upload.wikimedia.org`), geocoding from Photon (`photon.komoot.io`), map tiles from OpenStreetMap (`tile.openstreetmap.org`), and HTTPS images through an address-checked proxy that rejects loopback, private, and link-local IP addresses. No cookies, credentials, or conversation text beyond the specific search query or place name are sent. Turning web lookups off disables all external network requests.
|
|
18
18
|
|
|
19
19
|
## Limits
|
|
20
20
|
|
|
21
|
-
File reads outside the agent's workspace, thread storage,
|
|
21
|
+
File reads outside the agent's workspace, thread storage, `/tmp`, and the extra folders in settings are refused; agents are told to copy other files into thread storage first. Sandboxed `app` blocks require a desktop or browser client; mobile clients display the block's source code.
|
package/client/settings.tsx
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { useSettings, type PluginSurfaceProps } from "@getpaseo/plugin/client";
|
|
2
|
-
import { SettingsCard, SettingsSection, SettingsSwitch } from "@getpaseo/plugin/client/ui";
|
|
2
|
+
import { SettingsAction, SettingsCard, SettingsInput, SettingsSection, SettingsSwitch } from "@getpaseo/plugin/client/ui";
|
|
3
3
|
import React from "react";
|
|
4
4
|
import { Text, View } from "react-native";
|
|
5
5
|
import { genuiSettings } from "../shared/settings";
|
|
6
6
|
|
|
7
7
|
export function GenUiSettingsScreen({ theme }: PluginSurfaceProps) {
|
|
8
8
|
const settings = useSettings(genuiSettings);
|
|
9
|
+
const [folders, setFolders] = React.useState<string | null>(null);
|
|
9
10
|
|
|
10
11
|
if (settings.status === "loading") {
|
|
11
12
|
return (
|
|
@@ -52,6 +53,26 @@ export function GenUiSettingsScreen({ theme }: PluginSurfaceProps) {
|
|
|
52
53
|
/>
|
|
53
54
|
</SettingsCard>
|
|
54
55
|
</SettingsSection>
|
|
56
|
+
|
|
57
|
+
<SettingsSection title="Files">
|
|
58
|
+
<SettingsCard>
|
|
59
|
+
<SettingsInput
|
|
60
|
+
label="Extra folders"
|
|
61
|
+
hint="Comma-separated folders, besides the workspace, thread storage and /tmp, that Load, Snippet and Image can read."
|
|
62
|
+
initialValue={values.extraFolders}
|
|
63
|
+
placeholder="~/dev/scratch"
|
|
64
|
+
onChangeText={setFolders}
|
|
65
|
+
/>
|
|
66
|
+
<SettingsAction
|
|
67
|
+
label="Apply folder changes"
|
|
68
|
+
actionLabel="Save"
|
|
69
|
+
disabled={folders === null || folders === values.extraFolders}
|
|
70
|
+
onPress={() => {
|
|
71
|
+
if (folders !== null) void save({ ...values, extraFolders: folders }, revision);
|
|
72
|
+
}}
|
|
73
|
+
/>
|
|
74
|
+
</SettingsCard>
|
|
75
|
+
</SettingsSection>
|
|
55
76
|
</View>
|
|
56
77
|
);
|
|
57
78
|
}
|
package/index.server.ts
CHANGED
|
@@ -29,7 +29,7 @@ import {
|
|
|
29
29
|
webTileRpc,
|
|
30
30
|
} from "./shared/rpc";
|
|
31
31
|
import { GENUI_BLOCK_KIND } from "./shared/segment";
|
|
32
|
-
import { genuiSettings } from "./shared/settings";
|
|
32
|
+
import { genuiSettings, parseFolders } from "./shared/settings";
|
|
33
33
|
import {
|
|
34
34
|
agentStorageDir,
|
|
35
35
|
examplesReport,
|
|
@@ -41,6 +41,7 @@ import {
|
|
|
41
41
|
loadGalleryFile,
|
|
42
42
|
loadGalleryImage,
|
|
43
43
|
readGallerySpec,
|
|
44
|
+
setExtraLoadFolders,
|
|
44
45
|
sketchFontDataUrl,
|
|
45
46
|
} from "./server/data-source";
|
|
46
47
|
import {
|
|
@@ -69,10 +70,14 @@ export default function contribute(server: PluginServerContext) {
|
|
|
69
70
|
let webLookupsEnabled = true;
|
|
70
71
|
|
|
71
72
|
void settings.read().then((state) => {
|
|
72
|
-
if (state.status
|
|
73
|
+
if (state.status !== "ready") return;
|
|
74
|
+
webLookupsEnabled = state.values.webLookups;
|
|
75
|
+
setExtraLoadFolders(parseFolders(state.values.extraFolders));
|
|
73
76
|
});
|
|
74
77
|
const unsubscribeSettings = settings.subscribe((state) => {
|
|
75
|
-
if (state.status
|
|
78
|
+
if (state.status !== "ready") return;
|
|
79
|
+
webLookupsEnabled = state.values.webLookups;
|
|
80
|
+
setExtraLoadFolders(parseFolders(state.values.extraFolders));
|
|
76
81
|
});
|
|
77
82
|
|
|
78
83
|
const web = createWebLookups(
|
|
@@ -92,13 +97,14 @@ export default function contribute(server: PluginServerContext) {
|
|
|
92
97
|
const current = await settings.read();
|
|
93
98
|
if (current.status === "ready" && !current.values.autoInstructions) return;
|
|
94
99
|
const webOn = current.status === "ready" ? current.values.webLookups : true;
|
|
100
|
+
const extraFolders = current.status === "ready" ? parseFolders(current.values.extraFolders) : [];
|
|
95
101
|
const existing = request.config.systemPrompt ?? "";
|
|
96
102
|
if (existing.includes(GENUI_MARKER)) return;
|
|
97
103
|
return {
|
|
98
104
|
...request,
|
|
99
105
|
config: {
|
|
100
106
|
...request.config,
|
|
101
|
-
systemPrompt: [existing, buildFullInstructions(webOn)].filter(Boolean).join("\n\n"),
|
|
107
|
+
systemPrompt: [existing, buildFullInstructions(webOn, extraFolders)].filter(Boolean).join("\n\n"),
|
|
102
108
|
},
|
|
103
109
|
};
|
|
104
110
|
});
|
package/package.json
CHANGED
package/server/data-source.ts
CHANGED
|
@@ -3,10 +3,12 @@ import { mkdir, open, readdir, readFile, realpath } from "node:fs/promises";
|
|
|
3
3
|
import os from "node:os";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
|
-
import type {
|
|
6
|
+
import type { PluginHandlerContext } from "@getpaseo/plugin/server";
|
|
7
7
|
import { collectLoads, compile, parseDataFile, type LoadedData } from "../shared/core";
|
|
8
8
|
import { COMPONENTS, componentSignature, type ComponentName } from "../shared/core/catalog";
|
|
9
9
|
|
|
10
|
+
type PaseoApi = PluginHandlerContext["paseo"];
|
|
11
|
+
|
|
10
12
|
export const MAX_DATA_BYTES = 2 * 1024 * 1024;
|
|
11
13
|
export const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
|
|
12
14
|
export const MAX_AUDIO_BYTES = 25 * 1024 * 1024;
|
|
@@ -47,7 +49,19 @@ type FileContent =
|
|
|
47
49
|
|
|
48
50
|
type FileReader = (requested: string, maxBytes: number) => Promise<FileContent>;
|
|
49
51
|
|
|
50
|
-
const AGENT_REFUSAL =
|
|
52
|
+
const AGENT_REFUSAL =
|
|
53
|
+
"only files in this agent's workspace, its thread storage, /tmp or a folder added in Generative UI settings can be loaded";
|
|
54
|
+
|
|
55
|
+
let extraRoots: readonly string[] = [];
|
|
56
|
+
|
|
57
|
+
/** Folders, besides the workspace, thread storage and /tmp, that agents may load files from. */
|
|
58
|
+
export function setExtraLoadFolders(folders: readonly string[]): void {
|
|
59
|
+
extraRoots = folders.map(expandHome).filter((folder) => path.isAbsolute(folder));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function expandHome(requested: string): string {
|
|
63
|
+
return requested === "~" || requested.startsWith("~/") ? path.join(os.homedir(), requested.slice(1)) : requested;
|
|
64
|
+
}
|
|
51
65
|
const GALLERY_REFUSAL = "gallery specs can only load files in gallery/";
|
|
52
66
|
|
|
53
67
|
function contains(root: string, target: string): boolean {
|
|
@@ -189,10 +203,11 @@ async function readAgentFile(
|
|
|
189
203
|
} else if (requested.startsWith(PASEO_STORAGE_PREFIX)) {
|
|
190
204
|
const rel = requested.slice(PASEO_STORAGE_PREFIX.length);
|
|
191
205
|
attempts = inside(storageRoot, path.resolve(storageRoot, rel));
|
|
192
|
-
} else if (path.isAbsolute(requested)) {
|
|
193
|
-
const target = path.resolve(requested);
|
|
206
|
+
} else if (path.isAbsolute(expandHome(requested))) {
|
|
207
|
+
const target = path.resolve(expandHome(requested));
|
|
194
208
|
attempts = [...inside(storageRoot, target), ...inside(workspaceCwd, target)].slice(0, 1);
|
|
195
209
|
if (attempts.length === 0) attempts = tempAttempts(target);
|
|
210
|
+
if (attempts.length === 0) attempts = extraRoots.flatMap((root) => inside(root, target)).slice(0, 1);
|
|
196
211
|
} else {
|
|
197
212
|
attempts = [
|
|
198
213
|
...inside(workspaceCwd, workspaceCwd !== null ? path.resolve(workspaceCwd, requested) : ""),
|
package/server/project.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
2
|
import { promisify } from "node:util";
|
|
3
|
-
import type {
|
|
3
|
+
import type { PluginHandlerContext } from "@getpaseo/plugin/server";
|
|
4
4
|
import type {
|
|
5
5
|
EnvironmentDetail,
|
|
6
6
|
EnvironmentDetailResult,
|
|
@@ -34,6 +34,8 @@ import {
|
|
|
34
34
|
import { lastMessage } from "../shared/core/thread-activity";
|
|
35
35
|
import { resolveAgentCwd } from "./data-source";
|
|
36
36
|
|
|
37
|
+
type PaseoApi = PluginHandlerContext["paseo"];
|
|
38
|
+
|
|
37
39
|
const execFileAsync = promisify(execFile);
|
|
38
40
|
|
|
39
41
|
function failure(reason: ProjectFailure["reason"], message: string): ProjectFailure {
|
package/shared/core/ast.ts
CHANGED
|
@@ -5,7 +5,8 @@ export type BinaryOperator =
|
|
|
5
5
|
| "??" | "||" | "&&"
|
|
6
6
|
| "==" | "!=" | "===" | "!=="
|
|
7
7
|
| "<" | "<=" | ">" | ">="
|
|
8
|
-
| "+" | "-" | "*" | "/" | "%" | "**"
|
|
8
|
+
| "+" | "-" | "*" | "/" | "%" | "**"
|
|
9
|
+
| "in";
|
|
9
10
|
|
|
10
11
|
export interface NamedArg {
|
|
11
12
|
readonly name: string;
|
|
@@ -24,10 +25,13 @@ export type Expr =
|
|
|
24
25
|
| { readonly type: "list"; readonly items: readonly Expr[]; readonly pos: Pos }
|
|
25
26
|
| {
|
|
26
27
|
readonly type: "object";
|
|
27
|
-
|
|
28
|
+
/** An expression key is computed, as in `{[k]: 1}`; a null key spreads `value`, as in `{...o}`. */
|
|
29
|
+
readonly entries: readonly { readonly key: string | Expr | null; readonly value: Expr; readonly pos: Pos }[];
|
|
28
30
|
readonly pos: Pos;
|
|
29
31
|
}
|
|
30
|
-
|
|
32
|
+
/** `...value`; the parser makes it only as a list item or an argument. */
|
|
33
|
+
| { readonly type: "spread"; readonly value: Expr; readonly pos: Pos }
|
|
34
|
+
| { readonly type: "unary"; readonly op: "!" | "-" | "typeof"; readonly operand: Expr; readonly pos: Pos }
|
|
31
35
|
| { readonly type: "binary"; readonly op: BinaryOperator; readonly left: Expr; readonly right: Expr; readonly pos: Pos }
|
|
32
36
|
| { readonly type: "conditional"; readonly test: Expr; readonly then: Expr; readonly else: Expr; readonly pos: Pos }
|
|
33
37
|
/** `object.name`; `pos` is the property name. */
|
|
@@ -41,16 +45,19 @@ export type Expr =
|
|
|
41
45
|
readonly named: readonly NamedArg[];
|
|
42
46
|
readonly pos: Pos;
|
|
43
47
|
}
|
|
44
|
-
/** `object.name(...)`; `pos` is the method name. */
|
|
48
|
+
/** `object.name(...)`; `pos` is the method name. `optional`: after a `?.`, so a null object gives null. */
|
|
45
49
|
| {
|
|
46
50
|
readonly type: "method";
|
|
47
51
|
readonly object: Expr;
|
|
48
52
|
readonly name: string;
|
|
49
53
|
readonly args: readonly Expr[];
|
|
50
54
|
readonly named: readonly NamedArg[];
|
|
55
|
+
readonly optional: boolean;
|
|
51
56
|
readonly pos: Pos;
|
|
52
57
|
}
|
|
53
|
-
| { readonly type: "arrow"; readonly params: readonly string[]; readonly body: Expr; readonly pos: Pos }
|
|
58
|
+
| { readonly type: "arrow"; readonly params: readonly string[]; readonly body: Expr; readonly pos: Pos }
|
|
59
|
+
/** `name` holds `value` while `body` runs; block bodies and destructuring parse into these. */
|
|
60
|
+
| { readonly type: "let"; readonly name: string; readonly value: Expr; readonly body: Expr; readonly pos: Pos };
|
|
54
61
|
|
|
55
62
|
export type CallExpr = Extract<Expr, { type: "call" }>;
|
|
56
63
|
export type ArrowExpr = Extract<Expr, { type: "arrow" }>;
|
package/shared/core/catalog.ts
CHANGED
|
@@ -674,6 +674,12 @@ export const FUNCTIONS = {
|
|
|
674
674
|
keys: "keys(object) → list of keys",
|
|
675
675
|
values: "values(object) → list of values",
|
|
676
676
|
entries: "entries(object) → list of [key, value]",
|
|
677
|
+
Number: "Number(x) → a number, or null for text that is not one",
|
|
678
|
+
String: "String(x) → text",
|
|
679
|
+
parseInt: "parseInt(text, radix?) → a whole number, or null",
|
|
680
|
+
parseFloat: "parseFloat(text) → a number, or null",
|
|
681
|
+
"JSON.stringify": "JSON.stringify(value, null?, indent?) → JSON text",
|
|
682
|
+
"Date.now": "Date.now() → milliseconds since 1970",
|
|
677
683
|
Load: "Load(path): JSON/CSV/TSV/JSONL/text file, workspace-relative or in thread storage",
|
|
678
684
|
} as const;
|
|
679
685
|
|
|
@@ -693,6 +699,13 @@ export const METHODS = {
|
|
|
693
699
|
"indexOf",
|
|
694
700
|
"concat",
|
|
695
701
|
"sort",
|
|
702
|
+
"reduce",
|
|
703
|
+
"flatMap",
|
|
704
|
+
"flat",
|
|
705
|
+
"at",
|
|
706
|
+
"findIndex",
|
|
707
|
+
"lastIndexOf",
|
|
708
|
+
"reverse",
|
|
696
709
|
],
|
|
697
710
|
string: [
|
|
698
711
|
"includes",
|
|
@@ -705,8 +718,19 @@ export const METHODS = {
|
|
|
705
718
|
"endsWith",
|
|
706
719
|
"replace",
|
|
707
720
|
"replaceAll",
|
|
721
|
+
"indexOf",
|
|
722
|
+
"lastIndexOf",
|
|
723
|
+
"at",
|
|
724
|
+
"charAt",
|
|
725
|
+
"substring",
|
|
726
|
+
"padStart",
|
|
727
|
+
"padEnd",
|
|
728
|
+
"repeat",
|
|
729
|
+
"trimStart",
|
|
730
|
+
"trimEnd",
|
|
731
|
+
"toString",
|
|
708
732
|
],
|
|
709
|
-
number: ["toFixed"],
|
|
733
|
+
number: ["toFixed", "toLocaleString", "toString"],
|
|
710
734
|
} as const;
|
|
711
735
|
|
|
712
736
|
/** Read-only properties allowed on lists and strings (plain objects allow any own key). */
|
package/shared/core/data.ts
CHANGED
|
@@ -47,7 +47,17 @@ export function collectLoads(program: Program): DataRequest[] {
|
|
|
47
47
|
expr.items.forEach(visit);
|
|
48
48
|
return;
|
|
49
49
|
case "object":
|
|
50
|
-
for (const entry of expr.entries)
|
|
50
|
+
for (const entry of expr.entries) {
|
|
51
|
+
if (entry.key !== null && typeof entry.key !== "string") visit(entry.key);
|
|
52
|
+
visit(entry.value);
|
|
53
|
+
}
|
|
54
|
+
return;
|
|
55
|
+
case "spread":
|
|
56
|
+
visit(expr.value);
|
|
57
|
+
return;
|
|
58
|
+
case "let":
|
|
59
|
+
visit(expr.value);
|
|
60
|
+
visit(expr.body);
|
|
51
61
|
return;
|
|
52
62
|
case "unary":
|
|
53
63
|
visit(expr.operand);
|
package/shared/core/evaluate.ts
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
coerceState,
|
|
10
10
|
DESCRIPTIONS,
|
|
11
11
|
EXPECTED,
|
|
12
|
+
functionArg,
|
|
12
13
|
LAMBDA_METHODS,
|
|
13
14
|
stateMismatch,
|
|
14
15
|
type Kind,
|
|
@@ -163,15 +164,26 @@ function roundTo(value: number, digits: number): number {
|
|
|
163
164
|
return value < 0 ? -rounded : rounded;
|
|
164
165
|
}
|
|
165
166
|
|
|
166
|
-
/** `1234.5` → "1,234.5"; fixed `digits`, or up to
|
|
167
|
-
function fmt(value: number, digits: number | undefined): string {
|
|
168
|
-
let fixed = roundTo(value, digits ??
|
|
167
|
+
/** `1234.5` → "1,234.5"; fixed `digits`, or up to `most` with trailing zeros trimmed. */
|
|
168
|
+
function fmt(value: number, digits: number | undefined, most = 2): string {
|
|
169
|
+
let fixed = roundTo(value, digits ?? most).toFixed(digits ?? most);
|
|
169
170
|
if (digits === undefined) fixed = fixed.replace(/\.0+$|(\.\d*?)0+$/, "$1");
|
|
170
171
|
const [whole, fraction] = fixed.split(".");
|
|
171
172
|
const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
172
173
|
return fraction === undefined ? grouped : `${grouped}.${fraction}`;
|
|
173
174
|
}
|
|
174
175
|
|
|
176
|
+
/** `list[index]`, counting from the end for a negative index, as `.at()` does. */
|
|
177
|
+
function at(list: readonly Value[] | string, index: number): Value {
|
|
178
|
+
const from = Math.trunc(index) < 0 ? list.length + Math.trunc(index) : Math.trunc(index);
|
|
179
|
+
return from >= 0 && from < list.length ? list[from] : null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function typeOf(value: Value): string {
|
|
183
|
+
if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") return typeof value;
|
|
184
|
+
return "object";
|
|
185
|
+
}
|
|
186
|
+
|
|
175
187
|
/** The expression passed for `params[index]`, positionally or by name. */
|
|
176
188
|
function argument(call: CallExpr, params: readonly ParamSpec[], index: number): Expr | undefined {
|
|
177
189
|
return index < call.args.length ? call.args[index] : call.named.find((arg) => arg.name === params[index].name)?.value;
|
|
@@ -246,23 +258,36 @@ const Interpreter = defineClass(
|
|
|
246
258
|
}
|
|
247
259
|
return this.named(expr.name, expr.pos);
|
|
248
260
|
case "list":
|
|
249
|
-
return checkLength(
|
|
250
|
-
expr.items.map((item) => this.expr(item, scope)),
|
|
251
|
-
expr.pos,
|
|
252
|
-
);
|
|
261
|
+
return checkLength(this.spread(expr.items, scope).values, expr.pos);
|
|
253
262
|
case "object": {
|
|
254
263
|
const object: Record<string, Value> = {};
|
|
255
264
|
for (const entry of expr.entries) {
|
|
256
265
|
const value = this.expr(entry.value, scope);
|
|
257
|
-
if (entry.key ===
|
|
266
|
+
if (entry.key === null) {
|
|
267
|
+
if (value === null) continue;
|
|
268
|
+
if (!isPlainObject(value)) throw new RuntimeError(entry.pos, `\`...\` in an object needs an object, got ${describe(value)}`);
|
|
269
|
+
// Copy own keys one by one: Object.assign would run the `__proto__` setter for loaded JSON's own `__proto__` key.
|
|
270
|
+
for (const [key, item] of Object.entries(value)) {
|
|
271
|
+
if (!(FORBIDDEN_PROPERTIES as readonly string[]).includes(key)) object[key] = item;
|
|
272
|
+
}
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
const key = typeof entry.key === "string" ? entry.key : toText(this.expr(entry.key, scope), entry.key.pos);
|
|
276
|
+
if ((FORBIDDEN_PROPERTIES as readonly string[]).includes(key)) throw new RuntimeError(entry.pos, `\`${key}\` is not accessible`);
|
|
277
|
+
if (key === "kind" && (value === "node" || value === "action" || value === "binding")) {
|
|
258
278
|
throw new RuntimeError(entry.pos, `\`kind: "${value}"\` is reserved; use another key or value`);
|
|
259
279
|
}
|
|
260
|
-
object[
|
|
280
|
+
object[key] = value;
|
|
261
281
|
}
|
|
262
282
|
return object;
|
|
263
283
|
}
|
|
284
|
+
case "spread":
|
|
285
|
+
throw new RuntimeError(expr.pos, "`...` works only inside [ ], { } and function arguments");
|
|
286
|
+
case "let":
|
|
287
|
+
return this.expr(expr.body, { name: expr.name, value: this.expr(expr.value, scope), parent: scope });
|
|
264
288
|
case "unary": {
|
|
265
289
|
const operand = this.expr(expr.operand, scope);
|
|
290
|
+
if (expr.op === "typeof") return typeOf(operand);
|
|
266
291
|
return expr.op === "!" ? !truthy(operand) : finite(-this.number(operand, expr.pos, "`-`"));
|
|
267
292
|
}
|
|
268
293
|
case "binary":
|
|
@@ -352,6 +377,10 @@ const Interpreter = defineClass(
|
|
|
352
377
|
}
|
|
353
378
|
if (typeof left === "number" && typeof right === "number") return finite(left + right);
|
|
354
379
|
throw new RuntimeError(expr.pos, `\`+\` needs numbers or text, got ${describe(left)} and ${describe(right)}`);
|
|
380
|
+
case "in":
|
|
381
|
+
if (isList(right)) return typeof left === "number" && Number.isInteger(left) && left >= 0 && left < right.length;
|
|
382
|
+
if (isPlainObject(right)) return Object.hasOwn(right, this.text(left, expr.left.pos, "`in`"));
|
|
383
|
+
throw new RuntimeError(expr.pos, `\`in\` needs an object or a list on its right, got ${describe(right)}`);
|
|
355
384
|
case "<":
|
|
356
385
|
case "<=":
|
|
357
386
|
case ">":
|
|
@@ -572,6 +601,27 @@ const Interpreter = defineClass(
|
|
|
572
601
|
throw new RuntimeError(call.pos, `unknown action \`${call.name}\``);
|
|
573
602
|
},
|
|
574
603
|
|
|
604
|
+
/** Evaluated items or arguments with `...list` spread in place, and the position each came from. */
|
|
605
|
+
spread(exprs: readonly Expr[], scope: Scope | null): { values: Value[]; positions: Pos[] } {
|
|
606
|
+
const values: Value[] = [];
|
|
607
|
+
const positions: Pos[] = [];
|
|
608
|
+
for (const expr of exprs) {
|
|
609
|
+
if (expr.type !== "spread") {
|
|
610
|
+
values.push(this.expr(expr, scope));
|
|
611
|
+
positions.push(expr.pos);
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
const list = this.expr(expr.value, scope);
|
|
615
|
+
if (!isList(list)) throw new RuntimeError(expr.pos, `\`...\` needs a list here, got ${describe(list)}`);
|
|
616
|
+
checkLength(list, expr.pos);
|
|
617
|
+
for (const item of list) {
|
|
618
|
+
values.push(item);
|
|
619
|
+
positions.push(expr.pos);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
return { values, positions };
|
|
623
|
+
},
|
|
624
|
+
|
|
575
625
|
/** Numbers in a list; nulls are skipped. */
|
|
576
626
|
numbers(value: Value, pos: Pos, label: string): number[] {
|
|
577
627
|
if (!isList(value)) throw new RuntimeError(pos, `${label} needs a list of numbers, got ${describe(value)}`);
|
|
@@ -581,11 +631,12 @@ const Interpreter = defineClass(
|
|
|
581
631
|
},
|
|
582
632
|
|
|
583
633
|
callFunction(call: CallExpr, scope: Scope | null): Value {
|
|
584
|
-
const
|
|
634
|
+
const { values: args, positions } = this.spread(call.args, scope);
|
|
635
|
+
const posAt = (index: number) => positions[index] ?? call.pos;
|
|
585
636
|
const name = call.name;
|
|
586
|
-
const numberAt = (index: number) => this.number(args[index],
|
|
637
|
+
const numberAt = (index: number) => this.number(args[index] ?? null, posAt(index), `${name}()`);
|
|
587
638
|
const digitsAt = (index: number) =>
|
|
588
|
-
index < args.length ? this.digits(args[index],
|
|
639
|
+
index < args.length ? this.digits(args[index], posAt(index), `${name}()`) : undefined;
|
|
589
640
|
switch (name) {
|
|
590
641
|
case "round":
|
|
591
642
|
return finite(roundTo(numberAt(0), digitsAt(1) ?? 0));
|
|
@@ -602,12 +653,12 @@ const Interpreter = defineClass(
|
|
|
602
653
|
case "pow":
|
|
603
654
|
return finite(numberAt(0) ** numberAt(1));
|
|
604
655
|
case "sum":
|
|
605
|
-
return finite(this.numbers(args[0],
|
|
656
|
+
return finite(this.numbers(args[0] ?? null, posAt(0), "sum()").reduce((total, n) => total + n, 0));
|
|
606
657
|
case "min":
|
|
607
658
|
case "max": {
|
|
608
659
|
const values =
|
|
609
660
|
args.length === 1 && isList(args[0])
|
|
610
|
-
? this.numbers(args[0],
|
|
661
|
+
? this.numbers(args[0], posAt(0), `${name}()`)
|
|
611
662
|
: args.map((_, index) => numberAt(index));
|
|
612
663
|
if (values.length === 0) return null;
|
|
613
664
|
return name === "min" ? Math.min(...values) : Math.max(...values);
|
|
@@ -615,8 +666,8 @@ const Interpreter = defineClass(
|
|
|
615
666
|
case "keys":
|
|
616
667
|
case "values":
|
|
617
668
|
case "entries": {
|
|
618
|
-
const object = args[0];
|
|
619
|
-
if (!isPlainObject(object)) throw new RuntimeError(
|
|
669
|
+
const object = args[0] ?? null;
|
|
670
|
+
if (!isPlainObject(object)) throw new RuntimeError(posAt(0), `${name}() needs an object, got ${describe(object)}`);
|
|
620
671
|
const pairs = Object.entries(object);
|
|
621
672
|
return checkLength(
|
|
622
673
|
name === "keys" ? pairs.map(([key]) => key) : name === "values" ? pairs.map(([, value]) => value) : pairs,
|
|
@@ -624,12 +675,35 @@ const Interpreter = defineClass(
|
|
|
624
675
|
);
|
|
625
676
|
}
|
|
626
677
|
case "Load": {
|
|
627
|
-
const path = this.text(args[0],
|
|
678
|
+
const path = this.text(args[0], posAt(0), "Load()");
|
|
628
679
|
const loaded = this.data.get(dataKey({ path, raw: false }));
|
|
629
680
|
if (loaded === undefined) throw new LoadPending(call.pos, path);
|
|
630
681
|
if (!loaded.ok) throw new RuntimeError(call.pos, `Couldn't load ${path}: ${loaded.error}`);
|
|
631
682
|
return loaded.value;
|
|
632
683
|
}
|
|
684
|
+
case "Number": {
|
|
685
|
+
const value = args[0] ?? null;
|
|
686
|
+
if (value === null) return 0;
|
|
687
|
+
if (typeof value === "boolean") return value ? 1 : 0;
|
|
688
|
+
if (typeof value === "number") return value;
|
|
689
|
+
if (typeof value === "string") return finite(Number(value.trim().replaceAll(",", "")));
|
|
690
|
+
throw new RuntimeError(posAt(0), `Number() needs text or a number, got ${describe(value)}`);
|
|
691
|
+
}
|
|
692
|
+
case "String":
|
|
693
|
+
return toText(args[0] ?? null, posAt(0));
|
|
694
|
+
case "parseInt":
|
|
695
|
+
return finite(parseInt(toText(args[0] ?? null, posAt(0)), args.length > 1 ? numberAt(1) : 10));
|
|
696
|
+
case "parseFloat":
|
|
697
|
+
return finite(parseFloat(toText(args[0] ?? null, posAt(0))));
|
|
698
|
+
case "JSON.stringify": {
|
|
699
|
+
const indent = args[2] ?? null;
|
|
700
|
+
if (indent !== null && typeof indent !== "number" && typeof indent !== "string") {
|
|
701
|
+
throw new RuntimeError(posAt(2), `JSON.stringify() indent must be a number or text, got ${describe(indent)}`);
|
|
702
|
+
}
|
|
703
|
+
return checkString(JSON.stringify(args[0] ?? null, null, indent ?? undefined), call.pos);
|
|
704
|
+
}
|
|
705
|
+
case "Date.now":
|
|
706
|
+
return Date.now();
|
|
633
707
|
}
|
|
634
708
|
throw new RuntimeError(call.pos, `\`${name}\` is not a function`);
|
|
635
709
|
},
|
|
@@ -640,7 +714,7 @@ const Interpreter = defineClass(
|
|
|
640
714
|
* by the call site too, so two calls never share component state.
|
|
641
715
|
*/
|
|
642
716
|
callOwn(call: CallExpr, fn: ArrowExpr, scope: Scope | null): Value {
|
|
643
|
-
const args = call.args
|
|
717
|
+
const args = this.spread(call.args, scope).values;
|
|
644
718
|
let inner: Scope | null = null;
|
|
645
719
|
for (const [index, name] of fn.params.entries()) {
|
|
646
720
|
inner = { name, value: index < args.length ? args[index] : null, parent: inner };
|
|
@@ -656,12 +730,23 @@ const Interpreter = defineClass(
|
|
|
656
730
|
|
|
657
731
|
method(call: Extract<Expr, { type: "method" }>, scope: Scope | null): Value {
|
|
658
732
|
const receiver = this.expr(call.object, scope);
|
|
733
|
+
if (receiver === null && call.optional) return null;
|
|
659
734
|
if (isList(receiver) && LAMBDA_METHODS.has(call.name)) return this.lambdaMethod(receiver, call, scope);
|
|
660
735
|
if (isList(receiver) && call.name === "sort") return this.sort(receiver, call, scope);
|
|
661
|
-
|
|
736
|
+
if (isList(receiver) && call.name === "reduce") return this.reduce(receiver, call, scope);
|
|
737
|
+
const { values: args, positions } = this.spread(call.args, scope);
|
|
738
|
+
const posAt = (index: number) => positions[index] ?? call.pos;
|
|
662
739
|
const label = `.${call.name}()`;
|
|
663
|
-
const textAt = (index: number) => this.text(args[index],
|
|
664
|
-
const
|
|
740
|
+
const textAt = (index: number) => this.text(args[index] ?? null, posAt(index), label);
|
|
741
|
+
const numberAt = (index: number) => this.number(args[index] ?? null, posAt(index), label);
|
|
742
|
+
const bounds = () => args.map((arg, index) => this.number(arg, posAt(index), label));
|
|
743
|
+
/** A whole count that keeps the result within the text limit. */
|
|
744
|
+
const sizeAt = (index: number, per: number) => {
|
|
745
|
+
const count = numberAt(index);
|
|
746
|
+
if (!Number.isInteger(count) || count < 0) throw new RuntimeError(posAt(index), `${label} needs a whole number of 0 or more`);
|
|
747
|
+
if (count * per > MAX_STRING_LENGTH) throw new RuntimeError(call.pos, `text longer than ${MAX_STRING_LENGTH} characters`);
|
|
748
|
+
return count;
|
|
749
|
+
};
|
|
665
750
|
if (isList(receiver)) {
|
|
666
751
|
switch (call.name) {
|
|
667
752
|
case "join":
|
|
@@ -677,6 +762,18 @@ const Interpreter = defineClass(
|
|
|
677
762
|
return receiver.indexOf(args[0]);
|
|
678
763
|
case "concat":
|
|
679
764
|
return checkLength(receiver.concat(...args), call.pos);
|
|
765
|
+
case "at":
|
|
766
|
+
return at(receiver, numberAt(0));
|
|
767
|
+
case "lastIndexOf":
|
|
768
|
+
return receiver.lastIndexOf(args[0] ?? null);
|
|
769
|
+
case "reverse":
|
|
770
|
+
return [...receiver].reverse();
|
|
771
|
+
case "flat": {
|
|
772
|
+
const depth = args.length > 0 ? numberAt(0) : 1;
|
|
773
|
+
const flatten = (list: readonly Value[], level: number): Value[] =>
|
|
774
|
+
checkLength(list.flatMap((item) => (isList(item) && level > 0 ? flatten(item, level - 1) : [item])), call.pos);
|
|
775
|
+
return flatten(receiver, depth);
|
|
776
|
+
}
|
|
680
777
|
}
|
|
681
778
|
} else if (typeof receiver === "string") {
|
|
682
779
|
switch (call.name) {
|
|
@@ -701,10 +798,40 @@ const Interpreter = defineClass(
|
|
|
701
798
|
return checkString(receiver.replace(textAt(0), () => textAt(1)), call.pos);
|
|
702
799
|
case "replaceAll":
|
|
703
800
|
return checkString(receiver.replaceAll(textAt(0), () => textAt(1)), call.pos);
|
|
801
|
+
case "indexOf":
|
|
802
|
+
return receiver.indexOf(textAt(0));
|
|
803
|
+
case "lastIndexOf":
|
|
804
|
+
return receiver.lastIndexOf(textAt(0));
|
|
805
|
+
case "at":
|
|
806
|
+
return at(receiver, numberAt(0));
|
|
807
|
+
case "charAt":
|
|
808
|
+
return receiver.charAt(numberAt(0));
|
|
809
|
+
case "substring":
|
|
810
|
+
return receiver.substring(...(bounds() as [number, number?]));
|
|
811
|
+
case "padStart":
|
|
812
|
+
case "padEnd": {
|
|
813
|
+
const width = sizeAt(0, 1);
|
|
814
|
+
const fill = args.length > 1 ? textAt(1) : " ";
|
|
815
|
+
return call.name === "padStart" ? receiver.padStart(width, fill) : receiver.padEnd(width, fill);
|
|
816
|
+
}
|
|
817
|
+
case "repeat":
|
|
818
|
+
return receiver.repeat(sizeAt(0, receiver.length));
|
|
819
|
+
case "trimStart":
|
|
820
|
+
return receiver.trimStart();
|
|
821
|
+
case "trimEnd":
|
|
822
|
+
return receiver.trimEnd();
|
|
704
823
|
}
|
|
705
824
|
} else if (typeof receiver === "number" && call.name === "toFixed") {
|
|
706
|
-
const digits = args.length > 0 ? this.digits(args[0],
|
|
825
|
+
const digits = args.length > 0 ? this.digits(args[0], posAt(0), label) : 0;
|
|
707
826
|
return roundTo(receiver, digits).toFixed(digits);
|
|
827
|
+
} else if (typeof receiver === "number" && call.name === "toLocaleString") {
|
|
828
|
+
return fmt(receiver, undefined, 3);
|
|
829
|
+
}
|
|
830
|
+
if (call.name === "toString" && (typeof receiver === "number" || typeof receiver === "string" || typeof receiver === "boolean")) {
|
|
831
|
+
if (args.length === 0 || typeof receiver !== "number") return String(receiver);
|
|
832
|
+
const radix = numberAt(0);
|
|
833
|
+
if (!Number.isInteger(radix) || radix < 2 || radix > 36) throw new RuntimeError(posAt(0), `${label} radix must be a whole number from 2 to 36`);
|
|
834
|
+
return receiver.toString(radix);
|
|
708
835
|
}
|
|
709
836
|
throw new RuntimeError(call.pos, `\`${label}\` is not available on ${describe(receiver)}`);
|
|
710
837
|
},
|
|
@@ -712,7 +839,7 @@ const Interpreter = defineClass(
|
|
|
712
839
|
/** A sorted copy; without a comparator, numbers sort numerically and anything else as text. */
|
|
713
840
|
sort(list: readonly Value[], call: Extract<Expr, { type: "method" }>, scope: Scope | null): Value {
|
|
714
841
|
checkLength(list, call.pos);
|
|
715
|
-
const fn = call.args[0];
|
|
842
|
+
const fn = call.args[0] && functionArg(call.args[0], this.program.named, "sort");
|
|
716
843
|
if (fn === undefined) {
|
|
717
844
|
return [...list].sort((a, b) =>
|
|
718
845
|
typeof a === "number" && typeof b === "number" ? a - b : toText(a, call.pos).localeCompare(toText(b, call.pos)),
|
|
@@ -728,9 +855,29 @@ const Interpreter = defineClass(
|
|
|
728
855
|
});
|
|
729
856
|
},
|
|
730
857
|
|
|
858
|
+
/** `.reduce(fn, start?)`; without `start` the first item starts the total. */
|
|
859
|
+
reduce(list: readonly Value[], call: Extract<Expr, { type: "method" }>, scope: Scope | null): Value {
|
|
860
|
+
checkLength(list, call.pos);
|
|
861
|
+
const fn = call.args[0] && functionArg(call.args[0], this.program.named, "reduce");
|
|
862
|
+
if (fn?.type !== "arrow") throw new RuntimeError(call.pos, "`.reduce()` takes a function, as in `(total, x) => total + x.price, 0`");
|
|
863
|
+
if (call.args.length < 2 && list.length === 0) {
|
|
864
|
+
throw new RuntimeError(call.pos, "`.reduce()` on an empty list needs a starting value, as in `.reduce(f, 0)`");
|
|
865
|
+
}
|
|
866
|
+
const [totalName, itemName, indexName] = fn.params;
|
|
867
|
+
let total = call.args.length > 1 ? this.expr(call.args[1], scope) : list[0];
|
|
868
|
+
for (let index = call.args.length > 1 ? 0 : 1; index < list.length; index++) {
|
|
869
|
+
let inner = scope;
|
|
870
|
+
if (totalName !== undefined) inner = { name: totalName, value: total, parent: inner };
|
|
871
|
+
if (itemName !== undefined) inner = { name: itemName, value: list[index], parent: inner };
|
|
872
|
+
if (indexName !== undefined) inner = { name: indexName, value: index, parent: inner };
|
|
873
|
+
total = this.expr(fn.body, inner);
|
|
874
|
+
}
|
|
875
|
+
return total;
|
|
876
|
+
},
|
|
877
|
+
|
|
731
878
|
lambdaMethod(list: readonly Value[], call: Extract<Expr, { type: "method" }>, scope: Scope | null): Value {
|
|
732
879
|
checkLength(list, call.pos);
|
|
733
|
-
const fn = call.args[0];
|
|
880
|
+
const fn = call.args[0] && functionArg(call.args[0], this.program.named, call.name);
|
|
734
881
|
if (fn?.type !== "arrow") throw new RuntimeError(call.pos, `\`.${call.name}()\` takes a function, as in \`x => x.price\``);
|
|
735
882
|
const [itemName, indexName] = fn.params;
|
|
736
883
|
const apply = (item: Value, index: number): Value => {
|
|
@@ -740,15 +887,18 @@ const Interpreter = defineClass(
|
|
|
740
887
|
return this.expr(fn.body, inner);
|
|
741
888
|
};
|
|
742
889
|
switch (call.name) {
|
|
743
|
-
case "map":
|
|
890
|
+
case "map":
|
|
891
|
+
case "flatMap": {
|
|
744
892
|
const base = this.suffix;
|
|
745
893
|
const out = list.map((item, index) => {
|
|
746
894
|
this.suffix = `${base}#${index}`;
|
|
747
895
|
return apply(item, index);
|
|
748
896
|
});
|
|
749
897
|
this.suffix = base;
|
|
750
|
-
return out;
|
|
898
|
+
return call.name === "map" ? out : checkLength(out.flatMap((item) => (isList(item) ? item : [item])), call.pos);
|
|
751
899
|
}
|
|
900
|
+
case "findIndex":
|
|
901
|
+
return list.findIndex((item, index) => truthy(apply(item, index)));
|
|
752
902
|
case "filter":
|
|
753
903
|
return list.filter((item, index) => truthy(apply(item, index)));
|
|
754
904
|
case "find":
|