playcanvas-agent-bridge-cli 0.5.3 → 0.6.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 CHANGED
@@ -20,7 +20,7 @@ npm install -g github:Q-My99/playcanvas-agent-bridge-cli
20
20
  pcbridge install-skill --agent all
21
21
  ```
22
22
 
23
- The commands documented below track repository version `0.5.3`. npm installs the latest stable
23
+ The commands documented below track repository version `0.6.0`. npm installs the latest stable
24
24
  release; use the GitHub install when testing changes that have not been released yet.
25
25
 
26
26
  One-shot with npx:
@@ -30,6 +30,67 @@ npx playcanvas-agent-bridge-cli doctor
30
30
  npx playcanvas-agent-bridge-cli install-skill --agent all
31
31
  ```
32
32
 
33
+ ## Update pcbridge components
34
+
35
+ The CLI/daemon, installed agent skills, generated Chrome extension, and optional custom Editor
36
+ frontend are separate local components. Updating one does not update the others automatically.
37
+
38
+ ### Update the CLI, daemon, and agent skills
39
+
40
+ First stop the running daemon with **Ctrl+C in the terminal where it was started**. There is no
41
+ `pcbridge daemon stop` command. Remember that terminal's working directory because it is the
42
+ workspace root and must be reused when the daemon starts again.
43
+
44
+ ```bash
45
+ npm install -g playcanvas-agent-bridge-cli@latest
46
+ pcbridge version
47
+ pcbridge install-skill --agent all
48
+ cd /the/same/workspace/root
49
+ pcbridge daemon start
50
+ ```
51
+
52
+ Installing the npm package replaces the CLI files, but an already-running daemon remains the old
53
+ in-memory version until it is restarted. Installed Codex, Claude, Cursor, and Windsurf skills are
54
+ also copies, so rerun `install-skill`; start a new agent task/session if the client has already
55
+ loaded the old skill.
56
+
57
+ ### Update the Chrome extension
58
+
59
+ After updating the CLI, regenerate the unpacked extension directory:
60
+
61
+ ```bash
62
+ pcbridge install-extension --no-open
63
+ ```
64
+
65
+ Then complete these **manual Chrome steps**:
66
+
67
+ 1. Open `chrome://extensions`.
68
+ 2. Find **PlayCanvas Agent Bridge** and click **Reload**. Loading it again is unnecessary when the
69
+ existing entry already points to `~/.pcbridge/extension`.
70
+ 3. If the extension is not installed, enable Developer Mode, click **Load unpacked**, and select the
71
+ directory printed by `pcbridge install-extension`.
72
+ 4. Refresh every open PlayCanvas Editor and Launch tab.
73
+ 5. After restarting the daemon, run `pcbridge doctor` and confirm the generated and connected
74
+ extension versions match the CLI.
75
+
76
+ Updating npm alone does not refresh `~/.pcbridge/extension`, and rewriting that directory does not
77
+ make Chrome reload an unpacked extension automatically.
78
+
79
+ ### Update the custom PlayCanvas Editor frontend
80
+
81
+ The custom frontend has its own release lifecycle and is not bundled with the CLI or extension:
82
+
83
+ ```bash
84
+ pcbridge frontend update
85
+ pcbridge frontend status
86
+ ```
87
+
88
+ `frontend update` downloads, verifies, and activates the latest published frontend by default. A
89
+ running daemon resolves the active release for each request, so a frontend-only update does not
90
+ require a daemon restart. The **manual step is to refresh the PlayCanvas Editor tab**. If the project
91
+ is currently using the official frontend, open the extension popup and choose **Use custom
92
+ frontend**. Previously downloaded frontend releases remain installed until explicitly removed.
93
+
33
94
  ## Install the Chrome extension
34
95
 
35
96
  Run:
