@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,254 @@
1
+ import { createHash } from "node:crypto";
2
+ import ts from "typescript";
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { relative, resolve, sep } from "node:path";
5
+ import { declaredActionPlacement, definitionTypeInfo, runtimeExportNames } from "./plugin-compiler.mjs";
6
+
7
+ import { contractName, MEMBER_HOOK_RUN } from "../src/internal/contracts.ts";
8
+ const unalias = (checker, symbol) =>
9
+ symbol && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
10
+ const brand = (type, name) => type.getProperties().some((p) => p.name.startsWith(`__@${name}@`));
11
+
12
+ export const contractEntry = (folder) => resolve(folder, "src/contracts.ts");
13
+
14
+ export function importedContractEntry(root, id) {
15
+ if (id === "auth") return resolve(import.meta.dirname, "../core-contracts/auth.ts");
16
+ const source = contractEntry(resolve(root, "..", id));
17
+ // Optional dependencies can distribute their contract types separately from
18
+ // the defining plugin. The checked-in copy is never executable at runtime.
19
+ return existsSync(source) ? source : resolve(root, "contracts", id + ".ts");
20
+ }
21
+
22
+ export function contractPlacementMigration(value) {
23
+ const on = value && ts.isStringLiteralLike(value) && value.text === "server" ? "server" : "caller";
24
+ return `use contract(name, { on: "${on}" })`;
25
+ }
26
+
27
+ function nonDataMethods(entry, exported, data, file) {
28
+ const declared = new Set(
29
+ data && ts.isArrayLiteralExpression(data)
30
+ ? data.elements.filter(ts.isStringLiteralLike).map((name) => name.text)
31
+ : [],
32
+ );
33
+ // The normal path needs only the syntax tree. Resolve the contract's type to
34
+ // report method names only when rejecting an old or incomplete declaration.
35
+ const program = ts.createProgram([entry], { noEmit: true, skipLibCheck: true });
36
+ const source = program.getSourceFile(entry);
37
+ const checker = program.getTypeChecker();
38
+ const call = source?.statements
39
+ .filter(ts.isVariableStatement)
40
+ .flatMap((statement) => [...statement.declarationList.declarations])
41
+ .find((declaration) => declaration.name.getText(source) === exported)?.initializer;
42
+ const node = call && ts.isCallExpression(call) && call.typeArguments?.[0];
43
+ const names = node
44
+ ? checker
45
+ .getTypeFromTypeNode(node)
46
+ .getProperties()
47
+ .flatMap((property) => {
48
+ const type = checker.getNonNullableType(checker.getTypeOfSymbolAtLocation(property, node));
49
+ return type.getCallSignatures().length && !declared.has(property.name) ? [property.name] : [];
50
+ })
51
+ : [];
52
+ return names.length ? names.join(", ") : (data?.getText(file) ?? "all methods");
53
+ }
54
+
55
+ /** A public contract module describes types and keys, and is never loaded by its providers. */
56
+ export function contractDeclarations(entry) {
57
+ if (!existsSync(entry)) return [];
58
+ const text = readFileSync(entry, "utf8");
59
+ const declarationHash = createHash("sha256").update(text).digest("hex");
60
+ const file = ts.createSourceFile(entry, text, ts.ScriptTarget.Latest, true);
61
+ const imports = new Set();
62
+ const contracts = [];
63
+ for (const statement of file.statements) {
64
+ if (ts.isImportDeclaration(statement) && statement.moduleSpecifier.text === "@tokamaq/sdk")
65
+ for (const field of statement.importClause?.namedBindings?.elements ?? [])
66
+ if ((field.propertyName ?? field.name).text === "contract") imports.add(field.name.text);
67
+ if (
68
+ !ts.isVariableStatement(statement) ||
69
+ !statement.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)
70
+ )
71
+ continue;
72
+ for (const { name, initializer: call } of statement.declarationList.declarations) {
73
+ if (
74
+ !ts.isIdentifier(name) ||
75
+ !call ||
76
+ !ts.isCallExpression(call) ||
77
+ !imports.has(call.expression.getText(file))
78
+ )
79
+ throw new Error(`${entry} must export contracts declared with contract<T>("name", options)`);
80
+ const [key, options] = call.arguments;
81
+ const property = (name) =>
82
+ options && ts.isObjectLiteralExpression(options)
83
+ ? options.properties.find(
84
+ (p) => ts.isPropertyAssignment(p) && p.name.getText(file).replace(/['"]/g, "") === name,
85
+ )?.initializer
86
+ : undefined;
87
+ const on = property("on");
88
+ const place = property("place");
89
+ if (place) throw new Error(`${entry}: ${contractPlacementMigration(place)}`);
90
+ if (
91
+ !key ||
92
+ !ts.isStringLiteralLike(key) ||
93
+ !contractName.test(key.text) ||
94
+ (options && (!on || !ts.isStringLiteralLike(on) || !["caller", "server"].includes(on.text)))
95
+ )
96
+ throw new Error(`${entry}: contract names and on values must be literals`);
97
+ const local = on?.text === "caller";
98
+ if (contracts.some((item) => item.name === key.text))
99
+ throw new Error(`${entry}: duplicate contract ${key.text}`);
100
+ const data = property("dataMethods");
101
+ if (data && !local) throw new Error(`${entry}: dataMethods requires a caller contract`);
102
+ if (data && data.kind !== ts.SyntaxKind.TrueKeyword) {
103
+ const missing = nonDataMethods(entry, name.text, data, file);
104
+ throw new Error(
105
+ `${entry}: caller contract "${key.text}" requires dataMethods: true on QuickJS; non-data methods: ${missing}`,
106
+ );
107
+ }
108
+ contracts.push({
109
+ exported: name.text,
110
+ name: key.text,
111
+ on: local ? "caller" : "server",
112
+ declarationHash,
113
+ dataMethods: local ? true : undefined,
114
+ memberHook: call.typeArguments?.[0]?.getText(file) === "MemberHook",
115
+ });
116
+ }
117
+ }
118
+ return contracts;
119
+ }
120
+
121
+ export function discoverProviders(root, files, program, checker) {
122
+ const entry = contractEntry(root);
123
+ const providers = [];
124
+ const seen = new Set();
125
+ for (const path of files) {
126
+ const source = program.getSourceFile(path);
127
+ const module = checker.getSymbolAtLocation(source);
128
+ if (!module) continue;
129
+ const runtime = runtimeExportNames(checker, module);
130
+ for (const exported of checker.getExportsOfModule(module)) {
131
+ if (!runtime.has(exported.name)) continue;
132
+ const target = unalias(checker, exported);
133
+ const type = checker.getTypeOfSymbolAtLocation(target, source);
134
+ if (seen.has(target) || !brand(type, "providerBrand")) continue;
135
+ const memberHook = brand(type, "memberHookProviderBrand");
136
+ const declaration = target.valueDeclaration;
137
+ if (!declaration || declaration.getSourceFile() !== source) continue;
138
+ const call = ts.isExportAssignment(declaration) ? declaration.expression : declaration.initializer;
139
+ if (!call || !ts.isCallExpression(call) || ![2, 3].includes(call.arguments.length))
140
+ throw new Error(`${path}: export the result of provide(contract, implementation) directly`);
141
+ seen.add(target);
142
+ const [key, implementation, options] = call.arguments;
143
+ const keySymbol = unalias(
144
+ checker,
145
+ checker.getSymbolAtLocation(ts.isPropertyAccessExpression(key) ? key.name : key),
146
+ );
147
+ const keyFile = keySymbol?.valueDeclaration?.getSourceFile().fileName;
148
+ const imported =
149
+ keyFile && /[\\/]\.tokamaq[\\/]types[\\/]([^\\/]+)[\\/]contracts\.d\.ts$/.exec(keyFile);
150
+ const owner = imported?.[1];
151
+ const ownerEntry = owner ? importedContractEntry(root, owner) : entry;
152
+ const contract =
153
+ (owner || keyFile === entry) &&
154
+ contractDeclarations(ownerEntry).find((item) => item.exported === keySymbol?.name);
155
+ if (!contract)
156
+ throw new Error(
157
+ `${path}: provide requires a named contract from src/contracts.ts or plugin:<id>/contracts`,
158
+ );
159
+ let unavailable;
160
+ if (options) {
161
+ const field = ts.isObjectLiteralExpression(options) && options.properties[0];
162
+ if (
163
+ contract.on !== "caller" ||
164
+ !field ||
165
+ options.properties.length !== 1 ||
166
+ !ts.isPropertyAssignment(field) ||
167
+ field.name.getText(source) !== "unavailable" ||
168
+ !ts.isStringLiteralLike(field.initializer) ||
169
+ !field.initializer.text ||
170
+ Buffer.byteLength(field.initializer.text) > 1024
171
+ )
172
+ throw new Error(`${path}: provider options must be { unavailable: "message" } (up to 1024 bytes)`);
173
+ unavailable = field.initializer.text;
174
+ }
175
+ const local = relative(root, path).split(sep).join("/");
176
+ const methods = [];
177
+ if (memberHook) {
178
+ if (owner !== "auth" || !contract.memberHook)
179
+ throw new Error(`${path}: onMember requires an auth membership event`);
180
+ methods.push({ member: MEMBER_HOOK_RUN, kind: "mutation", field: implementation, argument: true });
181
+ } else if (contract.on === "server" || ts.isObjectLiteralExpression(implementation)) {
182
+ if (!ts.isObjectLiteralExpression(implementation))
183
+ throw new Error(`${path}: a server provider must declare its members in an object literal`);
184
+ for (const field of implementation.properties) {
185
+ if (
186
+ (!ts.isShorthandPropertyAssignment(field) && !ts.isPropertyAssignment(field)) ||
187
+ !(ts.isIdentifier(field.name) || ts.isStringLiteralLike(field.name)) ||
188
+ !contractName.test(field.name.text)
189
+ ) {
190
+ // Spread and computed Runner methods are resolved when the provider binds.
191
+ if (contract.on === "caller") continue;
192
+ throw new Error(`${path}: a server provider requires statically named members`);
193
+ }
194
+ const value = ts.isShorthandPropertyAssignment(field) ? field.name : field.initializer;
195
+ const actual = checker.getTypeAtLocation(value);
196
+ const info = definitionTypeInfo(checker, actual, value);
197
+ if (info?.kind === "httpAction")
198
+ throw new Error(`${path}: HTTP actions cannot provide contract methods`);
199
+ const expression = ts.isShorthandPropertyAssignment(field)
200
+ ? checker.getShorthandAssignmentValueSymbol(field)?.valueDeclaration?.initializer
201
+ : value;
202
+ const on =
203
+ info?.on ?? (info?.kind === "action" ? declaredActionPlacement(checker, expression) : undefined);
204
+ if (contract.on === "caller" && info?.kind && (info.kind !== "action" || on !== "caller"))
205
+ throw new Error(
206
+ `${path}: contract "${contract.name}" method "${field.name.text}" requires action({ on: "caller" })`,
207
+ );
208
+ if (info?.kind) methods.push({ member: field.name.text, kind: info.kind, on, field });
209
+ }
210
+ }
211
+ providers.push({
212
+ ...contract,
213
+ exported: exported.name,
214
+ owner,
215
+ path,
216
+ registration: `${local.replace(/\.tsx?$/, "")}:${exported.name}`,
217
+ call,
218
+ methods,
219
+ unavailable,
220
+ });
221
+ }
222
+ }
223
+ return providers;
224
+ }
225
+
226
+ // Names are private registry keys, disjoint from authored modules. The
227
+ // manifest ties each such key to one provider and one contract owner.
228
+ export const contractTarget = (provider, method) => `$contract:${provider.registration}:${method.member}`;
229
+
230
+ export function contractManifest(root, namespace, providers = []) {
231
+ const contracts = contractDeclarations(contractEntry(root)).map(
232
+ ({ name, on, declarationHash, dataMethods }) => ({
233
+ name,
234
+ on,
235
+ declarationHash,
236
+ dataMethods,
237
+ }),
238
+ );
239
+ return {
240
+ contracts,
241
+ contractProviders: providers.map((p) => ({
242
+ owner: p.owner ?? namespace,
243
+ name: p.name,
244
+ declarationHash: p.declarationHash,
245
+ on: p.on,
246
+ dataMethods: p.dataMethods,
247
+ registration: p.registration,
248
+ unavailable: p.unavailable,
249
+ methods: Object.fromEntries(
250
+ p.on === "caller" ? [] : p.methods.map((method) => [method.member, contractTarget(p, method)]),
251
+ ),
252
+ })),
253
+ };
254
+ }
@@ -0,0 +1,42 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { lanes, placedModules } from "./placement.mjs";
3
+
4
+ export function httpActionEntry(placement, root, organized) {
5
+ const modules = placedModules(placement, root, organized, lanes.http.keep);
6
+ if (!modules.length) return;
7
+ const routes = Object.create(null);
8
+ const shapes = new Set();
9
+ const adapter = fileURLToPath(new URL("../src/http-action.ts", import.meta.url));
10
+ const imports = [`import { bindHttpAction } from ${JSON.stringify(adapter)};`];
11
+ const handlers = [];
12
+ for (const [file, , names] of modules) {
13
+ for (const name of names) {
14
+ const { path } = placement.modules.get(file).get(name);
15
+ if (typeof path !== "string")
16
+ throw new Error(`${file}:${name}: HTTP action path must be a string literal`);
17
+ if (Object.hasOwn(routes, path)) throw new Error(`Duplicate HTTP action path: ${path}`);
18
+ const parts = path.slice(1).split("/");
19
+ const shape = parts.map((part) => (part.startsWith(":") ? ":" : part)).join("/");
20
+ if (shapes.has(shape)) throw new Error(`Ambiguous HTTP action path: ${path}`);
21
+ shapes.add(shape);
22
+ if (
23
+ path === "/reload" ||
24
+ (parts.length >= 3 &&
25
+ parts[0] &&
26
+ parts[0] !== "*" &&
27
+ parts[1] === "assets" &&
28
+ (parts.length > 3 || (parts[2] && parts[2] !== "*")))
29
+ )
30
+ throw new Error(`HTTP action path only matches a reserved core route: ${path}`);
31
+ const binding = `route${imports.length}`;
32
+ routes[path] = true;
33
+ imports.push(`import { ${JSON.stringify(name)} as ${binding} } from ${JSON.stringify(file)};`);
34
+ handlers.push(`[${JSON.stringify(path)}]: bindHttpAction(${binding})`);
35
+ }
36
+ }
37
+ return {
38
+ modules,
39
+ paths: Object.keys(routes),
40
+ source: imports.join("\n") + `\nexport const handlers = { ${handlers.join(", ")} };\n`,
41
+ };
42
+ }