dsh-ppt 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/types.d.ts CHANGED
@@ -94,6 +94,43 @@ export interface PptProjectArgs {
94
94
  deckPath: string;
95
95
  expectedRevision?: number;
96
96
  }
97
+ export interface PptDataSource {
98
+ id: string;
99
+ name?: string;
100
+ format?: 'csv' | 'tsv' | 'text';
101
+ path?: string;
102
+ content?: string;
103
+ kind?: 'table' | 'text';
104
+ rows?: Array<Array<string | number>>;
105
+ text?: string;
106
+ }
107
+ export interface PptDataMetric {
108
+ id: string;
109
+ label?: string;
110
+ kind: 'source' | 'input' | 'formula';
111
+ source?: {
112
+ sourceId: string;
113
+ cell?: string;
114
+ line?: number;
115
+ numberIndex?: number;
116
+ };
117
+ value?: number;
118
+ min?: number;
119
+ max?: number;
120
+ step?: number;
121
+ note?: string;
122
+ formula?: string;
123
+ format?: {
124
+ style?: 'number' | 'percent';
125
+ digits?: number;
126
+ unit?: string;
127
+ };
128
+ }
129
+ export interface PptDataModel {
130
+ schemaVersion?: 1;
131
+ sources: PptDataSource[];
132
+ metrics: PptDataMetric[];
133
+ }
97
134
  export interface PptSlideSpec {
98
135
  id?: string;
99
136
  layout?: PptSlideLayout;
@@ -135,6 +172,8 @@ export interface PptCreateArgs {
135
172
  overwrite?: boolean;
136
173
  template?: PptTemplateId;
137
174
  brand?: PptBrand;
175
+ /** Optional explicit source facts, assumptions and safe arithmetic; bind slides with {{metricId}}. */
176
+ dataModel?: PptDataModel;
138
177
  }
139
178
  export interface PptThemeInfo {
140
179
  id: string;
@@ -186,6 +225,10 @@ export interface PptCreateResult {
186
225
  }
187
226
  /** Shared generator and optional renderer exposed to the plugin. */
188
227
  export interface DeckEngine {
228
+ previewDeckData(options: Record<string, unknown>): Record<string, any>;
229
+ updateDeckData(options: Record<string, unknown>): Promise<PptCreateResult>;
230
+ dataReport(manifest: any): string;
231
+ dataNotes(manifest: any, slide: any): string;
189
232
  buildDeckAsync?(options: Record<string, unknown>): Promise<PptCreateResult>;
190
233
  listTemplates(lang?: string): unknown[];
191
234
  editDeck(options: Record<string, unknown>): Promise<PptCreateResult>;
package/lib/workbench.js CHANGED
@@ -126,7 +126,7 @@ export class PptWorkbench {
126
126
  const render = this.renders.get(entry.id);
127
127
  const currentRender = render && render.revision === manifest.revision && digest(ordinaryFile(files.pptx)) === render.sourceSha256 ? render : undefined;
128
128
  return { ok: true, project: { ...entry, deckId: manifest.deckId, revision: manifest.revision, slides: manifest.slides,
129
- undoAvailable: manifest.history.length, quality: check, html,
129
+ undoAvailable: manifest.history.length, quality: check, html, dataModel: manifest.dataModel ?? null,
130
130
  assets: Object.fromEntries(Object.entries(manifest.assets ?? {}).map(([key, value]) => [key, { data: value.data, mime: value.mime }])),
131
131
  render: currentRender ? { pageCount: currentRender.pngPaths.length, missingFonts: currentRender.missingFonts ?? [] } : null } };
132
132
  }
@@ -170,7 +170,7 @@ export class PptWorkbench {
170
170
  return this.view(body.id);
171
171
  const { entry, engine, manifest, files } = await this.project(body.id);
172
172
  signal?.throwIfAborted();
173
- const context = { id: entry.id, manifest };
173
+ const context = { id: entry.id, manifest, ...(manifest.dataModel ? { dataNotes: Object.fromEntries(manifest.slides.map((s) => [s.id, engine.dataNotes(manifest, s)])) } : {}) };
174
174
  if (body.operation === 'coach-options')
175
175
  return { ok: true, ...await this.coaching.options(signal) };
176
176
  if (body.operation === 'coach-list')
@@ -201,6 +201,16 @@ export class PptWorkbench {
201
201
  return { ok: true, data: 'data:image/png;base64,' + bytes.toString('base64') };
202
202
  }
203
203
  this.revision(body, manifest);
204
+ if (body.operation === 'data-preview' || body.operation === 'data-apply') {
205
+ // Always force file reads off, including nested source updates and scenario packets.
206
+ const args = { deckPath: entry.path, expectedRevision: body.expectedRevision, parameters: body.parameters, sourceUpdates: body.sourceUpdates,
207
+ scenario: body.scenario, previewToken: body.previewToken, confirmed: body.confirmed, saveAs: body.saveAs !== false, allowFiles: false, signal };
208
+ if (body.operation === 'data-preview')
209
+ return engine.previewDeckData(args);
210
+ const result = await engine.updateDeckData(args);
211
+ await this.remember(result, args);
212
+ return { ...await this.view(digest(result.jsonPath)), originalId: entry.id };
213
+ }
204
214
  if (body.operation === 'coach-create')
205
215
  return { ok: true, run: await this.coaching.create(context, body, signal) };
206
216
  if (body.operation === 'coach-step') {
@@ -266,19 +276,23 @@ export class PptWorkbench {
266
276
  return denied;
267
277
  try {
268
278
  const params = new URL(request.url).searchParams, kind = params.get('kind');
269
- if (!['html', 'pptx', 'json', 'bundle', 'notes', 'coaching'].includes(String(kind)))
279
+ if (!['html', 'pptx', 'json', 'bundle', 'notes', 'coaching', 'data'].includes(String(kind)))
270
280
  return fail(400, '不支持此文件类型');
271
- const { entry, manifest, files } = await this.project(params.get('id'));
281
+ const { entry, manifest, files, engine } = await this.project(params.get('id'));
272
282
  if (String(manifest.revision) !== params.get('revision'))
273
283
  return fail(409, '项目已被修改,请重新打开后下载');
274
284
  request.signal.throwIfAborted();
275
285
  let name, bytes;
276
- if (kind === 'coaching') {
286
+ if (kind === 'data') {
287
+ bytes = strToU8(engine.dataReport(manifest));
288
+ name = basename(entry.path, '.json') + '-data-lineage.md';
289
+ }
290
+ else if (kind === 'coaching') {
277
291
  bytes = strToU8(this.coaching.markdown({ id: entry.id, manifest }, params.get('run')));
278
292
  name = basename(entry.path, '.json') + '-rehearsal.md';
279
293
  }
280
294
  else if (kind === 'notes') {
281
- bytes = strToU8(speakerNotes(manifest));
295
+ bytes = strToU8(speakerNotes({ ...manifest, slides: manifest.slides.map((slide) => ({ ...slide, notes: engine.dataNotes(manifest, slide) })) }));
282
296
  name = basename(entry.path, '.json') + '-speaker-notes.md';
283
297
  }
284
298
  else if (kind === 'bundle') {
@@ -309,10 +323,10 @@ export class PptWorkbench {
309
323
  request.signal.throwIfAborted();
310
324
  if ((await this.project(entry.id)).manifest.revision !== manifest.revision)
311
325
  return fail(409, '项目已被修改,请重新打开后下载');
312
- const type = kind === 'notes' || kind === 'coaching' ? 'text/markdown; charset=utf-8' : kind === 'bundle' ? 'application/zip' : kind === 'pptx' ? 'application/vnd.openxmlformats-officedocument.presentationml.presentation' : kind === 'html' ? 'text/html; charset=utf-8' : 'application/json; charset=utf-8';
326
+ const type = kind === 'notes' || kind === 'coaching' || kind === 'data' ? 'text/markdown; charset=utf-8' : kind === 'bundle' ? 'application/zip' : kind === 'pptx' ? 'application/vnd.openxmlformats-officedocument.presentationml.presentation' : kind === 'html' ? 'text/html; charset=utf-8' : 'application/json; charset=utf-8';
313
327
  return new Response(new Uint8Array(bytes), { headers: {
314
328
  'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff',
315
- 'content-disposition': `attachment; filename="presentation.${kind === 'bundle' ? 'zip' : kind === 'notes' || kind === 'coaching' ? 'md' : kind}"; filename*=UTF-8''${encodeURIComponent(name)}`,
329
+ 'content-disposition': `attachment; filename="presentation.${kind === 'bundle' ? 'zip' : kind === 'notes' || kind === 'coaching' || kind === 'data' ? 'md' : kind}"; filename*=UTF-8''${encodeURIComponent(name)}`,
316
330
  } });
317
331
  }
318
332
  catch (error) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-ppt",
3
- "version": "0.14.0",
4
- "description": "DSH 演示文稿插件:生成 HTML、可编辑 PPTX 和工程文件,支持轻量编辑、可选 AI 预审与模拟答辩。",
3
+ "version": "0.15.0",
4
+ "description": "DSH 演示文稿插件:生成 HTML、可编辑 PPTX 和工程文件,支持数字溯源、现场推演、编辑与可选 AI 演练。",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "types": "lib/index.d.ts",
@@ -79,7 +79,9 @@
79
79
  "packageManager": "pnpm@11.7.0",
80
80
  "dependencies": {
81
81
  "@office-kit/pptx": "0.21.0",
82
- "fflate": "0.8.3"
82
+ "csv-parse": "6.1.0",
83
+ "fflate": "0.8.3",
84
+ "jsep": "1.4.0"
83
85
  },
84
86
  "peerDependencies": {
85
87
  "@deepseek-ai/libreoffice-kit": "0.1.5"
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: dsh-ppt
3
3
  description: "Turn one sentence or a Markdown document into a complete, presentation-ready deck: a standalone HTML web slideshow plus an editable PPTX export, with 5 built-in visual themes (Swiss Pulse / Velvet Standard / Data Drift / Soft Signal / Maximalist Type), slide transitions + bullet entrance animations (motion, on by default), and bilingual Chinese/English support. Use when the user asks for a PPT, slides, deck, keynote, 演示文稿, 幻灯片, 汇报, 提案, 路演, 培训材料, or wants to turn a document into a presentation. 中文:把一句话或一篇文档变成完整演示文稿(HTML 网页放映 + PPTX 导出),内置 5 套视觉主题、页间转场与要点入场动画,中英双语。"
4
- compatibility: "Node ^22.19.0 or >=24.0.0. Images/charts use @office-kit/pptx@0.21.0. Optional PNG/PDF renderer: @deepseek-ai/libreoffice-kit@0.1.3. Cross-harness: copy the full directory and run npm install --ignore-scripts there."
4
+ compatibility: "Node ^22.19.0 or >=24.0.0. Images/charts use @office-kit/pptx@0.21.0; optional data models use jsep@1.4.0 and csv-parse@6.1.0. Optional PNG/PDF renderer: @deepseek-ai/libreoffice-kit@0.1.5. Cross-harness: copy the full directory and run npm install --ignore-scripts there."
5
5
  allowed-tools: "Bash, Read, Write, Edit"
6
6
  ---
7
7
 
@@ -16,6 +16,7 @@ allowed-tools: "Bash, Read, Write, Edit"
16
16
  ## 执行纪律(每次都要遵守)
17
17
 
18
18
  - 默认直接交付成品,不自动触发 AI 预审或答辩。用户可在设置页成品下载区主动开启两个可选模式;选择模型、范围与调用上限后再发送材料。AI 演练不等于事实核验,不编造实验、数据或引用;采纳建议另存副本,原件保留。
19
+ - 数字溯源和现场推演也按需启用。提供 `dataModel` 与结构化 `slides` 的 `{{metricId}}` 绑定;先读 `references/data.md`。源事实必须对应真实材料行或单元格;用户假设用 `kind:input` 标注,禁止虚构来源。修改数据先 `ppt_data(action:preview)`,展示指标与页面差异,得到确认后携带原预览凭证和修订号保存;默认新副本。离线 HTML 参数必须回存确认后才能交付对应静态 PPTX。
19
20
 
20
21
  - 修改工程先 `ppt_check`。外部编辑过的 HTML/PPTX、缺少成品校验记录的旧工程不可覆盖;告知用户 `saveAs:true` 只从 JSON 另存新副本,原件保留,Office 手工修改不会导入。不得绕过校验或自行篡改校验值。
21
22
 
@@ -49,6 +50,7 @@ allowed-tools: "Bash, Read, Write, Edit"
49
50
  | 选主题拿不准 | `references/themes.md` | 5 套主题色板 + 情绪决策树 |
50
51
  | 用表格/金句/备注/结构化 slides | `references/syntax.md` | Markdown 解析、进阶语法、slides JSON、motion 开关 |
51
52
  | 图片/图表/模板/品牌/编辑/渲染 | `references/advanced.md` | 参数、限制、草稿与成品、收据语义 |
53
+ | 数字溯源与现场推演 | `references/data.md` | 来源绑定、公式、更新预览与离线参数回存 |
52
54
  | 交付异常 | `references/troubleshooting.md` | 症状 → 处理对照表 |
53
55
 
54
56
  ## 质量门禁(交付前逐项确认)
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "dsh-ppt-skill",
3
- "version": "0.7.0",
3
+ "version": "0.15.0",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "description": "Standalone dsh-ppt skill dependencies for image/chart export",
7
- "dependencies": { "@office-kit/pptx": "0.21.0" },
8
- "peerDependencies": { "@deepseek-ai/libreoffice-kit": "0.1.3" },
7
+ "dependencies": { "@office-kit/pptx": "0.21.0", "csv-parse": "6.1.0", "jsep": "1.4.0" },
8
+ "peerDependencies": { "@deepseek-ai/libreoffice-kit": "0.1.5" },
9
9
  "peerDependenciesMeta": { "@deepseek-ai/libreoffice-kit": { "optional": true } },
10
10
  "engines": { "node": "^22.19.0 || >=24.0.0" }
11
11
  }
@@ -0,0 +1,67 @@
1
+ # 数据来源、公式和推演
2
+
3
+ 默认直接交付成品。需要解释数字或现场推演时,才在 `ppt_create` 提供 `dataModel` 和结构化 `slides`。不从相同数值猜来源,不虚构单元格、原文或文件。
4
+
5
+ ## 最小完整示例
6
+
7
+ ```json
8
+ {
9
+ "title": "经营情景",
10
+ "slides": [
11
+ { "layout": "cover", "title": "经营情景", "subtitle": "基期收入 {{base}}" },
12
+ { "layout": "bullets", "title": "增长 {{growth}}", "bullets": ["推演收入 {{revenue}}", "以上增长率是讨论假设"] },
13
+ { "layout": "chart", "title": "收入对比", "chart": { "kind": "column", "categories": ["基期", "情景"], "series": [{"name": "收入", "values": ["{{base}}", "{{revenue}}"]}], "unit": "万元" } }
14
+ ],
15
+ "dataModel": {
16
+ "schemaVersion": 1,
17
+ "sources": [{ "id": "sales", "name": "经营数据.csv", "format": "csv", "content": "项目,收入\n基期,1000" }],
18
+ "metrics": [
19
+ { "id": "base", "label": "基期收入", "kind": "source", "source": { "sourceId": "sales", "cell": "B2" }, "format": { "digits": 0, "unit": "万元" } },
20
+ { "id": "growth", "label": "增长率", "kind": "input", "value": 0.3, "min": 0, "max": 1, "step": 0.1, "note": "用于讨论的假设,不是业绩承诺", "format": { "style": "percent", "digits": 0 } },
21
+ { "id": "revenue", "label": "情景收入", "kind": "formula", "formula": "base * (1 + growth)", "format": { "digits": 0, "unit": "万元" } }
22
+ ]
23
+ }
24
+ }
25
+ ```
26
+
27
+ `source` 是材料中的事实,`input` 是可调假设,`formula` 是推导。百分比以比例计算:30% 是 `0.3`。数字格式为 `number`(默认)或 `percent`、0–6 位小数及可选 `unit`。显示舍入不改变计算输入。
28
+
29
+ 文本、要点、表格、备注和图表标签用 `{{metricId}}`;图表数值必须是完整占位符,计算仍使用原始数值。ID 使用字母开头的字母和数字,最多 48 字符。
30
+
31
+ ## 来源
32
+
33
+ - 表格:`format:csv/tsv` + `content`,或 `kind:table` + `rows`。地址 `A1–Z500`,首行表头也算第 1 行。引用格必须是单一数值,可含千位逗号或百分号。
34
+ - 材料:`format:text` + `content`,或 `kind:text` + `text`。引用 `{sourceId,line:1,numberIndex:0}`;行号从 1 开始,该行数值序号从 0 开始。日期、版本号也可能被识别为数字,必须检查截取位置。
35
+ - 工具调用可显式给 `path` 读取本地普通文件,按会话 cwd 解析;只读取一次并嵌入,不监视源文件。网页只能使用用户选取或粘贴的内容,不能让浏览器请求读取任意路径。
36
+ - UTF-8 CSV / TSV / TXT / Markdown;最多 8 个来源、合计 1 MiB,表格最多 500 行 / 26 列,各行等宽,每格最多 2000 字符。文本引用行最多 8000 字符。无 XLSX / PDF 数字自动提取。
37
+
38
+ ## 算术与范围
39
+
40
+ 最多 80 个指标和 12 个假设。假设必须提供有限的 `value/min/max/step`,处于范围和步长网格内,最多 100000 步。计算结果绝对值不超过 1e15。
41
+
42
+ 公式允许指标 ID、括号、`+ - * / % **`、一元正负,以及 `min/max/sum/abs/floor/ceil/round`。`round(value,digits)` 的 digits 为 0–6。最多 256 个 AST 节点、32 层表达式和 40 层指标依赖。循环、除零、未知指标、非有限结果会报错。没有 `eval`、属性访问、赋值、网络或文件执行。
43
+
44
+ ## 更新与确认
45
+
46
+ ```js
47
+ // 1. 先预览,不修改任何成品。
48
+ ppt_data({ action: 'preview', deckPath, expectedRevision: 0,
49
+ parameters: { growth: 0.5 } })
50
+ // 或替换已有来源:sourceUpdates:[{id:'sales',format:'csv',content:'项目,收入\n基期,1200'}]
51
+
52
+ // 2. 向用户展示 changes、affectedSlides 与字段前后差异,确认后再保存。
53
+ ppt_data({ action: 'apply', deckPath, expectedRevision: 0,
54
+ parameters: { growth: 0.5 }, confirmed: true, previewToken: preview.token })
55
+ ```
56
+
57
+ 应用默认 `saveAs:true`,原稿不变,新副本可撤销;`saveAs:false` 仍执行外部成品修改保护。预览凭证绑定完整工程状态、数据与修订,任一变化都应重新预览。`ppt_undo` 同步恢复来源、参数、公式和页面。
58
+
59
+ `ppt_edit` 会保留未修改字段的绑定。用普通文字替换绑定字段会解除该字段绑定;需要继续联动时保留占位符。确认后的静态 PPTX 备注和下载报告附上引用链。可选 AI 预审也会获得页面相关的公式与假设说明,不把来源关联当作事实核验。
60
+
61
+ 离线 HTML 的 `scenario.json` 包含 `schemaVersion/deckId/revision/fingerprint/parameters`。导回相同 DSH 工程后预览、确认,再下载匹配的静态 PPTX;也可作为 `ppt_data.scenario` 传入。不可将旧工程参数强套到新副本。
62
+
63
+ 跨 harness:在技能目录 `npm install --ignore-scripts` 后,使用 `node scripts/build-deck.mjs --title ... --slides @slides.json --data-model @model.json --out ...`。直接 JS 调用使用 `deck-advanced.mjs` 的 `buildDeckAsync`;同步 `deck-core.buildDeck` 不支持数据模型。
64
+
65
+ ## Dependencies
66
+
67
+ CSV parsing uses [csv-parse](https://csv.js.org/parse/api/sync/) 6.1.0 ([MIT](https://github.com/adaltas/node-csv/blob/master/LICENSE)). Formulas are parsed with [jsep](https://github.com/EricSmekens/jsep) 1.4.0 ([MIT](https://github.com/EricSmekens/jsep/blob/main/LICENSE)); the plugin supplies its own restricted evaluator. Dependencies retain their own license notices. Offline HTML embeds the plugin's validated arithmetic representation and runtime, not those parser implementations.
@@ -28,6 +28,7 @@ const HELP = `dsh-ppt —— 一句话 / 一篇文档 → HTML 放映 + PPTX 导
28
28
  --slides <json> 结构化 slides JSON(可选,与 --content 二选一)
29
29
  --template <id> weekly / defense / project / pitch;仅模板会生成草稿
30
30
  --brand <json|@path> 品牌颜色、字体、Logo、页脚
31
+ --data-model <json|@path> 可选数字来源、公式与推演假设;配合 --slides
31
32
  --edit <deck.json> 修改指定页,配合 --edits <json|@path>
32
33
  --undo <deck.json> 撤销最近一次修改
33
34
  --check <deck.json> 查看质量报告和页码 / ID
@@ -76,6 +77,7 @@ export function parseArgv(argv) {
76
77
  else if (key === '--slides') args.slides = readJson(nextValue())
77
78
  else if (key === '--template') args.template = nextValue()
78
79
  else if (key === '--brand') args.brand = readJson(nextValue())
80
+ else if (key === '--data-model') args.dataModel = readJson(nextValue())
79
81
  else if (key === '--edit') args.edit = nextValue()
80
82
  else if (key === '--edits') args.edits = readJson(nextValue())
81
83
  else if (key === '--undo') args.undo = nextValue()
@@ -163,6 +165,7 @@ export async function main(argv = process.argv.slice(2), io = {}) {
163
165
  overwrite: args.overwrite,
164
166
  template: args.template,
165
167
  brand: args.brand,
168
+ dataModel: args.dataModel,
166
169
  }
167
170
  const result = await buildDeckAsync(options)
168
171
  log('dsh-ppt 已生成 ' + result.slideCount + ' 页演示文稿:')
@@ -4,6 +4,8 @@ import { createHash, randomUUID } from 'node:crypto'
4
4
  import { inflateSync } from 'node:zlib'
5
5
  import { buildPptx, renderHtml, normalizeBuildOptions, normalizeSlides, resolveTheme, resolveLanguage, resolveDeckFileName, commitDeckArtifacts, DECK_VERSION, pptxEastAsianFont } from './deck-core.mjs'
6
6
  import { MEDIA_LAYOUTS, mediaBoxes, LOGO_BOX, FOOTER_BOX, chartColors, normalizeChart } from './deck-media.mjs'
7
+ import { normalizeDataModel, prepareDataSlides, validateDataSnapshot, previewDataChange, dataNotes, dataReport } from './deck-data.mjs'
8
+ export { dataNotes, dataReport } from './deck-data.mjs'
7
9
  export { buildDeck, buildThemePreview, listThemes, resolveTheme, resolveLanguage } from './deck-core.mjs'
8
10
 
9
11
  const MAX_IMAGE = 5 * 1024 * 1024, MAX_ASSETS = 32 * 1024 * 1024, MAX_DOCUMENT = 64 * 1024 * 1024
@@ -149,7 +151,7 @@ function validateRawSlides(slides) {
149
151
  })
150
152
  }
151
153
  function snapshot(manifest) {
152
- return clone(Object.fromEntries(['title', 'theme', 'language', 'motion', 'slides', 'brand', 'template'].filter(k => manifest[k] !== undefined).map(k => [k, manifest[k]])))
154
+ return clone(Object.fromEntries(['title', 'theme', 'language', 'motion', 'slides', 'brand', 'template', 'dataModel'].filter(k => manifest[k] !== undefined).map(k => [k, manifest[k]])))
153
155
  }
154
156
  function collectAssets(manifest) {
155
157
  const ids = new Set()
@@ -231,7 +233,7 @@ export function checkManifest(manifest) {
231
233
  }
232
234
 
233
235
  async function exportPptx(manifest, theme, language, signal) {
234
- const base = buildPptx(manifest, theme, language)
236
+ const base = buildPptx({ ...manifest, slides: manifest.slides.map(s => ({ ...s, notes: dataNotes(manifest,s) })) }, theme, language)
235
237
  if (!manifest.brand?.logoAssetId && !manifest.brand?.footer && !manifest.slides.some(s => s.image || s.chart)) return base
236
238
  abort(signal)
237
239
  let lib
@@ -327,6 +329,7 @@ function commit(paths, data) {
327
329
  function validateSnapshot(value, assets) {
328
330
  resolveTheme(value.theme); resolveLanguage(value.language)
329
331
  validateRawSlides(value.slides)
332
+ validateDataSnapshot(value, normalizeSlides)
330
333
  if (value.brand != null) {
331
334
  if (Object.hasOwn(value.brand, 'logo')) fail('工程品牌仅支持嵌入的 logoAssetId,不读取本地 logo 路径')
332
335
  for (const key of ['primaryColor', 'backgroundColor', 'textColor', 'fontFamily', 'name', 'footer']) {
@@ -357,12 +360,17 @@ export async function buildDeckAsync(options = {}) {
357
360
  if (options.template && !scenario) fail('未知 template,请使用 weekly / defense / project / pitch')
358
361
  const input = { ...options, theme: options.theme || scenario?.theme,
359
362
  ...(!options.content?.trim() && !options.slides?.length && scenario ? { slides: templateSlides(scenario, String(options.title ?? ''), options.lang) } : {}) }
360
- const normalized = normalizeBuildOptions(input), cwd = resolve(options.cwd || '.')
363
+ const cwd = resolve(options.cwd || '.')
364
+ const dataModel = options.dataModel ? normalizeDataModel(options.dataModel, { cwd, allowFiles:true }) : undefined
365
+ if (dataModel && (!Array.isArray(input.slides) || !input.slides.length)) fail('数据绑定需使用结构化 slides / Data binding requires structured slides')
366
+ const prepared = dataModel ? prepareDataSlides(input.slides, dataModel, normalizeSlides, resolveLanguage(input.lang).id) : undefined
367
+ const normalized = normalizeBuildOptions({ ...input, ...(prepared ? { slides:prepared } : {}) })
368
+ if(prepared) normalized.deck.slides = prepared
361
369
  const assets = {}
362
370
  const brand = normalizeBrand(options.brand, assets, cwd)
363
371
  const manifest = { version: DECK_VERSION, schemaVersion: 1, deckId: randomUUID(), revision: 0,
364
372
  title: normalized.title, theme: normalized.theme.id, language: normalized.language.id, motion: normalized.motion,
365
- ...(scenario ? { template: scenario.id } : {}), ...(brand ? { brand } : {}), assets, history: [],
373
+ ...(scenario ? { template: scenario.id } : {}), ...(brand ? { brand } : {}), ...(dataModel ? {dataModel} : {}), assets, history: [],
366
374
  slides: embedSlides(normalized.deck.slides, assets, cwd).map(s => ({ ...s, id: randomUUID() })) }
367
375
  const data = await generate(manifest, options.signal)
368
376
  mkdirSync(normalized.outputDir, { recursive: true })
@@ -448,14 +456,15 @@ export async function editDeck(options = {}) {
448
456
  if (!edit.patch || typeof edit.patch !== 'object' || Array.isArray(edit.patch)) fail('第 ' + (index + 1) + ' 页 patch 需为对象')
449
457
  for (const key of Object.keys(edit.patch)) if (!allowed.has(key)) fail('不支持修改页面字段:' + key)
450
458
  validateRawSlides([edit.patch])
451
- const changed = { ...next.slides[index], ...edit.patch }
459
+ const changed = { ...next.slides[index], ...next.slides[index].dataTemplate, ...edit.patch }
460
+ delete changed.dataTemplate
452
461
  for (const key of Object.keys(changed)) if (changed[key] === null) delete changed[key]
453
462
  if (edit.patch.chart) { if (!edit.patch.layout) changed.layout = 'chart'; if (changed.layout === 'chart') delete changed.image }
454
463
  if (edit.patch.image) { if (!edit.patch.layout && !['image', 'image-left', 'image-right'].includes(changed.layout)) changed.layout = 'image-right'; if (['image', 'image-left', 'image-right'].includes(changed.layout)) delete changed.chart }
455
464
  if (edit.patch.layout && !MEDIA_LAYOUTS.has(edit.patch.layout)) { delete changed.image; delete changed.chart }
456
465
  validateRawSlides([changed])
457
466
  let slides
458
- try { slides = normalizeSlides([changed], 120, next.language) } catch (error) { fail(`第 ${index + 1} 页修改失败:${error.message}`) }
467
+ try { slides = next.dataModel ? prepareDataSlides([changed], next.dataModel, normalizeSlides, next.language) : normalizeSlides([changed], 120, next.language) } catch (error) { fail(`第 ${index + 1} 页修改失败:${error.message}`) }
459
468
  if (slides.length !== 1) fail(`第 ${index + 1} 页修改会产生分页,请减少表格行数或另建演示文稿`)
460
469
  const embedded = embedSlides(slides, next.assets, resolve(options.cwd || '.'))[0]
461
470
  next.slides[index] = { ...embedded, id: current.slides[index].id }
@@ -487,7 +496,7 @@ export async function editDeck(options = {}) {
487
496
  if (options.append !== undefined) {
488
497
  if (!Array.isArray(options.append) || options.append.length < 1 || options.append.length > 5) fail('append 需为 1-5 页')
489
498
  validateRawSlides(options.append)
490
- const added = normalizeSlides(options.append, 120, next.language)
499
+ const added = next.dataModel ? prepareDataSlides(options.append, next.dataModel, normalizeSlides, next.language) : normalizeSlides(options.append, 120, next.language)
491
500
  if (next.slides.length + added.length > 120) fail('工程页数超过 120')
492
501
  next.slides.push(...embedSlides(added, next.assets, resolve(options.cwd || '.')).map(slide => ({ ...slide, id: randomUUID() })))
493
502
  }
@@ -504,11 +513,31 @@ export async function undoDeck(options = {}) {
504
513
  expected(state.manifest, options.expectedRevision)
505
514
  if (!state.manifest.history.length) fail('该工程没有可撤销的修改')
506
515
  const next = clone(state.manifest), prior = next.history.pop()
507
- for (const key of ['brand', 'template']) delete next[key]
516
+ for (const key of ['brand', 'template', 'dataModel']) delete next[key]
508
517
  Object.assign(next, prior)
509
518
  return saveRevision(state, next, options.signal)
510
519
  }
511
520
 
521
+ function dataChange(state, options) {
522
+ expected(state.manifest, options.expectedRevision)
523
+ const packet=options.scenario
524
+ if(packet && (packet.schemaVersion!==1||packet.deckId!==state.manifest.deckId||packet.revision!==state.manifest.revision||packet.fingerprint!==state.manifest.dataModel?.fingerprint))fail('推演参数来自其他工程或旧版本,请重新导出 / Scenario belongs to another project or revision')
525
+ return previewDataChange(state.manifest,{...options,...(packet?{parameters:packet.parameters}:{})},normalizeSlides)
526
+ }
527
+ export function previewDeckData(options = {}) {
528
+ abort(options.signal)
529
+ const state=readDocument(options.deckPath, options.cwd)
530
+ return { ok:true, deckId:state.manifest.deckId, revision:state.manifest.revision, ...dataChange(state,options).preview }
531
+ }
532
+ export async function updateDeckData(options = {}) {
533
+ abort(options.signal)
534
+ const state=readDocument(options.deckPath,options.cwd),change=dataChange(state,options)
535
+ if(options.confirmed!==true||options.expectedRevision===undefined||options.previewToken!==change.preview.token)fail('请先预览差异,再携带修订号与预览凭证确认 / Preview changes and confirm with the revision and preview token')
536
+ if(!change.preview.changed)return {...result(state.manifest,pathsFor(state.path)),changed:false}
537
+ const next={...clone(state.manifest),dataModel:change.model,slides:change.slides,history:[...state.manifest.history,snapshot(state.manifest)].slice(-MAX_HISTORY)}
538
+ return {...await saveRevision(state,next,options.signal,options.saveAs!==false,true),changed:true}
539
+ }
540
+
512
541
  export function checkDeck(options = {}) {
513
542
  abort(options.signal)
514
543
  const { manifest, path } = readDocument(options.deckPath, options.cwd)
@@ -19,6 +19,7 @@ import { resolve as resolvePath, join as joinPath } from 'node:path'
19
19
  import { deflateRawSync } from 'node:zlib'
20
20
  import { MEDIA_LAYOUTS, MEDIA_CSS, normalizeMediaSlide, renderMediaHtml, mediaBoxes } from './deck-media.mjs'
21
21
  import { renderDelivery } from './deck-delivery.mjs'
22
+ import { renderDataView } from './deck-data-view.mjs'
22
23
 
23
24
  /**
24
25
  * manifest 版本跟随发布包 package.json;把 skills/dsh-ppt 独立复制到其他
@@ -952,6 +953,7 @@ export function commitDeckArtifacts(artifacts) {
952
953
  }
953
954
 
954
955
  export function buildDeck(options = {}) {
956
+ if(options.dataModel!==undefined)throw new Error('dsh-ppt:数据绑定请使用 deck-advanced.mjs 的 buildDeckAsync / Data models require buildDeckAsync from deck-advanced.mjs')
955
957
  if (options.brand || options.template || options.slides?.some(slide => MEDIA_LAYOUTS.has(slide.layout) || slide.image || slide.chart)) {
956
958
  throw new Error('dsh-ppt:图片、图表、模板与品牌请使用异步 buildDeckAsync 或 ppt_create / CLI')
957
959
  }
@@ -1024,6 +1026,7 @@ body.motion .bullets li{
1024
1026
  const themeLabel = t.name[lang.id] ?? t.name.en
1025
1027
  const total = manifest.slides.length
1026
1028
  const delivery = renderDelivery(manifest, files, lang.id)
1029
+ const dataView = renderDataView(manifest, t)
1027
1030
 
1028
1031
  return `<!DOCTYPE html>
1029
1032
  <html lang="${lang.attr}">
@@ -1051,7 +1054,8 @@ body{
1051
1054
  -webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility;
1052
1055
  }
1053
1056
  #stage{position:fixed;inset:0}
1054
- .slide-frame{position:fixed;inset:0}
1057
+ .slide-frame{position:fixed;inset:0;pointer-events:none}
1058
+ .slide-frame.is-current,body.overview .slide-frame{pointer-events:auto}
1055
1059
  .slide{
1056
1060
  position:absolute;inset:0;display:none;flex-direction:column;justify-content:center;
1057
1061
  padding:clamp(34px,7vw,110px);overflow:hidden;
@@ -1236,11 +1240,13 @@ body.presenting #hud:hover{opacity:1;pointer-events:auto}
1236
1240
  #progress,#hud,#notes-panel,#help-panel,#toast{display:none !important}
1237
1241
  }
1238
1242
  ${delivery.css}
1243
+ ${dataView.css}
1239
1244
  </style>
1240
1245
  </head>
1241
1246
  <body class="${motion ? 'motion' : 'no-motion'}">
1242
1247
  <div id="progress" aria-hidden="true"></div>
1243
1248
  ${delivery.body}
1249
+ ${dataView.body}
1244
1250
  <div id="stage">
1245
1251
  ${slides}
1246
1252
  </div>
@@ -1650,10 +1656,12 @@ ${slides}
1650
1656
  window.addEventListener('beforeunload', closePresenter);
1651
1657
 
1652
1658
  ${delivery.script}
1659
+ window.addEventListener('dsh-data-change', () => { syncNotes(); if (presenterOpen()) sendInit(); updatePresenter(); });
1653
1660
  const start = Number.parseInt(location.hash?.replace('#slide-', ''), 10);
1654
1661
  go(Number.isInteger(start) ? start - 1 : 0);
1655
1662
  })();
1656
1663
  </script>
1664
+ ${dataView.script}
1657
1665
  </body>
1658
1666
  </html>`
1659
1667
  }
@@ -0,0 +1,76 @@
1
+ /** Shared Node/browser arithmetic. No eval, property access, assignments or I/O. */
2
+ export function createDataMath() {
3
+ const functions = {
4
+ min: values => Math.min(...values), max: values => Math.max(...values),
5
+ sum: values => values.reduce((a, b) => a + b, 0), abs: values => Math.abs(values[0]),
6
+ floor: values => Math.floor(values[0]), ceil: values => Math.ceil(values[0]),
7
+ round: values => {
8
+ const digits = values[1] ?? 0;
9
+ if (!Number.isInteger(digits) || digits < 0 || digits > 6) throw new Error('round digits: 0–6');
10
+ const scale = 10 ** digits; return Math.round((values[0] + Number.EPSILON) * scale) / scale;
11
+ },
12
+ };
13
+ function finite(value) {
14
+ if (!Number.isFinite(value) || Math.abs(value) > 1e15) throw new Error('Result must be finite and within ±1e15');
15
+ return Object.is(value, -0) ? 0 : value;
16
+ }
17
+ function inspect(ast, known) {
18
+ const dependencies = new Set(); let nodes = 0;
19
+ function visit(node, depth = 0) {
20
+ if (!node || ++nodes > 256 || depth > 32) throw new Error('Formula exceeds its complexity limit');
21
+ if (node.type === 'Literal' && typeof node.value === 'number') { finite(node.value); return; }
22
+ if (node.type === 'Identifier') {
23
+ if (!known.has(node.name)) throw new Error('Unknown metric: ' + node.name);
24
+ dependencies.add(node.name); return;
25
+ }
26
+ if (node.type === 'UnaryExpression' && ['+', '-'].includes(node.operator)) { visit(node.argument, depth + 1); return; }
27
+ if (node.type === 'BinaryExpression' && ['+', '-', '*', '/', '%', '**'].includes(node.operator)) {
28
+ visit(node.left, depth + 1); visit(node.right, depth + 1); return;
29
+ }
30
+ if (node.type === 'CallExpression' && node.callee?.type === 'Identifier' && Object.hasOwn(functions, node.callee.name.toLowerCase())) {
31
+ const name = node.callee.name.toLowerCase(), args = node.arguments;
32
+ if (!Array.isArray(args) || args.length < 1 || args.length > 16 || ['abs', 'floor', 'ceil'].includes(name) && args.length !== 1 || name === 'round' && args.length > 2) throw new Error('Invalid function arguments');
33
+ args.forEach(arg => visit(arg, depth + 1)); return;
34
+ }
35
+ throw new Error('Only arithmetic and min/max/sum/abs/floor/ceil/round are supported');
36
+ }
37
+ visit(ast); return [...dependencies];
38
+ }
39
+ function evaluate(ast, lookup) {
40
+ function visit(node) {
41
+ if (node.type === 'Literal') return finite(node.value);
42
+ if (node.type === 'Identifier') return finite(lookup(node.name));
43
+ if (node.type === 'UnaryExpression') return finite((node.operator === '-' ? -1 : 1) * visit(node.argument));
44
+ if (node.type === 'CallExpression') return finite(functions[node.callee.name.toLowerCase()](node.arguments.map(visit)));
45
+ const left = visit(node.left), right = visit(node.right);
46
+ if (['/', '%'].includes(node.operator) && right === 0) throw new Error('Division by zero');
47
+ return finite(({ '+': () => left + right, '-': () => left - right, '*': () => left * right,
48
+ '/': () => left / right, '%': () => left % right, '**': () => left ** right })[node.operator]());
49
+ }
50
+ return visit(ast);
51
+ }
52
+ function inputValue(metric, value) {
53
+ if (typeof value !== 'number') throw new Error('Input must be a number');
54
+ finite(value);
55
+ if (value < metric.min || value > metric.max || Math.abs((value - metric.min) / metric.step - Math.round((value - metric.min) / metric.step)) > 1e-6) throw new Error('Input outside range or step: ' + metric.id);
56
+ return value;
57
+ }
58
+ function solve(metrics, overrides = {}) {
59
+ const byId = new Map(metrics.map(m => [m.id, m])), values = new Map(), visiting = new Set();
60
+ for (const key of Object.keys(overrides)) if (byId.get(key)?.kind !== 'input') throw new Error('Only declared assumptions can change: ' + key);
61
+ function value(id) {
62
+ if (values.has(id)) return values.get(id);
63
+ const metric = byId.get(id); if (!metric) throw new Error('Unknown metric: ' + id);
64
+ if (visiting.has(id) || visiting.size >= 40) throw new Error('Cyclic or excessively deep formula: ' + id);
65
+ visiting.add(id);
66
+ const result = metric.kind === 'formula' ? evaluate(metric.ast, value) : metric.kind === 'input' ? inputValue(metric, Object.hasOwn(overrides, id) ? overrides[id] : metric.value) : finite(metric.value);
67
+ visiting.delete(id); values.set(id, result); return result;
68
+ }
69
+ metrics.forEach(m => value(m.id)); return Object.fromEntries(values);
70
+ }
71
+ function format(value, metric, language = 'zh') {
72
+ const style = metric.format?.style || 'number', digits = metric.format?.digits ?? 2;
73
+ return new Intl.NumberFormat(language === 'en' ? 'en-US' : 'zh-CN', { style:style==='number'?'decimal':style, minimumFractionDigits: digits, maximumFractionDigits: digits }).format(value) + (metric.format?.unit || '');
74
+ }
75
+ return { inspect, solve, format, finite, inputValue };
76
+ }