@d1g1tal/media-type 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Class representing the parameters for a media type record.
3
+ * This class has the equivalent surface API to a JavaScript {@link Map}.
4
+ *
5
+ * However, {@link MediaTypeParameters} methods will always interpret their arguments
6
+ * as appropriate for media types, so parameter names will be lowercased,
7
+ * and attempting to set invalid characters will throw an {@link Error}.
8
+ *
9
+ * @example charset=utf-8
10
+ * @module MediaTypeParameters
11
+ */
12
+ export default class MediaTypeParameters {
13
+ /**
14
+ * Create a new MediaTypeParameters instance.
15
+ *
16
+ * @param {Map.<string, string>} map The map of parameters for a media type.
17
+ */
18
+ constructor(map: Map<string, string>);
19
+ _map: Map<string, string>;
20
+ /**
21
+ * Gets the number of media type parameters.
22
+ *
23
+ * @returns {number} The number of media type parameters
24
+ */
25
+ get size(): number;
26
+ /**
27
+ * Gets the media type parameter value for the supplied name.
28
+ *
29
+ * @param {string} name The name of the media type parameter to retrieve.
30
+ * @returns {string} The media type parameter value.
31
+ */
32
+ get(name: string): string;
33
+ /**
34
+ * Indicates whether the media type parameter with the specified name exists or not.
35
+ *
36
+ * @param {string} name The name of the media type parameter to check.
37
+ * @returns {boolean} true if the media type parameter exists, false otherwise.
38
+ */
39
+ has(name: string): boolean;
40
+ /**
41
+ * Adds a new media type parameter using the specified name and value to the MediaTypeParameters.
42
+ * If an parameter with the same name already exists, the parameter will be updated.
43
+ *
44
+ * @param {string} name The name of the media type parameter to set.
45
+ * @param {string} value The media type parameter value.
46
+ * @returns {MediaTypeParameters} This instance.
47
+ */
48
+ set(name: string, value: string): MediaTypeParameters;
49
+ /**
50
+ * Clears all the media type parameters.
51
+ */
52
+ clear(): void;
53
+ /**
54
+ * Removes the media type parameter using the specified name.
55
+ *
56
+ * @param {string} name The name of the media type parameter to delete.
57
+ * @returns {boolean} true if the parameter existed and has been removed, or false if the parameter does not exist.
58
+ */
59
+ delete(name: string): boolean;
60
+ /**
61
+ * Executes a provided function once per each name/value pair in the MediaTypeParameters, in insertion order.
62
+ *
63
+ * @param {function(string, string): void} callback The function called on each iteration.
64
+ * @param {*} [thisArg] Optional object when binding 'this' to the callback.
65
+ */
66
+ forEach(callback: (arg0: string, arg1: string) => void, thisArg?: any): void;
67
+ /**
68
+ * Returns an iterable of parameter names.
69
+ *
70
+ * @returns {IterableIterator<string>} The {@link IterableIterator} of media type parameter names.
71
+ */
72
+ keys(): IterableIterator<string>;
73
+ /**
74
+ * Returns an iterable of parameter values.
75
+ *
76
+ * @returns {IterableIterator<string>} The {@link IterableIterator} of media type parameter values.
77
+ */
78
+ values(): IterableIterator<string>;
79
+ /**
80
+ * Returns an iterable of name, value pairs for every parameter entry in the media type parameters.
81
+ *
82
+ * @returns {IterableIterator<Array<Array<string>>>} The media type parameter entries.
83
+ */
84
+ entries(): IterableIterator<Array<Array<string>>>;
85
+ /**
86
+ * A method that returns the default iterator for the {@link MediaTypeParameters}. Called by the semantics of the for-of statement.
87
+ *
88
+ * @returns {Iterator<string, string, undefined>} The {@link Symbol.iterator} for the media type parameters.
89
+ */
90
+ [Symbol.iterator](): Iterator<string, string, undefined>;
91
+ }
@@ -0,0 +1,141 @@
1
+ import { asciiLowercase, solelyContainsHTTPQuotedStringTokenCodePoints, solelyContainsHTTPTokenCodePoints } from './utils.js';
2
+
3
+ /**
4
+ * Class representing the parameters for a media type record.
5
+ * This class has the equivalent surface API to a JavaScript {@link Map}.
6
+ *
7
+ * However, {@link MediaTypeParameters} methods will always interpret their arguments
8
+ * as appropriate for media types, so parameter names will be lowercased,
9
+ * and attempting to set invalid characters will throw an {@link Error}.
10
+ *
11
+ * @example charset=utf-8
12
+ * @module MediaTypeParameters
13
+ */
14
+ export default class MediaTypeParameters {
15
+ /**
16
+ * Create a new MediaTypeParameters instance.
17
+ *
18
+ * @param {Map.<string, string>} map The map of parameters for a media type.
19
+ */
20
+ constructor(map) {
21
+ this._map = map;
22
+ }
23
+
24
+ /**
25
+ * Gets the number of media type parameters.
26
+ *
27
+ * @returns {number} The number of media type parameters
28
+ */
29
+ get size() {
30
+ return this._map.size;
31
+ }
32
+
33
+ /**
34
+ * Gets the media type parameter value for the supplied name.
35
+ *
36
+ * @param {string} name The name of the media type parameter to retrieve.
37
+ * @returns {string} The media type parameter value.
38
+ */
39
+ get(name) {
40
+ return this._map.get(asciiLowercase(String(name)));
41
+ }
42
+
43
+ /**
44
+ * Indicates whether the media type parameter with the specified name exists or not.
45
+ *
46
+ * @param {string} name The name of the media type parameter to check.
47
+ * @returns {boolean} true if the media type parameter exists, false otherwise.
48
+ */
49
+ has(name) {
50
+ return this._map.has(asciiLowercase(String(name)));
51
+ }
52
+
53
+ /**
54
+ * Adds a new media type parameter using the specified name and value to the MediaTypeParameters.
55
+ * If an parameter with the same name already exists, the parameter will be updated.
56
+ *
57
+ * @param {string} name The name of the media type parameter to set.
58
+ * @param {string} value The media type parameter value.
59
+ * @returns {MediaTypeParameters} This instance.
60
+ */
61
+ set(name, value) {
62
+ name = asciiLowercase(String(name));
63
+ value = String(value);
64
+
65
+ if (!solelyContainsHTTPTokenCodePoints(name)) {
66
+ throw new Error(`Invalid media type parameter name "${name}": only HTTP token code points are valid.`);
67
+ }
68
+
69
+ if (!solelyContainsHTTPQuotedStringTokenCodePoints(value)) {
70
+ throw new Error(`Invalid media type parameter value "${value}": only HTTP quoted-string token code points are valid.`);
71
+ }
72
+
73
+ this._map.set(name, value);
74
+
75
+ return this;
76
+ }
77
+
78
+ /**
79
+ * Clears all the media type parameters.
80
+ */
81
+ clear() {
82
+ this._map.clear();
83
+ }
84
+
85
+ /**
86
+ * Removes the media type parameter using the specified name.
87
+ *
88
+ * @param {string} name The name of the media type parameter to delete.
89
+ * @returns {boolean} true if the parameter existed and has been removed, or false if the parameter does not exist.
90
+ */
91
+ delete(name) {
92
+ name = asciiLowercase(String(name));
93
+ return this._map.delete(name);
94
+ }
95
+
96
+ /**
97
+ * Executes a provided function once per each name/value pair in the MediaTypeParameters, in insertion order.
98
+ *
99
+ * @param {function(string, string): void} callback The function called on each iteration.
100
+ * @param {*} [thisArg] Optional object when binding 'this' to the callback.
101
+ */
102
+ forEach(callback, thisArg) {
103
+ this._map.forEach(callback, thisArg);
104
+ }
105
+
106
+ /**
107
+ * Returns an iterable of parameter names.
108
+ *
109
+ * @returns {IterableIterator<string>} The {@link IterableIterator} of media type parameter names.
110
+ */
111
+ keys() {
112
+ return this._map.keys();
113
+ }
114
+
115
+ /**
116
+ * Returns an iterable of parameter values.
117
+ *
118
+ * @returns {IterableIterator<string>} The {@link IterableIterator} of media type parameter values.
119
+ */
120
+ values() {
121
+ return this._map.values();
122
+ }
123
+
124
+ /**
125
+ * Returns an iterable of name, value pairs for every parameter entry in the media type parameters.
126
+ *
127
+ * @returns {IterableIterator<Array<Array<string>>>} The media type parameter entries.
128
+ */
129
+ entries() {
130
+ return this._map.entries();
131
+ }
132
+
133
+ /**
134
+ * A method that returns the default iterator for the {@link MediaTypeParameters}. Called by the semantics of the for-of statement.
135
+ *
136
+ * @returns {Iterator<string, string, undefined>} The {@link Symbol.iterator} for the media type parameters.
137
+ */
138
+ [Symbol.iterator]() {
139
+ return this._map[Symbol.iterator]();
140
+ }
141
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Class used to parse media types.
3
+ *
4
+ * @see https://mimesniff.spec.whatwg.org/#understanding-mime-types
5
+ * @module MediaType
6
+ */
7
+ export default class MediaType {
8
+ /**
9
+ * Static factor method for parsing a media type.
10
+ *
11
+ * @param {string} string The media type to parse
12
+ * @returns {MediaType} The parsed {@link MediaType} object
13
+ */
14
+ static parse(string: string): MediaType;
15
+ /**
16
+ * Create a new MediaType instance from a string representation.
17
+ *
18
+ * @param {string} string The media type to parse
19
+ */
20
+ constructor(string: string);
21
+ _type: string;
22
+ _subtype: string;
23
+ _parameters: MediaTypeParameters;
24
+ /**
25
+ * Gets the media type essence (type/subtype).
26
+ *
27
+ * @returns {string} The media type without any parameters
28
+ */
29
+ get essence(): string;
30
+ /**
31
+ * Sets the type.
32
+ */
33
+ set type(arg: string);
34
+ /**
35
+ * Gets the type.
36
+ *
37
+ * @returns {string} The type.
38
+ */
39
+ get type(): string;
40
+ /**
41
+ * Sets the subtype.
42
+ */
43
+ set subtype(arg: string);
44
+ /**
45
+ * Gets the subtype.
46
+ *
47
+ * @returns {string} The subtype.
48
+ */
49
+ get subtype(): string;
50
+ /**
51
+ * Gets the parameters.
52
+ *
53
+ * @returns {MediaTypeParameters} The media type parameters.
54
+ */
55
+ get parameters(): MediaTypeParameters;
56
+ /**
57
+ * Gets the serialized version of the media type.
58
+ *
59
+ * @returns {string} The serialized media type.
60
+ */
61
+ toString(): string;
62
+ /**
63
+ * Determines if this instance is a JavaScript media type.
64
+ *
65
+ * @param {Object} [options] Optional options.
66
+ * @param {boolean} [options.prohibitParameters=false] The option to prohibit parameters when checking if the media type is JavaScript.
67
+ * @returns {boolean} true if this instance represents a JavaScript media type, false otherwise.
68
+ */
69
+ isJavaScript({ prohibitParameters }?: {
70
+ prohibitParameters?: boolean;
71
+ }): boolean;
72
+ /**
73
+ * Determines if this instance is an XML media type.
74
+ *
75
+ * @returns {boolean} true if this instance represents an XML media type, false otherwise.
76
+ */
77
+ isXML(): boolean;
78
+ /**
79
+ * Determines if this instance is an HTML media type.
80
+ *
81
+ * @returns {boolean} true if this instance represents an HTML media type, false otherwise.
82
+ */
83
+ isHTML(): boolean;
84
+ /**
85
+ * Gets the name of the class.
86
+ *
87
+ * @returns {string} The class name
88
+ */
89
+ get [Symbol.toStringTag](): string;
90
+ }
91
+ import MediaTypeParameters from "./media-type-parameters.js";
@@ -0,0 +1,188 @@
1
+ import MediaTypeParameters from './media-type-parameters.js';
2
+ import parse from './parser.js';
3
+ import serialize from './serializer.js';
4
+ import { asciiLowercase, solelyContainsHTTPTokenCodePoints } from './utils.js';
5
+
6
+ /**
7
+ * Class used to parse media types.
8
+ *
9
+ * @see https://mimesniff.spec.whatwg.org/#understanding-mime-types
10
+ * @module MediaType
11
+ */
12
+ export default class MediaType {
13
+ /**
14
+ * Create a new MediaType instance from a string representation.
15
+ *
16
+ * @param {string} string The media type to parse
17
+ */
18
+ constructor(string) {
19
+ string = String(string);
20
+ const result = parse(string);
21
+ if (result === null) {
22
+ throw new Error(`Could not parse media type string '${string}'`);
23
+ }
24
+
25
+ this._type = result.type;
26
+ this._subtype = result.subtype;
27
+ this._parameters = new MediaTypeParameters(result.parameters);
28
+ }
29
+
30
+ /**
31
+ * Static factor method for parsing a media type.
32
+ *
33
+ * @param {string} string The media type to parse
34
+ * @returns {MediaType} The parsed {@link MediaType} object
35
+ */
36
+ static parse(string) {
37
+ try {
38
+ return new this(string);
39
+ } catch (e) {
40
+ return null;
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Gets the media type essence (type/subtype).
46
+ *
47
+ * @returns {string} The media type without any parameters
48
+ */
49
+ get essence() {
50
+ return `${this.type}/${this.subtype}`;
51
+ }
52
+
53
+ /**
54
+ * Gets the type.
55
+ *
56
+ * @returns {string} The type.
57
+ */
58
+ get type() {
59
+ return this._type;
60
+ }
61
+
62
+ /**
63
+ * Sets the type.
64
+ */
65
+ set type(value) {
66
+ value = asciiLowercase(String(value));
67
+
68
+ if (value.length === 0) {
69
+ throw new Error('Invalid type: must be a non-empty string');
70
+ }
71
+ if (!solelyContainsHTTPTokenCodePoints(value)) {
72
+ throw new Error(`Invalid type ${value}: must contain only HTTP token code points`);
73
+ }
74
+
75
+ this._type = value;
76
+ }
77
+
78
+ /**
79
+ * Gets the subtype.
80
+ *
81
+ * @returns {string} The subtype.
82
+ */
83
+ get subtype() {
84
+ return this._subtype;
85
+ }
86
+
87
+ /**
88
+ * Sets the subtype.
89
+ */
90
+ set subtype(value) {
91
+ value = asciiLowercase(String(value));
92
+
93
+ if (value.length === 0) {
94
+ throw new Error('Invalid subtype: must be a non-empty string');
95
+ }
96
+ if (!solelyContainsHTTPTokenCodePoints(value)) {
97
+ throw new Error(`Invalid subtype ${value}: must contain only HTTP token code points`);
98
+ }
99
+
100
+ this._subtype = value;
101
+ }
102
+
103
+ /**
104
+ * Gets the parameters.
105
+ *
106
+ * @returns {MediaTypeParameters} The media type parameters.
107
+ */
108
+ get parameters() {
109
+ return this._parameters;
110
+ }
111
+
112
+ /**
113
+ * Gets the serialized version of the media type.
114
+ *
115
+ * @returns {string} The serialized media type.
116
+ */
117
+ toString() {
118
+ // The serialize function works on both 'media type records' (i.e. the results of parse) and on this class, since
119
+ // this class's interface is identical.
120
+ return serialize(this);
121
+ }
122
+
123
+ /**
124
+ * Determines if this instance is a JavaScript media type.
125
+ *
126
+ * @param {Object} [options] Optional options.
127
+ * @param {boolean} [options.prohibitParameters=false] The option to prohibit parameters when checking if the media type is JavaScript.
128
+ * @returns {boolean} true if this instance represents a JavaScript media type, false otherwise.
129
+ */
130
+ isJavaScript({prohibitParameters = false} = {}) {
131
+ switch (this._type) {
132
+ case 'text': {
133
+ switch (this._subtype) {
134
+ case 'ecmascript':
135
+ case 'javascript':
136
+ case 'javascript1.0':
137
+ case 'javascript1.1':
138
+ case 'javascript1.2':
139
+ case 'javascript1.3':
140
+ case 'javascript1.4':
141
+ case 'javascript1.5':
142
+ case 'jscript':
143
+ case 'livescript':
144
+ case 'x-ecmascript':
145
+ case 'x-javascript': return !prohibitParameters || this._parameters.size === 0;
146
+ default: return false;
147
+ }
148
+ }
149
+ case 'application': {
150
+ switch (this._subtype) {
151
+ case 'ecmascript':
152
+ case 'javascript':
153
+ case 'x-ecmascript':
154
+ case 'x-javascript': return !prohibitParameters || this._parameters.size === 0;
155
+ default: return false;
156
+ }
157
+ }
158
+ default: return false;
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Determines if this instance is an XML media type.
164
+ *
165
+ * @returns {boolean} true if this instance represents an XML media type, false otherwise.
166
+ */
167
+ isXML() {
168
+ return (this._subtype === 'xml' && (this._type === 'text' || this._type === 'application')) || this._subtype.endsWith('+xml');
169
+ }
170
+
171
+ /**
172
+ * Determines if this instance is an HTML media type.
173
+ *
174
+ * @returns {boolean} true if this instance represents an HTML media type, false otherwise.
175
+ */
176
+ isHTML() {
177
+ return this._subtype === 'html' && this._type === 'text';
178
+ }
179
+
180
+ /**
181
+ * Gets the name of the class.
182
+ *
183
+ * @returns {string} The class name
184
+ */
185
+ get [Symbol.toStringTag]() {
186
+ return 'MediaType';
187
+ }
188
+ }
@@ -0,0 +1,13 @@
1
+ export default parse;
2
+ /**
3
+ * Function to parse a media type.
4
+ *
5
+ * @module parser
6
+ * @param {string} input The media type to parse
7
+ * @returns {{ type: string, subtype: string, parameters: Map<string, string> }} An object populated with the parsed media type properties and any parameters.
8
+ */
9
+ declare function parse(input: string): {
10
+ type: string;
11
+ subtype: string;
12
+ parameters: Map<string, string>;
13
+ };
package/src/parser.js ADDED
@@ -0,0 +1,109 @@
1
+ import {
2
+ asciiLowercase,
3
+ collectAnHTTPQuotedString, isHTTPWhitespaceChar, removeLeadingAndTrailingHTTPWhitespace,
4
+ removeTrailingHTTPWhitespace, solelyContainsHTTPQuotedStringTokenCodePoints, solelyContainsHTTPTokenCodePoints
5
+ } from './utils.js';
6
+
7
+ /**
8
+ * Function to parse a media type.
9
+ *
10
+ * @module parser
11
+ * @param {string} input The media type to parse
12
+ * @returns {{ type: string, subtype: string, parameters: Map<string, string> }} An object populated with the parsed media type properties and any parameters.
13
+ */
14
+ const parse = (input) => {
15
+ input = removeLeadingAndTrailingHTTPWhitespace(input);
16
+
17
+ let position = 0;
18
+ let type = '';
19
+ while (position < input.length && input[position] !== '/') {
20
+ type += input[position];
21
+ ++position;
22
+ }
23
+
24
+ if (type.length === 0 || !solelyContainsHTTPTokenCodePoints(type)) {
25
+ return null;
26
+ }
27
+
28
+ if (position >= input.length) {
29
+ return null;
30
+ }
31
+
32
+ // Skips past "/"
33
+ ++position;
34
+
35
+ let subtype = '';
36
+ while (position < input.length && input[position] !== ';') {
37
+ subtype += input[position];
38
+ ++position;
39
+ }
40
+
41
+ subtype = removeTrailingHTTPWhitespace(subtype);
42
+
43
+ if (subtype.length === 0 || !solelyContainsHTTPTokenCodePoints(subtype)) {
44
+ return null;
45
+ }
46
+
47
+ const mediaType = {
48
+ type: asciiLowercase(type),
49
+ subtype: asciiLowercase(subtype),
50
+ parameters: new Map()
51
+ };
52
+
53
+ while (position < input.length) {
54
+ // Skip past ";"
55
+ ++position;
56
+
57
+ while (isHTTPWhitespaceChar(input[position])) {
58
+ ++position;
59
+ }
60
+
61
+ let parameterName = '';
62
+ while (position < input.length && input[position] !== ';' && input[position] !== '=') {
63
+ parameterName += input[position];
64
+ ++position;
65
+ }
66
+ parameterName = asciiLowercase(parameterName);
67
+
68
+ if (position < input.length) {
69
+ if (input[position] === ';') {
70
+ continue;
71
+ }
72
+
73
+ // Skip past "="
74
+ ++position;
75
+ }
76
+
77
+ let parameterValue = null;
78
+ if (input[position] === '"') {
79
+ [parameterValue, position] = collectAnHTTPQuotedString(input, position);
80
+
81
+ while (position < input.length && input[position] !== ';') {
82
+ ++position;
83
+ }
84
+ } else {
85
+ parameterValue = '';
86
+ while (position < input.length && input[position] !== ';') {
87
+ parameterValue += input[position];
88
+ ++position;
89
+ }
90
+
91
+ parameterValue = removeTrailingHTTPWhitespace(parameterValue);
92
+
93
+ if (parameterValue === '') {
94
+ continue;
95
+ }
96
+ }
97
+
98
+ if (parameterName.length > 0 &&
99
+ solelyContainsHTTPTokenCodePoints(parameterName) &&
100
+ solelyContainsHTTPQuotedStringTokenCodePoints(parameterValue) &&
101
+ !mediaType.parameters.has(parameterName)) {
102
+ mediaType.parameters.set(parameterName, parameterValue);
103
+ }
104
+ }
105
+
106
+ return mediaType;
107
+ };
108
+
109
+ export default parse;
@@ -0,0 +1,11 @@
1
+ export default serialize;
2
+ export type MediaType = import('./media-type.js').default;
3
+ /** @typedef { import('./media-type.js').default } MediaType */
4
+ /**
5
+ * A function that serializes the provided {@link mediaType} to a string.
6
+ *
7
+ * @module serializer
8
+ * @param {MediaType} mediaType The media type to serialize.
9
+ * @returns {string} The serialized media type.
10
+ */
11
+ declare function serialize(mediaType: MediaType): string;
@@ -0,0 +1,35 @@
1
+ import { solelyContainsHTTPTokenCodePoints } from './utils.js';
2
+ // eslint-disable-next-line jsdoc/valid-types
3
+ /** @typedef { import('./media-type.js').default } MediaType */
4
+
5
+ /**
6
+ * A function that serializes the provided {@link mediaType} to a string.
7
+ *
8
+ * @module serializer
9
+ * @param {MediaType} mediaType The media type to serialize.
10
+ * @returns {string} The serialized media type.
11
+ */
12
+ const serialize = (mediaType) => {
13
+ let serialization = `${mediaType.type}/${mediaType.subtype}`;
14
+
15
+ if (mediaType.parameters.size === 0) {
16
+ return serialization;
17
+ }
18
+
19
+ for (let [name, value] of mediaType.parameters) {
20
+ serialization += ';';
21
+ serialization += name;
22
+ serialization += '=';
23
+
24
+ if (!solelyContainsHTTPTokenCodePoints(value) || value.length === 0) {
25
+ value = value.replace(/(["\\])/ug, '\\$1');
26
+ value = `"${value}"`;
27
+ }
28
+
29
+ serialization += value;
30
+ }
31
+
32
+ return serialization;
33
+ };
34
+
35
+ export default serialize;