diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b87ff66..042faef 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,7 +6,11 @@ on: jobs: test: - runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} defaults: run: working-directory: dsh-reader diff --git a/.gitignore b/.gitignore index d9d47e3..2da6e02 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,5 @@ eval/*.json dsh-reader/eval/*.json dsh-reader/plugin-market.json dsh-reader/demo/out/ + +示例-Word文档.docx diff --git a/README.md b/README.md index 7aaf191..d2c2536 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ **在 DSH 里读书、读论文、读文档。划词解释不离开原文,概念卡里继续追问、递归生长。** -- 📚 **读什么**:书、论文、技术报告、技术文档、规范——PDF / EPUB / Markdown 直接在会话主区域打开,不用先切到别的阅读器。 +- 📚 **读什么**:书、论文、技术报告、技术文档、规范——PDF / EPUB / Word(.docx)/ Markdown 直接在会话主区域打开,不用先切到别的阅读器。 - 🎯 **不打断心流**:划词即解释、翻译、笔记,卡片贴着原文浮出;不切窗口、不离开当前页,读完还停在原来那段。 - 🧠 **递归学习**:解释里遇到新概念,就在卡片里继续追问、生成子卡;父卡保留、概念链可见,一层层长成自己的体系。 @@ -130,7 +130,9 @@ 完成。在任意会话顶部切到「阅读」即可。工作区自带三份试读素材:`示例-分布式系统阅读.md`、`示例-分布式系统.epub`、`示例-分布式系统.pdf`,打开就能用。 -> `@latest` 现在就是 0.14.0;如果习惯插件市场索引、或想固定版本,也可以按下面的步骤安装和更新。 +Windows 10/11(x64)使用同一套桌面端与安装步骤;插件与阅读数据位于 `%USERPROFILE%\.dsh\profiles\desktop`,工作区数据仍在 `.dsh-reader/`。 + +> `@latest` 现在就是 0.15.0;如果习惯插件市场索引、或想固定版本,也可以按下面的步骤安装和更新。 ### 也可以从插件市场索引安装 @@ -162,7 +164,7 @@ dsh plugin --profile web add ./dsh-reader ## 边界 -扫描版 PDF(没有文本层)不能划词;固定版式 EPUB(FXL)不支持;段落对照翻译、概念图谱和移动端尚未包含。解释、导读和追问需要 dsh 已配置可用模型。论文中图片化的公式无法直接选中,需要走图片附件;PDF 文本层里的公式可以按文本选中。 +扫描版 PDF(没有文本层)不能划词;固定版式 EPUB(FXL)不支持;`.doc` 旧格式、`.rtf`、`.wps` 不支持;Word 按连续滚动阅读,不还原分页、页眉页脚与分栏。段落对照翻译、概念图谱和移动端尚未包含。解释、导读和追问需要 dsh 已配置可用模型。论文中图片化的公式无法直接选中,需要走图片附件;PDF 文本层里的公式可以按文本选中。 --- diff --git "a/docs/0.15-\351\252\214\346\224\266\350\256\260\345\275\225.md" "b/docs/0.15-\351\252\214\346\224\266\350\256\260\345\275\225.md" new file mode 100644 index 0000000..04a0237 --- /dev/null +++ "b/docs/0.15-\351\252\214\346\224\266\350\256\260\345\275\225.md" @@ -0,0 +1,82 @@ +# 砚读 0.15.0 验收记录 + +> 对应 PRD:`docs/PRD-v0.15-Word与Windows.md` +> 分支:`feat/0.15-word-windows` | PR:https://github.com/2019wakeup/dsh-reader/pull/7 +> 记录时间:2026-11-24 + +## 1. 自动化门禁 + +| 门禁 | 结果 | 证据 | +| --- | --- | --- | +| 单元 + DOM | **429/429** | `node --test test/*.test.mjs` | +| eval | **18/18** | `node eval/run.mjs` | +| Word pipeline | **9/9** | `node eval/docx.mjs` | +| 视觉回归 | **170/170 + 22 基线** | `node eval/visual.mjs` | +| 动效 | **16/16** | `node eval/motion.mjs` | +| 发布门禁 | **13/13** | `node scripts/release-check.mjs` | +| 发布包 | **PASS**,227 个文件 | `node scripts/publish-check.mjs` | +| CI | Windows / macOS / Ubuntu 全绿 | GitHub Actions `45396635211` | + +## 2. Word(D 系列) + +| ID | 状态 | 验证 | +| --- | --- | --- | +| D-01 书库与 MIME | ✅ | 视觉断言:书库出现 DOCX,打开后渲染第一章 | +| D-02 语义 HTML | ✅ | 浏览器断言正文/标题;真实 mammoth 夹具 | +| D-03 标题与目录 | ✅ | 视觉断言目录列出「第一章 / 第二章」;TOC 点线页码被清理 | +| D-04 划词解释 | ✅ | 视觉断言选区工具条出现,含解释/翻译/笔记/高亮 | +| D-05 翻译 | ✅ | 复用 HTML 块管线;表格单元格不参与对照,单测覆盖 | +| D-06 标注 | ✅ | 标注重锚单测;视觉覆盖标注编辑器(Markdown);docx 选区动作可点 | +| D-07 全文搜索 | ✅ | 视觉断言搜索命中「第二章 结论」并跳章 | +| D-08 表格 | ✅ | 视觉断言 `.rd-table-wrap` 存在 | +| D-09 图片 | ✅ | 适配层 Blob URL + revoke;EMF 占位 | +| D-10 超链接 | ✅ | sanitizer 单测:`javascript:` 降级 | +| D-11 位置与工具 | ✅ | 单测:docx position `page:0` + chapterTitle;context window 读当前章 | +| D-12 脚注/尾注 | ✅(降级) | mammoth 输出在文末;DETAIL 记录“按章分配留待后续” | +| D-13 导读/导图 | ✅ | docx 章节复用 `epubGuideStructure` | +| D-14 分页符 | ➖ | 不还原分页;文档明确说明 | +| D-15 代码块 | ✅ | `HTML Preformatted`/`代码` 样式映射为 `pre` | +| D-16 长文档 | ✅ | 按 h1 切章;条目数 5000、document.xml 20MB 护栏 | +| D-17 安全 | ✅ | 脚本/链接清洗;缺 `document.xml` 拒绝;zip 入口预算 | +| D-18 修订/批注/分栏等 | ➖ | 本版不做,DETAIL 记录 | + +## 3. Windows(W 系列) + +| ID | 状态 | 验证 | +| --- | --- | --- | +| W-01 发布包完整 | ✅ | `publish-check` 解包 import Host 入口通过 | +| W-02 路径归一化 | ✅ | POSIX 单测 + Windows CI | +| W-03 中文编码 | ✅ | UTF-8/UTF-16/GB18030 单测 | +| W-04 文件锁/错误 | ✅ | 404/403/423 单测;真机占用场景待走 | +| W-05 原子写重试 | ✅ | rename 重试 + copyFile 回退单测 | +| W-06 测试跨平台 | ✅ | Windows CI `pnpm test` 通过 | +| W-07 CI Windows 矩阵 | ✅ | 三平台矩阵全绿 | +| W-08 书库过滤 | ✅ | `~$*`/`desktop.ini`/`Thumbs.db` 单测 | +| W-09 快捷键 | ✅ | `Ctrl+Y` 单测;帮助文案按平台 | +| W-10 Ctrl+滚轮 | ✅ | 代码路径;真机手势待走 | +| W-11 字体/PDF 文本层 | ✅ | 字体栈与 DPR 上限;真机视觉待走 | +| W-12 滚动条 | ✅ | `scrollbar-gutter` + 布局探针 | +| W-13 路径安全 | ✅(部分) | realpath fail-closed、`isInside` 包含判断;长路径显式报错未做 | +| W-14 排序 | ✅ | `Intl.Collator` 数字感知,`第2章` 在 `第10章` 前 | +| W-15 拖拽/IME | ✅(部分) | IME 组合输入不触发 Esc;复制失败有提示;文件拖入未做 | +| W-16 安装文档 | ✅ | README / DETAIL 已加 Windows 与 Word 说明 | + +## 4. 待真机手工项 + +以下无法在当前 macOS 环境完成,发布前由维护者在 Windows 10/11 x64 上走一遍: + +- [ ] 插件安装 → 启用 → 重启 → 打开阅读视图; +- [ ] 中文路径 / 子目录 Markdown 相对图片; +- [ ] GBK `.txt`、UTF-16LE `.md`; +- [ ] Word 占用 `.docx` 时打开与保存标注(423 提示、不丢数据); +- [ ] 125% / 150% DPI、经典滚动条、短文档不横跳; +- [ ] `Ctrl+Y`、`Ctrl+滚轮`、帮助面板键位; +- [ ] 输入法组合输入与 `Esc`; +- [ ] 导出 JSON、标注 Markdown、恢复备份。 + +## 5. 发布步骤 + +1. 合并 PR #7 到 `main`; +2. 打 tag `v0.15.0` 并推送,Release workflow 执行 `npm publish`; +3. 发布后确认 `npm view @2019wakeup/dsh-reader version` 为 `0.15.0`,市场索引已指向 npm 源; +4. 完成第 4 节 Windows 真机清单后,把本文件对应项勾上。 diff --git "a/docs/PRD-v0.15-Word\344\270\216Windows.md" "b/docs/PRD-v0.15-Word\344\270\216Windows.md" new file mode 100644 index 0000000..a727a26 --- /dev/null +++ "b/docs/PRD-v0.15-Word\344\270\216Windows.md" @@ -0,0 +1,978 @@ +# PRD v0.15.0:砚读 · Word 与 Windows + +> 版本 0.15.0 | 2026-11-24 | 作者:lead | 状态:待评审 +> 基线:npm `@2019wakeup/dsh-reader@0.14.0` +> 前序:`docs/PRD-v1.0-阅读工作台.md`、`docs/PRD-v0.14-阅读动效.md` +> 调研依据:本工作区 0.14.0 源码(行号以 2026-11-24 工作区为准)、`npm pack` 实测、DSH 桌面端 0.2.2-rc.5 安装文档 + +--- + +## 0. 一页结论 + +**0.15.0 只做两件事:让砚读能读 Word,让 Windows 用户能正常用。** + +这不是"再加一个格式、再加一个平台"。现有阅读管线的核心契约只有一条:**非 PDF 文档 = 扁平语义 HTML + h1–h3 标题 + 块级文本**,划词、翻译、标注、概念、目录、搜索、对话上下文全部挂在这条契约上(`src/client/app.js:3165-3191`、`src/client/styles.js:30-53`)。Word 支持要做的,是造一个满足这条契约的解析器;Windows 支持要做的,是让这条契约在 `win32` 的路径、编码、字体和脚本下不破。 + +**Word 的产品判断:不还原 Word 的分页版式。** + +`.docx` 被解析成语义 HTML,进入现有连续阅读管线。用户得到的是和 EPUB/Markdown 一致的阅读体验:连续滚动、划词解释、段落翻译、四色高亮、目录跳转、概念沉淀、全文搜索、"问 AI"带章节上下文。代价是看不到 Word 的精确分页、页眉页脚、分栏和文本框;收益是零学习成本,且阅读位置、标注、概念卡不需要为 Word 单独造一套模型。 + +**Windows 的产品判断:不做一个 Windows 专用版,也不新增安装器。** + +Windows 桌面端已经是 DSH 的官方发行平台之一(官方下载页提供 Windows x64 安装包,文件名以官网为准;数据目录 `%USERPROFILE%\.dsh`、`%APPDATA%\@deepseek-ai\dsh-desktop`,见 DSH 安装文档 `desktop-uninstall-cleanup.zh.md`)。插件代码本身是纯 JS,理论跨平台;但 0.14.0 的 401 条测试、163 项视觉检查、发布脚本和帮助文案都只按 macOS 写。0.15 要把这些假设逐条拆掉,用 GitHub Actions `windows-latest` + 真机清单证明"同一份代码在 Windows 上能装、能开、能划词、能导出"。 + +**三件事:** + +1. **Word 能读**:`.docx` 打开、标题目录、划词解释、段落翻译、高亮笔记、概念卡、全文搜索、导出、`reader_context`/`reader_read` 全通。 +2. **Windows 能用**:路径分隔符、GBK/UTF-16 中文、文件占用、`Ctrl+Y`、字体与滚动条、安装与发布链路。 +3. **两条线都不破坏现有体验**:macOS 的 401 条测试、163 项视觉检查、12 项发布门禁保持全绿。 + +**不做什么:** + +- ❌ 不支持 `.doc`(Word 97–2003 二进制)、`.rtf`、`.wps`; +- ❌ 不做 Word 版式还原:不还原分页、页眉页脚、分栏、文本框、页码; +- ❌ 不做 Word 编辑、批注写入、修订接受/拒绝; +- ❌ 不做 Linux 官方支持(代码不主动破坏,但不验收); +- ❌ 不承诺 Windows ARM64(x64 模拟可跑,不作为验收目标); +- ❌ 不做跨平台像素基线(字体不同,像素必然不同)。 + +**前后对比:** + +| 能力 | 0.14.0 实际 | 0.15.0 目标 | +| --- | --- | --- | +| 书库格式 | PDF / EPUB / `.md` / `.markdown` / `.txt` | 再加 `.docx` | +| Word 打开 | 不在可读集合内,书库不显示 | 打开后 1.5s 内出第一章,目录可直接跳 | +| Word 划词 | 无 | 工具条、解释、翻译、高亮、笔记与 Markdown 一致 | +| Word 位置 | 无 | 章节 + 字符百分比;无页码,不伪造页码 | +| Windows 安装 | npm 包缺 Host 依赖,安装后阅读视图不出现(0.14 实测缺陷) | 安装即可用;`npm pack` 文件完整 | +| Windows 中文 | GBK/UTF-16 文本全部乱码 | BOM + GB18030 回退,正确显示 | +| Windows 路径 | `sub\book.md` 的 basename/图片解析错 | 统一 POSIX 相对路径,子目录图片正常 | +| Windows 文件占用 | 一律 HTTP 500,提示不可读 | 423 + "文件被其他程序占用",不丢标注 | +| Windows 快捷键 | 帮助写死 `⌘Z`;`Ctrl+Y` 无反应 | 按平台显示 `Ctrl` / `⌘`;支持 `Ctrl+Y` | +| Windows 测试 | `npm test`、`release:check` 在 Windows 必挂 | 双平台 CI 全绿 | + +**版本号**:0.14.0 → 0.15.0(minor)。新增格式与平台支持,无数据模型破坏;store 仍是 v2,docx 复用 `docs` / `annotations` / `concepts` 的现有结构。 + +> 版本线说明:产品文档里的「1.0」是能力里程碑;npm 包继续沿 0.1x 版本线发布。本 PRD 沿用 npm 版本线。 + +--- + +## 1. 为什么是现在 + +### 1.1 现状:三种格式,一个平台 + +0.14.0 的阅读能力覆盖"书"和"网页文档":PDF、EPUB、Markdown、纯文本。但用户真实工作里最多的文档是 `.docx`:课程作业、开题报告、评审意见、技术方案、合同、会议纪要。这些文档的宿命通常是: + +1. 导出成 PDF 再读——目录、页边距、页码都在,但文本层和标注体验取决于导出质量; +2. 复制成 Markdown 再读——格式全丢,图片要手动搬; +3. 在 Word 里读,遇到问题切到浏览器问——上下文断掉,这正是砚读要解决的问题。 + +Word 是"文档"这个词最主流的所指,阅读器绕开它,等于把最需要"边读边问"的材料挡在门外。 + +平台侧的问题同样具体。下面每一条都来自 0.14.0 源码审计,不是猜测: + +| 面 | 0.14.0 实际 | 代码位置 | Windows 后果 | +| --- | --- | --- | --- | +| 发布包 | `files` 不含 `src/`,但 Host 顶层 `import './src/client/translate.js'`;`npm pack` 实测 223 个文件无此文件 | `package.json:12-21`、`index.js:9` | npm 安装后 `ERR_MODULE_NOT_FOUND`,阅读视图完全不出现 | +| 书库路径 | `path.relative()` 原样返回;客户端 `basename`/`dirname` 只按 `/` 切 | `index.js:129`、`src/client/util.js:14-22` | 子目录文档显示成整串 `sub\book.md`;Markdown 相对图片解析到工作区根,404 | +| 文本编码 | 固定 `TextDecoder('utf-8')` | `src/client/app.js:33-35` | 记事本/老编辑器保存的 GBK `.txt`、UTF-16 `.md` 全部乱码 | +| 文件占用 | `fs.stat` 异常一律 404;`fs.readFile` 异常冒成 500 且带绝对路径 | `index.js:140-143`、`index.js:1521-1528` | 读文件报 `HTTP 500`;store 写入遇锁时标注保存失败 | +| store 写入 | 写 tmp 后 `fs.rename`,无重试 | `lib/store.js:254-256` | OneDrive/杀软短暂占用时 rename `EPERM`,整次标注保存 reject | +| 快捷键 | `Ctrl+Y` 不识别;帮助面板写死 `⌘Z / ⌘⇧Z` | `src/client/shortcuts.js:10-12`、`src/client/app.js:4821` | Windows 用户的肌肉记忆失效,帮助文案不可信 | +| 字体/滚动条 | `system-ui` 先命中 Segoe UI;`.rd-main` 未设 `scrollbar-gutter` | `src/client/styles.js:3`、`src/client/styles.js:29` | 中文回退雅黑,字宽与行高和 mac 不同;短文档滚动条出现/消失导致正文横跳 | +| 测试/脚本 | `paths.test.mjs` 断言 POSIX 路径;`host.test.mjs` 用 `/etc/hosts` 建 symlink;Chrome 路径写死;`make-demo` 用 `/usr/bin/zip`;`publish-check` 直接 `execFileSync('npm')` | `test/paths.test.mjs:5-38`、`test/host.test.mjs:237`、`eval/visual.mjs:21`、`scripts/make-demo-epub.mjs:110-111`、`scripts/publish-check.mjs:25-31` | Windows 上 `npm test`、`release:check`、`publish:check` 全红,等于没有回归网 | + +**其中发布包缺文件是 0.14 已有的真实缺陷,不只影响 Windows。** 任何从 npm 安装 0.14.0 的用户都会在插件加载时失败;桌面端插件页只会显示"加载失败"。0.15 必须把它和 Windows 支持同批修掉,否则"Windows 能装"从第一步就是假的。 + +### 1.2 用户信号 + +- **格式信号**:README 的"用在这些场景"里已经写了"论文与研究报告""技术文档与规范""课程材料",这些场景的实际载体大量是 `.docx`。用户不会为了一个阅读器改变自己的文件格式。 +- **平台信号**:DSH 桌面端提供 Windows x64 安装包,Windows 用户不需要预装 Node.js。插件 README 的安装说明却只写"Finder""⌘",Windows 用户按图索骥会在第一步困惑。 +- **安装信号**:0.14 的 npm 包缺文件,说明"发布产物完整性"没有被任何自动化检查覆盖;`publish-check` 只检查版本号、README、license、market 一致性,没有"解包后 Host 能 import"这一项。这正是 0.15 要补的门禁。 + +### 1.3 两个边界其实是同一个问题 + +把 Word 和 Windows 放在同一版,不是强行打包,而是它们共用同一套验证: + +- Word 支持要证明"新格式满足 HTML 契约"; +- Windows 支持要证明"同一契约在 `win32` 下不破"; +- 两者都要跑 `node --test`、都要在书库/渲染/搜索/导出链路上回归; +- 两者都触碰 `index.js` 的文件读取与 `app.js` 的文档打开分支,合批改一次,比拆两个版本少一轮回归。 + +### 1.4 为什么现在做 + +- 0.14.0 刚发布,工作区干净,401 条测试、163 项视觉检查、16 项动效检查是可靠的回归网。 +- docx 有成熟解析库(mammoth),接入成本低于自研;PDF.js 已经建立了"第三方代码作为懒加载资产"的先例(`assets/pdf.min.mjs` 与 `index.js:1538`),不破坏"零 npm 运行时依赖"。 +- Windows 的失败点可以通过静态审计全部列出来(见 §1.1),不需要等用户报障。 +- npm 包缺陷越晚修,受影响用户越多;0.15 与 Windows 同批发版,用户只需要升级一次。 + +--- + +## 2. 定位、目标与非目标 + +### 2.1 一句话定位 + +**让砚读覆盖"你真正在读的文档",并让这件事在 Windows 上同样成立。** + +### 2.2 目标用户与场景 + +- 主用户不变:用 DSH 做研究、学习、技术阅读的重度个人用户。 +- 新增用户:Windows 桌面的 DSH 用户;日常材料以 `.docx` 为主的学生、研究者、工程师、产品/法务。 +- 新增验收场景: + - 一份 30 页中文 Word 课程讲义:打开、看目录、划词解释、翻译一段英文引用、高亮、导出标注; + - 一份 2.4MB Word 技术报告(473 段、9 张表、27 张图):首屏、滚动、表格横向滚动、图片、搜索跨章、`reader_context` 能读到正文; + - 一台 Windows 11 + 125% 缩放 + 中文用户名的工作机:安装、打开子目录文档、GBK 笔记、文件被 Word 占用时保存标注、`Ctrl+Y` 重做、`Ctrl+滚轮` 缩放。 + +### 2.3 目标 + +1. **格式闭环**:`.docx` 与 PDF/EPUB/Markdown 共享同一套阅读、标注、概念、检索、对话能力,不需要用户切换心智。 +2. **平台闭环**:Windows 上安装、打开、阅读、保存、导出全链路可用,错误提示可读。 +3. **契约稳定**:docx 复用现有 store v2 与 HTML 契约,不新增文档类型字段、不改标注结构。 +4. **可验证**:每条 Word/Windows 需求都有自动化或明确的手工验收,不靠"看起来能用"。 +5. **不倒退**:macOS 的测试、视觉、动效、发布门禁全部保持。 + +### 2.4 非目标 + +- ❌ 不做 Word 版式还原(分页、页眉页脚、分栏、文本框、页码、页面背景)。 +- ❌ 不支持 `.doc` 二进制、`.rtf`、`.wps`;加密/密码保护的 docx 明确报错,不做解密。 +- ❌ 不做 Word 编辑、批注写回、修订接受/拒绝、目录域更新。 +- ❌ 不做 Windows 专用安装器、系统托盘、文件关联、右键菜单。 +- ❌ 不做 Linux 验收;不做 Windows ARM64 承诺。 +- ❌ 不做跨平台像素基线;Windows 只做布局探针(不溢出、不重叠、可点击)。 +- ❌ 不引入新的 Host 运行时依赖(mammoth 以客户端资产形式打包,Host 不 `import` 它)。 + +### 2.5 成功标准 + +| 维度 | 目标 | 验证方式 | +| --- | --- | --- | +| Word 打开 | 夹具 8 类 + 真实 2.4MB 报告全部打开;首屏 < 1.5s(473 段) | `eval/docx.mjs` + 手工 | +| Word 功能 | 划词、解释、翻译、高亮、笔记、概念、搜索、导出、`reader_context` 全通 | `test/docx.test.mjs` + eval + 手工 | +| Word 结构 | h1–h3 目录可跳;TOC 域旧页码不出现;无标题文档有"正文"兜底 | eval 断言 DOM | +| Word 性能 | 5000 段打开 < 2s;滚动无 > 50ms long task;10 万段按章加载不崩 | Puppeteer + PerformanceObserver | +| Windows 安装 | `npm pack` 后解包 Host 可 import;Windows 安装后阅读视图出现 | `publish-check` 新增"解包可加载"项;真机 | +| Windows 中文 | GBK/GB18030、UTF-16LE/BE、带 BOM 的 `.txt`/`.md` 正确显示 | 单测 + 真机 | +| Windows 路径 | 子目录文档的 basename、面包屑、相对图片、store 路径全部正确 | 单测 + 真机 | +| Windows 文件占用 | 占用时提示"文件被其他程序占用",标注不丢、store 不坏 | 单测 + 真机 | +| Windows 回归 | `node --test`、`eval/run.mjs`、`release-check` 的平台无关项在 `windows-latest` 全绿 | GitHub Actions | +| macOS 回归 | 401 条测试、163 项视觉、16/16 动效、12 项发布门禁不变 | 本地 + CI | +| 体积 | docx 资产懒加载;首屏 `client.js` 不因 docx 增大 | 构建前后字节对比 | +| 安全 | zip bomb、XXE/实体膨胀、`javascript:` 链接、SVG 脚本、`altChunk` 全部拒绝或无害化 | 安全夹具 + eval | + +--- + +## 3. Word 阅读体验 + +### 3.1 打开与首屏 + +书库把 `.docx` 视为可读文件,徽标显示 `DOCX`。点击后: + +1. 工具栏先显示文件名与"加载中…"; +2. 适配层解析 + 切章,完成后只渲染第一章; +3. 首屏出现后,目录在后台就绪; +4. 失败时给中文错误卡片,区分:不是 zip、文件损坏、加密文档、`.doc` 旧格式、章节过大。 + +首屏不显示骨架屏动画之外的占位,不显示"正在转换"——解析发生在浏览器本地,没有外部进程。 + +### 3.2 结构:标题即目录 + +docx 的章节标题有两个来源,适配层都要认: + +- 段落样式映射到 `heading 1`–`heading 6`(`word/styles.xml` 的 `w:style/w:name`); +- 段落属性带 `w:outlineLvl`(0–8),即使样式名不是 heading。 + +中文版 Word 的样式名通常是 `heading 1`(内部名)而不是"标题 1",但用户自定义样式、模板继承、WPS 生成的文档不一定。因此**预扫 `styles.xml` 建立 styleId → 标题级别的映射,再交给 mammoth**,而不是依赖默认样式名。 + +`TOC` 域(`w:sdt` 里的 `TOC`/`PAGEREF`)在 Word 里是**缓存结果**,页码和条目可能已过期。0.15 一律丢弃 TOC 域缓存,用标题重建目录;用户不会看到"目录里写着第 3 页,实际在第 7 章"。 + +无标题文档:整篇作为一章,目录显示"正文",不报错。 + +### 3.3 划词与概念 + +docx 渲染进 `.rd-page.rd-prose` 后,选区工具条、解释、翻译、高亮、笔记、复制全部走现有逻辑(`src/client/app.js:1470-1530`): + +- 解释 prompt 里的 `sentence`/`paragraph` 取选区所在的 `p`/`li`/`blockquote`; +- 概念卡记录 `chapter`(章序号)、`quote`、`occurrence`,**不写 `page`**; +- 概念卡"回到原文"按章跳转,不显示页码; +- 同一概念在 docx 与其它文档之间可以复用,`docs[docKey].path` 记录 `.docx` 相对路径。 + +### 3.4 翻译 + +- 默认英译中;目标语言与源语言与其它格式共用设置。 +- 只翻译可见块,滚动时继续补齐;块选择器与 Markdown 一致(`p`、`li`、`blockquote`、`h2`、`h3`、`h4`;`td` 只用于单元格内划词翻译,不参与段落对照)。 +- **表格单元格不参与段落对照翻译**:译文插入会撑破列宽,表格内改用划词翻译。这是明确取舍,写进设置说明。 +- 代码块/等宽块不翻译(`pre` 不进收集器)。 +- `only` 模式(仅译文)保留表格、图片、脚注锚点;不因为替换文本丢掉结构。 + +### 3.5 标注与检索 + +- 标注复用 `kind: 'text'`,`chapter` 存章序号;章内按 `quote + occurrence` 重锚(`src/client/annotations.js:113-139`)。 +- 搜索必须跨章:适配层提供 `docx.chapters[].text`,搜索命中后跳到对应章,再按 `quote` 定位。只搜当前章会让"全文搜索"名不副实。 +- 目录、标注、概念位置的文案用"第 N 章「标题」",不用页码(`lib/reader-context.js:210-220` 已支持 `chapterTitle`)。 + +### 3.6 表格、图片与脚注 + +- **表格**:真 ``,包 `.rd-table-wrap` 横向滚动;保留 `gridSpan`/`vMerge` 合并单元格;不压缩字号、不强制换行。 +- **图片**:按需解压 `word/media/*`,生成 Blob URL,关闭文档时统一 revoke;EMF/WMF 显示占位(浏览器不渲染),SVG 只走 ``,不内联。 +- **超链接**:只允许 `http:`/`https:`/`mailto:`/`#anchor`;`javascript:`、`data:`、`file:` 一律降级为纯文本。 +- **脚注/尾注(P1)**:上标锚点 + 章末脚注列表;不做浮层。若 mammoth 只给文末汇总,适配层按 `footnoteReference` 的 id 重新分配到所属章;做不到则降级为文末列表并记录。 +- **分页符(P1)**:渲染为一条细分隔线,不做分页;不产生页码。 +- **代码块(P1)**:等宽样式或 `HTML Preformatted` 映射为 `pre > code`。 + +### 3.7 长文档 + +- 单条 zip entry ≤ 40MB(现有 `MAX_ENTRY_BYTES`,`src/client/epub.js:49`);新增**总解压预算 200MB**,超限报"文档过大"。 +- 按 h1 切章,章级渲染;单章超过 3000 个块时,再按 h2 切子章,目录仍按 h1–h3 展示(P1)。 +- 打开 10 万段文档不允许整棵 DOM 挂载;超限时给明确提示,不白屏。 +- 滚动位置按 `chapter + scrollTop` 记忆;返回时先恢复章,再恢复章内滚动。 + +### 3.8 Word 边界 + +- `.docm` 不进入可读集合;若后续加入,宏不执行(P2)。 +- 修订:显示"接受所有修订后的最终稿"(`w:ins` 保留、`w:del` 丢弃),不做差异视图。 +- 批注:忽略,不渲染侧栏。 +- 分栏、文本框、页眉页脚、页码、页面背景:不还原。 +- OMML 公式:显示占位或纯文本,不做 MathML 转换(P2 再议)。 +- 加密/密码保护:不支持,提示"文档已加密,砚读无法打开"。 + +--- + +## 4. Windows 体验 + +### 4.1 安装 + +- 官方桌面端提供 Windows x64 安装包(Windows 10/11),无需预装 Node.js/pnpm。 +- 安装插件:侧栏 → **插件** → **添加插件** → 输入 `@2019wakeup/dsh-reader@latest` → 启用 → 重启。 +- 插件市场索引与 macOS 相同;索引 URL 走 `https:`。 +- 数据目录:`%USERPROFILE%\.dsh\profiles\desktop`;工作区内的 `.dsh-reader/` 不变。 + +**前置条件**:发布包必须完整。0.14.0 的 npm 包缺 `src/client/translate.js`,Windows 用户安装后会直接加载失败;W-01 必须最先修。 + +### 4.2 书库与路径 + +- Host 的 `listDir` 统一返回**POSIX 相对路径**(`\` → `/`);客户端不再看到反斜杠。 +- store 中 `doc.path`、阅读位置 `path` 等路径字段全部写 POSIX;`docKey` 仍是内容指纹,不受影响。 +- 读取旧 store 时把 `\` 归一化,迁移不破坏;跨平台复制 store 后,概念卡"回到原文"仍能定位。 +- 书库过滤 Windows 垃圾文件:`~$*`(Office 属主文件)、`desktop.ini`、`Thumbs.db`、`$RECYCLE.BIN`、`System Volume Information`。 +- 排序用 `Intl.Collator(undefined, { numeric: true })`,`第2章` 排在 `第10章` 前(P2)。 + +### 4.3 中文编码 + +Windows 上大量 `.txt`/`.md` 由记事本、老编辑器、Git 工具生成,编码不一定是 UTF-8: + +- 有 BOM:按 `UTF-8` / `UTF-16LE` / `UTF-16BE` 分派; +- 无 BOM:先 `fatal: true` 试 UTF-8;失败回退 `gb18030`(Chromium 内置); +- 仍失败:显示乱码替换符并在状态栏提示"编码可能不是 UTF-8/GBK"。 + +解码统一走一个 `decodeText(bytes)`,正文、搜索、翻译、概念、导出都用同一结果,避免"正文正常、搜索乱码"。 + +### 4.4 文件锁与错误 + +- `ENOENT` → 404 "文件不存在"; +- `EACCES`/`EPERM` → 403 "没有权限读取"; +- `EBUSY`(或写 store 时的 `EPERM`)→ 423 "文件被其他程序占用,请关闭后重试"; +- 不回传绝对路径;错误文案进 i18n。 +- store 原子写:`rename` 失败按 50/150/400ms 重试 3 次;仍失败回退 `copyFile` 覆盖;清理 tmp;位置上报失败静默,不弹错。 +- 备份删除失败不阻塞主流程。 + +### 4.5 键盘 + +- 撤销/重做:`Ctrl+Z` / `Ctrl+Shift+Z` / `Ctrl+Y`(Windows 标准);macOS 保持 `⌘Z` / `⌘⇧Z`。 +- 搜索:`Ctrl+F`。 +- 帮助面板与 README/DETAIL 的键位按平台显示;没有"⌘"出现在 Windows 上。 +- 输入法:`Esc` 在 `compositionstart` 后不关闭浮层;`Enter` 在输入法组合中不发送。 + +### 4.6 字体、滚动条与缩放 + +- 字体栈显式包含 `"Segoe UI"`、`"Microsoft YaHei UI"`、`"Microsoft YaHei"`;等宽显式包含 `"Cascadia Mono"`、`Consolas`。 +- PDF 文本层 span 显式设置 pdf.js 的字体族,减少 Windows 下选区与字形的水平偏移。 +- `.rd-main` 加 `scrollbar-gutter: stable`,避免短文档滚动条出现/消失导致正文横跳;布局探针测量时扣除 `offsetHeight - clientHeight`。 +- `Ctrl+滚轮`:阻止 Chromium 整页缩放,改为 PDF 缩放(PDF 文档)或正文字号(文本类文档);给出一次轻提示。 +- 高 DPI:`devicePixelRatio` 取整、上限 3;PDF canvas 不超过 3×,避免 200% 以上发虚。 +- 视觉验收不比较 Windows 像素;只验证不溢出、不重叠、关键按钮可点击。 + +### 4.7 测试与发布 + +- 单测去平台化:路径用 `path.join`/`os.tmpdir()`;symlink 测试在 Windows 用 junction 或按平台 skip;`host.test.mjs` 的 `/etc/hosts` 改为临时文件。 +- eval:Chrome 路径支持 `CHROME_PATH` 环境变量,Windows 自动探测 `Program Files\Google\Chrome\Application\chrome.exe` 与 Edge。 +- 脚本:`/tmp` → `os.tmpdir()`;`/usr/bin/zip` → Node 生成 demo zip;`npm` 调用在 Windows 用 `npm.cmd` 或 `shell: true`;`verify-market-index` 不再依赖 macOS 安装路径。 +- CI:新增 `ci.yml`,`macos-latest` + `windows-latest`;Windows 跑 `node --test`、`eval/run.mjs`、`release-check` 的平台无关项;视觉/动效只在 macOS 跑。 +- 发布工作流(`release.yml`)保持 `ubuntu-latest`,但发布前必须等 CI 双平台通过。 + +--- + +## 5. 需求清单 + +优先级定义:**P0 首先交付;P1 同属 0.15.0 发布范围,排在 P0 之后;P2 有余力再做,不承诺。** + +### 5.1 Word(D 系列) + +| ID | 需求 | 验收要点 | 优先级 | +| --- | --- | --- | --- | +| D-01 | `.docx` 进入可读集合与 MIME | 书库显示、能打开、错误可读 | P0 | +| D-02 | docx → 语义 HTML | 扁平块、标题/段落/加粗/斜体/下划线/删除线 | P0 | +| D-03 | 标题与目录 | h1–h3 可跳;TOC 域旧页码丢弃;无标题兜底 | P0 | +| D-04 | 划词解释 | 工具条、解释、概念卡、`occurrence` 正确 | P0 | +| D-05 | 翻译 | 可见块渐进;表格不参与;`only` 模式结构不丢 | P0 | +| D-06 | 标注 | 高亮/笔记/重锚;章节文案无页码 | P0 | +| D-07 | 全文搜索 | 跨章索引;命中跳章并定位 | P0 | +| D-08 | 表格 | 合并单元格;横向滚动;不撑破阅读区 | P0 | +| D-09 | 图片 | Blob URL;按需解压;关闭 revoke;EMF 占位 | P0 | +| D-10 | 超链接 | 只放行安全协议;`#anchor` 可跳 | P0 | +| D-11 | 阅读位置与工具 | `chapter + percent`;`reader_context`/`reader_read` 可读 | P0 | +| D-12 | 脚注/尾注 | 上标 + 章末列表 | P1 | +| D-13 | 导读/导图 | 摘要与导图复用现有结构 | P1 | +| D-14 | 分页符 | 细分隔线,不做分页 | P1 | +| D-15 | 代码块 | `pre > code`,不翻译 | P1 | +| D-16 | 长文档分章 | 按 h1 切;超大章按 h2 切;10 万段不崩 | P1 | +| D-17 | 安全与体积护栏 | 单条 40MB、总解压 200MB、脚本链接过滤 | P0 | +| D-18 | 修订/批注/分栏/文本框/OMML | 不做,明确记录 | P2(本版不做) | + +### 5.2 Windows(W 系列) + +| ID | 需求 | 验收要点 | 优先级 | +| --- | --- | --- | --- | +| W-01 | 发布包完整 | `npm pack` 后解包,Host 可 `import`;`publish-check` 覆盖 | P0 | +| W-02 | 路径归一化 | Host 返回 POSIX;客户端 basename/dirname/面包屑/图片解析正确 | P0 | +| W-03 | 中文编码探测 | UTF-8/UTF-16 BOM、GB18030 回退 | P0 | +| W-04 | 文件锁与错误映射 | 404/403/423;中文文案;不含绝对路径 | P0 | +| W-05 | store 写重试 | rename 3 次 + copyFile 回退;标注不丢 | P0 | +| W-06 | 测试链路跨平台 | `node --test` 在 Windows 全绿 | P0 | +| W-07 | CI Windows 矩阵 | `windows-latest` 跑单测 + eval + release 检查 | P0 | +| W-08 | 书库过滤 | `~$*`、`desktop.ini`、`Thumbs.db` 等不出现 | P1 | +| W-09 | 快捷键平台化 | `Ctrl+Y`;帮助文案按平台 | P1 | +| W-10 | Ctrl+滚轮 | 阻止整页缩放;PDF/字号缩放 | P1 | +| W-11 | 字体与 PDF 文本层 | 字体栈、等宽、text layer 字族、DPR 上限 | P1 | +| W-12 | 滚动条与布局探针 | `scrollbar-gutter`;测量扣除滚动条 | P2 | +| W-13 | 路径安全与长路径 | realpath fail-closed;大小写;UNC/长路径明确报错 | P2 | +| W-14 | 排序 | 数字感知 collator | P2 | +| W-15 | 拖拽/剪贴板/IME | 拖入打开;复制失败提示;Esc 不打断输入法 | P2 | +| W-16 | 安装文档 | README/DETAIL 增加 Windows 安装、路径、已知差异 | P1 | + +**本版范围**:D-01 至 D-17、W-01 至 W-11、W-16 属于 0.15.0;P2 不阻塞发布。若排期严重超支,只允许砍 P2,不允许砍 P0。 + +--- + +## 6. 交互规格 + +### 6.1 D-01 打开 docx + +```text +书库点击 report.docx + → 工具栏显示文件名 + 加载中 + → 解析(本地)→ 渲染第一章 + → 目录后台就绪 +``` + +- 加载中不锁工具栏;用户可以返回书库。 +- 解析超过 3s 显示进度文案("正在解析…"),不显示百分比假进度。 +- 失败卡片给出原因与"重试";`retry` 重新读取文件,不刷新页面。 + +### 6.2 D-03 章节与目录 + +- 目录列出 h1–h3,层级缩进与 Markdown 一致。 +- 点击目录滚动到标题,并触发 0.14 的一次性定位环(`pulseElement`)。 +- 当前章节在目录里高亮;滚动跨章时更新。 +- 章切换不重建抽屉滚动位置;目录面板保持滚动。 + +### 6.3 D-04 划词 + +- 选区在 `.rd-page` 内才显示工具条;在表格、图片说明、脚注里同样可用。 +- 解释返回后卡片贴词出现;`chapter`、`quote`、`occurrence` 写入概念出现位置。 +- 从概念卡"回到原文":先切章,再滚动,再定位环;三步都在同一交互里完成,不闪回第一页。 + +### 6.4 D-08 表格 + +- 表格外层 `.rd-table-wrap` 横向滚动;滚动条细,支持触控板横向。 +- 单元格内可以划词、解释、复制;高亮跨单元格时按文本节点拆段。 +- 表格不参与段落翻译;单元格内划词翻译可用。 +- 超宽表格不压缩字号;最左列不冻结(P2 可加)。 + +### 6.5 D-09 图片 + +- 图片按原始宽高比缩放到阅读列宽。 +- 点击不打开灯箱(P2);右键可复制图片地址(系统菜单)。 +- 图片加载失败显示占位 + alt 文本。 +- 关闭文档时 revoke 所有 Blob URL,不泄漏。 + +### 6.6 D-12 脚注(P1) + +- 正文脚注引用显示为上标数字,点击滚动到章末脚注列表。 +- 章末脚注列表用 `hr` 与正文分隔。 +- 脚注里的文本可划词、可解释。 +- 若适配层无法按章分配,降级为文末统一列表,并在 DETAIL.md 记录。 + +### 6.7 D-17 错误与降级 + +| 情况 | 表现 | +| --- | --- | +| 不是 zip | "不是有效的 Word 文档(.docx)" | +| 损坏/截断 | "文档结构损坏,无法打开" | +| 加密 | "文档已加密,砚读无法打开" | +| `.doc` 旧格式 | "不支持 .doc,请另存为 .docx" | +| 超大 | "文档过大(解压后超过 200MB)" | +| 解析器加载失败 | "Word 解析器加载失败,请重试" + 重试 | + +所有错误都进 `debug.lastError`,设置页可读;不弹系统对话框。 + +### 6.8 W-02 书库与路径 + +- Windows 的路径分隔符不出现在 UI:面包屑、文件名、概念位置文案统一 `/`。 +- `~$报告.docx`、`desktop.ini`、`Thumbs.db` 不显示;`$RECYCLE.BIN` 不显示为目录。 +- 空目录与只有垃圾文件的目录显示"这个目录里还没有可读的文档"。 + +### 6.9 W-03 编码 + +- 打开 GBK `.txt`:正文正确;搜索、翻译、概念 quote 与正文一致。 +- 打开 UTF-16LE `.md`:标题识别正常,目录可用。 +- 无法判断编码时:不阻塞打开,状态栏提示;用户可改用 UTF-8 另存。 + +### 6.10 W-04 文件锁 + +- 打开时被占用:错误卡片"文件被其他程序占用,请关闭后重试"。 +- 保存标注时被占用:保留本地未保存状态,提示重试;不静默丢。 +- store 写入重试期间不弹错;最终失败才提示。 +- 备份损坏时不阻止读取;恢复入口仍可用。 + +### 6.11 W-09 快捷键 + +- `Ctrl+Z` 撤销、`Ctrl+Shift+Z`/`Ctrl+Y` 重做、`Ctrl+F` 搜索。 +- 帮助面板显示当前平台键位;`?` 打开。 +- 输入框内不拦截快捷键(现有 `isEditableTarget` 逻辑保留)。 + +### 6.12 W-10 缩放 + +- `Ctrl+滚轮` 在阅读区:PDF 缩放 10% 步进;文本类字号 1px 步进。 +- 阻止页面缩放后,DSH 宿主界面不跟着缩放。 +- 捏合触控板在 Windows 上可能映射为 `Ctrl+滚轮`;行为一致。 +- 缩放后 PDF 文本层重新对齐;不出现选区错位。 + +### 6.13 P2 规格摘要 + +| ID | 规格 | +| --- | --- | +| W-12 | `scrollbar-gutter: stable`;布局探针扣除滚动条 | +| W-13 | realpath 失败拒绝;`path.relative` 判越界;大小写不敏感比较;长路径显式报错 | +| W-14 | `Intl.Collator(undefined, { numeric: true, sensitivity: 'base' })` | +| W-15 | 拖入文件打开;复制失败 toast;`compositionstart` 后 Esc 不关浮层 | + +--- + +## 7. 技术方案 + +### 7.1 路线选择 + +| 方案 | 做法 | 增量体积 | 优点 | 代价 | 结论 | +| --- | --- | --- | --- | --- | --- | +| A. 自研 OOXML | 复用 `src/client/epub.js` 的 unzip,解析 `document.xml`/`styles.xml`/`numbering.xml`/rels/media | 25–40KB / 8–12KB gzip | 零依赖、完全可控、可精确适配阅读器主题 | 12–16 人日;OOXML 边角多,长期维护重 | 备选 | +| B. mammoth 1.13.0 | 构建期打包为 `assets/docx.mjs`,运行期懒加载;输出语义 HTML | 405KB / 100.6KB gzip(含 JSZip) | 输出正好符合契约;标题/列表/表格/图片/链接/脚注/修订覆盖强 | 体积大;不认 `outlineLvl`;不做 sanitization | **采用** | +| C. docx-preview 0.4.1 | 按 Word 版式渲染分页 DOM | 75.5KB + JSZip 97.8KB / 约 49KB gzip | 版式最像 Word,支持页眉页脚/OMML | 分页 DOM 与连续滚动冲突;`sanitize.js` 删 class/style 会让版式塌掉 | 不采用 | +| D. Host 转换 | Host 调 LibreOffice/pandoc 转 HTML | 0 客户端 | 实现简单 | 插件无 spawn 先例;违背"宿主不解析源文件";跨平台/安全/延迟都差 | 不采用 | + +**结论**:采用 **B + 适配层**。理由: + +1. **契约匹配**:mammoth 输出的是扁平语义块(`p`/`h1`/`table`/`img`/`a`),正好是 `.rd-prose > *` 需要的形状;不需要把 Word 的版式翻译成 CSS。 +2. **工期**:0.15 同时做 Windows,docx 自研 12–16 人日会挤掉 Windows 的真机验证;mammoth 路线 6–8 人日。 +3. **先例**:PDF.js 已经是随包第三方资产(`assets/pdf.min.mjs`,`index.js:1538`),mammoth 用同样的懒加载方式,不增加 Host 依赖、不影响首屏。 +4. **可替换**:适配层接口(`docxOpen(bytes) → { chapters, assets, outline }`)与解析器解耦;若以后自研,只换实现。 + +**体积取舍**:405KB / 100.6KB gzip 只在打开 `.docx` 时加载,不计入 `client.js` 首屏;首屏 bundle 不变。PRD 接受该体积并记录在 §9.5。 + +### 7.2 架构 + +```text +index.js + ├─ MIME 增加 .docx + ├─ readFile:200MB 单文件上限(不变) + └─ listDir:path.relative → 归一化为 POSIX + +src/client/docx.js(新增) + ├─ docxOpen(bytes) + │ ├─ 复用 unzip / inflate(epub.js) + │ ├─ 预算检查:单条 40MB、总解压 200MB + │ ├─ 预扫 word/styles.xml → outlineLvl / heading 映射 + │ ├─ 剔除 TOC 域缓存(sdt + PAGEREF) + │ ├─ mammoth.convertToHtml(懒加载 assets/docx.mjs) + │ │ ├─ styleMap:heading / outlineLvl + │ │ └─ convertImage:media → Blob URL,登记 assets + │ ├─ 后处理:扁平化、table 包裹、协议过滤、脚注分配 + │ └─ 按 h1 切章 → chapters[{ label, html, text }] + └─ docxGuideStructure(chapters) → { toc, parts, sections } + +src/client/app.js + ├─ READABLE 增加 .docx + ├─ openDoc:doc.ext === '.docx' → docxOpen + ├─ renderedHtml:docx 当前章 + ├─ 目录:docx 章列表 + h1–h3 + ├─ currentPosition / buildContextWindow:docx 分支 + └─ 搜索:跨章索引 + 跳章 + +src/client/styles.js + ├─ .rd-prose 表格/图片/脚注样式 + └─ Windows 字体栈、scrollbar-gutter +``` + +### 7.3 适配层关键实现 + +**标题映射**(预扫 `styles.xml`): + +```js +// styleId -> { name, outlineLvl } +// 生成 mammoth styleMap: +// p[style-name='标题 1'] => h1 +// p[style-name='heading 2'] => h2 +// 对带 outlineLvl 但无 heading 名称的样式,用其 w:name 生成映射 +``` + +mammoth 默认只认样式名,不认 `outlineLvl`;中文模板、WPS 模板、企业模板经常只靠 `outlineLvl`,不预扫会丢标题。 + +**图片**: + +```js +mammoth.images.imgElement(async (image) => { + if (!ALLOWED_IMAGE.has(image.contentType)) return { src: placeholder } + const buffer = await image.readAsArrayBuffer() + const url = URL.createObjectURL(new Blob([buffer], { type: image.contentType })) + assets.push(url) + return { src: url } +}) +``` + +只解压被引用到的 `word/media/*`;EMF/WMF 直接占位,不尝试解码。 + +**章节切分**: + +```js +// 按

切;无 h1 → 一章;单章 > 3000 块 → 按 h2 切子章 +function splitChapters(html) → [{ label, html, text }] +``` + +章节序号一旦发布就冻结:标注只存 `chapter` 序号,切分规则变化会让旧标注错位。 + +**位置百分比**(字符加权,比等章权重准): + +```js +percent = (beforeChapterChars + chapterProgress * chapterChars) / totalChars +``` + +### 7.4 章节与位置 + +- `chapter`:h1 序号(0 基);无 h1 为 0。 +- `chapterTitle`:h1 文本;无 h1 为"正文"。 +- `page`:固定 0,不伪造。 +- `total`:0。 +- `percent`:按字符加权。 +- `reader_context`:客户端上报的窗口文本取当前章前后;`reader_read` 的 `chapter` 模式返回当前章。 +- 跳转:目录/标注/概念 → 切章 → 滚动 → 定位环。 + +### 7.5 图片与资产 + +- `docx.assets` 与 `doc.epub.assetUrls` 同构,关闭时统一 revoke(`app.js:1144-1152` 扩展分支)。 +- 单图上限 20MB;超过给占位。 +- 并发解压上限 4,避免大图集卡死。 +- 同一张图被多次引用只解压一次(按 rel id 缓存)。 + +### 7.6 安全 + +| 风险 | 防护 | +| --- | --- | +| zip bomb | 单条 40MB + 总解压 200MB + 条目数上限 5000 | +| XML 实体膨胀 / XXE | 预扫用 DOMParser;拒绝含 `DOCTYPE`/`ENTITY` 的 XML;mammoth 输入前剥离 | +| 脚本注入 | mammoth 输出后白名单化;禁 `script`/`iframe`/`on*`;链接协议白名单 | +| 图片 SVG 脚本 | 只走 ``,不内联;Blob type 限制 | +| `altChunk` 注入 HTML | 不处理 `altChunk`(P2 也不做) | +| 路径穿越 | `resolveInWorkspace` 已有;新增 realpath fail-closed | + +### 7.7 Windows 适配层 + +**路径归一化**(Host): + +```js +const toPosix = (p) => String(p).replace(/\\/g, '/') +// listDir 的 path、store 的 doc.path、reading.position.path +``` + +**客户端**:`basename`/`dirname`/`markdownImageResolver`/面包屑统一 `normalizeRelPath`;`READABLE` 扩展名判断不受影响。 + +**编码**: + +```js +function decodeText(bytes) { + const bom = detectBom(bytes) + if (bom) return new TextDecoder(bom).decode(bytes) + try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes) } + catch { return new TextDecoder('gb18030').decode(bytes) } +} +``` + +**错误映射**:`fs` 错误码 → `{ status, code }`;响应体只给 `code` 与中文文案,不含路径。 + +**快捷键**:`shortcutFor` 增加 `key === 'y'` 的 redo;帮助面板用 `platformLabel()`(`navigator.userAgentData?.platform`)。 + +**字体/滚动条**:CSS 显式字体栈;`.rd-main { scrollbar-gutter: stable }`;`host-layout.js` 测量扣除 `offsetHeight - clientHeight`。 + +### 7.8 发布包修复 + +0.14.0 的 Host 入口 `import { blockHash } from './src/client/translate.js'`,而 `files` 不含 `src/`。修法: + +1. 新增 `lib/block-hash.js`(纯函数,无 Node 内置依赖),放 `normalizeBlockText`/`blockHash`; +2. `index.js` 改为从 `./lib/block-hash.js` 导入; +3. `src/client/translate.js` 改为从 `../../lib/block-hash.js` 导入(Node 测试可直接解析),并在 `scripts/build-client.mjs` 的拼接列表里把 `lib/block-hash.js` 放在 `src/client/translate.js` 之前——构建器会剥掉 import 行、保留函数定义,浏览器 bundle 里不出现重复实现; +4. `publish-check` 新增:`npm pack` 后解包,用 Host 入口 `import()` 一次,失败即拒绝发布; +5. `files` 白名单保持不含 `src/`,避免把客户端源码散进包。 + +### 7.9 文件改动 + +| 文件 | 改动 | 风险 | +| --- | --- | --- | +| `src/client/docx.js` | 新增:解析、切章、图片、脚注、安全、导读结构 | 高(新模块) | +| `assets/docx.mjs` | 新增:mammoth 构建产物(懒加载) | 中(体积 + 许可) | +| `assets/LICENSE-MAMMOTH` | 新增:BSD-2 许可证 | 低 | +| `src/client/app.js` | READABLE、openDoc、渲染、目录、搜索、位置、图片 revoke | 高(大文件) | +| `src/client/styles.js` | 表格/图片/脚注;Windows 字体栈、scrollbar-gutter | 中 | +| `src/client/util.js` | `normalizeRelPath`、`basename`/`dirname` 兼容 `\` | 中 | +| `src/client/api.js` | 错误码到中文文案的映射 | 低 | +| `src/client/shortcuts.js` | `Ctrl+Y`;平台标签 | 低 | +| `src/client/i18n.js` | docx/Windows 文案;修重复键覆盖 | 低 | +| `src/client/host-layout.js` | 高度测量扣除滚动条 | 低 | +| `index.js` | MIME、listDir 归一化、错误映射、文件锁 | 中 | +| `lib/paths.js` | realpath fail-closed;跨平台前缀比较 | 中 | +| `lib/store.js` | rename 重试 + copyFile 回退 | 中 | +| `lib/reader-context.js` | docx 位置兼容(`chapterTitle`) | 低 | +| `lib/block-hash.js` | 新增:`normalizeBlockText`/`blockHash` 纯函数,Host 与客户端共用 | 低 | +| `src/client/translate.js` | 改为引用 `lib/block-hash.js`,去掉重复定义 | 低 | +| `scripts/build-client.mjs` | 拼接顺序加入 `lib/block-hash.js` 与 `docx.js`;构建 mammoth 资产 | 中 | +| `scripts/publish-check.mjs` | 解包可加载检查;npm.cmd | 中 | +| `test/docx.test.mjs` | 新增:夹具生成 + 解析断言 | 中 | +| `test/windows.test.mjs` | 新增:路径、编码、错误、快捷键 | 中 | +| `test/paths.test.mjs` / `host.test.mjs` | 去平台化 | 中 | +| `eval/docx.mjs` | 新增:真实渲染、目录、划词、搜索、性能 | 中 | +| `eval/visual.mjs` / `motion.mjs` / `layout-host.mjs` | Chrome 路径探测;Windows 不跑像素 | 低 | +| `scripts/make-demo-epub.mjs` | Node zip 生成 | 低 | +| `.github/workflows/ci.yml` | 新增:macOS + Windows 矩阵 | 低 | +| `package.json` | `0.15.0`、`eval:docx` 脚本、可选 `dependencies` 不变 | 低 | +| `plugin-market.json` | 0.15.0 条目 | 低 | +| `README.md` / `docs/DETAIL.md` | Word、Windows、安装、已知差异 | 低 | + +--- + +## 8. 兼容与降级 + +1. **store 兼容**:v2 不变;旧 store 的 `\` 路径读取时归一化,写回 POSIX;docKey 仍是内容指纹,改名/移动不丢标注。 +2. **旧版 DSH**:docx 不依赖新宿主 API;Windows 修复不改变插件接口。低于 `0.2.2-rc.5` 的 DSH 仍按现有能力降级(对话面板隐藏)。 +3. **mammoth 加载失败**:显示错误 + 重试;不 fallback 到自研解析(未实现),也不假装成功。 +4. **大文档**:分章 + 章级渲染;超限给明确错误;不白屏、不冻死。 +5. **表格翻译降级**:表格不参与段落翻译,提供划词翻译;写进设置说明。 +6. **脚注降级**:无法按章分配时退回文末列表,DETAIL.md 记录。 +7. **Windows 视觉降级**:不承诺像素一致;布局探针保证不溢出、不重叠、可点击。 +8. **字体缺失**:字体栈最后回退 `sans-serif`;不内嵌字体。 +9. **发布回滚**:docx 是新增格式,回滚只需回退客户端代码与版本号;Windows 修复向后兼容,回滚不影响 store。 + +--- + +## 9. 测试与验收 + +### 9.1 单元测试 + +新增 `test/docx.test.mjs`,用手写 zip 夹具(复用 `test/epub.test.mjs` 的 `zipBytes` 思路),覆盖: + +1. `minimal`:一段文本 → `p`;书库可读。 +2. `styles-outline`:数字 styleId + `outlineLvl` + `heading` 名称 → h1/h2 正确。 +3. `toc-field`:含 `TOC`/`PAGEREF` 的 sdt → 旧页码不出现,目录按标题重建。 +4. `numbering`:嵌套列表、起始编号。 +5. `table`:`gridSpan`/`vMerge` 合并单元格;`rd-table-wrap`。 +6. `media`:PNG 正常、SVG 走 img、EMF 占位、缺失 rel 不崩。 +7. `links`:`javascript:` 降级、`#anchor` 可跳。 +8. `notes`:脚注引用与章末分配(P1)。 +9. `broken`:非 zip、截断、畸形 XML、`DOCTYPE` 实体、zip bomb、超 200MB → 明确错误。 +10. `large`:1 万段切章(默认 skip,CI 手动跑)。 + +新增 `test/windows.test.mjs`: + +1. `normalizeRelPath`:`sub\a.md` → `sub/a.md`;`C:\ws\a` → `C:/ws/a`。 +2. `basename`/`dirname` 对 `\` 兼容。 +3. `decodeText`:UTF-8、UTF-8 BOM、UTF-16LE、GB18030 字节。 +4. 错误映射:ENOENT/EBUSY/EACCES → 404/423/403。 +5. `shortcutFor`:`Ctrl+Y` → redo;`Ctrl+Shift+Z` → redo。 +6. store 写重试:mock rename 失败两次后成功;三次失败后 copyFile。 + +目标:新增 ≥25 条单测(每个夹具拆成 2–3 条断言级用例);现有 401 条不回归;`paths.test.mjs`/`host.test.mjs` 在 Windows 也通过。 + +### 9.2 docx eval(新增 `eval/docx.mjs`) + +复用 `eval/visual/harness.jsx` 的 fixture 与 server,至少 12 项: + +| # | 检查 | 断言 | +| --- | --- | --- | +| 1 | 打开 | 第一章渲染;无 console error | +| 2 | 目录 | h1–h3 数量正确;点击跳章;定位环出现 | +| 3 | 划词 | 选区工具条出现;解释请求带 `chapter`/`quote` | +| 4 | 翻译 | 可见段落入队;表格不翻译;`only` 模式保留表格/图片 | +| 5 | 表格 | `.rd-table-wrap` 存在;超宽时出现横向滚动 | +| 6 | 图片 | `src` 为 blob:;关闭后 revoke | +| 7 | 搜索 | 跨章命中;跳章后高亮定位 | +| 8 | 脚注(P1) | 上标点击滚到章末;脚注文本可划词;若 0.15 未实现则从 eval 移除并记录 | +| 9 | 位置 | `reader_context` 返回 `page:0` + `chapterTitle` + percent | +| 10 | 导出 | 标注 Markdown 显示"第 N 章" | +| 11 | 性能 | 5000 段打开 < 2s;无 >50ms long task | +| 12 | 安全 | `javascript:` 链接无 href;无 `script`/`on*` | + +### 9.3 Windows 矩阵 + +- GitHub Actions `ci.yml`:`macos-latest` + `windows-latest`。 +- Windows 跑:`node --test test/*.test.mjs`、`node eval/run.mjs`、`node scripts/release-check.mjs` 的平台无关项、`npm pack` + 解包 import。 +- 视觉/动效只在 macOS 跑;Windows 跑 `eval/layout-host.mjs` 的布局探针(不溢出、不重叠)。 +- 结果作为发布前置:双平台绿才允许打 tag。 + +### 9.4 视觉回归 + +- macOS:163 项检查 + 22 张基线不变;新增 docx 打开截图基线(浅色/深色),需人工比对。 +- Windows:不做像素基线;做布局探针与关键控件坐标断言(工具栏、抽屉、卡片在视口内)。 +- 字体差异导致的换行变化不视为回归;溢出/重叠/不可点击视为回归。 + +### 9.5 性能与体积 + +| 项 | 预算 | +| --- | --- | +| 首屏 `client.js` | 因 docx 增量 ≤ 5KB 未压缩(只是分支与接口) | +| docx 资产 | 懒加载;405KB / 100.6KB gzip;仅打开 docx 时请求 | +| 打开 2.4MB / 473 段 | < 1.5s 首屏 | +| 打开 5000 段 | < 2s | +| 滚动 | 无 >50ms long task(Puppeteer + PerformanceObserver) | +| 图片 revoke | 关闭后 `docx.assets` 全部 revoke,无泄漏 | + +构建前后对比记录在发布说明;超预算必须解释。 + +### 9.6 手工验收 + +**Word:** + +- [ ] 中文讲义(含标题、列表、表格、图片、超链接)打开、目录、划词、解释、高亮、翻译、搜索、导出。 +- [ ] 2.4MB 技术报告(473 段、9 表、27 图)首屏、滚动、表格横向、图片、跨章搜索。 +- [ ] 无标题文档、单段文档、空文档、加密文档、损坏文档、`.doc` 文件各一。 +- [ ] 浅色/深色/米黄;1280px/900px;200% 缩放。 + +**Windows:** + +- [ ] Windows 11 x64 安装插件、启用、重启、打开阅读视图。 +- [ ] 中文用户名/中文路径/子目录文档;Markdown 相对图片。 +- [ ] GBK `.txt`、UTF-16LE `.md`、带 BOM 的 `.md`。 +- [ ] `~$报告.docx`、`desktop.ini`、`Thumbs.db` 不显示。 +- [ ] Word 占用文件时打开/保存标注;提示可读、数据不丢。 +- [ ] `Ctrl+Y`、`Ctrl+滚轮`、帮助面板键位。 +- [ ] 125%/150% 缩放;经典滚动条;短文档不横跳。 +- [ ] PDF 打开、文本层选择、双页、缩放。 +- [ ] 对话输入法、发送、`Esc` 取消候选。 +- [ ] 导出 JSON、导出标注 Markdown、恢复备份。 + +### 9.7 发布门禁 + +在现有 12 项 release check 上增加第 13 项,并把 CI 双平台作为前置: + +```text +docx pipeline node eval/docx.mjs ≥12/12 +``` + +最终门禁: + +- `node --test test/*.test.mjs`:≥426 条(401 + 25)全绿,macOS 与 Windows 均通过。 +- `node eval/run.mjs`:18/18。 +- `node eval/visual.mjs`:163 项 + 22 张基线(macOS)。 +- `node eval/motion.mjs`:16/16。 +- `node eval/docx.mjs`:≥12/12。 +- `node eval/layout-host.mjs`:6/6(macOS + Windows)。 +- `node scripts/release-check.mjs`:13/13。 +- `publish-check`:`npm pack` 后解包可 import。 +- GitHub Actions:macOS + Windows 双绿。 + +--- + +## 10. 发布、回滚与度量 + +### 10.1 版本与发布 + +- npm 版本:`0.14.0` → `0.15.0`。 +- 同步更新:`package.json`、`client.js`(构建产物)、`assets/docx.mjs`、`plugin-market.json`、README 版本号、DETAIL.md。 +- 发布说明一句话:**"0.15.0:支持 Word(.docx)阅读,支持 Windows 桌面端;路径、中文编码、文件锁、快捷键与发布链路跨平台修复;无数据变更。"** +- 发布顺序:先合并 W-01(发布包完整)→ 再合 docx → 再合 Windows 适配 → 最后文档与市场索引。 + +### 10.2 回滚 + +- docx 是新增格式:回滚客户端代码与版本号即可,store 不变(docx 文档的 `docs` 记录保留但不再可读,不影响其它格式)。 +- Windows 修复向后兼容,但 0.14.x 不认 0.15 写入的 POSIX 路径(basename/图片解析会错)——因此回滚只允许回退到 0.14.x 的完整包,并提示 Windows 用户重装 0.15;不做跨版本 store 降级。 +- 若 mammoth 资产在某个 Windows 版本加载失败:可通过移除 `READABLE` 中的 `.docx` 热修;不阻塞其它格式。 + +### 10.3 度量 + +- 不新增遥测、不上报用户行为。 +- 用 3 天 dogfood 记录:docx 打开失败次数、Windows 上错误提示、文件锁发生次数、`Ctrl+Y` 使用、表格/图片问题。 +- 发布后观察 issue 标签:`docx`、`windows`;出现"打不开/乱码/标注丢"即进入 0.15.1。 + +--- + +## 11. 排期 + +预计 10–12 个开发日(含测试与文档,不含评审等待)。 + +| 阶段 | 内容 | 产出 | 估时 | +| --- | --- | --- | --- | +| M0 发布修复 | W-01 发布包、publish-check 解包检查 | 可安装的 0.15 基线 | 1d | +| M1 docx 解析 | mammoth 资产、适配层、标题映射、切章、图片、安全 | 能打开并渲染 | 3d | +| M2 docx 功能 | 目录、划词、翻译、标注、搜索、位置、导读 | 功能闭环 | 2.5d | +| M3 Windows 适配 | W-02~W-05、W-08~W-11 | Windows 可用 | 2d | +| M4 跨平台测试 | 单测去平台化、CI 矩阵、Chrome 探测、脚本修复 | 双平台绿 | 1.5d | +| M5 文档与发布 | README、DETAIL、市场索引、发布说明 | 可发布 | 1d | +| M6 真机验收 | Windows 手工清单、dogfood | 验收记录 | 1d | + +依赖关系:M0 → M1/M3 可并行;M2 依赖 M1;M4 依赖 M2/M3;M6 依赖 M4。 + +--- + +## 12. 风险与决策记录 + +### 12.1 风险 + +| 风险 | 概率 | 影响 | 缓解 | +| --- | --- | --- | --- | +| mammoth 对中文模板标题识别不足 | 中 | 高 | 预扫 `styles.xml`(heading 名称 + `outlineLvl`)生成 styleMap;夹具覆盖数字 styleId/WPS 模板 | +| mammoth 体积超预期 | 中 | 中 | 懒加载资产;首屏不计入;记录 405KB/100.6KB gzip;必要时裁剪未用模块 | +| TOC 域旧页码被渲染 | 中 | 中 | 预处理剔除 sdt;eval 断言 | +| 脚注按章分配失败 | 中 | 低 | 降级文末列表;DETAIL.md 记录 | +| 表格内翻译撑破布局 | 高 | 中 | 表格不参与段落翻译;划词翻译兜底 | +| 大文档整棵 DOM 卡死 | 中 | 高 | 按 h1 切章;5000 段预算;超限提示 | +| Windows 无真机,只有 CI | 高 | 高 | CI `windows-latest` + 作者/志愿者真机清单;发布前必须完成 | +| Windows 杀软/OneDrive 锁文件 | 中 | 高 | rename 重试 + copyFile 回退;423 提示;失败不丢本地状态 | +| 路径归一化破坏 macOS 旧 store | 低 | 高 | 读取时兼容 `\`;写回 POSIX;迁移测试覆盖 | +| 发布包修复引入循环引用 | 低 | 中 | `blockHash` 移到 `lib/block-hash.js`;`src` 只 import;构建与 `npm pack` 双重检查 | +| 视觉基线因字体变化漂移 | 中 | 低 | Windows 不做像素;macOS 只更新 docx 新基线并人工比对 | +| mammoth 安全边界不清 | 中 | 高 | 白名单 sanitize;拒绝 DOCTYPE/ENTITY;链接协议过滤;安全夹具 | +| 双平台 CI 时间过长 | 中 | 低 | Windows 只跑单测 + eval;视觉/动效留在 macOS | + +### 12.2 决策记录 + +| 决策 | 选择 | 理由 | +| --- | --- | --- | +| docx 渲染路线 | mammoth 懒加载 + 适配层 | 契约匹配、工期短、PDF.js 已有先例;自研留作备选 | +| 是否还原分页 | 不还原 | 连续滚动是产品性格;分页会破坏位置、翻译、缩放 | +| 页码 | 不伪造,`page:0` | docx 没有稳定页码;伪造会让 `reader_context` 和标注错位 | +| 表格翻译 | 不参与段落对照 | 译文撑破列宽;划词翻译兜底 | +| `.doc` | 不支持 | 二进制格式;mammoth 不支持;提示另存 | +| Windows 范围 | 10/11 x64 | 与 DSH 官方发行一致;ARM64 不承诺 | +| Windows 视觉 | 不做像素基线 | 字体不同;布局探针更实际 | +| 测试策略 | 双平台 CI + 真机清单 | 作者主环境是 macOS;不能只靠 mac 单测 | +| 发布包检查 | `npm pack` 后解包 import | 0.14 的真实缺陷;必须成为门禁 | +| 路径存储 | POSIX 相对路径 | 跨平台 store 可迁移;UI 不出现反斜杠 | +| 编码回退 | GB18030 | 覆盖 GBK/GB2312;Chromium 内置 | +| 快捷键 | 保留 `⌘`,增加 `Ctrl` 分支 | 不破坏 mac 用户;Windows 原生习惯 | + +### 12.3 评审重点 + +以下三项最可能被挑战,已按建议写入;如需调整,优先改这三处: + +1. **mammoth 体积**:405KB / 100.6KB gzip 是资产懒加载,还是应该自研 25–40KB?本文选择前者,理由是工期与覆盖率;若坚持"零第三方代码",改走 A 路线,排期 +6–8 人日。 +2. **表格不参与段落翻译**:这是体验取舍;如果要求表格也能对照翻译,需要改列宽策略,排期 +1–2 人日。 +3. **Windows 支持范围**:是否承诺 Windows ARM64、是否做像素基线;本文选择"x64 + 布局探针",理由是与 DSH 官方发行一致。 + +--- + +## 13. 附录 + +### 13.1 验收清单 + +> 发布前逐项确认;未完成项必须写明原因。 + +**Word(D 系列)** + +- [ ] D-01 书库显示 `.docx`,能打开;错误可读。 +- [ ] D-02 标题/段落/加粗/斜体/下划线/删除线渲染正确。 +- [ ] D-03 目录 h1–h3 可跳;TOC 旧页码不出现;无标题兜底。 +- [ ] D-04 划词解释、概念卡、`occurrence` 正确。 +- [ ] D-05 翻译可见块;表格不翻译;`only` 模式结构保留。 +- [ ] D-06 高亮/笔记/重锚;文案无页码。 +- [ ] D-07 跨章搜索;跳章定位。 +- [ ] D-08 表格合并单元格、横向滚动。 +- [ ] D-09 图片 Blob URL、关闭 revoke、EMF 占位。 +- [ ] D-10 安全链接白名单;`#anchor` 跳转。 +- [ ] D-11 `reader_context`/`reader_read` 可读 docx;位置 `chapter + percent`。 +- [ ] D-12 脚注(P1)上标 + 章末;失败降级文末。 +- [ ] D-13 导读/导图(P1)可用。 +- [ ] D-14 分页符(P1)细分隔线。 +- [ ] D-15 代码块(P1)不翻译。 +- [ ] D-16 大文档分章、10 万段不崩。 +- [ ] D-17 zip bomb/XXE/脚本注入全部拒绝。 + +**Windows(W 系列)** + +- [ ] W-01 `npm pack` 解包 Host 可 import;publish-check 覆盖。 +- [ ] W-02 子目录文档 basename/面包屑/图片正确。 +- [ ] W-03 GBK/UTF-16 正确显示。 +- [ ] W-04 文件锁 423 + 中文提示;无绝对路径。 +- [ ] W-05 store 写重试;标注不丢。 +- [ ] W-06 Windows `node --test` 全绿。 +- [ ] W-07 CI `windows-latest` 全绿。 +- [ ] W-08 垃圾文件不显示。 +- [ ] W-09 `Ctrl+Y`、帮助键位正确。 +- [ ] W-10 `Ctrl+滚轮` 不缩放整页。 +- [ ] W-11 字体栈、text layer、DPR。 +- [ ] W-16 README/DETAIL 增加 Windows 说明。 + +**回归** + +- [ ] 401 条旧测试全绿。 +- [ ] 163 项视觉 + 22 张基线不变(macOS)。 +- [ ] 16/16 动效。 +- [ ] 12 → 13 项 release check。 +- [ ] 首屏 `client.js` 增量 ≤5KB。 +- [ ] 发布说明、README、DETAIL、market 同步。 + +### 13.2 代码触点 + +| 位置 | 用途 | +| --- | --- | +| `src/client/docx.js` | 新增:docx 解析、切章、图片、脚注、安全、导读结构 | +| `src/client/app.js` `openDoc()` | docx 打开分支 | +| `src/client/app.js` `renderedHtml` | docx 当前章 HTML | +| `src/client/app.js` `renderContent()` | `.rd-prose` 注入 | +| `src/client/app.js` `renderDrawerShell()` | 目录 docx 分支 | +| `src/client/app.js` `reportCurrentPosition()` / `buildContextWindow()` | docx 位置与窗口 | +| `src/client/app.js` 搜索抽屉 | 跨章搜索与跳章 | +| `src/client/app.js` `revokeAssets()` | docx 图片 revoke | +| `src/client/util.js` | `READABLE`、`normalizeRelPath`、`basename`/`dirname` | +| `src/client/shortcuts.js` | `Ctrl+Y`、平台标签 | +| `src/client/styles.js` | 表格/图片/脚注、字体栈、`scrollbar-gutter` | +| `src/client/i18n.js` | docx/Windows 文案;修重复键 | +| `index.js` `listDir`/`readFile` | POSIX 路径、错误映射、垃圾文件过滤 | +| `lib/paths.js` | realpath fail-closed | +| `lib/store.js` | 写重试 | +| `lib/block-hash.js` | `normalizeBlockText`/`blockHash` 纯函数 | +| `scripts/build-client.mjs` | `block-hash`/`docx.js` 拼接、mammoth 资产 | +| `scripts/publish-check.mjs` | 解包可加载 | +| `test/docx.test.mjs` / `test/windows.test.mjs` | 新增测试 | +| `eval/docx.mjs` | 新增 eval | +| `.github/workflows/ci.yml` | 双平台 CI | + +### 13.3 术语 + +- **docx 契约**:非 PDF 文档统一渲染为扁平语义 HTML + h1–h3,挂进 `.rd-page.rd-prose`。 +- **适配层**:包裹 mammoth 的 `src/client/docx.js`,负责标题映射、切章、图片、脚注、安全。 +- **懒加载资产**:`assets/docx.mjs` 在打开 docx 时才加载,不计入首屏 bundle。 +- **POSIX 相对路径**:统一用 `/` 分隔的工作区相对路径,跨平台存储与展示。 +- **布局探针**:不比较像素,只断言元素在视口内、不溢出、不重叠、可点击。 +- **发布包完整性**:`npm pack` 产物解包后,Host 入口能 import、阅读视图能注册。 +- **P0/P1/P2**:发布优先级;P0 首先交付,P1 同属 0.15.0 范围,P2 有余力再做。 + +### 13.4 调研方法与未验证项 + +**已在本工作区验证:** + +- `npm pack @2019wakeup/dsh-reader@0.14.0`(本地目录与 registry tarball 各一次):223 个文件,均无 `src/client/translate.js`;`index.js:9` 顶层 import 该文件。 +- 0.14.0 源码逐文件审计:路径、编码、文件锁、快捷键、字体、测试/脚本的 macOS 假设,行号见 §1.1 与 §13.2。 +- 现有 READABLE、HTML 契约、翻译块收集器、标注重锚、`reader_context` 位置字段的代码路径。 +- DSH 桌面端本地安装文档确认 Windows 数据目录与卸载路径。 + +**未在本工作区验证(实现阶段必须复核):** + +- mammoth / docx-preview 的体积、许可证与输出细节来自外部产物实测(2026-11-24),项目内尚未接入;标题映射、TOC 域、脚注分配的最终行为要用夹具复核。 +- Windows 真机行为(文件锁、OneDrive/杀软、输入法、DPI、经典滚动条)未实测;PRD 中的错误码与文案是代码级推断,验收以 §9.6 手工清单为准。 +- DSH Windows 安装包的具体文件名与系统要求以官方下载页为准;本文只确认"官方提供 Windows x64 桌面端"。 +- 2.4MB Word 技术报告只做了结构统计(473 段、8 个 h1、32 个 h2、9 张表、27 张图、217 处修订、83 个书签),未在 0.15 实现前跑通渲染。 +- "打开 5000 段 < 2s""10 万段不崩"是预算目标,需要用真实夹具在目标机型上标定。 diff --git a/dsh-reader/README.md b/dsh-reader/README.md index f55df8f..0aadb4a 100644 --- a/dsh-reader/README.md +++ b/dsh-reader/README.md @@ -6,7 +6,7 @@ - **递归学习**:解释里遇到新概念,就在悬浮卡里继续追问、生成子卡;父卡保留、概念链可见,最多 3 层。 - **交给原生对话**:需要工具、联网或多轮推演时,把选区(含图 / 内联 SVG / MathML)交给当前会话,回答在书页旁流出来。 -PDF / EPUB / Markdown / TXT 都在会话主区域打开;核心是**概念卡**——划词解释后自动沉淀成一张留在原文旁边的卡片,记录定义、语境、例子和出处,跨书、跨论文复用「本书用法」。 +PDF / EPUB / Word(.docx)/ Markdown / TXT 都在会话主区域打开;核心是**概念卡**——划词解释后自动沉淀成一张留在原文旁边的卡片,记录定义、语境、例子和出处,跨书、跨论文复用「本书用法」。 ![划词 → 解释 → 概念卡原地浮出](https://raw.githubusercontent.com/2019wakeup/dsh-reader/main/dsh-reader/docs/demos/01-select-explain.gif) @@ -32,7 +32,7 @@ PDF / EPUB / Markdown / TXT 都在会话主区域打开;核心是**概念卡** 1. 下载安装 [DeepSeek 官方桌面端](https://www.deepseek.com/download/),登录 DeepSeek 账号; 2. 侧栏 → **插件** → **添加插件**,输入 `@2019wakeup/dsh-reader@latest`,装好后在插件详情打开「启用」,重启桌面端。 -> `@latest` 现在就是 0.14.0;如果习惯插件市场索引、或想固定版本,也可以按下面的步骤安装和更新。 +> `@latest` 现在就是 0.15.0;如果习惯插件市场索引、或想固定版本,也可以按下面的步骤安装和更新。 ### 也可以从插件市场索引安装 @@ -43,6 +43,10 @@ PDF / EPUB / Markdown / TXT 都在会话主区域打开;核心是**概念卡** ``` 3. 在发现页找到「砚读 · DSH 阅读插件」安装;以后有新版本会直接显示更新按钮。 +### Windows 桌面端 + +Windows 10/11(x64)使用同一套桌面端与安装步骤;插件与阅读数据位于 `%USERPROFILE%\.dsh\profiles\desktop`,工作区数据仍在 `.dsh-reader/`。文件编码、路径分隔符、文件占用与快捷键已按 Windows 处理;不支持 `.doc` 旧格式,请先另存为 `.docx`。 + ### 开发者:命令行 ```bash @@ -75,10 +79,10 @@ dsh plugin --profile web add ./dsh-reader - 追问:卡内就概念继续提问,可带相关概念上下文;同概念跨书复用时追加「本书用法」。 - 悬停:已收录概念在正文中显示虚线,停留 150ms 浮出卡片,不遮挡当前行。 - 导读(长书,可选「快速(篇级)」/「标准(段+篇)」成本档位):PDF 读真实书签、按章分块、段→篇→全书两层归约;显示阶段进度、可停止;思维导图为「书→篇→节」;增量缓存;导出 PNG/SVG/MD。 -- 目录:PDF 优先真实书签(缩进/页码/当前页高亮),无书签时按 20 页分组;EPUB/Markdown 按章节/标题。 +- 目录:PDF 优先真实书签(缩进/页码/当前页高亮),无书签时按 20 页分组;EPUB/Word/Markdown 按章节/标题。 - 概念抽屉默认按当前书过滤,可切「全部」。 -- 搜索:⌘F 全文搜索(Markdown/EPUB 定位原文,PDF 逐页提取跳页)。 -- 翻译:Markdown/EPUB 三态「关 / 段落对照 / 仅译文」;PDF 右侧译文抽屉按页对照;划词可即时翻译;可选中文/英文/日文,按段缓存不重复计费。 +- 搜索:⌘F 全文搜索(Markdown/EPUB/Word 定位原文,Word 跨章;PDF 逐页提取跳页)。 +- 翻译:Markdown/EPUB/Word 三态「关 / 段落对照 / 仅译文」;PDF 右侧译文抽屉按页对照;划词可即时翻译;可选中文/英文/日文,按段缓存不重复计费。Word 表格单元格不参与段落对照,避免译文撑破列宽。 - 阅读:浅色/深色/米黄主题、PDF 双页、方向键或 J/K 翻页;设置重启保留。 - 数据:JSON 导出/导入、标注 Markdown 导出、最近 5 份备份一键恢复;最近 10 次发送内容可在设置查看。 - 概念:支持合并(别名/出现位置随目标保留);原文改动后按路径发现旧标注并一键迁移。 @@ -117,13 +121,13 @@ dsh plugin --profile web add ./dsh-reader ## 开发 ```bash -node --test test/*.test.mjs # 单元与冒烟测试(401 条) +node --test test/*.test.mjs # 单元与冒烟测试(429 条) node eval/run.mjs # 产品级 eval(18 项) node eval/visual.mjs # 视觉 eval(无头 Chrome,163 项检查 + 22 张像素基线) node eval/motion.mjs # 动效 eval(无头 Chrome,16 项) node eval/layout-host.mjs # 宿主布局探针(6 项) node scripts/build-client.mjs # 由 src/client/*.js 生成 client.js -node scripts/release-check.mjs # 发布门禁(12 项) +node scripts/release-check.mjs # 发布门禁(13 项) (cd demo && npm run render) # 重新生成 README 演示 GIF(Remotion,见 demo/README.md) ``` @@ -133,6 +137,8 @@ node scripts/release-check.mjs # 发布门禁(12 项) - 扫描版 PDF(无文本层)不能标注。 - 固定版式 EPUB(FXL)不支持。 +- `.doc` 旧格式、`.rtf`、`.wps` 不支持;Word 不还原分页、页眉页脚、分栏、文本框与页码。 +- Windows 上不支持 `.doc` 文件关联与右键打开;请从书库或拖拽进入。 - 段落对照翻译、概念图谱、移动端尚未包含(见 1.0 PRD 决策)。 - 解释/导读/追问需要 DSH 已配置可用模型。 - 解释请求有 90 秒上限:模型迟迟不返回时会被中止并在卡片上显示超时(重试按钮可直接再试)。慢的渠道可以用环境变量 `DSH_READER_EXPLAIN_TIMEOUT_MS` 调高;失败原因会写进 `.dsh-reader/store.json` 的 `debug.lastError`。 diff --git a/dsh-reader/assets/LICENSE-MAMMOTH b/dsh-reader/assets/LICENSE-MAMMOTH new file mode 100644 index 0000000..7e70661 --- /dev/null +++ b/dsh-reader/assets/LICENSE-MAMMOTH @@ -0,0 +1,22 @@ +Copyright (c) 2013, Michael Williamson +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/dsh-reader/assets/mammoth.browser.min.js b/dsh-reader/assets/mammoth.browser.min.js new file mode 100644 index 0000000..650e8a6 --- /dev/null +++ b/dsh-reader/assets/mammoth.browser.min.js @@ -0,0 +1,13 @@ +!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;g="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,g.mammoth=f()}}(function(){var define;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o0&&(childrenXml=deletedParagraphContents.concat(childrenXml),deletedParagraphContents=[]),ReadResult.map(readParagraphProperties(paragraphPropertiesElement),readXmlElements(childrenXml),function(properties,children){return new documents.Paragraph(children,properties)}).insertExtra()},"w:r":function(element){return ReadResult.map(readRunProperties(element.firstOrEmpty("w:rPr")),readXmlElements(element.children),function(properties,children){var hyperlinkOptions=currentHyperlinkOptions();return null!==hyperlinkOptions&&(children=[new documents.Hyperlink(children,hyperlinkOptions)]),new documents.Run(children,properties)})},"w:fldChar":readFldChar,"w:instrText":readInstrText,"w:t":function(element){return elementResult(new documents.Text(element.text()))},"w:tab":function(element){return elementResult(new documents.Tab)},"w:noBreakHyphen":function(){return elementResult(new documents.Text("‑"))},"w:softHyphen":function(element){return elementResult(new documents.Text("­"))},"w:sym":readSymbol,"w:hyperlink":function(element){var relationshipId=element.attributes["r:id"],anchor=element.attributes["w:anchor"];return readXmlElements(element.children).map(function(children){function create(options){var targetFrame=element.attributes["w:tgtFrame"]||null;return new documents.Hyperlink(children,_.extend({targetFrame:targetFrame},options))}if(relationshipId){var href=relationships.findTargetByRelationshipId(relationshipId);return anchor&&(href=uris.replaceFragment(href,anchor)),create({href:href})}return anchor?create({anchor:anchor}):children})},"w:tbl":readTable,"w:tr":readTableRow,"w:tc":readTableCell,"w:footnoteReference":noteReferenceReader("footnote"),"w:endnoteReference":noteReferenceReader("endnote"),"w:commentReference":readCommentReference,"w:br":function(element){var breakType=element.attributes["w:type"];return null==breakType||"textWrapping"===breakType?elementResult(documents.lineBreak):"page"===breakType?elementResult(documents.pageBreak):"column"===breakType?elementResult(documents.columnBreak):emptyResultWithMessages([warning("Unsupported break type: "+breakType)])},"w:bookmarkStart":function(element){var name=element.attributes["w:name"];return"_GoBack"===name?emptyResult():elementResult(new documents.BookmarkStart({name:name}))},"mc:AlternateContent":function(element){return readChildElements(element.firstOrEmpty("mc:Fallback"))},"w:sdt":function(element){var contentResult=readXmlElements(element.firstOrEmpty("w:sdtContent").children);return contentResult.map(function(content){var checkbox=element.firstOrEmpty("w:sdtPr").first("wordml:checkbox");if(checkbox){var checkedElement=checkbox.first("wordml:checked"),isChecked=!!checkedElement&&readBooleanAttributeValue(checkedElement.attributes["wordml:val"]),documentCheckbox=documents.checkbox({checked:isChecked}),hasCheckbox=!1,replacedContent=content.map(transforms._elementsOfType(documents.types.text,function(text){return text.value.length>0&&!hasCheckbox?(hasCheckbox=!0,documentCheckbox):text}));return hasCheckbox?replacedContent:documentCheckbox}return content})},"w:customXml":readChildElements,"w:ins":readChildElements,"w:moveFromRangeEnd":readChildElements,"w:moveFromRangeStart":readChildElements,"w:moveTo":readChildElements,"w:moveToRangeEnd":readChildElements,"w:moveToRangeStart":readChildElements,"w:object":readChildElements,"w:smartTag":readChildElements,"w:drawing":readChildElements,"w:pict":function(element){return readChildElements(element).toExtra()},"v:roundrect":readChildElements,"v:shape":readChildElements,"v:textbox":readChildElements,"w:txbxContent":readChildElements,"wp:inline":readDrawingElement,"wp:anchor":readDrawingElement, +"v:imagedata":readImageData,"v:group":readChildElements,"v:rect":readChildElements};return{readXmlElement:readXmlElement,readXmlElements:readXmlElements}}function readNumberingProperties(styleId,element,numbering){var level=element.firstOrEmpty("w:ilvl").attributes["w:val"],numId=element.firstOrEmpty("w:numId").attributes["w:val"];if(void 0!==level&&void 0!==numId)return numbering.findLevel(numId,level);if(null!=styleId){var levelByStyleId=numbering.findLevelByParagraphStyleId(styleId);if(null!=levelByStyleId)return levelByStyleId}return void 0!==numId?numbering.findLevel(numId,"0"):null}function emptyResultWithMessages(messages){return new ReadResult(null,null,messages)}function emptyResult(){return new ReadResult(null)}function elementResult(element){return new ReadResult(element)}function elementResultWithMessages(element,messages){return new ReadResult(element,null,messages)}function ReadResult(element,extra,messages){this.value=element||[],this.extra=extra||[],this._result=new Result({element:this.value,extra:extra},messages),this.messages=this._result.messages}function combineResults(results){var result=Result.combine(_.pluck(results,"_result"));return new ReadResult(_.flatten(_.pluck(result.value,"element")),_.filter(_.flatten(_.pluck(result.value,"extra")),identity),result.messages)}function joinElements(first,second){return _.flatten([first,second])}function identity(value){return value}exports.createBodyReader=createBodyReader,exports._readNumberingProperties=readNumberingProperties;var dingbatToUnicode=require("dingbat-to-unicode"),_=require("underscore"),documents=require("../documents"),Result=require("../results").Result,warning=require("../results").warning,xml=require("../xml"),transforms=require("../transforms"),uris=require("./uris"),supportedImageTypes={"image/png":!0,"image/gif":!0,"image/jpeg":!0,"image/svg+xml":!0,"image/tiff":!0},ignoreElements={"office-word:wrap":!0,"v:shadow":!0,"v:shapetype":!0,"w:annotationRef":!0,"w:bookmarkEnd":!0,"w:sectPr":!0,"w:proofErr":!0,"w:lastRenderedPageBreak":!0,"w:commentRangeStart":!0,"w:commentRangeEnd":!0,"w:del":!0,"w:footnoteRef":!0,"w:endnoteRef":!0,"w:moveFrom":!0,"w:pPr":!0,"w:rPr":!0,"w:tblPr":!0,"w:tblGrid":!0,"w:trPr":!0,"w:tcPr":!0};ReadResult.prototype.toExtra=function(){return new ReadResult(null,joinElements(this.extra,this.value),this.messages)},ReadResult.prototype.insertExtra=function(){var extra=this.extra;return extra&&extra.length?new ReadResult(joinElements(this.value,extra),null,this.messages):this},ReadResult.prototype.map=function(func){var result=this._result.map(function(value){return func(value.element)});return new ReadResult(result.value,this.extra,result.messages)},ReadResult.prototype.flatMap=function(func){var result=this._result.flatMap(function(value){return func(value.element)._result});return new ReadResult(result.value.element,joinElements(this.extra,result.value.extra),result.messages)},ReadResult.map=function(first,second,func){return new ReadResult(func(first.value,second.value),joinElements(first.extra,second.extra),first.messages.concat(second.messages))}},{"../documents":4,"../results":25,"../transforms":30,"../xml":35,"./uris":16,"dingbat-to-unicode":50,underscore:67}],6:[function(require,module,exports){function createCommentsReader(bodyReader){function readCommentsXml(element){return Result.combine(element.getElementsByTagName("w:comment").map(readCommentElement))}function readCommentElement(element){function readOptionalAttribute(name){return(element.attributes[name]||"").trim()||null}var id=element.attributes["w:id"];return bodyReader.readXmlElements(element.children).map(function(body){return documents.comment({commentId:id,body:body,authorName:readOptionalAttribute("w:author"),authorInitials:readOptionalAttribute("w:initials")})})}return readCommentsXml}var documents=require("../documents"),Result=require("../results").Result;exports.createCommentsReader=createCommentsReader},{"../documents":4,"../results":25}],7:[function(require,module,exports){function readContentTypesFromXml(element){var extensionDefaults=Object.create(null),overrides=Object.create(null);return element.children.forEach(function(child){if("content-types:Default"===child.name&&(extensionDefaults[child.attributes.Extension]=child.attributes.ContentType),"content-types:Override"===child.name){var name=child.attributes.PartName;"/"===name.charAt(0)&&(name=name.substring(1)),overrides[name]=child.attributes.ContentType}}),contentTypes(overrides,extensionDefaults)}function contentTypes(overrides,extensionDefaults){return{findContentType:function(path){var overrideContentType=overrides[path];if(overrideContentType)return overrideContentType;var pathParts=path.split("."),extension=pathParts[pathParts.length-1];if(Object.prototype.hasOwnProperty.call(extensionDefaults,extension))return extensionDefaults[extension];var fallback=fallbackContentTypes[extension.toLowerCase()];return fallback?"image/"+fallback:null}}}exports.readContentTypesFromXml=readContentTypesFromXml;var fallbackContentTypes={png:"png",gif:"gif",jpeg:"jpeg",jpg:"jpeg",tif:"tiff",tiff:"tiff",bmp:"bmp"};exports.defaultContentTypes=contentTypes({},{})},{}],8:[function(require,module,exports){function DocumentXmlReader(options){function convertXmlToDocument(element){var body=element.first("w:body");if(null==body)throw new Error("Could not find the body element: are you sure this is a docx file?");var result=bodyReader.readXmlElements(body.children).map(function(children){return new documents.Document(children,{notes:options.notes,comments:options.comments})});return new Result(result.value,result.messages)}var bodyReader=options.bodyReader;return{convertXmlToDocument:convertXmlToDocument}}exports.DocumentXmlReader=DocumentXmlReader;var documents=require("../documents"),Result=require("../results").Result},{"../documents":4,"../results":25}],9:[function(require,module,exports){function read(docxFile,input,options){input=input||{},options=options||{};var files=new Files({externalFileAccess:options.externalFileAccess,relativeToFile:input.path});return promises.props({contentTypes:readContentTypesFromZipFile(docxFile),partPaths:findPartPaths(docxFile),docxFile:docxFile,files:files}).also(function(result){return{styles:readStylesFromZipFile(docxFile,result.partPaths.styles)}}).also(function(result){return{numbering:readNumberingFromZipFile(docxFile,result.partPaths.numbering,result.styles)}}).also(function(result){return{footnotes:readXmlFileWithBody(result.partPaths.footnotes,result,function(bodyReader,xml){return xml?notesReader.createFootnotesReader(bodyReader)(xml):new Result([])}),endnotes:readXmlFileWithBody(result.partPaths.endnotes,result,function(bodyReader,xml){return xml?notesReader.createEndnotesReader(bodyReader)(xml):new Result([])}),comments:readXmlFileWithBody(result.partPaths.comments,result,function(bodyReader,xml){return xml?commentsReader.createCommentsReader(bodyReader)(xml):new Result([])})}}).also(function(result){return{notes:result.footnotes.flatMap(function(footnotes){return result.endnotes.map(function(endnotes){return new documents.Notes(footnotes.concat(endnotes))})})}}).then(function(result){return readXmlFileWithBody(result.partPaths.mainDocument,result,function(bodyReader,xml){return result.notes.flatMap(function(notes){return result.comments.flatMap(function(comments){var reader=new DocumentXmlReader({bodyReader:bodyReader,notes:notes,comments:comments});return reader.convertXmlToDocument(xml)})})})})}function findPartPaths(docxFile){return readPackageRelationships(docxFile).then(function(packageRelationships){var mainDocumentPath=findPartPath({docxFile:docxFile,relationships:packageRelationships,relationshipType:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",basePath:"",fallbackPath:"word/document.xml"});if(!docxFile.exists(mainDocumentPath))throw new Error("Could not find main document part. Are you sure this is a valid .docx file?");return xmlFileReader({filename:relationshipsFilename(mainDocumentPath),readElement:relationshipsReader.readRelationships,defaultValue:relationshipsReader.defaultValue})(docxFile).then(function(documentRelationships){function findPartRelatedToMainDocument(name){return findPartPath({docxFile:docxFile,relationships:documentRelationships,relationshipType:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/"+name,basePath:zipfile.splitPath(mainDocumentPath).dirname,fallbackPath:"word/"+name+".xml"})}return{mainDocument:mainDocumentPath,comments:findPartRelatedToMainDocument("comments"),endnotes:findPartRelatedToMainDocument("endnotes"),footnotes:findPartRelatedToMainDocument("footnotes"),numbering:findPartRelatedToMainDocument("numbering"),styles:findPartRelatedToMainDocument("styles")}})})}function findPartPath(options){var docxFile=options.docxFile,relationships=options.relationships,relationshipType=options.relationshipType,basePath=options.basePath,fallbackPath=options.fallbackPath,targets=relationships.findTargetsByType(relationshipType),normalisedTargets=targets.map(function(target){return stripPrefix(zipfile.joinPath(basePath,target),"/")}),validTargets=normalisedTargets.filter(function(target){return docxFile.exists(target)});return 0===validTargets.length?fallbackPath:validTargets[0]}function stripPrefix(value,prefix){return value.substring(0,prefix.length)===prefix?value.substring(prefix.length):value}function xmlFileReader(options){return function(zipFile){return readXmlFromZipFile(zipFile,options.filename).then(function(element){return element?options.readElement(element):options.defaultValue})}}function readXmlFileWithBody(filename,options,func){var readRelationshipsFromZipFile=xmlFileReader({filename:relationshipsFilename(filename),readElement:relationshipsReader.readRelationships,defaultValue:relationshipsReader.defaultValue});return readRelationshipsFromZipFile(options.docxFile).then(function(relationships){var bodyReader=new createBodyReader({relationships:relationships,contentTypes:options.contentTypes,docxFile:options.docxFile,numbering:options.numbering,styles:options.styles,files:options.files});return readXmlFromZipFile(options.docxFile,filename).then(function(xml){return func(bodyReader,xml)})})}function relationshipsFilename(filename){var split=zipfile.splitPath(filename);return zipfile.joinPath(split.dirname,"_rels",split.basename+".rels")}function readNumberingFromZipFile(zipFile,path,styles){return xmlFileReader({filename:path,readElement:function(element){return numberingXml.readNumberingXml(element,{styles:styles})},defaultValue:numberingXml.defaultNumbering})(zipFile)}function readStylesFromZipFile(zipFile,path){return xmlFileReader({filename:path,readElement:stylesReader.readStylesXml,defaultValue:stylesReader.defaultStyles})(zipFile)}exports.read=read,exports._findPartPaths=findPartPaths;var promises=require("../promises"),documents=require("../documents"),Result=require("../results").Result,zipfile=require("../zipfile"),readXmlFromZipFile=require("./office-xml-reader").readXmlFromZipFile,createBodyReader=require("./body-reader").createBodyReader,DocumentXmlReader=require("./document-xml-reader").DocumentXmlReader,relationshipsReader=require("./relationships-reader"),contentTypesReader=require("./content-types-reader"),numberingXml=require("./numbering-xml"),stylesReader=require("./styles-reader"),notesReader=require("./notes-reader"),commentsReader=require("./comments-reader"),Files=require("./files").Files,readContentTypesFromZipFile=xmlFileReader({filename:"[Content_Types].xml",readElement:contentTypesReader.readContentTypesFromXml,defaultValue:contentTypesReader.defaultContentTypes}),readPackageRelationships=xmlFileReader({filename:"_rels/.rels",readElement:relationshipsReader.readRelationships,defaultValue:relationshipsReader.defaultValue})},{"../documents":4,"../promises":23,"../results":25,"../zipfile":40,"./body-reader":5,"./comments-reader":6,"./content-types-reader":7,"./document-xml-reader":8,"./files":1,"./notes-reader":10,"./numbering-xml":11,"./office-xml-reader":12,"./relationships-reader":13,"./styles-reader":15}],10:[function(require,module,exports){function createReader(noteType,bodyReader){function readNotesXml(element){return Result.combine(element.getElementsByTagName("w:"+noteType).filter(isFootnoteElement).map(readFootnoteElement))}function isFootnoteElement(element){var type=element.attributes["w:type"];return"continuationSeparator"!==type&&"separator"!==type}function readFootnoteElement(footnoteElement){var id=footnoteElement.attributes["w:id"];return bodyReader.readXmlElements(footnoteElement.children).map(function(body){return documents.Note({noteType:noteType,noteId:id,body:body})})}return readNotesXml}var documents=require("../documents"),Result=require("../results").Result;exports.createFootnotesReader=createReader.bind(this,"footnote"),exports.createEndnotesReader=createReader.bind(this,"endnote")},{"../documents":4,"../results":25}],11:[function(require,module,exports){function Numbering(nums,abstractNums,styles){function findLevel(numId,level){return findLevelWithSeenNumIds(numId,level,Object.create(null))}function findLevelWithSeenNumIds(numId,level,seenNumIds){if(seenNumIds[numId])return null;seenNumIds[numId]=!0;var num=nums[numId];if(!num)return null;var abstractNum=abstractNums[num.abstractNumId];if(abstractNum){if(null==abstractNum.numStyleLink)return abstractNums[num.abstractNumId].levels[level];var style=styles.findNumberingStyleById(abstractNum.numStyleLink);return findLevelWithSeenNumIds(style.numId,level,seenNumIds)}return null}function findLevelByParagraphStyleId(styleId){return levelsByParagraphStyleId[styleId]||null}var allLevels=_.flatten(_.values(abstractNums).map(function(abstractNum){return _.values(abstractNum.levels)})),levelsByParagraphStyleId=_.indexBy(allLevels.filter(function(level){return null!=level.paragraphStyleId}),"paragraphStyleId");return{findLevel:findLevel,findLevelByParagraphStyleId:findLevelByParagraphStyleId}}function readNumberingXml(root,options){if(!options||!options.styles)throw new Error("styles is missing");var abstractNums=readAbstractNums(root),nums=readNums(root,abstractNums);return new Numbering(nums,abstractNums,options.styles)}function readAbstractNums(root){var abstractNums=Object.create(null);return root.getElementsByTagName("w:abstractNum").forEach(function(element){var id=element.attributes["w:abstractNumId"];abstractNums[id]=readAbstractNum(element)}),abstractNums}function readAbstractNum(element){var levels=Object.create(null),levelWithoutIndex=null;element.getElementsByTagName("w:lvl").forEach(function(levelElement){var levelIndex=levelElement.attributes["w:ilvl"],numFmt=levelElement.firstOrEmpty("w:numFmt").attributes["w:val"],isOrdered="bullet"!==numFmt,paragraphStyleId=levelElement.firstOrEmpty("w:pStyle").attributes["w:val"];void 0===levelIndex?levelWithoutIndex={isOrdered:isOrdered,level:"0",paragraphStyleId:paragraphStyleId}:levels[levelIndex]={isOrdered:isOrdered,level:levelIndex,paragraphStyleId:paragraphStyleId}}),null!==levelWithoutIndex&&void 0===levels[levelWithoutIndex.level]&&(levels[levelWithoutIndex.level]=levelWithoutIndex);var numStyleLink=element.firstOrEmpty("w:numStyleLink").attributes["w:val"];return{levels:levels,numStyleLink:numStyleLink}}function readNums(root){var nums=Object.create(null);return root.getElementsByTagName("w:num").forEach(function(element){var numId=element.attributes["w:numId"],abstractNumId=element.first("w:abstractNumId").attributes["w:val"];nums[numId]={abstractNumId:abstractNumId}}),nums}var _=require("underscore");exports.readNumberingXml=readNumberingXml,exports.Numbering=Numbering,exports.defaultNumbering=new Numbering({},{})},{underscore:67}],12:[function(require,module,exports){function read(xmlString){return xml.readString(xmlString,xmlNamespaceMap).then(function(document){return collapseAlternateContent(document)[0]})}function readXmlFromZipFile(docxFile,path){return docxFile.exists(path)?docxFile.read(path,"utf-8").then(stripUtf8Bom).then(read):promises.resolve(null)}function stripUtf8Bom(xmlString){return xmlString.replace(/^\uFEFF/g,"")}function collapseAlternateContent(node){return"element"===node.type?"mc:AlternateContent"===node.name?node.firstOrEmpty("mc:Fallback").children:(node.children=_.flatten(node.children.map(collapseAlternateContent,!0)),[node]):[node]}var _=require("underscore"),promises=require("../promises"),xml=require("../xml");exports.read=read,exports.readXmlFromZipFile=readXmlFromZipFile;var xmlNamespaceMap={"http://schemas.openxmlformats.org/wordprocessingml/2006/main":"w","http://schemas.openxmlformats.org/officeDocument/2006/relationships":"r","http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing":"wp","http://schemas.openxmlformats.org/drawingml/2006/main":"a","http://schemas.openxmlformats.org/drawingml/2006/picture":"pic","http://purl.oclc.org/ooxml/wordprocessingml/main":"w","http://purl.oclc.org/ooxml/officeDocument/relationships":"r","http://purl.oclc.org/ooxml/drawingml/wordprocessingDrawing":"wp","http://purl.oclc.org/ooxml/drawingml/main":"a","http://purl.oclc.org/ooxml/drawingml/picture":"pic","http://schemas.openxmlformats.org/package/2006/content-types":"content-types","http://schemas.openxmlformats.org/package/2006/relationships":"relationships","http://schemas.openxmlformats.org/markup-compatibility/2006":"mc","urn:schemas-microsoft-com:vml":"v","urn:schemas-microsoft-com:office:word":"office-word","http://schemas.microsoft.com/office/word/2010/wordml":"wordml"}},{"../promises":23,"../xml":35,underscore:67}],13:[function(require,module,exports){function readRelationships(element){var relationships=[];return element.children.forEach(function(child){if("relationships:Relationship"===child.name){var relationship={relationshipId:child.attributes.Id,target:child.attributes.Target,type:child.attributes.Type};relationships.push(relationship)}}),new Relationships(relationships)}function Relationships(relationships){var targetsByRelationshipId=Object.create(null);relationships.forEach(function(relationship){targetsByRelationshipId[relationship.relationshipId]=relationship.target});var targetsByType=Object.create(null);return relationships.forEach(function(relationship){targetsByType[relationship.type]||(targetsByType[relationship.type]=[]),targetsByType[relationship.type].push(relationship.target)}),{findTargetByRelationshipId:function(relationshipId){return targetsByRelationshipId[relationshipId]},findTargetsByType:function(type){return targetsByType[type]||[]}}}exports.readRelationships=readRelationships,exports.defaultValue=new Relationships([]),exports.Relationships=Relationships},{}],14:[function(require,module,exports){function writeStyleMap(docxFile,styleMap){return docxFile.write(styleMapPath,styleMap),updateRelationships(docxFile).then(function(){return updateContentTypes(docxFile)})}function updateRelationships(docxFile){var path="word/_rels/document.xml.rels",relationshipsUri="http://schemas.openxmlformats.org/package/2006/relationships",relationshipElementName="{"+relationshipsUri+"}Relationship";return docxFile.read(path,"utf8").then(xml.readString).then(function(relationshipsContainer){var relationships=relationshipsContainer.children;addOrUpdateElement(relationships,relationshipElementName,"Id",{Id:"rMammothStyleMap",Type:schema,Target:styleMapAbsolutePath});var namespaces={"":relationshipsUri};return docxFile.write(path,xml.writeString(relationshipsContainer,namespaces))})}function updateContentTypes(docxFile){var path="[Content_Types].xml",contentTypesUri="http://schemas.openxmlformats.org/package/2006/content-types",overrideName="{"+contentTypesUri+"}Override";return docxFile.read(path,"utf8").then(xml.readString).then(function(typesElement){var children=typesElement.children;addOrUpdateElement(children,overrideName,"PartName",{PartName:styleMapAbsolutePath,ContentType:"text/prs.mammoth.style-map"});var namespaces={"":contentTypesUri};return docxFile.write(path,xml.writeString(typesElement,namespaces))})}function addOrUpdateElement(elements,name,identifyingAttribute,attributes){var existingElement=_.find(elements,function(element){return element.name===name&&element.attributes[identifyingAttribute]===attributes[identifyingAttribute]});existingElement?existingElement.attributes=attributes:elements.push(xml.element(name,attributes))}function readStyleMap(docxFile){return docxFile.exists(styleMapPath)?docxFile.read(styleMapPath,"utf8"):promises.resolve(null)}var _=require("underscore"),promises=require("../promises"),xml=require("../xml");exports.writeStyleMap=writeStyleMap,exports.readStyleMap=readStyleMap;var schema="http://schemas.zwobble.org/mammoth/style-map",styleMapPath="mammoth/style-map",styleMapAbsolutePath="/"+styleMapPath},{"../promises":23,"../xml":35,underscore:67}],15:[function(require,module,exports){function Styles(paragraphStyles,characterStyles,tableStyles,numberingStyles){return{findParagraphStyleById:function(styleId){return paragraphStyles[styleId]},findCharacterStyleById:function(styleId){return characterStyles[styleId]},findTableStyleById:function(styleId){return tableStyles[styleId]},findNumberingStyleById:function(styleId){return numberingStyles[styleId]}}}function readStylesXml(root){var paragraphStyles=Object.create(null),characterStyles=Object.create(null),tableStyles=Object.create(null),numberingStyles=Object.create(null);return root.getElementsByTagName("w:style").forEach(function(styleElement){var styleSet,style=readStyleElement(styleElement);switch(style.type){case"paragraph":styleSet=paragraphStyles;break;case"character":styleSet=characterStyles;break;case"table":styleSet=tableStyles;break;case"numbering":styleSet=numberingStyles}styleSet&&void 0===styleSet[style.styleId]&&(styleSet[style.styleId]=style)}),new Styles(paragraphStyles,characterStyles,tableStyles,numberingStyles)}function readStyleElement(styleElement){var type=styleElement.attributes["w:type"];if("numbering"===type)return readNumberingStyleElement(type,styleElement);var styleId=readStyleId(styleElement),name=styleName(styleElement);return{type:type,styleId:styleId,name:name}}function styleName(styleElement){var nameElement=styleElement.first("w:name");return nameElement?nameElement.attributes["w:val"]:null}function readNumberingStyleElement(type,styleElement){var styleId=readStyleId(styleElement),numId=styleElement.firstOrEmpty("w:pPr").firstOrEmpty("w:numPr").firstOrEmpty("w:numId").attributes["w:val"];return{type:type,numId:numId,styleId:styleId}}function readStyleId(styleElement){return styleElement.attributes["w:styleId"]}exports.readStylesXml=readStylesXml,exports.Styles=Styles,exports.defaultStyles=new Styles({},{}),Styles.EMPTY=new Styles({},{},{},{})},{}],16:[function(require,module,exports){function uriToZipEntryName(base,uri){return"/"===uri.charAt(0)?uri.substr(1):base+"/"+uri}function replaceFragment(uri,fragment){var hashIndex=uri.indexOf("#");return-1!==hashIndex&&(uri=uri.substring(0,hashIndex)),uri+"#"+fragment}exports.uriToZipEntryName=uriToZipEntryName,exports.replaceFragment=replaceFragment},{}],17:[function(require,module,exports){function nonFreshElement(tagName,attributes,children){return elementWithTag(htmlPaths.element(tagName,attributes,{fresh:!1}),children)}function freshElement(tagName,attributes,children){var tag=htmlPaths.element(tagName,attributes,{fresh:!0});return elementWithTag(tag,children)}function elementWithTag(tag,children){return{type:"element",tag:tag,children:children||[]}}function text(value){return{type:"text",value:value}}function isVoidElement(node){return 0===node.children.length&&voidTagNames[node.tag.tagName]}var htmlPaths=require("../styles/html-paths"),forceWrite={type:"forceWrite"};exports.freshElement=freshElement,exports.nonFreshElement=nonFreshElement,exports.elementWithTag=elementWithTag,exports.text=text,exports.forceWrite=forceWrite;var voidTagNames={br:!0,hr:!0,img:!0,input:!0};exports.isVoidElement=isVoidElement},{"../styles/html-paths":28}],18:[function(require,module,exports){function write(writer,nodes){nodes.forEach(function(node){writeNode(writer,node)})}function writeNode(writer,node){toStrings[node.type](writer,node)}function generateElementString(writer,node){ast.isVoidElement(node)?writer.selfClosing(node.tag.tagName,node.tag.attributes):(writer.open(node.tag.tagName,node.tag.attributes),write(writer,node.children),writer.close(node.tag.tagName))}function generateTextString(writer,node){writer.text(node.value)}var ast=require("./ast");exports.freshElement=ast.freshElement,exports.nonFreshElement=ast.nonFreshElement,exports.elementWithTag=ast.elementWithTag,exports.text=ast.text,exports.forceWrite=ast.forceWrite,exports.simplify=require("./simplify");var toStrings={element:generateElementString,text:generateTextString,forceWrite:function(){}};exports.write=write},{"./ast":17,"./simplify":19}],19:[function(require,module,exports){function simplify(nodes){return collapse(removeEmpty(nodes))}function collapse(nodes){var children=[];return nodes.map(collapseNode).forEach(function(child){appendChild(children,child)}),children}function collapseNode(node){return collapsers[node.type](node)}function collapseElement(node){return ast.elementWithTag(node.tag,collapse(node.children))}function identity(value){return value}function appendChild(children,child){var lastChild=children[children.length-1];"element"===child.type&&!child.tag.fresh&&lastChild&&"element"===lastChild.type&&child.tag.matchesElement(lastChild.tag)?(child.tag.separator&&appendChild(lastChild.children,ast.text(child.tag.separator)),child.children.forEach(function(grandChild){appendChild(lastChild.children,grandChild)})):children.push(child)}function removeEmpty(nodes){return flatMap(nodes,function(node){return emptiers[node.type](node)})}function flatMap(values,func){return _.flatten(_.map(values,func),!0)}function neverEmpty(node){return[node]}function elementEmptier(element){var children=removeEmpty(element.children);return 0!==children.length||ast.isVoidElement(element)?[ast.elementWithTag(element.tag,children)]:[]}function textEmptier(node){return 0===node.value.length?[]:[node]}var _=require("underscore"),ast=require("./ast"),collapsers={element:collapseElement,text:identity,forceWrite:identity},emptiers={element:elementEmptier,text:textEmptier,forceWrite:neverEmpty};module.exports=simplify},{"./ast":17,underscore:67}],20:[function(require,module,exports){function imgElement(func){return function(element,messages){return promises.resolve(func(element)).then(function(result){var attributes={};return element.altText&&(attributes.alt=element.altText),_.extend(attributes,result),[Html.freshElement("img",attributes)]})}}function imageFilenameExtension(image){return image.contentType.split(/\/|\\/)[1]}var _=require("underscore"),promises=require("./promises"),Html=require("./html");exports.imgElement=imgElement,exports.inline=exports.imgElement,exports.dataUri=imgElement(function(element){return element.readAsBase64String().then(function(imageBuffer){return{src:"data:"+element.contentType+";base64,"+imageBuffer}})}),exports.imageFilenameExtension=imageFilenameExtension},{"./html":18,"./promises":23,underscore:67}],21:[function(require,module,exports){(function(Buffer){function convertToHtml(input,options){return convert(input,options)}function convertToMarkdown(input,options){var markdownOptions=Object.create(options||{});return markdownOptions.outputFormat="markdown",convert(input,markdownOptions)}function convert(input,options){options=readOptions(options);var result=unzip.openZip(input).then(function(docxFile){return docxStyleMap.readStyleMap(docxFile).then(function(styleMap){return options.embeddedStyleMap=styleMap,docxFile})}).then(function(docxFile){return docxReader.read(docxFile,input,options).then(function(documentResult){return documentResult.map(options.transformDocument)}).then(function(documentResult){return convertDocumentToHtml(documentResult,options)})});return promises.toExternalPromise(result)}function readEmbeddedStyleMap(input){var result=unzip.openZip(input).then(docxStyleMap.readStyleMap);return promises.toExternalPromise(result)}function convertDocumentToHtml(documentResult,options){var styleMapResult=parseStyleMap(options.readStyleMap()),parsedOptions=_.extend({},options,{styleMap:styleMapResult.value}),documentConverter=new DocumentConverter(parsedOptions);return documentResult.flatMapThen(function(document){return styleMapResult.flatMapThen(function(styleMap){return documentConverter.convertToHtml(document)})})}function parseStyleMap(styleMap){return Result.combine((styleMap||[]).map(readStyle)).map(function(styleMap){return styleMap.filter(function(styleMapping){return!!styleMapping})})}function extractRawText(input){var result=unzip.openZip(input).then(docxReader.read).then(function(documentResult){return documentResult.map(convertElementToRawText)});return promises.toExternalPromise(result)}function embedStyleMap(input,styleMap){var result=unzip.openZip(input).then(function(docxFile){return docxStyleMap.writeStyleMap(docxFile,styleMap).then(function(){return docxFile})}).then(function(docxFile){return docxFile.toArrayBuffer()}).then(function(arrayBuffer){return{toArrayBuffer:function(){return arrayBuffer},toBuffer:function(){return Buffer.from(arrayBuffer)}}});return promises.toExternalPromise(result)}var _=require("underscore"),docxReader=require("./docx/docx-reader"),docxStyleMap=require("./docx/style-map"),DocumentConverter=require("./document-to-html").DocumentConverter,convertElementToRawText=require("./raw-text").convertElementToRawText,readStyle=require("./style-reader").readStyle,readOptions=require("./options-reader").readOptions,promises=require("./promises"),unzip=require("./unzip"),Result=require("./results").Result;exports.convertToHtml=convertToHtml,exports.convertToMarkdown=convertToMarkdown,exports.convert=convert,exports.extractRawText=extractRawText,exports.images=require("./images"),exports.transforms=require("./transforms"),exports.underline=require("./underline"),exports.embedStyleMap=embedStyleMap,exports.readEmbeddedStyleMap=readEmbeddedStyleMap,exports.styleMapping=function(){throw new Error("Use a raw string instead of mammoth.styleMapping e.g. \"p[style-name='Title'] => h1\" instead of mammoth.styleMapping(\"p[style-name='Title'] => h1\")")}}).call(this,require("buffer").Buffer)},{"./document-to-html":3,"./docx/docx-reader":9,"./docx/style-map":14,"./images":20,"./options-reader":22,"./promises":23,"./raw-text":24,"./results":25,"./style-reader":26,"./transforms":30,"./underline":31,"./unzip":2,buffer:48,underscore:67}],22:[function(require,module,exports){function readOptions(options){return options=options||{},_.extend({},standardOptions,options,{customStyleMap:readStyleMap(options.styleMap),readStyleMap:function(){var styleMap=this.customStyleMap;return this.includeEmbeddedStyleMap&&(styleMap=styleMap.concat(readStyleMap(this.embeddedStyleMap))),this.includeDefaultStyleMap&&(styleMap=styleMap.concat(defaultStyleMap)),styleMap}})}function readStyleMap(styleMap){return styleMap?_.isString(styleMap)?styleMap.split("\n").map(function(line){return line.trim()}).filter(function(line){return""!==line&&"#"!==line.charAt(0)}):styleMap:[]}function identity(value){return value}exports.readOptions=readOptions;var _=require("underscore"),defaultStyleMap=exports._defaultStyleMap=["p.Heading1 => h1:fresh","p.Heading2 => h2:fresh","p.Heading3 => h3:fresh","p.Heading4 => h4:fresh","p.Heading5 => h5:fresh","p.Heading6 => h6:fresh","p[style-name='Heading 1'] => h1:fresh","p[style-name='Heading 2'] => h2:fresh","p[style-name='Heading 3'] => h3:fresh","p[style-name='Heading 4'] => h4:fresh","p[style-name='Heading 5'] => h5:fresh","p[style-name='Heading 6'] => h6:fresh","p[style-name='heading 1'] => h1:fresh","p[style-name='heading 2'] => h2:fresh","p[style-name='heading 3'] => h3:fresh","p[style-name='heading 4'] => h4:fresh","p[style-name='heading 5'] => h5:fresh","p[style-name='heading 6'] => h6:fresh","p.Heading => h1:fresh","p[style-name='Heading'] => h1:fresh","r[style-name='Strong'] => strong","p[style-name='footnote text'] => p:fresh","r[style-name='footnote reference'] =>","p[style-name='endnote text'] => p:fresh","r[style-name='endnote reference'] =>","p[style-name='annotation text'] => p:fresh","r[style-name='annotation reference'] =>","p[style-name='Footnote'] => p:fresh","r[style-name='Footnote anchor'] =>","p[style-name='Endnote'] => p:fresh","r[style-name='Endnote anchor'] =>","p:unordered-list(1) => ul > li:fresh","p:unordered-list(2) => ul|ol > li > ul > li:fresh","p:unordered-list(3) => ul|ol > li > ul|ol > li > ul > li:fresh","p:unordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh","p:unordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh","p:ordered-list(1) => ol > li:fresh","p:ordered-list(2) => ul|ol > li > ol > li:fresh","p:ordered-list(3) => ul|ol > li > ul|ol > li > ol > li:fresh","p:ordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh","p:ordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh","r[style-name='Hyperlink'] =>","p[style-name='Normal'] => p:fresh","p.Body => p:fresh","p[style-name='Body'] => p:fresh"],standardOptions=exports._standardOptions={ +externalFileAccess:!1,transformDocument:identity,includeDefaultStyleMap:!0,includeEmbeddedStyleMap:!0}},{underscore:67}],23:[function(require,module,exports){(function(process){function addAlsoToPromise(promise){return promise.also=alsoMethod,promise}function defer(){var resolve,reject,promise=new Promise(function(resolveArg,rejectArg){resolve=resolveArg,reject=rejectArg});return{resolve:resolve,reject:reject,promise:promise}}function ExternalPromise(executor){var promise=new Promise(executor);return promise.__proto__=ExternalPromise.prototype,promise}function toExternalPromise(promise){return ExternalPromise.resolve(promise)}function isNode(){return"undefined"==typeof process?!1:"[object process]"==={}.toString.call(process).toLowerCase()}var _=require("underscore");exports.defer=defer,exports.Promise=Promise,exports.resolve=Promise.resolve.bind(Promise),exports.reject=Promise.reject.bind(Promise),exports.forEachSeries=function(array,func){var arrayIndex=0,deferred=defer(),next=function(){if(arrayIndex=0;index--)result=this._elements[index].wrapNodes(result);return result},Element.prototype.matchesElement=function(element){return this.tagNames[element.tagName]&&_.isEqual(this.attributes||{},element.attributes||{})},Element.prototype.wrap=function(generateNodes){return this.wrapNodes(generateNodes())},Element.prototype.wrapNodes=function(nodes){return[html.elementWithTag(this,nodes)]},exports.empty=elements([]),exports.ignore={wrap:function(){return[]}}},{"../html":18,underscore:67}],29:[function(require,module,exports){function tokenise(string){var identifierCharacter="(?:[a-zA-Z\\-_]|\\\\.)",tokeniser=new RegexTokeniser([{name:"identifier",regex:new RegExp("("+identifierCharacter+"(?:"+identifierCharacter+"|[0-9])*)")},{name:"dot",regex:/\./},{name:"colon",regex:/:/},{name:"gt",regex:/>/},{name:"whitespace",regex:/\s+/},{name:"arrow",regex:/=>/},{name:"equals",regex:/=/},{name:"startsWith",regex:/\^=/},{name:"open-paren",regex:/\(/},{name:"close-paren",regex:/\)/},{name:"open-square-bracket",regex:/\[/},{name:"close-square-bracket",regex:/\]/},{name:"string",regex:new RegExp(stringPrefix+"'")},{name:"unterminated-string",regex:new RegExp(stringPrefix)},{name:"integer",regex:/([0-9]+)/},{name:"choice",regex:/\|/},{name:"bang",regex:/(!)/}]);return tokeniser.tokenise(string)}var lop=require("lop"),RegexTokeniser=lop.RegexTokeniser;exports.tokenise=tokenise;var stringPrefix="'((?:\\\\(?:.|$)|[^'\\\\])*)"},{lop:54}],30:[function(require,module,exports){function paragraph(transform){return elementsOfType("paragraph",transform)}function run(transform){return elementsOfType("run",transform)}function elementsOfType(elementType,transform){return elements(function(element){return element.type===elementType?transform(element):element})}function elements(transform){return function transformElement(element){if(element.children){var children=_.map(element.children,transformElement);element=_.extend(element,{children:children})}return transform(element)}}function getDescendantsOfType(element,type){return getDescendants(element).filter(function(descendant){return descendant.type===type})}function getDescendants(element){var descendants=[];return visitDescendants(element,function(descendant){descendants.push(descendant)}),descendants}function visitDescendants(element,visit){element.children&&element.children.forEach(function(child){visitDescendants(child,visit),visit(child)})}var _=require("underscore");exports.paragraph=paragraph,exports.run=run,exports._elements=elements,exports._elementsOfType=elementsOfType,exports.getDescendantsOfType=getDescendantsOfType,exports.getDescendants=getDescendants},{underscore:67}],31:[function(require,module,exports){function element(name){return function(html){return Html.elementWithTag(htmlPaths.element(name),[html])}}var htmlPaths=require("./styles/html-paths"),Html=require("./html");exports.element=element},{"./html":18,"./styles/html-paths":28}],32:[function(require,module,exports){function writer(options){return options=options||{},options.prettyPrint?prettyWriter():simpleWriter()}function prettyWriter(){function open(tagName,attributes){indentedElements[tagName]&&indent(),stack.push(tagName),writer.open(tagName,attributes),indentedElements[tagName]&&indentationLevel++,start=!1}function close(tagName){indentedElements[tagName]&&(indentationLevel--,indent()),stack.pop(),writer.close(tagName)}function text(value){startText();var text=isInPre()?value:value.replace("\n","\n"+indentation);writer.text(text)}function selfClosing(tagName,attributes){indent(),writer.selfClosing(tagName,attributes)}function insideIndentedElement(){return 0===stack.length||indentedElements[stack[stack.length-1]]}function startText(){inText||(indent(),inText=!0)}function indent(){if(inText=!1,!start&&insideIndentedElement()&&!isInPre()){writer._append("\n");for(var i=0;indentationLevel>i;i++)writer._append(indentation)}}function isInPre(){return _.some(stack,function(tagName){return"pre"===tagName})}var indentationLevel=0,indentation=" ",stack=[],start=!0,inText=!1,writer=simpleWriter();return{asString:writer.asString,open:open,close:close,text:text,selfClosing:selfClosing}}function simpleWriter(){function open(tagName,attributes){var attributeString=generateAttributeString(attributes);fragments.push("<"+tagName+attributeString+">")}function close(tagName){fragments.push("")}function selfClosing(tagName,attributes){var attributeString=generateAttributeString(attributes);fragments.push("<"+tagName+attributeString+" />")}function generateAttributeString(attributes){return _.map(attributes,function(value,key){return" "+key+'="'+escapeHtmlAttribute(value)+'"'}).join("")}function text(value){fragments.push(escapeHtmlText(value))}function append(html){fragments.push(html)}function asString(){return fragments.join("")}var fragments=[];return{asString:asString,open:open,close:close,text:text,selfClosing:selfClosing,_append:append}}function escapeHtmlText(value){return value.replace(/&/g,"&").replace(//g,">")}function escapeHtmlAttribute(value){return value.replace(/&/g,"&").replace(/"/g,""").replace(//g,">")}var _=require("underscore");exports.writer=writer;var indentedElements={div:!0,p:!0,ul:!0,li:!0}},{underscore:67}],33:[function(require,module,exports){function writer(options){return options=options||{},"markdown"===options.outputFormat?markdownWriter.writer():htmlWriter.writer(options)}var htmlWriter=require("./html-writer"),markdownWriter=require("./markdown-writer");exports.writer=writer},{"./html-writer":32,"./markdown-writer":34}],34:[function(require,module,exports){function symmetricMarkdownElement(end){return markdownElement(end,end)}function markdownElement(start,end){return function(){return{start:start,end:end}}}function markdownLink(attributes){var href=attributes.href||"";return href?{start:"[",end:"]("+escapeMarkdown(href)+")",anchorPosition:"before"}:{}}function markdownImage(attributes){var src=attributes.src||"",altText=attributes.alt||"";return src||altText?{start:"!["+escapeMarkdown(altText)+"]("+escapeMarkdown(src)+")"}:{}}function markdownList(options){return function(attributes,list){return{start:list?"\n":"",end:list?"":"\n",list:{isOrdered:options.isOrdered,indent:list?list.indent+1:0,count:0}}}}function markdownListItem(attributes,list,listItem){list=list||{indent:0,isOrdered:!1,count:0},list.count++,listItem.hasClosed=!1;var bullet=list.isOrdered?list.count+".":"-",start=repeatString(" ",list.indent)+bullet+" ";return{start:start,end:function(){return listItem.hasClosed?void 0:(listItem.hasClosed=!0,"\n")}}}function repeatString(value,count){return new Array(count+1).join(value)}function markdownWriter(){function open(tagName,attributes){attributes=attributes||{};var createElement=htmlToMarkdown[tagName]||function(){return{}},element=createElement(attributes,list,listItem);elementStack.push({end:element.end,list:list}),element.list&&(list=element.list);var anchorBeforeStart="before"===element.anchorPosition;anchorBeforeStart&&writeAnchor(attributes),fragments.push(element.start||""),anchorBeforeStart||writeAnchor(attributes)}function writeAnchor(attributes){if(attributes.id){var writer=htmlWriter.writer();writer.open("a",{id:attributes.id}),writer.close("a"),fragments.push(writer.asString())}}function close(tagName){var element=elementStack.pop();list=element.list;var end=_.isFunction(element.end)?element.end():element.end;fragments.push(end||"")}function selfClosing(tagName,attributes){open(tagName,attributes),close(tagName)}function text(value){fragments.push(escapeMarkdown(value))}function asString(){return fragments.join("")}var fragments=[],elementStack=[],list=null,listItem={};return{asString:asString,open:open,close:close,text:text,selfClosing:selfClosing}}function escapeMarkdown(value){return value.replace(/\\/g,"\\\\").replace(/([\`\*_\{\}\[\]\(\)\#\+\-\.\!])/g,"\\$1")}var _=require("underscore"),htmlWriter=require("./html-writer"),htmlToMarkdown={p:markdownElement("","\n\n"),br:markdownElement(""," \n"),ul:markdownList({isOrdered:!1}),ol:markdownList({isOrdered:!0}),li:markdownListItem,strong:symmetricMarkdownElement("__"),em:symmetricMarkdownElement("*"),a:markdownLink,img:markdownImage};!function(){for(var i=1;6>=i;i++)htmlToMarkdown["h"+i]=markdownElement(repeatString("#",i)+" ","\n\n")}(),exports.writer=markdownWriter},{"./html-writer":32,underscore:67}],35:[function(require,module,exports){var nodes=require("./nodes");exports.Element=nodes.Element,exports.element=nodes.element,exports.emptyElement=nodes.emptyElement,exports.text=nodes.text,exports.readString=require("./reader").readString,exports.writeString=require("./writer").writeString},{"./nodes":36,"./reader":37,"./writer":38}],36:[function(require,module,exports){function Element(name,attributes,children){this.type="element",this.name=name,this.attributes=attributes||{},this.children=children||[]}function toElementList(array){return _.extend(array,elementListPrototype)}var _=require("underscore");exports.Element=Element,exports.element=function(name,attributes,children){return new Element(name,attributes,children)},exports.text=function(value){return{type:"text",value:value}};var emptyElement=exports.emptyElement={first:function(){return null},firstOrEmpty:function(){return emptyElement},attributes:{},children:[]};Element.prototype.first=function(name){return _.find(this.children,function(child){return child.name===name})},Element.prototype.firstOrEmpty=function(name){return this.first(name)||emptyElement},Element.prototype.getElementsByTagName=function(name){var elements=_.filter(this.children,function(child){return child.name===name});return toElementList(elements)},Element.prototype.text=function(){if(0===this.children.length)return"";if(1!==this.children.length||"text"!==this.children[0].type)throw new Error("Not implemented");return this.children[0].value};var elementListPrototype={getElementsByTagName:function(name){return toElementList(_.flatten(this.map(function(element){return element.getElementsByTagName(name)},!0)))}}},{underscore:67}],37:[function(require,module,exports){function readString(xmlString,namespaceMap){function convertNode(node){switch(node.nodeType){case Node.ELEMENT_NODE:return convertElement(node);case Node.TEXT_NODE:return nodes.text(node.nodeValue)}}function convertElement(element){var convertedName=convertName(element),convertedChildren=[];_.forEach(element.childNodes,function(childNode){var convertedNode=convertNode(childNode);convertedNode&&convertedChildren.push(convertedNode)});var convertedAttributes=Object.create(null);return _.forEach(element.attributes,function(attribute){convertedAttributes[convertName(attribute)]=attribute.value}),new Element(convertedName,convertedAttributes,convertedChildren)}function convertName(node){if(node.namespaceURI){var prefix,mappedPrefix=namespaceMap[node.namespaceURI];return prefix=mappedPrefix?mappedPrefix+":":"{"+node.namespaceURI+"}",prefix+node.localName}return node.localName}namespaceMap=namespaceMap||{};try{var document=xmldom.parseFromString(xmlString,"text/xml")}catch(error){return promises.reject(error)}return"parsererror"===document.documentElement.tagName?promises.resolve(new Error(document.documentElement.textContent)):promises.resolve(convertNode(document.documentElement))}var promises=require("../promises"),_=require("underscore"),xmldom=require("./xmldom"),nodes=require("./nodes"),Element=nodes.Element;exports.readString=readString;var Node=xmldom.Node},{"../promises":23,"./nodes":36,"./xmldom":39,underscore:67}],38:[function(require,module,exports){function writeString(root,namespaces){function writeNode(builder,node){return nodeWriters[node.type](builder,node)}function writeElement(builder,element){var elementBuilder=builder.element(mapElementName(element.name),element.attributes);element.children.forEach(function(child){writeNode(elementBuilder,child)})}function mapElementName(name){var longFormMatch=/^\{(.*)\}(.*)$/.exec(name);if(longFormMatch){var prefix=uriToPrefix[longFormMatch[1]];return prefix+(""===prefix?"":":")+longFormMatch[2]}return name}function writeDocument(root){var builder=xmlbuilder.create(mapElementName(root.name),{version:"1.0",encoding:"UTF-8",standalone:!0});return _.forEach(namespaces,function(uri,prefix){var key="xmlns"+(""===prefix?"":":"+prefix);builder.attribute(key,uri)}),root.children.forEach(function(child){writeNode(builder,child)}),builder.end()}var uriToPrefix=_.invert(namespaces),nodeWriters={element:writeElement,text:writeTextNode};return writeDocument(root)}function writeTextNode(builder,node){builder.text(node.value)}var _=require("underscore"),xmlbuilder=require("xmlbuilder");exports.writeString=writeString},{underscore:67,xmlbuilder:89}],39:[function(require,module,exports){function parseFromString(string){var error=null,domParser=new xmldom.DOMParser({errorHandler:function(level,message){error={level:level,message:message}}}),document=domParser.parseFromString(string);if(null===error)return document;throw new Error(error.level+": "+error.message)}var xmldom=require("@xmldom/xmldom"),dom=require("@xmldom/xmldom/lib/dom");exports.parseFromString=parseFromString,exports.Node=dom.Node},{"@xmldom/xmldom":45,"@xmldom/xmldom/lib/dom":43}],40:[function(require,module,exports){function openArrayBuffer(arrayBuffer){return JSZip.loadAsync(arrayBuffer).then(function(zipFile){function exists(name){return null!==zipFile.file(name)}function read(name,encoding){return zipFile.file(name).async("uint8array").then(function(array){if("base64"===encoding)return base64js.fromByteArray(array);if(encoding){var decoder=new TextDecoder(encoding);return decoder.decode(array)}return array})}function write(name,contents){zipFile.file(name,contents)}function toArrayBuffer(){return zipFile.generateAsync({type:"arraybuffer"})}return{exists:exists,read:read,write:write,toArrayBuffer:toArrayBuffer}})}function splitPath(path){var lastIndex=path.lastIndexOf("/");return-1===lastIndex?{dirname:"",basename:path}:{dirname:path.substring(0,lastIndex),basename:path.substring(lastIndex+1)}}function joinPath(){var nonEmptyPaths=Array.prototype.filter.call(arguments,function(path){return path}),relevantPaths=[];return nonEmptyPaths.forEach(function(path){/^\//.test(path)?relevantPaths=[path]:relevantPaths.push(path)}),relevantPaths.join("/")}var base64js=require("base64-js"),JSZip=require("jszip");exports.openArrayBuffer=openArrayBuffer,exports.splitPath=splitPath,exports.joinPath=joinPath},{"base64-js":47,jszip:53}],41:[function(require,module,exports){"use strict";function find(list,predicate,ac){if(void 0===ac&&(ac=Array.prototype),list&&"function"==typeof ac.find)return ac.find.call(list,predicate);for(var i=0;i=start+length||start?new java.lang.String(chars,start,length)+"":chars}function appendElement(hander,node){hander.currentElement?hander.currentElement.appendChild(node):hander.doc.appendChild(node)}var conventions=require("./conventions"),dom=require("./dom"),entities=require("./entities"),sax=require("./sax"),DOMImplementation=dom.DOMImplementation,NAMESPACE=conventions.NAMESPACE,ParseError=sax.ParseError,XMLReader=sax.XMLReader;DOMParser.prototype.parseFromString=function(source,mimeType){var options=this.options,sax=new XMLReader,domBuilder=options.domBuilder||new DOMHandler,errorHandler=options.errorHandler,locator=options.locator,defaultNSMap=options.xmlns||{},isHTML=/\/x?html?$/.test(mimeType),entityMap=isHTML?entities.HTML_ENTITIES:entities.XML_ENTITIES;locator&&domBuilder.setDocumentLocator(locator),sax.errorHandler=buildErrorHandler(errorHandler,domBuilder,locator),sax.domBuilder=options.domBuilder||domBuilder,isHTML&&(defaultNSMap[""]=NAMESPACE.HTML),defaultNSMap.xml=defaultNSMap.xml||NAMESPACE.XML;var normalize=options.normalizeLineEndings||normalizeLineEndings;return source&&"string"==typeof source?sax.parse(normalize(source),defaultNSMap,entityMap):sax.errorHandler.error("invalid doc source"),domBuilder.doc},DOMHandler.prototype={startDocument:function(){this.doc=(new DOMImplementation).createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(namespaceURI,localName,qName,attrs){var doc=this.doc,el=doc.createElementNS(namespaceURI,qName||localName),len=attrs.length;appendElement(this,el),this.currentElement=el,this.locator&&position(this.locator,el);for(var i=0;len>i;i++){var namespaceURI=attrs.getURI(i),value=attrs.getValue(i),qName=attrs.getQName(i),attr=doc.createAttributeNS(namespaceURI,qName);this.locator&&position(attrs.getLocator(i),attr),attr.value=attr.nodeValue=value,el.setAttributeNode(attr)}},endElement:function(namespaceURI,localName,qName){var current=this.currentElement;current.tagName;this.currentElement=current.parentNode},startPrefixMapping:function(prefix,uri){},endPrefixMapping:function(prefix){},processingInstruction:function(target,data){var ins=this.doc.createProcessingInstruction(target,data);this.locator&&position(this.locator,ins),appendElement(this,ins)},ignorableWhitespace:function(ch,start,length){},characters:function(chars,start,length){if(chars=_toString.apply(this,arguments)){if(this.cdata)var charNode=this.doc.createCDATASection(chars);else var charNode=this.doc.createTextNode(chars);this.currentElement?this.currentElement.appendChild(charNode):/^\s*$/.test(chars)&&this.doc.appendChild(charNode),this.locator&&position(this.locator,charNode)}},skippedEntity:function(name){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(locator){(this.locator=locator)&&(locator.lineNumber=0)},comment:function(chars,start,length){chars=_toString.apply(this,arguments);var comm=this.doc.createComment(chars);this.locator&&position(this.locator,comm),appendElement(this,comm)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(name,publicId,systemId){var impl=this.doc.implementation;if(impl&&impl.createDocumentType){var dt=impl.createDocumentType(name,publicId,systemId);this.locator&&position(this.locator,dt),appendElement(this,dt),this.doc.doctype=dt}},warning:function(error){console.warn("[xmldom warning] "+error,_locator(this.locator))},error:function(error){console.error("[xmldom error] "+error,_locator(this.locator))},fatalError:function(error){throw new ParseError(error,this.locator)}},"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){DOMHandler.prototype[key]=function(){return null}}),exports.__DOMHandler=DOMHandler,exports.normalizeLineEndings=normalizeLineEndings,exports.DOMParser=DOMParser},{"./conventions":41,"./dom":43,"./entities":44,"./sax":46}],43:[function(require,module,exports){function notEmptyString(input){return""!==input}function splitOnASCIIWhitespace(input){return input?input.split(/[\t\n\f\r ]+/).filter(notEmptyString):[]}function orderedSetReducer(current,element){return current.hasOwnProperty(element)||(current[element]=!0),current}function toOrderedSet(input){if(!input)return[];var list=splitOnASCIIWhitespace(input);return Object.keys(list.reduce(orderedSetReducer,{}))}function arrayIncludes(list){return function(element){return list&&-1!==list.indexOf(element)}}function copy(src,dest){for(var p in src)Object.prototype.hasOwnProperty.call(src,p)&&(dest[p]=src[p])}function _extends(Class,Super){function t(){}var pt=Class.prototype;pt instanceof Super||(t.prototype=Super.prototype,t=new t,copy(pt,t),Class.prototype=pt=t),pt.constructor!=Class&&("function"!=typeof Class&&console.error("unknown Class:"+Class),pt.constructor=Class)}function DOMException(code,message){if(message instanceof Error)var error=message;else error=this,Error.call(this,ExceptionMessage[code]),this.message=ExceptionMessage[code],Error.captureStackTrace&&Error.captureStackTrace(this,DOMException);return error.code=code,message&&(this.message=this.message+": "+message),error}function NodeList(){}function LiveNodeList(node,refresh){this._node=node,this._refresh=refresh,_updateLiveList(this)}function _updateLiveList(list){var inc=list._node._inc||list._node.ownerDocument._inc;if(list._inc!=inc){var ls=list._refresh(list._node);__set__(list,"length",ls.length),copy(ls,list),list._inc=inc}}function NamedNodeMap(){}function _findNodeIndex(list,node){for(var i=list.length;i--;)if(list[i]===node)return i}function _addNamedNode(el,list,newAttr,oldAttr){if(oldAttr?list[_findNodeIndex(list,oldAttr)]=newAttr:list[list.length++]=newAttr,el){newAttr.ownerElement=el;var doc=el.ownerDocument;doc&&(oldAttr&&_onRemoveAttribute(doc,el,oldAttr),_onAddAttribute(doc,el,newAttr))}}function _removeNamedNode(el,list,attr){var i=_findNodeIndex(list,attr);if(!(i>=0))throw new DOMException(NOT_FOUND_ERR,new Error(el.tagName+"@"+attr));for(var lastIndex=list.length-1;lastIndex>i;)list[i]=list[++i];if(list.length=lastIndex,el){var doc=el.ownerDocument;doc&&(_onRemoveAttribute(doc,el,attr),attr.ownerElement=null)}}function DOMImplementation(){}function Node(){}function _xmlEncoder(c){return"<"==c&&"<"||">"==c&&">"||"&"==c&&"&"||'"'==c&&"""||"&#"+c.charCodeAt()+";"}function _visitNode(node,callback){if(callback(node))return!0;if(node=node.firstChild)do if(_visitNode(node,callback))return!0;while(node=node.nextSibling)}function Document(){this.ownerDocument=this}function _onAddAttribute(doc,el,newAttr){doc&&doc._inc++;var ns=newAttr.namespaceURI;ns===NAMESPACE.XMLNS&&(el._nsMap[newAttr.prefix?newAttr.localName:""]=newAttr.value)}function _onRemoveAttribute(doc,el,newAttr,remove){doc&&doc._inc++;var ns=newAttr.namespaceURI;ns===NAMESPACE.XMLNS&&delete el._nsMap[newAttr.prefix?newAttr.localName:""]}function _onUpdateChild(doc,el,newChild){if(doc&&doc._inc){doc._inc++;var cs=el.childNodes;if(newChild)cs[cs.length++]=newChild;else{for(var child=el.firstChild,i=0;child;)cs[i++]=child,child=child.nextSibling;cs.length=i,delete cs[cs.length]}}}function _removeChild(parentNode,child){var previous=child.previousSibling,next=child.nextSibling;return previous?previous.nextSibling=next:parentNode.firstChild=next,next?next.previousSibling=previous:parentNode.lastChild=previous,child.parentNode=null,child.previousSibling=null,child.nextSibling=null,_onUpdateChild(parentNode.ownerDocument,parentNode),child}function hasValidParentNodeType(node){return node&&(node.nodeType===Node.DOCUMENT_NODE||node.nodeType===Node.DOCUMENT_FRAGMENT_NODE||node.nodeType===Node.ELEMENT_NODE)}function hasInsertableNodeType(node){return node&&(isElementNode(node)||isTextNode(node)||isDocTypeNode(node)||node.nodeType===Node.DOCUMENT_FRAGMENT_NODE||node.nodeType===Node.COMMENT_NODE||node.nodeType===Node.PROCESSING_INSTRUCTION_NODE)}function isDocTypeNode(node){return node&&node.nodeType===Node.DOCUMENT_TYPE_NODE}function isElementNode(node){return node&&node.nodeType===Node.ELEMENT_NODE}function isTextNode(node){return node&&node.nodeType===Node.TEXT_NODE}function isElementInsertionPossible(doc,child){var parentChildNodes=doc.childNodes||[];if(find(parentChildNodes,isElementNode)||isDocTypeNode(child))return!1;var docTypeNode=find(parentChildNodes,isDocTypeNode);return!(child&&docTypeNode&&parentChildNodes.indexOf(docTypeNode)>parentChildNodes.indexOf(child))}function isElementReplacementPossible(doc,child){function hasElementChildThatIsNotChild(node){return isElementNode(node)&&node!==child}var parentChildNodes=doc.childNodes||[];if(find(parentChildNodes,hasElementChildThatIsNotChild))return!1;var docTypeNode=find(parentChildNodes,isDocTypeNode);return!(child&&docTypeNode&&parentChildNodes.indexOf(docTypeNode)>parentChildNodes.indexOf(child))}function assertPreInsertionValidity1to5(parent,node,child){if(!hasValidParentNodeType(parent))throw new DOMException(HIERARCHY_REQUEST_ERR,"Unexpected parent node type "+parent.nodeType);if(child&&child.parentNode!==parent)throw new DOMException(NOT_FOUND_ERR,"child not in parent");if(!hasInsertableNodeType(node)||isDocTypeNode(node)&&parent.nodeType!==Node.DOCUMENT_NODE)throw new DOMException(HIERARCHY_REQUEST_ERR,"Unexpected node type "+node.nodeType+" for parent node type "+parent.nodeType)}function assertPreInsertionValidityInDocument(parent,node,child){var parentChildNodes=parent.childNodes||[],nodeChildNodes=node.childNodes||[];if(node.nodeType===Node.DOCUMENT_FRAGMENT_NODE){var nodeChildElements=nodeChildNodes.filter(isElementNode);if(nodeChildElements.length>1||find(nodeChildNodes,isTextNode))throw new DOMException(HIERARCHY_REQUEST_ERR,"More than one element or text in fragment");if(1===nodeChildElements.length&&!isElementInsertionPossible(parent,child))throw new DOMException(HIERARCHY_REQUEST_ERR,"Element in fragment can not be inserted before doctype")}if(isElementNode(node)&&!isElementInsertionPossible(parent,child))throw new DOMException(HIERARCHY_REQUEST_ERR,"Only one element can be added and only after doctype");if(isDocTypeNode(node)){if(find(parentChildNodes,isDocTypeNode))throw new DOMException(HIERARCHY_REQUEST_ERR,"Only one doctype is allowed");var parentElementChild=find(parentChildNodes,isElementNode);if(child&&parentChildNodes.indexOf(parentElementChild)1||find(nodeChildNodes,isTextNode))throw new DOMException(HIERARCHY_REQUEST_ERR,"More than one element or text in fragment");if(1===nodeChildElements.length&&!isElementReplacementPossible(parent,child))throw new DOMException(HIERARCHY_REQUEST_ERR,"Element in fragment can not be inserted before doctype")}if(isElementNode(node)&&!isElementReplacementPossible(parent,child))throw new DOMException(HIERARCHY_REQUEST_ERR,"Only one element can be added and only after doctype");if(isDocTypeNode(node)){if(find(parentChildNodes,hasDoctypeChildThatIsNotChild))throw new DOMException(HIERARCHY_REQUEST_ERR,"Only one doctype is allowed");var parentElementChild=find(parentChildNodes,isElementNode);if(child&&parentChildNodes.indexOf(parentElementChild)=0;nsi--){var namespace=visibleNamespaces[nsi];if(""===namespace.prefix&&namespace.namespace===node.namespaceURI){defaultNS=namespace.namespace;break}}if(defaultNS!==node.namespaceURI)for(var nsi=visibleNamespaces.length-1;nsi>=0;nsi--){var namespace=visibleNamespaces[nsi];if(namespace.namespace===node.namespaceURI){namespace.prefix&&(prefixedNodeName=namespace.prefix+":"+nodeName);break}}}buf.push("<",prefixedNodeName);for(var i=0;len>i;i++){var attr=attrs.item(i);"xmlns"==attr.prefix?visibleNamespaces.push({prefix:attr.localName,namespace:attr.value}):"xmlns"==attr.nodeName&&visibleNamespaces.push({prefix:"",namespace:attr.value})}for(var i=0;len>i;i++){var attr=attrs.item(i);if(needNamespaceDefine(attr,isHTML,visibleNamespaces)){var prefix=attr.prefix||"",uri=attr.namespaceURI;addSerializedAttribute(buf,prefix?"xmlns:"+prefix:"xmlns",uri),visibleNamespaces.push({prefix:prefix,namespace:uri})}serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces)}if(nodeName===prefixedNodeName&&needNamespaceDefine(node,isHTML,visibleNamespaces)){var prefix=node.prefix||"",uri=node.namespaceURI;addSerializedAttribute(buf,prefix?"xmlns:"+prefix:"xmlns",uri),visibleNamespaces.push({prefix:prefix,namespace:uri})}if(child||isHTML&&!/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){if(buf.push(">"),isHTML&&/^script$/i.test(nodeName))for(;child;)child.data?buf.push(child.data):serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces.slice()),child=child.nextSibling;else for(;child;)serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces.slice()),child=child.nextSibling;buf.push("")}else buf.push("/>");return;case DOCUMENT_NODE:case DOCUMENT_FRAGMENT_NODE:for(var child=node.firstChild;child;)serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces.slice()),child=child.nextSibling;return;case ATTRIBUTE_NODE:return addSerializedAttribute(buf,node.name,node.value);case TEXT_NODE:return buf.push(node.data.replace(/[<&>]/g,_xmlEncoder));case CDATA_SECTION_NODE:return buf.push("");case COMMENT_NODE:return buf.push("");case DOCUMENT_TYPE_NODE:var pubid=node.publicId,sysid=node.systemId;if(buf.push("");else if(sysid&&"."!=sysid)buf.push(" SYSTEM ",sysid,">");else{var sub=node.internalSubset;sub&&buf.push(" [",sub,"]"),buf.push(">")}return;case PROCESSING_INSTRUCTION_NODE:return buf.push("");case ENTITY_REFERENCE_NODE:return buf.push("&",node.nodeName,";");default:buf.push("??",node.nodeName)}}function importNode(doc,node,deep){var node2;switch(node.nodeType){case ELEMENT_NODE:node2=node.cloneNode(!1),node2.ownerDocument=doc;case DOCUMENT_FRAGMENT_NODE:break;case ATTRIBUTE_NODE:deep=!0}if(node2||(node2=node.cloneNode(!1)),node2.ownerDocument=doc,node2.parentNode=null,deep)for(var child=node.firstChild;child;)node2.appendChild(importNode(doc,child,deep)),child=child.nextSibling;return node2}function cloneNode(doc,node,deep){var node2=new node.constructor;for(var n in node)if(Object.prototype.hasOwnProperty.call(node,n)){var v=node[n];"object"!=typeof v&&v!=node2[n]&&(node2[n]=v)}switch(node.childNodes&&(node2.childNodes=new NodeList),node2.ownerDocument=doc,node2.nodeType){case ELEMENT_NODE:var attrs=node.attributes,attrs2=node2.attributes=new NamedNodeMap,len=attrs.length;attrs2._ownerElement=node2;for(var i=0;len>i;i++)node2.setAttributeNode(cloneNode(doc,attrs.item(i),!0));break;case ATTRIBUTE_NODE:deep=!0}if(deep)for(var child=node.firstChild;child;)node2.appendChild(cloneNode(doc,child,deep)),child=child.nextSibling;return node2}function __set__(object,key,value){object[key]=value}function getTextContent(node){switch(node.nodeType){case ELEMENT_NODE:case DOCUMENT_FRAGMENT_NODE:var buf=[];for(node=node.firstChild;node;)7!==node.nodeType&&8!==node.nodeType&&buf.push(getTextContent(node)),node=node.nextSibling;return buf.join("");default:return node.nodeValue}}var conventions=require("./conventions"),find=conventions.find,NAMESPACE=conventions.NAMESPACE,NodeType={},ELEMENT_NODE=NodeType.ELEMENT_NODE=1,ATTRIBUTE_NODE=NodeType.ATTRIBUTE_NODE=2,TEXT_NODE=NodeType.TEXT_NODE=3,CDATA_SECTION_NODE=NodeType.CDATA_SECTION_NODE=4,ENTITY_REFERENCE_NODE=NodeType.ENTITY_REFERENCE_NODE=5,ENTITY_NODE=NodeType.ENTITY_NODE=6,PROCESSING_INSTRUCTION_NODE=NodeType.PROCESSING_INSTRUCTION_NODE=7,COMMENT_NODE=NodeType.COMMENT_NODE=8,DOCUMENT_NODE=NodeType.DOCUMENT_NODE=9,DOCUMENT_TYPE_NODE=NodeType.DOCUMENT_TYPE_NODE=10,DOCUMENT_FRAGMENT_NODE=NodeType.DOCUMENT_FRAGMENT_NODE=11,NOTATION_NODE=NodeType.NOTATION_NODE=12,ExceptionCode={},ExceptionMessage={},HIERARCHY_REQUEST_ERR=(ExceptionCode.INDEX_SIZE_ERR=(ExceptionMessage[1]="Index size error",1),ExceptionCode.DOMSTRING_SIZE_ERR=(ExceptionMessage[2]="DOMString size error",2),ExceptionCode.HIERARCHY_REQUEST_ERR=(ExceptionMessage[3]="Hierarchy request error",3)),NOT_FOUND_ERR=(ExceptionCode.WRONG_DOCUMENT_ERR=(ExceptionMessage[4]="Wrong document",4),ExceptionCode.INVALID_CHARACTER_ERR=(ExceptionMessage[5]="Invalid character",5),ExceptionCode.NO_DATA_ALLOWED_ERR=(ExceptionMessage[6]="No data allowed",6),ExceptionCode.NO_MODIFICATION_ALLOWED_ERR=(ExceptionMessage[7]="No modification allowed",7),ExceptionCode.NOT_FOUND_ERR=(ExceptionMessage[8]="Not found",8)),INUSE_ATTRIBUTE_ERR=(ExceptionCode.NOT_SUPPORTED_ERR=(ExceptionMessage[9]="Not supported",9),ExceptionCode.INUSE_ATTRIBUTE_ERR=(ExceptionMessage[10]="Attribute in use",10));ExceptionCode.INVALID_STATE_ERR=(ExceptionMessage[11]="Invalid state",11),ExceptionCode.SYNTAX_ERR=(ExceptionMessage[12]="Syntax error",12),ExceptionCode.INVALID_MODIFICATION_ERR=(ExceptionMessage[13]="Invalid modification",13),ExceptionCode.NAMESPACE_ERR=(ExceptionMessage[14]="Invalid namespace",14),ExceptionCode.INVALID_ACCESS_ERR=(ExceptionMessage[15]="Invalid access",15);DOMException.prototype=Error.prototype,copy(ExceptionCode,DOMException),NodeList.prototype={length:0,item:function(index){return this[index]||null},toString:function(isHTML,nodeFilter){for(var buf=[],i=0;i0},lookupPrefix:function(namespaceURI){for(var el=this;el;){var map=el._nsMap;if(map)for(var n in map)if(Object.prototype.hasOwnProperty.call(map,n)&&map[n]===namespaceURI)return n;el=el.nodeType==ATTRIBUTE_NODE?el.ownerDocument:el.parentNode}return null},lookupNamespaceURI:function(prefix){for(var el=this;el;){var map=el._nsMap;if(map&&Object.prototype.hasOwnProperty.call(map,prefix))return map[prefix];el=el.nodeType==ATTRIBUTE_NODE?el.ownerDocument:el.parentNode}return null},isDefaultNamespace:function(namespaceURI){var prefix=this.lookupPrefix(namespaceURI);return null==prefix}},copy(NodeType,Node),copy(NodeType,Node.prototype),Document.prototype={nodeName:"#document",nodeType:DOCUMENT_NODE,doctype:null,documentElement:null,_inc:1,insertBefore:function(newChild,refChild){if(newChild.nodeType==DOCUMENT_FRAGMENT_NODE){for(var child=newChild.firstChild;child;){var next=child.nextSibling;this.insertBefore(child,refChild),child=next}return newChild}return _insertBefore(this,newChild,refChild),newChild.ownerDocument=this,null===this.documentElement&&newChild.nodeType===ELEMENT_NODE&&(this.documentElement=newChild),newChild},removeChild:function(oldChild){return this.documentElement==oldChild&&(this.documentElement=null),_removeChild(this,oldChild)},replaceChild:function(newChild,oldChild){_insertBefore(this,newChild,oldChild,assertPreReplacementValidityInDocument),newChild.ownerDocument=this,oldChild&&this.removeChild(oldChild),isElementNode(newChild)&&(this.documentElement=newChild)},importNode:function(importedNode,deep){return importNode(this,importedNode,deep)},getElementById:function(id){var rtv=null;return _visitNode(this.documentElement,function(node){return node.nodeType==ELEMENT_NODE&&node.getAttribute("id")==id?(rtv=node,!0):void 0}),rtv},getElementsByClassName:function(classNames){var classNamesSet=toOrderedSet(classNames);return new LiveNodeList(this,function(base){var ls=[];return classNamesSet.length>0&&_visitNode(base.documentElement,function(node){if(node!==base&&node.nodeType===ELEMENT_NODE){var nodeClassNames=node.getAttribute("class");if(nodeClassNames){var matches=classNames===nodeClassNames;if(!matches){var nodeClassNamesSet=toOrderedSet(nodeClassNames);matches=classNamesSet.every(arrayIncludes(nodeClassNamesSet))}matches&&ls.push(node)}}}),ls})},createElement:function(tagName){var node=new Element;node.ownerDocument=this,node.nodeName=tagName,node.tagName=tagName,node.localName=tagName,node.childNodes=new NodeList;var attrs=node.attributes=new NamedNodeMap;return attrs._ownerElement=node,node},createDocumentFragment:function(){var node=new DocumentFragment;return node.ownerDocument=this,node.childNodes=new NodeList,node},createTextNode:function(data){var node=new Text;return node.ownerDocument=this,node.appendData(data),node},createComment:function(data){var node=new Comment;return node.ownerDocument=this,node.appendData(data),node},createCDATASection:function(data){var node=new CDATASection;return node.ownerDocument=this,node.appendData(data),node},createProcessingInstruction:function(target,data){var node=new ProcessingInstruction;return node.ownerDocument=this,node.tagName=node.target=target,node.nodeValue=node.data=data,node},createAttribute:function(name){var node=new Attr;return node.ownerDocument=this,node.name=name,node.nodeName=name,node.localName=name,node.specified=!0,node},createEntityReference:function(name){var node=new EntityReference;return node.ownerDocument=this,node.nodeName=name,node},createElementNS:function(namespaceURI,qualifiedName){var node=new Element,pl=qualifiedName.split(":"),attrs=node.attributes=new NamedNodeMap;return node.childNodes=new NodeList,node.ownerDocument=this,node.nodeName=qualifiedName,node.tagName=qualifiedName,node.namespaceURI=namespaceURI,2==pl.length?(node.prefix=pl[0],node.localName=pl[1]):node.localName=qualifiedName,attrs._ownerElement=node,node},createAttributeNS:function(namespaceURI,qualifiedName){var node=new Attr,pl=qualifiedName.split(":");return node.ownerDocument=this,node.nodeName=qualifiedName,node.name=qualifiedName,node.namespaceURI=namespaceURI,node.specified=!0,2==pl.length?(node.prefix=pl[0],node.localName=pl[1]):node.localName=qualifiedName,node}},_extends(Document,Node),Element.prototype={nodeType:ELEMENT_NODE,hasAttribute:function(name){return null!=this.getAttributeNode(name)},getAttribute:function(name){var attr=this.getAttributeNode(name);return attr&&attr.value||""},getAttributeNode:function(name){return this.attributes.getNamedItem(name)},setAttribute:function(name,value){var attr=this.ownerDocument.createAttribute(name);attr.value=attr.nodeValue=""+value,this.setAttributeNode(attr)},removeAttribute:function(name){var attr=this.getAttributeNode(name);attr&&this.removeAttributeNode(attr)},appendChild:function(newChild){return newChild.nodeType===DOCUMENT_FRAGMENT_NODE?this.insertBefore(newChild,null):_appendSingleChild(this,newChild)},setAttributeNode:function(newAttr){return this.attributes.setNamedItem(newAttr)},setAttributeNodeNS:function(newAttr){return this.attributes.setNamedItemNS(newAttr)},removeAttributeNode:function(oldAttr){return this.attributes.removeNamedItem(oldAttr.nodeName)},removeAttributeNS:function(namespaceURI,localName){var old=this.getAttributeNodeNS(namespaceURI,localName);old&&this.removeAttributeNode(old)},hasAttributeNS:function(namespaceURI,localName){return null!=this.getAttributeNodeNS(namespaceURI,localName)},getAttributeNS:function(namespaceURI,localName){var attr=this.getAttributeNodeNS(namespaceURI,localName);return attr&&attr.value||""},setAttributeNS:function(namespaceURI,qualifiedName,value){var attr=this.ownerDocument.createAttributeNS(namespaceURI,qualifiedName);attr.value=attr.nodeValue=""+value,this.setAttributeNode(attr)},getAttributeNodeNS:function(namespaceURI,localName){return this.attributes.getNamedItemNS(namespaceURI,localName)},getElementsByTagName:function(tagName){return new LiveNodeList(this,function(base){var ls=[];return _visitNode(base,function(node){node===base||node.nodeType!=ELEMENT_NODE||"*"!==tagName&&node.tagName!=tagName||ls.push(node)}),ls})},getElementsByTagNameNS:function(namespaceURI,localName){return new LiveNodeList(this,function(base){var ls=[];return _visitNode(base,function(node){node===base||node.nodeType!==ELEMENT_NODE||"*"!==namespaceURI&&node.namespaceURI!==namespaceURI||"*"!==localName&&node.localName!=localName||ls.push(node)}),ls})}},Document.prototype.getElementsByTagName=Element.prototype.getElementsByTagName,Document.prototype.getElementsByTagNameNS=Element.prototype.getElementsByTagNameNS,_extends(Element,Node),Attr.prototype.nodeType=ATTRIBUTE_NODE,_extends(Attr,Node), +CharacterData.prototype={data:"",substringData:function(offset,count){return this.data.substring(offset,offset+count)},appendData:function(text){text=this.data+text,this.nodeValue=this.data=text,this.length=text.length},insertData:function(offset,text){this.replaceData(offset,0,text)},appendChild:function(newChild){throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])},deleteData:function(offset,count){this.replaceData(offset,count,"")},replaceData:function(offset,count,text){var start=this.data.substring(0,offset),end=this.data.substring(offset+count);text=start+text+end,this.nodeValue=this.data=text,this.length=text.length}},_extends(CharacterData,Node),Text.prototype={nodeName:"#text",nodeType:TEXT_NODE,splitText:function(offset){var text=this.data,newText=text.substring(offset);text=text.substring(0,offset),this.data=this.nodeValue=text,this.length=text.length;var newNode=this.ownerDocument.createTextNode(newText);return this.parentNode&&this.parentNode.insertBefore(newNode,this.nextSibling),newNode}},_extends(Text,CharacterData),Comment.prototype={nodeName:"#comment",nodeType:COMMENT_NODE},_extends(Comment,CharacterData),CDATASection.prototype={nodeName:"#cdata-section",nodeType:CDATA_SECTION_NODE},_extends(CDATASection,CharacterData),DocumentType.prototype.nodeType=DOCUMENT_TYPE_NODE,_extends(DocumentType,Node),Notation.prototype.nodeType=NOTATION_NODE,_extends(Notation,Node),Entity.prototype.nodeType=ENTITY_NODE,_extends(Entity,Node),EntityReference.prototype.nodeType=ENTITY_REFERENCE_NODE,_extends(EntityReference,Node),DocumentFragment.prototype.nodeName="#document-fragment",DocumentFragment.prototype.nodeType=DOCUMENT_FRAGMENT_NODE,_extends(DocumentFragment,Node),ProcessingInstruction.prototype.nodeType=PROCESSING_INSTRUCTION_NODE,_extends(ProcessingInstruction,Node),XMLSerializer.prototype.serializeToString=function(node,isHtml,nodeFilter){return nodeSerializeToString.call(node,isHtml,nodeFilter)},Node.prototype.toString=nodeSerializeToString;try{Object.defineProperty&&(Object.defineProperty(LiveNodeList.prototype,"length",{get:function(){return _updateLiveList(this),this.$$length}}),Object.defineProperty(Node.prototype,"textContent",{get:function(){return getTextContent(this)},set:function(data){switch(this.nodeType){case ELEMENT_NODE:case DOCUMENT_FRAGMENT_NODE:for(;this.firstChild;)this.removeChild(this.firstChild);(data||String(data))&&this.appendChild(this.ownerDocument.createTextNode(data));break;default:this.data=data,this.value=data,this.nodeValue=data}}}),__set__=function(object,key,value){object["$$"+key]=value})}catch(e){}exports.DocumentType=DocumentType,exports.DOMException=DOMException,exports.DOMImplementation=DOMImplementation,exports.Element=Element,exports.Node=Node,exports.NodeList=NodeList,exports.XMLSerializer=XMLSerializer},{"./conventions":41}],44:[function(require,module,exports){var freeze=require("./conventions").freeze;exports.XML_ENTITIES=freeze({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'}),exports.HTML_ENTITIES=freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",times:"×",divide:"÷",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪","int":"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",euro:"€",trade:"™",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"}),exports.entityMap=exports.HTML_ENTITIES},{"./conventions":41}],45:[function(require,module,exports){var dom=require("./dom");exports.DOMImplementation=dom.DOMImplementation,exports.XMLSerializer=dom.XMLSerializer,exports.DOMParser=require("./dom-parser").DOMParser},{"./dom":43,"./dom-parser":42}],46:[function(require,module,exports){function ParseError(message,locator){this.message=message,this.locator=locator,Error.captureStackTrace&&Error.captureStackTrace(this,ParseError)}function XMLReader(){}function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){function fixedFromCharCode(code){if(code>65535){code-=65536;var surrogate1=55296+(code>>10),surrogate2=56320+(1023&code);return String.fromCharCode(surrogate1,surrogate2)}return String.fromCharCode(code)}function entityReplacer(a){var k=a.slice(1,-1);return Object.hasOwnProperty.call(entityMap,k)?entityMap[k]:"#"===k.charAt(0)?fixedFromCharCode(parseInt(k.substr(1).replace("x","0x"))):(errorHandler.error("entity not found:"+a),a)}function appendText(end){if(end>start){var xt=source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);locator&&position(start),domBuilder.characters(xt,0,end-start),start=end}}function position(p,m){for(;p>=lineEnd&&(m=linePattern.exec(source));)lineStart=m.index,lineEnd=lineStart+m[0].length,locator.lineNumber++;locator.columnNumber=p-lineStart+1}for(var lineStart=0,lineEnd=0,linePattern=/.*(?:\r\n?|\n)|.*$/g,locator=domBuilder.locator,parseStack=[{currentNSMap:defaultNSMapCopy}],closeMap={},start=0;;){try{var tagStart=source.indexOf("<",start);if(0>tagStart){if(!source.substr(start).match(/^\s*$/)){var doc=domBuilder.doc,text=doc.createTextNode(source.substr(start));doc.appendChild(text),domBuilder.currentElement=text}return}switch(tagStart>start&&appendText(tagStart),source.charAt(tagStart+1)){case"/":var end=source.indexOf(">",tagStart+3),tagName=source.substring(tagStart+2,end).replace(/[ \t\n\r]+$/g,""),config=parseStack.pop();0>end?(tagName=source.substring(tagStart+2).replace(/[\s<].*/,""),errorHandler.error("end tag name: "+tagName+" is not complete:"+config.tagName),end=tagStart+1+tagName.length):tagName.match(/\si;i++){var a=el[i];position(a.offset),a.locator=copyLocator(locator,{})}domBuilder.locator=locator2,appendElement(el,domBuilder,currentNSMap)&&parseStack.push(el),domBuilder.locator=locator}else appendElement(el,domBuilder,currentNSMap)&&parseStack.push(el);NAMESPACE.isHTML(el.uri)&&!el.closed?end=parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder):end++}}catch(e){if(e instanceof ParseError)throw e;errorHandler.error("element parse error: "+e),end=-1}end>start?start=end:appendText(Math.max(tagStart,start)+1)}}function copyLocator(f,t){return t.lineNumber=f.lineNumber,t.columnNumber=f.columnNumber,t}function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){function addAttribute(qname,value,startIndex){el.attributeNames.hasOwnProperty(qname)&&errorHandler.fatalError("Attribute "+qname+" redefined"),el.addValue(qname,value.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,entityReplacer),startIndex)}for(var attrName,value,p=++start,s=S_TAG;;){var c=source.charAt(p);switch(c){case"=":if(s===S_ATTR)attrName=source.slice(start,p),s=S_EQ;else{if(s!==S_ATTR_SPACE)throw new Error("attribute equal must after attrName");s=S_EQ}break;case"'":case'"':if(s===S_EQ||s===S_ATTR){if(s===S_ATTR&&(errorHandler.warning('attribute value must after "="'),attrName=source.slice(start,p)),start=p+1,p=source.indexOf(c,start),!(p>0))throw new Error("attribute value no end '"+c+"' match");value=source.slice(start,p),addAttribute(attrName,value,start-1),s=S_ATTR_END}else{if(s!=S_ATTR_NOQUOT_VALUE)throw new Error('attribute value must after "="');value=source.slice(start,p),addAttribute(attrName,value,start),errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+")!!"),start=p+1,s=S_ATTR_END}break;case"/":switch(s){case S_TAG:el.setTagName(source.slice(start,p));case S_ATTR_END:case S_TAG_SPACE:case S_TAG_CLOSE:s=S_TAG_CLOSE,el.closed=!0;case S_ATTR_NOQUOT_VALUE:case S_ATTR:case S_ATTR_SPACE:break;default:throw new Error("attribute invalid close char('/')")}break;case"":return errorHandler.error("unexpected end of input"),s==S_TAG&&el.setTagName(source.slice(start,p)),p;case">":switch(s){case S_TAG:el.setTagName(source.slice(start,p));case S_ATTR_END:case S_TAG_SPACE:case S_TAG_CLOSE:break;case S_ATTR_NOQUOT_VALUE:case S_ATTR:value=source.slice(start,p),"/"===value.slice(-1)&&(el.closed=!0,value=value.slice(0,-1));case S_ATTR_SPACE:s===S_ATTR_SPACE&&(value=attrName),s==S_ATTR_NOQUOT_VALUE?(errorHandler.warning('attribute "'+value+'" missed quot(")!'),addAttribute(attrName,value,start)):(NAMESPACE.isHTML(currentNSMap[""])&&value.match(/^(?:disabled|checked|selected)$/i)||errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!'),addAttribute(value,value,start));break;case S_EQ:throw new Error("attribute value missed!!")}return p;case"€":c=" ";default:if(" ">=c)switch(s){case S_TAG:el.setTagName(source.slice(start,p)),s=S_TAG_SPACE;break;case S_ATTR:attrName=source.slice(start,p),s=S_ATTR_SPACE;break;case S_ATTR_NOQUOT_VALUE:var value=source.slice(start,p);errorHandler.warning('attribute "'+value+'" missed quot(")!!'),addAttribute(attrName,value,start);case S_ATTR_END:s=S_TAG_SPACE}else switch(s){case S_ATTR_SPACE:el.tagName;NAMESPACE.isHTML(currentNSMap[""])&&attrName.match(/^(?:disabled|checked|selected)$/i)||errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!'),addAttribute(attrName,attrName,start),start=p,s=S_ATTR;break;case S_ATTR_END:errorHandler.warning('attribute space is required"'+attrName+'"!!');case S_TAG_SPACE:s=S_ATTR,start=p;break;case S_EQ:s=S_ATTR_NOQUOT_VALUE,start=p;break;case S_TAG_CLOSE:throw new Error("elements closed character '/' and '>' must be connected to")}}p++}}function appendElement(el,domBuilder,currentNSMap){for(var tagName=el.tagName,localNSMap=null,i=el.length;i--;){var a=el[i],qName=a.qName,value=a.value,nsp=qName.indexOf(":");if(nsp>0)var prefix=a.prefix=qName.slice(0,nsp),localName=qName.slice(nsp+1),nsPrefix="xmlns"===prefix&&localName;else localName=qName,prefix=null,nsPrefix="xmlns"===qName&&"";a.localName=localName,nsPrefix!==!1&&(null==localNSMap&&(localNSMap={},_copy(currentNSMap,currentNSMap={})),currentNSMap[nsPrefix]=localNSMap[nsPrefix]=value,a.uri=NAMESPACE.XMLNS,domBuilder.startPrefixMapping(nsPrefix,value))}for(var i=el.length;i--;){a=el[i];var prefix=a.prefix;prefix&&("xml"===prefix&&(a.uri=NAMESPACE.XML),"xmlns"!==prefix&&(a.uri=currentNSMap[prefix||""]))}var nsp=tagName.indexOf(":");nsp>0?(prefix=el.prefix=tagName.slice(0,nsp),localName=el.localName=tagName.slice(nsp+1)):(prefix=null,localName=el.localName=tagName);var ns=el.uri=currentNSMap[prefix||""];if(domBuilder.startElement(ns,localName,tagName,el),!el.closed)return el.currentNSMap=currentNSMap,el.localNSMap=localNSMap,!0;if(domBuilder.endElement(ns,localName,tagName),localNSMap)for(prefix in localNSMap)Object.prototype.hasOwnProperty.call(localNSMap,prefix)&&domBuilder.endPrefixMapping(prefix)}function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){if(/^(?:script|textarea)$/i.test(tagName)){var elEndStart=source.indexOf("",elStartEnd),text=source.substring(elStartEnd+1,elEndStart);if(/[&<]/.test(text))return/^script$/i.test(tagName)?(domBuilder.characters(text,0,text.length),elEndStart):(text=text.replace(/&#?\w+;/g,entityReplacer),domBuilder.characters(text,0,text.length),elEndStart)}return elStartEnd+1}function fixSelfClosed(source,elStartEnd,tagName,closeMap){var pos=closeMap[tagName];return null==pos&&(pos=source.lastIndexOf(""),elStartEnd>pos&&(pos=source.lastIndexOf("pos}function _copy(source,target){for(var n in source)Object.prototype.hasOwnProperty.call(source,n)&&(target[n]=source[n])}function parseDCC(source,start,domBuilder,errorHandler){var next=source.charAt(start+2);switch(next){case"-":if("-"===source.charAt(start+3)){var end=source.indexOf("-->",start+4);return end>start?(domBuilder.comment(source,start+4,end-start-4),end+3):(errorHandler.error("Unclosed comment"),-1)}return-1;default:if("CDATA["==source.substr(start+3,6)){var end=source.indexOf("]]>",start+9);return domBuilder.startCDATA(),domBuilder.characters(source,start+9,end-start-9),domBuilder.endCDATA(),end+3}var matchs=split(source,start),len=matchs.length;if(len>1&&/!doctype/i.test(matchs[0][0])){var name=matchs[1][0],pubid=!1,sysid=!1;len>3&&(/^public$/i.test(matchs[2][0])?(pubid=matchs[3][0],sysid=len>4&&matchs[4][0]):/^system$/i.test(matchs[2][0])&&(sysid=matchs[3][0]));var lastMatch=matchs[len-1];return domBuilder.startDTD(name,pubid,sysid),domBuilder.endDTD(),lastMatch.index+lastMatch[0].length}}return-1}function parseInstruction(source,start,domBuilder){var end=source.indexOf("?>",start);if(end){var match=source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);if(match){match[0].length;return domBuilder.processingInstruction(match[1],match[2]),end+2}return-1}return-1}function ElementAttributes(){this.attributeNames={}}function split(source,start){var match,buf=[],reg=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(reg.lastIndex=start,reg.exec(source);match=reg.exec(source);)if(buf.push(match),match[1])return buf}var NAMESPACE=require("./conventions").NAMESPACE,nameStartChar=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,nameChar=new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),tagNamePattern=new RegExp("^"+nameStartChar.source+nameChar.source+"*(?::"+nameStartChar.source+nameChar.source+"*)?$"),S_TAG=0,S_ATTR=1,S_ATTR_SPACE=2,S_EQ=3,S_ATTR_NOQUOT_VALUE=4,S_ATTR_END=5,S_TAG_SPACE=6,S_TAG_CLOSE=7;ParseError.prototype=new Error,ParseError.prototype.name=ParseError.name,XMLReader.prototype={parse:function(source,defaultNSMap,entityMap){var domBuilder=this.domBuilder;domBuilder.startDocument(),_copy(defaultNSMap,defaultNSMap={}),parse(source,defaultNSMap,entityMap,domBuilder,this.errorHandler),domBuilder.endDocument()}},ElementAttributes.prototype={setTagName:function(tagName){if(!tagNamePattern.test(tagName))throw new Error("invalid tagName:"+tagName);this.tagName=tagName},addValue:function(qName,value,offset){if(!tagNamePattern.test(qName))throw new Error("invalid attribute:"+qName);this.attributeNames[qName]=this.length,this[this.length++]={qName:qName,value:value,offset:offset}},length:0,getLocalName:function(i){return this[i].localName},getLocator:function(i){return this[i].locator},getQName:function(i){return this[i].qName},getURI:function(i){return this[i].uri},getValue:function(i){return this[i].value}},exports.XMLReader=XMLReader,exports.ParseError=ParseError},{"./conventions":41}],47:[function(require,module,exports){"use strict";function getLens(b64){var len=b64.length;if(len%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var validLen=b64.indexOf("=");-1===validLen&&(validLen=len);var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}function toByteArray(b64){var tmp,i,lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1],arr=new Arr(_byteLength(b64,validLen,placeHoldersLen)),curByte=0,len=placeHoldersLen>0?validLen-4:validLen;for(i=0;len>i;i+=4)tmp=revLookup[b64.charCodeAt(i)]<<18|revLookup[b64.charCodeAt(i+1)]<<12|revLookup[b64.charCodeAt(i+2)]<<6|revLookup[b64.charCodeAt(i+3)],arr[curByte++]=tmp>>16&255,arr[curByte++]=tmp>>8&255,arr[curByte++]=255&tmp;return 2===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[curByte++]=255&tmp),1===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[curByte++]=tmp>>8&255,arr[curByte++]=255&tmp),arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var tmp,output=[],i=start;end>i;i+=3)tmp=(uint8[i]<<16&16711680)+(uint8[i+1]<<8&65280)+(255&uint8[i+2]),output.push(tripletToBase64(tmp));return output.join("")}function fromByteArray(uint8){for(var tmp,len=uint8.length,extraBytes=len%3,parts=[],maxChunkLength=16383,i=0,len2=len-extraBytes;len2>i;i+=maxChunkLength)parts.push(encodeChunk(uint8,i,i+maxChunkLength>len2?len2:i+maxChunkLength));return 1===extraBytes?(tmp=uint8[len-1],parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"=")),parts.join("")}exports.byteLength=byteLength,exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;len>i;++i)lookup[i]=code[i],revLookup[code.charCodeAt(i)]=i;revLookup["-".charCodeAt(0)]=62,revLookup["_".charCodeAt(0)]=63},{}],48:[function(require,module,exports){(function(global){"use strict";function typedArraySupport(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()&&"function"==typeof arr.subarray&&0===arr.subarray(1,1).byteLength}catch(e){return!1}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(that,length){if(kMaxLength()size)throw new RangeError('"size" argument must not be negative')}function alloc(that,size,fill,encoding){return assertSize(size),0>=size?createBuffer(that,size):void 0!==fill?"string"==typeof encoding?createBuffer(that,size).fill(fill,encoding):createBuffer(that,size).fill(fill):createBuffer(that,size)}function allocUnsafe(that,size){if(assertSize(size),that=createBuffer(that,0>size?0:0|checked(size)),!Buffer.TYPED_ARRAY_SUPPORT)for(var i=0;size>i;++i)that[i]=0;return that}function fromString(that,string,encoding){if(("string"!=typeof encoding||""===encoding)&&(encoding="utf8"),!Buffer.isEncoding(encoding))throw new TypeError('"encoding" must be a valid string encoding');var length=0|byteLength(string,encoding);that=createBuffer(that,length);var actual=that.write(string,encoding);return actual!==length&&(that=that.slice(0,actual)),that}function fromArrayLike(that,array){var length=array.length<0?0:0|checked(array.length);that=createBuffer(that,length);for(var i=0;length>i;i+=1)that[i]=255&array[i];return that}function fromArrayBuffer(that,array,byteOffset,length){if(array.byteLength,0>byteOffset||array.byteLength=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|length}function SlowBuffer(length){return+length!=length&&(length=0),Buffer.alloc(+length)}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(string)||string instanceof ArrayBuffer))return string.byteLength;"string"!=typeof string&&(string=""+string);var len=string.length;if(0===len)return 0;for(var loweredCase=!1;;)switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":case void 0:return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||0>start)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),0>=end)return"";if(end>>>=0,start>>>=0,start>=end)return"";for(encoding||(encoding="utf8");;)switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):byteOffset>2147483647?byteOffset=2147483647:-2147483648>byteOffset&&(byteOffset=-2147483648),byteOffset=+byteOffset,isNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),0>byteOffset&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(0>byteOffset){if(!dir)return-1;byteOffset=0}if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val=255&val,Buffer.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}var indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&(encoding=String(encoding).toLowerCase(),"ucs2"===encoding||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(arr.length<2||val.length<2)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}var i;if(dir){var foundIndex=-1;for(i=byteOffset;arrLength>i;i++)if(read(arr,i)===read(val,-1===foundIndex?0:i-foundIndex)){if(-1===foundIndex&&(foundIndex=i),i-foundIndex+1===valLength)return foundIndex*indexSize}else-1!==foundIndex&&(i-=i-foundIndex),foundIndex=-1}else for(byteOffset+valLength>arrLength&&(byteOffset=arrLength-valLength),i=byteOffset;i>=0;i--){for(var found=!0,j=0;valLength>j;j++)if(read(arr,i+j)!==read(val,j)){found=!1;break}if(found)return i}return-1}function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;length?(length=Number(length),length>remaining&&(length=remaining)):length=remaining;var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");length>strLen/2&&(length=strLen/2);for(var i=0;length>i;++i){var parsed=parseInt(string.substr(2*i,2),16);if(isNaN(parsed))return i;buf[offset+i]=parsed}return i}function utf8Write(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length)}function asciiWrite(buf,string,offset,length){return blitBuffer(asciiToBytes(string),buf,offset,length)}function latin1Write(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length)}function ucs2Write(buf,string,offset,length){return blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length)}function base64Slice(buf,start,end){return 0===start&&end===buf.length?base64.fromByteArray(buf):base64.fromByteArray(buf.slice(start,end))}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);for(var res=[],i=start;end>i;){var firstByte=buf[i],codePoint=null,bytesPerSequence=firstByte>239?4:firstByte>223?3:firstByte>191?2:1;if(end>=i+bytesPerSequence){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:128>firstByte&&(codePoint=firstByte);break;case 2:secondByte=buf[i+1],128===(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte,tempCodePoint>127&&(codePoint=tempCodePoint));break;case 3:secondByte=buf[i+1],thirdByte=buf[i+2],128===(192&secondByte)&&128===(192&thirdByte)&&(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte,tempCodePoint>2047&&(55296>tempCodePoint||tempCodePoint>57343)&&(codePoint=tempCodePoint));break;case 4:secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128===(192&secondByte)&&128===(192&thirdByte)&&128===(192&fourthByte)&&(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte,tempCodePoint>65535&&1114112>tempCodePoint&&(codePoint=tempCodePoint))}}null===codePoint?(codePoint=65533,bytesPerSequence=1):codePoint>65535&&(codePoint-=65536,res.push(codePoint>>>10&1023|55296),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}function decodeCodePointsArray(codePoints){var len=codePoints.length;if(MAX_ARGUMENTS_LENGTH>=len)return String.fromCharCode.apply(String,codePoints);for(var res="",i=0;len>i;)res+=String.fromCharCode.apply(String,codePoints.slice(i,i+=MAX_ARGUMENTS_LENGTH));return res}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;end>i;++i)ret+=String.fromCharCode(127&buf[i]);return ret}function latin1Slice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;end>i;++i)ret+=String.fromCharCode(buf[i]);return ret}function hexSlice(buf,start,end){var len=buf.length;(!start||0>start)&&(start=0),(!end||0>end||end>len)&&(end=len);for(var out="",i=start;end>i;++i)out+=toHex(buf[i]);return out}function utf16leSlice(buf,start,end){for(var bytes=buf.slice(start,end),res="",i=0;ioffset)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||min>value)throw new RangeError('"value" argument is out of bounds');if(offset+ext>buf.length)throw new RangeError("Index out of range")}function objectWriteUInt16(buf,value,offset,littleEndian){0>value&&(value=65535+value+1);for(var i=0,j=Math.min(buf.length-offset,2);j>i;++i)buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>8*(littleEndian?i:1-i)}function objectWriteUInt32(buf,value,offset,littleEndian){0>value&&(value=4294967295+value+1);for(var i=0,j=Math.min(buf.length-offset,4);j>i;++i)buf[offset+i]=value>>>8*(littleEndian?i:3-i)&255}function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(0>offset)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){ +return noAssert||checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}function base64clean(str){if(str=stringtrim(str).replace(INVALID_BASE64_RE,""),str.length<2)return"";for(;str.length%4!==0;)str+="=";return str}function stringtrim(str){return str.trim?str.trim():str.replace(/^\s+|\s+$/g,"")}function toHex(n){return 16>n?"0"+n.toString(16):n.toString(16)}function utf8ToBytes(string,units){units=units||1/0;for(var codePoint,length=string.length,leadSurrogate=null,bytes=[],i=0;length>i;++i){if(codePoint=string.charCodeAt(i),codePoint>55295&&57344>codePoint){if(!leadSurrogate){if(codePoint>56319){(units-=3)>-1&&bytes.push(239,191,189);continue}if(i+1===length){(units-=3)>-1&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(56320>codePoint){(units-=3)>-1&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else leadSurrogate&&(units-=3)>-1&&bytes.push(239,191,189);if(leadSurrogate=null,128>codePoint){if((units-=1)<0)break;bytes.push(codePoint)}else if(2048>codePoint){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(65536>codePoint){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(1114112>codePoint))throw new Error("Invalid code point");if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,63&codePoint|128)}}return bytes}function asciiToBytes(str){for(var byteArray=[],i=0;i>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;length>i&&!(i+offset>=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isnan(val){return val!==val}var base64=require("base64-js"),ieee754=require("ieee754"),isArray=require("isarray");exports.Buffer=Buffer,exports.SlowBuffer=SlowBuffer,exports.INSPECT_MAX_BYTES=50,Buffer.TYPED_ARRAY_SUPPORT=void 0!==global.TYPED_ARRAY_SUPPORT?global.TYPED_ARRAY_SUPPORT:typedArraySupport(),exports.kMaxLength=kMaxLength(),Buffer.poolSize=8192,Buffer._augment=function(arr){return arr.__proto__=Buffer.prototype,arr},Buffer.from=function(value,encodingOrOffset,length){return from(null,value,encodingOrOffset,length)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0})),Buffer.alloc=function(size,fill,encoding){return alloc(null,size,fill,encoding)},Buffer.allocUnsafe=function(size){return allocUnsafe(null,size)},Buffer.allocUnsafeSlow=function(size){return allocUnsafe(null,size)},Buffer.isBuffer=function(b){return!(null==b||!b._isBuffer)},Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);len>i;++i)if(a[i]!==b[i]){x=a[i],y=b[i];break}return y>x?-1:x>y?1:0},Buffer.isEncoding=function(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},Buffer.concat=function(list,length){if(!isArray(list))throw new TypeError('"list" argument must be an Array of Buffers');if(0===list.length)return Buffer.alloc(0);var i;if(void 0===length)for(length=0,i=0;ii;i+=2)swap(this,i,i+1);return this},Buffer.prototype.swap32=function(){var len=this.length;if(len%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var i=0;len>i;i+=4)swap(this,i,i+3),swap(this,i+1,i+2);return this},Buffer.prototype.swap64=function(){var len=this.length;if(len%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var i=0;len>i;i+=8)swap(this,i,i+7),swap(this,i+1,i+6),swap(this,i+2,i+5),swap(this,i+3,i+4);return this},Buffer.prototype.toString=function(){var length=0|this.length;return 0===length?"":0===arguments.length?utf8Slice(this,0,length):slowToString.apply(this,arguments)},Buffer.prototype.equals=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return this===b?!0:0===Buffer.compare(this,b)},Buffer.prototype.inspect=function(){var str="",max=exports.INSPECT_MAX_BYTES;return this.length>0&&(str=this.toString("hex",0,max).match(/.{2}/g).join(" "),this.length>max&&(str+=" ... ")),""},Buffer.prototype.compare=function(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target))throw new TypeError("Argument must be a Buffer");if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),0>start||end>target.length||0>thisStart||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;if(start>>>=0,end>>>=0,thisStart>>>=0,thisEnd>>>=0,this===target)return 0;for(var x=thisEnd-thisStart,y=end-start,len=Math.min(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;len>i;++i)if(thisCopy[i]!==targetCopy[i]){x=thisCopy[i],y=targetCopy[i];break}return y>x?-1:x>y?1:0},Buffer.prototype.includes=function(val,byteOffset,encoding){return-1!==this.indexOf(val,byteOffset,encoding)},Buffer.prototype.indexOf=function(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,!0)},Buffer.prototype.lastIndexOf=function(val,byteOffset,encoding){return bidirectionalIndexOf(this,val,byteOffset,encoding,!1)},Buffer.prototype.write=function(string,offset,length,encoding){if(void 0===offset)encoding="utf8",length=this.length,offset=0;else if(void 0===length&&"string"==typeof offset)encoding=offset,length=this.length,offset=0;else{if(!isFinite(offset))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");offset=0|offset,isFinite(length)?(length=0|length,void 0===encoding&&(encoding="utf8")):(encoding=length,length=void 0)}var remaining=this.length-offset;if((void 0===length||length>remaining)&&(length=remaining),string.length>0&&(0>length||0>offset)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start,end=void 0===end?len:~~end,0>start?(start+=len,0>start&&(start=0)):start>len&&(start=len),0>end?(end+=len,0>end&&(end=0)):end>len&&(end=len),start>end&&(end=start);var newBuf;if(Buffer.TYPED_ARRAY_SUPPORT)newBuf=this.subarray(start,end),newBuf.__proto__=Buffer.prototype;else{var sliceLen=end-start;newBuf=new Buffer(sliceLen,void 0);for(var i=0;sliceLen>i;++i)newBuf[i]=this[i+start]}return newBuf},Buffer.prototype.readUIntLE=function(offset,byteLength,noAssert){offset=0|offset,byteLength=0|byteLength,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i0&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset=0|offset,byteLength=0|byteLength,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset=0|offset,byteLength=0|byteLength,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];i>0&&(mul*=256);)val+=this[offset+--i]*mul;return mul*=128,val>=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),128&this[offset]?-1*(255-this[offset]+1):this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset=0|offset,byteLength=0|byteLength,!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1,i=0;for(this[offset]=255&value;++i=0&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset=0|offset,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++ivalue&&0===sub&&0!==this[offset+i-1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset=0|offset,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)0>value&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),0>value&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset=0|offset,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),0>value&&(value=4294967295+value+1),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),end>0&&start>end&&(end=start),end===start)return 0;if(0===target.length||0===this.length)return 0;if(0>targetStart)throw new RangeError("targetStart out of bounds");if(0>start||start>=this.length)throw new RangeError("sourceStart out of bounds");if(0>end)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStartstart&&end>targetStart)for(i=len-1;i>=0;--i)target[i+targetStart]=this[i+start];else if(1e3>len||!Buffer.TYPED_ARRAY_SUPPORT)for(i=0;len>i;++i)target[i+targetStart]=this[i+start];else Uint8Array.prototype.set.call(target,this.subarray(start,start+len),targetStart);return len},Buffer.prototype.fill=function(val,start,end,encoding){if("string"==typeof val){if("string"==typeof start?(encoding=start,start=0,end=this.length):"string"==typeof end&&(encoding=end,end=this.length),1===val.length){var code=val.charCodeAt(0);256>code&&(val=code)}if(void 0!==encoding&&"string"!=typeof encoding)throw new TypeError("encoding must be a string");if("string"==typeof encoding&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding)}else"number"==typeof val&&(val=255&val);if(0>start||this.length=end)return this;start>>>=0,end=void 0===end?this.length:end>>>0,val||(val=0);var i;if("number"==typeof val)for(i=start;end>i;++i)this[i]=val;else{var bytes=Buffer.isBuffer(val)?val:utf8ToBytes(new Buffer(val,encoding).toString()),len=bytes.length;for(i=0;end-start>i;++i)this[i+start]=bytes[i%len]}return this};var INVALID_BASE64_RE=/[^+\/0-9A-Za-z-_]/g}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"base64-js":47,ieee754:51,isarray:52}],49:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var dingbats={SYMBOL:{32:32,33:33,34:8704,35:35,36:8707,37:37,38:38,39:8717,40:40,41:41,42:42,43:43,44:44,45:8722,46:46,47:47,48:48,49:49,50:50,51:51,52:52,53:53,54:54,55:55,56:56,57:57,58:58,59:59,60:60,61:61,62:62,63:63,64:8773,65:913,66:914,67:935,68:916,69:917,70:934,71:915,72:919,73:921,74:977,75:922,76:923,77:924,78:925,79:927,80:928,81:920,82:929,83:931,84:932,85:933,86:962,87:937,88:926,89:936,90:918,91:91,92:8756,93:93,94:8869,95:95,96:8254,97:945,98:946,99:967,100:948,101:949,102:966,103:947,104:951,105:953,106:981,107:954,108:955,109:956,110:957,111:959,112:960,113:952,114:961,115:963,116:964,117:965,118:982,119:969,120:958,121:968,122:950,123:123,124:124,125:125,126:126,160:8364,161:978,162:8242,163:8804,164:8260,165:8734,166:402,167:9827,168:9830,169:9829,170:9824,171:8596,172:8592,173:8593,174:8594,175:8595,176:176,177:177,178:8243,179:8805,180:215,181:8733,182:8706,183:8226,184:247,185:8800,186:8801,187:8776,188:8230,189:9168,190:9135,191:8629,192:8501,193:8465,194:8476,195:8472,196:8855,197:8853,198:8709,199:8745,200:8746,201:8835,202:8839,203:8836,204:8834,205:8838,206:8712,207:8713,208:8736,209:8711,210:174,211:169,212:8482,213:8719,214:8730,215:8901,216:172,217:8743,218:8744,219:8660,220:8656,221:8657,222:8658,223:8659,224:9674,225:12296,226:174,227:169,228:8482,229:8721,230:9115,231:9116,232:9117,233:9121,234:9122,235:9123,236:9127,237:9128,238:9129,239:9130,240:63743,241:12297,242:8747,243:8992,244:9134,245:8993,246:9118,247:9119,248:9120,249:9124,250:9125,251:9126,252:9131,253:9132,254:9133},WEBDINGS:{32:32,33:128375,34:128376,35:128370,36:128374,37:127942,38:127894,39:128391,40:128488,41:128489,42:128496,43:128497,44:127798,45:127895,46:128638,47:128636,48:128469,49:128470,50:128471,51:9204,52:9205,53:9206,54:9207,55:9194,56:9193,57:9198,58:9197,59:9208,60:9209,61:9210,62:128474,63:128499,64:128736,65:127959,66:127960,67:127961,68:127962,69:127964,70:127981,71:127963,72:127968,73:127958,74:127965,75:128739,76:128269,77:127956,78:128065,79:128066,80:127966,81:127957,82:128740,83:127967,84:128755,85:128364,86:128363,87:128360,88:128264,89:127892,90:127893,91:128492,92:128637,93:128493,94:128490,95:128491,96:11156,97:10004,98:128690,99:11036,100:128737,101:128230,102:128753,103:11035,104:128657,105:128712,106:128745,107:128752,108:128968,109:128372,110:11044,111:128741,112:128660,113:128472,114:128473,115:10067,116:128754,117:128647,118:128653,119:9971,120:10680,121:8854,122:128685,123:128494,124:9168,125:128495,126:128498,128:128697,129:128698,130:128713,131:128714,132:128700,133:128125,134:127947,135:9975,136:127938,137:127948,138:127946,139:127940,140:127949,141:127950,142:128664,143:128480,144:128738,145:128176,146:127991,147:128179,148:128106,149:128481,150:128482,151:128483,152:10031,153:128388,154:128389,155:128387,156:128390,157:128441,158:128442,159:128443,160:128373,161:128368,162:128445,163:128446,164:128203,165:128466,166:128467,167:128366,168:128218,169:128478,170:128479,171:128451,172:128450,173:128444,174:127917,175:127900,176:127896,177:127897,178:127911,179:128191,180:127902,181:128247,182:127903,183:127916,184:128253,185:128249,186:128254,187:128251,188:127898,189:127899,190:128250,191:128187,192:128421,193:128422,194:128423,195:128377,196:127918,197:128379,198:128380,199:128223,200:128385,201:128384,202:128424,203:128425,204:128447,205:128426,206:128476,207:128274,208:128275,209:128477,210:128229,211:128228,212:128371,213:127779,214:127780,215:127781,216:127782,217:9729,218:127784,219:127783,220:127785,221:127786,222:127788,223:127787,224:127772,225:127777,226:128715,227:128719,228:127869,229:127864,230:128718,231:128717,232:9413,233:9855,234:128710,235:128392,236:127891,237:128484,238:128485,239:128486,240:128487,241:128746,242:128063,243:128038,244:128031,245:128021,246:128008,247:128620,248:128622,249:128621,250:128623,251:128506,252:127757,253:127759,254:127758,255:128330},WINGDINGS:{32:32,33:128393,34:9986,35:9985,36:128083,37:128365,38:128366,39:128367,40:128383,41:9990,42:128386,43:128387,44:128234,45:128235,46:128236,47:128237,48:128448,49:128449,50:128462,51:128463,52:128464,53:128452,54:8987,55:128430,56:128432,57:128434,58:128435,59:128436,60:128427,61:128428,62:9991,63:9997,64:128398,65:9996,66:128399,67:128077,68:128078,69:9756,70:9758,71:9757,72:9759,73:128400,74:9786,75:128528,76:9785,77:128163,78:128369,79:127987,80:127985,81:9992,82:9788,83:127778,84:10052,85:128326,86:10014,87:128328,88:10016,89:10017,90:9770,91:9775,92:128329,93:9784,94:9800,95:9801,96:9802,97:9803,98:9804,99:9805,100:9806,101:9807,102:9808,103:9809,104:9810,105:9811,106:128624,107:128629,108:9899,109:128318,110:9724,111:128911,112:128912,113:10065,114:10066,115:128927,116:10731,117:9670,118:10070,119:11049,120:8999,121:11193,122:8984,123:127989,124:127990,125:128630,126:128631,127:9647,128:127243,129:10112,130:10113,131:10114,132:10115,133:10116,134:10117,135:10118,136:10119,137:10120,138:10121,139:127244,140:10122,141:10123,142:10124,143:10125,144:10126,145:10127,146:10128,147:10129,148:10130,149:10131,150:128610,151:128608,152:128609,153:128611,154:128606,155:128604,156:128605,157:128607,158:8729,159:8226,160:11037,161:11096,162:128902,163:128904,164:128906,165:128907,166:128319,167:9642,168:128910,169:128961,170:128965,171:9733,172:128971,173:128975,174:128979,175:128977,176:11216,177:8982,178:11214,179:11215,180:11217,181:10026,182:10032,183:128336,184:128337,185:128338,186:128339,187:128340,188:128341,189:128342,190:128343,191:128344,192:128345,193:128346,194:128347,195:11184,196:11185,197:11186,198:11187,199:11188,200:11189,201:11190,202:11191,203:128618,204:128619,205:128597,206:128596,207:128599,208:128598,209:128592,210:128593,211:128594,212:128595,213:9003,214:8998,215:11160,216:11162,217:11161,218:11163,219:11144,220:11146,221:11145,222:11147,223:129128,224:129130,225:129129,226:129131,227:129132,228:129133,229:129135,230:129134,231:129144,232:129146,233:129145,234:129147,235:129148,236:129149,237:129151,238:129150,239:8678,240:8680,241:8679,242:8681,243:11012,244:8691,245:11009,246:11008,247:11011,248:11010,249:129196,250:129197,251:128502,252:10003,253:128503,254:128505},"WINGDINGS 2":{32:32,33:128394,34:128395,35:128396,36:128397,37:9988,38:9984,39:128382,40:128381,41:128453,42:128454,43:128455,44:128456,45:128457,46:128458,47:128459,48:128460,49:128461,50:128203,51:128465,52:128468,53:128437,54:128438,55:128439,56:128440,57:128429,58:128431,59:128433,60:128402,61:128403,62:128408,63:128409,64:128410,65:128411,66:128072,67:128073,68:128412,69:128413,70:128414,71:128415,72:128416,73:128417,74:128070,75:128071,76:128418,77:128419,78:128401,79:128500,80:128504,81:128501,82:9745,83:11197,84:9746,85:11198,86:11199,87:128711,88:10680,89:128625,90:128628,91:128626,92:128627,93:8253,94:128633,95:128634,96:128635,97:128614,98:128612,99:128613,100:128615,101:128602,102:128600,103:128601,104:128603,105:9450,106:9312,107:9313,108:9314,109:9315,110:9316,111:9317,112:9318,113:9319,114:9320,115:9321,116:9471,117:10102,118:10103,119:10104,120:10105,121:10106,122:10107,123:10108,124:10109,125:10110,126:10111,128:9737,129:127765,130:9789,131:9790,132:11839,133:10013,134:128327,135:128348,136:128349,137:128350,138:128351,139:128352,140:128353,141:128354,142:128355,143:128356,144:128357,145:128358,146:128359,147:128616,148:128617,149:8901,150:128900,151:10625,152:9679,153:9675,154:128901,155:128903,156:128905,157:8857,158:10687,159:128908,160:128909,161:9726,162:9632,163:9633,164:128913,165:128914,166:128915,167:128916,168:9635,169:128917,170:128918,171:128919,172:128920,173:11049,174:11045,175:9671,176:128922,177:9672,178:128923,179:128924,180:128925,181:128926,182:11050,183:11047,184:9674,185:128928,186:9686,187:9687,188:11210,189:11211,190:11200,191:11201,192:11039,193:11202,194:11043,195:11042,196:11203,197:11204,198:128929,199:128930,200:128931,201:128932,202:128933,203:128934,204:128935,205:128936,206:128937,207:128938,208:128939,209:128940,210:128941,211:128942,212:128943,213:128944,214:128945,215:128946,216:128947,217:128948,218:128949,219:128950,220:128951,221:128952,222:128953,223:128954,224:128955,225:128956,226:128957,227:128958,228:128959,229:128960,230:128962,231:128964,232:128966,233:128969,234:128970,235:10038,236:128972,237:128974,238:128976,239:128978,240:10041,241:128963,242:128967,243:10031,244:128973,245:128980,246:11212,247:11213,248:8251,249:8258},"WINGDINGS 3":{32:32,33:11104,34:11106,35:11105,36:11107,37:11110,38:11111,39:11113,40:11112,41:11120,42:11122,43:11121,44:11123,45:11126,46:11128,47:11131,48:11133,49:11108,50:11109,51:11114,52:11116,53:11115,54:11117,55:11085,56:11168,57:11169,58:11170,59:11171,60:11172,61:11173,62:11174,63:11175,64:11152,65:11153,66:11154,67:11155,68:11136,69:11139,70:11134,71:11135,72:11140,73:11142,74:11141,75:11143,76:11151,77:11149,78:11150,79:11148,80:11118,81:11119,82:9099,83:8996,84:8963,85:8997,86:9251,87:9085,88:8682,89:11192,90:129184,91:129185,92:129186,93:129187,94:129188,95:129189,96:129190,97:129191,98:129192,99:129193,100:129194,101:129195,102:129104,103:129106,104:129105,105:129107,106:129108,107:129109,108:129111,109:129110,110:129112,111:129113,112:9650,113:9660,114:9651,115:9661,116:9664,117:9654,118:9665,119:9655,120:9699,121:9698,122:9700,123:9701,124:128896,125:128898,126:128897,128:128899,129:11205,130:11206,131:11207,132:11208,133:11164,134:11166,135:11165,136:11167,137:129040,138:129042,139:129041,140:129043,141:129044,142:129046,143:129045,144:129047,145:129048,146:129050,147:129049,148:129051,149:129052,150:129054,151:129053,152:129055,153:129024,154:129026,155:129025,156:129027,157:129028,158:129030,159:129029,160:129031,161:129032,162:129034,163:129033,164:129035,165:129056,166:129058,167:129060,168:129062,169:129064,170:129066,171:129068,172:129180,173:129181,174:129182,175:129183,176:129070,177:129072,178:129074,179:129076,180:129078,181:129080,182:129082,183:129081,184:129083,185:129176,186:129178,187:129177,188:129179,189:129084,190:129086,191:129085,192:129087,193:129088,194:129090,195:129089,196:129091,197:129092,198:129094,199:129093,200:129095,201:11176,202:11177,203:11178,204:11179,205:11180,206:11181,207:11182,208:11183,209:129120,210:129122,211:129121,212:129123,213:129124,214:129125,215:129127,216:129126,217:129136,218:129138,219:129137,220:129139,221:129140,222:129141,223:129143,224:129142,225:129152,226:129154,227:129153,228:129155,229:129156,230:129157,231:129159,232:129158,233:129168,234:129170,235:129169,236:129171,237:129172,238:129174,239:129173,240:129175}};exports["default"]=dingbats},{}],50:[function(require,module,exports){"use strict";function codePoint(typeface,codePoint){var codePointMap=dingbats_1["default"][typeface.toUpperCase()];if(void 0===codePointMap)return void 0;var unicodeCodePoint=codePointMap[codePoint];return void 0===unicodeCodePoint?void 0:{codePoint:unicodeCodePoint,string:fromCodePoint(unicodeCodePoint)}}function dec(typeface,dec){return codePoint(typeface,parseInt(dec,10))}function hex(typeface,hex){return codePoint(typeface,parseInt(hex,16))}function fromCodePointPolyfill(codePoint){if(65535>=codePoint)return String.fromCharCode(codePoint);var highSurrogate=Math.floor((codePoint-65536)/1024)+55296,lowSurrogate=(codePoint-65536)%1024+56320;return String.fromCharCode(highSurrogate,lowSurrogate)}var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{"default":mod}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.hex=exports.dec=exports.codePoint=void 0;var dingbats_1=__importDefault(require("./dingbats")),fromCodePoint=String.fromCodePoint?String.fromCodePoint:fromCodePointPolyfill;exports.codePoint=codePoint,exports.dec=dec,exports.hex=hex},{"./dingbats":49}],51:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=8*nBytes-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:(s?-1:1)*(1/0);m+=Math.pow(2,mLen),e-=eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)},exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=8*nBytes-mLen-1,eMax=(1<>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=0>value||0===value&&0>1/value?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(c=Math.pow(2,-e))<1&&(e--,c*=2),value+=e+eBias>=1?rt/c:rt*Math.pow(2,1-eBias),value*c>=2&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):e+eBias>=1?(m=(value*c-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));mLen>=8;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<0;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},{}],52:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr)}},{}],53:[function(require,module,exports){(function(global,Buffer){!function(t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).JSZip=t(); +}(function(){return function s(a,o,h){function u(r,t){if(!o[r]){if(!a[r]){var e="function"==typeof require&&require;if(!t&&e)return e(r,!0);if(l)return l(r,!0);var i=new Error("Cannot find module '"+r+"'");throw i.code="MODULE_NOT_FOUND",i}var n=o[r]={exports:{}};a[r][0].call(n.exports,function(t){var e=a[r][1][t];return u(e||t)},n,n.exports,s,a,o,h)}return o[r].exports}for(var l="function"==typeof require&&require,t=0;tu?t[u++]:0,l>u?t[u++]:0):(e=t.charCodeAt(u++),r=l>u?t.charCodeAt(u++):0,l>u?t.charCodeAt(u++):0),n=e>>2,s=(3&e)<<4|r>>4,a=f>1?(15&r)<<2|i>>6:64,o=f>2?63&i:64,h.push(p.charAt(n)+p.charAt(s)+p.charAt(a)+p.charAt(o));return h.join("")},r.decode=function(t){var e,r,i,n,s,a,o=0,h=0,u="data:";if(t.substr(0,u.length)===u)throw new Error("Invalid base64 input, it looks like a data url.");var l,f=3*(t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"")).length/4;if(t.charAt(t.length-1)===p.charAt(64)&&f--,t.charAt(t.length-2)===p.charAt(64)&&f--,f%1!=0)throw new Error("Invalid base64 input, bad content length.");for(l=d.uint8array?new Uint8Array(0|f):new Array(0|f);o>4,r=(15&n)<<4|(s=p.indexOf(t.charAt(o++)))>>2,i=(3&s)<<6|(a=p.indexOf(t.charAt(o++))),l[h++]=e,64!==s&&(l[h++]=r),64!==a&&(l[h++]=i);return l}},{"./support":30,"./utils":32}],2:[function(t,e,r){"use strict";function o(t,e,r,i,n){this.compressedSize=t,this.uncompressedSize=e,this.crc32=r,this.compression=i,this.compressedContent=n}var i=t("./external"),n=t("./stream/DataWorker"),s=t("./stream/Crc32Probe"),a=t("./stream/DataLengthProbe");o.prototype={getContentWorker:function(){var t=new n(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new a("data_length")),e=this;return t.on("end",function(){if(this.streamInfo.data_length!==e.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),t},getCompressedWorker:function(){return new n(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},o.createWorkerFrom=function(t,e,r){return t.pipe(new s).pipe(new a("uncompressedSize")).pipe(e.compressWorker(r)).pipe(new a("compressedSize")).withStreamInfo("compression",e)},e.exports=o},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(t,e,r){"use strict";var i=t("./stream/GenericWorker");r.STORE={magic:"\x00\x00",compressWorker:function(t){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},r.DEFLATE=t("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(t,e,r){"use strict";var i=t("./utils"),o=function(){for(var t,e=[],r=0;256>r;r++){t=r;for(var i=0;8>i;i++)t=1&t?3988292384^t>>>1:t>>>1;e[r]=t}return e}();e.exports=function(t,e){return void 0!==t&&t.length?"string"!==i.getTypeOf(t)?function(t,e,r,i){var n=o,s=i+r;t^=-1;for(var a=i;s>a;a++)t=t>>>8^n[255&(t^e[a])];return-1^t}(0|e,t,t.length,0):function(t,e,r,i){var n=o,s=i+r;t^=-1;for(var a=i;s>a;a++)t=t>>>8^n[255&(t^e.charCodeAt(a))];return-1^t}(0|e,t,t.length,0):0}},{"./utils":32}],5:[function(t,e,r){"use strict";r.base64=!1,r.binary=!1,r.dir=!1,r.createFolders=!0,r.date=null,r.compression=null,r.compressionOptions=null,r.comment=null,r.unixPermissions=null,r.dosPermissions=null},{}],6:[function(t,e,r){"use strict";var i=null;i="undefined"!=typeof Promise?Promise:t("lie"),e.exports={Promise:i}},{lie:37}],7:[function(t,e,r){"use strict";function h(t,e){a.call(this,"FlateWorker/"+t),this._pako=null,this._pakoAction=t,this._pakoOptions=e,this.meta={}}var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,n=t("pako"),s=t("./utils"),a=t("./stream/GenericWorker"),o=i?"uint8array":"array";r.magic="\b\x00",s.inherits(h,a),h.prototype.processChunk=function(t){this.meta=t.meta,null===this._pako&&this._createPako(),this._pako.push(s.transformTo(o,t.data),!1)},h.prototype.flush=function(){a.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},h.prototype.cleanUp=function(){a.prototype.cleanUp.call(this),this._pako=null},h.prototype._createPako=function(){this._pako=new n[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}},r.compressWorker=function(t){return new h("Deflate",t)},r.uncompressWorker=function(){return new h("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(t,e,r){"use strict";function A(t,e){var r,i="";for(r=0;e>r;r++)i+=String.fromCharCode(255&t),t>>>=8;return i}function i(t,e,r,i,n,s){var a,o,h=t.file,u=t.compression,l=s!==O.utf8encode,f=I.transformTo("string",s(h.name)),d=I.transformTo("string",O.utf8encode(h.name)),c=h.comment,p=I.transformTo("string",s(c)),m=I.transformTo("string",O.utf8encode(c)),_=d.length!==h.name.length,g=m.length!==c.length,b="",v="",y="",w=h.dir,k=h.date,x={crc32:0,compressedSize:0,uncompressedSize:0};e&&!r||(x.crc32=t.crc32,x.compressedSize=t.compressedSize,x.uncompressedSize=t.uncompressedSize);var S=0;e&&(S|=8),l||!_&&!g||(S|=2048);var z=0,C=0;w&&(z|=16),"UNIX"===n?(C=798,z|=function(t,e){var r=t;return t||(r=e?16893:33204),(65535&r)<<16}(h.unixPermissions,w)):(C=20,z|=function(t){return 63&(t||0)}(h.dosPermissions)),a=k.getUTCHours(),a<<=6,a|=k.getUTCMinutes(),a<<=5,a|=k.getUTCSeconds()/2,o=k.getUTCFullYear()-1980,o<<=4,o|=k.getUTCMonth()+1,o<<=5,o|=k.getUTCDate(),_&&(v=A(1,1)+A(B(f),4)+d,b+="up"+A(v.length,2)+v),g&&(y=A(1,1)+A(B(p),4)+m,b+="uc"+A(y.length,2)+y);var E="";return E+="\n\x00",E+=A(S,2),E+=u.magic,E+=A(a,2),E+=A(o,2),E+=A(x.crc32,4),E+=A(x.compressedSize,4),E+=A(x.uncompressedSize,4),E+=A(f.length,2),E+=A(b.length,2),{fileRecord:R.LOCAL_FILE_HEADER+E+f+b,dirRecord:R.CENTRAL_FILE_HEADER+A(C,2)+E+A(p.length,2)+"\x00\x00\x00\x00"+A(z,4)+A(i,4)+f+b+p}}function s(t,e,r,i){n.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=e,this.zipPlatform=r,this.encodeFileName=i,this.streamFiles=t,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}var I=t("../utils"),n=t("../stream/GenericWorker"),O=t("../utf8"),B=t("../crc32"),R=t("../signature");I.inherits(s,n),s.prototype.push=function(t){var e=t.meta.percent||0,r=this.entriesCount,i=this._sources.length;this.accumulate?this.contentBuffer.push(t):(this.bytesWritten+=t.data.length,n.prototype.push.call(this,{data:t.data,meta:{currentFile:this.currentFile,percent:r?(e+100*(r-i-1))/r:100}}))},s.prototype.openedSource=function(t){this.currentSourceOffset=this.bytesWritten,this.currentFile=t.file.name;var e=this.streamFiles&&!t.file.dir;if(e){var r=i(t,e,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:r.fileRecord,meta:{percent:0}})}else this.accumulate=!0},s.prototype.closedSource=function(t){this.accumulate=!1;var e=this.streamFiles&&!t.file.dir,r=i(t,e,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(r.dirRecord),e)this.push({data:function(t){return R.DATA_DESCRIPTOR+A(t.crc32,4)+A(t.compressedSize,4)+A(t.uncompressedSize,4)}(t),meta:{percent:100}});else for(this.push({data:r.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},s.prototype.flush=function(){for(var t=this.bytesWritten,e=0;e0?t.substring(0,e):""},g=function(t){return"/"!==t.slice(-1)&&(t+="/"),t},b=function(t,e){return e=void 0!==e?e:f.createFolders,t=g(t),this.files[t]||s.call(this,t,null,{dir:!0,createFolders:e}),this.files[t]},i={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(t){var e,r,i;for(e in this.files)i=this.files[e],(r=e.slice(this.root.length,e.length))&&e.slice(0,this.root.length)===this.root&&t(r,i)},filter:function(r){var i=[];return this.forEach(function(t,e){r(t,e)&&i.push(e)}),i},file:function(t,e,r){if(1!==arguments.length)return t=this.root+t,s.call(this,t,e,r),this;if(h(t)){var i=t;return this.filter(function(t,e){return!e.dir&&i.test(t)})}var n=this.files[this.root+t];return n&&!n.dir?n:null},folder:function(r){if(!r)return this;if(h(r))return this.filter(function(t,e){return e.dir&&r.test(t)});var t=this.root+r,e=b.call(this,t),i=this.clone();return i.root=e.name,i},remove:function(r){r=this.root+r;var t=this.files[r];if(t||("/"!==r.slice(-1)&&(r+="/"),t=this.files[r]),t&&!t.dir)delete this.files[r];else for(var e=this.filter(function(t,e){return e.name.slice(0,r.length)===r}),i=0;i=0;--s)if(this.data[s]===e&&this.data[s+1]===r&&this.data[s+2]===i&&this.data[s+3]===n)return s-this.zero;return-1},n.prototype.readAndCheckSignature=function(t){var e=t.charCodeAt(0),r=t.charCodeAt(1),i=t.charCodeAt(2),n=t.charCodeAt(3),s=this.readData(4);return e===s[0]&&r===s[1]&&i===s[2]&&n===s[3]},n.prototype.readData=function(t){if(this.checkOffset(t),0===t)return[];var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=n},{"../utils":32,"./DataReader":18}],18:[function(t,e,r){"use strict";function n(t){this.data=t,this.length=t.length,this.index=0,this.zero=0}var i=t("../utils");n.prototype={checkOffset:function(t){this.checkIndex(this.index+t)},checkIndex:function(t){if(this.lengtht)throw new Error("End of data reached (data length = "+this.length+", asked index = "+t+"). Corrupted zip ?")},setIndex:function(t){this.checkIndex(t),this.index=t},skip:function(t){this.setIndex(this.index+t)},byteAt:function(t){},readInt:function(t){var e,r=0;for(this.checkOffset(t),e=this.index+t-1;e>=this.index;e--)r=(r<<8)+this.byteAt(e);return this.index+=t,r},readString:function(t){return i.transformTo("string",this.readData(t))},readData:function(t){},lastIndexOfSignature:function(t){},readAndCheckSignature:function(t){},readDate:function(){var t=this.readInt(4);return new Date(Date.UTC(1980+(t>>25&127),(t>>21&15)-1,t>>16&31,t>>11&31,t>>5&63,(31&t)<<1))}},e.exports=n},{"../utils":32}],19:[function(t,e,r){"use strict";function n(t){i.call(this,t)}var i=t("./Uint8ArrayReader");t("../utils").inherits(n,i),n.prototype.readData=function(t){this.checkOffset(t);var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=n},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(t,e,r){"use strict";function n(t){i.call(this,t)}var i=t("./DataReader");t("../utils").inherits(n,i),n.prototype.byteAt=function(t){return this.data.charCodeAt(this.zero+t)},n.prototype.lastIndexOfSignature=function(t){return this.data.lastIndexOf(t)-this.zero},n.prototype.readAndCheckSignature=function(t){return t===this.readData(4)},n.prototype.readData=function(t){this.checkOffset(t);var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=n},{"../utils":32,"./DataReader":18}],21:[function(t,e,r){"use strict";function n(t){i.call(this,t)}var i=t("./ArrayReader");t("../utils").inherits(n,i),n.prototype.readData=function(t){if(this.checkOffset(t),0===t)return new Uint8Array(0);var e=this.data.subarray(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=n},{"../utils":32,"./ArrayReader":17}],22:[function(t,e,r){"use strict";var i=t("../utils"),n=t("../support"),s=t("./ArrayReader"),a=t("./StringReader"),o=t("./NodeBufferReader"),h=t("./Uint8ArrayReader");e.exports=function(t){var e=i.getTypeOf(t);return i.checkSupport(e),"string"!==e||n.uint8array?"nodebuffer"===e?new o(t):n.uint8array?new h(i.transformTo("uint8array",t)):new s(i.transformTo("array",t)):new a(t)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(t,e,r){"use strict";r.LOCAL_FILE_HEADER="PK",r.CENTRAL_FILE_HEADER="PK",r.CENTRAL_DIRECTORY_END="PK",r.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",r.ZIP64_CENTRAL_DIRECTORY_END="PK",r.DATA_DESCRIPTOR="PK\b"},{}],24:[function(t,e,r){"use strict";function s(t){i.call(this,"ConvertWorker to "+t),this.destType=t}var i=t("./GenericWorker"),n=t("../utils");n.inherits(s,i),s.prototype.processChunk=function(t){this.push({data:n.transformTo(this.destType,t.data),meta:t.meta})},e.exports=s},{"../utils":32,"./GenericWorker":28}],25:[function(t,e,r){"use strict";function s(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}var i=t("./GenericWorker"),n=t("../crc32");t("../utils").inherits(s,i),s.prototype.processChunk=function(t){this.streamInfo.crc32=n(t.data,this.streamInfo.crc32||0),this.push(t)},e.exports=s},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(t,e,r){"use strict";function s(t){n.call(this,"DataLengthProbe for "+t),this.propName=t,this.withStreamInfo(t,0)}var i=t("../utils"),n=t("./GenericWorker");i.inherits(s,n),s.prototype.processChunk=function(t){if(t){var e=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=e+t.data.length}n.prototype.processChunk.call(this,t)},e.exports=s},{"../utils":32,"./GenericWorker":28}],27:[function(t,e,r){"use strict";function s(t){n.call(this,"DataWorker");var e=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,t.then(function(t){e.dataIsReady=!0,e.data=t,e.max=t&&t.length||0,e.type=i.getTypeOf(t),e.isPaused||e._tickAndRepeat()},function(t){e.error(t)})}var i=t("../utils"),n=t("./GenericWorker");i.inherits(s,n),s.prototype.cleanUp=function(){n.prototype.cleanUp.call(this),this.data=null},s.prototype.resume=function(){return!!n.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},s.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},s.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var t=null,e=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":t=this.data.substring(this.index,e);break;case"uint8array":t=this.data.subarray(this.index,e);break;case"array":case"nodebuffer":t=this.data.slice(this.index,e)}return this.index=e,this.push({data:t,meta:{percent:this.max?this.index/this.max*100:0}})},e.exports=s},{"../utils":32,"./GenericWorker":28}],28:[function(t,e,r){"use strict";function i(t){this.name=t||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}i.prototype={push:function(t){this.emit("data",t)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(t){this.emit("error",t)}return!0},error:function(t){return!this.isFinished&&(this.isPaused?this.generatedError=t:(this.isFinished=!0,this.emit("error",t),this.previous&&this.previous.error(t),this.cleanUp()),!0)},on:function(t,e){return this._listeners[t].push(e),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(t,e){if(this._listeners[t])for(var r=0;r "+t:t}},e.exports=i},{}],29:[function(t,e,r){"use strict";function l(t,o){return new a.Promise(function(e,r){var i=[],n=t._internalType,s=t._outputType,a=t._mimeType;t.on("data",function(t,e){i.push(t),o&&o(e)}).on("error",function(t){i=[],r(t)}).on("end",function(){try{var t=function(t,e,r){switch(t){case"blob":return h.newBlob(h.transformTo("arraybuffer",e),r);case"base64":return u.encode(e);default:return h.transformTo(t,e)}}(s,function(t,e){var r,i=0,n=null,s=0;for(r=0;rn;n++)u[n]=n>=252?6:n>=248?5:n>=240?4:n>=224?3:n>=192?2:1;u[254]=u[254]=1,s.utf8encode=function(t){return h.nodebuffer?r.newBufferFrom(t,"utf-8"):function(t){var e,r,i,n,s,a=t.length,o=0;for(n=0;a>n;n++)55296==(64512&(r=t.charCodeAt(n)))&&a>n+1&&56320==(64512&(i=t.charCodeAt(n+1)))&&(r=65536+(r-55296<<10)+(i-56320),n++),o+=128>r?1:2048>r?2:65536>r?3:4;for(e=h.uint8array?new Uint8Array(o):new Array(o),n=s=0;o>s;n++)55296==(64512&(r=t.charCodeAt(n)))&&a>n+1&&56320==(64512&(i=t.charCodeAt(n+1)))&&(r=65536+(r-55296<<10)+(i-56320),n++),128>r?e[s++]=r:(2048>r?e[s++]=192|r>>>6:(65536>r?e[s++]=224|r>>>12:(e[s++]=240|r>>>18,e[s++]=128|r>>>12&63),e[s++]=128|r>>>6&63),e[s++]=128|63&r);return e}(t)},s.utf8decode=function(t){return h.nodebuffer?o.transformTo("nodebuffer",t).toString("utf-8"):function(t){var e,r,i,n,s=t.length,a=new Array(2*s);for(e=r=0;s>e;)if((i=t[e++])<128)a[r++]=i;else if(4<(n=u[i]))a[r++]=65533,e+=n-1;else{for(i&=2===n?31:3===n?15:7;n>1&&s>e;)i=i<<6|63&t[e++],n--;n>1?a[r++]=65533:65536>i?a[r++]=i:(i-=65536,a[r++]=55296|i>>10&1023,a[r++]=56320|1023&i)}return a.length!==r&&(a.subarray?a=a.subarray(0,r):a.length=r),o.applyFromCharCode(a)}(t=o.transformTo(h.uint8array?"uint8array":"array",t))},o.inherits(a,i),a.prototype.processChunk=function(t){var e=o.transformTo(h.uint8array?"uint8array":"array",t.data);if(this.leftOver&&this.leftOver.length){if(h.uint8array){var r=e;(e=new Uint8Array(r.length+this.leftOver.length)).set(this.leftOver,0),e.set(r,this.leftOver.length)}else e=this.leftOver.concat(e);this.leftOver=null}var i=function(t,e){var r;for((e=e||t.length)>t.length&&(e=t.length),r=e-1;r>=0&&128==(192&t[r]);)r--;return 0>r?e:0===r?e:r+u[t[r]]>e?r:e}(e),n=e;i!==e.length&&(h.uint8array?(n=e.subarray(0,i),this.leftOver=e.subarray(i,e.length)):(n=e.slice(0,i),this.leftOver=e.slice(i,e.length))),this.push({data:s.utf8decode(n),meta:t.meta})},a.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:s.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},s.Utf8DecodeWorker=a,o.inherits(l,i),l.prototype.processChunk=function(t){this.push({data:s.utf8encode(t.data),meta:t.meta})},s.Utf8EncodeWorker=l},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(t,e,a){"use strict";function n(t){return t}function l(t,e){for(var r=0;r1;)try{return s.stringifyByChunk(t,r,e)}catch(t){e=Math.floor(e/2)}return s.stringifyByChar(t)}function d(t,e){for(var r=0;r=s)return String.fromCharCode.apply(null,t); +for(;s>n;)"array"===e||"nodebuffer"===e?i.push(String.fromCharCode.apply(null,t.slice(n,Math.min(n+r,s)))):i.push(String.fromCharCode.apply(null,t.subarray(n,Math.min(n+r,s)))),n+=r;return i.join("")},stringifyByChar:function(t){for(var e="",r=0;r0;)t=this.reader.readInt(2),e=this.reader.readInt(4),r=this.reader.readData(e),this.zip64ExtensibleData[t]={id:t,length:e,value:r}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1t)throw this.isSignature(0,s.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(t);var e=t;if(this.checkSignature(s.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===n.MAX_VALUE_16BITS||this.diskWithCentralDirStart===n.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===n.MAX_VALUE_16BITS||this.centralDirRecords===n.MAX_VALUE_16BITS||this.centralDirSize===n.MAX_VALUE_32BITS||this.centralDirOffset===n.MAX_VALUE_32BITS){if(this.zip64=!0,(t=this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(t),this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,s.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var r=this.centralDirOffset+this.centralDirSize;this.zip64&&(r+=20,r+=12+this.zip64EndOfCentralSize);var i=e-r;if(i>0)this.isSignature(e,s.CENTRAL_FILE_HEADER)||(this.reader.zero=i);else if(0>i)throw new Error("Corrupted zip: missing "+Math.abs(i)+" bytes.")},prepareReader:function(t){this.reader=i(t)},load:function(t){this.prepareReader(t),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},e.exports=h},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utf8":31,"./utils":32,"./zipEntry":34}],34:[function(t,e,r){"use strict";function l(t,e){this.options=t,this.loadOptions=e}var i=t("./reader/readerFor"),s=t("./utils"),n=t("./compressedObject"),a=t("./crc32"),o=t("./utf8"),h=t("./compressions"),u=t("./support");l.prototype={isEncrypted:function(){return 1==(1&this.bitFlag)},useUTF8:function(){return 2048==(2048&this.bitFlag)},readLocalPart:function(t){var e,r;if(t.skip(22),this.fileNameLength=t.readInt(2),r=t.readInt(2),this.fileName=t.readData(this.fileNameLength),t.skip(r),-1===this.compressedSize||-1===this.uncompressedSize)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(null===(e=function(t){for(var e in h)if(h.hasOwnProperty(e)&&h[e].magic===t)return h[e];return null}(this.compressionMethod)))throw new Error("Corrupted zip : compression "+s.pretty(this.compressionMethod)+" unknown (inner file : "+s.transformTo("string",this.fileName)+")");this.decompressed=new n(this.compressedSize,this.uncompressedSize,this.crc32,e,t.readData(this.compressedSize))},readCentralPart:function(t){this.versionMadeBy=t.readInt(2),t.skip(2),this.bitFlag=t.readInt(2),this.compressionMethod=t.readString(2),this.date=t.readDate(),this.crc32=t.readInt(4),this.compressedSize=t.readInt(4),this.uncompressedSize=t.readInt(4);var e=t.readInt(2);if(this.extraFieldsLength=t.readInt(2),this.fileCommentLength=t.readInt(2),this.diskNumberStart=t.readInt(2),this.internalFileAttributes=t.readInt(2),this.externalFileAttributes=t.readInt(4),this.localHeaderOffset=t.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");t.skip(e),this.readExtraFields(t),this.parseZIP64ExtraField(t),this.fileComment=t.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var t=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),0==t&&(this.dosPermissions=63&this.externalFileAttributes),3==t&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(t){if(this.extraFields[1]){var e=i(this.extraFields[1].value);this.uncompressedSize===s.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===s.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===s.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===s.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4))}},readExtraFields:function(t){var e,r,i,n=t.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});t.index+4s;s++)t[n+s]=e[r+s]},flattenChunks:function(t){var e,r,i,n,s,a;for(e=i=0,r=t.length;r>e;e++)i+=t[e].length;for(a=new Uint8Array(i),e=n=0,r=t.length;r>e;e++)s=t[e],a.set(s,n),n+=s.length;return a}},s={arraySet:function(t,e,r,i,n){for(var s=0;i>s;s++)t[n+s]=e[r+s]},flattenChunks:function(t){return[].concat.apply([],t)}};r.setTyped=function(t){t?(r.Buf8=Uint8Array,r.Buf16=Uint16Array,r.Buf32=Int32Array,r.assign(r,n)):(r.Buf8=Array,r.Buf16=Array,r.Buf32=Array,r.assign(r,s))},r.setTyped(i)},{}],42:[function(t,e,r){"use strict";function l(t,e){if(65537>e&&(t.subarray&&s||!t.subarray&&n))return String.fromCharCode.apply(null,h.shrinkBuf(t,e));for(var r="",i=0;e>i;i++)r+=String.fromCharCode(t[i]);return r}var h=t("./common"),n=!0,s=!0;try{String.fromCharCode.apply(null,[0])}catch(t){n=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){s=!1}for(var u=new h.Buf8(256),i=0;256>i;i++)u[i]=i>=252?6:i>=248?5:i>=240?4:i>=224?3:i>=192?2:1;u[254]=u[254]=1,r.string2buf=function(t){var e,r,i,n,s,a=t.length,o=0;for(n=0;a>n;n++)55296==(64512&(r=t.charCodeAt(n)))&&a>n+1&&56320==(64512&(i=t.charCodeAt(n+1)))&&(r=65536+(r-55296<<10)+(i-56320),n++),o+=128>r?1:2048>r?2:65536>r?3:4;for(e=new h.Buf8(o),n=s=0;o>s;n++)55296==(64512&(r=t.charCodeAt(n)))&&a>n+1&&56320==(64512&(i=t.charCodeAt(n+1)))&&(r=65536+(r-55296<<10)+(i-56320),n++),128>r?e[s++]=r:(2048>r?e[s++]=192|r>>>6:(65536>r?e[s++]=224|r>>>12:(e[s++]=240|r>>>18,e[s++]=128|r>>>12&63),e[s++]=128|r>>>6&63),e[s++]=128|63&r);return e},r.buf2binstring=function(t){return l(t,t.length)},r.binstring2buf=function(t){for(var e=new h.Buf8(t.length),r=0,i=e.length;i>r;r++)e[r]=t.charCodeAt(r);return e},r.buf2string=function(t,e){var r,i,n,s,a=e||t.length,o=new Array(2*a);for(r=i=0;a>r;)if((n=t[r++])<128)o[i++]=n;else if(4<(s=u[n]))o[i++]=65533,r+=s-1;else{for(n&=2===s?31:3===s?15:7;s>1&&a>r;)n=n<<6|63&t[r++],s--;s>1?o[i++]=65533:65536>n?o[i++]=n:(n-=65536,o[i++]=55296|n>>10&1023,o[i++]=56320|1023&n)}return l(o,i)},r.utf8border=function(t,e){var r;for((e=e||t.length)>t.length&&(e=t.length),r=e-1;r>=0&&128==(192&t[r]);)r--;return 0>r?e:0===r?e:r+u[t[r]]>e?r:e}},{"./common":41}],43:[function(t,e,r){"use strict";e.exports=function(t,e,r,i){for(var n=65535&t|0,s=t>>>16&65535|0,a=0;0!==r;){for(r-=a=r>2e3?2e3:r;s=s+(n=n+e[i++]|0)|0,--a;);n%=65521,s%=65521}return n|s<<16|0}},{}],44:[function(t,e,r){"use strict";e.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(t,e,r){"use strict";var o=function(){for(var t,e=[],r=0;256>r;r++){t=r;for(var i=0;8>i;i++)t=1&t?3988292384^t>>>1:t>>>1;e[r]=t}return e}();e.exports=function(t,e,r,i){var n=o,s=i+r;t^=-1;for(var a=i;s>a;a++)t=t>>>8^n[255&(t^e[a])];return-1^t}},{}],46:[function(t,e,r){"use strict";function R(t,e){return t.msg=i[e],e}function T(t){return(t<<1)-(t>4?9:0)}function D(t){for(var e=t.length;0<=--e;)t[e]=0}function F(t){var e=t.state,r=e.pending;r>t.avail_out&&(r=t.avail_out),0!==r&&(d.arraySet(t.output,e.pending_buf,e.pending_out,r,t.next_out),t.next_out+=r,e.pending_out+=r,t.total_out+=r,t.avail_out-=r,e.pending-=r,0===e.pending&&(e.pending_out=0))}function N(t,e){u._tr_flush_block(t,0<=t.block_start?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,F(t.strm)}function U(t,e){t.pending_buf[t.pending++]=e}function P(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function L(t,e){var r,i,n=t.max_chain_length,s=t.strstart,a=t.prev_length,o=t.nice_match,h=t.strstart>t.w_size-z?t.strstart-(t.w_size-z):0,u=t.window,l=t.w_mask,f=t.prev,d=t.strstart+S,c=u[s+a-1],p=u[s+a];t.prev_length>=t.good_match&&(n>>=2),o>t.lookahead&&(o=t.lookahead);do if(u[(r=e)+a]===p&&u[r+a-1]===c&&u[r]===u[s]&&u[++r]===u[s+1]){s+=2,r++;do;while(u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&u[++s]===u[++r]&&d>s);if(i=S-(d-s),s=d-S,i>a){if(t.match_start=e,o<=(a=i))break;c=u[s+a-1],p=u[s+a]}}while((e=f[e&l])>h&&0!=--n);return a<=t.lookahead?a:t.lookahead}function j(t){var e,r,i,n,s,a,o,h,u,l,f=t.w_size;do{if(n=t.window_size-t.lookahead-t.strstart,t.strstart>=f+(f-z)){for(d.arraySet(t.window,t.window,f,f,0),t.match_start-=f,t.strstart-=f,t.block_start-=f,e=r=t.hash_size;i=t.head[--e],t.head[e]=i>=f?i-f:0,--r;);for(e=r=f;i=t.prev[--e],t.prev[e]=i>=f?i-f:0,--r;);n+=f}if(0===t.strm.avail_in)break;if(a=t.strm,o=t.window,h=t.strstart+t.lookahead,u=n,l=void 0,l=a.avail_in,l>u&&(l=u),r=0===l?0:(a.avail_in-=l,d.arraySet(o,a.input,a.next_in,l,h),1===a.state.wrap?a.adler=c(a.adler,o,l,h):2===a.state.wrap&&(a.adler=p(a.adler,o,l,h)),a.next_in+=l,a.total_in+=l,l),t.lookahead+=r,t.lookahead+t.insert>=x)for(s=t.strstart-t.insert,t.ins_h=t.window[s],t.ins_h=(t.ins_h<=x&&(t.ins_h=(t.ins_h<=x)if(i=u._tr_tally(t,t.strstart-t.match_start,t.match_length-x),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=x){for(t.match_length--;t.strstart++,t.ins_h=(t.ins_h<=x&&(t.ins_h=(t.ins_h<=x&&t.match_length<=t.prev_length){for(n=t.strstart+t.lookahead-x,i=u._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-x),t.lookahead-=t.prev_length-1,t.prev_length-=2;++t.strstart<=n&&(t.ins_h=(t.ins_h<i?(a=0,i=-i):i>15&&(a=2,i-=16),1>n||n>y||r!==v||8>i||i>15||0>e||e>9||0>s||s>b)return R(t,_);8===i&&(i=9);var o=new H;return(t.state=o).strm=t,o.wrap=a,o.gzhead=null,o.w_bits=i,o.w_size=1<t.pending_buf_size-5&&(r=t.pending_buf_size-5);;){if(t.lookahead<=1){if(j(t),0===t.lookahead&&e===l)return A;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var i=t.block_start+r;if((0===t.strstart||t.strstart>=i)&&(t.lookahead=t.strstart-i,t.strstart=i,N(t,!1),0===t.strm.avail_out))return A;if(t.strstart-t.block_start>=t.w_size-z&&(N(t,!1),0===t.strm.avail_out))return A}return t.insert=0,e===f?(N(t,!0),0===t.strm.avail_out?O:B):(t.strstart>t.block_start&&(N(t,!1),t.strm.avail_out),A)}),new M(4,4,8,4,Z),new M(4,5,16,8,Z),new M(4,6,32,32,Z),new M(4,4,16,16,W),new M(8,16,32,32,W),new M(8,16,128,128,W),new M(8,32,128,256,W),new M(32,128,258,1024,W),new M(32,258,258,4096,W)],r.deflateInit=function(t,e){return Y(t,e,v,15,8,0)},r.deflateInit2=Y,r.deflateReset=K,r.deflateResetKeep=G,r.deflateSetHeader=function(t,e){return t&&t.state?2!==t.state.wrap?_:(t.state.gzhead=e,m):_},r.deflate=function(t,e){var r,i,n,s;if(!t||!t.state||e>5||0>e)return t?R(t,_):_;if(i=t.state,!t.output||!t.input&&0!==t.avail_in||666===i.status&&e!==f)return R(t,0===t.avail_out?-5:_);if(i.strm=t,r=i.last_flush,i.last_flush=e,i.status===C)if(2===i.wrap)t.adler=0,U(i,31),U(i,139),U(i,8),i.gzhead?(U(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),U(i,255&i.gzhead.time),U(i,i.gzhead.time>>8&255),U(i,i.gzhead.time>>16&255),U(i,i.gzhead.time>>24&255),U(i,9===i.level?2:2<=i.strategy||i.level<2?4:0),U(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(U(i,255&i.gzhead.extra.length),U(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=p(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69):(U(i,0),U(i,0),U(i,0),U(i,0),U(i,0),U(i,9===i.level?2:2<=i.strategy||i.level<2?4:0),U(i,3),i.status=E);else{var a=v+(i.w_bits-8<<4)<<8;a|=(2<=i.strategy||i.level<2?0:i.level<6?1:6===i.level?2:3)<<6,0!==i.strstart&&(a|=32),a+=31-a%31,i.status=E,P(i,a),0!==i.strstart&&(P(i,t.adler>>>16),P(i,65535&t.adler)),t.adler=1}if(69===i.status)if(i.gzhead.extra){for(n=i.pending;i.gzindex<(65535&i.gzhead.extra.length)&&(i.pending!==i.pending_buf_size||(i.gzhead.hcrc&&i.pending>n&&(t.adler=p(t.adler,i.pending_buf,i.pending-n,n)),F(t),n=i.pending,i.pending!==i.pending_buf_size));)U(i,255&i.gzhead.extra[i.gzindex]),i.gzindex++;i.gzhead.hcrc&&i.pending>n&&(t.adler=p(t.adler,i.pending_buf,i.pending-n,n)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=73)}else i.status=73;if(73===i.status)if(i.gzhead.name){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(t.adler=p(t.adler,i.pending_buf,i.pending-n,n)),F(t),n=i.pending,i.pending===i.pending_buf_size)){s=1;break}s=i.gzindexn&&(t.adler=p(t.adler,i.pending_buf,i.pending-n,n)),0===s&&(i.gzindex=0,i.status=91)}else i.status=91;if(91===i.status)if(i.gzhead.comment){n=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>n&&(t.adler=p(t.adler,i.pending_buf,i.pending-n,n)),F(t),n=i.pending,i.pending===i.pending_buf_size)){s=1;break}s=i.gzindexn&&(t.adler=p(t.adler,i.pending_buf,i.pending-n,n)),0===s&&(i.status=103)}else i.status=103;if(103===i.status&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&F(t),i.pending+2<=i.pending_buf_size&&(U(i,255&t.adler),U(i,t.adler>>8&255),t.adler=0,i.status=E)):i.status=E),0!==i.pending){if(F(t),0===t.avail_out)return i.last_flush=-1,m}else if(0===t.avail_in&&T(e)<=T(r)&&e!==f)return R(t,-5);if(666===i.status&&0!==t.avail_in)return R(t,-5);if(0!==t.avail_in||0!==i.lookahead||e!==l&&666!==i.status){var o=2===i.strategy?function(t,e){for(var r;;){if(0===t.lookahead&&(j(t),0===t.lookahead)){if(e===l)return A;break}if(t.match_length=0,r=u._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,r&&(N(t,!1),0===t.strm.avail_out))return A}return t.insert=0,e===f?(N(t,!0),0===t.strm.avail_out?O:B):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?A:I}(i,e):3===i.strategy?function(t,e){for(var r,i,n,s,a=t.window;;){if(t.lookahead<=S){if(j(t),t.lookahead<=S&&e===l)return A;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=x&&0n);t.match_length=S-(s-n),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=x?(r=u._tr_tally(t,1,t.match_length-x),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(r=u._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),r&&(N(t,!1),0===t.strm.avail_out))return A}return t.insert=0,e===f?(N(t,!0),0===t.strm.avail_out?O:B):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?A:I}(i,e):h[i.level].func(i,e);if(o!==O&&o!==B||(i.status=666),o===A||o===O)return 0===t.avail_out&&(i.last_flush=-1),m;if(o===I&&(1===e?u._tr_align(i):5!==e&&(u._tr_stored_block(i,0,0,!1),3===e&&(D(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),F(t),0===t.avail_out))return i.last_flush=-1,m}return e!==f?m:i.wrap<=0?1:(2===i.wrap?(U(i,255&t.adler),U(i,t.adler>>8&255),U(i,t.adler>>16&255),U(i,t.adler>>24&255),U(i,255&t.total_in),U(i,t.total_in>>8&255),U(i,t.total_in>>16&255),U(i,t.total_in>>24&255)):(P(i,t.adler>>>16),P(i,65535&t.adler)),F(t),0=r.w_size&&(0===s&&(D(r.head),r.strstart=0,r.block_start=0,r.insert=0),u=new d.Buf8(r.w_size),d.arraySet(u,e,l-r.w_size,r.w_size,0),e=u,l=r.w_size),a=t.avail_in,o=t.next_in,h=t.input,t.avail_in=l,t.next_in=0,t.input=e,j(r);r.lookahead>=x;){for(i=r.strstart,n=r.lookahead-(x-1);r.ins_h=(r.ins_h<p&&(c+=z[i++]<>>=y=v>>>24,p-=y,0===(y=v>>>16&255))C[s++]=65535&v;else{if(!(16&y)){if(0==(64&y)){v=m[(65535&v)+(c&(1<p&&(c+=z[i++]<>>=y,p-=y),15>p&&(c+=z[i++]<>>=y=v>>>24,p-=y,!(16&(y=v>>>16&255))){if(0==(64&y)){v=_[(65535&v)+(c&(1<>>=y,p-=y,(y=s-a)y){for(w-=y;C[s++]=d[x++],--y;);x=s-k,S=C}}else if(y>f){if(x+=u+f-y,(y-=f)f){for(w-=y=f;C[s++]=d[x++],--y;);x=s-k,S=C}}}else if(x+=f-y,w>y){for(w-=y;C[s++]=d[x++],--y;);x=s-k,S=C}for(;w>2;)C[s++]=S[x++],C[s++]=S[x++],C[s++]=S[x++],w-=3;w&&(C[s++]=S[x++],w>1&&(C[s++]=S[x++]))}else{for(x=s-k;C[s++]=C[x++],C[s++]=C[x++],C[s++]=C[x++],2<(w-=3););w&&(C[s++]=C[x++],w>1&&(C[s++]=C[x++]))}break}}break}}while(n>i&&o>s);i-=w=p>>3,c&=(1<<(p-=w<<3))-1,t.next_in=i,t.next_out=s,t.avail_in=n>i?n-i+5:5-(i-n),t.avail_out=o>s?o-s+257:257-(s-o),r.hold=c,r.bits=p}},{}],49:[function(t,e,r){"use strict";function L(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function s(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new I.Buf16(320),this.work=new I.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function a(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=P,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new I.Buf32(i),e.distcode=e.distdyn=new I.Buf32(n),e.sane=1,e.back=-1,N):U}function o(t){var e;return t&&t.state?((e=t.state).wsize=0,e.whave=0,e.wnext=0,a(t)):U}function h(t,e){var r,i;return t&&t.state?(i=t.state,0>e?(r=0,e=-e):(r=1+(e>>4),48>e&&(e&=15)),e&&(8>e||e>15)?U:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=r,i.wbits=e,o(t))):U}function u(t,e){var r,i;return t?(i=new s,(t.state=i).window=null,(r=h(t,e))!==N&&(t.state=null),r):U}function j(t){if(d){var e;for(l=new I.Buf32(512),f=new I.Buf32(32),e=0;144>e;)t.lens[e++]=8;for(;256>e;)t.lens[e++]=9;for(;280>e;)t.lens[e++]=7;for(;288>e;)t.lens[e++]=8;for(T(D,t.lens,0,288,l,0,t.work,{bits:9}),e=0;32>e;)t.lens[e++]=5;T(F,t.lens,0,32,f,0,t.work,{bits:5}),d=!1}t.lencode=l,t.lenbits=9,t.distcode=f,t.distbits=5}function Z(t,e,r,i){var n,s=t.state;return null===s.window&&(s.wsize=1<=s.wsize?(I.arraySet(s.window,e,r-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):(i<(n=s.wsize-s.wnext)&&(n=i),I.arraySet(s.window,e,r-i,n,s.wnext),(i-=n)?(I.arraySet(s.window,e,r-i,i,0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whavel;){if(0===o)break t;o--,u+=i[s++]<>>8&255,r.check=B(r.check,E,2,0),l=u=0,r.mode=2;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&u)<<8)+(u>>8))%31){t.msg="incorrect header check",r.mode=30;break}if(8!=(15&u)){t.msg="unknown compression method",r.mode=30;break}if(l-=4,k=8+(15&(u>>>=4)),0===r.wbits)r.wbits=k;else if(k>r.wbits){t.msg="invalid window size",r.mode=30;break}r.dmax=1<l;){if(0===o)break t;o--,u+=i[s++]<>8&1),512&r.flags&&(E[0]=255&u,E[1]=u>>>8&255,r.check=B(r.check,E,2,0)),l=u=0,r.mode=3;case 3:for(;32>l;){if(0===o)break t;o--,u+=i[s++]<>>8&255,E[2]=u>>>16&255,E[3]=u>>>24&255,r.check=B(r.check,E,4,0)),l=u=0,r.mode=4;case 4:for(;16>l;){if(0===o)break t;o--,u+=i[s++]<>8),512&r.flags&&(E[0]=255&u,E[1]=u>>>8&255,r.check=B(r.check,E,2,0)),l=u=0,r.mode=5;case 5:if(1024&r.flags){for(;16>l;){if(0===o)break t;o--,u+=i[s++]<>>8&255,r.check=B(r.check,E,2,0)),l=u=0}else r.head&&(r.head.extra=null);r.mode=6;case 6:if(1024&r.flags&&(o<(c=r.length)&&(c=o),c&&(r.head&&(k=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),I.arraySet(r.head.extra,i,s,c,k)),512&r.flags&&(r.check=B(r.check,i,c,s)),o-=c,s+=c,r.length-=c),r.length))break t;r.length=0,r.mode=7;case 7:if(2048&r.flags){if(0===o)break t;for(c=0;k=i[s+c++],r.head&&k&&r.length<65536&&(r.head.name+=String.fromCharCode(k)),k&&o>c;);if(512&r.flags&&(r.check=B(r.check,i,c,s)),o-=c,s+=c,k)break t}else r.head&&(r.head.name=null);r.length=0,r.mode=8;case 8:if(4096&r.flags){if(0===o)break t;for(c=0;k=i[s+c++],r.head&&k&&r.length<65536&&(r.head.comment+=String.fromCharCode(k)),k&&o>c;);if(512&r.flags&&(r.check=B(r.check,i,c,s)),o-=c,s+=c,k)break t}else r.head&&(r.head.comment=null);r.mode=9;case 9:if(512&r.flags){for(;16>l;){if(0===o)break t;o--,u+=i[s++]<>9&1,r.head.done=!0),t.adler=r.check=0,r.mode=12;break;case 10:for(;32>l;){if(0===o)break t;o--,u+=i[s++]<>>=7&l,l-=7&l,r.mode=27;break}for(;3>l;){if(0===o)break t;o--,u+=i[s++]<>>=1)){case 0:r.mode=14;break;case 1:if(j(r),r.mode=20,6!==e)break;u>>>=2,l-=2;break t;case 2:r.mode=17;break;case 3:t.msg="invalid block type",r.mode=30}u>>>=2,l-=2;break;case 14:for(u>>>=7&l,l-=7&l;32>l;){if(0===o)break t;o--,u+=i[s++]<>>16^65535)){t.msg="invalid stored block lengths",r.mode=30;break}if(r.length=65535&u,l=u=0,r.mode=15,6===e)break t;case 15:r.mode=16;case 16:if(c=r.length){if(c>o&&(c=o),c>h&&(c=h),0===c)break t;I.arraySet(n,i,s,c,a),o-=c,s+=c,h-=c,a+=c,r.length-=c;break}r.mode=12;break;case 17:for(;14>l;){if(0===o)break t;o--,u+=i[s++]<>>=5,l-=5,r.ndist=1+(31&u),u>>>=5,l-=5,r.ncode=4+(15&u),u>>>=4,l-=4,286l;){if(0===o)break t;o--,u+=i[s++]<>>=3,l-=3}for(;r.have<19;)r.lens[A[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,S={bits:r.lenbits},x=T(0,r.lens,0,19,r.lencode,0,r.work,S),r.lenbits=S.bits,x){t.msg="invalid code lengths set",r.mode=30;break}r.have=0,r.mode=19;case 19:for(;r.have>>16&255,b=65535&C,!((_=C>>>24)<=l);){if(0===o)break t;o--,u+=i[s++]<b)u>>>=_,l-=_,r.lens[r.have++]=b;else{if(16===b){for(z=_+2;z>l;){if(0===o)break t;o--,u+=i[s++]<>>=_,l-=_,0===r.have){t.msg="invalid bit length repeat",r.mode=30;break}k=r.lens[r.have-1],c=3+(3&u),u>>>=2,l-=2}else if(17===b){for(z=_+3;z>l;){if(0===o)break t;o--,u+=i[s++]<>>=_)),u>>>=3,l-=3}else{for(z=_+7;z>l;){if(0===o)break t;o--,u+=i[s++]<>>=_)),u>>>=7,l-=7}if(r.have+c>r.nlen+r.ndist){t.msg="invalid bit length repeat",r.mode=30;break}for(;c--;)r.lens[r.have++]=k}}if(30===r.mode)break;if(0===r.lens[256]){t.msg="invalid code -- missing end-of-block",r.mode=30;break}if(r.lenbits=9,S={bits:r.lenbits},x=T(D,r.lens,0,r.nlen,r.lencode,0,r.work,S),r.lenbits=S.bits,x){t.msg="invalid literal/lengths set",r.mode=30;break}if(r.distbits=6,r.distcode=r.distdyn,S={bits:r.distbits},x=T(F,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,S),r.distbits=S.bits,x){t.msg="invalid distances set",r.mode=30;break}if(r.mode=20,6===e)break t;case 20:r.mode=21;case 21:if(o>=6&&h>=258){t.next_out=a,t.avail_out=h,t.next_in=s,t.avail_in=o,r.hold=u,r.bits=l,R(t,d),a=t.next_out,n=t.output,h=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,u=r.hold,l=r.bits,12===r.mode&&(r.back=-1);break}for(r.back=0;g=(C=r.lencode[u&(1<>>16&255,b=65535&C,!((_=C>>>24)<=l);){if(0===o)break t;o--,u+=i[s++]<>v)])>>>16&255,b=65535&C,!(v+(_=C>>>24)<=l);){if(0===o)break t;o--,u+=i[s++]<>>=v,l-=v,r.back+=v}if(u>>>=_,l-=_,r.back+=_,r.length=b,0===g){r.mode=26;break}if(32&g){r.back=-1,r.mode=12;break}if(64&g){t.msg="invalid literal/length code",r.mode=30;break}r.extra=15&g,r.mode=22;case 22:if(r.extra){for(z=r.extra;z>l;){if(0===o)break t;o--,u+=i[s++]<>>=r.extra,l-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=23;case 23:for(;g=(C=r.distcode[u&(1<>>16&255,b=65535&C,!((_=C>>>24)<=l);){if(0===o)break t;o--,u+=i[s++]<>v)])>>>16&255,b=65535&C,!(v+(_=C>>>24)<=l);){if(0===o)break t;o--,u+=i[s++]<>>=v,l-=v,r.back+=v}if(u>>>=_,l-=_,r.back+=_,64&g){t.msg="invalid distance code",r.mode=30;break}r.offset=b,r.extra=15&g,r.mode=24;case 24:if(r.extra){for(z=r.extra;z>l;){if(0===o)break t;o--,u+=i[s++]<>>=r.extra,l-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){t.msg="invalid distance too far back",r.mode=30;break}r.mode=25;case 25:if(0===h)break t;if(c=d-h,r.offset>c){if((c=r.offset-c)>r.whave&&r.sane){t.msg="invalid distance too far back",r.mode=30;break}p=c>r.wnext?(c-=r.wnext,r.wsize-c):r.wnext-c,c>r.length&&(c=r.length),m=r.window}else m=n,p=a-r.offset,c=r.length;for(c>h&&(c=h),h-=c,r.length-=c;n[a++]=m[p++],--c;);0===r.length&&(r.mode=21);break;case 26:if(0===h)break t;n[a++]=r.length,h--,r.mode=21;break;case 27:if(r.wrap){for(;32>l;){if(0===o)break t;o--,u|=i[s++]<l;){if(0===o)break t;o--,u+=i[s++]<=b;b++)O[b]=0;for(v=0;i>v;v++)O[e[r+v]]++;for(k=g,w=15;w>=1&&0===O[w];w--);if(k>w&&(k=w),0===w)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(y=1;w>y&&0===O[y];y++);for(y>k&&(k=y),b=z=1;15>=b;b++)if(z<<=1,(z-=O[b])<0)return-1;if(z>0&&(0===t||1!==w))return-1;for(B[1]=0,b=1;15>b;b++)B[b+1]=B[b]+O[b];for(v=0;i>v;v++)0!==e[r+v]&&(a[B[e[r+v]]++]=v);if(c=0===t?(A=R=a,19):1===t?(A=F,I-=257,R=N,T-=257,256):(A=U,R=P,-1),b=y,d=s,S=v=E=0,l=-1,f=(C=1<<(x=k))-1,1===t&&C>852||2===t&&C>592)return 1;for(;;){for(p=b-S,_=a[v]c?(m=R[T+a[v]],A[I+a[v]]):(m=96,0),h=1<>S)+(u-=h)]=p<<24|m<<16|_|0,0!==u;);for(h=1<>=1;if(0!==h?(E&=h-1,E+=h):E=0,v++,0==--O[b]){if(b===w)break;b=e[r+a[v]]}if(b>k&&(E&f)!==l){for(0===S&&(S=k),d+=y,z=1<<(x=b-S);w>x+S&&!((z-=O[x+S])<=0);)x++,z<<=1;if(C+=1<852||2===t&&C>592)return 1;n[l=E&f]=k<<24|x<<16|d-s|0}}return 0!==E&&(n[d+E]=b-S<<24|64<<16|0),o.bits=k,0}},{"../utils/common":41}],51:[function(t,e,r){"use strict";e.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(t,e,r){"use strict";function i(t){for(var e=t.length;0<=--e;)t[e]=0}function D(t,e,r,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=r,this.elems=i,this.max_length=n,this.has_stree=t&&t.length}function F(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function N(t){return 256>t?E[t]:E[256+(t>>>7)]}function U(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function P(t,e,r){t.bi_valid>c-r?(t.bi_buf|=e<>c-t.bi_valid,t.bi_valid+=r-c):(t.bi_buf|=e<>>=1,r<<=1,0<--e;);return r>>>1}function Z(t,e,r){var i,n,s=new Array(g+1),a=0;for(i=1;g>=i;i++)s[i]=a=a+r[i-1]<<1;for(n=0;e>=n;n++){var o=t[2*n+1];0!==o&&(t[2*n]=j(s[o]++,o))}}function W(t){var e;for(e=0;l>e;e++)t.dyn_ltree[2*e]=0;for(e=0;f>e;e++)t.dyn_dtree[2*e]=0;for(e=0;d>e;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*m]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function M(t){8r;r++)0!==s[2*r]?(t.heap[++t.heap_len]=u=r,t.depth[r]=0):s[2*r+1]=0;for(;t.heap_len<2;)s[2*(n=t.heap[++t.heap_len]=2>u?++u:0)]=1,t.depth[n]=0,t.opt_len--,o&&(t.static_len-=a[2*n+1]);for(e.max_code=u,r=t.heap_len>>1;r>=1;r--)G(t,s,r);for(n=h;r=t.heap[1],t.heap[1]=t.heap[t.heap_len--],G(t,s,1),i=t.heap[1],t.heap[--t.heap_max]=r,t.heap[--t.heap_max]=i,s[2*n]=s[2*r]+s[2*i],t.depth[n]=(t.depth[r]>=t.depth[i]?t.depth[r]:t.depth[i])+1,s[2*r+1]=s[2*i+1]=n,t.heap[1]=n++,G(t,s,1),2<=t.heap_len;);t.heap[--t.heap_max]=t.heap[1],function(t,e){var r,i,n,s,a,o,h=e.dyn_tree,u=e.max_code,l=e.stat_desc.static_tree,f=e.stat_desc.has_stree,d=e.stat_desc.extra_bits,c=e.stat_desc.extra_base,p=e.stat_desc.max_length,m=0;for(s=0;g>=s;s++)t.bl_count[s]=0;for(h[2*t.heap[t.heap_max]+1]=0,r=t.heap_max+1;_>r;r++)p<(s=h[2*h[2*(i=t.heap[r])+1]+1]+1)&&(s=p,m++),h[2*i+1]=s,i>u||(t.bl_count[s]++,a=0,i>=c&&(a=d[i-c]),o=h[2*i],t.opt_len+=o*(s+a),f&&(t.static_len+=o*(l[2*i+1]+a)));if(0!==m){do{for(s=p-1;0===t.bl_count[s];)s--;t.bl_count[s]--,t.bl_count[s+1]+=2,t.bl_count[p]--,m-=2}while(m>0);for(s=p;0!==s;s--)for(i=t.bl_count[s];0!==i;)u<(n=t.heap[--r])||(h[2*n+1]!==s&&(t.opt_len+=(s-h[2*n+1])*h[2*n],h[2*n+1]=s),i--)}}(t,e),Z(s,u,t.bl_count)}function X(t,e,r){var i,n,s=-1,a=e[1],o=0,h=7,u=4;for(0===a&&(h=138,u=3),e[2*(r+1)+1]=65535,i=0;r>=i;i++)n=a,a=e[2*(i+1)+1],++oo?t.bl_tree[2*n]+=o:0!==n?(n!==s&&t.bl_tree[2*n]++,t.bl_tree[2*b]++):10>=o?t.bl_tree[2*v]++:t.bl_tree[2*y]++,s=n,u=(o=0)===a?(h=138,3):n===a?(h=6,3):(h=7,4))}function V(t,e,r){var i,n,s=-1,a=e[1],o=0,h=7,u=4;for(0===a&&(h=138,u=3),i=0;r>=i;i++)if(n=a,a=e[2*(i+1)+1],!(++oo)for(;L(t,n,t.bl_tree),0!=--o;);else 0!==n?(n!==s&&(L(t,n,t.bl_tree),o--),L(t,b,t.bl_tree),P(t,o-3,2)):10>=o?(L(t,v,t.bl_tree),P(t,o-3,3)):(L(t,y,t.bl_tree),P(t,o-11,7));s=n,u=(o=0)===a?(h=138,3):n===a?(h=6,3):(h=7,4)}}function J(t,e,r,i){P(t,(s<<1)+(i?1:0),3),function(t,e,r,i){M(t),i&&(U(t,r),U(t,~r)),n.arraySet(t.pending_buf,t.window,e,r,t.pending),t.pending+=r}(t,e,r,!0)}var n=t("../utils/common"),o=0,h=1,s=0,a=29,u=256,l=u+1+a,f=30,d=19,_=2*l+1,g=15,c=16,p=7,m=256,b=16,v=17,y=18,w=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],k=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],x=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],z=new Array(2*(l+2));i(z);var C=new Array(2*f);i(C);var E=new Array(512);i(E);var A=new Array(256);i(A);var I=new Array(a);i(I);var O,B,R,T=new Array(f);i(T);var q=!1;r._tr_init=function(t){q||(function(){var t,e,r,i,n,s=new Array(g+1);for(i=r=0;a-1>i;i++)for(I[i]=r,t=0;t<1<i;i++)for(T[i]=n,t=0;t<1<>=7;f>i;i++)for(T[i]=n<<7,t=0;t<1<=e;e++)s[e]=0;for(t=0;143>=t;)z[2*t+1]=8,t++,s[8]++;for(;255>=t;)z[2*t+1]=9,t++,s[9]++;for(;279>=t;)z[2*t+1]=7,t++,s[7]++;for(;287>=t;)z[2*t+1]=8,t++,s[8]++;for(Z(z,l+1,s),t=0;f>t;t++)C[2*t+1]=5,C[2*t]=j(t,5);O=new D(z,w,u+1,l,g),B=new D(C,k,0,f,g),R=new D(new Array(0),x,0,d,p)}(),q=!0),t.l_desc=new F(t.dyn_ltree,O),t.d_desc=new F(t.dyn_dtree,B),t.bl_desc=new F(t.bl_tree,R),t.bi_buf=0,t.bi_valid=0,W(t)},r._tr_stored_block=J,r._tr_flush_block=function(t,e,r,i){var n,s,a=0;0=e;e++,r>>>=1)if(1&r&&0!==t.dyn_ltree[2*e])return o;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return h;for(e=32;u>e;e++)if(0!==t.dyn_ltree[2*e])return h;return o}(t)),Y(t,t.l_desc),Y(t,t.d_desc),a=function(t){var e;for(X(t,t.dyn_ltree,t.l_desc.max_code),X(t,t.dyn_dtree,t.d_desc.max_code),Y(t,t.bl_desc),e=d-1;e>=3&&0===t.bl_tree[2*S[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}(t),n=t.opt_len+3+7>>>3,(s=t.static_len+3+7>>>3)<=n&&(n=s)):n=s=r+5,n>=r+4&&-1!==e?J(t,e,r,i):4===t.strategy||s===n?(P(t,2+(i?1:0),3),K(t,z,C)):(P(t,4+(i?1:0),3),function(t,e,r,i){var n;for(P(t,e-257,5),P(t,r-1,5),P(t,i-4,4),n=0;i>n;n++)P(t,t.bl_tree[2*S[n]+1],3);V(t,t.dyn_ltree,e-1),V(t,t.dyn_dtree,r-1)}(t,t.l_desc.max_code+1,t.d_desc.max_code+1,a+1),K(t,t.dyn_ltree,t.dyn_dtree)),W(t),i&&M(t)},r._tr_tally=function(t,e,r){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&r,t.last_lit++,0===e?t.dyn_ltree[2*r]++:(t.matches++,e--,t.dyn_ltree[2*(A[r]+u+1)]++,t.dyn_dtree[2*N(e)]++),t.last_lit===t.lit_bufsize-1},r._tr_align=function(t){P(t,2,3),L(t,m,z),function(t){16===t.bi_valid?(U(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):8<=t.bi_valid&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}(t)}},{"../utils/common":41}],53:[function(t,e,r){"use strict";e.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(t,e,r){"use strict";e.exports="function"==typeof setImmediate?setImmediate:function(){var t=[].slice.apply(arguments);t.splice(1,0,0),setTimeout.apply(null,t)}},{}]},{},[10])(10)})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},require("buffer").Buffer)},{buffer:48}],54:[function(require,module,exports){exports.Parser=require("./lib/parser").Parser,exports.rules=require("./lib/rules"),exports.errors=require("./lib/errors"),exports.results=require("./lib/parsing-results"),exports.StringSource=require("./lib/StringSource"),exports.Token=require("./lib/Token"),exports.bottomUp=require("./lib/bottom-up"),exports.RegexTokeniser=require("./lib/regex-tokeniser").RegexTokeniser,exports.rule=function(ruleBuilder){var rule;return function(input){return rule||(rule=ruleBuilder()),rule(input)}}},{"./lib/StringSource":55,"./lib/Token":56,"./lib/bottom-up":58,"./lib/errors":59,"./lib/parser":61,"./lib/parsing-results":62,"./lib/regex-tokeniser":63,"./lib/rules":64}],55:[function(require,module,exports){var StringSourceRange=(module.exports=function(string,description){ +var self={asString:function(){return string},range:function(startIndex,endIndex){return new StringSourceRange(string,description,startIndex,endIndex)}};return self},function(string,description,startIndex,endIndex){this._string=string,this._description=description,this._startIndex=startIndex,this._endIndex=endIndex});StringSourceRange.prototype.to=function(otherRange){return new StringSourceRange(this._string,this._description,this._startIndex,otherRange._endIndex)},StringSourceRange.prototype.describe=function(){var position=this._position(),description=this._description?this._description+"\n":"";return description+"Line number: "+position.lineNumber+"\nCharacter number: "+position.characterNumber},StringSourceRange.prototype.lineNumber=function(){return this._position().lineNumber},StringSourceRange.prototype.characterNumber=function(){return this._position().characterNumber},StringSourceRange.prototype._position=function(){for(var self=this,index=0,nextNewLine=function(){return self._string.indexOf("\n",index)},lineNumber=1;-1!==nextNewLine()&&nextNewLine()startIndex){var value=result[1],token=new Token(rules[i].name,value,source.range(startIndex,endIndex));return{token:token,endIndex:endIndex}}}}var endIndex=startIndex+1,token=new Token("unrecognisedCharacter",string.substring(startIndex,endIndex),source.range(startIndex,endIndex));return{token:token,endIndex:endIndex}}function endToken(input,source){return new Token("end",null,source.range(input.length,input.length))}return rules=rules.map(function(rule){return{name:rule.name,regex:new RegExp(rule.regex.source,"g")}}),{tokenise:tokenise}}var Token=require("./Token"),StringSource=require("./StringSource");exports.RegexTokeniser=RegexTokeniser},{"./StringSource":55,"./Token":56}],64:[function(require,module,exports){function noOpRule(input){return results.success(null,input)}function describeTokenMismatch(input,expected){var error,token=input.head();return error=token?errors.error({expected:expected,actual:describeToken(token),location:token.source}):errors.error({expected:expected,actual:"end of tokens"}),results.failure([error],input)}var _=require("underscore"),options=require("option"),results=require("./parsing-results"),errors=require("./errors"),lazyIterators=require("./lazy-iterators");exports.token=function(tokenType,value){var matchValue=void 0!==value;return function(input){var token=input.head();if(!token||token.name!==tokenType||matchValue&&token.value!==value){var expected=describeToken({name:tokenType,value:value});return describeTokenMismatch(input,expected)}return results.success(token.value,input.tail(),token.source)}},exports.tokenOfType=function(tokenType){return exports.token(tokenType)},exports.firstOf=function(name,parsers){return _.isArray(parsers)||(parsers=Array.prototype.slice.call(arguments,1)),function(input){return lazyIterators.fromArray(parsers).map(function(parser){return parser(input)}).filter(function(result){return result.isSuccess()||result.isError()}).first()||describeTokenMismatch(input,name)}},exports.then=function(parser,func){return function(input){var result=parser(input);return result.map||console.log(result),result.map(func)}},exports.sequence=function(){function isCapturedRule(subRule){return subRule.isCaptured}var parsers=Array.prototype.slice.call(arguments,0),rule=function(input){var result=_.foldl(parsers,function(memo,parser){var result=memo.result,hasCut=memo.hasCut;if(!result.isSuccess())return{result:result,hasCut:hasCut};var subResult=parser(result.remaining());if(subResult.isCut())return{result:result,hasCut:!0};if(subResult.isSuccess()){var values;values=parser.isCaptured?result.value().withValue(parser,subResult.value()):result.value();var remaining=subResult.remaining(),source=input.to(remaining);return{result:results.success(values,remaining,source),hasCut:hasCut}}return hasCut?{result:results.error(subResult.errors(),subResult.remaining()),hasCut:hasCut}:{result:subResult,hasCut:hasCut}},{result:results.success(new SequenceValues,input),hasCut:!1}).result,source=input.to(result.remaining());return result.map(function(values){return values.withValue(exports.sequence.source,source)})};return rule.head=function(){var firstCapture=_.find(parsers,isCapturedRule);return exports.then(rule,exports.sequence.extract(firstCapture))},rule.map=function(func){return exports.then(rule,function(result){return func.apply(this,result.toArray())})},rule};var SequenceValues=function(values,valuesArray){this._values=values||{},this._valuesArray=valuesArray||[]};SequenceValues.prototype.withValue=function(rule,value){if(rule.captureName&&rule.captureName in this._values)throw new Error('Cannot add second value for capture "'+rule.captureName+'"');var newValues=_.clone(this._values);newValues[rule.captureName]=value;var newValuesArray=this._valuesArray.concat([value]);return new SequenceValues(newValues,newValuesArray)},SequenceValues.prototype.get=function(rule){if(rule.captureName in this._values)return this._values[rule.captureName];throw new Error('No value for capture "'+rule.captureName+'"')},SequenceValues.prototype.toArray=function(){return this._valuesArray},exports.sequence.capture=function(rule,name){var captureRule=function(){return rule.apply(this,arguments)};return captureRule.captureName=name,captureRule.isCaptured=!0,captureRule},exports.sequence.extract=function(rule){return function(result){return result.get(rule)}},exports.sequence.applyValues=function(func){var rules=Array.prototype.slice.call(arguments,1);return function(result){var values=rules.map(function(rule){return result.get(rule)});return func.apply(this,values)}},exports.sequence.source={captureName:"☃source☃"},exports.sequence.cut=function(){return function(input){return results.cut(input)}},exports.optional=function(rule){return function(input){var result=rule(input);return result.isSuccess()?result.map(options.some):result.isFailure()?results.success(options.none,input):result}},exports.zeroOrMoreWithSeparator=function(rule,separator){return repeatedWithSeparator(rule,separator,!1)},exports.oneOrMoreWithSeparator=function(rule,separator){return repeatedWithSeparator(rule,separator,!0)};var zeroOrMore=exports.zeroOrMore=function(rule){return function(input){for(var result,values=[];(result=rule(input))&&result.isSuccess();)input=result.remaining(),values.push(result.value());return result.isError()?result:results.success(values,input)}};exports.oneOrMore=function(rule){return exports.oneOrMoreWithSeparator(rule,noOpRule)};var repeatedWithSeparator=function(rule,separator,isOneOrMore){return function(input){var result=rule(input);if(result.isSuccess()){var mainRule=exports.sequence.capture(rule,"main"),remainingRule=zeroOrMore(exports.then(exports.sequence(separator,mainRule),exports.sequence.extract(mainRule))),remainingResult=remainingRule(result.remaining());return results.success([result.value()].concat(remainingResult.value()),remainingResult.remaining())}return isOneOrMore||result.isError()?result:results.success([],input)}};exports.leftAssociative=function(leftRule,rightRule,func){var rights;rights=func?[{func:func,rule:rightRule}]:rightRule,rights=rights.map(function(right){return exports.then(right.rule,function(rightValue){return function(leftValue,source){return right.func(leftValue,rightValue,source)}})});var repeatedRule=exports.firstOf.apply(null,["rules"].concat(rights));return function(input){var start=input,leftResult=leftRule(input);if(!leftResult.isSuccess())return leftResult;for(var repeatedResult=repeatedRule(leftResult.remaining());repeatedResult.isSuccess();){var remaining=repeatedResult.remaining(),source=start.to(repeatedResult.remaining()),right=repeatedResult.value();leftResult=results.success(right(leftResult.value(),source),remaining,source),repeatedResult=repeatedRule(leftResult.remaining())}return repeatedResult.isError()?repeatedResult:leftResult}},exports.leftAssociative.firstOf=function(){return Array.prototype.slice.call(arguments,0)},exports.nonConsuming=function(rule){return function(input){return rule(input).changeRemaining(input)}};var describeToken=function(token){return token.value?token.name+' "'+token.value+'"':token.name}},{"./errors":59,"./lazy-iterators":60,"./parsing-results":62,option:65,underscore:67}],65:[function(require,module,exports){function callOrReturn(value){return"function"==typeof value?value():value}exports.none=Object.create({value:function(){throw new Error("Called value on none")},isNone:function(){return!0},isSome:function(){return!1},map:function(){return exports.none},flatMap:function(){return exports.none},filter:function(){return exports.none},toArray:function(){return[]},orElse:callOrReturn,valueOrElse:callOrReturn}),exports.some=function(value){return new Some(value)};var Some=function(value){this._value=value};Some.prototype.value=function(){return this._value},Some.prototype.isNone=function(){return!1},Some.prototype.isSome=function(){return!0},Some.prototype.map=function(func){return new Some(func(this._value))},Some.prototype.flatMap=function(func){return func(this._value)},Some.prototype.filter=function(predicate){return predicate(this._value)?this:exports.none},Some.prototype.toArray=function(){return[this._value]},Some.prototype.orElse=function(value){return this},Some.prototype.valueOrElse=function(value){return this._value},exports.isOption=function(value){return value===exports.none||value instanceof Some},exports.fromNullable=function(value){return null==value?exports.none:new Some(value)}},{}],66:[function(require,module,exports){function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}function runTimeout(fun){if(cachedSetTimeout===setTimeout)return setTimeout(fun,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(fun,0);try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout)return clearTimeout(marker);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(marker);try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var timeout=runTimeout(cleanUpNextTick);draining=!0;for(var len=queue.length;len;){for(currentQueue=queue,queue=[];++queueIndex1)for(var i=1;iindex;index++)rest[index]=arguments[index+startIndex];switch(startIndex){case 0:return func.call(this,rest);case 1:return func.call(this,arguments[0],rest);case 2:return func.call(this,arguments[0],arguments[1],rest)}var args=Array(startIndex+1);for(index=0;startIndex>index;index++)args[index]=arguments[index];return args[startIndex]=rest,func.apply(this,args)}}function isObject(obj){var type=typeof obj;return"function"===type||"object"===type&&!!obj}function isNull(obj){return null===obj}function isUndefined(obj){return void 0===obj}function isBoolean(obj){return obj===!0||obj===!1||"[object Boolean]"===toString.call(obj)}function isElement(obj){return!(!obj||1!==obj.nodeType)}function tagTester(name){var tag="[object "+name+"]";return function(obj){return toString.call(obj)===tag}}function ie10IsDataView(obj){return null!=obj&&isFunction$1(obj.getInt8)&&isArrayBuffer(obj.buffer)}function has$1(obj,key){return null!=obj&&hasOwnProperty.call(obj,key)}function isFinite$1(obj){return!isSymbol(obj)&&_isFinite(obj)&&!isNaN(parseFloat(obj))}function isNaN$1(obj){return isNumber(obj)&&_isNaN(obj)}function constant(value){return function(){return value}}function createSizePropertyCheck(getSizeProperty){return function(collection){var sizeProperty=getSizeProperty(collection);return"number"==typeof sizeProperty&&sizeProperty>=0&&MAX_ARRAY_INDEX>=sizeProperty}}function shallowProperty(key){return function(obj){return null==obj?void 0:obj[key]}}function isTypedArray(obj){return nativeIsView?nativeIsView(obj)&&!isDataView$1(obj):isBufferLike(obj)&&typedArrayPattern.test(toString.call(obj))}function emulatedSet(keys){for(var hash={},l=keys.length,i=0;l>i;++i)hash[keys[i]]=!0;return{contains:function(key){return hash[key]},push:function(key){return hash[key]=!0,keys.push(key)}}}function collectNonEnumProps(obj,keys){keys=emulatedSet(keys);var nonEnumIdx=nonEnumerableProps.length,constructor=obj.constructor,proto=isFunction$1(constructor)&&constructor.prototype||ObjProto,prop="constructor";for(has$1(obj,prop)&&!keys.contains(prop)&&keys.push(prop);nonEnumIdx--;)prop=nonEnumerableProps[nonEnumIdx],prop in obj&&obj[prop]!==proto[prop]&&!keys.contains(prop)&&keys.push(prop)}function keys(obj){if(!isObject(obj))return[];if(nativeKeys)return nativeKeys(obj);var keys=[];for(var key in obj)has$1(obj,key)&&keys.push(key);return hasEnumBug&&collectNonEnumProps(obj,keys),keys}function isEmpty(obj){if(null==obj)return!0;var length=getLength(obj);return"number"==typeof length&&(isArray(obj)||isString(obj)||isArguments$1(obj))?0===length:0===getLength(keys(obj))}function isMatch(object,attrs){var _keys=keys(attrs),length=_keys.length;if(null==object)return!length;for(var obj=Object(object),i=0;length>i;i++){var key=_keys[i];if(attrs[key]!==obj[key]||!(key in obj))return!1}return!0}function _$1(obj){return obj instanceof _$1?obj:this instanceof _$1?void(this._wrapped=obj):new _$1(obj)}function toBufferView(bufferSource){return new Uint8Array(bufferSource.buffer||bufferSource,bufferSource.byteOffset||0,getByteLength(bufferSource))}function eq(a,b,aStack,bStack){if(a===b)return 0!==a||1/a===1/b;if(null==a||null==b)return!1;if(a!==a)return b!==b;var type=typeof a;return"function"!==type&&"object"!==type&&"object"!=typeof b?!1:deepEq(a,b,aStack,bStack)}function deepEq(a,b,aStack,bStack){a instanceof _$1&&(a=a._wrapped),b instanceof _$1&&(b=b._wrapped);var className=toString.call(a);if(className!==toString.call(b))return!1;if(hasStringTagBug&&"[object Object]"==className&&isDataView$1(a)){if(!isDataView$1(b))return!1;className=tagDataView}switch(className){case"[object RegExp]":case"[object String]":return""+a==""+b;case"[object Number]":return+a!==+a?+b!==+b:0===+a?1/+a===1/b:+a===+b;case"[object Date]":case"[object Boolean]":return+a===+b;case"[object Symbol]":return SymbolProto.valueOf.call(a)===SymbolProto.valueOf.call(b);case"[object ArrayBuffer]":case tagDataView:return deepEq(toBufferView(a),toBufferView(b),aStack,bStack)}var areArrays="[object Array]"===className;if(!areArrays&&isTypedArray$1(a)){var byteLength=getByteLength(a);if(byteLength!==getByteLength(b))return!1;if(a.buffer===b.buffer&&a.byteOffset===b.byteOffset)return!0;areArrays=!0}if(!areArrays){if("object"!=typeof a||"object"!=typeof b)return!1;var aCtor=a.constructor,bCtor=b.constructor;if(aCtor!==bCtor&&!(isFunction$1(aCtor)&&aCtor instanceof aCtor&&isFunction$1(bCtor)&&bCtor instanceof bCtor)&&"constructor"in a&&"constructor"in b)return!1}aStack=aStack||[],bStack=bStack||[];for(var length=aStack.length;length--;)if(aStack[length]===a)return bStack[length]===b;if(aStack.push(a),bStack.push(b),areArrays){if(length=a.length,length!==b.length)return!1;for(;length--;)if(!eq(a[length],b[length],aStack,bStack))return!1}else{var key,_keys=keys(a);if(length=_keys.length,keys(b).length!==length)return!1;for(;length--;)if(key=_keys[length],!has$1(b,key)||!eq(a[key],b[key],aStack,bStack))return!1}return aStack.pop(),bStack.pop(),!0}function isEqual(a,b){return eq(a,b)}function allKeys(obj){if(!isObject(obj))return[];var keys=[];for(var key in obj)keys.push(key);return hasEnumBug&&collectNonEnumProps(obj,keys),keys}function ie11fingerprint(methods){var length=getLength(methods);return function(obj){if(null==obj)return!1;var keys=allKeys(obj);if(getLength(keys))return!1;for(var i=0;length>i;i++)if(!isFunction$1(obj[methods[i]]))return!1;return methods!==weakMapMethods||!isFunction$1(obj[forEachName])}}function values(obj){for(var _keys=keys(obj),length=_keys.length,values=Array(length),i=0;length>i;i++)values[i]=obj[_keys[i]];return values}function pairs(obj){for(var _keys=keys(obj),length=_keys.length,pairs=Array(length),i=0;length>i;i++)pairs[i]=[_keys[i],obj[_keys[i]]];return pairs}function invert(obj){for(var result={},_keys=keys(obj),i=0,length=_keys.length;length>i;i++)result[obj[_keys[i]]]=_keys[i];return result}function functions(obj){var names=[];for(var key in obj)isFunction$1(obj[key])&&names.push(key);return names.sort()}function createAssigner(keysFunc,defaults){return function(obj){var length=arguments.length;if(defaults&&(obj=Object(obj)),2>length||null==obj)return obj;for(var index=1;length>index;index++)for(var source=arguments[index],keys=keysFunc(source),l=keys.length,i=0;l>i;i++){var key=keys[i];defaults&&void 0!==obj[key]||(obj[key]=source[key])}return obj}}function ctor(){return function(){}}function baseCreate(prototype){if(!isObject(prototype))return{};if(nativeCreate)return nativeCreate(prototype);var Ctor=ctor();Ctor.prototype=prototype;var result=new Ctor;return Ctor.prototype=null,result}function create(prototype,props){var result=baseCreate(prototype);return props&&extendOwn(result,props),result}function clone(obj){return isObject(obj)?isArray(obj)?obj.slice():extend({},obj):obj}function tap(obj,interceptor){return interceptor(obj),obj}function toPath$1(path){return isArray(path)?path:[path]}function toPath(path){return _$1.toPath(path)}function deepGet(obj,path){for(var length=path.length,i=0;length>i;i++){if(null==obj)return void 0;obj=obj[path[i]]}return length?obj:void 0}function get(object,path,defaultValue){var value=deepGet(object,toPath(path));return isUndefined(value)?defaultValue:value}function has(obj,path){path=toPath(path);for(var length=path.length,i=0;length>i;i++){var key=path[i];if(!has$1(obj,key))return!1;obj=obj[key]}return!!length}function identity(value){return value}function matcher(attrs){return attrs=extendOwn({},attrs),function(obj){return isMatch(obj,attrs)}}function property(path){return path=toPath(path),function(obj){return deepGet(obj,path)}}function optimizeCb(func,context,argCount){if(void 0===context)return func;switch(null==argCount?3:argCount){case 1:return function(value){return func.call(context,value)};case 3:return function(value,index,collection){return func.call(context,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(context,accumulator,value,index,collection)}}return function(){return func.apply(context,arguments)}}function baseIteratee(value,context,argCount){return null==value?identity:isFunction$1(value)?optimizeCb(value,context,argCount):isObject(value)&&!isArray(value)?matcher(value):property(value)}function iteratee(value,context){return baseIteratee(value,context,1/0)}function cb(value,context,argCount){return _$1.iteratee!==iteratee?_$1.iteratee(value,context):baseIteratee(value,context,argCount)}function mapObject(obj,iteratee,context){iteratee=cb(iteratee,context);for(var _keys=keys(obj),length=_keys.length,results={},index=0;length>index;index++){var currentKey=_keys[index];results[currentKey]=iteratee(obj[currentKey],currentKey,obj)}return results}function noop(){}function propertyOf(obj){return null==obj?noop:function(path){return get(obj,path)}}function times(n,iteratee,context){var accum=Array(Math.max(0,n));iteratee=optimizeCb(iteratee,context,1);for(var i=0;n>i;i++)accum[i]=iteratee(i);return accum}function random(min,max){return null==max&&(max=min,min=0),min+Math.floor(Math.random()*(max-min+1))}function createEscaper(map){var escaper=function(match){return map[match]},source="(?:"+keys(map).join("|")+")",testRegexp=RegExp(source),replaceRegexp=RegExp(source,"g");return function(string){return string=null==string?"":""+string,testRegexp.test(string)?string.replace(replaceRegexp,escaper):string}}function escapeChar(match){return"\\"+escapes[match]}function template(text,settings,oldSettings){!settings&&oldSettings&&(settings=oldSettings),settings=defaults({},settings,_$1.templateSettings);var matcher=RegExp([(settings.escape||noMatch).source,(settings.interpolate||noMatch).source,(settings.evaluate||noMatch).source].join("|")+"|$","g"),index=0,source="__p+='";text.replace(matcher,function(match,escape,interpolate,evaluate,offset){return source+=text.slice(index,offset).replace(escapeRegExp,escapeChar),index=offset+match.length,escape?source+="'+\n((__t=("+escape+"))==null?'':_.escape(__t))+\n'":interpolate?source+="'+\n((__t=("+interpolate+"))==null?'':__t)+\n'":evaluate&&(source+="';\n"+evaluate+"\n__p+='"),match}),source+="';\n";var argument=settings.variable;if(argument){if(!bareIdentifier.test(argument))throw new Error("variable is not a bare identifier: "+argument)}else source="with(obj||{}){\n"+source+"}\n",argument="obj";source="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+source+"return __p;\n";var render;try{render=new Function(argument,"_",source)}catch(e){throw e.source=source,e}var template=function(data){return render.call(this,data,_$1)};return template.source="function("+argument+"){\n"+source+"}",template}function result(obj,path,fallback){path=toPath(path);var length=path.length;if(!length)return isFunction$1(fallback)?fallback.call(obj):fallback;for(var i=0;length>i;i++){var prop=null==obj?void 0:obj[path[i]];void 0===prop&&(prop=fallback,i=length),obj=isFunction$1(prop)?prop.call(obj):prop}return obj}function uniqueId(prefix){var id=++idCounter+"";return prefix?prefix+id:id}function chain(obj){var instance=_$1(obj);return instance._chain=!0,instance}function executeBound(sourceFunc,boundFunc,context,callingContext,args){if(!(callingContext instanceof boundFunc))return sourceFunc.apply(context,args);var self=baseCreate(sourceFunc.prototype),result=sourceFunc.apply(self,args);return isObject(result)?result:self}function flatten$1(input,depth,strict,output){if(output=output||[],depth||0===depth){if(0>=depth)return output.concat(input)}else depth=1/0;for(var idx=output.length,i=0,length=getLength(input);length>i;i++){var value=input[i];if(isArrayLike(value)&&(isArray(value)||isArguments$1(value)))if(depth>1)flatten$1(value,depth-1,strict,output), +idx=output.length;else for(var j=0,len=value.length;len>j;)output[idx++]=value[j++];else strict||(output[idx++]=value)}return output}function memoize(func,hasher){var memoize=function(key){var cache=memoize.cache,address=""+(hasher?hasher.apply(this,arguments):key);return has$1(cache,address)||(cache[address]=func.apply(this,arguments)),cache[address]};return memoize.cache={},memoize}function throttle(func,wait,options){var timeout,context,args,result,previous=0;options||(options={});var later=function(){previous=options.leading===!1?0:now(),timeout=null,result=func.apply(context,args),timeout||(context=args=null)},throttled=function(){var _now=now();previous||options.leading!==!1||(previous=_now);var remaining=wait-(_now-previous);return context=this,args=arguments,0>=remaining||remaining>wait?(timeout&&(clearTimeout(timeout),timeout=null),previous=_now,result=func.apply(context,args),timeout||(context=args=null)):timeout||options.trailing===!1||(timeout=setTimeout(later,remaining)),result};return throttled.cancel=function(){clearTimeout(timeout),previous=0,timeout=context=args=null},throttled}function debounce(func,wait,immediate){var timeout,previous,args,result,context,later=function(){var passed=now()-previous;wait>passed?timeout=setTimeout(later,wait-passed):(timeout=null,immediate||(result=func.apply(context,args)),timeout||(args=context=null))},debounced=restArguments(function(_args){return context=this,args=_args,previous=now(),timeout||(timeout=setTimeout(later,wait),immediate&&(result=func.apply(context,args))),result});return debounced.cancel=function(){clearTimeout(timeout),timeout=args=context=null},debounced}function wrap(func,wrapper){return partial(wrapper,func)}function negate(predicate){return function(){return!predicate.apply(this,arguments)}}function compose(){var args=arguments,start=args.length-1;return function(){for(var i=start,result=args[start].apply(this,arguments);i--;)result=args[i].call(this,result);return result}}function after(times,func){return function(){return--times<1?func.apply(this,arguments):void 0}}function before(times,func){var memo;return function(){return--times>0&&(memo=func.apply(this,arguments)),1>=times&&(func=null),memo}}function findKey(obj,predicate,context){predicate=cb(predicate,context);for(var key,_keys=keys(obj),i=0,length=_keys.length;length>i;i++)if(key=_keys[i],predicate(obj[key],key,obj))return key}function createPredicateIndexFinder(dir){return function(array,predicate,context){predicate=cb(predicate,context);for(var length=getLength(array),index=dir>0?0:length-1;index>=0&&length>index;index+=dir)if(predicate(array[index],index,array))return index;return-1}}function sortedIndex(array,obj,iteratee,context){iteratee=cb(iteratee,context,1);for(var value=iteratee(obj),low=0,high=getLength(array);high>low;){var mid=Math.floor((low+high)/2);iteratee(array[mid])0?i=idx>=0?idx:Math.max(idx+length,i):length=idx>=0?Math.min(idx+1,length):idx+length+1;else if(sortedIndex&&idx&&length)return idx=sortedIndex(array,item),array[idx]===item?idx:-1;if(item!==item)return idx=predicateFind(slice.call(array,i,length),isNaN$1),idx>=0?idx+i:-1;for(idx=dir>0?i:length-1;idx>=0&&length>idx;idx+=dir)if(array[idx]===item)return idx;return-1}}function find(obj,predicate,context){var keyFinder=isArrayLike(obj)?findIndex:findKey,key=keyFinder(obj,predicate,context);return void 0!==key&&-1!==key?obj[key]:void 0}function findWhere(obj,attrs){return find(obj,matcher(attrs))}function each(obj,iteratee,context){iteratee=optimizeCb(iteratee,context);var i,length;if(isArrayLike(obj))for(i=0,length=obj.length;length>i;i++)iteratee(obj[i],i,obj);else{var _keys=keys(obj);for(i=0,length=_keys.length;length>i;i++)iteratee(obj[_keys[i]],_keys[i],obj)}return obj}function map(obj,iteratee,context){iteratee=cb(iteratee,context);for(var _keys=!isArrayLike(obj)&&keys(obj),length=(_keys||obj).length,results=Array(length),index=0;length>index;index++){var currentKey=_keys?_keys[index]:index;results[index]=iteratee(obj[currentKey],currentKey,obj)}return results}function createReduce(dir){var reducer=function(obj,iteratee,memo,initial){var _keys=!isArrayLike(obj)&&keys(obj),length=(_keys||obj).length,index=dir>0?0:length-1;for(initial||(memo=obj[_keys?_keys[index]:index],index+=dir);index>=0&&length>index;index+=dir){var currentKey=_keys?_keys[index]:index;memo=iteratee(memo,obj[currentKey],currentKey,obj)}return memo};return function(obj,iteratee,memo,context){var initial=arguments.length>=3;return reducer(obj,optimizeCb(iteratee,context,4),memo,initial)}}function filter(obj,predicate,context){var results=[];return predicate=cb(predicate,context),each(obj,function(value,index,list){predicate(value,index,list)&&results.push(value)}),results}function reject(obj,predicate,context){return filter(obj,negate(cb(predicate)),context)}function every(obj,predicate,context){predicate=cb(predicate,context);for(var _keys=!isArrayLike(obj)&&keys(obj),length=(_keys||obj).length,index=0;length>index;index++){var currentKey=_keys?_keys[index]:index;if(!predicate(obj[currentKey],currentKey,obj))return!1}return!0}function some(obj,predicate,context){predicate=cb(predicate,context);for(var _keys=!isArrayLike(obj)&&keys(obj),length=(_keys||obj).length,index=0;length>index;index++){var currentKey=_keys?_keys[index]:index;if(predicate(obj[currentKey],currentKey,obj))return!0}return!1}function contains(obj,item,fromIndex,guard){return isArrayLike(obj)||(obj=values(obj)),("number"!=typeof fromIndex||guard)&&(fromIndex=0),indexOf(obj,item,fromIndex)>=0}function pluck(obj,key){return map(obj,property(key))}function where(obj,attrs){return filter(obj,matcher(attrs))}function max(obj,iteratee,context){var value,computed,result=-(1/0),lastComputed=-(1/0);if(null==iteratee||"number"==typeof iteratee&&"object"!=typeof obj[0]&&null!=obj){obj=isArrayLike(obj)?obj:values(obj);for(var i=0,length=obj.length;length>i;i++)value=obj[i],null!=value&&value>result&&(result=value)}else iteratee=cb(iteratee,context),each(obj,function(v,index,list){computed=iteratee(v,index,list),(computed>lastComputed||computed===-(1/0)&&result===-(1/0))&&(result=v,lastComputed=computed)});return result}function min(obj,iteratee,context){var value,computed,result=1/0,lastComputed=1/0;if(null==iteratee||"number"==typeof iteratee&&"object"!=typeof obj[0]&&null!=obj){obj=isArrayLike(obj)?obj:values(obj);for(var i=0,length=obj.length;length>i;i++)value=obj[i],null!=value&&result>value&&(result=value)}else iteratee=cb(iteratee,context),each(obj,function(v,index,list){computed=iteratee(v,index,list),(lastComputed>computed||computed===1/0&&result===1/0)&&(result=v,lastComputed=computed)});return result}function sample(obj,n,guard){if(null==n||guard)return isArrayLike(obj)||(obj=values(obj)),obj[random(obj.length-1)];var sample=isArrayLike(obj)?clone(obj):values(obj),length=getLength(sample);n=Math.max(Math.min(n,length),0);for(var last=length-1,index=0;n>index;index++){var rand=random(index,last),temp=sample[index];sample[index]=sample[rand],sample[rand]=temp}return sample.slice(0,n)}function shuffle(obj){return sample(obj,1/0)}function sortBy(obj,iteratee,context){var index=0;return iteratee=cb(iteratee,context),pluck(map(obj,function(value,key,list){return{value:value,index:index++,criteria:iteratee(value,key,list)}}).sort(function(left,right){var a=left.criteria,b=right.criteria;if(a!==b){if(a>b||void 0===a)return 1;if(b>a||void 0===b)return-1}return left.index-right.index}),"value")}function group(behavior,partition){return function(obj,iteratee,context){var result=partition?[[],[]]:{};return iteratee=cb(iteratee,context),each(obj,function(value,index){var key=iteratee(value,index,obj);behavior(result,value,key)}),result}}function toArray(obj){return obj?isArray(obj)?slice.call(obj):isString(obj)?obj.match(reStrSymbol):isArrayLike(obj)?map(obj,identity):values(obj):[]}function size(obj){return null==obj?0:isArrayLike(obj)?obj.length:keys(obj).length}function keyInObj(value,key,obj){return key in obj}function initial(array,n,guard){return slice.call(array,0,Math.max(0,array.length-(null==n||guard?1:n)))}function first(array,n,guard){return null==array||array.length<1?null==n||guard?void 0:[]:null==n||guard?array[0]:initial(array,array.length-n)}function rest(array,n,guard){return slice.call(array,null==n||guard?1:n)}function last(array,n,guard){return null==array||array.length<1?null==n||guard?void 0:[]:null==n||guard?array[array.length-1]:rest(array,Math.max(0,array.length-n))}function compact(array){return filter(array,Boolean)}function flatten(array,depth){return flatten$1(array,depth,!1)}function uniq(array,isSorted,iteratee,context){isBoolean(isSorted)||(context=iteratee,iteratee=isSorted,isSorted=!1),null!=iteratee&&(iteratee=cb(iteratee,context));for(var result=[],seen=[],i=0,length=getLength(array);length>i;i++){var value=array[i],computed=iteratee?iteratee(value,i,array):value;isSorted&&!iteratee?(i&&seen===computed||result.push(value),seen=computed):iteratee?contains(seen,computed)||(seen.push(computed),result.push(value)):contains(result,value)||result.push(value)}return result}function intersection(array){for(var result=[],argsLength=arguments.length,i=0,length=getLength(array);length>i;i++){var item=array[i];if(!contains(result,item)){var j;for(j=1;argsLength>j&&contains(arguments[j],item);j++);j===argsLength&&result.push(item)}}return result}function unzip(array){for(var length=array&&max(array,getLength).length||0,result=Array(length),index=0;length>index;index++)result[index]=pluck(array,index);return result}function object(list,values){for(var result={},i=0,length=getLength(list);length>i;i++)values?result[list[i]]=values[i]:result[list[i][0]]=list[i][1];return result}function range(start,stop,step){null==stop&&(stop=start||0,start=0),step||(step=start>stop?-1:1);for(var length=Math.max(Math.ceil((stop-start)/step),0),range=Array(length),idx=0;length>idx;idx++,start+=step)range[idx]=start;return range}function chunk(array,count){if(null==count||1>count)return[];for(var result=[],i=0,length=array.length;length>i;)result.push(slice.call(array,i,i+=count));return result}function chainResult(instance,obj){return instance._chain?_$1(obj).chain():obj}function mixin(obj){return each(functions(obj),function(name){var func=_$1[name]=obj[name];_$1.prototype[name]=function(){var args=[this._wrapped];return push.apply(args,arguments),chainResult(this,func.apply(_$1,args))}}),_$1}var VERSION="1.13.1",root="object"==typeof self&&self.self===self&&self||"object"==typeof global&&global.global===global&&global||Function("return this")()||{},ArrayProto=Array.prototype,ObjProto=Object.prototype,SymbolProto="undefined"!=typeof Symbol?Symbol.prototype:null,push=ArrayProto.push,slice=ArrayProto.slice,toString=ObjProto.toString,hasOwnProperty=ObjProto.hasOwnProperty,supportsArrayBuffer="undefined"!=typeof ArrayBuffer,supportsDataView="undefined"!=typeof DataView,nativeIsArray=Array.isArray,nativeKeys=Object.keys,nativeCreate=Object.create,nativeIsView=supportsArrayBuffer&&ArrayBuffer.isView,_isNaN=isNaN,_isFinite=isFinite,hasEnumBug=!{toString:null}.propertyIsEnumerable("toString"),nonEnumerableProps=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"],MAX_ARRAY_INDEX=Math.pow(2,53)-1,isString=tagTester("String"),isNumber=tagTester("Number"),isDate=tagTester("Date"),isRegExp=tagTester("RegExp"),isError=tagTester("Error"),isSymbol=tagTester("Symbol"),isArrayBuffer=tagTester("ArrayBuffer"),isFunction=tagTester("Function"),nodelist=root.document&&root.document.childNodes;"function"!=typeof/./&&"object"!=typeof Int8Array&&"function"!=typeof nodelist&&(isFunction=function(obj){return"function"==typeof obj||!1});var isFunction$1=isFunction,hasObjectTag=tagTester("Object"),hasStringTagBug=supportsDataView&&hasObjectTag(new DataView(new ArrayBuffer(8))),isIE11="undefined"!=typeof Map&&hasObjectTag(new Map),isDataView=tagTester("DataView"),isDataView$1=hasStringTagBug?ie10IsDataView:isDataView,isArray=nativeIsArray||tagTester("Array"),isArguments=tagTester("Arguments");!function(){isArguments(arguments)||(isArguments=function(obj){return has$1(obj,"callee")})}();var isArguments$1=isArguments,getByteLength=shallowProperty("byteLength"),isBufferLike=createSizePropertyCheck(getByteLength),typedArrayPattern=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/,isTypedArray$1=supportsArrayBuffer?isTypedArray:constant(!1),getLength=shallowProperty("length");_$1.VERSION=VERSION,_$1.prototype.value=function(){return this._wrapped},_$1.prototype.valueOf=_$1.prototype.toJSON=_$1.prototype.value,_$1.prototype.toString=function(){return String(this._wrapped)};var tagDataView="[object DataView]",forEachName="forEach",hasName="has",commonInit=["clear","delete"],mapTail=["get",hasName,"set"],mapMethods=commonInit.concat(forEachName,mapTail),weakMapMethods=commonInit.concat(mapTail),setMethods=["add"].concat(commonInit,forEachName,hasName),isMap=isIE11?ie11fingerprint(mapMethods):tagTester("Map"),isWeakMap=isIE11?ie11fingerprint(weakMapMethods):tagTester("WeakMap"),isSet=isIE11?ie11fingerprint(setMethods):tagTester("Set"),isWeakSet=tagTester("WeakSet"),extend=createAssigner(allKeys),extendOwn=createAssigner(keys),defaults=createAssigner(allKeys,!0);_$1.toPath=toPath$1,_$1.iteratee=iteratee;var now=Date.now||function(){return(new Date).getTime()},escapeMap={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},_escape=createEscaper(escapeMap),unescapeMap=invert(escapeMap),_unescape=createEscaper(unescapeMap),templateSettings=_$1.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},noMatch=/(.)^/,escapes={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},escapeRegExp=/\\|'|\r|\n|\u2028|\u2029/g,bareIdentifier=/^\s*(\w|\$)+\s*$/,idCounter=0,partial=restArguments(function(func,boundArgs){var placeholder=partial.placeholder,bound=function(){for(var position=0,length=boundArgs.length,args=Array(length),i=0;length>i;i++)args[i]=boundArgs[i]===placeholder?arguments[position++]:boundArgs[i];for(;positionindex)throw new Error("bindAll must be passed function names");for(;index--;){var key=keys[index];obj[key]=bind(obj[key],obj)}return obj}),delay=restArguments(function(func,wait,args){return setTimeout(function(){return func.apply(null,args)},wait)}),defer=partial(delay,_$1,1),once=partial(before,2),findIndex=createPredicateIndexFinder(1),findLastIndex=createPredicateIndexFinder(-1),indexOf=createIndexFinder(1,findIndex,sortedIndex),lastIndexOf=createIndexFinder(-1,findLastIndex),reduce=createReduce(1),reduceRight=createReduce(-1),invoke=restArguments(function(obj,path,args){var contextPath,func;return isFunction$1(path)?func=path:(path=toPath(path),contextPath=path.slice(0,-1),path=path[path.length-1]),map(obj,function(context){var method=func;if(!method){if(contextPath&&contextPath.length&&(context=deepGet(context,contextPath)),null==context)return void 0;method=context[path]}return null==method?method:method.apply(context,args)})}),groupBy=group(function(result,value,key){has$1(result,key)?result[key].push(value):result[key]=[value]}),indexBy=group(function(result,value,key){result[key]=value}),countBy=group(function(result,value,key){has$1(result,key)?result[key]++:result[key]=1}),partition=group(function(result,value,pass){result[pass?0:1].push(value)},!0),reStrSymbol=/[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g,pick=restArguments(function(obj,keys){var result={},iteratee=keys[0];if(null==obj)return result;isFunction$1(iteratee)?(keys.length>1&&(iteratee=optimizeCb(iteratee,keys[1])),keys=allKeys(obj)):(iteratee=keyInObj,keys=flatten$1(keys,!1,!1),obj=Object(obj));for(var i=0,length=keys.length;length>i;i++){var key=keys[i],value=obj[key];iteratee(value,key,obj)&&(result[key]=value)}return result}),omit=restArguments(function(obj,keys){var context,iteratee=keys[0];return isFunction$1(iteratee)?(iteratee=negate(iteratee),keys.length>1&&(context=keys[1])):(keys=map(flatten$1(keys,!1,!1),String),iteratee=function(value,key){return!contains(keys,key)}),pick(obj,iteratee,context)}),difference=restArguments(function(array,rest){return rest=flatten$1(rest,!0,!0),filter(array,function(value){return!contains(rest,value)})}),without=restArguments(function(array,otherArrays){return difference(array,otherArrays)}),union=restArguments(function(arrays){return uniq(flatten$1(arrays,!0,!0))}),zip=restArguments(unzip);each(["pop","push","reverse","shift","sort","splice","unshift"],function(name){var method=ArrayProto[name];_$1.prototype[name]=function(){var obj=this._wrapped;return null!=obj&&(method.apply(obj,arguments),"shift"!==name&&"splice"!==name||0!==obj.length||delete obj[0]),chainResult(this,obj)}}),each(["concat","join","slice"],function(name){var method=ArrayProto[name];_$1.prototype[name]=function(){var obj=this._wrapped;return null!=obj&&(obj=method.apply(obj,arguments)),chainResult(this,obj)}});var allExports={__proto__:null,VERSION:VERSION,restArguments:restArguments,isObject:isObject,isNull:isNull,isUndefined:isUndefined,isBoolean:isBoolean,isElement:isElement,isString:isString,isNumber:isNumber,isDate:isDate,isRegExp:isRegExp,isError:isError,isSymbol:isSymbol,isArrayBuffer:isArrayBuffer,isDataView:isDataView$1,isArray:isArray,isFunction:isFunction$1,isArguments:isArguments$1,isFinite:isFinite$1,isNaN:isNaN$1,isTypedArray:isTypedArray$1,isEmpty:isEmpty,isMatch:isMatch,isEqual:isEqual,isMap:isMap,isWeakMap:isWeakMap,isSet:isSet,isWeakSet:isWeakSet,keys:keys,allKeys:allKeys,values:values,pairs:pairs,invert:invert,functions:functions,methods:functions,extend:extend,extendOwn:extendOwn,assign:extendOwn,defaults:defaults,create:create,clone:clone,tap:tap,get:get,has:has,mapObject:mapObject,identity:identity,constant:constant,noop:noop,toPath:toPath$1,property:property,propertyOf:propertyOf,matcher:matcher,matches:matcher,times:times,random:random,now:now,escape:_escape,unescape:_unescape,templateSettings:templateSettings,template:template,result:result,uniqueId:uniqueId,chain:chain,iteratee:iteratee,partial:partial,bind:bind,bindAll:bindAll,memoize:memoize,delay:delay,defer:defer,throttle:throttle,debounce:debounce,wrap:wrap,negate:negate,compose:compose,after:after,before:before,once:once,findKey:findKey,findIndex:findIndex,findLastIndex:findLastIndex,sortedIndex:sortedIndex,indexOf:indexOf,lastIndexOf:lastIndexOf,find:find,detect:find,findWhere:findWhere,each:each,forEach:each,map:map,collect:map,reduce:reduce,foldl:reduce,inject:reduce,reduceRight:reduceRight,foldr:reduceRight,filter:filter,select:filter,reject:reject,every:every,all:every,some:some,any:some,contains:contains,includes:contains,include:contains,invoke:invoke,pluck:pluck,where:where,max:max,min:min,shuffle:shuffle,sample:sample,sortBy:sortBy,groupBy:groupBy,indexBy:indexBy,countBy:countBy,partition:partition,toArray:toArray,size:size,pick:pick,omit:omit,first:first,head:first,take:first,initial:initial,last:last,rest:rest,tail:rest,drop:rest,compact:compact,flatten:flatten,without:without,uniq:uniq,unique:uniq,union:union,intersection:intersection,difference:difference,unzip:unzip,transpose:unzip,zip:zip,object:object,range:range,chunk:chunk,mixin:mixin,"default":_$1},_=mixin(allExports);return _._=_,_})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],68:[function(require,module,exports){(function(){var assign,getValue,isArray,isEmpty,isFunction,isObject,isPlainObject,slice=[].slice,hasProp={}.hasOwnProperty;assign=function(){var i,key,len,source,sources,target;if(target=arguments[0],sources=2<=arguments.length?slice.call(arguments,1):[],isFunction(Object.assign))Object.assign.apply(null,arguments);else for(i=0,len=sources.length;len>i;i++)if(source=sources[i],null!=source)for(key in source)hasProp.call(source,key)&&(target[key]=source[key]);return target},isFunction=function(val){return!!val&&"[object Function]"===Object.prototype.toString.call(val)},isObject=function(val){var ref;return!!val&&("function"==(ref=typeof val)||"object"===ref)},isArray=function(val){return isFunction(Array.isArray)?Array.isArray(val):"[object Array]"===Object.prototype.toString.call(val)},isEmpty=function(val){var key;if(isArray(val))return!val.length;for(key in val)if(hasProp.call(val,key))return!1;return!0},isPlainObject=function(val){var ctor,proto;return isObject(val)&&(proto=Object.getPrototypeOf(val))&&(ctor=proto.constructor)&&"function"==typeof ctor&&ctor instanceof ctor&&Function.prototype.toString.call(ctor)===Function.prototype.toString.call(Object)},getValue=function(obj){return isFunction(obj.valueOf)?obj.valueOf():obj},module.exports.assign=assign,module.exports.isFunction=isFunction,module.exports.isObject=isObject,module.exports.isArray=isArray,module.exports.isEmpty=isEmpty,module.exports.isPlainObject=isPlainObject,module.exports.getValue=getValue}).call(this)},{}],69:[function(require,module,exports){(function(){var XMLAttribute;module.exports=XMLAttribute=function(){function XMLAttribute(parent,name,value){if(this.options=parent.options,this.stringify=parent.stringify,this.parent=parent,null==name)throw new Error("Missing attribute name. "+this.debugInfo(name));if(null==value)throw new Error("Missing attribute value. "+this.debugInfo(name));this.name=this.stringify.attName(name),this.value=this.stringify.attValue(value)}return XMLAttribute.prototype.clone=function(){return Object.create(this)},XMLAttribute.prototype.toString=function(options){return this.options.writer.set(options).attribute(this)},XMLAttribute.prototype.debugInfo=function(name){var ref,ref1;return name=name||this.name,null!=name||(null!=(ref=this.parent)?ref.name:void 0)?null==name?"parent: <"+this.parent.name+">":(null!=(ref1=this.parent)?ref1.name:void 0)?"attribute: {"+name+"}, parent: <"+this.parent.name+">":"attribute: {"+name+"}":""},XMLAttribute}()}).call(this)},{}],70:[function(require,module,exports){(function(){var XMLCData,XMLNode,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;XMLNode=require("./XMLNode"),module.exports=XMLCData=function(superClass){function XMLCData(parent,text){if(XMLCData.__super__.constructor.call(this,parent),null==text)throw new Error("Missing CDATA text. "+this.debugInfo());this.text=this.stringify.cdata(text)}return extend(XMLCData,superClass),XMLCData.prototype.clone=function(){return Object.create(this)},XMLCData.prototype.toString=function(options){return this.options.writer.set(options).cdata(this)},XMLCData}(XMLNode)}).call(this)},{"./XMLNode":81}],71:[function(require,module,exports){(function(){var XMLComment,XMLNode,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;XMLNode=require("./XMLNode"),module.exports=XMLComment=function(superClass){function XMLComment(parent,text){if(XMLComment.__super__.constructor.call(this,parent),null==text)throw new Error("Missing comment text. "+this.debugInfo());this.text=this.stringify.comment(text)}return extend(XMLComment,superClass),XMLComment.prototype.clone=function(){return Object.create(this)},XMLComment.prototype.toString=function(options){return this.options.writer.set(options).comment(this)},XMLComment}(XMLNode)}).call(this)},{"./XMLNode":81}],72:[function(require,module,exports){(function(){var XMLDTDAttList,XMLNode,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;XMLNode=require("./XMLNode"),module.exports=XMLDTDAttList=function(superClass){function XMLDTDAttList(parent,elementName,attributeName,attributeType,defaultValueType,defaultValue){if(XMLDTDAttList.__super__.constructor.call(this,parent),null==elementName)throw new Error("Missing DTD element name. "+this.debugInfo());if(null==attributeName)throw new Error("Missing DTD attribute name. "+this.debugInfo(elementName));if(!attributeType)throw new Error("Missing DTD attribute type. "+this.debugInfo(elementName));if(!defaultValueType)throw new Error("Missing DTD attribute default. "+this.debugInfo(elementName));if(0!==defaultValueType.indexOf("#")&&(defaultValueType="#"+defaultValueType),!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/))throw new Error("Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT. "+this.debugInfo(elementName));if(defaultValue&&!defaultValueType.match(/^(#FIXED|#DEFAULT)$/))throw new Error("Default value only applies to #FIXED or #DEFAULT. "+this.debugInfo(elementName));this.elementName=this.stringify.eleName(elementName),this.attributeName=this.stringify.attName(attributeName),this.attributeType=this.stringify.dtdAttType(attributeType),this.defaultValue=this.stringify.dtdAttDefault(defaultValue),this.defaultValueType=defaultValueType}return extend(XMLDTDAttList,superClass),XMLDTDAttList.prototype.toString=function(options){return this.options.writer.set(options).dtdAttList(this)},XMLDTDAttList}(XMLNode)}).call(this)},{"./XMLNode":81}],73:[function(require,module,exports){(function(){var XMLDTDElement,XMLNode,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;XMLNode=require("./XMLNode"),module.exports=XMLDTDElement=function(superClass){function XMLDTDElement(parent,name,value){if(XMLDTDElement.__super__.constructor.call(this,parent),null==name)throw new Error("Missing DTD element name. "+this.debugInfo());value||(value="(#PCDATA)"),Array.isArray(value)&&(value="("+value.join(",")+")"),this.name=this.stringify.eleName(name),this.value=this.stringify.dtdElementValue(value)}return extend(XMLDTDElement,superClass),XMLDTDElement.prototype.toString=function(options){return this.options.writer.set(options).dtdElement(this)},XMLDTDElement}(XMLNode)}).call(this)},{"./XMLNode":81}],74:[function(require,module,exports){(function(){var XMLDTDEntity,XMLNode,isObject,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;isObject=require("./Utility").isObject,XMLNode=require("./XMLNode"),module.exports=XMLDTDEntity=function(superClass){function XMLDTDEntity(parent,pe,name,value){if(XMLDTDEntity.__super__.constructor.call(this,parent),null==name)throw new Error("Missing DTD entity name. "+this.debugInfo(name));if(null==value)throw new Error("Missing DTD entity value. "+this.debugInfo(name));if(this.pe=!!pe,this.name=this.stringify.eleName(name),isObject(value)){if(!value.pubID&&!value.sysID)throw new Error("Public and/or system identifiers are required for an external entity. "+this.debugInfo(name));if(value.pubID&&!value.sysID)throw new Error("System identifier is required for a public external entity. "+this.debugInfo(name));if(null!=value.pubID&&(this.pubID=this.stringify.dtdPubID(value.pubID)),null!=value.sysID&&(this.sysID=this.stringify.dtdSysID(value.sysID)),null!=value.nData&&(this.nData=this.stringify.dtdNData(value.nData)),this.pe&&this.nData)throw new Error("Notation declaration is not allowed in a parameter entity. "+this.debugInfo(name))}else this.value=this.stringify.dtdEntityValue(value)}return extend(XMLDTDEntity,superClass),XMLDTDEntity.prototype.toString=function(options){return this.options.writer.set(options).dtdEntity(this)},XMLDTDEntity}(XMLNode)}).call(this)},{"./Utility":68,"./XMLNode":81}],75:[function(require,module,exports){(function(){var XMLDTDNotation,XMLNode,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;XMLNode=require("./XMLNode"),module.exports=XMLDTDNotation=function(superClass){function XMLDTDNotation(parent,name,value){if(XMLDTDNotation.__super__.constructor.call(this,parent),null==name)throw new Error("Missing DTD notation name. "+this.debugInfo(name));if(!value.pubID&&!value.sysID)throw new Error("Public or system identifiers are required for an external entity. "+this.debugInfo(name));this.name=this.stringify.eleName(name),null!=value.pubID&&(this.pubID=this.stringify.dtdPubID(value.pubID)),null!=value.sysID&&(this.sysID=this.stringify.dtdSysID(value.sysID))}return extend(XMLDTDNotation,superClass),XMLDTDNotation.prototype.toString=function(options){return this.options.writer.set(options).dtdNotation(this)},XMLDTDNotation}(XMLNode)}).call(this)},{"./XMLNode":81}],76:[function(require,module,exports){(function(){var XMLDeclaration,XMLNode,isObject,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;isObject=require("./Utility").isObject,XMLNode=require("./XMLNode"),module.exports=XMLDeclaration=function(superClass){function XMLDeclaration(parent,version,encoding,standalone){var ref;XMLDeclaration.__super__.constructor.call(this,parent),isObject(version)&&(ref=version,version=ref.version,encoding=ref.encoding,standalone=ref.standalone),version||(version="1.0"),this.version=this.stringify.xmlVersion(version),null!=encoding&&(this.encoding=this.stringify.xmlEncoding(encoding)),null!=standalone&&(this.standalone=this.stringify.xmlStandalone(standalone))}return extend(XMLDeclaration,superClass),XMLDeclaration.prototype.toString=function(options){return this.options.writer.set(options).declaration(this)},XMLDeclaration}(XMLNode)}).call(this)},{"./Utility":68,"./XMLNode":81}],77:[function(require,module,exports){(function(){var XMLDTDAttList,XMLDTDElement,XMLDTDEntity,XMLDTDNotation,XMLDocType,XMLNode,isObject,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;isObject=require("./Utility").isObject,XMLNode=require("./XMLNode"),XMLDTDAttList=require("./XMLDTDAttList"),XMLDTDEntity=require("./XMLDTDEntity"),XMLDTDElement=require("./XMLDTDElement"),XMLDTDNotation=require("./XMLDTDNotation"),module.exports=XMLDocType=function(superClass){function XMLDocType(parent,pubID,sysID){var ref,ref1;XMLDocType.__super__.constructor.call(this,parent), +this.name="!DOCTYPE",this.documentObject=parent,isObject(pubID)&&(ref=pubID,pubID=ref.pubID,sysID=ref.sysID),null==sysID&&(ref1=[pubID,sysID],sysID=ref1[0],pubID=ref1[1]),null!=pubID&&(this.pubID=this.stringify.dtdPubID(pubID)),null!=sysID&&(this.sysID=this.stringify.dtdSysID(sysID))}return extend(XMLDocType,superClass),XMLDocType.prototype.element=function(name,value){var child;return child=new XMLDTDElement(this,name,value),this.children.push(child),this},XMLDocType.prototype.attList=function(elementName,attributeName,attributeType,defaultValueType,defaultValue){var child;return child=new XMLDTDAttList(this,elementName,attributeName,attributeType,defaultValueType,defaultValue),this.children.push(child),this},XMLDocType.prototype.entity=function(name,value){var child;return child=new XMLDTDEntity(this,!1,name,value),this.children.push(child),this},XMLDocType.prototype.pEntity=function(name,value){var child;return child=new XMLDTDEntity(this,!0,name,value),this.children.push(child),this},XMLDocType.prototype.notation=function(name,value){var child;return child=new XMLDTDNotation(this,name,value),this.children.push(child),this},XMLDocType.prototype.toString=function(options){return this.options.writer.set(options).docType(this)},XMLDocType.prototype.ele=function(name,value){return this.element(name,value)},XMLDocType.prototype.att=function(elementName,attributeName,attributeType,defaultValueType,defaultValue){return this.attList(elementName,attributeName,attributeType,defaultValueType,defaultValue)},XMLDocType.prototype.ent=function(name,value){return this.entity(name,value)},XMLDocType.prototype.pent=function(name,value){return this.pEntity(name,value)},XMLDocType.prototype.not=function(name,value){return this.notation(name,value)},XMLDocType.prototype.up=function(){return this.root()||this.documentObject},XMLDocType}(XMLNode)}).call(this)},{"./Utility":68,"./XMLDTDAttList":72,"./XMLDTDElement":73,"./XMLDTDEntity":74,"./XMLDTDNotation":75,"./XMLNode":81}],78:[function(require,module,exports){(function(){var XMLDocument,XMLNode,XMLStringWriter,XMLStringifier,isPlainObject,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;isPlainObject=require("./Utility").isPlainObject,XMLNode=require("./XMLNode"),XMLStringifier=require("./XMLStringifier"),XMLStringWriter=require("./XMLStringWriter"),module.exports=XMLDocument=function(superClass){function XMLDocument(options){XMLDocument.__super__.constructor.call(this,null),this.name="?xml",options||(options={}),options.writer||(options.writer=new XMLStringWriter),this.options=options,this.stringify=new XMLStringifier(options),this.isDocument=!0}return extend(XMLDocument,superClass),XMLDocument.prototype.end=function(writer){var writerOptions;return writer?isPlainObject(writer)&&(writerOptions=writer,writer=this.options.writer.set(writerOptions)):writer=this.options.writer,writer.document(this)},XMLDocument.prototype.toString=function(options){return this.options.writer.set(options).document(this)},XMLDocument}(XMLNode)}).call(this)},{"./Utility":68,"./XMLNode":81,"./XMLStringWriter":85,"./XMLStringifier":86}],79:[function(require,module,exports){(function(){var XMLAttribute,XMLCData,XMLComment,XMLDTDAttList,XMLDTDElement,XMLDTDEntity,XMLDTDNotation,XMLDeclaration,XMLDocType,XMLDocumentCB,XMLElement,XMLProcessingInstruction,XMLRaw,XMLStringWriter,XMLStringifier,XMLText,getValue,isFunction,isObject,isPlainObject,ref,hasProp={}.hasOwnProperty;ref=require("./Utility"),isObject=ref.isObject,isFunction=ref.isFunction,isPlainObject=ref.isPlainObject,getValue=ref.getValue,XMLElement=require("./XMLElement"),XMLCData=require("./XMLCData"),XMLComment=require("./XMLComment"),XMLRaw=require("./XMLRaw"),XMLText=require("./XMLText"),XMLProcessingInstruction=require("./XMLProcessingInstruction"),XMLDeclaration=require("./XMLDeclaration"),XMLDocType=require("./XMLDocType"),XMLDTDAttList=require("./XMLDTDAttList"),XMLDTDEntity=require("./XMLDTDEntity"),XMLDTDElement=require("./XMLDTDElement"),XMLDTDNotation=require("./XMLDTDNotation"),XMLAttribute=require("./XMLAttribute"),XMLStringifier=require("./XMLStringifier"),XMLStringWriter=require("./XMLStringWriter"),module.exports=XMLDocumentCB=function(){function XMLDocumentCB(options,onData,onEnd){var writerOptions;this.name="?xml",options||(options={}),options.writer?isPlainObject(options.writer)&&(writerOptions=options.writer,options.writer=new XMLStringWriter(writerOptions)):options.writer=new XMLStringWriter(options),this.options=options,this.writer=options.writer,this.stringify=new XMLStringifier(options),this.onDataCallback=onData||function(){},this.onEndCallback=onEnd||function(){},this.currentNode=null,this.currentLevel=-1,this.openTags={},this.documentStarted=!1,this.documentCompleted=!1,this.root=null}return XMLDocumentCB.prototype.node=function(name,attributes,text){var ref1;if(null==name)throw new Error("Missing node name.");if(this.root&&-1===this.currentLevel)throw new Error("Document can only have one root node. "+this.debugInfo(name));return this.openCurrent(),name=getValue(name),null==attributes&&(attributes={}),attributes=getValue(attributes),isObject(attributes)||(ref1=[attributes,text],text=ref1[0],attributes=ref1[1]),this.currentNode=new XMLElement(this,name,attributes),this.currentNode.children=!1,this.currentLevel++,this.openTags[this.currentLevel]=this.currentNode,null!=text&&this.text(text),this},XMLDocumentCB.prototype.element=function(name,attributes,text){return this.currentNode&&this.currentNode instanceof XMLDocType?this.dtdElement.apply(this,arguments):this.node(name,attributes,text)},XMLDocumentCB.prototype.attribute=function(name,value){var attName,attValue;if(!this.currentNode||this.currentNode.children)throw new Error("att() can only be used immediately after an ele() call in callback mode. "+this.debugInfo(name));if(null!=name&&(name=getValue(name)),isObject(name))for(attName in name)hasProp.call(name,attName)&&(attValue=name[attName],this.attribute(attName,attValue));else isFunction(value)&&(value=value.apply()),this.options.skipNullAttributes&&null==value||(this.currentNode.attributes[name]=new XMLAttribute(this,name,value));return this},XMLDocumentCB.prototype.text=function(value){var node;return this.openCurrent(),node=new XMLText(this,value),this.onData(this.writer.text(node,this.currentLevel+1),this.currentLevel+1),this},XMLDocumentCB.prototype.cdata=function(value){var node;return this.openCurrent(),node=new XMLCData(this,value),this.onData(this.writer.cdata(node,this.currentLevel+1),this.currentLevel+1),this},XMLDocumentCB.prototype.comment=function(value){var node;return this.openCurrent(),node=new XMLComment(this,value),this.onData(this.writer.comment(node,this.currentLevel+1),this.currentLevel+1),this},XMLDocumentCB.prototype.raw=function(value){var node;return this.openCurrent(),node=new XMLRaw(this,value),this.onData(this.writer.raw(node,this.currentLevel+1),this.currentLevel+1),this},XMLDocumentCB.prototype.instruction=function(target,value){var i,insTarget,insValue,len,node;if(this.openCurrent(),null!=target&&(target=getValue(target)),null!=value&&(value=getValue(value)),Array.isArray(target))for(i=0,len=target.length;len>i;i++)insTarget=target[i],this.instruction(insTarget);else if(isObject(target))for(insTarget in target)hasProp.call(target,insTarget)&&(insValue=target[insTarget],this.instruction(insTarget,insValue));else isFunction(value)&&(value=value.apply()),node=new XMLProcessingInstruction(this,target,value),this.onData(this.writer.processingInstruction(node,this.currentLevel+1),this.currentLevel+1);return this},XMLDocumentCB.prototype.declaration=function(version,encoding,standalone){var node;if(this.openCurrent(),this.documentStarted)throw new Error("declaration() must be the first node.");return node=new XMLDeclaration(this,version,encoding,standalone),this.onData(this.writer.declaration(node,this.currentLevel+1),this.currentLevel+1),this},XMLDocumentCB.prototype.doctype=function(root,pubID,sysID){if(this.openCurrent(),null==root)throw new Error("Missing root node name.");if(this.root)throw new Error("dtd() must come before the root node.");return this.currentNode=new XMLDocType(this,pubID,sysID),this.currentNode.rootNodeName=root,this.currentNode.children=!1,this.currentLevel++,this.openTags[this.currentLevel]=this.currentNode,this},XMLDocumentCB.prototype.dtdElement=function(name,value){var node;return this.openCurrent(),node=new XMLDTDElement(this,name,value),this.onData(this.writer.dtdElement(node,this.currentLevel+1),this.currentLevel+1),this},XMLDocumentCB.prototype.attList=function(elementName,attributeName,attributeType,defaultValueType,defaultValue){var node;return this.openCurrent(),node=new XMLDTDAttList(this,elementName,attributeName,attributeType,defaultValueType,defaultValue),this.onData(this.writer.dtdAttList(node,this.currentLevel+1),this.currentLevel+1),this},XMLDocumentCB.prototype.entity=function(name,value){var node;return this.openCurrent(),node=new XMLDTDEntity(this,!1,name,value),this.onData(this.writer.dtdEntity(node,this.currentLevel+1),this.currentLevel+1),this},XMLDocumentCB.prototype.pEntity=function(name,value){var node;return this.openCurrent(),node=new XMLDTDEntity(this,!0,name,value),this.onData(this.writer.dtdEntity(node,this.currentLevel+1),this.currentLevel+1),this},XMLDocumentCB.prototype.notation=function(name,value){var node;return this.openCurrent(),node=new XMLDTDNotation(this,name,value),this.onData(this.writer.dtdNotation(node,this.currentLevel+1),this.currentLevel+1),this},XMLDocumentCB.prototype.up=function(){if(this.currentLevel<0)throw new Error("The document node has no parent.");return this.currentNode?(this.currentNode.children?this.closeNode(this.currentNode):this.openNode(this.currentNode),this.currentNode=null):this.closeNode(this.openTags[this.currentLevel]),delete this.openTags[this.currentLevel],this.currentLevel--,this},XMLDocumentCB.prototype.end=function(){for(;this.currentLevel>=0;)this.up();return this.onEnd()},XMLDocumentCB.prototype.openCurrent=function(){return this.currentNode?(this.currentNode.children=!0,this.openNode(this.currentNode)):void 0},XMLDocumentCB.prototype.openNode=function(node){return node.isOpen?void 0:(!this.root&&0===this.currentLevel&&node instanceof XMLElement&&(this.root=node),this.onData(this.writer.openNode(node,this.currentLevel),this.currentLevel),node.isOpen=!0)},XMLDocumentCB.prototype.closeNode=function(node){return node.isClosed?void 0:(this.onData(this.writer.closeNode(node,this.currentLevel),this.currentLevel),node.isClosed=!0)},XMLDocumentCB.prototype.onData=function(chunk,level){return this.documentStarted=!0,this.onDataCallback(chunk,level+1)},XMLDocumentCB.prototype.onEnd=function(){return this.documentCompleted=!0,this.onEndCallback()},XMLDocumentCB.prototype.debugInfo=function(name){return null==name?"":"node: <"+name+">"},XMLDocumentCB.prototype.ele=function(){return this.element.apply(this,arguments)},XMLDocumentCB.prototype.nod=function(name,attributes,text){return this.node(name,attributes,text)},XMLDocumentCB.prototype.txt=function(value){return this.text(value)},XMLDocumentCB.prototype.dat=function(value){return this.cdata(value)},XMLDocumentCB.prototype.com=function(value){return this.comment(value)},XMLDocumentCB.prototype.ins=function(target,value){return this.instruction(target,value)},XMLDocumentCB.prototype.dec=function(version,encoding,standalone){return this.declaration(version,encoding,standalone)},XMLDocumentCB.prototype.dtd=function(root,pubID,sysID){return this.doctype(root,pubID,sysID)},XMLDocumentCB.prototype.e=function(name,attributes,text){return this.element(name,attributes,text)},XMLDocumentCB.prototype.n=function(name,attributes,text){return this.node(name,attributes,text)},XMLDocumentCB.prototype.t=function(value){return this.text(value)},XMLDocumentCB.prototype.d=function(value){return this.cdata(value)},XMLDocumentCB.prototype.c=function(value){return this.comment(value)},XMLDocumentCB.prototype.r=function(value){return this.raw(value)},XMLDocumentCB.prototype.i=function(target,value){return this.instruction(target,value)},XMLDocumentCB.prototype.att=function(){return this.currentNode&&this.currentNode instanceof XMLDocType?this.attList.apply(this,arguments):this.attribute.apply(this,arguments)},XMLDocumentCB.prototype.a=function(){return this.currentNode&&this.currentNode instanceof XMLDocType?this.attList.apply(this,arguments):this.attribute.apply(this,arguments)},XMLDocumentCB.prototype.ent=function(name,value){return this.entity(name,value)},XMLDocumentCB.prototype.pent=function(name,value){return this.pEntity(name,value)},XMLDocumentCB.prototype.not=function(name,value){return this.notation(name,value)},XMLDocumentCB}()}).call(this)},{"./Utility":68,"./XMLAttribute":69,"./XMLCData":70,"./XMLComment":71,"./XMLDTDAttList":72,"./XMLDTDElement":73,"./XMLDTDEntity":74,"./XMLDTDNotation":75,"./XMLDeclaration":76,"./XMLDocType":77,"./XMLElement":80,"./XMLProcessingInstruction":82,"./XMLRaw":83,"./XMLStringWriter":85,"./XMLStringifier":86,"./XMLText":87}],80:[function(require,module,exports){(function(){var XMLAttribute,XMLElement,XMLNode,getValue,isFunction,isObject,ref,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;ref=require("./Utility"),isObject=ref.isObject,isFunction=ref.isFunction,getValue=ref.getValue,XMLNode=require("./XMLNode"),XMLAttribute=require("./XMLAttribute"),module.exports=XMLElement=function(superClass){function XMLElement(parent,name,attributes){if(XMLElement.__super__.constructor.call(this,parent),null==name)throw new Error("Missing element name. "+this.debugInfo());this.name=this.stringify.eleName(name),this.attributes={},null!=attributes&&this.attribute(attributes),parent.isDocument&&(this.isRoot=!0,this.documentObject=parent,parent.rootObject=this)}return extend(XMLElement,superClass),XMLElement.prototype.clone=function(){var att,attName,clonedSelf,ref1;clonedSelf=Object.create(this),clonedSelf.isRoot&&(clonedSelf.documentObject=null),clonedSelf.attributes={},ref1=this.attributes;for(attName in ref1)hasProp.call(ref1,attName)&&(att=ref1[attName],clonedSelf.attributes[attName]=att.clone());return clonedSelf.children=[],this.children.forEach(function(child){var clonedChild;return clonedChild=child.clone(),clonedChild.parent=clonedSelf,clonedSelf.children.push(clonedChild)}),clonedSelf},XMLElement.prototype.attribute=function(name,value){var attName,attValue;if(null!=name&&(name=getValue(name)),isObject(name))for(attName in name)hasProp.call(name,attName)&&(attValue=name[attName],this.attribute(attName,attValue));else isFunction(value)&&(value=value.apply()),this.options.skipNullAttributes&&null==value||(this.attributes[name]=new XMLAttribute(this,name,value));return this},XMLElement.prototype.removeAttribute=function(name){var attName,i,len;if(null==name)throw new Error("Missing attribute name. "+this.debugInfo());if(name=getValue(name),Array.isArray(name))for(i=0,len=name.length;len>i;i++)attName=name[i],delete this.attributes[attName];else delete this.attributes[name];return this},XMLElement.prototype.toString=function(options){return this.options.writer.set(options).element(this)},XMLElement.prototype.att=function(name,value){return this.attribute(name,value)},XMLElement.prototype.a=function(name,value){return this.attribute(name,value)},XMLElement}(XMLNode)}).call(this)},{"./Utility":68,"./XMLAttribute":69,"./XMLNode":81}],81:[function(require,module,exports){(function(){var XMLCData,XMLComment,XMLDeclaration,XMLDocType,XMLElement,XMLNode,XMLProcessingInstruction,XMLRaw,XMLText,getValue,isEmpty,isFunction,isObject,ref,hasProp={}.hasOwnProperty;ref=require("./Utility"),isObject=ref.isObject,isFunction=ref.isFunction,isEmpty=ref.isEmpty,getValue=ref.getValue,XMLElement=null,XMLCData=null,XMLComment=null,XMLDeclaration=null,XMLDocType=null,XMLRaw=null,XMLText=null,XMLProcessingInstruction=null,module.exports=XMLNode=function(){function XMLNode(parent){this.parent=parent,this.parent&&(this.options=this.parent.options,this.stringify=this.parent.stringify),this.children=[],XMLElement||(XMLElement=require("./XMLElement"),XMLCData=require("./XMLCData"),XMLComment=require("./XMLComment"),XMLDeclaration=require("./XMLDeclaration"),XMLDocType=require("./XMLDocType"),XMLRaw=require("./XMLRaw"),XMLText=require("./XMLText"),XMLProcessingInstruction=require("./XMLProcessingInstruction"))}return XMLNode.prototype.element=function(name,attributes,text){var childNode,item,j,k,key,lastChild,len,len1,ref1,val;if(lastChild=null,null==attributes&&(attributes={}),attributes=getValue(attributes),isObject(attributes)||(ref1=[attributes,text],text=ref1[0],attributes=ref1[1]),null!=name&&(name=getValue(name)),Array.isArray(name))for(j=0,len=name.length;len>j;j++)item=name[j],lastChild=this.element(item);else if(isFunction(name))lastChild=this.element(name.apply());else if(isObject(name)){for(key in name)if(hasProp.call(name,key))if(val=name[key],isFunction(val)&&(val=val.apply()),isObject(val)&&isEmpty(val)&&(val=null),!this.options.ignoreDecorators&&this.stringify.convertAttKey&&0===key.indexOf(this.stringify.convertAttKey))lastChild=this.attribute(key.substr(this.stringify.convertAttKey.length),val);else if(!this.options.separateArrayItems&&Array.isArray(val))for(k=0,len1=val.length;len1>k;k++)item=val[k],childNode={},childNode[key]=item,lastChild=this.element(childNode);else isObject(val)?(lastChild=this.element(key),lastChild.element(val)):lastChild=this.element(key,val)}else lastChild=!this.options.ignoreDecorators&&this.stringify.convertTextKey&&0===name.indexOf(this.stringify.convertTextKey)?this.text(text):!this.options.ignoreDecorators&&this.stringify.convertCDataKey&&0===name.indexOf(this.stringify.convertCDataKey)?this.cdata(text):!this.options.ignoreDecorators&&this.stringify.convertCommentKey&&0===name.indexOf(this.stringify.convertCommentKey)?this.comment(text):!this.options.ignoreDecorators&&this.stringify.convertRawKey&&0===name.indexOf(this.stringify.convertRawKey)?this.raw(text):!this.options.ignoreDecorators&&this.stringify.convertPIKey&&0===name.indexOf(this.stringify.convertPIKey)?this.instruction(name.substr(this.stringify.convertPIKey.length),text):this.node(name,attributes,text);if(null==lastChild)throw new Error("Could not create any elements with: "+name+". "+this.debugInfo());return lastChild},XMLNode.prototype.insertBefore=function(name,attributes,text){var child,i,removed;if(this.isRoot)throw new Error("Cannot insert elements at root level. "+this.debugInfo(name));return i=this.parent.children.indexOf(this),removed=this.parent.children.splice(i),child=this.parent.element(name,attributes,text),Array.prototype.push.apply(this.parent.children,removed),child},XMLNode.prototype.insertAfter=function(name,attributes,text){var child,i,removed;if(this.isRoot)throw new Error("Cannot insert elements at root level. "+this.debugInfo(name));return i=this.parent.children.indexOf(this),removed=this.parent.children.splice(i+1),child=this.parent.element(name,attributes,text),Array.prototype.push.apply(this.parent.children,removed),child},XMLNode.prototype.remove=function(){var i,ref1;if(this.isRoot)throw new Error("Cannot remove the root element. "+this.debugInfo());return i=this.parent.children.indexOf(this),[].splice.apply(this.parent.children,[i,i-i+1].concat(ref1=[])),ref1,this.parent},XMLNode.prototype.node=function(name,attributes,text){var child,ref1;return null!=name&&(name=getValue(name)),attributes||(attributes={}),attributes=getValue(attributes),isObject(attributes)||(ref1=[attributes,text],text=ref1[0],attributes=ref1[1]),child=new XMLElement(this,name,attributes),null!=text&&child.text(text),this.children.push(child),child},XMLNode.prototype.text=function(value){var child;return child=new XMLText(this,value),this.children.push(child),this},XMLNode.prototype.cdata=function(value){var child;return child=new XMLCData(this,value),this.children.push(child),this},XMLNode.prototype.comment=function(value){var child;return child=new XMLComment(this,value),this.children.push(child),this},XMLNode.prototype.commentBefore=function(value){var child,i,removed;return i=this.parent.children.indexOf(this),removed=this.parent.children.splice(i),child=this.parent.comment(value),Array.prototype.push.apply(this.parent.children,removed),this},XMLNode.prototype.commentAfter=function(value){var child,i,removed;return i=this.parent.children.indexOf(this),removed=this.parent.children.splice(i+1),child=this.parent.comment(value),Array.prototype.push.apply(this.parent.children,removed),this},XMLNode.prototype.raw=function(value){var child;return child=new XMLRaw(this,value),this.children.push(child),this},XMLNode.prototype.instruction=function(target,value){var insTarget,insValue,instruction,j,len;if(null!=target&&(target=getValue(target)),null!=value&&(value=getValue(value)),Array.isArray(target))for(j=0,len=target.length;len>j;j++)insTarget=target[j],this.instruction(insTarget);else if(isObject(target))for(insTarget in target)hasProp.call(target,insTarget)&&(insValue=target[insTarget],this.instruction(insTarget,insValue));else isFunction(value)&&(value=value.apply()),instruction=new XMLProcessingInstruction(this,target,value),this.children.push(instruction);return this},XMLNode.prototype.instructionBefore=function(target,value){var child,i,removed;return i=this.parent.children.indexOf(this),removed=this.parent.children.splice(i),child=this.parent.instruction(target,value),Array.prototype.push.apply(this.parent.children,removed),this},XMLNode.prototype.instructionAfter=function(target,value){var child,i,removed;return i=this.parent.children.indexOf(this),removed=this.parent.children.splice(i+1),child=this.parent.instruction(target,value),Array.prototype.push.apply(this.parent.children,removed),this},XMLNode.prototype.declaration=function(version,encoding,standalone){var doc,xmldec;return doc=this.document(),xmldec=new XMLDeclaration(doc,version,encoding,standalone),doc.children[0]instanceof XMLDeclaration?doc.children[0]=xmldec:doc.children.unshift(xmldec),doc.root()||doc},XMLNode.prototype.doctype=function(pubID,sysID){var child,doc,doctype,i,j,k,len,len1,ref1,ref2;for(doc=this.document(),doctype=new XMLDocType(doc,pubID,sysID),ref1=doc.children,i=j=0,len=ref1.length;len>j;i=++j)if(child=ref1[i],child instanceof XMLDocType)return doc.children[i]=doctype,doctype;for(ref2=doc.children,i=k=0,len1=ref2.length;len1>k;i=++k)if(child=ref2[i],child.isRoot)return doc.children.splice(i,0,doctype),doctype;return doc.children.push(doctype),doctype},XMLNode.prototype.up=function(){if(this.isRoot)throw new Error("The root node has no parent. Use doc() if you need to get the document object.");return this.parent},XMLNode.prototype.root=function(){var node;for(node=this;node;){if(node.isDocument)return node.rootObject;if(node.isRoot)return node;node=node.parent}},XMLNode.prototype.document=function(){var node;for(node=this;node;){if(node.isDocument)return node;node=node.parent}},XMLNode.prototype.end=function(options){return this.document().end(options)},XMLNode.prototype.prev=function(){var i;if(i=this.parent.children.indexOf(this),1>i)throw new Error("Already at the first node. "+this.debugInfo());return this.parent.children[i-1]},XMLNode.prototype.next=function(){var i;if(i=this.parent.children.indexOf(this),-1===i||i===this.parent.children.length-1)throw new Error("Already at the last node. "+this.debugInfo());return this.parent.children[i+1]},XMLNode.prototype.importDocument=function(doc){var clonedRoot;return clonedRoot=doc.root().clone(),clonedRoot.parent=this,clonedRoot.isRoot=!1,this.children.push(clonedRoot),this},XMLNode.prototype.debugInfo=function(name){var ref1,ref2;return name=name||this.name,null!=name||(null!=(ref1=this.parent)?ref1.name:void 0)?null==name?"parent: <"+this.parent.name+">":(null!=(ref2=this.parent)?ref2.name:void 0)?"node: <"+name+">, parent: <"+this.parent.name+">":"node: <"+name+">":""},XMLNode.prototype.ele=function(name,attributes,text){return this.element(name,attributes,text)},XMLNode.prototype.nod=function(name,attributes,text){return this.node(name,attributes,text)},XMLNode.prototype.txt=function(value){return this.text(value)},XMLNode.prototype.dat=function(value){return this.cdata(value)},XMLNode.prototype.com=function(value){return this.comment(value)},XMLNode.prototype.ins=function(target,value){return this.instruction(target,value)},XMLNode.prototype.doc=function(){return this.document()},XMLNode.prototype.dec=function(version,encoding,standalone){return this.declaration(version,encoding,standalone)},XMLNode.prototype.dtd=function(pubID,sysID){return this.doctype(pubID,sysID)},XMLNode.prototype.e=function(name,attributes,text){return this.element(name,attributes,text)},XMLNode.prototype.n=function(name,attributes,text){return this.node(name,attributes,text)},XMLNode.prototype.t=function(value){return this.text(value)},XMLNode.prototype.d=function(value){return this.cdata(value)},XMLNode.prototype.c=function(value){return this.comment(value)},XMLNode.prototype.r=function(value){return this.raw(value)},XMLNode.prototype.i=function(target,value){return this.instruction(target,value)},XMLNode.prototype.u=function(){return this.up()},XMLNode.prototype.importXMLBuilder=function(doc){return this.importDocument(doc)},XMLNode}()}).call(this)},{"./Utility":68,"./XMLCData":70,"./XMLComment":71,"./XMLDeclaration":76,"./XMLDocType":77,"./XMLElement":80,"./XMLProcessingInstruction":82,"./XMLRaw":83,"./XMLText":87}],82:[function(require,module,exports){(function(){var XMLNode,XMLProcessingInstruction,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;XMLNode=require("./XMLNode"),module.exports=XMLProcessingInstruction=function(superClass){function XMLProcessingInstruction(parent,target,value){if(XMLProcessingInstruction.__super__.constructor.call(this,parent),null==target)throw new Error("Missing instruction target. "+this.debugInfo());this.target=this.stringify.insTarget(target),value&&(this.value=this.stringify.insValue(value))}return extend(XMLProcessingInstruction,superClass),XMLProcessingInstruction.prototype.clone=function(){return Object.create(this)},XMLProcessingInstruction.prototype.toString=function(options){return this.options.writer.set(options).processingInstruction(this)},XMLProcessingInstruction}(XMLNode)}).call(this)},{"./XMLNode":81}],83:[function(require,module,exports){(function(){var XMLNode,XMLRaw,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;XMLNode=require("./XMLNode"),module.exports=XMLRaw=function(superClass){function XMLRaw(parent,text){if(XMLRaw.__super__.constructor.call(this,parent),null==text)throw new Error("Missing raw text. "+this.debugInfo());this.value=this.stringify.raw(text)}return extend(XMLRaw,superClass),XMLRaw.prototype.clone=function(){return Object.create(this)},XMLRaw.prototype.toString=function(options){return this.options.writer.set(options).raw(this)},XMLRaw}(XMLNode)}).call(this)},{"./XMLNode":81}],84:[function(require,module,exports){(function(){var XMLCData,XMLComment,XMLDTDAttList,XMLDTDElement,XMLDTDEntity,XMLDTDNotation,XMLDeclaration,XMLDocType,XMLElement,XMLProcessingInstruction,XMLRaw,XMLStreamWriter,XMLText,XMLWriterBase,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;XMLDeclaration=require("./XMLDeclaration"),XMLDocType=require("./XMLDocType"),XMLCData=require("./XMLCData"),XMLComment=require("./XMLComment"),XMLElement=require("./XMLElement"),XMLRaw=require("./XMLRaw"),XMLText=require("./XMLText"),XMLProcessingInstruction=require("./XMLProcessingInstruction"),XMLDTDAttList=require("./XMLDTDAttList"),XMLDTDElement=require("./XMLDTDElement"),XMLDTDEntity=require("./XMLDTDEntity"),XMLDTDNotation=require("./XMLDTDNotation"),XMLWriterBase=require("./XMLWriterBase"),module.exports=XMLStreamWriter=function(superClass){function XMLStreamWriter(stream,options){XMLStreamWriter.__super__.constructor.call(this,options),this.stream=stream}return extend(XMLStreamWriter,superClass),XMLStreamWriter.prototype.document=function(doc){var child,i,j,len,len1,ref,ref1,results;for(ref=doc.children,i=0,len=ref.length;len>i;i++)child=ref[i],child.isLastRootNode=!1;for(doc.children[doc.children.length-1].isLastRootNode=!0,ref1=doc.children,results=[],j=0,len1=ref1.length;len1>j;j++)switch(child=ref1[j],!1){case!(child instanceof XMLDeclaration):results.push(this.declaration(child));break;case!(child instanceof XMLDocType):results.push(this.docType(child));break;case!(child instanceof XMLComment):results.push(this.comment(child));break;case!(child instanceof XMLProcessingInstruction):results.push(this.processingInstruction(child));break;default:results.push(this.element(child))}return results},XMLStreamWriter.prototype.attribute=function(att){return this.stream.write(" "+att.name+'="'+att.value+'"')},XMLStreamWriter.prototype.cdata=function(node,level){return this.stream.write(this.space(level)+""+this.endline(node))},XMLStreamWriter.prototype.comment=function(node,level){return this.stream.write(this.space(level)+""+this.endline(node))},XMLStreamWriter.prototype.declaration=function(node,level){return this.stream.write(this.space(level)),this.stream.write('"),this.stream.write(this.endline(node))},XMLStreamWriter.prototype.docType=function(node,level){var child,i,len,ref;if(level||(level=0),this.stream.write(this.space(level)),this.stream.write("0){for(this.stream.write(" ["),this.stream.write(this.endline(node)),ref=node.children,i=0,len=ref.length;len>i;i++)switch(child=ref[i],!1){case!(child instanceof XMLDTDAttList):this.dtdAttList(child,level+1);break;case!(child instanceof XMLDTDElement):this.dtdElement(child,level+1);break;case!(child instanceof XMLDTDEntity):this.dtdEntity(child,level+1);break;case!(child instanceof XMLDTDNotation):this.dtdNotation(child,level+1);break;case!(child instanceof XMLCData):this.cdata(child,level+1);break;case!(child instanceof XMLComment):this.comment(child,level+1);break;case!(child instanceof XMLProcessingInstruction):this.processingInstruction(child,level+1);break;default:throw new Error("Unknown DTD node type: "+child.constructor.name)}this.stream.write("]")}return this.stream.write(this.spacebeforeslash+">"),this.stream.write(this.endline(node))},XMLStreamWriter.prototype.element=function(node,level){var att,child,i,len,name,ref,ref1,space;level||(level=0),space=this.space(level),this.stream.write(space+"<"+node.name),ref=node.attributes;for(name in ref)hasProp.call(ref,name)&&(att=ref[name], +this.attribute(att));if(0===node.children.length||node.children.every(function(e){return""===e.value}))this.allowEmpty?this.stream.write(">"):this.stream.write(this.spacebeforeslash+"/>");else if(this.pretty&&1===node.children.length&&null!=node.children[0].value)this.stream.write(">"),this.stream.write(node.children[0].value),this.stream.write("");else{for(this.stream.write(">"+this.newline),ref1=node.children,i=0,len=ref1.length;len>i;i++)switch(child=ref1[i],!1){case!(child instanceof XMLCData):this.cdata(child,level+1);break;case!(child instanceof XMLComment):this.comment(child,level+1);break;case!(child instanceof XMLElement):this.element(child,level+1);break;case!(child instanceof XMLRaw):this.raw(child,level+1);break;case!(child instanceof XMLText):this.text(child,level+1);break;case!(child instanceof XMLProcessingInstruction):this.processingInstruction(child,level+1);break;default:throw new Error("Unknown XML node type: "+child.constructor.name)}this.stream.write(space+"")}return this.stream.write(this.endline(node))},XMLStreamWriter.prototype.processingInstruction=function(node,level){return this.stream.write(this.space(level)+""+this.endline(node))},XMLStreamWriter.prototype.raw=function(node,level){return this.stream.write(this.space(level)+node.value+this.endline(node))},XMLStreamWriter.prototype.text=function(node,level){return this.stream.write(this.space(level)+node.value+this.endline(node))},XMLStreamWriter.prototype.dtdAttList=function(node,level){return this.stream.write(this.space(level)+""+this.endline(node))},XMLStreamWriter.prototype.dtdElement=function(node,level){return this.stream.write(this.space(level)+""+this.endline(node))},XMLStreamWriter.prototype.dtdEntity=function(node,level){return this.stream.write(this.space(level)+""+this.endline(node))},XMLStreamWriter.prototype.dtdNotation=function(node,level){return this.stream.write(this.space(level)+""+this.endline(node))},XMLStreamWriter.prototype.endline=function(node){return node.isLastRootNode?"":this.newline},XMLStreamWriter}(XMLWriterBase)}).call(this)},{"./XMLCData":70,"./XMLComment":71,"./XMLDTDAttList":72,"./XMLDTDElement":73,"./XMLDTDEntity":74,"./XMLDTDNotation":75,"./XMLDeclaration":76,"./XMLDocType":77,"./XMLElement":80,"./XMLProcessingInstruction":82,"./XMLRaw":83,"./XMLText":87,"./XMLWriterBase":88}],85:[function(require,module,exports){(function(){var XMLCData,XMLComment,XMLDTDAttList,XMLDTDElement,XMLDTDEntity,XMLDTDNotation,XMLDeclaration,XMLDocType,XMLElement,XMLProcessingInstruction,XMLRaw,XMLStringWriter,XMLText,XMLWriterBase,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;XMLDeclaration=require("./XMLDeclaration"),XMLDocType=require("./XMLDocType"),XMLCData=require("./XMLCData"),XMLComment=require("./XMLComment"),XMLElement=require("./XMLElement"),XMLRaw=require("./XMLRaw"),XMLText=require("./XMLText"),XMLProcessingInstruction=require("./XMLProcessingInstruction"),XMLDTDAttList=require("./XMLDTDAttList"),XMLDTDElement=require("./XMLDTDElement"),XMLDTDEntity=require("./XMLDTDEntity"),XMLDTDNotation=require("./XMLDTDNotation"),XMLWriterBase=require("./XMLWriterBase"),module.exports=XMLStringWriter=function(superClass){function XMLStringWriter(options){XMLStringWriter.__super__.constructor.call(this,options)}return extend(XMLStringWriter,superClass),XMLStringWriter.prototype.document=function(doc){var child,i,len,r,ref;for(this.textispresent=!1,r="",ref=doc.children,i=0,len=ref.length;len>i;i++)child=ref[i],r+=function(){switch(!1){case!(child instanceof XMLDeclaration):return this.declaration(child);case!(child instanceof XMLDocType):return this.docType(child);case!(child instanceof XMLComment):return this.comment(child);case!(child instanceof XMLProcessingInstruction):return this.processingInstruction(child);default:return this.element(child,0)}}.call(this);return this.pretty&&r.slice(-this.newline.length)===this.newline&&(r=r.slice(0,-this.newline.length)),r},XMLStringWriter.prototype.attribute=function(att){return" "+att.name+'="'+att.value+'"'},XMLStringWriter.prototype.cdata=function(node,level){return this.space(level)+""+this.newline},XMLStringWriter.prototype.comment=function(node,level){return this.space(level)+""+this.newline},XMLStringWriter.prototype.declaration=function(node,level){var r;return r=this.space(level),r+='",r+=this.newline},XMLStringWriter.prototype.docType=function(node,level){var child,i,len,r,ref;if(level||(level=0),r=this.space(level),r+="0){for(r+=" [",r+=this.newline,ref=node.children,i=0,len=ref.length;len>i;i++)child=ref[i],r+=function(){switch(!1){case!(child instanceof XMLDTDAttList):return this.dtdAttList(child,level+1);case!(child instanceof XMLDTDElement):return this.dtdElement(child,level+1);case!(child instanceof XMLDTDEntity):return this.dtdEntity(child,level+1);case!(child instanceof XMLDTDNotation):return this.dtdNotation(child,level+1);case!(child instanceof XMLCData):return this.cdata(child,level+1);case!(child instanceof XMLComment):return this.comment(child,level+1);case!(child instanceof XMLProcessingInstruction):return this.processingInstruction(child,level+1);default:throw new Error("Unknown DTD node type: "+child.constructor.name)}}.call(this);r+="]"}return r+=this.spacebeforeslash+">",r+=this.newline},XMLStringWriter.prototype.element=function(node,level){var att,child,i,j,len,len1,name,r,ref,ref1,ref2,space,textispresentwasset;level||(level=0),textispresentwasset=!1,this.textispresent?(this.newline="",this.pretty=!1):(this.newline=this.newlinedefault,this.pretty=this.prettydefault),space=this.space(level),r="",r+=space+"<"+node.name,ref=node.attributes;for(name in ref)hasProp.call(ref,name)&&(att=ref[name],r+=this.attribute(att));if(0===node.children.length||node.children.every(function(e){return""===e.value}))r+=this.allowEmpty?">"+this.newline:this.spacebeforeslash+"/>"+this.newline;else if(this.pretty&&1===node.children.length&&null!=node.children[0].value)r+=">",r+=node.children[0].value,r+=""+this.newline;else{if(this.dontprettytextnodes)for(ref1=node.children,i=0,len=ref1.length;len>i;i++)if(child=ref1[i],null!=child.value){this.textispresent++,textispresentwasset=!0;break}for(this.textispresent&&(this.newline="",this.pretty=!1,space=this.space(level)),r+=">"+this.newline,ref2=node.children,j=0,len1=ref2.length;len1>j;j++)child=ref2[j],r+=function(){switch(!1){case!(child instanceof XMLCData):return this.cdata(child,level+1);case!(child instanceof XMLComment):return this.comment(child,level+1);case!(child instanceof XMLElement):return this.element(child,level+1);case!(child instanceof XMLRaw):return this.raw(child,level+1);case!(child instanceof XMLText):return this.text(child,level+1);case!(child instanceof XMLProcessingInstruction):return this.processingInstruction(child,level+1);default:throw new Error("Unknown XML node type: "+child.constructor.name)}}.call(this);textispresentwasset&&this.textispresent--,this.textispresent||(this.newline=this.newlinedefault,this.pretty=this.prettydefault),r+=space+""+this.newline}return r},XMLStringWriter.prototype.processingInstruction=function(node,level){var r;return r=this.space(level)+""+this.newline},XMLStringWriter.prototype.raw=function(node,level){return this.space(level)+node.value+this.newline},XMLStringWriter.prototype.text=function(node,level){return this.space(level)+node.value+this.newline},XMLStringWriter.prototype.dtdAttList=function(node,level){var r;return r=this.space(level)+""+this.newline},XMLStringWriter.prototype.dtdElement=function(node,level){return this.space(level)+""+this.newline},XMLStringWriter.prototype.dtdEntity=function(node,level){var r;return r=this.space(level)+""+this.newline},XMLStringWriter.prototype.dtdNotation=function(node,level){var r;return r=this.space(level)+""+this.newline},XMLStringWriter.prototype.openNode=function(node,level){var att,name,r,ref;if(level||(level=0),node instanceof XMLElement){r=this.space(level)+"<"+node.name,ref=node.attributes;for(name in ref)hasProp.call(ref,name)&&(att=ref[name],r+=this.attribute(att));return r+=(node.children?">":"/>")+this.newline}return r=this.space(level)+"")+this.newline},XMLStringWriter.prototype.closeNode=function(node,level){switch(level||(level=0),!1){case!(node instanceof XMLElement):return this.space(level)+""+this.newline;case!(node instanceof XMLDocType):return this.space(level)+"]>"+this.newline}},XMLStringWriter}(XMLWriterBase)}).call(this)},{"./XMLCData":70,"./XMLComment":71,"./XMLDTDAttList":72,"./XMLDTDElement":73,"./XMLDTDEntity":74,"./XMLDTDNotation":75,"./XMLDeclaration":76,"./XMLDocType":77,"./XMLElement":80,"./XMLProcessingInstruction":82,"./XMLRaw":83,"./XMLText":87,"./XMLWriterBase":88}],86:[function(require,module,exports){(function(){var XMLStringifier,bind=function(fn,me){return function(){return fn.apply(me,arguments)}},hasProp={}.hasOwnProperty;module.exports=XMLStringifier=function(){function XMLStringifier(options){this.assertLegalChar=bind(this.assertLegalChar,this);var key,ref,value;options||(options={}),this.noDoubleEncoding=options.noDoubleEncoding,ref=options.stringify||{};for(key in ref)hasProp.call(ref,key)&&(value=ref[key],this[key]=value)}return XMLStringifier.prototype.eleName=function(val){return val=""+val||"",this.assertLegalChar(val)},XMLStringifier.prototype.eleText=function(val){return val=""+val||"",this.assertLegalChar(this.elEscape(val))},XMLStringifier.prototype.cdata=function(val){return val=""+val||"",val=val.replace("]]>","]]]]>"),this.assertLegalChar(val)},XMLStringifier.prototype.comment=function(val){if(val=""+val||"",val.match(/--/))throw new Error("Comment text cannot contain double-hypen: "+val);return this.assertLegalChar(val)},XMLStringifier.prototype.raw=function(val){return""+val||""},XMLStringifier.prototype.attName=function(val){return val=""+val||""},XMLStringifier.prototype.attValue=function(val){return val=""+val||"",this.attEscape(val)},XMLStringifier.prototype.insTarget=function(val){return""+val||""},XMLStringifier.prototype.insValue=function(val){if(val=""+val||"",val.match(/\?>/))throw new Error("Invalid processing instruction value: "+val);return val},XMLStringifier.prototype.xmlVersion=function(val){if(val=""+val||"",!val.match(/1\.[0-9]+/))throw new Error("Invalid version number: "+val);return val},XMLStringifier.prototype.xmlEncoding=function(val){if(val=""+val||"",!val.match(/^[A-Za-z](?:[A-Za-z0-9._-])*$/))throw new Error("Invalid encoding: "+val);return val},XMLStringifier.prototype.xmlStandalone=function(val){return val?"yes":"no"},XMLStringifier.prototype.dtdPubID=function(val){return""+val||""},XMLStringifier.prototype.dtdSysID=function(val){return""+val||""},XMLStringifier.prototype.dtdElementValue=function(val){return""+val||""},XMLStringifier.prototype.dtdAttType=function(val){return""+val||""},XMLStringifier.prototype.dtdAttDefault=function(val){return null!=val?""+val||"":val},XMLStringifier.prototype.dtdEntityValue=function(val){return""+val||""},XMLStringifier.prototype.dtdNData=function(val){return""+val||""},XMLStringifier.prototype.convertAttKey="@",XMLStringifier.prototype.convertPIKey="?",XMLStringifier.prototype.convertTextKey="#text",XMLStringifier.prototype.convertCDataKey="#cdata",XMLStringifier.prototype.convertCommentKey="#comment",XMLStringifier.prototype.convertRawKey="#raw",XMLStringifier.prototype.assertLegalChar=function(str){var res;if(res=str.match(/[\0\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/))throw new Error("Invalid character in string: "+str+" at index "+res.index);return str},XMLStringifier.prototype.elEscape=function(str){var ampregex;return ampregex=this.noDoubleEncoding?/(?!&\S+;)&/g:/&/g,str.replace(ampregex,"&").replace(//g,">").replace(/\r/g," ")},XMLStringifier.prototype.attEscape=function(str){var ampregex;return ampregex=this.noDoubleEncoding?/(?!&\S+;)&/g:/&/g,str.replace(ampregex,"&").replace(/0?new Array(indent).join(this.indent):""):""},XMLWriterBase}()}).call(this)},{}],89:[function(require,module,exports){(function(){var XMLDocument,XMLDocumentCB,XMLStreamWriter,XMLStringWriter,assign,isFunction,ref;ref=require("./Utility"),assign=ref.assign,isFunction=ref.isFunction,XMLDocument=require("./XMLDocument"),XMLDocumentCB=require("./XMLDocumentCB"),XMLStringWriter=require("./XMLStringWriter"),XMLStreamWriter=require("./XMLStreamWriter"),module.exports.create=function(name,xmldec,doctype,options){var doc,root;if(null==name)throw new Error("Root element needs a name.");return options=assign({},xmldec,doctype,options),doc=new XMLDocument(options),root=doc.element(name),options.headless||(doc.declaration(options),(null!=options.pubID||null!=options.sysID)&&doc.doctype(options)),root},module.exports.begin=function(options,onData,onEnd){var ref1;return isFunction(options)&&(ref1=[options,onData],onData=ref1[0],onEnd=ref1[1],options={}),onData?new XMLDocumentCB(options,onData,onEnd):new XMLDocument(options)},module.exports.stringWriter=function(options){return new XMLStringWriter(options)},module.exports.streamWriter=function(stream,options){return new XMLStreamWriter(stream,options)}}).call(this)},{"./Utility":68,"./XMLDocument":78,"./XMLDocumentCB":79,"./XMLStreamWriter":84,"./XMLStringWriter":85}]},{},[21])(21)}); diff --git a/dsh-reader/client.js b/dsh-reader/client.js index 72bb43b..3c72356 100644 --- a/dsh-reader/client.js +++ b/dsh-reader/client.js @@ -44,13 +44,22 @@ function extOf(name) { return m ? '.' + m[1].toLowerCase() : '' } +/** + * Normalize a workspace-relative path to POSIX separators. Windows hosts can + * hand over `sub\\book.md`; every client-side path consumer expects `/`. + * @param {string} value + */ +function normalizeRelPath(value) { + return String(value || '').replace(/\\/g, '/') +} + function basename(file) { - const parts = String(file || '').split('/') + const parts = normalizeRelPath(file).split('/') return parts[parts.length - 1] || file } function dirname(file) { - const parts = String(file || '').split('/') + const parts = normalizeRelPath(file).split('/') parts.pop() return parts.join('/') || '.' } @@ -59,7 +68,7 @@ function normalizeTerm(value) { return String(value || '').trim().toLowerCase() } -const READABLE = new Set(['.md', '.markdown', '.txt', '.epub', '.pdf']) +const READABLE = new Set(['.md', '.markdown', '.txt', '.epub', '.pdf', '.docx']) function debounce(fn, wait) { let timer = null @@ -69,6 +78,21 @@ function debounce(fn, wait) { } } +/** + * Modifier key shown in help text for the current platform. + * @returns {string} `⌘` on Apple platforms, `Ctrl` elsewhere + */ +function modifierLabel() { + const platform = + (typeof navigator !== 'undefined' && (navigator.userAgentData?.platform || navigator.platform)) || '' + return /Mac|iPhone|iPad|iPod/i.test(platform) ? '⌘' : 'Ctrl' +} + +/** Undo/redo hint that matches the platform modifier. */ +function undoLabel() { + return modifierLabel() === '⌘' ? '⌘Z / ⌘⇧Z' : 'Ctrl+Z / Ctrl+Shift+Z' +} + const REDUCE_QUERY = '(prefers-reduced-motion: reduce)' const RING_CLASS = 'rd-jump-ring' @@ -614,6 +638,11 @@ function buildAssetQuoteSuffix(assets, t) { const ZH = { + 'error.fileNotFound': '文件不存在', + 'error.permissionDenied': '没有权限读取该文件', + 'error.fileBusy': '文件被其他程序占用,请关闭后重试', + 'label.copied': '已复制', + 'label.copyFailed': '复制失败,请手动选择文本', 'view.label': '阅读', 'library.title': '书库', 'library.empty': '这个目录里还没有可读的文档', @@ -899,6 +928,11 @@ const ZH = { } const EN = { + 'error.fileNotFound': 'File not found', + 'error.permissionDenied': 'Permission denied', + 'error.fileBusy': 'The file is in use. Close it and try again.', + 'label.copied': 'Copied', + 'label.copyFailed': 'Copy failed; select the text manually', 'view.label': 'Reader', 'library.title': 'Library', 'library.empty': 'No readable documents in this folder', @@ -1222,6 +1256,17 @@ const EXPLAIN_TIMEOUT_MS = 100_000 const timeoutText = () => (typeof t === 'function' ? t('label.timeout') : 'request timed out') +const FILE_ERROR_KEYS = { + 'file not found': 'error.fileNotFound', + 'permission denied': 'error.permissionDenied', + 'file busy': 'error.fileBusy', +} + +function fileErrorText(code, status) { + const key = code && FILE_ERROR_KEYS[code] + return key && typeof t === 'function' ? t(key) : 'HTTP ' + status +} + /** * Fetch JSON from the plugin host. * @@ -1261,7 +1306,10 @@ const api = { fetchBytes(sessionId, path) { const url = `${BASE}/api/file?sessionId=${encodeURIComponent(sessionId || '')}&path=${encodeURIComponent(path)}` return fetch(url).then(async (res) => { - if (!res.ok) throw new Error('HTTP ' + res.status) + if (!res.ok) { + const data = await res.json().catch(() => null) + throw new Error(fileErrorText(data && data.error, res.status)) + } const bytes = await res.arrayBuffer() return { bytes, fingerprint: res.headers.get('x-doc-fingerprint') || '' } }) @@ -1396,7 +1444,7 @@ const api = { const READER_CSS = ` .rd-root,.rd-root *,.rd-hover-zone *,.rd-note-mask *{box-sizing:border-box} -.rd-root{display:flex;flex-direction:column;height:100%;min-height:0;background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);font-family:ui-sans-serif,system-ui,-apple-system,"PingFang SC","Microsoft YaHei",sans-serif} +.rd-root{display:flex;flex-direction:column;height:100%;min-height:0;background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI","Microsoft YaHei UI","Microsoft YaHei","PingFang SC",sans-serif} .rd-toolbar{display:flex;align-items:center;gap:8px;height:44px;flex:0 0 auto;padding:0 12px;border-bottom:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-base)} .rd-icon-btn{width:30px;min-width:30px;padding:0;display:inline-flex;align-items:center;justify-content:center} .rd-icon-btn svg{display:block;width:18px;height:18px;flex:0 0 auto} @@ -1422,7 +1470,7 @@ const READER_CSS = ` .rd-btn.ghost:hover{background:var(--dsw-alias-bg-layer-1)} .rd-btn:disabled{opacity:.45;cursor:default} .rd-body{display:flex;flex:1;min-height:0} -.rd-main{flex:1;min-width:0;overflow:auto;position:relative;scroll-behavior:smooth;overscroll-behavior:contain} +.rd-main{flex:1;min-width:0;overflow:auto;position:relative;scroll-behavior:smooth;overscroll-behavior:contain;scrollbar-gutter:stable} .rd-page{max-width:760px;margin:0 auto;padding:40px 28px 120px;font-size:var(--rd-fs,18px);line-height:var(--rd-lh,1.85)} .rd-prose>h1{font-size:1.7em;line-height:1.3;margin:1.4em 0 .6em;font-weight:700} .rd-prose>h2{font-size:1.4em;line-height:1.35;margin:1.4em 0 .5em;font-weight:650} @@ -1431,7 +1479,7 @@ const READER_CSS = ` .rd-prose p{margin:.9em 0} .rd-prose blockquote{margin:1em 0;padding:.2em 0 .2em 1em;border-left:3px solid var(--dsw-alias-border-l2);color:var(--dsw-alias-label-secondary)} .rd-prose pre{margin:1em 0;padding:14px 16px;border-radius:10px;background:var(--dsw-alias-bg-layer-2);overflow:auto;font-size:.86em;line-height:1.6} -.rd-prose code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.9em;background:var(--dsw-alias-bg-layer-2);padding:1px 5px;border-radius:5px} +.rd-prose code{font-family:ui-monospace,SFMono-Regular,Menlo,"Cascadia Mono",Consolas,monospace;font-size:.9em;background:var(--dsw-alias-bg-layer-2);padding:1px 5px;border-radius:5px} .rd-prose pre code{background:transparent;padding:0;border-radius:0} .rd-prose ul,.rd-prose ol{margin:.8em 0;padding-left:1.4em} .rd-prose li{margin:.3em 0} @@ -2421,6 +2469,231 @@ async function epubOpen(bytes) { } + +const MAMMOTH_URL = '/dsh-reader-live/assets/mammoth.browser.min.js' + +const IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/svg+xml']) + +let mammothPromise = null + +function localName(element) { + return String((element && (element.localName || element.tagName)) || '') + .toLowerCase() + .split(':') + .pop() +} + +function attr(element, name) { + if (!element) return '' + return element.getAttribute(name) || element.getAttribute(`w:${name}`) || '' +} + +function descendants(root, name) { + return Array.from(root.getElementsByTagName('*')).filter((element) => localName(element) === name) +} + +/** + * Read paragraph styles that carry a heading level, either through a `heading N` + * style name or through `w:outlineLvl` (common in Chinese and WPS templates). + * @param {string} stylesXml contents of word/styles.xml + * @returns {Array<{styleId: string, name: string, level: number}>} + */ +function parseStyleOutline(stylesXml) { + if (!stylesXml || typeof DOMParser === 'undefined') return [] + const parsed = new DOMParser().parseFromString(stylesXml, 'application/xml') + if (parsed.querySelector('parsererror')) return [] + const styles = [] + for (const style of descendants(parsed, 'style')) { + if ((attr(style, 'type') || '').toLowerCase() !== 'paragraph') continue + const styleId = attr(style, 'styleId') + const nameElement = descendants(style, 'name')[0] + const name = attr(nameElement, 'val') + if (!styleId || !name) continue + const pPr = descendants(style, 'pPr')[0] + const outlineElement = pPr ? descendants(pPr, 'outlineLvl')[0] : null + const outline = outlineElement ? Number(attr(outlineElement, 'val')) : NaN + let level = Number.isFinite(outline) && outline >= 0 && outline <= 5 ? outline + 1 : 0 + if (!level) { + const match = /^(?:heading|标题)\s*([1-6])$/i.exec(name.trim()) + if (match) level = Number(match[1]) + } + if (level) styles.push({ styleId, name, level }) + } + return styles +} + +const CODE_STYLE = /^(html preformatted|preformatted text|代码|代码块|源代码)$/i + +/** + * Collect paragraph style names that should render as a code block. + * @param {string} stylesXml contents of word/styles.xml + */ +function parseCodeStyles(stylesXml) { + if (!stylesXml || typeof DOMParser === 'undefined') return [] + const parsed = new DOMParser().parseFromString(stylesXml, 'application/xml') + if (parsed.querySelector('parsererror')) return [] + const names = [] + for (const style of descendants(parsed, 'style')) { + if ((attr(style, 'type') || '').toLowerCase() !== 'paragraph') continue + const name = attr(descendants(style, 'name')[0], 'val') + if (name && CODE_STYLE.test(name.trim())) names.push(name.trim()) + } + return names +} + +/** + * Build mammoth style-map entries for headings and code styles. + * @param {Array<{name: string, level: number}>} styles + * @param {string[]} [codeStyles] + */ +function styleMapFor(styles, codeStyles = []) { + const map = (styles || []).map(({ name, level }) => `p[style-name='${String(name).replace(/'/g, "\\'")}'] => h${level}`) + for (const name of codeStyles) map.push(`p[style-name='${String(name).replace(/'/g, "\\'")}'] => pre`) + return map +} + +function wrapTables(root) { + for (const table of Array.from(root.querySelectorAll('table'))) { + if (table.parentElement && table.parentElement.classList.contains('rd-table-wrap')) continue + const wrap = document.createElement('div') + wrap.className = 'rd-table-wrap' + table.parentNode.insertBefore(wrap, table) + wrap.appendChild(table) + } +} + +function stripTocLeaders(root) { + for (const paragraph of Array.from(root.querySelectorAll('p'))) { + const text = String(paragraph.textContent || '').trim() + if (/^.{0,120}(?:\.{3,}|…{2,}|·{3,})\s*\d+\s*$/.test(text)) paragraph.remove() + } +} + +/** + * Sanitize mammoth output: mammoth does not sanitize, and Word files are + * untrusted input. Keep the semantic tags, drop scripts and unsafe URLs. + * @param {string} html + */ +function sanitizeDocxHtml(html) { + if (typeof document === 'undefined') return String(html || '') + const container = document.createElement('div') + container.innerHTML = String(html || '') + for (const node of Array.from(container.querySelectorAll('script,iframe,object,embed,style,link,meta,base,form'))) { + node.remove() + } + for (const element of Array.from(container.querySelectorAll('*'))) { + for (const attribute of Array.from(element.attributes)) { + if (/^on/i.test(attribute.name)) element.removeAttribute(attribute.name) + if (attribute.name === 'href' && !/^(https?:|mailto:|#)/i.test(attribute.value)) element.removeAttribute('href') + if (attribute.name === 'src' && !/^(https?:|blob:|data:image\/)/i.test(attribute.value)) element.removeAttribute('src') + } + } + return container.innerHTML +} + +/** + * Split mammoth's flat HTML into h1 chapters and build the outline. The split + * rule is frozen once published: annotations store only the chapter index. + * @param {string} html sanitized document HTML + */ +function splitDocxChapters(html) { + if (typeof document === 'undefined') return { chapters: [], outline: [] } + const container = document.createElement('div') + container.innerHTML = String(html || '') + wrapTables(container) + stripTocLeaders(container) + const chapters = [] + const outline = [] + let current = null + const startChapter = (label) => { + current = { label: label || '正文', html: '', text: '' } + chapters.push(current) + } + for (const node of Array.from(container.childNodes)) { + const tag = node.nodeType === 1 ? String(node.tagName || '').toLowerCase() : '' + if (tag === 'h1') startChapter((node.textContent || '').trim() || `第 ${chapters.length + 1} 章`) + else if (!current) startChapter('正文') + if (node.nodeType === 1) { + current.html += node.outerHTML || '' + current.text += `${node.textContent || ''}\n` + if (/^h[1-3]$/.test(tag)) outline.push({ level: Number(tag[1]), label: (node.textContent || '').trim() }) + } else { + current.html += node.textContent || '' + current.text += node.textContent || '' + } + } + if (chapters.length === 0) startChapter('正文') + for (const chapter of chapters) chapter.text = chapter.text.trim() + return { chapters, outline } +} + +/** + * Load the vendored mammoth bundle once. The bundle is UMD and publishes + * `window.mammoth`; it is only requested when the user opens a .docx file. + * @param {string} [src] + */ +function loadMammoth(src = MAMMOTH_URL) { + if (typeof window !== 'undefined' && window.mammoth) return Promise.resolve(window.mammoth) + if (typeof document === 'undefined') return Promise.reject(new Error('docx parser unavailable')) + if (mammothPromise) return mammothPromise + mammothPromise = new Promise((resolve, reject) => { + const script = document.createElement('script') + script.src = src + script.async = true + script.dataset.readerDocx = '1' + script.onload = () => { + if (window.mammoth) resolve(window.mammoth) + else reject(new Error('docx parser unavailable')) + } + script.onerror = () => reject(new Error('docx parser failed to load')) + document.head.appendChild(script) + }).catch((error) => { + mammothPromise = null + throw error + }) + return mammothPromise +} + +/** + * Parse a .docx into chapters for the existing HTML reading pipeline. + * @param {Uint8Array} bytes docx bytes + * @param {{mammoth?: object, loadMammoth?: () => Promise}} [options] + */ +async function docxOpen(bytes, options = {}) { + const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes) + const files = await unzip(u8) + if (files.size > 5000) throw new Error('docx has too many parts') + if (!files.has('word/document.xml')) throw new Error('docx is missing word/document.xml') + // Inflating the main part first enforces the 40MB per-entry budget before + // mammoth expands the whole archive. + const documentXml = await zipText(files, 'word/document.xml') + if (documentXml.length > 20 * 1024 * 1024) throw new Error('docx document is too large') + const stylesXml = files.has('word/styles.xml') ? await zipText(files, 'word/styles.xml') : '' + const styles = stylesXml ? parseStyleOutline(stylesXml) : [] + const codeStyles = stylesXml ? parseCodeStyles(stylesXml) : [] + const engine = options.mammoth || (await (options.loadMammoth || loadMammoth)()) + if (!engine || typeof engine.convertToHtml !== 'function') throw new Error('docx parser unavailable') + const assets = [] + const convertImage = + engine.images && typeof engine.images.imgElement === 'function' + ? engine.images.imgElement(async (image) => { + const type = String(image.contentType || '') + if (!IMAGE_TYPES.has(type) || typeof URL.createObjectURL !== 'function') return { src: '' } + const buffer = await image.readAsArrayBuffer() + const url = URL.createObjectURL(new Blob([buffer], { type })) + assets.push(url) + return { src: url } + }) + : undefined + const arrayBuffer = u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength) + const result = await engine.convertToHtml({ arrayBuffer }, { styleMap: styleMapFor(styles, codeStyles), convertImage }) + const clean = sanitizeDocxHtml(result && result.value) + const { chapters, outline } = splitDocxChapters(clean) + if (chapters.length === 0) throw new Error('empty docx') + return { chapters, outline, assets } +} + + let pdfjsPromise = null function loadPdfjs() { @@ -2463,7 +2736,7 @@ async function pdfOpen(bytes) { async function pdfRenderPage(pdf, pageNumber, canvas, layer, scale, onTask) { const page = await pdf.doc.getPage(pageNumber) const viewport = page.getViewport({ scale }) - const dpr = Math.min(window.devicePixelRatio || 1, 2) + const dpr = Math.min(window.devicePixelRatio || 1, 3) canvas.width = Math.floor(viewport.width * dpr) canvas.height = Math.floor(viewport.height * dpr) canvas.style.width = viewport.width + 'px' @@ -2490,6 +2763,7 @@ async function pdfRenderPage(pdf, pageNumber, canvas, layer, scale, onTask) { span.style.left = tx[4] + 'px' span.style.top = tx[5] - height + 'px' span.style.fontSize = height + 'px' + span.style.fontFamily = 'Arial, "Microsoft YaHei", sans-serif' layer.appendChild(span) const expected = (item.width || 0) * viewport.scale const actual = span.getBoundingClientRect().width @@ -2999,6 +3273,7 @@ function shortcutFor(event, context = {}) { if (modifier && !event.altKey && key.toLowerCase() === 'z') { return event.shiftKey ? 'redo' : 'undo' } + if (modifier && !event.altKey && !event.shiftKey && key.toLowerCase() === 'y') return 'redo' if (modifier && !event.altKey && key.toLowerCase() === 'f') return 'search' if (modifier || event.altKey) return null if (key === 'Home') return 'start' @@ -3587,7 +3862,7 @@ function panelPosition(input) { function buildTranslatedHtml(html, resolve) { const container = document.createElement('div') container.innerHTML = String(html || '') - for (const node of container.querySelectorAll('p, li, blockquote, h2, h3, h4, td, pre')) { + for (const node of container.querySelectorAll('p, li, blockquote, h2, h3, h4, pre')) { if (node.closest('.rd-card, .rd-trans')) continue const text = normalizeBlockText(node.textContent) if (!text) continue @@ -4040,6 +4315,7 @@ function annotationsMarkdown(store, now = Date.now()) { } + /** * Find a stale document entry that shares the current path but has a different * fingerprint and still carries annotations to migrate. @@ -4050,7 +4326,7 @@ function annotationsMarkdown(store, now = Date.now()) { function staleDocFor(docs, path, key) { for (const [docKey, doc] of Object.entries(docs || {})) { if (docKey === key) continue - if (!doc || doc.path !== path) continue + if (!doc || normalizeRelPath(doc.path) !== normalizeRelPath(path)) continue if (Array.isArray(doc.annotations) && doc.annotations.length > 0) { return { fromKey: docKey, count: doc.annotations.length } } @@ -4139,7 +4415,8 @@ function hostAvailableHeight(node, viewportHeight) { if (clips) { const rect = parent.getBoundingClientRect() const padBottom = parseFloat(style.paddingBottom) || 0 - const candidate = rect.bottom - padBottom + const scrollbar = Math.max(0, (parent.offsetHeight || 0) - (parent.clientHeight || 0)) + const candidate = rect.bottom - padBottom - scrollbar if (candidate > 0 && candidate < bottom) bottom = candidate // The nearest scroll container already bounds everything above it. if (overflowY === 'auto' || overflowY === 'scroll' || overflowY === 'overlay') { @@ -4172,6 +4449,43 @@ function fitHostHeight(node, viewportHeight) { } +/** + * Decode a text file the way Windows users actually save them: UTF-8 (with or + * without BOM), UTF-16 with BOM, and the GBK/GB18030 family used by older + * Chinese editors. Falls back to UTF-8 replacement characters when nothing + * matches, so opening never blocks on encoding. + * @param {ArrayBuffer|Uint8Array} bytes file bytes + */ +function decodeText(bytes) { + const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes) + if (u8.length >= 3 && u8[0] === 0xef && u8[1] === 0xbb && u8[2] === 0xbf) { + return new TextDecoder('utf-8').decode(u8.subarray(3)) + } + if (u8.length >= 2 && u8[0] === 0xff && u8[1] === 0xfe) { + return new TextDecoder('utf-16le').decode(u8.subarray(2)) + } + if (u8.length >= 2 && u8[0] === 0xfe && u8[1] === 0xff) { + return new TextDecoder('utf-16be').decode(u8.subarray(2)) + } + // BOM-less UTF-16: ASCII-heavy text has a NUL in every other byte. + if (u8.length >= 4 && u8[1] === 0 && u8[3] === 0 && u8[0] !== 0) { + return new TextDecoder('utf-16le').decode(u8) + } + if (u8.length >= 4 && u8[0] === 0 && u8[2] === 0 && u8[1] !== 0) { + return new TextDecoder('utf-16be').decode(u8) + } + try { + return new TextDecoder('utf-8', { fatal: true }).decode(u8) + } catch { + try { + return new TextDecoder('gb18030').decode(u8) + } catch { + return new TextDecoder('utf-8').decode(u8) + } + } +} + + /** * Pure row model for the in-reader conversation panel. * @@ -5240,7 +5554,9 @@ function currentPosition(doc, state = {}) { const ext = String(doc.ext || '') const name = String(doc.name || '') const path = String(doc.path || '') - const chapters = doc.epub && Array.isArray(doc.epub.chapters) ? doc.epub.chapters : null + const chapters = + (doc.docx && Array.isArray(doc.docx.chapters) && doc.docx.chapters) || + (doc.epub && Array.isArray(doc.epub.chapters) ? doc.epub.chapters : null) const isPdf = ext === '.pdf' || /\.pdf$/i.test(name) if (isPdf) { const totalPages = doc.pdf ? Number(doc.pdf.numPages) : NaN @@ -5384,8 +5700,10 @@ async function buildContextWindow(doc, state = {}) { if (pages.length === 0) return null text = parts.join('\n\n') title = `${name} · 第 ${pages[0] === pages[pages.length - 1] ? pages[0] : `${pages[0]}-${pages[pages.length - 1]}`} 页` - } else if (ext === '.epub') { - const chapters = doc.epub && Array.isArray(doc.epub.chapters) ? doc.epub.chapters : null + } else if (ext === '.epub' || ext === '.docx') { + const chapters = + (doc.docx && Array.isArray(doc.docx.chapters) && doc.docx.chapters) || + (doc.epub && Array.isArray(doc.epub.chapters) ? doc.epub.chapters : null) if (!chapters) return null const requestedChapter = Number(known.chapter) const index = Number.isFinite(requestedChapter) && requestedChapter > 0 ? Math.floor(requestedChapter) : 0 @@ -5499,8 +5817,9 @@ const COLORS = ['#f2c94c', '#6fcf97', '#56ccf2', '#bb6bd9'] const TRANSLATE_TARGETS = ['zh', 'en', 'ja', 'ko', 'fr', 'de', 'es', 'ru', 'pt'] const TRANSLATE_SOURCES = ['auto', ...TRANSLATE_TARGETS] -function decodeText(bytes) { - return new TextDecoder('utf-8').decode(bytes) +/** Chapters exposed by the packaged text formats (EPUB and Word). */ +function chaptersFor(target) { + return (target && target.docx && target.docx.chapters) || (target && target.epub && target.epub.chapters) || [] } function markdownImageResolver(sessionId, doc) { @@ -5514,9 +5833,9 @@ function markdownImageResolver(sessionId, doc) { } catch { /* keep the raw path */ } - const parts = String(doc.path).split('/') + const parts = normalizeRelPath(doc.path).split('/') parts.pop() - for (const part of decoded.split('/')) { + for (const part of normalizeRelPath(decoded).split('/')) { if (!part || part === '.') continue if (part === '..') parts.pop() else parts.push(part) @@ -5731,7 +6050,7 @@ function PdfPane(props) { ) } -const READER_VERSION = '0.14.0' +const READER_VERSION = '0.15.0' class ReaderBoundary extends React.Component { constructor(props) { @@ -5768,7 +6087,7 @@ class ReaderBoundary extends React.Component { message: this.state.error?.message, stack: this.state.error?.stack, }) - if (navigator.clipboard) navigator.clipboard.writeText(text) + if (navigator.clipboard) navigator.clipboard.writeText(text).catch(() => {}) }, }, t('action.copyDiagnostics'), @@ -6074,6 +6393,16 @@ function ReaderView(props) { toastTimer.current = setTimeout(() => setToast(null), 4000) } + const copyText = async (text) => { + try { + if (!navigator.clipboard) throw new Error('clipboard unavailable') + await navigator.clipboard.writeText(String(text || '')) + flash(t('label.copied')) + } catch { + flash(t('label.copyFailed')) + } + } + const mergeStore = (next) => { if (!next) return setStore((current) => (Number(next.revision || 0) >= Number(current.revision || 0) ? next : current)) @@ -6322,11 +6651,32 @@ function ReaderView(props) { return root ? root.closest('.rd-main') || root.parentElement : null } + // Ctrl+wheel is the Windows pinch/zoom gesture. Keep it inside the reader + // instead of letting Chromium scale the whole DSH window. + React.useEffect(() => { + if (!doc) return undefined + const main = readingScroller() + if (!main) return undefined + const onWheel = (event) => { + if (!event.ctrlKey && !event.metaKey) return + event.preventDefault() + const direction = event.deltaY < 0 ? 1 : -1 + if (doc.ext === '.pdf') { + setZoom((current) => Math.min(2.5, Math.max(0.6, +(current + direction * 0.15).toFixed(2)))) + } else { + const current = Number(prefs.fontSize) || 18 + changePrefs({ fontSize: Math.min(26, Math.max(14, current + direction)) }) + } + } + main.addEventListener('wheel', onWheel, { passive: false }) + return () => main.removeEventListener('wheel', onWheel) + }, [doc && doc.path, doc && doc.ext, prefs.fontSize]) + // Title of the chapter/section currently on screen, used for quote locations. const docChapterTitle = () => { if (!doc) return '' - if (doc.ext === '.epub' && doc.epub && doc.epub.chapters[chapter]) { - return String(doc.epub.chapters[chapter].label || '') + if ((doc.ext === '.epub' || doc.ext === '.docx') && chaptersFor(doc)[chapter]) { + return String(chaptersFor(doc)[chapter].label || '') } if (doc.ext === '.pdf') return '' const root = contentRef.current @@ -6351,7 +6701,9 @@ function ReaderView(props) { scrollHeight: main.scrollHeight, clientHeight: main.clientHeight, }) - if (doc.ext === '.epub' && doc.epub) return Math.round(chapterProgress(chapter, local, doc.epub.chapters.length) * 100) + if ((doc.ext === '.epub' || doc.ext === '.docx') && chaptersFor(doc).length) { + return Math.round(chapterProgress(chapter, local, chaptersFor(doc).length) * 100) + } return Math.round(local * 100) } @@ -6398,8 +6750,8 @@ function ReaderView(props) { scrollHeight: main.scrollHeight, clientHeight: main.clientHeight, }) - if (doc.ext === '.epub' && doc.epub) { - setReadingProgress(chapterProgress(chapter, local, doc.epub.chapters.length)) + if ((doc.ext === '.epub' || doc.ext === '.docx') && chaptersFor(doc).length) { + setReadingProgress(chapterProgress(chapter, local, chaptersFor(doc).length)) } else { setReadingProgress(local) } @@ -6440,8 +6792,9 @@ function ReaderView(props) { main.scrollTo({ top: target.top, behavior: 'instant' }) return } - if (doc.ext !== '.epub' || !doc.epub) return - if (target.kind === 'end' && chapter < doc.epub.chapters.length - 1) goChapter(chapter + 1, 'top') + const chapters = chaptersFor(doc) + if ((doc.ext !== '.epub' && doc.ext !== '.docx') || chapters.length === 0) return + if (target.kind === 'end' && chapter < chapters.length - 1) goChapter(chapter + 1, 'top') if (target.kind === 'start' && chapter > 0) goChapter(chapter - 1, 'bottom') } @@ -6490,6 +6843,7 @@ function ReaderView(props) { React.useEffect(() => { const onKey = (event) => { + if (event.isComposing) return const action = shortcutFor(event, { editable: isEditableTarget(event.target), pageKeys: prefs.pageKeys }) if (action === 'undo' || action === 'redo') { event.preventDefault() @@ -6611,7 +6965,11 @@ function ReaderView(props) { }, []) const revokeAssets = (target) => { - for (const url of (target && target.epub && target.epub.assetUrls) || []) { + const urls = [ + ...((target && target.epub && target.epub.assetUrls) || []), + ...((target && target.docx && target.docx.assets) || []), + ] + for (const url of urls) { try { URL.revokeObjectURL(url) } catch { @@ -6632,6 +6990,9 @@ function ReaderView(props) { next.epub = await epubOpen(opened.bytes) if (next.epub.fixedLayout) throw new Error(t('label.fxlUnsupported')) } + if (ext === '.docx') { + next.docx = await docxOpen(opened.bytes) + } if (ext === '.pdf') { next.pdf = await pdfOpen(opened.bytes) next.pdf.structure = null @@ -7114,6 +7475,10 @@ function ReaderView(props) { if (fragment) setPendingAnchor(fragment) } } + if (doc && doc.ext === '.docx' && href.startsWith('#')) { + const local = document.getElementById(decodeURIComponent(href.slice(1))) + if (local && local.scrollIntoView) local.scrollIntoView({ block: 'start' }) + } } const updateAnnotation = async (id, patch) => { @@ -7445,7 +7810,23 @@ function ReaderView(props) { setSearchBusy(true) setSearchDone(false) try { - if (doc.ext === '.pdf' && doc.pdf) { + if (doc.ext === '.docx' && doc.docx) { + const chapters = doc.docx.chapters || [] + const results = [] + const needle = query.toLowerCase() + for (const [index, chapter] of chapters.entries()) { + const text = String(chapter.text || '') + for (const hit of searchText(text, query, 50 - results.length)) { + results.push({ + ...hit, + chapter: index, + occurrence: text.slice(0, hit.index).toLowerCase().split(needle).length - 1, + }) + } + if (results.length >= 50) break + } + setSearchResults(results) + } else if (doc.ext === '.pdf' && doc.pdf) { const results = [] for (let pageNumber = 1; pageNumber <= doc.pdf.numPages && results.length < 50; pageNumber += 1) { const page = await doc.pdf.doc.getPage(pageNumber) @@ -7480,15 +7861,23 @@ function ReaderView(props) { jumpToPdfPage(result.page) return } - const root = contentRef.current - if (!root) return - const found = findQuoteRange(root, searchQuery.trim(), result.occurrence || 0) - if (found) { - const node = found.range.startContainer - const element = node.nodeType === 3 ? node.parentElement : node - if (element && element.scrollIntoView) element.scrollIntoView({ block: 'center' }) - pulseRange(found.range, pulseOptions()) + const reveal = () => { + const root = contentRef.current + if (!root) return + const found = findQuoteRange(root, searchQuery.trim(), result.occurrence || 0) + if (found) { + const node = found.range.startContainer + const element = node.nodeType === 3 ? node.parentElement : node + if (element && element.scrollIntoView) element.scrollIntoView({ block: 'center' }) + pulseRange(found.range, pulseOptions()) + } + } + if (doc?.ext === '.docx' && Number.isFinite(result.chapter) && result.chapter !== chapter) { + goChapter(result.chapter, 'top') + requestAnimationFrame(() => requestAnimationFrame(reveal)) + return } + reveal() } const renderSelectionTranslation = () => { @@ -7611,7 +8000,7 @@ function ReaderView(props) { const collectTranslationBlocks = (limit = 1000) => { const root = contentRef.current if (!root) return [] - const nodes = root.querySelectorAll('p, li, blockquote, h2, h3, h4, td') + const nodes = root.querySelectorAll('p, li, blockquote, h2, h3, h4') const blocks = [] const seen = new Set() for (const node of nodes) { @@ -7901,6 +8290,7 @@ function ReaderView(props) { const structureOptions = quickGuide ? { maxSections: 32, maxParts: 24, oneSectionPerPart: true } : {} let structure = null if (doc.ext === '.epub' && doc.epub) structure = epubGuideStructure(doc.epub, structureOptions) + else if (doc.ext === '.docx' && doc.docx) structure = epubGuideStructure(doc.docx, structureOptions) else if (doc.ext === '.pdf' && doc.pdf) { if (quickGuide) structure = await pdfGuideStructure(doc.pdf, structureOptions) else if (doc.pdf.structure) structure = doc.pdf.structure @@ -7941,10 +8331,11 @@ function ReaderView(props) { if (!section) return // The fullscreen overlay hides the book; jumping to the source must reveal it. if (mapFullscreen) setMapFullscreen(false) - if (doc?.ext === '.epub') { + if (doc?.ext === '.epub' || doc?.ext === '.docx') { const match = String(section.id || '').match(/^(?:e|c)(\d+)/i) const index = Number.isFinite(section.chapter) ? section.chapter : match ? Number(match[1]) : NaN - if (Number.isFinite(index) && doc.epub.chapters[index]) jumpToChapter(index) + const chapters = chaptersFor(doc) + if (Number.isFinite(index) && chapters[index]) jumpToChapter(index) return } if (doc?.ext === '.pdf') { @@ -8453,11 +8844,12 @@ function ReaderView(props) { h('button', { key: 'next', className: 'rd-btn ghost', onClick: () => setPage((p) => Math.min(doc.pdf.numPages, p + step)) }, '›'), ) } - if (doc.ext === '.epub') { + if (doc.ext === '.epub' || doc.ext === '.docx') { + const chapters = chaptersFor(doc) buttons.push( h('button', { key: 'prev', className: 'rd-btn ghost', onClick: () => { if (chapter > 0) goChapter(chapter - 1, 'bottom') } }, '‹'), - h('span', { key: 'chapter', className: 'rd-muted', style: { fontSize: '12px' } }, `${chapter + 1} / ${doc.epub.chapters.length}`), - h('button', { key: 'next', className: 'rd-btn ghost', onClick: () => { if (chapter < doc.epub.chapters.length - 1) goChapter(chapter + 1, 'top') } }, '›'), + h('span', { key: 'chapter', className: 'rd-muted', style: { fontSize: '12px' } }, `${chapter + 1} / ${chapters.length}`), + h('button', { key: 'next', className: 'rd-btn ghost', onClick: () => { if (chapter < chapters.length - 1) goChapter(chapter + 1, 'top') } }, '›'), ) } buttons.push(h('span', { key: 'spacer', className: 'rd-spacer' })) @@ -8567,7 +8959,7 @@ function ReaderView(props) { } const renderLibrary = () => { - const parts = dir === '.' ? [] : dir.split('/') + const parts = dir === '.' ? [] : normalizeRelPath(dir).split('/') const trail = [{ label: '…', path: '.' }] let acc = '' for (const part of parts) { @@ -8622,7 +9014,7 @@ function ReaderView(props) { const renderedHtml = React.useMemo(() => { if (!doc || doc.ext === '.pdf') return '' - if (doc.ext === '.epub') return (doc.epub.chapters[chapter] || {}).html || '' + if (doc.ext === '.epub' || doc.ext === '.docx') return (chaptersFor(doc)[chapter] || {}).html || '' return markdownRender(decodeText(doc.bytes), { resolveImage: markdownImageResolver(sessionId, doc) }) }, [doc, chapter]) @@ -8721,8 +9113,8 @@ function ReaderView(props) { if (!drawer || !doc) return null let body = null if (drawer === 'toc') { - if (doc.ext === '.epub') { - body = doc.epub.chapters.map((item, index) => + if (doc.ext === '.epub' || doc.ext === '.docx') { + body = chaptersFor(doc).map((item, index) => h( 'div', { @@ -10141,7 +10533,7 @@ function ReaderView(props) { { className: 'rd-btn', onClick: () => { - navigator.clipboard.writeText(menu.text) + copyText(menu.text) setMenu(null) }, }, @@ -10287,7 +10679,7 @@ function ReaderView(props) { 'div', { className: 'rd-help-box', onClick: (event) => event.stopPropagation() }, h('h3', { style: { marginTop: 0 } }, t('label.shortcuts')), - [['← / →', t('help.paging')], ['⌘Z / ⌘⇧Z', t('help.undo')], ['?', t('help.help')], ['Esc', t('help.close')]].map( + [['← / →', t('help.paging')], [undoLabel(), t('help.undo')], ['?', t('help.help')], ['Esc', t('help.close')]].map( ([keys, label]) => h('div', { key: keys, className: 'rd-help-row' }, h('span', null, label), h('b', null, keys)), ), ), diff --git a/dsh-reader/docs/DETAIL.md b/dsh-reader/docs/DETAIL.md index 075c47e..4abc2e6 100644 --- a/dsh-reader/docs/DETAIL.md +++ b/dsh-reader/docs/DETAIL.md @@ -1,6 +1,6 @@ # 阅读(Reader) -在主区域新增一个「阅读」视图:读工作区里的 PDF、EPUB、Markdown 与纯文本,划词高亮、写笔记,让模型解释不懂的概念,并在之后悬停概念时原地浮出卡片。 +在主区域新增一个「阅读」视图:读工作区里的 PDF、EPUB、Word(.docx)、Markdown 与纯文本,划词高亮、写笔记,让模型解释不懂的概念,并在之后悬停概念时原地浮出卡片。 ## 用法 @@ -12,15 +12,15 @@ 6. 在概念卡里再选中一个词,可以「再解释」,形成嵌套概念(最多 3 层)。 7. 右侧抽屉提供目录、标注、概念、导读、对话、设置六个面板。 8. 导读:生成章节摘要、全书主旨与核心问题;导图按「书→篇→节」展示,章内分块节点用「(N)+ 要点首句」区分(不再重复章节名),根节点显示去掉扩展名与下载站后缀的书名;导图画布铺一层随平移/缩放同步的点阵网格,暗示可拖拽缩放;可折叠/缩放/跳转,并可导出 SVG/PNG/Markdown;长书显示进度、可停止。 -9. ⌘F 搜索全文;PDF 可切换双页,翻页键可用方向键或 J/K;目录优先显示 PDF 真实书签。 +9. ⌘F 搜索全文;Word 跨章搜索;PDF 可切换双页,翻页键可用方向键或 J/K;目录优先显示 PDF 真实书签。 10. 导读按「段 → 篇 → 全书」分层归约,长书有阶段进度、可停止;概念抽屉按当前书过滤;浮窗始终留在阅读区内。 -11. 工具栏「译」:Markdown/EPUB 段落双语对照;PDF 右侧译文抽屉按页对照;划词工具条可即时翻译;设置里选目标语言。 +11. 工具栏「译」:Markdown/EPUB/Word 段落双语对照(Word 表格单元格除外);PDF 右侧译文抽屉按页对照;划词工具条可即时翻译;设置里选目标语言。 12. 读书对话:选中正文点「问 AI」,引用进入底部原生输入框(首行带书名/章节/位置),回车即由当前会话的原生智能体回答;回答实时显示在抽屉「对话」页签,可继续追问,也可「在对话页打开」切到完整对话页。对话按角色分列:提问在右侧品牌色气泡,回答在左侧纸感气泡。回答生成中直接流式显示正文,尚无正文时显示当前动作(正在读取文件/执行命令…),过程折叠与光标保留;引用的原文显示为来源条,过程/工具调用折叠成每条回答里的「过程 · N」,历史轮次与「在对话页打开」收在抽屉标题行,不额外占用对话空间;对话面板与阅读区使用不同底色。消息里的图片通过客户端 Session 服务就地解析显示(点开可看原图),PDF/文档等附件显示为带类型与大小的文件卡;解析失败时降级为文件名占位。选中正文点「问 AI」时,选区内的图片会作为附件加入输入框、内联 SVG 序列化为附件文件、MathML 公式的 TeX 源码写入引用;PNG/JPEG/WebP/GIF 走原生图片附件,其他格式作为文件附件(PDF 文本层没有图片/公式对象,只引用文本)。抽屉「对话」页签可拖拽宽度(默认 420px,320–720),关闭面板时新回答会点亮未读点。面板按角色区分「你」与「助手」,引用消息的书名/位置单独成行;推理与工具调用默认折叠成「过程 · N」,需要看轨迹时点开这条回答里的「过程」展开。 10. 概念可合并、可追问、可记录本书用法;数据可导出 JSON 或 Markdown,导入前有数量确认,设置里可恢复备份。 概念与标注保存在工作区的 `.dsh-reader/store.json`,随工作区走,不上传。 -对话面板本身不存消息:它只读当前会话的对话快照,消息由 DSH 会话日志保存。阅读位置与当前窗口文本由客户端上报到 `POST /api/context`,位置进 `store.json` 的 `reading` 字段,窗口进 `.dsh-reader/context.json`(单会话 24000 字,最多 10 个会话),供宿主工具 `reader_context`、`reader_read` 读取;宿主不解析 PDF/EPUB 源文件。 +对话面板本身不存消息:它只读当前会话的对话快照,消息由 DSH 会话日志保存。阅读位置与当前窗口文本由客户端上报到 `POST /api/context`,位置进 `store.json` 的 `reading` 字段,窗口进 `.dsh-reader/context.json`(单会话 24000 字,最多 10 个会话),供宿主工具 `reader_context`、`reader_read` 读取;宿主不解析 PDF/EPUB/Word 源文件,Word 的窗口取当前章。 - 数据为 v2:文档以内容指纹为主键,改名/移动后自动重绑;旧版 v1 数据会在首次读取时自动迁移,迁移前备份。 - 每次写入前保留最近 5 份快照(`.dsh-reader/backups/`)。 @@ -51,6 +51,9 @@ - 扫描版 PDF 没有文本层,不能标注。 - 固定版式 EPUB(FXL)不支持。 +- `.doc` 旧格式、`.rtf`、`.wps` 不支持;Word 不还原分页、页眉页脚、分栏、文本框与页码。 +- 加密/密码保护的 Word 文档无法打开。 +- Word 的修订显示为“接受所有修订后的最终稿”,批注不显示;脚注按 mammoth 的输出显示在文末(按章分配留待后续)。 - 段落对照翻译、概念图谱、移动端尚未包含。 - 解释/导读/追问需要 DSH 已配置可用的模型。 - 读书对话的输入框、模型选择与工具能力由 DSH 提供;旧版 DSH 缺少对话标准 props 时,「问 AI」入口与「对话」页签自动隐藏,其余功能不受影响。 diff --git a/dsh-reader/eval/cases.mjs b/dsh-reader/eval/cases.mjs index 7c70b86..b6f7fa6 100644 --- a/dsh-reader/eval/cases.mjs +++ b/dsh-reader/eval/cases.mjs @@ -3,6 +3,7 @@ import { parseHTML } from 'linkedom' import fs from 'node:fs/promises' import os from 'node:os' import path from 'node:path' +import { pathToFileURL } from 'node:url' import { fileURLToPath } from 'node:url' const here = path.dirname(fileURLToPath(import.meta.url)) @@ -25,18 +26,18 @@ if (dom.window.Range) { dom.window.Range.prototype.getClientRects = () => [] } -const { applyHighlights } = await import(path.join(root, 'src/client/annotations.js')) -const { markTerms } = await import(path.join(root, 'src/client/concepts.js')) -const { markdownRender } = await import(path.join(root, 'src/client/markdown.js')) -const { markdownSections } = await import(path.join(root, 'src/client/sections.js')) -const { docFingerprint } = await import(path.join(root, 'lib/fingerprint.js')) -const { readStore } = await import(path.join(root, 'lib/store.js')) -const { parseSectionReply, parseOverviewReply } = await import(path.join(root, 'lib/guide.js')) -const { buildTree, layoutTree, chunkNodeLines, mapGridVars } = await import(path.join(root, 'src/client/mindmap.js')) -const { clampCardPosition } = await import(path.join(root, 'src/client/card-drag.js')) -const { takeTranslationBatch, isNearViewport } = await import(path.join(root, 'src/client/translation-schedule.js')) -const { buildTranscript, formatLocation, buildQuoteText } = await import(path.join(root, 'src/client/chat-transcript.js')) -const { buildReadingReport, buildReaderContextPayload, buildReaderReadPayload } = await import(path.join(root, 'lib/reader-context.js')) +const { applyHighlights } = await import(pathToFileURL(path.join(root, 'src/client/annotations.js')).href) +const { markTerms } = await import(pathToFileURL(path.join(root, 'src/client/concepts.js')).href) +const { markdownRender } = await import(pathToFileURL(path.join(root, 'src/client/markdown.js')).href) +const { markdownSections } = await import(pathToFileURL(path.join(root, 'src/client/sections.js')).href) +const { docFingerprint } = await import(pathToFileURL(path.join(root, 'lib/fingerprint.js')).href) +const { readStore } = await import(pathToFileURL(path.join(root, 'lib/store.js')).href) +const { parseSectionReply, parseOverviewReply } = await import(pathToFileURL(path.join(root, 'lib/guide.js')).href) +const { buildTree, layoutTree, chunkNodeLines, mapGridVars } = await import(pathToFileURL(path.join(root, 'src/client/mindmap.js')).href) +const { clampCardPosition } = await import(pathToFileURL(path.join(root, 'src/client/card-drag.js')).href) +const { takeTranslationBatch, isNearViewport } = await import(pathToFileURL(path.join(root, 'src/client/translation-schedule.js')).href) +const { buildTranscript, formatLocation, buildQuoteText } = await import(pathToFileURL(path.join(root, 'src/client/chat-transcript.js')).href) +const { buildReadingReport, buildReaderContextPayload, buildReaderReadPayload } = await import(pathToFileURL(path.join(root, 'lib/reader-context.js')).href) function mount(html) { const host = document.createElement('div') diff --git a/dsh-reader/eval/docx.mjs b/dsh-reader/eval/docx.mjs new file mode 100644 index 0000000..21a92d8 --- /dev/null +++ b/dsh-reader/eval/docx.mjs @@ -0,0 +1,172 @@ +#!/usr/bin/env node +/** + * Word pipeline probe (PRD v0.15 §9.2). + * + * Runs the real mammoth bundle through `docxOpen` in a DOM, then asserts the + * chapter/outline/table/sanitizer contract that the reader relies on. It is the + * release gate's 13th check; the browser-level fixture lives in eval/visual.mjs. + */ +import fs from 'node:fs' +import vm from 'node:vm' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { JSDOM } from 'jsdom' + +const here = path.dirname(fileURLToPath(import.meta.url)) +const root = path.resolve(here, '..') + +const dom = new JSDOM('') +globalThis.document = dom.window.document +globalThis.DOMParser = dom.window.DOMParser +globalThis.window = globalThis +vm.runInThisContext(fs.readFileSync(path.join(root, 'assets', 'mammoth.browser.min.js'), 'utf8')) +const mammoth = globalThis.mammoth +const { docxOpen, parseStyleOutline, splitDocxChapters, sanitizeDocxHtml } = await import( + path.join(root, 'src', 'client', 'docx.js') +) + +function zipBytes(entries) { + const enc = new TextEncoder() + const locals = [] + const centrals = [] + let offset = 0 + for (const [name, text] of entries) { + const nameBytes = enc.encode(name) + const data = enc.encode(text) + const local = new Uint8Array(30 + nameBytes.length + data.length) + const lv = new DataView(local.buffer) + lv.setUint32(0, 0x04034b50, true) + lv.setUint16(4, 20, true) + lv.setUint32(18, data.length, true) + lv.setUint32(22, data.length, true) + lv.setUint16(26, nameBytes.length, true) + local.set(nameBytes, 30) + local.set(data, 30 + nameBytes.length) + locals.push(local) + const central = new Uint8Array(46 + nameBytes.length) + const cv = new DataView(central.buffer) + cv.setUint32(0, 0x02014b50, true) + cv.setUint16(4, 20, true) + cv.setUint16(6, 20, true) + cv.setUint32(20, data.length, true) + cv.setUint32(24, data.length, true) + cv.setUint16(28, nameBytes.length, true) + cv.setUint32(42, offset, true) + central.set(nameBytes, 46) + centrals.push(central) + offset += local.length + } + const cdOffset = offset + const cdSize = centrals.reduce((sum, part) => sum + part.length, 0) + const eocd = new Uint8Array(22) + const ev = new DataView(eocd.buffer) + ev.setUint32(0, 0x06054b50, true) + ev.setUint16(8, entries.length, true) + ev.setUint16(10, entries.length, true) + ev.setUint32(12, cdSize, true) + ev.setUint32(16, cdOffset, true) + const out = new Uint8Array(offset + cdSize + eocd.length) + let at = 0 + for (const part of locals) { + out.set(part, at) + at += part.length + } + for (const part of centrals) { + out.set(part, at) + at += part.length + } + out.set(eocd, at) + return out +} + +const CONTENT_TYPES = + '' +const RELS = + '' +const STYLES = + '' +const DOC = + '' + + '第一章 技术报告' + + '技术报告正文。' + + '1.1 数据' + + '指标数值' + + '1 引言............3' + + '第二章 结论' + + '结论正文。' + + '' + +const checks = [] +function check(name, fn) { + try { + const detail = fn() + checks.push({ name, pass: true, detail }) + console.log(`PASS ${name.padEnd(34)} ${detail}`) + } catch (error) { + checks.push({ name, pass: false, detail: String(error && error.message ? error.message : error) }) + console.log(`FAIL ${name.padEnd(34)} ${error && error.message ? error.message : error}`) + } +} + +const docx = zipBytes([ + ['[Content_Types].xml', CONTENT_TYPES], + ['_rels/.rels', RELS], + ['word/document.xml', DOC], + ['word/styles.xml', STYLES], +]) +const result = await docxOpen(docx, { mammoth }) + +check('chapter split', () => { + if (result.chapters.length !== 2) throw new Error(`chapters=${result.chapters.length}`) + return `${result.chapters.map((chapter) => chapter.label).join(' | ')}` +}) +check('outline levels', () => { + const levels = result.outline.map((item) => item.level).join(',') + if (levels !== '1,2,1') throw new Error(`levels=${levels}`) + return levels +}) +check('outlineLvl heading', () => { + if (!result.chapters[0].html.includes('

第一章 技术报告

')) throw new Error(result.chapters[0].html.slice(0, 80)) + return 'h1' +}) +check('table wrapper', () => { + if (!result.chapters[0].html.includes('rd-table-wrap')) throw new Error('missing wrapper') + return 'wrapped' +}) +check('toc leaders removed', () => { + if (result.chapters[0].html.includes('............')) throw new Error('dot leaders survived') + return 'clean' +}) +check('sanitizer strips scripts', () => { + const clean = sanitizeDocxHtml('

ac

') + if (/script|onclick|javascript:/.test(clean)) throw new Error(clean) + return 'clean' +}) +check('style outline parser', () => { + const styles = parseStyleOutline(STYLES) + if (styles.length !== 2 || styles[0].level !== 1) throw new Error(JSON.stringify(styles)) + return `${styles.length} styles` +}) +check('chapter text', () => { + if (!result.chapters[1].text.includes('结论正文')) throw new Error(result.chapters[1].text) + return 'ok' +}) +let guard = '' +try { + await docxOpen(zipBytes([['word/styles.xml', STYLES]]), { mammoth }) + guard = 'opened without document.xml' +} catch (error) { + guard = /document\.xml/.test(String(error && error.message)) ? 'rejected' : `wrong error: ${error && error.message}` +} +check('zip guard', () => { + if (guard !== 'rejected') throw new Error(guard) + return guard +}) + +const failed = checks.filter((item) => !item.pass) +await fs.promises.writeFile( + path.join(here, 'docx-report.json'), + JSON.stringify({ at: new Date().toISOString(), total: checks.length, failed: failed.length, checks }, null, 2), +) +console.log(`\n${checks.length - failed.length}/${checks.length} docx checks passed`) +process.exit(failed.length === 0 ? 0 : 1) diff --git a/dsh-reader/eval/motion.mjs b/dsh-reader/eval/motion.mjs index 7b0e3c9..6895ecb 100644 --- a/dsh-reader/eval/motion.mjs +++ b/dsh-reader/eval/motion.mjs @@ -818,7 +818,21 @@ async function main() { return { pass: false, detail: 'child explain action missing' } } await page.waitForFunction(() => document.querySelectorAll('.rd-card').length >= 2, { timeout: 8000 }) - await sleep(340) + // Wait for the stacking animation to settle; measuring mid-flight used to + // read a partial -4.5px shift and made this check flaky under load. + await page + .waitForFunction( + () => { + const cards = [...document.querySelectorAll('.rd-card')] + return ( + cards.length >= 2 && + cards.every((card) => card.getAnimations().every((animation) => animation.playState === 'finished')) + ) + }, + { timeout: 5000 }, + ) + .catch(() => {}) + await sleep(120) const records = await completeRecords(await stopProbe(), '.rd-card', (item) => hasClass(item, 'rd-card') && onlyOpacityTransform(item)) const cardAnimations = records.filter((item) => hasClass(item, 'rd-card') && onlyOpacityTransform(item)) const state = await page.evaluate(() => { diff --git a/dsh-reader/eval/visual.mjs b/dsh-reader/eval/visual.mjs index c461d26..c8bb8e7 100644 --- a/dsh-reader/eval/visual.mjs +++ b/dsh-reader/eval/visual.mjs @@ -22,7 +22,89 @@ const CHROME = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' const BASELINE = path.join(here, 'visual', 'baseline') const UPDATE = process.env.VISUAL_UPDATE === '1' -const DEMOS = ['示例-分布式系统阅读.md', '示例-Markdown语法.md', '示例-分布式系统.epub', '示例-分布式系统.pdf'] +const DEMOS = ['示例-分布式系统阅读.md', '示例-Markdown语法.md', '示例-分布式系统.epub', '示例-分布式系统.pdf', '示例-Word文档.docx'] +const DOCX_DEMO = '示例-Word文档.docx' + +function docxZip(entries) { + const enc = new TextEncoder() + const locals = [] + const centrals = [] + let offset = 0 + for (const [name, text] of entries) { + const nameBytes = enc.encode(name) + const data = enc.encode(text) + const local = new Uint8Array(30 + nameBytes.length + data.length) + const lv = new DataView(local.buffer) + lv.setUint32(0, 0x04034b50, true) + lv.setUint16(4, 20, true) + lv.setUint32(18, data.length, true) + lv.setUint32(22, data.length, true) + lv.setUint16(26, nameBytes.length, true) + local.set(nameBytes, 30) + local.set(data, 30 + nameBytes.length) + locals.push(local) + const central = new Uint8Array(46 + nameBytes.length) + const cv = new DataView(central.buffer) + cv.setUint32(0, 0x02014b50, true) + cv.setUint16(4, 20, true) + cv.setUint16(6, 20, true) + cv.setUint32(20, data.length, true) + cv.setUint32(24, data.length, true) + cv.setUint16(28, nameBytes.length, true) + cv.setUint32(42, offset, true) + central.set(nameBytes, 46) + centrals.push(central) + offset += local.length + } + const cdOffset = offset + const cdSize = centrals.reduce((sum, part) => sum + part.length, 0) + const eocd = new Uint8Array(22) + const ev = new DataView(eocd.buffer) + ev.setUint32(0, 0x06054b50, true) + ev.setUint16(8, entries.length, true) + ev.setUint16(10, entries.length, true) + ev.setUint32(12, cdSize, true) + ev.setUint32(16, cdOffset, true) + const out = new Uint8Array(offset + cdSize + eocd.length) + let at = 0 + for (const part of locals) { out.set(part, at); at += part.length } + for (const part of centrals) { out.set(part, at); at += part.length } + out.set(eocd, at) + return out +} + +async function ensureDocxDemo() { + const target = path.join(workspace, DOCX_DEMO) + try { + await fs.access(target) + return + } catch { + /* generate below */ + } + const contentTypes = + '' + const rels = + '' + const styles = + '' + const body = + '第一章 技术报告' + + '技术报告正文,用来说明 Word 阅读与划词。' + + '1.1 数据表' + + '指标数值吞吐1200' + + '第二章 结论' + + '结论正文。' + const document = `${body}` + await fs.writeFile( + target, + docxZip([ + ['[Content_Types].xml', contentTypes], + ['_rels/.rels', rels], + ['word/document.xml', document], + ['word/styles.xml', styles], + ]), + ) +} const results = [] function record(name, pass, detail) { @@ -327,6 +409,7 @@ function requireSync(file) { async function main() { await fs.mkdir(BASELINE, { recursive: true }) + await ensureDocxDemo() const fixtures = await buildFixtures() const harnessCode = await makeHarness() const server = await startServer(fixtures, harnessCode) @@ -1992,6 +2075,67 @@ async function main() { reason: selectionAssets.reason, }), ) + // Word: open the generated fixture and assert the prose/TOC pipeline. + await clickAny('.rd-toolbar button', ['←']) + await page.waitForSelector('.rd-library', { timeout: 8000 }) + await clickAny('.rd-entry', [DOCX_DEMO]) + await page.waitForSelector('.rd-prose h1', { timeout: 20000 }) + const docx = await page.evaluate(() => ({ + text: document.querySelector('.rd-prose')?.textContent || '', + h1: document.querySelectorAll('.rd-prose h1').length, + tables: document.querySelectorAll('.rd-prose .rd-table-wrap table').length, + })) + record('docx opens', docx.text.includes('技术报告正文') && docx.h1 >= 1, `h1=${docx.h1}`) + record('docx table wraps', docx.tables >= 1, `${docx.tables} tables`) + await clickAny('.rd-toolbar button', ['目录', 'Contents']) + await page.waitForSelector('.rd-drawer-item', { timeout: 8000 }) + const docxToc = await page.$$eval('.rd-drawer-item', (nodes) => nodes.map((node) => node.textContent.trim())) + record( + 'docx toc lists chapters', + docxToc.some((label) => label.includes('第一章')) && docxToc.some((label) => label.includes('第二章')), + docxToc.join(' | ').slice(0, 80), + ) + await page.keyboard.press('Escape') + + await page.evaluate(() => { + const paragraph = document.querySelector('.rd-prose p') + const range = document.createRange() + range.selectNodeContents(paragraph) + const selection = window.getSelection() + selection.removeAllRanges() + selection.addRange(range) + paragraph.dispatchEvent(new MouseEvent('mouseup', { bubbles: true })) + }) + const docxMenu = await page.waitForSelector('.rd-mini', { timeout: 8000 }).then(() => true).catch(() => false) + record('docx selection opens the toolbar', docxMenu, '') + if (docxMenu) { + const actions = await page.$$eval('.rd-mini button', (nodes) => + nodes.map((node) => `${node.textContent || ''} ${node.getAttribute('aria-label') || ''}`), + ) + record( + 'docx selection exposes explain/highlight/note', + actions.some((text) => text.includes('解释')) && + actions.some((text) => text.includes('高亮')) && + actions.some((text) => text.includes('笔记')), + actions.join('|').slice(0, 80), + ) + await page.keyboard.press('Escape') + } + + await page.keyboard.down('Meta') + await page.keyboard.press('f') + await page.keyboard.up('Meta') + await page.waitForSelector('.rd-search input', { timeout: 8000 }) + await page.type('.rd-search input', '结论') + await page.keyboard.press('Enter') + await page.waitForFunction(() => document.querySelectorAll('.rd-search .rd-drawer-item').length > 0, { timeout: 8000 }) + const docxHits = await page.$$eval('.rd-search .rd-drawer-item', (nodes) => nodes.map((node) => node.textContent)) + record('docx search hits a later chapter', docxHits.some((text) => text.includes('结论')), docxHits.join(' | ').slice(0, 80)) + await clickAny('.rd-search .rd-drawer-item', ['结论']) + await page.waitForFunction(() => (document.querySelector('.rd-prose')?.textContent || '').includes('结论正文'), { timeout: 8000 }).catch(() => {}) + const chapterTwo = await page.evaluate(() => document.querySelector('.rd-prose')?.textContent || '') + record('docx search jumps across chapters', chapterTwo.includes('结论正文'), chapterTwo.slice(0, 30)) + await page.keyboard.press('Escape') } catch (error) { try { const dump = await page.evaluate(() => ({ diff --git a/dsh-reader/eval/visual/baseline/01-library.png b/dsh-reader/eval/visual/baseline/01-library.png index 4bc9c9d..a3ba3f4 100644 Binary files a/dsh-reader/eval/visual/baseline/01-library.png and b/dsh-reader/eval/visual/baseline/01-library.png differ diff --git a/dsh-reader/index.js b/dsh-reader/index.js index d91b0df..20dbfcb 100644 --- a/dsh-reader/index.js +++ b/dsh-reader/index.js @@ -2,7 +2,7 @@ import fs from 'node:fs/promises' import path from 'node:path' import { randomUUID } from 'node:crypto' import { fileURLToPath } from 'node:url' -import { resolveInWorkspace } from './lib/paths.js' +import { isInside, resolveInWorkspace, toPosix } from './lib/paths.js' import { createDeadline } from './lib/deadline.js' import { readStore, writeStore, mutateStore, upsertDoc, listBackups, restoreLatestBackup } from './lib/store.js' import { recordSent } from './lib/sent.js' @@ -34,6 +34,7 @@ const MAX_BODY_BYTES = 20 * 1024 * 1024 const MIME = { '.pdf': 'application/pdf', '.epub': 'application/epub+zip', + '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.md': 'text/markdown; charset=utf-8', '.markdown': 'text/markdown; charset=utf-8', '.txt': 'text/plain; charset=utf-8', @@ -58,6 +59,18 @@ function httpError(status, message) { return error } +const IGNORED_ENTRY = /^(~\$.*|desktop\.ini|Thumbs\.db|\$RECYCLE\.BIN|System Volume Information)$/i +const NAME_COLLATOR = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }) + +/** Map a fs error to a small JSON contract without leaking absolute paths. */ +function fileError(error) { + const code = error && error.code + if (code === 'ENOENT') return { status: 404, error: 'file not found' } + if (code === 'EACCES' || code === 'EPERM') return { status: 403, error: 'permission denied' } + if (code === 'EBUSY' || code === 'ETXTBSY') return { status: 423, error: 'file busy' } + return null +} + function normalizeTerm(term) { return String(term || '').trim().toLowerCase() } @@ -122,14 +135,14 @@ async function listDir(cwd, dir) { return json({ error: 'directory unavailable' }, 404) } const rows = entries - .filter((entry) => !entry.name.startsWith('.')) + .filter((entry) => !entry.name.startsWith('.') && !IGNORED_ENTRY.test(entry.name)) .map((entry) => ({ name: entry.name, type: entry.isDirectory() ? 'dir' : 'file', - path: path.relative(cwd, path.join(target.abs, entry.name)), + path: toPosix(path.relative(cwd, path.join(target.abs, entry.name))), })) - .sort((a, b) => (a.type === b.type ? a.name.localeCompare(b.name) : a.type === 'dir' ? -1 : 1)) - return json({ cwd, dir: path.relative(cwd, target.abs) || '.', entries: rows }) + .sort((a, b) => (a.type === b.type ? NAME_COLLATOR.compare(a.name, b.name) : a.type === 'dir' ? -1 : 1)) + return json({ cwd, dir: toPosix(path.relative(cwd, target.abs)) || '.', entries: rows }) } async function readFile(cwd, rel) { @@ -138,8 +151,9 @@ async function readFile(cwd, rel) { let stat try { stat = await fs.stat(target.abs) - } catch { - return json({ error: 'file not found' }, 404) + } catch (error) { + const mapped = fileError(error) + return mapped ? json({ error: mapped.error }, mapped.status) : json({ error: 'file not found' }, 404) } if (!stat.isFile()) return json({ error: 'not a file' }, 400) if (stat.size > MAX_FILE_BYTES) return json({ error: 'file too large' }, 413) @@ -149,9 +163,20 @@ async function readFile(cwd, rel) { } catch { root = path.resolve(cwd) } - const real = await fs.realpath(target.abs).catch(() => null) - if (real && real !== root && !real.startsWith(root + path.sep)) return json({ error: 'ESCAPE' }, 403) - const bytes = await fs.readFile(target.abs) + let real + try { + real = await fs.realpath(target.abs) + } catch { + return json({ error: 'ESCAPE' }, 403) + } + if (!isInside(root, real)) return json({ error: 'ESCAPE' }, 403) + let bytes + try { + bytes = await fs.readFile(target.abs) + } catch (error) { + const mapped = fileError(error) + return mapped ? json({ error: mapped.error }, mapped.status) : json({ error: 'read failed' }, 500) + } const type = MIME[path.extname(target.abs).toLowerCase()] || 'application/octet-stream' return new Response(bytes, { headers: { diff --git a/dsh-reader/lib/atomic-write.js b/dsh-reader/lib/atomic-write.js new file mode 100644 index 0000000..483c989 --- /dev/null +++ b/dsh-reader/lib/atomic-write.js @@ -0,0 +1,52 @@ +import fs from 'node:fs/promises' +import path from 'node:path' + +const RETRY_DELAYS = [50, 150] + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) + +/** + * Replace `file` with `tmp`, tolerating transient Windows locks. + * + * `fs.rename` over a file held by Word, OneDrive or a virus scanner can fail + * with EPERM/EBUSY. Retry briefly, then fall back to copying the bytes so the + * user's annotation is not lost. + * @param {string} tmp temporary file that already holds the new bytes + * @param {string} file destination file + */ +export async function replaceFile(tmp, file) { + let lastError + for (let attempt = 0; attempt <= RETRY_DELAYS.length; attempt += 1) { + try { + await fs.rename(tmp, file) + return + } catch (error) { + lastError = error + if (attempt < RETRY_DELAYS.length) await sleep(RETRY_DELAYS[attempt]) + } + } + try { + await fs.copyFile(tmp, file) + await fs.rm(tmp, { force: true }) + } catch (error) { + await fs.rm(tmp, { force: true }).catch(() => {}) + throw lastError || error + } +} + +/** + * Write a file through a sibling temp file plus `replaceFile`. + * @param {string} file destination file + * @param {string} data UTF-8 payload + */ +export async function writeFileAtomic(file, data) { + const tmp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}` + await fs.mkdir(path.dirname(file), { recursive: true }) + try { + await fs.writeFile(tmp, data, 'utf8') + } catch (error) { + await fs.rm(tmp, { force: true }).catch(() => {}) + throw error + } + await replaceFile(tmp, file) +} diff --git a/dsh-reader/lib/paths.js b/dsh-reader/lib/paths.js index a4f50ac..1eecf38 100644 --- a/dsh-reader/lib/paths.js +++ b/dsh-reader/lib/paths.js @@ -1,5 +1,27 @@ import path from 'node:path' +/** + * Normalize a workspace-relative path to POSIX separators. The client, the + * store and every URL parameter use `/`; win32 `path.relative` returns `\`. + * @param {string} value + */ +export function toPosix(value) { + return String(value || '').replace(/\\/g, '/') +} + +/** + * Whether `target` is the workspace root or a descendant of it. Uses + * path.relative so Windows drive-letter case and junctions behave correctly. + * @param {string} root absolute workspace directory + * @param {string} target absolute candidate path + */ +export function isInside(root, target) { + const base = path.resolve(root) + const candidate = path.resolve(target) + const relative = path.relative(base, candidate) + return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) +} + /** * Resolve a workspace-relative reference without letting it leave the workspace. * @param {string} cwd absolute workspace directory @@ -10,6 +32,6 @@ export function resolveInWorkspace(cwd, rel) { if (path.isAbsolute(rel)) return { ok: false, code: 'ABSOLUTE' } const root = path.resolve(cwd) const abs = path.resolve(root, rel) - if (abs !== root && !abs.startsWith(root + path.sep)) return { ok: false, code: 'ESCAPE' } + if (!isInside(root, abs)) return { ok: false, code: 'ESCAPE' } return { ok: true, abs } } diff --git a/dsh-reader/lib/reader-context.js b/dsh-reader/lib/reader-context.js index 99eb3ab..9af5bce 100644 --- a/dsh-reader/lib/reader-context.js +++ b/dsh-reader/lib/reader-context.js @@ -1,5 +1,6 @@ import fs from 'node:fs/promises' import path from 'node:path' +import { writeFileAtomic } from './atomic-write.js' export const READING_DIR = '.dsh-reader' export const CONTEXT_FILE = 'context.json' @@ -145,14 +146,7 @@ function enqueueContextWrite(cwd, task) { async function writeContextFile(cwd, context) { const dir = path.join(cwd, READING_DIR) await fs.mkdir(dir, { recursive: true }) - const file = readingContextPath(cwd) - const tmp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}` - try { - await fs.writeFile(tmp, JSON.stringify(context, null, 2), 'utf8') - await fs.rename(tmp, file) - } finally { - await fs.rm(tmp, { force: true }).catch(() => {}) - } + await writeFileAtomic(readingContextPath(cwd), JSON.stringify(context, null, 2)) } /** diff --git a/dsh-reader/lib/store.js b/dsh-reader/lib/store.js index 0e7a580..077bb89 100644 --- a/dsh-reader/lib/store.js +++ b/dsh-reader/lib/store.js @@ -3,6 +3,8 @@ import path from 'node:path' import { migrateV1 } from './migrate.js' import { defaultPrefs } from './prefs.js' import { MAX_READING_SESSIONS, MAX_SESSION_ID_CHARS, normalizeReaderPosition } from './reader-context.js' +import { toPosix } from './paths.js' +import { writeFileAtomic } from './atomic-write.js' const DATA_DIR = '.dsh-reader' const STORE_FILE = 'store.json' @@ -69,7 +71,7 @@ function normalizeDocs(raw) { for (const [key, doc] of Object.entries(raw)) { if (!isRecord(doc)) continue docs[key] = { - path: typeof doc.path === 'string' ? doc.path : '', + path: typeof doc.path === 'string' ? toPosix(doc.path) : '', size: Number.isFinite(doc.size) ? doc.size : 0, mtime: Number.isFinite(doc.mtime) ? doc.mtime : 0, annotations: Array.isArray(doc.annotations) @@ -182,7 +184,7 @@ export async function backupStore(cwd) { await fs.writeFile(path.join(dir, name), raw) const entries = (await fs.readdir(dir)).filter((entry) => /^store-.*\.json$/.test(entry)).sort() for (const stale of entries.slice(0, Math.max(0, entries.length - BACKUP_KEEP))) { - await fs.rm(path.join(dir, stale), { force: true }) + await fs.rm(path.join(dir, stale), { force: true }).catch(() => {}) } return name } @@ -251,9 +253,7 @@ export async function writeStore(cwd, store, options = {}) { const dir = path.join(cwd, DATA_DIR) await fs.mkdir(dir, { recursive: true }) const file = storePath(cwd) - const tmp = `${file}.tmp-${process.pid}-${Date.now()}` - await fs.writeFile(tmp, JSON.stringify(normalizeV2(store), null, 2), 'utf8') - await fs.rename(tmp, file) + await writeFileAtomic(file, JSON.stringify(normalizeV2(store), null, 2)) } const writeQueues = new Map() @@ -310,7 +310,7 @@ export function upsertDoc(store, input) { } store.docs[docKey] = { ...current, - path: input.path || current.path, + path: toPosix(input.path || current.path), size: Number.isFinite(input.size) ? input.size : current.size, mtime: Number.isFinite(input.mtime) ? input.mtime : current.mtime, annotations: Array.isArray(input.annotations) ? input.annotations : current.annotations, diff --git a/dsh-reader/package.json b/dsh-reader/package.json index d4878f3..185aa8b 100644 --- a/dsh-reader/package.json +++ b/dsh-reader/package.json @@ -1,6 +1,6 @@ { "name": "@2019wakeup/dsh-reader", - "version": "0.14.0", + "version": "0.15.0", "type": "module", "description": "Reading workspace with concept cards and in-reader conversation for DeepSeek Harness", "exports": { @@ -54,7 +54,8 @@ "market:build": "node scripts/build-market-index.mjs", "market:verify": "node scripts/verify-market-index.mjs", "publish:check": "node scripts/publish-check.mjs", - "eval:motion": "node eval/motion.mjs" + "eval:motion": "node eval/motion.mjs", + "eval:docx": "node eval/docx.mjs" }, "peerDependencies": { "@deepseek-ai/dsh-tools": ">=0.2.0-rc.1 <0.3.0-0" diff --git a/dsh-reader/scripts/build-client.mjs b/dsh-reader/scripts/build-client.mjs index 4ae4128..8d62183 100644 --- a/dsh-reader/scripts/build-client.mjs +++ b/dsh-reader/scripts/build-client.mjs @@ -14,6 +14,7 @@ const files = [ 'src/client/sanitize.js', 'src/client/markdown.js', 'src/client/epub.js', + 'src/client/docx.js', 'src/client/pdf.js', 'src/client/concepts.js', 'src/client/annotations.js', @@ -36,6 +37,7 @@ const files = [ 'src/client/relink.js', 'src/client/search.js', 'src/client/host-layout.js', + 'src/client/text-decode.js', 'src/client/chat-transcript.js', 'src/client/chat-panel.js', 'src/client/chat-context.js', diff --git a/dsh-reader/scripts/release-check.mjs b/dsh-reader/scripts/release-check.mjs index 3a6c9c0..e7ce02a 100644 --- a/dsh-reader/scripts/release-check.mjs +++ b/dsh-reader/scripts/release-check.mjs @@ -53,7 +53,12 @@ await check('eval pipeline', async () => { await check('visual pipeline', async () => { command('visual', 'node eval/visual.mjs') - return '163 checks + baselines' + return '170 checks + baselines' +}) + +await check('docx pipeline', async () => { + command('docx', 'node eval/docx.mjs') + return '9/9' }) await check('motion pipeline', async () => { diff --git a/dsh-reader/src/client/api.js b/dsh-reader/src/client/api.js index b7502f9..7308ce8 100644 --- a/dsh-reader/src/client/api.js +++ b/dsh-reader/src/client/api.js @@ -6,6 +6,17 @@ const EXPLAIN_TIMEOUT_MS = 100_000 const timeoutText = () => (typeof t === 'function' ? t('label.timeout') : 'request timed out') +const FILE_ERROR_KEYS = { + 'file not found': 'error.fileNotFound', + 'permission denied': 'error.permissionDenied', + 'file busy': 'error.fileBusy', +} + +function fileErrorText(code, status) { + const key = code && FILE_ERROR_KEYS[code] + return key && typeof t === 'function' ? t(key) : 'HTTP ' + status +} + /** * Fetch JSON from the plugin host. * @@ -45,7 +56,10 @@ export const api = { fetchBytes(sessionId, path) { const url = `${BASE}/api/file?sessionId=${encodeURIComponent(sessionId || '')}&path=${encodeURIComponent(path)}` return fetch(url).then(async (res) => { - if (!res.ok) throw new Error('HTTP ' + res.status) + if (!res.ok) { + const data = await res.json().catch(() => null) + throw new Error(fileErrorText(data && data.error, res.status)) + } const bytes = await res.arrayBuffer() return { bytes, fingerprint: res.headers.get('x-doc-fingerprint') || '' } }) diff --git a/dsh-reader/src/client/app.js b/dsh-reader/src/client/app.js index 6de386c..78ef6d0 100644 --- a/dsh-reader/src/client/app.js +++ b/dsh-reader/src/client/app.js @@ -30,8 +30,9 @@ const COLORS = ['#f2c94c', '#6fcf97', '#56ccf2', '#bb6bd9'] const TRANSLATE_TARGETS = ['zh', 'en', 'ja', 'ko', 'fr', 'de', 'es', 'ru', 'pt'] const TRANSLATE_SOURCES = ['auto', ...TRANSLATE_TARGETS] -function decodeText(bytes) { - return new TextDecoder('utf-8').decode(bytes) +/** Chapters exposed by the packaged text formats (EPUB and Word). */ +function chaptersFor(target) { + return (target && target.docx && target.docx.chapters) || (target && target.epub && target.epub.chapters) || [] } function markdownImageResolver(sessionId, doc) { @@ -45,9 +46,9 @@ function markdownImageResolver(sessionId, doc) { } catch { /* keep the raw path */ } - const parts = String(doc.path).split('/') + const parts = normalizeRelPath(doc.path).split('/') parts.pop() - for (const part of decoded.split('/')) { + for (const part of normalizeRelPath(decoded).split('/')) { if (!part || part === '.') continue if (part === '..') parts.pop() else parts.push(part) @@ -299,7 +300,7 @@ class ReaderBoundary extends React.Component { message: this.state.error?.message, stack: this.state.error?.stack, }) - if (navigator.clipboard) navigator.clipboard.writeText(text) + if (navigator.clipboard) navigator.clipboard.writeText(text).catch(() => {}) }, }, t('action.copyDiagnostics'), @@ -605,6 +606,16 @@ export function ReaderView(props) { toastTimer.current = setTimeout(() => setToast(null), 4000) } + const copyText = async (text) => { + try { + if (!navigator.clipboard) throw new Error('clipboard unavailable') + await navigator.clipboard.writeText(String(text || '')) + flash(t('label.copied')) + } catch { + flash(t('label.copyFailed')) + } + } + const mergeStore = (next) => { if (!next) return setStore((current) => (Number(next.revision || 0) >= Number(current.revision || 0) ? next : current)) @@ -853,11 +864,32 @@ export function ReaderView(props) { return root ? root.closest('.rd-main') || root.parentElement : null } + // Ctrl+wheel is the Windows pinch/zoom gesture. Keep it inside the reader + // instead of letting Chromium scale the whole DSH window. + React.useEffect(() => { + if (!doc) return undefined + const main = readingScroller() + if (!main) return undefined + const onWheel = (event) => { + if (!event.ctrlKey && !event.metaKey) return + event.preventDefault() + const direction = event.deltaY < 0 ? 1 : -1 + if (doc.ext === '.pdf') { + setZoom((current) => Math.min(2.5, Math.max(0.6, +(current + direction * 0.15).toFixed(2)))) + } else { + const current = Number(prefs.fontSize) || 18 + changePrefs({ fontSize: Math.min(26, Math.max(14, current + direction)) }) + } + } + main.addEventListener('wheel', onWheel, { passive: false }) + return () => main.removeEventListener('wheel', onWheel) + }, [doc && doc.path, doc && doc.ext, prefs.fontSize]) + // Title of the chapter/section currently on screen, used for quote locations. const docChapterTitle = () => { if (!doc) return '' - if (doc.ext === '.epub' && doc.epub && doc.epub.chapters[chapter]) { - return String(doc.epub.chapters[chapter].label || '') + if ((doc.ext === '.epub' || doc.ext === '.docx') && chaptersFor(doc)[chapter]) { + return String(chaptersFor(doc)[chapter].label || '') } if (doc.ext === '.pdf') return '' const root = contentRef.current @@ -882,7 +914,9 @@ export function ReaderView(props) { scrollHeight: main.scrollHeight, clientHeight: main.clientHeight, }) - if (doc.ext === '.epub' && doc.epub) return Math.round(chapterProgress(chapter, local, doc.epub.chapters.length) * 100) + if ((doc.ext === '.epub' || doc.ext === '.docx') && chaptersFor(doc).length) { + return Math.round(chapterProgress(chapter, local, chaptersFor(doc).length) * 100) + } return Math.round(local * 100) } @@ -929,8 +963,8 @@ export function ReaderView(props) { scrollHeight: main.scrollHeight, clientHeight: main.clientHeight, }) - if (doc.ext === '.epub' && doc.epub) { - setReadingProgress(chapterProgress(chapter, local, doc.epub.chapters.length)) + if ((doc.ext === '.epub' || doc.ext === '.docx') && chaptersFor(doc).length) { + setReadingProgress(chapterProgress(chapter, local, chaptersFor(doc).length)) } else { setReadingProgress(local) } @@ -971,8 +1005,9 @@ export function ReaderView(props) { main.scrollTo({ top: target.top, behavior: 'instant' }) return } - if (doc.ext !== '.epub' || !doc.epub) return - if (target.kind === 'end' && chapter < doc.epub.chapters.length - 1) goChapter(chapter + 1, 'top') + const chapters = chaptersFor(doc) + if ((doc.ext !== '.epub' && doc.ext !== '.docx') || chapters.length === 0) return + if (target.kind === 'end' && chapter < chapters.length - 1) goChapter(chapter + 1, 'top') if (target.kind === 'start' && chapter > 0) goChapter(chapter - 1, 'bottom') } @@ -1021,6 +1056,7 @@ export function ReaderView(props) { React.useEffect(() => { const onKey = (event) => { + if (event.isComposing) return const action = shortcutFor(event, { editable: isEditableTarget(event.target), pageKeys: prefs.pageKeys }) if (action === 'undo' || action === 'redo') { event.preventDefault() @@ -1142,7 +1178,11 @@ export function ReaderView(props) { }, []) const revokeAssets = (target) => { - for (const url of (target && target.epub && target.epub.assetUrls) || []) { + const urls = [ + ...((target && target.epub && target.epub.assetUrls) || []), + ...((target && target.docx && target.docx.assets) || []), + ] + for (const url of urls) { try { URL.revokeObjectURL(url) } catch { @@ -1163,6 +1203,9 @@ export function ReaderView(props) { next.epub = await epubOpen(opened.bytes) if (next.epub.fixedLayout) throw new Error(t('label.fxlUnsupported')) } + if (ext === '.docx') { + next.docx = await docxOpen(opened.bytes) + } if (ext === '.pdf') { next.pdf = await pdfOpen(opened.bytes) next.pdf.structure = null @@ -1645,6 +1688,10 @@ export function ReaderView(props) { if (fragment) setPendingAnchor(fragment) } } + if (doc && doc.ext === '.docx' && href.startsWith('#')) { + const local = document.getElementById(decodeURIComponent(href.slice(1))) + if (local && local.scrollIntoView) local.scrollIntoView({ block: 'start' }) + } } const updateAnnotation = async (id, patch) => { @@ -1976,7 +2023,23 @@ export function ReaderView(props) { setSearchBusy(true) setSearchDone(false) try { - if (doc.ext === '.pdf' && doc.pdf) { + if (doc.ext === '.docx' && doc.docx) { + const chapters = doc.docx.chapters || [] + const results = [] + const needle = query.toLowerCase() + for (const [index, chapter] of chapters.entries()) { + const text = String(chapter.text || '') + for (const hit of searchText(text, query, 50 - results.length)) { + results.push({ + ...hit, + chapter: index, + occurrence: text.slice(0, hit.index).toLowerCase().split(needle).length - 1, + }) + } + if (results.length >= 50) break + } + setSearchResults(results) + } else if (doc.ext === '.pdf' && doc.pdf) { const results = [] for (let pageNumber = 1; pageNumber <= doc.pdf.numPages && results.length < 50; pageNumber += 1) { const page = await doc.pdf.doc.getPage(pageNumber) @@ -2011,15 +2074,23 @@ export function ReaderView(props) { jumpToPdfPage(result.page) return } - const root = contentRef.current - if (!root) return - const found = findQuoteRange(root, searchQuery.trim(), result.occurrence || 0) - if (found) { - const node = found.range.startContainer - const element = node.nodeType === 3 ? node.parentElement : node - if (element && element.scrollIntoView) element.scrollIntoView({ block: 'center' }) - pulseRange(found.range, pulseOptions()) + const reveal = () => { + const root = contentRef.current + if (!root) return + const found = findQuoteRange(root, searchQuery.trim(), result.occurrence || 0) + if (found) { + const node = found.range.startContainer + const element = node.nodeType === 3 ? node.parentElement : node + if (element && element.scrollIntoView) element.scrollIntoView({ block: 'center' }) + pulseRange(found.range, pulseOptions()) + } + } + if (doc?.ext === '.docx' && Number.isFinite(result.chapter) && result.chapter !== chapter) { + goChapter(result.chapter, 'top') + requestAnimationFrame(() => requestAnimationFrame(reveal)) + return } + reveal() } const renderSelectionTranslation = () => { @@ -2142,7 +2213,7 @@ export function ReaderView(props) { const collectTranslationBlocks = (limit = 1000) => { const root = contentRef.current if (!root) return [] - const nodes = root.querySelectorAll('p, li, blockquote, h2, h3, h4, td') + const nodes = root.querySelectorAll('p, li, blockquote, h2, h3, h4') const blocks = [] const seen = new Set() for (const node of nodes) { @@ -2432,6 +2503,7 @@ export function ReaderView(props) { const structureOptions = quickGuide ? { maxSections: 32, maxParts: 24, oneSectionPerPart: true } : {} let structure = null if (doc.ext === '.epub' && doc.epub) structure = epubGuideStructure(doc.epub, structureOptions) + else if (doc.ext === '.docx' && doc.docx) structure = epubGuideStructure(doc.docx, structureOptions) else if (doc.ext === '.pdf' && doc.pdf) { if (quickGuide) structure = await pdfGuideStructure(doc.pdf, structureOptions) else if (doc.pdf.structure) structure = doc.pdf.structure @@ -2472,10 +2544,11 @@ export function ReaderView(props) { if (!section) return // The fullscreen overlay hides the book; jumping to the source must reveal it. if (mapFullscreen) setMapFullscreen(false) - if (doc?.ext === '.epub') { + if (doc?.ext === '.epub' || doc?.ext === '.docx') { const match = String(section.id || '').match(/^(?:e|c)(\d+)/i) const index = Number.isFinite(section.chapter) ? section.chapter : match ? Number(match[1]) : NaN - if (Number.isFinite(index) && doc.epub.chapters[index]) jumpToChapter(index) + const chapters = chaptersFor(doc) + if (Number.isFinite(index) && chapters[index]) jumpToChapter(index) return } if (doc?.ext === '.pdf') { @@ -2984,11 +3057,12 @@ export function ReaderView(props) { h('button', { key: 'next', className: 'rd-btn ghost', onClick: () => setPage((p) => Math.min(doc.pdf.numPages, p + step)) }, '›'), ) } - if (doc.ext === '.epub') { + if (doc.ext === '.epub' || doc.ext === '.docx') { + const chapters = chaptersFor(doc) buttons.push( h('button', { key: 'prev', className: 'rd-btn ghost', onClick: () => { if (chapter > 0) goChapter(chapter - 1, 'bottom') } }, '‹'), - h('span', { key: 'chapter', className: 'rd-muted', style: { fontSize: '12px' } }, `${chapter + 1} / ${doc.epub.chapters.length}`), - h('button', { key: 'next', className: 'rd-btn ghost', onClick: () => { if (chapter < doc.epub.chapters.length - 1) goChapter(chapter + 1, 'top') } }, '›'), + h('span', { key: 'chapter', className: 'rd-muted', style: { fontSize: '12px' } }, `${chapter + 1} / ${chapters.length}`), + h('button', { key: 'next', className: 'rd-btn ghost', onClick: () => { if (chapter < chapters.length - 1) goChapter(chapter + 1, 'top') } }, '›'), ) } buttons.push(h('span', { key: 'spacer', className: 'rd-spacer' })) @@ -3098,7 +3172,7 @@ export function ReaderView(props) { } const renderLibrary = () => { - const parts = dir === '.' ? [] : dir.split('/') + const parts = dir === '.' ? [] : normalizeRelPath(dir).split('/') const trail = [{ label: '…', path: '.' }] let acc = '' for (const part of parts) { @@ -3153,7 +3227,7 @@ export function ReaderView(props) { const renderedHtml = React.useMemo(() => { if (!doc || doc.ext === '.pdf') return '' - if (doc.ext === '.epub') return (doc.epub.chapters[chapter] || {}).html || '' + if (doc.ext === '.epub' || doc.ext === '.docx') return (chaptersFor(doc)[chapter] || {}).html || '' return markdownRender(decodeText(doc.bytes), { resolveImage: markdownImageResolver(sessionId, doc) }) }, [doc, chapter]) @@ -3252,8 +3326,8 @@ export function ReaderView(props) { if (!drawer || !doc) return null let body = null if (drawer === 'toc') { - if (doc.ext === '.epub') { - body = doc.epub.chapters.map((item, index) => + if (doc.ext === '.epub' || doc.ext === '.docx') { + body = chaptersFor(doc).map((item, index) => h( 'div', { @@ -4672,7 +4746,7 @@ export function ReaderView(props) { { className: 'rd-btn', onClick: () => { - navigator.clipboard.writeText(menu.text) + copyText(menu.text) setMenu(null) }, }, @@ -4818,7 +4892,7 @@ export function ReaderView(props) { 'div', { className: 'rd-help-box', onClick: (event) => event.stopPropagation() }, h('h3', { style: { marginTop: 0 } }, t('label.shortcuts')), - [['← / →', t('help.paging')], ['⌘Z / ⌘⇧Z', t('help.undo')], ['?', t('help.help')], ['Esc', t('help.close')]].map( + [['← / →', t('help.paging')], [undoLabel(), t('help.undo')], ['?', t('help.help')], ['Esc', t('help.close')]].map( ([keys, label]) => h('div', { key: keys, className: 'rd-help-row' }, h('span', null, label), h('b', null, keys)), ), ), diff --git a/dsh-reader/src/client/chat-context.js b/dsh-reader/src/client/chat-context.js index c1dce16..c070dfb 100644 --- a/dsh-reader/src/client/chat-context.js +++ b/dsh-reader/src/client/chat-context.js @@ -29,7 +29,9 @@ export function currentPosition(doc, state = {}) { const ext = String(doc.ext || '') const name = String(doc.name || '') const path = String(doc.path || '') - const chapters = doc.epub && Array.isArray(doc.epub.chapters) ? doc.epub.chapters : null + const chapters = + (doc.docx && Array.isArray(doc.docx.chapters) && doc.docx.chapters) || + (doc.epub && Array.isArray(doc.epub.chapters) ? doc.epub.chapters : null) const isPdf = ext === '.pdf' || /\.pdf$/i.test(name) if (isPdf) { const totalPages = doc.pdf ? Number(doc.pdf.numPages) : NaN @@ -174,8 +176,10 @@ export async function buildContextWindow(doc, state = {}) { if (pages.length === 0) return null text = parts.join('\n\n') title = `${name} · 第 ${pages[0] === pages[pages.length - 1] ? pages[0] : `${pages[0]}-${pages[pages.length - 1]}`} 页` - } else if (ext === '.epub') { - const chapters = doc.epub && Array.isArray(doc.epub.chapters) ? doc.epub.chapters : null + } else if (ext === '.epub' || ext === '.docx') { + const chapters = + (doc.docx && Array.isArray(doc.docx.chapters) && doc.docx.chapters) || + (doc.epub && Array.isArray(doc.epub.chapters) ? doc.epub.chapters : null) if (!chapters) return null const requestedChapter = Number(known.chapter) const index = Number.isFinite(requestedChapter) && requestedChapter > 0 ? Math.floor(requestedChapter) : 0 diff --git a/dsh-reader/src/client/docx.js b/dsh-reader/src/client/docx.js new file mode 100644 index 0000000..9a83074 --- /dev/null +++ b/dsh-reader/src/client/docx.js @@ -0,0 +1,224 @@ +import { unzip, zipText } from './epub.js' + +export const MAMMOTH_URL = '/dsh-reader-live/assets/mammoth.browser.min.js' + +const IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/svg+xml']) + +let mammothPromise = null + +function localName(element) { + return String((element && (element.localName || element.tagName)) || '') + .toLowerCase() + .split(':') + .pop() +} + +function attr(element, name) { + if (!element) return '' + return element.getAttribute(name) || element.getAttribute(`w:${name}`) || '' +} + +function descendants(root, name) { + return Array.from(root.getElementsByTagName('*')).filter((element) => localName(element) === name) +} + +/** + * Read paragraph styles that carry a heading level, either through a `heading N` + * style name or through `w:outlineLvl` (common in Chinese and WPS templates). + * @param {string} stylesXml contents of word/styles.xml + * @returns {Array<{styleId: string, name: string, level: number}>} + */ +export function parseStyleOutline(stylesXml) { + if (!stylesXml || typeof DOMParser === 'undefined') return [] + const parsed = new DOMParser().parseFromString(stylesXml, 'application/xml') + if (parsed.querySelector('parsererror')) return [] + const styles = [] + for (const style of descendants(parsed, 'style')) { + if ((attr(style, 'type') || '').toLowerCase() !== 'paragraph') continue + const styleId = attr(style, 'styleId') + const nameElement = descendants(style, 'name')[0] + const name = attr(nameElement, 'val') + if (!styleId || !name) continue + const pPr = descendants(style, 'pPr')[0] + const outlineElement = pPr ? descendants(pPr, 'outlineLvl')[0] : null + const outline = outlineElement ? Number(attr(outlineElement, 'val')) : NaN + let level = Number.isFinite(outline) && outline >= 0 && outline <= 5 ? outline + 1 : 0 + if (!level) { + const match = /^(?:heading|标题)\s*([1-6])$/i.exec(name.trim()) + if (match) level = Number(match[1]) + } + if (level) styles.push({ styleId, name, level }) + } + return styles +} + +const CODE_STYLE = /^(html preformatted|preformatted text|代码|代码块|源代码)$/i + +/** + * Collect paragraph style names that should render as a code block. + * @param {string} stylesXml contents of word/styles.xml + */ +export function parseCodeStyles(stylesXml) { + if (!stylesXml || typeof DOMParser === 'undefined') return [] + const parsed = new DOMParser().parseFromString(stylesXml, 'application/xml') + if (parsed.querySelector('parsererror')) return [] + const names = [] + for (const style of descendants(parsed, 'style')) { + if ((attr(style, 'type') || '').toLowerCase() !== 'paragraph') continue + const name = attr(descendants(style, 'name')[0], 'val') + if (name && CODE_STYLE.test(name.trim())) names.push(name.trim()) + } + return names +} + +/** + * Build mammoth style-map entries for headings and code styles. + * @param {Array<{name: string, level: number}>} styles + * @param {string[]} [codeStyles] + */ +export function styleMapFor(styles, codeStyles = []) { + const map = (styles || []).map(({ name, level }) => `p[style-name='${String(name).replace(/'/g, "\\'")}'] => h${level}`) + for (const name of codeStyles) map.push(`p[style-name='${String(name).replace(/'/g, "\\'")}'] => pre`) + return map +} + +function wrapTables(root) { + for (const table of Array.from(root.querySelectorAll('table'))) { + if (table.parentElement && table.parentElement.classList.contains('rd-table-wrap')) continue + const wrap = document.createElement('div') + wrap.className = 'rd-table-wrap' + table.parentNode.insertBefore(wrap, table) + wrap.appendChild(table) + } +} + +function stripTocLeaders(root) { + for (const paragraph of Array.from(root.querySelectorAll('p'))) { + const text = String(paragraph.textContent || '').trim() + if (/^.{0,120}(?:\.{3,}|…{2,}|·{3,})\s*\d+\s*$/.test(text)) paragraph.remove() + } +} + +/** + * Sanitize mammoth output: mammoth does not sanitize, and Word files are + * untrusted input. Keep the semantic tags, drop scripts and unsafe URLs. + * @param {string} html + */ +export function sanitizeDocxHtml(html) { + if (typeof document === 'undefined') return String(html || '') + const container = document.createElement('div') + container.innerHTML = String(html || '') + for (const node of Array.from(container.querySelectorAll('script,iframe,object,embed,style,link,meta,base,form'))) { + node.remove() + } + for (const element of Array.from(container.querySelectorAll('*'))) { + for (const attribute of Array.from(element.attributes)) { + if (/^on/i.test(attribute.name)) element.removeAttribute(attribute.name) + if (attribute.name === 'href' && !/^(https?:|mailto:|#)/i.test(attribute.value)) element.removeAttribute('href') + if (attribute.name === 'src' && !/^(https?:|blob:|data:image\/)/i.test(attribute.value)) element.removeAttribute('src') + } + } + return container.innerHTML +} + +/** + * Split mammoth's flat HTML into h1 chapters and build the outline. The split + * rule is frozen once published: annotations store only the chapter index. + * @param {string} html sanitized document HTML + */ +export function splitDocxChapters(html) { + if (typeof document === 'undefined') return { chapters: [], outline: [] } + const container = document.createElement('div') + container.innerHTML = String(html || '') + wrapTables(container) + stripTocLeaders(container) + const chapters = [] + const outline = [] + let current = null + const startChapter = (label) => { + current = { label: label || '正文', html: '', text: '' } + chapters.push(current) + } + for (const node of Array.from(container.childNodes)) { + const tag = node.nodeType === 1 ? String(node.tagName || '').toLowerCase() : '' + if (tag === 'h1') startChapter((node.textContent || '').trim() || `第 ${chapters.length + 1} 章`) + else if (!current) startChapter('正文') + if (node.nodeType === 1) { + current.html += node.outerHTML || '' + current.text += `${node.textContent || ''}\n` + if (/^h[1-3]$/.test(tag)) outline.push({ level: Number(tag[1]), label: (node.textContent || '').trim() }) + } else { + current.html += node.textContent || '' + current.text += node.textContent || '' + } + } + if (chapters.length === 0) startChapter('正文') + for (const chapter of chapters) chapter.text = chapter.text.trim() + return { chapters, outline } +} + +/** + * Load the vendored mammoth bundle once. The bundle is UMD and publishes + * `window.mammoth`; it is only requested when the user opens a .docx file. + * @param {string} [src] + */ +export function loadMammoth(src = MAMMOTH_URL) { + if (typeof window !== 'undefined' && window.mammoth) return Promise.resolve(window.mammoth) + if (typeof document === 'undefined') return Promise.reject(new Error('docx parser unavailable')) + if (mammothPromise) return mammothPromise + mammothPromise = new Promise((resolve, reject) => { + const script = document.createElement('script') + script.src = src + script.async = true + script.dataset.readerDocx = '1' + script.onload = () => { + if (window.mammoth) resolve(window.mammoth) + else reject(new Error('docx parser unavailable')) + } + script.onerror = () => reject(new Error('docx parser failed to load')) + document.head.appendChild(script) + }).catch((error) => { + mammothPromise = null + throw error + }) + return mammothPromise +} + +/** + * Parse a .docx into chapters for the existing HTML reading pipeline. + * @param {Uint8Array} bytes docx bytes + * @param {{mammoth?: object, loadMammoth?: () => Promise}} [options] + */ +export async function docxOpen(bytes, options = {}) { + const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes) + const files = await unzip(u8) + if (files.size > 5000) throw new Error('docx has too many parts') + if (!files.has('word/document.xml')) throw new Error('docx is missing word/document.xml') + // Inflating the main part first enforces the 40MB per-entry budget before + // mammoth expands the whole archive. + const documentXml = await zipText(files, 'word/document.xml') + if (documentXml.length > 20 * 1024 * 1024) throw new Error('docx document is too large') + const stylesXml = files.has('word/styles.xml') ? await zipText(files, 'word/styles.xml') : '' + const styles = stylesXml ? parseStyleOutline(stylesXml) : [] + const codeStyles = stylesXml ? parseCodeStyles(stylesXml) : [] + const engine = options.mammoth || (await (options.loadMammoth || loadMammoth)()) + if (!engine || typeof engine.convertToHtml !== 'function') throw new Error('docx parser unavailable') + const assets = [] + const convertImage = + engine.images && typeof engine.images.imgElement === 'function' + ? engine.images.imgElement(async (image) => { + const type = String(image.contentType || '') + if (!IMAGE_TYPES.has(type) || typeof URL.createObjectURL !== 'function') return { src: '' } + const buffer = await image.readAsArrayBuffer() + const url = URL.createObjectURL(new Blob([buffer], { type })) + assets.push(url) + return { src: url } + }) + : undefined + const arrayBuffer = u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength) + const result = await engine.convertToHtml({ arrayBuffer }, { styleMap: styleMapFor(styles, codeStyles), convertImage }) + const clean = sanitizeDocxHtml(result && result.value) + const { chapters, outline } = splitDocxChapters(clean) + if (chapters.length === 0) throw new Error('empty docx') + return { chapters, outline, assets } +} diff --git a/dsh-reader/src/client/host-layout.js b/dsh-reader/src/client/host-layout.js index 9b39880..4d5d718 100644 --- a/dsh-reader/src/client/host-layout.js +++ b/dsh-reader/src/client/host-layout.js @@ -53,7 +53,8 @@ export function hostAvailableHeight(node, viewportHeight) { if (clips) { const rect = parent.getBoundingClientRect() const padBottom = parseFloat(style.paddingBottom) || 0 - const candidate = rect.bottom - padBottom + const scrollbar = Math.max(0, (parent.offsetHeight || 0) - (parent.clientHeight || 0)) + const candidate = rect.bottom - padBottom - scrollbar if (candidate > 0 && candidate < bottom) bottom = candidate // The nearest scroll container already bounds everything above it. if (overflowY === 'auto' || overflowY === 'scroll' || overflowY === 'overlay') { diff --git a/dsh-reader/src/client/i18n.js b/dsh-reader/src/client/i18n.js index d3494b2..25b8552 100644 --- a/dsh-reader/src/client/i18n.js +++ b/dsh-reader/src/client/i18n.js @@ -1,4 +1,9 @@ const ZH = { + 'error.fileNotFound': '文件不存在', + 'error.permissionDenied': '没有权限读取该文件', + 'error.fileBusy': '文件被其他程序占用,请关闭后重试', + 'label.copied': '已复制', + 'label.copyFailed': '复制失败,请手动选择文本', 'view.label': '阅读', 'library.title': '书库', 'library.empty': '这个目录里还没有可读的文档', @@ -284,6 +289,11 @@ const ZH = { } const EN = { + 'error.fileNotFound': 'File not found', + 'error.permissionDenied': 'Permission denied', + 'error.fileBusy': 'The file is in use. Close it and try again.', + 'label.copied': 'Copied', + 'label.copyFailed': 'Copy failed; select the text manually', 'view.label': 'Reader', 'library.title': 'Library', 'library.empty': 'No readable documents in this folder', diff --git a/dsh-reader/src/client/pdf.js b/dsh-reader/src/client/pdf.js index 71f061a..5ec4fce 100644 --- a/dsh-reader/src/client/pdf.js +++ b/dsh-reader/src/client/pdf.js @@ -40,7 +40,7 @@ export async function pdfOpen(bytes) { export async function pdfRenderPage(pdf, pageNumber, canvas, layer, scale, onTask) { const page = await pdf.doc.getPage(pageNumber) const viewport = page.getViewport({ scale }) - const dpr = Math.min(window.devicePixelRatio || 1, 2) + const dpr = Math.min(window.devicePixelRatio || 1, 3) canvas.width = Math.floor(viewport.width * dpr) canvas.height = Math.floor(viewport.height * dpr) canvas.style.width = viewport.width + 'px' @@ -67,6 +67,7 @@ export async function pdfRenderPage(pdf, pageNumber, canvas, layer, scale, onTas span.style.left = tx[4] + 'px' span.style.top = tx[5] - height + 'px' span.style.fontSize = height + 'px' + span.style.fontFamily = 'Arial, "Microsoft YaHei", sans-serif' layer.appendChild(span) const expected = (item.width || 0) * viewport.scale const actual = span.getBoundingClientRect().width diff --git a/dsh-reader/src/client/relink.js b/dsh-reader/src/client/relink.js index 14e9436..bdb5551 100644 --- a/dsh-reader/src/client/relink.js +++ b/dsh-reader/src/client/relink.js @@ -1,3 +1,5 @@ +import { normalizeRelPath } from './util.js' + /** * Find a stale document entry that shares the current path but has a different * fingerprint and still carries annotations to migrate. @@ -8,7 +10,7 @@ export function staleDocFor(docs, path, key) { for (const [docKey, doc] of Object.entries(docs || {})) { if (docKey === key) continue - if (!doc || doc.path !== path) continue + if (!doc || normalizeRelPath(doc.path) !== normalizeRelPath(path)) continue if (Array.isArray(doc.annotations) && doc.annotations.length > 0) { return { fromKey: docKey, count: doc.annotations.length } } diff --git a/dsh-reader/src/client/shortcuts.js b/dsh-reader/src/client/shortcuts.js index e50e3b5..1fff759 100644 --- a/dsh-reader/src/client/shortcuts.js +++ b/dsh-reader/src/client/shortcuts.js @@ -11,6 +11,7 @@ export function shortcutFor(event, context = {}) { if (modifier && !event.altKey && key.toLowerCase() === 'z') { return event.shiftKey ? 'redo' : 'undo' } + if (modifier && !event.altKey && !event.shiftKey && key.toLowerCase() === 'y') return 'redo' if (modifier && !event.altKey && key.toLowerCase() === 'f') return 'search' if (modifier || event.altKey) return null if (key === 'Home') return 'start' diff --git a/dsh-reader/src/client/styles.js b/dsh-reader/src/client/styles.js index 2d76df1..4c5b004 100644 --- a/dsh-reader/src/client/styles.js +++ b/dsh-reader/src/client/styles.js @@ -1,6 +1,6 @@ export const READER_CSS = ` .rd-root,.rd-root *,.rd-hover-zone *,.rd-note-mask *{box-sizing:border-box} -.rd-root{display:flex;flex-direction:column;height:100%;min-height:0;background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);font-family:ui-sans-serif,system-ui,-apple-system,"PingFang SC","Microsoft YaHei",sans-serif} +.rd-root{display:flex;flex-direction:column;height:100%;min-height:0;background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI","Microsoft YaHei UI","Microsoft YaHei","PingFang SC",sans-serif} .rd-toolbar{display:flex;align-items:center;gap:8px;height:44px;flex:0 0 auto;padding:0 12px;border-bottom:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-base)} .rd-icon-btn{width:30px;min-width:30px;padding:0;display:inline-flex;align-items:center;justify-content:center} .rd-icon-btn svg{display:block;width:18px;height:18px;flex:0 0 auto} @@ -26,7 +26,7 @@ export const READER_CSS = ` .rd-btn.ghost:hover{background:var(--dsw-alias-bg-layer-1)} .rd-btn:disabled{opacity:.45;cursor:default} .rd-body{display:flex;flex:1;min-height:0} -.rd-main{flex:1;min-width:0;overflow:auto;position:relative;scroll-behavior:smooth;overscroll-behavior:contain} +.rd-main{flex:1;min-width:0;overflow:auto;position:relative;scroll-behavior:smooth;overscroll-behavior:contain;scrollbar-gutter:stable} .rd-page{max-width:760px;margin:0 auto;padding:40px 28px 120px;font-size:var(--rd-fs,18px);line-height:var(--rd-lh,1.85)} .rd-prose>h1{font-size:1.7em;line-height:1.3;margin:1.4em 0 .6em;font-weight:700} .rd-prose>h2{font-size:1.4em;line-height:1.35;margin:1.4em 0 .5em;font-weight:650} @@ -35,7 +35,7 @@ export const READER_CSS = ` .rd-prose p{margin:.9em 0} .rd-prose blockquote{margin:1em 0;padding:.2em 0 .2em 1em;border-left:3px solid var(--dsw-alias-border-l2);color:var(--dsw-alias-label-secondary)} .rd-prose pre{margin:1em 0;padding:14px 16px;border-radius:10px;background:var(--dsw-alias-bg-layer-2);overflow:auto;font-size:.86em;line-height:1.6} -.rd-prose code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.9em;background:var(--dsw-alias-bg-layer-2);padding:1px 5px;border-radius:5px} +.rd-prose code{font-family:ui-monospace,SFMono-Regular,Menlo,"Cascadia Mono",Consolas,monospace;font-size:.9em;background:var(--dsw-alias-bg-layer-2);padding:1px 5px;border-radius:5px} .rd-prose pre code{background:transparent;padding:0;border-radius:0} .rd-prose ul,.rd-prose ol{margin:.8em 0;padding-left:1.4em} .rd-prose li{margin:.3em 0} diff --git a/dsh-reader/src/client/text-decode.js b/dsh-reader/src/client/text-decode.js new file mode 100644 index 0000000..e7c6847 --- /dev/null +++ b/dsh-reader/src/client/text-decode.js @@ -0,0 +1,35 @@ +/** + * Decode a text file the way Windows users actually save them: UTF-8 (with or + * without BOM), UTF-16 with BOM, and the GBK/GB18030 family used by older + * Chinese editors. Falls back to UTF-8 replacement characters when nothing + * matches, so opening never blocks on encoding. + * @param {ArrayBuffer|Uint8Array} bytes file bytes + */ +export function decodeText(bytes) { + const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes) + if (u8.length >= 3 && u8[0] === 0xef && u8[1] === 0xbb && u8[2] === 0xbf) { + return new TextDecoder('utf-8').decode(u8.subarray(3)) + } + if (u8.length >= 2 && u8[0] === 0xff && u8[1] === 0xfe) { + return new TextDecoder('utf-16le').decode(u8.subarray(2)) + } + if (u8.length >= 2 && u8[0] === 0xfe && u8[1] === 0xff) { + return new TextDecoder('utf-16be').decode(u8.subarray(2)) + } + // BOM-less UTF-16: ASCII-heavy text has a NUL in every other byte. + if (u8.length >= 4 && u8[1] === 0 && u8[3] === 0 && u8[0] !== 0) { + return new TextDecoder('utf-16le').decode(u8) + } + if (u8.length >= 4 && u8[0] === 0 && u8[2] === 0 && u8[1] !== 0) { + return new TextDecoder('utf-16be').decode(u8) + } + try { + return new TextDecoder('utf-8', { fatal: true }).decode(u8) + } catch { + try { + return new TextDecoder('gb18030').decode(u8) + } catch { + return new TextDecoder('utf-8').decode(u8) + } + } +} diff --git a/dsh-reader/src/client/translate.js b/dsh-reader/src/client/translate.js index 38aa395..90e5f1d 100644 --- a/dsh-reader/src/client/translate.js +++ b/dsh-reader/src/client/translate.js @@ -9,7 +9,7 @@ export { normalizeBlockText, blockHash } export function buildTranslatedHtml(html, resolve) { const container = document.createElement('div') container.innerHTML = String(html || '') - for (const node of container.querySelectorAll('p, li, blockquote, h2, h3, h4, td, pre')) { + for (const node of container.querySelectorAll('p, li, blockquote, h2, h3, h4, pre')) { if (node.closest('.rd-card, .rd-trans')) continue const text = normalizeBlockText(node.textContent) if (!text) continue diff --git a/dsh-reader/src/client/util.js b/dsh-reader/src/client/util.js index ee62353..b893f72 100644 --- a/dsh-reader/src/client/util.js +++ b/dsh-reader/src/client/util.js @@ -11,13 +11,22 @@ export function extOf(name) { return m ? '.' + m[1].toLowerCase() : '' } +/** + * Normalize a workspace-relative path to POSIX separators. Windows hosts can + * hand over `sub\\book.md`; every client-side path consumer expects `/`. + * @param {string} value + */ +export function normalizeRelPath(value) { + return String(value || '').replace(/\\/g, '/') +} + export function basename(file) { - const parts = String(file || '').split('/') + const parts = normalizeRelPath(file).split('/') return parts[parts.length - 1] || file } export function dirname(file) { - const parts = String(file || '').split('/') + const parts = normalizeRelPath(file).split('/') parts.pop() return parts.join('/') || '.' } @@ -26,7 +35,7 @@ export function normalizeTerm(value) { return String(value || '').trim().toLowerCase() } -export const READABLE = new Set(['.md', '.markdown', '.txt', '.epub', '.pdf']) +export const READABLE = new Set(['.md', '.markdown', '.txt', '.epub', '.pdf', '.docx']) export function debounce(fn, wait) { let timer = null @@ -35,3 +44,18 @@ export function debounce(fn, wait) { timer = setTimeout(() => fn(...args), wait) } } + +/** + * Modifier key shown in help text for the current platform. + * @returns {string} `⌘` on Apple platforms, `Ctrl` elsewhere + */ +export function modifierLabel() { + const platform = + (typeof navigator !== 'undefined' && (navigator.userAgentData?.platform || navigator.platform)) || '' + return /Mac|iPhone|iPad|iPod/i.test(platform) ? '⌘' : 'Ctrl' +} + +/** Undo/redo hint that matches the platform modifier. */ +export function undoLabel() { + return modifierLabel() === '⌘' ? '⌘Z / ⌘⇧Z' : 'Ctrl+Z / Ctrl+Shift+Z' +} diff --git a/dsh-reader/test/atomic-write.test.mjs b/dsh-reader/test/atomic-write.test.mjs new file mode 100644 index 0000000..d7c5159 --- /dev/null +++ b/dsh-reader/test/atomic-write.test.mjs @@ -0,0 +1,79 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' +import { replaceFile, writeFileAtomic } from '../lib/atomic-write.js' + +async function tempDir() { + return fs.mkdtemp(path.join(os.tmpdir(), 'reader-atomic-')) +} + +test('writeFileAtomic replaces the destination', async () => { + const dir = await tempDir() + try { + const file = path.join(dir, 'store.json') + await fs.writeFile(file, 'old') + await writeFileAtomic(file, 'new') + assert.equal(await fs.readFile(file, 'utf8'), 'new') + const leftovers = (await fs.readdir(dir)).filter((name) => name.includes('.tmp-')) + assert.deepEqual(leftovers, []) + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } +}) + +test('replaceFile retries a transient rename lock', async () => { + const dir = await tempDir() + const file = path.join(dir, 'store.json') + const tmp = path.join(dir, 'store.tmp') + try { + await fs.writeFile(file, 'old') + await fs.writeFile(tmp, 'new') + const original = fs.rename + let calls = 0 + fs.rename = async (from, to) => { + calls += 1 + if (calls < 3) { + const error = new Error('locked') + error.code = 'EBUSY' + throw error + } + return original.call(fs, from, to) + } + try { + await replaceFile(tmp, file) + } finally { + fs.rename = original + } + assert.equal(calls, 3) + assert.equal(await fs.readFile(file, 'utf8'), 'new') + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } +}) + +test('replaceFile falls back to copying when rename never succeeds', async () => { + const dir = await tempDir() + const file = path.join(dir, 'store.json') + const tmp = path.join(dir, 'store.tmp') + try { + await fs.writeFile(file, 'old') + await fs.writeFile(tmp, 'new') + const original = fs.rename + fs.rename = async () => { + const error = new Error('locked') + error.code = 'EPERM' + throw error + } + try { + await replaceFile(tmp, file) + } finally { + fs.rename = original + } + assert.equal(await fs.readFile(file, 'utf8'), 'new') + await assert.rejects(fs.stat(tmp)) + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } +}) diff --git a/dsh-reader/test/chat-context.test.mjs b/dsh-reader/test/chat-context.test.mjs index f089a86..173762b 100644 --- a/dsh-reader/test/chat-context.test.mjs +++ b/dsh-reader/test/chat-context.test.mjs @@ -31,6 +31,32 @@ test('currentPosition 输出 EPUB 章节与百分比', () => { assert.equal(position.total, 0) }) +test('currentPosition 输出 docx 章节且不带页码', () => { + const doc = { + name: '报告.docx', + ext: '.docx', + path: '报告.docx', + docx: { chapters: [{ label: '第一章' }, { label: '第二章' }] }, + } + const position = currentPosition(doc, { chapter: 1, percent: 60 }) + assert.equal(position.chapter, 1) + assert.equal(position.chapterTitle, '第二章') + assert.equal(position.page, 0) + assert.equal(position.percent, 60) +}) + +test('buildContextWindow 读取 docx 当前章节', async () => { + const doc = { + name: '报告.docx', + ext: '.docx', + path: '报告.docx', + docx: { chapters: [{ label: '第一章', html: '

第一章

正文内容

' }] }, + } + const window = await buildContextWindow(doc, { chapter: 0 }) + assert.match(window.title, /第一章/) + assert.match(window.text, /正文内容/) +}) + test('currentPosition 缺字段兜底并夹取百分比', () => { assert.equal(currentPosition(null), null) const plain = currentPosition({ name: '书.md', ext: '.md' }, {}) diff --git a/dsh-reader/test/docx-mammoth.test.mjs b/dsh-reader/test/docx-mammoth.test.mjs new file mode 100644 index 0000000..feb1da6 --- /dev/null +++ b/dsh-reader/test/docx-mammoth.test.mjs @@ -0,0 +1,91 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import vm from 'node:vm' +import { JSDOM } from 'jsdom' + +const dom = new JSDOM('') +globalThis.document = dom.window.document +globalThis.DOMParser = dom.window.DOMParser +globalThis.window = globalThis +vm.runInThisContext(fs.readFileSync(new URL('../assets/mammoth.browser.min.js', import.meta.url), 'utf8')) +const mammoth = globalThis.mammoth +const { docxOpen } = await import('../src/client/docx.js') + +function zipBytes(entries) { + const enc = new TextEncoder() + const locals = [] + const centrals = [] + let offset = 0 + for (const [name, text] of entries) { + const nameBytes = enc.encode(name) + const data = enc.encode(text) + const local = new Uint8Array(30 + nameBytes.length + data.length) + const lv = new DataView(local.buffer) + lv.setUint32(0, 0x04034b50, true) + lv.setUint16(4, 20, true) + lv.setUint32(18, data.length, true) + lv.setUint32(22, data.length, true) + lv.setUint16(26, nameBytes.length, true) + local.set(nameBytes, 30) + local.set(data, 30 + nameBytes.length) + locals.push(local) + + const central = new Uint8Array(46 + nameBytes.length) + const cv = new DataView(central.buffer) + cv.setUint32(0, 0x02014b50, true) + cv.setUint16(4, 20, true) + cv.setUint16(6, 20, true) + cv.setUint32(20, data.length, true) + cv.setUint32(24, data.length, true) + cv.setUint16(28, nameBytes.length, true) + cv.setUint32(42, offset, true) + central.set(nameBytes, 46) + centrals.push(central) + offset += local.length + } + const cdOffset = offset + const cdSize = centrals.reduce((sum, part) => sum + part.length, 0) + const eocd = new Uint8Array(22) + const ev = new DataView(eocd.buffer) + ev.setUint32(0, 0x06054b50, true) + ev.setUint16(8, entries.length, true) + ev.setUint16(10, entries.length, true) + ev.setUint32(12, cdSize, true) + ev.setUint32(16, cdOffset, true) + const out = new Uint8Array(offset + cdSize + eocd.length) + let at = 0 + for (const part of locals) { + out.set(part, at) + at += part.length + } + for (const part of centrals) { + out.set(part, at) + at += part.length + } + out.set(eocd, at) + return out +} + +const CONTENT_TYPES = + '' +const RELS = + '' +const DOC = + '第一章 引言这是正文。' +const STYLES = + '' + +test('converts a real docx through mammoth with outlineLvl headings', async () => { + const docx = zipBytes([ + ['[Content_Types].xml', CONTENT_TYPES], + ['_rels/.rels', RELS], + ['word/document.xml', DOC], + ['word/styles.xml', STYLES], + ]) + const result = await docxOpen(docx, { mammoth }) + assert.equal(result.chapters.length, 1) + assert.equal(result.chapters[0].label, '第一章 引言') + assert.match(result.chapters[0].html, /

第一章 引言<\/h1>/) + assert.match(result.chapters[0].html, /这是正文。/) +}) diff --git a/dsh-reader/test/docx.test.mjs b/dsh-reader/test/docx.test.mjs new file mode 100644 index 0000000..caddedb --- /dev/null +++ b/dsh-reader/test/docx.test.mjs @@ -0,0 +1,145 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { JSDOM } from 'jsdom' + +const dom = new JSDOM('') +globalThis.document = dom.window.document +globalThis.DOMParser = dom.window.DOMParser + +const { parseStyleOutline, parseCodeStyles, styleMapFor, sanitizeDocxHtml, splitDocxChapters, docxOpen } = await import('../src/client/docx.js') + +function zipBytes(entries) { + const enc = new TextEncoder() + const locals = [] + const centrals = [] + let offset = 0 + for (const [name, text] of entries) { + const nameBytes = enc.encode(name) + const data = enc.encode(text) + const local = new Uint8Array(30 + nameBytes.length + data.length) + const lv = new DataView(local.buffer) + lv.setUint32(0, 0x04034b50, true) + lv.setUint16(4, 20, true) + lv.setUint32(18, data.length, true) + lv.setUint32(22, data.length, true) + lv.setUint16(26, nameBytes.length, true) + local.set(nameBytes, 30) + local.set(data, 30 + nameBytes.length) + locals.push(local) + + const central = new Uint8Array(46 + nameBytes.length) + const cv = new DataView(central.buffer) + cv.setUint32(0, 0x02014b50, true) + cv.setUint16(4, 20, true) + cv.setUint16(6, 20, true) + cv.setUint32(20, data.length, true) + cv.setUint32(24, data.length, true) + cv.setUint16(28, nameBytes.length, true) + cv.setUint32(42, offset, true) + central.set(nameBytes, 46) + centrals.push(central) + offset += local.length + } + const cdOffset = offset + const cdSize = centrals.reduce((sum, part) => sum + part.length, 0) + const eocd = new Uint8Array(22) + const ev = new DataView(eocd.buffer) + ev.setUint32(0, 0x06054b50, true) + ev.setUint16(8, entries.length, true) + ev.setUint16(10, entries.length, true) + ev.setUint32(12, cdSize, true) + ev.setUint32(16, cdOffset, true) + const out = new Uint8Array(offset + cdSize + eocd.length) + let at = 0 + for (const part of locals) { + out.set(part, at) + at += part.length + } + for (const part of centrals) { + out.set(part, at) + at += part.length + } + out.set(eocd, at) + return out +} + +const STYLES = ` + + + + +` + +test('reads heading levels from names and outlineLvl', () => { + const styles = parseStyleOutline(STYLES) + assert.deepEqual(styles, [ + { styleId: '2', name: '标题 1', level: 1 }, + { styleId: 'Heading2', name: 'heading 2', level: 2 }, + ]) + assert.deepEqual(styleMapFor(styles), ["p[style-name='标题 1'] => h1", "p[style-name='heading 2'] => h2"]) +}) + +test('maps code styles to pre without touching headings', () => { + const styles = `` + assert.deepEqual(parseCodeStyles(styles), ['HTML Preformatted']) + assert.deepEqual(styleMapFor([], parseCodeStyles(styles)), ["p[style-name='HTML Preformatted'] => pre"]) +}) + +test('sanitizes scripts and unsafe urls', () => { + const clean = sanitizeDocxHtml( + '

hi badok

', + ) + assert.doesNotMatch(clean, /script|onclick|javascript:/) + assert.match(clean, /https:\/\/e\.com/) +}) + +test('splits h1 chapters, wraps tables and drops TOC leaders', () => { + const { chapters, outline } = splitDocxChapters( + '

前言

第一章

a

1 引言............3

1.1

x

第二章

b

', + ) + assert.equal(chapters.length, 3) + assert.equal(chapters[0].label, '正文') + assert.equal(chapters[1].label, '第一章') + assert.match(chapters[1].html, /rd-table-wrap/) + assert.doesNotMatch(chapters[1].html, /\.\.\./) + assert.deepEqual(outline.map((item) => item.level), [1, 2, 1]) +}) + +test('accepts an ArrayBuffer like the host fetch returns', async () => { + const docx = zipBytes([ + ['word/document.xml', ''], + ['word/styles.xml', STYLES], + ]) + const engine = { convertToHtml: async () => ({ value: '

第一章

正文

' }) } + const result = await docxOpen(docx.buffer, { mammoth: engine }) + assert.equal(result.chapters.length, 1) + assert.equal(result.chapters[0].label, '第一章') +}) + +test('rejects a zip without word/document.xml', async () => { + const docx = zipBytes([['word/styles.xml', STYLES]]) + const engine = { convertToHtml: async () => ({ value: '

x

' }) } + await assert.rejects(docxOpen(docx, { mammoth: engine }), /word\/document.xml/) +}) + +test('opens a docx through an injected mammoth engine', async () => { + const docx = zipBytes([ + [ + 'word/document.xml', + 'hi', + ], + ['word/styles.xml', STYLES], + ]) + let received = null + const engine = { + convertToHtml: async ({ arrayBuffer }, options) => { + received = options + assert.ok(arrayBuffer.byteLength > 0) + return { value: '

intro

第一章

正文

' } + }, + } + const result = await docxOpen(docx, { mammoth: engine }) + assert.equal(result.chapters.length, 2) + assert.equal(result.chapters[1].label, '第一章') + assert.equal(received.styleMap.length, 2) +}) diff --git a/dsh-reader/test/encoding.test.mjs b/dsh-reader/test/encoding.test.mjs new file mode 100644 index 0000000..c8103ad --- /dev/null +++ b/dsh-reader/test/encoding.test.mjs @@ -0,0 +1,27 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { decodeText } from '../src/client/text-decode.js' + +test('decodes UTF-8 with and without BOM', () => { + const text = new TextEncoder().encode('你好,世界') + assert.equal(decodeText(text), '你好,世界') + const bom = new Uint8Array([0xef, 0xbb, 0xbf, ...text]) + assert.equal(decodeText(bom), '你好,世界') +}) + +test('decodes UTF-16LE and UTF-16BE with BOM', () => { + const le = new Uint8Array([0xff, 0xfe, 0x2d, 0x4e, 0x87, 0x65]) + const be = new Uint8Array([0xfe, 0xff, 0x4e, 0x2d, 0x65, 0x87]) + assert.equal(decodeText(le), '中文') + assert.equal(decodeText(be), '中文') +}) + +test('falls back to GB18030 for legacy Chinese text', () => { + const gbk = new Uint8Array([0xd6, 0xd0, 0xce, 0xc4]) + assert.equal(decodeText(gbk), '中文') +}) + +test('accepts an ArrayBuffer', () => { + const bytes = new TextEncoder().encode('plain') + assert.equal(decodeText(bytes.buffer), 'plain') +}) diff --git a/dsh-reader/test/host.test.mjs b/dsh-reader/test/host.test.mjs index c207655..52c5411 100644 --- a/dsh-reader/test/host.test.mjs +++ b/dsh-reader/test/host.test.mjs @@ -233,10 +233,52 @@ test('does not serve html as html', async (t) => { }) test('rejects a symlink that escapes the workspace', async (t) => { + if (process.platform === 'win32') { + t.skip('creating symlinks needs Developer Mode or elevation on Windows') + return + } const { cwd, call } = await setup(t) - await fs.symlink('/etc/hosts', path.join(cwd, 'leak.md')) - const res = await call('/dsh-reader-live/api/file?sessionId=s1&path=leak.md') - assert.equal(res.status, 403) + const outside = path.join(os.tmpdir(), `reader-outside-${process.pid}-${Date.now()}.md`) + await fs.writeFile(outside, 'secret') + try { + await fs.symlink(outside, path.join(cwd, 'leak.md')) + const res = await call('/dsh-reader-live/api/file?sessionId=s1&path=leak.md') + assert.equal(res.status, 403) + } finally { + await fs.rm(outside, { force: true }) + } +}) + +test('lists POSIX paths and hides Windows junk files', async (t) => { + const { cwd, call } = await setup(t) + for (const name of ['~$draft.md', 'desktop.ini', 'Thumbs.db']) { + await fs.writeFile(path.join(cwd, name), 'junk') + } + await fs.writeFile(path.join(cwd, 'sub', 'note.md'), '# note') + await fs.writeFile(path.join(cwd, '第2章.md'), '# 2') + await fs.writeFile(path.join(cwd, '第10章.md'), '# 10') + const res = await call('/dsh-reader-live/api/list?sessionId=s1&dir=.') + const body = await res.json() + const names = body.entries.map((entry) => entry.name) + for (const hidden of ['~$draft.md', 'desktop.ini', 'Thumbs.db']) { + assert.ok(!names.includes(hidden), `${hidden} must not be listed`) + } + assert.equal(body.entries.find((entry) => entry.name === 'sub').path, 'sub') + const ordered = names.filter((name) => name.startsWith('第')) + assert.deepEqual(ordered, ['第2章.md', '第10章.md']) + const nested = await call('/dsh-reader-live/api/list?sessionId=s1&dir=sub') + const nestedBody = await nested.json() + assert.equal(nestedBody.dir, 'sub') + assert.equal(nestedBody.entries[0].path, 'sub/note.md') +}) + +test('reports a missing file without leaking the workspace path', async (t) => { + const { cwd, call } = await setup(t) + const res = await call('/dsh-reader-live/api/file?sessionId=s1&path=missing.md') + assert.equal(res.status, 404) + const body = await res.json() + assert.equal(body.error, 'file not found') + assert.ok(!JSON.stringify(body).includes(cwd), 'response must not contain the absolute workspace path') }) test('explains a new concept once and reuses it afterwards', async (t) => { diff --git a/dsh-reader/test/paths.test.mjs b/dsh-reader/test/paths.test.mjs index 2e70b83..bb536a5 100644 --- a/dsh-reader/test/paths.test.mjs +++ b/dsh-reader/test/paths.test.mjs @@ -1,39 +1,56 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { resolveInWorkspace } from '../lib/paths.js' +import os from 'node:os' +import path from 'node:path' +import { isInside, resolveInWorkspace, toPosix } from '../lib/paths.js' + +const root = path.join(os.tmpdir(), 'reader-ws') test('accepts a nested relative path', () => { - const r = resolveInWorkspace('/w', 'book/ch1.md') + const r = resolveInWorkspace(root, 'book/ch1.md') assert.equal(r.ok, true) - assert.equal(r.abs, '/w/book/ch1.md') + assert.equal(r.abs, path.join(root, 'book', 'ch1.md')) }) test('rejects parent traversal', () => { - const r = resolveInWorkspace('/w', '../secret.txt') + const r = resolveInWorkspace(root, '../secret.txt') assert.equal(r.ok, false) assert.equal(r.code, 'ESCAPE') }) test('rejects traversal hidden mid-path', () => { - const r = resolveInWorkspace('/w', 'book/../../secret.txt') + const r = resolveInWorkspace(root, 'book/../../secret.txt') assert.equal(r.ok, false) assert.equal(r.code, 'ESCAPE') }) test('rejects absolute paths', () => { - const r = resolveInWorkspace('/w', '/etc/passwd') + const r = resolveInWorkspace(root, path.resolve(root, '..', 'etc', 'passwd')) assert.equal(r.ok, false) assert.equal(r.code, 'ABSOLUTE') }) test('rejects a sibling directory sharing the prefix', () => { - const r = resolveInWorkspace('/w', '../w2/x.md') + const r = resolveInWorkspace(root, '../reader-ws2/x.md') assert.equal(r.ok, false) assert.equal(r.code, 'ESCAPE') }) test('accepts the workspace root itself', () => { - const r = resolveInWorkspace('/w', '.') + const r = resolveInWorkspace(root, '.') assert.equal(r.ok, true) - assert.equal(r.abs, '/w') + assert.equal(r.abs, root) +}) + +test('normalizes win32 separators for the wire format', () => { + assert.equal(toPosix('sub\\book.md'), 'sub/book.md') + assert.equal(toPosix('sub/book.md'), 'sub/book.md') + assert.equal(toPosix(''), '') +}) + +test('contains the root and its descendants only', () => { + assert.equal(isInside(root, root), true) + assert.equal(isInside(root, path.join(root, 'book', 'ch1.md')), true) + assert.equal(isInside(root, path.join(root, '..', 'outside.md')), false) + assert.equal(isInside(root, `${root}2`), false) }) diff --git a/dsh-reader/test/shortcuts.test.mjs b/dsh-reader/test/shortcuts.test.mjs index 5a8b9db..dfcd5a5 100644 --- a/dsh-reader/test/shortcuts.test.mjs +++ b/dsh-reader/test/shortcuts.test.mjs @@ -31,6 +31,8 @@ test('maps undo and redo with the platform modifier', () => { assert.equal(shortcutFor(key('z', { metaKey: true })), 'undo') assert.equal(shortcutFor(key('Z', { ctrlKey: true })), 'undo') assert.equal(shortcutFor(key('z', { metaKey: true, shiftKey: true })), 'redo') + assert.equal(shortcutFor(key('y', { ctrlKey: true })), 'redo') + assert.equal(shortcutFor(key('Y', { ctrlKey: true })), 'redo') }) test('maps command-f to search', () => { diff --git a/dsh-reader/test/translate.test.mjs b/dsh-reader/test/translate.test.mjs index 39c8d0c..50c4504 100644 --- a/dsh-reader/test/translate.test.mjs +++ b/dsh-reader/test/translate.test.mjs @@ -20,6 +20,13 @@ test('builds a translation-only html keeping untranslated blocks', () => { assert.match(output, /标题/) }) +test('keeps table cells untranslated', () => { + const html = '

hello

cell
' + const output = buildTranslatedHtml(html, () => '译文') + assert.match(output, /

译文<\/p>/) + assert.match(output, /cell<\/td>/) +}) + test('translate prompt asks for an id-keyed json map', () => { const { system, user } = buildTranslatePrompt({ target: 'en', diff --git a/dsh-reader/test/windows.test.mjs b/dsh-reader/test/windows.test.mjs new file mode 100644 index 0000000..022a9ad --- /dev/null +++ b/dsh-reader/test/windows.test.mjs @@ -0,0 +1,49 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' +import { toPosix } from '../lib/paths.js' +import { emptyStore, readStore, upsertDoc } from '../lib/store.js' +import { normalizeRelPath, basename, dirname } from '../src/client/util.js' +import { staleDocFor } from '../src/client/relink.js' + +test('Host and client normalize win32 separators', () => { + assert.equal(toPosix('sub\\book.md'), 'sub/book.md') + assert.equal(normalizeRelPath('sub\\book.md'), 'sub/book.md') + assert.equal(normalizeRelPath('C:\\ws\\book.md'), 'C:/ws/book.md') + assert.equal(normalizeRelPath('./a\\b/../c.md'), './a/b/../c.md') + assert.equal(normalizeRelPath(''), '') +}) + +test('basename and dirname accept backslashes', () => { + assert.equal(basename('sub\\book.md'), 'book.md') + assert.equal(dirname('sub\\book.md'), 'sub') + assert.equal(dirname('book.md'), '.') + assert.equal(basename('sub/deeper\\book.md'), 'book.md') +}) + +test('upsertDoc stores a POSIX path', () => { + const store = emptyStore() + upsertDoc(store, { docKey: 'fp', path: 'sub\\book.md' }) + assert.equal(store.docs.fp.path, 'sub/book.md') +}) + +test('reading a legacy store normalizes windows separators', async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'reader-paths-')) + try { + const store = emptyStore() + store.docs.k = { path: 'sub\\book.md', annotations: [], positions: {} } + await fs.mkdir(path.join(dir, '.dsh-reader'), { recursive: true }) + await fs.writeFile(path.join(dir, '.dsh-reader', 'store.json'), JSON.stringify(store)) + const read = await readStore(dir) + assert.equal(read.docs.k.path, 'sub/book.md') + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } +}) + +test('relink matches both spellings of the same path', () => { + const docs = { old: { path: 'sub\\book.md', annotations: [{ id: '1' }] } } + assert.deepEqual(staleDocFor(docs, 'sub/book.md', 'new'), { fromKey: 'old', count: 1 }) +}) diff --git a/plugin-market.json b/plugin-market.json index bf4dc8e..9c89fe9 100644 --- a/plugin-market.json +++ b/plugin-market.json @@ -72,6 +72,16 @@ "sortKeys": {} }, "versions": [ + { + "version": "0.15.0", + "publishTimestamp": 1795524192, + "source": { + "type": "npm" + }, + "engines": { + "dsh": ">=0.2.2-rc.5 <0.3.0-0" + } + }, { "version": "0.14.0", "publishTimestamp": 1795516031,