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.
@@ -20,8 +20,12 @@
20
20
  | `cards` | `pillars \| bento \| exec-summary \| numbered` | `kicker, title, subtitle, items`(2–6 项), `takeaway` | **主力去要点墙版式**:并列支柱卡、Apple/Linear 非对称 Bento 网格、麦肯锡顶部总论断+三支柱 `exec-summary` |
21
21
  | `comparison` | `versus \| before-after \| do-dont \| issue-action` | `kicker, title, items`(2 列或 2–4 对配对行), `takeaway` | A/B 方案对比、改造前后、✓ 推荐 vs ✗ 误区、政企「痛点 ──▶ 整改举措」原生箭头配对 |
22
22
  | `matrix` | `2x2 \| grid` | `kicker, title, items`(4 象限), `takeaway` | 咨询四象限矩阵(带原生 X/Y 坐标轴箭头与象限卡片) |
23
- | `process` | `steps \| timeline \| chevron \| layers \| funnel \| flywheel` | `kicker, title, items`(3–6 步), `takeaway` | 方法管线步骤、里程碑时间轴、**咨询价值链咬合五边形箭头(`chevron`,亦支持 `layout: "chevron" \| "value-chain"` 别名)**、技术分层、转化漏斗、4 节点增长飞轮 |
24
- | `callout` | `formula \| definition \| takeaways` | `kicker, title, subtitle, items / bullets, source` | 学术公式/算法定理框、核心概念定义卡、复盘行动清单 |
23
+ | `process` | `steps \| timeline \| chevron \| layers \| funnel \| flywheel` | `kicker, title, items`(3–6 步), `takeaway` | 方法管线步骤、里程碑时间轴、咬合五边形箭头(`chevron`)、技术分层、转化漏斗、4 节点增长飞轮 |
24
+ | **`value-chain`** | — | `kicker, title, items[]`(支持辅助活动 + 基本活动 + 右侧利润池 Wedge), `takeaway` | **正宗波特价值链(Porter Value Chain)**:顶部横向支撑活动(`Support Activities`)横梁 + 底部咬合基本活动(`Primary Activities`)五边形箭头 + 右侧利润池三角楔形 |
25
+ | **`marimekko`** | — | `kicker, title, rows[][]` 或 `items[]`(`value` 权重 + `bullets[]` 份额), `takeaway, source` | **麦肯锡不等宽市场地图(Marimekko)**:按各赛道规模比例切分列宽 + 100% 堆叠份额块 + 顶部规模标签 + 底部 0%–100% 标尺 |
26
+ | **`sankey`** | — | `kicker, title, items[]`(`tag -> title, value, status`)或 `bullets[]`(`"A -> B: 68.5亿"`), `takeaway, source` | **财报级桑基流向图(Sankey)**:多层拓扑守恒节点柱 + 原生三次贝塞尔丝带(`<a:custGeom>` / SVG),清晰呈现营收拆分与资金流向 |
27
+ | **`swot`** | — | `kicker, title, items[]`(4 项 S/W/O/T), `takeaway` | **咨询级 SWOT 十字矩阵**:四象限语义色卡(优势/短板/机遇/威胁)+ 中央「破局核心」战略锚点 + 底部 `SO/WO/ST/WT` 行动洞察 |
28
+ | `callout` | `formula \| definition \| takeaways` | `kicker, title, subtitle, formula?, items / bullets, source` | **原生公式(`<m:oMath>` + MathML,支持 `formula` 或 `$...$`/`$$...$$` LaTeX)**、算法定理框、核心概念定义卡与复盘清单 |
25
29
  | `table` | `tableStyle`: `consulting \| booktabs \| minimal \| banded \| harvey` | `kicker, title, rows`(首行表头), `takeaway, source` | 原生可编辑对比表(`booktabs` 为**无竖线学术三线表**;`harvey` 支持哈维球;数值列右对齐;> 8 行自动分页) |
26
30
  | **`gantt`** | `quarters \| months \| weeks \| swimlane` | `kicker, title, columns[], items[]`(`start, span, milestone?`), `takeaway` | **原生甘特排期图**:自动时间刻度栅格、泳道标签、比例条形块与菱形里程碑节点 |
27
31
  | **`architecture`** | `layered \| platform` | `kicker, title, items[]`(`bullets[]` 子模块,`status:'accent'` 侧边纵列) | **原生系统架构图**:多层技术栈横向模块 + 右侧跨层安全/治理纵栏 + 双向数据流箭头 |
