@native-sdk/cli 0.8.3 → 0.9.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.
Files changed (188) hide show
  1. package/build/app.zig +905 -61
  2. package/build.zig +674 -373
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +6 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +455 -3
  7. package/packages/core/package-lock.json +11 -11
  8. package/packages/core/package.json +2 -2
  9. package/packages/core/scripts/compiler_typecheck.mjs +116 -15
  10. package/packages/core/scripts/gen_service_surface.mjs +268 -0
  11. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  12. package/packages/core/scripts/run_external_core_compiler.mjs +77 -6
  13. package/packages/core/scripts/run_external_service_compiler.mjs +240 -0
  14. package/packages/core/scripts/stage_external_core.mjs +9 -1
  15. package/packages/core/scripts/stage_external_services.mjs +172 -0
  16. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  17. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  18. package/packages/core/sdk/core.d.ts +214 -2
  19. package/packages/core/sdk/core.ts +715 -42
  20. package/packages/core/sdk/events.d.ts +50 -0
  21. package/packages/core/sdk/events.ts +75 -0
  22. package/packages/core/src/checker.ts +528 -15
  23. package/packages/core/src/cli.ts +143 -3
  24. package/packages/core/src/contract.ts +26 -5
  25. package/packages/core/src/devhost.ts +1849 -18
  26. package/packages/core/src/devhost_journal.mjs +181 -0
  27. package/packages/core/src/devhost_resolver.mjs +17 -1
  28. package/packages/core/src/devhost_service_worker.mjs +90 -0
  29. package/packages/core/src/diagnostics.ts +84 -18
  30. package/packages/core/src/frontend.ts +204 -34
  31. package/packages/core/src/modules.ts +129 -80
  32. package/packages/core/src/service_contract.ts +597 -0
  33. package/packages/core/src/sqlite_cli.ts +93 -0
  34. package/packages/core/src/sqlite_codegen.ts +806 -0
  35. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  36. package/packages/core/src/typed_ast.ts +36 -8
  37. package/skill-data/core/SKILL.md +4 -2
  38. package/skill-data/core/references/project-anatomy.md +3 -2
  39. package/skill-data/core/references/web-engines-packaging-debugging.md +3 -1
  40. package/skill-data/native-ui/SKILL.md +55 -8
  41. package/skill-data/ts-core/SKILL.md +92 -40
  42. package/skill-data/ts-services/SKILL.md +126 -0
  43. package/skill-data/ts-services/references/service-surface.md +603 -0
  44. package/skill-data/zig/SKILL.md +1 -1
  45. package/skills/native-sdk/SKILL.md +1 -1
  46. package/src/app_runner/no_migrations.zig +3 -0
  47. package/src/app_runner/no_services.zig +20 -0
  48. package/src/app_runner/root.zig +104 -4
  49. package/src/app_runner/ts_core_main.zig +268 -4
  50. package/src/automation/snapshot.zig +23 -5
  51. package/src/embed/app_exports.zig +11 -1
  52. package/src/embed/c_api.zig +48 -2
  53. package/src/embed/conversions.zig +4 -5
  54. package/src/embed/host.zig +115 -1
  55. package/src/embed/root.zig +7 -0
  56. package/src/embed/tests.zig +213 -0
  57. package/src/embed/types.zig +51 -0
  58. package/src/embed/ui_host.zig +121 -5
  59. package/src/platform/android/NativeSdkActivity.java +131 -0
  60. package/src/platform/android/android_host.c +182 -1
  61. package/src/platform/android/native_sdk_app.h +17 -0
  62. package/src/platform/ios/native_sdk_app.h +17 -0
  63. package/src/platform/ios/uikit_host.m +115 -0
  64. package/src/platform/linux/cef_host.cpp +1 -1
  65. package/src/platform/linux/gtk_host.c +89 -17
  66. package/src/platform/linux/gtk_host.h +3 -0
  67. package/src/platform/linux/root.zig +41 -18
  68. package/src/platform/macos/appkit_host.h +26 -3
  69. package/src/platform/macos/appkit_host.m +1051 -129
  70. package/src/platform/macos/capture_info_plist.c +25 -0
  71. package/src/platform/macos/cef_host.mm +270 -36
  72. package/src/platform/macos/root.zig +312 -34
  73. package/src/platform/null_platform.zig +281 -19
  74. package/src/platform/null_platform_tests.zig +74 -0
  75. package/src/platform/root.zig +16 -0
  76. package/src/platform/types.zig +279 -15
  77. package/src/platform/windows/root.zig +243 -21
  78. package/src/platform/windows/webview2_host.cpp +464 -46
  79. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  80. package/src/primitives/app_manifest/root.zig +4 -0
  81. package/src/primitives/app_manifest/tests.zig +3 -0
  82. package/src/primitives/app_manifest/types.zig +34 -0
  83. package/src/primitives/app_manifest/validation.zig +19 -1
  84. package/src/primitives/canvas/code_tests.zig +9 -9
  85. package/src/primitives/canvas/events.zig +12 -11
  86. package/src/primitives/canvas/frame.zig +44 -9
  87. package/src/primitives/canvas/icons/mic.svg +1 -0
  88. package/src/primitives/canvas/icons.zig +2 -0
  89. package/src/primitives/canvas/root.zig +8 -0
  90. package/src/primitives/canvas/text_span_tests.zig +39 -0
  91. package/src/primitives/canvas/ui.zig +23 -4
  92. package/src/primitives/canvas/ui_markup.zig +15 -0
  93. package/src/primitives/canvas/ui_markup_compiled.zig +9 -0
  94. package/src/primitives/canvas/ui_markup_compiled_tests.zig +1 -1
  95. package/src/primitives/canvas/ui_markup_tests.zig +5 -0
  96. package/src/primitives/canvas/ui_markup_view.zig +9 -0
  97. package/src/primitives/canvas/ui_markup_view_tests.zig +9 -6
  98. package/src/primitives/canvas/ui_schema.zig +19 -10
  99. package/src/primitives/canvas/ui_schema_tests.zig +5 -3
  100. package/src/primitives/canvas/ui_tests.zig +18 -4
  101. package/src/primitives/canvas/widget_invalidation.zig +9 -2
  102. package/src/primitives/canvas/widget_render.zig +296 -114
  103. package/src/primitives/canvas/widget_runtime_tests.zig +133 -0
  104. package/src/primitives/canvas/widget_text_input.zig +10 -10
  105. package/src/primitives/canvas/widget_tree.zig +1 -1
  106. package/src/primitives/canvas/widgets.zig +29 -5
  107. package/src/root.zig +56 -0
  108. package/src/runtime/api.zig +11 -0
  109. package/src/runtime/automation_snapshot.zig +4 -0
  110. package/src/runtime/automation_widget_dispatch.zig +1 -0
  111. package/src/runtime/bridge_payload.zig +2 -0
  112. package/src/runtime/bridge_permission_tests.zig +23 -2
  113. package/src/runtime/bridge_responses.zig +3 -1
  114. package/src/runtime/canvas_frame.zig +31 -13
  115. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  116. package/src/runtime/canvas_frame_invalidation_tests.zig +35 -10
  117. package/src/runtime/canvas_widget_anchored_tests.zig +83 -0
  118. package/src/runtime/canvas_widget_events.zig +69 -24
  119. package/src/runtime/canvas_widget_runtime.zig +101 -6
  120. package/src/runtime/canvas_widget_scroll_driver_tests.zig +47 -4
  121. package/src/runtime/canvas_widget_scroll_drivers.zig +3 -3
  122. package/src/runtime/canvas_widget_semantics_tests.zig +2 -0
  123. package/src/runtime/canvas_widget_split_tree_tests.zig +228 -0
  124. package/src/runtime/canvas_widget_state.zig +6 -1
  125. package/src/runtime/canvas_widget_text_tests.zig +112 -3
  126. package/src/runtime/clock.zig +13 -1
  127. package/src/runtime/core.zig +133 -1
  128. package/src/runtime/credentials_store.zig +115 -0
  129. package/src/runtime/effects.zig +2568 -75
  130. package/src/runtime/effects_audio_capture_tests.zig +251 -0
  131. package/src/runtime/effects_credentials_tests.zig +332 -0
  132. package/src/runtime/effects_host_tests.zig +208 -1
  133. package/src/runtime/effects_relational_tests.zig +314 -0
  134. package/src/runtime/effects_store_tests.zig +211 -0
  135. package/src/runtime/flow.zig +14 -1
  136. package/src/runtime/gpu_surface_events.zig +6 -1
  137. package/src/runtime/native_command_event_tests.zig +42 -0
  138. package/src/runtime/persist_store.zig +666 -0
  139. package/src/runtime/record_store.zig +788 -0
  140. package/src/runtime/relational_store.zig +854 -0
  141. package/src/runtime/root.zig +52 -0
  142. package/src/runtime/runtime_event_tests.zig +70 -0
  143. package/src/runtime/service_host.zig +711 -0
  144. package/src/runtime/service_pool.zig +1314 -0
  145. package/src/runtime/session_blobs.zig +1 -1
  146. package/src/runtime/session_journal.zig +102 -0
  147. package/src/runtime/session_record.zig +177 -0
  148. package/src/runtime/session_replay.zig +109 -4
  149. package/src/runtime/shell_layout.zig +1 -0
  150. package/src/runtime/shell_layout_tests.zig +120 -0
  151. package/src/runtime/sqlite_engine.zig +474 -0
  152. package/src/runtime/state.zig +6 -0
  153. package/src/runtime/system_services.zig +49 -10
  154. package/src/runtime/tests.zig +5 -0
  155. package/src/runtime/ts_core_host.zig +1189 -118
  156. package/src/runtime/ts_core_host_tests.zig +638 -11
  157. package/src/runtime/ts_ui_app.zig +537 -1
  158. package/src/runtime/ui_app.zig +160 -19
  159. package/src/runtime/ui_app_tests.zig +203 -5
  160. package/src/runtime/validation.zig +22 -0
  161. package/src/runtime/view.zig +11 -0
  162. package/src/runtime/view_widget_scroll.zig +56 -5
  163. package/src/runtime/view_widget_text.zig +24 -5
  164. package/src/runtime/view_widget_tree.zig +1 -1
  165. package/src/runtime/window_storage.zig +1 -0
  166. package/src/runtime/window_view_runtime.zig +2 -3
  167. package/src/runtime/window_views.zig +19 -0
  168. package/src/tooling/android.zig +21 -16
  169. package/src/tooling/db.zig +160 -0
  170. package/src/tooling/ios.zig +7 -1
  171. package/src/tooling/manifest.zig +1248 -2
  172. package/src/tooling/package.zig +953 -6
  173. package/src/tooling/raw_manifest.zig +65 -0
  174. package/src/tooling/root.zig +1 -0
  175. package/src/tooling/templates.zig +216 -4
  176. package/src/tooling/ts_core.zig +283 -17
  177. package/src/tooling/verbs.zig +7 -0
  178. package/third_party/sqlite/README.md +13 -0
  179. package/third_party/sqlite/sqlite3.c +269649 -0
  180. package/third_party/sqlite/sqlite3.h +14349 -0
  181. package/tools/corewire/core_abi.zig +14 -2
  182. package/tools/corewire/emit.zig +98 -29
  183. package/tools/corewire/emit_facade.zig +414 -23
  184. package/tools/corewire/emit_profile.zig +6 -2
  185. package/tools/corewire/emit_service.zig +924 -0
  186. package/tools/corewire/main.zig +122 -0
  187. package/tools/corewire/service_contract.zig +250 -0
  188. package/tools/corewire/sidecar.zig +26 -15
