@matatbread/matbot-tool-types 0.4.25 → 0.5.1
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/package.json +7 -6
- package/src/anchor.ts +23 -0
- package/src/build-dts.ts +21 -18
- package/src/checker.ts +104 -57
- package/src/index.ts +106 -186
- package/src/parameters.cts +141 -0
package/package.json
CHANGED
|
@@ -3,12 +3,13 @@
|
|
|
3
3
|
"matbotRuntime": [
|
|
4
4
|
"node"
|
|
5
5
|
],
|
|
6
|
-
"version": "0.
|
|
6
|
+
"version": "0.5.1",
|
|
7
7
|
"engines": {
|
|
8
8
|
"node": ">=24.0.0"
|
|
9
9
|
},
|
|
10
10
|
"files": [
|
|
11
|
-
"src"
|
|
11
|
+
"src",
|
|
12
|
+
"src/parameters.cts"
|
|
12
13
|
],
|
|
13
14
|
"description": "Node-only ToolTypeIndex service: derives a self-contained .d.ts of the loaded tools' result/service types (by compiling their `declare module` augmentations) so tool-call code generators and composers can type what `tool` calls resolve to.",
|
|
14
15
|
"keywords": [
|
|
@@ -37,13 +38,13 @@
|
|
|
37
38
|
"typescript": "^6.0.3"
|
|
38
39
|
},
|
|
39
40
|
"peerDependencies": {
|
|
40
|
-
"@matatbread/matbot-plugin-api": "^0.
|
|
41
|
-
"@matatbread/matbot-core": "^0.
|
|
41
|
+
"@matatbread/matbot-plugin-api": "^0.5.1",
|
|
42
|
+
"@matatbread/matbot-core": "^0.5.1"
|
|
42
43
|
},
|
|
43
44
|
"devDependencies": {
|
|
44
45
|
"typescript": "^6.0.3",
|
|
45
|
-
"@matatbread/matbot-plugin-api": "^0.
|
|
46
|
-
"@matatbread/matbot-core": "^0.
|
|
46
|
+
"@matatbread/matbot-plugin-api": "^0.5.1",
|
|
47
|
+
"@matatbread/matbot-core": "^0.5.1"
|
|
47
48
|
},
|
|
48
49
|
"scripts": {
|
|
49
50
|
"typecheck": "tsc --noEmit"
|
package/src/anchor.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
|
|
6
|
+
// Where a matbot package's types are read from, for every Program tool-types builds: the monorepo source
|
|
7
|
+
// if present, then the project's own install, and finally THIS module's own resolution — which reaches the
|
|
8
|
+
// copy the host loaded, tool-types peer-depending on plugin-api (and core, through it). For a plugin fetched
|
|
9
|
+
// over http, "this module" is the mirrored copy, and the cache's `node_modules` links the host's singletons.
|
|
10
|
+
//
|
|
11
|
+
// One function because there were two copies, and they drifted: the dts build had the last step and the
|
|
12
|
+
// snippet check did not, so in any project where plugin-api is not resolvable from the config directory (a
|
|
13
|
+
// pnpm project, a globally installed CLI, a bare directory holding only matbot.yaml) the check's import of
|
|
14
|
+
// plugin-api failed, `tool` was `any`, and every tool call in a function body typechecked — a wrong
|
|
15
|
+
// argument, an unknown property, a tool that does not exist.
|
|
16
|
+
export function anchorPackage(projectRoot: string, dir: string, name: string): string | undefined {
|
|
17
|
+
const monorepo = join(projectRoot, dir, 'src', 'index.ts');
|
|
18
|
+
if (existsSync(monorepo)) return monorepo;
|
|
19
|
+
for (const from of [join(projectRoot, '_'), fileURLToPath(import.meta.url)]) {
|
|
20
|
+
try { return createRequire(from).resolve(name); } catch { /* try the next anchor */ }
|
|
21
|
+
}
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
package/src/build-dts.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type TS from 'typescript';
|
|
|
2
2
|
import type { Runtime } from '@matatbread/matbot-plugin-api';
|
|
3
3
|
import { contractArms } from '@matatbread/matbot-plugin-api';
|
|
4
4
|
import { compileToolValidator, generateValidator, type ToolValidator, type ValidatorSource } from './validator.js';
|
|
5
|
+
import { anchorPackage } from './anchor.js';
|
|
5
6
|
|
|
6
7
|
// Derive a self-contained `declare module … { interface ToolContracts {…} interface MatbotServices {…} }`
|
|
7
8
|
// from the live type graph, so a compiled (or hand-rolled) plugin's compilation sees correct types for
|
|
@@ -121,7 +122,6 @@ export async function collectToolTypeRoots(
|
|
|
121
122
|
const { readFileSync, readdirSync, statSync, existsSync } = await import('node:fs');
|
|
122
123
|
const { join } = await import('node:path');
|
|
123
124
|
const { fileURLToPath } = await import('node:url');
|
|
124
|
-
const { createRequire } = await import('node:module');
|
|
125
125
|
|
|
126
126
|
// Anchor plugin-api: the monorepo source if present, then the project's own install, and finally THIS
|
|
127
127
|
// module's own resolution — which always works, because tool-types peer-depends on plugin-api, so
|
|
@@ -135,14 +135,15 @@ export async function collectToolTypeRoots(
|
|
|
135
135
|
// — which compiled clean and only happened to resemble the real `Principal`. A wrong guess compiles too,
|
|
136
136
|
// and the cast gate cannot see it: nothing was cast, a contract was asserted. Same failure the scaffold's
|
|
137
137
|
// dangling plugin-api link used to cause, and the same fix.
|
|
138
|
-
const
|
|
139
|
-
let pluginApiIndex: string | undefined = existsSync(monorepoApi) ? monorepoApi : undefined;
|
|
140
|
-
for (const from of pluginApiIndex === undefined ? [join(projectRoot, '_'), fileURLToPath(import.meta.url)] : []) {
|
|
141
|
-
try { pluginApiIndex = createRequire(from).resolve('@matatbread/matbot-plugin-api'); break; } catch { /* try the next anchor */ }
|
|
142
|
-
}
|
|
138
|
+
const pluginApiIndex = anchorPackage(projectRoot, 'plugin-api', '@matatbread/matbot-plugin-api');
|
|
143
139
|
if (!pluginApiIndex) return null;
|
|
144
140
|
|
|
145
|
-
|
|
141
|
+
// Core is a root too, for the tools `assembleMachine` registers itself (`about_matbot`, `single_turn`,
|
|
142
|
+
// `gate_action`). Nothing else reliably reaches them: no plugin owns them, so no `resolvedUrl` does, and
|
|
143
|
+
// the `plugins/` glob below finds core only through some plugin's import of it — which made those three
|
|
144
|
+
// typed or not by whichever plugins an installation happened to load.
|
|
145
|
+
const coreIndex = anchorPackage(projectRoot, 'core', '@matatbread/matbot-core');
|
|
146
|
+
const roots = new Set<string>([pluginApiIndex, ...(coreIndex !== undefined ? [coreIndex] : [])]);
|
|
146
147
|
|
|
147
148
|
// A loaded plugin's `resolvedUrl` → an on-disk type-bearing source file. `.ts`/`.d.ts` used directly;
|
|
148
149
|
// an npm `.js` entry maps to its sibling `.d.ts`; anything else (blob:, bare specifier, missing) skipped.
|
|
@@ -156,10 +157,10 @@ export async function collectToolTypeRoots(
|
|
|
156
157
|
for (const u of pluginEntryUrls ?? []) { const p = toSource(u); if (p) roots.add(p); }
|
|
157
158
|
|
|
158
159
|
// UNION with a glob of the monorepo `plugins/` tree (not a fallback): the resolvedUrl roots above cover
|
|
159
|
-
// every *loaded* plugin (builtin, compiled, installed), but
|
|
160
|
-
// plugin
|
|
161
|
-
//
|
|
162
|
-
//
|
|
160
|
+
// every *loaded* plugin (builtin, compiled, installed), but a static caller has no loaded set at all —
|
|
161
|
+
// the web bundle's build describes every plugin it bakes, none of which is loaded where it runs. The
|
|
162
|
+
// glob is how that caller sees them. In a real deployment there is no `plugins/` tree, so this no-ops
|
|
163
|
+
// and the scan is purely resolvedUrl-driven. Dedup is by path (a Set of roots).
|
|
163
164
|
//
|
|
164
165
|
// So the roots deliberately over-reach: wherever that tree exists — this repo, or an embedder that vendors
|
|
165
166
|
// it — plugins for OTHER runtimes and plugins nobody loaded are scanned too. Two consequences, and they
|
|
@@ -479,9 +480,8 @@ export async function buildToolTypesData(
|
|
|
479
480
|
const bundledDecls = new Map<string, string>();
|
|
480
481
|
|
|
481
482
|
// Bundling flattens every referenced workspace type into ONE scope, but a type's name is only unique
|
|
482
|
-
// within its own file: two plugins each declaring a file-local
|
|
483
|
-
//
|
|
484
|
-
// to represent it rather than ask the sources not to do it. Emitted side by side they were a TS2300
|
|
483
|
+
// within its own file: two plugins each declaring a file-local type of one name is legal TypeScript, so
|
|
484
|
+
// the generator has to represent it rather than ask the sources not to do it. Emitted side by side they were a TS2300
|
|
485
485
|
// that nothing compiled the dts to catch, and both references then resolved to an error type — the
|
|
486
486
|
// narrowing the contract exists to give, silently gone. So the first symbol to claim a name keeps it
|
|
487
487
|
// and later ones are alpha-renamed (`SkipKind$1`), with every reference rewritten to match.
|
|
@@ -792,10 +792,13 @@ export async function buildToolTypesData(
|
|
|
792
792
|
const params: string[] = [], results: string[] = [], paramNodes: TS.TypeNode[] = [];
|
|
793
793
|
for (const raw of arms) {
|
|
794
794
|
const a = resolveAlias(raw);
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
795
|
+
// Two arguments, or three with a `Call` signature, which is the proxy's alone: the wire is `Result`/`Args`.
|
|
796
|
+
if (!ts.isTypeReferenceNode(a) || a.typeName.getText() !== 'ToolContract') return undefined;
|
|
797
|
+
const [result, args, ...rest] = a.typeArguments ?? [];
|
|
798
|
+
if (result === undefined || args === undefined || rest.length > 1) return undefined;
|
|
799
|
+
results.push(expandNamed(result, new Set(), 0));
|
|
800
|
+
params.push(expandNamed(args, new Set(), 0));
|
|
801
|
+
paramNodes.push(args);
|
|
799
802
|
}
|
|
800
803
|
return { result: results.join(' | '), params: params.join(' | '), paramNodes };
|
|
801
804
|
};
|
package/src/checker.ts
CHANGED
|
@@ -35,7 +35,7 @@ interface DiagnosticRecord {
|
|
|
35
35
|
// plugin is a module: it has a top of file to add an import to, `@matatbread/matbot-plugin-api` is a real
|
|
36
36
|
// dependency of its build dir, and nothing else is importable. A `tool_function` body is
|
|
37
37
|
// `async function __fn(…) { … }`: no top of file, no static imports, and a different importable set
|
|
38
|
-
// entirely —
|
|
38
|
+
// entirely — node's builtins and installed packages, by name. These were written for the first and fired in both, so
|
|
39
39
|
// a body that mistyped `node:fs` was told there are no modules here.
|
|
40
40
|
const HINTS: { codes: number[]; pattern?: RegExp; only?: 'project' | 'snippet'; hint: string }[] = [
|
|
41
41
|
{
|
|
@@ -78,10 +78,9 @@ const HINTS: { codes: number[]; pattern?: RegExp; only?: 'project' | 'snippet';
|
|
|
78
78
|
{
|
|
79
79
|
codes: [2307],
|
|
80
80
|
only: 'snippet',
|
|
81
|
-
//
|
|
82
|
-
//
|
|
83
|
-
|
|
84
|
-
hint: 'this module is not typed here. The comment block at the top of these declarations says what this installation permits; a node builtin has real types (either spelling: `node:os` or `os`), while a bare package or an http(s) URL has none, and importing one of those needs noTypeCheck.',
|
|
81
|
+
// What this adds is WHY a specifier can be absent: a refused one is IMPORT-GATE's finding, at the same
|
|
82
|
+
// position, and this one's is dropped there, so what is left is a module with no declarations.
|
|
83
|
+
hint: 'this module is not typed here. A node builtin has real types (either spelling: `node:os` or `os`); a package has them only if it is installed with declarations of its own, and otherwise importing it needs noTypeCheck.',
|
|
85
84
|
},
|
|
86
85
|
{
|
|
87
86
|
codes: [2305],
|
|
@@ -176,12 +175,25 @@ function reportOf(diags: DiagnosticRecord[], mode: Mode): ToolCheckReport {
|
|
|
176
175
|
};
|
|
177
176
|
}
|
|
178
177
|
|
|
179
|
-
|
|
178
|
+
type CheckParameters = NonNullable<ToolCheckReport['parameters']>;
|
|
179
|
+
|
|
180
|
+
// Handed to the worker as stripped text, never as a path to require: installed, this file is under
|
|
181
|
+
// node_modules, where node refuses to strip types (#118), and the worker loads no hooks to do it instead.
|
|
182
|
+
let parametersJs: string | undefined;
|
|
183
|
+
async function parametersSource(): Promise<string> {
|
|
184
|
+
if (parametersJs === undefined) {
|
|
185
|
+
const [{ readFile }, { stripTypeScriptTypes }] = await Promise.all([import('node:fs/promises'), import('node:module')]);
|
|
186
|
+
parametersJs = stripTypeScriptTypes(await readFile(new URL('./parameters.cts', import.meta.url), 'utf8'));
|
|
187
|
+
}
|
|
188
|
+
return parametersJs;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async function runWorker(data: Record<string, unknown>, importRefused?: (spec: string) => boolean): Promise<{ diags: DiagnosticRecord[] | null; parameters?: CheckParameters }> {
|
|
180
192
|
const { Worker } = await import('node:worker_threads');
|
|
181
193
|
const { createRequire } = await import('node:module');
|
|
182
194
|
const typescriptPath = createRequire(import.meta.url).resolve('typescript');
|
|
183
195
|
|
|
184
|
-
const result = await new Promise<{ ok?: boolean; diagnostics?: DiagnosticRecord[]; error?: string }>((resolve, reject) => {
|
|
196
|
+
const result = await new Promise<{ ok?: boolean; diagnostics?: DiagnosticRecord[]; parameters?: CheckParameters; error?: string }>((resolve, reject) => {
|
|
185
197
|
// Parsed AS TypeScript, never left to node to guess: without the flag eval'd code runs as JS and is
|
|
186
198
|
// retried as TS only if it fails to parse, and `new Set<string>(x)` parses fine as two comparisons —
|
|
187
199
|
// so it would have thrown `string is not defined` but for an unrelated annotation elsewhere in the
|
|
@@ -193,13 +205,31 @@ async function runWorker(data: Record<string, unknown>): Promise<DiagnosticRecor
|
|
|
193
205
|
execArgv: ['--input-type=commonjs-typescript'],
|
|
194
206
|
});
|
|
195
207
|
const timer = setTimeout(() => { void w.terminate(); reject(new Error('typecheck worker timed out')); }, 120_000);
|
|
196
|
-
|
|
208
|
+
// At most one question before the result: which of the literal specifiers it found are refused. A
|
|
209
|
+
// predicate is a closure over this thread's gate snapshot and cannot be cloned into the worker, and a
|
|
210
|
+
// list cannot be computed in advance, packages being an open set; so the worker finishes the program,
|
|
211
|
+
// asks, and completes its findings from the answer.
|
|
212
|
+
w.on('message', (m: { ask?: string[] }) => {
|
|
213
|
+
if (m.ask !== undefined) {
|
|
214
|
+
// A predicate that throws is a plumbing fault, and surfaces as one: thrown here it would be an
|
|
215
|
+
// uncaught exception in a listener, and answered "not refused" a fail-open nobody saw.
|
|
216
|
+
let refused: string[];
|
|
217
|
+
try { refused = m.ask.filter(spec => importRefused?.(spec) === true); }
|
|
218
|
+
catch (e) { clearTimeout(timer); void w.terminate(); reject(e); return; }
|
|
219
|
+
w.postMessage({ refused });
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
clearTimeout(timer); resolve(m as never); void w.terminate();
|
|
223
|
+
});
|
|
197
224
|
w.once('error', e => { clearTimeout(timer); reject(e); });
|
|
198
225
|
w.once('exit', code => { clearTimeout(timer); if (code !== 0) reject(new Error(`typecheck worker exited with ${code}`)); });
|
|
199
226
|
});
|
|
200
227
|
|
|
201
228
|
if (result.error !== undefined) throw new Error(result.error);
|
|
202
|
-
return
|
|
229
|
+
return {
|
|
230
|
+
diags: result.ok ? null : (result.diagnostics ?? []),
|
|
231
|
+
...(result.parameters !== undefined ? { parameters: result.parameters } : {}),
|
|
232
|
+
};
|
|
203
233
|
}
|
|
204
234
|
|
|
205
235
|
/**
|
|
@@ -214,7 +244,7 @@ async function runWorker(data: Record<string, unknown>): Promise<DiagnosticRecor
|
|
|
214
244
|
export async function checkProjectDir(
|
|
215
245
|
buildDir: string, opts?: { ownContracts?: readonly string[] },
|
|
216
246
|
): Promise<CheckResult> {
|
|
217
|
-
const diags = await runWorker({
|
|
247
|
+
const { diags } = await runWorker({
|
|
218
248
|
mode: 'project', buildDir,
|
|
219
249
|
...(opts?.ownContracts !== undefined ? { ownContracts: [...opts.ownContracts] } : {}),
|
|
220
250
|
});
|
|
@@ -236,28 +266,31 @@ export async function checkSnippetAgainst(opts: {
|
|
|
236
266
|
prefixLen: number;
|
|
237
267
|
prefixLines: number;
|
|
238
268
|
apiIndexPath?: string;
|
|
239
|
-
/** `paths` entries for the
|
|
240
|
-
*
|
|
241
|
-
* something that typechecks and is refused at run time. Built by the caller, which knows the set. */
|
|
269
|
+
/** `paths` entries for the builtins a body may import — one per module the gate does not refuse, so
|
|
270
|
+
* nothing is typed that the call will never hand over. Built by the caller, which holds the answer. */
|
|
242
271
|
importPaths?: Record<string, string[]>;
|
|
243
272
|
/** Declaration files for the globals a body HAS beyond the standard library, loaded as roots: on node,
|
|
244
273
|
* `Buffer`. Module types arrive only through {@link importPaths}, which load on an import, so a body
|
|
245
274
|
* using a node global without importing anything would otherwise fail on a name it really has. */
|
|
246
275
|
globalTypes?: readonly string[];
|
|
247
|
-
/**
|
|
248
|
-
* declaration file pulls in the ambient `declare module
|
|
249
|
-
* declarations reference (`node:fs` reaches `node:stream`,
|
|
250
|
-
*
|
|
251
|
-
*
|
|
252
|
-
* the
|
|
253
|
-
|
|
276
|
+
/** Whether the gate refuses an import outright ({@link ToolCheckOptions.importRefused}) — `paths`
|
|
277
|
+
* cannot enforce that. Loading ONE builtin's declaration file pulls in the ambient `declare module
|
|
278
|
+
* 'node:…'` blocks of everything its own declarations reference (`node:fs` reaches `node:stream`,
|
|
279
|
+
* which reaches most of the rest), so a refused specifier resolves anyway and typechecks clean, and an
|
|
280
|
+
* installed package resolves by ordinary lookup. A literal `import('…')` is therefore checked
|
|
281
|
+
* STRUCTURALLY, the way the cast gate and ENV-GATE close the other holes the type system cannot: the
|
|
282
|
+
* worker sends the literal specifiers it found back here once, and this answers which are refused.
|
|
283
|
+
* Absent ⇒ nothing is refused, and nothing is asked. */
|
|
284
|
+
importRefused?: (spec: string) => boolean;
|
|
254
285
|
/** The identifiers the RUNNER does not bind, from `FunctionRunner.withheldGlobals` — the list ENV-GATE
|
|
255
286
|
* rejects. It comes from the runner because a copy here could not be kept in step with it, and a name
|
|
256
287
|
* that is shadowed but not rejected typechecks and then fails at the first call. Absent ⇒ nothing is
|
|
257
288
|
* rejected: with no runner there is no claim about what a body does not have. */
|
|
258
289
|
withheldGlobals?: readonly string[];
|
|
290
|
+
/** Functions in the snippet whose parameter schemas to report ({@link ToolCheckOptions.parametersOf}). */
|
|
291
|
+
parametersOf?: readonly string[];
|
|
259
292
|
}): Promise<ToolCheckReport> {
|
|
260
|
-
const diags = await runWorker({
|
|
293
|
+
const { diags, parameters } = await runWorker({
|
|
261
294
|
mode: 'snippet',
|
|
262
295
|
root: opts.root,
|
|
263
296
|
source: opts.source,
|
|
@@ -267,10 +300,14 @@ export async function checkSnippetAgainst(opts: {
|
|
|
267
300
|
...(opts.apiIndexPath !== undefined ? { apiIndexPath: opts.apiIndexPath } : {}),
|
|
268
301
|
...(opts.importPaths !== undefined ? { importPaths: opts.importPaths } : {}),
|
|
269
302
|
...(opts.globalTypes !== undefined ? { globalTypes: opts.globalTypes } : {}),
|
|
270
|
-
...(opts.
|
|
303
|
+
...(opts.importRefused !== undefined ? { askImports: true } : {}),
|
|
271
304
|
...(opts.withheldGlobals !== undefined ? { withheldGlobals: opts.withheldGlobals } : {}),
|
|
272
|
-
|
|
273
|
-
|
|
305
|
+
...(opts.parametersOf !== undefined && opts.parametersOf.length > 0
|
|
306
|
+
? { parametersOf: [...opts.parametersOf], parametersSource: await parametersSource() }
|
|
307
|
+
: {}),
|
|
308
|
+
}, opts.importRefused);
|
|
309
|
+
const report = reportOf(diags ?? [], 'snippet');
|
|
310
|
+
return parameters !== undefined ? { ...report, parameters } : report;
|
|
274
311
|
}
|
|
275
312
|
|
|
276
313
|
// The worker body: CommonJS (Worker eval mode is CJS, so `require` exists and no loader hooks are
|
|
@@ -454,41 +491,28 @@ try {
|
|
|
454
491
|
return d.getSourceFile().fileName === virtual && d.getStart() >= minStart;
|
|
455
492
|
});
|
|
456
493
|
};
|
|
457
|
-
// The
|
|
458
|
-
//
|
|
459
|
-
// where both rules live and are documented.
|
|
494
|
+
// The by-name rule, inlined: the worker is a CommonJS realm with no loader hooks, so it cannot import
|
|
495
|
+
// 'importableByName' from plugin-api, which is where the rule lives and is documented.
|
|
460
496
|
const byName = function (spec) {
|
|
461
497
|
return spec !== '' && !/[^\\w@.~+!$&'()*,;=:/-]/.test(spec) && !/^[./]/.test(spec)
|
|
462
498
|
&& (spec.indexOf('node:') === 0 || !/^[a-z][a-z0-9+.-]*:/i.test(spec))
|
|
463
499
|
&& !spec.split('/').some(function (seg) { return seg === '.' || seg === '..'; });
|
|
464
500
|
};
|
|
465
|
-
// The node runner's canonicalImport, which is what the gate asks about: 'os' is 'node:os', so a
|
|
466
|
-
// restriction of 'node:' admits it at both.
|
|
467
|
-
const isBuiltin = require('node:module').isBuiltin;
|
|
468
|
-
const canonical = function (spec) {
|
|
469
|
-
return spec.indexOf(':') < 0 && isBuiltin(spec) ? 'node:' + spec : spec;
|
|
470
|
-
};
|
|
471
|
-
const permits = workerData.permittedImports;
|
|
472
501
|
const API_PKG = '@matatbread/matbot-plugin-api';
|
|
473
502
|
const withheld = new Set<string>(workerData.withheldGlobals ?? []);
|
|
474
|
-
const permitted = function (spec) {
|
|
475
|
-
return permits.some(function (p) {
|
|
476
|
-
return spec === p
|
|
477
|
-
|| (p.charAt(p.length - 1) === '/' || p.charAt(p.length - 1) === ':'
|
|
478
|
-
? spec.indexOf(p) === 0
|
|
479
|
-
: spec.indexOf(p + '/') === 0);
|
|
480
|
-
});
|
|
481
|
-
};
|
|
482
503
|
// Where an import was reported on by a rule of ours, so tsc's own complaint about the same specifier is
|
|
483
504
|
// dropped. Both fire whenever the module does not resolve, and tsc's is actively misleading here: it
|
|
484
|
-
// offers "Do you need to install type definitions for node?" about a module the
|
|
505
|
+
// offers "Do you need to install type definitions for node?" about a module the gate refuses,
|
|
485
506
|
// which is not a thing the author can fix — or, for a specifier that lands on a declaration-only
|
|
486
507
|
// package, a path inside matbot's own node_modules. Which of the three tsc emits depends on whether
|
|
487
508
|
// @types/node happens to be reachable from the program root, so these rules are the deterministic ones.
|
|
488
509
|
const importStarts = new Set();
|
|
489
|
-
// Every literal import()'s specifier and where it sits, recorded whether or not
|
|
490
|
-
// the rewrite below is about SPELLING, which no
|
|
510
|
+
// Every literal import()'s specifier and where it sits, recorded whether or not anything is refused:
|
|
511
|
+
// the rewrite below is about SPELLING, which no permission decides.
|
|
491
512
|
const importSpecs = new Map();
|
|
513
|
+
// The literal imports the gate may refuse — by name, and not the types-only package — asked about once
|
|
514
|
+
// the program is checked (see runWorker).
|
|
515
|
+
const importSites = [];
|
|
492
516
|
const envVisit = function (node, sf) {
|
|
493
517
|
if (envGate && node.getStart(sf) >= minStart) {
|
|
494
518
|
if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword
|
|
@@ -510,13 +534,8 @@ try {
|
|
|
510
534
|
synth.push(mk(sf, node.arguments[0], 90006,
|
|
511
535
|
"'" + spec + "' cannot be imported by a function body, which imports only node builtins ('node:fs') and packages already installed where matbot runs, by name — never a path or a URL. To use other code, install it as a package, or as a matbot plugin with the 'plugin' tool."));
|
|
512
536
|
importStarts.add(at);
|
|
513
|
-
} else
|
|
514
|
-
|
|
515
|
-
permits.length === 0
|
|
516
|
-
? "module imports are switched off on this installation, so '" + spec + "' cannot be imported. Compute with the tools available instead."
|
|
517
|
-
: "'" + spec + "' is not permitted on this installation, which allows only: " + permits.join(', ')
|
|
518
|
-
+ ". This is configuration, not a permission anyone can grant at the call — use a permitted module, or none."));
|
|
519
|
-
importStarts.add(at);
|
|
537
|
+
} else {
|
|
538
|
+
importSites.push({ sf: sf, node: node.arguments[0], spec: spec, at: at });
|
|
520
539
|
}
|
|
521
540
|
}
|
|
522
541
|
if (ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.ImportKeyword) {
|
|
@@ -664,13 +683,21 @@ try {
|
|
|
664
683
|
};
|
|
665
684
|
for (const gf of gateFiles) { visit(gf, gf); contractVisit(gf, gf); envVisit(gf, gf); escapeVisit(gf, gf); }
|
|
666
685
|
|
|
686
|
+
const finish = function (refused) {
|
|
687
|
+
try {
|
|
688
|
+
// Before the rewrites below, which defer to a position a gate has already spoken at.
|
|
689
|
+
for (const site of importSites) {
|
|
690
|
+
if (!refused.has(site.spec)) continue;
|
|
691
|
+
synth.push(mk(site.sf, site.node, 90006,
|
|
692
|
+
"'" + site.spec + "' is refused to this function by the permission policy in force — a standing answer, so the import would be refused at the call too. Use another module, or none; this is not something to work around."));
|
|
693
|
+
importStarts.add(site.at);
|
|
694
|
+
}
|
|
695
|
+
|
|
667
696
|
// A bare 'node' is not the builtins namespace — it resolves to @types/node's index.d.ts, which is
|
|
668
697
|
// references and ambient blocks with no export, so tsc reports "File '<matbot's own node_modules>/
|
|
669
698
|
// @types/node/index.d.ts' is not a module": a path the body never named and its author cannot act on.
|
|
670
699
|
// Rewritten only where tsc ALREADY failed on it, so a package genuinely called 'node' is untouched,
|
|
671
|
-
// and only where no gate has spoken at that position, so one mistake stays one finding.
|
|
672
|
-
// a restriction of ["node"] permits — a package of that name, no builtin — which is why this fires with
|
|
673
|
-
// no restriction in force too.
|
|
700
|
+
// and only where no gate has spoken at that position, so one mistake stays one finding.
|
|
674
701
|
for (const d of targets) {
|
|
675
702
|
if (d.code !== 2306 && d.code !== 2307) continue;
|
|
676
703
|
if (importSpecs.get(d.start) !== 'node' || importStarts.has(d.start)) continue;
|
|
@@ -699,7 +726,7 @@ try {
|
|
|
699
726
|
if (spec !== undefined) {
|
|
700
727
|
synth.push({ file: d.file, start: d.start, length: d.length, code: 90006,
|
|
701
728
|
category: ts.DiagnosticCategory.Error, __syn: true,
|
|
702
|
-
messageText: "'" + spec + "' has no type declarations here, so nothing it returns can be checked.
|
|
729
|
+
messageText: "'" + spec + "' has no type declarations here, so nothing it returns can be checked. Use a builtin that has them, or define this function with noTypeCheck." });
|
|
703
730
|
importStarts.add(d.start);
|
|
704
731
|
continue;
|
|
705
732
|
}
|
|
@@ -752,7 +779,27 @@ try {
|
|
|
752
779
|
}
|
|
753
780
|
return out;
|
|
754
781
|
};
|
|
755
|
-
|
|
782
|
+
const parametersModule = function () {
|
|
783
|
+
const m = { exports: {} };
|
|
784
|
+
new Function('module', 'exports', 'require', workerData.parametersSource)(m, m.exports, require);
|
|
785
|
+
return m.exports;
|
|
786
|
+
};
|
|
787
|
+
// Read from the program just checked, so a schema describes exactly the types that were graded.
|
|
788
|
+
const parameters = workerData.parametersOf && virtual !== null
|
|
789
|
+
? parametersModule().parametersOf(ts, program.getTypeChecker(), program.getSourceFile(virtual), workerData.parametersOf)
|
|
790
|
+
: undefined;
|
|
791
|
+
parentPort.postMessage({ ok: errors.length === 0, diagnostics: errors.map(rec), ...(parameters ? { parameters } : {}) });
|
|
792
|
+
} catch (e) {
|
|
793
|
+
parentPort.postMessage({ error: String((e && e.message) || e) });
|
|
794
|
+
}
|
|
795
|
+
};
|
|
796
|
+
|
|
797
|
+
const asked = workerData.askImports ? [...new Set(importSites.map(function (s) { return s.spec; }))] : [];
|
|
798
|
+
if (asked.length === 0) finish(new Set());
|
|
799
|
+
else {
|
|
800
|
+
parentPort.once('message', function (m) { finish(new Set(m.refused)); });
|
|
801
|
+
parentPort.postMessage({ ask: asked });
|
|
802
|
+
}
|
|
756
803
|
} catch (e) {
|
|
757
804
|
parentPort.postMessage({ error: String((e && e.message) || e) });
|
|
758
805
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
import { dirname, join, resolve } from 'node:path';
|
|
2
2
|
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
-
import { createRequire } from 'node:module';
|
|
4
|
-
import {
|
|
5
|
-
import
|
|
3
|
+
import { builtinModules, createRequire } from 'node:module';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { PLUGIN_API_VERSION, RegistryChangeKind, contractArms, splitContract } from '@matatbread/matbot-plugin-api';
|
|
6
|
+
import type { FunctionRunner, MatbotMachine, MatbotPluginSpec, ToolCheckOptions, ToolCheckReport, ToolTypeIndex } from '@matatbread/matbot-plugin-api';
|
|
6
7
|
import { getRegisteredPlugins } from '@matatbread/matbot-core';
|
|
7
8
|
import { buildToolTypesData, compileToolValidators, type SyntheticContract, type ToolTypesData } from './build-dts.js';
|
|
8
9
|
import { checkSnippetAgainst } from './checker.js';
|
|
10
|
+
import { anchorPackage } from './anchor.js';
|
|
9
11
|
import type { ToolValidator } from './validator.js';
|
|
10
12
|
|
|
13
|
+
// Where to resolve from when the host names no project: this package's own install, from which plugin-api,
|
|
14
|
+
// core and `@types/node` all resolve. Never the working directory — a plugin is handed its directories.
|
|
15
|
+
const OWN_DIR = fileURLToPath(new URL('..', import.meta.url));
|
|
16
|
+
|
|
11
17
|
export {
|
|
12
18
|
buildMatbotToolsDts, buildToolTypesData, collectToolTypeRoots, compileToolValidators, filterToolTypesData,
|
|
13
19
|
type DtsParts, type MatbotToolsDts, type ToolTypesData, type ToolTypeRoots,
|
|
@@ -47,35 +53,6 @@ export function asToolValidatorSupplier(index: unknown): ToolValidatorSupplier |
|
|
|
47
53
|
: undefined;
|
|
48
54
|
}
|
|
49
55
|
|
|
50
|
-
// Split a string on `sep` at bracket-depth 0 only (respecting `<> {} () []`), so a top-level `|` or `,`
|
|
51
|
-
// inside a nested type isn't mistaken for a separator.
|
|
52
|
-
function splitTopLevel(s: string, sep: string): string[] {
|
|
53
|
-
const parts: string[] = [];
|
|
54
|
-
let depth = 0, start = 0;
|
|
55
|
-
for (let i = 0; i < s.length; i++) {
|
|
56
|
-
const c = s[i];
|
|
57
|
-
if (c === '<' || c === '{' || c === '(' || c === '[') depth++;
|
|
58
|
-
else if (c === '>' || c === '}' || c === ')' || c === ']') depth--;
|
|
59
|
-
else if (depth === 0 && c === sep) { parts.push(s.slice(start, i)); start = i + 1; }
|
|
60
|
-
}
|
|
61
|
-
parts.push(s.slice(start));
|
|
62
|
-
return parts;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
// Flatten a `toolContract` (`ToolContract<Result, Args>`, or a `|`-union of such arms) to the wire's
|
|
66
|
-
// `params`/`result` union text — the same projection build-dts derives from source arms.
|
|
67
|
-
function splitContract(contract: string): { params: string; result: string } {
|
|
68
|
-
const results: string[] = [], params: string[] = [];
|
|
69
|
-
for (const armText of splitTopLevel(contract, '|')) {
|
|
70
|
-
const m = armText.trim().match(/^ToolContract\s*<([\s\S]*)>$/);
|
|
71
|
-
if (!m) continue;
|
|
72
|
-
const inner = splitTopLevel(m[1]!, ',');
|
|
73
|
-
if (inner[0] !== undefined) results.push(inner[0].trim());
|
|
74
|
-
if (inner[1] !== undefined) params.push(inner[1].trim());
|
|
75
|
-
}
|
|
76
|
-
return { result: results.join(' | ') || 'unknown', params: params.join(' | ') || 'unknown' };
|
|
77
|
-
}
|
|
78
|
-
|
|
79
56
|
// Best-effort JSON-Schema → TypeScript type text. Used only for the params half of a tool that has neither
|
|
80
57
|
// a source augmentation nor a `toolContract` (a foreign/MCP proxy): its `inputSchema` is always present, so
|
|
81
58
|
// we synthesise *something* structural rather than leaving `unknown` — so a composer sees real fields. There
|
|
@@ -155,16 +132,12 @@ export const buildToolTypes: ToolTypesFill = i =>
|
|
|
155
132
|
* already declares is skipped, so nothing is declared twice. `declare const tool: ToolProxy` (mapped over
|
|
156
133
|
* the merged `ToolContracts`) plus its override factory `toolInContext` is what generators call.
|
|
157
134
|
*/
|
|
158
|
-
/**
|
|
159
|
-
*
|
|
160
|
-
*
|
|
161
|
-
|
|
162
|
-
* itself. */
|
|
163
|
-
function fingerprintOf(runner: FunctionRunner | undefined, settings: FunctionRunSettings | undefined): string {
|
|
135
|
+
/** What a runner states, printed: a stable fingerprint of the environment a check's verdict was reached
|
|
136
|
+
* under, for a caller that PERSISTS the verdict (`function-tools` stores one beside each definition and
|
|
137
|
+
* compares it). Sorted and printed rather than identity-derived, because it has to survive a restart. */
|
|
138
|
+
function fingerprintOf(runner: FunctionRunner | undefined): string {
|
|
164
139
|
if (runner === undefined) return 'no-runner';
|
|
165
|
-
|
|
166
|
-
return `permit=${permit === undefined ? '*' : [...permit].sort().join(',')};`
|
|
167
|
-
+ `withheld=${[...(runner.withheldGlobals ?? [])].sort().join(',')}`;
|
|
140
|
+
return `withheld=${[...(runner.withheldGlobals ?? [])].sort().join(',')}`;
|
|
168
141
|
}
|
|
169
142
|
|
|
170
143
|
export class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
@@ -187,9 +160,9 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
187
160
|
//
|
|
188
161
|
// A `FunctionRunner` arriving or leaving deliberately does NOT, though it is the obvious thing to
|
|
189
162
|
// reach for now that the runner is a plugin and can appear after a dts has been handed out. Nothing
|
|
190
|
-
// derived from it is held: each `dts`/`check`/`environment` reads the runner
|
|
191
|
-
//
|
|
192
|
-
//
|
|
163
|
+
// derived from it is held: each `dts`/`check`/`environment` reads the runner once at its start, and
|
|
164
|
+
// the one cache near it — {@link importPaths} — keys on the refused set's CONTENT, so a different
|
|
165
|
+
// answer is a different key. What IS cached is the source scan, which the
|
|
193
166
|
// runner has no part in. Subscribing would throw away a good TypeScript build every time the runner
|
|
194
167
|
// was registered or hot-reloaded, to recompute something that was never stale.
|
|
195
168
|
machine.Notifier.consume(() => { this.generation++; }, this.ac.signal,
|
|
@@ -213,7 +186,7 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
213
186
|
// Read before anything is awaited, with the live tool list: a change that lands while this builds
|
|
214
187
|
// leaves the result stale, for the next caller to rebuild, instead of being marked seen.
|
|
215
188
|
const generation = this.generation;
|
|
216
|
-
const root = this.machine.
|
|
189
|
+
const root = this.machine.projectDir ?? OWN_DIR;
|
|
217
190
|
// Scan the source each loaded plugin was actually loaded from (its resolvedUrl) — builtin, compiled
|
|
218
191
|
// (.compiled-plugins/), or installed (.plugins/) alike — so every registered tool's real augmentation
|
|
219
192
|
// is read. build-dts UNIONs a glob of the monorepo `plugins/` tree onto these roots (not a fallback:
|
|
@@ -244,17 +217,9 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
244
217
|
this.builtFor = generation;
|
|
245
218
|
}
|
|
246
219
|
|
|
247
|
-
|
|
248
|
-
* passed to everything inside it. Per invocation, never cached: whose settings they are depends on how
|
|
249
|
-
* the settings store is partitioned, and the next invocation may be another principal's. */
|
|
250
|
-
private async runnerNow(): Promise<{ runner: FunctionRunner | undefined; settings: FunctionRunSettings | undefined }> {
|
|
251
|
-
const runner = this.machine.FunctionRunner;
|
|
252
|
-
return { runner, settings: await runner?.settings?.() };
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
async dts(): Promise<string> { return this.dtsUnder(await this.runnerNow()); }
|
|
220
|
+
async dts(): Promise<string> { return this.dtsUnder(this.machine.FunctionRunner); }
|
|
256
221
|
|
|
257
|
-
private async dtsUnder(
|
|
222
|
+
private async dtsUnder(runner: FunctionRunner | undefined): Promise<string> {
|
|
258
223
|
await this.ensureBuilt();
|
|
259
224
|
// `tool` — the injected proxy `function-tools`/compiled skills call — is a `ToolProxy`, a mapped type
|
|
260
225
|
// over the (augmented) `ToolContracts`: each multi-arm entry becomes an overload set, so `await
|
|
@@ -268,7 +233,7 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
268
233
|
// checker agreed. It names what is permitted HERE, from the live set, rather than claiming imports
|
|
269
234
|
// work in general — a module outside the set does not resolve, which is the whole point of scoping
|
|
270
235
|
// the types to it. `require` and the rest are rejected by the env gate, not left to fail at a call.
|
|
271
|
-
return `${this.registryBlock(this.cache!)}\ndeclare const tool: import('@matatbread/matbot-plugin-api').ToolProxy;\ndeclare const toolInContext: import('@matatbread/matbot-plugin-api').ToolBox;\ndeclare const context: import('@matatbread/matbot-plugin-api').ComposedCallContext;\n${
|
|
236
|
+
return `${this.registryBlock(this.cache!)}\ndeclare const tool: import('@matatbread/matbot-plugin-api').ToolProxy;\ndeclare const toolInContext: import('@matatbread/matbot-plugin-api').ToolBox;\ndeclare const context: import('@matatbread/matbot-plugin-api').ComposedCallContext;\n${this.importNote(runner)}`;
|
|
272
237
|
}
|
|
273
238
|
|
|
274
239
|
async wireContracts(): Promise<Record<string, { params: string; result: string }>> {
|
|
@@ -283,120 +248,46 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
283
248
|
}
|
|
284
249
|
|
|
285
250
|
/**
|
|
286
|
-
* `paths` for the
|
|
287
|
-
*
|
|
288
|
-
*
|
|
289
|
-
*
|
|
290
|
-
*
|
|
291
|
-
* which types it. An absent restriction means every builtin: a body may ASK for anything and the gate
|
|
292
|
-
* decides, so refusing to type what it may legitimately ask for would make the prompt unreachable.
|
|
293
|
-
* Resolved from THIS package, where `@types/node` is a dependency: the program is
|
|
251
|
+
* `paths` for the builtins a body may import, so `await import('node:os')` is checked against the real
|
|
252
|
+
* signatures — every builtin, less any the permission gate REFUSES the code being checked
|
|
253
|
+
* ({@link ToolCheckOptions.importRefused}). Not the set it would ALLOW: anything the gate has not
|
|
254
|
+
* refused may be asked for, and refusing to type what a body may legitimately ask for would make the
|
|
255
|
+
* prompt unreachable. Resolved from THIS package, where `@types/node` is a dependency: the program is
|
|
294
256
|
* rooted at the `matbot.yaml` directory, which under pnpm and in any published install has no
|
|
295
257
|
* `node_modules/@types` in its lookup chain, so nothing would resolve from there.
|
|
296
258
|
*
|
|
297
259
|
* A builtin gets its real declaration file. A bare package name is left to ordinary resolution: if it
|
|
298
|
-
* is installed it types properly, and if it is not, the error is honest.
|
|
260
|
+
* is installed it types properly, and if it is not, the error is honest. A refused one is IMPORT-GATE's.
|
|
299
261
|
*
|
|
300
262
|
* A path or a URL gets nothing, because a body cannot import one at all (`importableByName`), and
|
|
301
263
|
* IMPORT-GATE says so at the check.
|
|
302
264
|
*/
|
|
303
|
-
/**
|
|
304
|
-
*
|
|
305
|
-
* CONTENT of the permit list it was computed from: settings are read afresh per invocation, so each
|
|
306
|
-
* read is a new array and an identity key would never hit. */
|
|
265
|
+
/** It walks every builtin with a stat apiece, so it is cached against the CONTENT of the refused set:
|
|
266
|
+
* the gate is read afresh per check, and nearly always refuses the same builtins (usually none). */
|
|
307
267
|
private pathsFor?: { key: string; paths: Record<string, string[]> };
|
|
308
268
|
|
|
309
|
-
private async importPaths(
|
|
310
|
-
const key =
|
|
269
|
+
private async importPaths(refused: ReadonlySet<string>): Promise<Record<string, string[]>> {
|
|
270
|
+
const key = [...refused].sort().join(',');
|
|
311
271
|
if (this.pathsFor !== undefined && this.pathsFor.key === key) return this.pathsFor.paths;
|
|
312
|
-
const paths =
|
|
272
|
+
const paths = computeImportPaths(refused);
|
|
313
273
|
this.pathsFor = { key, paths };
|
|
314
274
|
return paths;
|
|
315
275
|
}
|
|
316
276
|
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
//
|
|
327
|
-
// expanded here: `node:fs` admits `node:fs/promises` at the gate, so it must TYPE the submodule too.
|
|
328
|
-
// Emitting the exact specifier alone left a permitted import failing the check, reachable only with
|
|
329
|
-
// `noTypeCheck` — the one divergence between what runs and what is graded.
|
|
330
|
-
// What the GATE would allow, which is the only set worth typing: unrestricted admits any spelling, a
|
|
331
|
-
// restriction admits what its boundary rule admits. Anything else is a divergence between what runs
|
|
332
|
-
// and what is graded, in one direction or the other.
|
|
333
|
-
const allowed = (spec: string): boolean => restricted === undefined || importPermitted(restricted, spec);
|
|
334
|
-
for (const m of builtinModules) {
|
|
335
|
-
if (m.startsWith('_')) continue;
|
|
336
|
-
// Some entries ALREADY carry the prefix — node:sea, node:sqlite, node:test, node:test/reporters,
|
|
337
|
-
// which have no unprefixed spelling — so prefixing unconditionally wrote `node:node:sqlite`, and
|
|
338
|
-
// those four got no entry at all. `await import('node:sqlite')` then failed the check with tsc's
|
|
339
|
-
// "install type definitions for node", which is the message IMPORT-GATE exists to replace.
|
|
340
|
-
const prefixed = m.startsWith('node:');
|
|
341
|
-
const bare = prefixed ? m.slice('node:'.length) : m;
|
|
342
|
-
const file = declarationFile(nodeTypes, bare);
|
|
343
|
-
if (file === undefined) continue;
|
|
344
|
-
if (allowed(`node:${bare}`)) out[`node:${bare}`] = [file];
|
|
345
|
-
// The UNPREFIXED spelling too, where node has one: `import('os')` resolves to `node:os` at run
|
|
346
|
-
// time, and a bare specifier is the spelling a model reaches for first. Allowed by the PREFIXED
|
|
347
|
-
// spelling, because that is what the gate asks about (`canonicalImport`) — so `['node:']` types
|
|
348
|
-
// `os`, as the gate admits it.
|
|
349
|
-
if (!prefixed && allowed(`node:${bare}`)) out[bare] = [file];
|
|
350
|
-
}
|
|
351
|
-
return out;
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
/** The part of the dts that is about imports: which modules this install permits AND which of those
|
|
355
|
-
* have types, that second half being this package's own knowledge. Everything else about the
|
|
356
|
-
* environment — the gate, what is not in scope — is the runner's to state, and is appended verbatim. */
|
|
357
|
-
private async importNote(runner: FunctionRunner | undefined, settings: FunctionRunSettings | undefined): Promise<string> {
|
|
358
|
-
const restricted = settings?.permittedImports;
|
|
359
|
-
const typed = new Set(Object.keys(await this.importPaths(restricted)));
|
|
360
|
-
// "Switched off" is `permit: []` and nothing else — the one configured "never". Derived from the
|
|
361
|
-
// TYPED set instead, it fired for any restriction naming no builtin (`permit: ['lodash']`), telling
|
|
362
|
-
// an author imports were off while the gate was perfectly willing to ask about one.
|
|
363
|
-
// An entry is typed if it names a declaration itself or admits one — `node:` and `node:fs` both do,
|
|
364
|
-
// through their submodules. A bare package admits none, which is a stated refusal rather than a fake
|
|
365
|
-
// type, so the listing says so where the author will read it.
|
|
366
|
-
const covered = (p: string): boolean => typed.has(p) || [...typed].some(t => importPermitted([p], t));
|
|
367
|
-
// The EXPANDED set, because a prefix is not an answer: `node:` tells an author nothing about which
|
|
368
|
-
// builtins exist, and `node:fs` hides that `node:fs/promises` came with it. Restriction entries that
|
|
369
|
-
// admit no declaration at all are listed after it, marked — a bare package is untypeable here, which
|
|
370
|
-
// is a stated refusal rather than a fake type, and the author needs to know which it is.
|
|
371
|
-
// A bare `node` is the one entry that is not merely untypeable but unimportable: the boundary rule
|
|
372
|
-
// reads it as a PACKAGE of that name (it admits `node/sub`, never `node:os`), so an install meaning
|
|
373
|
-
// the builtins and missing the colon permits nothing a body can use. Listing it as "untyped —
|
|
374
|
-
// import it only with noTypeCheck" invited exactly the attempt that cannot work, so it says what it is.
|
|
375
|
-
// A path or a URL is unimportable outright, whoever's runner listed it: the gate never asks about one.
|
|
376
|
-
const mark = (p: string): string => p === 'node'
|
|
377
|
-
? `${p} (a PACKAGE of that name — not node's builtins, which are spelled 'node:fs'; nothing here can import it)`
|
|
378
|
-
: !importableByName(p.replace(/\/$/, ''))
|
|
379
|
-
? `${p} (a path or a URL — a body imports only builtins and packages, by name; nothing here can import it)`
|
|
380
|
-
: `${p} (untyped — import it only with noTypeCheck)`;
|
|
381
|
-
const listing = [
|
|
382
|
-
...[...typed].sort(),
|
|
383
|
-
...(restricted ?? []).filter(p => !covered(p)).sort().map(mark),
|
|
384
|
-
];
|
|
385
|
-
// Whether an import is GATED is whether a runner routes it, not whether a restriction exists. With no
|
|
386
|
-
// runner nothing rewrites `import(…)`: it reaches node's own loader, unasked and unchecked. Saying
|
|
387
|
-
// "you will be asked" there is a promise nothing keeps, and a body discovers the contradiction the
|
|
388
|
-
// first time it imports something.
|
|
277
|
+
/** The part of the dts that is about imports. Composed from what the runner STATES — whether there is
|
|
278
|
+
* one, and the identifiers it does not bind — never from prose it supplies: the facts are the runner's,
|
|
279
|
+
* the wording is this file's, and the same list is what ENV-GATE enforces, so the note cannot drift
|
|
280
|
+
* from it. */
|
|
281
|
+
private importNote(runner: FunctionRunner | undefined): string {
|
|
282
|
+
// Whether an import is GATED is whether a runner routes it. With no runner nothing rewrites
|
|
283
|
+
// `import(…)`: it reaches node's own loader, unasked and unchecked. Saying "you will be asked" there
|
|
284
|
+
// is a promise nothing keeps, and a body discovers the contradiction the first time it imports
|
|
285
|
+
// something. Which modules the gate REFUSES is not listed: that is an answer about one function, and
|
|
286
|
+
// this text is shown to every one. A literal import of a refused module fails the check, saying so.
|
|
389
287
|
const gated = runner !== undefined;
|
|
390
|
-
const
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
: restricted === undefined
|
|
394
|
-
? `// A body may import node builtins${subject}${gated ? ' — you will be asked\n// the first time' : ''}: const fs = await import('node:fs/promises');\n`
|
|
395
|
-
: `// A body may import these${subject}:\n`
|
|
396
|
-
+ `${listing.map(p => `// ${p}`).join('\n')}\n`;
|
|
397
|
-
// Composed from what the runner STATES — the permitted set above, and the identifiers it does not
|
|
398
|
-
// bind — never from prose it supplies: the facts are the runner's, the wording is this file's, and
|
|
399
|
-
// the same two arrays are what IMPORT-GATE and ENV-GATE enforce, so the note cannot drift from them.
|
|
288
|
+
const note = gated
|
|
289
|
+
? `// A body may import node builtins and installed packages, each subject to permission at the call — you will be asked\n// the first time: const fs = await import('node:fs/promises');\n`
|
|
290
|
+
: `// A body may import node builtins and installed packages: const fs = await import('node:fs/promises');\n`;
|
|
400
291
|
const withheld = runner?.withheldGlobals ?? [];
|
|
401
292
|
return `${note}`
|
|
402
293
|
+ (withheld.length > 0
|
|
@@ -405,65 +296,64 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
405
296
|
: '');
|
|
406
297
|
}
|
|
407
298
|
|
|
408
|
-
/** The
|
|
299
|
+
/** The runner's statement, printed: a stable fingerprint of the environment a check's verdict was
|
|
409
300
|
* reached under, for a caller that PERSISTS the verdict (`function-tools` stores one beside each
|
|
410
|
-
* definition).
|
|
411
|
-
* — unlike {@link pathsFor}, whose job is the opposite and which keys on the array itself. */
|
|
301
|
+
* definition). */
|
|
412
302
|
async environment(): Promise<string> {
|
|
413
|
-
|
|
414
|
-
return fingerprintOf(runner, settings);
|
|
303
|
+
return fingerprintOf(this.machine.FunctionRunner);
|
|
415
304
|
}
|
|
416
305
|
|
|
417
|
-
async check(snippet: string): Promise<ToolCheckReport> {
|
|
306
|
+
async check(snippet: string, opts?: ToolCheckOptions): Promise<ToolCheckReport> {
|
|
418
307
|
// ABSOLUTE, always. The virtual file is named `<root>/…`, and `ts.createProgram` normalises a
|
|
419
308
|
// relative one to a different string than the hook compares against — so `getSourceFile(virtual)`
|
|
420
309
|
// missed, there were no files to check, and the snippet came back clean whatever was in it. A
|
|
421
310
|
// checker that silently passes everything is the one failure mode this path must not have.
|
|
422
|
-
const root = resolve(this.machine.
|
|
423
|
-
// Read ONCE, before anything else: the dts, the
|
|
424
|
-
//
|
|
425
|
-
//
|
|
426
|
-
const
|
|
427
|
-
const prefix = `${await this.dtsUnder(
|
|
311
|
+
const root = resolve(this.machine.projectDir ?? OWN_DIR);
|
|
312
|
+
// Read ONCE, before anything else: the dts, the worker's list and the fingerprint stamped below all
|
|
313
|
+
// have to describe one environment — the one this was graded against — not whatever is current by
|
|
314
|
+
// the time each is computed.
|
|
315
|
+
const runner = this.machine.FunctionRunner;
|
|
316
|
+
const prefix = `${await this.dtsUnder(runner)}\n`;
|
|
428
317
|
const source = `${prefix}${snippet}\nexport {};\n`; // trailing export ⇒ this file is a module
|
|
429
318
|
|
|
430
|
-
// Anchor `@matatbread/matbot-plugin-api`
|
|
431
|
-
//
|
|
432
|
-
//
|
|
433
|
-
const
|
|
434
|
-
let apiIndex: string | undefined = existsSync(monorepoApi) ? monorepoApi : undefined;
|
|
319
|
+
// Anchor `@matatbread/matbot-plugin-api` (see anchorPackage). Without it the dts's imports fail, `tool`
|
|
320
|
+
// is `any`, and every tool call in the snippet passes — so a check that cannot find it is a plumbing
|
|
321
|
+
// fault, and is refused as one rather than reported as a pass.
|
|
322
|
+
const apiIndex = anchorPackage(root, 'plugin-api', '@matatbread/matbot-plugin-api');
|
|
435
323
|
if (apiIndex === undefined) {
|
|
436
|
-
|
|
324
|
+
throw new Error('cannot type-check: @matatbread/matbot-plugin-api resolves neither from the project ' +
|
|
325
|
+
`directory (${root}) nor from tool-types itself, so every tool call would typecheck as \`any\`.`);
|
|
437
326
|
}
|
|
438
327
|
|
|
439
328
|
// Worker-hosted check (see checker.ts) — off the main loop, and each diagnostic comes back as an
|
|
440
329
|
// annotated block (caret-anchored frame, related locations, HINT) with snippet-relative positions.
|
|
441
|
-
const
|
|
442
|
-
const importPaths = await this.importPaths(
|
|
443
|
-
|
|
444
|
-
// ambient `declare module 'node:…'` blocks of everything its own declarations reference, so a
|
|
445
|
-
// forbidden specifier resolves through the back door and typechecks clean. The checker closes that
|
|
446
|
-
// structurally. Absent stays absent — unrestricted means nothing to enforce.
|
|
447
|
-
const restricted = settings?.permittedImports;
|
|
448
|
-
const withheld = runner?.withheldGlobals;
|
|
330
|
+
const refused = opts?.importRefused;
|
|
331
|
+
const importPaths = await this.importPaths(refusedBuiltins(refused));
|
|
332
|
+
const withheld = runner?.withheldGlobals;
|
|
449
333
|
const report = await checkSnippetAgainst({
|
|
450
334
|
root, source,
|
|
451
335
|
prefixLen: prefix.length,
|
|
452
336
|
prefixLines: prefix.split('\n').length - 1,
|
|
453
|
-
|
|
337
|
+
apiIndexPath: apiIndex,
|
|
454
338
|
...(Object.keys(importPaths).length > 0 ? { importPaths } : {}),
|
|
455
339
|
globalTypes: nodeGlobalTypes(),
|
|
456
|
-
|
|
340
|
+
// Not only its `paths`: one builtin's declaration file drags in the ambient `declare module
|
|
341
|
+
// 'node:…'` blocks of everything its own declarations reference, so a refused specifier resolves
|
|
342
|
+
// through the back door and typechecks clean, and a package resolves by ordinary lookup. The
|
|
343
|
+
// checker closes that structurally, asking this predicate about the literal imports it finds.
|
|
344
|
+
...(refused !== undefined ? { importRefused: refused } : {}),
|
|
457
345
|
// ENV-GATE's list, from the runner that withholds them. Absent with no runner, which is correct:
|
|
458
346
|
// nothing is withheld there either, so there is nothing to reject.
|
|
459
347
|
...(withheld !== undefined ? { withheldGlobals: withheld } : {}),
|
|
348
|
+
...(opts?.parametersOf !== undefined ? { parametersOf: opts.parametersOf } : {}),
|
|
460
349
|
});
|
|
461
|
-
// Stamped here and nowhere else, from the same
|
|
462
|
-
//
|
|
463
|
-
//
|
|
464
|
-
return report.checked ? { ...report, environment: fingerprintOf(runner
|
|
350
|
+
// Stamped here and nowhere else, from the same runner the worker was handed, so the fingerprint
|
|
351
|
+
// cannot describe an environment other than the one graded against. Only on a verdict that exists:
|
|
352
|
+
// `checked: false` has nothing to be stale.
|
|
353
|
+
return report.checked ? { ...report, environment: fingerprintOf(runner) } : report;
|
|
465
354
|
}
|
|
466
355
|
|
|
356
|
+
|
|
467
357
|
// Every live tool the source scan didn't already declare: a source-less tool that carries its contract as
|
|
468
358
|
// a `toolContract` string (a `function-tools` function; the `tool-store` per-namespace tool), spliced
|
|
469
359
|
// verbatim; plus any tool with neither augmentation nor `toolContract` (a foreign/MCP proxy, or a plugin
|
|
@@ -530,6 +420,36 @@ function nodeGlobalTypes(): string[] {
|
|
|
530
420
|
return ['buffer.buffer.d.ts', 'buffer.d.ts'].map(f => join(nodeTypes, f)).filter(f => existsSync(f));
|
|
531
421
|
}
|
|
532
422
|
|
|
423
|
+
// Every builtin by its canonical, prefixed name — the spelling the gate is asked about. Some entries
|
|
424
|
+
// ALREADY carry the prefix — node:sea, node:sqlite, node:test, node:test/reporters, which have no
|
|
425
|
+
// unprefixed spelling — so prefixing unconditionally wrote `node:node:sqlite`, and those four got no entry.
|
|
426
|
+
const BUILTINS: readonly string[] = builtinModules
|
|
427
|
+
.filter(m => !m.startsWith('_'))
|
|
428
|
+
.map(m => m.startsWith('node:') ? m : `node:${m}`);
|
|
429
|
+
|
|
430
|
+
// The builtins the gate refuses the code being checked, asked one at a time: each is its own question to
|
|
431
|
+
// the gate, and `node:fs` refused says nothing the gate did not say about `node:fs/promises`.
|
|
432
|
+
function refusedBuiltins(refused: ((spec: string) => boolean) | undefined): Set<string> {
|
|
433
|
+
return refused === undefined ? new Set() : new Set(BUILTINS.filter(b => refused(b)));
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
function computeImportPaths(refused: ReadonlySet<string>): Record<string, string[]> {
|
|
437
|
+
const nodeTypes = dirname(createRequire(import.meta.url).resolve('@types/node/package.json'));
|
|
438
|
+
const out: Record<string, string[]> = {};
|
|
439
|
+
for (const spec of BUILTINS) {
|
|
440
|
+
if (refused.has(spec)) continue;
|
|
441
|
+
const bare = spec.slice('node:'.length);
|
|
442
|
+
const file = declarationFile(nodeTypes, bare);
|
|
443
|
+
if (file === undefined) continue;
|
|
444
|
+
out[spec] = [file];
|
|
445
|
+
// The UNPREFIXED spelling too, where node has one: `import('os')` resolves to `node:os` at run time,
|
|
446
|
+
// and a bare specifier is the spelling a model reaches for first. Decided by the PREFIXED spelling,
|
|
447
|
+
// because that is what the gate asks about (`canonicalImport`).
|
|
448
|
+
if (builtinModules.includes(bare)) out[bare] = [file];
|
|
449
|
+
}
|
|
450
|
+
return out;
|
|
451
|
+
}
|
|
452
|
+
|
|
533
453
|
// Where @types/node declares a builtin. Most have a file of their own, but a few subpaths are declared
|
|
534
454
|
// inside their parent's (`path/posix` in path.d.ts, `util/types` in util.d.ts, `test/reporters` in
|
|
535
455
|
// test.d.ts), and skipping those left a module the gate admits failing the check. The parent is taken
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import type TS from 'typescript';
|
|
2
|
+
|
|
3
|
+
// The JSON Schema of a function's parameters, from the CHECKER'S RESOLVED TYPES — what a defined tool's
|
|
4
|
+
// `inputSchema` is on node. function-tools derives the same thing from the parameter text by hand, which is
|
|
5
|
+
// all the browser has; that derivation cannot see a named type, an imported one, an alias, `Omit<…>` or an
|
|
6
|
+
// indexed access, and degrades each to `{}`. Here every one of them arrives already evaluated.
|
|
7
|
+
//
|
|
8
|
+
// Run in the checker's worker, which is CommonJS with no loader hooks: hence `.cts` and `module.exports`
|
|
9
|
+
// rather than an `export`. The checker strips it and hands the worker the text, since node strips nothing
|
|
10
|
+
// under node_modules, where this file is once installed.
|
|
11
|
+
//
|
|
12
|
+
// The conventions are the hand path's, so the two agree wherever both can answer: the JSON projection of the
|
|
13
|
+
// type (`toJSON` wins, a method is absent), a union of scalars as a `type`/`enum` pair, and anything a
|
|
14
|
+
// provider or json-validation could not honour — a union with a structural arm, a tuple's positions, a
|
|
15
|
+
// function — as the permissive `{}` rather than a constraint that rejects a valid call.
|
|
16
|
+
|
|
17
|
+
type Schema = Record<string, unknown>;
|
|
18
|
+
|
|
19
|
+
interface Parameter { name: string; optional: boolean; schema: Schema }
|
|
20
|
+
|
|
21
|
+
const MAX_DEPTH = 6;
|
|
22
|
+
|
|
23
|
+
// Their instances stringify to `{}`: state behind accessors or internal slots, so nothing reaches the wire.
|
|
24
|
+
const EMPTY_JSON = new Set(['Map', 'Set', 'WeakMap', 'WeakSet', 'WeakRef', 'RegExp', 'Promise', 'Error']);
|
|
25
|
+
|
|
26
|
+
function schemaOf(ts: typeof TS, checker: TS.TypeChecker, location: TS.Node, root: TS.Type): Schema {
|
|
27
|
+
const F = ts.TypeFlags;
|
|
28
|
+
const onPath = new Set<TS.Type>();
|
|
29
|
+
|
|
30
|
+
const scalar = (t: TS.Type): { type: string; value?: string | number | boolean } | undefined => {
|
|
31
|
+
if (t.flags & F.StringLiteral) return { type: 'string', value: (t as TS.StringLiteralType).value };
|
|
32
|
+
if (t.flags & F.NumberLiteral) return { type: 'number', value: (t as TS.NumberLiteralType).value };
|
|
33
|
+
if (t.flags & F.BooleanLiteral) return { type: 'boolean', value: checker.typeToString(t) === 'true' };
|
|
34
|
+
if (t.flags & F.String) return { type: 'string' };
|
|
35
|
+
if (t.flags & F.Number) return { type: 'number' };
|
|
36
|
+
if (t.flags & F.Boolean) return { type: 'boolean' };
|
|
37
|
+
if (t.flags & F.Null) return { type: 'null' };
|
|
38
|
+
return undefined;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const walk = (t: TS.Type, depth: number): Schema => {
|
|
42
|
+
if (depth > MAX_DEPTH || onPath.has(t)) return {};
|
|
43
|
+
if (t.flags & (F.Any | F.Unknown | F.TypeParameter | F.Never)) return {};
|
|
44
|
+
|
|
45
|
+
if (t.isUnion()) {
|
|
46
|
+
const arms = t.types.filter(m => !(m.flags & (F.Undefined | F.Void)));
|
|
47
|
+
if (arms.length === 0) return {};
|
|
48
|
+
if (arms.length === 1) return walk(arms[0]!, depth);
|
|
49
|
+
const scalars = arms.map(scalar);
|
|
50
|
+
// A structural arm makes the union a job for `anyOf`, which json-validation does not enforce.
|
|
51
|
+
if (scalars.some(s => s === undefined)) return {};
|
|
52
|
+
const ss = scalars as { type: string; value?: string | number | boolean }[];
|
|
53
|
+
const open = new Set(ss.filter(s => s.value === undefined).map(s => s.type));
|
|
54
|
+
// `boolean` arrives as `true | false`; both together are the open type, not an enum of two.
|
|
55
|
+
if (ss.filter(s => s.type === 'boolean' && s.value !== undefined).length === 2) open.add('boolean');
|
|
56
|
+
const literals = ss.filter(s => s.value !== undefined && !open.has(s.type));
|
|
57
|
+
const types = [...new Set([...open, ...literals.map(s => s.type)])];
|
|
58
|
+
const typed: Schema = types.length === 1 ? { type: types[0] } : { type: types };
|
|
59
|
+
// `'a' | string` widens: an enum of the literal arms would reject the open one.
|
|
60
|
+
return open.size === 0 ? { ...typed, enum: literals.map(s => s.value) } : typed;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const s = scalar(t);
|
|
64
|
+
if (s !== undefined) return s.value !== undefined ? { type: s.type, enum: [s.value] } : { type: s.type };
|
|
65
|
+
if (t.flags & (F.BigInt | F.BigIntLiteral | F.ESSymbol | F.UniqueESSymbol)) return {};
|
|
66
|
+
if (t.getCallSignatures().length > 0) return {};
|
|
67
|
+
|
|
68
|
+
// `toJSON()` decides what is on the wire: a Date is its string.
|
|
69
|
+
const toJSON = checker.getPropertyOfType(t, 'toJSON');
|
|
70
|
+
if (toJSON !== undefined) {
|
|
71
|
+
const sig = checker.getTypeOfSymbolAtLocation(toJSON, location).getCallSignatures()[0];
|
|
72
|
+
if (sig !== undefined) return walk(checker.getReturnTypeOfSignature(sig), depth + 1);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
onPath.add(t);
|
|
76
|
+
try {
|
|
77
|
+
if (checker.isArrayType(t)) {
|
|
78
|
+
const el = checker.getTypeArguments(t as TS.TypeReference)[0];
|
|
79
|
+
return { type: 'array', ...(el !== undefined ? { items: walk(el, depth + 1) } : {}) };
|
|
80
|
+
}
|
|
81
|
+
if (checker.isTupleType(t)) return { type: 'array' };
|
|
82
|
+
const name = t.getSymbol()?.getName();
|
|
83
|
+
if (name !== undefined && EMPTY_JSON.has(name)) return { type: 'object' };
|
|
84
|
+
if (!(t.flags & F.Object) && !t.isIntersection()) return {};
|
|
85
|
+
|
|
86
|
+
const properties: Record<string, Schema> = {};
|
|
87
|
+
const required: string[] = [];
|
|
88
|
+
for (const p of checker.getPropertiesOfType(t)) {
|
|
89
|
+
const pt = checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration ?? location);
|
|
90
|
+
if (pt.getCallSignatures().length > 0 && !pt.isUnion()) continue; // a method: never on the wire
|
|
91
|
+
properties[p.getName()] = walk(pt, depth + 1);
|
|
92
|
+
const optional = (p.flags & ts.SymbolFlags.Optional) !== 0
|
|
93
|
+
|| (pt.isUnion() && pt.types.some(m => m.flags & F.Undefined));
|
|
94
|
+
if (!optional) required.push(p.getName());
|
|
95
|
+
}
|
|
96
|
+
const index = checker.getIndexTypeOfType(t, ts.IndexKind.String);
|
|
97
|
+
return {
|
|
98
|
+
type: 'object',
|
|
99
|
+
...(Object.keys(properties).length > 0 ? { properties } : {}),
|
|
100
|
+
...(required.length > 0 ? { required } : {}),
|
|
101
|
+
...(index !== undefined ? { additionalProperties: walk(index, depth + 1) } : {}),
|
|
102
|
+
};
|
|
103
|
+
} finally {
|
|
104
|
+
onPath.delete(t);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
return walk(root, 0);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The function a top-level declaration of `name` gives the file: a function declaration, or a `const`
|
|
112
|
+
* initialised with a function or arrow expression. `export` or not. */
|
|
113
|
+
function findFunction(ts: typeof TS, sf: TS.SourceFile, name: string): TS.SignatureDeclaration | undefined {
|
|
114
|
+
for (const st of sf.statements) {
|
|
115
|
+
if (ts.isFunctionDeclaration(st) && st.name?.text === name) return st;
|
|
116
|
+
if (ts.isVariableStatement(st)) {
|
|
117
|
+
for (const d of st.declarationList.declarations) {
|
|
118
|
+
if (ts.isIdentifier(d.name) && d.name.text === name && d.initializer !== undefined
|
|
119
|
+
&& (ts.isArrowFunction(d.initializer) || ts.isFunctionExpression(d.initializer))) return d.initializer;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Each named function's parameters with their schemas; a name the file does not declare is absent. */
|
|
127
|
+
function parametersOf(ts: typeof TS, checker: TS.TypeChecker, sf: TS.SourceFile, names: readonly string[]): Record<string, Parameter[]> {
|
|
128
|
+
const out: Record<string, Parameter[]> = {};
|
|
129
|
+
for (const name of names) {
|
|
130
|
+
const fn = findFunction(ts, sf, name);
|
|
131
|
+
if (fn === undefined) continue;
|
|
132
|
+
out[name] = fn.parameters.map((p, i) => ({
|
|
133
|
+
name: ts.isIdentifier(p.name) ? p.name.text : `arg${i}`,
|
|
134
|
+
optional: p.questionToken !== undefined || p.initializer !== undefined,
|
|
135
|
+
schema: schemaOf(ts, checker, p, checker.getTypeAtLocation(p)),
|
|
136
|
+
}));
|
|
137
|
+
}
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
module.exports = { parametersOf };
|