@file-viewer/renderer-email 2.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,160 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and configuration
27
+ files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object code,
31
+ generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form,
34
+ made available under the License, as indicated by a copyright notice that is
35
+ included in or attached to the work.
36
+
37
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
38
+ is based on (or derived from) the Work and for which the editorial revisions,
39
+ annotations, elaborations, or other modifications represent, as a whole, an
40
+ original work of authorship. For the purposes of this License, Derivative Works
41
+ shall not include works that remain separable from, or merely link (or bind by
42
+ name) to the interfaces of, the Work and Derivative Works thereof.
43
+
44
+ "Contribution" shall mean any work of authorship, including the original version
45
+ of the Work and any modifications or additions to that Work or Derivative Works
46
+ thereof, that is intentionally submitted to Licensor for inclusion in the Work by
47
+ the copyright owner or by an individual or Legal Entity authorized to submit on
48
+ behalf of the copyright owner. For the purposes of this definition, "submitted"
49
+ means any form of electronic, verbal, or written communication sent to the
50
+ Licensor or its representatives, including but not limited to communication on
51
+ electronic mailing lists, source code control systems, and issue tracking systems
52
+ that are managed by, or on behalf of, the Licensor for the purpose of discussing
53
+ and improving the Work, but excluding communication that is conspicuously marked
54
+ or otherwise designated in writing by the copyright owner as "Not a
55
+ Contribution."
56
+
57
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58
+ of whom a Contribution has been received by Licensor and subsequently
59
+ incorporated within the Work.
60
+
61
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
62
+ License, each Contributor hereby grants to You a perpetual, worldwide,
63
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
64
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
65
+ sublicense, and distribute the Work and such Derivative Works in Source or
66
+ Object form.
67
+
68
+ 3. Grant of Patent License. Subject to the terms and conditions of this License,
69
+ each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
70
+ no-charge, royalty-free, irrevocable (except as stated in this section) patent
71
+ license to make, have made, use, offer to sell, sell, import, and otherwise
72
+ transfer the Work, where such license applies only to those patent claims
73
+ licensable by such Contributor that are necessarily infringed by their
74
+ Contribution(s) alone or by combination of their Contribution(s) with the Work to
75
+ which such Contribution(s) was submitted. If You institute patent litigation
76
+ against any entity (including a cross-claim or counterclaim in a lawsuit)
77
+ alleging that the Work or a Contribution incorporated within the Work
78
+ constitutes direct or contributory patent infringement, then any patent licenses
79
+ granted to You under this License for that Work shall terminate as of the date
80
+ such litigation is filed.
81
+
82
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
83
+ Derivative Works thereof in any medium, with or without modifications, and in
84
+ Source or Object form, provided that You meet the following conditions:
85
+
86
+ (a) You must give any other recipients of the Work or Derivative Works a copy of
87
+ this License; and
88
+
89
+ (b) You must cause any modified files to carry prominent notices stating that
90
+ You changed the files; and
91
+
92
+ (c) You must retain, in the Source form of any Derivative Works that You
93
+ distribute, all copyright, patent, trademark, and attribution notices from the
94
+ Source form of the Work, excluding those notices that do not pertain to any part
95
+ of the Derivative Works; and
96
+
97
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then
98
+ any Derivative Works that You distribute must include a readable copy of the
99
+ attribution notices contained within such NOTICE file, excluding those notices
100
+ that do not pertain to any part of the Derivative Works, in at least one of the
101
+ following places: within a NOTICE text file distributed as part of the Derivative
102
+ Works; within the Source form or documentation, if provided along with the
103
+ Derivative Works; or, within a display generated by the Derivative Works, if and
104
+ wherever such third-party notices normally appear. The contents of the NOTICE
105
+ file are for informational purposes only and do not modify the License. You may
106
+ add Your own attribution notices within Derivative Works that You distribute,
107
+ alongside or as an addendum to the NOTICE text from the Work, provided that such
108
+ additional attribution notices cannot be construed as modifying the License.
109
+
110
+ You may add Your own copyright statement to Your modifications and may provide
111
+ additional or different license terms and conditions for use, reproduction, or
112
+ distribution of Your modifications, or for any such Derivative Works as a whole,
113
+ provided Your use, reproduction, and distribution of the Work otherwise complies
114
+ with the conditions stated in this License.
115
+
116
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
117
+ Contribution intentionally submitted for inclusion in the Work by You to the
118
+ Licensor shall be under the terms and conditions of this License, without any
119
+ additional terms or conditions. Notwithstanding the above, nothing herein shall
120
+ supersede or modify the terms of any separate license agreement you may have
121
+ executed with Licensor regarding such Contributions.
122
+
123
+ 6. Trademarks. This License does not grant permission to use the trade names,
124
+ trademarks, service marks, or product names of the Licensor, except as required
125
+ for reasonable and customary use in describing the origin of the Work and
126
+ reproducing the content of the NOTICE file.
127
+
128
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
129
+ writing, Licensor provides the Work (and each Contributor provides its
130
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
131
+ KIND, either express or implied, including, without limitation, any warranties or
132
+ conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
133
+ PARTICULAR PURPOSE. You are solely responsible for determining the
134
+ appropriateness of using or redistributing the Work and assume any risks
135
+ associated with Your exercise of permissions under this License.
136
+
137
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
138
+ tort (including negligence), contract, or otherwise, unless required by
139
+ applicable law (such as deliberate and grossly negligent acts) or agreed to in
140
+ writing, shall any Contributor be liable to You for damages, including any
141
+ direct, indirect, special, incidental, or consequential damages of any character
142
+ arising as a result of this License or out of the use or inability to use the
143
+ Work (including but not limited to damages for loss of goodwill, work stoppage,
144
+ computer failure or malfunction, or any and all other commercial damages or
145
+ losses), even if such Contributor has been advised of the possibility of such
146
+ damages.
147
+
148
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or
149
+ Derivative Works thereof, You may choose to offer, and charge a fee for,
150
+ acceptance of support, warranty, indemnity, or other liability obligations and/or
151
+ rights consistent with this License. However, in accepting such obligations, You
152
+ may act only on Your own behalf and on Your sole responsibility, not on behalf of
153
+ any other Contributor, and only if You agree to indemnify, defend, and hold each
154
+ Contributor harmless for any liability incurred by, or claims asserted against,
155
+ such Contributor by reason of your accepting any such warranty or additional
156
+ liability.
157
+
158
+ END OF TERMS AND CONDITIONS
159
+
160
+ Copyright 2026 Flyfish Viewer
package/README.en.md ADDED
@@ -0,0 +1,40 @@
1
+ # @file-viewer/renderer-email
2
+
3
+ Standalone email renderer package for Flyfish File Viewer. It handles `.eml`, `.msg`, and `.mbox` previews, body/header switching, attachment download, and nested attachment previews.
4
+
5
+ ## Usage
6
+
7
+ ```ts
8
+ import FileViewer from '@file-viewer/vue3'
9
+ import { emailRenderer } from '@file-viewer/renderer-email'
10
+
11
+ const options = {
12
+ builtinRenderers: 'none',
13
+ renderers: emailRenderer,
14
+ }
15
+ ```
16
+
17
+ You can also compose it with other renderers:
18
+
19
+ ```ts
20
+ import { emailRenderer } from '@file-viewer/renderer-email'
21
+ import { pdfRenderer } from '@file-viewer/renderer-pdf'
22
+ import { archiveRenderer } from '@file-viewer/renderer-archive'
23
+
24
+ const options = {
25
+ builtinRenderers: 'none',
26
+ renderers: [pdfRenderer, archiveRenderer, emailRenderer],
27
+ }
28
+ ```
29
+
30
+ ## Capabilities
31
+
32
+ - Parses `.eml` and `.mbox` with `postal-mime`.
33
+ - Parses Outlook `.msg` with `@kenjiuno/msgreader`.
34
+ - Supports HTML body, plain-text body, and raw header switching. HTML email is rendered read-only inside a sandbox iframe.
35
+ - Supports attachment download and nested preview through `renderNestedBuffer` when the host viewer provides it.
36
+ - Does not depend on any online service or public CDN, making it suitable for intranet attachment centers, ticket email archives, and customer communication review.
37
+
38
+ ## Migration Note
39
+
40
+ The core package no longer bundles the email renderer and no longer installs `postal-mime` / `@kenjiuno/msgreader` directly. Install this renderer explicitly, or use `@file-viewer/preset-all`, when email preview is required.
package/README.md ADDED
@@ -0,0 +1,40 @@
1
+ # @file-viewer/renderer-email
2
+
3
+ Flyfish File Viewer 的独立邮件 renderer 包。它负责 `.eml`、`.msg`、`.mbox` 邮件预览、正文/头信息切换、附件下载和附件嵌套预览。
4
+
5
+ ## 用法
6
+
7
+ ```ts
8
+ import FileViewer from '@file-viewer/vue3'
9
+ import { emailRenderer } from '@file-viewer/renderer-email'
10
+
11
+ const options = {
12
+ builtinRenderers: 'none',
13
+ renderers: emailRenderer,
14
+ }
15
+ ```
16
+
17
+ 也可以与其他 renderer 组合:
18
+
19
+ ```ts
20
+ import { emailRenderer } from '@file-viewer/renderer-email'
21
+ import { pdfRenderer } from '@file-viewer/renderer-pdf'
22
+ import { archiveRenderer } from '@file-viewer/renderer-archive'
23
+
24
+ const options = {
25
+ builtinRenderers: 'none',
26
+ renderers: [pdfRenderer, archiveRenderer, emailRenderer],
27
+ }
28
+ ```
29
+
30
+ ## 能力边界
31
+
32
+ - `.eml` 和 `.mbox` 使用 `postal-mime` 解析邮件头、HTML 正文、纯文本正文和附件。
33
+ - `.msg` 使用 `@kenjiuno/msgreader` 解析 Outlook MSG 文件。
34
+ - 支持 HTML / 正文 / 头信息切换,HTML 邮件在 sandbox iframe 中只读展示。
35
+ - 支持附件下载;宿主 viewer 提供 `renderNestedBuffer` 时,附件会继续复用 PDF、Office、图片、代码等现有 renderer。
36
+ - 不绑定任何在线服务或公共 CDN,适合内网附件中心、工单邮件归档和客户来信查看。
37
+
38
+ ## 迁移说明
39
+
40
+ `@file-viewer/core` 已不再内置 email renderer,也不再直接安装 `postal-mime` / `@kenjiuno/msgreader`。需要邮件预览时,请显式安装本包,或直接使用 `@file-viewer/preset-all` 聚合能力。
@@ -0,0 +1,2 @@
1
+ import type { FileRenderContext, FileViewerRenderedInstance } from '@file-viewer/core';
2
+ export default function renderEmail(buffer: ArrayBuffer, target: HTMLDivElement, type?: string, context?: FileRenderContext): Promise<FileViewerRenderedInstance>;
package/dist/email.js ADDED
@@ -0,0 +1,463 @@
1
+ import { disposeFileViewerRendered } from '@file-viewer/core';
2
+ const emailStyle = `
3
+ .email-viewer{position:relative;height:100%;min-height:0;display:flex;flex-direction:column;background:#f3f6f8;color:#172033;box-sizing:border-box}
4
+ .email-viewer *{box-sizing:border-box}
5
+ .email-header{padding:18px 22px;border-bottom:1px solid rgba(23,32,51,.08);background:#fff}
6
+ .email-header>span{color:#1f7a58;font-size:12px;font-weight:900}
7
+ .email-header h2{margin:4px 0 12px;font-size:22px;line-height:1.25}
8
+ .email-meta{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px 18px}
9
+ .email-meta p{margin:0;color:#526275;font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
10
+ .email-meta strong{margin-right:8px;color:#172033}
11
+ .email-body{flex:1;min-height:0;display:grid;grid-template-columns:minmax(240px,300px) minmax(0,1fr)}
12
+ .email-sidebar{min-height:0;display:flex;flex-direction:column;gap:14px;padding:14px;border-right:1px solid rgba(23,32,51,.08);background:rgba(255,255,255,.7)}
13
+ .body-tabs{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px;padding:4px;border-radius:12px;background:rgba(23,32,51,.06)}
14
+ .body-tabs button,.attachment-item,.attachment-preview-head button{font:inherit;cursor:pointer}
15
+ .body-tabs button{height:34px;border:0;border-radius:9px;background:transparent;color:#64748b;font-size:12px;font-weight:800}
16
+ .body-tabs button.active{background:#fff;color:#172033}
17
+ .body-tabs button:disabled{opacity:.4;cursor:not-allowed}
18
+ .attachment-panel{min-height:0;overflow:auto}
19
+ .attachment-title{display:flex;justify-content:space-between;color:#172033;font-size:14px;margin-bottom:8px}
20
+ .attachment-title span{color:#64748b}
21
+ .attachment-empty{margin:8px 0 0;color:#64748b;font-size:12px}
22
+ .attachment-item{width:100%;min-height:62px;display:grid;grid-template-columns:42px minmax(0,1fr);gap:10px;align-items:center;margin-bottom:8px;padding:9px;border:1px solid rgba(23,32,51,.08);border-radius:12px;background:#fff;text-align:left}
23
+ .attachment-item:hover,.attachment-item.active{border-color:rgba(31,122,88,.28);box-shadow:0 10px 22px rgba(23,32,51,.08)}
24
+ .attachment-item span{grid-row:span 2;height:38px;display:inline-flex;align-items:center;justify-content:center;border-radius:10px;background:rgba(31,122,88,.12);color:#1f7a58;font-size:11px;font-weight:900}
25
+ .attachment-item strong,.attachment-item em{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
26
+ .attachment-item em{color:#64748b;font-size:12px;font-style:normal}
27
+ .message-panel{min-width:0;min-height:0;display:grid;grid-template-rows:minmax(240px,46%) minmax(0,1fr)}
28
+ .email-message-content{min-height:0}
29
+ .email-html,.email-text{width:100%;height:100%;border:0;background:#fff}
30
+ .email-text{margin:0;overflow:auto;padding:20px;white-space:pre-wrap;word-break:break-word;line-height:1.65}
31
+ .attachment-preview{min-height:0;display:flex;flex-direction:column;border-top:1px solid rgba(23,32,51,.08)}
32
+ .attachment-preview[hidden]{display:none}
33
+ .attachment-preview-head{min-height:48px;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:8px 14px;background:rgba(255,255,255,.78)}
34
+ .attachment-preview-head button{height:32px;padding:0 12px;border:0;border-radius:9px;background:#1f7a58;color:#fff;font-weight:800}
35
+ .attachment-target{flex:1;min-height:0;overflow:auto}
36
+ .email-attachment-render{width:100%;height:100%;min-height:320px}
37
+ .email-state{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;gap:14px;background:rgba(243,246,248,.86);z-index:2}
38
+ .email-state span{width:34px;height:34px;border-radius:999px;border:3px solid rgba(31,122,88,.16);border-top-color:#1f7a58;animation:email-spin .9s linear infinite}
39
+ .email-error{position:absolute;right:18px;bottom:18px;width:min(460px,calc(100% - 36px));padding:14px;border-radius:14px;background:#fff7e8;color:#8a4b00;box-shadow:0 16px 36px rgba(23,32,51,.14);z-index:3}
40
+ .email-error p{margin:6px 0 0}
41
+ @keyframes email-spin{to{transform:rotate(360deg)}}
42
+ @media (prefers-color-scheme:dark){.file-viewer[data-viewer-theme='system'] .email-viewer{background:#172033;color:#e5eef8}.file-viewer[data-viewer-theme='system'] .email-header,.file-viewer[data-viewer-theme='system'] .attachment-item,.file-viewer[data-viewer-theme='system'] .email-html,.file-viewer[data-viewer-theme='system'] .email-text{background:#fff;color:#172033}}
43
+ .file-viewer[data-viewer-theme='dark'] .email-viewer{background:#172033;color:#e5eef8}
44
+ .file-viewer[data-viewer-theme='dark'] .email-header,.file-viewer[data-viewer-theme='dark'] .attachment-item,.file-viewer[data-viewer-theme='dark'] .email-html,.file-viewer[data-viewer-theme='dark'] .email-text{background:#fff;color:#172033}
45
+ @media (max-width:860px){.email-meta,.email-body{grid-template-columns:1fr}.email-body{grid-template-rows:auto minmax(0,1fr)}.email-sidebar{border-right:0;border-bottom:1px solid rgba(23,32,51,.08)}}
46
+ `;
47
+ const formatBytes = (value) => {
48
+ if (!Number.isFinite(value) || value < 0) {
49
+ return '-';
50
+ }
51
+ if (value < 1024) {
52
+ return `${value} B`;
53
+ }
54
+ const mb = value / 1024 / 1024;
55
+ if (mb >= 1) {
56
+ return `${mb.toFixed(mb < 10 ? 1 : 0)} MB`;
57
+ }
58
+ return `${(value / 1024).toFixed(value < 10 * 1024 ? 1 : 0)} KB`;
59
+ };
60
+ const normalizeAddress = (value) => {
61
+ if (!value) {
62
+ return [];
63
+ }
64
+ const source = Array.isArray(value) ? value : [value];
65
+ return source.flatMap(item => {
66
+ const candidate = item;
67
+ if (candidate.group) {
68
+ return normalizeAddress(candidate.group);
69
+ }
70
+ return [{
71
+ name: candidate.name || '',
72
+ address: candidate.address || candidate.email || '',
73
+ }];
74
+ });
75
+ };
76
+ const addressText = (items) => {
77
+ return items
78
+ .map(item => item.name && item.address ? `${item.name} <${item.address}>` : item.address || item.name || '')
79
+ .filter(Boolean)
80
+ .join(', ');
81
+ };
82
+ const toArrayBuffer = async (value) => {
83
+ if (value instanceof ArrayBuffer) {
84
+ return value;
85
+ }
86
+ if (value instanceof Uint8Array) {
87
+ const copy = new Uint8Array(value.byteLength);
88
+ copy.set(value);
89
+ return copy.buffer;
90
+ }
91
+ return toArrayBuffer(new TextEncoder().encode(value));
92
+ };
93
+ const normalizeContentId = (value) => (value || '').replace(/[<>]/g, '');
94
+ const createPostalAttachments = (email, objectUrls, cidUrls) => {
95
+ const attachments = (email.attachments || []).map((attachment, index) => {
96
+ var _a;
97
+ const size = typeof attachment.content === 'string'
98
+ ? attachment.content.length
99
+ : ((_a = attachment.content) === null || _a === void 0 ? void 0 : _a.byteLength) || 0;
100
+ const name = attachment.filename || `attachment-${index + 1}`;
101
+ return {
102
+ id: `${index}-${name}`,
103
+ name,
104
+ mimeType: attachment.mimeType,
105
+ size,
106
+ contentId: attachment.contentId,
107
+ load: () => toArrayBuffer(attachment.content),
108
+ };
109
+ });
110
+ return Promise.all(attachments.map(async (attachment) => {
111
+ var _a;
112
+ if (!attachment.contentId || !((_a = attachment.mimeType) === null || _a === void 0 ? void 0 : _a.startsWith('image/'))) {
113
+ return;
114
+ }
115
+ const buffer = await attachment.load();
116
+ const url = URL.createObjectURL(new Blob([buffer], { type: attachment.mimeType }));
117
+ objectUrls.push(url);
118
+ cidUrls.set(normalizeContentId(attachment.contentId), url);
119
+ })).then(() => attachments);
120
+ };
121
+ const parseEml = async (buffer, filename, objectUrls, cidUrls) => {
122
+ var _a, _b;
123
+ const PostalMime = (await import('postal-mime')).default;
124
+ const email = await PostalMime.parse(buffer, {
125
+ attachmentEncoding: 'arraybuffer',
126
+ maxNestingDepth: 24,
127
+ maxHeadersSize: 2 * 1024 * 1024,
128
+ });
129
+ const attachments = await createPostalAttachments(email, objectUrls, cidUrls);
130
+ return {
131
+ kind: 'eml',
132
+ subject: email.subject || filename,
133
+ from: normalizeAddress(email.from),
134
+ to: normalizeAddress(email.to),
135
+ cc: normalizeAddress(email.cc),
136
+ date: email.date,
137
+ text: email.text,
138
+ html: email.html,
139
+ headers: ((_a = email.headerLines) === null || _a === void 0 ? void 0 : _a.map((item) => item.line).join('\n'))
140
+ || ((_b = email.headers) === null || _b === void 0 ? void 0 : _b.map((item) => `${item.originalKey}: ${item.value}`).join('\n')),
141
+ attachments,
142
+ };
143
+ };
144
+ const parseMbox = async (buffer, filename, objectUrls, cidUrls) => {
145
+ var _a, _b, _c, _d;
146
+ const source = new TextDecoder('utf-8', { fatal: false }).decode(buffer);
147
+ const starts = [...source.matchAll(/^From .*$\n/gm)].map(match => match.index || 0);
148
+ const firstStart = (_a = starts[0]) !== null && _a !== void 0 ? _a : 0;
149
+ const secondStart = (_b = starts[1]) !== null && _b !== void 0 ? _b : source.length;
150
+ const firstMessage = source.slice(firstStart, secondStart).replace(/^From .*$\n/, '');
151
+ const encoded = new TextEncoder().encode(firstMessage).buffer;
152
+ const PostalMime = (await import('postal-mime')).default;
153
+ const email = await PostalMime.parse(encoded, {
154
+ attachmentEncoding: 'arraybuffer',
155
+ maxNestingDepth: 24,
156
+ maxHeadersSize: 2 * 1024 * 1024,
157
+ });
158
+ const attachments = await createPostalAttachments(email, objectUrls, cidUrls);
159
+ return {
160
+ kind: 'mbox',
161
+ subject: email.subject || `${filename} · 第 1 封`,
162
+ from: normalizeAddress(email.from),
163
+ to: normalizeAddress(email.to),
164
+ cc: normalizeAddress(email.cc),
165
+ date: email.date,
166
+ text: `MBOX 共识别 ${Math.max(1, starts.length)} 封邮件,当前展示第 1 封。\n\n${email.text || ''}`,
167
+ html: email.html,
168
+ headers: ((_c = email.headerLines) === null || _c === void 0 ? void 0 : _c.map((item) => item.line).join('\n'))
169
+ || ((_d = email.headers) === null || _d === void 0 ? void 0 : _d.map((item) => `${item.originalKey}: ${item.value}`).join('\n')),
170
+ attachments,
171
+ };
172
+ };
173
+ const parseMsg = async (buffer, filename) => {
174
+ var _a;
175
+ const msgReaderModule = await import('@kenjiuno/msgreader');
176
+ const MsgReader = (((_a = msgReaderModule.default) === null || _a === void 0 ? void 0 : _a.default) || msgReaderModule.default);
177
+ const reader = new MsgReader(buffer);
178
+ const fileData = reader.getFileData();
179
+ const attachments = (fileData.attachments || []).map((attachment, index) => {
180
+ const name = attachment.fileName || attachment.fileNameShort || attachment.name || `attachment-${index + 1}${attachment.extension || ''}`;
181
+ return {
182
+ id: `${index}-${name}`,
183
+ name,
184
+ mimeType: 'application/octet-stream',
185
+ size: attachment.contentLength || attachment.size || 0,
186
+ contentId: attachment.pidContentId,
187
+ async load() {
188
+ const file = reader.getAttachment(attachment);
189
+ return toArrayBuffer(file.content);
190
+ },
191
+ };
192
+ });
193
+ return {
194
+ kind: 'msg',
195
+ subject: fileData.subject || filename,
196
+ from: normalizeAddress({ name: fileData.senderName, address: fileData.senderEmail }),
197
+ to: normalizeAddress(fileData.recipients || []).filter(item => item.name || item.address),
198
+ cc: [],
199
+ date: fileData.messageDeliveryTime || fileData.clientSubmitTime || fileData.creationTime,
200
+ text: fileData.body,
201
+ html: fileData.html || '',
202
+ headers: fileData.headers,
203
+ attachments,
204
+ };
205
+ };
206
+ const parseEmail = (buffer, type, filename, objectUrls, cidUrls) => {
207
+ if (type === 'msg') {
208
+ return parseMsg(buffer, filename);
209
+ }
210
+ if (type === 'mbox') {
211
+ return parseMbox(buffer, filename, objectUrls, cidUrls);
212
+ }
213
+ return parseEml(buffer, filename, objectUrls, cidUrls);
214
+ };
215
+ const createStyle = () => {
216
+ const style = document.createElement('style');
217
+ style.textContent = emailStyle;
218
+ return style;
219
+ };
220
+ const createElement = (tagName, className, text) => {
221
+ const element = document.createElement(tagName);
222
+ if (className) {
223
+ element.className = className;
224
+ }
225
+ if (text !== undefined) {
226
+ element.textContent = text;
227
+ }
228
+ return element;
229
+ };
230
+ const getAttachmentExtension = (name) => {
231
+ const index = name.lastIndexOf('.');
232
+ return index >= 0 ? name.slice(index + 1).toLowerCase() : 'txt';
233
+ };
234
+ const createHtmlSrcdoc = (html, cidUrls) => {
235
+ let next = html;
236
+ cidUrls.forEach((url, cid) => {
237
+ const escaped = cid.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
238
+ next = next.replace(new RegExp(`cid:${escaped}`, 'gi'), url);
239
+ });
240
+ return `<!doctype html><html><head><meta charset="utf-8"><base target="_blank"><style>body{margin:0;padding:18px;font-family:Aptos,"Segoe UI",sans-serif;line-height:1.6;color:#172033;word-break:break-word;}img{max-width:100%;height:auto;}</style></head><body>${next}</body></html>`;
241
+ };
242
+ const appendMeta = (meta, label, value) => {
243
+ const row = document.createElement('p');
244
+ const strong = document.createElement('strong');
245
+ strong.textContent = label;
246
+ row.append(strong, document.createTextNode(value || '-'));
247
+ meta.append(row);
248
+ };
249
+ export default async function renderEmail(buffer, target, type = 'eml', context) {
250
+ const normalizedType = type === 'msg' ? 'msg' : type === 'mbox' ? 'mbox' : 'eml';
251
+ const filename = (context === null || context === void 0 ? void 0 : context.filename) || `message.${normalizedType}`;
252
+ const objectUrls = [];
253
+ const cidUrls = new Map();
254
+ const cleanups = [];
255
+ let nestedRendered;
256
+ let overlay = null;
257
+ let errorElement = null;
258
+ const root = createElement('section', 'email-viewer');
259
+ const style = createStyle();
260
+ target.replaceChildren(style, root);
261
+ const listen = (element, event, listener) => {
262
+ element.addEventListener(event, listener);
263
+ cleanups.push(() => element.removeEventListener(event, listener));
264
+ };
265
+ const showLoading = (text) => {
266
+ if (!overlay) {
267
+ overlay = createElement('div', 'email-state');
268
+ overlay.append(createElement('span'), createElement('strong', undefined, text));
269
+ root.append(overlay);
270
+ return;
271
+ }
272
+ const label = overlay.querySelector('strong');
273
+ if (label) {
274
+ label.textContent = text;
275
+ }
276
+ };
277
+ const hideLoading = () => {
278
+ overlay === null || overlay === void 0 ? void 0 : overlay.remove();
279
+ overlay = null;
280
+ };
281
+ const showError = (message) => {
282
+ errorElement === null || errorElement === void 0 ? void 0 : errorElement.remove();
283
+ errorElement = createElement('div', 'email-error');
284
+ errorElement.append(createElement('strong', undefined, '邮件预览提示'));
285
+ errorElement.append(createElement('p', undefined, message));
286
+ root.append(errorElement);
287
+ };
288
+ const clearAttachmentPreview = async () => {
289
+ await disposeFileViewerRendered(nestedRendered);
290
+ nestedRendered = undefined;
291
+ };
292
+ const downloadAttachment = async (attachment) => {
293
+ const attachmentBuffer = await attachment.load();
294
+ const url = URL.createObjectURL(new Blob([attachmentBuffer], { type: attachment.mimeType || 'application/octet-stream' }));
295
+ objectUrls.push(url);
296
+ const link = document.createElement('a');
297
+ link.href = url;
298
+ link.download = attachment.name;
299
+ document.body.append(link);
300
+ link.click();
301
+ link.remove();
302
+ };
303
+ const renderParsedEmail = (parsed) => {
304
+ let activeBody = parsed.html ? 'html' : parsed.text ? 'text' : 'headers';
305
+ let activeAttachment = null;
306
+ const tabButtons = [];
307
+ const attachmentButtons = [];
308
+ root.replaceChildren();
309
+ const header = createElement('header', 'email-header');
310
+ header.append(createElement('span', undefined, parsed.kind.toUpperCase()));
311
+ header.append(createElement('h2', undefined, parsed.subject || filename));
312
+ const meta = createElement('div', 'email-meta');
313
+ appendMeta(meta, '发件人', addressText(parsed.from));
314
+ appendMeta(meta, '收件人', addressText(parsed.to));
315
+ if (parsed.cc.length) {
316
+ appendMeta(meta, '抄送', addressText(parsed.cc));
317
+ }
318
+ appendMeta(meta, '时间', parsed.date || '-');
319
+ header.append(meta);
320
+ const body = createElement('div', 'email-body');
321
+ const sidebar = createElement('aside', 'email-sidebar');
322
+ const tabs = createElement('div', 'body-tabs');
323
+ const messagePanel = createElement('main', 'message-panel');
324
+ const messageContent = createElement('div', 'email-message-content');
325
+ const attachmentPreview = createElement('section', 'attachment-preview');
326
+ attachmentPreview.hidden = true;
327
+ const attachmentPreviewHead = createElement('div', 'attachment-preview-head');
328
+ const attachmentPreviewTitle = createElement('strong');
329
+ const attachmentDownload = createElement('button', undefined, '下载附件');
330
+ attachmentDownload.type = 'button';
331
+ const attachmentTarget = createElement('div', 'attachment-target');
332
+ attachmentPreviewHead.append(attachmentPreviewTitle, attachmentDownload);
333
+ attachmentPreview.append(attachmentPreviewHead, attachmentTarget);
334
+ const renderMessageContent = () => {
335
+ messageContent.replaceChildren();
336
+ if (activeBody === 'html' && parsed.html) {
337
+ const iframe = createElement('iframe', 'email-html');
338
+ iframe.setAttribute('sandbox', '');
339
+ iframe.srcdoc = createHtmlSrcdoc(parsed.html, cidUrls);
340
+ messageContent.append(iframe);
341
+ return;
342
+ }
343
+ const pre = createElement('pre', 'email-text');
344
+ pre.textContent = activeBody === 'text' ? parsed.text || '' : parsed.headers || '';
345
+ messageContent.append(pre);
346
+ };
347
+ const syncTabState = () => {
348
+ tabButtons.forEach(({ mode, button }) => {
349
+ button.classList.toggle('active', mode === activeBody);
350
+ });
351
+ };
352
+ const bodyModes = [
353
+ { key: 'html', label: 'HTML', disabled: !parsed.html },
354
+ { key: 'text', label: '正文', disabled: !parsed.text },
355
+ { key: 'headers', label: '头信息', disabled: !parsed.headers },
356
+ ];
357
+ bodyModes.forEach(mode => {
358
+ const button = createElement('button', undefined, mode.label);
359
+ button.type = 'button';
360
+ button.disabled = mode.disabled;
361
+ listen(button, 'click', () => {
362
+ if (button.disabled) {
363
+ return;
364
+ }
365
+ activeBody = mode.key;
366
+ syncTabState();
367
+ renderMessageContent();
368
+ });
369
+ tabButtons.push({ mode: mode.key, button });
370
+ tabs.append(button);
371
+ });
372
+ syncTabState();
373
+ const attachmentPanel = createElement('section', 'attachment-panel');
374
+ const attachmentTitle = createElement('div', 'attachment-title');
375
+ attachmentTitle.append(createElement('strong', undefined, '附件'), createElement('span', undefined, String(parsed.attachments.length)));
376
+ attachmentPanel.append(attachmentTitle);
377
+ if (!parsed.attachments.length) {
378
+ attachmentPanel.append(createElement('p', 'attachment-empty', '暂无附件'));
379
+ }
380
+ const syncAttachmentState = () => {
381
+ attachmentButtons.forEach(({ id, button }) => {
382
+ button.classList.toggle('active', id === (activeAttachment === null || activeAttachment === void 0 ? void 0 : activeAttachment.id));
383
+ });
384
+ };
385
+ const previewAttachment = async (attachment) => {
386
+ activeAttachment = attachment;
387
+ syncAttachmentState();
388
+ attachmentPreview.hidden = false;
389
+ attachmentPreviewTitle.textContent = attachment.name;
390
+ showLoading(`正在打开附件 ${attachment.name}...`);
391
+ try {
392
+ await clearAttachmentPreview();
393
+ attachmentTarget.replaceChildren();
394
+ const attachmentBuffer = await attachment.load();
395
+ const child = createElement('div', 'email-attachment-render');
396
+ attachmentTarget.append(child);
397
+ const extension = getAttachmentExtension(attachment.name);
398
+ if (context === null || context === void 0 ? void 0 : context.renderNestedBuffer) {
399
+ nestedRendered = await context.renderNestedBuffer(attachmentBuffer, extension, child, {
400
+ ...context,
401
+ filename: attachment.name,
402
+ options: context.options,
403
+ });
404
+ }
405
+ else {
406
+ child.append(createElement('div', undefined, `当前运行环境未提供附件嵌套预览入口,请下载 ${attachment.name} 后查看。`));
407
+ }
408
+ }
409
+ catch (nextError) {
410
+ console.error(nextError);
411
+ showError(nextError instanceof Error ? nextError.message : String(nextError));
412
+ }
413
+ finally {
414
+ hideLoading();
415
+ }
416
+ };
417
+ parsed.attachments.forEach(attachment => {
418
+ const button = createElement('button', 'attachment-item');
419
+ button.type = 'button';
420
+ const icon = createElement('span', undefined, getAttachmentExtension(attachment.name).toUpperCase() || 'FILE');
421
+ const name = createElement('strong', undefined, attachment.name);
422
+ const size = createElement('em', undefined, formatBytes(attachment.size));
423
+ button.append(icon, name, size);
424
+ listen(button, 'click', () => {
425
+ void previewAttachment(attachment);
426
+ });
427
+ attachmentButtons.push({ id: attachment.id, button });
428
+ attachmentPanel.append(button);
429
+ });
430
+ listen(attachmentDownload, 'click', () => {
431
+ if (activeAttachment) {
432
+ void downloadAttachment(activeAttachment);
433
+ }
434
+ });
435
+ renderMessageContent();
436
+ sidebar.append(tabs, attachmentPanel);
437
+ messagePanel.append(messageContent, attachmentPreview);
438
+ body.append(sidebar, messagePanel);
439
+ root.append(header, body);
440
+ };
441
+ showLoading('正在解析邮件...');
442
+ try {
443
+ const parsed = await parseEmail(buffer, normalizedType, filename, objectUrls, cidUrls);
444
+ renderParsedEmail(parsed);
445
+ }
446
+ catch (nextError) {
447
+ console.error(nextError);
448
+ root.replaceChildren();
449
+ showError(nextError instanceof Error ? nextError.message : String(nextError));
450
+ }
451
+ finally {
452
+ hideLoading();
453
+ }
454
+ return {
455
+ $el: root,
456
+ async unmount() {
457
+ await clearAttachmentPreview();
458
+ cleanups.splice(0).forEach(cleanup => cleanup());
459
+ objectUrls.forEach(url => URL.revokeObjectURL(url));
460
+ target.replaceChildren();
461
+ },
462
+ };
463
+ }
@@ -0,0 +1,5 @@
1
+ import { type FileRenderHandler, type FileViewerRenderedInstance, type FileViewerRendererPlugin, type RendererDefinition } from '@file-viewer/core';
2
+ export declare const emailRendererDefinition: RendererDefinition;
3
+ export declare const renderFileViewerEmail: FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>;
4
+ export declare const emailRenderer: FileViewerRendererPlugin<FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>>;
5
+ export default emailRenderer;
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ import { DEFAULT_RENDERER_DEFINITIONS, } from '@file-viewer/core';
2
+ const emailDefinition = DEFAULT_RENDERER_DEFINITIONS.find(definition => definition.id === 'email');
3
+ if (!emailDefinition) {
4
+ throw new Error('@file-viewer/renderer-email could not locate the shared email format definition.');
5
+ }
6
+ export const emailRendererDefinition = emailDefinition;
7
+ export const renderFileViewerEmail = (buffer, target, type, context) => import('./email.js').then(({ default: renderEmail }) => renderEmail(buffer, target, type, context));
8
+ export const emailRenderer = {
9
+ id: 'file-viewer-renderer-email',
10
+ label: 'Flyfish File Viewer email renderer',
11
+ definitions: [emailRendererDefinition],
12
+ handlers: [{
13
+ rendererId: emailRendererDefinition.id,
14
+ handler: renderFileViewerEmail,
15
+ }],
16
+ };
17
+ export default emailRenderer;
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "@file-viewer/renderer-email",
3
+ "version": "2.0.11",
4
+ "private": false,
5
+ "type": "module",
6
+ "description": "Standalone email renderer plugin for Flyfish File Viewer with EML, MSG, MBOX, attachments, and nested previews.",
7
+ "keywords": [
8
+ "file-viewer",
9
+ "renderer",
10
+ "email",
11
+ "eml",
12
+ "msg",
13
+ "mbox",
14
+ "document-preview",
15
+ "document-viewer",
16
+ "file-preview",
17
+ "self-hosted"
18
+ ],
19
+ "publishConfig": {
20
+ "access": "public",
21
+ "registry": "https://registry.npmjs.org/"
22
+ },
23
+ "author": {
24
+ "name": "Wangyu",
25
+ "email": "wybaby168@gmail.com"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/flyfish-dev/file-viewer-renderer-email.git",
30
+ "directory": "packages/renderers/email"
31
+ },
32
+ "homepage": "https://doc.file-viewer.app/guide/on-demand-renderers",
33
+ "bugs": {
34
+ "url": "https://github.com/flyfish-dev/file-viewer-renderer-email/issues"
35
+ },
36
+ "funding": {
37
+ "type": "individual",
38
+ "url": "https://dev.flyfish.group/shop"
39
+ },
40
+ "main": "./dist/index.js",
41
+ "module": "./dist/index.js",
42
+ "types": "./dist/index.d.ts",
43
+ "exports": {
44
+ ".": {
45
+ "types": "./dist/index.d.ts",
46
+ "import": "./dist/index.js",
47
+ "default": "./dist/index.js"
48
+ },
49
+ "./package.json": "./package.json"
50
+ },
51
+ "files": [
52
+ "dist",
53
+ "README.md",
54
+ "README.en.md",
55
+ "LICENSE"
56
+ ],
57
+ "dependencies": {
58
+ "@file-viewer/core": "^2.0.11",
59
+ "@kenjiuno/msgreader": "^1.28.0",
60
+ "postal-mime": "^2.7.4"
61
+ },
62
+ "devDependencies": {
63
+ "typescript": "^6.0.3"
64
+ },
65
+ "license": "Apache-2.0",
66
+ "scripts": {
67
+ "build": "tsc -b tsconfig.json",
68
+ "type-check": "tsc -b tsconfig.json"
69
+ }
70
+ }