@@ -105,9 +166,9 @@ When a ready Editor connects, pcbridge creates `<projectId>-<projectName>/` auto
105
166
  ```text
106
167
  1552681-pcbridge-test/
107
168
  ├── pcbridge.project.json # project metadata plus the agent-readable asset catalog
108
- ├── assets/ # PlayCanvas folder mirror; scripts eager, binary assets lazy
169
+ ├── assets/ # collision-safe projection of the PlayCanvas folder tree
109
170
  ├── tmp/ # builds, cache, conflicts, captures, and quarantined remote deletions
110
- └── .pcbridge/ # internal sync state; do not edit
171
+ └── .pcbridge/ # internal sync state and content-addressed object cache; do not edit
111
172
  ```
112
173
 
113
174
  Inspect or refresh the workspace with:
@@ -129,10 +190,21 @@ imported type; local folders are created remotely. Renames and moves preserve th
129
190
  a local file only clears the local cache and never deletes the remote Asset. The `tmp/` tree is
130
191
  agent-owned and excluded from workspace synchronization.
131
192
 
132
- `pcbridge.project.json` schema v2 stores every asset id, type, PlayCanvas folder, project-relative
133
- `assets/...` file path, download presence, and the remote/local/base MD5 values. Agents may read
134
- this catalog directly; the `assets` object is managed by pcbridge. An existing schema-v1 hidden
135
- asset index is migrated automatically and retained as `.pcbridge/asset-index.v1.json` for rollback.
193
+ PlayCanvas may create source and generated Assets with the same display name, for example a source
194
+ GLB plus Container/Model outputs or a font plus generated atlas files. The manifest keeps the remote
195
+ display `folder` separate from the unique local `projectionPath`. The real `file.filename` is used
196
+ when possible; only collisions receive `.__pc_<type>_<assetId>` before the extension. Source and
197
+ standalone projections are writable. Generated derivatives are lazy and read-only: pulling or
198
+ building them stores immutable bytes under `.pcbridge/objects/<assetId>/<md5>/`, and a local edit or
199
+ move is quarantined under `tmp/conflicts/` before the projection is restored.
200
+
201
+ `pcbridge.project.json` schema v3 records `origin` (`source`, `derived`, or `standalone`), advertised
202
+ and observed remote file metadata, the effective MD5, and local presence/writability/current/base
203
+ hashes. Texture variants, additional font maps, and similar build-only files are listed under
204
+ `local.resources`; they are read-only managed files beside the primary Asset projection. Agents may
205
+ read this catalog directly; the `assets` object is managed by pcbridge. Existing
206
+ schema-v1 and schema-v2 state is migrated automatically; the v1 hidden index is retained as
207
+ `.pcbridge/asset-index.v1.json` for rollback.
136
208
  An empty snapshot received while indexed assets exist is ignored, and a non-empty shrinking
137
209
  snapshot must repeat before files are moved to `tmp/trash/remote/`.
138
210
 
@@ -140,10 +212,14 @@ snapshot must repeat before files are moved to `tmp/trash/remote/`.
140
212
 
141
213
  Selecting a PlayCanvas Template Asset adds a **pcbridge Tiny Builder** section to the Attributes
142
214
  panel. **Build and upload to S3** collects recursive Asset references, attached scripts, and child
143
- Templates in the page. The daemon validates the workspace MD5 cache, downloads only missing or
144
- remote-updated files, and uploads objects concurrently without creating a ZIP. Generated
145
- `tinyapp.json` and `gamescript.js` files live under `tmp/builds/`; variants and additional font maps
146
- are cached under `tmp/cache/assets/`.
215
+ Templates in the page. The daemon materializes every dependency under `assets/`: an existing local
216
+ file is reused when it matches the effective remote MD5, while a missing or remote-updated file is
217
+ synchronized from PlayCanvas first. Texture variants and additional font maps are stored beside the
218
+ primary Asset as managed read-only resources, not under `tmp/cache/assets/`. The internal
219
+ `.pcbridge/objects/` cache avoids repeat downloads, and uploads run concurrently without creating a
220
+ ZIP. Attached non-`sds*` scripts are merged, transpiled to ES5 with Babel, and conservatively
221
+ compressed with Terser while preserving function and class names. Only generated `tinyapp.json`
222
+ and `gamescript.js` files live under `tmp/builds/`.
147
223
 
