vizmatic 0.6.0 → 0.7.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.
Files changed (42) hide show
  1. package/README.md +18 -18
  2. package/assets/THIRD_PARTY_LICENSES.md +10 -1
  3. package/assets/licenses/satori-NOTICES.txt +688 -0
  4. package/dist/{chunk-RWF4VBUL.js → chunk-CJOXWJQA.js} +2 -1
  5. package/dist/chunk-MAHT32CE.js +79 -0
  6. package/dist/cli.js +4 -4
  7. package/dist/index.cjs +1044 -155
  8. package/dist/index.d.cts +440 -5
  9. package/dist/index.d.ts +440 -5
  10. package/dist/index.js +1003 -129
  11. package/dist/satori.cjs +27 -0
  12. package/dist/scene-browser-assets.js +1 -1
  13. package/dist/scene-browser.js +17 -17
  14. package/dist/scene-cli.js +1 -1
  15. package/dist/scene-layout.wasm +0 -0
  16. package/dist/stage-browser/dagre.esm-6F3RIGLP.js +6 -0
  17. package/dist/stage-browser/stage.js +1 -1
  18. package/dist/stage-export.cjs +10 -2
  19. package/dist/stage-export.d.cts +11 -1
  20. package/dist/stage-export.d.ts +11 -1
  21. package/dist/stage-export.js +8 -2
  22. package/examples/_teaching/categorical-tail-loss.ts +25 -0
  23. package/examples/_teaching/teaching-byte-diff.ts +48 -0
  24. package/examples/_teaching/teaching-routed-transfer.ts +35 -0
  25. package/examples/_teaching/teaching-token-history.ts +29 -0
  26. package/examples/_teaching/teaching-weighted-vector.ts +55 -0
  27. package/examples/films/attention.ts +2 -2
  28. package/examples/films/cache-miss.ts +3 -3
  29. package/examples/films/central-limit.ts +1 -1
  30. package/examples/films/complex-maps.ts +1 -1
  31. package/examples/films/deck-example.ts +5 -5
  32. package/examples/films/euler-circle.ts +2 -2
  33. package/examples/films/fourier-epicycles.ts +15 -3
  34. package/examples/films/gradient-descent.ts +1 -1
  35. package/examples/films/linear-maps.ts +1 -1
  36. package/examples/films/lorenz.ts +1 -1
  37. package/examples/films/pythagoras.ts +3 -3
  38. package/examples/films/taylor-series.ts +2 -2
  39. package/examples/films/vizmatic-title.ts +1 -1
  40. package/package.json +4 -4
  41. package/dist/chunk-JHHPLALU.js +0 -79
  42. package/dist/stage-browser/dagre.esm-N2NIVIAZ.js +0 -6
