@native-sdk/cli 0.8.4 → 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 (146) hide show
  1. package/build/app.zig +859 -62
  2. package/build.zig +543 -13
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +2 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +365 -2
  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 +149 -0
  19. package/packages/core/sdk/core.ts +529 -12
  20. package/packages/core/sdk/events.d.ts +36 -0
  21. package/packages/core/sdk/events.ts +57 -0
  22. package/packages/core/src/checker.ts +468 -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 +1847 -16
  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 +82 -16
  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/references/project-anatomy.md +1 -1
  38. package/skill-data/native-ui/SKILL.md +47 -0
  39. package/skill-data/ts-core/SKILL.md +80 -31
  40. package/skill-data/ts-services/SKILL.md +126 -0
  41. package/skill-data/ts-services/references/service-surface.md +603 -0
  42. package/skill-data/zig/SKILL.md +1 -1
  43. package/skills/native-sdk/SKILL.md +1 -1
  44. package/src/app_runner/no_migrations.zig +3 -0
  45. package/src/app_runner/no_services.zig +20 -0
  46. package/src/app_runner/root.zig +104 -4
  47. package/src/app_runner/ts_core_main.zig +249 -8
  48. package/src/automation/snapshot.zig +23 -5
  49. package/src/embed/app_exports.zig +11 -1
  50. package/src/embed/c_api.zig +48 -2
  51. package/src/embed/conversions.zig +4 -5
  52. package/src/embed/host.zig +109 -1
  53. package/src/embed/root.zig +7 -0
  54. package/src/embed/tests.zig +213 -0
  55. package/src/embed/types.zig +51 -0
  56. package/src/embed/ui_host.zig +119 -5
  57. package/src/platform/android/NativeSdkActivity.java +131 -0
  58. package/src/platform/android/android_host.c +182 -1
  59. package/src/platform/android/native_sdk_app.h +17 -0
  60. package/src/platform/ios/native_sdk_app.h +17 -0
  61. package/src/platform/ios/uikit_host.m +115 -0
  62. package/src/platform/linux/cef_host.cpp +1 -1
  63. package/src/platform/linux/gtk_host.c +89 -17
  64. package/src/platform/linux/gtk_host.h +3 -0
  65. package/src/platform/linux/root.zig +40 -18
  66. package/src/platform/macos/appkit_host.h +16 -3
  67. package/src/platform/macos/appkit_host.m +536 -36
  68. package/src/platform/macos/cef_host.mm +248 -36
  69. package/src/platform/macos/root.zig +244 -34
  70. package/src/platform/null_platform.zig +223 -19
  71. package/src/platform/null_platform_tests.zig +74 -0
  72. package/src/platform/root.zig +9 -0
  73. package/src/platform/types.zig +179 -15
  74. package/src/platform/windows/root.zig +187 -21
  75. package/src/platform/windows/webview2_host.cpp +293 -46
  76. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  77. package/src/primitives/app_manifest/root.zig +4 -0
  78. package/src/primitives/app_manifest/tests.zig +3 -0
  79. package/src/primitives/app_manifest/types.zig +32 -0
  80. package/src/primitives/app_manifest/validation.zig +19 -1
  81. package/src/root.zig +46 -0
  82. package/src/runtime/api.zig +11 -0
  83. package/src/runtime/automation_snapshot.zig +4 -0
  84. package/src/runtime/bridge_permission_tests.zig +23 -2
  85. package/src/runtime/bridge_responses.zig +3 -1
  86. package/src/runtime/canvas_frame.zig +18 -11
  87. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  88. package/src/runtime/clock.zig +13 -1
  89. package/src/runtime/core.zig +133 -1
  90. package/src/runtime/credentials_store.zig +115 -0
  91. package/src/runtime/effects.zig +2295 -113
  92. package/src/runtime/effects_credentials_tests.zig +332 -0
  93. package/src/runtime/effects_host_tests.zig +208 -1
  94. package/src/runtime/effects_relational_tests.zig +314 -0
  95. package/src/runtime/effects_store_tests.zig +211 -0
  96. package/src/runtime/flow.zig +14 -1
  97. package/src/runtime/gpu_surface_events.zig +6 -1
  98. package/src/runtime/native_command_event_tests.zig +42 -0
  99. package/src/runtime/persist_store.zig +666 -0
  100. package/src/runtime/record_store.zig +788 -0
  101. package/src/runtime/relational_store.zig +854 -0
  102. package/src/runtime/root.zig +49 -0
  103. package/src/runtime/runtime_event_tests.zig +70 -0
  104. package/src/runtime/service_host.zig +711 -0
  105. package/src/runtime/service_pool.zig +1314 -0
  106. package/src/runtime/session_blobs.zig +1 -1
  107. package/src/runtime/session_journal.zig +102 -0
  108. package/src/runtime/session_record.zig +177 -0
  109. package/src/runtime/session_replay.zig +109 -4
  110. package/src/runtime/shell_layout.zig +1 -0
  111. package/src/runtime/shell_layout_tests.zig +120 -0
  112. package/src/runtime/sqlite_engine.zig +474 -0
  113. package/src/runtime/state.zig +6 -0
  114. package/src/runtime/system_services.zig +49 -10
  115. package/src/runtime/tests.zig +4 -0
  116. package/src/runtime/ts_core_host.zig +788 -86
  117. package/src/runtime/ts_core_host_tests.zig +231 -11
  118. package/src/runtime/ts_ui_app.zig +499 -1
  119. package/src/runtime/ui_app.zig +142 -16
  120. package/src/runtime/ui_app_tests.zig +155 -5
  121. package/src/runtime/validation.zig +22 -0
  122. package/src/runtime/view.zig +9 -0
  123. package/src/runtime/window_storage.zig +1 -0
  124. package/src/runtime/window_view_runtime.zig +2 -3
  125. package/src/runtime/window_views.zig +19 -0
  126. package/src/tooling/android.zig +21 -16
  127. package/src/tooling/db.zig +160 -0
  128. package/src/tooling/ios.zig +7 -1
  129. package/src/tooling/manifest.zig +214 -2
  130. package/src/tooling/package.zig +116 -0
  131. package/src/tooling/raw_manifest.zig +30 -0
  132. package/src/tooling/root.zig +1 -0
  133. package/src/tooling/templates.zig +161 -4
  134. package/src/tooling/ts_core.zig +283 -17
  135. package/src/tooling/verbs.zig +7 -0
  136. package/third_party/sqlite/README.md +13 -0
  137. package/third_party/sqlite/sqlite3.c +269649 -0
  138. package/third_party/sqlite/sqlite3.h +14349 -0
  139. package/tools/corewire/core_abi.zig +14 -2
  140. package/tools/corewire/emit.zig +98 -29
  141. package/tools/corewire/emit_facade.zig +378 -23
  142. package/tools/corewire/emit_profile.zig +6 -2
  143. package/tools/corewire/emit_service.zig +924 -0
  144. package/tools/corewire/main.zig +122 -0
  145. package/tools/corewire/service_contract.zig +250 -0
  146. package/tools/corewire/sidecar.zig +26 -15
