@threenative/runtime-native 0.3.3 → 0.3.5

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 (39) hide show
  1. package/NOTICE +1 -1
  2. package/android/README.md +10 -0
  3. package/android/app/build.gradle.kts +23 -0
  4. package/android/app/src/main/java/com/mystral/engine/MystralActivity.java +87 -2
  5. package/android/app/src/main/java/com/mystral/engine/TnUiOverlay.java +170 -8
  6. package/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  7. package/build/web/tn-native-engine-web.mjs +2 -0
  8. package/build/web/tn-native-engine-web.wasm +0 -0
  9. package/package.json +20 -6
  10. package/scripts/asset-manifest.mjs +38 -19
  11. package/scripts/bundle-native-engine.mjs +303 -0
  12. package/scripts/bundle.mjs +38 -41
  13. package/scripts/check-source-list.mjs +11 -5
  14. package/scripts/desktop-distribution.mjs +19 -5
  15. package/scripts/inspect-macos-icon.mjs +169 -0
  16. package/scripts/install-prebuilt.mjs +33 -21
  17. package/scripts/package-android.mjs +64 -6
  18. package/scripts/package-desktop.mjs +51 -14
  19. package/scripts/package-engine-desktop.mjs +102 -0
  20. package/scripts/package-ios.mjs +36 -32
  21. package/scripts/physical-device-evidence.mjs +135 -1
  22. package/scripts/production-evidence.mjs +36 -9
  23. package/scripts/profile-production.mjs +696 -146
  24. package/scripts/qualify-physical-mobile.mjs +286 -69
  25. package/scripts/verify-starter-consumer.mjs +58 -8
  26. package/scripts/verify-starter-desktop-base.mjs +12 -2
  27. package/scripts/windows-installer.mjs +12 -5
  28. package/scripts/xvfb.sh +15 -0
  29. package/src/engine/player/core-addons.mjs +15 -0
  30. package/src/engine/player/core-assets.mjs +59 -0
  31. package/src/engine/player/core-audio.mjs +11 -0
  32. package/src/engine/player/core-hdr.mjs +29 -0
  33. package/src/engine/player/core-host.mjs +148 -0
  34. package/src/engine/player/core-lut.mjs +7 -0
  35. package/src/engine/player/core-textures.mjs +167 -0
  36. package/src/engine/player/core-three.mjs +294 -0
  37. package/src/engine/player/core-tsl.mjs +80 -0
  38. package/src/engine/player/core-unused.mjs +21 -0
  39. package/src/engine/player/core-webgpu.mjs +207 -0
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env node
2
+ // Desktop package for a game with `engine: "threenative"`: the V8 engine player, the game bundled on the
3
+ // engine's own three, its cooked assets and its built UI, in one directory with a launcher. The
4
+ // player reads `native/assets.tnpk` and `ui/index.html` beside the bundle, so the layout is the contract.
5
+ import { createHash } from "node:crypto";
6
+ import { readFileSync, readdirSync, chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
7
+ import { basename, join, resolve } from "node:path";
8
+ import { pathToFileURL } from "node:url";
9
+ import { bundleNativeEngine, cookNativeEngineAssets } from "./bundle-native-engine.mjs";
10
+
11
+ const PLAYER = "tn-native-engine-player-v8";
12
+
13
+ /** The launcher: the window opens with the game's title and size, and every argument reaches the player. */
14
+ export function launcher(width, height, title) {
15
+ return [
16
+ "#!/bin/sh",
17
+ 'DIR=$(cd "$(dirname "$0")" && pwd)',
18
+ ...(title ? [`TN_PLAYER_TITLE=\${TN_PLAYER_TITLE:-'${title.replaceAll("'", "'\\''")}'}`, "export TN_PLAYER_TITLE"] : []),
19
+ `: "\${TN_PLAYER_WIDTH:=${width}}"`,
20
+ `: "\${TN_PLAYER_HEIGHT:=${height}}"`,
21
+ "export TN_PLAYER_WIDTH TN_PLAYER_HEIGHT",
22
+ `exec "$DIR/${PLAYER}" "$DIR/game.js" "$@"`,
23
+ "",
24
+ ].join("\n");
25
+ }
26
+
27
+ /**
28
+ * Writes `output` as a directory: `<name>` (launcher), the player, `game.js`, `native/assets.tnpk`
29
+ * and, for a web UI, `ui/`. `bundle` and `cook` are the engine bundler's, injectable for the unit test.
30
+ */
31
+ export async function packageEngineDesktop(
32
+ { project, entry, player, ui, output, buildReceipt, width = 1280, height = 720, title },
33
+ { bundle = bundleNativeEngine, cook = cookNativeEngineAssets } = {},
34
+ ) {
35
+ if (!player || !existsSync(player)) {
36
+ throw new Error(
37
+ `TN_ENGINE_PLAYER_MISSING: engine "threenative" on desktop needs the engine player (${PLAYER}) at ${player ?? "(not set)"}.Build it (cmake --preset tn-linux -B build/tn-engine-ui -DTN_ENGINE_ONLY=ON -DTN_ENGINE_PLAYER=ON -DTN_ENGINE_PLAYER_UI_OVERLAY=ON) and set THREENATIVE_ENGINE_PLAYER, or set engine: "threejs" in threenative.config.ts to package with the legacy host.`,
38
+ );
39
+ }
40
+ rmSync(output, { force: true, recursive: true });
41
+ mkdirSync(output, { recursive: true });
42
+ const outfile = join(output, "game.js");
43
+ const bundled = await bundle({ entry, outfile });
44
+ await cook({ project, outfile });
45
+ copyFileSync(player, join(output, PLAYER));
46
+ chmodSync(join(output, PLAYER), 0o755);
47
+ if (ui) {
48
+ if (!existsSync(join(ui, "index.html")))
49
+ throw new Error(`TN_UI_BUNDLE_MISSING: ${ui} has no index.html, which is the page the overlay loads.`);
50
+ cpSync(ui, join(output, "ui"), { recursive: true });
51
+ }
52
+ const start = join(output, basename(output));
53
+ writeFileSync(start, launcher(width, height, title));
54
+ chmodSync(start, 0o755);
55
+ if (buildReceipt) {
56
+ const receipt = JSON.parse(readFileSync(buildReceipt, "utf8"));
57
+ if (receipt.buildProtocol !== "midway-clean-build-v1" || !/^[a-f0-9]{40}$/.test(bundled?.engineCommit)
58
+ || receipt.engineCommit !== bundled.engineCommit
59
+ || receipt.playerSha256 !== createHash("sha256").update(readFileSync(join(output, PLAYER))).digest("hex"))
60
+ throw new Error("TN_ENGINE_PROVENANCE_INVALID: rebuild packages/player from a clean matching engine checkout");
61
+ const artifacts = {};
62
+ const visit = (dir, prefix = "") => {
63
+ for (const item of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : 1)) {
64
+ const relative = prefix + item.name;
65
+ if (item.isDirectory()) visit(join(dir, item.name), `${relative}/`);
66
+ else if (item.isFile()) artifacts[relative] = createHash("sha256").update(readFileSync(join(dir, item.name))).digest("hex");
67
+ else throw new Error(`TN_ENGINE_PROVENANCE_SYMLINK: ${relative}`);
68
+ }
69
+ };
70
+ visit(output);
71
+ const directorySha256 = createHash("sha256").update(Object.entries(artifacts).map(([file, digest]) => `${file} ${digest}`).join("\n")).digest("hex");
72
+ writeFileSync(join(output, "midway-provenance.json"), JSON.stringify({ buildProtocol: receipt.buildProtocol, engineCommit: bundled.engineCommit, artifacts, directorySha256 }));
73
+ }
74
+ console.log(`ThreeNative desktop artifact: ${output}`);
75
+ return output;
76
+ }
77
+
78
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
79
+ const args = process.argv.slice(2);
80
+ const flags = new Map();
81
+ for (let i = 0; i < args.length; i += 2) {
82
+ if (!["--project", "--entry", "--player", "--ui", "--output", "--build-receipt", "--width", "--height", "--title"].includes(args[i]) || !args[i + 1] || flags.has(args[i]))
83
+ throw new Error(`TN_ENGINE_PACKAGE_ARGS: invalid or repeated option ${args[i]}`);
84
+ flags.set(args[i], args[i + 1]);
85
+ }
86
+ try {
87
+ await packageEngineDesktop({
88
+ project: flags.get("--project"),
89
+ entry: flags.get("--entry"),
90
+ player: flags.get("--player"),
91
+ ui: flags.get("--ui"),
92
+ output: flags.get("--output"),
93
+ buildReceipt: flags.get("--build-receipt"),
94
+ width: flags.has("--width") ? Number(flags.get("--width")) : undefined,
95
+ height: flags.has("--height") ? Number(flags.get("--height")) : undefined,
96
+ title: flags.get("--title"),
97
+ });
98
+ } catch (error) {
99
+ console.error(error instanceof Error ? error.message : String(error));
100
+ process.exitCode = 1;
101
+ }
102
+ }
@@ -14,11 +14,13 @@ import {
14
14
  writeFileSync,
15
15
  } from 'node:fs';