@@ -0,0 +1,181 @@
1
+ import fs from "node:fs";
2
+
3
+ // Kept in lockstep with `zig build print-pins`; the Node test suite checks
4
+ // both values so a runtime wire change cannot silently strand dev-host
5
+ // recordings.
6
+ export const journalFormatFingerprint = 0x7f56860e36c25e39n;
7
+ export const automationProtocolFingerprint = 0x096c8aa4730c11ecn;
8
+
9
+ const requestKeyBase = 0x5453525100000000n;
10
+ const textEncoder = new TextEncoder();
11
+ const textDecoder = new TextDecoder();
12
+
13
+ function concat(parts) {
14
+ const length = parts.reduce((sum, part) => sum + part.length, 0);
15
+ const out = new Uint8Array(length);
16
+ let at = 0;
17
+ for (const part of parts) { out.set(part, at); at += part.length; }
18
+ return out;
19
+ }
20
+
21
+ function numberBytes(method, size, value) {
22
+ const out = new Uint8Array(size);
23
+ new DataView(out.buffer)[method](0, value, true);
24
+ return out;
25
+ }
26
+ const u16 = (value) => numberBytes("setUint16", 2, value);
27
+ const u32 = (value) => numberBytes("setUint32", 4, value);
28
+ const i32 = (value) => numberBytes("setInt32", 4, value);
29
+ const u64 = (value) => numberBytes("setBigUint64", 8, BigInt(value));
30
+ const i64 = (value) => numberBytes("setBigInt64", 8, BigInt(value));
31
+ const f32 = (value) => numberBytes("setFloat32", 4, value);
32
+ const stringBytes = (value) => { const bytes = typeof value === "string" ? textEncoder.encode(value) : value; return concat([u32(bytes.length), bytes]); };
33
+
34
+ function frame(kind, payload) {
35
+ return concat([new Uint8Array([kind]), u32(payload.length), payload]);
36
+ }
37
+
38
+ function defaultEffect(kind, key, payload, options = {}) {
39
+ return concat([
40
+ new Uint8Array([kind]), u64(key), stringBytes(payload), stringBytes(new Uint8Array(0)),
41
+ new Uint8Array([0]), u32(options.dropped ?? 0), i32(options.code ?? 0), new Uint8Array([0, 0, 0]), u16(0),
42
+ // fetch outcome, file op/outcome, clipboard op/outcome, timer outcome
43
+ new Uint8Array([0, 0, 0, 1, 0]), u64(0), new Uint8Array([0]), i64(0),
44
+ // audio defaults: position, zero timing/state, 32 zero bands
45
+ new Uint8Array([1]), u64(0), u64(0), new Uint8Array([0, 0]), new Uint8Array(32),
46
+ // image defaults + 16-byte blob hash
47
+ new Uint8Array([0]), u64(0), u64(0), new Uint8Array(16), u64(0),
48
+ // channel event + cumulative drops
49
+ new Uint8Array([options.channelKind ?? 0]), u32(options.channelDroppedTotal ?? 0),
50
+ // video defaults
51
+ new Uint8Array([1]), u64(0), u64(0), new Uint8Array([0, 0]), u64(0), u64(0), u64(0), new Uint8Array([0, 0]),
52
+ // pty defaults + 16-byte blob hash
53
+ new Uint8Array([0]), i32(0), u32(0), new Uint8Array(16), u64(0),
54
+ ]);
55
+ }
56
+
57
+ export class DevhostJournalWriter {
58
+ constructor(file, appName, canvasLabel, width, height) {
59
+ this.file = file;
60
+ this.parts = [];
61
+ this.eventCount = 0;
62
+ this.effectCount = 0;
63
+ const preamble = new Uint8Array(16);
64
+ preamble.set(textEncoder.encode("NSDKSJNL"), 0);
65
+ new DataView(preamble.buffer).setBigUint64(8, journalFormatFingerprint, true);
66
+ this.parts.push(preamble);
67
+ const platform = process.platform === "darwin" ? "macos" : process.platform === "win32" ? "windows" : process.platform;
68
+ const header = concat([u64(automationProtocolFingerprint), stringBytes(platform), stringBytes(appName), i64(Date.now()), f32(width), f32(height)]);
69
+ this.parts.push(frame(1, header));
70
+ }
71
+
72
+ event(tag, payload = new Uint8Array(0)) {
73
+ this.parts.push(frame(2, concat([new Uint8Array([tag]), payload])));
74
+ this.eventCount += 1;
75
+ }
76
+
77
+ installFrame(canvasLabel, width, height) {
78
+ this.event(18, concat([
79
+ u64(1), stringBytes(canvasLabel), f32(width), f32(height), f32(1),
80
+ u64(1), u64(1_000_000), u64(0), u64(0), new Uint8Array([1]),
81
+ ]));
82
+ }
83
+ appStart() { this.event(1); }
84
+ wake() { this.event(16); }
85
+ menuCommand(name) { this.event(14, concat([stringBytes(name), u64(1)])); }
86
+ host(index, ok, payload) {
87
+ this.parts.push(frame(3, defaultEffect(9, requestKeyBase + BigInt(index), payload, { code: ok ? 0 : 1 })));
88
+ this.effectCount += 1;
89
+ }
90
+ channel(key, state, payload = new Uint8Array(0), dropped = 0, droppedTotal = 0) {
91
+ const channelKind = state === "data" ? 0 : state === "closed" ? 1 : 2;
92
+ this.parts.push(frame(3, defaultEffect(12, BigInt(key), payload, { dropped, channelKind, channelDroppedTotal: droppedTotal })));
93
+ this.effectCount += 1;
94
+ }
95
+ finish() {
96
+ this.parts.push(frame(6, concat([u64(this.eventCount), u64(this.effectCount), u64(0), u64(0)])));
97
+ fs.writeFileSync(this.file, concat(this.parts));
98
+ }
99
+ }
100
+
101
+ class Reader {
102
+ constructor(bytes) { this.bytes = bytes; this.at = 0; }
103
+ take(length) { if (this.at + length > this.bytes.length) throw new Error("truncated session journal"); const out = this.bytes.subarray(this.at, this.at + length); this.at += length; return out; }
104
+ byte() { return this.take(1)[0]; }
105
+ u16() { const b = this.take(2); return new DataView(b.buffer, b.byteOffset, 2).getUint16(0, true); }
106
+ u32() { const b = this.take(4); return new DataView(b.buffer, b.byteOffset, 4).getUint32(0, true); }
107
+ i32() { const b = this.take(4); return new DataView(b.buffer, b.byteOffset, 4).getInt32(0, true); }
108
+ u64() { const b = this.take(8); return new DataView(b.buffer, b.byteOffset, 8).getBigUint64(0, true); }
109
+ i64() { const b = this.take(8); return new DataView(b.buffer, b.byteOffset, 8).getBigInt64(0, true); }
110
+ f32() { const b = this.take(4); return new DataView(b.buffer, b.byteOffset, 4).getFloat32(0, true); }
111
+ string() { return this.take(this.u32()); }
112
+ done() { return this.at === this.bytes.length; }
113
+ }
114
+
115
+ function decodeEffect(payload) {
116
+ const r = new Reader(payload);
117
+ const kind = r.byte();
118
+ const key = r.u64();
119
+ const bytes = r.string();
120
+ r.string(); r.byte();
121
+ const dropped = r.u32();
122
+ const code = r.i32();
123
+ r.byte(); r.byte(); r.byte(); r.u16();
124
+ r.byte(); r.byte(); r.byte(); r.byte(); r.byte(); r.u64(); r.byte(); r.i64();
125
+ r.byte(); r.u64(); r.u64(); r.byte(); r.byte(); r.take(32);
126
+ r.byte(); r.u64(); r.u64(); r.take(16); r.u64();
127
+ const channelKind = r.byte();
128
+ const channelDroppedTotal = r.u32();
129
+ r.byte(); r.u64(); r.u64(); r.byte(); r.byte(); r.u64(); r.u64(); r.u64(); r.byte(); r.byte();
130
+ r.byte(); r.i32(); r.u32(); r.take(16); r.u64();
131
+ if (!r.done()) throw new Error("unsupported session effect suffix");
132
+ return { type: "effect", kind, key, payload: bytes, code, dropped, channelKind, channelDroppedTotal };
133
+ }
134
+
135
+ export function readDevhostJournal(file) {
136
+ const bytes = new Uint8Array(fs.readFileSync(file));
137
+ const r = new Reader(bytes);
138
+ if (textDecoder.decode(r.take(8)) !== "NSDKSJNL") throw new Error("not a Native SDK session journal");
139
+ if (r.u64() !== journalFormatFingerprint) throw new Error("session journal format differs from this SDK; re-record it");
140
+ const records = [];
141
+ let headerSeen = false;
142
+ let events = 0;
143
+ let effects = 0;
144
+ let ended = false;
145
+ while (!r.done()) {
146
+ const kind = r.byte();
147
+ const payload = r.take(r.u32());
148
+ if (kind === 1) {
149
+ if (headerSeen || records.length > 0) throw new Error("session journal header is misplaced");
150
+ headerSeen = true;
151
+ const h = new Reader(payload);
152
+ if (h.u64() !== automationProtocolFingerprint) throw new Error("session automation protocol differs from this SDK");
153
+ h.string(); h.string(); h.i64(); h.f32(); h.f32();
154
+ if (!h.done()) throw new Error("invalid session journal header");
155
+ } else if (kind === 2) {
156
+ const event = new Reader(payload);
157
+ const tag = event.byte();
158
+ let name = null;
159
+ if (tag === 14) { name = textDecoder.decode(event.string()); event.u64(); }
160
+ records.push({ type: "event", tag, name });
161
+ events += 1;
162
+ } else if (kind === 3) {
163
+ records.push(decodeEffect(payload));
164
+ effects += 1;
165
+ } else if (kind === 4 || kind === 5) {
166
+ // Renderer checkpoints are meaningful to the packaged host and inert
167
+ // in the logic-only dev host.
168
+ } else if (kind === 6) {
169
+ const end = new Reader(payload);
170
+ const expectedEvents = Number(end.u64());
171
+ const expectedEffects = Number(end.u64());
172
+ end.u64(); end.u64();
173
+ if (!end.done() || expectedEvents !== events || expectedEffects !== effects) throw new Error("session journal record counts disagree");
174
+ ended = true;
175
+ } else throw new Error(`unsupported session journal record ${kind}`);
176
+ }
177
+ if (!headerSeen || !ended) throw new Error("session journal is incomplete");
178
+ return records;
179
+ }
180
+
181
+ export { requestKeyBase };
@@ -10,13 +10,29 @@
10
10
  // always imports the SDK checkout's module directly. Relative imports