@@ -0,0 +1,364 @@
1
+ // Runtime-owned SQLite policy shared by schema/query analysis and the
2
+ // node devhost. Node's SQLite is intentionally only the parser/executor for
3
+ // those tools: its build enables optional modules and functions that the
4
+ // vendored app engine does not ship, so this gate narrows it to the runtime's
5
+ // documented FTS5 + JSON surface.
6
+
7
+ import { constants as sqliteConstants, type DatabaseSync } from "node:sqlite";
8
+
9
+ type SqliteAuthorizer = (
10
+ action: number,
11
+ first: string | null,
12
+ second: string | null,
13
+ databaseName?: string | null,
14
+ triggerOrView?: string | null,
15
+ ) => number;
16
+ type AuthorizerDatabase = DatabaseSync & {
17
+ setAuthorizer?: (callback: SqliteAuthorizer | null) => void;
18
+ };
19
+
20
+ interface SqlToken {
21
+ readonly text: string;
22
+ readonly kind: "word" | "identifier" | "literal" | "symbol";
23
+ }
24
+
25
+ export interface RelationalTableReference {
26
+ readonly schema: string | null;
27
+ readonly table: string;
28
+ }
29
+
30
+ const relationalOwnedPragmas = new Set([
31
+ "user_version", "schema_version", "writable_schema", "query_only",
32
+ "journal_mode", "synchronous", "locking_mode", "foreign_keys",
33
+ "defer_foreign_keys", "busy_timeout", "wal_autocheckpoint", "temp_store",
34
+ "temp_store_directory", "data_store_directory",
35
+ ]);
36
+
37
+ const relationalVirtualTableModules = new Set(["fts5", "fts5vocab"]);
38
+ const relationalUnavailableReadTables = new Set(["dbstat", "fts3tokenize"]);
39
+ const relationalTempSchemaActions = new Set([
40
+ sqliteConstants.SQLITE_CREATE_TEMP_INDEX, sqliteConstants.SQLITE_CREATE_TEMP_TABLE,
41
+ sqliteConstants.SQLITE_CREATE_TEMP_TRIGGER, sqliteConstants.SQLITE_CREATE_TEMP_VIEW,
42
+ sqliteConstants.SQLITE_DROP_TEMP_INDEX, sqliteConstants.SQLITE_DROP_TEMP_TABLE,
43
+ sqliteConstants.SQLITE_DROP_TEMP_TRIGGER, sqliteConstants.SQLITE_DROP_TEMP_VIEW,
44
+ ]);
45
+
46
+ // SQLITE_ENABLE_MATH_FUNCTIONS is enabled in Node's SQLite but not in the
47
+ // app engine. These names are otherwise absent from the vendored build (the
48
+ // core `round` function is deliberately not part of this list).
49
+ const relationalOptionalFunctions = new Set([
50
+ "acos", "acosh", "asin", "asinh", "atan", "atan2", "atanh",
51
+ "ceil", "ceiling", "cos", "cosh", "degrees", "exp", "floor", "ln",
52
+ "log", "log10", "log2", "mod", "pi", "pow", "power", "radians",
53
+ "sin", "sinh", "sqrt", "tan", "tanh", "trunc",
54
+ // Node also enables RTREE/GEOPOLY. CREATE VIRTUAL TABLE is gated below;
55
+ // reject their scalar inspection helpers as well.
56
+ "rtreecheck", "rtreedepth", "rtreenode",
57
+ // The app engine is compiled with SQLITE_OMIT_LOAD_EXTENSION. Node keeps
58
+ // the function in its parser surface even though execution is unauthorized.
59
+ "load_extension",
60
+ ]);
61
+
62
+ function sqlTokens(sql: string): SqlToken[] {
63
+ const tokens: SqlToken[] = [];
64
+ let at = 0;
65
+ while (at < sql.length) {
66
+ const char = sql[at]!;
67
+ if (/\s/.test(char)) { at += 1; continue; }
68
+ if (char === ";") { at += 1; continue; }
69
+ if (char === "-" && sql[at + 1] === "-") {
70
+ const end = sql.indexOf("\n", at + 2);
71
+ at = end < 0 ? sql.length : end + 1;
72
+ continue;
73
+ }
74
+ if (char === "/" && sql[at + 1] === "*") {
75
+ const end = sql.indexOf("*/", at + 2);
76
+ at = end < 0 ? sql.length : end + 2;
77
+ continue;
78
+ }
79
+ if (char === "'") {
80
+ let text = "";
81
+ at += 1;
82
+ while (at < sql.length) {
83
+ if (sql[at] !== "'") { text += sql[at]!; at += 1; continue; }
84
+ if (sql[at + 1] === "'") { text += "'"; at += 2; continue; }
85
+ at += 1;
86
+ break;
87
+ }
88
+ tokens.push({ text: text.toLowerCase(), kind: "literal" });
89
+ continue;
90
+ }
91
+ if (char === "\"" || char === "`" || char === "[") {
92
+ const close = char === "[" ? "]" : char;
93
+ let text = "";
94
+ at += 1;
95
+ while (at < sql.length) {
96
+ if (sql[at] !== close) { text += sql[at]!; at += 1; continue; }
97
+ if (sql[at + 1] === close) { text += close; at += 2; continue; }
98
+ at += 1;
99
+ break;
100
+ }
101
+ tokens.push({ text: text.toLowerCase(), kind: "identifier" });
102
+ continue;
103
+ }
104
+ if (/[A-Za-z_]/.test(char)) {
105
+ let end = at + 1;
106
+ while (/[A-Za-z0-9_$]/.test(sql[end] ?? "")) end += 1;
107
+ tokens.push({ text: sql.slice(at, end).toLowerCase(), kind: "word" });
108
+ at = end;
109
+ continue;
110
+ }
111
+ tokens.push({ text: char, kind: "symbol" });
112
+ at += 1;
113
+ }
114
+ return tokens;
115
+ }
116
+
117
+ function tokenName(token: SqlToken | undefined): string | null {
118
+ return token?.kind === "word" || token?.kind === "identifier" ? token.text : null;
119
+ }
120
+
121
+ function sqliteName(token: SqlToken | undefined): string | null {
122
+ return token?.kind === "literal" ? token.text : tokenName(token);
123
+ }
124
+
125
+ const relationalFromTerminators = new Set([
126
+ "where", "group", "having", "window", "order", "limit", "returning",
127
+ "union", "intersect", "except",
128
+ ]);
129
+
130
+ function tableReferenceAt(tokens: readonly SqlToken[], start: number): RelationalTableReference | null {
131
+ const first = sqliteName(tokens[start]);
132
+ if (first === null) return null;
133
+ if (tokens[start + 1]?.text !== ".") return { schema: null, table: first };
134
+ const table = sqliteName(tokens[start + 2]);
135
+ return table === null ? null : { schema: first, table };
136
+ }
137
+
138
+ /// Table factors named by one SQLite statement. The scanner follows FROM
139
+ /// lists at each parenthesis depth, including comma joins, and preserves
140
+ /// quoted identifiers as one token. SQLite remains the grammar authority;
141
+ /// this is the shared compatibility/dependency view used where Node 22 has no
142
+ /// authorizer callback and where EXPLAIN text loses identifier boundaries.
143
+ export function relationalTableReferences(sql: string): readonly RelationalTableReference[] {
144
+ const tokens = sqlTokens(sql);
145
+ const references: RelationalTableReference[] = [];
146
+ const fromDepths = new Set<number>();
147
+ const expectingAtDepth = new Set<number>();
148
+ let depth = 0;
149
+
150
+ for (let at = 0; at < tokens.length; at++) {
151
+ const token = tokens[at]!;
152
+ if (token.text === "(") {
153
+ expectingAtDepth.delete(depth);
154
+ depth += 1;
155
+ continue;
156
+ }
157
+ if (token.text === ")") {
158
+ fromDepths.delete(depth);
159
+ expectingAtDepth.delete(depth);
160
+ depth = Math.max(0, depth - 1);
161
+ continue;
162
+ }
163
+
164
+ if (expectingAtDepth.has(depth)) {
165
+ const reference = tableReferenceAt(tokens, at);
166
+ expectingAtDepth.delete(depth);
167
+ if (reference !== null) references.push(reference);
168
+ }
169
+
170
+ if (token.kind === "word" && token.text === "from") {
171
+ fromDepths.add(depth);
172
+ expectingAtDepth.add(depth);
173
+ continue;
174
+ }
175
+ if (token.kind === "word" && token.text === "join") {
176
+ fromDepths.add(depth);
177
+ expectingAtDepth.add(depth);
178
+ continue;
179
+ }
180
+ if (fromDepths.has(depth) && token.text === ",") {
181
+ expectingAtDepth.add(depth);
182
+ continue;
183
+ }
184
+ if (fromDepths.has(depth) && token.kind === "word" && relationalFromTerminators.has(token.text)) {
185
+ fromDepths.delete(depth);
186
+ expectingAtDepth.delete(depth);
187
+ continue;
188
+ }
189
+ if (token.kind === "word" && (token.text === "update" || token.text === "into")) {
190
+ let tableAt = at + 1;
191
+ if (token.text === "update" && tokens[tableAt]?.kind === "word" && tokens[tableAt]?.text === "or") tableAt += 2;
192
+ const reference = tableReferenceAt(tokens, tableAt);
193
+ if (reference !== null) references.push(reference);
194
+ }
195
+ }
196
+ return references;
197
+ }
198
+
199
+ function cteNamesAndMainToken(tokens: readonly SqlToken[], start: number): { ctes: Set<string>; declarations: Set<number>; main: number } {
200
+ const ctes = new Set<string>();
201
+ const declarations = new Set<number>();
202
+ if (tokens[start]?.kind !== "word" || tokens[start]?.text !== "with") return { ctes, declarations, main: start };
203
+ let at = tokens[start + 1]?.kind === "word" && tokens[start + 1]?.text === "recursive" ? start + 2 : start + 1;
204
+ while (at < tokens.length) {
205
+ const name = sqliteName(tokens[at]);
206
+ if (name === null) break;
207
+ ctes.add(name);
208
+ declarations.add(at);
209
+ at += 1;
210
+ if (tokens[at]?.text === "(") {
211
+ let depth = 1;
212
+ while (++at < tokens.length && depth > 0) {
213
+ if (tokens[at]?.text === "(") depth += 1;
214
+ else if (tokens[at]?.text === ")") depth -= 1;
215
+ }
216
+ }
217
+ if (tokens[at]?.kind !== "word" || tokens[at]?.text !== "as") break;
218
+ at += 1;
219
+ if (tokens[at]?.kind === "word" && tokens[at]?.text === "not") at += 1;
220
+ if (tokens[at]?.kind === "word" && tokens[at]?.text === "materialized") at += 1;
221
+ if (tokens[at]?.text !== "(") break;
222
+ let depth = 1;
223
+ while (++at < tokens.length && depth > 0) {
224
+ if (tokens[at]?.text === "(") depth += 1;
225
+ else if (tokens[at]?.text === ")") depth -= 1;
226
+ }
227
+ if (tokens[at]?.text !== ",") break;
228
+ at += 1;
229
+ }
230
+ return { ctes, declarations, main: at };
231
+ }
232
+
233
+ /// Node 22 ships `node:sqlite` without DatabaseSync.setAuthorizer. Keep the
234
+ /// native authorizer when the host provides it, and let callers pair this with
235
+ /// `inspectRelationalSql` on older supported Node releases.
236
+ export function setRelationalAuthorizer(
237
+ db: DatabaseSync,
238
+ callback: SqliteAuthorizer | null,
239
+ ): boolean {
240
+ const setAuthorizer = (db as AuthorizerDatabase).setAuthorizer;
241
+ if (typeof setAuthorizer !== "function") return false;
242
+ setAuthorizer.call(db, callback);
243
+ return true;
244
+ }
245
+
246
+ export interface RelationalSqlInspection {
247
+ readonly error: string | null;
248
+ readonly writes: boolean;
249
+ }
250
+
251
+ /// Preflight one SQLite statement without executing it. SQLite remains the
252
+ /// grammar authority; this compatibility inspection covers the policy events
253
+ /// that Node 22 cannot expose through an authorizer callback.
254
+ export function inspectRelationalSql(sql: string, denyTransactions: boolean): RelationalSqlInspection {
255
+ const tokens = sqlTokens(sql);
256
+ let start = 0;
257
+ if (tokens[start]?.kind === "word" && tokens[start]?.text === "explain") {
258
+ start += 1;
259
+ if (tokens[start]?.kind === "word" && tokens[start]?.text === "query" && tokens[start + 1]?.kind === "word" && tokens[start + 1]?.text === "plan") start += 2;
260
+ }
261
+ const { ctes, declarations, main } = cteNamesAndMainToken(tokens, start);
262
+ const keyword = tokens[main]?.kind === "word" ? tokens[main]?.text ?? "" : "";
263
+ const writes = keyword === "insert" || keyword === "update" || keyword === "delete" || keyword === "replace" ||
264
+ keyword === "create" || keyword === "drop" || keyword === "alter";
265
+
266
+ if (keyword === "attach" || keyword === "detach" || keyword === "vacuum") {
267
+ return { error: "not authorized to access databases outside the relational store", writes };
268
+ }
269
+ if (ddlTargetsTempSchema(tokens, main, keyword)) {
270
+ return { error: "TEMP schema objects are not authorized because native reads use a separate connection", writes };
271
+ }
272
+ if (denyTransactions && (keyword === "begin" || keyword === "commit" || keyword === "end" || keyword === "rollback" || keyword === "savepoint" || keyword === "release")) {
273
+ return { error: "transaction control is not authorized", writes };
274
+ }
275
+ if (keyword === "pragma") {
276
+ let nameAt = main + 1;
277
+ if (tokens[nameAt + 1]?.text === ".") nameAt += 2;
278
+ const name = sqliteName(tokens[nameAt]);
279
+ const value = tokens[nameAt + 1];
280
+ if (name !== null && relationalOwnedPragmas.has(name) && value !== undefined) {
281
+ return { error: `PRAGMA ${name} is not authorized`, writes };
282
+ }
283
+ }
284
+
285
+ if (keyword === "create") {
286
+ const virtualAt = tokens.findIndex((token, index) => index > main && token.kind === "word" && token.text === "virtual");
287
+ const usingAt = tokens.findIndex((token, index) => index > virtualAt && token.kind === "word" && token.text === "using");
288
+ if (virtualAt >= 0 && usingAt >= 0) {
289
+ const module = sqliteName(tokens[usingAt + 1]) ?? "";
290
+ if (!relationalVirtualTableModules.has(module)) {
291
+ return { error: `virtual table module ${module || "<unknown>"} is not authorized`, writes };
292
+ }
293
+ }
294
+ }
295
+
296
+ let declaredTableAt = -1;
297
+ if (keyword === "create") {
298
+ const tableAt = tokens.findIndex((token, index) => index > main && token.kind === "word" && token.text === "table");
299
+ if (tableAt >= 0) {
300
+ declaredTableAt = tableAt + 1;
301
+ if (tokens[declaredTableAt]?.kind === "word" && tokens[declaredTableAt]?.text === "if") declaredTableAt += 3;
302
+ if (tokens[declaredTableAt + 1]?.text === ".") declaredTableAt += 2;
303
+ }
304
+ }
305
+
306
+ for (let at = 0; at + 1 < tokens.length; at++) {
307
+ const name = tokenName(tokens[at]);
308
+ if (name === null || tokens[at + 1]?.text !== "(") continue;
309
+ if (at !== declaredTableAt && !declarations.has(at) && (relationalOptionalFunctions.has(name) || name.startsWith("geopoly_"))) {
310
+ return { error: `SQLite function ${name} is not authorized because it is unavailable in the packaged runtime`, writes };
311
+ }
312
+ }
313
+
314
+ for (const reference of relationalTableReferences(sql)) {
315
+ if (reference.schema === "temp") {
316
+ return { error: "TEMP schema objects are not authorized because native reads use a separate connection", writes };
317
+ }
318
+ if (relationalUnavailableReadTables.has(reference.table) && (reference.schema !== null || !ctes.has(reference.table))) {
319
+ return { error: `SQLite table ${reference.table} is not authorized because it is unavailable in the packaged runtime`, writes };
320
+ }
321
+ }
322
+ return { error: null, writes };
323
+ }
324
+
325
+ function ddlTargetsTempSchema(tokens: readonly SqlToken[], main: number, keyword: string): boolean {
326
+ if (keyword !== "create" && keyword !== "drop" && keyword !== "alter") return false;
327
+ let at = main + 1;
328
+ if (keyword === "create" && (sqliteName(tokens[at]) === "temp" || sqliteName(tokens[at]) === "temporary")) return true;
329
+ if (keyword === "create" && sqliteName(tokens[at]) === "unique") at += 1;
330
+ if (keyword === "create" && sqliteName(tokens[at]) === "virtual") at += 1;
331
+ if (!["table", "index", "trigger", "view"].includes(sqliteName(tokens[at]) ?? "")) return false;
332
+ at += 1;
333
+ if (sqliteName(tokens[at]) === "if") at += keyword === "create" ? 3 : 2;
334
+ return sqliteName(tokens[at]) === "temp" && tokens[at + 1]?.text === ".";
335
+ }
336
+
337
+ export function relationalRuntimePolicy(
338
+ action: number,
339
+ first: string | null,
340
+ second: string | null,
341
+ ): number {
342
+ if (action === sqliteConstants.SQLITE_ATTACH || action === sqliteConstants.SQLITE_DETACH) {
343
+ return sqliteConstants.SQLITE_DENY;
344
+ }
345
+ if (relationalTempSchemaActions.has(action)) {
346
+ return sqliteConstants.SQLITE_DENY;
347
+ }
348
+ if (action === sqliteConstants.SQLITE_PRAGMA && second !== null && relationalOwnedPragmas.has((first ?? "").toLowerCase())) {
349
+ return sqliteConstants.SQLITE_DENY;
350
+ }
351
+ if (action === sqliteConstants.SQLITE_CREATE_VTABLE && !relationalVirtualTableModules.has((second ?? "").toLowerCase())) {
352
+ return sqliteConstants.SQLITE_DENY;
353
+ }
354
+ if (action === sqliteConstants.SQLITE_READ && relationalUnavailableReadTables.has((first ?? "").toLowerCase())) {
355
+ return sqliteConstants.SQLITE_DENY;
356
+ }
357
+ if (action === sqliteConstants.SQLITE_FUNCTION) {
358
+ const name = (second ?? first ?? "").toLowerCase();
359
+ if (relationalOptionalFunctions.has(name) || name.startsWith("geopoly_")) {
360
+ return sqliteConstants.SQLITE_DENY;
361
+ }
362
+ }
363
+ return sqliteConstants.SQLITE_OK;
364
+ }
@@ -70,7 +70,10 @@ export type Declaration = tsImpl.Declaration;
70
70
  /// except `useUnknownInCatchVariables` (see below), where the subset checker