@@ -17,7 +17,7 @@ import { resolve as resolvePath } from 'node:path'
17
17
  import { pathToFileURL } from 'node:url'
18
18
  import { listThemes, THEME_IDS, DEFAULT_THEME } from './deck-themes.mjs'
19
19
  import { CHROME_STYLE_IDS } from './deck-absorb.mjs'
20
- import { buildDeckAsync, listTemplates, editDeck, undoDeck, checkDeckAsync, renderDeck, absorbPptx } from './deck-advanced.mjs'
20
+ import { buildDeckAsync, listTemplates, editDeck, undoDeck, checkDeckAsync, renderDeck, absorbPptx, importPptxDeck } from './deck-advanced.mjs'
21
21
 
22
22
  const HELP = `dsh-ppt —— 一句话 / 一篇文档 → HTML 放映 + PPTX 导出
23
23
 
@@ -34,6 +34,12 @@ const HELP = `dsh-ppt —— 一句话 / 一篇文档 → HTML 放映 + PPTX 导
34
34
  --clone-structure 配合 --reference-pptx 使用,克隆参考文稿的逐页版式骨架与母版 chrome
35
35
  --chrome <style> 母版骨架风格:${CHROME_STYLE_IDS.join(' / ')}
36
36
  --absorb <deck.pptx> 只读检查并输出参考 .pptx 的净化主题、推荐内置主题/骨架与逐页分布 JSON
37
+ --import-pptx <path> 导入外部 .pptx 全量内容(标题/要点/表格/图表/图片/备注)并一键翻新为 dsh-ppt 工程
38
+ --sync-pptx <path> 将 Office 修改后的 .pptx 内容回导同步至已有工程(自动写入 .history/ 支持撤销)
39
+ --target-project <dir> 配合 --sync-pptx 指定目标工程目录(或传 --edit <deck.json>)
40
+ --preserve-theme 配合 --import-pptx 使用,保留原 .pptx 净化后的品牌配色与 Logo
41
+ --no-modernize 配合 --import-pptx/--sync-pptx 关闭自动版式升维
42
+ --handout 同时生成 <file>.handout.md 演讲者讲义与逐字稿文件
37
43
  --smart-layout 显式开启多版式叙事节奏自动升维(配合 --no-smart-layout 可关闭)
38
44
  --brand <json|@path> 品牌主辅颜色、标题/正文字体、封面反白、Logo、页脚、chromeStyle
39
45
  --data-model <json|@path> 可选数字来源、公式与推演假设;配合 --slides
@@ -58,9 +64,10 @@ const HELP = `dsh-ppt —— 一句话 / 一篇文档 → HTML 放映 + PPTX 导
58
64
  --help 显示本帮助
59
65
 
60
66
  输出:
61
- <file>.html 独立网页放映(无外链,可直接双击打开)
62
- <file>.pptx 可编辑 PPTX(16:9)
63
- <file>.json deck manifest
67
+ <file>.html 独立网页放映(无外链,支持按 P 启动双屏演讲者提词台、按 L 开启虚拟激光笔)
68
+ <file>.pptx 可编辑 PPTX(16:9)
69
+ <file>.json deck manifest
70
+ <file>.handout.md 演讲者讲义(传 --handout 时同步落盘,HTML 检查面板随时可下载)
64
71
  `
65
72
 
