@nimiplatform/app-tools 0.16.0-rc.14 → 0.16.0-rc.18

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 (84) hide show
  1. package/README.md +5 -42
  2. package/bin/nimi-app.mjs +25 -6
  3. package/lib/app-dependency-combinations.mjs +1 -0
  4. package/lib/app-doctor-update.mjs +8 -6
  5. package/lib/app-info.mjs +39 -19
  6. package/lib/app-lifecycle-guidance.mjs +1 -1
  7. package/lib/app-pack.mjs +31 -13
  8. package/lib/app-project-lifecycle.mjs +32 -12
  9. package/lib/app-resources.mjs +36 -0
  10. package/lib/app-scaffold-profiles.mjs +72 -2
  11. package/lib/app-scaffold.mjs +11 -13
  12. package/lib/index.mjs +7 -0
  13. package/lib/public-storefront.mjs +327 -0
  14. package/lib/storefront-media.mjs +8 -4
  15. package/lib/storefront-pack.mjs +152 -0
  16. package/lib/storefront-release-verification.mjs +31 -0
  17. package/lib/storefront-source.mjs +161 -0
  18. package/lib/web-coordination.mjs +4 -1
  19. package/lib/web-scaffold.mjs +3 -3
  20. package/package.json +9 -6
  21. package/scripts/sync-app-source.mjs +5 -12
  22. package/skills/nimi-app-lifecycle/SKILL.md +1 -0
  23. package/skills/nimi-app-lifecycle/references/storefront.md +28 -0
  24. package/templates/app-source/src/ai-studio-core/ai-config.ts +12 -0
  25. package/templates/app-source/src/ai-studio-core/ai-studio-core.css +138 -117
  26. package/templates/app-source/src/ai-studio-core/history.ts +10 -8
  27. package/templates/app-source/src/ai-studio-core/host-context.tsx +1 -0
  28. package/templates/app-source/src/ai-studio-core/job-recovery-panel.tsx +15 -10
  29. package/templates/app-source/src/ai-studio-core/job-recovery.ts +505 -115
  30. package/templates/app-source/src/ai-studio-core/messages/en.json +55 -9
  31. package/templates/app-source/src/ai-studio-core/messages/zh.json +55 -9
  32. package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +8 -2
  33. package/templates/app-source/src/ai-studio-core/parameter-fields.tsx +2 -0
  34. package/templates/app-source/src/ai-studio-core/parameters.ts +5 -4
  35. package/templates/app-source/src/ai-studio-core/run-target.ts +12 -1
  36. package/templates/app-source/src/ai-studio-core/runtime-types.ts +3 -0
  37. package/templates/app-source/src/ai-studio-core/runtime.ts +50 -12
  38. package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +6 -7
  39. package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +88 -27
  40. package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +33 -0
  41. package/templates/app-source/src/ai-studio-core/section-ai-testing-music-result.tsx +2 -2
  42. package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +10 -3
  43. package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +6 -4
  44. package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +121 -40
  45. package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +34 -8
  46. package/templates/app-source/src/ai-studio-core/section-ai-testing-transcript-result.tsx +16 -2
  47. package/templates/app-source/src/ai-studio-core/section-ai-testing-transcription-result.tsx +18 -7
  48. package/templates/app-source/src/ai-studio-core/section-ai-testing-vision-result.tsx +1 -1
  49. package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +78 -9
  50. package/templates/app-source/src/ai-studio-core/text-media-replay.ts +2 -1
  51. package/templates/app-source/src/ai-studio-core/workspace.tsx +138 -3
  52. package/templates/app-source/src/product-modules/agent-center/index.tsx +19 -3
  53. package/templates/app-source/src/product-modules/agent-conversation/index.tsx +19 -3
  54. package/templates/app-source/src/product-modules/agent-realtime/index.tsx +19 -3
  55. package/templates/app-source/src/product-modules/kit-recipes/gallery.tsx +12 -7
  56. package/templates/app-source/src/product-modules/kit-recipes/kit-component-gallery-surface.tsx +48 -20
  57. package/templates/app-source/src/studio-modules/studio-create/messages/en.json +2 -2
  58. package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +2 -2
  59. package/templates/app-source/src/studio-modules/studio-create/registration.ts +1 -1
  60. package/templates/app-source/src/studio-modules/studio-create/runtime.ts +11 -19
  61. package/templates/app-source/src/studio-modules/studio-media/audio-separate-parameters.tsx +7 -4
  62. package/templates/app-source/src/studio-modules/studio-media/audio-separate-runtime.ts +14 -10
  63. package/templates/app-source/src/studio-modules/studio-media/messages/en.json +3 -1
  64. package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +3 -1
  65. package/templates/app-source/src/studio-modules/studio-media/music-parameters.tsx +6 -5
  66. package/templates/app-source/src/studio-modules/studio-media/music-transcription-parameters.tsx +19 -11
  67. package/templates/app-source/src/studio-modules/studio-media/music-transcription-runtime.ts +14 -10
  68. package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +54 -16
  69. package/templates/app-source/src/studio-modules/studio-media/runtime.ts +22 -9
  70. package/templates/app-source/src/studio-modules/studio-media/vision-runtime.ts +19 -10
  71. package/templates/app-source/src/studio-modules/studio-media/voice-convert-parameters.tsx +12 -6
  72. package/templates/app-source/src/studio-modules/studio-media/voice-convert-runtime.ts +11 -9
  73. package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +5 -0
  74. package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +5 -0
  75. package/templates/app-source/src/studio-modules/studio-voice/parameter-panel.tsx +18 -7
  76. package/templates/app-source/src/studio-modules/studio-voice/parameters.ts +28 -4
  77. package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +12 -8
  78. package/templates/app-source/src/workbench-core/runtime-gate.tsx +171 -44
  79. package/templates/app-source/src/workbench-core/workbench-core.css +226 -23
  80. package/templates/app-source/src/workbench-core/workbench-core.tsx +5 -5
  81. package/templates/app-source.manifest.json +2 -2
  82. package/templates/default-starter/NIMI_APP.md +11 -3
  83. package/templates/default-starter.manifest.json +2 -2
  84. package/templates/storefront-release.yml +97 -0
