briyah 2.0.14 → 2.0.16

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 (31) hide show
  1. package/README.md +48 -0
  2. package/dist-sdk/server/src/app.controller.d.ts +4 -0
  3. package/dist-sdk/server/src/app.controller.js +4 -2
  4. package/dist-sdk/server/src/app.service.d.ts +15 -2
  5. package/dist-sdk/server/src/app.service.js +30 -2
  6. package/dist-sdk/server/src/charts/chart-svg.d.ts +24 -0
  7. package/dist-sdk/server/src/charts/chart-svg.js +415 -0
  8. package/dist-sdk/server/src/charts/chart-validation.d.ts +28 -0
  9. package/dist-sdk/server/src/charts/chart-validation.js +129 -0
  10. package/dist-sdk/server/src/charts/chart.types.d.ts +60 -0
  11. package/dist-sdk/server/src/charts/chart.types.js +27 -0
  12. package/dist-sdk/server/src/packs/pack-instantiation.service.js +1 -0
  13. package/dist-sdk/server/src/packs/pack-manifest.d.ts +6 -0
  14. package/dist-sdk/server/src/packs/pack-manifest.js +3 -0
  15. package/dist-sdk/server/src/room/room-clock.d.ts +27 -0
  16. package/dist-sdk/server/src/room/room-clock.js +51 -0
  17. package/dist-sdk/server/src/room/room-config.d.ts +8 -0
  18. package/dist-sdk/server/src/room/room-store.service.js +4 -0
  19. package/dist-sdk/server/src/room/room.d.ts +16 -5
  20. package/dist-sdk/server/src/room/room.js +32 -5
  21. package/dist-sdk/server/src/sdk/index.d.ts +5 -0
  22. package/dist-sdk/server/src/sdk/index.js +10 -1
  23. package/dist-sdk/server/src/tools/core/chart.tool.d.ts +15 -0
  24. package/dist-sdk/server/src/tools/core/chart.tool.js +83 -0
  25. package/dist-sdk/server/src/tools/core/data.tools.d.ts +14 -2
  26. package/dist-sdk/server/src/tools/core/data.tools.js +31 -4
  27. package/dist-sdk/server/src/tools/core/index.js +2 -0
  28. package/dist-sdk/server/src/tools/shared/coerce.d.ts +7 -0
  29. package/dist-sdk/server/src/tools/shared/coerce.js +17 -0
  30. package/dist-sdk/shared/types/app.types.d.ts +5 -0
  31. package/package.json +1 -1
package/README.md CHANGED
@@ -1395,6 +1395,54 @@ current scene, and it is built for stories: it decides whether a picture is warr
1395
1395
  setting before the moment, and gives each named character a portrait. Use it for a story-like
1396
1396
  room, and `create_image` for an agent asked to make a picture of something.
1397
1397
 
1398
+ ### Example 15: Telling a room's agents today's date
1399
+
1400
+ A model does not know the date. Asked about "this year" it guesses from the newest thing it has
1401
+ seen. A room that works in the present names a time zone, and every turn its agents take opens
1402
+ with the date and time there — `Today is Monday, November 2, 2026; the time is 9:58 PM
1403
+ (America/Chicago).` — in the uncached per-turn prompt, so it costs no cache.
1404
+
1405
+ ```typescript
1406
+ const { roomId } = await app.createRoom(
1407
+ 'Assistant', goal, agentIds, 'Lisa', 'directed',
1408
+ undefined, undefined, undefined, undefined, undefined,
1409
+ 'America/Chicago', // timeZone: any IANA name
1410
+ );
1411
+ ```
1412
+
1413
+ Leave it out for a story or campaign, which keeps its own clock (the room's situation time).
1414
+ `editRoom` takes it in the same place; an empty string stops it, and a name the runtime does not
1415
+ know is refused with a `ValidationError`. Room Settings has it as "Tell the agents today's date",
1416
+ and a pack room template as `timeZone`.
1417
+
1418
+ ### Example 16: Letting an agent make charts
1419
+
1420
+ Grant the core tool `make_chart`. The agent describes a chart as data — a line, column, bar,
1421
+ stacked column or pie, its categories and one value per category in each series — and gets back
1422
+ a `block` to put in its message or document:
1423
+
1424
+ ````
1425
+ ```chart
1426
+ {"type":"line","title":"Fleet miles by quarter","categories":["2025 Q1","2025 Q2"],"series":[{"name":"Fleet miles","values":[970269,1007320]}]}
1427
+ ```
1428
+ ````
1429
+
1430
+ The host draws each block wherever it shows the agent's markdown:
1431
+
1432
+ ```typescript
1433
+ import { validateChart, renderChartSvg, CHART_BLOCK_LANGUAGE } from 'briyah';
1434
+
1435
+ // e.g. a marked renderer: code({ text, lang }) for lang === CHART_BLOCK_LANGUAGE
1436
+ const checked = validateChart(JSON.parse(text));
1437
+ const html = checked.ok ? renderChartSvg(checked.spec) : `<em>Chart could not be drawn: ${checked.error}</em>`;
1438
+ ```
1439
+
1440
+ `renderChartSvg` is a pure function: no dependencies, nothing fetched, every label escaped. The
1441
+ same spec gives the same SVG in a viewer and a printed PDF. Validate before drawing even though
1442
+ the tool already checked: stored text can be edited since. Columns and bars start at zero; a line
1443
+ fits its axis to the data unless the spec says `"startAtZero": true`. Never ask an image model
1444
+ for a chart — it draws a plausible one with numbers of its own.
1445
+
1398
1446
  ## Data Storage
1399
1447
 
1400
1448
  Briyah stores data in the following structure:
@@ -105,6 +105,8 @@ export declare class AppController {
105
105
  illustrationMode?: string;
106
106
  /** The default shape of the room's pictures. Absent means 'square'. */
107
107
  imageAspect?: string;
108
+ /** IANA time zone the agents are told the date in. Absent: not told. */
109
+ timeZone?: string;
108
110
  }): Promise<CreateRoomResponse>;
