the editable site (validation-lab)
deploy / build-and-publish (push) Successful in 1m37s

This commit is contained in:
2026-11-21 08:03:55 +01:00
commit 3ac81d5a52
13454 changed files with 2227005 additions and 0 deletions
+4
View File
@@ -0,0 +1,4 @@
export type LightOptions = import("./lib/core.js").LightOptions;
export type Options = import("./lib/index.js").Options;
export { stringifyEntitiesLight, stringifyEntities } from "./lib/index.js";
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"2BACa,OAAO,eAAe,EAAE,YAAY;sBACpC,OAAO,gBAAgB,EAAE,OAAO"}
+6
View File
@@ -0,0 +1,6 @@
/**
* @typedef {import('./lib/core.js').LightOptions} LightOptions
* @typedef {import('./lib/index.js').Options} Options
*/
export {stringifyEntitiesLight, stringifyEntities} from './lib/index.js'
+8
View File
@@ -0,0 +1,8 @@
/**
* List of legacy (that don’t need a trailing `;`) named references which could,
* depending on what follows them, turn into a different meaning
*
* @type {Array<string>}
*/
export const dangerous: Array<string>;
//# sourceMappingURL=dangerous.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"dangerous.d.ts","sourceRoot":"","sources":["dangerous.js"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,wBAFU,KAAK,CAAC,MAAM,CAAC,CAWtB"}
+16
View File
@@ -0,0 +1,16 @@
/**
* List of legacy (that don’t need a trailing `;`) named references which could,
* depending on what follows them, turn into a different meaning
*
* @type {Array<string>}
*/
export const dangerous = [
'cent',
'copy',
'divide',
'gt',
'lt',
'not',
'para',
'times'
]
+38
View File
@@ -0,0 +1,38 @@
/**
* Encode certain characters in `value`.
*
* @param {string} value
* Value to encode.
* @param {CoreWithFormatOptions} options
* Configuration.
* @returns {string}
* Encoded value.
*/
export function core(value: string, options: CoreWithFormatOptions): string;
/**
* Configuration for `stringifyEntitiesLight`.
*/
export type LightOptions = {
/**
* Whether to only escape possibly dangerous characters (default: `false`);
* those characters are `"`, `&`, `'`, `<`, `>`, and `` ` ``.
*/
escapeOnly?: boolean | null | undefined;
/**
* Whether to only escape the given subset of characters (optional);
* only BMP characters are supported here (so no emoji).
*/
subset?: ReadonlyArray<string> | null | undefined;
};
/**
* Internal format options.
*/
export type FormatOptions = {
/**
* Format strategy.
*/
format: (code: number, next: number, options: CoreWithFormatOptions) => string;
};
export type CoreWithFormatOptions = LightOptions & FormatOptions & FormatSmartOptions;
import type { FormatSmartOptions } from './util/format-smart.js';
//# sourceMappingURL=core.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["core.js"],"names":[],"mappings":"AAoCA;;;;;;;;;GASG;AACH,4BAPW,MAAM,WAEN,qBAAqB,GAEnB,MAAM,CAkElB;;;;;;;;;iBAtGa,OAAO,GAAG,IAAI,GAAG,SAAS;;;;;aAG1B,aAAa,CAAC,MAAM,CAAC,GAAG,IAAI,GAAG,SAAS;;;;;;;;;YAQxC,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,qBAAqB,KAAK,MAAM;;oCAKvE,YAAY,GAAG,aAAa,GAAG,kBAAkB;wCAtBzB,wBAAwB"}
+151
View File
@@ -0,0 +1,151 @@
/**
* @import {FormatSmartOptions} from './util/format-smart.js'
*/
/**
* @typedef LightOptions
* Configuration for `stringifyEntitiesLight`.
* @property {boolean | null | undefined} [escapeOnly=false]
* Whether to only escape possibly dangerous characters (default: `false`);
* those characters are `"`, `&`, `'`, `<`, `>`, and `` ` ``.
* @property {ReadonlyArray<string> | null | undefined} [subset]
* Whether to only escape the given subset of characters (optional);
* only BMP characters are supported here (so no emoji).
*/
/**
* @typedef FormatOptions
* Internal format options.
* @property {(code: number, next: number, options: CoreWithFormatOptions) => string} format
* Format strategy.
*/
/**
* @typedef {LightOptions & FormatOptions & FormatSmartOptions} CoreWithFormatOptions
*/
const defaultSubsetRegex = /["&'<>`]/g
const surrogatePairsRegex = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g
const controlCharactersRegex =
// eslint-disable-next-line no-control-regex, regexp/hexadecimal-escape, regexp/no-control-character, regexp/no-obscure-range -- matching control characters is the point.
/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g
const regexEscapeRegex = /[|\\{}()[\]^$+*?.]/g
/** @type {WeakMap<ReadonlyArray<string>, RegExp>} */
const subsetToRegexCache = new WeakMap()
/**
* Encode certain characters in `value`.
*
* @param {string} value
* Value to encode.
* @param {CoreWithFormatOptions} options
* Configuration.
* @returns {string}
* Encoded value.
*/
export function core(value, options) {
value = value.replace(
options.subset
? charactersToExpressionCached(options.subset)
: defaultSubsetRegex,
basic
)
if (options.subset || options.escapeOnly) {
return value
}
return (
value
// Surrogate pairs.
.replace(surrogatePairsRegex, surrogate)
// BMP control characters (C0 except for LF, CR, SP; DEL; and some more
// non-ASCII ones).
.replace(controlCharactersRegex, basic)
)
/**
* Encode a surrogate pair.
*
* @param {string} pair
* Surrogate pair.
* @param {number} index
* Index of `pair` in `all`.
* @param {string} all
* Whole value.
* @returns {string}
* Character reference.
*/
function surrogate(pair, index, all) {
return options.format(
(pair.charCodeAt(0) - 0xd800) * 0x400 +
pair.charCodeAt(1) -
0xdc00 +
0x10000,
all.charCodeAt(index + 2),
options
)
}
/**
* Encode a character.
*
* @param {string} character
* Character.
* @param {number} index
* Index of `character` in `all`.
* @param {string} all
* Whole value.
* @returns {string}
* Character reference.
*/
function basic(character, index, all) {
return options.format(
character.charCodeAt(0),
all.charCodeAt(index + 1),
options
)
}
}
/**
* A wrapper function that caches the result of `charactersToExpression` with a WeakMap.
* This can improve performance when tooling calls `charactersToExpression` repeatedly
* with the same subset.
*
* @param {ReadonlyArray<string>} subset
* Characters to match.
* @returns {RegExp}
* Expression.
*/
function charactersToExpressionCached(subset) {
let cached = subsetToRegexCache.get(subset)
if (!cached) {
cached = charactersToExpression(subset)
subsetToRegexCache.set(subset, cached)
}
return cached
}
/**
* Create an expression that matches any of `subset`.
*
* @param {ReadonlyArray<string>} subset
* Characters to match.
* @returns {RegExp}
* Expression.
*/
function charactersToExpression(subset) {
/** @type {Array<string>} */
const groups = []
let index = -1
while (++index < subset.length) {
groups.push(subset[index].replace(regexEscapeRegex, '\\$&'))
}
return new RegExp('(?:' + groups.join('|') + ')', 'g')
}
+31
View File
@@ -0,0 +1,31 @@
/**
* Encode special characters in `value`.
*
* @param {string} value
* Value to encode.
* @param {Options | null | undefined} [options]
* Configuration.
* @returns {string}
* Encoded value.
*/
export function stringifyEntities(value: string, options?: Options | null | undefined): string;
/**
* Encode special characters in `value` as hexadecimal character references.
*
* @param {string} value
* Value to encode.
* @param {LightOptions | null | undefined} [options]
* Configuration.
* @returns {string}
* Encoded value.
*/
export function stringifyEntitiesLight(value: string, options?: LightOptions | null | undefined): string;
/**
* Configuration for `stringifyEntities`.
*
* Includes the fields of `LightOptions`.
*/
export type Options = LightOptions & FormatSmartOptions;
import type { LightOptions } from './core.js';
import type { FormatSmartOptions } from './util/format-smart.js';
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAgBA;;;;;;;;;GASG;AACH,yCAPW,MAAM,YAEN,OAAO,GAAG,IAAI,GAAG,SAAS,GAExB,MAAM,CAKlB;AAED;;;;;;;;;GASG;AACH,8CAPW,MAAM,YAEN,YAAY,GAAG,IAAI,GAAG,SAAS,GAE7B,MAAM,CAKlB;;;;;;sBApCY,YAAY,GAAG,kBAAkB;kCALf,WAAW;wCACL,wBAAwB"}
+43
View File
@@ -0,0 +1,43 @@
/**
* @import {LightOptions} from './core.js'
* @import {FormatSmartOptions} from './util/format-smart.js'
*/
/**
* @typedef {LightOptions & FormatSmartOptions} Options
* Configuration for `stringifyEntities`.
*
* Includes the fields of `LightOptions`.
*/
import {core} from './core.js'
import {formatSmart} from './util/format-smart.js'
import {formatBasic} from './util/format-basic.js'
/**
* Encode special characters in `value`.
*
* @param {string} value
* Value to encode.
* @param {Options | null | undefined} [options]
* Configuration.
* @returns {string}
* Encoded value.
*/
export function stringifyEntities(value, options) {
return core(value, Object.assign({format: formatSmart}, options))
}
/**
* Encode special characters in `value` as hexadecimal character references.
*
* @param {string} value
* Value to encode.
* @param {LightOptions | null | undefined} [options]
* Configuration.
* @returns {string}
* Encoded value.
*/
export function stringifyEntitiesLight(value, options) {
return core(value, Object.assign({format: formatBasic}, options))
}
+10
View File
@@ -0,0 +1,10 @@
/**
* The smallest way to encode a character.
*
* @param {number} code
* Code point.
* @returns {string}
* Hexadecimal reference.
*/
export function formatBasic(code: number): string;
//# sourceMappingURL=format-basic.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"format-basic.d.ts","sourceRoot":"","sources":["format-basic.js"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,kCALW,MAAM,GAEJ,MAAM,CAKlB"}
+11
View File
@@ -0,0 +1,11 @@
/**
* The smallest way to encode a character.
*
* @param {number} code
* Code point.
* @returns {string}
* Hexadecimal reference.
*/
export function formatBasic(code) {
return '&#x' + code.toString(16).toUpperCase() + ';'
}
+46
View File
@@ -0,0 +1,46 @@
/**
* Configurable ways to encode a character yielding pretty or small results.
*
* @param {number} code
* Code point.
* @param {number} next
* Code point of the next character (or `NaN`).
* @param {FormatSmartOptions} options
* Configuration.
* @returns {string}
* Character reference.
*/
export function formatSmart(code: number, next: number, options: FormatSmartOptions): string;
/**
* Configuration for `stringifyEntities` that is not in `LightOptions`.
*/
export type FormatSmartOptions = {
/**
* Create character references which don’t fail in attributes
* (default: `false`);
* only applies when operating dangerously with
* `omitOptionalSemicolons: true`.
*/
attribute?: boolean | null | undefined;
/**
* Whether to omit semicolons when possible (default: `false`);
* this creates what HTML calls “parse errors” but is otherwise still valid
* HTML,
* so don’t use this except when building a minifier;
* omitting semicolons is possible for certain named and numeric references in
* some cases.
*/
omitOptionalSemicolons?: boolean | null | undefined;
/**
* Prefer named character references (`&amp;`) where possible
* (default: `false`).
*/
useNamedReferences?: boolean | null | undefined;
/**
* Prefer the shortest possible reference,
* if that results in less bytes (default: `false`);
* `useNamedReferences` can be omitted when using `useShortestReferences`.
*/
useShortestReferences?: boolean | null | undefined;
};
//# sourceMappingURL=format-smart.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"format-smart.d.ts","sourceRoot":"","sources":["format-smart.js"],"names":[],"mappings":"AA4BA;;;;;;;;;;;GAWG;AACH,kCATW,MAAM,QAEN,MAAM,WAEN,kBAAkB,GAEhB,MAAM,CAsClB;;;;;;;;;;;gBAxEa,OAAO,GAAG,IAAI,GAAG,SAAS;;;;;;;;;6BAK1B,OAAO,GAAG,IAAI,GAAG,SAAS;;;;;yBAO1B,OAAO,GAAG,IAAI,GAAG,SAAS;;;;;;4BAG1B,OAAO,GAAG,IAAI,GAAG,SAAS"}
+76
View File
@@ -0,0 +1,76 @@
/**
* @typedef FormatSmartOptions
* Configuration for `stringifyEntities` that is not in `LightOptions`.
* @property {boolean | null | undefined} [attribute=false]
* Create character references which don’t fail in attributes
* (default: `false`);
* only applies when operating dangerously with
* `omitOptionalSemicolons: true`.
* @property {boolean | null | undefined} [omitOptionalSemicolons=false]
* Whether to omit semicolons when possible (default: `false`);
* this creates what HTML calls “parse errors” but is otherwise still valid
* HTML,
* so don’t use this except when building a minifier;
* omitting semicolons is possible for certain named and numeric references in
* some cases.
* @property {boolean | null | undefined} [useNamedReferences=false]
* Prefer named character references (`&amp;`) where possible
* (default: `false`).
* @property {boolean | null | undefined} [useShortestReferences=false]
* Prefer the shortest possible reference,
* if that results in less bytes (default: `false`);
* `useNamedReferences` can be omitted when using `useShortestReferences`.
*/
import {toHexadecimal} from './to-hexadecimal.js'
import {toDecimal} from './to-decimal.js'
import {toNamed} from './to-named.js'
/**
* Configurable ways to encode a character yielding pretty or small results.
*
* @param {number} code
* Code point.
* @param {number} next
* Code point of the next character (or `NaN`).
* @param {FormatSmartOptions} options
* Configuration.
* @returns {string}
* Character reference.
*/
export function formatSmart(code, next, options) {
const omit = options.omitOptionalSemicolons && next !== 59 /* `;` */
let numeric = toHexadecimal(code, next, omit)
/** @type {string | undefined} */
let named
if (options.useNamedReferences || options.useShortestReferences) {
named = toNamed(code, next, omit, options.attribute)
}
// Use the shortest numeric reference when requested.
// A simple algorithm would use decimal for all code points under 100, as
// those are shorter than hexadecimal:
//
// * `&#99;` vs `&#x63;` (decimal shorter)
// * `&#100;` vs `&#x64;` (equal)
//
// However, because we take `next` into consideration when `omit` is used,
// And it would be possible that decimals are shorter on bigger values as
// well if `next` is hexadecimal but not decimal, we instead compare both.
if (
(options.useShortestReferences || !named) &&
options.useShortestReferences
) {
const decimal = toDecimal(code, next, omit)
if (decimal.length < numeric.length) {
numeric = decimal
}
}
return named &&
(!options.useShortestReferences || named.length < numeric.length)
? named
: numeric
}
+14
View File
@@ -0,0 +1,14 @@
/**
* Configurable ways to encode characters as decimal references.
*
* @param {number} code
* Code point.
* @param {number} next
* Code point of the next character (or `NaN`).
* @param {boolean | null | undefined} omit
* Whether to omit the semicolon when possible.
* @returns {string}
* Decimal reference.
*/
export function toDecimal(code: number, next: number, omit: boolean | null | undefined): string;
//# sourceMappingURL=to-decimal.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"to-decimal.d.ts","sourceRoot":"","sources":["to-decimal.js"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AACH,gCATW,MAAM,QAEN,MAAM,QAEN,OAAO,GAAG,IAAI,GAAG,SAAS,GAExB,MAAM,CAQlB"}
+20
View File
@@ -0,0 +1,20 @@
const decimalRegex = /\d/
/**
* Configurable ways to encode characters as decimal references.
*
* @param {number} code
* Code point.
* @param {number} next
* Code point of the next character (or `NaN`).
* @param {boolean | null | undefined} omit
* Whether to omit the semicolon when possible.
* @returns {string}
* Decimal reference.
*/
export function toDecimal(code, next, omit) {
const value = '&#' + String(code)
return omit && next && !decimalRegex.test(String.fromCharCode(next))
? value
: value + ';'
}
+14
View File
@@ -0,0 +1,14 @@
/**
* Configurable ways to encode characters as hexadecimal references.
*
* @param {number} code
* Code point.
* @param {number} next
* Code point of the next character (or `NaN`).
* @param {boolean | null | undefined} omit
* Whether to omit the semicolon when possible.
* @returns {string}
* Hexadecimal reference.
*/
export function toHexadecimal(code: number, next: number, omit: boolean | null | undefined): string;
//# sourceMappingURL=to-hexadecimal.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"to-hexadecimal.d.ts","sourceRoot":"","sources":["to-hexadecimal.js"],"names":[],"mappings":"AAEA;;;;;;;;;;;GAWG;AACH,oCATW,MAAM,QAEN,MAAM,QAEN,OAAO,GAAG,IAAI,GAAG,SAAS,GAExB,MAAM,CAQlB"}
+20
View File
@@ -0,0 +1,20 @@
const hexadecimalRegex = /[\dA-Fa-f]/
/**
* Configurable ways to encode characters as hexadecimal references.
*
* @param {number} code
* Code point.
* @param {number} next
* Code point of the next character (or `NaN`).
* @param {boolean | null | undefined} omit
* Whether to omit the semicolon when possible.
* @returns {string}
* Hexadecimal reference.
*/
export function toHexadecimal(code, next, omit) {
const value = '&#x' + code.toString(16).toUpperCase()
return omit && next && !hexadecimalRegex.test(String.fromCharCode(next))
? value
: value + ';'
}
+16
View File
@@ -0,0 +1,16 @@
/**
* Configurable ways to encode characters as named references.
*
* @param {number} code
* Code point.
* @param {number} next
* Code point of the next character (or `NaN`).
* @param {boolean | null | undefined} omit
* Whether to omit the semicolon when possible.
* @param {boolean | null | undefined} attribute
* Whether the reference is in an attribute.
* @returns {string}
* Named reference, or empty string if there is no name.
*/
export function toNamed(code: number, next: number, omit: boolean | null | undefined, attribute: boolean | null | undefined): string;
//# sourceMappingURL=to-named.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"to-named.d.ts","sourceRoot":"","sources":["to-named.js"],"names":[],"mappings":"AAwBA;;;;;;;;;;;;;GAaG;AACH,8BAXW,MAAM,QAEN,MAAM,QAEN,OAAO,GAAG,IAAI,GAAG,SAAS,aAE1B,OAAO,GAAG,IAAI,GAAG,SAAS,GAExB,MAAM,CA0BlB"}
+62
View File
@@ -0,0 +1,62 @@
import {characterEntitiesLegacy} from 'character-entities-legacy'
import {characterEntitiesHtml4} from 'character-entities-html4'
import {dangerous} from '../constant/dangerous.js'
const own = {}.hasOwnProperty
/**
* `characterEntitiesHtml4` but inverted.
*
* @type {Record<string, string>}
*/
const characters = {}
/** @type {string} */
let key
for (key in characterEntitiesHtml4) {
if (own.call(characterEntitiesHtml4, key)) {
characters[characterEntitiesHtml4[key]] = key
}
}
const notAlphanumericRegex = /[^\dA-Za-z]/
/**
* Configurable ways to encode characters as named references.
*
* @param {number} code
* Code point.
* @param {number} next
* Code point of the next character (or `NaN`).
* @param {boolean | null | undefined} omit
* Whether to omit the semicolon when possible.
* @param {boolean | null | undefined} attribute
* Whether the reference is in an attribute.
* @returns {string}
* Named reference, or empty string if there is no name.
*/
export function toNamed(code, next, omit, attribute) {
const character = String.fromCharCode(code)
if (own.call(characters, character)) {
const name = characters[character]
const value = '&' + name
if (
omit &&
characterEntitiesLegacy.includes(name) &&
!dangerous.includes(name) &&
(!attribute ||
(next &&
next !== 61 /* `=` */ &&
notAlphanumericRegex.test(String.fromCharCode(next))))
) {
return value
}
return value + ';'
}
return ''
}
+22
View File
@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) Titus Wormer <mailto:tituswormer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+79
View File
@@ -0,0 +1,79 @@
{
"author": "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)",
"bugs": "https://github.com/wooorm/stringify-entities/issues",
"contributors": [
"Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)"
],
"dependencies": {
"character-entities-html4": "^2.0.0",
"character-entities-legacy": "^3.0.0"
},
"description": "Serialize (encode) HTML character references",
"devDependencies": {
"@types/node": "^26.0.0",
"c8": "^12.0.0",
"character-entities": "^2.0.0",
"prettier": "^3.0.0",
"remark-cli": "^12.0.0",
"remark-preset-wooorm": "^11.0.0",
"type-coverage": "^2.0.0",
"typescript": "^6.0.0",
"xo": "^5.0.0"
},
"files": [
"lib/",
"index.d.ts.map",
"index.d.ts",
"index.js"
],
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
},
"keywords": [
"character",
"encode",
"entities",
"entity",
"escape",
"html",
"reference",
"stringify"
],
"license": "MIT",
"main": "index.js",
"name": "stringify-entities",
"prettier": {
"bracketSpacing": false,
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "none",
"useTabs": false
},
"remarkConfig": {
"plugins": [
"preset-wooorm"
]
},
"repository": "wooorm/stringify-entities",
"scripts": {
"build": "tsc --build --clean && tsc --build && type-coverage",
"format": "remark --frail --output --quiet -- . && prettier --log-level warn --write -- . && xo --fix",
"generate": "node --conditions development build.js",
"prepack": "npm run build && npm run format",
"test-api": "node --conditions development test.js",
"test-coverage": "c8 --100 --reporter lcov -- npm run test-api",
"test": "npm run generate && npm run build && npm run format && npm run test-coverage"
},
"sideEffects": false,
"typeCoverage": {
"atLeast": 100,
"detail": true,
"ignoreCatch": true,
"strict": true
},
"types": "index.d.ts",
"type": "module",
"version": "4.0.5"
}
+278
View File
@@ -0,0 +1,278 @@
# stringify-entities
[![Build][badge-build-image]][badge-build-url]
[![Coverage][badge-coverage-image]][badge-coverage-url]
[![Downloads][badge-downloads-image]][badge-downloads-url]
[![Size][badge-size-image]][badge-size-url]
Serialize (encode) HTML character references.
## Contents
* [What is this?](#what-is-this)
* [When should I use this?](#when-should-i-use-this)
* [Install](#install)
* [Use](#use)
* [API](#api)
* [`LightOptions`](#lightoptions)
* [`Options`](#options)
* [`stringifyEntitiesLight(value[, options])`](#stringifyentitieslightvalue-options)
* [`stringifyEntities(value[, options])`](#stringifyentitiesvalue-options)
* [Algorithm](#algorithm)
* [Compatibility](#compatibility)
* [Security](#security)
* [Related](#related)
* [Contribute](#contribute)
* [License](#license)
## What is this?
This is a small and powerful encoder of HTML character references
(often called entities).
This one has either all the options you need for a minifier/formatter,
or a tiny size when using
[`stringifyEntitiesLight`][api-stringify-entities-light].
## When should I use this?
You can use this for spec-compliant encoding of character references.
It’s small and fast enough to do that well.
You can also use this when making an HTML formatter or minifier,
because there are different ways to produce pretty or tiny output.
This package is reliable:
``'`'`` characters are encoded to ensure no scripts run in
Internet Explorer 6 to 8.
Additionally, only named references recognized by HTML 4 are encoded,
meaning the infamous `&apos;`
(which people think is a [virus][telegraph-apos])
won’t show up.
## Install
This package is [ESM only][github-gist-esm].
In Node.js (version 14.14+),
install with [npm][npmjs-install]:
```sh
npm install stringify-entities
```
In browsers with [`esm.sh`][esmsh]:
```html
<script type="module">
import {stringifyEntities} from 'https://esm.sh/stringify-entities@4?bundle'
</script>
```
## Use
```js
import {stringifyEntities} from 'stringify-entities'
stringifyEntities('alpha © bravo ≠ charlie 𝌆 delta')
// => 'alpha &#xA9; bravo &#x2260; charlie &#x1D306; delta'
stringifyEntities('alpha © bravo ≠ charlie 𝌆 delta', {useNamedReferences: true})
// => 'alpha &copy; bravo &ne; charlie &#x1D306; delta'
```
## API
This package exports the identifiers
[`stringifyEntities`][api-stringify-entities] and
[`stringifyEntitiesLight`][api-stringify-entities-light].
There is no default export.
It exports the additional [TypeScript][] types
[`LightOptions`][api-light-options] and
[`Options`][api-options].
### `LightOptions`
Configuration for [`stringifyEntitiesLight`][api-stringify-entities-light]
(TypeScript type).
###### Fields
* `escapeOnly` (`boolean`, default: `false`)
— whether to only escape possibly dangerous characters;
those characters are `"`, `&`, `'`, `<`, `>`, and `` ` ``
* `subset` (`ReadonlyArray<string>`, optional)
— whether to only escape the given subset of characters;
only BMP characters are supported here (so no emoji)
### `Options`
Configuration for [`stringifyEntities`][api-stringify-entities]
(TypeScript type).
Includes the fields of [`LightOptions`][api-light-options].
If you do not care about the following fields,
use [`stringifyEntitiesLight`][api-stringify-entities-light].
###### Fields
* `attribute` (`boolean`, default: `false`)
— create character references which don’t fail in attributes;
only applies when operating dangerously with
`omitOptionalSemicolons: true`
* `omitOptionalSemicolons` (`boolean`, default: `false`)
— whether to omit semicolons when possible;
this creates what HTML calls “parse errors” but is otherwise still valid
HTML,
so don’t use this except when building a minifier;
omitting semicolons is possible for certain named and numeric references in
some cases
* `useNamedReferences` (`boolean`, default: `false`)
— prefer named character references (`&amp;`) where possible
* `useShortestReferences` (`boolean`, default: `false`)
— prefer the shortest possible reference,
if that results in less bytes;
`useNamedReferences` can be omitted when using `useShortestReferences`
### `stringifyEntitiesLight(value[, options])`
Encode special characters in `value` as hexadecimal character references.
###### Parameters
* `value` (`string`, required)
— value to encode
* `options` ([`LightOptions`][api-light-options], optional)
— configuration
###### Returns
Encoded value (`string`).
### `stringifyEntities(value[, options])`
Encode special characters in `value`.
###### Parameters
* `value` (`string`, required)
— value to encode
* `options` ([`Options`][api-options], optional)
— configuration
###### Returns
Encoded value (`string`).
## Algorithm
By default,
all dangerous, non-ASCII, and non-printable ASCII characters are encoded.
A `subset` of characters can be given to encode just those characters.
Alternatively,
pass `escapeOnly` to escape just the dangerous characters
(`"`, `'`, `<`, `>`, `&`, `` ` ``).
By default, hexadecimal character references are used.
Pass `useNamedReferences` to use named character references when possible,
or `useShortestReferences` to use whichever is shortest:
decimal, hexadecimal, or named.
There is also [`stringifyEntitiesLight`][api-stringify-entities-light],
which works just like [`stringifyEntities`][api-stringify-entities]
but without the formatting options:
it’s much smaller but always outputs hexadecimal character references.
## Compatibility
This package is compatible with maintained versions of Node.js.
When we cut a new major release,
we drop support for unmaintained versions of Node.
This means we try to keep the current release line,
`stringify-entities@4`,
compatible with Node.js 14.14.
## Security
By default,
`"`, `&`, `'`, `<`, `>`, and `` ` `` are always encoded,
so the result is safe to use in HTML text and in quoted attribute values.
Spaces and other ASCII characters are not encoded,
so the result is not safe in unquoted attribute values.
When you pass `subset`,
only those characters are encoded.
Leaving out characters such as `<` or `&` can open you up to a
[cross-site scripting (XSS)][wikipedia-xss] attack.
## Related
* [`wooorm/character-entities`][github-character-entities]
— info on character references
* [`wooorm/character-entities-html4`][github-character-entities-html4]
— info on HTML 4 character references
* [`wooorm/character-entities-legacy`][github-character-entities-legacy]
— info on legacy character references
* [`wooorm/character-reference-invalid`][github-character-reference-invalid]
— info on invalid numeric character references
* [`wooorm/parse-entities`][github-parse-entities]
— parse (decode) HTML character references
## Contribute
Yes please!
See [How to Contribute to Open Source][opensource-guide-contribute].
## License
[MIT][file-license] © [Titus Wormer][wooorm]
<!-- Definitions -->
[api-light-options]: #lightoptions
[api-options]: #options
[api-stringify-entities]: #stringifyentitiesvalue-options
[api-stringify-entities-light]: #stringifyentitieslightvalue-options
[badge-build-image]: https://github.com/wooorm/stringify-entities/workflows/main/badge.svg
[badge-build-url]: https://github.com/wooorm/stringify-entities/actions
[badge-coverage-image]: https://img.shields.io/codecov/c/github/wooorm/stringify-entities.svg
[badge-coverage-url]: https://codecov.io/github/wooorm/stringify-entities
[badge-downloads-image]: https://img.shields.io/npm/dm/stringify-entities.svg
[badge-downloads-url]: https://www.npmjs.com/package/stringify-entities
[badge-size-image]: https://img.shields.io/bundlejs/size/stringify-entities
[badge-size-url]: https://bundlejs.com/?q=stringify-entities
[esmsh]: https://esm.sh
[file-license]: license
[github-character-entities]: https://github.com/wooorm/character-entities
[github-character-entities-html4]: https://github.com/wooorm/character-entities-html4
[github-character-entities-legacy]: https://github.com/wooorm/character-entities-legacy
[github-character-reference-invalid]: https://github.com/wooorm/character-reference-invalid
[github-gist-esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c
[github-parse-entities]: https://github.com/wooorm/parse-entities
[npmjs-install]: https://docs.npmjs.com/cli/install
[opensource-guide-contribute]: https://opensource.guide/how-to-contribute/
[telegraph-apos]: https://www.telegraph.co.uk/technology/advice/10516839/Why-do-some-apostrophes-get-replaced-with-andapos.html
[typescript]: https://www.typescriptlang.org
[wikipedia-xss]: https://en.wikipedia.org/wiki/Cross-site_scripting
[wooorm]: https://wooorm.com