@niracler/encore 0.1.0 → 0.3.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.
@@ -0,0 +1,255 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://encore.niracler.com/schema/session.schema.json",
4
+ "title": "Encore Session Replay",
5
+ "description": "Self-contained intermediate representation (session.json) for AI agent session replays in Encore.",
6
+ "type": "object",
7
+ "required": ["tool", "title", "items"],
8
+ "properties": {
9
+ "$schema": {
10
+ "type": "string",
11
+ "description": "Optional JSON Schema reference."
12
+ },
13
+ "tool": {
14
+ "type": "string",
15
+ "enum": ["codex", "claude-code", "claude-ai", "workbuddy"],
16
+ "description": "Source AI agent environment identifier."
17
+ },
18
+ "model": {
19
+ "type": "string",
20
+ "description": "Primary LLM model identifier used during the session."
21
+ },
22
+ "lang": {
23
+ "type": "string",
24
+ "enum": ["zh", "en"],
25
+ "description": "Default UI language for the player."
26
+ },
27
+ "title": {
28
+ "type": "string",
29
+ "minLength": 1,
30
+ "description": "Session title displayed in the header and browser tab."
31
+ },
32
+ "description": {
33
+ "type": "string",
34
+ "description": "Opening story intro displayed on the empty stage before playback begins."
35
+ },
36
+ "started": {
37
+ "type": "string",
38
+ "format": "date-time",
39
+ "description": "ISO-8601 timestamp of the first item in the session."
40
+ },
41
+ "ended": {
42
+ "type": "string",
43
+ "format": "date-time",
44
+ "description": "ISO-8601 timestamp of the last item in the session."
45
+ },
46
+ "tokens": {
47
+ "type": "integer",
48
+ "minimum": 0,
49
+ "description": "Peak or total token count recorded in the session."
50
+ },
51
+ "contextWindow": {
52
+ "type": "integer",
53
+ "minimum": 1,
54
+ "description": "Context window token capacity (e.g. 200000 or 1000000)."
55
+ },
56
+ "initialContext": {
57
+ "type": "object",
58
+ "description": "Initial mounted context records captured from the session preamble.",
59
+ "properties": {
60
+ "sys": {
61
+ "type": "array",
62
+ "items": { "$ref": "#/$defs/contextRecord" }
63
+ },
64
+ "schema": {
65
+ "type": "array",
66
+ "items": { "$ref": "#/$defs/contextRecord" }
67
+ },
68
+ "mem": {
69
+ "type": "array",
70
+ "items": { "$ref": "#/$defs/contextRecord" }
71
+ },
72
+ "skill": {
73
+ "type": "array",
74
+ "items": { "$ref": "#/$defs/contextRecord" }
75
+ }
76
+ },
77
+ "additionalProperties": false
78
+ },
79
+ "frames": {
80
+ "type": "array",
81
+ "description": "Curated visual milestone frames (.webp) extracted or referenced during the session.",
82
+ "items": { "$ref": "#/$defs/sessionFrame" }
83
+ },
84
+ "audioClips": {
85
+ "type": "array",
86
+ "description": "Optional audio clips generated during the session.",
87
+ "items": { "$ref": "#/$defs/audioClip" }
88
+ },
89
+ "deliverables": {
90
+ "type": "array",
91
+ "description": "Final deliverables presented at the end of the replay.",
92
+ "items": { "$ref": "#/$defs/deliverable" }
93
+ },
94
+ "items": {
95
+ "type": "array",
96
+ "description": "Ordered sequence of normalized conversation and tool events.",
97
+ "items": { "$ref": "#/$defs/sessionItem" }
98
+ }
99
+ },
100
+ "$defs": {
101
+ "contextRecord": {
102
+ "type": "object",
103
+ "required": ["id", "title", "payload"],
104
+ "properties": {
105
+ "id": { "type": "string" },
106
+ "tag": { "type": "string" },
107
+ "title": { "type": "string" },
108
+ "meta": { "type": "string" },
109
+ "tokEst": { "type": "integer", "minimum": 0 },
110
+ "stepIndex": { "type": "integer" },
111
+ "payload": { "type": "string" },
112
+ "images": {
113
+ "type": "array",
114
+ "items": { "type": "string" }
115
+ }
116
+ }
117
+ },
118
+ "sessionFrame": {
119
+ "type": "object",
120
+ "required": ["img"],
121
+ "properties": {
122
+ "time": { "type": "string" },
123
+ "img": { "type": "string" },
124
+ "who": { "type": "string", "enum": ["you", "ai"] },
125
+ "label": { "type": "string" },
126
+ "w": { "type": "integer", "minimum": 1 },
127
+ "h": { "type": "integer", "minimum": 1 }
128
+ }
129
+ },
130
+ "audioClip": {
131
+ "type": "object",
132
+ "required": ["src"],
133
+ "properties": {
134
+ "id": { "type": "string" },
135
+ "label": { "type": "string" },
136
+ "src": { "type": "string" },
137
+ "time": { "type": "string" }
138
+ }
139
+ },
140
+ "deliverable": {
141
+ "type": "object",
142
+ "required": ["title"],
143
+ "properties": {
144
+ "title": { "type": "string" },
145
+ "href": { "type": "string" },
146
+ "meta": { "type": "string" },
147
+ "cover": { "type": "string" },
148
+ "previewSheet": { "type": "string" },
149
+ "source": {
150
+ "type": "object", "required": ["path"],
151
+ "description": "External reference consumed at export. An optional SHA-256 must come from the session at handoff.",
152
+ "properties": { "path": { "type": "string" }, "sha256": { "type": "string", "pattern": "^[0-9a-fA-F]{64}$" } }
153
+ },
154
+ "availability": { "enum": ["verified", "export-copy", "missing"] },
155
+ "sessionSha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },
156
+ "unavailableReason": { "enum": ["outside-root", "unreadable"] },
157
+ "previewColumns": { "type": "array", "items": { "type": "string" } },
158
+ "revision": {
159
+ "type": "object",
160
+ "description": "Earlier local file and the corresponding line or cell to compare in both versions.",
161
+ "required": ["href", "label"],
162
+ "oneOf": [{ "required": ["page", "linePrefix"] }, { "required": ["sheet", "cell"] }],
163
+ "properties": {
164
+ "href": { "type": "string" }, "label": { "type": "string" },
165
+ "page": { "type": "integer", "minimum": 1 }, "linePrefix": { "type": "string", "minLength": 1 },
166
+ "sheet": { "type": "string", "minLength": 1 }, "cell": { "type": "string", "pattern": "^[a-zA-Z]+[1-9][0-9]*$" }
167
+ }
168
+ },
169
+ "preview": {
170
+ "properties": {
171
+ "change": {
172
+ "type": "object", "required": ["before", "after"],
173
+ "properties": { "before": { "type": "string" }, "after": { "type": "string" } }
174
+ }
175
+ },
176
+ "oneOf": [
177
+ {
178
+ "type": "object", "required": ["type", "pages"],
179
+ "properties": {
180
+ "type": { "const": "pdf" },
181
+ "pages": { "type": "array", "minItems": 1, "items": {
182
+ "type": "object", "required": ["src", "width", "height"],
183
+ "properties": { "src": { "type": "string" }, "width": { "type": "integer", "minimum": 1 }, "height": { "type": "integer", "minimum": 1 } }
184
+ } }
185
+ }
186
+ },
187
+ {
188
+ "type": "object", "required": ["type", "src", "sheet", "count", "rows"],
189
+ "properties": {
190
+ "type": { "const": "xlsx" }, "src": { "type": "string" }, "sheet": { "type": "string" },
191
+ "count": { "type": "integer", "minimum": 1 },
192
+ "rows": { "type": "array", "items": { "type": "array", "items": { "type": "string" } } }
193
+ }
194
+ }
195
+ ]
196
+ },
197
+ "portrait": {
198
+ "description": "Portrait cut of the same video, sharing the landscape cut's timeline.",
199
+ "type": "object",
200
+ "required": ["href"],
201
+ "properties": {
202
+ "href": { "type": "string" },
203
+ "cover": { "type": "string" }
204
+ }
205
+ }
206
+ }
207
+ },
208
+ "sessionItem": {
209
+ "type": "object",
210
+ "required": ["type"],
211
+ "properties": {
212
+ "deliverables": {
213
+ "type": "array", "description": "Files handed over at this event.",
214
+ "items": { "$ref": "#/$defs/deliverable" }
215
+ },
216
+ "type": {
217
+ "type": "string",
218
+ "enum": ["user", "assistant", "reasoning", "tool", "compact"]
219
+ },
220
+ "text": { "type": "string" },
221
+ "time": { "type": "string" },
222
+ "done": { "type": "string" },
223
+ "name": { "type": "string" },
224
+ "kind": { "type": "string" },
225
+ "summary": { "type": "string" },
226
+ "input": { "type": "string" },
227
+ "output": { "type": "string" },
228
+ "file": { "type": "string" },
229
+ "files": {
230
+ "type": "array",
231
+ "items": { "type": "string" }
232
+ },
233
+ "skill": { "type": "string" },
234
+ "agent": { "type": "string" },
235
+ "question": { "type": "boolean" },
236
+ "answer": { "type": "boolean" },
237
+ "contextTokens": { "type": "integer", "minimum": 0 },
238
+ "images": {
239
+ "type": "array",
240
+ "items": { "type": "string" }
241
+ },
242
+ "omittedImages": { "type": "integer", "minimum": 0 },
243
+ "stats": {
244
+ "type": "object",
245
+ "additionalProperties": { "type": "integer", "minimum": 0 }
246
+ },
247
+ "seq": { "type": "integer", "minimum": 1 },
248
+ "trigger": { "type": "string" },
249
+ "preTokens": { "type": "integer", "minimum": 0 },
250
+ "postTokens": { "type": "integer", "minimum": 0 },
251
+ "droppedTokens": { "type": "integer", "minimum": 0 }
252
+ }
253
+ }
254
+ }
255
+ }
@@ -1,80 +1,84 @@
1
1
  ---