148
224
  Create `.env` in the directory where the daemon starts for workspace defaults, or in a project
149
225
  directory for per-project values. Project values override workspace values field by field. Do not
@@ -163,7 +239,10 @@ PCBRIDGE_S3_FORCE_PATH_STYLE=false
163
239
 
164
240
  The implementation uses the standard AWS S3 client and supports Amazon S3, Alibaba OSS, Tencent
165
241
  COS, Cloudflare R2, and other compatible providers. Set `PCBRIDGE_S3_FORCE_PATH_STYLE` when the
166
- provider requires path-style addressing. Builds can also be started and inspected from the CLI:
242
+ provider requires path-style addressing. Bucket-prefixed OSS endpoints such as
243
+ `https://my-bucket.oss-cn-shanghai.aliyuncs.com` are normalized before the SDK applies the bucket,
244
+ and uploads use a fixed `Content-MD5` instead of streaming checksum trailers. Builds can also be
245
+ started and inspected from the CLI:
167
246
 
168
247
  ```bash
169
248
  pcbridge builder start --target editor:<sceneId> --asset <templateAssetId> --suffix '-${time}'
package/README.zh-CN.md CHANGED
@@ -13,7 +13,7 @@ npm install -g playcanvas-agent-bridge-cli
13
13
  pcbridge install-skill --agent all
14
14
  ```
15
15
 
16
- 下文命令跟随仓库版 `0.5.3`。npm 安装的是最新稳定版本;测试尚未发布的改动时请使用
16
+ 下文命令跟随仓库版 `0.6.0`。npm 安装的是最新稳定版本;测试尚未发布的改动时请使用
17
17
  GitHub 安装。
18
18
 
19
19
  如果要测试尚未发布的改动,也可以直接从这个 GitHub 仓库安装:
@@ -30,6 +30,64 @@ npx playcanvas-agent-bridge-cli doctor
30
30
  npx playcanvas-agent-bridge-cli install-skill --agent all
31
31
  ```
32
32
 
33
+ ## 更新 pcbridge 各组件
34
+
35
+ CLI/daemon、已安装的 Agent 技能、生成的 Chrome 插件和可选的本地 Editor 前端是四个独立的
36
+ 本地组件,更新其中一个不会自动更新其他组件。
37
+
38
+ ### 更新 CLI、daemon 和 Agent 技能
39
+
40
+ 先在启动 daemon 的终端中按 **Ctrl+C 手动停止 daemon**。目前没有 `pcbridge daemon stop`
41
+ 命令。请记住该终端的工作目录,它就是 workspace 根目录,升级后必须回到同一目录启动。
42
+
43
+ ```bash
44
+ npm install -g playcanvas-agent-bridge-cli@latest
45
+ pcbridge version
46
+ pcbridge install-skill --agent all
47
+ cd /原来的/workspace/根目录
48
+ pcbridge daemon start
49
+ ```
50
+
51
+ npm 全局安装会替换 CLI 文件,但已经运行的 daemon 仍然是内存中的旧版本,必须重启才会生效。
52
+ Codex、Claude、Cursor 和 Windsurf 的技能文件也是安装时复制出去的,因此需要重新执行
53
+ `install-skill`;如果当前 Agent 任务已经加载了旧技能,请新建一个任务或会话再使用新技能。
54
+
55
+ ### 更新 Chrome 插件
56
+
57
+ CLI 更新完成后,重新生成 unpacked 插件目录:
58
+
59
+ ```bash
60
+ pcbridge install-extension --no-open
61
+ ```
62
+
63
+ 然后完成以下 **Chrome 手动操作**:
64
+
65
+ 1. 打开 `chrome://extensions`。
66
+ 2. 找到 **PlayCanvas Agent Bridge**,点击 **Reload**。如果现有条目已经指向
67
+ `~/.pcbridge/extension`,不需要再次 Load unpacked。
68
+ 3. 如果插件尚未安装,开启 Developer Mode,点击 **Load unpacked**,选择
69
+ `pcbridge install-extension` 打印的目录。
70
+ 4. 刷新所有已经打开的 PlayCanvas Editor 和 Launch 页面。
71
+ 5. daemon 重启后运行 `pcbridge doctor`,确认生成目录中的插件版本、浏览器已连接插件版本和
72
+ CLI 版本一致。
73
+
74
+ 只更新 npm 包不会更新 `~/.pcbridge/extension`;重新写入插件目录后,Chrome 也不会自动 reload
75
+ unpacked 插件。
76
+
77
+ ### 更新 PlayCanvas 本地前端
78
+
79
+ 本地前端使用独立的 Release,不会随 CLI 或插件一起更新:
80
+
81
+ ```bash
82
+ pcbridge frontend update
83
+ pcbridge frontend status
84
+ ```
85
+
86
+ `frontend update` 默认会下载、校验并激活最新发布版。如果 daemon 已经运行,它会在每次请求时
87
+ 读取当前激活版本,因此只更新前端不需要重启 daemon;**用户仍然必须刷新 PlayCanvas Editor
88
+ 页面**。如果当前项目正在使用官方前端,请打开插件 popup,点击 **Use custom frontend**。
89
+ 旧的本地前端版本会继续保留,除非显式执行 `frontend remove`。
90
+
33
91
  ## 安装 Chrome 插件
