fix(docx): keep the original root namespaces when regenerating a part (#63)

comments.xml and footnotes/endnotes.xml are rebuilt by splicing unchanged
entries back in as their original bytes, then wrapping them in a root with a
hardcoded namespace list. The bytes and the root disagree:

  w:comments declares w and w14, so a preserved comment holding
  <w:hyperlink r:id="..."> leaves r unbound
  NOTE_NS declares w and r, so a preserved paragraph holding w14:paraId,
  which Word writes on every paragraph, leaves w14 unbound

Both parse clean with fast-xml-parser's validator, which is not namespace
aware, and fail a namespace-aware parse with "unbound prefix". Word reports
that as unreadable content, so adding one comment to a document with a linked
comment, or one footnote to any Word-authored document, is enough.

Reuse the original part's root attributes when there is an original, keeping
the literal list only for parts created from scratch. The regression test
checks prefixes are bound rather than calling the XML validator, which cannot
see this class of defect.
This commit is contained in:
Waiel Al-Shujaa
2026-08-09 08:52:26 +08:00
committed by GitHub
parent d8305ff2dc
commit 6a2d1cd823
3 changed files with 86 additions and 7 deletions
+17 -1
View File
@@ -34,6 +34,22 @@ const NOTE_NS =
'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ' +
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"'
/**
* Root attributes for a regenerated part. Entries are spliced back in as original bytes, so
* the root has to keep declaring whatever prefixes those bytes use: Word puts w14:paraId on
* every paragraph it writes, and a literal namespace list leaves that prefix unbound.
*/
export function rootAttributes(
originalXml: string | null,
rootTag: string,
fallback: string,
): string {
const attrs = originalXml
? new RegExp(`<${rootTag}\\b([^>]*?)/?>`).exec(originalXml)?.[1]?.trim()
: undefined
return attrs && attrs.includes('xmlns:') ? attrs : fallback
}
/** real notes (separator entries excluded), in file order */
export function parseNotesXml(xml: string, kind: NoteKind): NoteInfo[] {
return noteEntriesOf(xml, kind).map(({ id, text, xml: entryXml }) => {
@@ -185,7 +201,7 @@ export function buildNotesXml(
.join('')
return (
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
`<${ROOT[kind]} ${NOTE_NS}>${structural}${body}</${ROOT[kind]}>`
`<${ROOT[kind]} ${rootAttributes(originalXml, ROOT[kind], NOTE_NS)}>${structural}${body}</${ROOT[kind]}>`
)
}
+7 -6
View File
@@ -5,6 +5,7 @@ import {
NOTE_PART_PATH,
NOTE_REL_TYPE,
buildNotesXml,
rootAttributes,
type NoteKind,
} from './notes'
import {
@@ -1353,6 +1354,10 @@ function headerFooterPartXml(
* their original bytes (rich formatting/multiple paragraphs/inline hyperlinks are
* preserved); only new or edited comments fall back to a plain-text rebuild.
*/
const COMMENTS_NS =
'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ' +
'xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml"'
function buildCommentsXml(comments: CommentInfo[], originalXml: string | null): string {
const originals = new Map<string, { text: string; xml: string }>()
if (originalXml) {
@@ -1387,12 +1392,8 @@ function buildCommentsXml(comments: CommentInfo[], originalXml: string | null):
return `<w:comment ${attrs}>${paras}</w:comment>`
})
.join('')
return (
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n' +
'<w:comments xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"' +
' xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml">' +
`${body}</w:comments>`
)
const ns = rootAttributes(originalXml, 'w:comments', COMMENTS_NS)
return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<w:comments ${ns}>${body}</w:comments>`
}
/** word/commentsExtended.xml: one commentEx per comment (reply parent-child + resolved flag) */
@@ -0,0 +1,62 @@
/**
* Regenerated parts splice original entry bytes back in, so their root has to keep declaring
* every prefix those bytes use. A literal namespace list leaves prefixes unbound, which Word
* reports as unreadable content. fast-xml-parser's validator does not catch this: it is not
* namespace-aware, so the check here has to be.
*/
import { describe, expect, it } from 'vitest'
import { buildNotesXml, rootAttributes } from '../src/notes'
/** every prefix used on an element or attribute must be declared on the root */
function unboundPrefixes(xml: string): string[] {
const root = /<([a-zA-Z][\w.-]*:[\w.-]+)\b([^>]*)>/.exec(xml.replace(/<\?[\s\S]*?\?>/, ''))
const declared = new Set(
[...(root?.[2] ?? '').matchAll(/xmlns:([\w.-]+)=/g)].map((m) => m[1]!).concat('xml'),
)
const used = new Set<string>()
for (const m of xml.matchAll(/<\/?([a-zA-Z][\w.-]*):/g)) used.add(m[1]!)
for (const m of xml.matchAll(/[\s"']([a-zA-Z][\w.-]*):[\w.-]+=["']/g)) used.add(m[1]!)
return [...used].filter((p) => !declared.has(p) && p !== 'xmlns')
}
describe('regenerated part namespaces', () => {
it('the check itself catches an unbound prefix', () => {
expect(unboundPrefixes('<w:x xmlns:w="w"><w:p w14:paraId="1"/></w:x>')).toEqual(['w14'])
expect(unboundPrefixes('<w:x xmlns:w="w" xmlns:w14="b"><w:p w14:paraId="1"/></w:x>')).toEqual(
[],
)
})
it('keeps the original root attributes when a part is regenerated', () => {
const original =
'<w:footnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"' +
' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"' +
' xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml">' +
'<w:footnote w:id="2"><w:p w14:paraId="4A2B1C0D" w14:textId="77BB0011">' +
'<w:r><w:t>original</w:t></w:r></w:p></w:footnote></w:footnotes>'
const out = buildNotesXml(
'footnote',
[
{ id: '2', text: 'original' },
{ id: '3', text: 'added' },
],
original,
)
expect(out).toContain('w14:paraId="4A2B1C0D"')
expect(unboundPrefixes(out)).toEqual([])
})
it('falls back to the literal namespaces when there is no original part', () => {
const out = buildNotesXml('footnote', [{ id: '2', text: 'fresh' }], null)
expect(unboundPrefixes(out)).toEqual([])
expect(out).toContain('xmlns:w=')
})
it('rootAttributes ignores a root that declares no namespaces', () => {
expect(rootAttributes('<w:comments>', 'w:comments', 'FALLBACK')).toBe('FALLBACK')
expect(rootAttributes(null, 'w:comments', 'FALLBACK')).toBe('FALLBACK')
expect(rootAttributes('<w:comments xmlns:w="a" xmlns:r="b">', 'w:comments', 'FALLBACK')).toBe(
'xmlns:w="a" xmlns:r="b"',
)
})
})