123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- 'use strict'
- const {
- unassigned_code_points,
- commonly_mapped_to_nothing,
- non_ASCII_space_characters,
- prohibited_characters,
- bidirectional_r_al,
- bidirectional_l,
- } = require('./lib/memory-code-points')
- module.exports = saslprep
- const mapping2space = non_ASCII_space_characters
- const mapping2nothing = commonly_mapped_to_nothing
- const getCodePoint = character => character.codePointAt(0)
- const first = x => x[0]
- const last = x => x[x.length - 1]
- function saslprep(input, opts = {}) {
- if (typeof input !== 'string') {
- throw new TypeError('Expected string.')
- }
- if (input.length === 0) {
- return ''
- }
-
- const mapped_input = input
- .split('')
- .map(getCodePoint)
-
- .map(character => (mapping2space.get(character) ? 0x20 : character))
-
- .filter(character => !mapping2nothing.get(character))
-
- const normalized_input = String.fromCodePoint(...mapped_input).normalize('NFKC')
- const normalized_map = normalized_input.split('').map(getCodePoint)
-
- const hasProhibited = normalized_map.some(character =>
- prohibited_characters.get(character)
- )
- if (hasProhibited) {
- throw new Error(
- 'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3'
- )
- }
-
- if (opts.allowUnassigned !== true) {
- const hasUnassigned = normalized_map.some(character =>
- unassigned_code_points.get(character)
- )
- if (hasUnassigned) {
- throw new Error(
- 'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5'
- )
- }
- }
-
- const hasBidiRAL = normalized_map
- .some((character) => bidirectional_r_al.get(character))
- const hasBidiL = normalized_map
- .some((character) => bidirectional_l.get(character))
-
-
- if (hasBidiRAL && hasBidiL) {
- throw new Error(
- 'String must not contain RandALCat and LCat at the same time,' +
- ' see https://tools.ietf.org/html/rfc3454#section-6'
- )
- }
-
- const isFirstBidiRAL = bidirectional_r_al.get(getCodePoint(first(normalized_input)))
- const isLastBidiRAL = bidirectional_r_al.get(getCodePoint(last(normalized_input)))
- if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) {
- throw new Error(
- 'Bidirectional RandALCat character must be the first and the last' +
- ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6'
- )
- }
- return normalized_input
- }
|