34
92
 
35
93
  运行:
@@ -105,9 +163,9 @@ pcbridge daemon start
105
163
  ```text
106
164
  1552681-pcbridge-test/
107
165
  ├── pcbridge.project.json # 项目信息和供 agent 读取的资源目录
108
- ├── assets/ # 与 PlayCanvas 文件夹结构对应,所有文件内容自动双向同步
166
+ ├── assets/ # PlayCanvas 文件树的碰撞安全本地投影
109
167
  ├── tmp/ # 构建产物、缓存、冲突、截图和远端删除隔离副本
110
- └── .pcbridge/ # 内部同步状态,请勿手动修改
168
+ └── .pcbridge/ # 内部同步状态和内容寻址对象缓存,请勿手动修改
111
169
  ```
112
170
 
113
171
  查看或手动刷新工作区:
@@ -132,19 +190,32 @@ daemon 会监控项目 `assets/` 目录:本地新增文件会上传到对应
132
190
  缓存,不会删除 PlayCanvas 远端 Asset;远端删除仍会隔离到 `tmp/trash/remote/`。`tmp/` 下的
133
191
  构建、缓存和 agent 临时文件完全不参与 workspace 同步。
134
192
 
135
- schema v2 的 `pcbridge.project.json` 会记录每个 asset 的 id、类型、PlayCanvas 文件夹、相对
136
- 项目根目录的 `assets/...` 文件路径、是否已下载,以及远端、本地和同步基线 MD5。agent 可以
137
- 直接读取这些信息,但其中的 `assets` 对象由 pcbridge 管理。已有 schema v1 隐藏索引会自动
138
- 迁移,并保留为 `.pcbridge/asset-index.v1.json` 以便回退。已有资源时收到的空快照会被忽略;
193
+ PlayCanvas 可能生成同名的源 Asset 和派生 Asset,例如源 GLB 与 Container/Model,或字体源文件
194
+ 与字体图集。manifest 会把网页端显示路径 `folder` 和本地唯一路径 `projectionPath` 分开记录。
195
+ 本地优先使用真实的 `file.filename`;只有名称碰撞时,才会在扩展名前加入
196
+ `.__pc_<type>_<assetId>`。source 和 standalone 投影可写;derived 投影按需下载且只读,内容会
197
+ 缓存到 `.pcbridge/objects/<assetId>/<md5>/`。修改或移动 derived 投影时,本地副本会隔离到
198
+ `tmp/conflicts/`,随后从对象缓存恢复正确内容,不会反向上传到 PlayCanvas。
199
+
200
+ schema v3 的 `pcbridge.project.json` 会记录 `origin`(`source`、`derived` 或 `standalone`)、
201
+ PlayCanvas 声明和实际观察到的文件元数据、最终采用的 MD5,以及本地是否存在、是否可写、当前
202
+ 和同步基线 MD5。贴图 variant、字体附加图集等仅在构建中使用的文件记录在 `local.resources`
203
+ 中,并作为主 Asset 同目录下的只读受管文件。agent 可以直接读取这些信息,但 `assets` 对象由
204
+ pcbridge 管理。schema v1
205
+ 和 v2 会自动迁移;v1 隐藏索引仍保留为 `.pcbridge/asset-index.v1.json` 以便回退。已有资源时
206
+ 收到的空快照会被忽略;
139
207
  非空但缩小的快照必须连续出现两次,文件才会被移动到 `tmp/trash/remote/`。
