dsh-ppt 0.23.0 → 0.24.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,1193 @@
1
+ /**
2
+ * deck-import.mjs —— 外部 .pptx 全量内容提取与版式映射器(100% @office-kit/pptx + Node 内置模块,零外部依赖)。
3
+ *
4
+ * 提取每页真实内容:
5
+ * - 标题、Kicker / Eyebrow、副标题、正文段落与要点(保留粗体引导词为 **bold**)
6
+ * - 表格(<a:tbl> -> 矩形 rows: string[][])
7
+ * - 原生图表(ppt/charts/chart*.xml -> { kind, categories, series, caption },保留可编辑数据)
8
+ * - 嵌入位图(png / jpeg / webp,安全写入 assetOutDir/imported-sN-M.<ext> 或 data URI)
9
+ * - 演讲者备注(ppt/notesSlides/notesSlide*.xml -> slide.notes,剥离页码占位符)
10
+ * 并智能映射为最契合的 dsh-ppt 原生版式原型:
11
+ * cover / section / kpi / cards / comparison / table / chart / chart-split /
12
+ * image-left / image-right / gallery / closing / bullets
13
+ */
14
+
15
+ import { lstatSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
16
+ import { createHash } from 'node:crypto'
17
+ import { dirname, posix, resolve, join } from 'node:path'
18
+ import { inflateSync } from 'node:zlib'
19
+
20
+ const MAX_PPTX_BYTES = 64 * 1024 * 1024
21
+ const MAX_IMAGE_BYTES = 5 * 1024 * 1024
22
+
23
+ const SUPPORTED_CHART_KINDS = new Set([
24
+ 'column', 'bar', 'line', 'area', 'pie', 'doughnut',
25
+ 'stacked-column', 'stacked-bar', 'percent-column', 'percent-bar',
26
+ 'radar', 'scatter', 'waterfall',
27
+ ])
28
+
29
+ const KPI_NUM_RE = /(?:[$¥€£]|\b\d+(?:[.,]\d+)?\s*(?:[%%倍xX万亿千百kKmMbBtT]+|亿元|亿美元|万元|美元|元|家|个|人|次|天|小时|ms|pp|bps)?)/
30
+
31
+ function fail(zh, en) {
32
+ throw new Error('dsh-ppt:' + zh + (en ? ' / ' + en : ''))
33
+ }
34
+
35
+ function decodeXml(str) {
36
+ return String(str ?? '')
37
+ .replace(/&#x([0-9a-fA-F]+);/g, (_, hex) => {
38
+ const code = Number.parseInt(hex, 16)
39
+ return Number.isFinite(code) ? String.fromCodePoint(code) : ''
40
+ })
41
+ .replace(/&#(\d+);/g, (_, dec) => {
42
+ const code = Number.parseInt(dec, 10)
43
+ return Number.isFinite(code) ? String.fromCodePoint(code) : ''
44
+ })
45
+ .replace(/&lt;/g, '<')
46
+ .replace(/&gt;/g, '>')
47
+ .replace(/&quot;/g, '"')
48
+ .replace(/&apos;/g, "'")
49
+ .replace(/&amp;/g, '&')
50
+ }
51
+
52
+ function safePartName(name) {
53
+ const s = String(name ?? '').replace(/\\/g, '/').trim()
54
+ if (!s) return ''
55
+ return s.startsWith('/') ? s : '/' + s
56
+ }
57
+
58
+ function resolveRelTarget(basePart, target) {
59
+ const clean = String(target ?? '').replace(/\\/g, '/').trim()
60
+ if (!clean || /^[a-z][a-z0-9+.-]*:/i.test(clean)) return ''
61
+ if (clean.startsWith('/')) return posix.normalize(clean)
62
+ const dir = posix.dirname(safePartName(basePart))
63
+ return posix.normalize(posix.join(dir, clean))
64
+ }
65
+
66
+ function relsPartFor(partName) {
67
+ const p = safePartName(partName)
68
+ const dir = posix.dirname(p)
69
+ const base = posix.basename(p)
70
+ return (dir === '/' ? '' : dir) + '/_rels/' + base + '.rels'
71
+ }
72
+
73
+ function safeReadPartText(lib, pres, partName) {
74
+ if (!partName) return ''
75
+ for (const candidate of [safePartName(partName), safePartName(partName).replace(/^\//, '')]) {
76
+ try {
77
+ const raw = lib.readPackagePart?.(pres, candidate)
78
+ if (raw && raw.byteLength > 0) return Buffer.from(raw).toString('utf8')
79
+ } catch { /* ignore missing part */ }
80
+ }
81
+ return ''
82
+ }
83
+
84
+ function parseRelationships(relsXml) {
85
+ const map = new Map()
86
+ if (!relsXml) return map
87
+ const relRe = /<Relationship\b([^>]*)\/?>/g
88
+ for (const m of relsXml.matchAll(relRe)) {
89
+ const attrs = m[1]
90
+ const id = /\bId=["']([^"']+)["']/.exec(attrs)?.[1]
91
+ const type = /\bType=["']([^"']+)["']/.exec(attrs)?.[1] || ''
92
+ const target = /\bTarget=["']([^"']+)["']/.exec(attrs)?.[1] || ''
93
+ const targetMode = /\bTargetMode=["']([^"']+)["']/.exec(attrs)?.[1] || ''
94
+ if (id && target && targetMode.toLowerCase() !== 'external') {
95
+ map.set(id, { id, type, target })
96
+ }
97
+ }
98
+ return map
99
+ }
100
+
101
+ function extractXmlTextTokens(xmlFragment) {
102
+ const parts = []
103
+ for (const m of String(xmlFragment ?? '').matchAll(/<a:t\b[^>]*>([\s\S]*?)<\/a:t>/g)) {
104
+ parts.push(decodeXml(m[1]))
105
+ }
106
+ return parts.join('')
107
+ }
108
+
109
+ function formatRunsToMarkdown(runs) {
110
+ if (!runs.length) return { plain: '', markdown: '', maxSizePt: 0, hasBoldLead: false }
111
+ const merged = []
112
+ let maxSizePt = 0
113
+ for (const r of runs) {
114
+ if (r.sizePt && r.sizePt > maxSizePt) maxSizePt = r.sizePt
115
+ if (!r.text) continue
116
+ const last = merged[merged.length - 1]
117
+ if (last && last.bold === r.bold) {
118
+ last.text += r.text
119
+ } else {
120
+ merged.push({ text: r.text, bold: Boolean(r.bold) })
121
+ }
122
+ }
123
+ const plain = merged.map((r) => r.text).join('').replace(/\s+/g, ' ').trim()
124
+ if (!plain) return { plain: '', markdown: '', maxSizePt, hasBoldLead: false }
125
+
126
+ const hasBold = merged.some((r) => r.bold && r.text.trim().length > 0)
127
+ const hasNonBold = merged.some((r) => !r.bold && r.text.trim().length > 0)
128
+ if (!hasBold || !hasNonBold) {
129
+ return { plain, markdown: plain, maxSizePt, hasBoldLead: false }
130
+ }
131
+
132
+ let md = ''
133
+ let hasBoldLead = false
134
+ merged.forEach((seg, idx) => {
135
+ if (!seg.bold) {
136
+ md += seg.text
137
+ return
138
+ }
139
+ const leadMatch = /^(\s*)([\s\S]*?)(\s*)$/.exec(seg.text)
140
+ const pre = leadMatch?.[1] ?? ''
141
+ const core = leadMatch?.[2] ?? ''
142
+ const post = leadMatch?.[3] ?? ''
143
+ if (!core) {
144
+ md += seg.text
145
+ return
146
+ }
147
+ if (idx === 0) hasBoldLead = true
148
+ md += pre + '**' + core + '**' + post
149
+ })
150
+ md = md.replace(/\*\*\s*\*\*/g, '').replace(/[ \t]+/g, ' ').trim()
151
+ return { plain, markdown: md, maxSizePt, hasBoldLead }
152
+ }
153
+
154
+ function extractParagraphsFromTxBody(txBodyXml) {
155
+ if (!txBodyXml) return []
156
+ const paragraphs = []
157
+ const pRe = /<a:p\b[^>]*>([\s\S]*?)<\/a:p>/g
158
+ for (const pm of txBodyXml.matchAll(pRe)) {
159
+ const pInner = pm[1]
160
+ const runs = []
161
+ let pDefaultBold = false
162
+ let pDefaultSize = 0
163
+ const pPrMatch = /<a:pPr\b([^>]*)>([\s\S]*?)<\/a:pPr>/.exec(pInner)
164
+ if (pPrMatch) {
165
+ const defRPr = /<a:defRPr\b([^>]*)>/.exec(pPrMatch[2])
166
+ if (defRPr) {
167
+ if (/\bb=["']?(?:1|true)["']?/i.test(defRPr[1])) pDefaultBold = true
168
+ const szM = /\bsz=["'](\d+)["']/.exec(defRPr[1])
169
+ if (szM) pDefaultSize = Number(szM[1]) / 100
170
+ }
171
+ }
172
+
173
+ const tokenRe = /<a:r\b[^>]*>([\s\S]*?)<\/a:r>|<a:fld\b([^>]*)>([\s\S]*?)<\/a:fld>|<a:br\b[^>]*\/?>/g
174
+ for (const tm of pInner.matchAll(tokenRe)) {
175
+ if (tm[0].startsWith('<a:br')) {
176
+ runs.push({ text: ' ', bold: false, sizePt: pDefaultSize })
177
+ continue
178
+ }
179
+ if (tm[0].startsWith('<a:fld')) {
180
+ const fldAttrs = tm[2] || ''
181
+ if (/\btype=["']slidenum["']/i.test(fldAttrs)) continue
182
+ const fldInner = tm[3] || ''
183
+ const text = extractXmlTextTokens(fldInner)
184
+ if (text) runs.push({ text, bold: pDefaultBold, sizePt: pDefaultSize })
185
+ continue
186
+ }
187
+ const rInner = tm[1] || ''
188
+ const rPrAttrs = /<a:rPr\b([^>]*?)(?:\/>|>)/.exec(rInner)?.[1] || ''
189
+ const isBold = /\bb=["']?(?:1|true)["']?/i.test(rPrAttrs)
190
+ ? true
191
+ : /\bb=["']?(?:0|false)["']?/i.test(rPrAttrs)
192
+ ? false
193
+ : pDefaultBold
194
+ const szM = /\bsz=["'](\d+)["']/.exec(rPrAttrs)
195
+ const sizePt = szM ? Number(szM[1]) / 100 : pDefaultSize
196
+ const text = extractXmlTextTokens(rInner)
197
+ if (text) runs.push({ text, bold: isBold, sizePt })
198
+ }
199
+ const formatted = formatRunsToMarkdown(runs)
200
+ if (formatted.plain) {
201
+ paragraphs.push(formatted)
202
+ }
203
+ }
204
+ return paragraphs
205
+ }
206
+
207
+ function extractParagraphsFromShape(lib, shape) {
208
+ try {
209
+ const xml = lib.getShapeXmlString?.(shape)
210
+ if (xml) {
211
+ const txBody = /<p:txBody\b[^>]*>([\s\S]*?)<\/p:txBody>|<a:txBody\b[^>]*>([\s\S]*?)<\/a:txBody>/.exec(xml)
212
+ const inner = txBody?.[1] || txBody?.[2] || ''
213
+ if (inner) {
214
+ const paras = extractParagraphsFromTxBody(inner)
215
+ if (paras.length > 0) return paras
216
+ }
217
+ }
218
+ } catch { /* fallback to run API */ }
219
+
220
+ const out = []
221
+ try {
222
+ const pCount = lib.getShapeParagraphCount?.(shape) ?? 0
223
+ for (let p = 0; p < pCount; p += 1) {
224
+ const rCount = lib.getShapeRunCount?.(shape, p) ?? 0
225
+ const runs = []
226
+ for (let r = 0; r < rCount; r += 1) {
227
+ const text = lib.getShapeRunText?.(shape, p, r) ?? ''
228
+ const fmt = lib.getShapeRunFormat?.(shape, p, r) ?? {}
229
+ runs.push({ text, bold: Boolean(fmt.bold), sizePt: Number(fmt.size || 0) })
230
+ }
231
+ const formatted = formatRunsToMarkdown(runs)
232
+ if (formatted.plain) out.push(formatted)
233
+ }
234
+ } catch { /* ignore */ }
235
+ if (out.length === 0) {
236
+ try {
237
+ const raw = String(lib.getShapeText?.(shape) ?? '').trim()
238
+ if (raw) {
239
+ for (const line of raw.split(/\r?\n/)) {
240
+ const t = line.trim()
241
+ if (t) out.push({ plain: t, markdown: t, maxSizePt: 0, hasBoldLead: false })
242
+ }
243
+ }
244
+ } catch { /* ignore */ }
245
+ }
246
+ return out
247
+ }
248
+
249
+ function flattenShapes(lib, shapes) {
250
+ const out = []
251
+ const visit = (list) => {
252
+ if (!Array.isArray(list)) return
253
+ for (const s of list) {
254
+ if (!s) continue
255
+ out.push(s)
256
+ try {
257
+ const children = lib.getGroupChildren?.(s)
258
+ if (Array.isArray(children) && children.length > 0) visit(children)
259
+ } catch { /* not a group */ }
260
+ }
261
+ }
262
+ visit(shapes)
263
+ return out
264
+ }
265
+
266
+ function getBoundsNorm(lib, shape, slideW, slideH) {
267
+ let b = null
268
+ try {
269
+ b = lib.getShapeBoundsResolved?.(shape)
270
+ } catch { /* ignore */ }
271
+ if (!b || !Number.isFinite(b.w)) {
272
+ try { b = lib.getShapeBounds?.(shape) } catch { b = null }
273
+ }
274
+ if (!b || !Number.isFinite(b.w) || !Number.isFinite(b.h)) {
275
+ return { x: 0, y: 0, w: 0, h: 0 }
276
+ }
277
+ return {
278
+ x: (b.x ?? 0) / slideW,
279
+ y: (b.y ?? 0) / slideH,
280
+ w: (b.w ?? 0) / slideW,
281
+ h: (b.h ?? 0) / slideH,
282
+ }
283
+ }
284
+
285
+ // ---------------------------------------------------------------------------
286
+ // Notes Extraction (stripping slide number placeholders)
287
+ // ---------------------------------------------------------------------------
288
+
289
+ function extractNotesFromXml(notesXml, slideNumber = 0) {
290
+ if (!notesXml) return ''
291
+ const lines = []
292
+ const spRe = /<p:sp\b[^>]*>([\s\S]*?)<\/p:sp>/g
293
+ for (const sm of notesXml.matchAll(spRe)) {
294
+ const spInner = sm[1]
295
+ const phMatch = /<p:ph\b([^>]*)\/?>/.exec(spInner)
296
+ const phType = phMatch ? (/\btype=["']([^"']+)["']/.exec(phMatch[1])?.[1] || '') : ''
297
+ if (phType === 'sldImg' || phType === 'sldNum' || phType === 'hdr' || phType === 'ftr' || phType === 'dt') {
298
+ continue
299
+ }
300
+ const txBody = /<p:txBody\b[^>]*>([\s\S]*?)<\/p:txBody>/.exec(spInner)?.[1] || ''
301
+ if (!txBody) continue
302
+ for (const p of extractParagraphsFromTxBody(txBody)) {
303
+ if (p.plain) lines.push(p.plain)
304
+ }
305
+ }
306
+ if (lines.length > 1 && slideNumber > 0 && lines[lines.length - 1].trim() === String(slideNumber)) {
307
+ lines.pop()
308
+ }
309
+ return lines.join('\n').trim()
310
+ }
311
+
312
+ function extractSlideNotes(lib, pres, slide, slidePartName, slideRels, slideNumber = 0) {
313
+ for (const rel of slideRels.values()) {
314
+ if (/\/notesSlide$/i.test(rel.type)) {
315
+ const notesPart = resolveRelTarget(slidePartName, rel.target)
316
+ const notesXml = safeReadPartText(lib, pres, notesPart)
317
+ const cleaned = extractNotesFromXml(notesXml, slideNumber)
318
+ if (cleaned) return cleaned
319
+ }
320
+ }
321
+ try {
322
+ const fallback = String(lib.getSlideNotes?.(slide) ?? '').trim()
323
+ if (!fallback) return ''
324
+ return fallback
325
+ .split(/\r?\n/)
326
+ .map((l) => l.trim())
327
+ .filter((l, idx, arr) => l && !(idx === arr.length - 1 && /^\d{1,3}$/.test(l)))
328
+ .join('\n')
329
+ .trim()
330
+ } catch {
331
+ return ''
332
+ }
333
+ }
334
+
335
+ // ---------------------------------------------------------------------------
336
+ // Table Extraction (<a:tbl> -> rectangular string[][])
337
+ // ---------------------------------------------------------------------------
338
+
339
+ function extractTablesFromXml(slideXml) {
340
+ if (!slideXml) return []
341
+ const tables = []
342
+ const tblRe = /<a:tbl\b[^>]*>([\s\S]*?)<\/a:tbl>/g
343
+ for (const tm of slideXml.matchAll(tblRe)) {
344
+ const rows = []
345
+ for (const tr of tm[1].matchAll(/<a:tr\b[^>]*>([\s\S]*?)<\/a:tr>/g)) {
346
+ const row = []
347
+ for (const tc of tr[1].matchAll(/<a:tc\b([^>]*)>([\s\S]*?)<\/a:tc>/g)) {
348
+ const tcAttrs = tc[1]
349
+ const tcInner = tc[2]
350
+ const txBody = /<a:txBody\b[^>]*>([\s\S]*?)<\/a:txBody>/.exec(tcInner)?.[1] || ''
351
+ const cellText = extractParagraphsFromTxBody(txBody).map((p) => p.plain).join(' ').trim()
352
+ row.push(cellText)
353
+ const gridSpan = Number(/\bgridSpan=["'](\d+)["']/.exec(tcAttrs)?.[1] || 1)
354
+ for (let k = 1; k < gridSpan; k += 1) row.push('')
355
+ }
356
+ if (row.length > 0) rows.push(row)
357
+ }
358
+ if (rows.length > 0) {
359
+ const maxCols = Math.max(...rows.map((r) => r.length))
360
+ const rect = rows.map((r) => (r.length < maxCols ? [...r, ...Array(maxCols - r.length).fill('')] : r))
361
+ if (rect.length >= 2 && maxCols >= 1) tables.push(rect)
362
+ }
363
+ }
364
+ return tables
365
+ }
366
+
367
+ function extractSlideTablesNormalized(lib, slide, slideXml) {
368
+ const out = []
369
+ try {
370
+ const kitTables = lib.getSlideTables?.(slide) ?? []
371
+ for (const tbl of kitTables) {
372
+ const sz = lib.getTableSize?.(tbl)
373
+ let rowCount = sz?.rows
374
+ let colCount = sz?.cols
375
+ if (!rowCount || !colCount) {
376
+ const dims = lib.getTableDimensions?.(tbl)
377
+ rowCount = dims?.rows
378
+ colCount = dims?.cols
379
+ }
380
+ if (rowCount > 0 && colCount > 0) {
381
+ const rows = []
382
+ for (let r = 0; r < rowCount; r += 1) {
383
+ const row = []
384
+ for (let c = 0; c < colCount; c += 1) {
385
+ let txt = ''
386
+ try {
387
+ const cell = lib.getTableCell?.(tbl, r, c)
388
+ if (cell) txt = String(lib.getTableCellText?.(cell) ?? '').replace(/\s+/g, ' ').trim()
389
+ } catch { /* ignore */ }
390
+ row.push(txt)
391
+ }
392
+ rows.push(row)
393
+ }
394
+ if (rows.length >= 2) out.push(rows)
395
+ }
396
+ }
397
+ } catch { /* fallback to XML */ }
398
+
399
+ if (out.length === 0) {
400
+ out.push(...extractTablesFromXml(slideXml))
401
+ }
402
+ return out
403
+ }
404
+
405
+ // ---------------------------------------------------------------------------
406
+ // Chart Extraction (ppt/charts/chart*.xml <c:cat> / <c:val> + @office-kit)
407
+ // ---------------------------------------------------------------------------
408
+
409
+ function extractPointCache(blockXml, asNumber = false) {
410
+ if (!blockXml) return []
411
+ const pts = []
412
+ const ptRe = /<c:pt\b[^>]*\bidx=["'](\d+)["'][^>]*>[\s\S]*?<c:v>([\s\S]*?)<\/c:v>[\s\S]*?<\/c:pt>/g
413
+ for (const m of blockXml.matchAll(ptRe)) {
414
+ const idx = Number(m[1])
415
+ const raw = decodeXml(m[2]).trim()
416
+ pts.push({ idx, raw })
417
+ }
418
+ if (pts.length === 0) {
419
+ // Fallback for multiLvlStrRef or direct <c:v> inside <c:cat>/<c:val>
420
+ const lvlPts = []
421
+ let fallbackIdx = 0
422
+ for (const vm of blockXml.matchAll(/<c:v>([\s\S]*?)<\/c:v>/g)) {
423
+ lvlPts.push({ idx: fallbackIdx++, raw: decodeXml(vm[1]).trim() })
424
+ }
425
+ if (lvlPts.length > 0) {
426
+ return lvlPts.map((p) => (asNumber ? (Number.isFinite(Number(p.raw)) ? Number(p.raw) : 0) : p.raw))
427
+ }
428
+ return []
429
+ }
430
+ pts.sort((a, b) => a.idx - b.idx)
431
+ const maxIdx = pts[pts.length - 1].idx
432
+ const arr = Array(maxIdx + 1).fill(asNumber ? 0 : '')
433
+ for (const p of pts) {
434
+ if (asNumber) {
435
+ const n = Number(p.raw.replace(/,/g, ''))
436
+ arr[p.idx] = Number.isFinite(n) ? n : 0
437
+ } else {
438
+ arr[p.idx] = p.raw
439
+ }
440
+ }
441
+ return arr
442
+ }
443
+
444
+ function parseChartXml(chartXml) {
445
+ if (!chartXml || !/<c:chartSpace\b/.test(chartXml)) return null
446
+
447
+ const titleBlock = /<c:title\b[^>]*>([\s\S]*?)<\/c:title>/.exec(chartXml)?.[1] || ''
448
+ const caption = extractXmlTextTokens(titleBlock).replace(/\s+/g, ' ').trim()
449
+
450
+ let kind = 'column'
451
+ let plotBlock = ''
452
+
453
+ const barMatch = /<c:barChart\b[^>]*>([\s\S]*?)<\/c:barChart>/.exec(chartXml)
454
+ const bar3dMatch = /<c:bar3DChart\b[^>]*>([\s\S]*?)<\/c:bar3DChart>/.exec(chartXml)
455
+ const lineMatch = /<c:lineChart\b[^>]*>([\s\S]*?)<\/c:lineChart>/.exec(chartXml)
456
+ const areaMatch = /<c:areaChart\b[^>]*>([\s\S]*?)<\/c:areaChart>/.exec(chartXml)
457
+ const pieMatch = /<c:pieChart\b[^>]*>([\s\S]*?)<\/c:pieChart>/.exec(chartXml)
458
+ const doughnutMatch = /<c:doughnutChart\b[^>]*>([\s\S]*?)<\/c:doughnutChart>/.exec(chartXml)
459
+ const radarMatch = /<c:radarChart\b[^>]*>([\s\S]*?)<\/c:radarChart>/.exec(chartXml)
460
+ const scatterMatch = /<c:scatterChart\b[^>]*>([\s\S]*?)<\/c:scatterChart>/.exec(chartXml)
461
+
462
+ if (barMatch || bar3dMatch) {
463
+ plotBlock = (barMatch || bar3dMatch)[1]
464
+ const barDir = /<c:barDir\b[^>]*\bval=["']([^"']+)["']/.exec(plotBlock)?.[1] || 'col'
465
+ const grouping = /<c:grouping\b[^>]*\bval=["']([^"']+)["']/.exec(plotBlock)?.[1] || 'clustered'
466
+ const horiz = barDir === 'bar'
467
+ if (grouping === 'percentStacked') kind = horiz ? 'percent-bar' : 'percent-column'
468
+ else if (grouping === 'stacked') kind = horiz ? 'stacked-bar' : 'stacked-column'
469
+ else kind = horiz ? 'bar' : 'column'
470
+ } else if (lineMatch) {
471
+ plotBlock = lineMatch[1]
472
+ kind = 'line'
473
+ } else if (areaMatch) {
474
+ plotBlock = areaMatch[1]
475
+ kind = 'area'
476
+ } else if (doughnutMatch) {
477
+ plotBlock = doughnutMatch[1]
478
+ kind = 'doughnut'
479
+ } else if (pieMatch) {
480
+ plotBlock = pieMatch[1]
481
+ kind = 'pie'
482
+ } else if (radarMatch) {
483
+ plotBlock = radarMatch[1]
484
+ kind = 'radar'
485
+ } else if (scatterMatch) {
486
+ plotBlock = scatterMatch[1]
487
+ kind = 'scatter'
488
+ } else {
489
+ plotBlock = chartXml
490
+ }
491
+
492
+ let categories = []
493
+ const series = []
494
+ const serRe = /<c:ser\b[^>]*>([\s\S]*?)<\/c:ser>/g
495
+ let serIndex = 0
496
+ for (const sm of plotBlock.matchAll(serRe)) {
497
+ serIndex += 1
498
+ const serInner = sm[1]
499
+ const txBlock = /<c:tx\b[^>]*>([\s\S]*?)<\/c:tx>/.exec(serInner)?.[1] || ''
500
+ let name = ''
501
+ const directV = /<c:v>([\s\S]*?)<\/c:v>/.exec(txBlock)
502
+ if (directV) name = decodeXml(directV[1]).trim()
503
+ if (!name) name = 'Series ' + serIndex
504
+
505
+ const catBlock = /<c:cat\b[^>]*>([\s\S]*?)<\/c:cat>/.exec(serInner)?.[1] ||
506
+ /<c:xVal\b[^>]*>([\s\S]*?)<\/c:xVal>/.exec(serInner)?.[1] || ''
507
+ if (categories.length === 0 && catBlock) {
508
+ categories = extractPointCache(catBlock, false).map((v, i) => String(v || i + 1))
509
+ }
510
+
511
+ const valBlock = /<c:val\b[^>]*>([\s\S]*?)<\/c:val>/.exec(serInner)?.[1] ||
512
+ /<c:yVal\b[^>]*>([\s\S]*?)<\/c:yVal>/.exec(serInner)?.[1] || ''
513
+ const values = extractPointCache(valBlock, true)
514
+ if (values.length > 0) {
515
+ series.push({ name, values })
516
+ }
517
+ }
518
+
519
+ if (series.length === 0) return null
520
+ const maxLen = Math.max(categories.length, ...series.map((s) => s.values.length))
521
+ if (maxLen === 0) return null
522
+ if (categories.length < maxLen) {
523
+ for (let i = categories.length; i < maxLen; i += 1) categories.push(String(i + 1))
524
+ }
525
+ const normalizedSeries = series.map((s) => ({
526
+ name: s.name,
527
+ values: categories.map((_, idx) => (Number.isFinite(s.values[idx]) ? s.values[idx] : 0)),
528
+ }))
529
+
530
+ return {
531
+ kind: SUPPORTED_CHART_KINDS.has(kind) ? kind : 'column',
532
+ categories,
533
+ series: normalizedSeries,
534
+ ...(caption ? { caption } : {}),
535
+ }
536
+ }
537
+
538
+ function extractSlideChartsNormalized(lib, pres, slide, slidePartName, slideRels, slideW, slideH) {
539
+ const out = []
540
+
541
+ // 1) Try reading chart XML parts directly from slide relationships (<c:cat>/<c:val> caches)
542
+ for (const rel of slideRels.values()) {
543
+ if (/\/chart$/i.test(rel.type)) {
544
+ const chartPart = resolveRelTarget(slidePartName, rel.target)
545
+ const chartXml = safeReadPartText(lib, pres, chartPart)
546
+ const parsed = parseChartXml(chartXml)
547
+ if (parsed) out.push({ chart: parsed, bounds: null })
548
+ }
549
+ }
550
+
551
+ // 2) Cross-check with @office-kit/pptx getSlideCharts for bounding boxes and fallback specs
552
+ try {
553
+ const kitCharts = lib.getSlideCharts?.(slide) ?? []
554
+ kitCharts.forEach((entry, idx) => {
555
+ const bounds = entry.shape ? getBoundsNorm(lib, entry.shape, slideW, slideH) : null
556
+ if (out[idx]) {
557
+ out[idx].bounds = bounds
558
+ } else if (entry.spec && Array.isArray(entry.spec.series) && entry.spec.series.length > 0) {
559
+ const rawKind = String(entry.spec.kind || 'column')
560
+ const kind = SUPPORTED_CHART_KINDS.has(rawKind) ? rawKind : 'column'
561
+ const categories = Array.isArray(entry.spec.categories) && entry.spec.categories.length > 0
562
+ ? entry.spec.categories.map((c) => String(c))
563
+ : entry.spec.series[0].values.map((_, i) => String(i + 1))
564
+ out.push({
565
+ chart: {
566
+ kind,
567
+ categories,
568
+ series: entry.spec.series.map((s, si) => ({
569
+ name: String(s.name || `Series ${si + 1}`),
570
+ values: categories.map((_, ci) => {
571
+ const v = Number(s.values?.[ci])
572
+ return Number.isFinite(v) ? v : 0
573
+ }),
574
+ })),
575
+ ...(entry.spec.title ? { caption: String(entry.spec.title) } : {}),
576
+ },
577
+ bounds,
578
+ })
579
+ }
580
+ })
581
+ } catch { /* ignore */ }
582
+
583
+ return out
584
+ }
585
+
586
+ // ---------------------------------------------------------------------------
587
+ // Image Extraction (PNG / JPEG / WebP)
588
+ // ---------------------------------------------------------------------------
589
+
590
+ function inspectRasterImage(bytes) {
591
+ if (!bytes || bytes.byteLength < 24 || bytes.byteLength > MAX_IMAGE_BYTES) return null
592
+ const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes)
593
+
594
+ // PNG
595
+ if (buf.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
596
+ if (buf.length < 45 || buf.toString('ascii', 12, 16) !== 'IHDR') return null
597
+ const width = buf.readUInt32BE(16)
598
+ const height = buf.readUInt32BE(20)
599
+ if (!width || !height || width > 16000 || height > 16000) return null
600
+ let offset = 8
601
+ let ended = false
602
+ const compressed = []
603
+ while (offset + 12 <= buf.length) {
604
+ const length = buf.readUInt32BE(offset)
605
+ const type = buf.toString('ascii', offset + 4, offset + 8)
606
+ if (offset + length + 12 > buf.length) return null
607
+ if (type === 'IDAT') compressed.push(buf.subarray(offset + 8, offset + 8 + length))
608
+ if (type === 'IEND') { ended = true; break }
609
+ offset += length + 12
610
+ }
611
+ if (!ended || compressed.length === 0) return null
612
+ try { inflateSync(Buffer.concat(compressed), { maxOutputLength: 128 * 1024 * 1024 }) } catch { return null }
613
+ return { width, height, mime: 'image/png', ext: 'png', bytes: buf }
614
+ }
615
+
616
+ // JPEG
617
+ if (buf[0] === 0xff && buf[1] === 0xd8) {
618
+ let offset = 2
619
+ let width = 0
620
+ let height = 0
621
+ while (offset + 4 < buf.length) {
622
+ if (buf[offset] !== 0xff) break
623
+ while (offset < buf.length && buf[offset] === 0xff) offset += 1
624
+ if (offset >= buf.length) break
625
+ const marker = buf[offset++]
626
+ if (marker === 0xd9 || marker === 0xda) break
627
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue
628
+ if (offset + 2 > buf.length) return null
629
+ const length = buf.readUInt16BE(offset)
630
+ if (length < 2 || offset + length > buf.length) return null
631
+ if ([0xc0, 0xc1, 0xc2].includes(marker) && length >= 7) {
632
+ height = buf.readUInt16BE(offset + 3)
633
+ width = buf.readUInt16BE(offset + 5)
634
+ }
635
+ offset += length
636
+ }
637
+ if (!buf.subarray(-2).equals(Buffer.from([0xff, 0xd9])) || !width || !height) return null
638
+ return { width, height, mime: 'image/jpeg', ext: 'jpg', bytes: buf }
639
+ }
640
+
641
+ // WebP (RIFF....WEBP)
642
+ if (buf.length >= 30 && buf.toString('ascii', 0, 4) === 'RIFF' && buf.toString('ascii', 8, 12) === 'WEBP') {
643
+ const chunk = buf.toString('ascii', 12, 16)
644
+ let width = 0
645
+ let height = 0
646
+ if (chunk === 'VP8 ' && buf.length >= 30) {
647
+ width = buf.readUInt16LE(26) & 0x3fff
648
+ height = buf.readUInt16LE(28) & 0x3fff
649
+ } else if (chunk === 'VP8L' && buf.length >= 25) {
650
+ const bits = buf.readUInt32LE(21)
651
+ width = (bits & 0x3fff) + 1
652
+ height = ((bits >> 14) & 0x3fff) + 1
653
+ } else if (chunk === 'VP8X' && buf.length >= 30) {
654
+ width = 1 + (buf[24] | (buf[25] << 8) | (buf[26] << 16))
655
+ height = 1 + (buf[27] | (buf[28] << 8) | (buf[29] << 16))
656
+ }
657
+ if (width > 0 && height > 0 && width <= 16000 && height <= 16000) {
658
+ return { width, height, mime: 'image/webp', ext: 'webp', bytes: buf }
659
+ }
660
+ }
661
+
662
+ return null
663
+ }
664
+
665
+ function extractSlideImages(lib, pres, slide, slideIndex, slidePartName, slideRels, slideW, slideH, assetOutDir, extractedAssets) {
666
+ const shapes = flattenShapes(lib, lib.getSlideShapes(slide))
667
+ const seenHashes = new Set()
668
+ const items = []
669
+
670
+ const pushImage = (info, bounds, alt) => {
671
+ if (!info || info.width < 8 || info.height < 8) return
672
+ const digest = createHash('sha256').update(info.bytes).digest('hex')
673
+ if (seenHashes.has(digest)) return
674
+ seenHashes.add(digest)
675
+
676
+ const imgNum = items.length + 1
677
+ let src
678
+ let writtenPath
679
+ if (assetOutDir) {
680
+ mkdirSync(assetOutDir, { recursive: true })
681
+ const safeName = `imported-s${slideIndex + 1}-${imgNum}.${info.ext}`
682
+ writtenPath = resolve(assetOutDir, safeName)
683
+ writeFileSync(writtenPath, info.bytes)
684
+ src = writtenPath
685
+ } else {
686
+ src = `data:${info.mime};base64,${info.bytes.toString('base64')}`
687
+ }
688
+
689
+ const cleanAlt = String(alt || '').trim() || `Slide ${slideIndex + 1} image ${imgNum}`
690
+ items.push({
691
+ src,
692
+ alt: cleanAlt,
693
+ fit: 'contain',
694
+ bounds,
695
+ width: info.width,
696
+ height: info.height,
697
+ })
698
+ extractedAssets.push({
699
+ slide: slideIndex + 1,
700
+ ...(writtenPath ? { path: writtenPath } : {}),
701
+ mime: info.mime,
702
+ width: info.width,
703
+ height: info.height,
704
+ })
705
+ }
706
+
707
+ for (const shape of shapes) {
708
+ try {
709
+ if (!lib.hasShapeImage?.(shape)) continue
710
+ const rawBytes = lib.getShapeImageBytes?.(shape)
711
+ const info = inspectRasterImage(rawBytes)
712
+ if (!info) continue
713
+ const bounds = getBoundsNorm(lib, shape, slideW, slideH)
714
+ const alt = lib.getShapeDescription?.(shape) || lib.getShapeAltTitle?.(shape) || lib.getShapeName?.(shape)
715
+ pushImage(info, bounds, alt)
716
+ } catch { /* ignore unreadable shape image */ }
717
+ }
718
+
719
+ // Fallback: inspect slide relationship image parts via getMediaParts
720
+ if (items.length === 0) {
721
+ try {
722
+ const mediaParts = lib.getMediaParts?.(pres) ?? []
723
+ const mediaByName = new Map()
724
+ for (const mp of mediaParts) {
725
+ if (mp?.partName && mp?.bytes) mediaByName.set(safePartName(mp.partName), mp.bytes)
726
+ }
727
+ for (const rel of slideRels.values()) {
728
+ if (/\/image$/i.test(rel.type)) {
729
+ const targetPart = safePartName(resolveRelTarget(slidePartName, rel.target))
730
+ const rawBytes = mediaByName.get(targetPart) || (() => {
731
+ try { return lib.readPackagePart?.(pres, targetPart) } catch { return null }
732
+ })()
733
+ const info = inspectRasterImage(rawBytes)
734
+ if (info) pushImage(info, { x: 0.5, y: 0.2, w: 0.4, h: 0.5 }, '')
735
+ }
736
+ }
737
+ } catch { /* ignore */ }
738
+ }
739
+
740
+ return items
741
+ }
742
+
743
+ // ---------------------------------------------------------------------------
744
+ // Text Shapes & Archetype Inference
745
+ // ---------------------------------------------------------------------------
746
+
747
+ function extractTextShapes(lib, slide, slideW, slideH) {
748
+ const shapes = flattenShapes(lib, lib.getSlideShapes(slide))
749
+ const textShapes = []
750
+
751
+ for (const shape of shapes) {
752
+ try {
753
+ if (lib.isTableShape?.(shape) || lib.isChartShape?.(shape) || lib.hasShapeImage?.(shape)) continue
754
+ if (lib.isShapeHidden?.(shape)) continue
755
+ } catch { /* ignore */ }
756
+
757
+ let phType = ''
758
+ let shapeName = ''
759
+ try { phType = String(lib.getShapePlaceholderType?.(shape) || '').toLowerCase() } catch { phType = '' }
760
+ try { shapeName = String(lib.getShapeName?.(shape) || '').trim() } catch { shapeName = '' }
761
+ if (phType === 'sldnum' || phType === 'dt' || phType === 'ftr' || phType === 'hdr') continue
762
+ if (/^(?:slide\s*number|brand\s*footer)$/i.test(shapeName)) continue
763
+
764
+ const paragraphs = extractParagraphsFromShape(lib, shape)
765
+ if (paragraphs.length === 0) continue
766
+
767
+ const bounds = getBoundsNorm(lib, shape, slideW, slideH)
768
+ const plainJoined = paragraphs.map((p) => p.plain).join(' ').trim()
769
+ // Skip corner page-number badges (e.g. "2", "02 / 08", "Page 2")
770
+ if (bounds.y > 0.86 && plainJoined.length <= 16 && /^(?:\d{1,3}(?:\s*\/\s*\d{1,3})?|page\s*\d+|第\s*\d+\s*页)$/i.test(plainJoined)) continue
771
+
772
+ const maxSizePt = Math.max(...paragraphs.map((p) => p.maxSizePt || 0), 0)
773
+ textShapes.push({
774
+ phType,
775
+ bounds,
776
+ paragraphs,
777
+ plainJoined,
778
+ maxSizePt,
779
+ })
780
+ }
781
+
782
+ return textShapes
783
+ }
784
+
785
+ function shapeToCardItem(shapeObj) {
786
+ const paras = shapeObj.paragraphs
787
+ if (paras.length === 0) return null
788
+ if (paras.length === 1) {
789
+ const p = paras[0]
790
+ const boldColon = /^\*\*([^*]+)\*\*\s*[::—-]?\s*([\s\S]*)$/.exec(p.markdown)
791
+ if (boldColon) {
792
+ return { title: boldColon[1].trim(), text: boldColon[2].trim(), markdown: p.markdown }
793
+ }
794
+ const colonMatch = /^([^::]{1,20})[::]\s*([\s\S]+)$/.exec(p.plain)
795
+ if (colonMatch) {
796
+ return { title: colonMatch[1].trim(), text: colonMatch[2].trim(), markdown: `**${colonMatch[1].trim()}**:${colonMatch[2].trim()}` }
797
+ }
798
+ return { title: p.plain, text: '', markdown: p.markdown }
799
+ }
800
+ const heading = paras[0].plain
801
+ const rest = paras.slice(1).map((p) => p.markdown)
802
+ const restPlain = paras.slice(1).map((p) => p.plain).join(' ').trim()
803
+ const markdown = restPlain ? `**${heading}**:${restPlain}` : paras[0].markdown
804
+ return {
805
+ title: heading,
806
+ text: restPlain,
807
+ bullets: rest.length > 1 ? rest : undefined,
808
+ markdown,
809
+ }
810
+ }
811
+
812
+ function detectKpiItem(card) {
813
+ const combined = `${card.title} ${card.text || ''}`.trim()
814
+ const numMatch = /([-+]?(?:[$¥€£]\s*)?\d+(?:,\d{3})*(?:\.\d+)?\s*(?:[%%倍xX万亿千百kKmMbBtT]+|亿元|亿美元|万元|美元|元|家|个|人|次|天|小时|ms|pp|bps)?)/.exec(combined)
815
+ if (!numMatch) return null
816
+ const value = numMatch[1].replace(/\s+/g, '')
817
+ const label = combined.replace(numMatch[0], '').replace(/^[::—\-\s]+|[::—\-\s]+$/g, '').trim()
818
+ return {
819
+ title: label || card.title,
820
+ value,
821
+ ...(card.text && card.text !== value ? { text: card.text } : {}),
822
+ }
823
+ }
824
+
825
+ function classifyAndBuildSlide(raw, slideIndex, totalSlides) {
826
+ const { textShapes, tables, charts, images, notes } = raw
827
+ let titleShape = null
828
+ let kickerShape = null
829
+ let subtitleShape = null
830
+
831
+ // 1) Pick Title shape
832
+ titleShape = textShapes.find((s) => s.phType === 'ctrtitle' || s.phType === 'title') || null
833
+ if (!titleShape && textShapes.length > 0) {
834
+ const topCandidates = textShapes
835
+ .filter((s) => s.bounds.y <= 0.45)
836
+ .sort((a, b) => (b.maxSizePt - a.maxSizePt) || (a.bounds.y - b.bounds.y))
837
+ titleShape = topCandidates[0] || textShapes[0]
838
+ }
839
+
840
+ // 2) Pick Kicker / Eyebrow above title
841
+ if (titleShape) {
842
+ kickerShape = textShapes.find((s) =>
843
+ s !== titleShape &&
844
+ s.bounds.y + s.bounds.h <= titleShape.bounds.y + 0.04 &&
845
+ s.plainJoined.length <= 42 &&
846
+ (s.maxSizePt === 0 || titleShape.maxSizePt === 0 || s.maxSizePt < titleShape.maxSizePt)
847
+ ) || null
848
+ }
849
+
850
+ // 3) Pick Subtitle shape
851
+ subtitleShape = textShapes.find((s) => s !== titleShape && s !== kickerShape && s.phType === 'subtitle') || null
852
+ if (!subtitleShape && titleShape) {
853
+ const titleStr = titleShape.paragraphs.map((p) => p.plain).join(' ').trim()
854
+ const isFramingSlide = tables.length === 0 && charts.length === 0 && images.length === 0
855
+ const isCoverOrEnd = isFramingSlide && (
856
+ slideIndex === 0 ||
857
+ (slideIndex === totalSlides - 1 && totalSlides >= 3 && /谢谢|感谢|Q\s*&\s*A|Thank|Contact|Next\s*Step/i.test(titleStr))
858
+ )
859
+ if (isCoverOrEnd) {
860
+ subtitleShape = textShapes.find((s) =>
861
+ s !== titleShape &&
862
+ s !== kickerShape &&
863
+ s.bounds.y >= titleShape.bounds.y &&
864
+ !s.paragraphs.some((p) => p.hasBoldLead) &&
865
+ (slideIndex === 0 ? s.paragraphs.length <= 2 : s.paragraphs.length === 1)
866
+ ) || null
867
+ } else {
868
+ const remainingCount = textShapes.filter((s) => s !== titleShape && s !== kickerShape).length
869
+ subtitleShape = textShapes.find((s) =>
870
+ s !== titleShape &&
871
+ s !== kickerShape &&
872
+ s.paragraphs.length === 1 &&
873
+ s.bounds.w >= 0.45 &&
874
+ s.bounds.h <= 0.14 &&
875
+ s.bounds.y >= titleShape.bounds.y &&
876
+ s.bounds.y <= titleShape.bounds.y + Math.max(0.16, titleShape.bounds.h + 0.06) &&
877
+ s.plainJoined.length <= 90 &&
878
+ !s.paragraphs.some((p) => p.hasBoldLead) &&
879
+ (remainingCount > 1 || isFramingSlide)
880
+ ) || null
881
+ }
882
+ }
883
+
884
+ const usedShapes = new Set([titleShape, kickerShape, subtitleShape].filter(Boolean))
885
+ const bodyShapes = textShapes
886
+ .filter((s) => !usedShapes.has(s))
887
+ .sort((a, b) => (Math.abs(a.bounds.y - b.bounds.y) < 0.08 ? a.bounds.x - b.bounds.x : a.bounds.y - b.bounds.y))
888
+
889
+ const title = titleShape ? titleShape.paragraphs.map((p) => p.plain).join(' ').trim() : `Slide ${slideIndex + 1}`
890
+ const kicker = kickerShape ? kickerShape.plainJoined : undefined
891
+ const subtitle = subtitleShape ? subtitleShape.paragraphs.map((p) => p.plain).join(' ').trim() : undefined
892
+
893
+ const bullets = []
894
+ for (const s of bodyShapes) {
895
+ if (bodyShapes.length >= 2 && s.paragraphs.length >= 2 && s.paragraphs[0].plain.length <= 36) {
896
+ const card = shapeToCardItem(s)
897
+ if (card) bullets.push(card.markdown)
898
+ } else {
899
+ for (const p of s.paragraphs) bullets.push(p.markdown)
900
+ }
901
+ }
902
+
903
+ const base = {
904
+ title,
905
+ ...(kicker ? { kicker } : {}),
906
+ ...(subtitle ? { subtitle } : {}),
907
+ ...(notes ? { notes } : {}),
908
+ }
909
+
910
+ // Priority 1: Table
911
+ if (tables.length > 0) {
912
+ const takeaway = bullets.length > 0 ? bullets[0] : undefined
913
+ return {
914
+ ...base,
915
+ layout: 'table',
916
+ rows: tables[0],
917
+ ...(takeaway ? { takeaway } : {}),
918
+ }
919
+ }
920
+
921
+ // Priority 2: Chart / Chart-Split
922
+ if (charts.length > 0) {
923
+ const primaryChart = charts[0]
924
+ const hasSplitContent = bullets.length >= 1 || (primaryChart.bounds && primaryChart.bounds.w > 0 && primaryChart.bounds.w < 0.68 && bodyShapes.length > 0)
925
+ if (hasSplitContent && bullets.length > 0) {
926
+ return {
927
+ ...base,
928
+ layout: 'chart-split',
929
+ chart: primaryChart.chart,
930
+ bullets: bullets.slice(0, 5),
931
+ }
932
+ }
933
+ return {
934
+ ...base,
935
+ layout: 'chart',
936
+ chart: primaryChart.chart,
937
+ ...(bullets.length > 0 ? { takeaway: bullets[0] } : {}),
938
+ }
939
+ }
940
+
941
+ // Priority 3: Embedded Images (Gallery vs Image-Left / Image-Right)
942
+ if (images.length >= 2) {
943
+ return {
944
+ ...base,
945
+ layout: 'gallery',
946
+ images: images.slice(0, 4).map(({ src, alt, fit }) => ({ src, alt, fit })),
947
+ ...(bullets.length > 0 ? { bullets: bullets.slice(0, 4) } : {}),
948
+ }
949
+ }
950
+ if (images.length === 1) {
951
+ const img = images[0]
952
+ const center = (img.bounds?.x ?? 0.5) + (img.bounds?.w ?? 0.4) / 2
953
+ const layout = center < 0.5 ? 'image-left' : 'image-right'
954
+ return {
955
+ ...base,
956
+ layout,
957
+ image: { src: img.src, alt: img.alt, fit: img.fit },
958
+ ...(bullets.length > 0 ? { bullets: bullets.slice(0, 5) } : {}),
959
+ }
960
+ }
961
+
962
+ // Priority 4: Framing slides (Cover / Closing / Section)
963
+ if (slideIndex === 0 && (titleShape?.phType === 'ctrtitle' || (bodyShapes.length <= 1 && bullets.length <= 2))) {
964
+ return {
965
+ ...base,
966
+ layout: 'cover',
967
+ ...(bullets.length > 0 && !base.subtitle ? { subtitle: bullets.join(' · ') } : {}),
968
+ }
969
+ }
970
+
971
+ if (
972
+ slideIndex === totalSlides - 1 &&
973
+ totalSlides >= 3 &&
974
+ ((bodyShapes.length <= 1 && bullets.length <= 2) || /谢谢|感谢|Q\s*&\s*A|Thank|Contact|Next\s*Step/i.test(title))
975
+ ) {
976
+ return {
977
+ ...base,
978
+ layout: 'closing',
979
+ ...(bullets.length > 0 ? { bullets } : {}),
980
+ }
981
+ }
982
+
983
+ if (slideIndex > 0 && (titleShape?.phType === 'sechdr' || (bodyShapes.length === 0 && bullets.length === 0))) {
984
+ return {
985
+ ...base,
986
+ layout: 'section',
987
+ }
988
+ }
989
+
990
+ // Priority 5: Multi-shape structured cards -> KPI / Comparison / Cards
991
+ if (bodyShapes.length >= 2 && bodyShapes.length <= 6) {
992
+ const cards = bodyShapes.map(shapeToCardItem).filter(Boolean)
993
+ const kpiCandidates = cards.map(detectKpiItem)
994
+ const kpiCount = kpiCandidates.filter(Boolean).length
995
+
996
+ if (cards.length >= 2 && cards.length <= 4 && kpiCount >= Math.ceil(cards.length * 0.6)) {
997
+ return {
998
+ ...base,
999
+ layout: 'kpi',
1000
+ variant: 'grid',
1001
+ items: kpiCandidates.map((k, idx) => k || { title: cards[idx].title, value: cards[idx].text || cards[idx].title }),
1002
+ bullets,
1003
+ }
1004
+ }
1005
+
1006
+ if (cards.length === 2) {
1007
+ const sideBySide = Math.abs(bodyShapes[0].bounds.x - bodyShapes[1].bounds.x) > 0.18
1008
+ if (sideBySide) {
1009
+ return {
1010
+ ...base,
1011
+ layout: 'comparison',
1012
+ variant: /问题|痛点|风险|issue|risk/i.test(title) ? 'issue-action' : 'versus',
1013
+ items: cards.map((c) => ({
1014
+ title: c.title,
1015
+ ...(c.text ? { text: c.text } : {}),
1016
+ ...(c.bullets ? { bullets: c.bullets } : {}),
1017
+ })),
1018
+ bullets,
1019
+ }
1020
+ }
1021
+ }
1022
+
1023
+ if (cards.length >= 3 && cards.length <= 6) {
1024
+ return {
1025
+ ...base,
1026
+ layout: 'cards',
1027
+ variant: cards.length === 4 ? 'bento' : 'pillars',
1028
+ items: cards.map((c) => ({
1029
+ title: c.title,
1030
+ ...(c.text ? { text: c.text } : {}),
1031
+ ...(c.bullets ? { bullets: c.bullets } : {}),
1032
+ })),
1033
+ bullets,
1034
+ }
1035
+ }
1036
+ }
1037
+
1038
+ // Check bullet-level KPI when single text shape contains 2-4 numeric bullets
1039
+ if (bullets.length >= 2 && bullets.length <= 4) {
1040
+ const kpis = bullets.map((b) => {
1041
+ const plain = b.replace(/\*\*/g, '')
1042
+ const colon = /^([^::]{1,22})[::]\s*([\s\S]+)$/.exec(plain)
1043
+ const num = KPI_NUM_RE.exec(colon ? colon[2] : plain)
1044
+ if (!num || !/\d/.test(num[0])) return null
1045
+ return {
1046
+ title: colon ? colon[1].trim() : plain.replace(num[0], '').trim() || plain,
1047
+ value: num[0].trim(),
1048
+ ...(colon && colon[2].trim() !== num[0].trim() ? { text: colon[2].trim() } : {}),
1049
+ }
1050
+ })
1051
+ if (kpis.every(Boolean)) {
1052
+ return {
1053
+ ...base,
1054
+ layout: 'kpi',
1055
+ variant: 'grid',
1056
+ items: kpis,
1057
+ bullets,
1058
+ }
1059
+ }
1060
+ }
1061
+
1062
+ // Priority 6: Bullets fallback
1063
+ return {
1064
+ ...base,
1065
+ layout: 'bullets',
1066
+ ...(bullets.length > 0 ? { bullets } : {}),
1067
+ }
1068
+ }
1069
+
1070
+ /**
1071
+ * Extract full structured slide content from an external .pptx file or Buffer.
1072
+ * @param {object} options
1073
+ * @param {string} [options.pptxPath]
1074
+ * @param {Uint8Array} [options.bytes]
1075
+ * @param {string} [options.cwd='.']
1076
+ * @param {string} [options.assetOutDir]
1077
+ * @param {AbortSignal} [options.signal]
1078
+ */
1079
+ export async function extractPptxSlides(options = {}) {
1080
+ options.signal?.throwIfAborted()
1081
+ const cwd = resolve(String(options.cwd ?? '.'))
1082
+ const assetOutDir = options.assetOutDir ? resolve(cwd, String(options.assetOutDir)) : null
1083
+
1084
+ let bytes
1085
+ let resolvedPath
1086
+ if (options.bytes instanceof Uint8Array) {
1087
+ bytes = options.bytes
1088
+ if (typeof options.pptxPath === 'string' && options.pptxPath.trim()) {
1089
+ resolvedPath = resolve(cwd, options.pptxPath.trim())
1090
+ }
1091
+ } else {
1092
+ if (typeof options.pptxPath !== 'string' || !options.pptxPath.trim()) {
1093
+ fail('请提供要导入的 .pptx 文件路径 pptxPath', 'pptxPath is required')
1094
+ }
1095
+ resolvedPath = resolve(cwd, options.pptxPath.trim())
1096
+ let stat
1097
+ try {
1098
+ stat = lstatSync(resolvedPath)
1099
+ } catch {
1100
+ fail('找不到要导入的 PPTX 文件:' + resolvedPath, 'PPTX file not found: ' + resolvedPath)
1101
+ }
1102
+ if (!stat.isFile() || stat.isSymbolicLink()) {
1103
+ fail('导入的 PPTX 必须是普通文件(不支持目录或符号链接)', 'PPTX must be a regular file')
1104
+ }
1105
+ if (stat.size < 22 || stat.size > MAX_PPTX_BYTES) {
1106
+ fail('导入的 PPTX 文件大小需在 64 MiB 以内', 'PPTX must be up to 64 MiB')
1107
+ }
1108
+ bytes = readFileSync(resolvedPath)
1109
+ }
1110
+
1111
+ if (!bytes || bytes.byteLength < 22 || bytes.byteLength > MAX_PPTX_BYTES || bytes[0] !== 0x50 || bytes[1] !== 0x4b) {
1112
+ fail('文件不是有效的 .pptx 压缩包', 'Invalid .pptx archive')
1113
+ }
1114
+
1115
+ options.signal?.throwIfAborted()
1116
+ let lib
1117
+ try {
1118
+ lib = await import('@office-kit/pptx')
1119
+ } catch (error) {
1120
+ fail('导入解析 PPTX 需要 @office-kit/pptx@0.21.0。独立技能请在技能目录运行 npm install --ignore-scripts。' + error.message)
1121
+ }
1122
+ options.signal?.throwIfAborted()
1123
+
1124
+ let pres
1125
+ try {
1126
+ pres = await lib.loadPresentation(bytes)
1127
+ } catch (error) {
1128
+ fail('无法解析 PPTX 结构:' + error.message, 'Failed to parse PPTX: ' + error.message)
1129
+ }
1130
+ options.signal?.throwIfAborted()
1131
+
1132
+ const rawSlides = lib.getSlides(pres) ?? []
1133
+ if (rawSlides.length === 0) {
1134
+ fail('PPTX 文件中没有任何幻灯片页面', 'PPTX contains no slides')
1135
+ }
1136
+
1137
+ const rawSize = lib.getSlideSize(pres)
1138
+ const slideW = rawSize?.width ?? 12192000
1139
+ const slideH = rawSize?.height ?? 6858000
1140
+ const extractedAssets = []
1141
+ let chartCount = 0
1142
+ let tableCount = 0
1143
+ let notesCount = 0
1144
+
1145
+ const rawContents = rawSlides.map((slide, idx) => {
1146
+ options.signal?.throwIfAborted()
1147
+ const slidePartName = safePartName(lib.getSlidePartName?.(slide) || `/ppt/slides/slide${idx + 1}.xml`)
1148
+ const slideXml = (() => {
1149
+ try { return lib.getSlideXmlString?.(slide) || safeReadPartText(lib, pres, slidePartName) } catch { return safeReadPartText(lib, pres, slidePartName) }
1150
+ })()
1151
+ const slideRelsXml = safeReadPartText(lib, pres, relsPartFor(slidePartName))
1152
+ const slideRels = parseRelationships(slideRelsXml)
1153
+
1154
+ const textShapes = extractTextShapes(lib, slide, slideW, slideH)
1155
+ const tables = extractSlideTablesNormalized(lib, slide, slideXml)
1156
+ const charts = extractSlideChartsNormalized(lib, pres, slide, slidePartName, slideRels, slideW, slideH)
1157
+ const images = extractSlideImages(lib, pres, slide, idx, slidePartName, slideRels, slideW, slideH, assetOutDir, extractedAssets)
1158
+ const notes = extractSlideNotes(lib, pres, slide, slidePartName, slideRels, idx + 1)
1159
+
1160
+ chartCount += charts.length
1161
+ tableCount += tables.length
1162
+ if (notes) notesCount += 1
1163
+
1164
+ return { textShapes, tables, charts, images, notes }
1165
+ })
1166
+
1167
+ const slides = rawContents.map((raw, idx) => classifyAndBuildSlide(raw, idx, rawContents.length))
1168
+
1169
+ let coreTitle = ''
1170
+ try { coreTitle = String(lib.getCoreProperties?.(pres)?.title || '').trim() } catch { coreTitle = '' }
1171
+ const firstTitle = String(slides[0]?.title || '').trim()
1172
+ const title = (firstTitle && firstTitle !== 'Slide 1' ? firstTitle : coreTitle) || 'Imported Presentation'
1173
+
1174
+ return {
1175
+ ok: true,
1176
+ title,
1177
+ slideSize: {
1178
+ width: Number((slideW / 914400).toFixed(3)),
1179
+ height: Number((slideH / 914400).toFixed(3)),
1180
+ widthEmu: slideW,
1181
+ heightEmu: slideH,
1182
+ },
1183
+ slides,
1184
+ extractedAssets,
1185
+ stats: {
1186
+ slideCount: slides.length,
1187
+ chartCount,
1188
+ tableCount,
1189
+ imageCount: extractedAssets.length,
1190
+ notesCount,
1191
+ },
1192
+ }
1193
+ }