@neta-art/cohub-cli 10.26.0 → 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,10 +1,150 @@
1
1
  import { _ as union, a as array, c as discriminatedUnion, d as literal, f as number$1, h as string, l as json, m as record, n as _enum, p as object, s as boolean, v as unknown } from "./schemas.js";
2
- import { A as invertMatrix, B as taskArtifactPreviewUrl, C as clampBoardFontSize, D as estimateTextWidth, E as drawSampleRadius, F as pointsRect$1, G as BOARD_COLOR_TOKENS$1, I as scaleVector, J as BOARD_EXTENSION_TYPE_PATTERN$1, L as setBoardTextLayouter, M as layoutBoardText, O as fitBoardMediaSize, P as multiplyMatrix, Q as BOARD_SHAPE_GEOMETRIES$1, R as sideAnchor, S as bendControl, St as clampBoardStrokeSize, T as drawPointsBounds, V as BOARD_CLIPBOARD_KIND, W as BOARD_CAMERA_TARGET$1, Z as BOARD_SHADOW_DEFAULTS, _ as IDENTITY_MATRIX, _t as BOARD_MONO_FONT_STACK, b as arrowBindings, ct as hasAuthoredSize, d as diffMergePatch, dt as parseBoardMediaSource$1, f as listBoardProperties, gt as BOARD_FONT_STACK, h as pruneBoardTrack, ht as BOARD_DEFAULT_SIZES$1, j as isArrowBinding, k as framePoint, lt as isBuiltinItemType, m as parseBoardDocument, mt as BOARD_ARROW_STROKE_SIZE, n as createBoardItemId, p as mergePatch, r as sameJson, s as modelFormatForPath, st as boardItemPreview, u as applyBoardPatchToDocument, ut as parseBoardItem$1, v as adoptBoardNaturalSize, w as createBoardLayout, x as autoAnchorSide, xt as boardDefaultSize, y as applyMatrix$1, z as featuredTaskArtifact } from "./id.js";
3
- import { $ as rectCenter, A as compileBoardAnimations, B as clampZoom, C as resolveBoardAnimationCamera, D as sceneItemToItem, E as refreshBoardScene, G as frameEdgeHandleAt, H as effectBounds, J as itemBounds, K as frameHandlePosition, L as CORNER_RESIZE_HANDLES, M as withBoardScripts, O as BOARD_SCRIPT_HISTORY_MS, Q as pointToWorld, R as cameraForRect, S as createBoardAnimationSampler, T as placeItem, U as frameContainsPoint, V as degToRad, W as frameCornerRotationHandleAt, X as normalizeViewport, Y as normalizeRotation, Z as panBy, _ as boardSplitTarget, a as boardNavigableFrames, at as rotationHandlePosition, b as findBoardKeyTrack, ct as selectionBounds, dt as visibleWorldRect, et as rectContainsPoint, f as boardInsertTime, ft as worldPoint, g as boardShiftTargets, h as boardRemoveTime, it as rotatePointAround, j as evaluateBoardAnimations, lt as stateForCamera, m as boardRemoveTarget, nt as resizeFrame, o as boardReadingOrder, ot as scaleFrames, p as boardPlaceTarget, pt as zoomAround, q as frameRect, r as boardFrameRegion, rt as rotateFrames, s as boardRegionStep, st as screenPoint, t as BOARD_THEME_DATA, tt as rectsIntersect, u as boardSequence, ut as unionRects, v as boardTargetSpan, w as buildBoardScene, x as newBoardTrackId, y as boardTrimTarget, z as cameraForState } from "./themes.js";
2
+ import { A as invertMatrix, B as taskArtifactPreviewUrl, C as clampBoardFontSize, Ct as clampBoardStrokeSize, D as estimateTextWidth, E as drawSampleRadius, F as pointsRect$1, G as BOARD_COLOR_TOKENS$1, I as scaleVector, J as BOARD_EXTENSION_TYPE_PATTERN$1, L as setBoardTextLayouter, M as layoutBoardText, O as fitBoardMediaSize, P as multiplyMatrix, Q as BOARD_SHAPE_GEOMETRIES$1, R as sideAnchor, S as bendControl, St as boardDefaultSize, T as drawPointsBounds, V as BOARD_CLIPBOARD_KIND, W as BOARD_CAMERA_TARGET$1, Z as BOARD_SHADOW_DEFAULTS, _ as IDENTITY_MATRIX, _t as BOARD_FONT_STACK, b as arrowBindings, ct as hasAuthoredSize, d as diffMergePatch, dt as parseBoardMediaSource$1, f as listBoardProperties, gt as BOARD_DEFAULT_SIZES$1, h as pruneBoardTrack, j as isArrowBinding, k as framePoint, lt as isBuiltinItemType, m as parseBoardDocument, mt as BOARD_ARROW_STROKE_SIZE, n as createBoardItemId, p as mergePatch, r as sameJson, s as modelFormatForPath, st as boardItemPreview, u as applyBoardPatchToDocument, ut as parseBoardItem$1, v as adoptBoardNaturalSize, vt as BOARD_MONO_FONT_STACK, w as createBoardLayout, x as autoAnchorSide, y as applyMatrix$1, z as featuredTaskArtifact } from "./id.js";
3
+ import { $ as panBy, B as boardZoomFloor, C as createBoardAnimationSampler, D as refreshBoardScene, E as placeItem, G as frameContainsPoint, H as cameraForState, J as frameHandlePosition, K as frameCornerRotationHandleAt, M as evaluateBoardAnimations, N as withBoardScripts, O as sceneItemToItem, Q as normalizeViewport, S as boardCameraScale, T as buildBoardScene, U as degToRad, V as cameraForRect, W as effectBounds, X as itemBounds, Y as frameRect, Z as normalizeRotation, _ as boardSplitTarget, a as boardNavigableFrames, at as rotateFrames, b as findBoardKeyTrack, ct as scaleFrames, dt as stateForCamera, et as pointToWorld, f as boardInsertTime, ft as unionRects, g as boardShiftTargets, h as boardRemoveTime, ht as zoomAround, it as resizeFrame, j as compileBoardAnimations, k as BOARD_SCRIPT_HISTORY_MS, lt as screenPoint, m as boardRemoveTarget, mt as worldPoint, nt as rectContainsPoint, o as boardReadingOrder, ot as rotatePointAround, p as boardPlaceTarget, pt as visibleWorldRect, q as frameEdgeHandleAt, r as boardFrameRegion, rt as rectsIntersect, s as boardRegionStep, st as rotationHandlePosition, t as BOARD_THEME_DATA, tt as rectCenter, u as boardSequence, ut as selectionBounds, v as boardTargetSpan, w as resolveBoardAnimationCamera, x as newBoardTrackId, y as boardTrimTarget, z as CORNER_RESIZE_HANDLES } from "./themes.js";
4
4
  import { i as mediaVariantSize } from "./media.js";