@@ -0,0 +1,36 @@
1
+ import { lstatSync, readFileSync, realpathSync } from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ export function readAppResource(root, relative, label, maxBytes) {
5
+ if (
6
+ typeof relative !== 'string' ||
7
+ path.isAbsolute(relative) ||
8
+ /[\\:\x00]/u.test(relative) ||
9
+ relative.split('/').some((part) => !part || part === '.' || part === '..')
10
+ ) {
11
+ throw new Error('metadata.' + label + ' must name an App-relative resource');
12
+ }
13
+ const field =
14
+ label === 'license' ? 'App license' : label === 'introduction' ? 'NIMI_APP.md' : 'metadata.' + label;
15
+ const file = path.join(root, relative);
16
+ try {
17
+ const stat = lstatSync(file);
18
+ const physical = path.relative(realpathSync(root), realpathSync(file));
19
+ if (
20
+ physical === '..' ||
21
+ physical.startsWith('..' + path.sep) ||
22
+ path.isAbsolute(physical) ||
23
+ !stat.isFile() ||
24
+ stat.isSymbolicLink() ||
25
+ stat.size === 0 ||
26
+ stat.size > maxBytes
27
+ ) {
28
+ throw new Error('must be a nonempty regular file inside the App of at most ' + maxBytes + ' bytes');
29
+ }
30
+ return readFileSync(file);
31
+ } catch (error) {
32
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR')
33
+ throw new Error(field + ' resource is missing: ' + relative);
34
+ throw new Error(field + ' resource ' + relative + ': ' + error.message, { cause: error });
35
+ }
36
+ }
@@ -252,6 +252,7 @@ function renderDefaultElectronProductionPackager(identity) {
252
252
  "const appPackage = JSON.parse(await readFile(path.join(appRoot, 'package.json'), 'utf8'));",
253
253
  'const APP_VERSION = appPackage.version;',
254
254
  'const RESOURCE_VERSION = MACOS_BUILD ? APP_VERSION : resolveWindowsResourceVersion(APP_VERSION);',
255
+ "const APP_DECLARES_SHARP = Object.hasOwn(appPackage.dependencies || {}, 'sharp');",
255
256
  "for (const sectionName of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']) {",
256
257
  ' if (Object.hasOwn(appPackage[sectionName] || {}, NATIVE_BINDING_PACKAGE)) {',
257
258
  " throw new Error('The protected native binding must arrive through the Kit optional dependency.');",
@@ -342,6 +343,9 @@ function renderDefaultElectronProductionPackager(identity) {
342
343
  ' : installedNativePackage;',
343
344
  ' await mkdir(path.dirname(nativeDestination), { recursive: true });',
344
345
  ' await cp(nativePackageRoot, nativeDestination, { recursive: true, dereference: true, force: false });',
346
+ ' if (APP_DECLARES_SHARP) {',
347
+ ' await stageDeclaredSharpRuntime(productionSourceRoot);',
348
+ ' }',
345
349
  ' await mkdir(packagerTempRoot, { recursive: true });',
346
350
  '',
347
351
  ' const packagePaths = await packager({',
@@ -349,7 +353,7 @@ function renderDefaultElectronProductionPackager(identity) {
349
353
  ' icon: MACOS_BUILD ? icons.icns : icons.ico,',
350
354
  ' platform: NATIVE_PLATFORM,',
351
355
  ' arch: NATIVE_ARCH,',
352
- ` appBundleId: ${JSON.stringify(identity.tauriIdentifier)},`,
356
+ ` appBundleId: ${JSON.stringify(identity.nativeBundleIdentifier)},`,
353
357
  ' name: APP_EXECUTABLE_NAME,',
354
358
  ' executableName: APP_EXECUTABLE_NAME,',
355
359
  ' appVersion: RESOURCE_VERSION,',
@@ -471,7 +475,11 @@ function renderDefaultElectronProductionPackager(identity) {
471
475
  ' const forbiddenPatterns = [',
472
476
  ' /(?:^|\\/)@electron-internal(?:\\/|$)/,',
473
477
  ' /(?:^|\\/)node_modules\\/typescript(?:\\/|$)/,',
474
- ' /(?:^|\\/)@img\\/sharp-/,',
478
+ ' ...(APP_DECLARES_SHARP',
479
+ ' ? [MACOS_BUILD',
480
+ ' ? /(?:^|\\/)@img\\/sharp-(?:libvips-)?(?!darwin-arm64(?:\\/|$))/',
481
+ ' : /(?:^|\\/)@img\\/sharp-(?:libvips-)?(?!win32-x64(?:\\/|$))/]',
482
+ ' : [/(?:^|\\/)@img\\/sharp-/]),',
475
483
  ' ...(MACOS_BUILD',
476
484
  ' ? [/\\.dll$/i, /(?:^|\\/)kit-protected-local-win32-x64(?:\\/|$)/, /win32-x64.*\\.node$/i, /linux-.*\\.node$/i]',
477
485
  ' : [/\\.dylib$/i, /(?:^|\\/)kit-protected-local-darwin-arm64(?:\\/|$)/, /darwin-arm64.*\\.node$/i, /linux-.*\\.node$/i]),',
@@ -485,6 +493,68 @@ function renderDefaultElectronProductionPackager(identity) {
485
493
  ' }',
486
494
  '}',
487
495
  '',
496
+ 'async function resolveInstalledPackageDir(packageName, fromRoot) {',
497
+ " const parts = packageName.split('/');",
498
+ ' let current = fromRoot;',
499
+ ' for (;;) {',
500
+ " const candidates = [path.join(current, 'node_modules', ...parts)];",
501
+ " if (path.basename(current) === 'node_modules') {",
502
+ ' candidates.unshift(path.join(current, ...parts));',
503
+ ' }',
504
+ ' for (const candidate of candidates) {',
505
+ ' try {',
506
+ ' return await realpath(candidate);',
507
+ ' } catch (error) {',
508
+ " if (error?.code !== 'ENOENT') throw error;",
509
+ ' }',
510
+ ' }',
511
+ ' const parent = path.dirname(current);',
512
+ ' if (parent === current) break;',
513
+ ' current = parent;',
514
+ ' }',
515
+ ' try {',
516
+ " return await realpath(path.join(appRoot, 'node_modules', ...parts));",
517
+ ' } catch (error) {',
518
+ " if (error?.code === 'ENOENT') return null;",
519
+ ' throw error;',
520
+ ' }',
521
+ '}',
522
+ '',
523
+ 'async function stageDeclaredSharpRuntime(sourceRoot) {',
524
+ " const sharpRoot = await resolveInstalledPackageDir('sharp', appRoot);",
525
+ ' if (!sharpRoot) {',
526
+ " throw new Error('App declares sharp in dependencies, but node_modules/sharp could not be resolved.');",
527
+ ' }',
528
+ ' const platformSuffix = `-${NATIVE_PLATFORM}-${NATIVE_ARCH}`;',
529
+ ' const staged = new Set();',
530
+ " const queue = [['sharp', sharpRoot]];",
531
+ ' while (queue.length > 0) {',
532
+ ' const [pkgName, pkgRoot] = queue.shift();',
533
+ ' if (staged.has(pkgName)) continue;',
534
+ ' staged.add(pkgName);',
535
+ " const destination = path.join(sourceRoot, 'node_modules', ...pkgName.split('/'));",
536
+ ' await mkdir(path.dirname(destination), { recursive: true });',
537
+ ' await cp(pkgRoot, destination, { recursive: true, dereference: true, force: false });',
538
+ " const manifest = JSON.parse(await readFile(path.join(pkgRoot, 'package.json'), 'utf8'));",
539
+ ' for (const depName of Object.keys(manifest.dependencies || {})) {',
540
+ ' if (staged.has(depName)) continue;',
541
+ ' const depRoot = await resolveInstalledPackageDir(depName, pkgRoot);',
542
+ ' if (!depRoot) {',
543
+ ' throw new Error(`Unable to resolve declared sharp dependency ${depName} from ${pkgName}.`);',
544
+ ' }',
545
+ ' queue.push([depName, depRoot]);',
546
+ ' }',
547
+ ' for (const optName of Object.keys(manifest.optionalDependencies || {})) {',
548
+ ' if (!optName.endsWith(platformSuffix) || staged.has(optName)) continue;',
549
+ ' const optRoot = await resolveInstalledPackageDir(optName, pkgRoot);',
550
+ ' if (!optRoot) {',
551
+ ' throw new Error(`Unable to resolve declared sharp platform package ${optName} from ${pkgName}.`);',
552
+ ' }',
553
+ ' queue.push([optName, optRoot]);',
554
+ ' }',
555
+ ' }',
556
+ '}',
557
+ '',
488
558
  'async function findPackageRoot(entry, expectedName) {',
489
559
  ' let current = path.dirname(await realpath(entry));',
490
560
  ' for (;;) {',
@@ -472,7 +472,7 @@ function appSlugFromAppId(appId) {
472
472
  return packageSafeName(appId);
473
473
  }
474
474
 
475
- function tauriIdentifierFromAppId(appId) {
475
+ function nativeBundleIdentifierFromAppId(appId) {
476
476
  const suffix = String(appId || DEFAULT_APP_ID)
477
477
  .toLowerCase()
478
478
  .replace(/[^a-z0-9.-]+/g, '.')
@@ -504,7 +504,7 @@ function assertNonLabIdentity(identity) {
504
504
  identity.appId === 'nimi.lab',
505
505
  normalizedTitle === 'nimi lab',
506
506
  identity.packageName === '@nimiplatform/lab',
507
- identity.tauriIdentifier === 'ai.nimi.apps.nimi.lab',
507
+ identity.nativeBundleIdentifier === 'ai.nimi.apps.nimi.lab',
508
508
  identity.cargoPackageName === 'nimiapp-lab-shell',
509
509
  identity.appSlug === 'nimi-lab',
510
510
  ];
@@ -566,8 +566,7 @@ function buildAppIdentity(
566
566
  profile,
567
567
  packageName: resolvedPackageName,
568
568
  cargoPackageName: `${cargoSafeNameFromPackageName(resolvedPackageName)}-shell`,
569
- tauriIdentifier: tauriIdentifierFromAppId(appId),
570
- nativeBundleIdentifier: tauriIdentifierFromAppId(appId),
569
+ nativeBundleIdentifier: nativeBundleIdentifierFromAppId(appId),
571
570
  appSlug: appSlugFromAppId(appId),
572
571
  rendererEntryId: `${appSlugFromAppId(appId)}-app`,
573
572
  accentPack: String(accentPack || '').trim() || 'nimi-accent',
@@ -759,7 +758,7 @@ function resolveScaffoldVersionReference(value, versions, dependencyName) {
759
758
 
760
759
  function targetIdentityMap(identity) {
761
760
  return {
762
- tauriIdentifier: identity.tauriIdentifier,
761
+ nativeBundleIdentifier: identity.nativeBundleIdentifier,
763
762
  packageName: identity.packageName,
764
763
  cargoPackageName: identity.cargoPackageName,
765
764
  appId: identity.appId,
@@ -804,7 +803,7 @@ function applyIdentityReplacement(content, manifest, target) {
804
803
 
805
804
  export function assertIdentityNeutralProductSource(relativePath, content, manifest) {
806
805
  const forbidden = [
807
- 'tauriIdentifier',
806
+ 'nativeBundleIdentifier',
808
807
  'packageName',
809
808
  'cargoPackageName',
810
809
  'appId',
@@ -1179,7 +1178,7 @@ export function renderAppIdentityInput(identity) {
1179
1178
  version: identity.version,
1180
1179
  npm_package_name: identity.packageName,
1181
1180
  cargo_package_name: identity.cargoPackageName,
1182
- tauri_identifier: identity.tauriIdentifier,
1181
+ native_bundle_identifier: identity.nativeBundleIdentifier,
1183
1182
  package_author: identity.author || null,
1184
1183
  identity_role: 'scaffold-generated-authoring-input',
1185
1184
  }, { lineWidth: 0 });
@@ -1260,7 +1259,7 @@ export function renderAppSubmissionInput(identity, options = {}) {
1260
1259
  ...(identity.platform === 'web' ? { platform: 'web' } : {}),
1261
1260
  npm_package_name: identity.packageName,
1262
1261
  cargo_package_name: identity.cargoPackageName,
1263
- tauri_identifier: identity.tauriIdentifier,
1262
+ native_bundle_identifier: identity.nativeBundleIdentifier,
1264
1263
  package_author: identity.author || null,
1265
1264
  submission_role: 'developer-submitted-input',
1266
1265
  capability_contract_refs: options.capabilityContractRefs || [],
@@ -1380,7 +1379,6 @@ function buildIdentityMapping(identity, targetDir = '') {
1380
1379
  author: identity.author || null,
1381
1380
  cargoPackageName: identity.cargoPackageName,
1382
1381
  nativeBundleIdentifier: identity.nativeBundleIdentifier,
1383
- tauriIdentifier: identity.tauriIdentifier,
1384
1382
  appSlug: identity.appSlug,
1385
1383
  rendererEntryId: identity.rendererEntryId,
1386
1384
  devPort: identity.devPort,
@@ -1407,7 +1405,7 @@ function buildScaffoldIntent(identity, versions, targetDir = '') {
1407
1405
  packageName: identity.packageName,
1408
1406
  packageAuthor: identity.author || null,
1409
1407
  cargoPackageName: identity.cargoPackageName,
1410
- tauriIdentifier: identity.tauriIdentifier,
1408
+ nativeBundleIdentifier: identity.nativeBundleIdentifier,
1411
1409
  accentPack: identity.accentPack,
1412
1410
  features: identity.features,
1413
1411
  directFeatures: identity.capabilityResolution.directFeatureIds,
@@ -1587,7 +1585,7 @@ function buildScaffoldLock(identity, versions, files, targetDir = '') {
1587
1585
  packageName: identity.packageName,
1588
1586
  packageAuthor: identity.author || null,
1589
1587
  cargoPackageName: identity.cargoPackageName,
1590
- tauriIdentifier: identity.tauriIdentifier,
1588
+ nativeBundleIdentifier: identity.nativeBundleIdentifier,
1591
1589
  accentPack: identity.accentPack,
1592
1590
  appAccessItems: identity.appAccessItems,
1593
1591
  capabilityContractRefs: identity.capabilityResolution.capabilityContractRefs,
@@ -1672,7 +1670,7 @@ function buildAppScaffoldSnapshotWithResolver(
1672
1670
  packageName: identity.packageName,
1673
1671
  packageAuthor: identity.author || null,
1674
1672
  cargoPackageName: identity.cargoPackageName,
1675
- tauriIdentifier: identity.tauriIdentifier,
1673
+ nativeBundleIdentifier: identity.nativeBundleIdentifier,
1676
1674
  features: identity.features,
1677
1675
  files: allFiles,
1678
1676
  createFiles,
@@ -1720,7 +1718,7 @@ export function buildAppScaffoldSnapshotFromIntent({ intent, versions, targetDir
1720
1718
  }, resolveAppScaffoldIntentFeatures);
1721
1719
  const expectedIntent = JSON.parse(snapshot.filesByPath.get(SCAFFOLD_INTENT_PATH).content);
1722
1720
  // @nimi-authority: rule.nimi.platform.app-ecosystem.p-scaf-018c
1723
- const immutableInputs = new Set(['intentVersion', 'scaffoldVersion', 'initRequired', 'initCommand', 'initOrder', 'profile', 'platform', 'carrier', 'appId', 'appTitle', 'version', 'packageName', 'packageAuthor', 'cargoPackageName', 'tauriIdentifier', 'accentPack', 'directFeatures', 'devPort', 'semantics']);
1721
+ const immutableInputs = new Set(['intentVersion', 'scaffoldVersion', 'initRequired', 'initCommand', 'initOrder', 'profile', 'platform', 'carrier', 'appId', 'appTitle', 'version', 'packageName', 'packageAuthor', 'cargoPackageName', 'nativeBundleIdentifier', 'accentPack', 'directFeatures', 'devPort', 'semantics']);
1724
1722
  if (canonicalJson(Object.keys(intent).sort()) !== canonicalJson(Object.keys(expectedIntent).sort())) {
1725
1723
  throw new Error('Scaffold intent fields do not match the current canonical resolved intent');
1726
1724
  }
package/lib/index.mjs CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  validateAppInitialization,
20
20
  } from './app-project-lifecycle.mjs';
21
21
  import { aggregateAppTargetCandidates, packAppTarget } from './app-pack.mjs';
22
+ import { checkStorefront, packStorefront } from './storefront-pack.mjs';
22
23
  import { runDevShell } from '../scripts/dev-shell.mjs';
23
24
  export { runDevShell };
24
25
  import { parse as parseYaml } from 'yaml';
@@ -210,6 +211,7 @@ export function syncApp(cwd, options = {}) {
210
211
  }
211
212
 
212
213
  export function checkApp(cwd, options = {}) {
214
+ if (options.storefront) return checkStorefront(cwd, options);
213
215
  return checkAppProject(cwd, options, appScaffoldVersions(), appToolRunners());
214
216
  }
215
217
 
@@ -222,6 +224,11 @@ export function buildApp(cwd, options = {}) {
222
224
  }
223
225
 
224
226
  export async function packApp(cwd, options = {}) {
227
+ if (options.storefront) {
228
+ if (options.target || options.aggregate) throw new Error('--storefront cannot be combined with a native target or --aggregate');
229
+ return packStorefront(cwd, options);
230
+ }
231
+ if (options.rev !== undefined && options.rev !== '') throw new Error('--rev requires --storefront');
225
232
  const manifest = parseYaml(readFileSync(path.join(path.resolve(cwd, options.dir || '.'), 'nimi.app.yaml'), 'utf8'));
226
233
  if (manifest.platform === 'web') throw new Error('Web pack is not implemented; use the App-owned website build and deployment process.');
227
234
  return options.aggregate
@@ -0,0 +1,327 @@
1
+ // @nimi-authority: rule.nimi.platform.app-ecosystem.p-napp-042e
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { isAppId } from './app-identifiers.mjs';
4
+ import {
5
+ inspectStaticStorefrontImage,
6
+ STOREFRONT_LOCALE_PATTERN,
7
+ STOREFRONT_SHA256_PATTERN,
8
+ } from './storefront-media.mjs';
9
+
10
+ const MiB = 1024 * 1024;
11
+ export const PUBLIC_STOREFRONT_MAX_BYTES = MiB;
12
+ export const PUBLIC_STOREFRONT_ARCHIVE_MAX_BYTES = 32 * MiB;
13
+ const OPAQUE_ARTWORK_ROLES = new Set(['capsule_wide', 'capsule_portrait', 'hero_banner', 'showcase']);
14
+ export const PUBLIC_STOREFRONT_SLOTS = Object.freeze({
15
+ icon: { minW: 512, maxW: 512, minH: 512, maxH: 512, maxBytes: MiB / 2, ratios: [1] },
16
+ capsule_wide: { minW: 1280, maxW: 2560, minH: 720, maxH: 1440, maxBytes: 2 * MiB, ratios: [16 / 9] },
17
+ capsule_portrait: { minW: 600, maxW: 1500, minH: 800, maxH: 2000, maxBytes: 2 * MiB, ratios: [3 / 4] },
18
+ hero_banner: { minW: 1600, maxW: 2560, minH: 680, maxH: 1440, maxBytes: 2 * MiB, ratios: [21 / 9, 16 / 9] },
19
+ logo_mark: { minW: 320, maxW: 1600, minH: 120, maxH: 600, maxBytes: MiB, ratios: [] },
20
+ showcase: { minW: 1280, maxW: 2560, minH: 720, maxH: 1440, maxBytes: 2 * MiB, ratios: [16 / 9] },
21
+ });
22
+
23
+ export function storefrontFields(value, label, required, optional = []) {
24
+ if (!value || typeof value !== 'object' || Array.isArray(value))
25
+ throw new Error(label + ' must be an object');
26
+ for (const key of required)
27
+ if (!Object.hasOwn(value, key)) throw new Error(label + '.' + key + ' is required');
28
+ for (const key of Object.keys(value)) {
29
+ if (!required.includes(key) && !optional.includes(key))
30
+ throw new Error(label + ' contains unsupported field ' + key);
31
+ }
32
+ return value;
33
+ }
34
+ export function storefrontText(value, label, max, document = false) {
35
+ if (
36
+ typeof value !== 'string' ||
37
+ !value.trim() ||
38
+ value.includes('\0') ||
39
+ (!document && (value.trim() !== value || /[\r\n]/u.test(value))) ||
40
+ (document ? Buffer.byteLength(value) : [...value].length) > max
41
+ )
42
+ throw new Error(label + ' is invalid or too long');
43
+ return value;
44
+ }
45
+ export function storefrontLocale(value) {
46
+ if (typeof value !== 'string' || value.length > 16 || !STOREFRONT_LOCALE_PATTERN.test(value))
47
+ throw new Error('Invalid storefront locale: ' + value);
48
+ return value;
49
+ }
50
+ function slug(value, label) {
51
+ if (typeof value !== 'string' || !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(value))
52
+ throw new Error('Invalid ' + label);
53
+ return value;
54
+ }
55
+ function uniqueIds(value, label, min, max) {
56
+ if (
57
+ !Array.isArray(value) ||
58
+ value.length < min ||
59
+ value.length > max ||
60
+ new Set(value).size !== value.length
61
+ )
62
+ throw new Error('Invalid ' + label);
63
+ return value.map((v) => slug(v, label));
64
+ }
65
+ function dimensions(ref, role, label) {
66
+ const spec = PUBLIC_STOREFRONT_SLOTS[role];
67
+ const ratio = ref.width / ref.height;
68
+ if (
69
+ !Number.isInteger(ref.width) ||
70
+ !Number.isInteger(ref.height) ||
71
+ ref.width < spec.minW ||
72
+ ref.width > spec.maxW ||
73
+ ref.height < spec.minH ||
74
+ ref.height > spec.maxH ||
75
+ (role === 'logo_mark'
76
+ ? ratio < 1 || ratio > 5
77
+ : !spec.ratios.some((r) => Math.abs(ratio / r - 1) <= 0.02))
78
+ ) {
79
+ throw new Error(label + ' has unsupported dimensions or aspect ratio');
80
+ }
81
+ }
82
+ function checkedRef(ref, role, label) {
83
+ storefrontFields(ref, label, ['media_type', 'width', 'height', 'size', 'sha256']);
84
+ if (
85
+ !['image/png', 'image/webp'].includes(ref.media_type) ||
86
+ !Number.isSafeInteger(ref.size) ||
87
+ ref.size < 1 ||
88
+ ref.size > PUBLIC_STOREFRONT_SLOTS[role].maxBytes ||
89
+ typeof ref.sha256 !== 'string' ||
90
+ !STOREFRONT_SHA256_PATTERN.test(ref.sha256)
91
+ ) {
92
+ throw new Error('Invalid storefront image reference at ' + label);
93
+ }
94
+ dimensions(ref, role, label);
95
+ return ref;
96
+ }
97
+
98
+ export function inspectPublicStorefrontImage(bytes, role, label, warnings = []) {
99
+ const ref = inspectStaticStorefrontImage(bytes, PUBLIC_STOREFRONT_SLOTS[role], label, (pixels, w, h) => {
100
+ const count = w * h,
101
+ channels = pixels.length / count;
102
+ if (channels !== 3 && channels !== 4) throw new Error(label + ' has an unsupported pixel layout');
103
+ const checkOpaqueWarnings = OPAQUE_ARTWORK_ROLES.has(role);
104
+ const corner = Math.max(1, Math.floor(Math.min(w, h) * 0.04));
105
+ const clearCorners = [0, 0, 0, 0];
106
+ const colors = checkOpaqueWarnings ? new Uint32Array(512) : null;
107
+ let visible = 0,
108
+ edgeWhite = 0,
109
+ brightness = 0,
110
+ squareBrightness = 0;
111
+ for (let y = 0; y < h; y++)
112
+ for (let x = 0; x < w; x++) {
113
+ const i = (y * w + x) * channels;
114
+ const alpha = channels === 4 ? pixels[i + 3] : 255;
115
+ if (!alpha) {
116
+ if ((x < corner || x >= w - corner) && (y < corner || y >= h - corner))
117
+ clearCorners[Number(x >= w - corner) + 2 * Number(y >= h - corner)]++;
118
+ continue;
119
+ }
120
+ visible++;
121
+ if (checkOpaqueWarnings) {
122
+ const r = pixels[i],
123
+ g = pixels[i + 1],
124
+ b = pixels[i + 2];
125
+ if ((x === 0 || y === 0 || x === w - 1 || y === h - 1) && Math.min(r, g, b) >= 245) edgeWhite++;
126
+ const luminance = (54 * r + 183 * g + 19 * b) / 256;
127
+ brightness += luminance;
128
+ squareBrightness += luminance * luminance;
129
+ colors[((r >> 5) << 6) | ((g >> 5) << 3) | (b >> 5)]++;
130
+ }
131
+ }
132
+ if (
133
+ !visible ||
134
+ (role === 'icon' && visible / count < 0.05) ||
135
+ (role === 'logo_mark' &&
136
+ (visible / count < 0.03 || clearCorners.some((n) => n / (corner * corner) < 0.95)))
137
+ ) {
138
+ throw new Error(label + ' does not meet the visible artwork or transparent wordmark requirements');
139
+ }
140
+ if (checkOpaqueWarnings) {
141
+ if (edgeWhite / (2 * (w + h) - 4) >= 0.75) warnings.push({ field: label, reason: 'light-edges' });
142
+ if (squareBrightness / visible - (brightness / visible) ** 2 < 36)
143
+ warnings.push({ field: label, reason: 'low-luminance-variance' });
144
+ if (Math.max(...colors) / visible >= 0.98) warnings.push({ field: label, reason: 'dominant-color' });
145
+ }
146
+ });
147
+ dimensions(ref, role, label);
148
+ return ref;
149
+ }
150
+
151
+ export function readPublicStorefront(doc, readImage = checkedRef) {
152
+ storefrontFields(doc, 'storefront', [
153
+ 'format',
154
+ 'app_id',
155
+ 'revision',
156
+ 'default_locale',
157
+ 'primary_genre',
158
+ 'secondary_genres',
159
+ 'tag_ids',
160
+ 'brand',
161
+ 'locales',
162
+ 'media',
163
+ ]);
164
+ if (
165
+ doc.format !== 'nimi.storefront/v2' ||
166
+ !isAppId(doc.app_id) ||
167
+ !Number.isSafeInteger(doc.revision) ||
168
+ doc.revision <= 0
169
+ )
170
+ throw new Error('Invalid storefront format or identity');
171
+ const primary = slug(doc.primary_genre, 'primary_genre');
172
+ if (uniqueIds(doc.secondary_genres, 'secondary_genres', 0, 2).includes(primary))
173
+ throw new Error('Secondary genres must differ from the primary genre');
174
+ uniqueIds(doc.tag_ids, 'tag_ids', 1, 6);
175
+ storefrontFields(doc.brand, 'brand', ['accent_color', 'surface_tone']);
176
+ if (
177
+ !/^#[0-9a-f]{6}$/iu.test(doc.brand.accent_color) ||
178
+ !['light', 'dark', 'vivid'].includes(doc.brand.surface_tone)
179
+ )
180
+ throw new Error('Invalid storefront brand');
181
+ const defaultLocale = storefrontLocale(doc.default_locale);
182
+ const languages = Object.keys(doc.locales ?? {}).sort();
183
+ if (languages.length > 16 || !['en', 'zh', defaultLocale].every((k) => languages.includes(k)))
184
+ throw new Error('Storefront requires zh, en and its default locale');
185
+ for (const lang of languages) storefrontLocale(lang);
186
+ const localized = (values, label, max) => {
187
+ storefrontFields(values, label, [...new Set(['en', 'zh', defaultLocale])], languages);
188
+ for (const [lang, text] of Object.entries(values)) storefrontText(text, label + '.' + lang, max);
189
+ return values;
190
+ };
191
+ const refs = new Map();
192
+ const refsBySha = new Map();
193
+ function image(value, role, label) {
194
+ const ref = readImage(value, role, label);
195
+ const file = ref.sha256 + (ref.media_type === 'image/png' ? '.png' : '.webp');
196
+ const existing = refsBySha.get(ref.sha256);
197
+ if (existing) {
198
+ if (!isDeepStrictEqual(existing.ref, ref)) {
199
+ throw new Error('Conflicting storefront image metadata for ' + ref.sha256 + ' at ' + label);
200
+ }
201
+ existing.roles.add(role);
202
+ } else {
203
+ const item = { ref, roles: new Set([role]) };
204
+ refs.set(file, item);
205
+ refsBySha.set(ref.sha256, item);
206
+ }
207
+ return ref;
208
+ }
209
+ function slot(value, role, label) {
210
+ const poster = role === 'showcase';
211
+ const extra = poster ? ['id', 'kind', 'target_carrier', 'is_fictional_sample', 'title', 'caption'] : [];
212
+ storefrontFields(
213
+ value,
214
+ label,
215
+ ['alt', 'default', ...extra],
216
+ role === 'hero_banner' ? ['locales', 'focal_point'] : ['locales'],
217
+ );
218
+ localized(value.alt, label + '.alt', 200);
219
+ const out = { ...value, default: image(value.default, role, label + '.default') };
220
+ if (value.locales !== undefined) {
221
+ storefrontFields(
222
+ value.locales,
223
+ label + '.locales',
224
+ [],
225
+ languages.filter((k) => k !== defaultLocale),
226
+ );
227
+ out.locales = Object.fromEntries(
228
+ Object.keys(value.locales)
229
+ .sort()
230
+ .map((lang) => [lang, image(value.locales[lang], role, label + '.' + lang)]),
231
+ );
232
+ }
233
+ if (value.focal_point !== undefined) {
234
+ storefrontFields(value.focal_point, label + '.focal_point', ['x', 'y']);
235
+ if (Object.values(value.focal_point).some((x) => !Number.isFinite(x) || x < 0 || x > 1))
236
+ throw new Error(label + ' has an invalid focal point');
237
+ }
238
+ if (poster) {
239
+ slug(value.id, 'poster id');
240
+ if (
241
+ value.kind !== 'poster' ||
242
+ typeof value.is_fictional_sample !== 'boolean' ||
243
+ !['all', 'desktop', 'hosted-web', 'bundled'].includes(value.target_carrier)
244
+ )
245
+ throw new Error('Invalid experience poster at ' + label);
246
+ localized(value.title, label + '.title', 80);
247
+ localized(value.caption, label + '.caption', 280);
248
+ }
249
+ return out;
250
+ }
251
+ storefrontFields(
252
+ doc.media,
253
+ 'media',
254
+ ['icon', 'capsule_wide', 'hero_banner', 'showcase'],
255
+ ['capsule_portrait', 'logo_mark'],
256
+ );
257
+ if (!Array.isArray(doc.media.showcase) || doc.media.showcase.length < 2 || doc.media.showcase.length > 6)
258
+ throw new Error('Storefront needs 2–6 experience posters');
259
+ const media = {};
260
+ for (const role of Object.keys(PUBLIC_STOREFRONT_SLOTS)) {
261
+ if (role === 'showcase')
262
+ media.showcase = doc.media.showcase.map((s, i) => slot(s, role, 'showcase[' + i + ']'));
263
+ else if (doc.media[role] !== undefined) media[role] = slot(doc.media[role], role, role);
264
+ }
265
+ const posterIds = new Set(media.showcase.map((x) => x.id));
266
+ if (posterIds.size !== media.showcase.length) throw new Error('Duplicate storefront poster ID');
267
+ for (const lang of languages) {
268
+ const entry = doc.locales[lang],
269
+ label = 'locales.' + lang;
270
+ storefrontFields(entry, label, [
271
+ 'display_name',
272
+ 'tagline',
273
+ 'summary',
274
+ 'introduction_markdown',
275
+ 'highlights',
276
+ ]);
277
+ if (typeof entry.display_name === 'string' && [...entry.display_name].length > 80) {
278
+ throw new Error(
279
+ label +
280
+ '.display_name exceeds the 80-character public storefront limit (offline app-info allows up to 120 characters)',
281
+ );
282
+ }
283
+ storefrontText(entry.display_name, label + '.display_name', 80);
284
+ storefrontText(entry.tagline, label + '.tagline', 90);
285
+ storefrontText(entry.summary, label + '.summary', 280);
286
+ storefrontText(entry.introduction_markdown, label + '.introduction_markdown', 96 * 1024, true);
287
+ if (!Array.isArray(entry.highlights) || entry.highlights.length < 1 || entry.highlights.length > 4)
288
+ throw new Error(label + ' needs 1–4 highlights');
289
+ const ids = new Set();
290
+ for (const item of entry.highlights) {
291
+ storefrontFields(item, label + '.highlights', ['id', 'title', 'description'], ['showcase_id']);
292
+ slug(item.id, 'highlight id');
293
+ if (ids.has(item.id) || (item.showcase_id !== undefined && !posterIds.has(item.showcase_id)))
294
+ throw new Error('Invalid highlight or poster link at ' + label);
295
+ ids.add(item.id);
296
+ storefrontText(item.title, label + '.highlight.title', 60);
297
+ storefrontText(item.description, label + '.highlight.description', 200);
298
+ }
299
+ }
300
+ const manifest = { ...doc, media };
301
+ if (Buffer.byteLength(JSON.stringify(manifest)) > PUBLIC_STOREFRONT_MAX_BYTES)
302
+ throw new Error('Storefront manifest exceeds 1 MiB');
303
+ return { manifest, refs };
304
+ }
305
+
306
+ export function storefrontSummarySnapshot(manifest) {
307
+ const locales = Object.fromEntries(
308
+ Object.entries(manifest.locales).map(([lang, entry]) => [
309
+ lang,
310
+ {
311
+ display_name: entry.display_name,
312
+ tagline: entry.tagline,
313
+ summary: entry.summary,
314
+ highlights_count: entry.highlights.length,
315
+ },
316
+ ]),
317
+ );
318
+ return {
319
+ default_locale: manifest.default_locale,
320
+ primary_genre: manifest.primary_genre,
321
+ secondary_genres: manifest.secondary_genres,
322
+ tag_ids: manifest.tag_ids,
323
+ brand: manifest.brand,
324
+ locales,
325
+ media_slots: manifest.media,
326
+ };
327
+ }
@@ -35,9 +35,10 @@ export function storefrontMediaExtension(mediaType) {
35
35
  throw new Error(`Unsupported storefront image media type: ${mediaType}`);
36
36
  }
37
37
 
38
- export function inspectStaticStorefrontImage(bytes, bounds, label = 'storefront image') {
39
- if (!Buffer.isBuffer(bytes) || bytes.length === 0 || bytes.length > STOREFRONT_IMAGE_MAX_BYTES) {
40
- throw new Error(`${label} must be a nonempty static WebP or PNG of at most ${STOREFRONT_IMAGE_MAX_BYTES} bytes`);
38
+ export function inspectStaticStorefrontImage(bytes, bounds, label = 'storefront image', inspectPixels) {
39
+ const maxBytes = bounds.maxBytes ?? STOREFRONT_IMAGE_MAX_BYTES;
40
+ if (!Buffer.isBuffer(bytes) || bytes.length === 0 || bytes.length > maxBytes) {
41
+ throw new Error(`${label} must be a nonempty static WebP or PNG of at most ${maxBytes} bytes`);
41
42
  }
42
43
  const sha256 = createHash('sha256').update(bytes).digest('hex');
43
44
 
@@ -67,6 +68,7 @@ export function inspectStaticStorefrontImage(bytes, bounds, label = 'storefront
67
68
  assertImageBounds(width, height, bounds, label);
68
69
  const decoded = PNG.sync.read(bytes, { checkCRC: true });
69
70
  if (decoded.width !== width || decoded.height !== height) throw new Error(`${label} PNG dimensions are inconsistent`);
71
+ inspectPixels?.(decoded.data, width, height);
70
72
  return { media_type: 'image/png', width, height, size: bytes.length, sha256 };
71
73
  }
72
74
 
@@ -107,14 +109,16 @@ export function inspectStaticStorefrontImage(bytes, bounds, label = 'storefront
107
109
  if (!hasBitstream || width <= 0 || height <= 0) throw new Error(`${label} WebP is missing image bitstream or dimensions`);
108
110
  assertImageBounds(width, height, bounds, label);
109
111
  const { Transformer } = require('@napi-rs/image');
112
+ let pixels;
110
113
  try {
111
114
  const image = new Transformer(bytes);
112
- const pixels = image.rawPixelsSync();
115
+ pixels = image.rawPixelsSync();
113
116
  const decoded = image.metadataSync();
114
117
  if (decoded.width !== width || decoded.height !== height || !pixels.length) throw new Error('invalid decoded image');
115
118
  } catch (cause) {
116
119
  throw new Error(`${label} WebP pixels could not be decoded`, { cause });
117
120
  }
121
+ inspectPixels?.(pixels, width, height);
118
122
  return { media_type: 'image/webp', width, height, size: bytes.length, sha256 };
119
123
  }
120
124