package/dist/index.cjs CHANGED
@@ -133,19 +133,28 @@ __export(index_exports, {
133
133
  analyzeAnimationCadence: () => analyzeAnimationCadence,
134
134
  arcSwap: () => arcSwap,
135
135
  assertDensity: () => assertDensity,
136
+ assertTokenHistoryTransition: () => assertTokenHistoryTransition,
137
+ byteDifferenceState: () => byteDifferenceState,
136
138
  cameraSvgTransform: () => cameraSvgTransform,
137
139
  canvas: () => canvas,
140
+ categoricalSampling: () => categoricalSampling,
138
141
  checkFrame: () => checkFrame,
139
142
  colors: () => colors,
143
+ compareByteSequences: () => compareByteSequences,
140
144
  compositeColor: () => compositeColor,
141
145
  createCanvasComponents: () => createCanvasComponents,
142
146
  createCueTrack: () => createCueTrack,
143
147
  createFocusDirector: () => createFocusDirector,
144
148
  createPlotArea: () => createPlotArea,
145
149
  createPolylineMorph: () => createPolylineMorph,
150
+ createTeachingByteDifference: () => createTeachingByteDifference,
146
151
  createTeachingCanvas: () => createTeachingCanvas,
152
+ createTeachingCategoricalSampling: () => createTeachingCategoricalSampling,
147
153
  createTeachingFocus: () => createTeachingFocus,
154
+ createTeachingRoutedTransfer: () => createTeachingRoutedTransfer,
155
+ createTeachingTokenHistory: () => createTeachingTokenHistory,
148
156
  createTeachingValueChange: () => createTeachingValueChange,
157
+ createTeachingVectorAccumulation: () => createTeachingVectorAccumulation,
149
158
  cropPixels: () => cropPixels,
150
159
  cropRgbImage: () => cropRgbImage,
151
160
  cropRgbRaster: () => cropRgbRaster,
@@ -164,6 +173,7 @@ __export(index_exports, {
164
173
  dotProduct: () => dotProduct,
165
174
  encodeRgbPng: () => encodeRgbPng,
166
175
  entropy: () => entropy,
176
+ escapedByte: () => escapedByte,
167
177
  estimateTextWidth: () => estimateTextWidth,
168
178
  evaluateSceneSource: () => evaluateSceneSource,
169
179
  flattenRgbImage: () => flattenRgbImage,
@@ -193,6 +203,7 @@ __export(index_exports, {
193
203
  interpolateCamera: () => interpolateCamera,
194
204
  keyframe: () => keyframe,
195
205
  layoutAllocation: () => layoutAllocation,
206
+ layoutByteDifference: () => layoutByteDifference,
196
207
  layoutCellGrid: () => layoutCellGrid,
197
208
  layoutTokenRow: () => layoutTokenRow,
198
209
  lerpArray: () => lerpArray,
@@ -205,6 +216,7 @@ __export(index_exports, {
205
216
  normalizeWatermark: () => normalizeWatermark,
206
217
  parallel: () => parallel,
207
218
  parseDensity: () => parseDensity,
219
+ planTeachingRoutedTransfer: () => planTeachingRoutedTransfer,
208
220
  pointAlongPath: () => pointAlongPath,
209
221
  prepareScene: () => prepareScene,
210
222
  projectWorldPoint: () => projectWorldPoint,
@@ -239,6 +251,7 @@ __export(index_exports, {
239
251
  statusColor: () => statusColor,
240
252
  styles: () => styles,
241
253
  sumForces: () => sumForces,
254
+ tokenHistoryState: () => tokenHistoryState,
242
255
  toneGradients: () => toneGradients,
243
256
  tracePolyline: () => tracePolyline,
244
257
  transposeMatrix: () => transposeMatrix,
@@ -248,6 +261,7 @@ __export(index_exports, {
248
261
  valueChangeState: () => valueChangeState,
249
262
  videoFrameSchedule: () => videoFrameSchedule,
250
263
  waveValue: () => waveValue,
264
+ weightedVectorState: () => weightedVectorState,
251
265
  withColorAlpha: () => withColorAlpha,
252
266
  withDensity: () => withDensity,
253
267
  wrapWithBrand: () => wrapWithBrand,
@@ -350,9 +364,9 @@ function densityTokens(density = DEFAULT_DENSITY) {
350
364
  const cached = tokenCache.get(density);
351
365
  if (cached) return cached;
352
366
  assertDensity(density);
353
- const tokens = typeof density === "number" ? buildTokens("custom", numericCurve(density)) : buildTokens(density, curves[density]);
354
- tokenCache.set(density, tokens);
355
- return tokens;
367
+ const tokens2 = typeof density === "number" ? buildTokens("custom", numericCurve(density)) : buildTokens(density, curves[density]);
368
+ tokenCache.set(density, tokens2);
369
+ return tokens2;
356
370
  }
357
371
  var sharedKey = /* @__PURE__ */ Symbol.for("vizmatic.density");
358
372
  var globals = globalThis;
@@ -752,12 +766,12 @@ function withColorAlpha(color, opacity) {
752
766
  if (typeof color !== "string" || !Number.isFinite(opacity)) return "transparent";
753
767
  const parsed = parseColor(color);
754
768
  if (!parsed) return "transparent";
755
- const alpha2 = Math.min(1, Math.max(0, parsed.alpha * Math.min(1, Math.max(0, opacity))));
769
+ const alpha3 = Math.min(1, Math.max(0, parsed.alpha * Math.min(1, Math.max(0, opacity))));
756
770
  const hex = color.trim();
757
771
  if (/^#[\da-f]{6}$/i.test(hex)) {
758
- return `${hex}${Math.round(alpha2 * 255).toString(16).padStart(2, "0")}`;
772
+ return `${hex}${Math.round(alpha3 * 255).toString(16).padStart(2, "0")}`;
759
773
  }
760
- return `rgba(${parsed.channels.join(", ")}, ${Number(alpha2.toFixed(6))})`;
774
+ return `rgba(${parsed.channels.join(", ")}, ${Number(alpha3.toFixed(6))})`;
761
775
  }
762
776
  function colorLuminance(color, backdrop) {
763
777
  const parsed = parseColor(color);
@@ -779,12 +793,12 @@ function colorLuminance(color, backdrop) {
779
793
  function compositeColor(foreground, background) {
780
794
  const front = parseColor(foreground), back = parseColor(background);
781
795
  if (!front || !back) throw new Error("Color compositing requires valid CSS colors");
782
- const alpha2 = front.alpha + back.alpha * (1 - front.alpha);
783
- if (alpha2 === 0) return "transparent";
796
+ const alpha3 = front.alpha + back.alpha * (1 - front.alpha);
797
+ if (alpha3 === 0) return "transparent";
784
798
  const channels = front.channels.map((value, index) => Math.round(
785
- (value * front.alpha + back.channels[index] * back.alpha * (1 - front.alpha)) / alpha2
799
+ (value * front.alpha + back.channels[index] * back.alpha * (1 - front.alpha)) / alpha3
786
800
  ));
787
- return alpha2 === 1 ? `rgb(${channels.join(", ")})` : `rgba(${channels.join(", ")}, ${Number(alpha2.toFixed(6))})`;
801
+ return alpha3 === 1 ? `rgb(${channels.join(", ")})` : `rgba(${channels.join(", ")}, ${Number(alpha3.toFixed(6))})`;
788
802
  }
789
803
  function colorContrast(left, right, rightBackdrop) {
790
804
  const leftLuminance = colorLuminance(left);
@@ -2571,8 +2585,8 @@ function Sparkline({
2571
2585
  const h = height ?? d.f(18);
2572
2586
  const stroke = color ?? (tone ? getToneColor(tone, c) : c.textSecondary);
2573
2587
  const line = strokeWidth ?? d.w(1.5);
2574
- const finite6 = values.filter(Number.isFinite);
2575
- const low = min ?? Math.min(...finite6), high = max ?? Math.max(...finite6);
2588
+ const finite8 = values.filter(Number.isFinite);
2589
+ const low = min ?? Math.min(...finite8), high = max ?? Math.max(...finite8);
2576
2590
  const range = high - low || 1;
2577
2591
  const inset = endDot ? d.g(3) : line;
2578
2592
  const x = (index) => inset + (values.length <= 1 ? 0 : index / (values.length - 1) * (w - inset * 2));
@@ -4299,9 +4313,9 @@ function preferredSide(from, to) {
4299
4313
  return to.cy >= from.cy ? "bottom" : "top";
4300
4314
  }
4301
4315
  function routingAnchor(node, side, offset = 0.5) {
4302
- const bounds2 = box(node);
4303
- if (side === "left" || side === "right") return { x: bounds2[side], y: bounds2.top + node.height * offset };
4304
- return { x: bounds2.left + node.width * offset, y: bounds2[side] };
4316
+ const bounds4 = box(node);
4317
+ if (side === "left" || side === "right") return { x: bounds4[side], y: bounds4.top + node.height * offset };
4318
+ return { x: bounds4.left + node.width * offset, y: bounds4[side] };
4305
4319
  }
4306
4320
  function outward(point, side, distance) {
4307
4321
  return {
@@ -5545,14 +5559,14 @@ function GraphDiagram({
5545
5559
  if (!from || !to) return;
5546
5560
  const [fromSide, toSide] = chooseSides(from, to, flowIsHorizontal(edge));
5547
5561
  const coordinate = (node, side) => side === "left" || side === "right" ? node.cy : node.cx;
5548
- const add = (node, side, other, end) => {
5562
+ const add2 = (node, side, other, end) => {
5549
5563
  const key = `${node.id}\0${side}`;
5550
5564
  const list = sideUsers.get(key) ?? [];
5551
5565
  list.push({ key: `${index}\0${end}`, other: coordinate(other, side) + index * 1e-3, length: side === "left" || side === "right" ? node.height : node.width });
5552
5566
  sideUsers.set(key, list);
5553
5567
  };
5554
- add(from, fromSide, to, "from");
5555
- add(to, toSide, from, "to");
5568
+ add2(from, fromSide, to, "from");
5569
+ add2(to, toSide, from, "to");
5556
5570
  });
5557
5571
  for (const users of sideUsers.values()) {
5558
5572
  users.sort((left, right) => left.other - right.other);
@@ -6878,7 +6892,7 @@ function SequenceDiagram({
6878
6892
  const noteElements = rows.map((row, rowIndex) => {
6879
6893
  if (!row.item || !isNote(row.item)) return null;
6880
6894
  const note = row.item;
6881
- const bounds2 = sequenceNoteBounds(note, participantXs, resolvedWidth, noteWidth, padding);
6895
+ const bounds4 = sequenceNoteBounds(note, participantXs, resolvedWidth, noteWidth, padding);
6882
6896
  const tone = note.tone ?? "warm";
6883
6897
  const accent = note.muted ? c.textMuted : getToneColor(tone, c);
6884
6898
  return import_react9.default.createElement("div", {
@@ -6886,9 +6900,9 @@ function SequenceDiagram({
6886
6900
  "data-vizmatic-sequence-note": note.id ?? row.key,
6887
6901
  style: {
6888
6902
  position: "absolute",
6889
- left: bounds2.left,
6903
+ left: bounds4.left,
6890
6904
  top: rowCenter(rowIndex) - 17,
6891
- width: bounds2.width,
6905
+ width: bounds4.width,
6892
6906
  minHeight: 34,
6893
6907
  boxSizing: "border-box",
6894
6908
  display: "flex",
@@ -7096,10 +7110,10 @@ function validateSchema(schema, owner) {
7096
7110
  function schemaLabel(schema) {
7097
7111
  if (schema == null) return void 0;
7098
7112
  if (typeof schema === "string") return schema;
7099
- const prefix = [schema.name, schema.version].filter(Boolean).join(" ");
7113
+ const prefix2 = [schema.name, schema.version].filter(Boolean).join(" ");
7100
7114
  const fieldList = Array.isArray(schema.fields) ? schema.fields : Object.entries(schema.fields).map(([name, type]) => ({ name, type, required: false }));
7101
7115
  const fields = fieldList.map((field) => `${field.name}${field.type ? `: ${field.type}` : ""}${field.required ? " *" : ""}`).join(", ");
7102
- return [prefix, fields ? `{ ${fields} }` : void 0].filter(Boolean).join(" ");
7116
+ return [prefix2, fields ? `{ ${fields} }` : void 0].filter(Boolean).join(" ");
7103
7117
  }
7104
7118
  function detailWithSchema(detail, schema) {
7105
7119
  const renderedSchema = schemaLabel(schema);
@@ -8502,13 +8516,13 @@ function AxisPlot({
8502
8516
  opacity: path.opacity ?? 1
8503
8517
  })];
8504
8518
  }));
8505
- elements.push(...vectors.map((vector, index) => {
8506
- const color = vector.color ?? getToneColor(vector.tone ?? "blue", c);
8507
- const x1 = sx(vector.x1);
8508
- const y1 = sy(vector.y1);
8509
- const x2 = sx(vector.x2);
8510
- const y2 = sy(vector.y2);
8511
- if (vector.arrow) {
8519
+ elements.push(...vectors.map((vector2, index) => {
8520
+ const color = vector2.color ?? getToneColor(vector2.tone ?? "blue", c);
8521
+ const x1 = sx(vector2.x1);
8522
+ const y1 = sy(vector2.y1);
8523
+ const x2 = sx(vector2.x2);
8524
+ const y2 = sy(vector2.y2);
8525
+ if (vector2.arrow) {
8512
8526
  return VectorArrow({
8513
8527
  key: `axis-vector-${index}`,
8514
8528
  x1,
@@ -8516,9 +8530,9 @@ function AxisPlot({
8516
8530
  x2,
8517
8531
  y2,
8518
8532
  color,
8519
- strokeWidth: vector.strokeWidth,
8520
- arrowSize: vector.arrowSize,
8521
- opacity: vector.opacity
8533
+ strokeWidth: vector2.strokeWidth,
8534
+ arrowSize: vector2.arrowSize,
8535
+ opacity: vector2.opacity
8522
8536
  });
8523
8537
  }
8524
8538
  return VectorSegment({
@@ -8528,11 +8542,11 @@ function AxisPlot({
8528
8542
  x2,
8529
8543
  y2,
8530
8544
  color,
8531
- strokeWidth: vector.strokeWidth,
8532
- opacity: vector.opacity,
8533
- showStartDot: vector.showStartDot,
8534
- showEndDot: vector.showEndDot,
8535
- dotRadius: vector.dotRadius
8545
+ strokeWidth: vector2.strokeWidth,
8546
+ opacity: vector2.opacity,
8547
+ showStartDot: vector2.showStartDot,
8548
+ showEndDot: vector2.showEndDot,
8549
+ dotRadius: vector2.dotRadius
8536
8550
  });
8537
8551
  }));
8538
8552
  elements.push(...points.map((point, index) => SvgPoint({
@@ -8696,14 +8710,14 @@ async function renderWithCanvasChartFit(render, element, options) {
8696
8710
  const prepared = prepareChartFits(element);
8697
8711
  if (!prepared.sizes.size) return render(prepared.element, options);
8698
8712
  const viewports = /* @__PURE__ */ new Map();
8699
- const bounds2 = /* @__PURE__ */ new Map();
8713
+ const bounds4 = /* @__PURE__ */ new Map();
8700
8714
  await render(prepared.element, { ...options, onNodeDetected(node) {
8701
8715
  const viewport = node.props[VIEWPORT_PROP];
8702
8716
  if (typeof viewport === "string") viewports.set(viewport, node);
8703
8717
  const id = node.props[SCOPE_PROP];
8704
8718
  if (typeof id !== "string" || node.width < 0 || node.height < 0) return;
8705
- const prior = bounds2.get(id);
8706
- bounds2.set(id, {
8719
+ const prior = bounds4.get(id);
8720
+ bounds4.set(id, {
8707
8721
  left: Math.min(prior?.left ?? Infinity, node.left),
8708
8722
  top: Math.min(prior?.top ?? Infinity, node.top),
8709
8723
  right: Math.max(prior?.right ?? -Infinity, node.left + node.width),
@@ -8713,7 +8727,7 @@ async function renderWithCanvasChartFit(render, element, options) {
8713
8727
  const geometry = /* @__PURE__ */ new Map();
8714
8728
  for (const [id, size] of prepared.sizes) {
8715
8729
  const viewport = viewports.get(id);
8716
- const measured = bounds2.get(id);
8730
+ const measured = bounds4.get(id);
8717
8731
  if (!viewport || !measured) throw new Error("Could not measure the chart inside CanvasItem.");
8718
8732
  const width = measured.right - measured.left, height = measured.bottom - measured.top;
8719
8733
  const scale = Math.min(size.width / width, size.height / height);
@@ -10958,7 +10972,7 @@ function GeometryDiagram({
10958
10972
  width = 720,
10959
10973
  height = 440
10960
10974
  }) {
10961
- const bounds2 = geometryBounds(points);
10975
+ const bounds4 = geometryBounds(points);
10962
10976
  dimensions(width, height, "GeometryDiagram");
10963
10977
  labelText(title, "GeometryDiagram title", 32);
10964
10978
  bounded(segments, 256, "GeometryDiagram segments");
@@ -11006,10 +11020,10 @@ function GeometryDiagram({
11006
11020
  colorValue(angle.color, c.accent, `GeometryDiagram angle ${index} color`);
11007
11021
  });
11008
11022
  const padding = 80;
11009
- const maxRange = Math.max(bounds2.width, bounds2.height);
11023
+ const maxRange = Math.max(bounds4.width, bounds4.height);
11010
11024
  const scale = maxRange === 0 ? Math.min(width - padding * 2, height - padding * 2) : Math.min((width - padding * 2) / maxRange, (height - padding * 2) / maxRange);
11011
- const centerX = bounds2.minX / 2 + bounds2.maxX / 2;
11012
- const centerY = bounds2.minY / 2 + bounds2.maxY / 2;
11025
+ const centerX = bounds4.minX / 2 + bounds4.maxX / 2;
11026
+ const centerY = bounds4.minY / 2 + bounds4.maxY / 2;
11013
11027
  if (!Number.isFinite(centerX) || !Number.isFinite(centerY) || !Number.isFinite(scale) || scale <= 0) {
11014
11028
  throw new RangeError("GeometryDiagram coordinates cannot be mapped into the viewport.");
11015
11029
  }
@@ -12273,11 +12287,11 @@ function AttentionMatrix({
12273
12287
  const fullyMasked = mask?.[i].every((value) => !value) ?? false;
12274
12288
  if (Math.abs(total - (fullyMasked ? 0 : 1)) > 1e-6) throw new Error("Each visible attention row must sum to one");
12275
12289
  }
12276
- const labels = (input, count, prefix) => {
12290
+ const labels = (input, count, prefix2) => {
12277
12291
  if (input && (input.length !== count || input.some((value) => typeof value !== "string" || value.length > 24))) {
12278
12292
  throw new Error("Attention labels must match the matrix dimensions and contain at most 24 characters");
12279
12293
  }
12280
- return input ? [...input] : Array.from({ length: count }, (_, i) => `${prefix}${i + 1}`);
12294
+ return input ? [...input] : Array.from({ length: count }, (_, i) => `${prefix2}${i + 1}`);
12281
12295
  };
12282
12296
  const queryNames = labels(queryLabels, rows, "q");
12283
12297
  const keyNames = labels(keyLabels, columns, "k");
@@ -13879,8 +13893,8 @@ var PngDecoder = class extends IOBuffer {
13879
13893
  }
13880
13894
  let i = 0;
13881
13895
  for (; i < length; i++) {
13882
- const alpha2 = this.readByte();
13883
- this._palette[i].push(alpha2);
13896
+ const alpha3 = this.readByte();
13897
+ this._palette[i].push(alpha3);
13884
13898
  }
13885
13899
  for (; i < this._palette.length; i++) {
13886
13900
  this._palette[i].push(255);
@@ -14163,15 +14177,15 @@ var PngEncoder = class extends IOBuffer {
14163
14177
  writeCrc(this, 4 + paletteLength);
14164
14178
  }
14165
14179
  encodeTRNS() {
14166
- const alpha2 = this._png.palette.filter((color) => {
14180
+ const alpha3 = this._png.palette.filter((color) => {
14167
14181
  return color.at(-1) !== 255;
14168
14182
  });
14169
- this.writeUint32(alpha2.length);
14183
+ this.writeUint32(alpha3.length);
14170
14184
  this.writeChars("tRNS");
14171
- for (const el of alpha2) {
14185
+ for (const el of alpha3) {
14172
14186
  this.writeByte(el.at(-1));
14173
14187
  }
14174
- writeCrc(this, 4 + alpha2.length);
14188
+ writeCrc(this, 4 + alpha3.length);
14175
14189
  }
14176
14190
  // https://www.w3.org/TR/PNG/#11IDAT
14177
14191
  encodeIDAT(data) {
@@ -14861,7 +14875,7 @@ function detectLayoutOverflow(nodes, width, height) {
14861
14875
  }
14862
14876
 
14863
14877
  // src/satori.ts
14864
- var satoriModule = __toESM(require("satori"), 1);
14878
+ var satoriModule = __toESM(require("./satori.cjs"), 1);
14865
14879
  function resolveSatori(api) {
14866
14880
  if (typeof api === "function") return api;
14867
14881
  if (api && typeof api === "object") {
@@ -15164,7 +15178,7 @@ async function renderToPngInContext(element, options, createFn, theme) {
15164
15178
  const detectPixels = detectResult.pixels;
15165
15179
  const pixelData = new Uint8Array(detectPixels.buffer);
15166
15180
  const detectedBg = detectBackgroundColor(pixelData);
15167
- const bounds2 = detectContentBounds(
15181
+ const bounds4 = detectContentBounds(
15168
15182
  pixelData,
15169
15183
  options.width,
15170
15184
  detectResult.height,
@@ -15187,7 +15201,7 @@ async function renderToPngInContext(element, options, createFn, theme) {
15187
15201
  let finalWidth = options.width;
15188
15202
  let finalHeight = options.height;
15189
15203
  let finalElement = element;
15190
- const croppedHeight = bounds2.y + bounds2.height;
15204
+ const croppedHeight = bounds4.y + bounds4.height;
15191
15205
  const heightSaved = options.height - croppedHeight;
15192
15206
  const heightSavedPercent = heightSaved / options.height * 100;
15193
15207
  if (shouldCropHeight(options.crop) && heightSavedPercent >= CROP_THRESHOLD_PERCENT) {
@@ -15829,16 +15843,16 @@ function cropFramePixels(pixels, canvasWidth, region) {
15829
15843
  }
15830
15844
  function deltaPixelFrame(frame, previous, enabled) {
15831
15845
  if (!enabled || !previous) return frame;
15832
- const bounds2 = changedBounds(previous, frame.pixels, frame.width, frame.height);
15833
- if (!bounds2 || bounds2.width === frame.width && bounds2.height === frame.height) return frame;
15846
+ const bounds4 = changedBounds(previous, frame.pixels, frame.width, frame.height);
15847
+ if (!bounds4 || bounds4.width === frame.width && bounds4.height === frame.height) return frame;
15834
15848
  return {
15835
15849
  ...frame,
15836
- x: bounds2.x,
15837
- y: bounds2.y,
15850
+ x: bounds4.x,
15851
+ y: bounds4.y,
15838
15852
  delta: true,
15839
- width: bounds2.width,
15840
- height: bounds2.height,
15841
- pixels: cropFramePixels(frame.pixels, frame.width, bounds2)
15853
+ width: bounds4.width,
15854
+ height: bounds4.height,
15855
+ pixels: cropFramePixels(frame.pixels, frame.width, bounds4)
15842
15856
  };
15843
15857
  }
15844
15858
  function encodeGif(frames, loop, deltaFrames) {
@@ -16373,12 +16387,12 @@ function normalizedOpacity(value, name = "Canvas opacity") {
16373
16387
  finite3(value, name);
16374
16388
  return Math.max(0, Math.min(1, value));
16375
16389
  }
16376
- function validateBounds(bounds2) {
16377
- finite3(bounds2.x, "Canvas x");
16378
- finite3(bounds2.y, "Canvas y");
16379
- positive2(bounds2.width, "Canvas width");
16380
- positive2(bounds2.height, "Canvas height");
16381
- nonnegative(bounds2.radius ?? 14, "Canvas radius");
16390
+ function validateBounds(bounds4) {
16391
+ finite3(bounds4.x, "Canvas x");
16392
+ finite3(bounds4.y, "Canvas y");
16393
+ positive2(bounds4.width, "Canvas width");
16394
+ positive2(bounds4.height, "Canvas height");
16395
+ nonnegative(bounds4.radius ?? 14, "Canvas radius");
16382
16396
  }
16383
16397
  function layoutTokenRow(values, options = {}) {
16384
16398
  const { advance = 24, gap = 16, minWidth = 64, paddingX = 17, width } = options;
@@ -16404,24 +16418,24 @@ function layoutTokenRow(values, options = {}) {
16404
16418
  return items;
16405
16419
  }
16406
16420
  function createCanvasComponents(painter) {
16407
- function fade(alpha2, draw) {
16408
- const amount2 = normalizedOpacity(alpha2);
16421
+ function fade(alpha3, draw) {
16422
+ const amount2 = normalizedOpacity(alpha3);
16409
16423
  if (amount2 > 0) painter.opacity(amount2, draw);
16410
16424
  }
16411
16425
  function panel(options, draw) {
16412
16426
  validateBounds(options);
16413
16427
  const { x, y, width, height, fill, stroke, radius = 14, padding = 10, id, scope = "container", opacity = 1 } = options;
16414
16428
  nonnegative(padding, "Canvas padding");
16415
- const alpha2 = normalizedOpacity(opacity);
16429
+ const alpha3 = normalizedOpacity(opacity);
16416
16430
  if (scope !== "container" && scope !== "label") throw new Error("Canvas scope must be container or label");
16417
16431
  let shape;
16418
- const paint = () => painter.opacity(alpha2, () => {
16432
+ const paint = () => painter.opacity(alpha3, () => {
16419
16433
  shape = painter.rect(x, y, width, height, fill, stroke, radius);
16420
16434
  if (draw) {
16421
- const bounds2 = { x, y, width, height, radius };
16435
+ const bounds4 = { x, y, width, height, radius };
16422
16436
  const scopeOptions = { padding, id };
16423
- if (scope === "label") painter.labelScope(bounds2, draw, scopeOptions);
16424
- else painter.container(bounds2, draw, scopeOptions);
16437
+ if (scope === "label") painter.labelScope(bounds4, draw, scopeOptions);
16438
+ else painter.container(bounds4, draw, scopeOptions);
16425
16439
  }
16426
16440
  });
16427
16441
  if (options.focusTarget && painter.target) painter.target(options.focusTarget, paint);
@@ -16476,11 +16490,11 @@ function createCanvasComponents(painter) {
16476
16490
  finite3(y, "Token row y");
16477
16491
  positive2(height, "Token height");
16478
16492
  finite3(reveal, "Token reveal");
16479
- const alpha2 = normalizedOpacity(opacity);
16493
+ const alpha3 = normalizedOpacity(opacity);
16480
16494
  const items = layoutTokenRow(values, options);
16481
16495
  const shapes = [];
16482
16496
  for (let index = 0; index < items.length; index += 1) {
16483
- const amount2 = Math.max(0, Math.min(1, reveal * items.length - index)) * alpha2;
16497
+ const amount2 = Math.max(0, Math.min(1, reveal * items.length - index)) * alpha3;
16484
16498
  if (amount2 <= 0) continue;
16485
16499
  const { text: label, x, width } = items[index];
16486
16500
  const shape = card({ ...style, label, x, y, width, height, opacity: amount2 });
@@ -16537,11 +16551,11 @@ function edgeDistance(shape, ux, uy) {
16537
16551
  return low;
16538
16552
  }
16539
16553
  function safeGap(shape, ux, uy, clearance, edge) {
16540
- const expanded = Math.min(
16554
+ const expanded2 = Math.min(
16541
16555
  ux === 0 ? Infinity : (shape.width / 2 + clearance) / Math.abs(ux),
16542
16556
  uy === 0 ? Infinity : (shape.height / 2 + clearance) / Math.abs(uy)
16543
16557
  );
16544
- return expanded - edge;
16558
+ return expanded2 - edge;
16545
16559
  }
16546
16560
  function createTeachingTransfer(painter) {
16547
16561
  return (options) => {
@@ -16597,7 +16611,7 @@ function layoutCellGrid(options) {
16597
16611
  if (![rows, columns, rows * columns].every(Number.isSafeInteger) || rows <= 0 || columns <= 0) {
16598
16612
  throw new Error("Grid rows and columns must be positive safe integers");
16599
16613
  }
16600
- const bounds2 = { x, y, width, height };
16614
+ const bounds4 = { x, y, width, height };
16601
16615
  const cells = Array.from({ length: rows }, (_, row) => Array.from({ length: columns }, (_2, column) => ({
16602
16616
  x: x + column * width / columns,
16603
16617
  y: y + row * height / rows,
@@ -16605,7 +16619,7 @@ function layoutCellGrid(options) {
16605
16619
  height: height / rows
16606
16620
  })));
16607
16621
  return {
16608
- bounds: bounds2,
16622
+ bounds: bounds4,
16609
16623
  cells,
16610
16624
  cell(row, column) {
16611
16625
  if (!Number.isSafeInteger(row) || !Number.isSafeInteger(column) || row < 0 || row >= rows || column < 0 || column >= columns) {
@@ -16740,9 +16754,9 @@ function createTeachingTimeline(painter) {
16740
16754
  if (!Number.isFinite(value) || value < lo || value > hi) throw new Error("Timeline point must lie inside the domain");
16741
16755
  return left + (value - lo) / (hi - lo) * plotWidth;
16742
16756
  };
16743
- const bounds2 = { x, y, width, height };
16744
- const result = { bounds: bounds2, time, point, lanes: /* @__PURE__ */ Object.create(null), intervals: /* @__PURE__ */ Object.create(null) };
16745
- painter.container(bounds2, () => {
16757
+ const bounds4 = { x, y, width, height };
16758
+ const result = { bounds: bounds4, time, point, lanes: /* @__PURE__ */ Object.create(null), intervals: /* @__PURE__ */ Object.create(null) };
16759
+ painter.container(bounds4, () => {
16746
16760
  lanes.forEach((lane, index) => target(lane.focusTarget, () => {
16747
16761
  const top = y + index * (laneHeight + laneGap);
16748
16762
  const track = { x: left - 2, y: top + labelHeight, width: plotWidth + 4, height: barHeight };
@@ -16969,11 +16983,11 @@ function createFocusDirector(painter, options = {}) {
16969
16983
  }
16970
16984
  function createTeachingFocus(painter) {
16971
16985
  function focusFrame(options) {
16972
- const { bounds: bounds2, strength, color = "#63DEEC", padding = 8, clip } = options;
16973
- if (![bounds2.x, bounds2.y, bounds2.width, bounds2.height, strength, padding].every(Number.isFinite) || bounds2.width <= 0 || bounds2.height <= 0 || padding < 0 || strength < 0 || strength > 1) throw new Error("Invalid focus frame geometry or strength");
16986
+ const { bounds: bounds4, strength, color = "#63DEEC", padding = 8, clip } = options;
16987
+ if (![bounds4.x, bounds4.y, bounds4.width, bounds4.height, strength, padding].every(Number.isFinite) || bounds4.width <= 0 || bounds4.height <= 0 || padding < 0 || strength < 0 || strength > 1) throw new Error("Invalid focus frame geometry or strength");
16974
16988
  if (strength === 0) return;
16975
16989
  const corners = (offset) => {
16976
- const x = bounds2.x - offset, y = bounds2.y - offset, w = bounds2.width + offset * 2, h = bounds2.height + offset * 2;
16990
+ const x = bounds4.x - offset, y = bounds4.y - offset, w = bounds4.width + offset * 2, h = bounds4.height + offset * 2;
16977
16991
  const corner = Math.min(24, w / 4, h / 4);
16978
16992
  return [[x, y, 1, 1], [x + w, y, -1, 1], [x, y + h, 1, -1], [x + w, y + h, -1, -1]].map(([cx, cy, sx, sy]) => [{ x: cx + sx * corner, y: cy }, { x: cx, y: cy }, { x: cx, y: cy + sy * corner }]);
16979
16993
  };
@@ -16997,31 +17011,874 @@ function createTeachingFocus(painter) {
16997
17011
  return { focusFrame };
16998
17012
  }
16999
17013
 
17014
+ // src/teaching-vector.ts
17015
+ var clamp4 = (value) => Math.max(0, Math.min(1, value));
17016
+ var cleanZero = (value) => value === 0 ? 0 : value;
17017
+ function finite4(value, name) {
17018
+ if (!Number.isFinite(value)) throw new Error(`${name} must be finite`);
17019
+ return value;
17020
+ }
17021
+ function vector(values, dimensions2, name) {
17022
+ if (values.length !== dimensions2) throw new Error(`${name} must have ${dimensions2} coordinates`);
17023
+ return values.map((value) => cleanZero(finite4(value, name)));
17024
+ }
17025
+ function add(left, right) {
17026
+ return left.map((value, index) => cleanZero(finite4(value + right[index], "Weighted vector sum")));
17027
+ }
17028
+ function weightedVectorState(options) {
17029
+ const progress = clamp4(finite4(options.progress, "Weighted vector progress"));
17030
+ const dimensions2 = options.initial?.length ?? options.terms[0]?.values.length ?? 0;
17031
+ if (!dimensions2) throw new Error("Weighted vectors require at least one coordinate; an empty sum needs an initial vector");
17032
+ const initial = options.initial ? vector(options.initial, dimensions2, "Initial vector") : Array(dimensions2).fill(0);
17033
+ const ids = /* @__PURE__ */ new Set();
17034
+ let prefix2 = [...initial];
17035
+ const position2 = progress * options.terms.length;
17036
+ const completedCount = Math.min(options.terms.length, Math.floor(position2));
17037
+ const terms = options.terms.map((term, index) => {
17038
+ if (typeof term.id !== "string" || !term.id.trim() || term.id !== term.id.trim() || ids.has(term.id)) {
17039
+ throw new Error("Weighted vector terms require distinct nonempty IDs without surrounding whitespace");
17040
+ }
17041
+ ids.add(term.id);
17042
+ const label = term.label ?? term.id;
17043
+ if (typeof label !== "string" || !label.trim()) throw new Error("Weighted vector labels must be nonempty");
17044
+ const weight = finite4(term.weight, "Vector weight");
17045
+ const values = vector(term.values, dimensions2, `Vector ${term.id}`);
17046
+ const contribution = values.map((value) => cleanZero(finite4(weight * value, "Weighted vector contribution")));
17047
+ const start = [...prefix2], end = add(start, contribution);
17048
+ prefix2 = end;
17049
+ const fraction = clamp4(position2 - index);
17050
+ const status = fraction === 1 ? "completed" : index === completedCount && progress < 1 ? "current" : "pending";
17051
+ const applied = contribution.map((value) => cleanZero(value * fraction));
17052
+ return {
17053
+ ...term,
17054
+ label,
17055
+ values,
17056
+ weight,
17057
+ status,
17058
+ progress: fraction,
17059
+ contribution,
17060
+ applied,
17061
+ start,
17062
+ end,
17063
+ currentEnd: add(start, applied),
17064
+ zero: contribution.every((value) => value === 0)
17065
+ };
17066
+ });
17067
+ const completedSum = completedCount ? [...terms[completedCount - 1].end] : [...initial];
17068
+ const current = terms.find((term) => term.status === "current") ?? null;
17069
+ return {
17070
+ progress,
17071
+ dimensions: dimensions2,
17072
+ initial,
17073
+ terms,
17074
+ completedCount,
17075
+ current,
17076
+ completedSum,
17077
+ sum: current ? [...current.currentEnd] : [...completedSum],
17078
+ total: [...prefix2]
17079
+ };
17080
+ }
17081
+ function positive4(value, name) {
17082
+ if (finite4(value, name) <= 0) throw new Error(`${name} must be positive`);
17083
+ }
17084
+ function bounds2(value, name) {
17085
+ finite4(value.x, `${name} x`);
17086
+ finite4(value.y, `${name} y`);
17087
+ positive4(value.width, `${name} width`);
17088
+ positive4(value.height, `${name} height`);
17089
+ }
17090
+ function createTeachingVectorAccumulation(painter) {
17091
+ return (options) => {
17092
+ const state = weightedVectorState(options);
17093
+ const {
17094
+ plot,
17095
+ ledger,
17096
+ projection,
17097
+ fontSize = 28,
17098
+ color = "#63DEEC",
17099
+ restColor = "#8D9CB9",
17100
+ completedOpacity = 0.45,
17101
+ width = 4,
17102
+ endpointRadius = 5,
17103
+ revealTotal = false,
17104
+ totalLabel = "Accumulated vector",
17105
+ format = (value) => String(Number(value.toPrecision(4)))
17106
+ } = options;
17107
+ bounds2(plot.bounds, "Vector plot");
17108
+ bounds2(ledger, "Vector ledger");
17109
+ positive4(fontSize, "Vector font size");
17110
+ positive4(width, "Vector stroke width");
17111
+ positive4(endpointRadius, "Vector endpoint radius");
17112
+ finite4(completedOpacity, "Completed vector opacity");
17113
+ if (completedOpacity < 0 || completedOpacity > 1) throw new Error("Completed vector opacity must lie between zero and one");
17114
+ const [x0, x1] = plot.xDomain, [y0, y1] = plot.yDomain;
17115
+ for (const value of [x0, x1, y0, y1]) finite4(value, "Vector plot domain");
17116
+ if (x1 <= x0 || y1 <= y0) throw new Error("Vector plot domains must increase");
17117
+ const sx = plot.bounds.width / (x1 - x0), sy = plot.bounds.height / (y1 - y0);
17118
+ if (!Number.isFinite(sx) || !Number.isFinite(sy) || sx <= 0 || sy <= 0 || Math.abs(sx - sy) > Math.max(sx, sy) * 1e-9) {
17119
+ throw new Error("Weighted vector drawing requires equal-unit plot geometry");
17120
+ }
17121
+ if (state.dimensions !== 2 && !projection) throw new Error("Weighted vector drawing requires 2D values or an explicit projection");
17122
+ if (projection && !projection.label.trim()) throw new Error("Vector projection requires a visible declaration");
17123
+ const rowHeight = fontSize * 2.5, headerHeight = fontSize * 1.6;
17124
+ if (ledger.height < headerHeight + state.terms.length * rowHeight + fontSize * 1.8) {
17125
+ throw new Error("Vector ledger height must contain the identities, contributions and result");
17126
+ }
17127
+ const point = (values) => {
17128
+ const projected = projection ? projection.point([...values]) : values;
17129
+ if (projected.length !== 2) throw new Error("Vector projection must return exactly two coordinates");
17130
+ const [x, y] = projected;
17131
+ finite4(x, "Projected vector x");
17132
+ finite4(y, "Projected vector y");
17133
+ if (x < x0 || x > x1 || y < y0 || y > y1) throw new Error("Vector endpoints must lie inside the declared plot domains");
17134
+ const p = plot.point(x, y);
17135
+ finite4(p.x, "Vector endpoint x");
17136
+ finite4(p.y, "Vector endpoint y");
17137
+ const expectedX = finite4(plot.bounds.x + (x - x0) * sx, "Declared vector endpoint x");
17138
+ const expectedY = finite4(plot.bounds.y + plot.bounds.height - (y - y0) * sy, "Declared vector endpoint y");
17139
+ const tolerance = Math.max(1, Math.abs(expectedX), Math.abs(expectedY), plot.bounds.width, plot.bounds.height) * 1e-9;
17140
+ if (Math.abs(p.x - expectedX) > tolerance || Math.abs(p.y - expectedY) > tolerance) {
17141
+ throw new Error("Vector plot mapping must match its declared equal-unit transform");
17142
+ }
17143
+ return p;
17144
+ };
17145
+ const segments = [];
17146
+ for (const term of state.terms) {
17147
+ const from = point(term.start);
17148
+ point(term.end);
17149
+ const to = point(term.currentEnd);
17150
+ if (term.status !== "pending") segments.push({
17151
+ id: term.id,
17152
+ status: term.status,
17153
+ from,
17154
+ to,
17155
+ zero: Math.hypot(to.x - from.x, to.y - from.y) < 1e-9
17156
+ });
17157
+ }
17158
+ const endpoint2 = point(state.sum);
17159
+ const vectorText = (values) => `(${values.map(format).join(", ")})`;
17160
+ const target = (id, draw) => painter.target ? painter.target(id, draw) : draw();
17161
+ const paintedTerms = state.terms.map((term, index) => ({
17162
+ term,
17163
+ index,
17164
+ input: `${term.label}: ${format(term.weight)} \xD7 ${vectorText(term.values)}`,
17165
+ detail: term.status === "pending" ? "pending" : `${term.status}: ${vectorText(term.applied)}`
17166
+ }));
17167
+ const totalText = `${totalLabel}: ${revealTotal ? vectorText(state.sum) : "?"}`;
17168
+ for (const segment of segments) {
17169
+ const term = state.terms.find((term2) => term2.id === segment.id);
17170
+ const ink = term.color ?? color;
17171
+ target(term.id, () => painter.opacity(term.status === "completed" ? completedOpacity : 1, () => {
17172
+ if (segment.zero) painter.circle(segment.to.x, segment.to.y, endpointRadius, "transparent", ink, width);
17173
+ else painter.arrow(segment.from.x, segment.from.y, segment.to.x, segment.to.y, ink, width);
17174
+ }));
17175
+ }
17176
+ if (revealTotal) {
17177
+ const mark = () => {
17178
+ painter.circle(endpoint2.x, endpoint2.y, endpointRadius * 1.5, color);
17179
+ };
17180
+ if (options.totalTarget) target(options.totalTarget, mark);
17181
+ else mark();
17182
+ }
17183
+ painter.labelScope(ledger, () => {
17184
+ painter.text(
17185
+ projection ? `Projection: ${projection.label}` : "Weighted contributions",
17186
+ ledger.x + 12,
17187
+ ledger.y + fontSize,
17188
+ fontSize * 0.85,
17189
+ restColor
17190
+ );
17191
+ for (const { term, index, input, detail } of paintedTerms) target(term.id, () => {
17192
+ const ink = term.color ?? color;
17193
+ const y = ledger.y + headerHeight + index * rowHeight;
17194
+ painter.text(input, ledger.x + 12, y + fontSize, fontSize, term.status === "pending" ? restColor : ink);
17195
+ painter.text(detail, ledger.x + 12, y + fontSize * 1.9, fontSize * 0.8, restColor);
17196
+ });
17197
+ const result = () => {
17198
+ painter.text(
17199
+ totalText,
17200
+ ledger.x + 12,
17201
+ ledger.y + headerHeight + state.terms.length * rowHeight + fontSize,
17202
+ fontSize,
17203
+ revealTotal ? color : restColor
17204
+ );
17205
+ };
17206
+ if (options.totalTarget) target(options.totalTarget, result);
17207
+ else result();
17208
+ }, { padding: 4 });
17209
+ return { state, segments, endpoint: endpoint2 };
17210
+ };
17211
+ }
17212
+
17213
+ // src/teaching-categorical-sampling.ts
17214
+ function categoricalSampling(options) {
17215
+ if (options.normalization !== "probabilities" && options.normalization !== "weights") throw new Error("Sampling requires an explicit mass normalization contract");
17216
+ if (!options.categories.length) throw new Error("Sampling needs at least one category");
17217
+ const ids = /* @__PURE__ */ new Set();
17218
+ let total = 0;
17219
+ for (const category of options.categories) {
17220
+ if (!category.id || ids.has(category.id) || !category.label.trim()) throw new Error("Sampling category IDs must be unique and labels nonempty");
17221
+ if (!Number.isFinite(category.mass) || category.mass < 0) throw new Error("Sampling masses must be finite and nonnegative");
17222
+ ids.add(category.id);
17223
+ total += category.mass;
17224
+ }
17225
+ if (!Number.isFinite(total) || total <= 0) throw new Error("Sampling total mass must be finite and positive");
17226
+ if (options.normalization === "probabilities" && Math.abs(total - 1) > 1e-12) throw new Error("Sampling probabilities must sum to one within 1e-12");
17227
+ let cumulative = 0;
17228
+ let lastPositive = 0;
17229
+ options.categories.forEach((category, index) => {
17230
+ if (category.mass > 0) lastPositive = index;
17231
+ });
17232
+ const categories = options.categories.map((category, index) => {
17233
+ const lower = cumulative, probability = category.mass / total;
17234
+ cumulative = index === lastPositive ? 1 : Math.min(1, cumulative + probability);
17235
+ if (category.mass > 0 && (probability === 0 || cumulative <= lower)) throw new Error("Positive category is too small for cumulative floating-point precision");
17236
+ return { ...category, probability, lower, upper: cumulative, count: 0, empiricalProbability: null };
17237
+ });
17238
+ ids.clear();
17239
+ const draws = options.draws.map((draw) => {
17240
+ if (!draw.id || ids.has(draw.id)) throw new Error("Sampling draw IDs must be nonempty and unique");
17241
+ if (!Number.isFinite(draw.uniform) || draw.uniform < 0 || draw.uniform >= 1) throw new Error("Supplied uniform draws must be finite inside [0, 1)");
17242
+ ids.add(draw.id);
17243
+ const categoryIndex = categories.findIndex((category) => category.mass > 0 && draw.uniform >= category.lower && draw.uniform < category.upper);
17244
+ if (categoryIndex < 0) throw new Error("Supplied draw could not be represented by the normalized intervals");
17245
+ categories[categoryIndex].count += 1;
17246
+ return { ...draw, categoryId: categories[categoryIndex].id, categoryIndex };
17247
+ });
17248
+ if (draws.length) categories.forEach((category) => {
17249
+ category.empiricalProbability = category.count / draws.length;
17250
+ });
17251
+ return { inputTotal: total, normalization: options.normalization, categories, draws };
17252
+ }
17253
+ var COLORS2 = ["#79A6FF", "#FF8DC3", "#63DEEC", "#FFCE73", "#A6DF91"];
17254
+ function createTeachingCategoricalSampling(painter) {
17255
+ return (options) => {
17256
+ const model = categoricalSampling(options);
17257
+ const { x, y, width, height, fontSize = 28, color = "#DEE7F5", trackColor = "#18283B", visibleDraws = 0, drawProgress = 0, showEmpirical = false, formatProbability = (value) => value.toFixed(3) } = options;
17258
+ if (![x, y, x + width, y + height, fontSize].every(Number.isFinite) || fontSize <= 0 || width <= 0 || height <= 0) throw new Error("Sampling needs finite positive bounds and font size");
17259
+ if (!Number.isInteger(visibleDraws) || visibleDraws < 0 || visibleDraws > model.draws.length) throw new Error("Visible sample count must be an integer inside the supplied draw count");
17260
+ if (!Number.isFinite(drawProgress) || drawProgress < 0 || drawProgress > 1 || visibleDraws === model.draws.length && drawProgress !== 0) throw new Error("Sampling progress must be inside [0, 1] for an available next draw");
17261
+ if (showEmpirical && visibleDraws !== model.draws.length) throw new Error("Empirical reveal requires every supplied sample to be retained");
17262
+ const columns = options.columns ?? Math.max(1, Math.min(8, model.draws.length));
17263
+ if (!Number.isInteger(columns) || columns < 1) throw new Error("Sampling columns must be a positive integer");
17264
+ const railWidth = fontSize * 2, contentWidth = width - railWidth;
17265
+ const gap = fontSize * 0.5, cellWidth = (contentWidth - 4 - (columns - 1) * gap) / columns, cellHeight = fontSize * 1.9;
17266
+ const legendColumns = Math.min(3, model.categories.length), legendRows = Math.ceil(model.categories.length / legendColumns), legendHeight = legendRows * fontSize * 1.7;
17267
+ const bandY = y + fontSize * 4, bandHeight = fontSize * 1.3, legendY = bandY + bandHeight + fontSize * 1.5;
17268
+ const captionY = legendY + legendHeight + fontSize * 0.5, poolY = captionY + fontSize * 3.3, rows = Math.ceil(model.draws.length / columns), empiricalY = poolY + Math.max(1, rows) * (cellHeight + gap) + fontSize * 2;
17269
+ if (cellWidth < fontSize * 2 || contentWidth / legendColumns < fontSize * 5 || empiricalY + bandHeight + fontSize * 1.7 > y + height) throw new Error("Sampling bounds cannot fit probability labels, sample IDs and empirical strip");
17270
+ const inset = fontSize * 0.22 + 2, stripX = x + inset, stripWidth = contentWidth - inset * 2;
17271
+ const point = (u) => stripX + u * stripWidth;
17272
+ const categoryColor = (index) => model.categories[index].color ?? COLORS2[index % COLORS2.length];
17273
+ const target = (id, draw) => id && painter.target ? painter.target(id, draw) : draw();
17274
+ const label = (value, bounds4, align = "left", ink = color, size = fontSize) => painter.labelScope(bounds4, () => painter.text(value, align === "center" ? bounds4.x + bounds4.width / 2 : align === "right" ? bounds4.x + bounds4.width : bounds4.x, bounds4.y + size * 1.05, size, ink, align), { padding: 0 });
17275
+ const strip = (top, empirical) => {
17276
+ painter.rect(stripX, top, stripWidth, bandHeight, trackColor, void 0, 0);
17277
+ let cumulative = 0;
17278
+ model.categories.forEach((category, index) => {
17279
+ const probability = empirical ? category.empiricalProbability ?? 0 : category.probability;
17280
+ const left = cumulative;
17281
+ cumulative += probability;
17282
+ if (probability > 0) target(category.focusTarget, () => painter.rect(point(left), top, stripWidth * probability, bandHeight, categoryColor(index), void 0, 0));
17283
+ });
17284
+ };
17285
+ const sampleBounds = model.draws.map((_draw, index) => ({ x: x + 2 + index % columns * (cellWidth + gap), y: poolY + Math.floor(index / columns) * (cellHeight + gap), width: cellWidth, height: cellHeight }));
17286
+ const shapes = [];
17287
+ painter.container({ x, y, width, height }, () => {
17288
+ label(options.normalization === "weights" ? "Original probabilities \xB7 normalized supplied weights" : "Original probabilities \xB7 supplied distribution", { x, y, width: contentWidth, height: fontSize * 1.6 });
17289
+ strip(bandY, false);
17290
+ label("0", { x, y: bandY + bandHeight + 2, width: fontSize * 2, height: fontSize * 1.2 }, "left", color, fontSize * 0.8);
17291
+ label("1", { x: x + contentWidth - fontSize * 2, y: bandY + bandHeight + 2, width: fontSize * 2, height: fontSize * 1.2 }, "right", color, fontSize * 0.8);
17292
+ model.categories.forEach((category, index) => {
17293
+ const bounds4 = { x: x + index % legendColumns * contentWidth / legendColumns, y: legendY + Math.floor(index / legendColumns) * fontSize * 1.7, width: contentWidth / legendColumns - gap, height: fontSize * 1.5 };
17294
+ target(category.focusTarget, () => label(`${category.label}: ${formatProbability(category.probability)}`, bounds4, "left", categoryColor(index)));
17295
+ });
17296
+ label(`Supplied samples \xB7 ${visibleDraws} retained / ${model.draws.length}`, { x, y: poolY - fontSize * 1.8, width: contentWidth, height: fontSize * 1.5 });
17297
+ for (let index = 0; index < visibleDraws; index += 1) target(options.sampleFocusTarget, () => {
17298
+ const draw = model.draws[index], bounds4 = sampleBounds[index];
17299
+ shapes.push(painter.rect(bounds4.x, bounds4.y, bounds4.width, bounds4.height, trackColor, categoryColor(draw.categoryIndex), 4));
17300
+ label(draw.id, bounds4, "center", categoryColor(draw.categoryIndex));
17301
+ });
17302
+ if (drawProgress > 0 && visibleDraws < model.draws.length) target(options.sampleFocusTarget, () => {
17303
+ const draw = model.draws[visibleDraws], destination = sampleBounds[visibleDraws], landed = drawProgress >= 0.4;
17304
+ const from = { x: point(draw.uniform), y: bandY - fontSize * 1.2 }, onBand = { x: point(draw.uniform), y: bandY + bandHeight / 2 };
17305
+ const progress = landed ? (drawProgress - 0.4) / 0.6 : drawProgress / 0.4;
17306
+ const destinationPoint = { x: destination.x + destination.width / 2, y: destination.y + destination.height / 2 };
17307
+ const railX = x + width - inset;
17308
+ const route = landed ? [onBand, from, { x: railX, y: from.y }, { x: railX, y: destinationPoint.y }, destinationPoint] : [from, onBand];
17309
+ const lengths = route.slice(1).map((point2, index) => Math.hypot(point2.x - route[index].x, point2.y - route[index].y));
17310
+ let remaining = progress * lengths.reduce((sum, length) => sum + length, 0);
17311
+ let marker = route[route.length - 1];
17312
+ for (let index = 0; index < lengths.length; index += 1) {
17313
+ const length = lengths[index];
17314
+ if (remaining <= length && length > 0) {
17315
+ const ratio = remaining / length;
17316
+ marker = { x: route[index].x + (route[index + 1].x - route[index].x) * ratio, y: route[index].y + (route[index + 1].y - route[index].y) * ratio };
17317
+ break;
17318
+ }
17319
+ remaining -= length;
17320
+ }
17321
+ const ink = landed ? categoryColor(draw.categoryIndex) : color;
17322
+ painter.circle(marker.x, marker.y, fontSize * 0.22, ink, trackColor, 3);
17323
+ const caption = `${landed ? "Copy" : "Draw"} ${draw.id} \xB7 supplied u=${draw.uniform.toFixed(3)}`;
17324
+ label(caption, { x, y: captionY, width: contentWidth, height: fontSize * 1.3 }, "left", ink, fontSize * 0.8);
17325
+ });
17326
+ if (showEmpirical) {
17327
+ label(model.draws.length ? "Empirical frequencies \xB7 supplied sample only" : "No samples \xB7 empirical distribution undefined", { x, y: empiricalY - fontSize * 1.7, width: contentWidth, height: fontSize * 1.5 });
17328
+ if (model.draws.length) {
17329
+ strip(empiricalY, true);
17330
+ const text = model.categories.map((category) => `${category.label}: ${category.count}/${model.draws.length}`).join(" \xB7 ");
17331
+ label(text, { x, y: empiricalY + bandHeight + fontSize * 0.25, width: contentWidth, height: fontSize * 1.3 }, "left", color, fontSize * 0.8);
17332
+ }
17333
+ }
17334
+ }, { padding: 0 });
17335
+ return { model, sampleBounds, shapes, point, visibleDraws };
17336
+ };
17337
+ }
17338
+
17339
+ // src/teaching-routed-transfer.ts
17340
+ function finite5(value, name) {
17341
+ if (!Number.isFinite(value)) throw new Error(`${name} must be finite`);
17342
+ }
17343
+ function nonnegative3(value, name) {
17344
+ finite5(value, name);
17345
+ if (value < 0) throw new Error(`${name} must be nonnegative`);
17346
+ }
17347
+ function bounds3(value, name) {
17348
+ for (const field of ["x", "y", "width", "height"]) finite5(value[field], `${name} ${field}`);
17349
+ if (value.width <= 0 || value.height <= 0) throw new Error(`${name} dimensions must be positive`);
17350
+ finite5(value.x + value.width, `${name} right edge`);
17351
+ finite5(value.y + value.height, `${name} bottom edge`);
17352
+ }
17353
+ function identifier(id, name) {
17354
+ if (typeof id !== "string" || !id.trim()) throw new Error(`${name} must be a nonempty ID`);
17355
+ }
17356
+ function alpha2(value) {
17357
+ finite5(value, "Routed transfer opacity");
17358
+ return Math.max(0, Math.min(1, value));
17359
+ }
17360
+ function expanded(box2, clearance) {
17361
+ return { left: box2.x - clearance, top: box2.y - clearance, right: box2.x + box2.width + clearance, bottom: box2.y + box2.height + clearance };
17362
+ }
17363
+ function lengthOf(points) {
17364
+ let sum = 0;
17365
+ for (let i = 1; i < points.length; i++) sum += Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);
17366
+ return sum;
17367
+ }
17368
+ function trimLeads(points, amount2) {
17369
+ const length = lengthOf(points);
17370
+ if (length <= 2 * amount2) throw new Error("endpoint spacing leaves no positive-length clear transfer");
17371
+ const result = [pointAlongSamples(points, amount2 / length)];
17372
+ let distance = 0;
17373
+ for (let i = 1; i < points.length; i++) {
17374
+ distance += Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);
17375
+ if (distance > amount2 + 1e-6 && distance < length - amount2 - 1e-6) result.push(points[i]);
17376
+ }
17377
+ result.push(pointAlongSamples(points, 1 - amount2 / length));
17378
+ return result;
17379
+ }
17380
+ function parameters(options) {
17381
+ identifier(options.id, "Routed transfer ID");
17382
+ identifier(options.source.id, "Routed transfer source");
17383
+ identifier(options.target.id, "Routed transfer target");
17384
+ if (options.source.id === options.target.id) throw new Error("Routed transfer source and target IDs must differ");
17385
+ bounds3(options.source.shape, "Routed transfer source");
17386
+ bounds3(options.target.shape, "Routed transfer target");
17387
+ bounds3(options.corridor, "Routed transfer corridor");
17388
+ const ids = /* @__PURE__ */ new Set([options.source.id, options.target.id]);
17389
+ for (const obstacle of options.obstacles) {
17390
+ identifier(obstacle.id, "Routed transfer obstacle");
17391
+ if (ids.has(obstacle.id)) throw new Error(`Duplicate routed transfer object ID: ${obstacle.id}`);
17392
+ ids.add(obstacle.id);
17393
+ bounds3(obstacle.bounds, `Routed transfer obstacle ${obstacle.id}`);
17394
+ }
17395
+ const width = options.width ?? 3, margin = options.margin ?? 2;
17396
+ nonnegative3(width, "Routed transfer width");
17397
+ if (width === 0) throw new Error("Routed transfer width must be positive");
17398
+ nonnegative3(margin, "Routed transfer margin");
17399
+ if (options.progress !== void 0) finite5(options.progress, "Routed transfer progress");
17400
+ if (options.marker && options.progress === void 0) throw new Error("Routed transfer marker requires progress");
17401
+ const radius = options.marker?.radius ?? 7, strokeWidth = options.marker?.strokeWidth ?? 3;
17402
+ nonnegative3(radius, "Routed transfer marker radius");
17403
+ if (radius === 0) throw new Error("Routed transfer marker radius must be positive");
17404
+ nonnegative3(strokeWidth, "Routed transfer marker stroke width");
17405
+ const markerInk = options.progress === void 0 ? 0 : radius + (options.marker?.stroke ? strokeWidth / 2 : 0);
17406
+ const clearance = Math.max(width / 2, markerInk) + margin;
17407
+ const opacity = Math.min(alpha2(options.source.opacity), alpha2(options.target.opacity), alpha2(options.opacity ?? 1));
17408
+ return { width, margin, radius, strokeWidth, clearance, opacity };
17409
+ }
17410
+ function planTeachingRoutedTransfer(options) {
17411
+ const { clearance } = parameters(options);
17412
+ const fail = (reason) => {
17413
+ throw new Error(`Cannot route transfer ${options.id} (${options.source.id} \u2192 ${options.target.id}): ${reason}`);
17414
+ };
17415
+ const guard = clearance + 0.01, corridor = options.corridor;
17416
+ if (corridor.width <= 2 * guard || corridor.height <= 2 * guard) fail("corridor is too small for the requested ink clearance");
17417
+ const origin = { x: corridor.x + guard, y: corridor.y + guard };
17418
+ const toLocal = (shape) => {
17419
+ const x = shape.x - origin.x, y = shape.y - origin.y;
17420
+ finite5(x, "Routed transfer local x");
17421
+ finite5(y, "Routed transfer local y");
17422
+ return { x: Number(x.toFixed(6)), y: Number(y.toFixed(6)), width: shape.width, height: shape.height };
17423
+ };
17424
+ const endpoints = [options.source, options.target];
17425
+ const nodes = endpoints.map((endpoint2) => {
17426
+ const b = toLocal(endpoint2.shape);
17427
+ return { id: endpoint2.id, cx: b.x + b.width / 2, cy: b.y + b.height / 2, width: b.width, height: b.height };
17428
+ });
17429
+ const obstacles = options.obstacles.map((obstacle) => expanded(toLocal(obstacle.bounds), 0));
17430
+ const result = routeOrthogonalGraph(nodes, [{ from: options.source.id, to: options.target.id, fromSide: options.source.side, toSide: options.target.side }], corridor.width - 2 * guard, corridor.height - 2 * guard, guard, 14, obstacles);
17431
+ const raw = result.routes.get(0);
17432
+ if (!raw) return fail(result.failures[0]?.reason ?? "no legal route was returned");
17433
+ const points = (() => {
17434
+ try {
17435
+ return trimLeads(raw, guard).map((point) => ({ x: point.x + origin.x, y: point.y + origin.y }));
17436
+ } catch (error) {
17437
+ return fail(error instanceof Error ? error.message : String(error));
17438
+ }
17439
+ })();
17440
+ const occupied = [...endpoints.map((endpoint2) => expanded(endpoint2.shape, clearance)), ...options.obstacles.map((obstacle) => expanded(obstacle.bounds, clearance))];
17441
+ for (const point of points) {
17442
+ if (point.x < corridor.x + clearance || point.x > corridor.x + corridor.width - clearance || point.y < corridor.y + clearance || point.y > corridor.y + corridor.height - clearance) fail("route ink leaves the permitted corridor");
17443
+ }
17444
+ for (let i = 1; i < points.length; i++) {
17445
+ if (occupied.some((obstacle) => routingSegmentBlocked(points[i - 1], points[i], obstacle))) fail("a complete route segment violates object clearance");
17446
+ }
17447
+ const immutable = Object.freeze(points.map((point) => Object.freeze(point)));
17448
+ return {
17449
+ id: options.id,
17450
+ source: options.source,
17451
+ target: options.target,
17452
+ points: immutable,
17453
+ length: lengthOf(immutable),
17454
+ clearance,
17455
+ positionAt(progress) {
17456
+ finite5(progress, "Routed transfer progress");
17457
+ return pointAlongSamples(immutable, Math.max(0, Math.min(1, progress)));
17458
+ }
17459
+ };
17460
+ }
17461
+ function createTeachingRoutedTransfer(painter) {
17462
+ return (options) => {
17463
+ const { width, radius, strokeWidth, opacity } = parameters(options);
17464
+ if (opacity === 0) return null;
17465
+ const route = planTeachingRoutedTransfer(options), color = options.color ?? "#63DEEC";
17466
+ const paint = () => painter.opacity(opacity, () => {
17467
+ painter.path(route.points, { id: `${options.id}:route`, color, width });
17468
+ if (options.progress !== void 0 && options.progress > 0 && options.progress < 1) {
17469
+ const point = route.positionAt(options.progress);
17470
+ painter.circle(point.x, point.y, radius, options.marker?.fill ?? color, options.marker?.stroke, strokeWidth);
17471
+ }
17472
+ });
17473
+ if (painter.target) painter.target(options.focusTarget ?? options.id, paint);
17474
+ else paint();
17475
+ return route;
17476
+ };
17477
+ }
17478
+
17479
+ // src/teaching-byte-diff.ts
17480
+ function compareByteSequences(before, after) {
17481
+ if (!(before instanceof Uint8Array) || !(after instanceof Uint8Array)) {
17482
+ throw new Error("Byte comparison requires two Uint8Arrays");
17483
+ }
17484
+ const left = Array.from(before), right = Array.from(after);
17485
+ let commonPrefix = 0, commonSuffix = 0;
17486
+ while (commonPrefix < Math.min(left.length, right.length) && left[commonPrefix] === right[commonPrefix]) commonPrefix++;
17487
+ while (commonSuffix < Math.min(left.length, right.length) - commonPrefix && left[left.length - commonSuffix - 1] === right[right.length - commonSuffix - 1]) commonSuffix++;
17488
+ const columns = [];
17489
+ const add2 = (oldOffset, newOffset) => {
17490
+ const oldByte = oldOffset === null ? null : { offset: oldOffset, value: left[oldOffset] };
17491
+ const newByte = newOffset === null ? null : { offset: newOffset, value: right[newOffset] };
17492
+ const kind = !oldByte ? "insert" : !newByte ? "delete" : oldByte.value === newByte.value ? "equal" : "replace";
17493
+ columns.push({ id: `before:${oldOffset ?? "none"}|after:${newOffset ?? "none"}`, kind, before: oldByte, after: newByte });
17494
+ };
17495
+ for (let offset = 0; offset < commonPrefix; offset++) add2(offset, offset);
17496
+ const leftMiddle = left.length - commonPrefix - commonSuffix;
17497
+ const rightMiddle = right.length - commonPrefix - commonSuffix;
17498
+ for (let offset = 0; offset < Math.max(leftMiddle, rightMiddle); offset++) {
17499
+ add2(offset < leftMiddle ? commonPrefix + offset : null, offset < rightMiddle ? commonPrefix + offset : null);
17500
+ }
17501
+ for (let offset = 0; offset < commonSuffix; offset++) {
17502
+ add2(left.length - commonSuffix + offset, right.length - commonSuffix + offset);
17503
+ }
17504
+ return {
17505
+ algorithm: "common-prefix/suffix with positional middle",
17506
+ beforeLength: left.length,
17507
+ afterLength: right.length,
17508
+ commonPrefix,
17509
+ commonSuffix,
17510
+ equal: left.length === right.length && commonPrefix === left.length,
17511
+ columns
17512
+ };
17513
+ }
17514
+ function escapedByte(value) {
17515
+ if (!Number.isInteger(value) || value < 0 || value > 255) throw new Error("A byte must be an integer from 0 through 255");
17516
+ if (value === 0) return "\\0";
17517
+ if (value === 9) return "\\t";
17518
+ if (value === 10) return "\\n";
17519
+ if (value === 13) return "\\r";
17520
+ if (value === 32) return "space";
17521
+ if (value === 92) return "\\\\";
17522
+ if (value >= 33 && value <= 126) return String.fromCharCode(value);
17523
+ return `\\x${value.toString(16).padStart(2, "0").toUpperCase()}`;
17524
+ }
17525
+ function byteDifferenceState(options) {
17526
+ if (!Number.isFinite(options.scanProgress)) throw new Error("Byte scan progress must be finite");
17527
+ const comparison = compareByteSequences(options.before, options.after);
17528
+ const progress = Math.max(0, Math.min(1, options.scanProgress));
17529
+ const scannedColumns = Math.floor(progress * comparison.columns.length);
17530
+ return {
17531
+ comparison,
17532
+ progress,
17533
+ scannedColumns,
17534
+ scanComplete: progress === 1,
17535
+ verdict: options.revealVerdict ? comparison.equal ? "equal" : "different" : null
17536
+ };
17537
+ }
17538
+ function layoutByteDifference(options) {
17539
+ const { x, y, width, height, fontSize = 28, maxColumns = 10 } = options;
17540
+ if (![x, y, width, height, fontSize, x + width, y + height].every(Number.isFinite) || width <= 0 || height <= 0 || fontSize <= 0) {
17541
+ throw new Error("Byte strip bounds and font size must be finite with positive dimensions");
17542
+ }
17543
+ if (fontSize < 24) throw new Error("Byte strip font size must be at least 24 px for checked label padding");
17544
+ if (!Number.isSafeInteger(maxColumns) || maxColumns < 1) throw new Error("Byte window size must be a positive safe integer");
17545
+ const state = byteDifferenceState(options), all = state.comparison.columns;
17546
+ const start = options.startColumn ?? Math.max(0, state.comparison.commonPrefix - 2);
17547
+ if (!Number.isSafeInteger(start) || start < 0 || start > all.length || all.length > 0 && start === all.length) {
17548
+ throw new Error("Byte window start is outside the alignment");
17549
+ }
17550
+ const columns = all.slice(start, start + maxColumns), count = Math.max(1, columns.length);
17551
+ const gutter = fontSize * 5.2, cellWidth = (width - gutter) / count;
17552
+ const longest = Math.max(5, ...columns.flatMap((column) => [column.before, column.after].map((byte) => byte ? String(byte.offset).length + 1 : 5)));
17553
+ if (cellWidth < fontSize * 0.65 * longest + 12 || height < fontSize * 10) {
17554
+ throw new Error("Byte strip cannot fit its byte labels and offsets");
17555
+ }
17556
+ const headerHeight = fontSize * 1.7, footerHeight = fontSize * 1.7, rowHeight = (height - headerHeight - footerHeight) / 2;
17557
+ if (cellWidth <= 4 || rowHeight <= 4 || gutter - 8 <= 8 || headerHeight <= 8 || footerHeight <= 8 || rowHeight * 0.3 <= 8) {
17558
+ throw new Error("Byte strip cannot fit positive cell insets and checked label padding");
17559
+ }
17560
+ const cells = columns.map((column, index) => ({
17561
+ column,
17562
+ alignmentIndex: start + index,
17563
+ beforeBounds: { x: x + gutter + index * cellWidth, y: y + headerHeight, width: cellWidth, height: rowHeight },
17564
+ afterBounds: { x: x + gutter + index * cellWidth, y: y + headerHeight + rowHeight, width: cellWidth, height: rowHeight }
17565
+ }));
17566
+ return {
17567
+ ...state,
17568
+ bounds: { x, y, width, height },
17569
+ cells,
17570
+ gutter,
17571
+ headerHeight,
17572
+ footerHeight,
17573
+ rowHeight,
17574
+ omittedLeading: start,
17575
+ omittedTrailing: all.length - start - columns.length
17576
+ };
17577
+ }
17578
+ function createTeachingByteDifference(painter) {
17579
+ return (options) => {
17580
+ const layout = layoutByteDifference(options);
17581
+ const {
17582
+ x,
17583
+ y,
17584
+ width,
17585
+ height,
17586
+ fontSize = 28,
17587
+ fill = "#101820",
17588
+ stroke = "#516376",
17589
+ textColor = "#E9EFFF",
17590
+ mutedColor = "#91A3B8",
17591
+ scanColor = "#63DEEC",
17592
+ changeColor = "#F4D477",
17593
+ beforeLabel = "Before",
17594
+ afterLabel = "After"
17595
+ } = options;
17596
+ const label = (value, bounds4, size, color = textColor) => painter.labelScope(bounds4, () => {
17597
+ painter.text(value, bounds4.x + bounds4.width / 2, bounds4.y + bounds4.height / 2 + size * 0.34, size, color, "center", "mono");
17598
+ }, { padding: 4 });
17599
+ painter.container(layout.bounds, () => {
17600
+ label(
17601
+ "Prefix/suffix alignment; positional middle; not minimum edits",
17602
+ { x, y, width, height: layout.headerHeight },
17603
+ fontSize * 0.63,
17604
+ mutedColor
17605
+ );
17606
+ for (const [row, name] of [beforeLabel, afterLabel].entries()) {
17607
+ label(name, { x, y: y + layout.headerHeight + row * layout.rowHeight, width: layout.gutter - 8, height: layout.rowHeight }, fontSize * 0.72);
17608
+ }
17609
+ for (const cell of layout.cells) {
17610
+ const visited = cell.alignmentIndex < layout.scannedColumns;
17611
+ const color = visited ? cell.column.kind === "equal" ? mutedColor : changeColor : stroke;
17612
+ for (const [byte, bounds4] of [[cell.column.before, cell.beforeBounds], [cell.column.after, cell.afterBounds]]) {
17613
+ painter.rect(bounds4.x + 2, bounds4.y + 2, bounds4.width - 4, bounds4.height - 4, fill, color, 0);
17614
+ label(byte ? `@${byte.offset}` : "none", { ...bounds4, height: bounds4.height * 0.3 }, fontSize * 0.65, mutedColor);
17615
+ label(
17616
+ byte ? byte.value.toString(16).padStart(2, "0").toUpperCase() : "--",
17617
+ { ...bounds4, y: bounds4.y + bounds4.height * 0.3, height: bounds4.height * 0.35 },
17618
+ fontSize,
17619
+ visited ? textColor : mutedColor
17620
+ );
17621
+ label(
17622
+ byte ? escapedByte(byte.value) : "no byte",
17623
+ { ...bounds4, y: bounds4.y + bounds4.height * 0.65, height: bounds4.height * 0.35 },
17624
+ fontSize * 0.7,
17625
+ mutedColor
17626
+ );
17627
+ }
17628
+ }
17629
+ if (!layout.cells.length) {
17630
+ for (const row of [0, 1]) label("empty", {
17631
+ x: x + layout.gutter,
17632
+ y: y + layout.headerHeight + row * layout.rowHeight,
17633
+ width: width - layout.gutter,
17634
+ height: layout.rowHeight
17635
+ }, fontSize, mutedColor);
17636
+ }
17637
+ const scanPosition = layout.progress * layout.comparison.columns.length - layout.omittedLeading;
17638
+ if (layout.cells.length && scanPosition >= 0 && scanPosition <= layout.cells.length) {
17639
+ const cellWidth = layout.cells[0].beforeBounds.width;
17640
+ const cursor = Math.max(1, Math.min(width - layout.gutter - 1, scanPosition * cellWidth));
17641
+ painter.rect(
17642
+ x + layout.gutter + cursor - 1,
17643
+ y + layout.headerHeight - 7,
17644
+ 2,
17645
+ 5,
17646
+ scanColor,
17647
+ void 0,
17648
+ 0
17649
+ );
17650
+ }
17651
+ const verdict = layout.verdict === null ? "Verdict held" : layout.verdict === "equal" ? "Bytes equal" : "Bytes differ";
17652
+ label(
17653
+ `${layout.omittedLeading} columns before window; ${layout.omittedTrailing} after \xB7 ${verdict}`,
17654
+ { x, y: y + height - layout.footerHeight, width, height: layout.footerHeight },
17655
+ fontSize * 0.66,
17656
+ layout.verdict === null ? mutedColor : textColor
17657
+ );
17658
+ }, { padding: 0 });
17659
+ return layout;
17660
+ };
17661
+ }
17662
+
17663
+ // src/teaching-token-history.ts
17664
+ function tokens(input, name) {
17665
+ if (!Array.isArray(input)) throw new Error(`Token history ${name} must be an array`);
17666
+ return Object.freeze(input.map((item) => {
17667
+ if (!item || typeof item.id !== "string" || !item.id.trim() || item.id !== item.id.trim()) {
17668
+ throw new Error("Token occurrence IDs must be nonempty without surrounding whitespace");
17669
+ }
17670
+ if (!(typeof item.token === "string" && item.token.trim()) && !(typeof item.token === "number" && Number.isSafeInteger(item.token) && item.token >= 0)) {
17671
+ throw new Error("History tokens require nonempty text or a nonnegative safe integer vocabulary ID");
17672
+ }
17673
+ return Object.freeze({ id: item.id, token: item.token });
17674
+ }));
17675
+ }
17676
+ function equal(left, right) {
17677
+ return left.id === right.id && left.token === right.token;
17678
+ }
17679
+ function prefix(part, whole, name) {
17680
+ if (part.length > whole.length || part.some((token, index) => !equal(token, whole[index]))) {
17681
+ throw new Error(`Token history ${name} must preserve the exact ordered occurrence prefix`);
17682
+ }
17683
+ }
17684
+ function tokenHistoryState(options) {
17685
+ const prompt = tokens(options.prompt, "prompt"), accepted = tokens(options.accepted, "accepted");
17686
+ const processed = tokens(options.processed, "processed"), emitted = tokens(options.emitted, "emitted");
17687
+ const history = Object.freeze([...prompt, ...accepted]);
17688
+ if (new Set(history.map((token) => token.id)).size !== history.length) {
17689
+ throw new Error("Token history requires distinct occurrence IDs, including repeated vocabulary tokens");
17690
+ }
17691
+ prefix(processed, history, "processed");
17692
+ prefix(emitted, accepted, "emitted");
17693
+ if (accepted.length && processed.length < prompt.length) throw new Error("Accepted output requires the complete processed prompt");
17694
+ if (accepted.length && processed.length < prompt.length + accepted.length - 1) {
17695
+ throw new Error("Ordinary decoding permits at most one accepted token awaiting processing");
17696
+ }
17697
+ const phase = options.phase ?? "resident";
17698
+ if (!["resident", "dropped", "replay"].includes(phase)) throw new Error("Unknown token history phase");
17699
+ if (phase === "replay" && options.replayProgress === void 0) throw new Error("Replay requires explicit progress");
17700
+ const replayProgress = options.replayProgress ?? 0;
17701
+ if (!Number.isFinite(replayProgress) || replayProgress < 0 || replayProgress > 1) {
17702
+ throw new Error("Replay progress must be finite between zero and one");
17703
+ }
17704
+ const position2 = replayProgress * processed.length;
17705
+ const completed = phase === "resident" ? processed.length : phase === "dropped" ? 0 : Math.floor(position2);
17706
+ const fraction = position2 - Math.floor(position2);
17707
+ const moving = phase === "replay" && fraction > 0 && completed < processed.length ? Object.freeze({ token: processed[completed], position: completed, progress: fraction }) : null;
17708
+ return Object.freeze({
17709
+ prompt,
17710
+ accepted,
17711
+ processed,
17712
+ emitted,
17713
+ history,
17714
+ phase,
17715
+ replayProgress,
17716
+ kv: Object.freeze(processed.slice(0, completed)),
17717
+ pendingAccepted: Object.freeze(accepted.filter((_, index) => prompt.length + index >= processed.length)),
17718
+ moving
17719
+ });
17720
+ }
17721
+ function assertTokenHistoryTransition(before, after) {
17722
+ before = tokenHistoryState(before);
17723
+ after = tokenHistoryState(after);
17724
+ prefix(before.prompt, after.prompt, "prompt transition");
17725
+ if (before.prompt.length !== after.prompt.length) throw new Error("A request prompt cannot change during its history");
17726
+ prefix(before.accepted, after.accepted, "accepted transition");
17727
+ prefix(before.emitted, after.emitted, "emitted transition");
17728
+ if (before.phase !== "resident" || after.phase !== "resident") {
17729
+ if (before.accepted.length !== after.accepted.length || before.emitted.length !== after.emitted.length) {
17730
+ throw new Error("Drop and replay transitions cannot sample or emit new output");
17731
+ }
17732
+ prefix(before.processed, after.processed, "replay target");
17733
+ if (before.processed.length !== after.processed.length) throw new Error("Replay must rebuild the retained processed prefix");
17734
+ } else if (after.processed.length < before.processed.length) {
17735
+ throw new Error("Resident processed history cannot shrink without an explicit drop or replay");
17736
+ }
17737
+ }
17738
+ function createTeachingTokenHistory(painter) {
17739
+ return (options) => {
17740
+ const state = tokenHistoryState(options);
17741
+ const { x, y, width, height, fontSize = 28, gap = 8, labelWidth = 245, focusPrefix } = options;
17742
+ if (![x, y, x + width, y + height, width, height, fontSize, gap, labelWidth].every(Number.isFinite) || width <= 0 || height <= 0 || fontSize <= 0 || gap < 0 || labelWidth <= 0) {
17743
+ throw new Error("Token history drawing bounds and sizes must be finite and positive");
17744
+ }
17745
+ const columns = Math.max(1, state.history.length), top = fontSize * 1.9, bottom = fontSize * 2;
17746
+ const cellWidth = (width - labelWidth - gap * (columns - 1) - 4) / columns;
17747
+ const laneHeight = (height - top - bottom) / 5, cellHeight = laneHeight - gap;
17748
+ if (cellWidth < fontSize * 2.2 || cellHeight < fontSize * 1.6 || labelWidth < fontSize * 5) {
17749
+ throw new Error("Token history bounds must fit its occurrence columns and five readable lanes");
17750
+ }
17751
+ const color = {
17752
+ prompt: "#7FA7FF",
17753
+ accepted: "#92E28C",
17754
+ processed: "#63DEEC",
17755
+ kv: "#63DEEC",
17756
+ emitted: "#92E28C",
17757
+ pending: "#FFD75E",
17758
+ empty: "#586278",
17759
+ text: "#F2EFE6",
17760
+ fill: "#141820",
17761
+ ...options.colors
17762
+ };
17763
+ const lanes = [
17764
+ { id: "prompt", label: "Prompt", tokens: state.prompt, offset: 0 },
17765
+ { id: "accepted", label: "Accepted output", tokens: state.accepted, offset: state.prompt.length },
17766
+ { id: "processed", label: "Processed prefix", tokens: state.processed, offset: 0 },
17767
+ { id: "kv", label: "Resident KV", tokens: state.kv, offset: 0 },
17768
+ { id: "emitted", label: "Already delivered", tokens: state.emitted, offset: state.prompt.length }
17769
+ ];
17770
+ const pending = new Set(state.pendingAccepted.map((token) => token.id));
17771
+ const bounds4 = { x, y, width, height };
17772
+ const target = (id, draw) => {
17773
+ if (id && painter.target) painter.target(id, draw);
17774
+ else draw();
17775
+ };
17776
+ const cell = (position2, row) => ({
17777
+ x: x + labelWidth + 1 + position2 * (cellWidth + gap),
17778
+ y: y + top + row * laneHeight,
17779
+ width: cellWidth,
17780
+ height: cellHeight
17781
+ });
17782
+ const paintToken = (token, shape, stroke, fill = color.fill) => {
17783
+ painter.rect(shape.x, shape.y, shape.width, shape.height, fill, stroke, 7);
17784
+ painter.labelScope(shape, () => painter.text(
17785
+ String(token.token),
17786
+ shape.x + shape.width / 2,
17787
+ shape.y + shape.height / 2 + fontSize * 0.34,
17788
+ fontSize,
17789
+ color.text,
17790
+ "center",
17791
+ "mono"
17792
+ ), { padding: 5 });
17793
+ };
17794
+ painter.container(bounds4, () => {
17795
+ for (let position2 = 0; position2 < state.history.length; position2 += 1) {
17796
+ const shape = cell(position2, 0);
17797
+ painter.labelScope({ ...shape, y, height: top }, () => painter.text(
17798
+ `position ${position2}`,
17799
+ shape.x + shape.width / 2,
17800
+ y + fontSize,
17801
+ fontSize * 0.7,
17802
+ color.empty,
17803
+ "center"
17804
+ ), { padding: 3 });
17805
+ }
17806
+ lanes.forEach((lane, row) => target(focusPrefix ? `${focusPrefix}-${lane.id}` : void 0, () => {
17807
+ const labelBounds = { x, y: y + top + row * laneHeight, width: labelWidth - gap, height: cellHeight };
17808
+ painter.labelScope(labelBounds, () => painter.text(
17809
+ lane.label,
17810
+ x + 5,
17811
+ labelBounds.y + cellHeight / 2 + fontSize * 0.34,
17812
+ fontSize * 0.82,
17813
+ color[lane.id]
17814
+ ), { padding: 3 });
17815
+ for (let position2 = 0; position2 < columns; position2 += 1) {
17816
+ const shape = cell(position2, row), token = lane.tokens[position2 - lane.offset];
17817
+ if (token) {
17818
+ const isPending = lane.id === "accepted" && pending.has(token.id);
17819
+ target(
17820
+ isPending && focusPrefix ? `${focusPrefix}-pending` : void 0,
17821
+ () => paintToken(token, shape, isPending ? color.pending : color[lane.id], lane.id === "processed" ? "transparent" : color.fill)
17822
+ );
17823
+ } else painter.rect(shape.x, shape.y, shape.width, shape.height, "transparent", color.empty, 7);
17824
+ }
17825
+ }));
17826
+ if (state.moving) {
17827
+ const from = cell(state.moving.position, 2), to = cell(state.moving.position, 3);
17828
+ const progress = state.moving.progress;
17829
+ const settle = Math.max(0, (progress - 0.65) / 0.35);
17830
+ const grow = Math.max(0, (progress - 0.8) / 0.2);
17831
+ const copyWidth = Math.min(from.width, fontSize * 3);
17832
+ const copyHeight = Math.min(from.height, fontSize * 1.8);
17833
+ const movingWidth = copyWidth + (from.width - copyWidth) * grow;
17834
+ const movingHeight = copyHeight + (from.height - copyHeight) * grow;
17835
+ const startInset = Math.min(7, from.width - copyWidth);
17836
+ const startCenterX = from.x + startInset + copyWidth / 2;
17837
+ const centerX = startCenterX + (from.x + from.width / 2 - startCenterX) * settle;
17838
+ const centerY = from.y + from.height / 2 + (to.y - from.y) * progress;
17839
+ const moving = { x: centerX - movingWidth / 2, y: centerY - movingHeight / 2, width: movingWidth, height: movingHeight };
17840
+ target(focusPrefix ? `${focusPrefix}-replay` : void 0, () => paintToken(state.moving.token, moving, color.kv));
17841
+ }
17842
+ const pendingText = state.pendingAccepted.map((token) => String(token.token)).join(", ");
17843
+ const message = state.phase === "replay" ? "Replay rebuilds KV; no sampling or delivery" : state.phase === "dropped" ? "KV released; accepted and delivered history retained" : pendingText ? `Accepted but unprocessed: ${pendingText}` : "All accepted positions are processed";
17844
+ painter.labelScope({ x, y: y + height - bottom, width, height: bottom }, () => painter.text(
17845
+ message,
17846
+ x + width / 2,
17847
+ y + height - fontSize * 0.6,
17848
+ fontSize * 0.82,
17849
+ state.phase === "replay" ? color.kv : color.pending,
17850
+ "center"
17851
+ ), { padding: 3 });
17852
+ }, { padding: 0 });
17853
+ return state;
17854
+ };
17855
+ }
17856
+
17000
17857
  // src/teaching-canvas.ts
17001
17858
  var INK = "#8D9CB9";
17002
17859
  var ACCENT = "#63DEEC";
17003
17860
  var PANEL = "#18283B";
17004
- function finite4(value, name) {
17861
+ function finite6(value, name) {
17005
17862
  if (!Number.isFinite(value)) throw new Error(`${name} must be finite`);
17006
17863
  }
17007
- function positive4(value, name) {
17008
- finite4(value, name);
17864
+ function positive5(value, name) {
17865
+ finite6(value, name);
17009
17866
  if (value <= 0) throw new Error(`${name} must be positive`);
17010
17867
  }
17011
17868
  function boundsOf(options) {
17012
- finite4(options.x, "Teaching x");
17013
- finite4(options.y, "Teaching y");
17014
- positive4(options.width, "Teaching width");
17015
- positive4(options.height, "Teaching height");
17869
+ finite6(options.x, "Teaching x");
17870
+ finite6(options.y, "Teaching y");
17871
+ positive5(options.width, "Teaching width");
17872
+ positive5(options.height, "Teaching height");
17016
17873
  return { x: options.x, y: options.y, width: options.width, height: options.height };
17017
17874
  }
17018
17875
  function amount(value, name = "Teaching progress") {
17019
- finite4(value, name);
17876
+ finite6(value, name);
17020
17877
  return Math.max(0, Math.min(1, value));
17021
17878
  }
17022
17879
  function domainOf(domain, name) {
17023
- finite4(domain[0], `${name} start`);
17024
- finite4(domain[1], `${name} end`);
17880
+ finite6(domain[0], `${name} start`);
17881
+ finite6(domain[1], `${name} end`);
17025
17882
  if (domain[1] <= domain[0] || !Number.isFinite(domain[1] - domain[0])) {
17026
17883
  throw new Error(`${name} must have a finite positive span`);
17027
17884
  }
@@ -17030,54 +17887,54 @@ function domainOf(domain, name) {
17030
17887
  function createTeachingCanvas(painter) {
17031
17888
  const components = createCanvasComponents(painter);
17032
17889
  function axes(options) {
17033
- let bounds2 = boundsOf(options);
17890
+ let bounds4 = boundsOf(options);
17034
17891
  const xDomain = domainOf(options.xDomain, "Plot x domain");
17035
17892
  const yDomain = domainOf(options.yDomain, "Plot y domain");
17036
17893
  if (options.equalUnits) {
17037
17894
  const xSpan = xDomain[1] - xDomain[0];
17038
17895
  const ySpan = yDomain[1] - yDomain[0];
17039
- const pixelsPerUnit = Math.min(bounds2.width / xSpan, bounds2.height / ySpan);
17896
+ const pixelsPerUnit = Math.min(bounds4.width / xSpan, bounds4.height / ySpan);
17040
17897
  const width2 = xSpan * pixelsPerUnit;
17041
17898
  const height2 = ySpan * pixelsPerUnit;
17042
- bounds2 = boundsOf({
17043
- x: bounds2.x + (bounds2.width - width2) / 2,
17044
- y: bounds2.y + (bounds2.height - height2) / 2,
17899
+ bounds4 = boundsOf({
17900
+ x: bounds4.x + (bounds4.width - width2) / 2,
17901
+ y: bounds4.y + (bounds4.height - height2) / 2,
17045
17902
  width: width2,
17046
17903
  height: height2
17047
17904
  });
17048
17905
  }
17049
- const { x, y, width, height } = bounds2;
17906
+ const { x, y, width, height } = bounds4;
17050
17907
  const { color = INK, gridColor, fontSize = 28, xTicks = [], yTicks = [], formatX = String, formatY = String } = options;
17051
- positive4(fontSize, "Axis font size");
17052
- xTicks.forEach((tick) => finite4(tick, "Axis x tick"));
17053
- yTicks.forEach((tick) => finite4(tick, "Axis y tick"));
17908
+ positive5(fontSize, "Axis font size");
17909
+ xTicks.forEach((tick) => finite6(tick, "Axis x tick"));
17910
+ yTicks.forEach((tick) => finite6(tick, "Axis y tick"));
17054
17911
  const plot = {
17055
- bounds: bounds2,
17912
+ bounds: bounds4,
17056
17913
  xDomain,
17057
17914
  yDomain,
17058
17915
  point(px, py) {
17059
- finite4(px, "Plot point x");
17060
- finite4(py, "Plot point y");
17916
+ finite6(px, "Plot point x");
17917
+ finite6(py, "Plot point y");
17061
17918
  const point = {
17062
17919
  x: x + (px - xDomain[0]) / (xDomain[1] - xDomain[0]) * width,
17063
17920
  y: y + height - (py - yDomain[0]) / (yDomain[1] - yDomain[0]) * height
17064
17921
  };
17065
- finite4(point.x, "Mapped point x");
17066
- finite4(point.y, "Mapped point y");
17922
+ finite6(point.x, "Mapped point x");
17923
+ finite6(point.y, "Mapped point y");
17067
17924
  return point;
17068
17925
  }
17069
17926
  };
17070
17927
  for (const tick of xTicks) {
17071
17928
  if (tick < xDomain[0] || tick > xDomain[1]) continue;
17072
17929
  const point = plot.point(tick, yDomain[0]);
17073
- if (gridColor) painter.path([{ x: point.x, y }, { x: point.x, y: y + height }], { color: gridColor, width: 1, clip: bounds2 });
17930
+ if (gridColor) painter.path([{ x: point.x, y }, { x: point.x, y: y + height }], { color: gridColor, width: 1, clip: bounds4 });
17074
17931
  painter.line(point.x, y + height, point.x, y + height + 7, color, 2);
17075
17932
  painter.text(formatX(tick), point.x, y + height + 36, fontSize, color, "center");
17076
17933
  }
17077
17934
  for (const tick of yTicks) {
17078
17935
  if (tick < yDomain[0] || tick > yDomain[1]) continue;
17079
17936
  const point = plot.point(xDomain[0], tick);
17080
- if (gridColor) painter.path([{ x, y: point.y }, { x: x + width, y: point.y }], { color: gridColor, width: 1, clip: bounds2 });
17937
+ if (gridColor) painter.path([{ x, y: point.y }, { x: x + width, y: point.y }], { color: gridColor, width: 1, clip: bounds4 });
17081
17938
  painter.line(x - 7, point.y, x, point.y, color, 2);
17082
17939
  painter.text(formatY(tick), x - 18, point.y + 9, fontSize, color, "right");
17083
17940
  }
@@ -17089,7 +17946,7 @@ function createTeachingCanvas(painter) {
17089
17946
  }
17090
17947
  function curve(options) {
17091
17948
  const { plot, points, color, width = 4, progress = 1 } = options;
17092
- positive4(width, "Curve width");
17949
+ positive5(width, "Curve width");
17093
17950
  const mapped = points.map((point) => plot.point(point.x, point.y));
17094
17951
  const visible = tracePolyline(mapped, progress);
17095
17952
  if (visible.length > 1) painter.path(visible, { color, width, clip: plot.bounds });
@@ -17097,10 +17954,10 @@ function createTeachingCanvas(painter) {
17097
17954
  }
17098
17955
  function scatter(options) {
17099
17956
  const { plot, points, color = ACCENT, radius = 7, opacity = 1 } = options;
17100
- positive4(radius, "Scatter radius");
17101
- const alpha2 = amount(opacity, "Scatter opacity");
17957
+ positive5(radius, "Scatter radius");
17958
+ const alpha3 = amount(opacity, "Scatter opacity");
17102
17959
  const projected = points.map((point) => {
17103
- positive4(point.radius ?? radius, "Scatter point radius");
17960
+ positive5(point.radius ?? radius, "Scatter point radius");
17104
17961
  return {
17105
17962
  ...plot.point(point.x, point.y),
17106
17963
  radius: point.radius ?? radius,
@@ -17109,8 +17966,8 @@ function createTeachingCanvas(painter) {
17109
17966
  };
17110
17967
  });
17111
17968
  const shapes = [];
17112
- if (alpha2 === 0) return shapes;
17113
- painter.opacity(alpha2, () => {
17969
+ if (alpha3 === 0) return shapes;
17970
+ painter.opacity(alpha3, () => {
17114
17971
  for (const point of projected) {
17115
17972
  if (!point.inDomain) continue;
17116
17973
  shapes.push(painter.circle(point.x, point.y, point.radius, point.color));
@@ -17119,26 +17976,26 @@ function createTeachingCanvas(painter) {
17119
17976
  return shapes;
17120
17977
  }
17121
17978
  function bars(options) {
17122
- const bounds2 = boundsOf(options);
17123
- const { x, y, width, height } = bounds2;
17979
+ const bounds4 = boundsOf(options);
17980
+ const { x, y, width, height } = bounds4;
17124
17981
  const { values, labels, colors: colors2, color = ACCENT, progress = 1, showValues = false, format = String, fontSize = 28, gap = 20 } = options;
17125
- positive4(fontSize, "Bar font size");
17126
- finite4(gap, "Bar gap");
17982
+ positive5(fontSize, "Bar font size");
17983
+ finite6(gap, "Bar gap");
17127
17984
  if (gap < 0) throw new Error("Bar gap must be nonnegative");
17128
17985
  values.forEach((value) => {
17129
- finite4(value, "Bar value");
17986
+ finite6(value, "Bar value");
17130
17987
  if (value < 0) throw new Error("Bar values must be nonnegative");
17131
17988
  });
17132
17989
  if (labels && labels.length !== values.length) throw new Error("Bar labels must match values");
17133
17990
  if (colors2 && colors2.length !== values.length) throw new Error("Bar colors must match values");
17134
17991
  const maximumValue = values.reduce((maximum2, value) => Math.max(maximum2, value), 0);
17135
17992
  const maximum = options.max ?? (maximumValue || 1);
17136
- positive4(maximum, "Bar maximum");
17993
+ positive5(maximum, "Bar maximum");
17137
17994
  if (maximum < maximumValue) throw new Error("Bar maximum must contain every value");
17138
17995
  const reveal = amount(progress);
17139
- if (!values.length) return { bars: [], slots: [], bounds: bounds2 };
17996
+ if (!values.length) return { bars: [], slots: [], bounds: bounds4 };
17140
17997
  const barWidth = (width - gap * (values.length - 1)) / values.length;
17141
- positive4(barWidth, "Bar width after gaps");
17998
+ positive5(barWidth, "Bar width after gaps");
17142
17999
  const shapes = [];
17143
18000
  const slots = [];
17144
18001
  values.forEach((value, index) => {
@@ -17149,28 +18006,28 @@ function createTeachingCanvas(painter) {
17149
18006
  if (labels) painter.text(labels[index], left + barWidth / 2, y + height + 38, fontSize, INK, "center");
17150
18007
  if (showValues && reveal > 0) painter.text(format(value), left + barWidth / 2, y + height - barHeight - 14, fontSize, colors2?.[index] ?? color, "center");
17151
18008
  });
17152
- return { bars: shapes, slots, bounds: bounds2 };
18009
+ return { bars: shapes, slots, bounds: bounds4 };
17153
18010
  }
17154
18011
  function flowGraph(options) {
17155
18012
  const { nodes, edges, stroke = ACCENT, fill = PANEL, textColor = "#FFFFFF", padding = 12 } = options;
17156
- finite4(padding, "Flow node padding");
18013
+ finite6(padding, "Flow node padding");
17157
18014
  if (padding < 0) throw new Error("Flow node padding must be nonnegative");
17158
18015
  const descriptors = /* @__PURE__ */ Object.create(null);
17159
18016
  for (const node of nodes) {
17160
18017
  if (!node.id || Object.hasOwn(descriptors, node.id)) throw new Error("Flow node IDs must be nonempty and unique");
17161
- const bounds2 = boundsOf(node);
17162
- positive4(node.fontSize ?? 30, "Flow node font size");
17163
- finite4(node.radius ?? 14, "Flow node radius");
18018
+ const bounds4 = boundsOf(node);
18019
+ positive5(node.fontSize ?? 30, "Flow node font size");
18020
+ finite6(node.radius ?? 14, "Flow node radius");
17164
18021
  if ((node.radius ?? 14) < 0) throw new Error("Flow node radius must be nonnegative");
17165
- descriptors[node.id] = { ...bounds2, radius: node.radius ?? 14 };
18022
+ descriptors[node.id] = { ...bounds4, radius: node.radius ?? 14 };
17166
18023
  }
17167
18024
  for (const edge of edges) {
17168
18025
  if (!Object.hasOwn(descriptors, edge.from) || !Object.hasOwn(descriptors, edge.to)) throw new Error("Flow edge must reference existing nodes");
17169
18026
  if (edge.from === edge.to) throw new Error("Flow edges must connect distinct nodes");
17170
18027
  if (edge.progress !== void 0) amount(edge.progress);
17171
- if (edge.width !== void 0) positive4(edge.width, "Flow edge width");
18028
+ if (edge.width !== void 0) positive5(edge.width, "Flow edge width");
17172
18029
  for (const gap of [edge.gap, edge.fromGap, edge.toGap]) {
17173
- if (gap !== void 0) finite4(gap, "Flow edge gap");
18030
+ if (gap !== void 0) finite6(gap, "Flow edge gap");
17174
18031
  }
17175
18032
  }
17176
18033
  const target = (id, draw) => id && painter.target ? painter.target(id, draw) : draw();
@@ -17195,7 +18052,24 @@ function createTeachingCanvas(painter) {
17195
18052
  }
17196
18053
  return { nodes: descriptors, routes };
17197
18054
  }
17198
- return { axes, curve, scatter, bars, flowGraph, transfer: createTeachingTransfer(painter), grid: createTeachingGrid(painter), timeline: createTeachingTimeline(painter), allocation: createTeachingAllocation(painter), ...createTeachingValueChange(painter), ...createTeachingFocus(painter) };
18055
+ return {
18056
+ axes,
18057
+ curve,
18058
+ scatter,
18059
+ bars,
18060
+ flowGraph,
18061
+ transfer: createTeachingTransfer(painter),
18062
+ routedTransfer: createTeachingRoutedTransfer(painter),
18063
+ grid: createTeachingGrid(painter),
18064
+ timeline: createTeachingTimeline(painter),
18065
+ allocation: createTeachingAllocation(painter),
18066
+ vectorAccumulation: createTeachingVectorAccumulation(painter),
18067
+ categoricalSampling: createTeachingCategoricalSampling(painter),
18068
+ byteDifference: createTeachingByteDifference(painter),
18069
+ tokenHistory: createTeachingTokenHistory(painter),
18070
+ ...createTeachingValueChange(painter),
18071
+ ...createTeachingFocus(painter)
18072
+ };
17199
18073
  }
17200
18074
 
17201
18075
  // src/teaching-cues.ts
@@ -17623,6 +18497,7 @@ async function renderRgbaVideo(renderFrame2, options) {
17623
18497
  } else {
17624
18498
  args.push("-c:v", "libx264", "-preset", preset);
17625
18499
  if (options.tune) args.push("-tune", options.tune);
18500
+ if (options.tune === "animation" || /slow|placebo/.test(preset)) args.push("-refs", "4");
17626
18501
  args.push("-crf", String(crf), "-threads:v", String(threads));
17627
18502
  }
17628
18503
  args.push("-pix_fmt", "yuv420p", ...COLOR_TAGS);
@@ -18118,7 +18993,7 @@ function integer(value, name, min, max) {
18118
18993
  }
18119
18994
  return value;
18120
18995
  }
18121
- function finite5(value, name) {
18996
+ function finite7(value, name) {
18122
18997
  if (typeof value !== "number" || !Number.isFinite(value) || Math.abs(value) > 32768) {
18123
18998
  throw new Error(`Editable scene ${name} must be finite and within 32768 canvas units.`);
18124
18999
  }
@@ -18138,7 +19013,7 @@ function validateSceneComponentProps(name, props) {
18138
19013
  const check = (value, key) => {
18139
19014
  if (++values > 8192) throw new Error(`Editable scene ${name} props exceed their value budget.`);
18140
19015
  if (typeof value === "number") {
18141
- if (/^(?:width|height|x|y|x1|y1|x2|y2|cx|cy|r|rx|ry|radius|length|padding|gap|nodeWidth|nodeHeight|cellSize|cellWidth|cellHeight|fontSize|nodeSize|tileWidth|minHeight)$/i.test(key)) finite5(value, `${name}.${key}`);
19016
+ if (/^(?:width|height|x|y|x1|y1|x2|y2|cx|cy|r|rx|ry|radius|length|padding|gap|nodeWidth|nodeHeight|cellSize|cellWidth|cellHeight|fontSize|nodeSize|tileWidth|minHeight)$/i.test(key)) finite7(value, `${name}.${key}`);
18142
19017
  if (/^(?:rows|cols|columns|count|repeat|gridCount|tickCount)$/i.test(key)) integer(value, `${name}.${key}`, key === "gridCount" ? 0 : 1, 2e3);
18143
19018
  }
18144
19019
  if (Array.isArray(value)) value.forEach((item) => check(item, ""));
@@ -18148,8 +19023,8 @@ function validateSceneComponentProps(name, props) {
18148
19023
  };
18149
19024
  Object.entries(props).forEach(([key, value]) => check(value, key));
18150
19025
  if (name === "DashedLine") {
18151
- const x1 = finite5(props.x1, "DashedLine.x1"), y1 = finite5(props.y1, "DashedLine.y1");
18152
- const x2 = finite5(props.x2, "DashedLine.x2"), y2 = finite5(props.y2, "DashedLine.y2");
19026
+ const x1 = finite7(props.x1, "DashedLine.x1"), y1 = finite7(props.y1, "DashedLine.y1");
19027
+ const x2 = finite7(props.x2, "DashedLine.x2"), y2 = finite7(props.y2, "DashedLine.y2");
18153
19028
  const spacing = props.dotSpacing ?? 8;
18154
19029
  if (typeof spacing !== "number" || !Number.isFinite(spacing) || spacing <= 0 || Math.hypot(x2 - x1, y2 - y1) / spacing > 2e3) {
18155
19030
  throw new Error("Editable scene DashedLine requires positive dotSpacing and at most 2000 dots.");
@@ -19419,13 +20294,13 @@ function colorFromCss(value) {
19419
20294
  }
19420
20295
  function compositeOver(foreground, background) {
19421
20296
  if (foreground.alpha >= 1 || !background) return foreground;
19422
- const alpha2 = foreground.alpha + background.alpha * (1 - foreground.alpha);
19423
- if (alpha2 <= 0) return { r: 0, g: 0, b: 0, alpha: 0 };
20297
+ const alpha3 = foreground.alpha + background.alpha * (1 - foreground.alpha);
20298
+ if (alpha3 <= 0) return { r: 0, g: 0, b: 0, alpha: 0 };
19424
20299
  return {
19425
- r: (foreground.r * foreground.alpha + background.r * background.alpha * (1 - foreground.alpha)) / alpha2,
19426
- g: (foreground.g * foreground.alpha + background.g * background.alpha * (1 - foreground.alpha)) / alpha2,
19427
- b: (foreground.b * foreground.alpha + background.b * background.alpha * (1 - foreground.alpha)) / alpha2,
19428
- alpha: alpha2
20300
+ r: (foreground.r * foreground.alpha + background.r * background.alpha * (1 - foreground.alpha)) / alpha3,
20301
+ g: (foreground.g * foreground.alpha + background.g * background.alpha * (1 - foreground.alpha)) / alpha3,
20302
+ b: (foreground.b * foreground.alpha + background.b * background.alpha * (1 - foreground.alpha)) / alpha3,
20303
+ alpha: alpha3
19429
20304
  };
19430
20305
  }
19431
20306
  function isUnresolvedColor(value) {
@@ -19815,12 +20690,12 @@ function analyzeRenderedLayout(nodes, theme) {
19815
20690
  }
19816
20691
  return diagnostics;
19817
20692
  }
19818
- function analyzeWhitespaceBalance(bounds2, width, height, theme) {
20693
+ function analyzeWhitespaceBalance(bounds4, width, height, theme) {
19819
20694
  const gutters = {
19820
- left: bounds2.x,
19821
- right: width - bounds2.x - bounds2.width,
19822
- top: bounds2.y,
19823
- bottom: height - bounds2.y - bounds2.height
20695
+ left: bounds4.x,
20696
+ right: width - bounds4.x - bounds4.width,
20697
+ top: bounds4.y,
20698
+ bottom: height - bounds4.y - bounds4.height
19824
20699
  };
19825
20700
  const diagnostics = [];
19826
20701
  const horizontalDifference = Math.abs(gutters.left - gutters.right);
@@ -19832,7 +20707,7 @@ function analyzeWhitespaceBalance(bounds2, width, height, theme) {
19832
20707
  theme,
19833
20708
  message: `Horizontal gutters differ by ${Math.round(horizontalDifference)}px (${Math.round(gutters.left)}px left, ${Math.round(gutters.right)}px right).`,
19834
20709
  suggestion: "Recenter the composition, crop the canvas, or use the open space intentionally.",
19835
- location: { x: bounds2.x, y: bounds2.y, width: bounds2.width, height: bounds2.height }
20710
+ location: { x: bounds4.x, y: bounds4.y, width: bounds4.width, height: bounds4.height }
19836
20711
  });
19837
20712
  }
19838
20713
  if (verticalDifference > 48 && verticalDifference / height > 0.12) {
@@ -19842,7 +20717,7 @@ function analyzeWhitespaceBalance(bounds2, width, height, theme) {
19842
20717
  theme,
19843
20718
  message: `Vertical gutters differ by ${Math.round(verticalDifference)}px (${Math.round(gutters.top)}px top, ${Math.round(gutters.bottom)}px bottom).`,
19844
20719
  suggestion: "Recenter the composition, crop the canvas, or use the open space intentionally.",
19845
- location: { x: bounds2.x, y: bounds2.y, width: bounds2.width, height: bounds2.height }
20720
+ location: { x: bounds4.x, y: bounds4.y, width: bounds4.width, height: bounds4.height }
19846
20721
  });
19847
20722
  }
19848
20723
  return diagnostics;
@@ -20312,19 +21187,28 @@ async function checkFrame(input, options = {}) {
20312
21187
  analyzeAnimationCadence,
20313
21188
  arcSwap,
20314
21189
  assertDensity,
21190
+ assertTokenHistoryTransition,
21191
+ byteDifferenceState,
20315
21192
  cameraSvgTransform,
20316
21193
  canvas,
21194
+ categoricalSampling,
20317
21195
  checkFrame,
20318
21196
  colors,
21197
+ compareByteSequences,
20319
21198
  compositeColor,
20320
21199
  createCanvasComponents,
20321
21200
  createCueTrack,
20322
21201
  createFocusDirector,
20323
21202
  createPlotArea,
20324
21203
  createPolylineMorph,
21204
+ createTeachingByteDifference,
20325
21205
  createTeachingCanvas,
21206
+ createTeachingCategoricalSampling,
20326
21207
  createTeachingFocus,
21208
+ createTeachingRoutedTransfer,
21209
+ createTeachingTokenHistory,
20327
21210
  createTeachingValueChange,
21211
+ createTeachingVectorAccumulation,
20328
21212
  cropPixels,
20329
21213
  cropRgbImage,
20330
21214
  cropRgbRaster,
@@ -20343,6 +21227,7 @@ async function checkFrame(input, options = {}) {
20343
21227
  dotProduct,
20344
21228
  encodeRgbPng,
20345
21229
  entropy,
21230
+ escapedByte,
20346
21231
  estimateTextWidth,
20347
21232
  evaluateSceneSource,
20348
21233
  flattenRgbImage,
@@ -20372,6 +21257,7 @@ async function checkFrame(input, options = {}) {
20372
21257
  interpolateCamera,
20373
21258
  keyframe,
20374
21259
  layoutAllocation,
21260
+ layoutByteDifference,
20375
21261
  layoutCellGrid,
20376
21262
  layoutTokenRow,
20377
21263
  lerpArray,
@@ -20384,6 +21270,7 @@ async function checkFrame(input, options = {}) {
20384
21270
  normalizeWatermark,
20385
21271
  parallel,
20386
21272
  parseDensity,
21273
+ planTeachingRoutedTransfer,
20387
21274
  pointAlongPath,
20388
21275
  prepareScene,
20389
21276
  projectWorldPoint,
@@ -20418,6 +21305,7 @@ async function checkFrame(input, options = {}) {
20418
21305
  statusColor,
20419
21306
  styles,
20420
21307
  sumForces,
21308
+ tokenHistoryState,
20421
21309
  toneGradients,
20422
21310
  tracePolyline,
20423
21311
  transposeMatrix,
@@ -20427,6 +21315,7 @@ async function checkFrame(input, options = {}) {
20427
21315
  valueChangeState,
20428
21316
  videoFrameSchedule,
20429
21317
  waveValue,
21318
+ weightedVectorState,
20430
21319
  withColorAlpha,
20431
21320
  withDensity,
20432
21321
  wrapWithBrand,