Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(native): a portable TypeScript logic core for arm C (#7988)

Cindy Zhang7380888e8a23
diff --git a/packages/native/README.md b/packages/native/README.md
index b52a209c1f..ca182a0aa8 100644
--- a/packages/native/README.md
+++ b/packages/native/README.md
@@ -20,6 +20,7 @@ rests on evidence.
| Native theme | `defineNativeTheme` | Durable theme intent (`material: 'opaque' \| 'translucent'`) plus platform entries scoped by OS version, such as Liquid Glass from iOS 26. Never sets tokens. |
| Icons | `NATIVE_ICON_DEFAULTS` | Astryx's built-in icon names mapped to SF Symbols on Apple platforms and Material Symbols on Android. |
| Wire | `AstryxNode`, `AstryxAction` | Each component as JSON a TypeScript core sends a native host (arm C), and the action a host sends back when a view calls a callback. Swift decodes `<Name>Node` and turns it into `<Name>Props` with `viewProps(send:)`. |
+| Logic core | `@astryxdesign/native/logic` | `createLogicCore` holds a screen's state, builds its node tree, and reduces actions; `connectBridge` carries it to a native host as JSON. ECMAScript built-ins only, so it runs in Hermes. Shaped after EJ Campbell's astryx-swift spike. |
Contracts cover Button, Card, Divider, Heading, HStack, ProgressBar, Selector,
Switch, Text, TextInput, and VStack. React Native and Android bindings are not built yet; see
@@ -95,6 +96,31 @@ if case .switch(let wifi) = node {
}
```
+```ts
+import {connectBridge, createLogicCore} from '@astryxdesign/native/logic';
+
+const core = createLogicCore<{wifi: boolean}, AstryxNode, AstryxAction>({
+ initial: {wifi: true},
+ view: state => ({
+ component: 'Switch',
+ key: 'wifi',
+ props: {label: 'Wi-Fi', value: state.wifi},
+ events: ['onChange'],
+ }),
+ reduce: (state, action) =>
+ action.component === 'Switch' && action.event === 'onChange'
+ ? {wifi: action.args[0]}
+ : state,
+});
+// In the app's JavaScript engine: the host reads snapshots and dispatches actions.
+const bridge = connectBridge(core, {
+ connected() {},
+ changed(json) {
+ /* to Swift */
+ },
+});
+```
+
## Working on it
```sh
diff --git a/packages/native/package.json b/packages/native/package.json
index 5fb837af7e..fa7cf635cb 100644
--- a/packages/native/package.json
+++ b/packages/native/package.json
@@ -62,6 +62,11 @@
"source": "./src/contract/index.ts",
"types": "./dist/contract/index.d.ts",
"default": "./dist/contract/index.js"
+ },
+ "./logic": {
+ "source": "./src/logic/index.ts",
+ "types": "./dist/logic/index.d.ts",
+ "default": "./dist/logic/index.js"
}
},
"scripts": {
diff --git a/packages/native/src/logic/connectBridge.ts b/packages/native/src/logic/connectBridge.ts
new file mode 100644
index 0000000000..1fa0c51f77
--- /dev/null
+++ b/packages/native/src/logic/connectBridge.ts
@@ -0,0 +1,72 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+//
+// Follows the bridge of EJ Campbell's astryx-swift spike
+// (github.com/ejc3/astryx-swift, MIT).
+
+/**
+ * @file logic/connectBridge.ts
+ * @input A logic core and the native host's two calls in
+ * @output The two calls the host makes: read the snapshot, dispatch an action
+ * @position Carries a logic core across a JavaScript engine boundary as JSON
+ * strings, the one form every engine bridge passes cheaply
+ */
+
+import type {LogicAction, LogicCore, LogicNode} from './createLogicCore.js';
+
+/** Bumped when the bridge's calls or their JSON change meaning. */
+export const BRIDGE_VERSION = 1;
+
+/** What the native host offers the core. */
+export interface BridgeHost {
+ /**
+ * The core is running and speaks this bridge version. Called while
+ * `connectBridge` runs, before it returns the bridge: read and dispatch
+ * through the returned bridge, not from inside this call.
+ */
+ connected(bridgeVersion: number): void;
+ /** The tree changed; here it is as JSON. */
+ changed(snapshotJSON: string): void;
+}
+
+export interface Bridge {
+ getSnapshot(): string;
+ /** An action as the host's JSON, such as Swift's `AstryxAction.json`. */
+ dispatch(actionJSON: string): void;
+ disconnect(): void;
+}
+
+function isAction(value: unknown): value is LogicAction {
+ if (typeof value !== 'object' || value === null) {
+ return false;
+ }
+ const action = value as Record<string, unknown>;
+ return (
+ typeof action.key === 'string' &&
+ typeof action.component === 'string' &&
+ typeof action.event === 'string' &&
+ Array.isArray(action.args)
+ );
+}
+
+export function connectBridge<
+ State,
+ Node extends LogicNode,
+ Action extends LogicAction,
+>(core: LogicCore<State, Node, Action>, host: BridgeHost): Bridge {
+ const unsubscribe = core.subscribe(() =>
+ host.changed(JSON.stringify(core.getSnapshot())),
+ );
+ host.connected(BRIDGE_VERSION);
+ return {
+ getSnapshot: () => JSON.stringify(core.getSnapshot()),
+ dispatch(actionJSON) {
+ const action: unknown = JSON.parse(actionJSON);
+ if (!isAction(action)) {
+ throw new Error(`Not an Astryx action: ${actionJSON}`);
+ }
+ // The host sends only actions for callbacks the tree listed in `events`.
+ core.dispatch(action as Action);
+ },
+ disconnect: unsubscribe,
+ };
+}
diff --git a/packages/native/src/logic/createLogicCore.ts b/packages/native/src/logic/createLogicCore.ts
new file mode 100644
index 0000000000..04b3924a98
--- /dev/null
+++ b/packages/native/src/logic/createLogicCore.ts
@@ -0,0 +1,97 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+//
+// The shape of this runtime (one state, a snapshot per change, a bridge of two
+// calls in and two out) follows EJ Campbell's astryx-swift spike
+// (github.com/ejc3/astryx-swift, MIT), whose core runs in Hermes and drives
+// SwiftUI views.
+
+/**
+ * @file logic/createLogicCore.ts
+ * @input A screen's initial state, a view of the state as a node tree, and a
+ * reducer of actions
+ * @output A logic core: the current tree, a dispatcher, and change listeners
+ * @position Arm C of the native experiment (AST-082 FR12): component logic in
+ * TypeScript, run by a JavaScript engine inside a native app, decides every
+ * word, value, and state; native views draw the tree and send actions back.
+ * Uses ECMAScript built-ins only, so it runs in Hermes, Node, and browsers
+ */
+
+/** The least a node has: the component it names and its identity in the tree. */
+export interface LogicNode {
+ readonly component: string;
+ readonly key: string;
+}
+
+/** The least an action has: the node, its component, the callback, and its arguments. */
+export interface LogicAction {
+ readonly key: string;
+ readonly component: string;
+ readonly event: string;
+ readonly args: readonly unknown[];
+}
+
+export interface LogicCoreOptions<
+ State,
+ Node extends LogicNode,
+ Action extends LogicAction,
+> {
+ readonly initial: State;
+ /** The whole screen for a state. Pure: the same state gives the same tree. */
+ readonly view: (state: State) => Node;
+ /** The next state after an action. Returns the same state when nothing changes. */
+ readonly reduce: (state: State, action: Action) => State;
+}
+
+export interface LogicCore<
+ State,
+ Node extends LogicNode,
+ Action extends LogicAction,
+> {
+ getState(): State;
+ /** The tree for the current state, built once per change. */
+ getSnapshot(): Node;
+ dispatch(action: Action): void;
+ /** Called after every change; returns the unsubscribe. */
+ subscribe(listener: () => void): () => void;
+}
+
+/**
+ * Creates a logic core. Pass the platform's `AstryxNode` and `AstryxAction`
+ * types from `@astryxdesign/native/components` so a tree and an action are
+ * checked against that platform's contracts.
+ */
+export function createLogicCore<
+ State,
+ Node extends LogicNode,
+ Action extends LogicAction,
+>(
+ options: LogicCoreOptions<State, Node, Action>,
+): LogicCore<State, Node, Action> {
+ let state = options.initial;
+ let snapshot: Node | null = null;
+ const listeners = new Set<() => void>();
+ return {
+ getState: () => state,
+ getSnapshot() {
+ snapshot ??= options.view(state);
+ return snapshot;
+ },
+ dispatch(action) {
+ const next = options.reduce(state, action);
+ if (Object.is(next, state)) {
+ return;
+ }
+ state = next;
+ snapshot = null;
+ for (const listener of [...listeners]) {
+ listener();
+ }
+ },
+ subscribe(listener) {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ };
+}
diff --git a/packages/native/src/logic/index.ts b/packages/native/src/logic/index.ts
new file mode 100644
index 0000000000..5ac463daa8
--- /dev/null
+++ b/packages/native/src/logic/index.ts
@@ -0,0 +1,19 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file logic/index.ts
+ * @input None
+ * @output The logic core runtime (`@astryxdesign/native/logic`)
+ * @position Arm C entry. Portable: ECMAScript built-ins only, no Node or DOM
+ * APIs, no clock and no randomness of its own
+ */
+
+export {createLogicCore} from './createLogicCore.js';
+export type {
+ LogicAction,
+ LogicCore,
+ LogicCoreOptions,
+ LogicNode,
+} from './createLogicCore.js';
+export {BRIDGE_VERSION, connectBridge} from './connectBridge.js';
+export type {Bridge, BridgeHost} from './connectBridge.js';
diff --git a/packages/native/src/logic/logic.test.ts b/packages/native/src/logic/logic.test.ts
new file mode 100644
index 0000000000..3c6f703a54
--- /dev/null
+++ b/packages/native/src/logic/logic.test.ts
@@ -0,0 +1,160 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import vm from 'node:vm';
+import ts from 'typescript';
+import {describe, expect, it} from 'vitest';
+import {connectBridge, createLogicCore, type LogicNode} from './index.js';
+
+type Node = LogicNode & {props: Record<string, unknown>; events?: string[]};
+type Action = {
+ key: string;
+ component: string;
+ event: string;
+ args: readonly unknown[];
+};
+
+function settings() {
+ return createLogicCore<{wifi: boolean}, Node, Action>({
+ initial: {wifi: true},
+ view: state => ({
+ component: 'VStack',
+ key: 'root',
+ props: {
+ children: [
+ {
+ component: 'Switch',
+ key: 'wifi',
+ props: {label: 'Wi-Fi', value: state.wifi},
+ events: ['onChange'],
+ },
+ {
+ component: 'Text',
+ key: 'status',
+ props: {children: state.wifi ? 'Connected' : 'Off'},
+ },
+ ],
+ },
+ }),
+ reduce: (state, action) =>
+ action.key === 'wifi' && action.event === 'onChange'
+ ? {wifi: action.args[0] === true}
+ : state,
+ });
+}
+
+describe('logic core', () => {
+ it('rebuilds the tree once per change and tells the host', () => {
+ const core = settings();
+ const changes: string[] = [];
+ let version = 0;
+ const bridge = connectBridge(core, {
+ connected: v => {
+ version = v;
+ },
+ changed: json => changes.push(json),
+ });
+ expect(version).toBe(1);
+ const first = core.getSnapshot();
+ expect(core.getSnapshot()).toBe(first);
+
+ bridge.dispatch(
+ '{"args":[false],"component":"Switch","event":"onChange","key":"wifi"}',
+ );
+ expect(core.getState()).toEqual({wifi: false});
+ expect(changes).toHaveLength(1);
+ expect(changes[0]).toContain('"children":"Off"');
+
+ // An action that changes nothing sends nothing.
+ bridge.dispatch(
+ '{"args":[],"component":"Button","event":"onClick","key":"other"}',
+ );
+ expect(changes).toHaveLength(1);
+ });
+
+ it('refuses JSON that is not an action', () => {
+ const bridge = connectBridge(settings(), {
+ connected: () => {},
+ changed: () => {},
+ });
+ expect(() => bridge.dispatch('{"key":"wifi"}')).toThrow(
+ 'Not an Astryx action',
+ );
+ });
+
+ const dir = path.dirname(fileURLToPath(import.meta.url));
+ const sources = fs
+ .readdirSync(dir)
+ .filter(file => file.endsWith('.ts') && !file.endsWith('.test.ts'));
+
+ it('type-checks with ECMAScript built-ins only', () => {
+ const program = ts.createProgram(
+ sources.map(file => path.join(dir, file)),
+ {
+ strict: true,
+ noEmit: true,
+ module: ts.ModuleKind.ESNext,
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
+ lib: ['lib.es2022.d.ts'],
+ types: [],
+ },
+ );
+ const errors = ts
+ .getPreEmitDiagnostics(program)
+ .map(d => ts.flattenDiagnosticMessageText(d.messageText, '\n'));
+ expect(errors).toEqual([]);
+ });
+
+ it('runs in an engine with no host globals, as in Hermes', () => {
+ // Each module as CommonJS, evaluated in a fresh context with no timers,
+ // process, require, or DOM. (V8 still exposes `console` there; the
+ // ES2022-only type check above is what keeps it out.)
+ const modules = new Map<string, Record<string, unknown>>();
+ const context = vm.createContext({});
+ const load = (file: string): Record<string, unknown> => {
+ const cached = modules.get(file);
+ if (cached) {
+ return cached;
+ }
+ const exports: Record<string, unknown> = {};
+ modules.set(file, exports);
+ const {outputText} = ts.transpileModule(
+ fs.readFileSync(path.join(dir, file), 'utf8'),
+ {
+ compilerOptions: {
+ module: ts.ModuleKind.CommonJS,
+ target: ts.ScriptTarget.ES2022,
+ },
+ },
+ );
+ const run = vm.runInContext(
+ `(function (exports, require) {${outputText}\n})`,
+ context,
+ ) as (e: unknown, r: (name: string) => unknown) => void;
+ run(exports, name =>
+ load(name.replace(/^\.\//, '').replace(/\.js$/, '.ts')),
+ );
+ return exports;
+ };
+ load('index.ts');
+ const run = vm.runInContext(
+ `(function (logic) {
+ const core = logic.createLogicCore({
+ initial: {count: 0},
+ view: s => ({component: 'Text', key: 'count', props: {children: String(s.count)}}),
+ reduce: (s, a) => a.event === 'onClick' ? {count: s.count + 1} : s,
+ });
+ const seen = [];
+ const bridge = logic.connectBridge(core, {connected() {}, changed(json) { seen.push(json); }});
+ bridge.dispatch(JSON.stringify({key: 'add', component: 'Button', event: 'onClick', args: []}));
+ return seen;
+ })`,
+ context,
+ ) as (logic: unknown) => string[];
+ expect(run(load('index.ts'))).toEqual([
+ '{"component":"Text","key":"count","props":{"children":"1"}}',
+ ]);
+ });
+});