@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.
Files changed (71) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1403 -2
  3. package/build-internals.ts +25 -0
  4. package/caller/agent-launch.ts +60 -0
  5. package/client.tsx +498 -0
  6. package/component-actions.ts +327 -0
  7. package/component-alerts.ts +136 -0
  8. package/component-attributes.ts +340 -0
  9. package/component-parts.tsx +1177 -0
  10. package/core-contracts/auth.ts +40 -0
  11. package/package.json +98 -4
  12. package/quit.ts +58 -0
  13. package/regions.tsx +94 -0
  14. package/screen-search.ts +211 -0
  15. package/send-file.ts +175 -0
  16. package/server-build-internals.ts +11 -0
  17. package/solid.ts +132 -0
  18. package/src/agent-command.ts +48 -0
  19. package/src/agent-info-cache.ts +34 -0
  20. package/src/agent-reports.ts +140 -0
  21. package/src/agent-turn.ts +289 -0
  22. package/src/api.ts +174 -0
  23. package/src/auth.ts +39 -0
  24. package/src/call-error.ts +37 -0
  25. package/src/caller-storage.ts +32 -0
  26. package/src/client.ts +163 -0
  27. package/src/database.ts +322 -0
  28. package/src/functions.ts +726 -0
  29. package/src/hooks.ts +141 -0
  30. package/src/host.ts +211 -0
  31. package/src/http-action.ts +55 -0
  32. package/src/index.ts +126 -0
  33. package/src/internal/contracts.ts +260 -0
  34. package/src/internal/machine-scope.ts +21 -0
  35. package/src/local.ts +22 -0
  36. package/src/plugin.ts +162 -0
  37. package/src/points.ts +79 -0
  38. package/src/protocol.ts +64 -0
  39. package/src/schema.ts +136 -0
  40. package/src/storage.ts +193 -0
  41. package/src/thread-context.ts +42 -0
  42. package/src/transport.ts +421 -0
  43. package/src/triggers.ts +87 -0
  44. package/src/unstable.ts +66 -0
  45. package/src/validators.ts +248 -0
  46. package/src/values.ts +98 -0
  47. package/src/visibility.ts +8 -0
  48. package/src/websocket-transport.ts +91 -0
  49. package/src/window-state-protocol.ts +7 -0
  50. package/src/within.ts +24 -0
  51. package/src/worker-limits.ts +5 -0
  52. package/tools/bundle.mjs +490 -0
  53. package/tools/client-entry.mjs +10 -0
  54. package/tools/contracts.mjs +254 -0
  55. package/tools/http-actions.mjs +42 -0
  56. package/tools/placement.mjs +535 -0
  57. package/tools/plugin-boundary.mjs +592 -0
  58. package/tools/plugin-compiler.mjs +125 -0
  59. package/tools/plugin-descriptor.ts +75 -0
  60. package/tools/points.mjs +340 -0
  61. package/tools/result-validator.mjs +83 -0
  62. package/tools/server-builtins.mjs +82 -0
  63. package/tools/server-files.mjs +34 -0
  64. package/tools/table-references.mjs +98 -0
  65. package/tools/worker.mjs +110 -0
  66. package/tsconfig.plugin-server.json +12 -0
  67. package/tsconfig.plugin-window.json +15 -0
  68. package/view.ts +27 -0
  69. package/web.d.ts +6 -0
  70. package/window-state-host.ts +228 -0
  71. package/window-state.ts +43 -0
