playcanvas-agent-bridge-cli 0.2.2 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +218 -52
  2. package/README.zh-CN.md +210 -51
  3. package/dist/cli.js +723 -92
  4. package/dist/config.js +6 -2
  5. package/dist/daemon/server.js +181 -19
  6. package/dist/daemon/target-registry.js +61 -3
  7. package/dist/frontend/server.js +191 -0
  8. package/dist/frontend/store.js +369 -0
  9. package/dist/shared/protocol.js +3 -1
  10. package/dist/snippets.js +764 -30
  11. package/dist/workspace/manager.js +536 -0
  12. package/extension/icons/concepts/pcbridge-bridge.png +0 -0
  13. package/extension/icons/concepts/pcbridge-cube.png +0 -0
  14. package/extension/icons/concepts/pcbridge-p-active.png +0 -0
  15. package/extension/icons/concepts/pcbridge-p-arch.png +0 -0
  16. package/extension/icons/concepts/pcbridge-p-bridge.png +0 -0
  17. package/extension/icons/concepts/pcbridge-p-emblem.png +0 -0
  18. package/extension/icons/concepts/pcbridge-signal.png +0 -0
  19. package/extension/icons/icon-128.png +0 -0
  20. package/extension/icons/icon-16.png +0 -0
  21. package/extension/icons/icon-32.png +0 -0
  22. package/extension/icons/icon-48.png +0 -0
  23. package/extension/isolated.js +214 -43
  24. package/extension/main.js +619 -32
  25. package/extension/manifest.json +29 -7
  26. package/extension/popup.html +188 -24
  27. package/extension/popup.js +199 -10
  28. package/extension/service-worker.js +268 -17
  29. package/package.json +4 -1
  30. package/skills/claude/playcanvas-agent-bridge-cli/SKILL.md +97 -24
  31. package/skills/codex/playcanvas-agent-bridge-cli/SKILL.md +167 -52
  32. package/skills/codex/playcanvas-agent-bridge-cli/agents/openai.yaml +2 -2
  33. package/skills/cursor/playcanvas-agent-bridge-cli.mdc +63 -23
  34. package/skills/windsurf/playcanvas-agent-bridge-cli.md +61 -23
package/dist/config.js CHANGED
@@ -4,10 +4,14 @@ 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.2.2";
7
+ export const VERSION = "0.4.2";
8
8
  export const DEFAULT_HOST = "127.0.0.1";
9
9
  export const DEFAULT_PORT = 17329;
10
- export const CONFIG_DIR = join(homedir(), ".pcbridge");
10
+ export const DEFAULT_FRONTEND_PORT = 3487;
11
+ export const DEFAULT_FRONTEND_REPOSITORY = "Q-My99/playcanvas-editor";
12
+ export const CONFIG_DIR = process.env.PCBRIDGE_CONFIG_DIR
13
+ ? resolve(process.env.PCBRIDGE_CONFIG_DIR)
14
+ : join(homedir(), ".pcbridge");
11
15
  export const SESSION_FILE = join(CONFIG_DIR, "session.json");
12
16
  export const EXTENSION_INSTALL_DIR = join(CONFIG_DIR, "extension");
