playcanvas-agent-bridge-cli 0.3.0 → 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.
- package/README.md +182 -58
- package/README.zh-CN.md +175 -58
- package/dist/builder/manager.js +456 -0
- package/dist/cli.js +520 -87
- package/dist/config.js +1 -1
- package/dist/daemon/server.js +180 -6
- package/dist/daemon/target-registry.js +43 -3
- package/dist/shared/protocol.js +3 -1
- package/dist/snippets.js +726 -69
- package/dist/workspace/manager.js +1123 -0
- package/extension/icons/concepts/pcbridge-bridge.png +0 -0
- package/extension/icons/concepts/pcbridge-cube.png +0 -0
- package/extension/icons/concepts/pcbridge-p-active.png +0 -0
- package/extension/icons/concepts/pcbridge-p-arch.png +0 -0
- package/extension/icons/concepts/pcbridge-p-bridge.png +0 -0
- package/extension/icons/concepts/pcbridge-p-emblem.png +0 -0
- package/extension/icons/concepts/pcbridge-signal.png +0 -0
- package/extension/icons/icon-128.png +0 -0
- package/extension/icons/icon-16.png +0 -0
- package/extension/icons/icon-32.png +0 -0
- package/extension/icons/icon-48.png +0 -0
- package/extension/isolated.js +147 -15
- package/extension/main.js +757 -24
- package/extension/manifest.json +14 -2
- package/extension/popup.html +179 -56
- package/extension/popup.js +204 -62
- package/extension/service-worker.js +331 -17
- package/package.json +3 -1
- package/skills/claude/playcanvas-agent-bridge-cli/SKILL.md +93 -28
- package/skills/codex/playcanvas-agent-bridge-cli/SKILL.md +148 -57
- package/skills/cursor/playcanvas-agent-bridge-cli.mdc +56 -24
- package/skills/windsurf/playcanvas-agent-bridge-cli.md +55 -25
|
@@ -0,0 +1,1123 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { copyFile, lstat, mkdir, readFile, readdir, rename, rmdir, stat, writeFile, } from "node:fs/promises";
|
|
4
|
+
import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
5
|
+
const PROJECT_FILE = "pcbridge.project.json";
|
|
6
|
+
const LEGACY_INDEX_FILE = join(".pcbridge", "asset-index.json");
|
|
7
|
+
const LEGACY_INDEX_BACKUP_FILE = join(".pcbridge", "asset-index.v1.json");
|
|
8
|
+
const SYNC_STATE_FILE = join(".pcbridge", "sync-state.json");
|
|
9
|
+
const DEFAULT_REFRESH_INTERVAL_MS = 5000;
|
|
10
|
+
function hashContent(value) {
|
|
11
|
+
return createHash("md5").update(value).digest("hex");
|
|
12
|
+
}
|
|
13
|
+
function hashLegacyContent(value) {
|
|
14
|
+
return createHash("sha256").update(value).digest("hex");
|
|
15
|
+
}
|
|
16
|
+
function toPosixPath(value) {
|
|
17
|
+
return value.replaceAll("\\", "/");
|
|
18
|
+
}
|
|
19
|
+
function manifestLocalPath(value) {
|
|
20
|
+
if (!value)
|
|
21
|
+
return null;
|
|
22
|
+
const parts = value.split("/");
|
|
23
|
+
if (parts[0] !== "assets" || parts.length < 2)
|
|
24
|
+
return null;
|
|
25
|
+
if (parts.some((part) => !part || part === "." || part === ".." || part.includes("\\"))) {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
return join(...parts.slice(1));
|
|
29
|
+
}
|
|
30
|
+
export function safeWorkspaceName(value, fallback) {
|
|
31
|
+
const safe = value
|
|
32
|
+
.normalize("NFKC")
|
|
33
|
+
.replace(/[<>:"/\\|?*\u0000-\u001f]/g, "-")
|
|
34
|
+
.replace(/\s+/g, "-")
|
|
35
|
+
.replace(/-+/g, "-")
|
|
36
|
+
.replace(/^[. -]+|[. -]+$/g, "")
|
|
37
|
+
.slice(0, 80);
|
|
38
|
+
return safe || fallback;
|
|
39
|
+
}
|
|
40
|
+
export function safeAssetName(value, fallback) {
|
|
41
|
+
const safe = value
|
|
42
|
+
.normalize("NFKC")
|
|
43
|
+
.replace(/[<>:"/\\|?*\u0000-\u001f]/g, "-")
|
|
44
|
+
.replace(/[. ]+$/g, "")
|
|
45
|
+
.replace(/^[.]+$/g, "")
|
|
46
|
+
.slice(0, 120);
|
|
47
|
+
return safe || fallback;
|
|
48
|
+
}
|
|
49
|
+
function collisionName(filename, id) {
|
|
50
|
+
const extension = extname(filename);
|
|
51
|
+
const stem = extension ? filename.slice(0, -extension.length) : filename;
|
|
52
|
+
return `${stem}~${id}${extension}`;
|
|
53
|
+
}
|
|
54
|
+
function asObject(value) {
|
|
55
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
56
|
+
throw new Error("Invalid workspace response from PlayCanvas target.");
|
|
57
|
+
}
|
|
58
|
+
return value;
|
|
59
|
+
}
|
|
60
|
+
async function atomicWrite(path, value) {
|
|
61
|
+
await mkdir(dirname(path), { recursive: true });
|
|
62
|
+
const temporary = join(dirname(path), `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
|
|
63
|
+
await writeFile(temporary, value);
|
|
64
|
+
await rename(temporary, path);
|
|
65
|
+
}
|
|
66
|
+
async function readJson(path) {
|
|
67
|
+
try {
|
|
68
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
async function isSymbolicLink(path) {
|
|
75
|
+
try {
|
|
76
|
+
return (await lstat(path)).isSymbolicLink();
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
export class WorkspaceManager {
|
|
83
|
+
rootDir;
|
|
84
|
+
#requestTarget;
|
|
85
|
+
#records = new Map();
|
|
86
|
+
#refreshTimer = null;
|
|
87
|
+
constructor(options) {
|
|
88
|
+
this.rootDir = resolve(options.rootDir);
|
|
89
|
+
this.#requestTarget = options.requestTarget;
|
|
90
|
+
const interval = options.refreshIntervalMs ?? DEFAULT_REFRESH_INTERVAL_MS;
|
|
91
|
+
if (interval > 0) {
|
|
92
|
+
this.#refreshTimer = setInterval(() => {
|
|
93
|
+
for (const record of this.#records.values()) {
|
|
94
|
+
if (record.connected)
|
|
95
|
+
void this.#sync(record, false);
|
|
96
|
+
}
|
|
97
|
+
}, interval);
|
|
98
|
+
this.#refreshTimer.unref();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
async close() {
|
|
102
|
+
if (this.#refreshTimer) {
|
|
103
|
+
clearInterval(this.#refreshTimer);
|
|
104
|
+
this.#refreshTimer = null;
|
|
105
|
+
}
|
|
106
|
+
await Promise.all(Array.from(this.#records.values(), (record) => record.syncPromise).filter(Boolean));
|
|
107
|
+
}
|
|
108
|
+
async handleTarget(info) {
|
|
109
|
+
if (info.kind !== "editor" ||
|
|
110
|
+
!info.ready ||
|
|
111
|
+
!info.projectId ||
|
|
112
|
+
!info.projectName) {
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
const existing = this.#records.get(info.projectId);
|
|
116
|
+
if (existing && existing.branchId && info.branchId && existing.branchId !== info.branchId) {
|
|
117
|
+
existing.state = "conflict";
|
|
118
|
+
existing.lastError = `Branch ${info.branchId} cannot sync into workspace branch ${existing.branchId}.`;
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
const record = existing || await this.#createRecord(info);
|
|
122
|
+
record.targetId = info.id;
|
|
123
|
+
record.targetInfo = info;
|
|
124
|
+
record.connected = true;
|
|
125
|
+
record.projectName = info.projectName;
|
|
126
|
+
record.branchName = info.branchName || record.branchName;
|
|
127
|
+
await this.#writeManifest(record);
|
|
128
|
+
await this.#sync(record, false);
|
|
129
|
+
}
|
|
130
|
+
markDisconnected(info) {
|
|
131
|
+
if (!info.projectId)
|
|
132
|
+
return;
|
|
133
|
+
const record = this.#records.get(info.projectId);
|
|
134
|
+
if (record?.targetId === info.id)
|
|
135
|
+
record.connected = false;
|
|
136
|
+
}
|
|
137
|
+
statusForTarget(info) {
|
|
138
|
+
if (!info?.projectId) {
|
|
139
|
+
return {
|
|
140
|
+
available: false,
|
|
141
|
+
state: "unavailable",
|
|
142
|
+
rootDirectory: this.rootDir,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
const record = this.#records.get(info.projectId);
|
|
146
|
+
if (!record) {
|
|
147
|
+
return {
|
|
148
|
+
available: false,
|
|
149
|
+
state: info.kind === "editor" ? "initializing" : "unavailable",
|
|
150
|
+
rootDirectory: this.rootDir,
|
|
151
|
+
projectId: info.projectId,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
if (record.branchId && info.branchId && record.branchId !== info.branchId) {
|
|
155
|
+
return {
|
|
156
|
+
...this.#status(record),
|
|
157
|
+
state: "conflict",
|
|
158
|
+
branchConflict: {
|
|
159
|
+
workspaceBranchId: record.branchId,
|
|
160
|
+
targetBranchId: info.branchId,
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
return this.#status(record);
|
|
165
|
+
}
|
|
166
|
+
async syncTarget(info) {
|
|
167
|
+
if (!info.projectId)
|
|
168
|
+
throw new Error("The selected target has no project metadata.");
|
|
169
|
+
const record = this.#records.get(info.projectId);
|
|
170
|
+
if (!record)
|
|
171
|
+
throw new Error("The selected project workspace has not been initialized.");
|
|
172
|
+
if (record.branchId && info.branchId && record.branchId !== info.branchId) {
|
|
173
|
+
throw new Error(`Workspace is bound to branch ${record.branchId}, not ${info.branchId}.`);
|
|
174
|
+
}
|
|
175
|
+
record.targetId = info.id;
|
|
176
|
+
record.targetInfo = info;
|
|
177
|
+
record.connected = true;
|
|
178
|
+
await this.#sync(record, true);
|
|
179
|
+
return this.#status(record);
|
|
180
|
+
}
|
|
181
|
+
async prepareAssetFiles(info, assetIds) {
|
|
182
|
+
if (!info.projectId)
|
|
183
|
+
throw new Error("The selected target has no project metadata.");
|
|
184
|
+
const record = this.#records.get(info.projectId);
|
|
185
|
+
if (!record)
|
|
186
|
+
throw new Error("The selected project workspace has not been initialized.");
|
|
187
|
+
record.targetId = info.id;
|
|
188
|
+
record.targetInfo = info;
|
|
189
|
+
record.connected = true;
|
|
190
|
+
await this.#sync(record, true);
|
|
191
|
+
const assets = [];
|
|
192
|
+
for (const rawId of assetIds) {
|
|
193
|
+
const id = String(rawId);
|
|
194
|
+
const entry = record.index.entries[id];
|
|
195
|
+
if (!entry)
|
|
196
|
+
throw new Error(`Asset ${id} is not present in the workspace catalog.`);
|
|
197
|
+
if (entry.status === "conflict" || entry.status === "error") {
|
|
198
|
+
throw new Error(`Asset ${id} cannot be built while its workspace state is ${entry.status}.`);
|
|
199
|
+
}
|
|
200
|
+
if (entry.localPath && !existsSync(this.#assetPath(record, entry.localPath))) {
|
|
201
|
+
await this.#downloadAsset(record, entry);
|
|
202
|
+
}
|
|
203
|
+
assets.push({
|
|
204
|
+
id,
|
|
205
|
+
name: entry.name,
|
|
206
|
+
type: entry.type,
|
|
207
|
+
filename: entry.filename,
|
|
208
|
+
path: entry.localPath ? this.#assetPath(record, entry.localPath) : null,
|
|
209
|
+
hash: entry.localHash,
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
await this.#persist(record);
|
|
213
|
+
return {
|
|
214
|
+
projectDirectory: record.directory,
|
|
215
|
+
tmpDirectory: record.tmpDirectory,
|
|
216
|
+
assets,
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
async pullAsset(info, assetId) {
|
|
220
|
+
if (!info.projectId)
|
|
221
|
+
throw new Error("The selected target has no project metadata.");
|
|
222
|
+
const record = this.#records.get(info.projectId);
|
|
223
|
+
if (!record)
|
|
224
|
+
throw new Error("The selected project workspace has not been initialized.");
|
|
225
|
+
const entry = record.index.entries[String(assetId)];
|
|
226
|
+
if (!entry)
|
|
227
|
+
throw new Error(`Asset ${assetId} is not present in the workspace index.`);
|
|
228
|
+
if (!entry.localPath)
|
|
229
|
+
throw new Error(`Asset ${assetId} has no downloadable file.`);
|
|
230
|
+
if (entry.type === "script") {
|
|
231
|
+
throw new Error("Scripts are synchronized automatically; use workspace sync instead.");
|
|
232
|
+
}
|
|
233
|
+
const result = await this.#downloadAsset(record, entry);
|
|
234
|
+
await this.#persist(record);
|
|
235
|
+
return {
|
|
236
|
+
assetId,
|
|
237
|
+
path: result.path,
|
|
238
|
+
size: result.size,
|
|
239
|
+
hash: result.hash,
|
|
240
|
+
hashAlgorithm: "md5",
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
async #createRecord(info) {
|
|
244
|
+
await mkdir(this.rootDir, { recursive: true });
|
|
245
|
+
const existingDirectory = await this.#findProjectDirectory(info.projectId || "");
|
|
246
|
+
const directoryName = `${info.projectId}-${safeWorkspaceName(info.projectName || "project", "project")}`;
|
|
247
|
+
const directory = existingDirectory || this.#withinRoot(join(this.rootDir, directoryName));
|
|
248
|
+
if (await isSymbolicLink(directory)) {
|
|
249
|
+
throw new Error(`Workspace project directory cannot be a symbolic link: ${directory}`);
|
|
250
|
+
}
|
|
251
|
+
const assetsDirectory = join(directory, "assets");
|
|
252
|
+
const tmpDirectory = join(directory, "tmp");
|
|
253
|
+
await mkdir(assetsDirectory, { recursive: true });
|
|
254
|
+
await mkdir(join(tmpDirectory, "scripts"), { recursive: true });
|
|
255
|
+
await mkdir(join(tmpDirectory, "captures"), { recursive: true });
|
|
256
|
+
await mkdir(join(tmpDirectory, "conflicts"), { recursive: true });
|
|
257
|
+
await mkdir(join(tmpDirectory, "trash", "remote"), { recursive: true });
|
|
258
|
+
await mkdir(join(directory, ".pcbridge"), { recursive: true });
|
|
259
|
+
const manifest = await readJson(join(directory, PROJECT_FILE));
|
|
260
|
+
const syncState = await readJson(join(directory, SYNC_STATE_FILE));
|
|
261
|
+
const legacyPrimaryPath = join(directory, LEGACY_INDEX_FILE);
|
|
262
|
+
const legacyBackupPath = join(directory, LEGACY_INDEX_BACKUP_FILE);
|
|
263
|
+
const legacyPrimary = await readJson(legacyPrimaryPath);
|
|
264
|
+
const legacyBackup = legacyPrimary ? null : await readJson(legacyBackupPath);
|
|
265
|
+
const legacy = legacyPrimary?.schemaVersion === 1
|
|
266
|
+
? legacyPrimary
|
|
267
|
+
: legacyBackup?.schemaVersion === 1 ? legacyBackup : null;
|
|
268
|
+
const index = manifest?.schemaVersion === 2 && manifest.assets
|
|
269
|
+
? this.#indexFromManifest(manifest, syncState, info)
|
|
270
|
+
: await this.#indexFromLegacy(directory, legacy, info);
|
|
271
|
+
const record = {
|
|
272
|
+
projectId: info.projectId || "",
|
|
273
|
+
projectName: info.projectName || "Project",
|
|
274
|
+
branchId: info.branchId || index.branchId || null,
|
|
275
|
+
branchName: info.branchName || null,
|
|
276
|
+
directory,
|
|
277
|
+
assetsDirectory,
|
|
278
|
+
tmpDirectory,
|
|
279
|
+
targetId: info.id,
|
|
280
|
+
targetInfo: info,
|
|
281
|
+
connected: true,
|
|
282
|
+
state: "initializing",
|
|
283
|
+
lastSyncedAt: typeof syncState?.lastSuccessfulSyncAt === "string"
|
|
284
|
+
? syncState.lastSuccessfulSyncAt
|
|
285
|
+
: typeof manifest?.workspace?.lastSuccessfulSyncAt === "string"
|
|
286
|
+
? manifest.workspace.lastSuccessfulSyncAt
|
|
287
|
+
: null,
|
|
288
|
+
lastError: null,
|
|
289
|
+
lastWarning: null,
|
|
290
|
+
syncStartedAt: null,
|
|
291
|
+
syncPhase: null,
|
|
292
|
+
syncProgress: null,
|
|
293
|
+
pendingShrinkDigest: null,
|
|
294
|
+
pendingShrinkCount: 0,
|
|
295
|
+
legacyIndexPath: legacyPrimary?.schemaVersion === 1 ? legacyPrimaryPath : null,
|
|
296
|
+
index,
|
|
297
|
+
syncPromise: null,
|
|
298
|
+
};
|
|
299
|
+
this.#records.set(record.projectId, record);
|
|
300
|
+
return record;
|
|
301
|
+
}
|
|
302
|
+
async #findProjectDirectory(projectId) {
|
|
303
|
+
let entries;
|
|
304
|
+
try {
|
|
305
|
+
entries = await readdir(this.rootDir, { withFileTypes: true });
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
for (const entry of entries) {
|
|
311
|
+
if (!entry.isDirectory() || entry.isSymbolicLink())
|
|
312
|
+
continue;
|
|
313
|
+
const directory = this.#withinRoot(join(this.rootDir, entry.name));
|
|
314
|
+
const manifest = await readJson(join(directory, PROJECT_FILE));
|
|
315
|
+
if (manifest?.project?.id === projectId)
|
|
316
|
+
return directory;
|
|
317
|
+
}
|
|
318
|
+
return null;
|
|
319
|
+
}
|
|
320
|
+
#withinRoot(path) {
|
|
321
|
+
const resolved = resolve(path);
|
|
322
|
+
if (resolved !== this.rootDir && !resolved.startsWith(`${this.rootDir}${sep}`)) {
|
|
323
|
+
throw new Error(`Workspace path escapes daemon root: ${path}`);
|
|
324
|
+
}
|
|
325
|
+
return resolved;
|
|
326
|
+
}
|
|
327
|
+
#assetPath(record, localPath) {
|
|
328
|
+
const path = this.#withinRoot(join(record.assetsDirectory, localPath));
|
|
329
|
+
if (path !== record.assetsDirectory && !path.startsWith(`${record.assetsDirectory}${sep}`)) {
|
|
330
|
+
throw new Error(`Asset path escapes project assets directory: ${localPath}`);
|
|
331
|
+
}
|
|
332
|
+
return path;
|
|
333
|
+
}
|
|
334
|
+
#indexFromManifest(manifest, syncState, info) {
|
|
335
|
+
const entries = {};
|
|
336
|
+
for (const [id, asset] of Object.entries(manifest.assets || {})) {
|
|
337
|
+
const localPath = manifestLocalPath(asset.file?.path);
|
|
338
|
+
const present = Boolean(localPath && asset.file?.present);
|
|
339
|
+
const state = asset.state === "remote-only" ? "indexed" : asset.state;
|
|
340
|
+
entries[id] = {
|
|
341
|
+
id,
|
|
342
|
+
name: asset.name,
|
|
343
|
+
type: asset.type,
|
|
344
|
+
remotePath: asset.folder ? asset.folder.split("/").filter(Boolean) : [],
|
|
345
|
+
localPath,
|
|
346
|
+
filename: asset.file?.filename || null,
|
|
347
|
+
remoteFileSize: asset.file?.size ?? null,
|
|
348
|
+
remoteFileHash: asset.file?.hash.remote || null,
|
|
349
|
+
localHash: present ? asset.file?.hash.local || null : null,
|
|
350
|
+
lastSyncedHash: asset.file?.hash.base || null,
|
|
351
|
+
legacyLastSyncedSha256: syncState?.entries?.[id]?.legacyLastSyncedSha256,
|
|
352
|
+
pendingRemoteHash: syncState?.entries?.[id]?.pendingRemoteHash,
|
|
353
|
+
localFileSize: syncState?.entries?.[id]?.localFileSize,
|
|
354
|
+
localMtimeMs: syncState?.entries?.[id]?.localMtimeMs,
|
|
355
|
+
downloaded: present,
|
|
356
|
+
status: state,
|
|
357
|
+
error: asset.error,
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
return {
|
|
361
|
+
schemaVersion: 2,
|
|
362
|
+
projectId: info.projectId || manifest.project?.id || "",
|
|
363
|
+
branchId: info.branchId || manifest.activeBranch?.id || null,
|
|
364
|
+
updatedAt: manifest.workspace?.updatedAt || new Date().toISOString(),
|
|
365
|
+
entries,
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
async #indexFromLegacy(directory, legacy, info) {
|
|
369
|
+
const entries = {};
|
|
370
|
+
for (const [id, old] of Object.entries(legacy?.entries || {})) {
|
|
371
|
+
const localPath = old.localPath || null;
|
|
372
|
+
const assetsDirectory = resolve(directory, "assets");
|
|
373
|
+
const candidate = localPath ? resolve(assetsDirectory, localPath) : null;
|
|
374
|
+
const path = candidate && candidate.startsWith(`${assetsDirectory}${sep}`) ? candidate : null;
|
|
375
|
+
const localContent = path && existsSync(path) ? await readFile(path) : null;
|
|
376
|
+
const localHash = localContent ? hashContent(localContent) : null;
|
|
377
|
+
const localSha256 = localContent ? hashLegacyContent(localContent) : null;
|
|
378
|
+
const migratedBase = old.lastSyncedHash && localSha256 === old.lastSyncedHash
|
|
379
|
+
? old.remoteFileHash || null
|
|
380
|
+
: null;
|
|
381
|
+
entries[id] = {
|
|
382
|
+
id,
|
|
383
|
+
name: old.name,
|
|
384
|
+
type: old.type,
|
|
385
|
+
remotePath: old.remotePath || [],
|
|
386
|
+
localPath,
|
|
387
|
+
filename: old.filename || null,
|
|
388
|
+
remoteFileSize: old.remoteFileSize ?? null,
|
|
389
|
+
remoteFileHash: old.remoteFileHash || null,
|
|
390
|
+
localHash,
|
|
391
|
+
lastSyncedHash: migratedBase,
|
|
392
|
+
legacyLastSyncedSha256: migratedBase ? undefined : old.lastSyncedHash || undefined,
|
|
393
|
+
pendingRemoteHash: old.pendingRemoteHash,
|
|
394
|
+
localFileSize: old.localFileSize,
|
|
395
|
+
localMtimeMs: old.localMtimeMs,
|
|
396
|
+
downloaded: Boolean(localContent),
|
|
397
|
+
status: old.status,
|
|
398
|
+
error: old.error,
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
return {
|
|
402
|
+
schemaVersion: 2,
|
|
403
|
+
projectId: info.projectId || legacy?.projectId || "",
|
|
404
|
+
branchId: info.branchId || legacy?.branchId || null,
|
|
405
|
+
updatedAt: legacy?.updatedAt || new Date().toISOString(),
|
|
406
|
+
entries,
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
#manifestAssets(record) {
|
|
410
|
+
const assets = {};
|
|
411
|
+
const sorted = Object.values(record.index.entries)
|
|
412
|
+
.sort((left, right) => left.id.localeCompare(right.id, undefined, { numeric: true }));
|
|
413
|
+
for (const entry of sorted) {
|
|
414
|
+
const present = Boolean(entry.localPath && entry.downloaded && existsSync(this.#assetPath(record, entry.localPath)));
|
|
415
|
+
const publicState = entry.status === "indexed" && entry.localPath && !present
|
|
416
|
+
? "remote-only"
|
|
417
|
+
: entry.status;
|
|
418
|
+
const asset = {
|
|
419
|
+
id: entry.id,
|
|
420
|
+
name: entry.name,
|
|
421
|
+
type: entry.type,
|
|
422
|
+
folder: toPosixPath(entry.remotePath.join("/")),
|
|
423
|
+
file: entry.localPath && entry.filename
|
|
424
|
+
? {
|
|
425
|
+
filename: entry.filename,
|
|
426
|
+
path: `assets/${toPosixPath(entry.localPath)}`,
|
|
427
|
+
size: entry.remoteFileSize,
|
|
428
|
+
present,
|
|
429
|
+
hash: {
|
|
430
|
+
algorithm: "md5",
|
|
431
|
+
remote: entry.remoteFileHash,
|
|
432
|
+
local: present ? entry.localHash : null,
|
|
433
|
+
base: entry.lastSyncedHash,
|
|
434
|
+
matches: entry.remoteFileHash && present && entry.localHash
|
|
435
|
+
? entry.remoteFileHash === entry.localHash
|
|
436
|
+
: null,
|
|
437
|
+
},
|
|
438
|
+
}
|
|
439
|
+
: null,
|
|
440
|
+
state: publicState,
|
|
441
|
+
};
|
|
442
|
+
if (entry.error)
|
|
443
|
+
asset.error = entry.error;
|
|
444
|
+
assets[entry.id] = asset;
|
|
445
|
+
}
|
|
446
|
+
return assets;
|
|
447
|
+
}
|
|
448
|
+
async #writeManifest(record) {
|
|
449
|
+
const path = join(record.directory, PROJECT_FILE);
|
|
450
|
+
const existing = await readJson(path);
|
|
451
|
+
const info = record.targetInfo;
|
|
452
|
+
const scenes = Array.isArray(existing?.scenes) ? [...existing.scenes] : [];
|
|
453
|
+
if (info.sceneId) {
|
|
454
|
+
const scene = scenes.find((item) => item.id === info.sceneId);
|
|
455
|
+
if (scene)
|
|
456
|
+
scene.name = info.sceneName || scene.name;
|
|
457
|
+
else
|
|
458
|
+
scenes.push({ id: info.sceneId, name: info.sceneName || null });
|
|
459
|
+
}
|
|
460
|
+
const now = new Date().toISOString();
|
|
461
|
+
const existingSettings = existing?.settings && typeof existing.settings === "object"
|
|
462
|
+
? existing.settings
|
|
463
|
+
: {};
|
|
464
|
+
const existingSync = existingSettings.sync && typeof existingSettings.sync === "object"
|
|
465
|
+
? existingSettings.sync
|
|
466
|
+
: {};
|
|
467
|
+
const previousLastSuccessfulSyncAt = existing?.workspace &&
|
|
468
|
+
Object.prototype.hasOwnProperty.call(existing.workspace, "lastSuccessfulSyncAt")
|
|
469
|
+
? existing.workspace.lastSuccessfulSyncAt
|
|
470
|
+
: record.lastSyncedAt;
|
|
471
|
+
const manifest = {
|
|
472
|
+
...(existing || {}),
|
|
473
|
+
schemaVersion: 2,
|
|
474
|
+
project: { id: record.projectId, name: record.projectName },
|
|
475
|
+
activeBranch: { id: record.branchId, name: record.branchName },
|
|
476
|
+
scenes,
|
|
477
|
+
workspace: {
|
|
478
|
+
...(existing?.workspace || {}),
|
|
479
|
+
createdAt: existing?.workspace?.createdAt || now,
|
|
480
|
+
updatedAt: existing?.workspace?.updatedAt || now,
|
|
481
|
+
assetCatalogComplete: Boolean(record.lastSyncedAt),
|
|
482
|
+
assetCount: Object.values(record.index.entries)
|
|
483
|
+
.filter((entry) => entry.type !== "folder").length,
|
|
484
|
+
assetHashAlgorithm: "md5",
|
|
485
|
+
lastSuccessfulSyncAt: previousLastSuccessfulSyncAt,
|
|
486
|
+
},
|
|
487
|
+
settings: {
|
|
488
|
+
...existingSettings,
|
|
489
|
+
sync: {
|
|
490
|
+
conflictPolicy: "safe-newer",
|
|
491
|
+
deletePolicy: "quarantine",
|
|
492
|
+
...existingSync,
|
|
493
|
+
contentMode: "all",
|
|
494
|
+
},
|
|
495
|
+
},
|
|
496
|
+
assets: this.#manifestAssets(record),
|
|
497
|
+
};
|
|
498
|
+
if (existing && JSON.stringify(manifest) === JSON.stringify(existing))
|
|
499
|
+
return;
|
|
500
|
+
manifest.workspace = {
|
|
501
|
+
...manifest.workspace,
|
|
502
|
+
updatedAt: now,
|
|
503
|
+
lastSuccessfulSyncAt: record.lastSyncedAt,
|
|
504
|
+
};
|
|
505
|
+
await atomicWrite(path, `${JSON.stringify(manifest, null, 2)}\n`);
|
|
506
|
+
}
|
|
507
|
+
async #writeSyncState(record) {
|
|
508
|
+
record.index.updatedAt = new Date().toISOString();
|
|
509
|
+
const entries = Object.fromEntries(Object.values(record.index.entries)
|
|
510
|
+
.filter((entry) => entry.legacyLastSyncedSha256 ||
|
|
511
|
+
entry.pendingRemoteHash ||
|
|
512
|
+
entry.localFileSize !== undefined ||
|
|
513
|
+
entry.localMtimeMs !== undefined)
|
|
514
|
+
.map((entry) => [entry.id, {
|
|
515
|
+
legacyLastSyncedSha256: entry.legacyLastSyncedSha256,
|
|
516
|
+
pendingRemoteHash: entry.pendingRemoteHash,
|
|
517
|
+
localFileSize: entry.localFileSize,
|
|
518
|
+
localMtimeMs: entry.localMtimeMs,
|
|
519
|
+
}]));
|
|
520
|
+
await atomicWrite(join(record.directory, SYNC_STATE_FILE), `${JSON.stringify({
|
|
521
|
+
schemaVersion: 1,
|
|
522
|
+
projectId: record.projectId,
|
|
523
|
+
branchId: record.branchId,
|
|
524
|
+
updatedAt: record.index.updatedAt,
|
|
525
|
+
lastSuccessfulSyncAt: record.lastSyncedAt,
|
|
526
|
+
entries,
|
|
527
|
+
}, null, 2)}\n`);
|
|
528
|
+
}
|
|
529
|
+
async #persist(record) {
|
|
530
|
+
await this.#writeManifest(record);
|
|
531
|
+
await this.#writeSyncState(record);
|
|
532
|
+
if (record.legacyIndexPath && existsSync(record.legacyIndexPath)) {
|
|
533
|
+
const backup = join(record.directory, LEGACY_INDEX_BACKUP_FILE);
|
|
534
|
+
if (!existsSync(backup))
|
|
535
|
+
await rename(record.legacyIndexPath, backup);
|
|
536
|
+
if (!existsSync(record.legacyIndexPath))
|
|
537
|
+
record.legacyIndexPath = null;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
async #sync(record, force) {
|
|
541
|
+
if (record.syncPromise)
|
|
542
|
+
return record.syncPromise;
|
|
543
|
+
record.syncPromise = this.#performSync(record, force).finally(() => {
|
|
544
|
+
record.syncPromise = null;
|
|
545
|
+
});
|
|
546
|
+
return record.syncPromise;
|
|
547
|
+
}
|
|
548
|
+
async #performSync(record, force) {
|
|
549
|
+
const previousState = record.state === "syncing" ? "initializing" : record.state;
|
|
550
|
+
record.state = "syncing";
|
|
551
|
+
record.lastError = null;
|
|
552
|
+
record.lastWarning = null;
|
|
553
|
+
record.syncStartedAt = new Date().toISOString();
|
|
554
|
+
record.syncPhase = "snapshot";
|
|
555
|
+
try {
|
|
556
|
+
const response = await this.#requestTarget(record.targetId, "bridge:workspaceSnapshot", {}, 60000);
|
|
557
|
+
if (!response.ok)
|
|
558
|
+
throw new Error(response.error.message);
|
|
559
|
+
const data = asObject(response.data);
|
|
560
|
+
const assets = Array.isArray(data.assets) ? data.assets : [];
|
|
561
|
+
if (!this.#acceptSnapshot(record, assets)) {
|
|
562
|
+
record.state = previousState;
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
record.syncPhase = "reconciling";
|
|
566
|
+
record.syncProgress = {
|
|
567
|
+
completed: 0,
|
|
568
|
+
total: assets.filter((asset) => asset.type !== "folder" && asset.file).length,
|
|
569
|
+
assetId: null,
|
|
570
|
+
action: "comparing",
|
|
571
|
+
};
|
|
572
|
+
await this.#applySnapshot(record, assets, force);
|
|
573
|
+
record.lastSyncedAt = new Date().toISOString();
|
|
574
|
+
const entries = Object.values(record.index.entries);
|
|
575
|
+
record.state = entries.some((entry) => entry.status === "conflict")
|
|
576
|
+
? "conflict"
|
|
577
|
+
: entries.some((entry) => entry.status === "local-change")
|
|
578
|
+
? "local-change"
|
|
579
|
+
: entries.some((entry) => entry.status === "remote-change")
|
|
580
|
+
? "remote-change"
|
|
581
|
+
: entries.some((entry) => entry.status === "error")
|
|
582
|
+
? "error"
|
|
583
|
+
: "synced";
|
|
584
|
+
record.syncPhase = "persisting";
|
|
585
|
+
await this.#persist(record);
|
|
586
|
+
}
|
|
587
|
+
catch (error) {
|
|
588
|
+
record.state = "error";
|
|
589
|
+
record.lastError = error instanceof Error ? error.message : String(error);
|
|
590
|
+
}
|
|
591
|
+
finally {
|
|
592
|
+
record.syncStartedAt = null;
|
|
593
|
+
record.syncPhase = null;
|
|
594
|
+
record.syncProgress = null;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
#acceptSnapshot(record, assets) {
|
|
598
|
+
const previousIds = Object.keys(record.index.entries);
|
|
599
|
+
if (!previousIds.length) {
|
|
600
|
+
record.pendingShrinkDigest = null;
|
|
601
|
+
record.pendingShrinkCount = 0;
|
|
602
|
+
return true;
|
|
603
|
+
}
|
|
604
|
+
const incomingIds = new Set(assets.map((asset) => String(asset.id)));
|
|
605
|
+
const missing = previousIds.filter((id) => !incomingIds.has(id));
|
|
606
|
+
if (!missing.length) {
|
|
607
|
+
record.pendingShrinkDigest = null;
|
|
608
|
+
record.pendingShrinkCount = 0;
|
|
609
|
+
return true;
|
|
610
|
+
}
|
|
611
|
+
if (!assets.length) {
|
|
612
|
+
record.pendingShrinkDigest = null;
|
|
613
|
+
record.pendingShrinkCount = 0;
|
|
614
|
+
record.lastWarning =
|
|
615
|
+
`Ignored an empty PlayCanvas asset snapshot while ${previousIds.length} indexed assets ` +
|
|
616
|
+
"are present. Waiting for the Editor asset store to finish loading.";
|
|
617
|
+
return false;
|
|
618
|
+
}
|
|
619
|
+
const digest = hashContent([...incomingIds].sort().join("\n"));
|
|
620
|
+
if (record.pendingShrinkDigest === digest)
|
|
621
|
+
record.pendingShrinkCount += 1;
|
|
622
|
+
else {
|
|
623
|
+
record.pendingShrinkDigest = digest;
|
|
624
|
+
record.pendingShrinkCount = 1;
|
|
625
|
+
}
|
|
626
|
+
if (record.pendingShrinkCount < 2) {
|
|
627
|
+
record.lastWarning =
|
|
628
|
+
`Deferred ${missing.length} possible remote deletion${missing.length === 1 ? "" : "s"}; ` +
|
|
629
|
+
"the same non-empty asset snapshot must be observed twice.";
|
|
630
|
+
return false;
|
|
631
|
+
}
|
|
632
|
+
record.pendingShrinkDigest = null;
|
|
633
|
+
record.pendingShrinkCount = 0;
|
|
634
|
+
return true;
|
|
635
|
+
}
|
|
636
|
+
async #applySnapshot(record, assets, force) {
|
|
637
|
+
const folderAssets = assets
|
|
638
|
+
.filter((asset) => asset.type === "folder")
|
|
639
|
+
.sort((left, right) => (left.path?.length || 0) - (right.path?.length || 0));
|
|
640
|
+
const folderPaths = new Map();
|
|
641
|
+
const usedNames = new Map();
|
|
642
|
+
const allocateName = (parent, rawName, id) => {
|
|
643
|
+
const parentKey = parent.join("/").toLocaleLowerCase();
|
|
644
|
+
const used = usedNames.get(parentKey) || new Set();
|
|
645
|
+
const safe = safeAssetName(rawName, `asset-${id}`);
|
|
646
|
+
const key = safe.toLocaleLowerCase();
|
|
647
|
+
const selected = used.has(key) ? collisionName(safe, id) : safe;
|
|
648
|
+
used.add(selected.toLocaleLowerCase());
|
|
649
|
+
usedNames.set(parentKey, used);
|
|
650
|
+
return selected;
|
|
651
|
+
};
|
|
652
|
+
for (const folder of folderAssets) {
|
|
653
|
+
const parentIds = (folder.path || []).map(String);
|
|
654
|
+
const parent = parentIds.length ? folderPaths.get(parentIds[parentIds.length - 1]) || [] : [];
|
|
655
|
+
const name = allocateName(parent, folder.name, String(folder.id));
|
|
656
|
+
const path = [...parent, name];
|
|
657
|
+
folderPaths.set(String(folder.id), path);
|
|
658
|
+
await mkdir(this.#assetPath(record, join(...path)), { recursive: true });
|
|
659
|
+
}
|
|
660
|
+
const previous = record.index.entries;
|
|
661
|
+
const next = {};
|
|
662
|
+
for (const asset of assets) {
|
|
663
|
+
const id = String(asset.id);
|
|
664
|
+
const parentIds = (asset.path || []).map(String);
|
|
665
|
+
const parent = parentIds.length ? folderPaths.get(parentIds[parentIds.length - 1]) || [] : [];
|
|
666
|
+
if (asset.type === "folder") {
|
|
667
|
+
next[id] = {
|
|
668
|
+
id,
|
|
669
|
+
name: asset.name,
|
|
670
|
+
type: asset.type,
|
|
671
|
+
remotePath: folderPaths.get(id) || parent,
|
|
672
|
+
localPath: null,
|
|
673
|
+
filename: null,
|
|
674
|
+
remoteFileSize: null,
|
|
675
|
+
remoteFileHash: null,
|
|
676
|
+
localHash: null,
|
|
677
|
+
lastSyncedHash: null,
|
|
678
|
+
localFileSize: undefined,
|
|
679
|
+
localMtimeMs: undefined,
|
|
680
|
+
downloaded: false,
|
|
681
|
+
status: "indexed",
|
|
682
|
+
};
|
|
683
|
+
continue;
|
|
684
|
+
}
|
|
685
|
+
const remoteFilename = asset.file?.filename || (asset.type === "script" ? asset.name : null);
|
|
686
|
+
const localName = remoteFilename ? allocateName(parent, remoteFilename, id) : null;
|
|
687
|
+
const localPath = localName ? join(...parent, localName) : null;
|
|
688
|
+
const old = previous[id];
|
|
689
|
+
const entry = {
|
|
690
|
+
id,
|
|
691
|
+
name: asset.name,
|
|
692
|
+
type: asset.type,
|
|
693
|
+
remotePath: parent,
|
|
694
|
+
localPath,
|
|
695
|
+
filename: remoteFilename,
|
|
696
|
+
remoteFileSize: asset.file?.size ?? null,
|
|
697
|
+
remoteFileHash: asset.file?.hash || null,
|
|
698
|
+
localHash: old?.localHash || null,
|
|
699
|
+
lastSyncedHash: old?.lastSyncedHash || null,
|
|
700
|
+
legacyLastSyncedSha256: old?.legacyLastSyncedSha256,
|
|
701
|
+
pendingRemoteHash: old?.pendingRemoteHash,
|
|
702
|
+
localFileSize: old?.localFileSize,
|
|
703
|
+
localMtimeMs: old?.localMtimeMs,
|
|
704
|
+
downloaded: old?.downloaded || false,
|
|
705
|
+
status: old?.status || "indexed",
|
|
706
|
+
error: old?.error,
|
|
707
|
+
};
|
|
708
|
+
next[id] = entry;
|
|
709
|
+
if (asset.file && record.syncProgress) {
|
|
710
|
+
record.syncProgress.assetId = id;
|
|
711
|
+
record.syncProgress.action = "comparing";
|
|
712
|
+
}
|
|
713
|
+
if (old?.localPath && localPath && old.localPath !== localPath && existsSync(this.#assetPath(record, old.localPath))) {
|
|
714
|
+
const oldPath = this.#assetPath(record, old.localPath);
|
|
715
|
+
const newPath = this.#assetPath(record, localPath);
|
|
716
|
+
await mkdir(dirname(newPath), { recursive: true });
|
|
717
|
+
if (!existsSync(newPath))
|
|
718
|
+
await rename(oldPath, newPath);
|
|
719
|
+
}
|
|
720
|
+
if (asset.type === "script" && localPath) {
|
|
721
|
+
await this.#reconcileScript(record, entry, old, force);
|
|
722
|
+
}
|
|
723
|
+
else if (localPath) {
|
|
724
|
+
await this.#reconcileBinary(record, entry, old);
|
|
725
|
+
}
|
|
726
|
+
if (asset.file && record.syncProgress)
|
|
727
|
+
record.syncProgress.completed += 1;
|
|
728
|
+
}
|
|
729
|
+
const deletionBatch = new Date().toISOString().replaceAll(":", "-");
|
|
730
|
+
for (const [id, old] of Object.entries(previous)) {
|
|
731
|
+
if (next[id] || !old.localPath || !existsSync(this.#assetPath(record, old.localPath)))
|
|
732
|
+
continue;
|
|
733
|
+
const source = this.#assetPath(record, old.localPath);
|
|
734
|
+
const destination = join(record.tmpDirectory, "trash", "remote", deletionBatch, `${id}-${safeWorkspaceName(basename(old.localPath), `asset-${id}`)}`);
|
|
735
|
+
await mkdir(dirname(destination), { recursive: true });
|
|
736
|
+
await rename(source, destination);
|
|
737
|
+
}
|
|
738
|
+
const obsoleteFolders = Object.entries(previous)
|
|
739
|
+
.filter(([id, old]) => old.type === "folder" &&
|
|
740
|
+
(!next[id] || next[id].remotePath.join("/") !== old.remotePath.join("/")))
|
|
741
|
+
.map(([, old]) => old.remotePath)
|
|
742
|
+
.sort((left, right) => right.length - left.length);
|
|
743
|
+
for (const folder of obsoleteFolders) {
|
|
744
|
+
if (!folder.length)
|
|
745
|
+
continue;
|
|
746
|
+
await rmdir(this.#assetPath(record, join(...folder))).catch(() => undefined);
|
|
747
|
+
}
|
|
748
|
+
record.index = {
|
|
749
|
+
schemaVersion: 2,
|
|
750
|
+
projectId: record.projectId,
|
|
751
|
+
branchId: record.branchId,
|
|
752
|
+
updatedAt: new Date().toISOString(),
|
|
753
|
+
entries: next,
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
async #localFileSnapshot(record, entry, old) {
|
|
757
|
+
if (!entry.localPath)
|
|
758
|
+
return null;
|
|
759
|
+
const path = this.#assetPath(record, entry.localPath);
|
|
760
|
+
if (!existsSync(path))
|
|
761
|
+
return null;
|
|
762
|
+
const info = await stat(path);
|
|
763
|
+
const cachedHash = old?.localHash &&
|
|
764
|
+
old.localFileSize === info.size &&
|
|
765
|
+
old.localMtimeMs === info.mtimeMs
|
|
766
|
+
? old.localHash
|
|
767
|
+
: null;
|
|
768
|
+
return {
|
|
769
|
+
hash: cachedHash || hashContent(await readFile(path)),
|
|
770
|
+
size: info.size,
|
|
771
|
+
mtimeMs: info.mtimeMs,
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
async #recordLocalFile(record, entry, hash) {
|
|
775
|
+
if (!entry.localPath)
|
|
776
|
+
return;
|
|
777
|
+
const info = await stat(this.#assetPath(record, entry.localPath));
|
|
778
|
+
entry.localHash = hash;
|
|
779
|
+
entry.localFileSize = info.size;
|
|
780
|
+
entry.localMtimeMs = info.mtimeMs;
|
|
781
|
+
entry.downloaded = true;
|
|
782
|
+
}
|
|
783
|
+
async #readRemoteAsset(record, entry) {
|
|
784
|
+
const response = await this.#requestTarget(record.targetId, "bridge:readAssetFile", { assetId: entry.id }, 120000);
|
|
785
|
+
if (!response.ok)
|
|
786
|
+
throw new Error(response.error.message);
|
|
787
|
+
const data = asObject(response.data);
|
|
788
|
+
const base64 = typeof data.base64 === "string" ? data.base64 : "";
|
|
789
|
+
if (!base64)
|
|
790
|
+
throw new Error(`Asset ${entry.id} returned no file data.`);
|
|
791
|
+
const content = Buffer.from(base64, "base64");
|
|
792
|
+
const hash = hashContent(content);
|
|
793
|
+
if (entry.remoteFileHash && entry.remoteFileHash !== hash) {
|
|
794
|
+
throw new Error(`Asset ${entry.id} changed while it was being downloaded: ` +
|
|
795
|
+
`expected ${entry.remoteFileHash}, received ${hash}.`);
|
|
796
|
+
}
|
|
797
|
+
entry.remoteFileHash = hash;
|
|
798
|
+
return { content, hash };
|
|
799
|
+
}
|
|
800
|
+
async #downloadAsset(record, entry) {
|
|
801
|
+
if (!entry.localPath)
|
|
802
|
+
throw new Error(`Asset ${entry.id} has no downloadable file.`);
|
|
803
|
+
if (record.syncProgress) {
|
|
804
|
+
record.syncProgress.assetId = entry.id;
|
|
805
|
+
record.syncProgress.action = "downloading";
|
|
806
|
+
}
|
|
807
|
+
const remote = await this.#readRemoteAsset(record, entry);
|
|
808
|
+
const path = this.#assetPath(record, entry.localPath);
|
|
809
|
+
await atomicWrite(path, remote.content);
|
|
810
|
+
await this.#recordLocalFile(record, entry, remote.hash);
|
|
811
|
+
entry.lastSyncedHash = remote.hash;
|
|
812
|
+
entry.status = "synced";
|
|
813
|
+
delete entry.legacyLastSyncedSha256;
|
|
814
|
+
delete entry.pendingRemoteHash;
|
|
815
|
+
delete entry.error;
|
|
816
|
+
return { path, size: remote.content.byteLength, hash: remote.hash };
|
|
817
|
+
}
|
|
818
|
+
async #uploadBinary(record, entry, content, localHash) {
|
|
819
|
+
if (record.syncProgress) {
|
|
820
|
+
record.syncProgress.assetId = entry.id;
|
|
821
|
+
record.syncProgress.action = "uploading";
|
|
822
|
+
}
|
|
823
|
+
const response = await this.#requestTarget(record.targetId, "bridge:writeAssetFile", {
|
|
824
|
+
assetId: entry.id,
|
|
825
|
+
filename: entry.filename || entry.name,
|
|
826
|
+
base64: content.toString("base64"),
|
|
827
|
+
}, 120000);
|
|
828
|
+
if (!response.ok) {
|
|
829
|
+
entry.status = "local-change";
|
|
830
|
+
entry.error = response.error.message;
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
await this.#recordLocalFile(record, entry, localHash);
|
|
834
|
+
entry.pendingRemoteHash = localHash;
|
|
835
|
+
entry.status = "local-change";
|
|
836
|
+
delete entry.legacyLastSyncedSha256;
|
|
837
|
+
entry.error = "Waiting for PlayCanvas to confirm the uploaded file hash.";
|
|
838
|
+
}
|
|
839
|
+
async #writeBinaryConflict(record, entry, remoteContent, localHash) {
|
|
840
|
+
if (!entry.localPath)
|
|
841
|
+
return;
|
|
842
|
+
if (record.syncProgress) {
|
|
843
|
+
record.syncProgress.assetId = entry.id;
|
|
844
|
+
record.syncProgress.action = "conflict";
|
|
845
|
+
}
|
|
846
|
+
const conflictBase = join(record.tmpDirectory, "conflicts", `${entry.id}-${safeWorkspaceName(entry.filename || entry.name, `asset-${entry.id}`)}`);
|
|
847
|
+
await mkdir(dirname(conflictBase), { recursive: true });
|
|
848
|
+
await copyFile(this.#assetPath(record, entry.localPath), `${conflictBase}.local`);
|
|
849
|
+
await atomicWrite(`${conflictBase}.remote`, remoteContent);
|
|
850
|
+
entry.localHash = localHash;
|
|
851
|
+
entry.downloaded = true;
|
|
852
|
+
entry.status = "conflict";
|
|
853
|
+
entry.error =
|
|
854
|
+
`Local and remote asset files changed since the last sync. See ` +
|
|
855
|
+
`${relative(record.directory, conflictBase)}.*`;
|
|
856
|
+
}
|
|
857
|
+
async #reconcileBinary(record, entry, old) {
|
|
858
|
+
const local = await this.#localFileSnapshot(record, entry, old);
|
|
859
|
+
const baseline = old?.lastSyncedHash || null;
|
|
860
|
+
const advertisedRemoteHash = entry.remoteFileHash;
|
|
861
|
+
if (!local) {
|
|
862
|
+
await this.#downloadAsset(record, entry);
|
|
863
|
+
return;
|
|
864
|
+
}
|
|
865
|
+
entry.localHash = local.hash;
|
|
866
|
+
entry.localFileSize = local.size;
|
|
867
|
+
entry.localMtimeMs = local.mtimeMs;
|
|
868
|
+
entry.downloaded = true;
|
|
869
|
+
if (advertisedRemoteHash && local.hash === advertisedRemoteHash) {
|
|
870
|
+
entry.lastSyncedHash = local.hash;
|
|
871
|
+
entry.status = "synced";
|
|
872
|
+
delete entry.legacyLastSyncedSha256;
|
|
873
|
+
delete entry.pendingRemoteHash;
|
|
874
|
+
delete entry.error;
|
|
875
|
+
return;
|
|
876
|
+
}
|
|
877
|
+
if (old?.pendingRemoteHash &&
|
|
878
|
+
local.hash === old.pendingRemoteHash &&
|
|
879
|
+
advertisedRemoteHash !== old.pendingRemoteHash) {
|
|
880
|
+
entry.pendingRemoteHash = old.pendingRemoteHash;
|
|
881
|
+
entry.status = "local-change";
|
|
882
|
+
entry.error = "Waiting for PlayCanvas to confirm the uploaded file hash.";
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
if (baseline && local.hash === baseline && advertisedRemoteHash !== baseline) {
|
|
886
|
+
await this.#downloadAsset(record, entry);
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
889
|
+
if (baseline && advertisedRemoteHash === baseline && local.hash !== baseline) {
|
|
890
|
+
await this.#uploadBinary(record, entry, await readFile(this.#assetPath(record, entry.localPath)), local.hash);
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
const remote = await this.#readRemoteAsset(record, entry);
|
|
894
|
+
if (remote.hash === local.hash) {
|
|
895
|
+
entry.lastSyncedHash = local.hash;
|
|
896
|
+
entry.status = "synced";
|
|
897
|
+
delete entry.legacyLastSyncedSha256;
|
|
898
|
+
delete entry.pendingRemoteHash;
|
|
899
|
+
delete entry.error;
|
|
900
|
+
return;
|
|
901
|
+
}
|
|
902
|
+
if (baseline && remote.hash === baseline) {
|
|
903
|
+
await this.#uploadBinary(record, entry, await readFile(this.#assetPath(record, entry.localPath)), local.hash);
|
|
904
|
+
return;
|
|
905
|
+
}
|
|
906
|
+
if (baseline && local.hash === baseline) {
|
|
907
|
+
await atomicWrite(this.#assetPath(record, entry.localPath), remote.content);
|
|
908
|
+
await this.#recordLocalFile(record, entry, remote.hash);
|
|
909
|
+
entry.lastSyncedHash = remote.hash;
|
|
910
|
+
entry.status = "synced";
|
|
911
|
+
delete entry.pendingRemoteHash;
|
|
912
|
+
delete entry.error;
|
|
913
|
+
return;
|
|
914
|
+
}
|
|
915
|
+
if (old?.status === "conflict" && old.localHash === local.hash && old.remoteFileHash === remote.hash) {
|
|
916
|
+
entry.status = "conflict";
|
|
917
|
+
entry.error = old.error;
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
await this.#writeBinaryConflict(record, entry, remote.content, local.hash);
|
|
921
|
+
}
|
|
922
|
+
async #reconcileScript(record, entry, old, force) {
|
|
923
|
+
if (!entry.localPath)
|
|
924
|
+
return;
|
|
925
|
+
const path = this.#assetPath(record, entry.localPath);
|
|
926
|
+
const localBytes = existsSync(path) ? await readFile(path) : null;
|
|
927
|
+
const localContent = localBytes?.toString("utf8") ?? null;
|
|
928
|
+
const localHash = localBytes === null ? null : hashContent(localBytes);
|
|
929
|
+
const baseline = old?.lastSyncedHash || null;
|
|
930
|
+
const advertisedRemoteHash = entry.remoteFileHash;
|
|
931
|
+
if (localContent !== null && advertisedRemoteHash && localHash === advertisedRemoteHash) {
|
|
932
|
+
entry.localHash = localHash;
|
|
933
|
+
entry.lastSyncedHash = localHash;
|
|
934
|
+
entry.downloaded = true;
|
|
935
|
+
entry.status = "synced";
|
|
936
|
+
delete entry.legacyLastSyncedSha256;
|
|
937
|
+
delete entry.pendingRemoteHash;
|
|
938
|
+
delete entry.error;
|
|
939
|
+
return;
|
|
940
|
+
}
|
|
941
|
+
if (localContent !== null &&
|
|
942
|
+
old?.pendingRemoteHash &&
|
|
943
|
+
localHash === old.pendingRemoteHash &&
|
|
944
|
+
advertisedRemoteHash !== old.pendingRemoteHash) {
|
|
945
|
+
entry.localHash = localHash;
|
|
946
|
+
entry.pendingRemoteHash = old.pendingRemoteHash;
|
|
947
|
+
entry.downloaded = true;
|
|
948
|
+
entry.status = "local-change";
|
|
949
|
+
entry.error = "Waiting for PlayCanvas to confirm the uploaded file hash.";
|
|
950
|
+
return;
|
|
951
|
+
}
|
|
952
|
+
const localChanged = localHash !== null && localHash !== baseline;
|
|
953
|
+
const remoteMetadataChanged = !old || old.remoteFileHash !== advertisedRemoteHash;
|
|
954
|
+
if (!force && localContent !== null && baseline && !localChanged && !remoteMetadataChanged) {
|
|
955
|
+
entry.localHash = localHash;
|
|
956
|
+
entry.lastSyncedHash = baseline;
|
|
957
|
+
entry.downloaded = true;
|
|
958
|
+
entry.status = "synced";
|
|
959
|
+
delete entry.error;
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
if (localContent !== null && baseline && advertisedRemoteHash === baseline && localChanged) {
|
|
963
|
+
await this.#uploadScript(record, entry, localContent, localHash);
|
|
964
|
+
return;
|
|
965
|
+
}
|
|
966
|
+
if (record.syncProgress) {
|
|
967
|
+
record.syncProgress.assetId = entry.id;
|
|
968
|
+
record.syncProgress.action = "downloading";
|
|
969
|
+
}
|
|
970
|
+
const response = await this.#requestTarget(record.targetId, "bridge:readAssetText", { assetId: entry.id }, 30000);
|
|
971
|
+
if (!response.ok) {
|
|
972
|
+
entry.status = "error";
|
|
973
|
+
entry.error = response.error.message;
|
|
974
|
+
return;
|
|
975
|
+
}
|
|
976
|
+
const data = asObject(response.data);
|
|
977
|
+
const remoteContent = typeof data.text === "string" ? data.text : "";
|
|
978
|
+
const remoteHash = hashContent(remoteContent);
|
|
979
|
+
if (advertisedRemoteHash && advertisedRemoteHash !== remoteHash) {
|
|
980
|
+
entry.localHash = localHash;
|
|
981
|
+
entry.status = "error";
|
|
982
|
+
entry.error =
|
|
983
|
+
`Remote script ${entry.id} changed while it was being read: ` +
|
|
984
|
+
`expected ${advertisedRemoteHash}, received ${remoteHash}.`;
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
entry.remoteFileHash = remoteHash;
|
|
988
|
+
if (localContent === null) {
|
|
989
|
+
await atomicWrite(path, remoteContent);
|
|
990
|
+
entry.localHash = remoteHash;
|
|
991
|
+
entry.lastSyncedHash = remoteHash;
|
|
992
|
+
entry.downloaded = true;
|
|
993
|
+
entry.status = "synced";
|
|
994
|
+
delete entry.legacyLastSyncedSha256;
|
|
995
|
+
delete entry.pendingRemoteHash;
|
|
996
|
+
delete entry.error;
|
|
997
|
+
return;
|
|
998
|
+
}
|
|
999
|
+
if (!localHash)
|
|
1000
|
+
throw new Error(`Could not hash local script ${entry.id}.`);
|
|
1001
|
+
if (localHash === remoteHash) {
|
|
1002
|
+
entry.localHash = localHash;
|
|
1003
|
+
entry.lastSyncedHash = localHash;
|
|
1004
|
+
entry.downloaded = true;
|
|
1005
|
+
entry.status = "synced";
|
|
1006
|
+
delete entry.legacyLastSyncedSha256;
|
|
1007
|
+
delete entry.pendingRemoteHash;
|
|
1008
|
+
delete entry.error;
|
|
1009
|
+
return;
|
|
1010
|
+
}
|
|
1011
|
+
if (baseline) {
|
|
1012
|
+
if (localHash === baseline) {
|
|
1013
|
+
await atomicWrite(path, remoteContent);
|
|
1014
|
+
entry.localHash = remoteHash;
|
|
1015
|
+
entry.lastSyncedHash = remoteHash;
|
|
1016
|
+
entry.downloaded = true;
|
|
1017
|
+
entry.status = "synced";
|
|
1018
|
+
delete entry.legacyLastSyncedSha256;
|
|
1019
|
+
delete entry.pendingRemoteHash;
|
|
1020
|
+
delete entry.error;
|
|
1021
|
+
return;
|
|
1022
|
+
}
|
|
1023
|
+
if (remoteHash === baseline) {
|
|
1024
|
+
await this.#uploadScript(record, entry, localContent, localHash);
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
await this.#writeConflict(record, entry, localContent, remoteContent);
|
|
1028
|
+
return;
|
|
1029
|
+
}
|
|
1030
|
+
const legacyBaseline = old?.legacyLastSyncedSha256;
|
|
1031
|
+
if (legacyBaseline && localBytes) {
|
|
1032
|
+
const localChangedFromLegacy = hashLegacyContent(localBytes) !== legacyBaseline;
|
|
1033
|
+
const remoteChangedFromLegacy = hashLegacyContent(remoteContent) !== legacyBaseline;
|
|
1034
|
+
if (!localChangedFromLegacy) {
|
|
1035
|
+
await atomicWrite(path, remoteContent);
|
|
1036
|
+
entry.localHash = remoteHash;
|
|
1037
|
+
entry.lastSyncedHash = remoteHash;
|
|
1038
|
+
entry.downloaded = true;
|
|
1039
|
+
entry.status = "synced";
|
|
1040
|
+
delete entry.legacyLastSyncedSha256;
|
|
1041
|
+
delete entry.pendingRemoteHash;
|
|
1042
|
+
delete entry.error;
|
|
1043
|
+
return;
|
|
1044
|
+
}
|
|
1045
|
+
if (!remoteChangedFromLegacy) {
|
|
1046
|
+
await this.#uploadScript(record, entry, localContent, localHash);
|
|
1047
|
+
return;
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
await this.#writeConflict(record, entry, localContent, remoteContent);
|
|
1051
|
+
}
|
|
1052
|
+
async #uploadScript(record, entry, localContent, localHash) {
|
|
1053
|
+
if (record.syncProgress) {
|
|
1054
|
+
record.syncProgress.assetId = entry.id;
|
|
1055
|
+
record.syncProgress.action = "uploading";
|
|
1056
|
+
}
|
|
1057
|
+
const writeResponse = await this.#requestTarget(record.targetId, "bridge:writeScriptText", { assetId: entry.id, text: localContent }, 60000);
|
|
1058
|
+
if (!writeResponse.ok) {
|
|
1059
|
+
entry.localHash = localHash;
|
|
1060
|
+
entry.status = "local-change";
|
|
1061
|
+
entry.error = writeResponse.error.message;
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
entry.localHash = localHash;
|
|
1065
|
+
entry.pendingRemoteHash = localHash;
|
|
1066
|
+
entry.downloaded = true;
|
|
1067
|
+
entry.status = "local-change";
|
|
1068
|
+
delete entry.legacyLastSyncedSha256;
|
|
1069
|
+
entry.error = "Waiting for PlayCanvas to confirm the uploaded file hash.";
|
|
1070
|
+
}
|
|
1071
|
+
async #writeConflict(record, entry, localContent, remoteContent) {
|
|
1072
|
+
if (record.syncProgress) {
|
|
1073
|
+
record.syncProgress.assetId = entry.id;
|
|
1074
|
+
record.syncProgress.action = "conflict";
|
|
1075
|
+
}
|
|
1076
|
+
const conflictBase = join(record.tmpDirectory, "conflicts", `${entry.id}-${safeWorkspaceName(entry.filename || entry.name, `script-${entry.id}`)}`);
|
|
1077
|
+
await atomicWrite(`${conflictBase}.local`, localContent);
|
|
1078
|
+
await atomicWrite(`${conflictBase}.remote`, remoteContent);
|
|
1079
|
+
entry.localHash = hashContent(localContent);
|
|
1080
|
+
entry.downloaded = true;
|
|
1081
|
+
entry.status = "conflict";
|
|
1082
|
+
entry.error = `Local and remote script changed since the last sync. See ${relative(record.directory, conflictBase)}.*`;
|
|
1083
|
+
}
|
|
1084
|
+
#status(record) {
|
|
1085
|
+
const entries = Object.values(record.index.entries);
|
|
1086
|
+
const scripts = entries.filter((entry) => entry.type === "script");
|
|
1087
|
+
const downloadable = entries.filter((entry) => entry.localPath && entry.type !== "script");
|
|
1088
|
+
return {
|
|
1089
|
+
available: true,
|
|
1090
|
+
state: record.state,
|
|
1091
|
+
rootDirectory: this.rootDir,
|
|
1092
|
+
projectDirectory: record.directory,
|
|
1093
|
+
assetsDirectory: record.assetsDirectory,
|
|
1094
|
+
tmpDirectory: record.tmpDirectory,
|
|
1095
|
+
projectId: record.projectId,
|
|
1096
|
+
projectName: record.projectName,
|
|
1097
|
+
branchId: record.branchId,
|
|
1098
|
+
branchName: record.branchName,
|
|
1099
|
+
connected: record.connected,
|
|
1100
|
+
lastSyncedAt: record.lastSyncedAt,
|
|
1101
|
+
lastError: record.lastError,
|
|
1102
|
+
lastWarning: record.lastWarning,
|
|
1103
|
+
progress: record.syncPhase && record.syncStartedAt
|
|
1104
|
+
? {
|
|
1105
|
+
phase: record.syncPhase,
|
|
1106
|
+
startedAt: record.syncStartedAt,
|
|
1107
|
+
...(record.syncProgress || {}),
|
|
1108
|
+
}
|
|
1109
|
+
: null,
|
|
1110
|
+
counts: {
|
|
1111
|
+
assets: entries.filter((entry) => entry.type !== "folder").length,
|
|
1112
|
+
folders: entries.filter((entry) => entry.type === "folder").length,
|
|
1113
|
+
scripts: scripts.length,
|
|
1114
|
+
scriptsSynced: scripts.filter((entry) => entry.status === "synced").length,
|
|
1115
|
+
localChanges: entries.filter((entry) => entry.status === "local-change").length,
|
|
1116
|
+
remoteChanges: entries.filter((entry) => entry.status === "remote-change").length,
|
|
1117
|
+
conflicts: entries.filter((entry) => entry.status === "conflict").length,
|
|
1118
|
+
lazyAssets: downloadable.filter((entry) => !entry.downloaded).length,
|
|
1119
|
+
downloadedAssets: downloadable.filter((entry) => entry.downloaded).length,
|
|
1120
|
+
},
|
|
1121
|
+
};
|
|
1122
|
+
}
|
|
1123
|
+
}
|