@native-sdk/cli 0.11.0 → 0.11.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 (182) hide show
  1. package/build/app.zig +73 -37
  2. package/build.zig +239 -5
  3. package/native-sdk.d.ts +5 -1
  4. package/package.json +13 -12
  5. package/packages/core/compile-surface/core.ts +30 -0
  6. package/packages/core/package-lock.json +6 -6
  7. package/packages/core/package.json +3 -3
  8. package/packages/core/scripts/scriptc-toolchain.json +44 -44
  9. package/packages/core/scripts/stage_external_core.mjs +27 -16
  10. package/packages/core/sdk/core.d.ts +24 -1
  11. package/packages/core/sdk/core.ts +51 -1
  12. package/packages/core/sdk/events.d.ts +5 -0
  13. package/packages/core/sdk/events.ts +10 -0
  14. package/packages/core/src/bridge_descriptors.ts +3 -3
  15. package/packages/core/src/checker.ts +20 -0
  16. package/packages/core/src/cli.ts +2 -11
  17. package/packages/core/src/context_menus.ts +76 -0
  18. package/packages/core/src/diagnostics.ts +7 -0
  19. package/packages/core/src/extent_program.ts +53 -0
  20. package/packages/core/src/frontend.ts +12 -10
  21. package/packages/core/src/markup_canonical.ts +140 -0
  22. package/packages/core/src/markup_construction.ts +189 -0
  23. package/packages/core/src/markup_display.ts +43 -0
  24. package/packages/core/src/markup_document.ts +226 -0
  25. package/packages/core/src/markup_elements.ts +225 -0
  26. package/packages/core/src/markup_expressions.ts +79 -0
  27. package/packages/core/src/markup_imports.ts +146 -0
  28. package/packages/core/src/markup_parser.ts +228 -0
  29. package/packages/core/src/markup_runtime.ts +93 -0
  30. package/packages/core/src/markup_scalars.ts +143 -0
  31. package/packages/core/src/markup_shapes.ts +243 -0
  32. package/packages/core/src/markup_specialized.ts +242 -0
  33. package/packages/core/src/markup_text.ts +86 -0
  34. package/packages/core/src/markup_values.ts +336 -0
  35. package/packages/core/src/portable_sources.json +24 -0
  36. package/packages/core/src/registered_font.ts +2 -3
  37. package/packages/core/src/runtime_policy.ts +24 -0
  38. package/packages/core/src/scalar_text.ts +1 -3
  39. package/packages/core/src/scroll_mutation.ts +86 -0
  40. package/packages/core/src/scroll_tree.ts +86 -0
  41. package/packages/core/src/service_contract.ts +53 -2
  42. package/packages/core/src/sqlite_cli.ts +3 -46
  43. package/packages/core/src/sqlite_codegen.ts +84 -0
  44. package/packages/core/src/staged_rebuild.ts +60 -0
  45. package/packages/core/src/view_bridge.ts +161 -0
  46. package/packages/core/src/view_check.ts +145 -0
  47. package/packages/core/src/view_evaluator.ts +823 -0
  48. package/packages/core/src/view_frontend.ts +340 -218
  49. package/packages/core/src/view_program.ts +221 -0
  50. package/packages/core/src/view_reload.ts +166 -0
  51. package/packages/core/src/view_reload_watch.ts +98 -0
  52. package/packages/core/src/view_sources.ts +34 -0
  53. package/packages/core/src/virtual_windows.ts +88 -0
  54. package/packages/core/src/web_panes.ts +67 -0
  55. package/packages/core/src/widget_continuity.ts +37 -0
  56. package/packages/core/src/widget_reconcile.ts +63 -0
  57. package/packages/core/src/widget_retention.ts +62 -0
  58. package/skill-data/native-ui/SKILL.md +2 -2
  59. package/skill-data/ts-core/SKILL.md +5 -3
  60. package/skill-data/ts-services/references/service-surface.md +29 -5
  61. package/src/app_runner/root.zig +14 -0
  62. package/src/app_runner/ts_compiled_view.zig +88 -17
  63. package/src/app_runner/ts_core_main.zig +43 -5
  64. package/src/app_runner/ts_core_mobile.zig +1 -1
  65. package/src/automation/server.zig +56 -3
  66. package/src/embed/host.zig +2 -0
  67. package/src/embed/tests.zig +2 -0
  68. package/src/embed/ui_host.zig +2 -0
  69. package/src/platform/keyboard_input.zig +32 -0
  70. package/src/platform/linux/root.zig +2 -0
  71. package/src/platform/macos/appkit_host.h +7 -2
  72. package/src/platform/macos/appkit_host.m +31 -9
  73. package/src/platform/macos/cef_host.mm +15 -1
  74. package/src/platform/macos/global_shortcuts.zig +138 -0
  75. package/src/platform/macos/key_codes.zig +102 -0
  76. package/src/platform/macos/keyboard_input.zig +81 -0
  77. package/src/platform/macos/root.zig +25 -3
  78. package/src/platform/macos/webview_inspection_test.m +106 -0
  79. package/src/platform/null_platform.zig +104 -0
  80. package/src/platform/root.zig +14 -0
  81. package/src/platform/types.zig +102 -0
  82. package/src/platform/windows/global_shortcuts.zig +157 -0
  83. package/src/platform/windows/key_codes.zig +63 -0
  84. package/src/platform/windows/keyboard_input.zig +136 -0
  85. package/src/platform/windows/root.zig +15 -0
  86. package/src/primitives/canvas/decision_reuse.zig +133 -0
  87. package/src/primitives/canvas/font_ttf.zig +27 -3
  88. package/src/primitives/canvas/fonts/Geist-Bold.ttf +0 -0
  89. package/src/primitives/canvas/fonts/Geist-Medium.ttf +0 -0
  90. package/src/primitives/canvas/fonts/OFL.txt +93 -0
  91. package/src/primitives/canvas/fonts/README.md +15 -0
  92. package/src/primitives/canvas/intrinsic_measure_policy.zig +4 -1
  93. package/src/primitives/canvas/markdown_tests.zig +3 -3
  94. package/src/primitives/canvas/reference.zig +3 -5
  95. package/src/primitives/canvas/reference_tests.zig +58 -0
  96. package/src/primitives/canvas/registered_font_policy.zig +1 -1
  97. package/src/primitives/canvas/root.zig +7 -4
  98. package/src/primitives/canvas/text_metrics.zig +32 -39
  99. package/src/primitives/canvas/text_metrics_tests.zig +52 -7
  100. package/src/primitives/canvas/text_query_policy.zig +142 -3
  101. package/src/primitives/canvas/text_scalar_policy.zig +80 -2
  102. package/src/primitives/canvas/tokens.zig +9 -0
  103. package/src/primitives/canvas/ui.zig +1 -0
  104. package/src/primitives/canvas/ui_markup.zig +69 -14
  105. package/src/primitives/canvas/ui_markup_canonical.zig +237 -0
  106. package/src/primitives/canvas/ui_markup_compiled.zig +1407 -23
  107. package/src/primitives/canvas/ui_markup_compiled_values.zig +76 -0
  108. package/src/primitives/canvas/ui_markup_construction.zig +146 -0
  109. package/src/primitives/canvas/ui_markup_display.zig +82 -0
  110. package/src/primitives/canvas/ui_markup_document.zig +196 -0
  111. package/src/primitives/canvas/ui_markup_elements.zig +163 -0
  112. package/src/primitives/canvas/ui_markup_expr.zig +192 -2
  113. package/src/primitives/canvas/ui_markup_imports.zig +262 -0
  114. package/src/primitives/canvas/ui_markup_parser.zig +117 -0
  115. package/src/primitives/canvas/ui_markup_runtime.zig +76 -0
  116. package/src/primitives/canvas/ui_markup_scalars.zig +115 -0
  117. package/src/primitives/canvas/ui_markup_shapes.zig +224 -0
  118. package/src/primitives/canvas/ui_markup_specialized.zig +106 -0
  119. package/src/primitives/canvas/ui_markup_text.zig +128 -0
  120. package/src/primitives/canvas/ui_markup_values.zig +368 -0
  121. package/src/primitives/canvas/ui_markup_view.zig +2817 -74
  122. package/src/primitives/canvas/virtual_extent_policy.zig +58 -0
  123. package/src/primitives/canvas/virtual_extents.zig +47 -33
  124. package/src/primitives/canvas/widget_metric_policy.zig +4 -1
  125. package/src/primitives/canvas/widget_runtime.zig +2 -1
  126. package/src/root.zig +5 -0
  127. package/src/runtime/api.zig +1 -0
  128. package/src/runtime/bridge_descriptor_policy.zig +1 -1
  129. package/src/runtime/bridge_payload.zig +2 -0
  130. package/src/runtime/canvas_widget_context_menu.zig +179 -0
  131. package/src/runtime/canvas_widget_context_menu_test_cases.zig +1147 -0
  132. package/src/runtime/canvas_widget_context_menu_tests.zig +23 -1098
  133. package/src/runtime/canvas_widget_runtime.zig +306 -92
  134. package/src/runtime/context_menu_policy.zig +112 -0
  135. package/src/runtime/core.zig +14 -0
  136. package/src/runtime/effects.zig +172 -4
  137. package/src/runtime/effects_host_tests.zig +25 -0
  138. package/src/runtime/flow.zig +1 -0
  139. package/src/runtime/flow_reference.zig +1 -0
  140. package/src/runtime/global_shortcuts.zig +75 -0
  141. package/src/runtime/keyboard_input.zig +86 -0
  142. package/src/runtime/root.zig +3 -0
  143. package/src/runtime/scroll_mutation_policy.zig +130 -0
  144. package/src/runtime/scroll_mutation_runtime.zig +158 -0
  145. package/src/runtime/scroll_tree_policy.zig +99 -0
  146. package/src/runtime/session_record.zig +7 -0
  147. package/src/runtime/staged_rebuild_policy.zig +83 -0
  148. package/src/runtime/system_services.zig +19 -0
  149. package/src/runtime/tests.zig +1 -0
  150. package/src/runtime/ts_core_host.zig +126 -0
  151. package/src/runtime/ts_ui_app.zig +24 -0
  152. package/src/runtime/ui_app.zig +274 -31
  153. package/src/runtime/ui_app_tests.zig +48 -179
  154. package/src/runtime/ui_app_window_tests.zig +133 -0
  155. package/src/runtime/view_reload.zig +226 -0
  156. package/src/runtime/view_widget_scroll.zig +30 -21
  157. package/src/runtime/view_widget_tree.zig +43 -13
  158. package/src/runtime/virtual_window_policy.zig +128 -0
  159. package/src/runtime/web_pane_policy.zig +111 -0
  160. package/src/runtime/web_pane_test_cases.zig +204 -0
  161. package/src/runtime/widget_continuity_policy.zig +73 -0
  162. package/src/runtime/widget_reconcile_policy.zig +81 -0
  163. package/src/runtime/widget_retention_policy.zig +75 -0
  164. package/src/runtime/window_views.zig +19 -4
  165. package/src/security/root.zig +1 -0
  166. package/src/tooling/templates.zig +8 -0
  167. package/src/tooling/ts_core.zig +84 -1
  168. package/src/tooling/verbs.zig +79 -15
  169. package/tools/corewire/core.test.ts +25 -3
  170. package/tools/corewire/core_abi.zig +4 -0
  171. package/tools/corewire/core_contract.ts +1 -1
  172. package/tools/corewire/core_goldens.json +75 -75
  173. package/tools/corewire/core_projection.ts +3 -2
  174. package/tools/corewire/emit_mirror.ts +19 -9
  175. package/tools/corewire/facade_templates.ts +1 -1
  176. package/tools/corewire/intake.test.ts +4 -0
  177. package/tools/corewire/intake_goldens.json +50 -50
  178. package/tools/corewire/invocation.test.ts +4 -0
  179. package/tools/corewire/invocation_goldens.json +3 -3
  180. package/tools/corewire/mirror_templates.ts +4 -0
  181. package/tools/corewire/profile_emission.ts +2 -0
  182. package/tools/corewire/sidecar.zig +2 -0
