@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,253 @@
1
+ #!/usr/bin/env node
2
+ // Mechanical diff of two scriptc surface manifests, keyed by their
3
+ // stable entry ids — the pre-flight for every compiler pin move. The
4
+ // manifest (schemaVersion 1) is the compiler's own machine-readable
5
+ // statement of what compiles (`static`), what needs the dynamic engine
6
+ // this SDK never enables (`dynamic-only`), and what refuses with which
7
+ // SC code (`unsupported`); diffing old pin against candidate turns
8
+ // "what changed upstream?" into a checklist instead of folklore:
9
+ //
10
+ // - entries flipped to static -> compile fixtures to add BEFORE
11
+ // the pin moves (supported must
12
+ // compile; each watched flip also
13
+ // names the repository layers to
14
+ // re-audit without assuming their
15
+ // independent constraints retire)
16
+ // - tier regressions -> surface the candidate REMOVED;
17
+ // audit before moving anything
18
+ // - new / removed entries -> projection growth or upstream
19
+ // renames (a rename shows as
20
+ // remove+add; ids are stable, so
21
+ // treat removals as suspect)
22
+ // - semantic note / SC-code moves -> teaching text and fence codes
23
+ // that docs or checks may echo
24
+ // - coverage-statement changes -> the projection's scope or profile
25
+ // changed even when its rows did not
26
+ //
27
+ // node surface_manifest_diff.mjs <old> <new> [--json]
28
+ //
29
+ // <old>/<new> each resolve, in order: a surface-manifest.json path; a
30
+ // directory containing one (directly, or under its
31
+ // node_modules/@scriptc/compiler/); the word "pinned" (the compiler
32
+ // declared in this package, with stale installs refused); or a version
33
+ // X.Y.Z, accepted only if it matches the installed compiler — other
34
+ // versions must be fetched by hand
35
+ // (`npm pack @scriptc/compiler@X.Y.Z`, extract package/surface-manifest.json)
36
+ // so this tool stays offline like the builds it serves.
37
+ //
38
+ // Exit 0: diff printed (including "no differences"). Exit 2: unusable
39
+ // input (unresolvable spec, unknown schema version).
40
+
41
+ import fs from "node:fs";
42
+ import path from "node:path";
43
+ import { fileURLToPath } from "node:url";
44
+
45
+ const KNOWN_SCHEMA_VERSION = 1;
46
+ const coreRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
47
+ const pinnedManifestPath = path.join(
48
+ coreRoot, "node_modules", "@scriptc", "compiler", "surface-manifest.json");
49
+ const packagePath = path.join(coreRoot, "package.json");
50
+
51
+ // Entries whose flip to `static` changes the compiler premise beneath
52
+ // concrete machinery or teaching in this repository, so the diff can say
53
+ // "this flip has an audit attached" instead of relying on memory. A compiler
54
+ // flip does not, by itself, retire Native's service contract or runtime
55
+ // constraints: those layers must change and prove the wider surface first.
56
+ // Staging transforms with no projected manifest entry yet (readonly-array
57
+ // erasure, alias folding/dedupe, record storage in stage_external_core.mjs)
58
+ // are not listed —
59
+ // absence from the manifest means "not projected", and their eventual
60
+ // entries will surface in the added-entries section first.
61
+ const STATIC_FLIP_AUDITS = {
62
+ "diagnostic.sc1012": "compiler-level default import/export caveats; service operations remain named-export only until contract dispatch changes",
63
+ "diagnostic.sc1013": "namespace-import caveats in service authoring docs/skills",
64
+ "diagnostic.sc1014": "compiler-level re-export/export-list caveats; service operations still require direct declarations until contract extraction changes",
65
+ "diagnostic.sc1031": "destructuring caveats in service authoring docs/skills",
66
+ "diagnostic.sc1070": "compiler-level async/await caveats; service operations remain synchronous until contract and runtime support change",
67
+ "diagnostic.sc1071": "compiler-level generator caveats; service operations remain non-generator until contract and runtime support change",
68
+ "syntax.typeof-expressions": "typeof caveats in service authoring docs/skills",
69
+ "syntax.spread-arguments": "spread-argument caveats in service authoring docs/skills",
70
+ };
71
+
72
+ function fail(message) {
73
+ console.error(`surface_manifest_diff: ${message}`);
74
+ process.exit(2);
75
+ }
76
+
77
+ function loadManifest(file, spec) {
78
+ let manifest;
79
+ try {
80
+ manifest = JSON.parse(fs.readFileSync(file, "utf8"));
81
+ } catch (error) {
82
+ fail(`cannot read manifest for '${spec}' at ${file}: ${error.message}`);
83
+ }
84
+ if (manifest.schemaVersion !== KNOWN_SCHEMA_VERSION) {
85
+ fail(`'${spec}' has manifest schemaVersion ${manifest.schemaVersion}; this tool knows version ${KNOWN_SCHEMA_VERSION} — update the tool before trusting the diff`);
86
+ }
87
+ if (!Array.isArray(manifest.entries)) fail(`'${spec}' has no entries array`);
88
+ return { file, manifest };
89
+ }
90
+
91
+ function declaredCompilerPin() {
92
+ let pkg;
93
+ try {
94
+ pkg = JSON.parse(fs.readFileSync(packagePath, "utf8"));
95
+ } catch (error) {
96
+ fail(`cannot read the scriptc pin from ${packagePath}: ${error.message}`);
97
+ }
98
+ const pin = pkg.dependencies?.scriptc;
99
+ if (typeof pin !== "string") fail(`${packagePath} has no dependencies.scriptc pin`);
100
+ return pin;
101
+ }
102
+
103
+ function resolveSpec(spec) {
104
+ if (spec === "pinned") {
105
+ if (!fs.existsSync(pinnedManifestPath)) {
106
+ fail("the pinned compiler is not installed — run `npm ci --include=dev` in the SDK's packages/core");
107
+ }
108
+ const pinned = loadManifest(pinnedManifestPath, spec);
109
+ const declared = declaredCompilerPin();
110
+ if (pinned.manifest.compilerVersion !== declared) {
111
+ fail(`installed compiler manifest is ${pinned.manifest.compilerVersion} but packages/core/package.json pins scriptc ${declared} — run \`npm ci --include=dev\` in packages/core`);
112
+ }
113
+ return pinned;
114
+ }
115
+ if (fs.existsSync(spec)) {
116
+ const stat = fs.statSync(spec);
117
+ if (stat.isFile()) return loadManifest(spec, spec);
118
+ for (const candidate of [
119
+ path.join(spec, "surface-manifest.json"),
120
+ path.join(spec, "node_modules", "@scriptc", "compiler", "surface-manifest.json"),
121
+ ]) {
122
+ if (fs.existsSync(candidate)) return loadManifest(candidate, spec);
123
+ }
124
+ fail(`directory '${spec}' contains no surface-manifest.json (looked directly and under node_modules/@scriptc/compiler/)`);
125
+ }
126
+ if (/^\d+\.\d+\.\d+$/.test(spec)) {
127
+ if (fs.existsSync(pinnedManifestPath)) {
128
+ const pinned = loadManifest(pinnedManifestPath, spec);
129
+ if (pinned.manifest.compilerVersion === spec) return pinned;
130
+ fail(`version ${spec} is not the installed compiler (${pinned.manifest.compilerVersion}) — fetch its manifest by hand (npm pack @scriptc/compiler@${spec}, extract package/surface-manifest.json) and pass the path`);
131
+ }
132
+ fail(`version ${spec} cannot be resolved: the pinned compiler is not installed — run \`npm ci --include=dev\` in the SDK's packages/core`);
133
+ }
134
+ fail(`cannot resolve '${spec}': not a file, not a directory, not "pinned", not an installed version`);
135
+ }
136
+
137
+ const args = process.argv.slice(2);
138
+ const json = args.includes("--json");
139
+ const specs = args.filter((a) => a !== "--json");
140
+ if (specs.length !== 2) {
141
+ console.error("usage: surface_manifest_diff.mjs <old> <new> [--json]");
142
+ console.error(' <old>/<new>: manifest path | directory | "pinned" | installed version X.Y.Z');
143
+ process.exit(2);
144
+ }
145
+
146
+ const oldSide = resolveSpec(specs[0]);
147
+ const newSide = resolveSpec(specs[1]);
148
+
149
+ const byId = (m) => new Map(m.entries.map((e) => [e.id, e]));
150
+ const oldById = byId(oldSide.manifest);
151
+ const newById = byId(newSide.manifest);
152
+ const oldCoverage = new Set(oldSide.manifest.coverage ?? []);
153
+ const newCoverage = new Set(newSide.manifest.coverage ?? []);
154
+
155
+ // Tier order for regression detection: losing ground means moving DOWN.
156
+ const TIER_RANK = { static: 2, "dynamic-only": 1, unsupported: 0 };
157
+ const rank = (status) => TIER_RANK[status] ?? -1;
158
+
159
+ const summarize = (e) => ({
160
+ id: e.id, kind: e.kind, name: e.name, status: e.status,
161
+ ...(e.code !== undefined && { code: e.code }),
162
+ ...(e.note !== undefined && { note: e.note }),
163
+ });
164
+
165
+ const diff = {
166
+ old: { version: oldSide.manifest.compilerVersion, entries: oldSide.manifest.entries.length, file: oldSide.file },
167
+ new: { version: newSide.manifest.compilerVersion, entries: newSide.manifest.entries.length, file: newSide.file },
168
+ flippedToStatic: [], // any status -> static
169
+ tierRegressions: [], // static -> dynamic-only/unsupported, dynamic-only -> unsupported
170
+ otherTierMoves: [], // unsupported -> dynamic-only (eased, but still unusable without --dynamic)
171
+ added: [],
172
+ removed: [],
173
+ codeChanges: [], // SC code moved, including alongside a tier move
174
+ noteChanges: [], // semantic note changed, including alongside a tier move
175
+ nameChanges: [], // same id, display name changed
176
+ followUpAudits: [], // repository layers to re-audit for watched static flips
177
+ coverageChanges: {
178
+ added: [...newCoverage].filter((statement) => !oldCoverage.has(statement)),
179
+ removed: [...oldCoverage].filter((statement) => !newCoverage.has(statement)),
180
+ },
181
+ };
182
+
183
+ for (const [id, oldEntry] of oldById) {
184
+ const newEntry = newById.get(id);
185
+ if (!newEntry) { diff.removed.push(summarize(oldEntry)); continue; }
186
+ if (oldEntry.status !== newEntry.status) {
187
+ const move = { ...summarize(newEntry), oldStatus: oldEntry.status, ...(oldEntry.code !== undefined && { oldCode: oldEntry.code }) };
188
+ if (newEntry.status === "static") {
189
+ diff.flippedToStatic.push(move);
190
+ if (STATIC_FLIP_AUDITS[id]) diff.followUpAudits.push({ id, audit: STATIC_FLIP_AUDITS[id] });
191
+ } else if (rank(newEntry.status) < rank(oldEntry.status)) {
192
+ diff.tierRegressions.push(move);
193
+ } else {
194
+ diff.otherTierMoves.push(move);
195
+ }
196
+ }
197
+ if (oldEntry.code !== newEntry.code) {
198
+ diff.codeChanges.push({ id, kind: newEntry.kind, name: newEntry.name, status: newEntry.status, oldCode: oldEntry.code, newCode: newEntry.code });
199
+ }
200
+ if (oldEntry.note !== newEntry.note) {
201
+ diff.noteChanges.push({ id, kind: newEntry.kind, name: newEntry.name, status: newEntry.status, oldNote: oldEntry.note, newNote: newEntry.note });
202
+ }
203
+ if (oldEntry.name !== newEntry.name) {
204
+ diff.nameChanges.push({ id, kind: newEntry.kind, oldName: oldEntry.name, newName: newEntry.name });
205
+ }
206
+ }
207
+ for (const [id, newEntry] of newById) {
208
+ if (!oldById.has(id)) diff.added.push(summarize(newEntry));
209
+ }
210
+
211
+ if (json) {
212
+ console.log(JSON.stringify(diff, null, 2));
213
+ process.exit(0);
214
+ }
215
+
216
+ const line = (e) => {
217
+ const code = e.code ? ` ${e.code}` : "";
218
+ const from = e.oldStatus ? `${e.oldStatus} -> ` : "";
219
+ return ` ${e.id} [${from}${e.status}]${code} ${e.name}`;
220
+ };
221
+ const clip = (text, max = 110) =>
222
+ text === undefined ? "(none)" : text.length <= max ? text : `${text.slice(0, max - 1)}…`;
223
+
224
+ console.log(`surface manifest diff: ${diff.old.version} (${diff.old.entries} entries) -> ${diff.new.version} (${diff.new.entries} entries)`);
225
+
226
+ const section = (title, items, render) => {
227
+ console.log(`\n${title}: ${items.length}`);
228
+ for (const item of items) console.log(render(item));
229
+ };
230
+
231
+ section("flipped to static (add compile fixtures before any pin move)", diff.flippedToStatic, line);
232
+ if (diff.followUpAudits.length > 0) {
233
+ console.log("\n follow-up audits due with these flips (compiler support alone does not retire Native contract/runtime constraints):");
234
+ for (const item of diff.followUpAudits) console.log(` ${item.id} audit: ${item.audit}`);
235
+ }
236
+ section("tier regressions (the candidate REMOVED surface — audit before moving)", diff.tierRegressions, line);
237
+ section("eased to dynamic-only (still unusable: this SDK never passes --dynamic)", diff.otherTierMoves, line);
238
+ section("new entries", diff.added, line);
239
+ section("removed entries (stable ids should not vanish — suspect a rename or projection change)", diff.removed, line);
240
+ section("SC-code changes", diff.codeChanges,
241
+ (c) => ` ${c.id} ${c.oldCode ?? "(none)"} -> ${c.newCode ?? "(none)"} ${c.name}`);
242
+ section("semantic note changes", diff.noteChanges, (c) =>
243
+ ` ${c.id} ${c.name}\n old: ${clip(c.oldNote)}\n new: ${clip(c.newNote)}`);
244
+ section("name changes", diff.nameChanges, (c) => ` ${c.id} "${c.oldName}" -> "${c.newName}"`);
245
+ section("coverage statements added (candidate scope)", diff.coverageChanges.added,
246
+ (statement) => ` + ${statement}`);
247
+ section("coverage statements removed (old scope)", diff.coverageChanges.removed,
248
+ (statement) => ` - ${statement}`);
249
+
250
+ const total = diff.flippedToStatic.length + diff.tierRegressions.length + diff.otherTierMoves.length
251
+ + diff.added.length + diff.removed.length + diff.codeChanges.length + diff.noteChanges.length
252
+ + diff.nameChanges.length + diff.coverageChanges.added.length + diff.coverageChanges.removed.length;
253
+ if (total === 0) console.log("\nno differences.");
@@ -0,0 +1,189 @@
1
+ #!/usr/bin/env node
2
+ // Resolve explicit npm versions only during `native vendor`, then copy every
3
+ // resolved package into the app-owned service vendor tree. Builds never run
4
+ // npm and accept these bytes only after verifying the manifest hash.
5
+
6
+ import crypto from "node:crypto";
7
+ import fs from "node:fs";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import { spawnSync } from "node:child_process";
11
+ import { fileURLToPath } from "node:url";
12
+
13
+ function packageContentHash(root) {
14
+ const files = [];
15
+ const walk = (current, prefix = "") => {
16
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
17
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
18
+ const absolute = path.join(current, entry.name);
19
+ if (entry.isSymbolicLink()) throw new Error(`package contains a symlink: ${rel}`);
20
+ if (entry.isDirectory()) walk(absolute, rel);
21
+ else if (entry.isFile()) files.push({ rel, absolute });
22
+ }
23
+ };
24
+ walk(root);
25
+ files.sort((a, b) => a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0);
26
+ const hash = crypto.createHash("sha256");
27
+ hash.update("native-sdk.service-package.v1\0");
28
+ for (const file of files) {
29
+ const bytes = fs.readFileSync(file.absolute);
30
+ const size = Buffer.alloc(8);
31
+ size.writeBigUInt64LE(BigInt(bytes.length));
32
+ hash.update(file.rel);
33
+ hash.update("\0");
34
+ hash.update(size);
35
+ hash.update(bytes);
36
+ }
37
+ return hash.digest("hex");
38
+ }
39
+
40
+ function packageDirectories(nodeModules) {
41
+ const out = [];
42
+ for (const entry of fs.readdirSync(nodeModules, { withFileTypes: true })) {
43
+ if (!entry.isDirectory() || entry.name === ".bin") continue;
44
+ if (entry.name.startsWith("@")) {
45
+ for (const child of fs.readdirSync(path.join(nodeModules, entry.name), { withFileTypes: true })) {
46
+ if (child.isDirectory()) out.push(path.join(nodeModules, entry.name, child.name));
47
+ }
48
+ } else out.push(path.join(nodeModules, entry.name));
49
+ }
50
+ return out;
51
+ }
52
+
53
+ function servicePackagesField(source) {
54
+ const marker = /(^|\n)[ \t]*\.service_packages[ \t]*=[ \t]*\.\{/m;
55
+ const match = marker.exec(source);
56
+ if (!match) return null;
57
+ const fieldStart = match.index + match[1].length;
58
+ const open = source.indexOf("{", fieldStart);
59
+ let at = open;
60
+ let depth = 0;
61
+ let string = false;
62
+ let escaped = false;
63
+ for (; at < source.length; at++) {
64
+ const char = source[at];
65
+ if (string) {
66
+ if (escaped) escaped = false;
67
+ else if (char === "\\") escaped = true;
68
+ else if (char === '"') string = false;
69
+ continue;
70
+ }
71
+ if (char === '"') string = true;
72
+ else if (char === "{") depth++;
73
+ else if (char === "}" && --depth === 0) {
74
+ let end = at + 1;
75
+ while (/[ \t]/.test(source[end] ?? "")) end++;
76
+ if (source[end] === ",") end++;
77
+ return { fieldStart, open, close: at, end };
78
+ }
79
+ }
80
+ throw new Error("app.zon service_packages field is not balanced");
81
+ }
82
+
83
+ export function readServicePackages(source) {
84
+ const field = servicePackagesField(source);
85
+ if (!field) return [];
86
+ const body = source.slice(field.open + 1, field.close);
87
+ const entries = [];
88
+ const pattern = /\.\{\s*\.name\s*=\s*("(?:\\.|[^"\\])*")\s*,\s*\.version\s*=\s*("(?:\\.|[^"\\])*")\s*,\s*\.content_hash\s*=\s*("(?:\\.|[^"\\])*")\s*,?\s*\}/g;
89
+ for (const match of body.matchAll(pattern)) {
90
+ const name = JSON.parse(match[1]);
91
+ const version = JSON.parse(match[2]);
92
+ const contentHash = JSON.parse(match[3]);
93
+ if (typeof name !== "string" || typeof version !== "string" || typeof contentHash !== "string") {
94
+ throw new Error("app.zon service_packages contains a non-string package fact");
95
+ }
96
+ entries.push({ name, version, content_hash: contentHash });
97
+ }
98
+ const declaredCount = body.match(/\.name\s*=/g)?.length ?? 0;
99
+ if (entries.length !== declaredCount) throw new Error("app.zon service_packages is not in the package-fact shape written by native vendor");
100
+ return entries;
101
+ }
102
+
103
+ function packageNameFromSpec(spec) {
104
+ return spec.slice(0, spec.lastIndexOf("@"));
105
+ }
106
+
107
+ export function mergePackageSpecs(source, requested) {
108
+ const specs = new Map(readServicePackages(source).map((entry) => [entry.name, `${entry.name}@${entry.version}`]));
109
+ for (const spec of requested) specs.set(packageNameFromSpec(spec), spec);
110
+ return [...specs].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, spec]) => spec);
111
+ }
112
+
113
+ export function replaceServicePackages(source, entries) {
114
+ const rendered = [
115
+ " .service_packages = .{",
116
+ ...entries.map((entry) => ` .{ .name = ${JSON.stringify(entry.name)}, .version = ${JSON.stringify(entry.version)}, .content_hash = ${JSON.stringify(entry.content_hash)} },`),
117
+ " },",
118
+ ].join("\n");
119
+ const field = servicePackagesField(source);
120
+ if (!field) {
121
+ const close = source.lastIndexOf("}");
122
+ if (close < 0) throw new Error("app.zon has no closing top-level brace");
123
+ return `${source.slice(0, close).trimEnd()}\n${rendered}\n${source.slice(close)}`;
124
+ }
125
+ return source.slice(0, field.fieldStart) + rendered + source.slice(field.end);
126
+ }
127
+
128
+ export function replaceVendorTree(vendorRoot, stageRoot) {
129
+ fs.mkdirSync(path.dirname(vendorRoot), { recursive: true });
130
+ fs.rmSync(vendorRoot, { recursive: true, force: true });
131
+ fs.renameSync(stageRoot, vendorRoot);
132
+ }
133
+
134
+ function main(argv) {
135
+ const appRoot = path.resolve(argv[2] ?? ".");
136
+ const requested = argv.slice(3);
137
+ if (requested.length === 0 || requested.some((spec) => !/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+@\d+\.\d+\.\d+$/i.test(spec))) {
138
+ console.error("usage: native vendor [dir] <package@exact-version> [more packages...]");
139
+ return 2;
140
+ }
141
+
142
+ const manifestPath = path.join(appRoot, "app.zon");
143
+ if (!fs.existsSync(manifestPath)) throw new Error(`${manifestPath} does not exist`);
144
+ const current = fs.readFileSync(manifestPath, "utf8");
145
+ const installSpecs = mergePackageSpecs(current, requested);
146
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "native-service-vendor-"));
147
+ const servicesRoot = path.join(appRoot, "src", "services");
148
+ const stageRoot = path.join(appRoot, ".native", `.service-vendor-stage-${process.pid}-${Date.now()}`);
149
+ try {
150
+ const install = spawnSync("npm", ["install", "--ignore-scripts", "--no-audit", "--no-fund", "--package-lock=false", "--prefix", work, ...installSpecs], { stdio: "inherit" });
151
+ if (install.status !== 0) return install.status ?? 1;
152
+ const nodeModules = path.join(work, "node_modules");
153
+ const packages = packageDirectories(nodeModules);
154
+ for (const packageDir of packages) {
155
+ if (fs.existsSync(path.join(packageDir, "node_modules"))) {
156
+ throw new Error("the resolved npm graph contains nested package versions; choose a dependency set npm can flatten before vendoring it for the static service tier");
157
+ }
158
+ }
159
+ fs.mkdirSync(stageRoot, { recursive: true });
160
+ const entries = [];
161
+ for (const packageDir of packages) {
162
+ const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf8"));
163
+ if (typeof manifest.name !== "string" || typeof manifest.version !== "string") throw new Error(`${packageDir} has no package identity`);
164
+ const destination = path.join(stageRoot, ...manifest.name.split("/"));
165
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
166
+ fs.cpSync(packageDir, destination, { recursive: true });
167
+ entries.push({ name: manifest.name, version: manifest.version, content_hash: packageContentHash(destination) });
168
+ }
169
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
170
+ const vendorRoot = path.join(servicesRoot, "vendor");
171
+ replaceVendorTree(vendorRoot, stageRoot);
172
+ fs.writeFileSync(manifestPath, replaceServicePackages(current, entries));
173
+ console.log(`vendored ${entries.length} package${entries.length === 1 ? "" : "s"} into src/services/vendor and updated app.zon`);
174
+ for (const entry of entries) console.log(` ${entry.name}@${entry.version} ${entry.content_hash}`);
175
+ return 0;
176
+ } finally {
177
+ fs.rmSync(stageRoot, { recursive: true, force: true });
178
+ fs.rmSync(work, { recursive: true, force: true });
179
+ }
180
+ }
181
+
182
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
183
+ try {
184
+ process.exitCode = main(process.argv);
185
+ } catch (error) {
186
+ console.error(error instanceof Error ? error.message : String(error));
187
+ process.exitCode = 1;
188
+ }
189
+ }
@@ -1,13 +1,33 @@
1
1
  export declare function asciiBytes(s: string): Uint8Array;
