@tokamaq/sdk 0.0.0-stage → 0.1.0-dev.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/LICENSE +21 -0
- package/README.md +1403 -2
- package/build-internals.ts +25 -0
- package/caller/agent-launch.ts +60 -0
- package/client.tsx +498 -0
- package/component-actions.ts +327 -0
- package/component-alerts.ts +136 -0
- package/component-attributes.ts +340 -0
- package/component-parts.tsx +1177 -0
- package/core-contracts/auth.ts +40 -0
- package/package.json +98 -4
- package/quit.ts +58 -0
- package/regions.tsx +94 -0
- package/screen-search.ts +211 -0
- package/send-file.ts +175 -0
- package/server-build-internals.ts +11 -0
- package/solid.ts +132 -0
- package/src/agent-command.ts +48 -0
- package/src/agent-info-cache.ts +34 -0
- package/src/agent-reports.ts +140 -0
- package/src/agent-turn.ts +289 -0
- package/src/api.ts +174 -0
- package/src/auth.ts +39 -0
- package/src/call-error.ts +37 -0
- package/src/caller-storage.ts +32 -0
- package/src/client.ts +163 -0
- package/src/database.ts +322 -0
- package/src/functions.ts +726 -0
- package/src/hooks.ts +141 -0
- package/src/host.ts +211 -0
- package/src/http-action.ts +55 -0
- package/src/index.ts +126 -0
- package/src/internal/contracts.ts +260 -0
- package/src/internal/machine-scope.ts +21 -0
- package/src/local.ts +22 -0
- package/src/plugin.ts +162 -0
- package/src/points.ts +79 -0
- package/src/protocol.ts +64 -0
- package/src/schema.ts +136 -0
- package/src/storage.ts +193 -0
- package/src/thread-context.ts +42 -0
- package/src/transport.ts +421 -0
- package/src/triggers.ts +87 -0
- package/src/unstable.ts +66 -0
- package/src/validators.ts +248 -0
- package/src/values.ts +98 -0
- package/src/visibility.ts +8 -0
- package/src/websocket-transport.ts +91 -0
- package/src/window-state-protocol.ts +7 -0
- package/src/within.ts +24 -0
- package/src/worker-limits.ts +5 -0
- package/tools/bundle.mjs +490 -0
- package/tools/client-entry.mjs +10 -0
- package/tools/contracts.mjs +254 -0
- package/tools/http-actions.mjs +42 -0
- package/tools/placement.mjs +535 -0
- package/tools/plugin-boundary.mjs +592 -0
- package/tools/plugin-compiler.mjs +125 -0
- package/tools/plugin-descriptor.ts +75 -0
- package/tools/points.mjs +340 -0
- package/tools/result-validator.mjs +83 -0
- package/tools/server-builtins.mjs +82 -0
- package/tools/server-files.mjs +34 -0
- package/tools/table-references.mjs +98 -0
- package/tools/worker.mjs +110 -0
- package/tsconfig.plugin-server.json +12 -0
- package/tsconfig.plugin-window.json +15 -0
- package/view.ts +27 -0
- package/web.d.ts +6 -0
- package/window-state-host.ts +228 -0
- package/window-state.ts +43 -0
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
// Discover function placement from SDK types, including aliases and re-exports.
|
|
2
|
+
// Build entries name only their own definitions; transforms erase the others
|
|
3
|
+
// before either bundler reads their imports or emits any source.
|
|
4
|
+
import ts from "typescript";
|
|
5
|
+
import { readdirSync, realpathSync } from "node:fs";
|
|
6
|
+
import { dirname, join, relative, resolve, sep } from "node:path";
|
|
7
|
+
import {
|
|
8
|
+
actionPlacementLiteral,
|
|
9
|
+
definitionInfo,
|
|
10
|
+
definitionTypeInfo,
|
|
11
|
+
pluginCompilerOptions,
|
|
12
|
+
runtimeExportNames,
|
|
13
|
+
serverConfigPath,
|
|
14
|
+
} from "./plugin-compiler.mjs";
|
|
15
|
+
|
|
16
|
+
import { suppliedNodeModules, nodeModule } from "./server-builtins.mjs";
|
|
17
|
+
import { resultValidator } from "./result-validator.mjs";
|
|
18
|
+
import { discoverPoints, originalSymbol } from "./points.mjs";
|
|
19
|
+
import { discoverProviders, contractTarget } from "./contracts.mjs";
|
|
20
|
+
|
|
21
|
+
const hookable = (kind) => ["query", "mutation", "action"].includes(kind);
|
|
22
|
+
export const runnerFunction = (kind) => kind === "action" || kind === "actionHook";
|
|
23
|
+
export function runnerProvider(provider) {
|
|
24
|
+
return localProvider(provider) || provider.methods.some((method) => runnerFunction(method.kind));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function runnerActionFiles(modules, providers, on) {
|
|
28
|
+
const action = (entry) =>
|
|
29
|
+
runnerFunction(entry.kind) &&
|
|
30
|
+
(entry.kind === "actionHook" ||
|
|
31
|
+
on === undefined ||
|
|
32
|
+
(on === "caller" ? entry.on && entry.on !== "server" : entry.on === on));
|
|
33
|
+
return new Set([
|
|
34
|
+
...[...modules].filter(([, exports]) => [...exports.values()].some(action)).map(([path]) => path),
|
|
35
|
+
...providers
|
|
36
|
+
.filter((provider) => runnerProvider(provider) && provider.methods.some(action))
|
|
37
|
+
.map((p) => p.path),
|
|
38
|
+
]);
|
|
39
|
+
}
|
|
40
|
+
const serverProvider = (provider) => provider.on === "server";
|
|
41
|
+
const localProvider = (provider) => provider.on === "caller";
|
|
42
|
+
const transaction = (kind) => !runnerFunction(kind) && kind !== "httpAction";
|
|
43
|
+
const noFunctions = () => false;
|
|
44
|
+
|
|
45
|
+
export const lanes = {
|
|
46
|
+
window: { keep: noFunctions, provider: noFunctions, method: noFunctions },
|
|
47
|
+
http: { keep: (kind) => kind === "httpAction", provider: noFunctions, method: noFunctions },
|
|
48
|
+
local: {
|
|
49
|
+
keep: runnerFunction,
|
|
50
|
+
provider: runnerProvider,
|
|
51
|
+
method: runnerFunction,
|
|
52
|
+
},
|
|
53
|
+
server: { keep: (kind) => kind !== "httpAction", provider: serverProvider },
|
|
54
|
+
descriptor: {
|
|
55
|
+
keep: transaction,
|
|
56
|
+
provider: serverProvider,
|
|
57
|
+
method: transaction,
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
export function functionPlacement(root, selected, namespace) {
|
|
62
|
+
root = realpathSync(root);
|
|
63
|
+
const src = resolve(root, "src");
|
|
64
|
+
const files = selected ? [...selected.files] : [];
|
|
65
|
+
function scan(dir) {
|
|
66
|
+
for (const item of readdirSync(dir, { withFileTypes: true })) {
|
|
67
|
+
if (/^[._]|^(dist|node_modules|tests)$/.test(item.name)) continue;
|
|
68
|
+
const path = resolve(dir, item.name);
|
|
69
|
+
if (item.isDirectory()) scan(path);
|
|
70
|
+
else if (/\.tsx?$/.test(path) && !/\.(d|test|spec)\.tsx?$/.test(path)) files.push(path);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
for (const directory of selected ? [] : [src]) {
|
|
74
|
+
try {
|
|
75
|
+
scan(directory);
|
|
76
|
+
} catch (error) {
|
|
77
|
+
if (error.code !== "ENOENT") throw error;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (!files.length) return;
|
|
81
|
+
const config = serverConfigPath(selected?.configRoot ?? root, root);
|
|
82
|
+
const options = ts.getParsedCommandLineOfConfigFile(
|
|
83
|
+
config,
|
|
84
|
+
{},
|
|
85
|
+
{
|
|
86
|
+
...ts.sys,
|
|
87
|
+
onUnRecoverableConfigFileDiagnostic() {},
|
|
88
|
+
},
|
|
89
|
+
)?.options;
|
|
90
|
+
const program = ts.createProgram(files.sort(), pluginCompilerOptions(root, options ?? {}));
|
|
91
|
+
const checker = program.getTypeChecker();
|
|
92
|
+
const modules = new Map();
|
|
93
|
+
const stageKind = (type) =>
|
|
94
|
+
["hook", "trigger"].find((kind) =>
|
|
95
|
+
type.getProperties().some((p) => p.name.startsWith(`__@${kind}Brand@`)),
|
|
96
|
+
);
|
|
97
|
+
function targetsStage(symbol) {
|
|
98
|
+
const expression = originalSymbol(checker, symbol)?.valueDeclaration?.initializer;
|
|
99
|
+
const target = expression && ts.isCallExpression(expression) && expression.arguments[0];
|
|
100
|
+
return target && stageKind(checker.getTypeAtLocation(target));
|
|
101
|
+
}
|
|
102
|
+
function hookInfo(type, source) {
|
|
103
|
+
const reference = checker.getTypeOfSymbolAtLocation(type.getProperty("reference"), source);
|
|
104
|
+
const brand = reference.getProperties().find((p) => p.name.startsWith("__@referenceTypes@"));
|
|
105
|
+
const metadata = brand && checker.getTypeOfSymbolAtLocation(brand, source);
|
|
106
|
+
const literal = (property) => {
|
|
107
|
+
const symbol = metadata?.getProperty(property);
|
|
108
|
+
return symbol && checker.getTypeOfSymbolAtLocation(symbol, source).value;
|
|
109
|
+
};
|
|
110
|
+
const targetKey = reference.getProperties().find((p) => p.name.startsWith("__@functionName@"));
|
|
111
|
+
return {
|
|
112
|
+
kind: literal("kind") === "action" ? "actionHook" : "hook",
|
|
113
|
+
targetKind: literal("kind"),
|
|
114
|
+
owner: literal("owner"),
|
|
115
|
+
target: targetKey && checker.getTypeOfSymbolAtLocation(targetKey, source).value,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
const providers = discoverProviders(root, files, program, checker);
|
|
119
|
+
for (const path of files) {
|
|
120
|
+
if (path === resolve(src, "server/api.ts")) continue;
|
|
121
|
+
const source = program.getSourceFile(path);
|
|
122
|
+
const symbol = checker.getSymbolAtLocation(source);
|
|
123
|
+
const exports = new Map();
|
|
124
|
+
const runtime = symbol && runtimeExportNames(checker, symbol);
|
|
125
|
+
for (const value of symbol ? checker.getExportsOfModule(symbol) : []) {
|
|
126
|
+
if (!runtime.has(value.name)) continue;
|
|
127
|
+
const definition = definitionInfo(checker, value, source);
|
|
128
|
+
const type = checker.getTypeOfSymbolAtLocation(value, source);
|
|
129
|
+
const stage = stageKind(type);
|
|
130
|
+
if (stage === "trigger") {
|
|
131
|
+
if (["client", "local"].some((part) => path.startsWith(resolve(src, part) + sep)))
|
|
132
|
+
throw new Error("Triggers must be exported from the plugin's server part");
|
|
133
|
+
exports.set(value.name, { kind: stage });
|
|
134
|
+
} else if (stage === "hook") {
|
|
135
|
+
if (path.startsWith(resolve(src, "client") + sep))
|
|
136
|
+
throw new Error("Hooks must be exported from the plugin's server part");
|
|
137
|
+
const info = hookInfo(type, source);
|
|
138
|
+
if (info.targetKind ? !hookable(info.targetKind) : targetsStage(value))
|
|
139
|
+
throw new Error("Only queries, mutations and actions can be hooked");
|
|
140
|
+
if (!info.targetKind) throw new Error("Hook target reference could not be resolved");
|
|
141
|
+
if (namespace && info.owner === namespace) throw new Error("Hooks must target another plugin");
|
|
142
|
+
exports.set(value.name, info);
|
|
143
|
+
} else if (definition?.kind) {
|
|
144
|
+
exports.set(value.name, {
|
|
145
|
+
...definition,
|
|
146
|
+
...(hookable(definition.kind) ? { type, source, symbol: originalSymbol(checker, value) } : {}),
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (exports.size) modules.set(path, exports);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const allDefinitions = [...modules.values()].flatMap((definitions) => [...definitions.values()]);
|
|
154
|
+
const namedPoints = discoverPoints(
|
|
155
|
+
files.map((file) => program.getSourceFile(file)),
|
|
156
|
+
checker,
|
|
157
|
+
allDefinitions.map(({ symbol }) => symbol).filter(Boolean),
|
|
158
|
+
console.warn,
|
|
159
|
+
);
|
|
160
|
+
for (const definition of allDefinitions) definition.points = namedPoints.get(definition.symbol);
|
|
161
|
+
|
|
162
|
+
function edits(path, lane) {
|
|
163
|
+
const file = program.getSourceFile(path);
|
|
164
|
+
if (!file || !files.includes(path)) return [];
|
|
165
|
+
const cuts = [];
|
|
166
|
+
const retained = new Set();
|
|
167
|
+
const discard = new Set();
|
|
168
|
+
const helpers = new Map();
|
|
169
|
+
const symbolOf = (node) => checker.getSymbolAtLocation(node);
|
|
170
|
+
|
|
171
|
+
const calls = new Map(providers.filter((p) => p.path === path).map((p) => [p.call, p]));
|
|
172
|
+
const fields = new Map(
|
|
173
|
+
providers.filter((p) => p.path === path).flatMap((p) => p.methods.map((m) => [m.field, m])),
|
|
174
|
+
);
|
|
175
|
+
function references(node, into, erased = false) {
|
|
176
|
+
const provider = !erased && calls.get(node);
|
|
177
|
+
if (provider && !lane.provider(provider)) {
|
|
178
|
+
cuts.push([node.getStart(file), node.end, "undefined"]);
|
|
179
|
+
references(node, discard, true);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const method = !erased && fields.get(node);
|
|
183
|
+
if (method && lane.method && !lane.method(method.kind)) {
|
|
184
|
+
cuts.push([
|
|
185
|
+
node.getStart(file),
|
|
186
|
+
node.end,
|
|
187
|
+
method.argument ? "undefined" : `${JSON.stringify(method.member)}: undefined`,
|
|
188
|
+
]);
|
|
189
|
+
references(node, discard, true);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (!erased && ts.isVariableDeclaration(node) && node.initializer) {
|
|
193
|
+
const type = checker.getTypeAtLocation(node.initializer);
|
|
194
|
+
const stage = stageKind(type);
|
|
195
|
+
const target =
|
|
196
|
+
stage === "hook"
|
|
197
|
+
? hookInfo(type, node).kind
|
|
198
|
+
: (stage ?? definitionTypeInfo(checker, type, node)?.kind);
|
|
199
|
+
if (target && lane.keep && !lane.keep(target)) {
|
|
200
|
+
cuts.push([node.initializer.getStart(file), node.initializer.end, "undefined"]);
|
|
201
|
+
references(node.initializer, discard, true);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (ts.isIdentifier(node) && !isDeclarationName(node)) {
|
|
206
|
+
const symbol = ts.isExportSpecifier(node.parent)
|
|
207
|
+
? checker.getExportSpecifierLocalTargetSymbol(node.parent)
|
|
208
|
+
: ts.isShorthandPropertyAssignment(node.parent)
|
|
209
|
+
? checker.getShorthandAssignmentValueSymbol(node.parent)
|
|
210
|
+
: symbolOf(node);
|
|
211
|
+
if (symbol) into.add(symbol);
|
|
212
|
+
}
|
|
213
|
+
ts.forEachChild(node, (child) => references(child, into, erased));
|
|
214
|
+
}
|
|
215
|
+
for (const statement of file.statements) {
|
|
216
|
+
if (ts.isImportDeclaration(statement)) continue;
|
|
217
|
+
const helper = helperName(statement);
|
|
218
|
+
const symbol = helper && symbolOf(helper);
|
|
219
|
+
if (symbol) {
|
|
220
|
+
const refs = new Set();
|
|
221
|
+
references(statement, refs);
|
|
222
|
+
helpers.set(symbol, { statement, refs });
|
|
223
|
+
} else {
|
|
224
|
+
references(statement, retained);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// Follow private helper chains reachable from an erased handler. Shared
|
|
229
|
+
// helpers and independent top-level effects stay in the entry's graph.
|
|
230
|
+
function expand(symbols) {
|
|
231
|
+
for (const symbol of symbols) for (const ref of helpers.get(symbol)?.refs ?? []) symbols.add(ref);
|
|
232
|
+
}
|
|
233
|
+
expand(discard);
|
|
234
|
+
for (const symbol of helpers.keys()) if (!discard.has(symbol)) retained.add(symbol);
|
|
235
|
+
expand(retained);
|
|
236
|
+
const dropped = [];
|
|
237
|
+
for (const [symbol, { statement }] of helpers)
|
|
238
|
+
if (discard.has(symbol) && !retained.has(symbol))
|
|
239
|
+
dropped.push([statement.getStart(file), statement.end, ""]);
|
|
240
|
+
|
|
241
|
+
const imports = importEdits(file, (name) => {
|
|
242
|
+
const symbol = symbolOf(name);
|
|
243
|
+
return discard.has(symbol) && !retained.has(symbol);
|
|
244
|
+
});
|
|
245
|
+
return [
|
|
246
|
+
...dropped,
|
|
247
|
+
...imports,
|
|
248
|
+
...cuts.filter(([start]) => !dropped.some(([left, right]) => start >= left && start < right)),
|
|
249
|
+
];
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function transform(path, lane) {
|
|
253
|
+
const cuts = edits(path, lane);
|
|
254
|
+
if (!cuts.length) return;
|
|
255
|
+
let contents = program.getSourceFile(path).text;
|
|
256
|
+
for (const [start, end, replacement] of cuts.sort((a, b) => b[0] - a[0]))
|
|
257
|
+
contents = contents.slice(0, start) + replacement + contents.slice(end);
|
|
258
|
+
return contents;
|
|
259
|
+
}
|
|
260
|
+
function points(server, organized) {
|
|
261
|
+
return Object.fromEntries(
|
|
262
|
+
[...modules].flatMap(([path, definitions]) =>
|
|
263
|
+
[...definitions].flatMap(([name, definition]) =>
|
|
264
|
+
definition.points?.size
|
|
265
|
+
? [
|
|
266
|
+
[
|
|
267
|
+
`${moduleName(server, path, organized)}:${name}`,
|
|
268
|
+
Object.fromEntries([...definition.points].map(([name, point]) => [name, point.validators])),
|
|
269
|
+
],
|
|
270
|
+
]
|
|
271
|
+
: [],
|
|
272
|
+
),
|
|
273
|
+
),
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function results(server, organized) {
|
|
278
|
+
return Object.fromEntries(
|
|
279
|
+
[...modules].flatMap(([path, definitions]) =>
|
|
280
|
+
[...definitions].flatMap(([name, { kind, type, source }]) => {
|
|
281
|
+
const result = hookable(kind) && resultValidator(checker, type, source);
|
|
282
|
+
return result ? [[`${moduleName(server, path, organized)}:${name}`, result]] : [];
|
|
283
|
+
}),
|
|
284
|
+
),
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
const callerFiles = runnerActionFiles(modules, providers, "caller");
|
|
288
|
+
for (const path of callerFiles) {
|
|
289
|
+
const file = program.getSourceFile(path);
|
|
290
|
+
if (!file) continue;
|
|
291
|
+
const stubbed = new Set();
|
|
292
|
+
for (const statement of file.statements) {
|
|
293
|
+
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteralLike(statement.moduleSpecifier)) continue;
|
|
294
|
+
if (!suppliedNodeModules.local.includes(nodeModule(statement.moduleSpecifier.text))) continue;
|
|
295
|
+
const clause = statement.importClause;
|
|
296
|
+
if (!clause || clause.isTypeOnly) continue;
|
|
297
|
+
const add = (binding) => {
|
|
298
|
+
if (binding) stubbed.add(checker.getSymbolAtLocation(binding));
|
|
299
|
+
};
|
|
300
|
+
add(clause.name);
|
|
301
|
+
const bindings = clause.namedBindings;
|
|
302
|
+
if (bindings && ts.isNamespaceImport(bindings)) add(bindings.name);
|
|
303
|
+
else for (const binding of bindings?.elements ?? []) if (!binding.isTypeOnly) add(binding.name);
|
|
304
|
+
}
|
|
305
|
+
function checkModuleLoad(node) {
|
|
306
|
+
if (ts.isImportDeclaration(node) || ts.isFunctionLike(node) || ts.isTypeNode(node)) return;
|
|
307
|
+
if (
|
|
308
|
+
ts.isPropertyDeclaration(node) &&
|
|
309
|
+
!node.modifiers?.some((m) => m.kind === ts.SyntaxKind.StaticKeyword)
|
|
310
|
+
) {
|
|
311
|
+
if (ts.isComputedPropertyName(node.name)) checkModuleLoad(node.name);
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
if (
|
|
315
|
+
ts.isIdentifier(node) &&
|
|
316
|
+
!isDeclarationName(node) &&
|
|
317
|
+
stubbed.has(checker.getSymbolAtLocation(node))
|
|
318
|
+
) {
|
|
319
|
+
throw new Error(
|
|
320
|
+
`Plugin import boundary: ${relative(root, path)} uses ${node.text} at module load. Move it inside the handler.`,
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
ts.forEachChild(node, checkModuleLoad);
|
|
324
|
+
}
|
|
325
|
+
if (stubbed.size) checkModuleLoad(file);
|
|
326
|
+
|
|
327
|
+
function visit(node) {
|
|
328
|
+
const specifier =
|
|
329
|
+
(ts.isImportDeclaration(node) && !node.importClause?.isTypeOnly) ||
|
|
330
|
+
(ts.isExportDeclaration(node) && !node.isTypeOnly)
|
|
331
|
+
? node.moduleSpecifier
|
|
332
|
+
: ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword
|
|
333
|
+
? node.arguments[0]
|
|
334
|
+
: undefined;
|
|
335
|
+
if (specifier && ts.isStringLiteralLike(specifier)) {
|
|
336
|
+
const dependency = checker.getSymbolAtLocation(specifier)?.declarations?.find(ts.isSourceFile);
|
|
337
|
+
if (dependency && !dependency.isDeclarationFile && dependency.fileName.startsWith(root + sep))
|
|
338
|
+
callerFiles.add(dependency.fileName);
|
|
339
|
+
}
|
|
340
|
+
ts.forEachChild(node, visit);
|
|
341
|
+
}
|
|
342
|
+
visit(file);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
for (const path of files) {
|
|
346
|
+
const file = program.getSourceFile(path);
|
|
347
|
+
function visit(node) {
|
|
348
|
+
if (
|
|
349
|
+
ts.isCallExpression(node) &&
|
|
350
|
+
definitionTypeInfo(checker, checker.getTypeAtLocation(node), node)?.kind === "action"
|
|
351
|
+
) {
|
|
352
|
+
const options = node.arguments[0];
|
|
353
|
+
const type = options && checker.getTypeAtLocation(options);
|
|
354
|
+
if (type?.getProperty("handler") && type.getProperty("on")) {
|
|
355
|
+
if (!actionPlacementLiteral(checker, options))
|
|
356
|
+
throw new Error(
|
|
357
|
+
`Action placement in ${path} must use a literal: "caller", "server", or a machine id`,
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
ts.forEachChild(node, visit);
|
|
362
|
+
}
|
|
363
|
+
visit(file);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
return { modules, providers, callerFiles, transform, edits, results, points };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function isDeclarationName(node) {
|
|
370
|
+
return (
|
|
371
|
+
(ts.isVariableDeclaration(node.parent) || ts.isFunctionDeclaration(node.parent)) &&
|
|
372
|
+
node.parent.name === node
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function helperName(statement) {
|
|
377
|
+
if (statement.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) return;
|
|
378
|
+
if (ts.isFunctionDeclaration(statement)) return statement.name;
|
|
379
|
+
if (!ts.isVariableStatement(statement) || statement.declarationList.declarations.length !== 1) return;
|
|
380
|
+
const declaration = statement.declarationList.declarations[0];
|
|
381
|
+
if (ts.isIdentifier(declaration.name)) return declaration.name;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function importEdits(file, unused) {
|
|
385
|
+
const edits = [];
|
|
386
|
+
for (const node of file.statements) {
|
|
387
|
+
if (!ts.isImportDeclaration(node) || !node.importClause || node.importClause.isTypeOnly) continue;
|
|
388
|
+
const clause = node.importClause;
|
|
389
|
+
const defaultName = clause.name && (!unused(clause.name) ? clause.name.text : "");
|
|
390
|
+
const bindings = clause.namedBindings;
|
|
391
|
+
let changed = clause.name && !defaultName;
|
|
392
|
+
let named = "";
|
|
393
|
+
if (bindings && ts.isNamespaceImport(bindings)) {
|
|
394
|
+
if (!unused(bindings.name)) named = bindings.getText(file);
|
|
395
|
+
else changed = true;
|
|
396
|
+
} else if (bindings) {
|
|
397
|
+
const kept = bindings.elements.filter((item) => !unused(item.name));
|
|
398
|
+
changed ||= kept.length !== bindings.elements.length;
|
|
399
|
+
if (kept.length) named = "{ " + kept.map((item) => item.getText(file)).join(", ") + " }";
|
|
400
|
+
}
|
|
401
|
+
if (!changed) continue;
|
|
402
|
+
const names = [defaultName, named].filter(Boolean).join(", ");
|
|
403
|
+
const replacement = names ? `import ${names} from ${node.moduleSpecifier.getText(file)};` : "";
|
|
404
|
+
edits.push([node.getStart(file), node.end, replacement]);
|
|
405
|
+
}
|
|
406
|
+
return edits;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
export function moduleName(root, file, organized) {
|
|
410
|
+
const path = relative(root, file)
|
|
411
|
+
.split(sep)
|
|
412
|
+
.join("/")
|
|
413
|
+
.replace(/\.tsx?$/, "");
|
|
414
|
+
return organized && !path.startsWith("../") ? path.split("/").at(-1) : path.replace(/^\.\.\//, "");
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
export function placedModules(placement, root, organized, keep) {
|
|
418
|
+
return [...placement.modules].flatMap(([path, exports]) => {
|
|
419
|
+
const names = keep
|
|
420
|
+
? [...exports].filter(([, definition]) => keep(definition.kind)).map(([name]) => name)
|
|
421
|
+
: [...exports.keys()];
|
|
422
|
+
return names.length ? [[path, moduleName(root, path, organized), names]] : [];
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
export function registrySource({
|
|
427
|
+
root,
|
|
428
|
+
modules,
|
|
429
|
+
hasSchema,
|
|
430
|
+
metadata,
|
|
431
|
+
hasActionHooks,
|
|
432
|
+
placement,
|
|
433
|
+
results,
|
|
434
|
+
points,
|
|
435
|
+
providers = [],
|
|
436
|
+
lane = lanes.server,
|
|
437
|
+
worker = false,
|
|
438
|
+
header = "",
|
|
439
|
+
}) {
|
|
440
|
+
const imports = [];
|
|
441
|
+
const entries = [];
|
|
442
|
+
for (const [index, [path, module, names]] of modules.entries()) {
|
|
443
|
+
const source = JSON.stringify(path.replace(/\.tsx?$/, ""));
|
|
444
|
+
if (!names) {
|
|
445
|
+
// Standalone features have always registered every exported SDK definition.
|
|
446
|
+
imports.push(`import * as m${index} from ${source};`);
|
|
447
|
+
entries.push(`${JSON.stringify(module)}: m${index}`);
|
|
448
|
+
continue;
|
|
449
|
+
}
|
|
450
|
+
const namesWithBindings = names.map((name, i) => [name, `f${index}_${i}`]);
|
|
451
|
+
imports.push(
|
|
452
|
+
`import { ${namesWithBindings.map(([name, binding]) => `${JSON.stringify(name)} as ${binding}`).join(", ")} } from ${source};`,
|
|
453
|
+
);
|
|
454
|
+
entries.push(
|
|
455
|
+
`${JSON.stringify(module)}: {${namesWithBindings.map(([name, binding]) => `${JSON.stringify(name)}: ${binding}`).join(", ")}}`,
|
|
456
|
+
);
|
|
457
|
+
}
|
|
458
|
+
const registrations = providers.filter(lane.provider);
|
|
459
|
+
const contractImports = registrations.map((p, i) => {
|
|
460
|
+
const name = p.exported === "default" ? `provider${i}` : `{ ${p.exported} as provider${i} }`;
|
|
461
|
+
return `import ${name} from ${JSON.stringify(p.path.replace(/\.tsx?$/, ""))};`;
|
|
462
|
+
});
|
|
463
|
+
imports.push(...contractImports);
|
|
464
|
+
const localProviders = registrations.flatMap((p, i) =>
|
|
465
|
+
localProvider(p) ? [`${JSON.stringify(p.registration)}: provider${i}`] : [],
|
|
466
|
+
);
|
|
467
|
+
const serverData = registrations.map(
|
|
468
|
+
(p, i) =>
|
|
469
|
+
`${JSON.stringify(p.registration)}: contractData(provider${i}.implementation, ${JSON.stringify(p.methods.map((m) => m.member))})`,
|
|
470
|
+
);
|
|
471
|
+
const targets = registrations.flatMap((p, i) =>
|
|
472
|
+
(localProvider(p) ? [] : p.methods)
|
|
473
|
+
.filter((m) => lane.method?.(m.kind) !== false)
|
|
474
|
+
.map(
|
|
475
|
+
(m) =>
|
|
476
|
+
`${JSON.stringify(contractTarget(p, m))}: provider${i}.implementation[${JSON.stringify(m.member)}]`,
|
|
477
|
+
),
|
|
478
|
+
);
|
|
479
|
+
const declaredPoints = Object.fromEntries(
|
|
480
|
+
Object.entries(points ?? {}).map(([name, points]) => [name, Object.keys(points)]),
|
|
481
|
+
);
|
|
482
|
+
const registry = `createRegistry({${entries.join(",")}}, {${targets.join(",")}}, ${JSON.stringify(declaredPoints)})`;
|
|
483
|
+
const definitions = imports.join("\n");
|
|
484
|
+
const hookKinds = JSON.stringify(
|
|
485
|
+
Object.fromEntries(
|
|
486
|
+
modules.flatMap(([path, module, names]) =>
|
|
487
|
+
[...(placement?.modules.get(path) ?? [])].flatMap(([name, definition]) =>
|
|
488
|
+
definition.targetKind && (!names || names.includes(name))
|
|
489
|
+
? [[`${module}:${name}`, definition.targetKind]]
|
|
490
|
+
: [],
|
|
491
|
+
),
|
|
492
|
+
),
|
|
493
|
+
),
|
|
494
|
+
);
|
|
495
|
+
if (worker)
|
|
496
|
+
return (
|
|
497
|
+
header +
|
|
498
|
+
`import {createRegistry,createHookRegistry} from "@tokamaq/sdk";\n${definitions}\nexport const functions = ${registry};\nexport const hooks = createHookRegistry({${entries.join(",")}}, ${hookKinds});\n${localProviders.length && lane === lanes.local ? `export const contractProviders = {${localProviders.join(",")}};\n` : ""}`
|
|
499
|
+
);
|
|
500
|
+
const boundHost = hasSchema ? "{ ...host, bundleSchema: schemaValue }" : "host";
|
|
501
|
+
return (
|
|
502
|
+
header +
|
|
503
|
+
'import {createRegistry, functionMetadata, schemaMetadata, invokeFunction, createHookRegistry, hookMetadata, invokeHook, createTriggerRegistry, triggerMetadata, invokeTrigger, type HostBridge, type JsonValue} from "@tokamaq/sdk";\n' +
|
|
504
|
+
(serverData.length ? 'import {contractData} from "@tokamaq/sdk/internal/contracts";\n' : "") +
|
|
505
|
+
definitions +
|
|
506
|
+
"\n" +
|
|
507
|
+
(hasSchema
|
|
508
|
+
? `import schemaValue from ${JSON.stringify(join(root, "schema"))};\nexport const schema = schemaMetadata(schemaValue);\n`
|
|
509
|
+
: "export const schema = schemaMetadata(null);\n") +
|
|
510
|
+
`export const functions = ${registry};\nexport const metadata = ${
|
|
511
|
+
metadata?.length
|
|
512
|
+
? `[...functionMetadata(functions), ...${JSON.stringify(metadata)}]`
|
|
513
|
+
: "functionMetadata(functions)"
|
|
514
|
+
};\n` +
|
|
515
|
+
`export const hooks = createHookRegistry({${entries.join(",")}}, ${hookKinds});\n` +
|
|
516
|
+
`const triggers = createTriggerRegistry({${entries.join(",")}});\n` +
|
|
517
|
+
`export const describe = () => ({schema, functions: metadata, hooks: hookMetadata(hooks), triggers: triggerMetadata(triggers),${hasActionHooks ? " actionHooks: true," : ""} results: ${JSON.stringify(results ?? {})}${points && Object.keys(points).length ? `, points: ${JSON.stringify(points)}` : ""}${serverData.length ? `, contractProviders: {${serverData.join(",")}}` : ""}});\n` +
|
|
518
|
+
`export const invoke = (request: {name: string; args: JsonValue}, host: HostBridge) => invokeFunction(functions, request, ${boundHost});\n` +
|
|
519
|
+
`export const invoke_hook = (request: Parameters<typeof invokeHook>[1], host: HostBridge) => invokeHook(hooks, request, ${boundHost});\n` +
|
|
520
|
+
`export const invoke_trigger = (request: Parameters<typeof invokeTrigger>[1], host: HostBridge) => invokeTrigger(triggers, request, ${boundHost});\n`
|
|
521
|
+
);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
export function placementTransform(placement, lane) {
|
|
525
|
+
return {
|
|
526
|
+
name: "tokamaq-function-placement",
|
|
527
|
+
setup(build) {
|
|
528
|
+
build.onLoad({ filter: /\.tsx?$/ }, ({ path }) => {
|
|
529
|
+
const contents = placement.transform(path, lane);
|
|
530
|
+
if (contents !== undefined)
|
|
531
|
+
return { contents, loader: path.endsWith(".tsx") ? "tsx" : "ts", resolveDir: dirname(path) };
|
|
532
|
+
});
|
|
533
|
+
},
|
|
534
|
+
};
|
|
535
|
+
}
|