5
5
  import { $ as GlobalResourceRegistry, B as definedProps, C as ImageSource, D as DOMAdapter, E as updateQuadBounds, F as Texture, G as multiplyColors, H as InstructionSet, I as TextureMatrix, J as Bounds, K as multiplyHexColors, L as groupD8, M as assignWithIgnore, N as RenderGroup, O as ViewContainer, P as TexturePool, Q as BigPool, R as TextureSource, S as Cache, T as Sprite, U as getLocalBounds, V as nextPow2, W as bgr2rgb, X as FilterEffect, Y as Rectangle, _ as getPo2TextureFromSource, a as Filter, at as ObservablePoint, b as canvasUtils, c as UniformGroup, ct as Color, d as GpuProgram, dt as extensions, et as warn, f as getAttributeInfoFromFormat, g as CanvasFilterSystem, h as FilterPipe, i as vertex$2, it as uid$1, j as Container, k as Ticker, l as RendererType, lt as eventemitter3_default, m as getTestContext, n as Buffer, nt as v8_0_0, o as State, ot as Matrix, p as GlProgram, q as getGlobalBounds, r as BufferUsage, rt as v8_3_4, s as Shader, st as Point, t as Geometry, tt as deprecation, u as BindGroup, ut as ExtensionType, w as CanvasSource, x as canUseNewCanvasBlendModes, y as CanvasPool, z as TextureStyle } from "./Geometry.js";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { Worker } from "node:worker_threads";
8
+ //#region ../protocol/src/realtime/board-awareness.ts
9
+ const idSchema = string().min(1).max(160);
10
+ const finiteSchema = number$1().finite();
11
+ const BOARD_AWARENESS_WORLD_COORDINATE_LIMIT = 1e9;
12
+ const BOARD_AWARENESS_WORLD_EXTENT_LIMIT = 1e8;
13
+ const BOARD_AWARENESS_MIN_VIEWPORT_ZOOM = .05;
14
+ const worldCoordinateSchema = finiteSchema.min(-1e9).max(BOARD_AWARENESS_WORLD_COORDINATE_LIMIT);
15
+ const worldExtentSchema = finiteSchema.positive().max(BOARD_AWARENESS_WORLD_EXTENT_LIMIT);
16
+ const viewportZoomSchema = finiteSchema.min(BOARD_AWARENESS_MIN_VIEWPORT_ZOOM).max(8);
17
+ const BoardAwarenessPointSchema = object({
18
+ x: worldCoordinateSchema,
19
+ y: worldCoordinateSchema
20
+ });
21
+ const BoardAwarenessDrawPointSchema = BoardAwarenessPointSchema.extend({ p: finiteSchema.min(0).max(1) });
22
+ const BoardAwarenessFrameSchema = object({
23
+ x: worldCoordinateSchema,
24
+ y: worldCoordinateSchema,
25
+ width: worldExtentSchema,
26
+ height: worldExtentSchema,
27
+ rotation: finiteSchema
28
+ });
29
+ const BoardAwarenessViewportSchema = object({
30
+ x: worldCoordinateSchema,
31
+ y: worldCoordinateSchema,
32
+ width: worldExtentSchema,
33
+ height: worldExtentSchema,
34
+ zoom: viewportZoomSchema
35
+ });
36
+ const BoardAwarenessItemPreviewSchema = object({
37
+ itemId: idSchema,
38
+ frame: BoardAwarenessFrameSchema
39
+ });
40
+ const BoardAwarenessStateUpdateSchema = object({
41
+ type: literal("state"),
42
+ client: object({
43
+ formFactor: _enum(["desktop", "mobile"]),
44
+ scripts: boolean().optional()
45
+ }).optional(),
46
+ cursor: BoardAwarenessPointSchema.extend({
47
+ pointerType: _enum([
48
+ "mouse",
49
+ "pen",
50
+ "touch"
51
+ ]),
52
+ pressed: boolean().optional()
53
+ }).nullable(),
54
+ viewport: BoardAwarenessViewportSchema.nullable().optional(),
55
+ tool: string().min(1).max(40),
56
+ selection: object({
57
+ ids: array(idSchema).max(64),
58
+ count: number$1().int().nonnegative().max(5e4),
59
+ bounds: BoardAwarenessFrameSchema.nullable()
60
+ }),
61
+ editingId: idSchema.nullable()
62
+ });
63
+ const BoardAwarenessGestureSchema = discriminatedUnion("kind", [
64
+ object({
65
+ kind: literal("draw"),
66
+ id: idSchema,
67
+ itemId: idSchema,
68
+ color: string().min(1).max(64),
69
+ size: finiteSchema.positive().max(256),
70
+ from: number$1().int().nonnegative().max(1e5),
71
+ points: array(BoardAwarenessDrawPointSchema).min(1).max(64)
72
+ }),
73
+ object({
74
+ kind: literal("arrow"),
75
+ id: idSchema,
76
+ itemId: idSchema,
77
+ start: BoardAwarenessPointSchema,
78
+ current: BoardAwarenessPointSchema,
79
+ startItemId: idSchema.nullable().default(null),
80
+ endItemId: idSchema.nullable().default(null),
81
+ color: string().min(1).max(64),
82
+ size: finiteSchema.positive().max(256).default(BOARD_ARROW_STROKE_SIZE)
83
+ }),
84
+ object({
85
+ kind: literal("box"),
86
+ id: idSchema,
87
+ itemId: idSchema,
88
+ shape: _enum(["shape", "frame"]),
89
+ start: BoardAwarenessPointSchema,
90
+ current: BoardAwarenessPointSchema,
91
+ color: string().min(1).max(64),
92
+ geometry: string().min(1).max(40).default("rectangle")
93
+ }),
94
+ object({
95
+ kind: literal("transform"),
96
+ id: idSchema,
97
+ mode: _enum([
98
+ "translate",
99
+ "resize",
100
+ "rotate",
101
+ "arrow"
102
+ ]),
103
+ items: array(BoardAwarenessItemPreviewSchema).max(64),
104
+ bounds: BoardAwarenessFrameSchema.nullable()
105
+ })
106
+ ]);
107
+ const BOARD_REACTIONS = [
108
+ "heart",
109
+ "star",
110
+ "spark",
111
+ "confetti"
112
+ ];
113
+ const BOARD_SCRIPT_BROADCAST_JSON_LENGTH = 1024;
114
+ const BoardAwarenessUpdateSchema = discriminatedUnion("type", [
115
+ BoardAwarenessStateUpdateSchema,
116
+ object({
117
+ type: literal("gesture"),
118
+ gesture: BoardAwarenessGestureSchema
119
+ }),
120
+ object({
121
+ type: literal("gesture.end"),
122
+ gestureId: idSchema,
123
+ resultingItemIds: array(idSchema).max(64)
124
+ }),
125
+ object({
126
+ type: literal("gesture.cancel"),
127
+ gestureId: idSchema
128
+ }),
129
+ object({
130
+ type: literal("reaction"),
131
+ reaction: _enum(BOARD_REACTIONS),
132
+ at: BoardAwarenessPointSchema
133
+ }),
134
+ object({
135
+ type: literal("script"),
136
+ owner: idSchema,
137
+ event: string().min(1).max(64),
138
+ data: json().refine((data) => JSON.stringify(data).length <= BOARD_SCRIPT_BROADCAST_JSON_LENGTH, `Broadcast data exceeds ${BOARD_SCRIPT_BROADCAST_JSON_LENGTH} characters of JSON.`)
139
+ })
140
+ ]);
141
+ object({
142
+ spaceId: string().uuid(),
143
+ boardId: string().uuid(),
144
+ seq: number$1().int().nonnegative(),
145
+ update: BoardAwarenessUpdateSchema
146
+ });
147
+ //#endregion
8
148
  //#region ../sdk/src/board/model/script.ts
