@neta-art/cohub-cli 10.25.1 → 10.27.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.
@@ -1,4 +1,4 @@
1
1
  import { m as parseBoardDocument } from "./id.js";
2
2
  import { A as boardScriptAttachments, D as boardShaderParameters, E as boardTimedMedia, S as boardTexturePixels, T as boardMediaSpans, _ as selectBoardExportAssets, a as describeBoardScriptLanes, c as boardRenderTheme, d as inspectBoardScene, f as measureBoardText, g as planBoardExport, i as createNodeBoardScriptHost, j as hasBoardScripts, l as checkBoardShader, m as boardAutoplayLoops, n as createNodeBoardRenderer, o as describeBoardExportWarning, p as createBoardRenderSampler, r as exportBoardImageBytes, s as prepareBoardExport, t as createBoardScriptHarness, u as inspectBoardItems, v as boardAssetKey, w as boardMediaRate, x as boardTextureEdge, y as boardAssetKeySource } from "./board-kernel.js";
3
- import { J as itemBounds, N as BOARD_SCRIPT_DRAWING_EXAMPLE, P as BOARD_SCRIPT_RAIN_EXAMPLE, S as createBoardAnimationSampler, c as boardPathTrack, d as boardSequencePatch, i as boardFrameRegions, k as boardAnimatesScriptParams, l as boardPlacePatch, s as boardRegionStep, tt as rectsIntersect, u as boardSequence, w as buildBoardScene } from "./themes.js";
3
+ import { A as boardAnimatesScriptParams, C as createBoardAnimationSampler, F as BOARD_SCRIPT_RAIN_EXAMPLE, P as BOARD_SCRIPT_DRAWING_EXAMPLE, T as buildBoardScene, X as itemBounds, c as boardPathTrack, d as boardSequencePatch, i as boardFrameRegions, l as boardPlacePatch, rt as rectsIntersect, s as boardRegionStep, u as boardSequence } from "./themes.js";
4
4
  export { BOARD_SCRIPT_DRAWING_EXAMPLE, BOARD_SCRIPT_RAIN_EXAMPLE, boardAnimatesScriptParams, boardAssetKey, boardAssetKeySource, boardAutoplayLoops, boardFrameRegions, boardMediaRate, boardMediaSpans, boardPathTrack, boardPlacePatch, boardRegionStep, boardRenderTheme, boardScriptAttachments, boardSequence, boardSequencePatch, boardShaderParameters, boardTextureEdge, boardTexturePixels, boardTimedMedia, buildBoardScene, checkBoardShader, createBoardAnimationSampler, createBoardRenderSampler, createBoardScriptHarness, createNodeBoardRenderer, createNodeBoardScriptHost, describeBoardExportWarning, describeBoardScriptLanes, exportBoardImageBytes, hasBoardScripts, inspectBoardItems, inspectBoardScene, itemBounds, measureBoardText, parseBoardDocument, planBoardExport, prepareBoardExport, rectsIntersect, selectBoardExportAssets };
@@ -1,5 +1,5 @@
1
1
  import { C as boardModelFormat, g as planBoardExport } from "./board-kernel.js";
2
- import { w as buildBoardScene } from "./themes.js";
2
+ import { T as buildBoardScene } from "./themes.js";
3
3
  import { i as settleBoardDocument, s as loadBoardDocument } from "./board-export-resources.js";
4
4
  import { a as findBoardGpuBrowser, r as openBoardGpu } from "./daemon.js";
5
5
  import { r as gpuResources } from "./board-export.js";
@@ -1,7 +1,7 @@
1
1
  import { t as createClient } from "./client.js";
2
2
  import { d as diffMergePatch } from "./id.js";
3
3
  import { A as boardScriptAttachments, D as boardShaderParameters, O as boardScriptSenseOf, a as describeBoardScriptLanes, g as planBoardExport, k as parseBoardScriptInputs, l as checkBoardShader, n as createNodeBoardRenderer, t as createBoardScriptHarness } from "./board-kernel.js";
4
- import { J as itemBounds, tt as rectsIntersect, w as buildBoardScene } from "./themes.js";
4
+ import { T as buildBoardScene, X as itemBounds, rt as rectsIntersect } from "./themes.js";
5
5
  import { i as settleBoardDocument, s as loadBoardDocument } from "./board-export-resources.js";
6
6
  import { a as findBoardGpuBrowser, r as openBoardGpu } from "./daemon.js";
7
7
  import { a as readSpaceFileBytes, o as resolveBundledFonts, r as gpuResources, s as runBoardExport } from "./board-export.js";
@@ -114,7 +114,35 @@ function parseStep(entry, index) {
114
114
  if (typeof step.inputs !== "string" || !step.inputs) throw new Error(`${name}.inputs must be a Space file path`);
115
115
  return { inputs: step.inputs };
116
116
  }
117
- throw new Error(`${name} must be one of wait, tool, tap, drag, move, pointer, key, select, input or inputs`);
117
+ if ("peers" in step) {
118
+ if (!Array.isArray(step.peers)) throw new Error(`${name}.peers must list viewers`);
119
+ return { peers: step.peers.map((entry, at) => parsePeer(entry, `${name}.peers[${at}]`)) };
120
+ }
121
+ if ("broadcast" in step) {
122
+ if (typeof step.broadcast !== "string" || !step.broadcast) throw new Error(`${name}.broadcast must be an event type`);
123
+ if (typeof step.to !== "string" || !step.to) throw new Error(`${name}.to must be the id of the script that receives it`);
124
+ if (step.from !== void 0 && typeof step.from !== "string") throw new Error(`${name}.from must be a viewer name`);
125
+ return {
126
+ broadcast: step.broadcast,
127
+ to: step.to,
128
+ data: step.data ?? null,
129
+ from: step.from ?? "Peer"
130
+ };
131
+ }
132
+ throw new Error(`${name} must be one of wait, tool, tap, drag, move, pointer, key, select, input, inputs, peers or broadcast`);
133
+ }
134
+ function parsePeer(entry, name) {
135
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) throw new Error(`${name} must be an object`);
136
+ const peer = entry;
137
+ if (typeof peer.name !== "string" || !peer.name) throw new Error(`${name}.name must be a viewer name`);
138
+ if (peer.pointerType !== void 0 && !POINTER_TYPES.includes(peer.pointerType)) throw new Error(`${name}.pointerType must be one of ${POINTER_TYPES.join(", ")}`);
139
+ if (peer.pressed !== void 0 && typeof peer.pressed !== "boolean") throw new Error(`${name}.pressed must be a boolean`);
140
+ return {
141
+ name: peer.name,
142
+ ...peer.at !== void 0 ? { point: point(peer.at, `${name}.at`) } : {},
143
+ ...peer.pointerType !== void 0 ? { pointerType: peer.pointerType } : {},
144
+ ...peer.pressed !== void 0 ? { pressed: peer.pressed } : {}
145
+ };
118
146
  }
