@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.
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,82 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { isBuiltin } from "node:module";
3
+ import { isAbsolute, relative } from "node:path";
4
+
5
+ const action = ["node:path", "node:os", "node:crypto", "node:url"];
6
+
7
+ // The QuickJS host must supply exactly this list.
8
+ export const suppliedNodeModules = { action, local: [...action, "node:fs/promises"] };
9
+
10
+ export function nodeModule(path) {
11
+ if (path.startsWith("node:") || path === "bun" || path.startsWith("bun:")) return path;
12
+ if (isBuiltin(path)) return `node:${path}`;
13
+ }
14
+
15
+ function unavailable(pluginRoot, importer, module, lane) {
16
+ const file = isAbsolute(importer) ? relative(pluginRoot, importer) : importer;
17
+ const advice = suppliedNodeModules.local.includes(module)
18
+ ? ' Move it into an action with on: "caller".'
19
+ : "";
20
+
21
+ return new Error(
22
+ `Plugin import boundary: ${file} imports ${JSON.stringify(module)}, which is unavailable in ${lane}.${advice} A plugin that needs real Node can start it through proc in a caller action.`,
23
+ );
24
+ }
25
+
26
+ export function workerBuiltins(pluginRoot) {
27
+ const supplied = suppliedNodeModules.local;
28
+
29
+ return {
30
+ name: "worker-node-builtins",
31
+ setup(build) {
32
+ build.onResolve({ filter: /.*/ }, ({ path, importer }) => {
33
+ // Bun injects its own node:module import for the require shim.
34
+ if (!importer || importer === "runtime") return;
35
+
36
+ const module = nodeModule(path);
37
+ if (!module || supplied.includes(module)) return;
38
+
39
+ throw unavailable(pluginRoot, importer, module, "caller actions");
40
+ });
41
+ },
42
+ };
43
+ }
44
+
45
+ export function serverBuiltins(name, pluginRoot, lane, { callerFiles, onStub } = {}) {
46
+ return {
47
+ name,
48
+ setup(build) {
49
+ build.onResolve({ filter: /.*/ }, ({ path, importer }) => {
50
+ if (!importer) return;
51
+
52
+ const module = nodeModule(path);
53
+ if (suppliedNodeModules.local.includes(module) && callerFiles?.has(importer)) {
54
+ onStub?.(importer);
55
+ return { path: module, namespace: "unavailable-machine-module" };
56
+ }
57
+
58
+ if (module) throw unavailable(pluginRoot, importer, module, lane);
59
+ });
60
+ build.onLoad({ filter: /.*/, namespace: "unavailable-machine-module" }, async ({ path }) => {
61
+ const names = Object.keys(await import(path)).filter(
62
+ (name) => /^[a-zA-Z_$][\w$]*$/.test(name) && name !== "default",
63
+ );
64
+ const bindings = names.map(
65
+ (name, i) => `const binding${i} = unavailable; export {binding${i} as ${name}};`,
66
+ );
67
+ return {
68
+ contents: `import { requireActionMachine } from ${JSON.stringify(fileURLToPath(new URL("../src/functions.ts", import.meta.url)))};
69
+ const fail = () => requireActionMachine(${JSON.stringify(`This needs a machine: ${path} is not available on the server`)});
70
+ const unavailable = new Proxy(function () {}, {
71
+ apply: fail,
72
+ construct: fail,
73
+ get: fail,
74
+ });
75
+ ${bindings.join("\n")}
76
+ export default unavailable;`,
77
+ loader: "ts",
78
+ };
79
+ });
80
+ },
81
+ };
82
+ }
@@ -0,0 +1,34 @@
1
+ import { existsSync } from "node:fs";
2
+ import { basename, dirname, resolve } from "node:path";
3
+
4
+ export function serverDirectory(root) {
5
+ if (existsSync(resolve(root, "src/server"))) return resolve(root, "src/server");
6
+ return resolve(root, "src");
7
+ }
8
+
9
+ export function isServerRoot(root) {
10
+ return basename(root) === "server" && basename(dirname(root)) === "src";
11
+ }
12
+
13
+ export function isInternalReferenceModule(file) {
14
+ return basename(dirname(file)) === "_generated" && ["internal.ts", "plugin.ts"].includes(basename(file));
15
+ }
16
+
17
+ /** The authored modules registered by the server bundler. */
18
+ export function isServerModule(root, file) {
19
+ return (
20
+ file.endsWith(".ts") &&
21
+ !file
22
+ .split("/")
23
+ .some(
24
+ (part) =>
25
+ part === ".." ||
26
+ part.startsWith("_") ||
27
+ part.startsWith(".") ||
28
+ ["node_modules", "dist", "tests"].includes(part),
29
+ ) &&
30
+ !(isServerRoot(root) && file === "api.ts") &&
31
+ file !== "schema.ts" &&
32
+ !/\.(d|test|spec)\.ts$/.test(file)
33
+ );
34
+ }
@@ -0,0 +1,98 @@
1
+ import ts from "typescript";
2
+ import { existsSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { pluginCompilerOptions } from "./plugin-compiler.mjs";
5
+ import { serverDirectory } from "./server-files.mjs";
6
+
7
+ const quote = JSON.stringify;
8
+
9
+ /** Read inferred schema types without executing the owner's code. */
10
+ export function tableReferences(folder, owner, config) {
11
+ const entry = resolve(serverDirectory(folder), "schema.ts");
12
+ if (!existsSync(entry)) return [];
13
+ const program = ts.createProgram([entry], pluginCompilerOptions(folder, config));
14
+ const checker = program.getTypeChecker();
15
+ const source = program.getSourceFile(entry);
16
+ const module = checker.getSymbolAtLocation(source);
17
+ const schema = module && checker.getExportsOfModule(module).find((symbol) => symbol.name === "default");
18
+ const tables = schema && checker.getTypeOfSymbolAtLocation(schema, source).getProperty("tables");
19
+ const typeOf = (symbol) => checker.getTypeOfSymbolAtLocation(symbol, source);
20
+
21
+ function render(type, omitUndefined = false, ancestors = new Set()) {
22
+ if (type.aliasSymbol?.name === "Id") {
23
+ const argument = type.aliasTypeArguments[0];
24
+ const members = argument.isUnion() ? argument.types : [argument];
25
+ const names = members.map((member) =>
26
+ member.isStringLiteral() && !member.value.includes(".")
27
+ ? quote(`${owner}.${member.value}`)
28
+ : checker.typeToString(member),
29
+ );
30
+ return `Id<${names.join(" | ")}>`;
31
+ }
32
+ if (type.aliasSymbol?.name === "JsonValue") return "JsonValue";
33
+ if (type.isUnion() || type.isIntersection()) {
34
+ const members = type.types.filter(
35
+ (member) => !omitUndefined || !(member.flags & ts.TypeFlags.Undefined),
36
+ );
37
+ if (members.length === 1) return render(members[0], false, ancestors);
38
+ return (
39
+ members.map((member) => render(member, false, ancestors)).join(type.isUnion() ? " | " : " & ") ||
40
+ "never"
41
+ );
42
+ }
43
+ if (!(type.flags & ts.TypeFlags.Object)) return checker.typeToString(type);
44
+ if (ancestors.has(type)) throw new Error(`Plugin ${owner}: recursive table field types cannot be copied`);
45
+ return renderObject(type, new Set(ancestors).add(type));
46
+ }
47
+
48
+ function renderObject(type, ancestors) {
49
+ const args = checker.getTypeArguments(type);
50
+ if (checker.isArrayType(type)) return `Array<${render(args[0], false, ancestors)}>`;
51
+ if (checker.isTupleType(type))
52
+ return `[${args.map((item) => render(item, false, ancestors)).join(", ")}]`;
53
+ const properties = type.getProperties().map((property) => {
54
+ const optional = Boolean(property.flags & ts.SymbolFlags.Optional);
55
+ return `${quote(property.name)}${optional ? "?" : ""}: ${render(typeOf(property), optional, ancestors)}`;
56
+ });
57
+ const index = type.getStringIndexType();
58
+ if (index) properties.push(`[key: string]: ${render(index, false, ancestors)}`);
59
+ return `{ ${properties.join("; ")} }`;
60
+ }
61
+
62
+ return (tables ? typeOf(tables).getProperties() : []).map((table) => {
63
+ const fields = typeOf(table).getProperty("fields");
64
+ const document = (fields ? typeOf(fields).getProperties() : []).map((field) => {
65
+ const validator = typeOf(field);
66
+ const optional = validator.getProperty("optional");
67
+ const value = validator.getProperty("_type");
68
+ const fieldType = value ? render(typeOf(value), true) : "never";
69
+ return `${quote(field.name)}${optional && checker.typeToString(typeOf(optional)) === "true" ? "?" : ""}: ${fieldType}`;
70
+ });
71
+ return { name: table.name, qualified: `${owner}.${table.name}`, document: `{ ${document.join("; ")} }` };
72
+ });
73
+ }
74
+
75
+ export function tableDeclarations(owner, tables, allowed) {
76
+ // Preserve the owner in missing-property diagnostics, even when it exports no tables.
77
+ return (
78
+ '// Generated table handles. Do not edit.\nimport type { Id, JsonValue, TableReference } from "@tokamaq/sdk";\n' +
79
+ `export declare const tables: {\n readonly [Symbol.toStringTag]?: ${quote(owner)};\n` +
80
+ tables
81
+ .map(
82
+ ({ name, qualified, document }) =>
83
+ ` readonly ${quote(name)}: ${
84
+ allowed
85
+ ? `TableReference<${quote(qualified)}, ${document}>`
86
+ : `{ readonly ${quote(`Declare ${owner} in depends to reference ${qualified}`)}: never }`
87
+ };\n`,
88
+ )
89
+ .join("") +
90
+ "};\n"
91
+ );
92
+ }
93
+
94
+ export function tableReferenceSource(tables) {
95
+ return `export const tables = Object.freeze({${tables
96
+ .map(({ name, qualified }) => `[${quote(name)}]: Object.freeze({ qualifiedName: ${quote(qualified)} })`)
97
+ .join(",")}});\n`;
98
+ }
@@ -0,0 +1,110 @@
1
+ import { isServerRoot } from "./server-files.mjs";
2
+ import { Visibility } from "../src/visibility.ts";
3
+ import { join } from "node:path";
4
+ import { functionPlacement, lanes, placementTransform, registrySource } from "./placement.mjs";
5
+ import { bunPluginBoundary } from "./plugin-boundary.mjs";
6
+ import { contractTarget } from "./contracts.mjs";
7
+ import { serverBuiltins, workerBuiltins } from "./server-builtins.mjs";
8
+
9
+ export function transactionSources({
10
+ root,
11
+ files,
12
+ modules,
13
+ hasSchema,
14
+ header,
15
+ pluginRoot,
16
+ placement,
17
+ namespace,
18
+ }) {
19
+ const paths = files.map((file) => join(root, file));
20
+ placement ??= functionPlacement(pluginRoot, { files: paths, configRoot: root }, namespace);
21
+ const inLane = (keep) =>
22
+ paths.flatMap((path, index) => {
23
+ const definitions = placement?.modules.get(path);
24
+ const names = definitions
25
+ ? [...definitions].filter(([, definition]) => keep(definition.kind)).map(([name]) => name)
26
+ : [];
27
+ return names.length ? [[path, modules[index], names]] : [];
28
+ });
29
+ const actions = inLane((kind) => kind === "action");
30
+ // The action process validates arguments. Transactions only need the
31
+ // action metadata to advertise and route those calls.
32
+ const metadata = actions.flatMap(([path, module, names]) =>
33
+ names.map((name) => ({
34
+ name: `${module}:${name}`,
35
+ kind: "action",
36
+ args: { kind: "any" },
37
+ visibility: placement.modules.get(path).get(name).visibility,
38
+ on: placement.modules.get(path).get(name).on,
39
+ })),
40
+ );
41
+ const providers = placement?.providers ?? [];
42
+ for (const provider of providers)
43
+ for (const method of provider.methods)
44
+ if (method.kind === "action")
45
+ metadata.push({
46
+ name: contractTarget(provider, method),
47
+ kind: "action",
48
+ args: { kind: "any" },
49
+ visibility: Visibility.Internal,
50
+ on: method.on,
51
+ });
52
+ return {
53
+ source: registrySource({
54
+ root,
55
+ modules: inLane(lanes.descriptor.keep),
56
+ hasSchema,
57
+ metadata,
58
+ placement,
59
+ hasActionHooks: inLane((kind) => kind === "actionHook").length > 0,
60
+ results: placement?.results(root, isServerRoot(root)),
61
+ points: placement?.points(root, isServerRoot(root)),
62
+ providers,
63
+ lane: lanes.descriptor,
64
+ header,
65
+ }),
66
+ plugins: [
67
+ serverBuiltins("transaction-builtins", pluginRoot, "queries and mutations"),
68
+ ...(placement ? [placementTransform(placement, lanes.descriptor)] : []),
69
+ ],
70
+ };
71
+ }
72
+
73
+ export async function buildLocalBundle({ root, sdkRoot, pluginRoot, source, plugins, actionModules }) {
74
+ const result = await Bun.build({
75
+ entrypoints: ["tokamaq-worker:entry"],
76
+ target: "node",
77
+ format: "esm",
78
+ packages: "bundle",
79
+ sourcemap: "external",
80
+ outdir: join(root, "dist"),
81
+ naming: "local.js",
82
+ env: "disable",
83
+ plugins: [
84
+ workerBuiltins(pluginRoot),
85
+ bunPluginBoundary(pluginRoot, { publicOnly: (path) => !actionModules.has(path) }),
86
+ ...plugins,
87
+ {
88
+ name: "worker-sdk",
89
+ setup(build) {
90
+ build.onResolve({ filter: /^@tokamaq\/sdk$/ }, () => ({ path: join(sdkRoot, "src/index.ts") }));
91
+ },
92
+ },
93
+ {
94
+ name: "worker-source",
95
+ setup(build) {
96
+ build.onResolve({ filter: /^tokamaq-worker:entry$/ }, () => ({
97
+ path: "entry",
98
+ namespace: "worker",
99
+ }));
100
+ build.onLoad({ filter: /.*/, namespace: "worker" }, () => ({
101
+ contents: source,
102
+ loader: "ts",
103
+ resolveDir: join(sdkRoot, "worker"),
104
+ }));
105
+ },
106
+ },
107
+ ],
108
+ });
109
+ if (!result.success) throw new AggregateError(result.logs, "Local bundle failed");
110
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "lib": ["ES2022"],
5
+ "module": "Preserve",
6
+ "moduleResolution": "bundler",
7
+ "verbatimModuleSyntax": true,
8
+ "strict": true,
9
+ "noEmit": true,
10
+ "types": []
11
+ }
12
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "Bundler",
6
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
7
+ "jsx": "preserve",
8
+ "jsxImportSource": "@solidjs/web",
9
+ "strict": true,
10
+ "skipLibCheck": true,
11
+ "noEmit": true,
12
+ "allowImportingTsExtensions": true,
13
+ "types": ["vite/client", "node"]
14
+ }
15
+ }
package/view.ts ADDED
@@ -0,0 +1,27 @@
1
+ import type { JSX } from "@solidjs/web";
2
+
3
+ const viewBrand: unique symbol = Symbol("tokamaq.view");
4
+
5
+ export interface ViewOptions {
6
+ readonly route: string;
7
+ readonly title?: string;
8
+ /** Single-colour SVG path in a 24 × 24 box for a page in the rail. */
9
+ readonly icon?: string;
10
+ }
11
+
12
+ /** Declare a page. The compiler publishes its screen parts. */
13
+ export function view<T extends (...args: never[]) => JSX.Element>(
14
+ options: ViewOptions,
15
+ render: T,
16
+ ): T & {
17
+ readonly [viewBrand]: string;
18
+ } {
19
+ return Object.assign(render, { [viewBrand]: options.route });
20
+ }
21
+
22
+ /** Route declared by a loaded page export. */
23
+ export function viewRoute(value: unknown): string | undefined {
24
+ return typeof value === "function" && viewBrand in value && typeof value[viewBrand] === "string"
25
+ ? value[viewBrand]
26
+ : undefined;
27
+ }
package/web.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ // Opt-in authoring types for browser-targeted dependencies such as the AI SDK.
2
+ // These declarations install no runtime API. Tokamaq implements the subset in
3
+ // packages/engine/WEB_APIS.md; unsupported browser APIs fail at runtime.
4
+ /// <reference lib="dom" />
5
+ /// <reference lib="dom.iterable" />
6
+ export {};
@@ -0,0 +1,228 @@
1
+ import { createSignal, onCleanup, type Signal } from "solid-js";
2
+ import { assertJson, jsonSnapshot, type JsonValue } from "./src/values";
3
+ import type { ClientTransport } from "./src/client";
4
+ import { readWindowState, writeWindowState } from "./src/window-state-protocol";
5
+ import { makeState, type StateOptions, type WindowState } from "./window-state";
6
+
7
+ export { windowStateModule } from "./src/window-state-protocol";
8
+ export type WindowStateTransport = Partial<Pick<ClientTransport, "query" | "mutation">>;
9
+
10
+ type Saved = { value: JsonValue } | null;
11
+ export interface WindowStateStorage {
12
+ device: {
13
+ read(key: string): Saved;
14
+ write(key: string, value: JsonValue): void;
15
+ };
16
+ me: {
17
+ read(key: string): Promise<Saved>;
18
+ write(key: string, value: JsonValue): Promise<unknown>;
19
+ };
20
+ report(error: unknown): void;
21
+ }
22
+
23
+ /** The workspace key separates device storage for different server connections. */
24
+ export function windowStateStorage(
25
+ plugin: string,
26
+ workspaceKey: string,
27
+ transport?: WindowStateTransport,
28
+ ): WindowStateStorage {
29
+ const deviceKey = (key: string) => JSON.stringify(["tokamaq.window-state", workspaceKey, plugin, key]);
30
+
31
+ return {
32
+ device: {
33
+ read(key) {
34
+ const stored = localStorage.getItem(deviceKey(key));
35
+ if (stored === null) return null;
36
+ const value: unknown = JSON.parse(stored);
37
+ assertJson(value, "saved window state");
38
+ return { value };
39
+ },
40
+ write(key, value) {
41
+ localStorage.setItem(deviceKey(key), JSON.stringify(value));
42
+ },
43
+ },
44
+ me: {
45
+ async read(key) {
46
+ if (!transport?.query) throw new Error("No server connection for window state");
47
+ const saved = await transport.query(readWindowState, { plugin, key });
48
+ if (saved === null) return null;
49
+ if (typeof saved === "object" && !Array.isArray(saved) && "value" in saved)
50
+ return { value: saved.value };
51
+ throw new Error("Invalid server window state");
52
+ },
53
+ async write(key, value) {
54
+ if (!transport?.mutation) throw new Error("No server connection for window state");
55
+ await transport.mutation(writeWindowState, { plugin, key, value });
56
+ },
57
+ },
58
+ report(error) {
59
+ // oxlint-disable-next-line no-console -- Report failed saves without unloading the plugin.
60
+ console.warn(`Window state for ${plugin}: ${String(error)}`);
61
+ },
62
+ };
63
+ }
64
+
65
+ /** One scope per plugin in the window. Generated modules receive it as a capability. */
66
+ export function createWindowState(storage?: WindowStateStorage) {
67
+ const cells = new Map<string, unknown>();
68
+ const mounted = new Map<string, Set<number>>();
69
+ const controller = new AbortController();
70
+ const unsaved = new Set<string>();
71
+ const [hasUnsavedChanges, setHasUnsavedChanges] = createSignal(false);
72
+ let site: string | undefined;
73
+
74
+ return {
75
+ hasUnsavedChanges,
76
+ dispose: () => controller.abort(),
77
+ at<T>(key: string, render: () => T): T {
78
+ const previous = site;
79
+ site = key;
80
+ try {
81
+ return render();
82
+ } finally {
83
+ site = previous;
84
+ }
85
+ },
86
+
87
+ instance(component: string, key?: unknown): string {
88
+ const name = JSON.stringify([
89
+ component,
90
+ site ?? null,
91
+ typeof key === "string" || typeof key === "number" ? key : null,
92
+ ]);
93
+ let slots = mounted.get(name);
94
+ if (!slots) mounted.set(name, (slots = new Set()));
95
+ let index = 0;
96
+ while (slots.has(index)) index++;
97
+ slots.add(index);
98
+ onCleanup(() => {
99
+ slots.delete(index);
100
+ if (!slots.size) mounted.delete(name);
101
+ });
102
+ return `${name}:${index}`;
103
+ },
104
+
105
+ state<T>(name: string, initial: T, options?: StateOptions): WindowState<T> {
106
+ const key = JSON.stringify(["state", name]);
107
+ const existing = cells.get(key) as WindowState<T> | undefined;
108
+ if (existing) return existing;
109
+ const cell = options?.keep
110
+ ? storedState(key, initial, options.keep, storage, controller.signal, (pending) => {
111
+ if (pending) unsaved.add(key);
112
+ else unsaved.delete(key);
113
+ setHasUnsavedChanges(unsaved.size > 0);
114
+ })
115
+ : makeState(initial).state;
116
+ cells.set(key, cell);
117
+ return cell;
118
+ },
119
+
120
+ signal<T>(name: string, create: () => Signal<T>): Signal<T> {
121
+ const key = JSON.stringify(["signal", name]);
122
+ if (!cells.has(key)) cells.set(key, create());
123
+ return cells.get(key) as Signal<T>;
124
+ },
125
+ };
126
+ }
127
+
128
+ function storedState<T>(
129
+ key: string,
130
+ initial: T,
131
+ keep: NonNullable<StateOptions["keep"]>,
132
+ storage: WindowStateStorage | undefined,
133
+ signal: AbortSignal,
134
+ markUnsaved: (pending: boolean) => void,
135
+ ): WindowState<T> {
136
+ if (!storage) throw new Error("Persistent state requires window storage");
137
+ jsonSnapshot(initial, "state");
138
+ if (keep === "device") {
139
+ let value = initial;
140
+ try {
141
+ const saved = storage.device.read(key);
142
+ if (saved) value = saved.value as T;
143
+ } catch (error) {
144
+ storage.report(error);
145
+ }
146
+ return makeState(value, (next) => {
147
+ const snapshot = jsonSnapshot(next, "state");
148
+ try {
149
+ storage.device.write(key, snapshot);
150
+ } catch (error) {
151
+ storage.report(error);
152
+ }
153
+ }).state;
154
+ }
155
+
156
+ let edits: ((previous: T) => T)[] | undefined = [];
157
+ let latestSave = 0;
158
+ const save = (snapshot: JsonValue) => {
159
+ const version = ++latestSave;
160
+ void storage.me.write(key, snapshot).then(() => {
161
+ if (!signal.aborted && version === latestSave) markUnsaved(false);
162
+ }, storage.report);
163
+ };
164
+ const cell = makeState(initial, (next, apply) => {
165
+ const snapshot = jsonSnapshot(next, "state");
166
+ if (signal.aborted) return;
167
+ markUnsaved(true);
168
+ if (edits) edits.push(apply);
169
+ else save(snapshot);
170
+ });
171
+ void readWithRetry(storage, key, signal)
172
+ .then((saved) => {
173
+ if (signal.aborted || !edits) return;
174
+ const queued = edits;
175
+ edits = undefined;
176
+ let value = saved ? (saved.value as T) : initial;
177
+ if (queued.length) {
178
+ try {
179
+ // Replay updater functions so early edits build on the saved state.
180
+ const updated = queued.reduce((previous, apply) => apply(previous), value);
181
+ save(jsonSnapshot(updated, "state"));
182
+ value = updated;
183
+ } catch (error) {
184
+ storage.report(error);
185
+ }
186
+ }
187
+ cell.restore(value);
188
+ })
189
+ .catch(storage.report);
190
+ return cell.state;
191
+ }
192
+
193
+ async function readWithRetry(storage: WindowStateStorage, key: string, signal: AbortSignal) {
194
+ let delay = 250;
195
+ while (!signal.aborted) {
196
+ try {
197
+ return await storage.me.read(key);
198
+ } catch (error) {
199
+ if (signal.aborted) return;
200
+ storage.report(error);
201
+ await new Promise<void>((resolve) => {
202
+ const finish = () => {
203
+ clearTimeout(timer);
204
+ signal.removeEventListener("abort", finish);
205
+ resolve();
206
+ };
207
+ const timer = setTimeout(finish, delay);
208
+ signal.addEventListener("abort", finish, { once: true });
209
+ });
210
+ delay = Math.min(delay * 2, 5_000);
211
+ }
212
+ }
213
+ }
214
+
215
+ type WindowStateScope = ReturnType<typeof createWindowState>;
216
+ const bindings = new Map<string, WindowStateScope>();
217
+
218
+ export function offerWindowState(binding: string, scope: WindowStateScope): () => void {
219
+ bindings.set(binding, scope);
220
+ return () => bindings.delete(binding);
221
+ }
222
+
223
+ export function claimWindowState(binding: string): WindowStateScope {
224
+ const scope = bindings.get(binding);
225
+ if (!scope) throw new Error("Window state binding has expired");
226
+ bindings.delete(binding);
227
+ return scope;
228
+ }
@@ -0,0 +1,43 @@
1
+ import { createMemo, createSignal, type Accessor, type Setter } from "solid-js";
2
+
3
+ const windowStateBrand: unique symbol = Symbol("tokamaq.window-state");
4
+
5
+ export type WindowState<T> = Accessor<T> & {
6
+ readonly [windowStateBrand]: true;
7
+ readonly set: Setter<T>;
8
+ };
9
+ export type WindowDerived<T> = Accessor<T> & { readonly [windowStateBrand]: true };
10
+
11
+ export interface StateOptions {
12
+ keep?: "device" | "me";
13
+ }
14
+
15
+ /** Read with `value()` and write with `value.set(next)`. */
16
+ export function state<T>(value: T, options?: StateOptions): WindowState<T> {
17
+ if (options?.keep) throw new Error("Persistent state requires the Tokamaq plugin build");
18
+ return makeState(value).state;
19
+ }
20
+
21
+ export function makeState<T>(value: T, write?: (value: T, apply: (previous: T) => T) => void) {
22
+ const [read, set] =
23
+ typeof value === "function"
24
+ ? createSignal<T>(() => value)
25
+ : createSignal<T>(value as Exclude<T, Function>);
26
+ const update = ((next: T | ((previous: T) => T)) => {
27
+ const apply = typeof next === "function" ? (next as (previous: T) => T) : () => next;
28
+ return set((previous) => {
29
+ const value = apply(previous);
30
+ write?.(value, apply);
31
+ return value;
32
+ });
33
+ }) as Setter<T>;
34
+ return {
35
+ state: Object.assign(read, { [windowStateBrand]: true as const, set: write ? update : set }),
36
+ restore: (value: T) => set(() => value),
37
+ };
38
+ }
39
+
40
+ /** A tracked computation, including Solid's Loading and isPending behavior. */
41
+ export function derived<T>(compute: () => T | PromiseLike<T>): WindowDerived<T> {
42
+ return Object.assign(createMemo<T>(compute), { [windowStateBrand]: true as const });
43
+ }