11
11
  // inside the core's src/ are real files node resolves itself.
12
12
 
13
+ let generatedCoreUrl = null;
14
+ let servicesClientUrl = null;
15
+ let servicePackages = {};
16
+
17
+ export function initialize(data) {
18
+ generatedCoreUrl = data?.generatedCoreUrl ?? null;
19
+ servicesClientUrl = data?.servicesClientUrl ?? null;
20
+ servicePackages = data?.servicePackages ?? {};
21
+ }
22
+
13
23
  export async function resolve(specifier, context, nextResolve) {
14
24
  if (specifier === "@native-sdk/core") {
15
- return { shortCircuit: true, url: new URL("../sdk/core.ts", import.meta.url).href };
25
+ return { shortCircuit: true, url: generatedCoreUrl ?? new URL("../sdk/core.ts", import.meta.url).href };
16
26
  }
17
27
  if (specifier.startsWith("@native-sdk/core/")) {
18
28
  const lib = specifier.slice("@native-sdk/core/".length);
19
29
  return { shortCircuit: true, url: new URL(`../sdk/${lib}.ts`, import.meta.url).href };
20
30
  }
31
+ if (specifier === "@native-sdk/services" && servicesClientUrl) {
32
+ return { shortCircuit: true, url: servicesClientUrl };
33
+ }
34
+ if (Object.hasOwn(servicePackages, specifier)) {
35
+ return { shortCircuit: true, url: servicePackages[specifier] };
36
+ }
21
37
  return nextResolve(specifier, context);
22
38
  }