66
73
  export function parseArgv(argv) {
@@ -92,6 +99,12 @@ export function parseArgv(argv) {
92
99
  else if (key === '--persona') args.persona = nextValue()
93
100
  else if (key === '--reference-pptx') args.referencePptx = nextValue()
94
101
  else if (key === '--absorb') args.absorb = nextValue()
102
+ else if (key === '--import-pptx') args.importPptx = nextValue()
103
+ else if (key === '--sync-pptx') args.syncPptx = nextValue()
104
+ else if (key === '--target-project') args.targetProject = nextValue()
105
+ else if (key === '--preserve-theme') args.preserveTheme = true
106
+ else if (key === '--no-modernize') args.modernize = false
107
+ else if (key === '--handout') args.handout = true
95
108
  else if (key === '--brand') args.brand = readJson(nextValue())
96
109
  else if (key === '--data-model') args.dataModel = readJson(nextValue())
97
110
  else if (key === '--edit') args.edit = nextValue()
@@ -139,11 +152,35 @@ export async function main(argv = process.argv.slice(2), io = {}) {
139
152
  return 0
140
153
  }
141
154
  if (args.listTemplates) { log(JSON.stringify({ templates: listTemplates(args.lang) }, null, 2)); return 0 }
142
- if ([args.edit, args.undo, args.check, args.render, args.absorb].filter(Boolean).length > 1) {
143
- throw new Error('dsh-ppt CLI:--edit / --undo / --check / --render / --absorb 只能选择一项')
155
+ if ([args.edit && !args.syncPptx ? args.edit : null, args.undo, args.check, args.render, args.absorb, args.importPptx, args.syncPptx].filter(Boolean).length > 1) {
156
+ throw new Error('dsh-ppt CLI:--edit / --undo / --check / --render / --absorb / --import-pptx / --sync-pptx 只能选择一项')
144
157
  }
145
158
  if (args.renderReceipt !== undefined && !args.check) throw new Error('dsh-ppt CLI:--render-receipt 需配合 --check')
146
159
  if (!args.render && [args.format, args.width, args.timeoutMs].some(v => v !== undefined)) throw new Error('dsh-ppt CLI:--format / --width / --timeout 需配合 --render')
160
+ if (args.importPptx || args.syncPptx) {
161
+ const imported = await importPptxDeck({
162
+ pptxPath: args.importPptx || args.syncPptx,
163
+ outDir: resolvePath(args.out || '.'),
164
+ outputDir: resolvePath(args.out || '.'),
165
+ ...(args.syncPptx ? {
166
+ ...(args.edit ? { deckPath: args.edit } : {}),
167
+ ...(args.targetProject ? { targetProjectDir: args.targetProject } : (!args.edit ? { targetProjectDir: resolvePath(args.out || '.') } : {})),
168
+ } : {}),
169
+ ...(args.title ? { title: args.title } : {}),
170
+ ...(args.file ? { fileName: args.file } : {}),
171
+ ...(args.theme ? { theme: args.theme } : {}),
172
+ ...(args.persona ? { persona: args.persona } : {}),
173
+ ...(args.chrome ? { chromeStyle: args.chrome } : {}),
174
+ ...(args.lang ? { lang: args.lang } : {}),
175
+ ...(args.motion ? { motion: args.motion } : {}),
176
+ modernize: args.modernize !== false,
177
+ preserveSourceTheme: args.preserveTheme === true,
178
+ overwrite: args.overwrite === true,
179
+ handout: args.handout === true,
180
+ })
181
+ log(JSON.stringify(imported, null, 2))
182
+ return 0
183
+ }
147
184
  if (args.absorb) {
148
185
  const absorbed = await absorbPptx({ pptxPath: args.absorb })
149
186
  log(JSON.stringify(absorbed, null, 2))
@@ -205,12 +242,14 @@ export async function main(argv = process.argv.slice(2), io = {}) {
205
242
  template: args.template,
206
243
  brand: effectiveBrand,
207
244
  dataModel: args.dataModel,
245
+ ...(args.handout ? { handout: true } : {}),
208
246
  }
209
247
  const result = await buildDeckAsync(options)
210
248
  log('dsh-ppt 已生成 ' + result.slideCount + ' 页演示文稿:')
211
249
  log(' HTML 放映:' + result.htmlPath)
212
250
  log(' PPTX 导出:' + result.pptxPath)
213
251
  log(' Manifest :' + result.jsonPath)
252
+ if (result.handoutPath) log(' 讲义 Handout:' + result.handoutPath)
214
253
  if (result.deliveryStatus === 'draft') log(' 草稿:还有待填写内容,不可作为成品交付。')
215
254
  log(' 质量检查:' + result.quality.errorCount + ' 个错误 / ' + result.quality.warningCount + ' 个提醒;修订号 ' + result.revision)
216
255
  return 0
@@ -1,5 +1,5 @@
1
- import { mkdirSync, readFileSync, statSync, openSync, closeSync, rmSync } from 'node:fs'
2
- import { resolve, dirname, extname, basename } from 'node:path'
1
+ import { mkdirSync, readdirSync, readFileSync, statSync, openSync, closeSync, rmSync, writeFileSync } from 'node:fs'
2
+ import { resolve, dirname, extname, basename, join } from 'node:path'
3
3
  import { createHash, randomUUID } from 'node:crypto'
4
4
  import { inflateSync } from 'node:zlib'
5
5
  import { buildPptx, renderHtml, normalizeBuildOptions, normalizeSlides, resolveLanguage, resolveDeckFileName, commitDeckArtifacts, DECK_VERSION, buildDeck } from './deck-core.mjs'
@@ -9,12 +9,16 @@ import { MEDIA_LAYOUTS, mediaBoxes, LOGO_BOX, FOOTER_BOX, normalizeChart, buildO
9
9
  import { normalizeDataModel, prepareDataSlides, validateDataSnapshot, previewDataChange, dataNotes, dataReport } from './deck-data.mjs'
10
10
  import { normalizeVisual, applyVisualActions } from './deck-visual.mjs'
11
11
  import { absorbPptx, CHROME_STYLE_IDS } from './deck-absorb.mjs'
12
+ import { extractPptxSlides } from './deck-import.mjs'
13
+ import { renderHandoutMarkdown } from './deck-delivery.mjs'
12
14
  import { SCENARIO_TEMPLATES, findScenarioTemplate, buildScenarioSlides, listScenarioTemplates, inferThemeFromContent, promoteMarkdownSlides, auditSlideAesthetics } from './deck-director.mjs'
13
15
  export { readRenderReceipt } from './deck-render.mjs'
14
16
  export { dataNotes, dataReport } from './deck-data.mjs'
15
17
  export { buildDeck, resolveLanguage } from './deck-core.mjs'
16
18
  export { listThemes, listMasterPresets, resolveTheme } from './deck-themes.mjs'
17
19
  export { absorbPptx } from './deck-absorb.mjs'
20
+ export { extractPptxSlides } from './deck-import.mjs'
21
+ export { renderHandoutMarkdown } from './deck-delivery.mjs'
18
22
  export { inferThemeFromContent } from './deck-director.mjs'
19
23
 
20
24
  export function buildThemePreview(options = {}) {
@@ -65,7 +69,14 @@ function imageInfo(bytes, page) {
65
69
  offset += length
66
70
  }
67
71
  if (!bytes.subarray(-2).equals(Buffer.from([0xff, 0xd9]))) fail(`${page} JPEG 文件不完整`)
68
- } else fail(`${page} 图片仅支持 PNG / JPEG,请先转换格式`)
72
+ } else if (bytes.length >= 30 && bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP') {
73
+ mime = 'image/webp'
74
+ const chunk = bytes.toString('ascii', 12, 16)
75
+ if (chunk === 'VP8 ' && bytes.length >= 30) { width = bytes.readUInt16LE(26) & 0x3fff; height = bytes.readUInt16LE(28) & 0x3fff }
76
+ else if (chunk === 'VP8L' && bytes.length >= 25) { const bits = bytes.readUInt32LE(21); width = (bits & 0x3fff) + 1; height = ((bits >> 14) & 0x3fff) + 1 }
77
+ else if (chunk === 'VP8X' && bytes.length >= 30) { width = 1 + (bytes[24] | (bytes[25] << 8) | (bytes[26] << 16)); height = 1 + (bytes[27] | (bytes[28] << 8) | (bytes[29] << 16)) }
78
+ else fail(`${page} WebP 文件头无效`)
79
+ } else fail(`${page} 图片仅支持 PNG / JPEG / WebP,请先转换格式`)
69
80
  if (!width || !height || width > 16000 || height > 16000 || width * height > 32_000_000) fail(`${page} 图片尺寸无效或超过 3200 万像素`)
70
81
  return { width, height, mime }
71
82
  }
@@ -78,11 +89,11 @@ function addAsset(image, assets, cwd, page) {
78
89
  const source = String(image.src ?? '').trim()
79
90
  let bytes
80
91
  if (/^data:/i.test(source)) {
81
- const match = /^data:image\/(png|jpeg);base64,([A-Za-z0-9+/=\r\n]+)$/.exec(source)
92
+ const match = /^data:image\/(png|jpeg|webp);base64,([A-Za-z0-9+/=\r\n]+)$/.exec(source)
82
93
  if (!match || source.length > MAX_IMAGE * 1.4) fail(`${page} 图片 data URI 无效或超过 5 MiB`)
83
94
  bytes = Buffer.from(match[2], 'base64')
84
95
  } else {
85
- if (!source || /^[a-z][a-z0-9+.-]*:/i.test(source) && !/^[a-z]:[\\/]/i.test(source)) fail(`${page} 图片需本地路径或 PNG/JPEG data URI,不支持外链`)
96
+ if (!source || /^[a-z][a-z0-9+.-]*:/i.test(source) && !/^[a-z]:[\\/]/i.test(source)) fail(`${page} 图片需本地路径或 PNG/JPEG/WebP data URI,不支持外链`)
86
97
  const path = resolve(cwd, source)
87
98
  let size
88
99
  try { size = statSync(path).size } catch { fail(`${page} 图片不存在:${path}`) }
@@ -209,7 +220,7 @@ function collectAssets(manifest) {
209
220
  function embeddedAssetError(asset, id) {
210
221
  try {
211
222
  if (!asset || typeof asset.data !== 'string' || asset.data.length > MAX_IMAGE * 1.4) fail('嵌入图片数据缺失或过大')
212
- const match = /^data:image\/(png|jpeg);base64,([A-Za-z0-9+/=]+)$/.exec(asset.data)
223
+ const match = /^data:image\/(png|jpeg|webp);base64,([A-Za-z0-9+/=]+)$/.exec(asset.data)
213
224
  if (!match) fail('嵌入图片格式无效')
214
225
  const bytes = Buffer.from(match[2], 'base64')
215
226
  if (bytes.length > MAX_IMAGE || bytes.toString('base64') !== match[2]) fail('嵌入图片编码无效或过大')
@@ -415,13 +426,15 @@ function documentBytes(manifest) {
415
426
  if (Buffer.byteLength(text) > MAX_DOCUMENT) fail('JSON 工程含历史超过 64 MiB,请缩减图片或清理历史后另存工程')
416
427
  return text
417
428
  }
418
- function result(manifest, paths) {
429
+ function result(manifest, paths, writeHandout = false) {
430
+ const handoutPath = paths.json.slice(0, -5) + '.handout.md'
419
431
  return { ok: true, title: manifest.title, theme: manifest.theme, language: manifest.language,
420
432
  slideCount: manifest.slides.length, deckId: manifest.deckId, revision: manifest.revision,
421
433
  slides: manifest.slides.map((s, i) => ({ slide: i + 1, id: s.id, title: s.title, layout: s.layout })),
422
434
  undoAvailable: manifest.history.length, deliveryStatus: manifest.quality?.issues.some(i => i.code === 'template-unfilled') ? 'draft' : 'ready-for-review',
423
435
  quality: manifest.quality, verification: { static: 'checked', pptxRender: 'not-verified', visual: 'not-verified' }, outputDir: dirname(paths.json),
424
- files: paths, htmlPath: paths.html, pptxPath: paths.pptx, jsonPath: paths.json }
436
+ files: paths, htmlPath: paths.html, pptxPath: paths.pptx, jsonPath: paths.json,
437
+ ...(writeHandout ? { handoutPath } : {}) }
425
438
  }
426
439
  function pathsFor(jsonPath) {
427
440
  const base = jsonPath.slice(0, -5)
@@ -446,10 +459,19 @@ async function generate(manifest, signal) {
446
459
  abort(signal)
447
460
  return { json, pptx, manifest, theme, language }
448
461
  }
449
- function commit(paths, data) {
450
- const html = renderHtml(data.manifest, data.theme, data.language, paths)
462
+ function commit(paths, data, writeHandout = false) {
463
+ const handoutPath = paths.json.slice(0, -5) + '.handout.md'
464
+ const html = renderHtml(data.manifest, data.theme, data.language, { ...paths, ...(writeHandout ? { handout: handoutPath } : {}) })
451
465
  data.manifest.artifacts = { html: hash(html), pptx: hash(data.pptx) }
452
- commitDeckArtifacts([{ path: paths.json, data: documentBytes(data.manifest), encoding: 'utf8' }, { path: paths.html, data: html, encoding: 'utf8' }, { path: paths.pptx, data: data.pptx }])
466
+ const artifacts = [
467
+ { path: paths.json, data: documentBytes(data.manifest), encoding: 'utf8' },
468
+ { path: paths.html, data: html, encoding: 'utf8' },
469
+ { path: paths.pptx, data: data.pptx },
470
+ ]
471
+ if (writeHandout) {
472
+ artifacts.push({ path: handoutPath, data: renderHandoutMarkdown(data.manifest, data.language.id), encoding: 'utf8' })
473
+ }
474
+ commitDeckArtifacts(artifacts)
453
475
  }
454
476
 
455
477
  function validateEmbeddedImgObject(img, assets) {
@@ -636,8 +658,9 @@ export async function buildDeckAsync(options = {}) {
636
658
  // Resolve collisions after asynchronous rendering; an earlier call may have committed meanwhile.
637
659
  const file = resolveDeckFileName(normalized.outputDir, normalized.fileName, normalized.overwrite)
638
660
  const paths = pathsFor(resolve(normalized.outputDir, file + '.json'))
639
- withLock(paths.json, () => { abort(options.signal); commit(paths, data) })
640
- return result(manifest, paths)
661
+ const writeHandout = options.handout === true
662
+ withLock(paths.json, () => { abort(options.signal); commit(paths, data, writeHandout) })
663
+ return result(manifest, paths, writeHandout)
641
664
  }
642
665
 
643
666
  function readDocument(pathInput, cwd = '.') {
@@ -722,7 +745,7 @@ export async function editDeck(options = {}) {
722
745
  const used = new Set()
723
746
  const allowed = new Set([
724
747
  'layout', 'variant', 'chrome', 'title', 'subtitle', 'kicker', 'takeaway', 'source',
725
- 'text', 'activeIndex', 'tableStyle', 'bullets', 'items', 'cards', 'metrics',
748
+ 'text', 'formula', 'activeIndex', 'tableStyle', 'bullets', 'items', 'cards', 'metrics',
726
749
  'columns', 'steps', 'quadrants', 'rows', 'notes', 'image', 'images', 'chart', 'visual',
727
750
  ])
728
751
  for (const edit of options.edits ?? []) {
@@ -906,3 +929,224 @@ export async function renderDeck(options = {}) {
906
929
  return renderer.renderDeck({ ...options, pptxPath: resolve(cwd, options.pptxPath),
907
930
  ...(options.outputDir !== undefined ? { outputDir: resolve(cwd, options.outputDir) } : {}) })
908
931
  }
932
+
933
+ function detectSlidesLanguage(slides, title) {
934
+ const sample = [title, ...(slides || []).flatMap(s => [s.title, s.subtitle, ...(s.bullets || [])])].filter(Boolean).join(' ')
935
+ const cjkCount = (sample.match(/[\u3400-\u9fff]/g) || []).length
936
+ return cjkCount >= 4 ? 'zh' : 'en'
937
+ }
938
+
939
+ function findProjectJsonInDir(targetDir, cwd) {
940
+ const dir = resolve(cwd, String(targetDir))
941
+ if (extname(dir).toLowerCase() === '.json') return readDocument(dir, cwd)
942
+ let entries
943
+ try {
944
+ entries = readdirSync(dir).filter(f => f.endsWith('.json') && !f.startsWith('.'))
945
+ } catch {
946
+ fail('找不到目标工程目录:' + dir)
947
+ }
948
+ entries.sort((a, b) => (a === 'project.json' ? -1 : b === 'project.json' ? 1 : a.localeCompare(b)))
949
+ for (const name of entries) {
950
+ try { return readDocument(join(dir, name), cwd) } catch { /* skip non-manifest json */ }
951
+ }
952
+ fail('目标目录中未找到有效的 dsh-ppt .json 工程:' + dir)
953
+ }
954
+
955
+ function sanitizeImportedSlideForSync(extractedSlide, priorSlide) {
956
+ if (!priorSlide) return extractedSlide
957
+ const merged = {
958
+ ...extractedSlide,
959
+ id: priorSlide.id,
960
+ }
961
+ // Keep prior visual/chrome/tableStyle tuning when layout category matches
962
+ if (priorSlide.chrome && !merged.chrome) merged.chrome = priorSlide.chrome
963
+ if (priorSlide.visual && !merged.visual) merged.visual = clone(priorSlide.visual)
964
+ if (priorSlide.tableStyle && merged.layout === 'table' && !merged.tableStyle) merged.tableStyle = priorSlide.tableStyle
965
+ if (priorSlide.variant && merged.layout === priorSlide.layout && !merged.variant) merged.variant = priorSlide.variant
966
+ // Preserve dataTemplate provenance only if Office edits left bound content untouched
967
+ if (priorSlide.dataTemplate) {
968
+ const unchanged =
969
+ merged.title === priorSlide.title &&
970
+ JSON.stringify(merged.bullets ?? null) === JSON.stringify(priorSlide.bullets ?? null) &&
971
+ JSON.stringify(merged.rows ?? null) === JSON.stringify(priorSlide.rows ?? null) &&
972
+ JSON.stringify(merged.chart ?? null) === JSON.stringify(priorSlide.chart ?? null)
973
+ if (unchanged) merged.dataTemplate = clone(priorSlide.dataTemplate)
974
+ }
975
+ return merged
976
+ }
977
+
978
+ /**
979
+ * Full .pptx content importer, legacy deck refurbisher, and Office round-trip sync.
980
+ * Mode A (new import / legacy modernization): writes standalone HTML, refurbished PPTX, JSON project (and optional .handout.md).
981
+ * Mode B (sync onto targetProjectDir / deckPath): snapshots prior manifest into .history/ + manifest.history, updates slides, rebuilds deliverables.
982
+ */
983
+ export async function importPptxDeck(options = {}) {
984
+ abort(options.signal)
985
+ const cwd = resolve(String(options.cwd ?? '.'))
986
+ const hasTarget = Boolean(
987
+ (typeof options.deckPath === 'string' && options.deckPath.trim()) ||
988
+ (typeof options.targetProjectDir === 'string' && options.targetProjectDir.trim())
989
+ )
990
+ const modernize = options.modernize !== false
991
+ const preserveSourceTheme = options.preserveSourceTheme === true
992
+ const writeHandout = options.handout === true
993
+
994
+ if (hasTarget) {
995
+ // Mode B: Office Round-Trip Sync onto existing dsh-ppt project
996
+ const state = options.deckPath
997
+ ? readDocument(options.deckPath, cwd)
998
+ : findProjectJsonInDir(options.targetProjectDir, cwd)
999
+ const current = state.manifest
1000
+ const projectDir = dirname(state.path)
1001
+ const assetOutDir = options.assetOutDir ? resolve(cwd, String(options.assetOutDir)) : join(projectDir, 'assets')
1002
+
1003
+ const extracted = await extractPptxSlides({
1004
+ pptxPath: options.pptxPath,
1005
+ bytes: options.bytes,
1006
+ cwd,
1007
+ assetOutDir,
1008
+ signal: options.signal,
1009
+ })
1010
+
1011
+ // Write disk snapshot to .history/ AND push onto manifest.history so undoDeck / ppt_undo works 100%
1012
+ const historyDir = join(projectDir, '.history')
1013
+ mkdirSync(historyDir, { recursive: true })
1014
+ const histFile = join(historyDir, `${basename(state.path, '.json')}-rev${current.revision}-${Date.now()}.json`)
1015
+ writeFileSync(histFile, documentBytes(current), 'utf8')
1016
+
1017
+ const next = clone(current)
1018
+ next.history = [...next.history, snapshot(current)].slice(-MAX_HISTORY)
1019
+
1020
+ let syncSlides = extracted.slides
1021
+ if (modernize) {
1022
+ syncSlides = promoteMarkdownSlides(syncSlides, { explicitSmartLayout: false })
1023
+ }
1024
+ const mergedRaw = syncSlides.map((s, idx) => {
1025
+ const prior = current.slides[idx] || current.slides.find(p => p.title && p.title === s.title)
1026
+ return sanitizeImportedSlideForSync(s, prior)
1027
+ })
1028
+ validateRawSlides(mergedRaw)
1029
+ const normalizedSlides = normalizeSlides(mergedRaw, 120, next.language)
1030
+ const usedIds = new Set()
1031
+ const embedded = embedSlides(normalizedSlides, next.assets, cwd).map((s, idx) => {
1032
+ let id = mergedRaw[idx]?.id || randomUUID()
1033
+ if (usedIds.has(id)) id = randomUUID()
1034
+ usedIds.add(id)
1035
+ const dataTemplate = mergedRaw[idx]?.dataTemplate
1036
+ return { ...s, id, ...(dataTemplate ? { dataTemplate } : {}) }
1037
+ })
1038
+ next.slides = embedded
1039
+
1040
+ if (options.theme && options.theme !== 'auto') {
1041
+ next.theme = resolveTheme(options.theme).id
1042
+ }
1043
+ if (options.chromeStyle) {
1044
+ next.brand = normalizeBrand({ ...(next.brand || {}), chromeStyle: options.chromeStyle }, next.assets, cwd)
1045
+ }
1046
+ if (preserveSourceTheme) {
1047
+ const absorbed = await absorbPptx({ pptxPath: options.pptxPath, bytes: options.bytes, cwd, extractLogo: true, signal: options.signal })
1048
+ next.brand = normalizeBrand({ ...(next.brand || {}), ...absorbed.sanitizedBrand, ...(options.chromeStyle ? { chromeStyle: options.chromeStyle } : {}) }, next.assets, cwd)
1049
+ }
1050
+
1051
+ next.version = DECK_VERSION
1052
+ next.schemaVersion = 1
1053
+ next.revision = current.revision + 1
1054
+
1055
+ const data = await generate(next, options.signal)
1056
+ const paths = pathsFor(state.path)
1057
+ withLock(state.path, () => {
1058
+ abort(options.signal)
1059
+ if (hash(readFileSync(state.path)) !== state.fingerprint) fail('工程已被其他操作修改,请重新读取后重试')
1060
+ commit(paths, data, writeHandout)
1061
+ })
1062
+
1063
+ return {
1064
+ ...result(next, paths, writeHandout),
1065
+ importedFrom: options.pptxPath ? resolve(cwd, String(options.pptxPath)) : 'memory.pptx',
1066
+ syncedProject: true,
1067
+ historySnapshotPath: histFile,
1068
+ extractedStats: extracted.stats,
1069
+ }
1070
+ }
1071
+
1072
+ // Mode A: New Import & Legacy Deck Modernization
1073
+ const rawOut = options.outDir ?? options.outputDir ?? (options.pptxPath ? dirname(resolve(cwd, String(options.pptxPath))) : '.')
1074
+ const resolvedOutDir = resolve(cwd, String(rawOut))
1075
+ const assetOutDir = options.assetOutDir ? resolve(cwd, String(options.assetOutDir)) : join(resolvedOutDir, 'assets')
1076
+
1077
+ const extracted = await extractPptxSlides({
1078
+ pptxPath: options.pptxPath,
1079
+ bytes: options.bytes,
1080
+ cwd,
1081
+ assetOutDir,
1082
+ signal: options.signal,
1083
+ })
1084
+
1085
+ let absorbed = null
1086
+ if (preserveSourceTheme) {
1087
+ absorbed = await absorbPptx({
1088
+ pptxPath: options.pptxPath,
1089
+ bytes: options.bytes,
1090
+ cwd,
1091
+ extractLogo: true,
1092
+ signal: options.signal,
1093
+ })
1094
+ }
1095
+
1096
+ const rawSlides = modernize
1097
+ ? promoteMarkdownSlides(extracted.slides, { explicitSmartLayout: false })
1098
+ : extracted.slides
1099
+
1100
+ const baseFileName = typeof options.pptxPath === 'string' && options.pptxPath.trim() && !basename(options.pptxPath).startsWith('.import-')
1101
+ ? basename(options.pptxPath, extname(options.pptxPath))
1102
+ : ''
1103
+ const title = (typeof options.title === 'string' && options.title.trim()) ||
1104
+ (extracted.title && extracted.title !== 'Imported Presentation' ? extracted.title : '') ||
1105
+ baseFileName ||
1106
+ 'Imported Presentation'
1107
+
1108
+ const lang = options.lang || detectSlidesLanguage(rawSlides, title)
1109
+ const requestedTheme = typeof options.theme === 'string' && options.theme.trim() ? options.theme.trim() : 'auto'
1110
+ const effectiveTheme = requestedTheme === 'auto' && preserveSourceTheme && absorbed
1111
+ ? absorbed.recommendedTheme
1112
+ : requestedTheme
1113
+
1114
+ let brand = options.brand
1115
+ if (preserveSourceTheme && absorbed) {
1116
+ brand = {
1117
+ ...absorbed.sanitizedBrand,
1118
+ ...(absorbed.recommendedChrome ? { chromeStyle: absorbed.recommendedChrome } : {}),
1119
+ ...(options.chromeStyle ? { chromeStyle: options.chromeStyle } : {}),
1120
+ ...(options.brand && typeof options.brand === 'object' ? options.brand : {}),
1121
+ }
1122
+ } else if (options.chromeStyle) {
1123
+ brand = {
1124
+ ...(options.brand && typeof options.brand === 'object' ? options.brand : {}),
1125
+ chromeStyle: options.chromeStyle,
1126
+ }
1127
+ }
1128
+
1129
+ const built = await buildDeckAsync({
1130
+ title,
1131
+ slides: rawSlides,
1132
+ theme: effectiveTheme,
1133
+ persona: options.persona || 'auto',
1134
+ lang,
1135
+ motion: options.motion,
1136
+ brand,
1137
+ outputDir: resolvedOutDir,
1138
+ fileName: options.fileName || baseFileName || title,
1139
+ overwrite: options.overwrite === true,
1140
+ smartLayout: false,
1141
+ handout: writeHandout,
1142
+ cwd,
1143
+ signal: options.signal,
1144
+ })
1145
+
1146
+ return {
1147
+ ...built,
1148
+ importedFrom: options.pptxPath ? resolve(cwd, String(options.pptxPath)) : 'memory.pptx',
1149
+ syncedProject: false,
1150
+ extractedStats: extracted.stats,
1151
+ }
1152
+ }