@neta-art/cohub-cli 10.17.1 → 10.18.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 +6 -0
- package/dist/board-export-resources.d.ts +2 -0
- package/dist/board-export-resources.js +1 -0
- package/dist/board-export.d.ts +4 -1
- package/dist/board-export.js +109 -23
- package/dist/board-gpu/index.d.ts +32 -0
- package/dist/board-gpu/index.js +188 -0
- package/dist/board-gpu/page.js +70178 -0
- package/dist/board-gpu/protocol.d.ts +37 -0
- package/dist/board-gpu/protocol.js +1 -0
- package/dist/board-kernel/{getPo2TextureFromSource.js → FilterPipe.js} +251 -1
- package/dist/board-kernel/browserAll.js +1 -1
- package/dist/board-kernel/init.js +1 -251
- package/dist/board-kernel/webworkerAll.js +1 -1
- package/dist/board-kernel.d.ts +3 -3
- package/dist/board-kernel.js +6624 -1462
- package/dist/board-simulate.d.ts +4 -0
- package/dist/board-simulate.js +34 -4
- package/dist/client.d.ts +1 -0
- package/dist/client.js +4 -1
- package/dist/commands/apps.js +25 -3
- package/dist/commands/boards/examples.js +21 -5
- package/dist/commands/boards.js +10 -2
- package/dist/commands/space-displays.js +301 -82
- package/dist/commands/spaces.js +11 -2
- package/dist/host/runtime.d.ts +12 -2
- package/dist/host/runtime.js +155 -10
- package/dist/host/serve.js +49 -11
- package/dist/host/workspaces.d.ts +2 -0
- package/dist/host/workspaces.js +18 -0
- package/dist/index.js +1 -0
- package/dist/runtime/cli-path.d.ts +5 -0
- package/dist/runtime/cli-path.js +27 -0
- package/dist/runtime/connection.d.ts +22 -4
- package/dist/runtime/connection.js +13 -3
- package/dist/runtime/harnesses/claude-approval.d.ts +31 -0
- package/dist/runtime/harnesses/claude-approval.js +119 -0
- package/dist/runtime/harnesses/claude.js +42 -3
- package/dist/runtime/harnesses/codex-approval.d.ts +25 -0
- package/dist/runtime/harnesses/codex-approval.js +69 -0
- package/dist/runtime/harnesses/codex.js +36 -5
- package/dist/runtime/harnesses/index.js +12 -3
- package/dist/runtime/harnesses/stream-json.d.ts +16 -2
- package/dist/runtime/harnesses/stream-json.js +26 -6
- package/dist/runtime/harnesses/types.d.ts +3 -1
- package/dist/runtime/instance.d.ts +1 -0
- package/dist/runtime/instance.js +1 -0
- package/dist/runtime/launch.js +2 -4
- package/dist/runtime/local-workspace.d.ts +15 -0
- package/dist/runtime/local-workspace.js +52 -0
- package/dist/runtime/model-catalog.js +7 -4
- package/dist/runtime/native/approvals.d.ts +18 -0
- package/dist/runtime/native/approvals.js +54 -0
- package/dist/runtime/native/codex-link.d.ts +7 -0
- package/dist/runtime/native/codex-link.js +40 -5
- package/dist/runtime/native/daemon.d.ts +5 -1
- package/dist/runtime/native/daemon.js +6 -1
- package/dist/runtime/native/execution.d.ts +2 -0
- package/dist/runtime/preferences.d.ts +7 -0
- package/dist/runtime/preferences.js +22 -0
- package/dist/runtime/presentation.d.ts +3 -0
- package/dist/runtime/presentation.js +2 -1
- package/dist/runtime/supervisor.js +92 -9
- package/dist/space-files/transfer.js +3 -2
- package/dist/space-files/upload.d.ts +5 -2
- package/dist/space-files/upload.js +41 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -73,6 +73,12 @@ cohub boards export lesson.board --animation lecture --at 0:92s:40ms --camera --
|
|
|
73
73
|
NODE_DEBUG=cohub:board-export cohub boards export lesson.board --animation lecture --at 0:92s:40ms -o lecture.mp4
|
|
74
74
|
```
|
|
75
75
|
|
|
76
|
+
Boards whose scripts draw with shaders render in a local Chrome, Chromium or Edge (headless;
|
|
77
|
+
software WebGL without a GPU) so frames match the web app; the rest render in Node.
|
|
78
|
+
`--renderer canvas` keeps Node and warns about the shaders it could not run, `--renderer gpu`
|
|
79
|
+
always uses the browser, and `COHUB_CHROME` picks the browser executable. `boards simulate`
|
|
80
|
+
compiles the same shaders with that browser and reports their errors.
|
|
81
|
+
|
|
76
82
|
Debug output reports render stages, RSS, heap, external buffers, reserved image bytes,
|
|
77
83
|
and available/constrained process memory. Video encoding is reported separately.
|
|
78
84
|
MP4 exports require even output dimensions and fail before rendering if the initial
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { BoardNodeRenderer } from "@neta-art/cohub/board/export/node";
|
|
2
2
|
export declare const BOARD_EXPORT_IMAGE_MEMORY_MIB = 256;
|
|
3
|
+
export declare const BOARD_EXPORT_RENDERERS: readonly ["auto", "canvas", "gpu"];
|
|
4
|
+
export type BoardExportRenderer = (typeof BOARD_EXPORT_RENDERERS)[number];
|
|
3
5
|
export declare class BoardExportResourceError extends Error {
|
|
4
6
|
}
|
|
5
7
|
export type BoardExportDecodeImage = (bytes: Uint8Array, mimeType?: string, maxEdge?: number) => ReturnType<BoardNodeRenderer["decodeImage"]>;
|
package/dist/board-export.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import type { BoardDocument, BoardExportRegion, BoardSceneItem, BoardThemeId } from "@neta-art/cohub/board";
|
|
2
2
|
import type { BoardNodeExportFormat, BoardNodeFont, BoardNodeTexture } from "@neta-art/cohub/board/export/node";
|
|
3
3
|
import type { BoardScriptHost } from "@neta-art/cohub/board/render";
|
|
4
|
+
import { type BoardGpuResources } from "./board-gpu/index.js";
|
|
4
5
|
import { createClient } from "./client.js";
|
|
5
|
-
import { type BoardExportDecodeImage } from "./board-export-resources.js";
|
|
6
|
+
import { type BoardExportRenderer, type BoardExportDecodeImage } from "./board-export-resources.js";
|
|
6
7
|
export declare function resolveBundledFonts(): BoardNodeFont[];
|
|
7
8
|
export type BoardExportSource = {
|
|
8
9
|
document: BoardDocument;
|
|
@@ -58,6 +59,7 @@ export type BoardExportRunOptions = {
|
|
|
58
59
|
};
|
|
59
60
|
document?: BoardDocument;
|
|
60
61
|
scripts?: BoardScriptHost;
|
|
62
|
+
renderer?: BoardExportRenderer;
|
|
61
63
|
signal?: AbortSignal;
|
|
62
64
|
imageMemoryMiB?: number;
|
|
63
65
|
onPlan?: (plan: {
|
|
@@ -95,4 +97,5 @@ export declare function runBoardVideoExport(options: BoardVideoExportOptions): P
|
|
|
95
97
|
warnings: string[];
|
|
96
98
|
}>;
|
|
97
99
|
export declare function runBoardExport(options: BoardExportRunOptions): Promise<BoardExportRunResult | null>;
|
|
100
|
+
export declare function gpuResources(spaceId: string, document: BoardDocument): BoardGpuResources;
|
|
98
101
|
export {};
|
package/dist/board-export.js
CHANGED
|
@@ -11,8 +11,9 @@ import { tmpdir } from "node:os";
|
|
|
11
11
|
const execFile = promisify(execFileCallback);
|
|
12
12
|
import { boardMediaNaturalSize, parseBoardMediaSource } from "@neta-art/cohub/board";
|
|
13
13
|
import { imageVariantUrl, MEDIA_VARIANT_MAX, mediaVariantSize, videoFrameUrl } from "@neta-art/cohub/media";
|
|
14
|
-
import { hasBoardScripts, boardAssetKey, boardAssetKeySource, boardDocumentAt, boardRenderTheme, boardTextureEdge, boardTexturePixels, createBoardRenderSampler, buildBoardScene, createNodeBoardRenderer, createNodeBoardScriptHost, exportBoardImageBytes, parseBoardDocument, planBoardExport, prepareBoardExport, selectBoardExportAssets, } from "./board-kernel.js";
|
|
14
|
+
import { hasBoardScripts, boardAssetKey, boardAssetKeySource, boardDocumentAt, boardRenderTheme, boardTextureEdge, boardTexturePixels, createBoardRenderSampler, buildBoardScene, createNodeBoardRenderer, createNodeBoardScriptHost, describeBoardExportWarning, exportBoardImageBytes, parseBoardDocument, planBoardExport, prepareBoardExport, selectBoardExportAssets, } from "./board-kernel.js";
|
|
15
15
|
import { settleBoardDocument } from "./board-media.js";
|
|
16
|
+
import { findBoardGpuBrowser, launchBoardGpuExporter } from "./board-gpu/index.js";
|
|
16
17
|
import { BOARD_EXPORT_FONTS } from "./board-fonts.js";
|
|
17
18
|
import { createClient } from "./client.js";
|
|
18
19
|
import { downloadPublicAudio, downloadPublicImage } from "./safe-remote-image.js";
|
|
@@ -49,7 +50,7 @@ export async function loadBoardDocument(spaceId, target) {
|
|
|
49
50
|
throw new Error("Board changed while reading. Retry the export.");
|
|
50
51
|
Object.assign(items, result.items);
|
|
51
52
|
}
|
|
52
|
-
const parsed = parseBoardDocument({ board: snapshot.board, items, animations: snapshot.animations ?? {} });
|
|
53
|
+
const parsed = parseBoardDocument({ board: snapshot.board, items, animations: snapshot.animations ?? {} }, { keepUnknown: true });
|
|
53
54
|
if (!parsed.ok)
|
|
54
55
|
throw new Error(`Board ${result.id} could not be read: ${parsed.diagnostics[0]?.path}: ${parsed.diagnostics[0]?.message}`);
|
|
55
56
|
return { document: parsed.document, boardId: result.id, title: result.title };
|
|
@@ -279,6 +280,7 @@ export async function runBoardExport(options) {
|
|
|
279
280
|
});
|
|
280
281
|
};
|
|
281
282
|
let scriptHost = null;
|
|
283
|
+
let gpu = null;
|
|
282
284
|
const textureCache = { textures: new Map(), edges: new Map(), missed: new Map() };
|
|
283
285
|
let backgroundTexture;
|
|
284
286
|
try {
|
|
@@ -321,7 +323,7 @@ export async function runBoardExport(options) {
|
|
|
321
323
|
warnings.push("The board background image could not be loaded; the fallback color was exported.");
|
|
322
324
|
}
|
|
323
325
|
}
|
|
324
|
-
if (!options.scripts && hasBoardScripts(document))
|
|
326
|
+
if (!options.scripts && options.renderer !== "gpu" && hasBoardScripts(document))
|
|
325
327
|
scriptHost = createNodeBoardScriptHost(renderer, {
|
|
326
328
|
concurrency: 2,
|
|
327
329
|
readModule: async (src) => {
|
|
@@ -329,16 +331,50 @@ export async function runBoardExport(options) {
|
|
|
329
331
|
return new TextDecoder().decode(bytes);
|
|
330
332
|
},
|
|
331
333
|
});
|
|
332
|
-
const host = scriptHost;
|
|
333
334
|
const assetKey = (item) => {
|
|
334
335
|
const key = boardExportAssetKey(item);
|
|
335
336
|
return key && omittedKeys.has(key) ? null : key;
|
|
336
337
|
};
|
|
337
338
|
const frames = [];
|
|
338
339
|
const reported = new Set();
|
|
340
|
+
const report = (text) => {
|
|
341
|
+
if (reported.has(text))
|
|
342
|
+
return;
|
|
343
|
+
reported.add(text);
|
|
344
|
+
warnings.push(text);
|
|
345
|
+
};
|
|
339
346
|
let completed = 0;
|
|
347
|
+
let decided = options.renderer === "canvas";
|
|
348
|
+
const emit = async (frame) => {
|
|
349
|
+
if (options.onFrame)
|
|
350
|
+
await options.onFrame(frame, completed);
|
|
351
|
+
else
|
|
352
|
+
frames.push(frame);
|
|
353
|
+
completed++;
|
|
354
|
+
options.onProgress?.(completed, times.length);
|
|
355
|
+
};
|
|
356
|
+
const launchGpu = async (browser) => {
|
|
357
|
+
const exporter = await launchBoardGpuExporter(gpuResources(options.spaceId, document), { browser, signal: options.signal });
|
|
358
|
+
try {
|
|
359
|
+
await exporter.init({ document, animation: options.animation ?? null, theme: options.theme });
|
|
360
|
+
}
|
|
361
|
+
catch (error) {
|
|
362
|
+
await exporter.close();
|
|
363
|
+
throw error;
|
|
364
|
+
}
|
|
365
|
+
scriptHost?.destroy();
|
|
366
|
+
scriptHost = null;
|
|
367
|
+
return exporter;
|
|
368
|
+
};
|
|
369
|
+
if (options.renderer === "gpu") {
|
|
370
|
+
const browser = findBoardGpuBrowser();
|
|
371
|
+
if (!browser)
|
|
372
|
+
throw new Error("GPU export needs Chrome, Chromium or Edge. Install one, or set COHUB_CHROME to its path.");
|
|
373
|
+
gpu = await launchGpu(browser);
|
|
374
|
+
}
|
|
340
375
|
for (const time of times) {
|
|
341
376
|
options.signal?.throwIfAborted();
|
|
377
|
+
const host = scriptHost;
|
|
342
378
|
host?.clearFrames();
|
|
343
379
|
const frameOptions = { sampler, camera: options.camera, ...(time === null ? {} : { at: { animation: options.animation, time } }), region, scale: options.scale, padding: times.length > 1 ? 0 : options.padding };
|
|
344
380
|
const initial = prepareBoardExport(document, frameOptions);
|
|
@@ -346,18 +382,55 @@ export async function runBoardExport(options) {
|
|
|
346
382
|
continue;
|
|
347
383
|
let prepared = initial;
|
|
348
384
|
trace("prepare", completed, initial.plan);
|
|
349
|
-
|
|
350
|
-
await
|
|
351
|
-
for (const
|
|
352
|
-
const error =
|
|
385
|
+
const prepareScripts = async (scripts, shaders) => {
|
|
386
|
+
await scripts.prepare(initial.scene.items, [time ?? 0], initial.plan.scale, initial.document.board, { shaders });
|
|
387
|
+
for (const id of [...Object.keys(initial.document.board.scripts ?? {}), ...initial.scene.items.map((item) => item.id)]) {
|
|
388
|
+
const error = scripts.error(id);
|
|
353
389
|
if (error)
|
|
354
|
-
throw new Error(`${
|
|
390
|
+
throw new Error(`${initial.document.board.scripts?.[id]?.src ?? initial.scene.get(id)?.script?.src ?? id}: ${error}`);
|
|
355
391
|
}
|
|
356
|
-
|
|
392
|
+
return prepareBoardExport(document, { ...frameOptions, scripts });
|
|
393
|
+
};
|
|
394
|
+
if (host && !gpu) {
|
|
395
|
+
const scripted = await prepareScripts(host, !decided);
|
|
357
396
|
if (!scripted)
|
|
358
397
|
continue;
|
|
359
398
|
prepared = scripted;
|
|
360
399
|
}
|
|
400
|
+
if (!decided) {
|
|
401
|
+
decided = true;
|
|
402
|
+
const shaded = (host?.shaders?.(prepared.document, time ?? 0) ?? []).map((owner) => owner.id);
|
|
403
|
+
const browser = shaded.length ? findBoardGpuBrowser() : null;
|
|
404
|
+
if (browser)
|
|
405
|
+
gpu = await launchGpu(browser);
|
|
406
|
+
else if (host && shaded.length) {
|
|
407
|
+
report(`Shaders in ${shaded.join(", ")} need Chrome, Chromium or Edge; install one or set COHUB_CHROME to draw them.`);
|
|
408
|
+
host.clearFrames();
|
|
409
|
+
const scripted = await prepareScripts(host, false);
|
|
410
|
+
if (!scripted)
|
|
411
|
+
continue;
|
|
412
|
+
prepared = scripted;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
if (gpu) {
|
|
416
|
+
trace("gpu", completed, prepared.plan);
|
|
417
|
+
const result = await gpu.render({
|
|
418
|
+
time,
|
|
419
|
+
region,
|
|
420
|
+
...(options.camera ? { camera: options.camera } : {}),
|
|
421
|
+
scale: options.scale,
|
|
422
|
+
...(times.length > 1 || options.padding === undefined ? {} : { padding: options.padding }),
|
|
423
|
+
background: options.background,
|
|
424
|
+
format: options.format,
|
|
425
|
+
...(options.quality === undefined ? {} : { quality: options.quality }),
|
|
426
|
+
withImages: options.withImages,
|
|
427
|
+
imageMemory: imageMemoryBytes,
|
|
428
|
+
});
|
|
429
|
+
for (const warning of result.warnings)
|
|
430
|
+
report(options.withImages && warning.kind === "images-missing" ? describeBoardExportWarning(warning) : describeWarning(warning));
|
|
431
|
+
await emit({ time, bytes: result.bytes, width: result.width, height: result.height, scale: result.scale, itemCount: result.itemCount, format: options.format });
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
361
434
|
trace("images", completed, prepared.plan);
|
|
362
435
|
if (options.withImages) {
|
|
363
436
|
const visible = prepared.plan.items.filter((item) => prepared.scene.opacity(item.id) > 0);
|
|
@@ -393,12 +466,11 @@ export async function runBoardExport(options) {
|
|
|
393
466
|
for (const warning of result.warnings) {
|
|
394
467
|
if (warning.kind === "images-missing" && options.withImages)
|
|
395
468
|
continue;
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
reported.add(text);
|
|
469
|
+
if (warning.kind === "shaders-unsupported" && options.renderer !== "canvas")
|
|
470
|
+
continue;
|
|
471
|
+
report(describeWarning(warning));
|
|
400
472
|
}
|
|
401
|
-
|
|
473
|
+
await emit({
|
|
402
474
|
time,
|
|
403
475
|
bytes: result.bytes,
|
|
404
476
|
width: result.plan.width,
|
|
@@ -406,18 +478,13 @@ export async function runBoardExport(options) {
|
|
|
406
478
|
scale: result.plan.scale,
|
|
407
479
|
itemCount: result.plan.items.length,
|
|
408
480
|
format: result.format,
|
|
409
|
-
};
|
|
410
|
-
if (options.onFrame)
|
|
411
|
-
await options.onFrame(frame, completed);
|
|
412
|
-
else
|
|
413
|
-
frames.push(frame);
|
|
414
|
-
completed++;
|
|
415
|
-
options.onProgress?.(completed, times.length);
|
|
481
|
+
});
|
|
416
482
|
trace("rendered", completed, result.plan);
|
|
417
483
|
}
|
|
418
484
|
return completed ? { frames, warnings } : null;
|
|
419
485
|
}
|
|
420
486
|
finally {
|
|
487
|
+
await gpu?.close();
|
|
421
488
|
scriptHost?.destroy();
|
|
422
489
|
for (const texture of textureCache.textures.values())
|
|
423
490
|
texture.destroy(true);
|
|
@@ -425,6 +492,25 @@ export async function runBoardExport(options) {
|
|
|
425
492
|
renderer.destroy();
|
|
426
493
|
}
|
|
427
494
|
}
|
|
495
|
+
export function gpuResources(spaceId, document) {
|
|
496
|
+
const client = createClient();
|
|
497
|
+
const scene = buildBoardScene(document);
|
|
498
|
+
return {
|
|
499
|
+
fonts: resolveBundledFonts().flatMap(({ path, family }) => (family ? [{ path, family }] : [])),
|
|
500
|
+
readModule: async (path) => new TextDecoder().decode((await readSpaceFileBytes(client, spaceId, path)).bytes),
|
|
501
|
+
async readPicture(request) {
|
|
502
|
+
if ("background" in request) {
|
|
503
|
+
const source = document.board.background.image && parseBoardMediaSource(document.board.background.image.src);
|
|
504
|
+
if (!source)
|
|
505
|
+
return null;
|
|
506
|
+
return source.kind === "url" ? downloadPublicImage(source.value) : readSpaceFileBytes(client, spaceId, source.value);
|
|
507
|
+
}
|
|
508
|
+
const source = boardAssetKeySource(request.key);
|
|
509
|
+
const item = scene.items.find((entry) => boardAssetKey(entry) === request.key);
|
|
510
|
+
return source && item ? fetchBoardPicture(client, spaceId, source, item, request.edge) : null;
|
|
511
|
+
},
|
|
512
|
+
};
|
|
513
|
+
}
|
|
428
514
|
function describeWarning(warning) {
|
|
429
515
|
if (warning.kind === "scale-clamped") {
|
|
430
516
|
return `Scale reduced from ${warning.requested}x to ${Number(warning.applied).toFixed(2)}x to stay within the size limit.`;
|
|
@@ -436,5 +522,5 @@ function describeWarning(warning) {
|
|
|
436
522
|
if (warning.kind === "many-items") {
|
|
437
523
|
return `${warning.count} items exported.`;
|
|
438
524
|
}
|
|
439
|
-
return warning
|
|
525
|
+
return describeBoardExportWarning(warning);
|
|
440
526
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { BoardGpuFrame, BoardGpuInit, BoardGpuResult, BoardGpuShader } from "./protocol.js";
|
|
2
|
+
export type { BoardGpuFrame, BoardGpuResult, BoardGpuShader } from "./protocol.js";
|
|
3
|
+
export declare function findBoardGpuBrowser(env?: NodeJS.ProcessEnv): string | null;
|
|
4
|
+
export type BoardGpuResources = {
|
|
5
|
+
readModule(path: string): Promise<string>;
|
|
6
|
+
readPicture(request: {
|
|
7
|
+
key: string;
|
|
8
|
+
edge: number;
|
|
9
|
+
} | {
|
|
10
|
+
background: true;
|
|
11
|
+
}): Promise<{
|
|
12
|
+
bytes: Uint8Array;
|
|
13
|
+
mimeType: string;
|
|
14
|
+
} | null>;
|
|
15
|
+
fonts: readonly {
|
|
16
|
+
family: string;
|
|
17
|
+
path: string;
|
|
18
|
+
}[];
|
|
19
|
+
};
|
|
20
|
+
export type BoardGpuExporter = {
|
|
21
|
+
readonly browser: string;
|
|
22
|
+
init(init: BoardGpuInit): Promise<void>;
|
|
23
|
+
render(frame: BoardGpuFrame): Promise<Omit<BoardGpuResult, "data"> & {
|
|
24
|
+
bytes: Uint8Array;
|
|
25
|
+
}>;
|
|
26
|
+
compile(shaders: BoardGpuShader[]): Promise<Record<string, string>>;
|
|
27
|
+
close(): Promise<void>;
|
|
28
|
+
};
|
|
29
|
+
export declare function launchBoardGpuExporter(resources: BoardGpuResources, options: {
|
|
30
|
+
browser: string;
|
|
31
|
+
signal?: AbortSignal;
|
|
32
|
+
}): Promise<BoardGpuExporter>;
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
|
5
|
+
import { createServer } from "node:http";
|
|
6
|
+
import { tmpdir } from "node:os";
|
|
7
|
+
import { basename, join } from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
export function findBoardGpuBrowser(env = process.env) {
|
|
10
|
+
const named = env.COHUB_CHROME?.trim();
|
|
11
|
+
if (named)
|
|
12
|
+
return existsSync(named) ? named : null;
|
|
13
|
+
const candidates = process.platform === "darwin"
|
|
14
|
+
? ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium", "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"]
|
|
15
|
+
: process.platform === "win32"
|
|
16
|
+
? [env.PROGRAMFILES, env["PROGRAMFILES(X86)"], env.LOCALAPPDATA].flatMap((root) => root ? [join(root, "Google/Chrome/Application/chrome.exe"), join(root, "Microsoft/Edge/Application/msedge.exe")] : [])
|
|
17
|
+
: ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "microsoft-edge"].flatMap((name) => (env.PATH ?? "").split(":").filter(Boolean).map((dir) => join(dir, name)));
|
|
18
|
+
return candidates.find((path) => existsSync(path)) ?? null;
|
|
19
|
+
}
|
|
20
|
+
const CALL_TIMEOUT_MS = 120_000;
|
|
21
|
+
function devtools(input, output) {
|
|
22
|
+
let next = 0;
|
|
23
|
+
let buffer = "";
|
|
24
|
+
const pending = new Map();
|
|
25
|
+
const listeners = new Set();
|
|
26
|
+
output.setEncoding("utf8");
|
|
27
|
+
output.on("data", (chunk) => {
|
|
28
|
+
buffer += chunk;
|
|
29
|
+
for (let end = buffer.indexOf("\0"); end >= 0; end = buffer.indexOf("\0")) {
|
|
30
|
+
const raw = buffer.slice(0, end);
|
|
31
|
+
buffer = buffer.slice(end + 1);
|
|
32
|
+
let message;
|
|
33
|
+
try {
|
|
34
|
+
message = JSON.parse(raw);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
const waiting = message.id === undefined ? undefined : pending.get(message.id);
|
|
40
|
+
if (waiting && message.id !== undefined) {
|
|
41
|
+
pending.delete(message.id);
|
|
42
|
+
if (message.error)
|
|
43
|
+
waiting.reject(new Error(message.error.message));
|
|
44
|
+
else
|
|
45
|
+
waiting.resolve(message.result ?? {});
|
|
46
|
+
}
|
|
47
|
+
for (const listener of listeners)
|
|
48
|
+
listener(message);
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
const fail = (error) => {
|
|
52
|
+
for (const waiting of pending.values())
|
|
53
|
+
waiting.reject(error);
|
|
54
|
+
pending.clear();
|
|
55
|
+
};
|
|
56
|
+
output.on("close", () => fail(new Error("The browser closed.")));
|
|
57
|
+
output.on("error", (error) => fail(error));
|
|
58
|
+
input.on("error", (error) => fail(error));
|
|
59
|
+
return {
|
|
60
|
+
send(method, params = {}, sessionId) {
|
|
61
|
+
const id = ++next;
|
|
62
|
+
return new Promise((resolve, reject) => {
|
|
63
|
+
pending.set(id, { resolve, reject });
|
|
64
|
+
input.write(`${JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) })}\0`);
|
|
65
|
+
});
|
|
66
|
+
},
|
|
67
|
+
listen(listener) {
|
|
68
|
+
listeners.add(listener);
|
|
69
|
+
},
|
|
70
|
+
fail,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
const PAGE = (fonts) => `<!doctype html><meta charset="utf-8"><style>${fonts
|
|
74
|
+
.map(({ family, file }) => `@font-face{font-family:"${family}";src:url("fonts/${file}") format("woff2");font-weight:100 900}`)
|
|
75
|
+
.join("")}</style><body>${fonts.map(({ family }) => `<span style="font-family:'${family}'">.</span>`).join("")}<script type="module" src="page.js"></script>`;
|
|
76
|
+
export async function launchBoardGpuExporter(resources, options) {
|
|
77
|
+
const bundle = fileURLToPath(new URL("./page.js", import.meta.url));
|
|
78
|
+
if (!existsSync(bundle))
|
|
79
|
+
throw new Error("This CLI build has no GPU exporter; reinstall @neta-art/cohub-cli.");
|
|
80
|
+
const token = randomBytes(16).toString("hex");
|
|
81
|
+
const fonts = resources.fonts.map(({ family, path }) => ({ family, path, file: basename(path) }));
|
|
82
|
+
const server = createServer(async (request, response) => {
|
|
83
|
+
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
84
|
+
const [, prefix, ...rest] = url.pathname.split("/");
|
|
85
|
+
const route = rest.join("/");
|
|
86
|
+
try {
|
|
87
|
+
if (prefix !== token)
|
|
88
|
+
throw Object.assign(new Error("Not found"), { status: 404 });
|
|
89
|
+
if (route === "")
|
|
90
|
+
return void response.writeHead(200, { "content-type": "text/html" }).end(PAGE(fonts));
|
|
91
|
+
if (route === "page.js")
|
|
92
|
+
return void response.writeHead(200, { "content-type": "text/javascript" }).end(await readFile(bundle));
|
|
93
|
+
const font = route.startsWith("fonts/") && fonts.find(({ file }) => file === route.slice(6));
|
|
94
|
+
if (font)
|
|
95
|
+
return void response.writeHead(200, { "content-type": "font/woff2" }).end(await readFile(font.path));
|
|
96
|
+
if (route === "module") {
|
|
97
|
+
const code = await resources.readModule(url.searchParams.get("path") ?? "");
|
|
98
|
+
return void response.writeHead(200, { "content-type": "text/javascript" }).end(code);
|
|
99
|
+
}
|
|
100
|
+
if (route === "asset") {
|
|
101
|
+
const picture = await resources.readPicture(url.searchParams.has("background")
|
|
102
|
+
? { background: true }
|
|
103
|
+
: { key: url.searchParams.get("key") ?? "", edge: Number(url.searchParams.get("edge")) || 4096 });
|
|
104
|
+
if (!picture)
|
|
105
|
+
throw Object.assign(new Error("Not found"), { status: 404 });
|
|
106
|
+
return void response.writeHead(200, { "content-type": picture.mimeType }).end(picture.bytes);
|
|
107
|
+
}
|
|
108
|
+
throw Object.assign(new Error("Not found"), { status: 404 });
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
response.writeHead(error.status ?? 500).end(error instanceof Error ? error.message : String(error));
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
115
|
+
const port = server.address().port;
|
|
116
|
+
const profile = await mkdtemp(join(tmpdir(), "cohub-board-gpu-"));
|
|
117
|
+
let chrome = null;
|
|
118
|
+
const close = async () => {
|
|
119
|
+
chrome?.kill();
|
|
120
|
+
chrome = null;
|
|
121
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
122
|
+
await rm(profile, { recursive: true, force: true }).catch(() => { });
|
|
123
|
+
};
|
|
124
|
+
const start = async (sandbox) => {
|
|
125
|
+
const child = spawn(options.browser, [
|
|
126
|
+
"--headless=new", "--remote-debugging-pipe", `--user-data-dir=${profile}`, "--no-first-run", "--no-default-browser-check",
|
|
127
|
+
"--disable-extensions", "--disable-background-networking", "--mute-audio", "--hide-scrollbars", "--enable-unsafe-swiftshader",
|
|
128
|
+
...(sandbox ? [] : ["--no-sandbox"]), "about:blank",
|
|
129
|
+
], { stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"] });
|
|
130
|
+
const [, , , input, output] = child.stdio;
|
|
131
|
+
const protocol = devtools(input, output);
|
|
132
|
+
child.once("exit", () => protocol.fail(new Error("The browser stopped.")));
|
|
133
|
+
child.once("error", (error) => protocol.fail(error));
|
|
134
|
+
chrome = child;
|
|
135
|
+
return { protocol, created: await protocol.send("Target.createTarget", { url: "about:blank" }) };
|
|
136
|
+
};
|
|
137
|
+
try {
|
|
138
|
+
const { protocol, created } = await start(true).catch(() => {
|
|
139
|
+
chrome?.kill();
|
|
140
|
+
return start(false);
|
|
141
|
+
});
|
|
142
|
+
options.signal?.addEventListener("abort", () => void close(), { once: true });
|
|
143
|
+
const { targetId } = created;
|
|
144
|
+
const { sessionId } = await protocol.send("Target.attachToTarget", { targetId, flatten: true });
|
|
145
|
+
const page = (method, params) => protocol.send(method, params, sessionId);
|
|
146
|
+
let crashed = null;
|
|
147
|
+
protocol.listen((message) => {
|
|
148
|
+
if (message.sessionId === sessionId && message.method === "Runtime.exceptionThrown")
|
|
149
|
+
crashed ??= String(message.params?.exceptionDetails?.exception?.description ?? "The export page failed.");
|
|
150
|
+
});
|
|
151
|
+
await page("Runtime.enable");
|
|
152
|
+
await page("Page.enable");
|
|
153
|
+
await page("Page.navigate", { url: `http://127.0.0.1:${port}/${token}/` });
|
|
154
|
+
const call = async (expression, timeoutMs = CALL_TIMEOUT_MS) => {
|
|
155
|
+
let timer;
|
|
156
|
+
const expired = new Promise((_resolve, reject) => {
|
|
157
|
+
timer = setTimeout(() => reject(new Error("The GPU exporter stopped responding; a shader may be too heavy to render.")), timeoutMs);
|
|
158
|
+
});
|
|
159
|
+
const reply = await Promise.race([page("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true }), expired])
|
|
160
|
+
.finally(() => clearTimeout(timer));
|
|
161
|
+
if (reply.exceptionDetails)
|
|
162
|
+
throw new Error(reply.exceptionDetails.exception?.description?.split("\n")[0] ?? reply.exceptionDetails.text ?? "The export page failed.");
|
|
163
|
+
return reply.result?.value;
|
|
164
|
+
};
|
|
165
|
+
const loaded = () => call("Boolean(globalThis.cohubBoardGpu)", 5_000).catch(() => false);
|
|
166
|
+
for (const started = Date.now(); !(await loaded());) {
|
|
167
|
+
if (crashed || Date.now() - started > 20_000)
|
|
168
|
+
throw new Error(crashed ?? "The GPU exporter did not start.");
|
|
169
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
browser: options.browser,
|
|
173
|
+
async init(init) {
|
|
174
|
+
await call(`cohubBoardGpu.init(${JSON.stringify(init)})`);
|
|
175
|
+
},
|
|
176
|
+
compile: (shaders) => call(`cohubBoardGpu.compile(${JSON.stringify(shaders)})`),
|
|
177
|
+
async render(frame) {
|
|
178
|
+
const { data, ...rest } = await call(`cohubBoardGpu.render(${JSON.stringify(frame)})`);
|
|
179
|
+
return { ...rest, bytes: new Uint8Array(Buffer.from(data, "base64")) };
|
|
180
|
+
},
|
|
181
|
+
close,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
await close();
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
}
|