@file-viewer/renderer-email 3.1.1 → 3.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,205 @@
1
+ export const normalizeEmailResourceId = (value) => {
2
+ const isUri = /^cid:/i.test(value.trim());
3
+ let result = value.trim().replace(/^cid:/i, '').replace(/^<|>$/g, '');
4
+ if (isUri) {
5
+ try {
6
+ result = decodeURIComponent(result);
7
+ }
8
+ catch { /* Keep malformed escapes literal. */ }
9
+ }
10
+ return result;
11
+ };
12
+ /** Sandboxed srcdoc cannot read blob:null URLs from a different opaque
13
+ * origin (file:// WebViews, data: hosts). Keep ordinary hosts zero-copy and use
14
+ * a bounded data URL only for those hosts or browsers without object URLs.
15
+ */
16
+ export function createEmailImageResource(buffer, mimeType, objectUrls) {
17
+ if (typeof URL.createObjectURL === 'function') {
18
+ const url = URL.createObjectURL(new Blob([buffer], { type: mimeType }));
19
+ if (!url.startsWith('blob:null/')) {
20
+ objectUrls.push(url);
21
+ return url;
22
+ }
23
+ URL.revokeObjectURL(url);
24
+ }
25
+ const bytes = new Uint8Array(buffer);
26
+ const parts = [];
27
+ // Divisible by three: only the final base64 chunk can contain padding.
28
+ for (let offset = 0; offset < bytes.length; offset += 24576) {
29
+ parts.push(btoa(String.fromCharCode(...bytes.subarray(offset, offset + 24576))));
30
+ }
31
+ return `data:${mimeType};base64,${parts.join('')}`;
32
+ }
33
+ const ALLOWED_TAGS = new Set('a abbr address article aside b bdi bdo big blockquote br caption center cite code col colgroup dd del details div dl dt em figcaption figure font footer h1 h2 h3 h4 h5 h6 header hr i img ins kbd label li main mark ol p pre q rp rt ruby s samp section small span strike strong style sub summary sup table tbody td tfoot th thead time title tr tt u ul var wbr'.split(' '));
34
+ const DROP_CONTENT = new Set('script iframe frame frameset object embed applet svg math template noscript audio video source track input link meta base'.split(' '));
35
+ const ALLOWED_ATTRS = new Set('alt title class id style width height align valign bgcolor color face size border cellpadding cellspacing colspan rowspan dir lang role aria-label scope start type value open name text'.split(' '));
36
+ const SAFE_IMAGE = /^data:image\/(?:png|jpeg|gif|webp|avif|bmp);base64,[a-z0-9+/=\r\n]+$/i;
37
+ export function createEmailHtmlDocument(html, resources, darkMode = false, documentRef = document) {
38
+ var _a, _b;
39
+ if (html.length > 32 * 1024 * 1024)
40
+ throw new Error('Email HTML exceeds the safety limit.');
41
+ // Template contents are inert, unlike parsing a live document with loadable images.
42
+ const template = documentRef.createElement('template');
43
+ const inertDocument = template.content.ownerDocument;
44
+ if (inertDocument.defaultView)
45
+ throw new Error('Email parsing requires an inert template document.');
46
+ const parsed = inertDocument.createElement('html');
47
+ parsed.innerHTML = html;
48
+ // Fragment parsing drops the outer html token. Recover only its language and
49
+ // direction through a second inert element; never copy executable attributes.
50
+ const rootAttributes = (_a = /^\s*(?:<!doctype[^>]*>\s*)?<html\b((?:[^>"']|"[^"]*"|'[^']*')*)>/i.exec(html.slice(0, 16384))) === null || _a === void 0 ? void 0 : _a[1];
51
+ if (rootAttributes) {
52
+ const probe = inertDocument.createElement('div');
53
+ probe.innerHTML = `<div${rootAttributes}></div>`;
54
+ for (const name of ['lang', 'dir']) {
55
+ const value = (_b = probe.firstElementChild) === null || _b === void 0 ? void 0 : _b.getAttribute(name);
56
+ if (value)
57
+ parsed.setAttribute(name, value);
58
+ }
59
+ }
60
+ const head = parsed.querySelector('head') || inertDocument.createElement('head');
61
+ const body = parsed.querySelector('body') || inertDocument.createElement('body');
62
+ const ownedUrls = new Set(resources.values());
63
+ const lookup = (value) => {
64
+ const trimmed = value.trim();
65
+ if (ownedUrls.has(trimmed) && /^blob:/.test(trimmed))
66
+ return trimmed;
67
+ if (SAFE_IMAGE.test(trimmed))
68
+ return trimmed;
69
+ const key = normalizeEmailResourceId(trimmed);
70
+ let exact = resources.get(key);
71
+ if (!exact && !/^cid:/i.test(trimmed)) {
72
+ try {
73
+ exact = resources.get(decodeURIComponent(key));
74
+ }
75
+ catch { /* Literal Content-Location. */ }
76
+ }
77
+ if (exact && (/^blob:/.test(exact) || SAFE_IMAGE.test(exact)))
78
+ return exact;
79
+ if (/^cid:/i.test(trimmed)) {
80
+ // Legacy writers vary CID casing. Only use a case-insensitive fallback
81
+ // when it identifies exactly one attachment; never replace a prefix.
82
+ const matches = [...resources].filter(([id]) => id.toLowerCase() === key.toLowerCase());
83
+ if (matches.length === 1 && (/^blob:/.test(matches[0][1]) || SAFE_IMAGE.test(matches[0][1])))
84
+ return matches[0][1];
85
+ }
86
+ return undefined;
87
+ };
88
+ let expandedResourceCharacters = 0;
89
+ const resource = (value) => {
90
+ const resolved = lookup(value);
91
+ if (resolved) {
92
+ expandedResourceCharacters += resolved.length;
93
+ if (expandedResourceCharacters > 48 * 1024 * 1024)
94
+ throw new Error('Email inline resource expansion limit exceeded.');
95
+ }
96
+ return resolved;
97
+ };
98
+ const css = (value) => value
99
+ .replace(/@import\s+(?:url\([^)]*\)|[^;]*);?/gi, '')
100
+ .replace(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)/gi, (_match, double, single, bare) => {
101
+ var _a, _b;
102
+ const resolved = resource(String((_b = (_a = double !== null && double !== void 0 ? double : single) !== null && _a !== void 0 ? _a : bare) !== null && _b !== void 0 ? _b : ''));
103
+ return resolved ? `url("${resolved.replace(/["\\\r\n]/g, '')}")` : 'none';
104
+ });
105
+ const attributes = (element) => {
106
+ const tag = element.localName.toLowerCase();
107
+ for (const attribute of Array.from(element.attributes)) {
108
+ const name = attribute.name.toLowerCase();
109
+ if (tag === 'img' && name === 'src') {
110
+ const resolved = resource(attribute.value);
111
+ if (resolved)
112
+ element.setAttribute('src', resolved);
113
+ else
114
+ element.removeAttribute(attribute.name);
115
+ }
116
+ else if (name === 'background') {
117
+ const resolved = resource(attribute.value);
118
+ if (resolved)
119
+ element.setAttribute('background', resolved);
120
+ else
121
+ element.removeAttribute(attribute.name);
122
+ }
123
+ else if (tag === 'a' && name === 'href') {
124
+ if (!/^#[a-z0-9_:.\-]+$/i.test(attribute.value))
125
+ element.removeAttribute(attribute.name);
126
+ }
127
+ else if (name === 'style')
128
+ element.setAttribute('style', css(attribute.value));
129
+ else if (!ALLOWED_ATTRS.has(name))
130
+ element.removeAttribute(attribute.name);
131
+ }
132
+ };
133
+ let count = 0;
134
+ const clean = (parent) => {
135
+ const pending = [...parent.children];
136
+ while (pending.length) {
137
+ const element = pending.pop();
138
+ if (++count > 100000)
139
+ throw new Error('Email HTML node limit exceeded.');
140
+ const tag = element.localName.toLowerCase();
141
+ if (DROP_CONTENT.has(tag)) {
142
+ element.remove();
143
+ continue;
144
+ }
145
+ if (!ALLOWED_TAGS.has(tag)) {
146
+ const children = [...element.children];
147
+ element.replaceWith(...Array.from(element.childNodes));
148
+ pending.push(...children);
149
+ continue;
150
+ }
151
+ attributes(element);
152
+ if (tag === 'style')
153
+ element.textContent = css(element.textContent || '');
154
+ pending.push(...element.children);
155
+ }
156
+ };
157
+ clean(head);
158
+ clean(body);
159
+ attributes(parsed);
160
+ attributes(body);
161
+ // Preserve legacy Outlook body colors as well as modern inline styles.
162
+ if (body.getAttribute('bgcolor') && !body.style.backgroundColor)
163
+ body.style.backgroundColor = body.getAttribute('bgcolor');
164
+ if (body.getAttribute('text') && !body.style.color)
165
+ body.style.color = body.getAttribute('text');
166
+ if (body.getAttribute('background') && !body.style.backgroundImage)
167
+ body.style.backgroundImage = `url("${body.getAttribute('background').replace(/["\\\r\n]/g, '')}")`;
168
+ // Check escaped serialization growth before building a potentially huge srcdoc.
169
+ const escapedLength = (value, attribute = false) => {
170
+ let size = value.length;
171
+ for (let index = 0; index < value.length; index++) {
172
+ const code = value.charCodeAt(index);
173
+ if (code === 38)
174
+ size += 4;
175
+ else if (code === 60 || code === 62)
176
+ size += 3;
177
+ else if (attribute && code === 34)
178
+ size += 5;
179
+ }
180
+ return size;
181
+ };
182
+ const nodes = [parsed];
183
+ let estimated = 0;
184
+ while (nodes.length) {
185
+ const node = nodes.pop();
186
+ if (node.nodeType === 3)
187
+ estimated += escapedLength(node.nodeValue || '');
188
+ else if (node.nodeType === 1) {
189
+ estimated += 32;
190
+ for (const attr of Array.from(node.attributes))
191
+ estimated += attr.name.length + escapedLength(attr.value, true) + 8;
192
+ }
193
+ if (estimated > 64 * 1024 * 1024)
194
+ throw new Error('Email HTML serialization limit exceeded.');
195
+ nodes.push(...Array.from(node.childNodes));
196
+ }
197
+ const escape = (value) => value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
198
+ const serializeAttributes = (element) => Array.from(element.attributes).map(attr => ` ${attr.name}="${escape(attr.value)}"`).join('');
199
+ const background = darkMode ? '#111827' : '#fff';
200
+ const foreground = darkMode ? '#e5e7eb' : '#172033';
201
+ // CSP is required in addition to sanitization: CSS escapes and future HTML
202
+ // features must not introduce external requests or executable content.
203
+ const csp = "default-src 'none'; script-src 'none'; connect-src 'none'; img-src blob: data:; style-src 'unsafe-inline'; font-src 'none'; media-src 'none'; object-src 'none'; frame-src 'none'; base-uri 'none'; form-action 'none'";
204
+ return `<!doctype html><html${serializeAttributes(parsed)}><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${csp}"><meta name="referrer" content="no-referrer"><style>:root{color-scheme:${darkMode ? 'dark' : 'light'}}body{margin:0;padding:18px;font-family:Aptos,"Segoe UI",sans-serif;line-height:1.6;overflow-wrap:anywhere;background:${background};color:${foreground}}img{max-width:100%;height:auto}table{max-width:100%}</style>${head.innerHTML}</head><body${serializeAttributes(body)}>${body.innerHTML}</body></html>`;
205
+ }
package/dist/msg.d.ts ADDED
@@ -0,0 +1,65 @@
1
+ import type { ParsedEmailView } from './email.js';
2
+ /** Structural view of @kenjiuno/msgreader 1.28's documented API. Keep it local:
3
+ * consumers continue to use the shared File Viewer contract, not MAPI types.
4
+ */
5
+ export interface MsgFields {
6
+ dataType?: string;
7
+ error?: unknown;
8
+ subject?: string;
9
+ senderName?: string;
10
+ senderEmail?: string;
11
+ senderSmtpAddress?: string;
12
+ sentRepresentingSmtpAddress?: string;
13
+ sentRepresentingName?: string;
14
+ sentRepresentingEmail?: string;
15
+ displayTo?: string;
16
+ displayCc?: string;
17
+ displayBcc?: string;
18
+ body?: string;
19
+ bodyHtml?: string;
20
+ html?: Uint8Array | ArrayBuffer | string;
21
+ headers?: string;
22
+ compressedRtf?: Uint8Array;
23
+ internetCodepage?: number;
24
+ messageCodepage?: number;
25
+ clientSubmitTime?: string;
26
+ messageDeliveryTime?: string;
27
+ creationTime?: string;
28
+ recipients?: MsgFields[];
29
+ attachments?: MsgFields[];
30
+ name?: string;
31
+ email?: string;
32
+ smtpAddress?: string;
33
+ recipType?: string | number;
34
+ fileName?: string;
35
+ fileNameShort?: string;
36
+ extension?: string;
37
+ contentLength?: number;
38
+ pidContentId?: string;
39
+ contentLocation?: string;
40
+ attachMimeTag?: string;
41
+ attachmentHidden?: boolean;
42
+ innerMsgContent?: boolean;
43
+ innerMsgContentFields?: MsgFields;
44
+ messageClass?: string;
45
+ messageId?: string;
46
+ [key: string]: unknown;
47
+ }
48
+ export interface MsgReaderLike {
49
+ parserConfig?: {
50
+ ansiEncoding?: string;
51
+ propertyObserver?: (fields: MsgFields, tag: number, raw: Uint8Array | null) => void;
52
+ };
53
+ getFileData(): MsgFields;
54
+ getAttachment(attachment: MsgFields): {
55
+ fileName: string;
56
+ content: Uint8Array;
57
+ };
58
+ }
59
+ export type MsgReaderConstructor = new (buffer: ArrayBuffer) => MsgReaderLike;
60
+ export declare function safeMsgAttachmentName(value: unknown, fallback: string): string;
61
+ /** Exported only from the internal module for deterministic normalization tests. */
62
+ export declare function normalizeMsg(reader: MsgReaderLike, fields: MsgFields, filename: string, objectUrls: string[], cidUrls: Map<string, string>, signal?: AbortSignal): Promise<ParsedEmailView>;
63
+ /** Capture standard MAPI strings not named by the reader's default map. */
64
+ export declare function captureMsgProperty(fields: MsgFields, tag: number, raw: Uint8Array | null, codepage?: number): void;
65
+ export declare function parseMsg(buffer: ArrayBuffer, filename: string, objectUrls: string[], cidUrls: Map<string, string>, signal?: AbortSignal): Promise<ParsedEmailView>;
package/dist/msg.js ADDED
@@ -0,0 +1,242 @@
1
+ import { inspectMsgContainer, MAX_MSG_BYTES } from './msgCfb.js';
2
+ import { createEmailImageResource, normalizeEmailResourceId } from './emailHtml.js';
3
+ import { decompressMsgRtf, extractMsgRtf } from './msgRtf.js';
4
+ import { decodeEmailHtmlBytes, msgCodepageLabel } from './msgEncoding.js';
5
+ const MAX_ATTACHMENTS = 1024;
6
+ const MAX_RECIPIENTS = 4096;
7
+ const MAX_BODY_CHARS = 32 * 1024 * 1024;
8
+ const MAX_INLINE_BYTES = 32 * 1024 * 1024;
9
+ const MAX_NESTED_MESSAGES = 24;
10
+ const MIME = {
11
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif',
12
+ webp: 'image/webp', avif: 'image/avif', bmp: 'image/bmp', tif: 'image/tiff', tiff: 'image/tiff',
13
+ svg: 'image/svg+xml', pdf: 'application/pdf', txt: 'text/plain', csv: 'text/csv',
14
+ html: 'text/html', htm: 'text/html', rtf: 'application/rtf', msg: 'application/vnd.ms-outlook',
15
+ eml: 'message/rfc822', zip: 'application/zip',
16
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
17
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
18
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
19
+ };
20
+ const RASTER_MIME = /^image\/(?:png|jpeg|gif|webp|avif|bmp|x-ms-bmp)$/i;
21
+ const string = (value, max = MAX_BODY_CHARS) => {
22
+ if (typeof value !== 'string')
23
+ return '';
24
+ if (value.length > max)
25
+ throw new Error('Outlook MSG text exceeds the safety limit.');
26
+ return value.replace(/\0+$/, '');
27
+ };
28
+ export function safeMsgAttachmentName(value, fallback) {
29
+ const name = string(value, 32768).split(/[\\/]/).pop().replace(/[\x00-\x1f\x7f\u202a-\u202e\u2066-\u2069]/g, '').replace(/[<>:"|?*]/g, '_').replace(/[. ]+$/, '').trim();
30
+ return !name || name === '.' || name === '..' ? fallback : name;
31
+ }
32
+ const recipient = (item) => ({ name: string(item.name, 32768), address: string(item.smtpAddress || item.email, 32768) });
33
+ const addressText = (items) => items.map(item => item.name && item.address ? `${item.name} <${item.address}>` : item.address || item.name || '').join(', ');
34
+ const copy = (value) => {
35
+ const bytes = value instanceof ArrayBuffer ? new Uint8Array(value) : value;
36
+ if (!(bytes instanceof Uint8Array) || bytes.length > MAX_MSG_BYTES)
37
+ throw new Error('Invalid or oversized MSG attachment.');
38
+ return new Uint8Array(bytes).buffer;
39
+ };
40
+ function assertFieldTree(root) {
41
+ var _a, _b;
42
+ const seen = new Set();
43
+ const pending = [{ item: root, depth: 0 }];
44
+ let count = 0;
45
+ while (pending.length) {
46
+ const { item, depth } = pending.pop();
47
+ if (depth > MAX_NESTED_MESSAGES || seen.has(item) || ++count > 32768)
48
+ throw new Error('Outlook MSG nesting limit exceeded.');
49
+ seen.add(item);
50
+ if ((((_a = item.attachments) === null || _a === void 0 ? void 0 : _a.length) || 0) > MAX_ATTACHMENTS || (((_b = item.recipients) === null || _b === void 0 ? void 0 : _b.length) || 0) > MAX_RECIPIENTS)
51
+ throw new Error('Outlook MSG recipient/attachment limit exceeded.');
52
+ for (const attachment of item.attachments || []) {
53
+ if (attachment.innerMsgContentFields)
54
+ pending.push({ item: attachment.innerMsgContentFields, depth: depth + 1 });
55
+ }
56
+ }
57
+ }
58
+ /** Exported only from the internal module for deterministic normalization tests. */
59
+ export async function normalizeMsg(reader, fields, filename, objectUrls, cidUrls, signal) {
60
+ var _a, _b;
61
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
62
+ if (fields.error || fields.dataType !== 'msg')
63
+ throw new Error(string(fields.error) || 'The file does not contain a readable Outlook message.');
64
+ assertFieldTree(fields);
65
+ const warnings = [];
66
+ const actualSender = { name: string(fields.senderName, 32768), address: string(fields.senderSmtpAddress || fields.senderEmail, 32768) };
67
+ const represented = { name: string(fields.sentRepresentingName, 32768), address: string(fields.sentRepresentingSmtpAddress || fields.sentRepresentingEmail, 32768) };
68
+ const hasRepresentation = !!(represented.name || represented.address);
69
+ const from = [hasRepresentation ? represented : actualSender].filter(item => item.name || item.address);
70
+ const sender = hasRepresentation && (actualSender.address || actualSender.name) &&
71
+ (actualSender.address !== represented.address || actualSender.name !== represented.name) ? [actualSender] : [];
72
+ const to = [];
73
+ const cc = [];
74
+ const bcc = [];
75
+ for (const item of fields.recipients || []) {
76
+ const address = recipient(item);
77
+ if (!address.name && !address.address)
78
+ continue;
79
+ const kind = String((_a = item.recipType) !== null && _a !== void 0 ? _a : 'to').toLowerCase();
80
+ (kind === 'cc' || kind === '2' ? cc : kind === 'bcc' || kind === '3' ? bcc : to).push(address);
81
+ }
82
+ // Display lists are useful in drafts that omit recipient rows. They are
83
+ // display text, not an address parser: do not invent SMTP addresses.
84
+ if (!to.length && fields.displayTo)
85
+ to.push({ name: string(fields.displayTo, 32768) });
86
+ if (!cc.length && fields.displayCc)
87
+ cc.push({ name: string(fields.displayCc, 32768) });
88
+ if (!bcc.length && fields.displayBcc)
89
+ bcc.push({ name: string(fields.displayBcc, 32768) });
90
+ let html = string(fields.bodyHtml);
91
+ if (!html && fields.html)
92
+ html = decodeEmailHtmlBytes(fields.html, fields.internetCodepage, fields.messageCodepage);
93
+ let text = string(fields.body);
94
+ let rtf;
95
+ if ((_b = fields.compressedRtf) === null || _b === void 0 ? void 0 : _b.length) {
96
+ try {
97
+ const uncompressed = decompressMsgRtf(fields.compressedRtf);
98
+ const extracted = extractMsgRtf(uncompressed, fields.messageCodepage);
99
+ text || (text = extracted.text);
100
+ html || (html = extracted.html || '');
101
+ rtf = copy(uncompressed);
102
+ }
103
+ catch (error) {
104
+ if (!html && !text)
105
+ throw error;
106
+ warnings.push('email.msg.rtfUnavailable');
107
+ }
108
+ }
109
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
110
+ let inlineBytes = 0;
111
+ const attachments = (fields.attachments || []).map((attachment, index) => {
112
+ const fallback = `attachment-${index + 1}`;
113
+ let name = safeMsgAttachmentName(attachment.fileName || attachment.fileNameShort || attachment.name, fallback);
114
+ const extension = string(attachment.extension, 128).replace(/^\./, '');
115
+ if (attachment.innerMsgContent && !/\.msg$/i.test(name))
116
+ name += '.msg';
117
+ else if (!name.includes('.') && /^[a-z0-9]{1,16}$/i.test(extension))
118
+ name += `.${extension}`;
119
+ const hint = string(attachment.attachMimeTag, 256).split(';')[0].trim().toLowerCase();
120
+ const mimeType = attachment.innerMsgContent ? MIME.msg : (/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i.test(hint) ? hint : MIME[name.split('.').pop().toLowerCase()] || 'application/octet-stream');
121
+ const size = Number.isSafeInteger(attachment.contentLength) && attachment.contentLength >= 0 ? attachment.contentLength : -1;
122
+ if (size > MAX_MSG_BYTES)
123
+ throw new Error('Outlook MSG attachment exceeds the size limit.');
124
+ const contentId = string(attachment.pidContentId, 32768);
125
+ const contentLocation = string(attachment.contentLocation, 32768);
126
+ const result = {
127
+ id: `msg-${index}`,
128
+ name, size, mimeType, contentId, contentLocation,
129
+ inline: !!attachment.attachmentHidden || !!contentId,
130
+ async load() {
131
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
132
+ // Do not cache every extracted buffer: the reader already owns the CFB.
133
+ const extracted = reader.getAttachment(attachment);
134
+ if (!extracted || !(extracted.content instanceof Uint8Array))
135
+ throw new Error(`Attachment data is not embedded: ${name}`);
136
+ const buffer = copy(extracted.content);
137
+ result.size = buffer.byteLength;
138
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
139
+ return buffer;
140
+ },
141
+ };
142
+ return result;
143
+ });
144
+ // Only raster CID images are decoded eagerly. PDF/Office/nested MSG remain lazy.
145
+ for (const attachment of attachments) {
146
+ const referenced = !!(attachment.contentId || attachment.contentLocation || attachment.inline || html.includes(attachment.name));
147
+ if (!referenced || !RASTER_MIME.test(attachment.mimeType || ''))
148
+ continue;
149
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
150
+ try {
151
+ if (inlineBytes + Math.max(0, attachment.size) > MAX_INLINE_BYTES)
152
+ throw new Error('Inline image size limit exceeded.');
153
+ const bytes = await attachment.load();
154
+ inlineBytes += bytes.byteLength;
155
+ if (inlineBytes > MAX_INLINE_BYTES)
156
+ throw new Error('Inline image size limit exceeded.');
157
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
158
+ const cid = normalizeEmailResourceId(attachment.contentId || '');
159
+ const keys = [cid, attachment.contentLocation].filter((key) => !!key);
160
+ // A unique filename is also a valid local Content-Location fallback.
161
+ if (attachments.filter(item => item.name === attachment.name).length === 1)
162
+ keys.push(attachment.name);
163
+ const available = keys.map(normalizeEmailResourceId).filter(key => !cidUrls.has(key));
164
+ if (available.length) {
165
+ const url = createEmailImageResource(bytes, attachment.mimeType, objectUrls);
166
+ available.forEach(key => cidUrls.set(key, url));
167
+ }
168
+ }
169
+ catch (error) {
170
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted)
171
+ throw error;
172
+ if (!warnings.includes('email.msg.inlineUnavailable'))
173
+ warnings.push('email.msg.inlineUnavailable');
174
+ }
175
+ }
176
+ const subject = string(fields.subject, 32768) || filename;
177
+ const date = string(fields.clientSubmitTime || fields.messageDeliveryTime || fields.creationTime, 4096);
178
+ const rawHeaders = string(fields.headers, 2 * 1024 * 1024);
179
+ const headerLine = (key, value) => value ? `${key}: ${value.replace(/[\r\n\0]/g, ' ')}` : '';
180
+ // Outlook drafts may have no transport headers. Label the generated metadata
181
+ // explicitly instead of misrepresenting it as the original transport envelope.
182
+ const headers = rawHeaders || [
183
+ 'X-File-Viewer-Source: Outlook MAPI properties (not transport headers)',
184
+ headerLine('Subject', subject), headerLine('From', addressText(from)), headerLine('Sender', addressText(sender)),
185
+ headerLine('To', addressText(to)), headerLine('Cc', addressText(cc)),
186
+ headerLine('Bcc', addressText(bcc)), headerLine('Date', date),
187
+ headerLine('Message-ID', string(fields.messageId, 32768)),
188
+ headerLine('Message-Class', string(fields.messageClass, 32768)),
189
+ ].filter(Boolean).join('\r\n');
190
+ if (!html && !text && !rtf)
191
+ warnings.push('email.msg.noBody');
192
+ if (/\.smime(?:\.|$)|rpmsg|protected/i.test(string(fields.messageClass, 32768)))
193
+ warnings.push('email.msg.protected');
194
+ return { kind: 'msg', subject, from, sender, to, cc, bcc, date, text, html, rtf, headers, attachments, warnings };
195
+ }
196
+ /** Capture standard MAPI strings not named by the reader's default map. */
197
+ export function captureMsgProperty(fields, tag, raw, codepage) {
198
+ const name = { 0x0042: 'sentRepresentingName', 0x0065: 'sentRepresentingEmail',
199
+ 0x0e04: 'displayTo', 0x0e03: 'displayCc', 0x0e02: 'displayBcc',
200
+ 0x3713: 'contentLocation' }[tag >>> 16];
201
+ const type = tag & 0xffff;
202
+ if (!name || !raw || (type !== 0x001f && type !== 0x001e))
203
+ return;
204
+ if (raw.length > 65536)
205
+ throw new Error('Outlook MSG metadata exceeds the safety limit.');
206
+ const value = decodeEmailHtmlBytes(raw, type === 0x001f ? 1200 : codepage || 1252);
207
+ // MsgReader also observes inline property-table references, whose 8-byte
208
+ // length/flags record is not the variable-length string stored in the CFB.
209
+ if (/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value))
210
+ return;
211
+ fields[name] = value;
212
+ }
213
+ export async function parseMsg(buffer, filename, objectUrls, cidUrls, signal) {
214
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
215
+ const { messageCodepage } = inspectMsgContainer(buffer);
216
+ const module = await import('@kenjiuno/msgreader');
217
+ signal === null || signal === void 0 ? void 0 : signal.throwIfAborted();
218
+ // CJS interop varies between native ESM, Vite and Webpack.
219
+ const exported = module.default;
220
+ const constructor = typeof exported === 'function' ? exported : exported === null || exported === void 0 ? void 0 : exported.default;
221
+ if (typeof constructor !== 'function')
222
+ throw new Error('Outlook MSG parser failed to load.');
223
+ const localBuffer = buffer instanceof ArrayBuffer ? buffer : new Uint8Array(buffer).slice().buffer;
224
+ const reader = new constructor(localBuffer);
225
+ const label = msgCodepageLabel(messageCodepage);
226
+ reader.parserConfig = {
227
+ // iconv-lite's names differ from WHATWG for Korean/Chinese codepages.
228
+ ...(messageCodepage ? { ansiEncoding: { 949: 'cp949', 936: 'cp936', 932: 'cp932', 950: 'cp950' }[messageCodepage] || label || `cp${messageCodepage}` } : {}),
229
+ propertyObserver: (fields, tag, raw) => captureMsgProperty(fields, tag, raw, messageCodepage),
230
+ };
231
+ const initialUrls = objectUrls.length;
232
+ const initialCids = new Map(cidUrls);
233
+ try {
234
+ return await normalizeMsg(reader, reader.getFileData(), filename, objectUrls, cidUrls, signal);
235
+ }
236
+ catch (error) {
237
+ objectUrls.splice(initialUrls).forEach(url => URL.revokeObjectURL(url));
238
+ cidUrls.clear();
239
+ initialCids.forEach((url, cid) => cidUrls.set(cid, url));
240
+ throw error;
241
+ }
242
+ }
@@ -0,0 +1,7 @@
1
+ /** Bounded structural validation before handing an untrusted CFB to MsgReader.
2
+ * MS-CFB: header, FAT/DIFAT, directory and MiniFAT. This is not a second MSG parser.
3
+ */
4
+ export declare const MAX_MSG_BYTES: number;
5
+ export declare function inspectMsgContainer(buffer: ArrayBuffer): {
6
+ messageCodepage?: number;
7
+ };