2
2
  name: encore
3
3
  description: >
4
- Export, curate, and polish AI Agent session replays (Codex, Claude Code, Claude.ai) into standalone web stage replays using Encore.
5
- Use when the user asks to export a session replay, polish/curate a generated `session.json`, prune and label `.webp` process screenshots, write a replay title and story intro, or clean up semantic privacy leaks before publishing.
4
+ Export, curate, and rebuild portable AI Agent replays (Codex, Claude Code, Claude.ai, WorkBuddy) with Encore.
5
+ Use when the user asks to export a Raw Log into a Replay, curate `session.json`, select and label `.webp` Frames, review packaged Attachments or Deliverables, write a title and opening description, or redact residual sensitive details before publishing.
6
6
  ---
7
7
 
8
- # Encore — AI Agent Session Replay & Curation Skill
8
+ # Encore — Session Replay & Curation Skill
9
9
 
10
- `encore` turns raw AI Agent logs (`Codex`, `Claude Code`, `Claude.ai`) into an interactive web replay stage (**Left**: streaming conversation, tool shimmer, sub-agents, and visual deliverables; **Right**: live Context Window inspector and compaction boundaries; **Bottom**: milestone timeline).
10
+ Encore turns a Raw Log from **Codex**, **Claude Code**, **Claude.ai**, or **WorkBuddy** into a portable **Replay** rendered by the standalone **Player** (**Left**: Turns, Tool calls, Sub-agents, Attachments, Deliverables, and Frames; **Right**: live Context Snapshot inspector and Compaction boundaries; **Bottom**: Step timeline).
11
11
 