@@ -0,0 +1,125 @@
1
+ import { Visibility } from "../src/visibility.ts";
2
+ import ts from "typescript";
3
+ import { relative, resolve, sep } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ export const generated = (root) => resolve(root, ".tokamaq/types");
7
+
8
+ export function serverConfigPath(directory, pluginRoot) {
9
+ return (
10
+ ts.findConfigFile(directory, (path) => {
11
+ const fromPlugin = relative(pluginRoot, path);
12
+ return !fromPlugin.startsWith(".." + sep) && ts.sys.fileExists(path);
13
+ }) ?? fileURLToPath(new URL("../tsconfig.plugin-server.json", import.meta.url))
14
+ );
15
+ }
16
+
17
+ export function pluginCompilerOptions(root, options) {
18
+ // Resolve inherited paths at their declaring config, before adding our own.
19
+ const base = options.baseUrl ?? options.pathsBasePath ?? root;
20
+ const paths = Object.fromEntries(
21
+ Object.entries(options.paths ?? {}).map(([key, values]) => [
22
+ key,
23
+ values.map((value) => resolve(base, value)),
24
+ ]),
25
+ );
26
+ return {
27
+ ...options,
28
+ paths: {
29
+ ...paths,
30
+ "plugin:*/tables": [resolve(generated(root), "*/tables.d.ts")],
31
+ "plugin:*/contracts": [resolve(generated(root), "*/contracts.d.ts")],
32
+ "plugin:*/server": [resolve(generated(root), "*/server.d.ts")],
33
+ "plugin:*/client": [resolve(generated(root), "*/client.d.ts")],
34
+ "plugin:*": [resolve(generated(root), "*/server.d.ts")],
35
+ },
36
+ };
37
+ }
38
+
39
+ /** Runtime exports only: erased named/star re-exports must never grant references. */
40
+ export function runtimeExportNames(checker, module, seen = new Set()) {
41
+ if (seen.has(module)) return new Set();
42
+ seen.add(module);
43
+ const file = module.declarations?.find(ts.isSourceFile);
44
+ if (!file) return new Set();
45
+ const names = new Set(
46
+ checker
47
+ .getExportsOfModule(module)
48
+ .filter(
49
+ (symbol) =>
50
+ symbol.flags & ts.SymbolFlags.Value && symbol.declarations?.some((d) => d.getSourceFile() === file),
51
+ )
52
+ .map((symbol) => symbol.name),
53
+ );
54
+ for (const statement of file.statements) {
55
+ if (!ts.isExportDeclaration(statement) || statement.isTypeOnly) continue;
56
+ if (!statement.exportClause) {
57
+ if (!statement.moduleSpecifier) continue;
58
+ const target = checker.getSymbolAtLocation(statement.moduleSpecifier);
59
+ if (target)
60
+ for (const name of runtimeExportNames(checker, target, new Set(seen))) {
61
+ if (name !== "default") names.add(name);
62
+ }
63
+ } else if (ts.isNamedExports(statement.exportClause)) {
64
+ for (const item of statement.exportClause.elements) if (!item.isTypeOnly) names.add(item.name.text);
65
+ } else names.add(statement.exportClause.name.text);
66
+ }
67
+ return names;
68
+ }
69
+
70
+ export function definitionInfo(checker, symbol, source) {
71
+ const info = definitionTypeInfo(checker, checker.getTypeOfSymbolAtLocation(symbol, source), source);
72
+ if (info?.kind === "action" && info.on === undefined) {
73
+ const target = symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
74
+ info.on = declaredActionPlacement(checker, target.valueDeclaration?.initializer);
75
+ }
76
+ return info;
77
+ }
78
+
79
+ export function declaredActionPlacement(checker, expression, seen = new Set()) {
80
+ if (!expression || seen.has(expression)) return;
81
+ seen.add(expression);
82
+ if (ts.isIdentifier(expression)) {
83
+ const symbol = checker.getSymbolAtLocation(expression);
84
+ const target = symbol?.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
85
+ return declaredActionPlacement(checker, target?.valueDeclaration?.initializer, seen);
86
+ }
87
+ if (!ts.isCallExpression(expression)) return;
88
+ const options = expression.arguments[0];
89
+ return actionPlacementLiteral(checker, options) ?? declaredActionPlacement(checker, options, seen);
90
+ }
91
+
92
+ export function actionPlacementLiteral(checker, options) {
93
+ if (!options || !ts.isObjectLiteralExpression(options)) return;
94
+ const field = [...options.properties].reverse().find((property) => {
95
+ if (ts.isSpreadAssignment(property))
96
+ return !!checker.getTypeAtLocation(property.expression).getProperty("on");
97
+ const name = property.name;
98
+ return name && (ts.isIdentifier(name) || ts.isStringLiteralLike(name)) && name.text === "on";
99
+ });
100
+ if (!field || !ts.isPropertyAssignment(field)) return;
101
+ let value = field.initializer;
102
+ while (ts.isAsExpression(value) || ts.isParenthesizedExpression(value)) value = value.expression;
103
+ if (!ts.isStringLiteralLike(value)) return;
104
+ return /^(server|caller|machine:[\w-]+|device:[\w-]+|[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})$/.test(
105
+ value.text,
106
+ )
107
+ ? value.text
108
+ : undefined;
109
+ }
110
+
111
+ export function definitionTypeInfo(checker, type, source) {
112
+ if (type.getProperties().some((property) => property.name.startsWith("__@httpActionBrand@"))) {
113
+ const path = type.getProperty("path");
114
+ return { kind: "httpAction", path: path && checker.getTypeOfSymbolAtLocation(path, source).value };
115
+ }
116
+ if (!type.getProperties().some((property) => property.name.startsWith("__@definitionBrand@"))) return;
117
+ const kind = type.getProperty("kind");
118
+ const property = type.getProperty("visibility");
119
+ const visibility = property && checker.getTypeOfSymbolAtLocation(property, source).value;
120
+ return {
121
+ kind: kind && checker.getTypeOfSymbolAtLocation(kind, source).value,
122
+ on: type.getProperty("on") && checker.getTypeOfSymbolAtLocation(type.getProperty("on"), source).value,
123
+ visibility: Object.values(Visibility).includes(visibility) ? visibility : undefined,
124
+ };
125
+ }
@@ -0,0 +1,75 @@
1
+ /** Parse authored descriptors without evaluating plugin code. */
2
+ import ts from "typescript";
3
+ import { resolve } from "node:path";
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import type { PluginDefinition } from "../src/plugin.ts";
6
+
7
+ export function readDescriptor(root: string): PluginDefinition | undefined {
8
+ const path = resolve(root, "plugin.ts");
9
+ if (!existsSync(path)) return;
10
+ const source = ts.createSourceFile(path, readFileSync(path, "utf8"), ts.ScriptTarget.Latest, true);
11
+ const fail = (): never => {
12
+ throw new Error("plugin.ts must export default definePlugin({...}) with static literal metadata");
13
+ };
14
+ const helper = source.statements.flatMap((statement) =>
15
+ ts.isImportDeclaration(statement) &&
16
+ ts.isStringLiteral(statement.moduleSpecifier) &&
17
+ statement.moduleSpecifier.text === "@tokamaq/sdk" &&
18
+ statement.importClause?.namedBindings &&
19
+ ts.isNamedImports(statement.importClause.namedBindings)
20
+ ? statement.importClause.namedBindings.elements
21
+ .filter((e) => (e.propertyName ?? e.name).text === "definePlugin")
22
+ .map((e) => e.name.text)
23
+ : [],
24
+ );
25
+ const assignment = source.statements.find(ts.isExportAssignment);
26
+ if (!assignment || assignment.isExportEquals || !ts.isCallExpression(assignment.expression)) return fail();
27
+ const call = assignment.expression;
28
+ if (
29
+ !ts.isIdentifier(call.expression) ||
30
+ !helper.includes(call.expression.text) ||
31
+ call.arguments.length !== 1
32
+ )
33
+ return fail();
34
+ function literal(node: ts.Node): unknown {
35
+ if (ts.isStringLiteralLike(node)) return node.text;
36
+ if (ts.isArrayLiteralExpression(node)) return node.elements.map(literal);
37
+ if (ts.isObjectLiteralExpression(node)) {
38
+ const result: Record<string, unknown> = {};
39
+ for (const property of node.properties) {
40
+ if (
41
+ !ts.isPropertyAssignment(property) ||
42
+ !(ts.isIdentifier(property.name) || ts.isStringLiteral(property.name))
43
+ )
44
+ return fail();
45
+ const key = property.name.text;
46
+ if (Object.hasOwn(result, key)) return fail();
47
+ result[key] = literal(property.initializer);
48
+ }
49
+ return result;
50
+ }
51
+ return fail();
52
+ }
53
+ const value = literal(call.arguments[0]!) as Record<string, unknown>;
54
+ const allowed = [
55
+ "id",
56
+ "version",
57
+ "name",
58
+ "description",
59
+ "depends",
60
+ "optional",
61
+ "permissions",
62
+ "runtime",
63
+ "maintenance",
64
+ ];
65
+ if (!value || Array.isArray(value) || Object.keys(value).some((key) => !allowed.includes(key)))
66
+ return fail();
67
+ for (const key of ["depends", "optional"]) {
68
+ if (value[key] === undefined) continue;
69
+ const ids = value[key];
70
+ if (!Array.isArray(ids) || ids.some((id) => typeof id !== "string") || new Set(ids).size !== ids.length)
71
+ return fail();
72
+ value[key] = Object.fromEntries(ids.map((id) => [id, "*"]));
73
+ }
74
+ return value as unknown as PluginDefinition;
75
+ }
@@ -0,0 +1,340 @@
1
+ import ts from "typescript";
2
+ import { includesUndefined, validatorFromType } from "./result-validator.mjs";
3
+
4
+ export function originalSymbol(checker, symbol) {
5
+ return symbol?.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
6
+ }
7
+
8
+ function pointCall(checker, node) {
9
+ return (
10
+ ts.isCallExpression(node) &&
11
+ checker
12
+ .getTypeAtLocation(node.expression)
13
+ .getProperties()
14
+ .some((property) => property.name.startsWith("__@pointBrand@"))
15
+ );
16
+ }
17
+
18
+ function legacyPointCall(checker, node) {
19
+ if (!ts.isCallExpression(node)) return false;
20
+ const access = node.expression;
21
+ const member = ts.isPropertyAccessExpression(access)
22
+ ? access.name
23
+ : ts.isElementAccessExpression(access) && access.argumentExpression;
24
+ if (!member || member.text !== "point" || checker.getSymbolAtLocation(member)) return false;
25
+
26
+ const receiver = checker.getTypeAtLocation(access.expression);
27
+ return (
28
+ receiver.getProperty("call") || (ts.isIdentifier(access.expression) && access.expression.text === "ctx")
29
+ );
30
+ }
31
+
32
+ function referencedDeclaration(checker, node) {
33
+ if (!(ts.isIdentifier(node) || ts.isStringLiteralLike(node))) return;
34
+ if (ts.isDeclarationName(node) && !ts.isShorthandPropertyAssignment(node.parent)) return;
35
+ if (ts.isImportSpecifier(node.parent) || ts.isImportClause(node.parent)) return;
36
+ return originalSymbol(
37
+ checker,
38
+ checker.getShorthandAssignmentValueSymbol(node.parent) ?? checker.getSymbolAtLocation(node),
39
+ )?.valueDeclaration;
40
+ }
41
+
42
+ function callableBody(declaration) {
43
+ if (!declaration) return;
44
+ if (ts.isFunctionLike(declaration)) return declaration;
45
+ if (ts.isVariableDeclaration(declaration) || ts.isPropertyAssignment(declaration))
46
+ return declaration.initializer;
47
+ }
48
+
49
+ function sourceLocation(node) {
50
+ const file = node.getSourceFile();
51
+ const { line, character } = file.getLineAndCharacterOfPosition(node.getStart());
52
+ return `${file.fileName}:${line + 1}:${character + 1}`;
53
+ }
54
+
55
+ function traceHandler(checker, declaration, file, follow) {
56
+ const seen = new Set();
57
+ function find(node) {
58
+ if (!node || seen.has(node) || node.getSourceFile() !== file) return;
59
+ seen.add(node);
60
+ if (ts.isObjectLiteralExpression(node)) {
61
+ for (const property of node.properties) {
62
+ if (ts.isSpreadAssignment(property)) find(property.expression);
63
+ const name = property.name;
64
+ if (!name || !(ts.isIdentifier(name) || ts.isStringLiteral(name)) || name.text !== "handler")
65
+ continue;
66
+ if (ts.isPropertyAssignment(property)) follow(property.initializer);
67
+ else if (ts.isShorthandPropertyAssignment(property)) follow(property.name);
68
+ else if (ts.isMethodDeclaration(property)) follow(property);
69
+ }
70
+ return;
71
+ }
72
+ const local = referencedDeclaration(checker, node);
73
+ if (local && ts.isVariableDeclaration(local)) find(local.initializer);
74
+ if (!ts.isFunctionLike(node)) ts.forEachChild(node, find);
75
+ }
76
+ find(ts.isVariableDeclaration(declaration) ? declaration.initializer : declaration);
77
+ }
78
+
79
+ function traceOwner(checker, declaration) {
80
+ const file = declaration.getSourceFile();
81
+ const edges = new Map();
82
+ function follow(node) {
83
+ if (!node || edges.has(node) || node.getSourceFile() !== file) return;
84
+ const children = [];
85
+ edges.set(node, children);
86
+ const add = (child) => {
87
+ if (!child || child.getSourceFile() !== file) return;
88
+ children.push(child);
89
+ follow(child);
90
+ };
91
+ ts.forEachChild(node, add);
92
+ // A static member reference follows that member, not its siblings.
93
+ if (!staticReceiver(node)) add(callableBody(referencedDeclaration(checker, node)));
94
+ }
95
+ traceHandler(checker, declaration, file, follow);
96
+ return edges;
97
+ }
98
+
99
+ function staticReceiver(node) {
100
+ const parent = node.parent;
101
+ return (
102
+ parent?.expression === node &&
103
+ (ts.isPropertyAccessExpression(parent) ||
104
+ (ts.isElementAccessExpression(parent) && ts.isStringLiteralLike(parent.argumentExpression)))
105
+ );
106
+ }
107
+
108
+ function unsafeReference(call, edges, references) {
109
+ const parents = new Map();
110
+ for (const [node, children] of edges) {
111
+ for (const child of children) {
112
+ const incoming = parents.get(child) ?? [];
113
+ incoming.push(node);
114
+ parents.set(child, incoming);
115
+ }
116
+ }
117
+ const reachesPoint = new Set([call]);
118
+ for (const node of reachesPoint) {
119
+ for (const parent of parents.get(node) ?? []) reachesPoint.add(parent);
120
+ }
121
+ for (const [outside, declaration] of references) {
122
+ if (edges.has(outside)) continue;
123
+ const body = callableBody(declaration);
124
+ const escapesObject =
125
+ ts.isObjectLiteralExpression(body) &&
126
+ !staticReceiver(outside) &&
127
+ body.properties.some((property) => reachesPoint.has(callableBody(property)));
128
+ if (reachesPoint.has(body) || escapesObject) {
129
+ const inside = references.find(([node, target]) => target === declaration && reachesPoint.has(node));
130
+ return { outside, inside: inside?.[0] };
131
+ }
132
+ }
133
+ }
134
+
135
+ export function discoverPoints(files, checker, definitions, warn = () => {}) {
136
+ const owners = new Map();
137
+ const calls = new Map();
138
+ const references = [];
139
+ function collect(node) {
140
+ if (legacyPointCall(checker, node))
141
+ throw new Error(`${sourceLocation(node)}: Import point from "@tokamaq/sdk" and write point(ctx, ...).`);
142
+ if (pointCall(checker, node)) calls.set(node, []);
143
+ ts.forEachChild(node, collect);
144
+ }
145
+ for (const file of files) if (file) collect(file);
146
+ if (!calls.size) return owners;
147
+
148
+ function collectReferences(node) {
149
+ const declaration = referencedDeclaration(checker, node);
150
+ if (callableBody(declaration)) references.push([node, declaration]);
151
+ ts.forEachChild(node, collectReferences);
152
+ }
153
+ for (const file of files) if (file) collectReferences(file);
154
+
155
+ for (const symbol of new Set(definitions)) {
156
+ if (!symbol?.valueDeclaration) continue;
157
+ const edges = traceOwner(checker, symbol.valueDeclaration);
158
+ for (const [call, matches] of calls) if (edges.has(call)) matches.push({ symbol, edges });
159
+ }
160
+ for (const [call, matches] of calls) {
161
+ const error = (message) => {
162
+ throw new Error(`${sourceLocation(call)}: ${message}`);
163
+ };
164
+ const [, name] = call.arguments;
165
+ if (!name || !ts.isStringLiteralLike(name))
166
+ error("A point name must be a string literal; pass a literal name.");
167
+ if (!name.text || name.text.includes("#")) error('A point name cannot be empty or contain "#".');
168
+ const ambiguous = (sites) =>
169
+ error(
170
+ `Cannot attribute point "${name.text}" to exactly one exported query, mutation or action${sites}; call it in that function's handler or a helper in the same module used only by that handler.`,
171
+ );
172
+ if (matches.length !== 1)
173
+ ambiguous(
174
+ matches.length
175
+ ? ` (${matches.map(({ symbol }) => sourceLocation(symbol.valueDeclaration)).join(", ")})`
176
+ : "",
177
+ );
178
+ const [{ symbol: owner, edges }] = matches;
179
+ const conflict = unsafeReference(call, edges, references);
180
+ if (conflict)
181
+ ambiguous(
182
+ ` (owner at ${sourceLocation(conflict.inside ?? owner.valueDeclaration)}, other use at ${sourceLocation(conflict.outside)})`,
183
+ );
184
+ const points = owners.get(owner) ?? new Map();
185
+ if (points.has(name.text)) error(`Duplicate point name "${name.text}" in the same function.`);
186
+
187
+ points.set(name.text, pointTypes(checker, call, name.text, error, warn));
188
+ owners.set(owner, points);
189
+ }
190
+ return owners;
191
+ }
192
+
193
+ function pointTypes(checker, call, name, error, warn) {
194
+ const signature = checker.getResolvedSignature(call);
195
+ if (![3, 4].includes(call.arguments.length) || !signature?.parameters[2])
196
+ error("A point takes a context, name, data, and an optional callback or { collect: true }.");
197
+ const input = checker.getTypeOfSymbolAtLocation(signature.parameters[2], call);
198
+ const invalid = () => error(`Point "${name}" requires plain data; describe it as data, or use \`after\`.`);
199
+ let result;
200
+ if (call.arguments.length === 4) {
201
+ const option =
202
+ signature.parameters[3] && checker.getTypeOfSymbolAtLocation(signature.parameters[3], call);
203
+ const run = option?.getCallSignatures()[0];
204
+ if (run) {
205
+ result = checker.getAwaitedType(checker.getReturnTypeOfSignature(run));
206
+ if (!result) invalid();
207
+ } else if (!option?.getProperty("collect")) {
208
+ invalid();
209
+ }
210
+ }
211
+ let empty = false;
212
+ const emptyLiteral = () => {
213
+ empty = true;
214
+ };
215
+ const types = {
216
+ input: dataType(checker, input, call, invalid, emptyLiteral),
217
+ result: result && dataType(checker, result, call, invalid, emptyLiteral, true),
218
+ validators: {
219
+ args: validatorFromType(checker, input, call, true),
220
+ result: result && validatorFromType(checker, result, call, true),
221
+ },
222
+ };
223
+ if (empty)
224
+ warn(
225
+ `${sourceLocation(call)}: Point "${name}" infers an empty object or never[]; annotate empty literals with the types hooks may return (e.g. Record<string, string> or string[]).`,
226
+ );
227
+ return types;
228
+ }
229
+
230
+ // A consumer cannot name the owner's private type aliases. Spell out the
231
+ // data shape and use local aliases only for cycles in the type graph.
232
+ function dataType(checker, root, location, invalid, emptyLiteral, result = false) {
233
+ const active = new Map();
234
+ const recursive = [];
235
+ const reference = (index) => `\x00${index}\x00`;
236
+ const list = (value) => `(${value})[]`;
237
+ function visit(type, optional = false, normalize = false) {
238
+ const existing = active.get(type);
239
+ if (existing) {
240
+ if (existing.index === undefined) {
241
+ existing.index = recursive.length;
242
+ recursive.push(existing);
243
+ }
244
+ return reference(existing.index);
245
+ }
246
+ if (active.size >= 64) invalid();
247
+ const node = {};
248
+ active.set(type, node);
249
+ node.body = render(type, optional, normalize);
250
+ active.delete(type);
251
+ return node.index === undefined ? node.body : reference(node.index);
252
+ }
253
+
254
+ function render(type, optional, normalize) {
255
+ const flags = type.flags;
256
+ if (normalize && flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined)) return "null";
257
+ if (flags & ts.TypeFlags.Undefined && optional) return "undefined";
258
+ if (type.isLiteral() && !(flags & ts.TypeFlags.BigIntLiteral)) return JSON.stringify(type.value);
259
+ if (
260
+ flags &
261
+ (ts.TypeFlags.Any |
262
+ ts.TypeFlags.Unknown |
263
+ ts.TypeFlags.Never |
264
+ ts.TypeFlags.StringLike |
265
+ ts.TypeFlags.NumberLike |
266
+ ts.TypeFlags.BooleanLike |
267
+ ts.TypeFlags.Null)
268
+ )
269
+ return checker.typeToString(type);
270
+ if (type.isUnionOrIntersection()) {
271
+ const operator = type.isUnion() ? " | " : " & ";
272
+ return `(${type.types.map((member) => visit(member, optional, normalize)).join(operator)})`;
273
+ }
274
+ if (checker.isTupleType(type)) {
275
+ const items = checker.getTypeArguments(type).map((item, i) => {
276
+ const flag = type.target.elementFlags[i];
277
+ const optional = Boolean(flag & ts.ElementFlags.Optional);
278
+ const value = visit(item, optional);
279
+ if (flag & ts.ElementFlags.Rest) return `...${list(value)}`;
280
+ return optional ? `(${value})?` : value;
281
+ });
282
+ return `${type.target.readonly ? "readonly " : ""}[${items.join(", ")}]`;
283
+ }
284
+ if (checker.isArrayType(type)) {
285
+ if (checker.getTypeArguments(type)[0].flags & ts.TypeFlags.Never) emptyLiteral();
286
+ return `${type.target.symbol?.name === "ReadonlyArray" ? "readonly " : ""}${list(visit(checker.getTypeArguments(type)[0]))}`;
287
+ }
288
+ if (
289
+ !(flags & ts.TypeFlags.Object) ||
290
+ type.getCallSignatures().length ||
291
+ type.getConstructSignatures().length ||
292
+ type.getSymbol()?.declarations?.some(ts.isClassLike)
293
+ )
294
+ invalid();
295
+
296
+ const fields = checker.getIndexInfosOfType(type).map((index) => {
297
+ if (index.keyType.flags & ts.TypeFlags.ESSymbolLike) invalid();
298
+ return `${index.isReadonly ? "readonly " : ""}[key: ${visit(index.keyType)}]: ${visit(index.type)};`;
299
+ });
300
+ for (const field of type.getProperties()) {
301
+ if (field.name.startsWith("__@") || field.declarations?.some(ts.isAccessor)) invalid();
302
+ const name = ts.isIdentifierText(field.name, ts.ScriptTarget.Latest)
303
+ ? field.name
304
+ : JSON.stringify(field.name);
305
+ const fieldType = checker.getTypeOfSymbolAtLocation(field, location);
306
+ const optional = Boolean(field.flags & ts.SymbolFlags.Optional) || includesUndefined(fieldType);
307
+ const readonly =
308
+ Boolean(ts.getCheckFlags(field) & ts.CheckFlags.Readonly) ||
309
+ field.declarations?.some((node) => ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Readonly);
310
+ const value = visit(fieldType, optional);
311
+ fields.push(`${readonly ? "readonly " : ""}${name}${optional ? "?" : ""}: ${value};`);
312
+ }
313
+ if (!fields.length) emptyLiteral();
314
+ return `{ ${fields.join(" ")} }`;
315
+ }
316
+
317
+ const body = visit(root, false, result);
318
+ return { body, recursive: recursive.map(({ body }) => body) };
319
+ }
320
+
321
+ export function pointReferenceTypes(points, kind, namespace, qualified, aliases) {
322
+ if (!points?.size) return "";
323
+ const render = ({ body, recursive }) => {
324
+ const offset = aliases.length;
325
+ const qualify = (source) =>
326
+ source.replaceAll(/\x00(\d+)\x00/g, (_, index) => `PointData${offset + Number(index)}`);
327
+ recursive.forEach((type, index) =>
328
+ aliases.push(`type PointData${offset + index} = ${qualify(type)};
329
+ `),
330
+ );
331
+ return qualify(body);
332
+ };
333
+ return ` & { readonly points: {${[...points]
334
+ .map(([name, { input, result }]) => {
335
+ const argsType = render(input);
336
+ const resultType = result ? render(result) : argsType;
337
+ return `readonly ${JSON.stringify(name)}: import("@tokamaq/sdk").PointReference<${JSON.stringify(kind)}, ${argsType}, ${resultType}, ${JSON.stringify(namespace) ?? "string"}, ${JSON.stringify(`${qualified}#${name}`)}, ${!result}>;`;
338
+ })
339
+ .join("")}} }`;
340
+ }
@@ -0,0 +1,83 @@
1
+ import ts from "typescript";
2
+
3
+ // Turn a finite wire type into the same validator format used for arguments.
4
+ // Open or recursive subtrees leave the surrounding type intact.
5
+ export function resultValidator(checker, definition, location) {
6
+ const returns = definition.getProperty("returns");
7
+ if (returns && !(returns.flags & ts.SymbolFlags.Optional)) return;
8
+ const types = definition.getProperty("_types");
9
+ if (!types) return;
10
+ const carrier = checker.getNonNullableType(checker.getTypeOfSymbolAtLocation(types, location));
11
+ const result = carrier.getProperty("result");
12
+ if (!result) return;
13
+ return validatorFromType(checker, checker.getTypeOfSymbolAtLocation(result, location), location);
14
+ }
15
+
16
+ export function includesUndefined(type) {
17
+ return (
18
+ Boolean(type.flags & ts.TypeFlags.Undefined) || (type.isUnion() && type.types.some(includesUndefined))
19
+ );
20
+ }
21
+
22
+ export function validatorFromType(checker, type, location, point = false) {
23
+ const visit = (type, ancestors, optional = false) => {
24
+ if (ancestors.length >= 16 || ancestors.includes(type)) return { kind: "any" };
25
+ const nested = [...ancestors, type];
26
+ const flags = type.flags;
27
+ if (type.aliasSymbol?.name === "JsonValue" || flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
28
+ return { kind: "any" };
29
+ if (optional && flags & ts.TypeFlags.Undefined) return { kind: "never" };
30
+ if (flags & ts.TypeFlags.Never) return { kind: "never" };
31
+ if (flags & (ts.TypeFlags.Void | ts.TypeFlags.Null | ts.TypeFlags.Undefined)) return { kind: "null" };
32
+ if (flags & ts.TypeFlags.Boolean) return { kind: "boolean" };
33
+ if (flags & ts.TypeFlags.BooleanLiteral) return { kind: "literal", value: type.intrinsicName === "true" };
34
+ if (type.isLiteral()) return { kind: "literal", value: type.value };
35
+ if (flags & ts.TypeFlags.String) return { kind: "string" };
36
+ if (flags & ts.TypeFlags.Number) return { kind: "number" };
37
+ if (type.isUnion()) {
38
+ const members = type.types
39
+ .filter((member) => !optional || !(member.flags & ts.TypeFlags.Undefined))
40
+ .map((member) => visit(member, nested));
41
+ return { kind: "union", members };
42
+ }
43
+ if (checker.isTupleType(type)) {
44
+ return {
45
+ kind: "tuple",
46
+ items: checker.getTypeArguments(type).map((item, index) => {
47
+ const flags = type.target.elementFlags[index];
48
+ return {
49
+ value: visit(item, nested, Boolean(flags & ts.ElementFlags.Optional)),
50
+ optional: Boolean(flags & ts.ElementFlags.Optional),
51
+ rest: Boolean(flags & ts.ElementFlags.Rest),
52
+ };
53
+ }),
54
+ };
55
+ }
56
+ if (checker.isArrayType(type)) {
57
+ const item = visit(checker.getTypeArguments(type)[0], nested);
58
+ return { kind: "array", item };
59
+ }
60
+ if (type.isIntersection() && type.types.some((member) => member.flags & ts.TypeFlags.String)) {
61
+ const brand = type.getProperty("__table");
62
+ if (brand) {
63
+ const table = checker.getTypeOfSymbolAtLocation(brand, location);
64
+ if (table.isStringLiteral()) return { kind: "id", table: table.value };
65
+ }
66
+ return { kind: "string" };
67
+ }
68
+ if (!(flags & ts.TypeFlags.Object || type.isIntersection())) return { kind: "any" };
69
+ if (checker.getIndexInfosOfType(type).length) return { kind: "any" };
70
+ if (type.getCallSignatures().length) return { kind: "any" };
71
+
72
+ const fields = [];
73
+ for (const field of type.getProperties()) {
74
+ if (field.name.startsWith("__@")) continue;
75
+ const fieldType = checker.getTypeOfSymbolAtLocation(field, location);
76
+ const optional = field.flags & ts.SymbolFlags.Optional || (point && includesUndefined(fieldType));
77
+ const inner = visit(fieldType, nested, Boolean(optional));
78
+ fields.push([field.name, optional ? { kind: "optional", inner } : inner]);
79
+ }
80
+ return fields.length || point ? { kind: "object", fields: Object.fromEntries(fields) } : { kind: "any" };
81
+ };
82
+ return visit(type, []);
83
+ }