@nimiplatform/app-tools 0.1.3 → 0.2.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 (120) hide show
  1. package/LICENSE +198 -6
  2. package/README.md +83 -27
  3. package/bin/nimi-app.mjs +328 -45
  4. package/lib/app-access-declaration.mjs +49 -0
  5. package/lib/app-doctor-update.mjs +411 -149
  6. package/lib/app-pack.mjs +401 -0
  7. package/lib/app-project-lifecycle.mjs +1141 -0
  8. package/lib/app-scaffold-capabilities.mjs +769 -0
  9. package/lib/app-scaffold-default-source.mjs +21 -0
  10. package/lib/app-scaffold-profiles.mjs +1093 -0
  11. package/lib/app-scaffold.mjs +1266 -813
  12. package/lib/index.mjs +194 -42
  13. package/lib/simulator-conformance-ast.mjs +498 -0
  14. package/lib/simulator-conformance-css.mjs +116 -0
  15. package/lib/simulator-conformance-graph.mjs +757 -0
  16. package/lib/simulator-conformance.d.mts +14 -0
  17. package/lib/simulator-conformance.mjs +203 -0
  18. package/lib/simulator-css-profile.d.mts +27 -0
  19. package/lib/simulator-css-profile.mjs +531 -0
  20. package/lib/simulator-kit-export-resolution.mjs +70 -0
  21. package/lib/simulator-manifest.mjs +334 -0
  22. package/package.json +66 -3
  23. package/scripts/dev-shell.mjs +465 -0
  24. package/scripts/sync-app-source.mjs +300 -0
  25. package/scripts/sync-scaffold-versions.mjs +91 -0
  26. package/templates/app-source/LICENSE +21 -0
  27. package/templates/app-source/src/ai-studio-core/ai-config.ts +100 -0
  28. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +338 -0
  29. package/templates/app-source/src/ai-studio-core/contexts.tsx +61 -0
  30. package/templates/app-source/src/ai-studio-core/history-policy.ts +447 -0
  31. package/templates/app-source/src/ai-studio-core/history.ts +824 -0
  32. package/templates/app-source/src/ai-studio-core/host-context.tsx +79 -0
  33. package/templates/app-source/src/ai-studio-core/index.ts +214 -0
  34. package/templates/app-source/src/ai-studio-core/messages/en.json +310 -0
  35. package/templates/app-source/src/ai-studio-core/messages/index.ts +47 -0
  36. package/templates/app-source/src/ai-studio-core/messages/zh.json +310 -0
  37. package/templates/app-source/src/ai-studio-core/module-registration.ts +109 -0
  38. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +65 -0
  39. package/templates/app-source/src/ai-studio-core/parameter-fields.tsx +247 -0
  40. package/templates/app-source/src/ai-studio-core/parameters.ts +110 -0
  41. package/templates/app-source/src/ai-studio-core/prompt-drafts.ts +69 -0
  42. package/templates/app-source/src/ai-studio-core/run-target.ts +123 -0
  43. package/templates/app-source/src/ai-studio-core/runtime-dispatcher.ts +35 -0
  44. package/templates/app-source/src/ai-studio-core/runtime-types.ts +86 -0
  45. package/templates/app-source/src/ai-studio-core/runtime.ts +306 -0
  46. package/templates/app-source/src/ai-studio-core/section-ai-testing-admission.ts +38 -0
  47. package/templates/app-source/src/ai-studio-core/section-ai-testing-ai-config.tsx +30 -0
  48. package/templates/app-source/src/ai-studio-core/section-ai-testing-artifact-preview.ts +40 -0
  49. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +257 -0
  50. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +676 -0
  51. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +19 -0
  52. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +291 -0
  53. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +413 -0
  54. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +174 -0
  55. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +449 -0
  56. package/templates/app-source/src/ai-studio-core/section-ai-testing-surface.tsx +45 -0
  57. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +494 -0
  58. package/templates/app-source/src/ai-studio-core/studio-directives.ts +33 -0
  59. package/templates/app-source/src/ai-studio-core/workspace.tsx +381 -0
  60. package/templates/app-source/src/product-modules/agent-center/index.tsx +27 -0
  61. package/templates/app-source/src/product-modules/agent-conversation/index.tsx +19 -0
  62. package/templates/app-source/src/product-modules/agent-realtime/index.tsx +29 -0
  63. package/templates/app-source/src/product-modules/kit-recipes/gallery.tsx +142 -0
  64. package/templates/app-source/src/product-modules/kit-recipes/index.tsx +19 -0
  65. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-data-recipes.tsx +336 -0
  66. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-demos.tsx +165 -0
  67. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-recipes.tsx +682 -0
  68. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-surface.tsx +341 -0
  69. package/templates/app-source/src/studio-modules/studio-create/descriptors.ts +26 -0
  70. package/templates/app-source/src/studio-modules/studio-create/index.ts +14 -0
  71. package/templates/app-source/src/studio-modules/studio-create/messages/en.json +67 -0
  72. package/templates/app-source/src/studio-modules/studio-create/messages/index.ts +5 -0
  73. package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +67 -0
  74. package/templates/app-source/src/studio-modules/studio-create/parameter-panel.tsx +153 -0
  75. package/templates/app-source/src/studio-modules/studio-create/parameters.ts +70 -0
  76. package/templates/app-source/src/studio-modules/studio-create/registration.ts +46 -0
  77. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +339 -0
  78. package/templates/app-source/src/studio-modules/studio-media/descriptors.ts +22 -0
  79. package/templates/app-source/src/studio-modules/studio-media/index.ts +12 -0
  80. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +82 -0
  81. package/templates/app-source/src/studio-modules/studio-media/messages/index.ts +5 -0
  82. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +82 -0
  83. package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +283 -0
  84. package/templates/app-source/src/studio-modules/studio-media/parameters.ts +94 -0
  85. package/templates/app-source/src/studio-modules/studio-media/registration.ts +44 -0
  86. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +113 -0
  87. package/templates/app-source/src/studio-modules/studio-voice/descriptors.ts +28 -0
  88. package/templates/app-source/src/studio-modules/studio-voice/index.ts +16 -0
  89. package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +99 -0
  90. package/templates/app-source/src/studio-modules/studio-voice/messages/index.ts +5 -0
  91. package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +99 -0
  92. package/templates/app-source/src/studio-modules/studio-voice/parameter-panel.tsx +284 -0
  93. package/templates/app-source/src/studio-modules/studio-voice/parameters.ts +116 -0
  94. package/templates/app-source/src/studio-modules/studio-voice/registration.ts +59 -0
  95. package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +347 -0
  96. package/templates/app-source/src/workbench-core/empty-state.tsx +31 -0
  97. package/templates/app-source/src/workbench-core/index.ts +17 -0
  98. package/templates/app-source/src/workbench-core/runtime-gate.tsx +131 -0
  99. package/templates/app-source/src/workbench-core/workbench-core.css +255 -0
  100. package/templates/app-source/src/workbench-core/workbench-core.tsx +140 -0
  101. package/templates/app-source.manifest.json +333 -0
  102. package/templates/default-starter/AGENTS.md +33 -0
  103. package/templates/default-starter/LICENSE +21 -0
  104. package/templates/default-starter/README.md +41 -0
  105. package/templates/default-starter/SECURITY.md +5 -0
  106. package/templates/default-starter/index.html +12 -0
  107. package/templates/default-starter/scripts/validate.mjs +26 -0
  108. package/templates/default-starter/src/shell/App.tsx +27 -0
  109. package/templates/default-starter/src/shell/auth/app-identity.ts +3 -0
  110. package/templates/default-starter/src/shell/auth/local-app-client.ts +18 -0
  111. package/templates/default-starter/src/shell/auth/runtime-platform.ts +110 -0
  112. package/templates/default-starter/src/shell/authenticated-shell.tsx +20 -0
  113. package/templates/default-starter/src/shell/workbench-target-adapter.ts +40 -0
  114. package/templates/default-starter/src/styles.css +26 -0
  115. package/templates/default-starter/src-tauri/Cargo.toml +17 -0
  116. package/templates/default-starter/src-tauri/build.rs +5 -0
  117. package/templates/default-starter/src-tauri/capabilities/default.json +7 -0
  118. package/templates/default-starter/src-tauri/tauri.conf.json +26 -0
  119. package/templates/default-starter/tsconfig.json +18 -0
  120. package/templates/default-starter.manifest.json +99 -0
