@native-sdk/cli 0.8.4 → 0.9.1

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 (161) hide show
  1. package/build/app.zig +1178 -74
  2. package/build.zig +715 -17
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +10 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +435 -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/merge_static_archives.mjs +78 -0
  12. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  13. package/packages/core/scripts/run_external_core_compiler.mjs +122 -6
  14. package/packages/core/scripts/run_external_service_compiler.mjs +280 -0
  15. package/packages/core/scripts/stage_external_core.mjs +9 -1
  16. package/packages/core/scripts/stage_external_services.mjs +172 -0
  17. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  18. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  19. package/packages/core/sdk/core.d.ts +224 -0
  20. package/packages/core/sdk/core.ts +694 -22
  21. package/packages/core/sdk/events.d.ts +89 -0
  22. package/packages/core/sdk/events.ts +128 -0
  23. package/packages/core/src/checker.ts +936 -15
  24. package/packages/core/src/cli.ts +156 -3
  25. package/packages/core/src/contract.ts +28 -5
  26. package/packages/core/src/devhost.ts +1876 -16
  27. package/packages/core/src/devhost_journal.mjs +183 -0
  28. package/packages/core/src/devhost_resolver.mjs +17 -1
  29. package/packages/core/src/devhost_service_worker.mjs +90 -0
  30. package/packages/core/src/diagnostics.ts +179 -22
  31. package/packages/core/src/frontend.ts +210 -34
  32. package/packages/core/src/infer.ts +24 -0
  33. package/packages/core/src/modules.ts +129 -80
  34. package/packages/core/src/service_contract.ts +597 -0
  35. package/packages/core/src/sqlite_cli.ts +93 -0
  36. package/packages/core/src/sqlite_codegen.ts +806 -0
  37. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  38. package/packages/core/src/typed_ast.ts +36 -8
  39. package/skill-data/automation/SKILL.md +1 -1
  40. package/skill-data/core/references/project-anatomy.md +1 -1
  41. package/skill-data/native-ui/SKILL.md +58 -5
  42. package/skill-data/ts-core/SKILL.md +123 -41
  43. package/skill-data/ts-services/SKILL.md +126 -0
  44. package/skill-data/ts-services/references/service-surface.md +604 -0
  45. package/skill-data/zig/SKILL.md +1 -1
  46. package/skills/native-sdk/SKILL.md +1 -1
  47. package/src/app_runner/no_migrations.zig +3 -0
  48. package/src/app_runner/no_services.zig +20 -0
  49. package/src/app_runner/root.zig +133 -4
  50. package/src/app_runner/ts_core_main.zig +254 -8
  51. package/src/app_runner/ts_core_mobile.zig +241 -0
  52. package/src/automation/protocol.zig +5 -1
  53. package/src/automation/snapshot.zig +31 -11
  54. package/src/embed/app_exports.zig +12 -1
  55. package/src/embed/c_api.zig +48 -2
  56. package/src/embed/conversions.zig +4 -5
  57. package/src/embed/host.zig +109 -1
  58. package/src/embed/root.zig +8 -0
  59. package/src/embed/tests.zig +241 -0
  60. package/src/embed/types.zig +51 -0
  61. package/src/embed/ui_host.zig +185 -5
  62. package/src/platform/android/NativeSdkActivity.java +131 -0
  63. package/src/platform/android/android_host.c +182 -1
  64. package/src/platform/android/native_sdk_app.h +17 -0
  65. package/src/platform/ios/native_sdk_app.h +17 -0
  66. package/src/platform/ios/uikit_host.m +115 -0
  67. package/src/platform/linux/cef_host.cpp +8 -2
  68. package/src/platform/linux/gtk_host.c +289 -22
  69. package/src/platform/linux/gtk_host.h +5 -1
  70. package/src/platform/linux/root.zig +109 -22
  71. package/src/platform/macos/appkit_host.h +24 -7
  72. package/src/platform/macos/appkit_host.m +686 -64
  73. package/src/platform/macos/cef_host.mm +400 -66
  74. package/src/platform/macos/root.zig +304 -47
  75. package/src/platform/null_platform.zig +435 -48
  76. package/src/platform/null_platform_tests.zig +113 -0
  77. package/src/platform/root.zig +19 -0
  78. package/src/platform/types.zig +281 -28
  79. package/src/platform/windows/root.zig +207 -27
  80. package/src/platform/windows/webview2_host.cpp +334 -51
  81. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  82. package/src/primitives/app_manifest/root.zig +4 -0
  83. package/src/primitives/app_manifest/tests.zig +3 -0
  84. package/src/primitives/app_manifest/types.zig +32 -0
  85. package/src/primitives/app_manifest/validation.zig +19 -1
  86. package/src/root.zig +53 -0
  87. package/src/runtime/api.zig +19 -0
  88. package/src/runtime/automation_commands.zig +35 -2
  89. package/src/runtime/automation_snapshot.zig +32 -20
  90. package/src/runtime/bridge_permission_tests.zig +58 -3
  91. package/src/runtime/bridge_responses.zig +4 -2
  92. package/src/runtime/builtin_bridge.zig +11 -1
  93. package/src/runtime/canvas_frame.zig +18 -11
  94. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  95. package/src/runtime/clock.zig +13 -1
  96. package/src/runtime/core.zig +145 -7
  97. package/src/runtime/credentials_store.zig +115 -0
  98. package/src/runtime/effects.zig +3701 -231
  99. package/src/runtime/effects_credentials_tests.zig +332 -0
  100. package/src/runtime/effects_file_tests.zig +587 -0
  101. package/src/runtime/effects_host_tests.zig +208 -1
  102. package/src/runtime/effects_notification_tests.zig +11 -0
  103. package/src/runtime/effects_relational_tests.zig +314 -0
  104. package/src/runtime/effects_store_tests.zig +211 -0
  105. package/src/runtime/file_access.zig +400 -0
  106. package/src/runtime/file_effect_crash_helper.zig +28 -0
  107. package/src/runtime/file_effect_crash_tests.zig +37 -0
  108. package/src/runtime/flow.zig +35 -10
  109. package/src/runtime/gpu_surface_events.zig +6 -1
  110. package/src/runtime/native_command_event_tests.zig +86 -2
  111. package/src/runtime/persist_store.zig +666 -0
  112. package/src/runtime/pty.zig +5 -2
  113. package/src/runtime/record_store.zig +788 -0
  114. package/src/runtime/relational_store.zig +854 -0
  115. package/src/runtime/root.zig +54 -0
  116. package/src/runtime/runtime_event_tests.zig +70 -0
  117. package/src/runtime/service_host.zig +711 -0
  118. package/src/runtime/service_pool.zig +1314 -0
  119. package/src/runtime/session_blobs.zig +4 -1
  120. package/src/runtime/session_journal.zig +158 -5
  121. package/src/runtime/session_record.zig +215 -0
  122. package/src/runtime/session_replay.zig +206 -11
  123. package/src/runtime/session_tests.zig +81 -0
  124. package/src/runtime/shell_layout.zig +1 -0
  125. package/src/runtime/shell_layout_tests.zig +120 -0
  126. package/src/runtime/sqlite_engine.zig +474 -0
  127. package/src/runtime/state.zig +16 -0
  128. package/src/runtime/system_services.zig +170 -38
  129. package/src/runtime/tests.zig +4 -0
  130. package/src/runtime/ts_core_host.zig +1067 -95
  131. package/src/runtime/ts_core_host_tests.zig +325 -11
  132. package/src/runtime/ts_ui_app.zig +953 -2
  133. package/src/runtime/ui_app.zig +434 -96
  134. package/src/runtime/ui_app_tests.zig +287 -11
  135. package/src/runtime/ui_app_window_tests.zig +61 -7
  136. package/src/runtime/validation.zig +42 -0
  137. package/src/runtime/view.zig +9 -0
  138. package/src/runtime/window_storage.zig +1 -0
  139. package/src/runtime/window_view_runtime.zig +2 -3
  140. package/src/runtime/window_views.zig +19 -0
  141. package/src/tooling/android.zig +21 -16
  142. package/src/tooling/db.zig +160 -0
  143. package/src/tooling/ios.zig +7 -1
  144. package/src/tooling/manifest.zig +214 -2
  145. package/src/tooling/package.zig +116 -0
  146. package/src/tooling/raw_manifest.zig +30 -0
  147. package/src/tooling/root.zig +1 -0
  148. package/src/tooling/templates.zig +189 -4
  149. package/src/tooling/ts_core.zig +366 -17
  150. package/src/tooling/verbs.zig +7 -0
  151. package/third_party/sqlite/README.md +13 -0
  152. package/third_party/sqlite/sqlite3.c +269649 -0
  153. package/third_party/sqlite/sqlite3.h +14349 -0
  154. package/tools/corewire/core_abi.zig +14 -2
  155. package/tools/corewire/emit.zig +98 -29
  156. package/tools/corewire/emit_facade.zig +442 -27
  157. package/tools/corewire/emit_profile.zig +6 -2
  158. package/tools/corewire/emit_service.zig +924 -0
  159. package/tools/corewire/main.zig +122 -0
  160. package/tools/corewire/service_contract.zig +250 -0
  161. 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
+ }