@brunosouzas/design-system 0.6.1 → 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 (40) hide show
  1. package/NOTICE +13 -0
  2. package/README.md +75 -40
  3. package/dist/scripts/cover.d.ts +7 -4
  4. package/dist/scripts/cover.js +25 -8
  5. package/dist/src/fonts/embed.d.ts +7 -0
  6. package/dist/src/fonts/embed.js +219 -0
  7. package/dist/src/pieces/bank-objects.d.ts +1 -1
  8. package/dist/src/pieces/bank-objects.js +26 -18
  9. package/dist/src/pieces/cover.js +2 -1
  10. package/dist/src/pieces/diagram.js +3 -3
  11. package/dist/src/pieces/eip-icons.js +27 -27
  12. package/dist/src/pieces/emote.d.ts +13 -0
  13. package/dist/src/pieces/emote.js +88 -0
  14. package/dist/src/pieces/index.d.ts +1 -1
  15. package/dist/src/pieces/index.js +1 -1
  16. package/dist/src/pieces/ink.d.ts +26 -16
  17. package/dist/src/pieces/ink.js +15 -6
  18. package/dist/src/pieces/library.d.ts +9 -15
  19. package/dist/src/pieces/library.js +52 -53
  20. package/dist/src/pieces/link-icons.d.ts +2 -1
  21. package/dist/src/pieces/link-icons.js +10 -18
  22. package/dist/src/pieces/metro.d.ts +4 -2
  23. package/dist/src/pieces/metro.js +14 -13
  24. package/dist/src/pieces/node.d.ts +5 -3
  25. package/dist/src/pieces/node.js +6 -4
  26. package/dist/src/pieces/params.js +2 -2
  27. package/dist/tokens/generated/tokens.d.ts +68 -156
  28. package/dist/tokens/generated/tokens.js +69 -157
  29. package/fonts/OFL.txt +97 -0
  30. package/fonts/SourceCodePro-Bold.ttf +0 -0
  31. package/fonts/SourceCodePro-Regular.ttf +0 -0
  32. package/fonts/SourceSans3-Black.ttf +0 -0
  33. package/fonts/SourceSans3-Bold.ttf +0 -0
  34. package/fonts/SourceSans3-Regular.ttf +0 -0
  35. package/package.json +10 -1
  36. package/tokens/generated/tokens.css +60 -110
  37. package/tokens/generated/tokens.json +69 -157
  38. package/tokens/generated/tokens.ts +69 -157
  39. package/dist/src/pieces/cast.d.ts +0 -35
  40. package/dist/src/pieces/cast.js +0 -333