@@ -0,0 +1,401 @@
1
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-009b
2
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-018a
3
+
4
+ import { createHash } from 'node:crypto';
5
+ import {
6
+ existsSync,
7
+ lstatSync,
8
+ mkdirSync,
9
+ readFileSync,
10
+ readdirSync,
11
+ writeFileSync,
12
+ } from 'node:fs';
13
+ import path from 'node:path';
14
+ import { spawnSync } from 'node:child_process';
15
+ import { parse as parseYaml } from 'yaml';
16
+
17
+ const PACKAGE_FORMAT = 'nimi.app-package/v1';
18
+ const TARGET_METADATA_FORMAT = 'nimi.app-target-candidate/v1';
19
+ const AGGREGATE_FORMAT = 'nimi.app-release-candidate/v1';
20
+ const BUILD_PROFILE_PATH = '.nimi/config/build-profile.yaml';
21
+ const OUTPUT_DIR = 'dist/nimi-app';
22
+ const SEMVER_PATTERN = /^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?(?:\+[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?$/u;
23
+ const TARGETS = Object.freeze({
24
+ 'windows-x86_64': Object.freeze({ os: 'windows', arch: 'x86_64' }),
25
+ });
26
+
27
+ function compareText(left, right) {
28
+ return left < right ? -1 : left > right ? 1 : 0;
29
+ }
30
+
31
+ function sortedValue(value) {
32
+ if (Array.isArray(value)) return value.map(sortedValue);
33
+ if (!value || typeof value !== 'object') return value;
34
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, sortedValue(value[key])]));
35
+ }
36
+
37
+ function canonicalJson(value) {
38
+ return `${JSON.stringify(sortedValue(value), null, 2)}\n`;
39
+ }
40
+
41
+ function canonicalRelative(value, field) {
42
+ if (typeof value !== 'string' || !value || value !== value.trim() || value.includes('\\')) {
43
+ throw new Error(`${field} must be a canonical relative path`);
44
+ }
45
+ const parts = value.split('/');
46
+ if (value.startsWith('/') || parts.some((part) => !part || part === '.' || part === '..')) {
47
+ throw new Error(`${field} must be a canonical relative path`);
48
+ }
49
+ return value;
50
+ }
51
+
52
+ function resolveInside(root, relative, field) {
53
+ const normalized = canonicalRelative(relative, field);
54
+ const resolved = path.resolve(root, ...normalized.split('/'));
55
+ const prefix = `${path.resolve(root)}${path.sep}`;
56
+ if (!resolved.startsWith(prefix)) throw new Error(`${field} escapes the App repository`);
57
+ return { normalized, resolved };
58
+ }
59
+
60
+ function readJson(filePath, label) {
61
+ try {
62
+ const value = JSON.parse(readFileSync(filePath, 'utf8'));
63
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('root must be an object');
64
+ return value;
65
+ } catch (error) {
66
+ throw new Error(`Invalid ${label}: ${error instanceof Error ? error.message : String(error)}`);
67
+ }
68
+ }
69
+
70
+ function readYaml(filePath, label) {
71
+ if (!existsSync(filePath)) throw new Error(`${label} is missing: ${filePath}`);
72
+ try {
73
+ const value = parseYaml(readFileSync(filePath, 'utf8'));
74
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('root must be an object');
75
+ return value;
76
+ } catch (error) {
77
+ throw new Error(`Invalid ${label}: ${error instanceof Error ? error.message : String(error)}`);
78
+ }
79
+ }
80
+
81
+ function readCargoPackageVersion(source) {
82
+ let inPackage = false;
83
+ for (const line of source.split(/\r?\n/u)) {
84
+ const header = line.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/u);
85
+ if (header) {
86
+ inPackage = header[1] === 'package';
87
+ continue;
88
+ }
89
+ if (!inPackage) continue;
90
+ const match = line.match(/^\s*version\s*=\s*"([^"]+)"\s*(?:#.*)?$/u);
91
+ if (match) return match[1];
92
+ }
93
+ throw new Error('src-tauri/Cargo.toml [package] version is missing');
94
+ }
95
+
96
+ function collectPayload(payloadPath) {
97
+ const stat = lstatSync(payloadPath);
98
+ if (stat.isSymbolicLink()) throw new Error('Pack payload must not contain symbolic links');
99
+ if (stat.isFile()) {
100
+ return [{ relative: path.basename(payloadPath), bytes: readFileSync(payloadPath), mode: stat.mode & 0o111 ? 0o755 : 0o644 }];
101
+ }
102
+ if (!stat.isDirectory()) throw new Error('Pack payload must be a regular file or directory');
103
+ const entries = [];
104
+ const walk = (current, prefix = '') => {
105
+ for (const entry of readdirSync(current, { withFileTypes: true }).sort((left, right) => compareText(left.name, right.name))) {
106
+ const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
107
+ const absolute = path.join(current, entry.name);
108
+ const entryStat = lstatSync(absolute);
109
+ if (entryStat.isSymbolicLink()) throw new Error(`Pack payload must not contain symbolic links: ${relative}`);
110
+ if (entryStat.isDirectory()) {
111
+ walk(absolute, relative);
112
+ } else if (entryStat.isFile()) {
113
+ entries.push({ relative, bytes: readFileSync(absolute), mode: entryStat.mode & 0o111 ? 0o755 : 0o644 });
114
+ } else {
115
+ throw new Error(`Unsupported pack payload entry: ${relative}`);
116
+ }
117
+ }
118
+ };
119
+ walk(payloadPath);
120
+ if (entries.length === 0) throw new Error('Pack payload must not be empty');
121
+ return entries;
122
+ }
123
+
124
+ const CRC_TABLE = (() => {
125
+ const table = new Uint32Array(256);
126
+ for (let index = 0; index < 256; index += 1) {
127
+ let value = index;
128
+ for (let bit = 0; bit < 8; bit += 1) value = (value & 1) ? (0xedb88320 ^ (value >>> 1)) : (value >>> 1);
129
+ table[index] = value >>> 0;
130
+ }
131
+ return table;
132
+ })();
133
+
134
+ function crc32(bytes) {
135
+ let crc = 0xffffffff;
136
+ for (const byte of bytes) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
137
+ return (crc ^ 0xffffffff) >>> 0;
138
+ }
139
+
140
+ function zipEntryName(value) {
141
+ const name = canonicalRelative(value, 'archive entry');
142
+ if (Buffer.byteLength(name) > 0xffff) throw new Error(`Archive entry path is too long: ${name}`);
143
+ return name;
144
+ }
145
+
146
+ export function writeNimiAppArchive(entries) {
147
+ const normalized = entries.map((entry) => ({
148
+ name: zipEntryName(entry.name),
149
+ bytes: Buffer.isBuffer(entry.bytes) ? entry.bytes : Buffer.from(entry.bytes),
150
+ mode: entry.mode === 0o755 ? 0o755 : 0o644,
151
+ })).sort((left, right) => compareText(left.name, right.name));
152
+ if (normalized.length === 0) throw new Error('nimiapp archive requires at least one file');
153
+ if (new Set(normalized.map((entry) => entry.name)).size !== normalized.length) throw new Error('nimiapp archive entries must be unique');
154
+
155
+ const localParts = [];
156
+ const centralParts = [];
157
+ let offset = 0;
158
+ for (const entry of normalized) {
159
+ if (entry.bytes.length > 0xffffffff) throw new Error(`Archive entry is too large: ${entry.name}`);
160
+ const name = Buffer.from(entry.name, 'utf8');
161
+ const crc = crc32(entry.bytes);
162
+ const local = Buffer.alloc(30);
163
+ local.writeUInt32LE(0x04034b50, 0);
164
+ local.writeUInt16LE(20, 4);
165
+ local.writeUInt16LE(0x0800, 6);
166
+ local.writeUInt16LE(0, 8);
167
+ local.writeUInt16LE(0, 10);
168
+ local.writeUInt16LE(0x0021, 12);
169
+ local.writeUInt32LE(crc, 14);
170
+ local.writeUInt32LE(entry.bytes.length, 18);
171
+ local.writeUInt32LE(entry.bytes.length, 22);
172
+ local.writeUInt16LE(name.length, 26);
173
+ local.writeUInt16LE(0, 28);
174
+ localParts.push(local, name, entry.bytes);
175
+
176
+ const central = Buffer.alloc(46);
177
+ central.writeUInt32LE(0x02014b50, 0);
178
+ central.writeUInt16LE(0x0314, 4);
179
+ central.writeUInt16LE(20, 6);
180
+ central.writeUInt16LE(0x0800, 8);
181
+ central.writeUInt16LE(0, 10);
182
+ central.writeUInt16LE(0, 12);
183
+ central.writeUInt16LE(0x0021, 14);
184
+ central.writeUInt32LE(crc, 16);
185
+ central.writeUInt32LE(entry.bytes.length, 20);
186
+ central.writeUInt32LE(entry.bytes.length, 24);
187
+ central.writeUInt16LE(name.length, 28);
188
+ central.writeUInt16LE(0, 30);
189
+ central.writeUInt16LE(0, 32);
190
+ central.writeUInt16LE(0, 34);
191
+ central.writeUInt16LE(0, 36);
192
+ central.writeUInt32LE(((0o100000 | entry.mode) << 16) >>> 0, 38);
193
+ central.writeUInt32LE(offset, 42);
194
+ centralParts.push(central, name);
195
+ offset += local.length + name.length + entry.bytes.length;
196
+ }
197
+ const central = Buffer.concat(centralParts);
198
+ const end = Buffer.alloc(22);
199
+ end.writeUInt32LE(0x06054b50, 0);
200
+ end.writeUInt16LE(0, 4);
201
+ end.writeUInt16LE(0, 6);
202
+ end.writeUInt16LE(normalized.length, 8);
203
+ end.writeUInt16LE(normalized.length, 10);
204
+ end.writeUInt32LE(central.length, 12);
205
+ end.writeUInt32LE(offset, 16);
206
+ end.writeUInt16LE(0, 20);
207
+ return Buffer.concat([...localParts, central, end]);
208
+ }
209
+
210
+ export function readNimiAppArchive(bytes) {
211
+ const archive = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
212
+ if (archive.length < 22 || archive.readUInt32LE(archive.length - 22) !== 0x06054b50) throw new Error('Invalid nimiapp ZIP end record');
213
+ const endOffset = archive.length - 22;
214
+ const count = archive.readUInt16LE(endOffset + 10);
215
+ const centralSize = archive.readUInt32LE(endOffset + 12);
216
+ const centralOffset = archive.readUInt32LE(endOffset + 16);
217
+ if (centralOffset + centralSize !== endOffset || count !== archive.readUInt16LE(endOffset + 8)) throw new Error('Invalid nimiapp ZIP directory');
218
+ const entries = new Map();
219
+ let cursor = centralOffset;
220
+ for (let index = 0; index < count; index += 1) {
221
+ if (archive.readUInt32LE(cursor) !== 0x02014b50) throw new Error('Invalid nimiapp ZIP central entry');
222
+ const method = archive.readUInt16LE(cursor + 10);
223
+ const expectedCrc = archive.readUInt32LE(cursor + 16);
224
+ const size = archive.readUInt32LE(cursor + 24);
225
+ const nameLength = archive.readUInt16LE(cursor + 28);
226
+ const extraLength = archive.readUInt16LE(cursor + 30);
227
+ const commentLength = archive.readUInt16LE(cursor + 32);
228
+ const localOffset = archive.readUInt32LE(cursor + 42);
229
+ const mode = (archive.readUInt32LE(cursor + 38) >>> 16) & 0o777;
230
+ if (method !== 0 || extraLength !== 0 || commentLength !== 0) throw new Error('Unsupported nimiapp ZIP entry encoding');
231
+ if (mode !== 0o644 && mode !== 0o755) throw new Error('Unsupported nimiapp ZIP entry mode');
232
+ const name = zipEntryName(archive.subarray(cursor + 46, cursor + 46 + nameLength).toString('utf8'));
233
+ if (entries.has(name) || archive.readUInt32LE(localOffset) !== 0x04034b50) throw new Error('Invalid or duplicate nimiapp ZIP entry');
234
+ const localNameLength = archive.readUInt16LE(localOffset + 26);
235
+ const localExtraLength = archive.readUInt16LE(localOffset + 28);
236
+ const localName = archive.subarray(localOffset + 30, localOffset + 30 + localNameLength).toString('utf8');
237
+ if (localName !== name || localExtraLength !== 0 || archive.readUInt16LE(localOffset + 8) !== 0) {
238
+ throw new Error('Invalid nimiapp ZIP local entry');
239
+ }
240
+ const dataOffset = localOffset + 30 + localNameLength + localExtraLength;
241
+ const payload = archive.subarray(dataOffset, dataOffset + size);
242
+ if (payload.length !== size || crc32(payload) !== expectedCrc) throw new Error(`nimiapp ZIP entry digest mismatch: ${name}`);
243
+ entries.set(name, Object.freeze({ bytes: Buffer.from(payload), mode }));
244
+ cursor += 46 + nameLength;
245
+ }
246
+ if (cursor !== centralOffset + centralSize) throw new Error('Invalid nimiapp ZIP directory size');
247
+ const names = [...entries.keys()];
248
+ if (names.some((name, index) => index > 0 && compareText(names[index - 1], name) >= 0)) throw new Error('nimiapp ZIP entries are not canonical');
249
+ return entries;
250
+ }
251
+
252
+ function readPackInputs(targetDir, targetId) {
253
+ const target = TARGETS[targetId];
254
+ if (!target) throw new Error(`Unsupported App package target: ${targetId}`);
255
+ const packageJson = readJson(path.join(targetDir, 'package.json'), 'package.json');
256
+ const licensePath = path.join(targetDir, 'LICENSE');
257
+ if (!existsSync(licensePath)) throw new Error('App package LICENSE is missing');
258
+ const licenseStat = lstatSync(licensePath);
259
+ if (!licenseStat.isFile() || licenseStat.isSymbolicLink() || licenseStat.size === 0) {
260
+ throw new Error('App package LICENSE must be a non-empty direct regular file');
261
+ }
262
+ const manifestPath = path.join(targetDir, 'nimi.app.yaml');
263
+ const manifest = readYaml(manifestPath, 'nimi.app.yaml');
264
+ const cargoPath = path.join(targetDir, 'src-tauri', 'Cargo.toml');
265
+ if (!existsSync(cargoPath)) throw new Error('src-tauri/Cargo.toml is missing');
266
+ const tauriConfig = readJson(path.join(targetDir, 'src-tauri', 'tauri.conf.json'), 'src-tauri/tauri.conf.json');
267
+ const buildProfile = readYaml(path.join(targetDir, BUILD_PROFILE_PATH), BUILD_PROFILE_PATH);
268
+ const appId = String(manifest.app_id || '');
269
+ const version = String(packageJson.version || '');
270
+ if (!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/u.test(appId)) throw new Error('nimi.app.yaml app_id must be canonical and dotted');
271
+ if (
272
+ !SEMVER_PATTERN.test(version)
273
+ || manifest.version !== version
274
+ || readCargoPackageVersion(readFileSync(cargoPath, 'utf8')) !== version
275
+ || tauriConfig.version !== version
276
+ ) {
277
+ throw new Error('package.json, nimi.app.yaml, Cargo.toml, and tauri.conf.json versions must be exact and lockstep before pack');
278
+ }
279
+ const configured = buildProfile.targets?.[targetId];
280
+ if (!configured || typeof configured !== 'object' || Array.isArray(configured)) throw new Error(`Build profile does not declare target: ${targetId}`);
281
+ if (configured.os !== target.os || configured.arch !== target.arch) throw new Error(`Build profile target identity mismatch: ${targetId}`);
282
+ const payload = resolveInside(targetDir, configured.payload_path, `targets.${targetId}.payload_path`);
283
+ if (!existsSync(payload.resolved)) throw new Error(`Built target payload is missing: ${payload.normalized}`);
284
+ const runtimeEntry = canonicalRelative(configured.runtime_entry, `targets.${targetId}.runtime_entry`);
285
+ if (!runtimeEntry.startsWith('payload/')) throw new Error('runtime_entry must resolve inside the packaged payload');
286
+ const payloadStat = lstatSync(payload.resolved);
287
+ const runtimeRelative = runtimeEntry.slice('payload/'.length);
288
+ const runtimeHostPath = payloadStat.isFile()
289
+ ? payload.resolved
290
+ : resolveInside(payload.resolved, runtimeRelative, `targets.${targetId}.runtime_entry`).resolved;
291
+ return { target, targetId, targetDir, packageJson, licensePath, manifestPath, appId, version, payloadPath: payload.resolved, runtimeEntry, runtimeHostPath };
292
+ }
293
+
294
+ function requireCommand(result, label) {
295
+ if (result.status !== 0) {
296
+ const detail = [result.error?.message, result.stdout, result.stderr].filter(Boolean).join('\n').trim();
297
+ throw new Error(`${label} failed${detail ? `: ${detail}` : ''}`);
298
+ }
299
+ return [result.stdout, result.stderr].filter(Boolean).join('\n');
300
+ }
301
+
302
+ function verifyWindowsNativeTrust(input) {
303
+ if (process.platform !== 'win32' || process.arch !== 'x64') throw new Error('Production Windows pack must run on windows-x86_64');
304
+ const result = spawnSync('powershell.exe', [
305
+ '-NoProfile',
306
+ '-NonInteractive',
307
+ '-Command',
308
+ "$signature = Get-AuthenticodeSignature -LiteralPath $env:NIMI_APP_SIGN_TARGET; if ($signature.Status -ne 'Valid' -or -not $signature.SignerCertificate) { Write-Error ('Authenticode status: ' + $signature.Status); exit 1 }; $signature.SignerCertificate.Subject",
309
+ ], {
310
+ encoding: 'utf8',
311
+ env: { ...process.env, NIMI_APP_SIGN_TARGET: input.runtimeHostPath },
312
+ });
313
+ const subject = requireCommand(result, 'Windows Authenticode verification').trim();
314
+ if (!subject) throw new Error('Windows Authenticode verification returned no signer subject');
315
+ return {
316
+ posture: 'observed-valid-native-signature',
317
+ windows_authenticode: 'valid',
318
+ certificate_subject: subject,
319
+ };
320
+ }
321
+
322
+ function resolveNativeTrust(input, production) {
323
+ if (!production) return { posture: 'development-unsigned' };
324
+ return verifyWindowsNativeTrust(input);
325
+ }
326
+
327
+ export function packAppTarget(cwd, options = {}) {
328
+ const targetDir = path.resolve(cwd, String(options.dir || '').trim() || '.');
329
+ const targetId = String(options.target || '').trim();
330
+ if (!targetId) throw new Error('nimi-app pack requires --target');
331
+ const input = readPackInputs(targetDir, targetId);
332
+ const payloadEntries = collectPayload(input.payloadPath).map((entry) => {
333
+ const name = `payload/${entry.relative.replaceAll('\\', '/')}`;
334
+ return { name, bytes: entry.bytes, mode: name === input.runtimeEntry ? 0o755 : entry.mode };
335
+ });
336
+ if (!payloadEntries.some((entry) => entry.name === input.runtimeEntry)) throw new Error(`runtime_entry is missing from target payload: ${input.runtimeEntry}`);
337
+ const nativeTrust = resolveNativeTrust(input, options.production === true);
338
+ const packageManifest = {
339
+ format: PACKAGE_FORMAT,
340
+ app_id: input.appId,
341
+ version: input.version,
342
+ target_id: input.targetId,
343
+ os: input.target.os,
344
+ arch: input.target.arch,
345
+ runtime_entry: input.runtimeEntry,
346
+ native_trust: nativeTrust,
347
+ };
348
+ const archive = writeNimiAppArchive([
349
+ { name: 'LICENSE', bytes: readFileSync(input.licensePath), mode: 0o644 },
350
+ { name: 'manifest.json', bytes: canonicalJson(packageManifest), mode: 0o644 },
351
+ { name: 'nimi.app.yaml', bytes: readFileSync(input.manifestPath), mode: 0o644 },
352
+ ...payloadEntries,
353
+ ]);
354
+ const sha256 = createHash('sha256').update(archive).digest('hex');
355
+ const outputDir = path.join(targetDir, OUTPUT_DIR);
356
+ mkdirSync(outputDir, { recursive: true });
357
+ const stem = `${input.appId}-${input.version}-${input.targetId}`;
358
+ const artifactPath = path.join(outputDir, `${stem}.nimiapp`);
359
+ const metadataPath = path.join(outputDir, `${stem}.target.json`);
360
+ writeFileSync(artifactPath, archive);
361
+ const metadata = {
362
+ format: TARGET_METADATA_FORMAT,
363
+ app_id: input.appId,
364
+ version: input.version,
365
+ target_id: input.targetId,
366
+ os: input.target.os,
367
+ arch: input.target.arch,
368
+ asset_name: path.basename(artifactPath),
369
+ size: archive.length,
370
+ sha256,
371
+ runtime_entry: input.runtimeEntry,
372
+ native_trust: packageManifest.native_trust,
373
+ };
374
+ writeFileSync(metadataPath, canonicalJson(metadata));
375
+ return { ok: true, command: 'pack', dir: targetDir, artifactPath, metadataPath, ...metadata };
376
+ }
377
+
378
+ export function aggregateAppTargetCandidates(cwd, options = {}) {
379
+ const targetDir = path.resolve(cwd, String(options.dir || '').trim() || '.');
380
+ const outputDir = path.join(targetDir, OUTPUT_DIR);
381
+ if (!existsSync(outputDir)) throw new Error('No target metadata exists to aggregate');
382
+ const files = readdirSync(outputDir).filter((name) => name.endsWith('.target.json')).sort();
383
+ if (files.length === 0) throw new Error('No target metadata exists to aggregate');
384
+ const targets = files.map((name) => readJson(path.join(outputDir, name), name));
385
+ const appId = targets[0].app_id;
386
+ const version = targets[0].version;
387
+ const seen = new Set();
388
+ for (const target of targets) {
389
+ if (target.format !== TARGET_METADATA_FORMAT || target.app_id !== appId || target.version !== version) throw new Error('Target metadata cannot be aggregated across App releases');
390
+ if (seen.has(target.target_id)) throw new Error(`Duplicate target metadata: ${target.target_id}`);
391
+ seen.add(target.target_id);
392
+ const artifactPath = path.join(outputDir, target.asset_name);
393
+ if (!existsSync(artifactPath)) throw new Error(`Target artifact is missing: ${target.asset_name}`);
394
+ const bytes = readFileSync(artifactPath);
395
+ if (bytes.length !== target.size || createHash('sha256').update(bytes).digest('hex') !== target.sha256) throw new Error(`Target artifact changed after pack: ${target.asset_name}`);
396
+ }
397
+ const candidate = { format: AGGREGATE_FORMAT, app_id: appId, version, targets: targets.sort((left, right) => compareText(left.target_id, right.target_id)) };
398
+ const candidatePath = path.join(outputDir, `${appId}-${version}.candidate.json`);
399
+ writeFileSync(candidatePath, canonicalJson(candidate));
400
+ return { ok: true, command: 'pack', aggregate: true, dir: targetDir, candidatePath, ...candidate };
401
+ }