@native-sdk/cli 0.8.2 → 0.8.4
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/build/app.zig +50 -3
- package/build.zig +134 -360
- package/native-sdk.d.ts +4 -0
- package/package.json +9 -9
- package/packages/core/compile-surface/core.ts +90 -1
- package/packages/core/package-lock.json +2 -2
- package/packages/core/package.json +1 -1
- package/packages/core/sdk/core.d.ts +65 -2
- package/packages/core/sdk/core.ts +189 -33
- package/packages/core/sdk/events.d.ts +14 -0
- package/packages/core/sdk/events.ts +18 -0
- package/packages/core/src/checker.ts +61 -1
- package/packages/core/src/devhost.ts +3 -3
- package/packages/core/src/diagnostics.ts +4 -4
- package/skill-data/core/SKILL.md +4 -2
- package/skill-data/core/references/project-anatomy.md +2 -1
- package/skill-data/core/references/web-engines-packaging-debugging.md +3 -1
- package/skill-data/native-ui/SKILL.md +8 -8
- package/skill-data/ts-core/SKILL.md +16 -13
- package/src/app_runner/app_assets.zig +138 -0
- package/src/app_runner/root.zig +2 -0
- package/src/app_runner/ts_core_main.zig +27 -3
- package/src/embed/host.zig +6 -0
- package/src/embed/ui_host.zig +2 -0
- package/src/platform/linux/root.zig +1 -0
- package/src/platform/macos/appkit_host.h +10 -0
- package/src/platform/macos/appkit_host.m +515 -93
- package/src/platform/macos/capture_info_plist.c +25 -0
- package/src/platform/macos/cef_host.mm +22 -0
- package/src/platform/macos/root.zig +68 -0
- package/src/platform/null_platform.zig +58 -0
- package/src/platform/root.zig +7 -0
- package/src/platform/types.zig +100 -0
- package/src/platform/windows/root.zig +56 -0
- package/src/platform/windows/webview2_host.cpp +171 -0
- package/src/primitives/app_manifest/types.zig +2 -0
- package/src/primitives/canvas/code_tests.zig +9 -9
- package/src/primitives/canvas/events.zig +12 -11
- package/src/primitives/canvas/frame.zig +44 -9
- package/src/primitives/canvas/icons/mic.svg +1 -0
- package/src/primitives/canvas/icons.zig +2 -0
- package/src/primitives/canvas/root.zig +8 -0
- package/src/primitives/canvas/text_span_tests.zig +39 -0
- package/src/primitives/canvas/ui.zig +23 -4
- package/src/primitives/canvas/ui_markup.zig +15 -0
- package/src/primitives/canvas/ui_markup_compiled.zig +9 -0
- package/src/primitives/canvas/ui_markup_compiled_tests.zig +1 -1
- package/src/primitives/canvas/ui_markup_tests.zig +5 -0
- package/src/primitives/canvas/ui_markup_view.zig +9 -0
- package/src/primitives/canvas/ui_markup_view_tests.zig +9 -6
- package/src/primitives/canvas/ui_schema.zig +19 -10
- package/src/primitives/canvas/ui_schema_tests.zig +5 -3
- package/src/primitives/canvas/ui_tests.zig +18 -4
- package/src/primitives/canvas/widget_invalidation.zig +9 -2
- package/src/primitives/canvas/widget_render.zig +321 -115
- package/src/primitives/canvas/widget_runtime_tests.zig +173 -0
- package/src/primitives/canvas/widget_text_input.zig +10 -10
- package/src/primitives/canvas/widget_tree.zig +1 -1
- package/src/primitives/canvas/widgets.zig +41 -5
- package/src/root.zig +10 -0
- package/src/runtime/automation_widget_dispatch.zig +1 -0
- package/src/runtime/bridge_payload.zig +2 -0
- package/src/runtime/canvas_frame.zig +13 -2
- package/src/runtime/canvas_frame_invalidation_tests.zig +35 -10
- package/src/runtime/canvas_widget_anchored_tests.zig +83 -0
- package/src/runtime/canvas_widget_event_tests.zig +1 -0
- package/src/runtime/canvas_widget_events.zig +69 -24
- package/src/runtime/canvas_widget_runtime.zig +101 -6
- package/src/runtime/canvas_widget_scroll_driver_tests.zig +47 -4
- package/src/runtime/canvas_widget_scroll_drivers.zig +3 -3
- package/src/runtime/canvas_widget_semantics_tests.zig +2 -0
- package/src/runtime/canvas_widget_split_tree_tests.zig +228 -0
- package/src/runtime/canvas_widget_state.zig +10 -1
- package/src/runtime/canvas_widget_text_tests.zig +112 -3
- package/src/runtime/effects.zig +313 -2
- package/src/runtime/effects_audio_capture_tests.zig +251 -0
- package/src/runtime/root.zig +3 -0
- package/src/runtime/tests.zig +1 -0
- package/src/runtime/ts_core_host.zig +401 -32
- package/src/runtime/ts_core_host_tests.zig +407 -0
- package/src/runtime/ts_ui_app.zig +39 -1
- package/src/runtime/ui_app.zig +18 -3
- package/src/runtime/ui_app_tests.zig +48 -0
- package/src/runtime/view.zig +2 -0
- package/src/runtime/view_widget_scroll.zig +56 -5
- package/src/runtime/view_widget_text.zig +24 -5
- package/src/runtime/view_widget_tree.zig +1 -1
- package/src/tooling/manifest.zig +1034 -0
- package/src/tooling/package.zig +841 -10
- package/src/tooling/raw_manifest.zig +35 -0
- package/src/tooling/templates.zig +55 -0
- package/tools/corewire/emit_facade.zig +36 -0
|
@@ -73,3 +73,17 @@ export interface AudioEvent {
|
|
|
73
73
|
readonly buffering: boolean;
|
|
74
74
|
readonly bands: Uint8Array;
|
|
75
75
|
}
|
|
76
|
+
export type AudioCaptureSource = "microphone" | "system";
|
|
77
|
+
export type AudioCaptureState = "started" | "data" | "failed" | "stopped" | "rejected";
|
|
78
|
+
export interface AudioCaptureEvent {
|
|
79
|
+
readonly key: number;
|
|
80
|
+
readonly state: AudioCaptureState;
|
|
81
|
+
readonly source: AudioCaptureSource;
|
|
82
|
+
readonly sampleRate: number;
|
|
83
|
+
readonly channels: number;
|
|
84
|
+
readonly timestampMs: number;
|
|
85
|
+
readonly frames: number;
|
|
86
|
+
readonly pcm: Uint8Array;
|
|
87
|
+
readonly droppedPending: number;
|
|
88
|
+
readonly droppedTotal: number;
|
|
89
|
+
}
|
|
@@ -201,3 +201,21 @@ export interface AudioEvent {
|
|
|
201
201
|
readonly buffering: boolean;
|
|
202
202
|
readonly bands: Uint8Array;
|
|
203
203
|
}
|
|
204
|
+
|
|
205
|
+
/// Native audio-capture vocabulary and fixed event record. PCM chunks are
|
|
206
|
+
/// interleaved signed 16-bit little-endian in the requested format.
|
|
207
|
+
export type AudioCaptureSource = "microphone" | "system";
|
|
208
|
+
export type AudioCaptureState = "started" | "data" | "failed" | "stopped" | "rejected";
|
|
209
|
+
|
|
210
|
+
export interface AudioCaptureEvent {
|
|
211
|
+
readonly key: number;
|
|
212
|
+
readonly state: AudioCaptureState;
|
|
213
|
+
readonly source: AudioCaptureSource;
|
|
214
|
+
readonly sampleRate: number;
|
|
215
|
+
readonly channels: number;
|
|
216
|
+
readonly timestampMs: number;
|
|
217
|
+
readonly frames: number;
|
|
218
|
+
readonly pcm: Uint8Array;
|
|
219
|
+
readonly droppedPending: number;
|
|
220
|
+
readonly droppedTotal: number;
|
|
221
|
+
}
|
|
@@ -465,6 +465,7 @@ export class SubsetChecker {
|
|
|
465
465
|
this.checkCmdPurity();
|
|
466
466
|
this.checkSubPurity();
|
|
467
467
|
this.checkModelBindingSurface();
|
|
468
|
+
this.checkThemePackHelper();
|
|
468
469
|
this.checkViewUnbound();
|
|
469
470
|
this.checkReservedContractConsts();
|
|
470
471
|
this.checkValueRecordAliases();
|
|
@@ -661,6 +662,65 @@ export class SubsetChecker {
|
|
|
661
662
|
}
|
|
662
663
|
}
|
|
663
664
|
|
|
665
|
+
/// `themePack(model)` is both an ordinary exported Model helper and a
|
|
666
|
+
/// generated-launcher convention. Keep its shape exact here so a typo
|
|
667
|
+
/// is taught in core.ts instead of failing inside the generated Zig
|
|
668
|
+
/// adapter (or, worse, becoming an inert markup-only helper).
|
|
669
|
+
private checkThemePackHelper(): void {
|
|
670
|
+
let decl: ts.FunctionDeclaration | null = null;
|
|
671
|
+
for (const stmt of this.entry.statements) {
|
|
672
|
+
if (
|
|
673
|
+
ts.isFunctionDeclaration(stmt) &&
|
|
674
|
+
stmt.name?.text === "themePack" &&
|
|
675
|
+
hasExportModifier(stmt)
|
|
676
|
+
) {
|
|
677
|
+
decl = stmt;
|
|
678
|
+
break;
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
if (decl === null) {
|
|
682
|
+
for (const binding of exportListBindings(this.tast, this.entry)) {
|
|
683
|
+
if (
|
|
684
|
+
binding.exportedName === "themePack" &&
|
|
685
|
+
binding.target !== null &&
|
|
686
|
+
binding.target !== undefined &&
|
|
687
|
+
ts.isFunctionDeclaration(binding.target) &&
|
|
688
|
+
binding.target.getSourceFile() === this.entry
|
|
689
|
+
) {
|
|
690
|
+
decl = binding.target;
|
|
691
|
+
break;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
if (decl === null) return;
|
|
696
|
+
|
|
697
|
+
const helper = this.table.modelHelperDecls().find(
|
|
698
|
+
(candidate) => candidate.name === "themePack" && candidate.decl === decl,
|
|
699
|
+
);
|
|
700
|
+
if (helper === undefined || decl.type === undefined) {
|
|
701
|
+
this.report(
|
|
702
|
+
"NS1033",
|
|
703
|
+
"`themePack` is not a single-Model-parameter helper with an explicit return type.",
|
|
704
|
+
decl.name ?? decl,
|
|
705
|
+
);
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
const returns = this.table.resolveTypeNode(decl.type);
|
|
710
|
+
if (
|
|
711
|
+
returns.k !== "enum" ||
|
|
712
|
+
returns.members.length !== 2 ||
|
|
713
|
+
!returns.members.includes("house") ||
|
|
714
|
+
!returns.members.includes("geist")
|
|
715
|
+
) {
|
|
716
|
+
this.report(
|
|
717
|
+
"NS1033",
|
|
718
|
+
"`themePack` does not return exactly the built-in `\"house\" | \"geist\"` theme-pack union.",
|
|
719
|
+
decl.type,
|
|
720
|
+
);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
|
|
664
724
|
/// NS1032 — `export const viewUnbound = [...] as const`: the dead-state
|
|
665
725
|
/// lint opt-out. Every entry must be a string literal naming a Model
|
|
666
726
|
/// field, an exported model helper, or a Msg kind; the emitter routes the
|
|
@@ -1092,7 +1152,7 @@ export class SubsetChecker {
|
|
|
1092
1152
|
/// entry points, but the exports themselves live in the entry module.
|
|
1093
1153
|
private static readonly entryOnlyExports = new Set([
|
|
1094
1154
|
"update", "initialModel", "subscriptions",
|
|
1095
|
-
"commandMsg", "keyMsg", "frameMsg", "pinchMsg", "dropMsg", "appearanceMsg", "chromeMsg", "envMsgs",
|
|
1155
|
+
"commandMsg", "keyMsg", "frameMsg", "pinchMsg", "dropMsg", "appearanceMsg", "chromeMsg", "envMsgs", "themePack",
|
|
1096
1156
|
"viewUnbound", "modelUnbound", "msgUnbound",
|
|
1097
1157
|
]);
|
|
1098
1158
|
|
|
@@ -33,8 +33,8 @@
|
|
|
33
33
|
// - timer/now/delay arms carry exactly one number payload field (pinned
|
|
34
34
|
// by tsc), so the harness constructs them shape-directed without
|
|
35
35
|
// needing the field's name.
|
|
36
|
-
// Every other effect (files, fetch, clipboard,
|
|
37
|
-
// host commands)
|
|
36
|
+
// Every other effect (files, buffered/streaming fetch, clipboard,
|
|
37
|
+
// notifications, spawn, audio, host commands)
|
|
38
38
|
// is printed as `cmd ...` and NOT performed — feed its result back yourself
|
|
39
39
|
// as an ordinary Msg line. That is the point: results are plain messages,
|
|
40
40
|
// and the loop stays deterministic.
|
|
@@ -161,7 +161,7 @@ function performCmd(cmd: Cmdish): void {
|
|
|
161
161
|
if (delays.delete(key)) {
|
|
162
162
|
say(`cmd cancel ${key} (delay dropped)`);
|
|
163
163
|
} else {
|
|
164
|
-
say(`cmd cancel ${key} (not performed here - a live request or named op drops silently; a live spawn ends loudly, err arm "cancelled")`);
|
|
164
|
+
say(`cmd cancel ${key} (not performed here - a live request or buffered named op drops silently; a live spawn or streaming fetch ends loudly, err arm "cancelled")`);
|
|
165
165
|
}
|
|
166
166
|
return;
|
|
167
167
|
}
|
|
@@ -104,7 +104,7 @@ export const rules = {
|
|
|
104
104
|
id: "NS1014",
|
|
105
105
|
title: "the core's entry points live in core.ts",
|
|
106
106
|
fix: "Move this export into src/core.ts (imported modules may hold the helpers it calls and the types it uses).",
|
|
107
|
-
why: "The build wires `update`, `initialModel`, `subscriptions`, the host-event channels, and `viewUnbound` from the entry module only, so an entry export in an imported file would be silently ignored.",
|
|
107
|
+
why: "The build wires `update`, `initialModel`, `subscriptions`, the host-event channels, `themePack`, and `viewUnbound` from the entry module only, so an entry export in an imported file would be silently ignored.",
|
|
108
108
|
},
|
|
109
109
|
NS1015: {
|
|
110
110
|
id: "NS1015",
|
|
@@ -216,9 +216,9 @@ export const rules = {
|
|
|
216
216
|
},
|
|
217
217
|
NS1033: {
|
|
218
218
|
id: "NS1033",
|
|
219
|
-
title: "wiring
|
|
220
|
-
fix: "Declare the channel exactly: `commandMsg(name: string)` / `keyMsg(key: KeyEvent)` / `frameMsg(model: Model, frame: FrameEvent)` / `pinchMsg(pinch: PinchEvent)` / `dropMsg(drop: FileDropEvent)` returning `Msg | null`; `export const appearanceMsg = \"<arm>\"` / `chromeMsg = \"<arm>\"` naming a Msg arm with that channel's record shape; `export const envMsgs = [{ env: \"NAME\", msg: \"<arm>\" }] as const` with one-`Uint8Array`-field arms.",
|
|
221
|
-
why: "The generated wiring builds
|
|
219
|
+
title: "wiring exports match their runtime shapes",
|
|
220
|
+
fix: "Declare the channel exactly: `commandMsg(name: string)` / `keyMsg(key: KeyEvent)` / `frameMsg(model: Model, frame: FrameEvent)` / `pinchMsg(pinch: PinchEvent)` / `dropMsg(drop: FileDropEvent)` returning `Msg | null`; `themePack(model: Model): ThemePack` where `ThemePack` is `\"house\" | \"geist\"`; `export const appearanceMsg = \"<arm>\"` / `chromeMsg = \"<arm>\"` naming a Msg arm with that channel's record shape; `export const envMsgs = [{ env: \"NAME\", msg: \"<arm>\" }] as const` with one-`Uint8Array`-field arms.",
|
|
221
|
+
why: "The generated wiring builds host events and model-derived theme selection structurally from your declarations at build time; a wrong shape would otherwise surface as a Zig compile error inside generated code instead of a teaching diagnostic here.",
|
|
222
222
|
},
|
|
223
223
|
NS1034: {
|
|
224
224
|
id: "NS1034",
|
package/skill-data/core/SKILL.md
CHANGED
|
@@ -177,9 +177,11 @@ Zero-config apps package WITHOUT ejecting — `native package` works directly on
|
|
|
177
177
|
|
|
178
178
|
```bash
|
|
179
179
|
native build
|
|
180
|
-
native package --target macos
|
|
180
|
+
native package --target macos --archive
|
|
181
181
|
```
|
|
182
182
|
|
|
183
|
+
On macOS, `--archive` adds a zero-config drag-to-Applications DMG with a generated 1×/2× Retina background. The optional `app.zon` `.dmg` block controls its volume name, PNG/JPEG/TIFF background, usable Finder canvas/icon geometry, and Applications link. An adjacent `name@2x.png`/`.jpg` is discovered automatically. Use `.dmg.items` only for a fully art-directed list: exactly one `app`, plus optional `applications`, project-relative `file`, and absolute `link` entries, each with its own icon-center position.
|
|
184
|
+
|
|
183
185
|
Apps that own their build (ejected or scaffolded `--full`) wire the same step into the build graph: keep package metadata in `app.zon`, build the frontend assets, build the native binary, then package:
|
|
184
186
|
|
|
185
187
|
```bash
|
|
@@ -265,7 +267,7 @@ When changing app behavior, keep tests in the app's existing authoring tier. Typ
|
|
|
265
267
|
|
|
266
268
|
## Examples to inspect
|
|
267
269
|
|
|
268
|
-
- `examples/
|
|
270
|
+
- `examples/chatbot`: a substantial app authored entirely in TypeScript + Native markup, with streaming fetch effects and modules.
|
|
269
271
|
- `examples/soundboard-ts`: TypeScript + Native markup port of the full music-player showcase.
|
|
270
272
|
- `examples/system-monitor-ts`: TypeScript + Native markup app using spawn effects, timers, and tables.
|
|
271
273
|
- `examples/hello`: smallest lower-level inline HTML/WebView app.
|
|
@@ -79,6 +79,7 @@ Important manifest fields:
|
|
|
79
79
|
- `web_engine`: `system` or `chromium`.
|
|
80
80
|
- `cef`: CEF layout config for Chromium.
|
|
81
81
|
- `windows`: initial window definitions.
|
|
82
|
+
- `dmg`: optional macOS disk-image art direction; use the zero-config drag-to-Applications layout, override its background/geometry, or declare a positioned `items` list for arbitrary files and links.
|
|
82
83
|
|
|
83
84
|
## Build steps to know
|
|
84
85
|
|
|
@@ -89,7 +90,7 @@ native check
|
|
|
89
90
|
native dev
|
|
90
91
|
native test
|
|
91
92
|
native build
|
|
92
|
-
native package --target macos
|
|
93
|
+
native package --target macos --archive
|
|
93
94
|
```
|
|
94
95
|
|
|
95
96
|
Equivalent/common owned-build steps:
|
|
@@ -71,7 +71,7 @@ zig build package
|
|
|
71
71
|
CLI path:
|
|
72
72
|
|
|
73
73
|
```bash
|
|
74
|
-
native package --target macos --manifest app.zon --binary zig-out/bin/MyApp
|
|
74
|
+
native package --target macos --manifest app.zon --binary zig-out/bin/MyApp --archive
|
|
75
75
|
```
|
|
76
76
|
|
|
77
77
|
Important package manifest fields:
|
|
@@ -98,6 +98,8 @@ For frontend apps, package the built frontend assets. The build step usually wir
|
|
|
98
98
|
|
|
99
99
|
macOS minimum system version is 11.0.
|
|
100
100
|
|
|
101
|
+
With `--archive`, the CLI wraps that bundle in a styled DMG. Defaults include a generated 1×/2× Retina background and arrow, an Applications alias, positioned 128px icons, hidden Finder chrome, and a 660×400 usable canvas. Override `.dmg.volume_name`, `.background`, `.window_width`, `.window_height`, `.icon_size`, `.app_position`, `.applications_position`, or `.applications_link` in `app.zon`. Custom backgrounds are project-relative PNG/JPEG/TIFF files; a neighboring `name@2x.png`/`.jpg` is combined automatically, and a prebuilt multi-resolution TIFF also works. For arbitrary visible contents, `.dmg.items` replaces the fixed pair with positioned `app`, `applications`, project-relative `file`, and absolute `link` entries.
|
|
102
|
+
|
|
101
103
|
Signing modes:
|
|
102
104
|
|
|
103
105
|
```bash
|
|
@@ -17,7 +17,7 @@ The markup compiles to the same widget tree a hand-written `canvas.Ui(Msg)` buil
|
|
|
17
17
|
|
|
18
18
|
Editors highlight `.native` markup well in HTML mode — the default scaffold writes no editor config, so add `.vscode/settings.json` with `"files.associations": {"*.native": "html"}` yourself, or scaffold with `native init --full`, which writes it.
|
|
19
19
|
|
|
20
|
-
Start a new app with `native init` (zero-config: `app.zon` + `src/core.ts` + `src/app.native` + assets; the CLI generates the build graph). Use `examples/
|
|
20
|
+
Start a new app with `native init` (zero-config: `app.zon` + `src/core.ts` + `src/app.native` + assets; the CLI generates the build graph). Use `examples/chatbot`, `examples/soundboard-ts`, and `examples/system-monitor-ts` as substantial TypeScript references. The `native check|dev|test|build` verbs drive any app directory shaped this way.
|
|
21
21
|
|
|
22
22
|
## App wiring (Zig cores and extensions only)
|
|
23
23
|
|
|
@@ -180,7 +180,7 @@ Automation drives the native path honestly: snapshots list every widget's declar
|
|
|
180
180
|
| `text` > `span` | inline styled runs | mixed-style text in ONE wrapped paragraph: span children style runs with `weight="regular\|medium\|bold"`, `mono`, `italic`, `scale` (a positive multiplier on the paragraph's base size — inline headings, hero stats), `underline`, `foreground` (token name); `{bindings}` interpolate inside spans; whitespace between runs collapses to a single space (none = the runs abut); spans do not nest, take no events, and the paragraph announces as one text run — see "Rich text" |
|
|
181
181
|
| `button`, `toggle-button`, `list-item`, `menu-item`, `toggle`, `switch`, `select`, `avatar` | text-bearing controls | label is the text content; `button`, `toggle-button`, `list-item`, and `menu-item` also take `icon="save"` — a vector icon drawn inline (buttons/toggle-buttons before the label, icon-only when the content is empty: add a `label`; list/menu items as a leading slot), ONE hit target whose icon follows the element's enabled/disabled tint (no overlay stacking, no duplicated `on-press`); tab strips are `toggle-button` children, so tabs get icons this way; `select` shows `placeholder` while empty and dispatches `on-press`; `avatar` renders initials, or a runtime image via `image="{binding}"` (see the Images section) |
|
|
182
182
|
| `checkbox`, `radio`, `slider`, `progress` | value controls | `checked`, `value` (a 0..1 fraction on slider and progress; progress clamps out-of-range values at render, never an error); the checkbox/radio label rides `text="..."` — these are not text-bearing elements, so text content is a teaching error (`label=` alone names one for accessibility without a visible label); a slider's `value` follows the source when it MOVES (model-driven progress renders every rebuild) and keeps the user's drag while the source replays the same value — use `slider` for seek bars, `progress` for display-only; a markup slider's `on-change` dispatches a PLAIN Msg with no value payload — mirror the applied value into the model with `Options.sync` (the Zig builder's `on_value = Ui.valueMsg(.tag)` does deliver the applied f32) |
|
|
183
|
-
| `text-field`, `input`, `search-field`, `combobox`, `textarea` | text entry | `placeholder`; edits via `on-input`, enter via `on-submit` on single-line kinds; in a `textarea`, Enter (and Shift+Enter) inserts a newline and `on-submit` dispatches on primary+Enter (cmd on macOS, ctrl elsewhere)
|
|
183
|
+
| `text-field`, `input`, `search-field`, `combobox`, `textarea` | text entry | `placeholder`; edits via `on-input`, enter via `on-submit` on single-line kinds; in a default `textarea`, Enter (and Shift+Enter) inserts a newline and `on-submit` dispatches on primary+Enter (cmd on macOS, ctrl elsewhere). A chat composer opts into `submit-on-enter="true"`: plain Enter submits, Shift+Enter remains a newline, and the primary chord still submits. `search-field` carries a built-in trailing clear affordance whenever it holds text (press the x, or Escape while focused — both clear through the text-edit path, so `on-input` hears it; no attribute, no external Clear button needed) |
|
|
184
184
|
| `status-bar` | status bar | text leaf: content only, no children |
|
|
185
185
|
| `separator`, `spacer` | separator, flexible space | `separator` is axis-aware: a horizontal rule in a `column`, a thin vertical divider in a `row`; give `spacer` a `grow` |
|
|
186
186
|
| `skeleton`, `spinner` | loading leaves | size `skeleton` with `width`/`height` |
|
|
@@ -193,13 +193,13 @@ Automation drives the native path honestly: snapshots list every widget's declar
|
|
|
193
193
|
| `timeline` > `timeline-item` | composite ledger list | items only inside a timeline (for/if fine); items are leaves — `title` (required), `description`, `meta`, `indicator`, `variant`, `connector="false"` on the last item, `selected`; `on-press` makes the whole item pressable with a trailing chevron |
|
|
194
194
|
| `chart` > `series` | composite data chart | series only inside a chart, and only series (the set is static — data varies through bindings); each series is a leaf — `values="{binding}"` (required) names a model `[]const f32` iterable, `kind` is `line`/`area`/`bar` (literal), `color` a token name, `label` the semantics name; chart takes `y-min`, `y-max`, `grid-lines`, `baseline`, `x-labels`, `y-labels`, `hover-details`, `stroke-width`, box options, `label` — see "Charts" |
|
|
195
195
|
| `context-menu` | consumed by its parent | right-click menu on its DIRECT parent (a hit target or an element with `on-press`/`on-hold`); metadata, never a flow child. Children: `menu-item`s (`on-press` required, `disabled` optional, no `icon`) and bare `separator`s, with `if`/`else`/`for` around them. Attribute-less; presents natively where the host has a menu presenter, as an anchored surface elsewhere — see "Context menus" |
|
|
196
|
-
| `input-group` > `textarea` + `input-group-actions` | composite grouped input | the composer shape: ONE bordered field wrapping exactly one `textarea` (first — document order is focus order) plus an optional `input-group-actions` row of controls inside the same border. The group wears the focus ring for its focused descendant and the textarea's own chrome dissolves automatically, so the whole group reads as one field; the textarea keeps its full behavior (`text`, `placeholder`, `on-input`, `on-submit`, `autofocus`). Group takes `label`, `width`, `height`, `min-width`, `grow`, `key`, `global-key`; the actions row takes `gap` and holds ordinary elements (`if`/`else`/`for` work — swap send for stop while streaming) — put a `<spacer grow="1"/>` between leading and trailing controls (`Ui.inputGroup`/`Ui.inputGroupActions` are the Zig-view equivalents) |
|
|
196
|
+
| `input-group` > `textarea` + `input-group-actions` | composite grouped input | the composer shape: ONE bordered field wrapping exactly one `textarea` (first — document order is focus order) plus an optional `input-group-actions` row of controls inside the same border. The group wears the focus ring for its focused descendant and the textarea's own chrome dissolves automatically, so the whole group reads as one field; the textarea keeps its full behavior (`text`, `placeholder`, `on-input`, `on-submit`, `autofocus`, and optional `submit-on-enter`). Group takes `label`, `width`, `height`, `min-width`, `grow`, `key`, `global-key`; the actions row takes `gap` and holds ordinary elements (`if`/`else`/`for` work — swap send for stop while streaming) — put a `<spacer grow="1"/>` between leading and trailing controls (`Ui.inputGroup`/`Ui.inputGroupActions` are the Zig-view equivalents) |
|
|
197
197
|
|
|
198
198
|
Not markup-expressible (deliberately — write these as Zig view functions with `canvas.Ui`): `icon_button` (`<button icon="...">` with empty content is the declarative icon button), `data_grid` (per-column cell templates), `popover`/`menu_surface` (anchored to runtime geometry), `segmented_control` (use `tabs`/`toggle-group`: `<button>` children of `<tabs>` lower to segmented triggers automatically, so the active tab lifts per the house treatment). Charts ARE expressible: `<chart>` with `<series values="{binding}">` children binding model f32 iterables — see the Charts section (`.band` series and dynamic series composition stay with `ui.chart`). Built-in vector icons ARE expressible: `<icon name="search"/>` (closed, compile-checked name set; `Ui.icon` is the Zig-view equivalent). App-authored icons: `canvas.svg_icon.parseComptime(@embedFile("icons/logo.svg"))` parses any SVG in the common 24x24 stroke-icon dialect at comptime; register the parsed table once at boot with `canvas.icons.registerAppIcons(&table)` and draw by name via `ui.appIcon(.{...}, "logo")` or `ElementOptions.icon` — registered names render exactly like built-ins on every draw path. Markup `<icon>`/`<button icon>` stay built-in-only (the compiled engine validates names at comptime, where runtime registrations cannot exist — engine parity). Runtime images ARE expressible: `<image image="{cover}" width="120" height="80" label="Cover art"/>` and `<avatar image="{user_image}">CT</avatar>` bind a `u64` ImageId model field/fn (the id is just model data; 0 draws nothing / keeps the initials fallback) — see the Images section; the `image` binding is required on the leaf (an unbound `<image>` is dead markup) and stays avatar+image scoped.
|
|
199
199
|
|
|
200
200
|
## Attributes
|
|
201
201
|
|
|
202
|
-
Layout: `gap` (flow containers only — stacking containers `stack`/`panel`/`card`/`alert`/`bubble`/`dialog`/`drawer`/`sheet`/`resizable` layer their children, so `gap` there is a validation error, not silence: wrap the children in a `column`/`row` inside; on `split` it sets the divider band thickness), `padding` (uniform), `grow`, `width`, `height` (definite: the element is exactly that size — intrinsic content neither shrinks nor silently overflows it; `resizable` treats `width` as the initial width), `min-width` (a floor WITHOUT `width`'s definite max — the element may grow past it but never shrink below; on split panes it bounds the divider drag), `wrap` (`text` only: `wrap="true"` word-wraps at the width the element receives and reserves the wrapped height in columns; `wrap="false"` and unset are honest single-line — one line whose overflow follows `overflow`), `overflow` (`text` only, a teaching error elsewhere: what a single line does with content that does not fit — `ellipsis`, the default, elides behind a trailing … measured with the same metrics paint uses, right for width-constrained list-row titles; `clip` hard-cuts at the frame for fixed-format content like a duration column where "1…" beats nothing; there is deliberately no overflow-visible), `text-alignment` (start|center|end — text leaves, status bars, surface titles; controls that own their label placement ignore it), `columns` (`grid` only: fixed column count, omit for the derived near-square grid; a teaching error elsewhere), `main` (start|center|end|space_between), `cross` (stretch|start|center|end), `virtualized`, `virtual-item-extent`, `anchor` (`dropdown-menu` and `tooltip`, literal `below`/`above`: floats the surface against its parent instead of the flow — auto-flips when the preferred side does not fit, height clamps to the chosen side, x clamps into the window; an anchored tooltip's visibility is runtime-owned hover intent, unlike the model-owned dropdown), `anchor-alignment` (with `anchor`: `start`/`end`/`stretch` — stretch also widens the surface to at least the anchor's width, the select-menu look), `anchor-offset` (with `anchor`: literal gap in points, default 4), `tooltip-delay` (`tooltip` only, beside `anchor` — a teaching error elsewhere or without it: hover-intent show delay in ms, default 600, `"0"` = instant; keyboard-focus reveals are always immediate), `overscroll` (`scroll` only, a teaching error elsewhere: `none` pins the region at its content edges — the shipped default via the `ScrollPhysics.overscroll` token — `rubber_band` lets it bounce past them on both the engine and native paths, `default` follows the token).
|
|
202
|
+
Layout: `gap` (flow containers only — stacking containers `stack`/`panel`/`card`/`alert`/`bubble`/`dialog`/`drawer`/`sheet`/`resizable` layer their children, so `gap` there is a validation error, not silence: wrap the children in a `column`/`row` inside; on `split` it sets the divider band thickness), `padding` (uniform), `grow`, `width`, `height` (definite: the element is exactly that size — intrinsic content neither shrinks nor silently overflows it; `resizable` treats `width` as the initial width), `min-width` (a floor WITHOUT `width`'s definite max — the element may grow past it but never shrink below; on split panes it bounds the divider drag), `max-width` (a ceiling WITHOUT `width`'s definite min — the element still shrinks with a narrow parent; use a growing child inside a centered row for a responsive content column), `wrap` (`text` only: `wrap="true"` word-wraps at the width the element receives and reserves the wrapped height in columns; `wrap="false"` and unset are honest single-line — one line whose overflow follows `overflow`), `overflow` (`text` only, a teaching error elsewhere: what a single line does with content that does not fit — `ellipsis`, the default, elides behind a trailing … measured with the same metrics paint uses, right for width-constrained list-row titles; `clip` hard-cuts at the frame for fixed-format content like a duration column where "1…" beats nothing; there is deliberately no overflow-visible), `text-alignment` (start|center|end — text leaves, status bars, surface titles; controls that own their label placement ignore it), `columns` (`grid` only: fixed column count, omit for the derived near-square grid; a teaching error elsewhere), `main` (start|center|end|space_between), `cross` (stretch|start|center|end), `virtualized`, `virtual-item-extent`, `anchor` (`dropdown-menu` and `tooltip`, literal `below`/`above`: floats the surface against its parent instead of the flow — auto-flips when the preferred side does not fit, height clamps to the chosen side, x clamps into the window; an anchored tooltip's visibility is runtime-owned hover intent, unlike the model-owned dropdown), `anchor-alignment` (with `anchor`: `start`/`end`/`stretch` — stretch also widens the surface to at least the anchor's width, the select-menu look), `anchor-offset` (with `anchor`: literal gap in points, default 4), `tooltip-delay` (`tooltip` only, beside `anchor` — a teaching error elsewhere or without it: hover-intent show delay in ms, default 600, `"0"` = instant; keyboard-focus reveals are always immediate), `overscroll` (`scroll` only, a teaching error elsewhere: `none` pins the region at its content edges — the shipped default via the `ScrollPhysics.overscroll` token — `rubber_band` lets it bounce past them on both the engine and native paths, `default` follows the token).
|
|
203
203
|
Appearance/state: `variant` (default|primary|secondary|outline|ghost|destructive), `size` (the control scale default|sm|lg|icon on every sized element; on `text` also the typography rungs heading|display — named typography token steps (`heading_size` 28, `display_size` 48, themable like every token) for section headings and hero stats/timer numerals. The two axes stay apart: heading/display on a control is a teaching error naming text as their home, unknown values list the vocabulary, and numeric sizes are refused by design — retheme the typography tokens to move the whole scale), `disabled`, `checked`, `selected`, `value`, `placeholder`, `icon` (`button`, `toggle-button`, `list-item`, `menu-item`: vector icon drawn inline — buttons/toggle-buttons before the label, list/menu items as a leading slot; a teaching error anywhere else. A built-in name, `app:<name>`, or one `{binding}` resolving to such a name). **One size register per row**: every control class shares the control height at a given register (default 36, sm 31.5, lg 40.5 before density), so a toolbar/filter row reads as one height exactly when every control in it carries the SAME `size` — mixing `size="sm"` buttons with a default field renders two heights in one row, and hand-sized pressable panels (`height="30"`) never land on the scale; compose rows from real controls at one register.
|
|
204
204
|
Focus: `autofocus` (focusable controls only — a teaching error elsewhere): moves keyboard focus to the element when it MOUNTS or when the bound value turns on, edge-triggered so holding it true never re-steals focus from the user. The TEA way to focus an editor on note-create (`<text-field autofocus="{editing}" ...>` or mount the field under an `<if>` with `autofocus="true"`; Zig views use `ElementOptions.autofocus`) and to give keyboard-first apps their first focus without a click.
|
|
205
205
|
Semantics: `role` (listitem, treeitem, button, ...; `treeitem` also makes the row part of its tree's roving keyboard focus set), `label` (accessible name — it REPLACES the element's text content as the announced name, so snapshot greps and screen readers see the label, never the text; don't `label` an element whose visible text you grep for), `expanded` (tree rows: disclosure state, model-owned — omit on leaves). Accessible names are ENFORCED: an interactive control with no text content, no `text=`, and no `label=` is a validation error (icon-only controls need `label`; text-entry controls need `label` or `placeholder`), unknown/misused literal roles are errors (`role="tree"` on a text leaf can never hold rows), unnamed avatars and labels duplicating the text content are warnings (`label=""` marks an image decorative). Zig-built trees get the same discipline from `canvas.expectA11yAuditSweepClean` (missing names as the bridges would announce them, focusables clipped out of keyboard reach, identically labeled siblings) — adopt it next to the layout sweep.
|
|
@@ -368,7 +368,7 @@ Color and radius come from the design tokens, referenced by token NAME — liter
|
|
|
368
368
|
</row>
|
|
369
369
|
```
|
|
370
370
|
|
|
371
|
-
References resolve against the app's LIVE tokens on every rebuild (`finalizeWithTokens`), so a themed app (`tokens`/`tokens_fn`) re-resolves them when the theme changes — dark mode flips `surface` automatically. The DEFAULT theme follows the system appearance: an app that sets neither `tokens` nor `tokens_fn` derives the stock tokens from the OS light/dark setting (plus high-contrast and reduce-motion) and re-themes live when the user flips it. Pass explicit `tokens` for a fixed look, or `tokens_fn` for model-owned
|
|
371
|
+
References resolve against the app's LIVE tokens on every rebuild (`finalizeWithTokens`), so a themed app (`tokens`/`tokens_fn`) re-resolves them when the theme changes — dark mode flips `surface` automatically. The DEFAULT theme follows the system appearance: an app that sets neither `tokens` nor `tokens_fn` derives the stock tokens from the OS light/dark setting (plus high-contrast and reduce-motion) and re-themes live when the user flips it. A TypeScript core may export `themePack(model: Model): ThemePack` (`ThemePack = "house" | "geist"`) for a model-owned built-in pack toggle; the generated adapter changes only the pack and preserves those live system axes, manifest accent, and surface scale. Pass explicit `tokens` for a fixed look, or `tokens_fn` for a fully model-owned custom palette (usually still following the system scheme through `on_appearance`). An explicit `style` value set in Zig always wins over a token ref on the same field. Unknown token names are validation/compile errors.
|
|
372
372
|
|
|
373
373
|
One Zig-only style knob rides beside the tokens: `ElementOptions.style = .{ .quiet_hover = true }` silences a pressable surface's pointer HOVER wash only — press and selection fills, the focus ring, cursor intent, and hit testing stay — for image-forward content tiles (cover art, photo cards) where the pointer rests on content rather than a control register. Acting controls (list rows, menu items, buttons, tab triggers) keep their washes: there the hover fill IS the affordance.
|
|
374
374
|
|
|
@@ -484,7 +484,7 @@ For `<if test>`, prefer an explicit boolean predicate method over numeric truthi
|
|
|
484
484
|
|
|
485
485
|
## Messages
|
|
486
486
|
|
|
487
|
-
`on-press`, `on-double-press`, `on-toggle`, `on-change`, `on-submit` (
|
|
487
|
+
`on-press`, `on-double-press`, `on-toggle`, `on-change`, `on-submit` (Enter in a text field; primary+Enter in a default textarea; plain Enter too when that textarea declares `submit-on-enter="true"`), `on-dismiss` (dismissible surfaces: dialog, drawer, sheet, dropdown-menu — dispatched when Escape or a click outside dismisses the surface, so the model owns the close), `on-hold` (press-and-hold, see the Pickers section), and `on-hover-enter`/`on-hover-leave` (the pointer-hover containment pair, below) take `tag` or `tag:{payload}`. The tag must be an arm of your `Msg` union; payload bindings coerce to the arm's payload type. In TypeScript, an arm is `{ readonly kind: "tag"; readonly field: Type }`; in Zig it is a tagged-union variant. `on-input` is special: name an arm carrying `TextInputEvent` from `@native-sdk/core/text` in TypeScript or `canvas.TextInputEvent` in Zig. `on-scroll` (the `scroll` element only) similarly carries `ScrollState` from `@native-sdk/core/events` in TypeScript or `canvas.ScrollState` in Zig. In Zig builder views the constructors are `Ui.inputMsg(.tag)` / `Ui.scrollMsg(.tag)` on `on_input` / `on_scroll`. `on-reach-end` (the `scroll` element only; `on_reach_end` in Zig views, any scroll container including the windowed virtual list) is a plain Msg dispatched when a user scroll comes within one viewport of the content end — the infinite-fetch signal, fired once per approach with hysteresis (re-arms past 1.5 viewports, which appending a batch causes by growing the extent). A programmatic jump to the end fires once and NEVER re-arms while the offset stays near the end — re-arming needs a post-scroll observation at least 1.5 viewports from it.
|
|
488
488
|
|
|
489
489
|
Scroll offsets follow the same mirror discipline as text: the Msg carries the offset the runtime ALREADY applied, so store it in the model and echo it back through the scroll's `value` — the echoed source value equals the runtime offset, which the scroll reconcile rule treats as "unchanged", so rebuilds never stomp live scrolling. `on-scroll` is how long content pages or lazy-loads: keep a bounded window in the model and slide it from `offset` (near-end when `offset + viewport_extent` approaches `content_extent`).
|
|
490
490
|
|
|
@@ -814,8 +814,8 @@ The `.wake` platform event is how live platforms marshal worker completions onto
|
|
|
814
814
|
|
|
815
815
|
> **Effects test surface — exact signatures.** These are the complete fake-executor entry points; do not excavate the SDK source. Harness and switch: `const harness = try native_sdk.TestHarness().create(std.testing.allocator, .{ .size = geometry.SizeF.init(w, h) });` then `app_state.effects.executor = .fake;` before dispatching. Every `feed*`/`fire*` returns `error{EffectNotFound}!void`; every `pending*At(index: usize)` returns an optional request record; each family's `pending*Count()` returns `usize`.
|
|
816
816
|
>
|
|
817
|
-
> - Spawn: `pendingSpawnAt(index: usize) ?SpawnRequest` · `feedLine(key: u64, bytes: []const u8)` · `feedStderr(key: u64, bytes: []const u8)` · `feedExit(key: u64, code: i32)` · `feedExitReason(key: u64, code: i32, reason: EffectExitReason)` (`feedExit` is the clean-exit sugar; the reason enum covers `signaled`/`cancelled`/...) · `feedOutput(key: u64, bytes: []const u8)` (raw collect-stdout append, no line framing).
|
|
818
|
-
> - Fetch: `pendingFetchAt(index: usize) ?FetchRequest` · `feedResponse(key: u64, status: u16, body: []const u8)` · `feedResponseOutcome(key: u64, outcome: EffectFetchOutcome, status: u16, body: []const u8)`.
|
|
817
|
+
> - Spawn: `pendingSpawnAt(index: usize) ?SpawnRequest` · `feedLine(key: u64, bytes: []const u8)` · `feedLineWithMetadata(key: u64, bytes: []const u8, truncated: bool, dropped_before: u32)` (line mode only; also serves streamed fetches) · `feedStderr(key: u64, bytes: []const u8)` · `feedExit(key: u64, code: i32)` · `feedExitReason(key: u64, code: i32, reason: EffectExitReason)` (`feedExit` is the clean-exit sugar; the reason enum covers `signaled`/`cancelled`/...) · `feedOutput(key: u64, bytes: []const u8)` (raw collect-stdout append, no line framing).
|
|
818
|
+
> - Fetch: `pendingFetchAt(index: usize) ?FetchRequest` · `feedResponse(key: u64, status: u16, body: []const u8)` · `feedResponseOutcome(key: u64, outcome: EffectFetchOutcome, status: u16, body: []const u8)` · `feedResponseOutcomeWithMetadata(key: u64, outcome: EffectFetchOutcome, status: u16, body: []const u8, truncated: bool, dropped_before: u32)`.
|
|
819
819
|
> - Files: `pendingFileAt(index: usize) ?FileRequest` · `feedFileResult(key: u64, outcome: EffectFileOutcome, bytes: []const u8)`.
|
|
820
820
|
> - Clipboard: `pendingClipboardAt(index: usize) ?ClipboardRequest` · `feedClipboardResult(key: u64, outcome: EffectClipboardOutcome, text: []const u8)`.
|
|
821
821
|
> - Host commands: `pendingHostAt(index: usize) ?HostRequest` · `feedHostResult(key: u64, ok: bool, bytes: []const u8)`.
|
|
@@ -98,7 +98,7 @@ Logic:
|
|
|
98
98
|
- **Exceptions — `throw`/`try`/`catch`/`finally` as pure control flow.** Inside a core, exceptions are deterministic: `throw` carries a subset VALUE and unwinds to the nearest enclosing `catch` — across helper calls, out of array-method callbacks (a `throw` inside `.map`'s callback exits the whole loop, like JS), through nested `try`s, with `finally` running on every path (fall-through, `return`, `break`/`continue`, and throw alike). The discipline is two rules. First (NS1057): thrown values are kind-tagged subset shapes — throw kind-discriminated records (`throw { kind: "bad_digit", at: i } as ParseError`, where `ParseError` is an interface with a string-literal `kind` field or a `kind`-discriminated union; a single-shape core may also throw a number), and SEVERAL distinct shapes may throw: the checker collects every shape the core throws into its implicit thrown union. The catch binding IS that union — narrow it in place with kind tests, no `as` ceremony: `catch (e) { if (e.kind === "bad_digit") return -e.at; if (e.kind === "io") return e.code; return -1; }` (or `switch (e.kind)` — tsc cannot prove exhaustiveness over the implicit union, so give the switch a `default` or a trailing return). Bare rethrow (`throw e;`) re-raises the bound value — a narrowed arm included — and `catch { ... }` needs no binding; the single-`as` form (`const err = e as ParseError;`) stays legal in single-shape cores (and for a DECLARED union whose arms equal the thrown set — declare `type AppError = ... | ...` and `as AppError` works). What teaches: untagged values in a heterogeneous set, two shapes sharing one `kind` with different payloads, asserting one member shape of a multi-shape core, the binding escaping untyped into a call/store/return, and `throw new Error(...)` (engine error objects carry stack traces with no native layout). Second (NS1058): `finally` never redirects control flow — no `return`/`throw`/`break`-out inside it (JS's own no-unsafe-finally rule; loops fully inside the finally may break within themselves). An UNCAUGHT throw that reaches an exported function's boundary is a defined deterministic panic — exactly where node's process would crash. A throw mid-mutation of an owned array keeps the mutations applied so far, exactly like JS — the catch sees the array as node would.
|
|
99
99
|
- **Local function values — const helpers hoist.** `const scale = (x: number): number => x * 3;` (arrow or `function` expression) hoists to an ordinary module-level fn when it is capture-free (module constants and other const helpers are fine to reference; enclosing locals/params are not — pass them as parameters), fully annotated (every parameter and the return type), and used only by direct calls (`scale(v)`, recursion included) or as an array-method callback (`xs.map(scale)`, comparators included). Everything else teaches NS1054: captures, missing annotations, `let` bindings, returning/storing the value, passing it to your own functions, calling through a record field. Capturing a locally-owned array also ENDS its ownership at the capture (a later mutation is the NS1051 teach) — the stored closure would retain the reference.
|
|
100
100
|
|
|
101
|
-
Not yet in v1 — genuine roadmap deferrals, each stopping with a loud, tailored NS9001 naming the rewrite (never missing basic syntax; the banned-with-a-rule families live in "What the subset means" above): `.toSorted()`/`.sort()` without a comparator (JS ToString ordering; pass `(a, b) => a - b`), `.reduce` without an initial value (a taught NS1007 — JS throws on an empty array) or with an index parameter (use a classic loop), `.indexOf`/`.includes` on record arrays (match a field with `.find`/`.findIndex`), `.join` on number arrays (elements are float-valued; join byte values instead), float values (`/`, `**`, `Math.round`, `Math.sqrt`, float `Math.floor`-family results) where an integer is required such as an index (a taught NS1016 — those values can be fractional or NaN), Math methods beyond the batch above, `Number` methods beyond the three classifiers, float-valued template holes (JS float-to-string fidelity is a runtime v2 surface), arrays of unions (`readonly View[]`) or arrays of byte-strings (`readonly Uint8Array[]`) as model fields (wrap the element in a single-field interface), record payloads on `Cmd.request` results (results and errors arrive as one bytes payload; the record-shaped results are `Cmd.fetch`'s `{ status, body }` arm, `Cmd.spawn`'s collect `{ code, output }` arm, and the fixed audio event arm),
|
|
101
|
+
Not yet in v1 — genuine roadmap deferrals, each stopping with a loud, tailored NS9001 naming the rewrite (never missing basic syntax; the banned-with-a-rule families live in "What the subset means" above): `.toSorted()`/`.sort()` without a comparator (JS ToString ordering; pass `(a, b) => a - b`), `.reduce` without an initial value (a taught NS1007 — JS throws on an empty array) or with an index parameter (use a classic loop), `.indexOf`/`.includes` on record arrays (match a field with `.find`/`.findIndex`), `.join` on number arrays (elements are float-valued; join byte values instead), float values (`/`, `**`, `Math.round`, `Math.sqrt`, float `Math.floor`-family results) where an integer is required such as an index (a taught NS1016 — those values can be fractional or NaN), Math methods beyond the batch above, `Number` methods beyond the three classifiers, float-valued template holes (JS float-to-string fidelity is a runtime v2 surface), arrays of unions (`readonly View[]`) or arrays of byte-strings (`readonly Uint8Array[]`) as model fields (wrap the element in a single-field interface), record payloads on `Cmd.request` results (results and errors arrive as one bytes payload; the record-shaped results are `Cmd.fetch`'s buffered `{ status, body }` arm, `Cmd.spawn`'s collect `{ code, output }` arm, and the fixed audio event arm), a collect spawn's stderr tail (v1 delivers the exit code and stdout; stderr is not surfaced — put diagnostics on stdout or check the code), per-line truncation flags (a stdout or response line over its configured bound arrives cut, without a flag), and non-timer subscriptions (`Sub.timer` is the one subscription; one-shot needs are `Cmd.delay`, and process/fetch/audio streams are Cmd-initiated, not subscribed).
|
|
102
102
|
|
|
103
103
|
## Effects are Cmd data
|
|
104
104
|
|
|
@@ -128,7 +128,7 @@ The command set (Cmd wire format v3):
|
|
|
128
128
|
- `Cmd.now("tick")` — request a timestamp; the runtime dispatches the named Msg arm with the time (ms) as its payload. The target arm must carry exactly one number field (`{ kind: "tick", at: number }`), and tsc checks that for you.
|
|
129
129
|
- `Cmd.host(name, ...args)` — a fire-and-forget host command by literal name; the host decides what the name means. Args are numbers, OR exactly one bytes payload: a `Uint8Array` (`Cmd.host("clipboard.write", model.draft)`) or a flat inline record of number/boolean/`Uint8Array` fields (`Cmd.host("cfg.save", { gain: model.gain, on: model.muted, label: asciiBytes("main") })`) — the record lowers to one bytes payload from your types at build time, byte-identical under node and native. Anything else (a smuggled string, a nested record, a payload plus extra args) is a taught error (NS1020/NS1026).
|
|
130
130
|
- `Cmd.request(name, payload, { key?, ok, err })` — a routed host command: the host performs `name` with the payload (same bytes/record rules) and dispatches exactly one result back to you as an ordinary Msg — the `ok` arm with the result bytes on success, or the `err` arm with the error bytes on failure. Both arms must carry exactly one `Uint8Array` field (`{ kind: "loaded", body: Uint8Array }`), checked by tsc and taught by NS1027. The routing is data — string-literal arm names, never callbacks — so the result decoder derives from your Msg types at build time. The optional `key` (a string literal) names the in-flight effect: issuing a request whose key is already in flight replaces it (the old result is dropped), which is the debounce/exactly-one-in-flight discipline.
|
|
131
|
-
- `Cmd.cancel(key)` — drop the in-flight keyed effect with that key, silently: a cancelled request, named engine op (`readFile`/`writeFile`/`fetch`/`clipboardRead`), or armed delay dispatches NEITHER arm — its result is simply dropped.
|
|
131
|
+
- `Cmd.cancel(key)` — drop the in-flight keyed effect with that key, silently: a cancelled request, buffered named engine op (`readFile`/`writeFile`/`fetch`/`clipboardRead`), or armed delay dispatches NEITHER arm — its result is simply dropped. Live spawn and streaming-fetch operations are the exceptions: cancel ends the stream and its `err` arm dispatches with `cancelled`, loud because an app may already have handled earlier stream messages.
|
|
132
132
|
- `Cmd.batch([a, b])` — several commands from one dispatch, performed in order.
|
|
133
133
|
|
|
134
134
|
### The named engine ops
|
|
@@ -137,7 +137,7 @@ These map directly onto the host's effect engine — files, HTTP, the clipboard,
|
|
|
137
137
|
|
|
138
138
|
- `Cmd.readFile(path, { key?, ok, err })` — read a whole file. `ok` arm: one `Uint8Array` field with the content. `err` reasons: `not_found`, `io_failed`, `truncated` (the file exceeds the engine's 1 MiB read bound — a cut file never passes as whole), `rejected`. Paths are at most 1024 bytes.
|
|
139
139
|
- `Cmd.writeFile(path, bytes, { key?, ok, err })` — write a whole file (parent directories created, an existing file replaced whole; at most 1 MiB). `ok` arm: NO payload fields (`{ kind: "wrote" }`) — a successful write has nothing to report. `err` reasons: `io_failed`, `rejected`.
|
|
140
|
-
- `Cmd.fetch({ url, method?, headers?, body?, timeoutMs? }, { key?, ok, err })` — a buffered HTTP(S) exchange. `ok` arm: exactly two fields, one `number` and one `Uint8Array` (`{ kind: "fetched", status: number, body: Uint8Array }`) — matched by type, so the names are yours. The status is the real HTTP status: a 404 is still `ok` (an HTTP-level error is a delivered response). `err` reasons: `connect_failed`, `tls_failed`, `protocol_failed`, `timed_out`, `rejected`, and `truncated` (the body exceeded the engine's 256 KiB buffered bound — never delivered silently cut). The spec is an inline object: `url` bytes (≤ 2 KiB), `method` one of `"GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD"` (default GET), `headers` an inline flat record — names are compile-time ASCII, values are string literals OR runtime bytes (`{ authorization: bearerToken(model.apiKey), "content-type": "application/json" }` — how a launch-supplied key rides an `Authorization` header; ≤ 8 headers, ≤ 1 KiB total, NS1029/NS1030), `body` bytes (≤ 64 KiB), `timeoutMs` a positive integer literal (engine default when omitted).
|
|
140
|
+
- `Cmd.fetch({ url, method?, headers?, body?, timeoutMs? }, { key?, ok, err })` — a buffered HTTP(S) exchange. `ok` arm: exactly two fields, one `number` and one `Uint8Array` (`{ kind: "fetched", status: number, body: Uint8Array }`) — matched by type, so the names are yours. The status is the real HTTP status: a 404 is still `ok` (an HTTP-level error is a delivered response). `err` reasons: `connect_failed`, `tls_failed`, `protocol_failed`, `timed_out`, `rejected`, and `truncated` (the body exceeded the engine's 256 KiB buffered bound — never delivered silently cut). The spec is an inline object: `url` bytes (≤ 2 KiB), `method` one of `"GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD"` (default GET), `headers` an inline flat record — names are compile-time ASCII, values are string literals OR runtime bytes (`{ authorization: bearerToken(model.apiKey), "content-type": "application/json" }` — how a launch-supplied key rides an `Authorization` header; ≤ 8 headers, ≤ 1 KiB total, NS1029/NS1030), `body` bytes (≤ 64 KiB), `timeoutMs` a positive integer literal (engine default when omitted).
|
|
141
141
|
- `Cmd.clipboardWrite(bytes)` — put bytes on the system clipboard, fire-and-forget: there is no routing, and a refused or over-bound write is dropped by design.
|
|
142
142
|
- `Cmd.clipboardRead({ key?, ok, err })` — read the clipboard. `ok` arm: one `Uint8Array` field with the text. `err` reasons: `failed` (no clipboard service, over-bound content, pasteboard error), `rejected`.
|
|
143
143
|
- `Cmd.showNotification({ title, subtitle?, body? })` — request a desktop notification, fire-and-forget: `title` is required bytes (1–128), `subtitle` optional bytes (up to 128), and `body` optional bytes (up to 1024). The host validates all fields before entering the platform service; invalid or unavailable requests fail closed, and Focus / Do Not Disturb and user settings remain authoritative after acceptance. Fake execution and session replay never display one.
|
|
@@ -145,18 +145,21 @@ These map directly onto the host's effect engine — files, HTTP, the clipboard,
|
|
|
145
145
|
|
|
146
146
|
One honesty note on `Cmd.persist()`: it compiles and encodes, but no shipping host implements the persist verb yet, so the checker teaches NS1028 as a WARNING (never failing the build). Persist real state with `Cmd.writeFile` and load it back with `Cmd.readFile` from `initialModel`'s boot command — the pattern every real app uses.
|
|
147
147
|
|
|
148
|
-
### The streaming ops: spawn, audio, and channels
|
|
148
|
+
### The streaming ops: fetch, spawn, audio, and channels
|
|
149
149
|
|
|
150
|
-
|
|
150
|
+
Four effect families deliver MANY results from one command — a keyed stream the app opens imperatively and drives (this is the opposite of `Sub`: a Sub is declared from the model and the host reconciles it; a stream is a `Cmd` with a lifecycle you cancel or stop). Routing still follows the `Cmd.request` rules: string-literal arm names, shapes checked by tsc and taught by NS1027.
|
|
151
151
|
|
|
152
|
+
- `Cmd.fetch({ url, method?, headers?, body?, timeoutMs?, maxLineBytes? }, { key?, line, ok, err })` — line-stream an HTTP(S) response. Each complete response line dispatches `line` as one `Uint8Array` field, so SSE and NDJSON parsers can update the Model incrementally. Exactly ONE terminal follows: a delivered, lossless response (non-2xx included) dispatches `ok` as one number field carrying the HTTP status; a cut/dropped line dispatches `err: truncated`, and transport failure, timeout, rejection, or cancellation dispatches `err` with that reason. `maxLineBytes` raises the 4 KiB per-line default up to 256 KiB for large event records; the per-line truncation flag is not exposed directly because any such loss makes the terminal loud. A duplicate live key is rejected rather than replaced so two responses cannot splice into one logical stream; `Cmd.cancel(key)` ends it loudly through `err: cancelled`.
|
|
152
153
|
- `Cmd.spawn(argv, { key?, stdin?, line?, exit, err })` — run a subprocess, streaming stdout line by line. `argv` is an inline array literal of bytes elements (`[asciiBytes("/bin/ps"), asciiBytes("-axo")]`, at most 16 elements, 2 KiB total; the array shape is NS1029, the bounds NS1030), and `stdin` (optional bytes, ≤ 4 KiB) is written to the child once. Each stdout line dispatches the `line` arm (one `Uint8Array` field) as it arrives, across dispatches; omit `line` to drop lines (an exit-only spawn, e.g. piping stdin to `pbcopy`). Exactly ONE terminal ends the stream: a clean exit dispatches the `exit` arm — one number field carrying the exit code (a non-zero code is still `exit`: the process ran; its failure code is yours to read) — and every other end dispatches `err` with the reason bytes: `signaled`, `cancelled`, `rejected` (a duplicate live key, or dynamic argv/stdin the engine refused), `spawn_failed` (the binary could not start). Lines over the engine's 4 KiB line bound arrive cut.
|
|
153
154
|
- `Cmd.spawn(argv, { key?, stdin?, collect: true, exit, err })` — the same child, whole stdout buffered instead of streamed (the system-monitor shape: run `ps`, parse the block). No `line` arm (NS1027 teaches the conflict). The `exit` arm is a two-field record — one number field (the exit code) and one `Uint8Array` field (the collected stdout, up to 512 KiB), matched by type like `Cmd.fetch`'s arm. Collected stdout over the bound routes `err` with `truncated` — a cut block never parses as whole.
|
|
154
|
-
- `Cmd.cancel(key)` aimed at a live spawn ends the child mid-stream; the stream's `err` arm dispatches with `cancelled` — loud on purpose, because killing a process is an observable event (the contrast with
|
|
155
|
+
- `Cmd.cancel(key)` aimed at a live spawn ends the child mid-stream; the stream's `err` arm dispatches with `cancelled` — loud on purpose, because killing a process is an observable event (the contrast with buffered named ops, whose cancel is silent). Spawn keys share streaming fetch's duplicate discipline: a spawn whose key is already streaming is rejected (`err` gets `rejected`), never replaced — a running subprocess is never killed implicitly; cancel it first.
|
|
155
156
|
- `Cmd.audioPlay(key, { path?, url?, cachePath?, expectedBytes? }, { event })` — open the audio event stream. One player is the whole surface, so a new `audioPlay` always REPLACES the current playback (the one key-reuse exception besides `Cmd.request`). The source cascade is the engine's: the local `path` is tried first, a missing file falls through to `url` (streamed progressively, cached at `cachePath` when given, integrity-gated by `expectedBytes` — omitted/0 means unknown size). At least one of `path`/`url` is required (NS1029); each is bytes, at most 1 KiB (NS1030). Prefer OMITTING `cachePath` for URL sources: when the app wiring configures a caches directory (`TsUiApp`'s `audio_cache_dir`), the host derives the conventional content-addressed cache path from the URL itself — your update never builds filesystem paths, and replay re-derives the same path by construction. Pass `cachePath` only to override that convention.
|
|
156
157
|
- The `event` arm is the one SDK-fixed record shape, six fields matched by NAME: `state` (the `AudioState` string-literal union — import it from `@native-sdk/core/events`, or declare an alias with exactly the members `"loaded" | "position" | "completed" | "failed" | "rejected" | "spectrum"` in any order; the runtime matches members by name), `positionMs: number`, `durationMs: number` (milliseconds; the duration is the player's estimate), `playing: boolean`, `buffering: boolean` (true while a streamed url is stalled waiting for bytes), and `bands: Uint8Array` (the 32 spectrum band magnitudes, 0–255 each, all zeros outside `"spectrum"` events). Every playback event dispatches this arm — `"failed"` (unplayable source, decode/device failure) and `"rejected"` (an empty or over-long source) included, so failure is never silence — until `Cmd.audioStop` closes the stream. `"completed"` fires once at the natural end and does NOT close the stream: starting the next track from it is the idiom.
|
|
157
158
|
- `Cmd.audioPause(key)` / `Cmd.audioResume(key)` / `Cmd.audioStop(key)` / `Cmd.audioSeek(key, ms)` / `Cmd.audioSetVolume(key, volume)` — fire-and-forget control verbs: no result of their own; their consequences arrive on the event stream (`audioResume` on a dead player reports one `"failed"` event, never silence). A verb whose key names no open stream is a no-op. `audioStop` is the audio stream's close — no events for the key after it (`Cmd.cancel` does not apply to audio). Volume is clamped 0..1 and remembered across tracks; a literal outside 0..1 (or a negative seek literal) stops the build (NS1030).
|
|
158
159
|
- `Cmd.channelOpen(key, { event })` — open an EXTERNAL-SOURCE channel under the app's numeric key: the host stages a long-lived, thread-safe posting seam its NATIVE side feeds — embedders and platform-services extensions post bytes from their own threads (sockets, watchers, workers), and each accepted post dispatches the `event` arm as one `"data"` event. Posting is deliberately not a TS verb — compiled cores are single-threaded, so the TS tier opens, closes, and receives while the posting handle lives on the native side (`Effects.channelHandle(key)`). `key` may be any number expression, a positive integer below 2^53 (a certain-to-be-refused literal stops the build, NS1030). The `event` arm is a five-field record matched by NAME: `key` (the channel key echoed verbatim, so concurrent channels sharing one arm stay distinguishable; a key the wire cannot carry exactly echoes 0), `state` (the `ChannelState` union — import it from `@native-sdk/core` or declare an alias with exactly the three members `"data" | "closed" | "rejected"` in any order; checked BOTH directions, since a narrower union would silently drop states the host emits), `bytes` (`Uint8Array` — the post's payload on `"data"` events, empty otherwise), and `droppedPending`/`droppedTotal` (numbers — the honest back-pressure counters: posts the native handle refused since the previous delivered event, and over the channel's whole life; refused posts count, never silence). One channel per key at a time — a duplicate live key dispatches `"rejected"` — and the key shares the engine's effect-key space (a same-key fetch is blocked while the channel lives). No timer polling anywhere: the source wakes the loop itself. Channel events journal at the effect boundary, so recorded sessions replay the whole stream from the journal — the native posting side is never needed at replay (a native producer that consults `ChannelHandle.live()` before launching keeps replay fully offline; one that launches unconditionally is stopped at its first post, which answers `.closed`).
|
|
159
160
|
- `Cmd.channelClose(key)` — close the open channel under the key, if any: staged posts flush, exactly one `"closed"` event (final drop totals aboard) dispatches the event arm, and the key frees. A key with no open channel no-ops.
|
|
161
|
+
- `Cmd.audioCaptureStart(key, { source, sampleRate?, channels? }, { event })` — start a native `"microphone"` or `"system"` audio stream. The host converts into interleaved signed-16 little-endian PCM at 16/24/48 kHz and mono/stereo (default 48 kHz mono), in chunks no larger than 20 ms. The ten-field event arm is matched by NAME: `key`, `state` (exactly `"started" | "data" | "failed" | "stopped" | "rejected"`), `source` (exactly `"microphone" | "system"`), `sampleRate`, `channels`, `timestampMs`, `frames`, `pcm`, `droppedPending`, and `droppedTotal`. PCM is dispatch-lifetime bytes; the commit walker copies it when stored in the model. The bounded queue, wake behavior, drop accounting, journaling, and offline replay are the channel transport's. Microphone and system may run concurrently; a second start for one source replaces that source's prior key.
|
|
162
|
+
- `Cmd.audioCaptureStop(key)` — synchronously quiesce native callbacks, flush already accepted chunks, deliver exactly one `"stopped"` terminal, and free the key. The key remains occupied until that terminal is delivered, so wait for `"stopped"` before reusing it; an earlier restart is rejected. A missing key no-ops. Declare `"microphone"` and/or `"system_audio"` in `app.zon` permissions so macOS dev executables and packaged apps carry the required usage descriptions.
|
|
160
163
|
- `Cmd.imageLoad(id, { path?, url?, cachePath?, expectedBytes? }, { event })` — load an image at runtime under the model-owned NUMERIC ImageId your markup binds (`<image image="{cover}"/>`, `<avatar image="{avatar}"/>`); `id` may be any number expression (ids are model data), a positive integer below 2^53 (a certain-to-be-refused literal like 0 stops the build, NS1030). The source cascade is `audioPlay`'s exactly: local `path` first, a missing file falls through to `url` (fetched whole, installed at the cache path and integrity-gated by `expectedBytes`); at least one of `path`/`url` (NS1029), and prefer OMITTING `cachePath` — the wiring's caches directory (`TsUiApp`'s `image_cache_dir`) derives the content-addressed path from the URL. Exactly ONE `event` arm dispatches per load — a five-field record matched by NAME: `id` (the requested ImageId echoed verbatim, so concurrent loads sharing one arm stay distinguishable; an id the wire cannot carry exactly echoes 0), `state` (the `ImageState` union — exactly the fifteen members `"loaded" | "rejected" | "not_found" | "io_failed" | "connect_failed" | "tls_failed" | "protocol_failed" | "timed_out" | "http_status" | "cancelled" | "too_large" | "unsupported" | "decode_failed" | "registry_full" | "alloc_failed"`, any order; `"alloc_failed"` is resource exhaustion at registration — the host refused the memory, the bytes may be fine, retry when memory frees), `width`/`height` (the decoded dimensions on `"loaded"`, 0 otherwise), and `status` (the HTTP status for url loads that performed an exchange; 0 when none occurred — local paths, cache hits — so a cached `"loaded"` is distinguishable from a network one). On `"loaded"` the pixels are already registered under the id — store the id in the model then (the store-on-success discipline keeps a fallback rendering until the load lands). One load per id at a time: a duplicate live id dispatches `"rejected"` (the spawn discipline — a load in flight is never replaced implicitly), and image loads are not the string-keyed `Cmd.cancel`'s to end — `Cmd.imageCancel(id)` is their cancel, LOUD like spawn's: the one terminal still arrives as the event arm's `"cancelled"`, and the id frees for a fresh load once it lands (an id with no live load no-ops; the same NS1030 literal gate as `imageLoad`). Decode limits are the registered-image limits (16 slots, 1 MiB decoded pixels — avatar/cover scale, not photo scale); the encoded source bound is 1.25 MiB, and over-bound sources fail whole with `"too_large"`, never cut. `Cmd.imageUnregister(id)` releases a loaded image's registry slot — the gallery eviction move when the 17th distinct image would answer `"registry_full"`: views bound to the id fall back, and the slot accepts the next load. Unregister is synchronous registry surgery, NOT an effect — no result Msg, an unregistered id no-ops (the same NS1030 literal gate) — and it frees only the CURRENT registration: a load in flight under the id still registers at its terminal, so cancel the load first (`Cmd.imageCancel`) to keep the slot free.
|
|
161
164
|
|
|
162
165
|
### The window verbs
|
|
@@ -205,7 +208,7 @@ export function subscriptions(model: Model): Sub<Msg> {
|
|
|
205
208
|
|
|
206
209
|
Sub values follow the Cmd purity rule with their own home (NS1025): built inline in `subscriptions`' return path, never stored, never returned from anywhere else. Debounced re-arm falls out of reconciliation — change the key or interval and the timer re-arms; drop it from the set and it stops.
|
|
207
210
|
|
|
208
|
-
Keep the Sub-vs-stream line straight: a Sub is DECLARATIVE — derived from the model, started and stopped by reconciliation, and the app never opens or closes one. The multi-result streams (`Cmd.spawn`'s lines, `Cmd.audioPlay`'s events) are Cmd-INITIATED — imperative opens with a keyed lifecycle the app drives (`Cmd.cancel` for spawn, `Cmd.audioStop` for
|
|
211
|
+
Keep the Sub-vs-stream line straight: a Sub is DECLARATIVE — derived from the model, started and stopped by reconciliation, and the app never opens or closes one. The multi-result streams (`Cmd.fetch`'s response lines, `Cmd.spawn`'s stdout lines, `Cmd.audioPlay`'s events, `Cmd.channelOpen`'s posts, and audio capture chunks) are Cmd-INITIATED — imperative opens with a keyed lifecycle the app drives (`Cmd.cancel` for fetch/spawn, `Cmd.audioStop` for playback, `Cmd.channelClose` for external channels, and `Cmd.audioCaptureStop` for capture). If the effect should exist exactly while some model state holds, it wants a Sub shape; if the app decides when it starts and ends, it is a stream.
|
|
209
212
|
|
|
210
213
|
One caveat for node-side pokes: the build resolves the `@native-sdk/core*` specifiers for you, but plain `node` does not know them, so quick behavioral checks under node work directly on cores with no SDK import, and on cores importing `Cmd`, `Sub`, `asciiBytes`, or the text engine only with a module mapping (or by copying the SDK module files next to the core and rewriting the specifiers). `native dev --core` already maps them.
|
|
211
214
|
|
|
@@ -218,9 +221,9 @@ One caveat for node-side pokes: the build resolves the `@native-sdk/core*` speci
|
|
|
218
221
|
- **Everything module-level is importable**: interfaces, literal-union aliases, discriminated unions, module `const` numbers and tables, and helper functions all cross files (renamed imports and `import * as ns` namespace aliases both work — the alias is dot-syntax over the same flat namespace, never a value of its own). Export lists and value re-exports work too: `export { helper, doneCount as remaining }` binds names over existing declarations, and `export { parsePs } from "./parsers.ts"` forwards another module's export by name (a renamed binding emits as a flat-namespace alias). Type names and EXPORTED value names must be unique across the core's files (NS1038 - declare once, import where used; renamed exports claim their new names in the same namespace); colliding PRIVATE helpers are fine (the compile uniques them per module).
|
|
219
222
|
- **No runtime import cycles** (NS1036). `import type` back-edges are legal and idiomatic: a helper module type-imports `Model` from `./core.ts` while `core.ts` runtime-imports the helpers - that is the expected shape, not a smell.
|
|
220
223
|
- **The entry contract (NS1014)**: `update`, `initialModel`, `subscriptions`, the wiring channels (`commandMsg`/`keyMsg`/`frameMsg`/`pinchMsg`/`dropMsg`/`appearanceMsg`/`chromeMsg`/`envMsgs`), and `viewUnbound` are DECLARED in `core.ts` and exported under their own names (`export` on the declaration or an un-renamed `export { update }` list entry — a rename or a re-export from an imported module cannot bind an entry point) - imports may FEED them, never replace them. The markup binding surface is also entry-only: an exported single-Model-parameter helper binds (`{doneCount}`) only when it is DECLARED in `core.ts` — export lists participate under their exported names (`export { taskTotal as taskCount }` binds `{taskCount}`), but a re-export of an imported helper does not bind (under node the app's module object is the entry's exports, so it would bind natively but not exist under node). Imported modules export cross-module API for update and the entry helpers to call.
|
|
221
|
-
- **SDK library modules**: `@native-sdk/core/text` ships the byte-splice text engine - `applyTextInputEvent(state, event, capacity)` / `clampedInsertEvent` over `TextEditState` (the full caret/word/selection/IME reducer for markup text controls), plus `containsIgnoreCase`, `orderIgnoreCase`, and `trimAsciiSpaces`. `@native-sdk/core/events` ships the canonical event record types (`TextInputEvent` re-exported, `ScrollState`, `FrameEvent`, `KeyEvent`, `PinchEvent`, `FileDropEvent`, `ColorScheme`/`AppearanceEvent`, `ChromeInsets`/`ChromeButtons`/`ChromeEvent`, `AudioState`/`AudioEvent`) so no core re-types the vocabulary. Unlike `@native-sdk/core` (intrinsic, never compiled into the core) these are ordinary subset TypeScript, compiled INTO your core when imported and absent when not. Under node they resolve like the core module itself. One namespace rule to know (NS1038): module-scope names are unique across the whole import graph, so a core that imports an SDK event type deletes its own in-file mirror of that name.
|
|
224
|
+
- **SDK library modules**: `@native-sdk/core/text` ships the byte-splice text engine - `applyTextInputEvent(state, event, capacity)` / `clampedInsertEvent` over `TextEditState` (the full caret/word/selection/IME reducer for markup text controls), plus `containsIgnoreCase`, `orderIgnoreCase`, and `trimAsciiSpaces`. `@native-sdk/core/events` ships the canonical event record types (`TextInputEvent` re-exported, `ScrollState`, `FrameEvent`, `KeyEvent`, `PinchEvent`, `FileDropEvent`, `ColorScheme`/`AppearanceEvent`, `ChromeInsets`/`ChromeButtons`/`ChromeEvent`, `AudioState`/`AudioEvent`, `AudioCaptureState`/`AudioCaptureSource`/`AudioCaptureEvent`) so no core re-types the vocabulary. Unlike `@native-sdk/core` (intrinsic, never compiled into the core) these are ordinary subset TypeScript, compiled INTO your core when imported and absent when not. Under node they resolve like the core module itself. One namespace rule to know (NS1038): module-scope names are unique across the whole import graph, so a core that imports an SDK event type deletes its own in-file mirror of that name.
|
|
222
225
|
|
|
223
|
-
The reference splits are `examples/soundboard-ts` (core.ts + library.ts + player.ts + the SDK text engine), `examples/system-monitor-ts` (core.ts + parsers.ts + table.ts + the SDK text engine), and `examples/
|
|
226
|
+
The reference splits are `examples/soundboard-ts` (core.ts + library.ts + player.ts + the SDK text engine), `examples/system-monitor-ts` (core.ts + parsers.ts + table.ts + the SDK text engine), and `examples/chatbot` (core.ts + api.ts — the JSON-over-bytes wire-format reference: request encoding and a targeted parse walk that returns `null` on anything malformed) in the SDK repo.
|
|
224
227
|
|
|
225
228
|
## Text is bytes
|
|
226
229
|
|
|
@@ -264,7 +267,7 @@ The stays-out tail teaches by name (NS1060 unless noted): `charCodeAt`/`charAt`/
|
|
|
264
267
|
|
|
265
268
|
The SDK text helpers remain for what the methods do not cover: `containsIgnoreCase` (ASCII case-insensitive search) and `orderIgnoreCase` (an ASCII case-insensitive `.toSorted` comparator) from `@native-sdk/core/text`. `trimAsciiSpaces` also stays, but it is NOT `.trim()`: it strips space/tab/CR only — never LF — as a no-copy view, which is exactly right for line-oriented parsers where `\n` is the record separator; for user input and general whitespace, `.trim()` is now the canonical form.
|
|
266
269
|
|
|
267
|
-
A freshly created `Uint8Array` is writable until it escapes (stored, returned, passed on); after that it is immutable like everything else. One consequence worth knowing before you build byte output: a buffer PASSED to a helper has escaped, so a writing helper cannot take an out-parameter — build bytes with measure-then-fill inside one function (count the output length, allocate exactly it, write inline), or build a `Uint8Array[]` push-builder of parts and concatenate once (`examples/
|
|
270
|
+
A freshly created `Uint8Array` is writable until it escapes (stored, returned, passed on); after that it is immutable like everything else. One consequence worth knowing before you build byte output: a buffer PASSED to a helper has escaped, so a writing helper cannot take an out-parameter — build bytes with measure-then-fill inside one function (count the output length, allocate exactly it, write inline), or build a `Uint8Array[]` push-builder of parts and concatenate once (`examples/chatbot/src/api.ts` does both, JSON escaping included). `===` on two `Uint8Array` values is banned (it would be JS reference identity, which has no native mapping) — compare an id field, or contents with a loop (`s.startsWith(t) && s.length === t.length` is the whole-equality idiom). `bytes.join("-")` renders byte values as decimal text with a literal separator (arena bytes, same result under node); number arrays have no `.join` because their elements are float-valued.
|
|
268
271
|
|
|
269
272
|
## Text input from markup
|
|
270
273
|
|
|
@@ -322,7 +325,7 @@ The generated wiring detects each channel from an export (export exists → wire
|
|
|
322
325
|
- **`dropMsg(drop: FileDropEvent): Msg | null`** — native file drops after widget routing. `FileDropEvent` is exactly `{ windowId; viewLabel; point; paths }`: `point` is `{ x; y } | null`, and `paths` is `readonly Uint8Array[]` so arbitrary UTF-8 filesystem names remain byte text. Return null to ignore the drop or map it to any ordinary Msg.
|
|
323
326
|
- **`export const appearanceMsg = "<arm>"`** — system appearance changes dispatch the named arm, a record of exactly `{ colorScheme: ColorScheme; reduceMotion: boolean; highContrast: boolean }` where `ColorScheme` is a NAMED `"light" | "dark"` alias (routing is data: a string-literal arm name, the effects rule applied to the app shell).
|
|
324
327
|
- **`export const chromeMsg = "<arm>"`** — window-chrome geometry (the hidden-titlebar channel), a record of exactly `{ insets: { top; right; bottom; left }; buttons: { x; y; width; height }; tabsProjected: boolean }` (numbers/boolean). Delivered before the first view build and again on changes.
|
|
325
|
-
- **`export const envMsgs = [{ env: "NAME", msg: "<arm>" }] as const`** — each named environment variable present at launch dispatches its value through the arm (exactly one `Uint8Array` field, `BytesKind` — annotate with `readonly EnvMsg<Msg>[]` from the SDK for tsc checking) as one journaled Msg right after the boot command. The core never reads the environment (NS1005), and neither does replay: the deliveries are journaled at record time and fed back from the journal, so a recording replays byte-identically even when
|
|
328
|
+
- **`export const envMsgs = [{ env: "NAME", msg: "<arm>" }] as const`** — each named environment variable present at launch dispatches its value through the arm (exactly one `Uint8Array` field, `BytesKind` — annotate with `readonly EnvMsg<Msg>[]` from the SDK for tsc checking) as one journaled Msg right after the boot command. The generated runner also synthesizes the reserved `NATIVE_SDK_APP_DATA_DIR` value from `native_sdk.app_dirs` when requested here; use it as the root for durable `Cmd.writeFile`/`Cmd.readFile` paths instead of relying on the package's process working directory. The core never reads the environment (NS1005), and neither does replay: the deliveries are journaled at record time and fed back from the journal, so a recording replays byte-identically even when ambient variables are unset or changed at replay launch.
|
|
326
329
|
- **`app.zon .assets.images`** — `.assets = .{ .images = .{ .{ .id = 1, .path = "assets/art/cover.jpg" }, ... } }`: each file is read once at launch and registered on the installing frame; the `id` is the `ImageId` markup avatar bindings reference (`<avatar image="{coverId}">`), and a missing file or failed decode keeps the initials fallback.
|
|
327
330
|
|
|
328
331
|
## The rules the checker enforces
|
|
@@ -466,7 +469,7 @@ export function update(model: Model, msg: Msg): Model {
|
|
|
466
469
|
|
|
467
470
|
## Running a core as an app
|
|
468
471
|
|
|
469
|
-
A `native init` app needs NONE of this section: the build detects `src/core.ts` and stages the wiring itself (a core exporting `commandMsg(name: string): Msg | null` automatically receives menu/shortcut command events as Msgs). The section below is for hand-Zig wiring — embedding a core in an existing Zig app or customizing the UiApp surface.
|
|
472
|
+
A `native init` app needs NONE of this section: the build detects `src/core.ts` and stages the wiring itself (a core exporting `commandMsg(name: string): Msg | null` automatically receives menu/shortcut command events as Msgs). A core can also export `themePack(model: Model): ThemePack`, with `export type ThemePack = "house" | "geist"`, to select the built-in pack from live model state; the adapter wires it as the stock theme's pack axis while system scheme/contrast/motion, manifest accent, and surface scale remain runtime-owned. The section below is for hand-Zig wiring — embedding a core in an existing Zig app or customizing the UiApp surface.
|
|
470
473
|
|
|
471
474
|
The compiled core runs as a full desktop app through `native_sdk.TsUiApp(core)` — the committed TS model IS the app model, no shim, no glue:
|
|
472
475
|
|
|
@@ -486,7 +489,7 @@ var app = Adapter.init(allocator, .{ .audio_cache_dir = resolved_cache_dir }, .{
|
|
|
486
489
|
});
|
|
487
490
|
```
|
|
488
491
|
|
|
489
|
-
- `update`/`update_fx`/`init_fx` belong to the adapter (it runs your `initialModel`, `update`, and `subscriptions` through the effect bridge), and the adapter wires `on_command`/`on_key`/`on_pinch`/`on_drop`/`on_appearance`/`on_chrome`/`on_frame` from the core's channel exports automatically (
|
|
492
|
+
- `update`/`update_fx`/`init_fx` belong to the adapter (it runs your `initialModel`, `update`, and `subscriptions` through the effect bridge), and the adapter wires `on_command`/`on_key`/`on_pinch`/`on_drop`/`on_appearance`/`on_chrome`/`on_frame` from the core's channel exports automatically. It likewise wires `theme_fn` from an exported `themePack(model)` helper. A wiring that also sets one of those seams is a teaching panic. Everything else is ordinary wiring: `tokens_fn`/`windows_fn` derive from `*const core.Model`, and `CoreOptions` carries the adapter-owned knobs (`audio_cache_dir`, `boot_images`, `env_values`).
|
|
490
493
|
- Markup binds your model's field names EXACTLY as you wrote them: `nextId` binds as `{nextId}` (the core's model keeps the TS spellings). Record arrays iterate with `<for each="tasks" as="t" key="id">` and items bind their fields (`{t.title}`); optional scalars gate with `<if test="{selected}">` (null is falsy); string-literal unions bind as their member name (`{filter}` renders `all` — compare against a quoted literal, `selected="{sortKey == 'cpu'}"`); exported single-model helpers bind as derived values (`{doneCount}`) and slice-returning ones drive `for each`. Markup `<chart>` series bind number arrays too — `<series kind="bar" values="{cpuSpark}" />` over a field or helper returning `readonly number[]` (f64, narrowed per sample into the chart pipeline); pad a filling window's leading gap with `NaN` samples, which draw nothing.
|
|
491
494
|
- `Options.sync` does not exist for TS apps (a committed model cannot be mutated in place): keep continuous controls model-driven — bind the widget's value and echo `on-change`/`on-scroll` Msgs back into the model.
|
|
492
495
|
- One live app per core module per process: two apps over the SAME core would share one committed root — and a process carries ONE compiled core (the archive owns a fixed-prefix C ABI symbol set).
|