package/NOTICE ADDED
@@ -0,0 +1,13 @@
1
+ @brunosouzas/design-system
2
+ Copyright Bruno Souza. Licensed under the Apache License, Version 2.0 (LICENSE).
3
+
4
+ This package ships third-party font files, unmodified, in fonts/:
5
+
6
+ - Source Sans 3, release 3.052R (SourceSans3-Regular.ttf, SourceSans3-Bold.ttf,
7
+ SourceSans3-Black.ttf), from https://github.com/adobe-fonts/source-sans
8
+ - Source Code Pro, release 2.042R (SourceCodePro-Regular.ttf,
9
+ SourceCodePro-Bold.ttf), from https://github.com/adobe-fonts/source-code-pro
10
+
11
+ Copyright Adobe, with Reserved Font Name 'Source'. Licensed under the SIL Open
12
+ Font License, Version 1.1: fonts/OFL.txt. The cover command embeds a subset of
13
+ these faces in the SVG files it writes (an embedded document font, OFL-FAQ 1.12).
package/README.md CHANGED
@@ -25,19 +25,19 @@ The visual identity of [brunosouzas.com](https://brunosouzas.com): design tokens
25
25
 
26
26
  ## Status
27
27
 
28
- Early. The first change of the [roadmap](docs/roadmap.md) is implemented: the token source and its CSS, TypeScript and JSON exports, the motion components, and the circuit-breaker state machine as the first catalogue scene (16:9 and 4:5, Portuguese and English), with commands to render its stills and videos. The first variety scene, `publish-subscribe`, is implemented with independent message copies, Publish acceptance, two ACKs and a local invoice NACK. Its owner stills/video approval is pending; implementation is not visual approval. The illustration pieces (roadmap item 3), the metro and diagram pieces (item 6) stackledger's map markers, zones and icons (AB#167, 0.3.0) and the body diagram pieces (AB#141, 0.3.2) are implemented: the static drawing library that covers, banners, diagrams and scenes share, with a command that builds a blog cover from a JSON spec. The published covers are not ported to it yet (item 5). The cast of mascots and the emotes (AB#152, 0.5.0) are pieces too, with the approved cast motion test in the Studio; new videos are language-neutral by default ([ADR 0005](docs/adr/0005-neutral-videos-and-the-cast.md)).
28
+ Early. The first change of the [roadmap](docs/roadmap.md) is implemented: the token source and its CSS, TypeScript and JSON exports, the motion components, and the circuit-breaker state machine as the first catalogue scene (16:9 and 4:5, Portuguese and English), with commands to render its stills and videos. The first variety scene, `publish-subscribe`, is implemented with independent message copies, Publish acceptance, two ACKs and a local invoice NACK. Its owner stills/video approval is pending; implementation is not visual approval. The illustration pieces (roadmap item 3), the metro and diagram pieces (item 6) stackledger's map markers, zones and icons (AB#167, 0.3.0) and the body diagram pieces (AB#141, 0.3.2) are implemented: the static drawing library that covers, banners, diagrams and scenes share, with a command that builds a blog cover from a JSON spec. The published covers are not ported to it yet (item 5). Mira, the four pillar characters, the bank objects and the emotes are pieces too ([ADR 0007](docs/adr/0007-mira-and-the-pillar-cast.md)); new videos are language-neutral by default ([ADR 0005](docs/adr/0005-neutral-videos-and-the-cast.md)). Since 0.7.0 every piece follows one grammar ([ADR 0009](docs/adr/0009-one-piece-grammar.md)) and every written SVG carries its Source faces ([ADR 0008](docs/adr/0008-type-inside-the-image.md)); see [Upgrading to 0.7.0](#upgrading-to-070).
29
29
 
30
30
  ## What it is
31
31
 
32
32
  The blog's articles explain how systems behave: a circuit breaker opening, a pipeline promoting a build, a message being retried. Static diagrams show the states; an animation shows the change. This repository keeps both in one visual language, so a reader recognises the site in an article, on LinkedIn and on a slide.
33
33
 
34
- - **Design tokens, one source.** Colours with fixed meanings (green healthy, orange blocked, yellow transitional, red the failure path), the Lato type scale, the thick ink outline, the hard offset shadow, radii, and motion timings. Exported as CSS variables for the site, TypeScript for the animations and JSON for anything else (the SVG generators of the static diagrams).
35
- - **Motion components.** React components for [Remotion](https://www.remotion.dev): an ink block with a hard shadow, a pill label, an arrow that draws itself, a token travelling along a transition, call-result squares, a countdown ring. Flow primitives in `src/brand/flow-components.tsx` add a white hexagonal `Exchange`, rail-ended `Queue`, yellow-tab `TaggedContainer` and persistent `PositionedToken` (stationary or path-positioned). Copy identities, splits and ACK/NACK rules belong to scenes, not to a generic message engine.
34
+ - **Design tokens, one source.** Colours with fixed meanings (green healthy, orange blocked, yellow transitional, red the failure path, under `color.state.*`), the brand palette, the Source type stacks (Source Sans 3, Source Code Pro, Source Serif 4), the thick ink outline, radii, and motion timings. Exported as CSS variables for the site, TypeScript for the animations and JSON for anything else (the SVG generators of the static diagrams).
35
+ - **Motion components.** React components for [Remotion](https://www.remotion.dev): an ink block, a pill label, an arrow that draws itself, a token travelling along a transition, call-result squares, a countdown ring. Flow primitives in `src/brand/flow-components.tsx` add a white hexagonal `Exchange`, rail-ended `Queue`, white-tab `TaggedContainer` and persistent `PositionedToken` (stationary or path-positioned). Copy identities, splits and ACK/NACK rules belong to scenes, not to a generic message engine.
36
36
  - **Illustration pieces.** The objects the blog's covers and diagrams draw again and again (pill label, sheet, code panel, robot, server stack, gear, road, the 26 EIP icons and more), each a pure TypeScript function that returns an SVG node tree from the tokens. The same tree becomes an SVG file for a cover and React elements for a scene, and a scene animates a piece by recomputing its parameters every frame. See [Illustration pieces and covers](#illustration-pieces-and-covers).
37
- - **A cast and emotes.** Seven mascots that are the technical objects themselves (Dev, AI agent, Architect, DevOps, Data, Requester, Message) and eight reaction symbols with a fixed meaning, so a video can tell its story without words. See [The cast and the emotes](#the-cast-and-the-emotes).
37
+ - **A cast and emotes.** Mira and four pillar characters (Visor, Drone, Kiu, Sinal), six bank objects for scenery, and eight reaction symbols with a fixed meaning, so a video can tell its story without words. See [The cast and the emotes](#the-cast-and-the-emotes).
38
38
  - **A catalogue of scenes.** Each scene animates something a published article already says. The first two are in 16:9 (article) and 4:5 (LinkedIn), in Portuguese and English from one text table; new scenes are one language-neutral 16:9 video ([ADR 0005](docs/adr/0005-neutral-videos-and-the-cast.md)). The first is the [circuit-breaker state machine](docs/spikes/2026-10-22-motion-pilot/README.md).
39
39
 
40
- The style follows the illustration covers of the [Spotify Engineering blog](https://engineering.atspotify.com/): flat shapes, a dark ink outline, a hard shadow with no blur, saturated colours on a calm page.
40
+ The style started from the illustration covers of the [Spotify Engineering blog](https://engineering.atspotify.com/) and, since 0.7.0, follows the brand's own grammar: flat shapes, one rounded ink outline, no hard shadow, white bodies on a warm page, one orange accent, and colour only where it means something ([ADR 0009](docs/adr/0009-one-piece-grammar.md)).
41
41
 
42
42
  ## How it works
43
43
 
@@ -54,7 +54,7 @@ The generated files are committed, so a consumer can read them without running N
54
54
 
55
55
  ## Install
56
56
 
57
- The tokens and the illustration pieces are published on npm as [`@brunosouzas/design-system`](https://www.npmjs.com/package/@brunosouzas/design-system), with provenance; releases follow [docs/release.md](docs/release.md). The package has no runtime dependency: Remotion, the motion components and the scenes stay in this repository.
57
+ The tokens and the illustration pieces are published on npm as [`@brunosouzas/design-system`](https://www.npmjs.com/package/@brunosouzas/design-system), with provenance; releases follow [docs/release.md](docs/release.md). Its one runtime dependency is `harfbuzzjs`, pinned exactly, which subsets the fonts it ships in `fonts/` (Source Sans 3 and Source Code Pro, under the [SIL Open Font License](fonts/OFL.txt)); Remotion, the motion components and the scenes stay in this repository.
58
58
 
59
59
  ```bash
60
60
  npm install @brunosouzas/design-system
@@ -64,6 +64,7 @@ npm install @brunosouzas/design-system
64
64
  |---|---|
65
65
  | `@brunosouzas/design-system` | the pieces, `toSvg`, `pose`, the cover spec helpers and `tokens` |
66
66
  | `@brunosouzas/design-system/react` | `toReact`, for React and Remotion (needs `react` 19) |
67
+ | `@brunosouzas/design-system/fonts` | `embedFonts`, for Node: embeds the Source faces a tree's text uses (reads `fonts/`, loads WebAssembly) |
67
68
  | `@brunosouzas/design-system/tokens` | the typed `tokens` object |
68
69
  | `@brunosouzas/design-system/tokens.css` | the `--ds-*` custom properties |
69
70
  | `@brunosouzas/design-system/tokens.json` | the plain values |
@@ -75,9 +76,19 @@ const label = pill({ x: 60, y: 30, text: "main" });
75
76
 
76
77
  The package also installs the cover command as `brunosouzas-cover <spec.json> --out <file.svg>`.
77
78
 
79
+ ### Type in a written image
80
+
81
+ An SVG shown through `<img>` cannot load web fonts, so a written image carries its own: `embedFonts(tree)` adds one `<style>` after the `<desc>` with a `@font-face` per Source face the tree's text uses, each a subset holding only the glyphs drawn ([ADR 0008](docs/adr/0008-type-inside-the-image.md)). The cover command and `npm run pieces:sheet` call it before they write; a tree without Source text is returned unchanged. It is async, reads only the faces it needs, and rejects naming the font file or `harfbuzzjs` when one fails to load. It lives in its own entry so the root entry stays importable in a browser. Its output is for written files and `<img>`: when you inline a piece's SVG in an HTML page, skip `embedFonts` and let the page's fonts apply, because an inline `<style>` with `@font-face` applies to the whole document and would replace the page's Source faces with a subset.
82
+
83
+ ```ts
84
+ import { coverTree, toSvg } from "@brunosouzas/design-system";
85
+ import { embedFonts } from "@brunosouzas/design-system/fonts";
86
+ const svg = toSvg(await embedFonts(coverTree(spec)));
87
+ ```
88
+
78
89
  ## Commands
79
90
 
80
- Requirements: Node.js 22.12 or later. Rendering also needs the network: Remotion downloads its headless browser on first use, and every render fetches Lato from Google Fonts.
91
+ Requirements: Node.js 22.12 or later. Rendering also needs the network: Remotion downloads its headless browser on first use, and every render fetches Source Sans 3 and Source Code Pro from Google Fonts.
81
92
 
82
93
  ```bash
83
94
  npm ci # install the pinned dependencies
@@ -93,6 +104,7 @@ npm run render -- publish-subscribe --dry-run # print eight commands; real v
93
104
  npm run build # compile the package into dist/ (the package test needs it)
94
105
  npm run cover -- cover.json --out card.svg # build a blog cover (or a banner, diagram or icon) from its spec
95
106
  npm run pieces:sheet -- --out out/pieces.svg # every piece once, labelled, for review
107
+ npm run pieces:sheet -- --out out/dark.svg --surface dark # the same on the dark surface
96
108
  npm run studio # Remotion Studio, for frame-by-frame review
97
109
  ```
98
110
 
@@ -131,22 +143,22 @@ The components take every colour and size from the tokens, and what is visible a
131
143
 
132
144
  - `toSvg(node)` writes a tree as SVG text; `toReact(node)` turns the same tree into React elements. Both describe the same elements, attributes and text, which the tests check.
133
145
  - `pose(node, { x, y, tilt, squash, hop, scale, shake, opacity })` animates any piece around its base point; a scene recomputes the numbers every frame.
134
- - Every colour parameter is a token path (`"color.healthy"`, `"illustration.accent"`), never a hex value, except the three data fills of the map pieces below. Each piece checks its parameters before drawing and names the first wrong one. Positions and points take any finite number, because a map has no edge; sizes stay within 10000. A drawing that would hold a non-finite number throws `<piece>: the drawing overflows`.
135
- - The 52 pieces, with their anchors, parameters and defaults, are listed in [design §4](openspec/changes/archive/2026-10-23-illustration-pieces/design.md) (the 26 cover pieces), in [design §3](openspec/changes/archive/2026-10-23-metro-and-diagram-pieces/design.md) of `metro-and-diagram-pieces` (the nine map and diagram pieces) and in [design §3, §5 and §6](openspec/changes/archive/2026-10-23-stackledger-map-and-link-pieces/design.md) of `stackledger-map-and-link-pieces` (the six markers, zones and icons) and in [design §3 to §5](openspec/changes/archive/2026-10-23-body-diagram-pieces/design.md) of `body-diagram-pieces` (the ten body diagram pieces), plus `stateStart` ([design §4](openspec/changes/archive/2026-10-24-designer-formats/design.md) of `designer-formats`); the rules are in [`openspec/specs/illustration-pieces/`](openspec/specs/illustration-pieces/spec.md). `npm run pieces:sheet -- --out <file.svg>` draws them all.
146
+ - Every colour parameter is a token path (`"color.state.healthy"`, `"illustration.accent"`), never a hex value, except the three data fills of the map pieces below. Each piece checks its parameters before drawing and names the first wrong one. Positions and points take any finite number, because a map has no edge; sizes stay within 10000. A drawing that would hold a non-finite number throws `<piece>: the drawing overflows`.
147
+ - The 62 pieces, with their anchors, parameters and defaults, are listed in [design §4](openspec/changes/archive/2026-10-23-illustration-pieces/design.md) (the 26 cover pieces), in [design §3](openspec/changes/archive/2026-10-23-metro-and-diagram-pieces/design.md) of `metro-and-diagram-pieces` (the nine map and diagram pieces) and in [design §3, §5 and §6](openspec/changes/archive/2026-10-23-stackledger-map-and-link-pieces/design.md) of `stackledger-map-and-link-pieces` (the six markers, zones and icons) and in [design §3 to §5](openspec/changes/archive/2026-10-23-body-diagram-pieces/design.md) of `body-diagram-pieces` (the ten body diagram pieces), plus `stateStart` ([design §4](openspec/changes/archive/2026-10-24-designer-formats/design.md) of `designer-formats`); the rules are in [`openspec/specs/illustration-pieces/`](openspec/specs/illustration-pieces/spec.md). `npm run pieces:sheet -- --out <file.svg>` draws them all, and `--surface dark` draws every piece that takes `surface` on the dark surface.
136
148
 
137
149
  ### Maps and diagrams
138
150
 
139
- Thirteen pieces draw a metro map and its page diagrams, for [stackledger](https://github.com/brunosouzas/stackledger) and any other map in this style: `lineBadge`, `stationMarker` (stop, interchange as a capsule, deprecated), `pipe`, `countBadge`, `nodeBlock`, `pillNode`, `hexNode` (normal, focus, placeholder), `messageArrow` (curved, straight or through two `controls` points, with a head and an optional label; `kind` `reply`, `failure` or `failFast` dashes it and paints it as ADR 0003 says; `heads: "start"` or `"both"` puts heads at `from`, `dashed` overrides the kind's dash), `ledgerMark` (stackledger's mark; `surface: "dark"` lines it with a light rim), `renewalRing` (orange bands round a station), `suggestedHalo` (a dashed muted circle), `licenceMark` (a 10-unit disc, green when held, white to buy) and `zone` (the outline the caller gives, widened by a round 32-unit stroke at the surface's zone opacity, with an optional title). They paint what the caller lays out: positions, hulls, text measurement and truncation stay with the map engine.
151
+ Thirteen pieces draw a metro map and its page diagrams, for [stackledger](https://github.com/brunosouzas/stackledger) and any other map in this style: `lineBadge`, `stationMarker` (stop, interchange as a capsule, deprecated), `pipe`, `countBadge`, `nodeBlock`, `pillNode`, `hexNode` (normal, focus, placeholder), `messageArrow` (curved, straight or through two `controls` points, with a head and an optional label; `kind` `reply`, `failure` or `failFast` dashes it and paints it as ADR 0003 says; `heads: "start"` or `"both"` puts heads at `from`, `dashed` overrides the kind's dash), `ledgerMark` (stackledger's mark; on `surface: "dark"` a muted band lines its ink square), `renewalRing` (orange bands round a station), `suggestedHalo` (a dashed muted circle), `licenceMark` (a 10-unit disc, green when held, white to buy) and `zone` (the outline the caller gives, widened by a round 32-unit stroke at the surface's zone opacity, with an optional title). They paint what the caller lays out: positions, hulls, text measurement and truncation stay with the map engine.
140
152
 
141
153
  - A `placeholder` node may have a `subtitle` (drawn like a normal node's, all muted), and `lineBadge` may have no `text` (the pill alone, 30 wide by default).
142
154
  - The licence's disc is small, so it has its own room rule: `size` at least three outlines (9 at ink scale 1).
143
155
 
144
- - `surface: "light" | "dark"` picks the background they sit on (`surface.*` tokens); every map and diagram piece takes it except `pipe`; `ledgerMark` takes only `surface`. On dark the hard shadow takes `surface.dark.shadow` and the outline gets a light rim ([ADR 0003](docs/adr/0003-visual-language-and-colour-meaning.md), amendment of AB#157).
145
- - `inkScale` (0.25 to 8) thickens the outline, rim and shadow without changing the geometry, on `lineBadge`, `stationMarker`, `countBadge` and the three nodes; the map uses 1, the page diagrams 1.6. A shape's height (a marker's diameter) must be at least four outlines; a placeholder node, which draws no ink, is exempt.
156
+ - `surface: "light" | "dark"` picks the background they sit on (`surface.*` tokens); every map and diagram piece takes it except `pipe`; `ledgerMark` takes only `surface`. On dark, ink strokes on the background or on a dark face take `surface.dark.muted`, since ink vanishes on black; marks over a light or state fill stay ink ([ADR 0009](docs/adr/0009-one-piece-grammar.md)).
157
+ - `inkScale` (0.25 to 8) thickens the outline without changing the geometry, on `lineBadge`, `stationMarker`, `countBadge` and the three nodes; the map uses 1, the page diagrams 1.6. A shape's height (a marker's diameter) must be at least four outlines; a placeholder node, which draws no ink, is exempt.
146
158
  - `countBadge` takes `textSize` (6 to 48, default 11): without `height`, the height, width and baseline grow with it.
147
159
  - A line's colour comes from the map's data, so `pipe.fill`, `lineBadge.fill` and `zone.fill` also accept `#RRGGBB`. Every other colour is a token path, and a cover spec rejects any hex.
148
160
  - `map.bendRadius` (32) is the radius of a bundle's centre line at a 45° or 90° bend; no piece reads it, the map engine draws the arcs (`pipe.d` takes `A`).
149
- - The `map.*` tokens hold the measures (outline 3, shadow 3.5, line 12, casing 6, badge 20, node 46, ring 3, halo 1.5, licence 10, zone padding 32, bend radius 32…), `surface.*.zoneOpacity` the zone's opacity (0.12, dark 0.22), `surface.*.backdropWater`, `backdropWaterEdge`, `backdropPark` and `backdropCredit` the colours of a city backdrop behind a map and its OpenStreetMap credit (no piece draws it; stackledger does), and `site.*` the page palette, fonts and type scale of brunosouzas.com in light and dark.
161
+ - The `map.*` tokens hold the measures (outline 3, shadow 0, line 12, casing 6, badge 20, node 46, ring 3, halo 1.5, licence 10, zone padding 32, bend radius 32…), `surface.*.zoneOpacity` the zone's opacity (0.12, dark 0.22), `surface.*.backdropWater`, `backdropWaterEdge`, `backdropPark` and `backdropCredit` the colours of a city backdrop behind a map and its OpenStreetMap credit (no piece draws it; stackledger does), and `site.*` the page palette, fonts and type scale of brunosouzas.com in light and dark.
150
162
 
151
163
  ```ts
152
164
  import { lineBadge, pipe, stationMarker, toSvg } from "@brunosouzas/design-system";
@@ -163,43 +175,31 @@ Ten pieces draw what the blog's body diagrams need beyond the map pieces: `diagr
163
175
  - Backticks mark code: `` "adopts a `correlationId`" `` draws `correlationId` in the monospace stack, as a `tspan`. An odd number of backticks is drawn as is. The cover `pill` follows the same rule (`` "`main`" ``).
164
176
  - `milestonePin` takes `size`, the head's radius (6 to 48, default 18); the head, its outline and the label scale with it.
165
177
  - Widths the piece estimates (`tagWidth`, `conditionWidth`, a label's `width`) can be passed by a caller that measures its text.
166
- - A body diagram is 800 wide. Lay it out in 560 units and show it 800 wide: the pieces then come out at the sizes of the published diagrams (text about 18, outline about 4); only the hard shadow is shallower (5 instead of 8). The cover command does this for you with `"format": "diagram"` (below).
178
+ - A body diagram is 800 wide. Lay it out in 560 units and show it 800 wide: the pieces then come out at the sizes of the published diagrams (text about 18, outline about 4). The cover command does this for you with `"format": "diagram"` (below).
167
179
  - `stateStart({ cx, cy, r, surface })` draws the filled start dot of a state machine (7.7 units, 11 at 800), in the surface's text colour, with no outline and no shadow.
168
180
 
169
181
  ### The cast and the emotes
170
182
 
171
- `mascot({ who, x, y, face, action, scale, look, headTilt, prop, surface })` draws one character standing with the centre of its ground line at `(x, y)`. Each one carries its identity in three layers, so no video has to introduce it: a body shape, a mark always visible, and a prop when its hands are free.
172
-
173
- | `who` | Body | Mark | Prop | Colour |
174
- |---|---|---|---|---|
175
- | `dev` | modern all-in-one computer, face and code on the screen | `</>` on the chin | | `cast.dev.*` |
176
- | `agent` | retro lamp all-in-one: dome, chrome neck, the screen is the head | AI spark | | white, glowing face (`cast.glow`) |
177
- | `architect` | drafting set square with its hole and a pencil | ruler ticks | diagram board | `cast.architect.*` |
178
- | `devops` | gear | ∞ | wrench | `cast.devops.*` (magenta, never the blocked orange) |
179
- | `data` | cylinder with a lid | two bands | magnifier | `cast.data.*` |
180
- | `request` | speech bubble | the request line | | `color.caller` |
181
- | `message` | envelope (0.7 of the others) | flap and seal | | white |
183
+ The cast of [ADR 0007](docs/adr/0007-mira-and-the-pillar-cast.md) shares one skin (white body, ink outline, a near-black visor with the amber idle eyes, `cast.eyes`); a character's identity is its shape, never a colour. Each takes `x`, `y` (the centre of its ground line), `scale`, `surface`, `expression` (`idle`, `done`, `waiting`, `failed`) and `view` (`front`, `back`):
182
184
 
183
- - `face`: `normal`, `blink`, `happy`, `wink`, `surprised`, `worried`, `thinking`, `focused`. One drawing for everyone; the agent's face glows on its dark screen.
184
- - `action`: `none` (the default: an expression has no hands or feet), `rest`, `wave`, `hold`, `reach`, `up`, `shrug`, `type`. Arms and legs start at the body's sides; hands are mittens.
185
- - `look` (-1 to 1) moves the gaze, `headTilt` (-30 to 30) turns the agent's head on its neck, `prop: false` hides the prop. Every part is a group named by `data-part` (`body`, `face`, `eyes`, `brows`, `mouth`, `arm-left`, `arm-right`, `legs`, `prop`, `mark`, …), so a scene can animate it.
185
+ - `mira(…)`: the protagonist, an astrolabe with a screen face; `needleAngle` points the route, `carries` rides a message on the needle's tip.
186
+ - `visor` (AI engineering; `holds`, `points`), `drone` (delivery; `carries`), `kiu` (wiki and series; `steps`), `sinal` (stackledger, without the parent-brand hood tip).
187
+ - `bankObject({ name, x, y, scale, surface })`: six objects for scenery, `courier`, `lume`, `carga`, `anel`, `modulo`, `hub`, with the cast's idle eyes on their screen and no expression.
186
188
 
187
189
  `emote({ kind, x, y, scale, burst, surface })` draws a reaction beside a head, never over the face. Each kind keeps one meaning in every video, like the colours:
188
190
 
189
191
  | `kind` | Shape | Meaning |
190
192
  |---|---|---|
191
- | `idea` | bulb | an idea |
193
+ | `idea` | amber bulb with rays | an idea |
192
194
  | `doubt` | ? | doubt, not understood |
193
195
  | `problem` | ! in a red triangle | a problem appears |
194
196
  | `worked` | green check | it worked |
195
197
  | `refused` | red cross | refused |
196
- | `pressure` | sweat drops | under pressure |
197
- | `liked` | heart | liked |
198
- | `waiting` | Z Z Z | waiting |
199
-
200
- In a scene, an emote pops in on the frame the face changes (`emotePop` in `src/brand/cast-motion.ts`, with `leave`, `blinking`, `breathe`, `squashAfter` and `hop`), one at a time, and the body acts through `pose`. A mascot's colour is its identity and never changes with state. The approved motion test is the Studio composition `cast-motion-test` (folder `cast`): `npx remotion render src/index.ts cast-motion-test`. It is a proof of the cast, not an article scene, so `npm run stills` and `npm run render` do not list it.
198
+ | `pressure` | white sweat drops | under pressure |
199
+ | `liked` | heart in the accent | liked |
200
+ | `waiting` | white Z Z Z | waiting |
201
201
 
202
- On a dark page pass `surface: "dark"` (AB#187, 0.5.2): the hard shadows take `surface.dark.shadow`, the ground takes `surface.dark.grid`, and a light rim (`surface.dark.rim`) lines the whole outline, limbs and props included; faces are unchanged. Without `surface`, the cast draws as in 0.5.0.
202
+ In a scene, an emote pops in on the frame the face changes (`emotePop` in `src/brand/cast-motion.ts`, with `leave`, `blinking`, `breathe`, `squashAfter` and `hop`), one at a time, and the body acts through `pose`. On a dark page pass `surface: "dark"`: the outlines, rays and Z casings take `surface.dark.muted`, the marks over a fill stay ink.
203
203
 
204
204
  ### A cover
205
205
 
@@ -210,7 +210,7 @@ A cover is a JSON spec kept with its article, outside this repository: drafts ar
210
210
  "id": "sdd",
211
211
  "title": "A one-line request becomes a reviewed spec before any code",
212
212
  "description": "Illustration. On the left, a small slip …",
213
- "background": "blush",
213
+ "background": "trackAi",
214
214
  "rings": { "cx": 400, "cy": 220, "radius": 96 },
215
215
  "pieces": [
216
216
  { "piece": "speechBubble", "x": 52, "y": 174, "width": 160, "height": 74 },
@@ -219,7 +219,23 @@ A cover is a JSON spec kept with its article, outside this repository: drafts ar
219
219
  }
220
220
  ```
221
221
 
222
- - `background` names one pair in `coverBackground` (a background and its ring colour): `trackIntegration`, `trackDelivery` or `trackAi` for a cover of that track (ADR 0006), `neutral` (the brand background) for a category with no track, or one of the 21 pairs measured from the covers published before 0.6.0, kept until 0.7.0 so their specs still build. Which cover takes which pair is the `illustration` skill's rule, not the package's.
222
+ - `background` names one pair in `coverBackground` (a background and its ring colour). Since 0.7.0 the pairs are track families (ADR 0006, amended 2026-11-06): each track has a default `track<Name>` and named tones `<track><Tone>`, and each article picks one tone of its track, so a series varies and the track stays recognisable; `neutral` (the brand background) is for a cover with no track. These twelve are the only pairs. Which cover takes which tone is the `illustration` skill's rule, not the package's.
223
+
224
+ | Track | Name | Tone | Fill | Ring |
225
+ |---|---|---|---|---|
226
+ | Integration | `trackIntegration` | peach, default | `#F7C6A1` | `#E3AB84` |
227
+ | Integration | `integrationClay` | clay | `#E9CDBE` | `#D3B3A3` |
228
+ | Integration | `integrationSand` | sand | `#EED7A8` | `#D8BF8C` |
229
+ | Delivery | `trackDelivery` | sage, default | `#B9DEC3` | `#98C6A5` |
230
+ | Delivery | `deliveryMint` | mint | `#A9DCD6` | `#88C4BD` |
231
+ | Delivery | `deliveryOlive` | olive | `#D3DFA8` | `#B9C78A` |
232
+ | AI | `trackAi` | periwinkle, default | `#C5CDF2` | `#A5AEDA` |
233
+ | AI | `aiSky` | sky | `#B5D5F2` | `#94BBDE` |
234
+ | AI | `aiLilac` | lilac | `#DCC7F0` | `#C3A9DC` |
235
+ | Personal tools | `trackPersonal` | butter, default (new) | `#F4DD8E` | `#DDC46C` |
236
+ | Personal tools | `personalRose` | rose | `#F5C9DA` | `#E0ABC0` |
237
+ | no track | `neutral` | cream (unchanged) | `#F6F3EC` | `#D8D6D0` |
238
+
223
239
  - `pieces` are drawn in order; their words go on top.
224
240
  - The `rings` centre stays within ±10000 in a cover spec, and a piece that overflows is reported at its entry (`pieces[1]: the drawing overflows`).
225
241
  - `custom` (optional) is the cover's one free-form object, a JSON node tree limited to drawing tags and a fixed list of attributes, with no external references. An object that repeats becomes a piece instead. It is painted after every piece's shapes; `customAt: <i>` paints it before `pieces[i]` instead, so a pill can sit on top of it (words always stay on top).
@@ -236,7 +252,7 @@ The banner is one image that scales down as a whole. Words in it become small on
236
252
 
237
253
  ### Signature lockup
238
254
 
239
- A cover, banner, LinkedIn card or og spec takes an optional `"signature": true`: Mira (scale 0.25) and the symbol, anchored to the frame's bottom-right corner by `cover.signatureMargin` from both edges. Omit it and nothing is added — `signature` isn't used by a diagram, a favicon or an avatar.
255
+ A cover, banner, LinkedIn card or og spec takes an optional `"signature": true`: Mira (scale 0.25) and the symbol, anchored to the frame's bottom-right corner by `cover.signatureMargin` from both edges. Omit it and nothing is added. A diagram, favicon, avatar or icon spec refuses the key (an icon accepted it and drew nothing before 0.7.0).
240
256
 
241
257
  ### Social and platform formats
242
258
 
@@ -256,7 +272,7 @@ npx --yes --package @brunosouzas/design-system@<version> brunosouzas-cover desig
256
272
  ```
257
273
 
258
274
  - `"format": "diagram"` takes a `height` in layout units (1 to 10000) and no `background`: the spec is laid out 560 wide and written 800 wide, on the `color.panel` panel with rounded corners (`bodyDiagram.radius`, 14 at 800) and rings in `color.ring` that show at step 28 and width 2, out to the farthest corner. Pieces get the map outline (3) and label size (13), which show at 4.3 and 18.6. `test/fixtures/covers/circuit-breaker-states.json` is the circuit breaker article's state diagram.
259
- - `"format": "icon"` holds one `eipIcon`, `uiIcon` or `linkIcon` at 0,0 and writes it in a box of its own size (64x40 for an EIP icon). An EIP icon takes its title and description, with the CC BY 4.0 credit, from the icon's data, so its spec has neither; a UI or link icon spec needs both. No `background`, `rings` or `custom`.
275
+ - `"format": "icon"` holds one `eipIcon`, `uiIcon` or `linkIcon` at 0,0 and writes it in a box of its own size (64x40 for an EIP icon). An EIP icon takes its title and description, with the CC BY 4.0 credit, from the icon's data, so its spec has neither; a UI or link icon spec needs both. No `background`, `rings`, `custom` or `signature`.
260
276
  - **Text tables.** `"text": { "pt": { "open": ["taxa de falha", "> limite"] }, "en": { ... } }` holds one table per language with the same keys; any string `"@open"` elsewhere in the spec (pieces, `title`, `description`, even `id`) is replaced by that key's value for the language passed with `--lang <code>`. Every language must define every key, and the ids in the output gain the language (`<id>-pt`). Without `text`, strings are drawn as written, so `"@home"` stays a label.
261
277
  - Like a cover, a diagram or icon is a standalone image: `uiIcon` `colour: "currentColor"` is refused in every format.
262
278
 
@@ -267,7 +283,7 @@ Add it to `src/pieces/library.ts` (or `src/pieces/metro.ts` for a map or diagram
267
283
  ### UI and link icons
268
284
 
269
285
  - `uiIcon({ name, x, y, size, colour })` draws one of seven glyphs of the sites' chrome in a 24-unit box and one token colour: `sun`, `moon`, `zoomIn`, `zoomOut`, `reset`, `calendar`, `download` (data in `UI_ICONS`). `colour: "currentColor"` makes the icon follow its element's text colour (a button that inverts on hover, say); it only works when the SVG is inline in the page, since an `<img>` does not inherit the page's colour, and a cover spec refuses it.
270
- - `linkIcon({ icon, x, y, size, surface })` draws a link sticker as brunosouzas.com draws its social icons (46-unit box, light or dark frame): `github`, `linkedin`, `email`, `website` (data in `LINK_ICONS`). The GitHub mark is from [Font Awesome](https://fontawesome.com/), licensed [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).
286
+ - `linkIcon({ icon, x, y, size, surface })` draws a link sticker in a 46-unit box, a white face with its outline and no frame (on dark the outline takes `surface.dark.muted`): `github`, `linkedin`, `email`, `website` (data in `LINK_ICONS`). The GitHub mark is from [Font Awesome](https://fontawesome.com/), licensed [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).
271
287
  - Neither holds a link, a style, a script or a URL, so a consumer can write one with `toSvg` inside its own `<svg xmlns=…>` and ship it as a static file.
272
288
 
273
289
  ```ts
@@ -279,6 +295,21 @@ const github = toSvg(el("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "
279
295
 
280
296
  `src/pieces/eip-icons.ts` holds the 26 Enterprise Integration Patterns icons as data. They are redrawn from the icons by Gregor Hohpe and Bobby Woolf ([enterpriseintegrationpatterns.com](https://www.enterpriseintegrationpatterns.com/)), licensed [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/); each icon keeps that credit in its description.
281
297
 
298
+ ## Upgrading to 0.7.0
299
+
300
+ 0.7.0 is a breaking release (cards 300 and 301). Rebuild every image once on it; the output changes appearance (ADR 0009) and carries its fonts (ADR 0008).
301
+
302
+ | Removed | Use instead |
303
+ |---|---|
304
+ | `color.healthy`, `color.blocked`, `color.transitional`, `color.caller`, `color.backend`, `color.failure`, `color.failFast` (and their `--ds-color-*` variables) | the same values at `color.state.*` (`--ds-color-state-*`); a spec that passes `"color.healthy"` is refused, pass `"color.state.healthy"` |
305
+ | the 21 `coverBackground` pairs from before 0.6.0 (`blush`, `peach`, `lavender`, `navy`, `mustard`, …) | a tone of the cover's track family (`trackIntegration`, `integrationClay`, `deliveryMint`, `aiSky`, `trackPersonal`, … see "Cover spec") or `neutral` |
306
+ | `mascot`, `MASCOTS`, `MASCOT_ACTIONS`, `MASCOT_FACES`, the types `MascotName`, `MascotFace`, `MascotAction`, `MascotParams` and the seven-role `cast.*` colours | Mira, the pillar characters or a bank object (ADR 0007); `emote` and `EMOTE_KINDS` stay |
307
+ | `illustration.healthyShade`, `illustration.transitionalShade` | nothing reads them; pass a token path if a drawing needs a shade |
308
+ | `"signature"` in an icon spec | remove it (it drew nothing) |
309
+ | the `cast-motion-test` composition | none; the cast timing helpers in `src/brand/cast-motion.ts` stay |
310
+
311
+ Other changes a consumer sees: `font.sans` and `font.mono` name Source Sans 3 and Source Code Pro first, and the new `font.serif` names Source Serif 4; `cover.labelWeight` is 700 (Source Sans 3 has no static 800); the `shadow` tokens and `map.shadow` are 0; `color.ink`, `color.panel`, `color.ring`, `illustration.*` and `surface.*` take the v2 values; several pieces have new defaults (a white `taggedContainer` tab, an ink `arcArrow`, white bodies), listed in [ADR 0009](docs/adr/0009-one-piece-grammar.md) and the change's design.
312
+
282
313
  ## Decisions
283
314
 
284
315
  Project-wide decisions are recorded as ADRs in [`docs/adr/`](docs/adr/README.md).
@@ -288,6 +319,10 @@ Project-wide decisions are recorded as ADRs in [`docs/adr/`](docs/adr/README.md)
288
319
  - **One visual language, fixed colour meanings.** Green is always healthy, orange always blocked, red always the failure path, so a reader learns the code once. Rotated text is allowed since the 2026-10-23 amendment. [ADR 0003](docs/adr/0003-visual-language-and-colour-meaning.md)
289
320
  - **Scenes illustrate an approved source.** Every string on screen comes from a published article, or from a post or page the owner approved, so a scene or piece never says more than the reviewed text. Catalogue scenes still come from published articles. [ADR 0004](docs/adr/0004-scenes-illustrate-published-articles.md)
290
321
  - **Neutral videos, told by a fixed cast.** One video for both languages, no words on screen, a caption only when the motion cannot explain itself, and every gesture tied to an article line. [ADR 0005](docs/adr/0005-neutral-videos-and-the-cast.md)
322
+ - **Three token layers.** Primitive, semantic and component tokens, with the brand palette measured for AA contrast in both themes and the states under `color.state.*`. [ADR 0006](docs/adr/0006-three-layer-tokens-and-brand-colour.md)
323
+ - **Mira and the pillar cast.** A protagonist and four pillar characters replace the engineering-role cast. [ADR 0007](docs/adr/0007-mira-and-the-pillar-cast.md)
324
+ - **Type inside the image.** Every written SVG embeds a subset of the Source faces its text uses, so readers see Source through `<img>`. [ADR 0008](docs/adr/0008-type-inside-the-image.md)
325
+ - **One piece grammar.** No hard shadow, white bodies, one accent, colour only where it means something, ink muted on dark; a test checks every piece. [ADR 0009](docs/adr/0009-one-piece-grammar.md)
291
326
 
292
327
  ## How this project is built
293
328
 
@@ -15,12 +15,15 @@ export declare const parseCoverArgs: (args: string[], cwd: string) => {
15
15
  ok: false;
16
16
  problem: string;
17
17
  };
18
- /** Builds the cover text for a spec file's contents, or the problem lines. */
19
- export declare const buildCover: (text: string, label: string, lang?: string) => {
18
+ /**
19
+ * Builds the cover text for a spec file's contents, its fonts embedded, or the
20
+ * problem lines. Rejects when embedding fails (a font file, or harfbuzzjs).
21
+ */
22
+ export declare const buildCover: (text: string, label: string, lang?: string) => Promise<{
20
23
  ok: true;
21
24
  svg: string;
22
25
  } | {
23
26
  ok: false;
24
27
  lines: string[];
25
- };
26
- export declare const runCover: (args: string[], io: CoverIo) => number;
28
+ }>;
29
+ export declare const runCover: (args: string[], io: CoverIo) => Promise<number>;
@@ -7,13 +7,19 @@
7
7
  // makes every cover reproducible, and only the pieces live in this public
8
8
  // repository.
9
9
  //
10
+ // Every written image embeds, as subsets, the Source faces its text uses
11
+ // (`embedFonts`, ADR 0008), so a reader sees Source inside an `<img>`.
12
+ //
10
13
  // What can go wrong: a bad invocation reports its first problem with the
11
- // usage; an invalid spec reports every problem by JSON path. In both cases the
12
- // command exits 1 and writes nothing. An existing output file is replaced.
14
+ // usage; an invalid spec reports every problem by JSON path; a font file that
15
+ // cannot be read or a WebAssembly subsetter that does not load prints the
16
+ // error's one line (naming the file or harfbuzzjs). In each case the command
17
+ // exits 1 and writes nothing. An existing output file is replaced.
13
18
  import { closeSync, existsSync, openSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
14
19
  import { randomUUID } from "node:crypto";
15
20
  import { dirname, resolve } from "node:path";
16
21
  import { fileURLToPath } from "node:url";
22
+ import { embedFonts } from "../src/fonts/embed.js";
17
23
  import { coverTree, LANGUAGE, validateCoverSpec } from "../src/pieces/cover.js";
18
24
  import { toSvg } from "../src/pieces/render.js";
19
25
  export const COVER_USAGE = "usage: npm run cover -- <spec.json> --out <file.svg> [--lang <code>]";
@@ -93,17 +99,20 @@ const parseJson = (text, label) => {
93
99
  return { problem: `${label}: invalid JSON${where} (${message})` };
94
100
  }
95
101
  };
96
- /** Builds the cover text for a spec file's contents, or the problem lines. */
97
- export const buildCover = (text, label, lang) => {
102
+ /**
103
+ * Builds the cover text for a spec file's contents, its fonts embedded, or the
104
+ * problem lines. Rejects when embedding fails (a font file, or harfbuzzjs).
105
+ */
106
+ export const buildCover = async (text, label, lang) => {
98
107
  const parsed = parseJson(text, label);
99
108
  if ("problem" in parsed)
100
109
  return { ok: false, lines: [parsed.problem] };
101
110
  const problems = validateCoverSpec(parsed.value, { lang });
102
111
  if (problems.length > 0)
103
112
  return { ok: false, lines: problems.map((p) => `${p.path}: ${p.message}`) };
104
- return { ok: true, svg: `${toSvg(coverTree(parsed.value, { lang }))}\n` };
113
+ return { ok: true, svg: `${toSvg(await embedFonts(coverTree(parsed.value, { lang })))}\n` };
105
114
  };
106
- export const runCover = (args, io) => {
115
+ export const runCover = async (args, io) => {
107
116
  const invocation = parseCoverArgs(args, io.cwd);
108
117
  if (!invocation.ok) {
109
118
  io.error(invocation.problem);
@@ -120,7 +129,15 @@ export const runCover = (args, io) => {
120
129
  io.error(COVER_USAGE);
121
130
  return 1;
122
131
  }
123
- const result = buildCover(text, invocation.spec, invocation.lang);
132
+ let result;
133
+ try {
134
+ result = await buildCover(text, invocation.spec, invocation.lang);
135
+ }
136
+ catch (error) {
137
+ // The embedding failed: no image ships without its faces.
138
+ io.error(error instanceof Error ? error.message : String(error));
139
+ return 1;
140
+ }
124
141
  if (!result.ok) {
125
142
  for (const line of result.lines)
126
143
  io.error(line);
@@ -165,5 +182,5 @@ const isMain = (() => {
165
182
  }
166
183
  })();
167
184
  if (isMain) {
168
- process.exitCode = runCover(process.argv.slice(2), { cwd: process.env.INIT_CWD ?? process.cwd(), log: console.log, error: console.error });
185
+ process.exitCode = await runCover(process.argv.slice(2), { cwd: process.env.INIT_CWD ?? process.cwd(), log: console.log, error: console.error });
169
186
  }
@@ -0,0 +1,7 @@
1
+ import type { SvgNode } from "../pieces/node.ts";
2
+ /**
3
+ * The tree with the Source faces its drawn text uses embedded as subsets, in
4
+ * one `style` right after the root's `desc` (or as its first child). A tree
5
+ * with no face to embed resolves to the input; the input is never modified.
6
+ */
7
+ export declare const embedFonts: (tree: SvgNode) => Promise<SvgNode>;
@@ -0,0 +1,219 @@
1
+ // Source faces embedded in an SVG tree (spec illustration-pieces, "Fonts
2
+ // embedded in an SVG tree"; design.md Decision 1, ADR 0008), exported from the
3
+ // subpath `@brunosouzas/design-system/fonts`.
4
+ //
5
+ // Why: the site shows covers and diagrams through `<img>`, which never loads a
6
+ // page's web fonts, and Source is not installed on most readers' machines. So
7
+ // every written image carries, as a TrueType subset in a `<style>`, only the
8
+ // characters it draws in each Source face; the reader sees Source, at 2-10 KB
9
+ // gzip per image.
10
+ //
11
+ // How: `await embedFonts(tree)` returns a new tree with one `style` after the
12
+ // root's `desc` (or first), one `@font-face` per face its drawn text uses. The
13
+ // cover command and `npm run pieces:sheet` call it before writing.
14
+ //
15
+ // What can go wrong: an unreadable font file or a WebAssembly module that does
16
+ // not load rejects with an Error naming the file or `harfbuzzjs`; a failed load
17
+ // is not cached, so the next call retries. A character no shipped face has is
18
+ // left out of the subset (the browser takes it from the next family of the
19
+ // stack). This module reads files, so it lives outside src/pieces/, whose
20
+ // modules stay pure (the root entry must import in a browser bundle).
21
+ import { existsSync, readFileSync } from "node:fs";
22
+ import { readFile } from "node:fs/promises";
23
+ import { createRequire } from "node:module";
24
+ import { dirname, join } from "node:path";
25
+ import { fileURLToPath } from "node:url";
26
+ const PACKAGE_NAME = "@brunosouzas/design-system";
27
+ const FACES = [
28
+ { family: "Source Code Pro", weight: 400, upTo: 549, range: "100 549", file: "SourceCodePro-Regular.ttf" },
29
+ { family: "Source Code Pro", weight: 700, upTo: Infinity, range: "550 900", file: "SourceCodePro-Bold.ttf" },
30
+ { family: "Source Sans 3", weight: 400, upTo: 549, range: "100 549", file: "SourceSans3-Regular.ttf" },
31
+ { family: "Source Sans 3", weight: 700, upTo: 799, range: "550 799", file: "SourceSans3-Bold.ttf" },
32
+ { family: "Source Sans 3", weight: 900, upTo: Infinity, range: "800 900", file: "SourceSans3-Black.ttf" },
33
+ ];
34
+ // FACES is already in the order of the rules: family name by code point, then weight.
35
+ /** Subtrees whose strings are never drawn. */
36
+ const NOT_DRAWN = new Set(["title", "desc", "style"]);
37
+ /** First family of a `font-family` list, trimmed and unquoted. */
38
+ const firstFamily = (value) => value.split(",")[0].trim().replace(/^(["'])(.*)\1$/, "$2");
39
+ /** CSS weight of a `font-weight` value: keywords other than `bold`, and anything non-numeric, are 400. */
40
+ const weightOf = (value) => {
41
+ if (typeof value === "number")
42
+ return value;
43
+ if (value === undefined)
44
+ return 400;
45
+ const trimmed = value.trim();
46
+ if (trimmed === "bold")
47
+ return 700;
48
+ return /^\d+(\.\d+)?$/.test(trimmed) ? Number(trimmed) : 400;
49
+ };
50
+ /** The shipped face a text is drawn in, or undefined (another family, or none). Italic and oblique take the upright face. */
51
+ const faceOf = (inherited) => {
52
+ if (inherited.family === undefined)
53
+ return undefined;
54
+ const family = firstFamily(inherited.family);
55
+ const weight = weightOf(inherited.weight);
56
+ const ofFamily = FACES.filter((face) => face.family === family);
57
+ // Snapped to the first face whose declared range reaches the weight (549.5
58
+ // goes to 700 and 799.5 to 900, as in the browser); above 900, the heaviest.
59
+ return ofFamily.find((face) => weight <= face.upTo);
60
+ };
61
+ /** Drawn characters per face: the strings of text and tspan nodes, outside title, desc and style. */
62
+ const drawnText = (node, inherited, out) => {
63
+ if (NOT_DRAWN.has(node.tag))
64
+ return;
65
+ const own = {
66
+ family: node.attrs["font-family"] === undefined ? inherited.family : String(node.attrs["font-family"]),
67
+ weight: node.attrs["font-weight"] ?? inherited.weight,
68
+ };
69
+ const isText = node.tag === "text" || node.tag === "tspan";
70
+ for (const child of node.children) {
71
+ if (typeof child !== "string")
72
+ drawnText(child, own, out);
73
+ else if (isText) {
74
+ const face = faceOf(own);
75
+ if (face === undefined)
76
+ continue;
77
+ const characters = out.get(face) ?? new Set();
78
+ for (const character of child)
79
+ characters.add(character);
80
+ out.set(face, characters);
81
+ }
82
+ }
83
+ };
84
+ // ---------- loading (lazy, once per process, failures not cached) ----------
85
+ let fontsFolder;
86
+ /** `fonts/` of this package: the nearest package.json above this module named @brunosouzas/design-system (works from src/ and dist/). */
87
+ const fontsDir = () => {
88
+ if (fontsFolder !== undefined)
89
+ return fontsFolder;
90
+ const start = dirname(fileURLToPath(import.meta.url));
91
+ for (let dir = start;; dir = dirname(dir)) {
92
+ const manifest = join(dir, "package.json");
93
+ if (existsSync(manifest) && JSON.parse(readFileSync(manifest, "utf8")).name === PACKAGE_NAME) {
94
+ fontsFolder = join(dir, "fonts");
95
+ return fontsFolder;
96
+ }
97
+ if (dirname(dir) === dir)
98
+ throw new Error(`cannot find the fonts/ folder of ${PACKAGE_NAME} above ${start}`);
99
+ }
100
+ };
101
+ const message = (error) => (error instanceof Error ? error.message : String(error));
102
+ const fontFiles = new Map();
103
+ const fontFile = (file) => {
104
+ const path = join(fontsDir(), file);
105
+ let loading = fontFiles.get(path);
106
+ if (loading === undefined) {
107
+ loading = readFile(path).then((bytes) => new Uint8Array(bytes), (error) => {
108
+ fontFiles.delete(path); // not cached: the next call reads it again
109
+ throw new Error(`cannot read the font file ${path}: ${message(error)}`);
110
+ });
111
+ fontFiles.set(path, loading);
112
+ }
113
+ return loading;
114
+ };
115
+ let harfBuzz;
116
+ const subsetter = () => {
117
+ if (harfBuzz !== undefined)
118
+ return harfBuzz;
119
+ const loading = (async () => {
120
+ try {
121
+ const wasm = createRequire(import.meta.url).resolve("harfbuzzjs/dist/harfbuzz-subset.wasm");
122
+ const { instance } = await WebAssembly.instantiate(await readFile(wasm));
123
+ const hb = instance.exports;
124
+ hb._initialize();
125
+ return hb;
126
+ }
127
+ catch (error) {
128
+ throw new Error(`harfbuzzjs: cannot load the WebAssembly subsetter: ${message(error)}`);
129
+ }
130
+ })();
131
+ // Cached only once assigned, and cleared on rejection, so a failure thrown
132
+ // before the first await (the module cannot be resolved) is not cached either.
133
+ harfBuzz = loading;
134
+ loading.catch(() => {
135
+ if (harfBuzz === loading)
136
+ harfBuzz = undefined; // not cached: the next call loads it again
137
+ });
138
+ return loading;
139
+ };
140
+ // ---------- subsetting ----------
141
+ // The mode of the spike that proved the routine (card 300): HarfBuzz may use the copy in place; it is freed after.
142
+ const HB_MEMORY_MODE_WRITABLE = 2;
143
+ const HB_SUBSET_SETS_UNICODE = 1;
144
+ const HB_SUBSET_SETS_LAYOUT_FEATURE_TAG = 6;
145
+ const HB_SUBSET_FLAGS_NO_HINTING = 0x1;
146
+ // Kerning and the ligatures the text may use; every other layout feature is dropped.
147
+ const LAYOUT_FEATURES = ["kern", "liga", "calt"];
148
+ const tag = (name) => [...name].reduce((value, character) => ((value << 8) | character.charCodeAt(0)) >>> 0, 0);
149
+ /** A TrueType subset of `font` holding the glyphs of `characters` (deterministic: same input, same bytes). */
150
+ const subset = (hb, font, characters, file) => {
151
+ const input = hb.hb_subset_input_create_or_fail();
152
+ if (input === 0)
153
+ throw new Error(`harfbuzzjs: cannot create a subset input for ${file}`);
154
+ const data = hb.malloc(font.byteLength);
155
+ new Uint8Array(hb.memory.buffer).set(font, data);
156
+ const blob = hb.hb_blob_create(data, font.byteLength, HB_MEMORY_MODE_WRITABLE, 0, 0);
157
+ const face = hb.hb_face_create(blob, 0);
158
+ hb.hb_blob_destroy(blob);
159
+ try {
160
+ const unicodes = hb.hb_subset_input_set(input, HB_SUBSET_SETS_UNICODE);
161
+ for (const character of characters)
162
+ hb.hb_set_add(unicodes, character.codePointAt(0));
163
+ const features = hb.hb_subset_input_set(input, HB_SUBSET_SETS_LAYOUT_FEATURE_TAG);
164
+ hb.hb_set_clear(features);
165
+ for (const feature of LAYOUT_FEATURES)
166
+ hb.hb_set_add(features, tag(feature));
167
+ hb.hb_subset_input_set_flags(input, hb.hb_subset_input_get_flags(input) | HB_SUBSET_FLAGS_NO_HINTING);
168
+ const result = hb.hb_subset_or_fail(face, input);
169
+ if (result === 0)
170
+ throw new Error(`harfbuzzjs: subsetting ${file} failed`);
171
+ const out = hb.hb_face_reference_blob(result);
172
+ const offset = hb.hb_blob_get_data(out, 0);
173
+ const bytes = new Uint8Array(hb.memory.buffer).slice(offset, offset + hb.hb_blob_get_length(out));
174
+ hb.hb_blob_destroy(out);
175
+ hb.hb_face_destroy(result);
176
+ return bytes;
177
+ }
178
+ finally {
179
+ hb.hb_subset_input_destroy(input);
180
+ hb.hb_face_destroy(face);
181
+ hb.free(data);
182
+ }
183
+ };
184
+ /** Glyph count of a TrueType font (its `maxp` table); a subset with only `.notdef` draws none of its characters. */
185
+ const glyphCount = (font) => {
186
+ const view = new DataView(font.buffer, font.byteOffset, font.byteLength);
187
+ const tables = view.getUint16(4);
188
+ for (let i = 0; i < tables; i++) {
189
+ const record = 12 + i * 16;
190
+ if (view.getUint32(record) === tag("maxp"))
191
+ return view.getUint16(view.getUint32(record + 8) + 4);
192
+ }
193
+ return 0;
194
+ };
195
+ const fontFace = (face, font) => `@font-face{font-family:'${face.family}';font-weight:${face.range};font-style:normal;src:url(data:font/ttf;base64,${Buffer.from(font).toString("base64")}) format('truetype')}`;
196
+ /**
197
+ * The tree with the Source faces its drawn text uses embedded as subsets, in
198
+ * one `style` right after the root's `desc` (or as its first child). A tree
199
+ * with no face to embed resolves to the input; the input is never modified.
200
+ */
201
+ export const embedFonts = async (tree) => {
202
+ const used = new Map();
203
+ drawnText(tree, {}, used);
204
+ const faces = FACES.filter((face) => used.has(face));
205
+ if (faces.length === 0)
206
+ return tree;
207
+ const hb = await subsetter();
208
+ const rules = [];
209
+ for (const face of faces) {
210
+ const font = subset(hb, await fontFile(face.file), used.get(face), face.file);
211
+ if (glyphCount(font) > 1)
212
+ rules.push(fontFace(face, font));
213
+ }
214
+ if (rules.length === 0)
215
+ return tree;
216
+ const style = { tag: "style", attrs: {}, children: [rules.join("\n")] };
217
+ const at = tree.children.findIndex((child) => typeof child !== "string" && child.tag === "desc") + 1;
218
+ return { ...tree, children: [...tree.children.slice(0, at), style, ...tree.children.slice(at)] };
219
+ };