playcanvas-agent-bridge-cli 0.2.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,613 @@
1
+ export const entityReader = `
2
+ function readEntity(entity) {
3
+ const get = (path) => {
4
+ try {
5
+ return entity.get(path);
6
+ } catch {
7
+ return undefined;
8
+ }
9
+ };
10
+ const components = get("components") || {};
11
+ return {
12
+ resource_id: get("resource_id"),
13
+ name: get("name"),
14
+ parent: get("parent"),
15
+ enabled: get("enabled"),
16
+ position: get("position"),
17
+ rotation: get("rotation"),
18
+ scale: get("scale"),
19
+ tags: get("tags") || [],
20
+ components: Object.keys(components || {})
21
+ };
22
+ }
23
+ `;
24
+ export const assetReader = `
25
+ function readAsset(asset) {
26
+ const get = (path) => {
27
+ try {
28
+ return asset.get(path);
29
+ } catch {
30
+ return undefined;
31
+ }
32
+ };
33
+ const path = get("path") || [];
34
+ return {
35
+ id: get("id"),
36
+ name: get("name"),
37
+ type: get("type"),
38
+ path,
39
+ folder: Array.isArray(path) && path.length ? path[path.length - 1] : null,
40
+ tags: get("tags") || [],
41
+ file: get("file") || null
42
+ };
43
+ }
44
+ `;
45
+ export const assetFolderHelpers = `
46
+ function splitAssetPath(path) {
47
+ if (Array.isArray(path)) return path.map(String).map((part) => part.trim()).filter(Boolean);
48
+ return String(path || "")
49
+ .split("/")
50
+ .map((part) => part.trim())
51
+ .filter(Boolean);
52
+ }
53
+
54
+ function isChildFolder(asset, name, parent) {
55
+ if (!asset || asset.get("type") !== "folder" || asset.get("name") !== name) return false;
56
+ const path = asset.get("path") || [];
57
+ if (!parent) return path.length === 0;
58
+ return path[path.length - 1] === parent.get("id");
59
+ }
60
+
61
+ async function ensureFolderPath(assets, path) {
62
+ const created = [];
63
+ let parent = null;
64
+ for (const name of splitAssetPath(path)) {
65
+ let folder = assets.list().find((asset) => isChildFolder(asset, name, parent));
66
+ if (!folder) {
67
+ folder = await assets.createFolder({ name, folder: parent || undefined });
68
+ created.push(folder);
69
+ }
70
+ parent = folder;
71
+ }
72
+ return { folder: parent, created };
73
+ }
74
+
75
+ async function resolveFolder(assets, args) {
76
+ if (args.folderId !== undefined && args.folderId !== null && args.folderId !== "") {
77
+ const folder = assets.get(Number(args.folderId));
78
+ if (!folder || folder.get("type") !== "folder") {
79
+ throw new Error("Folder asset not found: " + args.folderId);
80
+ }
81
+ return { folder, created: [] };
82
+ }
83
+ if (args.folder) {
84
+ return ensureFolderPath(assets, args.folder);
85
+ }
86
+ return { folder: null, created: [] };
87
+ }
88
+
89
+ function bytesFromBase64(base64) {
90
+ const binary = atob(base64);
91
+ const bytes = new Uint8Array(binary.length);
92
+ for (let index = 0; index < binary.length; index += 1) {
93
+ bytes[index] = binary.charCodeAt(index);
94
+ }
95
+ return bytes;
96
+ }
97
+ `;
98
+ export function entityListSnippet() {
99
+ return `
100
+ ${entityReader}
101
+ const args = command.args || {};
102
+ const entities = editor.api.globals.entities;
103
+ let items = entities.list();
104
+ if (args.name) {
105
+ const needle = String(args.name).toLowerCase();
106
+ items = items.filter((entity) => String(entity.get("name") || "").toLowerCase().includes(needle));
107
+ }
108
+ if (args.component) {
109
+ items = items.filter((entity) => Boolean(entity.get("components." + args.component)));
110
+ }
111
+ const total = items.length;
112
+ const offset = Math.max(0, Number(args.offset || 0));
113
+ const limit = Math.max(1, Math.min(Number(args.limit || 50), 500));
114
+ const page = items.slice(offset, offset + limit);
115
+ return {
116
+ items: args.full ? page.map((entity) => entity.json()) : page.map(readEntity),
117
+ total,
118
+ offset,
119
+ limit,
120
+ hasMore: offset + page.length < total
121
+ };
122
+ `;
123
+ }
124
+ export function entityGetSnippet() {
125
+ return `
126
+ ${entityReader}
127
+ const args = command.args || {};
128
+ const entity = editor.api.globals.entities.get(args.id);
129
+ if (!entity) {
130
+ throw new Error("Entity not found: " + args.id);
131
+ }
132
+ return args.full ? entity.jsonHierarchy() : readEntity(entity);
133
+ `;
134
+ }
135
+ export function entityCreateSnippet() {
136
+ return `
137
+ ${entityReader}
138
+ const args = command.args || {};
139
+ const entities = editor.api.globals.entities;
140
+ const data = { ...(args.data || {}) };
141
+ if (!data.parent) {
142
+ data.parent = entities.root;
143
+ } else if (typeof data.parent === "string") {
144
+ const parent = entities.get(data.parent);
145
+ if (!parent) {
146
+ throw new Error("Parent entity not found: " + data.parent);
147
+ }
148
+ data.parent = parent;
149
+ }
150
+ data.position = data.position || [0, 0, 0];
151
+ data.rotation = data.rotation || [0, 0, 0];
152
+ data.scale = data.scale || [1, 1, 1];
153
+ data.enabled = data.enabled !== false;
154
+ data.components = data.components || {};
155
+ data.children = data.children || [];
156
+ data.tags = data.tags || [];
157
+ const entity = entities.create(data, { history: true, select: true });
158
+ if (!entity) {
159
+ throw new Error("PlayCanvas did not return a created entity.");
160
+ }
161
+ return readEntity(entity);
162
+ `;
163
+ }
164
+ export function entityPatchSnippet() {
165
+ return `
166
+ ${entityReader}
167
+ const args = command.args || {};
168
+ const entity = editor.api.globals.entities.get(args.id);
169
+ if (!entity) {
170
+ throw new Error("Entity not found: " + args.id);
171
+ }
172
+ for (const change of args.sets || []) {
173
+ entity.set(change.path, change.value);
174
+ }
175
+ return readEntity(entity);
176
+ `;
177
+ }
178
+ export function entityDeleteSnippet() {
179
+ return `
180
+ const args = command.args || {};
181
+ const entities = editor.api.globals.entities;
182
+ const ids = Array.isArray(args.ids) && args.ids.length ? args.ids : [args.id];
183
+ const found = [];
184
+ const missing = [];
185
+ for (const id of ids) {
186
+ const entity = entities.get(id);
187
+ if (entity) found.push(entity);
188
+ else missing.push(id);
189
+ }
190
+ if (!found.length) {
191
+ return { affected: 0, deleted: [], missing };
192
+ }
193
+ await entities.delete(found, { history: true });
194
+ return {
195
+ affected: found.length,
196
+ deleted: found.map((entity) => ({
197
+ resource_id: entity.get("resource_id"),
198
+ name: entity.get("name")
199
+ })),
200
+ missing
201
+ };
202
+ `;
203
+ }
204
+ export function entityAddComponentSnippet() {
205
+ return `
206
+ ${entityReader}
207
+ const args = command.args || {};
208
+ const entity = editor.api.globals.entities.get(args.id);
209
+ if (!entity) {
210
+ throw new Error("Entity not found: " + args.id);
211
+ }
212
+ if (!args.component) {
213
+ throw new Error("component is required.");
214
+ }
215
+ entity.addComponent(args.component, args.data || {});
216
+ return readEntity(entity);
217
+ `;
218
+ }
219
+ export function entityRemoveComponentSnippet() {
220
+ return `
221
+ ${entityReader}
222
+ const args = command.args || {};
223
+ const entity = editor.api.globals.entities.get(args.id);
224
+ if (!entity) {
225
+ throw new Error("Entity not found: " + args.id);
226
+ }
227
+ if (!args.component) {
228
+ throw new Error("component is required.");
229
+ }
230
+ if (entity.get("components." + args.component)) {
231
+ entity.removeComponent(args.component);
232
+ return { affected: 1, entity: readEntity(entity) };
233
+ }
234
+ return { affected: 0, entity: readEntity(entity) };
235
+ `;
236
+ }
237
+ export function entitySetMaterialSnippet() {
238
+ return `
239
+ ${entityReader}
240
+ ${assetReader}
241
+ const args = command.args || {};
242
+ const globals = editor.api.globals;
243
+ const entity = globals.entities.get(args.id);
244
+ if (!entity) {
245
+ throw new Error("Entity not found: " + args.id);
246
+ }
247
+ const material = globals.assets.get(Number(args.materialId));
248
+ if (!material || material.get("type") !== "material") {
249
+ throw new Error("Material asset not found: " + args.materialId);
250
+ }
251
+ if (!entity.get("components.render")) {
252
+ entity.addComponent("render", { type: args.renderType || "box" });
253
+ }
254
+ const slot = Math.max(0, Number(args.slot || 0));
255
+ const materialAssets = entity.get("components.render.materialAssets") || [];
256
+ while (materialAssets.length <= slot) {
257
+ materialAssets.push(null);
258
+ }
259
+ materialAssets[slot] = material.get("id");
260
+ entity.set("components.render.materialAssets", materialAssets);
261
+ return {
262
+ entity: readEntity(entity),
263
+ material: readAsset(material),
264
+ slot,
265
+ materialAssets
266
+ };
267
+ `;
268
+ }
269
+ export function entityAddScriptSnippet() {
270
+ return `
271
+ ${entityReader}
272
+ ${assetReader}
273
+ const args = command.args || {};
274
+ const globals = editor.api.globals;
275
+ const entity = globals.entities.get(args.id);
276
+ if (!entity) {
277
+ throw new Error("Entity not found: " + args.id);
278
+ }
279
+ let scriptName = args.scriptName;
280
+ let scriptAsset = null;
281
+ if (!scriptName && args.assetId !== undefined && args.assetId !== null) {
282
+ scriptAsset = globals.assets.get(Number(args.assetId));
283
+ if (!scriptAsset || scriptAsset.get("type") !== "script") {
284
+ throw new Error("Script asset not found: " + args.assetId);
285
+ }
286
+ const scripts = Object.keys(scriptAsset.get("data.scripts") || {});
287
+ if (scripts.length !== 1) {
288
+ throw new Error("Use --script-name when the script asset has zero or multiple script definitions.");
289
+ }
290
+ scriptName = scripts[0];
291
+ }
292
+ if (!scriptName) {
293
+ throw new Error("scriptName is required.");
294
+ }
295
+ if (!entity.get("components.script")) {
296
+ entity.addComponent("script", { enabled: true, order: [], scripts: {} });
297
+ }
298
+ const attributes = args.attributes || {};
299
+ const existing = entity.get("components.script.scripts." + scriptName);
300
+ if (existing) {
301
+ entity.set("components.script.scripts." + scriptName + ".enabled", args.enabled !== false);
302
+ entity.set("components.script.scripts." + scriptName + ".attributes", {
303
+ ...(existing.attributes || {}),
304
+ ...attributes
305
+ });
306
+ } else {
307
+ entity.addScript(scriptName, {
308
+ attributes,
309
+ history: true
310
+ });
311
+ }
312
+ const order = entity.get("components.script.order") || [];
313
+ if (!order.includes(scriptName)) {
314
+ order.push(scriptName);
315
+ entity.set("components.script.order", order);
316
+ }
317
+ return {
318
+ entity: readEntity(entity),
319
+ scriptName,
320
+ scriptAsset: scriptAsset ? readAsset(scriptAsset) : null,
321
+ script: entity.get("components.script.scripts." + scriptName)
322
+ };
323
+ `;
324
+ }
325
+ export function assetListSnippet() {
326
+ return `
327
+ ${assetReader}
328
+ const args = command.args || {};
329
+ const assets = editor.api.globals.assets;
330
+ let items = assets.list();
331
+ if (args.type) {
332
+ items = items.filter((asset) => asset.get("type") === args.type);
333
+ }
334
+ if (args.name) {
335
+ const needle = String(args.name).toLowerCase();
336
+ items = items.filter((asset) => String(asset.get("name") || "").toLowerCase().includes(needle));
337
+ }
338
+ const total = items.length;
339
+ const offset = Math.max(0, Number(args.offset || 0));
340
+ const limit = Math.max(1, Math.min(Number(args.limit || 50), 500));
341
+ const page = items.slice(offset, offset + limit);
342
+ return {
343
+ items: args.full ? page.map((asset) => asset.json()) : page.map(readAsset),
344
+ total,
345
+ offset,
346
+ limit,
347
+ hasMore: offset + page.length < total
348
+ };
349
+ `;
350
+ }
351
+ export function assetGetSnippet() {
352
+ return `
353
+ ${assetReader}
354
+ const args = command.args || {};
355
+ const asset = editor.api.globals.assets.get(Number(args.id));
356
+ if (!asset) {
357
+ throw new Error("Asset not found: " + args.id);
358
+ }
359
+ return args.full ? asset.json() : readAsset(asset);
360
+ `;
361
+ }
362
+ export function assetFolderEnsureSnippet() {
363
+ return `
364
+ ${assetReader}
365
+ ${assetFolderHelpers}
366
+ const args = command.args || {};
367
+ if (!args.path) {
368
+ throw new Error("path is required.");
369
+ }
370
+ const assets = editor.api.globals.assets;
371
+ const result = await ensureFolderPath(assets, args.path);
372
+ return {
373
+ folder: result.folder ? readAsset(result.folder) : null,
374
+ created: result.created.map(readAsset)
375
+ };
376
+ `;
377
+ }
378
+ export function assetUploadSnippet() {
379
+ return `
380
+ ${assetReader}
381
+ ${assetFolderHelpers}
382
+ const args = command.args || {};
383
+ if (!args.base64) {
384
+ throw new Error("base64 file content is required.");
385
+ }
386
+ if (!args.name) {
387
+ throw new Error("name is required.");
388
+ }
389
+ if (!args.type) {
390
+ throw new Error("type is required.");
391
+ }
392
+ const assets = editor.api.globals.assets;
393
+ const folderResult = await resolveFolder(assets, args);
394
+ const blob = new Blob([bytesFromBase64(args.base64)], {
395
+ type: args.mime || "application/octet-stream"
396
+ });
397
+ const asset = await assets.upload({
398
+ name: args.name,
399
+ type: args.type,
400
+ folder: folderResult.folder || undefined,
401
+ filename: args.filename || args.name,
402
+ file: blob,
403
+ preload: args.preload !== false
404
+ }, null);
405
+ return {
406
+ asset: readAsset(asset),
407
+ createdFolders: folderResult.created.map(readAsset)
408
+ };
409
+ `;
410
+ }
411
+ export function assetDeleteSnippet() {
412
+ return `
413
+ ${assetReader}
414
+ const args = command.args || {};
415
+ const assets = editor.api.globals.assets;
416
+ const ids = Array.isArray(args.ids) && args.ids.length ? args.ids : [args.id];
417
+ const found = [];
418
+ const missing = [];
419
+ for (const id of ids) {
420
+ const asset = assets.get(Number(id));
421
+ if (asset) found.push(asset);
422
+ else missing.push(id);
423
+ }
424
+ if (!found.length) {
425
+ return { affected: 0, deleted: [], missing };
426
+ }
427
+ const deleted = found.map(readAsset);
428
+ await assets.delete(found);
429
+ return {
430
+ affected: found.length,
431
+ deleted,
432
+ missing
433
+ };
434
+ `;
435
+ }
436
+ export function materialCreateSnippet() {
437
+ return `
438
+ ${assetReader}
439
+ ${assetFolderHelpers}
440
+ const args = command.args || {};
441
+ if (!args.name) {
442
+ throw new Error("name is required.");
443
+ }
444
+ const assets = editor.api.globals.assets;
445
+ const folderResult = await resolveFolder(assets, args);
446
+ const data = { ...(args.data || {}) };
447
+ if (args.diffuseMap !== undefined && args.diffuseMap !== null) {
448
+ data.diffuseMap = Number(args.diffuseMap);
449
+ }
450
+ if (args.emissiveMap !== undefined && args.emissiveMap !== null) {
451
+ data.emissiveMap = Number(args.emissiveMap);
452
+ }
453
+ if (args.normalMap !== undefined && args.normalMap !== null) {
454
+ data.normalMap = Number(args.normalMap);
455
+ }
456
+ const material = await assets.createMaterial({
457
+ name: args.name,
458
+ folder: folderResult.folder || undefined,
459
+ data,
460
+ preload: args.preload !== false
461
+ });
462
+ for (const [key, value] of Object.entries(data)) {
463
+ material.set("data." + key, value);
464
+ }
465
+ return {
466
+ material: readAsset(material),
467
+ data: {
468
+ diffuseMap: material.get("data.diffuseMap"),
469
+ emissiveMap: material.get("data.emissiveMap"),
470
+ normalMap: material.get("data.normalMap")
471
+ },
472
+ createdFolders: folderResult.created.map(readAsset)
473
+ };
474
+ `;
475
+ }
476
+ export function scriptCreateSnippet() {
477
+ return `
478
+ ${assetReader}
479
+ ${assetFolderHelpers}
480
+ const args = command.args || {};
481
+ if (!args.filename) {
482
+ throw new Error("filename is required.");
483
+ }
484
+ const assets = editor.api.globals.assets;
485
+ const folderResult = await resolveFolder(assets, args);
486
+ const asset = await assets.createScript({
487
+ filename: args.filename,
488
+ text: String(args.text || ""),
489
+ folder: folderResult.folder || undefined,
490
+ preload: args.preload !== false
491
+ });
492
+ return {
493
+ asset: readAsset(asset),
494
+ scripts: asset.get("data.scripts") || {},
495
+ createdFolders: folderResult.created.map(readAsset)
496
+ };
497
+ `;
498
+ }
499
+ export function scriptSetTextSnippet() {
500
+ return `
501
+ ${assetReader}
502
+ const args = command.args || {};
503
+ const globals = editor.api.globals;
504
+ const asset = globals.assets.get(Number(args.assetId));
505
+ if (!asset) {
506
+ throw new Error("Asset not found: " + args.assetId);
507
+ }
508
+ if (asset.get("type") !== "script") {
509
+ throw new Error("Asset is not a script: " + args.assetId);
510
+ }
511
+ const filename = asset.get("file.filename") || asset.get("name");
512
+ const form = new FormData();
513
+ form.append("filename", filename);
514
+ form.append("file", new Blob([String(args.text || "")], { type: "text/javascript" }), filename);
515
+ const branchId = window.config?.self?.branch?.id || window.config?.branch?.id;
516
+ if (branchId) {
517
+ form.append("branchId", String(branchId));
518
+ }
519
+ const headers = {};
520
+ if (globals.accessToken) {
521
+ headers.Authorization = "Bearer " + globals.accessToken;
522
+ }
523
+ const response = await fetch("/api/assets/" + asset.get("id"), {
524
+ method: "PUT",
525
+ headers,
526
+ body: form
527
+ });
528
+ const body = await response.json().catch(() => ({}));
529
+ if (!response.ok || body.error) {
530
+ throw new Error(body.error || "Failed to update script asset.");
531
+ }
532
+ return {
533
+ asset: readAsset(asset),
534
+ response: body
535
+ };
536
+ `;
537
+ }
538
+ export function scriptParseSnippet() {
539
+ return `
540
+ ${assetReader}
541
+ const args = command.args || {};
542
+ const asset = editor.api.globals.assets.get(Number(args.assetId));
543
+ if (!asset) {
544
+ throw new Error("Asset not found: " + args.assetId);
545
+ }
546
+ const [error, data] = await new Promise((resolve) => {
547
+ editor.call("scripts:parse", asset.observer, (...values) => resolve(values));
548
+ });
549
+ if (error) {
550
+ throw new Error(String(error));
551
+ }
552
+ return {
553
+ asset: readAsset(asset),
554
+ scripts: data?.scripts || {}
555
+ };
556
+ `;
557
+ }
558
+ export function viewportCaptureSnippet() {
559
+ return `
560
+ const args = command.args || {};
561
+ const app = editor.call("viewport:app");
562
+ if (!app) {
563
+ throw new Error("Viewport app not found.");
564
+ }
565
+ const device = app.graphicsDevice;
566
+ const gl = device && device.gl;
567
+ if (!gl) {
568
+ throw new Error("WebGL context not found.");
569
+ }
570
+ editor.call("viewport:render");
571
+ app.tick();
572
+ const width = device.width;
573
+ const height = device.height;
574
+ const pixels = new Uint8Array(width * height * 4);
575
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
576
+ gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
577
+ const flipped = new Uint8Array(width * height * 4);
578
+ const rowSize = width * 4;
579
+ for (let y = 0; y < height; y += 1) {
580
+ flipped.set(
581
+ pixels.subarray((height - 1 - y) * rowSize, (height - y) * rowSize),
582
+ y * rowSize
583
+ );
584
+ }
585
+ const srcCanvas = document.createElement("canvas");
586
+ srcCanvas.width = width;
587
+ srcCanvas.height = height;
588
+ srcCanvas.getContext("2d").putImageData(
589
+ new ImageData(new Uint8ClampedArray(flipped.buffer), width, height),
590
+ 0,
591
+ 0
592
+ );
593
+ const maxWidth = Number(args.maxWidth || 1200);
594
+ let outWidth = width;
595
+ let outHeight = height;
596
+ if (maxWidth > 0 && width > maxWidth) {
597
+ outWidth = maxWidth;
598
+ outHeight = Math.round(height * (maxWidth / width));
599
+ }
600
+ const dstCanvas = document.createElement("canvas");
601
+ dstCanvas.width = outWidth;
602
+ dstCanvas.height = outHeight;
603
+ dstCanvas.getContext("2d").drawImage(srcCanvas, 0, 0, outWidth, outHeight);
604
+ const mime = args.format === "webp" ? "image/webp" : "image/png";
605
+ const dataUrl = dstCanvas.toDataURL(mime, Number(args.quality || 0.85));
606
+ return {
607
+ mime,
608
+ width: outWidth,
609
+ height: outHeight,
610
+ base64: dataUrl.split(",")[1]
611
+ };
612
+ `;
613
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "host": "127.0.0.1",
3
+ "port": 17329,
4
+ "token": "generated-by-pcbridge-install-extension"
5
+ }