12
- While `npx @niracler/encore` produces an immediately playable replay ("raw cut / 生肉"), this skill guides you through turning it into a curated, publication-ready showcase ("director's cut / 熟肉").
12
+ While `npx @niracler/encore@latest` builds an immediately playable Replay, this skill guides **Curation** before publishing.
13
13
 
14
14
  ---
15
15
 
16
16
  ## Workflow
17
17
 
18
- ### 1. Locate or Generate the Initial Replay Folder
18
+ ### 1. Export the Initial Replay
19
19
 
20
- - If the user hasn't specified a log file yet, list recent local sessions:
20
+ - If the user has not specified a Raw Log yet, list recent local sessions:
21
21
  ```bash
22
- npx @niracler/encore --list
22
+ npx @niracler/encore@latest --list
23
23
  ```
24
- - Export the target session into a replay directory (without blocking on the preview server):
24
+ - Export the target Raw Log into an explicit Replay directory with `-o` so it is saved outside the default temporary preview directory, without blocking on the preview server (pass `--asset-root <dir>` if referenced Attachments or Deliverables live outside the current working directory and native session workspace):
25
25
  ```bash
26
- npx @niracler/encore <path-to-log.jsonl> -o ./replays/<slug> --no-serve
26
+ npx @niracler/encore@latest <path-to-log.jsonl> -o ./replays/<slug> --no-serve
27
27
  ```
