embedExactSourceMetadata function
Appends an invisible exact-source trailer to rendered.
The source is encoded from the exact Dart UTF-16 code-unit sequence rather than from a normalized form, so case, NFC/NFD choice, combining-mark order, punctuation, aliases, and even unpaired UTF-16 code units are retained.
Implementation
String embedExactSourceMetadata(String rendered, String originalSource) {
final bytes = _stringToUtf16Le(originalSource);
final encoded = base64Url.encode(bytes).replaceAll('=', '');
final sourceChecksum = _fnv1a32(bytes).toRadixString(16).padLeft(8, '0');
final renderedChecksum =
_fnv1a32(_stringToUtf16Le(rendered)).toRadixString(16).padLeft(8, '0');
final payload =
'$_exactSourceMagic$encoded:$sourceChecksum:$renderedChecksum';
final taggedPayload = <int>[_exactSourceStartTag];
for (final unit in payload.codeUnits) {
if (unit < 0x20 || unit > 0x7E) {
throw StateError('Exact-source payload unexpectedly contains non-ASCII.');
}
taggedPayload.add(0xE0000 + unit);
}
taggedPayload.add(_exactSourceEndTag);
return rendered + String.fromCharCodes(taggedPayload);
}