2
+ export declare function utf8Bytes(s: string): Uint8Array;
2
3
  export type Msgish = {
3
4
  readonly kind: string;
4
5
  };
6
+ /** Cooperative cancellation capability supplied by generated service hosts. */
7
+ export interface ServiceCancellation {
8
+ /** True after Cmd.cancel or the operation deadline requests cancellation. */
9
+ readonly cancelled: () => boolean;
10
+ /** Throw a boundary-tagged cancellation error when cancellation was requested. */
11
+ readonly throwIfCancelled: () => void;
12
+ }
5
13
  export type TimestampKind<M extends Msgish> = M extends Msgish ? {
6
14
  [K in Exclude<keyof M, "kind">]-?: M[K] extends number ? [Exclude<keyof M, "kind">] extends [K] ? M["kind"] : never : never;
7
15
  }[Exclude<keyof M, "kind">] : never;
8
16
  export type BytesKind<M extends Msgish> = M extends Msgish ? {
9
17
  [K in Exclude<keyof M, "kind">]-?: M[K] extends Uint8Array ? [Exclude<keyof M, "kind">] extends [K] ? M["kind"] : never : never;
10
18
  }[Exclude<keyof M, "kind">] : never;
19
+ export type ServiceKind<M extends Msgish, P> = M extends Msgish ? {
20
+ [K in Exclude<keyof M, "kind">]-?: M[K] extends P ? P extends M[K] ? [Exclude<keyof M, "kind">] extends [K] ? M["kind"] : never : never : never;
21
+ }[Exclude<keyof M, "kind">] : never;
22
+ export interface ServiceRoute<M extends Msgish, P> {
23
+ readonly key?: string;
24
+ readonly ok: ServiceKind<M, P>;
25
+ readonly err: BytesKind<M>;
26
+ }
27
+ export interface ServiceStreamRoute<M extends Msgish, P> extends ServiceRoute<M, P> {
28
+ readonly channelKey: number;
29
+ readonly event: ChannelEventKind<M>;
30
+ }
11
31
  export type EmptyKind<M extends Msgish> = M extends Msgish ? [Exclude<keyof M, "kind">] extends [never] ? M["kind"] : never : never;