119
147
  async function run(harness, steps, progress, presses, readInputs) {
120
148
  for (const [index, step] of steps.entries()) {
@@ -131,6 +159,8 @@ async function run(harness, steps, progress, presses, readInputs) {
131
159
  await harness.key("keyup", step.key);
132
160
  } else if ("input" in step) await harness.input(step.input, step.data);
133
161
  else if ("inputs" in step) await harness.replay(parseBoardScriptInputs(await readInputs(step.inputs)));
162
+ else if ("peers" in step) await harness.peers(step.peers);
163
+ else if ("broadcast" in step) await harness.broadcast(step.to, step.broadcast, step.data, { name: step.from });
134
164
  else await harness.select(step.select);
135
165
  if (press) presses.push({
136
166
  step: index,
@@ -228,6 +258,7 @@ async function runBoardSimulation(options) {
228
258
  ...early.errors
229
259
  },
230
260
  presses,
261
+ broadcasts: [],
231
262
  warnings: ["Stopped before the steps: fix the shader errors first."],
232
263
  shaders: {
233
264
  count: initial.shaders.length,
@@ -252,6 +283,7 @@ async function runBoardSimulation(options) {
252
283
  changes: diffMergePatch(document, current.document) ?? {},
253
284
  errors,
254
285
  presses,
286
+ broadcasts: [...current.broadcasts],
255
287
  warnings,
256
288
  ...shaders.length ? { shaders: {
257
289
  count: shaders.length,
@@ -10,7 +10,7 @@ function parseBoardTime(value, name = "time") {
10
10
  if (!match?.[1]) throw new Error(`${name}: expected a time such as 1500, 500ms, 12.5s or 2m`);
11
11
  return Math.round(Number(match[1]) * (UNITS[(match[2] ?? "").toLowerCase()] ?? 1) * 1e3) / 1e3;
12
12
  }
13
- function parseBoardTimes(value, name = "--at", limit = 1e4) {
13
+ function parseBoardTimes(value, name = "--at", limit = 1e4, fps) {
14
14
  if (value.includes(",")) {
15
15
  const entries = value.split(",");
16
16
  if (entries.length > limit) throw new Error(`${name}: frame count exceeds the limit of ${limit}`);
@@ -18,11 +18,13 @@ function parseBoardTimes(value, name = "--at", limit = 1e4) {
18
18
  }
19
19
  const parts = value.split(":");
20
20
  if (parts.length === 1) return [parseBoardTime(value, name)];
21
- if (parts.length !== 3) throw new Error(`${name}: expected a time or start:end:step`);
22
- const [start, end, step] = parts.map((part) => parseBoardTime(part, name));
23
- if (step <= 0) throw new Error(`${name}: step must be greater than zero`);
21
+ if (parts.length === 2 && !fps) throw new Error(`${name}: start:end needs --fps, or write start:end:step`);
22
+ if (parts.length !== 2 && parts.length !== 3) throw new Error(`${name}: expected a time or start:end:step`);
23
+ const [start, end, written] = parts.map((part) => parseBoardTime(part, name));
24
+ const step = written ?? 1e3 / fps;
25
+ if (!(step > 0)) throw new Error(`${name}: step must be greater than zero`);
24
26
  if (end < start) throw new Error(`${name}: end must not be before start`);
25
- const count = Math.floor((end - start) / step + 1e-9) + 1;
27
+ const count = Math.floor((end - start + Math.min(.5, step / 2)) / step) + 1;
26
28
  if (count > limit) throw new Error(`${name}: ${count} frames exceed the limit of ${limit}`);
27
29
  return Array.from({ length: count }, (_, index) => Math.round((start + index * step) * 1e3) / 1e3);
28
30
  }
@@ -1,7 +1,7 @@
1
1
  import { m as record, p as object, x as toJSONSchema } from "./schemas.js";
2
2
  import { C as error, D as json, E as handleHttp, O as jsonRequested, b as resolveSpace, j as table, k as ok, r as createRealtimeClient, t as createClient } from "./client.js";
3
- import { $ as BoardAnimationHeaderSchema, G as BOARD_COLOR_TOKENS, K as BOARD_EFFECT_KINDS, W as BOARD_CAMERA_TARGET, X as BOARD_ITEM_TYPES, Y as BOARD_ITEM_SCHEMAS, at as BoardSettingsSchema, bt as BOARD_TEXT_SCALE, f as listBoardProperties, g as resolveBoardProperty, ht as BOARD_DEFAULT_SIZES, it as BoardScriptSchema, lt as isBuiltinItemType, ot as BoardTrackSchema, q as BOARD_EFFECT_KIND_INFO, rt as BoardKeySchema, tt as BoardExtensionItemSchema, vt as BOARD_PAGE_SIZE } from "./id.js";
4
- import { F as BOARD_SCRIPT_SENSES_EXAMPLE, I as BOARD_SCRIPT_TILT_EXAMPLE, N as BOARD_SCRIPT_DRAWING_EXAMPLE, P as BOARD_SCRIPT_RAIN_EXAMPLE, S as createBoardAnimationSampler, c as boardPathTrack, d as boardSequencePatch, i as boardFrameRegions, l as boardPlacePatch, n as BOARD_THEME_IDS, s as boardRegionStep, w as buildBoardScene } from "./themes.js";
3
+ import { $ as BoardAnimationHeaderSchema, G as BOARD_COLOR_TOKENS, K as BOARD_EFFECT_KINDS, W as BOARD_CAMERA_TARGET, X as BOARD_ITEM_TYPES, Y as BOARD_ITEM_SCHEMAS, at as BoardSettingsSchema, f as listBoardProperties, g as resolveBoardProperty, gt as BOARD_DEFAULT_SIZES, it as BoardScriptSchema, lt as isBuiltinItemType, ot as BoardTrackSchema, q as BOARD_EFFECT_KIND_INFO, rt as BoardKeySchema, tt as BoardExtensionItemSchema, xt as BOARD_TEXT_SCALE, yt as BOARD_PAGE_SIZE } from "./id.js";
4
+ import { C as createBoardAnimationSampler, F as BOARD_SCRIPT_RAIN_EXAMPLE, I as BOARD_SCRIPT_SENSES_EXAMPLE, L as BOARD_SCRIPT_SPARKS_EXAMPLE, P as BOARD_SCRIPT_DRAWING_EXAMPLE, R as BOARD_SCRIPT_TILT_EXAMPLE, T as buildBoardScene, c as boardPathTrack, d as boardSequencePatch, i as boardFrameRegions, l as boardPlacePatch, n as BOARD_THEME_IDS, s as boardRegionStep } from "./themes.js";
5
5
  import { a as settleBoardMediaDurations, i as settleBoardDocument, o as settleBoardPatch, s as loadBoardDocument, t as BOARD_EXPORT_RENDERERS } from "./board-export-resources.js";
6
6
  import { n as parseBoardTime, r as parseBoardTimes, t as formatBoardTime } from "./board-time.js";
7
7
  import { constants, existsSync } from "node:fs";
@@ -131,6 +131,8 @@ const BOARD_SCRIPT_API = {
131
131
  scene: "scene(items, options?): replace this instance's world or screen layer of temporary Board items; never saved. IDs are unique across both layers.",
132
132
  hitRegions: "hitRegions(regions): replace the input declarations.",
133
133
  emit: "emit(id, type, data?): send a custom event to another scripted item in scope, or to any Board script by its key. Exports deliver it within the same moment, in document order. A handler may answer with emits; past 16 in a row the emit rejects, so emit from onFrame() to send on the next step.",
134
+ broadcast: "broadcast(type, data?): deliver a custom event to this script on every viewer's screen, this one included, so others see the effect of this viewer's input. The event carries peer: null here, { id, actorId, name, color } from another viewer. Fire-and-forget and lossy: data up to 1024 characters of JSON, about 10 a second per viewer, nothing while the page is hidden, nothing for viewers who join later. While a handler of another viewer's broadcast runs, it can neither commit nor broadcast; after an await it is unguarded and may save twice, so answer broadcasts with presentation only and persist with commit() from your own input. Like emit, past 16 handlers deep it rejects. Exports deliver it only here.",
135
+ peers: "Other viewers on the Board: { id, actorId, name, color, point (owner coordinates, or null), pointerType, pressed }; current after each peerschange.",
134
136
  commit: "commit(patch): save a Board patch; resolves true once written here. Within 5 s of this viewer's input, outside onFrame steps, it saves undoably; otherwise one live editor saves it and others resolve false. It may edit items in scope, add children to a scoped frame, and attach modules already running in scope. Read-only viewers cannot commit: capabilities.has(\"board.commit\") is false there.",
135
137
  layoutText: "layoutText({ text, fontSize?, fontWeight?, font?, lineHeight?, width? }): the size a native text item would take.",
136
138
  uniforms: "uniforms(values): set the shader's declared uniforms from numbers or number arrays; kept until changed.",
@@ -191,6 +193,7 @@ const BOARD_SCRIPT_API = {
191
193
  change: "data.added, data.changed, data.removed: item ids in scope; data.source: user, script or remote.",
192
194
  gesture: "data: this viewer's draw, shape, frame or arrow gesture over the owner: id, tool, phase (start | update | end | cancel), points in owner coordinates, and on end the item it created.",
193
195
  envchange: "data: the new ctx.env.",
196
+ peerschange: "data: the other viewers, as ctx.peers; their cursors move at about 25 Hz. Exports have none.",
194
197
  "browser:devicemotion": "data: the DeviceMotionEvent's acceleration, accelerationIncludingGravity, rotationRate (deg/s) and interval, in device axes, with t its timeStamp. One event per reading.",
195
198
  "browser:deviceorientation": "data: alpha, beta, gamma, absolute, and on iOS webkitCompassHeading and webkitCompassAccuracy; t.",
196
199
  "browser:deviceorientationabsolute": "As deviceorientation, relative to the Earth, where the browser offers it.",
@@ -497,7 +500,8 @@ const MODULES = {
497
500
  custom: BOARD_SCRIPT_DRAWING_EXAMPLE,
498
501
  rain: BOARD_SCRIPT_RAIN_EXAMPLE,
499
502
  tilt: BOARD_SCRIPT_TILT_EXAMPLE,
500
- senses: BOARD_SCRIPT_SENSES_EXAMPLE
503
+ senses: BOARD_SCRIPT_SENSES_EXAMPLE,
504
+ sparks: BOARD_SCRIPT_SPARKS_EXAMPLE
501
505
  };
502
506
  /**
503
507
  * Starter documents for `boards create -i` and patches for `boards apply -i`.
@@ -962,6 +966,21 @@ const BOARD_EXAMPLES = {
962
966
  },
963
967
  script: { src: "scripts/tilt.js" }
964
968
  } } }
969
+ },
970
+ sparks: {
971
+ description: "Sparks every viewer sees where anyone clicks, and halos on the others' cursors; use --module to print scripts/sparks.js.",
972
+ value: { items: { pad: {
973
+ type: "custom",
974
+ position: {
975
+ x: 0,
976
+ y: 0
977
+ },
978
+ size: {
979
+ width: 640,
980
+ height: 400
981
+ },
982
+ script: { src: "scripts/sparks.js" }
983
+ } } }
965
984
  }
966
985
  };
967
986
  function registerBoardExampleCommands(boards) {
@@ -1171,6 +1190,30 @@ function list(value) {
1171
1190
  const entries = value?.split(",").map((entry) => entry.trim()).filter(Boolean);
1172
1191
  return entries?.length ? entries : void 0;
1173
1192
  }
1193
+ /** Filters a saved Board locally; the checkpoint API returns the whole document. */
1194
+ function selectCheckpointBoard(saved, filter) {
1195
+ const { board, items, animations, ...rest } = saved;
1196
+ let picked = Object.entries(items);
1197
+ if (filter.items) picked = picked.filter(([id]) => filter.items?.includes(id));
1198
+ if (filter.within) {
1199
+ const inside = /* @__PURE__ */ new Set([filter.within]);
1200
+ for (let grew = true; grew;) {
1201
+ grew = false;
1202
+ for (const [id, item] of Object.entries(items)) if (!inside.has(id) && typeof item.parent === "string" && inside.has(item.parent)) {
1203
+ inside.add(id);
1204
+ grew = true;
1205
+ }
1206
+ }
1207
+ picked = picked.filter(([id]) => inside.has(id));
1208
+ }
1209
+ const show = (section) => !filter.sections || filter.sections.has(section);
1210
+ return {
1211
+ ...rest,
1212
+ ...show("board") ? { board } : {},
1213
+ ...show("items") ? { items: Object.fromEntries(picked) } : {},
1214
+ ...show("animations") ? { animations: filter.animations ? Object.fromEntries(Object.entries(animations).filter(([id]) => filter.animations?.includes(id))) : animations } : {}
1215
+ };
1216
+ }
1174
1217
  async function boardClient(boards, target, spaceId) {
1175
1218
  spaceId ??= await resolveSpace(boards);
1176
1219
  return createClient().space(spaceId).boards.open(target);
@@ -1315,13 +1358,13 @@ function framePath(pattern, index) {
1315
1358
  return pattern.replace(/%(0?)(\d*)d/, (_match, zero, width) => String(index).padStart(Number(width || 0), zero ? "0" : " "));
1316
1359
  }
1317
1360
  function registerExportCommand(boards) {
1318
- withJson(boards.command("export <board>").description("Render a Board to an image, or an animation to a frame sequence").requiredOption("-o, --out <file>", "Output file; the extension picks the format. Sequences need %d, e.g. frames/%04d.png").option("--at <time>", "A moment, comma-separated moments, or start:end:step").option("--camera", "Follow the animation camera").option("--size <widthxheight>", "Camera output in pixels; frames keep their own size", "1600x900").option("--animation <id>", "Animation the --at times refer to").option("--frame <item-id>", "Export one frame as a page").option("--items <ids>", "Comma-separated item ids").option("--rect <rect>", "World rect as x,y,width,height").option("--scale <factor>", "Output pixels per board unit", "2").option("--padding <units>", "Padding around the content in board units").option("--theme <name>", `Cohub theme: ${BOARD_THEME_IDS.join(", ")}`, "dark").option("--paper <mode>", "Output paper: paper or transparent", "paper").option("--format <format>", `Override the format (${BOARD_EXPORT_FORMATS.join(", ")}, ${BOARD_VIDEO_FORMATS.join(", ")})`).option("--quality <q>", "JPEG/WebP quality from 0 to 1", "0.92").option("--fps <rate>", "Video frame rate; defaults to the --at step").option("--image-memory <mib>", "Decoded image memory budget in MiB", String(256)).option("--no-images", "Draw placeholders instead of downloading images").option("--renderer <renderer>", "auto draws in Node and uses local Chrome for shaders; canvas or gpu forces one", "auto").option("--force", "Replace existing output files").option("--timeout <time>", "Fail a frame that takes longer, naming the scripts still running", "2m").option("--inputs <file>", "A Space file of recorded browser input for scripts to replay from time 0").option("--async", "Run as a Task in the Space's sandbox and return at once; paths are Space paths")).addHelpText("after", `
1361
+ withJson(boards.command("export <board>").description("Render a Board to an image, or an animation to a frame sequence").requiredOption("-o, --out <file>", "Output file; the extension picks the format. Sequences need %d, e.g. frames/%04d.png").option("--at <time>", "A moment, comma-separated moments, start:end:step, or start:end with --fps").option("--camera", "Follow the animation camera").option("--size <widthxheight>", "Camera output in pixels, the animation's viewport by default; frames keep their own size").option("--animation <id>", "Animation the --at times refer to").option("--frame <item-id>", "Export one frame as a page").option("--items <ids>", "Comma-separated item ids").option("--rect <rect>", "World rect as x,y,width,height").option("--scale <factor>", "Output pixels per board unit", "2").option("--padding <units>", "Padding around the content in board units").option("--theme <name>", `Cohub theme: ${BOARD_THEME_IDS.join(", ")}`, "dark").option("--paper <mode>", "Output paper: paper or transparent", "paper").option("--format <format>", `Override the format (${BOARD_EXPORT_FORMATS.join(", ")}, ${BOARD_VIDEO_FORMATS.join(", ")})`).option("--quality <q>", "JPEG/WebP quality from 0 to 1", "0.92").option("--fps <rate>", "Frames a second for --at start:end; a video plays at it (defaults to the --at step)").option("--image-memory <mib>", "Decoded image memory budget in MiB", String(256)).option("--no-images", "Draw placeholders instead of downloading images").option("--renderer <renderer>", "auto draws in Node and uses local Chrome for shaders; canvas or gpu forces one", "auto").option("--force", "Replace existing output files").option("--timeout <time>", "Fail a frame that takes longer, naming the scripts still running", "2m").option("--inputs <file>", "A Space file of recorded browser input for scripts to replay from time 0").option("--async", "Run as a Task in the Space's sandbox and return at once; paths are Space paths")).addHelpText("after", `
1319
1362
  Shaders draw in a shared headless Chrome that stays up a few minutes between calls;
1320
1363
  Boards without shaders never start it. Set COHUB_BOARD_GPU_DAEMON=0 to start one per call.
1321
1364
 
1322
1365
  Examples:
1323
1366
  cohub boards export plan.board -o plan.png
1324
- cohub boards export plan.board --animation intro --at 0:20s:40ms -o intro.mp4 --async
1367
+ cohub boards export plan.board --animation intro --at 0:20s --fps 24 -o intro.mp4 --async
1325
1368
  cohub boards export plan.board --frame s2 -o slide-2.png
1326
1369
  cohub boards export plan.board --animation lecture --at 4.5s -o moment.png
1327
1370
  cohub boards export plan.board --animation lecture --at 0:6s:40ms -o frames/%04d.png
@@ -1336,11 +1379,15 @@ page: its fill and shaders, without its outline and label.`).action(async (targe
1336
1379
  process.once("SIGINT", cancel);
1337
1380
  try {
1338
1381
  const out = options.out;
1339
- const times = options.at ? parseBoardTimes(options.at) : void 0;
1382
+ const rate = options.fps ? parseNumber(options.fps, "--fps", {
1383
+ min: .01,
1384
+ max: 240
1385
+ }) : void 0;
1386
+ const times = options.at ? parseBoardTimes(options.at, "--at", 1e4, rate) : void 0;
1340
1387
  let camera;
1341
1388
  if (options.camera) {
1342
1389
  if (!options.animation || !times) throw new Error("--camera needs --animation and --at.");
1343
- camera = parseSize(options.size ?? "1600x900");
1390
+ camera = options.size ? parseSize(options.size) : "viewport";
1344
1391
  }
1345
1392
  const progress = (completed, total) => {
1346
1393
  if (!jsonRequested(options) && (completed === total || completed % 30 === 0)) process.stderr.write(`Rendered ${completed}/${total} frames\n`);
@@ -1364,10 +1411,7 @@ page: its fill and shaders, without its outline and label.`).action(async (targe
1364
1411
  if (videoFormat) {
1365
1412
  if (!times || times.length < 2) throw new Error("Video export needs an --at range.");
1366
1413
  const step = times[1] - times[0];
1367
- const fps = options.fps ? parseNumber(options.fps, "--fps", {
1368
- min: .01,
1369
- max: 240
1370
- }) : 1e3 / step;
1414
+ const fps = rate ?? 1e3 / step;
1371
1415
  if (existsSync(out) && !options.force) throw new Error(`${out} already exists; use --force to replace it.`);
1372
1416
  await mkdir(dirname(out), { recursive: true });
1373
1417
  const { runBoardVideoExport } = await import("./board-export2.js");
@@ -1480,11 +1524,15 @@ Steps are {"steps": [...]}, points in board coordinates, run on a virtual clock:
1480
1524
  {"wait": "500ms"} {"tool": "draw"} {"tap": [x, y]} {"drag": [[x, y], ...], "pointerType": "pen"}
1481
1525
  {"pointer": "down", "at": [x, y]} {"key": "Enter"} {"select": ["id"]}
1482
1526
  {"input": "browser:devicemotion", "data": {...}} {"inputs": "takes/flick.json"}
1527
+ {"peers": [{"name": "Ada", "at": [x, y], "pressed": true}]}
1528
+ {"broadcast": "burst", "to": "<script id>", "data": {...}, "from": "Ada"}
1483
1529
  {"tool": "play"} acts like an App visitor: drags move unlocked items, empty space pans,
1484
1530
  script regions take every press, and keys reach scripts that listen for them.
1485
1531
  Every source (motion, gamepad, microphone, camera, location) is on. An input step
1486
1532
  delivers one browser event to the scripts listening, shaped as \`cohub boards schema
1487
1533
  script\` describes; an inputs step replays a recording on the virtual clock.
1534
+ A peers step sets the other viewers scripts see in ctx.peers; a broadcast step delivers
1535
+ another viewer's ctx.broadcast() to a script. What the scripts broadcast is reported.
1488
1536
 
1489
1537
  Shaders are compiled with a local Chrome, Chromium or Edge when one is found, before
1490
1538
  the steps run; their errors join the scripts' errors and stop the run.
@@ -1534,6 +1582,7 @@ Examples:
1534
1582
  const changed = Object.keys(result.changes.items ?? {}).length;
1535
1583
  ok(`Simulated ${formatBoardTime(result.time)}: ${result.commits} commit${result.commits === 1 ? "" : "s"}, ${changed} item${changed === 1 ? "" : "s"} changed (not saved)`);
1536
1584
  for (const press of result.presses) console.log(` step ${press.step + 1}: ${describePress(press)}`);
1585
+ if (result.broadcasts.length) console.log(` ${result.broadcasts.length} broadcast${result.broadcasts.length === 1 ? "" : "s"}: ${[...new Set(result.broadcasts.map(({ owner, type }) => `${owner} "${type}"`))].join(", ")}`);
1537
1586
  for (const [id, message] of Object.entries(result.errors)) console.log(` ! ${id}: ${message.split("\n")[0]}`);
1538
1587
  for (const warning of result.warnings) console.log(` ! ${warning}`);
1539
1588
  if (result.shaders && !result.shaders.compiled) console.log(" Shaders were checked but not compiled; install Chrome, Chromium or Edge, or set COHUB_CHROME, to compile them.");
@@ -1668,15 +1717,32 @@ Times are milliseconds; 500ms, 12.5s and 2m also work on the command line.`);
1668
1717
  handleHttp(cause);
1669
1718
  }
1670
1719
  });
1671
- boards.command("get <board>").description("Print the Board document as JSON").option("--only <sections>", "board, items, animations (comma-separated)").option("--items <ids>", "Only these items").option("--within <frame-id>", "A frame and everything inside it").option("--rect <rect>", "Items intersecting x,y,width,height").option("--animations <ids>", "Only these animations").option("--limit <n>", "Page size for items").option("--cursor <cursor>", "Continue from a previous page's next").option("--since <version>", "Only the changes after this version; the whole Board when they are unavailable").addHelpText("after", `
1720
+ boards.command("get <board>").description("Print the Board document as JSON").option("--only <sections>", "board, items, animations (comma-separated)").option("--items <ids>", "Only these items").option("--within <frame-id>", "A frame and everything inside it").option("--rect <rect>", "Items intersecting x,y,width,height").option("--animations <ids>", "Only these animations").option("--limit <n>", "Page size for items").option("--cursor <cursor>", "Continue from a previous page's next").option("--since <version>", "Only the changes after this version; the whole Board when they are unavailable").option("--checkpoint <id>", "The Board as this checkpoint saved it").addHelpText("after", `
1672
1721
  cohub boards get plan.board
1673
1722
  cohub boards get plan.board --within s2
1674
1723
  cohub boards get plan.board --only board
1675
- cohub boards get plan.board --since 12`).action(async (target, options) => {
1724
+ cohub boards get plan.board --since 12
1725
+ cohub boards get plan.board --checkpoint <checkpoint-id>`).action(async (target, options) => {
1676
1726
  try {
1677
1727
  const only = list(options.only);
1678
1728
  if (only?.some((section) => section !== "board" && section !== "items" && section !== "animations")) throw new Error("--only takes board, items, animations, or a combination.");
1679
1729
  const sections = only ? new Set(only) : null;
1730
+ if (options.checkpoint) {
1731
+ const unsupported = [
1732
+ "rect",
1733
+ "limit",
1734
+ "cursor",
1735
+ "since"
1736
+ ].filter((name) => options[name] !== void 0);
1737
+ if (unsupported.length) throw new Error(`--checkpoint cannot be combined with ${unsupported.map((name) => `--${name}`).join(", ")}.`);
1738
+ const saved = await createClient().space(await resolveSpace(boards)).checkpoints(options.checkpoint).board(target);
1739
+ return json(selectCheckpointBoard(saved, {
1740
+ sections,
1741
+ items: list(options.items),
1742
+ within: options.within,
1743
+ animations: list(options.animations)
1744
+ }));
1745
+ }
1680
1746
  const input = {
1681
1747
  ...only ? { only: only.filter((section) => section !== "board") } : {},
1682
1748
  ...list(options.items) ? { items: list(options.items) } : {},
@@ -1710,7 +1776,7 @@ Times are milliseconds; 500ms, 12.5s and 2m also work on the command line.`);
1710
1776
  handleHttp(cause);
1711
1777
  }
1712
1778
  });
1713
- withJson(boards.command("apply <board> [patch]").description("Merge a patch into the Board: fields merge, null deletes").option("-i, --input <file>", "Patch JSON; - for stdin").option("--replace", "Make the document equal to the input instead of merging").option("--cascade", "Also delete children and tracks of deleted items, and tracks of deleted Board scripts").option("--dry-run", "Validate without writing").option("--base-version <n>", "Fail if the Board moved past this version").option("--mutation-id <id>", "Stable id; retries never apply twice")).addHelpText("after", `
1779
+ withJson(boards.command("apply <board> [patch]").description("Merge a patch into the Board: fields merge, null deletes").option("-i, --input <file>", "Patch JSON; - for stdin").option("--replace", "Make the document equal to the input instead of merging; a Board with items needs --base-version").option("--cascade", "Also delete children and tracks of deleted items, and tracks of deleted Board scripts").option("--dry-run", "Validate without writing").option("--base-version <n>", "Fail if the Board moved past this version").option("--mutation-id <id>", "Stable id; retries never apply twice")).addHelpText("after", `
1714
1780
  cohub boards apply plan.board '{"items":{"t1":{"type":"text","props":{"text":"Hi","fontSize":48}}}}'
1715
1781
  cohub boards apply plan.board '{"items":{"t1":{"position":{"x":200}}}}'
1716
1782
  cohub boards apply plan.board '{"items":{"t1":null}}'
@@ -1719,6 +1785,18 @@ Times are milliseconds; 500ms, 12.5s and 2m also work on the command line.`);
1719
1785
  const spaceId = await resolveSpace(boards);
1720
1786
  const board = await boardClient(boards, target, spaceId);
1721
1787
  const read = await readPatch(inline, options.input, BOARD_TRANSACTION_INPUT_MAX_BYTES);
1788
+ let baseVersion = options.baseVersion === void 0 ? void 0 : parseNumber(options.baseVersion, "--base-version", {
1789
+ min: 0,
1790
+ integer: true
1791
+ });
1792
+ if (options.replace && !options.dryRun && baseVersion === void 0) {
1793
+ const current = await board.get({
1794
+ only: ["items"],
1795
+ limit: 1
1796
+ });
1797
+ if (Object.keys(current.items ?? {}).length) throw new Error(`--replace deletes everything the input leaves out of "${current.title ?? current.id}" (${current.id}, version ${current.version}). Pass --base-version ${current.version} to replace it.`);
1798
+ baseVersion = current.version;
1799
+ }
1722
1800
  const patch = await settleBoardPatch(spaceId, read, async (items) => options.replace ? {} : board.get({
1723
1801
  only: ["items"],
1724
1802
  items
@@ -1727,10 +1805,7 @@ Times are milliseconds; 500ms, 12.5s and 2m also work on the command line.`);
1727
1805
  ...options.replace ? { replace: true } : {},
1728
1806
  ...options.cascade ? { cascade: true } : {},
1729
1807
  ...options.dryRun ? { dryRun: true } : {},
1730
- ...options.baseVersion === void 0 ? {} : { baseVersion: parseNumber(options.baseVersion, "--base-version", {
1731
- min: 0,
1732
- integer: true
1733
- }) },
1808
+ ...baseVersion === void 0 ? {} : { baseVersion },
1734
1809
  ...options.mutationId ? { mutationId: options.mutationId } : {}
1735
1810
  });
1736
1811
  if (jsonRequested(options)) return json(result);
@@ -1303,14 +1303,18 @@ var BillingApi = class {
1303
1303
  this.transport = transport;
1304
1304
  }
1305
1305
  async getCredits(input) {
1306
- const query = input?.tokenType ? `?tokenType=${encodeURIComponent(input.tokenType)}` : "";
1307
- return this.transport.request(`/api/billing/credits${query}`);
1306
+ const params = new URLSearchParams();
1307
+ if (input?.tokenType) params.set("tokenType", input.tokenType);
1308
+ if (input?.includeExhausted) params.set("include", "exhausted");
1309
+ const query = params.toString();
1310
+ return this.transport.request(`/api/billing/credits${query ? `?${query}` : ""}`);
1308
1311
  }
1309
1312
  async getBalanceActivities(input) {
1310
1313
  const params = new URLSearchParams();
1311
1314
  if (input?.tokenType) params.set("tokenType", input.tokenType);
1312
- if (input?.page) params.set("page", String(input.page));
1315
+ if (input?.cursor) params.set("cursor", input.cursor);
1313
1316
  if (input?.limit) params.set("limit", String(input.limit));
1317
+ if (input?.filter) params.set("filter", input.filter);
1314
1318
  const query = params.toString();
1315
1319
  return this.transport.request(`/api/billing/balance-activities${query ? `?${query}` : ""}`);
1316
1320
  }
@@ -2927,6 +2931,12 @@ async function fileText(file, customFetch = fetch) {
2927
2931
  if (file.encoding !== "base64") return file.content;
2928
2932
  return new TextDecoder().decode(Uint8Array.from(atob(file.content), (char) => char.charCodeAt(0)));
2929
2933
  }
2934
+ async function readBoardId(files, path, customFetch) {
2935
+ const file = await files.read(path, customFetch);
2936
+ if (isSpaceFsSymlink(file)) throw new Error(`${path} is a symbolic link to ${file.target}.`);
2937
+ if (!("content" in file)) throw new Error(`${path} is being prepared; try again shortly.`);
2938
+ return parseBoardManifest(await fileText(file, customFetch)).boardId;
2939
+ }
2930
2940
  var SpaceBoardsApi = class {
2931
2941
  http;
2932
2942
  spaceId;
@@ -2955,11 +2965,8 @@ var SpaceBoardsApi = class {
2955
2965
  async open(target, customFetch) {
2956
2966
  return this.byId(isBoardPath(target) ? await this.resolveId(target, customFetch) : target);
2957
2967
  }
2958
- async resolveId(path, customFetch) {
2959
- const file = await this.files.read(path, customFetch);
2960
- if (isSpaceFsSymlink(file)) throw new Error(`${path} is a symbolic link to ${file.target}.`);
2961
- if (!("content" in file)) throw new Error(`${path} is being prepared; try again shortly.`);
2962
- return parseBoardManifest(await fileText(file, customFetch)).boardId;
2968
+ resolveId(path, customFetch) {
2969
+ return readBoardId(this.files, path, customFetch);
2963
2970
  }
2964
2971
  /** Create a `.board` file and its Board, optionally with an initial document. */
2965
2972
  create(input) {
@@ -2988,8 +2995,9 @@ var SpaceWalletApi = class {
2988
2995
  funding() {
2989
2996
  return this.transport.request(`/api/spaces/${this.spaceId}/wallet/funding`);
2990
2997
  }
2991
- activities(page = 1) {
2992
- return this.transport.request(`/api/spaces/${this.spaceId}/wallet/activities?page=${page}`);
2998
+ activities(cursor) {
2999
+ const query = cursor ? `?cursor=${encodeURIComponent(cursor)}` : "";
3000
+ return this.transport.request(`/api/spaces/${this.spaceId}/wallet/activities${query}`);
2993
3001
  }
2994
3002
  createOrder(input) {
2995
3003
  return this.transport.request(`/api/spaces/${this.spaceId}/wallet/orders`, {
@@ -6426,6 +6434,21 @@ var SpaceCheckpointFilesApi = class {
6426
6434
  if (!source) throw new HttpError(`Checkpoint file cannot be saved: ${path}`, 404, null);
6427
6435
  return source;
6428
6436
  }
6437
+ /** A browser-ready URL for a saved file; null when it was not saved. */
6438
+ async resolve(path, options = {}) {
6439
+ let file;
6440
+ try {
6441
+ file = await this.read(path);
6442
+ } catch (error) {
6443
+ if (error instanceof HttpError && (error.status === 404 || error.status === 410)) return null;
6444
+ throw error;
6445
+ }
6446
+ if (file.delivery === "url" && file.url) return file.media ? {
6447
+ url: file.url,
6448
+ media: file.media
6449
+ } : { url: file.url };
6450
+ return (options.purpose ?? "preview") === "preview" ? { url: inlineFileDataUrl(file) } : null;
6451
+ }
6429
6452
  };
6430
6453
  async function hydrateCheckpointDiffSummary(summary, customFetch) {
6431
6454
  if (summary.delivery !== "url" || !summary.url) return {
@@ -6505,6 +6528,11 @@ var SpaceCheckpointApi = class {
6505
6528
  get(customFetch) {
6506
6529
  return this.transport.request(`/api/spaces/${this.spaceId}/checkpoints/${this.id}`, { fetch: customFetch });
6507
6530
  }
6531
+ /** The Board as this checkpoint captured it, by id or by `.board` path. */
6532
+ async board(target, customFetch) {
6533
+ const boardId = isBoardPath(target) ? await readBoardId(this.files, target, customFetch) : target;
6534
+ return this.transport.request(`/api/spaces/${this.spaceId}/checkpoints/${this.id}/boards/${encodeURIComponent(boardId)}`, { fetch: customFetch });
6535
+ }
6508
6536
  };
6509
6537
  function createSpaceCheckpointsApi(transport, spaceId) {
6510
6538
  const checkpoint = (checkpointId) => new SpaceCheckpointApi(transport, spaceId, checkpointId);
@@ -6965,6 +6993,14 @@ var TasksApi = class {
6965
6993
  };
6966
6994
  //#endregion
6967
6995
  //#region ../sdk/src/apis/user.ts
6996
+ function userListQuery(options) {
6997
+ const params = new URLSearchParams();
6998
+ if (options.filter) params.set("filter", options.filter);
6999
+ if (options.cursor) params.set("cursor", options.cursor);
7000
+ if (options.limit !== void 0) params.set("limit", String(options.limit));
7001
+ const query = params.toString();
7002
+ return query ? `?${query}` : "";
7003
+ }
6968
7004
  const usageDate = (value) => value instanceof Date ? value.toISOString() : value;
6969
7005
  var UserApi = class {
6970
7006
  transport;
@@ -7010,6 +7046,12 @@ var UserApi = class {
7010
7046
  const query = params.toString();
7011
7047
  return this.transport.request(`/api/me/sessions${query ? `?${query}` : ""}`, { fetch });
7012
7048
  }
7049
+ listApps(options = {}) {
7050
+ return this.transport.request(`/api/me/apps${userListQuery(options)}`);
7051
+ }
7052
+ listCronJobs(options = {}) {
7053
+ return this.transport.request(`/api/me/cron-jobs${userListQuery(options)}`);
7054
+ }
7013
7055
  getSession(sessionId, customFetch) {
7014
7056
  return this.transport.request(`/api/sessions/${sessionId}`, { fetch: customFetch });
7015
7057
  }
@@ -1,4 +1,5 @@
1
1
  import { C as error, D as json, E as handleHttp, O as jsonRequested, j as table, k as ok, t as createClient } from "./client.js";
2
+ import { n as isUserCronJobFilter } from "./user-lists.js";
2
3
  import { readFileSync } from "node:fs";
3
4
  //#region src/commands/cron-jobs.ts
4
5
  function readJsonObject(pathOrJson) {
@@ -9,13 +10,50 @@ function readJsonObject(pathOrJson) {
9
10
  }
10
11
  function registerCronJobs(program) {
11
12
  const cmd = program.command("cron-jobs").description("Scheduled jobs");
12
- cmd.command("ls [spaceId]").alias("list").description("List scheduled jobs").option("--json", "Output as JSON").action(async (spaceId, opts) => {
13
+ cmd.command("ls [spaceId]").alias("list").description("List scheduled jobs in a space, or yours across spaces").option("--filter <filter>", "Without a space: mine, all, paused, or attention", "mine").option("--cursor <cursor>", "Without a space: pagination cursor").option("--json", "Output as JSON").action(async (spaceId, opts) => {
13
14
  const client = createClient();
14
15
  try {
15
- const result = await client.cronJobs.list(spaceId);
16
+ if (spaceId) {
17
+ const result = await client.cronJobs.list(spaceId);
18
+ if (jsonRequested(opts)) return json(result);
19
+ if (result.jobs.length === 0) return console.log(" (empty)");
20
+ table(result.jobs, [
21
+ {
22
+ key: "id",
23
+ label: "ID"
24
+ },
25
+ {
26
+ key: "title",
27
+ label: "Title"
28
+ },
29
+ {
30
+ key: "taskType",
31
+ label: "Type"
32
+ },
33
+ {
34
+ key: "cronExpression",
35
+ label: "Schedule"
36
+ },
37
+ {
38
+ key: "enabled",
39
+ label: "Enabled"
40
+ }
41
+ ]);
42
+ return;
43
+ }
44
+ if (!isUserCronJobFilter(opts.filter)) error("Invalid filter", "Expected mine, all, paused, or attention");
45
+ const result = await client.user.listCronJobs({
46
+ filter: opts.filter,
47
+ cursor: opts.cursor
48
+ });
16
49
  if (jsonRequested(opts)) return json(result);
17
- if (result.jobs.length === 0) return console.log(" (empty)");
18
- table(result.jobs, [
50
+ if (result.items.length === 0) return console.log(" (empty)");
51
+ table(result.items.map((job) => ({
52
+ ...job,
53
+ spaceName: job.space?.name ?? "-",
54
+ lastRunStatus: job.lastRun?.status ?? "-",
55
+ nextRun: job.nextRunAt ?? "-"
56
+ })), [
19
57
  {
20
58
  key: "id",
21
59
  label: "ID"
@@ -25,8 +63,8 @@ function registerCronJobs(program) {
25
63
  label: "Title"
26
64
  },
27
65
  {
28
- key: "taskType",
29
- label: "Type"
66
+ key: "spaceName",
67
+ label: "Space"
30
68
  },
31
69
  {
32
70
  key: "cronExpression",
@@ -37,10 +75,19 @@ function registerCronJobs(program) {
37
75
  label: "Enabled"
38
76
  },
39
77
  {
40
- key: "spaceId",
41
- label: "Space"
78
+ key: "nextRun",
79
+ label: "Next run"
80
+ },
81
+ {
82
+ key: "lastRunStatus",
83
+ label: "Last run"
84
+ },
85
+ {
86
+ key: "access",
87
+ label: "Access"
42
88
  }
43
89
  ]);
90
+ if (result.pageInfo.nextCursor) console.log(`\n More: --cursor ${result.pageInfo.nextCursor}`);
44
91
  } catch (e) {
45
92
  handleHttp(e);
46
93
  }
@@ -41,7 +41,9 @@ const PERMISSIONS = [
41
41
  "user.space.list",
42
42
  "user.session.list",
43
43
  "user.taskrun.list",
44
- "user.usage.read"
44
+ "user.usage.read",
45
+ "user.app.list",
46
+ "user.cronjob.list"
45
47
  ];
46
48
  //#endregion
47
49
  //#region ../sdk/src/environment.ts