@tokamaq/sdk 0.0.0-stage → 0.1.0-dev.2
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,592 @@
|
|
|
1
|
+
import { clientEntry } from "./client-entry.mjs";
|
|
2
|
+
import { readDescriptor } from "./plugin-descriptor.ts";
|
|
3
|
+
import { Visibility } from "../src/visibility.ts";
|
|
4
|
+
// One import policy for the SDK's Bun bundles and the public Vite builder.
|
|
5
|
+
// Provider source is read by TypeScript for types/metadata, never evaluated or bundled.
|
|
6
|
+
import { discoverPoints, pointReferenceTypes } from "./points.mjs";
|
|
7
|
+
import ts from "typescript";
|
|
8
|
+
import {
|
|
9
|
+
existsSync,
|
|
10
|
+
mkdirSync,
|
|
11
|
+
readFileSync,
|
|
12
|
+
readdirSync,
|
|
13
|
+
realpathSync,
|
|
14
|
+
statSync,
|
|
15
|
+
writeFileSync,
|
|
16
|
+
} from "node:fs";
|
|
17
|
+
import { isBuiltin } from "node:module";
|
|
18
|
+
import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
|
|
19
|
+
import { windowStateModule } from "../src/window-state-protocol.ts";
|
|
20
|
+
import { isInternalReferenceModule, isServerModule, isServerRoot, serverDirectory } from "./server-files.mjs";
|
|
21
|
+
import {
|
|
22
|
+
generated,
|
|
23
|
+
definitionInfo,
|
|
24
|
+
pluginCompilerOptions,
|
|
25
|
+
runtimeExportNames,
|
|
26
|
+
serverConfigPath,
|
|
27
|
+
} from "./plugin-compiler.mjs";
|
|
28
|
+
|
|
29
|
+
import { contractDeclarations, contractPlacementMigration, importedContractEntry } from "./contracts.mjs";
|
|
30
|
+
|
|
31
|
+
import { tableDeclarations, tableReferences, tableReferenceSource } from "./table-references.mjs";
|
|
32
|
+
|
|
33
|
+
const specifier = /^plugin:([a-z][a-z0-9]*(?:[._-][a-z0-9]+)*)(?:\/(server|client|contracts|tables))?$/;
|
|
34
|
+
export function parsePluginSpecifier(text) {
|
|
35
|
+
const match = specifier.exec(text);
|
|
36
|
+
if (!match) return;
|
|
37
|
+
return { id: match[1], side: match[2] ?? "server" };
|
|
38
|
+
}
|
|
39
|
+
const inside = (root, file) => {
|
|
40
|
+
const local = relative(root, file);
|
|
41
|
+
return local === "" || (!isAbsolute(local) && local !== ".." && !local.startsWith(".." + sep));
|
|
42
|
+
};
|
|
43
|
+
function canonical(file) {
|
|
44
|
+
const path = resolve(file);
|
|
45
|
+
if (existsSync(path)) return realpathSync(path);
|
|
46
|
+
const parent = dirname(path);
|
|
47
|
+
return parent === path ? path : resolve(canonical(parent), basename(path));
|
|
48
|
+
}
|
|
49
|
+
// The SDK is the host contract every plugin builds against. A workspace may
|
|
50
|
+
// resolve it by a tsconfig alias to its source instead of through node_modules.
|
|
51
|
+
const sdkRoot = canonical(resolve(import.meta.dirname, ".."));
|
|
52
|
+
const excluded =
|
|
53
|
+
/(?:^|\/)(?:node_modules|dist|tests|__tests__|\.tokamaq)(?:\/|$)|\.(?:test|spec)\.[cm]?[jt]sx?$/;
|
|
54
|
+
const windowSdk = ["@tokamaq/sdk/client", windowStateModule];
|
|
55
|
+
|
|
56
|
+
function assertWindowImport(path, id) {
|
|
57
|
+
if (id === windowStateModule || id === "@tokamaq/sdk/window-state-host")
|
|
58
|
+
throw new Error(`Window state runtime imports are reserved for the plugin build: ${path}`);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function assertWindowSide(path, id) {
|
|
62
|
+
if (windowSdk.some((name) => id === name || id.startsWith(name + "/") || id.startsWith(name + "?")))
|
|
63
|
+
throw new Error(`Window state is only available in the window: ${path}`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function featurePluginRoot(folder) {
|
|
67
|
+
return isServerRoot(folder)
|
|
68
|
+
? resolve(folder, "../..")
|
|
69
|
+
: basename(folder) === "src" && existsSync(resolve(folder, "../plugin.ts"))
|
|
70
|
+
? dirname(folder)
|
|
71
|
+
: folder;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function configuration(file, root) {
|
|
75
|
+
const path = serverConfigPath(dirname(file), root);
|
|
76
|
+
const config = ts.readConfigFile(path, ts.sys.readFile);
|
|
77
|
+
return ts.parseJsonConfigFileContent(config.config, ts.sys, dirname(path));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function diagnostic(importer, id, target) {
|
|
81
|
+
return new Error(
|
|
82
|
+
`Plugin import boundary: ${importer} imports ${JSON.stringify(id)}${target ? ` (${target})` : ""} outside its plugin folder. ` +
|
|
83
|
+
'Keep helpers inside this plugin or install a package through node_modules. Use "plugin:<id>/server" for public types and host-call references, or "plugin:<id>/client" for the client registry.',
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function pluginOwner(file) {
|
|
88
|
+
for (let dir = dirname(file); dirname(dir) !== dir; dir = dirname(dir)) {
|
|
89
|
+
if (existsSync(resolve(dir, "plugin.ts")) && existsSync(resolve(dir, "package.json"))) return dir;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function assertPluginResolution(root, importer, id, target, packageImport = false) {
|
|
94
|
+
root = canonical(root);
|
|
95
|
+
target = canonical(target);
|
|
96
|
+
const owner = pluginOwner(target);
|
|
97
|
+
if (owner && canonical(owner) !== root) throw diagnostic(importer, id, target);
|
|
98
|
+
if (!inside(root, canonical(importer))) return; // ordinary package-internal dependency
|
|
99
|
+
if (/^@tokamaq\/sdk(?:\/|$)/.test(id) && inside(sdkRoot, target)) return;
|
|
100
|
+
if (inside(root, target)) return;
|
|
101
|
+
if (packageImport) return;
|
|
102
|
+
throw diagnostic(importer, id, target);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function provider(root, id) {
|
|
106
|
+
const reference = parsePluginSpecifier(id);
|
|
107
|
+
if (!reference) throw new Error(`Invalid plugin specifier ${id}`);
|
|
108
|
+
const { side } = reference;
|
|
109
|
+
const folder = resolve(root, "..", reference.id);
|
|
110
|
+
const backendEntry = resolve(serverDirectory(folder), "api.ts");
|
|
111
|
+
const entry =
|
|
112
|
+
side === "contracts"
|
|
113
|
+
? importedContractEntry(root, reference.id)
|
|
114
|
+
: side === "server"
|
|
115
|
+
? existsSync(backendEntry)
|
|
116
|
+
? backendEntry
|
|
117
|
+
: resolve(folder, "api.ts")
|
|
118
|
+
: clientEntry(folder);
|
|
119
|
+
if (side === "tables")
|
|
120
|
+
return { folder, entry: resolve(serverDirectory(folder), "schema.ts"), side, id: reference.id };
|
|
121
|
+
if (!existsSync(entry)) throw new Error(`Plugin import ${id}: missing public API ${entry}`);
|
|
122
|
+
return { folder, entry, side, id: reference.id };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function publicReferences(folder, entry) {
|
|
126
|
+
const options = pluginCompilerOptions(folder, configuration(entry, folder).options);
|
|
127
|
+
const backend = serverDirectory(folder);
|
|
128
|
+
const authored = ts.sys
|
|
129
|
+
.readDirectory(backend, [".ts"])
|
|
130
|
+
.filter((file) => isServerModule(backend, relative(backend, file).split(sep).join("/")));
|
|
131
|
+
const program = ts.createProgram([entry, ...authored], options);
|
|
132
|
+
const checker = program.getTypeChecker();
|
|
133
|
+
const file = program.getSourceFile(entry);
|
|
134
|
+
const module = checker.getSymbolAtLocation(file);
|
|
135
|
+
const original = (symbol) =>
|
|
136
|
+
symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
|
|
137
|
+
const targets = new Map();
|
|
138
|
+
const sources = [];
|
|
139
|
+
for (const source of program.getSourceFiles()) {
|
|
140
|
+
const local = relative(backend, source.fileName).split(sep).join("/");
|
|
141
|
+
if (!isServerModule(backend, local)) continue;
|
|
142
|
+
sources.push(source);
|
|
143
|
+
const symbol = checker.getSymbolAtLocation(source);
|
|
144
|
+
const runtime = symbol && runtimeExportNames(checker, symbol);
|
|
145
|
+
for (const exported of symbol ? checker.getExportsOfModule(symbol) : []) {
|
|
146
|
+
if (!runtime.has(exported.name)) continue;
|
|
147
|
+
const target = original(exported);
|
|
148
|
+
const definition = definitionInfo(checker, target, source);
|
|
149
|
+
if (!definition || definition.kind === "httpAction") continue;
|
|
150
|
+
const moduleName = isServerRoot(backend) ? basename(local, ".ts") : local.slice(0, -3);
|
|
151
|
+
if (!targets.has(target) || target.valueDeclaration?.getSourceFile() === source)
|
|
152
|
+
targets.set(target, [
|
|
153
|
+
moduleName,
|
|
154
|
+
exported.name,
|
|
155
|
+
definition.visibility,
|
|
156
|
+
definition.kind,
|
|
157
|
+
source.fileName,
|
|
158
|
+
]);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const points = discoverPoints(
|
|
162
|
+
sources,
|
|
163
|
+
checker,
|
|
164
|
+
[...targets]
|
|
165
|
+
.filter(([, [, , , kind]]) => ["query", "mutation", "action"].includes(kind))
|
|
166
|
+
.map(([symbol]) => symbol),
|
|
167
|
+
);
|
|
168
|
+
for (const [symbol, target] of targets) target.push(points.get(symbol));
|
|
169
|
+
const runtime = module ? runtimeExportNames(checker, module) : new Set();
|
|
170
|
+
const refs = (module ? checker.getExportsOfModule(module) : []).flatMap((exported) => {
|
|
171
|
+
if (!runtime.has(exported.name)) return [];
|
|
172
|
+
const target = targets.get(original(exported));
|
|
173
|
+
return target && target[2] !== Visibility.Internal ? [[exported.name, target]] : [];
|
|
174
|
+
});
|
|
175
|
+
const imports = new Set();
|
|
176
|
+
for (const source of program.getSourceFiles()) {
|
|
177
|
+
if (!inside(folder, source.fileName) || inside(generated(folder), source.fileName)) continue;
|
|
178
|
+
for (const imported of ts.preProcessFile(source.text, true, true).importedFiles)
|
|
179
|
+
if (imported.fileName.startsWith("plugin:")) imports.add(imported.fileName);
|
|
180
|
+
}
|
|
181
|
+
const internal = [...targets.values()].filter(([, , visibility]) => visibility === Visibility.Internal);
|
|
182
|
+
return { refs, imports, internal };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export function pluginReferenceSource(root, id, { publicOnly = false } = {}) {
|
|
186
|
+
const target = provider(root, id);
|
|
187
|
+
if (target.side === "tables")
|
|
188
|
+
return tableReferenceSource(
|
|
189
|
+
tableReferences(target.folder, target.id, configuration(target.entry, target.folder).options),
|
|
190
|
+
);
|
|
191
|
+
if (target.side === "contracts")
|
|
192
|
+
return (
|
|
193
|
+
'import { contractReference } from "@tokamaq/sdk/internal/contracts";\n' +
|
|
194
|
+
contractDeclarations(target.entry)
|
|
195
|
+
.map(
|
|
196
|
+
({ exported, name, on, dataMethods }) =>
|
|
197
|
+
`export const ${exported} = contractReference(${JSON.stringify(name)}, ${JSON.stringify(on)}, ${JSON.stringify(target.id)}${dataMethods === undefined ? "" : ", " + JSON.stringify(dataMethods)});`,
|
|
198
|
+
)
|
|
199
|
+
.join("\n")
|
|
200
|
+
);
|
|
201
|
+
if (target.side === "client") throw new Error(`Use ${id} in a client bundle through the client registry`);
|
|
202
|
+
const { refs: all, internal } = publicReferences(target.folder, target.entry);
|
|
203
|
+
const refs = publicOnly ? all.filter(([, [, , visibility]]) => visibility === Visibility.Public) : all;
|
|
204
|
+
const internalRefs = publicOnly ? [] : internal;
|
|
205
|
+
const kinds = Object.fromEntries(
|
|
206
|
+
[...refs.map(([, target]) => target), ...internalRefs].map(([module, method, , kind]) => [
|
|
207
|
+
`${module}:${method}`,
|
|
208
|
+
kind,
|
|
209
|
+
]),
|
|
210
|
+
);
|
|
211
|
+
const points = Object.fromEntries(
|
|
212
|
+
[...refs.map(([, ref]) => ref), ...internalRefs].flatMap(([module, method, , , , named]) =>
|
|
213
|
+
named?.size ? [[`${module}:${method}`, [...named.keys()]]] : [],
|
|
214
|
+
),
|
|
215
|
+
);
|
|
216
|
+
return (
|
|
217
|
+
'import { createApi } from "@tokamaq/sdk";\n' +
|
|
218
|
+
`const references = createApi(${JSON.stringify(target.id)}, ${JSON.stringify(Object.keys(kinds))}, ${JSON.stringify(kinds)}, ${JSON.stringify(points)});\n` +
|
|
219
|
+
`export const internal = createApi(${JSON.stringify(target.id)}, ${JSON.stringify(internalRefs.map(([module, method]) => `${module}:${method}`))}, ${JSON.stringify(kinds)}, ${JSON.stringify(points)});\n` +
|
|
220
|
+
refs
|
|
221
|
+
.map(
|
|
222
|
+
([name, [module, method]]) =>
|
|
223
|
+
`export const ${name} = references[${JSON.stringify(module)}][${JSON.stringify(method)}];`,
|
|
224
|
+
)
|
|
225
|
+
.join("\n") +
|
|
226
|
+
`\nexport const api = {${refs.map(([name]) => name).join(",")}};\n`
|
|
227
|
+
);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function declarePlugin(root, id, declared, depends, tableOwners) {
|
|
231
|
+
if (declared.has(id)) return;
|
|
232
|
+
declared.add(id);
|
|
233
|
+
const target = provider(root, id);
|
|
234
|
+
const path = resolve(generated(root), target.id, `${target.side}.d.ts`);
|
|
235
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
236
|
+
if (target.side === "tables") {
|
|
237
|
+
const tables = tableReferences(
|
|
238
|
+
target.folder,
|
|
239
|
+
target.id,
|
|
240
|
+
configuration(target.entry, target.folder).options,
|
|
241
|
+
);
|
|
242
|
+
writeFileSync(path, tableDeclarations(target.id, tables, Object.hasOwn(depends ?? {}, target.id)));
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
const parts = resolve(dirname(target.entry), "_generated/components.d.ts");
|
|
246
|
+
const entry = JSON.stringify(target.side === "client" && existsSync(parts) ? parts : target.entry);
|
|
247
|
+
if (target.side === "contracts") {
|
|
248
|
+
writeFileSync(
|
|
249
|
+
path,
|
|
250
|
+
`export type * from ${entry};\n` +
|
|
251
|
+
contractDeclarations(target.entry)
|
|
252
|
+
.map(
|
|
253
|
+
({ exported }) =>
|
|
254
|
+
`export declare const ${exported}: typeof import(${entry})[${JSON.stringify(exported)}];`,
|
|
255
|
+
)
|
|
256
|
+
.join("\n") +
|
|
257
|
+
"\n",
|
|
258
|
+
);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
const { refs, imports, internal } = publicReferences(target.folder, target.entry);
|
|
262
|
+
const aliases = [];
|
|
263
|
+
const referenceType = ([module, method, , kind, source, points], type = "ReferenceFromDefinition") =>
|
|
264
|
+
`import("@tokamaq/sdk").${type}<typeof import(${JSON.stringify(source)})[${JSON.stringify(method)}], ${JSON.stringify(target.id)}> & { readonly [functionName]: ${JSON.stringify(`${target.id}/${module}:${method}`)} }${pointReferenceTypes(points, kind, target.id, `${target.id}/${module}:${method}`, aliases)}`;
|
|
265
|
+
const qualify = (type) =>
|
|
266
|
+
tableOwners.has(target.id)
|
|
267
|
+
? `import("@tokamaq/sdk").QualifiedPluginApi<${JSON.stringify(target.id)}, ${type}>`
|
|
268
|
+
: type;
|
|
269
|
+
const internalTree = {};
|
|
270
|
+
for (const ref of internal) {
|
|
271
|
+
let branch = internalTree;
|
|
272
|
+
for (const segment of ref[0].split("/")) branch = branch[segment] ??= Object.create(null);
|
|
273
|
+
branch[ref[1]] = `${qualify(`{ref: ${referenceType(ref, "HookReferenceFromDefinition")}}`)}["ref"]`;
|
|
274
|
+
}
|
|
275
|
+
const declaration = (tree) =>
|
|
276
|
+
`{${Object.entries(tree)
|
|
277
|
+
.map(
|
|
278
|
+
([key, value]) =>
|
|
279
|
+
`readonly ${JSON.stringify(key)}: ${typeof value === "string" ? value : declaration(value)};`,
|
|
280
|
+
)
|
|
281
|
+
.join("")}}`;
|
|
282
|
+
const publicApi =
|
|
283
|
+
target.side === "server" &&
|
|
284
|
+
qualify(declaration(Object.fromEntries(refs.map(([name, ref]) => [name, referenceType(ref)]))));
|
|
285
|
+
writeFileSync(
|
|
286
|
+
path,
|
|
287
|
+
`// Generated public plugin types. Runtime imports use references or the client registry.\n` +
|
|
288
|
+
(target.side === "client"
|
|
289
|
+
? `export * from ${entry};\n`
|
|
290
|
+
: 'import { functionName } from "@tokamaq/sdk";\n' +
|
|
291
|
+
`export type * from ${entry};\n` +
|
|
292
|
+
aliases.join("") +
|
|
293
|
+
`type PublicApi = ${publicApi};\n` +
|
|
294
|
+
`export declare const internal: ${declaration(internalTree)};\n` +
|
|
295
|
+
`export declare const api: PublicApi;\n` +
|
|
296
|
+
refs
|
|
297
|
+
.map(([name]) => `export declare const ${name}: PublicApi[${JSON.stringify(name)}];\n`)
|
|
298
|
+
.join("")),
|
|
299
|
+
);
|
|
300
|
+
// Public API types can themselves depend on other sanctioned public types.
|
|
301
|
+
// Materialize that type graph in the consumer; no provider code is emitted.
|
|
302
|
+
for (const dependency of imports) declarePlugin(root, dependency, declared, depends, tableOwners);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function removedClientMember(node) {
|
|
306
|
+
if (!ts.isPropertyAccessExpression(node)) return;
|
|
307
|
+
if (node.name.text === "hasLocal") return "call the action and handle the noMachine failure";
|
|
308
|
+
if (node.name.text === "local" && ts.isCallExpression(node.parent) && node.parent.expression === node)
|
|
309
|
+
return "use client.action(...)";
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function localReceiver(node) {
|
|
313
|
+
if (ts.isPropertyAccessExpression(node) && node.name.text === "local") return node.expression;
|
|
314
|
+
if (
|
|
315
|
+
ts.isElementAccessExpression(node) &&
|
|
316
|
+
ts.isStringLiteralLike(node.argumentExpression) &&
|
|
317
|
+
node.argumentExpression.text === "local"
|
|
318
|
+
)
|
|
319
|
+
return node.expression;
|
|
320
|
+
if (
|
|
321
|
+
ts.isBindingElement(node) &&
|
|
322
|
+
ts.isObjectBindingPattern(node.parent) &&
|
|
323
|
+
(node.propertyName ?? node.name).getText().replace(/['"]/g, "") === "local" &&
|
|
324
|
+
ts.isVariableDeclaration(node.parent.parent)
|
|
325
|
+
)
|
|
326
|
+
return node.parent.parent.initializer;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function needsMigrationChecker(node) {
|
|
330
|
+
return (
|
|
331
|
+
!!removedClientMember(node) || !!localReceiver(node) || !!ts.forEachChild(node, needsMigrationChecker)
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** Check even erased type imports and unused source modules; tests are separate. */
|
|
336
|
+
export function checkPluginImports(root, depends = readDescriptor(root)?.depends ?? {}) {
|
|
337
|
+
root = resolve(root);
|
|
338
|
+
const declared = new Set();
|
|
339
|
+
const imports = new Map();
|
|
340
|
+
const tableOwners = new Set();
|
|
341
|
+
function checkFile(path) {
|
|
342
|
+
const parsed = ts.createSourceFile(path, readFileSync(path, "utf8"), ts.ScriptTarget.Latest, true);
|
|
343
|
+
const options = configuration(path, root).options;
|
|
344
|
+
const program = needsMigrationChecker(parsed)
|
|
345
|
+
? ts.createProgram([path], pluginCompilerOptions(root, options))
|
|
346
|
+
: undefined;
|
|
347
|
+
const source = program?.getSourceFile(path) ?? parsed;
|
|
348
|
+
const checker = program?.getTypeChecker();
|
|
349
|
+
function check(id) {
|
|
350
|
+
assertWindowImport(path, id);
|
|
351
|
+
if (id.startsWith("@tokamaq/sdk/internal/"))
|
|
352
|
+
throw new Error(`Internal SDK imports are reserved for the plugin build: ${path}`);
|
|
353
|
+
if (/^src\/(?:server|local)\//.test(relative(root, path).split(sep).join("/")))
|
|
354
|
+
assertWindowSide(path, id);
|
|
355
|
+
if (id.startsWith("plugin:")) {
|
|
356
|
+
if (!imports.has(id)) imports.set(id, path);
|
|
357
|
+
const reference = parsePluginSpecifier(id);
|
|
358
|
+
if (reference?.side === "tables" && Object.hasOwn(depends, reference.id))
|
|
359
|
+
tableOwners.add(reference.id);
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
if (id.startsWith("@plugins/")) throw diagnostic(path, id);
|
|
363
|
+
if (isBuiltin(id)) return;
|
|
364
|
+
const resolved = ts.resolveModuleName(id, path, options, ts.sys).resolvedModule;
|
|
365
|
+
if (resolved) {
|
|
366
|
+
const bare = !id.startsWith(".") && !isAbsolute(id);
|
|
367
|
+
assertPluginResolution(
|
|
368
|
+
root,
|
|
369
|
+
path,
|
|
370
|
+
id,
|
|
371
|
+
resolved.resolvedFileName,
|
|
372
|
+
bare && resolved.isExternalLibraryImport,
|
|
373
|
+
);
|
|
374
|
+
} else if (id.startsWith(".") || isAbsolute(id)) {
|
|
375
|
+
// Assets (including CSS) are outside TypeScript's module resolver.
|
|
376
|
+
const target = resolve(dirname(path), id.split("?")[0]);
|
|
377
|
+
assertPluginResolution(root, path, id, target);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
const sdkContracts = new Set();
|
|
381
|
+
const sdkNamespaces = new Set();
|
|
382
|
+
const sdkFactories = new Set();
|
|
383
|
+
const importedBinding = (node, bindings) =>
|
|
384
|
+
ts.isIdentifier(node) &&
|
|
385
|
+
checker?.getSymbolAtLocation(node)?.declarations?.some((declaration) => bindings.has(declaration));
|
|
386
|
+
const sdkNamespace = (node) => importedBinding(node, sdkNamespaces);
|
|
387
|
+
|
|
388
|
+
function functionsFactory(call) {
|
|
389
|
+
if (!call || !ts.isCallExpression(call)) return false;
|
|
390
|
+
const target = call.expression;
|
|
391
|
+
return (
|
|
392
|
+
importedBinding(target, sdkFactories) ||
|
|
393
|
+
(ts.isPropertyAccessExpression(target) &&
|
|
394
|
+
target.name.text === "createFunctions" &&
|
|
395
|
+
sdkNamespace(target.expression))
|
|
396
|
+
);
|
|
397
|
+
}
|
|
398
|
+
for (const node of source.statements) {
|
|
399
|
+
if (
|
|
400
|
+
!ts.isImportDeclaration(node) ||
|
|
401
|
+
!ts.isStringLiteralLike(node.moduleSpecifier) ||
|
|
402
|
+
node.moduleSpecifier.text !== "@tokamaq/sdk"
|
|
403
|
+
)
|
|
404
|
+
continue;
|
|
405
|
+
const bindings = node.importClause?.namedBindings;
|
|
406
|
+
if (!bindings) continue;
|
|
407
|
+
if (ts.isNamespaceImport(bindings)) {
|
|
408
|
+
sdkNamespaces.add(bindings);
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
for (const binding of bindings.elements) {
|
|
412
|
+
const imported = (binding.propertyName ?? binding.name).text;
|
|
413
|
+
if (imported === "local") throw new Error(`${path}: use action({ on: "caller", … })`);
|
|
414
|
+
if (imported === "createFunctions") sdkFactories.add(binding);
|
|
415
|
+
if (imported === "contract") sdkContracts.add(binding.name.text);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function visit(node) {
|
|
420
|
+
const local = localReceiver(node);
|
|
421
|
+
if (
|
|
422
|
+
local &&
|
|
423
|
+
(sdkNamespace(local) ||
|
|
424
|
+
functionsFactory(local) ||
|
|
425
|
+
(ts.isIdentifier(local) &&
|
|
426
|
+
checker
|
|
427
|
+
?.getSymbolAtLocation(local)
|
|
428
|
+
?.declarations?.some(
|
|
429
|
+
(declaration) =>
|
|
430
|
+
ts.isVariableDeclaration(declaration) && functionsFactory(declaration.initializer),
|
|
431
|
+
)))
|
|
432
|
+
) {
|
|
433
|
+
throw new Error(`${path}: use action({ on: "caller", … })`);
|
|
434
|
+
}
|
|
435
|
+
const replacement = removedClientMember(node);
|
|
436
|
+
if (replacement && checker) {
|
|
437
|
+
const receiver = checker.getTypeAtLocation(node.expression);
|
|
438
|
+
const sdkClient = receiver
|
|
439
|
+
.getProperty("action")
|
|
440
|
+
?.declarations?.some(
|
|
441
|
+
(declaration) =>
|
|
442
|
+
declaration.parent?.name?.text === "TokamaqClient" &&
|
|
443
|
+
inside(sdkRoot, declaration.getSourceFile().fileName),
|
|
444
|
+
);
|
|
445
|
+
const unknownClient =
|
|
446
|
+
(receiver.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0 &&
|
|
447
|
+
/(?:^|\.)(?:client|useClient\(\))$/i.test(node.expression.getText(source));
|
|
448
|
+
if (sdkClient || unknownClient) throw new Error(`${path}: ${replacement}`);
|
|
449
|
+
}
|
|
450
|
+
if (
|
|
451
|
+
ts.isCallExpression(node) &&
|
|
452
|
+
ts.isIdentifier(node.expression) &&
|
|
453
|
+
sdkContracts.has(node.expression.text)
|
|
454
|
+
) {
|
|
455
|
+
const options = node.arguments[1];
|
|
456
|
+
const place =
|
|
457
|
+
options && ts.isObjectLiteralExpression(options)
|
|
458
|
+
? options.properties.find(
|
|
459
|
+
({ name }) =>
|
|
460
|
+
name && (ts.isIdentifier(name) || ts.isStringLiteralLike(name)) && name.text === "place",
|
|
461
|
+
)
|
|
462
|
+
: undefined;
|
|
463
|
+
if (place)
|
|
464
|
+
throw new Error(
|
|
465
|
+
`${path}: ${contractPlacementMigration(ts.isPropertyAssignment(place) ? place.initializer : undefined)}`,
|
|
466
|
+
);
|
|
467
|
+
}
|
|
468
|
+
if (
|
|
469
|
+
(ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&
|
|
470
|
+
node.moduleSpecifier &&
|
|
471
|
+
ts.isStringLiteralLike(node.moduleSpecifier)
|
|
472
|
+
)
|
|
473
|
+
check(node.moduleSpecifier.text);
|
|
474
|
+
if (
|
|
475
|
+
ts.isImportTypeNode(node) &&
|
|
476
|
+
ts.isLiteralTypeNode(node.argument) &&
|
|
477
|
+
ts.isStringLiteralLike(node.argument.literal)
|
|
478
|
+
)
|
|
479
|
+
check(node.argument.literal.text);
|
|
480
|
+
if (
|
|
481
|
+
ts.isImportEqualsDeclaration(node) &&
|
|
482
|
+
ts.isExternalModuleReference(node.moduleReference) &&
|
|
483
|
+
node.moduleReference.expression &&
|
|
484
|
+
ts.isStringLiteralLike(node.moduleReference.expression)
|
|
485
|
+
)
|
|
486
|
+
check(node.moduleReference.expression.text);
|
|
487
|
+
if (
|
|
488
|
+
ts.isCallExpression(node) &&
|
|
489
|
+
(node.expression.kind === ts.SyntaxKind.ImportKeyword ||
|
|
490
|
+
(ts.isIdentifier(node.expression) && node.expression.text === "require"))
|
|
491
|
+
) {
|
|
492
|
+
const arg = node.arguments[0];
|
|
493
|
+
if (arg && ts.isStringLiteralLike(arg)) check(arg.text);
|
|
494
|
+
else
|
|
495
|
+
throw new Error(
|
|
496
|
+
`Dynamic plugin imports require a string literal: ${path}. Computed imports cannot be checked against the plugin boundary.`,
|
|
497
|
+
);
|
|
498
|
+
}
|
|
499
|
+
ts.forEachChild(node, visit);
|
|
500
|
+
}
|
|
501
|
+
visit(source);
|
|
502
|
+
for (const ref of source.referencedFiles) check(ref.fileName);
|
|
503
|
+
}
|
|
504
|
+
const visited = new Set();
|
|
505
|
+
function walk(dir) {
|
|
506
|
+
if (!existsSync(dir)) return;
|
|
507
|
+
const real = canonical(dir);
|
|
508
|
+
if (visited.has(real)) return;
|
|
509
|
+
visited.add(real);
|
|
510
|
+
// Check ordinary importing files before following directory links, so an
|
|
511
|
+
// escape reports the authored import whenever there is one.
|
|
512
|
+
const items = readdirSync(dir, { withFileTypes: true }).sort(
|
|
513
|
+
(a, b) => Number(a.isSymbolicLink()) - Number(b.isSymbolicLink()),
|
|
514
|
+
);
|
|
515
|
+
for (const item of items) {
|
|
516
|
+
const path = resolve(dir, item.name);
|
|
517
|
+
if (excluded.test(relative(root, path).split(sep).join("/")) || /^vite\.config\./.test(item.name))
|
|
518
|
+
continue;
|
|
519
|
+
if (item.isSymbolicLink() && !inside(canonical(root), canonical(path)))
|
|
520
|
+
throw diagnostic(path, item.name, canonical(path));
|
|
521
|
+
if (item.isDirectory() || (item.isSymbolicLink() && statSync(path).isDirectory())) walk(path);
|
|
522
|
+
else if (/\.[cm]?[jt]sx?$/.test(item.name)) checkFile(path);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
walk(root);
|
|
526
|
+
for (const [id, path] of imports) {
|
|
527
|
+
try {
|
|
528
|
+
declarePlugin(root, id, declared, depends, tableOwners);
|
|
529
|
+
} catch (error) {
|
|
530
|
+
throw new Error(`${diagnostic(path, id).message} ${error.message}`);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
export function bunPluginReferences(root, options) {
|
|
536
|
+
return {
|
|
537
|
+
name: "plugin-references",
|
|
538
|
+
setup(build) {
|
|
539
|
+
build.onResolve({ filter: /^@tokamaq\/sdk$/ }, ({ importer }) => {
|
|
540
|
+
if (importer.startsWith("plugin:")) return { path: Bun.resolveSync("@tokamaq/sdk", root) };
|
|
541
|
+
});
|
|
542
|
+
build.onResolve({ filter: /^plugin:/ }, ({ path, importer }) => {
|
|
543
|
+
const restricted =
|
|
544
|
+
typeof options?.publicOnly === "function" ? options.publicOnly(importer) : options?.publicOnly;
|
|
545
|
+
return { path, namespace: restricted ? "public-plugin-reference" : "plugin-reference" };
|
|
546
|
+
});
|
|
547
|
+
for (const namespace of ["plugin-reference", "public-plugin-reference"])
|
|
548
|
+
build.onLoad({ filter: /.*/, namespace }, ({ path }) => ({
|
|
549
|
+
contents: pluginReferenceSource(root, path, {
|
|
550
|
+
publicOnly: namespace === "public-plugin-reference",
|
|
551
|
+
}),
|
|
552
|
+
loader: "js",
|
|
553
|
+
resolveDir: root,
|
|
554
|
+
}));
|
|
555
|
+
},
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
export function bunPluginBoundary(root, { publicOnly = false } = {}) {
|
|
560
|
+
return {
|
|
561
|
+
name: "plugin-import-boundary",
|
|
562
|
+
setup(build) {
|
|
563
|
+
bunPluginReferences(root, { publicOnly }).setup(build);
|
|
564
|
+
build.onResolve({ filter: /.*/, namespace: "file" }, ({ path, importer }) => {
|
|
565
|
+
if (!importer || !isAbsolute(importer) || path.startsWith("node:") || isBuiltin(path)) return;
|
|
566
|
+
assertWindowSide(importer, path);
|
|
567
|
+
const target = Bun.resolveSync(path, dirname(importer));
|
|
568
|
+
if (
|
|
569
|
+
(typeof publicOnly === "function" ? publicOnly(importer) : publicOnly) &&
|
|
570
|
+
isInternalReferenceModule(canonical(target))
|
|
571
|
+
)
|
|
572
|
+
throw new Error(
|
|
573
|
+
`Local code cannot import internal references: ${path}. Import the generated public api instead.`,
|
|
574
|
+
);
|
|
575
|
+
const bare = !path.startsWith(".") && !isAbsolute(path);
|
|
576
|
+
// Bun resolves workspace symlinks to their real location. A bare import
|
|
577
|
+
// must also resolve via node_modules, not a tsconfig source alias.
|
|
578
|
+
assertPluginResolution(
|
|
579
|
+
root,
|
|
580
|
+
importer,
|
|
581
|
+
path,
|
|
582
|
+
target,
|
|
583
|
+
bare &&
|
|
584
|
+
Boolean(
|
|
585
|
+
ts.resolveModuleName(path, importer, configuration(importer, root).options, ts.sys)
|
|
586
|
+
.resolvedModule?.isExternalLibraryImport,
|
|
587
|
+
),
|
|
588
|
+
);
|
|
589
|
+
});
|
|
590
|
+
},
|
|
591
|
+
};
|
|
592
|
+
}
|