the editable site (validation-lab)
This commit is contained in:
commit
3ac81d5a52
13454 files changed
+2227005
No files matched your search
+11
@@ -0,0 +1,11 @@
|
||||
Copyright (c) Felix Böhm
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
|
||||
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Replace the given code point with U+FFFD if it is NUL (0), a surrogate, or
|
||||
* outside the valid Unicode range. Code points in the C1 controls range
|
||||
* (128-159) are remapped to their Windows-1252 equivalents, following the
|
||||
* HTML spec. All other code points are returned unchanged.
|
||||
* @param codePoint Unicode code point to convert.
|
||||
*/
|
||||
export declare function replaceCodePoint(codePoint: number): number;
|
||||
/**
|
||||
* XML numeric character references are the referenced Unicode code point.
|
||||
* Invalid values still become U+FFFD; the HTML Windows-1252 C1 remap is not
|
||||
* applied.
|
||||
* @see https://www.w3.org/TR/xml/#NT-CharRef
|
||||
* @param codePoint Unicode code point to convert.
|
||||
*/
|
||||
export declare function replaceCodePointXML(codePoint: number): number;
|
||||
/**
|
||||
* Convert the code point of a decoded numeric entity to a string, replacing
|
||||
* invalid values.
|
||||
*
|
||||
* Fast path for plain BMP code points: [1..0x7F] and [0xA0..0xD7FF] pass
|
||||
* `replaceCodePoint` unchanged (no NUL, C1 remap, surrogate, or out-of-range
|
||||
* handling) and fit a single charCode. 0xd760 = 0xD800 (the first surrogate)
|
||||
* - 0xA0.
|
||||
* @param codePoint Unicode code point to convert.
|
||||
*/
|
||||
export declare function codePointToString(codePoint: number): string;
|
||||
//# sourceMappingURL=decode-codepoint.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"decode-codepoint.d.ts","sourceRoot":"","sources":["../src/decode-codepoint.ts"],"names":[],"mappings":"AAwBA;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAU1D;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAE7D;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAI3D"}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
// Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134
|
||||
/**
|
||||
* C1 Unicode control character reference replacements (code points 128-159).
|
||||
* Index i gives the replacement for code point 128+i; 0 means "no replacement".
|
||||
*/
|
||||
const c1 = [
|
||||
8364, 0, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, 8249, 338, 0,
|
||||
381, 0, 0, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732, 8482, 353, 8250,
|
||||
339, 0, 382, 376,
|
||||
];
|
||||
/**
|
||||
* True for NUL, UTF-16 surrogates, and values past U+10FFFF.
|
||||
* @param codePoint Unicode code point to check.
|
||||
*/
|
||||
function isInvalidCodePoint(codePoint) {
|
||||
return (codePoint === 0 ||
|
||||
(codePoint >= 0xd8_00 && codePoint <= 0xdf_ff) ||
|
||||
codePoint > 0x10_ff_ff);
|
||||
}
|
||||
/**
|
||||
* Replace the given code point with U+FFFD if it is NUL (0), a surrogate, or
|
||||
* outside the valid Unicode range. Code points in the C1 controls range
|
||||
* (128-159) are remapped to their Windows-1252 equivalents, following the
|
||||
* HTML spec. All other code points are returned unchanged.
|
||||
* @param codePoint Unicode code point to convert.
|
||||
*/
|
||||
export function replaceCodePoint(codePoint) {
|
||||
if (isInvalidCodePoint(codePoint)) {
|
||||
return 0xff_fd;
|
||||
}
|
||||
if (codePoint >= 128 && codePoint <= 159) {
|
||||
return c1[codePoint - 128] || codePoint;
|
||||
}
|
||||
return codePoint;
|
||||
}
|
||||
/**
|
||||
* XML numeric character references are the referenced Unicode code point.
|
||||
* Invalid values still become U+FFFD; the HTML Windows-1252 C1 remap is not
|
||||
* applied.
|
||||
* @see https://www.w3.org/TR/xml/#NT-CharRef
|
||||
* @param codePoint Unicode code point to convert.
|
||||
*/
|
||||
export function replaceCodePointXML(codePoint) {
|
||||
return isInvalidCodePoint(codePoint) ? 0xff_fd : codePoint;
|
||||
}
|
||||
/**
|
||||
* Convert the code point of a decoded numeric entity to a string, replacing
|
||||
* invalid values.
|
||||
*
|
||||
* Fast path for plain BMP code points: [1..0x7F] and [0xA0..0xD7FF] pass
|
||||
* `replaceCodePoint` unchanged (no NUL, C1 remap, surrogate, or out-of-range
|
||||
* handling) and fit a single charCode. 0xd760 = 0xD800 (the first surrogate)
|
||||
* - 0xA0.
|
||||
* @param codePoint Unicode code point to convert.
|
||||
*/
|
||||
export function codePointToString(codePoint) {
|
||||
return (codePoint - 1) >>> 0 < 0x7f || (codePoint - 0xa0) >>> 0 < 0xd7_60
|
||||
? String.fromCharCode(codePoint)
|
||||
: String.fromCodePoint(replaceCodePoint(codePoint));
|
||||
}
|
||||
//# sourceMappingURL=decode-codepoint.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"decode-codepoint.js","sourceRoot":"","sources":["../src/decode-codepoint.ts"],"names":[],"mappings":"AAAA,qHAAqH;AAErH;;;GAGG;AACH,MAAM,EAAE,GAAa;IACjB,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;IACxE,GAAG,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI;IACzE,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,GAAG;CACnB,CAAC;AAEF;;;GAGG;AACH,SAAS,kBAAkB,CAAC,SAAiB;IACzC,OAAO,CACH,SAAS,KAAK,CAAC;QACf,CAAC,SAAS,IAAI,OAAO,IAAI,SAAS,IAAI,OAAO,CAAC;QAC9C,SAAS,GAAG,UAAU,CACzB,CAAC;AACN,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAAC,SAAiB;IAC9C,IAAI,kBAAkB,CAAC,SAAS,CAAC,EAAE,CAAC;QAChC,OAAO,OAAO,CAAC;IACnB,CAAC;IAED,IAAI,SAAS,IAAI,GAAG,IAAI,SAAS,IAAI,GAAG,EAAE,CAAC;QACvC,OAAO,EAAE,CAAC,SAAS,GAAG,GAAG,CAAC,IAAI,SAAS,CAAC;IAC5C,CAAC;IAED,OAAO,SAAS,CAAC;AACrB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CAAC,SAAiB;IACjD,OAAO,kBAAkB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AAC/D,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,iBAAiB,CAAC,SAAiB;IAC/C,OAAO,CAAC,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,IAAI,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,OAAO;QACrE,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,SAAS,CAAC;QAChC,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC;AAC5D,CAAC"}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
/**
|
||||
* Decoding mode for named entities.
|
||||
*/
|
||||
export declare enum DecodingMode {
|
||||
/** Entities in text nodes that can end with any character. */
|
||||
Legacy = 0,
|
||||
/** Only allow entities terminated with a semicolon. */
|
||||
Strict = 1,
|
||||
/** Entities in attributes have limitations on ending characters. */
|
||||
Attribute = 2
|
||||
}
|
||||
/**
|
||||
* Decodes an HTML string.
|
||||
* @param htmlString The string to decode.
|
||||
* @param mode The decoding mode.
|
||||
* @returns The decoded string.
|
||||
*/
|
||||
export declare function decodeHTML(htmlString: string, mode?: DecodingMode): string;
|
||||
/**
|
||||
* Decodes an HTML string in an attribute.
|
||||
* @param htmlAttribute The string to decode.
|
||||
* @returns The decoded string.
|
||||
*/
|
||||
export declare function decodeHTMLAttribute(htmlAttribute: string): string;
|
||||
/**
|
||||
* Decodes an HTML string, requiring all entities to be terminated by a
|
||||
* semicolon.
|
||||
* @param htmlString The string to decode.
|
||||
* @returns The decoded string.
|
||||
*/
|
||||
export declare function decodeHTMLStrict(htmlString: string): string;
|
||||
/**
|
||||
* Decodes an XML string, requiring all entities to be terminated by a
|
||||
* semicolon.
|
||||
* @param xmlString The string to decode.
|
||||
* @returns The decoded string.
|
||||
*/
|
||||
export declare function decodeXML(xmlString: string): string;
|
||||
/**
|
||||
* Producers for character reference errors as defined in the HTML spec.
|
||||
*/
|
||||
export interface EntityErrorProducer {
|
||||
missingSemicolonAfterCharacterReference(): void;
|
||||
absenceOfDigitsInNumericCharacterReference(consumedCharacters: number): void;
|
||||
/**
|
||||
* Validate the accumulated numeric value, before Unicode replacement.
|
||||
* Values beyond the JavaScript number range are positive infinity.
|
||||
*/
|
||||
validateNumericCharacterReference(code: number): void;
|
||||
}
|
||||
/**
|
||||
* Token decoder with support of writing partial entities; the shared base
|
||||
* of `HtmlEntityDecoder` and `XmlEntityDecoder`. Numeric entities are
|
||||
* identical in both document types and are handled here; named entities are
|
||||
* left to the subclasses.
|
||||
*
|
||||
* The decoder is driven by a tokenizer: after a `&`, write the following
|
||||
* input (possibly in chunks). `write` returns the number of characters
|
||||
* consumed once the entity is decided, or -1 while more input is needed.
|
||||
* Rejection may surface later than strictly possible (the decoder buffers
|
||||
* until a terminator or the name-length limit), but emitted code points,
|
||||
* consumed counts, and final return values are exact.
|
||||
*/
|
||||
declare abstract class EntityDecoderBase {
|
||||
/**
|
||||
* The function that is called when a codepoint is decoded.
|
||||
*
|
||||
* For multi-byte named entities, this will be called multiple times,
|
||||
* with the second codepoint, and the same `consumed` value.
|
||||
* @param codepoint The decoded codepoint.
|
||||
* @param consumed The number of bytes consumed by the decoder.
|
||||
*/
|
||||
protected readonly emitCodePoint: (cp: number, consumed: number) => void;
|
||||
/** An object that is used to produce errors. */
|
||||
protected readonly errors?: EntityErrorProducer | undefined;
|
||||
/** The current state of the decoder. */
|
||||
protected state: number;
|
||||
/** Characters that were consumed while parsing an entity. */
|
||||
protected consumed: number;
|
||||
/** Accumulated numeric code point, or a packed partial XML name. */
|
||||
protected result: number;
|
||||
/** The mode in which the decoder is operating. */
|
||||
protected decodeMode: DecodingMode;
|
||||
/** Replacement rules for numeric character references. */
|
||||
protected readonly replaceNumericCodePoint: (codePoint: number) => number;
|
||||
constructor(
|
||||
/**
|
||||
* The function that is called when a codepoint is decoded.
|
||||
*
|
||||
* For multi-byte named entities, this will be called multiple times,
|
||||
* with the second codepoint, and the same `consumed` value.
|
||||
* @param codepoint The decoded codepoint.
|
||||
* @param consumed The number of bytes consumed by the decoder.
|
||||
*/
|
||||
emitCodePoint: (cp: number, consumed: number) => void,
|
||||
/** An object that is used to produce errors. */
|
||||
errors?: EntityErrorProducer | undefined);
|
||||
/**
|
||||
* Switches between the numeric decimal and hexadecimal states.
|
||||
*
|
||||
* Equivalent to the `Numeric character reference state` in the HTML spec.
|
||||
* @param input The string containing the entity (or a continuation of the entity).
|
||||
* @param offset The current offset.
|
||||
* @returns The number of characters that were consumed, or -1 if the entity is incomplete.
|
||||
*/
|
||||
private stateNumericStart;
|
||||
/**
|
||||
* Parses a hexadecimal numeric entity.
|
||||
*
|
||||
* Equivalent to the `Hexadecimal character reference state` in the HTML spec.
|
||||
* @param input The string containing the entity (or a continuation of the entity).
|
||||
* @param offset The current offset.
|
||||
* @returns The number of characters that were consumed, or -1 if the entity is incomplete.
|
||||
*/
|
||||
private stateNumericHex;
|
||||
/**
|
||||
* Parses a decimal numeric entity.
|
||||
*
|
||||
* Equivalent to the `Decimal character reference state` in the HTML spec.
|
||||
* @param input The string containing the entity (or a continuation of the entity).
|
||||
* @param offset The current offset.
|
||||
* @returns The number of characters that were consumed, or -1 if the entity is incomplete.
|
||||
*/
|
||||
private stateNumericDecimal;
|
||||
/**
|
||||
* Validate and emit a numeric entity.
|
||||
*
|
||||
* Implements the logic from the `Hexadecimal character reference start
|
||||
* state` and `Numeric character reference end state` in the HTML spec.
|
||||
* @param lastCp The last code point of the entity. Used to see if the
|
||||
* entity was terminated with a semicolon.
|
||||
* @param expectedLength The minimum number of characters that should be
|
||||
* consumed. Used to validate that at least one digit
|
||||
* was consumed.
|
||||
* @returns The number of characters that were consumed.
|
||||
*/
|
||||
private emitNumericEntity;
|
||||
/**
|
||||
* Resets the instance to make it reusable.
|
||||
* @param decodeMode Entity decoding mode to use.
|
||||
*/
|
||||
startEntity(decodeMode: DecodingMode): void;
|
||||
/**
|
||||
* Write an entity to the decoder. This can be called multiple times with partial entities.
|
||||
* If the entity is incomplete, the decoder will return -1.
|
||||
* @param input The string containing the entity (or a continuation of the entity).
|
||||
* @param offset The offset at which the entity begins. Should be 0 if this is not the first call.
|
||||
* @returns The number of characters that were consumed, or -1 if the entity is incomplete.
|
||||
*/
|
||||
write(input: string, offset: number): number;
|
||||
/**
|
||||
* Decode a named entity.
|
||||
* @param input The string containing the entity (or a continuation of the entity).
|
||||
* @param offset The current offset.
|
||||
* @returns The number of characters that were consumed, or -1 if the entity is incomplete.
|
||||
*/
|
||||
protected abstract stateNamedEntity(input: string, offset: number): number;
|
||||
/**
|
||||
* Resolve a named entity that was still incomplete when the input
|
||||
* ended.
|
||||
* @returns The number of characters that were consumed.
|
||||
*/
|
||||
protected abstract endNamedEntity(): number;
|
||||
/**
|
||||
* Signal to the parser that the end of the input was reached.
|
||||
*
|
||||
* Remaining data will be emitted and relevant errors will be produced.
|
||||
* @returns The number of characters consumed.
|
||||
*/
|
||||
end(): number;
|
||||
}
|
||||
/**
|
||||
* Streaming decoder for HTML entities.
|
||||
*
|
||||
* When the entity fits inside the current chunk (the common case), the
|
||||
* lookup runs directly on the chunk via the same length-probe scheme as the
|
||||
* synchronous decoder; chunk-boundary runs use a reusable character buffer.
|
||||
*/
|
||||
export declare class HtmlEntityDecoder extends EntityDecoderBase {
|
||||
/** Total name characters seen for the current named entity. */
|
||||
private runLength;
|
||||
/** Reused for ASCII alphanumerics; the 32nd character rules out an exact match. */
|
||||
private readonly nameBuffer;
|
||||
/**
|
||||
* Emit the replacement for a matched slot. Values are at most two
|
||||
* UTF-16 code units; like previous versions, each unit is emitted as
|
||||
* its own callback (surrogate halves included).
|
||||
* @param slot The matched slot.
|
||||
*/
|
||||
private emitSlot;
|
||||
startEntity(decodeMode: DecodingMode): void;
|
||||
protected stateNamedEntity(input: string, offset: number): number;
|
||||
protected endNamedEntity(): number;
|
||||
}
|
||||
/**
|
||||
* Streaming decoder for XML entities: the five predefined named entities
|
||||
* plus numeric character references.
|
||||
*/
|
||||
export declare class XmlEntityDecoder extends EntityDecoderBase {
|
||||
protected readonly replaceNumericCodePoint: (codePoint: number) => number;
|
||||
protected stateNamedEntity(input: string, offset: number): number;
|
||||
protected endNamedEntity(): number;
|
||||
}
|
||||
export { replaceCodePoint, replaceCodePointXML } from "./decode-codepoint.js";
|
||||
//# sourceMappingURL=decode.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"decode.d.ts","sourceRoot":"","sources":["../src/decode.ts"],"names":[],"mappings":"AA+DA;;GAEG;AACH,oBAAY,YAAY;IACpB,8DAA8D;IAC9D,MAAM,IAAI;IACV,uDAAuD;IACvD,MAAM,IAAI;IACV,oEAAoE;IACpE,SAAS,IAAI;CAChB;AAydD;;;;;GAKG;AACH,wBAAgB,UAAU,CACtB,UAAU,EAAE,MAAM,EAClB,IAAI,GAAE,YAAkC,GACzC,MAAM,CAER;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,CAEjE;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAiGnD;AAQD;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAChC,uCAAuC,IAAI,IAAI,CAAC;IAChD,0CAA0C,CACtC,kBAAkB,EAAE,MAAM,GAC3B,IAAI,CAAC;IACR;;;OAGG;IACH,iCAAiC,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;CACzD;AAED;;;;;;;;;;;;GAYG;AACH,uBAAe,iBAAiB;IAexB;;;;;;;OAOG;IACH,SAAS,CAAC,QAAQ,CAAC,aAAa,EAAE,CAC9B,EAAE,EAAE,MAAM,EAC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C/D,OAAO,CAAC,SAAS,CAAK;IAEtB,mFAAmF;IACnF,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAsB;IAEjD;;;;;OAKG;IACH,OAAO,CAAC,QAAQ;IASP,WAAW,CAAC,UAAU,EAAE,YAAY,GAAG,IAAI;IAKpD,SAAS,CAAC,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM;IAyHjE,SAAS,CAAC,cAAc,IAAI,MAAM;CAkBrC;AAyGD;;;GAGG;AACH,qBAAa,gBAAiB,SAAQ,iBAAiB;IACnD,mBAA4B,uBAAuB,EAAE,CACjD,SAAS,EAAE,MAAM,KAChB,MAAM,CAAuB;IAElC,SAAS,CAAC,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM;IA+BjE,SAAS,CAAC,cAAc,IAAI,MAAM;CAIrC;AAED,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC"}
|
||||
+1129
File diff suppressed because it is too large.
Load diff
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"decode.js","sourceRoot":"","sources":["../src/decode.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,GACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EACH,aAAa,EACb,aAAa,EACb,UAAU,EAEV,cAAc,EACd,SAAS,GACZ,MAAM,kCAAkC,CAAC;AAE1C,4EAA4E;AAC5E,MAAM,QAAQ,GAAG,EAAE,CAAC,CAAC,MAAM;AAC3B,MAAM,QAAQ,GAAG,EAAE,CAAC,CAAC,MAAM;AAC3B,MAAM,SAAS,GAAG,EAAE,CAAC,CAAC,MAAM;AAC5B,MAAM,WAAW,GAAG,EAAE,CAAC,CAAC,MAAM;AAC9B,MAAM,SAAS,GAAG,EAAE,CA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AC;AAE5B;;;;GAIG;AACH,SAAS,cAAc,CAAC,MAAc;IAClC,MAAM,QAAQ,GAAG,MAAM,KAAK,sBAAsB,CAAC;IACnD,OAAO,QAAQ,KAAK,yBAAyB;QACzC,CAAC,CAAC,mBAAmB;QACrB,CAAC,CAAC,QAAQ,CAAC;AACnB,CAAC;AAED,+EAA+E;AAC/E,MAAM,aAAa,GAAe,eAAe,CAAC,CAAC,GAAe,EAAE;IAChE,MAAM,MAAM,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC9C,KAAK,IAAILine truncated
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Encodes all characters in the input using HTML entities. This includes
|
||||
* characters that are valid ASCII characters in HTML documents, such as `#`.
|
||||
*
|
||||
* To get a more compact output, consider using the `encodeNonAsciiHTML`
|
||||
* function, which will only encode characters that are not valid in HTML
|
||||
* documents, as well as non-ASCII characters.
|
||||
*
|
||||
* If a character has no equivalent entity, a numeric decimal reference
|
||||
* (eg. `ü`) will be used.
|
||||
* @param input Input string to encode.
|
||||
*/
|
||||
export declare function encodeHTML(input: string): string;
|
||||
/**
|
||||
* Encodes all non-ASCII characters, as well as characters not valid in HTML
|
||||
* documents using HTML entities. This function will not encode characters that
|
||||
* are valid in HTML documents, such as `#`.
|
||||
*
|
||||
* If a character has no equivalent entity, a numeric decimal reference
|
||||
* (eg. `ü`) will be used.
|
||||
* @param input Input string to encode.
|
||||
*/
|
||||
export declare function encodeNonAsciiHTML(input: string): string;
|
||||
/** @internal Exported for tests; not re-exported from the package entry. */
|
||||
export declare const INLINE_SCAN_WINDOW = 16;
|
||||
//# sourceMappingURL=encode.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"encode.d.ts","sourceRoot":"","sources":["../src/encode.ts"],"names":[],"mappings":"AAmKA;;;;;;;;;;;GAWG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEhD;AACD;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAExD;AAwBD,4EAA4E;AAC5E,eAAO,MAAM,kBAAkB,KAAK,CAAC"}
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
import { XML_BITSET_VALUE, xmlEncodeRegex } from "./escape.js";
|
||||
import htmlTrieData from "./generated/encode-html.js";
|
||||
/**
|
||||
* Flat lookup table for ASCII entity values (code points 0–127).
|
||||
*
|
||||
* Built once at startup from the full trie. For ASCII characters that need
|
||||
* encoding, a direct `asciiEntities[charCode]` array index is much faster
|
||||
* than `Map.get(charCode)` because it avoids hashing and bucket lookup.
|
||||
*
|
||||
* A few ASCII characters also start multi-code-point entities
|
||||
* (e.g. `<` + U+20D2 → `<⃒`). For those, the table holds the branch
|
||||
* node itself (children plus the single-char value), so the ASCII path
|
||||
* never consults `htmlTrie`.
|
||||
*/
|
||||
const asciiEntities = /* #__PURE__ */ Array.from({ length: 128 }, () => null);
|
||||
const htmlTrie = (() => {
|
||||
/**
|
||||
* Parse a compact encode trie string into a Map keyed by code point.
|
||||
*
|
||||
* The serialized format (produced by `scripts/write-encode-map.ts`) stores
|
||||
* entries in ascending code-point order with delta encoding:
|
||||
*
|
||||
* [gap]name;[{children}]
|
||||
*
|
||||
* - `gap` is a base-10 integer giving `currentKey - previousKey - 1`.
|
||||
* The very first entry stores the absolute key. A gap of 0 is omitted.
|
||||
* - `name;` is the entity name (without `&` prefix) terminated by `;`.
|
||||
* Because gaps use only digits `[0-9]` and entity names always start with
|
||||
* a letter `[A-Za-z]`, no additional delimiter is needed.
|
||||
* - `{…}` is an optional children block using the same scheme recursively.
|
||||
* Children represent the second code unit of multi-character entities
|
||||
* (e.g. `<` + U+20D2 → `<⃒`).
|
||||
*/
|
||||
const trie = new Map();
|
||||
const data = htmlTrieData;
|
||||
let cursor = 0;
|
||||
let lastKey = -1;
|
||||
function readGap() {
|
||||
let value = 0;
|
||||
let ch;
|
||||
while ((ch = data.charCodeAt(cursor)) >= 48 /* '0' */ &&
|
||||
ch <= 57 /* '9' */) {
|
||||
value = value * 10 + ch - 48;
|
||||
cursor++;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function readEntity() {
|
||||
const semi = data.indexOf(";", cursor);
|
||||
const entity = `&${data.substring(cursor, semi)};`;
|
||||
cursor = semi + 1;
|
||||
return entity;
|
||||
}
|
||||
const astralEntries = [];
|
||||
while (cursor < data.length) {
|
||||
lastKey += readGap() + 1;
|
||||
const entityValue = data.charCodeAt(cursor) === 123 /* '{' */ ? null : readEntity();
|
||||
if (data.charCodeAt(cursor) === 123 /* '{' */) {
|
||||
cursor++; // Skip '{'
|
||||
const next = new Map();
|
||||
let childKey = -1;
|
||||
while (data.charCodeAt(cursor) !== 125 /* '}' */) {
|
||||
childKey += readGap() + 1;
|
||||
next.set(childKey, readEntity());
|
||||
}
|
||||
const branch = { value: entityValue, next };
|
||||
trie.set(lastKey, branch);
|
||||
cursor++; // Skip '}'
|
||||
// ASCII fast path holds the branch node itself (children + value).
|
||||
if (lastKey < 0x80) {
|
||||
asciiEntities[lastKey] = branch;
|
||||
}
|
||||
}
|
||||
else if (lastKey < 0x80) {
|
||||
asciiEntities[lastKey] = entityValue;
|
||||
}
|
||||
else if (lastKey > 0xff_ff) {
|
||||
astralEntries.push([lastKey, entityValue]);
|
||||
}
|
||||
else {
|
||||
trie.set(lastKey, entityValue);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* Batch-insert astral entries as surrogate-pair trie nodes.
|
||||
* Entries are sorted by code point, so same-high-surrogate groups
|
||||
* are contiguous — no intermediate grouping Map needed.
|
||||
*/
|
||||
let astralIndex = 0;
|
||||
while (astralIndex < astralEntries.length) {
|
||||
const hi = 0xd8_00 | ((astralEntries[astralIndex][0] - 0x1_00_00) >> 10);
|
||||
const children = [];
|
||||
while (astralIndex < astralEntries.length &&
|
||||
(0xd8_00 | ((astralEntries[astralIndex][0] - 0x1_00_00) >> 10)) ===
|
||||
hi) {
|
||||
const lo = 0xdc_00 |
|
||||
((astralEntries[astralIndex][0] - 0x1_00_00) & 0x3_ff);
|
||||
children.push([lo, astralEntries[astralIndex][1]]);
|
||||
astralIndex++;
|
||||
}
|
||||
trie.set(hi, { value: null, next: new Map(children) });
|
||||
}
|
||||
return trie;
|
||||
})();
|
||||
/**
|
||||
* Bitset covering ASCII code points 0–127. Each of the four 32-bit words
|
||||
* covers a 32-code-point range. A set bit means "this character needs
|
||||
* encoding" when used with `encodeHTML`.
|
||||
*/
|
||||
const HTML_BITSET = /* #__PURE__ */ new Uint32Array([
|
||||
0x16_00, // 09 (\t), 0A (\n), 0C (\f)
|
||||
0xfc_00_ff_fe, // 21-2D (!-.), 2E (.), 2F (/), 3A-3F (:;<=>?)
|
||||
0xf8_00_00_01, // 40 (@), 5B-5F ([\]^_)
|
||||
0x38_00_00_01, // 60 (`), 7B-7D ({|})
|
||||
]);
|
||||
const XML_BITSET = /* #__PURE__ */ new Uint32Array([0, XML_BITSET_VALUE, 0, 0]);
|
||||
/*
|
||||
* Regex equivalent of `HTML_BITSET` (plus all non-ASCII code units, lone
|
||||
* surrogates included — no `u` flag). Must stay in sync with the bitset:
|
||||
* the scan uses the regex to find candidates and the bitset to re-check
|
||||
* adjacent characters. The XML equivalent is `xmlEncodeRegex`, shared with
|
||||
* `escape.ts`.
|
||||
*/
|
||||
// eslint-disable-next-line unicorn/prefer-unicode-code-point-escapes -- the `\u{...}` form requires the `u` flag, which we deliberately omit so lone surrogates match by code unit
|
||||
const HTML_ENCODE_RE = /[\t\n\f!-/:-@[-`{-}\u0080-\uFFFF]/g;
|
||||
const numericReference = (cp) => `&#${cp};`;
|
||||
/**
|
||||
* Encodes all characters in the input using HTML entities. This includes
|
||||
* characters that are valid ASCII characters in HTML documents, such as `#`.
|
||||
*
|
||||
* To get a more compact output, consider using the `encodeNonAsciiHTML`
|
||||
* function, which will only encode characters that are not valid in HTML
|
||||
* documents, as well as non-ASCII characters.
|
||||
*
|
||||
* If a character has no equivalent entity, a numeric decimal reference
|
||||
* (eg. `ü`) will be used.
|
||||
* @param input Input string to encode.
|
||||
*/
|
||||
export function encodeHTML(input) {
|
||||
return encodeHTMLTrieRe(HTML_BITSET, HTML_ENCODE_RE, input);
|
||||
}
|
||||
/**
|
||||
* Encodes all non-ASCII characters, as well as characters not valid in HTML
|
||||
* documents using HTML entities. This function will not encode characters that
|
||||
* are valid in HTML documents, such as `#`.
|
||||
*
|
||||
* If a character has no equivalent entity, a numeric decimal reference
|
||||
* (eg. `ü`) will be used.
|
||||
* @param input Input string to encode.
|
||||
*/
|
||||
export function encodeNonAsciiHTML(input) {
|
||||
return encodeHTMLTrieRe(XML_BITSET, xmlEncodeRegex, input);
|
||||
}
|
||||
/**
|
||||
* Whether `code` (a UTF-16 code unit) must be encoded: any non-ASCII unit, or
|
||||
* an ASCII unit flagged in `bitset`.
|
||||
* @param bitset Bitset of ASCII characters to encode.
|
||||
* @param code Code unit to test.
|
||||
*/
|
||||
function isEncodable(bitset, code) {
|
||||
return code >= 0x80 || ((bitset[code >>> 5] >>> code) & 1) === 1;
|
||||
}
|
||||
/*
|
||||
* The inline scan beats the regex jump only for short gaps (measured
|
||||
* break-even is ~7 characters; below it the per-call regex overhead
|
||||
* dominates, above it the regex skips clean spans faster in native code).
|
||||
* So we scan at most `INLINE_SCAN_WINDOW` characters inline before deferring
|
||||
* to the regex. Any gap long enough to exhaust the window switches to
|
||||
* long-gap mode, which skips the inline scan entirely; we stay in that mode
|
||||
* while total gaps are at least `LONG_GAP_THRESHOLD` characters long and
|
||||
* drop back to the inline scan as soon as a shorter gap appears. Gaps are
|
||||
* always measured from where they start, so every window-exhausting gap
|
||||
* enters long-gap mode and no gap length pays both scans repeatedly.
|
||||
*/
|
||||
/** @internal Exported for tests; not re-exported from the package entry. */
|
||||
export const INLINE_SCAN_WINDOW = 16;
|
||||
const LONG_GAP_THRESHOLD = 8;
|
||||
function encodeHTMLTrieRe(bitset, re, input) {
|
||||
const { length } = input;
|
||||
let out;
|
||||
let last = 0; // Start of the next untouched slice.
|
||||
let index = 0;
|
||||
let wasLongGap = false; // The previous gap was long; skip the inline scan.
|
||||
while (index < length) {
|
||||
let char = input.charCodeAt(index);
|
||||
/*
|
||||
* Find the next encodable character (one matching `bitset`, or any
|
||||
* non-ASCII unit). Gaps between entities in dense text are only a
|
||||
* few characters, so scan a short window inline first; the regex —
|
||||
* which matches exactly the same characters and skips clean spans
|
||||
* in native code — runs for longer gaps. Gap lengths cluster, so
|
||||
* after a window-exhausting gap the window is skipped until a gap
|
||||
* shorter than LONG_GAP_THRESHOLD reappears. Once located, the
|
||||
* character is captured in `char` and control falls through to the
|
||||
* encode logic below instead of re-testing it on the next loop
|
||||
* iteration.
|
||||
*/
|
||||
if (!isEncodable(bitset, char)) {
|
||||
const gapStart = index;
|
||||
let next = index + 1;
|
||||
let wasFound = false;
|
||||
if (!wasLongGap) {
|
||||
const bound = Math.min(index + INLINE_SCAN_WINDOW, length);
|
||||
while (next < bound &&
|
||||
!isEncodable(bitset, (char = input.charCodeAt(next)))) {
|
||||
next++;
|
||||
}
|
||||
if (next < bound) {
|
||||
// `char` already holds the encodable unit at `next`.
|
||||
index = next;
|
||||
wasFound = true;
|
||||
}
|
||||
else if (next >= length) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!wasFound) {
|
||||
/*
|
||||
* Every match is a single code unit, so `test` pins it at
|
||||
* `lastIndex - 1` without allocating a match object.
|
||||
*/
|
||||
re.lastIndex = next;
|
||||
if (!re.test(input))
|
||||
break;
|
||||
index = re.lastIndex - 1;
|
||||
/*
|
||||
* Reaching the regex from the inline scan means the gap
|
||||
* exhausted the window, so it is long by definition; once
|
||||
* in long-gap mode, stay until a gap shorter than the
|
||||
* threshold appears.
|
||||
*/
|
||||
wasLongGap =
|
||||
!wasLongGap || index - gapStart >= LONG_GAP_THRESHOLD;
|
||||
char = input.charCodeAt(index);
|
||||
}
|
||||
}
|
||||
// Lazy-init: copy the prefix before the first character that needs encoding.
|
||||
if (out == null)
|
||||
out = input.substring(0, index);
|
||||
else if (last !== index)
|
||||
out += input.substring(last, index);
|
||||
if (char < 0x80) {
|
||||
const node = asciiEntities[char];
|
||||
if (typeof node === "object" && node !== null) {
|
||||
// Multi-code-point entity first (e.g. < + U+20D2 → <⃒).
|
||||
if (index + 1 < length) {
|
||||
const value = node.next.get(input.charCodeAt(index + 1));
|
||||
if (value != null) {
|
||||
out += value;
|
||||
last = index += 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out += node.value ?? numericReference(char);
|
||||
}
|
||||
else {
|
||||
out += node ?? numericReference(char);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Non-ASCII: full trie lookup with multi-char entity support.
|
||||
let node = htmlTrie.get(char);
|
||||
if (typeof node === "object") {
|
||||
if (index + 1 < length) {
|
||||
const value = node.next.get(input.charCodeAt(index + 1));
|
||||
if (value != null) {
|
||||
out += value;
|
||||
last = index += 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
node = node.value;
|
||||
}
|
||||
if (node == null) {
|
||||
// No named entity exists; emit a decimal numeric reference.
|
||||
const cp = input.codePointAt(index);
|
||||
out += numericReference(cp);
|
||||
// Astral code points consume two UTF-16 code units.
|
||||
if (cp !== char)
|
||||
index++;
|
||||
}
|
||||
else {
|
||||
out += node;
|
||||
}
|
||||
}
|
||||
last = index += 1;
|
||||
}
|
||||
// If nothing needed encoding, return the original string (avoids allocation).
|
||||
if (out == null)
|
||||
return input;
|
||||
if (last < length)
|
||||
out += input.substr(last);
|
||||
return out;
|
||||
}
|
||||
//# sourceMappingURL=encode.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"encode.js","sourceRoot":"","sources":["../src/encode.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC/D,OAAO,YAAY,MAAM,4BAA4B,CAAC;AAiBtD;;;;;;;;;;;GAWG;AAC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G,KAAK,CAAC;YACrB,IAAI,CAAC,UAAU,EAAE,CAAC;gBACd,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,GAAG,kBAAkB,EAAE,MAAM,CAAC,CAAC;gBAC3D,OACI,IAAI,GAAG,KAAK;oBACZ,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC,IAAI,GAAG,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,EACvD,CAAC;oBACC,IAAI,EAAE,CAAC;gBACX,CAAC;gBACD,IAAI,IAAI,GAAG,KAAK,EAAE,CAAC;oBACf,qDAAqD;oBACrD,KAAK,GAAG,IAAI,CAAC;oBACb,QAAQ,GAAG,IAAI,CAAC;gBACpB,CAAC;qBAAM,IAAI,IAAI,IAAI,MAAM,EAAE,CAAC;oBACxB,MAAM;gBACV,CAAC;YACL,CAAC;YACD,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACZ;;;mBAGG;gBACH,EAAE,CAAC,SAAS,GAAG,IAAI,CAAC;gBACpB,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC;oBAAE,MAAM;gBAC3B,KAAK,GAAG,EAAELine truncated
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Bitset for ASCII characters that need to be escaped in XML.
|
||||
*/
|
||||
export declare const XML_BITSET_VALUE = 1342177476;
|
||||
/**
|
||||
* Matches exactly the characters `encodeXML` escapes: the five XML special
|
||||
* characters plus every non-ASCII code unit (lone surrogates included — no
|
||||
* `u` flag). Kept in sync with `XML_BITSET_VALUE`.
|
||||
*
|
||||
* Shared with `encodeNonAsciiHTML` in `encode.ts`. Because the regex is
|
||||
* stateful (`g` flag), every call site must set `lastIndex` before use.
|
||||
*/
|
||||
export declare const xmlEncodeRegex: RegExp;
|
||||
/**
|
||||
* Encodes all non-ASCII characters, as well as characters not valid in XML
|
||||
* documents using XML entities.
|
||||
*
|
||||
* If a character has no equivalent entity, a numeric decimal reference
|
||||
* (eg. `ü`) will be used.
|
||||
* @param input Input string to encode.
|
||||
*/
|
||||
export declare function encodeXML(input: string): string;
|
||||
/**
|
||||
* Encodes all non-ASCII characters, as well as characters not valid in XML
|
||||
* documents using numeric decimal reference (eg. `ü`).
|
||||
*
|
||||
* Have a look at `escapeUTF8` if you want a more concise output at the expense
|
||||
* of reduced transportability.
|
||||
* @param data String to escape.
|
||||
*/
|
||||
export declare const escape: typeof encodeXML;
|
||||
/**
|
||||
* Encodes all characters not valid in XML documents using XML entities.
|
||||
*
|
||||
* Note that the output will be character-set dependent.
|
||||
* @param data String to escape.
|
||||
*/
|
||||
export declare function escapeUTF8(data: string): string;
|
||||
/**
|
||||
* Encodes all characters that have to be escaped in HTML attributes,
|
||||
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
|
||||
* @param data String to escape.
|
||||
*/
|
||||
export declare function escapeAttribute(data: string): string;
|
||||
/**
|
||||
* Encodes all characters that have to be escaped in HTML text,
|
||||
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
|
||||
* @param data String to escape.
|
||||
*/
|
||||
export declare function escapeText(data: string): string;
|
||||
//# sourceMappingURL=escape.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"escape.d.ts","sourceRoot":"","sources":["../src/escape.ts"],"names":[],"mappings":"AAkBA;;GAEG;AACH,eAAO,MAAM,gBAAgB,aAAgB,CAAC;AAE9C;;;;;;;GAOG;AAEH,eAAO,MAAM,cAAc,EAAE,MAAgC,CAAC;AAe9D;;;;;;;GAOG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAmD/C;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,MAAM,EAAE,OAAO,SAAqB,CAAC;AA2BlD;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE/C;AAID;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEpD;AAID;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE/C"}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* Get the named reference for an XML special character or U+00A0.
|
||||
* @param char Code unit matched by one of the escape regexes.
|
||||
*/
|
||||
function getEscape(char) {
|
||||
return char === 34
|
||||
? """
|
||||
: char === 38
|
||||
? "&"
|
||||
: char === 39
|
||||
? "'"
|
||||
: char === 60
|
||||
? "<"
|
||||
: char === 62
|
||||
? ">"
|
||||
: " ";
|
||||
}
|
||||
/**
|
||||
* Bitset for ASCII characters that need to be escaped in XML.
|
||||
*/
|
||||
export const XML_BITSET_VALUE = 0x50_00_00_c4; // 32..63 -> 34 ("),38 (&),39 ('),60 (<),62 (>)
|
||||
/**
|
||||
* Matches exactly the characters `encodeXML` escapes: the five XML special
|
||||
* characters plus every non-ASCII code unit (lone surrogates included — no
|
||||
* `u` flag). Kept in sync with `XML_BITSET_VALUE`.
|
||||
*
|
||||
* Shared with `encodeNonAsciiHTML` in `encode.ts`. Because the regex is
|
||||
* stateful (`g` flag), every call site must set `lastIndex` before use.
|
||||
*/
|
||||
// eslint-disable-next-line unicorn/prefer-unicode-code-point-escapes -- the `\u{...}` form requires the `u` flag, which we deliberately omit so lone surrogates match by code unit
|
||||
export const xmlEncodeRegex = /["&'<>\u0080-\uFFFF]/g;
|
||||
/**
|
||||
* Whether `code` (a UTF-16 code unit) is escaped by {@link encodeXML}: a
|
||||
* non-ASCII unit, or one of the five XML specials flagged in
|
||||
* `XML_BITSET_VALUE` (which is only meaningful for code units 32-63).
|
||||
* @param code Code unit to test.
|
||||
*/
|
||||
function isXmlEscapable(code) {
|
||||
return (code >= 0x80 ||
|
||||
(code >= 32 && code < 64 && ((XML_BITSET_VALUE >>> code) & 1) === 1));
|
||||
}
|
||||
/**
|
||||
* Encodes all non-ASCII characters, as well as characters not valid in XML
|
||||
* documents using XML entities.
|
||||
*
|
||||
* If a character has no equivalent entity, a numeric decimal reference
|
||||
* (eg. `ü`) will be used.
|
||||
* @param input Input string to encode.
|
||||
*/
|
||||
export function encodeXML(input) {
|
||||
const { length } = input;
|
||||
let out;
|
||||
let last = 0;
|
||||
let index = 0;
|
||||
while (index < length) {
|
||||
const char = input.charCodeAt(index);
|
||||
/*
|
||||
* Find the next character to escape: scan a short window inline
|
||||
* (escapable characters cluster in markup-heavy input), then fall
|
||||
* back to the regex, which skips clean spans in native code.
|
||||
*/
|
||||
if (!isXmlEscapable(char)) {
|
||||
const bound = Math.min(index + 32, length);
|
||||
let next = index + 1;
|
||||
while (next < bound && !isXmlEscapable(input.charCodeAt(next))) {
|
||||
next++;
|
||||
}
|
||||
if (next < bound) {
|
||||
index = next;
|
||||
continue;
|
||||
}
|
||||
if (next >= length)
|
||||
break;
|
||||
xmlEncodeRegex.lastIndex = next;
|
||||
if (!xmlEncodeRegex.test(input))
|
||||
break;
|
||||
index = xmlEncodeRegex.lastIndex - 1;
|
||||
continue;
|
||||
}
|
||||
if (out === undefined)
|
||||
out = input.substring(0, index);
|
||||
else if (last !== index)
|
||||
out += input.substring(last, index);
|
||||
if (char < 64) {
|
||||
// Known replacement
|
||||
out += getEscape(char);
|
||||
last = index += 1;
|
||||
continue;
|
||||
}
|
||||
// Non-ASCII: encode as numeric entity (handle surrogate pair)
|
||||
const cp = input.codePointAt(index);
|
||||
out += `&#${cp};`;
|
||||
if (cp !== char)
|
||||
index++; // Skip trailing surrogate
|
||||
last = index += 1;
|
||||
}
|
||||
if (out === undefined)
|
||||
return input;
|
||||
if (last < length)
|
||||
out += input.substr(last);
|
||||
return out;
|
||||
}
|
||||
/**
|
||||
* Encodes all non-ASCII characters, as well as characters not valid in XML
|
||||
* documents using numeric decimal reference (eg. `ü`).
|
||||
*
|
||||
* Have a look at `escapeUTF8` if you want a more concise output at the expense
|
||||
* of reduced transportability.
|
||||
* @param data String to escape.
|
||||
*/
|
||||
export const escape = encodeXML;
|
||||
/**
|
||||
* Escape `data` using `re`, mapping each matched character to its entity.
|
||||
* Every match is one UTF-16 code unit, so its index is `lastIndex - 1`.
|
||||
* @param re Global regex matching exactly the characters to escape
|
||||
* (`"`, `&`, `'`, `<`, `>`, `\u00A0` at most).
|
||||
* @param data String to escape.
|
||||
*/
|
||||
function escapeWithRegex(re, data) {
|
||||
re.lastIndex = 0;
|
||||
if (!re.test(data))
|
||||
return data;
|
||||
let out = "";
|
||||
let last = 0;
|
||||
do {
|
||||
const index = re.lastIndex - 1;
|
||||
if (last !== index)
|
||||
out += data.substring(last, index);
|
||||
const char = data.charCodeAt(index);
|
||||
out += getEscape(char);
|
||||
last = index + 1;
|
||||
} while (re.test(data));
|
||||
return out + data.substring(last);
|
||||
}
|
||||
const xmlEscapeRegex = /["&'<>]/g;
|
||||
/**
|
||||
* Encodes all characters not valid in XML documents using XML entities.
|
||||
*
|
||||
* Note that the output will be character-set dependent.
|
||||
* @param data String to escape.
|
||||
*/
|
||||
export function escapeUTF8(data) {
|
||||
return escapeWithRegex(xmlEscapeRegex, data);
|
||||
}
|
||||
const attributeEscapeRegex = /["&<>\u{A0}]/gu;
|
||||
/**
|
||||
* Encodes all characters that have to be escaped in HTML attributes,
|
||||
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
|
||||
* @param data String to escape.
|
||||
*/
|
||||
export function escapeAttribute(data) {
|
||||
return escapeWithRegex(attributeEscapeRegex, data);
|
||||
}
|
||||
const textEscapeRegex = /[&<>\u{A0}]/gu;
|
||||
/**
|
||||
* Encodes all characters that have to be escaped in HTML text,
|
||||
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
|
||||
* @param data String to escape.
|
||||
*/
|
||||
export function escapeText(data) {
|
||||
return escapeWithRegex(textEscapeRegex, data);
|
||||
}
|
||||
//# sourceMappingURL=escape.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"escape.js","sourceRoot":"","sources":["../src/escape.ts"],"names":[],"mappings":"A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e,CAAC;AAExC;;;;GAIG;AACH,MAAM,UAAU,UAAU,CAAC,IAAY;IACnC,OAAO,eAAe,CAAC,eAAe,EAAE,IAAI,CAAC,CAAC;AAClD,CAAC"}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Serialized decode data; the format is documented in
|
||||
* `src/internal/decode-data-format.ts`. `[0]` is one-byte data (all char
|
||||
* codes <= 0xFF: header, front-coded name suffixes, per-name metadata,
|
||||
* cuckoo choice bits); `[1]` holds the replacement values.
|
||||
*/
|
||||
export declare const htmlDecodeData: readonly [string, string];
|
||||
//# sourceMappingURL=decode-data-html.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"decode-data-html.d.ts","sourceRoot":"","sources":["../../src/generated/decode-data-html.ts"],"names":[],"mappings":"AAGA;;;;;GAKG;AAEH,eAAO,MAAM,cAAc,EAAE,SAAS,CAAC,MAAM,EAAE,MAAM,CAA8iyB,CAAC"}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
// Generated using scripts/write-decode-map.ts
|
||||
/* eslint-disable unicorn/prefer-unicode-code-point-escapes -- Fixed-width escapes keep generated source compact. */
|
||||
/**
|
||||
* Serialized decode data; the format is documented in
|
||||
* `src/internal/decode-data-format.ts`. `[0]` is one-byte data (all char
|
||||
* codes <= 0xFF: header, front-coded name suffixes, per-name metadata,
|
||||
* cuckoo choice bits); `[1]` holds the replacement values.
|
||||
*/
|
||||
// biome-ignore format: generated data
|
||||
export const htmlDecodeData = ["Q=¨`p0AEligMPacutebrevecircyfrgravelphamacrndogonpfpplyFunctionringscrsigntildeumlBackslashrvwedcyecausernoullistafropfrevescrumpeqCHcyOPYacutepitalDifferentialDyleyscaronedilirconintdotedillanterDotfrhiircleDotMinusPlusTimeslockwiseContourIntegralseCurlyDoubleQuoteQuoteolonengruentinttourIntegralpfroductunterClockwiseContourIntegralrossscrupCapDDotrahdJcyScyZcyaggerrrshvcaronyeltafriacriticalAcuteDotubleAcuteGraveTildemondfferentialDopftDotEqualubleContourIntegralDotwnArrowLeftArrowRightArrowTeeongLeftArrowRightArrowRightArrowRightArrowTeeUpArrowDownArrowVerticalBarwnArrowBarUpArrowBreveLeftRightVectorTeeVectorVectorBarRightTeeVectorVectorBarTeeArrowarrowscrtrokENGTHacutecaronircydotfrgravelementmacrptySmallSquareVerySmallSquareogonpfpsilonqualTildeilibriumscrimtaumlxistsponentialEFcyfrilledSmallSquareVerySmallSquareopfrAlluriertrfscrGJcyTammadbrevecedilircydotfrgopfreaterEqualLessFullEqualGreaterLessSlantEqualTildescrtHARDcyacektcircfrilbertSpaceopfrizontalLinescrtrokumpDownHumpEqualIEcyJligOcyacutecircydotfrgravemacrginaryIpliesntegralrsectionvisibleCommaTimesogonpftascrtildeukcymlJcircyfropfscrercyukcyKHcyJcyappacedilyfropfscrLJcyTacutembdangplacetrfrrcaronedilyeftAngleBracketrrowBarRightArrowCeilingDoubleBracketwnTeeVectorVectorBarFloorRightArrowVectorTeeArrowVectorriangleBarEqualUpDownVectorTeeVectorVectorBarVectorBararrowrightarrowssEqualGreaterFullEqualGreaterLessSlantEqualTildefrleftarrowmidotongLeftArrowRightArrowRightArrowleftarrowrightarrowrightarrowpfwerLeftArrowRightArrowscrhtroktMapcyediumSpacellintrffrinusPlusopfscruNJcyacutecaronedilyegativeMediumSpaceThickSpacenSpaceVeryThinSpacestedGreaterGreaterLessLesswLinefroBreaknBreakingSpacepftCongruentupCapDoubleVerticalBarElementqualTildexistsGreaterEqualFullEqualGreaterLessSlantEqualTildeHumpDownHumpEqualLeftTriangleBarEqualssEqualGreaterLessSlantEqualTildeNestedGreaterGreaterLessLessPrecedesEqualSlantEqualReverseElementightTriangleBarEqualSquareSubsetEqualpersetEqualubsetEqualcceedsEqualSlantEqualTildepersetEqualTildeEqualFullEqualTildeVerticalBarscrtildeuOEligacutecircydblacfrgravemacregaicronopfpenCurlyDoubleQuoteQuoterscrlashtildemesumlverBarraceketParenthesisPartialDcyfrhiilusMinusoincareplanepfrecedesEqualSlantEqualTildeimeoductportionalscriQUOTfropfscrRBarrEGacutengrrtlcaronedilyeverseElementquilibriumUpEquilibriumfrhoightAngleBracketrrowBarLeftArrowCeilingDoubleBracketwnTeeVectorVectorBarFloorTeeArrowVectorriangleBarEqualUpDownVectorTeeVectorVectorBarVectorBararrowopfundImpliesrightarrowscrhuleDelayedSHCHcycyOFTcyacutecaronedilircyfrhortDownArrowLeftArrowRightArrowUpArrowigmamallCircleopfqrtuareIntersectionSubsetEqualpersetEqualUnionscrtarubsetEqualcceedsEqualSlantEqualTildehThatmpersetEqualsetTHORNRADESHcycyabucaronedilyfrhereforetaickSpacenSpaceildeEqualFullEqualTildeopfripleDotscrtrokUacuterrocirbrcyevecircydblacfrgravemacrnderBarraceketParenthesisionPlusogonpfpArrowBarDownArrowDownArrowEquilibriumTeeArrowarrowdownarrowperLeftArrowRightArrowsilonringscrtildeumlVDashbarcydashleerbarticalBarLineSeparatorTildeyThinSpacefropfscrvdashWcircedgefropfscrXfriopfscrYAcyIcyUcyacutecircyfropfscrumlZHcyacutecaronydoteroWidthSpacetafropfscraacutebrevecEdircuteyeligfrgravelefsymphphamacrlgpndanddslopevgelemsdaabcdefghrtvbdsphtzarrogonpfpEacireidosproxeqringscrtympeqtildeumlwconintintbNotackcongepsilonprimesimeqrveewedgebrktbrkcongydquoecausemptyvpsirnoutahweenfrigcapircupodotplustimessqcuptartriangledownupuplusveewedgekarowlacklozengesquaretriangledownleftrightnkk12434ocknequivotopfttomwtiexDLRlrHDUduULRlrVHLRhlrboxdLRlrhDUduminusplustimesuLRlrvHLRhlrprimerevevbarscremiimeolbhsubulletmpEeqcacutepandbrcupcapupdotsretoncapsronedilircupssmdotedilmptyvnterdotfrhcyeckmarkiirEceqlearrowleftrightdRSastcircdashefnintmidscirlubsuitoloneqmmatpfnlementxesngdotintpfrodysrrarrossscrubepetdotudarrlreprsclarrppbrcapcapupdotorsrarrmlyeqprecsuccveewedgerenvearrowleftrightveewedwconintintylctydArrHaraggerlethrrshvbkarowlaccaronydaggerrrotseqegltamptyvfishtrharlriamondsuitsegammasinvideontimesonxjcylcornropollarpfteqdotminusplussquareublebarwedgewnarrowdownarrowsharpoonleftrightrbkarowcornropscryoltroktdotrifuarrharwanglezcyigrarreDDototacutestercaronircolonydotefDotrgravesdotlinterslsdotmacrptysetvsp134ngspogonpfparsllussilonvqcircolonsimlantgtrlessualsestivDDvparslrDotarrscrdotimtahumlroxclistpectationonentialefallingdotseqcyemalefiligligligriligjliglatligtnsnofopfrallkvpartintrac123456823534584556878slownscrgElacutemmadpbrevecircydotelqqslantsccdotollesfrggimeljcylEajnEapproxeqqsimopfravescrimeltccirdotlParquestrapproxrrdoteqlessqlesslesssimvertneqqnEhArrairsplfmiltrdcyrcirwbarcirceartsuitlliprconfrksearowwarowoarrmthtokleftarrowrightarrowpfrbarscrlashtrokybullpheniacutecircyecyxclffrgraveiiintntnfinotajligmacrgelinepartthofpedncarefintieodottcalegersrcallarhkprodocygonpftaprodquestscrinEdotsvvtildeukcymljcircyfrmathopfscrercyukcykappavcedilyfrgreenhcyjcyopfscrlAarrrrtailBarrEgHaracuteemptyvgranmbdangdlepquorrbfsfshklpplsimtltailesb
Line truncated
|
||||
//# sourceMappingURL=decode-data-html.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"decode-data-html.js","sourceRoot":"","sources":["../../src/generated/decode-data-html.ts"],"names":[],"mappings":"AAAA,8CAA8C;AAC9C,oHAAoH;AAEpH;;;;;GAKG;AACH,sCAAsC;AACtC,MAAM,CAAC,MAAM,cAAc,GAA8B,CAAC,qjYAAqjY,EAAC,k/ZAAk/Z,CAAC,CAAC"}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
declare const _default: "9Tab;NewLine;22excl;quot;num;dollar;percnt;amp;apos;lpar;rpar;ast;plus;comma;1period;sol;10colon;semi;lt;{8402nvlt;}equals;{8421bne;}gt;{8402nvgt;}quest;commat;26lsqb;bsol;rsqb;Hat;lowbar;grave;5{106fjlig;}20lcub;vert;rcub;34nbsp;iexcl;cent;pound;curren;yen;brvbar;sect;die;copy;ordf;laquo;not;shy;reg;macr;deg;pm;sup2;sup3;acute;micro;para;middot;cedil;sup1;ordm;raquo;frac14;half;frac34;iquest;Agrave;Aacute;Acirc;Atilde;Auml;angst;AElig;Ccedil;Egrave;Eacute;Ecirc;Euml;Igrave;Iacute;Icirc;Iuml;ETH;Ntilde;Ograve;Oacute;Ocirc;Otilde;Ouml;times;Oslash;Ugrave;Uacute;Ucirc;Uuml;Yacute;THORN;szlig;agrave;aacute;acirc;atilde;auml;aring;aelig;ccedil;egrave;eacute;ecirc;euml;igrave;iacute;icirc;iuml;eth;ntilde;ograve;oacute;ocirc;otilde;ouml;div;oslash;ugrave;uacute;ucirc;uuml;yacute;thorn;yuml;Amacr;amacr;Abreve;abreve;Aogon;aogon;Cacute;cacute;Ccirc;ccirc;Cdot;cdot;Ccaron;ccaron;Dcaron;dcaron;Dstrok;dstrok;Emacr;emacr;2Edot;edot;Eogon;eogon;Ecaron;ecaron;Gcirc;gcirc;Gbreve;gbreve;Gdot;gdot;Gcedil;1Hcirc;hcirc;Hstrok;hstrok;Itilde;itilde;Imacr;imacr;2Iogon;iogon;Idot;imath;IJlig;ijlig;Jcirc;jcirc;Kcedil;kcedil;kgreen;Lacute;lacute;Lcedil;lcedil;Lcaron;lcaron;Lmidot;lmidot;Lstrok;lstrok;Nacute;nacute;Ncedil;ncedil;Ncaron;ncaron;napos;ENG;eng;Omacr;omacr;2Odblac;odblac;OElig;oelig;Racute;racute;Rcedil;rcedil;Rcaron;rcaron;Sacute;sacute;Scirc;scirc;Scedil;scedil;Scaron;scaron;Tcedil;tcedil;Tcaron;tcaron;Tstrok;tstrok;Utilde;utilde;Umacr;umacr;Ubreve;ubreve;Uring;uring;Udblac;udblac;Uogon;uogon;Wcirc;wcirc;Ycirc;ycirc;Yuml;Zacute;zacute;Zdot;zdot;Zcaron;zcaron;19fnof;34imped;63gacute;65jmath;142circ;caron;16breve;dot;ring;ogon;tilde;dblac;51DownBreve;127Alpha;Beta;Gamma;Delta;Epsilon;Zeta;Eta;Theta;Iota;Kappa;Lambda;Mu;Nu;Xi;Omicron;Pi;Rho;1Sigma;Tau;Upsilon;Phi;Chi;Psi;ohm;7alpha;beta;gamma;delta;epsi;zeta;eta;theta;iota;kappa;lambda;mu;nu;xi;omicron;pi;rho;sigmaf;sigma;tau;upsi;phi;chi;psi;omega;7thetav;Upsi;2phiv;piv;5Gammad;gammad;18kappav;rhov;3epsiv;bepsi;10IOcy;DJcy;GJcy;Jukcy;DScy;Iukcy;YIcy;Jsercy;LJcy;NJcy;TSHcy;KJcy;1Ubrcy;DZcy;Acy;Bcy;Vcy;Gcy;Dcy;IEcy;ZHcy;Zcy;Icy;Jcy;Kcy;Lcy;Mcy;Ncy;Ocy;Pcy;Rcy;Scy;Tcy;Ucy;Fcy;KHcy;TScy;CHcy;SHcy;SHCHcy;HARDcy;Ycy;SOFTcy;Ecy;YUcy;YAcy;acy;bcy;vcy;gcy;dcy;iecy;zhcy;zcy;icy;jcy;kcy;lcy;mcy;ncy;ocy;pcy;rcy;scy;tcy;ucy;fcy;khcy;tscy;chcy;shcy;shchcy;hardcy;ycy;softcy;ecy;yucy;yacy;1iocy;djcy;gjcy;jukcy;dscy;iukcy;yicy;jsercy;ljcy;njcy;tshcy;kjcy;1ubrcy;dzcy;7074ensp;emsp;emsp13;emsp14;1numsp;puncsp;thinsp;hairsp;ZeroWidthSpace;zwnj;zwj;lrm;rlm;dash;2ndash;mdash;horbar;Vert;1lsquo;rsquo;sbquo;1ldquo;rdquo;bdquo;1dagger;Dagger;bull;2nldr;mldr;9permil;pertenk;prime;Prime;tprime;bprime;3lsaquo;rsaquo;3oline;2caret;1hybull;frasl;10bsemi;7qprime;7MediumSpace;{8202ThickSpace;}NoBreak;af;it;ic;72euro;46tdot;DotDot;37Copf;2incare;4gscr;Hscr;Hfr;Hopf;planckh;hbar;Iscr;Im;Lscr;ell;1Nopf;numero;copysr;wp;Popf;Qopf;Rscr;Re;Ropf;rx;3trade;1Zopf;2mho;Zfr;iiota;2Bscr;Cfr;1escr;Escr;Fscr;1Mscr;oscr;aleph;beth;gimel;daleth;12DD;dd;ee;ii;10frac13;frac23;frac15;frac25;frac35;frac45;frac16;frac56;frac18;frac38;frac58;frac78;49larr;uarr;rarr;darr;harr;varr;nwarr;nearr;searr;swarr;nlarr;nrarr;1rarrw;{824nrarrw;}Larr;Uarr;Rarr;Darr;larrtl;rarrtl;mapstoleft;mapstoup;map;mapstodown;1larrhk;rarrhk;larrlp;rarrlp;harrw;nharr;1lsh;rsh;ldsh;rdsh;1crarr;cularr;curarr;2olarr;orarr;lharu;lhard;uharr;uharl;rharu;rhard;dharr;dharl;rlarr;udarr;lrarr;llarr;uuarr;rrarr;ddarr;lrhar;rlhar;nlArr;nhArr;nrArr;lArr;uArr;rArr;dArr;iff;vArr;nwArr;neArr;seArr;swArr;lAarr;rAarr;1zigrarr;6larrb;rarrb;15duarr;7loarr;roarr;hoarr;forall;comp;part;{824npart;}exist;nexist;empty;1Del;in;notin;1ni;notni;2prod;coprod;sum;minus;mp;plusdo;1setmn;lowast;compfn;1Sqrt;2prop;infin;angrt;ang;{8402nang;}angmsd;angsph;mid;nmid;par;npar;and;or;cap;{65024caps;}cup;{65024cups;}int;Int;tint;oint;Conint;Cconint;cwint;cwconint;awconint;there4;becaus;ratio;Colon;minusd;1mDDot;homtht;sim;{8402nvsim;}bsim;{817race;}ac;{819acE;}acd;wr;nsim;esim;{824nesim;}sime;nsime;cong;simne;ncong;ap;nap;ape;apid;{824napid;}bcong;CupCap;{8402nvap;}bump;{824nbump;}bumpe;{824nbumpe;}doteq;{824nedot;}eDot;efDot;erDot;Assign;ecolon;ecir;cire;1wedgeq;veeeq;1trie;2equest;ne;equiv;{8421bnequiv;}nequiv;1le;{8402nvle;}ge;{8402nvge;}lE;{824nlE;}gE;{824ngE;}lnE;{65024lvnE;}gnE;{65024gvnE;}ll;{824nLtv;7577nLt;}gg;{824nGtv;7577nGt;}twixt;NotCupCap;nlt;ngt;nle;nge;lsim;gsim;nlsim;ngsim;lg;gl;ntlg;ntgl;pr;sc;prcue;sccue;prsim;scsim;{824NotSucceedsTilde;}npr;nsc;sub;{8402vnsub;}sup;{8402vnsup;}nsub;nsup;sube;supe;nsube;nsupe;subne;{65024vsubne;}supne;{65024vsupne;}1cupdot;uplus;sqsub;{824NotSquareSubset;}sqsup;{824NotSquareSuperset;}sqsube;sqsupe;sqcap;{65024sqcaps;}sqcup;{65024sqcups;}oplus;ominus;otimes;osol;odot;ocir;oast;1odash;plusb;minusb;timesb;sdotb;vdash;dashv;top;bot;1models;vDash;Vdash;Vvdash;VDash;nvdash;nvDash;nVdash;nVDash;prurel;1vltri;vrtri;ltrie;{8402nvltrie;}rtrie;{8402nvrtrie;}origof;imof;mumap;hercon;intcal;veebar;1barvee;angrtvb;lrtri;WedLine truncated
|
||||
export default _default;
|
||||
//# sourceMappingURL=encode-html.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"encode-html.d.ts","sourceRoot":"","sources":["../../src/generated/encode-html.ts"],"names":[],"mappings":"wBAEe,mtTAAmtT;AAAluT,wBAAmuT"}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
// Generated using scripts/write-encode-map.ts
|
||||
export default "9Tab;NewLine;22excl;quot;num;dollar;percnt;amp;apos;lpar;rpar;ast;plus;comma;1period;sol;10colon;semi;lt;{8402nvlt;}equals;{8421bne;}gt;{8402nvgt;}quest;commat;26lsqb;bsol;rsqb;Hat;lowbar;grave;5{106fjlig;}20lcub;vert;rcub;34nbsp;iexcl;cent;pound;curren;yen;brvbar;sect;die;copy;ordf;laquo;not;shy;reg;macr;deg;pm;sup2;sup3;acute;micro;para;middot;cedil;sup1;ordm;raquo;frac14;half;frac34;iquest;Agrave;Aacute;Acirc;Atilde;Auml;angst;AElig;Ccedil;Egrave;Eacute;Ecirc;Euml;Igrave;Iacute;Icirc;Iuml;ETH;Ntilde;Ograve;Oacute;Ocirc;Otilde;Ouml;times;Oslash;Ugrave;Uacute;Ucirc;Uuml;Yacute;THORN;szlig;agrave;aacute;acirc;atilde;auml;aring;aelig;ccedil;egrave;eacute;ecirc;euml;igrave;iacute;icirc;iuml;eth;ntilde;ograve;oacute;ocirc;otilde;ouml;div;oslash;ugrave;uacute;ucirc;uuml;yacute;thorn;yuml;Amacr;amacr;Abreve;abreve;Aogon;aogon;Cacute;cacute;Ccirc;ccirc;Cdot;cdot;Ccaron;ccaron;Dcaron;dcaron;Dstrok;dstrok;Emacr;emacr;2Edot;edot;Eogon;eogon;Ecaron;ecaron;Gcirc;gcirc;Gbreve;gbreve;Gdot;gdot;Gcedil;1Hcirc;hcirc;Hstrok;hstrok;Itilde;itilde;Imacr;imacr;2Iogon;iogon;Idot;imath;IJlig;ijlig;Jcirc;jcirc;Kcedil;kcedil;kgreen;Lacute;lacute;Lcedil;lcedil;Lcaron;lcaron;Lmidot;lmidot;Lstrok;lstrok;Nacute;nacute;Ncedil;ncedil;Ncaron;ncaron;napos;ENG;eng;Omacr;omacr;2Odblac;odblac;OElig;oelig;Racute;racute;Rcedil;rcedil;Rcaron;rcaron;Sacute;sacute;Scirc;scirc;Scedil;scedil;Scaron;scaron;Tcedil;tcedil;Tcaron;tcaron;Tstrok;tstrok;Utilde;utilde;Umacr;umacr;Ubreve;ubreve;Uring;uring;Udblac;udblac;Uogon;uogon;Wcirc;wcirc;Ycirc;ycirc;Yuml;Zacute;zacute;Zdot;zdot;Zcaron;zcaron;19fnof;34imped;63gacute;65jmath;142circ;caron;16breve;dot;ring;ogon;tilde;dblac;51DownBreve;127Alpha;Beta;Gamma;Delta;Epsilon;Zeta;Eta;Theta;Iota;Kappa;Lambda;Mu;Nu;Xi;Omicron;Pi;Rho;1Sigma;Tau;Upsilon;Phi;Chi;Psi;ohm;7alpha;beta;gamma;delta;epsi;zeta;eta;theta;iota;kappa;lambda;mu;nu;xi;omicron;pi;rho;sigmaf;sigma;tau;upsi;phi;chi;psi;omega;7thetav;Upsi;2phiv;piv;5Gammad;gammad;18kappav;rhov;3epsiv;bepsi;10IOcy;DJcy;GJcy;Jukcy;DScy;Iukcy;YIcy;Jsercy;LJcy;NJcy;TSHcy;KJcy;1Ubrcy;DZcy;Acy;Bcy;Vcy;Gcy;Dcy;IEcy;ZHcy;Zcy;Icy;Jcy;Kcy;Lcy;Mcy;Ncy;Ocy;Pcy;Rcy;Scy;Tcy;Ucy;Fcy;KHcy;TScy;CHcy;SHcy;SHCHcy;HARDcy;Ycy;SOFTcy;Ecy;YUcy;YAcy;acy;bcy;vcy;gcy;dcy;iecy;zhcy;zcy;icy;jcy;kcy;lcy;mcy;ncy;ocy;pcy;rcy;scy;tcy;ucy;fcy;khcy;tscy;chcy;shcy;shchcy;hardcy;ycy;softcy;ecy;yucy;yacy;1iocy;djcy;gjcy;jukcy;dscy;iukcy;yicy;jsercy;ljcy;njcy;tshcy;kjcy;1ubrcy;dzcy;7074ensp;emsp;emsp13;emsp14;1numsp;puncsp;thinsp;hairsp;ZeroWidthSpace;zwnj;zwj;lrm;rlm;dash;2ndash;mdash;horbar;Vert;1lsquo;rsquo;sbquo;1ldquo;rdquo;bdquo;1dagger;Dagger;bull;2nldr;mldr;9permil;pertenk;prime;Prime;tprime;bprime;3lsaquo;rsaquo;3oline;2caret;1hybull;frasl;10bsemi;7qprime;7MediumSpace;{8202ThickSpace;}NoBreak;af;it;ic;72euro;46tdot;DotDot;37Copf;2incare;4gscr;Hscr;Hfr;Hopf;planckh;hbar;Iscr;Im;Lscr;ell;1Nopf;numero;copysr;wp;Popf;Qopf;Rscr;Re;Ropf;rx;3trade;1Zopf;2mho;Zfr;iiota;2Bscr;Cfr;1escr;Escr;Fscr;1Mscr;oscr;aleph;beth;gimel;daleth;12DD;dd;ee;ii;10frac13;frac23;frac15;frac25;frac35;frac45;frac16;frac56;frac18;frac38;frac58;frac78;49larr;uarr;rarr;darr;harr;varr;nwarr;nearr;searr;swarr;nlarr;nrarr;1rarrw;{824nrarrw;}Larr;Uarr;Rarr;Darr;larrtl;rarrtl;mapstoleft;mapstoup;map;mapstodown;1larrhk;rarrhk;larrlp;rarrlp;harrw;nharr;1lsh;rsh;ldsh;rdsh;1crarr;cularr;curarr;2olarr;orarr;lharu;lhard;uharr;uharl;rharu;rhard;dharr;dharl;rlarr;udarr;lrarr;llarr;uuarr;rrarr;ddarr;lrhar;rlhar;nlArr;nhArr;nrArr;lArr;uArr;rArr;dArr;iff;vArr;nwArr;neArr;seArr;swArr;lAarr;rAarr;1zigrarr;6larrb;rarrb;15duarr;7loarr;roarr;hoarr;forall;comp;part;{824npart;}exist;nexist;empty;1Del;in;notin;1ni;notni;2prod;coprod;sum;minus;mp;plusdo;1setmn;lowast;compfn;1Sqrt;2prop;infin;angrt;ang;{8402nang;}angmsd;angsph;mid;nmid;par;npar;and;or;cap;{65024caps;}cup;{65024cups;}int;Int;tint;oint;Conint;Cconint;cwint;cwconint;awconint;there4;becaus;ratio;Colon;minusd;1mDDot;homtht;sim;{8402nvsim;}bsim;{817race;}ac;{819acE;}acd;wr;nsim;esim;{824nesim;}sime;nsime;cong;simne;ncong;ap;nap;ape;apid;{824napid;}bcong;CupCap;{8402nvap;}bump;{824nbump;}bumpe;{824nbumpe;}doteq;{824nedot;}eDot;efDot;erDot;Assign;ecolon;ecir;cire;1wedgeq;veeeq;1trie;2equest;ne;equiv;{8421bnequiv;}nequiv;1le;{8402nvle;}ge;{8402nvge;}lE;{824nlE;}gE;{824ngE;}lnE;{65024lvnE;}gnE;{65024gvnE;}ll;{824nLtv;7577nLt;}gg;{824nGtv;7577nGt;}twixt;NotCupCap;nlt;ngt;nle;nge;lsim;gsim;nlsim;ngsim;lg;gl;ntlg;ntgl;pr;sc;prcue;sccue;prsim;scsim;{824NotSucceedsTilde;}npr;nsc;sub;{8402vnsub;}sup;{8402vnsup;}nsub;nsup;sube;supe;nsube;nsupe;subne;{65024vsubne;}supne;{65024vsupne;}1cupdot;uplus;sqsub;{824NotSquareSubset;}sqsup;{824NotSquareSuperset;}sqsube;sqsupe;sqcap;{65024sqcaps;}sqcup;{65024sqcups;}oplus;ominus;otimes;osol;odot;ocir;oast;1odash;plusb;minusb;timesb;sdotb;vdash;dashv;top;bot;1models;vDash;Vdash;Vvdash;VDash;nvdash;nvDash;nVdash;nVDash;prurel;1vltri;vrtri;ltrie;{8402nvltrie;}rtrie;{8402nvrtrie;}origof;imof;mumap;hercon;intcal;veebar;1barvee;angrtvb;lrtri;Wedge;Vee;xcLine truncated
|
||||
//# sourceMappingURL=encode-html.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"encode-html.js","sourceRoot":"","sources":["../../src/generated/encode-html.ts"],"names":[],"mappings":"AAAA,8CAA8C;AAE9C,eAAe,mtTAAmtT,CAAC"}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
import { type DecodingMode } from "./decode.js";
|
||||
/** The level of entities to support. */
|
||||
export declare enum EntityLevel {
|
||||
/** Support only XML entities. */
|
||||
XML = 0,
|
||||
/** Support HTML entities, which are a superset of XML entities. */
|
||||
HTML = 1
|
||||
}
|
||||
/**
|
||||
* Encoding strategy used by `encode`.
|
||||
*/
|
||||
export declare enum EncodingMode {
|
||||
/**
|
||||
* The output is UTF-8 encoded. Only characters that need escaping within
|
||||
* XML will be escaped.
|
||||
*/
|
||||
UTF8 = 0,
|
||||
/**
|
||||
* The output consists only of ASCII characters. Characters that need
|
||||
* escaping within HTML, and characters that aren't ASCII characters will
|
||||
* be escaped.
|
||||
*/
|
||||
ASCII = 1,
|
||||
/**
|
||||
* Encode all characters that have an equivalent entity, as well as all
|
||||
* characters that are not ASCII characters.
|
||||
*/
|
||||
Extensive = 2,
|
||||
/**
|
||||
* Encode all characters that have to be escaped in HTML attributes,
|
||||
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
|
||||
*/
|
||||
Attribute = 3,
|
||||
/**
|
||||
* Encode all characters that have to be escaped in HTML text,
|
||||
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
|
||||
*/
|
||||
Text = 4
|
||||
}
|
||||
/**
|
||||
* Options for `decode`.
|
||||
*/
|
||||
export interface DecodingOptions {
|
||||
/**
|
||||
* The level of entities to support.
|
||||
* @default {@link EntityLevel.XML}
|
||||
*/
|
||||
level?: EntityLevel;
|
||||
/**
|
||||
* Decoding mode. If `Legacy`, will support legacy entities not terminated
|
||||
* with a semicolon (`;`).
|
||||
*
|
||||
* Always `Strict` for XML. For HTML, set this to
|
||||
* {@link DecodingMode.Attribute} if you are parsing an attribute value.
|
||||
* @default {@link DecodingMode.Legacy}
|
||||
*/
|
||||
mode?: DecodingMode | undefined;
|
||||
}
|
||||
/**
|
||||
* Decodes a string with entities.
|
||||
* @param input String to decode.
|
||||
* @param options Decoding options.
|
||||
*/
|
||||
export declare function decode(input: string, options?: DecodingOptions | EntityLevel): string;
|
||||
/**
|
||||
* Options for `encode`.
|
||||
*/
|
||||
export interface EncodingOptions {
|
||||
/**
|
||||
* The level of entities to support.
|
||||
* @default {@link EntityLevel.XML}
|
||||
*/
|
||||
level?: EntityLevel;
|
||||
/**
|
||||
* Output format.
|
||||
* @default {@link EncodingMode.Extensive}
|
||||
*/
|
||||
mode?: EncodingMode;
|
||||
}
|
||||
/**
|
||||
* Encodes a string with entities.
|
||||
* @param input String to encode.
|
||||
* @param options Encoding options.
|
||||
*/
|
||||
export declare function encode(input: string, options?: EncodingOptions | EntityLevel): string;
|
||||
export { DecodingMode, decodeHTML, decodeHTMLAttribute, decodeHTMLStrict, decodeXML, decodeXML as decodeXMLStrict, HtmlEntityDecoder, XmlEntityDecoder, } from "./decode.js";
|
||||
export { encodeHTML, encodeNonAsciiHTML, } from "./encode.js";
|
||||
export { encodeXML, escape, escapeAttribute, escapeText, escapeUTF8, } from "./escape.js";
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources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import { decodeHTML, decodeXML } from "./decode.js";
|
||||
import { encodeHTML, encodeNonAsciiHTML } from "./encode.js";
|
||||
import { encodeXML, escapeAttribute, escapeText, escapeUTF8, } from "./escape.js";
|
||||
/** The level of entities to support. */
|
||||
export var EntityLevel;
|
||||
(function (EntityLevel) {
|
||||
/** Support only XML entities. */
|
||||
EntityLevel[EntityLevel["XML"] = 0] = "XML";
|
||||
/** Support HTML entities, which are a superset of XML entities. */
|
||||
EntityLevel[EntityLevel["HTML"] = 1] = "HTML";
|
||||
})(EntityLevel || (EntityLevel = {}));
|
||||
/**
|
||||
* Encoding strategy used by `encode`.
|
||||
*/
|
||||
export var EncodingMode;
|
||||
(function (EncodingMode) {
|
||||
/**
|
||||
* The output is UTF-8 encoded. Only characters that need escaping within
|
||||
* XML will be escaped.
|
||||
*/
|
||||
EncodingMode[EncodingMode["UTF8"] = 0] = "UTF8";
|
||||
/**
|
||||
* The output consists only of ASCII characters. Characters that need
|
||||
* escaping within HTML, and characters that aren't ASCII characters will
|
||||
* be escaped.
|
||||
*/
|
||||
EncodingMode[EncodingMode["ASCII"] = 1] = "ASCII";
|
||||
/**
|
||||
* Encode all characters that have an equivalent entity, as well as all
|
||||
* characters that are not ASCII characters.
|
||||
*/
|
||||
EncodingMode[EncodingMode["Extensive"] = 2] = "Extensive";
|
||||
/**
|
||||
* Encode all characters that have to be escaped in HTML attributes,
|
||||
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
|
||||
*/
|
||||
EncodingMode[EncodingMode["Attribute"] = 3] = "Attribute";
|
||||
/**
|
||||
* Encode all characters that have to be escaped in HTML text,
|
||||
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
|
||||
*/
|
||||
EncodingMode[EncodingMode["Text"] = 4] = "Text";
|
||||
})(EncodingMode || (EncodingMode = {}));
|
||||
/**
|
||||
* Decodes a string with entities.
|
||||
* @param input String to decode.
|
||||
* @param options Decoding options.
|
||||
*/
|
||||
export function decode(input, options = EntityLevel.XML) {
|
||||
const level = typeof options === "number" ? options : options.level;
|
||||
if (level === EntityLevel.HTML) {
|
||||
const mode = typeof options === "object" ? options.mode : undefined;
|
||||
return decodeHTML(input, mode);
|
||||
}
|
||||
return decodeXML(input);
|
||||
}
|
||||
/**
|
||||
* Encodes a string with entities.
|
||||
* @param input String to encode.
|
||||
* @param options Encoding options.
|
||||
*/
|
||||
export function encode(input, options = EntityLevel.XML) {
|
||||
const { mode = EncodingMode.Extensive, level = EntityLevel.XML } = typeof options === "number" ? { level: options } : options;
|
||||
switch (mode) {
|
||||
case EncodingMode.UTF8: {
|
||||
return escapeUTF8(input);
|
||||
}
|
||||
case EncodingMode.Attribute: {
|
||||
return escapeAttribute(input);
|
||||
}
|
||||
case EncodingMode.Text: {
|
||||
return escapeText(input);
|
||||
}
|
||||
case EncodingMode.ASCII: {
|
||||
return (level === EntityLevel.HTML ? encodeNonAsciiHTML : encodeXML)(input);
|
||||
}
|
||||
// biome-ignore lint/complexity/noUselessSwitchCase: we get an error for the switch not being exhaustive
|
||||
case EncodingMode.Extensive:
|
||||
default: {
|
||||
return (level === EntityLevel.HTML ? encodeHTML : encodeXML)(input);
|
||||
}
|
||||
}
|
||||
}
|
||||
export { DecodingMode, decodeHTML, decodeHTMLAttribute, decodeHTMLStrict, decodeXML, decodeXML as decodeXMLStrict, HtmlEntityDecoder, XmlEntityDecoder, } from "./decode.js";
|
||||
export { encodeHTML, encodeNonAsciiHTML, } from "./encode.js";
|
||||
export { encodeXML, escape, escapeAttribute, escapeText, escapeUTF8, } from "./escape.js";
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,UAAU,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EACH,SAAS,EACT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CAAC,CAAC,CAAC,OAAO,CAAC;IAE/D,QAAQ,IAAI,EAAE,CAAC;QACX,KAAK,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;YACrB,OAAO,UAAU,CAAC,KAAK,CAAC,CAAC;QAC7B,CAAC;QACD,KAAK,YAAY,CAAC,SAAS,CAAC,CAAC,CAAC;YAC1B,OAAO,eAAe,CAAC,KAAK,CAAC,CAAC;QAClC,CAAC;QACD,KAAK,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;YACrB,OAAO,UAAU,CAAC,KAAK,CAAC,CAAC;QAC7B,CAAC;QACD,KAAK,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC;YACtB,OAAO,CACH,KAAK,KAAK,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,SAAS,CAC9D,CAAC,KAAK,CAAC,CAAC;QACb,CAAC;QACD,wGAAwG;QACxG,KAAK,YAAY,CAAC,SAAS,CAAC;QAC5B,OAAO,CAAC,CAAC,CAAC;YACN,OAAO,CAAC,KAAK,KAAK,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,KAAK,CAAC,CAAC;QACxE,CAAC;IACL,CAAC;AACL,CAAC;AAED,OAAO,EACH,YAAY,EACZ,UAAU,EACV,mBAAmB,EACnB,gBAAgB,EAChB,SAAS,EACT,SAAS,IAAI,eAAe,EAC5B,iBAAiB,EACjB,gBAAgB,GACnB,MAAM,aAAa,CAAC;AAErB,OAAO,EACH,UAAU,EACV,kBAAkB,GACrB,MAAM,aAAa,CAAC;AACrB,OAAO,EACH,SAAS,EACT,MAAM,EACN,eAAe,EACf,UAAU,EACV,UAAU,GACb,MAAM,aAAa,CAAC"}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* Constants and helpers shared between the decode-data generator
|
||||
* (`scripts/write-decode-map.ts`) and the runtime (`src/decode.ts`).
|
||||
*
|
||||
* The format and the algorithms (front-coded names, exact 32-bit keys in a
|
||||
* two-choice cuckoo table, the length-probe front end, and the measured
|
||||
* engineering notes) are documented with references in
|
||||
* `scripts/README.md`.
|
||||
*/
|
||||
/** Bias added to every meta char so none needs escaping in JS source. */
|
||||
export declare const META_BIAS = 35;
|
||||
/** Bias for header and choice-bit chars. */
|
||||
export declare const HEADER_BIAS = 48;
|
||||
/** Number of header chars: n (2), suffixes length (2), bucket count (2). */
|
||||
export declare const HEADER_LENGTH = 6;
|
||||
/** Choice bits packed per char. */
|
||||
export declare const CHOICE_BITS_PER_CHAR = 6;
|
||||
/** Multiplier deriving the first candidate bucket from a key. */
|
||||
export declare const BUCKET_HASH_1 = 2654435761;
|
||||
/** Multiplier deriving the second candidate bucket from a key. */
|
||||
export declare const BUCKET_HASH_2 = 2246822507;
|
||||
/** Size of the (c0,c1) class table (10-bit index). */
|
||||
export declare const PAIR_TABLE_SIZE = 1024;
|
||||
/**
|
||||
* Map an alphanumeric char code to 6 bits (1..62); 0 = not alphanumeric.
|
||||
* Used for the key's last-character field.
|
||||
*/
|
||||
export declare const CHAR_REMAP: Uint8Array;
|
||||
/**
|
||||
* The exact 32-bit key for a name occurring at `nameStart` with `length`
|
||||
* chars. Covers the first two and last two characters plus the length;
|
||||
* middle characters are verified separately against the names blob.
|
||||
*
|
||||
* The hot decoder inlines this computation; tests assert both stay in sync
|
||||
* by looking every entity up through the public API.
|
||||
* @param text Text containing the name.
|
||||
* @param nameStart Index of the name's first character.
|
||||
* @param length Length of the name.
|
||||
*/
|
||||
export declare function exactKey(text: string, nameStart: number, length: number): number;
|
||||
/**
|
||||
* The 10-bit (c0,c1) class index used by the probe front end. The function
|
||||
* was chosen by exhaustive search over load-free mixers for minimal
|
||||
* candidate-set collisions on the real entity set.
|
||||
* @param c0 First char code of the candidate name.
|
||||
* @param c1 Second char code.
|
||||
*/
|
||||
export declare function pairIndex(c0: number, c1: number): number;
|
||||
/**
|
||||
* First candidate bucket for a key in a table of `buckets` buckets.
|
||||
* @param key Exact key.
|
||||
* @param buckets Bucket count.
|
||||
*/
|
||||
export declare function bucketOne(key: number, buckets: number): number;
|
||||
/**
|
||||
* Second candidate bucket for a key.
|
||||
* @param key Exact key.
|
||||
* @param buckets Bucket count.
|
||||
*/
|
||||
export declare function bucketTwo(key: number, buckets: number): number;
|
||||
/**
|
||||
* Decode data for the HTML entity set, built from the serialized form at
|
||||
* module init. The format and the algorithms operating on it are documented
|
||||
* in `scripts/README.md`. XML's five entities are matched directly and
|
||||
* ship no data.
|
||||
*/
|
||||
export interface DecodeData {
|
||||
/** Exact 32-bit keys; two-slot buckets, slot index = 2*bucket (+1). */
|
||||
keys: Int32Array;
|
||||
/** Bucket count for the cuckoo table. */
|
||||
buckets: number;
|
||||
/** Per-slot word offset in `middles`. */
|
||||
slotMidOff: Uint16Array;
|
||||
/**
|
||||
* Per-slot value location in `values`: offset in bits 2..15, legacy
|
||||
* flag in bit 1, and length minus one in bit 0. Replaces a per-slot
|
||||
* `string[]`: half the footprint and no
|
||||
* per-value heap objects, for a slightly costlier emit (see
|
||||
* `emitHtmlValue`).
|
||||
*/
|
||||
slotValue: Uint16Array;
|
||||
/** Concatenated replacement values; indexed via `slotValue`. */
|
||||
values: string;
|
||||
/**
|
||||
* Per (c0,c1) class: candidate name lengths. Bits 0-14 = exact lengths
|
||||
* 2..16, bit 15 = lengths above 16 exist, bits 16-20 = legacy lengths.
|
||||
*/
|
||||
lengthBits: Uint32Array;
|
||||
/** Deduplicated middles, packed as pairs of UTF-16 code units per word. */
|
||||
middles: Uint32Array;
|
||||
}
|
||||
/**
|
||||
* Build the lookup structures from a serialized dataset.
|
||||
* @param packed Serialized decode data, see `decode-data-format.ts`.
|
||||
*/
|
||||
export declare function initDecodeData(packed: readonly [string, string]): DecodeData;
|
||||
//# sourceMappingURL=decode-data-format.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"decode-data-format.d.ts","sourceRoot":"","sources":["../../src/internal/decode-data-format.ts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AAE,WAAW,CAAC;CACxB;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,UAAU,CA4F5E"}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
/**
|
||||
* Constants and helpers shared between the decode-data generator
|
||||
* (`scripts/write-decode-map.ts`) and the runtime (`src/decode.ts`).
|
||||
*
|
||||
* The format and the algorithms (front-coded names, exact 32-bit keys in a
|
||||
* two-choice cuckoo table, the length-probe front end, and the measured
|
||||
* engineering notes) are documented with references in
|
||||
* `scripts/README.md`.
|
||||
*/
|
||||
/** Bias added to every meta char so none needs escaping in JS source. */
|
||||
export const META_BIAS = 0x23;
|
||||
/** Bias for header and choice-bit chars. */
|
||||
export const HEADER_BIAS = 0x30;
|
||||
/** Number of header chars: n (2), suffixes length (2), bucket count (2). */
|
||||
export const HEADER_LENGTH = 6;
|
||||
/** Choice bits packed per char. */
|
||||
export const CHOICE_BITS_PER_CHAR = 6;
|
||||
/** Multiplier deriving the first candidate bucket from a key. */
|
||||
export const BUCKET_HASH_1 = 0x9e_37_79_b1;
|
||||
/** Multiplier deriving the second candidate bucket from a key. */
|
||||
export const BUCKET_HASH_2 = 0x85_eb_ca_6b;
|
||||
/** Size of the (c0,c1) class table (10-bit index). */
|
||||
export const PAIR_TABLE_SIZE = 1024;
|
||||
/**
|
||||
* Map an alphanumeric char code to 6 bits (1..62); 0 = not alphanumeric.
|
||||
* Used for the key's last-character field.
|
||||
*/
|
||||
export const CHAR_REMAP = (() => {
|
||||
const remap = new Uint8Array(128);
|
||||
for (let code = 0x30; code <= 0x39; code++)
|
||||
remap[code] = code - 0x2f;
|
||||
for (let code = 0x41; code <= 0x5a; code++)
|
||||
remap[code] = code - 0x36;
|
||||
for (let code = 0x61; code <= 0x7a; code++)
|
||||
remap[code] = code - 0x3c;
|
||||
return remap;
|
||||
})();
|
||||
/**
|
||||
* The exact 32-bit key for a name occurring at `nameStart` with `length`
|
||||
* chars. Covers the first two and last two characters plus the length;
|
||||
* middle characters are verified separately against the names blob.
|
||||
*
|
||||
* The hot decoder inlines this computation; tests assert both stay in sync
|
||||
* by looking every entity up through the public API.
|
||||
* @param text Text containing the name.
|
||||
* @param nameStart Index of the name's first character.
|
||||
* @param length Length of the name.
|
||||
*/
|
||||
export function exactKey(text, nameStart, length) {
|
||||
return ((text.charCodeAt(nameStart) << 25) |
|
||||
(text.charCodeAt(nameStart + 1) << 18) |
|
||||
(text.charCodeAt(nameStart + length - 2) << 11) |
|
||||
(CHAR_REMAP[text.charCodeAt(nameStart + length - 1)] << 5) |
|
||||
length);
|
||||
}
|
||||
/**
|
||||
* The 10-bit (c0,c1) class index used by the probe front end. The function
|
||||
* was chosen by exhaustive search over load-free mixers for minimal
|
||||
* candidate-set collisions on the real entity set.
|
||||
* @param c0 First char code of the candidate name.
|
||||
* @param c1 Second char code.
|
||||
*/
|
||||
export function pairIndex(c0, c1) {
|
||||
return (((c0 * 3) << 3) ^ c1) & (PAIR_TABLE_SIZE - 1);
|
||||
}
|
||||
/**
|
||||
* First candidate bucket for a key in a table of `buckets` buckets.
|
||||
* @param key Exact key.
|
||||
* @param buckets Bucket count.
|
||||
*/
|
||||
export function bucketOne(key, buckets) {
|
||||
return ((Math.imul(key, BUCKET_HASH_1) >>> 16) * buckets) >>> 16;
|
||||
}
|
||||
/**
|
||||
* Second candidate bucket for a key.
|
||||
* @param key Exact key.
|
||||
* @param buckets Bucket count.
|
||||
*/
|
||||
export function bucketTwo(key, buckets) {
|
||||
return ((Math.imul(key, BUCKET_HASH_2) >>> 16) * buckets) >>> 16;
|
||||
}
|
||||
/**
|
||||
* Build the lookup structures from a serialized dataset.
|
||||
* @param packed Serialized decode data, see `decode-data-format.ts`.
|
||||
*/
|
||||
export function initDecodeData(packed) {
|
||||
const [data, values] = packed;
|
||||
const nameCount = ((data.charCodeAt(0) - HEADER_BIAS) << 6) |
|
||||
(data.charCodeAt(1) - HEADER_BIAS);
|
||||
const suffixesLength = ((data.charCodeAt(2) - HEADER_BIAS) << 6) |
|
||||
(data.charCodeAt(3) - HEADER_BIAS);
|
||||
const buckets = ((data.charCodeAt(4) - HEADER_BIAS) << 6) |
|
||||
(data.charCodeAt(5) - HEADER_BIAS);
|
||||
const metaStart = HEADER_LENGTH + suffixesLength;
|
||||
const choicesStart = metaStart + 2 * nameCount;
|
||||
const slotCount = 2 * buckets;
|
||||
const keys = new Int32Array(slotCount);
|
||||
const slotMidOff = new Uint16Array(slotCount);
|
||||
const slotValue = new Uint16Array(slotCount);
|
||||
const lengthBits = new Uint32Array(PAIR_TABLE_SIZE);
|
||||
const middleOffsets = new Map();
|
||||
const middles = [];
|
||||
let name = "";
|
||||
let suffixOffset = HEADER_LENGTH;
|
||||
let valueOffset = 0;
|
||||
for (let index = 0; index < nameCount; index++) {
|
||||
const meta0 = data.charCodeAt(metaStart + 2 * index) - META_BIAS;
|
||||
const meta1 = data.charCodeAt(metaStart + 2 * index + 1) - META_BIAS;
|
||||
const prefixLength = meta0 & 31;
|
||||
const length = prefixLength + (meta1 & 31);
|
||||
const valueLength = (meta1 >> 5) + 1;
|
||||
name =
|
||||
name.slice(0, prefixLength) +
|
||||
data.slice(suffixOffset, suffixOffset + length - prefixLength);
|
||||
suffixOffset += length - prefixLength;
|
||||
const key = exactKey(name, 0, length);
|
||||
const choice = (data.charCodeAt(choicesStart + Math.floor(index / CHOICE_BITS_PER_CHAR)) -
|
||||
HEADER_BIAS) &
|
||||
(1 << (index % CHOICE_BITS_PER_CHAR));
|
||||
let slot = 2 * (choice === 0 ? bucketOne : bucketTwo)(key, buckets);
|
||||
if (keys[slot] !== 0)
|
||||
slot += 1;
|
||||
keys[slot] = key;
|
||||
if (length > 4) {
|
||||
const middle = name.slice(2, length - 2);
|
||||
const existing = middleOffsets.get(middle);
|
||||
if (existing === undefined) {
|
||||
middleOffsets.set(middle, middles.length);
|
||||
slotMidOff[slot] = middles.length;
|
||||
for (let middleIndex = 0; middleIndex < middle.length; middleIndex += 2) {
|
||||
middles.push(middle.charCodeAt(middleIndex) |
|
||||
(middle.charCodeAt(middleIndex + 1) << 16));
|
||||
}
|
||||
}
|
||||
else {
|
||||
slotMidOff[slot] = existing;
|
||||
}
|
||||
}
|
||||
const pair = pairIndex(name.charCodeAt(0), name.charCodeAt(1));
|
||||
lengthBits[pair] |= length <= 16 ? 1 << (length - 2) : 0x80_00;
|
||||
if ((meta0 & 0x20) !== 0) {
|
||||
lengthBits[pair] |= 1 << (length - 2 + 16);
|
||||
}
|
||||
/*
|
||||
* Values have one or two units, leaving bit 1 for the legacy flag.
|
||||
* The generator checks the 14-bit offset and two-unit value limits.
|
||||
*/
|
||||
slotValue[slot] =
|
||||
(valueOffset << 2) | (valueLength - 1) | ((meta0 & 0x20) >> 4);
|
||||
valueOffset += valueLength;
|
||||
}
|
||||
return {
|
||||
keys,
|
||||
buckets,
|
||||
slotMidOff,
|
||||
slotValue,
|
||||
values,
|
||||
lengthBits,
|
||||
middles: new Uint32Array(middles),
|
||||
};
|
||||
}
|
||||
//# sourceMappingURL=decode-data-format.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"decode-data-format.js","sourceRoot":"","sources":["../../src/internal/decode-data-format.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,yEAAyE;AACzE,MAAM,CAAC,MAAM,SAAS,GAAG,IAAI,CAAC;AAC9B,4CAA4C;AAC5C,MAAM,CAAC,MAAM,WAAW,GAAG,IAAI,CAAC;AAChC,4EAA4E;AAC5E,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,CAAC;AAC/B,mCAAmC;AACnC,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAEtC,iEAAiE;AACjE,MAAM,CAAC,MAAM,aAAa,GAAG,aAAa,CAAC;AAC3C,kEAAkE;AAClE,MAAM,CAAC,MAAM,aAAa,GAAG,aAAa,CAAC;AAE3C,sDAAsD;AACtD,MAAM,CAAC,MAAM,eAAe,G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AG,QAAQ,CAAC;YAChC,CAAC;QACL,CAAC;QAED,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;QAC/D,UAAU,CAAC,IAAI,CAAC,IAAI,MAAM,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;QAC/D,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACvB,Line truncated
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"name": "entities",
|
||||
"version": "9.0.0",
|
||||
"description": "Encode & decode XML and HTML entities with ease & speed",
|
||||
"keywords": [
|
||||
"html entities",
|
||||
"entity decoder",
|
||||
"entity encoding",
|
||||
"html decoding",
|
||||
"html encoding",
|
||||
"xml decoding",
|
||||
"xml encoding"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/fb55/entities.git"
|
||||
},
|
||||
"funding": "https://github.com/fb55/entities?sponsor=1",
|
||||
"license": "BSD-2-Clause",
|
||||
"author": "Felix Boehm <me@feedic.com>",
|
||||
"sideEffects": false,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./decode": {
|
||||
"types": "./dist/decode.d.ts",
|
||||
"default": "./dist/decode.js"
|
||||
},
|
||||
"./escape": {
|
||||
"types": "./dist/escape.d.ts",
|
||||
"default": "./dist/escape.js"
|
||||
}
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"dist",
|
||||
"src",
|
||||
"!**/*.spec.ts"
|
||||
],
|
||||
"scripts": {
|
||||
"prebenchmark": "npm ci --prefix scripts/benchmark",
|
||||
"benchmark": "npm --prefix scripts/benchmark run benchmark --",
|
||||
"build": "npm run clean && tsc",
|
||||
"build:decode-map": "node --import=tsx scripts/write-decode-map.ts",
|
||||
"build:docs": "typedoc --hideGenerator src/index.ts",
|
||||
"build:encode-trie": "node --import=tsx scripts/write-encode-map.ts",
|
||||
"clean": "node -e \"fs.rmSync('dist', { recursive: true, force: true })\"",
|
||||
"format": "npm run format:es && npm run format:biome",
|
||||
"format:biome": "biome check --fix .",
|
||||
"format:es": "npm run lint:es -- --fix",
|
||||
"lint": "npm run lint:es && npm run lint:ts && npm run lint:biome",
|
||||
"lint:biome": "biome check .",
|
||||
"lint:es": "eslint .",
|
||||
"lint:ts": "tsc --noEmit -p tsconfig.eslint.json",
|
||||
"prepublishOnly": "npm run build",
|
||||
"test": "npm run test:vi && npm run lint",
|
||||
"test:vi": "vitest run"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "^2.5.15",
|
||||
"@eslint/compat": "^2.1.1",
|
||||
"@feedic/eslint-config": "^0.5.0",
|
||||
"@types/node": "^26.6.5",
|
||||
"eslint": "^10.13.0",
|
||||
"eslint-config-biome": "^2.1.3",
|
||||
"tsx": "^4.23.15",
|
||||
"typedoc": "^0.28.20",
|
||||
"typescript": "^6.0.3",
|
||||
"typescript-eslint": "^8.71.2",
|
||||
"vitest": "^5.0.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
# entities [](https://npmjs.org/package/entities) [](https://npmjs.org/package/entities) [](https://github.com/fb55/entities/actions/workflows/nodejs-test.yml)
|
||||
|
||||
Encode & decode HTML & XML entities with ease & speed.
|
||||
|
||||
## Features
|
||||
|
||||
- 😇 Tried and true: `entities` is used by many popular libraries; eg.
|
||||
[`htmlparser2`](https://github.com/fb55/htmlparser2), the official
|
||||
[AWS SDK](https://github.com/aws/aws-sdk-js-v3) and
|
||||
[`commonmark`](https://github.com/commonmark/commonmark.js) use it to process
|
||||
HTML entities.
|
||||
- ⚡️ Fast: `entities` is the fastest library for decoding HTML entities (as of
|
||||
September 2025); see [performance](#performance).
|
||||
- 🎛 Configurable: Get an output tailored for your needs. You are fine with
|
||||
UTF8? That'll save you some bytes. Prefer to only have ASCII characters? We
|
||||
can do that as well!
|
||||
|
||||
## How to…
|
||||
|
||||
### …install `entities`
|
||||
|
||||
npm install entities
|
||||
|
||||
### …use `entities`
|
||||
|
||||
```javascript
|
||||
import * as entities from "entities";
|
||||
|
||||
// Encoding
|
||||
entities.escapeUTF8("& ü"); // "&#38; ü"
|
||||
entities.encodeXML("& ü"); // "&#38; ü"
|
||||
entities.encodeHTML("& ü"); // "&#38; ü"
|
||||
|
||||
// Decoding
|
||||
entities.decodeXML("asdf & ÿ ü '"); // "asdf & ÿ ü '"
|
||||
entities.decodeHTML("asdf & ÿ ü '"); // "asdf & ÿ ü '"
|
||||
```
|
||||
|
||||
## Performance
|
||||
|
||||
Benchmarked in October 2026 with Node v26.9.0 on AMD Ryzen 7 5800X3D
|
||||
(median of three runs). Other libraries are shown relative to `entities`.
|
||||
|
||||
### Decoding
|
||||
|
||||
| Library | Short text (49 B) | Plain prose (4.0 KiB) | Prose with references (4.0 KiB) | All named references (19.9 KiB) | Numeric references (4.0 KiB) |
|
||||
| -------------------- | ----------------: | --------------------: | ------------------------------: | ------------------------------: | ---------------------------: |
|
||||
| entities | 578 MB/s | 131,381 MB/s | 1,425 MB/s | 161 MB/s | 272 MB/s |
|
||||
| html-entities 2.6.0 | 5.5× slower | 61× slower | 4.8× slower | 2.7× slower | 7.1× slower |
|
||||
| he 2.0.0 | 7.8× slower | 61× slower | 7.5× slower | 5.0× slower | 8.0× slower |
|
||||
| parse-entities 4.0.2 | 14× slower | 1,040× slower | 30× slower | 13× slower | 5.0× slower |
|
||||
| ent 2.2.2 | 10× slower | 61× slower | 10× slower | 6.9× slower | 11× slower |
|
||||
|
||||
`entities` returns input without `&` after a single `indexOf` scan, hence
|
||||
the plain prose result.
|
||||
|
||||
### Encoding
|
||||
|
||||
| Library | Short text (48 B) | ASCII prose (4.0 KiB) | Accented prose (4.0 KiB) | CJK and emoji (4.0 KiB) |
|
||||
| ------------------------ | ----------------: | --------------------: | -----------------------: | ----------------------: |
|
||||
| entities | 195 MB/s | 1,107 MB/s | 251 MB/s | 127 MB/s |
|
||||
| html-entities 2.6.0 | 3.0× slower | 1.1× slower | 1.6× slower | 2.7× slower |
|
||||
| he 2.0.0 | 9.4× slower | 2.0× slower | 4.3× slower | 4.4× slower |
|
||||
| stringify-entities 4.0.4 | 8.0× slower | 1.7× slower | 3.8× slower | 5.6× slower |
|
||||
| ent 2.2.2 | 14× slower | 98× slower | 23× slower | 5.3× slower |
|
||||
|
||||
### Escaping
|
||||
|
||||
| Library | Short text (48 B) | Prose (4.0 KiB) | Markup (4.1 KiB) |
|
||||
| ------------------------ | ----------------: | --------------: | ---------------: |
|
||||
| entities | 326 MB/s | 4,447 MB/s | 304 MB/s |
|
||||
| html-entities 2.6.0 | 2.3× slower | 1.8× slower | 1.7× slower |
|
||||
| he 2.0.0 | 2.1× slower | 1.7× slower | 1.6× slower |
|
||||
| stringify-entities 4.0.4 | 3.6× slower | 2.7× slower | 2.8× slower |
|
||||
| html-escaper 3.0.3 | 2.2× slower | 1.7× slower | 1.6× slower |
|
||||
| lodash 4.18.1 | 2.4× slower | 1.8× slower | 1.7× slower |
|
||||
|
||||
### Unescaping
|
||||
|
||||
| Library | Short text (62 B) | Prose (4.1 KiB) | Markup (5.7 KiB) |
|
||||
| -------------------- | ----------------: | --------------: | ---------------: |
|
||||
| entities | 329 MB/s | 4,552 MB/s | 410 MB/s |
|
||||
| html-entities 2.6.0 | 3.7× slower | 5.7× slower | 3.7× slower |
|
||||
| he 2.0.0 | 5.2× slower | 8.4× slower | 5.8× slower |
|
||||
| parse-entities 4.0.2 | 8.0× slower | 75× slower | 13× slower |
|
||||
| ent 2.2.2 | 7.8× slower | 11× slower | 8.9× slower |
|
||||
| html-escaper 3.0.3 | 2.8× slower | 5.2× slower | 3.0× slower |
|
||||
| lodash 4.18.1 | 3.0× slower | 4.8× slower | 3.0× slower |
|
||||
|
||||
Note: Micro-benchmarks may vary across machines and Node versions.
|
||||
|
||||
---
|
||||
|
||||
## FAQ
|
||||
|
||||
> What methods should I actually use to encode my documents?
|
||||
|
||||
If your target supports UTF-8, the `escapeUTF8` method is going to be your best
|
||||
choice. Otherwise, use either `encodeHTML` or `encodeXML` based on whether
|
||||
you're dealing with an HTML or an XML document.
|
||||
|
||||
You can have a look at the options for the `encode` and `decode` methods to see
|
||||
everything you can configure.
|
||||
|
||||
> When should I use strict decoding?
|
||||
|
||||
When strict decoding, entities not terminated with a semicolon will be ignored.
|
||||
This is helpful for decoding entities in legacy environments.
|
||||
|
||||
> Why should I use `entities` instead of alternative modules?
|
||||
|
||||
As of October 2026, `entities` is faster than other modules. Still, this is
|
||||
not a differentiated space and other modules can catch up.
|
||||
|
||||
**More importantly**, you might already have `entities` in your dependency graph
|
||||
(as a dependency of eg. `cheerio`, or `htmlparser2`), and including it directly
|
||||
might not even increase your bundle size. The same is true for other entity
|
||||
libraries, so have a look through your `node_modules` directory!
|
||||
|
||||
> Does `entities` support tree shaking?
|
||||
|
||||
Yes! Note that for best results, you should not use the `encode` and `decode`
|
||||
functions, as they wrap around a number of other functions, all of which will
|
||||
remain in the bundle. Instead, use the functions that you need directly.
|
||||
|
||||
---
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
This library wouldn't be possible without the work of these individuals. Thanks
|
||||
to
|
||||
|
||||
- [@mathiasbynens](https://github.com/mathiasbynens) for his explanations about
|
||||
character encodings, and his library `he`, which was one of the inspirations
|
||||
for `entities`
|
||||
- [@inikulin](https://github.com/inikulin) for his work on optimized tries for
|
||||
decoding HTML entities for the `parse5` project
|
||||
- [@mdevils](https://github.com/mdevils) for taking on the challenge of
|
||||
producing a quick entity library with his `html-entities` library. `entities`
|
||||
would be quite a bit slower if there wasn't any competition. Right now
|
||||
`entities` is on top, but we'll see how long that lasts!
|
||||
|
||||
---
|
||||
|
||||
License: BSD-2-Clause
|
||||
|
||||
## Security contact information
|
||||
|
||||
To report a security vulnerability, please use the
|
||||
[Tidelift security contact](https://tidelift.com/security). Tidelift will
|
||||
coordinate the fix and disclosure.
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
// Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134
|
||||
|
||||
/**
|
||||
* C1 Unicode control character reference replacements (code points 128-159).
|
||||
* Index i gives the replacement for code point 128+i; 0 means "no replacement".
|
||||
*/
|
||||
const c1: number[] = [
|
||||
8364, 0, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, 8249, 338, 0,
|
||||
381, 0, 0, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732, 8482, 353, 8250,
|
||||
339, 0, 382, 376,
|
||||
];
|
||||
|
||||
/**
|
||||
* True for NUL, UTF-16 surrogates, and values past U+10FFFF.
|
||||
* @param codePoint Unicode code point to check.
|
||||
*/
|
||||
function isInvalidCodePoint(codePoint: number): boolean {
|
||||
return (
|
||||
codePoint === 0 ||
|
||||
(codePoint >= 0xd8_00 && codePoint <= 0xdf_ff) ||
|
||||
codePoint > 0x10_ff_ff
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the given code point with U+FFFD if it is NUL (0), a surrogate, or
|
||||
* outside the valid Unicode range. Code points in the C1 controls range
|
||||
* (128-159) are remapped to their Windows-1252 equivalents, following the
|
||||
* HTML spec. All other code points are returned unchanged.
|
||||
* @param codePoint Unicode code point to convert.
|
||||
*/
|
||||
export function replaceCodePoint(codePoint: number): number {
|
||||
if (isInvalidCodePoint(codePoint)) {
|
||||
return 0xff_fd;
|
||||
}
|
||||
|
||||
if (codePoint >= 128 && codePoint <= 159) {
|
||||
return c1[codePoint - 128] || codePoint;
|
||||
}
|
||||
|
||||
return codePoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* XML numeric character references are the referenced Unicode code point.
|
||||
* Invalid values still become U+FFFD; the HTML Windows-1252 C1 remap is not
|
||||
* applied.
|
||||
* @see https://www.w3.org/TR/xml/#NT-CharRef
|
||||
* @param codePoint Unicode code point to convert.
|
||||
*/
|
||||
export function replaceCodePointXML(codePoint: number): number {
|
||||
return isInvalidCodePoint(codePoint) ? 0xff_fd : codePoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert the code point of a decoded numeric entity to a string, replacing
|
||||
* invalid values.
|
||||
*
|
||||
* Fast path for plain BMP code points: [1..0x7F] and [0xA0..0xD7FF] pass
|
||||
* `replaceCodePoint` unchanged (no NUL, C1 remap, surrogate, or out-of-range
|
||||
* handling) and fit a single charCode. 0xd760 = 0xD800 (the first surrogate)
|
||||
* - 0xA0.
|
||||
* @param codePoint Unicode code point to convert.
|
||||
*/
|
||||
export function codePointToString(codePoint: number): string {
|
||||
return (codePoint - 1) >>> 0 < 0x7f || (codePoint - 0xa0) >>> 0 < 0xd7_60
|
||||
? String.fromCharCode(codePoint)
|
||||
: String.fromCodePoint(replaceCodePoint(codePoint));
|
||||
}
|
||||
+1299
File diff suppressed because it is too large.
Load diff
+337
@@ -0,0 +1,337 @@
|
||||
import { XML_BITSET_VALUE, xmlEncodeRegex } from "./escape.js";
|
||||
import htmlTrieData from "./generated/encode-html.js";
|
||||
|
||||
/**
|
||||
* A node inside the encoding trie used by `encode.ts`.
|
||||
*
|
||||
* There are two physical shapes to minimize allocations and lookup cost:
|
||||
*
|
||||
* 1. Leaf node (string)
|
||||
* - A plain string (already in the form `"&name;"`).
|
||||
* - Represents a terminal match with no children.
|
||||
*
|
||||
* 2. Branch / value node (object)
|
||||
*/
|
||||
type EncodeTrieNode =
|
||||
| string
|
||||
| { value: string | null; next: Map<number, EncodeTrieNode> };
|
||||
|
||||
/**
|
||||
* Flat lookup table for ASCII entity values (code points 0–127).
|
||||
*
|
||||
* Built once at startup from the full trie. For ASCII characters that need
|
||||
* encoding, a direct `asciiEntities[charCode]` array index is much faster
|
||||
* than `Map.get(charCode)` because it avoids hashing and bucket lookup.
|
||||
*
|
||||
* A few ASCII characters also start multi-code-point entities
|
||||
* (e.g. `<` + U+20D2 → `<⃒`). For those, the table holds the branch
|
||||
* node itself (children plus the single-char value), so the ASCII path
|
||||
* never consults `htmlTrie`.
|
||||
*/
|
||||
const asciiEntities: (EncodeTrieNode | null)[] = /* #__PURE__ */ Array.from(
|
||||
{ length: 128 },
|
||||
() => null,
|
||||
);
|
||||
|
||||
const htmlTrie: Map<number, EncodeTrieNode> = (() => {
|
||||
/**
|
||||
* Parse a compact encode trie string into a Map keyed by code point.
|
||||
*
|
||||
* The serialized format (produced by `scripts/write-encode-map.ts`) stores
|
||||
* entries in ascending code-point order with delta encoding:
|
||||
*
|
||||
* [gap]name;[{children}]
|
||||
*
|
||||
* - `gap` is a base-10 integer giving `currentKey - previousKey - 1`.
|
||||
* The very first entry stores the absolute key. A gap of 0 is omitted.
|
||||
* - `name;` is the entity name (without `&` prefix) terminated by `;`.
|
||||
* Because gaps use only digits `[0-9]` and entity names always start with
|
||||
* a letter `[A-Za-z]`, no additional delimiter is needed.
|
||||
* - `{…}` is an optional children block using the same scheme recursively.
|
||||
* Children represent the second code unit of multi-character entities
|
||||
* (e.g. `<` + U+20D2 → `<⃒`).
|
||||
*/
|
||||
const trie = new Map<number, EncodeTrieNode>();
|
||||
const data = htmlTrieData;
|
||||
let cursor = 0;
|
||||
let lastKey = -1;
|
||||
|
||||
function readGap(): number {
|
||||
let value = 0;
|
||||
let ch: number;
|
||||
while (
|
||||
(ch = data.charCodeAt(cursor)) >= 48 /* '0' */ &&
|
||||
ch <= 57 /* '9' */
|
||||
) {
|
||||
value = value * 10 + ch - 48;
|
||||
cursor++;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function readEntity(): string {
|
||||
const semi = data.indexOf(";", cursor);
|
||||
const entity = `&${data.substring(cursor, semi)};`;
|
||||
cursor = semi + 1;
|
||||
return entity;
|
||||
}
|
||||
|
||||
const astralEntries: [number, string][] = [];
|
||||
|
||||
while (cursor < data.length) {
|
||||
lastKey += readGap() + 1;
|
||||
|
||||
const entityValue =
|
||||
data.charCodeAt(cursor) === 123 /* '{' */ ? null : readEntity();
|
||||
|
||||
if (data.charCodeAt(cursor) === 123 /* '{' */) {
|
||||
cursor++; // Skip '{'
|
||||
const next = new Map<number, EncodeTrieNode>();
|
||||
let childKey = -1;
|
||||
while (data.charCodeAt(cursor) !== 125 /* '}' */) {
|
||||
childKey += readGap() + 1;
|
||||
next.set(childKey, readEntity());
|
||||
}
|
||||
const branch = { value: entityValue, next };
|
||||
trie.set(lastKey, branch);
|
||||
cursor++; // Skip '}'
|
||||
// ASCII fast path holds the branch node itself (children + value).
|
||||
if (lastKey < 0x80) {
|
||||
asciiEntities[lastKey] = branch;
|
||||
}
|
||||
} else if (lastKey < 0x80) {
|
||||
asciiEntities[lastKey] = entityValue;
|
||||
} else if (lastKey > 0xff_ff) {
|
||||
astralEntries.push([lastKey, entityValue!]);
|
||||
} else {
|
||||
trie.set(lastKey, entityValue!);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Batch-insert astral entries as surrogate-pair trie nodes.
|
||||
* Entries are sorted by code point, so same-high-surrogate groups
|
||||
* are contiguous — no intermediate grouping Map needed.
|
||||
*/
|
||||
let astralIndex = 0;
|
||||
while (astralIndex < astralEntries.length) {
|
||||
const hi =
|
||||
0xd8_00 | ((astralEntries[astralIndex][0] - 0x1_00_00) >> 10);
|
||||
const children: [number, string][] = [];
|
||||
while (
|
||||
astralIndex < astralEntries.length &&
|
||||
(0xd8_00 | ((astralEntries[astralIndex][0] - 0x1_00_00) >> 10)) ===
|
||||
hi
|
||||
) {
|
||||
const lo =
|
||||
0xdc_00 |
|
||||
((astralEntries[astralIndex][0] - 0x1_00_00) & 0x3_ff);
|
||||
children.push([lo, astralEntries[astralIndex][1]]);
|
||||
astralIndex++;
|
||||
}
|
||||
trie.set(hi, { value: null, next: new Map(children) });
|
||||
}
|
||||
|
||||
return trie;
|
||||
})();
|
||||
|
||||
/**
|
||||
* Bitset covering ASCII code points 0–127. Each of the four 32-bit words
|
||||
* covers a 32-code-point range. A set bit means "this character needs
|
||||
* encoding" when used with `encodeHTML`.
|
||||
*/
|
||||
const HTML_BITSET = /* #__PURE__ */ new Uint32Array([
|
||||
0x16_00, // 09 (\t), 0A (\n), 0C (\f)
|
||||
0xfc_00_ff_fe, // 21-2D (!-.), 2E (.), 2F (/), 3A-3F (:;<=>?)
|
||||
0xf8_00_00_01, // 40 (@), 5B-5F ([\]^_)
|
||||
0x38_00_00_01, // 60 (`), 7B-7D ({|})
|
||||
]);
|
||||
|
||||
const XML_BITSET = /* #__PURE__ */ new Uint32Array([0, XML_BITSET_VALUE, 0, 0]);
|
||||
|
||||
/*
|
||||
* Regex equivalent of `HTML_BITSET` (plus all non-ASCII code units, lone
|
||||
* surrogates included — no `u` flag). Must stay in sync with the bitset:
|
||||
* the scan uses the regex to find candidates and the bitset to re-check
|
||||
* adjacent characters. The XML equivalent is `xmlEncodeRegex`, shared with
|
||||
* `escape.ts`.
|
||||
*/
|
||||
// eslint-disable-next-line unicorn/prefer-unicode-code-point-escapes -- the `\u{...}` form requires the `u` flag, which we deliberately omit so lone surrogates match by code unit
|
||||
const HTML_ENCODE_RE = /[\t\n\f!-/:-@[-`{-}\u0080-\uFFFF]/g;
|
||||
|
||||
const numericReference = (cp: number) => `&#${cp};`;
|
||||
|
||||
/**
|
||||
* Encodes all characters in the input using HTML entities. This includes
|
||||
* characters that are valid ASCII characters in HTML documents, such as `#`.
|
||||
*
|
||||
* To get a more compact output, consider using the `encodeNonAsciiHTML`
|
||||
* function, which will only encode characters that are not valid in HTML
|
||||
* documents, as well as non-ASCII characters.
|
||||
*
|
||||
* If a character has no equivalent entity, a numeric decimal reference
|
||||
* (eg. `ü`) will be used.
|
||||
* @param input Input string to encode.
|
||||
*/
|
||||
export function encodeHTML(input: string): string {
|
||||
return encodeHTMLTrieRe(HTML_BITSET, HTML_ENCODE_RE, input);
|
||||
}
|
||||
/**
|
||||
* Encodes all non-ASCII characters, as well as characters not valid in HTML
|
||||
* documents using HTML entities. This function will not encode characters that
|
||||
* are valid in HTML documents, such as `#`.
|
||||
*
|
||||
* If a character has no equivalent entity, a numeric decimal reference
|
||||
* (eg. `ü`) will be used.
|
||||
* @param input Input string to encode.
|
||||
*/
|
||||
export function encodeNonAsciiHTML(input: string): string {
|
||||
return encodeHTMLTrieRe(XML_BITSET, xmlEncodeRegex, input);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `code` (a UTF-16 code unit) must be encoded: any non-ASCII unit, or
|
||||
* an ASCII unit flagged in `bitset`.
|
||||
* @param bitset Bitset of ASCII characters to encode.
|
||||
* @param code Code unit to test.
|
||||
*/
|
||||
function isEncodable(bitset: Uint32Array, code: number): boolean {
|
||||
return code >= 0x80 || ((bitset[code >>> 5] >>> code) & 1) === 1;
|
||||
}
|
||||
|
||||
/*
|
||||
* The inline scan beats the regex jump only for short gaps (measured
|
||||
* break-even is ~7 characters; below it the per-call regex overhead
|
||||
* dominates, above it the regex skips clean spans faster in native code).
|
||||
* So we scan at most `INLINE_SCAN_WINDOW` characters inline before deferring
|
||||
* to the regex. Any gap long enough to exhaust the window switches to
|
||||
* long-gap mode, which skips the inline scan entirely; we stay in that mode
|
||||
* while total gaps are at least `LONG_GAP_THRESHOLD` characters long and
|
||||
* drop back to the inline scan as soon as a shorter gap appears. Gaps are
|
||||
* always measured from where they start, so every window-exhausting gap
|
||||
* enters long-gap mode and no gap length pays both scans repeatedly.
|
||||
*/
|
||||
/** @internal Exported for tests; not re-exported from the package entry. */
|
||||
export const INLINE_SCAN_WINDOW = 16;
|
||||
const LONG_GAP_THRESHOLD = 8;
|
||||
|
||||
function encodeHTMLTrieRe(
|
||||
bitset: Uint32Array,
|
||||
re: RegExp,
|
||||
input: string,
|
||||
): string {
|
||||
const { length } = input;
|
||||
let out: string | undefined;
|
||||
let last = 0; // Start of the next untouched slice.
|
||||
let index = 0;
|
||||
let wasLongGap = false; // The previous gap was long; skip the inline scan.
|
||||
|
||||
while (index < length) {
|
||||
let char = input.charCodeAt(index);
|
||||
|
||||
/*
|
||||
* Find the next encodable character (one matching `bitset`, or any
|
||||
* non-ASCII unit). Gaps between entities in dense text are only a
|
||||
* few characters, so scan a short window inline first; the regex —
|
||||
* which matches exactly the same characters and skips clean spans
|
||||
* in native code — runs for longer gaps. Gap lengths cluster, so
|
||||
* after a window-exhausting gap the window is skipped until a gap
|
||||
* shorter than LONG_GAP_THRESHOLD reappears. Once located, the
|
||||
* character is captured in `char` and control falls through to the
|
||||
* encode logic below instead of re-testing it on the next loop
|
||||
* iteration.
|
||||
*/
|
||||
if (!isEncodable(bitset, char)) {
|
||||
const gapStart = index;
|
||||
let next = index + 1;
|
||||
let wasFound = false;
|
||||
if (!wasLongGap) {
|
||||
const bound = Math.min(index + INLINE_SCAN_WINDOW, length);
|
||||
while (
|
||||
next < bound &&
|
||||
!isEncodable(bitset, (char = input.charCodeAt(next)))
|
||||
) {
|
||||
next++;
|
||||
}
|
||||
if (next < bound) {
|
||||
// `char` already holds the encodable unit at `next`.
|
||||
index = next;
|
||||
wasFound = true;
|
||||
} else if (next >= length) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!wasFound) {
|
||||
/*
|
||||
* Every match is a single code unit, so `test` pins it at
|
||||
* `lastIndex - 1` without allocating a match object.
|
||||
*/
|
||||
re.lastIndex = next;
|
||||
if (!re.test(input)) break;
|
||||
index = re.lastIndex - 1;
|
||||
/*
|
||||
* Reaching the regex from the inline scan means the gap
|
||||
* exhausted the window, so it is long by definition; once
|
||||
* in long-gap mode, stay until a gap shorter than the
|
||||
* threshold appears.
|
||||
*/
|
||||
wasLongGap =
|
||||
!wasLongGap || index - gapStart >= LONG_GAP_THRESHOLD;
|
||||
char = input.charCodeAt(index);
|
||||
}
|
||||
}
|
||||
|
||||
// Lazy-init: copy the prefix before the first character that needs encoding.
|
||||
if (out == null) out = input.substring(0, index);
|
||||
else if (last !== index) out += input.substring(last, index);
|
||||
|
||||
if (char < 0x80) {
|
||||
const node = asciiEntities[char];
|
||||
if (typeof node === "object" && node !== null) {
|
||||
// Multi-code-point entity first (e.g. < + U+20D2 → <⃒).
|
||||
if (index + 1 < length) {
|
||||
const value = node.next.get(input.charCodeAt(index + 1));
|
||||
if (value != null) {
|
||||
out += value;
|
||||
last = index += 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out += node.value ?? numericReference(char);
|
||||
} else {
|
||||
out += node ?? numericReference(char);
|
||||
}
|
||||
} else {
|
||||
// Non-ASCII: full trie lookup with multi-char entity support.
|
||||
let node: EncodeTrieNode | undefined | null = htmlTrie.get(char);
|
||||
|
||||
if (typeof node === "object") {
|
||||
if (index + 1 < length) {
|
||||
const value = node.next.get(input.charCodeAt(index + 1));
|
||||
if (value != null) {
|
||||
out += value;
|
||||
last = index += 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
node = node.value;
|
||||
}
|
||||
|
||||
if (node == null) {
|
||||
// No named entity exists; emit a decimal numeric reference.
|
||||
const cp = input.codePointAt(index)!;
|
||||
out += numericReference(cp);
|
||||
// Astral code points consume two UTF-16 code units.
|
||||
if (cp !== char) index++;
|
||||
} else {
|
||||
out += node;
|
||||
}
|
||||
}
|
||||
last = index += 1;
|
||||
}
|
||||
|
||||
// If nothing needed encoding, return the original string (avoids allocation).
|
||||
if (out == null) return input;
|
||||
if (last < length) out += input.substr(last);
|
||||
return out;
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* Get the named reference for an XML special character or U+00A0.
|
||||
* @param char Code unit matched by one of the escape regexes.
|
||||
*/
|
||||
function getEscape(char: number): string {
|
||||
return char === 34
|
||||
? """
|
||||
: char === 38
|
||||
? "&"
|
||||
: char === 39
|
||||
? "'"
|
||||
: char === 60
|
||||
? "<"
|
||||
: char === 62
|
||||
? ">"
|
||||
: " ";
|
||||
}
|
||||
|
||||
/**
|
||||
* Bitset for ASCII characters that need to be escaped in XML.
|
||||
*/
|
||||
export const XML_BITSET_VALUE = 0x50_00_00_c4; // 32..63 -> 34 ("),38 (&),39 ('),60 (<),62 (>)
|
||||
|
||||
/**
|
||||
* Matches exactly the characters `encodeXML` escapes: the five XML special
|
||||
* characters plus every non-ASCII code unit (lone surrogates included — no
|
||||
* `u` flag). Kept in sync with `XML_BITSET_VALUE`.
|
||||
*
|
||||
* Shared with `encodeNonAsciiHTML` in `encode.ts`. Because the regex is
|
||||
* stateful (`g` flag), every call site must set `lastIndex` before use.
|
||||
*/
|
||||
// eslint-disable-next-line unicorn/prefer-unicode-code-point-escapes -- the `\u{...}` form requires the `u` flag, which we deliberately omit so lone surrogates match by code unit
|
||||
export const xmlEncodeRegex: RegExp = /["&'<>\u0080-\uFFFF]/g;
|
||||
|
||||
/**
|
||||
* Whether `code` (a UTF-16 code unit) is escaped by {@link encodeXML}: a
|
||||
* non-ASCII unit, or one of the five XML specials flagged in
|
||||
* `XML_BITSET_VALUE` (which is only meaningful for code units 32-63).
|
||||
* @param code Code unit to test.
|
||||
*/
|
||||
function isXmlEscapable(code: number): boolean {
|
||||
return (
|
||||
code >= 0x80 ||
|
||||
(code >= 32 && code < 64 && ((XML_BITSET_VALUE >>> code) & 1) === 1)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes all non-ASCII characters, as well as characters not valid in XML
|
||||
* documents using XML entities.
|
||||
*
|
||||
* If a character has no equivalent entity, a numeric decimal reference
|
||||
* (eg. `ü`) will be used.
|
||||
* @param input Input string to encode.
|
||||
*/
|
||||
export function encodeXML(input: string): string {
|
||||
const { length } = input;
|
||||
let out: string | undefined;
|
||||
let last = 0;
|
||||
let index = 0;
|
||||
|
||||
while (index < length) {
|
||||
const char = input.charCodeAt(index);
|
||||
|
||||
/*
|
||||
* Find the next character to escape: scan a short window inline
|
||||
* (escapable characters cluster in markup-heavy input), then fall
|
||||
* back to the regex, which skips clean spans in native code.
|
||||
*/
|
||||
if (!isXmlEscapable(char)) {
|
||||
const bound = Math.min(index + 32, length);
|
||||
let next = index + 1;
|
||||
while (next < bound && !isXmlEscapable(input.charCodeAt(next))) {
|
||||
next++;
|
||||
}
|
||||
if (next < bound) {
|
||||
index = next;
|
||||
continue;
|
||||
}
|
||||
if (next >= length) break;
|
||||
xmlEncodeRegex.lastIndex = next;
|
||||
if (!xmlEncodeRegex.test(input)) break;
|
||||
index = xmlEncodeRegex.lastIndex - 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (out === undefined) out = input.substring(0, index);
|
||||
else if (last !== index) out += input.substring(last, index);
|
||||
|
||||
if (char < 64) {
|
||||
// Known replacement
|
||||
out += getEscape(char);
|
||||
last = index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Non-ASCII: encode as numeric entity (handle surrogate pair)
|
||||
const cp = input.codePointAt(index)!;
|
||||
out += `&#${cp};`;
|
||||
if (cp !== char) index++; // Skip trailing surrogate
|
||||
last = index += 1;
|
||||
}
|
||||
|
||||
if (out === undefined) return input;
|
||||
if (last < length) out += input.substr(last);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes all non-ASCII characters, as well as characters not valid in XML
|
||||
* documents using numeric decimal reference (eg. `ü`).
|
||||
*
|
||||
* Have a look at `escapeUTF8` if you want a more concise output at the expense
|
||||
* of reduced transportability.
|
||||
* @param data String to escape.
|
||||
*/
|
||||
export const escape: typeof encodeXML = encodeXML;
|
||||
|
||||
/**
|
||||
* Escape `data` using `re`, mapping each matched character to its entity.
|
||||
* Every match is one UTF-16 code unit, so its index is `lastIndex - 1`.
|
||||
* @param re Global regex matching exactly the characters to escape
|
||||
* (`"`, `&`, `'`, `<`, `>`, `\u00A0` at most).
|
||||
* @param data String to escape.
|
||||
*/
|
||||
function escapeWithRegex(re: RegExp, data: string): string {
|
||||
re.lastIndex = 0;
|
||||
if (!re.test(data)) return data;
|
||||
|
||||
let out = "";
|
||||
let last = 0;
|
||||
do {
|
||||
const index = re.lastIndex - 1;
|
||||
if (last !== index) out += data.substring(last, index);
|
||||
const char = data.charCodeAt(index);
|
||||
out += getEscape(char);
|
||||
last = index + 1;
|
||||
} while (re.test(data));
|
||||
|
||||
return out + data.substring(last);
|
||||
}
|
||||
|
||||
const xmlEscapeRegex = /["&'<>]/g;
|
||||
/**
|
||||
* Encodes all characters not valid in XML documents using XML entities.
|
||||
*
|
||||
* Note that the output will be character-set dependent.
|
||||
* @param data String to escape.
|
||||
*/
|
||||
export function escapeUTF8(data: string): string {
|
||||
return escapeWithRegex(xmlEscapeRegex, data);
|
||||
}
|
||||
|
||||
const attributeEscapeRegex = /["&<>\u{A0}]/gu;
|
||||
|
||||
/**
|
||||
* Encodes all characters that have to be escaped in HTML attributes,
|
||||
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
|
||||
* @param data String to escape.
|
||||
*/
|
||||
export function escapeAttribute(data: string): string {
|
||||
return escapeWithRegex(attributeEscapeRegex, data);
|
||||
}
|
||||
|
||||
const textEscapeRegex = /[&<>\u{A0}]/gu;
|
||||
|
||||
/**
|
||||
* Encodes all characters that have to be escaped in HTML text,
|
||||
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
|
||||
* @param data String to escape.
|
||||
*/
|
||||
export function escapeText(data: string): string {
|
||||
return escapeWithRegex(textEscapeRegex, data);
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
// Generated using scripts/write-decode-map.ts
|
||||
/* eslint-disable unicorn/prefer-unicode-code-point-escapes -- Fixed-width escapes keep generated source compact. */
|
||||
|
||||
/**
|
||||
* Serialized decode data; the format is documented in
|
||||
* `src/internal/decode-data-format.ts`. `[0]` is one-byte data (all char
|
||||
* codes <= 0xFF: header, front-coded name suffixes, per-name metadata,
|
||||
* cuckoo choice bits); `[1]` holds the replacement values.
|
||||
*/
|
||||
// biome-ignore format: generated data
|
||||
export const htmlDecodeData: readonly [string, string] = ["Q=¨`p0AEligMPacutebrevecircyfrgravelphamacrndogonpfpplyFunctionringscrsigntildeumlBackslashrvwedcyecausernoullistafropfrevescrumpeqCHcyOPYacutepitalDifferentialDyleyscaronedilirconintdotedillanterDotfrhiircleDotMinusPlusTimeslockwiseContourIntegralseCurlyDoubleQuoteQuoteolonengruentinttourIntegralpfroductunterClockwiseContourIntegralrossscrupCapDDotrahdJcyScyZcyaggerrrshvcaronyeltafriacriticalAcuteDotubleAcuteGraveTildemondfferentialDopftDotEqualubleContourIntegralDotwnArrowLeftArrowRightArrowTeeongLeftArrowRightArrowRightArrowRightArrowTeeUpArrowDownArrowVerticalBarwnArrowBarUpArrowBreveLeftRightVectorTeeVectorVectorBarRightTeeVectorVectorBarTeeArrowarrowscrtrokENGTHacutecaronircydotfrgravelementmacrptySmallSquareVerySmallSquareogonpfpsilonqualTildeilibriumscrimtaumlxistsponentialEFcyfrilledSmallSquareVerySmallSquareopfrAlluriertrfscrGJcyTammadbrevecedilircydotfrgopfreaterEqualLessFullEqualGreaterLessSlantEqualTildescrtHARDcyacektcircfrilbertSpaceopfrizontalLinescrtrokumpDownHumpEqualIEcyJligOcyacutecircydotfrgravemacrginaryIpliesntegralrsectionvisibleCommaTimesogonpftascrtildeukcymlJcircyfropfscrercyukcyKHcyJcyappacedilyfropfscrLJcyTacutembdangplacetrfrrcaronedilyeftAngleBracketrrowBarRightArrowCeilingDoubleBracketwnTeeVectorVectorBarFloorRightArrowVectorTeeArrowVectorriangleBarEqualUpDownVectorTeeVectorVectorBarVectorBararrowrightarrowssEqualGreaterFullEqualGreaterLessSlantEqualTildefrleftarrowmidotongLeftArrowRightArrowRightArrowleftarrowrightarrowrightarrowpfwerLeftArrowRightArrowscrhtroktMapcyediumSpacellintrffrinusPlusopfscruNJcyacutecaronedilyegativeMediumSpaceThickSpacenSpaceVeryThinSpacestedGreaterGreaterLessLesswLinefroBreaknBreakingSpacepftCongruentupCapDoubleVerticalBarElementqualTildexistsGreaterEqualFullEqualGreaterLessSlantEqualTildeHumpDownHumpEqualLeftTriangleBarEqualssEqualGreaterLessSlantEqualTildeNestedGreaterGreaterLessLessPrecedesEqualSlantEqualReverseElementightTriangleBarEqualSquareSubsetEqualpersetEqualubsetEqualcceedsEqualSlantEqualTildepersetEqualTildeEqualFullEqualTildeVerticalBarscrtildeuOEligacutecircydblacfrgravemacregaicronopfpenCurlyDoubleQuoteQuoterscrlashtildemesumlverBarraceketParenthesisPartialDcyfrhiilusMinusoincareplanepfrecedesEqualSlantEqualTildeimeoductportionalscriQUOTfropfscrRBarrEGacutengrrtlcaronedilyeverseElementquilibriumUpEquilibriumfrhoightAngleBracketrrowBarLeftArrowCeilingDoubleBracketwnTeeVectorVectorBarFloorTeeArrowVectorriangleBarEqualUpDownVectorTeeVectorVectorBarVectorBararrowopfundImpliesrightarrowscrhuleDelayedSHCHcycyOFTcyacutecaronedilircyfrhortDownArrowLeftArrowRightArrowUpArrowigmamallCircleopfqrtuareIntersectionSubsetEqualpersetEqualUnionscrtarubsetEqualcceedsEqualSlantEqualTildehThatmpersetEqualsetTHORNRADESHcycyabucaronedilyfrhereforetaickSpacenSpaceildeEqualFullEqualTildeopfripleDotscrtrokUacuterrocirbrcyevecircydblacfrgravemacrnderBarraceketParenthesisionPlusogonpfpArrowBarDownArrowDownArrowEquilibriumTeeArrowarrowdownarrowperLeftArrowRightArrowsilonringscrtildeumlVDashbarcydashleerbarticalBarLineSeparatorTildeyThinSpacefropfscrvdashWcircedgefropfscrXfriopfscrYAcyIcyUcyacutecircyfropfscrumlZHcyacutecaronydoteroWidthSpacetafropfscraacutebrevecEdircuteyeligfrgravelefsymphphamacrlgpndanddslopevgelemsdaabcdefghrtvbdsphtzarrogonpfpEacireidosproxeqringscrtympeqtildeumlwconintintbNotackcongepsilonprimesimeqrveewedgebrktbrkcongydquoecausemptyvpsirnoutahweenfrigcapircupodotplustimessqcuptartriangledownupuplusveewedgekarowlacklozengesquaretriangledownleftrightnkk12434ocknequivotopfttomwtiexDLRlrHDUduULRlrVHLRhlrboxdLRlrhDUduminusplustimesuLRlrvHLRhlrprimerevevbarscremiimeolbhsubulletmpEeqcacutepandbrcupcapupdotsretoncapsronedilircupssmdotedilmptyvnterdotfrhcyeckmarkiirEceqlearrowleftrightdRSastcircdashefnintmidscirlubsuitoloneqmmatpfnlementxesngdotintpfrodysrrarrossscrubepetdotudarrlreprsclarrppbrcapcapupdotorsrarrmlyeqprecsuccveewedgerenvearrowleftrightveewedwconintintylctydArrHaraggerlethrrshvbkarowlaccaronydaggerrrotseqegltamptyvfishtrharlriamondsuitsegammasinvideontimesonxjcylcornropollarpfteqdotminusplussquareublebarwedgewnarrowdownarrowsharpoonleftrightrbkarowcornropscryoltroktdotrifuarrharwanglezcyigrarreDDototacutestercaronircolonydotefDotrgravesdotlinterslsdotmacrptysetvsp134ngspogonpfparsllussilonvqcircolonsimlantgtrlessualsestivDDvparslrDotarrscrdotimtahumlroxclistpectationonentialefallingdotseqcyemalefiligligligriligjliglatligtnsnofopfrallkvpartintrac123456823534584556878slownscrgElacutemmadpbrevecircydotelqqslantsccdotollesfrggimeljcylEajnEapproxeqqsimopfravescrimeltccirdotlParquestrapproxrrdoteqlessqlesslesssimvertneqqnEhArrairsplfmiltrdcyrcirwbarcirceartsuitlliprconfrksearowwarowoarrmthtokleftarrowrightarrowpfrbarscrlashtrokybullpheniacutecircyecyxclffrgraveiiintntnfinotajligmacrgelinepartthofpedncarefintieodottcalegersrcallarhkprodocygonpftaprodquestscrinEdotsvvtildeukcymljcircyfrmathopfscrercyukcykappavcedilyfrgreenhcyjcyopfscrlAarrrrtailBarrEgHaracuteemptyvgranmbdangdlepq
Line truncated
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
// Generated using scripts/write-encode-map.ts
|
||||
|
||||
export default "9Tab;NewLine;22excl;quot;num;dollar;percnt;amp;apos;lpar;rpar;ast;plus;comma;1period;sol;10colon;semi;lt;{8402nvlt;}equals;{8421bne;}gt;{8402nvgt;}quest;commat;26lsqb;bsol;rsqb;Hat;lowbar;grave;5{106fjlig;}20lcub;vert;rcub;34nbsp;iexcl;cent;pound;curren;yen;brvbar;sect;die;copy;ordf;laquo;not;shy;reg;macr;deg;pm;sup2;sup3;acute;micro;para;middot;cedil;sup1;ordm;raquo;frac14;half;frac34;iquest;Agrave;Aacute;Acirc;Atilde;Auml;angst;AElig;Ccedil;Egrave;Eacute;Ecirc;Euml;Igrave;Iacute;Icirc;Iuml;ETH;Ntilde;Ograve;Oacute;Ocirc;Otilde;Ouml;times;Oslash;Ugrave;Uacute;Ucirc;Uuml;Yacute;THORN;szlig;agrave;aacute;acirc;atilde;auml;aring;aelig;ccedil;egrave;eacute;ecirc;euml;igrave;iacute;icirc;iuml;eth;ntilde;ograve;oacute;ocirc;otilde;ouml;div;oslash;ugrave;uacute;ucirc;uuml;yacute;thorn;yuml;Amacr;amacr;Abreve;abreve;Aogon;aogon;Cacute;cacute;Ccirc;ccirc;Cdot;cdot;Ccaron;ccaron;Dcaron;dcaron;Dstrok;dstrok;Emacr;emacr;2Edot;edot;Eogon;eogon;Ecaron;ecaron;Gcirc;gcirc;Gbreve;gbreve;Gdot;gdot;Gcedil;1Hcirc;hcirc;Hstrok;hstrok;Itilde;itilde;Imacr;imacr;2Iogon;iogon;Idot;imath;IJlig;ijlig;Jcirc;jcirc;Kcedil;kcedil;kgreen;Lacute;lacute;Lcedil;lcedil;Lcaron;lcaron;Lmidot;lmidot;Lstrok;lstrok;Nacute;nacute;Ncedil;ncedil;Ncaron;ncaron;napos;ENG;eng;Omacr;omacr;2Odblac;odblac;OElig;oelig;Racute;racute;Rcedil;rcedil;Rcaron;rcaron;Sacute;sacute;Scirc;scirc;Scedil;scedil;Scaron;scaron;Tcedil;tcedil;Tcaron;tcaron;Tstrok;tstrok;Utilde;utilde;Umacr;umacr;Ubreve;ubreve;Uring;uring;Udblac;udblac;Uogon;uogon;Wcirc;wcirc;Ycirc;ycirc;Yuml;Zacute;zacute;Zdot;zdot;Zcaron;zcaron;19fnof;34imped;63gacute;65jmath;142circ;caron;16breve;dot;ring;ogon;tilde;dblac;51DownBreve;127Alpha;Beta;Gamma;Delta;Epsilon;Zeta;Eta;Theta;Iota;Kappa;Lambda;Mu;Nu;Xi;Omicron;Pi;Rho;1Sigma;Tau;Upsilon;Phi;Chi;Psi;ohm;7alpha;beta;gamma;delta;epsi;zeta;eta;theta;iota;kappa;lambda;mu;nu;xi;omicron;pi;rho;sigmaf;sigma;tau;upsi;phi;chi;psi;omega;7thetav;Upsi;2phiv;piv;5Gammad;gammad;18kappav;rhov;3epsiv;bepsi;10IOcy;DJcy;GJcy;Jukcy;DScy;Iukcy;YIcy;Jsercy;LJcy;NJcy;TSHcy;KJcy;1Ubrcy;DZcy;Acy;Bcy;Vcy;Gcy;Dcy;IEcy;ZHcy;Zcy;Icy;Jcy;Kcy;Lcy;Mcy;Ncy;Ocy;Pcy;Rcy;Scy;Tcy;Ucy;Fcy;KHcy;TScy;CHcy;SHcy;SHCHcy;HARDcy;Ycy;SOFTcy;Ecy;YUcy;YAcy;acy;bcy;vcy;gcy;dcy;iecy;zhcy;zcy;icy;jcy;kcy;lcy;mcy;ncy;ocy;pcy;rcy;scy;tcy;ucy;fcy;khcy;tscy;chcy;shcy;shchcy;hardcy;ycy;softcy;ecy;yucy;yacy;1iocy;djcy;gjcy;jukcy;dscy;iukcy;yicy;jsercy;ljcy;njcy;tshcy;kjcy;1ubrcy;dzcy;7074ensp;emsp;emsp13;emsp14;1numsp;puncsp;thinsp;hairsp;ZeroWidthSpace;zwnj;zwj;lrm;rlm;dash;2ndash;mdash;horbar;Vert;1lsquo;rsquo;sbquo;1ldquo;rdquo;bdquo;1dagger;Dagger;bull;2nldr;mldr;9permil;pertenk;prime;Prime;tprime;bprime;3lsaquo;rsaquo;3oline;2caret;1hybull;frasl;10bsemi;7qprime;7MediumSpace;{8202ThickSpace;}NoBreak;af;it;ic;72euro;46tdot;DotDot;37Copf;2incare;4gscr;Hscr;Hfr;Hopf;planckh;hbar;Iscr;Im;Lscr;ell;1Nopf;numero;copysr;wp;Popf;Qopf;Rscr;Re;Ropf;rx;3trade;1Zopf;2mho;Zfr;iiota;2Bscr;Cfr;1escr;Escr;Fscr;1Mscr;oscr;aleph;beth;gimel;daleth;12DD;dd;ee;ii;10frac13;frac23;frac15;frac25;frac35;frac45;frac16;frac56;frac18;frac38;frac58;frac78;49larr;uarr;rarr;darr;harr;varr;nwarr;nearr;searr;swarr;nlarr;nrarr;1rarrw;{824nrarrw;}Larr;Uarr;Rarr;Darr;larrtl;rarrtl;mapstoleft;mapstoup;map;mapstodown;1larrhk;rarrhk;larrlp;rarrlp;harrw;nharr;1lsh;rsh;ldsh;rdsh;1crarr;cularr;curarr;2olarr;orarr;lharu;lhard;uharr;uharl;rharu;rhard;dharr;dharl;rlarr;udarr;lrarr;llarr;uuarr;rrarr;ddarr;lrhar;rlhar;nlArr;nhArr;nrArr;lArr;uArr;rArr;dArr;iff;vArr;nwArr;neArr;seArr;swArr;lAarr;rAarr;1zigrarr;6larrb;rarrb;15duarr;7loarr;roarr;hoarr;forall;comp;part;{824npart;}exist;nexist;empty;1Del;in;notin;1ni;notni;2prod;coprod;sum;minus;mp;plusdo;1setmn;lowast;compfn;1Sqrt;2prop;infin;angrt;ang;{8402nang;}angmsd;angsph;mid;nmid;par;npar;and;or;cap;{65024caps;}cup;{65024cups;}int;Int;tint;oint;Conint;Cconint;cwint;cwconint;awconint;there4;becaus;ratio;Colon;minusd;1mDDot;homtht;sim;{8402nvsim;}bsim;{817race;}ac;{819acE;}acd;wr;nsim;esim;{824nesim;}sime;nsime;cong;simne;ncong;ap;nap;ape;apid;{824napid;}bcong;CupCap;{8402nvap;}bump;{824nbump;}bumpe;{824nbumpe;}doteq;{824nedot;}eDot;efDot;erDot;Assign;ecolon;ecir;cire;1wedgeq;veeeq;1trie;2equest;ne;equiv;{8421bnequiv;}nequiv;1le;{8402nvle;}ge;{8402nvge;}lE;{824nlE;}gE;{824ngE;}lnE;{65024lvnE;}gnE;{65024gvnE;}ll;{824nLtv;7577nLt;}gg;{824nGtv;7577nGt;}twixt;NotCupCap;nlt;ngt;nle;nge;lsim;gsim;nlsim;ngsim;lg;gl;ntlg;ntgl;pr;sc;prcue;sccue;prsim;scsim;{824NotSucceedsTilde;}npr;nsc;sub;{8402vnsub;}sup;{8402vnsup;}nsub;nsup;sube;supe;nsube;nsupe;subne;{65024vsubne;}supne;{65024vsupne;}1cupdot;uplus;sqsub;{824NotSquareSubset;}sqsup;{824NotSquareSuperset;}sqsube;sqsupe;sqcap;{65024sqcaps;}sqcup;{65024sqcups;}oplus;ominus;otimes;osol;odot;ocir;oast;1odash;plusb;minusb;timesb;sdotb;vdash;dashv;top;bot;1models;vDash;Vdash;Vvdash;VDash;nvdash;nvDash;nVdash;nVDash;prurel;1vltri;vrtri;ltrie;{8402nvltrie;}rtrie;{8402nvrtrie;}origof;imof;mumap;hercon;intcal;veebar;1barvee;angrtvb;lrtri;Wedge;Vee;xcLine truncated
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
import { type DecodingMode, decodeHTML, decodeXML } from "./decode.js";
|
||||
import { encodeHTML, encodeNonAsciiHTML } from "./encode.js";
|
||||
import {
|
||||
encodeXML,
|
||||
escapeAttribute,
|
||||
escapeText,
|
||||
escapeUTF8,
|
||||
} from "./escape.js";
|
||||
|
||||
/** The level of entities to support. */
|
||||
export enum EntityLevel {
|
||||
/** Support only XML entities. */
|
||||
XML = 0,
|
||||
/** Support HTML entities, which are a superset of XML entities. */
|
||||
HTML = 1,
|
||||
}
|
||||
|
||||
/**
|
||||
* Encoding strategy used by `encode`.
|
||||
*/
|
||||
export enum EncodingMode {
|
||||
/**
|
||||
* The output is UTF-8 encoded. Only characters that need escaping within
|
||||
* XML will be escaped.
|
||||
*/
|
||||
UTF8,
|
||||
/**
|
||||
* The output consists only of ASCII characters. Characters that need
|
||||
* escaping within HTML, and characters that aren't ASCII characters will
|
||||
* be escaped.
|
||||
*/
|
||||
ASCII,
|
||||
/**
|
||||
* Encode all characters that have an equivalent entity, as well as all
|
||||
* characters that are not ASCII characters.
|
||||
*/
|
||||
Extensive,
|
||||
/**
|
||||
* Encode all characters that have to be escaped in HTML attributes,
|
||||
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
|
||||
*/
|
||||
Attribute,
|
||||
/**
|
||||
* Encode all characters that have to be escaped in HTML text,
|
||||
* following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}.
|
||||
*/
|
||||
Text,
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for `decode`.
|
||||
*/
|
||||
export interface DecodingOptions {
|
||||
/**
|
||||
* The level of entities to support.
|
||||
* @default {@link EntityLevel.XML}
|
||||
*/
|
||||
level?: EntityLevel;
|
||||
/**
|
||||
* Decoding mode. If `Legacy`, will support legacy entities not terminated
|
||||
* with a semicolon (`;`).
|
||||
*
|
||||
* Always `Strict` for XML. For HTML, set this to
|
||||
* {@link DecodingMode.Attribute} if you are parsing an attribute value.
|
||||
* @default {@link DecodingMode.Legacy}
|
||||
*/
|
||||
mode?: DecodingMode | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes a string with entities.
|
||||
* @param input String to decode.
|
||||
* @param options Decoding options.
|
||||
*/
|
||||
export function decode(
|
||||
input: string,
|
||||
options: DecodingOptions | EntityLevel = EntityLevel.XML,
|
||||
): string {
|
||||
const level = typeof options === "number" ? options : options.level;
|
||||
|
||||
if (level === EntityLevel.HTML) {
|
||||
const mode = typeof options === "object" ? options.mode : undefined;
|
||||
return decodeHTML(input, mode);
|
||||
}
|
||||
|
||||
return decodeXML(input);
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for `encode`.
|
||||
*/
|
||||
export interface EncodingOptions {
|
||||
/**
|
||||
* The level of entities to support.
|
||||
* @default {@link EntityLevel.XML}
|
||||
*/
|
||||
level?: EntityLevel;
|
||||
/**
|
||||
* Output format.
|
||||
* @default {@link EncodingMode.Extensive}
|
||||
*/
|
||||
mode?: EncodingMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes a string with entities.
|
||||
* @param input String to encode.
|
||||
* @param options Encoding options.
|
||||
*/
|
||||
export function encode(
|
||||
input: string,
|
||||
options: EncodingOptions | EntityLevel = EntityLevel.XML,
|
||||
): string {
|
||||
const { mode = EncodingMode.Extensive, level = EntityLevel.XML } =
|
||||
typeof options === "number" ? { level: options } : options;
|
||||
|
||||
switch (mode) {
|
||||
case EncodingMode.UTF8: {
|
||||
return escapeUTF8(input);
|
||||
}
|
||||
case EncodingMode.Attribute: {
|
||||
return escapeAttribute(input);
|
||||
}
|
||||
case EncodingMode.Text: {
|
||||
return escapeText(input);
|
||||
}
|
||||
case EncodingMode.ASCII: {
|
||||
return (
|
||||
level === EntityLevel.HTML ? encodeNonAsciiHTML : encodeXML
|
||||
)(input);
|
||||
}
|
||||
// biome-ignore lint/complexity/noUselessSwitchCase: we get an error for the switch not being exhaustive
|
||||
case EncodingMode.Extensive:
|
||||
default: {
|
||||
return (level === EntityLevel.HTML ? encodeHTML : encodeXML)(input);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export {
|
||||
DecodingMode,
|
||||
decodeHTML,
|
||||
decodeHTMLAttribute,
|
||||
decodeHTMLStrict,
|
||||
decodeXML,
|
||||
decodeXML as decodeXMLStrict,
|
||||
HtmlEntityDecoder,
|
||||
XmlEntityDecoder,
|
||||
} from "./decode.js";
|
||||
|
||||
export {
|
||||
encodeHTML,
|
||||
encodeNonAsciiHTML,
|
||||
} from "./encode.js";
|
||||
export {
|
||||
encodeXML,
|
||||
escape,
|
||||
escapeAttribute,
|
||||
escapeText,
|
||||
escapeUTF8,
|
||||
} from "./escape.js";
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
/**
|
||||
* Constants and helpers shared between the decode-data generator
|
||||
* (`scripts/write-decode-map.ts`) and the runtime (`src/decode.ts`).
|
||||
*
|
||||
* The format and the algorithms (front-coded names, exact 32-bit keys in a
|
||||
* two-choice cuckoo table, the length-probe front end, and the measured
|
||||
* engineering notes) are documented with references in
|
||||
* `scripts/README.md`.
|
||||
*/
|
||||
|
||||
/** Bias added to every meta char so none needs escaping in JS source. */
|
||||
export const META_BIAS = 0x23;
|
||||
/** Bias for header and choice-bit chars. */
|
||||
export const HEADER_BIAS = 0x30;
|
||||
/** Number of header chars: n (2), suffixes length (2), bucket count (2). */
|
||||
export const HEADER_LENGTH = 6;
|
||||
/** Choice bits packed per char. */
|
||||
export const CHOICE_BITS_PER_CHAR = 6;
|
||||
|
||||
/** Multiplier deriving the first candidate bucket from a key. */
|
||||
export const BUCKET_HASH_1 = 0x9e_37_79_b1;
|
||||
/** Multiplier deriving the second candidate bucket from a key. */
|
||||
export const BUCKET_HASH_2 = 0x85_eb_ca_6b;
|
||||
|
||||
/** Size of the (c0,c1) class table (10-bit index). */
|
||||
export const PAIR_TABLE_SIZE = 1024;
|
||||
|
||||
/**
|
||||
* Map an alphanumeric char code to 6 bits (1..62); 0 = not alphanumeric.
|
||||
* Used for the key's last-character field.
|
||||
*/
|
||||
export const CHAR_REMAP: Uint8Array = ((): Uint8Array => {
|
||||
const remap = new Uint8Array(128);
|
||||
for (let code = 0x30; code <= 0x39; code++) remap[code] = code - 0x2f;
|
||||
for (let code = 0x41; code <= 0x5a; code++) remap[code] = code - 0x36;
|
||||
for (let code = 0x61; code <= 0x7a; code++) remap[code] = code - 0x3c;
|
||||
return remap;
|
||||
})();
|
||||
|
||||
/**
|
||||
* The exact 32-bit key for a name occurring at `nameStart` with `length`
|
||||
* chars. Covers the first two and last two characters plus the length;
|
||||
* middle characters are verified separately against the names blob.
|
||||
*
|
||||
* The hot decoder inlines this computation; tests assert both stay in sync
|
||||
* by looking every entity up through the public API.
|
||||
* @param text Text containing the name.
|
||||
* @param nameStart Index of the name's first character.
|
||||
* @param length Length of the name.
|
||||
*/
|
||||
export function exactKey(
|
||||
text: string,
|
||||
nameStart: number,
|
||||
length: number,
|
||||
): number {
|
||||
return (
|
||||
(text.charCodeAt(nameStart) << 25) |
|
||||
(text.charCodeAt(nameStart + 1) << 18) |
|
||||
(text.charCodeAt(nameStart + length - 2) << 11) |
|
||||
(CHAR_REMAP[text.charCodeAt(nameStart + length - 1)] << 5) |
|
||||
length
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The 10-bit (c0,c1) class index used by the probe front end. The function
|
||||
* was chosen by exhaustive search over load-free mixers for minimal
|
||||
* candidate-set collisions on the real entity set.
|
||||
* @param c0 First char code of the candidate name.
|
||||
* @param c1 Second char code.
|
||||
*/
|
||||
export function pairIndex(c0: number, c1: number): number {
|
||||
return (((c0 * 3) << 3) ^ c1) & (PAIR_TABLE_SIZE - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* First candidate bucket for a key in a table of `buckets` buckets.
|
||||
* @param key Exact key.
|
||||
* @param buckets Bucket count.
|
||||
*/
|
||||
export function bucketOne(key: number, buckets: number): number {
|
||||
return ((Math.imul(key, BUCKET_HASH_1) >>> 16) * buckets) >>> 16;
|
||||
}
|
||||
|
||||
/**
|
||||
* Second candidate bucket for a key.
|
||||
* @param key Exact key.
|
||||
* @param buckets Bucket count.
|
||||
*/
|
||||
export function bucketTwo(key: number, buckets: number): number {
|
||||
return ((Math.imul(key, BUCKET_HASH_2) >>> 16) * buckets) >>> 16;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode data for the HTML entity set, built from the serialized form at
|
||||
* module init. The format and the algorithms operating on it are documented
|
||||
* in `scripts/README.md`. XML's five entities are matched directly and
|
||||
* ship no data.
|
||||
*/
|
||||
export interface DecodeData {
|
||||
/** Exact 32-bit keys; two-slot buckets, slot index = 2*bucket (+1). */
|
||||
keys: Int32Array;
|
||||
/** Bucket count for the cuckoo table. */
|
||||
buckets: number;
|
||||
/** Per-slot word offset in `middles`. */
|
||||
slotMidOff: Uint16Array;
|
||||
/**
|
||||
* Per-slot value location in `values`: offset in bits 2..15, legacy
|
||||
* flag in bit 1, and length minus one in bit 0. Replaces a per-slot
|
||||
* `string[]`: half the footprint and no
|
||||
* per-value heap objects, for a slightly costlier emit (see
|
||||
* `emitHtmlValue`).
|
||||
*/
|
||||
slotValue: Uint16Array;
|
||||
/** Concatenated replacement values; indexed via `slotValue`. */
|
||||
values: string;
|
||||
/**
|
||||
* Per (c0,c1) class: candidate name lengths. Bits 0-14 = exact lengths
|
||||
* 2..16, bit 15 = lengths above 16 exist, bits 16-20 = legacy lengths.
|
||||
*/
|
||||
lengthBits: Uint32Array;
|
||||
/** Deduplicated middles, packed as pairs of UTF-16 code units per word. */
|
||||
middles: Uint32Array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the lookup structures from a serialized dataset.
|
||||
* @param packed Serialized decode data, see `decode-data-format.ts`.
|
||||
*/
|
||||
export function initDecodeData(packed: readonly [string, string]): DecodeData {
|
||||
const [data, values] = packed;
|
||||
const nameCount =
|
||||
((data.charCodeAt(0) - HEADER_BIAS) << 6) |
|
||||
(data.charCodeAt(1) - HEADER_BIAS);
|
||||
const suffixesLength =
|
||||
((data.charCodeAt(2) - HEADER_BIAS) << 6) |
|
||||
(data.charCodeAt(3) - HEADER_BIAS);
|
||||
const buckets =
|
||||
((data.charCodeAt(4) - HEADER_BIAS) << 6) |
|
||||
(data.charCodeAt(5) - HEADER_BIAS);
|
||||
const metaStart = HEADER_LENGTH + suffixesLength;
|
||||
const choicesStart = metaStart + 2 * nameCount;
|
||||
|
||||
const slotCount = 2 * buckets;
|
||||
const keys = new Int32Array(slotCount);
|
||||
const slotMidOff = new Uint16Array(slotCount);
|
||||
const slotValue = new Uint16Array(slotCount);
|
||||
const lengthBits = new Uint32Array(PAIR_TABLE_SIZE);
|
||||
const middleOffsets = new Map<string, number>();
|
||||
const middles: number[] = [];
|
||||
let name = "";
|
||||
let suffixOffset = HEADER_LENGTH;
|
||||
let valueOffset = 0;
|
||||
|
||||
for (let index = 0; index < nameCount; index++) {
|
||||
const meta0 = data.charCodeAt(metaStart + 2 * index) - META_BIAS;
|
||||
const meta1 = data.charCodeAt(metaStart + 2 * index + 1) - META_BIAS;
|
||||
const prefixLength = meta0 & 31;
|
||||
const length = prefixLength + (meta1 & 31);
|
||||
const valueLength = (meta1 >> 5) + 1;
|
||||
name =
|
||||
name.slice(0, prefixLength) +
|
||||
data.slice(suffixOffset, suffixOffset + length - prefixLength);
|
||||
suffixOffset += length - prefixLength;
|
||||
|
||||
const key = exactKey(name, 0, length);
|
||||
const choice =
|
||||
(data.charCodeAt(
|
||||
choicesStart + Math.floor(index / CHOICE_BITS_PER_CHAR),
|
||||
) -
|
||||
HEADER_BIAS) &
|
||||
(1 << (index % CHOICE_BITS_PER_CHAR));
|
||||
let slot = 2 * (choice === 0 ? bucketOne : bucketTwo)(key, buckets);
|
||||
if (keys[slot] !== 0) slot += 1;
|
||||
keys[slot] = key;
|
||||
|
||||
if (length > 4) {
|
||||
const middle = name.slice(2, length - 2);
|
||||
const existing = middleOffsets.get(middle);
|
||||
if (existing === undefined) {
|
||||
middleOffsets.set(middle, middles.length);
|
||||
slotMidOff[slot] = middles.length;
|
||||
for (
|
||||
let middleIndex = 0;
|
||||
middleIndex < middle.length;
|
||||
middleIndex += 2
|
||||
) {
|
||||
middles.push(
|
||||
middle.charCodeAt(middleIndex) |
|
||||
(middle.charCodeAt(middleIndex + 1) << 16),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
slotMidOff[slot] = existing;
|
||||
}
|
||||
}
|
||||
|
||||
const pair = pairIndex(name.charCodeAt(0), name.charCodeAt(1));
|
||||
lengthBits[pair] |= length <= 16 ? 1 << (length - 2) : 0x80_00;
|
||||
if ((meta0 & 0x20) !== 0) {
|
||||
lengthBits[pair] |= 1 << (length - 2 + 16);
|
||||
}
|
||||
|
||||
/*
|
||||
* Values have one or two units, leaving bit 1 for the legacy flag.
|
||||
* The generator checks the 14-bit offset and two-unit value limits.
|
||||
*/
|
||||
slotValue[slot] =
|
||||
(valueOffset << 2) | (valueLength - 1) | ((meta0 & 0x20) >> 4);
|
||||
valueOffset += valueLength;
|
||||
}
|
||||
|
||||
return {
|
||||
keys,
|
||||
buckets,
|
||||
slotMidOff,
|
||||
slotValue,
|
||||
values,
|
||||
lengthBits,
|
||||
middles: new Uint32Array(middles),
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user