28
- - This produces:
29
- - `session.json` — self-contained replay data & metadata (`title`, `description`, `deliverables`, `frames`, `items`)
30
- - `*.webp` — deduplicated embedded images extracted from the session
31
- - `index.html`, `encore-player.js`, `encore-player.css` — standalone web player (`<div data-encore-player src="./session.json"></div>`)
28
+ - Output files:
29
+ - `session.json` — canonical **Session** data (`title`, `description`, `initialContext`, `deliverables`, `frames`, `items`)
30
+ - `*.webp` — deduplicated embedded **Frames** extracted from the Raw Log
31
+ - `attachments/` — collected **Attachments** and **Deliverables** within allowed **Asset Roots**, plus generated PDF/XLSX previews when applicable
32
+ - `index.html`, `encore-player.js`, `encore-player.css` — standalone **Player** (`<div data-encore-player src="./session.json"></div>`)
32
33
 
33
34
  ---
34
35
 
35
- ### 2. Visual Frame Curation & Naming (`frames[]`)
36
+ ### 2. Curate & Label Frames (`frames[]`)
36
37
 
37
- Raw sessions often contain 15–40 screenshots, including terminal errors, minor CSS tweaks, or duplicate checks.
38
+ Raw exports often contain 15–40 Frames, including terminal errors, minor tweaks, or duplicate views.
38
39
 
39
40
  1. **Inspect every image**: Use `view_image` (or `Read`) to visually inspect each `.webp` file listed in `session.json -> frames`.
40
- 2. **Prune noise**: Delete entries from `session.json -> frames` that are broken renders, repetitive micro-adjustments, or uninformative screenshots. Keep **3 to 12 key visual milestones** that clearly show the evolution from reference/sketch to final output.
41
- 3. **Write narrative labels**: Replace generic fallback labels (`过程产出 #1` / `Stage Output #1`) with concrete 6–16 character labels that tell the viewer what changed:
41
+ 2. **Keep key milestones**: Remove broken renders, repetitive micro-adjustments, or uninformative entries from `session.json -> frames`. Keep **3 to 12 milestone Frames** showing progression from reference to final result.
42
+ 3. **Write concrete labels**: Replace fallback labels (`过程画面 #1` / `Agent Frame #1`) with concrete 6–16 character labels stating what changed:
42
43
  - Good: `"第一张草图:信息过载"`, `"V2:改为深色双栏网格"`, `"终稿:定版课程海报"`
43
44
  - Bad: `"图片 1"`, `"修改后"`, `"赋能视觉升级版"`
44
45
 
45
46
  ---
46
47
 
47
- ### 3. Title & Story Intro (`title` & `description`)
48
+ ### 3. Write Title & Opening Description (`title` & `description`)
48
49
 
49
- Edit the top-level `title` and `description` in `session.json` following these **direct, anti-fluff writing rules**:
50
+ Edit the top-level `title` and `description` in `session.json`:
50
51
 
51
52
  1. **`title` (8–24 chars)**:
52
53
  - State the concrete task, turning point, or friction directly.
53
54
  - Good: `"嫌太难看,重新设计七阶段图"`, `"把内部播放器拆成开源工具 Encore"`, `"排查 Mesh 40940 冲突并补齐测试"`
54
- - Avoid empty buzzwords (`赋能`, `深度剖析`, `全方位重构`, `探索与实践`, `基于 AI 的…`).
55
+ - Skip empty buzzwords (`赋能`, `深度剖析`, `全方位重构`, `探索与实践`, `基于 AI 的…`).
55
56
  2. **`description` (1–3 sentences, 40–120 chars)**:
56
- - Shown on the empty stage before the viewer clicks **Play**.
57
- - Explain **what problem the session tackled**, **what key pivot or collaboration happened mid-way**, and **what outcome was reached**.
58
- - Write in plain, natural prose. Do not repeat the title word-for-word.
57
+ - Shown in the **Player** before the viewer clicks **Play**.
58
+ - State **what problem the Session tackled**, **what key pivot or Sub-agent collaboration happened**, and **what Deliverable or outcome was reached**.
59
+ - Write plain, direct prose without repeating the title.
59
60
 
60
61
  ---
61
62
 
62
- ### 4. Semantic Privacy & Time-Window Cleanup (`items[]`)
63
+ ### 4. Redaction, Packaged Files, & Turn Trimming
63
64
 
64
- `encore` automatically masks home paths (`~`), API keys (`[密钥]`), emails (`[邮箱]`), and private IPs (`[内网地址]`), and prints non-blocking warnings for suspicious strings.
65
+ Automatic **Redaction** rewrites `session.json` to hide home paths (`~`), API keys (`[密钥]`), emails (`[邮箱]`), and private IPs (`[内网地址]`), and prints non-blocking **Leak Check** warnings.
65
66
 
66
- 1. **Check CLI warnings**: Inspect any paths reported by `encore` under `Privacy check found ... potential sensitive snippet(s)`.
67
- 2. **Scan for semantic leaks across both `initialContext` and `items[]`**: Regex cannot catch internal company codenames, colleague names, private intranet hostnames, or confidential business numbers. Always inspect `initialContext.mem`, `initialContext.sys`, `items[type="compact"].text`, and `items[]`, replacing sensitive passages with a clear marker such as:
68
- - `(涉及内部业务细节,已略去)` or `(Internal context redacted)`
69
- 3. **Trim off-topic tails**: If the user chatted about an unrelated topic at the beginning or end of the same window, either re-run `npx @niracler/encore <log.jsonl> --from <ISO> --to <ISO> -o <dir> --no-serve` or remove the off-topic entries from `session.json -> items`.
67
+ 1. **Review Leak Check warnings**: Inspect every path reported under `Leak check found ... potential sensitive snippet(s)`.
68
+ 2. **Redact residual sensitive details in `initialContext` and `items[]`**: Regex cannot catch internal codenames, colleague names, intranet hostnames, or business figures. Inspect `initialContext.mem`, `initialContext.sys`, `items[type="compact"].text`, and `items[]`, replacing sensitive passages with a clear marker such as `(涉及内部业务细节,已略去)` or `(Internal context redacted)`.
69
+ 3. **Inspect packaged Attachments and Deliverables (`attachments/`)**: Automatic Redaction only rewrites `session.json`; it does not modify packaged PDFs, spreadsheets, images, or videos. Verify each collected file before publishing, and remove or replace any file that contains private data.
70
+ 4. **Trim off-topic Turns**: If the Raw Log starts or ends with an unrelated topic, either re-export with `--from <ISO> --to <ISO>` or remove those Events from `session.json -> items`.
70
71
 
71
72
  ---
72
73
 
73
- ### 5. Re-render & Verify
74
+ ### 5. Rebuild & Verify
74
75
 
75
- - Because `index.html` dynamically mounts `<div data-encore-player src="./session.json"></div>`, any edits to `session.json` take effect immediately on browser refresh.
76
- - Run `npx @niracler/encore ./replays/<slug> --no-serve` once after editing `session.json` so `index.html`'s `<title>` tag is synced and the privacy leak check runs cleanly against your curated JSON.
77
- - To launch a live local preview for the user:
76
+ - Because `index.html` loads `./session.json` at runtime, edits to `session.json` appear immediately on browser refresh.
77
+ - Run a **Rebuild** after editing `session.json` so Encore refreshes Player assets, syncs `<title>`, refreshes attachment previews, drops references to deleted Frames, and re-runs the **Leak Check** without re-importing the Raw Log or overwriting Curation edits:
78
78
  ```bash
79
- npx @niracler/encore play ./replays/<slug>
79
+ npx @niracler/encore@latest ./replays/<slug> --no-serve
80
+ ```
81
+ - Launch a local preview for the user:
82
+ ```bash
83
+ npx @niracler/encore@latest play ./replays/<slug>
80
84
  ```