71
71
  /// itself is the stricter authority — so the 6-to-7 provider swap changes no
72
72
  /// acceptance decision.
73
- export function subsetCompilerOptions(): tsImpl.CompilerOptions {
73
+ export function subsetCompilerOptions(
74
+ coreModulePath: string = sdkCoreModulePath,
75
+ generatedServicesPath?: string,
76
+ ): tsImpl.CompilerOptions {
74
77
  return {
75
78
  strict: true,
76
79
  // The one strict-family knob turned OFF: the subset's own checker types
@@ -88,7 +91,10 @@ export function subsetCompilerOptions(): tsImpl.CompilerOptions {
88
91
  // their published names. Absolute mappings so entry files anywhere
89
92
  // (tmp dirs, workspaces) resolve the same modules.
90
93
  paths: {
91
- "@native-sdk/core": [sdkCoreModulePath.replace(/\.ts$/, "")],
94
+ "@native-sdk/core": [coreModulePath.replace(/\.ts$/, "")],
95
+ ...(generatedServicesPath
96
+ ? { "@native-sdk/services": [generatedServicesPath.replace(/\.ts$/, "")] }
97
+ : {}),
92
98
  ...Object.fromEntries(
93
99
  [...sdkLibraryModules].map(([name, p]) => [name, [p.replace(/\.ts$/, "")]]),
94
100
  ),
@@ -585,10 +591,32 @@ export function lineColumn(file: SourceFile, pos: number): { line: number; colum
585
591
  return { line: lc.line + 1, column: lc.character + 1 };
586
592
  }
587
593
 
588
- /// Build a checked program rooted at the app-core entry file. tsc resolves
589
- /// the whole import graph from it (relative modules under src/, the SDK
590
- /// modules by their published names), so a multi-file core needs no extra
591
- /// root names; modules.ts validates the graph's boundaries first.
592
- export function createSubsetProgram(entry: string): tsImpl.Program {
593
- return tsImpl.createProgram([entry, bytesTextMethodsDts], subsetCompilerOptions());
594
+ /// Build the one checked program used by both TypeScript classes. `roots`
595
+ /// includes the independently discovered src/services/**/*.ts modules: a
596
+ /// valid core never imports those files, so they cannot be discovered from
597
+ /// the entry root. The caller still passes only core files to the subset
598
+ /// checker and integer inference.
599
+ export function createSubsetProgram(
600
+ entry: string,
601
+ roots: readonly string[] = [entry],
602
+ virtualFiles: ReadonlyMap<string, string> = new Map(),
603
+ coreModulePath: string = sdkCoreModulePath,
604
+ ): tsImpl.Program {
605
+ const generatedServicesPath = [...virtualFiles.keys()].find((file) => path.basename(file) === "services.gen.ts");
606
+ const options = subsetCompilerOptions(coreModulePath, generatedServicesPath);
607
+ if (virtualFiles.size === 0) return tsImpl.createProgram([...new Set([entry, ...roots, bytesTextMethodsDts])], options);
608
+ const host = tsImpl.createCompilerHost(options);
609
+ const virtual = new Map([...virtualFiles].map(([file, source]) => [path.resolve(file), source]));
610
+ const originalFileExists = host.fileExists.bind(host);
611
+ const originalReadFile = host.readFile.bind(host);
612
+ const originalGetSourceFile = host.getSourceFile.bind(host);
613
+ host.fileExists = (file) => virtual.has(path.resolve(file)) || originalFileExists(file);
614
+ host.readFile = (file) => virtual.get(path.resolve(file)) ?? originalReadFile(file);
615
+ host.getSourceFile = (file, languageVersion, onError, shouldCreateNewSourceFile) => {
616
+ const source = virtual.get(path.resolve(file));
617
+ return source === undefined
618
+ ? originalGetSourceFile(file, languageVersion, onError, shouldCreateNewSourceFile)
619
+ : tsImpl.createSourceFile(file, source, languageVersion, true, tsImpl.ScriptKind.TS);
620
+ };
621
+ return tsImpl.createProgram([...new Set([entry, ...roots, bytesTextMethodsDts])], options, host);
594
622
  }
@@ -63,7 +63,7 @@ Keep product-level metadata and policies in `app.zon`:
63
63
 
64
64
  Important manifest fields:
65
65
 
66
- - `id`: reverse-DNS bundle identifier. Used for bundle metadata and log/state paths.
66
+ - `id`: reverse-DNS bundle identifier, at most 128 bytes. Used for bundle metadata, credential service namespacing, and log/state paths.
67
67
  - `name`: short machine name.
68
68
  - `display_name`: human app name — shown by the application menu, Dock, app switcher, and About panel in dev runs and packaged bundles alike.
69
69
  - `description`: optional one-line About-panel description (max 256 bytes, single line).
@@ -19,6 +19,33 @@ Editors highlight `.native` markup well in HTML mode — the default scaffold wr
19
19
 
20
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
+ ## Menu-bar status items (TypeScript default)
23
+
24
+ Export `statusItem(model: Model): StatusItemState` from `src/core.ts`. The generated launcher installs icon/tooltip/click-open commands plus the boot presentation/menu, re-derives it after every committed update, and patches presentation/menu independently. Import `StatusItemState` from `@native-sdk/core/events`. Commands route through the core's `commandMsg(name): Msg | null` export. There is no app-owned Zig wiring and `statusItem` is automatically marked shell-bound for the markup lint.
25
+
26
+ ```ts
27
+ import { asciiBytes, utf8Bytes } from "@native-sdk/core";
28
+ import { type StatusItemState } from "@native-sdk/core/events";
29
+
30
+ export function statusItem(model: Model): StatusItemState {
31
+ return {
32
+ iconPath: asciiBytes("assets/menu-bar.svg"),
33
+ tooltip: utf8Bytes("Player status"),
34
+ activationCommand: asciiBytes("app.refresh"),
35
+ alternateActivationCommand: asciiBytes("player.toggle"),
36
+ openCommand: asciiBytes("app.refresh"),
37
+ presentation: { title: model.playing ? utf8Bytes("MB PLAY") : utf8Bytes("MB"), width: 62, tone: "normal", iconOpacity: 1, monospaced: true },
38
+ items: [
39
+ { id: 1, label: utf8Bytes("Open"), command: asciiBytes("app.open"), separator: false, enabled: true, detail: asciiBytes(""), role: "command", key: asciiBytes(""), modifiers: { primary: false, command: false, control: false, option: false, shift: false } },
40
+ { id: 0, label: asciiBytes(""), command: asciiBytes(""), separator: true, enabled: false, detail: asciiBytes(""), role: "command", key: asciiBytes(""), modifiers: { primary: false, command: false, control: false, option: false, shift: false } },
41
+ { id: 2, label: model.playing ? utf8Bytes("Pause") : utf8Bytes("Play"), command: asciiBytes("player.toggle"), separator: false, enabled: true, detail: utf8Bytes("configured ✓"), role: "agent", key: asciiBytes(""), modifiers: { primary: false, command: false, control: false, option: false, shift: false } },
42
+ ],
43
+ };
44
+ }
45
+ ```
46
+
47
+ Presentation fields are `title`, `width`, `tone`, `iconOpacity`, and `monospaced`. Rows add secondary `detail`, a semantic `command | info | header | hero | agent | context` role, a key equivalent, and all five modifier booleans to the ordinary id/label/command/separator/enabled fields. Actionable rows need unique non-zero whole u32 ids; separators conventionally use id 0, and the menu cap is 32 rows. `examples/menu-bar` is the full TypeScript + Native markup hide/Open/Quit lifecycle. The lower-level Zig `Options.status_item` / `status_item_fn` recipe appears below for Zig cores and custom wiring.
48
+
22
49
  ## App wiring (Zig cores and extensions only)
23
50
 
24
51
  A default TypeScript app writes none of this: generated wiring connects `src/core.ts`, `src/app.native`, and `app.zon`. Use the following only when the existing app has a Zig core or the task explicitly requires owned runtime wiring.
@@ -86,6 +113,8 @@ URL changes navigate; bumping `reload_token` reloads the same URL (the CenterPan
86
113
 
87
114
  ### Menu-bar extra (status item)
88
115
 
116
+ This is the Zig-core/custom-wiring form. Default TypeScript apps use the exported `statusItem(model)` helper above.
117
+
89
118
  `Options.status_item` installs a macOS `NSStatusItem` once, on the installing frame; its menu items dispatch commands through the same `on_command` mapping the toolbar and menus use (source `.tray`):
90
119
 
91
120
  ```zig
@@ -683,6 +712,24 @@ File rules:
683
712
  - Writes replace the file whole; `writeFile` bytes are copied at call time so the caller's buffer is immediately reusable. Reads deliver drain-scratch bytes — copy what the model keeps.
684
713
  - In the fake executor: `pendingFileAt(0)` records `key`/`op`/`path`/`bytes` for assertions; `feedFileResult(key, .ok, "{...}")` answers a read (over-bound content is cut and rewritten to `.truncated`, mirroring the real reader), `feedFileResult(key, .ok, "")` acknowledges a write; failure outcomes pass through as fed.
685
714
 
715
+ `fx.credentialsSet` / `fx.credentialsGet` / `fx.credentialsDelete` are the only place authentication tokens, passwords, and similar app secrets belong. Declare both `.capabilities = .{ "credentials" }` and `.permissions = .{ "credentials" }` in `app.zon`; the stable app id is the OS keychain service namespace, while the supplied key is its account. Never copy a fetched secret into Model: consume the drain-scratch `result.bytes` immediately while constructing the next effect, so persistence, state fingerprints, and diagnostics cannot capture it.
716
+
717
+ ```zig
718
+ pub const Msg = union(enum) {
719
+ load_token,
720
+ token_result: native_sdk.EffectCredentialsResult,
721
+ };
722
+
723
+ .load_token => fx.credentialsGet(.{
724
+ .key = 41,
725
+ .credential_key = "api-token", // UTF-8, 1..256 bytes
726
+ .on_result = Effects.credentialsMsg(.token_result),
727
+ }),
728
+ .token_result => |result| model.useTokenNow(result), // COPY nothing into Model
729
+ ```
730
+
731
+ Credential effects have their own four worker slots and file-style replacement: reissuing a key cancels the old operation silently and starts the new one. `result.outcome` is closed: `.ok`, `.miss`, `.denied`, `.locked`, `.io_failed`, `.over_bound`, or `.rejected`; get secrets are binary-safe and bounded at 2,560 bytes (the cross-platform floor set by WinCred), and delete is idempotent. Session recording elides every secret and replay delivers same-length placeholder bytes, so replay can verify control flow but cannot authenticate with the original value. Tests stay hermetic with `TestHarness(App).createWithCredentials(...)`; they never open the developer's live keychain.
732
+
686
733
  `fx.writeClipboard` / `fx.readClipboard` put text on (and read it from) the system clipboard through the platform pasteboard — the same seam the runtime's cmd+C copy uses. Never spawn `pbcopy`/`pbpaste`/`xclip` for this. Same discipline: key-based (shared key space and 16 slots), exactly one terminal Msg with an explicit outcome. The pasteboard call is synchronous on the loop thread (no worker), but the result still arrives as an ordinary Msg on the next drain:
687
734
 
688
735
  ```zig