@iwsdk/vite-plugin-dev 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4567 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ /** SHA-256 over the exact UTF-8 bytes of a string. */
8
+ function sha256(value) {
9
+ return sha256Bytes(encodeUtf8(value));
10
+ }
11
+ /** SHA-256 over an exact byte sequence. */
12
+ function sha256Bytes(bytes) {
13
+ const bitLength = bytes.length * 8;
14
+ const paddedLength = Math.ceil((bytes.length + 9) / 64) * 64;
15
+ const padded = new Uint8Array(paddedLength);
16
+ padded.set(bytes);
17
+ padded[bytes.length] = 0x80;
18
+ const lengthHigh = Math.floor(bitLength / 0x1_0000_0000);
19
+ const lengthLow = bitLength >>> 0;
20
+ writeUint32(padded, paddedLength - 8, lengthHigh);
21
+ writeUint32(padded, paddedLength - 4, lengthLow);
22
+ const state = new Uint32Array([
23
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c,
24
+ 0x1f83d9ab, 0x5be0cd19,
25
+ ]);
26
+ const words = new Uint32Array(64);
27
+ for (let offset = 0; offset < padded.length; offset += 64) {
28
+ for (let index = 0; index < 16; index += 1) {
29
+ const wordOffset = offset + index * 4;
30
+ words[index] =
31
+ (padded[wordOffset] << 24) |
32
+ (padded[wordOffset + 1] << 16) |
33
+ (padded[wordOffset + 2] << 8) |
34
+ padded[wordOffset + 3];
35
+ }
36
+ for (let index = 16; index < 64; index += 1) {
37
+ const x = words[index - 15];
38
+ const y = words[index - 2];
39
+ const s0 = rotateRight(x, 7) ^ rotateRight(x, 18) ^ (x >>> 3);
40
+ const s1 = rotateRight(y, 17) ^ rotateRight(y, 19) ^ (y >>> 10);
41
+ words[index] = (words[index - 16] + s0 + words[index - 7] + s1) >>> 0;
42
+ }
43
+ let a = state[0];
44
+ let b = state[1];
45
+ let c = state[2];
46
+ let d = state[3];
47
+ let e = state[4];
48
+ let f = state[5];
49
+ let g = state[6];
50
+ let h = state[7];
51
+ for (let index = 0; index < 64; index += 1) {
52
+ const sum1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);
53
+ const choice = (e & f) ^ (~e & g);
54
+ const temp1 = (h + sum1 + choice + SHA256_CONSTANTS[index] + words[index]) >>> 0;
55
+ const sum0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);
56
+ const majority = (a & b) ^ (a & c) ^ (b & c);
57
+ const temp2 = (sum0 + majority) >>> 0;
58
+ h = g;
59
+ g = f;
60
+ f = e;
61
+ e = (d + temp1) >>> 0;
62
+ d = c;
63
+ c = b;
64
+ b = a;
65
+ a = (temp1 + temp2) >>> 0;
66
+ }
67
+ state[0] = (state[0] + a) >>> 0;
68
+ state[1] = (state[1] + b) >>> 0;
69
+ state[2] = (state[2] + c) >>> 0;
70
+ state[3] = (state[3] + d) >>> 0;
71
+ state[4] = (state[4] + e) >>> 0;
72
+ state[5] = (state[5] + f) >>> 0;
73
+ state[6] = (state[6] + g) >>> 0;
74
+ state[7] = (state[7] + h) >>> 0;
75
+ }
76
+ return `sha256:${Array.from(state)
77
+ .map((word) => word.toString(16).padStart(8, '0'))
78
+ .join('')}`;
79
+ }
80
+ function rotateRight(value, shift) {
81
+ return (value >>> shift) | (value << (32 - shift));
82
+ }
83
+ function writeUint32(bytes, offset, value) {
84
+ bytes[offset] = value >>> 24;
85
+ bytes[offset + 1] = value >>> 16;
86
+ bytes[offset + 2] = value >>> 8;
87
+ bytes[offset + 3] = value;
88
+ }
89
+ function encodeUtf8(value) {
90
+ const bytes = [];
91
+ for (let index = 0; index < value.length; index += 1) {
92
+ let codePoint = value.charCodeAt(index);
93
+ if (codePoint >= 0xd800 && codePoint <= 0xdbff) {
94
+ const low = value.charCodeAt(index + 1);
95
+ if (low >= 0xdc00 && low <= 0xdfff) {
96
+ codePoint = 0x10000 + ((codePoint - 0xd800) << 10) + (low - 0xdc00);
97
+ index += 1;
98
+ }
99
+ else {
100
+ codePoint = 0xfffd;
101
+ }
102
+ }
103
+ else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) {
104
+ codePoint = 0xfffd;
105
+ }
106
+ if (codePoint <= 0x7f) {
107
+ bytes.push(codePoint);
108
+ }
109
+ else if (codePoint <= 0x7ff) {
110
+ bytes.push(0xc0 | (codePoint >>> 6), 0x80 | (codePoint & 0x3f));
111
+ }
112
+ else if (codePoint <= 0xffff) {
113
+ bytes.push(0xe0 | (codePoint >>> 12), 0x80 | ((codePoint >>> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
114
+ }
115
+ else {
116
+ bytes.push(0xf0 | (codePoint >>> 18), 0x80 | ((codePoint >>> 12) & 0x3f), 0x80 | ((codePoint >>> 6) & 0x3f), 0x80 | (codePoint & 0x3f));
117
+ }
118
+ }
119
+ return new Uint8Array(bytes);
120
+ }
121
+ const SHA256_CONSTANTS = new Uint32Array([
122
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
123
+ 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
124
+ 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
125
+ 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
126
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
127
+ 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
128
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
129
+ 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
130
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
131
+ 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
132
+ 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
133
+ ]);
134
+
135
+ /**
136
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
137
+ *
138
+ * This source code is licensed under the MIT license found in the
139
+ * LICENSE file in the root directory of this source tree.
140
+ */
141
+ function deepClone(value) {
142
+ return JSON.parse(JSON.stringify(value));
143
+ }
144
+ function isPlainObject(value) {
145
+ return (typeof value === 'object' &&
146
+ value !== null &&
147
+ !Array.isArray(value) &&
148
+ Object.getPrototypeOf(value) === Object.prototype);
149
+ }
150
+ function isFiniteNumber(value) {
151
+ return typeof value === 'number' && Number.isFinite(value);
152
+ }
153
+ function isVec3(value) {
154
+ return (Array.isArray(value) &&
155
+ value.length === 3 &&
156
+ value.every((entry) => isFiniteNumber(entry)));
157
+ }
158
+ function isVec2(value) {
159
+ return (Array.isArray(value) &&
160
+ value.length === 2 &&
161
+ value.every((entry) => isFiniteNumber(entry)));
162
+ }
163
+ function isJsonValue(value) {
164
+ if (value === null ||
165
+ typeof value === 'string' ||
166
+ typeof value === 'boolean') {
167
+ return true;
168
+ }
169
+ if (typeof value === 'number') {
170
+ return Number.isFinite(value);
171
+ }
172
+ if (Array.isArray(value)) {
173
+ return value.every((entry) => isJsonValue(entry));
174
+ }
175
+ if (isPlainObject(value)) {
176
+ return Object.values(value).every((entry) => isJsonValue(entry));
177
+ }
178
+ return false;
179
+ }
180
+ function findNode(nodes, nodeId) {
181
+ for (const node of nodes) {
182
+ if (node.id === nodeId) {
183
+ return node;
184
+ }
185
+ const child = findNode(node.children ?? [], nodeId);
186
+ if (child != null) {
187
+ return child;
188
+ }
189
+ }
190
+ return undefined;
191
+ }
192
+ function findNodeLocation(nodes, nodeId, parent = null) {
193
+ const index = nodes.findIndex((node) => node.id === nodeId);
194
+ if (index !== -1) {
195
+ return {
196
+ index,
197
+ node: nodes[index],
198
+ parent,
199
+ siblings: nodes,
200
+ };
201
+ }
202
+ for (const node of nodes) {
203
+ const location = findNodeLocation(node.children ?? [], nodeId, node);
204
+ if (location != null) {
205
+ return location;
206
+ }
207
+ }
208
+ return undefined;
209
+ }
210
+
211
+ /**
212
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
213
+ *
214
+ * This source code is licensed under the MIT license found in the
215
+ * LICENSE file in the root directory of this source tree.
216
+ */
217
+ const MAX_SCENE_PATTERN_INSTANCES = 10_000;
218
+ /**
219
+ * Expand a pattern in stable order. Scatter uses the declared PCG32
220
+ * algorithm; other distributions derive a stable seed from the scene data.
221
+ */
222
+ function generateScenePatternTransforms(distribution, options = {}) {
223
+ const maxInstances = options.maxInstances ?? MAX_SCENE_PATTERN_INSTANCES;
224
+ const requestedCount = getScenePatternRequestedCount(distribution);
225
+ if (requestedCount > maxInstances) {
226
+ throw new Error(`Scene pattern expansion of ${requestedCount} exceeds the limit of ${maxInstances}`);
227
+ }
228
+ if (distribution.type === 'explicit') {
229
+ return deepClone(distribution.transforms);
230
+ }
231
+ const random = new Pcg32(distribution.type === 'scatter'
232
+ ? distribution.seed
233
+ : stableStringSeed(`${options.seedKey ?? ''}:${canonicalizeForSeed(distribution)}`));
234
+ if (distribution.type === 'scatter') {
235
+ return generateScatterTransforms(distribution, random, options.collisionRadius ?? 0);
236
+ }
237
+ const bases = [];
238
+ switch (distribution.type) {
239
+ case 'linear':
240
+ for (let index = 0; index < distribution.count; index += 1) {
241
+ bases.push({
242
+ position: distribution.step.map((component) => component * index),
243
+ });
244
+ }
245
+ break;
246
+ case 'grid':
247
+ for (let z = 0; z < distribution.count[2]; z += 1) {
248
+ for (let y = 0; y < distribution.count[1]; y += 1) {
249
+ for (let x = 0; x < distribution.count[0]; x += 1) {
250
+ bases.push({
251
+ position: [
252
+ x * distribution.spacing[0],
253
+ y * distribution.spacing[1],
254
+ z * distribution.spacing[2],
255
+ ],
256
+ });
257
+ }
258
+ }
259
+ }
260
+ break;
261
+ case 'radial': {
262
+ const start = distribution.startAngleDeg ?? 0;
263
+ const arc = distribution.arcDeg ?? 360;
264
+ const step = arc / distribution.count;
265
+ for (let index = 0; index < distribution.count; index += 1) {
266
+ const angleDeg = start + step * index;
267
+ const angle = degreesToRadians$1(angleDeg);
268
+ bases.push({
269
+ position: [
270
+ Math.sin(angle) * distribution.radius,
271
+ 0,
272
+ Math.cos(angle) * distribution.radius,
273
+ ],
274
+ ...(distribution.faceCenter
275
+ ? { rotationDeg: [0, angleDeg + 180, 0] }
276
+ : {}),
277
+ });
278
+ }
279
+ break;
280
+ }
281
+ case 'along-path':
282
+ bases.push(...generateAlongPathTransforms(distribution));
283
+ break;
284
+ }
285
+ return bases.map((base) => applyPatternVariation(base, distribution.variation, random));
286
+ }
287
+ function getScenePatternRequestedCount(distribution) {
288
+ switch (distribution.type) {
289
+ case 'grid':
290
+ return distribution.count.reduce((product, component) => product * component, 1);
291
+ case 'explicit':
292
+ return distribution.transforms.length;
293
+ default:
294
+ return distribution.count;
295
+ }
296
+ }
297
+ /** Actual materialized instance count for the supplied deterministic options. */
298
+ function getScenePatternInstanceCount(distribution, options = {}) {
299
+ return generateScenePatternTransforms(distribution, options).length;
300
+ }
301
+ /** Stable ID for a local prefab node expanded by an instance node. */
302
+ function deriveSceneInstanceNodeId(instanceNodeId, prefabNodeId) {
303
+ return `${instanceNodeId}/${prefabNodeId}`;
304
+ }
305
+ /** Stable namespace for one expanded pattern instance. */
306
+ function deriveScenePatternInstanceNamespace(patternNodeId, instanceIndex) {
307
+ return `${patternNodeId}/${String(instanceIndex).padStart(4, '0')}`;
308
+ }
309
+ /**
310
+ * Enumerate authored and reserved derived runtime IDs using the exact same
311
+ * namespace rules as lowering. Scatter reserves its declared contiguous ID
312
+ * range even when collision skipping materializes fewer instances.
313
+ */
314
+ function collectSceneRuntimeNodeIds(document, maxDerivedNodes = MAX_SCENE_PATTERN_INSTANCES) {
315
+ const prefabs = new Map((document.resources.prefabs ?? []).map((prefab) => [prefab.id, prefab]));
316
+ const entries = [];
317
+ let derivedCount = 0;
318
+ const visit = (node, options) => {
319
+ if (options.derived) {
320
+ derivedCount += 1;
321
+ if (derivedCount > maxDerivedNodes) {
322
+ throw new Error(`Scene derived-node expansion exceeds the limit of ${maxDerivedNodes}`);
323
+ }
324
+ }
325
+ const id = options.namespace == null
326
+ ? node.id
327
+ : deriveSceneInstanceNodeId(options.namespace, node.id);
328
+ entries.push({
329
+ derived: options.derived,
330
+ id,
331
+ sourcePath: options.sourcePath,
332
+ });
333
+ const content = node.content;
334
+ if (content?.type === 'instance' || content?.type === 'pattern') {
335
+ const prefab = prefabs.get(content.prefab);
336
+ if (prefab == null) {
337
+ throw new Error(`Scene references unknown prefab "${content.prefab}"`);
338
+ }
339
+ if (options.prefabStack.includes(prefab.id)) {
340
+ throw new Error(`Recursive scene prefab expansion: ${[
341
+ ...options.prefabStack,
342
+ prefab.id,
343
+ ].join(' -> ')}`);
344
+ }
345
+ const nextStack = [...options.prefabStack, prefab.id];
346
+ if (content.type === 'instance') {
347
+ visit(prefab.root, {
348
+ derived: true,
349
+ namespace: id,
350
+ prefabStack: nextStack,
351
+ sourcePath: `${options.sourcePath}.content.prefab(${JSON.stringify(prefab.id)}).root`,
352
+ });
353
+ }
354
+ else {
355
+ const count = getScenePatternRequestedCount(content.distribution);
356
+ for (let index = 0; index < count; index += 1) {
357
+ visit(prefab.root, {
358
+ derived: true,
359
+ namespace: deriveScenePatternInstanceNamespace(id, index),
360
+ prefabStack: nextStack,
361
+ sourcePath: `${options.sourcePath}.content.prefab(${JSON.stringify(prefab.id)}).root`,
362
+ });
363
+ }
364
+ }
365
+ }
366
+ (node.children ?? []).forEach((child, index) => visit(child, {
367
+ derived: options.derived,
368
+ namespace: options.namespace,
369
+ prefabStack: options.prefabStack,
370
+ sourcePath: `${options.sourcePath}.children[${index}]`,
371
+ }));
372
+ };
373
+ document.nodes.forEach((node, index) => visit(node, {
374
+ derived: false,
375
+ prefabStack: [],
376
+ sourcePath: `$.nodes[${index}]`,
377
+ }));
378
+ return entries;
379
+ }
380
+ function generateScatterTransforms(distribution, random, collisionRadius) {
381
+ const transforms = [];
382
+ const accepted = [];
383
+ const maxAttempts = Math.max(256, distribution.count * 64);
384
+ for (let attempt = 0; attempt < maxAttempts && transforms.length < distribution.count; attempt += 1) {
385
+ const position = randomScatterPosition(distribution.region, random);
386
+ const transform = applyPatternVariation({ position }, distribution.variation, random);
387
+ const finalPosition = transform.position ?? position;
388
+ const scale = Math.max(...scaleToVec3$1(transform.scale));
389
+ const radius = collisionRadius * scale;
390
+ if (distribution.collision === 'skip' &&
391
+ accepted.some((entry) => distanceSquared(finalPosition, entry.position) <
392
+ (radius + entry.radius) * (radius + entry.radius))) {
393
+ continue;
394
+ }
395
+ transforms.push(transform);
396
+ accepted.push({ position: finalPosition, radius });
397
+ }
398
+ return transforms;
399
+ }
400
+ function randomScatterPosition(region, random) {
401
+ if (region.type === 'box') {
402
+ return [
403
+ random.signed() * region.size[0] * 0.5,
404
+ random.signed() * region.size[1] * 0.5,
405
+ random.signed() * region.size[2] * 0.5,
406
+ ];
407
+ }
408
+ for (;;) {
409
+ const point = [random.signed(), random.signed(), random.signed()];
410
+ if (distanceSquared(point, [0, 0, 0]) <= 1) {
411
+ return point.map((component) => component * region.radius);
412
+ }
413
+ }
414
+ }
415
+ function generateAlongPathTransforms(distribution) {
416
+ const segmentLengths = [];
417
+ let totalLength = 0;
418
+ for (let index = 1; index < distribution.points.length; index += 1) {
419
+ const length = Math.sqrt(distanceSquared(distribution.points[index - 1], distribution.points[index]));
420
+ segmentLengths.push(length);
421
+ totalLength += length;
422
+ }
423
+ const transforms = [];
424
+ for (let index = 0; index < distribution.count; index += 1) {
425
+ const distance = distribution.count === 1
426
+ ? 0
427
+ : (totalLength * index) / (distribution.count - 1);
428
+ let traversed = 0;
429
+ let segmentIndex = 0;
430
+ while (segmentIndex < segmentLengths.length - 1 &&
431
+ traversed + segmentLengths[segmentIndex] < distance) {
432
+ traversed += segmentLengths[segmentIndex];
433
+ segmentIndex += 1;
434
+ }
435
+ const start = distribution.points[segmentIndex];
436
+ const end = distribution.points[segmentIndex + 1];
437
+ const length = segmentLengths[segmentIndex] || 1;
438
+ const t = Math.min(1, Math.max(0, (distance - traversed) / length));
439
+ const position = start.map((component, axis) => component + (end[axis] - component) * t);
440
+ transforms.push({
441
+ position,
442
+ ...(distribution.orientToPath
443
+ ? {
444
+ rotationDeg: [
445
+ 0,
446
+ radiansToDegrees$1(Math.atan2(end[0] - start[0], end[2] - start[2])),
447
+ 0,
448
+ ],
449
+ }
450
+ : {}),
451
+ });
452
+ }
453
+ return transforms;
454
+ }
455
+ function applyPatternVariation(base, variation, random) {
456
+ if (variation == null) {
457
+ return base;
458
+ }
459
+ const result = deepClone(base);
460
+ if (variation.positionJitter != null) {
461
+ const position = result.position ?? [0, 0, 0];
462
+ result.position = position.map((component, index) => component + random.signed() * variation.positionJitter[index]);
463
+ }
464
+ if (variation.yawDeg != null) {
465
+ const rotation = result.rotationDeg ?? [0, 0, 0];
466
+ result.rotationDeg = [
467
+ rotation[0],
468
+ rotation[1] + random.range(...variation.yawDeg),
469
+ rotation[2],
470
+ ];
471
+ }
472
+ if (variation.scale != null) {
473
+ const multiplier = random.range(...variation.scale);
474
+ const scale = scaleToVec3$1(result.scale);
475
+ result.scale = scale.map((component) => component * multiplier);
476
+ }
477
+ return result;
478
+ }
479
+ function scaleToVec3$1(scale) {
480
+ if (scale == null) {
481
+ return [1, 1, 1];
482
+ }
483
+ return typeof scale === 'number' ? [scale, scale, scale] : scale;
484
+ }
485
+ function distanceSquared(first, second) {
486
+ const x = first[0] - second[0];
487
+ const y = first[1] - second[1];
488
+ const z = first[2] - second[2];
489
+ return x * x + y * y + z * z;
490
+ }
491
+ function degreesToRadians$1(degrees) {
492
+ return (degrees * Math.PI) / 180;
493
+ }
494
+ function radiansToDegrees$1(radians) {
495
+ return (radians * 180) / Math.PI;
496
+ }
497
+ function canonicalizeForSeed(value) {
498
+ if (value === null || typeof value !== 'object') {
499
+ return JSON.stringify(value);
500
+ }
501
+ if (Array.isArray(value)) {
502
+ return `[${value.map((entry) => canonicalizeForSeed(entry)).join(',')}]`;
503
+ }
504
+ const record = value;
505
+ return `{${Object.keys(value)
506
+ .sort()
507
+ .map((key) => `${JSON.stringify(key)}:${canonicalizeForSeed(record[key])}`)
508
+ .join(',')}}`;
509
+ }
510
+ function stableStringSeed(value) {
511
+ let hash = 0x811c9dc5;
512
+ for (let index = 0; index < value.length; index += 1) {
513
+ hash ^= value.charCodeAt(index);
514
+ hash = Math.imul(hash, 0x01000193);
515
+ }
516
+ return hash >>> 0;
517
+ }
518
+ class Pcg32 {
519
+ constructor(seed) {
520
+ this.state = (seed ^ 0x853c49e6) >>> 0;
521
+ this.nextUint32();
522
+ }
523
+ nextUint32() {
524
+ this.state = (Math.imul(this.state, 747796405) + 2891336453) >>> 0;
525
+ const shift = (this.state >>> 28) + 4;
526
+ const word = Math.imul((this.state >>> shift) ^ this.state, 277803737);
527
+ return ((word >>> 22) ^ word) >>> 0;
528
+ }
529
+ next() {
530
+ return this.nextUint32() / 0x1_0000_0000;
531
+ }
532
+ signed() {
533
+ return this.next() * 2 - 1;
534
+ }
535
+ range(min, max) {
536
+ return min + this.next() * (max - min);
537
+ }
538
+ }
539
+
540
+ /**
541
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
542
+ *
543
+ * This source code is licensed under the MIT license found in the
544
+ * LICENSE file in the root directory of this source tree.
545
+ */
546
+ /**
547
+ * Returns the complete identity set for declared composition inputs.
548
+ * Prompt identity is derived from its exact UTF-8 bytes. Reference hashes are
549
+ * declarations; callers need a trusted byte provider to verify referenced data.
550
+ */
551
+ function getSceneCompositionSourceHashes(input) {
552
+ const hashes = new Set();
553
+ if (input.prompt != null) {
554
+ hashes.add(sha256(input.prompt));
555
+ }
556
+ input.references?.forEach((reference) => {
557
+ hashes.add(`sha256:${reference.sha256.toLowerCase()}`);
558
+ });
559
+ return [...hashes].sort();
560
+ }
561
+
562
+ /**
563
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
564
+ *
565
+ * This source code is licensed under the MIT license found in the
566
+ * LICENSE file in the root directory of this source tree.
567
+ */
568
+ const CURRENT_SCENE_VERSION = 'iwsdk.scene.v1';
569
+ const CURRENT_SCENE_REVIEW_VERSION = 'iwsdk.scene-review.v1';
570
+ const MAX_SCENE_CORRECTION_ROUNDS = 10;
571
+ const SCENE_IMPORT_ID_PATTERN = '^[A-Za-z][A-Za-z0-9_-]*$';
572
+
573
+ /**
574
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
575
+ *
576
+ * This source code is licensed under the MIT license found in the
577
+ * LICENSE file in the root directory of this source tree.
578
+ */
579
+ const SCENE_DOCUMENT_SCHEMA_ID = 'https://iwsdk.dev/schemas/iwsdk.scene.v1.schema.json';
580
+ /**
581
+ * Normative syntax for an IWSDK v1 authoring document. Cross-reference
582
+ * resolution, namespace uniqueness, cycle detection, and runtime capability
583
+ * checks are semantic validation performed after this structural schema.
584
+ */
585
+ const SCENE_DOCUMENT_JSON_SCHEMA = {
586
+ $id: SCENE_DOCUMENT_SCHEMA_ID,
587
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
588
+ title: 'IWSDK Scene Document v1',
589
+ description: 'Closed declarative scene document shared by IWSDK authoring, editor, and runtime projection workflows.',
590
+ type: 'object',
591
+ additionalProperties: false,
592
+ required: ['version', 'units', 'resources', 'nodes'],
593
+ properties: {
594
+ version: {
595
+ const: CURRENT_SCENE_VERSION,
596
+ description: 'Scene document schema version.',
597
+ },
598
+ units: {
599
+ const: 'meters',
600
+ description: 'Scene unit system. IWSDK scene documents use meters.',
601
+ },
602
+ imports: {
603
+ type: 'array',
604
+ items: { $ref: '#/$defs/sceneImport' },
605
+ description: 'Ordered reusable scene modules resolved before runtime projection.',
606
+ },
607
+ components: {
608
+ type: 'object',
609
+ additionalProperties: { $ref: '#/$defs/componentValue' },
610
+ description: 'Components applied to the runtime level-root entity. An explicit empty map disables implicit root components.',
611
+ },
612
+ player: { $ref: '#/$defs/playerRig' },
613
+ metadata: { $ref: '#/$defs/jsonObject' },
614
+ authoring: { $ref: '#/$defs/authoring' },
615
+ resources: { $ref: '#/$defs/resources' },
616
+ environment: { $ref: '#/$defs/environment' },
617
+ nodes: {
618
+ type: 'array',
619
+ items: { $ref: '#/$defs/node' },
620
+ description: 'Ordered top-level scene hierarchy.',
621
+ },
622
+ },
623
+ $defs: {
624
+ identifier: { type: 'string', minLength: 1 },
625
+ builtinEntity: {
626
+ type: 'object',
627
+ additionalProperties: false,
628
+ properties: {
629
+ components: {
630
+ type: 'object',
631
+ additionalProperties: { $ref: '#/$defs/componentValue' },
632
+ },
633
+ transform: {
634
+ $ref: '#/$defs/transform',
635
+ deprecated: true,
636
+ description: 'Legacy tracked-space preview transform. Retained for file compatibility and ignored at runtime.',
637
+ },
638
+ },
639
+ },
640
+ playerRig: {
641
+ type: 'object',
642
+ additionalProperties: false,
643
+ properties: {
644
+ components: {
645
+ type: 'object',
646
+ additionalProperties: { $ref: '#/$defs/componentValue' },
647
+ },
648
+ transform: { $ref: '#/$defs/transform' },
649
+ camera: { $ref: '#/$defs/builtinEntity' },
650
+ head: { $ref: '#/$defs/builtinEntity' },
651
+ leftTargetRay: { $ref: '#/$defs/builtinEntity' },
652
+ rightTargetRay: { $ref: '#/$defs/builtinEntity' },
653
+ leftGrip: { $ref: '#/$defs/builtinEntity' },
654
+ rightGrip: { $ref: '#/$defs/builtinEntity' },
655
+ },
656
+ },
657
+ color: {
658
+ type: 'string',
659
+ pattern: '^#[0-9a-fA-F]{6}$',
660
+ },
661
+ sha256Digest: {
662
+ type: 'string',
663
+ pattern: '^[0-9a-fA-F]{64}$',
664
+ },
665
+ sha256Hash: {
666
+ type: 'string',
667
+ pattern: '^sha256:[0-9a-fA-F]{64}$',
668
+ },
669
+ vec2: {
670
+ type: 'array',
671
+ minItems: 2,
672
+ maxItems: 2,
673
+ items: { type: 'number' },
674
+ },
675
+ vec3: {
676
+ type: 'array',
677
+ minItems: 3,
678
+ maxItems: 3,
679
+ items: { type: 'number' },
680
+ },
681
+ vec4: {
682
+ type: 'array',
683
+ minItems: 4,
684
+ maxItems: 4,
685
+ items: { type: 'number' },
686
+ },
687
+ normalizedVec2: {
688
+ type: 'array',
689
+ minItems: 2,
690
+ maxItems: 2,
691
+ items: { type: 'number', minimum: 0, maximum: 1 },
692
+ },
693
+ normalizedVec4: {
694
+ type: 'array',
695
+ minItems: 4,
696
+ maxItems: 4,
697
+ items: { type: 'number', minimum: 0, maximum: 1 },
698
+ },
699
+ positiveVec2: {
700
+ type: 'array',
701
+ minItems: 2,
702
+ maxItems: 2,
703
+ items: { type: 'number', exclusiveMinimum: 0 },
704
+ },
705
+ positiveVec3: {
706
+ type: 'array',
707
+ minItems: 3,
708
+ maxItems: 3,
709
+ items: { type: 'number', exclusiveMinimum: 0 },
710
+ },
711
+ bounds: {
712
+ type: 'object',
713
+ additionalProperties: false,
714
+ required: ['min', 'max'],
715
+ properties: {
716
+ min: { $ref: '#/$defs/vec3' },
717
+ max: { $ref: '#/$defs/vec3' },
718
+ },
719
+ },
720
+ transform: {
721
+ type: 'object',
722
+ additionalProperties: false,
723
+ properties: {
724
+ position: { $ref: '#/$defs/vec3' },
725
+ rotationDeg: { $ref: '#/$defs/vec3' },
726
+ scale: {
727
+ oneOf: [{ type: 'number' }, { $ref: '#/$defs/vec3' }],
728
+ },
729
+ },
730
+ },
731
+ playerSpaceParent: {
732
+ type: 'object',
733
+ additionalProperties: false,
734
+ required: ['type', 'target'],
735
+ properties: {
736
+ type: { const: 'player-space' },
737
+ target: {
738
+ enum: [
739
+ 'player',
740
+ 'camera',
741
+ 'head',
742
+ 'left-target-ray',
743
+ 'right-target-ray',
744
+ 'left-grip',
745
+ 'right-grip',
746
+ ],
747
+ },
748
+ },
749
+ },
750
+ sceneImport: {
751
+ type: 'object',
752
+ additionalProperties: false,
753
+ required: ['id', 'src'],
754
+ properties: {
755
+ id: { $ref: '#/$defs/identifier' },
756
+ src: { type: 'string', minLength: 1 },
757
+ transform: { $ref: '#/$defs/transform' },
758
+ },
759
+ },
760
+ jsonObject: {
761
+ type: 'object',
762
+ additionalProperties: { $ref: '#/$defs/jsonValue' },
763
+ },
764
+ jsonValue: {
765
+ oneOf: [
766
+ { type: 'string' },
767
+ { type: 'number' },
768
+ { type: 'boolean' },
769
+ { type: 'null' },
770
+ {
771
+ type: 'array',
772
+ items: { $ref: '#/$defs/jsonValue' },
773
+ },
774
+ {
775
+ type: 'object',
776
+ additionalProperties: { $ref: '#/$defs/jsonValue' },
777
+ },
778
+ ],
779
+ },
780
+ componentValue: { $ref: '#/$defs/jsonObject' },
781
+ resources: {
782
+ type: 'object',
783
+ additionalProperties: false,
784
+ properties: {
785
+ prefabs: {
786
+ type: 'array',
787
+ items: { $ref: '#/$defs/prefab' },
788
+ },
789
+ },
790
+ },
791
+ prefab: {
792
+ type: 'object',
793
+ additionalProperties: false,
794
+ required: ['id', 'root'],
795
+ properties: {
796
+ id: { $ref: '#/$defs/identifier' },
797
+ root: { $ref: '#/$defs/node' },
798
+ },
799
+ },
800
+ prefabNodeOverride: {
801
+ type: 'object',
802
+ additionalProperties: false,
803
+ properties: {
804
+ transform: { $ref: '#/$defs/transform' },
805
+ components: {
806
+ type: 'object',
807
+ additionalProperties: { $ref: '#/$defs/componentValue' },
808
+ },
809
+ visible: { type: 'boolean' },
810
+ },
811
+ },
812
+ prefabOverrideMap: {
813
+ type: 'object',
814
+ propertyNames: { minLength: 1 },
815
+ additionalProperties: { $ref: '#/$defs/prefabNodeOverride' },
816
+ },
817
+ patternVariation: {
818
+ type: 'object',
819
+ additionalProperties: false,
820
+ properties: {
821
+ scale: {
822
+ type: 'array',
823
+ minItems: 2,
824
+ maxItems: 2,
825
+ items: { type: 'number', exclusiveMinimum: 0 },
826
+ },
827
+ yawDeg: {
828
+ type: 'array',
829
+ minItems: 2,
830
+ maxItems: 2,
831
+ items: { type: 'number' },
832
+ },
833
+ positionJitter: { $ref: '#/$defs/vec3' },
834
+ },
835
+ },
836
+ patternDistribution: {
837
+ oneOf: [
838
+ { $ref: '#/$defs/linearDistribution' },
839
+ { $ref: '#/$defs/gridDistribution' },
840
+ { $ref: '#/$defs/radialDistribution' },
841
+ { $ref: '#/$defs/alongPathDistribution' },
842
+ { $ref: '#/$defs/scatterDistribution' },
843
+ { $ref: '#/$defs/explicitDistribution' },
844
+ ],
845
+ },
846
+ linearDistribution: {
847
+ type: 'object',
848
+ additionalProperties: false,
849
+ required: ['type', 'count', 'step'],
850
+ properties: {
851
+ type: { const: 'linear' },
852
+ count: { type: 'integer', minimum: 1, maximum: 100000 },
853
+ step: { $ref: '#/$defs/vec3' },
854
+ variation: { $ref: '#/$defs/patternVariation' },
855
+ },
856
+ },
857
+ gridDistribution: {
858
+ type: 'object',
859
+ additionalProperties: false,
860
+ required: ['type', 'count', 'spacing'],
861
+ properties: {
862
+ type: { const: 'grid' },
863
+ count: {
864
+ type: 'array',
865
+ minItems: 3,
866
+ maxItems: 3,
867
+ items: { type: 'integer', minimum: 1, maximum: 100000 },
868
+ },
869
+ spacing: { $ref: '#/$defs/vec3' },
870
+ variation: { $ref: '#/$defs/patternVariation' },
871
+ },
872
+ },
873
+ radialDistribution: {
874
+ type: 'object',
875
+ additionalProperties: false,
876
+ required: ['type', 'count', 'radius'],
877
+ properties: {
878
+ type: { const: 'radial' },
879
+ count: { type: 'integer', minimum: 1, maximum: 100000 },
880
+ radius: { type: 'number', minimum: 0 },
881
+ startAngleDeg: { type: 'number' },
882
+ arcDeg: {
883
+ type: 'number',
884
+ exclusiveMinimum: 0,
885
+ maximum: 360,
886
+ },
887
+ faceCenter: { type: 'boolean' },
888
+ variation: { $ref: '#/$defs/patternVariation' },
889
+ },
890
+ },
891
+ alongPathDistribution: {
892
+ type: 'object',
893
+ additionalProperties: false,
894
+ required: ['type', 'points', 'count'],
895
+ properties: {
896
+ type: { const: 'along-path' },
897
+ points: {
898
+ type: 'array',
899
+ minItems: 2,
900
+ items: { $ref: '#/$defs/vec3' },
901
+ },
902
+ count: { type: 'integer', minimum: 1, maximum: 100000 },
903
+ orientToPath: { type: 'boolean' },
904
+ variation: { $ref: '#/$defs/patternVariation' },
905
+ },
906
+ },
907
+ scatterRegion: {
908
+ oneOf: [
909
+ {
910
+ type: 'object',
911
+ additionalProperties: false,
912
+ required: ['type', 'size'],
913
+ properties: {
914
+ type: { const: 'box' },
915
+ size: { $ref: '#/$defs/positiveVec3' },
916
+ },
917
+ },
918
+ {
919
+ type: 'object',
920
+ additionalProperties: false,
921
+ required: ['type', 'radius'],
922
+ properties: {
923
+ type: { const: 'sphere' },
924
+ radius: { type: 'number', exclusiveMinimum: 0 },
925
+ },
926
+ },
927
+ ],
928
+ },
929
+ scatterDistribution: {
930
+ type: 'object',
931
+ additionalProperties: false,
932
+ required: ['type', 'count', 'seed', 'algorithm', 'collision', 'region'],
933
+ properties: {
934
+ type: { const: 'scatter' },
935
+ count: { type: 'integer', minimum: 1, maximum: 100000 },
936
+ seed: { type: 'integer' },
937
+ algorithm: { const: 'pcg32-box-rejection-v1' },
938
+ collision: { enum: ['allow', 'skip'] },
939
+ region: { $ref: '#/$defs/scatterRegion' },
940
+ variation: { $ref: '#/$defs/patternVariation' },
941
+ },
942
+ },
943
+ explicitDistribution: {
944
+ type: 'object',
945
+ additionalProperties: false,
946
+ required: ['type', 'transforms'],
947
+ properties: {
948
+ type: { const: 'explicit' },
949
+ transforms: {
950
+ type: 'array',
951
+ minItems: 1,
952
+ maxItems: 100000,
953
+ items: { $ref: '#/$defs/transform' },
954
+ },
955
+ },
956
+ },
957
+ nodeContent: {
958
+ oneOf: [
959
+ { $ref: '#/$defs/groupContent' },
960
+ { $ref: '#/$defs/assetContent' },
961
+ { $ref: '#/$defs/instanceContent' },
962
+ { $ref: '#/$defs/patternContent' },
963
+ ],
964
+ },
965
+ groupContent: {
966
+ type: 'object',
967
+ additionalProperties: false,
968
+ required: ['type'],
969
+ properties: { type: { const: 'group' } },
970
+ },
971
+ assetContent: {
972
+ type: 'object',
973
+ additionalProperties: false,
974
+ required: ['type', 'asset'],
975
+ properties: {
976
+ type: { const: 'asset' },
977
+ asset: { $ref: '#/$defs/identifier' },
978
+ castShadow: { type: 'boolean' },
979
+ receiveShadow: { type: 'boolean' },
980
+ },
981
+ },
982
+ instanceContent: {
983
+ type: 'object',
984
+ additionalProperties: false,
985
+ required: ['type', 'prefab'],
986
+ properties: {
987
+ type: { const: 'instance' },
988
+ prefab: { $ref: '#/$defs/identifier' },
989
+ overrides: { $ref: '#/$defs/prefabOverrideMap' },
990
+ },
991
+ },
992
+ patternContent: {
993
+ type: 'object',
994
+ additionalProperties: false,
995
+ required: ['type', 'prefab', 'distribution'],
996
+ properties: {
997
+ type: { const: 'pattern' },
998
+ prefab: { $ref: '#/$defs/identifier' },
999
+ distribution: { $ref: '#/$defs/patternDistribution' },
1000
+ overrides: { $ref: '#/$defs/prefabOverrideMap' },
1001
+ },
1002
+ },
1003
+ nodeConstraints: {
1004
+ type: 'object',
1005
+ additionalProperties: false,
1006
+ properties: {
1007
+ lookAt: { $ref: '#/$defs/lookAtConstraint' },
1008
+ },
1009
+ },
1010
+ lookAtConstraint: {
1011
+ type: 'object',
1012
+ additionalProperties: false,
1013
+ required: ['target', 'mode'],
1014
+ properties: {
1015
+ target: { $ref: '#/$defs/vec3' },
1016
+ mode: { const: 'yaw-v1' },
1017
+ },
1018
+ },
1019
+ node: {
1020
+ type: 'object',
1021
+ additionalProperties: false,
1022
+ required: ['id'],
1023
+ properties: {
1024
+ id: { $ref: '#/$defs/identifier' },
1025
+ name: { type: 'string', minLength: 1 },
1026
+ visible: { type: 'boolean' },
1027
+ framingRole: { default: 'content', enum: ['content', 'support'] },
1028
+ content: { $ref: '#/$defs/nodeContent' },
1029
+ transform: { $ref: '#/$defs/transform' },
1030
+ constraints: { $ref: '#/$defs/nodeConstraints' },
1031
+ components: {
1032
+ type: 'object',
1033
+ additionalProperties: { $ref: '#/$defs/componentValue' },
1034
+ },
1035
+ children: {
1036
+ type: 'array',
1037
+ items: { $ref: '#/$defs/node' },
1038
+ },
1039
+ metadata: { $ref: '#/$defs/jsonObject' },
1040
+ parent: { $ref: '#/$defs/playerSpaceParent' },
1041
+ },
1042
+ },
1043
+ fog: {
1044
+ oneOf: [
1045
+ {
1046
+ type: 'object',
1047
+ additionalProperties: false,
1048
+ required: ['type', 'near', 'far'],
1049
+ properties: {
1050
+ type: { const: 'linear' },
1051
+ color: { $ref: '#/$defs/color' },
1052
+ near: { type: 'number', minimum: 0 },
1053
+ far: { type: 'number', exclusiveMinimum: 0 },
1054
+ },
1055
+ },
1056
+ {
1057
+ type: 'object',
1058
+ additionalProperties: false,
1059
+ required: ['type', 'density'],
1060
+ properties: {
1061
+ type: { const: 'exponential' },
1062
+ color: { $ref: '#/$defs/color' },
1063
+ density: { type: 'number', exclusiveMinimum: 0 },
1064
+ },
1065
+ },
1066
+ ],
1067
+ },
1068
+ environment: {
1069
+ type: 'object',
1070
+ additionalProperties: false,
1071
+ properties: {
1072
+ fog: { $ref: '#/$defs/fog' },
1073
+ toneMapping: {
1074
+ enum: ['none', 'linear', 'reinhard', 'cineon', 'aces'],
1075
+ },
1076
+ exposure: { type: 'number', minimum: 0 },
1077
+ shadows: { type: 'boolean' },
1078
+ shadowMapType: { enum: ['basic', 'pcf', 'pcf-soft'] },
1079
+ },
1080
+ },
1081
+ sourceReference: {
1082
+ type: 'object',
1083
+ additionalProperties: false,
1084
+ required: ['id', 'uri', 'roles', 'width', 'height', 'sha256'],
1085
+ properties: {
1086
+ id: { $ref: '#/$defs/identifier' },
1087
+ uri: { type: 'string', minLength: 1 },
1088
+ roles: {
1089
+ type: 'array',
1090
+ minItems: 1,
1091
+ uniqueItems: true,
1092
+ items: { enum: ['layout', 'identity', 'palette', 'style'] },
1093
+ },
1094
+ width: { type: 'integer', minimum: 1 },
1095
+ height: { type: 'integer', minimum: 1 },
1096
+ sha256: { $ref: '#/$defs/sha256Digest' },
1097
+ },
1098
+ },
1099
+ compositionInput: {
1100
+ type: 'object',
1101
+ additionalProperties: false,
1102
+ required: ['kind'],
1103
+ properties: {
1104
+ kind: { enum: ['text', 'image', 'hybrid'] },
1105
+ prompt: { type: 'string', minLength: 1 },
1106
+ references: {
1107
+ type: 'array',
1108
+ items: { $ref: '#/$defs/sourceReference' },
1109
+ },
1110
+ },
1111
+ },
1112
+ compositionTarget: {
1113
+ type: 'object',
1114
+ additionalProperties: false,
1115
+ required: ['surfaces', 'assetPolicy'],
1116
+ properties: {
1117
+ surfaces: {
1118
+ type: 'array',
1119
+ minItems: 1,
1120
+ uniqueItems: true,
1121
+ items: { enum: ['browser', 'vr', 'ar', 'shared'] },
1122
+ },
1123
+ style: { type: 'string', minLength: 1 },
1124
+ assetPolicy: { const: 'manifest-assets' },
1125
+ },
1126
+ },
1127
+ acceptedApproximation: {
1128
+ type: 'object',
1129
+ additionalProperties: false,
1130
+ required: ['feature', 'requested', 'implementation', 'status'],
1131
+ properties: {
1132
+ feature: { $ref: '#/$defs/identifier' },
1133
+ requested: { type: 'string', minLength: 1 },
1134
+ implementation: { type: 'string', minLength: 1 },
1135
+ status: { const: 'accepted' },
1136
+ },
1137
+ },
1138
+ representationPolicy: {
1139
+ type: 'object',
1140
+ additionalProperties: false,
1141
+ required: ['fidelityCeiling', 'allowed'],
1142
+ properties: {
1143
+ fidelityCeiling: { type: 'string', minLength: 1 },
1144
+ allowed: {
1145
+ type: 'array',
1146
+ minItems: 1,
1147
+ uniqueItems: true,
1148
+ items: {
1149
+ enum: ['asset', 'prefab', 'pattern'],
1150
+ },
1151
+ },
1152
+ acceptedApproximations: {
1153
+ type: 'array',
1154
+ items: { $ref: '#/$defs/acceptedApproximation' },
1155
+ },
1156
+ },
1157
+ },
1158
+ featureAcceptance: {
1159
+ oneOf: [
1160
+ { $ref: '#/$defs/presenceAcceptance' },
1161
+ { $ref: '#/$defs/countAcceptance' },
1162
+ { $ref: '#/$defs/projectedRegionAcceptance' },
1163
+ { $ref: '#/$defs/spatialRelationAcceptance' },
1164
+ { $ref: '#/$defs/visualJudgmentAcceptance' },
1165
+ ],
1166
+ },
1167
+ presenceAcceptance: {
1168
+ type: 'object',
1169
+ additionalProperties: false,
1170
+ required: ['id', 'kind', 'nodeRefs'],
1171
+ properties: {
1172
+ id: { $ref: '#/$defs/identifier' },
1173
+ kind: { const: 'presence' },
1174
+ nodeRefs: {
1175
+ type: 'array',
1176
+ minItems: 1,
1177
+ items: { $ref: '#/$defs/identifier' },
1178
+ },
1179
+ view: { $ref: '#/$defs/identifier' },
1180
+ },
1181
+ },
1182
+ countAcceptance: {
1183
+ type: 'object',
1184
+ additionalProperties: false,
1185
+ required: ['id', 'kind'],
1186
+ allOf: [
1187
+ {
1188
+ anyOf: [
1189
+ {
1190
+ properties: { nodeRefs: {} },
1191
+ required: ['nodeRefs'],
1192
+ },
1193
+ {
1194
+ properties: { pattern: {} },
1195
+ required: ['pattern'],
1196
+ },
1197
+ ],
1198
+ },
1199
+ {
1200
+ anyOf: [
1201
+ {
1202
+ properties: { equals: {} },
1203
+ required: ['equals'],
1204
+ },
1205
+ {
1206
+ properties: { minimum: {} },
1207
+ required: ['minimum'],
1208
+ },
1209
+ {
1210
+ properties: { maximum: {} },
1211
+ required: ['maximum'],
1212
+ },
1213
+ ],
1214
+ },
1215
+ ],
1216
+ properties: {
1217
+ id: { $ref: '#/$defs/identifier' },
1218
+ kind: { const: 'count' },
1219
+ nodeRefs: {
1220
+ type: 'array',
1221
+ minItems: 1,
1222
+ items: { $ref: '#/$defs/identifier' },
1223
+ },
1224
+ pattern: { $ref: '#/$defs/identifier' },
1225
+ equals: { type: 'integer', minimum: 0 },
1226
+ minimum: { type: 'integer', minimum: 0 },
1227
+ maximum: { type: 'integer', minimum: 0 },
1228
+ },
1229
+ },
1230
+ projectedRegionAcceptance: {
1231
+ type: 'object',
1232
+ additionalProperties: false,
1233
+ required: [
1234
+ 'id',
1235
+ 'kind',
1236
+ 'measurement',
1237
+ 'nodeRefs',
1238
+ 'view',
1239
+ 'reference',
1240
+ 'region',
1241
+ ],
1242
+ properties: {
1243
+ id: { $ref: '#/$defs/identifier' },
1244
+ kind: { const: 'projected-region' },
1245
+ measurement: {
1246
+ oneOf: [
1247
+ {
1248
+ type: 'object',
1249
+ additionalProperties: false,
1250
+ required: ['method', 'applicability'],
1251
+ properties: {
1252
+ method: { const: 'projected-world-aabb-v1' },
1253
+ applicability: { const: 'single-axis-aligned-box' },
1254
+ },
1255
+ },
1256
+ {
1257
+ type: 'object',
1258
+ additionalProperties: false,
1259
+ required: ['method', 'applicability'],
1260
+ properties: {
1261
+ method: { const: 'capture-node-mask-bounds-v1' },
1262
+ applicability: { const: 'visible-node-mask' },
1263
+ },
1264
+ },
1265
+ ],
1266
+ },
1267
+ nodeRefs: {
1268
+ type: 'array',
1269
+ minItems: 1,
1270
+ items: { $ref: '#/$defs/identifier' },
1271
+ },
1272
+ view: { $ref: '#/$defs/identifier' },
1273
+ reference: { $ref: '#/$defs/identifier' },
1274
+ region: { $ref: '#/$defs/normalizedVec4' },
1275
+ centerTolerance: { type: 'number', minimum: 0 },
1276
+ extentTolerance: { type: 'number', minimum: 0 },
1277
+ },
1278
+ },
1279
+ spatialRelationAcceptance: {
1280
+ type: 'object',
1281
+ additionalProperties: false,
1282
+ required: ['id', 'kind', 'nodeRefs', 'target', 'relation'],
1283
+ properties: {
1284
+ id: { $ref: '#/$defs/identifier' },
1285
+ kind: { const: 'spatial-relation' },
1286
+ nodeRefs: {
1287
+ type: 'array',
1288
+ minItems: 1,
1289
+ items: { $ref: '#/$defs/identifier' },
1290
+ },
1291
+ target: { $ref: '#/$defs/identifier' },
1292
+ relation: {
1293
+ enum: [
1294
+ 'above',
1295
+ 'below',
1296
+ 'left-of',
1297
+ 'right-of',
1298
+ 'in-front-of',
1299
+ 'behind',
1300
+ 'touching',
1301
+ ],
1302
+ },
1303
+ tolerance: { type: 'number', minimum: 0 },
1304
+ },
1305
+ },
1306
+ visualJudgmentAcceptance: {
1307
+ type: 'object',
1308
+ additionalProperties: false,
1309
+ required: ['id', 'kind', 'view', 'criterion'],
1310
+ properties: {
1311
+ id: { $ref: '#/$defs/identifier' },
1312
+ kind: { const: 'visual-judgment' },
1313
+ view: { $ref: '#/$defs/identifier' },
1314
+ criterion: { type: 'string', minLength: 1 },
1315
+ },
1316
+ },
1317
+ featureEvidence: {
1318
+ type: 'object',
1319
+ additionalProperties: false,
1320
+ required: ['reference'],
1321
+ oneOf: [
1322
+ {
1323
+ properties: { region: {} },
1324
+ required: ['region'],
1325
+ },
1326
+ {
1327
+ properties: { point: {} },
1328
+ required: ['point'],
1329
+ },
1330
+ ],
1331
+ properties: {
1332
+ reference: { $ref: '#/$defs/identifier' },
1333
+ region: { $ref: '#/$defs/normalizedVec4' },
1334
+ point: { $ref: '#/$defs/normalizedVec2' },
1335
+ },
1336
+ },
1337
+ objectInspectionPart: {
1338
+ type: 'object',
1339
+ additionalProperties: false,
1340
+ required: ['id', 'description', 'nodeRefs'],
1341
+ properties: {
1342
+ id: { $ref: '#/$defs/identifier' },
1343
+ description: { type: 'string', minLength: 1 },
1344
+ nodeRefs: {
1345
+ type: 'array',
1346
+ minItems: 1,
1347
+ uniqueItems: true,
1348
+ items: { $ref: '#/$defs/identifier' },
1349
+ },
1350
+ },
1351
+ },
1352
+ objectInspectionContact: {
1353
+ type: 'object',
1354
+ additionalProperties: false,
1355
+ required: ['id', 'description', 'nodeRefs', 'targetNodeRefs'],
1356
+ properties: {
1357
+ id: { $ref: '#/$defs/identifier' },
1358
+ description: { type: 'string', minLength: 1 },
1359
+ nodeRefs: {
1360
+ type: 'array',
1361
+ minItems: 1,
1362
+ uniqueItems: true,
1363
+ items: { $ref: '#/$defs/identifier' },
1364
+ },
1365
+ targetNodeRefs: {
1366
+ type: 'array',
1367
+ minItems: 1,
1368
+ uniqueItems: true,
1369
+ items: { $ref: '#/$defs/identifier' },
1370
+ },
1371
+ },
1372
+ },
1373
+ objectInspectionContext: {
1374
+ type: 'object',
1375
+ additionalProperties: false,
1376
+ required: ['background', 'lighting'],
1377
+ properties: {
1378
+ background: { enum: ['authored', 'neutral'] },
1379
+ lighting: { enum: ['authored', 'neutral'] },
1380
+ includeNodeRefs: {
1381
+ type: 'array',
1382
+ minItems: 1,
1383
+ uniqueItems: true,
1384
+ items: { $ref: '#/$defs/identifier' },
1385
+ },
1386
+ },
1387
+ },
1388
+ objectInspectionSpec: {
1389
+ type: 'object',
1390
+ additionalProperties: false,
1391
+ required: [
1392
+ 'silhouette',
1393
+ 'proportions',
1394
+ 'parts',
1395
+ 'negativeSpace',
1396
+ 'contacts',
1397
+ 'materialResponse',
1398
+ 'requiredViews',
1399
+ 'context',
1400
+ ],
1401
+ properties: {
1402
+ silhouette: {
1403
+ type: 'array',
1404
+ minItems: 1,
1405
+ uniqueItems: true,
1406
+ items: { type: 'string', minLength: 1 },
1407
+ },
1408
+ proportions: {
1409
+ type: 'array',
1410
+ minItems: 1,
1411
+ uniqueItems: true,
1412
+ items: { type: 'string', minLength: 1 },
1413
+ },
1414
+ parts: {
1415
+ type: 'array',
1416
+ minItems: 1,
1417
+ items: { $ref: '#/$defs/objectInspectionPart' },
1418
+ },
1419
+ negativeSpace: {
1420
+ type: 'array',
1421
+ minItems: 1,
1422
+ uniqueItems: true,
1423
+ items: { type: 'string', minLength: 1 },
1424
+ },
1425
+ contacts: {
1426
+ type: 'array',
1427
+ minItems: 1,
1428
+ items: { $ref: '#/$defs/objectInspectionContact' },
1429
+ },
1430
+ materialResponse: {
1431
+ type: 'array',
1432
+ minItems: 1,
1433
+ uniqueItems: true,
1434
+ items: { type: 'string', minLength: 1 },
1435
+ },
1436
+ requiredViews: {
1437
+ type: 'array',
1438
+ minItems: 1,
1439
+ uniqueItems: true,
1440
+ items: { $ref: '#/$defs/identifier' },
1441
+ },
1442
+ context: { $ref: '#/$defs/objectInspectionContext' },
1443
+ },
1444
+ },
1445
+ feature: {
1446
+ type: 'object',
1447
+ additionalProperties: false,
1448
+ required: ['id', 'priority', 'description', 'nodeRefs', 'acceptance'],
1449
+ properties: {
1450
+ id: { $ref: '#/$defs/identifier' },
1451
+ priority: { enum: ['required', 'optional'] },
1452
+ description: { type: 'string', minLength: 1 },
1453
+ nodeRefs: {
1454
+ type: 'array',
1455
+ minItems: 1,
1456
+ items: { $ref: '#/$defs/identifier' },
1457
+ },
1458
+ acceptance: {
1459
+ type: 'array',
1460
+ items: { $ref: '#/$defs/featureAcceptance' },
1461
+ },
1462
+ evidence: {
1463
+ type: 'array',
1464
+ items: { $ref: '#/$defs/featureEvidence' },
1465
+ },
1466
+ identityCritical: { type: 'boolean' },
1467
+ objectInspection: { $ref: '#/$defs/objectInspectionSpec' },
1468
+ },
1469
+ },
1470
+ assumption: {
1471
+ type: 'object',
1472
+ additionalProperties: false,
1473
+ required: ['id', 'statement', 'certainty'],
1474
+ properties: {
1475
+ id: { $ref: '#/$defs/identifier' },
1476
+ statement: { type: 'string', minLength: 1 },
1477
+ certainty: { enum: ['low', 'medium', 'high'] },
1478
+ },
1479
+ },
1480
+ reviewConfiguration: {
1481
+ type: 'object',
1482
+ additionalProperties: false,
1483
+ required: ['heroView', 'requiredViews', 'lenses', 'maxCorrectionRounds'],
1484
+ properties: {
1485
+ heroView: { $ref: '#/$defs/identifier' },
1486
+ requiredViews: {
1487
+ type: 'array',
1488
+ minItems: 1,
1489
+ uniqueItems: true,
1490
+ items: { $ref: '#/$defs/identifier' },
1491
+ },
1492
+ lenses: {
1493
+ type: 'array',
1494
+ minItems: 1,
1495
+ uniqueItems: true,
1496
+ items: { enum: ['layout', 'geometry', 'final'] },
1497
+ },
1498
+ maxCorrectionRounds: {
1499
+ type: 'integer',
1500
+ minimum: 0,
1501
+ maximum: MAX_SCENE_CORRECTION_ROUNDS,
1502
+ },
1503
+ },
1504
+ },
1505
+ compositionFeasibility: {
1506
+ type: 'object',
1507
+ additionalProperties: false,
1508
+ required: ['status'],
1509
+ properties: {
1510
+ status: { enum: ['supported', 'conditional', 'blocked'] },
1511
+ reasons: {
1512
+ type: 'array',
1513
+ minItems: 1,
1514
+ items: { type: 'string', minLength: 1 },
1515
+ },
1516
+ },
1517
+ },
1518
+ compilationProvenance: {
1519
+ type: 'object',
1520
+ additionalProperties: false,
1521
+ required: ['adapter', 'skill', 'capabilityHash', 'inputHashes'],
1522
+ properties: {
1523
+ adapter: {
1524
+ type: 'object',
1525
+ additionalProperties: false,
1526
+ required: ['id', 'version'],
1527
+ properties: {
1528
+ id: { $ref: '#/$defs/identifier' },
1529
+ version: { type: 'string', minLength: 1 },
1530
+ },
1531
+ },
1532
+ skill: {
1533
+ type: 'object',
1534
+ additionalProperties: false,
1535
+ required: ['id', 'version'],
1536
+ properties: {
1537
+ id: { const: 'iwsdk-scene-composer' },
1538
+ version: { type: 'string', minLength: 1 },
1539
+ },
1540
+ },
1541
+ capabilityHash: { $ref: '#/$defs/sha256Hash' },
1542
+ inputHashes: {
1543
+ type: 'array',
1544
+ minItems: 1,
1545
+ uniqueItems: true,
1546
+ items: { $ref: '#/$defs/sha256Hash' },
1547
+ },
1548
+ },
1549
+ },
1550
+ composition: {
1551
+ type: 'object',
1552
+ additionalProperties: false,
1553
+ required: [
1554
+ 'mode',
1555
+ 'input',
1556
+ 'target',
1557
+ 'feasibility',
1558
+ 'provenance',
1559
+ 'representationPolicy',
1560
+ 'features',
1561
+ 'review',
1562
+ ],
1563
+ properties: {
1564
+ mode: { const: 'static' },
1565
+ input: { $ref: '#/$defs/compositionInput' },
1566
+ target: { $ref: '#/$defs/compositionTarget' },
1567
+ feasibility: { $ref: '#/$defs/compositionFeasibility' },
1568
+ provenance: { $ref: '#/$defs/compilationProvenance' },
1569
+ representationPolicy: { $ref: '#/$defs/representationPolicy' },
1570
+ features: {
1571
+ type: 'array',
1572
+ items: { $ref: '#/$defs/feature' },
1573
+ },
1574
+ assumptions: {
1575
+ type: 'array',
1576
+ items: { $ref: '#/$defs/assumption' },
1577
+ },
1578
+ review: { $ref: '#/$defs/reviewConfiguration' },
1579
+ },
1580
+ },
1581
+ nodeAnnotation: {
1582
+ type: 'object',
1583
+ additionalProperties: false,
1584
+ required: ['node', 'reviewLayer'],
1585
+ properties: {
1586
+ node: { $ref: '#/$defs/identifier' },
1587
+ featureRefs: {
1588
+ type: 'array',
1589
+ items: { $ref: '#/$defs/identifier' },
1590
+ },
1591
+ reviewLayer: { enum: ['layout', 'geometry', 'final'] },
1592
+ },
1593
+ },
1594
+ authoringView: {
1595
+ oneOf: [
1596
+ {
1597
+ type: 'object',
1598
+ additionalProperties: false,
1599
+ required: ['id', 'role', 'projection', 'position', 'target', 'fov'],
1600
+ properties: {
1601
+ id: { $ref: '#/$defs/identifier' },
1602
+ role: { enum: ['hero', 'diagnostic'] },
1603
+ projection: { const: 'perspective' },
1604
+ position: { $ref: '#/$defs/vec3' },
1605
+ target: { $ref: '#/$defs/vec3' },
1606
+ fov: {
1607
+ type: 'number',
1608
+ exclusiveMinimum: 0,
1609
+ exclusiveMaximum: 180,
1610
+ },
1611
+ },
1612
+ },
1613
+ {
1614
+ type: 'object',
1615
+ additionalProperties: false,
1616
+ required: [
1617
+ 'id',
1618
+ 'role',
1619
+ 'projection',
1620
+ 'position',
1621
+ 'target',
1622
+ 'height',
1623
+ ],
1624
+ properties: {
1625
+ id: { $ref: '#/$defs/identifier' },
1626
+ role: { enum: ['hero', 'diagnostic'] },
1627
+ projection: { const: 'orthographic' },
1628
+ position: { $ref: '#/$defs/vec3' },
1629
+ target: { $ref: '#/$defs/vec3' },
1630
+ height: { type: 'number', exclusiveMinimum: 0 },
1631
+ },
1632
+ },
1633
+ ],
1634
+ },
1635
+ authoring: {
1636
+ type: 'object',
1637
+ additionalProperties: false,
1638
+ properties: {
1639
+ composition: { $ref: '#/$defs/composition' },
1640
+ nodeAnnotations: {
1641
+ type: 'array',
1642
+ items: { $ref: '#/$defs/nodeAnnotation' },
1643
+ },
1644
+ views: {
1645
+ type: 'array',
1646
+ items: { $ref: '#/$defs/authoringView' },
1647
+ },
1648
+ },
1649
+ },
1650
+ },
1651
+ };
1652
+ const SCENE_REVIEW_V1_SCHEMA_ID = 'https://iwsdk.dev/schemas/iwsdk.scene-review.v1.schema.json';
1653
+ /** Immutable review evidence bound to one document/runtime revision pair. */
1654
+ const SCENE_REVIEW_V1_JSON_SCHEMA = {
1655
+ $id: SCENE_REVIEW_V1_SCHEMA_ID,
1656
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
1657
+ title: 'IWSDK Scene Review v1',
1658
+ description: 'Closed evidence record for deterministic layout, geometry, and final scene review.',
1659
+ type: 'object',
1660
+ additionalProperties: false,
1661
+ required: [
1662
+ 'version',
1663
+ 'documentHash',
1664
+ 'runtimeHash',
1665
+ 'capabilityHash',
1666
+ 'sourceHashes',
1667
+ 'round',
1668
+ 'result',
1669
+ 'lenses',
1670
+ 'featureResults',
1671
+ 'waivers',
1672
+ 'stop',
1673
+ ],
1674
+ properties: {
1675
+ version: { const: CURRENT_SCENE_REVIEW_VERSION },
1676
+ documentHash: { $ref: '#/$defs/sha256' },
1677
+ runtimeHash: { $ref: '#/$defs/sha256' },
1678
+ capabilityHash: { $ref: '#/$defs/sha256' },
1679
+ sourceHashes: {
1680
+ type: 'array',
1681
+ items: { $ref: '#/$defs/sha256' },
1682
+ },
1683
+ round: {
1684
+ type: 'integer',
1685
+ minimum: 0,
1686
+ maximum: MAX_SCENE_CORRECTION_ROUNDS,
1687
+ },
1688
+ previousReview: { $ref: '#/$defs/reviewLineage' },
1689
+ correction: { $ref: '#/$defs/correctionLineage' },
1690
+ result: { enum: ['pass', 'accepted-with-gaps', 'fail'] },
1691
+ lenses: {
1692
+ type: 'array',
1693
+ items: { $ref: '#/$defs/lens' },
1694
+ },
1695
+ featureResults: {
1696
+ type: 'array',
1697
+ items: { $ref: '#/$defs/featureResult' },
1698
+ },
1699
+ waivers: {
1700
+ type: 'array',
1701
+ items: { $ref: '#/$defs/waiver' },
1702
+ },
1703
+ stop: { $ref: '#/$defs/stop' },
1704
+ },
1705
+ $defs: {
1706
+ identifier: { type: 'string', minLength: 1 },
1707
+ sha256: {
1708
+ type: 'string',
1709
+ pattern: '^sha256:[0-9a-fA-F]{64}$',
1710
+ },
1711
+ vec3: {
1712
+ type: 'array',
1713
+ minItems: 3,
1714
+ maxItems: 3,
1715
+ items: { type: 'number' },
1716
+ },
1717
+ normalizedVec4: {
1718
+ type: 'array',
1719
+ minItems: 4,
1720
+ maxItems: 4,
1721
+ items: { type: 'number', minimum: 0, maximum: 1 },
1722
+ },
1723
+ jsonObject: {
1724
+ type: 'object',
1725
+ additionalProperties: { $ref: '#/$defs/jsonValue' },
1726
+ },
1727
+ jsonValue: {
1728
+ oneOf: [
1729
+ { type: 'string' },
1730
+ { type: 'number' },
1731
+ { type: 'boolean' },
1732
+ { type: 'null' },
1733
+ {
1734
+ type: 'array',
1735
+ items: { $ref: '#/$defs/jsonValue' },
1736
+ },
1737
+ {
1738
+ type: 'object',
1739
+ additionalProperties: { $ref: '#/$defs/jsonValue' },
1740
+ },
1741
+ ],
1742
+ },
1743
+ camera: {
1744
+ oneOf: [
1745
+ {
1746
+ type: 'object',
1747
+ additionalProperties: false,
1748
+ required: ['projection', 'position', 'target', 'fov'],
1749
+ properties: {
1750
+ projection: { const: 'perspective' },
1751
+ position: { $ref: '#/$defs/vec3' },
1752
+ target: { $ref: '#/$defs/vec3' },
1753
+ fov: {
1754
+ type: 'number',
1755
+ exclusiveMinimum: 0,
1756
+ exclusiveMaximum: 180,
1757
+ },
1758
+ },
1759
+ },
1760
+ {
1761
+ type: 'object',
1762
+ additionalProperties: false,
1763
+ required: ['projection', 'position', 'target', 'height'],
1764
+ properties: {
1765
+ projection: { const: 'orthographic' },
1766
+ position: { $ref: '#/$defs/vec3' },
1767
+ target: { $ref: '#/$defs/vec3' },
1768
+ height: { type: 'number', exclusiveMinimum: 0 },
1769
+ },
1770
+ },
1771
+ ],
1772
+ },
1773
+ capture: {
1774
+ type: 'object',
1775
+ additionalProperties: false,
1776
+ required: [
1777
+ 'id',
1778
+ 'view',
1779
+ 'path',
1780
+ 'screenshotSha256',
1781
+ 'width',
1782
+ 'height',
1783
+ 'camera',
1784
+ 'rendererEnvironment',
1785
+ 'visibleNodeIds',
1786
+ ],
1787
+ properties: {
1788
+ id: { $ref: '#/$defs/identifier' },
1789
+ view: { $ref: '#/$defs/identifier' },
1790
+ path: { type: 'string', minLength: 1 },
1791
+ screenshotSha256: { $ref: '#/$defs/sha256' },
1792
+ width: { type: 'integer', minimum: 1 },
1793
+ height: { type: 'integer', minimum: 1 },
1794
+ camera: { $ref: '#/$defs/camera' },
1795
+ rendererEnvironment: { $ref: '#/$defs/jsonObject' },
1796
+ visibleNodeIds: {
1797
+ type: 'array',
1798
+ items: { $ref: '#/$defs/identifier' },
1799
+ },
1800
+ nodeMaskRegions: {
1801
+ type: 'object',
1802
+ additionalProperties: { $ref: '#/$defs/normalizedVec4' },
1803
+ },
1804
+ },
1805
+ },
1806
+ reviewStatus: {
1807
+ enum: ['pass', 'partial', 'fail', 'not-applicable'],
1808
+ },
1809
+ lens: {
1810
+ type: 'object',
1811
+ additionalProperties: false,
1812
+ required: ['id', 'status', 'captures'],
1813
+ properties: {
1814
+ id: { enum: ['layout', 'geometry', 'final'] },
1815
+ status: { $ref: '#/$defs/reviewStatus' },
1816
+ captures: {
1817
+ type: 'array',
1818
+ items: { $ref: '#/$defs/capture' },
1819
+ },
1820
+ },
1821
+ },
1822
+ featureResult: {
1823
+ type: 'object',
1824
+ additionalProperties: false,
1825
+ required: ['feature', 'criterion', 'status', 'evidenceRefs'],
1826
+ properties: {
1827
+ feature: { $ref: '#/$defs/identifier' },
1828
+ criterion: { $ref: '#/$defs/identifier' },
1829
+ status: { $ref: '#/$defs/reviewStatus' },
1830
+ evidenceRefs: {
1831
+ type: 'array',
1832
+ items: { $ref: '#/$defs/identifier' },
1833
+ },
1834
+ observation: { type: 'string' },
1835
+ },
1836
+ },
1837
+ reviewLineage: {
1838
+ type: 'object',
1839
+ additionalProperties: false,
1840
+ required: ['path', 'reviewSha256'],
1841
+ properties: {
1842
+ path: { type: 'string', minLength: 1 },
1843
+ reviewSha256: { $ref: '#/$defs/sha256' },
1844
+ },
1845
+ },
1846
+ correctionLineage: {
1847
+ type: 'object',
1848
+ additionalProperties: false,
1849
+ required: ['path', 'correctionSha256'],
1850
+ properties: {
1851
+ path: { type: 'string', minLength: 1 },
1852
+ correctionSha256: { $ref: '#/$defs/sha256' },
1853
+ },
1854
+ },
1855
+ waiver: {
1856
+ type: 'object',
1857
+ additionalProperties: false,
1858
+ required: ['feature', 'criterion', 'reason', 'authorizedBy'],
1859
+ properties: {
1860
+ feature: { $ref: '#/$defs/identifier' },
1861
+ criterion: { $ref: '#/$defs/identifier' },
1862
+ reason: { type: 'string', minLength: 1 },
1863
+ authorizedBy: { const: 'user' },
1864
+ },
1865
+ },
1866
+ stop: {
1867
+ type: 'object',
1868
+ additionalProperties: false,
1869
+ required: ['reason', 'openDefectTags'],
1870
+ properties: {
1871
+ reason: {
1872
+ enum: [
1873
+ 'success',
1874
+ 'continue-refining',
1875
+ 'round-limit',
1876
+ 'repeated-defect',
1877
+ 'oscillation',
1878
+ 'plateau',
1879
+ 'missing-input',
1880
+ 'representation-gap',
1881
+ ],
1882
+ },
1883
+ openDefectTags: {
1884
+ type: 'array',
1885
+ items: { type: 'string', minLength: 1 },
1886
+ },
1887
+ },
1888
+ },
1889
+ },
1890
+ };
1891
+ const SCENE_REVIEW_JSON_SCHEMA = SCENE_REVIEW_V1_JSON_SCHEMA;
1892
+
1893
+ /**
1894
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1895
+ *
1896
+ * This source code is licensed under the MIT license found in the
1897
+ * LICENSE file in the root directory of this source tree.
1898
+ */
1899
+ const MAX_SCENE_COORDINATE = 1_000_000;
1900
+ const MAX_SCENE_NODES = 10_000;
1901
+ const MAX_SCENE_RESOURCES = 4_096;
1902
+ const MAX_SCENE_PATTERN_EXPANSION = 10_000;
1903
+ function validateSceneDocument(value, options = {}) {
1904
+ const issues = validateSchema(value, SCENE_DOCUMENT_JSON_SCHEMA);
1905
+ if (issues.length === 0) {
1906
+ validateSceneSemantics(value, issues, options.componentCatalog, options.validateAuthoringWorkflow !== false, options.validateComponentLinks !== false, options.knownAssetIds == null
1907
+ ? undefined
1908
+ : new Set(options.knownAssetIds));
1909
+ }
1910
+ return { valid: issues.length === 0, issues };
1911
+ }
1912
+ function validateSceneReview(value) {
1913
+ const issues = validateSchema(value, SCENE_REVIEW_JSON_SCHEMA);
1914
+ if (issues.length === 0) {
1915
+ validateReviewSemantics(value, issues);
1916
+ }
1917
+ return { valid: issues.length === 0, issues };
1918
+ }
1919
+ function assertValidSceneDocument(value, options = {}) {
1920
+ assertValidationResult('IWSDK scene document', validateSceneDocument(value, options));
1921
+ }
1922
+ function assertValidSceneReview(value) {
1923
+ assertValidationResult('IWSDK scene review', validateSceneReview(value));
1924
+ }
1925
+ function assertValidationResult(label, result) {
1926
+ if (!result.valid) {
1927
+ const details = result.issues
1928
+ .map((issue) => `${issue.path}: ${issue.message}`)
1929
+ .join('\n');
1930
+ throw new Error(`Invalid ${label}:\n${details}`);
1931
+ }
1932
+ }
1933
+ /** Validates the Draft 2020-12 subset used by the exported closed schemas. */
1934
+ function validateSchema(value, rootSchemaValue) {
1935
+ const issues = [];
1936
+ const rootSchema = rootSchemaValue;
1937
+ validateSchemaValue(value, rootSchema, rootSchema, '$', issues);
1938
+ return issues;
1939
+ }
1940
+ function validateSchemaValue(value, schema, rootSchema, path, issues) {
1941
+ if (schema === true) {
1942
+ return;
1943
+ }
1944
+ if (schema === false) {
1945
+ addIssue(issues, path, 'value is not allowed', 'schema');
1946
+ return;
1947
+ }
1948
+ const reference = schema.$ref;
1949
+ if (typeof reference === 'string') {
1950
+ const resolved = resolveSchemaReference(reference, rootSchema);
1951
+ if (resolved == null) {
1952
+ addIssue(issues, path, `unresolved schema reference "${reference}"`, 'schema');
1953
+ return;
1954
+ }
1955
+ validateSchemaValue(value, resolved, rootSchema, path, issues);
1956
+ return;
1957
+ }
1958
+ if (Array.isArray(schema.allOf)) {
1959
+ for (const branch of schema.allOf) {
1960
+ validateSchemaValue(value, branch, rootSchema, path, issues);
1961
+ }
1962
+ }
1963
+ if (Array.isArray(schema.anyOf)) {
1964
+ if (!schema.anyOf.some((branch) => schemaMatches(value, branch, rootSchema))) {
1965
+ addIssue(issues, path, 'value must match at least one allowed schema', 'schema');
1966
+ return;
1967
+ }
1968
+ }
1969
+ if (Array.isArray(schema.oneOf)) {
1970
+ const discriminator = selectDiscriminatedBranch(value, schema.oneOf);
1971
+ if (discriminator != null) {
1972
+ validateSchemaValue(value, discriminator, rootSchema, path, issues);
1973
+ return;
1974
+ }
1975
+ const matches = schema.oneOf.filter((branch) => schemaMatches(value, branch, rootSchema));
1976
+ if (matches.length !== 1) {
1977
+ const branchIssues = schema.oneOf.map((branch) => {
1978
+ const candidate = [];
1979
+ validateSchemaValue(value, branch, rootSchema, path, candidate);
1980
+ return candidate;
1981
+ });
1982
+ const closest = branchIssues.sort((left, right) => left.length - right.length)[0];
1983
+ if (closest != null && closest.length > 0) {
1984
+ issues.push(...closest);
1985
+ }
1986
+ else {
1987
+ addIssue(issues, path, 'value must match exactly one allowed schema', 'schema');
1988
+ }
1989
+ return;
1990
+ }
1991
+ return;
1992
+ }
1993
+ if (schema.not != null &&
1994
+ schemaMatches(value, schema.not, rootSchema)) {
1995
+ addIssue(issues, path, 'value matches a prohibited schema', 'schema');
1996
+ return;
1997
+ }
1998
+ if ('const' in schema && !jsonEqual(value, schema.const)) {
1999
+ addIssue(issues, path, `value must equal ${JSON.stringify(schema.const)}`, 'schema');
2000
+ return;
2001
+ }
2002
+ if (Array.isArray(schema.enum) &&
2003
+ !schema.enum.some((entry) => jsonEqual(value, entry))) {
2004
+ addIssue(issues, path, 'value is not one of the allowed values', 'schema');
2005
+ return;
2006
+ }
2007
+ if (!validateSchemaType(value, schema.type, path, issues)) {
2008
+ return;
2009
+ }
2010
+ if (typeof value === 'string') {
2011
+ validateStringSchema(value, schema, path, issues);
2012
+ }
2013
+ else if (typeof value === 'number') {
2014
+ validateNumberSchema(value, schema, path, issues);
2015
+ }
2016
+ else if (Array.isArray(value)) {
2017
+ validateArraySchema(value, schema, rootSchema, path, issues);
2018
+ }
2019
+ else if (isPlainObject(value)) {
2020
+ validateObjectSchema(value, schema, rootSchema, path, issues);
2021
+ }
2022
+ if (isPlainObject(schema.if)) {
2023
+ const branch = schemaMatches(value, schema.if, rootSchema)
2024
+ ? schema.then
2025
+ : schema.else;
2026
+ if (branch != null) {
2027
+ validateSchemaValue(value, branch, rootSchema, path, issues);
2028
+ }
2029
+ }
2030
+ }
2031
+ function validateSchemaType(value, type, path, issues) {
2032
+ if (type == null) {
2033
+ return true;
2034
+ }
2035
+ const types = Array.isArray(type) ? type : [type];
2036
+ const matches = types.some((candidate) => {
2037
+ switch (candidate) {
2038
+ case 'null':
2039
+ return value === null;
2040
+ case 'boolean':
2041
+ return typeof value === 'boolean';
2042
+ case 'string':
2043
+ return typeof value === 'string';
2044
+ case 'number':
2045
+ return isFiniteNumber(value);
2046
+ case 'integer':
2047
+ return isFiniteNumber(value) && Number.isInteger(value);
2048
+ case 'array':
2049
+ return Array.isArray(value);
2050
+ case 'object':
2051
+ return isPlainObject(value);
2052
+ default:
2053
+ return false;
2054
+ }
2055
+ });
2056
+ if (!matches) {
2057
+ addIssue(issues, path, `value must be ${types.join(' or ')}`, 'schema');
2058
+ }
2059
+ return matches;
2060
+ }
2061
+ function validateStringSchema(value, schema, path, issues) {
2062
+ if (typeof schema.minLength === 'number' && value.length < schema.minLength) {
2063
+ addIssue(issues, path, `string must contain at least ${schema.minLength} characters`, 'schema');
2064
+ }
2065
+ if (typeof schema.maxLength === 'number' && value.length > schema.maxLength) {
2066
+ addIssue(issues, path, `string must contain at most ${schema.maxLength} characters`, 'schema');
2067
+ }
2068
+ if (typeof schema.pattern === 'string' &&
2069
+ !new RegExp(schema.pattern, 'u').test(value)) {
2070
+ addIssue(issues, path, `string must match ${schema.pattern}`, 'schema');
2071
+ }
2072
+ }
2073
+ function validateNumberSchema(value, schema, path, issues) {
2074
+ if (typeof schema.minimum === 'number' && value < schema.minimum) {
2075
+ addIssue(issues, path, `number must be at least ${schema.minimum}`, 'schema');
2076
+ }
2077
+ if (typeof schema.maximum === 'number' && value > schema.maximum) {
2078
+ addIssue(issues, path, `number must be at most ${schema.maximum}`, 'schema');
2079
+ }
2080
+ if (typeof schema.exclusiveMinimum === 'number' &&
2081
+ value <= schema.exclusiveMinimum) {
2082
+ addIssue(issues, path, `number must be above ${schema.exclusiveMinimum}`, 'schema');
2083
+ }
2084
+ if (typeof schema.exclusiveMaximum === 'number' &&
2085
+ value >= schema.exclusiveMaximum) {
2086
+ addIssue(issues, path, `number must be below ${schema.exclusiveMaximum}`, 'schema');
2087
+ }
2088
+ }
2089
+ function validateArraySchema(value, schema, rootSchema, path, issues) {
2090
+ if (typeof schema.minItems === 'number' && value.length < schema.minItems) {
2091
+ addIssue(issues, path, `array must contain at least ${schema.minItems} items`, 'schema');
2092
+ }
2093
+ if (typeof schema.maxItems === 'number' && value.length > schema.maxItems) {
2094
+ addIssue(issues, path, `array must contain at most ${schema.maxItems} items`, 'schema');
2095
+ }
2096
+ if (schema.uniqueItems === true) {
2097
+ const seen = new Set();
2098
+ for (let index = 0; index < value.length; index += 1) {
2099
+ const key = JSON.stringify(value[index]);
2100
+ if (seen.has(key)) {
2101
+ addIssue(issues, `${path}[${index}]`, 'array items must be unique', 'schema');
2102
+ }
2103
+ seen.add(key);
2104
+ }
2105
+ }
2106
+ if (Array.isArray(schema.prefixItems)) {
2107
+ schema.prefixItems.forEach((itemSchema, index) => {
2108
+ if (index < value.length) {
2109
+ validateSchemaValue(value[index], itemSchema, rootSchema, `${path}[${index}]`, issues);
2110
+ }
2111
+ });
2112
+ }
2113
+ if (schema.items != null && !Array.isArray(schema.items)) {
2114
+ const start = Array.isArray(schema.prefixItems)
2115
+ ? schema.prefixItems.length
2116
+ : 0;
2117
+ for (let index = start; index < value.length; index += 1) {
2118
+ validateSchemaValue(value[index], schema.items, rootSchema, `${path}[${index}]`, issues);
2119
+ }
2120
+ }
2121
+ }
2122
+ function validateObjectSchema(value, schema, rootSchema, path, issues) {
2123
+ const properties = isPlainObject(schema.properties) ? schema.properties : {};
2124
+ if (isPlainObject(schema.propertyNames)) {
2125
+ for (const key of Object.keys(value)) {
2126
+ validateSchemaValue(key, schema.propertyNames, rootSchema, childPath(path, key), issues);
2127
+ }
2128
+ }
2129
+ if (Array.isArray(schema.required)) {
2130
+ for (const key of schema.required) {
2131
+ if (typeof key === 'string' && !(key in value)) {
2132
+ addIssue(issues, childPath(path, key), 'required property is missing', 'schema');
2133
+ }
2134
+ }
2135
+ }
2136
+ if (typeof schema.minProperties === 'number' &&
2137
+ Object.keys(value).length < schema.minProperties) {
2138
+ addIssue(issues, path, `object must contain at least ${schema.minProperties} properties`, 'schema');
2139
+ }
2140
+ if (typeof schema.maxProperties === 'number' &&
2141
+ Object.keys(value).length > schema.maxProperties) {
2142
+ addIssue(issues, path, `object must contain at most ${schema.maxProperties} properties`, 'schema');
2143
+ }
2144
+ for (const [key, entry] of Object.entries(value)) {
2145
+ const propertySchema = properties[key];
2146
+ if (propertySchema != null) {
2147
+ validateSchemaValue(entry, propertySchema, rootSchema, childPath(path, key), issues);
2148
+ continue;
2149
+ }
2150
+ if (schema.additionalProperties === false) {
2151
+ addIssue(issues, childPath(path, key), 'property is not allowed', 'schema');
2152
+ }
2153
+ else if (isPlainObject(schema.additionalProperties) ||
2154
+ typeof schema.additionalProperties === 'boolean') {
2155
+ validateSchemaValue(entry, schema.additionalProperties, rootSchema, childPath(path, key), issues);
2156
+ }
2157
+ }
2158
+ }
2159
+ function resolveSchemaReference(reference, rootSchema) {
2160
+ if (!reference.startsWith('#/') || typeof rootSchema === 'boolean') {
2161
+ return undefined;
2162
+ }
2163
+ let current = rootSchema;
2164
+ for (const rawSegment of reference.slice(2).split('/')) {
2165
+ const segment = rawSegment.replace(/~1/g, '/').replace(/~0/g, '~');
2166
+ if (!isPlainObject(current) || !(segment in current)) {
2167
+ return undefined;
2168
+ }
2169
+ current = current[segment];
2170
+ }
2171
+ return typeof current === 'boolean' || isPlainObject(current)
2172
+ ? current
2173
+ : undefined;
2174
+ }
2175
+ function selectDiscriminatedBranch(value, branches) {
2176
+ if (!isPlainObject(value)) {
2177
+ return undefined;
2178
+ }
2179
+ for (const discriminator of ['type', 'model', 'kind', 'projection']) {
2180
+ const discriminant = value[discriminator];
2181
+ if (discriminant == null) {
2182
+ continue;
2183
+ }
2184
+ const matching = branches.filter((branch) => {
2185
+ if (!isPlainObject(branch) || !isPlainObject(branch.properties)) {
2186
+ return false;
2187
+ }
2188
+ const property = branch.properties[discriminator];
2189
+ return isPlainObject(property) && property.const === discriminant;
2190
+ });
2191
+ if (matching.length === 1) {
2192
+ return matching[0];
2193
+ }
2194
+ }
2195
+ return undefined;
2196
+ }
2197
+ function schemaMatches(value, schema, rootSchema) {
2198
+ const issues = [];
2199
+ validateSchemaValue(value, schema, rootSchema, '$', issues);
2200
+ return issues.length === 0;
2201
+ }
2202
+ function jsonEqual(left, right) {
2203
+ return JSON.stringify(left) === JSON.stringify(right);
2204
+ }
2205
+ function childPath(path, key) {
2206
+ return /^[A-Za-z_$][A-Za-z0-9_$-]*$/.test(key)
2207
+ ? `${path}.${key}`
2208
+ : `${path}[${JSON.stringify(key)}]`;
2209
+ }
2210
+ function validateSceneSemantics(document, issues, componentCatalog, validateAuthoringWorkflow, validateLinkedComponentFields, knownAssetIds) {
2211
+ validateSceneImports(document.imports ?? [], issues);
2212
+ validateMetadataNamespaces(document.metadata, '$.metadata', issues);
2213
+ const resourceIds = new Map();
2214
+ const prefabIds = new Set();
2215
+ const resources = document.resources;
2216
+ const resourceCount = resources.prefabs?.length ?? 0;
2217
+ if (resourceCount > MAX_SCENE_RESOURCES) {
2218
+ addIssue(issues, '$.resources', `resource count exceeds ${MAX_SCENE_RESOURCES}`, 'limit');
2219
+ }
2220
+ const registerResource = (id, path, kind) => {
2221
+ const previous = resourceIds.get(id);
2222
+ if (previous != null) {
2223
+ addIssue(issues, path, `duplicate resource id "${id}" (already used by ${previous})`, 'duplicate-id');
2224
+ }
2225
+ else {
2226
+ resourceIds.set(id, kind);
2227
+ }
2228
+ };
2229
+ resources.prefabs?.forEach((prefab, index) => {
2230
+ registerResource(prefab.id, `$.resources.prefabs[${index}].id`, 'prefab');
2231
+ prefabIds.add(prefab.id);
2232
+ });
2233
+ const schemas = validateComponentCatalog(componentCatalog, issues);
2234
+ const mainNodeIds = collectNodeIdsStrict(document.nodes, '$.nodes', issues);
2235
+ validateComponents(document.components, '$.components', schemas, componentCatalog != null, issues);
2236
+ validateRootComponents(document.components, issues);
2237
+ validatePlayerComponents(document, schemas, componentCatalog != null, issues);
2238
+ if (componentCatalog != null && validateLinkedComponentFields) {
2239
+ validateComponentLinks(document, schemas, mainNodeIds, issues);
2240
+ }
2241
+ let totalNodes = mainNodeIds.size;
2242
+ const prefabNodeIds = new Map();
2243
+ resources.prefabs?.forEach((prefab, index) => {
2244
+ const path = `$.resources.prefabs[${index}].root`;
2245
+ const localIds = collectNodeIdsStrict([prefab.root], path, issues);
2246
+ prefabNodeIds.set(prefab.id, localIds);
2247
+ totalNodes += localIds.size;
2248
+ });
2249
+ resources.prefabs?.forEach((prefab, index) => {
2250
+ const path = `$.resources.prefabs[${index}].root`;
2251
+ validateNodes([prefab.root], path, prefabIds, prefabNodeIds, schemas, componentCatalog != null, knownAssetIds, issues, false);
2252
+ });
2253
+ if (totalNodes > MAX_SCENE_NODES) {
2254
+ addIssue(issues, '$.nodes', `node count exceeds ${MAX_SCENE_NODES}`, 'limit');
2255
+ }
2256
+ validateNodes(document.nodes, '$.nodes', prefabIds, prefabNodeIds, schemas, componentCatalog != null, knownAssetIds, issues, true);
2257
+ validatePrefabCycles(document, prefabIds, issues);
2258
+ if (!issues.some((issue) => ['cycle', 'duplicate-id', 'limit', 'reference'].includes(issue.code ?? ''))) {
2259
+ validateRuntimeNodeIds(document, issues);
2260
+ }
2261
+ if (validateAuthoringWorkflow) {
2262
+ validateAuthoring(document, mainNodeIds, issues);
2263
+ }
2264
+ if (document.environment?.fog?.type === 'linear' &&
2265
+ document.environment.fog.near >= document.environment.fog.far) {
2266
+ addIssue(issues, '$.environment.fog', 'linear fog near must be below far', 'range');
2267
+ }
2268
+ }
2269
+ function validateSceneImports(imports, issues) {
2270
+ const ids = new Set();
2271
+ const safeId = new RegExp(SCENE_IMPORT_ID_PATTERN, 'u');
2272
+ imports.forEach((sceneImport, index) => {
2273
+ const path = `$.imports[${index}]`;
2274
+ if (!safeId.test(sceneImport.id)) {
2275
+ addIssue(issues, `${path}.id`, 'import id must start with an ASCII letter and contain only ASCII letters, digits, "_", or "-"', 'unsafe-id');
2276
+ }
2277
+ if (ids.has(sceneImport.id)) {
2278
+ addIssue(issues, `${path}.id`, `duplicate import id "${sceneImport.id}"`, 'duplicate-id');
2279
+ }
2280
+ ids.add(sceneImport.id);
2281
+ if (sceneImport.src.trim().length === 0) {
2282
+ addIssue(issues, `${path}.src`, 'import source must not be blank', 'unsafe-uri');
2283
+ }
2284
+ });
2285
+ }
2286
+ function validateRuntimeNodeIds(document, issues) {
2287
+ let entries;
2288
+ try {
2289
+ entries = collectSceneRuntimeNodeIds(document, MAX_SCENE_PATTERN_EXPANSION);
2290
+ }
2291
+ catch (error) {
2292
+ addIssue(issues, '$.nodes', error instanceof Error ? error.message : String(error), 'limit');
2293
+ return;
2294
+ }
2295
+ const seen = new Map();
2296
+ for (const entry of entries) {
2297
+ const previous = seen.get(entry.id);
2298
+ if (previous == null) {
2299
+ seen.set(entry.id, entry);
2300
+ continue;
2301
+ }
2302
+ if (!entry.derived && !previous.derived) {
2303
+ continue;
2304
+ }
2305
+ addIssue(issues, `${entry.sourcePath}.id`, `derived runtime node id "${entry.id}" collides with ${previous.sourcePath}`, 'duplicate-id');
2306
+ }
2307
+ }
2308
+ function validateNodes(nodes, path, prefabIds, prefabNodeIds, schemas, validateComponentFields, knownAssetIds, issues, allowPlayerParent) {
2309
+ nodes.forEach((node, index) => {
2310
+ const nodePath = nodes.length === 1 && path.endsWith('.root') ? path : `${path}[${index}]`;
2311
+ validateTransformCoordinates(node.transform, `${nodePath}.transform`, issues);
2312
+ if (node.parent != null && !allowPlayerParent) {
2313
+ addIssue(issues, `${nodePath}.parent`, 'player-space parents are only valid on top-level scene nodes', 'conflict');
2314
+ }
2315
+ validateMetadataNamespaces(node.metadata, `${nodePath}.metadata`, issues);
2316
+ const content = node.content;
2317
+ if (content?.type === 'asset' &&
2318
+ knownAssetIds != null &&
2319
+ !knownAssetIds.has(content.asset)) {
2320
+ addIssue(issues, `${nodePath}.content.asset`, `asset "${content.asset}" is not declared in the project asset catalog; add "${content.asset}" to the asset manifest or replace this reference with a declared asset id`, 'reference');
2321
+ }
2322
+ if (content?.type === 'instance' || content?.type === 'pattern') {
2323
+ if (!prefabIds.has(content.prefab)) {
2324
+ addIssue(issues, `${nodePath}.content.prefab`, `unknown prefab "${content.prefab}"`, 'reference');
2325
+ }
2326
+ if (content.type === 'pattern') {
2327
+ validatePatternExpansion(content.distribution, `${nodePath}.content.distribution`, issues);
2328
+ }
2329
+ }
2330
+ if (content?.type === 'instance' || content?.type === 'pattern') {
2331
+ validatePrefabOverrides(content.overrides, content.prefab, nodePath, prefabNodeIds, schemas, validateComponentFields, issues);
2332
+ }
2333
+ validateComponents(node.components, `${nodePath}.components`, schemas, validateComponentFields, issues);
2334
+ validateNodes(node.children ?? [], `${nodePath}.children`, prefabIds, prefabNodeIds, schemas, validateComponentFields, knownAssetIds, issues, false);
2335
+ });
2336
+ }
2337
+ function collectNodeIdsStrict(nodes, path, issues) {
2338
+ const ids = new Set();
2339
+ const visit = (entries, entryPath) => {
2340
+ entries.forEach((node, index) => {
2341
+ const nodePath = entries.length === 1 && entryPath.endsWith('.root')
2342
+ ? entryPath
2343
+ : `${entryPath}[${index}]`;
2344
+ if (ids.has(node.id)) {
2345
+ addIssue(issues, `${nodePath}.id`, `duplicate node id "${node.id}"`, 'duplicate-id');
2346
+ }
2347
+ ids.add(node.id);
2348
+ visit(node.children ?? [], `${nodePath}.children`);
2349
+ });
2350
+ };
2351
+ visit(nodes, path);
2352
+ return ids;
2353
+ }
2354
+ function validatePrefabCycles(document, prefabIds, issues) {
2355
+ const graph = new Map();
2356
+ document.resources.prefabs?.forEach((prefab) => {
2357
+ const dependencies = new Set();
2358
+ walkNodes([prefab.root], '$', (node) => {
2359
+ if ((node.content?.type === 'instance' ||
2360
+ node.content?.type === 'pattern') &&
2361
+ prefabIds.has(node.content.prefab)) {
2362
+ dependencies.add(node.content.prefab);
2363
+ }
2364
+ });
2365
+ graph.set(prefab.id, dependencies);
2366
+ });
2367
+ const visiting = new Set();
2368
+ const visited = new Set();
2369
+ const visit = (id, trail) => {
2370
+ if (visiting.has(id)) {
2371
+ addIssue(issues, '$.resources.prefabs', `prefab recursion: ${[...trail, id].join(' -> ')}`, 'cycle');
2372
+ return;
2373
+ }
2374
+ if (visited.has(id)) {
2375
+ return;
2376
+ }
2377
+ visiting.add(id);
2378
+ for (const dependency of graph.get(id) ?? []) {
2379
+ visit(dependency, [...trail, id]);
2380
+ }
2381
+ visiting.delete(id);
2382
+ visited.add(id);
2383
+ };
2384
+ for (const id of graph.keys()) {
2385
+ visit(id, []);
2386
+ }
2387
+ }
2388
+ function validateAuthoring(document, nodeIds, issues) {
2389
+ const authoring = document.authoring;
2390
+ if (authoring == null) {
2391
+ return;
2392
+ }
2393
+ const viewIds = new Set();
2394
+ const viewsById = new Map();
2395
+ authoring.views?.forEach((view, index) => {
2396
+ if (viewIds.has(view.id)) {
2397
+ addIssue(issues, `$.authoring.views[${index}].id`, `duplicate view id "${view.id}"`, 'duplicate-id');
2398
+ }
2399
+ viewIds.add(view.id);
2400
+ viewsById.set(view.id, view);
2401
+ });
2402
+ const composition = authoring.composition;
2403
+ const referenceIds = new Set();
2404
+ composition?.input.references?.forEach((reference, index) => {
2405
+ if (referenceIds.has(reference.id)) {
2406
+ addIssue(issues, `$.authoring.composition.input.references[${index}].id`, `duplicate reference id "${reference.id}"`, 'duplicate-id');
2407
+ }
2408
+ referenceIds.add(reference.id);
2409
+ validateSafeUri(reference.uri, `$.authoring.composition.input.references[${index}].uri`, issues);
2410
+ });
2411
+ if (composition != null) {
2412
+ if ((composition.input.kind === 'text' ||
2413
+ composition.input.kind === 'hybrid') &&
2414
+ !nonEmpty(composition.input.prompt)) {
2415
+ addIssue(issues, '$.authoring.composition.input.prompt', `${composition.input.kind} input requires a prompt`, 'required');
2416
+ }
2417
+ if ((composition.input.kind === 'image' ||
2418
+ composition.input.kind === 'hybrid') &&
2419
+ (composition.input.references?.length ?? 0) === 0) {
2420
+ addIssue(issues, '$.authoring.composition.input.references', `${composition.input.kind} input requires references`, 'required');
2421
+ }
2422
+ if (composition.feasibility.status === 'blocked') {
2423
+ addIssue(issues, '$.authoring.composition.feasibility.status', 'blocked composition cannot be materialized', 'state');
2424
+ }
2425
+ if (composition.feasibility.status === 'conditional' &&
2426
+ (composition.representationPolicy.acceptedApproximations?.length ?? 0) ===
2427
+ 0) {
2428
+ addIssue(issues, '$.authoring.composition.representationPolicy.acceptedApproximations', 'conditional composition requires an accepted approximation', 'required');
2429
+ }
2430
+ const provenanceInputs = new Set(composition.provenance.inputHashes.map((hash) => hash.toLowerCase()));
2431
+ const declaredInputHashes = new Set(getSceneCompositionSourceHashes(composition.input).map((hash) => hash.toLowerCase()));
2432
+ declaredInputHashes.forEach((expected) => {
2433
+ if (!provenanceInputs.has(expected)) {
2434
+ addIssue(issues, '$.authoring.composition.provenance.inputHashes', `declared input hash "${expected}" is missing from compilation provenance`, 'reference');
2435
+ }
2436
+ });
2437
+ provenanceInputs.forEach((actual) => {
2438
+ if (!declaredInputHashes.has(actual)) {
2439
+ addIssue(issues, '$.authoring.composition.provenance.inputHashes', `compilation provenance hash "${actual}" does not identify a declared prompt or reference`, 'reference');
2440
+ }
2441
+ });
2442
+ validateCompositionPolicies(document, composition, issues);
2443
+ const featureIds = new Set();
2444
+ composition.features.forEach((feature, featureIndex) => {
2445
+ const featurePath = `$.authoring.composition.features[${featureIndex}]`;
2446
+ if (featureIds.has(feature.id)) {
2447
+ addIssue(issues, `${featurePath}.id`, `duplicate feature id "${feature.id}"`, 'duplicate-id');
2448
+ }
2449
+ featureIds.add(feature.id);
2450
+ if (feature.priority === 'required' && feature.acceptance.length === 0) {
2451
+ addIssue(issues, `${featurePath}.acceptance`, 'required feature must declare acceptance criteria', 'required');
2452
+ }
2453
+ validateNodeReferences(feature.nodeRefs, `${featurePath}.nodeRefs`, nodeIds, issues);
2454
+ validateObjectInspection(document, feature, featurePath, nodeIds, viewIds, new Set([
2455
+ composition.review.heroView,
2456
+ ...composition.review.requiredViews,
2457
+ ]), issues);
2458
+ const criterionIds = new Set();
2459
+ const acceptanceCoveredBindings = new Set();
2460
+ feature.acceptance.forEach((criterion, criterionIndex) => {
2461
+ const criterionPath = `${featurePath}.acceptance[${criterionIndex}]`;
2462
+ if (criterionIds.has(criterion.id)) {
2463
+ addIssue(issues, `${criterionPath}.id`, `duplicate criterion id "${criterion.id}"`, 'duplicate-id');
2464
+ }
2465
+ criterionIds.add(criterion.id);
2466
+ validateAcceptance(criterion, criterionPath, document, nodeIds, viewIds, referenceIds, issues);
2467
+ acceptanceSubjectNodeReferences(criterion).forEach((subject) => {
2468
+ if (!nodeIds.has(subject.nodeId)) {
2469
+ return;
2470
+ }
2471
+ const coveringBindings = feature.nodeRefs.filter((binding) => isNodeSameOrDescendant(document.nodes, subject.nodeId, binding));
2472
+ if (coveringBindings.length === 0) {
2473
+ addIssue(issues, `${criterionPath}.${subject.path}`, `criterion subject node "${subject.nodeId}" is outside feature "${feature.id}" node bindings`, 'reference');
2474
+ return;
2475
+ }
2476
+ coveringBindings.forEach((binding) => acceptanceCoveredBindings.add(binding));
2477
+ });
2478
+ });
2479
+ if (feature.priority === 'required') {
2480
+ feature.nodeRefs.forEach((nodeRef, nodeRefIndex) => {
2481
+ if (nodeIds.has(nodeRef) && !acceptanceCoveredBindings.has(nodeRef)) {
2482
+ addIssue(issues, `${featurePath}.nodeRefs[${nodeRefIndex}]`, `required feature binding "${nodeRef}" is not covered by an acceptance criterion subject`, 'required');
2483
+ }
2484
+ });
2485
+ }
2486
+ feature.evidence?.forEach((evidence, evidenceIndex) => {
2487
+ if (!referenceIds.has(evidence.reference)) {
2488
+ addIssue(issues, `${featurePath}.evidence[${evidenceIndex}].reference`, `unknown reference "${evidence.reference}"`, 'reference');
2489
+ }
2490
+ if (evidence.region != null) {
2491
+ validateNormalizedRegion(evidence.region, `${featurePath}.evidence[${evidenceIndex}].region`, issues);
2492
+ }
2493
+ });
2494
+ });
2495
+ const reviewPath = '$.authoring.composition.review';
2496
+ if (!viewIds.has(composition.review.heroView)) {
2497
+ addIssue(issues, `${reviewPath}.heroView`, `unknown view "${composition.review.heroView}"`, 'reference');
2498
+ }
2499
+ if (viewsById.get(composition.review.heroView)?.role !== 'hero') {
2500
+ addIssue(issues, `${reviewPath}.heroView`, 'heroView must reference a hero-role view', 'reference');
2501
+ }
2502
+ composition.review.requiredViews.forEach((view, index) => {
2503
+ if (!viewIds.has(view)) {
2504
+ addIssue(issues, `${reviewPath}.requiredViews[${index}]`, `unknown view "${view}"`, 'reference');
2505
+ }
2506
+ });
2507
+ composition.representationPolicy.acceptedApproximations?.forEach((approximation, index) => {
2508
+ if (!featureIds.has(approximation.feature)) {
2509
+ addIssue(issues, `$.authoring.composition.representationPolicy.acceptedApproximations[${index}].feature`, `unknown feature "${approximation.feature}"`, 'reference');
2510
+ }
2511
+ });
2512
+ const assumptionIds = new Set();
2513
+ composition.assumptions?.forEach((assumption, index) => {
2514
+ if (assumptionIds.has(assumption.id)) {
2515
+ addIssue(issues, `$.authoring.composition.assumptions[${index}].id`, `duplicate assumption id "${assumption.id}"`, 'duplicate-id');
2516
+ }
2517
+ assumptionIds.add(assumption.id);
2518
+ });
2519
+ }
2520
+ authoring.nodeAnnotations?.forEach((annotation, index) => {
2521
+ if (!nodeIds.has(annotation.node)) {
2522
+ addIssue(issues, `$.authoring.nodeAnnotations[${index}].node`, `unknown node "${annotation.node}"`, 'reference');
2523
+ }
2524
+ annotation.featureRefs?.forEach((feature, featureIndex) => {
2525
+ if (!composition?.features.some((entry) => entry.id === feature)) {
2526
+ addIssue(issues, `$.authoring.nodeAnnotations[${index}].featureRefs[${featureIndex}]`, `unknown feature "${feature}"`, 'reference');
2527
+ }
2528
+ });
2529
+ });
2530
+ validateLayoutReviewVisibility(document, issues);
2531
+ }
2532
+ function validateLayoutReviewVisibility(document, issues) {
2533
+ const annotations = document.authoring?.nodeAnnotations ?? [];
2534
+ const layoutAnnotations = annotations
2535
+ .map((annotation, index) => ({ annotation, index }))
2536
+ .filter(({ annotation }) => annotation.reviewLayer === 'layout');
2537
+ if (layoutAnnotations.length === 0) {
2538
+ return;
2539
+ }
2540
+ const annotationByNode = new Map(annotations.map((annotation) => [annotation.node, annotation]));
2541
+ const nodeById = new Map();
2542
+ const effectiveLayerByNode = new Map();
2543
+ const collectEffectiveLayers = (nodes, inheritedLayer) => {
2544
+ nodes.forEach((node) => {
2545
+ nodeById.set(node.id, node);
2546
+ const effectiveLayer = annotationByNode.get(node.id)?.reviewLayer ?? inheritedLayer;
2547
+ effectiveLayerByNode.set(node.id, effectiveLayer);
2548
+ collectEffectiveLayers(node.children ?? [], effectiveLayer);
2549
+ });
2550
+ };
2551
+ collectEffectiveLayers(document.nodes, 'layout');
2552
+ const prefabById = new Map((document.resources.prefabs ?? []).map((prefab) => [prefab.id, prefab]));
2553
+ const subtreeHasLayoutRenderable = (node, inheritedLayer, authoredNode, prefabStack = [], prefabOverrides, ancestorVisible = true) => {
2554
+ const effectivelyVisible = ancestorVisible && (prefabOverrides?.[node.id]?.visible ?? true);
2555
+ if (!effectivelyVisible) {
2556
+ return false;
2557
+ }
2558
+ const effectiveLayer = authoredNode
2559
+ ? (effectiveLayerByNode.get(node.id) ?? inheritedLayer)
2560
+ : inheritedLayer;
2561
+ if (effectiveLayer === 'layout' && node.content?.type === 'asset') {
2562
+ return true;
2563
+ }
2564
+ const content = node.content;
2565
+ if ((content?.type === 'instance' || content?.type === 'pattern') &&
2566
+ (content.type !== 'pattern' ||
2567
+ getScenePatternRequestedCount(content.distribution) > 0)) {
2568
+ const prefab = prefabById.get(content.prefab);
2569
+ if (prefab != null && !prefabStack.includes(prefab.id)) {
2570
+ if (subtreeHasLayoutRenderable(prefab.root, effectiveLayer, false, [...prefabStack, prefab.id], content.overrides, effectivelyVisible)) {
2571
+ return true;
2572
+ }
2573
+ }
2574
+ }
2575
+ return (node.children ?? []).some((child) => subtreeHasLayoutRenderable(child, effectiveLayer, authoredNode, prefabStack, prefabOverrides, effectivelyVisible));
2576
+ };
2577
+ layoutAnnotations.forEach(({ annotation, index }) => {
2578
+ const node = nodeById.get(annotation.node);
2579
+ if (node != null && !subtreeHasLayoutRenderable(node, 'layout', true)) {
2580
+ addIssue(issues, `$.authoring.nodeAnnotations[${index}]`, `layout annotation for node "${annotation.node}" has no effectively layout-visible renderable`, 'review-visibility');
2581
+ }
2582
+ });
2583
+ const layoutFeatureIds = new Set(layoutAnnotations.flatMap(({ annotation }) => annotation.featureRefs ?? []));
2584
+ document.authoring?.composition?.features.forEach((feature, index) => {
2585
+ if (!layoutFeatureIds.has(feature.id)) {
2586
+ return;
2587
+ }
2588
+ const hasLayoutRenderable = feature.nodeRefs.some((nodeId) => {
2589
+ const node = nodeById.get(nodeId);
2590
+ return node != null && subtreeHasLayoutRenderable(node, 'layout', true);
2591
+ });
2592
+ if (!hasLayoutRenderable) {
2593
+ addIssue(issues, `$.authoring.composition.features[${index}].nodeRefs`, `layout feature "${feature.id}" has no effectively layout-visible renderable`, 'review-visibility');
2594
+ }
2595
+ });
2596
+ }
2597
+ function validateCompositionPolicies(document, composition, issues) {
2598
+ const allowed = new Set(composition.representationPolicy.allowed);
2599
+ if (!allowed.has('prefab') && (document.resources.prefabs?.length ?? 0) > 0) {
2600
+ addIssue(issues, '$.resources.prefabs', 'representationPolicy does not allow prefab resources', 'policy');
2601
+ }
2602
+ const validateNode = (node, path) => {
2603
+ const contentType = node.content?.type;
2604
+ if (contentType == null || contentType === 'group') {
2605
+ return;
2606
+ }
2607
+ const representation = contentType === 'instance' ? 'prefab' : contentType;
2608
+ if (!allowed.has(representation)) {
2609
+ addIssue(issues, `${path}.content.type`, `representationPolicy does not allow ${representation} content`, 'policy');
2610
+ }
2611
+ };
2612
+ walkNodes(document.nodes, '$.nodes', validateNode);
2613
+ document.resources.prefabs?.forEach((prefab, index) => {
2614
+ walkNodes([prefab.root], `$.resources.prefabs[${index}].root`, validateNode);
2615
+ });
2616
+ }
2617
+ function validateAcceptance(criterion, path, document, nodeIds, viewIds, referenceIds, issues) {
2618
+ if ('nodeRefs' in criterion && criterion.nodeRefs != null) {
2619
+ validateNodeReferences(criterion.nodeRefs, `${path}.nodeRefs`, nodeIds, issues);
2620
+ }
2621
+ if ('view' in criterion &&
2622
+ criterion.view != null &&
2623
+ !viewIds.has(criterion.view)) {
2624
+ addIssue(issues, `${path}.view`, `unknown view "${criterion.view}"`, 'reference');
2625
+ }
2626
+ if (criterion.kind === 'count') {
2627
+ const limits = [
2628
+ criterion.equals,
2629
+ criterion.minimum,
2630
+ criterion.maximum,
2631
+ ].filter((entry) => entry != null);
2632
+ if (limits.length === 0) {
2633
+ addIssue(issues, path, 'count criterion requires equals, minimum, or maximum', 'required');
2634
+ }
2635
+ if ((criterion.nodeRefs?.length ?? 0) === 0 && criterion.pattern == null) {
2636
+ addIssue(issues, path, 'count criterion requires nodeRefs or pattern', 'required');
2637
+ }
2638
+ if (criterion.pattern != null) {
2639
+ const pattern = findNodeById(document.nodes, criterion.pattern);
2640
+ if (pattern?.content?.type !== 'pattern') {
2641
+ addIssue(issues, `${path}.pattern`, `unknown pattern node "${criterion.pattern}"`, 'reference');
2642
+ }
2643
+ }
2644
+ if (criterion.minimum != null &&
2645
+ criterion.maximum != null &&
2646
+ criterion.minimum > criterion.maximum) {
2647
+ addIssue(issues, path, 'count minimum must not exceed maximum', 'range');
2648
+ }
2649
+ if (criterion.equals != null &&
2650
+ ((criterion.minimum != null && criterion.equals < criterion.minimum) ||
2651
+ (criterion.maximum != null && criterion.equals > criterion.maximum))) {
2652
+ addIssue(issues, path, 'count equals must satisfy minimum and maximum', 'range');
2653
+ }
2654
+ }
2655
+ else if (criterion.kind === 'projected-region') {
2656
+ if (!referenceIds.has(criterion.reference)) {
2657
+ addIssue(issues, `${path}.reference`, `unknown reference "${criterion.reference}"`, 'reference');
2658
+ }
2659
+ validateNormalizedRegion(criterion.region, `${path}.region`, issues);
2660
+ }
2661
+ else if (criterion.kind === 'spatial-relation' &&
2662
+ !nodeIds.has(criterion.target)) {
2663
+ addIssue(issues, `${path}.target`, `unknown target node "${criterion.target}"`, 'reference');
2664
+ }
2665
+ }
2666
+ function acceptanceSubjectNodeReferences(criterion) {
2667
+ if (criterion.kind === 'count' && criterion.pattern != null) {
2668
+ return [{ nodeId: criterion.pattern, path: 'pattern' }];
2669
+ }
2670
+ if (!('nodeRefs' in criterion) || criterion.nodeRefs == null) {
2671
+ return [];
2672
+ }
2673
+ return criterion.nodeRefs.map((nodeId, index) => ({
2674
+ nodeId,
2675
+ path: `nodeRefs[${index}]`,
2676
+ }));
2677
+ }
2678
+ function validateObjectInspection(document, feature, featurePath, nodeIds, viewIds, reviewViewIds, issues) {
2679
+ const inspection = feature.objectInspection;
2680
+ if (feature.identityCritical === true && inspection == null) {
2681
+ addIssue(issues, `${featurePath}.objectInspection`, 'identity-critical feature must declare an object inspection spec', 'required');
2682
+ return;
2683
+ }
2684
+ if (inspection == null) {
2685
+ return;
2686
+ }
2687
+ if (feature.identityCritical !== true) {
2688
+ addIssue(issues, `${featurePath}.identityCritical`, 'object inspection requires identityCritical to be true', 'required');
2689
+ }
2690
+ const validateInspectionSubjects = (refs, path) => {
2691
+ validateNodeReferences(refs, path, nodeIds, issues);
2692
+ refs.forEach((nodeRef, index) => {
2693
+ if (nodeIds.has(nodeRef) &&
2694
+ !feature.nodeRefs.some((binding) => nodeIds.has(binding) &&
2695
+ isNodeSameOrDescendant(document.nodes, nodeRef, binding))) {
2696
+ addIssue(issues, `${path}[${index}]`, `inspection subject node "${nodeRef}" is outside feature "${feature.id}" node bindings`, 'reference');
2697
+ }
2698
+ });
2699
+ };
2700
+ const partIds = new Set();
2701
+ inspection.parts.forEach((part, index) => {
2702
+ const partPath = `${featurePath}.objectInspection.parts[${index}]`;
2703
+ if (partIds.has(part.id)) {
2704
+ addIssue(issues, `${partPath}.id`, `duplicate inspection part id "${part.id}"`, 'duplicate-id');
2705
+ }
2706
+ partIds.add(part.id);
2707
+ validateInspectionSubjects(part.nodeRefs, `${partPath}.nodeRefs`);
2708
+ });
2709
+ const contactIds = new Set();
2710
+ inspection.contacts.forEach((contact, index) => {
2711
+ const contactPath = `${featurePath}.objectInspection.contacts[${index}]`;
2712
+ if (contactIds.has(contact.id)) {
2713
+ addIssue(issues, `${contactPath}.id`, `duplicate inspection contact id "${contact.id}"`, 'duplicate-id');
2714
+ }
2715
+ contactIds.add(contact.id);
2716
+ validateInspectionSubjects(contact.nodeRefs, `${contactPath}.nodeRefs`);
2717
+ validateNodeReferences(contact.targetNodeRefs, `${contactPath}.targetNodeRefs`, nodeIds, issues);
2718
+ });
2719
+ if (inspection.context.includeNodeRefs != null) {
2720
+ validateNodeReferences(inspection.context.includeNodeRefs, `${featurePath}.objectInspection.context.includeNodeRefs`, nodeIds, issues);
2721
+ }
2722
+ inspection.requiredViews.forEach((viewId, index) => {
2723
+ const viewPath = `${featurePath}.objectInspection.requiredViews[${index}]`;
2724
+ if (!viewIds.has(viewId)) {
2725
+ addIssue(issues, viewPath, `unknown view "${viewId}"`, 'reference');
2726
+ }
2727
+ else if (!reviewViewIds.has(viewId)) {
2728
+ addIssue(issues, viewPath, `inspection view "${viewId}" is not required by composition review`, 'required');
2729
+ }
2730
+ });
2731
+ }
2732
+ function isNodeSameOrDescendant(nodes, nodeId, possibleAncestorId) {
2733
+ const possibleAncestor = findNodeById(nodes, possibleAncestorId);
2734
+ return (possibleAncestor != null && findNodeById([possibleAncestor], nodeId) != null);
2735
+ }
2736
+ function validateNormalizedRegion(region, path, issues) {
2737
+ if (region.some((entry) => entry < 0 || entry > 1) ||
2738
+ region[0] + region[2] > 1 ||
2739
+ region[1] + region[3] > 1) {
2740
+ addIssue(issues, path, 'region must fit within normalized image coordinates', 'range');
2741
+ }
2742
+ }
2743
+ function validateReviewSemantics(review, issues) {
2744
+ if (review.round === 0 && review.previousReview != null) {
2745
+ addIssue(issues, '$.previousReview', 'initial review round 0 cannot declare prior review lineage', 'state');
2746
+ }
2747
+ const lensIds = new Set();
2748
+ const captureIds = new Set();
2749
+ review.lenses.forEach((lens, lensIndex) => {
2750
+ if (lensIds.has(lens.id)) {
2751
+ addIssue(issues, `$.lenses[${lensIndex}].id`, `duplicate lens id "${lens.id}"`, 'duplicate-id');
2752
+ }
2753
+ lensIds.add(lens.id);
2754
+ lens.captures.forEach((capture, captureIndex) => {
2755
+ const path = `$.lenses[${lensIndex}].captures[${captureIndex}]`;
2756
+ if (captureIds.has(capture.id)) {
2757
+ addIssue(issues, `${path}.id`, `duplicate capture id "${capture.id}"`, 'duplicate-id');
2758
+ }
2759
+ captureIds.add(capture.id);
2760
+ if (capture.camera.projection === 'perspective' &&
2761
+ capture.camera.fov == null) {
2762
+ addIssue(issues, `${path}.camera.fov`, 'perspective camera requires fov', 'required');
2763
+ }
2764
+ if (capture.camera.projection === 'orthographic' &&
2765
+ capture.camera.height == null) {
2766
+ addIssue(issues, `${path}.camera.height`, 'orthographic camera requires height', 'required');
2767
+ }
2768
+ });
2769
+ });
2770
+ const results = new Map();
2771
+ review.featureResults.forEach((result, index) => {
2772
+ const path = `$.featureResults[${index}]`;
2773
+ const key = `${result.feature}\u0000${result.criterion}`;
2774
+ if (results.has(key)) {
2775
+ addIssue(issues, path, 'feature criterion result is duplicated', 'duplicate-id');
2776
+ }
2777
+ results.set(key, result.status);
2778
+ result.evidenceRefs.forEach((reference, evidenceIndex) => {
2779
+ if (!captureIds.has(reference)) {
2780
+ addIssue(issues, `${path}.evidenceRefs[${evidenceIndex}]`, `unknown capture "${reference}"`, 'reference');
2781
+ }
2782
+ });
2783
+ });
2784
+ const waived = new Set();
2785
+ review.waivers.forEach((waiver, index) => {
2786
+ const key = `${waiver.feature}\u0000${waiver.criterion}`;
2787
+ const status = results.get(key);
2788
+ if (status == null) {
2789
+ addIssue(issues, `$.waivers[${index}]`, 'waiver does not name a feature result', 'reference');
2790
+ }
2791
+ else if (status === 'pass') {
2792
+ addIssue(issues, `$.waivers[${index}]`, 'passing criterion cannot be waived', 'state');
2793
+ }
2794
+ waived.add(key);
2795
+ });
2796
+ if (review.result === 'pass') {
2797
+ if (review.lenses.some((lens) => lens.status !== 'pass') ||
2798
+ review.featureResults.some((result) => result.status !== 'pass')) {
2799
+ addIssue(issues, '$.result', 'pass requires every lens and feature criterion to pass', 'state');
2800
+ }
2801
+ if (review.waivers.length > 0) {
2802
+ addIssue(issues, '$.waivers', 'pass cannot include waivers', 'state');
2803
+ }
2804
+ }
2805
+ else if (review.result === 'accepted-with-gaps') {
2806
+ review.featureResults.forEach((result) => {
2807
+ const key = `${result.feature}\u0000${result.criterion}`;
2808
+ if (result.status !== 'pass' && !waived.has(key)) {
2809
+ addIssue(issues, '$.waivers', `non-passing criterion "${result.criterion}" requires a waiver`, 'state');
2810
+ }
2811
+ });
2812
+ }
2813
+ if (review.stop.reason === 'success' && review.result === 'fail') {
2814
+ addIssue(issues, '$.stop.reason', 'failed review cannot stop for success', 'state');
2815
+ }
2816
+ if (review.stop.reason === 'continue-refining' && review.result !== 'fail') {
2817
+ addIssue(issues, '$.stop.reason', 'continue-refining is valid only for a failed review', 'state');
2818
+ }
2819
+ }
2820
+ function validatePatternExpansion(distribution, path, issues) {
2821
+ const count = getScenePatternRequestedCount(distribution);
2822
+ if (count > MAX_SCENE_PATTERN_EXPANSION) {
2823
+ addIssue(issues, path, `pattern expands to ${count} instances; maximum is ${MAX_SCENE_PATTERN_EXPANSION}`, 'limit');
2824
+ }
2825
+ validateCoordinatesInValue(distribution, path, issues);
2826
+ }
2827
+ function validateTransformCoordinates(value, path, issues) {
2828
+ if (value != null) {
2829
+ validateCoordinatesInValue(value, path, issues);
2830
+ }
2831
+ }
2832
+ function validateCoordinatesInValue(value, path, issues) {
2833
+ const visit = (entry, entryPath) => {
2834
+ if (isFiniteNumber(entry)) {
2835
+ if (Math.abs(entry) > MAX_SCENE_COORDINATE) {
2836
+ addIssue(issues, entryPath, `absolute value exceeds ${MAX_SCENE_COORDINATE}`, 'limit');
2837
+ }
2838
+ }
2839
+ else if (Array.isArray(entry)) {
2840
+ entry.forEach((child, index) => visit(child, `${entryPath}[${index}]`));
2841
+ }
2842
+ else if (isPlainObject(entry)) {
2843
+ Object.entries(entry).forEach(([key, child]) => visit(child, childPath(entryPath, key)));
2844
+ }
2845
+ };
2846
+ visit(value, path);
2847
+ }
2848
+ function validatePrefabOverrides(overrides, prefabId, nodePath, prefabNodeIds, schemas, validateComponentFields, issues) {
2849
+ if (overrides == null) {
2850
+ return;
2851
+ }
2852
+ for (const [nodeId, override] of Object.entries(overrides)) {
2853
+ if (!prefabNodeIds.get(prefabId)?.has(nodeId)) {
2854
+ addIssue(issues, `${nodePath}.content.overrides[${JSON.stringify(nodeId)}]`, `unknown node "${nodeId}" in prefab "${prefabId}"`, 'reference');
2855
+ }
2856
+ validateComponents(override.components, `${nodePath}.content.overrides[${JSON.stringify(nodeId)}].components`, schemas, validateComponentFields, issues);
2857
+ }
2858
+ }
2859
+ function validateComponentCatalog(catalog, issues) {
2860
+ const byId = new Map();
2861
+ Object.entries(catalog ?? {}).forEach(([catalogId, schema]) => {
2862
+ const schemaPath = `$componentCatalog[${JSON.stringify(catalogId)}]`;
2863
+ if (catalogId !== schema.id) {
2864
+ addIssue(issues, `${schemaPath}.id`, `catalog key must match component schema id "${schema.id}"`, 'reference');
2865
+ }
2866
+ byId.set(schema.id, schema);
2867
+ Object.entries(schema.fields).forEach(([name, field]) => {
2868
+ const fieldPath = `${schemaPath}.fields[${JSON.stringify(name)}]`;
2869
+ if (field.min != null && field.max != null && field.min > field.max) {
2870
+ addIssue(issues, fieldPath, 'field min must not exceed max', 'range');
2871
+ }
2872
+ if (field.default !== undefined &&
2873
+ !matchesComponentField(field.default, field)) {
2874
+ addIssue(issues, `${fieldPath}.default`, `default does not match ${field.type}`, 'type');
2875
+ }
2876
+ if (field.type === 'Enum' && field.enum == null) {
2877
+ addIssue(issues, `${fieldPath}.enum`, 'Enum field requires enum values', 'required');
2878
+ }
2879
+ });
2880
+ });
2881
+ return byId;
2882
+ }
2883
+ function validateComponents(components, path, schemas, validateComponentFields, issues) {
2884
+ if (components == null) {
2885
+ return;
2886
+ }
2887
+ for (const [name, value] of Object.entries(components)) {
2888
+ const componentPath = childPath(path, name);
2889
+ if (!isPlainObject(value) || !isJsonValue(value)) {
2890
+ addIssue(issues, componentPath, 'component payload must be a JSON object', 'type');
2891
+ continue;
2892
+ }
2893
+ if (!validateComponentFields) {
2894
+ continue;
2895
+ }
2896
+ const componentId = stripComponentPrefix(name);
2897
+ const schema = schemas.get(componentId) ?? schemas.get(name);
2898
+ if (schema == null) {
2899
+ addIssue(issues, componentPath, `component "${componentId}" is not present in the active component catalog`, 'reference');
2900
+ continue;
2901
+ }
2902
+ for (const [fieldName, fieldValue] of Object.entries(value)) {
2903
+ const field = schema.fields[fieldName];
2904
+ if (field == null) {
2905
+ addIssue(issues, childPath(componentPath, fieldName), 'component field is not declared', 'property');
2906
+ }
2907
+ else if (!matchesComponentField(fieldValue, field)) {
2908
+ addIssue(issues, childPath(componentPath, fieldName), `value does not match ${field.type}`, 'type');
2909
+ }
2910
+ }
2911
+ if (['DirectionalLight', 'PointLight', 'SpotLight'].includes(componentId)) {
2912
+ const near = value.shadowCameraNear ?? schema.fields.shadowCameraNear?.default;
2913
+ const far = value.shadowCameraFar ?? schema.fields.shadowCameraFar?.default;
2914
+ if (isFiniteNumber(near) && isFiniteNumber(far) && near >= far) {
2915
+ addIssue(issues, componentPath, 'shadow camera near must be less than shadow camera far', 'range');
2916
+ }
2917
+ }
2918
+ }
2919
+ }
2920
+ function validateRootComponents(components, issues) {
2921
+ const intrinsic = new Set(['LevelRoot', 'LevelTag', 'Transform']);
2922
+ for (const name of Object.keys(components ?? {})) {
2923
+ if (intrinsic.has(stripComponentPrefix(name))) {
2924
+ addIssue(issues, childPath('$.components', name), `component "${name}" is owned by the runtime level root`, 'conflict');
2925
+ }
2926
+ }
2927
+ }
2928
+ function validatePlayerComponents(document, schemas, validateComponentFields, issues) {
2929
+ const targets = [
2930
+ ['player', document.player],
2931
+ ['camera', document.player?.camera],
2932
+ ['head', document.player?.head],
2933
+ ['leftTargetRay', document.player?.leftTargetRay],
2934
+ ['rightTargetRay', document.player?.rightTargetRay],
2935
+ ['leftGrip', document.player?.leftGrip],
2936
+ ['rightGrip', document.player?.rightGrip],
2937
+ ];
2938
+ const intrinsic = new Set(['LevelRoot', 'LevelTag', 'Transform']);
2939
+ for (const [target, descriptor] of targets) {
2940
+ const descriptorPath = target === 'player' ? '$.player' : `$.player.${target}`;
2941
+ const path = `${descriptorPath}.components`;
2942
+ validateTransformCoordinates(descriptor?.transform, `${descriptorPath}.transform`, issues);
2943
+ validateComponents(descriptor?.components, path, schemas, validateComponentFields, issues);
2944
+ for (const name of Object.keys(descriptor?.components ?? {})) {
2945
+ if (intrinsic.has(stripComponentPrefix(name))) {
2946
+ addIssue(issues, childPath(path, name), `component "${name}" is owned by the runtime player rig`, 'conflict');
2947
+ }
2948
+ }
2949
+ }
2950
+ }
2951
+ function matchesComponentField(value, field) {
2952
+ let matches;
2953
+ switch (field.type) {
2954
+ case 'Int8':
2955
+ case 'Int16':
2956
+ case 'Int32':
2957
+ matches = Number.isInteger(value);
2958
+ break;
2959
+ case 'Entity':
2960
+ matches =
2961
+ value === null ||
2962
+ Number.isInteger(value) ||
2963
+ isSceneEntityReference(value);
2964
+ break;
2965
+ case 'Float32':
2966
+ case 'Float64':
2967
+ matches = isFiniteNumber(value);
2968
+ break;
2969
+ case 'Boolean':
2970
+ matches = typeof value === 'boolean';
2971
+ break;
2972
+ case 'String':
2973
+ case 'FilePath':
2974
+ matches = typeof value === 'string';
2975
+ break;
2976
+ case 'Object':
2977
+ matches = isJsonValue(value);
2978
+ break;
2979
+ case 'Vec2':
2980
+ matches = isVec2(value);
2981
+ break;
2982
+ case 'Vec3':
2983
+ matches = isVec3(value);
2984
+ break;
2985
+ case 'Vec4':
2986
+ matches =
2987
+ Array.isArray(value) &&
2988
+ value.length === 4 &&
2989
+ value.every(isFiniteNumber);
2990
+ break;
2991
+ case 'Color':
2992
+ matches =
2993
+ Array.isArray(value) &&
2994
+ value.length === 4 &&
2995
+ value.every((entry) => isFiniteNumber(entry) && entry >= 0 && entry <= 1);
2996
+ break;
2997
+ case 'Enum':
2998
+ matches =
2999
+ typeof value === 'string' &&
3000
+ (field.enum == null || Object.values(field.enum).includes(value));
3001
+ break;
3002
+ }
3003
+ if (matches && isFiniteNumber(value)) {
3004
+ matches =
3005
+ (field.min == null || value >= field.min) &&
3006
+ (field.max == null || value <= field.max);
3007
+ }
3008
+ return matches;
3009
+ }
3010
+ function validateComponentLinks(document, schemas, nodeIds, issues) {
3011
+ validateComponentLinkMap(document.components, '$.components', schemas, nodeIds, issues);
3012
+ const playerTargets = [
3013
+ ['player', document.player],
3014
+ ['camera', document.player?.camera],
3015
+ ['head', document.player?.head],
3016
+ ['leftTargetRay', document.player?.leftTargetRay],
3017
+ ['rightTargetRay', document.player?.rightTargetRay],
3018
+ ['leftGrip', document.player?.leftGrip],
3019
+ ['rightGrip', document.player?.rightGrip],
3020
+ ];
3021
+ for (const [target, descriptor] of playerTargets) {
3022
+ const descriptorPath = target === 'player' ? '$.player' : `$.player.${target}`;
3023
+ validateComponentLinkMap(descriptor?.components, `${descriptorPath}.components`, schemas, nodeIds, issues);
3024
+ }
3025
+ const visit = (nodes, path) => {
3026
+ nodes.forEach((node, index) => {
3027
+ const nodePath = nodes.length === 1 && path.endsWith('.root')
3028
+ ? path
3029
+ : `${path}[${index}]`;
3030
+ validateComponentLinkMap(node.components, `${nodePath}.components`, schemas, nodeIds, issues);
3031
+ visit(node.children ?? [], `${nodePath}.children`);
3032
+ });
3033
+ };
3034
+ visit(document.nodes, '$.nodes');
3035
+ }
3036
+ function validateComponentLinkMap(components, path, schemas, nodeIds, issues) {
3037
+ for (const [name, payload] of Object.entries(components ?? {})) {
3038
+ if (!isPlainObject(payload)) {
3039
+ continue;
3040
+ }
3041
+ const schema = schemas.get(stripComponentPrefix(name)) ?? schemas.get(name);
3042
+ if (schema == null) {
3043
+ continue;
3044
+ }
3045
+ const componentPath = childPath(path, name);
3046
+ for (const [fieldName, field] of Object.entries(schema.fields)) {
3047
+ if (field.hidden === true) {
3048
+ continue;
3049
+ }
3050
+ const fieldPath = childPath(componentPath, fieldName);
3051
+ const value = payload[fieldName] ?? field.default;
3052
+ if (field.type === 'FilePath' &&
3053
+ (typeof value !== 'string' || value.trim().length === 0)) {
3054
+ addIssue(issues, fieldPath, 'file path is not selected', 'required');
3055
+ continue;
3056
+ }
3057
+ const isEntityField = field.type === 'Entity' || field.widget === 'entity';
3058
+ if (!isEntityField) {
3059
+ if (field.required === true && (value == null || value === '')) {
3060
+ addIssue(issues, fieldPath, 'field is required', 'required');
3061
+ }
3062
+ continue;
3063
+ }
3064
+ if (value == null) {
3065
+ if (field.required === true) {
3066
+ addIssue(issues, fieldPath, 'entity reference is not linked', 'required');
3067
+ }
3068
+ continue;
3069
+ }
3070
+ if (isSceneNodeReference(value) && !nodeIds.has(value.id)) {
3071
+ addIssue(issues, fieldPath, `referenced scene entity "${value.id}" does not exist`, 'reference');
3072
+ }
3073
+ else if (!Number.isInteger(value) && !isSceneEntityReference(value)) {
3074
+ addIssue(issues, fieldPath, 'value is not a scene entity reference', 'type');
3075
+ }
3076
+ }
3077
+ }
3078
+ }
3079
+ function isSceneNodeReference(value) {
3080
+ return (isPlainObject(value) &&
3081
+ value.type === 'node' &&
3082
+ typeof value.id === 'string' &&
3083
+ value.id.length > 0);
3084
+ }
3085
+ function isSceneEntityReference(value) {
3086
+ return (isSceneNodeReference(value) ||
3087
+ (isPlainObject(value) &&
3088
+ value.type === 'level-root' &&
3089
+ Object.keys(value).length === 1) ||
3090
+ (isPlainObject(value) &&
3091
+ value.type === 'player-space' &&
3092
+ [
3093
+ 'player',
3094
+ 'camera',
3095
+ 'head',
3096
+ 'left-target-ray',
3097
+ 'right-target-ray',
3098
+ 'left-grip',
3099
+ 'right-grip',
3100
+ ].includes(String(value.target))));
3101
+ }
3102
+ function stripComponentPrefix(name) {
3103
+ const prefix = 'com.iwsdk.components.';
3104
+ return name.startsWith(prefix) ? name.slice(prefix.length) : name;
3105
+ }
3106
+ function validateSafeUri(uri, path, issues) {
3107
+ const scheme = /^([a-z][a-z0-9+.-]*):/iu.exec(uri)?.[1]?.toLowerCase();
3108
+ if (scheme != null && scheme !== 'http' && scheme !== 'https') {
3109
+ addIssue(issues, path, `URI scheme "${scheme}" is not allowed`, 'unsafe-uri');
3110
+ }
3111
+ }
3112
+ function validateMetadataNamespaces(metadata, path, issues) {
3113
+ if (metadata == null) {
3114
+ return;
3115
+ }
3116
+ for (const key of Object.keys(metadata)) {
3117
+ if (!/^[^.:/]+[.:/].+$/u.test(key)) {
3118
+ addIssue(issues, childPath(path, key), 'metadata extension key must be namespaced', 'namespace');
3119
+ }
3120
+ }
3121
+ }
3122
+ function validateNodeReferences(refs, path, ids, issues) {
3123
+ refs.forEach((reference, index) => {
3124
+ if (!ids.has(reference)) {
3125
+ addIssue(issues, `${path}[${index}]`, `unknown node "${reference}"`, 'reference');
3126
+ }
3127
+ });
3128
+ }
3129
+ function walkNodes(nodes, path, visitor) {
3130
+ nodes.forEach((node, index) => {
3131
+ const nodePath = nodes.length === 1 && path.endsWith('.root') ? path : `${path}[${index}]`;
3132
+ visitor(node, nodePath);
3133
+ walkNodes(node.children ?? [], `${nodePath}.children`, visitor);
3134
+ });
3135
+ }
3136
+ function findNodeById(nodes, id) {
3137
+ for (const node of nodes) {
3138
+ if (node.id === id) {
3139
+ return node;
3140
+ }
3141
+ const nested = findNodeById(node.children ?? [], id);
3142
+ if (nested != null) {
3143
+ return nested;
3144
+ }
3145
+ }
3146
+ return undefined;
3147
+ }
3148
+ function nonEmpty(value) {
3149
+ return typeof value === 'string' && value.length > 0;
3150
+ }
3151
+ function addIssue(issues, path, message, code) {
3152
+ issues.push({ path, message, code });
3153
+ }
3154
+
3155
+ /**
3156
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3157
+ *
3158
+ * This source code is licensed under the MIT license found in the
3159
+ * LICENSE file in the root directory of this source tree.
3160
+ */
3161
+ const DOCUMENT_INTEGRITY_VALIDATION_OPTIONS = {
3162
+ validateAuthoringWorkflow: false,
3163
+ };
3164
+ function parseSceneDocument(text, validationOptions = {}) {
3165
+ const value = JSON.parse(text);
3166
+ assertValidSceneDocument(value, validationOptions);
3167
+ return value;
3168
+ }
3169
+ function parseSceneReview(text) {
3170
+ const value = JSON.parse(text);
3171
+ assertValidSceneReview(value);
3172
+ return value;
3173
+ }
3174
+ function serializeSceneDocument(document, validationOptions = DOCUMENT_INTEGRITY_VALIDATION_OPTIONS) {
3175
+ assertValidSceneDocument(document, validationOptions);
3176
+ return `${JSON.stringify(sortJsonValue(document), null, 2)}\n`;
3177
+ }
3178
+ function serializeSceneReview(review) {
3179
+ assertValidSceneReview(review);
3180
+ return `${JSON.stringify(sortJsonValue(review), null, 2)}\n`;
3181
+ }
3182
+ /** RFC 8785 JSON Canonicalization Scheme serialization. */
3183
+ function canonicalizeJson(value) {
3184
+ if (!isJsonValue(value)) {
3185
+ throw new Error('Canonical JSON input must be finite JSON data');
3186
+ }
3187
+ return canonicalizeValue(value);
3188
+ }
3189
+ function serializeCanonicalSceneDocument(document, validationOptions = DOCUMENT_INTEGRITY_VALIDATION_OPTIONS) {
3190
+ assertValidSceneDocument(document, validationOptions);
3191
+ return canonicalizeJson(document);
3192
+ }
3193
+ function projectRuntimeSceneDocument(document, validationOptions = DOCUMENT_INTEGRITY_VALIDATION_OPTIONS) {
3194
+ assertValidSceneDocument(document, validationOptions);
3195
+ const projected = deepClone(document);
3196
+ delete projected.authoring;
3197
+ delete projected.imports;
3198
+ return projected;
3199
+ }
3200
+ function serializeCanonicalRuntimeSceneDocument(document, validationOptions = DOCUMENT_INTEGRITY_VALIDATION_OPTIONS) {
3201
+ return canonicalizeJson(projectRuntimeSceneDocument(document, validationOptions));
3202
+ }
3203
+ function hashSceneDocument(document, validationOptions = DOCUMENT_INTEGRITY_VALIDATION_OPTIONS) {
3204
+ return sha256(serializeCanonicalSceneDocument(document, validationOptions));
3205
+ }
3206
+ function hashRuntimeSceneDocument(document, validationOptions = DOCUMENT_INTEGRITY_VALIDATION_OPTIONS) {
3207
+ return sha256(serializeCanonicalRuntimeSceneDocument(document, validationOptions));
3208
+ }
3209
+ function sortJsonValue(value) {
3210
+ if (Array.isArray(value)) {
3211
+ return value.map((entry) => sortJsonValue(entry));
3212
+ }
3213
+ if (value !== null && typeof value === 'object') {
3214
+ const sorted = {};
3215
+ for (const key of Object.keys(value).sort()) {
3216
+ sorted[key] = sortJsonValue(value[key]);
3217
+ }
3218
+ return sorted;
3219
+ }
3220
+ return value;
3221
+ }
3222
+ function canonicalizeValue(value) {
3223
+ if (value === null || typeof value !== 'object') {
3224
+ return JSON.stringify(value);
3225
+ }
3226
+ if (Array.isArray(value)) {
3227
+ return `[${value.map((entry) => canonicalizeValue(entry)).join(',')}]`;
3228
+ }
3229
+ return `{${Object.keys(value)
3230
+ .sort()
3231
+ .map((key) => `${JSON.stringify(key)}:${canonicalizeValue(value[key])}`)
3232
+ .join(',')}}`;
3233
+ }
3234
+
3235
+ /**
3236
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3237
+ *
3238
+ * This source code is licensed under the MIT license found in the
3239
+ * LICENSE file in the root directory of this source tree.
3240
+ */
3241
+ function getSceneNodeLocalBounds(_node, assetBounds) {
3242
+ return assetBounds;
3243
+ }
3244
+
3245
+ const IDENTITY_LINEAR_MATRIX = [1, 0, 0, 0, 1, 0, 0, 0, 1];
3246
+ function resolveLookAtYawDeg(position, target) {
3247
+ const dx = target[0] - position[0];
3248
+ const dz = target[2] - position[2];
3249
+ const radians = Math.atan2(dx, dz);
3250
+ return normalizeDegrees((radians * 180) / Math.PI);
3251
+ }
3252
+ function resolveLookAtTransform(node, target) {
3253
+ const transform = node.transform ?? {};
3254
+ const position = transform.position ?? [0, 0, 0];
3255
+ const rotation = transform.rotationDeg ?? [0, 0, 0];
3256
+ const nextTransform = {
3257
+ ...transform,
3258
+ rotationDeg: [
3259
+ rotation[0],
3260
+ resolveLookAtYawDeg(position, target),
3261
+ rotation[2],
3262
+ ],
3263
+ };
3264
+ return nextTransform;
3265
+ }
3266
+ function resolveLookAtTransformInDocument(document, nodeId, target) {
3267
+ const location = findRequiredNodeLocation(document, nodeId);
3268
+ const parentWorldTransform = getParentWorldTransform(document, nodeId);
3269
+ return resolveLookAtTransform(location.node, worldPointToLocal(target, parentWorldTransform));
3270
+ }
3271
+ /** Resolve authoring-only orientation constraints into runtime transforms. */
3272
+ function resolveSceneAuthoringTransforms(document) {
3273
+ const resolvedDocument = JSON.parse(JSON.stringify(document));
3274
+ const nodes = flattenSceneNodes(resolvedDocument.nodes);
3275
+ for (const node of nodes) {
3276
+ const lookAt = node.constraints?.lookAt;
3277
+ if (lookAt != null) {
3278
+ node.transform = resolveLookAtTransformInDocument(resolvedDocument, node.id, lookAt.target);
3279
+ }
3280
+ }
3281
+ return resolvedDocument;
3282
+ }
3283
+ /** Apply prefab overrides and resolve its local constraints without mutation. */
3284
+ function resolveScenePrefabRoot(document, root, overrides) {
3285
+ const resolvedRoot = applyScenePrefabOverrides(root, overrides);
3286
+ const scope = {
3287
+ nodes: [resolvedRoot],
3288
+ resources: {
3289
+ ...(document.resources.prefabs == null
3290
+ ? {}
3291
+ : { prefabs: document.resources.prefabs }),
3292
+ },
3293
+ units: document.units,
3294
+ version: document.version,
3295
+ };
3296
+ return resolveSceneAuthoringTransforms(scope).nodes[0];
3297
+ }
3298
+ function applyScenePrefabOverrides(source, overrides) {
3299
+ const node = deepClone(source);
3300
+ const override = overrides?.[source.id];
3301
+ if (override?.transform != null) {
3302
+ node.transform = { ...(node.transform ?? {}), ...override.transform };
3303
+ }
3304
+ if (override?.components != null) {
3305
+ node.components = {
3306
+ ...(node.components ?? {}),
3307
+ ...deepClone(override.components),
3308
+ };
3309
+ }
3310
+ if (source.children != null) {
3311
+ node.children = source.children.map((child) => applyScenePrefabOverrides(child, overrides));
3312
+ }
3313
+ return node;
3314
+ }
3315
+ function flattenSceneNodes(nodes, result = []) {
3316
+ for (const node of nodes) {
3317
+ result.push(node);
3318
+ flattenSceneNodes(node.children ?? [], result);
3319
+ }
3320
+ return result;
3321
+ }
3322
+ function resolveReparentTransform(document, nodeId, parentId, parentTarget) {
3323
+ const location = findRequiredNodeLocation(document, nodeId);
3324
+ const currentParentTarget = location.parent == null ? location.node.parent?.target : undefined;
3325
+ if (location.parent?.id === parentId &&
3326
+ currentParentTarget === parentTarget) {
3327
+ return location.node.transform ?? {};
3328
+ }
3329
+ const nodeWorldTransform = getNodeWorldTransform(document, nodeId);
3330
+ const nextParentWorldTransform = parentId != null
3331
+ ? getNodeWorldTransform(document, parentId)
3332
+ : parentTarget == null
3333
+ ? identityWorldTransform()
3334
+ : getPlayerTargetWorldTransform(document, parentTarget);
3335
+ const nextLocalLinear = multiplyMat3(invertMat3(nextParentWorldTransform.linear), nodeWorldTransform.linear);
3336
+ const decomposedTransform = decomposeLinearTransform(nextLocalLinear);
3337
+ return compactTransform({
3338
+ ...(location.node.transform ?? {}),
3339
+ position: worldPointToLocal(nodeWorldTransform.position, nextParentWorldTransform),
3340
+ rotationDeg: decomposedTransform.rotationDeg,
3341
+ scale: vec3ToSceneScale(decomposedTransform.scale),
3342
+ });
3343
+ }
3344
+ function findRequiredNodeLocation(document, nodeId) {
3345
+ const location = findNodeLocation(document.nodes, nodeId);
3346
+ if (location == null) {
3347
+ throw new Error(`Unknown scene node "${nodeId}"`);
3348
+ }
3349
+ return location;
3350
+ }
3351
+ function getParentWorldTransform(document, nodeId) {
3352
+ const path = getRequiredNodePath(document.nodes, nodeId);
3353
+ return combineNodeWorldTransforms(path.slice(0, -1), getRootNodeParentWorldTransform(document, path[0]));
3354
+ }
3355
+ function getNodeWorldTransform(document, nodeId) {
3356
+ const path = getRequiredNodePath(document.nodes, nodeId);
3357
+ return combineNodeWorldTransforms(path, getRootNodeParentWorldTransform(document, path[0]));
3358
+ }
3359
+ function getRootNodeParentWorldTransform(document, root) {
3360
+ return root?.parent?.type === 'player-space'
3361
+ ? getPlayerTargetWorldTransform(document, root.parent.target)
3362
+ : identityWorldTransform();
3363
+ }
3364
+ function getPlayerTargetWorldTransform(document, target) {
3365
+ const player = transformWorldTransform(document.player?.transform);
3366
+ if (target === 'player') {
3367
+ return player;
3368
+ }
3369
+ // Tracked spaces have runtime-supplied poses, not authored local transforms.
3370
+ // Their only stable authored transform ancestor is Player Space itself.
3371
+ return player;
3372
+ }
3373
+ function transformWorldTransform(transform) {
3374
+ return {
3375
+ linear: composeLinearTransform(transform?.rotationDeg ?? [0, 0, 0], scaleToVec3(transform?.scale)),
3376
+ position: transform?.position ?? [0, 0, 0],
3377
+ };
3378
+ }
3379
+ function getRequiredNodePath(nodes, nodeId) {
3380
+ const path = getNodePath(nodes, nodeId);
3381
+ if (path == null) {
3382
+ throw new Error(`Unknown scene node "${nodeId}"`);
3383
+ }
3384
+ return path;
3385
+ }
3386
+ function getNodePath(nodes, nodeId, ancestors = []) {
3387
+ for (const node of nodes) {
3388
+ const path = [...ancestors, node];
3389
+ if (node.id === nodeId) {
3390
+ return path;
3391
+ }
3392
+ const childPath = getNodePath(node.children ?? [], nodeId, path);
3393
+ if (childPath != null) {
3394
+ return childPath;
3395
+ }
3396
+ }
3397
+ return undefined;
3398
+ }
3399
+ function combineNodeWorldTransforms(nodes, initial = identityWorldTransform()) {
3400
+ return nodes.reduce((worldTransform, node) => {
3401
+ const position = node.transform?.position ?? [0, 0, 0];
3402
+ const scale = scaleToVec3(node.transform?.scale);
3403
+ const rotationDeg = node.transform?.rotationDeg ?? [0, 0, 0];
3404
+ const localLinear = composeLinearTransform(rotationDeg, scale);
3405
+ return {
3406
+ linear: multiplyMat3(worldTransform.linear, localLinear),
3407
+ position: addVec3(worldTransform.position, transformVec3(worldTransform.linear, position)),
3408
+ };
3409
+ }, initial);
3410
+ }
3411
+ function worldPointToLocal(point, parentWorldTransform) {
3412
+ return roundHelperVec3(transformVec3(invertMat3(parentWorldTransform.linear), subtractVec3(point, parentWorldTransform.position)));
3413
+ }
3414
+ function identityWorldTransform() {
3415
+ return {
3416
+ linear: IDENTITY_LINEAR_MATRIX,
3417
+ position: [0, 0, 0],
3418
+ };
3419
+ }
3420
+ function composeLinearTransform(rotationDeg, scale) {
3421
+ const rotation = eulerDegToMatrix(rotationDeg);
3422
+ return [
3423
+ rotation[0] * scale[0],
3424
+ rotation[1] * scale[1],
3425
+ rotation[2] * scale[2],
3426
+ rotation[3] * scale[0],
3427
+ rotation[4] * scale[1],
3428
+ rotation[5] * scale[2],
3429
+ rotation[6] * scale[0],
3430
+ rotation[7] * scale[1],
3431
+ rotation[8] * scale[2],
3432
+ ];
3433
+ }
3434
+ function eulerDegToMatrix(rotationDeg) {
3435
+ const x = degreesToRadians(rotationDeg[0]);
3436
+ const y = degreesToRadians(rotationDeg[1]);
3437
+ const z = degreesToRadians(rotationDeg[2]);
3438
+ const a = Math.cos(x);
3439
+ const b = Math.sin(x);
3440
+ const c = Math.cos(y);
3441
+ const d = Math.sin(y);
3442
+ const e = Math.cos(z);
3443
+ const f = Math.sin(z);
3444
+ return [
3445
+ c * e,
3446
+ -c * f,
3447
+ d,
3448
+ a * f + b * e * d,
3449
+ a * e - b * f * d,
3450
+ -b * c,
3451
+ b * f - a * e * d,
3452
+ b * e + a * f * d,
3453
+ a * c,
3454
+ ];
3455
+ }
3456
+ function multiplyMat3(first, second) {
3457
+ return [
3458
+ first[0] * second[0] + first[1] * second[3] + first[2] * second[6],
3459
+ first[0] * second[1] + first[1] * second[4] + first[2] * second[7],
3460
+ first[0] * second[2] + first[1] * second[5] + first[2] * second[8],
3461
+ first[3] * second[0] + first[4] * second[3] + first[5] * second[6],
3462
+ first[3] * second[1] + first[4] * second[4] + first[5] * second[7],
3463
+ first[3] * second[2] + first[4] * second[5] + first[5] * second[8],
3464
+ first[6] * second[0] + first[7] * second[3] + first[8] * second[6],
3465
+ first[6] * second[1] + first[7] * second[4] + first[8] * second[7],
3466
+ first[6] * second[2] + first[7] * second[5] + first[8] * second[8],
3467
+ ];
3468
+ }
3469
+ function invertMat3(matrix) {
3470
+ const a00 = matrix[0];
3471
+ const a01 = matrix[1];
3472
+ const a02 = matrix[2];
3473
+ const a10 = matrix[3];
3474
+ const a11 = matrix[4];
3475
+ const a12 = matrix[5];
3476
+ const a20 = matrix[6];
3477
+ const a21 = matrix[7];
3478
+ const a22 = matrix[8];
3479
+ const b01 = a22 * a11 - a12 * a21;
3480
+ const b11 = -a22 * a10 + a12 * a20;
3481
+ const b21 = a21 * a10 - a11 * a20;
3482
+ let determinant = a00 * b01 + a01 * b11 + a02 * b21;
3483
+ if (Math.abs(determinant) < 1e-12) {
3484
+ throw new Error('Cannot convert world transform through a zero-scale parent');
3485
+ }
3486
+ determinant = 1 / determinant;
3487
+ return [
3488
+ b01 * determinant,
3489
+ (-a22 * a01 + a02 * a21) * determinant,
3490
+ (a12 * a01 - a02 * a11) * determinant,
3491
+ b11 * determinant,
3492
+ (a22 * a00 - a02 * a20) * determinant,
3493
+ (-a12 * a00 + a02 * a10) * determinant,
3494
+ b21 * determinant,
3495
+ (-a21 * a00 + a01 * a20) * determinant,
3496
+ (a11 * a00 - a01 * a10) * determinant,
3497
+ ];
3498
+ }
3499
+ function transformVec3(matrix, vector) {
3500
+ return [
3501
+ matrix[0] * vector[0] + matrix[1] * vector[1] + matrix[2] * vector[2],
3502
+ matrix[3] * vector[0] + matrix[4] * vector[1] + matrix[5] * vector[2],
3503
+ matrix[6] * vector[0] + matrix[7] * vector[1] + matrix[8] * vector[2],
3504
+ ];
3505
+ }
3506
+ function decomposeLinearTransform(linear) {
3507
+ const scale = [
3508
+ vectorLength([linear[0], linear[3], linear[6]]),
3509
+ vectorLength([linear[1], linear[4], linear[7]]),
3510
+ vectorLength([linear[2], linear[5], linear[8]]),
3511
+ ];
3512
+ if (scale.some((value) => Math.abs(value) < 1e-12)) {
3513
+ throw new Error('Cannot preserve the world transform of a zero-scale node');
3514
+ }
3515
+ // A negative determinant represents a reflection. Preserve it on one scale
3516
+ // axis so the remaining matrix is a proper rotation. This matches Three.js
3517
+ // Matrix4.decompose and keeps mirrored nodes visually unchanged when they
3518
+ // are reparented while preserving their world transform.
3519
+ if (determinantMat3(linear) < 0) {
3520
+ scale[0] = -scale[0];
3521
+ }
3522
+ const rotation = [
3523
+ linear[0] / scale[0],
3524
+ linear[1] / scale[1],
3525
+ linear[2] / scale[2],
3526
+ linear[3] / scale[0],
3527
+ linear[4] / scale[1],
3528
+ linear[5] / scale[2],
3529
+ linear[6] / scale[0],
3530
+ linear[7] / scale[1],
3531
+ linear[8] / scale[2],
3532
+ ];
3533
+ return {
3534
+ rotationDeg: matrixToEulerDeg(rotation),
3535
+ scale: roundHelperVec3(scale),
3536
+ };
3537
+ }
3538
+ function determinantMat3(matrix) {
3539
+ return (matrix[0] * (matrix[4] * matrix[8] - matrix[5] * matrix[7]) -
3540
+ matrix[1] * (matrix[3] * matrix[8] - matrix[5] * matrix[6]) +
3541
+ matrix[2] * (matrix[3] * matrix[7] - matrix[4] * matrix[6]));
3542
+ }
3543
+ function matrixToEulerDeg(matrix) {
3544
+ const y = Math.asin(clamp(matrix[2], -1, 1));
3545
+ let x;
3546
+ let z;
3547
+ if (Math.abs(matrix[2]) < 0.9999999) {
3548
+ x = Math.atan2(-matrix[5], matrix[8]);
3549
+ z = Math.atan2(-matrix[1], matrix[0]);
3550
+ }
3551
+ else {
3552
+ x = Math.atan2(matrix[7], matrix[4]);
3553
+ z = 0;
3554
+ }
3555
+ return roundHelperVec3([
3556
+ radiansToDegrees(x),
3557
+ radiansToDegrees(y),
3558
+ radiansToDegrees(z),
3559
+ ]);
3560
+ }
3561
+ function vectorLength(vector) {
3562
+ return Math.hypot(vector[0], vector[1], vector[2]);
3563
+ }
3564
+ function addVec3(first, second) {
3565
+ return [first[0] + second[0], first[1] + second[1], first[2] + second[2]];
3566
+ }
3567
+ function subtractVec3(first, second) {
3568
+ return [first[0] - second[0], first[1] - second[1], first[2] - second[2]];
3569
+ }
3570
+ function clamp(value, min, max) {
3571
+ return Math.min(max, Math.max(min, value));
3572
+ }
3573
+ function vec3ToSceneScale(scale) {
3574
+ return scale.every((value) => value === scale[0]) ? scale[0] : scale;
3575
+ }
3576
+ function getNodeWorldBounds(document, nodeId, options = {}) {
3577
+ const node = findRequiredNode(document, nodeId);
3578
+ const worldTransform = getNodeWorldTransform(document, nodeId);
3579
+ const excludedNodeIds = new Set(options.excludeNodeIds ?? []);
3580
+ const points = collectNodeBoundsPoints(document, node, worldTransform, [], node.id, excludedNodeIds, undefined, options.resolveAssetBounds);
3581
+ if (points.length === 0) {
3582
+ return {
3583
+ min: worldTransform.position,
3584
+ max: worldTransform.position,
3585
+ };
3586
+ }
3587
+ return boundsFromPoints(points);
3588
+ }
3589
+ /** Conservative collision sphere used by deterministic scatter lowering. */
3590
+ function getSceneNodeCollisionRadius(document, node, options = {}) {
3591
+ const points = collectNodeBoundsPoints(document, node, identityWorldTransform(), [], node.id, new Set(), undefined, options.resolveAssetBounds);
3592
+ const transform = node.transform ?? {};
3593
+ const linear = composeLinearTransform(transform.rotationDeg ?? [0, 0, 0], scaleToVec3(transform.scale));
3594
+ return points.reduce((radius, point) => Math.max(radius, vectorLength(transformVec3(linear, point))), 0);
3595
+ }
3596
+ function collectNodeBoundsPoints(document, node, nodeWorldTransform, prefabStack, runtimeNodeId, excludedNodeIds, derivedNamespace, resolveAssetBounds) {
3597
+ if (excludedNodeIds.has(runtimeNodeId)) {
3598
+ return [];
3599
+ }
3600
+ const points = [];
3601
+ const directBounds = getNodeDirectLocalBounds(node, resolveAssetBounds);
3602
+ if (directBounds != null) {
3603
+ points.push(...boundsCorners(directBounds).map((corner) => transformPoint(nodeWorldTransform, corner)));
3604
+ }
3605
+ const content = node.content;
3606
+ if (content?.type === 'instance' || content?.type === 'pattern') {
3607
+ const prefab = findRequiredPrefab(document, content.prefab);
3608
+ if (prefabStack.includes(prefab.id)) {
3609
+ throw new Error(`Recursive scene prefab expansion: ${[...prefabStack, prefab.id].join(' -> ')}`);
3610
+ }
3611
+ const root = resolveScenePrefabRoot(document, prefab.root, content.overrides);
3612
+ const nextStack = [...prefabStack, prefab.id];
3613
+ if (content.type === 'instance') {
3614
+ points.push(...collectNodeBoundsPoints(document, root, appendSceneTransform(nodeWorldTransform, root.transform), nextStack, deriveSceneInstanceNodeId(runtimeNodeId, root.id), excludedNodeIds, runtimeNodeId, resolveAssetBounds));
3615
+ }
3616
+ else {
3617
+ const collisionRadius = getSceneNodeCollisionRadiusInternal(document, root, nextStack, resolveAssetBounds);
3618
+ const transforms = generateScenePatternTransforms(content.distribution, {
3619
+ collisionRadius,
3620
+ seedKey: runtimeNodeId,
3621
+ });
3622
+ for (let index = 0; index < transforms.length; index += 1) {
3623
+ const transform = transforms[index];
3624
+ const namespace = deriveScenePatternInstanceNamespace(runtimeNodeId, index);
3625
+ const instanceTransform = appendSceneTransform(nodeWorldTransform, transform);
3626
+ points.push(...collectNodeBoundsPoints(document, root, appendSceneTransform(instanceTransform, root.transform), nextStack, deriveSceneInstanceNodeId(namespace, root.id), excludedNodeIds, namespace, resolveAssetBounds));
3627
+ }
3628
+ }
3629
+ }
3630
+ for (const child of node.children ?? []) {
3631
+ points.push(...collectNodeBoundsPoints(document, child, appendSceneTransform(nodeWorldTransform, child.transform), prefabStack, derivedNamespace == null
3632
+ ? child.id
3633
+ : deriveSceneInstanceNodeId(derivedNamespace, child.id), excludedNodeIds, derivedNamespace, resolveAssetBounds));
3634
+ }
3635
+ return points;
3636
+ }
3637
+ function getSceneNodeCollisionRadiusInternal(document, node, prefabStack, resolveAssetBounds) {
3638
+ const points = collectNodeBoundsPoints(document, node, identityWorldTransform(), prefabStack, node.id, new Set(), undefined, resolveAssetBounds);
3639
+ const transform = node.transform ?? {};
3640
+ const linear = composeLinearTransform(transform.rotationDeg ?? [0, 0, 0], scaleToVec3(transform.scale));
3641
+ return points.reduce((radius, point) => Math.max(radius, vectorLength(transformVec3(linear, point))), 0);
3642
+ }
3643
+ function appendSceneTransform(parent, transform) {
3644
+ const position = transform?.position ?? [0, 0, 0];
3645
+ const localLinear = composeLinearTransform(transform?.rotationDeg ?? [0, 0, 0], scaleToVec3(transform?.scale));
3646
+ return {
3647
+ linear: multiplyMat3(parent.linear, localLinear),
3648
+ position: addVec3(parent.position, transformVec3(parent.linear, position)),
3649
+ };
3650
+ }
3651
+ function transformPoint(transform, point) {
3652
+ return addVec3(transform.position, transformVec3(transform.linear, point));
3653
+ }
3654
+ function getNodeDirectLocalBounds(node, resolveAssetBounds) {
3655
+ const assetId = node.content?.type === 'asset' ? node.content.asset : undefined;
3656
+ const assetBounds = assetId == null ? undefined : resolveAssetBounds?.(assetId);
3657
+ return getSceneNodeLocalBounds(node, assetBounds);
3658
+ }
3659
+ function findRequiredPrefab(document, prefabId) {
3660
+ const prefab = document.resources.prefabs?.find((entry) => entry.id === prefabId);
3661
+ if (prefab == null) {
3662
+ throw new Error(`Scene references unknown prefab "${prefabId}"`);
3663
+ }
3664
+ return prefab;
3665
+ }
3666
+ function boundsCorners(bounds) {
3667
+ return [
3668
+ [bounds.min[0], bounds.min[1], bounds.min[2]],
3669
+ [bounds.min[0], bounds.min[1], bounds.max[2]],
3670
+ [bounds.min[0], bounds.max[1], bounds.min[2]],
3671
+ [bounds.min[0], bounds.max[1], bounds.max[2]],
3672
+ [bounds.max[0], bounds.min[1], bounds.min[2]],
3673
+ [bounds.max[0], bounds.min[1], bounds.max[2]],
3674
+ [bounds.max[0], bounds.max[1], bounds.min[2]],
3675
+ [bounds.max[0], bounds.max[1], bounds.max[2]],
3676
+ ];
3677
+ }
3678
+ function boundsFromPoints(points) {
3679
+ const min = [Infinity, Infinity, Infinity];
3680
+ const max = [-Infinity, -Infinity, -Infinity];
3681
+ for (const point of points) {
3682
+ for (let index = 0; index < 3; index += 1) {
3683
+ min[index] = Math.min(min[index], point[index]);
3684
+ max[index] = Math.max(max[index], point[index]);
3685
+ }
3686
+ }
3687
+ return {
3688
+ max: roundHelperVec3(max),
3689
+ min: roundHelperVec3(min),
3690
+ };
3691
+ }
3692
+ function findRequiredNode(document, nodeId) {
3693
+ const node = findNode(document.nodes, nodeId);
3694
+ if (node == null) {
3695
+ throw new Error(`Unknown node "${nodeId}"`);
3696
+ }
3697
+ return node;
3698
+ }
3699
+ function scaleToVec3(scale) {
3700
+ if (scale == null) {
3701
+ return [1, 1, 1];
3702
+ }
3703
+ return typeof scale === 'number' ? [scale, scale, scale] : scale;
3704
+ }
3705
+ function normalizeDegrees(value) {
3706
+ const normalized = value % 360;
3707
+ return normalized < 0 ? normalized + 360 : normalized;
3708
+ }
3709
+ function degreesToRadians(degrees) {
3710
+ return (degrees * Math.PI) / 180;
3711
+ }
3712
+ function radiansToDegrees(radians) {
3713
+ return (radians * 180) / Math.PI;
3714
+ }
3715
+ function roundHelperNumber(value) {
3716
+ const rounded = Number(value.toFixed(6));
3717
+ return Object.is(rounded, -0) ? 0 : rounded;
3718
+ }
3719
+ function roundHelperVec3(value) {
3720
+ return value.map(roundHelperNumber);
3721
+ }
3722
+ function compactTransform(transform) {
3723
+ const nextTransform = { ...transform };
3724
+ if (nextTransform.position != null &&
3725
+ nextTransform.position.every((value) => value === 0)) {
3726
+ delete nextTransform.position;
3727
+ }
3728
+ if (nextTransform.rotationDeg != null &&
3729
+ nextTransform.rotationDeg.every((value) => value === 0)) {
3730
+ delete nextTransform.rotationDeg;
3731
+ }
3732
+ const scale = scaleToVec3(nextTransform.scale);
3733
+ if (scale.every((value) => value === 1)) {
3734
+ delete nextTransform.scale;
3735
+ }
3736
+ return nextTransform;
3737
+ }
3738
+
3739
+ /**
3740
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3741
+ *
3742
+ * This source code is licensed under the MIT license found in the
3743
+ * LICENSE file in the root directory of this source tree.
3744
+ */
3745
+ function applyScenePatch(document, patch, validationOptions = {}) {
3746
+ const safePatch = deepClone(patch);
3747
+ assertValidScenePatch(safePatch);
3748
+ const previousDocument = deepClone(document);
3749
+ const nextDocument = applyPatchToClone(deepClone(document), safePatch);
3750
+ assertValidSceneDocument(nextDocument, validationOptions);
3751
+ return {
3752
+ document: nextDocument,
3753
+ inverse: { document: previousDocument, op: 'replaceDocument' },
3754
+ };
3755
+ }
3756
+ function applyPatchToClone(document, patch) {
3757
+ if (patch.op === 'replaceDocument') {
3758
+ return deepClone(patch.document);
3759
+ }
3760
+ if (patch.op === 'transaction') {
3761
+ return patch.patches.reduce((current, entry) => applyPatchToClone(current, entry), document);
3762
+ }
3763
+ applyPatchInPlace(document, patch);
3764
+ return document;
3765
+ }
3766
+ class SceneCommandHistory {
3767
+ constructor(document, options = {}) {
3768
+ this.past = [];
3769
+ this.future = [];
3770
+ this.validationOptions = options.validationOptions ?? {};
3771
+ if (options.validateInitialDocument !== false) {
3772
+ assertValidSceneDocument(document, this.validationOptions);
3773
+ }
3774
+ this.sceneDocument = deepClone(document);
3775
+ }
3776
+ get document() {
3777
+ return deepClone(this.sceneDocument);
3778
+ }
3779
+ apply(patch) {
3780
+ const safePatch = deepClone(patch);
3781
+ const result = applyScenePatch(this.sceneDocument, safePatch, this.validationOptions);
3782
+ this.past.push({ inverse: deepClone(result.inverse), patch: safePatch });
3783
+ this.future = [];
3784
+ this.sceneDocument = result.document;
3785
+ return this.document;
3786
+ }
3787
+ applyTransaction(patches) {
3788
+ return this.apply({ op: 'transaction', patches });
3789
+ }
3790
+ replace(document) {
3791
+ return this.apply({ document, op: 'replaceDocument' });
3792
+ }
3793
+ undo() {
3794
+ const entry = this.past.pop();
3795
+ if (entry == null) {
3796
+ return this.document;
3797
+ }
3798
+ const result = applyScenePatch(this.sceneDocument, entry.inverse, this.validationOptions);
3799
+ this.future.push(entry);
3800
+ this.sceneDocument = result.document;
3801
+ return this.document;
3802
+ }
3803
+ redo() {
3804
+ const entry = this.future.pop();
3805
+ if (entry == null) {
3806
+ return this.document;
3807
+ }
3808
+ const result = applyScenePatch(this.sceneDocument, entry.patch, this.validationOptions);
3809
+ this.past.push({ inverse: result.inverse, patch: entry.patch });
3810
+ this.sceneDocument = result.document;
3811
+ return this.document;
3812
+ }
3813
+ }
3814
+ function applyPatchInPlace(document, patch) {
3815
+ switch (patch.op) {
3816
+ case 'addNode':
3817
+ return addNode(document, patch.node, patch.parentId ?? null, patch.index);
3818
+ case 'removeNode':
3819
+ return removeNode(document, patch.nodeId);
3820
+ case 'moveNode':
3821
+ return moveNode(document, patch.nodeId, patch.parentId ?? null, patch.index, patch.preserveWorldTransform === true, patch.parent);
3822
+ case 'renameNode':
3823
+ return renameNode(document, patch.nodeId, patch.newNodeId);
3824
+ case 'updateTransform':
3825
+ return updateTransform(document, patch.nodeId, patch.transform);
3826
+ case 'updateVisibility':
3827
+ return updateVisibility(document, patch.nodeId, patch.visible);
3828
+ case 'updateFramingRole':
3829
+ return updateFramingRole(document, patch.nodeId, patch.framingRole);
3830
+ case 'updateComponent':
3831
+ return updateComponent(document, patch.nodeId, patch.component, patch.value);
3832
+ case 'updateRootComponent':
3833
+ return updateRootComponent(document, patch.component, patch.value);
3834
+ case 'updatePlayerComponent':
3835
+ return updatePlayerComponent(document, patch.target, patch.component, patch.value);
3836
+ case 'updatePlayerTransform':
3837
+ return updatePlayerTransform(document, patch.target, patch.transform);
3838
+ case 'reorderChildren':
3839
+ return reorderChildren(document, patch.parentId ?? null, patch.childIds);
3840
+ case 'updateContent':
3841
+ return updateContent(document, patch.nodeId, patch.content);
3842
+ case 'updateConstraints':
3843
+ return updateConstraints(document, patch.nodeId, patch.constraints);
3844
+ case 'setNodeMetadata':
3845
+ return setNodeMetadata(document, patch.nodeId, patch.value);
3846
+ case 'setAuthoring':
3847
+ return setAuthoring(document, patch.authoring);
3848
+ case 'setEnvironment':
3849
+ return setEnvironment(document, patch.environment);
3850
+ case 'addPrefab':
3851
+ return addPrefab(document, patch.prefab, patch.index);
3852
+ case 'updatePrefab':
3853
+ return updatePrefab(document, patch.prefabId, patch.prefab);
3854
+ case 'removePrefab':
3855
+ return removePrefab(document, patch.prefabId);
3856
+ case 'addAuthoringView':
3857
+ return addAuthoringView(document, patch.view, patch.index);
3858
+ case 'updateAuthoringView':
3859
+ return updateAuthoringView(document, patch.viewId, patch.view);
3860
+ case 'removeAuthoringView':
3861
+ return removeAuthoringView(document, patch.viewId);
3862
+ }
3863
+ }
3864
+ function assertValidScenePatch(value) {
3865
+ if (!isPlainObject(value)) {
3866
+ throw new Error('Scene patch must be an object');
3867
+ }
3868
+ const op = value.op;
3869
+ switch (op) {
3870
+ case 'replaceDocument':
3871
+ assertPlainObjectField(value.document, 'document');
3872
+ return;
3873
+ case 'transaction':
3874
+ if (!Array.isArray(value.patches)) {
3875
+ throw new Error('patches must be an array');
3876
+ }
3877
+ value.patches.forEach(assertValidScenePatch);
3878
+ return;
3879
+ case 'addNode':
3880
+ assertPlainObjectField(value.node, 'node');
3881
+ assertOptionalParentId(value.parentId);
3882
+ assertOptionalIndex(value.index);
3883
+ return;
3884
+ case 'removeNode':
3885
+ assertNonEmptyStringField(value.nodeId, 'nodeId');
3886
+ return;
3887
+ case 'moveNode':
3888
+ assertNonEmptyStringField(value.nodeId, 'nodeId');
3889
+ assertOptionalParentId(value.parentId);
3890
+ if (value.parent !== undefined) {
3891
+ assertPlayerSpaceParent(value.parent);
3892
+ }
3893
+ if (value.parentId != null && value.parent != null) {
3894
+ throw new Error('moveNode cannot set both parentId and parent');
3895
+ }
3896
+ assertOptionalIndex(value.index);
3897
+ assertOptionalBoolean(value.preserveWorldTransform, 'preserveWorldTransform');
3898
+ return;
3899
+ case 'renameNode':
3900
+ assertNonEmptyStringField(value.nodeId, 'nodeId');
3901
+ assertNonEmptyStringField(value.newNodeId, 'newNodeId');
3902
+ return;
3903
+ case 'updateTransform':
3904
+ assertNonEmptyStringField(value.nodeId, 'nodeId');
3905
+ if (value.transform !== undefined) {
3906
+ assertPlainObjectField(value.transform, 'transform');
3907
+ }
3908
+ return;
3909
+ case 'updateVisibility':
3910
+ assertNonEmptyStringField(value.nodeId, 'nodeId');
3911
+ assertOptionalBoolean(value.visible, 'visible');
3912
+ return;
3913
+ case 'updateFramingRole':
3914
+ assertNonEmptyStringField(value.nodeId, 'nodeId');
3915
+ if (value.framingRole !== undefined &&
3916
+ value.framingRole !== 'content' &&
3917
+ value.framingRole !== 'support') {
3918
+ throw new Error('framingRole must be "content" or "support"');
3919
+ }
3920
+ return;
3921
+ case 'updateComponent':
3922
+ assertNonEmptyStringField(value.nodeId, 'nodeId');
3923
+ assertNonEmptyStringField(value.component, 'component');
3924
+ if (value.value !== undefined && !isJsonValue(value.value)) {
3925
+ throw new Error('value must be JSON serializable');
3926
+ }
3927
+ return;
3928
+ case 'updateRootComponent':
3929
+ assertNonEmptyStringField(value.component, 'component');
3930
+ if (value.value !== undefined && !isJsonValue(value.value)) {
3931
+ throw new Error('value must be JSON serializable');
3932
+ }
3933
+ return;
3934
+ case 'updatePlayerComponent':
3935
+ assertPlayerTarget(value.target);
3936
+ assertNonEmptyStringField(value.component, 'component');
3937
+ if (value.value !== undefined && !isJsonValue(value.value)) {
3938
+ throw new Error('value must be JSON serializable');
3939
+ }
3940
+ return;
3941
+ case 'updatePlayerTransform':
3942
+ if (value.target !== 'player') {
3943
+ throw new Error('updatePlayerTransform only supports Player Space');
3944
+ }
3945
+ if (value.transform !== undefined) {
3946
+ assertPlainObjectField(value.transform, 'transform');
3947
+ }
3948
+ return;
3949
+ case 'reorderChildren':
3950
+ if (!Array.isArray(value.childIds) ||
3951
+ !value.childIds.every((childId) => typeof childId === 'string')) {
3952
+ throw new Error('childIds must be an array of strings');
3953
+ }
3954
+ assertOptionalParentId(value.parentId);
3955
+ return;
3956
+ case 'updateContent':
3957
+ assertNonEmptyStringField(value.nodeId, 'nodeId');
3958
+ if (value.content !== undefined) {
3959
+ assertPlainObjectField(value.content, 'content');
3960
+ }
3961
+ return;
3962
+ case 'updateConstraints':
3963
+ assertNonEmptyStringField(value.nodeId, 'nodeId');
3964
+ if (value.constraints !== undefined) {
3965
+ assertPlainObjectField(value.constraints, 'constraints');
3966
+ }
3967
+ return;
3968
+ case 'setNodeMetadata':
3969
+ assertNonEmptyStringField(value.nodeId, 'nodeId');
3970
+ if (value.value !== undefined &&
3971
+ (!isPlainObject(value.value) || !isJsonValue(value.value))) {
3972
+ throw new Error('value must be a JSON object');
3973
+ }
3974
+ return;
3975
+ case 'setAuthoring':
3976
+ if (value.authoring !== undefined) {
3977
+ assertPlainObjectField(value.authoring, 'authoring');
3978
+ }
3979
+ return;
3980
+ case 'setEnvironment':
3981
+ if (value.environment !== undefined) {
3982
+ assertPlainObjectField(value.environment, 'environment');
3983
+ }
3984
+ return;
3985
+ case 'addPrefab':
3986
+ assertPlainObjectField(value.prefab, 'prefab');
3987
+ assertOptionalIndex(value.index);
3988
+ return;
3989
+ case 'updatePrefab':
3990
+ assertNonEmptyStringField(value.prefabId, 'prefabId');
3991
+ assertPlainObjectField(value.prefab, 'prefab');
3992
+ return;
3993
+ case 'removePrefab':
3994
+ assertNonEmptyStringField(value.prefabId, 'prefabId');
3995
+ return;
3996
+ case 'addAuthoringView':
3997
+ assertPlainObjectField(value.view, 'view');
3998
+ assertOptionalIndex(value.index);
3999
+ return;
4000
+ case 'updateAuthoringView':
4001
+ assertNonEmptyStringField(value.viewId, 'viewId');
4002
+ assertPlainObjectField(value.view, 'view');
4003
+ return;
4004
+ case 'removeAuthoringView':
4005
+ assertNonEmptyStringField(value.viewId, 'viewId');
4006
+ return;
4007
+ default:
4008
+ throw new Error(`Unsupported scene patch op "${String(op)}"`);
4009
+ }
4010
+ }
4011
+ function assertPlainObjectField(value, fieldName) {
4012
+ if (!isPlainObject(value)) {
4013
+ throw new Error(`${fieldName} must be an object`);
4014
+ }
4015
+ }
4016
+ function assertNonEmptyStringField(value, fieldName) {
4017
+ if (typeof value !== 'string' || value.length === 0) {
4018
+ throw new Error(`${fieldName} must be a non-empty string`);
4019
+ }
4020
+ }
4021
+ function assertOptionalParentId(value) {
4022
+ if (value !== undefined && value !== null && typeof value !== 'string') {
4023
+ throw new Error('parentId must be a string or null');
4024
+ }
4025
+ }
4026
+ function assertPlayerTarget(value) {
4027
+ if (![
4028
+ 'player',
4029
+ 'camera',
4030
+ 'head',
4031
+ 'left-target-ray',
4032
+ 'right-target-ray',
4033
+ 'left-grip',
4034
+ 'right-grip',
4035
+ ].includes(String(value))) {
4036
+ throw new Error('target must name a built-in player space');
4037
+ }
4038
+ }
4039
+ function assertPlayerSpaceParent(value) {
4040
+ assertPlainObjectField(value, 'parent');
4041
+ if (value.type !== 'player-space') {
4042
+ throw new Error('parent.type must be "player-space"');
4043
+ }
4044
+ assertPlayerTarget(value.target);
4045
+ }
4046
+ function assertOptionalIndex(value) {
4047
+ if (value !== undefined &&
4048
+ (!Number.isInteger(value) || value < 0)) {
4049
+ throw new Error('index must be a non-negative integer');
4050
+ }
4051
+ }
4052
+ function assertOptionalBoolean(value, fieldName) {
4053
+ if (value !== undefined && typeof value !== 'boolean') {
4054
+ throw new Error(`${fieldName} must be a boolean`);
4055
+ }
4056
+ }
4057
+ function addNode(document, node, parentId, index) {
4058
+ if (findNode(document.nodes, node.id) != null) {
4059
+ throw new Error(`Cannot add duplicate node "${node.id}"`);
4060
+ }
4061
+ const siblings = getSiblings(document, parentId, { create: true });
4062
+ const insertionIndex = index ?? siblings.length;
4063
+ siblings.splice(insertionIndex, 0, deepClone(node));
4064
+ return {
4065
+ nodeId: node.id,
4066
+ op: 'removeNode',
4067
+ };
4068
+ }
4069
+ function removeNode(document, nodeId) {
4070
+ const location = findNodeLocation(document.nodes, nodeId);
4071
+ if (location == null) {
4072
+ throw new Error(`Cannot remove unknown node "${nodeId}"`);
4073
+ }
4074
+ const [removed] = location.siblings.splice(location.index, 1);
4075
+ return {
4076
+ index: location.index,
4077
+ node: removed,
4078
+ op: 'addNode',
4079
+ parentId: location.parent?.id ?? null,
4080
+ };
4081
+ }
4082
+ function moveNode(document, nodeId, parentId, index, preserveWorldTransform = false, parent) {
4083
+ if (parentId === nodeId) {
4084
+ throw new Error(`Cannot move node "${nodeId}" under itself`);
4085
+ }
4086
+ const source = findNodeLocation(document.nodes, nodeId);
4087
+ if (source == null) {
4088
+ throw new Error(`Cannot move unknown node "${nodeId}"`);
4089
+ }
4090
+ if (parentId != null &&
4091
+ findNode(source.node.children ?? [], parentId) != null) {
4092
+ throw new Error(`Cannot move node "${nodeId}" under its descendant "${parentId}"`);
4093
+ }
4094
+ if (parentId != null && findNode(document.nodes, parentId) == null) {
4095
+ throw new Error(`Unknown parent node "${parentId}"`);
4096
+ }
4097
+ const preservedTransform = preserveWorldTransform
4098
+ ? resolveReparentTransform(document, nodeId, parentId, parent?.target)
4099
+ : undefined;
4100
+ const previousParentId = source.parent?.id ?? null;
4101
+ const previousParent = source.parent == null && source.node.parent != null
4102
+ ? deepClone(source.node.parent)
4103
+ : undefined;
4104
+ const previousIndex = source.index;
4105
+ const [node] = source.siblings.splice(source.index, 1);
4106
+ if (preservedTransform != null) {
4107
+ if (isMeaningfulTransform(preservedTransform)) {
4108
+ node.transform = preservedTransform;
4109
+ }
4110
+ else {
4111
+ delete node.transform;
4112
+ }
4113
+ }
4114
+ if (source.parent != null && source.siblings.length === 0) {
4115
+ delete source.parent.children;
4116
+ }
4117
+ if (parentId != null || parent == null) {
4118
+ delete node.parent;
4119
+ }
4120
+ else {
4121
+ node.parent = deepClone(parent);
4122
+ }
4123
+ const destination = getSiblings(document, parentId, { create: true });
4124
+ const insertionIndex = Math.min(index ?? destination.length, destination.length);
4125
+ destination.splice(insertionIndex, 0, node);
4126
+ return {
4127
+ index: previousIndex,
4128
+ nodeId,
4129
+ op: 'moveNode',
4130
+ parentId: previousParentId,
4131
+ ...(previousParent == null ? {} : { parent: previousParent }),
4132
+ preserveWorldTransform,
4133
+ };
4134
+ }
4135
+ function renameNode(document, nodeId, newNodeId) {
4136
+ if (nodeId === newNodeId) {
4137
+ return {
4138
+ newNodeId: nodeId,
4139
+ nodeId,
4140
+ op: 'renameNode',
4141
+ };
4142
+ }
4143
+ const node = getRequiredNode(document, nodeId);
4144
+ if (findNode(document.nodes, newNodeId) != null) {
4145
+ throw new Error(`Cannot rename node "${nodeId}" to duplicate id "${newNodeId}"`);
4146
+ }
4147
+ node.id = newNodeId;
4148
+ rewriteNodeReferences(document, nodeId, newNodeId);
4149
+ return {
4150
+ newNodeId: nodeId,
4151
+ nodeId: newNodeId,
4152
+ op: 'renameNode',
4153
+ };
4154
+ }
4155
+ function rewriteNodeReferences(document, previousId, nextId) {
4156
+ const visit = (nodes) => {
4157
+ for (const entry of nodes) {
4158
+ rewriteComponentEntityReferences(entry.components, previousId, nextId);
4159
+ visit(entry.children ?? []);
4160
+ }
4161
+ };
4162
+ visit(document.nodes);
4163
+ rewriteComponentEntityReferences(document.components, previousId, nextId);
4164
+ for (const descriptor of [
4165
+ document.player,
4166
+ document.player?.camera,
4167
+ document.player?.head,
4168
+ document.player?.leftTargetRay,
4169
+ document.player?.rightTargetRay,
4170
+ document.player?.leftGrip,
4171
+ document.player?.rightGrip,
4172
+ ]) {
4173
+ rewriteComponentEntityReferences(descriptor?.components, previousId, nextId);
4174
+ }
4175
+ const composition = document.authoring?.composition;
4176
+ composition?.features.forEach((feature) => {
4177
+ feature.nodeRefs = replaceIds(feature.nodeRefs, previousId, nextId);
4178
+ feature.acceptance.forEach((criterion) => {
4179
+ if ('nodeRefs' in criterion && criterion.nodeRefs != null) {
4180
+ criterion.nodeRefs = replaceIds(criterion.nodeRefs, previousId, nextId);
4181
+ }
4182
+ if (criterion.kind === 'count' && criterion.pattern === previousId) {
4183
+ criterion.pattern = nextId;
4184
+ }
4185
+ if (criterion.kind === 'spatial-relation' &&
4186
+ criterion.target === previousId) {
4187
+ criterion.target = nextId;
4188
+ }
4189
+ });
4190
+ const inspection = feature.objectInspection;
4191
+ inspection?.parts.forEach((part) => {
4192
+ part.nodeRefs = replaceIds(part.nodeRefs, previousId, nextId);
4193
+ });
4194
+ inspection?.contacts.forEach((contact) => {
4195
+ contact.nodeRefs = replaceIds(contact.nodeRefs, previousId, nextId);
4196
+ contact.targetNodeRefs = replaceIds(contact.targetNodeRefs, previousId, nextId);
4197
+ });
4198
+ if (inspection?.context.includeNodeRefs != null) {
4199
+ inspection.context.includeNodeRefs = replaceIds(inspection.context.includeNodeRefs, previousId, nextId);
4200
+ }
4201
+ });
4202
+ document.authoring?.nodeAnnotations?.forEach((annotation) => {
4203
+ if (annotation.node === previousId) {
4204
+ annotation.node = nextId;
4205
+ }
4206
+ });
4207
+ }
4208
+ function rewriteComponentEntityReferences(components, previousId, nextId) {
4209
+ const visit = (value) => {
4210
+ if (Array.isArray(value)) {
4211
+ value.forEach(visit);
4212
+ return;
4213
+ }
4214
+ if (value == null || typeof value !== 'object') {
4215
+ return;
4216
+ }
4217
+ const record = value;
4218
+ if (record.type === 'node' && record.id === previousId) {
4219
+ record.id = nextId;
4220
+ }
4221
+ Object.values(record).forEach(visit);
4222
+ };
4223
+ Object.values(components ?? {}).forEach(visit);
4224
+ }
4225
+ function replaceIds(ids, previousId, nextId) {
4226
+ return ids.map((id) => (id === previousId ? nextId : id));
4227
+ }
4228
+ function updateTransform(document, nodeId, transform) {
4229
+ const node = getRequiredNode(document, nodeId);
4230
+ const previous = node.transform == null ? undefined : deepClone(node.transform);
4231
+ if (transform == null) {
4232
+ delete node.transform;
4233
+ }
4234
+ else {
4235
+ node.transform = deepClone(transform);
4236
+ }
4237
+ return {
4238
+ nodeId,
4239
+ op: 'updateTransform',
4240
+ transform: previous,
4241
+ };
4242
+ }
4243
+ function updateVisibility(document, nodeId, visible) {
4244
+ const node = getRequiredNode(document, nodeId);
4245
+ const previous = node.visible;
4246
+ // Visible is the default and is omitted from canonical scene JSON.
4247
+ if (visible === undefined || visible) {
4248
+ delete node.visible;
4249
+ }
4250
+ else {
4251
+ node.visible = false;
4252
+ }
4253
+ removeLegacyVisibilityComponent(node);
4254
+ return {
4255
+ nodeId,
4256
+ op: 'updateVisibility',
4257
+ visible: previous,
4258
+ };
4259
+ }
4260
+ function removeLegacyVisibilityComponent(node) {
4261
+ if (node.components == null) {
4262
+ return;
4263
+ }
4264
+ for (const componentName of Object.keys(node.components)) {
4265
+ if (componentName === 'Visibility' ||
4266
+ componentName === 'com.iwsdk.components.Visibility') {
4267
+ delete node.components[componentName];
4268
+ }
4269
+ }
4270
+ if (Object.keys(node.components).length === 0) {
4271
+ delete node.components;
4272
+ }
4273
+ }
4274
+ function updateFramingRole(document, nodeId, framingRole) {
4275
+ const node = getRequiredNode(document, nodeId);
4276
+ const previous = node.framingRole;
4277
+ if (framingRole === undefined) {
4278
+ delete node.framingRole;
4279
+ }
4280
+ else {
4281
+ node.framingRole = framingRole;
4282
+ }
4283
+ return {
4284
+ framingRole: previous,
4285
+ nodeId,
4286
+ op: 'updateFramingRole',
4287
+ };
4288
+ }
4289
+ function updateComponent(document, nodeId, component, value) {
4290
+ const node = getRequiredNode(document, nodeId);
4291
+ const previous = node.components?.[component];
4292
+ if (value === undefined) {
4293
+ if (node.components != null) {
4294
+ delete node.components[component];
4295
+ if (Object.keys(node.components).length === 0) {
4296
+ delete node.components;
4297
+ }
4298
+ }
4299
+ }
4300
+ else {
4301
+ node.components = node.components ?? {};
4302
+ node.components[component] = deepClone(value);
4303
+ }
4304
+ return {
4305
+ component,
4306
+ nodeId,
4307
+ op: 'updateComponent',
4308
+ value: previous === undefined ? undefined : deepClone(previous),
4309
+ };
4310
+ }
4311
+ function updateRootComponent(document, component, value) {
4312
+ const previous = document.components?.[component];
4313
+ document.components ??= {};
4314
+ if (value === undefined) {
4315
+ delete document.components[component];
4316
+ }
4317
+ else {
4318
+ document.components[component] = deepClone(value);
4319
+ }
4320
+ return {
4321
+ component,
4322
+ op: 'updateRootComponent',
4323
+ value: previous === undefined ? undefined : deepClone(previous),
4324
+ };
4325
+ }
4326
+ function updatePlayerComponent(document, target, component, value) {
4327
+ const { descriptor, targetKey } = getPlayerDescriptor(document, target);
4328
+ const previous = descriptor.components?.[component];
4329
+ descriptor.components ??= {};
4330
+ if (value === undefined) {
4331
+ delete descriptor.components[component];
4332
+ if (Object.keys(descriptor.components).length === 0) {
4333
+ delete descriptor.components;
4334
+ }
4335
+ }
4336
+ else {
4337
+ descriptor.components[component] = deepClone(value);
4338
+ }
4339
+ pruneEmptyPlayerDescriptor(document, targetKey, descriptor);
4340
+ return {
4341
+ component,
4342
+ op: 'updatePlayerComponent',
4343
+ target,
4344
+ value: previous === undefined ? undefined : deepClone(previous),
4345
+ };
4346
+ }
4347
+ function getPlayerDescriptor(document, target) {
4348
+ document.player ??= {};
4349
+ const targetKeys = {
4350
+ camera: 'camera',
4351
+ head: 'head',
4352
+ 'left-target-ray': 'leftTargetRay',
4353
+ 'right-target-ray': 'rightTargetRay',
4354
+ 'left-grip': 'leftGrip',
4355
+ 'right-grip': 'rightGrip',
4356
+ };
4357
+ const targetKey = target === 'player' ? null : targetKeys[target];
4358
+ return {
4359
+ descriptor: targetKey == null ? document.player : (document.player[targetKey] ??= {}),
4360
+ targetKey,
4361
+ };
4362
+ }
4363
+ function pruneEmptyPlayerDescriptor(document, targetKey, descriptor) {
4364
+ if (targetKey != null && Object.keys(descriptor).length === 0) {
4365
+ delete document.player?.[targetKey];
4366
+ }
4367
+ if (document.player != null && Object.keys(document.player).length === 0) {
4368
+ delete document.player;
4369
+ }
4370
+ }
4371
+ function updatePlayerTransform(document, target, transform) {
4372
+ document.player ??= {};
4373
+ const previous = document.player.transform;
4374
+ if (transform === undefined) {
4375
+ delete document.player.transform;
4376
+ }
4377
+ else {
4378
+ document.player.transform = deepClone(transform);
4379
+ }
4380
+ pruneEmptyPlayerDescriptor(document, null, document.player);
4381
+ return {
4382
+ op: 'updatePlayerTransform',
4383
+ target,
4384
+ transform: previous === undefined ? undefined : deepClone(previous),
4385
+ };
4386
+ }
4387
+ function reorderChildren(document, parentId, childIds) {
4388
+ const siblings = getSiblings(document, parentId, { create: false });
4389
+ const previousIds = siblings.map((node) => node.id);
4390
+ if (previousIds.length !== childIds.length) {
4391
+ throw new Error('reorderChildren must include every child id exactly once');
4392
+ }
4393
+ const byId = new Map(siblings.map((node) => [node.id, node]));
4394
+ const nextSiblings = childIds.map((id) => {
4395
+ const node = byId.get(id);
4396
+ if (node == null) {
4397
+ throw new Error(`Cannot reorder unknown child "${id}"`);
4398
+ }
4399
+ return node;
4400
+ });
4401
+ siblings.splice(0, siblings.length, ...nextSiblings);
4402
+ return {
4403
+ childIds: previousIds,
4404
+ op: 'reorderChildren',
4405
+ parentId,
4406
+ };
4407
+ }
4408
+ function updateContent(document, nodeId, content) {
4409
+ const node = getRequiredNode(document, nodeId);
4410
+ const previous = node.content;
4411
+ if (content == null) {
4412
+ delete node.content;
4413
+ }
4414
+ else {
4415
+ node.content = deepClone(content);
4416
+ }
4417
+ return {
4418
+ content: previous === undefined ? undefined : deepClone(previous),
4419
+ nodeId,
4420
+ op: 'updateContent',
4421
+ };
4422
+ }
4423
+ function updateConstraints(document, nodeId, constraints) {
4424
+ const node = getRequiredNode(document, nodeId);
4425
+ const previous = node.constraints;
4426
+ if (constraints == null) {
4427
+ delete node.constraints;
4428
+ }
4429
+ else {
4430
+ node.constraints = deepClone(constraints);
4431
+ }
4432
+ return {
4433
+ constraints: previous === undefined ? undefined : deepClone(previous),
4434
+ nodeId,
4435
+ op: 'updateConstraints',
4436
+ };
4437
+ }
4438
+ function setNodeMetadata(document, nodeId, value) {
4439
+ const node = getRequiredNode(document, nodeId);
4440
+ const previous = node.metadata === undefined ? undefined : deepClone(node.metadata);
4441
+ if (value === undefined) {
4442
+ delete node.metadata;
4443
+ }
4444
+ else {
4445
+ node.metadata = deepClone(value);
4446
+ }
4447
+ return {
4448
+ nodeId,
4449
+ op: 'setNodeMetadata',
4450
+ ...(previous === undefined ? {} : { value: previous }),
4451
+ };
4452
+ }
4453
+ function setAuthoring(document, authoring) {
4454
+ const previous = document.authoring == null ? undefined : deepClone(document.authoring);
4455
+ if (authoring == null) {
4456
+ delete document.authoring;
4457
+ }
4458
+ else {
4459
+ document.authoring = deepClone(authoring);
4460
+ }
4461
+ return { op: 'setAuthoring', authoring: previous };
4462
+ }
4463
+ function setEnvironment(document, environment) {
4464
+ const previous = document.environment == null ? undefined : deepClone(document.environment);
4465
+ if (environment == null) {
4466
+ delete document.environment;
4467
+ }
4468
+ else {
4469
+ document.environment = deepClone(environment);
4470
+ }
4471
+ return { op: 'setEnvironment', environment: previous };
4472
+ }
4473
+ function addPrefab(document, prefab, index) {
4474
+ const prefabs = (document.resources.prefabs ??= []);
4475
+ insertAt(prefabs, deepClone(prefab), index);
4476
+ return { op: 'removePrefab', prefabId: prefab.id };
4477
+ }
4478
+ function updatePrefab(document, prefabId, prefab) {
4479
+ if (prefab.id !== prefabId) {
4480
+ throw new Error('updatePrefab cannot rename a resource id');
4481
+ }
4482
+ const prefabs = document.resources.prefabs ?? [];
4483
+ const index = findResourceIndex(prefabs, prefabId, 'prefab');
4484
+ const previous = prefabs[index];
4485
+ prefabs[index] = deepClone(prefab);
4486
+ return { op: 'updatePrefab', prefabId, prefab: previous };
4487
+ }
4488
+ function removePrefab(document, prefabId) {
4489
+ const prefabs = document.resources.prefabs ?? [];
4490
+ const index = findResourceIndex(prefabs, prefabId, 'prefab');
4491
+ const [prefab] = prefabs.splice(index, 1);
4492
+ return { op: 'addPrefab', prefab, index };
4493
+ }
4494
+ function addAuthoringView(document, view, index) {
4495
+ document.authoring ??= {};
4496
+ const views = (document.authoring.views ??= []);
4497
+ insertAt(views, deepClone(view), index);
4498
+ return { op: 'removeAuthoringView', viewId: view.id };
4499
+ }
4500
+ function updateAuthoringView(document, viewId, view) {
4501
+ if (view.id !== viewId) {
4502
+ throw new Error('updateAuthoringView cannot rename a view id');
4503
+ }
4504
+ const views = document.authoring?.views ?? [];
4505
+ const index = findResourceIndex(views, viewId, 'authoring view');
4506
+ const previous = views[index];
4507
+ views[index] = deepClone(view);
4508
+ return { op: 'updateAuthoringView', viewId, view: previous };
4509
+ }
4510
+ function removeAuthoringView(document, viewId) {
4511
+ const views = document.authoring?.views ?? [];
4512
+ const index = findResourceIndex(views, viewId, 'authoring view');
4513
+ const [view] = views.splice(index, 1);
4514
+ return { op: 'addAuthoringView', view, index };
4515
+ }
4516
+ function insertAt(entries, value, index) {
4517
+ entries.splice(Math.min(index ?? entries.length, entries.length), 0, value);
4518
+ }
4519
+ function findResourceIndex(entries, id, kind) {
4520
+ const index = entries.findIndex((entry) => entry.id === id);
4521
+ if (index === -1) {
4522
+ throw new Error(`Unknown ${kind} "${id}"`);
4523
+ }
4524
+ return index;
4525
+ }
4526
+ function getRequiredNode(document, nodeId) {
4527
+ const node = findNode(document.nodes, nodeId);
4528
+ if (node == null) {
4529
+ throw new Error(`Unknown node "${nodeId}"`);
4530
+ }
4531
+ return node;
4532
+ }
4533
+ function getSiblings(document, parentId, options) {
4534
+ if (parentId == null) {
4535
+ return document.nodes;
4536
+ }
4537
+ const parent = getRequiredNode(document, parentId);
4538
+ if (parent.children == null) {
4539
+ if (!options.create) {
4540
+ return [];
4541
+ }
4542
+ parent.children = [];
4543
+ }
4544
+ return parent.children;
4545
+ }
4546
+ function isMeaningfulTransform(transform) {
4547
+ if (transform.position != null &&
4548
+ transform.position.some((value) => value !== 0)) {
4549
+ return true;
4550
+ }
4551
+ if (transform.rotationDeg != null &&
4552
+ transform.rotationDeg.some((value) => value !== 0)) {
4553
+ return true;
4554
+ }
4555
+ if (transform.scale != null) {
4556
+ const scale = typeof transform.scale === 'number'
4557
+ ? [transform.scale, transform.scale, transform.scale]
4558
+ : transform.scale;
4559
+ if (scale.some((value) => value !== 1)) {
4560
+ return true;
4561
+ }
4562
+ }
4563
+ return Object.keys(transform).some((key) => !['position', 'rotationDeg', 'scale'].includes(key));
4564
+ }
4565
+
4566
+ export { getSceneCompositionSourceHashes as A, parseSceneDocument as B, CURRENT_SCENE_VERSION as C, serializeSceneReview as D, resolveSceneAuthoringTransforms as E, parseSceneReview as F, MAX_SCENE_RESOURCES as M, SceneCommandHistory as S, assertValidSceneDocument as a, hashRuntimeSceneDocument as b, canonicalizeJson as c, MAX_SCENE_PATTERN_EXPANSION as d, MAX_SCENE_NODES as e, MAX_SCENE_COORDINATE as f, CURRENT_SCENE_REVIEW_VERSION as g, hashSceneDocument as h, applyScenePatch as i, serializeSceneDocument as j, SCENE_REVIEW_JSON_SCHEMA as k, SCENE_DOCUMENT_JSON_SCHEMA as l, findNode as m, getNodeWorldBounds as n, getScenePatternRequestedCount as o, resolveScenePrefabRoot as p, getSceneNodeCollisionRadius as q, resolveLookAtTransformInDocument as r, sha256 as s, MAX_SCENE_PATTERN_INSTANCES as t, getScenePatternInstanceCount as u, validateSceneDocument as v, deepClone as w, isPlainObject as x, SCENE_IMPORT_ID_PATTERN as y, validateSceneReview as z };
4567
+ //# sourceMappingURL=patch-BVc5fBs4.js.map