Skip to content

Commit 3538552

Browse files
d3xter666matz3
andauthored
fix: Strip UTF-8 BOM from resources to prevent corruption in XML and properties files (#1637)
JIRA: CPOUI5FOUNDATION-1364 Resolves: #1601 Additionally JSON & HTML files saved with UTF-8 BOM were fixed, too --------- Co-authored-by: Matthias Osswald <mat.osswald@sap.com>
1 parent cf83a19 commit 3538552

10 files changed

Lines changed: 569 additions & 12 deletions

File tree

‎internal/documentation/docs/pages/Configuration.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,8 @@ If your project uses a different encoding for `*.properties` files, you need to
208208

209209
UI5 CLI will read the corresponding files of the project in the given encoding. Any non-ASCII characters will be replaced with the respective Unicode escape sequences. This allows you to deploy the resulting files to any environment, independent of how it expects `*.properties` files to be encoded. Please refer to [RFC 7](https://github.com/UI5/cli/blob/main/rfcs/0007-properties-file-encoding.md) for details.
210210

211+
If a `*.properties` file was accidentally saved with a leading UTF-8 Byte Order Mark (BOM), the BOM is removed during this process. Otherwise it would be escaped into a literal `\uFEFF` sequence at the start of the file, corrupting the first key.
212+
211213
## Custom Configuration
212214

213215
::: info

‎packages/builder/lib/lbt/bundle/AutoSplitter.js‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import {pd} from "pretty-data";
33
import {toRequireJSName} from "../utils/ModuleName.js";
44
import {SectionType} from "./BundleDefinition.js";
55
import escapePropertiesFile from "../utils/escapePropertiesFile.js";
6-
import {makeStringLiteral} from "../utils/stringUtils.js";
6+
import {makeStringLiteral, stripBOM} from "../utils/stringUtils.js";
77
import {getLogger} from "@ui5/logger";
88
const log = getLogger("lbt:bundle:AutoSplitter");
99

@@ -312,19 +312,22 @@ class AutoSplitter {
312312
return fileContent.length;
313313
} else if ( this.optimizeXMLViews && /\.view.xml$/.test(module) ) {
314314
// needs to be activated when it gets activated in JSMergedModuleBuilderExt
315-
let fileContent = await resource.buffer();
315+
let fileContent = stripBOM((await resource.buffer()).toString());
316316
if ( this.optimize ) {
317317
// For XML we use the pretty data
318318
// Do not minify if XML(View) contains an <*:pre> tag because whitespace of
319319
// HTML <pre> should be preserved (should only happen rarely)
320-
if (!xmlHtmlPrePattern.test(fileContent.toString())) {
321-
fileContent = pd.xmlmin(fileContent.toString(), false);
320+
if (!xmlHtmlPrePattern.test(fileContent)) {
321+
fileContent = pd.xmlmin(fileContent, false);
322322
}
323323
}
324324
return fileContent.length;
325325
}
326326

327327
// if there is no precompiled information about the resource, just determine its length
328+
// Note: this is a rough size estimate used only for split-point selection, so (unlike the
329+
// Builder and the optimizeXMLViews branch above) it does not strip a leading UTF-8 BOM.
330+
// A BOM'd resource is therefore counted ~3 bytes larger here, which is immaterial.
328331
if ( !resource.info && /\.(js|json|xml)$/.test(module) ) {
329332
const fileContent = await resource.buffer();
330333
return fileContent.length;

‎packages/builder/lib/lbt/bundle/Builder.js‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import {
1111
MODULE__UI5LOADER, MODULE__UI5LOADER_AUTOCONFIG,
1212
MODULE__JQUERY_SAP_GLOBAL, MODULE__SAP_UI_CORE_CORE} from "../UI5ClientConstants.js";
1313
import escapePropertiesFile from "../utils/escapePropertiesFile.js";
14-
import {makeStringLiteral, removeHashbang} from "../utils/stringUtils.js";
14+
import {makeStringLiteral, removeHashbang, stripBOM} from "../utils/stringUtils.js";
1515
import BundleResolver from "./Resolver.js";
1616
import BundleSplitter from "./AutoSplitter.js";
1717
import {SectionType} from "./BundleDefinition.js";
@@ -453,6 +453,11 @@ class BundleBuilder {
453453
outW.writeln(`function(){`);
454454
// The module should be written to a new line in order for dev-tools to map breakpoints to it
455455
outW.ensureNewLine();
456+
// Note: a leading UTF-8 BOM is not stripped here. The JS code is written verbatim, where a
457+
// U+FEFF is a valid whitespace character to the parser, so it does not corrupt the module.
458+
// Stripping it would also shift all byte offsets and invalidate the source map handled below.
459+
// (removeHashbang below still drops a hashbang that sits behind such a BOM, which otherwise
460+
// would be an invalid HashbangComment and break the bundle.)
456461
let moduleContent = (await resource.buffer()).toString();
457462
moduleContent = removeHashbang(moduleContent);
458463
if (this.options.sourceMap) {
@@ -473,6 +478,8 @@ class BundleBuilder {
473478
} else if ( /\.js$/.test(moduleName) /* implicitly: && info != null && info.requiresTopLevelScope */ ) {
474479
log.warn(
475480
`Module ${moduleName} requires top level scope and can only be embedded as a string (requires 'eval')`);
481+
// Note: a leading UTF-8 BOM is not stripped here either. The string literal is eval'd as JS,
482+
// where a leading U+FEFF is whitespace and does not corrupt the module (unlike XML/JSON/properties).
476483
let moduleContent = (await resource.buffer()).toString();
477484
moduleContent = removeHashbang(moduleContent);
478485
if (this.options.sourceMap) {
@@ -489,10 +496,10 @@ class BundleBuilder {
489496
}
490497
outW.write( makeStringLiteral(moduleContent) );
491498
} else if ( /\.html$/.test(moduleName) ) {
492-
const fileContent = (await resource.buffer()).toString();
499+
const fileContent = stripBOM((await resource.buffer()).toString());
493500
outW.write( makeStringLiteral( fileContent ) );
494501
} else if ( /\.json$/.test(moduleName) ) {
495-
let fileContent = (await resource.buffer()).toString();
502+
let fileContent = stripBOM((await resource.buffer()).toString());
496503
if ( this.optimize ) {
497504
try {
498505
fileContent = JSON.stringify( JSON.parse( fileContent) );
@@ -503,7 +510,7 @@ class BundleBuilder {
503510
}
504511
outW.write(makeStringLiteral(fileContent));
505512
} else if ( /\.xml$/.test(moduleName) ) {
506-
let fileContent = (await resource.buffer()).toString();
513+
let fileContent = stripBOM((await resource.buffer()).toString());
507514
if ( this.optimize ) {
508515
// For XML we use the pretty data
509516
// Do not minify if XML(View) contains an <*:pre> tag,

‎packages/builder/lib/lbt/utils/stringUtils.js‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,30 @@ export function makeStringLiteral(str) {
1313
}
1414

1515
export function removeHashbang(str) {
16-
return str.replace(/^#!(.*)/, "");
16+
// A hashbang is only a valid ECMAScript HashbangComment when "#!" are the first characters of the
17+
// source. If the file was saved with a UTF-8 BOM, the "#!" is no longer first and would become a
18+
// syntax error once embedded in a bundle. Match (and keep) an optional leading BOM so the hashbang
19+
// line is removed in that case too; the BOM is valid JS whitespace and is left untouched.
20+
return str.replace(/^(\uFEFF)?#!(.*)/, "$1");
21+
}
22+
23+
/**
24+
* Removes a leading UTF-8 Byte Order Mark (BOM, U+FEFF) from the given string.
25+
*
26+
* When a source file is saved as "UTF-8 with BOM", decoding its buffer to a string keeps the BOM
27+
* as a leading U+FEFF character. Inside a bundle this character ends up within the inlined string
28+
* literal, which breaks strict XML engines (e.g. the Rust-based DOMParser in Chromium 153+) and
29+
* corrupts the first key of *.properties files. A BOM in a UI5 source file is always unintended,
30+
* so it is stripped before the content is embedded.
31+
*
32+
* Note: We intentionally do not decode via TextDecoder (which strips a BOM on its own). It operates
33+
* on a Buffer rather than the already-decoded strings handled here, and its "latin1" label maps to
34+
* windows-1252 instead of the ISO-8859-1 that *.properties files rely on. This string-based helper
35+
* matches the de-facto "strip-bom" contract (remove exactly one leading U+FEFF) without those pitfalls.
36+
*
37+
* @param {string} str input string that might start with a BOM
38+
* @returns {string} the input string without a leading BOM
39+
*/
40+
export function stripBOM(str) {
41+
return str.charCodeAt(0) === 0xFEFF ? str.slice(1) : str;
1742
}

‎packages/builder/lib/processors/nonAsciiEscaper.js‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {escapeUnicode} from "escape-unicode";
2+
import {stripBOM} from "../lbt/utils/stringUtils.js";
23

34
/**
45
* @public
@@ -57,6 +58,13 @@ const escapeNonAscii = function(string) {
5758
/**
5859
* Escapes non ASCII characters with unicode escape sequences.
5960
*
61+
* A leading UTF-8 Byte Order Mark (BOM, U+FEFF) is removed before escaping. Otherwise it would be
62+
* escaped to a literal "\\uFEFF" sequence at the start of the content, corrupting the first key of
63+
* a *.properties file. The removal is gated on the decoded content starting with U+FEFF, not on the
64+
* encoding name: a UTF-8 BOM decodes to a leading U+FEFF and is removed, whereas an ISO-8859-1
65+
* (latin1) decode can never produce U+FEFF (its code points are limited to U+0000-U+00FF), so
66+
* latin1 files are left untouched.
67+
*
6068
* ```js
6169
* const encoding = nonAsciiEscaper.getEncodingFromAlias("ISO-8859-1");
6270
* nonAsciiEscaper({resources, options: {encoding}});
@@ -79,9 +87,16 @@ async function nonAsciiEscaper({resources, options: {encoding}}) {
7987

8088
async function processResource(resource) {
8189
const resourceString = (await resource.getBuffer()).toString(encoding);
82-
const escaped = escapeNonAscii(resourceString);
83-
// only modify the resource's string if it was changed
84-
if (escaped.modified) {
90+
// Strip a leading UTF-8 BOM before escaping. Otherwise the U+FEFF character would be escaped
91+
// to a literal "\\uFEFF" sequence at the very start of the content, silently corrupting the
92+
// first key of a *.properties file. This is the common choke point for both the standalone
93+
// escapeNonAsciiCharacters task and the bundler (via escapePropertiesFile), so handling it
94+
// here covers every path. Only UTF-8 input is affected: a BOM decoded as latin1 becomes the
95+
// three characters "" (not U+FEFF), so ISO-8859-1 byte semantics are preserved.
96+
const strippedString = stripBOM(resourceString);
97+
const escaped = escapeNonAscii(strippedString);
98+
// modify the resource if a BOM was stripped and/or non-ascii characters were escaped
99+
if (escaped.modified || strippedString !== resourceString) {
85100
resource.setString(escaped.string);
86101
return resource;
87102
}

‎packages/builder/test/lib/lbt/bundle/AutoSplitter.js‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,31 @@ test("_calcMinSize: properties resource", async (t) => {
341341
t.is(await autoSplitter._calcMinSize("mymodule.properties"), 10, "length of 1234\\u00df");
342342
});
343343

344+
test("_calcMinSize: properties resource with UTF-8 BOM does not count the BOM", async (t) => {
345+
const pool = {
346+
findResourceWithInfo: function() {
347+
let content = "\uFEFFKEY=val";
348+
return {
349+
buffer: async () => Buffer.from(content, "utf8"),
350+
resource: {
351+
setString: (string) => {
352+
content = string;
353+
},
354+
getBuffer: async () => Buffer.from(content, "utf8")
355+
},
356+
getProject: () => {
357+
return {
358+
getPropertiesFileSourceEncoding: () => "UTF-8"
359+
};
360+
}
361+
};
362+
}
363+
};
364+
const autoSplitter = new AutoSplitter(pool);
365+
t.is(await autoSplitter._calcMinSize("mymodule.properties"), "KEY=val".length,
366+
"leading BOM is stripped and not counted in the size");
367+
});
368+
344369
test("_calcMinSize: xml view resource", async (t) => {
345370
const pool = {
346371
findResourceWithInfo: function() {
@@ -355,6 +380,22 @@ test("_calcMinSize: xml view resource", async (t) => {
355380
t.is(await autoSplitter._calcMinSize("mymodule.view.xml"), 5);
356381
});
357382

383+
test("_calcMinSize: xml view resource with UTF-8 BOM does not count BOM bytes in size", async (t) => {
384+
const xmlContent = "<xml/>";
385+
const pool = {
386+
findResourceWithInfo: function() {
387+
return {
388+
buffer: async () => Buffer.from("\uFEFF" + xmlContent, "utf8"),
389+
getProject: () => undefined
390+
};
391+
}
392+
};
393+
const autoSplitter = new AutoSplitter(pool);
394+
autoSplitter.optimizeXMLViews = true;
395+
t.is(await autoSplitter._calcMinSize("mymodule.view.xml"), xmlContent.length,
396+
"the 3 BOM bytes are stripped and not counted");
397+
});
398+
358399
test("_calcMinSize: xml view resource without optimizeXMLViews", async (t) => {
359400
const pool = {
360401
findResourceWithInfo: function() {

0 commit comments

Comments
 (0)