markdown-to-word 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -8
- package/build/cli.js +66 -3
- package/build/cli.js.map +1 -1
- package/build/docx-font-preset.d.ts +29 -3
- package/build/docx-font-preset.js +261 -13
- package/build/docx-font-preset.js.map +1 -1
- package/build/docx-html.d.ts +14 -6
- package/build/docx-html.js +157 -21
- package/build/docx-html.js.map +1 -1
- package/build/docx-images.d.ts +3 -1
- package/build/docx-images.js +144 -13
- package/build/docx-images.js.map +1 -1
- package/build/docx-structure.d.ts +9 -0
- package/build/docx-structure.js +51 -1
- package/build/docx-structure.js.map +1 -1
- package/build/font-presets.d.ts +37 -0
- package/build/font-presets.js +19 -0
- package/build/font-presets.js.map +1 -1
- package/build/input-checks.d.ts +4 -0
- package/build/input-checks.js +9 -0
- package/build/input-checks.js.map +1 -0
- package/build/main.d.ts +1 -1
- package/build/main.js +1 -1
- package/build/main.js.map +1 -1
- package/build/markdown-parser.d.ts +6 -5
- package/build/markdown-parser.js +14 -8
- package/build/markdown-parser.js.map +1 -1
- package/build/mcp.js +7 -0
- package/build/mcp.js.map +1 -1
- package/package.json +12 -11
package/build/docx-images.js
CHANGED
|
@@ -22,19 +22,33 @@ const ATTEMPTS = 2;
|
|
|
22
22
|
*/
|
|
23
23
|
const GENERATOR_URL = /http(s)?:\/\/(\w+:?\w*@)?(\S+)(:\d+)?((?<=\.)\w+)+(\/([\w#!:.?+=&%@!\-/])*)?/i;
|
|
24
24
|
const WEB_URL = /^https?:\/\//i;
|
|
25
|
-
/**
|
|
25
|
+
/**
|
|
26
|
+
* Leading bytes of the bitmap formats Word embeds. An image is checked
|
|
27
|
+
* against them whatever its declared type: html-to-docx drops a file it can't
|
|
28
|
+
* read (with its alt text), and embeds a format Word can't show, such as
|
|
29
|
+
* HEIC, as a broken picture.
|
|
30
|
+
*/
|
|
26
31
|
const SIGNATURES = [
|
|
27
32
|
['image/png', [0x89, 0x50, 0x4e, 0x47]],
|
|
28
33
|
['image/jpeg', [0xff, 0xd8, 0xff]],
|
|
29
34
|
['image/gif', [0x47, 0x49, 0x46, 0x38]],
|
|
30
35
|
['image/bmp', [0x42, 0x4d]],
|
|
31
36
|
];
|
|
37
|
+
/** The other format Word embeds, recognized by its root element. */
|
|
38
|
+
const SVG_TYPE = 'image/svg+xml';
|
|
39
|
+
/** How far into a file to look for SVG_START. */
|
|
40
|
+
const SVG_SNIFF_BYTES = 4096;
|
|
41
|
+
/** `data:[type][;params][;base64],payload` */
|
|
42
|
+
const DATA_URI = /^data:([^,]*?)(;base64)?,(.*)$/is;
|
|
43
|
+
const PERCENT = 0x25;
|
|
32
44
|
/**
|
|
33
45
|
* Downloads each web image in `html` and swaps its `src` for a `data:` URI,
|
|
34
46
|
* which html-to-docx embeds without downloading it again. An image that can't
|
|
35
47
|
* be fetched becomes its alt text, linked to its URL, where html-to-docx would
|
|
36
48
|
* drop it without a trace. Other sources it can't embed either, such as a
|
|
37
|
-
* relative path, keep their alt text too.
|
|
49
|
+
* relative path, keep their alt text too. So does a `data:` URI that isn't a
|
|
50
|
+
* PNG, JPEG, GIF, BMP or SVG image; one that is gets rewritten as base64 of
|
|
51
|
+
* the type its bytes show, which is the form html-to-docx reads.
|
|
38
52
|
*
|
|
39
53
|
* Each URL is fetched once, however many times it appears: at most
|
|
40
54
|
* MAX_IMAGES of them, CONCURRENCY at a time.
|
|
@@ -60,9 +74,9 @@ export async function embedImages(html) {
|
|
|
60
74
|
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker));
|
|
61
75
|
for (const image of images) {
|
|
62
76
|
const src = image.getAttribute('src') ?? '';
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
77
|
+
const dataUri = /^data:/i.test(src)
|
|
78
|
+
? checkDataUri(src)
|
|
79
|
+
: downloads.get(src);
|
|
66
80
|
if (dataUri) {
|
|
67
81
|
image.setAttribute('src', dataUri);
|
|
68
82
|
}
|
|
@@ -72,6 +86,73 @@ export async function embedImages(html) {
|
|
|
72
86
|
}
|
|
73
87
|
return dom.body.innerHTML;
|
|
74
88
|
}
|
|
89
|
+
/**
|
|
90
|
+
* `src`, a `data:` URI, as base64 of the image type its bytes show, or null
|
|
91
|
+
* if it's malformed, too large, or not an image Word embeds.
|
|
92
|
+
*/
|
|
93
|
+
function checkDataUri(src) {
|
|
94
|
+
const match = DATA_URI.exec(src);
|
|
95
|
+
if (!match)
|
|
96
|
+
return null;
|
|
97
|
+
const [, type, base64, payload] = match;
|
|
98
|
+
// At most four characters of payload make one byte (an escaped base64
|
|
99
|
+
// character, %2B, is a quarter of three bytes), so one this long decodes
|
|
100
|
+
// to more than the limit: turn it away before decoding allocates it.
|
|
101
|
+
if (payload.length > MAX_IMAGE_BYTES * 4 + 4)
|
|
102
|
+
return null;
|
|
103
|
+
let bytes;
|
|
104
|
+
try {
|
|
105
|
+
bytes = base64 ? base64Decode(payload) : percentDecode(payload);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
if (!bytes || bytes.length === 0 || bytes.length > MAX_IMAGE_BYTES) {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
const actual = imageType(type, bytes);
|
|
114
|
+
if (!actual)
|
|
115
|
+
return null;
|
|
116
|
+
return `data:${actual};base64,${Buffer.from(bytes).toString('base64')}`;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* The bytes of a base64 `data:` payload, or null if it isn't base64. Decoded
|
|
120
|
+
* as a browser does (the fetch spec's forgiving-base64): percent-escapes and
|
|
121
|
+
* whitespace are allowed, any other stray character fails. `Buffer.from`
|
|
122
|
+
* alone skips stray characters, which would embed a corrupted picture.
|
|
123
|
+
*/
|
|
124
|
+
function base64Decode(payload) {
|
|
125
|
+
let text = new TextDecoder().decode(percentDecode(payload));
|
|
126
|
+
text = text.replace(/[\t\n\f\r ]+/g, '');
|
|
127
|
+
if (text.length % 4 === 0)
|
|
128
|
+
text = text.replace(/={1,2}$/, '');
|
|
129
|
+
if (text.length % 4 === 1 || !/^[A-Za-z0-9+/]*$/.test(text))
|
|
130
|
+
return null;
|
|
131
|
+
return Buffer.from(text, 'base64');
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* The bytes of a URL-encoded `data:` payload. A `%` without two hex digits
|
|
135
|
+
* after it stays a `%`, as in a browser, so `width="100%"` in an SVG works.
|
|
136
|
+
*/
|
|
137
|
+
function percentDecode(payload) {
|
|
138
|
+
// `%` and hex digits are ASCII, so escapes can be read off the UTF-8 bytes.
|
|
139
|
+
const encoded = new TextEncoder().encode(payload);
|
|
140
|
+
const bytes = new Uint8Array(encoded.length);
|
|
141
|
+
let length = 0;
|
|
142
|
+
for (let index = 0; index < encoded.length; index++) {
|
|
143
|
+
const hex = encoded[index] === PERCENT
|
|
144
|
+
? String.fromCharCode(...encoded.subarray(index + 1, index + 3))
|
|
145
|
+
: '';
|
|
146
|
+
if (/^[0-9a-f]{2}$/i.test(hex)) {
|
|
147
|
+
bytes[length++] = parseInt(hex, 16);
|
|
148
|
+
index += 2;
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
bytes[length++] = encoded[index];
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return bytes.subarray(0, length);
|
|
155
|
+
}
|
|
75
156
|
function isFetchable(src) {
|
|
76
157
|
return WEB_URL.test(src) && GENERATOR_URL.test(src);
|
|
77
158
|
}
|
|
@@ -140,16 +221,66 @@ async function readBody(response, tooLarge) {
|
|
|
140
221
|
return bytes;
|
|
141
222
|
}
|
|
142
223
|
/**
|
|
143
|
-
* The image's media type
|
|
144
|
-
*
|
|
145
|
-
*
|
|
224
|
+
* The image's media type, read from its first bytes: PNG, JPEG, GIF or BMP,
|
|
225
|
+
* whatever `declared` says, or SVG if it says so (or names no image type)
|
|
226
|
+
* and the file starts like one. Null for anything else, such as an error
|
|
227
|
+
* page served with 200, or HEIC, which html-to-docx would embed but Word
|
|
228
|
+
* can't show.
|
|
146
229
|
*/
|
|
147
|
-
function imageType(
|
|
148
|
-
const declared = contentType?.split(';')[0].trim().toLowerCase();
|
|
149
|
-
if (declared?.startsWith('image/'))
|
|
150
|
-
return declared;
|
|
230
|
+
function imageType(declared, bytes) {
|
|
151
231
|
const match = SIGNATURES.find(([, signature]) => signature.every((byte, index) => bytes[index] === byte));
|
|
152
|
-
|
|
232
|
+
if (match)
|
|
233
|
+
return match[0];
|
|
234
|
+
const type = declared?.split(';')[0].trim().toLowerCase() ?? '';
|
|
235
|
+
if (type !== SVG_TYPE && type.startsWith('image/'))
|
|
236
|
+
return null;
|
|
237
|
+
const head = new TextDecoder().decode(bytes.subarray(0, SVG_SNIFF_BYTES));
|
|
238
|
+
return startsWithSvg(head) ? SVG_TYPE : null;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Whether `text` is an SVG file: `<svg` first, after at most a byte-order
|
|
242
|
+
* mark, an XML declaration, comments and a doctype. Anchored, so an HTML page
|
|
243
|
+
* with an inline icon doesn't count. A scan rather than one regular
|
|
244
|
+
* expression, which backtracks exponentially on input like
|
|
245
|
+
* `<!----><!----><!--...` (a comment's end can also be read as part of a
|
|
246
|
+
* longer comment).
|
|
247
|
+
*/
|
|
248
|
+
function startsWithSvg(text) {
|
|
249
|
+
let at = text.startsWith('\uFEFF') ? 1 : 0;
|
|
250
|
+
const skipSpace = () => {
|
|
251
|
+
while (at < text.length && /\s/.test(text[at]))
|
|
252
|
+
at++;
|
|
253
|
+
};
|
|
254
|
+
const startsHere = (prefix) => text.slice(at, at + prefix.length).toLowerCase() === prefix;
|
|
255
|
+
/** Moves past `end`, searching from `from`; false if it never comes. */
|
|
256
|
+
const skipPast = (end, from) => {
|
|
257
|
+
const index = text.indexOf(end, from);
|
|
258
|
+
if (index === -1)
|
|
259
|
+
return false;
|
|
260
|
+
at = index + end.length;
|
|
261
|
+
return true;
|
|
262
|
+
};
|
|
263
|
+
skipSpace();
|
|
264
|
+
if (startsHere('<?xml')) {
|
|
265
|
+
if (!skipPast('>', at))
|
|
266
|
+
return false;
|
|
267
|
+
skipSpace();
|
|
268
|
+
}
|
|
269
|
+
for (;;) {
|
|
270
|
+
if (startsHere('<!--')) {
|
|
271
|
+
if (!skipPast('-->', at + 4))
|
|
272
|
+
return false;
|
|
273
|
+
}
|
|
274
|
+
else if (startsHere('<!doctype')) {
|
|
275
|
+
if (!skipPast('>', at))
|
|
276
|
+
return false;
|
|
277
|
+
}
|
|
278
|
+
else {
|
|
279
|
+
break;
|
|
280
|
+
}
|
|
281
|
+
skipSpace();
|
|
282
|
+
}
|
|
283
|
+
return startsHere('<svg') && /[\s>]/.test(text[at + 4] ?? '');
|
|
153
284
|
}
|
|
154
285
|
/**
|
|
155
286
|
* Puts the image's alt text where it was, as a link to `src` when that's a web
|
package/build/docx-images.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docx-images.js","sourceRoot":"","sources":["../src/docx-images.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,6EAA6E;AAC7E,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAEhD;;;;GAIG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,CAAC;AAE9B;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,CAAC;AAE7B,iFAAiF;AACjF,MAAM,UAAU,GAAG,IAAI,CAAC;AACxB,MAAM,QAAQ,GAAG,CAAC,CAAC;AAEnB;;;;GAIG;AACH,MAAM,aAAa,GACjB,+EAA+E,CAAC;AAClF,MAAM,OAAO,GAAG,eAAe,CAAC;AAEhC,kFAAkF;AAClF,MAAM,UAAU,GAAyB;IACvC,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAA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AAE,CAC9C,SAAS,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,IAAI,CAAC,CACxD,CAAC;IACF,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC;AAC5B,CAAC;AAED;;;;GAIG;AACH,SAAS,kBAAkB,CAAC,KAAuB,EAAE,GAAW;IAC9D,MAAM,QAAQ,GAAG,KAAK,CAAC,aAAa,CAAC;IACrC,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACnC,MAAM,IAAI,GAAG,KAAK,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IACxE,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,KAAK,CAAC,MAAM,EAAE,CAAC;QACf,OAAO;IACT,CAAC;IACD,IAAI,CAAC,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QACpC,KAAK,CAAC,WAAW,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC;QACjD,OAAO;IACT,CAAC;IACD,MAAM,IAAI,GAAG,QAAQ,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;IACzC,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC/B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IACxB,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["import { Buffer } from 'buffer';\n\n/** html-to-docx's own limit for one image (imageProcessing.maxImageSize). */\nexport const MAX_IMAGE_BYTES = 10 * 1024 * 1024;\n\n/**\n * The most distinct image URLs fetched for one document: html-to-docx keeps\n * at most this many in its image cache (imageProcessing.maxCacheEntries). The\n * rest keep their alt text.\n */\nexport const MAX_IMAGES = 100;\n\n/**\n * How many downloads run at once. html-to-docx fetched one at a time; a few\n * in parallel is faster without opening a connection per image.\n */\nexport const CONCURRENCY = 4;\n\n/** Per attempt; the second attempt waits twice as long, as html-to-docx's do. */\nconst TIMEOUT_MS = 5000;\nconst ATTEMPTS = 2;\n\n/**\n * The URLs html-to-docx downloads (its `isValidUrl`, without the `g` flag\n * that makes `test()` stateful), anchored so the whole `src` is the URL.\n * Requiring both means this module never fetches what it wouldn't.\n */\nconst GENERATOR_URL =\n /http(s)?:\\/\\/(\\w+:?\\w*@)?(\\S+)(:\\d+)?((?<=\\.)\\w+)+(\\/([\\w#!:.?+=&%@!\\-/])*)?/i;\nconst WEB_URL = /^https?:\\/\\//i;\n\n/** Leading bytes of the image formats Word embeds, for servers that don't say. */\nconst SIGNATURES: [string, number[]][] = [\n ['image/png', [0x89, 0x50, 0x4e, 0x47]],\n ['image/jpeg', [0xff, 0xd8, 0xff]],\n ['image/gif', [0x47, 0x49, 0x46, 0x38]],\n ['image/bmp', [0x42, 0x4d]],\n];\n\n/**\n * Downloads each web image in `html` and swaps its `src` for a `data:` URI,\n * which html-to-docx embeds without downloading it again. An image that can't\n * be fetched becomes its alt text, linked to its URL, where html-to-docx would\n * drop it without a trace. Other sources it can't embed either, such as a\n * relative path, keep their alt text too.\n *\n * Each URL is fetched once, however many times it appears: at most\n * MAX_IMAGES of them, CONCURRENCY at a time.\n */\nexport async function embedImages(html: string): Promise<string> {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n const images = Array.from(dom.querySelectorAll('img'));\n if (images.length === 0) return html;\n\n const urls = new Set<string>();\n for (const image of images) {\n const src = image.getAttribute('src') ?? '';\n if (isFetchable(src) && urls.size < MAX_IMAGES) urls.add(src);\n }\n\n const queue = Array.from(urls);\n const downloads = new Map<string, string | null>();\n const worker = async (): Promise<void> => {\n for (let url = queue.shift(); url !== undefined; url = queue.shift()) {\n downloads.set(url, await fetchImage(url));\n }\n };\n await Promise.all(\n Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker)\n );\n\n for (const image of images) {\n const src = image.getAttribute('src') ?? '';\n if (src.startsWith('data:')) continue;\n const dataUri = downloads.get(src);\n if (dataUri) {\n image.setAttribute('src', dataUri);\n } else {\n replaceWithAltText(image, src);\n }\n }\n\n return dom.body.innerHTML;\n}\n\nfunction isFetchable(src: string): boolean {\n return WEB_URL.test(src) && GENERATOR_URL.test(src);\n}\n\n/** The image at `url` as a `data:` URI, or null if it can't be fetched. */\nasync function fetchImage(url: string): Promise<string | null> {\n for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {\n const tooLarge = new AbortController();\n try {\n const response = await fetch(url, {\n signal: AbortSignal.any([\n tooLarge.signal,\n AbortSignal.timeout(TIMEOUT_MS * attempt),\n ]),\n });\n // Not found, forbidden or too large won't change on a retry.\n if (!response.ok) return null;\n if (Number(response.headers.get('content-length')) > MAX_IMAGE_BYTES) {\n tooLarge.abort();\n return null;\n }\n const bytes = await readBody(response, tooLarge);\n if (!bytes || bytes.length === 0) return null;\n const type = imageType(response.headers.get('content-type'), bytes);\n if (!type) return null;\n return `data:${type};base64,${Buffer.from(bytes).toString('base64')}`;\n } catch {\n if (tooLarge.signal.aborted) return null;\n // Offline, blocked by CORS or the CSP, or timed out: try once more.\n }\n }\n return null;\n}\n\n/**\n * The response body, read a chunk at a time so a server that sends more than\n * MAX_IMAGE_BYTES (whatever its Content-Length said) is cut off there rather\n * than held in memory. Null if it was too large.\n */\nasync function readBody(\n response: Response,\n tooLarge: AbortController\n): Promise<Uint8Array | null> {\n if (!response.body) {\n const bytes = new Uint8Array(await response.arrayBuffer());\n return bytes.length > MAX_IMAGE_BYTES ? null : bytes;\n }\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (\n let chunk = await reader.read();\n !chunk.done;\n chunk = await reader.read()\n ) {\n total += chunk.value.length;\n if (total > MAX_IMAGE_BYTES) {\n tooLarge.abort();\n await reader.cancel().catch(() => {});\n return null;\n }\n chunks.push(chunk.value);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n\n/**\n * The image's media type: the server's, if it says it's an image, or else\n * read from the file's first bytes. Null for anything else (an error page\n * served with 200, say), which html-to-docx would fail to measure and drop.\n */\nfunction imageType(\n contentType: string | null,\n bytes: Uint8Array\n): string | null {\n const declared = contentType?.split(';')[0].trim().toLowerCase();\n if (declared?.startsWith('image/')) return declared;\n const match = SIGNATURES.find(([, signature]) =>\n signature.every((byte, index) => bytes[index] === byte)\n );\n return match?.[0] ?? null;\n}\n\n/**\n * Puts the image's alt text where it was, as a link to `src` when that's a web\n * URL and the image isn't already inside a link. With no alt text, the URL\n * itself is the text.\n */\nfunction replaceWithAltText(image: HTMLImageElement, src: string): void {\n const document = image.ownerDocument;\n const isWebUrl = WEB_URL.test(src);\n const text = image.getAttribute('alt')?.trim() || (isWebUrl ? src : '');\n if (!text) {\n image.remove();\n return;\n }\n if (!isWebUrl || image.closest('a')) {\n image.replaceWith(document.createTextNode(text));\n return;\n }\n const link = document.createElement('a');\n link.setAttribute('href', src);\n link.textContent = text;\n image.replaceWith(link);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"docx-images.js","sourceRoot":"","sources":["../src/docx-images.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,6EAA6E;AAC7E,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAEhD;;;;GAIG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,CAAC;AAE9B;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,CAAC;AAE7B,iFAAiF;AACjF,MAAM,UAAU,GAAG,IAAI,CAAC;AACxB,MAAM,QAAQ,GAAG,CAAC,CAAC;AAEnB;;;;GAIG;AACH,M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D,MAAM,QAAQ,GAAG,KAAK,CAAC,aAAa,CAAC;IACrC,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACnC,MAAM,IAAI,GAAG,KAAK,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;IACxE,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,KAAK,CAAC,MAAM,EAAE,CAAC;QACf,OAAO;IACT,CAAC;IACD,IAAI,CAAC,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QACpC,KAAK,CAAC,WAAW,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC;QACjD,OAAO;IACT,CAAC;IACD,MAAM,IAAI,GAAG,QAAQ,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;IACzC,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC/B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IACxB,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["import { Buffer } from 'buffer';\n\n/** html-to-docx's own limit for one image (imageProcessing.maxImageSize). */\nexport const MAX_IMAGE_BYTES = 10 * 1024 * 1024;\n\n/**\n * The most distinct image URLs fetched for one document: html-to-docx keeps\n * at most this many in its image cache (imageProcessing.maxCacheEntries). The\n * rest keep their alt text.\n */\nexport const MAX_IMAGES = 100;\n\n/**\n * How many downloads run at once. html-to-docx fetched one at a time; a few\n * in parallel is faster without opening a connection per image.\n */\nexport const CONCURRENCY = 4;\n\n/** Per attempt; the second attempt waits twice as long, as html-to-docx's do. */\nconst TIMEOUT_MS = 5000;\nconst ATTEMPTS = 2;\n\n/**\n * The URLs html-to-docx downloads (its `isValidUrl`, without the `g` flag\n * that makes `test()` stateful), anchored so the whole `src` is the URL.\n * Requiring both means this module never fetches what it wouldn't.\n */\nconst GENERATOR_URL =\n /http(s)?:\\/\\/(\\w+:?\\w*@)?(\\S+)(:\\d+)?((?<=\\.)\\w+)+(\\/([\\w#!:.?+=&%@!\\-/])*)?/i;\nconst WEB_URL = /^https?:\\/\\//i;\n\n/**\n * Leading bytes of the bitmap formats Word embeds. An image is checked\n * against them whatever its declared type: html-to-docx drops a file it can't\n * read (with its alt text), and embeds a format Word can't show, such as\n * HEIC, as a broken picture.\n */\nconst SIGNATURES: [string, number[]][] = [\n ['image/png', [0x89, 0x50, 0x4e, 0x47]],\n ['image/jpeg', [0xff, 0xd8, 0xff]],\n ['image/gif', [0x47, 0x49, 0x46, 0x38]],\n ['image/bmp', [0x42, 0x4d]],\n];\n\n/** The other format Word embeds, recognized by its root element. */\nconst SVG_TYPE = 'image/svg+xml';\n\n/** How far into a file to look for SVG_START. */\nconst SVG_SNIFF_BYTES = 4096;\n\n/** `data:[type][;params][;base64],payload` */\nconst DATA_URI = /^data:([^,]*?)(;base64)?,(.*)$/is;\n\nconst PERCENT = 0x25;\n\n/**\n * Downloads each web image in `html` and swaps its `src` for a `data:` URI,\n * which html-to-docx embeds without downloading it again. An image that can't\n * be fetched becomes its alt text, linked to its URL, where html-to-docx would\n * drop it without a trace. Other sources it can't embed either, such as a\n * relative path, keep their alt text too. So does a `data:` URI that isn't a\n * PNG, JPEG, GIF, BMP or SVG image; one that is gets rewritten as base64 of\n * the type its bytes show, which is the form html-to-docx reads.\n *\n * Each URL is fetched once, however many times it appears: at most\n * MAX_IMAGES of them, CONCURRENCY at a time.\n */\nexport async function embedImages(html: string): Promise<string> {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n const images = Array.from(dom.querySelectorAll('img'));\n if (images.length === 0) return html;\n\n const urls = new Set<string>();\n for (const image of images) {\n const src = image.getAttribute('src') ?? '';\n if (isFetchable(src) && urls.size < MAX_IMAGES) urls.add(src);\n }\n\n const queue = Array.from(urls);\n const downloads = new Map<string, string | null>();\n const worker = async (): Promise<void> => {\n for (let url = queue.shift(); url !== undefined; url = queue.shift()) {\n downloads.set(url, await fetchImage(url));\n }\n };\n await Promise.all(\n Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker)\n );\n\n for (const image of images) {\n const src = image.getAttribute('src') ?? '';\n const dataUri = /^data:/i.test(src)\n ? checkDataUri(src)\n : downloads.get(src);\n if (dataUri) {\n image.setAttribute('src', dataUri);\n } else {\n replaceWithAltText(image, src);\n }\n }\n\n return dom.body.innerHTML;\n}\n\n/**\n * `src`, a `data:` URI, as base64 of the image type its bytes show, or null\n * if it's malformed, too large, or not an image Word embeds.\n */\nfunction checkDataUri(src: string): string | null {\n const match = DATA_URI.exec(src);\n if (!match) return null;\n const [, type, base64, payload] = match;\n // At most four characters of payload make one byte (an escaped base64\n // character, %2B, is a quarter of three bytes), so one this long decodes\n // to more than the limit: turn it away before decoding allocates it.\n if (payload.length > MAX_IMAGE_BYTES * 4 + 4) return null;\n let bytes: Uint8Array | null;\n try {\n bytes = base64 ? base64Decode(payload) : percentDecode(payload);\n } catch {\n return null;\n }\n if (!bytes || bytes.length === 0 || bytes.length > MAX_IMAGE_BYTES) {\n return null;\n }\n const actual = imageType(type, bytes);\n if (!actual) return null;\n return `data:${actual};base64,${Buffer.from(bytes).toString('base64')}`;\n}\n\n/**\n * The bytes of a base64 `data:` payload, or null if it isn't base64. Decoded\n * as a browser does (the fetch spec's forgiving-base64): percent-escapes and\n * whitespace are allowed, any other stray character fails. `Buffer.from`\n * alone skips stray characters, which would embed a corrupted picture.\n */\nfunction base64Decode(payload: string): Uint8Array | null {\n let text = new TextDecoder().decode(percentDecode(payload));\n text = text.replace(/[\\t\\n\\f\\r ]+/g, '');\n if (text.length % 4 === 0) text = text.replace(/={1,2}$/, '');\n if (text.length % 4 === 1 || !/^[A-Za-z0-9+/]*$/.test(text)) return null;\n return Buffer.from(text, 'base64');\n}\n\n/**\n * The bytes of a URL-encoded `data:` payload. A `%` without two hex digits\n * after it stays a `%`, as in a browser, so `width=\"100%\"` in an SVG works.\n */\nfunction percentDecode(payload: string): Uint8Array {\n // `%` and hex digits are ASCII, so escapes can be read off the UTF-8 bytes.\n const encoded = new TextEncoder().encode(payload);\n const bytes = new Uint8Array(encoded.length);\n let length = 0;\n for (let index = 0; index < encoded.length; index++) {\n const hex =\n encoded[index] === PERCENT\n ? String.fromCharCode(...encoded.subarray(index + 1, index + 3))\n : '';\n if (/^[0-9a-f]{2}$/i.test(hex)) {\n bytes[length++] = parseInt(hex, 16);\n index += 2;\n } else {\n bytes[length++] = encoded[index];\n }\n }\n return bytes.subarray(0, length);\n}\n\nfunction isFetchable(src: string): boolean {\n return WEB_URL.test(src) && GENERATOR_URL.test(src);\n}\n\n/** The image at `url` as a `data:` URI, or null if it can't be fetched. */\nasync function fetchImage(url: string): Promise<string | null> {\n for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {\n const tooLarge = new AbortController();\n try {\n const response = await fetch(url, {\n signal: AbortSignal.any([\n tooLarge.signal,\n AbortSignal.timeout(TIMEOUT_MS * attempt),\n ]),\n });\n // Not found, forbidden or too large won't change on a retry.\n if (!response.ok) return null;\n if (Number(response.headers.get('content-length')) > MAX_IMAGE_BYTES) {\n tooLarge.abort();\n return null;\n }\n const bytes = await readBody(response, tooLarge);\n if (!bytes || bytes.length === 0) return null;\n const type = imageType(response.headers.get('content-type'), bytes);\n if (!type) return null;\n return `data:${type};base64,${Buffer.from(bytes).toString('base64')}`;\n } catch {\n if (tooLarge.signal.aborted) return null;\n // Offline, blocked by CORS or the CSP, or timed out: try once more.\n }\n }\n return null;\n}\n\n/**\n * The response body, read a chunk at a time so a server that sends more than\n * MAX_IMAGE_BYTES (whatever its Content-Length said) is cut off there rather\n * than held in memory. Null if it was too large.\n */\nasync function readBody(\n response: Response,\n tooLarge: AbortController\n): Promise<Uint8Array | null> {\n if (!response.body) {\n const bytes = new Uint8Array(await response.arrayBuffer());\n return bytes.length > MAX_IMAGE_BYTES ? null : bytes;\n }\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (\n let chunk = await reader.read();\n !chunk.done;\n chunk = await reader.read()\n ) {\n total += chunk.value.length;\n if (total > MAX_IMAGE_BYTES) {\n tooLarge.abort();\n await reader.cancel().catch(() => {});\n return null;\n }\n chunks.push(chunk.value);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n\n/**\n * The image's media type, read from its first bytes: PNG, JPEG, GIF or BMP,\n * whatever `declared` says, or SVG if it says so (or names no image type)\n * and the file starts like one. Null for anything else, such as an error\n * page served with 200, or HEIC, which html-to-docx would embed but Word\n * can't show.\n */\nfunction imageType(declared: string | null, bytes: Uint8Array): string | null {\n const match = SIGNATURES.find(([, signature]) =>\n signature.every((byte, index) => bytes[index] === byte)\n );\n if (match) return match[0];\n const type = declared?.split(';')[0].trim().toLowerCase() ?? '';\n if (type !== SVG_TYPE && type.startsWith('image/')) return null;\n const head = new TextDecoder().decode(bytes.subarray(0, SVG_SNIFF_BYTES));\n return startsWithSvg(head) ? SVG_TYPE : null;\n}\n\n/**\n * Whether `text` is an SVG file: `<svg` first, after at most a byte-order\n * mark, an XML declaration, comments and a doctype. Anchored, so an HTML page\n * with an inline icon doesn't count. A scan rather than one regular\n * expression, which backtracks exponentially on input like\n * `<!----><!----><!--...` (a comment's end can also be read as part of a\n * longer comment).\n */\nfunction startsWithSvg(text: string): boolean {\n let at = text.startsWith('\\uFEFF') ? 1 : 0;\n const skipSpace = (): void => {\n while (at < text.length && /\\s/.test(text[at] as string)) at++;\n };\n const startsHere = (prefix: string): boolean =>\n text.slice(at, at + prefix.length).toLowerCase() === prefix;\n /** Moves past `end`, searching from `from`; false if it never comes. */\n const skipPast = (end: string, from: number): boolean => {\n const index = text.indexOf(end, from);\n if (index === -1) return false;\n at = index + end.length;\n return true;\n };\n\n skipSpace();\n if (startsHere('<?xml')) {\n if (!skipPast('>', at)) return false;\n skipSpace();\n }\n for (;;) {\n if (startsHere('<!--')) {\n if (!skipPast('-->', at + 4)) return false;\n } else if (startsHere('<!doctype')) {\n if (!skipPast('>', at)) return false;\n } else {\n break;\n }\n skipSpace();\n }\n return startsHere('<svg') && /[\\s>]/.test(text[at + 4] ?? '');\n}\n\n/**\n * Puts the image's alt text where it was, as a link to `src` when that's a web\n * URL and the image isn't already inside a link. With no alt text, the URL\n * itself is the text.\n */\nfunction replaceWithAltText(image: HTMLImageElement, src: string): void {\n const document = image.ownerDocument;\n const isWebUrl = WEB_URL.test(src);\n const text = image.getAttribute('alt')?.trim() || (isWebUrl ? src : '');\n if (!text) {\n image.remove();\n return;\n }\n if (!isWebUrl || image.closest('a')) {\n image.replaceWith(document.createTextNode(text));\n return;\n }\n const link = document.createElement('a');\n link.setAttribute('href', src);\n link.textContent = text;\n image.replaceWith(link);\n}\n"]}
|
|
@@ -19,7 +19,16 @@ export interface DocumentStructure {
|
|
|
19
19
|
* - Section properties: the generator writes the body's `<w:sectPr>` (page
|
|
20
20
|
* size and margins) as its first child. The schema requires it last, and
|
|
21
21
|
* strict readers ignore it elsewhere, so it's moved to the end.
|
|
22
|
+
* - Image content types: the generator declares only JPEG, PNG and SVG in
|
|
23
|
+
* `[Content_Types].xml`, but embeds GIF and BMP too. Every part needs a
|
|
24
|
+
* declared type, and Word offers to repair a file that lacks one, so each
|
|
25
|
+
* image extension in `word/media/` gets a `<Default>`.
|
|
22
26
|
*/
|
|
23
27
|
export declare function patchStructure(wordDocument: Blob, structure: DocumentStructure): Promise<Blob>;
|
|
28
|
+
/**
|
|
29
|
+
* Adds a `<Default>` to `typesXml` for each image extension among `paths`
|
|
30
|
+
* under `word/media/` that it doesn't declare yet. Exported for testing.
|
|
31
|
+
*/
|
|
32
|
+
export declare function patchContentTypes(typesXml: string, paths: string[]): string;
|
|
24
33
|
/** Exported for testing. */
|
|
25
34
|
export declare function patchDocumentXml(documentXml: string, structure: DocumentStructure): string;
|
package/build/docx-structure.js
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import JSZip from 'jszip';
|
|
2
2
|
import { RULE_TEXT } from './docx-html.js';
|
|
3
3
|
import { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';
|
|
4
|
+
const CONTENT_TYPES = '[Content_Types].xml';
|
|
5
|
+
const CONTENT_TYPES_NS = 'http://schemas.openxmlformats.org/package/2006/content-types';
|
|
6
|
+
/** The media type of each image extension html-to-docx can write. */
|
|
7
|
+
const IMAGE_CONTENT_TYPES = {
|
|
8
|
+
png: 'image/png',
|
|
9
|
+
jpeg: 'image/jpeg',
|
|
10
|
+
jpg: 'image/jpeg',
|
|
11
|
+
gif: 'image/gif',
|
|
12
|
+
bmp: 'image/bmp',
|
|
13
|
+
svg: 'image/svg+xml',
|
|
14
|
+
};
|
|
4
15
|
/**
|
|
5
16
|
* Restores structure the generator drops or gets wrong:
|
|
6
17
|
*
|
|
@@ -15,6 +26,10 @@ import { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';
|
|
|
15
26
|
* - Section properties: the generator writes the body's `<w:sectPr>` (page
|
|
16
27
|
* size and margins) as its first child. The schema requires it last, and
|
|
17
28
|
* strict readers ignore it elsewhere, so it's moved to the end.
|
|
29
|
+
* - Image content types: the generator declares only JPEG, PNG and SVG in
|
|
30
|
+
* `[Content_Types].xml`, but embeds GIF and BMP too. Every part needs a
|
|
31
|
+
* declared type, and Word offers to repair a file that lacks one, so each
|
|
32
|
+
* image extension in `word/media/` gets a `<Default>`.
|
|
18
33
|
*/
|
|
19
34
|
export async function patchStructure(wordDocument, structure) {
|
|
20
35
|
const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());
|
|
@@ -24,14 +39,49 @@ export async function patchStructure(wordDocument, structure) {
|
|
|
24
39
|
}
|
|
25
40
|
const documentXml = await documentEntry.async('string');
|
|
26
41
|
const patched = patchDocumentXml(documentXml, structure);
|
|
27
|
-
|
|
42
|
+
const typesEntry = zip.file(CONTENT_TYPES);
|
|
43
|
+
const typesXml = typesEntry ? await typesEntry.async('string') : null;
|
|
44
|
+
const patchedTypes = typesXml === null
|
|
45
|
+
? null
|
|
46
|
+
: patchContentTypes(typesXml, Object.keys(zip.files));
|
|
47
|
+
if (patched === documentXml && patchedTypes === typesXml) {
|
|
28
48
|
return wordDocument;
|
|
29
49
|
}
|
|
30
50
|
zip.file('word/document.xml', patched);
|
|
51
|
+
if (patchedTypes !== null)
|
|
52
|
+
zip.file(CONTENT_TYPES, patchedTypes);
|
|
31
53
|
return new Blob([await zip.generateAsync({ type: 'arraybuffer' })], {
|
|
32
54
|
type: wordDocument.type,
|
|
33
55
|
});
|
|
34
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* Adds a `<Default>` to `typesXml` for each image extension among `paths`
|
|
59
|
+
* under `word/media/` that it doesn't declare yet. Exported for testing.
|
|
60
|
+
*/
|
|
61
|
+
export function patchContentTypes(typesXml, paths) {
|
|
62
|
+
const dom = new DOMParser().parseFromString(typesXml, 'application/xml');
|
|
63
|
+
const types = dom.documentElement;
|
|
64
|
+
const declared = new Set(Array.from(types.getElementsByTagNameNS(CONTENT_TYPES_NS, 'Default'), (d) => (d.getAttribute('Extension') ?? '').toLowerCase()));
|
|
65
|
+
let changed = false;
|
|
66
|
+
for (const path of paths) {
|
|
67
|
+
if (!path.startsWith('word/media/'))
|
|
68
|
+
continue;
|
|
69
|
+
const extension = /\.([^./]+)$/.exec(path)?.[1].toLowerCase();
|
|
70
|
+
const contentType = extension && IMAGE_CONTENT_TYPES[extension];
|
|
71
|
+
if (!contentType || declared.has(extension))
|
|
72
|
+
continue;
|
|
73
|
+
const entry = dom.createElementNS(CONTENT_TYPES_NS, 'Default');
|
|
74
|
+
entry.setAttribute('Extension', extension);
|
|
75
|
+
entry.setAttribute('ContentType', contentType);
|
|
76
|
+
// Defaults come before Overrides in the schema.
|
|
77
|
+
types.insertBefore(entry, types.getElementsByTagNameNS(CONTENT_TYPES_NS, 'Override')[0] ?? null);
|
|
78
|
+
declared.add(extension);
|
|
79
|
+
changed = true;
|
|
80
|
+
}
|
|
81
|
+
if (!changed)
|
|
82
|
+
return typesXml;
|
|
83
|
+
return keepXmlDeclaration(typesXml, new XMLSerializer().serializeToString(dom));
|
|
84
|
+
}
|
|
35
85
|
/** Exported for testing. */
|
|
36
86
|
export function patchDocumentXml(documentXml, structure) {
|
|
37
87
|
const dom = new DOMParser().parseFromString(documentXml, 'application/xml');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docx-structure.js","sourceRoot":"","sources":["../src/docx-structure.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,IAAI,IAAI,EAAE,MAAM,eAAe,CAAC;AAU9E;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,YAAkB,EAClB,SAA4B;IAE5B,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,MAAM,YAAY,CAAC,WAAW,EAAE,CAAC,CAAC;IACpE,MAAM,aAAa,GAAG,GAAG,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;IACpD,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CACb,gEAAgE,CACjE,CAAC;IACJ,CAAC;IAED,MAAM,WAAW,GAAG,MAAM,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACxD,MAAM,OAAO,GAAG,gBAAgB,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;IACzD,IAAI,OAAO,KAAK,WAAW,EAAE,CAAC;QAC5B,OAAO,YAAY,CAAC;IACtB,CAAC;IAED,GAAG,CAAC,IAAI,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;IACvC,OAAO,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C;IACD,IAAI,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC7C,6EAA6E;QAC7E,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,eAAe,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC;IAClE,CAAC;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,MAAe,EAAE,SAAiB;IAClD,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,MAAM,CACvC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,YAAY,KAAK,IAAI,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,CACxE,CAAC;AACJ,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport { RULE_TEXT } from './docx-html.js';\nimport { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';\n\n/** What the source HTML says about the document's rules and tables. */\nexport interface DocumentStructure {\n /** How many `<hr>` the HTML has. */\n rules: number;\n /** For each `<table>` in document order, whether its first row is a header. */\n headerRows: boolean[];\n}\n\n/**\n * Restores structure the generator drops or gets wrong:\n *\n * - Horizontal rules: each centered RULE_TEXT paragraph that stands in for an\n * `<hr>` (see prepareHtmlForDocx) becomes an empty paragraph with a bottom\n * border. They're matched in order against the number of `<hr>`, so a\n * paragraph that only happens to say `* * *` is left alone once they run out.\n * - Header rows: a table's header row gets `<w:tblHeader/>`, so Word repeats\n * it at the top of each page the table spans.\n * - Table grids: the generator writes a second `<w:tblGrid>` between rows,\n * which the schema doesn't allow; only the first is kept.\n * - Section properties: the generator writes the body's `<w:sectPr>` (page\n * size and margins) as its first child. The schema requires it last, and\n * strict readers ignore it elsewhere, so it's moved to the end.\n */\nexport async function patchStructure(\n wordDocument: Blob,\n structure: DocumentStructure\n): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const documentEntry = zip.file('word/document.xml');\n if (!documentEntry) {\n throw new Error(\n 'Cannot patch structure: document contains no word/document.xml'\n );\n }\n\n const documentXml = await documentEntry.async('string');\n const patched = patchDocumentXml(documentXml, structure);\n if (patched === documentXml) {\n return wordDocument;\n }\n\n zip.file('word/document.xml', patched);\n return new Blob([await zip.generateAsync({ type: 'arraybuffer' })], {\n type: wordDocument.type,\n });\n}\n\n/** Exported for testing. */\nexport function patchDocumentXml(\n documentXml: string,\n structure: DocumentStructure\n): string {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n let changed = false;\n\n let rulesLeft = structure.rules;\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n if (rulesLeft === 0) break;\n if (isRulePlaceholder(paragraph)) {\n drawRule(paragraph);\n rulesLeft--;\n changed = true;\n }\n }\n\n const tables = Array.from(dom.getElementsByTagNameNS(W_NS, 'tbl'));\n for (const [index, table] of tables.entries()) {\n const grids = children(table, 'tblGrid');\n for (const extra of grids.slice(1)) {\n extra.remove();\n changed = true;\n }\n\n const firstRow = children(table, 'tr')[0];\n if (structure.headerRows[index] && firstRow) {\n markHeaderRow(firstRow);\n changed = true;\n }\n }\n\n const body = dom.getElementsByTagNameNS(W_NS, 'body')[0];\n const sectPr = body && children(body, 'sectPr')[0];\n if (sectPr && body.lastElementChild !== sectPr) {\n body.appendChild(sectPr);\n changed = true;\n }\n\n if (!changed) {\n return documentXml;\n }\n return keepXmlDeclaration(\n documentXml,\n new XMLSerializer().serializeToString(dom)\n );\n}\n\nfunction isRulePlaceholder(paragraph: Element): boolean {\n const text = Array.from(paragraph.getElementsByTagNameNS(W_NS, 't'))\n .map((t) => t.textContent ?? '')\n .join('');\n const jc = children(children(paragraph, 'pPr')[0] ?? paragraph, 'jc')[0];\n return (\n text.trim() === RULE_TEXT && jc?.getAttributeNS(W_NS, 'val') === 'center'\n );\n}\n\n/** Replaces the paragraph's content with nothing but a bottom border. */\nfunction drawRule(paragraph: Element): void {\n const document = paragraph.ownerDocument;\n while (paragraph.firstChild) {\n paragraph.removeChild(paragraph.firstChild);\n }\n\n const pPr = paragraph.appendChild(document.createElementNS(W_NS, 'w:pPr'));\n const pBdr = pPr.appendChild(document.createElementNS(W_NS, 'w:pBdr'));\n const bottom = pBdr.appendChild(document.createElementNS(W_NS, 'w:bottom'));\n bottom.setAttributeNS(W_NS, 'w:val', 'single');\n bottom.setAttributeNS(W_NS, 'w:sz', '6');\n bottom.setAttributeNS(W_NS, 'w:space', '1');\n bottom.setAttributeNS(W_NS, 'w:color', 'auto');\n}\n\nfunction markHeaderRow(row: Element): void {\n const document = row.ownerDocument;\n let trPr = children(row, 'trPr')[0];\n if (!trPr) {\n trPr = row.insertBefore(\n document.createElementNS(W_NS, 'w:trPr'),\n row.firstChild\n );\n }\n if (children(trPr, 'tblHeader').length === 0) {\n // The generator writes at most cantSplit here, which comes before tblHeader.\n trPr.appendChild(document.createElementNS(W_NS, 'w:tblHeader'));\n }\n}\n\nfunction children(parent: Element, localName: string): Element[] {\n return Array.from(parent.children).filter(\n (child) => child.namespaceURI === W_NS && child.localName === localName\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"docx-structure.js","sourceRoot":"","sources":["../src/docx-structure.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,IAAI,IAAI,EAAE,MAAM,eAAe,CAAC;AAE9E,MAAM,aAAa,GAAG,qBAAqB,CAAC;AAC5C,MAAM,gBAAgB,GACpB,8DAA8D,CAAC;AAEjE,qEAAqE;AACrE,MAAM,mBAAmB,GAA2B;IAClD,GAAG,EAAE,WAAW;IAChB,IAAI,EAAE,YAAY;IAClB,GAAG,EAAE,YAAY;IACjB,GAAG,EAAE,WAAW;IAChB,GAAG,EAAE,WAAW;IAChB,GAAG,EAAE,eAAe;CACrB,CAAC;AAUF;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM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,QAAQ,CAAC,eAAe,CAAC,IAAI,EAAE,QAAQ,CAAC,EACxC,GAAG,CAAC,UAAU,CACf,CAAC;IACJ,CAAC;IACD,IAAI,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC7C,6EAA6E;QAC7E,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,eAAe,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC;IAClE,CAAC;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,MAAe,EAAE,SAAiB;IAClD,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,MAAM,CACvC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,YAAY,KAAK,IAAI,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,CACxE,CAAC;AACJ,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport { RULE_TEXT } from './docx-html.js';\nimport { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';\n\nconst CONTENT_TYPES = '[Content_Types].xml';\nconst CONTENT_TYPES_NS =\n 'http://schemas.openxmlformats.org/package/2006/content-types';\n\n/** The media type of each image extension html-to-docx can write. */\nconst IMAGE_CONTENT_TYPES: Record<string, string> = {\n png: 'image/png',\n jpeg: 'image/jpeg',\n jpg: 'image/jpeg',\n gif: 'image/gif',\n bmp: 'image/bmp',\n svg: 'image/svg+xml',\n};\n\n/** What the source HTML says about the document's rules and tables. */\nexport interface DocumentStructure {\n /** How many `<hr>` the HTML has. */\n rules: number;\n /** For each `<table>` in document order, whether its first row is a header. */\n headerRows: boolean[];\n}\n\n/**\n * Restores structure the generator drops or gets wrong:\n *\n * - Horizontal rules: each centered RULE_TEXT paragraph that stands in for an\n * `<hr>` (see prepareHtmlForDocx) becomes an empty paragraph with a bottom\n * border. They're matched in order against the number of `<hr>`, so a\n * paragraph that only happens to say `* * *` is left alone once they run out.\n * - Header rows: a table's header row gets `<w:tblHeader/>`, so Word repeats\n * it at the top of each page the table spans.\n * - Table grids: the generator writes a second `<w:tblGrid>` between rows,\n * which the schema doesn't allow; only the first is kept.\n * - Section properties: the generator writes the body's `<w:sectPr>` (page\n * size and margins) as its first child. The schema requires it last, and\n * strict readers ignore it elsewhere, so it's moved to the end.\n * - Image content types: the generator declares only JPEG, PNG and SVG in\n * `[Content_Types].xml`, but embeds GIF and BMP too. Every part needs a\n * declared type, and Word offers to repair a file that lacks one, so each\n * image extension in `word/media/` gets a `<Default>`.\n */\nexport async function patchStructure(\n wordDocument: Blob,\n structure: DocumentStructure\n): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const documentEntry = zip.file('word/document.xml');\n if (!documentEntry) {\n throw new Error(\n 'Cannot patch structure: document contains no word/document.xml'\n );\n }\n\n const documentXml = await documentEntry.async('string');\n const patched = patchDocumentXml(documentXml, structure);\n const typesEntry = zip.file(CONTENT_TYPES);\n const typesXml = typesEntry ? await typesEntry.async('string') : null;\n const patchedTypes =\n typesXml === null\n ? null\n : patchContentTypes(typesXml, Object.keys(zip.files));\n if (patched === documentXml && patchedTypes === typesXml) {\n return wordDocument;\n }\n\n zip.file('word/document.xml', patched);\n if (patchedTypes !== null) zip.file(CONTENT_TYPES, patchedTypes);\n return new Blob([await zip.generateAsync({ type: 'arraybuffer' })], {\n type: wordDocument.type,\n });\n}\n\n/**\n * Adds a `<Default>` to `typesXml` for each image extension among `paths`\n * under `word/media/` that it doesn't declare yet. Exported for testing.\n */\nexport function patchContentTypes(typesXml: string, paths: string[]): string {\n const dom = new DOMParser().parseFromString(typesXml, 'application/xml');\n const types = dom.documentElement;\n const declared = new Set(\n Array.from(types.getElementsByTagNameNS(CONTENT_TYPES_NS, 'Default'), (d) =>\n (d.getAttribute('Extension') ?? '').toLowerCase()\n )\n );\n let changed = false;\n for (const path of paths) {\n if (!path.startsWith('word/media/')) continue;\n const extension = /\\.([^./]+)$/.exec(path)?.[1].toLowerCase();\n const contentType = extension && IMAGE_CONTENT_TYPES[extension];\n if (!contentType || declared.has(extension)) continue;\n const entry = dom.createElementNS(CONTENT_TYPES_NS, 'Default');\n entry.setAttribute('Extension', extension);\n entry.setAttribute('ContentType', contentType);\n // Defaults come before Overrides in the schema.\n types.insertBefore(\n entry,\n types.getElementsByTagNameNS(CONTENT_TYPES_NS, 'Override')[0] ?? null\n );\n declared.add(extension);\n changed = true;\n }\n if (!changed) return typesXml;\n return keepXmlDeclaration(\n typesXml,\n new XMLSerializer().serializeToString(dom)\n );\n}\n\n/** Exported for testing. */\nexport function patchDocumentXml(\n documentXml: string,\n structure: DocumentStructure\n): string {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n let changed = false;\n\n let rulesLeft = structure.rules;\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n if (rulesLeft === 0) break;\n if (isRulePlaceholder(paragraph)) {\n drawRule(paragraph);\n rulesLeft--;\n changed = true;\n }\n }\n\n const tables = Array.from(dom.getElementsByTagNameNS(W_NS, 'tbl'));\n for (const [index, table] of tables.entries()) {\n const grids = children(table, 'tblGrid');\n for (const extra of grids.slice(1)) {\n extra.remove();\n changed = true;\n }\n\n const firstRow = children(table, 'tr')[0];\n if (structure.headerRows[index] && firstRow) {\n markHeaderRow(firstRow);\n changed = true;\n }\n }\n\n const body = dom.getElementsByTagNameNS(W_NS, 'body')[0];\n const sectPr = body && children(body, 'sectPr')[0];\n if (sectPr && body.lastElementChild !== sectPr) {\n body.appendChild(sectPr);\n changed = true;\n }\n\n if (!changed) {\n return documentXml;\n }\n return keepXmlDeclaration(\n documentXml,\n new XMLSerializer().serializeToString(dom)\n );\n}\n\nfunction isRulePlaceholder(paragraph: Element): boolean {\n const text = Array.from(paragraph.getElementsByTagNameNS(W_NS, 't'))\n .map((t) => t.textContent ?? '')\n .join('');\n const jc = children(children(paragraph, 'pPr')[0] ?? paragraph, 'jc')[0];\n return (\n text.trim() === RULE_TEXT && jc?.getAttributeNS(W_NS, 'val') === 'center'\n );\n}\n\n/** Replaces the paragraph's content with nothing but a bottom border. */\nfunction drawRule(paragraph: Element): void {\n const document = paragraph.ownerDocument;\n while (paragraph.firstChild) {\n paragraph.removeChild(paragraph.firstChild);\n }\n\n const pPr = paragraph.appendChild(document.createElementNS(W_NS, 'w:pPr'));\n const pBdr = pPr.appendChild(document.createElementNS(W_NS, 'w:pBdr'));\n const bottom = pBdr.appendChild(document.createElementNS(W_NS, 'w:bottom'));\n bottom.setAttributeNS(W_NS, 'w:val', 'single');\n bottom.setAttributeNS(W_NS, 'w:sz', '6');\n bottom.setAttributeNS(W_NS, 'w:space', '1');\n bottom.setAttributeNS(W_NS, 'w:color', 'auto');\n}\n\nfunction markHeaderRow(row: Element): void {\n const document = row.ownerDocument;\n let trPr = children(row, 'trPr')[0];\n if (!trPr) {\n trPr = row.insertBefore(\n document.createElementNS(W_NS, 'w:trPr'),\n row.firstChild\n );\n }\n if (children(trPr, 'tblHeader').length === 0) {\n // The generator writes at most cantSplit here, which comes before tblHeader.\n trPr.appendChild(document.createElementNS(W_NS, 'w:tblHeader'));\n }\n}\n\nfunction children(parent: Element, localName: string): Element[] {\n return Array.from(parent.children).filter(\n (child) => child.namespaceURI === W_NS && child.localName === localName\n );\n}\n"]}
|
package/build/font-presets.d.ts
CHANGED
|
@@ -34,6 +34,33 @@ export interface ParagraphStyle {
|
|
|
34
34
|
/** First-line indent, in characters of the body font size. */
|
|
35
35
|
firstLineIndentChars?: number;
|
|
36
36
|
}
|
|
37
|
+
/**
|
|
38
|
+
* How table cells are laid out. Cells sit outside the page grid: exact grid
|
|
39
|
+
* spacing would stretch every row and clip content that wraps.
|
|
40
|
+
*/
|
|
41
|
+
export interface TableStyle {
|
|
42
|
+
/** Word's 表格属性 → 单元格 → 垂直对齐方式. */
|
|
43
|
+
verticalAlign: 'top' | 'center' | 'bottom';
|
|
44
|
+
/** Line spacing of the paragraphs inside the cells. */
|
|
45
|
+
lineSpacing: LineSpacing;
|
|
46
|
+
/** Word's 如果定义了文档网格,则与网格对齐 (`w:snapToGrid`). */
|
|
47
|
+
snapToGrid: boolean;
|
|
48
|
+
}
|
|
49
|
+
/** How lists are laid out beyond the paragraph rules they share with the body. */
|
|
50
|
+
export interface ListStyle {
|
|
51
|
+
/**
|
|
52
|
+
* Bullet glyph per nesting level, the way Word's multi-level bullet library
|
|
53
|
+
* goes ● then ○ then ▪. Levels deeper than the list repeat its last glyph.
|
|
54
|
+
*/
|
|
55
|
+
bullets: string[];
|
|
56
|
+
/**
|
|
57
|
+
* Number nested ordered levels across the parent's number, so they read
|
|
58
|
+
* 1.1 and 1.1.1 the way Word's multi-level list does. This also makes every
|
|
59
|
+
* level of a list share one numbering definition, which is how Word counts
|
|
60
|
+
* them; without it the generator's per-level counters restart at 1.
|
|
61
|
+
*/
|
|
62
|
+
multilevelNumbers: boolean;
|
|
63
|
+
}
|
|
37
64
|
/** Paper and text block, in millimeters. */
|
|
38
65
|
export interface PageLayout {
|
|
39
66
|
widthMm: number;
|
|
@@ -61,6 +88,10 @@ export interface FontPreset {
|
|
|
61
88
|
* `pageMargins` take precedence.
|
|
62
89
|
*/
|
|
63
90
|
page?: PageLayout;
|
|
91
|
+
/** Layout for table cells, which sit outside the page grid. */
|
|
92
|
+
table?: TableStyle;
|
|
93
|
+
/** List layout, written into the numbering definitions. */
|
|
94
|
+
list?: ListStyle;
|
|
64
95
|
}
|
|
65
96
|
/**
|
|
66
97
|
* Chinese official documents (公文), after GB/T 9704-2012 《党政机关公文格式》:
|
|
@@ -83,6 +114,12 @@ export interface FontPreset {
|
|
|
83
114
|
* practice.
|
|
84
115
|
*/
|
|
85
116
|
export declare const CHINESE_OFFICIAL_DOC_FONTS: FontPreset;
|
|
117
|
+
/**
|
|
118
|
+
* The 公文 preset with multi-level numbering: nested items read 1.1 and 1.1.1,
|
|
119
|
+
* which is how contracts and similar instruments number their clauses rather
|
|
120
|
+
* than how a 公文 does.
|
|
121
|
+
*/
|
|
122
|
+
export declare const CHINESE_OFFICIAL_MULTILEVEL_FONTS: FontPreset;
|
|
86
123
|
export declare function mmToTwips(mm: number): number;
|
|
87
124
|
/** The presets offered in the UI, keyed by the value of their `<option>`. */
|
|
88
125
|
export declare const FONT_PRESETS: Record<string, FontPreset>;
|
package/build/font-presets.js
CHANGED
|
@@ -4,6 +4,11 @@ const BODY_FONT = '仿宋';
|
|
|
4
4
|
const SIZE_ER = 22;
|
|
5
5
|
/** Chinese size 3 (三号). */
|
|
6
6
|
const SIZE_SAN = 16;
|
|
7
|
+
/**
|
|
8
|
+
* Bullets per nesting level, as in Word's multi-level bullet library. The
|
|
9
|
+
* generator gives every level the same Symbol glyph, so nesting is invisible.
|
|
10
|
+
*/
|
|
11
|
+
const BULLET_GLYPHS = ['●', '○', '▪'];
|
|
7
12
|
/**
|
|
8
13
|
* Chinese official documents (公文), after GB/T 9704-2012 《党政机关公文格式》:
|
|
9
14
|
*
|
|
@@ -58,6 +63,19 @@ export const CHINESE_OFFICIAL_DOC_FONTS = {
|
|
|
58
63
|
marginsMm: { top: 37, right: 26, bottom: 35, left: 28 },
|
|
59
64
|
grid: { linesPerPage: 22, charsPerLine: 28 },
|
|
60
65
|
},
|
|
66
|
+
table: { verticalAlign: 'center', lineSpacing: 'single', snapToGrid: false },
|
|
67
|
+
// GB/T 9704-2012 §7.3.3 numbers its levels 一、 (一) 1. (1), not 1.1, so a
|
|
68
|
+
// 公文 does not count across parents. See CHINESE_OFFICIAL_MULTILEVEL_FONTS.
|
|
69
|
+
list: { bullets: BULLET_GLYPHS, multilevelNumbers: false },
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* The 公文 preset with multi-level numbering: nested items read 1.1 and 1.1.1,
|
|
73
|
+
* which is how contracts and similar instruments number their clauses rather
|
|
74
|
+
* than how a 公文 does.
|
|
75
|
+
*/
|
|
76
|
+
export const CHINESE_OFFICIAL_MULTILEVEL_FONTS = {
|
|
77
|
+
...CHINESE_OFFICIAL_DOC_FONTS,
|
|
78
|
+
list: { bullets: BULLET_GLYPHS, multilevelNumbers: true },
|
|
61
79
|
};
|
|
62
80
|
/** Twips (1/20 point) per millimeter. */
|
|
63
81
|
const TWIPS_PER_MM = 1440 / 25.4;
|
|
@@ -67,6 +85,7 @@ export function mmToTwips(mm) {
|
|
|
67
85
|
/** The presets offered in the UI, keyed by the value of their `<option>`. */
|
|
68
86
|
export const FONT_PRESETS = {
|
|
69
87
|
'chinese-official': CHINESE_OFFICIAL_DOC_FONTS,
|
|
88
|
+
'chinese-official-multilevel': CHINESE_OFFICIAL_MULTILEVEL_FONTS,
|
|
70
89
|
};
|
|
71
90
|
/**
|
|
72
91
|
* Whether most of the letters in `text` are Chinese characters, used to suggest
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"font-presets.js","sourceRoot":"","sources":["../src/font-presets.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"font-presets.js","sourceRoot":"","sources":["../src/font-presets.ts"],"names":[],"mappings":"AA8FA,MAAM,UAAU,GAAG,iBAAiB,CAAC;AACrC,MAAM,SAAS,GAAG,IAAI,CAAC;AAEvB,2BAA2B;AAC3B,MAAM,OAAO,GAAG,EAAE,CAAC;AACnB,2BAA2B;AAC3B,MAAM,QAAQ,GAAG,EAAE,CAAC;AAEpB;;;GAGG;AACH,MAAM,aAAa,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AAEtC;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAe;IACpD,IAAI,EAAE;QACJ,KAAK,EAAE,UAAU;QACjB,QAAQ,EAAE,SAAS;QACnB,MAAM,EAAE,QAAQ;QAChB,IAAI,EAAE,KAAK;KACZ;IACD,QAAQ,EAAE;QACR;YACE,KAAK,EAAE,UAAU;YACjB,QAAQ,EAAE,SAAS;YACnB,MAAM,EAAE,OAAO;YACf,IAAI,EAAE,KAAK;YACX,QAAQ,EAAE,IAA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e;IAC3D,GAAG,0BAA0B;IAC7B,IAAI,EAAE,EAAE,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAE,IAAI,EAAE;CAC1D,CAAC;AAEF,yCAAyC;AACzC,MAAM,YAAY,GAAG,IAAI,GAAG,IAAI,CAAC;AAEjC,MAAM,UAAU,SAAS,CAAC,EAAU;IAClC,OAAO,IAAI,CAAC,KAAK,CAAC,EAAE,GAAG,YAAY,CAAC,CAAC;AACvC,CAAC;AAED,6EAA6E;AAC7E,MAAM,CAAC,MAAM,YAAY,GAA+B;IACtD,kBAAkB,EAAE,0BAA0B;IAC9C,6BAA6B,EAAE,iCAAiC;CACjE,CAAC;AAEF;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,IAAY;IAC1C,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IACnD,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IACxD,MAAM,IAAI,GACR,IAAI,CAAC,KAAK,CAAC,4CAA4C,CAAC,EAAE,MAAM,IAAI,CAAC,CAAC;IAExE,OAAO,GAAG,IAAI,EAAE,IAAI,GAAG,GAAG,OAAO,IAAI,GAAG,IAAI,IAAI,GAAG,GAAG,GAAG,EAAE,CAAC;AAC9D,CAAC","sourcesContent":["/**\n * Typography for one level of a document.\n *\n * Word selects a typeface per character class: Latin letters and digits are\n * rendered from the `w:ascii`/`w:hAnsi` run-property slots, Chinese characters\n * from `w:eastAsia`. Naming both fonts per level is therefore enough to keep\n * Chinese text in a Chinese face and Latin text in a Latin one.\n */\nexport interface LevelStyle {\n /** Typeface for Latin letters, digits and punctuation. */\n latin: string;\n /** Typeface for Chinese characters. */\n eastAsia: string;\n /** Font size in points. Chinese named sizes: size 2 (二号) = 22pt, size 3 (三号) = 16pt. */\n sizePt: number;\n bold: boolean;\n /** Centers the paragraph, without the first-line indent. */\n centered?: boolean;\n}\n\n/**\n * Word line spacing rule:\n *\n * - `single`: single line spacing.\n * - `grid`: exact line spacing at the line pitch of the page's document grid,\n * with widow control off, so every full page holds `page.grid.linesPerPage`\n * lines. Needs `page.grid`.\n */\nexport type LineSpacing = 'single' | 'grid';\n\nexport interface ParagraphStyle {\n /** Paragraph spacing before and after, in points. */\n beforePt: number;\n afterPt: number;\n lineSpacing: LineSpacing;\n /** First-line indent, in characters of the body font size. */\n firstLineIndentChars?: number;\n}\n\n/**\n * How table cells are laid out. Cells sit outside the page grid: exact grid\n * spacing would stretch every row and clip content that wraps.\n */\nexport interface TableStyle {\n /** Word's 表格属性 → 单元格 → 垂直对齐方式. */\n verticalAlign: 'top' | 'center' | 'bottom';\n /** Line spacing of the paragraphs inside the cells. */\n lineSpacing: LineSpacing;\n /** Word's 如果定义了文档网格,则与网格对齐 (`w:snapToGrid`). */\n snapToGrid: boolean;\n}\n\n/** How lists are laid out beyond the paragraph rules they share with the body. */\nexport interface ListStyle {\n /**\n * Bullet glyph per nesting level, the way Word's multi-level bullet library\n * goes ● then ○ then ▪. Levels deeper than the list repeat its last glyph.\n */\n bullets: string[];\n /**\n * Number nested ordered levels across the parent's number, so they read\n * 1.1 and 1.1.1 the way Word's multi-level list does. This also makes every\n * level of a list share one numbering definition, which is how Word counts\n * them; without it the generator's per-level counters restart at 1.\n */\n multilevelNumbers: boolean;\n}\n\n/** Paper and text block, in millimeters. */\nexport interface PageLayout {\n widthMm: number;\n heightMm: number;\n marginsMm: { top: number; right: number; bottom: number; left: number };\n /** Word's document grid (文档网格): a fixed number of lines and characters. */\n grid?: { linesPerPage: number; charsPerLine: number };\n}\n\nexport interface FontPreset {\n body: LevelStyle;\n /** Six entries, applied to the `Heading1` - `Heading6` styles. */\n headings: LevelStyle[];\n /** Shared by the body text and every heading level. */\n paragraph: ParagraphStyle;\n /**\n * Page size and margins. Margins passed to `convertMarkdownToWord` as\n * `pageMargins` take precedence.\n */\n page?: PageLayout;\n /** Layout for table cells, which sit outside the page grid. */\n table?: TableStyle;\n /** List layout, written into the numbering definitions. */\n list?: ListStyle;\n}\n\nconst LATIN_FONT = 'Times New Roman';\nconst BODY_FONT = '仿宋';\n\n/** Chinese size 2 (二号). */\nconst SIZE_ER = 22;\n/** Chinese size 3 (三号). */\nconst SIZE_SAN = 16;\n\n/**\n * Bullets per nesting level, as in Word's multi-level bullet library. The\n * generator gives every level the same Symbol glyph, so nesting is invisible.\n */\nconst BULLET_GLYPHS = ['●', '○', '▪'];\n\n/**\n * Chinese official documents (公文), after GB/T 9704-2012 《党政机关公文格式》:\n *\n * - Body: FangSong (仿宋), size 3\n * - Heading 1 (the title): FZXiaoBiaoSong (方正小标宋简体), size 2, centered (7.3.1)\n * - Heading 2: SimHei (黑体), size 3\n * - Heading 3: KaiTi (楷体), size 3\n * - Heading 4: FangSong, size 3, bold. The standard sets levels 3 and 4 in\n * plain 仿宋, but a bolded fourth level is how these documents are made.\n * - Heading 5 and below: FangSong, size 3, not bold.\n * - A4 paper with a 37mm top and 28mm left margin around a 156 × 225mm text\n * block (5.1, 5.2.1)\n * - 22 lines of 28 characters per page (5.2.3), as a document grid with exact\n * line spacing at its pitch\n * - Paragraphs indented two characters (7.3.3), headings below the title too\n *\n * Every level uses Times New Roman for Latin text and no space before or after\n * paragraphs. The standard names no Latin font; Times New Roman is common\n * practice.\n */\nexport const CHINESE_OFFICIAL_DOC_FONTS: FontPreset = {\n body: {\n latin: LATIN_FONT,\n eastAsia: BODY_FONT,\n sizePt: SIZE_SAN,\n bold: false,\n },\n headings: [\n {\n latin: LATIN_FONT,\n eastAsia: '方正小标宋简体',\n sizePt: SIZE_ER,\n bold: false,\n centered: true,\n },\n { latin: LATIN_FONT, eastAsia: '黑体', sizePt: SIZE_SAN, bold: false },\n { latin: LATIN_FONT, eastAsia: '楷体', sizePt: SIZE_SAN, bold: false },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: true },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },\n { latin: LATIN_FONT, eastAsia: BODY_FONT, sizePt: SIZE_SAN, bold: false },\n ],\n paragraph: {\n beforePt: 0,\n afterPt: 0,\n lineSpacing: 'grid',\n firstLineIndentChars: 2,\n },\n page: {\n widthMm: 210,\n heightMm: 297,\n // 297 - 37 - 225 = 35 at the bottom, 210 - 28 - 156 = 26 on the right.\n marginsMm: { top: 37, right: 26, bottom: 35, left: 28 },\n grid: { linesPerPage: 22, charsPerLine: 28 },\n },\n table: { verticalAlign: 'center', lineSpacing: 'single', snapToGrid: false },\n // GB/T 9704-2012 §7.3.3 numbers its levels 一、 (一) 1. (1), not 1.1, so a\n // 公文 does not count across parents. See CHINESE_OFFICIAL_MULTILEVEL_FONTS.\n list: { bullets: BULLET_GLYPHS, multilevelNumbers: false },\n};\n\n/**\n * The 公文 preset with multi-level numbering: nested items read 1.1 and 1.1.1,\n * which is how contracts and similar instruments number their clauses rather\n * than how a 公文 does.\n */\nexport const CHINESE_OFFICIAL_MULTILEVEL_FONTS: FontPreset = {\n ...CHINESE_OFFICIAL_DOC_FONTS,\n list: { bullets: BULLET_GLYPHS, multilevelNumbers: true },\n};\n\n/** Twips (1/20 point) per millimeter. */\nconst TWIPS_PER_MM = 1440 / 25.4;\n\nexport function mmToTwips(mm: number): number {\n return Math.round(mm * TWIPS_PER_MM);\n}\n\n/** The presets offered in the UI, keyed by the value of their `<option>`. */\nexport const FONT_PRESETS: Record<string, FontPreset> = {\n 'chinese-official': CHINESE_OFFICIAL_DOC_FONTS,\n 'chinese-official-multilevel': CHINESE_OFFICIAL_MULTILEVEL_FONTS,\n};\n\n/**\n * Whether most of the letters in `text` are Chinese characters, used to suggest\n * the Chinese preset. Kana means Japanese, which also uses Han characters, so\n * text with a meaningful share of kana does not count.\n */\nexport function isMostlyChinese(text: string): boolean {\n const letters = text.match(/\\p{L}/gu)?.length ?? 0;\n const han = text.match(/\\p{Script=Han}/gu)?.length ?? 0;\n const kana =\n text.match(/[\\p{Script=Hiragana}\\p{Script=Katakana}]/gu)?.length ?? 0;\n\n return han >= 10 && han / letters >= 0.5 && kana < han / 10;\n}\n"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Checks for input that isn't Markdown, shared by the page (src/index.ts) and
|
|
2
|
+
// the `md2w` CLI (src/cli.ts) so both refuse the same files.
|
|
3
|
+
/** Word and other word-processor files: the reverse direction, word2md's job. */
|
|
4
|
+
export const WORD_FILE = /\.(docx?|dotx?|odt|rtf)$/i;
|
|
5
|
+
/** A file that's mostly binary isn't Markdown. NUL never appears in text. */
|
|
6
|
+
export function looksBinary(text) {
|
|
7
|
+
return text.slice(0, 8192).includes('\u0000');
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=input-checks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"input-checks.js","sourceRoot":"","sources":["../src/input-checks.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,6DAA6D;AAE7D,iFAAiF;AACjF,MAAM,CAAC,MAAM,SAAS,GAAG,2BAA2B,CAAC;AAErD,6EAA6E;AAC7E,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;AAChD,CAAC","sourcesContent":["// Checks for input that isn't Markdown, shared by the page (src/index.ts) and\n// the `md2w` CLI (src/cli.ts) so both refuse the same files.\n\n/** Word and other word-processor files: the reverse direction, word2md's job. */\nexport const WORD_FILE = /\\.(docx?|dotx?|odt|rtf)$/i;\n\n/** A file that's mostly binary isn't Markdown. NUL never appears in text. */\nexport function looksBinary(text: string): boolean {\n return text.slice(0, 8192).includes('\\u0000');\n}\n"]}
|
package/build/main.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export { convertMarkdownToWord, type ConversionOptions } from './converter.js';
|
|
2
2
|
export { extractTitle, parseMarkdownToHtml } from './markdown-parser.js';
|
|
3
|
-
export { CHINESE_OFFICIAL_DOC_FONTS, FONT_PRESETS, type FontPreset, type LevelStyle, type LineSpacing, type PageLayout, type ParagraphStyle, } from './font-presets.js';
|
|
3
|
+
export { CHINESE_OFFICIAL_DOC_FONTS, CHINESE_OFFICIAL_MULTILEVEL_FONTS, FONT_PRESETS, type FontPreset, type LevelStyle, type LineSpacing, type ListStyle, type PageLayout, type ParagraphStyle, type TableStyle, } from './font-presets.js';
|
package/build/main.js
CHANGED
|
@@ -3,5 +3,5 @@
|
|
|
3
3
|
// the DOM APIs the converter needs first.
|
|
4
4
|
export { convertMarkdownToWord } from './converter.js';
|
|
5
5
|
export { extractTitle, parseMarkdownToHtml } from './markdown-parser.js';
|
|
6
|
-
export { CHINESE_OFFICIAL_DOC_FONTS, FONT_PRESETS, } from './font-presets.js';
|
|
6
|
+
export { CHINESE_OFFICIAL_DOC_FONTS, CHINESE_OFFICIAL_MULTILEVEL_FONTS, FONT_PRESETS, } from './font-presets.js';
|
|
7
7
|
//# sourceMappingURL=main.js.map
|
package/build/main.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,+EAA+E;AAC/E,0CAA0C;AAC1C,OAAO,EAAE,qBAAqB,EAA0B,MAAM,gBAAgB,CAAC;AAC/E,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AACzE,OAAO,EACL,0BAA0B,EAC1B,YAAY,
|
|
1
|
+
{"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,+EAA+E;AAC/E,0CAA0C;AAC1C,OAAO,EAAE,qBAAqB,EAA0B,MAAM,gBAAgB,CAAC;AAC/E,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AACzE,OAAO,EACL,0BAA0B,EAC1B,iCAAiC,EACjC,YAAY,GAQb,MAAM,mBAAmB,CAAC","sourcesContent":["// The npm package's entry: the converter without the browser UI (index.ts).\n// Browsers and bundlers load this directly; Node loads node.ts, which supplies\n// the DOM APIs the converter needs first.\nexport { convertMarkdownToWord, type ConversionOptions } from './converter.js';\nexport { extractTitle, parseMarkdownToHtml } from './markdown-parser.js';\nexport {\n CHINESE_OFFICIAL_DOC_FONTS,\n CHINESE_OFFICIAL_MULTILEVEL_FONTS,\n FONT_PRESETS,\n type FontPreset,\n type LevelStyle,\n type LineSpacing,\n type ListStyle,\n type PageLayout,\n type ParagraphStyle,\n type TableStyle,\n} from './font-presets.js';\n"]}
|