@@ -0,0 +1,90 @@
1
+ import { parentPort, workerData } from "node:worker_threads";
2
+ import { register } from "node:module";
3
+ import { pathToFileURL } from "node:url";
4
+
5
+ if (!parentPort) throw new Error("the service worker requires a parent port");
6
+
7
+ register(new URL("./devhost_resolver.mjs", import.meta.url), { data: workerData.resolverData });
8
+
9
+ const operations = new Map();
10
+ for (const operation of workerData.operations) {
11
+ const module = await import(pathToFileURL(operation.absoluteModule).href);
12
+ const fn = module[operation.export];
13
+ if (typeof fn !== "function") throw new Error(`service contract export ${operation.name} is not callable`);
14
+ operations.set(operation.name, { operation, fn });
15
+ }
16
+
17
+ function errorFact(error) {
18
+ if (error && typeof error === "object") {
19
+ const kind = typeof error.kind === "string" ? error.kind : typeof error.name === "string" ? error.name : "service_error";
20
+ const message = typeof error.message === "string" ? error.message : "service operation threw";
21
+ return { kind, message };
22
+ }
23
+ return { kind: "service_error", message: "service operation threw" };
24
+ }
25
+
26
+ function incrementDrops(view) {
27
+ const mask = 0xffffffffn;
28
+ for (;;) {
29
+ const current = Atomics.load(view, 0);
30
+ const pending = current & mask;
31
+ const total = current >> 32n;
32
+ const nextPending = pending === mask ? mask : pending + 1n;
33
+ const nextTotal = total === mask ? mask : total + 1n;
34
+ const next = (nextTotal << 32n) | nextPending;
35
+ if (Atomics.compareExchange(view, 0, current, next) === current) return;
36
+ }
37
+ }
38
+
39
+ parentPort.on("message", ({ id, name, request, cancelBuffer, streamStateBuffer }) => {
40
+ const service = operations.get(name);
41
+ if (!service) {
42
+ parentPort.postMessage({ id, type: "error", error: { kind: "service_host", message: `unknown service operation ${name}` }, elapsed: 0 });
43
+ return;
44
+ }
45
+ const started = performance.now();
46
+ const flag = new Int32Array(cancelBuffer);
47
+ const streamInFlight = new Int32Array(streamStateBuffer, 0, 1);
48
+ const streamDrops = new BigUint64Array(streamStateBuffer, 8, 1);
49
+ const cancellation = {
50
+ cancelled: () => Atomics.load(flag, 0) !== 0,
51
+ throwIfCancelled: () => {
52
+ if (Atomics.load(flag, 0) !== 0) {
53
+ const error = new Error("service operation was cancelled");
54
+ error.name = "cancelled";
55
+ throw error;
56
+ }
57
+ },
58
+ };
59
+ const emit = (chunk) => {
60
+ cancellation.throwIfCancelled();
61
+ const limit = service.operation.stream?.in_flight ?? 0;
62
+ for (;;) {
63
+ const inFlight = Atomics.load(streamInFlight, 0);
64
+ if (inFlight >= limit) {
65
+ incrementDrops(streamDrops);
66
+ return;
67
+ }
68
+ if (Atomics.compareExchange(streamInFlight, 0, inFlight, inFlight + 1) === inFlight) break;
69
+ }
70
+ try {
71
+ parentPort.postMessage({ id, type: "chunk", chunk });
72
+ } catch (error) {
73
+ Atomics.sub(streamInFlight, 0, 1);
74
+ throw error;
75
+ }
76
+ };
77
+ try {
78
+ const args = [];
79
+ if (service.operation.request.kind !== "none") args.push(request);
80
+ if (service.operation.stream !== null) args.push(emit);
81
+ if (service.operation.cancellable) args.push(cancellation);
82
+ const result = service.fn(...args);
83
+ cancellation.throwIfCancelled();
84
+ parentPort.postMessage({ id, type: "result", result, elapsed: performance.now() - started });
85
+ } catch (error) {
86
+ parentPort.postMessage({ id, type: "error", error: errorFact(error), elapsed: performance.now() - started });
87
+ }
88
+ });
89
+
90
+ parentPort.postMessage({ type: "ready" });
@@ -43,7 +43,7 @@ export const rules = {
43
43
  NS1004: {
44
44
  id: "NS1004",
45
45
  title: "text is not indexable",
46
- fix: "Store text as `Uint8Array` bytes and index those; turn literals and templates into bytes with the `asciiBytes` intrinsic from \"@native-sdk/core\".",
46
+ fix: "Store text as `Uint8Array` bytes and index those; turn user-visible literals/templates into bytes with `utf8Bytes` from \"@native-sdk/core\" (`asciiBytes` is the narrower machine-text form).",
47
47
  why: "Code-unit reads behave differently in JS (UTF-16) and native (UTF-8); with them gone the encodings are indistinguishable.",
48
48
  },
49
49
  NS1005: {
@@ -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",
@@ -127,7 +127,7 @@ export const rules = {
127
127
  NS1018: {
128
128
  id: "NS1018",
129
129
  title: "text builds with templates and bytes, not +",
130
- fix: "Build the text as bytes: `asciiBytes(`${count} items`)` from \"@native-sdk/core\", or stitch byte buffers with `new Uint8Array(n)` + `.set`.",
130
+ fix: "Build the text as bytes: `utf8Bytes(`${count} items`)` from \"@native-sdk/core\", or stitch byte buffers with `new Uint8Array(n)` + `.set`.",
131
131
  why: "Runtime string concatenation would need a JS string heap the native binary does not carry; bytes in the frame arena are the one dynamic-text representation.",
132
132
  },
133
133
  NS1019: {
@@ -163,7 +163,7 @@ export const rules = {
163
163
  NS1024: {
164
164
  id: "NS1024",
165
165
  title: "model text is bytes",
166
- fix: "Type the field `Uint8Array` and build its values with the `asciiBytes` intrinsic from \"@native-sdk/core\" (literals and templates fold at compile time), or use a string-literal union (`\"low\" | \"high\"`) when the field holds one of a closed set of tags.",
166
+ fix: "Type the field `Uint8Array` and build user-visible values with `utf8Bytes` from \"@native-sdk/core\" (`asciiBytes` is for guaranteed-ASCII machine text), or use a string-literal union (`\"low\" | \"high\"`) when the field holds one of a closed set of tags.",
167
167
  why: "A `string` model field would need a JS string heap at every commit; bytes have exactly one representation under node and native, and literal-union tags compile to a native enum.",
168
168
  },
169
169
  NS1025: {
@@ -175,8 +175,8 @@ export const rules = {
175
175
  NS1026: {
176
176
  id: "NS1026",
177
177
  title: "host payloads are bytes or a flat scalar record",
178
- fix: "Pass one `Uint8Array` (build text with `asciiBytes`), or one inline record whose fields are numbers, booleans, or `Uint8Array` values — nothing nested, no extra arguments alongside a payload.",
179
- why: "A host command carries exactly one bytes payload on the wire; only these field types have a byte encoding that is identical under node and native.",
178
+ fix: "For a raw host call, pass one `Uint8Array` (build text with `asciiBytes`) or one inline scalar record. For nested/typed service data, declare one exported shared shape and call its generated constructor from `@native-sdk/services`.",
179
+ why: "Raw host commands carry one primitive bytes payload. Generated service clients are the deliberate record-valued arm: their sidecar-derived codec carries the wider boundary vocabulary identically under node and native.",
180
180
  },
181
181
  NS1027: {
182
182
  id: "NS1027",
@@ -186,15 +186,15 @@ export const rules = {
186
186
  },
187
187
  NS1028: {
188
188
  id: "NS1028",
189
- title: "Cmd.persist is not yet host-backed",
190
- fix: "Persist app state yourself with `Cmd.writeFile(path, bytes, { ok, err })` and load it back at boot with `Cmd.readFile` from `initialModel`'s command.",
191
- why: "No shipping host implements the persist verb yet, so the record is performed by nobody — a writeFile you control (own path, own format, a load path) is the persistence real apps use. The op still compiles and stays on the wire for hosts that add the service.",
189
+ title: "Cmd.persist and its capability must agree",
190
+ fix: "Add `\"persist\"` to app.zon's `capabilities` and configure `.persist = .{ .version = 1, .restore = .{ .ok = \"restored\", .none = \"fresh_boot\", .err = \"restore_failed\" } }`; or remove the unused capability/command.",
191
+ why: "The persist capability controls whether the engine-owned snapshot store and `core.persist` binding are linked into the app. Keeping the declaration and command in lockstep prevents a silently unperformed write and sheds storage code from apps that do not use it.",
192
192
  },
193
193
  NS1029: {
194
194
  id: "NS1029",
195
195
  title: "effect op arguments have a fixed shape",
196
- fix: "Spell the op exactly: paths/URLs/bodies are `Uint8Array` (asciiBytes for literals), `method` is one of the closed verb literals, `timeoutMs` is a number literal, and `headers` is an inline flat record whose names are compile-time ASCII and whose values are string literals or `Uint8Array` bytes (`{ accept: \"application/json\", authorization: token }`).",
197
- why: "Named effect ops encode to a fixed wire record shape at build time — a closed verb set, literal header names, and bytes-typed dynamic fields (URL, body, header values) are what encodes identically under node and native.",
196
+ fix: "Spell the built-in op exactly: paths/URLs/bodies are `Uint8Array`, `method` is a closed verb literal, `timeoutMs` is a number literal, and `headers` is an inline flat record. For an app service, use its generated `@native-sdk/services` constructor; its request and route shape come from the shared contract.",
197
+ why: "Every effect encodes to one fixed wire record. Built-ins own their hand-written shape; service operations own a generated shape and codec projected from services.contract.json.",
198
198
  },
199
199
  NS1030: {
200
200
  id: "NS1030",
@@ -216,9 +216,9 @@ export const rules = {
216
216
  },
217
217
  NS1033: {
218
218
  id: "NS1033",
219
- title: "wiring channel exports match their host event 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`; `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 these host events structurally from your declarations at build time (the effects-routing rule applied to the app shell); a wrong shape would otherwise surface as a Zig compile error inside generated code instead of a teaching diagnostic here.",
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`; `statusItem(model: Model): StatusItemState`; `appearanceMsg` / `chromeMsg` naming an arm with that channel's record shape; `envMsgs` entries targeting one-`Uint8Array`-field arms; and persistence ok/none routes naming void arms while err names a one-`Uint8Array`-field arm. Import canonical records from `@native-sdk/core/events`.",
221
+ why: "The generated wiring builds host events, persistence restore results, model-derived theme selection, and the live menu-bar status item 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",
@@ -229,12 +229,12 @@ export const rules = {
229
229
  NS1035: {
230
230
  id: "NS1035",
231
231
  title: "npm packages do not run inside a core",
232
- fix: "Vendor the logic as a module under src/ and import it relatively, or make the import type-only (`import type`); only \"@native-sdk/core\" modules carry runtime meaning.",
233
- why: "No JS engine ships in the binary — an npm package's code has nowhere to run natively, while types erase and cost nothing.",
232
+ fix: "Move ordinary TypeScript work into `src/services/` and call it through `Cmd.request`, vendor subset-legal core logic under src/ and import it relatively, or make the import type-only (`import type`); only \"@native-sdk/core\" modules carry runtime meaning in the core class.",
233
+ why: "No JS engine ships in the binary — the deterministic core carries only its closed subset, while service modules compile separately through scriptc's ordinary static tier and results return as messages.",
234
234
  },
235
235
  NS1036: {
236
236
  id: "NS1036",
237
- title: "core modules do not import in a cycle",
237
+ title: "runtime modules do not import in a cycle",
238
238
  fix: "Hoist the shared declarations into a module both sides import, or make the back-edge type-only (`import type { Model } from \"./core.ts\"` is fine).",
239
239
  why: "A runtime import cycle only works through JS's live-binding indirection, which the emitted native module (and plain reading order) cannot represent; type-only edges erase and are exempt.",
240
240
  },
@@ -253,7 +253,7 @@ export const rules = {
253
253
  NS1039: {
254
254
  id: "NS1039",
255
255
  title: "a namespace import is a compile-time alias",
256
- fix: "Reference members through the alias (`ns.helper(x)`, `ns.Config`) or import them by name; the SDK intrinsics are always named imports — `import { Cmd, Sub, asciiBytes } from \"@native-sdk/core\"`.",
256
+ fix: "Reference members through the alias (`ns.helper(x)`, `ns.Config`) or import them by name; the SDK intrinsics are always named imports — `import { Cmd, Sub, asciiBytes, utf8Bytes } from \"@native-sdk/core\"`.",
257
257
  why: "The core emits as one flat namespace, so `ns` is dot-syntax that erases at build time — it is not an object value that can be stored or passed — and the effect purity rules recognize the SDK factories by their imported names.",
258
258
  },
259
259
  NS1040: {
@@ -400,6 +400,72 @@ export const rules = {
400
400
  fix: "Spell the crossing in a schema-carried form: value-stored records (object-literal aliases) for message payloads, named records around optional or array payloads, and integer aliases whose values reach past 255.",
401
401
  why: "The contract sidecar is the machine-readable twin of the core's surface, and a shape its schema cannot state would silently drop from every consumer — so the build stops here with the spelling that carries it instead.",
402
402
  },
403
+ NS1064: {
404
+ id: "NS1064",
405
+ title: "asciiBytes is ASCII-only",
406
+ fix: "Use `utf8Bytes(...)` for user-visible or Unicode text; keep `asciiBytes(...)` for guaranteed-ASCII command names, keys, paths, URLs, and protocol values.",
407
+ why: "JavaScript strings are UTF-16 while the native text boundary is UTF-8; naming the encoding explicitly prevents a non-ASCII code unit from being truncated into a different byte sequence.",
408
+ },
409
+ NS1065: {
410
+ id: "NS1065",
411
+ title: "the core does not import services",
412
+ fix: "Import the generated constructor from `@native-sdk/services` and return it from update; raw `Cmd.request(\"module.operation\", bytes, { ok, err })` remains the low-level form. Shared boundary shapes live in a core module that the service imports, but the core-to-service edge is always an effect.",
413
+ why: "A direct import would run ambient, non-deterministic service authority inside update and erase the command/result boundary that journaling and replay depend on.",
414
+ },
415
+ NS1066: {
416
+ id: "NS1066",
417
+ title: "service package imports are exact vendored facts",
418
+ fix: "Run `native vendor . package@X.Y.Z`, check in `src/services/vendor/` and the generated app.zon `service_packages` facts, then import that exact package name; or vendor a local source module and import it relatively.",
419
+ why: "Service builds have no package-manager or network input: scriptc sees only manifest-declared, hash-verified checked-in sources through an explicit `--npm-static` allowlist.",
420
+ },
421
+ NS1067: {
422
+ id: "NS1067",
423
+ title: "service calls match the generated typed contract",
424
+ fix: "Export a synchronous, non-default named function with zero or one explicitly typed, contract-encodable request and a contract-encodable result. For a stream, add a last `emit: (chunk: SharedChunk) => void` parameter. Keep boundary records/enums/unions exported in a shared core-class module, let only `{ kind: \"...\", message: <string> }` escape, and call through `@native-sdk/services`.",
425
+ why: "The host codecs, runner registry, and typed client are projections of `services.contract.json`; every crossing data shape, stream declaration, deadline, and operation name must be stated there once.",
426
+ },
427
+ NS1068: {
428
+ id: "NS1068",
429
+ title: "persistent model shapes advance monotonically",
430
+ fix: "Increase app.zon's `.persist.version` when the `Model` shape changes, and never decrease or reuse a version number.",
431
+ why: "The version selects the app's pure migration path while the model fingerprint rejects accidental shape drift; reusing a version would make old bytes ambiguous and could restore them into the wrong model layout.",
432
+ },
433
+ NS1069: {
434
+ id: "NS1069",
435
+ title: "Cmd.store and its capability must agree",
436
+ fix: "Add `\"store\"` to app.zon's `capabilities`, or remove the unused capability/command.",
437
+ why: "The store capability controls whether SQLite and the engine-owned record-store binding are linked into the app. Keeping the declaration and command in lockstep prevents a rejected effect and sheds the storage engine from apps that do not use it.",
438
+ },
439
+ NS1070: {
440
+ id: "NS1070",
441
+ title: "Cmd.db and its capability must agree",
442
+ fix: "Add `\"sqlite\"` to app.zon's `capabilities`, or remove the unused capability/command.",
443
+ why: "The sqlite capability controls whether the relational database and its effect binding are linked into the app. Keeping the declaration and command in lockstep prevents a rejected effect and sheds SQLite from apps that do not use either storage tier.",
444
+ },
445
+ NS1071: {
446
+ id: "NS1071",
447
+ title: "Cmd.credentials and its capability must agree",
448
+ fix: "Add `\"credentials\"` to app.zon's `capabilities`, or remove the unused capability/command.",
449
+ why: "The credentials capability controls whether the core keychain path is linked into the app; keeping it in lockstep prevents a guaranteed denied effect and sheds the path from apps that do not use it.",
450
+ },
451
+ NS1072: {
452
+ id: "NS1072",
453
+ title: "core credentials require explicit permission",
454
+ fix: "Add `\"credentials\"` to app.zon's `permissions`, or remove the `Cmd.credentials.*` call.",
455
+ why: "Secrets are the first permission-gated core effect: the runtime refuses every undeclared access with `denied`, even when the build capability is present.",
456
+ },
457
+ NS1073: {
458
+ id: "NS1073",
459
+ title: "credential requests use the typed factory",
460
+ fix: "Use `Cmd.credentials.set`, `Cmd.credentials.get`, or `Cmd.credentials.delete` instead of spelling `core.credentials.*` through `Cmd.request`.",
461
+ why: "The typed factories own the bounded credential record encoding; reserving their wire namespace keeps arbitrary request bytes from being mistaken for secrets or keys.",
462
+ },
463
+ NS1420: {
464
+ id: "NS1420",
465
+ title: "declare stable SQL in src/queries.sql",
466
+ fix: "Move the string literal into a named `-- name: ...` block in src/queries.sql and call its generated `Cmd.q<Name>` constructor; keep Cmd.db only for genuinely dynamic escape-hatch SQL.",
467
+ why: "Declared SQL is prepared against the complete migration schema during native check, so table, column, result, and parameter mistakes never reach an installed app.",
468
+ },
403
469
  } as const satisfies Record<string, RuleCopy>;
404
470
 
405
471
  export type RuleId = keyof typeof rules;