16
16
  import { tmpdir } from 'node:os';
17
- import { basename, dirname, join, posix, resolve } from 'node:path';
17
+ import { basename, dirname, join, resolve } from 'node:path';
18
18
  import { fileURLToPath } from 'node:url';
19
19
  import { createRequire } from 'node:module';
20
20
  import { spawnSync } from 'node:child_process';
21
21
  import { assertNativeAssetsDecodable, deriveIosWebpSupport } from './asset-preflight.mjs';
22
+ import { listFiles, selectManifestAssets } from './asset-manifest.mjs';
23
+ import { mobileUiRenderer } from './package-android.mjs';
22
24
  import { downloadReleaseArtifact } from './install-prebuilt.mjs';
23
25
 
24
26
  export const NATIVE_ORIENTATIONS = ['landscape', 'portrait', 'sensor'];
@@ -210,17 +212,6 @@ function checksum(path) {
210
212
  return createHash('sha256').update(readFileSync(path)).digest('hex');
211
213
  }
212
214
 
213
- function listFiles(directory, relative = '') {
214
- const files = [];
215
- for (const entry of readdirSync(join(directory, relative), { withFileTypes: true })) {
216
- const path = relative ? posix.join(relative, entry.name) : entry.name;
217
- if (entry.isDirectory()) files.push(...listFiles(directory, path));
218
- else if (entry.isFile()) files.push(path);
219
- else throw new Error(`Unsupported iOS asset entry: ${join(directory, path)}`);
220
- }
221
- return files.sort();
222
- }
223
-
224
215
  function findApp(directory) {
225
216
  const entries = readdirSync(directory, { withFileTypes: true });
226
217
  for (const entry of entries) {
@@ -455,6 +446,33 @@ export function stageIosUi(ui, renderer, destination) {
455
446
  return listFiles(destination);
456
447
  }
457
448
 
449
+ /**
450
+ * Stage the game's compiled assets into the `.app`'s `game` directory.
451
+ *
452
+ * The same selector the other two packagers use, so one cook output left over from a previous
453
+ * bake is dropped here too instead of shipping inside the bundle. iOS ran no preflight at all.
454
+ * Its capability set is not Android's: `CMakeLists.txt` excludes IOS from every libwebp branch,
455
+ * so a WebP texture that packages for Android must still be refused here, while the audio answer
456
+ * is the same on every native target.
457
+ */
458
+ export function stageIosAssets(assets, destination) {
459
+ if (!assets || !existsSync(assets)) return [];
460
+ if (!statSync(assets).isDirectory()) {
461
+ throw new Error(`iOS assets path is not a directory: ${assets}`);
462
+ }
463
+ assertNativeAssetsDecodable(assets, {
464
+ target: 'ios',
465
+ capabilities: { webp: deriveIosWebpSupport() },
466
+ });
467
+ const { selected } = selectManifestAssets(assets);
468
+ for (const file of selected) {
469
+ const staged = join(destination, file);
470
+ mkdirSync(dirname(staged), { recursive: true });
471
+ cpSync(join(assets, file), staged);
472
+ }
473
+ return selected;
474
+ }
475
+
458
476
  export function stageIosSimulatorApp({
459
477
  assets,
460
478
  bundle,
@@ -496,7 +514,11 @@ export function stageIosSimulatorApp({
496
514
  const game = join(output, 'game');
497
515
  rmSync(game, { force: true, recursive: true });
498
516
  mkdirSync(game, { recursive: true });
499
- stageIosUi(ui, declared.ui?.renderer === 'web' ? 'web' : 'native', join(output, 'ui'));
517
+ // The CSS UI has an Android build and no iOS one yet: refused by name, not flattened to native.
518
+ if (declared.ui?.renderer === 'native-css') {
519
+ throw new Error('TN_UI_RENDERER_UNSUPPORTED: ui.renderer "native-css" has no iOS build');
520
+ }
521
+ stageIosUi(ui, mobileUiRenderer(declared.ui?.renderer), join(output, 'ui'));
500
522
  const plist = join(output, 'Info.plist');
501
523
  const infoPlist = readIosInfoPlist(plist, convertInfoPlist);
502
524
  writeFileSync(plist, renderIosInfoPlist(infoPlist.source, declared));
@@ -520,25 +542,7 @@ export function stageIosSimulatorApp({
520
542
  }
521
543
  copyFileSync(declared.bootSplash.image, join(output, 'LaunchImage.png'));
522
544
  }
523
- let assetFiles = [];
524
- if (assets && existsSync(assets)) {
525
- if (!statSync(assets).isDirectory()) {
526
- throw new Error(`iOS assets path is not a directory: ${assets}`);
527
- }
528
- // iOS ran no preflight at all. Its capability set is not Android's: `CMakeLists.txt` excludes
529
- // IOS from every libwebp branch, so a WebP texture that packages for Android must still be
530
- // refused here, while the audio answer is the same on every native target.
531
- assertNativeAssetsDecodable(assets, {
532
- target: 'ios',
533
- capabilities: { webp: deriveIosWebpSupport() },
534
- });
535
- assetFiles = listFiles(assets);
536
- for (const file of assetFiles) {
537
- const staged = join(game, file);
538
- mkdirSync(dirname(staged), { recursive: true });
539
- cpSync(join(assets, file), staged);
540
- }
541
- }
545
+ const assetFiles = stageIosAssets(assets, game);
542
546
  const report = {
543
547
  assets: assetFiles.map((path) => ({ path, sha256: checksum(join(game, path)) })),
544
548
  bundleSha256: checksum(bundle),
@@ -5,6 +5,8 @@ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
5
5
  import { join, relative, sep } from "node:path";
6
6
 
7
7
  export const PHYSICAL_EVIDENCE_SCHEMA = "physicalDeviceEvidenceV1";
8
+ /** v2 keeps every v1 block and re-reads only the lifecycle and the unmeasured timings. */
9
+ export const PHYSICAL_EVIDENCE_V2_SCHEMA = "physicalDeviceEvidenceV2";
8
10
  export const REQUIRED_PREREQUISITES = ["prd053", "prd054", "prd046", "prd048"];
9
11
  export const REQUIRED_GATE_IDS = [
10
12
  "evidence-schema",
@@ -21,6 +23,13 @@ export const REQUIRED_GATE_IDS = [
21
23
  "repository-collection",
22
24
  ];
23
25
 
26
+ /** The operations a v2 lifecycle certifies, in the order the device reads them; any later phase is a resume. */
27
+ const LIFECYCLE_OPERATIONS = ["background", "foreground", "rotate"];
28
+ /** v2 lifecycle times are offsets from the run's own clock. A wall-clock reading is a time no read produced. */
29
+ const RUN_RELATIVE_CLOCK = "run-relative-ms";
30
+ /** Timings the collector never measured, recorded as unmeasured rather than filled from the run's start. */
31
+ const UNMEASURED_TIMINGS = ["readyAt", "firstFrameAt", "frame300At"];
32
+
24
33
  const ROOT_KEYS = new Set([
25
34
  "schemaVersion",
26
35
  "identity",
@@ -287,6 +296,99 @@ function validateLifecycle(value, errors, execution) {
287
296
  if (value.stateContinuity !== true) add(errors, `${path}.stateContinuity`, "must be true for a physical resume report");
288
297
  }
289
298
 
299
+ /**
300
+ * The v2 execution block: the facts the run measured, with the three timings it did not.
301
+ *
302
+ * `sessionNonce` is gone because a device observation carries no nonce — the session claim is the
303
+ * one process every reading and this block share. The unmeasured timings are `null` rather than
304
+ * absent, so a reader can tell "not measured" from "not written about", and a string in any of
305
+ * them is refused: a value copied from the run's own start would read as a measurement.
306
+ */
307
+ function validateExecutionV2(value, errors) {
308
+ const path = "execution";
309
+ if (!objectAt(value, path, errors, new Set(["installStartedAt", "launchStartedAt", ...UNMEASURED_TIMINGS, "pid", "frames", "nonBlankCaptureSha256", "gpuErrorCount", "arm64", "nativeGpu", "processLiveness", "assertionCount"]))) return;
310
+ timestampAt(value.installStartedAt, `${path}.installStartedAt`, errors);
311
+ timestampAt(value.launchStartedAt, `${path}.launchStartedAt`, errors);
312
+ for (const key of UNMEASURED_TIMINGS) {
313
+ if (value[key] !== null) add(errors, `${path}.${key}`, "must be null: this run never measured it, and a time taken from the run's start would be a reading no device produced");
314
+ }
315
+ finiteNumberAt(value.pid, `${path}.pid`, errors, { integer: true, minimum: 1 });
316
+ finiteNumberAt(value.frames, `${path}.frames`, errors, { integer: true, minimum: 300 });
317
+ hashAt(value.nonBlankCaptureSha256, `${path}.nonBlankCaptureSha256`, errors);
318
+ finiteNumberAt(value.gpuErrorCount, `${path}.gpuErrorCount`, errors, { integer: true, minimum: 0 });
319
+ if (value.gpuErrorCount !== 0) add(errors, `${path}.gpuErrorCount`, "must equal zero");
320
+ if (value.arm64 !== true) add(errors, `${path}.arm64`, "must be true");
321
+ if (value.nativeGpu !== true) add(errors, `${path}.nativeGpu`, "must be true; software GPU is not physical evidence");
322
+ booleanAt(value.processLiveness, `${path}.processLiveness`, errors);
323
+ finiteNumberAt(value.assertionCount, `${path}.assertionCount`, errors, { integer: true, minimum: 1 });
324
+ if (value.processLiveness !== true) add(errors, `${path}.processLiveness`, "must be true for a passing physical report");
325
+ }
326
+
327
+ /**
328
+ * The v2 lifecycle block: one row per device-read operation, the readings it carried, and three
329
+ * step counts bracketing the away period.
330
+ *
331
+ * Nothing here is attributed to a phase that did not produce it — no wall-clock `at`, no session
332
+ * nonce, no per-phase step count, no fourth phase. Every claim v1 asserted as a standalone boolean
333
+ * is instead re-derived from these numbers below, and refused when the readings deny it.
334
+ */
335
+ function validateLifecycleV2(value, errors, execution) {
336
+ const path = "lifecycle";
337
+ if (!objectAt(value, path, errors, new Set(["clock", "operations", "framesPaused", "framesAdvanced", "physics"]))) return;
338
+ if (value.clock !== RUN_RELATIVE_CLOCK) add(errors, `${path}.clock`, `must be ${RUN_RELATIVE_CLOCK}; the runner reads offsets from the run's own clock, and a wall-clock time here would be one no read produced`);
339
+ if (!Array.isArray(value.operations)) add(errors, `${path}.operations`, "must be an array");
340
+ else if (value.operations.length < LIFECYCLE_OPERATIONS.length) add(errors, `${path}.operations`, `must carry at least ${LIFECYCLE_OPERATIONS.length} device-read operations`);
341
+ else {
342
+ let previous;
343
+ for (const [index, operation] of value.operations.entries()) {
344
+ const opPath = `${path}.operations[${index}]`;
345
+ if (!objectAt(operation, opPath, errors, new Set(["operation", "offsetMs", "frames", "focused", "framesPaused", "pid", "windowRotation", "requestedRotation"]))) continue;
346
+ const expected = LIFECYCLE_OPERATIONS[index] ?? "foreground";
347
+ if (operation.operation !== expected) add(errors, `${opPath}.operation`, `must be the ${expected} operation this claim rests on`);
348
+ if (operation.focused !== (operation.operation !== "background")) add(errors, `${opPath}.focused`, `must be ${String(operation.operation !== "background")}; the device reports unfocused only while the app is away`);
349
+ if (index === 0 && operation.framesPaused !== true) add(errors, `${opPath}.framesPaused`, "must be true; the backgrounded reading itself has to show the frame counter stopping");
350
+ finiteNumberAt(operation.offsetMs, `${opPath}.offsetMs`, errors, { minimum: 0 });
351
+ finiteNumberAt(operation.frames, `${opPath}.frames`, errors, { integer: true, minimum: 0 });
352
+ finiteNumberAt(operation.pid, `${opPath}.pid`, errors, { integer: true, minimum: 1 });
353
+ if (operation.pid !== execution?.pid) add(errors, `${opPath}.pid`, "must be the one process the rest of the evidence recorded");
354
+ if (Number.isFinite(operation.offsetMs) && Number.isFinite(previous?.offsetMs) && operation.offsetMs <= previous.offsetMs) add(errors, `${opPath}.offsetMs`, `is ${String(operation.offsetMs)}, not after the previous operation's ${String(previous.offsetMs)}`);
355
+ if (Number.isInteger(operation.frames) && Number.isInteger(previous?.frames) && operation.frames < previous.frames) add(errors, `${opPath}.frames`, `is ${String(operation.frames)}, below the previous operation's ${String(previous.frames)}; a device frame count does not run backwards`);
356
+ if (expected === "rotate") {
357
+ if (operation.windowRotation !== operation.requestedRotation) add(errors, `${opPath}.windowRotation`, `is ${String(operation.windowRotation)}, not the requested rotation ${String(operation.requestedRotation)}; the device has to have turned, not merely been asked to`);
358
+ if (operation.windowRotation === previous?.windowRotation) add(errors, `${opPath}.windowRotation`, `is still ${String(operation.windowRotation)}, so the device never turned`);
359
+ }
360
+ previous = operation;
361
+ }
362
+ }
363
+ const [away, resumed] = [value.operations?.[0], value.operations?.at(-1)];
364
+ booleanAt(value.framesPaused, `${path}.framesPaused`, errors);
365
+ booleanAt(value.framesAdvanced, `${path}.framesAdvanced`, errors);
366
+ if (value.framesPaused !== true) add(errors, `${path}.framesPaused`, "must be true for a passing physical report");
367
+ if (value.framesAdvanced !== true) add(errors, `${path}.framesAdvanced`, "must be true for a passing physical report");
368
+ if (isRecord(away) && Number.isInteger(away.frames) && Number.isInteger(resumed?.frames)) {
369
+ if (value.framesPaused !== away.framesPaused) add(errors, `${path}.framesPaused`, `is ${String(value.framesPaused)}, but the backgrounded reading recorded ${String(away.framesPaused)}`);
370
+ if (value.framesAdvanced !== (resumed.frames > away.frames)) add(errors, `${path}.framesAdvanced`, `is ${String(value.framesAdvanced)}, but the readings' own frame counts ${resumed.frames > away.frames ? "advance" : "do not advance"} past the backgrounded one`);
371
+ }
372
+ validateLifecycleStepsV2(value.physics, errors);
373
+ }
374
+
375
+ /** Three step counts around the away period: a claim the counts have to agree with, not replace. */
376
+ function validateLifecycleStepsV2(value, errors) {
377
+ const path = "lifecycle.physics";
378
+ if (!objectAt(value, path, errors, new Set(["steps", "stepsPaused", "stepsAdvanced"]))) return;
379
+ const stepsPath = `${path}.steps`;
380
+ if (!objectAt(value.steps, stepsPath, errors, new Set(["beforeBackground", "afterForeground", "afterAdvance"]))) return;
381
+ for (const key of ["beforeBackground", "afterForeground", "afterAdvance"]) finiteNumberAt(value.steps[key], `${stepsPath}.${key}`, errors, { integer: true, minimum: 0 });
382
+ booleanAt(value.stepsPaused, `${path}.stepsPaused`, errors);
383
+ booleanAt(value.stepsAdvanced, `${path}.stepsAdvanced`, errors);
384
+ if (value.stepsPaused !== true) add(errors, `${path}.stepsPaused`, "must be true for a passing physical report");
385
+ if (value.stepsAdvanced !== true) add(errors, `${path}.stepsAdvanced`, "must be true for a passing physical report");
386
+ const { beforeBackground, afterForeground, afterAdvance } = value.steps;
387
+ if (![beforeBackground, afterForeground, afterAdvance].every((step) => Number.isInteger(step) && step >= 0)) return;
388
+ if (afterForeground !== beforeBackground) add(errors, stepsPath, `the simulation stepped from ${String(beforeBackground)} to ${String(afterForeground)} while the app was away`);
389
+ if (afterAdvance <= afterForeground) add(errors, stepsPath, `the simulation did not advance after the return (${String(afterForeground)} to ${String(afterAdvance)})`);
390
+ }
391
+
290
392
  function validateMultitouch(value, errors, path) {
291
393
  if (!objectAt(value, path, errors, new Set(["status", "reportPath", "reportSha256", "candidateSha", "deviceClass", "maxPointers", "simultaneousMovementAndJump", "onePointerControl"]))) return;
292
394
  enumAt(value.status, `${path}.status`, errors, ["pass"]);
@@ -403,7 +505,7 @@ function validateConsumption(value, errors, candidateSha) {
403
505
  for (const key of ["multitouch", "physics"]) if (value[key]?.candidateSha !== candidateSha) add(errors, `${path}.${key}.candidateSha`, `must match candidate SHA ${candidateSha ?? "from source"}`);
404
506
  }
405
507
 
406
- export function validatePhysicalDeviceEvidence(evidence, options = {}) {
508
+ export function validatePhysicalDeviceEvidenceV1(evidence, options = {}) {
407
509
  const errors = [];
408
510
  if (!objectAt(evidence, "evidence", errors, ROOT_KEYS)) return { valid: false, errors };
409
511
  if (evidence.schemaVersion !== 1) add(errors, "schemaVersion", "must equal 1");
@@ -423,6 +525,32 @@ export function validatePhysicalDeviceEvidence(evidence, options = {}) {
423
525
  return { valid: errors.length === 0, errors: [...new Set(errors)] };
424
526
  }
425
527
 
528
+ export function validatePhysicalDeviceEvidenceV2(evidence, options = {}) {
529
+ const errors = [];
530
+ if (!objectAt(evidence, "evidence", errors, ROOT_KEYS)) return { valid: false, errors };
531
+ if (evidence.schemaVersion !== 2) add(errors, "schemaVersion", "must equal 2");
532
+ validateIdentity(evidence.identity, errors);
533
+ validateSource(evidence.source, errors, options);
534
+ validateDevice(evidence.device, errors, options);
535
+ validateSigning(evidence.signing, errors);
536
+ const candidateSha = options.candidateSha ?? evidence.source?.headSha;
537
+ validatePrerequisites(evidence.prerequisites, errors, { candidateSha });
538
+ validateExecutionV2(evidence.execution, errors);
539
+ validateLifecycleV2(evidence.lifecycle, errors, evidence.execution);
540
+ validateConsumption(evidence.consumption, errors, candidateSha);
541
+ validateTelemetry(evidence.telemetry, errors);
542
+ validateArtifacts(evidence.artifacts, errors);
543
+ validateGateEvidence(evidence.gateEvidence, errors);
544
+ if (evidence.identity?.verdict === "pass" && evidence.identity?.blockers?.length > 0) add(errors, "identity.blockers", "a pass report cannot contain blockers");
545
+ return { valid: errors.length === 0, errors: [...new Set(errors)] };
546
+ }
547
+
548
+ export function validatePhysicalDeviceEvidence(evidence, options = {}) {
549
+ return evidence?.schemaVersion === 2
550
+ ? validatePhysicalDeviceEvidenceV2(evidence, options)
551
+ : validatePhysicalDeviceEvidenceV1(evidence, options);
552
+ }
553
+
426
554
  export function assertValidPhysicalDeviceEvidence(evidence, options = {}) {
427
555
  const result = validatePhysicalDeviceEvidence(evidence, options);
428
556
  if (!result.valid) throw new EvidenceValidationError(result.errors);
@@ -435,6 +563,12 @@ export function physicalDeviceEvidenceV1(evidence, options = {}) {
435
563
 
436
564
  physicalDeviceEvidenceV1.schema = PHYSICAL_EVIDENCE_SCHEMA;
437
565
 
566
+ export function physicalDeviceEvidenceV2(evidence, options = {}) {
567
+ return validatePhysicalDeviceEvidenceV2(evidence, options);
568
+ }
569
+
570
+ physicalDeviceEvidenceV2.schema = PHYSICAL_EVIDENCE_V2_SCHEMA;
571
+
438
572
  export function sha256(value) {
439
573
  return createHash("sha256").update(value).digest("hex");
440
574
  }
@@ -31,19 +31,44 @@ export function nearestRank(values, percentile) {
31
31
 
32
32
  export function meanFps(frameIntervalsMs) {
33
33
  if (!Array.isArray(frameIntervalsMs) || frameIntervalsMs.length === 0) return undefined;
34
- if (frameIntervalsMs.some((value) => !Number.isFinite(value) || value <= 0)) return undefined;
35
- const mean = frameIntervalsMs.reduce((total, value) => total + value, 0) / frameIntervalsMs.length;
34
+ // Two presented frames can land inside one `performance.now()` quantum, which reads as a
35
+ // zero-length interval, and a cadence-limited browser produces them routinely. That is the
36
+ // clock's resolution rather than a measurement of the workload, and refusing the whole series
37
+ // over one of them discarded every other reading and blocked the comparison that had them.
38
+ // Excluding them can only understate the frame rate, and a series with nothing measurable left
39
+ // is still unmeasured.
40
+ //
41
+ // The exemption is the clock's alone: NaN, a negative and Infinity are malformed readings, and
42
+ // dropping them would publish a passing frame rate computed from the samples that happened to
43
+ // survive. Any invalid nonzero reading leaves the whole series unmeasured.
44
+ if (frameIntervalsMs.some((value) => !Number.isFinite(value) || value < 0)) return undefined;
45
+ const measurable = frameIntervalsMs.filter((value) => value > 0);
46
+ if (measurable.length === 0) return undefined;
47
+ const mean = measurable.reduce((total, value) => total + value, 0) / measurable.length;
36
48
  return 1_000 / mean;
37
49
  }
38
50
 
39
- export function oneSecondFrameFloors(intervals) {
40
- if (!Array.isArray(intervals) || intervals.length === 0) return [];
41
- const first = intervals[0]?.timestampMs;
42
- const last = intervals.at(-1)?.timestampMs;
51
+ /** How many of a series the clock could not resolve, so the evidence never hides the loss. */
52
+ export function unmeasurableIntervalCount(frameIntervalsMs) {
53
+ if (!Array.isArray(frameIntervalsMs)) return 0;
54
+ return frameIntervalsMs.filter((value) => value === 0).length;
55
+ }
56
+
57
+ /**
58
+ * Presented frames per second, from the elapsed milliseconds at which each presented frame landed.
59
+ *
60
+ * The count that used to be bucketed here was one record per rAF *callback*, and both arms run three
61
+ * callbacks per displayed frame, so a 40 fps display answered 120 and any `minOneSecondFps` floor
62
+ * passed on cadence it never presented. The stamps are the presented series, one per frame.
63
+ */
64
+ export function oneSecondFrameFloors(presentedStampsMs) {
65
+ if (!Array.isArray(presentedStampsMs) || presentedStampsMs.length === 0) return [];
66
+ const first = presentedStampsMs[0];
67
+ const last = presentedStampsMs.at(-1);
43
68
  if (!Number.isFinite(first) || !Number.isFinite(last) || last - first < 1_000) return [];
44
69
  const buckets = Math.floor((last - first) / 1_000);
45
- return Array.from({ length: buckets }, (_, bucket) => intervals.filter(({ timestampMs }) => {
46
- const offset = timestampMs - first;
70
+ return Array.from({ length: buckets }, (_, bucket) => presentedStampsMs.filter((stamp) => {
71
+ const offset = stamp - first;
47
72
  return offset >= bucket * 1_000 && offset < (bucket + 1) * 1_000;
48
73
  }).length);
49
74
  }
@@ -55,7 +80,9 @@ export function evaluateFrameBudget(metrics, budget = {}) {
55
80
  const p99 = finiteMetric(metrics.p99FrameMs) ? metrics.p99FrameMs : nearestRank(metrics.frameIntervalsMs, 0.99);
56
81
  const medianFrameMs = nearestRank(metrics.frameIntervalsMs, 0.5);
57
82
  if (budget.minFps !== undefined && (!finiteMetric(medianFrameMs) || Math.round(100_000 / medianFrameMs) / 100 < budget.minFps)) failures.push('TN_PROD_PERFORMANCE_BUDGET');
58
- const floors = metrics.oneSecondFps ?? oneSecondFrameFloors(metrics.intervals ?? []);
83
+ // Read the published presented-frame floors or nothing: the callback records this used to bucket
84
+ // are not a frame count, and an absent floor fails the budget rather than passing it unseen.
85
+ const floors = Array.isArray(metrics.oneSecondFps) ? metrics.oneSecondFps : [];
59
86
  const drawCalls = maximumMetric(metrics, 'drawCalls');
60
87
  const triangles = maximumMetric(metrics, 'triangles');
61
88
  if (budget.minMeanFps !== undefined && (mean === undefined || mean < budget.minMeanFps)) failures.push('TN_PROD_PERFORMANCE_BUDGET');