diff --git a/scene-contract/.gitignore b/scene-contract/.gitignore new file mode 100644 index 00000000..1eae0cf6 --- /dev/null +++ b/scene-contract/.gitignore @@ -0,0 +1,2 @@ +dist/ +node_modules/ diff --git a/scene-contract/package-lock.json b/scene-contract/package-lock.json new file mode 100644 index 00000000..69472aaf --- /dev/null +++ b/scene-contract/package-lock.json @@ -0,0 +1,304 @@ +{ + "name": "simplecad-scene-contract-parity", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "simplecad-scene-contract-parity", + "version": "1.0.0", + "dependencies": { + "ajv": "8.20.0" + }, + "devDependencies": { + "@types/node": "22.10.2", + "json-schema-to-typescript": "15.0.4", + "typescript": "5.7.2" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@apidevtools/json-schema-ref-parser": { + "version": "11.9.3", + "resolved": "https://registry.npmjs.org/@apidevtools/json-schema-ref-parser/-/json-schema-ref-parser-11.9.3.tgz", + "integrity": "sha512-60vepv88RwcJtSHrD6MjIL6Ta3SOYbgfnkHb+ppAVK+o9mXprRtulx7VlRl3lN3bbvysAfCS7WMVfhUYemB0IQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jsdevtools/ono": "^7.1.3", + "@types/json-schema": "^7.0.15", + "js-yaml": "^4.1.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/philsturgeon" + } + }, + "node_modules/@jsdevtools/ono": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz", + "integrity": "sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/lodash": { + "version": "4.17.24", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.24.tgz", + "integrity": "sha512-gIW7lQLZbue7lRSWEFql49QJJWThrTFFeIMJdp3eH4tKoxm1OvEPg02rm4wCCSHS0cL3/Fizimb35b7k8atwsQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.10.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.10.2.tgz", + "integrity": "sha512-Xxr6BBRCAOQixvonOye19wnzyDiUtTeqldOOmj3CkeblonbccA12PFwlufvRdrpjXxqnmUaeiU5EOA+7s5diUQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.20.0" + } + }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.3.tgz", + "integrity": "sha512-i70LwGWUduXqzicKXWshooq+sWL1K3WUU5rKZNG/0i3a1OSoX3HqhH5WbWwTmqWfor4urUakGPiRQcleRZTwOg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/js-yaml": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz", + "integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-schema-to-typescript": { + "version": "15.0.4", + "resolved": "https://registry.npmjs.org/json-schema-to-typescript/-/json-schema-to-typescript-15.0.4.tgz", + "integrity": "sha512-Su9oK8DR4xCmDsLlyvadkXzX6+GGXJpbhwoLtOGArAG61dvbW4YQmSEno2y66ahpIdmLMg6YUf/QHLgiwvkrHQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@apidevtools/json-schema-ref-parser": "^11.5.5", + "@types/json-schema": "^7.0.15", + "@types/lodash": "^4.17.7", + "is-glob": "^4.0.3", + "js-yaml": "^4.1.0", + "lodash": "^4.17.21", + "minimist": "^1.2.8", + "prettier": "^3.2.5", + "tinyglobby": "^0.2.9" + }, + "bin": { + "json2ts": "dist/src/cli.js" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/picomatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", + "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/prettier": { + "version": "3.9.5", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.5.tgz", + "integrity": "sha512-/FVl766LpUfB5vXgCYOYa0MeV/441Ia99AeICQIQFTY/Nw0roZwULcXpku5i1/m5kt/baz+s4Zogspd839HSMg==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.2.tgz", + "integrity": "sha512-i5t66RHxDvVN40HfDd1PsEThGNnlMCMT3jMUuoh9/0TaqWevNontacunWyN02LA9/fIbEWlcHZcgTKb9QoaLfg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.20.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz", + "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/scene-contract/package.json b/scene-contract/package.json new file mode 100644 index 00000000..46720c23 --- /dev/null +++ b/scene-contract/package.json @@ -0,0 +1,24 @@ +{ + "name": "simplecad-scene-contract-parity", + "version": "1.0.0", + "private": true, + "type": "module", + "engines": { + "node": ">=20" + }, + "scripts": { + "build": "tsc", + "generate:types": "uv run python ../tools/generate_scene_contract_types.py --language typescript", + "check:types": "uv run python ../tools/generate_scene_contract_types.py --check --language typescript", + "test": "npm run check:types && npm run build && node --test dist/test/*.test.js", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "ajv": "8.20.0" + }, + "devDependencies": { + "@types/node": "22.10.2", + "json-schema-to-typescript": "15.0.4", + "typescript": "5.7.2" + } +} diff --git a/scene-contract/src/canonical.ts b/scene-contract/src/canonical.ts new file mode 100644 index 00000000..de7596b4 --- /dev/null +++ b/scene-contract/src/canonical.ts @@ -0,0 +1,266 @@ +import { createHash } from "node:crypto"; + +export class DuplicateKeyError extends SyntaxError {} + +const decoder = new TextDecoder("utf-8", { fatal: true }); +const maxSafeInteger = 9_007_199_254_740_991; +const parserDepthCapacity = 256; + +function assertUnicodeScalarString(value: string): void { + for (let index = 0; index < value.length; index += 1) { + const unit = value.charCodeAt(index); + if (unit >= 0xd800 && unit <= 0xdbff) { + const next = value.charCodeAt(index + 1); + if (!Number.isInteger(next) || next < 0xdc00 || next > 0xdfff) { + throw new TypeError("string contains an unpaired surrogate"); + } + index += 1; + } else if (unit >= 0xdc00 && unit <= 0xdfff) { + throw new TypeError("string contains an unpaired surrogate"); + } + } +} + +class StrictJsonParser { + private offset = 0; + + public constructor(private readonly text: string) {} + + public parse(): unknown { + this.space(); + const parsed = this.value(0); + this.space(); + if (this.offset !== this.text.length) { + throw new SyntaxError("trailing data after JSON value"); + } + return parsed; + } + + private value(depth: number): unknown { + if (depth > parserDepthCapacity) { + throw new SyntaxError("JSON nesting exceeds parser capacity"); + } + this.space(); + const token = this.text[this.offset]; + if ( + this.text.startsWith("NaN", this.offset) || + this.text.startsWith("Infinity", this.offset) || + this.text.startsWith("-Infinity", this.offset) + ) { + throw new SyntaxError("non-finite JSON number is forbidden"); + } + if (token === "{") return this.object(depth + 1); + if (token === "[") return this.array(depth + 1); + if (token === '"') return this.string(); + if (token === "t" && this.consume("true")) return true; + if (token === "f" && this.consume("false")) return false; + if (token === "n" && this.consume("null")) return null; + if (token === "-" || (token !== undefined && token >= "0" && token <= "9")) { + return this.number(); + } + throw new SyntaxError(`invalid JSON token at offset ${this.offset}`); + } + + private object(depth: number): Record { + this.offset += 1; + this.space(); + const result: Record = Object.create(null) as Record; + const keys = new Set(); + if (this.text[this.offset] === "}") { + this.offset += 1; + return result; + } + while (true) { + if (this.text[this.offset] !== '"') { + throw new SyntaxError(`JSON object key expected at offset ${this.offset}`); + } + const key = this.string(); + if (keys.has(key)) { + throw new DuplicateKeyError(`duplicate JSON object member: ${JSON.stringify(key)}`); + } + keys.add(key); + this.space(); + if (this.text[this.offset] !== ":") { + throw new SyntaxError(`JSON object colon expected at offset ${this.offset}`); + } + this.offset += 1; + const child = this.value(depth); + result[key] = child; + this.space(); + const separator = this.text[this.offset]; + this.offset += 1; + if (separator === "}") return result; + if (separator !== ",") { + throw new SyntaxError(`JSON object separator expected at offset ${this.offset - 1}`); + } + this.space(); + } + } + + private array(depth: number): unknown[] { + this.offset += 1; + this.space(); + const result: unknown[] = []; + if (this.text[this.offset] === "]") { + this.offset += 1; + return result; + } + while (true) { + const child = this.value(depth); + result.push(child); + this.space(); + const separator = this.text[this.offset]; + this.offset += 1; + if (separator === "]") return result; + if (separator !== ",") { + throw new SyntaxError(`JSON array separator expected at offset ${this.offset - 1}`); + } + this.space(); + } + } + + private string(): string { + const start = this.offset; + this.offset += 1; + while (this.offset < this.text.length) { + const unit = this.text.charCodeAt(this.offset); + if (unit < 0x20) { + throw new SyntaxError(`unescaped control character at offset ${this.offset}`); + } + if (unit === 0x22) { + this.offset += 1; + const result = JSON.parse(this.text.slice(start, this.offset)) as string; + assertUnicodeScalarString(result); + return result; + } + if (unit === 0x5c) { + this.offset += 1; + const escape = this.text[this.offset]; + if (escape === "u") { + if (!/^[0-9a-fA-F]{4}$/.test(this.text.slice(this.offset + 1, this.offset + 5))) { + throw new SyntaxError(`invalid JSON Unicode escape at offset ${this.offset}`); + } + this.offset += 5; + continue; + } + if (escape === undefined || !'"\\/bfnrt'.includes(escape)) { + throw new SyntaxError(`invalid JSON escape at offset ${this.offset}`); + } + } + this.offset += 1; + } + throw new SyntaxError("unterminated JSON string"); + } + + private number(): number { + const match = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/.exec( + this.text.slice(this.offset), + ); + if (match === null) throw new SyntaxError(`invalid JSON number at offset ${this.offset}`); + const token = match[0]; + this.offset += token.length; + const result = Number(token); + if (!/[.eE]/.test(token) && Math.abs(result) > maxSafeInteger) { + throw new SyntaxError("JSON integer exceeds the JCS safe domain"); + } + if (!Number.isFinite(result)) throw new SyntaxError("non-finite JSON number is forbidden"); + return result; + } + + private consume(token: string): boolean { + if (!this.text.startsWith(token, this.offset)) return false; + this.offset += token.length; + return true; + } + + private space(): void { + while ( + this.text[this.offset] === " " || + this.text[this.offset] === "\n" || + this.text[this.offset] === "\r" || + this.text[this.offset] === "\t" + ) { + this.offset += 1; + } + } +} + +export function parseStrictJson(data: Uint8Array | string): unknown { + let text: string; + if (typeof data === "string") { + text = data; + } else { + if (data.length >= 3 && data[0] === 0xef && data[1] === 0xbb && data[2] === 0xbf) { + throw new SyntaxError("UTF-8 BOM is forbidden"); + } + text = decoder.decode(data); + } + if (text.startsWith("\ufeff")) throw new SyntaxError("UTF-8 BOM is forbidden"); + return new StrictJsonParser(text).parse(); +} + +function serialize(value: unknown, stack: Set): string { + if (value === null) return "null"; + if (typeof value === "boolean") return value ? "true" : "false"; + if (typeof value === "number") { + if (!Number.isFinite(value)) throw new TypeError("JSON number must be finite"); + return JSON.stringify(value); + } + if (typeof value === "string") { + assertUnicodeScalarString(value); + return JSON.stringify(value); + } + if (typeof value !== "object") throw new TypeError(`unsupported JSON value: ${typeof value}`); + if (stack.has(value)) throw new TypeError("cyclic value is not JSON"); + stack.add(value); + let result: string; + if (Array.isArray(value)) { + const items: string[] = []; + for (let index = 0; index < value.length; index += 1) { + if (!Object.hasOwn(value, index)) throw new TypeError("sparse arrays are outside the JSON domain"); + items.push(serialize(value[index], stack)); + } + result = `[${items.join(",")}]`; + } else { + const record = value as Record; + const keys = Object.keys(record).sort(); + for (const key of keys) assertUnicodeScalarString(key); + result = `{${keys + .map((key) => `${JSON.stringify(key)}:${serialize(record[key], stack)}`) + .join(",")}}`; + } + stack.delete(value); + return result; +} + +export function canonicalJsonBytes(value: unknown): Buffer { + return Buffer.from(serialize(value, new Set()), "utf8"); +} + +export function parseCanonicalJson(data: Uint8Array | string): unknown { + const raw = typeof data === "string" ? Buffer.from(data, "utf8") : Buffer.from(data); + const parsed = parseStrictJson(raw); + if (!raw.equals(canonicalJsonBytes(parsed))) { + throw new SyntaxError("JSON bytes are not RFC 8785 canonical"); + } + return parsed; +} + +export function sha256(data: Uint8Array): string { + return `sha256:${createHash("sha256").update(data).digest("hex")}`; +} + +export function canonicalJsonHash(value: unknown): string { + return sha256(canonicalJsonBytes(value)); +} + +export function computeSceneRevision(scene: Record): string { + const { revision: _revision, ...draft } = scene; + return canonicalJsonHash(draft); +} + +export function withSceneRevision(scene: Record): Record { + const result = structuredClone(scene); + result.revision = computeSceneRevision(result); + return result; +} diff --git a/scene-contract/src/documents.ts b/scene-contract/src/documents.ts new file mode 100644 index 00000000..e7aabe7e --- /dev/null +++ b/scene-contract/src/documents.ts @@ -0,0 +1,158 @@ +import type { + ConnectorBindingDocument as ConnectorBindingValue, + EntityDocument as EntityValue, + NormalizedProductDocument as NormalizedProductValue, + PresentationDocument as PresentationValue, + SceneDocument as SceneValue, +} from "./generated/index.js"; +import { canonicalJsonBytes, parseCanonicalJson, sha256 } from "./canonical.js"; +import type { ValidationReport } from "./report.js"; +import { + validateConnectorBinding, + validateEntityAsset, + validateNormalizedProduct, + validatePresentation, + validateSceneManifest, +} from "./validation.js"; + +export type SceneDocument = SceneValue; +export type EntityDocument = EntityValue; +export type PresentationDocument = PresentationValue; +export type ConnectorBindingDocument = ConnectorBindingValue; +export type NormalizedProductDocument = NormalizedProductValue; + +export type DeepReadonly = + T extends (...args: never[]) => unknown + ? T + : T extends readonly (infer Item)[] + ? readonly DeepReadonly[] + : T extends object + ? { readonly [Key in keyof T]: DeepReadonly } + : T; + +export interface ImmutableContractDocument { + readonly value: DeepReadonly; + readonly canonicalBytes: Buffer; + readonly canonicalHash: string; + toMutable(): Value; +} + +export interface ImmutableSceneDocument + extends ImmutableContractDocument { + readonly revision: string; +} + +export type ImmutableEntityDocument = ImmutableContractDocument; +export type ImmutablePresentationDocument = + ImmutableContractDocument; +export type ImmutableConnectorBindingDocument = + ImmutableContractDocument; +export type ImmutableNormalizedProductDocument = + ImmutableContractDocument; + +export interface ContractDocumentFactory { + fromValue(value: Value | DeepReadonly): Document; + parse(data: Uint8Array | string): Document; +} + +export class ContractDocumentValidationError extends TypeError { + public constructor(public readonly report: ValidationReport) { + const first = report.firstError; + super( + first === null + ? "Scene contract validation failed" + : `Scene contract validation failed: ${first.code} at ${first.path}: ${first.message}`, + ); + this.name = "ContractDocumentValidationError"; + } +} + +type Validator = (value: unknown) => ValidationReport; + +function deepFreeze(value: unknown): unknown { + if (Array.isArray(value)) { + for (const child of value) deepFreeze(child); + return Object.freeze(value); + } + if (value !== null && typeof value === "object") { + for (const child of Object.values(value)) deepFreeze(child); + return Object.freeze(value); + } + return value; +} + +class FrozenContractDocument + implements ImmutableContractDocument +{ + readonly #value: DeepReadonly; + readonly #canonicalBytes: Buffer; + readonly #canonicalHash: string; + + public constructor(value: Value | DeepReadonly, validate: Validator) { + const canonical = canonicalJsonBytes(value); + const detached = parseCanonicalJson(canonical); + const validation = validate(detached); + if (!validation.valid) throw new ContractDocumentValidationError(validation); + this.#value = deepFreeze(detached) as DeepReadonly; + this.#canonicalBytes = Buffer.from(canonical); + this.#canonicalHash = sha256(canonical); + Object.freeze(this); + } + + public get value(): DeepReadonly { + return this.#value; + } + + public get canonicalBytes(): Buffer { + return Buffer.from(this.#canonicalBytes); + } + + public get canonicalHash(): string { + return this.#canonicalHash; + } + + public toMutable(): Value { + return parseCanonicalJson(this.#canonicalBytes) as Value; + } +} + +class FrozenSceneDocument + extends FrozenContractDocument + implements ImmutableSceneDocument +{ + public get revision(): string { + return this.value.revision; + } +} + +function documentFactory( + create: (value: Value | DeepReadonly) => Document, +): ContractDocumentFactory { + return Object.freeze({ + fromValue: create, + parse: (data: Uint8Array | string) => create(parseCanonicalJson(data) as Value), + }); +} + +export const SceneDocument = documentFactory( + (value) => new FrozenSceneDocument(value, validateSceneManifest), +); + +export const EntityDocument = documentFactory( + (value) => new FrozenContractDocument(value, validateEntityAsset), +); + +export const PresentationDocument = documentFactory< + PresentationValue, + ImmutablePresentationDocument +>((value) => new FrozenContractDocument(value, validatePresentation)); + +export const ConnectorBindingDocument = documentFactory< + ConnectorBindingValue, + ImmutableConnectorBindingDocument +>((value) => new FrozenContractDocument(value, validateConnectorBinding)); + +export const NormalizedProductDocument = documentFactory< + NormalizedProductValue, + ImmutableNormalizedProductDocument +>((value) => new FrozenContractDocument(value, validateNormalizedProduct)); diff --git a/scene-contract/src/generated/connector_binding.ts b/scene-contract/src/generated/connector_binding.ts new file mode 100644 index 00000000..93721325 --- /dev/null +++ b/scene-contract/src/generated/connector_binding.ts @@ -0,0 +1,94 @@ +/* eslint-disable */ +/** + * This file was automatically generated by json-schema-to-typescript. + * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, + * and run json-schema-to-typescript to regenerate this file. + */ + +/** + * This interface was referenced by `ConnectorBindingDocument`'s JSON-Schema + * via the `definition` "logicalId". + */ +export type LogicalId = string; +/** + * This interface was referenced by `ConnectorBindingDocument`'s JSON-Schema + * via the `definition` "productId". + */ +export type ProductId = string; +/** + * This interface was referenced by `ConnectorBindingDocument`'s JSON-Schema + * via the `definition` "hash". + */ +export type Hash = string; +/** + * This interface was referenced by `ConnectorBindingDocument`'s JSON-Schema + * via the `definition` "structuralId". + */ +export type StructuralId = string; +/** + * This interface was referenced by `ConnectorBindingDocument`'s JSON-Schema + * via the `definition` "safeInteger". + */ +export type SafeInteger = number; + +export interface ConnectorBindingDocument { + schema_version: "1.0"; + binding_id: LogicalId; + source_model: SourceModel; + source_scene: SourceScene; + owner_definition_id: StructuralId; + selected_occurrence_node_id: StructuralId; + connector_id: ProductId; + name: string | null; + target: Target; +} +/** + * This interface was referenced by `ConnectorBindingDocument`'s JSON-Schema + * via the `definition` "sourceModel". + */ +export interface SourceModel { + graph_id: ProductId; + model_schema_version: "2.0"; + artifact_hash: Hash; +} +/** + * This interface was referenced by `ConnectorBindingDocument`'s JSON-Schema + * via the `definition` "sourceScene". + */ +export interface SourceScene { + scene_id: LogicalId; + revision: Hash; +} +/** + * This interface was referenced by `ConnectorBindingDocument`'s JSON-Schema + * via the `definition` "target". + */ +export interface Target { + kind: "topology_entity"; + entity_asset_id: Hash; + entity_id: string; + expected_source: ModelOutput | ModelTopology; + flip: boolean; +} +/** + * This interface was referenced by `ConnectorBindingDocument`'s JSON-Schema + * via the `definition` "modelOutput". + */ +export interface ModelOutput { + kind: "model_output"; + graph_id: ProductId; + node_id: ProductId; + output_slot: SafeInteger; +} +/** + * This interface was referenced by `ConnectorBindingDocument`'s JSON-Schema + * via the `definition` "modelTopology". + */ +export interface ModelTopology { + kind: "model_topology"; + graph_id: ProductId; + node_id: ProductId; + output_slot: SafeInteger; + topology_kind: "FACE" | "EDGE" | "VERTEX"; + topo_id: string; +} diff --git a/scene-contract/src/generated/entities.ts b/scene-contract/src/generated/entities.ts new file mode 100644 index 00000000..689c5085 --- /dev/null +++ b/scene-contract/src/generated/entities.ts @@ -0,0 +1,379 @@ +/* eslint-disable */ +/** + * This file was automatically generated by json-schema-to-typescript. + * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, + * and run json-schema-to-typescript to regenerate this file. + */ + +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "structuralId". + */ +export type StructuralId = string; +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "hash". + */ +export type Hash = string; +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "entityId". + */ +export type EntityId = string; +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "source". + */ +export type Source = ModelOutput | ModelTopology | ImportedPrimitive | Unbound; +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "productId". + */ +export type ProductId = string; +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "safeInteger". + */ +export type SafeInteger = number; +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "geometry". + */ +export type Geometry = + | BrepSolid + | Point + | Line + | Circle + | Ellipse + | BsplineCurve + | OtherCurve + | Plane + | Cylinder + | Cone + | Sphere + | Torus + | BsplineSurface + | OtherSurface; +/** + * @minItems 3 + * @maxItems 3 + * + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "vec3". + */ +export type Vec3 = [number, number, number]; +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "positiveInteger". + */ +export type PositiveInteger = number; + +export interface EntityDocument { + schema_version: "1.0"; + definition_id: StructuralId; + geometry_asset_id: Hash; + edge_asset_id: Hash; + geometry_engine: GeometryEngine; + /** + * @minItems 4 + */ + entities: [Entity, Entity, Entity, Entity, ...Entity[]]; + /** + * @minItems 1 + */ + face_groups: [Group, ...Group[]]; + edge_groups: Group[]; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "geometryEngine". + */ +export interface GeometryEngine { + name: "OpenCascade"; + version: string; + profile: "ocp-evaluated-properties-1"; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "entity". + */ +export interface Entity { + entity_id: EntityId; + kind: "solid" | "face" | "edge" | "vertex"; + parent_entity_ids: EntityId[]; + child_entity_ids: EntityId[]; + source: Source; + geometry: Geometry; + properties: SolidProperties | FaceProperties | EdgeProperties | VertexProperties; + sdk_connector_frame: null | Transform; + render_status: "rendered" | "degenerate"; + connector_binding_status: + | "not_applicable" + | "owner_not_part" + | "source_not_model" + | "frame_undefined" + | "selector_ambiguous" + | "selector_unstable" + | "supported"; + semantic_binding_ids: string[]; + evaluated_tags: string[]; + sdk_metadata: { + [k: string]: unknown; + }; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "modelOutput". + */ +export interface ModelOutput { + kind: "model_output"; + graph_id: ProductId; + node_id: ProductId; + output_slot: SafeInteger; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "modelTopology". + */ +export interface ModelTopology { + kind: "model_topology"; + graph_id: ProductId; + node_id: ProductId; + output_slot: SafeInteger; + topology_kind: "SOLID" | "FACE" | "EDGE" | "VERTEX"; + topo_id: string; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "importedPrimitive". + */ +export interface ImportedPrimitive { + kind: "imported_primitive"; + source_element_id: string; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "unbound". + */ +export interface Unbound { + kind: "unbound"; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "brepSolid". + */ +export interface BrepSolid { + type: "brep_solid"; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "point". + */ +export interface Point { + type: "point"; + position: Vec3; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "line". + */ +export interface Line { + type: "line"; + origin: Vec3; + direction: Vec3; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "circle". + */ +export interface Circle { + type: "circle"; + center: Vec3; + normal: Vec3; + x_direction: Vec3; + radius: number; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "ellipse". + */ +export interface Ellipse { + type: "ellipse"; + center: Vec3; + normal: Vec3; + x_direction: Vec3; + major_radius: number; + minor_radius: number; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "bsplineCurve". + */ +export interface BsplineCurve { + type: "bspline_curve"; + degree: SafeInteger; + rational: boolean; + periodic: boolean; + poles_count: SafeInteger; + knots_count: SafeInteger; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "otherCurve". + */ +export interface OtherCurve { + type: "other_curve"; + engine_type: string; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "plane". + */ +export interface Plane { + type: "plane"; + origin: Vec3; + normal: Vec3; + x_direction: Vec3; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "cylinder". + */ +export interface Cylinder { + type: "cylinder"; + origin: Vec3; + axis: Vec3; + x_direction: Vec3; + radius: number; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "cone". + */ +export interface Cone { + type: "cone"; + origin: Vec3; + axis: Vec3; + x_direction: Vec3; + reference_radius: number; + semi_angle_degrees: number; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "sphere". + */ +export interface Sphere { + type: "sphere"; + center: Vec3; + axis: Vec3; + x_direction: Vec3; + radius: number; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "torus". + */ +export interface Torus { + type: "torus"; + center: Vec3; + axis: Vec3; + x_direction: Vec3; + major_radius: number; + minor_radius: number; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "bsplineSurface". + */ +export interface BsplineSurface { + type: "bspline_surface"; + u_degree: SafeInteger; + v_degree: SafeInteger; + u_rational: boolean; + v_rational: boolean; + u_periodic: boolean; + v_periodic: boolean; + u_poles_count: SafeInteger; + v_poles_count: SafeInteger; + u_knots_count: SafeInteger; + v_knots_count: SafeInteger; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "otherSurface". + */ +export interface OtherSurface { + type: "other_surface"; + engine_type: string; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "solidProperties". + */ +export interface SolidProperties { + quality: "kernel_evaluated"; + bounds: Bounds; + volume: number; + surface_area: number; + centroid: Vec3; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "bounds". + */ +export interface Bounds { + min: Vec3; + max: Vec3; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "faceProperties". + */ +export interface FaceProperties { + quality: "kernel_evaluated"; + bounds: Bounds; + area: number; + centroid: Vec3; + orientation: "forward" | "reversed" | "internal" | "external"; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "edgeProperties". + */ +export interface EdgeProperties { + quality: "kernel_evaluated"; + bounds: Bounds; + length: number; + centroid: Vec3; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "vertexProperties". + */ +export interface VertexProperties { + quality: "kernel_evaluated"; + bounds: Bounds; + position: Vec3; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "transform". + */ +export interface Transform { + origin: Vec3; + x_axis: Vec3; + y_axis: Vec3; + z_axis: Vec3; +} +/** + * This interface was referenced by `EntityDocument`'s JSON-Schema + * via the `definition` "group". + */ +export interface Group { + group_id: SafeInteger; + entity_id: EntityId; + mesh_index: 0; + primitive_index: 0; + first_index: SafeInteger; + index_count: PositiveInteger; +} diff --git a/scene-contract/src/generated/index.ts b/scene-contract/src/generated/index.ts new file mode 100644 index 00000000..6a2407bc --- /dev/null +++ b/scene-contract/src/generated/index.ts @@ -0,0 +1,7 @@ +// Generated by tools/generate_scene_contract_types.py. Do not edit. + +export type { SceneDocument } from "./scene.js"; +export type { EntityDocument } from "./entities.js"; +export type { PresentationDocument } from "./presentation.js"; +export type { ConnectorBindingDocument } from "./connector_binding.js"; +export type { NormalizedProductDocument } from "./normalized_product.js"; diff --git a/scene-contract/src/generated/normalized_product.ts b/scene-contract/src/generated/normalized_product.ts new file mode 100644 index 00000000..b64de3ec --- /dev/null +++ b/scene-contract/src/generated/normalized_product.ts @@ -0,0 +1,128 @@ +/* eslint-disable */ +/** + * This file was automatically generated by json-schema-to-typescript. + * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, + * and run json-schema-to-typescript to regenerate this file. + */ + +export type NormalizedProductDocument = Part | Assembly; +export type ProductId = string; +export type BodySource = ModelBodySource | ManualBodySource; +export type SafeInteger = number; +export type Connector = { + [k: string]: unknown; +} & { + connector_id: ProductId; + name: string | null; + anchor: GeometryAnchor | PlacementAnchor | ForwardedAnchor; + geometry_ref?: null | GeometryRef; +}; +/** + * @minItems 3 + * @maxItems 3 + */ +export type Vec3 = [number, number, number]; +export type StructuralId = string; + +export interface Part { + kind: "part"; + part_id: ProductId; + body_source: BodySource; + name: string | null; + material: null | Material; + connectors: Connector[]; + metadata: { + [k: string]: unknown; + }; +} +export interface ModelBodySource { + kind: "model_output"; + graph_id: ProductId; + node_id: ProductId; + output_slot: SafeInteger; +} +export interface ManualBodySource { + kind: "manual"; + source_id: ProductId; +} +export interface Material { + material_id: ProductId; + name: string | null; + density: number | null; + density_unit: string | null; + color: null | [number, number, number]; + metadata: { + [k: string]: unknown; + }; +} +export interface GeometryAnchor { + anchor_kind: "geometry"; + geometry_ref: GeometryRef; +} +export interface GeometryRef { + kind: "face" | "edge" | "vertex"; + source_node_id: string | null; + geo_selector: { + [k: string]: unknown; + }; + flip: boolean; +} +export interface PlacementAnchor { + anchor_kind: "placement"; + placement: Transform; +} +export interface Transform { + origin: Vec3; + x_axis: Vec3; + y_axis: Vec3; + z_axis: Vec3; +} +export interface ForwardedAnchor { + anchor_kind: "forwarded"; + source_component_id: ProductId; + source_connector_id: ProductId; + offset: null | Transform; +} +export interface Assembly { + kind: "assembly"; + assembly_id: ProductId; + name: string | null; + components: Component[]; + connectors: Connector[]; + constraints: Constraint[]; + grounded_component_ids: ProductId[]; + metadata: { + [k: string]: unknown; + }; +} +export interface Component { + component_id: ProductId; + name: string | null; + definition_ref: StructuralId; + local_placement: Transform; +} +export interface Constraint { + constraint_id: ProductId; + constraint_kind: "fixed" | "revolute" | "prismatic" | "gear" | "belt" | "rack_pinion"; + connector_a: ConnectorRef; + connector_b: ConnectorRef; + drive_distance: number | null; + distance_limit: null | Limit; + drive_angle_degrees: number | null; + angle_limit: null | Limit; + pitch_radius_a: number | null; + pitch_radius_b: number | null; + pulley_radius_a: number | null; + pulley_radius_b: number | null; + pitch_radius: number | null; + phase_offset: number | null; + name: string | null; +} +export interface ConnectorRef { + component_id: ProductId; + connector_id: ProductId; +} +export interface Limit { + lower_value: number; + upper_value: number; +} diff --git a/scene-contract/src/generated/presentation.ts b/scene-contract/src/generated/presentation.ts new file mode 100644 index 00000000..976b320e --- /dev/null +++ b/scene-contract/src/generated/presentation.ts @@ -0,0 +1,120 @@ +/* eslint-disable */ +/** + * This file was automatically generated by json-schema-to-typescript. + * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, + * and run json-schema-to-typescript to regenerate this file. + */ + +/** + * This interface was referenced by `PresentationDocument`'s JSON-Schema + * via the `definition` "logicalId". + */ +export type LogicalId = string; +/** + * @minItems 4 + * @maxItems 4 + * + * This interface was referenced by `PresentationDocument`'s JSON-Schema + * via the `definition` "color". + */ +export type Color = [number, number, number, 1]; +/** + * This interface was referenced by `PresentationDocument`'s JSON-Schema + * via the `definition` "nodeOverride". + */ +export type NodeOverride = NodeOverride1 & { + node_id: StructuralId; + visible?: boolean; + appearance_name?: string; +}; +export type NodeOverride1 = { + [k: string]: unknown; +}; +/** + * This interface was referenced by `PresentationDocument`'s JSON-Schema + * via the `definition` "structuralId". + */ +export type StructuralId = string; +/** + * This interface was referenced by `PresentationDocument`'s JSON-Schema + * via the `definition` "camera". + */ +export type Camera = Perspective | Orthographic; +/** + * @minItems 3 + * @maxItems 3 + * + * This interface was referenced by `PresentationDocument`'s JSON-Schema + * via the `definition` "vec3". + */ +export type Vec3 = [number, number, number]; +/** + * This interface was referenced by `PresentationDocument`'s JSON-Schema + * via the `definition` "positive". + */ +export type Positive = number; + +export interface PresentationDocument { + schema_version: "1.0"; + presentation_id: LogicalId; + source_scene_id: LogicalId; + appearances: Appearance[]; + node_overrides: NodeOverride[]; + cameras: Camera[]; +} +/** + * This interface was referenced by `PresentationDocument`'s JSON-Schema + * via the `definition` "appearance". + */ +export interface Appearance { + name: string; + base_color: Color; + metallic: number; + roughness: number; + alpha_mode: "opaque"; + double_sided: boolean; + edge_color: Color; +} +/** + * This interface was referenced by `PresentationDocument`'s JSON-Schema + * via the `definition` "perspective". + */ +export interface Perspective { + name: string; + projection: "perspective"; + parent_node_id: null | StructuralId; + transform: Transform; + near: Positive; + far: Positive; + vertical_fov_degrees: number; +} +/** + * This interface was referenced by `PresentationDocument`'s JSON-Schema + * via the `definition` "transform". + */ +export interface Transform { + origin: Vec3; + x_axis: Vec3; + y_axis: Vec3; + z_axis: Vec3; +} +/** + * This interface was referenced by `PresentationDocument`'s JSON-Schema + * via the `definition` "orthographic". + */ +export interface Orthographic { + name: string; + projection: "orthographic"; + parent_node_id: null | StructuralId; + transform: Transform; + near: Positive; + far: Positive; + vertical_span: Positive; +} +/** + * This interface was referenced by `PresentationDocument`'s JSON-Schema + * via the `definition` "cameraBaseProperties". + */ +export interface CameraBaseProperties { + [k: string]: unknown; +} diff --git a/scene-contract/src/generated/scene.ts b/scene-contract/src/generated/scene.ts new file mode 100644 index 00000000..e9f2da2b --- /dev/null +++ b/scene-contract/src/generated/scene.ts @@ -0,0 +1,545 @@ +/* eslint-disable */ +/** + * This file was automatically generated by json-schema-to-typescript. + * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, + * and run json-schema-to-typescript to regenerate this file. + */ + +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "logicalId". + */ +export type LogicalId = string; +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "hash". + */ +export type Hash = string; +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "token". + */ +export type Token = string; +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "sceneSource". + */ +export type SceneSource = ModelSource | ImportedSource | ManualSource; +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "productId". + */ +export type ProductId = string; +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "safeInteger". + */ +export type SafeInteger = number; +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "uri". + */ +export type Uri = string; +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "definition". + */ +export type Definition = { + [k: string]: unknown; +} & { + definition_id: StructuralId; + kind: "part" | "assembly" | "shape"; + name: string | null; + source: DefinitionSource; + sdk_metadata: { + [k: string]: unknown; + }; + geometry_asset_id?: Hash; + edge_asset_id?: Hash; + entity_asset_id?: Hash; + appearance_id?: StructuralId; +}; +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "structuralId". + */ +export type StructuralId = string; +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "definitionSource". + */ +export type DefinitionSource = + ProductModelSource | ProductManualSource | ModelOutputSource | ImportedDefinitionSource | ManualDefinitionSource; +/** + * @minItems 3 + * @maxItems 3 + * + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "vec3". + */ +export type Vec3 = [Number, Number, Number]; +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "number". + */ +export type Number = number; +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "positiveNumber". + */ +export type PositiveNumber = number; +/** + * @minItems 4 + * @maxItems 4 + * + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "color". + */ +export type Color = [number, number, number, 1]; +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "connector". + */ +export type Connector = { + [k: string]: unknown; +} & { + connector_snapshot_id: StructuralId; + owner_definition_id: StructuralId; + connector_id: ProductId; + name: string | null; + anchor_kind: "geometry" | "placement" | "forwarded"; + local_transform: Transform; + target?: ConnectorTarget; + forwarded_from?: ForwardedFrom; + source: null | ModelOperationSource | ManualConnectorSource; + sdk_metadata: { + [k: string]: unknown; + }; +}; +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "camera". + */ +export type Camera = PerspectiveCamera | OrthographicCamera; + +export interface SceneDocument { + schema_version: "1.0"; + /** + * @maxItems 0 + */ + extensions_used: unknown[]; + /** + * @maxItems 0 + */ + extensions_required: unknown[]; + extensions: { + [k: string]: unknown; + }; + scene_id: LogicalId; + revision: Hash; + generator: Generator; + source: SceneSource; + presentation_source?: PresentationSource; + coordinate_system: CoordinateSystem; + compile_options: CompileOptions; + definitions: Definition[]; + nodes: Node[]; + geometry_assets: GeometryAsset[]; + edge_assets: EdgeAsset[]; + appearances: Appearance[]; + entity_assets: EntityAsset[]; + connectors: Connector[]; + cameras: Camera[]; + /** + * @maxItems 0 + */ + lights: unknown[]; + /** + * @maxItems 0 + */ + annotations: unknown[]; + /** + * @maxItems 0 + */ + diagnostics: unknown[]; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "generator". + */ +export interface Generator { + name: "simplecadapi"; + simplecadapi_version: Token; + ocp_version: Token; + ocp_bindings_version: Token; + python_abi: Token; + platform_tag: Token; + toolchain_hash: Hash; + profile: "scene-1.0-ocp-glb-1" | "scene-1.0-ocp-glb-2"; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "modelSource". + */ +export interface ModelSource { + kind: "model"; + graph_id: ProductId; + model_schema_version: "2.0"; + artifact_hash: Hash; + embedded_artifact_uri?: "model/model.json"; + embedded_artifact_byte_length?: SafeInteger; + /** + * @maxItems 25000 + */ + source_files?: SourceFile[]; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "sourceFile". + */ +export interface SourceFile { + path: string; + uri: Uri; + media_type: "text/x-python; charset=utf-8"; + byte_length: SafeInteger; + content_hash: Hash; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "importedSource". + */ +export interface ImportedSource { + kind: "imported"; + format: Token; + artifact_hash: Hash; + embedded_artifact_uri?: "source/source.bin"; + embedded_artifact_byte_length?: SafeInteger; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "manualSource". + */ +export interface ManualSource { + kind: "manual"; + source_id: LogicalId; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "presentationSource". + */ +export interface PresentationSource { + presentation_id: LogicalId; + schema_version: "1.0"; + artifact_hash: Hash; + embedded_artifact_uri?: "presentation/presentation.json"; + embedded_artifact_byte_length?: SafeInteger; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "coordinateSystem". + */ +export interface CoordinateSystem { + length_unit: "mm"; + handedness: "right"; + up_axis: "+Z"; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "compileOptions". + */ +export interface CompileOptions { + linear_tolerance: number; + angular_tolerance: number; + embed_source: boolean; + embed_presentation: boolean; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "productModelSource". + */ +export interface ProductModelSource { + kind: "product_model"; + root_id: LogicalId; + semantic_type: "Part" | "Assembly"; + semantic_id: ProductId; + graph_id: ProductId; + node_id: ProductId; + output_slot: SafeInteger; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "productManualSource". + */ +export interface ProductManualSource { + kind: "product_manual"; + root_id: LogicalId; + semantic_type: "Part" | "Assembly"; + semantic_id: ProductId; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "modelOutputSource". + */ +export interface ModelOutputSource { + kind: "model_output"; + root_id: LogicalId; + graph_id: ProductId; + node_id: ProductId; + output_slot: SafeInteger; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "importedDefinitionSource". + */ +export interface ImportedDefinitionSource { + kind: "imported"; + root_id: LogicalId; + source_element_id: string; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "manualDefinitionSource". + */ +export interface ManualDefinitionSource { + kind: "manual"; + root_id: LogicalId; + source_id: LogicalId; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "node". + */ +export interface Node { + node_id: StructuralId; + parent_node_id: StructuralId | null; + order: SafeInteger; + definition_id: StructuralId; + name: string | null; + transform: Transform; + visible: boolean; + selectable: boolean; + appearance_override_id: StructuralId | null; + source: ProductOccurrenceSource | ShapeRootSource; + sdk_metadata: { + [k: string]: unknown; + }; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "transform". + */ +export interface Transform { + origin: Vec3; + x_axis: Vec3; + y_axis: Vec3; + z_axis: Vec3; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "productOccurrenceSource". + */ +export interface ProductOccurrenceSource { + kind: "product_occurrence"; + root_id: LogicalId; + component_path: ProductId[]; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "shapeRootSource". + */ +export interface ShapeRootSource { + kind: "shape_root"; + root_id: LogicalId; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "geometryAsset". + */ +export interface GeometryAsset { + asset_id: Hash; + uri: Uri; + media_type: "model/gltf-binary"; + byte_length: SafeInteger; + content_hash: Hash; + scene_local_bounds: Bounds; + /** + * @minItems 16 + * @maxItems 16 + */ + asset_to_scene: [1000, 0, 0, 0, 0, 0, -1000, 0, 0, 1000, 0, 0, 0, 0, 0, 1]; + tessellation: { + linear_tolerance: PositiveNumber; + angular_tolerance: PositiveNumber; + }; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "bounds". + */ +export interface Bounds { + min: Vec3; + max: Vec3; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "edgeAsset". + */ +export interface EdgeAsset { + asset_id: Hash; + uri: Uri; + media_type: "model/gltf-binary"; + byte_length: SafeInteger; + content_hash: Hash; + scene_local_bounds: Bounds; + /** + * @minItems 16 + * @maxItems 16 + */ + asset_to_scene: [1000, 0, 0, 0, 0, 0, -1000, 0, 0, 1000, 0, 0, 0, 0, 0, 1]; + tessellation: { + linear_tolerance: PositiveNumber; + }; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "appearance". + */ +export interface Appearance { + appearance_id: string; + name: string | null; + source: null | ProductMaterialSource | PresentationAppearanceSource; + base_color: Color; + metallic: number; + roughness: number; + alpha_mode: "opaque"; + double_sided: boolean; + edge_color: Color; + sdk_metadata: { + [k: string]: unknown; + }; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "productMaterialSource". + */ +export interface ProductMaterialSource { + kind: "product_material"; + root_id: LogicalId; + material_id: ProductId; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "presentationAppearanceSource". + */ +export interface PresentationAppearanceSource { + kind: "presentation"; + presentation_id: LogicalId; + appearance_name: string; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "entityAsset". + */ +export interface EntityAsset { + entity_asset_id: Hash; + uri: Uri; + media_type: "application/vnd.simplecad.entities+json"; + byte_length: SafeInteger; + content_hash: Hash; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "connectorTarget". + */ +export interface ConnectorTarget { + entity_asset_id: Hash; + entity_id: string; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "forwardedFrom". + */ +export interface ForwardedFrom { + source_component_id: ProductId; + source_definition_id: StructuralId; + source_connector_id: ProductId; + source_connector_snapshot_id: StructuralId; + offset: null | Transform; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "modelOperationSource". + */ +export interface ModelOperationSource { + kind: "model_operation"; + graph_id: ProductId; + node_id: ProductId; + output_slot: SafeInteger; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "manualConnectorSource". + */ +export interface ManualConnectorSource { + kind: "manual"; + source_id: LogicalId; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "perspectiveCamera". + */ +export interface PerspectiveCamera { + camera_id: StructuralId; + name: string; + projection: "perspective"; + parent_node_id: null | StructuralId; + transform: Transform; + near: PositiveNumber; + far: PositiveNumber; + vertical_fov_degrees: number; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "orthographicCamera". + */ +export interface OrthographicCamera { + camera_id: StructuralId; + name: string; + projection: "orthographic"; + parent_node_id: null | StructuralId; + transform: Transform; + near: PositiveNumber; + far: PositiveNumber; + vertical_span: PositiveNumber; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "assetBase". + */ +export interface AssetBase { + asset_id?: Hash; + uri?: Uri; + media_type?: "model/gltf-binary"; + byte_length?: SafeInteger; + content_hash?: Hash; + scene_local_bounds?: Bounds; + /** + * @minItems 16 + * @maxItems 16 + */ + asset_to_scene?: [1000, 0, 0, 0, 0, 0, -1000, 0, 0, 1000, 0, 0, 0, 0, 0, 1]; + [k: string]: unknown; +} +/** + * This interface was referenced by `SceneDocument`'s JSON-Schema + * via the `definition` "cameraBase". + */ +export interface CameraBase { + camera_id?: StructuralId; + name?: string; + parent_node_id?: null | StructuralId; + transform?: Transform; + near?: PositiveNumber; + far?: PositiveNumber; + [k: string]: unknown; +} diff --git a/scene-contract/src/glb.ts b/scene-contract/src/glb.ts new file mode 100644 index 00000000..b9a5677d --- /dev/null +++ b/scene-contract/src/glb.ts @@ -0,0 +1,348 @@ +import { canonicalJsonBytes, parseStrictJson } from "./canonical.js"; +import { BASE_LIMITS, type SceneResourceLimits } from "./resources.js"; + +export type GlbKind = "triangle" | "line"; + +export interface GlbInfo { + kind: GlbKind; + vertexCount: number; + indexCount: number; + primitiveCount: number; + decodedBufferBytes: number; + positionBounds: readonly [readonly [number, number, number], readonly [number, number, number]]; +} + +const maxSafeInteger = 9_007_199_254_740_991; + +function record(value: unknown, context: string): Record { + if (value === null || typeof value !== "object" || Array.isArray(value)) { + throw new Error(`${context} must be an object`); + } + return value as Record; +} + +function requireKeys(value: unknown, expected: readonly string[], context: string): Record { + const result = record(value, context); + const keys = Object.keys(result).sort(); + if (keys.length !== expected.length || keys.some((key, index) => key !== [...expected].sort()[index])) { + throw new Error(`${context} fields do not match closed GLB profile`); + } + return result; +} + +function integer(value: unknown, context: string): number { + if (!Number.isSafeInteger(value) || typeof value !== "number" || value < 0 || value > maxSafeInteger) { + throw new Error(`${context} must be a non-negative safe integer`); + } + return value; +} + +function vec3(value: unknown, context: string): [number, number, number] { + if ( + !Array.isArray(value) || + value.length !== 3 || + value.some((component) => typeof component !== "number") + ) { + throw new Error(`${context} must be a three-number array`); + } + if (!value.every(Number.isFinite)) throw new Error(`${context} must contain finite values`); + return value as [number, number, number]; +} + +export function profileF32Bits(value: number): number { + if (typeof value !== "number" || !Number.isFinite(value)) throw new Error("f32 input must be a finite number"); + const converted = Math.fround(value); + if (!Number.isFinite(converted)) throw new Error("f32 conversion overflowed"); + const bytes = Buffer.allocUnsafe(4); + bytes.writeFloatLE(converted, 0); + const bits = bytes.readUInt32LE(); + return bits === 0x80000000 ? 0 : bits; +} + +export function profileF32(value: number): number { + const bytes = Buffer.allocUnsafe(4); + bytes.writeUInt32LE(profileF32Bits(value)); + return bytes.readFloatLE(); +} + +export function profileCross( + left: readonly [number, number, number], + right: readonly [number, number, number], +): [number, number, number] { + const a = vec3(left, "cross left"); + const b = vec3(right, "cross right"); + const p1x = a[1] * b[2]; + const p2x = a[2] * b[1]; + const p1y = a[2] * b[0]; + const p2y = a[0] * b[2]; + const p1z = a[0] * b[1]; + const p2z = a[1] * b[0]; + const result: [number, number, number] = [p1x - p2x, p1y - p2y, p1z - p2z]; + if (!result.every(Number.isFinite)) throw new Error("cross product produced a non-finite value"); + return result; +} + +export function profileNormalize(value: readonly [number, number, number]): [number, number, number] { + const vector = vec3(value, "normalize input"); + let squared = vector[0] * vector[0] + vector[1] * vector[1]; + squared += vector[2] * vector[2]; + if (!Number.isFinite(squared) || squared <= 0) throw new Error("normalize input has zero or non-finite length"); + const length = Math.sqrt(squared); + const result: [number, number, number] = vector.map((component) => profileF32(component / length)) as [number, number, number]; + let normSquared = result[0] * result[0] + result[1] * result[1]; + normSquared += result[2] * result[2]; + const norm = Math.sqrt(normSquared); + if (norm < 1 - 1e-6 || norm > 1 + 1e-6) throw new Error("normalized binary32 vector is outside the profile tolerance"); + return result; +} + +function array(value: unknown, context: string): unknown[] { + if (!Array.isArray(value)) throw new Error(`${context} must be an array`); + return value; +} + +function equalArray(left: readonly unknown[], right: readonly unknown[]): boolean { + return left.length === right.length && left.every((value, index) => value === right[index]); +} + +function tupleCompare(left: readonly number[], right: readonly number[]): number { + for (let index = 0; index < left.length; index += 1) { + if (left[index] !== right[index]) return left[index] - right[index]; + } + return 0; +} + +export function preflightGlbCounts( + kind: GlbKind, + vertexCountInput: number, + indexCountInput: number, + limits: SceneResourceLimits = BASE_LIMITS, +): number { + const vertexCount = integer(vertexCountInput, "POSITION count"); + const vertexLimit = kind === "triangle" + ? limits.triangle_vertices_per_asset + : limits.line_vertices_per_asset; + if (vertexCount === 0 || vertexCount > vertexLimit) { + throw new Error("GLB vertex count is empty or exceeds resource limit"); + } + const indexCount = integer(indexCountInput, "index count"); + const divisor = kind === "triangle" ? 3 : 2; + const primitiveCount = indexCount / divisor; + const primitiveLimit = kind === "triangle" + ? limits.triangles_per_asset + : limits.line_segments_per_asset; + if (indexCount === 0 || indexCount % divisor !== 0 || primitiveCount > primitiveLimit) { + throw new Error("GLB index count is invalid or exceeds resource limit"); + } + return primitiveCount; +} + +export function preflightGlb( + data: Uint8Array, + expectedKind?: GlbKind, + limits: SceneResourceLimits = BASE_LIMITS, +): GlbInfo { + if (data.byteLength > limits.one_member_bytes) throw new Error("GLB exceeds resource limit"); + const raw = Buffer.from(data); + if (raw.length < 28) throw new Error("truncated GLB"); + if (raw.readUInt32LE(0) !== 0x46546c67 || raw.readUInt32LE(4) !== 2 || raw.readUInt32LE(8) !== raw.length) { + throw new Error("invalid GLB header"); + } + const jsonLength = raw.readUInt32LE(12); + if (raw.readUInt32LE(16) !== 0x4e4f534a || jsonLength % 4 !== 0) { + throw new Error("invalid GLB JSON chunk header"); + } + const jsonEnd = 20 + jsonLength; + if (jsonEnd + 8 > raw.length) throw new Error("truncated GLB JSON chunk"); + const paddedJson = raw.subarray(20, jsonEnd); + let unpaddedLength = paddedJson.length; + while (unpaddedLength > 0 && paddedJson[unpaddedLength - 1] === 0x20) unpaddedLength -= 1; + const jsonBytes = paddedJson.subarray(0, unpaddedLength); + const expectedPadding = (4 - (jsonBytes.length % 4)) % 4; + if ( + paddedJson.length !== jsonBytes.length + expectedPadding || + paddedJson.subarray(jsonBytes.length).some((byte) => byte !== 0x20) + ) { + throw new Error("GLB JSON padding must use the minimal ASCII-space suffix"); + } + const document = parseStrictJson(jsonBytes); + if (document === null || typeof document !== "object" || Array.isArray(document) || !Buffer.from(jsonBytes).equals(canonicalJsonBytes(document))) { + throw new Error("GLB JSON chunk must be RFC 8785 canonical"); + } + const binLength = raw.readUInt32LE(jsonEnd); + if (raw.readUInt32LE(jsonEnd + 4) !== 0x004e4942 || binLength % 4 !== 0 || jsonEnd + 8 + binLength !== raw.length) { + throw new Error("invalid GLB BIN chunk header"); + } + const binData = raw.subarray(jsonEnd + 8); + const root = requireKeys( + document, + ["accessors", "asset", "bufferViews", "buffers", "meshes", "nodes", "scene", "scenes"], + "GLB root", + ); + const asset = root.asset; + if (JSON.stringify(asset) !== JSON.stringify({ generator: "SimpleCAD Scene GLB Profile 1", version: "2.0" })) { + throw new Error("GLB asset record does not match Scene profile"); + } + const nodes = array(root.nodes, "GLB nodes"); + const scenes = array(root.scenes, "GLB scenes"); + let skeletonValid = integer(root.scene, "GLB default scene") === 0 && nodes.length === 1 && scenes.length === 1; + if (skeletonValid) { + const node = requireKeys(nodes[0], ["mesh"], "GLB node"); + const scene = requireKeys(scenes[0], ["nodes"], "GLB scene"); + skeletonValid = integer(node.mesh, "GLB node mesh") === 0 && Array.isArray(scene.nodes) && equalArray(scene.nodes, [0]); + if (Array.isArray(scene.nodes) && scene.nodes.some((item) => !Number.isSafeInteger(item) || typeof item !== "number")) { + skeletonValid = false; + } + } + if (!skeletonValid) throw new Error("GLB scene/node skeleton does not match Scene profile"); + + const meshes = array(root.meshes, "GLB meshes"); + if (meshes.length !== 1) throw new Error("GLB must contain exactly one mesh"); + const mesh = requireKeys(meshes[0], ["primitives"], "GLB mesh"); + const primitives = array(mesh.primitives, "GLB primitives"); + if (primitives.length !== 1) throw new Error("GLB must contain exactly one primitive"); + const primitive = requireKeys(primitives[0], ["attributes", "indices", "mode"], "GLB primitive"); + const accessors = array(root.accessors, "GLB accessors"); + const views = array(root.bufferViews, "GLB bufferViews"); + const buffers = array(root.buffers, "GLB buffers"); + if (buffers.length !== 1) throw new Error("GLB accessors/bufferViews/buffer skeleton is invalid"); + const buffer = requireKeys(buffers[0], ["byteLength"], "GLB buffer"); + const bufferByteLength = integer(buffer.byteLength, "GLB buffer byteLength"); + const attributesRecord = record(primitive.attributes, "GLB primitive attributes"); + const attributes = Object.fromEntries( + Object.entries(attributesRecord).map(([name, value]) => [name, integer(value, `GLB ${name} attribute accessor`)]), + ); + const primitiveIndices = integer(primitive.indices, "GLB primitive index accessor"); + const primitiveMode = integer(primitive.mode, "GLB primitive mode"); + let kind: GlbKind; + let accessorCount: number; + let indexView: number; + if (JSON.stringify(attributes) === JSON.stringify({ NORMAL: 1, POSITION: 0 }) && primitiveIndices === 2 && primitiveMode === 4) { + kind = "triangle"; + accessorCount = 3; + indexView = 2; + } else if (JSON.stringify(attributes) === JSON.stringify({ POSITION: 0 }) && primitiveIndices === 1 && primitiveMode === 1) { + kind = "line"; + accessorCount = 2; + indexView = 1; + } else { + throw new Error("GLB primitive does not match triangle or line profile"); + } + if (expectedKind !== undefined && kind !== expectedKind) throw new Error(`expected ${expectedKind} GLB, got ${kind}`); + if (accessors.length !== accessorCount || views.length !== accessorCount) { + throw new Error("GLB accessor/bufferView count mismatch"); + } + + const position = requireKeys(accessors[0], ["bufferView", "componentType", "count", "max", "min", "type"], "POSITION accessor"); + const vertexCount = integer(position.count, "POSITION count"); + if (integer(position.bufferView, "POSITION bufferView") !== 0 || integer(position.componentType, "POSITION componentType") !== 5126 || position.type !== "VEC3") { + throw new Error("invalid POSITION accessor"); + } + const minimum = vec3(position.min, "POSITION min"); + const maximum = vec3(position.max, "POSITION max"); + if (minimum.some((value, index) => value > maximum[index])) throw new Error("POSITION min exceeds max"); + + if (kind === "triangle") { + const normal = requireKeys(accessors[1], ["bufferView", "componentType", "count", "type"], "NORMAL accessor"); + if (integer(normal.bufferView, "NORMAL bufferView") !== 1 || integer(normal.componentType, "NORMAL componentType") !== 5126 || integer(normal.count, "NORMAL count") !== vertexCount || normal.type !== "VEC3") { + throw new Error("invalid NORMAL accessor"); + } + } + const indexAccessor = requireKeys(accessors[indexView], ["bufferView", "componentType", "count", "type"], "index accessor"); + const indexCount = integer(indexAccessor.count, "index count"); + const primitiveCount = preflightGlbCounts(kind, vertexCount, indexCount, limits); + const componentType = vertexCount <= 65536 ? 5123 : 5125; + if (integer(indexAccessor.bufferView, "index bufferView") !== indexView || integer(indexAccessor.componentType, "index componentType") !== componentType || indexAccessor.type !== "SCALAR") { + throw new Error("invalid GLB index accessor"); + } + + let expectedOffset = 0; + const parsedViews: Record[] = []; + for (let viewIndex = 0; viewIndex < views.length; viewIndex += 1) { + const view = requireKeys(views[viewIndex], ["buffer", "byteLength", "byteOffset", "target"], `bufferView[${viewIndex}]`); + parsedViews.push(view); + const offset = integer(view.byteOffset, `bufferView[${viewIndex}].byteOffset`); + const length = integer(view.byteLength, `bufferView[${viewIndex}].byteLength`); + if (integer(view.buffer, `bufferView[${viewIndex}].buffer`) !== 0 || offset !== expectedOffset) throw new Error("GLB bufferView offset mismatch"); + if (integer(view.target, `bufferView[${viewIndex}].target`) !== (viewIndex < indexView ? 34962 : 34963)) throw new Error("GLB bufferView target mismatch"); + const expectedLength = viewIndex < indexView ? 12 * vertexCount : indexCount * (componentType === 5123 ? 2 : 4); + if (length !== expectedLength) throw new Error("GLB bufferView byteLength mismatch"); + expectedOffset = (expectedOffset + expectedLength + 3) & ~3; + } + const lastView = parsedViews.at(-1)!; + const unpaddedBinLength = integer(lastView.byteOffset, "last bufferView byteOffset") + integer(lastView.byteLength, "last bufferView byteLength"); + if (bufferByteLength !== unpaddedBinLength) throw new Error("GLB buffer byteLength mismatch"); + if (binLength !== ((unpaddedBinLength + 3) & ~3)) throw new Error("GLB BIN chunk length mismatch"); + if (binData.subarray(unpaddedBinLength).some((byte) => byte !== 0)) throw new Error("GLB BIN padding must be zero"); + + const positions: [number, number, number][] = []; + for (let index = 0; index < vertexCount; index += 1) { + const offset = index * 12; + const point: [number, number, number] = [binData.readFloatLE(offset), binData.readFloatLE(offset + 4), binData.readFloatLE(offset + 8)]; + if (!point.every(Number.isFinite)) throw new Error("GLB POSITION contains non-finite values"); + if ([0, 4, 8].some((delta) => binData.readUInt32LE(offset + delta) === 0x80000000)) throw new Error("GLB float buffers must encode zero with positive sign"); + positions.push(point); + } + const actualMin: [number, number, number] = [...positions[0]]; + const actualMax: [number, number, number] = [...positions[0]]; + for (const point of positions) { + for (let axis = 0; axis < 3; axis += 1) { + actualMin[axis] = Math.min(actualMin[axis], point[axis]); + actualMax[axis] = Math.max(actualMax[axis], point[axis]); + } + } + if (!equalArray(minimum, actualMin) || !equalArray(maximum, actualMax)) throw new Error("POSITION accessor bounds do not match buffer"); + + if (kind === "triangle") { + const normalOffset = integer(parsedViews[1].byteOffset, "NORMAL byteOffset"); + for (let index = 0; index < vertexCount; index += 1) { + const offset = normalOffset + index * 12; + const normal = [binData.readFloatLE(offset), binData.readFloatLE(offset + 4), binData.readFloatLE(offset + 8)]; + if ([0, 4, 8].some((delta) => binData.readUInt32LE(offset + delta) === 0x80000000)) throw new Error("GLB float buffers must encode zero with positive sign"); + const norm = Math.sqrt(normal.reduce((sum, component) => sum + component * component, 0)); + if (!normal.every(Number.isFinite) || norm < 1 - 1e-6 || norm > 1 + 1e-6) throw new Error("GLB NORMAL must be finite and normalized"); + } + } + const indices: number[] = []; + const indexOffset = integer(parsedViews[indexView].byteOffset, "index byteOffset"); + for (let index = 0; index < indexCount; index += 1) { + indices.push(componentType === 5123 ? binData.readUInt16LE(indexOffset + index * 2) : binData.readUInt32LE(indexOffset + index * 4)); + } + let maximumIndex = -1; + for (const index of indices) maximumIndex = Math.max(maximumIndex, index); + if (maximumIndex >= vertexCount || new Set(indices).size !== vertexCount) throw new Error("GLB indices must be in range and reference every vertex"); + if (kind === "triangle") { + const triangles: number[][] = []; + for (let index = 0; index < indexCount; index += 3) { + const triple = indices.slice(index, index + 3); + const rotations = [triple, [triple[1], triple[2], triple[0]], [triple[2], triple[0], triple[1]]].sort(tupleCompare); + if (!equalArray(triple, rotations[0])) throw new Error("GLB triangle indices are not in canonical cyclic rotation"); + const [a, b, c] = triple.map((item) => positions[item]); + const ab = b.map((value, axis) => value - a[axis]); + const ac = c.map((value, axis) => value - a[axis]); + const cross = [ab[1] * ac[2] - ab[2] * ac[1], ab[2] * ac[0] - ab[0] * ac[2], ab[0] * ac[1] - ab[1] * ac[0]]; + if (equalArray(a, b) || equalArray(b, c) || equalArray(a, c) || cross.every((value) => value === 0)) throw new Error("GLB contains a collapsed triangle"); + triangles.push(triple); + } + const sorted = [...triangles].sort(tupleCompare); + if (triangles.some((triple, index) => !equalArray(triple, sorted[index]))) throw new Error("GLB triangle records are not canonically sorted"); + } else { + const segments: number[][] = []; + for (let index = 0; index < indexCount; index += 2) { + const pair = indices.slice(index, index + 2); + if (pair[0] >= pair[1]) throw new Error("GLB line indices are not in canonical endpoint order"); + if (equalArray(positions[pair[0]], positions[pair[1]])) throw new Error("GLB contains a collapsed line segment"); + segments.push(pair); + } + const sortedUnique = [...new Map(segments.map((pair) => [pair.join(","), pair])).values()].sort(tupleCompare); + if (segments.length !== sortedUnique.length || segments.some((pair, index) => !equalArray(pair, sortedUnique[index]))) throw new Error("GLB line records are not sorted and unique"); + } + return { + kind, + vertexCount, + indexCount, + primitiveCount, + decodedBufferBytes: 2 * parsedViews.reduce((sum, view) => sum + integer(view.byteLength, "bufferView byteLength"), 0), + positionBounds: [minimum, maximum], + }; +} diff --git a/scene-contract/src/index.ts b/scene-contract/src/index.ts new file mode 100644 index 00000000..092bbcf6 --- /dev/null +++ b/scene-contract/src/index.ts @@ -0,0 +1,7 @@ +export * from "./canonical.js"; +export * from "./documents.js"; +export * from "./glb.js"; +export * from "./report.js"; +export * from "./resources.js"; +export * from "./validation.js"; +export * from "./zip.js"; diff --git a/scene-contract/src/report.ts b/scene-contract/src/report.ts new file mode 100644 index 00000000..ec7f5a68 --- /dev/null +++ b/scene-contract/src/report.ts @@ -0,0 +1,154 @@ +import { readFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { Ajv2020 } from "ajv/dist/2020.js"; +import { parseStrictJson } from "./canonical.js"; + +export type ValidationPhase = "parse" | "structure" | "semantic" | "package" | "budget"; +export type ValidationArtifact = "scene" | "entities" | "presentation" | "connector_binding" | "normalized_product" | "package" | "glb" | "zip"; + +export interface ValidationRule { + readonly id: string; + readonly phase: ValidationPhase; + readonly precedence: number; + readonly artifacts: readonly ValidationArtifact[]; + readonly pointer_policy: "exact" | "nearest_record" | "root"; + readonly summary: string; +} + +interface ValidationRuleRegistry { + readonly schema_version: "1.0"; + readonly registry_id: "scene-1.0-rules"; + readonly phases: readonly ValidationPhase[]; + readonly rules: readonly ValidationRule[]; +} + +export interface ValidationIssue { + severity: "error"; + code: string; + path: string; + message: string; + phase: ValidationPhase; +} + +export interface ValidationReport { + valid: boolean; + issues: readonly ValidationIssue[]; + firstError: ValidationIssue | null; +} + +const phaseOrder: Record = { + parse: 0, + structure: 1, + semantic: 2, + package: 3, + budget: 4, +}; + +function utf8Compare(left: string, right: string): number { + return Buffer.compare(Buffer.from(left, "utf8"), Buffer.from(right, "utf8")); +} + +const contractRoot = resolve( + dirname(fileURLToPath(import.meta.url)), + "../../../src/simplecadapi/scene/contracts", +); +const ruleSchema = parseStrictJson(readFileSync(resolve(contractRoot, "schemas/rules-1.schema.json"))); +const validateRuleSchema = new Ajv2020({ strict: true, allErrors: true }).compile(ruleSchema as object); + +export function validateRuleRegistry(value: unknown): ReadonlyMap { + if (!validateRuleSchema(value)) { + const errors = [...(validateRuleSchema.errors ?? [])].sort( + (left, right) => utf8Compare(left.instancePath, right.instancePath) || + utf8Compare(left.message ?? "", right.message ?? ""), + ); + const first = errors[0]; + throw new Error(`invalid scene rule registry at ${first?.instancePath ?? ""}: ${first?.message ?? "schema validation failed"}`); + } + + const registry = value as ValidationRuleRegistry; + const registryPhaseOrder = new Map(registry.phases.map((phase, index) => [phase, index])); + const byId = new Map(); + const phasePrecedence = new Set(); + for (const rule of registry.rules) { + if (byId.has(rule.id)) throw new Error(`invalid scene rule registry: duplicate rule ID ${JSON.stringify(rule.id)}`); + const precedenceKey = `${rule.phase}\0${rule.precedence}`; + if (phasePrecedence.has(precedenceKey)) { + throw new Error(`invalid scene rule registry: duplicate precedence ${rule.precedence} in phase ${JSON.stringify(rule.phase)}`); + } + byId.set(rule.id, rule); + phasePrecedence.add(precedenceKey); + } + const expected = [...registry.rules].sort( + (left, right) => + registryPhaseOrder.get(left.phase)! - registryPhaseOrder.get(right.phase)! || + left.precedence - right.precedence, + ); + if (registry.rules.some((rule, index) => rule !== expected[index])) { + throw new Error("invalid scene rule registry: rules must be ordered by phase and precedence"); + } + for (const phase of registry.phases) { + const phaseRules = registry.rules.filter((rule) => rule.phase === phase); + const ids = phaseRules.map((rule) => rule.id); + const expectedIds = [...ids].sort(utf8Compare); + if (ids.some((id, index) => id !== expectedIds[index])) { + throw new Error(`invalid scene rule registry: precedence in phase ${JSON.stringify(phase)} must match unsigned UTF-8 rule-ID order`); + } + } + return byId; +} + +const rules = validateRuleRegistry( + parseStrictJson(readFileSync(resolve(contractRoot, "rules/scene-1.0-rules.json"))), +); + +export function hasRootPointerPolicy(code: string): boolean { + return rules.get(code)?.pointer_policy === "root"; +} + +export function issue( + code: string, + path: string, + message: string, + phase: ValidationPhase = "semantic", +): ValidationIssue { + return { severity: "error", code, path, message, phase }; +} + +export function report(input: Iterable, artifact?: ValidationArtifact): ValidationReport { + const unique = new Map(); + for (const item of input) { + if (artifact !== undefined) { + const rule = rules.get(item.code); + if (rule === undefined) throw new Error(`unregistered scene validation issue code: ${JSON.stringify(item.code)}`); + if (item.phase !== rule.phase) { + throw new Error(`scene validation issue ${JSON.stringify(item.code)} has phase ${JSON.stringify(item.phase)}; registered phase is ${JSON.stringify(rule.phase)}`); + } + if (!rule.artifacts.includes(artifact)) { + throw new Error(`scene validation issue ${JSON.stringify(item.code)} does not apply to artifact ${JSON.stringify(artifact)}`); + } + if (rule.pointer_policy === "root" && item.path !== "") { + throw new Error(`scene validation issue ${JSON.stringify(item.code)} requires the root pointer`); + } + } + const key = artifact === undefined + ? `${item.phase}\0${item.code}\0${item.path}` + : `${item.phase}\0${item.code}\0${item.path}\0${item.message}`; + if (!unique.has(key)) unique.set(key, item); + } + const issues = [...unique.values()].sort( + (left, right) => + phaseOrder[left.phase] - phaseOrder[right.phase] || + (artifact === undefined + ? utf8Compare(left.code, right.code) + : rules.get(left.code)!.precedence - rules.get(right.code)!.precedence) || + utf8Compare(left.path, right.path) || + utf8Compare(left.message, right.message), + ); + return { valid: issues.length === 0, issues, firstError: issues[0] ?? null }; +} + +export function pointer(parts: readonly (string | number)[]): string { + if (parts.length === 0) return ""; + return `/${parts.map((part) => String(part).replaceAll("~", "~0").replaceAll("/", "~1")).join("/")}`; +} diff --git a/scene-contract/src/resources.ts b/scene-contract/src/resources.ts new file mode 100644 index 00000000..27d73fbf --- /dev/null +++ b/scene-contract/src/resources.ts @@ -0,0 +1,76 @@ +export const BASE_LIMITS = { + zip_members: 50_000, + input_archive_bytes: 256 * 1024 * 1024, + canonical_archive_bytes: 256 * 1024 * 1024, + total_uncompressed_bytes: 1024 * 1024 * 1024, + one_member_bytes: 256 * 1024 * 1024, + scene_json_bytes: 32 * 1024 * 1024, + entity_json_bytes: 64 * 1024 * 1024, + model_json_bytes: 64 * 1024 * 1024, + presentation_json_bytes: 8 * 1024 * 1024, + compression_ratio: 100, + json_depth: 64, + json_string_bytes: 1024 * 1024, + uri_bytes: 1024, + structural_id_bytes: 4096, + definitions: 25_000, + nodes: 100_000, + assets_per_kind: 25_000, + appearances: 25_000, + connectors: 100_000, + cameras: 1000, + hierarchy_depth: 256, + forwarded_connector_depth: 64, + entities_per_sidecar: 500_000, + entities_total: 2_000_000, + triangle_vertices_per_asset: 2_000_000, + triangle_vertices_total: 10_000_000, + triangles_per_asset: 2_000_000, + triangles_total: 10_000_000, + line_vertices_per_asset: 2_000_000, + line_vertices_total: 10_000_000, + line_segments_per_asset: 2_000_000, + line_segments_total: 10_000_000, + static_decoded_buffer_bytes: 512 * 1024 * 1024, +} as const; + +export type SceneResourceLimits = { readonly [Name in keyof typeof BASE_LIMITS]: number }; +export type SceneResourceLimitName = keyof typeof BASE_LIMITS; + +export function preflightInputArchiveSize(size: number, limits: SceneResourceLimits = BASE_LIMITS): number { + if (!Number.isSafeInteger(size) || size < 0) throw new Error("invalid input archive size"); + if (size > limits.input_archive_bytes) throw new Error("input archive exceeds resource limit"); + return size; +} + +export function preflightResourceCount( + count: number, + limitName: SceneResourceLimitName, + limits: SceneResourceLimits = BASE_LIMITS, +): number { + if (!Number.isSafeInteger(count) || count < 0) throw new Error("invalid resource count"); + if (count > limits[limitName]) throw new Error(`${limitName} exceeds resource limit`); + return count; +} + +export function preflightAggregateCompressionRatio( + uncompressedSize: number, + archiveSize: number, + limits: SceneResourceLimits = BASE_LIMITS, +): void { + if (!Number.isSafeInteger(uncompressedSize) || uncompressedSize < 0 || !Number.isSafeInteger(archiveSize) || archiveSize <= 0) { + throw new Error("invalid compression ratio sizes"); + } + if (uncompressedSize > limits.compression_ratio * archiveSize) throw new Error("aggregate compression ratio exceeds limit"); +} + +export function preflightMemberCompressionRatio( + uncompressedSize: number, + compressedSize: number, + limits: SceneResourceLimits = BASE_LIMITS, +): void { + if (!Number.isSafeInteger(uncompressedSize) || uncompressedSize < 0 || !Number.isSafeInteger(compressedSize) || compressedSize < 0) { + throw new Error("invalid compression ratio sizes"); + } + if (uncompressedSize > limits.compression_ratio * Math.max(1, compressedSize)) throw new Error("member compression ratio exceeds limit"); +} diff --git a/scene-contract/src/schema.ts b/scene-contract/src/schema.ts new file mode 100644 index 00000000..80532fc8 --- /dev/null +++ b/scene-contract/src/schema.ts @@ -0,0 +1,103 @@ +import { readFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { Ajv2020, type ErrorObject, type ValidateFunction } from "ajv/dist/2020.js"; +import { parseStrictJson } from "./canonical.js"; + +const contractRoot = resolve( + dirname(fileURLToPath(import.meta.url)), + "../../../src/simplecadapi/scene/contracts/schemas", +); + +const ajv = new Ajv2020({ strict: true, allErrors: true }); + +function declareRequiredProperties(value: unknown): void { + if (value === null || typeof value !== "object") return; + const schema = value as Record; + if ( + schema.type === undefined && + (schema.properties !== undefined || schema.required !== undefined) + ) { + schema.type = "object"; + } + if (Array.isArray(schema.required) && schema.required.every((item) => typeof item === "string")) { + const properties = + schema.properties !== null && typeof schema.properties === "object" && !Array.isArray(schema.properties) + ? (schema.properties as Record) + : {}; + for (const name of schema.required) properties[name] ??= {}; + schema.properties = properties; + } + for (const key of ["properties", "$defs", "patternProperties", "dependentSchemas"]) { + const schemas = schema[key]; + if (schemas !== null && typeof schemas === "object" && !Array.isArray(schemas)) { + Object.values(schemas).forEach(declareRequiredProperties); + } + } + for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"]) { + const schemas = schema[key]; + if (Array.isArray(schemas)) schemas.forEach(declareRequiredProperties); + } + for (const key of [ + "not", + "if", + "then", + "else", + "items", + "contains", + "additionalProperties", + "unevaluatedProperties", + "propertyNames", + ]) { + declareRequiredProperties(schema[key]); + } +} + +function load(name: string): ValidateFunction { + const schema = parseStrictJson(readFileSync(resolve(contractRoot, name))); + // Ajv strictRequired expects declarations in the same nested subschema. The + // contract uses valid required-only guards, so add behavior-neutral schemas. + declareRequiredProperties(schema); + return ajv.compile(schema as object); +} + +export type SchemaArtifact = "scene" | "entities" | "presentation" | "connector_binding" | "normalized_product"; + +const schemaFiles: Record = { + scene: "scene-1.0.schema.json", + entities: "entities-1.0.schema.json", + presentation: "presentation-1.0.schema.json", + connector_binding: "connector-binding-1.0.schema.json", + normalized_product: "normalized-product-1.schema.json", +}; +const schemaDocuments = Object.fromEntries( + Object.entries(schemaFiles).map(([artifact, name]) => [artifact, parseStrictJson(readFileSync(resolve(contractRoot, name)))]), +) as Record>; +const pointerValidators = new Map(); + +export function validateSchemaPointer(artifact: SchemaArtifact, schemaPointer: string, value: unknown): boolean { + const key = `${artifact}:${schemaPointer}`; + let validate = pointerValidators.get(key); + if (validate === undefined) { + const root = structuredClone(schemaDocuments[artifact]); + delete root.$id; + const wrapper = schemaPointer === "#" + ? root + : { $schema: root.$schema, $ref: schemaPointer, $defs: root.$defs }; + declareRequiredProperties(wrapper); + validate = ajv.compile(wrapper); + pointerValidators.set(key, validate); + } + return Boolean(validate(value)); +} + +export const validateSceneSchema = load("scene-1.0.schema.json"); +export const validateEntitiesSchema = load("entities-1.0.schema.json"); +export const validatePresentationSchema = load("presentation-1.0.schema.json"); +export const validateConnectorBindingSchema = load("connector-binding-1.0.schema.json"); +export const validateNormalizedProductSchema = load("normalized-product-1.schema.json"); + +export function schemaErrors(validate: ValidateFunction, value: unknown): ErrorObject[] { + validate(value); + return validate.errors === null || validate.errors === undefined ? [] : [...validate.errors]; +} diff --git a/scene-contract/src/transforms.ts b/scene-contract/src/transforms.ts new file mode 100644 index 00000000..975d6dba --- /dev/null +++ b/scene-contract/src/transforms.ts @@ -0,0 +1,35 @@ +/** Deterministic rigid-transform primitives used by Scene validation. */ + +type JsonRecord = Record; + +export function composeRigidTransforms(left: JsonRecord, right: JsonRecord): JsonRecord { + const origin = left.origin as number[]; + const xAxis = left.x_axis as number[]; + const yAxis = left.y_axis as number[]; + const zAxis = left.z_axis as number[]; + const rotate = (vector: number[]): number[] => [0, 1, 2].map((index) => + (xAxis[index] * vector[0] + yAxis[index] * vector[1]) + zAxis[index] * vector[2] + ); + const rotatedOrigin = rotate(right.origin as number[]); + return { + origin: origin.map((component, index) => component + rotatedOrigin[index]), + x_axis: rotate(right.x_axis as number[]), + y_axis: rotate(right.y_axis as number[]), + z_axis: rotate(right.z_axis as number[]), + }; +} + +export function rigidTransformsEqual(actual: JsonRecord, expected: JsonRecord): boolean { + const actualOrigin = actual.origin as number[]; + const expectedOrigin = expected.origin as number[]; + const originEpsilon = Math.max( + 1e-9, + 1e-12 * Math.max(1, ...actualOrigin.map(Math.abs), ...expectedOrigin.map(Math.abs)), + ); + return actualOrigin.every((component, index) => Math.abs(component - expectedOrigin[index]) <= originEpsilon) && + ["x_axis", "y_axis", "z_axis"].every((key) => + (actual[key] as number[]).every((component, index) => + Math.abs(component - (expected[key] as number[])[index]) <= 1e-12 + ) + ); +} diff --git a/scene-contract/src/validation.ts b/scene-contract/src/validation.ts new file mode 100644 index 00000000..058f7471 --- /dev/null +++ b/scene-contract/src/validation.ts @@ -0,0 +1,1746 @@ +import { + canonicalJsonBytes, + computeSceneRevision, + DuplicateKeyError, + parseCanonicalJson, + parseStrictJson, + sha256, +} from "./canonical.js"; +import { type GlbInfo, preflightGlb } from "./glb.js"; +import { hasRootPointerPolicy, issue, pointer, report, type ValidationArtifact, type ValidationIssue, type ValidationReport } from "./report.js"; +import { BASE_LIMITS, preflightResourceCount, type SceneResourceLimits } from "./resources.js"; +import { composeRigidTransforms, rigidTransformsEqual } from "./transforms.js"; +import type { ValidateFunction } from "ajv"; +import { + schemaErrors, + validateConnectorBindingSchema, + validateEntitiesSchema, + validateNormalizedProductSchema, + validatePresentationSchema, + validateSceneSchema, +} from "./schema.js"; + +type JsonRecord = Record; +type DocumentArtifact = Exclude; + +const collectionSortKeys: Record = { + definitions: "definition_id", + nodes: "node_id", + geometry_assets: "asset_id", + edge_assets: "asset_id", + entity_assets: "entity_asset_id", + appearances: "appearance_id", + connectors: "connector_snapshot_id", + cameras: "camera_id", + entities: "entity_id", +}; +const setArrayKeys = new Set(["semantic_binding_ids", "evaluated_tags", "parent_entity_ids", "child_entity_ids"]); +const identifierArrayKeys = new Set([ + "child_entity_ids", + "component_path", + "evaluated_tags", + "grounded_component_ids", + "parent_entity_ids", + "semantic_binding_ids", +]); +const sourcePathPattern = /^[A-Za-z0-9][A-Za-z0-9._/-]*\.py$/; +const operationSourceKeys = new Set([ + "assignment_targets", + "call_text", + "callsite_id", + "column", + "end_column", + "end_line", + "line", + "path", + "path_kind", + "schema_version", +]); + +function isRecord(value: unknown): value is JsonRecord { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function utf8Compare(left: string, right: string): number { + return Buffer.compare(Buffer.from(left, "utf8"), Buffer.from(right, "utf8")); +} + +function parseInput(value: unknown, canonical: boolean): { value?: unknown; issues: ValidationIssue[] } { + if (!(typeof value === "string" || value instanceof Uint8Array)) return { value, issues: [] }; + try { + return { value: canonical ? parseCanonicalJson(value) : parseStrictJson(value), issues: [] }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + let code: string; + if (error instanceof DuplicateKeyError) code = "duplicate_json_key"; + else if (message.includes("BOM")) code = "bom_forbidden"; + else if (error instanceof TypeError && (message.toLowerCase().includes("utf") || message.includes("surrogate"))) code = "invalid_utf8"; + else if (message.includes("nesting")) code = "resource_limit_exceeded"; + else if (message.includes("canonical") && canonical) code = "noncanonical_json"; + else if (message.includes("finite") || message.includes("NaN") || message.includes("Infinity")) code = "nonfinite_json_number"; + else code = "schema_invalid"; + const phase = code === "resource_limit_exceeded" ? "budget" : code === "schema_invalid" ? "structure" : "parse"; + return { issues: [issue(code, "", message, phase)] }; + } +} + +function structuralIssues(value: unknown, validator: ValidateFunction): ValidationIssue[] { + return schemaErrors(validator, value).map((error) => + issue( + "schema_invalid", + error.instancePath, + error.keyword === "additionalProperties" ? "unknown field is forbidden by the closed schema" : error.message ?? "schema validation failed", + "structure", + ), + ); +} + +function walk(value: unknown): [readonly (string | number)[], unknown][] { + const result: [readonly (string | number)[], unknown][] = []; + const stack: [readonly (string | number)[], unknown][] = [[[], value]]; + while (stack.length > 0) { + const current = stack.pop()!; + result.push(current); + const [path, child] = current; + if (Array.isArray(child)) { + for (let index = child.length - 1; index >= 0; index -= 1) stack.push([[...path, index], child[index]]); + } else if (isRecord(child)) { + const entries = Object.entries(child); + for (let index = entries.length - 1; index >= 0; index -= 1) stack.push([[...path, entries[index][0]], entries[index][1]]); + } + } + return result; +} + +function hasUnpairedSurrogate(value: string): boolean { + for (let index = 0; index < value.length; index += 1) { + const unit = value.charCodeAt(index); + if (unit >= 0xd800 && unit <= 0xdbff) { + const next = value.charCodeAt(index + 1); + if (next < 0xdc00 || next > 0xdfff) return true; + index += 1; + } else if (unit >= 0xdc00 && unit <= 0xdfff) { + return true; + } + } + return false; +} + +function isMetadataPath(path: readonly (string | number)[]): boolean { + return path.some((part) => part === "metadata" || part === "sdk_metadata"); +} + +function isIdentifierPath(path: readonly (string | number)[]): boolean { + if (path.length === 0) return false; + const field = path.at(-1); + if (typeof field === "string" && (field.endsWith("_id") || ["definition_ref", "source_element_id", "topo_id"].includes(field))) { + return true; + } + return path.length >= 2 && typeof field === "number" && typeof path.at(-2) === "string" && identifierArrayKeys.has(path.at(-2) as string); +} + +function isUriPath(path: readonly (string | number)[]): boolean { + const field = path.at(-1); + return typeof field === "string" && (field === "uri" || field.endsWith("_uri")); +} + +function serializedSize(value: unknown): number | null { + if (typeof value === "string") return Buffer.byteLength(value, "utf8"); + if (value instanceof Uint8Array) return value.byteLength; + try { + return canonicalJsonBytes(value).byteLength; + } catch { + return null; + } +} + +function serializedSizeIssues(value: unknown, artifact: ValidationArtifact, limits: SceneResourceLimits): ValidationIssue[] { + const size = serializedSize(value); + const limit = artifact === "scene" + ? limits.scene_json_bytes + : artifact === "entities" + ? limits.entity_json_bytes + : artifact === "presentation" + ? limits.presentation_json_bytes + : limits.one_member_bytes; + return size !== null && size > limit + ? [issue("resource_limit_exceeded", "", `${artifact} JSON bytes exceed resource limit`, "budget")] + : []; +} + +export function jsonResourceIssues(value: unknown, limits: SceneResourceLimits = BASE_LIMITS): ValidationIssue[] { + const issues: ValidationIssue[] = []; + for (const [path, child] of walk(value)) { + const jsonPointer = pointer(path); + if (path.length > limits.json_depth) { + issues.push(issue("resource_limit_exceeded", jsonPointer, "JSON nesting exceeds resource limit", "budget")); + } + if (isRecord(child)) { + for (const key of Object.keys(child)) { + const keyPointer = pointer([...path, key]); + if (hasUnpairedSurrogate(key)) { + issues.push(issue("invalid_utf8", keyPointer, "object key contains an unpaired surrogate", "parse")); + continue; + } + const keyBytes = Buffer.byteLength(key, "utf8"); + if (keyBytes > limits.json_string_bytes) { + issues.push(issue("resource_limit_exceeded", keyPointer, "JSON object key exceeds resource limit", "budget")); + } + if (isMetadataPath(path) && keyBytes > limits.structural_id_bytes) { + issues.push(issue("resource_limit_exceeded", keyPointer, "metadata key exceeds structural ID resource limit", "budget")); + } + } + } + if (typeof child === "number") { + if (!Number.isFinite(child)) { + issues.push(issue("nonfinite_json_number", jsonPointer, "JSON number must be finite", "parse")); + } + } else if (typeof child === "string") { + if (hasUnpairedSurrogate(child)) { + issues.push(issue("invalid_utf8", jsonPointer, "string contains an unpaired surrogate", "parse")); + } else { + const bytes = Buffer.byteLength(child, "utf8"); + if (bytes > limits.json_string_bytes) { + issues.push(issue("resource_limit_exceeded", jsonPointer, "JSON string exceeds resource limit", "budget")); + } + if (isUriPath(path) && bytes > limits.uri_bytes) { + issues.push(issue("resource_limit_exceeded", jsonPointer, "URI exceeds resource limit", "budget")); + } + if (isIdentifierPath(path) && bytes > limits.structural_id_bytes) { + issues.push(issue("resource_limit_exceeded", jsonPointer, "identifier exceeds structural ID resource limit", "budget")); + } + } + } + } + return issues; +} + +export function resourceCountIssues( + value: unknown, + artifact: DocumentArtifact, + limits: SceneResourceLimits = BASE_LIMITS, +): ValidationIssue[] { + if (!isRecord(value)) return []; + const issues: ValidationIssue[] = []; + let collections: readonly (readonly [string, keyof SceneResourceLimits])[] = []; + if (artifact === "scene") { + collections = [ + ["definitions", "definitions"], ["nodes", "nodes"], + ["geometry_assets", "assets_per_kind"], ["edge_assets", "assets_per_kind"], ["entity_assets", "assets_per_kind"], + ["appearances", "appearances"], ["connectors", "connectors"], ["cameras", "cameras"], + ]; + } else if (artifact === "entities") { + collections = [ + ["entities", "entities_per_sidecar"], + ["face_groups", "entities_per_sidecar"], + ["edge_groups", "entities_per_sidecar"], + ]; + } else if (artifact === "presentation") { + collections = [["node_overrides", "nodes"], ["appearances", "appearances"], ["cameras", "cameras"]]; + } + for (const [field, limitName] of collections) { + const records = value[field]; + if (Array.isArray(records)) { + try { + preflightResourceCount(records.length, limitName, limits); + } catch { + issues.push(issue("resource_limit_exceeded", `/${field}`, `${field} count exceeds resource limit`, "budget")); + } + } + } + if (artifact === "scene") { + const nodes = Array.isArray(value.nodes) ? value.nodes : []; + nodes.forEach((node, index) => { + const source = isRecord(node) && isRecord(node.source) ? node.source : null; + if (source !== null && Array.isArray(source.component_path) && source.component_path.length > limits.hierarchy_depth) { + issues.push(issue("resource_limit_exceeded", `/nodes/${index}/source/component_path`, "hierarchy depth exceeds resource limit", "budget")); + } + }); + const connectors = Array.isArray(value.connectors) ? value.connectors.filter(isRecord) : []; + const forwardEdges = new Map(); + for (const connector of connectors) { + if (connector.anchor_kind === "forwarded" && isRecord(connector.forwarded_from)) { + forwardEdges.set(connector.connector_snapshot_id, connector.forwarded_from.source_connector_snapshot_id); + } + } + for (const start of forwardEdges.keys()) { + const seen = new Set(); + let current: unknown = start; + let depth = 0; + while (forwardEdges.has(current) && !seen.has(current)) { + seen.add(current); + current = forwardEdges.get(current); + depth += 1; + if (depth > limits.forwarded_connector_depth) { + issues.push(issue("resource_limit_exceeded", "/connectors", "forwarded connector depth exceeds resource limit", "budget")); + break; + } + } + } + } + return issues; +} + +function arrayOrderIssues(value: JsonRecord): ValidationIssue[] { + const issues: ValidationIssue[] = []; + for (const [path, child] of walk(value)) { + const key = path.at(-1); + if (typeof key === "string" && setArrayKeys.has(key) && Array.isArray(child) && child.every((item) => typeof item === "string")) { + const expected = [...new Set(child)].sort(utf8Compare); + if (child.length !== expected.length || child.some((item, index) => item !== expected[index])) { + issues.push(issue("array_order_invalid", pointer(path), "set-like array is not sorted and unique")); + } + } + } + for (const [collection, idKey] of Object.entries(collectionSortKeys)) { + const records = value[collection]; + if (Array.isArray(records) && records.every((item) => isRecord(item) && typeof item[idKey] === "string")) { + const ids = records.map((item) => (item as JsonRecord)[idKey] as string); + const expected = [...new Set(ids)].sort(utf8Compare); + if (ids.length !== expected.length || ids.some((id, index) => id !== expected[index])) { + issues.push(issue("array_order_invalid", `/${collection}`, `${collection} is not sorted and unique by ${idKey}`)); + } + } + } + return issues; +} + +function vec3(value: unknown): value is [number, number, number] { + return Array.isArray(value) && value.length === 3 && value.every((item) => typeof item === "number" && Number.isFinite(item)); +} + +function transformIssue(value: unknown, path: string): ValidationIssue | null { + if (!isRecord(value) || !vec3(value.origin) || !vec3(value.x_axis) || !vec3(value.y_axis) || !vec3(value.z_axis)) return null; + const origin = value.origin; + const axes = [value.x_axis, value.y_axis, value.z_axis]; + if (origin.some((component) => Math.abs(component) > 1e12)) return issue("transform_invalid", path, "transform origin exceeds the scene coordinate limit"); + const dot = (left: readonly number[], right: readonly number[]) => left.reduce((sum, item, index) => sum + item * right[index], 0); + if (axes.some((axis) => Math.abs(Math.sqrt(dot(axis, axis)) - 1) > 1e-12)) return issue("transform_invalid", path, "transform axes must be unit vectors within 1e-12"); + if (Math.abs(dot(axes[0], axes[1])) > 1e-12 || Math.abs(dot(axes[0], axes[2])) > 1e-12 || Math.abs(dot(axes[1], axes[2])) > 1e-12) return issue("transform_invalid", path, "transform axes must be pairwise orthogonal within 1e-12"); + const cross = [axes[0][1] * axes[1][2] - axes[0][2] * axes[1][1], axes[0][2] * axes[1][0] - axes[0][0] * axes[1][2], axes[0][0] * axes[1][1] - axes[0][1] * axes[1][0]]; + if (cross.some((component, index) => Math.abs(component - axes[2][index]) > 1e-12)) return issue("transform_invalid", path, "z_axis must equal cross(x_axis, y_axis) within 1e-12"); + return null; +} + +function analyticIssues(geometry: unknown, path: string): ValidationIssue[] { + if (!isRecord(geometry)) return []; + const directionFields: Record = { + line: ["direction"], circle: ["normal", "x_direction"], ellipse: ["normal", "x_direction"], + plane: ["normal", "x_direction"], cylinder: ["axis", "x_direction"], cone: ["axis", "x_direction"], + sphere: ["axis", "x_direction"], torus: ["axis", "x_direction"], + }; + const coordinateFields: Record = { + point: ["position"], line: ["origin"], circle: ["center"], ellipse: ["center"], + plane: ["origin"], cylinder: ["origin"], cone: ["origin"], sphere: ["center"], + torus: ["center"], + }; + const type = typeof geometry.type === "string" ? geometry.type : ""; + const names = directionFields[type] ?? []; + const issues: ValidationIssue[] = []; + for (const name of coordinateFields[type] ?? []) { + const coordinate = geometry[name]; + if (vec3(coordinate) && coordinate.some((component) => Math.abs(component) > 1e12)) { + issues.push(issue("analytic_geometry_invalid", `${path}/${name}`, "analytic coordinate exceeds the scene coordinate limit")); + } + } + if (!names.every((name) => vec3(geometry[name]))) return issues; + const vectors = names.map((name) => geometry[name] as [number, number, number]); + vectors.forEach((vector, index) => { + const norm = Math.sqrt(vector.reduce((sum, component) => sum + component * component, 0)); + if (Math.abs(norm - 1) > 1e-12) issues.push(issue("analytic_geometry_invalid", `${path}/${names[index]}`, "analytic direction must be a unit vector within 1e-12")); + }); + if (vectors.length === 2 && Math.abs(vectors[0].reduce((sum, component, index) => sum + component * vectors[1][index], 0)) > 1e-12) { + issues.push(issue("analytic_geometry_invalid", path, "analytic axis and x_direction must be orthogonal within 1e-12")); + } + return issues; +} + +function boundsIssues(bounds: unknown, path: string, point?: unknown): ValidationIssue[] { + if (!isRecord(bounds) || !vec3(bounds.min) || !vec3(bounds.max)) return []; + const minimum = bounds.min; + const maximum = bounds.max; + const issues: ValidationIssue[] = []; + if (minimum.some((low, index) => low > maximum[index])) { + issues.push(issue("bounds_invalid", path, "bounds min exceeds max")); + } + if ([...minimum, ...maximum].some((component) => Math.abs(component) > 1e12)) { + issues.push(issue("bounds_invalid", path, "bounds exceed the scene coordinate limit")); + } + if (vec3(point)) { + const maxAbs = Math.max(1, ...minimum.map(Math.abs), ...maximum.map(Math.abs), ...point.map(Math.abs)); + const epsilon = Math.max(1e-9, 1e-12 * maxAbs); + if (point.some((value, index) => value < minimum[index] - epsilon || value > maximum[index] + epsilon)) { + issues.push(issue("bounds_invalid", path, "point or centroid is outside bounds")); + } + } + return issues; +} + +function encodeSegment(value: string): string { + let result = ""; + for (const byte of Buffer.from(value, "utf8")) { + const safe = + (byte >= 0x41 && byte <= 0x5a) || + (byte >= 0x61 && byte <= 0x7a) || + (byte >= 0x30 && byte <= 0x39) || + byte === 0x2d || byte === 0x2e || byte === 0x5f || byte === 0x7e; + result += safe ? String.fromCharCode(byte) : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`; + } + return result; +} + +function rootIdFromDefinition(definition: JsonRecord): unknown { + return isRecord(definition.source) ? definition.source.root_id : undefined; +} + +function setsEqual(left: ReadonlySet, right: ReadonlySet): boolean { + return left.size === right.size && [...left].every((value) => right.has(value)); +} + +function sceneSemanticIssues(scene: JsonRecord): ValidationIssue[] { + const issues: ValidationIssue[] = []; + if (scene.revision !== computeSceneRevision(scene)) issues.push(issue("revision_mismatch", "/revision", "scene revision does not match canonical draft hash")); + const source = isRecord(scene.source) ? scene.source : {}; + const sourceKind = source.kind; + const graphId = source.graph_id; + const sourceId = source.source_id; + const options = isRecord(scene.compile_options) ? scene.compile_options : {}; + const presentationSource = scene.presentation_source; + const embedSource = options.embed_source; + const embedded = Object.hasOwn(source, "embedded_artifact_uri"); + if (sourceKind === "manual" && (embedSource === true || embedded)) { + issues.push(issue("source_matrix_invalid", "/source", "manual source cannot be embedded")); + } else if ((sourceKind === "model" || sourceKind === "imported") && embedSource !== embedded) { + issues.push(issue("source_matrix_invalid", "/source", "embed_source does not match source embedding fields")); + } + const sourceFiles = Array.isArray(source.source_files) ? source.source_files.filter(isRecord) : []; + const sourcePaths = sourceFiles.map((record) => String(record.path ?? "")); + const expectedSourcePaths = [...new Set(sourcePaths)].sort(utf8Compare); + if (sourcePaths.some((path, index) => path !== expectedSourcePaths[index]) || sourcePaths.length !== expectedSourcePaths.length) { + issues.push(issue("array_order_invalid", "/source/source_files", "source_files is not sorted and unique by path")); + } + const casefoldSourcePaths = new Map(); + sourceFiles.forEach((record, index) => { + if (typeof record.path === "string") { + const segments = record.path.split("/"); + if (!sourcePathPattern.test(record.path) || segments.some((segment) => segment === "" || segment === "." || segment === "..")) { + issues.push(issue("source_matrix_invalid", `/source/source_files/${index}/path`, "source file path is not archive-safe")); + } + const folded = record.path.toLowerCase(); + const previous = casefoldSourcePaths.get(folded); + if (previous !== undefined && previous !== record.path) { + issues.push(issue("source_matrix_invalid", `/source/source_files/${index}/path`, "source file paths collide case-insensitively")); + } else { + casefoldSourcePaths.set(folded, record.path); + } + if (record.uri !== `sources/${record.path}`) { + issues.push(issue("source_matrix_invalid", `/source/source_files/${index}/uri`, "source file URI does not preserve the project-relative path")); + } + } + }); + const embedPresentation = options.embed_presentation; + if ((presentationSource === null || presentationSource === undefined) && embedPresentation === true) { + issues.push(issue("source_matrix_invalid", "/compile_options/embed_presentation", "presentation embedding requires presentation_source")); + } + if ( + isRecord(presentationSource) && + embedPresentation !== Object.hasOwn(presentationSource, "embedded_artifact_uri") + ) { + issues.push(issue("source_matrix_invalid", "/presentation_source", "embed_presentation does not match presentation embedding fields")); + } + + const definitions = Array.isArray(scene.definitions) ? scene.definitions.filter(isRecord) : []; + const nodes = Array.isArray(scene.nodes) ? scene.nodes.filter(isRecord) : []; + const appearances = Array.isArray(scene.appearances) ? scene.appearances.filter(isRecord) : []; + const definitionMap = new Map(definitions.map((record) => [record.definition_id, record])); + const nodeMap = new Map(nodes.map((record) => [record.node_id, record])); + const appearanceMap = new Map(appearances.map((record) => [record.appearance_id, record])); + const geometryMap = new Map((Array.isArray(scene.geometry_assets) ? scene.geometry_assets : []).filter(isRecord).map((record) => [record.asset_id, record])); + const edgeMap = new Map((Array.isArray(scene.edge_assets) ? scene.edge_assets : []).filter(isRecord).map((record) => [record.asset_id, record])); + const entityMap = new Map((Array.isArray(scene.entity_assets) ? scene.entity_assets : []).filter(isRecord).map((record) => [record.entity_asset_id, record])); + const validSources: Record> = { + model: { part: "product_model", assembly: "product_model", shape: "model_output" }, + manual: { part: "product_manual", assembly: "product_manual", shape: "manual" }, + imported: { shape: "imported" }, + }; + definitions.forEach((definition, index) => { + const path = `/definitions/${index}`; + const kind = definition.kind; + const nested = isRecord(definition.source) ? definition.source : {}; + const nestedKind = nested.kind; + const rootId = nested.root_id; + const validSource = typeof sourceKind === "string" && typeof kind === "string" + ? validSources[sourceKind]?.[kind] + : undefined; + if (nestedKind !== validSource) { + issues.push(issue("source_matrix_invalid", `${path}/source`, "definition source is incompatible with scene and definition kinds")); + } + if ((nestedKind === "product_model" || nestedKind === "model_output") && nested.graph_id !== graphId) { + issues.push(issue("source_matrix_invalid", `${path}/source/graph_id`, "definition graph_id differs from scene graph_id")); + } + if (nestedKind === "manual" && nested.source_id !== sourceId) { + issues.push(issue("source_matrix_invalid", `${path}/source/source_id`, "definition manual source_id differs from scene source_id")); + } + let expectedId: string; + if (nestedKind === "product_model" || nestedKind === "product_manual") { + const expectedSemantic = kind === "part" ? "Part" : "Assembly"; + if (nested.semantic_type !== expectedSemantic) { + issues.push(issue("source_matrix_invalid", `${path}/source/semantic_type`, "semantic_type differs from definition kind")); + } + expectedId = `definition/${String(rootId)}/${String(kind)}/${encodeSegment(String(nested.semantic_id ?? ""))}`; + } else if (nestedKind === "model_output") { + expectedId = `definition/${String(rootId)}/shape/model/${encodeSegment(String(nested.graph_id ?? ""))}/${encodeSegment(String(nested.node_id ?? ""))}/${String(nested.output_slot)}`; + } else if (nestedKind === "imported") { + expectedId = `definition/${String(rootId)}/shape/imported/${encodeSegment(String(nested.source_element_id ?? ""))}`; + } else { + expectedId = `definition/${String(rootId)}/shape/manual/${encodeSegment(String(nested.source_id ?? ""))}`; + } + if (definition.definition_id !== expectedId) { + issues.push(issue("source_matrix_invalid", `${path}/definition_id`, "definition_id does not match its source-derived structural ID")); + } + for (const [field, registry] of [ + ["geometry_asset_id", geometryMap], + ["edge_asset_id", edgeMap], + ["entity_asset_id", entityMap], + ["appearance_id", appearanceMap], + ] as const) { + const reference = definition[field]; + if (reference !== null && reference !== undefined && !registry.has(reference)) { + issues.push(issue("reference_missing", `${path}/${field}`, `referenced ${field} does not exist`)); + } + } + }); + + const roots: JsonRecord[] = []; + const siblingOrders = new Map(); + const referencedDefinitions = new Set(); + nodes.forEach((node, index) => { + const path = `/nodes/${index}`; + const definition = definitionMap.get(node.definition_id); + if (definition === undefined) { + issues.push(issue("reference_missing", `${path}/definition_id`, "node definition does not exist")); + return; + } + referencedDefinitions.add(node.definition_id); + const nodeSource = isRecord(node.source) ? node.source : {}; + const nodeKind = nodeSource.kind; + const rootId = nodeSource.root_id; + const expectedNodeKind = definition.kind === "part" || definition.kind === "assembly" ? "product_occurrence" : "shape_root"; + if (nodeKind !== expectedNodeKind || rootId !== rootIdFromDefinition(definition)) { + issues.push(issue("source_matrix_invalid", `${path}/source`, "node source kind/root does not match definition")); + } + let expectedNodeId: string; + let expectedParent: string | null; + if (nodeKind === "product_occurrence") { + const componentPath = Array.isArray(nodeSource.component_path) ? nodeSource.component_path : []; + const encodedPath = componentPath.map((segment) => `/${encodeSegment(String(segment))}`).join(""); + const encodedParentPath = componentPath.slice(0, -1).map((segment) => `/${encodeSegment(String(segment))}`).join(""); + expectedNodeId = `instance/${String(rootId)}${encodedPath}`; + expectedParent = componentPath.length === 0 ? null : `instance/${String(rootId)}${encodedParentPath}`; + } else { + expectedNodeId = `instance/${String(rootId)}`; + expectedParent = null; + } + if (node.node_id !== expectedNodeId) { + issues.push(issue("hierarchy_invalid", `${path}/node_id`, "node_id does not match source-derived structural ID")); + } + if (node.parent_node_id !== expectedParent) { + issues.push(issue("hierarchy_invalid", `${path}/parent_node_id`, "parent_node_id does not match component path")); + } + if (node.parent_node_id === null) roots.push(node); + else if (!nodeMap.has(node.parent_node_id)) { + issues.push(issue("reference_missing", `${path}/parent_node_id`, "parent node does not exist")); + } + const orders = siblingOrders.get(node.parent_node_id) ?? []; + orders.push(node.order); + siblingOrders.set(node.parent_node_id, orders); + const override = node.appearance_override_id; + if (node.selectable !== true) { + issues.push(issue("source_matrix_invalid", `${path}/selectable`, "node selectability must use the deterministic true default")); + } + if (presentationSource === null || presentationSource === undefined) { + if (node.visible !== true) { + issues.push(issue("source_matrix_invalid", `${path}/visible`, "node visibility requires presentation_source")); + } + if (override !== null && override !== undefined) { + issues.push(issue("source_matrix_invalid", `${path}/appearance_override_id`, "appearance override requires presentation_source")); + } + } + if (override !== null && override !== undefined && !appearanceMap.has(override)) { + issues.push(issue("reference_missing", `${path}/appearance_override_id`, "appearance override does not exist")); + } + if (definition.kind === "assembly" && override !== null && override !== undefined) { + issues.push(issue("source_matrix_invalid", `${path}/appearance_override_id`, "assembly occurrence cannot carry appearance override")); + } + const transform = transformIssue(node.transform, `${path}/transform`); + if (transform !== null) issues.push(transform); + }); + for (const [parent, orders] of siblingOrders) { + if ( + orders.every((order) => typeof order === "number" && Number.isInteger(order)) && + [...orders].sort((left, right) => (left as number) - (right as number)).some((order, index) => order !== index) + ) { + issues.push(issue("hierarchy_invalid", "/nodes", `sibling order under ${String(parent)} is not continuous`)); + } + } + const rootIds = roots.map((root) => isRecord(root.source) ? root.source.root_id : undefined); + const expectedRoots = [...rootIds].sort((left, right) => utf8Compare(String(left), String(right))); + const actualRoots = [...roots] + .sort((left, right) => (left.order as number) - (right.order as number)) + .map((root) => isRecord(root.source) ? root.source.root_id : undefined); + if (actualRoots.some((rootId, index) => rootId !== expectedRoots[index])) { + issues.push(issue("hierarchy_invalid", "/nodes", "root order does not match unsigned UTF-8 root_id order")); + } + const definitionIds = new Set(definitionMap.keys()); + if (definitionIds.size > 0 || nodeMap.size > 0) { + if (!setsEqual(referencedDefinitions, definitionIds)) { + issues.push(issue("hierarchy_invalid", "/nodes", "every definition must be instantiated by at least one node")); + } + const definitionRootIds = new Set([...definitionMap.values()].map(rootIdFromDefinition)); + if ([...definitionRootIds].some((rootId) => roots.filter((root) => isRecord(root.source) && root.source.root_id === rootId).length !== 1)) { + issues.push(issue("hierarchy_invalid", "/nodes", "each definition root_id must have exactly one root occurrence")); + } + } + + const usedAssets = new Set(); + for (const definition of definitions) { + for (const field of ["geometry_asset_id", "edge_asset_id", "entity_asset_id"]) { + const reference = definition[field]; + if (reference !== null && reference !== undefined) usedAssets.add(reference); + } + } + const declaredAssets = new Set([...geometryMap.keys(), ...edgeMap.keys(), ...entityMap.keys()]); + if (!setsEqual(usedAssets, declaredAssets)) { + issues.push(issue("reference_missing", "/definitions", "asset records must be referenced exactly by definitions")); + } + for (const [collection, uriKind] of [["geometry_assets", "geometry"], ["edge_assets", "edges"]] as const) { + const assets = Array.isArray(scene[collection]) ? (scene[collection] as unknown[]).filter(isRecord) : []; + assets.forEach((asset, index) => { + const path = `/${collection}/${index}`; + if (asset.asset_id !== asset.content_hash) { + issues.push(issue("source_matrix_invalid", `${path}/asset_id`, "asset_id must equal content_hash")); + } + const assetId = String(asset.asset_id ?? ""); + const digest = assetId.startsWith("sha256:") ? assetId.slice("sha256:".length) : assetId; + if (asset.uri !== `${uriKind}/sha256-${digest}.glb`) { + issues.push(issue("source_matrix_invalid", `${path}/uri`, "asset URI does not match content hash")); + } + const tessellation = isRecord(asset.tessellation) ? asset.tessellation : {}; + if (tessellation.linear_tolerance !== options.linear_tolerance) { + issues.push(issue("source_matrix_invalid", `${path}/tessellation/linear_tolerance`, "asset tolerance differs from compile options")); + } + if (collection === "geometry_assets" && tessellation.angular_tolerance !== options.angular_tolerance) { + issues.push(issue("source_matrix_invalid", `${path}/tessellation/angular_tolerance`, "asset tolerance differs from compile options")); + } + issues.push(...boundsIssues(asset.scene_local_bounds, `${path}/scene_local_bounds`)); + }); + } + const entityAssets = Array.isArray(scene.entity_assets) ? scene.entity_assets.filter(isRecord) : []; + entityAssets.forEach((asset, index) => { + const path = `/entity_assets/${index}`; + if (asset.entity_asset_id !== asset.content_hash) { + issues.push(issue("source_matrix_invalid", `${path}/entity_asset_id`, "entity_asset_id must equal content_hash")); + } + const assetId = String(asset.entity_asset_id ?? ""); + const digest = assetId.startsWith("sha256:") ? assetId.slice("sha256:".length) : assetId; + if (asset.uri !== `entities/sha256-${digest}.json`) { + issues.push(issue("source_matrix_invalid", `${path}/uri`, "entity URI does not match content hash")); + } + }); + appearances.forEach((appearance, index) => { + const path = `/appearances/${index}`; + const draft = { ...appearance }; + delete draft.appearance_id; + const expected = `appearance/evaluated/${sha256(canonicalJsonBytes(draft)).slice("sha256:".length)}`; + if (appearance.appearance_id !== expected) { + issues.push(issue("source_matrix_invalid", `${path}/appearance_id`, "appearance_id does not match content-derived identity")); + } + const appearanceSource = appearance.source; + if (isRecord(appearanceSource)) { + if (appearanceSource.kind === "product_material" && sourceKind !== "model" && sourceKind !== "manual") { + issues.push(issue("source_matrix_invalid", `${path}/source`, "product material source is incompatible with scene source")); + } + if ( + appearanceSource.kind === "product_material" && + !definitions.some((definition) => + definition.kind === "part" && + definition.appearance_id === appearance.appearance_id && + rootIdFromDefinition(definition) === appearanceSource.root_id + ) + ) { + issues.push(issue("source_matrix_invalid", `${path}/source/root_id`, "product material appearance provenance does not match a Part definition root")); + } + if ( + appearanceSource.kind === "presentation" && + (!isRecord(presentationSource) || appearanceSource.presentation_id !== presentationSource.presentation_id) + ) { + issues.push(issue("source_matrix_invalid", `${path}/source`, "presentation appearance source does not match presentation_source")); + } + } + }); + + const connectors = Array.isArray(scene.connectors) ? scene.connectors.filter(isRecord) : []; + if (sourceKind === "imported" && connectors.length > 0) { + issues.push(issue("source_matrix_invalid", "/connectors", "imported scene connectors must be empty")); + } + const connectorMap = new Map(connectors.map((record) => [record.connector_snapshot_id, record])); + const connectorIdsByOwner = new Map>(); + const forwardEdges = new Map(); + connectors.forEach((connector, index) => { + const path = `/connectors/${index}`; + const owner = definitionMap.get(connector.owner_definition_id); + if (owner === undefined) { + issues.push(issue("reference_missing", `${path}/owner_definition_id`, "connector owner definition does not exist")); + return; + } + const ownerIds = connectorIdsByOwner.get(connector.owner_definition_id) ?? new Set(); + if (ownerIds.has(connector.connector_id)) { + issues.push(issue("id_duplicate", `${path}/connector_id`, "connector_id is duplicated within owner definition")); + } + ownerIds.add(connector.connector_id); + connectorIdsByOwner.set(connector.owner_definition_id, ownerIds); + const ownerSource = isRecord(owner.source) ? owner.source : {}; + const ownerSemantic = ownerSource.semantic_id === undefined || ownerSource.semantic_id === null + ? "None" + : String(ownerSource.semantic_id); + const expectedSnapshot = `connector/${String(ownerSource.root_id)}/${String(owner.kind)}/${encodeSegment(ownerSemantic)}/${encodeSegment(String(connector.connector_id ?? ""))}`; + if (connector.connector_snapshot_id !== expectedSnapshot) { + issues.push(issue("connector_invalid", `${path}/connector_snapshot_id`, "connector snapshot ID does not match owner and connector IDs")); + } + const anchorKind = connector.anchor_kind; + if (anchorKind === "geometry" && owner.kind !== "part") { + issues.push(issue("connector_invalid", `${path}/owner_definition_id`, "geometry connector owner must be a Part")); + } + if (anchorKind === "placement" && owner.kind !== "part" && owner.kind !== "assembly") { + issues.push(issue("connector_invalid", `${path}/owner_definition_id`, "connector owner must be a Product definition")); + } + if (anchorKind === "forwarded" && owner.kind !== "assembly") { + issues.push(issue("connector_invalid", `${path}/owner_definition_id`, "forwarded connector owner must be an Assembly")); + } + const connectorSource = connector.source; + if (sourceKind === "model") { + if (!isRecord(connectorSource) || connectorSource.kind !== "model_operation" || connectorSource.graph_id !== graphId) { + issues.push(issue("connector_invalid", `${path}/source`, "model connector must use the scene graph model_operation source")); + } else if (connectorSource.output_slot !== 0) { + issues.push(issue("connector_invalid", `${path}/source/output_slot`, "connector producer output_slot must be 0")); + } + } else if ( + sourceKind === "manual" && + (!isRecord(connectorSource) || + Object.keys(connectorSource).length !== 2 || + connectorSource.kind !== "manual" || + connectorSource.source_id !== sourceId) + ) { + issues.push(issue("connector_invalid", `${path}/source`, "manual connector source must equal the top-level source_id")); + } + const transform = transformIssue(connector.local_transform, `${path}/local_transform`); + if (transform !== null) issues.push(transform); + if (anchorKind === "forwarded") { + const forwarded = isRecord(connector.forwarded_from) ? connector.forwarded_from : {}; + const sourceSnapshot = forwarded.source_connector_snapshot_id; + const sourceConnector = connectorMap.get(sourceSnapshot); + if ( + sourceConnector === undefined || + sourceConnector.owner_definition_id !== forwarded.source_definition_id || + sourceConnector.connector_id !== forwarded.source_connector_id + ) { + issues.push(issue("connector_invalid", `${path}/forwarded_from`, "forwarded connector source snapshot ownership is invalid")); + } + forwardEdges.set(connector.connector_snapshot_id, sourceSnapshot); + if (forwarded.offset !== null && forwarded.offset !== undefined) { + const offset = transformIssue(forwarded.offset, `${path}/forwarded_from/offset`); + if (offset !== null) issues.push(offset); + } + if (owner.kind === "assembly") { + const ownerNodes = nodes.filter((node) => + node.definition_id === connector.owner_definition_id && + isRecord(node.source) && + node.source.kind === "product_occurrence" + ); + const sourceChildren: JsonRecord[] = []; + for (const ownerNode of ownerNodes) { + const ownerNodeSource = ownerNode.source as JsonRecord; + const expectedPath = [ + ...(Array.isArray(ownerNodeSource.component_path) ? ownerNodeSource.component_path : []), + forwarded.source_component_id, + ]; + const matches = nodes.filter((node) => + isRecord(node.source) && + node.source.kind === "product_occurrence" && + node.source.root_id === ownerNodeSource.root_id && + Array.isArray(node.source.component_path) && + node.source.component_path.length === expectedPath.length && + node.source.component_path.every((component, componentIndex) => component === expectedPath[componentIndex]) && + node.parent_node_id === ownerNode.node_id + ); + if (matches.length !== 1 || matches[0].definition_id !== forwarded.source_definition_id) { + issues.push(issue("connector_invalid", `${path}/forwarded_from`, "forwarded connector source component is not one exact direct child")); + } else { + sourceChildren.push(matches[0]); + } + } + if (sourceChildren.length > 1) { + const expected = canonicalJsonBytes(sourceChildren[0].transform); + if (sourceChildren.slice(1).some((child) => !canonicalJsonBytes(child.transform).equals(expected))) { + issues.push(issue("connector_invalid", `${path}/forwarded_from`, "forwarded connector source child transforms differ between owner occurrences")); + } + } + if (sourceChildren.length > 0 && sourceConnector !== undefined) { + const childTransform = sourceChildren[0].transform; + const sourceTransform = sourceConnector.local_transform; + const offset = forwarded.offset ?? { + origin: [0, 0, 0], + x_axis: [1, 0, 0], + y_axis: [0, 1, 0], + z_axis: [0, 0, 1], + }; + if ( + isRecord(childTransform) && transformIssue(childTransform, "") === null && + isRecord(sourceTransform) && transformIssue(sourceTransform, "") === null && + isRecord(offset) && transformIssue(offset, "") === null && + isRecord(connector.local_transform) && transformIssue(connector.local_transform, "") === null + ) { + const expected = composeRigidTransforms(composeRigidTransforms(childTransform, sourceTransform), offset); + if (!rigidTransformsEqual(connector.local_transform, expected)) { + issues.push(issue("connector_invalid", `${path}/local_transform`, "forwarded connector transform does not match child, source, and offset composition")); + } + } + } + } + } + }); + for (const start of forwardEdges.keys()) { + const seen = new Set(); + let current: unknown = start; + while (forwardEdges.has(current)) { + if (seen.has(current)) { + issues.push(issue("connector_invalid", "/connectors", "forwarded connector graph contains a cycle")); + break; + } + seen.add(current); + current = forwardEdges.get(current); + } + } + const cameras = Array.isArray(scene.cameras) ? scene.cameras.filter(isRecord) : []; + cameras.forEach((camera, index) => { + const path = `/cameras/${index}`; + if (presentationSource === null || presentationSource === undefined) { + issues.push(issue("source_matrix_invalid", path, "evaluated scene camera requires presentation_source")); + } + if (camera.parent_node_id !== null && camera.parent_node_id !== undefined && !nodeMap.has(camera.parent_node_id)) { + issues.push(issue("reference_missing", `${path}/parent_node_id`, "camera parent node does not exist")); + } + if (typeof camera.near === "number" && typeof camera.far === "number" && camera.far <= camera.near) { + issues.push(issue("bounds_invalid", `${path}/far`, "camera far must exceed near")); + } + const transform = transformIssue(camera.transform, `${path}/transform`); + if (transform !== null) issues.push(transform); + }); + return issues; +} + +function entitySemanticIssues(asset: JsonRecord): ValidationIssue[] { + const issues: ValidationIssue[] = []; + const entityValues = Array.isArray(asset.entities) ? asset.entities : []; + const entities = entityValues.filter(isRecord); + const byId = new Map(entities.map((entity) => [entity.entity_id, entity])); + if (byId.size !== entityValues.length) { + issues.push(issue("id_duplicate", "/entities", "entity IDs must be unique")); + } + for (const kind of ["solid", "face", "edge", "vertex"]) { + const actual = new Set( + [...byId.entries()] + .filter(([entityId, entity]) => entity.kind === kind && typeof entityId === "string") + .map(([entityId]) => entityId), + ); + const expected = new Set([...actual].map((_id, index) => `entity/${kind}/${index}`)); + if (!setsEqual(actual, expected)) { + issues.push(issue("entity_topology_invalid", "/entities", `${kind} entity IDs must use dense zero-based ordinals`)); + } + } + const kindGeometry: Record> = { + solid: new Set(["brep_solid"]), + face: new Set(["plane", "cylinder", "cone", "sphere", "torus", "bspline_surface", "other_surface"]), + edge: new Set(["line", "circle", "ellipse", "bspline_curve", "other_curve"]), + vertex: new Set(["point"]), + }; + const expectedPropertyKeys: Record> = { + solid: new Set(["quality", "bounds", "volume", "surface_area", "centroid"]), + face: new Set(["quality", "bounds", "area", "centroid", "orientation"]), + edge: new Set(["quality", "bounds", "length", "centroid"]), + vertex: new Set(["quality", "bounds", "position"]), + }; + entities.forEach((entity, index) => { + const path = `/entities/${index}`; + const entityId = entity.entity_id; + const kind = entity.kind; + if (typeof entityId === "string" && !entityId.startsWith(`entity/${String(kind)}/`)) { + issues.push(issue("entity_topology_invalid", `${path}/entity_id`, "entity ID kind differs from entity kind")); + } + const geometry = isRecord(entity.geometry) ? entity.geometry : {}; + if (typeof kind === "string" && !kindGeometry[kind]?.has(geometry.type)) { + issues.push(issue("entity_topology_invalid", `${path}/geometry/type`, "geometry variant is incompatible with entity kind")); + } + issues.push(...analyticIssues(geometry, `${path}/geometry`)); + const properties = isRecord(entity.properties) ? entity.properties : {}; + if (typeof kind === "string" && !setsEqual(new Set(Object.keys(properties)), expectedPropertyKeys[kind] ?? new Set())) { + issues.push(issue("entity_topology_invalid", `${path}/properties`, "property record is incompatible with entity kind")); + } + const parents = Array.isArray(entity.parent_entity_ids) ? entity.parent_entity_ids : []; + const children = Array.isArray(entity.child_entity_ids) ? entity.child_entity_ids : []; + if ( + kind === "solid" && + (parents.length > 0 || children.length === 0 || children.some((child) => byId.get(child)?.kind !== "face")) + ) { + issues.push(issue("entity_topology_invalid", path, "solid must own one or more faces and have no parent")); + } + if ( + kind === "face" && + (parents.length !== 1 || byId.get(parents[0])?.kind !== "solid" || children.length === 0 || children.some((child) => byId.get(child)?.kind !== "edge")) + ) { + issues.push(issue("entity_topology_invalid", path, "face must have one solid parent and one or more edge children")); + } + if ( + kind === "edge" && + (parents.length === 0 || parents.some((parent) => byId.get(parent)?.kind !== "face") || + (children.length !== 1 && children.length !== 2) || children.some((child) => byId.get(child)?.kind !== "vertex")) + ) { + issues.push(issue("entity_topology_invalid", path, "edge must have face parents and one or two vertex children")); + } + if ( + kind === "vertex" && + (parents.length === 0 || parents.some((parent) => byId.get(parent)?.kind !== "edge") || children.length > 0) + ) { + issues.push(issue("entity_topology_invalid", path, "vertex must have edge parents and no children")); + } + for (const parent of parents) { + const target = byId.get(parent); + if (target === undefined) issues.push(issue("reference_missing", `${path}/parent_entity_ids`, "parent entity does not exist")); + else if (!Array.isArray(target.child_entity_ids) || !target.child_entity_ids.includes(entityId)) issues.push(issue("entity_topology_invalid", `${path}/parent_entity_ids`, "parent relation is not reciprocal")); + } + for (const child of children) { + const target = byId.get(child); + if (target === undefined) issues.push(issue("reference_missing", `${path}/child_entity_ids`, "child entity does not exist")); + else if (!Array.isArray(target.parent_entity_ids) || !target.parent_entity_ids.includes(entityId)) issues.push(issue("entity_topology_invalid", `${path}/child_entity_ids`, "child relation is not reciprocal")); + } + const source = entity.source; + if (isRecord(source) && source.kind === "model_topology") { + const expectedTopologyKind: Record = { solid: "SOLID", face: "FACE", edge: "EDGE", vertex: "VERTEX" }; + if (typeof kind === "string" && source.topology_kind !== expectedTopologyKind[kind]) { + issues.push(issue("source_matrix_invalid", `${path}/source/topology_kind`, "topology source kind differs from entity kind")); + } + } + const frame = entity.sdk_connector_frame; + if (kind === "solid" && frame !== null) { + issues.push(issue("connector_invalid", `${path}/sdk_connector_frame`, "solid connector frame must be null")); + } + if ((kind === "face" || kind === "vertex") && frame === null) { + issues.push(issue("connector_invalid", `${path}/sdk_connector_frame`, "face and vertex connector frames must be present")); + } + if (frame !== null && frame !== undefined) { + const frameIssue = transformIssue(frame, `${path}/sdk_connector_frame`); + if (frameIssue !== null) issues.push(frameIssue); + } + const status = entity.render_status; + if (kind !== "edge" && status !== "rendered") { + issues.push(issue("entity_topology_invalid", `${path}/render_status`, "only edges may be degenerate")); + } + if (kind === "solid" && entity.connector_binding_status !== "not_applicable") { + issues.push(issue("connector_invalid", `${path}/connector_binding_status`, "solid binding status must be not_applicable")); + } + if ( + kind === "edge" && + frame === null && + !new Set(["frame_undefined", "owner_not_part", "source_not_model"]).has(entity.connector_binding_status as string) + ) { + issues.push(issue("connector_invalid", `${path}/connector_binding_status`, "edge without frame cannot be supported")); + } + if (kind === "vertex") { + const point = geometry.position; + if (!equalJson(properties.position, point)) { + issues.push(issue("bounds_invalid", `${path}/properties/position`, "vertex property position differs from geometry point")); + } + issues.push(...boundsIssues(properties.bounds, `${path}/properties/bounds`, point)); + } else { + issues.push(...boundsIssues(properties.bounds, `${path}/properties/bounds`, properties.centroid)); + } + }); + const faceIds = new Set([...byId.entries()].filter(([, entity]) => entity.kind === "face").map(([entityId]) => entityId)); + const renderedEdgeIds = new Set([...byId.entries()].filter(([, entity]) => entity.kind === "edge" && entity.render_status === "rendered").map(([entityId]) => entityId)); + const degenerateEdgeIds = new Set([...byId.entries()].filter(([, entity]) => entity.kind === "edge" && entity.render_status === "degenerate").map(([entityId]) => entityId)); + for (const [groupsKey, expectedIds, divisor] of [["face_groups", faceIds, 3], ["edge_groups", renderedEdgeIds, 2]] as const) { + const groups = Array.isArray(asset[groupsKey]) ? (asset[groupsKey] as unknown[]).filter(isRecord) : []; + const groupIds = groups.map((group) => group.entity_id); + if (!setsEqual(new Set(groupIds), expectedIds) || new Set(groupIds).size !== groupIds.length) { + issues.push(issue("entity_range_invalid", `/${groupsKey}`, `${groupsKey} do not map exactly one group per rendered entity`)); + } + let first = 0; + groups.forEach((group, index) => { + const path = `/${groupsKey}/${index}`; + if (group.group_id !== index || group.first_index !== first) issues.push(issue("entity_range_invalid", path, "group IDs and ranges must be continuous")); + if (typeof group.index_count === "number") { + if (group.index_count <= 0 || group.index_count % divisor !== 0) issues.push(issue("entity_range_invalid", `${path}/index_count`, "group count has invalid primitive cardinality")); + first += group.index_count; + } + }); + } + const edgeGroups = Array.isArray(asset.edge_groups) ? asset.edge_groups.filter(isRecord) : []; + if (edgeGroups.some((group) => degenerateEdgeIds.has(group.entity_id))) { + issues.push(issue("entity_range_invalid", "/edge_groups", "degenerate edges must not have render groups")); + } + return issues; +} + +function presentationSemanticIssues(value: JsonRecord): ValidationIssue[] { + const issues: ValidationIssue[] = []; + const appearances = Array.isArray(value.appearances) ? value.appearances.filter(isRecord) : []; + const appearanceNames = appearances.map((appearance) => appearance.name); + if (new Set(appearanceNames).size !== appearanceNames.length) { + issues.push(issue("id_duplicate", "/appearances", "presentation appearance names must be unique")); + } + const appearanceNameSet = new Set(appearanceNames); + const overrides = Array.isArray(value.node_overrides) ? value.node_overrides.filter(isRecord) : []; + const nodeIds = overrides.map((override) => override.node_id); + if (new Set(nodeIds).size !== nodeIds.length) { + issues.push(issue("id_duplicate", "/node_overrides", "node overrides must target unique node IDs")); + } + overrides.forEach((override, index) => { + if (override.appearance_name !== undefined && !appearanceNameSet.has(override.appearance_name)) { + issues.push(issue("presentation_reference_invalid", `/node_overrides/${index}/appearance_name`, "appearance_name does not exist")); + } + }); + const cameras = Array.isArray(value.cameras) ? value.cameras.filter(isRecord) : []; + const cameraNames = cameras.map((camera) => camera.name); + if (new Set(cameraNames).size !== cameraNames.length) { + issues.push(issue("id_duplicate", "/cameras", "presentation camera names must be unique")); + } + cameras.forEach((camera, index) => { + if (typeof camera.near === "number" && typeof camera.far === "number" && camera.far <= camera.near) { + issues.push(issue("bounds_invalid", `/cameras/${index}/far`, "camera far must exceed near")); + } + const transform = transformIssue(camera.transform, `/cameras/${index}/transform`); + if (transform !== null) issues.push(transform); + }); + return issues; +} + +function connectorBindingSemanticIssues(value: JsonRecord): ValidationIssue[] { + const issues: ValidationIssue[] = []; + const sourceModel = isRecord(value.source_model) ? value.source_model : {}; + const target = isRecord(value.target) ? value.target : {}; + const expectedSource = isRecord(target.expected_source) ? target.expected_source : {}; + if (sourceModel.graph_id !== expectedSource.graph_id) { + issues.push(issue("source_matrix_invalid", "/target/expected_source/graph_id", "target graph differs from source model graph")); + } + if (typeof target.entity_id === "string" && target.entity_id.startsWith("entity/vertex/") && target.flip !== false) { + issues.push(issue("connector_invalid", "/target/flip", "vertex connector target requires flip=false")); + } + return issues; +} + +function normalizedProductSemanticIssues(value: JsonRecord): ValidationIssue[] { + const issues: ValidationIssue[] = []; + const connectors = Array.isArray(value.connectors) ? value.connectors.filter(isRecord) : []; + const connectorIds = connectors.map((connector) => connector.connector_id); + if (new Set(connectorIds).size !== connectorIds.length) { + issues.push(issue("id_duplicate", "/connectors", "connector IDs must be unique")); + } + if (value.kind !== "assembly") return issues; + + const components = Array.isArray(value.components) ? value.components.filter(isRecord) : []; + const componentIds = components.map((component) => component.component_id); + if (new Set(componentIds).size !== componentIds.length) { + issues.push(issue("id_duplicate", "/components", "component IDs must be unique")); + } + const componentSet = new Set(componentIds); + const grounded = Array.isArray(value.grounded_component_ids) ? value.grounded_component_ids : []; + if (grounded.some((componentId) => !componentSet.has(componentId))) { + issues.push(issue("reference_missing", "/grounded_component_ids", "grounded component does not exist")); + } + const constraints = Array.isArray(value.constraints) ? value.constraints.filter(isRecord) : []; + const constraintIds = constraints.map((constraint) => constraint.constraint_id); + if (new Set(constraintIds).size !== constraintIds.length) { + issues.push(issue("id_duplicate", "/constraints", "constraint IDs must be unique")); + } + constraints.forEach((constraint, index) => { + for (const referenceKey of ["connector_a", "connector_b"]) { + const reference = constraint[referenceKey]; + if (isRecord(reference) && !componentSet.has(reference.component_id)) { + issues.push(issue("reference_missing", `/constraints/${index}/${referenceKey}/component_id`, "constraint component does not exist")); + } + } + for (const limitKey of ["distance_limit", "angle_limit"]) { + const limit = constraint[limitKey]; + if ( + isRecord(limit) && + typeof limit.lower_value === "number" && + typeof limit.upper_value === "number" && + limit.lower_value > limit.upper_value + ) { + issues.push(issue("bounds_invalid", `/constraints/${index}/${limitKey}`, "constraint lower limit exceeds upper limit")); + } + } + }); + return issues; +} + +function validateDocument( + value: unknown, + artifact: DocumentArtifact, + validator: ValidateFunction, + semanticIssues: (parsed: JsonRecord) => ValidationIssue[], + checkArrayOrder = false, + limits: SceneResourceLimits = BASE_LIMITS, +): ValidationReport { + const serializedInput = typeof value === "string" || value instanceof Uint8Array; + const parsed = parseInput(value, serializedInput); + if (parsed.value === undefined && parsed.issues.length > 0) return report(parsed.issues, artifact); + const issues = [ + ...serializedSizeIssues(value, artifact, limits), + ...parsed.issues, + ...jsonResourceIssues(parsed.value, limits), + ...resourceCountIssues(parsed.value, artifact, limits), + ]; + if (issues.some((item) => item.code === "resource_limit_exceeded" && item.message.includes("nesting"))) { + return report(issues, artifact); + } + issues.push(...structuralIssues(parsed.value, validator)); + if (isRecord(parsed.value) && !issues.some((item) => item.phase === "parse" || item.phase === "structure")) { + if (checkArrayOrder) issues.push(...arrayOrderIssues(parsed.value)); + issues.push(...semanticIssues(parsed.value)); + } + return report(issues, artifact); +} + +export function validateSceneManifest(value: unknown, limits: SceneResourceLimits = BASE_LIMITS): ValidationReport { + return validateDocument(value, "scene", validateSceneSchema, sceneSemanticIssues, true, limits); +} + +export function validateEntityAsset(value: unknown, limits: SceneResourceLimits = BASE_LIMITS): ValidationReport { + return validateDocument(value, "entities", validateEntitiesSchema, entitySemanticIssues, true, limits); +} + +export function validatePresentation(value: unknown, limits: SceneResourceLimits = BASE_LIMITS): ValidationReport { + return validateDocument(value, "presentation", validatePresentationSchema, presentationSemanticIssues, false, limits); +} + +export function validateConnectorBinding(value: unknown, limits: SceneResourceLimits = BASE_LIMITS): ValidationReport { + return validateDocument(value, "connector_binding", validateConnectorBindingSchema, connectorBindingSemanticIssues, false, limits); +} + +export function validateNormalizedProduct(value: unknown, limits: SceneResourceLimits = BASE_LIMITS): ValidationReport { + return validateDocument(value, "normalized_product", validateNormalizedProductSchema, normalizedProductSemanticIssues, false, limits); +} + +type PackageMediaRole = "geometry" | "edge" | "entity" | "model_source" | "imported_source" | "python_source" | "presentation"; + +interface PackageRecord extends JsonRecord { + byte_length: unknown; + content_hash: unknown; + media_role: PackageMediaRole; +} + +function packageRecords(scene: JsonRecord): { records: Map; issues: ValidationIssue[] } { + const result = new Map(); + const issues: ValidationIssue[] = []; + const add = (uri: unknown, byteLength: unknown, contentHash: unknown, mediaRole: PackageMediaRole): void => { + if (typeof uri !== "string") return; + const record: PackageRecord = { byte_length: byteLength, content_hash: contentHash, media_role: mediaRole }; + const previous = result.get(uri); + if ( + previous !== undefined && + (previous.byte_length !== record.byte_length || + previous.content_hash !== record.content_hash || + previous.media_role !== record.media_role) + ) { + issues.push(issue("package_member_set_invalid", "", "manifest records for one URI disagree on hash, length, or media role", "package")); + return; + } + result.set(uri, record); + }; + for (const [key, mediaRole] of [["geometry_assets", "geometry"], ["edge_assets", "edge"], ["entity_assets", "entity"]] as const) { + const records = Array.isArray(scene[key]) ? scene[key] : []; + for (const value of records) if (isRecord(value)) add(value.uri, value.byte_length, value.content_hash, mediaRole); + } + if (isRecord(scene.source) && typeof scene.source.embedded_artifact_uri === "string") { + add( + scene.source.embedded_artifact_uri, + scene.source.embedded_artifact_byte_length, + scene.source.artifact_hash, + scene.source.kind === "model" ? "model_source" : "imported_source", + ); + const sourceFiles = Array.isArray(scene.source.source_files) ? scene.source.source_files : []; + for (const sourceFile of sourceFiles) { + if (isRecord(sourceFile)) add(sourceFile.uri, sourceFile.byte_length, sourceFile.content_hash, "python_source"); + } + } + if (isRecord(scene.presentation_source) && typeof scene.presentation_source.embedded_artifact_uri === "string") { + add( + scene.presentation_source.embedded_artifact_uri, + scene.presentation_source.embedded_artifact_byte_length, + scene.presentation_source.artifact_hash, + "presentation", + ); + } + return { records: result, issues }; +} + +export interface PackageBudgetContributions { + sceneJsonBytes: number; + glbDecodedBufferBytes: number; + entityJsonBytes: number; + otherImmutableJsonBytes: number; + entityCount: number; + entityVertexCount: number; + triangleVertexCount: number; + triangleCount: number; + lineVertexCount: number; + lineSegmentCount: number; +} + +export interface PackageBudgetTotals { + staticDecodedBufferBytes: number; + entityCount: number; + triangleVertexTotal: number; + triangleTotal: number; + lineVertexTotal: number; + lineSegmentTotal: number; +} + +export interface PackageBudgetLimits { + static_decoded_buffer_bytes: number; + entities_total: number; + triangle_vertices_total: number; + triangles_total: number; + line_vertices_total: number; + line_segments_total: number; +} + +export function computePackageBudgetTotals(input: PackageBudgetContributions): PackageBudgetTotals { + return { + staticDecodedBufferBytes: + input.sceneJsonBytes + + input.glbDecodedBufferBytes + + input.entityJsonBytes + + input.otherImmutableJsonBytes + + 2 * input.entityVertexCount * 16, + entityCount: input.entityCount, + triangleVertexTotal: input.triangleVertexCount, + triangleTotal: input.triangleCount, + lineVertexTotal: input.lineVertexCount, + lineSegmentTotal: input.lineSegmentCount, + }; +} + +export function packageBudgetIssues( + totals: PackageBudgetTotals, + limits: PackageBudgetLimits = BASE_LIMITS, +): ValidationIssue[] { + const issues: ValidationIssue[] = []; + if (totals.staticDecodedBufferBytes > limits.static_decoded_buffer_bytes) { + issues.push(issue("static_buffer_limit_exceeded", "", "static decoded buffer formula exceeds resource limit", "budget")); + } + if (totals.entityCount > limits.entities_total) { + issues.push(issue("resource_limit_exceeded", "/entity_assets", "total entity count exceeds resource limit", "budget")); + } + for (const [total, limit, message] of [ + [totals.triangleVertexTotal, limits.triangle_vertices_total, "total triangle GLB vertex count exceeds resource limit"], + [totals.triangleTotal, limits.triangles_total, "total triangle count exceeds resource limit"], + [totals.lineVertexTotal, limits.line_vertices_total, "total line GLB vertex count exceeds resource limit"], + [totals.lineSegmentTotal, limits.line_segments_total, "total line segment count exceeds resource limit"], + ] as const) { + if (total > limit) issues.push(issue("resource_limit_exceeded", "", message, "budget")); + } + return issues; +} + + +const sourceDecoder = new TextDecoder("utf-8", { fatal: true }); + +function sourceSegment( + content: string, + line: number, + column: number, + endLine: number, + endColumn: number, +): string | null { + const normalized = content.replace(/\r\n?/g, "\n"); + const lines = normalized.split("\n"); + if (normalized.endsWith("\n")) lines.pop(); + if (lines.length === 0 || line < 1 || endLine < line || endLine > lines.length) return null; + const startText = Array.from(lines[line - 1]); + const endText = Array.from(lines[endLine - 1]); + if (column < 0 || endColumn < 0 || column > startText.length || endColumn > endText.length || (line === endLine && endColumn < column)) return null; + if (line === endLine) return startText.slice(column, endColumn).join(""); + const parts = [startText.slice(column).join("")]; + for (let index = line; index < endLine - 1; index += 1) parts.push(lines[index]); + parts.push(endText.slice(0, endColumn).join("")); + return parts.join("\n"); +} + +function expectedCallsiteId(source: JsonRecord): string { + const material = [ + source.path ?? "", + source.line, + source.column, + source.end_line, + source.end_column, + source.call_text, + ].map(String).join("\x1f"); + return `callsite_${sha256(Buffer.from(material, "utf8")).slice("sha256:".length, "sha256:".length + 16)}`; +} + +function operationSourceIssues( + source: unknown, + path: string, + sourceFiles: ReadonlyMap, +): ValidationIssue[] { + if (!isRecord(source)) return [issue("source_matrix_invalid", path, "operation source must be an object")]; + const issues: ValidationIssue[] = []; + const keys = Object.keys(source); + if (keys.length !== operationSourceKeys.size || keys.some((key) => !operationSourceKeys.has(key))) { + issues.push(issue("source_matrix_invalid", path, "operation source fields do not match source mapping schema 1.0")); + } + const line = source.line; + const column = source.column; + const endLine = source.end_line; + const endColumn = source.end_column; + const assignmentTargets = source.assignment_targets; + const valid = + source.schema_version === "1.0" && + (source.path_kind === "project_relative" || source.path_kind === "unresolved") && + Number.isSafeInteger(line) && (line as number) >= 1 && + Number.isSafeInteger(column) && (column as number) >= 0 && + Number.isSafeInteger(endLine) && (endLine as number) >= (line as number) && + Number.isSafeInteger(endColumn) && (endColumn as number) >= 0 && + typeof source.call_text === "string" && + typeof source.callsite_id === "string" && /^callsite_[0-9a-f]{16}$/.test(source.callsite_id) && + Array.isArray(assignmentTargets) && assignmentTargets.every((value) => typeof value === "string" && value.length > 0); + if (!valid) { + issues.push(issue("source_matrix_invalid", path, "operation source values do not match source mapping schema 1.0")); + return issues; + } + if (source.path_kind === "unresolved") { + if (source.path !== null) issues.push(issue("source_matrix_invalid", `${path}/path`, "unresolved operation source path must be null")); + } else if (typeof source.path !== "string" || !sourceFiles.has(source.path)) { + issues.push(issue("source_matrix_invalid", `${path}/path`, "operation source path does not resolve to an embedded source file")); + } else { + const segment = sourceSegment(sourceFiles.get(source.path)!, line as number, column as number, endLine as number, endColumn as number); + if (segment === null || segment !== source.call_text) { + issues.push(issue("source_matrix_invalid", path, "operation source span does not match embedded source text")); + } + } + if (source.callsite_id !== expectedCallsiteId(source)) { + issues.push(issue("source_matrix_invalid", `${path}/callsite_id`, "operation callsite_id does not match its canonical source span")); + } + return issues; +} + +function embeddedModelIssues( + scene: JsonRecord, + payload: Buffer, + sourceFiles: ReadonlyMap, + entityPayloads: ReadonlyMap, +): ValidationIssue[] { + const prefix = "/model/model.json"; + let modelValue: unknown; + try { + modelValue = parseStrictJson(payload); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + if (error instanceof DuplicateKeyError) return [issue("duplicate_json_key", "", message, "parse")]; + if (error instanceof TypeError && message.toLowerCase().includes("utf")) return [issue("invalid_utf8", prefix, message, "parse")]; + return [issue("schema_invalid", prefix, message, "structure")]; + } + if (!isRecord(modelValue)) return [issue("schema_invalid", prefix, "embedded model must be a JSON object", "structure")]; + const model = modelValue; + if (model.schema_version !== "2.0" || !isRecord(model.graph)) { + return [issue("schema_invalid", prefix, "embedded model does not contain a schema 2.0 graph", "structure")]; + } + const graph = model.graph; + const sceneSource = isRecord(scene.source) ? scene.source : {}; + if (graph.graph_id !== sceneSource.graph_id) { + return [issue("source_matrix_invalid", `${prefix}/graph/graph_id`, "embedded model graph_id differs from scene source")]; + } + if (!Array.isArray(graph.nodes)) { + return [issue("schema_invalid", `${prefix}/graph/nodes`, "embedded model graph nodes must be an array", "structure")]; + } + + const issues: ValidationIssue[] = []; + const nodeMap = new Map(); + const nodeIndexes = new Map(); + graph.nodes.forEach((nodeValue, index) => { + const nodePath = `${prefix}/graph/nodes/${index}`; + if (!isRecord(nodeValue)) { + issues.push(issue("schema_invalid", nodePath, "model graph node must be an object", "structure")); + return; + } + const node = nodeValue; + const validNode = + typeof node.node_id === "string" && node.node_id.length > 0 && + typeof node.op === "string" && + isRecord(node.params) && + Array.isArray(node.inputs) && node.inputs.every((value) => typeof value === "string") && + Number.isSafeInteger(node.output_count) && (node.output_count as number) >= 1; + if (!validNode) { + issues.push(issue("schema_invalid", nodePath, "model graph node has an invalid Viewer operation shape", "structure")); + return; + } + const nodeId = node.node_id as string; + if (nodeMap.has(nodeId)) { + issues.push(issue("id_duplicate", `${nodePath}/node_id`, "model graph node_id is duplicated")); + return; + } + nodeMap.set(nodeId, node); + nodeIndexes.set(nodeId, index); + if (Object.hasOwn(node, "source")) issues.push(...operationSourceIssues(node.source, `${nodePath}/source`, sourceFiles)); + }); + for (const [nodeId, node] of nodeMap) { + for (const inputId of node.inputs as string[]) { + if (!nodeMap.has(inputId)) issues.push(issue("reference_missing", `${prefix}/graph/nodes/${nodeIndexes.get(nodeId)!}/inputs`, "model graph input references a missing node")); + } + } + if (!Array.isArray(model.leaf_ids) || !model.leaf_ids.every((value) => typeof value === "string" && nodeMap.has(value))) { + issues.push(issue("reference_missing", `${prefix}/leaf_ids`, "model leaf_ids must resolve to graph nodes")); + } + + const validateReference = (value: unknown, path: string): void => { + if (!isRecord(value)) return; + const node = typeof value.node_id === "string" ? nodeMap.get(value.node_id) : undefined; + if (node === undefined || !Number.isSafeInteger(value.output_slot) || (value.output_slot as number) < 0 || (value.output_slot as number) >= (node.output_count as number)) { + issues.push(issue("reference_missing", path, "model source does not resolve to an embedded graph output")); + } + }; + (Array.isArray(scene.definitions) ? scene.definitions : []).forEach((definitionValue, index) => { + if (!isRecord(definitionValue) || !isRecord(definitionValue.source)) return; + if (definitionValue.source.kind === "product_model" || definitionValue.source.kind === "model_output") validateReference(definitionValue.source, `/definitions/${index}/source`); + }); + (Array.isArray(scene.connectors) ? scene.connectors : []).forEach((connectorValue, index) => { + if (isRecord(connectorValue) && isRecord(connectorValue.source) && connectorValue.source.kind === "model_operation") validateReference(connectorValue.source, `/connectors/${index}/source`); + }); + for (const [uri, entityPayload] of entityPayloads) { + (Array.isArray(entityPayload.entities) ? entityPayload.entities : []).forEach((entityValue, index) => { + if (!isRecord(entityValue) || !isRecord(entityValue.source)) return; + if (entityValue.source.kind === "model_output" || entityValue.source.kind === "model_topology") validateReference(entityValue.source, `/${uri}/entities/${index}/source`); + }); + } + return issues; +} + +function embeddedPresentationIssues( + scene: JsonRecord, + payload: Buffer, + uri: string, + limits: SceneResourceLimits, +): ValidationIssue[] { + const prefix = `/${uri}`; + const presentationReport = validatePresentation(payload, limits); + const issues = presentationReport.issues.map((item) => { + const code = item.code === "presentation_reference_invalid" ? "source_matrix_invalid" : item.code; + const path = hasRootPointerPolicy(code) ? "" : `${prefix}${item.path}`; + return issue(code, path, item.message, item.phase); + }); + if (presentationReport.issues.some((item) => item.phase === "parse" || item.phase === "structure")) return issues; + let parsed: unknown; + try { parsed = parseCanonicalJson(payload); } catch { return issues; } + if (!isRecord(parsed) || !isRecord(scene.presentation_source)) return issues; + const presentation = parsed; + const presentationSource = scene.presentation_source; + if (presentation.presentation_id !== presentationSource.presentation_id) { + issues.push(issue("source_matrix_invalid", `${prefix}/presentation_id`, "presentation_id differs from manifest presentation_source")); + } + if (presentation.source_scene_id !== scene.scene_id) { + issues.push(issue("source_matrix_invalid", `${prefix}/source_scene_id`, "presentation source_scene_id differs from manifest scene_id")); + } + + const sceneAppearances = (Array.isArray(scene.appearances) ? scene.appearances : []).filter(isRecord); + const expectedAppearanceIds = new Map(); + const authoredAppearances = (Array.isArray(presentation.appearances) ? presentation.appearances : []).filter(isRecord); + authoredAppearances.forEach((authored, index) => { + const evaluated: JsonRecord = { + alpha_mode: authored.alpha_mode, + base_color: authored.base_color, + double_sided: authored.double_sided, + edge_color: authored.edge_color, + metallic: authored.metallic, + name: authored.name, + roughness: authored.roughness, + sdk_metadata: {}, + source: { + appearance_name: authored.name, + kind: "presentation", + presentation_id: presentation.presentation_id, + }, + }; + const appearanceId = `appearance/evaluated/${sha256(canonicalJsonBytes(evaluated)).slice("sha256:".length)}`; + expectedAppearanceIds.set(authored.name, appearanceId); + const expected = { appearance_id: appearanceId, ...evaluated }; + if (sceneAppearances.filter((appearance) => equalJson(appearance, expected)).length !== 1) { + issues.push(issue("source_matrix_invalid", `${prefix}/appearances/${index}`, "presentation appearance does not resolve to exactly one evaluated scene appearance")); + } + }); + const expectedAppearanceIdSet = new Set(expectedAppearanceIds.values()); + sceneAppearances.forEach((appearance, index) => { + if ( + isRecord(appearance.source) && + appearance.source.kind === "presentation" && + !expectedAppearanceIdSet.has(appearance.appearance_id as string) + ) { + issues.push(issue("source_matrix_invalid", `/appearances/${index}/source/appearance_name`, "evaluated presentation appearance does not resolve to an authored appearance")); + } + }); + + const sceneNodes = (Array.isArray(scene.nodes) ? scene.nodes : []).filter(isRecord); + const nodeMap = new Map(sceneNodes.map((node) => [node.node_id, node])); + const definitionMap = new Map( + (Array.isArray(scene.definitions) ? scene.definitions : []).filter(isRecord).map((definition) => [definition.definition_id, definition]), + ); + const overrides = (Array.isArray(presentation.node_overrides) ? presentation.node_overrides : []).filter(isRecord); + const overrideMap = new Map(overrides.map((override) => [override.node_id, override])); + overrides.forEach((override, index) => { + const node = nodeMap.get(override.node_id); + if (node === undefined) { + issues.push(issue("source_matrix_invalid", `${prefix}/node_overrides/${index}/node_id`, "node override target does not exist in the scene")); + return; + } + if (override.appearance_name !== undefined) { + const definition = definitionMap.get(node.definition_id); + if (definition === undefined || (definition.kind !== "part" && definition.kind !== "shape")) { + issues.push(issue("source_matrix_invalid", `${prefix}/node_overrides/${index}/appearance_name`, "appearance override target is not a renderable Part or Shape")); + } + } + }); + sceneNodes.forEach((node, index) => { + const override = overrideMap.get(node.node_id); + const expectedVisible = override?.visible ?? true; + const appearanceName = override?.appearance_name; + const expectedAppearanceId = appearanceName === undefined ? undefined : expectedAppearanceIds.get(appearanceName); + if (node.visible !== expectedVisible) { + issues.push(issue("source_matrix_invalid", `/nodes/${index}/visible`, "node visibility does not match the embedded presentation")); + } + if (expectedAppearanceId !== undefined && node.appearance_override_id !== expectedAppearanceId) { + issues.push(issue("source_matrix_invalid", `/nodes/${index}/appearance_override_id`, "node appearance override does not resolve the embedded presentation name")); + } + if (appearanceName === undefined && node.appearance_override_id !== null) { + issues.push(issue("source_matrix_invalid", `/nodes/${index}/appearance_override_id`, "node appearance override is not authored by the embedded presentation")); + } + }); + + const sceneCameras = (Array.isArray(scene.cameras) ? scene.cameras : []).filter(isRecord); + const expectedCameraIds = new Set(); + const authoredCameras = (Array.isArray(presentation.cameras) ? presentation.cameras : []).filter(isRecord); + authoredCameras.forEach((authored, index) => { + if (authored.parent_node_id !== null && !nodeMap.has(authored.parent_node_id)) { + issues.push(issue("source_matrix_invalid", `${prefix}/cameras/${index}/parent_node_id`, "presentation camera parent does not exist in the scene")); + } + const cameraId = `camera/${String(presentation.presentation_id)}/${encodeSegment(String(authored.name ?? ""))}`; + expectedCameraIds.add(cameraId); + const expected = { camera_id: cameraId, ...authored }; + if (sceneCameras.filter((camera) => equalJson(camera, expected)).length !== 1) { + issues.push(issue("source_matrix_invalid", `${prefix}/cameras/${index}`, "presentation camera does not resolve to exactly one evaluated scene camera")); + } + }); + sceneCameras.forEach((camera, index) => { + if (!expectedCameraIds.has(camera.camera_id as string)) { + issues.push(issue("source_matrix_invalid", `/cameras/${index}`, "evaluated scene camera is not authored by the embedded presentation")); + } + }); + return issues; +} + +function transformedBounds(info: GlbInfo, matrix: unknown): JsonRecord | null { + if (!Array.isArray(matrix) || matrix.length !== 16 || !matrix.every((item) => typeof item === "number")) return null; + const [minimum, maximum] = info.positionBounds; + const points: number[][] = []; + for (const x of [minimum[0], maximum[0]]) for (const y of [minimum[1], maximum[1]]) for (const z of [minimum[2], maximum[2]]) { + points.push([matrix[0] * x + matrix[1] * y + matrix[2] * z + matrix[3], matrix[4] * x + matrix[5] * y + matrix[6] * z + matrix[7], matrix[8] * x + matrix[9] * y + matrix[10] * z + matrix[11]]); + } + return { min: [0, 1, 2].map((axis) => Math.min(...points.map((point) => point[axis]))), max: [0, 1, 2].map((axis) => Math.max(...points.map((point) => point[axis]))) }; +} + +function equalJson(left: unknown, right: unknown): boolean { + return Buffer.compare(canonicalJsonBytes(left), canonicalJsonBytes(right)) === 0; +} + +export function validateScenePackage( + sceneInput: unknown, + blobsInput: ReadonlyMap | Record, + limits: SceneResourceLimits = BASE_LIMITS, +): ValidationReport { + const manifest = validateSceneManifest(sceneInput, limits); + const issues = [...manifest.issues]; + const parsed = parseInput(sceneInput, typeof sceneInput === "string" || sceneInput instanceof Uint8Array); + if (!isRecord(parsed.value) || issues.some((item) => item.phase === "parse" || item.phase === "structure")) return report(issues, "package"); + const scene = parsed.value; + const blobs = blobsInput instanceof Map ? new Map(blobsInput) : new Map(Object.entries(blobsInput)); + const packageRecordResult = packageRecords(scene); + const records = packageRecordResult.records; + issues.push(...packageRecordResult.issues); + if (blobs.size !== records.size || [...blobs.keys()].some((name) => !records.has(name))) issues.push(issue("package_member_set_invalid", "", "blob keys do not exactly equal manifest URI references", "package")); + const glbs = new Map(); + const entities = new Map(); + let embeddedModel: Buffer | null = null; + const sourceFiles = new Map(); + const sourcePathByUri = new Map(); + if (isRecord(scene.source) && Array.isArray(scene.source.source_files)) { + for (const sourceFile of scene.source.source_files) { + if (isRecord(sourceFile) && typeof sourceFile.uri === "string" && typeof sourceFile.path === "string") { + sourcePathByUri.set(sourceFile.uri, sourceFile.path); + } + } + } + const budget: PackageBudgetContributions = { + sceneJsonBytes: canonicalJsonBytes(scene).length, + glbDecodedBufferBytes: 0, + entityJsonBytes: 0, + otherImmutableJsonBytes: 0, + entityCount: 0, + entityVertexCount: 0, + triangleVertexCount: 0, + triangleCount: 0, + lineVertexCount: 0, + lineSegmentCount: 0, + }; + for (const [uri, asset] of records) { + const value = blobs.get(uri); + if (value === undefined) continue; + const roleLimit = asset.media_role === "entity" + ? limits.entity_json_bytes + : asset.media_role === "model_source" + ? limits.model_json_bytes + : asset.media_role === "presentation" + ? limits.presentation_json_bytes + : limits.one_member_bytes; + if (value.byteLength > Math.min(limits.one_member_bytes, roleLimit)) { + issues.push(issue("resource_limit_exceeded", `/${uri}`, "package member bytes exceed resource limit", "budget")); + continue; + } + const payload = Buffer.from(value); + if (payload.length !== asset.byte_length) issues.push(issue("blob_length_mismatch", `/${uri}`, "blob length differs from manifest", "package")); + if (sha256(payload) !== asset.content_hash) issues.push(issue("blob_hash_mismatch", `/${uri}`, "blob hash differs from manifest", "package")); + if (asset.media_role === "geometry" || asset.media_role === "edge") { + try { + const info = preflightGlb(payload, asset.media_role === "geometry" ? "triangle" : "line", limits); + glbs.set(uri, info); + budget.glbDecodedBufferBytes += info.decodedBufferBytes; + if (info.kind === "triangle") { + budget.triangleVertexCount += info.vertexCount; + budget.triangleCount += info.primitiveCount; + } else { + budget.lineVertexCount += info.vertexCount; + budget.lineSegmentCount += info.primitiveCount; + } + } + catch (error) { issues.push(issue("glb_profile_invalid", `/${uri}`, error instanceof Error ? error.message : String(error), "package")); } + } else if (asset.media_role === "entity") { + const entityReport = validateEntityAsset(payload, limits); + for (const item of entityReport.issues) { + issues.push(issue( + item.code, + hasRootPointerPolicy(item.code) ? "" : `/${uri}${item.path}`, + item.message, + item.phase, + )); + } + try { + const value = parseCanonicalJson(payload); + if (isRecord(value)) { + entities.set(uri, value); + budget.entityJsonBytes += payload.length; + const sidecarEntities = Array.isArray(value.entities) ? value.entities : []; + budget.entityCount += sidecarEntities.length; + budget.entityVertexCount += sidecarEntities.filter((entity) => isRecord(entity) && entity.kind === "vertex").length; + } + } catch { /* Reported above. */ } + } else if (asset.media_role === "presentation") { + issues.push(...embeddedPresentationIssues(scene, payload, uri, limits)); + budget.otherImmutableJsonBytes += payload.length; + } else if (asset.media_role === "model_source") { + embeddedModel = payload; + budget.otherImmutableJsonBytes += payload.length; + } else if (asset.media_role === "python_source") { + try { + const sourcePath = sourcePathByUri.get(uri); + if (sourcePath !== undefined) sourceFiles.set(sourcePath, sourceDecoder.decode(payload)); + } catch (error) { + issues.push(issue("invalid_utf8", `/${uri}`, error instanceof Error ? error.message : String(error), "parse")); + } + budget.otherImmutableJsonBytes += payload.length; + } + } + if (embeddedModel !== null) issues.push(...embeddedModelIssues(scene, embeddedModel, sourceFiles, entities)); + issues.push(...packageBudgetIssues(computePackageBudgetTotals(budget), limits)); + const geometryById = new Map((Array.isArray(scene.geometry_assets) ? scene.geometry_assets : []).filter(isRecord).map((item) => [item.asset_id, item])); + const edgesById = new Map((Array.isArray(scene.edge_assets) ? scene.edge_assets : []).filter(isRecord).map((item) => [item.asset_id, item])); + const entityById = new Map((Array.isArray(scene.entity_assets) ? scene.entity_assets : []).filter(isRecord).map((item) => [item.entity_asset_id, item])); + const definitions = Array.isArray(scene.definitions) ? scene.definitions : []; + definitions.forEach((value, definitionIndex) => { + if (!isRecord(value) || value.kind === "assembly") return; + const entityRecord = entityById.get(value.entity_asset_id); + const geometryRecord = geometryById.get(value.geometry_asset_id); + const edgeRecord = edgesById.get(value.edge_asset_id); + for (const [record, expectedKind] of [[geometryRecord, "geometry"], [edgeRecord, "edge"]] as const) { + if (!isRecord(record) || typeof record.uri !== "string") continue; + const info = glbs.get(record.uri); + if (info !== undefined) { + const expected = transformedBounds(info, record.asset_to_scene); + if (expected === null || !equalJson(record.scene_local_bounds, expected)) issues.push(issue("bounds_invalid", `/definitions/${definitionIndex}`, `${expectedKind} asset scene_local_bounds differ from transformed GLB bounds`)); + } + } + if (!isRecord(entityRecord) || typeof entityRecord.uri !== "string") return; + const payload = entities.get(entityRecord.uri); + if (payload === undefined) return; + if (payload.definition_id !== value.definition_id || payload.geometry_asset_id !== value.geometry_asset_id || payload.edge_asset_id !== value.edge_asset_id) issues.push(issue("reference_missing", `/definitions/${definitionIndex}/entity_asset_id`, "entity sidecar ownership triple differs from definition")); + if ( + !isRecord(payload.geometry_engine) || + !isRecord(scene.generator) || + payload.geometry_engine.version !== scene.generator.ocp_version + ) { + issues.push(issue("source_matrix_invalid", `/definitions/${definitionIndex}/entity_asset_id`, "entity geometry engine version differs from manifest generator")); + } + const sceneSourceKind = isRecord(scene.source) ? scene.source.kind : undefined; + const allowedEntitySources: Record> = { + model: new Set(["model_output", "model_topology"]), + imported: new Set(["imported_primitive", "unbound"]), + manual: new Set(["unbound"]), + }; + const definitionSource = isRecord(value.source) ? value.source : {}; + const sidecarEntities = Array.isArray(payload.entities) ? payload.entities : []; + sidecarEntities.forEach((entityValue, entityIndex) => { + if (!isRecord(entityValue)) return; + const entityPath = `/${entityRecord.uri}/entities/${entityIndex}`; + const entitySource = isRecord(entityValue.source) ? entityValue.source : null; + if ( + entitySource === null || + typeof entitySource.kind !== "string" || + typeof sceneSourceKind !== "string" || + !allowedEntitySources[sceneSourceKind]?.has(entitySource.kind) + ) { + issues.push(issue("source_matrix_invalid", `${entityPath}/source`, "entity source is incompatible with scene source")); + } else if ( + sceneSourceKind === "model" && + ["graph_id", "node_id", "output_slot"].some( + (field) => entitySource[field] !== definitionSource[field], + ) + ) { + issues.push(issue("source_matrix_invalid", `${entityPath}/source`, "entity model source differs from owning definition output")); + } + + let expectedStatus: string | null = null; + if (entityValue.kind === "solid") expectedStatus = "not_applicable"; + else if (value.kind !== "part") expectedStatus = "owner_not_part"; + else if (sceneSourceKind !== "model") expectedStatus = "source_not_model"; + else if (entityValue.sdk_connector_frame === null) expectedStatus = "frame_undefined"; + if (expectedStatus !== null && entityValue.connector_binding_status !== expectedStatus) { + issues.push(issue("connector_invalid", `${entityPath}/connector_binding_status`, `connector binding status must be ${expectedStatus}`)); + } + }); + const faceTotal = (Array.isArray(payload.face_groups) ? payload.face_groups : []).filter(isRecord).reduce((sum, group) => sum + (typeof group.index_count === "number" ? group.index_count : 0), 0); + const edgeTotal = (Array.isArray(payload.edge_groups) ? payload.edge_groups : []).filter(isRecord).reduce((sum, group) => sum + (typeof group.index_count === "number" ? group.index_count : 0), 0); + const geometryInfo = isRecord(geometryRecord) && typeof geometryRecord.uri === "string" ? glbs.get(geometryRecord.uri) : undefined; + const edgeInfo = isRecord(edgeRecord) && typeof edgeRecord.uri === "string" ? glbs.get(edgeRecord.uri) : undefined; + if (geometryInfo !== undefined && faceTotal !== geometryInfo.indexCount) issues.push(issue("entity_range_invalid", `/definitions/${definitionIndex}/entity_asset_id`, "face groups do not partition triangle GLB indices")); + if (edgeInfo !== undefined && edgeTotal !== edgeInfo.indexCount) issues.push(issue("entity_range_invalid", `/definitions/${definitionIndex}/entity_asset_id`, "edge groups do not partition line GLB indices")); + }); + return report(issues, "package"); +} diff --git a/scene-contract/src/zip.ts b/scene-contract/src/zip.ts new file mode 100644 index 00000000..27b67ea6 --- /dev/null +++ b/scene-contract/src/zip.ts @@ -0,0 +1,278 @@ +import { inflateRawSync } from "node:zlib"; +import { + BASE_LIMITS, + preflightAggregateCompressionRatio, + preflightInputArchiveSize, + preflightMemberCompressionRatio, + type SceneResourceLimits, +} from "./resources.js"; + +export interface ArchiveInfo { + members: ReadonlyMap; + inputSize: number; + canonicalSize: number; + usedDeflate: boolean; +} + +interface Entry { + name: string; + method: number; + crc32: number; + compressedSize: number; + uncompressedSize: number; + localOffset: number; +} + +const memberPattern = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,1023}$/; +function crc32Table(): Uint32Array { + const table = new Uint32Array(256); + for (let index = 0; index < 256; index += 1) { + let value = index; + for (let bit = 0; bit < 8; bit += 1) value = (value & 1) !== 0 ? 0xedb88320 ^ (value >>> 1) : value >>> 1; + table[index] = value >>> 0; + } + return table; +} + +const crcTable = crc32Table(); + +function crc32(data: Uint8Array): number { + let crc = 0xffffffff; + for (const byte of data) crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8); + return (crc ^ 0xffffffff) >>> 0; +} + +function ascii(raw: Uint8Array, context: string): string { + if (raw.some((byte) => byte > 0x7f)) throw new Error("archive member names must be ASCII"); + return Buffer.from(raw).toString("ascii"); +} + +function validateName(name: string, seen: Set): Buffer { + const encoded = Buffer.from(name, "ascii"); + if (encoded.toString("ascii") !== name) throw new Error("archive member names must be ASCII"); + if (!memberPattern.test(name)) throw new Error(`invalid archive member name: ${JSON.stringify(name)}`); + if (name.split("/").some((segment) => segment === "" || segment === "." || segment === "..")) { + throw new Error(`invalid archive member path segment: ${JSON.stringify(name)}`); + } + const folded = name.toLowerCase(); + if (seen.has(folded)) throw new Error(`duplicate or case-colliding archive member: ${JSON.stringify(name)}`); + seen.add(folded); + return encoded; +} + +export function canonicalArchiveSize(sizes: ReadonlyMap): number { + let total = 22; + for (const [name, size] of sizes) total += 76 + 2 * Buffer.byteLength(name, "ascii") + size; + return total; +} + +export function preflightArchiveMemberSizes( + sizes: ReadonlyMap, + limits: SceneResourceLimits = BASE_LIMITS, +): number { + if (sizes.size === 0 || !sizes.has("scene.json")) throw new Error("scene package must contain scene.json"); + if (sizes.size > limits.zip_members) throw new Error("archive member count exceeds resource limit"); + const seen = new Set(); + let total = 0; + for (const [name, size] of sizes) { + validateName(name, seen); + if (!Number.isSafeInteger(size) || size < 0) throw new Error(`invalid member size for ${JSON.stringify(name)}`); + if (size > limits.one_member_bytes) throw new Error(`archive member exceeds resource limit: ${JSON.stringify(name)}`); + if (name === "scene.json" && size > limits.scene_json_bytes) throw new Error("scene.json exceeds resource limit"); + if (name.startsWith("entities/") && size > limits.entity_json_bytes) throw new Error(`entity sidecar exceeds resource limit: ${JSON.stringify(name)}`); + if (name === "model/model.json" && size > limits.model_json_bytes) throw new Error("embedded model.json exceeds resource limit"); + if (name === "presentation/presentation.json" && size > limits.presentation_json_bytes) throw new Error("presentation JSON exceeds resource limit"); + total += size; + if (total > limits.total_uncompressed_bytes) throw new Error("total uncompressed bytes exceed resource limit"); + } + const result = canonicalArchiveSize(sizes); + if (result > limits.canonical_archive_bytes) throw new Error("canonical stored archive exceeds resource limit"); + if (sizes.size > 0xffff || result > 0xffffffff) throw new Error("archive would require ZIP64"); + return result; +} + +export function canonicalZipBytes( + input: ReadonlyMap | Record, + limits: SceneResourceLimits = BASE_LIMITS, +): Buffer { + const members = input instanceof Map ? new Map(input) : new Map(Object.entries(input)); + const payloads = new Map([...members].map(([name, value]) => [name, Buffer.from(value)])); + const canonicalSize = preflightArchiveMemberSizes(new Map([...payloads].map(([name, value]) => [name, value.length])), limits); + const localParts: Buffer[] = []; + const centralParts: Buffer[] = []; + let localOffset = 0; + for (const name of [...payloads.keys()].sort((left, right) => Buffer.compare(Buffer.from(left, "ascii"), Buffer.from(right, "ascii")))) { + const nameBytes = Buffer.from(name, "ascii"); + const payload = payloads.get(name)!; + const crc = crc32(payload); + const local = Buffer.alloc(30); + local.writeUInt32LE(0x04034b50, 0); + local.writeUInt16LE(20, 4); + local.writeUInt16LE(0x0800, 6); + local.writeUInt16LE(0, 8); + local.writeUInt16LE(0, 10); + local.writeUInt16LE(0x0021, 12); + local.writeUInt32LE(crc, 14); + local.writeUInt32LE(payload.length, 18); + local.writeUInt32LE(payload.length, 22); + local.writeUInt16LE(nameBytes.length, 26); + local.writeUInt16LE(0, 28); + localParts.push(local, nameBytes, payload); + const central = Buffer.alloc(46); + central.writeUInt32LE(0x02014b50, 0); + central.writeUInt16LE(0x0314, 4); + central.writeUInt16LE(20, 6); + central.writeUInt16LE(0x0800, 8); + central.writeUInt16LE(0, 10); + central.writeUInt16LE(0, 12); + central.writeUInt16LE(0x0021, 14); + central.writeUInt32LE(crc, 16); + central.writeUInt32LE(payload.length, 20); + central.writeUInt32LE(payload.length, 24); + central.writeUInt16LE(nameBytes.length, 28); + central.writeUInt16LE(0, 30); + central.writeUInt16LE(0, 32); + central.writeUInt16LE(0, 34); + central.writeUInt16LE(0, 36); + central.writeUInt32LE(0x81a40000, 38); + central.writeUInt32LE(localOffset, 42); + centralParts.push(central, nameBytes); + localOffset += local.length + nameBytes.length + payload.length; + } + const centralBytes = Buffer.concat(centralParts); + const eocd = Buffer.alloc(22); + eocd.writeUInt32LE(0x06054b50, 0); + eocd.writeUInt16LE(0, 4); + eocd.writeUInt16LE(0, 6); + eocd.writeUInt16LE(payloads.size, 8); + eocd.writeUInt16LE(payloads.size, 10); + eocd.writeUInt32LE(centralBytes.length, 12); + eocd.writeUInt32LE(localOffset, 16); + eocd.writeUInt16LE(0, 20); + const result = Buffer.concat([...localParts, centralBytes, eocd]); + if (result.length !== canonicalSize) throw new Error("canonical ZIP size formula disagrees with encoder"); + return result; +} + +export function preflightZipBytes(data: Uint8Array, limits: SceneResourceLimits = BASE_LIMITS): ArchiveInfo { + preflightInputArchiveSize(data.byteLength, limits); + const raw = Buffer.isBuffer(data) ? data : Buffer.from(data); + if (raw.length < 22) throw new Error("truncated ZIP archive"); + const eocdOffset = raw.length - 22; + if (raw.readUInt32LE(eocdOffset) !== 0x06054b50 || raw.readUInt16LE(eocdOffset + 20) !== 0) { + throw new Error("ZIP EOCD must be final and have no comment"); + } + const disk = raw.readUInt16LE(eocdOffset + 4); + const centralDisk = raw.readUInt16LE(eocdOffset + 6); + const diskCount = raw.readUInt16LE(eocdOffset + 8); + const totalCount = raw.readUInt16LE(eocdOffset + 10); + const centralSize = raw.readUInt32LE(eocdOffset + 12); + const centralOffset = raw.readUInt32LE(eocdOffset + 16); + if (disk !== 0 || centralDisk !== 0 || diskCount !== totalCount) throw new Error("multi-disk ZIP archives are forbidden"); + if (totalCount > limits.zip_members) throw new Error("archive member count exceeds resource limit"); + if (centralOffset + centralSize !== eocdOffset) throw new Error("ZIP central directory offset/size mismatch"); + const entries: Entry[] = []; + const seen = new Set(); + let cursor = centralOffset; + for (let index = 0; index < totalCount; index += 1) { + if (cursor + 46 > eocdOffset) throw new Error("truncated ZIP central directory"); + if (raw.readUInt32LE(cursor) !== 0x02014b50) throw new Error("invalid ZIP central header signature"); + const madeBy = raw.readUInt16LE(cursor + 4); + const needed = raw.readUInt16LE(cursor + 6); + const flags = raw.readUInt16LE(cursor + 8); + const method = raw.readUInt16LE(cursor + 10); + const dosTime = raw.readUInt16LE(cursor + 12); + const dosDate = raw.readUInt16LE(cursor + 14); + const crc = raw.readUInt32LE(cursor + 16); + const compressedSize = raw.readUInt32LE(cursor + 20); + const uncompressedSize = raw.readUInt32LE(cursor + 24); + const nameLength = raw.readUInt16LE(cursor + 28); + const extraLength = raw.readUInt16LE(cursor + 30); + const commentLength = raw.readUInt16LE(cursor + 32); + const diskStart = raw.readUInt16LE(cursor + 34); + const internalAttributes = raw.readUInt16LE(cursor + 36); + const externalAttributes = raw.readUInt32LE(cursor + 38); + const localOffset = raw.readUInt32LE(cursor + 42); + if (madeBy !== 0x0314 || needed !== 20) throw new Error("ZIP creator/version profile mismatch"); + if (flags !== 0x0800 || (method !== 0 && method !== 8)) throw new Error("unsupported ZIP flags or compression method"); + if (dosTime !== 0 || dosDate !== 0x0021) throw new Error("ZIP timestamp profile mismatch"); + if (extraLength !== 0 || commentLength !== 0 || diskStart !== 0 || internalAttributes !== 0) throw new Error("ZIP extra/comment/disk/attributes are forbidden"); + if (externalAttributes !== 0x81a40000) throw new Error("ZIP member must be Unix regular mode 0100644"); + const nameStart = cursor + 46; + const recordEnd = nameStart + nameLength + extraLength + commentLength; + if (recordEnd > eocdOffset) throw new Error("truncated ZIP central member record"); + const name = ascii(raw.subarray(nameStart, nameStart + nameLength), "central name"); + validateName(name, seen); + entries.push({ name, method, crc32: crc, compressedSize, uncompressedSize, localOffset }); + cursor = recordEnd; + } + if (cursor !== eocdOffset) throw new Error("unexpected bytes in ZIP central directory"); + const canonicalSize = preflightArchiveMemberSizes(new Map(entries.map((entry) => [entry.name, entry.uncompressedSize])), limits); + const occupied: [number, number][] = []; + const payloadRanges: { entry: Entry; start: number; end: number }[] = []; + let totalUncompressed = 0; + for (const entry of entries) { + const offset = entry.localOffset; + if (offset + 30 > centralOffset) throw new Error("truncated ZIP local header"); + if (raw.readUInt32LE(offset) !== 0x04034b50) throw new Error("invalid ZIP local header signature"); + const needed = raw.readUInt16LE(offset + 4); + const flags = raw.readUInt16LE(offset + 6); + const method = raw.readUInt16LE(offset + 8); + const dosTime = raw.readUInt16LE(offset + 10); + const dosDate = raw.readUInt16LE(offset + 12); + const crc = raw.readUInt32LE(offset + 14); + const compressedSize = raw.readUInt32LE(offset + 18); + const uncompressedSize = raw.readUInt32LE(offset + 22); + const nameLength = raw.readUInt16LE(offset + 26); + const extraLength = raw.readUInt16LE(offset + 28); + if (needed !== 20 || flags !== 0x0800 || method !== entry.method || dosTime !== 0 || dosDate !== 0x0021 || crc !== entry.crc32 || compressedSize !== entry.compressedSize || uncompressedSize !== entry.uncompressedSize || extraLength !== 0) { + throw new Error("ZIP central/local header mismatch"); + } + const nameStart = offset + 30; + const nameEnd = nameStart + nameLength; + const payloadEnd = nameEnd + compressedSize; + if (payloadEnd > centralOffset) throw new Error("ZIP member payload crosses central directory"); + if (ascii(raw.subarray(nameStart, nameEnd), "local name") !== entry.name) throw new Error("ZIP central/local member name mismatch"); + occupied.push([offset, payloadEnd]); + payloadRanges.push({ entry, start: nameEnd, end: payloadEnd }); + totalUncompressed += uncompressedSize; + } + occupied.sort((left, right) => left[0] - right[0]); + if (occupied.length > 0) { + if (occupied[0][0] !== 0) throw new Error("ZIP archive has a leading prefix"); + for (let index = 1; index < occupied.length; index += 1) { + if (occupied[index - 1][1] !== occupied[index][0]) throw new Error("ZIP local records overlap or contain gaps"); + } + if (occupied.at(-1)![1] !== centralOffset) throw new Error("ZIP bytes exist between local records and central directory"); + } + preflightAggregateCompressionRatio(totalUncompressed, raw.length, limits); + + const members = new Map(); + for (const { entry, start, end } of payloadRanges) { + const compressed = raw.subarray(start, end); + try { + preflightMemberCompressionRatio(entry.uncompressedSize, entry.compressedSize, limits); + } catch { + throw new Error(`member compression ratio exceeds limit: ${JSON.stringify(entry.name)}`); + } + let payload: Buffer; + if (entry.method === 0) { + payload = Buffer.from(compressed); + } else { + try { + const inflated = inflateRawSync(compressed, { maxOutputLength: entry.uncompressedSize + 1, info: true }) as unknown as { + buffer: Buffer; + engine: { bytesWritten: number }; + }; + if (inflated.engine.bytesWritten !== compressed.length) throw new Error("trailing deflate data"); + payload = Buffer.from(inflated.buffer); + } catch { + throw new Error(`invalid deflate stream: ${JSON.stringify(entry.name)}`); + } + } + if (payload.length !== entry.uncompressedSize) throw new Error(`ZIP member decoded size mismatch: ${JSON.stringify(entry.name)}`); + if (crc32(payload) !== entry.crc32) throw new Error(`ZIP member CRC mismatch: ${JSON.stringify(entry.name)}`); + members.set(entry.name, payload); + } + return { members, inputSize: raw.length, canonicalSize, usedDeflate: entries.some((entry) => entry.method === 8) }; +} diff --git a/scene-contract/test/canonical.test.ts b/scene-contract/test/canonical.test.ts new file mode 100644 index 00000000..90bd9366 --- /dev/null +++ b/scene-contract/test/canonical.test.ts @@ -0,0 +1,87 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + canonicalJsonBytes, + parseCanonicalJson, + parseStrictJson, + validateNormalizedProduct, + withSceneRevision, +} from "../src/index.js"; + +test("canonical JSON renders finite Numbers from their value", () => { + assert.equal(canonicalJsonBytes(1e30).toString("utf8"), "1e+30"); + assert.equal(canonicalJsonBytes(parseStrictJson("1e30")).toString("utf8"), "1e+30"); + + const nested = parseStrictJson('{"large":1e30,"small":[1E-7]}'); + assert.equal( + canonicalJsonBytes(nested).toString("utf8"), + '{"large":1e+30,"small":[1e-7]}', + ); + assert.deepEqual(parseCanonicalJson("1e+30"), 1e30); + assert.throws(() => parseCanonicalJson("1e30"), /canonical/); +}); + +test("canonical JSON normalizes negative zero at root and nested positions", () => { + const root = parseStrictJson("-0"); + assert.equal(Object.is(root, -0), true); + assert.equal(canonicalJsonBytes(root).toString("utf8"), "0"); + + const nested = parseStrictJson('{"values":[-0,0e0]}'); + assert.equal(canonicalJsonBytes(nested).toString("utf8"), '{"values":[0,0]}'); + assert.throws(() => parseCanonicalJson("-0"), /canonical/); +}); + +test("cloning parsed values does not change canonical bytes or scene revision", () => { + const scene = parseStrictJson('{"measurement":1e30,"nested":{"epsilon":1e-7}}') as Record< + string, + unknown + >; + const clone = structuredClone(scene); + + assert.deepEqual(canonicalJsonBytes(clone), canonicalJsonBytes(scene)); + assert.deepEqual(withSceneRevision(clone), withSceneRevision(scene)); +}); + +test("unsafe integer JSON is rejected lexically without affecting exponent Numbers", () => { + assert.throws(() => parseStrictJson("9007199254740992"), /safe domain/); + assert.throws(() => parseStrictJson('{"value":-9007199254740992}'), /safe domain/); + assert.equal( + canonicalJsonBytes(Number.MAX_SAFE_INTEGER + 1).toString("utf8"), + "9007199254740992", + ); + assert.equal(canonicalJsonBytes(parseStrictJson("1e30")).toString("utf8"), "1e+30"); +}); + +test("strict JSON rejects unpaired surrogates in values and object keys", () => { + assert.throws(() => parseStrictJson('{"value":"\\ud800"}'), /surrogate/); + assert.throws(() => parseStrictJson('{"\\ud800":0}'), /surrogate/); +}); + +test("serialized JSON over the depth limit reports a budget issue", () => { + let serialized = "0"; + for (let depth = 0; depth < 65; depth += 1) serialized = `{"x":${serialized}}`; + + const result = validateNormalizedProduct(serialized); + assert.equal(result.firstError?.code, "resource_limit_exceeded"); + assert.equal(result.firstError?.phase, "budget"); + assert.equal(result.firstError?.path, "/x".repeat(65)); +}); + +test("serialized non-finite tokens and overflow report nonfinite_json_number", () => { + for (const serialized of [ + "NaN", + "Infinity", + "-Infinity", + "1e999", + '[0,NaN]', + '{"value":1e999}', + ]) { + const result = validateNormalizedProduct(serialized); + assert.equal(result.firstError?.code, "nonfinite_json_number", serialized); + assert.equal(result.firstError?.phase, "parse", serialized); + } + + const programmatic = validateNormalizedProduct({ metadata: { value: Number.NaN } }); + assert.equal(programmatic.firstError?.code, "nonfinite_json_number"); + assert.equal(programmatic.firstError?.path, "/metadata/value"); +}); diff --git a/scene-contract/test/corpus-support.ts b/scene-contract/test/corpus-support.ts new file mode 100644 index 00000000..fc8e0a81 --- /dev/null +++ b/scene-contract/test/corpus-support.ts @@ -0,0 +1,118 @@ +import assert from "node:assert/strict"; +import { withSceneRevision } from "../src/index.js"; + +export interface ExpectedIssue { code: string; path: string } +export interface Mutation { + operation: "add" | "delete" | "set"; + path: (string | number)[]; + value?: unknown; +} +export interface SceneFieldCase { + name: string; + valid: boolean; + expected: ExpectedIssue | null; + mutations: Mutation[]; + recompute_revision: boolean; +} +export interface PackageCase { + name: string; + valid: boolean; + expected: ExpectedIssue | null; + manifest_base64: string; + blob_uris: string[]; + blob_mutations?: Record; +} +export interface SceneShapeCase extends PackageCase { + expected_shape: SceneShapeFacts; +} +export interface SceneShapeFacts { + definition_count: number; + definition_occurrence_counts: Record; + edge_asset_count: number; + entity_asset_count: number; + geometry_asset_count: number; + maximum_depth: number; + node_count: number; + root_node_ids: string[]; +} + +type JsonRecord = Record; + +function asRecord(value: unknown): JsonRecord { + assert.ok(value !== null && typeof value === "object" && !Array.isArray(value)); + return value as JsonRecord; +} + +function asRecords(value: unknown): JsonRecord[] { + assert.ok(Array.isArray(value)); + return value.map(asRecord); +} + +export function corpusBlobs( + pool: Record, + item: PackageCase, +): Map { + const blobs = new Map( + item.blob_uris.map((uri) => [uri, Buffer.from(pool[uri], "base64")]), + ); + for (const [uri, payload] of Object.entries(item.blob_mutations ?? {})) { + blobs.set(uri, Buffer.from(payload, "base64")); + } + return blobs; +} + +export function applySceneFieldCase( + scene: JsonRecord, + item: SceneFieldCase, +): JsonRecord { + const result = structuredClone(scene); + for (const mutation of item.mutations) { + let current: JsonRecord | unknown[] = result; + for (const part of mutation.path.slice(0, -1)) { + current = Array.isArray(current) + ? current[part as number] as JsonRecord | unknown[] + : current[part as string] as JsonRecord | unknown[]; + } + const final = mutation.path.at(-1)!; + if (mutation.operation === "delete") { + if (Array.isArray(current)) delete current[final as number]; + else delete current[final as string]; + } else if (Array.isArray(current)) { + current[final as number] = structuredClone(mutation.value); + } else { + current[final as string] = structuredClone(mutation.value); + } + } + return item.recompute_revision ? withSceneRevision(result) : result; +} + +export function sceneShapeFacts(scene: JsonRecord): SceneShapeFacts { + const nodes = asRecords(scene.nodes); + const definitionOccurrenceCounts: Record = {}; + for (const node of nodes) { + const definitionId = String(node.definition_id); + definitionOccurrenceCounts[definitionId] = + (definitionOccurrenceCounts[definitionId] ?? 0) + 1; + } + return { + definition_count: asRecords(scene.definitions).length, + definition_occurrence_counts: Object.fromEntries( + Object.entries(definitionOccurrenceCounts).sort(([left], [right]) => + Buffer.compare(Buffer.from(left), Buffer.from(right)) + ), + ), + edge_asset_count: asRecords(scene.edge_assets).length, + entity_asset_count: asRecords(scene.entity_assets).length, + geometry_asset_count: asRecords(scene.geometry_assets).length, + maximum_depth: Math.max( + ...nodes.map((node) => { + const source = asRecord(node.source); + return Array.isArray(source.component_path) ? source.component_path.length : 0; + }), + ), + node_count: nodes.length, + root_node_ids: nodes + .filter((node) => node.parent_node_id === null) + .map((node) => String(node.node_id)), + }; +} diff --git a/scene-contract/test/corpus.test.ts b/scene-contract/test/corpus.test.ts new file mode 100644 index 00000000..0728093d --- /dev/null +++ b/scene-contract/test/corpus.test.ts @@ -0,0 +1,1097 @@ +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import assert from "node:assert/strict"; +import test, { type TestContext } from "node:test"; +import { + canonicalJsonBytes, + canonicalZipBytes, + BASE_LIMITS, + computeSceneRevision, + DuplicateKeyError, + parseCanonicalJson, + parseStrictJson, + preflightAggregateCompressionRatio, + preflightArchiveMemberSizes, + preflightGlb, + preflightGlbCounts, + preflightInputArchiveSize, + preflightMemberCompressionRatio, + preflightZipBytes, + profileCross, + profileF32Bits, + profileNormalize, + issue, + report, + sha256, + validateConnectorBinding, + validateEntityAsset, + validateNormalizedProduct, + validatePresentation, + validateSceneManifest, + validateScenePackage, + computePackageBudgetTotals, + jsonResourceIssues, + packageBudgetIssues, + resourceCountIssues, + withSceneRevision, + type SceneResourceLimits, +} from "../src/index.js"; +import { validateSceneSchema, validateSchemaPointer, type SchemaArtifact } from "../src/schema.js"; +import { + applySceneFieldCase, + corpusBlobs, + sceneShapeFacts, + type ExpectedIssue, + type PackageCase, + type SceneFieldCase, + type SceneShapeCase, +} from "./corpus-support.js"; + +interface ValidationCase { name: string; valid: boolean; expected: ExpectedIssue | null; payload_base64: string } +interface GlbCase { name: string; valid: boolean; error: string | null; expected_kind: "triangle" | "line"; kind: "triangle" | "line" | null; payload_base64: string } +interface ZipCase { name: string; valid: boolean; error: string | null; used_deflate: boolean | null; payload_base64: string } +interface NumericVector { name: string; operation: "f32" | "cross" | "normalize"; input_bits: string[] | string[][]; expected_bits?: string | string[]; error?: string; valid: boolean } +interface ResourceCase { name: string; operation: string; parameters: Record; valid: boolean; error?: string | null; expected?: ExpectedIssue | null } +interface Artifact { base64: string; sha256: string; uri?: string; revision?: string } +interface RevisionVector { name: string; canonical_base64: string; draft_base64: string; revision: string; sha256: string } +interface SchemaMutation { operation: "delete" | "set"; path: (string | number)[]; value?: unknown } +interface SchemaFieldMatrix { + artifact: SchemaArtifact; + base: Record; + cases: { mutations: SchemaMutation[]; name: string; valid: boolean }[]; + schema_pointer: string; + variant: string; +} +interface Corpus { + format_version: string; + artifacts: Record; + blobs: Record; + jcs_vectors: { name: string; input: unknown; canonical_base64: string; sha256: string }[]; + manifest_cases: ValidationCase[]; + entity_cases: ValidationCase[]; + presentation_cases: ValidationCase[]; + connector_binding_cases: ValidationCase[]; + normalized_product_cases: ValidationCase[]; + package_cases: PackageCase[]; + glb_cases: GlbCase[]; + numeric_vectors: NumericVector[]; + resource_cases: ResourceCase[]; + resource_limits: Record; + revision_vectors: RevisionVector[]; + scene_field_cases: SceneFieldCase[]; + scene_shape_cases: SceneShapeCase[]; + schema_field_matrices: SchemaFieldMatrix[]; + zip_cases: ZipCase[]; +} + +const here = dirname(fileURLToPath(import.meta.url)); +const corpusPath = resolve(here, "../../../test/fixtures/scene-contract/corpus.json"); +const corpus = parseStrictJson(readFileSync(corpusPath)) as Corpus; +const decode = (value: string) => Buffer.from(value, "base64"); + +test("shared corpus has every Scene 1.0 parity section", () => { + assert.equal(corpus.format_version, "1.0"); + for (const section of [ + corpus.jcs_vectors, + corpus.manifest_cases, + corpus.entity_cases, + corpus.presentation_cases, + corpus.connector_binding_cases, + corpus.normalized_product_cases, + corpus.package_cases, + corpus.glb_cases, + corpus.numeric_vectors, + corpus.resource_cases, + corpus.revision_vectors, + corpus.scene_field_cases, + corpus.scene_shape_cases, + corpus.schema_field_matrices, + corpus.zip_cases, + ]) assert.ok(section.length > 0); +}); + +function applySchemaMutations(base: Record, mutations: SchemaMutation[]): Record { + const result = structuredClone(base); + for (const mutation of mutations) { + let current: Record = result; + for (const part of mutation.path.slice(0, -1)) current = current[part] as Record; + const field = mutation.path.at(-1)!; + if (mutation.operation === "delete") delete current[field]; + else current[field] = structuredClone(mutation.value); + } + return result; +} + +test("all closed schema records and discriminator variants replay shared field matrices", async (context) => { + for (const matrix of corpus.schema_field_matrices) await context.test( + `${matrix.artifact}:${matrix.schema_pointer}:${matrix.variant}`, + async (matrixContext) => { + for (const item of matrix.cases) await matrixContext.test(item.name, () => { + const value = applySchemaMutations(matrix.base, item.mutations); + assert.equal(validateSchemaPointer(matrix.artifact, matrix.schema_pointer, value), item.valid); + }); + }, + ); +}); + +test("shared positive case names cannot drift to negative expectations", () => { + const positiveNames: string[] = []; + for (const [sectionName, value] of Object.entries(corpus)) { + if (!Array.isArray(value)) continue; + for (const item of value) { + if (item === null || typeof item !== "object" || Array.isArray(item)) continue; + const record = item as Record; + if ( + typeof record.name !== "string" + || (!record.name.startsWith("valid_") && record.name !== "nullable_fields_nonnull") + ) continue; + const label = `${sectionName}:${record.name}`; + positiveNames.push(label); + assert.equal(record.valid, true, label); + if (Object.hasOwn(record, "expected")) assert.equal(record.expected, null, label); + if (Object.hasOwn(record, "error")) assert.equal(record.error, null, label); + } + } + assert.equal(positiveNames.length, 30); +}); + +test("strict JSON rejects duplicate keys and protects ordinary object semantics", () => { + assert.throws(() => parseStrictJson(Buffer.from('{"a":1,"a":2}')), DuplicateKeyError); + const value = parseStrictJson(Buffer.from('{"__proto__":{"polluted":true}}')) as Record; + assert.equal(Object.hasOwn(value, "__proto__"), true); + assert.equal(({} as { polluted?: boolean }).polluted, undefined); +}); + +test("canonical JSON accepts finite numbers and rejects non-finite numbers", () => { + assert.equal(canonicalJsonBytes(1e30).toString("utf8"), "1e+30"); + for (const value of [Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]) { + assert.throws(() => canonicalJsonBytes(value), /finite/); + } + assert.equal(canonicalJsonBytes(1.25).toString("utf8"), "1.25"); +}); + +test("strict parsing accepts valid noncanonical JSON while canonical parsing rejects it", () => { + const bytes = Buffer.from('{"b":1, "a":2}'); + assert.equal((parseStrictJson(bytes) as Record).a, 2); + assert.throws(() => parseCanonicalJson(bytes), /canonical/); +}); + +test("public validator resource overflows remain budget issues", () => { + const scene = validScene(); + const sceneBytes = canonicalJsonBytes(scene); + const collectionResult = validateSceneManifest(scene, { ...BASE_LIMITS, definitions: 0 }); + const serializedResult = validateSceneManifest(scene, { + ...BASE_LIMITS, + scene_json_bytes: sceneBytes.length - 1, + }); + + assert.deepEqual( + collectionResult.firstError === null + ? null + : [collectionResult.firstError.code, collectionResult.firstError.phase, collectionResult.firstError.path], + ["resource_limit_exceeded", "budget", "/definitions"], + ); + assert.deepEqual( + serializedResult.firstError === null + ? null + : [serializedResult.firstError.code, serializedResult.firstError.phase, serializedResult.firstError.path], + ["resource_limit_exceeded", "budget", ""], + ); +}); + +test("reports are deterministic by phase, UTF-8 rule ID, and UTF-8 pointer", () => { + const result = report([ + issue("z", "/b", "later path", "semantic"), + issue("a", "/z", "later code", "semantic"), + issue("a", "/a", "earlier pointer", "semantic"), + issue("z", "/z", "structure first", "structure"), + issue("a", "/a", "duplicate is ignored", "semantic"), + ]); + assert.deepEqual( + result.issues.map(({ phase, code, path }) => [phase, code, path]), + [ + ["structure", "z", "/z"], + ["semantic", "a", "/a"], + ["semantic", "a", "/z"], + ["semantic", "z", "/b"], + ], + ); +}); + +test("RFC 8785 vectors reproduce exact bytes and hashes", async (context) => { + for (const vector of corpus.jcs_vectors) await context.test(vector.name, () => { + const canonical = canonicalJsonBytes(vector.input); + assert.deepEqual(canonical, decode(vector.canonical_base64)); + assert.equal(sha256(canonical), vector.sha256); + }); +}); + +test("scene artifact revision and content hash are exact", () => { + const bytes = decode(corpus.artifacts.scene.base64); + const scene = parseStrictJson(bytes) as Record; + assert.equal(computeSceneRevision(scene), corpus.artifacts.scene.revision); + assert.equal(sha256(bytes), corpus.artifacts.scene.sha256); +}); + +test("all manifest cases match validity and expected first issue", async (context) => { + for (const item of corpus.manifest_cases) await context.test(item.name, () => { + const result = validateSceneManifest(decode(item.payload_base64)); + assert.equal(result.valid, item.valid); + if (item.expected !== null) { + assert.equal(result.firstError?.code, item.expected.code); + assert.equal(result.firstError?.path, item.expected.path); + } + }); +}); + +test("all entity cases match validity and expected first issue", async (context) => { + for (const item of corpus.entity_cases) await context.test(item.name, () => { + const result = validateEntityAsset(decode(item.payload_base64)); + assert.equal(result.valid, item.valid); + if (item.expected !== null) { + assert.equal(result.firstError?.code, item.expected.code); + assert.equal(result.firstError?.path, item.expected.path); + } + }); +}); + +async function assertValidationCases( + context: TestContext, + cases: ValidationCase[], + validate: (value: unknown) => ReturnType, +): Promise { + for (const item of cases) await context.test(item.name, () => { + const result = validate(decode(item.payload_base64)); + assert.equal(result.valid, item.valid); + if (item.expected !== null) { + assert.equal(result.firstError?.code, item.expected.code); + assert.equal(result.firstError?.path, item.expected.path); + } + }); +} + +test("all presentation cases match validity and expected first issue", async (context) => { + await assertValidationCases(context, corpus.presentation_cases, validatePresentation); +}); + +test("all connector binding cases match validity and expected first issue", async (context) => { + await assertValidationCases(context, corpus.connector_binding_cases, validateConnectorBinding); +}); + +test("all normalized product cases match validity and expected first issue", async (context) => { + await assertValidationCases(context, corpus.normalized_product_cases, validateNormalizedProduct); +}); + +test("presentation rejects a non-rigid camera transform", () => { + const valid = corpus.presentation_cases.find((item) => item.valid); + assert.ok(valid !== undefined); + const presentation = asRecord(parseStrictJson(decode(valid.payload_base64))); + const camera = asRecords(presentation.cameras)[0]; + asRecord(camera.transform).x_axis = [2, 0, 0]; + const result = validatePresentation(presentation); + assert.equal(result.firstError?.code, "transform_invalid"); + assert.equal(result.firstError?.path, "/cameras/0/transform"); +}); + +function artifactBlobs(): Map { + const result = new Map(); + for (const artifact of Object.values(corpus.artifacts)) { + if (artifact.uri !== undefined) result.set(artifact.uri, decode(artifact.base64)); + } + return result; +} + +type JsonRecord = Record; + +function asRecord(value: unknown): JsonRecord { + assert.ok(value !== null && typeof value === "object" && !Array.isArray(value)); + return value as JsonRecord; +} + +function asRecords(value: unknown): JsonRecord[] { + assert.ok(Array.isArray(value)); + return value.map(asRecord); +} + +function validScene(): JsonRecord { + return asRecord(parseStrictJson(decode(corpus.artifacts.scene.base64))); +} + +function validEntities(): JsonRecord { + return asRecord(parseStrictJson(decode(corpus.artifacts.entities.base64))); +} + +function operationSource(path: string, callText: string): JsonRecord { + const source: JsonRecord = { + schema_version: "1.0", + path, + path_kind: "project_relative", + line: 1, + column: 7, + end_line: 1, + end_column: 7 + Array.from(callText).length, + call_text: callText, + callsite_id: "", + assignment_targets: ["body"], + }; + const material = [ + source.path, + source.line, + source.column, + source.end_line, + source.end_column, + source.call_text, + ].map(String).join("\x1f"); + source.callsite_id = `callsite_${sha256(Buffer.from(material, "utf8")).slice("sha256:".length, "sha256:".length + 16)}`; + return source; +} + +function embeddedSourcePackage(): { + blobs: Map; + manifest: JsonRecord; + model: JsonRecord; + sourcePath: string; + sourceUri: string; +} { + const scene = validScene(); + const sidecar = validEntities(); + makeModelScene(scene, sidecar, "shape"); + + const definition = asRecords(scene.definitions)[0]; + const definitionId = "definition/root/shape/model/graph/node/0"; + definition.definition_id = definitionId; + asRecords(scene.nodes)[0].definition_id = definitionId; + sidecar.definition_id = definitionId; + + const callText = "scad.make_box_rsolid(width=1)"; + const sourcePath = "models/box.py"; + const sourceUri = `sources/${sourcePath}`; + const sourceBytes = Buffer.from(`body = ${callText}\n`, "utf8"); + const model: JsonRecord = { + schema_version: "2.0", + graph: { + graph_id: "graph", + nodes: [{ + node_id: "node", + op: "make_box_rsolid", + params: { width: 1 }, + inputs: [], + output_count: 1, + source: operationSource(sourcePath, callText), + }], + }, + leaf_ids: ["node"], + }; + const modelBytes = canonicalJsonBytes(model); + scene.source = { + kind: "model", + graph_id: "graph", + model_schema_version: "2.0", + artifact_hash: sha256(modelBytes), + embedded_artifact_uri: "model/model.json", + embedded_artifact_byte_length: modelBytes.length, + source_files: [{ + path: sourcePath, + uri: sourceUri, + media_type: "text/x-python; charset=utf-8", + byte_length: sourceBytes.length, + content_hash: sha256(sourceBytes), + }], + }; + asRecord(scene.compile_options).embed_source = true; + const replaced = replaceEntitySidecar(scene, sidecar); + replaced.blobs.set("model/model.json", modelBytes); + replaced.blobs.set(sourceUri, sourceBytes); + scene.revision = computeSceneRevision(scene); + return { blobs: replaced.blobs, manifest: scene, model, sourcePath, sourceUri }; +} + +function replaceEmbeddedModel( + fixture: ReturnType, +): void { + const payload = canonicalJsonBytes(fixture.model); + fixture.blobs.set("model/model.json", payload); + const source = asRecord(fixture.manifest.source); + source.artifact_hash = sha256(payload); + source.embedded_artifact_byte_length = payload.length; + fixture.manifest.revision = computeSceneRevision(fixture.manifest); +} + +function replaceEntitySidecar( + scene: JsonRecord, + sidecar: JsonRecord, +): { manifest: Buffer; blobs: Map; entityUri: string } { + const entityBytes = canonicalJsonBytes(sidecar); + const entityHash = sha256(entityBytes); + const entityUri = `entities/sha256-${entityHash.slice("sha256:".length)}.json`; + const entityRecord = asRecords(scene.entity_assets)[0]; + const oldUri = entityRecord.uri as string; + Object.assign(entityRecord, { + byte_length: entityBytes.length, + content_hash: entityHash, + entity_asset_id: entityHash, + uri: entityUri, + }); + asRecords(scene.definitions)[0].entity_asset_id = entityHash; + scene.revision = computeSceneRevision(scene); + const blobs = artifactBlobs(); + blobs.delete(oldUri); + blobs.set(entityUri, entityBytes); + return { manifest: canonicalJsonBytes(scene), blobs, entityUri }; +} + +function entityIndex(sidecar: JsonRecord, kind: string): number { + const index = asRecords(sidecar.entities).findIndex((entity) => entity.kind === kind); + assert.notEqual(index, -1); + return index; +} + +function assertFirstIssue( + result: ReturnType, + code: string, + path: string, +): void { + assert.equal(result.valid, false); + assert.equal(result.firstError?.code, code); + assert.equal(result.firstError?.path, path); +} + +test("scene semantic references and content identities reject independent mutations", async (context) => { + const missingHash = `sha256:${"f".repeat(64)}`; + const cases: [string, (scene: JsonRecord) => void, string, string][] = [ + ["missing definition appearance", (scene) => { + asRecords(scene.definitions)[0].appearance_id = `appearance/evaluated/${"f".repeat(64)}`; + }, "reference_missing", "/definitions/0/appearance_id"], + ["missing definition geometry asset", (scene) => { + asRecords(scene.definitions)[0].geometry_asset_id = missingHash; + }, "reference_missing", "/definitions"], + ["missing node appearance override", (scene) => { + asRecords(scene.nodes)[0].appearance_override_id = `appearance/evaluated/${"f".repeat(64)}`; + }, "reference_missing", "/nodes/0/appearance_override_id"], + ["geometry asset ID differs from content hash", (scene) => { + asRecords(scene.geometry_assets)[0].content_hash = missingHash; + }, "source_matrix_invalid", "/geometry_assets/0/asset_id"], + ["entity asset ID differs from content hash", (scene) => { + asRecords(scene.entity_assets)[0].content_hash = missingHash; + }, "source_matrix_invalid", "/entity_assets/0/entity_asset_id"], + ["entity asset URI is not content-derived", (scene) => { + asRecords(scene.entity_assets)[0].uri = "entities/noncanonical.json"; + }, "source_matrix_invalid", "/entity_assets/0/uri"], + ["geometry tessellation differs from compile options", (scene) => { + asRecord(asRecords(scene.geometry_assets)[0].tessellation).linear_tolerance = 0.02; + }, "source_matrix_invalid", "/geometry_assets/0/tessellation/linear_tolerance"], + ["appearance ID is not content-derived", (scene) => { + const appearanceId = `appearance/evaluated/${"f".repeat(64)}`; + asRecords(scene.appearances)[0].appearance_id = appearanceId; + asRecords(scene.definitions)[0].appearance_id = appearanceId; + }, "source_matrix_invalid", "/appearances/0/appearance_id"], + ["manual source cannot request embedding", (scene) => { + asRecord(scene.compile_options).embed_source = true; + }, "source_matrix_invalid", "/source"], + ["definition ID must be source-derived", (scene) => { + asRecord(scene.source).source_id = "other"; + asRecord(asRecords(scene.definitions)[0].source).source_id = "other"; + }, "source_matrix_invalid", "/definitions/0/definition_id"], + ]; + for (const [name, mutate, code, path] of cases) await context.test(name, () => { + const scene = validScene(); + mutate(scene); + scene.revision = computeSceneRevision(scene); + assertFirstIssue(validateSceneManifest(scene), code, path); + }); +}); + +function addSceneCamera(scene: JsonRecord): JsonRecord { + const camera = { + camera_id: "camera/test", + name: "Test camera", + projection: "perspective", + parent_node_id: null, + transform: structuredClone(asRecords(scene.nodes)[0].transform), + near: 1, + far: 10, + vertical_fov_degrees: 45, + }; + assert.ok(Array.isArray(scene.cameras)); + scene.cameras.push(camera); + return camera; +} + +test("scene cameras reject dangling parents and reversed clipping bounds independently", async (context) => { + await context.test("dangling parent", () => { + const scene = validScene(); + addSceneCamera(scene).parent_node_id = "instance/missing"; + scene.revision = computeSceneRevision(scene); + assertFirstIssue(validateSceneManifest(scene), "reference_missing", "/cameras/0/parent_node_id"); + }); + await context.test("far does not exceed near", () => { + const scene = validScene(); + addSceneCamera(scene).far = 1; + scene.revision = computeSceneRevision(scene); + assertFirstIssue(validateSceneManifest(scene), "bounds_invalid", "/cameras/0/far"); + }); +}); + +test("entity kind, frame, status, position, and bounds semantics reject independent mutations", async (context) => { + const cases: [string, string, (entity: JsonRecord) => void, string, (index: number) => string][] = [ + ["geometry kind", "solid", (entity) => { + entity.geometry = { type: "point", position: [0, 0, 0] }; + }, "entity_topology_invalid", (index) => `/entities/${index}/geometry/type`], + ["required connector frame", "face", (entity) => { + entity.sdk_connector_frame = null; + }, "connector_invalid", (index) => `/entities/${index}/sdk_connector_frame`], + ["render status", "vertex", (entity) => { + entity.render_status = "degenerate"; + }, "entity_topology_invalid", (index) => `/entities/${index}/render_status`], + ["vertex property position", "vertex", (entity) => { + const position = [...(asRecord(entity.properties).position as number[])]; + position[0] += 1; + asRecord(entity.properties).position = position; + }, "bounds_invalid", (index) => `/entities/${index}/properties/position`], + ["reversed bounds", "solid", (entity) => { + const bounds = asRecord(asRecord(entity.properties).bounds); + const maximum = bounds.max as number[]; + const minimum = [...(bounds.min as number[])]; + minimum[0] = maximum[0] + 1; + bounds.min = minimum; + }, "bounds_invalid", (index) => `/entities/${index}/properties/bounds`], + ]; + for (const [name, kind, mutate, code, path] of cases) await context.test(name, () => { + const sidecar = validEntities(); + const index = entityIndex(sidecar, kind); + mutate(asRecords(sidecar.entities)[index]); + assertFirstIssue(validateEntityAsset(sidecar), code, path(index)); + }); +}); + +test("analytic geometry coordinates enforce the scene coordinate limit", async (context) => { + const cases: [string, string, (geometry: JsonRecord) => void][] = [ + ["point.position", "vertex", (geometry) => { geometry.position = [1e12 + 1, 0, 0]; }], + ["line.origin", "edge", (geometry) => { geometry.origin = [0, -(1e12 + 1), 0]; }], + ["plane.origin", "face", (geometry) => { geometry.origin = [0, 0, 1e12 + 1]; }], + ["circle.center", "edge", (geometry) => { + for (const key of Object.keys(geometry)) delete geometry[key]; + Object.assign(geometry, { + type: "circle", + center: [1e12 + 1, 0, 0], + normal: [0, 0, 1], + x_direction: [1, 0, 0], + radius: 1, + }); + }], + ]; + for (const [name, kind, mutate] of cases) await context.test(name, () => { + const sidecar = validEntities(); + const index = entityIndex(sidecar, kind); + const geometry = asRecord(asRecords(sidecar.entities)[index].geometry); + mutate(geometry); + const result = validateEntityAsset(sidecar); + assert.equal(result.valid, false); + assert.ok(result.issues.some((item) => + item.code === "analytic_geometry_invalid" && + item.path === `/entities/${index}/geometry/${name.split(".")[1]}` + )); + }); +}); + +test("package checks entity geometry engine version against the manifest", () => { + const scene = validScene(); + const sidecar = validEntities(); + asRecord(sidecar.geometry_engine).version = "different"; + const { manifest, blobs } = replaceEntitySidecar(scene, sidecar); + const result = validateScenePackage(manifest, blobs); + assert.ok(result.issues.some((item) => + item.code === "source_matrix_invalid" && item.path === "/definitions/0/entity_asset_id" + )); +}); + +test("package rejects entity source variants incompatible with the scene source", () => { + const scene = validScene(); + const sidecar = validEntities(); + asRecords(sidecar.entities)[0].source = { + kind: "imported_primitive", + source_element_id: "element", + }; + const { manifest, blobs, entityUri } = replaceEntitySidecar(scene, sidecar); + const result = validateScenePackage(manifest, blobs); + assert.ok(result.issues.some((item) => + item.code === "source_matrix_invalid" && item.path === `/${entityUri}/entities/0/source` + )); +}); + +function makeModelScene(scene: JsonRecord, sidecar: JsonRecord, definitionKind: "shape" | "part"): void { + scene.source = { + kind: "model", + graph_id: "graph", + model_schema_version: "2.0", + artifact_hash: `sha256:${"1".repeat(64)}`, + }; + const definition = asRecords(scene.definitions)[0]; + definition.kind = definitionKind; + definition.source = definitionKind === "part" + ? { + kind: "product_model", + root_id: "root", + semantic_type: "Part", + semantic_id: "Part", + graph_id: "graph", + node_id: "node", + output_slot: 0, + } + : { + kind: "model_output", + root_id: "root", + graph_id: "graph", + node_id: "node", + output_slot: 0, + }; + for (const entity of asRecords(sidecar.entities)) { + entity.source = { + kind: "model_output", + graph_id: "graph", + node_id: "node", + output_slot: 0, + }; + } +} + +test("package checks model entity source ownership fields", () => { + const scene = validScene(); + const sidecar = validEntities(); + makeModelScene(scene, sidecar, "shape"); + asRecord(asRecords(sidecar.entities)[0].source).node_id = "other-node"; + const { manifest, blobs, entityUri } = replaceEntitySidecar(scene, sidecar); + const result = validateScenePackage(manifest, blobs); + assert.ok(result.issues.some((item) => + item.code === "source_matrix_invalid" && item.path === `/${entityUri}/entities/0/source` + )); +}); + +test("embedded model and Python source package validates", () => { + const fixture = embeddedSourcePackage(); + const result = validateScenePackage(fixture.manifest, fixture.blobs); + assert.equal(result.valid, true, JSON.stringify(result.issues)); +}); + +test("manifest rejects archive-unsafe embedded Python paths", () => { + const fixture = embeddedSourcePackage(); + const sourceFile = asRecords(asRecord(fixture.manifest.source).source_files)[0]; + sourceFile.path = "models/../box.py"; + sourceFile.uri = "sources/models/../box.py"; + fixture.manifest.revision = computeSceneRevision(fixture.manifest); + + const result = validateSceneManifest(fixture.manifest); + assert.ok(result.issues.some((item) => + item.code === "source_matrix_invalid" && item.path === "/source/source_files/0/path" + )); +}); + +test("package rejects malformed operation source mappings", () => { + const fixture = embeddedSourcePackage(); + const graph = asRecord(fixture.model.graph); + const source = asRecord(asRecords(graph.nodes)[0].source); + delete source.callsite_id; + replaceEmbeddedModel(fixture); + + const result = validateScenePackage(fixture.manifest, fixture.blobs); + assert.ok(result.issues.some((item) => + item.code === "source_matrix_invalid" && item.path === "/model/model.json/graph/nodes/0/source" + )); +}); + +test("package rejects invalid UTF-8 Python source bytes", () => { + const fixture = embeddedSourcePackage(); + const payload = Buffer.from([0xff]); + fixture.blobs.set(fixture.sourceUri, payload); + const sourceFile = asRecords(asRecord(fixture.manifest.source).source_files)[0]; + sourceFile.byte_length = payload.length; + sourceFile.content_hash = sha256(payload); + fixture.manifest.revision = computeSceneRevision(fixture.manifest); + + const result = validateScenePackage(fixture.manifest, fixture.blobs); + assert.ok(result.issues.some((item) => + item.code === "invalid_utf8" && item.path === `/${fixture.sourceUri}` + )); +}); + +test("package binding status rules follow Python precedence", async (context) => { + await context.test("solid is always not_applicable", () => { + const scene = validScene(); + const sidecar = validEntities(); + const index = entityIndex(sidecar, "solid"); + asRecords(sidecar.entities)[index].connector_binding_status = "supported"; + const { manifest, blobs, entityUri } = replaceEntitySidecar(scene, sidecar); + const result = validateScenePackage(manifest, blobs); + const found = result.issues.find((item) => item.code === "connector_invalid" && item.path === `/${entityUri}/entities/${index}/connector_binding_status`); + assert.match(found?.message ?? "", /not_applicable/); + }); + + await context.test("non-part owner precedes scene source", () => { + const scene = validScene(); + const sidecar = validEntities(); + const index = entityIndex(sidecar, "face"); + asRecords(sidecar.entities)[index].connector_binding_status = "source_not_model"; + const { manifest, blobs, entityUri } = replaceEntitySidecar(scene, sidecar); + const result = validateScenePackage(manifest, blobs); + const found = result.issues.find((item) => item.code === "connector_invalid" && item.path === `/${entityUri}/entities/${index}/connector_binding_status`); + assert.match(found?.message ?? "", /owner_not_part/); + }); + + await context.test("non-model part requires source_not_model", () => { + const scene = validScene(); + const sidecar = validEntities(); + const definition = asRecords(scene.definitions)[0]; + definition.kind = "part"; + definition.source = { + kind: "product_manual", + root_id: "root", + semantic_type: "Part", + semantic_id: "Part", + }; + const entities = asRecords(sidecar.entities); + for (const entity of entities) { + if (entity.kind !== "solid") entity.connector_binding_status = "source_not_model"; + } + const index = entityIndex(sidecar, "face"); + entities[index].connector_binding_status = "supported"; + const { manifest, blobs, entityUri } = replaceEntitySidecar(scene, sidecar); + const result = validateScenePackage(manifest, blobs); + const found = result.issues.find((item) => item.code === "connector_invalid" && item.path === `/${entityUri}/entities/${index}/connector_binding_status`); + assert.match(found?.message ?? "", /source_not_model/); + }); + + await context.test("model part null frame requires frame_undefined", () => { + const scene = validScene(); + const sidecar = validEntities(); + makeModelScene(scene, sidecar, "part"); + const entities = asRecords(sidecar.entities); + for (const entity of entities) { + if (entity.kind !== "solid") entity.connector_binding_status = "supported"; + } + const index = entityIndex(sidecar, "edge"); + entities[index].sdk_connector_frame = null; + entities[index].connector_binding_status = "owner_not_part"; + const { manifest, blobs, entityUri } = replaceEntitySidecar(scene, sidecar); + const result = validateScenePackage(manifest, blobs); + const found = result.issues.find((item) => item.code === "connector_invalid" && item.path === `/${entityUri}/entities/${index}/connector_binding_status`); + assert.match(found?.message ?? "", /frame_undefined/); + }); +}); + +test("all package cases match validity and expected first issue", async (context) => { + for (const item of corpus.package_cases) await context.test(item.name, () => { + const result = validateScenePackage( + decode(item.manifest_base64), + corpusBlobs(corpus.blobs, item), + ); + assert.equal(result.valid, item.valid); + if (item.expected !== null) { + assert.equal(result.firstError?.code, item.expected.code); + assert.equal(result.firstError?.path, item.expected.path); + } +}); + +test("accepted package fixtures cover every connector binding status", () => { + const statuses = new Set(); + for (const item of [...corpus.package_cases, ...corpus.scene_shape_cases]) { + if (!item.valid) continue; + for (const [uri, payload] of corpusBlobs(corpus.blobs, item)) { + if (!uri.startsWith("entities/")) continue; + const sidecar = asRecord(parseCanonicalJson(payload)); + for (const entity of asRecords(sidecar.entities)) { + statuses.add(String(entity.connector_binding_status)); + } + } + } + assert.deepEqual([...statuses].sort(), [ + "frame_undefined", + "not_applicable", + "owner_not_part", + "selector_ambiguous", + "selector_unstable", + "source_not_model", + "supported", + ]); +}); +}); + +test("scene field matrix replays independently", async (context) => { + const scene = validScene(); + for (const item of corpus.scene_field_cases) await context.test(item.name, () => { + const result = validateSceneManifest( + canonicalJsonBytes(applySceneFieldCase(scene, item)), + ); + assert.equal(result.valid, item.valid); + assert.equal(result.firstError?.code, item.expected?.code); + assert.equal(result.firstError?.path, item.expected?.path); + }); +}); + +test("scene shapes validate, round trip, and characterize asset reuse", async (context) => { + for (const item of corpus.scene_shape_cases) await context.test(item.name, () => { + const manifest = decode(item.manifest_base64); + const scene = asRecord(parseCanonicalJson(manifest)); + const result = validateScenePackage(manifest, corpusBlobs(corpus.blobs, item)); + assert.equal(result.valid, item.valid); + assert.equal(result.firstError?.code, item.expected?.code); + assert.equal(result.firstError?.path, item.expected?.path); + assert.deepEqual(canonicalJsonBytes(scene), manifest); + assert.deepEqual( + canonicalJsonBytes(sceneShapeFacts(scene)), + canonicalJsonBytes(item.expected_shape), + ); + + const definitions = new Map( + asRecords(scene.definitions).map((definition) => [ + String(definition.definition_id), + definition, + ]), + ); + for (const [definitionId, count] of Object.entries( + item.expected_shape.definition_occurrence_counts, + )) { + if (count <= 1) continue; + const occurrences = asRecords(scene.nodes).filter( + (node) => node.definition_id === definitionId, + ); + assert.equal(occurrences.length, count); + assert.equal(new Set(occurrences.map((node) => node.definition_id)).size, 1); + assert.notEqual(definitions.get(definitionId)?.geometry_asset_id, null); + } + }); +}); + +test("two-pass revision vectors reproduce exact drafts, revisions, and bytes", async (context) => { + for (const vector of corpus.revision_vectors) await context.test(vector.name, () => { + const draftBytes = decode(vector.draft_base64); + const draft = asRecord(parseCanonicalJson(draftBytes)); + const sceneBytes = decode(vector.canonical_base64); + const scene = withSceneRevision(draft); + assert.deepEqual(canonicalJsonBytes(draft), draftBytes); + assert.equal(scene.revision, vector.revision); + assert.deepEqual(canonicalJsonBytes(scene), sceneBytes); + assert.equal(sha256(sceneBytes), vector.sha256); + }); +}); + +test("all GLB cases match acceptance, kind, and exact rejection", async (context) => { + for (const item of corpus.glb_cases) await context.test(item.name, () => { + if (item.valid) { + const result = preflightGlb(decode(item.payload_base64), item.expected_kind); + assert.equal(result.kind, item.kind); + } else { + assert.throws(() => preflightGlb(decode(item.payload_base64), item.expected_kind), (error) => { + assert.equal((error as Error).message, item.error); + return true; + }); + } + }); +}); + +test("all ZIP cases match acceptance, deflate use, and exact rejection", async (context) => { + for (const item of corpus.zip_cases) await context.test(item.name, () => { + if (item.valid) { + const result = preflightZipBytes(decode(item.payload_base64)); + assert.equal(result.usedDeflate, item.used_deflate); + } else { + assert.throws(() => preflightZipBytes(decode(item.payload_base64)), (error) => { + assert.equal((error as Error).message, item.error); + return true; + }); + } + }); +}); + +function f64FromHex(value: string): number { + return Buffer.from(value, "hex").readDoubleBE(0); +} + +function f64Hex(value: number): string { + const bytes = Buffer.allocUnsafe(8); + bytes.writeDoubleBE(value, 0); + return bytes.toString("hex"); +} + +test("numeric profile vectors reproduce exact IEEE-754 results", async (context) => { + for (const vector of corpus.numeric_vectors) await context.test(vector.name, () => { + try { + let actual: string | string[]; + if (vector.operation === "f32") { + const input = vector.input_bits as string[]; + actual = profileF32Bits(f64FromHex(input[0])).toString(16).padStart(8, "0"); + } else if (vector.operation === "cross") { + const [left, right] = (vector.input_bits as string[][]).map( + (input) => input.map(f64FromHex) as [number, number, number], + ); + actual = profileCross(left, right).map(f64Hex); + } else { + const input = (vector.input_bits as string[][])[0].map(f64FromHex) as [number, number, number]; + actual = profileNormalize(input).map((component) => + profileF32Bits(component).toString(16).padStart(8, "0") + ); + } + assert.equal(vector.valid, true); + assert.deepEqual(actual, vector.expected_bits); + } catch (error) { + assert.equal(vector.valid, false); + assert.equal((error as Error).message, vector.error); + } + }); +}); + +test("resource profile and exact boundary cases match Python", async (context) => { + assert.deepEqual(BASE_LIMITS, Object.fromEntries(Object.entries(corpus.resource_limits))); + const scene = validScene(); + + for (const item of corpus.resource_cases) await context.test(item.name, () => { + let valid = false; + let error: string | null = null; + let first: ExpectedIssue | null = null; + try { + const parameters = item.parameters; + const limits = { ...BASE_LIMITS, ...(parameters.limits as Partial ?? {}) }; + if (item.operation === "input_archive_size") { + preflightInputArchiveSize(parameters.size as number, limits); + valid = true; + } else if (item.operation === "archive_member_sizes" || item.operation === "archive_member_count") { + let sizes: Map; + if (item.operation === "archive_member_sizes") { + sizes = new Map(Object.entries(parameters.sizes as Record)); + } else { + sizes = new Map([["scene.json", 0]]); + for (let index = 0; index < (parameters.count as number) - 1; index += 1) { + sizes.set(`x/${index.toString().padStart(5, "0")}`, 0); + } + } + preflightArchiveMemberSizes(sizes, limits); + valid = true; + } else if (item.operation === "aggregate_compression_ratio" || item.operation === "member_compression_ratio") { + const callback = item.operation === "aggregate_compression_ratio" + ? preflightAggregateCompressionRatio + : preflightMemberCompressionRatio; + callback(parameters.uncompressed_size as number, parameters.compressed_size as number, limits); + valid = true; + } else if (item.operation === "json_depth") { + const value: JsonRecord = {}; + let current = value; + for (let index = 0; index < (parameters.depth as number); index += 1) { + current.x = {}; + current = asRecord(current.x); + } + const result = report(jsonResourceIssues(value, limits)); + valid = result.valid; + first = result.firstError === null ? null : { code: result.firstError.code, path: result.firstError.path }; + } else if (item.operation === "json_domain") { + const text = parameters.text as string; + const kind = parameters.kind as string; + const field = parameters.field as string | null; + let value: JsonRecord; + if (kind === "value") value = { value: text }; + else if (kind === "object_key") value = { [text]: 0 }; + else if (kind === "metadata_key") value = { metadata: { [text]: 0 } }; + else if (kind === "sdk_metadata_key") value = { sdk_metadata: { [text]: 0 } }; + else if (kind === "identifier") value = { [field ?? "node_id"]: text }; + else if (kind === "identifier_array") value = { [field ?? "component_path"]: [text] }; + else if (kind === "uri") value = { uri: text }; + else throw new Error(`unknown JSON domain kind: ${kind}`); + const result = report(jsonResourceIssues(value, limits)); + valid = result.valid; + first = result.firstError === null ? null : { code: result.firstError.code, path: result.firstError.path }; + } else if (item.operation === "resource_count") { + const count = parameters.count as number; + const kind = parameters.kind as string; + const field = parameters.field as string | null; + let value: JsonRecord; + if (kind === "collection") value = { [field!]: Array(count).fill(null) }; + else if (kind === "hierarchy") value = { nodes: [{ source: { component_path: Array(count).fill("x") } }] }; + else if (kind === "forwarded") { + value = { + connectors: Array.from({ length: count }, (_unused, index) => ({ + anchor_kind: "forwarded", + connector_snapshot_id: `c${index}`, + forwarded_from: { source_connector_snapshot_id: `c${index + 1}` }, + })), + }; + } else throw new Error(`unknown resource count kind: ${kind}`); + const result = report(resourceCountIssues(value, parameters.artifact as "scene" | "entities" | "presentation", limits)); + valid = result.valid; + first = result.firstError === null ? null : { code: result.firstError.code, path: result.firstError.path }; + } else if (item.operation === "glb_counts") { + preflightGlbCounts( + parameters.kind as "triangle" | "line", + parameters.vertex_count as number, + parameters.index_count as number, + limits, + ); + valid = true; + } else if (item.operation === "package_budget") { + const input = parameters.contributions as { + scene_json_bytes: number; + glb_decoded_buffer_bytes: number; + entity_json_bytes: number; + other_immutable_json_bytes: number; + entity_count: number; + entity_vertex_count: number; + triangle_vertex_count: number; + triangle_count: number; + line_vertex_count: number; + line_segment_count: number; + }; + const totals = computePackageBudgetTotals({ + sceneJsonBytes: input.scene_json_bytes, + glbDecodedBufferBytes: input.glb_decoded_buffer_bytes, + entityJsonBytes: input.entity_json_bytes, + otherImmutableJsonBytes: input.other_immutable_json_bytes, + entityCount: input.entity_count, + entityVertexCount: input.entity_vertex_count, + triangleVertexCount: input.triangle_vertex_count, + triangleCount: input.triangle_count, + lineVertexCount: input.line_vertex_count, + lineSegmentCount: input.line_segment_count, + }); + const result = report(packageBudgetIssues(totals, limits), "package"); + valid = result.valid; + first = result.firstError === null ? null : { code: result.firstError.code, path: result.firstError.path }; + } else if (item.operation === "scene_geometry_byte_length") { + let value = structuredClone(scene); + const byteLength = Number(parameters.value); + asRecords(value.geometry_assets)[0].byte_length = byteLength; + if (byteLength <= Number.MAX_SAFE_INTEGER) value = withSceneRevision(value); + const result = validateSceneManifest(value); + valid = result.valid; + first = result.firstError === null ? null : { code: result.firstError.code, path: result.firstError.path }; + } else if (item.operation === "scene_compile_option") { + const value = structuredClone(scene); + const field = parameters.field as string; + const number = parameters.value as number; + asRecord(value.compile_options)[field] = number; + asRecord(asRecords(value.geometry_assets)[0].tessellation)[field] = number; + if (field === "linear_tolerance") asRecord(asRecords(value.edge_assets)[0].tessellation)[field] = number; + const result = validateSceneManifest(withSceneRevision(value)); + valid = result.valid; + first = result.firstError === null ? null : { code: result.firstError.code, path: result.firstError.path }; + } else { + throw new Error(`unknown resource operation: ${item.operation}`); + } + } catch (caught) { + valid = false; + error = (caught as Error).message; + } + assert.equal(valid, item.valid); + if (Object.hasOwn(item, "error")) assert.equal(error, item.error ?? null); + if (item.expected !== undefined && item.expected !== null) { + assert.equal(first?.code, item.expected.code); + assert.equal(first?.path, item.expected.path); + } + }); +}); + +test("canonical stored ZIP reproduces the exact shared vector", () => { + const expected = decode(corpus.artifacts.canonical_zip.base64); + const archive = preflightZipBytes(expected); + assert.equal(archive.inputSize, archive.canonicalSize); + assert.deepEqual(canonicalZipBytes(archive.members), expected); + assert.equal(`sha256:${createHash("sha256").update(expected).digest("hex")}`, corpus.artifacts.canonical_zip.sha256); +}); diff --git a/scene-contract/test/documents.test.ts b/scene-contract/test/documents.test.ts new file mode 100644 index 00000000..9ce6488e --- /dev/null +++ b/scene-contract/test/documents.test.ts @@ -0,0 +1,165 @@ +import { readFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import assert from "node:assert/strict"; +import test from "node:test"; +import { + ConnectorBindingDocument, + ContractDocumentValidationError, + EntityDocument, + type ImmutableContractDocument, + NormalizedProductDocument, + parseCanonicalJson, + parseStrictJson, + PresentationDocument, + SceneDocument, + sha256, +} from "../src/index.js"; + +interface ValidationCase { + valid: boolean; + payload_base64: string; +} + +interface Corpus { + artifacts: Record; + presentation_cases: ValidationCase[]; + connector_binding_cases: ValidationCase[]; + normalized_product_cases: ValidationCase[]; +} + +interface TestFactory { + fromValue(value: unknown): ImmutableContractDocument; + parse(data: Uint8Array | string): ImmutableContractDocument; +} + +const here = dirname(fileURLToPath(import.meta.url)); +const corpus = parseStrictJson( + readFileSync(resolve(here, "../../../test/fixtures/scene-contract/corpus.json")), +) as Corpus; + +const validCase = (cases: ValidationCase[]): Buffer => { + const item = cases.find((candidate) => candidate.valid); + assert.ok(item !== undefined); + return Buffer.from(item.payload_base64, "base64"); +}; + +const documents: readonly [string, TestFactory, Buffer][] = [ + [ + "scene", + SceneDocument as unknown as TestFactory, + Buffer.from(corpus.artifacts.scene.base64, "base64"), + ], + [ + "entities", + EntityDocument as unknown as TestFactory, + Buffer.from(corpus.artifacts.entities.base64, "base64"), + ], + [ + "presentation", + PresentationDocument as unknown as TestFactory, + validCase(corpus.presentation_cases), + ], + [ + "connector binding", + ConnectorBindingDocument as unknown as TestFactory, + validCase(corpus.connector_binding_cases), + ], + [ + "normalized product", + NormalizedProductDocument as unknown as TestFactory, + validCase(corpus.normalized_product_cases), + ], +]; + +function record(value: unknown): Record { + assert.ok(value !== null && typeof value === "object" && !Array.isArray(value)); + return value as Record; +} + +function assertDeepFrozen(value: unknown): void { + if (value === null || typeof value !== "object") return; + assert.equal(Object.isFrozen(value), true); + for (const child of Object.values(value)) assertDeepFrozen(child); +} + +function nestedContainer(value: Record): Record | unknown[] { + const result = Object.values(value).find( + (child) => child !== null && typeof child === "object", + ); + assert.ok(result !== undefined); + return result as Record | unknown[]; +} + +test("all contract document factories construct, parse, validate, and round trip", () => { + for (const [name, factory, payload] of documents) { + const input = record(parseCanonicalJson(payload)); + const constructed = factory.fromValue(input); + const parsed = factory.parse(payload); + + assert.deepEqual(constructed.canonicalBytes, payload, name); + assert.deepEqual(parsed.canonicalBytes, payload, name); + assert.equal(constructed.canonicalHash, sha256(payload), name); + assert.deepEqual(constructed.toMutable(), parsed.toMutable(), name); + assert.deepEqual(factory.fromValue(constructed.value).canonicalBytes, payload, name); + } +}); + +test("contract documents resist nested mutation and isolate mutable copies", () => { + for (const [name, factory, payload] of documents) { + const input = record(parseCanonicalJson(payload)); + const document = factory.fromValue(input); + const expectedHash = document.canonicalHash; + const expectedBytes = document.canonicalBytes; + + assert.equal(Object.isFrozen(document), true, name); + assertDeepFrozen(document.value); + assert.throws(() => { + record(document.value).mutation = true; + }, TypeError, name); + const frozenNested = nestedContainer(record(document.value)); + assert.throws(() => { + if (Array.isArray(frozenNested)) frozenNested.push(null); + else frozenNested.mutation = true; + }, TypeError, name); + + input.mutation = true; + const firstCopy = record(document.toMutable()); + const secondCopy = record(document.toMutable()); + const mutableNested = nestedContainer(firstCopy); + if (Array.isArray(mutableNested)) mutableNested.push(null); + else mutableNested.mutation = true; + firstCopy.mutation = true; + + assert.equal(Object.hasOwn(record(document.value), "mutation"), false, name); + assert.equal(Object.hasOwn(secondCopy, "mutation"), false, name); + assert.notDeepEqual(firstCopy, secondCopy, name); + + const exposedBytes = document.canonicalBytes; + exposedBytes[0] ^= 0xff; + assert.deepEqual(document.canonicalBytes, expectedBytes, name); + assert.equal(document.canonicalHash, expectedHash, name); + } +}); + +test("document constructors reject invalid values, noncanonical input, and stale revisions", () => { + for (const [name, factory] of documents) { + assert.throws( + () => factory.fromValue({}), + ContractDocumentValidationError, + name, + ); + } + assert.throws(() => SceneDocument.parse('{ "schema_version": "1.0" }'), /canonical/); + + const scene = record( + parseCanonicalJson(Buffer.from(corpus.artifacts.scene.base64, "base64")), + ); + scene.revision = `sha256:${"0".repeat(64)}`; + assert.throws( + () => SceneDocument.fromValue(scene as never), + (error: unknown) => + error instanceof ContractDocumentValidationError && + error.report.firstError?.code === "revision_mismatch", + ); +}); diff --git a/scene-contract/test/package-budget.test.ts b/scene-contract/test/package-budget.test.ts new file mode 100644 index 00000000..919d7a1e --- /dev/null +++ b/scene-contract/test/package-budget.test.ts @@ -0,0 +1,262 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { + canonicalJsonBytes, + computeSceneRevision, + parseStrictJson, + sha256, +} from "../src/canonical.js"; +import { report } from "../src/report.js"; +import { + computePackageBudgetTotals, + packageBudgetIssues, + validateSceneManifest, + validateScenePackage, +} from "../src/validation.js"; + +type JsonRecord = Record; + +interface Artifact { + base64: string; + uri?: string; +} + +interface Corpus { + artifacts: Record; + presentation_cases: { valid: boolean; payload_base64: string }[]; +} + +const here = dirname(fileURLToPath(import.meta.url)); +const corpusPath = resolve(here, "../../../test/fixtures/scene-contract/corpus.json"); +const corpus = parseStrictJson(readFileSync(corpusPath)) as Corpus; +const decode = (value: string): Buffer => Buffer.from(value, "base64"); + +function asRecord(value: unknown): JsonRecord { + assert.ok(value !== null && typeof value === "object" && !Array.isArray(value)); + return value as JsonRecord; +} + +function asRecords(value: unknown): JsonRecord[] { + assert.ok(Array.isArray(value)); + return value.map(asRecord); +} + +function validScene(): JsonRecord { + return asRecord(parseStrictJson(decode(corpus.artifacts.scene.base64))); +} + +function artifactBlobs(): Map { + const result = new Map(); + for (const artifact of Object.values(corpus.artifacts)) { + if (artifact.uri !== undefined) result.set(artifact.uri, decode(artifact.base64)); + } + return result; +} + +function validPresentation(): JsonRecord { + const value = corpus.presentation_cases.find((item) => item.valid); + assert.ok(value !== undefined); + return asRecord(parseStrictJson(decode(value.payload_base64))); +} + +function utf8Compare(left: string, right: string): number { + return Buffer.compare(Buffer.from(left, "utf8"), Buffer.from(right, "utf8")); +} + +function attachPresentation(scene: JsonRecord, blobs: Map): { presentation: JsonRecord; blobs: Map } { + const presentation = validPresentation(); + const presentationId = presentation.presentation_id as string; + const expectedAppearanceIds = new Map(); + const sceneAppearances = asRecords(scene.appearances); + for (const authored of asRecords(presentation.appearances)) { + const evaluated: JsonRecord = { + alpha_mode: authored.alpha_mode, + base_color: authored.base_color, + double_sided: authored.double_sided, + edge_color: authored.edge_color, + metallic: authored.metallic, + name: authored.name, + roughness: authored.roughness, + sdk_metadata: {}, + source: { + appearance_name: authored.name, + kind: "presentation", + presentation_id: presentationId, + }, + }; + const appearanceId = `appearance/evaluated/${sha256(canonicalJsonBytes(evaluated)).slice("sha256:".length)}`; + expectedAppearanceIds.set(authored.name, appearanceId); + sceneAppearances.push({ appearance_id: appearanceId, ...evaluated }); + } + sceneAppearances.sort((left, right) => utf8Compare(left.appearance_id as string, right.appearance_id as string)); + scene.appearances = sceneAppearances; + + const nodeMap = new Map(asRecords(scene.nodes).map((node) => [node.node_id, node])); + for (const override of asRecords(presentation.node_overrides)) { + const node = nodeMap.get(override.node_id); + assert.ok(node !== undefined); + if (override.visible !== undefined) node.visible = override.visible; + if (override.appearance_name !== undefined) node.appearance_override_id = expectedAppearanceIds.get(override.appearance_name); + } + scene.cameras = asRecords(presentation.cameras).map((camera) => ({ + camera_id: `camera/${presentationId}/${String(camera.name)}`, + ...camera, + })); + + const presentationBytes = canonicalJsonBytes(presentation); + asRecord(scene.compile_options).embed_presentation = true; + scene.presentation_source = { + artifact_hash: sha256(presentationBytes), + embedded_artifact_byte_length: presentationBytes.length, + embedded_artifact_uri: "presentation/presentation.json", + presentation_id: presentationId, + schema_version: "1.0", + }; + scene.revision = computeSceneRevision(scene); + const resultBlobs = new Map(blobs); + resultBlobs.set("presentation/presentation.json", presentationBytes); + return { presentation, blobs: resultBlobs }; +} + +function replacePresentation(scene: JsonRecord, blobs: Map, payload: Buffer): Map { + const source = asRecord(scene.presentation_source); + source.artifact_hash = sha256(payload); + source.embedded_artifact_byte_length = payload.length; + scene.revision = computeSceneRevision(scene); + const result = new Map(blobs); + result.set("presentation/presentation.json", payload); + return result; +} + +test("package budget formula and first error match Python with declarative limits", () => { + const totals = computePackageBudgetTotals({ + sceneJsonBytes: 7, + glbDecodedBufferBytes: 11, + entityJsonBytes: 13, + otherImmutableJsonBytes: 17, + entityCount: 23, + entityVertexCount: 19, + triangleVertexCount: 29, + triangleCount: 31, + lineVertexCount: 37, + lineSegmentCount: 41, + }); + assert.deepEqual(totals, { + staticDecodedBufferBytes: 656, + entityCount: 23, + triangleVertexTotal: 29, + triangleTotal: 31, + lineVertexTotal: 37, + lineSegmentTotal: 41, + }); + assert.deepEqual(packageBudgetIssues(totals, { + static_decoded_buffer_bytes: 656, + entities_total: 23, + triangle_vertices_total: 29, + triangles_total: 31, + line_vertices_total: 37, + line_segments_total: 41, + }), []); + + const result = report(packageBudgetIssues(totals, { + static_decoded_buffer_bytes: 655, + entities_total: 22, + triangle_vertices_total: 28, + triangles_total: 30, + line_vertices_total: 36, + line_segments_total: 40, + }), "package"); + assert.deepEqual( + result.firstError === null + ? null + : [result.firstError.code, result.firstError.path, result.firstError.message], + ["resource_limit_exceeded", "", "total line GLB vertex count exceeds resource limit"], + ); +}); + +test("embedded presentation must be canonical and resolve exactly against the scene", () => { + const scene = validScene(); + const attached = attachPresentation(scene, artifactBlobs()); + const validResult = validateScenePackage(canonicalJsonBytes(scene), attached.blobs); + assert.equal(validResult.valid, true, JSON.stringify(validResult.issues)); + + const noncanonical = Buffer.from(JSON.stringify(attached.presentation, null, 2)); + const blobs = replacePresentation(scene, attached.blobs, noncanonical); + const result = validateScenePackage(canonicalJsonBytes(scene), blobs); + assert.deepEqual( + result.firstError === null ? null : [result.firstError.code, result.firstError.path], + ["noncanonical_json", ""], + ); +}); + +test("embedded presentation IDs and scene references are contextual", async (context) => { + const cases: [string, (presentation: JsonRecord) => void, string, string][] = [ + ["presentation ID", (presentation) => { presentation.presentation_id = "other"; }, "source_matrix_invalid", "/presentation/presentation.json/presentation_id"], + ["source scene ID", (presentation) => { presentation.source_scene_id = "other"; }, "source_matrix_invalid", "/presentation/presentation.json/source_scene_id"], + ["node override", (presentation) => { asRecords(presentation.node_overrides)[0].node_id = "instance/missing"; }, "source_matrix_invalid", "/presentation/presentation.json/node_overrides/0/node_id"], + ["camera parent", (presentation) => { asRecords(presentation.cameras)[0].parent_node_id = "instance/missing"; }, "source_matrix_invalid", "/presentation/presentation.json/cameras/0/parent_node_id"], + ]; + for (const [name, mutate, code, path] of cases) await context.test(name, () => { + const scene = validScene(); + const attached = attachPresentation(scene, artifactBlobs()); + mutate(attached.presentation); + const blobs = replacePresentation(scene, attached.blobs, canonicalJsonBytes(attached.presentation)); + const result = validateScenePackage(canonicalJsonBytes(scene), blobs); + assert.ok(result.issues.some((item) => item.code === code && item.path === path)); + }); +}); + +test("presentation appearance provenance and camera resolution are exact", () => { + const scene = validScene(); + const attached = attachPresentation(scene, artifactBlobs()); + const sceneAppearances = asRecords(scene.appearances); + const appearance = sceneAppearances.find((item) => item.source !== null && asRecord(item.source).kind === "presentation"); + assert.ok(appearance !== undefined); + asRecord(appearance.source).appearance_name = "Other"; + const draft = { ...appearance }; + delete draft.appearance_id; + const appearanceId = `appearance/evaluated/${sha256(canonicalJsonBytes(draft)).slice("sha256:".length)}`; + appearance.appearance_id = appearanceId; + asRecords(scene.nodes)[0].appearance_override_id = appearanceId; + sceneAppearances.sort((left, right) => utf8Compare(left.appearance_id as string, right.appearance_id as string)); + scene.appearances = sceneAppearances; + scene.cameras = []; + scene.revision = computeSceneRevision(scene); + + const result = validateScenePackage(canonicalJsonBytes(scene), attached.blobs); + const appearanceIndex = asRecords(scene.appearances).indexOf(appearance); + assert.ok(result.issues.some((item) => item.code === "source_matrix_invalid" && item.path === `/appearances/${appearanceIndex}/source/appearance_name`)); + assert.ok(result.issues.some((item) => item.code === "source_matrix_invalid" && item.path === "/presentation/presentation.json/cameras/0")); +}); + +test("product material provenance must match a Part definition root", () => { + const scene = validScene(); + const appearance = asRecords(scene.appearances)[0]; + appearance.source = { kind: "product_material", material_id: "steel", root_id: "other" }; + const draft = { ...appearance }; + delete draft.appearance_id; + const appearanceId = `appearance/evaluated/${sha256(canonicalJsonBytes(draft)).slice("sha256:".length)}`; + appearance.appearance_id = appearanceId; + asRecords(scene.definitions)[0].appearance_id = appearanceId; + scene.revision = computeSceneRevision(scene); + + const result = validateSceneManifest(scene); + assert.ok(result.issues.some((item) => item.code === "source_matrix_invalid" && item.path === "/appearances/0/source/root_id")); +}); + +test("one URI cannot declare contradictory hash, length, or media roles", () => { + const scene = validScene(); + const edge = asRecords(scene.edge_assets)[0]; + const oldUri = edge.uri as string; + edge.uri = asRecords(scene.geometry_assets)[0].uri; + scene.revision = computeSceneRevision(scene); + const blobs = artifactBlobs(); + blobs.delete(oldUri); + + const result = validateScenePackage(canonicalJsonBytes(scene), blobs); + assert.ok(result.issues.some((item) => item.code === "package_member_set_invalid")); + assert.ok(result.issues.some((item) => item.code === "source_matrix_invalid" && item.path === "/edge_assets/0/uri")); +}); diff --git a/scene-contract/test/rules.test.ts b/scene-contract/test/rules.test.ts new file mode 100644 index 00000000..052fddc8 --- /dev/null +++ b/scene-contract/test/rules.test.ts @@ -0,0 +1,81 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { issue, parseStrictJson, report, validateRuleRegistry } from "../src/index.js"; + +const contractRoot = resolve( + dirname(fileURLToPath(import.meta.url)), + "../../../src/simplecadapi/scene/contracts", +); + +function registry(): Record { + return structuredClone( + parseStrictJson(readFileSync(resolve(contractRoot, "rules/scene-1.0-rules.json"))), + ) as Record; +} + +function rules(value: Record): Record[] { + assert.ok(Array.isArray(value.rules)); + return value.rules as Record[]; +} + +test("rule registry rejects malformed shape, duplicates, and wrong ordering", () => { + const valid = registry(); + assert.equal(validateRuleRegistry(valid).size, rules(valid).length); + + const missingPrecedence = registry(); + delete rules(missingPrecedence)[0].precedence; + assert.throws(() => validateRuleRegistry(missingPrecedence), /precedence/); + + const duplicateId = registry(); + rules(duplicateId)[1].id = rules(duplicateId)[0].id; + assert.throws(() => validateRuleRegistry(duplicateId), /duplicate rule ID/); + + const duplicatePrecedence = registry(); + rules(duplicatePrecedence)[1].precedence = 0; + assert.throws(() => validateRuleRegistry(duplicatePrecedence), /duplicate precedence/); + + const wrongOrder = registry(); + [rules(wrongOrder)[0], rules(wrongOrder)[1]] = [rules(wrongOrder)[1], rules(wrongOrder)[0]]; + assert.throws(() => validateRuleRegistry(wrongOrder), /ordered by phase and precedence/); + + const wrongIdOrder = registry(); + [rules(wrongIdOrder)[0].id, rules(wrongIdOrder)[1].id] = [rules(wrongIdOrder)[1].id, rules(wrongIdOrder)[0].id]; + assert.throws(() => validateRuleRegistry(wrongIdOrder), /unsigned UTF-8 rule-ID order/); +}); + +test("registered precedence orders artifact reports", () => { + const result = report([ + issue("transform_invalid", "/z", "later registered rule"), + issue("bounds_invalid", "/z", "z message"), + issue("bounds_invalid", "/z", "a message"), + issue("bounds_invalid", "/a", "earlier pointer"), + ], "scene"); + assert.deepEqual(result.issues.map(({ code, path, message }) => [code, path, message]), [ + ["bounds_invalid", "/a", "earlier pointer"], + ["bounds_invalid", "/z", "a message"], + ["bounds_invalid", "/z", "z message"], + ["transform_invalid", "/z", "later registered rule"], + ]); +}); + +test("artifact reports reject unregistered, wrong-phase, and wrong-artifact issues", () => { + assert.throws( + () => report([issue("not_registered", "", "no authority")], "scene"), + /unregistered/, + ); + assert.throws( + () => report([issue("bounds_invalid", "", "wrong phase", "package")], "scene"), + /registered phase/, + ); + assert.throws( + () => report([issue("presentation_reference_invalid", "", "wrong artifact")], "scene"), + /does not apply/, + ); + assert.throws( + () => report([issue("duplicate_json_key", "/value", "wrong pointer", "parse")], "scene"), + /root pointer/, + ); +}); diff --git a/scene-contract/test/zip-resource.test.ts b/scene-contract/test/zip-resource.test.ts new file mode 100644 index 00000000..22799b2a --- /dev/null +++ b/scene-contract/test/zip-resource.test.ts @@ -0,0 +1,91 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { BASE_LIMITS, preflightZipBytes } from "../src/index.js"; + +function declaredDeflateZip( + compressed: Uint8Array, + uncompressedSize: number, + localUncompressedSize = uncompressedSize, +): Buffer { + const name = Buffer.from("scene.json", "ascii"); + const local = Buffer.alloc(30); + local.writeUInt32LE(0x04034b50, 0); + local.writeUInt16LE(20, 4); + local.writeUInt16LE(0x0800, 6); + local.writeUInt16LE(8, 8); + local.writeUInt16LE(0, 10); + local.writeUInt16LE(0x0021, 12); + local.writeUInt32LE(0, 14); + local.writeUInt32LE(compressed.byteLength, 18); + local.writeUInt32LE(localUncompressedSize, 22); + local.writeUInt16LE(name.length, 26); + local.writeUInt16LE(0, 28); + + const centralOffset = local.length + name.length + compressed.byteLength; + const central = Buffer.alloc(46); + central.writeUInt32LE(0x02014b50, 0); + central.writeUInt16LE(0x0314, 4); + central.writeUInt16LE(20, 6); + central.writeUInt16LE(0x0800, 8); + central.writeUInt16LE(8, 10); + central.writeUInt16LE(0, 12); + central.writeUInt16LE(0x0021, 14); + central.writeUInt32LE(0, 16); + central.writeUInt32LE(compressed.byteLength, 20); + central.writeUInt32LE(uncompressedSize, 24); + central.writeUInt16LE(name.length, 28); + central.writeUInt16LE(0, 30); + central.writeUInt16LE(0, 32); + central.writeUInt16LE(0, 34); + central.writeUInt16LE(0, 36); + central.writeUInt32LE(0x81a40000, 38); + central.writeUInt32LE(0, 42); + + const eocd = Buffer.alloc(22); + eocd.writeUInt32LE(0x06054b50, 0); + eocd.writeUInt16LE(0, 4); + eocd.writeUInt16LE(0, 6); + eocd.writeUInt16LE(1, 8); + eocd.writeUInt16LE(1, 10); + eocd.writeUInt32LE(central.length + name.length, 12); + eocd.writeUInt32LE(centralOffset, 16); + eocd.writeUInt16LE(0, 20); + return Buffer.concat([local, name, compressed, central, name, eocd]); +} + +function assertError(archive: Uint8Array, expected: string): void { + assert.throws(() => preflightZipBytes(archive), (error) => { + assert.equal((error as Error).message, expected); + return true; + }); +} + +test("aggregate ratio uses cross-checked declarations before inflate", () => { + const compressed = Buffer.from([0]); + const template = declaredDeflateZip(compressed, 0); + const exactSize = template.length * BASE_LIMITS.compression_ratio; + + assertError( + declaredDeflateZip(compressed, exactSize), + 'member compression ratio exceeds limit: "scene.json"', + ); + assertError( + declaredDeflateZip(compressed, exactSize + 1), + "aggregate compression ratio exceeds limit", + ); + assertError( + declaredDeflateZip(compressed, exactSize + 1, exactSize), + "ZIP central/local header mismatch", + ); +}); + +test("zero compressed size uses one as the member ratio denominator", () => { + assertError( + declaredDeflateZip(Buffer.alloc(0), BASE_LIMITS.compression_ratio), + 'invalid deflate stream: "scene.json"', + ); + assertError( + declaredDeflateZip(Buffer.alloc(0), BASE_LIMITS.compression_ratio + 1), + 'member compression ratio exceeds limit: "scene.json"', + ); +}); diff --git a/scene-contract/tsconfig.json b/scene-contract/tsconfig.json new file mode 100644 index 00000000..a4405aa0 --- /dev/null +++ b/scene-contract/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "rootDir": ".", + "outDir": "dist", + "strict": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "skipLibCheck": true, + "declaration": true, + "sourceMap": true + }, + "include": ["src/**/*.ts", "test/**/*.ts"] +}