140
208
 
141
209
  ## Template 构建与 S3 上传
142
210
 
143
211
  选中 PlayCanvas Template Asset 后,Attributes 面板会出现 **pcbridge Tiny Builder**。点击
144
212
  **构建并上传到 S3** 后,网页只负责收集 Template、递归 Asset 引用、挂载脚本和子 Template;
145
- daemon 会核对工作区 MD5,缺失或远端更新的文件才会下载到工作区,然后直接并发上传对象,
146
- 不再生成 ZIP。生成的 `tinyapp.json` 和 `gamescript.js` 保存在 `tmp/builds/`,变体和字体附加
147
- 贴图缓存于 `tmp/cache/assets/`。
213
+ daemon 会把全部依赖物化到 `assets/`:本地文件与有效远端 MD5 一致时直接复用,不存在或远端
214
+ 已更新时先从 PlayCanvas 同步。贴图 variant 和字体附加图集会作为主 Asset 同目录下的只读
215
+ 受管资源保存,不再写入 `tmp/cache/assets/`;`.pcbridge/objects/` 仅作为避免重复下载的内部
216
+ 对象缓存。随后并发上传对象,不生成 ZIP;只有 `tinyapp.json` 和 `gamescript.js` 保存在
217
+ `tmp/builds/`。挂载的非 `sds*` 脚本会先合并,再由 Babel 转换为 ES5,并由 Terser 做保守
218
+ 压缩;函数名和类名会保留,避免破坏脚本注册和运行时反射。
148
219
 
149
220
  在 daemon 启动目录创建 `.env` 作为工作区默认配置,也可以在单个项目目录创建 `.env`;
150
221
  项目配置按字段覆盖工作区配置。不要提交含密钥的 `.env`:
@@ -163,7 +234,10 @@ PCBRIDGE_S3_FORCE_PATH_STYLE=false
163
234
 
164
235
  以上配置使用 AWS S3 标准客户端,适用于 Amazon S3、阿里云 OSS、腾讯云 COS、Cloudflare
165
236
  R2 等兼容服务;自定义服务是否需要 path-style URL 由
166
- `PCBRIDGE_S3_FORCE_PATH_STYLE` 决定。也可以从 CLI 发起和查看任务:
237
+ `PCBRIDGE_S3_FORCE_PATH_STYLE` 决定。若 OSS endpoint 已包含 bucket 前缀,例如
238
+ `https://my-bucket.oss-cn-shanghai.aliyuncs.com`,pcbridge 会先规范化 endpoint,避免 SDK 再次
239
+ 拼接 bucket;上传使用固定 `Content-MD5`,不会发送流式 checksum trailer。也可以从 CLI
240
+ 发起和查看任务:
167
241
 
