effect-appkit 0.0.0-stage → 0.1.0

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tanvesh01 and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,121 @@
1
- # Temporary Holding Version
1
+ # Effect AppKit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Write a component in TypeScript using [Effect UI](https://github.com/Effect-TS/ui). Run its model, updates, and effects in JavaScriptCore and render its view with actual macOS controls. SwiftUI can embed the same AppKit surface. No web view, React Native, or Node process runs in the app.
4
+
5
+ [![Kestrel Workspace: the trip checklist updating in a native Mac window](docs/public/images/kestrel-workspace.gif)](docs/docs/examples/kestrel-workspace.mdx)
6
+
7
+ ## Documentation website
8
+
9
+ The [documentation website](https://tanvesh01.github.io/effect-appkit/) includes a [quickstart](docs/docs/quickstart.mdx), the Kestrel example, embedding and custom-view guides, an [Effect UI DevTools walkthrough](docs/docs/guides/devtools.mdx), and a [control reference](docs/docs/reference/controls.mdx). To run the Holocron site locally:
10
+
11
+ ```sh
12
+ cd docs
13
+ bun install --frozen-lockfile
14
+ bun run dev
15
+ ```
16
+
17
+ To serve the production build locally, run `bun run build` followed by `bun run start`. Neither command publishes the site.
18
+
19
+ ## Run the examples
20
+
21
+ From this directory on a Mac with Xcode and Bun installed:
22
+
23
+ ```sh
24
+ bun install --frozen-lockfile --ignore-scripts
25
+ bun run demo:workspace
26
+ ```
27
+
28
+ [Kestrel Workspace](examples/kestrel/) opens **From Naples to the Alps**, a travel notebook with a checklist shared by the queue and the reader. Changes reset when you quit. Watch the [original Cap recording](docs/public/images/kestrel-workspace.mp4) or follow the [native workspace walkthrough](docs/docs/examples/kestrel-workspace.mdx).
29
+
30
+ For the smaller built-in controls example, follow the [counter quickstart](docs/docs/quickstart.mdx).
31
+
32
+ `bun run test` type-checks TypeScript, builds the example bundles, and runs the native Swift package tests. The GitHub Actions workflow runs that same command on macOS. SwiftPM itself does not fetch JavaScript tooling or bundle TypeScript.
33
+
34
+ ## Drive a debug app from an agent
35
+
36
+ Start the pinned Effect UI DevTools server first (Node and the repo’s dev dependencies are required). In separate terminals:
37
+
38
+ ```sh
39
+ # 1. Start the local MCP server, explicitly allowing dispatch.
40
+ bun run devtools --dispatch
41
+ ```
42
+
43
+ ```sh
44
+ # 2. Launch a debug build with control enabled.
45
+ EFFECT_APPKIT_DEVTOOLS=dispatch bun run demo:workspace
46
+ ```
47
+
48
+ Connect an HTTP MCP client to `http://127.0.0.1:4774/mcp`. Ask it to **find the `WorkspaceDemo` root, toggle the Courmayeur booking, verify the task’s `done` field changed, then restore it**. Or run `node examples/kestrel/check-workspace.mjs` against the running demo. No Accessibility permission or simulated clicks are needed.
49
+
50
+ For read-only inspection, omit `--dispatch` and launch with `EFFECT_APPKIT_DEVTOOLS=inspect`. The timeline is also available at `http://127.0.0.1:4774`. To change ports, pass `--port N` to the server and `EFFECT_APPKIT_DEVTOOLS_PORT=N` to the app. Relaunch the app if the connection drops.
51
+
52
+ DevTools is off by default and the native connection is compiled out of release builds. The server has no authentication: use it only on a trusted machine. Dispatch runs real updates and effects. State and logs cover Effect UI components; dispatch targets the mounted root only. Swift-local state, browser picking/time travel, and video capture are not part of this bridge.
53
+
54
+ ## Use in another app
55
+
56
+ 1. In Xcode, choose **File → Add Package Dependencies**, enter `https://github.com/tanvesh01/effect-appkit.git`, select the exact version `0.1.0`, and link **EffectAppKit** to a macOS 14+ target. For TypeScript, install the matching release tarball and Effect UI snapshot:
57
+
58
+ ```sh
59
+ bun add https://github.com/tanvesh01/effect-appkit/releases/download/0.1.0/effect-appkit-0.1.0.tgz effect@4.1.7 'https://pkg.pr.new/Effect-TS/ui/@effect/ui@82a1750'
60
+ ```
61
+
62
+ The adapter uses an upstream preview, not a stable npm release of `@effect/ui`. A fresh install depends on that preview remaining available. Commit your lockfile.
63
+ 2. At the top of your TypeScript entry, `import "effect-appkit/runtime"` **before importing Effect modules**. JavaScriptCore does not include the browser UTF-8 globals that Effect initializes at import time. Import `component` and `start` from `effect-appkit`, define your component, and call `start(MyComponent, props)`. See the counter for a complete entry.
64
+ 3. Build the entry with `bun build src/main.ts --target=browser --format=iife --conditions=production --minify --outfile=dist/main.js`. Add `dist/main.js` to your app target's **Copy Bundle Resources**. Bundle only code you trust. The host is not a sandbox for downloaded scripts.
65
+ 4. Load the script once, then choose a surface:
66
+
67
+ ```swift
68
+ import EffectAppKit
69
+
70
+ // In the app's throwing resource-loading path:
71
+ let script = try String(contentsOf: scriptURL, encoding: .utf8)
72
+
73
+ // AppKit, on the main actor:
74
+ let nativeView = try EffectAppKitView(script: script)
75
+ window.contentView = nativeView
76
+ // When permanently removing it, call nativeView.close().
77
+ ```
78
+
79
+ In a SwiftUI view's `body`, use `EffectAppKitSurface(script: script)`. The wrapper owns mounting and teardown. This is an AppKit renderer embedded in SwiftUI, **not** a TypeScript-to-Swift compiler or an arbitrary SwiftUI view-tree renderer.
80
+
81
+ ## Bring your own native view
82
+
83
+ Custom views are **leaves**: Effect UI owns their placement and model, while Swift owns everything inside them. They are registered on a surface, not globally. No renderer fork is needed.
84
+
85
+ Declare the name and the JSON types in TypeScript, then use the factory inside your component's `view`:
86
+
87
+ ```ts
88
+ const Presets = defineNativeView<{ selected: number }, { step: number }>("PresetPicker")
89
+ // Inside h.stack.children(...):
90
+ Presets({ selected: model.step }, event => Message.Choose(event))
91
+ ```
92
+
93
+ In Swift, create a `NativeViewRegistration` with the same name. Use `name:make:update:dismantle:` for an `NSView`, or `name:content:` for a SwiftUI view. Pass it in `registrations: [presetPicker]` to `EffectAppKitView` or `EffectAppKitSurface`. Keep registrations stable across SwiftUI updates. Swift decodes the entire props value (`Decodable`) and encodes native events (`Encodable`); both sides must agree on the JSON shape. TypeScript types do not generate Swift types.
94
+
95
+ The [TypeScript component](src/presets.ts) and its [SwiftUI segmented picker](Sources/EffectCounter/PresetPicker.swift) are a complete example:
96
+
97
+ ```sh
98
+ bun run bundle:presets
99
+ swift run EffectCounter dist/presets.js
100
+ ```
101
+
102
+ Select **5**, then press **Count: 0** to add five. **Hide presets** removes the native view; showing it again creates a fresh instance with the current model.
103
+
104
+ ## Supported views and limits
105
+
106
+ | TypeScript view | Native behavior |
107
+ | --- | --- |
108
+ | `h.stack.children(...)` | Vertical `NSStackView` with ordered children |
109
+ | `h.row.children(...)` | Horizontal `NSStackView` with ordered children |
110
+ | `h.label.prop("value", text)` or a text child of a stack | Read-only `NSTextField` |
111
+ | `h.button.prop("title", text).on("press", message)` | `NSButton` with native target/action |
112
+ | `h.checkbox.prop("title", text).prop("checked", bool).on("change", fn)` | Native checkbox; `fn` receives the new boolean state |
113
+ | `h.slider.prop("accessibilityLabel", text).prop("value", n).on("change", fn)` | Continuous native slider; `n` and the event payload range from 0 to 1 |
114
+
115
+ There is no DOM, HTML/CSS mapping, network client, or general browser environment. Provide any other APIs your own effects need. Unsupported elements and properties are errors, not inert views. Use this for small native surfaces; text editing, outline views, menus, navigation, and a full SwiftUI vocabulary are not implemented.
116
+
117
+ The host interface upstream is experimental. This project pins [`@effect/ui` at `82a1750`](https://github.com/Effect-TS/ui/tree/82a1750ad26e2b18e321b9c8a56aea552f54197a); update it together with the lockfile and rerun the native tests.
118
+
119
+ ## License
120
+
121
+ [MIT](LICENSE). The [GitHub release](https://github.com/tanvesh01/effect-appkit/releases/tag/0.1.0) contains the matching Swift tag and TypeScript package.
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "effect-appkit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Render Effect UI components as native AppKit controls on macOS.",
5
+ "license": "MIT",
6
+ "repository": { "type": "git", "url": "git+https://github.com/tanvesh01/effect-appkit.git" },
7
+ "type": "module",
8
+ "packageManager": "bun@1.3.14",
9
+ "exports": {
10
+ ".": "./src/appkit.ts",
11
+ "./runtime": "./src/runtime.js"
12
+ },
13
+ "files": ["src/appkit.ts", "src/devtools.ts", "src/runtime.js"],
14
+ "scripts": {
15
+ "check": "tsc --noEmit",
16
+ "devtools": "effect-ui-devtools",
17
+ "test": "bun run check && bun run bundle:counter && bun run bundle:presets && bun run bundle:workspace && swift test",
18
+ "bundle:workspace": "bun build examples/kestrel/workspace.ts --target=browser --format=iife --conditions=production --minify --outfile=dist/workspace.js",
19
+ "demo:workspace": "bun run bundle:workspace && swift run EffectCounter dist/workspace.js",
20
+ "bundle:presets": "bun build src/presets.ts --target=browser --format=iife --conditions=production --minify --outfile=dist/presets.js",
21
+ "bundle:counter": "bun build src/counter.ts --target=browser --format=iife --conditions=production --minify --outfile=dist/counter.js"
22
+ },
23
+ "dependencies": {
24
+ "@effect/ui": "https://pkg.pr.new/Effect-TS/ui/@effect/ui@82a1750",
25
+ "text-encoding-utf-8": "1.0.2"
26
+ },
27
+ "overrides": {
28
+ "@effect/ui": "https://pkg.pr.new/Effect-TS/ui/@effect/ui@82a1750",
29
+ "@effect/ui-kit": "https://pkg.pr.new/Effect-TS/ui/@effect/ui-kit@82a1750"
30
+ },
31
+ "peerDependencies": {
32
+ "effect": "^4.1.7"
33
+ },
34
+ "devDependencies": {
35
+ "@effect/platform-node": "4.1.7",
36
+ "@effect/ui-devtools": "https://pkg.pr.new/Effect-TS/ui/@effect/ui-devtools@82a1750",
37
+ "@effect/ui-kit": "https://pkg.pr.new/Effect-TS/ui/@effect/ui-kit@82a1750",
38
+ "effect": "4.1.7",
39
+ "typescript": "7.0.2"
40
+ }
41
+ }
package/src/appkit.ts ADDED
@@ -0,0 +1,297 @@
1
+ import "./runtime.js"
2
+ import * as Component from "@effect/ui/Component"
3
+ import * as Renderer from "@effect/ui/Renderer"
4
+ import * as View from "@effect/ui/View"
5
+ import * as Context from "effect/Context"
6
+ import * as Effect from "effect/Effect"
7
+ import * as Exit from "effect/Exit"
8
+ import * as Scope from "effect/Scope"
9
+ import { type DevToolsBridge, hasDevTools, withDevTools } from "./devtools.js"
10
+
11
+ /** JavaScriptCore exports native objects, not indexes into a node registry. */
12
+ export interface NativeNode { readonly _nativeNode: unique symbol }
13
+ type CustomKind = `custom:${string}`
14
+ type Kind = "root" | "text" | keyof Tags<never> | CustomKind
15
+
16
+ function isCustom(tag: string): tag is CustomKind {
17
+ return tag.startsWith("custom:")
18
+ }
19
+
20
+ export interface Bridge extends Partial<DevToolsBridge> {
21
+ readonly __akRoot: NativeNode
22
+ __akCreate(kind: Kind, value: string): NativeNode
23
+ __akInsert(parent: NativeNode, node: NativeNode, before: NativeNode | null): void
24
+ __akRemove(node: NativeNode): void
25
+ __akSet(node: NativeNode, key: string, value: string): void
26
+ __akListen(node: NativeNode, callback: ((payload?: boolean | number | string) => void) | null): void
27
+ }
28
+
29
+ export class AppKit extends Context.Service<AppKit, Bridge>()("effect-appkit/AppKit") {}
30
+
31
+ interface Control<Msg, Props, Events> extends View.ElementBuilder<Msg, never, Events, NativeNode> {
32
+ prop<K extends keyof Props & string>(key: K, value: Props[K]): this
33
+ }
34
+ interface Layout<Msg> extends View.ContainerBuilder<Msg, never, {}, NativeNode> {
35
+ prop(key: never, value: never): this
36
+ }
37
+ type Tags<Msg> = {
38
+ readonly stack: Layout<Msg>
39
+ readonly row: Layout<Msg>
40
+ readonly button: Control<Msg, { title: string }, { press: undefined }>
41
+ readonly checkbox: Control<Msg, { title: string; checked: boolean }, { change: boolean }>
42
+ readonly slider: Control<Msg, { value: number; accessibilityLabel: string }, { change: number }>
43
+ readonly label: Control<Msg, { value: string }, {}>
44
+ }
45
+ export interface Elements extends View.Elements {
46
+ readonly Tags: Tags<this["Msg"]>
47
+ readonly Host: AppKit
48
+ }
49
+ export const vocabulary: View.Vocabulary<Elements> = {
50
+ name: "appkit",
51
+ tags: {
52
+ stack: new View.ContainerBuilder("stack"),
53
+ row: new View.ContainerBuilder("row"),
54
+ button: new View.ElementBuilder("button"),
55
+ checkbox: new View.ElementBuilder("checkbox"),
56
+ slider: new View.ElementBuilder("slider"),
57
+ label: new View.ElementBuilder("label")
58
+ },
59
+ textParents: ["stack", "row"]
60
+ }
61
+ /** Defines an Effect UI component with the AppKit element and event vocabulary. */
62
+ export const component = Component.withElements(vocabulary)
63
+
64
+ /** A leaf supplied by the embedding app. Props and native events must be JSON values. */
65
+ export function defineNativeView<Props, Event = never>(name: string) {
66
+ if (!name) throw new Error("AppKit: a custom view needs a name")
67
+ const base = new View.ElementBuilder<never, never, { event: Event }, NativeNode>(`custom:${name}`)
68
+ return <Msg = never>(props: Props, onEvent?: (event: Event) => Msg | undefined) => {
69
+ const view: Control<Msg, { props: Props }, { event: Event }> = base.prop("props", props)
70
+ return onEvent === undefined ? view : view.on("event", onEvent)
71
+ }
72
+ }
73
+
74
+ function encodeProps(kind: CustomKind, props: unknown): string {
75
+ return JSON.stringify(props, function(key, value: unknown) {
76
+ // stringify runs toJSON before the replacer. Only accept the original data value.
77
+ if (Object.getOwnPropertyDescriptor(this, key)?.value === value) {
78
+ if (value === null || typeof value === "boolean" || typeof value === "string" ||
79
+ typeof value === "number" && Number.isFinite(value)) return value
80
+ if (Array.isArray(value)) {
81
+ // Dense indices plus length; reject extra fields that JSON would omit.
82
+ if (Reflect.ownKeys(value).length === value.length + 1) return value
83
+ } else if (typeof value === "object") {
84
+ const proto = Object.getPrototypeOf(value)
85
+ if ((proto === null || proto === Object.prototype) &&
86
+ Reflect.ownKeys(value).length === Object.keys(value).length) return value
87
+ }
88
+ }
89
+ throw new TypeError(`AppKit: 'props' on <${kind}> must be plain JSON data`)
90
+ })
91
+ }
92
+
93
+ type State = {
94
+ kind: Kind
95
+ children: NativeNode[]
96
+ parent?: NativeNode
97
+ listening: boolean
98
+ send?: (payload?: unknown) => void
99
+ wanted?: boolean | number
100
+ actual?: boolean | number
101
+ }
102
+
103
+ function isNormalized(value: unknown): value is number {
104
+ return typeof value === "number" && value >= 0 && value <= 1
105
+ }
106
+
107
+ /** Build one host per native root; all hierarchy mutations go through it. */
108
+ export function makeHost(bridge: Bridge): Renderer.Host<NativeNode> {
109
+ const states = new WeakMap<NativeNode, State>()
110
+ function register(native: NativeNode, kind: Kind) {
111
+ states.set(native, { kind, children: [], listening: false })
112
+ return native
113
+ }
114
+ register(bridge.__akRoot, "root")
115
+ function state(node: NativeNode) {
116
+ const s = states.get(node)
117
+ if (!s) throw new Error("AppKit: node belongs to a different host")
118
+ return s
119
+ }
120
+ function unlink(node: NativeNode, s: State) {
121
+ if (!s.parent) return
122
+ const siblings = state(s.parent).children
123
+ siblings.splice(siblings.indexOf(node), 1)
124
+ delete s.parent
125
+ }
126
+ function writeControl(node: NativeNode, s: State, value: boolean | number) {
127
+ if (s.actual === value) return
128
+ bridge.__akSet(node, s.kind === "checkbox" ? "checked" : "value", String(value))
129
+ s.actual = value
130
+ }
131
+ function updateListener(node: NativeNode, s: State) {
132
+ const listen = s.send !== undefined || s.wanted !== undefined
133
+ if (s.listening === listen) return
134
+ bridge.__akListen(node, !listen ? null : payload => {
135
+ if (isCustom(s.kind)) {
136
+ if (typeof payload !== "string") throw new TypeError(`AppKit: expected a JSON event from <${s.kind}>`)
137
+ s.send?.(JSON.parse(payload))
138
+ return
139
+ }
140
+ if (s.kind === "button") {
141
+ if (payload !== undefined) throw new TypeError("AppKit: button press takes no payload")
142
+ s.send?.()
143
+ return
144
+ }
145
+ if (payload === undefined || typeof payload === "string" ||
146
+ (s.kind === "checkbox" ? typeof payload !== "boolean" : !isNormalized(payload))) {
147
+ throw new TypeError(`AppKit: invalid change payload on <${s.kind}>`)
148
+ }
149
+ s.actual = payload
150
+ try {
151
+ s.send?.(payload)
152
+ } finally {
153
+ // Let the renderer's queued patch adopt the input before restoring a rejected edit.
154
+ if (s.wanted !== undefined && s.wanted !== s.actual) queueMicrotask(() => {
155
+ if (s.listening && s.wanted !== undefined) writeControl(node, s, s.wanted)
156
+ })
157
+ }
158
+ })
159
+ s.listening = listen
160
+ if (!listen) delete s.actual
161
+ }
162
+ function clearListeners(node: NativeNode) {
163
+ const s = state(node)
164
+ delete s.send
165
+ if (s.listening) {
166
+ bridge.__akListen(node, null)
167
+ s.listening = false
168
+ }
169
+ for (const child of s.children) clearListeners(child)
170
+ }
171
+ return {
172
+ elements: [vocabulary.name], controlled: new Set(["checked", "value"]), runsMounts: true,
173
+ createElement(tag) {
174
+ if (!isCustom(tag) && tag !== "stack" && tag !== "row" && tag !== "button" && tag !== "checkbox" && tag !== "slider" && tag !== "label") {
175
+ throw new Error(`AppKit: unsupported element <${tag}>`)
176
+ }
177
+ return register(bridge.__akCreate(tag, ""), tag)
178
+ },
179
+ createText: value => register(bridge.__akCreate("text", value), "text"),
180
+ setText(node, value) {
181
+ if (state(node).kind !== "text") throw new Error("AppKit: expected a text node")
182
+ bridge.__akSet(node, "value", value)
183
+ },
184
+ setAttr(node, key) {
185
+ throw new Error(`AppKit: <${state(node).kind}> does not support attribute '${key}'; use prop()`)
186
+ },
187
+ setProp(node, key, value) {
188
+ const s = state(node), { kind } = s
189
+ if (isCustom(kind) && key === "props") {
190
+ bridge.__akSet(node, key, encodeProps(kind, value))
191
+ return
192
+ }
193
+ if ((kind === "checkbox" && key === "checked") || (kind === "slider" && key === "value")) {
194
+ if (value === undefined) {
195
+ delete s.wanted
196
+ } else if (kind === "checkbox" && typeof value === "boolean" || kind === "slider" && isNormalized(value)) {
197
+ s.wanted = value
198
+ } else {
199
+ throw new TypeError(`AppKit: '${key}' must be ${kind === "checkbox" ? "a boolean" : "a number in [0, 1]"}`)
200
+ }
201
+ writeControl(node, s, s.wanted ?? (kind === "checkbox" ? false : 0))
202
+ updateListener(node, s)
203
+ return
204
+ }
205
+ if (!((kind === "button" || kind === "checkbox") && key === "title" ||
206
+ kind === "label" && key === "value" || kind === "slider" && key === "accessibilityLabel")) {
207
+ throw new Error(`AppKit: unsupported property '${key}' on <${kind}>`)
208
+ }
209
+ if (value !== undefined && typeof value !== "string") {
210
+ throw new TypeError(`AppKit: '${key}' must be a string`)
211
+ }
212
+ bridge.__akSet(node, key, value ?? "")
213
+ },
214
+ insertBefore(parent, node, before) {
215
+ const p = state(parent), s = state(node)
216
+ if (p.kind !== "root" && p.kind !== "stack" && p.kind !== "row") throw new Error(`AppKit: <${p.kind}> cannot contain children`)
217
+ if (before && state(before).parent !== parent) throw new Error("AppKit: insertion reference is not a child of the parent")
218
+ if (before === node) return
219
+ if (s.kind === "root") throw new Error("AppKit: cannot insert the root")
220
+ for (let ancestor: NativeNode | undefined = parent; ancestor; ancestor = state(ancestor).parent) {
221
+ if (ancestor === node) throw new Error("AppKit: cannot insert an ancestor into its descendant")
222
+ }
223
+ bridge.__akInsert(parent, node, before ?? null)
224
+ unlink(node, s)
225
+ p.children.splice(before ? p.children.indexOf(before) : p.children.length, 0, node)
226
+ s.parent = parent
227
+ },
228
+ remove(node) {
229
+ const s = state(node)
230
+ if (s.kind === "root") throw new Error("AppKit: cannot remove the root")
231
+ clearListeners(node)
232
+ bridge.__akRemove(node)
233
+ unlink(node, s)
234
+ },
235
+ parentOf: node => state(node).parent,
236
+ nextOf(node) {
237
+ const parent = state(node).parent
238
+ if (!parent) return undefined
239
+ const siblings = state(parent).children
240
+ return siblings[siblings.indexOf(node) + 1]
241
+ },
242
+ setEvents(node, handlers, dispatch, options) {
243
+ const s = state(node)
244
+ const event = isCustom(s.kind) ? "event" : s.kind === "button" ? "press" :
245
+ s.kind === "checkbox" || s.kind === "slider" ? "change" : undefined
246
+ for (const name in handlers) {
247
+ if (name !== event) throw new Error(`AppKit: unsupported '${name}' event on <${s.kind}>`)
248
+ if (options[name]?.preventDefault) throw new Error(`AppKit: ${s.kind} ${name} is not cancellable`)
249
+ }
250
+ const handler = event === undefined ? undefined : handlers[event]
251
+ if (event !== undefined && handler !== undefined) s.send = payload => { dispatch(event, handler, payload) }
252
+ else delete s.send
253
+ updateListener(node, s)
254
+ }
255
+ }
256
+ }
257
+
258
+ /** Closing the caller's Effect Scope unmounts its views and releases their targets. */
259
+ export function mount<Name extends string, Props, Model, Msg, Events, R>(
260
+ bridge: Bridge,
261
+ root: Component.Members<Name, Props, Model, Msg, Events, R, Elements, any>,
262
+ props: NoInfer<Props>
263
+ ) {
264
+ const mounted = Renderer.mount(root, props, bridge.__akRoot).pipe(
265
+ Effect.provideService(Renderer.Renderer, { host: makeHost(bridge) }),
266
+ Effect.provideService(AppKit, bridge)
267
+ )
268
+ return hasDevTools(bridge) ? withDevTools(bridge, root.message, mounted) : mounted
269
+ }
270
+
271
+ /**
272
+ * Mounts a root in the current EffectAppKitView and replaces its previous root.
273
+ * The view calls the returned unmount function on close; callers can also stop early.
274
+ * Provide application-specific services on the component or use scoped `mount`.
275
+ */
276
+ export function start<Name extends string, Props, Model, Msg, Events>(
277
+ root: Component.Members<Name, Props, Model, Msg, Events, AppKit | Renderer.Renderer | Scope.Scope, Elements, any>,
278
+ props: NoInfer<Props>
279
+ ): () => void {
280
+ const bridge = globalThis as typeof globalThis & Bridge & { __akUnmount?: () => void }
281
+ if (!bridge.__akRoot) throw new Error("effect-appkit: start() requires an EffectAppKitView")
282
+ bridge.__akUnmount?.()
283
+ const scope = Scope.makeUnsafe()
284
+ const unmount = () => {
285
+ if (bridge.__akUnmount !== unmount) return
286
+ delete bridge.__akUnmount
287
+ Effect.runSync(Scope.close(scope, Exit.void))
288
+ }
289
+ bridge.__akUnmount = unmount
290
+ try {
291
+ Effect.runSync(mount(bridge, root, props).pipe(Scope.provide(scope)))
292
+ } catch (error) {
293
+ unmount()
294
+ throw error
295
+ }
296
+ return unmount
297
+ }
@@ -0,0 +1,218 @@
1
+ import * as MessageLog from "@effect/ui/MessageLog"
2
+ import type * as Renderer from "@effect/ui/Renderer"
3
+ import * as Cause from "effect/Cause"
4
+ import * as Effect from "effect/Effect"
5
+ import type * as Scope from "effect/Scope"
6
+ import * as Schema from "effect/Schema"
7
+
8
+ export interface DevToolsBridge {
9
+ readonly __akDevToolsDispatch: boolean
10
+ __akDevToolsConnect(onControl: (text: string) => void, onControlOpen: () => void): void
11
+ __akDevToolsSend(channel: "log" | "control", text: string): void
12
+ __akDevToolsClose(): void
13
+ }
14
+
15
+ export function hasDevTools(bridge: Partial<DevToolsBridge>): bridge is DevToolsBridge {
16
+ return typeof bridge.__akDevToolsConnect === "function" && typeof bridge.__akDevToolsSend === "function" &&
17
+ typeof bridge.__akDevToolsClose === "function" && typeof bridge.__akDevToolsDispatch === "boolean"
18
+ }
19
+
20
+ // @effect/ui-devtools 82a1750 keeps its /control schemas private. Implement only
21
+ // the requests a native Renderer.Root can actually serve; never claim DOM support.
22
+ const Envelope = Schema.Struct({ id: Schema.Number, request: Schema.Unknown })
23
+ const decodeEnvelope = Schema.decodeUnknownOption(Schema.fromJsonString(Envelope))
24
+ const target = { session: Schema.String, instance: Schema.Number }
25
+ const decodeRequest = Schema.decodeUnknownSync(Schema.Union([
26
+ Schema.TaggedStruct("MessageSchema", { ...target, tag: Schema.optionalKey(Schema.String) }),
27
+ Schema.TaggedStruct("Dispatch", { ...target, messages: Schema.Array(Schema.Json), within: Schema.Finite })
28
+ ]))
29
+
30
+ type Outcome =
31
+ | { _tag: "Updated" | "Failed"; seq: number }
32
+ | { _tag: "Ignored"; reason: "closed" | "unchanged" }
33
+ | { _tag: "Unknown" }
34
+
35
+ const record = (x: unknown): x is Record<string, unknown> => typeof x === "object" && x !== null && !Array.isArray(x)
36
+
37
+ function messageSchema<Msg>(schema: Schema.Codec<Msg, any>, tag: string | undefined) {
38
+ const codec = Schema.toCodecJson(schema)
39
+ const document = Schema.toJsonSchemaDocument(codec)
40
+ const resolve = (s: unknown): Record<string, unknown> | undefined => {
41
+ if (!record(s)) return undefined
42
+ if (typeof s.$ref !== "string") return s
43
+ const name = s.$ref.slice(s.$ref.lastIndexOf("/") + 1).replaceAll("~1", "/").replaceAll("~0", "~")
44
+ return Object.hasOwn(document.definitions, name) ? document.definitions[name] : undefined
45
+ }
46
+ const root = resolve(document.schema)
47
+ const alternatives = root?.anyOf ?? root?.oneOf
48
+ const members: ReadonlyArray<unknown> = Array.isArray(alternatives) ? alternatives : [document.schema]
49
+ const literal = (s: Record<string, unknown> | undefined) => s?.const ?? (Array.isArray(s?.enum) ? s.enum[0] : undefined)
50
+ const tagOf = (member: unknown) => {
51
+ const props = resolve(member)?.properties
52
+ return record(props) ? literal(resolve(props._tag)) : undefined
53
+ }
54
+ const selected = tag === undefined ? members : members.filter((member) => tagOf(member) === tag)
55
+ if (!selected.length) throw new Error(`No message _tag ${tag}. The tags are ${members.map(tagOf).filter(Boolean).join(", ")}.`)
56
+
57
+ // Templates use synthetic values, never model data or user-supplied examples.
58
+ // The actual dispatch decoder decides whether each one is ready to send.
59
+ const candidate = (member: unknown, ancestors: Set<object>): unknown => {
60
+ const s = resolve(member)
61
+ if (!s || ancestors.has(s)) return null
62
+ ancestors.add(s)
63
+ try {
64
+ if ("const" in s || Array.isArray(s.enum)) return literal(s) ?? null
65
+ const options = s.anyOf ?? s.oneOf
66
+ if (Array.isArray(options)) return candidate(options[0], ancestors)
67
+ switch (s.type) {
68
+ case "object": {
69
+ const props = s.properties
70
+ return Object.fromEntries((Array.isArray(s.required) ? s.required : []).map((key: string) =>
71
+ [key, candidate(record(props) ? props[key] : undefined, ancestors)]))
72
+ }
73
+ case "array": return Array.isArray(s.prefixItems) ? s.prefixItems.map((item) => candidate(item, ancestors)) : []
74
+ case "boolean": return false
75
+ case "integer": case "number": return s.minimum ?? s.maximum ?? 0
76
+ case "string": return "a".repeat(typeof s.minLength === "number" ? Math.min(s.minLength, 64) : 0)
77
+ default: return null
78
+ }
79
+ } finally {
80
+ ancestors.delete(s)
81
+ }
82
+ }
83
+ const decode = Schema.decodeUnknownEffect(codec)
84
+ const redacted = MessageLog.redactSchema(schema)
85
+ const encodeSafe = redacted === schema ? undefined : Schema.encodeUnknownEffect(Schema.toCodecJson(redacted as Schema.Codec<unknown>))
86
+ return Effect.gen(function*() {
87
+ const examples = yield* Effect.forEach(selected, (member) => Effect.gen(function*() {
88
+ const message = candidate(member, new Set())
89
+ const tag = tagOf(member)
90
+ return yield* decode(message).pipe(Effect.matchEffect({
91
+ onFailure: (error) => Effect.succeed({ tag, invalid: error.message }),
92
+ onSuccess: (value): Effect.Effect<object> => encodeSafe === undefined ? Effect.succeed({ message }) :
93
+ encodeSafe(value).pipe(Effect.match({
94
+ onFailure: () => ({ tag, invalid: "No safely redacted example is available." }),
95
+ onSuccess: (safe) => hasRedaction(safe) ? { message: safe, redacted: true } : { message }
96
+ }))
97
+ }))
98
+ }))
99
+ return { schema: tag === undefined ? document.schema : selected[0], definitions: document.definitions, examples }
100
+ })
101
+ }
102
+
103
+ function hasRedaction(value: Schema.Json): boolean {
104
+ return value !== null && typeof value === "object" &&
105
+ (("~redacted" in value && value["~redacted"] === true) || Object.values(value).some(hasRedaction))
106
+ }
107
+
108
+ export function withDevTools<Model, Msg, Props, R>(
109
+ bridge: DevToolsBridge,
110
+ schema: Schema.Codec<Msg, any>,
111
+ mount: Effect.Effect<Renderer.Root<Model, Msg, Props>, never, R>
112
+ ): Effect.Effect<Renderer.Root<Model, Msg, Props>, never, R | Scope.Scope> {
113
+ return Effect.gen(function*() {
114
+ const scope = yield* Effect.scope
115
+ const ambient = yield* MessageLog.MessageLog
116
+ let root: Renderer.Root<Model, Msg, Props> | undefined
117
+ let instance: number | undefined
118
+ let controlOpen = false
119
+ let closed = false
120
+ const send = (channel: "log" | "control", frame: object) => bridge.__akDevToolsSend(channel, JSON.stringify(frame))
121
+ const announce = () => {
122
+ if (!closed && bridge.__akDevToolsDispatch && controlOpen && root) {
123
+ send("control", { _tag: "State", sessions: [root.session], paused: null, notRecording: [], picks: [] })
124
+ }
125
+ }
126
+
127
+ let observe: ((entry: MessageLog.Entry) => void) | undefined
128
+ const dispatch = (mounted: Renderer.Root<Model, Msg, Props>, id: number, message: Msg): Outcome => {
129
+ if (instance !== id || closed) return { _tag: "Ignored", reason: "closed" }
130
+ // AppKit has no deferred view transitions. Root.send runs update inline;
131
+ // attribute only the exact Dispatch entry, not a Command's subsequent update.
132
+ let outcome: Outcome | undefined
133
+ observe = (entry) => {
134
+ if (entry.session !== mounted.session || !("instance" in entry) || entry.instance !== id || outcome) return
135
+ if (entry._tag === "Update" && entry.source._tag === "Dispatch" && Object.is(entry.message, message)) {
136
+ outcome = { _tag: "Updated", seq: entry.seq }
137
+ } else if (entry._tag === "Failed" && entry.update?.source._tag === "Dispatch" && Object.is(entry.update.message, message)) {
138
+ outcome = { _tag: "Failed", seq: entry.seq }
139
+ }
140
+ }
141
+ try {
142
+ mounted.send(message)
143
+ return outcome ?? { _tag: "Ignored", reason: "unchanged" }
144
+ } catch {
145
+ // An unexpected host exception cannot prove the message was not applied.
146
+ return outcome ?? { _tag: "Unknown" }
147
+ } finally {
148
+ observe = undefined
149
+ }
150
+ }
151
+ const handle = (raw: unknown) => Effect.gen(function*() {
152
+ if (!bridge.__akDevToolsDispatch) return yield* Effect.fail("Native dispatch is disabled.")
153
+ if (!record(raw) || (raw._tag !== "Dispatch" && raw._tag !== "MessageSchema")) {
154
+ return yield* Effect.fail("AppKit supports only MessageSchema and Dispatch for the mounted root.")
155
+ }
156
+ const request = decodeRequest(raw)
157
+ const mounted = root
158
+ if (!mounted || mounted.session !== request.session) return yield* Effect.fail("No AppKit root for that session.")
159
+ if (instance !== request.instance) return yield* Effect.fail(`Instance ${request.instance} is not the mounted AppKit root.`)
160
+ if (request._tag === "MessageSchema") return yield* messageSchema(schema, request.tag)
161
+ const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(schema))
162
+ const messages = yield* Effect.forEach(request.messages, (message, index) =>
163
+ decode(message).pipe(Effect.mapError((error) => `Message ${index} does not decode: ${error.message}`)))
164
+ const deadline = Date.now() + request.within
165
+ const outcomes: Outcome[] = []
166
+ for (const message of messages) {
167
+ if (Date.now() >= deadline) break
168
+ const outcome = dispatch(mounted, request.instance, message)
169
+ outcomes.push(outcome)
170
+ if (outcome._tag !== "Updated") break
171
+ }
172
+ return { outcomes, paused: null }
173
+ })
174
+ const onControl = (text: string) => {
175
+ if (!bridge.__akDevToolsDispatch || closed) return
176
+ const envelope = decodeEnvelope(text)
177
+ if (envelope._tag === "None") return // No valid id to reply to.
178
+ const { id, request } = envelope.value
179
+ const reply = (ok: boolean, value: unknown) => {
180
+ if (!closed) send("control", { _tag: "Reply", id, ok, value })
181
+ }
182
+ Effect.runFork(handle(request).pipe(
183
+ Effect.matchCause({ onSuccess: (value) => reply(true, value), onFailure: (cause) => reply(false, Cause.pretty(cause)) }),
184
+ Effect.forkIn(scope)
185
+ ))
186
+ }
187
+ yield* Effect.addFinalizer(() => Effect.sync(() => {
188
+ closed = true
189
+ bridge.__akDevToolsClose()
190
+ }))
191
+ bridge.__akDevToolsConnect(onControl, () => { controlOpen = true; announce() })
192
+ // Wire v1 has no native host; use its headless (terminal) classification.
193
+ send("log", { _tag: "Hello", version: MessageLog.wireVersion, host: "terminal" } satisfies MessageLog.Wire)
194
+ const encoded = yield* MessageLog.makeEncoded((batch) => Effect.sync(() => {
195
+ for (const frame of batch) send("log", frame)
196
+ }))
197
+ // Mounted can be recorded before Renderer.mount returns its path and session.
198
+ const startup: Array<MessageLog.Mounted | MessageLog.Unmounted> = []
199
+ const lifecycle = (entry: MessageLog.Mounted | MessageLog.Unmounted) => {
200
+ if (!root) startup.push(entry)
201
+ else if (entry.path === root.path && entry.session === root.session) {
202
+ instance = entry._tag === "Mounted" ? entry.instance : undefined
203
+ }
204
+ }
205
+ const log = MessageLog.fanoutAll([ambient, encoded, {
206
+ enabled: bridge.__akDevToolsDispatch,
207
+ record: (entry) => {
208
+ if (entry._tag === "Mounted" || entry._tag === "Unmounted") lifecycle(entry)
209
+ observe?.(entry)
210
+ }
211
+ }])
212
+ root = yield* mount.pipe(Effect.provideService(MessageLog.MessageLog, log))
213
+ for (const entry of startup) lifecycle(entry)
214
+ startup.length = 0
215
+ announce()
216
+ return root
217
+ })
218
+ }
package/src/runtime.js ADDED
@@ -0,0 +1,5 @@
1
+ // Import effect-appkit/runtime first: Effect constructs UTF-8 codecs during module evaluation.
2
+ import { TextDecoder, TextEncoder } from "text-encoding-utf-8/src/encoding.js"
3
+
4
+ globalThis.TextEncoder ??= TextEncoder
5
+ globalThis.TextDecoder ??= TextDecoder