@@ -0,0 +1,169 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
3
+ import { extname, join, resolve, sep } from 'node:path'
4
+ import sharp from 'sharp'
5
+
6
+ function assertZipArchive(bytes) {
7
+ const isZip = bytes.length >= 4 && bytes[0] === 0x50 && bytes[1] === 0x4b
8
+ && ((bytes[2] === 0x03 && bytes[3] === 0x04) || (bytes[2] === 0x05 && bytes[3] === 0x06))
9
+ if (!isZip) throw new Error('Invalid XLSX archive')
10
+ }
11
+
12
+ function sheetRangeFromA1(sheet) {
13
+ const ref = sheet['!ref']
14
+ if (!ref) return undefined
15
+ const end = ref.includes(':') ? ref.split(':')[1] : ref
16
+ return `A1:${end}`
17
+ }
18
+
19
+ function cellText(value) {
20
+ if (value instanceof Date) return value.toISOString()
21
+ return value == null ? '' : String(value)
22
+ }
23
+
24
+ async function parseWorkbook(bytes, options = {}) {
25
+ assertZipArchive(bytes)
26
+ const { default: xlsx } = await import('node-xlsx')
27
+ return xlsx.parse(bytes, {
28
+ raw: true,
29
+ cellDates: true,
30
+ UTC: true,
31
+ defval: '',
32
+ blankrows: true,
33
+ ...options,
34
+ })
35
+ }
36
+
37
+ function readReplayAsset(directory, href) {
38
+ if (!href || /^(?:[a-z][\w+.-]*:|[/\\])/i.test(href)) throw new Error('Expected a replay-relative file')
39
+ const path = realpathSync(resolve(directory, href))
40
+ if (!path.startsWith(realpathSync(directory) + sep)) throw new Error('File is outside the replay')
41
+ return readFileSync(path)
42
+ }
43
+
44
+ async function revisionValue(bytes, ext, revision) {
45
+ if (ext === '.xlsx') {
46
+ const address = /^([A-Z]+)([1-9]\d*)$/i.exec(revision.cell)
47
+ if (!address || !revision.sheet) throw new Error('Expected a sheet name and A1 cell address')
48
+ const cell = revision.cell.toUpperCase()
49
+ const [sheet] = await parseWorkbook(bytes, { sheets: [revision.sheet], range: `${cell}:${cell}` })
50
+ if (!sheet) throw new Error(`Worksheet not found: ${revision.sheet}`)
51
+ return cellText(sheet.data[0]?.[0])
52
+ }
53
+ const { PDFiumLibrary } = await import('@hyzyla/pdfium')
54
+ const library = await PDFiumLibrary.init()
55
+ let document
56
+ try {
57
+ document = await library.loadDocument(bytes)
58
+ if (!Number.isInteger(revision.page) || revision.page < 1 || revision.page > document.getPageCount()) {
59
+ throw new Error('PDF page is out of range')
60
+ }
61
+ const lines = document.getPage(revision.page - 1).getText().split(/\r\n|[\r\n]/).map(line => line.trim())
62
+ const matches = lines.filter(line => revision.linePrefix && line.startsWith(revision.linePrefix))
63
+ if (matches.length !== 1) throw new Error(`Expected one matching PDF line on page ${revision.page}, found ${matches.length}`)
64
+ return matches[0]
65
+ } finally {
66
+ document?.destroy()
67
+ library.destroy()
68
+ }
69
+ }
70
+
71
+ async function previewPdf(bytes, staging, url) {
72
+ const { PDFiumLibrary } = await import('@hyzyla/pdfium')
73
+ const library = await PDFiumLibrary.init()
74
+ let document
75
+ try {
76
+ document = await library.loadDocument(bytes)
77
+ const pages = []
78
+ for (const page of document.pages()) {
79
+ const { originalWidth, originalHeight } = page.getOriginalSize()
80
+ const image = await page.render({ scale: 1800 / Math.max(originalWidth, originalHeight), render: 'bitmap' })
81
+ const name = `page-${pages.length + 1}.webp`
82
+ await sharp(image.data, { raw: { width: image.width, height: image.height, channels: 4 } })
83
+ .webp({ quality: 85 }).toFile(join(staging, name))
84
+ pages.push({ src: url + name, width: image.width, height: image.height })
85
+ }
86
+ if (!pages.length) throw new Error('Empty PDF')
87
+ return { type: 'pdf', pages }
88
+ } finally {
89
+ document?.destroy()
90
+ library.destroy()
91
+ }
92
+ }
93
+
94
+ async function previewWorkbook(bytes, staging, url, file) {
95
+ const parsed = await parseWorkbook(bytes, { range: sheetRangeFromA1 })
96
+ const sheets = parsed.map(({ name, data }) => ({
97
+ sheet: name,
98
+ data: data.map(row => row.map(cellText)),
99
+ }))
100
+ const selected = sheets.find(sheet => sheet.sheet === file.previewSheet) || sheets[0]
101
+ if (!selected) throw new Error('Empty workbook')
102
+ const header = selected.data[0] || []
103
+ const indexes = file.previewColumns?.length
104
+ ? file.previewColumns.map(name => header.indexOf(name)).filter(index => index >= 0)
105
+ : []
106
+ if (!indexes.length) indexes.push(...header.slice(0, 3).map((_, i) => i))
107
+ const rows = selected.data.slice(0, 4).map(row => indexes.map(i => String(row[i] ?? '')))
108
+ writeFileSync(join(staging, 'sheets.json'), JSON.stringify(sheets))
109
+ return { type: 'xlsx', src: url + 'sheets.json', sheet: selected.sheet, count: sheets.length, rows }
110
+ }
111
+
112
+ // Preview only files packaged inside this replay. External links keep their existing behavior.
113
+ export async function prepareAttachmentPreviews(session, directory) {
114
+ let changed = false
115
+ const files = [...(session.deliverables || session.files || []), ...(session.items || []).flatMap(item => item.deliverables || [])]
116
+ for (const file of files) {
117
+ if (file.availability === 'missing') continue
118
+ const href = file.href || ''
119
+ const ext = extname(href).toLowerCase()
120
+ if (!['.pdf', '.xlsx'].includes(ext) || /^(?:[a-z][\w+.-]*:|[/\\])/i.test(href)) continue
121
+ let preview
122
+ try {
123
+ const bytes = readReplayAsset(directory, href)
124
+ const key = createHash('sha256').update(bytes)
125
+ .update(JSON.stringify([1, ext, file.previewSheet, file.previewColumns])).digest('hex').slice(0, 24)
126
+ const url = `encore-previews/${key}/`
127
+ const target = join(directory, url)
128
+ const manifest = join(target, 'preview.json')
129
+ if (!existsSync(manifest)) {
130
+ const root = join(directory, 'encore-previews')
131
+ mkdirSync(root, { recursive: true })
132
+ const staging = mkdtempSync(join(root, 'building-'))
133
+ try {
134
+ preview = ext === '.pdf' ? await previewPdf(bytes, staging, url) : await previewWorkbook(bytes, staging, url, file)
135
+ writeFileSync(join(staging, 'preview.json'), JSON.stringify(preview))
136
+ try {
137
+ renameSync(staging, target)
138
+ } catch (err) {
139
+ if (!existsSync(manifest)) throw err
140
+ }
141
+ } finally {
142
+ rmSync(staging, { recursive: true, force: true })
143
+ }
144
+ }
145
+ preview = JSON.parse(readFileSync(manifest, 'utf8'))
146
+ if (file.revision) {
147
+ try {
148
+ const previous = readReplayAsset(directory, file.revision.href)
149
+ const before = await revisionValue(previous, ext, file.revision)
150
+ const after = await revisionValue(bytes, ext, file.revision)
151
+ if (before !== after) preview.change = { before, after }
152
+ } catch (err) {
153
+ // A missing earlier version does not prevent reading the current file.
154
+ console.warn(`Could not compare ${href}: ${err.message}`)
155
+ }
156
+ }
157
+ } catch (err) {
158
+ // An unreadable attachment can still be downloaded. Keep the rest of the replay usable.
159
+ console.warn(`Could not preview ${href}: ${err.message}`)
160
+ preview = undefined
161
+ }
162
+ if (JSON.stringify(file.preview) !== JSON.stringify(preview)) {
163
+ if (preview) file.preview = preview
164
+ else delete file.preview
165
+ changed = true
166
+ }
167
+ }
168
+ return changed
169
+ }