@@ -73,6 +73,10 @@ export interface ServiceSurfaceResult {
73
73
  readonly diagnostics: readonly SubsetDiagnostic[];
74
74
  readonly contract: string | null;
75
75
  readonly client: string | null;
76
+ /// The client's declaration module: exactly what declaration emit
77
+ /// produces for `client` (the exported operation signatures and the
78
+ /// imports they reference).
79
+ readonly clientDeclarations: string | null;
76
80
  }
77
81
 
78
82
  function report(site: string, node: ts.Node): SubsetDiagnostic {
@@ -397,6 +401,52 @@ function emitServiceClientDocument(document: {
397
401
  return out;
398
402
  }
399
403
 
404
+ /// The declaration module for `emitServiceClientDocument`'s client: one
405
+ /// `export declare function` per operation, keeping only the imports those
406
+ /// signatures reference, in the client's own import order. Matches
407
+ /// declaration emit for the client byte for byte (test/editor_declarations.test.ts).
408
+ function emitServiceClientDeclarations(document: {
409
+ readonly operations: readonly ServiceOperation[];
410
+ readonly types: ServiceTypes;
411
+ }): string {
412
+ const referenced = new Set<string>();
413
+ const reference = (ref: ServiceTypeRef): void => {
414
+ switch (ref.kind) {
415
+ case "optional": reference(ref.inner); break;
416
+ case "slice": reference(ref.elem); break;
417
+ case "record":
418
+ case "enum":
419
+ case "union": referenced.add(ref.name); break;
420
+ default: break;
421
+ }
422
+ };
423
+ const routes = new Set<string>();
424
+ const signatures: string[] = [];
425
+ for (const operation of document.operations) {
426
+ const request = operation.request.kind === "none" ? null : operation.request;
427
+ if (request) reference(request);
428
+ reference(operation.result);
429
+ const routeType = operation.stream === null ? "ServiceRoute" : "ServiceStreamRoute";
430
+ routes.add(routeType);
431
+ const requestParam = request ? `request: ${typeSpelling(request)}, ` : "";
432
+ signatures.push(`export declare function ${operation.client}(${requestParam}route: ${routeType}<Msg, ${typeSpelling(operation.result)}>): Cmd<Msg>;\n`);
433
+ }
434
+ const imports = new Map<string, Set<string>>();
435
+ imports.set("core.ts", new Set(["Msg"]));
436
+ for (const type of [...document.types.records, ...document.types.enums, ...document.types.unions]) {
437
+ if (!referenced.has(type.name)) continue;
438
+ const names = imports.get(type.origin) ?? new Set<string>();
439
+ names.add(type.name);
440
+ imports.set(type.origin, names);
441
+ }
442
+ const coreNames = ["Cmd", ...["ServiceRoute", "ServiceStreamRoute"].filter((name) => routes.has(name)).map((name) => `type ${name}`)];
443
+ let out = `import { ${coreNames.join(", ")} } from "@native-sdk/core";\n`;
444
+ for (const [origin, names] of [...imports].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
445
+ out += `import type { ${[...names].sort().join(", ")} } from "./${origin}";\n`;
446
+ }
447
+ return out + signatures.join("");
448
+ }
449
+
400
450
  export function emitServiceContract(
401
451
  tast: TypedAst,
402
452
  table: TypeTable,
@@ -407,7 +457,7 @@ export function emitServiceContract(
407
457
  packages: readonly ServicePackage[] = [],
408
458
  ): ServiceSurfaceResult {
409
459
  const emptyTypes: ServiceTypes = { records: [], enums: [], unions: [] };
410
- if (files.length === 0) return { operations: [], types: emptyTypes, diagnostics: [], contract: null, client: null };
460
+ if (files.length === 0) return { operations: [], types: emptyTypes, diagnostics: [], contract: null, client: null, clientDeclarations: null };
411
461
 
412
462
  const diagnostics: SubsetDiagnostic[] = [];
413
463
  const operations: ServiceOperation[] = [];
@@ -588,7 +638,7 @@ export function emitServiceContract(
588
638
  diagnostics.push(report("The service tree exports no callable operations.", files[0]));
589
639
  }
590
640
  const types = shapes.document();
591
- if (diagnostics.length > 0) return { operations, types, diagnostics, contract: null, client: null };
641
+ if (diagnostics.length > 0) return { operations, types, diagnostics, contract: null, client: null, clientDeclarations: null };
592
642
  const document = {
593
643
  format: serviceContractFormat,
594
644
  protocol_version: serviceProtocolVersion,
@@ -604,5 +654,6 @@ export function emitServiceContract(
604
654
  diagnostics,
605
655
  contract: `${JSON.stringify(document, null, 2)}\n`,
606
656
  client: emitServiceClientDocument(document),
657
+ clientDeclarations: emitServiceClientDeclarations(document),
607
658
  };
608
659
  }
@@ -1,8 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
- import ts from "@typescript/old";
5
- import { analyzeSqlite, checkMigrationState, formatSqliteDiagnostic, generateCoreSurface, generateMigrationsZig } from "./sqlite_codegen.ts";
4
+ import { analyzeSqlite, checkMigrationState, formatSqliteDiagnostic, generateCoreDeclarations, generateCoreSurface, generateMigrationsZig } from "./sqlite_codegen.ts";
6
5
 
7
6
  function argsOf(argv: string[]): Map<string, string> {
8
7
  const out = new Map<string, string>();
@@ -69,50 +68,8 @@ try {
69
68
  fs.copyFileSync(path.join(sdkDir, source), destination);
70
69
  }
71
70
  if (dtsOut) {
72
- const compilerOptions: ts.CompilerOptions = {
73
- strict: true,
74
- exactOptionalPropertyTypes: true,
75
- target: ts.ScriptTarget.ESNext,
76
- module: ts.ModuleKind.ESNext,
77
- moduleResolution: ts.ModuleResolutionKind.Bundler,
78
- lib: ["lib.esnext.d.ts"],
79
- types: [],
80
- allowImportingTsExtensions: true,
81
- rewriteRelativeImportExtensions: true,
82
- declaration: true,
83
- emitDeclarationOnly: true,
84
- skipLibCheck: false,
85
- };
86
- const input = path.resolve(sdkIn!);
87
- const host = ts.createCompilerHost(compilerOptions);
88
- const getSourceFile = host.getSourceFile.bind(host);
89
- host.getSourceFile = (fileName, languageVersion, onError, shouldCreateNewSourceFile) =>
90
- path.resolve(fileName) === input
91
- ? ts.createSourceFile(fileName, sdkSource, languageVersion, true)
92
- : getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
93
- let output = "";
94
- host.writeFile = (fileName, text) => {
95
- if (fileName.endsWith("core.d.ts")) output = text;
96
- };
97
- const program = ts.createProgram([input], compilerOptions, host);
98
- const errors = ts
99
- .getPreEmitDiagnostics(program)
100
- .filter((diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error);
101
- if (errors.length > 0) {
102
- throw new Error(
103
- errors
104
- .map(
105
- (diagnostic) =>
106
- `TS${diagnostic.code} ${ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")}`,
107
- )
108
- .join("\n"),
109
- );
110
- }
111
- const emit = program.emit();
112
- if (emit.emitSkipped || output.length === 0) {
113
- throw new Error("generated SQLite SDK declaration emit failed");
114
- }
115
- fs.writeFileSync(dtsOut, output.replace(/(from\s+")(\.\.?\/[^\"]+)\.ts(\")/g, "$1$2.js$3"));
71
+ const declarations = fs.readFileSync(path.join(sdkDir, "core.d.ts"), "utf8");
72
+ fs.writeFileSync(dtsOut, generateCoreDeclarations(fs.readFileSync(sdkIn!, "utf8"), declarations, analysis));
116
73
  }
117
74
  fs.writeFileSync(staticOut!, generateCoreSurface(fs.readFileSync(staticIn!, "utf8"), analysis));
118
75
  }
@@ -708,6 +708,90 @@ function generatePageDecoder(query: DeclaredQuery, stem: string): string {
708
708
  return out.join("\n");
709
709
  }
710
710
 
711
+ /// The declaration form of `generatedFragments`, as declaration emit prints
712
+ /// it: four-space indentation, bodies dropped, private page helpers omitted.
713
+ export function generatedDeclarationFragments(analysis: SqliteAnalysis): { types: string[]; cmds: string[]; subs: string[] } {
714
+ const types: string[] = [];
715
+ const cmds: string[] = [];
716
+ const subs: string[] = [];
717
+ if (analysis.queries.some((query) => query.kind === "query")) types.push("export type DbDecodedValue = null | number | Uint8Array;");
718
+ for (const query of analysis.queries) {
719
+ const stem = pascal(query.name);
720
+ types.push(`export interface ${stem}Params {`);
721
+ for (const param of query.params) types.push(` readonly ${param.name}: ${tsType(param, true)};`);
722
+ types.push("}");
723
+ if (query.kind === "query") {
724
+ types.push(`export interface ${stem}Row {`);
725
+ for (const column of query.columns) types.push(` readonly ${ident.test(column.name) ? column.name : js(column.name)}: ${tsType(column)};`);
726
+ types.push("}");
727
+ types.push(`export declare function decode${stem}Page(bytes: Uint8Array): ReadonlyArray<${stem}Row>;`);
728
+ }
729
+ }
730
+ for (const query of analysis.queries) {
731
+ const stem = pascal(query.name);
732
+ cmds.push(query.kind === "query"
733
+ ? ` q${stem}<M extends Msgish>(params: ${stem}Params, route: TypedRowsRoute<${stem}Row, M>): Cmd<M>;`
734
+ : ` q${stem}(params: ${stem}Params): TypedDbStatement;`);
735
+ }
736
+ if (analysis.queries.some((query) => query.kind === "exec")) cmds.push(" qTx<M extends Msgish>(statements: ReadonlyArray<TypedDbStatement>, route: WriteRoute<M>): Cmd<M>;");
737
+ for (const query of analysis.queries.filter((q) => q.live)) {
738
+ const stem = pascal(query.name);
739
+ subs.push(` q${stem}<M extends Msgish>(key: string, params: ${stem}Params, route: TypedRowsRoute<${stem}Row, M>): Sub<M>;`);
740
+ }
741
+ return { types, cmds, subs };
742
+ }
743
+
744
+ /// The declaration file for `generateCoreSurface(base, analysis)`: the
745
+ /// shipped declarations of `base` with the generated declarations inserted
746
+ /// where the generated source lands. Each insertion point is the
747
+ /// declaration that follows the marker in `base`. A marker whose anchor
748
+ /// cannot be found is an SDK bug, never a silent omission.
749
+ export function generateCoreDeclarations(base: string, baseDeclarations: string, analysis: SqliteAnalysis): string {
750
+ const fragments = generatedDeclarationFragments(analysis);
751
+ const lines = baseDeclarations.split("\n");
752
+ const insertions: { at: number; lines: string[] }[] = [];
753
+ for (const [marker, generated] of [
754
+ ["// @native-sqlite-generated-types", fragments.types],
755
+ ["// @native-sqlite-generated-cmds", fragments.cmds],
756
+ ["// @native-sqlite-generated-subs", fragments.subs],
757
+ ] as const) {
758
+ if (generated.length === 0) continue;
759
+ insertions.push({ at: declarationAnchor(base, lines, marker), lines: generated });
760
+ }
761
+ for (const insertion of insertions.sort((a, b) => b.at - a.at)) lines.splice(insertion.at, 0, ...insertion.lines);
762
+ return lines.join("\n");
763
+ }
764
+
765
+ function declarationAnchor(base: string, lines: readonly string[], marker: string): number {
766
+ const markerAt = base.indexOf(marker);
767
+ if (markerAt < 0) throw new Error(`the SDK core module has no ${marker} marker`);
768
+ const after = base.slice(markerAt + marker.length).split("\n").map((line) => line.trim())
769
+ .find((line) => line.length > 0 && !line.startsWith("//"));
770
+ const topLevel = /^export (?:declare )?(?:interface|type|function|const|class|enum) ([A-Za-z_$][A-Za-z0-9_$]*)/.exec(after ?? "");
771
+ const member = /^([A-Za-z_$][A-Za-z0-9_$]*)\s*[:<(]/.exec(after ?? "");
772
+ let at = -1;
773
+ if (topLevel) {
774
+ const declaration = new RegExp(`^export (?:declare )?(?:interface|type|function|const|class|enum) ${topLevel[1]}\\b`);
775
+ at = lines.findIndex((line) => declaration.test(line));
776
+ } else if (member) {
777
+ const owner = [...base.slice(0, markerAt).matchAll(/^export const ([A-Za-z_$][A-Za-z0-9_$]*) = \{/gm)].at(-1)?.[1];
778
+ const start = owner === undefined ? -1 : lines.findIndex((line) => line.startsWith(`export declare const ${owner}: {`));
779
+ if (start >= 0) {
780
+ const memberLine = new RegExp(`^ ${member[1]}[?]?[:<(]`);
781
+ const end = lines.findIndex((line, index) => index > start && line === "};");
782
+ at = lines.findIndex((line, index) => index > start && index < end && memberLine.test(line));
783
+ }
784
+ }
785
+ if (at < 0) throw new Error(`the SDK core declarations have no anchor for ${marker}`);
786
+ // A documented anchor keeps its JSDoc block attached.
787
+ while (at > 0 && lines[at - 1]!.trim().endsWith("*/")) {
788
+ let open = at - 1;
789
+ while (open > 0 && !lines[open]!.trim().startsWith("/**")) open--;
790
+ at = open;
791
+ }
792
+ return at;
793
+ }
794
+
711
795
  export function generateCoreSurface(base: string, analysis: SqliteAnalysis): string {
712
796
  const fragments = generatedFragments(analysis);
713
797
  return base
@@ -0,0 +1,60 @@
1
+ /** Staged rebuild program over copied facts. Operation 96, mode 0 schedules
2
+ * keyed splits, scroll restore, programmatic clamp, tab reveals and anchored
3
+ * relayout in that order for each stratum. The 32-byte header carries count,
4
+ * cursor, stratum, maximum stratum and phase as u32LE; each 8-byte node has
5
+ * keyed-split admission and stratum. The 24-byte result carries action,
6
+ * selected ordinal and the next cursor/phase/stratum. Native refreshes facts
7
+ * after mutations and retains all identities, widgets and geometry buffers.
8
+ * Mode 1 has a 32-byte request: admission flags, zero, then current/origin/
9
+ * previous-source/retained f32LE and twelve zeros. Its 12-byte result selects
10
+ * keep, enter-slide, value-only, retained-slide or relayout with an f32 value.
11
+ */
12
+ function nscvStagedRebuild(request: Uint8Array): Uint8Array {
13
+ if (request.length < 32 || request[0] !== 96 || request[1]! > 1 || request[3] !== 0)
14
+ throw new Error("invalid staged rebuild header");
15
+ const w = new DataView(request.buffer, request.byteOffset, request.byteLength);
16
+ if (request[1] === 1) {
17
+ const flags = request[2]!;
18
+ if (request.length !== 32 || flags > 127 || w.getUint32(20, true) !== 0 || w.getUint32(24, true) !== 0 || w.getUint32(28, true) !== 0)
19
+ throw new Error("invalid staged split facts");
20
+ const current = w.getFloat32(4, true), origin = w.getFloat32(8, true);
21
+ let action = 0, value = current;
22
+ if ((flags & 1) === 0) {
23
+ if ((flags & (4 | 8 | 16)) === (4 | 8 | 16)) { action = 1; value = origin; }
24
+ } else {
25
+ // Reuse the shipped split scalar policy; this program owns when and
26
+ // how its retained result changes the staged geometry.
27
+ const packet = new Uint8Array(26), split = new DataView(packet.buffer);
28
+ packet[0] = 2; packet[1] = ((flags & 2) !== 0 ? 1 : 0) | ((flags & 8) !== 0 ? 2 : 0) | ((flags & 32) !== 0 ? 4 : 0);
29
+ split.setFloat32(2, current, true); split.setFloat32(18, w.getFloat32(12, true), true); split.setFloat32(22, w.getFloat32(16, true), true);
30
+ value = new DataView(nscvSplitPolicy(packet).buffer).getFloat32(0, true);
31
+ if (value !== current) {
32
+ action = 2;
33
+ if ((flags & 4) !== 0) {
34
+ const sourceMoved = (flags & 2) !== 0 && current !== w.getFloat32(12, true);
35
+ action = (flags & 64) === 0 && ((flags & 32) !== 0 || sourceMoved && (flags & 8) !== 0) ? 3 : 4;
36
+ }
37
+ }
38
+ }
39
+ const result = new Uint8Array(12); result[0] = 96; result[1] = 1; result[2] = action;
40
+ new DataView(result.buffer).setFloat32(4, value, true); return result;
41
+ }
42
+ const count = w.getUint32(4, true), cursor = w.getUint32(8, true), stratum = w.getUint32(12, true);
43
+ const maximum = w.getUint32(16, true), phase = w.getUint32(20, true);
44
+ if (request[2] !== 0 || count > 1024 || cursor > count || stratum > maximum || maximum > 1024 || phase > 3 ||
45
+ request.length !== 32 + count * 8 || w.getUint32(24, true) !== 0 || w.getUint32(28, true) !== 0)
46
+ throw new Error("invalid staged rebuild state");
47
+ for (let i = 0; i < count; i++) if (w.getUint32(32 + i * 8, true) > 1 || w.getUint32(36 + i * 8, true) > maximum)
48
+ throw new Error("invalid staged rebuild node");
49
+ let action = 0, selected = 0, nextCursor = cursor, nextPhase = phase, nextStratum = stratum;
50
+ if (phase === 0) {
51
+ let index = cursor;
52
+ while (index < count && (w.getUint32(32 + index * 8, true) === 0 || w.getUint32(36 + index * 8, true) !== stratum)) index++;
53
+ if (index < count) { action = 1; selected = index; nextCursor = index + 1; }
54
+ else { action = 2; nextPhase = 1; nextCursor = count; }
55
+ } else if (phase < 3) { action = phase + 2; nextPhase = phase + 1; }
56
+ else if (stratum < maximum) { action = 5; nextPhase = 0; nextCursor = 0; nextStratum++; }
57
+ const result = new Uint8Array(24), out = new DataView(result.buffer);
58
+ result[0] = 96; result[2] = action; out.setUint32(4, selected, true); out.setUint32(8, nextCursor, true);
59
+ out.setUint32(12, nextPhase, true); out.setUint32(16, nextStratum, true); return result;
60
+ }
@@ -0,0 +1,161 @@
1
+ /** The per-app half of the development view evaluator: typed reads of this
2
+ * contract's model, its helpers, and its message constructors. Generated
3
+ * from the contract alone, never from author source.
4
+ */
5
+ import { createHash } from "node:crypto";
6
+ import type { ViewContract } from "./view_frontend.ts";
7
+
8
+ interface Ref { kind: string; name?: string; elem?: Ref; inner?: Ref; class?: string; type?: Ref }
9
+
10
+ /** Changes whenever a program compiled against one build could misread another. */
11
+ export function viewBridgeIdentity(contract: ViewContract, evaluatorSource: string): string {
12
+ const relevant = { model: contract.model, types: contract.types, helpers: contract.model_helpers, msg: contract.msg };
13
+ return createHash("sha256").update("native view program 1\0").update(JSON.stringify(relevant)).update("\0").update(evaluatorSource).digest("hex");
14
+ }
15
+
16
+ type Record = ViewContract["types"]["structs"][number] & { origin?: string | null };
17
+ type Enum = { name: string; members: string[]; origin?: string | null };
18
+
19
+ export function viewBridgeSource(contract: ViewContract, identity: string): string {
20
+ const allStructs = contract.types.structs as Record[], enums = (contract.types.enums ?? []) as Enum[];
21
+ // Only records a view can reach: the model, helper results and helper
22
+ // parameters, through record, list and optional fields.
23
+ const reachable = new Set<string>();
24
+ const visit = (ref: Ref | undefined): void => {
25
+ if (!ref) return;
26
+ if ((ref.kind === "value" || ref.kind === "node") && ref.name && !reachable.has(ref.name)) {
27
+ reachable.add(ref.name);
28
+ for (const field of allStructs.find(item => item.name === ref.name)?.fields ?? []) visit(field.type);
29
+ }
30
+ visit(ref.inner); visit(ref.elem);
31
+ };
32
+ visit({ kind: "value", name: contract.model });
33
+ for (const helper of contract.model_helpers) { visit(helper.returns); helper.params.forEach(visit); }
34
+ // Declared records keep their names; anonymous ones are spelled out, as
35
+ // the generated entry module spells them.
36
+ const spellings = new Map<string, string | null>();
37
+ const spell = (ref: Ref): string | null => {
38
+ switch (ref.kind) {
39
+ case "bool": return "boolean";
40
+ case "i64": case "f64": return "number";
41
+ case "bytes": return "Uint8Array";
42
+ case "optional": { const inner = spell(ref.inner!); return inner === null ? null : `${inner} | null`; }
43
+ case "slice": { const elem = spell(ref.elem!); return elem === null ? null : `readonly (${elem})[]`; }
44
+ case "enum": {
45
+ const item = enums.find(entry => entry.name === ref.name);
46
+ if (!item) return null;
47
+ return item.origin === null ? item.members.map(member => JSON.stringify(member)).join(" | ") : item.name;
48
+ }
49
+ case "value": case "node": return spellRecord(ref.name!);
50
+ }
51
+ return null;
52
+ };
53
+ const spellRecord = (name: string): string | null => {
54
+ if (spellings.has(name)) return spellings.get(name)!;
55
+ const record = allStructs.find(item => item.name === name);
56
+ if (!record) return null;
57
+ if (record.origin !== null && record.origin !== undefined) { spellings.set(name, name); return name; }
58
+ spellings.set(name, null);
59
+ const fields: string[] = [];
60
+ for (const field of record.fields) { const type = spell(field.type); if (type === null) return null; fields.push(`readonly ${JSON.stringify(field.name)}: ${type}`); }
61
+ const spelled = `{ ${fields.join("; ")} }`;
62
+ spellings.set(name, spelled);
63
+ return spelled;
64
+ };
65
+ const structs = allStructs.filter(item => reachable.has(item.name) && spellRecord(item.name) !== null);
66
+ const typeOf = (record: Record): string => spellRecord(record.name)!;
67
+ const structIndex = (name: string): number => structs.findIndex(item => item.name === name);
68
+ const enumIndex = (name: string): number => enums.findIndex(item => item.name === name);
69
+ const wrap = (ref: Ref, e: string): string => {
70
+ switch (ref.kind) {
71
+ case "bool": return `nscvdBoolean(${e})`;
72
+ case "i64": case "f64": return `nscvdNum(${e})`;
73
+ case "bytes": return `nscvdBytesValue(${e})`;
74
+ case "enum": return `nscvdStr(${e})`;
75
+ case "optional": return `(${e} === null ? nscvdNull() : ${wrap(ref.inner!, e + "!")})`;
76
+ case "value": case "node": return structIndex(ref.name!) < 0 ? `nscvdUnsupported(${JSON.stringify(ref.name)})` : `nscvdWrapS${structIndex(ref.name!)}(${e})`;
77
+ case "slice": {
78
+ const elem = ref.elem!;
79
+ if (elem.kind === "bool") return `nscvdBoolsValue(nscvdCopyBooleans(${e}))`;
80
+ if (elem.kind === "i64" || elem.kind === "f64") return `nscvdNumsValue(nscvdCopyNumbers(${e}))`;
81
+ if (elem.kind === "bytes") return `nscvdByteListValue(nscvdCopyBytes(${e}))`;
82
+ if (elem.kind === "enum") return `nscvdStrListValue(nscvdCopyStrings(${e}))`;
83
+ if (elem.kind === "value" || elem.kind === "node") return structIndex(elem.name!) < 0 ? `nscvdUnsupported(${JSON.stringify(elem.name)})` : `nscvdWrapL${structIndex(elem.name!)}(${e})`;
84
+ return `nscvdUnsupported("a nested list")`;
85
+ }
86
+ }
87
+ return `nscvdUnsupported(${JSON.stringify(ref.kind)})`;
88
+ };
89
+ // Integer slots are proven at the literal: a checked local, then the
90
+ // bounded conversion the compiler recognizes as whole.
91
+ let integers: string[] = [];
92
+ const scalar = (ref: Ref, e: string): string => {
93
+ switch (ref.kind) {
94
+ case "bool": return `nscvdBool(${e})`;
95
+ case "f64": return `nscvdNumber(${e})`;
96
+ case "i64": { const local = `nscvdI${integers.length}`; integers.push(`const ${local} = nscvdI64(nscvdNumber(${e}));`); return `${local} >= -9007199254740991 && ${local} <= 9007199254740991 ? Math.trunc(${local}) : 0`; }
97
+ case "bytes": return `nscvdBytes(${e})`;
98
+ case "enum": return `nscvdEnum${enumIndex(ref.name!)}(nscvdString(${e}))`;
99
+ }
100
+ throw new Error(`development view bridge: unsupported message field ${ref.kind}`);
101
+ };
102
+ const out: string[] = [];
103
+ out.push("// Generated development view bridge for this app's contract.", `const nscvdBridgeIdentity = ${JSON.stringify(identity)};`);
104
+ out.push("class NscvdContract {");
105
+ structs.forEach((item, i) => out.push(` r${i}: (${typeOf(item)}) | null = null;`, ` l${i}: readonly (${typeOf(item)})[] = [];`));
106
+ out.push("}");
107
+ out.push("function nscvdContractValue(type: number, list: boolean): NscvdValue { const value = nscvdTagged(NSCVD_CONTRACT); value.ct = type; value.cl = list; value.c = new NscvdContract(); return value; }");
108
+ structs.forEach((item, i) => out.push(
109
+ `function nscvdWrapS${i}(record: ${typeOf(item)}): NscvdValue { const value = nscvdContractValue(${i}, false); value.c!.r${i} = record; return value; }`,
110
+ `function nscvdWrapL${i}(list: readonly (${typeOf(item)})[]): NscvdValue { const value = nscvdContractValue(${i}, true); value.c!.l${i} = list; return value; }`));
111
+ enums.forEach((item, i) => out.push(`function nscvdEnum${i}(value: string): ${spell({ kind: "enum", name: item.name })} {`, ...item.members.map(member => ` if (value === ${JSON.stringify(member)}) return ${JSON.stringify(member)};`), ` throw new Error("invalid ${item.name} value " + value);`, "}"));
112
+ out.push(`function nscvdModel(): NscvdValue { return nscvdWrapS${structIndex(contract.model)}(nscfCommitted); }`);
113
+ out.push("function nscvdContractField(value: NscvdValue, name: string): NscvdValue {", " if (value.cl) throw new Error(\"development view list has no field \" + name);", " switch (value.ct) {");
114
+ structs.forEach((item, i) => {
115
+ out.push(` case ${i}: {`, ` const record = value.c!.r${i}!;`, " switch (name) {");
116
+ for (const field of item.fields) out.push(` case ${JSON.stringify(field.name)}: return ${wrap(field.type, `record[${JSON.stringify(field.name)}]`)};`);
117
+ out.push(" }", " break;", " }");
118
+ });
119
+ out.push(" }", " throw new Error(\"unknown development view model field \" + name);", "}");
120
+ out.push("function nscvdContractItems(value: NscvdValue): NscvdValue[] {", " if (!value.cl) throw new Error(\"development view record is not iterable\");", " const out: NscvdValue[] = [];", " switch (value.ct) {");
121
+ structs.forEach((_item, i) => out.push(` case ${i}: for (const item of value.c!.l${i}) out.push(nscvdWrapS${i}(item)); return out;`));
122
+ out.push(" }", " throw new Error(\"unknown development view list\");", "}");
123
+ out.push("function nscvdContractLength(value: NscvdValue): number {", " if (!value.cl) throw new Error(\"development view record has no length\");", " switch (value.ct) {");
124
+ structs.forEach((_item, i) => out.push(` case ${i}: return value.c!.l${i}.length;`));
125
+ out.push(" }", " throw new Error(\"unknown development view list\");", "}");
126
+ out.push("function nscvdHelper(name: string, args: NscvdValue[]): NscvdValue {", " switch (name) {");
127
+ for (const helper of contract.model_helpers) {
128
+ if (helper.params.length > 1) continue;
129
+ const range = helper.params.length === 1 ? "nscvdRange(args[1]!)" : null;
130
+ if (helper.params.length === 1 && !["value", "node"].includes(helper.params[0]!.kind)) continue;
131
+ out.push(` case ${JSON.stringify(helper.name)}: return ${wrap(helper.returns, `${helper.name}(nscfCommitted${range ? ", " + range : ""})`)};`);
132
+ }
133
+ out.push(" }", " throw new Error(\"unknown development view helper \" + name);", "}");
134
+ out.push("function nscvdPackMsg(arm: string, keys: string[], values: NscvdValue[]): number[] {",
135
+ " const field = (key: string): NscvdValue => { for (let i = 0; i < keys.length; i++) if (keys[i] === key) return values[i]!; throw new Error(\"missing development view message field \" + key); };",
136
+ " switch (arm) {");
137
+ for (const arm of contract.msg.arms) {
138
+ const p = arm.payload as Ref, fields: string[] = [`kind: ${JSON.stringify(arm.name)}`];
139
+ integers = [];
140
+ if (p.kind === "void") { /* kind only */ }
141
+ else if (arm.member && ["number", "bytes", "bool", "enum", "scalar"].includes(p.kind)) {
142
+ const type: Ref = p.kind === "number" ? { kind: p.class ?? "f64" } : p.kind === "scalar" ? p.type! : p;
143
+ if (!["bool", "f64", "i64", "bytes", "enum"].includes(type.kind)) continue;
144
+ fields.push(`${JSON.stringify(arm.member)}: ${scalar(type, `field(${JSON.stringify(arm.member)})`)}`);
145
+ } else if (p.kind === "record" && !arm.member) {
146
+ const record = allStructs.find(item => item.name === p.name);
147
+ if (!record || !record.fields.every(f => ["bool", "f64", "i64", "bytes", "enum"].includes(f.type.kind))) continue;
148
+ for (const f of record.fields) fields.push(`${JSON.stringify(f.name)}: ${scalar(f.type, `field(${JSON.stringify(f.name)})`)}`);
149
+ } else continue;
150
+ out.push(` case ${JSON.stringify(arm.name)}: { ${integers.join(" ")} return Array.from(nscfPackMsg({ ${fields.join(", ")} })); }`);
151
+ }
152
+ out.push(" }", " throw new Error(\"unknown development view message \" + arm);", "}");
153
+ const imageRecords = structs.map((item, i) => ({ item, i })).filter(({ item }) => item.fields.length === 4 && ["source", "image", "width", "height"].every(name => item.fields.some(f => f.name === name)));
154
+ out.push("function nscvdMarkdownImages(value: NscvdValue): { source: Uint8Array; image: number; width: number; height: number }[] {", " const out: { source: Uint8Array; image: number; width: number; height: number }[] = [];", " if (value.t === NSCVD_LIST && value.list.length === 0) return out;", " if (!value.cl) throw new Error(\"development view expected markdown images\");", " switch (value.ct) {");
155
+ for (const { item, i } of imageRecords) if (["i64", "f64"].includes(item.fields.find(f => f.name === "image")!.type.kind)) out.push(` case ${i}: for (const x of value.c!.l${i}) out.push({ source: x.source, image: x.image, width: x.width, height: x.height }); return out;`);
156
+ out.push(" }", " throw new Error(\"development view expected markdown images\");", "}");
157
+ out.push("function nscvdMarkdownImageWords(value: NscvdValue): { source: Uint8Array; image: { imageLower: number; imageUpper: number }; width: number; height: number }[] {", " const out: { source: Uint8Array; image: { imageLower: number; imageUpper: number }; width: number; height: number }[] = [];", " if (value.t === NSCVD_LIST && value.list.length === 0) return out;", " if (!value.cl) throw new Error(\"development view expected markdown images\");", " switch (value.ct) {");
158
+ for (const { item, i } of imageRecords) if (["value", "node"].includes(item.fields.find(f => f.name === "image")!.type.kind)) out.push(` case ${i}: for (const x of value.c!.l${i}) out.push({ source: x.source, image: { imageLower: x.image.imageLower, imageUpper: x.image.imageUpper }, width: x.width, height: x.height }); return out;`);
159
+ out.push(" }", " throw new Error(\"development view expected markdown images\");", "}");
160
+ return out.join("\n") + "\n";
161
+ }
@@ -0,0 +1,145 @@
1
+ #!/usr/bin/env node
2
+ // Check a TypeScript app's markup against its core: compile every view
3
+ // exactly as the build does (src/app.native plus src/windows/*.native,
4
+ // against the frontend's core contract), then report model state and Msg
5
+ // kinds no view uses.
6
+ //
7
+ // view_check.ts --contract <core.contract.json> --src <app src dir>
8
+ //
9
+ // Diagnostics go to stderr in the markup checker's format. stdout carries
10
+ // one JSON line, {"errors":N,"warnings":N}, for the caller's summary and
11
+ // --strict promotion.
12
+ //
13
+ // Exit codes: 0 checked (see stdout for the verdict); 2 usage.
14
+
15
+ import fs from "node:fs";
16
+ import path from "node:path";
17
+ import { pathToFileURL } from "node:url";
18
+ import { compileViewBundle, type ViewContract, type ViewUsage } from "./view_frontend.ts";
19
+ import { appViewSources } from "./view_sources.ts";
20
+
21
+ interface Ref { kind: string; name?: string; elem?: Ref }
22
+ interface CheckContract extends ViewContract {
23
+ model_unbound?: string[];
24
+ msg: ViewContract["msg"] & { unbound?: string[] };
25
+ }
26
+
27
+ export interface ViewCheckResult {
28
+ readonly error: string | null;
29
+ readonly warnings: readonly string[];
30
+ }
31
+
32
+ /// Compile the app's views beside `contract` and lint unused model state.
33
+ /// `srcLabel` prefixes diagnostic paths (the views' paths are relative to
34
+ /// the source directory).
35
+ export function checkAppViews(contract: CheckContract, srcDir: string, srcLabel = "src"): ViewCheckResult {
36
+ const { sources, windows } = appViewSources(srcDir);
37
+ const root = sources.get("app.native");
38
+ if (root === undefined) return { error: `${srcLabel}/app.native: error: a TypeScript app needs a root view at ${srcLabel}/app.native`, warnings: [] };
39
+ const usage: ViewUsage = { model: new Set(), msg: new Set() };
40
+ // The compiler names files relative to each view's own import root:
41
+ // src/ for the root view, src/windows/ for a secondary window. Compile
42
+ // each view on its own so a failure is reported under the right root,
43
+ // then the whole bundle once for the checks that span views.
44
+ const compile = (run: () => void, root: string): string | null => {
45
+ try {
46
+ run();
47
+ return null;
48
+ } catch (err) {
49
+ if (!(err instanceof Error)) throw err;
50
+ return locate(err.message, root);
51
+ }
52
+ };
53
+ const error = compile(() => compileViewBundle(root, contract, { sources }, [], usage), srcLabel) ??
54
+ windows.reduce<string | null>((found, window) => found ?? compile(() =>
55
+ compileViewBundle(window.source, contract, { entry: window.entry, sources: window.sources }, [], usage), `${srcLabel}/windows`), null) ??
56
+ compile(() => compileViewBundle(root, contract, { sources }, windows), srcLabel);
57
+ return error ? { error, warnings: [] } : { error: null, warnings: unusedState(contract, usage) };
58
+ }
59
+
60
+ /// "app.native:3:5: compiled TypeScript view: …" becomes
61
+ /// "src/app.native:3:5: error: compiled TypeScript view: …", where the
62
+ /// prefix is the import root the compiler resolved the file against.
63
+ function locate(message: string, importRoot: string): string {
64
+ const located = /^([^:\n]+\.native):(\d+):(\d+): ([\s\S]*)$/.exec(message);
65
+ if (located) return `${importRoot}/${located[1]}:${located[2]}:${located[3]}: error: ${located[4]}`;
66
+ return `error: ${message}`;
67
+ }
68
+
69
+ /// The entry exports the generated launcher wires to host channels (theme,
70
+ /// status items, windows, canvas chrome, …). A model helper with one of
71
+ /// these names feeds the host, never markup. Kept equal to the frontend
72
+ /// checker's entry-only export set by test/view_check.test.ts.
73
+ export const entryChannelExports: ReadonlySet<string> = new Set([
74
+ "update", "initialModel", "subscriptions", "migrate",
75
+ "commandMsg", "keyMsg", "frameMsg", "pinchMsg", "dropMsg", "appearanceMsg", "chromeMsg", "envMsgs", "themePack", "themeState", "tokenOverrides", "statusItem", "statusItems", "windows", "webPanes", "layoutTweens", "canvasIcons", "canvasChrome", "canvasChromeSuffix", "canvasAnimations", "canvasFrameMsg", "bootImageMsg", "sliderStateMsg",
76
+ "viewUnbound", "modelUnbound", "msgUnbound",
77
+ ]);
78
+
79
+ /// One warning per top-level Model field, zero-argument model helper and
80
+ /// Msg kind that no view binds or dispatches, minus the `viewUnbound`
81
+ /// opt-outs and the host-channel helpers. Model-only state is legitimate,
82
+ /// so these are warnings.
83
+ export function unusedState(contract: CheckContract, usage: ViewUsage): string[] {
84
+ const warnings: string[] = [];
85
+ const modelUnbound = new Set(contract.model_unbound ?? []);
86
+ const msgUnbound = new Set(contract.msg.unbound ?? []);
87
+ const fields = contract.types.structs.find(item => item.name === contract.model)?.fields ?? [];
88
+ for (const field of fields) {
89
+ if (usage.model.has(field.name) || modelUnbound.has(field.name)) continue;
90
+ const type = field.type as Ref;
91
+ if (type.kind === "slice" && type.elem?.kind !== "u8") {
92
+ warnings.push(`model list "${field.name}" (${typeText(type)}) is never iterated in markup - use it with for each, or list it in viewUnbound if only update or effect logic reads it`);
93
+ } else if (["node", "value", "record"].includes(type.kind)) {
94
+ warnings.push(`model field "${field.name}" (${typeText(type)}) has no markup binding into any of its fields - bind one, or list it in viewUnbound if only update or effect logic reads it`);
95
+ } else {
96
+ warnings.push(`model field "${field.name}" (${typeText(type)}) is never bound in markup - bind it, or list it in viewUnbound if only update or effect logic reads it`);
97
+ }
98
+ }
99
+ for (const helper of contract.model_helpers) {
100
+ if (helper.params.length !== 0 || usage.model.has(helper.name) || modelUnbound.has(helper.name) || entryChannelExports.has(helper.name)) continue;
101
+ warnings.push(`model helper "${helper.name}" (returns ${typeText(helper.returns as Ref)}) is never bound in markup - bind it, remove it, or list it in viewUnbound if only update or effect logic calls it`);
102
+ }
103
+ for (const arm of contract.msg.arms) {
104
+ if (usage.msg.has(arm.name) || msgUnbound.has(arm.name)) continue;
105
+ warnings.push(`Msg kind "${arm.name}" is never dispatched from markup - wire it to an on-* event, or list it in viewUnbound if only update, subscriptions or effects send it`);
106
+ }
107
+ return warnings;
108
+ }
109
+
110
+ function typeText(ref: Ref): string {
111
+ switch (ref.kind) {
112
+ case "i64": case "f64": case "u64": case "u32": case "i32": case "number": return "number";
113
+ case "bool": return "boolean";
114
+ case "bytes": case "string": return "string";
115
+ case "slice": return ref.elem ? `${typeText(ref.elem)}[]` : "array";
116
+ default: return ref.name ?? ref.kind;
117
+ }
118
+ }
119
+
120
+ function main(argv: readonly string[]): number {
121
+ let contractPath: string | null = null;
122
+ let srcDir: string | null = null;
123
+ for (let i = 0; i < argv.length; i++) {
124
+ if (argv[i] === "--contract") contractPath = argv[++i] ?? null;
125
+ else if (argv[i] === "--src") srcDir = argv[++i] ?? null;
126
+ else {
127
+ console.error(`view_check: unknown argument ${argv[i]}`);
128
+ return 2;
129
+ }
130
+ }
131
+ if (!contractPath || !srcDir) {
132
+ console.error("usage: view_check.ts --contract <core.contract.json> --src <app src dir>");
133
+ return 2;
134
+ }
135
+ const contract = JSON.parse(fs.readFileSync(contractPath, "utf8")) as CheckContract;
136
+ const result = checkAppViews(contract, srcDir, path.relative(process.cwd(), srcDir).split(path.sep).join("/") || ".");
137
+ if (result.error) console.error(result.error);
138
+ for (const warning of result.warnings) console.error(`warning: ${warning}`);
139
+ process.stdout.write(JSON.stringify({ errors: result.error ? 1 : 0, warnings: result.warnings.length }) + "\n");
140
+ return 0;
141
+ }
142
+
143
+ if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
144
+ process.exitCode = main(process.argv.slice(2));
145
+ }