content-disposition
Version:
Create and parse Content-Disposition header
485 lines • 16.6 kB
JavaScript
/*!
* content-disposition
* Copyright(c) 2014-2017 Douglas Christopher Wilson
* MIT Licensed
*/
/**
* Null object perf optimization. Faster than `Object.create(null)` and `{ __proto__: null }`.
*/
const NullObject = /* @__PURE__ */ (() => {
const C = function () { };
C.prototype = Object.create(null);
return C;
})();
/**
* Create an attachment Content-Disposition header.
*/
export function create(filename, options) {
const type = options?.type || 'attachment';
const parameters = createParameters(filename, options?.fallback);
return format({ type, parameters }, { extended: false });
}
const SP = 32; // " "
const HTAB = 9; // "\t"
const SEMI = 59; // ";"
const EQ = 61; // "="
const DQUOTE = 34; // '"'
const BSLASH = 92; // "\\"
const ASTERISK = 42; // "*"
const LOWER_CASE = 1;
const OWS = 2;
const SEMI_FLAG = 4;
const TOKEN_FLAG = 8;
const NON_ASCII = 0xff00;
const CASE_FLAGS = LOWER_CASE | NON_ASCII;
/**
* Character flags used to normalize the header while scanning.
* Out-of-range reads intentionally coerce to zero in bitwise expressions.
*/
const CHAR_MAP = new Uint8Array(0x100);
for (let code = 0x41 /* A */; code <= 0x5a /* Z */; code++) {
CHAR_MAP[code] |= LOWER_CASE | TOKEN_FLAG;
}
CHAR_MAP[HTAB] |= OWS;
CHAR_MAP[SP] |= OWS;
CHAR_MAP[SEMI] |= SEMI_FLAG;
for (let code = 0x80 /* non-ASCII */; code <= 0xff; code++) {
CHAR_MAP[code] |= LOWER_CASE;
}
for (const char of "!#$%&'*+-.^_`|~0123456789abcdefghijklmnopqrstuvwxyz") {
CHAR_MAP[char.charCodeAt(0)] |= TOKEN_FLAG;
}
/**
* Validate a non-empty HTTP token.
*/
function isTokenValid(str) {
const len = str.length;
if (len === 0)
return false;
for (let index = 0; index < len; index++) {
if ((CHAR_MAP[str.charCodeAt(index)] & TOKEN_FLAG) === 0)
return false;
}
return true;
}
/**
* Parse Content-Disposition header string.
*/
export function parse(header, options) {
const len = header.length;
const multipart = options?.multipart === true;
const extended = options?.extended !== false;
let index = 0;
while ((CHAR_MAP[header.charCodeAt(index)] & OWS) !== 0) {
index++;
}
const typeStart = index;
let typeFlags = 0;
let whitespace = -1;
while (index < len) {
const code = header.charCodeAt(index);
const flags = CHAR_MAP[code];
if ((flags & SEMI_FLAG) !== 0)
break;
if ((flags & OWS) !== 0) {
if (whitespace === -1)
whitespace = index;
}
else {
whitespace = -1;
}
typeFlags |= (code & NON_ASCII) | flags;
index++;
}
const typeEnd = whitespace === -1 ? index : whitespace;
const typeValue = header.slice(typeStart, typeEnd);
const type = (typeFlags & CASE_FLAGS) === 0 ? typeValue : typeValue.toLowerCase();
const parameters = new NullObject();
const seenKeys = new NullObject();
parameter: while (index < len) {
index++; // Skip over semicolon.
while ((CHAR_MAP[header.charCodeAt(index)] & OWS) !== 0) {
index++;
}
const keyStart = index;
let keyFlags = 0;
let keyWhitespace = -1;
while (index < len) {
const code = header.charCodeAt(index);
const flags = CHAR_MAP[code];
if ((flags & SEMI_FLAG) !== 0)
continue parameter;
if (code === EQ) {
const keyEnd = keyWhitespace === -1 ? index : keyWhitespace;
const keyValue = header.slice(keyStart, keyEnd);
const key = (keyFlags & CASE_FLAGS) === 0 ? keyValue : keyValue.toLowerCase();
index++;
while ((CHAR_MAP[header.charCodeAt(index)] & OWS) !== 0) {
index++;
}
if (index < len && header.charCodeAt(index) === DQUOTE) {
const quotedStart = ++index;
let encoded = false;
while (index < len) {
const code = header.charCodeAt(index);
if (code === DQUOTE) {
if (parameters[key] === undefined && !seenKeys[key]) {
parameters[key] = encoded
? multipart
? decodeMultipartEscapes(header, quotedStart, index)
: unescapeQuotedPairs(header, quotedStart, index)
: header.slice(quotedStart, index);
}
index++;
while (index < len) {
if ((CHAR_MAP[header.charCodeAt(index)] & SEMI_FLAG) !== 0) {
break;
}
index++;
}
seenKeys[key] = true;
continue parameter;
}
if (multipart) {
if (code === /* % */ 37) {
const decodedCode = multipartEscapeCode(header, index, len);
if (decodedCode !== 0) {
encoded = true;
index += 3;
continue;
}
}
}
else if (code === BSLASH && index + 1 < len) {
encoded = true;
index += 2;
continue;
}
index++;
}
seenKeys[key] = true;
continue parameter;
}
const valueStart = index;
const delimiter = header.indexOf(';', index);
index = delimiter === -1 ? len : delimiter;
if (seenKeys[key])
continue parameter;
seenKeys[key] = true;
let valueEnd = index;
while (valueEnd > valueStart &&
(CHAR_MAP[header.charCodeAt(valueEnd - 1)] & OWS) !== 0) {
valueEnd--;
}
const value = header.slice(valueStart, valueEnd);
if (extended && key.charCodeAt(key.length - 1) === ASTERISK) {
const normalizedKey = key.slice(0, -1);
const decoded = decodeExtended(value);
if (decoded !== undefined) {
parameters[normalizedKey] = decoded;
continue parameter;
}
}
if (parameters[key] === undefined)
parameters[key] = value;
continue parameter;
}
if ((flags & OWS) !== 0) {
if (keyWhitespace === -1)
keyWhitespace = index;
}
else {
keyWhitespace = -1;
}
keyFlags |= (code & NON_ASCII) | flags;
index++;
}
}
return { type, parameters };
}
/**
* Return the decoded character code for a multipart escape, or zero if invalid.
*/
function multipartEscapeCode(str, index, len) {
if (index + 2 >= len)
return 0;
const code2 = str.charCodeAt(index + 1);
const code3 = str.charCodeAt(index + 2);
if (code2 === 50 /* "2" */ && code3 === 50 /* "2" */)
return DQUOTE;
if (code2 !== 48 /* "0" */)
return 0;
if (code3 === 100 /* "d" */ || code3 === 68 /* "D" */)
return 13;
if (code3 === 97 /* "a" */ || code3 === 65 /* "A" */)
return 10;
return 0;
}
/**
* Remove backslashes from quoted pairs in a known-terminated quoted string.
*/
function unescapeQuotedPairs(str, start, end) {
let result = '';
for (let index = start; index < end; index++) {
if (str.charCodeAt(index) === BSLASH) {
result += str.slice(start, index);
start = ++index;
}
}
return result + str.slice(start, end);
}
/**
* Decode the escapes browsers apply to multipart quoted parameter values.
*/
function decodeMultipartEscapes(str, start, end) {
let result = '';
for (let index = start; index < end; index++) {
if (str.charCodeAt(index) !== /* % */ 37)
continue;
const decodedCode = multipartEscapeCode(str, index, end);
if (decodedCode === 0)
continue;
result += str.slice(start, index);
result += String.fromCharCode(decodedCode);
index += 2;
start = index + 1;
}
return result + str.slice(start, end);
}
/**
* RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%")
*/
const ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g; // eslint-disable-line no-control-regex
/**
* RegExp to match non-US-ASCII characters.
*/
const NON_ASCII_REGEXP = /[^\x20-\x7e]/g;
/**
* Match chars that can't be used in the filename for compatibility.
*/
const INVALID_FILENAME_REGEXP = /%[0-9A-Fa-f]{2}/;
/**
* RegExp for various RFC 2616 grammar
*
* parameter = token "=" ( token | quoted-string )
* token = 1*<any CHAR except CTLs or separators>
* separators = "(" | ")" | "<" | ">" | "@"
* | "," | ";" | ":" | "\" | <">
* | "/" | "[" | "]" | "?" | "="
* | "{" | "}" | SP | HT
* quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
* qdtext = <any TEXT except <">>
* quoted-pair = "\" CHAR
* CHAR = <any US-ASCII character (octets 0 - 127)>
* TEXT = <any OCTET except CTLs, but including LWS>
* LWS = [CRLF] 1*( SP | HT )
* CRLF = CR LF
* CR = <US-ASCII CR, carriage return (13)>
* LF = <US-ASCII LF, linefeed (10)>
* SP = <US-ASCII SP, space (32)>
* HT = <US-ASCII HT, horizontal-tab (9)>
* CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
* OCTET = <any 8-bit sequence of data>
*/
const ASCII_TEXT_REGEXP = /^[\x20-\x7e]*$/;
/**
* Create parameters object from filename and fallback.
*/
function createParameters(filename, fallback = true) {
if (filename === undefined)
return;
if (typeof fallback === 'string') {
if (!ASCII_TEXT_REGEXP.test(fallback)) {
throw new TypeError('Fallback must be valid US-ASCII: ' + fallback);
}
if (fallback === filename)
return { filename };
return { filename: fallback, 'filename*': encodeExtended(filename) };
}
// Use `filename` when possible, otherwise use `filename*`.
if (ASCII_TEXT_REGEXP.test(filename) &&
!INVALID_FILENAME_REGEXP.test(filename)) {
return { filename };
}
if (fallback === false) {
return { 'filename*': encodeExtended(filename) };
}
return {
filename: getAscii(filename),
'filename*': encodeExtended(filename),
};
}
/**
* Decode a RFC 8187 field value (gracefully).
*/
export function decodeExtended(str) {
const charsetEnd = str.indexOf("'");
if (charsetEnd <= 0) {
return undefined;
}
const languageEnd = str.indexOf("'", charsetEnd + 1);
if (languageEnd === -1) {
return undefined;
}
const charset = str.slice(0, charsetEnd).toLowerCase();
const encoded = str.slice(languageEnd + 1);
switch (charset) {
case 'iso-8859-1': {
return decodeHexEscapes(encoded);
}
case 'utf-8':
case 'utf8': {
return tryDecodeURIComponent(encoded);
}
}
return undefined;
}
/**
* Decode URI component but return `undefined` on error.
*/
function tryDecodeURIComponent(str) {
try {
return decodeURIComponent(str);
}
catch {
return undefined;
}
}
/**
* Format object to Content-Disposition header.
*/
export function format(obj, options) {
const { type, parameters } = obj;
const multipart = options?.multipart === true;
const extended = options?.extended !== false;
if (!type || !isTokenValid(type)) {
throw new TypeError('Invalid type: ' + type);
}
let result = type;
if (parameters) {
for (const param of Object.keys(parameters)) {
const value = parameters[param];
if (!isTokenValid(param)) {
throw new TypeError('Invalid parameter name: ' + param);
}
if (multipart) {
result += '; ' + param + '=' + qmultipart(value);
continue;
}
const formatted = parameterValue(value);
if (formatted !== undefined) {
result += '; ' + param + '=' + formatted;
continue;
}
if (!extended) {
throw new TypeError('Invalid parameter value: ' + value);
}
// Reject parameter names that indicate they are already extended.
if (param.charCodeAt(param.length - 1) === ASTERISK) {
throw new TypeError('Invalid extended parameter value: ' + value);
}
result += '; ' + param + '*=' + encodeExtended(value);
}
}
return result;
}
/**
* Get US-ASCII version of string.
*/
function getAscii(val) {
// simple Unicode -> US-ASCII transformation
return val.replace(NON_ASCII_REGEXP, '?');
}
/**
* Percent encode a single character.
*/
function pencode(char) {
return '%' + char.charCodeAt(0).toString(16).toUpperCase();
}
/**
* Serialize a token or quoted value, or return undefined if encoding is needed.
*/
function parameterValue(str) {
const len = str.length;
if (len === 0)
return '""';
let index = 0;
while (index < len && (CHAR_MAP[str.charCodeAt(index)] & TOKEN_FLAG) !== 0) {
index++;
}
if (index === len)
return str;
let result = '"';
let start = 0;
for (; index < len; index++) {
const code = str.charCodeAt(index);
if (code < SP || code === 127 || code > 255)
return undefined;
if (code === DQUOTE || code === BSLASH) {
result += str.slice(start, index) + '\\';
start = index;
}
}
return result + str.slice(start) + '"';
}
/**
* Quote a string for multipart/form-data.
*
* @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#multipart-form-data
*/
function qmultipart(str) {
// Skip the character loop when no escaping is needed.
if (!/[\n\r"]/.test(str))
return '"' + str + '"';
let result = '"';
let start = 0;
for (let index = 0; index < str.length; index++) {
const code = str.charCodeAt(index);
if (code === DQUOTE || code === 10 || code === 13) {
result += str.slice(start, index);
result += code === DQUOTE ? '%22' : code === 10 ? '%0A' : '%0D';
start = index + 1;
}
}
return result + str.slice(start) + '"';
}
/**
* Encode a Unicode string for HTTP (RFC 8187).
*/
export function encodeExtended(str) {
const encoded = encodeURIComponent(str).replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode);
return "UTF-8''" + encoded;
}
/**
* Hex digit values plus one; zero denotes an invalid digit.
*/
const HEX_VALUES = new Uint8Array(128);
for (let code = 48; code <= 57; code++)
HEX_VALUES[code] = code - 47;
for (let code = 65; code <= 70; code++)
HEX_VALUES[code] = code - 54;
for (let code = 97; code <= 102; code++)
HEX_VALUES[code] = code - 86;
/**
* Decode hex escapes in a string (e.g., %20 -> space).
*/
function decodeHexEscapes(str) {
let index = str.indexOf('%');
if (index === -1)
return str;
let start = 0;
let result = '';
do {
const high = HEX_VALUES[str.charCodeAt(index + 1)];
const low = HEX_VALUES[str.charCodeAt(index + 2)];
if (!high || !low)
return undefined;
result +=
str.slice(start, index) +
String.fromCharCode(((high - 1) << 4) | (low - 1));
start = index + 3;
index = str.indexOf('%', start);
} while (index !== -1);
return result + str.slice(start);
}
//# sourceMappingURL=index.js.map