168
242
  ```bash
169
243
  pcbridge builder start --target editor:<sceneId> --asset <templateAssetId> --suffix '-${time}'
@@ -1,9 +1,12 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { createReadStream, existsSync } from "node:fs";
3
3
  import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
4
- import { dirname, extname, join } from "node:path";
4
+ import { extname, join } from "node:path";
5
5
  import { PutObjectCommand, S3Client, } from "@aws-sdk/client-s3";
6
+ import { transformAsync } from "@babel/core";
7
+ import presetEnv from "@babel/preset-env";
6
8
  import { parse as parseEnv } from "dotenv";
9
+ import { minify } from "terser";
7
10
  const OMITTED_ASSET_FIELDS = new Set([
8
11
  "uniqueId",
9
12
  "createdAt",
@@ -36,6 +39,47 @@ function md5(value) {
36
39
  function clone(value) {
37
40
  return JSON.parse(JSON.stringify(value));
38
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
+ }
39
83
  function envValue(env, ...names) {
40
84
  for (const name of names) {
41
85
  const value = env[name];
@@ -75,6 +119,9 @@ function timestamp() {
75
119
  return `${date.getFullYear()}_${part(date.getMonth() + 1)}_${part(date.getDate())}-` +
76
120
  `${part(date.getHours())}_${part(date.getMinutes())}_${part(date.getSeconds())}`;
77
121
  }
122
+ function workspaceResourceKey(assetId, filename) {
123
+ return `${assetId}\0${filename.normalize("NFKC").toLocaleLowerCase()}`;
124
+ }
78
125
  function contentType(path) {
79
126
  const types = {
80
127
  ".bin": "application/octet-stream",
@@ -100,6 +147,21 @@ function publicObjectUrl(base, key) {
100
147
  const encoded = key.split("/").map(encodeURIComponent).join("/");
101
148
  return `${base.replace(/\/$/, "")}/${encoded}`;
102
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
+ }
103
165
  function sanitizeAsset(asset) {
104
166
  const result = clone(asset);
105
167
  for (const field of OMITTED_ASSET_FIELDS)
@@ -149,7 +211,8 @@ async function loadS3Settings(rootDir, projectDirectory) {
149
211
  return {
150
212
  client: new S3Client({
151
213
  region,
152
- endpoint,
214
+ endpoint: normalizeS3Endpoint(endpoint, bucket),
215
+ requestChecksumCalculation: "WHEN_REQUIRED",
153
216
  forcePathStyle: booleanValue(envValue(env, "PCBRIDGE_S3_FORCE_PATH_STYLE", "S3_FORCE_PATH_STYLE"), false),
154
217
  credentials: { accessKeyId, secretAccessKey, sessionToken },
155
218
  }),
@@ -228,30 +291,6 @@ export class BuilderManager {
228
291
  throw new Error(response.error.message);
229
292
  return descriptorFrom(response.data);
230
293
  }
231
- async #cacheRemoteFile(info, projectDirectory, assetId, filename, url, expectedHash) {
232
- const path = join(projectDirectory, "tmp", "cache", "assets", safeSegment(assetId, "asset"), safeSegment(filename, "file.bin"));
233
- if (existsSync(path)) {
234
- const content = await readFile(path);
235
- const hash = md5(content);
236
- if (!expectedHash || hash === expectedHash)
237
- return { path, hash };
238
- }
239
- const response = await this.#requestTarget(info.id, "bridge:readAssetResource", { assetId, url }, 120000);
240
- if (!response.ok)
241
- throw new Error(response.error.message);
242
- const data = response.data;
243
- const base64 = typeof data.base64 === "string" ? data.base64 : "";
244
- if (!base64)
245
- throw new Error(`Asset ${assetId} resource ${filename} returned no data.`);
246
- const content = Buffer.from(base64, "base64");
247
- const hash = md5(content);
248
- if (expectedHash && hash !== expectedHash) {
249
- throw new Error(`Asset ${assetId} resource ${filename} did not match its PlayCanvas MD5.`);
250
- }
251
- await mkdir(dirname(path), { recursive: true });
252
- await writeFile(path, content);
253
- return { path, hash };
254
- }
255
294
  async #run(job) {
256
295
  let activeClient = null;
257
296
  try {
@@ -277,6 +316,42 @@ export class BuilderManager {
277
316
  }
278
317
  const prepared = await this.#workspace.prepareAssetFiles(job.info, [...allAssetIds]);
279
318
  const preparedById = new Map(prepared.assets.map((asset) => [asset.id, asset]));
319
+ const resourceRequests = new Map();
320
+ for (const descriptor of descriptors.values()) {
321
+ for (const asset of descriptor.assets) {
322
+ const id = String(asset.id);
323
+ for (const variant of Object.values(asset.file?.variants || {})) {
324
+ if (!variant.url || !variant.filename)
325
+ continue;
326
+ resourceRequests.set(workspaceResourceKey(id, variant.filename), {
327
+ assetId: id,
328
+ filename: variant.filename,
329
+ url: variant.url,
330
+ hash: variant.hash,
331
+ });
332
+ }
333
+ const fontMaps = asset.type === "font" && Array.isArray(asset.data?.info &&
334
+ asset.data.info.maps)
335
+ ? asset.data.info.maps
336
+ : [];
337
+ if (!asset.file?.url || !asset.file.filename || fontMaps.length <= 1)
338
+ continue;
339
+ for (let index = 1; index < fontMaps.length; index += 1) {
340
+ const filename = asset.file.filename.replace(/(\.[^.]*)$/, `${index}$1`);
341
+ const url = asset.file.url.replace(/(\.[^.]*)$/, `${index}$1`);
342
+ resourceRequests.set(workspaceResourceKey(id, filename), {
343
+ assetId: id,
344
+ filename,
345
+ url,
346
+ });
347
+ }
348
+ }
349
+ }
350
+ const preparedResources = await this.#workspace.prepareAssetResources(job.info, [...resourceRequests.values()]);
351
+ const preparedResourceByKey = new Map(preparedResources.map((resource) => [
352
+ workspaceResourceKey(resource.assetId, resource.filename),
353
+ resource,
354
+ ]));
280
355
  const settings = await loadS3Settings(this.rootDir, prepared.projectDirectory);
281
356
  activeClient = settings.client;
282
357
  job.configSource = settings.source;
@@ -333,26 +408,34 @@ export class BuilderManager {
333
408
  if (output.file && local?.path && local.filename) {
334
409
  const relativeUrl = `${buildName}/${id}/${safeSegment(local.filename, `asset-${id}`)}`;
335
410
  const key = `${prefix}/${relativeUrl}`;
411
+ const hash = local.hash || md5(await readFile(local.path));
412
+ const fileInfo = await stat(local.path);
336
413
  output.file.url = relativeUrl;
414
+ output.file.hash = hash;
415
+ output.file.size = fileInfo.size;
337
416
  uploads.set(key, {
338
417
  key,
339
418
  path: local.path,
340
419
  contentType: contentType(local.path),
341
- hash: local.hash || md5(await readFile(local.path)),
420
+ hash,
342
421
  });
343
422
  }
344
423
  for (const variant of Object.values(output.file?.variants || {})) {
345
424
  if (!variant.url || !variant.filename)
346
425
  continue;
347
- const cached = await this.#cacheRemoteFile(job.info, prepared.projectDirectory, id, variant.filename, variant.url, variant.hash);
426
+ const resource = preparedResourceByKey.get(workspaceResourceKey(id, variant.filename));
427
+ if (!resource) {
428
+ throw new Error(`Asset ${id} resource ${variant.filename} was not prepared.`);
429
+ }
348
430
  const relativeUrl = `${buildName}/${id}/${safeSegment(variant.filename, "variant.bin")}`;
349
431
  const key = `${prefix}/${relativeUrl}`;
350
432
  variant.url = relativeUrl;
433
+ variant.hash = resource.hash;
351
434
  uploads.set(key, {
352
435
  key,
353
- path: cached.path,
354
- contentType: contentType(cached.path),
355
- hash: cached.hash,
436
+ path: resource.path,
437
+ contentType: contentType(resource.path),
438
+ hash: resource.hash,
356
439
  });
357
440
  }
358
441
  const fontMaps = asset.type === "font" && Array.isArray(asset.data?.info &&
@@ -363,13 +446,16 @@ export class BuilderManager {
363
446
  for (let index = 1; index < fontMaps.length; index += 1) {
364
447
  const filename = originalFilename.replace(/(\.[^.]*)$/, `${index}$1`);
365
448
  const url = originalFileUrl.replace(/(\.[^.]*)$/, `${index}$1`);
366
- const cached = await this.#cacheRemoteFile(job.info, prepared.projectDirectory, id, filename, url);
449
+ const resource = preparedResourceByKey.get(workspaceResourceKey(id, filename));
450
+ if (!resource) {
451
+ throw new Error(`Asset ${id} resource ${filename} was not prepared.`);
452
+ }
367
453
  const key = `${prefix}/${buildName}/${id}/${safeSegment(filename, `font-map-${index}`)}`;
368
454
  uploads.set(key, {
369
455
  key,
370
- path: cached.path,
371
- contentType: contentType(cached.path),
372
- hash: cached.hash,
456
+ path: resource.path,
457
+ contentType: contentType(resource.path),
458
+ hash: resource.hash,
373
459
  });
374
460
  }
375
461
  }
@@ -385,8 +471,9 @@ export class BuilderManager {
385
471
  scriptText += "\n";
386
472
  }
387
473
  if (scriptText.trim()) {
474
+ const gameScript = await compileGameScript(scriptText);
388
475
  const scriptPath = join(buildRoot, "gamescript.js");
389
- await writeFile(scriptPath, scriptText);
476
+ await writeFile(scriptPath, gameScript);
390
477
  const relativeUrl = `${buildName}/gamescript.js`;
391
478
  const key = `${prefix}/${relativeUrl}`;
392
479
  rootData.scriptUrl = relativeUrl;
@@ -394,7 +481,7 @@ export class BuilderManager {
394
481
  key,
395
482
  path: scriptPath,
396
483
  contentType: contentType(scriptPath),
397
- hash: md5(scriptText),
484
+ hash: md5(gameScript),
398
485
  });
399
486
  }
400
487
  const rootPath = join(buildRoot, "tinyapp.json");
@@ -416,28 +503,23 @@ export class BuilderManager {
416
503
  job.totalFiles = uploads.size;
417
504
  const uploadFiles = [...uploads.values()];
418
505
  this.#update(job, { state: "uploading", message: `Uploading 0/${uploadFiles.length} files` });
419
- const concurrency = Math.min(4, Math.max(1, uploadFiles.length));
420
- let cursor = 0;
421
- const worker = async () => {
422
- while (cursor < uploadFiles.length) {
423
- const file = uploadFiles[cursor++];
424
- const info = await stat(file.path);
425
- const input = {
426
- Bucket: settings.bucket,
427
- Key: file.key,
428
- Body: createReadStream(file.path),
429
- ContentLength: info.size,
430
- ContentType: file.contentType,
431
- Metadata: { "pcbridge-md5": file.hash },
432
- };
433
- await settings.client.send(new PutObjectCommand(input));
434
- job.completedFiles += 1;
435
- this.#update(job, {
436
- message: `Uploading ${job.completedFiles}/${uploadFiles.length} files`,
437
- });
438
- }
439
- };
440
- await Promise.all(Array.from({ length: concurrency }, () => worker()));
506
+ await mapWithConcurrency(uploadFiles, 4, async (file) => {
507
+ const info = await stat(file.path);
508
+ const input = {
509
+ Bucket: settings.bucket,
510
+ Key: file.key,
511
+ Body: createReadStream(file.path),
512
+ ContentLength: info.size,
513
+ ContentMD5: Buffer.from(file.hash, "hex").toString("base64"),
514
+ ContentType: file.contentType,
515
+ Metadata: { "pcbridge-md5": file.hash },
516
+ };
517
+ await settings.client.send(new PutObjectCommand(input));
518
+ job.completedFiles += 1;
519
+ this.#update(job, {
520
+ message: `Uploading ${job.completedFiles}/${uploadFiles.length} files`,
521
+ });
522
+ });
441
523
  this.#update(job, {
442
524
  state: "completed",
443
525
  message: `Uploaded ${uploadFiles.length} files`,
package/dist/config.js CHANGED
@@ -4,7 +4,7 @@ import { existsSync } from "node:fs";
4
4
  import { homedir } from "node:os";
5
5
  import { dirname, join, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
- export const VERSION = "0.5.3";
7
+ export const VERSION = "0.6.0";
8
8
  export const DEFAULT_HOST = "127.0.0.1";
9
9
  export const DEFAULT_PORT = 17329;
10
10
  export const DEFAULT_FRONTEND_PORT = 3487;