12
32
  export type FetchedKind<M extends Msgish> = M extends Msgish ? {
13
33
  [K in Exclude<keyof M, "kind">]-?: M[K] extends Uint8Array ? Exclude<keyof M, "kind" | K> extends infer O ? O extends keyof M ? M[O] extends number ? [Exclude<keyof M, "kind" | K | O>] extends [never] ? M["kind"] : never : never : never : never : never;
@@ -116,6 +136,31 @@ export interface WriteRoute<M extends Msgish> {
116
136
  readonly ok: EmptyKind<M>;
117
137
  readonly err: BytesKind<M>;
118
138
  }
139
+ export interface StoreScanOptions {
140
+ readonly limit?: number;
141
+ readonly after?: string | Uint8Array;
142
+ }
143
+ export interface DbText {
144
+ readonly __dbText: true;
145
+ readonly bytes: ReadonlyArray<number>;
146
+ }
147
+ export declare function dbText(bytes: Uint8Array): DbText;
148
+ export type DbValue = null | number | string | Uint8Array | boolean | DbText;
149
+ export type DbStatement = readonly [sql: string, params: ReadonlyArray<DbValue>];
150
+ export interface DbRowsRoute<M extends Msgish> {
151
+ readonly key?: string;
152
+ readonly page: BytesKind<M>;
153
+ readonly done: EmptyKind<M>;
154
+ readonly err: BytesKind<M>;
155
+ }
156
+ export interface TypedRowsRoute<Row, M extends Msgish> extends DbRowsRoute<M> {
157
+ readonly __row?: Row;
158
+ }
159
+ export interface TypedDbStatement {
160
+ readonly sql: string;
161
+ readonly params: ReadonlyArray<DbValue>;
162
+ readonly __typedDbStatement: true;
163
+ }
119
164
  export interface FetchRoute<M extends Msgish> {
120
165
  readonly key?: string;
121
166
  readonly ok: FetchedKind<M>;
@@ -188,6 +233,7 @@ export interface NotificationSpec {
188
233
  readonly subtitle?: Uint8Array;
189
234
  readonly body?: Uint8Array;
190
235
  }
236
+ export type LocalTimeStyle = "date" | "time" | "datetime";
191
237
  export type Cmd<M extends Msgish> = {
192
238
  readonly op: "none";
193
239
  } | {
@@ -209,6 +255,18 @@ export type Cmd<M extends Msgish> = {
209
255
  readonly key: string;
210
256
  readonly okKind: string;
211
257
  readonly errKind: string;
258
+ readonly typedService: boolean;
259
+ readonly payload: Uint8Array;
260
+ } | {
261
+ readonly op: "service_stream_request";
262
+ readonly name: string;
263
+ readonly key: string;
264
+ readonly okKind: string;
265
+ readonly errKind: string;
266
+ readonly typedService: true;
267
+ readonly channelKey: number;
268
+ readonly eventKind: string;
269
+ readonly maxPending: number;
212
270
  readonly payload: Uint8Array;
213
271
  } | {
214
272
  readonly op: "cancel";
@@ -226,6 +284,47 @@ export type Cmd<M extends Msgish> = {
226
284
  readonly errKind: string;
227
285
  readonly path: Uint8Array;
228
286
  readonly bytes: Uint8Array;
287
+ } | {
288
+ readonly op: "store_set";
289
+ readonly key: string;
290
+ readonly okKind: string;
291
+ readonly errKind: string;
292
+ readonly storeKey: string;
293
+ readonly bytes: Uint8Array;
294
+ } | {
295
+ readonly op: "store_get" | "store_delete";
296
+ readonly key: string;
297
+ readonly okKind: string;
298
+ readonly errKind: string;
299
+ readonly storeKey: string;
300
+ } | {
301
+ readonly op: "store_scan";
302
+ readonly key: string;
303
+ readonly okKind: string;
304
+ readonly errKind: string;
305
+ readonly prefix: string;
306
+ readonly limit: number;
307
+ readonly after: string | Uint8Array;
308
+ } | {
309
+ readonly op: "store_set_many";
310
+ readonly key: string;
311
+ readonly okKind: string;
312
+ readonly errKind: string;
313
+ readonly entries: ReadonlyArray<readonly [string, Uint8Array]>;
314
+ } | {
315
+ readonly op: "db_query";
316
+ readonly key: string;
317
+ readonly pageKind: string;
318
+ readonly doneKind: string;
319
+ readonly errKind: string;
320
+ readonly sql: string;
321
+ readonly params: ReadonlyArray<DbValue>;
322
+ } | {
323
+ readonly op: "db_exec";
324
+ readonly key: string;
325
+ readonly okKind: string;
326
+ readonly errKind: string;
327
+ readonly statements: ReadonlyArray<DbStatement>;
229
328
  } | {
230
329
  readonly op: "fetch";
231
330
  readonly key: string;
@@ -312,6 +411,12 @@ export type Cmd<M extends Msgish> = {
312
411
  } | {
313
412
  readonly op: "window_show";
314
413
  readonly label: string;
414
+ } | {
415
+ readonly op: "window_hide";
416
+ readonly label: string;
417
+ } | {
418
+ readonly op: "dock_presence";
419
+ readonly visible: boolean;
315
420
  } | {
316
421
  readonly op: "quit_app";
317
422
  } | {
@@ -332,6 +437,7 @@ export type Cmd<M extends Msgish> = {
332
437
  readonly op: "channel_open";
333
438
  readonly key: number;
334
439
  readonly eventKind: string;
440
+ readonly maxPending: number;
335
441
  } | {
336
442
  readonly op: "channel_close";
337
443
  readonly key: number;
@@ -370,6 +476,15 @@ export type Cmd<M extends Msgish> = {
370
476
  readonly cmds: readonly Cmd<M>[];
371
477
  };
372
478
  export declare function hostRecordBytes(payload: HostRecord): Uint8Array;
479
+ export declare function serviceConcat(parts: readonly Uint8Array[]): Uint8Array;
480
+ export declare function serviceBoolBytes(value: boolean): Uint8Array;
481
+ export declare function serviceF64Bytes(value: number): Uint8Array;
482
+ export declare function serviceI64Bytes(value: number): Uint8Array;
483
+ export declare function serviceBytes(value: Uint8Array): Uint8Array;
484
+ export declare function serviceEnumBytes(index: number): Uint8Array;
485
+ export declare function serviceUnionBytes(index: number): Uint8Array;
486
+ export declare function serviceOptionalBytes(value: Uint8Array | null): Uint8Array;
487
+ export declare function serviceSliceBytes(values: readonly Uint8Array[]): Uint8Array;
373
488
  declare function hostCmd(name: string, payload: Uint8Array | HostRecord): Cmd<never>;
374
489
  declare function hostCmd(name: string, ...args: readonly number[]): Cmd<never>;
375
490
  declare function fetchCmd<M extends Msgish>(spec: FetchSpec, route: FetchRoute<M>): Cmd<M>;
@@ -380,13 +495,34 @@ export declare const Cmd: {
380
495
  now<M extends Msgish>(msgKind: TimestampKind<M>): Cmd<M>;
381
496
  host: typeof hostCmd;
382
497
  request<M extends Msgish>(name: string, payload: Uint8Array | HostRecord, route: RequestRoute<M>): Cmd<M>;
498
+ serviceRequest<M extends Msgish, P>(name: string, payload: Uint8Array, route: ServiceRoute<M, P>): Cmd<M>;
499
+ serviceStreamRequest<M extends Msgish, P>(name: string, channelKey: number, payload: Uint8Array, route: ServiceStreamRoute<M, P>, maxPending: number): Cmd<M>;
383
500
  cancel(key: string): Cmd<never>;
384
501
  readFile<M extends Msgish>(path: Uint8Array, route: RequestRoute<M>): Cmd<M>;
385
502
  writeFile<M extends Msgish>(path: Uint8Array, bytes: Uint8Array, route: WriteRoute<M>): Cmd<M>;
503
+ store: {
504
+ set<M extends Msgish>(storeKey: string, bytes: Uint8Array, route: WriteRoute<M>): Cmd<M>;
505
+ get<M extends Msgish>(storeKey: string, route: RequestRoute<M>): Cmd<M>;
506
+ delete<M extends Msgish>(storeKey: string, route: WriteRoute<M>): Cmd<M>;
507
+ scan<M extends Msgish>(prefix: string, options: StoreScanOptions, route: RequestRoute<M>): Cmd<M>;
508
+ setMany<M extends Msgish>(entries: ReadonlyArray<readonly [string, Uint8Array]>, route: WriteRoute<M>): Cmd<M>;
509
+ };
510
+ credentials: {
511
+ set<M extends Msgish>(credentialKey: string, secret: Uint8Array, route: WriteRoute<M>): Cmd<M>;
512
+ get<M extends Msgish>(credentialKey: string, route: RequestRoute<M>): Cmd<M>;
513
+ delete<M extends Msgish>(credentialKey: string, route: WriteRoute<M>): Cmd<M>;
514
+ };
515
+ db: {
516
+ query<M extends Msgish>(sql: string, params: ReadonlyArray<DbValue>, route: DbRowsRoute<M>): Cmd<M>;
517
+ exec<M extends Msgish>(statements: ReadonlyArray<DbStatement>, route: WriteRoute<M>): Cmd<M>;
518
+ };
386
519
  fetch: typeof fetchCmd;
387
520
  clipboardWrite(bytes: Uint8Array): Cmd<never>;
388
521
  clipboardRead<M extends Msgish>(route: RequestRoute<M>): Cmd<M>;
389
522
  showNotification(spec: NotificationSpec): Cmd<never>;
523
+ openExternalUrl(url: Uint8Array): Cmd<never>;
524
+ revealPath(path: Uint8Array): Cmd<never>;
525
+ formatLocalTime<M extends Msgish>(timestampMs: number, style: LocalTimeStyle, route: RequestRoute<M>): Cmd<M>;
390
526
  delay<M extends Msgish>(key: string, ms: number, msgKind: TimestampKind<M>): Cmd<M>;
391
527
  spawn<M extends Msgish>(argv: readonly Uint8Array[], route: SpawnRoute<M> | SpawnCollectRoute<M>): Cmd<M>;
392
528
  audioPlay<M extends Msgish>(key: string, source: AudioSource, route: AudioRoute<M>): Cmd<M>;
@@ -404,6 +540,10 @@ export declare const Cmd: {
404
540
  videoSetMuted(key: string, muted: boolean): Cmd<never>;
405
541
  videoSetLoop(key: string, loop: boolean): Cmd<never>;
406
542
  showWindow(label: string): Cmd<never>;
543
+ hideWindow(label: string): Cmd<never>;
544
+ setDockPresence(visible: boolean): Cmd<never>;
545
+ launchAtLoginStatus<M extends Msgish>(route: RequestRoute<M>): Cmd<M>;
546
+ setLaunchAtLogin<M extends Msgish>(enabled: boolean, route: RequestRoute<M>): Cmd<M>;
407
547
  quitApp(): Cmd<never>;
408
548
  imageLoad<M extends Msgish>(id: number, source: ImageSource, route: ImageRoute<M>): Cmd<M>;
409
549
  imageCancel(id: number): Cmd<never>;
@@ -425,6 +565,15 @@ export type Sub<M extends Msgish> = {
425
565
  readonly key: string;
426
566
  readonly everyMs: number;
427
567
  readonly msgKind: string;
568
+ } | {
569
+ readonly op: "db_live";
570
+ readonly key: string;
571
+ readonly pageKind: string;
572
+ readonly doneKind: string;
573
+ readonly errKind: string;
574
+ readonly sql: string;
575
+ readonly params: ReadonlyArray<DbValue>;
576
+ readonly tables: readonly string[];
428
577
  } | {
429
578
  readonly op: "batch";
430
579
  readonly subs: readonly Sub<M>[];