45 lines
2.4 KiB
JavaScript
45 lines
2.4 KiB
JavaScript
"use strict";
|
|
|
|
// adpanel:surrogate-safe-cut — JS strings are arrays of UTF-16 code units, so
|
|
// a length cap enforced with String.prototype.slice can land BETWEEN the two
|
|
// units of a surrogate pair (every astral character — emoji, CJK Extension B,
|
|
// ... — is two units). The stored half-pair is not valid text: Node's UTF-8
|
|
// encoder (and therefore mysql2) replaces a lone surrogate with U+FFFD, so
|
|
// the last visible character of the stored value is silently mangled — a
|
|
// 4-byte character straddling the cap corrupts exactly one character with no
|
|
// error anywhere. ONE helper owns every cap cut: slice to maxUnits, then drop
|
|
// a trailing lone high surrogate (0xD800-0xDBFF); a cut that would leave half
|
|
// a pair simply ends one character earlier. The result never ends with a
|
|
// lone high surrogate — a trailing high unit is ALWAYS unpaired (a complete
|
|
// pair ends with the low half), so trailing highs are dropped repeatedly
|
|
// until the tail is clean — including when a short input itself arrived
|
|
// ending with one (or with a run of them), which could only ever store as
|
|
// U+FFFD anyway. maxUnits counts UTF-16 code units (the same unit
|
|
// String.prototype.length and the existing slice-based caps were measured
|
|
// in), NOT code points, so caps calibrated against .length keep their exact
|
|
// meaning. Callers keep their own pre-cut cleaning (control-char strip,
|
|
// trim, whitespace collapse, \t rewrite) and any suffix ("[Message
|
|
// truncated]", "...") — those are per-surface contracts; this helper does
|
|
// the cut and nothing else. A lone LOW surrogate (or an interior lone
|
|
// surrogate of either half) is NOT cut-created — a slice ending on a low
|
|
// unit always has its high half inside — so pre-broken interior input is
|
|
// left for the caller's own cleaning and stores as U+FFFD exactly as before.
|
|
// Idempotent: a returned value re-run through the helper with the same cap
|
|
// is unchanged (its length is <= maxUnits and its last unit is never a lone
|
|
// high surrogate).
|
|
function isHighSurrogate(unit) {
|
|
return unit >= 0xd800 && unit <= 0xdbff;
|
|
}
|
|
|
|
function safeTruncateUtf16(value, maxUnits) {
|
|
const text = String(value);
|
|
if (!Number.isInteger(maxUnits) || maxUnits <= 0) return "";
|
|
let cut = text.length <= maxUnits ? text : text.slice(0, maxUnits);
|
|
while (cut.length > 0 && isHighSurrogate(cut.charCodeAt(cut.length - 1))) {
|
|
cut = cut.slice(0, -1);
|
|
}
|
|
return cut;
|
|
}
|
|
|
|
module.exports = { safeTruncateUtf16 };
|