9
149
  const BOARD_SCRIPT_SENSES = [
10
150
  "motion",
@@ -192,7 +332,7 @@ function boardScriptInputsBetween(log, after, until) {
192
332
  }
193
333
  function supersedes(pending, event) {
194
334
  if (pending.type !== event.type) return false;
195
- if (event.type === "viewchange" || event.type === "selectionchange" || isBoardScriptLatestInput(event.type)) return true;
335
+ if (event.type === "viewchange" || event.type === "selectionchange" || event.type === "peerschange" || isBoardScriptLatestInput(event.type)) return true;
196
336
  if (event.type === "pointermove") return pending.pointerId === event.pointerId;
197
337
  if (event.type !== "gesture") return false;
198
338
  const a = pending.data;
@@ -225,10 +365,32 @@ function boardScriptEmit(document, sender, input) {
225
365
  event: {
226
366
  type,
227
367
  data: message.data,
228
- depth
368
+ depth,
369
+ ...message.remote === true ? { remote: true } : {}
229
370
  }
230
371
  };
231
372
  }
373
+ const RESERVED = /^(pointer|key|browser:)|^(click|focus|blur|change|selectionchange|transformend|viewchange|envchange|gesture|peerschange)$/;
374
+ function boardScriptBroadcast(input) {
375
+ const message = input;
376
+ const type = message?.type;
377
+ if (typeof type !== "string" || !type || type.length > 64) throw new Error("broadcast() takes an event type of 1–64 characters.");
378
+ if (RESERVED.test(type)) throw new Error(`broadcast("${type}"): input and host event types are reserved.`);
379
+ let json;
380
+ try {
381
+ json = JSON.stringify(message?.data ?? null);
382
+ } catch {}
383
+ if (json === void 0) throw new Error(`broadcast("${type}") data must be JSON.`);
384
+ if (json.length > 1024) throw new Error(`broadcast("${type}") data exceeds ${BOARD_SCRIPT_BROADCAST_JSON_LENGTH} characters of JSON.`);
385
+ const depth = typeof message?.depth === "number" && Number.isSafeInteger(message.depth) && message.depth > 0 ? message.depth : 1;
386
+ if (depth > 16) throw new Error(`broadcast("${type}") is ${depth} handlers deep, past the limit of 16: handlers keep answering each other. Broadcast from onFrame() to send it on the next step.`);
387
+ return {
388
+ type,
389
+ data: JSON.parse(json),
390
+ depth,
391
+ peer: null
392
+ };
393
+ }
232
394
  function createBoardScriptOutbox(order) {
233
395
  let queued = [];
234
396
  let seq = 0;
@@ -1647,7 +1809,10 @@ function boardTextureBytes(item, scale) {
1647
1809
  const pixels = boardTexturePixels(item, scale);
1648
1810
  const edge = boardTextureEdge(item, scale);
1649
1811
  const grow = Number.isFinite(edge) && pixels > 0 ? edge / pixels : 1;
1650
- return Math.ceil(item.frame.width / (crop?.w || 1) * scale * grow) * Math.ceil(item.frame.height / (crop?.h || 1) * scale * grow) * 4;
1812
+ const width = Math.ceil(item.frame.width / (crop?.w || 1) * scale * grow);
1813
+ const height = Math.ceil(item.frame.height / (crop?.h || 1) * scale * grow);
1814
+ const natural = boardMediaNaturalSize(item);
1815
+ return Math.min(width * height, natural ? natural.width * natural.height : Number.POSITIVE_INFINITY) * 4;
1651
1816
  }
1652
1817
  function selectBoardExportAssets(items, assetKey, options) {
1653
1818
  const budget = options.maxBytes ?? BOARD_EXPORT_TEXTURE_BYTES;
@@ -29029,7 +29194,7 @@ function syncBoardEffects(container, style, context) {
29029
29194
  const MAX_FLAT_PIXELS = 16e6;
29030
29195
  const MAX_FLAT_EDGE = 8192;
29031
29196
  /** Canvas filters apply per draw call, so exports draw blurred and shadowed layers into one picture first. */
29032
- function flattenBoardEffects(renderer, root, resolution) {
29197
+ function flattenBoardEffects(renderer, root, resolution, view) {
29033
29198
  const textures = [];
29034
29199
  const visit = (node) => {
29035
29200
  for (const child of [...node.children]) visit(child);
@@ -29050,7 +29215,12 @@ function flattenBoardEffects(renderer, root, resolution) {
29050
29215
  target.updateLocalTransform();
29051
29216
  const cast = parts.shadow && localCast(parts.shadow.cast, target.localTransform);
29052
29217
  const grow = (parts.blur?.radius ?? 0) * 3 + (cast ? cast.blur * 1.5 + Math.max(Math.abs(cast.x), Math.abs(cast.y)) : 0);
29053
- const frame = new Rectangle(bounds.x - grow, bounds.y - grow, bounds.width + grow * 2, bounds.height + grow * 2);
29218
+ const frame = visiblePart(target, new Rectangle(bounds.x - grow, bounds.y - grow, bounds.width + grow * 2, bounds.height + grow * 2), view, grow);
29219
+ if (!frame) {
29220
+ restore();
29221
+ target.visible = false;
29222
+ return;
29223
+ }
29054
29224
  const scale = Math.min(resolution, Math.sqrt(MAX_FLAT_PIXELS / (frame.width * frame.height)), MAX_FLAT_EDGE / Math.max(frame.width, frame.height));
29055
29225
  const picture = renderer.generateTexture({
29056
29226
  target,
@@ -29059,8 +29229,10 @@ function flattenBoardEffects(renderer, root, resolution) {
29059
29229
  antialias: true
29060
29230
  });
29061
29231
  restore();
29062
- const flat = paintEffects(renderer.texture.generateCanvas(picture), parts.blur?.radius ?? 0, cast, scale);
29063
- picture.destroy(true);
29232
+ const pixels = renderer.texture.generateCanvas(picture);
29233
+ releaseTexture(picture);
29234
+ const flat = paintEffects(pixels, parts.blur?.radius ?? 0, cast, scale);
29235
+ releaseCanvas(pixels);
29064
29236
  textures.push(flat);
29065
29237
  const layer = new Container({ label: "board-flat-effects" });
29066
29238
  layer.setFromMatrix(target.localTransform);
@@ -29075,9 +29247,44 @@ function flattenBoardEffects(renderer, root, resolution) {
29075
29247
  };
29076
29248
  visit(root);
29077
29249
  return () => {
29078
- for (const texture of textures) texture.destroy(true);
29250
+ for (const texture of textures) releaseTexture(texture);
29079
29251
  };
29080
29252
  }
29253
+ function visiblePart(target, frame, view, grow) {
29254
+ const toLocal = target.getGlobalTransform(new Matrix(), false).invert();
29255
+ const corners = [
29256
+ toLocal.apply({
29257
+ x: view.x,
29258
+ y: view.y
29259
+ }),
29260
+ toLocal.apply({
29261
+ x: view.right,
29262
+ y: view.y
29263
+ }),
29264
+ toLocal.apply({
29265
+ x: view.x,
29266
+ y: view.bottom
29267
+ }),
29268
+ toLocal.apply({
29269
+ x: view.right,
29270
+ y: view.bottom
29271
+ })
29272
+ ];
29273
+ const left = Math.max(frame.x, Math.min(...corners.map((point) => point.x)) - grow);
29274
+ const top = Math.max(frame.y, Math.min(...corners.map((point) => point.y)) - grow);
29275
+ const right = Math.min(frame.right, Math.max(...corners.map((point) => point.x)) + grow);
29276
+ const bottom = Math.min(frame.bottom, Math.max(...corners.map((point) => point.y)) + grow);
29277
+ return right > left && bottom > top ? new Rectangle(left, top, right - left, bottom - top) : null;
29278
+ }
29279
+ function releaseCanvas(canvas) {
29280
+ canvas.width = 1;
29281
+ canvas.height = 1;
29282
+ }
29283
+ function releaseTexture(texture) {
29284
+ const canvas = texture.source.resource;
29285
+ texture.destroy(true);
29286
+ if (canvas?.getContext) releaseCanvas(canvas);
29287
+ }
29081
29288
  function localCast(cast, transform) {
29082
29289
  const { a, b, c, d } = transform;
29083
29290
  const det = a * d - b * c || 1;
@@ -29113,10 +29320,12 @@ function paintEffects(picture, blur, cast, resolution) {
29113
29320
  out.context.filter = `blur(${cast.blur / 2 * resolution}px)`;
29114
29321
  out.context.globalAlpha = cast.alpha;
29115
29322
  out.context.drawImage(silhouette.canvas, cast.x * resolution, cast.y * resolution);
29323
+ releaseCanvas(silhouette.canvas);
29116
29324
  out.context.filter = "none";
29117
29325
  out.context.globalAlpha = 1;
29118
29326
  }
29119
29327
  out.context.drawImage(content, 0, 0);
29328
+ if (content !== picture) releaseCanvas(content);
29120
29329
  return new Texture({ source: new ImageSource({
29121
29330
  resource: out.canvas,
29122
29331
  resolution
@@ -32893,6 +33102,12 @@ function createBoardCardRendererResolver(renderers = []) {
32893
33102
  }
32894
33103
  /** The built-in renderers alone. */
32895
33104
  const getBoardCardRenderer = createBoardCardRendererResolver();
33105
+ //#endregion
33106
+ //#region ../protocol/dist/board-constants.js
33107
+ const BOARD_CAMERA_VIEWPORT = {
33108
+ width: 1600,
33109
+ height: 900
33110
+ };
32896
33111
  const BOARD_DEFAULT_ITEM_SIZE = {
32897
33112
  width: 240,
32898
33113
  height: 160
@@ -33513,7 +33728,11 @@ object({
33513
33728
  delay: nonNegative.default(0),
33514
33729
  loop: boolean().default(false),
33515
33730
  end: _enum(["hold", "reset"]).default("hold").describe("hold keeps the last frame; reset returns to the start."),
33516
- markers: array(BoardMarkerSchema).max(1e4).default([]).describe("Labeled points on this timeline; a nested animation's markers do not carry over.")
33731
+ markers: array(BoardMarkerSchema).max(1e4).default([]).describe("Labeled points on this timeline; a nested animation's markers do not carry over."),
33732
+ viewport: object({
33733
+ width: number$1().int().positive().max(8192),
33734
+ height: number$1().int().positive().max(8192)
33735
+ }).strict().optional().describe(`Screen pixels the camera tracks are framed for, ${BOARD_CAMERA_VIEWPORT.width}x${BOARD_CAMERA_VIEWPORT.height} by default. Every screen and export shows that framing, scaled to fit.`)
33517
33736
  }).strict().extend({ tracks: record(BoardKeySchema, BoardTrackSchema).default({}) }).strict();
33518
33737
  const BOARD_ENTER_PRESETS = [
33519
33738
  "fade-in",
@@ -33717,6 +33936,7 @@ function createScriptRuntime(module, initial, host) {
33717
33936
  let disposed = false;
33718
33937
  let stepping = false;
33719
33938
  let depth = 0;
33939
+ let remote = false;
33720
33940
  let revision = 0;
33721
33941
  let sceneRevision = 0;
33722
33942
  let randomState = 2166136261;
@@ -33751,6 +33971,7 @@ function createScriptRuntime(module, initial, host) {
33751
33971
  };
33752
33972
  let anchor = effects?.anchor;
33753
33973
  let view = null;
33974
+ let peers = [];
33754
33975
  let hits = effects?.hits ?? {};
33755
33976
  let uniforms = effects?.uniforms;
33756
33977
  let videoFrame;
@@ -33794,9 +34015,21 @@ function createScriptRuntime(module, initial, host) {
33794
34015
  target,
33795
34016
  type,
33796
34017
  data,
34018
+ depth: depth + 1,
34019
+ ...remote ? { remote } : {}
34020
+ });
34021
+ },
34022
+ async broadcast(type, data) {
34023
+ if (remote) throw new Error("broadcast() cannot answer another viewer's broadcast.");
34024
+ await host.call("board.broadcast", {
34025
+ type,
34026
+ data: data ?? null,
33797
34027
  depth: depth + 1
33798
34028
  });
33799
34029
  },
34030
+ get peers() {
34031
+ return peers;
34032
+ },
33800
34033
  get items() {
33801
34034
  return input.items;
33802
34035
  },
@@ -33881,6 +34114,7 @@ function createScriptRuntime(module, initial, host) {
33881
34114
  },
33882
34115
  async commit(patch) {
33883
34116
  if (input.capabilities && !input.capabilities.includes("board.commit")) throw new Error("This viewer cannot edit the Board.");
34117
+ if (remote) throw new Error("A handler of another viewer's broadcast cannot commit; the viewer who sent it saves.");
33884
34118
  return await host.call("board.commit", {
33885
34119
  patch,
33886
34120
  frame: stepping
@@ -33971,20 +34205,25 @@ function createScriptRuntime(module, initial, host) {
33971
34205
  event(event) {
33972
34206
  if (disposed) return;
33973
34207
  if (event.type === "viewchange") view = event.data;
34208
+ if (event.type === "peerschange") peers = event.data;
33974
34209
  if (event.type === "browser:video") {
33975
34210
  videoFrame?.close?.();
33976
34211
  videoFrame = event.data.frame;
33977
34212
  }
33978
34213
  const listeners = handlers.get(event.type);
33979
34214
  if (!listeners?.size) return;
33980
- const outer = depth;
34215
+ const outer = {
34216
+ depth,
34217
+ remote
34218
+ };
33981
34219
  depth = event.depth ?? 0;
34220
+ remote = event.remote === true;
33982
34221
  try {
33983
34222
  seeded(() => {
33984
34223
  for (const handler of listeners) handler(event);
33985
34224
  });
33986
34225
  } finally {
33987
- depth = outer;
34226
+ ({depth, remote} = outer);
33988
34227
  }
33989
34228
  invalidate();
33990
34229
  },
@@ -34070,6 +34309,7 @@ function layoutBoardScriptText(value) {
34070
34309
  }
34071
34310
  const BOARD_SCRIPT_EXPORT_CALLS = {
34072
34311
  "board.emit": () => void 0,
34312
+ "board.broadcast": () => void 0,
34073
34313
  "board.commit": () => false,
34074
34314
  "board.layoutText": layoutBoardScriptText
34075
34315
  };
@@ -36130,7 +36370,7 @@ function prepareBoardExport(input, options = {}) {
36130
36370
  const sampled = sample?.document ?? base;
36131
36371
  const document = options.scripts?.document?.(sampled, options.at?.time ?? 0) ?? sampled;
36132
36372
  const scene = document === sampled ? sample?.scene ?? buildBoardScene(document) : buildBoardScene(document);
36133
- const camera = options.camera ? resolveBoardAnimationCamera(sample?.evaluation.camera ?? {}, (id) => scene.get(id)?.frame, options.camera, options.at?.time ?? 0) : void 0;
36373
+ const camera = options.camera ? resolveBoardAnimationCamera(sample?.evaluation.camera ?? {}, (id) => scene.get(id)?.frame, options.camera, options.at?.time ?? 0, void 0, sample?.evaluation.cameraViewport) : void 0;
36134
36374
  const plan = planBoardExport({
36135
36375
  scene,
36136
36376
  region: camera && options.camera ? {
@@ -36200,7 +36440,7 @@ function renderBoardExport(renderer, input, options = {}) {
36200
36440
  layers: options.shaderLayers
36201
36441
  } } : {}
36202
36442
  });
36203
- const flattened = renderer.type === RendererType.CANVAS ? flattenBoardEffects(renderer, exportScene.root, plan.scale) : null;
36443
+ const flattened = renderer.type === RendererType.CANVAS ? flattenBoardEffects(renderer, exportScene.root, plan.scale, new Rectangle(0, 0, plan.width, plan.height)) : null;
36204
36444
  try {
36205
36445
  const texture = renderer.textureGenerator.generateTexture({
36206
36446
  target: exportScene.root,
@@ -36717,9 +36957,12 @@ function createNodeBoardScriptHost(renderer, options) {
36717
36957
  const lanes = createNodeScriptLanes(renderer, {
36718
36958
  ...options,
36719
36959
  async call(id, name, input) {
36720
- if (name === "board.emit" && current) {
36960
+ if ((name === "board.emit" || name === "board.broadcast") && current) {
36721
36961
  try {
36722
- const { target, event } = boardScriptEmit(current, id, input);
36962
+ const { target, event } = name === "board.emit" ? boardScriptEmit(current, id, input) : {
36963
+ target: id,
36964
+ event: boardScriptBroadcast(input)
36965
+ };
36723
36966
  outbox.push(id, target, event);
36724
36967
  } catch (error) {
36725
36968
  emitFailures.set(id, error instanceof Error ? error.message : String(error));
@@ -38120,9 +38363,12 @@ function createAnimationModule(ctx) {
38120
38363
  /** The value a replacing keyframe needs to keep the shown state: the property evaluated without the additive tracks on it. */
38121
38364
  function keyValue(found, target, property) {
38122
38365
  if (target === "camera") {
38123
- if (property === "zoom") return state.camera.zoom;
38124
- if (property === "center") return ctx.camera.viewCenter();
38125
- return;
38366
+ const shown = ctx.camera.shown();
38367
+ const { width, height } = state.surfaceSize;
38368
+ if (property === "center") return pointToWorld(screenPoint(width / 2, height / 2), shown);
38369
+ if (property !== "zoom") return void 0;
38370
+ const scale = boardCameraScale(state.surfaceSize, found.animation.viewport);
38371
+ return scale > 0 ? shown.zoom / scale : shown.zoom;
38126
38372
  }
38127
38373
  const overlaps = (other) => other === property || other.startsWith(`${property}.`) || property.startsWith(`${other}.`);
38128
38374
  const animations = { ...state.base.animations };
@@ -38365,6 +38611,7 @@ function createAnimationModule(ctx) {
38365
38611
  if (settings.duration !== void 0) next.duration = Math.max(1, Math.round(settings.duration));
38366
38612
  if (settings.delay !== void 0) next.delay = ms(settings.delay);
38367
38613
  if (!next.name) delete next.name;
38614
+ if (!next.viewport) delete next.viewport;
38368
38615
  return sameJson(next, animation) || commitAnimation(id, next);
38369
38616
  }
38370
38617
  function deleteAnimation(id) {
@@ -38536,6 +38783,17 @@ function createCameraModule(ctx) {
38536
38783
  const { state } = ctx;
38537
38784
  let motion = null;
38538
38785
  let frame = 0;
38786
+ let followed = null;
38787
+ let floor = null;
38788
+ function zoomFloor(zoom = state.camera.zoom) {
38789
+ const { scene, surfaceSize } = state;
38790
+ if (floor?.scene !== scene || floor.width !== surfaceSize.width || floor.height !== surfaceSize.height) floor = {
38791
+ scene,
38792
+ ...surfaceSize,
38793
+ zoom: boardZoomFloor(ctx.query.contentBounds(), surfaceSize)
38794
+ };
38795
+ return Math.min(floor.zoom, zoom);
38796
+ }
38539
38797
  function move(viewport) {
38540
38798
  state.camera = normalizeViewport(viewport, state.camera);
38541
38799
  state.hoverPoint = null;
@@ -38547,12 +38805,18 @@ function createCameraModule(ctx) {
38547
38805
  move(viewport);
38548
38806
  }
38549
38807
  function setCameraPolicy(policy) {
38550
- if (state.cameraPolicy === policy) return;
38551
38808
  state.cameraPolicy = policy;
38552
- ctx.preferencesChanged();
38809
+ }
38810
+ function follow(viewport) {
38811
+ followed = viewport;
38553
38812
  }
38554
38813
  function takeCameraControl() {
38814
+ if (state.cameraPolicy !== "follow" || !followed) return false;
38815
+ stop();
38816
+ move(followed);
38817
+ followed = null;
38555
38818
  setCameraPolicy("free");
38819
+ return true;
38556
38820
  }
38557
38821
  function step(now) {
38558
38822
  frame = 0;
@@ -38639,7 +38903,8 @@ function createCameraModule(ctx) {
38639
38903
  }
38640
38904
  function zoomAt(point, factor, animate = false) {
38641
38905
  if (!ctx.frames.release()) return;
38642
- const target = zoomAround(state.camera, point, state.camera.zoom * factor);
38906
+ takeCameraControl();
38907
+ const target = zoomAround(state.camera, point, state.camera.zoom * factor, zoomFloor());
38643
38908
  if (animate) animateCamera(target);
38644
38909
  else {
38645
38910
  stop();
@@ -38648,15 +38913,17 @@ function createCameraModule(ctx) {
38648
38913
  }
38649
38914
  function scroll(dx, dy, smooth = false) {
38650
38915
  if (!ctx.frames.release()) return;
38916
+ takeCameraControl();
38651
38917
  if (smooth) return glide((base) => panBy(base, -dx, -dy), motion?.kind === "glide" ? motion.anchor : surfaceCenter());
38652
38918
  stop();
38653
38919
  move(panBy(state.camera, -dx, -dy));
38654
38920
  }
38655
38921
  function zoomBy(point, factor, smooth = false) {
38656
38922
  if (!ctx.frames.release()) return;
38657
- if (smooth) return glide((base) => zoomAround(base, point, base.zoom * factor), point);
38923
+ takeCameraControl();
38924
+ if (smooth) return glide((base) => zoomAround(base, point, base.zoom * factor, zoomFloor(base.zoom)), point);
38658
38925
  stop();
38659
- move(zoomAround(state.camera, point, state.camera.zoom * factor));
38926
+ move(zoomAround(state.camera, point, state.camera.zoom * factor, zoomFloor()));
38660
38927
  }
38661
38928
  function fling(vx, vy) {
38662
38929
  if (Math.hypot(vx, vy) < BOARD_INPUT.flingStop) return;
@@ -38669,6 +38936,7 @@ function createCameraModule(ctx) {
38669
38936
  }
38670
38937
  function focusRect(rect, focus = {}) {
38671
38938
  ctx.frames.release({ present: true });
38939
+ takeCameraControl();
38672
38940
  const { surfaceSize } = state;
38673
38941
  if (surfaceSize.width <= 0 || surfaceSize.height <= 0) return;
38674
38942
  const target = cameraForRect(rect, surfaceSize, {
@@ -38738,16 +39006,23 @@ function createCameraModule(ctx) {
38738
39006
  setCamera,
38739
39007
  show,
38740
39008
  setCameraPolicy,
39009
+ follow,
38741
39010
  takeCameraControl,
39011
+ shown: () => followed ?? state.camera,
39012
+ following: () => followed !== null && state.cameraPolicy === "follow",
38742
39013
  stop,
38743
39014
  viewCenter,
38744
39015
  visibleRect,
38745
39016
  cameraState,
38746
39017
  restoreCameraState,
38747
39018
  zoomAt,
39019
+ zoomFloor,
38748
39020
  zoomIn: () => zoomAt(surfaceCenter(), ZOOM_STEP, true),
38749
39021
  zoomOut: () => zoomAt(surfaceCenter(), 1 / ZOOM_STEP, true),
38750
- resetZoom: () => zoomAt(surfaceCenter(), 1 / state.camera.zoom, true),
39022
+ resetZoom: () => {
39023
+ takeCameraControl();
39024
+ zoomAt(surfaceCenter(), 1 / state.camera.zoom, true);
39025
+ },
38751
39026
  focusRect,
38752
39027
  fitView,
38753
39028
  focusItems,
@@ -39090,7 +39365,10 @@ function createDocumentModule(ctx) {
39090
39365
  played = new Map([...items].filter(([id]) => state.base.items[id]));
39091
39366
  const changed = /* @__PURE__ */ new Set([...previous.keys(), ...played.keys()]);
39092
39367
  for (const id of changed) if (draft.has(id) || evaluated.has(id) || sameJson(previous.get(id), played.get(id))) changed.delete(id);
39093
- if (changed.size) rescene(changed);
39368
+ if (changed.size) move(changed);
39369
+ }
39370
+ function move(ids) {
39371
+ ctx.channels.reroute("scene", "motion", () => rescene(ids));
39094
39372
  }
39095
39373
  function setScriptItems(items) {
39096
39374
  const previous = scripted;
@@ -39098,13 +39376,14 @@ function createDocumentModule(ctx) {
39098
39376
  const changed = [.../* @__PURE__ */ new Set([...previous.keys(), ...items.keys()])].filter((id) => !sameJson(previous.get(id), items.get(id)));
39099
39377
  if (!changed.length) return changed;
39100
39378
  const restacked = /* @__PURE__ */ new Set();
39101
- rescene(changed.some((id) => {
39379
+ if (changed.some((id) => {
39102
39380
  const before = previous.get(id) ?? state.base.items[id];
39103
39381
  const after = items.get(id) ?? state.base.items[id];
39104
39382
  if (!before || !after || before.parent !== after.parent || !sameJson(arrowBindings(before), arrowBindings(after))) return true;
39105
39383
  if (before.z !== after.z) restacked.add(after.parent ?? "");
39106
39384
  return false;
39107
- }) || [...restacked].some(reordered) ? void 0 : changed);
39385
+ }) || [...restacked].some(reordered)) rescene();
39386
+ else move(changed);
39108
39387
  return changed;
39109
39388
  }
39110
39389
  function reordered(parent) {
@@ -39414,6 +39693,7 @@ function createFramesModule(ctx) {
39414
39693
  function go(id, options = {}) {
39415
39694
  const next = region(id);
39416
39695
  if (!next) return false;
39696
+ ctx.camera.takeCameraControl();
39417
39697
  const current = view();
39418
39698
  const present = options.present ?? current?.present ?? false;
39419
39699
  if (!current || present && !current.present) returnTo = state.camera;
@@ -39423,7 +39703,6 @@ function createFramesModule(ctx) {
39423
39703
  state.enteredId = null;
39424
39704
  state.hoverId = null;
39425
39705
  }
39426
- ctx.camera.takeCameraControl();
39427
39706
  const camera = target(next.rect, present);
39428
39707
  state.frameView = {
39429
39708
  id,
@@ -39650,11 +39929,24 @@ function computeSnap(moving, targets, options) {
39650
39929
  //#region ../sdk/src/board/editor/state.ts
39651
39930
  function createChannels() {
39652
39931
  const listeners = /* @__PURE__ */ new Map();
39932
+ let route = null;
39653
39933
  return {
39654
39934
  emit(channel) {
39655
- const subscribed = listeners.get(channel);
39935
+ const subscribed = listeners.get(route?.from === channel ? route.to : channel);
39656
39936
  if (subscribed) for (const listener of [...subscribed]) listener();
39657
39937
  },
39938
+ reroute(from, to, run) {
39939
+ const previous = route;
39940
+ route = {
39941
+ from,
39942
+ to
39943
+ };
39944
+ try {
39945
+ return run();
39946
+ } finally {
39947
+ route = previous;
39948
+ }
39949
+ },
39658
39950
  subscribe(channels, listener) {
39659
39951
  const list = typeof channels === "string" ? [channels] : channels;
39660
39952
  for (const channel of list) {
@@ -39889,6 +40181,7 @@ function createInteractionModule(ctx) {
39889
40181
  function beginPinch() {
39890
40182
  const [a, b] = [...activePointers.values()];
39891
40183
  if (!a || !b) return;
40184
+ ctx.camera.takeCameraControl();
39892
40185
  const gesture = state.interaction;
39893
40186
  state.interaction = { type: "idle" };
39894
40187
  state.snapGuides = [];
@@ -40258,7 +40551,7 @@ function createInteractionModule(ctx) {
40258
40551
  if (!a || !b || !pinch) return;
40259
40552
  const distance = Math.max(1, Math.hypot(a.x - b.x, a.y - b.y));
40260
40553
  const midpoint = screenPoint((a.x + b.x) / 2, (a.y + b.y) / 2);
40261
- const zoomed = zoomAround(state.camera, midpoint, clampZoom(pinch.zoom * (distance / pinch.distance)));
40554
+ const zoomed = zoomAround(state.camera, midpoint, pinch.zoom * (distance / pinch.distance), ctx.camera.zoomFloor(pinch.zoom));
40262
40555
  const next = panBy(zoomed, midpoint.x - pinch.midpoint.x, midpoint.y - pinch.midpoint.y);
40263
40556
  if (ctx.frames.view()?.present) ctx.camera.show(next, false);
40264
40557
  else ctx.camera.setCamera(next);
@@ -40464,13 +40757,17 @@ function createInteractionModule(ctx) {
40464
40757
  state.hoverId = isCreationBoardTool(state.tool) || hoveredControl() || ctx.frames.view()?.present ? null : ctx.query.pickAt(event.world, event.pointerType)?.id ?? null;
40465
40758
  return;
40466
40759
  case "panning": {
40467
- const held = holdsFrame(event.pointerType);
40468
- if ((interaction.tapSelection || held) && !interaction.moved && !dragged(event)) return;
40469
- if (!interaction.moved) state.interaction = {
40470
- ...interaction,
40471
- moved: true
40472
- };
40473
- pan(interaction.origin, event.screen.x - interaction.start.x, event.screen.y - interaction.start.y, event.pointerType);
40760
+ if ((interaction.tapSelection || holdsFrame(event.pointerType) || ctx.camera.following()) && !interaction.moved && !dragged(event)) return;
40761
+ let { origin } = interaction;
40762
+ if (!interaction.moved) {
40763
+ if (ctx.camera.takeCameraControl()) origin = { ...state.camera };
40764
+ state.interaction = {
40765
+ ...interaction,
40766
+ origin,
40767
+ moved: true
40768
+ };
40769
+ }
40770
+ pan(origin, event.screen.x - interaction.start.x, event.screen.y - interaction.start.y, event.pointerType);
40474
40771
  sample(event.screen);
40475
40772
  return;
40476
40773
  }
@@ -41566,7 +41863,7 @@ function createBoardEditor(options) {
41566
41863
  },
41567
41864
  controlOutset: 0,
41568
41865
  frameLabelSize: 12,
41569
- cameraPolicy: preferences?.cameraPolicy ?? "follow",
41866
+ cameraPolicy: "follow",
41570
41867
  frameView: null,
41571
41868
  tool: options.initialTool ?? "select",
41572
41869
  toolStyles: preferences?.toolStyles ?? createBoardToolStyles(),
@@ -41593,10 +41890,7 @@ function createBoardEditor(options) {
41593
41890
  channels,
41594
41891
  chosenTool: options.initialTool ?? null,
41595
41892
  preferencesChanged() {
41596
- options.onPreferencesChange?.({
41597
- toolStyles: state.toolStyles,
41598
- cameraPolicy: state.cameraPolicy
41599
- });
41893
+ options.onPreferencesChange?.({ toolStyles: state.toolStyles });
41600
41894
  }
41601
41895
  };
41602
41896
  ctx.document = createDocumentModule(ctx);
@@ -41614,9 +41908,14 @@ function createBoardEditor(options) {
41614
41908
  const { document, query, camera, frames, selection, creation, deletion, copy, interaction, animation, snapshots, remote } = ctx;
41615
41909
  const transformChannels = options.touchRotation === false ? [
41616
41910
  "scene",
41911
+ "motion",
41617
41912
  "selection",
41618
41913
  "hover"
41619
- ] : ["scene", "selection"];
41914
+ ] : [
41915
+ "scene",
41916
+ "motion",
41917
+ "selection"
41918
+ ];
41620
41919
  let viewStateQueued = false;
41621
41920
  function emitViewState() {
41622
41921
  viewStateQueued = false;
@@ -41733,7 +42032,11 @@ function createBoardEditor(options) {
41733
42032
  return read(["scene", "selection"], selection.autoplay);
41734
42033
  },
41735
42034
  get bounds() {
41736
- return read(["scene", "selection"], selection.bounds);
42035
+ return read([
42036
+ "scene",
42037
+ "motion",
42038
+ "selection"
42039
+ ], selection.bounds);
41737
42040
  },
41738
42041
  get selectionTransform() {
41739
42042
  return read(transformChannels, selection.transform);
@@ -41947,6 +42250,7 @@ function createBoardEditor(options) {
41947
42250
  setCamera: camera.setCamera,
41948
42251
  setCameraPolicy: camera.setCameraPolicy,
41949
42252
  takeCameraControl: camera.takeCameraControl,
42253
+ followCamera: camera.follow,
41950
42254
  viewCenter: tracked(["camera"], camera.viewCenter),
41951
42255
  cameraState: tracked(["camera"], camera.cameraState),
41952
42256
  restoreCameraState: camera.restoreCameraState,
@@ -42056,7 +42360,8 @@ const EVENTS = [
42056
42360
  "selectionchange",
42057
42361
  "transformend",
42058
42362
  "change",
42059
- "gesture"
42363
+ "gesture",
42364
+ "peerschange"
42060
42365
  ];
42061
42366
  function pointsRect(points) {
42062
42367
  let minX = Infinity;
@@ -42123,6 +42428,9 @@ function createBoardScriptObservers(send) {
42123
42428
  get gestures() {
42124
42429
  return [...subscribers.values()].some((entry) => entry.listens.has("gesture"));
42125
42430
  },
42431
+ get watchesPeers() {
42432
+ return [...subscribers.values()].some((entry) => entry.listens.has("peerschange"));
42433
+ },
42126
42434
  update(owner, output) {
42127
42435
  const listens = new Set(EVENTS.filter((type) => output?.listens.includes(type)));
42128
42436
  if (!listens.size) {
@@ -42142,6 +42450,7 @@ function createBoardScriptObservers(send) {
42142
42450
  entry.items = void 0;
42143
42451
  entry.diffed = void 0;
42144
42452
  }
42453
+ if (!listens.has("peerschange")) entry.peers = void 0;
42145
42454
  entry.listens = listens;
42146
42455
  subscribers.set(owner, entry);
42147
42456
  },
@@ -42217,6 +42526,28 @@ function createBoardScriptObservers(send) {
42217
42526
  });
42218
42527
  }
42219
42528
  },
42529
+ peers(document, scene, list) {
42530
+ for (const [owner, entry] of subscribers) {
42531
+ if (!entry.listens.has("peerschange") || entry.peers?.from === list && entry.peers.scene === scene) continue;
42532
+ if (!isBoardRootScript(document, owner) && !scene.get(owner)) continue;
42533
+ const local = invertMatrix(scene.layout.matrix(owner));
42534
+ const data = list.map((peer) => ({
42535
+ ...peer,
42536
+ point: peer.point && applyMatrix$1(local, peer.point)
42537
+ }));
42538
+ const key = JSON.stringify(data);
42539
+ const changed = entry.peers?.key !== key;
42540
+ entry.peers = {
42541
+ from: list,
42542
+ scene,
42543
+ key
42544
+ };
42545
+ if (changed) send(owner, {
42546
+ type: "peerschange",
42547
+ data
42548
+ });
42549
+ }
42550
+ },
42220
42551
  clear() {
42221
42552
  subscribers.clear();
42222
42553
  }
@@ -42560,6 +42891,16 @@ function createBoardScriptController(options) {
42560
42891
  const { patch, frame } = value;
42561
42892
  return commits.commit(id, patch, !frame && activated(id));
42562
42893
  } },
42894
+ "board.broadcast": async (id, value) => {
42895
+ try {
42896
+ const event = boardScriptBroadcast(value);
42897
+ if (host && !host.event(id, event)) throw new Error(`broadcast("${event.type}") from ${id}: 128 events are already waiting.`);
42898
+ options.peers?.broadcast(id, event.type, event.data);
42899
+ } catch (error) {
42900
+ emitFailures.set(id, error instanceof Error ? error.message : String(error));
42901
+ throw error;
42902
+ }
42903
+ },
42563
42904
  "board.layoutText": async (_id, value) => layoutBoardScriptText(value)
42564
42905
  },
42565
42906
  onOutput: (id, output) => {
@@ -42721,6 +43062,7 @@ function createBoardScriptController(options) {
42721
43062
  }
42722
43063
  }), editor.itemSource);
42723
43064
  if (observers.gestures) syncGesture();
43065
+ if (observers.watchesPeers) observers.peers(editor.document, editor.scene, options.peers?.list() ?? []);
42724
43066
  }
42725
43067
  host.sync(scriptDocument(), editor.scene, view.camera, time, !paused, view.visibleIds);
42726
43068
  }
@@ -42920,6 +43262,23 @@ function createBoardScriptController(options) {
42920
43262
  return current.log;
42921
43263
  } };
42922
43264
  },
43265
+ receive(owner, type, data, peer) {
43266
+ if (paused || !host) return;
43267
+ let event;
43268
+ try {
43269
+ event = boardScriptBroadcast({
43270
+ type,
43271
+ data
43272
+ });
43273
+ } catch {
43274
+ return;
43275
+ }
43276
+ host.event(owner, {
43277
+ ...event,
43278
+ peer,
43279
+ remote: true
43280
+ });
43281
+ },
42923
43282
  cursor() {
42924
43283
  if (!hover) return null;
42925
43284
  const output = outputs.get(hover.owner);
@@ -42969,6 +43328,17 @@ function createBoardScriptController(options) {
42969
43328
  }
42970
43329
  //#endregion
42971
43330
  //#region ../sdk/src/board/testing/index.ts
43331
+ function harnessPeer(peer) {
43332
+ return {
43333
+ id: peer.id ?? `peer-${peer.name}`,
43334
+ actorId: peer.actorId ?? peer.name,
43335
+ name: peer.name,
43336
+ color: peer.color ?? "#3b82f6",
43337
+ point: peer.point ?? null,
43338
+ pointerType: peer.pointerType ?? (peer.point ? "mouse" : null),
43339
+ pressed: peer.pressed ?? false
43340
+ };
43341
+ }
42972
43342
  const FRAME_MS = 1e3 / 60;
42973
43343
  function describeInteraction(editor) {
42974
43344
  const interaction = editor.interaction;
@@ -42994,6 +43364,8 @@ async function createBoardScriptHarness(options) {
42994
43364
  let clock = 0;
42995
43365
  let timers = [];
42996
43366
  let runtime = null;
43367
+ let peers = [];
43368
+ const broadcasts = [];
42997
43369
  const editor = createBoardEditor({
42998
43370
  document: options.document,
42999
43371
  readonly: options.readonly === true,
@@ -43016,6 +43388,14 @@ async function createBoardScriptHarness(options) {
43016
43388
  editor,
43017
43389
  device: () => device,
43018
43390
  leader: () => options.leader ?? true,
43391
+ peers: {
43392
+ list: () => peers,
43393
+ broadcast: (owner, type, data) => broadcasts.push({
43394
+ owner,
43395
+ type,
43396
+ data
43397
+ })
43398
+ },
43019
43399
  now: () => clock,
43020
43400
  setTimer(run, ms) {
43021
43401
  const timer = {
@@ -43184,6 +43564,18 @@ async function createBoardScriptHarness(options) {
43184
43564
  }
43185
43565
  await frame();
43186
43566
  },
43567
+ get broadcasts() {
43568
+ return broadcasts;
43569
+ },
43570
+ async peers(next) {
43571
+ peers = next.map(harnessPeer);
43572
+ await frame();
43573
+ },
43574
+ async broadcast(owner, type, data = null, from = { name: "Peer" }) {
43575
+ const { point: _point, pointerType: _type, pressed: _pressed, ...peer } = harnessPeer(from);
43576
+ controller.receive(owner, type, data, peer);
43577
+ await frame();
43578
+ },
43187
43579
  async flush() {
43188
43580
  controller.flush(true);
43189
43581
  await frame();