@sriinnu/fiche 0.18.0-bootstrap.0 → 0.19.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.
- package/CHANGELOG.md +134 -0
- package/LICENSE +22 -0
- package/NOTICE +13 -0
- package/PRIVACY.md +41 -0
- package/README.md +289 -0
- package/SECURITY.md +53 -0
- package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
- package/assets/SPLEEN_LICENSE.txt +24 -0
- package/assets/UNIFONT_LICENSE.txt +476 -0
- package/assets/fiche-logo-dark.svg +61 -0
- package/assets/fiche-logo-light.svg +61 -0
- package/assets/fiche-logo.svg +71 -0
- package/assets/fiche-mark.svg +48 -0
- package/bin/cli.js +7 -0
- package/bin/mcp.js +8 -0
- package/dist/calibrate.d.ts +30 -0
- package/dist/calibrate.js +588 -0
- package/dist/core/anthropic-vision.d.ts +28 -0
- package/dist/core/anthropic-vision.js +34 -0
- package/dist/core/applicability.d.ts +63 -0
- package/dist/core/applicability.js +151 -0
- package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono10.js +64 -0
- package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono12.js +64 -0
- package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
- package/dist/core/atlas-gray-jbmono14.js +64 -0
- package/dist/core/atlas-gray.d.ts +26 -0
- package/dist/core/atlas-gray.js +64 -0
- package/dist/core/atlas-jbmono10.d.ts +34 -0
- package/dist/core/atlas-jbmono10.js +71 -0
- package/dist/core/atlas-jbmono12.d.ts +34 -0
- package/dist/core/atlas-jbmono12.js +71 -0
- package/dist/core/atlas-jbmono14.d.ts +34 -0
- package/dist/core/atlas-jbmono14.js +71 -0
- package/dist/core/atlas.d.ts +34 -0
- package/dist/core/atlas.js +71 -0
- package/dist/core/baseline.d.ts +121 -0
- package/dist/core/baseline.js +200 -0
- package/dist/core/calibration.d.ts +86 -0
- package/dist/core/calibration.js +547 -0
- package/dist/core/casi-delta.d.ts +63 -0
- package/dist/core/casi-delta.js +1271 -0
- package/dist/core/claude-model-profiles.d.ts +53 -0
- package/dist/core/claude-model-profiles.js +160 -0
- package/dist/core/client-tool-round.d.ts +31 -0
- package/dist/core/client-tool-round.js +58 -0
- package/dist/core/codex-cache.d.ts +20 -0
- package/dist/core/codex-cache.js +59 -0
- package/dist/core/context-mmu.d.ts +350 -0
- package/dist/core/context-mmu.js +3028 -0
- package/dist/core/cpt-fit.d.ts +70 -0
- package/dist/core/cpt-fit.js +197 -0
- package/dist/core/env.d.ts +8 -0
- package/dist/core/env.js +15 -0
- package/dist/core/export.d.ts +127 -0
- package/dist/core/export.js +385 -0
- package/dist/core/factsheet.d.ts +77 -0
- package/dist/core/factsheet.js +494 -0
- package/dist/core/gemini-model-profiles.d.ts +20 -0
- package/dist/core/gemini-model-profiles.js +134 -0
- package/dist/core/google.d.ts +76 -0
- package/dist/core/google.js +1380 -0
- package/dist/core/gpt-model-profiles.d.ts +218 -0
- package/dist/core/gpt-model-profiles.js +570 -0
- package/dist/core/gpt-tokens.d.ts +14 -0
- package/dist/core/gpt-tokens.js +165 -0
- package/dist/core/history.d.ts +197 -0
- package/dist/core/history.js +1003 -0
- package/dist/core/index.d.ts +16 -0
- package/dist/core/index.js +16 -0
- package/dist/core/library.d.ts +80 -0
- package/dist/core/library.js +131 -0
- package/dist/core/measurement.d.ts +34 -0
- package/dist/core/measurement.js +280 -0
- package/dist/core/messages-chat-bridge.d.ts +23 -0
- package/dist/core/messages-chat-bridge.js +747 -0
- package/dist/core/messages-responses-bridge.d.ts +11 -0
- package/dist/core/messages-responses-bridge.js +893 -0
- package/dist/core/openai-history.d.ts +184 -0
- package/dist/core/openai-history.js +1279 -0
- package/dist/core/openai-savings.d.ts +57 -0
- package/dist/core/openai-savings.js +116 -0
- package/dist/core/openai.d.ts +68 -0
- package/dist/core/openai.js +2523 -0
- package/dist/core/pin.d.ts +199 -0
- package/dist/core/pin.js +1353 -0
- package/dist/core/png.d.ts +14 -0
- package/dist/core/png.js +188 -0
- package/dist/core/prefix-tape.d.ts +102 -0
- package/dist/core/prefix-tape.js +315 -0
- package/dist/core/price-id.d.ts +10 -0
- package/dist/core/price-id.js +26 -0
- package/dist/core/prices.generated.d.ts +36 -0
- package/dist/core/prices.generated.js +369 -0
- package/dist/core/pricing.d.ts +134 -0
- package/dist/core/pricing.js +335 -0
- package/dist/core/profile-base.d.ts +30 -0
- package/dist/core/profile-base.js +67 -0
- package/dist/core/provider-router.d.ts +51 -0
- package/dist/core/provider-router.js +121 -0
- package/dist/core/proxy.d.ts +252 -0
- package/dist/core/proxy.js +2929 -0
- package/dist/core/reader-tier.d.ts +24 -0
- package/dist/core/reader-tier.js +118 -0
- package/dist/core/render.d.ts +280 -0
- package/dist/core/render.js +1302 -0
- package/dist/core/request-guard.d.ts +31 -0
- package/dist/core/request-guard.js +126 -0
- package/dist/core/request-transform.d.ts +43 -0
- package/dist/core/request-transform.js +173 -0
- package/dist/core/schema-compiler.d.ts +64 -0
- package/dist/core/schema-compiler.js +1696 -0
- package/dist/core/schema-strip.d.ts +29 -0
- package/dist/core/schema-strip.js +173 -0
- package/dist/core/session-state.d.ts +219 -0
- package/dist/core/session-state.js +929 -0
- package/dist/core/stage-plugins.d.ts +45 -0
- package/dist/core/stage-plugins.js +205 -0
- package/dist/core/text-history.d.ts +74 -0
- package/dist/core/text-history.js +612 -0
- package/dist/core/text-hygiene.d.ts +160 -0
- package/dist/core/text-hygiene.js +2259 -0
- package/dist/core/toon.d.ts +29 -0
- package/dist/core/toon.js +425 -0
- package/dist/core/tracker.d.ts +223 -0
- package/dist/core/tracker.js +290 -0
- package/dist/core/transform.d.ts +589 -0
- package/dist/core/transform.js +3153 -0
- package/dist/core/types.d.ts +87 -0
- package/dist/core/types.js +8 -0
- package/dist/core/upstream-hosts.d.ts +127 -0
- package/dist/core/upstream-hosts.js +398 -0
- package/dist/core/vision-cost.d.ts +63 -0
- package/dist/core/vision-cost.js +137 -0
- package/dist/dashboard/fragments.d.ts +87 -0
- package/dist/dashboard/fragments.js +1515 -0
- package/dist/dashboard/types.d.ts +217 -0
- package/dist/dashboard/types.js +3 -0
- package/dist/dashboard/vendor.d.ts +3 -0
- package/dist/dashboard/vendor.js +6 -0
- package/dist/dashboard.d.ts +372 -0
- package/dist/dashboard.js +2731 -0
- package/dist/export-collect.d.ts +36 -0
- package/dist/export-collect.js +59 -0
- package/dist/file-tracker.d.ts +42 -0
- package/dist/file-tracker.js +234 -0
- package/dist/kosha-sync.d.ts +74 -0
- package/dist/kosha-sync.js +272 -0
- package/dist/launchd-socket.d.ts +22 -0
- package/dist/launchd-socket.js +210 -0
- package/dist/mcp/cli.d.ts +2 -0
- package/dist/mcp/cli.js +55 -0
- package/dist/mcp/server.d.ts +48 -0
- package/dist/mcp/server.js +987 -0
- package/dist/mmu-store.d.ts +31 -0
- package/dist/mmu-store.js +179 -0
- package/dist/node-fetch.d.ts +22 -0
- package/dist/node-fetch.js +489 -0
- package/dist/node.d.ts +9 -0
- package/dist/node.js +244396 -0
- package/dist/request-decoding.d.ts +30 -0
- package/dist/request-decoding.js +85 -0
- package/dist/sessions.d.ts +179 -0
- package/dist/sessions.js +837 -0
- package/dist/stats.d.ts +114 -0
- package/dist/stats.js +439 -0
- package/dist/turn-report.d.ts +65 -0
- package/dist/turn-report.js +724 -0
- package/dist/warp/app-launch.d.ts +26 -0
- package/dist/warp/app-launch.js +155 -0
- package/dist/warp/ca.d.ts +74 -0
- package/dist/warp/ca.js +416 -0
- package/dist/warp/connect.d.ts +42 -0
- package/dist/warp/connect.js +686 -0
- package/dist/warp/der.d.ts +57 -0
- package/dist/warp/der.js +151 -0
- package/dist/warp/index.d.ts +79 -0
- package/dist/warp/index.js +650 -0
- package/dist/warp/resolve.d.ts +12 -0
- package/dist/warp/resolve.js +49 -0
- package/dist/warp/route.d.ts +71 -0
- package/dist/warp/route.js +134 -0
- package/dist/worker.d.ts +71 -0
- package/dist/worker.js +174 -0
- package/docs/SECURITY_MODEL.md +84 -0
- package/package.json +115 -3
- package/plugins/fiche-companion/README.md +42 -0
- package/plugins/fiche-companion/assets/logo.svg +48 -0
- package/plugins/fiche-companion/hooks.json +11 -0
- package/plugins/fiche-companion/mcp_config.json +8 -0
- package/plugins/fiche-companion/plugin.json +18 -0
- package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
- package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
- package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
- package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
|
@@ -0,0 +1,1302 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Text → PNG renderer. Blits atlas glyphs into a grayscale framebuffer, then PNG-encodes.
|
|
3
|
+
* Iterates by codepoint so East Asian Wide chars (2-cell advance) and surrogate pairs handled correctly.
|
|
4
|
+
* Pages capped at 1568×728 px (1.14 MP): under both Anthropic tiers' limits, so every
|
|
5
|
+
* page bills at its raw 28-px patch count with no server-side downscale (WYSIWYG).
|
|
6
|
+
*/
|
|
7
|
+
import { readBrandEnv } from './env.js';
|
|
8
|
+
import { ATLAS_CELL_W, ATLAS_CELL_H, ATLAS_ASCENT, ATLAS_PIXELS, ATLAS_OFFSETS, ATLAS_WIDE_FLAGS, atlasRank, } from './atlas.js';
|
|
9
|
+
import { ATLAS_GRAY_CELL_W, ATLAS_GRAY_CELL_H, ATLAS_GRAY_ASCENT, ATLAS_GRAY_PIXELS, ATLAS_GRAY_OFFSETS, ATLAS_GRAY_WIDE_FLAGS, atlasGrayRank, } from './atlas-gray.js';
|
|
10
|
+
import { ATLAS_CELL_W as JBM10_CELL_W, ATLAS_CELL_H as JBM10_CELL_H, ATLAS_ASCENT as JBM10_ASCENT, ATLAS_PIXELS as JBM10_PIXELS, ATLAS_OFFSETS as JBM10_OFFSETS, ATLAS_WIDE_FLAGS as JBM10_WIDE_FLAGS, atlasRank as jbMono10Rank, } from './atlas-jbmono10.js';
|
|
11
|
+
import { ATLAS_GRAY_CELL_W as JBM10_GRAY_CELL_W, ATLAS_GRAY_CELL_H as JBM10_GRAY_CELL_H, ATLAS_GRAY_ASCENT as JBM10_GRAY_ASCENT, ATLAS_GRAY_PIXELS as JBM10_GRAY_PIXELS, ATLAS_GRAY_OFFSETS as JBM10_GRAY_OFFSETS, ATLAS_GRAY_WIDE_FLAGS as JBM10_GRAY_WIDE_FLAGS, atlasGrayRank as jbMono10GrayRank, } from './atlas-gray-jbmono10.js';
|
|
12
|
+
import { ATLAS_CELL_W as JBM12_CELL_W, ATLAS_CELL_H as JBM12_CELL_H, ATLAS_ASCENT as JBM12_ASCENT, ATLAS_PIXELS as JBM12_PIXELS, ATLAS_OFFSETS as JBM12_OFFSETS, ATLAS_WIDE_FLAGS as JBM12_WIDE_FLAGS, atlasRank as jbMono12Rank, } from './atlas-jbmono12.js';
|
|
13
|
+
import { ATLAS_GRAY_CELL_W as JBM12_GRAY_CELL_W, ATLAS_GRAY_CELL_H as JBM12_GRAY_CELL_H, ATLAS_GRAY_ASCENT as JBM12_GRAY_ASCENT, ATLAS_GRAY_PIXELS as JBM12_GRAY_PIXELS, ATLAS_GRAY_OFFSETS as JBM12_GRAY_OFFSETS, ATLAS_GRAY_WIDE_FLAGS as JBM12_GRAY_WIDE_FLAGS, atlasGrayRank as jbMono12GrayRank, } from './atlas-gray-jbmono12.js';
|
|
14
|
+
import { ATLAS_CELL_W as JBM14_CELL_W, ATLAS_CELL_H as JBM14_CELL_H, ATLAS_ASCENT as JBM14_ASCENT, ATLAS_PIXELS as JBM14_PIXELS, ATLAS_OFFSETS as JBM14_OFFSETS, ATLAS_WIDE_FLAGS as JBM14_WIDE_FLAGS, atlasRank as jbMono14Rank, } from './atlas-jbmono14.js';
|
|
15
|
+
import { ATLAS_GRAY_CELL_W as JBM14_GRAY_CELL_W, ATLAS_GRAY_CELL_H as JBM14_GRAY_CELL_H, ATLAS_GRAY_ASCENT as JBM14_GRAY_ASCENT, ATLAS_GRAY_PIXELS as JBM14_GRAY_PIXELS, ATLAS_GRAY_OFFSETS as JBM14_GRAY_OFFSETS, ATLAS_GRAY_WIDE_FLAGS as JBM14_GRAY_WIDE_FLAGS, atlasGrayRank as jbMono14GrayRank, } from './atlas-gray-jbmono14.js';
|
|
16
|
+
import { encodeGrayPng, encodeRgbPng } from './png.js';
|
|
17
|
+
export const DEFAULT_RENDER_FONT = 'spleen-5x8';
|
|
18
|
+
// Direct O(1) ASCII LUT ahead of glyph search — covers printable 0x20..0x7E (~99% of terminal text).
|
|
19
|
+
function buildAsciiRankLut(rankFn) {
|
|
20
|
+
const lut = new Int16Array(128).fill(-1);
|
|
21
|
+
for (let cp = 0x20; cp <= 0x7e; cp++) {
|
|
22
|
+
lut[cp] = rankFn(cp);
|
|
23
|
+
}
|
|
24
|
+
return lut;
|
|
25
|
+
}
|
|
26
|
+
const DEFAULT_ATLAS = {
|
|
27
|
+
bit: {
|
|
28
|
+
cellW: ATLAS_CELL_W,
|
|
29
|
+
cellH: ATLAS_CELL_H,
|
|
30
|
+
ascent: ATLAS_ASCENT,
|
|
31
|
+
pixels: ATLAS_PIXELS,
|
|
32
|
+
offsets: ATLAS_OFFSETS,
|
|
33
|
+
wideFlags: ATLAS_WIDE_FLAGS,
|
|
34
|
+
rank: atlasRank,
|
|
35
|
+
asciiRank: buildAsciiRankLut(atlasRank),
|
|
36
|
+
},
|
|
37
|
+
gray: {
|
|
38
|
+
cellW: ATLAS_GRAY_CELL_W,
|
|
39
|
+
cellH: ATLAS_GRAY_CELL_H,
|
|
40
|
+
ascent: ATLAS_GRAY_ASCENT,
|
|
41
|
+
pixels: ATLAS_GRAY_PIXELS,
|
|
42
|
+
offsets: ATLAS_GRAY_OFFSETS,
|
|
43
|
+
wideFlags: ATLAS_GRAY_WIDE_FLAGS,
|
|
44
|
+
rank: atlasGrayRank,
|
|
45
|
+
asciiRank: buildAsciiRankLut(atlasGrayRank),
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
const JBM10_ATLAS = {
|
|
49
|
+
bit: {
|
|
50
|
+
cellW: JBM10_CELL_W,
|
|
51
|
+
cellH: JBM10_CELL_H,
|
|
52
|
+
ascent: JBM10_ASCENT,
|
|
53
|
+
pixels: JBM10_PIXELS,
|
|
54
|
+
offsets: JBM10_OFFSETS,
|
|
55
|
+
wideFlags: JBM10_WIDE_FLAGS,
|
|
56
|
+
rank: jbMono10Rank,
|
|
57
|
+
asciiRank: buildAsciiRankLut(jbMono10Rank),
|
|
58
|
+
},
|
|
59
|
+
gray: {
|
|
60
|
+
cellW: JBM10_GRAY_CELL_W,
|
|
61
|
+
cellH: JBM10_GRAY_CELL_H,
|
|
62
|
+
ascent: JBM10_GRAY_ASCENT,
|
|
63
|
+
pixels: JBM10_GRAY_PIXELS,
|
|
64
|
+
offsets: JBM10_GRAY_OFFSETS,
|
|
65
|
+
wideFlags: JBM10_GRAY_WIDE_FLAGS,
|
|
66
|
+
rank: jbMono10GrayRank,
|
|
67
|
+
asciiRank: buildAsciiRankLut(jbMono10GrayRank),
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
const JBM12_ATLAS = {
|
|
71
|
+
bit: {
|
|
72
|
+
cellW: JBM12_CELL_W,
|
|
73
|
+
cellH: JBM12_CELL_H,
|
|
74
|
+
ascent: JBM12_ASCENT,
|
|
75
|
+
pixels: JBM12_PIXELS,
|
|
76
|
+
offsets: JBM12_OFFSETS,
|
|
77
|
+
wideFlags: JBM12_WIDE_FLAGS,
|
|
78
|
+
rank: jbMono12Rank,
|
|
79
|
+
asciiRank: buildAsciiRankLut(jbMono12Rank),
|
|
80
|
+
},
|
|
81
|
+
gray: {
|
|
82
|
+
cellW: JBM12_GRAY_CELL_W,
|
|
83
|
+
cellH: JBM12_GRAY_CELL_H,
|
|
84
|
+
ascent: JBM12_GRAY_ASCENT,
|
|
85
|
+
pixels: JBM12_GRAY_PIXELS,
|
|
86
|
+
offsets: JBM12_GRAY_OFFSETS,
|
|
87
|
+
wideFlags: JBM12_GRAY_WIDE_FLAGS,
|
|
88
|
+
rank: jbMono12GrayRank,
|
|
89
|
+
asciiRank: buildAsciiRankLut(jbMono12GrayRank),
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
const JBM14_ATLAS = {
|
|
93
|
+
bit: {
|
|
94
|
+
cellW: JBM14_CELL_W,
|
|
95
|
+
cellH: JBM14_CELL_H,
|
|
96
|
+
ascent: JBM14_ASCENT,
|
|
97
|
+
pixels: JBM14_PIXELS,
|
|
98
|
+
offsets: JBM14_OFFSETS,
|
|
99
|
+
wideFlags: JBM14_WIDE_FLAGS,
|
|
100
|
+
rank: jbMono14Rank,
|
|
101
|
+
asciiRank: buildAsciiRankLut(jbMono14Rank),
|
|
102
|
+
},
|
|
103
|
+
gray: {
|
|
104
|
+
cellW: JBM14_GRAY_CELL_W,
|
|
105
|
+
cellH: JBM14_GRAY_CELL_H,
|
|
106
|
+
ascent: JBM14_GRAY_ASCENT,
|
|
107
|
+
pixels: JBM14_GRAY_PIXELS,
|
|
108
|
+
offsets: JBM14_GRAY_OFFSETS,
|
|
109
|
+
wideFlags: JBM14_GRAY_WIDE_FLAGS,
|
|
110
|
+
rank: jbMono14GrayRank,
|
|
111
|
+
asciiRank: buildAsciiRankLut(jbMono14GrayRank),
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
function atlasSet(font) {
|
|
115
|
+
if (font === 'jetbrains-mono-10')
|
|
116
|
+
return JBM10_ATLAS;
|
|
117
|
+
if (font === 'jetbrains-mono-12')
|
|
118
|
+
return JBM12_ATLAS;
|
|
119
|
+
if (font === 'jetbrains-mono-14')
|
|
120
|
+
return JBM14_ATLAS;
|
|
121
|
+
return DEFAULT_ATLAS;
|
|
122
|
+
}
|
|
123
|
+
function fastBitRank(atlas, codepoint) {
|
|
124
|
+
return codepoint >= 0 && codepoint < 128 ? atlas.asciiRank[codepoint] : atlas.rank(codepoint);
|
|
125
|
+
}
|
|
126
|
+
function fastGrayRank(atlas, codepoint) {
|
|
127
|
+
return codepoint >= 0 && codepoint < 128 ? atlas.asciiRank[codepoint] : atlas.rank(codepoint);
|
|
128
|
+
}
|
|
129
|
+
function bitGlyph(codepoint, font) {
|
|
130
|
+
const selected = atlasSet(font).bit;
|
|
131
|
+
const rank = fastBitRank(selected, codepoint);
|
|
132
|
+
if (rank >= 0)
|
|
133
|
+
return { atlas: selected, rank };
|
|
134
|
+
if (selected !== DEFAULT_ATLAS.bit) {
|
|
135
|
+
const fallbackRank = fastBitRank(DEFAULT_ATLAS.bit, codepoint);
|
|
136
|
+
if (fallbackRank >= 0)
|
|
137
|
+
return { atlas: DEFAULT_ATLAS.bit, rank: fallbackRank };
|
|
138
|
+
}
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
function grayGlyph(codepoint, font) {
|
|
142
|
+
const selected = atlasSet(font).gray;
|
|
143
|
+
const rank = fastGrayRank(selected, codepoint);
|
|
144
|
+
if (rank >= 0)
|
|
145
|
+
return { atlas: selected, rank };
|
|
146
|
+
if (selected !== DEFAULT_ATLAS.gray) {
|
|
147
|
+
const fallbackRank = fastGrayRank(DEFAULT_ATLAS.gray, codepoint);
|
|
148
|
+
if (fallbackRank >= 0)
|
|
149
|
+
return { atlas: DEFAULT_ATLAS.gray, rank: fallbackRank };
|
|
150
|
+
}
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
/** Page-height ceiling. Measured (2026-07-01, count_tokens sweep, claude-sonnet-4-5 — see
|
|
154
|
+
* /tmp/pxexp/LEVER1-findings.md): the API downscales any image to fit BOTH long-edge ≤1568
|
|
155
|
+
* AND ~1.15 MP (≈1,143,750 px), then bills the exact 28-px patch count ⌈w/28⌉×⌈h/28⌉
|
|
156
|
+
* (1568×728 = 56×26 = 1456 tokens/image; the old ≈px/750 slope was the 28²=784 approximation).
|
|
157
|
+
* The old 1932×1932 page was billed at cap but resampled 0.555× → 5×8 glyphs reached the
|
|
158
|
+
* encoder at ~2.8×4.4 px. New page shape 1568×728 = 1,141,504 px fits both bounds →
|
|
159
|
+
* WYSIWYG for the vision encoder (also satisfies ≤2000 px/side for >20-image requests). */
|
|
160
|
+
export const MAX_HEIGHT_PX = 728;
|
|
161
|
+
/** Char budget for the static slab (system + tools + CLAUDE.md). Matches physical page
|
|
162
|
+
* capacity at 312 cols × 90 rows so image-count estimates track real pagination. */
|
|
163
|
+
export const READABLE_CHARS_PER_IMAGE = 28080;
|
|
164
|
+
/** Char budget for dense content (tool output, collapsed history). 312 cols × 90 rows = 28080
|
|
165
|
+
* chars fills the 1568×728 page. NOTE: verbatim recall of imaged text is unreliable at any size. */
|
|
166
|
+
export const DENSE_CONTENT_CHARS_PER_IMAGE = 28080;
|
|
167
|
+
export const DENSE_CONTENT_COLS = 312;
|
|
168
|
+
/** Bare 5×8 cell (no padding). A/B showed 5×8 beats 7×10 on dense JSON (4/5 vs 3/5 reads, 42% fewer tokens).
|
|
169
|
+
* Revert to {cellWBonus:2, cellHBonus:2} if misread rates rise. */
|
|
170
|
+
export const DENSE_RENDER_STYLE = { cellWBonus: 0, cellHBonus: 0, aa: true };
|
|
171
|
+
/** Anthropic static slab uses the same measured 312-column no-resize geometry. */
|
|
172
|
+
export const ANTHROPIC_SLAB_COLS = DENSE_CONTENT_COLS;
|
|
173
|
+
/** Default columns for the static slab. 312 × 5 px + 8 px pad = 1568 px — exactly the API's
|
|
174
|
+
* long-edge bound (313 cols = 1573 px would trigger a 0.997× resample, blurring every glyph). */
|
|
175
|
+
const DEFAULT_COLS = ANTHROPIC_SLAB_COLS;
|
|
176
|
+
/** Horizontal padding (left + right each), px. Exported for transform.ts token-cost math. */
|
|
177
|
+
export const PAD_X = 4;
|
|
178
|
+
/** Vertical padding (top + bottom each), px. Exported for transform.ts token-cost math. */
|
|
179
|
+
export const PAD_Y = 4;
|
|
180
|
+
/** Production ships bare 5×8 atlas cell (reflow+grayscale+inimage instruction band
|
|
181
|
+
* brought 5×8 to 98.95% OCR accuracy on Opus 4.7, matching or beating padded cells).
|
|
182
|
+
* RenderStyle.cellWBonus/cellHBonus override per-eval only. */
|
|
183
|
+
export const DEFAULT_CELL_W_BONUS = 0;
|
|
184
|
+
export const DEFAULT_CELL_H_BONUS = 0;
|
|
185
|
+
/** Effective cell pixel dimensions. transform.ts derives image-budget math from these. */
|
|
186
|
+
export const CELL_W = ATLAS_CELL_W + DEFAULT_CELL_W_BONUS;
|
|
187
|
+
export const CELL_H = ATLAS_CELL_H + DEFAULT_CELL_H_BONUS;
|
|
188
|
+
/** Visual rows per image: `floor((MAX_HEIGHT_PX − 2·PAD_Y) / CELL_H)`. Derived
|
|
189
|
+
* from the cell geometry above so break-even math auto-tracks it. */
|
|
190
|
+
export const LINES_PER_IMAGE = Math.max(1, Math.floor((MAX_HEIGHT_PX - 2 * PAD_Y) / CELL_H));
|
|
191
|
+
/** Real char capacity of one page AT A GIVEN COLUMN WIDTH.
|
|
192
|
+
*
|
|
193
|
+
* Lives here, next to the geometry it is derived from, because every caller that
|
|
194
|
+
* budgets images must price pages at the width it actually renders at. The
|
|
195
|
+
* DENSE_CONTENT_CHARS_PER_IMAGE constant is only correct for DENSE_CONTENT_COLS
|
|
196
|
+
* (312×90); using it while rendering at, say, COLS=100 overstates capacity 3.1×,
|
|
197
|
+
* so an image budget clears a plan that then emits 3× the images — the request
|
|
198
|
+
* blows the API's per-request limit and comes back 500. Always pass the cols the
|
|
199
|
+
* renderer will actually use. */
|
|
200
|
+
export function maxCharsPerImage(cols) {
|
|
201
|
+
return Math.min(Math.max(1, cols) * LINES_PER_IMAGE, READABLE_CHARS_PER_IMAGE);
|
|
202
|
+
}
|
|
203
|
+
export function renderCellWidth(style = {}) {
|
|
204
|
+
const atlas = style.aa === true ? atlasSet(style.font).gray : atlasSet(style.font).bit;
|
|
205
|
+
return Math.max(1, atlas.cellW + Math.floor(style.cellWBonus ?? DEFAULT_CELL_W_BONUS));
|
|
206
|
+
}
|
|
207
|
+
export function renderCellHeight(style = {}) {
|
|
208
|
+
const atlas = style.aa === true ? atlasSet(style.font).gray : atlasSet(style.font).bit;
|
|
209
|
+
return atlas.cellH + Math.max(0, Math.floor(style.cellHBonus ?? DEFAULT_CELL_H_BONUS));
|
|
210
|
+
}
|
|
211
|
+
// --- column-aware wrapping -------------------------------------------------
|
|
212
|
+
/** Visual width of a codepoint in cells (1 = Latin, 2 = East Asian Wide).
|
|
213
|
+
* Missing codepoints advance 1 cell so wrap math stays stable. */
|
|
214
|
+
function cellsFor(codepoint, markerScale = 1, font = DEFAULT_RENDER_FONT) {
|
|
215
|
+
// Enlarged ↵ occupies markerScale cells of wrap budget instead of 1.
|
|
216
|
+
if (codepoint === NL_SENTINEL_CP && markerScale > 1)
|
|
217
|
+
return markerScale;
|
|
218
|
+
const selected = atlasSet(font).bit;
|
|
219
|
+
let rank = fastBitRank(selected, codepoint);
|
|
220
|
+
if (rank >= 0)
|
|
221
|
+
return selected.wideFlags[rank] === 1 ? 2 : 1;
|
|
222
|
+
if (selected !== DEFAULT_ATLAS.bit) {
|
|
223
|
+
rank = fastBitRank(DEFAULT_ATLAS.bit, codepoint);
|
|
224
|
+
if (rank >= 0)
|
|
225
|
+
return DEFAULT_ATLAS.bit.wideFlags[rank] === 1 ? 2 : 1;
|
|
226
|
+
}
|
|
227
|
+
return 1;
|
|
228
|
+
}
|
|
229
|
+
const TAB_WIDTH = 4; // standard 4-space tab stops (logs, code, tool output are all 4-oriented)
|
|
230
|
+
/** Strip trailing whitespace per line and collapse 4+ consecutive \n to 3.
|
|
231
|
+
* Does NOT touch mid-line spaces or leading indent — structure is preserved. */
|
|
232
|
+
export function minifyForRender(text) {
|
|
233
|
+
return text
|
|
234
|
+
.split('\n')
|
|
235
|
+
.map(trimLineEnd)
|
|
236
|
+
.join('\n')
|
|
237
|
+
.replace(/\n{4,}/g, '\n\n\n'); // 4+ \n → 3 \n (max 2 blank lines)
|
|
238
|
+
}
|
|
239
|
+
/** Drop trailing spaces and tabs from one line.
|
|
240
|
+
* Scanned backwards: /[ \t]+$/ retries from every position in a long run of
|
|
241
|
+
* spaces when the line does not end in one, which is quadratic on one very
|
|
242
|
+
* long line. */
|
|
243
|
+
function trimLineEnd(line) {
|
|
244
|
+
let end = line.length;
|
|
245
|
+
while (end > 0) {
|
|
246
|
+
const c = line.charCodeAt(end - 1);
|
|
247
|
+
if (c !== 32 && c !== 9)
|
|
248
|
+
break;
|
|
249
|
+
end -= 1;
|
|
250
|
+
}
|
|
251
|
+
return end === line.length ? line : line.slice(0, end);
|
|
252
|
+
}
|
|
253
|
+
// --- R3 reflow -------------------------------------------------------------
|
|
254
|
+
//
|
|
255
|
+
// Marks each original hard newline with U+21B5 ↵ so the model can distinguish
|
|
256
|
+
// real newlines from soft-wraps. Lossless at the transform level (see dereflow):
|
|
257
|
+
// the only mutation is the minifyForRender pass. Wrap-the-line measured ~99%
|
|
258
|
+
// OCR fidelity vs ~78% for naive dense packing.
|
|
259
|
+
/** U+21B5 ↵ sentinel for original hard newlines in reflowed text. In full-bmp atlas via Unifont. */
|
|
260
|
+
export const NL_SENTINEL = '↵';
|
|
261
|
+
const NL_SENTINEL_CP = 0x21b5; // precomputed for hot-path comparisons
|
|
262
|
+
/** Look-alike (U+23CE ⏎) for a ↵ that was ALREADY in the source content — distinct from
|
|
263
|
+
* the U+21B5 ↵ we insert for newlines. reflow() bails when its input already contains the
|
|
264
|
+
* sentinel; that's vanishingly rare for normal content but common when the content is about
|
|
265
|
+
* inkling itself (rendered dumps, OCR, this very transcript). {@link neutralizeSentinel}
|
|
266
|
+
* swaps pre-existing sentinels for this glyph in RENDER-PREP only, so reflow can pack
|
|
267
|
+
* newlines instead of bailing to a raw, unpacked render. Originals are preserved verbatim
|
|
268
|
+
* elsewhere (recordRecoverable / cache-stable history), and reflow()'s own round-trip
|
|
269
|
+
* contract — and its tests — are left untouched. */
|
|
270
|
+
export const NL_SENTINEL_LITERAL = '⏎'; // U+23CE
|
|
271
|
+
export function neutralizeSentinel(text) {
|
|
272
|
+
return text.indexOf(NL_SENTINEL) >= 0
|
|
273
|
+
? text.split(NL_SENTINEL).join(NL_SENTINEL_LITERAL)
|
|
274
|
+
: text;
|
|
275
|
+
}
|
|
276
|
+
/** colorCycle palette: four dark ink-on-white hues for per-character boundary cues. */
|
|
277
|
+
const GLYPH_PALETTE = [
|
|
278
|
+
[20, 20, 20], // near-black
|
|
279
|
+
[20, 40, 160], // dark blue
|
|
280
|
+
[150, 20, 20], // dark red
|
|
281
|
+
[20, 110, 40], // dark green
|
|
282
|
+
];
|
|
283
|
+
/** colorByRole palette, indexed by slot-1. Only the boundary TAGS are tinted;
|
|
284
|
+
* body content stays black. [<user> tags, <assistant> tags]. */
|
|
285
|
+
export const ROLE_PALETTE = [
|
|
286
|
+
[150, 20, 20], // 1: <user> / </user> — dark red (81.3% contrast on white)
|
|
287
|
+
[20, 40, 160], // 2: <assistant> / </assistant> — dark blue (82.6% contrast on white)
|
|
288
|
+
];
|
|
289
|
+
const ROLE_SLOT_USER = 1;
|
|
290
|
+
const ROLE_SLOT_ASSISTANT = 2;
|
|
291
|
+
/**
|
|
292
|
+
* Slot markers for the parallel "slot string" — the structure-through mechanism
|
|
293
|
+
* that replaces the old parse-back. A slot string is a width-preserving copy of
|
|
294
|
+
* the rendered text: every structural role-tag character is swapped for one of
|
|
295
|
+
* these control codes, and every other codepoint is copied verbatim. Because the
|
|
296
|
+
* markers are width-1 (exactly like the ASCII tag chars they stand in for), the
|
|
297
|
+
* existing reflow / wrapLines / paging transforms mutate the slot string in lock-
|
|
298
|
+
* step with the text — only whitespace/newlines move, and those are slot 0 in
|
|
299
|
+
* both. The renderer then reads role attribution BY POSITION instead of trying to
|
|
300
|
+
* re-find "<user>" in flattened text (which miscolors a body that literally quotes
|
|
301
|
+
* a tag). The structure is known at serialize time and carried, never guessed.
|
|
302
|
+
*/
|
|
303
|
+
export const SLOT_MARK_USER = String.fromCharCode(1);
|
|
304
|
+
export const SLOT_MARK_ASSISTANT = String.fromCharCode(2);
|
|
305
|
+
const SLOT_MARK_RE = new RegExp('[' + SLOT_MARK_USER + SLOT_MARK_ASSISTANT + ']', 'g');
|
|
306
|
+
/** Map a slot-string codepoint to its color slot (0 = body / black ink). */
|
|
307
|
+
function slotForMarkCp(cp) {
|
|
308
|
+
if (cp === 0x0001)
|
|
309
|
+
return ROLE_SLOT_USER;
|
|
310
|
+
if (cp === 0x0002)
|
|
311
|
+
return ROLE_SLOT_ASSISTANT;
|
|
312
|
+
return 0;
|
|
313
|
+
}
|
|
314
|
+
/** Replacement for a literal slot-marker found in body content. Must (a) map to slot 0
|
|
315
|
+
* like body (it's not 0x01/0x02), (b) share the markers' width class so wrapLines splits
|
|
316
|
+
* the slot identically to the text, and (c) NOT be ' '/'\t' — minifyForRender strips
|
|
317
|
+
* trailing spaces/tabs, which would shorten the slot line (where a body \x01 sat) but not
|
|
318
|
+
* the text line (\x01 isn't stripped), desyncing the two and smearing role hues. A C0
|
|
319
|
+
* control char satisfies all three. */
|
|
320
|
+
const SLOT_NEUTRAL = '\u0003'; // U+0003 ETX — non-marker C0 control
|
|
321
|
+
/** Width-preserving slot-0 copy of body text: identical codepoints (so wrap math is
|
|
322
|
+
* unchanged) but with any literal slot-marker control char neutralized. These are rare in
|
|
323
|
+
* real content but DO occur (e.g. binary-ish tool output that gets collapsed into history),
|
|
324
|
+
* so the replacement is width- and strip-equivalent to the marker — never a space, which
|
|
325
|
+
* the minifier would strip and misalign. Guarantees body can't forge a role hue. */
|
|
326
|
+
export function slotCopyBody(body) {
|
|
327
|
+
if (body.indexOf(SLOT_MARK_USER) < 0 && body.indexOf(SLOT_MARK_ASSISTANT) < 0)
|
|
328
|
+
return body;
|
|
329
|
+
return body.replace(SLOT_MARK_RE, SLOT_NEUTRAL);
|
|
330
|
+
}
|
|
331
|
+
/** Build the slot-string segment for one role-wrapped turn, mirroring the text
|
|
332
|
+
* form `<${tag}>\n${body}\n</${tag}>`: marker chars over the open/close tags,
|
|
333
|
+
* a verbatim slot-0 copy of the body. `mark` is the role's slot marker. */
|
|
334
|
+
export function roleSlotSegment(tag, body, mark, attr = '') {
|
|
335
|
+
// `attr` (e.g. ` t="37"`) is part of the OPEN tag, so the marker run must cover it too —
|
|
336
|
+
// the renderer colors by codepoint position, so a short marker run would un-tint the
|
|
337
|
+
// attribute and break alignment. Width is identical to the text tag by construction.
|
|
338
|
+
const open = `<${tag}${attr}>`;
|
|
339
|
+
const close = `</${tag}>`;
|
|
340
|
+
return `${mark.repeat(open.length)}\n${slotCopyBody(body)}\n${mark.repeat(close.length)}`;
|
|
341
|
+
}
|
|
342
|
+
/** Minify + tab-expand + join lines with ↵ sentinel. Returns null if text already
|
|
343
|
+
* contains ↵ (caller falls back to non-reflow path; vanishingly rare in practice). */
|
|
344
|
+
export function reflow(text) {
|
|
345
|
+
if (text.indexOf(NL_SENTINEL) >= 0)
|
|
346
|
+
return null;
|
|
347
|
+
return minifyForRender(text)
|
|
348
|
+
.split('\n')
|
|
349
|
+
.map(expandTabsInLine)
|
|
350
|
+
.join(NL_SENTINEL);
|
|
351
|
+
}
|
|
352
|
+
/** Inverse of reflow: ↵ → '\n'. dereflow(reflow(text)) === minifyForRender(text) with tabs expanded. */
|
|
353
|
+
export function dereflow(reflowed) {
|
|
354
|
+
return reflowed.split(NL_SENTINEL).join('\n');
|
|
355
|
+
}
|
|
356
|
+
// --- atlas-miss escaping -----------------------------------------------------
|
|
357
|
+
//
|
|
358
|
+
// Codepoints absent from the atlas used to render as blank cells (droppedChars
|
|
359
|
+
// metrics). Emoji and other astral glyphs can't be DRAWN at 5×8 px, but they
|
|
360
|
+
// can be PRESERVED: substitute a deterministic textual escape (`[U+HEX]`) before
|
|
361
|
+
// wrap, so the model reads the codepoint instead of a gap. Applied at the same layer
|
|
362
|
+
// as tab expansion (wrapLines + measureContentCols), so wrap math and canvas
|
|
363
|
+
// measurement stay consistent. Pure string→string ⇒ renders stay deterministic.
|
|
364
|
+
/** Pure-ASCII delimiters: `🔥` → `[U+1F525]`. ASCII is the one range guaranteed
|
|
365
|
+
* present in BOTH atlases (mathematical white brackets U+27E6/7 were tried first
|
|
366
|
+
* and are absent from each — the "full-bmp" note on NL_SENTINEL overstates real
|
|
367
|
+
* coverage). ASCII output also makes idempotency structural: an escaped line
|
|
368
|
+
* contains no atlas misses, so a second pass is a no-op. `[U+…]` can collide
|
|
369
|
+
* with literal source text discussing codepoints; the escape is for model
|
|
370
|
+
* legibility, not machine round-trip, so the ambiguity is acceptable. */
|
|
371
|
+
export const GLYPH_ESCAPE_OPEN = '[U+';
|
|
372
|
+
export const GLYPH_ESCAPE_CLOSE = ']';
|
|
373
|
+
/** Codepoints that stay DROPPED (blank cell) rather than escaped. Escaping these
|
|
374
|
+
* would add noise, not information — they're modifiers/invisibles, not content.
|
|
375
|
+
* C0 additionally MUST keep width-1: the parallel slot string carries \x01/\x02
|
|
376
|
+
* role markers and \x03 neutral (see SLOT_MARK_*), and escaping them would
|
|
377
|
+
* desync slot/text alignment and smear role hues. */
|
|
378
|
+
function isEscapeExempt(cp) {
|
|
379
|
+
if (cp < 0x20)
|
|
380
|
+
return true; // C0 controls (slot markers; \t is expanded before we run)
|
|
381
|
+
if (cp >= 0x7f && cp <= 0x9f)
|
|
382
|
+
return true; // DEL + C1 controls
|
|
383
|
+
if (cp >= 0x0300 && cp <= 0x036f)
|
|
384
|
+
return true; // combining diacritics
|
|
385
|
+
if (cp === 0x200b || cp === 0x200c || cp === 0x200d || cp === 0x2060 || cp === 0xfeff)
|
|
386
|
+
return true; // zero-width / word-joiner / BOM
|
|
387
|
+
if (cp >= 0xfe00 && cp <= 0xfe0f)
|
|
388
|
+
return true; // variation selectors (emoji presentation)
|
|
389
|
+
if (cp >= 0xe0100 && cp <= 0xe01ef)
|
|
390
|
+
return true; // variation selectors supplement
|
|
391
|
+
return false;
|
|
392
|
+
}
|
|
393
|
+
/** Blank cells reserved on EACH side of the ↵ marker when it is laid out.
|
|
394
|
+
* Without them the marker carries no separation at all, so the value ending one
|
|
395
|
+
* source line and the identifier starting the next fuse into a single visual
|
|
396
|
+
* token (`00014↵L00003`) — a reader that transcribes the image perfectly still
|
|
397
|
+
* attributes line-trailing values to the FOLLOWING line. One cell per side makes
|
|
398
|
+
* the strongest boundary in the source separate at least as strongly as an
|
|
399
|
+
* intra-line word gap. */
|
|
400
|
+
export const NL_SENTINEL_PAD_CELLS = 1;
|
|
401
|
+
/** Surround every ↵ with blank cells so it reads as its own token. Pure
|
|
402
|
+
* string→string, applied at the same layer as tab expansion and atlas-miss
|
|
403
|
+
* escaping (wrapLines + measureContentCols), so wrap math and canvas
|
|
404
|
+
* measurement stay consistent. Runs on the render copy only: `reflow` still
|
|
405
|
+
* emits the bare sentinel, so the reflow/dereflow round-trip is untouched.
|
|
406
|
+
* Fast path allocates nothing for text with no markers (every non-reflowed
|
|
407
|
+
* render). */
|
|
408
|
+
export function padNewlineMarkers(line) {
|
|
409
|
+
if (line.indexOf(NL_SENTINEL) < 0)
|
|
410
|
+
return line; // fast path
|
|
411
|
+
const pad = ' '.repeat(NL_SENTINEL_PAD_CELLS);
|
|
412
|
+
return line.split(NL_SENTINEL).join(pad + NL_SENTINEL + pad);
|
|
413
|
+
}
|
|
414
|
+
/** Replace atlas-missing codepoints with `[U+HEX]` (uppercase hex — e.g.
|
|
415
|
+
* 🔥 → `[U+1F525]`). Lossless for non-exempt misses (hex → codepoint) and
|
|
416
|
+
* idempotent: the escape spells only atlas-present chars, so a second pass is
|
|
417
|
+
* a no-op. Fast path allocates nothing when every codepoint is in the atlas. */
|
|
418
|
+
export function escapeMissingGlyphs(line) {
|
|
419
|
+
let out = null; // lazily materialized on first miss
|
|
420
|
+
let i = 0;
|
|
421
|
+
for (const ch of line) {
|
|
422
|
+
const cp = ch.codePointAt(0);
|
|
423
|
+
if (atlasRank(cp) < 0 && !isEscapeExempt(cp)) {
|
|
424
|
+
if (out === null)
|
|
425
|
+
out = line.slice(0, i);
|
|
426
|
+
out += GLYPH_ESCAPE_OPEN + cp.toString(16).toUpperCase() + GLYPH_ESCAPE_CLOSE;
|
|
427
|
+
}
|
|
428
|
+
else if (out !== null) {
|
|
429
|
+
out += ch;
|
|
430
|
+
}
|
|
431
|
+
i += ch.length;
|
|
432
|
+
}
|
|
433
|
+
return out ?? line;
|
|
434
|
+
}
|
|
435
|
+
/** Expand \t to U+2192 → + padding to the next TAB_WIDTH stop. Visible marker lets the
|
|
436
|
+
* model distinguish indent-spaces from intentional-spaces. Wide CJK chars count as 2 cols.
|
|
437
|
+
* U+0009 is absent from the atlas (control codepoint), so without this every tab was a drop. */
|
|
438
|
+
export function expandTabsInLine(line) {
|
|
439
|
+
if (line.indexOf('\t') < 0)
|
|
440
|
+
return line; // fast path
|
|
441
|
+
let out = '';
|
|
442
|
+
let col = 0;
|
|
443
|
+
for (const ch of line) {
|
|
444
|
+
if (ch === '\t') {
|
|
445
|
+
const span = TAB_WIDTH - (col % TAB_WIDTH);
|
|
446
|
+
out += '→'; // visible tab marker (1 col)
|
|
447
|
+
if (span > 1)
|
|
448
|
+
out += ' '.repeat(span - 1); // pad to next stop
|
|
449
|
+
col += span;
|
|
450
|
+
}
|
|
451
|
+
else {
|
|
452
|
+
out += ch;
|
|
453
|
+
col += cellsFor(ch.codePointAt(0));
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
return out;
|
|
457
|
+
}
|
|
458
|
+
/** Visual width of a line in cells. Wide CJK = 2; enlarged ↵ = markerScale. */
|
|
459
|
+
export function measureLineCols(line, markerScale = 1, font = DEFAULT_RENDER_FONT) {
|
|
460
|
+
let w = 0;
|
|
461
|
+
for (const ch of line)
|
|
462
|
+
w += cellsFor(ch.codePointAt(0), markerScale, font);
|
|
463
|
+
return w;
|
|
464
|
+
}
|
|
465
|
+
/** Always renders at full canvas width. Signature kept for transform.ts compatibility; returns cols unchanged. */
|
|
466
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
467
|
+
export function shrinkColsToContent(text, cols, markerScale = 1, font = DEFAULT_RENDER_FONT) {
|
|
468
|
+
// Real content-width measurement — delegates to measureContentCols (was historically a
|
|
469
|
+
// no-op stub). The proxy's cost gate AND renderer both call this, so sizing the canvas to
|
|
470
|
+
// the widest line here makes the proxy match the SDK/export path (renderTextToImages),
|
|
471
|
+
// which already uses measureContentCols. Never narrows below the widest line ⇒ row count
|
|
472
|
+
// (and thus image/paging count) is unchanged; only the canvas WIDTH (pixel cost) drops.
|
|
473
|
+
return measureContentCols(text, cols, markerScale, font);
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Real content-width measurement (the capability `shrinkColsToContent` historically
|
|
477
|
+
* stubbed out): the display width, in cols, of the widest line in `text`, capped at
|
|
478
|
+
* `maxCols`. Lets a renderer size a narrow canvas to short-line content (e.g. code)
|
|
479
|
+
* instead of padding every page to full width. Pure function of (text, maxCols) →
|
|
480
|
+
* deterministic width → cache-prefix-safe. Tabs are expanded so the measured width
|
|
481
|
+
* matches what the renderer actually lays out.
|
|
482
|
+
*/
|
|
483
|
+
export function measureContentCols(text, maxCols, markerScale = 1, font = DEFAULT_RENDER_FONT) {
|
|
484
|
+
const cap = Math.max(1, maxCols | 0);
|
|
485
|
+
const selected = atlasSet(font).bit;
|
|
486
|
+
const defaultBit = DEFAULT_ATLAS.bit;
|
|
487
|
+
const len = text.length;
|
|
488
|
+
let widest = 1;
|
|
489
|
+
// Track `col` and `tabCol` independently so NL_SENTINEL keeps the same tab stops as wrapLines.
|
|
490
|
+
let col = 0;
|
|
491
|
+
let tabCol = 0;
|
|
492
|
+
let i = 0;
|
|
493
|
+
while (i < len) {
|
|
494
|
+
const code = text.charCodeAt(i);
|
|
495
|
+
if (code === 10) {
|
|
496
|
+
if (col > widest)
|
|
497
|
+
widest = col;
|
|
498
|
+
col = 0;
|
|
499
|
+
tabCol = 0;
|
|
500
|
+
i += 1;
|
|
501
|
+
continue;
|
|
502
|
+
}
|
|
503
|
+
if (code >= 0x20 && code <= 0x7e) {
|
|
504
|
+
let w = 1;
|
|
505
|
+
const r = selected.asciiRank[code];
|
|
506
|
+
if (r >= 0) {
|
|
507
|
+
w = selected.wideFlags[r] === 1 ? 2 : 1;
|
|
508
|
+
}
|
|
509
|
+
else if (selected !== defaultBit) {
|
|
510
|
+
const dr = defaultBit.asciiRank[code];
|
|
511
|
+
if (dr >= 0)
|
|
512
|
+
w = defaultBit.wideFlags[dr] === 1 ? 2 : 1;
|
|
513
|
+
}
|
|
514
|
+
col += w;
|
|
515
|
+
tabCol += w;
|
|
516
|
+
if (col >= cap)
|
|
517
|
+
return cap;
|
|
518
|
+
i += 1;
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
if (code === 9) {
|
|
522
|
+
const span = TAB_WIDTH - (tabCol % TAB_WIDTH);
|
|
523
|
+
col += span;
|
|
524
|
+
tabCol += span;
|
|
525
|
+
if (col >= cap)
|
|
526
|
+
return cap;
|
|
527
|
+
i += 1;
|
|
528
|
+
continue;
|
|
529
|
+
}
|
|
530
|
+
const cp = text.codePointAt(i);
|
|
531
|
+
const step = cp > 0xffff ? 2 : 1;
|
|
532
|
+
if (cp === NL_SENTINEL_CP) {
|
|
533
|
+
col += 2 * NL_SENTINEL_PAD_CELLS + (markerScale > 1 ? markerScale : 1);
|
|
534
|
+
tabCol += 1;
|
|
535
|
+
}
|
|
536
|
+
else if (fastBitRank(defaultBit, cp) < 0 && !isEscapeExempt(cp)) {
|
|
537
|
+
const escWidth = 4 + cp.toString(16).length;
|
|
538
|
+
col += escWidth;
|
|
539
|
+
tabCol += cellsFor(cp, 1, font);
|
|
540
|
+
}
|
|
541
|
+
else {
|
|
542
|
+
col += cellsFor(cp, markerScale, font);
|
|
543
|
+
tabCol += cellsFor(cp, 1, font);
|
|
544
|
+
}
|
|
545
|
+
if (col >= cap)
|
|
546
|
+
return cap;
|
|
547
|
+
i += step;
|
|
548
|
+
}
|
|
549
|
+
if (col > widest)
|
|
550
|
+
widest = col;
|
|
551
|
+
return Math.min(cap, widest);
|
|
552
|
+
}
|
|
553
|
+
export function wrapLines(text, cols, markerScale = 1, font = DEFAULT_RENDER_FONT, padMarkers = true) {
|
|
554
|
+
const out = [];
|
|
555
|
+
const minified = minifyForRender(text);
|
|
556
|
+
for (const rawWithTabs of minified.split('\n')) {
|
|
557
|
+
// Unlike tab expansion and escaping, marker padding is not idempotent, so rows
|
|
558
|
+
// that already went through here are re-wrapped with `padMarkers = false`.
|
|
559
|
+
const expanded = expandTabsInLine(rawWithTabs);
|
|
560
|
+
const raw = escapeMissingGlyphs(padMarkers ? padNewlineMarkers(expanded) : expanded);
|
|
561
|
+
if (raw.length === 0) {
|
|
562
|
+
out.push('');
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
let cur = '';
|
|
566
|
+
let curCols = 0;
|
|
567
|
+
// Codepoint iteration handles surrogate pairs as one unit.
|
|
568
|
+
// ↵ is treated as an inline glyph — it never forces a row break.
|
|
569
|
+
for (const ch of raw) {
|
|
570
|
+
const cp = ch.codePointAt(0);
|
|
571
|
+
const w = cellsFor(cp, markerScale, font);
|
|
572
|
+
if (curCols + w > cols) {
|
|
573
|
+
out.push(cur);
|
|
574
|
+
cur = ch;
|
|
575
|
+
curCols = w;
|
|
576
|
+
}
|
|
577
|
+
else {
|
|
578
|
+
cur += ch;
|
|
579
|
+
curCols += w;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
if (cur.length > 0)
|
|
583
|
+
out.push(cur);
|
|
584
|
+
}
|
|
585
|
+
return out;
|
|
586
|
+
}
|
|
587
|
+
function splitWrappedLinesIntoReadablePages(lines, maxLines, maxChars = READABLE_CHARS_PER_IMAGE) {
|
|
588
|
+
const pages = [];
|
|
589
|
+
let cur = [];
|
|
590
|
+
let curChars = 0;
|
|
591
|
+
const lineLimit = Math.max(1, maxLines | 0);
|
|
592
|
+
const charLimit = Math.max(1, maxChars | 0);
|
|
593
|
+
for (const line of lines) {
|
|
594
|
+
const lineChars = line.length + (cur.length > 0 ? 1 : 0);
|
|
595
|
+
if (cur.length > 0 &&
|
|
596
|
+
(cur.length >= lineLimit || curChars + lineChars > charLimit)) {
|
|
597
|
+
pages.push(cur);
|
|
598
|
+
cur = [];
|
|
599
|
+
curChars = 0;
|
|
600
|
+
}
|
|
601
|
+
cur.push(line);
|
|
602
|
+
curChars += line.length + (cur.length > 1 ? 1 : 0);
|
|
603
|
+
}
|
|
604
|
+
if (cur.length > 0)
|
|
605
|
+
pages.push(cur);
|
|
606
|
+
return pages.length > 0 ? pages : [[]];
|
|
607
|
+
}
|
|
608
|
+
function readableLinesPerColumn(cols) {
|
|
609
|
+
return Math.max(1, Math.floor(READABLE_CHARS_PER_IMAGE / Math.max(1, cols)));
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* Blit a 1-bit glyph at pixel (x, y). Returns cells advanced (1 or 2), or 0 if absent
|
|
613
|
+
* from atlas — caller must still advance 1 cell to keep wrap math stable.
|
|
614
|
+
*/
|
|
615
|
+
function blitGlyph(fb, fbW, x, y, codepoint, font = DEFAULT_RENDER_FONT, markerMask = null) {
|
|
616
|
+
const glyph = bitGlyph(codepoint, font);
|
|
617
|
+
if (!glyph)
|
|
618
|
+
return 0;
|
|
619
|
+
const { atlas, rank } = glyph;
|
|
620
|
+
const wide = atlas.wideFlags[rank] === 1;
|
|
621
|
+
const srcW = wide ? 2 * atlas.cellW : atlas.cellW;
|
|
622
|
+
// ATLAS_OFFSETS is a bit offset (MSB-first packing). Pixel (gx,gy): byte = bitIdx>>>3, bit = 7-(bitIdx&7).
|
|
623
|
+
const srcOff = atlas.offsets[rank];
|
|
624
|
+
const yOffset = atlasSet(font).bit.ascent - atlas.ascent;
|
|
625
|
+
for (let gy = 0; gy < atlas.cellH; gy++) {
|
|
626
|
+
const dstRow = (y + yOffset + gy) * fbW + x;
|
|
627
|
+
const bitRowStart = srcOff + gy * srcW;
|
|
628
|
+
for (let gx = 0; gx < srcW; gx++) {
|
|
629
|
+
const bitIdx = bitRowStart + gx;
|
|
630
|
+
const byte = atlas.pixels[bitIdx >>> 3];
|
|
631
|
+
const bit = (byte >>> (7 - (bitIdx & 7))) & 1;
|
|
632
|
+
if (bit) {
|
|
633
|
+
fb[dstRow + gx] = 255; // glyphs never overlap in grid layout; set unconditionally
|
|
634
|
+
if (markerMask)
|
|
635
|
+
markerMask[dstRow + gx] = 1;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
return wide ? 2 : 1;
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* Blit a grayscale atlas glyph at pixel (x, y) using max-blending. Selected by
|
|
643
|
+
* `style.aa`, which production sets via DENSE_RENDER_STYLE — this is NOT eval-only.
|
|
644
|
+
* Measured: the gray atlas is bit-identical to the bitmap atlas across all 95 ASCII
|
|
645
|
+
* glyphs (0/3800 intermediate coverage bytes) because Spleen-5x8.otb is a bitmap font
|
|
646
|
+
* at its native 8px, so AA has nothing to smooth. Only the Unifont vector fallback
|
|
647
|
+
* (CJK, box-drawing, accents) carries real grayscale (~48% intermediate bytes).
|
|
648
|
+
* Consequence: toggling `aa` cannot change a single pixel of ASCII content.
|
|
649
|
+
* Returns cells advanced (1 or 2), or 0 if absent from the gray atlas.
|
|
650
|
+
*/
|
|
651
|
+
function blitGlyphGray(fb, fbW, x, y, codepoint, font = DEFAULT_RENDER_FONT, markerMask = null) {
|
|
652
|
+
const glyph = grayGlyph(codepoint, font);
|
|
653
|
+
if (!glyph)
|
|
654
|
+
return 0;
|
|
655
|
+
const { atlas, rank } = glyph;
|
|
656
|
+
const wide = atlas.wideFlags[rank] === 1;
|
|
657
|
+
const srcW = wide ? 2 * atlas.cellW : atlas.cellW;
|
|
658
|
+
// ATLAS_GRAY_OFFSETS is a byte offset (1 byte/pixel, unlike the bit-packed 1-bit atlas).
|
|
659
|
+
const srcOff = atlas.offsets[rank];
|
|
660
|
+
const yOffset = atlasSet(font).gray.ascent - atlas.ascent;
|
|
661
|
+
for (let gy = 0; gy < atlas.cellH; gy++) {
|
|
662
|
+
const dstRow = (y + yOffset + gy) * fbW + x;
|
|
663
|
+
const srcRow = srcOff + gy * srcW;
|
|
664
|
+
for (let gx = 0; gx < srcW; gx++) {
|
|
665
|
+
const coverage = atlas.pixels[srcRow + gx];
|
|
666
|
+
if (coverage > 0) {
|
|
667
|
+
const idx = dstRow + gx;
|
|
668
|
+
if (coverage > fb[idx])
|
|
669
|
+
fb[idx] = coverage;
|
|
670
|
+
if (markerMask)
|
|
671
|
+
markerMask[idx] = 1;
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
return wide ? 2 : 1;
|
|
676
|
+
}
|
|
677
|
+
/** Blit a glyph scaled horizontally by scaleX (height unchanged). Used for enlarged ↵:
|
|
678
|
+
* horizontal-only avoids corrupting the row below. Returns cells advanced (scaleX or 2*scaleX). */
|
|
679
|
+
function blitGlyphScaled(fb, markerMask, fbW, fbH, x, y, codepoint, scaleX, font = DEFAULT_RENDER_FONT) {
|
|
680
|
+
const glyph = bitGlyph(codepoint, font);
|
|
681
|
+
if (!glyph)
|
|
682
|
+
return 0;
|
|
683
|
+
const { atlas, rank } = glyph;
|
|
684
|
+
const wide = atlas.wideFlags[rank] === 1;
|
|
685
|
+
const srcW = wide ? 2 * atlas.cellW : atlas.cellW;
|
|
686
|
+
const srcOff = atlas.offsets[rank];
|
|
687
|
+
const yOffset = atlasSet(font).bit.ascent - atlas.ascent;
|
|
688
|
+
for (let gy = 0; gy < atlas.cellH; gy++) {
|
|
689
|
+
const py = y + yOffset + gy;
|
|
690
|
+
if (py >= fbH)
|
|
691
|
+
break;
|
|
692
|
+
const bitRowStart = srcOff + gy * srcW;
|
|
693
|
+
for (let gx = 0; gx < srcW; gx++) {
|
|
694
|
+
const bitIdx = bitRowStart + gx;
|
|
695
|
+
const byte = atlas.pixels[bitIdx >>> 3];
|
|
696
|
+
if (((byte >>> (7 - (bitIdx & 7))) & 1) === 0)
|
|
697
|
+
continue;
|
|
698
|
+
for (let sx = 0; sx < scaleX; sx++) {
|
|
699
|
+
const px = x + gx * scaleX + sx;
|
|
700
|
+
if (px >= fbW)
|
|
701
|
+
break;
|
|
702
|
+
const idx = py * fbW + px;
|
|
703
|
+
fb[idx] = 255;
|
|
704
|
+
if (markerMask)
|
|
705
|
+
markerMask[idx] = 1;
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
return wide ? 2 * scaleX : scaleX;
|
|
710
|
+
}
|
|
711
|
+
/** Dilate ink on the pre-invert framebuffer (nonzero = ink). Radius is pixel
|
|
712
|
+
* passes; keeps width/height fixed so 5×8 packing is unchanged.
|
|
713
|
+
* axis: 'both' (4-connected), 'x' (horizontal only), 'y' (vertical only).
|
|
714
|
+
* Vertical-only thickens strokes without merging neighboring 5px-wide glyphs. */
|
|
715
|
+
function dilateInk(fb, fbW, fbH, radius, axis = 'both') {
|
|
716
|
+
const r = Math.max(0, Math.floor(radius));
|
|
717
|
+
if (r <= 0)
|
|
718
|
+
return;
|
|
719
|
+
const doX = axis === 'both' || axis === 'x';
|
|
720
|
+
const doY = axis === 'both' || axis === 'y';
|
|
721
|
+
let src = fb;
|
|
722
|
+
for (let pass = 0; pass < r; pass++) {
|
|
723
|
+
const out = new Uint8Array(src.length);
|
|
724
|
+
out.set(src);
|
|
725
|
+
for (let y = 0; y < fbH; y++) {
|
|
726
|
+
for (let x = 0; x < fbW; x++) {
|
|
727
|
+
const i = y * fbW + x;
|
|
728
|
+
if (src[i] > 0)
|
|
729
|
+
continue;
|
|
730
|
+
if ((doX && x > 0 && src[i - 1] > 0) ||
|
|
731
|
+
(doX && x + 1 < fbW && src[i + 1] > 0) ||
|
|
732
|
+
(doY && y > 0 && src[i - fbW] > 0) ||
|
|
733
|
+
(doY && y + 1 < fbH && src[i + fbW] > 0)) {
|
|
734
|
+
out[i] = 255;
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
src = out;
|
|
739
|
+
}
|
|
740
|
+
if (src !== fb)
|
|
741
|
+
fb.set(src);
|
|
742
|
+
}
|
|
743
|
+
const GRID_INK = 25; // pre-invert → 230 post-invert; distinct from gutter divider (64 → 191)
|
|
744
|
+
/** Draw faint grid rules onto background pixels only (glyph ink wins). Zero pixel-cost to image size. */
|
|
745
|
+
function drawGrid(fb, fbW, fbH, rows, gridCols, cellH, cellW, glyphH = ATLAS_CELL_H) {
|
|
746
|
+
for (let row = 0; row < rows; row++) {
|
|
747
|
+
const y = PAD_Y + row * cellH + (glyphH - 1);
|
|
748
|
+
if (y >= fbH)
|
|
749
|
+
break;
|
|
750
|
+
const rowStart = y * fbW;
|
|
751
|
+
for (let x = 0; x < fbW; x++) {
|
|
752
|
+
if (fb[rowStart + x] === 0)
|
|
753
|
+
fb[rowStart + x] = GRID_INK;
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
if (gridCols > 0) {
|
|
757
|
+
for (let col = gridCols;; col += gridCols) {
|
|
758
|
+
const x = PAD_X + col * cellW;
|
|
759
|
+
if (x >= fbW - PAD_X)
|
|
760
|
+
break;
|
|
761
|
+
for (let y = 0; y < fbH; y++) {
|
|
762
|
+
const idx = y * fbW + x;
|
|
763
|
+
if (fb[idx] === 0)
|
|
764
|
+
fb[idx] = GRID_INK;
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
/** Render text to a single PNG (≤ MAX_HEIGHT_PX tall). Wide glyphs occupy 2 consecutive cells. */
|
|
770
|
+
export async function renderChunkToPng(text, cols = DEFAULT_COLS, style = {}, maxHeightPx = MAX_HEIGHT_PX, slotText,
|
|
771
|
+
/** `text` is rows already laid out by wrapLines (renderTextToPngs pages), so
|
|
772
|
+
* its ↵ markers are padded already and must not be padded again. */
|
|
773
|
+
prewrapped = false) {
|
|
774
|
+
const markerScale = Math.max(1, Math.floor(style.markerScale ?? 1));
|
|
775
|
+
const lines = wrapLines(text, cols, markerScale, style.font, !prewrapped);
|
|
776
|
+
// Slot string carries role attribution by position. It is width-identical to
|
|
777
|
+
// `text`, so wrapLines splits it into the exact same rows — fitSlotLines[r] aligns
|
|
778
|
+
// codepoint-for-codepoint with fitLines[r]. Only built when coloring is on.
|
|
779
|
+
const slotLines = style.colorByRole === true && slotText !== undefined
|
|
780
|
+
? wrapLines(slotText, cols, markerScale, style.font, !prewrapped)
|
|
781
|
+
: null;
|
|
782
|
+
let fullCodepoints;
|
|
783
|
+
const cellH = renderCellHeight(style);
|
|
784
|
+
const maxLines = Math.max(1, Math.floor((maxHeightPx - 2 * PAD_Y) / cellH));
|
|
785
|
+
if (lines.length <= maxLines) {
|
|
786
|
+
let n = 0;
|
|
787
|
+
for (const _ of text)
|
|
788
|
+
n++;
|
|
789
|
+
fullCodepoints = n;
|
|
790
|
+
}
|
|
791
|
+
return renderLinesToPng(lines, slotLines, cols, style, maxHeightPx, fullCodepoints);
|
|
792
|
+
}
|
|
793
|
+
// Split out from `renderChunkToPng` so multi-page renders wrap once and blit pages directly.
|
|
794
|
+
async function renderLinesToPng(lines, slotLines, cols, style, maxHeightPx, fullCodepoints) {
|
|
795
|
+
const useAA = style.aa === true;
|
|
796
|
+
const selected = atlasSet(style.font);
|
|
797
|
+
const atlasH = useAA ? selected.gray.cellH : selected.bit.cellH;
|
|
798
|
+
const atlasW = useAA ? selected.gray.cellW : selected.bit.cellW;
|
|
799
|
+
const markerScale = Math.max(1, Math.floor(style.markerScale ?? 1));
|
|
800
|
+
const cellH = renderCellHeight(style);
|
|
801
|
+
const cellW = renderCellWidth(style);
|
|
802
|
+
const maxLines = Math.max(1, Math.floor((maxHeightPx - 2 * PAD_Y) / cellH));
|
|
803
|
+
const fitLines = lines.slice(0, maxLines);
|
|
804
|
+
const fitSlotLines = slotLines ? slotLines.slice(0, maxLines) : null;
|
|
805
|
+
// charsRendered = input codepoints covered by this image (for..of counts by codepoint, not code unit).
|
|
806
|
+
let charsRendered;
|
|
807
|
+
if (fitLines.length === lines.length && fullCodepoints !== undefined) {
|
|
808
|
+
charsRendered = fullCodepoints;
|
|
809
|
+
}
|
|
810
|
+
else {
|
|
811
|
+
// Sum kept-line codepoints + 1 separator per adjacent pair.
|
|
812
|
+
let n = 0;
|
|
813
|
+
for (let i = 0; i < fitLines.length; i++) {
|
|
814
|
+
for (const _ of fitLines[i])
|
|
815
|
+
n++;
|
|
816
|
+
}
|
|
817
|
+
n += Math.max(0, fitLines.length - 1);
|
|
818
|
+
charsRendered = n;
|
|
819
|
+
}
|
|
820
|
+
// Widen by overhang when cellW < atlasW so the last glyph stays inside the framebuffer.
|
|
821
|
+
const width = 2 * PAD_X + cols * cellW + Math.max(0, atlasW - cellW);
|
|
822
|
+
const height = 2 * PAD_Y + fitLines.length * cellH;
|
|
823
|
+
// Black canvas — inverted to black-on-white after blitting (matches Python proxy convention).
|
|
824
|
+
const fb = new Uint8Array(width * height);
|
|
825
|
+
// markerMask: 1 where ↵ glyph was inked; used to recolor those pixels red.
|
|
826
|
+
const markerMask = style.markerRed ? new Uint8Array(width * height) : null;
|
|
827
|
+
// colorMask: stores colorSlot per inked pixel (0 = background) for colorCycle / colorByRole RGB output.
|
|
828
|
+
const useColorCycle = style.colorCycle === true;
|
|
829
|
+
const useColorByRole = style.colorByRole === true;
|
|
830
|
+
const colorMask = (useColorCycle || useColorByRole) ? new Uint8Array(width * height) : null;
|
|
831
|
+
// Ink palette is fixed for the whole page; the composition pass indexes it per pixel.
|
|
832
|
+
const inkPalette = useColorByRole ? ROLE_PALETTE : GLYPH_PALETTE;
|
|
833
|
+
/** Stamp colorSlot over the inked pixels of one glyph's cell span. Identical
|
|
834
|
+
* for every blit path — only the horizontal span differs (scaled markers
|
|
835
|
+
* advance in cellW, normal glyphs in atlasW). */
|
|
836
|
+
const stampColorMask = (baseX, baseY, spanW, colorSlot) => {
|
|
837
|
+
if (!colorMask)
|
|
838
|
+
return;
|
|
839
|
+
for (let gy = 0; gy < atlasH; gy++) {
|
|
840
|
+
const py = baseY + gy;
|
|
841
|
+
if (py >= height)
|
|
842
|
+
break;
|
|
843
|
+
const rowBase = py * width;
|
|
844
|
+
for (let gx = 0; gx < spanW; gx++) {
|
|
845
|
+
const px = baseX + gx;
|
|
846
|
+
if (px >= width)
|
|
847
|
+
break;
|
|
848
|
+
const idx = rowBase + px;
|
|
849
|
+
if (fb[idx] > 0)
|
|
850
|
+
colorMask[idx] = colorSlot;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
};
|
|
854
|
+
let droppedChars = 0;
|
|
855
|
+
const droppedCodepoints = new Map();
|
|
856
|
+
let glyphIndex = 0; // every cell including spaces/missing
|
|
857
|
+
for (let row = 0; row < fitLines.length; row++) {
|
|
858
|
+
const line = fitLines[row];
|
|
859
|
+
const baseY = PAD_Y + row * cellH;
|
|
860
|
+
let col = 0;
|
|
861
|
+
// Per-row slot codepoints, aligned 1:1 with `line` (same wrap, width-preserved).
|
|
862
|
+
const slotRow = fitSlotLines ? Array.from(fitSlotLines[row] ?? '') : null;
|
|
863
|
+
let charIdx = 0;
|
|
864
|
+
for (const ch of line) {
|
|
865
|
+
if (col >= cols)
|
|
866
|
+
break; // shouldn't happen — wrap prevents this
|
|
867
|
+
const codepoint = ch.codePointAt(0);
|
|
868
|
+
const baseX = PAD_X + col * cellW;
|
|
869
|
+
const isMarker = codepoint === NL_SENTINEL_CP;
|
|
870
|
+
const colorSlot = useColorByRole
|
|
871
|
+
? (slotRow ? slotForMarkCp(slotRow[charIdx]?.codePointAt(0)) : 0) // 0 = body (black); only tags carry a role hue
|
|
872
|
+
: (glyphIndex % GLYPH_PALETTE.length) + 1; // 0 reserved for background in colorMask
|
|
873
|
+
let advance;
|
|
874
|
+
if (isMarker && markerScale > 1) {
|
|
875
|
+
advance = blitGlyphScaled(fb, markerMask, width, height, baseX, baseY, codepoint, markerScale, style.font);
|
|
876
|
+
// Scaled marker occupies whole cells, so its span is in cellW units.
|
|
877
|
+
if (colorMask && colorSlot > 0 && advance > 0)
|
|
878
|
+
stampColorMask(baseX, baseY, advance * cellW, colorSlot);
|
|
879
|
+
}
|
|
880
|
+
else {
|
|
881
|
+
advance = useAA
|
|
882
|
+
? blitGlyphGray(fb, width, baseX, baseY, codepoint, style.font, isMarker ? markerMask : null)
|
|
883
|
+
: blitGlyph(fb, width, baseX, baseY, codepoint, style.font, isMarker ? markerMask : null);
|
|
884
|
+
if (colorMask && colorSlot > 0 && advance > 0)
|
|
885
|
+
stampColorMask(baseX, baseY, advance * atlasW, colorSlot);
|
|
886
|
+
}
|
|
887
|
+
glyphIndex++;
|
|
888
|
+
charIdx++;
|
|
889
|
+
if (advance === 0) {
|
|
890
|
+
droppedChars++;
|
|
891
|
+
droppedCodepoints.set(codepoint, (droppedCodepoints.get(codepoint) ?? 0) + 1);
|
|
892
|
+
col += 1; // missing glyph still occupies 1 cell for wrap stability
|
|
893
|
+
}
|
|
894
|
+
else {
|
|
895
|
+
col += advance;
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
if (style.grid) {
|
|
900
|
+
drawGrid(fb, width, height, fitLines.length, Math.max(0, Math.floor(style.gridCols ?? 0)), cellH, cellW, atlasH);
|
|
901
|
+
}
|
|
902
|
+
// Optional ink dilate (pre-invert): thickens glyphs without changing cell pitch.
|
|
903
|
+
const dilate = Math.max(0, Math.floor(style.inkDilate ?? 0));
|
|
904
|
+
if (dilate > 0) {
|
|
905
|
+
const axis = style.inkDilateAxis === 'x' || style.inkDilateAxis === 'y' ? style.inkDilateAxis : 'both';
|
|
906
|
+
dilateInk(fb, width, height, dilate, axis);
|
|
907
|
+
}
|
|
908
|
+
// Invert to black-on-white unless style.invert === false (white-on-black).
|
|
909
|
+
if (style.invert !== false) {
|
|
910
|
+
for (let i = 0; i < fb.length; i++)
|
|
911
|
+
fb[i] = 255 - fb[i];
|
|
912
|
+
}
|
|
913
|
+
// Optional mid-light paper: remap pure white (255) toward paperGray while keeping
|
|
914
|
+
// black ink at 0. Linear: g' = paper * g / 255. No cell-pitch change.
|
|
915
|
+
const paper = Math.max(0, Math.min(255, Math.floor(style.paperGray ?? 255)));
|
|
916
|
+
if (paper < 255) {
|
|
917
|
+
for (let i = 0; i < fb.length; i++) {
|
|
918
|
+
const g = fb[i];
|
|
919
|
+
fb[i] = Math.round((paper * g) / 255);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
let png;
|
|
923
|
+
if (colorMask) {
|
|
924
|
+
// colorCycle / colorByRole: AA-blend ink onto paper in palette color.
|
|
925
|
+
const rgb = new Uint8Array(width * height * 3);
|
|
926
|
+
for (let i = 0; i < fb.length; i++) {
|
|
927
|
+
const g = fb[i]; // post-invert (+ optional paper): 0 = ink, paper = background
|
|
928
|
+
const slot = colorMask[i];
|
|
929
|
+
if (slot > 0) {
|
|
930
|
+
// coverage relative to paper so AA fringes stay correct on mid-light bg
|
|
931
|
+
const coverage = paper <= 0 ? 0 : Math.round(((paper - g) * 255) / paper);
|
|
932
|
+
const cov = Math.max(0, Math.min(255, coverage));
|
|
933
|
+
const [pr, pg, pb] = inkPalette[(slot - 1) % inkPalette.length];
|
|
934
|
+
// Alpha-blend ink color onto paper: channel = paper - cov*(paper-palette)/255
|
|
935
|
+
rgb[i * 3] = Math.round(paper - (cov * (paper - pr)) / 255);
|
|
936
|
+
rgb[i * 3 + 1] = Math.round(paper - (cov * (paper - pg)) / 255);
|
|
937
|
+
rgb[i * 3 + 2] = Math.round(paper - (cov * (paper - pb)) / 255);
|
|
938
|
+
}
|
|
939
|
+
else {
|
|
940
|
+
rgb[i * 3] = g;
|
|
941
|
+
rgb[i * 3 + 1] = g;
|
|
942
|
+
rgb[i * 3 + 2] = g;
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
png = await encodeRgbPng(rgb, width, height);
|
|
946
|
+
}
|
|
947
|
+
else if (markerMask) {
|
|
948
|
+
// markerRed: ↵ pixels → red, everything else stays greyscale.
|
|
949
|
+
const rgb = new Uint8Array(width * height * 3);
|
|
950
|
+
for (let i = 0; i < fb.length; i++) {
|
|
951
|
+
const g = fb[i];
|
|
952
|
+
if (markerMask[i] === 1 && g < 128) {
|
|
953
|
+
rgb[i * 3] = 220; // R
|
|
954
|
+
rgb[i * 3 + 1] = 0; // G
|
|
955
|
+
rgb[i * 3 + 2] = 0; // B
|
|
956
|
+
}
|
|
957
|
+
else {
|
|
958
|
+
rgb[i * 3] = g;
|
|
959
|
+
rgb[i * 3 + 1] = g;
|
|
960
|
+
rgb[i * 3 + 2] = g;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
png = await encodeRgbPng(rgb, width, height);
|
|
964
|
+
}
|
|
965
|
+
else {
|
|
966
|
+
png = await encodeGrayPng(fb, width, height);
|
|
967
|
+
}
|
|
968
|
+
return { png, width, height, charsRendered, droppedChars, droppedCodepoints };
|
|
969
|
+
}
|
|
970
|
+
/** Reflow-aware variant of renderTextToPngs. Falls back to non-reflow on sentinel collision. */
|
|
971
|
+
export async function renderTextToPngsReflow(text, cols = DEFAULT_COLS, style = {}) {
|
|
972
|
+
const packed = reflow(text);
|
|
973
|
+
return renderTextToPngs(packed ?? text, cols, style);
|
|
974
|
+
}
|
|
975
|
+
/** Split text into N PNGs each ≤ MAX_HEIGHT_PX tall, respecting per-image char budget. */
|
|
976
|
+
// --- rendered-page cache ---------------------------------------------------
|
|
977
|
+
/**
|
|
978
|
+
* Rendering is a pure function of (text, cols, maxCharsPerImage, style, maxHeightPx,
|
|
979
|
+
* slotText): the atlases are decoded once at module init and never mutated, and no
|
|
980
|
+
* module-level state feeds the output. So identical inputs can safely return the
|
|
981
|
+
* identical pages instead of being re-rasterized.
|
|
982
|
+
*
|
|
983
|
+
* This is worth a cache because the proxy deliberately re-renders the same bytes every
|
|
984
|
+
* turn: history chunks are frozen so they stay byte-identical for the upstream prompt
|
|
985
|
+
* cache (see the cache-stability note in history.ts), which means a long session pays
|
|
986
|
+
* full render cost for pages that provably did not change. Measured on a real session,
|
|
987
|
+
* ~134 images cost ~10s of single-threaded CPU per request while the payload hash held
|
|
988
|
+
* constant across consecutive turns.
|
|
989
|
+
*
|
|
990
|
+
* Bounded by total retained bytes. Eviction is LRU via Map's insertion order:
|
|
991
|
+
* re-inserting on hit moves an entry to the newest position.
|
|
992
|
+
*/
|
|
993
|
+
/** 64 MiB holds several turns of a heavy session on a host with real RAM. */
|
|
994
|
+
const RENDER_CACHE_DEFAULT_BYTES_NODE = 64 * 1024 * 1024;
|
|
995
|
+
/** A Workers isolate gets ~128 MiB for everything — the request body, the decoded
|
|
996
|
+
* atlases, the framebuffers, and whatever the compressor is holding. Half of that
|
|
997
|
+
* spent on retained pages is how an isolate gets killed mid-request, so the edge
|
|
998
|
+
* default is an order of magnitude lower and operators opt back up. */
|
|
999
|
+
const RENDER_CACHE_DEFAULT_BYTES_WORKERS = 8 * 1024 * 1024;
|
|
1000
|
+
/** `typeof process` cannot answer this: `nodejs_compat_v2` defines `process` on
|
|
1001
|
+
* Workers too. `navigator.userAgent` is the documented probe.
|
|
1002
|
+
*
|
|
1003
|
+
* Read off `globalThis` through a local shape rather than the ambient `navigator`
|
|
1004
|
+
* global: this project compiles `@cloudflare/workers-types` and `@types/node`
|
|
1005
|
+
* together, and `navigator` is absent from Node before 21 while `engines` allows
|
|
1006
|
+
* 20.19. Optional chaining answers "not Workers" for every one of those cases. */
|
|
1007
|
+
function isWorkersRuntime() {
|
|
1008
|
+
const nav = globalThis.navigator;
|
|
1009
|
+
return nav?.userAgent === 'Cloudflare-Workers';
|
|
1010
|
+
}
|
|
1011
|
+
/** Mutable rather than a const: Worker configuration arrives as per-request bindings,
|
|
1012
|
+
* not as `process.env` at module init, so `src/worker.ts` has to be able to set this
|
|
1013
|
+
* after the module has already loaded. Node still resolves it once, below. */
|
|
1014
|
+
let renderCacheMaxBytesValue = (() => {
|
|
1015
|
+
// Edge-safe: `process` is undefined off-Node.
|
|
1016
|
+
const raw = readBrandEnv('RENDER_CACHE_BYTES');
|
|
1017
|
+
const parsed = raw !== undefined && raw.trim() !== '' ? Number(raw) : NaN;
|
|
1018
|
+
// 0 disables the cache outright; negative/garbage falls back to the default.
|
|
1019
|
+
if (Number.isFinite(parsed) && parsed >= 0)
|
|
1020
|
+
return Math.floor(parsed);
|
|
1021
|
+
return isWorkersRuntime() ? RENDER_CACHE_DEFAULT_BYTES_WORKERS : RENDER_CACHE_DEFAULT_BYTES_NODE;
|
|
1022
|
+
})();
|
|
1023
|
+
const renderCache = new Map();
|
|
1024
|
+
const renderInFlight = new Map();
|
|
1025
|
+
let renderCacheEpoch = 0;
|
|
1026
|
+
let renderCacheBytes = 0;
|
|
1027
|
+
let renderCacheHits = 0;
|
|
1028
|
+
let renderCacheMisses = 0;
|
|
1029
|
+
let renderCacheEvictions = 0;
|
|
1030
|
+
let renderCacheOversized = 0;
|
|
1031
|
+
/** Observability for the dashboard/tests. `bytes` counts retained PNG payloads plus
|
|
1032
|
+
* the fixed-width keys.
|
|
1033
|
+
*
|
|
1034
|
+
* `evictions` and `oversized` answer different questions and a single "the cache is
|
|
1035
|
+
* not helping" number would conflate them: evictions mean the working set outgrew the
|
|
1036
|
+
* budget (raise it, or accept the churn), while `oversized` means a single render was
|
|
1037
|
+
* bigger than the entire budget and was therefore never stored at all — the failure a
|
|
1038
|
+
* too-small edge budget produces, where hit rate stays at zero no matter how stable
|
|
1039
|
+
* the input is. */
|
|
1040
|
+
export function renderCacheStats() {
|
|
1041
|
+
return {
|
|
1042
|
+
entries: renderCache.size,
|
|
1043
|
+
bytes: renderCacheBytes,
|
|
1044
|
+
hits: renderCacheHits,
|
|
1045
|
+
misses: renderCacheMisses,
|
|
1046
|
+
evictions: renderCacheEvictions,
|
|
1047
|
+
oversized: renderCacheOversized,
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
/** Current byte budget. Exposed so the dashboard can report utilisation rather than a
|
|
1051
|
+
* bare byte count the operator has no denominator for. */
|
|
1052
|
+
export function renderCacheMaxBytes() {
|
|
1053
|
+
return renderCacheMaxBytesValue;
|
|
1054
|
+
}
|
|
1055
|
+
/**
|
|
1056
|
+
* Set the byte budget at runtime and evict down to it immediately.
|
|
1057
|
+
*
|
|
1058
|
+
* Exists for the Worker entrypoint, which cannot use the module-init `process.env`
|
|
1059
|
+
* read: bindings are handed to `fetch(req, env, ctx)`, long after this module
|
|
1060
|
+
* evaluated. Node keeps using the env read.
|
|
1061
|
+
*
|
|
1062
|
+
* `0` disables the cache and drops everything already held. Negative or non-finite
|
|
1063
|
+
* input is ignored rather than obeyed — a broken value must not read as "unbounded".
|
|
1064
|
+
*/
|
|
1065
|
+
export function setRenderCacheMaxBytes(maxBytes) {
|
|
1066
|
+
if (!Number.isFinite(maxBytes) || maxBytes < 0)
|
|
1067
|
+
return;
|
|
1068
|
+
renderCacheMaxBytesValue = Math.floor(maxBytes);
|
|
1069
|
+
if (renderCacheMaxBytesValue === 0) {
|
|
1070
|
+
// Not clearRenderCache(): shrinking the budget is not a reason to throw away the
|
|
1071
|
+
// hit/miss history an operator is reading.
|
|
1072
|
+
renderCacheEpoch++;
|
|
1073
|
+
renderCache.clear();
|
|
1074
|
+
renderCacheBytes = 0;
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
evictToBudget();
|
|
1078
|
+
}
|
|
1079
|
+
/** Evict oldest-first until back within budget, optionally pinning one key that must
|
|
1080
|
+
* survive. Map iteration is insertion order, which the hit path keeps LRU-ordered. */
|
|
1081
|
+
function evictToBudget(pinnedKey) {
|
|
1082
|
+
for (const [k, v] of renderCache) {
|
|
1083
|
+
if (renderCacheBytes <= renderCacheMaxBytesValue)
|
|
1084
|
+
break;
|
|
1085
|
+
if (k === pinnedKey)
|
|
1086
|
+
continue;
|
|
1087
|
+
renderCache.delete(k);
|
|
1088
|
+
renderCacheBytes -= v.bytes;
|
|
1089
|
+
renderCacheEvictions++;
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
/** Drop every entry. Tests use this to isolate hit/miss accounting. */
|
|
1093
|
+
export function clearRenderCache() {
|
|
1094
|
+
renderCacheEpoch++;
|
|
1095
|
+
renderCache.clear();
|
|
1096
|
+
renderCacheBytes = 0;
|
|
1097
|
+
renderCacheHits = 0;
|
|
1098
|
+
renderCacheMisses = 0;
|
|
1099
|
+
renderCacheEvictions = 0;
|
|
1100
|
+
renderCacheOversized = 0;
|
|
1101
|
+
}
|
|
1102
|
+
/** Stable serialization of RenderStyle. Every field is a primitive (see the interface),
|
|
1103
|
+
* so String() is unambiguous; sorting keys removes any dependence on literal order.
|
|
1104
|
+
* Undefined values are skipped so `{}` and `{aa: undefined}` share one entry. */
|
|
1105
|
+
function styleCacheKey(style) {
|
|
1106
|
+
const src = style;
|
|
1107
|
+
let out = '';
|
|
1108
|
+
for (const k of Object.keys(src).sort()) {
|
|
1109
|
+
const v = src[k];
|
|
1110
|
+
if (v !== undefined)
|
|
1111
|
+
out += `${k}=${String(v)};`;
|
|
1112
|
+
}
|
|
1113
|
+
return out;
|
|
1114
|
+
}
|
|
1115
|
+
/** Copy the array and each entry's mutable `droppedCodepoints` map so a caller cannot
|
|
1116
|
+
* mutate cached state. The PNG bytes are shared deliberately — copying multi-MB
|
|
1117
|
+
* payloads on every hit would defeat the point; callers only base64-encode them. */
|
|
1118
|
+
function cloneForCaller(images) {
|
|
1119
|
+
return images.map((img) => ({ ...img, droppedCodepoints: new Map(img.droppedCodepoints) }));
|
|
1120
|
+
}
|
|
1121
|
+
/** Domain separator. Keeps these digests from ever being equal to a digest this
|
|
1122
|
+
* codebase computes over the same bytes for another purpose (`sha8` over the slab,
|
|
1123
|
+
* `sha256Text` in proxy.ts), and gives the encoding a version to bump if the input
|
|
1124
|
+
* tuple ever grows a field. */
|
|
1125
|
+
const RENDER_CACHE_KEY_DOMAIN = 'inkling/render-cache/v1\n';
|
|
1126
|
+
const renderCacheKeyEncoder = new TextEncoder();
|
|
1127
|
+
/**
|
|
1128
|
+
* Cache key: a SHA-256 over a canonical encoding of everything the renderer reads.
|
|
1129
|
+
*
|
|
1130
|
+
* #158 keyed on the source text verbatim, arguing that a digest collision would serve
|
|
1131
|
+
* the WRONG image and that a literal key is collision-free by construction. The
|
|
1132
|
+
* literal key is also a guarantee of the opposite kind: every prompt rendered this
|
|
1133
|
+
* process stays in the heap as a plaintext string until evicted, and — the part that
|
|
1134
|
+
* bites operationally — entry size scales with source length, so a budget meant to
|
|
1135
|
+
* bound retained *pages* spends most of itself on copies of the input (#210).
|
|
1136
|
+
*
|
|
1137
|
+
* A full 256-bit digest, not the 32-bit `sha8` used for telemetry elsewhere. At the
|
|
1138
|
+
* entry counts a byte budget permits, collision odds sit far below the failure modes
|
|
1139
|
+
* the pipeline already lives with, and #210 states the trade explicitly: a
|
|
1140
|
+
* cryptographic collision is the smaller risk against guaranteed prompt retention.
|
|
1141
|
+
*
|
|
1142
|
+
* Every free-form field is length-prefixed, so no regrouping of the same characters
|
|
1143
|
+
* can produce one encoding — ("a b", "c") and ("a", "b c") stay distinct, which is the
|
|
1144
|
+
* ambiguity #158's `slotLen` prefix guarded against. `-1` marks an absent `slotText`
|
|
1145
|
+
* and must stay distinct from empty, because renderTextToPngsUncached branches on
|
|
1146
|
+
* `slotText !== undefined` rather than on its length.
|
|
1147
|
+
*/
|
|
1148
|
+
async function renderCacheKey(text, cols, maxCharsPerImage, maxHeightPx, style, slotText) {
|
|
1149
|
+
const styleKey = styleCacheKey(style);
|
|
1150
|
+
const slotLen = slotText === undefined ? -1 : slotText.length;
|
|
1151
|
+
const canonical = RENDER_CACHE_KEY_DOMAIN +
|
|
1152
|
+
`${cols}|${maxCharsPerImage}|${maxHeightPx}|` +
|
|
1153
|
+
`${styleKey.length}|${styleKey}|` +
|
|
1154
|
+
`${slotLen}|${slotText ?? ''}|` +
|
|
1155
|
+
`${text.length}|${text}`;
|
|
1156
|
+
const digest = await crypto.subtle.digest('SHA-256', renderCacheKeyEncoder.encode(canonical));
|
|
1157
|
+
const bytes = new Uint8Array(digest);
|
|
1158
|
+
let hex = '';
|
|
1159
|
+
for (const b of bytes)
|
|
1160
|
+
hex += b.toString(16).padStart(2, '0');
|
|
1161
|
+
return hex;
|
|
1162
|
+
}
|
|
1163
|
+
export async function renderTextToPngsWithCharLimit(text, cols = DEFAULT_COLS, maxCharsPerImage = READABLE_CHARS_PER_IMAGE, style = {}, maxHeightPx = MAX_HEIGHT_PX, slotText) {
|
|
1164
|
+
if (renderCacheMaxBytesValue === 0) {
|
|
1165
|
+
return renderTextToPngsUncached(text, cols, maxCharsPerImage, style, maxHeightPx, slotText);
|
|
1166
|
+
}
|
|
1167
|
+
const key = await renderCacheKey(text, cols, maxCharsPerImage, maxHeightPx, style, slotText);
|
|
1168
|
+
const hit = renderCache.get(key);
|
|
1169
|
+
if (hit !== undefined) {
|
|
1170
|
+
renderCacheHits++;
|
|
1171
|
+
renderCache.delete(key); // re-insert to refresh LRU position
|
|
1172
|
+
renderCache.set(key, hit);
|
|
1173
|
+
return cloneForCaller(hit.images);
|
|
1174
|
+
}
|
|
1175
|
+
renderCacheMisses++;
|
|
1176
|
+
const pending = renderInFlight.get(key);
|
|
1177
|
+
if (pending !== undefined) {
|
|
1178
|
+
return cloneForCaller(await pending);
|
|
1179
|
+
}
|
|
1180
|
+
const startEpoch = renderCacheEpoch;
|
|
1181
|
+
const task = (async () => {
|
|
1182
|
+
const images = await renderTextToPngsUncached(text, cols, maxCharsPerImage, style, maxHeightPx, slotText);
|
|
1183
|
+
if (renderCacheMaxBytesValue === 0 || renderCacheEpoch !== startEpoch) {
|
|
1184
|
+
return images;
|
|
1185
|
+
}
|
|
1186
|
+
// Key strings are UTF-16 in memory; 2 bytes/unit is the honest estimate. The digest
|
|
1187
|
+
// is fixed-width, so this term is now a constant per entry rather than a second copy
|
|
1188
|
+
// of the input — the budget bounds retained pages, which is what it claims to bound.
|
|
1189
|
+
let bytes = key.length * 2;
|
|
1190
|
+
for (const img of images)
|
|
1191
|
+
bytes += img.png.byteLength;
|
|
1192
|
+
// A single render larger than the whole budget is not cacheable — storing it would
|
|
1193
|
+
// evict everything and then itself. Serve it and move on.
|
|
1194
|
+
if (bytes <= renderCacheMaxBytesValue) {
|
|
1195
|
+
const replaced = renderCache.get(key);
|
|
1196
|
+
if (replaced !== undefined) {
|
|
1197
|
+
renderCacheBytes -= replaced.bytes;
|
|
1198
|
+
renderCache.delete(key);
|
|
1199
|
+
}
|
|
1200
|
+
renderCache.set(key, { images, bytes });
|
|
1201
|
+
renderCacheBytes += bytes;
|
|
1202
|
+
evictToBudget(key); // never evict the entry just stored
|
|
1203
|
+
}
|
|
1204
|
+
else {
|
|
1205
|
+
renderCacheOversized++;
|
|
1206
|
+
}
|
|
1207
|
+
return images;
|
|
1208
|
+
})();
|
|
1209
|
+
renderInFlight.set(key, task);
|
|
1210
|
+
try {
|
|
1211
|
+
return cloneForCaller(await task);
|
|
1212
|
+
}
|
|
1213
|
+
finally {
|
|
1214
|
+
if (renderInFlight.get(key) === task) {
|
|
1215
|
+
renderInFlight.delete(key);
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
async function renderTextToPngsUncached(text, cols, maxCharsPerImage, style, maxHeightPx, slotText) {
|
|
1220
|
+
const markerScale = Math.max(1, Math.floor(style.markerScale ?? 1));
|
|
1221
|
+
const cellH = renderCellHeight(style);
|
|
1222
|
+
const lines = wrapLines(text, cols, markerScale, style.font);
|
|
1223
|
+
// Width-identical slot rows align 1:1 with `lines`; pages are contiguous slices,
|
|
1224
|
+
// so the same index range gives each page its slot half. Only built when coloring.
|
|
1225
|
+
const slotLines = style.colorByRole === true && slotText !== undefined
|
|
1226
|
+
? wrapLines(slotText, cols, markerScale, style.font)
|
|
1227
|
+
: null;
|
|
1228
|
+
const hardLinesPerImg = Math.max(1, Math.floor((maxHeightPx - 2 * PAD_Y) / cellH));
|
|
1229
|
+
// Dense pages (DENSE_CONTENT_CHARS_PER_IMAGE) fill the full 1932 px height;
|
|
1230
|
+
// the slab budget (READABLE_CHARS_PER_IMAGE) keeps its shorter row cap.
|
|
1231
|
+
const linesPerImg = Math.min(hardLinesPerImg, Math.max(1, Math.floor(maxCharsPerImage / cols)));
|
|
1232
|
+
const jobs = [];
|
|
1233
|
+
let slotCursor = 0;
|
|
1234
|
+
for (const page of splitWrappedLinesIntoReadablePages(lines, linesPerImg, maxCharsPerImage)) {
|
|
1235
|
+
const slotPage = slotLines ? slotLines.slice(slotCursor, slotCursor + page.length) : null;
|
|
1236
|
+
slotCursor += page.length;
|
|
1237
|
+
jobs.push({ page, slotPage });
|
|
1238
|
+
}
|
|
1239
|
+
return Promise.all(jobs.map((job) => renderLinesToPng(job.page, job.slotPage, cols, style, maxHeightPx)));
|
|
1240
|
+
}
|
|
1241
|
+
export async function renderTextToPngs(text, cols = DEFAULT_COLS, style = {}, maxHeightPx = MAX_HEIGHT_PX, slotText) {
|
|
1242
|
+
return renderTextToPngsWithCharLimit(text, cols, READABLE_CHARS_PER_IMAGE, style, maxHeightPx, slotText);
|
|
1243
|
+
}
|
|
1244
|
+
/**
|
|
1245
|
+
* The single dense-page rendering decision shared by the public SDK primitive
|
|
1246
|
+
* `renderTextToImages` (library.ts → `inkling export`) AND the proxy's `textToImageBlocks`
|
|
1247
|
+
* (transform.ts): optionally reflow, measure the content width, then render. Both callers
|
|
1248
|
+
* route through HERE so
|
|
1249
|
+
* export PNGs and proxy image blocks are produced by the exact same code and cannot drift —
|
|
1250
|
+
* `shrinkColsToContent` is `measureContentCols`, so the proxy's old inline path was already
|
|
1251
|
+
* identical at the default 384 cols; this makes it identical at every cols. Returns the raw
|
|
1252
|
+
* rendered pages; each caller packages them (PNG files vs. base64 Anthropic ImageBlocks).
|
|
1253
|
+
*
|
|
1254
|
+
* History (history.ts) deliberately does NOT use this: it reflows a parallel role-slot string
|
|
1255
|
+
* in lockstep with the text and renders with `colorByRole`, which code export has no concept
|
|
1256
|
+
* of — wiring slots through this public surface would bloat it for one internal caller. It
|
|
1257
|
+
* still shares the underlying `reflow()` + `renderTextToPngsWithCharLimit` primitives.
|
|
1258
|
+
*/
|
|
1259
|
+
export async function renderDensePages(text, opts = {}) {
|
|
1260
|
+
const source = opts.reflow ? reflow(text) ?? text : text;
|
|
1261
|
+
const maxCols = Math.max(1, (opts.cols ?? DENSE_CONTENT_COLS) | 0);
|
|
1262
|
+
const style = opts.style ?? DENSE_RENDER_STYLE;
|
|
1263
|
+
const cols = opts.shrink === false
|
|
1264
|
+
? maxCols
|
|
1265
|
+
: measureContentCols(source, maxCols, style.markerScale, style.font);
|
|
1266
|
+
const maxChars = opts.maxCharsPerImage ?? DENSE_CONTENT_CHARS_PER_IMAGE;
|
|
1267
|
+
const maxHeightPx = opts.maxHeightPx ?? MAX_HEIGHT_PX;
|
|
1268
|
+
return renderTextToPngsWithCharLimit(source, cols, maxChars, style, maxHeightPx);
|
|
1269
|
+
}
|
|
1270
|
+
/** Visual row count after soft-wrap at `cols` (only hard newlines start a new row). */
|
|
1271
|
+
export function countVisualRows(text, cols) {
|
|
1272
|
+
const sentinel = NL_SENTINEL.charCodeAt(0);
|
|
1273
|
+
let rows = 0;
|
|
1274
|
+
let lineStart = 0;
|
|
1275
|
+
let padCells = 0;
|
|
1276
|
+
const len = text.length;
|
|
1277
|
+
for (let i = 0; i <= len; i++) {
|
|
1278
|
+
const cc = i < len ? text.charCodeAt(i) : -1;
|
|
1279
|
+
if (cc === sentinel)
|
|
1280
|
+
padCells += 2 * NL_SENTINEL_PAD_CELLS;
|
|
1281
|
+
if (i === len || cc === 10 /* \n */) {
|
|
1282
|
+
const lineLen = i - lineStart + padCells;
|
|
1283
|
+
rows += lineLen === 0 ? 1 : Math.ceil(lineLen / Math.max(1, cols));
|
|
1284
|
+
lineStart = i + 1;
|
|
1285
|
+
padCells = 0;
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
return rows;
|
|
1289
|
+
}
|
|
1290
|
+
/** Estimate how many images `text` will render to at the given column width and page limits. */
|
|
1291
|
+
export function estimateImageCount(textOrLen, cols, maxChars = READABLE_CHARS_PER_IMAGE, maxLinesPerColumn = LINES_PER_IMAGE) {
|
|
1292
|
+
const readableLinesPerCol = Math.max(1, Math.floor(maxChars / Math.max(1, cols)));
|
|
1293
|
+
const hardLinesPerCol = Math.max(1, Math.floor(maxLinesPerColumn));
|
|
1294
|
+
const linesPerImage = Math.min(hardLinesPerCol, readableLinesPerCol);
|
|
1295
|
+
const charBudget = Math.max(1, maxChars);
|
|
1296
|
+
if (typeof textOrLen === 'number') {
|
|
1297
|
+
return Math.max(1, Math.ceil(textOrLen / charBudget));
|
|
1298
|
+
}
|
|
1299
|
+
const rows = countVisualRows(textOrLen, cols);
|
|
1300
|
+
return Math.max(1, Math.ceil(rows / linesPerImage), Math.ceil(textOrLen.length / charBudget));
|
|
1301
|
+
}
|
|
1302
|
+
//# sourceMappingURL=render.js.map
|