13
17
  export async function readOrCreateSession() {
@@ -1,8 +1,10 @@
1
1
  import http from "node:http";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { WebSocketServer } from "ws";
4
- import { DEFAULT_HOST, DEFAULT_PORT, VERSION } from "../config.js";
4
+ import { CONFIG_DIR, DEFAULT_FRONTEND_PORT, DEFAULT_HOST, DEFAULT_PORT, VERSION, } from "../config.js";
5
+ import { createFrontendServer, } from "../frontend/server.js";
5
6
  import { TargetRegistry } from "./target-registry.js";
7
+ import { WorkspaceManager } from "../workspace/manager.js";
6
8
  import { fail, normalizeError, ok, } from "../shared/protocol.js";
7
9
  function readBody(req) {
8
10
  return new Promise((resolve, reject) => {
@@ -38,10 +40,16 @@ function isJsonObject(value) {
38
40
  }
39
41
  export function createDaemonServer(options) {
40
42
  const host = options.host || DEFAULT_HOST;
41
- const port = Number(options.port || DEFAULT_PORT);
43
+ const port = Number(options.port ?? DEFAULT_PORT);
44
+ let actualPort = port;
42
45
  const registry = new TargetRegistry();
43
46
  const pending = new Map();
44
47
  const log = options.log || (() => undefined);
48
+ const frontend = createFrontendServer({
49
+ host,
50
+ port: options.frontendPort ?? DEFAULT_FRONTEND_PORT,
51
+ rootDir: options.frontendRootDir || CONFIG_DIR,
52
+ });
45
53
  function requireToken(req) {
46
54
  return req.headers["x-pcbridge-token"] === options.token;
47
55
  }
@@ -86,6 +94,15 @@ export function createDaemonServer(options) {
86
94
  });
87
95
  });
88
96
  }
97
+ const workspace = new WorkspaceManager({
98
+ rootDir: options.workspaceRoot || process.cwd(),
99
+ requestTarget: (target, method, params = {}, timeoutMs = 15000) => sendToTarget({
100
+ target,
101
+ method,
102
+ params,
103
+ timeoutMs,
104
+ }),
105
+ });
89
106
  const server = http.createServer(async (req, res) => {
90
107
  try {
91
108
  const url = new URL(req.url || "/", `http://${req.headers.host || `${host}:${port}`}`);
@@ -94,14 +111,25 @@ export function createDaemonServer(options) {
94
111
  writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
95
112
  return;
96
113
  }
114
+ const frontendStatus = await frontend.status();
97
115
  writeJson(res, 200, ok({
98
116
  version: VERSION,
99
117
  host,
100
- port,
118
+ port: actualPort,
101
119
  targetCount: registry.list().filter((target) => target.connected).length,
120
+ workspaceRoot: workspace.rootDir,
121
+ frontend: frontendStatus,
102
122
  }));
103
123
  return;
104
124
  }
125
+ if (url.pathname === "/frontend/status" && req.method === "GET") {
126
+ if (!requireToken(req)) {
127
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
128
+ return;
129
+ }
130
+ writeJson(res, 200, ok(await frontend.status()));
131
+ return;
132
+ }
105
133
  if (url.pathname === "/targets" && req.method === "GET") {
106
134
  if (!requireToken(req)) {
107
135
  writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
@@ -110,6 +138,85 @@ export function createDaemonServer(options) {
110
138
  writeJson(res, 200, ok(registry.list()));
111
139
  return;
112
140
  }
141
+ if (url.pathname === "/status" && req.method === "GET") {
142
+ if (!requireToken(req)) {
143
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
144
+ return;
145
+ }
146
+ const tabId = Number(url.searchParams.get("tabId"));
147
+ const target = Number.isFinite(tabId) ? registry.getByTabId(tabId) : undefined;
148
+ writeJson(res, 200, ok({
149
+ daemon: {
150
+ version: VERSION,
151
+ host,
152
+ port: actualPort,
153
+ workspaceRoot: workspace.rootDir,
154
+ targetCount: registry.list().filter((item) => item.connected).length,
155
+ },
156
+ target: target || null,
157
+ workspace: workspace.statusForTarget(target),
158
+ frontend: await frontend.status(),
159
+ }));
160
+ return;
161
+ }
162
+ if (url.pathname === "/workspace/status" && req.method === "GET") {
163
+ if (!requireToken(req)) {
164
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
165
+ return;
166
+ }
167
+ const resolved = registry.resolve(url.searchParams.get("target") || "current");
168
+ if (!resolved.ok) {
169
+ writeJson(res, 400, fail(resolved.code, resolved.message));
170
+ return;
171
+ }
172
+ writeJson(res, 200, ok(workspace.statusForTarget(resolved.target.info)));
173
+ return;
174
+ }
175
+ if (url.pathname === "/workspace/sync" && req.method === "POST") {
176
+ if (!requireToken(req)) {
177
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
178
+ return;
179
+ }
180
+ const body = await readBody(req);
181
+ const data = isJsonObject(body) ? body : {};
182
+ const selector = typeof data.target === "string" ? data.target : "current";
183
+ const resolved = registry.resolve(selector);
184
+ if (!resolved.ok) {
185
+ writeJson(res, 400, fail(resolved.code, resolved.message));
186
+ return;
187
+ }
188
+ try {
189
+ writeJson(res, 200, ok(await workspace.syncTarget(resolved.target.info)));
190
+ }
191
+ catch (error) {
192
+ writeJson(res, 400, fail("WORKSPACE_SYNC_FAILED", String(error)));
193
+ }
194
+ return;
195
+ }
196
+ if (url.pathname === "/workspace/pull" && req.method === "POST") {
197
+ if (!requireToken(req)) {
198
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
199
+ return;
200
+ }
201
+ const body = await readBody(req);
202
+ if (!isJsonObject(body) || typeof body.assetId !== "string") {
203
+ writeJson(res, 400, fail("INVALID_REQUEST", "workspace pull requires assetId."));
204
+ return;
205
+ }
206
+ const selector = typeof body.target === "string" ? body.target : "current";
207
+ const resolved = registry.resolve(selector);
208
+ if (!resolved.ok) {
209
+ writeJson(res, 400, fail(resolved.code, resolved.message));
210
+ return;
211
+ }
212
+ try {
213
+ writeJson(res, 200, ok(await workspace.pullAsset(resolved.target.info, body.assetId)));
214
+ }
215
+ catch (error) {
216
+ writeJson(res, 400, fail("WORKSPACE_PULL_FAILED", String(error)));
217
+ }
218
+ return;
219
+ }
113
220
  if (url.pathname === "/rpc" && req.method === "POST") {
114
221
  if (!requireToken(req)) {
115
222
  writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
@@ -142,14 +249,35 @@ export function createDaemonServer(options) {
142
249
  wss.emit("connection", ws, req);
143
250
  });
144
251
  });
252
+ const liveness = new WeakMap();
253
+ const pingTimer = setInterval(() => {
254
+ for (const client of wss.clients) {
255
+ if (liveness.get(client) === false) {
256
+ client.terminate();
257
+ continue;
258
+ }
259
+ liveness.set(client, false);
260
+ client.ping();
261
+ }
262
+ }, 15000);
263
+ pingTimer.unref();
145
264
  wss.on("connection", (ws) => {
146
- log("extension connected");
265
+ liveness.set(ws, true);
266
+ ws.on("pong", () => liveness.set(ws, true));
147
267
  ws.on("message", (raw) => {
148
268
  try {
149
269
  const message = JSON.parse(raw.toString());
150
270
  if (message.type === "target:update" && message.target?.clientId) {
151
- const info = registry.upsert(message.target, ws);
152
- log(`target ${info.id} ready=${info.ready} url=${info.url}`);
271
+ const result = registry.upsert(message.target, ws);
272
+ if (result.connected) {
273
+ log(`connected ${result.info.id} project=${result.info.projectId || "unknown"} ` +
274
+ `scene=${result.info.sceneId || "unknown"}`);
275
+ }
276
+ if (result.connected || result.changed) {
277
+ void workspace.handleTarget(result.info).catch((error) => {
278
+ log(`workspace initialization failed for ${result.info.id}: ${String(error)}`);
279
+ });
280
+ }
153
281
  return;
154
282
  }
155
283
  if (message.type === "response" && message.id) {
@@ -181,24 +309,58 @@ export function createDaemonServer(options) {
181
309
  }
182
310
  });
183
311
  ws.on("close", () => {
184
- registry.markDisconnected(ws);
185
- log("extension disconnected");
312
+ for (const info of registry.markDisconnected(ws)) {
313
+ const replacement = registry.list().find((candidate) => candidate.connected &&
314
+ candidate.ready &&
315
+ candidate.kind === "editor" &&
316
+ candidate.projectId === info.projectId &&
317
+ candidate.branchId === info.branchId);
318
+ if (replacement) {
319
+ void workspace.handleTarget(replacement).catch((error) => {
320
+ log(`workspace failover failed for ${replacement.id}: ${String(error)}`);
321
+ });
322
+ }
323
+ else
324
+ workspace.markDisconnected(info);
325
+ log(`disconnected ${info.id} project=${info.projectId || "unknown"} ` +
326
+ `scene=${info.sceneId || "unknown"}`);
327
+ }
186
328
  });
187
329
  });
188
330
  return {
189
331
  host,
190
- port,
332
+ get port() {
333
+ return actualPort;
334
+ },
191
335
  registry,
192
- listen: () => new Promise((resolve, reject) => {
193
- server.once("error", reject);
194
- server.listen(port, host, () => {
195
- server.off("error", reject);
196
- resolve();
336
+ frontend,
337
+ workspace,
338
+ listen: async () => {
339
+ await new Promise((resolveListen, reject) => {
340
+ server.once("error", reject);
341
+ server.listen(port, host, () => {
342
+ server.off("error", reject);
343
+ const address = server.address();
344
+ if (address && typeof address !== "string")
345
+ actualPort = address.port;
346
+ resolveListen();
347
+ });
197
348
  });
198
- }),
199
- close: () => new Promise((resolve) => {
200
- wss.close();
201
- server.close(() => resolve());
202
- }),
349
+ try {
350
+ await frontend.listen();
351
+ }
352
+ catch (error) {
353
+ log(`frontend server unavailable: ${String(error)}`);
354
+ }
355
+ },
356
+ close: async () => {
357
+ clearInterval(pingTimer);
358
+ await workspace.close();
359
+ await frontend.close();
360
+ await new Promise((resolveClose) => {
361
+ wss.close();
362
+ server.close(() => resolveClose());
363
+ });
364
+ },
203
365
  };
204
366
  }
@@ -5,34 +5,79 @@ export class TargetRegistry {
5
5
  const targetId = info.tabId !== undefined ? `tab:${info.tabId}` : `client:${info.clientId}`;
6
6
  const now = new Date().toISOString();
7
7
  const existing = this.#targets.get(targetId)?.info;
8
+ const kind = info.kind || existing?.kind || "unknown";
9
+ const launchValue = (value, previous) => kind === "launch" ? value ?? previous : undefined;
8
10
  const next = {
9
11
  id: targetId,
10
12
  clientId: info.clientId,
11
13
  tabId: info.tabId,
12
14
  windowId: info.windowId,
15
+ kind,
13
16
  url: info.url || existing?.url || "",
14
17
  title: info.title || existing?.title,
15
18
  projectId: info.projectId || existing?.projectId,
19
+ projectName: info.projectName || existing?.projectName,
16
20
  sceneId: info.sceneId || existing?.sceneId,
21
+ sceneName: info.sceneName || existing?.sceneName,
17
22
  branchId: info.branchId || existing?.branchId,
23
+ branchName: info.branchName || existing?.branchName,
18
24
  extensionVersion: info.extensionVersion || existing?.extensionVersion,
25
+ hasEditor: info.hasEditor ?? existing?.hasEditor,
26
+ hasPc: info.hasPc ?? existing?.hasPc,
27
+ hasRuntimeApp: info.hasRuntimeApp ?? existing?.hasRuntimeApp,
28
+ runtimeAppSource: launchValue(info.runtimeAppSource, existing?.runtimeAppSource),
29
+ runtimeAppAmbiguous: launchValue(info.runtimeAppAmbiguous, existing?.runtimeAppAmbiguous),
30
+ runtimeAppCandidateSources: launchValue(info.runtimeAppCandidateSources, existing?.runtimeAppCandidateSources),
31
+ runtimeCanvasId: launchValue(info.runtimeCanvasId, existing?.runtimeCanvasId),
32
+ engineVersion: launchValue(info.engineVersion, existing?.engineVersion),
33
+ readinessMode: launchValue(info.readinessMode, existing?.readinessMode),
34
+ pageReady: launchValue(info.pageReady, existing?.pageReady),
35
+ visibilityState: launchValue(info.visibilityState, existing?.visibilityState),
36
+ lifecycleReady: launchValue(info.lifecycleReady, existing?.lifecycleReady),
37
+ runtimeCreated: launchValue(info.runtimeCreated, existing?.runtimeCreated),
38
+ graphicsReady: launchValue(info.graphicsReady, existing?.graphicsReady),
39
+ graphicsContextLost: launchValue(info.graphicsContextLost, existing?.graphicsContextLost),
40
+ runtimeStarted: launchValue(info.runtimeStarted, existing?.runtimeStarted),
41
+ runtimeFrame: launchValue(info.runtimeFrame, existing?.runtimeFrame),
42
+ sceneLoaded: launchValue(info.sceneLoaded, existing?.sceneLoaded),
43
+ scriptsReady: launchValue(info.scriptsReady, existing?.scriptsReady),
44
+ scriptTypeCount: launchValue(info.scriptTypeCount, existing?.scriptTypeCount),
45
+ splashVisible: launchValue(info.splashVisible, existing?.splashVisible),
46
+ rootChildCount: launchValue(info.rootChildCount, existing?.rootChildCount),
47
+ readinessBlockers: launchValue(info.readinessBlockers, existing?.readinessBlockers),
48
+ canvasCount: info.canvasCount ?? existing?.canvasCount,
19
49
  ready: Boolean(info.ready),
20
50
  connected: true,
21
51
  lastSeen: now,
22
52
  };
23
53
  this.#targets.set(targetId, { info: next, ws });
24
54
  this.#clientToTarget.set(info.clientId, targetId);
25
- return next;
55
+ const comparable = (target) => target ? {
56
+ ...target,
57
+ lastSeen: undefined,
58
+ connected: undefined,
59
+ } : null;
60
+ return {
61
+ info: next,
62
+ connected: !existing?.connected,
63
+ changed: JSON.stringify(comparable(existing)) !== JSON.stringify(comparable(next)),
64
+ };
26
65
  }
27
66
  markDisconnected(ws) {
67
+ const disconnected = [];
28
68
  for (const [id, connection] of this.#targets.entries()) {
29
- if (connection.ws === ws) {
69
+ if (connection.ws === ws && connection.info.connected) {
30
70
  connection.info.connected = false;
31
71
  connection.info.ready = false;
32
72
  connection.info.lastSeen = new Date().toISOString();
33
73
  this.#targets.set(id, connection);
74
+ disconnected.push(connection.info);
34
75
  }
35
76
  }
77
+ return disconnected;
78
+ }
79
+ getByTabId(tabId) {
80
+ return this.#targets.get(`tab:${tabId}`)?.info;
36
81
  }
37
82
  list() {
38
83
  return Array.from(this.#targets.values())
@@ -48,7 +93,7 @@ export class TargetRegistry {
48
93
  return {
49
94
  ok: false,
50
95
  code: "NO_READY_TARGET",
51
- message: "No ready PlayCanvas Editor target is connected.",
96
+ message: "No ready PlayCanvas target is connected.",
52
97
  candidates: this.list(),
53
98
  };
54
99
  }
@@ -93,6 +138,19 @@ export class TargetRegistry {
93
138
  };
94
139
  }
95
140
  }
141
+ if ((kind === "editor" || kind === "launch") && value) {
142
+ const matches = targets.filter((target) => target.info.kind === kind && target.info.sceneId === value);
143
+ if (matches.length === 1)
144
+ return { ok: true, target: matches[0] };
145
+ if (matches.length > 1) {
146
+ return {
147
+ ok: false,
148
+ code: "AMBIGUOUS_TARGET",
149
+ message: `${selector} matches multiple connected targets.`,
150
+ candidates: matches.map((target) => target.info),
151
+ };
152
+ }
153
+ }
96
154
  return {
97
155
  ok: false,
98
156
  code: "TARGET_NOT_FOUND",
@@ -0,0 +1,191 @@
1
+ import { createReadStream } from "node:fs";
2
+ import http from "node:http";
3
+ import { realpath, stat } from "node:fs/promises";
4
+ import { extname, relative, resolve, sep } from "node:path";
5
+ import { CONFIG_DIR, DEFAULT_FRONTEND_PORT, DEFAULT_HOST, } from "../config.js";
6
+ import { getFrontendStatus } from "./store.js";
7
+ const MIME_TYPES = {
8
+ ".avif": "image/avif",
9
+ ".bin": "application/octet-stream",
10
+ ".css": "text/css; charset=utf-8",
11
+ ".gif": "image/gif",
12
+ ".html": "text/html; charset=utf-8",
13
+ ".ico": "image/x-icon",
14
+ ".jpeg": "image/jpeg",
15
+ ".jpg": "image/jpeg",
16
+ ".js": "text/javascript; charset=utf-8",
17
+ ".json": "application/json; charset=utf-8",
18
+ ".map": "application/json; charset=utf-8",
19
+ ".mjs": "text/javascript; charset=utf-8",
20
+ ".mp3": "audio/mpeg",
21
+ ".ogg": "audio/ogg",
22
+ ".png": "image/png",
23
+ ".svg": "image/svg+xml",
24
+ ".ttf": "font/ttf",
25
+ ".wasm": "application/wasm",
26
+ ".wav": "audio/wav",
27
+ ".webp": "image/webp",
28
+ ".woff": "font/woff",
29
+ ".woff2": "font/woff2",
30
+ };
31
+ function writeHeaders(res, statusCode, headers = {}) {
32
+ res.writeHead(statusCode, {
33
+ "Access-Control-Allow-Origin": "*",
34
+ "Access-Control-Allow-Methods": "GET, HEAD, OPTIONS",
35
+ "Cache-Control": "no-cache, must-revalidate",
36
+ "Cross-Origin-Resource-Policy": "cross-origin",
37
+ "X-Content-Type-Options": "nosniff",
38
+ ...headers,
39
+ });
40
+ }
41
+ function writeJson(res, statusCode, body, headOnly = false) {
42
+ const payload = Buffer.from(`${JSON.stringify(body)}\n`);
43
+ writeHeaders(res, statusCode, {
44
+ "Content-Length": payload.length,
45
+ "Content-Type": "application/json; charset=utf-8",
46
+ });
47
+ res.end(headOnly ? undefined : payload);
48
+ }
49
+ function hostAllowed(hostHeader) {
50
+ if (!hostHeader)
51
+ return false;
52
+ try {
53
+ const hostname = new URL(`http://${hostHeader}`).hostname;
54
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
55
+ }
56
+ catch {
57
+ return false;
58
+ }
59
+ }
60
+ async function resolveStaticFile(root, pathname) {
61
+ let decoded;
62
+ try {
63
+ decoded = decodeURIComponent(pathname);
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ if (decoded.includes("\0"))
69
+ return null;
70
+ const rootPath = await realpath(root);
71
+ const candidate = resolve(rootPath, `.${decoded}`);
72
+ const relation = relative(rootPath, candidate);
73
+ if (relation === ".." || relation.startsWith(`..${sep}`))
74
+ return null;
75
+ const filePath = await realpath(candidate).catch(() => null);
76
+ if (!filePath)
77
+ return null;
78
+ const realRelation = relative(rootPath, filePath);
79
+ if (realRelation === ".." || realRelation.startsWith(`..${sep}`))
80
+ return null;
81
+ const info = await stat(filePath).catch(() => null);
82
+ return info?.isFile() ? filePath : null;
83
+ }
84
+ export function createFrontendServer(options = {}) {
85
+ const host = options.host || DEFAULT_HOST;
86
+ const requestedPort = options.port ?? DEFAULT_FRONTEND_PORT;
87
+ const rootDir = options.rootDir || CONFIG_DIR;
88
+ const log = options.log || (() => undefined);
89
+ let actualPort = requestedPort;
90
+ let listening = false;
91
+ let runtimeError = null;
92
+ const runtime = () => ({
93
+ host,
94
+ port: actualPort,
95
+ listening,
96
+ error: runtimeError,
97
+ });
98
+ const status = async () => ({
99
+ ...(await getFrontendStatus({ rootDir })),
100
+ server: runtime(),
101
+ });
102
+ const server = http.createServer(async (req, res) => {
103
+ try {
104
+ const headOnly = req.method === "HEAD";
105
+ if (!hostAllowed(req.headers.host)) {
106
+ writeJson(res, 403, { ready: false, error: "Invalid Host header." }, headOnly);
107
+ return;
108
+ }
109
+ if (req.method === "OPTIONS") {
110
+ writeHeaders(res, 204);
111
+ res.end();
112
+ return;
113
+ }
114
+ if (req.method !== "GET" && !headOnly) {
115
+ writeJson(res, 405, { ready: false, error: "Method not allowed." });
116
+ return;
117
+ }
118
+ const url = new URL(req.url || "/", `http://${req.headers.host}`);
119
+ if (url.pathname === "/__pcbridge_frontend__/health") {
120
+ const current = await status();
121
+ writeJson(res, current.ready ? 200 : 503, current, headOnly);
122
+ return;
123
+ }
124
+ const current = await getFrontendStatus({ rootDir });
125
+ if (!current.activePath) {
126
+ writeJson(res, 503, {
127
+ ready: false,
128
+ error: "No active PlayCanvas Editor frontend is installed.",
129
+ }, headOnly);
130
+ return;
131
+ }
132
+ const filePath = await resolveStaticFile(current.activePath, url.pathname);
133
+ if (!filePath) {
134
+ writeJson(res, 404, { ready: false, error: "Frontend asset not found." }, headOnly);
135
+ return;
136
+ }
137
+ const info = await stat(filePath);
138
+ writeHeaders(res, 200, {
139
+ "Content-Length": info.size,
140
+ "Content-Type": MIME_TYPES[extname(filePath).toLowerCase()] || "application/octet-stream",
141
+ });
142
+ if (headOnly) {
143
+ res.end();
144
+ return;
145
+ }
146
+ createReadStream(filePath).on("error", () => res.destroy()).pipe(res);
147
+ }
148
+ catch (error) {
149
+ writeJson(res, 500, { ready: false, error: String(error) });
150
+ }
151
+ });
152
+ return {
153
+ status,
154
+ listen: () => new Promise((resolveListen, reject) => {
155
+ const onError = (error) => {
156
+ runtimeError = error.message;
157
+ server.off("listening", onListening);
158
+ reject(error);
159
+ };
160
+ const onListening = () => {
161
+ server.off("error", onError);
162
+ const address = server.address();
163
+ if (address && typeof address !== "string")
164
+ actualPort = address.port;
165
+ listening = true;
166
+ runtimeError = null;
167
+ log(`frontend server listening on http://${host}:${actualPort}`);
168
+ resolveListen();
169
+ };
170
+ server.once("error", onError);
171
+ server.once("listening", onListening);
172
+ server.listen(requestedPort, host);
173
+ }),
174
+ close: () => new Promise((resolveClose, reject) => {
175
+ if (!server.listening) {
176
+ listening = false;
177
+ resolveClose();
178
+ return;
179
+ }
180
+ server.close((error) => {
181
+ listening = false;
182
+ if (error) {
183
+ reject(error);
184
+ }
185
+ else {
186
+ resolveClose();
187
+ }
188
+ });
189
+ }),
190
+ };
191
+ }