playcanvas-agent-bridge-cli 0.6.1 → 0.6.2

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,821 @@
1
+ export const TEXT_FILE_TYPES = new Set([
2
+ "script",
3
+ "text",
4
+ "json",
5
+ "html",
6
+ "css",
7
+ "shader",
8
+ ]);
9
+ export const DATA_JSON_TYPES = new Set([
10
+ "material",
11
+ "template",
12
+ "cubemap",
13
+ "sprite",
14
+ "animstategraph",
15
+ "bundle",
16
+ ]);
17
+ export const MIN_EAGER_MAX_MB = 1;
18
+ export const MAX_EAGER_MAX_MB = 10;
19
+ export const DEFAULT_EAGER_MAX_MB = 2;
20
+ const ENTITY_KEY_ORDER = [
21
+ "resource_id",
22
+ "name",
23
+ "enabled",
24
+ "parent",
25
+ "children",
26
+ "tags",
27
+ "position",
28
+ "rotation",
29
+ "scale",
30
+ "template_id",
31
+ "template_ent_ids",
32
+ "components",
33
+ ];
34
+ const TRANSIENT_ASSET_DATA_KEYS = new Set([
35
+ "uniqueId",
36
+ "createdAt",
37
+ "modifiedAt",
38
+ "revision",
39
+ "user_id",
40
+ "thumbnails",
41
+ "has_thumbnail",
42
+ "task",
43
+ "region",
44
+ ]);
45
+ export function clampEagerMaxMb(value, fallback = DEFAULT_EAGER_MAX_MB) {
46
+ const parsed = Number(value);
47
+ if (!Number.isFinite(parsed))
48
+ return fallback;
49
+ return Math.min(MAX_EAGER_MAX_MB, Math.max(MIN_EAGER_MAX_MB, Math.round(parsed)));
50
+ }
51
+ export function eagerMaxBytesFromMb(mb) {
52
+ return clampEagerMaxMb(mb) * 1024 * 1024;
53
+ }
54
+ function isPlainObject(value) {
55
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
56
+ }
57
+ export function canonicalizeValue(value) {
58
+ if (value === null || value === undefined)
59
+ return null;
60
+ if (typeof value === "boolean" || typeof value === "string")
61
+ return value;
62
+ if (typeof value === "number") {
63
+ if (!Number.isFinite(value))
64
+ return null;
65
+ return value === 0 ? 0 : value;
66
+ }
67
+ if (Array.isArray(value)) {
68
+ return value.map((item) => canonicalizeValue(item));
69
+ }
70
+ if (isPlainObject(value)) {
71
+ const out = {};
72
+ const keys = Object.keys(value).sort((a, b) => a.localeCompare(b));
73
+ for (const key of keys) {
74
+ if (value[key] === undefined)
75
+ continue;
76
+ out[key] = canonicalizeValue(value[key]);
77
+ }
78
+ return out;
79
+ }
80
+ return String(value);
81
+ }
82
+ function canonicalizeEntityObject(id, raw) {
83
+ const out = {};
84
+ const priority = new Set(ENTITY_KEY_ORDER);
85
+ const normalized = {
86
+ ...raw,
87
+ resource_id: id,
88
+ };
89
+ for (const key of ENTITY_KEY_ORDER) {
90
+ if (Object.prototype.hasOwnProperty.call(normalized, key) && normalized[key] !== undefined) {
91
+ out[key] = canonicalizeValue(normalized[key]);
92
+ }
93
+ }
94
+ const rest = Object.keys(normalized)
95
+ .filter((key) => !priority.has(key) && normalized[key] !== undefined)
96
+ .sort((a, b) => a.localeCompare(b));
97
+ for (const key of rest) {
98
+ out[key] = canonicalizeValue(normalized[key]);
99
+ }
100
+ return out;
101
+ }
102
+ export function orderEntitiesDfs(entitiesRaw) {
103
+ const entries = Object.entries(entitiesRaw).filter(([, value]) => isPlainObject(value));
104
+ const byId = new Map(entries);
105
+ const ordered = {};
106
+ const visited = new Set();
107
+ const visit = (id) => {
108
+ if (visited.has(id))
109
+ return;
110
+ const entity = byId.get(id);
111
+ if (!entity)
112
+ return;
113
+ visited.add(id);
114
+ ordered[id] = canonicalizeEntityObject(id, entity);
115
+ const children = Array.isArray(entity.children) ? entity.children : [];
116
+ for (const childId of children) {
117
+ if (typeof childId === "string" && byId.has(childId)) {
118
+ visit(childId);
119
+ }
120
+ }
121
+ };
122
+ const roots = entries
123
+ .filter(([, entity]) => !entity.parent || typeof entity.parent !== "string" || !byId.has(entity.parent))
124
+ .map(([id]) => id)
125
+ .sort((a, b) => a.localeCompare(b));
126
+ for (const rootId of roots)
127
+ visit(rootId);
128
+ const remaining = entries
129
+ .map(([id]) => id)
130
+ .filter((id) => !visited.has(id))
131
+ .sort((a, b) => a.localeCompare(b));
132
+ for (const id of remaining)
133
+ visit(id);
134
+ return ordered;
135
+ }
136
+ export function canonicalizeAssetData(type, data) {
137
+ if (!isPlainObject(data))
138
+ return {};
139
+ const cleaned = {};
140
+ for (const [key, value] of Object.entries(data)) {
141
+ if (TRANSIENT_ASSET_DATA_KEYS.has(key) || value === undefined)
142
+ continue;
143
+ cleaned[key] = value;
144
+ }
145
+ if (type === "template" && isPlainObject(cleaned.entities)) {
146
+ const rest = canonicalizeValue(cleaned);
147
+ rest.entities = orderEntitiesDfs(cleaned.entities);
148
+ return rest;
149
+ }
150
+ return canonicalizeValue(cleaned);
151
+ }
152
+ export function canonicalStringify(value) {
153
+ return `${JSON.stringify(value, null, 2)}\n`;
154
+ }
155
+ export function stripDataAssetSuffix(name, type) {
156
+ const suffix = `.${type}.json`;
157
+ if (name.toLocaleLowerCase().endsWith(suffix.toLocaleLowerCase()) && name.length > suffix.length) {
158
+ return name.slice(0, -suffix.length);
159
+ }
160
+ return name;
161
+ }
162
+ export function dataAssetFilename(name, type) {
163
+ const stem = stripDataAssetSuffix(name || type, type);
164
+ return `${stem}.${type}.json`;
165
+ }
166
+ export function parseDataAssetFilename(filename) {
167
+ const match = filename.match(/^(.+)\.(material|template|cubemap|sprite|animstategraph|bundle)\.json$/i);
168
+ if (!match)
169
+ return null;
170
+ return {
171
+ stem: match[1],
172
+ type: match[2].toLocaleLowerCase(),
173
+ };
174
+ }
175
+ export function buildAssetProjection(input) {
176
+ const tags = Array.isArray(input.tags)
177
+ ? input.tags.filter((tag) => typeof tag === "string")
178
+ : [];
179
+ const doc = {
180
+ name: stripDataAssetSuffix(input.name, input.type),
181
+ preload: input.preload !== false,
182
+ tags,
183
+ data: canonicalizeAssetData(input.type, input.data),
184
+ };
185
+ const header = {
186
+ id: String(input.id),
187
+ kind: "asset",
188
+ type: input.type,
189
+ };
190
+ if (input.sourceAssetId) {
191
+ header.sourceAssetId = String(input.sourceAssetId);
192
+ }
193
+ if (input.writable === false) {
194
+ header.readonly = true;
195
+ }
196
+ const json = {
197
+ $pcbridge: header,
198
+ name: doc.name,
199
+ preload: doc.preload,
200
+ tags: doc.tags,
201
+ data: doc.data,
202
+ };
203
+ return { doc, json, text: canonicalStringify(json) };
204
+ }
205
+ export function parseAssetProjection(rawText, fallback) {
206
+ const parsed = JSON.parse(rawText);
207
+ if (!isPlainObject(parsed)) {
208
+ throw new Error("Structured asset projection must be a JSON object.");
209
+ }
210
+ const header = isPlainObject(parsed.$pcbridge) ? parsed.$pcbridge : null;
211
+ const embeddedId = header && (typeof header.id === "string" || typeof header.id === "number")
212
+ ? String(header.id).trim() || null
213
+ : null;
214
+ const embeddedType = header && typeof header.type === "string" && DATA_JSON_TYPES.has(header.type)
215
+ ? header.type
216
+ : fallback.type;
217
+ const rawName = typeof parsed.name === "string" && parsed.name.trim()
218
+ ? parsed.name.trim()
219
+ : fallback.name;
220
+ const preload = parsed.preload !== false;
221
+ const tags = Array.isArray(parsed.tags)
222
+ ? parsed.tags.filter((tag) => typeof tag === "string")
223
+ : [];
224
+ let rawData = isPlainObject(parsed.data) ? parsed.data : {};
225
+ if (embeddedType === "template" && isPlainObject(rawData) && isPlainObject(rawData.entities)) {
226
+ rawData = {
227
+ ...rawData,
228
+ entities: reconcileEntityHierarchy(rawData.entities),
229
+ };
230
+ }
231
+ return {
232
+ embeddedId,
233
+ embeddedType,
234
+ doc: {
235
+ name: stripDataAssetSuffix(rawName, embeddedType),
236
+ preload,
237
+ tags,
238
+ data: canonicalizeAssetData(embeddedType, rawData),
239
+ },
240
+ };
241
+ }
242
+ export function parseSceneFilename(filename) {
243
+ const match = filename.match(/^(.+)\.([0-9]+)\.scene\.json$/i);
244
+ if (!match)
245
+ return null;
246
+ return {
247
+ stem: match[1],
248
+ sceneId: match[2],
249
+ };
250
+ }
251
+ export function reconcileEntityHierarchy(rawEntities, baseEntities) {
252
+ const map = new Map();
253
+ for (const [id, raw] of Object.entries(rawEntities)) {
254
+ if (!id || !isPlainObject(raw))
255
+ continue;
256
+ const parent = raw.parent === null || raw.parent === undefined || raw.parent === ""
257
+ ? null
258
+ : String(raw.parent);
259
+ const children = Array.isArray(raw.children)
260
+ ? raw.children.filter((item) => typeof item === "string")
261
+ : [];
262
+ map.set(id, {
263
+ ...raw,
264
+ resource_id: id,
265
+ name: typeof raw.name === "string" ? raw.name : "New Entity",
266
+ enabled: raw.enabled !== false,
267
+ parent,
268
+ children: [...new Set(children)],
269
+ tags: Array.isArray(raw.tags) ? raw.tags.filter((t) => typeof t === "string") : [],
270
+ position: Array.isArray(raw.position) && raw.position.length === 3 ? raw.position : [0, 0, 0],
271
+ rotation: Array.isArray(raw.rotation) && raw.rotation.length === 3 ? raw.rotation : [0, 0, 0],
272
+ scale: Array.isArray(raw.scale) && raw.scale.length === 3 ? raw.scale : [1, 1, 1],
273
+ components: isPlainObject(raw.components) ? raw.components : {},
274
+ });
275
+ }
276
+ if (!map.size) {
277
+ throw new Error("Scene or Template entities map cannot be empty.");
278
+ }
279
+ // Reconcile parent <-> children edits when one side was updated by an Agent or tool.
280
+ for (const [parentId, entity] of map) {
281
+ const baseParent = isPlainObject(baseEntities?.[parentId])
282
+ ? baseEntities[parentId]
283
+ : null;
284
+ const baseChildren = new Set(Array.isArray(baseParent?.children)
285
+ ? baseParent.children.filter((item) => typeof item === "string")
286
+ : []);
287
+ const children = entity.children;
288
+ for (const childId of children) {
289
+ const child = map.get(childId);
290
+ if (!child)
291
+ continue;
292
+ const baseChild = isPlainObject(baseEntities?.[childId])
293
+ ? baseEntities[childId]
294
+ : null;
295
+ const baseChildParent = typeof baseChild?.parent === "string" ? baseChild.parent : null;
296
+ const childParentChanged = baseChild !== null && child.parent !== baseChildParent;
297
+ if (!childParentChanged && !baseChildren.has(childId) && child.parent !== parentId) {
298
+ child.parent = parentId;
299
+ }
300
+ }
301
+ }
302
+ // Filter children lists to existing entities whose parent actually points to parentId.
303
+ for (const [parentId, entity] of map) {
304
+ entity.children = entity.children.filter((childId) => {
305
+ const child = map.get(childId);
306
+ return Boolean(child && child.parent === parentId);
307
+ });
308
+ }
309
+ // Ensure every non-root entity appears in its declared parent's children list.
310
+ const roots = [];
311
+ for (const [id, entity] of map) {
312
+ const parentId = entity.parent;
313
+ if (parentId === null) {
314
+ roots.push(id);
315
+ continue;
316
+ }
317
+ const parent = map.get(parentId);
318
+ if (!parent) {
319
+ throw new Error(`Entity ${id} references missing parent ${parentId}.`);
320
+ }
321
+ const list = parent.children;
322
+ if (!list.includes(id))
323
+ list.push(id);
324
+ }
325
+ if (roots.length !== 1) {
326
+ throw new Error(`Expected exactly 1 root entity, found ${roots.length}.`);
327
+ }
328
+ // Verify acyclic reachability of all entities from the single root.
329
+ const visited = new Set();
330
+ const activeStack = new Set();
331
+ const walk = (id) => {
332
+ if (activeStack.has(id)) {
333
+ throw new Error(`Entity hierarchy cycle detected at ${id}.`);
334
+ }
335
+ if (visited.has(id))
336
+ return;
337
+ activeStack.add(id);
338
+ visited.add(id);
339
+ const entity = map.get(id);
340
+ for (const childId of entity.children) {
341
+ walk(childId);
342
+ }
343
+ activeStack.delete(id);
344
+ };
345
+ walk(roots[0]);
346
+ if (visited.size !== map.size) {
347
+ throw new Error("Entity hierarchy contains unreachable/cyclic entities.");
348
+ }
349
+ return orderEntitiesDfs(Object.fromEntries(map));
350
+ }
351
+ export function buildSceneProjection(input) {
352
+ const settings = isPlainObject(input.settings)
353
+ ? canonicalizeValue(input.settings)
354
+ : {};
355
+ const entities = isPlainObject(input.entities)
356
+ ? orderEntitiesDfs(input.entities)
357
+ : {};
358
+ const doc = {
359
+ name: input.name || `Scene ${input.id}`,
360
+ settings,
361
+ entities,
362
+ };
363
+ const active = input.active !== false;
364
+ const header = {
365
+ id: String(input.id),
366
+ kind: "scene",
367
+ active,
368
+ ...(active ? {} : { readonly: true }),
369
+ };
370
+ const json = {
371
+ $pcbridge: header,
372
+ name: doc.name,
373
+ settings: doc.settings,
374
+ entities: doc.entities,
375
+ };
376
+ return { doc, json, text: canonicalStringify(json) };
377
+ }
378
+ export function parseSceneProjection(rawText, fallback, baseEntities) {
379
+ const parsed = JSON.parse(rawText);
380
+ if (!isPlainObject(parsed)) {
381
+ throw new Error("Scene projection must be a JSON object.");
382
+ }
383
+ const header = isPlainObject(parsed.$pcbridge) ? parsed.$pcbridge : null;
384
+ const embeddedId = header && (typeof header.id === "string" || typeof header.id === "number")
385
+ ? String(header.id)
386
+ : fallback.id;
387
+ if (!isPlainObject(parsed.entities)) {
388
+ throw new Error("Scene projection must contain an entities object.");
389
+ }
390
+ const name = typeof parsed.name === "string" && parsed.name.trim()
391
+ ? parsed.name.trim()
392
+ : fallback.name;
393
+ const settings = isPlainObject(parsed.settings)
394
+ ? canonicalizeValue(parsed.settings)
395
+ : {};
396
+ const entities = reconcileEntityHierarchy(parsed.entities, baseEntities);
397
+ return {
398
+ embeddedId,
399
+ doc: {
400
+ name,
401
+ settings,
402
+ entities,
403
+ },
404
+ };
405
+ }
406
+ function jsonEqual(a, b) {
407
+ if (a === b)
408
+ return true;
409
+ if (a === undefined || b === undefined)
410
+ return false;
411
+ return JSON.stringify(a) === JSON.stringify(b);
412
+ }
413
+ function isMergeContainer(value) {
414
+ if (!value || typeof value !== "object" || Array.isArray(value))
415
+ return false;
416
+ const keys = Object.keys(value);
417
+ // If any child key contains '.', Observer dot-paths cannot address deeper children individually.
418
+ if (keys.some((key) => key.includes(".")))
419
+ return false;
420
+ return keys.length > 0;
421
+ }
422
+ function mergeObjectTree(base, local, remote, pathPrefix, conflicts) {
423
+ if (jsonEqual(local, remote))
424
+ return local;
425
+ if (jsonEqual(local, base))
426
+ return remote;
427
+ if (jsonEqual(remote, base))
428
+ return local;
429
+ const baseObj = isMergeContainer(base) ? base : null;
430
+ const localObj = isMergeContainer(local) ? local : null;
431
+ const remoteObj = isMergeContainer(remote) ? remote : null;
432
+ const allObjectsOrEmpty = (base === undefined || (base !== null && typeof base === "object" && !Array.isArray(base))) &&
433
+ local !== undefined && local !== null && typeof local === "object" && !Array.isArray(local) &&
434
+ remote !== undefined && remote !== null && typeof remote === "object" && !Array.isArray(remote);
435
+ const hasDottedKeys = (allObjectsOrEmpty && Object.keys(local).some((k) => k.includes("."))) ||
436
+ (allObjectsOrEmpty && Object.keys(remote).some((k) => k.includes("."))) ||
437
+ (baseObj && Object.keys(baseObj).some((k) => k.includes(".")));
438
+ if (allObjectsOrEmpty && !hasDottedKeys && (baseObj || localObj || remoteObj)) {
439
+ const b = base || {};
440
+ const l = local;
441
+ const r = remote;
442
+ const keys = [...new Set([...Object.keys(b), ...Object.keys(l), ...Object.keys(r)])].sort();
443
+ const merged = {};
444
+ for (const key of keys) {
445
+ const childPath = pathPrefix ? `${pathPrefix}.${key}` : key;
446
+ const hasB = Object.prototype.hasOwnProperty.call(b, key);
447
+ const hasL = Object.prototype.hasOwnProperty.call(l, key);
448
+ const hasR = Object.prototype.hasOwnProperty.call(r, key);
449
+ const next = mergeObjectTree(hasB ? b[key] : undefined, hasL ? l[key] : undefined, hasR ? r[key] : undefined, childPath, conflicts);
450
+ if (next !== undefined)
451
+ merged[key] = next;
452
+ }
453
+ return merged;
454
+ }
455
+ conflicts.push(pathPrefix || "$root");
456
+ return remote;
457
+ }
458
+ function mergeChildrenOrder(baseChildren, localChildren, remoteChildren, survivingIds, expectedParentId, mergedParentOf, conflictPath, conflicts) {
459
+ const validForParent = (id) => survivingIds.has(id) && mergedParentOf.get(id) === expectedParentId;
460
+ const baseFiltered = baseChildren.filter(validForParent);
461
+ const localFiltered = localChildren.filter(validForParent);
462
+ const remoteFiltered = remoteChildren.filter(validForParent);
463
+ const commonSurviving = baseFiltered.filter((id) => localFiltered.includes(id) && remoteFiltered.includes(id));
464
+ const localCommonOrder = localFiltered.filter((id) => commonSurviving.includes(id));
465
+ const remoteCommonOrder = remoteFiltered.filter((id) => commonSurviving.includes(id));
466
+ const localReordered = !jsonEqual(localCommonOrder, commonSurviving);
467
+ const remoteReordered = !jsonEqual(remoteCommonOrder, commonSurviving);
468
+ if (localReordered && remoteReordered && !jsonEqual(localCommonOrder, remoteCommonOrder)) {
469
+ conflicts.push(conflictPath);
470
+ }
471
+ const result = [];
472
+ const push = (id) => {
473
+ if (validForParent(id) && !result.includes(id))
474
+ result.push(id);
475
+ };
476
+ if (localReordered && !remoteReordered) {
477
+ for (const id of localFiltered)
478
+ push(id);
479
+ for (const id of remoteFiltered)
480
+ push(id);
481
+ }
482
+ else {
483
+ for (const id of remoteFiltered)
484
+ push(id);
485
+ for (const id of localFiltered)
486
+ push(id);
487
+ }
488
+ for (const [id, parentId] of mergedParentOf) {
489
+ if (parentId === expectedParentId)
490
+ push(id);
491
+ }
492
+ return result;
493
+ }
494
+ function mergeEntitiesMap(baseEntities, localEntities, remoteEntities, pathPrefix, conflicts) {
495
+ const allIds = [
496
+ ...new Set([
497
+ ...Object.keys(baseEntities),
498
+ ...Object.keys(localEntities),
499
+ ...Object.keys(remoteEntities),
500
+ ]),
501
+ ];
502
+ const rawMerged = new Map();
503
+ for (const id of allIds) {
504
+ const b = isPlainObject(baseEntities[id]) ? baseEntities[id] : undefined;
505
+ const l = isPlainObject(localEntities[id]) ? localEntities[id] : undefined;
506
+ const r = isPlainObject(remoteEntities[id]) ? remoteEntities[id] : undefined;
507
+ const entityPath = `${pathPrefix}.${id}`;
508
+ if (!b) {
509
+ if (l && !r) {
510
+ rawMerged.set(id, structuredClone(l));
511
+ }
512
+ else if (!l && r) {
513
+ rawMerged.set(id, structuredClone(r));
514
+ }
515
+ else if (l && r) {
516
+ if (!jsonEqual(l, r))
517
+ conflicts.push(entityPath);
518
+ rawMerged.set(id, structuredClone(r));
519
+ }
520
+ continue;
521
+ }
522
+ if (!l && !r)
523
+ continue;
524
+ if (!l && r) {
525
+ // Ignore mere child-array mutations caused by unrelated sibling additions when checking if entity was modified.
526
+ const bNoChildren = { ...b, children: [] };
527
+ const rNoChildren = { ...r, children: [] };
528
+ if (!jsonEqual(bNoChildren, rNoChildren)) {
529
+ conflicts.push(entityPath);
530
+ rawMerged.set(id, structuredClone(r));
531
+ }
532
+ continue;
533
+ }
534
+ if (l && !r) {
535
+ const bNoChildren = { ...b, children: [] };
536
+ const lNoChildren = { ...l, children: [] };
537
+ if (!jsonEqual(bNoChildren, lNoChildren)) {
538
+ conflicts.push(entityPath);
539
+ rawMerged.set(id, structuredClone(l));
540
+ }
541
+ continue;
542
+ }
543
+ // Present in base, local, and remote: merge all fields except `children` first.
544
+ const bRest = { ...b };
545
+ const lRest = { ...l };
546
+ const rRest = { ...r };
547
+ delete bRest.children;
548
+ delete lRest.children;
549
+ delete rRest.children;
550
+ const mergedFields = mergeObjectTree(bRest, lRest, rRest, entityPath, conflicts);
551
+ mergedFields.children = [];
552
+ rawMerged.set(id, mergedFields);
553
+ }
554
+ const survivingIds = new Set(rawMerged.keys());
555
+ const mergedParentOf = new Map();
556
+ for (const [id, entity] of rawMerged) {
557
+ const parent = typeof entity.parent === "string" ? entity.parent : null;
558
+ if (parent !== null && !survivingIds.has(parent)) {
559
+ conflicts.push(`${pathPrefix}.${id}.parent`);
560
+ }
561
+ mergedParentOf.set(id, parent);
562
+ }
563
+ for (const [id, entity] of rawMerged) {
564
+ const bChildren = Array.isArray(baseEntities[id]?.children)
565
+ ? baseEntities[id].children
566
+ : [];
567
+ const lChildren = Array.isArray(localEntities[id]?.children)
568
+ ? localEntities[id].children
569
+ : [];
570
+ const rChildren = Array.isArray(remoteEntities[id]?.children)
571
+ ? remoteEntities[id].children
572
+ : [];
573
+ entity.children = mergeChildrenOrder(bChildren, lChildren, Object.prototype.hasOwnProperty.call(remoteEntities, id) ? rChildren : [], survivingIds, id, mergedParentOf, `${pathPrefix}.${id}.children`, conflicts);
574
+ }
575
+ if (!conflicts.length) {
576
+ try {
577
+ return reconcileEntityHierarchy(Object.fromEntries(rawMerged));
578
+ }
579
+ catch (error) {
580
+ conflicts.push(`${pathPrefix}.$hierarchy(${error instanceof Error ? error.message : String(error)})`);
581
+ }
582
+ }
583
+ return orderEntitiesDfs(Object.fromEntries(rawMerged));
584
+ }
585
+ export function threeWayMergeAssetJson(type, base, local, remote) {
586
+ const conflicts = [];
587
+ const name = mergeObjectTree(base.name, local.name, remote.name, "name", conflicts);
588
+ const preload = mergeObjectTree(base.preload, local.preload, remote.preload, "preload", conflicts);
589
+ const tags = mergeObjectTree(base.tags, local.tags, remote.tags, "tags", conflicts);
590
+ let data;
591
+ if (type === "template" &&
592
+ isPlainObject(base.data.entities) &&
593
+ isPlainObject(local.data.entities) &&
594
+ isPlainObject(remote.data.entities)) {
595
+ const bRest = { ...base.data };
596
+ const lRest = { ...local.data };
597
+ const rRest = { ...remote.data };
598
+ delete bRest.entities;
599
+ delete lRest.entities;
600
+ delete rRest.entities;
601
+ data = mergeObjectTree(bRest, lRest, rRest, "data", conflicts) || {};
602
+ data.entities = mergeEntitiesMap(base.data.entities, local.data.entities, remote.data.entities, "data.entities", conflicts);
603
+ }
604
+ else {
605
+ data = mergeObjectTree(base.data, local.data, remote.data, "data", conflicts) || {};
606
+ }
607
+ return {
608
+ merged: {
609
+ name,
610
+ preload,
611
+ tags,
612
+ data: canonicalizeAssetData(type, data),
613
+ },
614
+ conflicts,
615
+ };
616
+ }
617
+ export function threeWayMergeSceneJson(base, local, remote) {
618
+ const conflicts = [];
619
+ const name = mergeObjectTree(base.name, local.name, remote.name, "name", conflicts);
620
+ const settings = mergeObjectTree(base.settings, local.settings, remote.settings, "settings", conflicts) || {};
621
+ const entities = mergeEntitiesMap(base.entities, local.entities, remote.entities, "entities", conflicts);
622
+ return {
623
+ merged: { name, settings, entities },
624
+ conflicts,
625
+ };
626
+ }
627
+ export function diffObjectPaths(current, target, prefix = "") {
628
+ const sets = [];
629
+ const unsets = [];
630
+ const walk = (cur, tgt, basePrefix) => {
631
+ const curKeys = Object.keys(cur);
632
+ const tgtKeys = Object.keys(tgt);
633
+ if (curKeys.some((k) => k.includes(".")) || tgtKeys.some((k) => k.includes("."))) {
634
+ if (!jsonEqual(cur, tgt) && basePrefix) {
635
+ sets.push({ path: basePrefix, value: tgt });
636
+ }
637
+ return;
638
+ }
639
+ for (const key of curKeys) {
640
+ if (!Object.prototype.hasOwnProperty.call(tgt, key)) {
641
+ const path = basePrefix ? `${basePrefix}.${key}` : key;
642
+ unsets.push(path);
643
+ }
644
+ }
645
+ for (const key of tgtKeys) {
646
+ const path = basePrefix ? `${basePrefix}.${key}` : key;
647
+ if (!Object.prototype.hasOwnProperty.call(cur, key)) {
648
+ sets.push({ path, value: tgt[key] });
649
+ continue;
650
+ }
651
+ const curVal = cur[key];
652
+ const tgtVal = tgt[key];
653
+ if (jsonEqual(curVal, tgtVal))
654
+ continue;
655
+ if (curVal && typeof curVal === "object" && !Array.isArray(curVal) &&
656
+ tgtVal && typeof tgtVal === "object" && !Array.isArray(tgtVal)) {
657
+ const curChildKeys = Object.keys(curVal);
658
+ const tgtChildKeys = Object.keys(tgtVal);
659
+ if ((curChildKeys.length === 0 && tgtChildKeys.length === 0) ||
660
+ curChildKeys.some((k) => k.includes(".")) ||
661
+ tgtChildKeys.some((k) => k.includes("."))) {
662
+ sets.push({ path, value: tgtVal });
663
+ }
664
+ else {
665
+ walk(curVal, tgtVal, path);
666
+ }
667
+ }
668
+ else {
669
+ sets.push({ path, value: tgtVal });
670
+ }
671
+ }
672
+ };
673
+ walk(current, target, prefix);
674
+ return { sets, unsets };
675
+ }
676
+ export function diffAssetPatchOps(current, target) {
677
+ const dataOps = diffObjectPaths(current.data, target.data);
678
+ const nameChanged = current.name !== target.name;
679
+ const preloadChanged = current.preload !== target.preload;
680
+ const tagsChanged = !jsonEqual(current.tags, target.tags);
681
+ if (!nameChanged && !preloadChanged && !tagsChanged && !dataOps.sets.length && !dataOps.unsets.length) {
682
+ return null;
683
+ }
684
+ const patch = {
685
+ sets: dataOps.sets,
686
+ unsets: dataOps.unsets,
687
+ };
688
+ if (nameChanged)
689
+ patch.name = target.name;
690
+ if (preloadChanged)
691
+ patch.preload = target.preload;
692
+ if (tagsChanged)
693
+ patch.tags = target.tags;
694
+ return patch;
695
+ }
696
+ export function diffScenePatchOps(current, target) {
697
+ const nameChanged = current.name !== target.name;
698
+ const settingsDiff = diffObjectPaths(current.settings, target.settings);
699
+ const curEntities = current.entities;
700
+ const tgtEntities = target.entities;
701
+ const createdIds = new Set(Object.keys(tgtEntities).filter((id) => !Object.prototype.hasOwnProperty.call(curEntities, id)));
702
+ const deletedAll = new Set(Object.keys(curEntities).filter((id) => !Object.prototype.hasOwnProperty.call(tgtEntities, id)));
703
+ // Only delete top-most deleted ancestors; PlayCanvas entities.delete cascades to children.
704
+ const deletes = [...deletedAll].filter((id) => {
705
+ const entity = curEntities[id];
706
+ let parent = typeof entity?.parent === "string" ? entity.parent : null;
707
+ while (parent) {
708
+ if (deletedAll.has(parent))
709
+ return false;
710
+ const parentEntity = curEntities[parent];
711
+ parent = typeof parentEntity?.parent === "string" ? parentEntity.parent : null;
712
+ }
713
+ return true;
714
+ });
715
+ // Because orderEntitiesDfs visits parents before children, iterating Object.keys(tgtEntities)
716
+ // naturally yields created entities in topological parent-before-child order.
717
+ const creates = [];
718
+ for (const id of Object.keys(tgtEntities)) {
719
+ if (!createdIds.has(id))
720
+ continue;
721
+ const entity = structuredClone(tgtEntities[id]);
722
+ const parentId = typeof entity.parent === "string" ? entity.parent : null;
723
+ const parent = parentId ? tgtEntities[parentId] : undefined;
724
+ const siblings = Array.isArray(parent?.children) ? parent.children : [];
725
+ const index = siblings.indexOf(id);
726
+ entity.children = [];
727
+ creates.push({ entity, ...(index >= 0 ? { index } : {}) });
728
+ }
729
+ const reparents = [];
730
+ const updates = [];
731
+ for (const id of Object.keys(tgtEntities)) {
732
+ if (createdIds.has(id))
733
+ continue;
734
+ const cur = curEntities[id];
735
+ const tgt = tgtEntities[id];
736
+ const curParent = typeof cur.parent === "string" ? cur.parent : null;
737
+ const tgtParent = typeof tgt.parent === "string" ? tgt.parent : null;
738
+ if (tgtParent !== null) {
739
+ const tgtParentObj = tgtEntities[tgtParent];
740
+ const tgtSiblings = Array.isArray(tgtParentObj?.children) ? tgtParentObj.children : [];
741
+ const tgtIndex = tgtSiblings.indexOf(id);
742
+ if (curParent !== tgtParent) {
743
+ reparents.push({ id, parent: tgtParent, index: Math.max(0, tgtIndex) });
744
+ }
745
+ else {
746
+ const curParentObj = curEntities[curParent];
747
+ const curSiblings = (Array.isArray(curParentObj?.children) ? curParentObj.children : [])
748
+ .filter((childId) => !deletedAll.has(childId));
749
+ const existingTgtSiblings = tgtSiblings.filter((childId) => !createdIds.has(childId) && curEntities[childId] && curEntities[childId].parent === tgtParent);
750
+ if (curSiblings.indexOf(id) !== existingTgtSiblings.indexOf(id)) {
751
+ reparents.push({ id, parent: tgtParent, index: Math.max(0, tgtIndex) });
752
+ }
753
+ }
754
+ }
755
+ const sets = [];
756
+ const unsets = [];
757
+ for (const field of ["name", "enabled", "tags", "position", "rotation", "scale", "template_id", "template_ent_ids"]) {
758
+ const hasCur = Object.prototype.hasOwnProperty.call(cur, field);
759
+ const hasTgt = Object.prototype.hasOwnProperty.call(tgt, field);
760
+ if (hasCur && !hasTgt)
761
+ unsets.push(field);
762
+ else if (hasTgt && !jsonEqual(cur[field], tgt[field]))
763
+ sets.push({ path: field, value: tgt[field] });
764
+ }
765
+ const curComps = isPlainObject(cur.components) ? cur.components : {};
766
+ const tgtComps = isPlainObject(tgt.components) ? tgt.components : {};
767
+ const addedComponents = {};
768
+ const removedComponents = [];
769
+ for (const comp of Object.keys(curComps)) {
770
+ if (!Object.prototype.hasOwnProperty.call(tgtComps, comp)) {
771
+ removedComponents.push(comp);
772
+ }
773
+ }
774
+ for (const comp of Object.keys(tgtComps)) {
775
+ if (!Object.prototype.hasOwnProperty.call(curComps, comp)) {
776
+ addedComponents[comp] = tgtComps[comp];
777
+ continue;
778
+ }
779
+ const curCompVal = curComps[comp];
780
+ const tgtCompVal = tgtComps[comp];
781
+ if (isPlainObject(curCompVal) && isPlainObject(tgtCompVal)) {
782
+ const compDiff = diffObjectPaths(curCompVal, tgtCompVal, `components.${comp}`);
783
+ sets.push(...compDiff.sets);
784
+ unsets.push(...compDiff.unsets);
785
+ }
786
+ else if (!jsonEqual(curCompVal, tgtCompVal)) {
787
+ sets.push({ path: `components.${comp}`, value: tgtCompVal });
788
+ }
789
+ }
790
+ if (Object.keys(addedComponents).length ||
791
+ removedComponents.length ||
792
+ sets.length ||
793
+ unsets.length) {
794
+ updates.push({
795
+ id,
796
+ addedComponents,
797
+ removedComponents,
798
+ sets,
799
+ unsets,
800
+ });
801
+ }
802
+ }
803
+ if (!nameChanged &&
804
+ !creates.length &&
805
+ !reparents.length &&
806
+ !updates.length &&
807
+ !deletes.length &&
808
+ !settingsDiff.sets.length &&
809
+ !settingsDiff.unsets.length) {
810
+ return null;
811
+ }
812
+ return {
813
+ ...(nameChanged ? { name: target.name } : {}),
814
+ creates,
815
+ reparents,
816
+ updates,
817
+ deletes,
818
+ settingsSets: settingsDiff.sets,
819
+ settingsUnsets: settingsDiff.unsets,
820
+ };
821
+ }