@assistant-ui/x-generative-compiler 0.0.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/README.md +38 -0
- package/dist/compile.d.ts +39 -0
- package/dist/compile.d.ts.map +1 -0
- package/dist/compile.js +235 -0
- package/dist/compile.js.map +1 -0
- package/dist/constants.d.ts +8 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +7 -0
- package/dist/constants.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/package.json +62 -0
- package/src/compile.test.ts +267 -0
- package/src/compile.ts +485 -0
- package/src/constants.ts +5 -0
- package/src/index.ts +9 -0
package/README.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# @assistant-ui/x-generative-compiler
|
|
2
|
+
|
|
3
|
+
> **Internal package.** Not meant for direct use. Use a build integration such as
|
|
4
|
+
> [`@assistant-ui/next`](../next) or [`@assistant-ui/vite`](../vite).
|
|
5
|
+
|
|
6
|
+
The framework-agnostic `"use generative"` compiler. It takes a module that
|
|
7
|
+
colocates a tool's schema, its server-only `execute`, and its client-only
|
|
8
|
+
`render`, and rewrites it for a single build target:
|
|
9
|
+
|
|
10
|
+
- **client** — keeps `render` and any `"use client"` `execute` (frontend tools),
|
|
11
|
+
drops backend `execute` and `hitl()` sentinels, and stamps each tool's inferred
|
|
12
|
+
`type`.
|
|
13
|
+
- **server** — keeps the backend `execute` (importing `server-only`), drops
|
|
14
|
+
`render`.
|
|
15
|
+
|
|
16
|
+
The marker functions a `"use generative"` file imports — `defineToolkit` and
|
|
17
|
+
`hitl` — live in `@assistant-ui/core/react` (re-exported from `@assistant-ui/react`).
|
|
18
|
+
This package only recognizes them by name and strips them at build time.
|
|
19
|
+
|
|
20
|
+
## API
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import {
|
|
24
|
+
compileGenerative,
|
|
25
|
+
isGenerativeModule,
|
|
26
|
+
GenerativeCompileError,
|
|
27
|
+
DIRECTIVE,
|
|
28
|
+
type Target,
|
|
29
|
+
} from "@assistant-ui/x-generative-compiler";
|
|
30
|
+
|
|
31
|
+
if (isGenerativeModule(code)) {
|
|
32
|
+
const { code: out, map } = compileGenerative(code, {
|
|
33
|
+
target: "server", // or "client"
|
|
34
|
+
filename,
|
|
35
|
+
sourceMaps: true,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
```
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Target } from "./constants.js";
|
|
2
|
+
|
|
3
|
+
//#region src/compile.d.ts
|
|
4
|
+
type ToolType = "frontend" | "backend" | "human";
|
|
5
|
+
interface CompileOptions {
|
|
6
|
+
/** Which build target to emit. */
|
|
7
|
+
target: Target;
|
|
8
|
+
/** Source filename, used for error messages and source maps. */
|
|
9
|
+
filename?: string;
|
|
10
|
+
/** Emit a source map alongside the code. */
|
|
11
|
+
sourceMaps?: boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Whether the `server` target prepends `import "server-only"` when it keeps a
|
|
14
|
+
* backend `execute`. Defaults to `true` (the Next.js/RSC convention, where the
|
|
15
|
+
* guard fires via the `react-server` condition). Set `false` for bundlers
|
|
16
|
+
* without a `react-server` layer (e.g. a Vite/TanStack Start `ssr` build),
|
|
17
|
+
* where the split is already structural and importing `server-only` would
|
|
18
|
+
* throw — see the Vite integration.
|
|
19
|
+
*/
|
|
20
|
+
injectServerOnly?: boolean;
|
|
21
|
+
}
|
|
22
|
+
interface CompileResult {
|
|
23
|
+
code: string;
|
|
24
|
+
map?: object | null;
|
|
25
|
+
}
|
|
26
|
+
/** Thrown when a `"use generative"` file violates an authoring constraint. */
|
|
27
|
+
declare class GenerativeCompileError extends Error {
|
|
28
|
+
constructor(message: string, filename?: string);
|
|
29
|
+
}
|
|
30
|
+
/** Whether a source string opts into generative compilation via the directive. */
|
|
31
|
+
declare function isGenerativeModule(code: string): boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Rewrites a `"use generative"` module for a single build target, keeping only the
|
|
34
|
+
* regions that target needs and pruning the imports the dropped regions used.
|
|
35
|
+
*/
|
|
36
|
+
declare function compileGenerative(code: string, options: CompileOptions): CompileResult;
|
|
37
|
+
//#endregion
|
|
38
|
+
export { CompileOptions, CompileResult, GenerativeCompileError, ToolType, compileGenerative, isGenerativeModule };
|
|
39
|
+
//# sourceMappingURL=compile.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compile.d.ts","names":[],"sources":["../src/compile.ts"],"mappings":";;;KAeY,QAAA;AAAA,UAEK,cAAA;EAFL;EAIV,MAAA,EAAQ,MAAM;;EAEd,QAAA;EANkB;EAQlB,UAAA;EAN6B;;;;;;;;EAe7B,gBAAA;AAAA;AAAA,UAGe,aAAA;EACf,IAAA;EACA,GAAG;AAAA;AAAA;AAAA,cAIQ,sBAAA,SAA+B,KAAK;cACnC,OAAA,UAAiB,QAAA;AAAA;;iBAOf,kBAAA,CAAmB,IAAY;;;;;iBA4B/B,iBAAA,CACd,IAAA,UACA,OAAA,EAAS,cAAA,GACR,aAAa"}
|
package/dist/compile.js
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { DIRECTIVE } from "./constants.js";
|
|
2
|
+
import { parse } from "@babel/parser";
|
|
3
|
+
import _traverse from "@babel/traverse";
|
|
4
|
+
import _generate from "@babel/generator";
|
|
5
|
+
import * as t from "@babel/types";
|
|
6
|
+
//#region src/compile.ts
|
|
7
|
+
const traverse = typeof _traverse === "function" ? _traverse : _traverse.default;
|
|
8
|
+
const generate = typeof _generate === "function" ? _generate : _generate.default;
|
|
9
|
+
/** Thrown when a `"use generative"` file violates an authoring constraint. */
|
|
10
|
+
var GenerativeCompileError = class extends Error {
|
|
11
|
+
constructor(message, filename) {
|
|
12
|
+
super(`[assistant-ui/next]${filename ? ` ${filename}:` : ""} ${message}`);
|
|
13
|
+
this.name = "GenerativeCompileError";
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
/** Whether a source string opts into generative compilation via the directive. */
|
|
17
|
+
function isGenerativeModule(code) {
|
|
18
|
+
let i = code.charCodeAt(0) === 65279 ? 1 : 0;
|
|
19
|
+
for (;;) {
|
|
20
|
+
while (i < code.length && /\s/.test(code[i])) i++;
|
|
21
|
+
if (code.startsWith("//", i)) {
|
|
22
|
+
const nl = code.indexOf("\n", i);
|
|
23
|
+
if (nl === -1) return false;
|
|
24
|
+
i = nl + 1;
|
|
25
|
+
} else if (code.startsWith("/*", i)) {
|
|
26
|
+
const end = code.indexOf("*/", i + 2);
|
|
27
|
+
if (end === -1) return false;
|
|
28
|
+
i = end + 2;
|
|
29
|
+
} else break;
|
|
30
|
+
}
|
|
31
|
+
return code.startsWith(`"use generative"`, i) || code.startsWith(`'use generative'`, i);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Rewrites a `"use generative"` module for a single build target, keeping only the
|
|
35
|
+
* regions that target needs and pruning the imports the dropped regions used.
|
|
36
|
+
*/
|
|
37
|
+
function compileGenerative(code, options) {
|
|
38
|
+
const { target, filename } = options;
|
|
39
|
+
const ast = parse(code, {
|
|
40
|
+
sourceType: "module",
|
|
41
|
+
plugins: [
|
|
42
|
+
"typescript",
|
|
43
|
+
"jsx",
|
|
44
|
+
"explicitResourceManagement"
|
|
45
|
+
]
|
|
46
|
+
});
|
|
47
|
+
if (!ast.program.directives.some((d) => d.value.value === "use generative")) throw new GenerativeCompileError(`missing "${DIRECTIVE}" directive`, filename);
|
|
48
|
+
const object = findDefaultExportObject(ast, filename);
|
|
49
|
+
let keptRender = false;
|
|
50
|
+
let keptBackendExecute = false;
|
|
51
|
+
for (const entry of object.properties) {
|
|
52
|
+
const value = entryValue(entry);
|
|
53
|
+
if (!value) throw new GenerativeCompileError("each tool must be an inline object literal (`name: { ... }`) so its `execute` can be routed", filename);
|
|
54
|
+
const type = inferToolType(value, filename);
|
|
55
|
+
const hasRender = !!findMember(value, "render");
|
|
56
|
+
const execute = findMember(value, "execute");
|
|
57
|
+
if ((type === "frontend" || type === "human") && !hasRender) throw new GenerativeCompileError(`a ${type} tool must declare a \`render\` (it has no server execute to show otherwise)`, filename);
|
|
58
|
+
if (target === "client") {
|
|
59
|
+
if (execute && type === "frontend") stripUseClient(execute);
|
|
60
|
+
else if (execute) removeMember(value, "execute");
|
|
61
|
+
if (hasRender) keptRender = true;
|
|
62
|
+
} else {
|
|
63
|
+
if (hasRender) removeMember(value, "render");
|
|
64
|
+
if (execute && type !== "backend") removeMember(value, "execute");
|
|
65
|
+
if (execute && type === "backend") keptBackendExecute = true;
|
|
66
|
+
}
|
|
67
|
+
setToolType(value, type);
|
|
68
|
+
}
|
|
69
|
+
pruneUnused(ast);
|
|
70
|
+
ast.program.directives = ast.program.directives.filter((d) => d.value.value !== "use generative" && d.value.value !== "use client");
|
|
71
|
+
if (target === "client" && keptRender) ast.program.directives.unshift(t.directive(t.directiveLiteral("use client")));
|
|
72
|
+
if (target === "server" && keptBackendExecute && (options.injectServerOnly ?? true)) ast.program.body.unshift(t.importDeclaration([], t.stringLiteral("server-only")));
|
|
73
|
+
const result = generate(ast, {
|
|
74
|
+
sourceMaps: options.sourceMaps ?? false,
|
|
75
|
+
filename,
|
|
76
|
+
jsescOption: { minimal: true }
|
|
77
|
+
}, code);
|
|
78
|
+
return {
|
|
79
|
+
code: result.code,
|
|
80
|
+
map: result.map
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function findDefaultExportObject(ast, filename) {
|
|
84
|
+
let object = null;
|
|
85
|
+
let sawDefault = false;
|
|
86
|
+
for (const stmt of ast.program.body) {
|
|
87
|
+
if (!t.isExportDefaultDeclaration(stmt)) continue;
|
|
88
|
+
sawDefault = true;
|
|
89
|
+
object = unwrapDefineToolkit(stmt.declaration);
|
|
90
|
+
if (object) stmt.declaration = object;
|
|
91
|
+
}
|
|
92
|
+
if (!sawDefault) throw new GenerativeCompileError("missing a default export", filename);
|
|
93
|
+
if (!object) throw new GenerativeCompileError("the default export must be `defineToolkit({ ... })` (imported from \"@assistant-ui/react\"); wrapping is required so a backend `execute` can't be authored in a way that reaches the client", filename);
|
|
94
|
+
return object;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Unwraps the required `defineToolkit({ ... })` wrapper (through `satisfies`/`as`
|
|
98
|
+
* and parens) to the underlying object literal. Anything else — a bare object, a
|
|
99
|
+
* `satisfies Toolkit` without the wrapper, some other call — yields `null` so the
|
|
100
|
+
* caller errors.
|
|
101
|
+
*/
|
|
102
|
+
function unwrapDefineToolkit(node) {
|
|
103
|
+
if (t.isTSSatisfiesExpression(node) || t.isTSAsExpression(node)) return unwrapDefineToolkit(node.expression);
|
|
104
|
+
if (t.isParenthesizedExpression(node)) return unwrapDefineToolkit(node.expression);
|
|
105
|
+
if (t.isCallExpression(node) && t.isIdentifier(node.callee, { name: "defineToolkit" }) && t.isObjectExpression(node.arguments[0])) return node.arguments[0];
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
function entryValue(entry) {
|
|
109
|
+
if (t.isObjectProperty(entry) && t.isObjectExpression(entry.value)) return entry.value;
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
/** A member of an entry object: `render`/`execute`/`type`, as property or method. */
|
|
113
|
+
function findMember(object, name) {
|
|
114
|
+
return object.properties.find((p) => (t.isObjectProperty(p) || t.isObjectMethod(p)) && memberName(p.key, p.computed) === name);
|
|
115
|
+
}
|
|
116
|
+
function removeMember(object, name) {
|
|
117
|
+
object.properties = object.properties.filter((p) => !((t.isObjectProperty(p) || t.isObjectMethod(p)) && memberName(p.key, p.computed) === name));
|
|
118
|
+
}
|
|
119
|
+
/** The `BlockStatement` body of an `execute` member, if it has one. */
|
|
120
|
+
function executeBody(member) {
|
|
121
|
+
if (t.isObjectMethod(member)) return member.body;
|
|
122
|
+
const value = member.value;
|
|
123
|
+
if ((t.isArrowFunctionExpression(value) || t.isFunctionExpression(value)) && t.isBlockStatement(value.body)) return value.body;
|
|
124
|
+
}
|
|
125
|
+
/** Whether an `execute` opts into the client via a leading `"use client"`. */
|
|
126
|
+
function executeIsClient(member) {
|
|
127
|
+
return !!executeBody(member)?.directives.some((d) => d.value.value === "use client");
|
|
128
|
+
}
|
|
129
|
+
/** Whether an `execute` is the `hitl()` human-in-the-loop sentinel. */
|
|
130
|
+
function executeIsHitl(member) {
|
|
131
|
+
return t.isObjectProperty(member) && t.isCallExpression(member.value) && t.isIdentifier(member.value.callee, { name: "hitl" });
|
|
132
|
+
}
|
|
133
|
+
/** Drops the `"use client"` directive from an `execute` body (kept frontend). */
|
|
134
|
+
function stripUseClient(member) {
|
|
135
|
+
const body = executeBody(member);
|
|
136
|
+
if (body) body.directives = body.directives.filter((d) => d.value.value !== "use client");
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* The tool's nature, inferred from its (mandatory) `execute` rather than an
|
|
140
|
+
* authored `type`: `hitl()` → `human`; `"use client"` → `frontend`; otherwise
|
|
141
|
+
* `backend`. The loader writes the result back as a `type` field (see
|
|
142
|
+
* {@link setToolType}) so the runtime keeps it.
|
|
143
|
+
*/
|
|
144
|
+
function inferToolType(object, filename) {
|
|
145
|
+
const execute = findMember(object, "execute");
|
|
146
|
+
if (!execute) throw new GenerativeCompileError("every tool must declare an `execute`; use `hitl()` for a human-in-the-loop tool", filename);
|
|
147
|
+
if (executeIsHitl(execute)) return "human";
|
|
148
|
+
return executeIsClient(execute) ? "frontend" : "backend";
|
|
149
|
+
}
|
|
150
|
+
/** Writes the resolved `type` back onto the tool object (replacing any author's). */
|
|
151
|
+
function setToolType(object, type) {
|
|
152
|
+
removeMember(object, "type");
|
|
153
|
+
object.properties.push(t.objectProperty(t.identifier("type"), t.stringLiteral(type)));
|
|
154
|
+
}
|
|
155
|
+
function memberName(key, computed) {
|
|
156
|
+
if (computed) return void 0;
|
|
157
|
+
if (t.isIdentifier(key)) return key.name;
|
|
158
|
+
if (t.isStringLiteral(key)) return key.value;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Removes declarations and import specifiers left unreferenced after region
|
|
162
|
+
* removal, to a fixpoint (a dropped helper frees what it used). Keeps exports,
|
|
163
|
+
* side-effect imports, and possibly-side-effectful initializers.
|
|
164
|
+
*/
|
|
165
|
+
function pruneUnused(ast) {
|
|
166
|
+
const hadSpecifiers = /* @__PURE__ */ new WeakSet();
|
|
167
|
+
for (const stmt of ast.program.body) if (t.isImportDeclaration(stmt) && stmt.specifiers.length > 0) hadSpecifiers.add(stmt);
|
|
168
|
+
let removedSomething = true;
|
|
169
|
+
while (removedSomething) {
|
|
170
|
+
removedSomething = false;
|
|
171
|
+
traverse(ast, { Program(path) {
|
|
172
|
+
path.scope.crawl();
|
|
173
|
+
const isUnused = (name) => {
|
|
174
|
+
const binding = path.scope.getBinding(name);
|
|
175
|
+
return !!binding && !binding.referenced;
|
|
176
|
+
};
|
|
177
|
+
path.node.body = path.node.body.filter((stmt) => {
|
|
178
|
+
if ((t.isFunctionDeclaration(stmt) || t.isClassDeclaration(stmt)) && stmt.id && isUnused(stmt.id.name)) {
|
|
179
|
+
removedSomething = true;
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
if (t.isVariableDeclaration(stmt)) {
|
|
183
|
+
stmt.declarations = stmt.declarations.filter((decl) => {
|
|
184
|
+
const names = Object.keys(t.getBindingIdentifiers(decl.id));
|
|
185
|
+
if (names.length > 0 && isPlainPattern(decl.id) && isRemovableInit(decl.init) && names.every(isUnused)) {
|
|
186
|
+
removedSomething = true;
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
return true;
|
|
190
|
+
});
|
|
191
|
+
if (stmt.declarations.length === 0) return false;
|
|
192
|
+
}
|
|
193
|
+
return true;
|
|
194
|
+
});
|
|
195
|
+
path.stop();
|
|
196
|
+
} });
|
|
197
|
+
}
|
|
198
|
+
traverse(ast, { Program(path) {
|
|
199
|
+
path.scope.crawl();
|
|
200
|
+
for (const stmt of path.node.body) {
|
|
201
|
+
if (!t.isImportDeclaration(stmt)) continue;
|
|
202
|
+
stmt.specifiers = stmt.specifiers.filter((spec) => {
|
|
203
|
+
const binding = path.scope.getBinding(spec.local.name);
|
|
204
|
+
return binding ? binding.referenced : true;
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
path.node.body = path.node.body.filter((stmt) => !(t.isImportDeclaration(stmt) && stmt.specifiers.length === 0 && hadSpecifiers.has(stmt)));
|
|
208
|
+
path.stop();
|
|
209
|
+
} });
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Whether a binding pattern is side-effect-free to drop: a plain identifier, or
|
|
213
|
+
* an object/array pattern of plain bindings — no default values
|
|
214
|
+
* (`{ a = expr }`) or computed keys (`{ [expr]: a }`), which would evaluate (and
|
|
215
|
+
* thus could have side effects) at destructuring time.
|
|
216
|
+
*/
|
|
217
|
+
function isPlainPattern(node) {
|
|
218
|
+
if (t.isIdentifier(node)) return true;
|
|
219
|
+
if (t.isObjectPattern(node)) return node.properties.every((p) => t.isRestElement(p) ? isPlainPattern(p.argument) : !p.computed && isPlainPattern(p.value));
|
|
220
|
+
if (t.isArrayPattern(node)) return node.elements.every((el) => el == null || isPlainPattern(el));
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
223
|
+
/** Whether a variable initializer is safe to drop (no observable side effects). */
|
|
224
|
+
function isRemovableInit(node) {
|
|
225
|
+
if (node == null) return true;
|
|
226
|
+
if (t.isTSAsExpression(node) || t.isTSSatisfiesExpression(node)) return isRemovableInit(node.expression);
|
|
227
|
+
if (t.isArrayExpression(node)) return node.elements.every((el) => el == null || t.isExpression(el) && isRemovableInit(el));
|
|
228
|
+
if (t.isObjectExpression(node)) return node.properties.every((p) => t.isObjectProperty(p) && !p.computed && t.isExpression(p.value) && isRemovableInit(p.value));
|
|
229
|
+
if (t.isTemplateLiteral(node)) return node.expressions.every((e) => t.isExpression(e) && isRemovableInit(e));
|
|
230
|
+
return t.isArrowFunctionExpression(node) || t.isFunctionExpression(node) || t.isClassExpression(node) || t.isIdentifier(node) || t.isMemberExpression(node) && !node.computed || t.isJSXElement(node) || t.isJSXFragment(node) || t.isLiteral(node);
|
|
231
|
+
}
|
|
232
|
+
//#endregion
|
|
233
|
+
export { GenerativeCompileError, compileGenerative, isGenerativeModule };
|
|
234
|
+
|
|
235
|
+
//# sourceMappingURL=compile.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compile.js","names":[],"sources":["../src/compile.ts"],"sourcesContent":["import { parse } from \"@babel/parser\";\nimport _traverse, { type NodePath } from \"@babel/traverse\";\nimport _generate from \"@babel/generator\";\nimport * as t from \"@babel/types\";\nimport { DIRECTIVE, type Target } from \"./constants\";\n\n// @babel/traverse and @babel/generator are CJS; their default export is the\n// function itself under some interop and `{ default }` under others.\nconst traverse = (\n typeof _traverse === \"function\" ? _traverse : (_traverse as any).default\n) as typeof _traverse;\nconst generate = (\n typeof _generate === \"function\" ? _generate : (_generate as any).default\n) as typeof _generate;\n\nexport type ToolType = \"frontend\" | \"backend\" | \"human\";\n\nexport interface CompileOptions {\n /** Which build target to emit. */\n target: Target;\n /** Source filename, used for error messages and source maps. */\n filename?: string;\n /** Emit a source map alongside the code. */\n sourceMaps?: boolean;\n /**\n * Whether the `server` target prepends `import \"server-only\"` when it keeps a\n * backend `execute`. Defaults to `true` (the Next.js/RSC convention, where the\n * guard fires via the `react-server` condition). Set `false` for bundlers\n * without a `react-server` layer (e.g. a Vite/TanStack Start `ssr` build),\n * where the split is already structural and importing `server-only` would\n * throw — see the Vite integration.\n */\n injectServerOnly?: boolean;\n}\n\nexport interface CompileResult {\n code: string;\n map?: object | null;\n}\n\n/** Thrown when a `\"use generative\"` file violates an authoring constraint. */\nexport class GenerativeCompileError extends Error {\n constructor(message: string, filename?: string) {\n super(`[assistant-ui/next]${filename ? ` ${filename}:` : \"\"} ${message}`);\n this.name = \"GenerativeCompileError\";\n }\n}\n\n/** Whether a source string opts into generative compilation via the directive. */\nexport function isGenerativeModule(code: string): boolean {\n // The directive must be a leading statement, preceded only by an optional BOM,\n // whitespace, and line/block comments. Scanned linearly — a regex over the\n // comment prefix is prone to catastrophic backtracking on crafted input.\n let i = code.charCodeAt(0) === 0xfeff ? 1 : 0;\n for (;;) {\n while (i < code.length && /\\s/.test(code[i]!)) i++;\n if (code.startsWith(\"//\", i)) {\n const nl = code.indexOf(\"\\n\", i);\n if (nl === -1) return false;\n i = nl + 1;\n } else if (code.startsWith(\"/*\", i)) {\n const end = code.indexOf(\"*/\", i + 2);\n if (end === -1) return false;\n i = end + 2;\n } else {\n break;\n }\n }\n return (\n code.startsWith(`\"${DIRECTIVE}\"`, i) || code.startsWith(`'${DIRECTIVE}'`, i)\n );\n}\n\n/**\n * Rewrites a `\"use generative\"` module for a single build target, keeping only the\n * regions that target needs and pruning the imports the dropped regions used.\n */\nexport function compileGenerative(\n code: string,\n options: CompileOptions,\n): CompileResult {\n const { target, filename } = options;\n\n const ast = parse(code, {\n sourceType: \"module\",\n plugins: [\"typescript\", \"jsx\", \"explicitResourceManagement\"],\n });\n\n if (!ast.program.directives.some((d) => d.value.value === DIRECTIVE)) {\n throw new GenerativeCompileError(\n `missing \"${DIRECTIVE}\" directive`,\n filename,\n );\n }\n\n const object = findDefaultExportObject(ast, filename);\n\n let keptRender = false;\n let keptBackendExecute = false;\n\n for (const entry of object.properties) {\n const value = entryValue(entry);\n if (!value) {\n // A non-inline tool (spread, method, or a call like `makeTool()`) can't be\n // analyzed, so its `execute` would pass through to the client unstripped.\n throw new GenerativeCompileError(\n \"each tool must be an inline object literal (`name: { ... }`) so its \" +\n \"`execute` can be routed\",\n filename,\n );\n }\n\n // Nature is inferred from `execute` (see inferToolType), not an authored\n // `type`. The resolved type is written back below so the runtime keeps it.\n const type = inferToolType(value, filename);\n const hasRender = !!findMember(value, \"render\");\n const execute = findMember(value, \"execute\");\n\n if ((type === \"frontend\" || type === \"human\") && !hasRender) {\n throw new GenerativeCompileError(\n `a ${type} tool must declare a \\`render\\` (it has no server execute to show otherwise)`,\n filename,\n );\n }\n\n if (target === \"client\") {\n // A frontend execute stays (its `\"use client\"` marker is no longer needed\n // once the module is client); a backend execute and a human `hitl()`\n // sentinel are both dropped.\n if (execute && type === \"frontend\") stripUseClient(execute);\n else if (execute) removeMember(value, \"execute\");\n if (hasRender) keptRender = true;\n } else {\n // server: render is never needed; only a backend execute survives.\n if (hasRender) removeMember(value, \"render\");\n if (execute && type !== \"backend\") removeMember(value, \"execute\");\n if (execute && type === \"backend\") keptBackendExecute = true;\n }\n\n setToolType(value, type);\n }\n\n pruneUnused(ast);\n\n // Replace the module directives with the target-appropriate one.\n ast.program.directives = ast.program.directives.filter(\n (d) => d.value.value !== DIRECTIVE && d.value.value !== \"use client\",\n );\n if (target === \"client\" && keptRender) {\n ast.program.directives.unshift(\n t.directive(t.directiveLiteral(\"use client\")),\n );\n }\n if (\n target === \"server\" &&\n keptBackendExecute &&\n (options.injectServerOnly ?? true)\n ) {\n ast.program.body.unshift(\n t.importDeclaration([], t.stringLiteral(\"server-only\")),\n );\n }\n\n const result = generate(\n ast,\n {\n sourceMaps: options.sourceMaps ?? false,\n filename,\n jsescOption: { minimal: true },\n },\n code,\n );\n\n return { code: result.code, map: result.map };\n}\n\nfunction findDefaultExportObject(\n ast: t.File,\n filename: string | undefined,\n): t.ObjectExpression {\n let object: t.ObjectExpression | null = null;\n let sawDefault = false;\n\n for (const stmt of ast.program.body) {\n if (!t.isExportDefaultDeclaration(stmt)) continue;\n sawDefault = true;\n object = unwrapDefineToolkit(stmt.declaration);\n // Emit the bare object literal, dropping the `defineToolkit(...)` wrapper\n // (and the import it pulled).\n if (object) stmt.declaration = object;\n }\n\n if (!sawDefault) {\n throw new GenerativeCompileError(\"missing a default export\", filename);\n }\n if (!object) {\n throw new GenerativeCompileError(\n \"the default export must be `defineToolkit({ ... })` (imported from \" +\n '\"@assistant-ui/react\"); wrapping is required so a backend `execute` ' +\n \"can't be authored in a way that reaches the client\",\n filename,\n );\n }\n return object;\n}\n\n/**\n * Unwraps the required `defineToolkit({ ... })` wrapper (through `satisfies`/`as`\n * and parens) to the underlying object literal. Anything else — a bare object, a\n * `satisfies Toolkit` without the wrapper, some other call — yields `null` so the\n * caller errors.\n */\nfunction unwrapDefineToolkit(node: t.Node): t.ObjectExpression | null {\n if (t.isTSSatisfiesExpression(node) || t.isTSAsExpression(node)) {\n return unwrapDefineToolkit(node.expression);\n }\n if (t.isParenthesizedExpression(node)) {\n return unwrapDefineToolkit(node.expression);\n }\n if (\n t.isCallExpression(node) &&\n t.isIdentifier(node.callee, { name: \"defineToolkit\" }) &&\n t.isObjectExpression(node.arguments[0])\n ) {\n return node.arguments[0];\n }\n return null;\n}\n\ntype Entry = t.ObjectExpression[\"properties\"][number];\n\nfunction entryValue(entry: Entry): t.ObjectExpression | null {\n if (t.isObjectProperty(entry) && t.isObjectExpression(entry.value)) {\n return entry.value;\n }\n return null;\n}\n\n/** A member of an entry object: `render`/`execute`/`type`, as property or method. */\nfunction findMember(\n object: t.ObjectExpression,\n name: string,\n): t.ObjectProperty | t.ObjectMethod | undefined {\n return object.properties.find(\n (p): p is t.ObjectProperty | t.ObjectMethod =>\n (t.isObjectProperty(p) || t.isObjectMethod(p)) &&\n memberName(p.key, p.computed) === name,\n );\n}\n\nfunction removeMember(object: t.ObjectExpression, name: string): void {\n object.properties = object.properties.filter(\n (p) =>\n !(\n (t.isObjectProperty(p) || t.isObjectMethod(p)) &&\n memberName(p.key, p.computed) === name\n ),\n );\n}\n\n/** The `BlockStatement` body of an `execute` member, if it has one. */\nfunction executeBody(\n member: t.ObjectProperty | t.ObjectMethod,\n): t.BlockStatement | undefined {\n if (t.isObjectMethod(member)) return member.body;\n const value = member.value;\n if (\n (t.isArrowFunctionExpression(value) || t.isFunctionExpression(value)) &&\n t.isBlockStatement(value.body)\n ) {\n return value.body;\n }\n return undefined;\n}\n\n/** Whether an `execute` opts into the client via a leading `\"use client\"`. */\nfunction executeIsClient(member: t.ObjectProperty | t.ObjectMethod): boolean {\n return !!executeBody(member)?.directives.some(\n (d) => d.value.value === \"use client\",\n );\n}\n\n/** Whether an `execute` is the `hitl()` human-in-the-loop sentinel. */\nfunction executeIsHitl(member: t.ObjectProperty | t.ObjectMethod): boolean {\n return (\n t.isObjectProperty(member) &&\n t.isCallExpression(member.value) &&\n t.isIdentifier(member.value.callee, { name: \"hitl\" })\n );\n}\n\n/** Drops the `\"use client\"` directive from an `execute` body (kept frontend). */\nfunction stripUseClient(member: t.ObjectProperty | t.ObjectMethod): void {\n const body = executeBody(member);\n if (body) {\n body.directives = body.directives.filter(\n (d) => d.value.value !== \"use client\",\n );\n }\n}\n\n/**\n * The tool's nature, inferred from its (mandatory) `execute` rather than an\n * authored `type`: `hitl()` → `human`; `\"use client\"` → `frontend`; otherwise\n * `backend`. The loader writes the result back as a `type` field (see\n * {@link setToolType}) so the runtime keeps it.\n */\nfunction inferToolType(\n object: t.ObjectExpression,\n filename: string | undefined,\n): ToolType {\n const execute = findMember(object, \"execute\");\n if (!execute) {\n throw new GenerativeCompileError(\n \"every tool must declare an `execute`; use `hitl()` for a \" +\n \"human-in-the-loop tool\",\n filename,\n );\n }\n if (executeIsHitl(execute)) return \"human\";\n return executeIsClient(execute) ? \"frontend\" : \"backend\";\n}\n\n/** Writes the resolved `type` back onto the tool object (replacing any author's). */\nfunction setToolType(object: t.ObjectExpression, type: ToolType): void {\n removeMember(object, \"type\");\n // Append (not prepend) so the inferred type wins over any earlier spread.\n object.properties.push(\n t.objectProperty(t.identifier(\"type\"), t.stringLiteral(type)),\n );\n}\n\nfunction memberName(\n key: t.Node,\n computed: boolean | undefined,\n): string | undefined {\n if (computed) return undefined;\n if (t.isIdentifier(key)) return key.name;\n if (t.isStringLiteral(key)) return key.value;\n return undefined;\n}\n\n/**\n * Removes declarations and import specifiers left unreferenced after region\n * removal, to a fixpoint (a dropped helper frees what it used). Keeps exports,\n * side-effect imports, and possibly-side-effectful initializers.\n */\nfunction pruneUnused(ast: t.File): void {\n const hadSpecifiers = new WeakSet<t.ImportDeclaration>();\n for (const stmt of ast.program.body) {\n if (t.isImportDeclaration(stmt) && stmt.specifiers.length > 0) {\n hadSpecifiers.add(stmt);\n }\n }\n\n let removedSomething = true;\n while (removedSomething) {\n removedSomething = false;\n traverse(ast, {\n Program(path: NodePath<t.Program>) {\n path.scope.crawl();\n const isUnused = (name: string): boolean => {\n const binding = path.scope.getBinding(name);\n return !!binding && !binding.referenced;\n };\n\n path.node.body = path.node.body.filter((stmt) => {\n if (\n (t.isFunctionDeclaration(stmt) || t.isClassDeclaration(stmt)) &&\n stmt.id &&\n isUnused(stmt.id.name)\n ) {\n removedSomething = true;\n return false;\n }\n if (t.isVariableDeclaration(stmt)) {\n stmt.declarations = stmt.declarations.filter((decl) => {\n // Handles destructuring too: drop the declarator only when *every*\n // bound name is unused (else a `const { a } = server` survives and\n // keeps a server import in the client graph). Restricted to plain\n // patterns so a default/computed-key side effect isn't dropped.\n const names = Object.keys(t.getBindingIdentifiers(decl.id));\n if (\n names.length > 0 &&\n isPlainPattern(decl.id) &&\n isRemovableInit(decl.init) &&\n names.every(isUnused)\n ) {\n removedSomething = true;\n return false;\n }\n return true;\n });\n if (stmt.declarations.length === 0) return false;\n }\n return true;\n });\n path.stop();\n },\n });\n }\n\n traverse(ast, {\n Program(path: NodePath<t.Program>) {\n path.scope.crawl();\n for (const stmt of path.node.body) {\n if (!t.isImportDeclaration(stmt)) continue;\n stmt.specifiers = stmt.specifiers.filter((spec) => {\n const binding = path.scope.getBinding(spec.local.name);\n return binding ? binding.referenced : true;\n });\n }\n path.node.body = path.node.body.filter(\n (stmt) =>\n !(\n t.isImportDeclaration(stmt) &&\n stmt.specifiers.length === 0 &&\n hadSpecifiers.has(stmt)\n ),\n );\n path.stop();\n },\n });\n}\n\n/**\n * Whether a binding pattern is side-effect-free to drop: a plain identifier, or\n * an object/array pattern of plain bindings — no default values\n * (`{ a = expr }`) or computed keys (`{ [expr]: a }`), which would evaluate (and\n * thus could have side effects) at destructuring time.\n */\nfunction isPlainPattern(node: t.Node): boolean {\n if (t.isIdentifier(node)) return true;\n if (t.isObjectPattern(node)) {\n return node.properties.every((p) =>\n t.isRestElement(p)\n ? isPlainPattern(p.argument)\n : !p.computed && isPlainPattern(p.value),\n );\n }\n if (t.isArrayPattern(node)) {\n return node.elements.every((el) => el == null || isPlainPattern(el));\n }\n return false; // AssignmentPattern (default), member expr, etc.\n}\n\n/** Whether a variable initializer is safe to drop (no observable side effects). */\nfunction isRemovableInit(node: t.Expression | null | undefined): boolean {\n if (node == null) return true;\n if (t.isTSAsExpression(node) || t.isTSSatisfiesExpression(node)) {\n return isRemovableInit(node.expression);\n }\n // Containers are removable only if every element is — a nested call (e.g.\n // `[track()]`) has an observable side effect that dropping would lose.\n if (t.isArrayExpression(node)) {\n return node.elements.every(\n (el) => el == null || (t.isExpression(el) && isRemovableInit(el)),\n );\n }\n if (t.isObjectExpression(node)) {\n return node.properties.every(\n (p) =>\n t.isObjectProperty(p) &&\n !p.computed &&\n t.isExpression(p.value) &&\n isRemovableInit(p.value),\n );\n }\n if (t.isTemplateLiteral(node)) {\n return node.expressions.every(\n (e) => t.isExpression(e) && isRemovableInit(e),\n );\n }\n return (\n t.isArrowFunctionExpression(node) ||\n t.isFunctionExpression(node) ||\n t.isClassExpression(node) ||\n t.isIdentifier(node) ||\n // non-computed only — `obj[fn()]` could hide a side-effectful key\n (t.isMemberExpression(node) && !node.computed) ||\n t.isJSXElement(node) ||\n t.isJSXFragment(node) ||\n t.isLiteral(node)\n );\n}\n"],"mappings":";;;;;;AAQA,MAAM,WACJ,OAAO,cAAc,aAAa,YAAa,UAAkB;AAEnE,MAAM,WACJ,OAAO,cAAc,aAAa,YAAa,UAAkB;;AA6BnE,IAAa,yBAAb,cAA4C,MAAM;CAChD,YAAY,SAAiB,UAAmB;EAC9C,MAAM,sBAAsB,WAAW,IAAI,SAAS,KAAK,GAAG,GAAG,SAAS;EACxE,KAAK,OAAO;CACd;AACF;;AAGA,SAAgB,mBAAmB,MAA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Ae,IAAI,GACvB,OAAO,KAAK,SAAS,OAAO,OAAO,MAAM,QAAQ,eAAe,EAAE,CAAC;CAErE,OAAO;AACT;;AAGA,SAAS,gBAAgB,MAAgD;CACvE,IAAI,QAAQ,MAAM,OAAO;CACzB,IAAI,EAAE,iBAAiB,IAAI,KAAK,EAAE,wBAAwB,IAAI,GAC5D,OAAO,gBAAgB,KAAK,UAAU;CAIxC,IAAI,EAAE,kBAAkB,IAAI,GAC1B,OAAO,KAAK,SAAS,OAClB,OAAO,MAAM,QAAS,EAAE,aAAa,EAAE,KAAK,gBAAgB,EAAE,CACjE;CAEF,IAAI,EAAE,mBAAmB,IAAI,GAC3B,OAAO,KAAK,WAAW,OACpB,MACC,EAAE,iBAAiB,CAAC,KACpB,CAAC,EAAE,YACH,EAAE,aAAa,EAAE,KAAK,KACtB,gBAAgB,EAAE,KAAK,CAC3B;CAEF,IAAI,EAAE,kBAAkB,IAAI,GAC1B,OAAO,KAAK,YAAY,OACrB,MAAM,EAAE,aAAa,CAAC,KAAK,gBAAgB,CAAC,CAC/C;CAEF,OACE,EAAE,0BAA0B,IAAI,KAChC,EAAE,qBAAqB,IAAI,KAC3B,EAAE,kBAAkB,IAAI,KACxB,EAAE,aAAa,IAAI,KAElB,EAAE,mBAAmB,IAAI,KAAK,CAAC,KAAK,YACrC,EAAE,aAAa,IAAI,KACnB,EAAE,cAAc,IAAI,KACpB,EAAE,UAAU,IAAI;AAEpB"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
//#region src/constants.d.ts
|
|
2
|
+
/** The directive a module uses to opt into generative compilation. */
|
|
3
|
+
declare const DIRECTIVE = "use generative";
|
|
4
|
+
/** Build target a generative module is compiled for. */
|
|
5
|
+
type Target = "client" | "server";
|
|
6
|
+
//#endregion
|
|
7
|
+
export { DIRECTIVE, Target };
|
|
8
|
+
//# sourceMappingURL=constants.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.d.ts","names":[],"sources":["../src/constants.ts"],"mappings":";;cACa,SAAA;;KAGD,MAAA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["/** The directive a module uses to opt into generative compilation. */\nexport const DIRECTIVE = \"use generative\";\n\n/** Build target a generative module is compiled for. */\nexport type Target = \"client\" | \"server\";\n"],"mappings":";;AACA,MAAa,YAAY"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { DIRECTIVE, Target } from "./constants.js";
|
|
2
|
+
import { CompileOptions, CompileResult, GenerativeCompileError, ToolType, compileGenerative, isGenerativeModule } from "./compile.js";
|
|
3
|
+
export { type CompileOptions, type CompileResult, DIRECTIVE, GenerativeCompileError, type Target, type ToolType, compileGenerative, isGenerativeModule };
|
package/dist/index.js
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@assistant-ui/x-generative-compiler",
|
|
3
|
+
"private": false,
|
|
4
|
+
"version": "0.0.1",
|
|
5
|
+
"description": "Internal: the framework-agnostic \"use generative\" compiler that splits a colocated tool (schema + server-only execute + client-only render) into per-target builds. Shared by @assistant-ui/next and @assistant-ui/vite.",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"assistant-ui",
|
|
8
|
+
"generative",
|
|
9
|
+
"compiler",
|
|
10
|
+
"use generative",
|
|
11
|
+
"rsc",
|
|
12
|
+
"internal"
|
|
13
|
+
],
|
|
14
|
+
"author": "AgentbaseAI Inc.",
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"type": "module",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"default": "./dist/index.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"main": "./dist/index.js",
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"files": [
|
|
26
|
+
"dist",
|
|
27
|
+
"src",
|
|
28
|
+
"README.md"
|
|
29
|
+
],
|
|
30
|
+
"sideEffects": false,
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "aui-build",
|
|
33
|
+
"test": "vitest run",
|
|
34
|
+
"test:watch": "vitest"
|
|
35
|
+
},
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@babel/generator": "^7.28.3",
|
|
38
|
+
"@babel/parser": "^7.28.4",
|
|
39
|
+
"@babel/traverse": "^7.28.4",
|
|
40
|
+
"@babel/types": "^7.28.4"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@assistant-ui/x-buildutils": "workspace:*",
|
|
44
|
+
"@types/babel__generator": "^7.27.0",
|
|
45
|
+
"@types/babel__traverse": "^7.28.0",
|
|
46
|
+
"@types/node": "^25.9.1",
|
|
47
|
+
"vitest": "^4.1.7"
|
|
48
|
+
},
|
|
49
|
+
"publishConfig": {
|
|
50
|
+
"access": "public",
|
|
51
|
+
"provenance": true
|
|
52
|
+
},
|
|
53
|
+
"homepage": "https://www.assistant-ui.com/",
|
|
54
|
+
"repository": {
|
|
55
|
+
"type": "git",
|
|
56
|
+
"url": "git+https://github.com/assistant-ui/assistant-ui.git",
|
|
57
|
+
"directory": "packages/x-generative-compiler"
|
|
58
|
+
},
|
|
59
|
+
"bugs": {
|
|
60
|
+
"url": "https://github.com/assistant-ui/assistant-ui/issues"
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
compileGenerative,
|
|
4
|
+
isGenerativeModule,
|
|
5
|
+
GenerativeCompileError,
|
|
6
|
+
} from "./compile";
|
|
7
|
+
|
|
8
|
+
const source = `"use generative";
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
import { db } from "@/db";
|
|
11
|
+
import { track } from "@/analytics";
|
|
12
|
+
import { Chart } from "@/ui/chart";
|
|
13
|
+
import { defineToolkit } from "@assistant-ui/react";
|
|
14
|
+
|
|
15
|
+
export default defineToolkit({
|
|
16
|
+
weather: {
|
|
17
|
+
description: "Show the weather.",
|
|
18
|
+
parameters: z.object({ city: z.string() }),
|
|
19
|
+
execute: async ({ city }) => db.weather.get(city),
|
|
20
|
+
render: (props) => <Chart data={props} />,
|
|
21
|
+
},
|
|
22
|
+
toast: {
|
|
23
|
+
description: "Show a toast.",
|
|
24
|
+
parameters: z.object({ msg: z.string() }),
|
|
25
|
+
execute: async ({ msg }) => {
|
|
26
|
+
"use client";
|
|
27
|
+
return track(msg);
|
|
28
|
+
},
|
|
29
|
+
render: (props) => <div>{props.msg}</div>,
|
|
30
|
+
},
|
|
31
|
+
});
|
|
32
|
+
`;
|
|
33
|
+
|
|
34
|
+
const server = () => compileGenerative(source, { target: "server" }).code;
|
|
35
|
+
const client = () => compileGenerative(source, { target: "client" }).code;
|
|
36
|
+
|
|
37
|
+
describe("compileGenerative — server target", () => {
|
|
38
|
+
const code = server();
|
|
39
|
+
|
|
40
|
+
it("keeps the schema", () => {
|
|
41
|
+
expect(code).toContain('import { z } from "zod"');
|
|
42
|
+
expect(code).toContain("z.object");
|
|
43
|
+
expect(code).toContain('description: "Show the weather."');
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it("keeps a backend execute and guards it with server-only", () => {
|
|
47
|
+
expect(code).toContain('import "server-only"');
|
|
48
|
+
expect(code).toContain("db.weather.get");
|
|
49
|
+
expect(code).toContain('import { db } from "@/db"');
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it("writes the inferred type back onto each tool", () => {
|
|
53
|
+
expect(code).toContain('type: "backend"'); // weather: execute, no "use client"
|
|
54
|
+
expect(code).toContain('type: "frontend"'); // toast: execute + "use client"
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it("drops all render and its client imports", () => {
|
|
58
|
+
expect(code).not.toContain("Chart");
|
|
59
|
+
expect(code).not.toContain("<div");
|
|
60
|
+
expect(code).not.toMatch(/render\s*:/);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it("drops a frontend execute and its client imports", () => {
|
|
64
|
+
expect(code).not.toContain("track");
|
|
65
|
+
expect(code).not.toContain("@/analytics");
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it("strips the use generative directive and adds no use client", () => {
|
|
69
|
+
expect(code).not.toContain("use generative");
|
|
70
|
+
expect(code).not.toContain("use client");
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
describe("compileGenerative — client target", () => {
|
|
75
|
+
const code = client();
|
|
76
|
+
|
|
77
|
+
it("marks the module use client and keeps render", () => {
|
|
78
|
+
expect(code.trimStart().startsWith('"use client"')).toBe(true);
|
|
79
|
+
expect(code).toContain("<Chart");
|
|
80
|
+
expect(code).toContain("<div");
|
|
81
|
+
expect(code).toContain('import { Chart } from "@/ui/chart"');
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it("keeps the schema for parsing", () => {
|
|
85
|
+
expect(code).toContain('import { z } from "zod"');
|
|
86
|
+
expect(code).toContain("z.object");
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("keeps a frontend execute (and drops its `use client` marker)", () => {
|
|
90
|
+
expect(code).toContain("track(msg)");
|
|
91
|
+
expect(code).toContain("@/analytics");
|
|
92
|
+
// exactly one "use client" — the module directive, not the execute body's
|
|
93
|
+
expect(code.match(/use client/g)?.length).toBe(1);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it("writes the inferred type back onto each tool", () => {
|
|
97
|
+
expect(code).toContain('type: "backend"'); // weather (schema-only on client)
|
|
98
|
+
expect(code).toContain('type: "frontend"'); // toast
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it("drops a backend execute and its server-only imports", () => {
|
|
102
|
+
expect(code).not.toContain("db.weather.get");
|
|
103
|
+
expect(code).not.toContain("@/db");
|
|
104
|
+
expect(code).not.toContain("server-only");
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
describe("compileGenerative — local dead-code elimination", () => {
|
|
109
|
+
const withHelpers = `"use generative";
|
|
110
|
+
import { z } from "zod";
|
|
111
|
+
import { cn } from "@/lib/utils";
|
|
112
|
+
import { db } from "@/db";
|
|
113
|
+
|
|
114
|
+
const Badge = ({ label }) => <span className={cn("badge")}>{label}</span>;
|
|
115
|
+
import { defineToolkit } from "@assistant-ui/react";
|
|
116
|
+
|
|
117
|
+
export default defineToolkit({
|
|
118
|
+
weather: {
|
|
119
|
+
description: "weather",
|
|
120
|
+
parameters: z.object({ city: z.string() }),
|
|
121
|
+
execute: async ({ city }) => db.weather.get(city),
|
|
122
|
+
render: (props) => <Badge label={props.city} />,
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
`;
|
|
126
|
+
|
|
127
|
+
it("strips a local helper component (and its imports) from the server", () => {
|
|
128
|
+
const code = compileGenerative(withHelpers, { target: "server" }).code;
|
|
129
|
+
expect(code).not.toContain("Badge");
|
|
130
|
+
expect(code).not.toContain("@/lib/utils");
|
|
131
|
+
expect(code).not.toContain("className");
|
|
132
|
+
expect(code).toContain("db.weather.get");
|
|
133
|
+
expect(code).toContain('import "server-only"');
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it("keeps the local helper on the client", () => {
|
|
137
|
+
const code = compileGenerative(withHelpers, { target: "client" }).code;
|
|
138
|
+
expect(code).toContain("Badge");
|
|
139
|
+
expect(code).toContain("@/lib/utils");
|
|
140
|
+
expect(code).not.toContain("@/db");
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it("prunes an unused destructured server binding from the client", () => {
|
|
144
|
+
const src = `"use generative";
|
|
145
|
+
import { defineToolkit } from "@assistant-ui/react";
|
|
146
|
+
import { db } from "@/db";
|
|
147
|
+
const { getWeather } = db;
|
|
148
|
+
export default defineToolkit({
|
|
149
|
+
weather: {
|
|
150
|
+
execute: async ({ city }) => getWeather(city),
|
|
151
|
+
render: () => null,
|
|
152
|
+
},
|
|
153
|
+
});`;
|
|
154
|
+
const client = compileGenerative(src, { target: "client" }).code;
|
|
155
|
+
expect(client).not.toContain("getWeather");
|
|
156
|
+
expect(client).not.toContain("@/db");
|
|
157
|
+
expect(compileGenerative(src, { target: "server" }).code).toContain(
|
|
158
|
+
"getWeather",
|
|
159
|
+
);
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
describe("compileGenerative — diagnostics", () => {
|
|
164
|
+
it("rejects a module without the directive", () => {
|
|
165
|
+
expect(() =>
|
|
166
|
+
compileGenerative(`export default {} satisfies Toolkit;`, {
|
|
167
|
+
target: "server",
|
|
168
|
+
}),
|
|
169
|
+
).toThrow(GenerativeCompileError);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it("strips a define-style wrapper and prunes its import", () => {
|
|
173
|
+
const wrapped = `"use generative";
|
|
174
|
+
import { z } from "zod";
|
|
175
|
+
import { db } from "@/db";
|
|
176
|
+
import { defineToolkit } from "@assistant-ui/react";
|
|
177
|
+
export default defineToolkit({
|
|
178
|
+
weather: {
|
|
179
|
+
parameters: z.object({ city: z.string() }),
|
|
180
|
+
execute: async ({ city }) => db.get(city),
|
|
181
|
+
render: (props) => <span>{props.city}</span>,
|
|
182
|
+
},
|
|
183
|
+
});`;
|
|
184
|
+
const serverCode = compileGenerative(wrapped, { target: "server" }).code;
|
|
185
|
+
// wrapper + its import gone; bare object with execute remains.
|
|
186
|
+
expect(serverCode).not.toContain("defineToolkit");
|
|
187
|
+
expect(serverCode).not.toContain("@assistant-ui/react");
|
|
188
|
+
expect(serverCode).toContain("db.get");
|
|
189
|
+
expect(serverCode).not.toContain("<span");
|
|
190
|
+
|
|
191
|
+
const clientCode = compileGenerative(wrapped, { target: "client" }).code;
|
|
192
|
+
expect(clientCode).not.toContain("defineToolkit");
|
|
193
|
+
expect(clientCode).not.toContain("@assistant-ui/react");
|
|
194
|
+
expect(clientCode).toContain("<span");
|
|
195
|
+
expect(clientCode).not.toContain("@/db");
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
it("requires the defineToolkit() wrapper", () => {
|
|
199
|
+
expect(() =>
|
|
200
|
+
compileGenerative(
|
|
201
|
+
`"use generative";\nexport default { a: { execute: async () => 1 } };`,
|
|
202
|
+
{ target: "server" },
|
|
203
|
+
),
|
|
204
|
+
).toThrow(/defineToolkit/);
|
|
205
|
+
expect(() =>
|
|
206
|
+
compileGenerative(`"use generative";\nexport default makeToolkit();`, {
|
|
207
|
+
target: "server",
|
|
208
|
+
}),
|
|
209
|
+
).toThrow(/defineToolkit/);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
it("rejects a tool that isn't an inline object literal", () => {
|
|
213
|
+
expect(() =>
|
|
214
|
+
compileGenerative(
|
|
215
|
+
`"use generative";\nimport { defineToolkit } from "@assistant-ui/react";\nexport default defineToolkit({ weather: makeTool() });`,
|
|
216
|
+
{ target: "server" },
|
|
217
|
+
),
|
|
218
|
+
).toThrow(/inline object literal/);
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
it("requires a render for human/frontend tools", () => {
|
|
222
|
+
expect(() =>
|
|
223
|
+
compileGenerative(
|
|
224
|
+
`"use generative";\nimport { defineToolkit, hitl } from "@assistant-ui/react";\nexport default defineToolkit({ ask: { execute: hitl() } });`,
|
|
225
|
+
{ target: "client" },
|
|
226
|
+
),
|
|
227
|
+
).toThrow(/must declare a `render`/);
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
it("requires every tool to declare an execute", () => {
|
|
231
|
+
expect(() =>
|
|
232
|
+
compileGenerative(
|
|
233
|
+
`"use generative";\nimport { defineToolkit } from "@assistant-ui/react";\nexport default defineToolkit({ ask: { render: () => null } });`,
|
|
234
|
+
{ target: "client" },
|
|
235
|
+
),
|
|
236
|
+
).toThrow(/must declare an `execute`/);
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
it("infers `human` from execute: hitl() and drops it on both builds", () => {
|
|
240
|
+
const src = `"use generative";\nimport { defineToolkit, hitl } from "@assistant-ui/react";\nexport default defineToolkit({ ask: { execute: hitl(), render: () => null } });`;
|
|
241
|
+
const server = compileGenerative(src, { target: "server" }).code;
|
|
242
|
+
expect(server).toContain('type: "human"');
|
|
243
|
+
expect(server).not.toContain("hitl"); // sentinel + its import pruned
|
|
244
|
+
const client = compileGenerative(src, { target: "client" }).code;
|
|
245
|
+
expect(client).toContain('type: "human"');
|
|
246
|
+
expect(client).not.toContain("hitl");
|
|
247
|
+
expect(client).toContain("render");
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
it("infers `frontend` from a `use client` execute and keeps it client-side", () => {
|
|
251
|
+
const src = `"use generative";\nimport { defineToolkit } from "@assistant-ui/react";\nimport { track } from "@/a";\nexport default defineToolkit({ t: { execute: async () => { "use client"; return track(); }, render: () => null } });`;
|
|
252
|
+
const server = compileGenerative(src, { target: "server" }).code;
|
|
253
|
+
expect(server).toContain('type: "frontend"');
|
|
254
|
+
expect(server).not.toContain("track"); // frontend execute dropped on server
|
|
255
|
+
const client = compileGenerative(src, { target: "client" }).code;
|
|
256
|
+
expect(client).toContain('type: "frontend"');
|
|
257
|
+
expect(client).toContain("track()");
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
it("detects generative modules by directive", () => {
|
|
261
|
+
expect(isGenerativeModule(`"use generative";\nexport default {};`)).toBe(
|
|
262
|
+
true,
|
|
263
|
+
);
|
|
264
|
+
expect(isGenerativeModule(`// a comment\n"use generative";\n`)).toBe(true);
|
|
265
|
+
expect(isGenerativeModule(`export default {};`)).toBe(false);
|
|
266
|
+
});
|
|
267
|
+
});
|
package/src/compile.ts
ADDED
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
import { parse } from "@babel/parser";
|
|
2
|
+
import _traverse, { type NodePath } from "@babel/traverse";
|
|
3
|
+
import _generate from "@babel/generator";
|
|
4
|
+
import * as t from "@babel/types";
|
|
5
|
+
import { DIRECTIVE, type Target } from "./constants";
|
|
6
|
+
|
|
7
|
+
// @babel/traverse and @babel/generator are CJS; their default export is the
|
|
8
|
+
// function itself under some interop and `{ default }` under others.
|
|
9
|
+
const traverse = (
|
|
10
|
+
typeof _traverse === "function" ? _traverse : (_traverse as any).default
|
|
11
|
+
) as typeof _traverse;
|
|
12
|
+
const generate = (
|
|
13
|
+
typeof _generate === "function" ? _generate : (_generate as any).default
|
|
14
|
+
) as typeof _generate;
|
|
15
|
+
|
|
16
|
+
export type ToolType = "frontend" | "backend" | "human";
|
|
17
|
+
|
|
18
|
+
export interface CompileOptions {
|
|
19
|
+
/** Which build target to emit. */
|
|
20
|
+
target: Target;
|
|
21
|
+
/** Source filename, used for error messages and source maps. */
|
|
22
|
+
filename?: string;
|
|
23
|
+
/** Emit a source map alongside the code. */
|
|
24
|
+
sourceMaps?: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Whether the `server` target prepends `import "server-only"` when it keeps a
|
|
27
|
+
* backend `execute`. Defaults to `true` (the Next.js/RSC convention, where the
|
|
28
|
+
* guard fires via the `react-server` condition). Set `false` for bundlers
|
|
29
|
+
* without a `react-server` layer (e.g. a Vite/TanStack Start `ssr` build),
|
|
30
|
+
* where the split is already structural and importing `server-only` would
|
|
31
|
+
* throw — see the Vite integration.
|
|
32
|
+
*/
|
|
33
|
+
injectServerOnly?: boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface CompileResult {
|
|
37
|
+
code: string;
|
|
38
|
+
map?: object | null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Thrown when a `"use generative"` file violates an authoring constraint. */
|
|
42
|
+
export class GenerativeCompileError extends Error {
|
|
43
|
+
constructor(message: string, filename?: string) {
|
|
44
|
+
super(`[assistant-ui/next]${filename ? ` ${filename}:` : ""} ${message}`);
|
|
45
|
+
this.name = "GenerativeCompileError";
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Whether a source string opts into generative compilation via the directive. */
|
|
50
|
+
export function isGenerativeModule(code: string): boolean {
|
|
51
|
+
// The directive must be a leading statement, preceded only by an optional BOM,
|
|
52
|
+
// whitespace, and line/block comments. Scanned linearly — a regex over the
|
|
53
|
+
// comment prefix is prone to catastrophic backtracking on crafted input.
|
|
54
|
+
let i = code.charCodeAt(0) === 0xfeff ? 1 : 0;
|
|
55
|
+
for (;;) {
|
|
56
|
+
while (i < code.length && /\s/.test(code[i]!)) i++;
|
|
57
|
+
if (code.startsWith("//", i)) {
|
|
58
|
+
const nl = code.indexOf("\n", i);
|
|
59
|
+
if (nl === -1) return false;
|
|
60
|
+
i = nl + 1;
|
|
61
|
+
} else if (code.startsWith("/*", i)) {
|
|
62
|
+
const end = code.indexOf("*/", i + 2);
|
|
63
|
+
if (end === -1) return false;
|
|
64
|
+
i = end + 2;
|
|
65
|
+
} else {
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return (
|
|
70
|
+
code.startsWith(`"${DIRECTIVE}"`, i) || code.startsWith(`'${DIRECTIVE}'`, i)
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Rewrites a `"use generative"` module for a single build target, keeping only the
|
|
76
|
+
* regions that target needs and pruning the imports the dropped regions used.
|
|
77
|
+
*/
|
|
78
|
+
export function compileGenerative(
|
|
79
|
+
code: string,
|
|
80
|
+
options: CompileOptions,
|
|
81
|
+
): CompileResult {
|
|
82
|
+
const { target, filename } = options;
|
|
83
|
+
|
|
84
|
+
const ast = parse(code, {
|
|
85
|
+
sourceType: "module",
|
|
86
|
+
plugins: ["typescript", "jsx", "explicitResourceManagement"],
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
if (!ast.program.directives.some((d) => d.value.value === DIRECTIVE)) {
|
|
90
|
+
throw new GenerativeCompileError(
|
|
91
|
+
`missing "${DIRECTIVE}" directive`,
|
|
92
|
+
filename,
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const object = findDefaultExportObject(ast, filename);
|
|
97
|
+
|
|
98
|
+
let keptRender = false;
|
|
99
|
+
let keptBackendExecute = false;
|
|
100
|
+
|
|
101
|
+
for (const entry of object.properties) {
|
|
102
|
+
const value = entryValue(entry);
|
|
103
|
+
if (!value) {
|
|
104
|
+
// A non-inline tool (spread, method, or a call like `makeTool()`) can't be
|
|
105
|
+
// analyzed, so its `execute` would pass through to the client unstripped.
|
|
106
|
+
throw new GenerativeCompileError(
|
|
107
|
+
"each tool must be an inline object literal (`name: { ... }`) so its " +
|
|
108
|
+
"`execute` can be routed",
|
|
109
|
+
filename,
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Nature is inferred from `execute` (see inferToolType), not an authored
|
|
114
|
+
// `type`. The resolved type is written back below so the runtime keeps it.
|
|
115
|
+
const type = inferToolType(value, filename);
|
|
116
|
+
const hasRender = !!findMember(value, "render");
|
|
117
|
+
const execute = findMember(value, "execute");
|
|
118
|
+
|
|
119
|
+
if ((type === "frontend" || type === "human") && !hasRender) {
|
|
120
|
+
throw new GenerativeCompileError(
|
|
121
|
+
`a ${type} tool must declare a \`render\` (it has no server execute to show otherwise)`,
|
|
122
|
+
filename,
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (target === "client") {
|
|
127
|
+
// A frontend execute stays (its `"use client"` marker is no longer needed
|
|
128
|
+
// once the module is client); a backend execute and a human `hitl()`
|
|
129
|
+
// sentinel are both dropped.
|
|
130
|
+
if (execute && type === "frontend") stripUseClient(execute);
|
|
131
|
+
else if (execute) removeMember(value, "execute");
|
|
132
|
+
if (hasRender) keptRender = true;
|
|
133
|
+
} else {
|
|
134
|
+
// server: render is never needed; only a backend execute survives.
|
|
135
|
+
if (hasRender) removeMember(value, "render");
|
|
136
|
+
if (execute && type !== "backend") removeMember(value, "execute");
|
|
137
|
+
if (execute && type === "backend") keptBackendExecute = true;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
setToolType(value, type);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
pruneUnused(ast);
|
|
144
|
+
|
|
145
|
+
// Replace the module directives with the target-appropriate one.
|
|
146
|
+
ast.program.directives = ast.program.directives.filter(
|
|
147
|
+
(d) => d.value.value !== DIRECTIVE && d.value.value !== "use client",
|
|
148
|
+
);
|
|
149
|
+
if (target === "client" && keptRender) {
|
|
150
|
+
ast.program.directives.unshift(
|
|
151
|
+
t.directive(t.directiveLiteral("use client")),
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
if (
|
|
155
|
+
target === "server" &&
|
|
156
|
+
keptBackendExecute &&
|
|
157
|
+
(options.injectServerOnly ?? true)
|
|
158
|
+
) {
|
|
159
|
+
ast.program.body.unshift(
|
|
160
|
+
t.importDeclaration([], t.stringLiteral("server-only")),
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const result = generate(
|
|
165
|
+
ast,
|
|
166
|
+
{
|
|
167
|
+
sourceMaps: options.sourceMaps ?? false,
|
|
168
|
+
filename,
|
|
169
|
+
jsescOption: { minimal: true },
|
|
170
|
+
},
|
|
171
|
+
code,
|
|
172
|
+
);
|
|
173
|
+
|
|
174
|
+
return { code: result.code, map: result.map };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function findDefaultExportObject(
|
|
178
|
+
ast: t.File,
|
|
179
|
+
filename: string | undefined,
|
|
180
|
+
): t.ObjectExpression {
|
|
181
|
+
let object: t.ObjectExpression | null = null;
|
|
182
|
+
let sawDefault = false;
|
|
183
|
+
|
|
184
|
+
for (const stmt of ast.program.body) {
|
|
185
|
+
if (!t.isExportDefaultDeclaration(stmt)) continue;
|
|
186
|
+
sawDefault = true;
|
|
187
|
+
object = unwrapDefineToolkit(stmt.declaration);
|
|
188
|
+
// Emit the bare object literal, dropping the `defineToolkit(...)` wrapper
|
|
189
|
+
// (and the import it pulled).
|
|
190
|
+
if (object) stmt.declaration = object;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (!sawDefault) {
|
|
194
|
+
throw new GenerativeCompileError("missing a default export", filename);
|
|
195
|
+
}
|
|
196
|
+
if (!object) {
|
|
197
|
+
throw new GenerativeCompileError(
|
|
198
|
+
"the default export must be `defineToolkit({ ... })` (imported from " +
|
|
199
|
+
'"@assistant-ui/react"); wrapping is required so a backend `execute` ' +
|
|
200
|
+
"can't be authored in a way that reaches the client",
|
|
201
|
+
filename,
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
return object;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Unwraps the required `defineToolkit({ ... })` wrapper (through `satisfies`/`as`
|
|
209
|
+
* and parens) to the underlying object literal. Anything else — a bare object, a
|
|
210
|
+
* `satisfies Toolkit` without the wrapper, some other call — yields `null` so the
|
|
211
|
+
* caller errors.
|
|
212
|
+
*/
|
|
213
|
+
function unwrapDefineToolkit(node: t.Node): t.ObjectExpression | null {
|
|
214
|
+
if (t.isTSSatisfiesExpression(node) || t.isTSAsExpression(node)) {
|
|
215
|
+
return unwrapDefineToolkit(node.expression);
|
|
216
|
+
}
|
|
217
|
+
if (t.isParenthesizedExpression(node)) {
|
|
218
|
+
return unwrapDefineToolkit(node.expression);
|
|
219
|
+
}
|
|
220
|
+
if (
|
|
221
|
+
t.isCallExpression(node) &&
|
|
222
|
+
t.isIdentifier(node.callee, { name: "defineToolkit" }) &&
|
|
223
|
+
t.isObjectExpression(node.arguments[0])
|
|
224
|
+
) {
|
|
225
|
+
return node.arguments[0];
|
|
226
|
+
}
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
type Entry = t.ObjectExpression["properties"][number];
|
|
231
|
+
|
|
232
|
+
function entryValue(entry: Entry): t.ObjectExpression | null {
|
|
233
|
+
if (t.isObjectProperty(entry) && t.isObjectExpression(entry.value)) {
|
|
234
|
+
return entry.value;
|
|
235
|
+
}
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** A member of an entry object: `render`/`execute`/`type`, as property or method. */
|
|
240
|
+
function findMember(
|
|
241
|
+
object: t.ObjectExpression,
|
|
242
|
+
name: string,
|
|
243
|
+
): t.ObjectProperty | t.ObjectMethod | undefined {
|
|
244
|
+
return object.properties.find(
|
|
245
|
+
(p): p is t.ObjectProperty | t.ObjectMethod =>
|
|
246
|
+
(t.isObjectProperty(p) || t.isObjectMethod(p)) &&
|
|
247
|
+
memberName(p.key, p.computed) === name,
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function removeMember(object: t.ObjectExpression, name: string): void {
|
|
252
|
+
object.properties = object.properties.filter(
|
|
253
|
+
(p) =>
|
|
254
|
+
!(
|
|
255
|
+
(t.isObjectProperty(p) || t.isObjectMethod(p)) &&
|
|
256
|
+
memberName(p.key, p.computed) === name
|
|
257
|
+
),
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** The `BlockStatement` body of an `execute` member, if it has one. */
|
|
262
|
+
function executeBody(
|
|
263
|
+
member: t.ObjectProperty | t.ObjectMethod,
|
|
264
|
+
): t.BlockStatement | undefined {
|
|
265
|
+
if (t.isObjectMethod(member)) return member.body;
|
|
266
|
+
const value = member.value;
|
|
267
|
+
if (
|
|
268
|
+
(t.isArrowFunctionExpression(value) || t.isFunctionExpression(value)) &&
|
|
269
|
+
t.isBlockStatement(value.body)
|
|
270
|
+
) {
|
|
271
|
+
return value.body;
|
|
272
|
+
}
|
|
273
|
+
return undefined;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Whether an `execute` opts into the client via a leading `"use client"`. */
|
|
277
|
+
function executeIsClient(member: t.ObjectProperty | t.ObjectMethod): boolean {
|
|
278
|
+
return !!executeBody(member)?.directives.some(
|
|
279
|
+
(d) => d.value.value === "use client",
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** Whether an `execute` is the `hitl()` human-in-the-loop sentinel. */
|
|
284
|
+
function executeIsHitl(member: t.ObjectProperty | t.ObjectMethod): boolean {
|
|
285
|
+
return (
|
|
286
|
+
t.isObjectProperty(member) &&
|
|
287
|
+
t.isCallExpression(member.value) &&
|
|
288
|
+
t.isIdentifier(member.value.callee, { name: "hitl" })
|
|
289
|
+
);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Drops the `"use client"` directive from an `execute` body (kept frontend). */
|
|
293
|
+
function stripUseClient(member: t.ObjectProperty | t.ObjectMethod): void {
|
|
294
|
+
const body = executeBody(member);
|
|
295
|
+
if (body) {
|
|
296
|
+
body.directives = body.directives.filter(
|
|
297
|
+
(d) => d.value.value !== "use client",
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* The tool's nature, inferred from its (mandatory) `execute` rather than an
|
|
304
|
+
* authored `type`: `hitl()` → `human`; `"use client"` → `frontend`; otherwise
|
|
305
|
+
* `backend`. The loader writes the result back as a `type` field (see
|
|
306
|
+
* {@link setToolType}) so the runtime keeps it.
|
|
307
|
+
*/
|
|
308
|
+
function inferToolType(
|
|
309
|
+
object: t.ObjectExpression,
|
|
310
|
+
filename: string | undefined,
|
|
311
|
+
): ToolType {
|
|
312
|
+
const execute = findMember(object, "execute");
|
|
313
|
+
if (!execute) {
|
|
314
|
+
throw new GenerativeCompileError(
|
|
315
|
+
"every tool must declare an `execute`; use `hitl()` for a " +
|
|
316
|
+
"human-in-the-loop tool",
|
|
317
|
+
filename,
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
if (executeIsHitl(execute)) return "human";
|
|
321
|
+
return executeIsClient(execute) ? "frontend" : "backend";
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** Writes the resolved `type` back onto the tool object (replacing any author's). */
|
|
325
|
+
function setToolType(object: t.ObjectExpression, type: ToolType): void {
|
|
326
|
+
removeMember(object, "type");
|
|
327
|
+
// Append (not prepend) so the inferred type wins over any earlier spread.
|
|
328
|
+
object.properties.push(
|
|
329
|
+
t.objectProperty(t.identifier("type"), t.stringLiteral(type)),
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function memberName(
|
|
334
|
+
key: t.Node,
|
|
335
|
+
computed: boolean | undefined,
|
|
336
|
+
): string | undefined {
|
|
337
|
+
if (computed) return undefined;
|
|
338
|
+
if (t.isIdentifier(key)) return key.name;
|
|
339
|
+
if (t.isStringLiteral(key)) return key.value;
|
|
340
|
+
return undefined;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Removes declarations and import specifiers left unreferenced after region
|
|
345
|
+
* removal, to a fixpoint (a dropped helper frees what it used). Keeps exports,
|
|
346
|
+
* side-effect imports, and possibly-side-effectful initializers.
|
|
347
|
+
*/
|
|
348
|
+
function pruneUnused(ast: t.File): void {
|
|
349
|
+
const hadSpecifiers = new WeakSet<t.ImportDeclaration>();
|
|
350
|
+
for (const stmt of ast.program.body) {
|
|
351
|
+
if (t.isImportDeclaration(stmt) && stmt.specifiers.length > 0) {
|
|
352
|
+
hadSpecifiers.add(stmt);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
let removedSomething = true;
|
|
357
|
+
while (removedSomething) {
|
|
358
|
+
removedSomething = false;
|
|
359
|
+
traverse(ast, {
|
|
360
|
+
Program(path: NodePath<t.Program>) {
|
|
361
|
+
path.scope.crawl();
|
|
362
|
+
const isUnused = (name: string): boolean => {
|
|
363
|
+
const binding = path.scope.getBinding(name);
|
|
364
|
+
return !!binding && !binding.referenced;
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
path.node.body = path.node.body.filter((stmt) => {
|
|
368
|
+
if (
|
|
369
|
+
(t.isFunctionDeclaration(stmt) || t.isClassDeclaration(stmt)) &&
|
|
370
|
+
stmt.id &&
|
|
371
|
+
isUnused(stmt.id.name)
|
|
372
|
+
) {
|
|
373
|
+
removedSomething = true;
|
|
374
|
+
return false;
|
|
375
|
+
}
|
|
376
|
+
if (t.isVariableDeclaration(stmt)) {
|
|
377
|
+
stmt.declarations = stmt.declarations.filter((decl) => {
|
|
378
|
+
// Handles destructuring too: drop the declarator only when *every*
|
|
379
|
+
// bound name is unused (else a `const { a } = server` survives and
|
|
380
|
+
// keeps a server import in the client graph). Restricted to plain
|
|
381
|
+
// patterns so a default/computed-key side effect isn't dropped.
|
|
382
|
+
const names = Object.keys(t.getBindingIdentifiers(decl.id));
|
|
383
|
+
if (
|
|
384
|
+
names.length > 0 &&
|
|
385
|
+
isPlainPattern(decl.id) &&
|
|
386
|
+
isRemovableInit(decl.init) &&
|
|
387
|
+
names.every(isUnused)
|
|
388
|
+
) {
|
|
389
|
+
removedSomething = true;
|
|
390
|
+
return false;
|
|
391
|
+
}
|
|
392
|
+
return true;
|
|
393
|
+
});
|
|
394
|
+
if (stmt.declarations.length === 0) return false;
|
|
395
|
+
}
|
|
396
|
+
return true;
|
|
397
|
+
});
|
|
398
|
+
path.stop();
|
|
399
|
+
},
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
traverse(ast, {
|
|
404
|
+
Program(path: NodePath<t.Program>) {
|
|
405
|
+
path.scope.crawl();
|
|
406
|
+
for (const stmt of path.node.body) {
|
|
407
|
+
if (!t.isImportDeclaration(stmt)) continue;
|
|
408
|
+
stmt.specifiers = stmt.specifiers.filter((spec) => {
|
|
409
|
+
const binding = path.scope.getBinding(spec.local.name);
|
|
410
|
+
return binding ? binding.referenced : true;
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
path.node.body = path.node.body.filter(
|
|
414
|
+
(stmt) =>
|
|
415
|
+
!(
|
|
416
|
+
t.isImportDeclaration(stmt) &&
|
|
417
|
+
stmt.specifiers.length === 0 &&
|
|
418
|
+
hadSpecifiers.has(stmt)
|
|
419
|
+
),
|
|
420
|
+
);
|
|
421
|
+
path.stop();
|
|
422
|
+
},
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* Whether a binding pattern is side-effect-free to drop: a plain identifier, or
|
|
428
|
+
* an object/array pattern of plain bindings — no default values
|
|
429
|
+
* (`{ a = expr }`) or computed keys (`{ [expr]: a }`), which would evaluate (and
|
|
430
|
+
* thus could have side effects) at destructuring time.
|
|
431
|
+
*/
|
|
432
|
+
function isPlainPattern(node: t.Node): boolean {
|
|
433
|
+
if (t.isIdentifier(node)) return true;
|
|
434
|
+
if (t.isObjectPattern(node)) {
|
|
435
|
+
return node.properties.every((p) =>
|
|
436
|
+
t.isRestElement(p)
|
|
437
|
+
? isPlainPattern(p.argument)
|
|
438
|
+
: !p.computed && isPlainPattern(p.value),
|
|
439
|
+
);
|
|
440
|
+
}
|
|
441
|
+
if (t.isArrayPattern(node)) {
|
|
442
|
+
return node.elements.every((el) => el == null || isPlainPattern(el));
|
|
443
|
+
}
|
|
444
|
+
return false; // AssignmentPattern (default), member expr, etc.
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** Whether a variable initializer is safe to drop (no observable side effects). */
|
|
448
|
+
function isRemovableInit(node: t.Expression | null | undefined): boolean {
|
|
449
|
+
if (node == null) return true;
|
|
450
|
+
if (t.isTSAsExpression(node) || t.isTSSatisfiesExpression(node)) {
|
|
451
|
+
return isRemovableInit(node.expression);
|
|
452
|
+
}
|
|
453
|
+
// Containers are removable only if every element is — a nested call (e.g.
|
|
454
|
+
// `[track()]`) has an observable side effect that dropping would lose.
|
|
455
|
+
if (t.isArrayExpression(node)) {
|
|
456
|
+
return node.elements.every(
|
|
457
|
+
(el) => el == null || (t.isExpression(el) && isRemovableInit(el)),
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
if (t.isObjectExpression(node)) {
|
|
461
|
+
return node.properties.every(
|
|
462
|
+
(p) =>
|
|
463
|
+
t.isObjectProperty(p) &&
|
|
464
|
+
!p.computed &&
|
|
465
|
+
t.isExpression(p.value) &&
|
|
466
|
+
isRemovableInit(p.value),
|
|
467
|
+
);
|
|
468
|
+
}
|
|
469
|
+
if (t.isTemplateLiteral(node)) {
|
|
470
|
+
return node.expressions.every(
|
|
471
|
+
(e) => t.isExpression(e) && isRemovableInit(e),
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
return (
|
|
475
|
+
t.isArrowFunctionExpression(node) ||
|
|
476
|
+
t.isFunctionExpression(node) ||
|
|
477
|
+
t.isClassExpression(node) ||
|
|
478
|
+
t.isIdentifier(node) ||
|
|
479
|
+
// non-computed only — `obj[fn()]` could hide a side-effectful key
|
|
480
|
+
(t.isMemberExpression(node) && !node.computed) ||
|
|
481
|
+
t.isJSXElement(node) ||
|
|
482
|
+
t.isJSXFragment(node) ||
|
|
483
|
+
t.isLiteral(node)
|
|
484
|
+
);
|
|
485
|
+
}
|
package/src/constants.ts
ADDED