109
111
  editRoom(req: ExpressRequest, roomId: string, body: {
110
112
  roomName: string;
@@ -124,6 +126,8 @@ export declare class AppController {
124
126
  illustrationMode?: string;
125
127
  /** The default shape of the room's pictures. */
126
128
  imageAspect?: string;
129
+ /** IANA time zone the agents are told the date in. Empty string stops it. */
130
+ timeZone?: string;
127
131
  }): Promise<void>;
128
132
  /**
129
133
  * Creates an agent that belongs to this room and adds it to it.
@@ -902,7 +902,9 @@ let AppController = AppController_1 = class AppController {
902
902
  const imageAspect = AppController_1.parseImageAspect(body.imageAspect);
903
903
  try {
904
904
  const appService = this.getAppService(req);
905
- return await appService.createRoom(body.roomName, body.roomGoal, body.agentIds ?? [], body.roomLeader, turnMode, body.moderator, body.beginInstruction, body.imageModel, illustrationMode, imageAspect);
905
+ return await appService.createRoom(body.roomName, body.roomGoal, body.agentIds ?? [], body.roomLeader, turnMode, body.moderator, body.beginInstruction, body.imageModel, illustrationMode, imageAspect,
906
+ // A name the runtime does not know comes back as a ValidationError: a 400.
907
+ body.timeZone);
906
908
  }
907
909
  catch (error) {
908
910
  logger_1.logger.error(`[${req.user?.sub}] Error creating room ${body.roomName}:`, error);
@@ -921,7 +923,7 @@ let AppController = AppController_1 = class AppController {
921
923
  const imageAspect = AppController_1.parseImageAspect(body.imageAspect);
922
924
  try {
923
925
  const appService = this.getAppService(req);
924
- await appService.editRoom(roomId, body.roomName, body.roomGoal, body.baseRoomDir, body.agentIds, body.roomLeader, turnMode, body.moderator, body.pack, body.beginInstruction, body.imageModel, illustrationMode, imageAspect);
926
+ await appService.editRoom(roomId, body.roomName, body.roomGoal, body.baseRoomDir, body.agentIds, body.roomLeader, turnMode, body.moderator, body.pack, body.beginInstruction, body.imageModel, illustrationMode, imageAspect, body.timeZone);
925
927
  }
926
928
  catch (error) {
927
929
  logger_1.logger.error(`[${req.user?.sub}] Error editing room ${roomId}:`, error);
@@ -474,8 +474,12 @@ export declare class AppService {
474
474
  * `'directed'` prompts only the message's targets. See {@link RoomTurnMode}.
475
475
  * @param moderator - Nickname of the agent that places messages the room cannot
476
476
  * route mechanically. Only consulted in `'moderated'` mode.
477
+ * @param timeZone - An IANA time zone (`America/Chicago`) in which every agent's
478
+ * turn is told today's date and time. Omit for a room that keeps its own clock,
479
+ * as a story does. See `RoomConfig.timeZone`.
477
480
  * @returns Object containing the new `roomId`
478
481
  * @throws {NotFoundError} If any agent ID does not exist
482
+ * @throws {ValidationError} If `timeZone` is not a time zone
479
483
  *
480
484
  * @example
481
485
  * ```typescript
@@ -527,7 +531,13 @@ export declare class AppService {
527
531
  * @param arriving An agent not yet in the room, checked as though it were.
528
532
  */
529
533
  private assertModeratorAvailable;
530
- createRoom(roomName: string, goal: string, agentIds: string[], roomLeader?: string, turnMode?: RoomTurnMode, moderator?: string, beginInstruction?: string, imageModel?: string, illustrationMode?: RoomIllustrationMode, imageAspect?: ImageAspect): Promise<CreateRoomResponse>;
534
+ /**
535
+ * Refuses a time zone the runtime does not know, where the caller can hear it.
536
+ * `Room.setTimeZone` would only warn, and the room's agents would silently go
537
+ * on without a date. Empty is allowed: it means "stop telling them".
538
+ */
539
+ private static assertTimeZone;
540
+ createRoom(roomName: string, goal: string, agentIds: string[], roomLeader?: string, turnMode?: RoomTurnMode, moderator?: string, beginInstruction?: string, imageModel?: string, illustrationMode?: RoomIllustrationMode, imageAspect?: ImageAspect, timeZone?: string): Promise<CreateRoomResponse>;
531
541
  /**
532
542
  * Updates the name, goal, and/or agent membership of an existing room.
533
543
  *
@@ -554,10 +564,13 @@ export declare class AppService {
554
564
  * @param illustrationMode - When the room illustrates itself. Omit to leave unchanged.
555
565
  * @param imageAspect - The shape the room draws in when an `illustrate` call names
556
566
  * none. Omit to leave unchanged. See {@link ImageAspect}.
567
+ * @param timeZone - The IANA time zone the agents are told the date in. Empty
568
+ * string stops telling them. Omit to leave unchanged. See `RoomConfig.timeZone`.
557
569
  * @throws {NotFoundError} If the room does not exist
558
570
  * @throws {OperationFailedError} If attempting to edit a published room instance
571
+ * @throws {ValidationError} If `timeZone` is not a time zone
559
572
  */
560
- editRoom(roomId: string, roomName: string, goal: string, baseRoomDir?: string, agentIds?: string[], roomLeader?: string, turnMode?: RoomTurnMode, moderator?: string, pack?: string, beginInstruction?: string, imageModel?: string, illustrationMode?: RoomIllustrationMode, imageAspect?: ImageAspect): Promise<void>;
573
+ editRoom(roomId: string, roomName: string, goal: string, baseRoomDir?: string, agentIds?: string[], roomLeader?: string, turnMode?: RoomTurnMode, moderator?: string, pack?: string, beginInstruction?: string, imageModel?: string, illustrationMode?: RoomIllustrationMode, imageAspect?: ImageAspect, timeZone?: string): Promise<void>;
561
574
  /**
562
575
  * Separates a room's name from the bare name of an agent that belongs to it.
563
576
  */
@@ -38,6 +38,7 @@ const errors_1 = require("./common/errors");
38
38
  const fs = __importStar(require("fs"));
39
39
  const path = __importStar(require("path"));
40
40
  const room_store_service_1 = require("./room/room-store.service");
41
+ const room_clock_1 = require("./room/room-clock");
41
42
  const prompt_resolver_1 = require("./config/prompt-resolver");
42
43
  const core_1 = require("./tools/core");
43
44
  const app_types_1 = require("../../shared/types/app.types");
@@ -800,8 +801,12 @@ class AppService {
800
801
  * `'directed'` prompts only the message's targets. See {@link RoomTurnMode}.
801
802
  * @param moderator - Nickname of the agent that places messages the room cannot
802
803
  * route mechanically. Only consulted in `'moderated'` mode.
804
+ * @param timeZone - An IANA time zone (`America/Chicago`) in which every agent's
805
+ * turn is told today's date and time. Omit for a room that keeps its own clock,
806
+ * as a story does. See `RoomConfig.timeZone`.
803
807
  * @returns Object containing the new `roomId`
804
808
  * @throws {NotFoundError} If any agent ID does not exist
809
+ * @throws {ValidationError} If `timeZone` is not a time zone
805
810
  *
806
811
  * @example
807
812
  * ```typescript
@@ -884,7 +889,19 @@ class AppService {
884
889
  throw new errors_1.ValidationError(`${names} ${needsModerator.length === 1 ? 'uses' : 'use'} a moderator, ` +
885
890
  `so room "${room.getName()}" needs one. ${reason}`);
886
891
  }
887
- async createRoom(roomName, goal, agentIds, roomLeader, turnMode, moderator, beginInstruction, imageModel, illustrationMode, imageAspect) {
892
+ /**
893
+ * Refuses a time zone the runtime does not know, where the caller can hear it.
894
+ * `Room.setTimeZone` would only warn, and the room's agents would silently go
895
+ * on without a date. Empty is allowed: it means "stop telling them".
896
+ */
897
+ static assertTimeZone(timeZone) {
898
+ const name = timeZone?.trim();
899
+ if (name && !(0, room_clock_1.isTimeZone)(name)) {
900
+ throw new errors_1.ValidationError(`"${name}" is not a time zone. Use an IANA name such as "America/Chicago" or "UTC".`);
901
+ }
902
+ }
903
+ async createRoom(roomName, goal, agentIds, roomLeader, turnMode, moderator, beginInstruction, imageModel, illustrationMode, imageAspect, timeZone) {
904
+ AppService.assertTimeZone(timeZone);
888
905
  // Validate that all agents exist before creating the room
889
906
  for (const agentId of agentIds) {
890
907
  const agent = await this.agentStore.getAgent(agentId);
@@ -922,6 +939,9 @@ class AppService {
922
939
  if (imageAspect !== undefined) {
923
940
  room.setImageAspect(imageAspect);
924
941
  }
942
+ if (timeZone !== undefined) {
943
+ room.setTimeZone(timeZone);
944
+ }
925
945
  // Before saveMetadata, so a room that cannot route its members' messages is
926
946
  // never written to disk.
927
947
  this.assertModeratorAvailable(room);
@@ -958,10 +978,14 @@ class AppService {
958
978
  * @param illustrationMode - When the room illustrates itself. Omit to leave unchanged.
959
979
  * @param imageAspect - The shape the room draws in when an `illustrate` call names
960
980
  * none. Omit to leave unchanged. See {@link ImageAspect}.
981
+ * @param timeZone - The IANA time zone the agents are told the date in. Empty
982
+ * string stops telling them. Omit to leave unchanged. See `RoomConfig.timeZone`.
961
983
  * @throws {NotFoundError} If the room does not exist
962
984
  * @throws {OperationFailedError} If attempting to edit a published room instance
985
+ * @throws {ValidationError} If `timeZone` is not a time zone
963
986
  */
964
- async editRoom(roomId, roomName, goal, baseRoomDir, agentIds, roomLeader, turnMode, moderator, pack, beginInstruction, imageModel, illustrationMode, imageAspect) {
987
+ async editRoom(roomId, roomName, goal, baseRoomDir, agentIds, roomLeader, turnMode, moderator, pack, beginInstruction, imageModel, illustrationMode, imageAspect, timeZone) {
988
+ AppService.assertTimeZone(timeZone);
965
989
  // Get the existing room
966
990
  const room = await this.roomStore.getRoom(roomId);
967
991
  if (!room) {
@@ -1022,6 +1046,9 @@ class AppService {
1022
1046
  if (imageAspect !== undefined) {
1023
1047
  room.setImageAspect(imageAspect);
1024
1048
  }
1049
+ if (timeZone !== undefined) {
1050
+ room.setTimeZone(timeZone);
1051
+ }
1025
1052
  // Catches clearing the moderator, or pointing it at an agent this edit just
1026
1053
  // removed, while a member still needs one.
1027
1054
  this.assertModeratorAvailable(room);
@@ -1288,6 +1315,7 @@ class AppService {
1288
1315
  imageModel: room.getImageModel(),
1289
1316
  illustrationMode: room.getIllustrationMode(),
1290
1317
  imageAspect: room.getImageAspect(),
1318
+ timeZone: room.getTimeZone(),
1291
1319
  baseRoomDir: room.getBaseRoomDir(),
1292
1320
  pack: room.getPack(),
1293
1321
  isPublished: room.getIsPublished(),
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Drawing a chart as SVG, from a spec {@link validateChart} has passed.
3
+ *
4
+ * A pure function with no dependencies and no I/O: the same spec gives the same
5
+ * markup on a server printing a PDF and on a client showing a viewer, and nothing
6
+ * in it fetches anything. Every piece of text is escaped, since categories and
7
+ * names come from a model.
8
+ *
9
+ * The rules a reader relies on are kept: a column's length is its value, so
10
+ * columns and bars start at zero; a line chart fits its value axis to the data
11
+ * unless asked to start at zero, because a trend that never nears zero would
12
+ * otherwise be a flat line; axis ticks are round numbers.
13
+ */
14
+ import { ChartSpec, ChartValueFormat } from './chart.types';
15
+ /**
16
+ * A value as the reader sees it. `compact` shortens large numbers for an axis
17
+ * (950K, 1.2M); labels on the data use the full figure.
18
+ */
19
+ export declare function formatChartValue(value: number, format?: ChartValueFormat, compact?: boolean, compactDigits?: number): string;
20
+ /**
21
+ * The chart as a standalone SVG document.
22
+ * @param spec A spec that {@link validateChart} returned
23
+ */
24
+ export declare function renderChartSvg(spec: ChartSpec): string;
@@ -0,0 +1,415 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatChartValue = formatChartValue;
4
+ exports.renderChartSvg = renderChartSvg;
5
+ const WIDTH = 720;
6
+ const HEIGHT = 400;
7
+ const FONT = 'Helvetica, Arial, sans-serif';
8
+ const TEXT = '#1f2937';
9
+ const MUTED = '#4b5563';
10
+ const GRID = '#e5e7eb';
11
+ const AXIS = '#9ca3af';
12
+ const TITLE = '#1d345d';
13
+ /** Distinct at a glance and in print; navy first, to match the reports around it. */
14
+ const PALETTE = [
15
+ '#1d345d', '#e07b39', '#2a9d8f', '#c9a227', '#b83b5e', '#6c5b9e',
16
+ '#4a90c2', '#7f8c8d', '#8fb339', '#d48a8a', '#3d5a80', '#a0522d',
17
+ ];
18
+ /** Value labels are written on the chart only when there are few enough to read. */
19
+ const MAX_LABELLED_POINTS = 12;
20
+ const esc = (text) => String(text ?? '')
21
+ .replace(/&/g, '&amp;')
22
+ .replace(/</g, '&lt;')
23
+ .replace(/>/g, '&gt;')
24
+ .replace(/"/g, '&quot;');
25
+ /** One decimal is plenty for coordinates and keeps the markup small. */
26
+ const r = (n) => Math.round(n * 10) / 10;
27
+ /** A rough width for 12px text, enough to lay labels out without measuring. */
28
+ const textWidth = (text, size = 12) => text.length * size * 0.55;
29
+ function fit(text, maxWidth, size = 12) {
30
+ if (textWidth(text, size) <= maxWidth)
31
+ return text;
32
+ const keep = Math.max(1, Math.floor(maxWidth / (size * 0.55)) - 1);
33
+ return `${text.slice(0, keep).trimEnd()}…`;
34
+ }
35
+ /**
36
+ * A value as the reader sees it. `compact` shortens large numbers for an axis
37
+ * (950K, 1.2M); labels on the data use the full figure.
38
+ */
39
+ function formatChartValue(value, format = 'number', compact = false, compactDigits = 1) {
40
+ const abs = Math.abs(value);
41
+ const digits = abs >= 100 ? 0 : abs >= 1 ? 1 : 2;
42
+ const plain = (n) => compact && n >= 10_000
43
+ ? new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: compactDigits }).format(n)
44
+ : n.toLocaleString('en-US', { maximumFractionDigits: digits });
45
+ if (format === 'percent')
46
+ return `${value < 0 ? '-' : ''}${plain(abs)}%`;
47
+ if (format === 'currency')
48
+ return `${value < 0 ? '-' : ''}$${plain(abs)}`;
49
+ return `${value < 0 ? '-' : ''}${plain(abs)}`;
50
+ }
51
+ /**
52
+ * Axis labels, compact (950K, 1.02M) with the fewest decimals that keep every tick
53
+ * distinct — one decimal alone writes 1.00M, 1.02M and 1.04M all as "1M".
54
+ */
55
+ function axisLabels(values, format) {
56
+ for (let digits = 1; digits <= 3; digits++) {
57
+ const labels = values.map((v) => formatChartValue(v, format, true, digits));
58
+ if (new Set(labels).size === labels.length)
59
+ return labels;
60
+ }
61
+ return values.map((v) => formatChartValue(v, format));
62
+ }
63
+ /** Round axis ticks spanning [min, max]: 1, 2 or 5 × 10ⁿ apart. */
64
+ function niceScale(min, max, targetTicks = 6) {
65
+ if (min === max) {
66
+ const pad = min === 0 ? 1 : Math.abs(min) * 0.1;
67
+ min -= pad;
68
+ max += pad;
69
+ }
70
+ const rough = (max - min) / Math.max(1, targetTicks - 1);
71
+ const power = Math.pow(10, Math.floor(Math.log10(rough)));
72
+ const fraction = rough / power;
73
+ const step = (fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10) * power;
74
+ return { min: Math.floor(min / step) * step, max: Math.ceil(max / step) * step, step };
75
+ }
76
+ function ticks(scale) {
77
+ const out = [];
78
+ // Counted rather than accumulated, so floating point never drops the last tick.
79
+ const count = Math.round((scale.max - scale.min) / scale.step);
80
+ for (let i = 0; i <= count; i++)
81
+ out.push(scale.min + i * scale.step);
82
+ return out;
83
+ }
84
+ function color(index) {
85
+ return PALETTE[index % PALETTE.length];
86
+ }
87
+ /** The legend, wrapped into rows across the width. @returns Its markup and height. */
88
+ function legend(items, top, width) {
89
+ if (items.length === 0)
90
+ return { svg: '', height: 0 };
91
+ const rows = [[]];
92
+ let rowWidth = 0;
93
+ for (const item of items) {
94
+ const name = fit(item.name, 220);
95
+ const itemWidth = 18 + textWidth(name) + 18;
96
+ if (rowWidth + itemWidth > width - 40 && rows[rows.length - 1].length) {
97
+ rows.push([]);
98
+ rowWidth = 0;
99
+ }
100
+ rows[rows.length - 1].push({ ...item, name, width: itemWidth });
101
+ rowWidth += itemWidth;
102
+ }
103
+ let svg = '';
104
+ rows.forEach((row, index) => {
105
+ const total = row.reduce((sum, item) => sum + item.width, 0);
106
+ let x = (width - total) / 2;
107
+ const y = top + index * 18;
108
+ for (const item of row) {
109
+ svg += `<rect x="${r(x)}" y="${r(y)}" width="12" height="12" rx="2" fill="${item.color}"/>`;
110
+ svg += `<text x="${r(x + 18)}" y="${r(y + 10)}" font-size="12" fill="${TEXT}">${esc(item.name)}</text>`;
111
+ x += item.width;
112
+ }
113
+ });
114
+ return { svg, height: rows.length * 18 };
115
+ }
116
+ /** The title, wrapped onto a second line when it is long. @returns Its markup and height. */
117
+ function heading(title, width) {
118
+ if (!title)
119
+ return { svg: '', height: 0 };
120
+ const perLine = Math.floor((width - 40) / (15 * 0.55));
121
+ const lines = [];
122
+ let line = '';
123
+ for (const word of title.split(/\s+/)) {
124
+ if (line && (line + ' ' + word).length > perLine) {
125
+ lines.push(line);
126
+ line = word;
127
+ }
128
+ else {
129
+ line = line ? `${line} ${word}` : word;
130
+ }
131
+ }
132
+ if (line)
133
+ lines.push(line);
134
+ const shown = lines.slice(0, 2);
135
+ const svg = shown
136
+ .map((text, index) => `<text x="${width / 2}" y="${24 + index * 19}" text-anchor="middle" font-size="15" font-weight="bold" fill="${TITLE}">${esc(text)}</text>`)
137
+ .join('');
138
+ return { svg, height: shown.length * 19 + 12 };
139
+ }
140
+ function open(spec, width, height) {
141
+ const label = esc(spec.title || 'Chart');
142
+ return (`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}" ` +
143
+ `font-family="${FONT}" role="img" aria-label="${label}"><title>${label}</title>` +
144
+ `<rect width="${width}" height="${height}" fill="#ffffff"/>`);
145
+ }
146
+ /**
147
+ * The chart as a standalone SVG document.
148
+ * @param spec A spec that {@link validateChart} returned
149
+ */
150
+ function renderChartSvg(spec) {
151
+ switch (spec.type) {
152
+ case 'pie':
153
+ return pieSvg(spec);
154
+ case 'bar':
155
+ return barSvg(spec);
156
+ default:
157
+ return verticalSvg(spec);
158
+ }
159
+ }
160
+ /** Line, column and stacked column: categories along the bottom, values up the side. */
161
+ function verticalSvg(spec) {
162
+ const format = spec.format ?? 'number';
163
+ const values = spec.series.flatMap((s) => s.values).filter((v) => v !== null);
164
+ let low;
165
+ let high;
166
+ if (spec.type === 'stacked-column') {
167
+ const totals = spec.categories.map((_, i) => spec.series.reduce((sum, s) => sum + (s.values[i] ?? 0), 0));
168
+ low = 0;
169
+ high = Math.max(...totals, 0);
170
+ }
171
+ else if (spec.type === 'line' && !spec.startAtZero) {
172
+ low = Math.min(...values);
173
+ high = Math.max(...values);
174
+ // A little room above and below, so no point sits on the frame — but never
175
+ // across zero, which would put a negative tick under a series that has none.
176
+ const pad = (high - low) * 0.08;
177
+ low = low >= 0 ? Math.max(0, low - pad) : low - pad;
178
+ high = high <= 0 ? Math.min(0, high + pad) : high + pad;
179
+ }
180
+ else {
181
+ low = Math.min(0, ...values);
182
+ high = Math.max(0, ...values);
183
+ }
184
+ const scale = niceScale(low, high);
185
+ const tickValues = ticks(scale);
186
+ const head = heading(spec.title, WIDTH);
187
+ const showLegend = spec.series.length > 1;
188
+ const key = legend(showLegend ? spec.series.map((s, i) => ({ name: s.name, color: color(i) })) : [], head.height + 8, WIDTH);
189
+ const tickLabels = axisLabels(tickValues, format);
190
+ const left = 16 + (spec.yLabel ? 20 : 0) + Math.max(...tickLabels.map((t) => textWidth(t))) + 8;
191
+ const right = WIDTH - 16;
192
+ const plotWidth = right - left;
193
+ const n = spec.categories.length;
194
+ const band = plotWidth / n;
195
+ // Category labels lie flat when they fit their band, and slant when they do not.
196
+ const widest = Math.max(...spec.categories.map((c) => textWidth(c)));
197
+ const slanted = widest > band - 6;
198
+ const labelEvery = slanted ? Math.max(1, Math.ceil(n / Math.floor(plotWidth / 16))) : 1;
199
+ const slantDepth = slanted ? Math.min(widest, 130) * 0.64 + 8 : 0;
200
+ const bottomPad = 12 + (slanted ? slantDepth : 18) + (spec.xLabel ? 20 : 0);
201
+ const top = head.height + key.height + (key.height ? 18 : 10);
202
+ const height = Math.max(HEIGHT, top + 220 + bottomPad);
203
+ const bottom = height - bottomPad;
204
+ const plotHeight = bottom - top;
205
+ const y = (v) => bottom - ((v - scale.min) / (scale.max - scale.min)) * plotHeight;
206
+ const cx = (i) => left + band * (i + 0.5);
207
+ let svg = open(spec, WIDTH, height) + head.svg + key.svg;
208
+ for (const [index, tick] of tickValues.entries()) {
209
+ const ty = r(y(tick));
210
+ const stroke = tick === 0 && scale.min < 0 ? AXIS : GRID;
211
+ svg += `<line x1="${r(left)}" y1="${ty}" x2="${right}" y2="${ty}" stroke="${stroke}" stroke-width="1"/>`;
212
+ svg += `<text x="${r(left - 8)}" y="${r(ty + 4)}" text-anchor="end" font-size="12" fill="${MUTED}">${esc(tickLabels[index])}</text>`;
213
+ }
214
+ svg += `<line x1="${r(left)}" y1="${r(bottom)}" x2="${right}" y2="${r(bottom)}" stroke="${AXIS}" stroke-width="1"/>`;
215
+ for (const [i, category] of spec.categories.entries()) {
216
+ if (i % labelEvery !== 0)
217
+ continue;
218
+ const text = esc(slanted ? fit(category, 130) : category);
219
+ svg += slanted
220
+ ? `<text transform="translate(${r(cx(i))},${r(bottom + 14)}) rotate(-40)" text-anchor="end" font-size="12" fill="${TEXT}">${text}</text>`
221
+ : `<text x="${r(cx(i))}" y="${r(bottom + 18)}" text-anchor="middle" font-size="12" fill="${TEXT}">${text}</text>`;
222
+ }
223
+ if (spec.xLabel) {
224
+ svg += `<text x="${r(left + plotWidth / 2)}" y="${r(height - 10)}" text-anchor="middle" font-size="12" fill="${MUTED}">${esc(spec.xLabel)}</text>`;
225
+ }
226
+ if (spec.yLabel) {
227
+ svg += `<text transform="translate(18,${r(top + plotHeight / 2)}) rotate(-90)" text-anchor="middle" font-size="12" fill="${MUTED}">${esc(spec.yLabel)}</text>`;
228
+ }
229
+ const labelled = n <= MAX_LABELLED_POINTS;
230
+ const dataLabel = (x, yy, v, room, anchor = 'middle') => {
231
+ const full = formatChartValue(v, format);
232
+ const text = textWidth(full, 11) <= room ? full : formatChartValue(v, format, true);
233
+ return `<text x="${r(x)}" y="${r(yy)}" text-anchor="${anchor}" font-size="11" fill="${TEXT}">${esc(text)}</text>`;
234
+ };
235
+ if (spec.type === 'line') {
236
+ for (const [s, series] of spec.series.entries()) {
237
+ let path = '';
238
+ let drawing = false;
239
+ for (const [i, v] of series.values.entries()) {
240
+ if (v === null) {
241
+ drawing = false;
242
+ continue;
243
+ }
244
+ path += `${drawing ? 'L' : 'M'}${r(cx(i))},${r(y(v))}`;
245
+ drawing = true;
246
+ }
247
+ svg += `<path d="${path}" fill="none" stroke="${color(s)}" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round"/>`;
248
+ if (n <= 30) {
249
+ for (const [i, v] of series.values.entries()) {
250
+ if (v === null)
251
+ continue;
252
+ svg += `<circle cx="${r(cx(i))}" cy="${r(y(v))}" r="3.5" fill="#ffffff" stroke="${color(s)}" stroke-width="2"/>`;
253
+ }
254
+ }
255
+ if (labelled && spec.series.length === 1) {
256
+ for (const [i, v] of series.values.entries()) {
257
+ if (v === null)
258
+ continue;
259
+ // Kept off the line: below a low point, where the line comes down
260
+ // into it from both sides; above a high one; and on a slope, above
261
+ // and to the side away from the neighbour the line climbs toward.
262
+ const before = series.values[i - 1] ?? null;
263
+ const after = series.values[i + 1] ?? null;
264
+ const low = (before === null || before > v) && (after === null || after > v);
265
+ const high = (before === null || before <= v) && (after === null || after <= v);
266
+ if (low) {
267
+ svg += dataLabel(cx(i), y(v) + 20, v, band - 4);
268
+ }
269
+ else if (high) {
270
+ svg += dataLabel(cx(i), y(v) - 10, v, band - 4);
271
+ }
272
+ else if (after !== null && after > v) {
273
+ svg += dataLabel(cx(i) - 6, y(v) - 8, v, band - 4, 'end');
274
+ }
275
+ else {
276
+ svg += dataLabel(cx(i) + 6, y(v) - 8, v, band - 4, 'start');
277
+ }
278
+ }
279
+ }
280
+ }
281
+ }
282
+ else if (spec.type === 'column') {
283
+ const group = band * 0.72;
284
+ const barWidth = group / spec.series.length;
285
+ const zero = y(Math.max(scale.min, Math.min(0, scale.max)));
286
+ for (const [s, series] of spec.series.entries()) {
287
+ for (const [i, v] of series.values.entries()) {
288
+ if (v === null)
289
+ continue;
290
+ const x = cx(i) - group / 2 + s * barWidth;
291
+ const yy = y(v);
292
+ svg += `<rect x="${r(x + 1)}" y="${r(Math.min(yy, zero))}" width="${r(Math.max(1, barWidth - 2))}" height="${r(Math.abs(zero - yy))}" fill="${color(s)}"/>`;
293
+ if (labelled && spec.series.length === 1) {
294
+ svg += dataLabel(x + barWidth / 2, v >= 0 ? yy - 5 : yy + 14, v, band - 4);
295
+ }
296
+ }
297
+ }
298
+ }
299
+ else {
300
+ // stacked-column
301
+ const barWidth = band * 0.6;
302
+ for (const [i] of spec.categories.entries()) {
303
+ let base = 0;
304
+ for (const [s, series] of spec.series.entries()) {
305
+ const v = series.values[i];
306
+ if (v === null || v === 0)
307
+ continue;
308
+ const y0 = y(base);
309
+ const y1 = y(base + v);
310
+ svg += `<rect x="${r(cx(i) - barWidth / 2)}" y="${r(y1)}" width="${r(barWidth)}" height="${r(y0 - y1)}" fill="${color(s)}" stroke="#ffffff" stroke-width="1"/>`;
311
+ base += v;
312
+ }
313
+ if (labelled && base > 0)
314
+ svg += dataLabel(cx(i), y(base) - 5, base, band - 4);
315
+ }
316
+ }
317
+ return `${svg}</svg>`;
318
+ }
319
+ /** Bars running across: categories down the side, for long names or many of them. */
320
+ function barSvg(spec) {
321
+ const format = spec.format ?? 'number';
322
+ const values = spec.series.flatMap((s) => s.values).filter((v) => v !== null);
323
+ const scale = niceScale(Math.min(0, ...values), Math.max(0, ...values));
324
+ const tickValues = ticks(scale);
325
+ const n = spec.categories.length;
326
+ const perSeries = spec.series.length > 1 ? 14 : 22;
327
+ const rowHeight = perSeries * spec.series.length + 10;
328
+ const head = heading(spec.title, WIDTH);
329
+ const key = legend(spec.series.length > 1 ? spec.series.map((s, i) => ({ name: s.name, color: color(i) })) : [], head.height + 8, WIDTH);
330
+ const top = head.height + key.height + (key.height ? 18 : 10);
331
+ const labelWidth = Math.min(220, Math.max(...spec.categories.map((c) => textWidth(c))));
332
+ const left = 16 + labelWidth + 10;
333
+ const valueRoom = n <= 30 ? 70 : 0;
334
+ const right = WIDTH - 16 - valueRoom;
335
+ const bottom = top + n * rowHeight;
336
+ const height = bottom + 30 + (spec.xLabel ? 20 : 0);
337
+ const x = (v) => left + ((v - scale.min) / (scale.max - scale.min)) * (right - left);
338
+ const zero = x(Math.max(scale.min, Math.min(0, scale.max)));
339
+ let svg = open(spec, WIDTH, height) + head.svg + key.svg;
340
+ const tickLabels = axisLabels(tickValues, format);
341
+ for (const [index, tick] of tickValues.entries()) {
342
+ const tx = r(x(tick));
343
+ svg += `<line x1="${tx}" y1="${r(top)}" x2="${tx}" y2="${r(bottom)}" stroke="${tick === 0 ? AXIS : GRID}" stroke-width="1"/>`;
344
+ svg += `<text x="${tx}" y="${r(bottom + 18)}" text-anchor="middle" font-size="12" fill="${MUTED}">${esc(tickLabels[index])}</text>`;
345
+ }
346
+ for (const [i, category] of spec.categories.entries()) {
347
+ const rowTop = top + i * rowHeight + 5;
348
+ svg += `<text x="${r(left - 10)}" y="${r(rowTop + (rowHeight - 10) / 2 + 4)}" text-anchor="end" font-size="12" fill="${TEXT}">${esc(fit(category, labelWidth))}</text>`;
349
+ for (const [s, series] of spec.series.entries()) {
350
+ const v = series.values[i];
351
+ if (v === null)
352
+ continue;
353
+ const by = rowTop + s * perSeries;
354
+ const bx = x(v);
355
+ svg += `<rect x="${r(Math.min(bx, zero))}" y="${r(by)}" width="${r(Math.max(1, Math.abs(bx - zero)))}" height="${perSeries - 2}" fill="${color(s)}"/>`;
356
+ if (valueRoom) {
357
+ const anchor = v >= 0 ? 'start' : 'end';
358
+ const lx = v >= 0 ? Math.max(bx, zero) + 5 : Math.min(bx, zero) - 5;
359
+ svg += `<text x="${r(lx)}" y="${r(by + perSeries / 2 + 3)}" text-anchor="${anchor}" font-size="11" fill="${TEXT}">${esc(formatChartValue(v, format))}</text>`;
360
+ }
361
+ }
362
+ }
363
+ if (spec.xLabel) {
364
+ svg += `<text x="${r((left + right) / 2)}" y="${r(height - 8)}" text-anchor="middle" font-size="12" fill="${MUTED}">${esc(spec.xLabel)}</text>`;
365
+ }
366
+ return `${svg}</svg>`;
367
+ }
368
+ /** A pie, with the legend beside it naming each slice's value and share. */
369
+ function pieSvg(spec) {
370
+ const format = spec.format ?? 'number';
371
+ const values = spec.series[0].values.map((v) => (v !== null && v > 0 ? v : 0));
372
+ const total = values.reduce((sum, v) => sum + v, 0);
373
+ const head = heading(spec.title, WIDTH);
374
+ const top = head.height + 10;
375
+ const height = Math.max(HEIGHT, top + 40 + spec.categories.length * 22);
376
+ const radius = Math.min(150, (height - top - 30) / 2);
377
+ const cx = 40 + radius;
378
+ const cy = top + 10 + radius;
379
+ let svg = open(spec, WIDTH, height) + head.svg;
380
+ let angle = -Math.PI / 2;
381
+ const slices = values.map((v, i) => ({ v, i })).filter(({ v }) => v > 0);
382
+ for (const { v, i } of slices) {
383
+ const sweep = (v / total) * Math.PI * 2;
384
+ if (slices.length === 1) {
385
+ svg += `<circle cx="${r(cx)}" cy="${r(cy)}" r="${r(radius)}" fill="${color(i)}"/>`;
386
+ }
387
+ else {
388
+ const end = angle + sweep;
389
+ const x0 = cx + radius * Math.cos(angle);
390
+ const y0 = cy + radius * Math.sin(angle);
391
+ const x1 = cx + radius * Math.cos(end);
392
+ const y1 = cy + radius * Math.sin(end);
393
+ svg += `<path d="M${r(cx)},${r(cy)} L${r(x0)},${r(y0)} A${r(radius)},${r(radius)} 0 ${sweep > Math.PI ? 1 : 0} 1 ${r(x1)},${r(y1)} Z" fill="${color(i)}" stroke="#ffffff" stroke-width="1.5"/>`;
394
+ }
395
+ const share = v / total;
396
+ if (share >= 0.05) {
397
+ const mid = angle + sweep / 2;
398
+ const lx = cx + radius * 0.62 * Math.cos(mid);
399
+ const ly = cy + radius * 0.62 * Math.sin(mid);
400
+ svg += `<text x="${r(lx)}" y="${r(ly + 4)}" text-anchor="middle" font-size="12" font-weight="bold" fill="#ffffff">${Math.round(share * 100)}%</text>`;
401
+ }
402
+ angle += sweep;
403
+ }
404
+ const legendX = cx + radius + 40;
405
+ const legendTop = cy - (spec.categories.length * 22) / 2;
406
+ for (const [i, category] of spec.categories.entries()) {
407
+ const v = spec.series[0].values[i];
408
+ const ly = legendTop + i * 22;
409
+ const share = v !== null && v > 0 ? ` (${((v / total) * 100).toFixed(1)}%)` : '';
410
+ const text = `${fit(category, 200)} — ${v === null ? 'no data' : formatChartValue(v, format)}${share}`;
411
+ svg += `<rect x="${r(legendX)}" y="${r(ly)}" width="12" height="12" rx="2" fill="${color(i)}"/>`;
412
+ svg += `<text x="${r(legendX + 18)}" y="${r(ly + 10)}" font-size="12" fill="${TEXT}">${esc(text)}</text>`;
413
+ }
414
+ return `${svg}</svg>`;
415
+ }