playcanvas-agent-bridge-cli 0.6.2 → 0.7.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 +71 -10
- package/README.zh-CN.md +68 -10
- package/dist/cli.js +384 -89
- package/dist/config.js +23 -1
- package/dist/daemon/server.js +259 -29
- package/dist/plugins/host.js +260 -0
- package/dist/plugins/store.js +567 -0
- package/dist/updates.js +475 -0
- package/extension/isolated.js +12 -3
- package/extension/main.js +72 -246
- package/extension/manifest.json +1 -1
- package/extension/popup.html +82 -1
- package/extension/popup.js +257 -4
- package/extension/service-worker.js +99 -5
- package/package.json +7 -8
- package/plugins/index.json +14 -0
- package/plugins/tinyapp-builder/node/builder.js +589 -0
- package/plugins/tinyapp-builder/node/index.js +30 -0
- package/plugins/tinyapp-builder/package.json +13 -0
- package/plugins/tinyapp-builder/page/editor.js +249 -0
- package/plugins/tinyapp-builder/pcbridge-plugin.json +28 -0
- package/skills/claude/pcbridge-plugin-authoring/SKILL.md +220 -0
- package/skills/claude/playcanvas-agent-bridge-cli/SKILL.md +24 -18
- package/skills/codex/pcbridge-plugin-authoring/SKILL.md +220 -0
- package/skills/codex/pcbridge-plugin-authoring/agents/openai.yaml +4 -0
- package/skills/codex/playcanvas-agent-bridge-cli/SKILL.md +32 -20
- package/skills/cursor/pcbridge-plugin-authoring.mdc +221 -0
- package/skills/cursor/playcanvas-agent-bridge-cli.mdc +14 -13
- package/skills/windsurf/pcbridge-plugin-authoring.md +215 -0
- package/skills/windsurf/playcanvas-agent-bridge-cli.md +14 -13
- package/dist/builder/manager.js +0 -564
package/dist/builder/manager.js
DELETED
|
@@ -1,564 +0,0 @@
|
|
|
1
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { createReadStream, existsSync } from "node:fs";
|
|
3
|
-
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
4
|
-
import { extname, join } from "node:path";
|
|
5
|
-
import { PutObjectCommand, S3Client, } from "@aws-sdk/client-s3";
|
|
6
|
-
import { transformAsync } from "@babel/core";
|
|
7
|
-
import presetEnv from "@babel/preset-env";
|
|
8
|
-
import { parse as parseEnv } from "dotenv";
|
|
9
|
-
import { minify } from "terser";
|
|
10
|
-
const OMITTED_ASSET_FIELDS = new Set([
|
|
11
|
-
"uniqueId",
|
|
12
|
-
"createdAt",
|
|
13
|
-
"modifiedAt",
|
|
14
|
-
"scope",
|
|
15
|
-
"user_id",
|
|
16
|
-
"source_asset_id",
|
|
17
|
-
"source",
|
|
18
|
-
"revision",
|
|
19
|
-
"region",
|
|
20
|
-
"task",
|
|
21
|
-
"path",
|
|
22
|
-
"has_thumbnail",
|
|
23
|
-
"thumbnail",
|
|
24
|
-
"thumbnails",
|
|
25
|
-
]);
|
|
26
|
-
const ENV_EXAMPLE = `# Copy to .env and fill in the values. A project .env overrides the workspace .env.\n\
|
|
27
|
-
PCBRIDGE_S3_ENDPOINT=https://s3.example.com\n\
|
|
28
|
-
PCBRIDGE_S3_REGION=us-east-1\n\
|
|
29
|
-
PCBRIDGE_S3_BUCKET=my-bucket\n\
|
|
30
|
-
PCBRIDGE_S3_ACCESS_KEY_ID=\n\
|
|
31
|
-
PCBRIDGE_S3_SECRET_ACCESS_KEY=\n\
|
|
32
|
-
# PCBRIDGE_S3_SESSION_TOKEN=\n\
|
|
33
|
-
PCBRIDGE_S3_PUBLIC_BASE_URL=https://cdn.example.com\n\
|
|
34
|
-
PCBRIDGE_S3_PREFIX=assets\n\
|
|
35
|
-
PCBRIDGE_S3_FORCE_PATH_STYLE=false\n`;
|
|
36
|
-
function md5(value) {
|
|
37
|
-
return createHash("md5").update(value).digest("hex");
|
|
38
|
-
}
|
|
39
|
-
function clone(value) {
|
|
40
|
-
return JSON.parse(JSON.stringify(value));
|
|
41
|
-
}
|
|
42
|
-
export async function compileGameScript(code) {
|
|
43
|
-
const transformed = await transformAsync(code, {
|
|
44
|
-
babelrc: false,
|
|
45
|
-
configFile: false,
|
|
46
|
-
sourceType: "script",
|
|
47
|
-
comments: false,
|
|
48
|
-
presets: [[presetEnv, {
|
|
49
|
-
targets: { ie: "11" },
|
|
50
|
-
modules: false,
|
|
51
|
-
useBuiltIns: false,
|
|
52
|
-
}]],
|
|
53
|
-
});
|
|
54
|
-
if (!transformed?.code)
|
|
55
|
-
throw new Error("Babel produced no ES5 game script output.");
|
|
56
|
-
const compressed = await minify(transformed.code, {
|
|
57
|
-
ecma: 5,
|
|
58
|
-
compress: { arrows: false },
|
|
59
|
-
mangle: true,
|
|
60
|
-
keep_classnames: true,
|
|
61
|
-
keep_fnames: true,
|
|
62
|
-
format: {
|
|
63
|
-
comments: false,
|
|
64
|
-
ecma: 5,
|
|
65
|
-
},
|
|
66
|
-
});
|
|
67
|
-
if (!compressed.code)
|
|
68
|
-
throw new Error("Terser produced no compressed game script output.");
|
|
69
|
-
return `${compressed.code}\n`;
|
|
70
|
-
}
|
|
71
|
-
async function mapWithConcurrency(values, limit, operation) {
|
|
72
|
-
const results = new Array(values.length);
|
|
73
|
-
let cursor = 0;
|
|
74
|
-
const worker = async () => {
|
|
75
|
-
while (cursor < values.length) {
|
|
76
|
-
const index = cursor++;
|
|
77
|
-
results[index] = await operation(values[index], index);
|
|
78
|
-
}
|
|
79
|
-
};
|
|
80
|
-
await Promise.all(Array.from({ length: Math.min(limit, values.length) }, () => worker()));
|
|
81
|
-
return results;
|
|
82
|
-
}
|
|
83
|
-
function envValue(env, ...names) {
|
|
84
|
-
for (const name of names) {
|
|
85
|
-
const value = env[name];
|
|
86
|
-
if (value && value.trim())
|
|
87
|
-
return value.trim();
|
|
88
|
-
}
|
|
89
|
-
return undefined;
|
|
90
|
-
}
|
|
91
|
-
function booleanValue(value, fallback = false) {
|
|
92
|
-
if (!value)
|
|
93
|
-
return fallback;
|
|
94
|
-
return ["1", "true", "yes", "on"].includes(value.toLowerCase());
|
|
95
|
-
}
|
|
96
|
-
function normalizePrefix(value) {
|
|
97
|
-
const parts = String(value || "assets")
|
|
98
|
-
.replaceAll("\\", "/")
|
|
99
|
-
.split("/")
|
|
100
|
-
.map((part) => part.trim())
|
|
101
|
-
.filter(Boolean);
|
|
102
|
-
if (parts.some((part) => part === "." || part === "..")) {
|
|
103
|
-
throw new Error("S3 upload prefix cannot contain . or .. path segments.");
|
|
104
|
-
}
|
|
105
|
-
return parts.join("/");
|
|
106
|
-
}
|
|
107
|
-
function safeSegment(value, fallback) {
|
|
108
|
-
const result = value
|
|
109
|
-
.normalize("NFKC")
|
|
110
|
-
.replace(/[<>:"/\\|?*\u0000-\u001f]/g, "-")
|
|
111
|
-
.replace(/[. ]+$/g, "")
|
|
112
|
-
.trim()
|
|
113
|
-
.slice(0, 120);
|
|
114
|
-
return result || fallback;
|
|
115
|
-
}
|
|
116
|
-
function timestamp() {
|
|
117
|
-
const date = new Date();
|
|
118
|
-
const part = (value) => String(value).padStart(2, "0");
|
|
119
|
-
return `${date.getFullYear()}_${part(date.getMonth() + 1)}_${part(date.getDate())}-` +
|
|
120
|
-
`${part(date.getHours())}_${part(date.getMinutes())}_${part(date.getSeconds())}`;
|
|
121
|
-
}
|
|
122
|
-
function workspaceResourceKey(assetId, filename) {
|
|
123
|
-
return `${assetId}\0${filename.normalize("NFKC").toLocaleLowerCase()}`;
|
|
124
|
-
}
|
|
125
|
-
function contentType(path) {
|
|
126
|
-
const types = {
|
|
127
|
-
".bin": "application/octet-stream",
|
|
128
|
-
".css": "text/css",
|
|
129
|
-
".gif": "image/gif",
|
|
130
|
-
".glb": "model/gltf-binary",
|
|
131
|
-
".gltf": "model/gltf+json",
|
|
132
|
-
".jpeg": "image/jpeg",
|
|
133
|
-
".jpg": "image/jpeg",
|
|
134
|
-
".js": "text/javascript; charset=utf-8",
|
|
135
|
-
".json": "application/json; charset=utf-8",
|
|
136
|
-
".mp3": "audio/mpeg",
|
|
137
|
-
".mp4": "video/mp4",
|
|
138
|
-
".ogg": "audio/ogg",
|
|
139
|
-
".png": "image/png",
|
|
140
|
-
".wasm": "application/wasm",
|
|
141
|
-
".webm": "video/webm",
|
|
142
|
-
".webp": "image/webp",
|
|
143
|
-
};
|
|
144
|
-
return types[extname(path).toLowerCase()] || "application/octet-stream";
|
|
145
|
-
}
|
|
146
|
-
function publicObjectUrl(base, key) {
|
|
147
|
-
const encoded = key.split("/").map(encodeURIComponent).join("/");
|
|
148
|
-
return `${base.replace(/\/$/, "")}/${encoded}`;
|
|
149
|
-
}
|
|
150
|
-
export function normalizeS3Endpoint(endpoint, bucket) {
|
|
151
|
-
if (!endpoint)
|
|
152
|
-
return undefined;
|
|
153
|
-
try {
|
|
154
|
-
const parsed = new URL(endpoint);
|
|
155
|
-
const bucketPrefix = `${bucket.toLowerCase()}.`;
|
|
156
|
-
if (!parsed.hostname.toLowerCase().startsWith(bucketPrefix))
|
|
157
|
-
return endpoint;
|
|
158
|
-
parsed.hostname = parsed.hostname.slice(bucketPrefix.length);
|
|
159
|
-
return parsed.toString().replace(/\/$/, "");
|
|
160
|
-
}
|
|
161
|
-
catch {
|
|
162
|
-
return endpoint;
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
function sanitizeAsset(asset) {
|
|
166
|
-
const result = clone(asset);
|
|
167
|
-
for (const field of OMITTED_ASSET_FIELDS)
|
|
168
|
-
delete result[field];
|
|
169
|
-
if (result.type === "material") {
|
|
170
|
-
result.data ||= {};
|
|
171
|
-
if (!result.data.shader)
|
|
172
|
-
result.data.shader = "blinn";
|
|
173
|
-
}
|
|
174
|
-
return result;
|
|
175
|
-
}
|
|
176
|
-
async function readEnvFile(path) {
|
|
177
|
-
if (!existsSync(path))
|
|
178
|
-
return {};
|
|
179
|
-
return parseEnv(await readFile(path, "utf8"));
|
|
180
|
-
}
|
|
181
|
-
async function loadS3Settings(rootDir, projectDirectory) {
|
|
182
|
-
const workspacePath = join(rootDir, ".env");
|
|
183
|
-
const projectPath = join(projectDirectory, ".env");
|
|
184
|
-
if (!existsSync(workspacePath) && !existsSync(projectPath)) {
|
|
185
|
-
await writeFile(join(rootDir, ".env.example"), ENV_EXAMPLE, { flag: "wx" }).catch(() => undefined);
|
|
186
|
-
}
|
|
187
|
-
const processValues = Object.fromEntries(Object.entries(process.env).filter((entry) => typeof entry[1] === "string"));
|
|
188
|
-
const workspaceValues = await readEnvFile(workspacePath);
|
|
189
|
-
const projectValues = await readEnvFile(projectPath);
|
|
190
|
-
const env = { ...processValues, ...workspaceValues, ...projectValues };
|
|
191
|
-
const source = existsSync(projectPath)
|
|
192
|
-
? "project"
|
|
193
|
-
: existsSync(workspacePath) ? "workspace" : "environment";
|
|
194
|
-
const endpoint = envValue(env, "PCBRIDGE_S3_ENDPOINT", "S3_ENDPOINT");
|
|
195
|
-
const region = envValue(env, "PCBRIDGE_S3_REGION", "AWS_REGION", "S3_REGION") || "us-east-1";
|
|
196
|
-
const bucket = envValue(env, "PCBRIDGE_S3_BUCKET", "S3_BUCKET");
|
|
197
|
-
const accessKeyId = envValue(env, "PCBRIDGE_S3_ACCESS_KEY_ID", "AWS_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID");
|
|
198
|
-
const secretAccessKey = envValue(env, "PCBRIDGE_S3_SECRET_ACCESS_KEY", "AWS_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY");
|
|
199
|
-
const sessionToken = envValue(env, "PCBRIDGE_S3_SESSION_TOKEN", "AWS_SESSION_TOKEN", "S3_SESSION_TOKEN");
|
|
200
|
-
if (!bucket)
|
|
201
|
-
throw new Error("Missing PCBRIDGE_S3_BUCKET in the project or workspace .env file.");
|
|
202
|
-
if (!accessKeyId || !secretAccessKey) {
|
|
203
|
-
throw new Error("Missing PCBRIDGE_S3_ACCESS_KEY_ID or PCBRIDGE_S3_SECRET_ACCESS_KEY in the project or workspace .env file.");
|
|
204
|
-
}
|
|
205
|
-
const configuredBase = envValue(env, "PCBRIDGE_S3_PUBLIC_BASE_URL", "S3_PUBLIC_BASE_URL");
|
|
206
|
-
let publicBaseUrl = configuredBase;
|
|
207
|
-
if (!publicBaseUrl && endpoint)
|
|
208
|
-
publicBaseUrl = `${endpoint.replace(/\/$/, "")}/${bucket}`;
|
|
209
|
-
if (!publicBaseUrl)
|
|
210
|
-
publicBaseUrl = `https://${bucket}.s3.${region}.amazonaws.com`;
|
|
211
|
-
return {
|
|
212
|
-
client: new S3Client({
|
|
213
|
-
region,
|
|
214
|
-
endpoint: normalizeS3Endpoint(endpoint, bucket),
|
|
215
|
-
requestChecksumCalculation: "WHEN_REQUIRED",
|
|
216
|
-
forcePathStyle: booleanValue(envValue(env, "PCBRIDGE_S3_FORCE_PATH_STYLE", "S3_FORCE_PATH_STYLE"), false),
|
|
217
|
-
credentials: { accessKeyId, secretAccessKey, sessionToken },
|
|
218
|
-
}),
|
|
219
|
-
bucket,
|
|
220
|
-
defaultPrefix: normalizePrefix(envValue(env, "PCBRIDGE_S3_PREFIX", "S3_PREFIX")),
|
|
221
|
-
publicBaseUrl,
|
|
222
|
-
source,
|
|
223
|
-
};
|
|
224
|
-
}
|
|
225
|
-
function descriptorFrom(value) {
|
|
226
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
227
|
-
throw new Error("PlayCanvas returned an invalid Template dependency descriptor.");
|
|
228
|
-
}
|
|
229
|
-
const candidate = value;
|
|
230
|
-
if (!candidate.template || !Array.isArray(candidate.assets)) {
|
|
231
|
-
throw new Error("PlayCanvas returned an incomplete Template dependency descriptor.");
|
|
232
|
-
}
|
|
233
|
-
return {
|
|
234
|
-
template: candidate.template,
|
|
235
|
-
assets: candidate.assets,
|
|
236
|
-
scripts: Array.isArray(candidate.scripts) ? candidate.scripts : [],
|
|
237
|
-
childTemplateIds: Array.isArray(candidate.childTemplateIds) ? candidate.childTemplateIds.map(String) : [],
|
|
238
|
-
projectUrl: typeof candidate.projectUrl === "string" ? candidate.projectUrl : null,
|
|
239
|
-
sceneUrl: typeof candidate.sceneUrl === "string" ? candidate.sceneUrl : null,
|
|
240
|
-
};
|
|
241
|
-
}
|
|
242
|
-
export class BuilderManager {
|
|
243
|
-
rootDir;
|
|
244
|
-
#requestTarget;
|
|
245
|
-
#workspace;
|
|
246
|
-
#jobs = new Map();
|
|
247
|
-
#activeRuns = new Set();
|
|
248
|
-
#activeClients = new Set();
|
|
249
|
-
#closing = false;
|
|
250
|
-
constructor(options) {
|
|
251
|
-
this.rootDir = options.rootDir;
|
|
252
|
-
this.#requestTarget = options.requestTarget;
|
|
253
|
-
this.#workspace = options.workspace;
|
|
254
|
-
}
|
|
255
|
-
start(info, templateAssetId, options = {}) {
|
|
256
|
-
if (this.#closing)
|
|
257
|
-
throw new Error("Tiny Builder is stopping with the daemon.");
|
|
258
|
-
const now = new Date().toISOString();
|
|
259
|
-
const job = {
|
|
260
|
-
id: `build_${randomUUID()}`,
|
|
261
|
-
target: info.id,
|
|
262
|
-
templateAssetId,
|
|
263
|
-
state: "queued",
|
|
264
|
-
message: "Queued",
|
|
265
|
-
completedFiles: 0,
|
|
266
|
-
totalFiles: 0,
|
|
267
|
-
createdAt: now,
|
|
268
|
-
updatedAt: now,
|
|
269
|
-
outputPath: null,
|
|
270
|
-
publicUrl: null,
|
|
271
|
-
configSource: null,
|
|
272
|
-
error: null,
|
|
273
|
-
info,
|
|
274
|
-
options,
|
|
275
|
-
};
|
|
276
|
-
this.#jobs.set(job.id, job);
|
|
277
|
-
while (this.#jobs.size > 100)
|
|
278
|
-
this.#jobs.delete(this.#jobs.keys().next().value);
|
|
279
|
-
const run = this.#run(job);
|
|
280
|
-
this.#activeRuns.add(run);
|
|
281
|
-
void run.finally(() => this.#activeRuns.delete(run));
|
|
282
|
-
return this.#publicJob(job);
|
|
283
|
-
}
|
|
284
|
-
async close() {
|
|
285
|
-
this.#closing = true;
|
|
286
|
-
for (const client of this.#activeClients)
|
|
287
|
-
client.destroy();
|
|
288
|
-
await Promise.allSettled(this.#activeRuns);
|
|
289
|
-
}
|
|
290
|
-
get(jobId) {
|
|
291
|
-
const job = this.#jobs.get(jobId);
|
|
292
|
-
return job ? this.#publicJob(job) : null;
|
|
293
|
-
}
|
|
294
|
-
#update(job, values) {
|
|
295
|
-
Object.assign(job, values, { updatedAt: new Date().toISOString() });
|
|
296
|
-
}
|
|
297
|
-
#publicJob(job) {
|
|
298
|
-
const { info: _info, options: _options, ...status } = job;
|
|
299
|
-
return status;
|
|
300
|
-
}
|
|
301
|
-
async #descriptor(info, assetId) {
|
|
302
|
-
const response = await this.#requestTarget(info.id, "bridge:collectTemplateDependencies", { assetId }, 60000);
|
|
303
|
-
if (!response.ok)
|
|
304
|
-
throw new Error(response.error.message);
|
|
305
|
-
return descriptorFrom(response.data);
|
|
306
|
-
}
|
|
307
|
-
async #run(job) {
|
|
308
|
-
let activeClient = null;
|
|
309
|
-
try {
|
|
310
|
-
if (this.#closing)
|
|
311
|
-
throw new Error("Build cancelled because the daemon is stopping.");
|
|
312
|
-
this.#update(job, { state: "collecting", message: "Collecting Template dependencies" });
|
|
313
|
-
const descriptors = new Map();
|
|
314
|
-
const visit = async (assetId, stack) => {
|
|
315
|
-
if (descriptors.has(assetId))
|
|
316
|
-
return;
|
|
317
|
-
if (stack.has(assetId))
|
|
318
|
-
throw new Error(`Template dependency cycle detected at asset ${assetId}.`);
|
|
319
|
-
const nextStack = new Set(stack).add(assetId);
|
|
320
|
-
const descriptor = await this.#descriptor(job.info, assetId);
|
|
321
|
-
descriptors.set(assetId, descriptor);
|
|
322
|
-
for (const childId of descriptor.childTemplateIds)
|
|
323
|
-
await visit(childId, nextStack);
|
|
324
|
-
};
|
|
325
|
-
await visit(job.templateAssetId, new Set());
|
|
326
|
-
this.#update(job, { state: "syncing", message: "Synchronizing dependency files" });
|
|
327
|
-
const allAssetIds = new Set();
|
|
328
|
-
for (const descriptor of descriptors.values()) {
|
|
329
|
-
for (const asset of descriptor.assets)
|
|
330
|
-
allAssetIds.add(String(asset.id));
|
|
331
|
-
}
|
|
332
|
-
const prepared = await this.#workspace.prepareAssetFiles(job.info, [...allAssetIds]);
|
|
333
|
-
const preparedById = new Map(prepared.assets.map((asset) => [asset.id, asset]));
|
|
334
|
-
const resourceRequests = new Map();
|
|
335
|
-
for (const descriptor of descriptors.values()) {
|
|
336
|
-
for (const asset of descriptor.assets) {
|
|
337
|
-
const id = String(asset.id);
|
|
338
|
-
for (const variant of Object.values(asset.file?.variants || {})) {
|
|
339
|
-
if (!variant.url || !variant.filename)
|
|
340
|
-
continue;
|
|
341
|
-
resourceRequests.set(workspaceResourceKey(id, variant.filename), {
|
|
342
|
-
assetId: id,
|
|
343
|
-
filename: variant.filename,
|
|
344
|
-
url: variant.url,
|
|
345
|
-
hash: variant.hash,
|
|
346
|
-
});
|
|
347
|
-
}
|
|
348
|
-
const fontMaps = asset.type === "font" && Array.isArray(asset.data?.info &&
|
|
349
|
-
asset.data.info.maps)
|
|
350
|
-
? asset.data.info.maps
|
|
351
|
-
: [];
|
|
352
|
-
if (!asset.file?.url || !asset.file.filename || fontMaps.length <= 1)
|
|
353
|
-
continue;
|
|
354
|
-
for (let index = 1; index < fontMaps.length; index += 1) {
|
|
355
|
-
const filename = asset.file.filename.replace(/(\.[^.]*)$/, `${index}$1`);
|
|
356
|
-
const url = asset.file.url.replace(/(\.[^.]*)$/, `${index}$1`);
|
|
357
|
-
resourceRequests.set(workspaceResourceKey(id, filename), {
|
|
358
|
-
assetId: id,
|
|
359
|
-
filename,
|
|
360
|
-
url,
|
|
361
|
-
});
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
const preparedResources = await this.#workspace.prepareAssetResources(job.info, [...resourceRequests.values()]);
|
|
366
|
-
const preparedResourceByKey = new Map(preparedResources.map((resource) => [
|
|
367
|
-
workspaceResourceKey(resource.assetId, resource.filename),
|
|
368
|
-
resource,
|
|
369
|
-
]));
|
|
370
|
-
const settings = await loadS3Settings(this.rootDir, prepared.projectDirectory);
|
|
371
|
-
activeClient = settings.client;
|
|
372
|
-
this.#activeClients.add(activeClient);
|
|
373
|
-
if (this.#closing)
|
|
374
|
-
throw new Error("Build cancelled because the daemon is stopping.");
|
|
375
|
-
job.configSource = settings.source;
|
|
376
|
-
const prefix = normalizePrefix(job.options.prefix || settings.defaultPrefix);
|
|
377
|
-
const uploads = new Map();
|
|
378
|
-
const built = new Map();
|
|
379
|
-
const buildTemplate = async (assetId) => {
|
|
380
|
-
const existing = built.get(assetId);
|
|
381
|
-
if (existing)
|
|
382
|
-
return existing;
|
|
383
|
-
const descriptor = descriptors.get(assetId);
|
|
384
|
-
if (!descriptor)
|
|
385
|
-
throw new Error(`Missing descriptor for Template ${assetId}.`);
|
|
386
|
-
for (const childId of descriptor.childTemplateIds)
|
|
387
|
-
await buildTemplate(childId);
|
|
388
|
-
const suffix = String(job.options.suffix || "").replaceAll("${time}", timestamp());
|
|
389
|
-
const buildName = safeSegment(`${descriptor.template.name}${suffix}`, `template-${assetId}`);
|
|
390
|
-
const buildRoot = join(prepared.tmpDirectory, "builds", buildName);
|
|
391
|
-
await mkdir(buildRoot, { recursive: true });
|
|
392
|
-
const rootData = {
|
|
393
|
-
projectUrl: descriptor.projectUrl,
|
|
394
|
-
sceneUrl: descriptor.sceneUrl,
|
|
395
|
-
template: clone(descriptor.template.data || {}),
|
|
396
|
-
assets: {},
|
|
397
|
-
};
|
|
398
|
-
const templateData = rootData.template;
|
|
399
|
-
const entities = templateData.entities && typeof templateData.entities === "object"
|
|
400
|
-
? templateData.entities
|
|
401
|
-
: {};
|
|
402
|
-
for (const entity of Object.values(entities)) {
|
|
403
|
-
const attributes = entity.components?.script;
|
|
404
|
-
const scripts = attributes?.scripts;
|
|
405
|
-
const handler = scripts?.sdsTinyRootHandler;
|
|
406
|
-
const values = handler?.attributes;
|
|
407
|
-
const childId = values && Number.isInteger(values.testTemplate)
|
|
408
|
-
? String(values.testTemplate)
|
|
409
|
-
: null;
|
|
410
|
-
if (!childId || !built.has(childId))
|
|
411
|
-
continue;
|
|
412
|
-
delete values.testTemplate;
|
|
413
|
-
values.type = "TinyApp";
|
|
414
|
-
values.tinyAppUrl = built.get(childId).publicUrl;
|
|
415
|
-
}
|
|
416
|
-
const assetOutput = rootData.assets;
|
|
417
|
-
const scriptIds = new Set(descriptor.scripts.map((script) => script.assetId));
|
|
418
|
-
for (const asset of descriptor.assets) {
|
|
419
|
-
const id = String(asset.id);
|
|
420
|
-
if (scriptIds.has(id) || asset.type === "script")
|
|
421
|
-
continue;
|
|
422
|
-
const output = sanitizeAsset(asset);
|
|
423
|
-
const originalFileUrl = asset.file?.url;
|
|
424
|
-
const originalFilename = asset.file?.filename;
|
|
425
|
-
const local = preparedById.get(id);
|
|
426
|
-
if (output.file && local?.path && local.filename) {
|
|
427
|
-
const relativeUrl = `${buildName}/${id}/${safeSegment(local.filename, `asset-${id}`)}`;
|
|
428
|
-
const key = `${prefix}/${relativeUrl}`;
|
|
429
|
-
const hash = local.hash || md5(await readFile(local.path));
|
|
430
|
-
const fileInfo = await stat(local.path);
|
|
431
|
-
output.file.url = relativeUrl;
|
|
432
|
-
output.file.hash = hash;
|
|
433
|
-
output.file.size = fileInfo.size;
|
|
434
|
-
uploads.set(key, {
|
|
435
|
-
key,
|
|
436
|
-
path: local.path,
|
|
437
|
-
contentType: contentType(local.path),
|
|
438
|
-
hash,
|
|
439
|
-
});
|
|
440
|
-
}
|
|
441
|
-
for (const variant of Object.values(output.file?.variants || {})) {
|
|
442
|
-
if (!variant.url || !variant.filename)
|
|
443
|
-
continue;
|
|
444
|
-
const resource = preparedResourceByKey.get(workspaceResourceKey(id, variant.filename));
|
|
445
|
-
if (!resource) {
|
|
446
|
-
throw new Error(`Asset ${id} resource ${variant.filename} was not prepared.`);
|
|
447
|
-
}
|
|
448
|
-
const relativeUrl = `${buildName}/${id}/${safeSegment(variant.filename, "variant.bin")}`;
|
|
449
|
-
const key = `${prefix}/${relativeUrl}`;
|
|
450
|
-
variant.url = relativeUrl;
|
|
451
|
-
variant.hash = resource.hash;
|
|
452
|
-
uploads.set(key, {
|
|
453
|
-
key,
|
|
454
|
-
path: resource.path,
|
|
455
|
-
contentType: contentType(resource.path),
|
|
456
|
-
hash: resource.hash,
|
|
457
|
-
});
|
|
458
|
-
}
|
|
459
|
-
const fontMaps = asset.type === "font" && Array.isArray(asset.data?.info &&
|
|
460
|
-
asset.data.info.maps)
|
|
461
|
-
? asset.data.info.maps
|
|
462
|
-
: [];
|
|
463
|
-
if (originalFileUrl && originalFilename && fontMaps.length > 1) {
|
|
464
|
-
for (let index = 1; index < fontMaps.length; index += 1) {
|
|
465
|
-
const filename = originalFilename.replace(/(\.[^.]*)$/, `${index}$1`);
|
|
466
|
-
const url = originalFileUrl.replace(/(\.[^.]*)$/, `${index}$1`);
|
|
467
|
-
const resource = preparedResourceByKey.get(workspaceResourceKey(id, filename));
|
|
468
|
-
if (!resource) {
|
|
469
|
-
throw new Error(`Asset ${id} resource ${filename} was not prepared.`);
|
|
470
|
-
}
|
|
471
|
-
const key = `${prefix}/${buildName}/${id}/${safeSegment(filename, `font-map-${index}`)}`;
|
|
472
|
-
uploads.set(key, {
|
|
473
|
-
key,
|
|
474
|
-
path: resource.path,
|
|
475
|
-
contentType: contentType(resource.path),
|
|
476
|
-
hash: resource.hash,
|
|
477
|
-
});
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
assetOutput[id] = output;
|
|
481
|
-
}
|
|
482
|
-
let scriptText = "";
|
|
483
|
-
for (const script of descriptor.scripts) {
|
|
484
|
-
const local = preparedById.get(script.assetId);
|
|
485
|
-
if (!local?.path)
|
|
486
|
-
continue;
|
|
487
|
-
scriptText += `\n//-----script:${script.name}-----\n`;
|
|
488
|
-
scriptText += await readFile(local.path, "utf8");
|
|
489
|
-
scriptText += "\n";
|
|
490
|
-
}
|
|
491
|
-
if (scriptText.trim()) {
|
|
492
|
-
const gameScript = await compileGameScript(scriptText);
|
|
493
|
-
const scriptPath = join(buildRoot, "gamescript.js");
|
|
494
|
-
await writeFile(scriptPath, gameScript);
|
|
495
|
-
const relativeUrl = `${buildName}/gamescript.js`;
|
|
496
|
-
const key = `${prefix}/${relativeUrl}`;
|
|
497
|
-
rootData.scriptUrl = relativeUrl;
|
|
498
|
-
uploads.set(key, {
|
|
499
|
-
key,
|
|
500
|
-
path: scriptPath,
|
|
501
|
-
contentType: contentType(scriptPath),
|
|
502
|
-
hash: md5(gameScript),
|
|
503
|
-
});
|
|
504
|
-
}
|
|
505
|
-
const rootPath = join(buildRoot, "tinyapp.json");
|
|
506
|
-
const rootContent = `${JSON.stringify(rootData)}\n`;
|
|
507
|
-
await writeFile(rootPath, rootContent);
|
|
508
|
-
const key = `${prefix}/${buildName}/tinyapp.json`;
|
|
509
|
-
const result = { key, publicUrl: publicObjectUrl(settings.publicBaseUrl, key), buildName };
|
|
510
|
-
uploads.set(key, {
|
|
511
|
-
key,
|
|
512
|
-
path: rootPath,
|
|
513
|
-
contentType: contentType(rootPath),
|
|
514
|
-
hash: md5(rootContent),
|
|
515
|
-
});
|
|
516
|
-
built.set(assetId, result);
|
|
517
|
-
return result;
|
|
518
|
-
};
|
|
519
|
-
this.#update(job, { state: "preparing", message: "Preparing upload manifest" });
|
|
520
|
-
const root = await buildTemplate(job.templateAssetId);
|
|
521
|
-
job.totalFiles = uploads.size;
|
|
522
|
-
const uploadFiles = [...uploads.values()];
|
|
523
|
-
this.#update(job, { state: "uploading", message: `Uploading 0/${uploadFiles.length} files` });
|
|
524
|
-
await mapWithConcurrency(uploadFiles, 4, async (file) => {
|
|
525
|
-
if (this.#closing)
|
|
526
|
-
throw new Error("Build cancelled because the daemon is stopping.");
|
|
527
|
-
const info = await stat(file.path);
|
|
528
|
-
const input = {
|
|
529
|
-
Bucket: settings.bucket,
|
|
530
|
-
Key: file.key,
|
|
531
|
-
Body: createReadStream(file.path),
|
|
532
|
-
ContentLength: info.size,
|
|
533
|
-
ContentMD5: Buffer.from(file.hash, "hex").toString("base64"),
|
|
534
|
-
ContentType: file.contentType,
|
|
535
|
-
Metadata: { "pcbridge-md5": file.hash },
|
|
536
|
-
};
|
|
537
|
-
await settings.client.send(new PutObjectCommand(input));
|
|
538
|
-
job.completedFiles += 1;
|
|
539
|
-
this.#update(job, {
|
|
540
|
-
message: `Uploading ${job.completedFiles}/${uploadFiles.length} files`,
|
|
541
|
-
});
|
|
542
|
-
});
|
|
543
|
-
this.#update(job, {
|
|
544
|
-
state: "completed",
|
|
545
|
-
message: `Uploaded ${uploadFiles.length} files`,
|
|
546
|
-
outputPath: join(prepared.tmpDirectory, "builds", root.buildName, "tinyapp.json"),
|
|
547
|
-
publicUrl: root.publicUrl,
|
|
548
|
-
});
|
|
549
|
-
}
|
|
550
|
-
catch (error) {
|
|
551
|
-
this.#update(job, {
|
|
552
|
-
state: "error",
|
|
553
|
-
message: "Build failed",
|
|
554
|
-
error: error instanceof Error ? error.message : String(error),
|
|
555
|
-
});
|
|
556
|
-
}
|
|
557
|
-
finally {
|
|
558
|
-
if (activeClient) {
|
|
559
|
-
this.#activeClients.delete(activeClient);
|
|
560
|
-
activeClient.destroy();
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
}
|
|
564
|
-
}
|