@milaboratories/pl-mcp-server 54.0.0 → 55.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -25
- package/dist/_virtual/_rolldown/runtime.cjs +22 -0
- package/dist/agent-tables.cjs +116 -0
- package/dist/agent-tables.cjs.map +1 -0
- package/dist/agent-tables.js +115 -0
- package/dist/agent-tables.js.map +1 -0
- package/dist/instructions.cjs +15 -12
- package/dist/instructions.cjs.map +1 -1
- package/dist/instructions.js +15 -12
- package/dist/instructions.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.js +1 -1
- package/dist/project-holds.cjs +58 -8
- package/dist/project-holds.cjs.map +1 -1
- package/dist/project-holds.js +58 -8
- package/dist/project-holds.js.map +1 -1
- package/dist/project-list.cjs +16 -0
- package/dist/project-list.cjs.map +1 -0
- package/dist/project-list.js +16 -0
- package/dist/project-list.js.map +1 -0
- package/dist/server-log.cjs +40 -18
- package/dist/server-log.cjs.map +1 -1
- package/dist/server-log.js +40 -19
- package/dist/server-log.js.map +1 -1
- package/dist/server.cjs +48 -18
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.ts +21 -20
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +48 -18
- package/dist/server.js.map +1 -1
- package/dist/tools/agent-tables.cjs +424 -0
- package/dist/tools/agent-tables.cjs.map +1 -0
- package/dist/tools/agent-tables.js +417 -0
- package/dist/tools/agent-tables.js.map +1 -0
- package/dist/tools/await.cjs +216 -73
- package/dist/tools/await.cjs.map +1 -1
- package/dist/tools/await.js +212 -75
- package/dist/tools/await.js.map +1 -1
- package/dist/tools/block-action-context.cjs +3 -0
- package/dist/tools/block-action-context.cjs.map +1 -1
- package/dist/tools/block-action-context.js +3 -0
- package/dist/tools/block-action-context.js.map +1 -1
- package/dist/tools/block-api.cjs +17 -2
- package/dist/tools/block-api.cjs.map +1 -1
- package/dist/tools/block-api.js +17 -3
- package/dist/tools/block-api.js.map +1 -1
- package/dist/tools/block-params.cjs +272 -4
- package/dist/tools/block-params.cjs.map +1 -1
- package/dist/tools/block-params.js +270 -6
- package/dist/tools/block-params.js.map +1 -1
- package/dist/tools/block-state.cjs +323 -42
- package/dist/tools/block-state.cjs.map +1 -1
- package/dist/tools/block-state.js +317 -46
- package/dist/tools/block-state.js.map +1 -1
- package/dist/tools/block-storage.cjs +153 -0
- package/dist/tools/block-storage.cjs.map +1 -0
- package/dist/tools/block-storage.js +147 -0
- package/dist/tools/block-storage.js.map +1 -0
- package/dist/tools/block-updates.cjs +405 -0
- package/dist/tools/block-updates.cjs.map +1 -0
- package/dist/tools/block-updates.js +397 -0
- package/dist/tools/block-updates.js.map +1 -0
- package/dist/tools/blocks.cjs +183 -70
- package/dist/tools/blocks.cjs.map +1 -1
- package/dist/tools/blocks.js +177 -70
- package/dist/tools/blocks.js.map +1 -1
- package/dist/tools/data-query.cjs +451 -113
- package/dist/tools/data-query.cjs.map +1 -1
- package/dist/tools/data-query.js +446 -118
- package/dist/tools/data-query.js.map +1 -1
- package/dist/tools/errors.cjs +21 -0
- package/dist/tools/errors.cjs.map +1 -0
- package/dist/tools/errors.js +20 -0
- package/dist/tools/errors.js.map +1 -0
- package/dist/tools/files.cjs +643 -0
- package/dist/tools/files.cjs.map +1 -0
- package/dist/tools/files.js +613 -0
- package/dist/tools/files.js.map +1 -0
- package/dist/tools/ids.cjs +56 -0
- package/dist/tools/ids.cjs.map +1 -1
- package/dist/tools/ids.js +51 -2
- package/dist/tools/ids.js.map +1 -1
- package/dist/tools/imports.cjs +195 -0
- package/dist/tools/imports.cjs.map +1 -0
- package/dist/tools/imports.js +186 -0
- package/dist/tools/imports.js.map +1 -0
- package/dist/tools/logs.cjs +98 -19
- package/dist/tools/logs.cjs.map +1 -1
- package/dist/tools/logs.js +95 -20
- package/dist/tools/logs.js.map +1 -1
- package/dist/tools/paging.cjs +27 -0
- package/dist/tools/paging.cjs.map +1 -0
- package/dist/tools/paging.js +26 -0
- package/dist/tools/paging.js.map +1 -0
- package/dist/tools/params-merge.cjs +106 -0
- package/dist/tools/params-merge.cjs.map +1 -0
- package/dist/tools/params-merge.js +106 -0
- package/dist/tools/params-merge.js.map +1 -0
- package/dist/tools/project-template.cjs +75 -0
- package/dist/tools/project-template.cjs.map +1 -0
- package/dist/tools/project-template.js +72 -0
- package/dist/tools/project-template.js.map +1 -0
- package/dist/tools/projects.cjs +66 -19
- package/dist/tools/projects.cjs.map +1 -1
- package/dist/tools/projects.js +66 -20
- package/dist/tools/projects.js.map +1 -1
- package/dist/tools/readiness.cjs +104 -0
- package/dist/tools/readiness.cjs.map +1 -0
- package/dist/tools/readiness.js +99 -0
- package/dist/tools/readiness.js.map +1 -0
- package/dist/tools/result-pool.cjs +260 -0
- package/dist/tools/result-pool.cjs.map +1 -0
- package/dist/tools/result-pool.js +252 -0
- package/dist/tools/result-pool.js.map +1 -0
- package/dist/tools/sandbox.cjs +112 -14
- package/dist/tools/sandbox.cjs.map +1 -1
- package/dist/tools/sandbox.js +110 -15
- package/dist/tools/sandbox.js.map +1 -1
- package/dist/tools/sdk-types.cjs +24 -0
- package/dist/tools/sdk-types.cjs.map +1 -0
- package/dist/tools/sdk-types.js +24 -0
- package/dist/tools/sdk-types.js.map +1 -0
- package/dist/tools/settle.cjs +155 -0
- package/dist/tools/settle.cjs.map +1 -0
- package/dist/tools/settle.js +148 -0
- package/dist/tools/settle.js.map +1 -0
- package/dist/tools/tokens.cjs +49 -8
- package/dist/tools/tokens.cjs.map +1 -1
- package/dist/tools/tokens.js +45 -9
- package/dist/tools/tokens.js.map +1 -1
- package/dist/tools/types.cjs +62 -11
- package/dist/tools/types.cjs.map +1 -1
- package/dist/tools/types.js +60 -12
- package/dist/tools/types.js.map +1 -1
- package/dist/tools/value-outline.cjs +119 -0
- package/dist/tools/value-outline.cjs.map +1 -0
- package/dist/tools/value-outline.js +117 -0
- package/dist/tools/value-outline.js.map +1 -0
- package/package.json +9 -8
- package/src/agent-tables.test.ts +246 -0
- package/src/agent-tables.ts +145 -0
- package/src/instructions.ts +15 -12
- package/src/project-holds.test.ts +179 -0
- package/src/project-holds.ts +114 -12
- package/src/project-list.test.ts +38 -0
- package/src/project-list.ts +25 -0
- package/src/server-log.test.ts +54 -1
- package/src/server-log.ts +49 -27
- package/src/server.logging.test.ts +38 -46
- package/src/server.test.ts +151 -17
- package/src/server.ts +62 -34
- package/src/tools/agent-tables.test.ts +650 -0
- package/src/tools/agent-tables.ts +673 -0
- package/src/tools/await.test.ts +287 -0
- package/src/tools/await.ts +393 -123
- package/src/tools/block-action-context.ts +3 -0
- package/src/tools/block-api.ts +19 -4
- package/src/tools/block-params.test.ts +828 -0
- package/src/tools/block-params.ts +623 -8
- package/src/tools/block-state.test.ts +480 -0
- package/src/tools/block-state.ts +659 -66
- package/src/tools/block-storage.test.ts +270 -0
- package/src/tools/block-storage.ts +195 -0
- package/src/tools/block-updates.test.ts +605 -0
- package/src/tools/block-updates.ts +751 -0
- package/src/tools/blocks.test.ts +169 -22
- package/src/tools/blocks.ts +336 -105
- package/src/tools/data-query.test.ts +641 -0
- package/src/tools/data-query.ts +807 -157
- package/src/tools/errors.test.ts +33 -0
- package/src/tools/errors.ts +23 -0
- package/src/tools/files.test.ts +842 -0
- package/src/tools/files.ts +990 -0
- package/src/tools/ids.test.ts +87 -0
- package/src/tools/ids.ts +67 -0
- package/src/tools/imports.ts +304 -0
- package/src/tools/logs.test.ts +70 -0
- package/src/tools/logs.ts +130 -21
- package/src/tools/paging.test.ts +39 -0
- package/src/tools/paging.ts +39 -0
- package/src/tools/params-merge.test.ts +274 -0
- package/src/tools/params-merge.ts +149 -0
- package/src/tools/project-template.test.ts +230 -0
- package/src/tools/project-template.ts +135 -0
- package/src/tools/projects.test.ts +122 -0
- package/src/tools/projects.ts +135 -25
- package/src/tools/readiness.test.ts +195 -0
- package/src/tools/readiness.ts +189 -0
- package/src/tools/result-pool.test.ts +377 -0
- package/src/tools/result-pool.ts +483 -0
- package/src/tools/sandbox.test.ts +128 -10
- package/src/tools/sandbox.ts +132 -18
- package/src/tools/sdk-types.ts +54 -0
- package/src/tools/settle.test.ts +340 -0
- package/src/tools/settle.ts +312 -0
- package/src/tools/tokens.ts +74 -9
- package/src/tools/types.ts +77 -12
- package/src/tools/value-outline.ts +143 -0
- package/dist/tools/screenshot.cjs +0 -44
- package/dist/tools/screenshot.cjs.map +0 -1
- package/dist/tools/screenshot.js +0 -44
- package/dist/tools/screenshot.js.map +0 -1
- package/dist/tools/ui-interaction.cjs +0 -140
- package/dist/tools/ui-interaction.cjs.map +0 -1
- package/dist/tools/ui-interaction.js +0 -140
- package/dist/tools/ui-interaction.js.map +0 -1
- package/src/tools/screenshot.ts +0 -61
- package/src/tools/ui-interaction.ts +0 -184
package/dist/tools/sandbox.cjs
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
+
let _milaboratories_helpers = require("@milaboratories/helpers");
|
|
1
2
|
let quickjs_emscripten = require("quickjs-emscripten");
|
|
2
3
|
// src/tools/sandbox.ts
|
|
4
|
+
/** The size of the sandbox's memory, in bytes. */
|
|
5
|
+
const MEMORY_LIMIT = 16777216;
|
|
3
6
|
/** Lazily initialized QuickJS runtime shared across evaluations. */
|
|
4
7
|
let sharedRuntime;
|
|
5
8
|
async function getRuntime() {
|
|
6
9
|
if (!sharedRuntime) {
|
|
7
10
|
sharedRuntime = (await (0, quickjs_emscripten.getQuickJS)()).newRuntime();
|
|
8
|
-
sharedRuntime.setMemoryLimit(
|
|
11
|
+
sharedRuntime.setMemoryLimit(MEMORY_LIMIT);
|
|
9
12
|
sharedRuntime.setMaxStackSize(327680);
|
|
10
13
|
}
|
|
11
14
|
return sharedRuntime;
|
|
@@ -93,24 +96,103 @@ function parseThrown(dumped) {
|
|
|
93
96
|
errorClass
|
|
94
97
|
};
|
|
95
98
|
}
|
|
99
|
+
/** The longest an expression may run, in milliseconds, whatever the caller asks for. */
|
|
100
|
+
const MAX_EXPRESSION_TIMEOUT_MS = 1e4;
|
|
101
|
+
/**
|
|
102
|
+
* The timeout an evaluation runs under: `requested`, at most {@link MAX_EXPRESSION_TIMEOUT_MS}.
|
|
103
|
+
* The sandbox runs on the server's thread, so a long evaluation holds every other call up.
|
|
104
|
+
*/
|
|
105
|
+
function clampExpressionTimeout(requested) {
|
|
106
|
+
if (Number.isNaN(requested)) return MAX_EXPRESSION_TIMEOUT_MS;
|
|
107
|
+
return Math.min(requested, MAX_EXPRESSION_TIMEOUT_MS);
|
|
108
|
+
}
|
|
109
|
+
/** The words a timeout argument is described with, for every tool that takes one. */
|
|
110
|
+
function expressionTimeoutText(subject, defaultMs) {
|
|
111
|
+
return `Timeout in ms for ${subject} (default ${defaultMs}, at most ${MAX_EXPRESSION_TIMEOUT_MS}).`;
|
|
112
|
+
}
|
|
113
|
+
const OUT_OF_MEMORY_HINT = "The values the expression reads do not fit in the sandbox's 16 MB. Read less: name the parts you need, e.g. `outputs.<key>?.value` or `data.<key>`, instead of whole values.";
|
|
114
|
+
/**
|
|
115
|
+
* Installs the context in the sandbox as globals that read their value from the host on first
|
|
116
|
+
* use, so a variable the expression does not read is never copied in. A plain-object variable is
|
|
117
|
+
* a Proxy that reads one key at a time: `outputs.qc?.value` copies `qc` only, `Object.keys(outputs)`
|
|
118
|
+
* the keys only, a spread or `JSON.stringify(outputs)` all of it. Values are copied as JSON.
|
|
119
|
+
*
|
|
120
|
+
* Writes behave as on a plain object. A value read once is kept, so a change inside it stays. The
|
|
121
|
+
* first change of the record itself (a key set, added or deleted, or the record frozen) copies
|
|
122
|
+
* every key into the Proxy's target, which from then on is the record. A global can be assigned.
|
|
123
|
+
*/
|
|
124
|
+
const CONTEXT_SETUP = `(() => {
|
|
125
|
+
const value = globalThis.__plValue, keysOf = globalThis.__plKeys;
|
|
126
|
+
delete globalThis.__plValue;
|
|
127
|
+
delete globalThis.__plKeys;
|
|
128
|
+
const parse = (json) => (json === undefined ? undefined : JSON.parse(json));
|
|
129
|
+
const record = (name) => {
|
|
130
|
+
const cache = new Map();
|
|
131
|
+
let keys;
|
|
132
|
+
// Set by the first change: the target then holds every key and answers for the record.
|
|
133
|
+
let copied = false;
|
|
134
|
+
const keyList = () => (keys ??= JSON.parse(keysOf(name)));
|
|
135
|
+
const own = (k) => !copied && typeof k === "string" && keyList().includes(k);
|
|
136
|
+
const read = (k) => {
|
|
137
|
+
if (!cache.has(k)) cache.set(k, parse(value(name, k)));
|
|
138
|
+
return cache.get(k);
|
|
139
|
+
};
|
|
140
|
+
const copy = (t) => {
|
|
141
|
+
if (copied) return;
|
|
142
|
+
for (const k of keyList())
|
|
143
|
+
Object.defineProperty(t, k, {
|
|
144
|
+
value: read(k), writable: true, enumerable: true, configurable: true,
|
|
145
|
+
});
|
|
146
|
+
copied = true;
|
|
147
|
+
};
|
|
148
|
+
return new Proxy({}, {
|
|
149
|
+
get: (t, k, r) => (own(k) ? read(k) : Reflect.get(t, k, r)),
|
|
150
|
+
has: (t, k) => own(k) || Reflect.has(t, k),
|
|
151
|
+
ownKeys: (t) => (copied ? Reflect.ownKeys(t) : [...keyList()]),
|
|
152
|
+
// An accessor, so that listing the keys (Object.keys) reads no value.
|
|
153
|
+
getOwnPropertyDescriptor: (t, k) =>
|
|
154
|
+
own(k)
|
|
155
|
+
? { get: () => read(k), enumerable: true, configurable: true }
|
|
156
|
+
: Reflect.getOwnPropertyDescriptor(t, k),
|
|
157
|
+
set: (t, k, v, r) => (copy(t), Reflect.set(t, k, v, r)),
|
|
158
|
+
defineProperty: (t, k, d) => (copy(t), Reflect.defineProperty(t, k, d)),
|
|
159
|
+
deleteProperty: (t, k) => (copy(t), Reflect.deleteProperty(t, k)),
|
|
160
|
+
preventExtensions: (t) => (copy(t), Reflect.preventExtensions(t)),
|
|
161
|
+
});
|
|
162
|
+
};
|
|
163
|
+
for (const [name, isRecord] of JSON.parse(keysOf())) {
|
|
164
|
+
let done = false, v;
|
|
165
|
+
Object.defineProperty(globalThis, name, {
|
|
166
|
+
get: () => {
|
|
167
|
+
if (!done) { v = isRecord ? record(name) : parse(value(name)); done = true; }
|
|
168
|
+
return v;
|
|
169
|
+
},
|
|
170
|
+
set: (next) => { v = next; done = true; },
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
})()`;
|
|
96
174
|
/**
|
|
97
175
|
* Evaluate a JS expression in a QuickJS sandbox.
|
|
98
|
-
* Variables from `context` are
|
|
176
|
+
* Variables from `context` are globals read from the host when the expression reads them (see
|
|
177
|
+
* {@link CONTEXT_SETUP}), so a large value it does not read costs nothing.
|
|
99
178
|
* Data is marshaled via JSON — no access to Node APIs, filesystem, or process.
|
|
100
179
|
*
|
|
101
180
|
* A failed evaluation throws a {@link SandboxError} whose message is the error as QuickJS reports it (`Name: message`),
|
|
102
|
-
* with a hint on writing several statements when the expression does not parse
|
|
103
|
-
*
|
|
181
|
+
* with a hint on writing several statements when the expression does not parse, and one on reading less when the
|
|
182
|
+
* sandbox runs out of memory. An evaluation that runs longer than `timeout` milliseconds (at most
|
|
183
|
+
* {@link MAX_EXPRESSION_TIMEOUT_MS}) throws a {@link SandboxError} saying that it timed out. An expression whose value
|
|
184
|
+
* is `undefined` (or anything else JSON has no form for, such as a function) gives `null`.
|
|
104
185
|
*/
|
|
105
186
|
async function safeEval(expression, context, timeout) {
|
|
106
187
|
const runtime = await getRuntime();
|
|
107
|
-
const
|
|
188
|
+
const limit = clampExpressionTimeout(timeout);
|
|
189
|
+
const deadline = Date.now() + limit;
|
|
108
190
|
let timedOut = false;
|
|
109
191
|
runtime.setInterruptHandler(() => {
|
|
110
192
|
if (Date.now() > deadline) timedOut = true;
|
|
111
193
|
return timedOut;
|
|
112
194
|
});
|
|
113
|
-
const timeoutMessage = `Evaluation timed out after ${
|
|
195
|
+
const timeoutMessage = `Evaluation timed out after ${limit} ms`;
|
|
114
196
|
const vm = runtime.newContext();
|
|
115
197
|
/** Reads the error of a failed evaluation and releases its handle. `undefined` when the timeout stopped the code. */
|
|
116
198
|
const takeThrown = (error) => {
|
|
@@ -119,23 +201,33 @@ async function safeEval(expression, context, timeout) {
|
|
|
119
201
|
return timedOut ? void 0 : parseThrown(dumped);
|
|
120
202
|
};
|
|
121
203
|
try {
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
204
|
+
const valueOf = vm.newFunction("__plValue", (nameHandle, keyHandle) => {
|
|
205
|
+
const value = context[vm.getString(nameHandle)];
|
|
206
|
+
const json = JSON.stringify(keyHandle === void 0 || !(0, _milaboratories_helpers.isPlainObject)(value) ? value : Object.getOwnPropertyDescriptor(value, vm.getString(keyHandle))?.value);
|
|
207
|
+
return json === void 0 ? vm.undefined : vm.newString(json);
|
|
208
|
+
});
|
|
209
|
+
const keysOf = vm.newFunction("__plKeys", (nameHandle) => {
|
|
210
|
+
const keys = nameHandle === void 0 ? Object.entries(context).map(([name, value]) => [name, (0, _milaboratories_helpers.isPlainObject)(value)]) : Object.keys(context[vm.getString(nameHandle)]);
|
|
211
|
+
return vm.newString(JSON.stringify(keys));
|
|
212
|
+
});
|
|
213
|
+
vm.setProp(vm.global, "__plValue", valueOf);
|
|
214
|
+
vm.setProp(vm.global, "__plKeys", keysOf);
|
|
215
|
+
valueOf.dispose();
|
|
216
|
+
keysOf.dispose();
|
|
217
|
+
const setupResult = vm.evalCode(CONTEXT_SETUP, "setup.js", { type: "global" });
|
|
126
218
|
if (setupResult.error) {
|
|
127
219
|
const thrown = takeThrown(setupResult.error);
|
|
128
220
|
if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);
|
|
129
|
-
throw new SandboxError(`Context setup failed: ${thrown.text}`, thrown.errorClass);
|
|
221
|
+
throw new SandboxError(`Context setup failed: ${thrown.text}${isOutOfMemory(thrown) ? `. ${OUT_OF_MEMORY_HINT}` : ""}`, thrown.errorClass);
|
|
130
222
|
}
|
|
131
223
|
setupResult.value.dispose();
|
|
132
|
-
const result = vm.evalCode(`JSON.stringify((${expression}))`, EXPRESSION_FILE);
|
|
224
|
+
const result = vm.evalCode(`JSON.stringify((${expression}\n))`, EXPRESSION_FILE);
|
|
133
225
|
if (result.error) {
|
|
134
226
|
const thrown = takeThrown(result.error);
|
|
135
227
|
if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);
|
|
136
|
-
throw new SandboxError(thrown.syntaxErrorFile === EXPRESSION_FILE ? `${thrown.text}. ${SINGLE_EXPRESSION_HINT}` : thrown.text, thrown.errorClass);
|
|
228
|
+
throw new SandboxError(thrown.syntaxErrorFile === EXPRESSION_FILE ? `${thrown.text}. ${SINGLE_EXPRESSION_HINT}` : isOutOfMemory(thrown) ? `${thrown.text}. ${OUT_OF_MEMORY_HINT}` : thrown.text, thrown.errorClass);
|
|
137
229
|
}
|
|
138
|
-
const json = vm.getString(result.value);
|
|
230
|
+
const json = vm.typeof(result.value) === "string" ? vm.getString(result.value) : "null";
|
|
139
231
|
result.value.dispose();
|
|
140
232
|
return JSON.parse(json);
|
|
141
233
|
} finally {
|
|
@@ -143,10 +235,16 @@ ${Object.keys(context).map((k) => `const ${k} = __ctx[${JSON.stringify(k)}];`).j
|
|
|
143
235
|
vm.dispose();
|
|
144
236
|
}
|
|
145
237
|
}
|
|
238
|
+
function isOutOfMemory(thrown) {
|
|
239
|
+
return /out of memory/i.test(thrown.text);
|
|
240
|
+
}
|
|
241
|
+
exports.MAX_EXPRESSION_TIMEOUT_MS = MAX_EXPRESSION_TIMEOUT_MS;
|
|
146
242
|
exports.SandboxError = SandboxError;
|
|
147
243
|
exports.THROWN_VALUE = THROWN_VALUE;
|
|
148
244
|
exports.TIMEOUT = TIMEOUT;
|
|
245
|
+
exports.clampExpressionTimeout = clampExpressionTimeout;
|
|
149
246
|
exports.errorClassOf = errorClassOf;
|
|
247
|
+
exports.expressionTimeoutText = expressionTimeoutText;
|
|
150
248
|
exports.safeEval = safeEval;
|
|
151
249
|
|
|
152
250
|
//# sourceMappingURL=sandbox.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sandbox.cjs","names":["getQuickJS"],"sources":["../../src/tools/sandbox.ts"],"sourcesContent":["import { getQuickJS, type QuickJSHandle, type QuickJSRuntime } from \"quickjs-emscripten\";\n\n/** Lazily initialized QuickJS runtime shared across evaluations. */\nlet sharedRuntime: QuickJSRuntime | undefined;\n\nasync function getRuntime(): Promise<QuickJSRuntime> {\n if (!sharedRuntime) {\n const quickjs = await getQuickJS();\n sharedRuntime = quickjs.newRuntime();\n sharedRuntime.setMemoryLimit(1024 * 1024 * 16); // 16 MB\n sharedRuntime.setMaxStackSize(1024 * 320);\n }\n return sharedRuntime;\n}\n\n/** File name the expression is evaluated under. QuickJS puts it into the syntax errors of the expression's own text. */\nconst EXPRESSION_FILE = \"transform.js\";\n\nconst SINGLE_EXPRESSION_HINT =\n \"A transform is a single expression; to run several statements, wrap them in an immediately invoked function: (() => { ...; return value; })()\";\n\n/**\n * The classes of the errors built into the JavaScript of the sandbox. Only these names are used as\n * the class of a failure: code can give an error any name, data included.\n */\nconst BUILT_IN_ERRORS: ReadonlySet<string> = new Set([\n \"Error\",\n \"AggregateError\",\n \"EvalError\",\n \"InternalError\",\n \"RangeError\",\n \"ReferenceError\",\n \"SyntaxError\",\n \"TypeError\",\n \"URIError\",\n]);\n\n/**\n * What kind of failure an error is, in words that hold nothing of the code or its data: the name of\n * a built-in error class, or `Error` for any other name.\n */\nexport function errorClassOf(name: string): string {\n return BUILT_IN_ERRORS.has(name) ? name : \"Error\";\n}\n\n/** The class of the failure of an evaluation that threw a value that is not an error. */\nexport const THROWN_VALUE = \"Thrown value\";\n\n/** The class of the failure of an evaluation that ran out of time. */\nexport const TIMEOUT = \"timeout\";\n\n/**\n * Thrown by {@link safeEval} when the evaluation fails. The message is the whole error, for the\n * agent; `errorClass` says only what kind of failure it was, for code that treats one kind apart.\n */\nexport class SandboxError extends Error {\n /** See {@link errorClassOf}, {@link THROWN_VALUE} and {@link TIMEOUT}. */\n readonly errorClass: string;\n\n constructor(message: string, errorClass: string) {\n super(message);\n this.name = \"SandboxError\";\n this.errorClass = errorClass;\n }\n}\n\n/** A value thrown inside the sandbox. */\ntype Thrown = {\n /** `Name: message` of an error, or the thrown value itself when it is not an error. */\n text: string;\n /** See {@link SandboxError.errorClass}. */\n errorClass: string;\n /** For a syntax error: the file whose text failed to parse, as QuickJS names it. */\n syntaxErrorFile?: string;\n};\n\n/**\n * Reads a thrown value from what `QuickJSContext.dump` returns for it. An error comes as a plain object\n * `{ name, message, stack }`, a syntax error also carries `fileName` and `lineNumber`: the name of the evaluated file\n * when the code did not parse, `<input>` when `JSON.parse` or `eval` failed at run time. Any other thrown value comes\n * as itself: a primitive, or an object that went through JSON.\n */\nfunction parseThrown(dumped: unknown): Thrown {\n if (typeof dumped === \"object\" && dumped !== null && \"name\" in dumped && \"message\" in dumped) {\n const { name, message } = dumped;\n if (typeof name === \"string\" && typeof message === \"string\") {\n // An error with neither a name nor a message still reads as an error.\n const label = name === \"\" ? \"Error\" : name;\n const text = message === \"\" ? label : `${label}: ${message}`;\n const errorClass = errorClassOf(name);\n if (name === \"SyntaxError\" && \"fileName\" in dumped && typeof dumped.fileName === \"string\")\n return { text, errorClass, syntaxErrorFile: dumped.fileName };\n return { text, errorClass };\n }\n }\n const errorClass = THROWN_VALUE;\n if (typeof dumped === \"string\") return { text: `${THROWN_VALUE}: ${dumped}`, errorClass };\n if (typeof dumped === \"object\" && dumped !== null) {\n // A thrown promise is dumped as its state, and the settled value can be a bigint.\n const json = JSON.stringify(dumped, (_key, value: unknown) =>\n typeof value === \"bigint\" ? `${value}n` : value,\n );\n return { text: `${THROWN_VALUE}: ${json}`, errorClass };\n }\n return { text: `${THROWN_VALUE}: ${String(dumped)}`, errorClass };\n}\n\n/**\n * Evaluate a JS expression in a QuickJS sandbox.\n * Variables from `context` are injected as globals.\n * Data is marshaled via JSON — no access to Node APIs, filesystem, or process.\n *\n * A failed evaluation throws a {@link SandboxError} whose message is the error as QuickJS reports it (`Name: message`),\n * with a hint on writing several statements when the expression does not parse. An evaluation that runs longer than\n * `timeout` milliseconds throws a {@link SandboxError} saying that it timed out.\n */\nexport async function safeEval(\n expression: string,\n context: Record<string, unknown>,\n timeout: number,\n): Promise<unknown> {\n const runtime = await getRuntime();\n\n // Set interrupt handler for timeout. QuickJS reports an interrupted evaluation as `InternalError: interrupted`,\n // so the flag is what tells a timeout from an error of the code itself.\n const deadline = Date.now() + timeout;\n let timedOut = false;\n runtime.setInterruptHandler(() => {\n if (Date.now() > deadline) timedOut = true;\n return timedOut;\n });\n const timeoutMessage = `Evaluation timed out after ${timeout} ms`;\n\n const vm = runtime.newContext();\n\n /** Reads the error of a failed evaluation and releases its handle. `undefined` when the timeout stopped the code. */\n const takeThrown = (error: QuickJSHandle): Thrown | undefined => {\n const dumped: unknown = vm.dump(error);\n // `dump` releases the handle itself when the thrown value is a promise.\n if (error.alive) error.dispose();\n return timedOut ? undefined : parseThrown(dumped);\n };\n\n try {\n // Inject context variables via JSON\n const contextJson = JSON.stringify(context);\n const setup = `const __ctx = JSON.parse(${JSON.stringify(contextJson)});\n${Object.keys(context)\n .map((k) => `const ${k} = __ctx[${JSON.stringify(k)}];`)\n .join(\"\\n\")}`;\n const setupResult = vm.evalCode(setup, \"setup.js\", { type: \"global\" });\n if (setupResult.error) {\n const thrown = takeThrown(setupResult.error);\n if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);\n throw new SandboxError(`Context setup failed: ${thrown.text}`, thrown.errorClass);\n }\n setupResult.value.dispose();\n\n // Evaluate the expression\n const result = vm.evalCode(`JSON.stringify((${expression}))`, EXPRESSION_FILE);\n if (result.error) {\n const thrown = takeThrown(result.error);\n if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);\n throw new SandboxError(\n thrown.syntaxErrorFile === EXPRESSION_FILE\n ? `${thrown.text}. ${SINGLE_EXPRESSION_HINT}`\n : thrown.text,\n thrown.errorClass,\n );\n }\n const json = vm.getString(result.value);\n result.value.dispose();\n return JSON.parse(json);\n } finally {\n runtime.setInterruptHandler(() => false);\n vm.dispose();\n }\n}\n"],"mappings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AK;GACtC,IAAI,CAAC,QAAQ,MAAM,IAAI,aAAa,gBAAgB,OAAO;GAC3D,MAAM,IAAI,aACR,OAAO,oBAAoB,kBACvB,GAAG,OAAO,KAAK,IAAI,2BACnB,OAAO,MACX,OAAO,UACT;EACF;EACA,MAAM,OAAO,GAAG,UAAU,OAAO,KAAK;EACtC,OAAO,MAAM,QAAQ;EACrB,OAAO,KAAK,MAAM,IAAI;CACxB,UAAU;EACR,QAAQ,0BAA0B,KAAK;EACvC,GAAG,QAAQ;CACb;AACF"}
|
|
1
|
+
{"version":3,"file":"sandbox.cjs","names":["getQuickJS","isPlainObject"],"sources":["../../src/tools/sandbox.ts"],"sourcesContent":["import { getQuickJS, type QuickJSHandle, type QuickJSRuntime } from \"quickjs-emscripten\";\nimport { isPlainObject } from \"@milaboratories/helpers\";\n\n/** The size of the sandbox's memory, in bytes. */\nconst MEMORY_LIMIT = 1024 * 1024 * 16;\n\n/** Lazily initialized QuickJS runtime shared across evaluations. */\nlet sharedRuntime: QuickJSRuntime | undefined;\n\nasync function getRuntime(): Promise<QuickJSRuntime> {\n if (!sharedRuntime) {\n const quickjs = await getQuickJS();\n sharedRuntime = quickjs.newRuntime();\n sharedRuntime.setMemoryLimit(MEMORY_LIMIT);\n sharedRuntime.setMaxStackSize(1024 * 320);\n }\n return sharedRuntime;\n}\n\n/** File name the expression is evaluated under. QuickJS puts it into the syntax errors of the expression's own text. */\nconst EXPRESSION_FILE = \"transform.js\";\n\nconst SINGLE_EXPRESSION_HINT =\n \"A transform is a single expression; to run several statements, wrap them in an immediately invoked function: (() => { ...; return value; })()\";\n\n/**\n * The classes of the errors built into the JavaScript of the sandbox. Only these names are used as\n * the class of a failure: code can give an error any name, data included.\n */\nconst BUILT_IN_ERRORS: ReadonlySet<string> = new Set([\n \"Error\",\n \"AggregateError\",\n \"EvalError\",\n \"InternalError\",\n \"RangeError\",\n \"ReferenceError\",\n \"SyntaxError\",\n \"TypeError\",\n \"URIError\",\n]);\n\n/**\n * What kind of failure an error is, in words that hold nothing of the code or its data: the name of\n * a built-in error class, or `Error` for any other name.\n */\nexport function errorClassOf(name: string): string {\n return BUILT_IN_ERRORS.has(name) ? name : \"Error\";\n}\n\n/** The class of the failure of an evaluation that threw a value that is not an error. */\nexport const THROWN_VALUE = \"Thrown value\";\n\n/** The class of the failure of an evaluation that ran out of time. */\nexport const TIMEOUT = \"timeout\";\n\n/**\n * Thrown by {@link safeEval} when the evaluation fails. The message is the whole error, for the\n * agent; `errorClass` says only what kind of failure it was, for code that treats one kind apart.\n */\nexport class SandboxError extends Error {\n /** See {@link errorClassOf}, {@link THROWN_VALUE} and {@link TIMEOUT}. */\n readonly errorClass: string;\n\n constructor(message: string, errorClass: string) {\n super(message);\n this.name = \"SandboxError\";\n this.errorClass = errorClass;\n }\n}\n\n/** A value thrown inside the sandbox. */\ntype Thrown = {\n /** `Name: message` of an error, or the thrown value itself when it is not an error. */\n text: string;\n /** See {@link SandboxError.errorClass}. */\n errorClass: string;\n /** For a syntax error: the file whose text failed to parse, as QuickJS names it. */\n syntaxErrorFile?: string;\n};\n\n/**\n * Reads a thrown value from what `QuickJSContext.dump` returns for it. An error comes as a plain object\n * `{ name, message, stack }`, a syntax error also carries `fileName` and `lineNumber`: the name of the evaluated file\n * when the code did not parse, `<input>` when `JSON.parse` or `eval` failed at run time. Any other thrown value comes\n * as itself: a primitive, or an object that went through JSON.\n */\nfunction parseThrown(dumped: unknown): Thrown {\n if (typeof dumped === \"object\" && dumped !== null && \"name\" in dumped && \"message\" in dumped) {\n const { name, message } = dumped;\n if (typeof name === \"string\" && typeof message === \"string\") {\n // An error with neither a name nor a message still reads as an error.\n const label = name === \"\" ? \"Error\" : name;\n const text = message === \"\" ? label : `${label}: ${message}`;\n const errorClass = errorClassOf(name);\n if (name === \"SyntaxError\" && \"fileName\" in dumped && typeof dumped.fileName === \"string\")\n return { text, errorClass, syntaxErrorFile: dumped.fileName };\n return { text, errorClass };\n }\n }\n const errorClass = THROWN_VALUE;\n if (typeof dumped === \"string\") return { text: `${THROWN_VALUE}: ${dumped}`, errorClass };\n if (typeof dumped === \"object\" && dumped !== null) {\n // A thrown promise is dumped as its state, and the settled value can be a bigint.\n const json = JSON.stringify(dumped, (_key, value: unknown) =>\n typeof value === \"bigint\" ? `${value}n` : value,\n );\n return { text: `${THROWN_VALUE}: ${json}`, errorClass };\n }\n return { text: `${THROWN_VALUE}: ${String(dumped)}`, errorClass };\n}\n\n/** The longest an expression may run, in milliseconds, whatever the caller asks for. */\nexport const MAX_EXPRESSION_TIMEOUT_MS = 10_000;\n\n/**\n * The timeout an evaluation runs under: `requested`, at most {@link MAX_EXPRESSION_TIMEOUT_MS}.\n * The sandbox runs on the server's thread, so a long evaluation holds every other call up.\n */\nexport function clampExpressionTimeout(requested: number): number {\n if (Number.isNaN(requested)) return MAX_EXPRESSION_TIMEOUT_MS;\n return Math.min(requested, MAX_EXPRESSION_TIMEOUT_MS);\n}\n\n/** The words a timeout argument is described with, for every tool that takes one. */\nexport function expressionTimeoutText(subject: string, defaultMs: number): string {\n return `Timeout in ms for ${subject} (default ${defaultMs}, at most ${MAX_EXPRESSION_TIMEOUT_MS}).`;\n}\n\nconst OUT_OF_MEMORY_HINT =\n \"The values the expression reads do not fit in the sandbox's 16 MB. Read less: name the \" +\n \"parts you need, e.g. `outputs.<key>?.value` or `data.<key>`, instead of whole values.\";\n\n/**\n * Installs the context in the sandbox as globals that read their value from the host on first\n * use, so a variable the expression does not read is never copied in. A plain-object variable is\n * a Proxy that reads one key at a time: `outputs.qc?.value` copies `qc` only, `Object.keys(outputs)`\n * the keys only, a spread or `JSON.stringify(outputs)` all of it. Values are copied as JSON.\n *\n * Writes behave as on a plain object. A value read once is kept, so a change inside it stays. The\n * first change of the record itself (a key set, added or deleted, or the record frozen) copies\n * every key into the Proxy's target, which from then on is the record. A global can be assigned.\n */\nconst CONTEXT_SETUP = `(() => {\n const value = globalThis.__plValue, keysOf = globalThis.__plKeys;\n delete globalThis.__plValue;\n delete globalThis.__plKeys;\n const parse = (json) => (json === undefined ? undefined : JSON.parse(json));\n const record = (name) => {\n const cache = new Map();\n let keys;\n // Set by the first change: the target then holds every key and answers for the record.\n let copied = false;\n const keyList = () => (keys ??= JSON.parse(keysOf(name)));\n const own = (k) => !copied && typeof k === \"string\" && keyList().includes(k);\n const read = (k) => {\n if (!cache.has(k)) cache.set(k, parse(value(name, k)));\n return cache.get(k);\n };\n const copy = (t) => {\n if (copied) return;\n for (const k of keyList())\n Object.defineProperty(t, k, {\n value: read(k), writable: true, enumerable: true, configurable: true,\n });\n copied = true;\n };\n return new Proxy({}, {\n get: (t, k, r) => (own(k) ? read(k) : Reflect.get(t, k, r)),\n has: (t, k) => own(k) || Reflect.has(t, k),\n ownKeys: (t) => (copied ? Reflect.ownKeys(t) : [...keyList()]),\n // An accessor, so that listing the keys (Object.keys) reads no value.\n getOwnPropertyDescriptor: (t, k) =>\n own(k)\n ? { get: () => read(k), enumerable: true, configurable: true }\n : Reflect.getOwnPropertyDescriptor(t, k),\n set: (t, k, v, r) => (copy(t), Reflect.set(t, k, v, r)),\n defineProperty: (t, k, d) => (copy(t), Reflect.defineProperty(t, k, d)),\n deleteProperty: (t, k) => (copy(t), Reflect.deleteProperty(t, k)),\n preventExtensions: (t) => (copy(t), Reflect.preventExtensions(t)),\n });\n };\n for (const [name, isRecord] of JSON.parse(keysOf())) {\n let done = false, v;\n Object.defineProperty(globalThis, name, {\n get: () => {\n if (!done) { v = isRecord ? record(name) : parse(value(name)); done = true; }\n return v;\n },\n set: (next) => { v = next; done = true; },\n });\n }\n})()`;\n\n/**\n * Evaluate a JS expression in a QuickJS sandbox.\n * Variables from `context` are globals read from the host when the expression reads them (see\n * {@link CONTEXT_SETUP}), so a large value it does not read costs nothing.\n * Data is marshaled via JSON — no access to Node APIs, filesystem, or process.\n *\n * A failed evaluation throws a {@link SandboxError} whose message is the error as QuickJS reports it (`Name: message`),\n * with a hint on writing several statements when the expression does not parse, and one on reading less when the\n * sandbox runs out of memory. An evaluation that runs longer than `timeout` milliseconds (at most\n * {@link MAX_EXPRESSION_TIMEOUT_MS}) throws a {@link SandboxError} saying that it timed out. An expression whose value\n * is `undefined` (or anything else JSON has no form for, such as a function) gives `null`.\n */\nexport async function safeEval(\n expression: string,\n context: Record<string, unknown>,\n timeout: number,\n): Promise<unknown> {\n const runtime = await getRuntime();\n const limit = clampExpressionTimeout(timeout);\n\n // Set interrupt handler for timeout. QuickJS reports an interrupted evaluation as `InternalError: interrupted`,\n // so the flag is what tells a timeout from an error of the code itself.\n const deadline = Date.now() + limit;\n let timedOut = false;\n runtime.setInterruptHandler(() => {\n if (Date.now() > deadline) timedOut = true;\n return timedOut;\n });\n const timeoutMessage = `Evaluation timed out after ${limit} ms`;\n\n const vm = runtime.newContext();\n\n /** Reads the error of a failed evaluation and releases its handle. `undefined` when the timeout stopped the code. */\n const takeThrown = (error: QuickJSHandle): Thrown | undefined => {\n const dumped: unknown = vm.dump(error);\n // `dump` releases the handle itself when the thrown value is a promise.\n if (error.alive) error.dispose();\n return timedOut ? undefined : parseThrown(dumped);\n };\n\n try {\n const valueOf = vm.newFunction(\"__plValue\", (nameHandle, keyHandle) => {\n const value = context[vm.getString(nameHandle)];\n const json = JSON.stringify(\n keyHandle === undefined || !isPlainObject(value)\n ? value\n : (Object.getOwnPropertyDescriptor(value, vm.getString(keyHandle))?.value as unknown),\n );\n return json === undefined ? vm.undefined : vm.newString(json);\n });\n const keysOf = vm.newFunction(\"__plKeys\", (nameHandle) => {\n const keys =\n nameHandle === undefined\n ? Object.entries(context).map(([name, value]) => [name, isPlainObject(value)])\n : Object.keys(context[vm.getString(nameHandle)] as object);\n return vm.newString(JSON.stringify(keys));\n });\n vm.setProp(vm.global, \"__plValue\", valueOf);\n vm.setProp(vm.global, \"__plKeys\", keysOf);\n valueOf.dispose();\n keysOf.dispose();\n const setupResult = vm.evalCode(CONTEXT_SETUP, \"setup.js\", { type: \"global\" });\n if (setupResult.error) {\n const thrown = takeThrown(setupResult.error);\n if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);\n throw new SandboxError(\n `Context setup failed: ${thrown.text}${isOutOfMemory(thrown) ? `. ${OUT_OF_MEMORY_HINT}` : \"\"}`,\n thrown.errorClass,\n );\n }\n setupResult.value.dispose();\n\n // Evaluate the expression. The line break lets it end in a `//` comment.\n const result = vm.evalCode(`JSON.stringify((${expression}\\n))`, EXPRESSION_FILE);\n if (result.error) {\n const thrown = takeThrown(result.error);\n if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);\n throw new SandboxError(\n thrown.syntaxErrorFile === EXPRESSION_FILE\n ? `${thrown.text}. ${SINGLE_EXPRESSION_HINT}`\n : isOutOfMemory(thrown)\n ? `${thrown.text}. ${OUT_OF_MEMORY_HINT}`\n : thrown.text,\n thrown.errorClass,\n );\n }\n // `JSON.stringify` gives `undefined` for a value JSON has no form for.\n const json = vm.typeof(result.value) === \"string\" ? vm.getString(result.value) : \"null\";\n result.value.dispose();\n return JSON.parse(json);\n } finally {\n runtime.setInterruptHandler(() => false);\n vm.dispose();\n }\n}\n\nfunction isOutOfMemory(thrown: Thrown): boolean {\n return /out of memory/i.test(thrown.text);\n}\n"],"mappings":";;;;AAIA,MAAM,eAAe;;AAGrB,IAAI;AAEJ,eAAe,aAAsC;CACnD,IAAI,CAAC,eAAe;EAElB,iBAAgB,OAAA,GADMA,mBAAAA,WAAAA,CAAW,EAAA,CACT,WAAW;EACnC,cAAc,eAAe,YAAY;EACzC,cAAc,gBAAgB,MAAU;CAC1C;CACA,OAAO;AACT;;AAGA,MAAM,kBAAkB;AAExB,MAAM,yBACJ;;;;;AAMF,MAAM,kCAAuC,IAAI,IAAI;CACnD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;AAMD,SAAgB,aAAa,MAAsB;CACjD,OAAO,gBAAgB,IAAI,IAAI,IAAI,OAAO;AAC5C;;AAGA,MAAa,eAAe;;AAG5B,MAAa,UAAU;;;;;AAMvB,IAAa,eA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QAAQ,GAAG,QAAQ,YAAY,MAAM;EACxC,QAAQ,QAAQ;EAChB,OAAO,QAAQ;EACf,MAAM,cAAc,GAAG,SAAS,eAAe,YAAY,EAAE,MAAM,SAAS,CAAC;EAC7E,IAAI,YAAY,OAAO;GACrB,MAAM,SAAS,WAAW,YAAY,KAAK;GAC3C,IAAI,CAAC,QAAQ,MAAM,IAAI,aAAa,gBAAgB,OAAO;GAC3D,MAAM,IAAI,aACR,yBAAyB,OAAO,OAAO,cAAc,MAAM,IAAI,KAAK,uBAAuB,MAC3F,OAAO,UACT;EACF;EACA,YAAY,MAAM,QAAQ;EAG1B,MAAM,SAAS,GAAG,SAAS,mBAAmB,WAAW,OAAO,eAAe;EAC/E,IAAI,OAAO,OAAO;GAChB,MAAM,SAAS,WAAW,OAAO,KAAK;GACtC,IAAI,CAAC,QAAQ,MAAM,IAAI,aAAa,gBAAgB,OAAO;GAC3D,MAAM,IAAI,aACR,OAAO,oBAAoB,kBACvB,GAAG,OAAO,KAAK,IAAI,2BACnB,cAAc,MAAM,IAClB,GAAG,OAAO,KAAK,IAAI,uBACnB,OAAO,MACb,OAAO,UACT;EACF;EAEA,MAAM,OAAO,GAAG,OAAO,OAAO,KAAK,MAAM,WAAW,GAAG,UAAU,OAAO,KAAK,IAAI;EACjF,OAAO,MAAM,QAAQ;EACrB,OAAO,KAAK,MAAM,IAAI;CACxB,UAAU;EACR,QAAQ,0BAA0B,KAAK;EACvC,GAAG,QAAQ;CACb;AACF;AAEA,SAAS,cAAc,QAAyB;CAC9C,OAAO,iBAAiB,KAAK,OAAO,IAAI;AAC1C"}
|
package/dist/tools/sandbox.js
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
+
import { isPlainObject } from "@milaboratories/helpers";
|
|
1
2
|
import { getQuickJS } from "quickjs-emscripten";
|
|
2
3
|
// src/tools/sandbox.ts
|
|
4
|
+
/** The size of the sandbox's memory, in bytes. */
|
|
5
|
+
const MEMORY_LIMIT = 16777216;
|
|
3
6
|
/** Lazily initialized QuickJS runtime shared across evaluations. */
|
|
4
7
|
let sharedRuntime;
|
|
5
8
|
async function getRuntime() {
|
|
6
9
|
if (!sharedRuntime) {
|
|
7
10
|
sharedRuntime = (await getQuickJS()).newRuntime();
|
|
8
|
-
sharedRuntime.setMemoryLimit(
|
|
11
|
+
sharedRuntime.setMemoryLimit(MEMORY_LIMIT);
|
|
9
12
|
sharedRuntime.setMaxStackSize(327680);
|
|
10
13
|
}
|
|
11
14
|
return sharedRuntime;
|
|
@@ -93,24 +96,103 @@ function parseThrown(dumped) {
|
|
|
93
96
|
errorClass
|
|
94
97
|
};
|
|
95
98
|
}
|
|
99
|
+
/** The longest an expression may run, in milliseconds, whatever the caller asks for. */
|
|
100
|
+
const MAX_EXPRESSION_TIMEOUT_MS = 1e4;
|
|
101
|
+
/**
|
|
102
|
+
* The timeout an evaluation runs under: `requested`, at most {@link MAX_EXPRESSION_TIMEOUT_MS}.
|
|
103
|
+
* The sandbox runs on the server's thread, so a long evaluation holds every other call up.
|
|
104
|
+
*/
|
|
105
|
+
function clampExpressionTimeout(requested) {
|
|
106
|
+
if (Number.isNaN(requested)) return MAX_EXPRESSION_TIMEOUT_MS;
|
|
107
|
+
return Math.min(requested, MAX_EXPRESSION_TIMEOUT_MS);
|
|
108
|
+
}
|
|
109
|
+
/** The words a timeout argument is described with, for every tool that takes one. */
|
|
110
|
+
function expressionTimeoutText(subject, defaultMs) {
|
|
111
|
+
return `Timeout in ms for ${subject} (default ${defaultMs}, at most ${MAX_EXPRESSION_TIMEOUT_MS}).`;
|
|
112
|
+
}
|
|
113
|
+
const OUT_OF_MEMORY_HINT = "The values the expression reads do not fit in the sandbox's 16 MB. Read less: name the parts you need, e.g. `outputs.<key>?.value` or `data.<key>`, instead of whole values.";
|
|
114
|
+
/**
|
|
115
|
+
* Installs the context in the sandbox as globals that read their value from the host on first
|
|
116
|
+
* use, so a variable the expression does not read is never copied in. A plain-object variable is
|
|
117
|
+
* a Proxy that reads one key at a time: `outputs.qc?.value` copies `qc` only, `Object.keys(outputs)`
|
|
118
|
+
* the keys only, a spread or `JSON.stringify(outputs)` all of it. Values are copied as JSON.
|
|
119
|
+
*
|
|
120
|
+
* Writes behave as on a plain object. A value read once is kept, so a change inside it stays. The
|
|
121
|
+
* first change of the record itself (a key set, added or deleted, or the record frozen) copies
|
|
122
|
+
* every key into the Proxy's target, which from then on is the record. A global can be assigned.
|
|
123
|
+
*/
|
|
124
|
+
const CONTEXT_SETUP = `(() => {
|
|
125
|
+
const value = globalThis.__plValue, keysOf = globalThis.__plKeys;
|
|
126
|
+
delete globalThis.__plValue;
|
|
127
|
+
delete globalThis.__plKeys;
|
|
128
|
+
const parse = (json) => (json === undefined ? undefined : JSON.parse(json));
|
|
129
|
+
const record = (name) => {
|
|
130
|
+
const cache = new Map();
|
|
131
|
+
let keys;
|
|
132
|
+
// Set by the first change: the target then holds every key and answers for the record.
|
|
133
|
+
let copied = false;
|
|
134
|
+
const keyList = () => (keys ??= JSON.parse(keysOf(name)));
|
|
135
|
+
const own = (k) => !copied && typeof k === "string" && keyList().includes(k);
|
|
136
|
+
const read = (k) => {
|
|
137
|
+
if (!cache.has(k)) cache.set(k, parse(value(name, k)));
|
|
138
|
+
return cache.get(k);
|
|
139
|
+
};
|
|
140
|
+
const copy = (t) => {
|
|
141
|
+
if (copied) return;
|
|
142
|
+
for (const k of keyList())
|
|
143
|
+
Object.defineProperty(t, k, {
|
|
144
|
+
value: read(k), writable: true, enumerable: true, configurable: true,
|
|
145
|
+
});
|
|
146
|
+
copied = true;
|
|
147
|
+
};
|
|
148
|
+
return new Proxy({}, {
|
|
149
|
+
get: (t, k, r) => (own(k) ? read(k) : Reflect.get(t, k, r)),
|
|
150
|
+
has: (t, k) => own(k) || Reflect.has(t, k),
|
|
151
|
+
ownKeys: (t) => (copied ? Reflect.ownKeys(t) : [...keyList()]),
|
|
152
|
+
// An accessor, so that listing the keys (Object.keys) reads no value.
|
|
153
|
+
getOwnPropertyDescriptor: (t, k) =>
|
|
154
|
+
own(k)
|
|
155
|
+
? { get: () => read(k), enumerable: true, configurable: true }
|
|
156
|
+
: Reflect.getOwnPropertyDescriptor(t, k),
|
|
157
|
+
set: (t, k, v, r) => (copy(t), Reflect.set(t, k, v, r)),
|
|
158
|
+
defineProperty: (t, k, d) => (copy(t), Reflect.defineProperty(t, k, d)),
|
|
159
|
+
deleteProperty: (t, k) => (copy(t), Reflect.deleteProperty(t, k)),
|
|
160
|
+
preventExtensions: (t) => (copy(t), Reflect.preventExtensions(t)),
|
|
161
|
+
});
|
|
162
|
+
};
|
|
163
|
+
for (const [name, isRecord] of JSON.parse(keysOf())) {
|
|
164
|
+
let done = false, v;
|
|
165
|
+
Object.defineProperty(globalThis, name, {
|
|
166
|
+
get: () => {
|
|
167
|
+
if (!done) { v = isRecord ? record(name) : parse(value(name)); done = true; }
|
|
168
|
+
return v;
|
|
169
|
+
},
|
|
170
|
+
set: (next) => { v = next; done = true; },
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
})()`;
|
|
96
174
|
/**
|
|
97
175
|
* Evaluate a JS expression in a QuickJS sandbox.
|
|
98
|
-
* Variables from `context` are
|
|
176
|
+
* Variables from `context` are globals read from the host when the expression reads them (see
|
|
177
|
+
* {@link CONTEXT_SETUP}), so a large value it does not read costs nothing.
|
|
99
178
|
* Data is marshaled via JSON — no access to Node APIs, filesystem, or process.
|
|
100
179
|
*
|
|
101
180
|
* A failed evaluation throws a {@link SandboxError} whose message is the error as QuickJS reports it (`Name: message`),
|
|
102
|
-
* with a hint on writing several statements when the expression does not parse
|
|
103
|
-
*
|
|
181
|
+
* with a hint on writing several statements when the expression does not parse, and one on reading less when the
|
|
182
|
+
* sandbox runs out of memory. An evaluation that runs longer than `timeout` milliseconds (at most
|
|
183
|
+
* {@link MAX_EXPRESSION_TIMEOUT_MS}) throws a {@link SandboxError} saying that it timed out. An expression whose value
|
|
184
|
+
* is `undefined` (or anything else JSON has no form for, such as a function) gives `null`.
|
|
104
185
|
*/
|
|
105
186
|
async function safeEval(expression, context, timeout) {
|
|
106
187
|
const runtime = await getRuntime();
|
|
107
|
-
const
|
|
188
|
+
const limit = clampExpressionTimeout(timeout);
|
|
189
|
+
const deadline = Date.now() + limit;
|
|
108
190
|
let timedOut = false;
|
|
109
191
|
runtime.setInterruptHandler(() => {
|
|
110
192
|
if (Date.now() > deadline) timedOut = true;
|
|
111
193
|
return timedOut;
|
|
112
194
|
});
|
|
113
|
-
const timeoutMessage = `Evaluation timed out after ${
|
|
195
|
+
const timeoutMessage = `Evaluation timed out after ${limit} ms`;
|
|
114
196
|
const vm = runtime.newContext();
|
|
115
197
|
/** Reads the error of a failed evaluation and releases its handle. `undefined` when the timeout stopped the code. */
|
|
116
198
|
const takeThrown = (error) => {
|
|
@@ -119,23 +201,33 @@ async function safeEval(expression, context, timeout) {
|
|
|
119
201
|
return timedOut ? void 0 : parseThrown(dumped);
|
|
120
202
|
};
|
|
121
203
|
try {
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
204
|
+
const valueOf = vm.newFunction("__plValue", (nameHandle, keyHandle) => {
|
|
205
|
+
const value = context[vm.getString(nameHandle)];
|
|
206
|
+
const json = JSON.stringify(keyHandle === void 0 || !isPlainObject(value) ? value : Object.getOwnPropertyDescriptor(value, vm.getString(keyHandle))?.value);
|
|
207
|
+
return json === void 0 ? vm.undefined : vm.newString(json);
|
|
208
|
+
});
|
|
209
|
+
const keysOf = vm.newFunction("__plKeys", (nameHandle) => {
|
|
210
|
+
const keys = nameHandle === void 0 ? Object.entries(context).map(([name, value]) => [name, isPlainObject(value)]) : Object.keys(context[vm.getString(nameHandle)]);
|
|
211
|
+
return vm.newString(JSON.stringify(keys));
|
|
212
|
+
});
|
|
213
|
+
vm.setProp(vm.global, "__plValue", valueOf);
|
|
214
|
+
vm.setProp(vm.global, "__plKeys", keysOf);
|
|
215
|
+
valueOf.dispose();
|
|
216
|
+
keysOf.dispose();
|
|
217
|
+
const setupResult = vm.evalCode(CONTEXT_SETUP, "setup.js", { type: "global" });
|
|
126
218
|
if (setupResult.error) {
|
|
127
219
|
const thrown = takeThrown(setupResult.error);
|
|
128
220
|
if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);
|
|
129
|
-
throw new SandboxError(`Context setup failed: ${thrown.text}`, thrown.errorClass);
|
|
221
|
+
throw new SandboxError(`Context setup failed: ${thrown.text}${isOutOfMemory(thrown) ? `. ${OUT_OF_MEMORY_HINT}` : ""}`, thrown.errorClass);
|
|
130
222
|
}
|
|
131
223
|
setupResult.value.dispose();
|
|
132
|
-
const result = vm.evalCode(`JSON.stringify((${expression}))`, EXPRESSION_FILE);
|
|
224
|
+
const result = vm.evalCode(`JSON.stringify((${expression}\n))`, EXPRESSION_FILE);
|
|
133
225
|
if (result.error) {
|
|
134
226
|
const thrown = takeThrown(result.error);
|
|
135
227
|
if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);
|
|
136
|
-
throw new SandboxError(thrown.syntaxErrorFile === EXPRESSION_FILE ? `${thrown.text}. ${SINGLE_EXPRESSION_HINT}` : thrown.text, thrown.errorClass);
|
|
228
|
+
throw new SandboxError(thrown.syntaxErrorFile === EXPRESSION_FILE ? `${thrown.text}. ${SINGLE_EXPRESSION_HINT}` : isOutOfMemory(thrown) ? `${thrown.text}. ${OUT_OF_MEMORY_HINT}` : thrown.text, thrown.errorClass);
|
|
137
229
|
}
|
|
138
|
-
const json = vm.getString(result.value);
|
|
230
|
+
const json = vm.typeof(result.value) === "string" ? vm.getString(result.value) : "null";
|
|
139
231
|
result.value.dispose();
|
|
140
232
|
return JSON.parse(json);
|
|
141
233
|
} finally {
|
|
@@ -143,6 +235,9 @@ ${Object.keys(context).map((k) => `const ${k} = __ctx[${JSON.stringify(k)}];`).j
|
|
|
143
235
|
vm.dispose();
|
|
144
236
|
}
|
|
145
237
|
}
|
|
146
|
-
|
|
238
|
+
function isOutOfMemory(thrown) {
|
|
239
|
+
return /out of memory/i.test(thrown.text);
|
|
240
|
+
}
|
|
241
|
+
export { MAX_EXPRESSION_TIMEOUT_MS, SandboxError, THROWN_VALUE, TIMEOUT, clampExpressionTimeout, errorClassOf, expressionTimeoutText, safeEval };
|
|
147
242
|
|
|
148
243
|
//# sourceMappingURL=sandbox.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sandbox.js","names":[],"sources":["../../src/tools/sandbox.ts"],"sourcesContent":["import { getQuickJS, type QuickJSHandle, type QuickJSRuntime } from \"quickjs-emscripten\";\n\n/** Lazily initialized QuickJS runtime shared across evaluations. */\nlet sharedRuntime: QuickJSRuntime | undefined;\n\nasync function getRuntime(): Promise<QuickJSRuntime> {\n if (!sharedRuntime) {\n const quickjs = await getQuickJS();\n sharedRuntime = quickjs.newRuntime();\n sharedRuntime.setMemoryLimit(1024 * 1024 * 16); // 16 MB\n sharedRuntime.setMaxStackSize(1024 * 320);\n }\n return sharedRuntime;\n}\n\n/** File name the expression is evaluated under. QuickJS puts it into the syntax errors of the expression's own text. */\nconst EXPRESSION_FILE = \"transform.js\";\n\nconst SINGLE_EXPRESSION_HINT =\n \"A transform is a single expression; to run several statements, wrap them in an immediately invoked function: (() => { ...; return value; })()\";\n\n/**\n * The classes of the errors built into the JavaScript of the sandbox. Only these names are used as\n * the class of a failure: code can give an error any name, data included.\n */\nconst BUILT_IN_ERRORS: ReadonlySet<string> = new Set([\n \"Error\",\n \"AggregateError\",\n \"EvalError\",\n \"InternalError\",\n \"RangeError\",\n \"ReferenceError\",\n \"SyntaxError\",\n \"TypeError\",\n \"URIError\",\n]);\n\n/**\n * What kind of failure an error is, in words that hold nothing of the code or its data: the name of\n * a built-in error class, or `Error` for any other name.\n */\nexport function errorClassOf(name: string): string {\n return BUILT_IN_ERRORS.has(name) ? name : \"Error\";\n}\n\n/** The class of the failure of an evaluation that threw a value that is not an error. */\nexport const THROWN_VALUE = \"Thrown value\";\n\n/** The class of the failure of an evaluation that ran out of time. */\nexport const TIMEOUT = \"timeout\";\n\n/**\n * Thrown by {@link safeEval} when the evaluation fails. The message is the whole error, for the\n * agent; `errorClass` says only what kind of failure it was, for code that treats one kind apart.\n */\nexport class SandboxError extends Error {\n /** See {@link errorClassOf}, {@link THROWN_VALUE} and {@link TIMEOUT}. */\n readonly errorClass: string;\n\n constructor(message: string, errorClass: string) {\n super(message);\n this.name = \"SandboxError\";\n this.errorClass = errorClass;\n }\n}\n\n/** A value thrown inside the sandbox. */\ntype Thrown = {\n /** `Name: message` of an error, or the thrown value itself when it is not an error. */\n text: string;\n /** See {@link SandboxError.errorClass}. */\n errorClass: string;\n /** For a syntax error: the file whose text failed to parse, as QuickJS names it. */\n syntaxErrorFile?: string;\n};\n\n/**\n * Reads a thrown value from what `QuickJSContext.dump` returns for it. An error comes as a plain object\n * `{ name, message, stack }`, a syntax error also carries `fileName` and `lineNumber`: the name of the evaluated file\n * when the code did not parse, `<input>` when `JSON.parse` or `eval` failed at run time. Any other thrown value comes\n * as itself: a primitive, or an object that went through JSON.\n */\nfunction parseThrown(dumped: unknown): Thrown {\n if (typeof dumped === \"object\" && dumped !== null && \"name\" in dumped && \"message\" in dumped) {\n const { name, message } = dumped;\n if (typeof name === \"string\" && typeof message === \"string\") {\n // An error with neither a name nor a message still reads as an error.\n const label = name === \"\" ? \"Error\" : name;\n const text = message === \"\" ? label : `${label}: ${message}`;\n const errorClass = errorClassOf(name);\n if (name === \"SyntaxError\" && \"fileName\" in dumped && typeof dumped.fileName === \"string\")\n return { text, errorClass, syntaxErrorFile: dumped.fileName };\n return { text, errorClass };\n }\n }\n const errorClass = THROWN_VALUE;\n if (typeof dumped === \"string\") return { text: `${THROWN_VALUE}: ${dumped}`, errorClass };\n if (typeof dumped === \"object\" && dumped !== null) {\n // A thrown promise is dumped as its state, and the settled value can be a bigint.\n const json = JSON.stringify(dumped, (_key, value: unknown) =>\n typeof value === \"bigint\" ? `${value}n` : value,\n );\n return { text: `${THROWN_VALUE}: ${json}`, errorClass };\n }\n return { text: `${THROWN_VALUE}: ${String(dumped)}`, errorClass };\n}\n\n/**\n * Evaluate a JS expression in a QuickJS sandbox.\n * Variables from `context` are injected as globals.\n * Data is marshaled via JSON — no access to Node APIs, filesystem, or process.\n *\n * A failed evaluation throws a {@link SandboxError} whose message is the error as QuickJS reports it (`Name: message`),\n * with a hint on writing several statements when the expression does not parse. An evaluation that runs longer than\n * `timeout` milliseconds throws a {@link SandboxError} saying that it timed out.\n */\nexport async function safeEval(\n expression: string,\n context: Record<string, unknown>,\n timeout: number,\n): Promise<unknown> {\n const runtime = await getRuntime();\n\n // Set interrupt handler for timeout. QuickJS reports an interrupted evaluation as `InternalError: interrupted`,\n // so the flag is what tells a timeout from an error of the code itself.\n const deadline = Date.now() + timeout;\n let timedOut = false;\n runtime.setInterruptHandler(() => {\n if (Date.now() > deadline) timedOut = true;\n return timedOut;\n });\n const timeoutMessage = `Evaluation timed out after ${timeout} ms`;\n\n const vm = runtime.newContext();\n\n /** Reads the error of a failed evaluation and releases its handle. `undefined` when the timeout stopped the code. */\n const takeThrown = (error: QuickJSHandle): Thrown | undefined => {\n const dumped: unknown = vm.dump(error);\n // `dump` releases the handle itself when the thrown value is a promise.\n if (error.alive) error.dispose();\n return timedOut ? undefined : parseThrown(dumped);\n };\n\n try {\n // Inject context variables via JSON\n const contextJson = JSON.stringify(context);\n const setup = `const __ctx = JSON.parse(${JSON.stringify(contextJson)});\n${Object.keys(context)\n .map((k) => `const ${k} = __ctx[${JSON.stringify(k)}];`)\n .join(\"\\n\")}`;\n const setupResult = vm.evalCode(setup, \"setup.js\", { type: \"global\" });\n if (setupResult.error) {\n const thrown = takeThrown(setupResult.error);\n if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);\n throw new SandboxError(`Context setup failed: ${thrown.text}`, thrown.errorClass);\n }\n setupResult.value.dispose();\n\n // Evaluate the expression\n const result = vm.evalCode(`JSON.stringify((${expression}))`, EXPRESSION_FILE);\n if (result.error) {\n const thrown = takeThrown(result.error);\n if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);\n throw new SandboxError(\n thrown.syntaxErrorFile === EXPRESSION_FILE\n ? `${thrown.text}. ${SINGLE_EXPRESSION_HINT}`\n : thrown.text,\n thrown.errorClass,\n );\n }\n const json = vm.getString(result.value);\n result.value.dispose();\n return JSON.parse(json);\n } finally {\n runtime.setInterruptHandler(() => false);\n vm.dispose();\n }\n}\n"],"mappings":";;;AAGA,IAAI;AAEJ,eAAe,aAAsC;CACnD,IAAI,CAAC,eAAe;EAElB,iBAAgB,MADM,WAAW,EAAA,CACT,WAAW;EACnC,cAAc,eAAe,QAAgB;EAC7C,cAAc,gBAAgB,MAAU;CAC1C;CACA,OAAO;AACT;;AAGA,MAAM,kBAAkB;AAExB,MAAM,yBACJ;;;;;AAMF,MAAM,kCAAuC,IAAI,IAAI;CACnD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;AAMD,SAAgB,aAAa,MAAsB;CACjD,OAAO,gBAAgB,IAAI,IAAI,IAAI,OAAO;AAC5C;;AAGA,MAAa,eAAe;;AAG5B,MAAa,UAAU;;;;;AAMvB,IAAa,eAAb,cAAkC,MAAM;;CAEtC;CAEA,YAAY,SAAiB,YAAoB;EAC/C,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,aAAa;CACpB;AACF;;;;;;;AAkBA,SAAS,YAAY,QAAyB;CAC5C,IAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,UAAU,UAAU,aAAa,QAAQ;EAC5F,MAAM,EAAE,MAAM,YAAY;EAC1B,IAAI,OAAO,SAAS,YAAY,OAAO,YAAY,UAAU;GAE3D,MAAM,QAAQ,SAAS,KAAK,UAAU;GACtC,MAAM,OAAO,YAAY,KAAK,QAAQ,GAAG,MAAM,IAAI;GACnD,MAAM,aAAa,aAAa,IAAI;GACpC,IAAI,SAAS,iBAAiB,cAAc,UAAU,OAAO,OAAO,aAAa,UAC/E,OAAO;IAAE;IAAM;IAAY,iBAAiB,OAAO;G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aAAa,gBAAgB,OAAO;GAC3D,MAAM,IAAI,aAAa,yBAAyB,OAAO,QAAQ,OAAO,UAAU;EAClF;EACA,YAAY,MAAM,QAAQ;EAG1B,MAAM,SAAS,GAAG,SAAS,mBAAmB,WAAW,KAAK,eAAe;EAC7E,IAAI,OAAO,OAAO;GAChB,MAAM,SAAS,WAAW,OAAO,KAAK;GACtC,IAAI,CAAC,QAAQ,MAAM,IAAI,aAAa,gBAAgB,OAAO;GAC3D,MAAM,IAAI,aACR,OAAO,oBAAoB,kBACvB,GAAG,OAAO,KAAK,IAAI,2BACnB,OAAO,MACX,OAAO,UACT;EACF;EACA,MAAM,OAAO,GAAG,UAAU,OAAO,KAAK;EACtC,OAAO,MAAM,QAAQ;EACrB,OAAO,KAAK,MAAM,IAAI;CACxB,UAAU;EACR,QAAQ,0BAA0B,KAAK;EACvC,GAAG,QAAQ;CACb;AACF"}
|
|
1
|
+
{"version":3,"file":"sandbox.js","names":[],"sources":["../../src/tools/sandbox.ts"],"sourcesContent":["import { getQuickJS, type QuickJSHandle, type QuickJSRuntime } from \"quickjs-emscripten\";\nimport { isPlainObject } from \"@milaboratories/helpers\";\n\n/** The size of the sandbox's memory, in bytes. */\nconst MEMORY_LIMIT = 1024 * 1024 * 16;\n\n/** Lazily initialized QuickJS runtime shared across evaluations. */\nlet sharedRuntime: QuickJSRuntime | undefined;\n\nasync function getRuntime(): Promise<QuickJSRuntime> {\n if (!sharedRuntime) {\n const quickjs = await getQuickJS();\n sharedRuntime = quickjs.newRuntime();\n sharedRuntime.setMemoryLimit(MEMORY_LIMIT);\n sharedRuntime.setMaxStackSize(1024 * 320);\n }\n return sharedRuntime;\n}\n\n/** File name the expression is evaluated under. QuickJS puts it into the syntax errors of the expression's own text. */\nconst EXPRESSION_FILE = \"transform.js\";\n\nconst SINGLE_EXPRESSION_HINT =\n \"A transform is a single expression; to run several statements, wrap them in an immediately invoked function: (() => { ...; return value; })()\";\n\n/**\n * The classes of the errors built into the JavaScript of the sandbox. Only these names are used as\n * the class of a failure: code can give an error any name, data included.\n */\nconst BUILT_IN_ERRORS: ReadonlySet<string> = new Set([\n \"Error\",\n \"AggregateError\",\n \"EvalError\",\n \"InternalError\",\n \"RangeError\",\n \"ReferenceError\",\n \"SyntaxError\",\n \"TypeError\",\n \"URIError\",\n]);\n\n/**\n * What kind of failure an error is, in words that hold nothing of the code or its data: the name of\n * a built-in error class, or `Error` for any other name.\n */\nexport function errorClassOf(name: string): string {\n return BUILT_IN_ERRORS.has(name) ? name : \"Error\";\n}\n\n/** The class of the failure of an evaluation that threw a value that is not an error. */\nexport const THROWN_VALUE = \"Thrown value\";\n\n/** The class of the failure of an evaluation that ran out of time. */\nexport const TIMEOUT = \"timeout\";\n\n/**\n * Thrown by {@link safeEval} when the evaluation fails. The message is the whole error, for the\n * agent; `errorClass` says only what kind of failure it was, for code that treats one kind apart.\n */\nexport class SandboxError extends Error {\n /** See {@link errorClassOf}, {@link THROWN_VALUE} and {@link TIMEOUT}. */\n readonly errorClass: string;\n\n constructor(message: string, errorClass: string) {\n super(message);\n this.name = \"SandboxError\";\n this.errorClass = errorClass;\n }\n}\n\n/** A value thrown inside the sandbox. */\ntype Thrown = {\n /** `Name: message` of an error, or the thrown value itself when it is not an error. */\n text: string;\n /** See {@link SandboxError.errorClass}. */\n errorClass: string;\n /** For a syntax error: the file whose text failed to parse, as QuickJS names it. */\n syntaxErrorFile?: string;\n};\n\n/**\n * Reads a thrown value from what `QuickJSContext.dump` returns for it. An error comes as a plain object\n * `{ name, message, stack }`, a syntax error also carries `fileName` and `lineNumber`: the name of the evaluated file\n * when the code did not parse, `<input>` when `JSON.parse` or `eval` failed at run time. Any other thrown value comes\n * as itself: a primitive, or an object that went through JSON.\n */\nfunction parseThrown(dumped: unknown): Thrown {\n if (typeof dumped === \"object\" && dumped !== null && \"name\" in dumped && \"message\" in dumped) {\n const { name, message } = dumped;\n if (typeof name === \"string\" && typeof message === \"string\") {\n // An error with neither a name nor a message still reads as an error.\n const label = name === \"\" ? \"Error\" : name;\n const text = message === \"\" ? label : `${label}: ${message}`;\n const errorClass = errorClassOf(name);\n if (name === \"SyntaxError\" && \"fileName\" in dumped && typeof dumped.fileName === \"string\")\n return { text, errorClass, syntaxErrorFile: dumped.fileName };\n return { text, errorClass };\n }\n }\n const errorClass = THROWN_VALUE;\n if (typeof dumped === \"string\") return { text: `${THROWN_VALUE}: ${dumped}`, errorClass };\n if (typeof dumped === \"object\" && dumped !== null) {\n // A thrown promise is dumped as its state, and the settled value can be a bigint.\n const json = JSON.stringify(dumped, (_key, value: unknown) =>\n typeof value === \"bigint\" ? `${value}n` : value,\n );\n return { text: `${THROWN_VALUE}: ${json}`, errorClass };\n }\n return { text: `${THROWN_VALUE}: ${String(dumped)}`, errorClass };\n}\n\n/** The longest an expression may run, in milliseconds, whatever the caller asks for. */\nexport const MAX_EXPRESSION_TIMEOUT_MS = 10_000;\n\n/**\n * The timeout an evaluation runs under: `requested`, at most {@link MAX_EXPRESSION_TIMEOUT_MS}.\n * The sandbox runs on the server's thread, so a long evaluation holds every other call up.\n */\nexport function clampExpressionTimeout(requested: number): number {\n if (Number.isNaN(requested)) return MAX_EXPRESSION_TIMEOUT_MS;\n return Math.min(requested, MAX_EXPRESSION_TIMEOUT_MS);\n}\n\n/** The words a timeout argument is described with, for every tool that takes one. */\nexport function expressionTimeoutText(subject: string, defaultMs: number): string {\n return `Timeout in ms for ${subject} (default ${defaultMs}, at most ${MAX_EXPRESSION_TIMEOUT_MS}).`;\n}\n\nconst OUT_OF_MEMORY_HINT =\n \"The values the expression reads do not fit in the sandbox's 16 MB. Read less: name the \" +\n \"parts you need, e.g. `outputs.<key>?.value` or `data.<key>`, instead of whole values.\";\n\n/**\n * Installs the context in the sandbox as globals that read their value from the host on first\n * use, so a variable the expression does not read is never copied in. A plain-object variable is\n * a Proxy that reads one key at a time: `outputs.qc?.value` copies `qc` only, `Object.keys(outputs)`\n * the keys only, a spread or `JSON.stringify(outputs)` all of it. Values are copied as JSON.\n *\n * Writes behave as on a plain object. A value read once is kept, so a change inside it stays. The\n * first change of the record itself (a key set, added or deleted, or the record frozen) copies\n * every key into the Proxy's target, which from then on is the record. A global can be assigned.\n */\nconst CONTEXT_SETUP = `(() => {\n const value = globalThis.__plValue, keysOf = globalThis.__plKeys;\n delete globalThis.__plValue;\n delete globalThis.__plKeys;\n const parse = (json) => (json === undefined ? undefined : JSON.parse(json));\n const record = (name) => {\n const cache = new Map();\n let keys;\n // Set by the first change: the target then holds every key and answers for the record.\n let copied = false;\n const keyList = () => (keys ??= JSON.parse(keysOf(name)));\n const own = (k) => !copied && typeof k === \"string\" && keyList().includes(k);\n const read = (k) => {\n if (!cache.has(k)) cache.set(k, parse(value(name, k)));\n return cache.get(k);\n };\n const copy = (t) => {\n if (copied) return;\n for (const k of keyList())\n Object.defineProperty(t, k, {\n value: read(k), writable: true, enumerable: true, configurable: true,\n });\n copied = true;\n };\n return new Proxy({}, {\n get: (t, k, r) => (own(k) ? read(k) : Reflect.get(t, k, r)),\n has: (t, k) => own(k) || Reflect.has(t, k),\n ownKeys: (t) => (copied ? Reflect.ownKeys(t) : [...keyList()]),\n // An accessor, so that listing the keys (Object.keys) reads no value.\n getOwnPropertyDescriptor: (t, k) =>\n own(k)\n ? { get: () => read(k), enumerable: true, configurable: true }\n : Reflect.getOwnPropertyDescriptor(t, k),\n set: (t, k, v, r) => (copy(t), Reflect.set(t, k, v, r)),\n defineProperty: (t, k, d) => (copy(t), Reflect.defineProperty(t, k, d)),\n deleteProperty: (t, k) => (copy(t), Reflect.deleteProperty(t, k)),\n preventExtensions: (t) => (copy(t), Reflect.preventExtensions(t)),\n });\n };\n for (const [name, isRecord] of JSON.parse(keysOf())) {\n let done = false, v;\n Object.defineProperty(globalThis, name, {\n get: () => {\n if (!done) { v = isRecord ? record(name) : parse(value(name)); done = true; }\n return v;\n },\n set: (next) => { v = next; done = true; },\n });\n }\n})()`;\n\n/**\n * Evaluate a JS expression in a QuickJS sandbox.\n * Variables from `context` are globals read from the host when the expression reads them (see\n * {@link CONTEXT_SETUP}), so a large value it does not read costs nothing.\n * Data is marshaled via JSON — no access to Node APIs, filesystem, or process.\n *\n * A failed evaluation throws a {@link SandboxError} whose message is the error as QuickJS reports it (`Name: message`),\n * with a hint on writing several statements when the expression does not parse, and one on reading less when the\n * sandbox runs out of memory. An evaluation that runs longer than `timeout` milliseconds (at most\n * {@link MAX_EXPRESSION_TIMEOUT_MS}) throws a {@link SandboxError} saying that it timed out. An expression whose value\n * is `undefined` (or anything else JSON has no form for, such as a function) gives `null`.\n */\nexport async function safeEval(\n expression: string,\n context: Record<string, unknown>,\n timeout: number,\n): Promise<unknown> {\n const runtime = await getRuntime();\n const limit = clampExpressionTimeout(timeout);\n\n // Set interrupt handler for timeout. QuickJS reports an interrupted evaluation as `InternalError: interrupted`,\n // so the flag is what tells a timeout from an error of the code itself.\n const deadline = Date.now() + limit;\n let timedOut = false;\n runtime.setInterruptHandler(() => {\n if (Date.now() > deadline) timedOut = true;\n return timedOut;\n });\n const timeoutMessage = `Evaluation timed out after ${limit} ms`;\n\n const vm = runtime.newContext();\n\n /** Reads the error of a failed evaluation and releases its handle. `undefined` when the timeout stopped the code. */\n const takeThrown = (error: QuickJSHandle): Thrown | undefined => {\n const dumped: unknown = vm.dump(error);\n // `dump` releases the handle itself when the thrown value is a promise.\n if (error.alive) error.dispose();\n return timedOut ? undefined : parseThrown(dumped);\n };\n\n try {\n const valueOf = vm.newFunction(\"__plValue\", (nameHandle, keyHandle) => {\n const value = context[vm.getString(nameHandle)];\n const json = JSON.stringify(\n keyHandle === undefined || !isPlainObject(value)\n ? value\n : (Object.getOwnPropertyDescriptor(value, vm.getString(keyHandle))?.value as unknown),\n );\n return json === undefined ? vm.undefined : vm.newString(json);\n });\n const keysOf = vm.newFunction(\"__plKeys\", (nameHandle) => {\n const keys =\n nameHandle === undefined\n ? Object.entries(context).map(([name, value]) => [name, isPlainObject(value)])\n : Object.keys(context[vm.getString(nameHandle)] as object);\n return vm.newString(JSON.stringify(keys));\n });\n vm.setProp(vm.global, \"__plValue\", valueOf);\n vm.setProp(vm.global, \"__plKeys\", keysOf);\n valueOf.dispose();\n keysOf.dispose();\n const setupResult = vm.evalCode(CONTEXT_SETUP, \"setup.js\", { type: \"global\" });\n if (setupResult.error) {\n const thrown = takeThrown(setupResult.error);\n if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);\n throw new SandboxError(\n `Context setup failed: ${thrown.text}${isOutOfMemory(thrown) ? `. ${OUT_OF_MEMORY_HINT}` : \"\"}`,\n thrown.errorClass,\n );\n }\n setupResult.value.dispose();\n\n // Evaluate the expression. The line break lets it end in a `//` comment.\n const result = vm.evalCode(`JSON.stringify((${expression}\\n))`, EXPRESSION_FILE);\n if (result.error) {\n const thrown = takeThrown(result.error);\n if (!thrown) throw new SandboxError(timeoutMessage, TIMEOUT);\n throw new SandboxError(\n thrown.syntaxErrorFile === EXPRESSION_FILE\n ? `${thrown.text}. ${SINGLE_EXPRESSION_HINT}`\n : isOutOfMemory(thrown)\n ? `${thrown.text}. ${OUT_OF_MEMORY_HINT}`\n : thrown.text,\n thrown.errorClass,\n );\n }\n // `JSON.stringify` gives `undefined` for a value JSON has no form for.\n const json = vm.typeof(result.value) === \"string\" ? vm.getString(result.value) : \"null\";\n result.value.dispose();\n return JSON.parse(json);\n } finally {\n runtime.setInterruptHandler(() => false);\n vm.dispose();\n }\n}\n\nfunction isOutOfMemory(thrown: Thrown): boolean {\n return /out of memory/i.test(thrown.text);\n}\n"],"mappings":";;;;AAIA,MAAM,eAAe;;AAGrB,IAAI;AAEJ,eAAe,aAAsC;CACnD,IAAI,CAAC,eAAe;EAElB,iBAAgB,MADM,WAAW,EAAA,CACT,WAAW;EACnC,cAAc,eAAe,YAAY;EACzC,cAAc,gBAAgB,MAAU;CAC1C;CACA,OAAO;AACT;;AAGA,MAAM,kBAAkB;AAExB,MAAM,yBACJ;;;;;AAMF,MAAM,kCAAuC,IAAI,IAAI;CACnD;CACA;CACA;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ds use in their params. A kind's `contract.d.ts` imports
|
|
4
|
+
* them from `@platforma-sdk/*` and `@milaboratories/*`, which an agent cannot open; this is what
|
|
5
|
+
* stands for each. `get_block_contract` returns all of them.
|
|
6
|
+
*/
|
|
7
|
+
const SDK_TYPES = {
|
|
8
|
+
PlRef: "/** Object form of a leaf GlobalPObjectId; copy `ref` from a block's option outputs (get_block_outputs) or from list_pool_columns. */\ntype PlRef = { __isRef: true; blockId: string; name: string; requireEnrichments?: true };",
|
|
9
|
+
PlId: "/** Id made by Platforma: 24 base32 characters. */\ntype PlId = string;",
|
|
10
|
+
ImportFileHandle: "/** Handle of a file to import into a block. Copy it from a tool result. */\ntype ImportFileHandle = `upload://upload/${string}` | `index://index/${string}`;",
|
|
11
|
+
PObjectId: "/** A leaf column id only: a block's own column (local) or another block's (GlobalPObjectId); never a filtered, discovered or overridden id. */\ntype PObjectId = string;",
|
|
12
|
+
GlobalPObjectId: "/** Canonical JSON of a PlRef without requireEnrichments: the `columnId` list_columns and get_block_outputs give a column of another block, and list_pool_columns one with a `ref`. */\ntype GlobalPObjectId = string;",
|
|
13
|
+
SUniversalPColumnId: "/** Same as ColumnUniversalId. */\ntype SUniversalPColumnId = string;",
|
|
14
|
+
ColumnUniversalId: "/** Any form of column id, leaf or not. Block workflows resolve leaf ids only today: for a block field copy the id the block offers in its option outputs, or a leaf `columnId` or `ref`. */\ntype ColumnUniversalId = string;",
|
|
15
|
+
ColumnValueId: "/** One value of one column; copy from `valueIds` of get_column_values (of a pool column too); never build it. */\ntype ColumnValueId = string;",
|
|
16
|
+
AxisId: "/** Identity of an axis of a column. */\ntype AxisId = { readonly type: \"Int\" | \"Long\" | \"String\"; readonly name: string; readonly domain?: Record<string, string>; readonly contextDomain?: Record<string, string> };",
|
|
17
|
+
PTableColumnId: "/** A column of a table: one of its axes or one of its columns. */\ntype PTableColumnId = { type: \"axis\"; id: AxisId } | { type: \"column\"; id: ColumnUniversalId };",
|
|
18
|
+
PColumnSpec: "/** Spec of a column, as tool results show it. */\ntype PColumnSpec = Record<string, unknown>;",
|
|
19
|
+
DatasetSelection: "/** A picked dataset: its column, an optional filter, and enrichments attached to it. An enrichment is a column the block's dataset option offers with the dataset: copy each from `enrichments` of that option in the block's option outputs (get_block_outputs); never build one. */\ntype DatasetSelection = { readonly __isDatasetSelection: \"v1\"; readonly primary: { readonly __isPrimaryRef: \"v1\"; readonly column: PlRef; readonly filter?: PlRef }; readonly enrichments?: readonly { readonly id: ColumnUniversalId; readonly label: string }[] };",
|
|
20
|
+
CanonicalizedJson: "/** JSON text of a value of type T, in canonical form. */\ntype CanonicalizedJson<T = unknown> = string;"
|
|
21
|
+
};
|
|
22
|
+
exports.SDK_TYPES = SDK_TYPES;
|
|
23
|
+
|
|
24
|
+
//# sourceMappingURL=sdk-types.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sdk-types.cjs","names":[],"sources":["../../src/tools/sdk-types.ts"],"sourcesContent":["/**\n * Short declarations of the SDK types kinds use in their params. A kind's `contract.d.ts` imports\n * them from `@platforma-sdk/*` and `@milaboratories/*`, which an agent cannot open; this is what\n * stands for each. `get_block_contract` returns all of them.\n */\nexport const SDK_TYPES: Record<string, string> = {\n PlRef:\n \"/** Object form of a leaf GlobalPObjectId; copy `ref` from a block's option outputs \" +\n \"(get_block_outputs) or from list_pool_columns. */\\n\" +\n \"type PlRef = { __isRef: true; blockId: string; name: string; requireEnrichments?: true };\",\n PlId: \"/** Id made by Platforma: 24 base32 characters. */\\ntype PlId = string;\",\n ImportFileHandle:\n \"/** Handle of a file to import into a block. Copy it from a tool result. */\\n\" +\n \"type ImportFileHandle = `upload://upload/${string}` | `index://index/${string}`;\",\n PObjectId:\n \"/** A leaf column id only: a block's own column (local) or another block's \" +\n \"(GlobalPObjectId); never a filtered, discovered or overridden id. */\\n\" +\n \"type PObjectId = string;\",\n GlobalPObjectId:\n \"/** Canonical JSON of a PlRef without requireEnrichments: the `columnId` list_columns \" +\n \"and get_block_outputs give a column of another block, and list_pool_columns one with a \" +\n \"`ref`. */\\n\" +\n \"type GlobalPObjectId = string;\",\n SUniversalPColumnId: \"/** Same as ColumnUniversalId. */\\ntype SUniversalPColumnId = string;\",\n ColumnUniversalId:\n \"/** Any form of column id, leaf or not. Block workflows resolve leaf ids only today: \" +\n \"for a block field copy the id the block offers in its option outputs, or a leaf \" +\n \"`columnId` or `ref`. */\\n\" +\n \"type ColumnUniversalId = string;\",\n ColumnValueId:\n \"/** One value of one column; copy from `valueIds` of get_column_values (of a pool \" +\n \"column too); never build it. */\\n\" +\n \"type ColumnValueId = string;\",\n AxisId:\n \"/** Identity of an axis of a column. */\\n\" +\n 'type AxisId = { readonly type: \"Int\" | \"Long\" | \"String\"; readonly name: string; ' +\n \"readonly domain?: Record<string, string>; readonly contextDomain?: Record<string, string> };\",\n PTableColumnId:\n \"/** A column of a table: one of its axes or one of its columns. */\\n\" +\n 'type PTableColumnId = { type: \"axis\"; id: AxisId } | { type: \"column\"; id: ColumnUniversalId };',\n PColumnSpec:\n \"/** Spec of a column, as tool results show it. */\\ntype PColumnSpec = Record<string, unknown>;\",\n DatasetSelection:\n \"/** A picked dataset: its column, an optional filter, and enrichments attached to it. \" +\n \"An enrichment is a column the block's dataset option offers with the dataset: copy each \" +\n \"from `enrichments` of that option in the block's option outputs (get_block_outputs); \" +\n \"never build one. */\\n\" +\n 'type DatasetSelection = { readonly __isDatasetSelection: \"v1\"; readonly primary: ' +\n '{ readonly __isPrimaryRef: \"v1\"; readonly column: PlRef; readonly filter?: PlRef }; ' +\n \"readonly enrichments?: readonly { readonly id: ColumnUniversalId; readonly label: string }[] };\",\n CanonicalizedJson:\n \"/** JSON text of a value of type T, in canonical form. */\\n\" +\n \"type CanonicalizedJson<T = unknown> = string;\",\n};\n"],"mappings":";;;;;;AAKA,MAAa,YAAoC;CAC/C,OACE;CAGF,MAAM;CACN,kBACE;CAEF,WACE;CAGF,iBACE;CAIF,qBAAqB;CACrB,mBACE;CAIF,eACE;CAGF,QACE;CAGF,gBACE;CAEF,aACE;CACF,kBACE;CAOF,mBACE;AAEJ"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// src/tools/sdk-types.ts
|
|
2
|
+
/**
|
|
3
|
+
* Short declarations of the SDK types kinds use in their params. A kind's `contract.d.ts` imports
|
|
4
|
+
* them from `@platforma-sdk/*` and `@milaboratories/*`, which an agent cannot open; this is what
|
|
5
|
+
* stands for each. `get_block_contract` returns all of them.
|
|
6
|
+
*/
|
|
7
|
+
const SDK_TYPES = {
|
|
8
|
+
PlRef: "/** Object form of a leaf GlobalPObjectId; copy `ref` from a block's option outputs (get_block_outputs) or from list_pool_columns. */\ntype PlRef = { __isRef: true; blockId: string; name: string; requireEnrichments?: true };",
|
|
9
|
+
PlId: "/** Id made by Platforma: 24 base32 characters. */\ntype PlId = string;",
|
|
10
|
+
ImportFileHandle: "/** Handle of a file to import into a block. Copy it from a tool result. */\ntype ImportFileHandle = `upload://upload/${string}` | `index://index/${string}`;",
|
|
11
|
+
PObjectId: "/** A leaf column id only: a block's own column (local) or another block's (GlobalPObjectId); never a filtered, discovered or overridden id. */\ntype PObjectId = string;",
|
|
12
|
+
GlobalPObjectId: "/** Canonical JSON of a PlRef without requireEnrichments: the `columnId` list_columns and get_block_outputs give a column of another block, and list_pool_columns one with a `ref`. */\ntype GlobalPObjectId = string;",
|
|
13
|
+
SUniversalPColumnId: "/** Same as ColumnUniversalId. */\ntype SUniversalPColumnId = string;",
|
|
14
|
+
ColumnUniversalId: "/** Any form of column id, leaf or not. Block workflows resolve leaf ids only today: for a block field copy the id the block offers in its option outputs, or a leaf `columnId` or `ref`. */\ntype ColumnUniversalId = string;",
|
|
15
|
+
ColumnValueId: "/** One value of one column; copy from `valueIds` of get_column_values (of a pool column too); never build it. */\ntype ColumnValueId = string;",
|
|
16
|
+
AxisId: "/** Identity of an axis of a column. */\ntype AxisId = { readonly type: \"Int\" | \"Long\" | \"String\"; readonly name: string; readonly domain?: Record<string, string>; readonly contextDomain?: Record<string, string> };",
|
|
17
|
+
PTableColumnId: "/** A column of a table: one of its axes or one of its columns. */\ntype PTableColumnId = { type: \"axis\"; id: AxisId } | { type: \"column\"; id: ColumnUniversalId };",
|
|
18
|
+
PColumnSpec: "/** Spec of a column, as tool results show it. */\ntype PColumnSpec = Record<string, unknown>;",
|
|
19
|
+
DatasetSelection: "/** A picked dataset: its column, an optional filter, and enrichments attached to it. An enrichment is a column the block's dataset option offers with the dataset: copy each from `enrichments` of that option in the block's option outputs (get_block_outputs); never build one. */\ntype DatasetSelection = { readonly __isDatasetSelection: \"v1\"; readonly primary: { readonly __isPrimaryRef: \"v1\"; readonly column: PlRef; readonly filter?: PlRef }; readonly enrichments?: readonly { readonly id: ColumnUniversalId; readonly label: string }[] };",
|
|
20
|
+
CanonicalizedJson: "/** JSON text of a value of type T, in canonical form. */\ntype CanonicalizedJson<T = unknown> = string;"
|
|
21
|
+
};
|
|
22
|
+
export { SDK_TYPES };
|
|
23
|
+
|
|
24
|
+
//# sourceMappingURL=sdk-types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sdk-types.js","names":[],"sources":["../../src/tools/sdk-types.ts"],"sourcesContent":["/**\n * Short declarations of the SDK types kinds use in their params. A kind's `contract.d.ts` imports\n * them from `@platforma-sdk/*` and `@milaboratories/*`, which an agent cannot open; this is what\n * stands for each. `get_block_contract` returns all of them.\n */\nexport const SDK_TYPES: Record<string, string> = {\n PlRef:\n \"/** Object form of a leaf GlobalPObjectId; copy `ref` from a block's option outputs \" +\n \"(get_block_outputs) or from list_pool_columns. */\\n\" +\n \"type PlRef = { __isRef: true; blockId: string; name: string; requireEnrichments?: true };\",\n PlId: \"/** Id made by Platforma: 24 base32 characters. */\\ntype PlId = string;\",\n ImportFileHandle:\n \"/** Handle of a file to import into a block. Copy it from a tool result. */\\n\" +\n \"type ImportFileHandle = `upload://upload/${string}` | `index://index/${string}`;\",\n PObjectId:\n \"/** A leaf column id only: a block's own column (local) or another block's \" +\n \"(GlobalPObjectId); never a filtered, discovered or overridden id. */\\n\" +\n \"type PObjectId = string;\",\n GlobalPObjectId:\n \"/** Canonical JSON of a PlRef without requireEnrichments: the `columnId` list_columns \" +\n \"and get_block_outputs give a column of another block, and list_pool_columns one with a \" +\n \"`ref`. */\\n\" +\n \"type GlobalPObjectId = string;\",\n SUniversalPColumnId: \"/** Same as ColumnUniversalId. */\\ntype SUniversalPColumnId = string;\",\n ColumnUniversalId:\n \"/** Any form of column id, leaf or not. Block workflows resolve leaf ids only today: \" +\n \"for a block field copy the id the block offers in its option outputs, or a leaf \" +\n \"`columnId` or `ref`. */\\n\" +\n \"type ColumnUniversalId = string;\",\n ColumnValueId:\n \"/** One value of one column; copy from `valueIds` of get_column_values (of a pool \" +\n \"column too); never build it. */\\n\" +\n \"type ColumnValueId = string;\",\n AxisId:\n \"/** Identity of an axis of a column. */\\n\" +\n 'type AxisId = { readonly type: \"Int\" | \"Long\" | \"String\"; readonly name: string; ' +\n \"readonly domain?: Record<string, string>; readonly contextDomain?: Record<string, string> };\",\n PTableColumnId:\n \"/** A column of a table: one of its axes or one of its columns. */\\n\" +\n 'type PTableColumnId = { type: \"axis\"; id: AxisId } | { type: \"column\"; id: ColumnUniversalId };',\n PColumnSpec:\n \"/** Spec of a column, as tool results show it. */\\ntype PColumnSpec = Record<string, unknown>;\",\n DatasetSelection:\n \"/** A picked dataset: its column, an optional filter, and enrichments attached to it. \" +\n \"An enrichment is a column the block's dataset option offers with the dataset: copy each \" +\n \"from `enrichments` of that option in the block's option outputs (get_block_outputs); \" +\n \"never build one. */\\n\" +\n 'type DatasetSelection = { readonly __isDatasetSelection: \"v1\"; readonly primary: ' +\n '{ readonly __isPrimaryRef: \"v1\"; readonly column: PlRef; readonly filter?: PlRef }; ' +\n \"readonly enrichments?: readonly { readonly id: ColumnUniversalId; readonly label: string }[] };\",\n CanonicalizedJson:\n \"/** JSON text of a value of type T, in canonical form. */\\n\" +\n \"type CanonicalizedJson<T = unknown> = string;\",\n};\n"],"mappings":";;;;;;AAKA,MAAa,YAAoC;CAC/C,OACE;CAGF,MAAM;CACN,kBACE;CAEF,WACE;CAGF,iBACE;CAIF,qBAAqB;CACrB,mBACE;CAIF,eACE;CAGF,QACE;CAGF,gBACE;CAEF,aACE;CACF,kBACE;CAOF,mBACE;AAEJ"}
|