@amazon/vinyl-hls-parser 1.1.1 → 1.2.1

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.
Files changed (62) hide show
  1. package/dist/hlsTestAssets/types/current/tsconfig.tsbuildinfo +1 -1
  2. package/dist/index.cjs +8 -1
  3. package/dist/index.cjs.map +2 -2
  4. package/dist/index.js +9 -2
  5. package/dist/index.js.map +3 -3
  6. package/dist/test/benchmark.es5.js +56 -248
  7. package/dist/test/benchmark.js +164 -972
  8. package/dist/test/benchmark.js.map +4 -4
  9. package/dist/types/current/parse/parseMainPlaylist.d.ts.map +1 -1
  10. package/dist/types/current/parse/parseMainPlaylist.js +16 -2
  11. package/dist/types/current/parse/parseMediaPlaylist.d.ts.map +1 -1
  12. package/dist/types/current/tsconfig.tsbuildinfo +1 -1
  13. package/dist/types/current/types/HlsDateRange.d.ts +51 -0
  14. package/dist/types/current/types/HlsDateRange.d.ts.map +1 -0
  15. package/dist/types/current/types/HlsDateRange.js +11 -0
  16. package/dist/types/current/types/HlsMainPlaylist.d.ts +22 -0
  17. package/dist/types/current/types/HlsMainPlaylist.d.ts.map +1 -0
  18. package/dist/types/current/types/HlsMainPlaylist.js +5 -0
  19. package/dist/types/current/types/HlsMediaPlaylist.d.ts +32 -0
  20. package/dist/types/current/types/HlsMediaPlaylist.d.ts.map +1 -0
  21. package/dist/types/current/types/HlsMediaPlaylist.js +5 -0
  22. package/dist/types/ts3.7/types/HlsDateRange.d.ts +51 -0
  23. package/dist/types/ts3.7/types/HlsMainPlaylist.d.ts +22 -0
  24. package/dist/types/ts3.7/types/HlsMediaPlaylist.d.ts +32 -0
  25. package/dist/types/ts4.1/types/HlsDateRange.d.ts +51 -0
  26. package/dist/types/ts4.1/types/HlsMainPlaylist.d.ts +22 -0
  27. package/dist/types/ts4.1/types/HlsMediaPlaylist.d.ts +32 -0
  28. package/dist/types/ts4.7/types/HlsDateRange.d.ts +51 -0
  29. package/dist/types/ts4.7/types/HlsMainPlaylist.d.ts +22 -0
  30. package/dist/types/ts4.7/types/HlsMediaPlaylist.d.ts +32 -0
  31. package/package.json +24 -14
  32. package/dist/test/benchmark.css +0 -71
  33. package/dist/test/benchmark.html +0 -67
  34. package/dist/test/favicon.png +0 -0
  35. package/dist/test/index.html +0 -61
  36. package/dist/test/integ.es5.js +0 -410
  37. package/dist/test/integ.js +0 -2127
  38. package/dist/test/integ.js.map +0 -7
  39. package/dist/test/jasmine.css +0 -304
  40. package/dist/test/jasmineHtml.es5.js +0 -670
  41. package/dist/test/jasmineHtml.js +0 -10851
  42. package/dist/test/jasmineHtml.js.map +0 -7
  43. package/dist/test/styles.css +0 -42
  44. package/dist/unit/types/current/index.d.ts +0 -7
  45. package/dist/unit/types/current/index.d.ts.map +0 -1
  46. package/dist/unit/types/current/index.js +0 -6
  47. package/dist/unit/types/current/parse/parseAttributes.test.d.ts +0 -2
  48. package/dist/unit/types/current/parse/parseAttributes.test.d.ts.map +0 -1
  49. package/dist/unit/types/current/parse/parseAttributes.test.js +0 -70
  50. package/dist/unit/types/current/parse/parseMainPlaylist.test.d.ts +0 -2
  51. package/dist/unit/types/current/parse/parseMainPlaylist.test.d.ts.map +0 -1
  52. package/dist/unit/types/current/parse/parseMainPlaylist.test.js +0 -194
  53. package/dist/unit/types/current/parse/parseMediaPlaylist.test.d.ts +0 -2
  54. package/dist/unit/types/current/parse/parseMediaPlaylist.test.d.ts.map +0 -1
  55. package/dist/unit/types/current/parse/parseMediaPlaylist.test.js +0 -401
  56. package/dist/unit/types/current/parse/parseUtil.test.d.ts +0 -2
  57. package/dist/unit/types/current/parse/parseUtil.test.d.ts.map +0 -1
  58. package/dist/unit/types/current/parse/parseUtil.test.js +0 -67
  59. package/dist/unit/types/current/setup.d.ts +0 -2
  60. package/dist/unit/types/current/setup.d.ts.map +0 -1
  61. package/dist/unit/types/current/setup.js +0 -19
  62. package/dist/unit/types/current/tsconfig.tsbuildinfo +0 -1
@@ -1,2127 +0,0 @@
1
- "use strict";
2
- (() => {
3
- var __defProp = Object.defineProperty;
4
- var __defProps = Object.defineProperties;
5
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
9
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
- var __spreadValues = (a, b) => {
11
- for (var prop in b || (b = {}))
12
- if (__hasOwnProp.call(b, prop))
13
- __defNormalProp(a, prop, b[prop]);
14
- if (__getOwnPropSymbols)
15
- for (var prop of __getOwnPropSymbols(b)) {
16
- if (__propIsEnum.call(b, prop))
17
- __defNormalProp(a, prop, b[prop]);
18
- }
19
- return a;
20
- };
21
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
22
-
23
- // ../vinyl-util/dist/index.js
24
- var __defProp2 = Object.defineProperty;
25
- var __defProps2 = Object.defineProperties;
26
- var __getOwnPropDescs2 = Object.getOwnPropertyDescriptors;
27
- var __getOwnPropSymbols2 = Object.getOwnPropertySymbols;
28
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
29
- var __propIsEnum2 = Object.prototype.propertyIsEnumerable;
30
- var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
31
- var __spreadValues2 = (a, b) => {
32
- for (var prop in b || (b = {}))
33
- if (__hasOwnProp2.call(b, prop))
34
- __defNormalProp2(a, prop, b[prop]);
35
- if (__getOwnPropSymbols2)
36
- for (var prop of __getOwnPropSymbols2(b)) {
37
- if (__propIsEnum2.call(b, prop))
38
- __defNormalProp2(a, prop, b[prop]);
39
- }
40
- return a;
41
- };
42
- var __spreadProps2 = (a, b) => __defProps2(a, __getOwnPropDescs2(b));
43
- var __publicField = (obj, key, value) => __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
44
- function invariant() {
45
- return void 0;
46
- }
47
- var ErrorOrigin = {
48
- /**
49
- * The error originated from Vinyl and was reported from the uncaught exception or promise
50
- * rejection handlers.
51
- */
52
- UNCAUGHT: "uncaught",
53
- /**
54
- * The error originated from Vinyl and was caught.
55
- */
56
- INTERNAL: "internal",
57
- /**
58
- * A Vinyl interface was used incorrectly by a consumer.
59
- */
60
- API: "api",
61
- /**
62
- * The error originated from a failed service call (500 errors).
63
- */
64
- SERVICE_EXTERNAL: "serviceExternal",
65
- /**
66
- * The error originated from a failed service call (400 errors).
67
- */
68
- SERVICE_INTERNAL: "serviceInternal",
69
- /**
70
- * The error originated from a problem playing provided media.
71
- * The reporter is from a component such as the element, source buffer, media source, etc.
72
- */
73
- MEDIA: "media",
74
- /**
75
- * The error originated from a problem parsing input data.
76
- * Such as a malformed Dash or HLS manifest.
77
- */
78
- PARSING: "parsing",
79
- /**
80
- * The error originated from an incompatibility with browser APIs,
81
- * such as EME.
82
- */
83
- COMPATIBILITY: "compatibility",
84
- /**
85
- * The error originated from DRM.
86
- * This does not include internal or service errors, only errors from the creation of media keys or media key
87
- * sessions.
88
- */
89
- DRM: "drm"
90
- };
91
- var ReportableError = class _ReportableError extends Error {
92
- constructor(message, origin = ErrorOrigin.INTERNAL, level = "fatal") {
93
- super(message);
94
- this.origin = origin;
95
- this.level = level;
96
- Object.setPrototypeOf(this, _ReportableError.prototype);
97
- }
98
- get [Symbol.toStringTag]() {
99
- return "ReportableError";
100
- }
101
- get name() {
102
- return this[Symbol.toStringTag];
103
- }
104
- /**
105
- * All ReportableError instances must be serializable.
106
- */
107
- toJSON() {
108
- return {
109
- level: this.level,
110
- message: this.message,
111
- name: this.name,
112
- origin: this.origin,
113
- stack: this.stack
114
- };
115
- }
116
- };
117
- var IllegalArgumentError = class _IllegalArgumentError extends ReportableError {
118
- constructor(message, isInternal = true) {
119
- super(message, isInternal ? ErrorOrigin.INTERNAL : ErrorOrigin.API);
120
- this.isInternal = isInternal;
121
- Object.setPrototypeOf(this, _IllegalArgumentError.prototype);
122
- }
123
- get [Symbol.toStringTag]() {
124
- return "IllegalArgumentError";
125
- }
126
- };
127
- var locale = {
128
- variableNotDefined: "Variable '{name}' is not defined"
129
- };
130
- var DEFAULT_SUBSTITUTE_PATTERN = /\{(\w+)}/g;
131
- function substitute(str, variables, pattern = DEFAULT_SUBSTITUTE_PATTERN) {
132
- return str.replace(pattern, (_, name) => {
133
- if (!(name in variables)) {
134
- throw new IllegalArgumentError(
135
- locale.variableNotDefined.replace("{name}", String(name))
136
- );
137
- }
138
- return String(variables[name]);
139
- });
140
- }
141
- function isWhitespaceChar(charCode) {
142
- return charCode === 32 || // ' ' (space)
143
- charCode === 9 || // '\t' (tab)
144
- charCode === 13 || // '\r' (carriage return)
145
- charCode === 10;
146
- }
147
- function eqStr(a, b, ignoreCase = false) {
148
- if (a == null && b == null) return true;
149
- if (a == null || b == null) return false;
150
- if (a === b) return true;
151
- if (ignoreCase)
152
- return a.length === b.length && a.toLowerCase() === b.toLowerCase();
153
- return false;
154
- }
155
- function char(str) {
156
- return str.charCodeAt(0);
157
- }
158
- function truncate(str, maxLength, indicator = "\u2026") {
159
- if (str == null) return str;
160
- if (str.length > maxLength)
161
- return str.substring(0, maxLength - indicator.length) + indicator;
162
- return str;
163
- }
164
- function clamp(value, min2, max2) {
165
- return Math.min(Math.max(value, min2), max2);
166
- }
167
- function printStringPosition(str, index, options) {
168
- var _a;
169
- const caret = (options == null ? void 0 : options.caret) || "^";
170
- index = clamp(index, 0, str.length);
171
- const minIndex = str.lastIndexOf("\n", index - 1) + 1;
172
- let maxIndex = str.indexOf("\n", index);
173
- if (maxIndex === -1) maxIndex = str.length;
174
- const split = (options == null ? void 0 : options.split) === void 0 ? 0.6 : options.split;
175
- const cols = ((_a = options == null ? void 0 : options.maxColumns) != null ? _a : 60) - caret.length;
176
- let leadingChars = cols * split;
177
- let trailingChars = cols * (1 - split);
178
- const maxLeadingChars = index - minIndex;
179
- const maxTrailingChars = maxIndex - index;
180
- if (leadingChars > maxLeadingChars) {
181
- trailingChars += leadingChars - maxLeadingChars;
182
- leadingChars = maxLeadingChars;
183
- if (trailingChars > maxTrailingChars) trailingChars = maxTrailingChars;
184
- } else if (trailingChars > maxTrailingChars) {
185
- leadingChars += trailingChars - maxTrailingChars;
186
- trailingChars = maxTrailingChars;
187
- if (leadingChars > maxLeadingChars) leadingChars = maxLeadingChars;
188
- }
189
- let out = str.substring(index - leadingChars, index + trailingChars) + "\n";
190
- out += " ".repeat(leadingChars) + caret;
191
- return out;
192
- }
193
- var StringReader = class {
194
- /**
195
- * @param data The string to read.
196
- */
197
- constructor(data) {
198
- this.data = data;
199
- __publicField(this, "position", 0);
200
- }
201
- /**
202
- * Returns true if the current {@link position} is less than the source data's length.
203
- */
204
- hasNext() {
205
- return this.position < this.data.length;
206
- }
207
- /**
208
- * Returns the number of characters remaining to be read.
209
- */
210
- get remaining() {
211
- return this.data.length - this.position;
212
- }
213
- /**
214
- * Returns the length of {@link data}.
215
- */
216
- get length() {
217
- return this.data.length;
218
- }
219
- /**
220
- * Throws a {@link StringParseError} where the location uses {@link printStringPosition} to
221
- * show a friendly message indicating the current position.
222
- *
223
- * @param message
224
- * @param offset The offset to add to the current position.
225
- */
226
- err(message, offset = 0) {
227
- throw new StringParseError(this.data, this.position + offset, message);
228
- }
229
- /**
230
- * Reads and returns the character code at the current position.
231
- * To read the next character without advancing the cursor, use {@link peek}
232
- *
233
- * Note:
234
- * This method has no bounds checking; if {@link position} is greater than or equal to
235
- * `str.length` then NaN will be returned and {@link position} will still be incremented.
236
- *
237
- * @see String.charCodeAt
238
- */
239
- next() {
240
- return this.data.charCodeAt(this.position++);
241
- }
242
- /**
243
- * Reads characters until the predicate returns false or the data length has been reached.
244
- *
245
- * @param predicate Given the char code at the cursor index, returns true if the character
246
- * should be included in the substring result.
247
- * @returns number The start position.
248
- */
249
- while(predicate) {
250
- const start = this.position;
251
- let i = start;
252
- const n = this.data.length;
253
- while (i < n && predicate(this.data.charCodeAt(i))) i++;
254
- this.position = i;
255
- return start;
256
- }
257
- /**
258
- * Reads characters until the predicate returns true or the string length has been reached.
259
- *
260
- * @param predicate
261
- * @returns number Returns the start index.
262
- */
263
- until(predicate) {
264
- return this.while((charCode) => !predicate(charCode));
265
- }
266
- /**
267
- * Reads characters until the given character has been found or the string length has been
268
- * reached.
269
- *
270
- * @param charCode
271
- * @return number Returns the start index.
272
- */
273
- untilChar(charCode) {
274
- return this.until((cc) => cc === charCode);
275
- }
276
- /**
277
- * Reads characters until the given string has been found or the string length has been
278
- * reached.
279
- *
280
- * @param string The string to match
281
- * @return number Returns the start index.
282
- */
283
- untilString(string) {
284
- const start = this.position;
285
- const index = this.data.indexOf(string, this.position);
286
- this.position = index === -1 ? this.data.length : index;
287
- return start;
288
- }
289
- /**
290
- * The same as {@link while} except returns the read substring as a result.
291
- */
292
- substringWhile(predicate) {
293
- return this.data.substring(this.while(predicate), this.position);
294
- }
295
- /**
296
- * The same as {@link until} except returns the read substring as a result.
297
- */
298
- substringUntil(predicate) {
299
- return this.substringWhile((charCode) => !predicate(charCode));
300
- }
301
- /**
302
- * The same as {@link untilChar} except returns the read substring as a result.
303
- */
304
- substringUntilChar(charCode) {
305
- return this.substringWhile((iCharCode) => charCode !== iCharCode);
306
- }
307
- /**
308
- * Reads the substring from the current index with the given length.
309
- *
310
- * @param length
311
- */
312
- substr(length) {
313
- const sub = this.data.substring(this.position, this.position + length);
314
- this.position += sub.length;
315
- return sub;
316
- }
317
- /**
318
- * Reads the expected string from the current position.
319
- * If the read string doesn't match the given string, a {@link StringParseError} is thrown.
320
- *
321
- * @param str The string required to match at the current position.
322
- * @param ignoreCase If true, the comparison will be case-insensitive.
323
- */
324
- read(str, ignoreCase = false) {
325
- const actual = this.substr(str.length);
326
- if (!eqStr(actual, str, ignoreCase))
327
- this.err(`Expected '${str}', actual: '${actual}'`);
328
- return actual;
329
- }
330
- /**
331
- * Reads the expected char code from the current position.
332
- * If the read character doesn't match the given character, a {@link StringParseError} is
333
- * thrown.
334
- *
335
- * @param charCode The character code required to match at the current position.
336
- */
337
- readChar(charCode) {
338
- const actual = this.next();
339
- if (actual !== charCode)
340
- this.err(
341
- `Expected '${String.fromCharCode(charCode)}', actual: '${String.fromCharCode(actual)}'`
342
- );
343
- return actual;
344
- }
345
- /**
346
- * Returns the character at the current position without advancing the cursor.
347
- *
348
- * Note:
349
- * This method has no bounds checking; if {@link position} is greater than or equal to
350
- * `str.length` then `NaN` will be returned.
351
- *
352
- * @see String.charCodeAt
353
- */
354
- get peek() {
355
- return this.data.charCodeAt(this.position);
356
- }
357
- /**
358
- * Reads through all whitespace characters, returning the starting index.
359
- */
360
- white() {
361
- return this.while(isWhitespaceChar);
362
- }
363
- /**
364
- * If {@link peek} equals the given character code, returns true and advances the index by
365
- * one.
366
- *
367
- * @param charCode
368
- */
369
- charIf(charCode) {
370
- if (this.peek === charCode) {
371
- this.next();
372
- return true;
373
- } else {
374
- return false;
375
- }
376
- }
377
- /**
378
- * If the given string matches the substring at the current position, returns true and advances
379
- * the index by the string's length.
380
- */
381
- stringIf(string, ignoreCase = false) {
382
- if (this.remaining < string.length) return false;
383
- const substr = this.data.substring(
384
- this.position,
385
- this.position + string.length
386
- );
387
- const match = eqStr(substr, string, ignoreCase);
388
- if (match) this.position += string.length;
389
- return match;
390
- }
391
- };
392
- var locale2 = {
393
- messageSeparator: ", at: \n"
394
- };
395
- var StringParseError = class _StringParseError extends ReportableError {
396
- constructor(str, position, reason) {
397
- const location2 = printStringPosition(str, position);
398
- super(
399
- `${reason}${locale2.messageSeparator}${location2}`,
400
- ErrorOrigin.PARSING
401
- );
402
- this.position = position;
403
- this.reason = reason;
404
- __publicField(this, "location");
405
- this.location = location2;
406
- Object.setPrototypeOf(this, _StringParseError.prototype);
407
- }
408
- get [Symbol.toStringTag]() {
409
- return "StringParseError";
410
- }
411
- toJSON() {
412
- return __spreadProps2(__spreadValues2({}, super.toJSON()), {
413
- position: this.position,
414
- location: this.location,
415
- reason: this.reason
416
- });
417
- }
418
- };
419
- function ownKeys(obj) {
420
- if (!obj) return /* @__PURE__ */ new Set();
421
- if (typeof Reflect !== "undefined")
422
- return new Set(Reflect.ownKeys(obj));
423
- const properties = /* @__PURE__ */ new Set();
424
- Object.getOwnPropertyNames(obj).forEach((item) => properties.add(item));
425
- Object.getOwnPropertySymbols(obj).forEach((item) => properties.add(item));
426
- return properties;
427
- }
428
- function isPlainObject(value) {
429
- if (!value || typeof value !== "object" || Array.isArray(value))
430
- return false;
431
- const proto = Object.getPrototypeOf(value);
432
- return !proto || !Object.getPrototypeOf(proto);
433
- }
434
- function toJson(value) {
435
- return toJsonInternal(value, /* @__PURE__ */ new Set());
436
- }
437
- function toJsonInternal(value, visited) {
438
- switch (typeof value) {
439
- case "object":
440
- return objectToJsonInternal(value, visited);
441
- case "undefined":
442
- case "boolean":
443
- case "number":
444
- case "string":
445
- return value;
446
- case "function":
447
- return `[function ${value.name}]`;
448
- case "symbol":
449
- return `[symbol ${value.toString().slice(7, -1)}]`;
450
- case "bigint":
451
- return value.toString();
452
- }
453
- }
454
- function objectToJsonInternal(value, visited) {
455
- if (value == null) return value;
456
- if (visited.has(value)) return `<circular reference: ${String(value)}>`;
457
- visited.add(value);
458
- if ("toJSON" in value && typeof value.toJSON === "function")
459
- return value.toJSON();
460
- if (value instanceof Set) {
461
- return Array.from(value).map((e) => toJsonInternal(e, visited));
462
- } else if (Array.isArray(value)) {
463
- return value.map((e) => toJsonInternal(e, visited));
464
- } else {
465
- if (isPlainObject(value)) {
466
- const o = {};
467
- for (const key in value) {
468
- o[key] = toJsonInternal(value[key], visited);
469
- }
470
- return o;
471
- } else if (value instanceof Error) {
472
- return {
473
- name: value.name,
474
- message: value.message,
475
- stack: value.stack
476
- };
477
- } else {
478
- return value.toString();
479
- }
480
- }
481
- }
482
- function stringifyForPrint(value, maxLength, indicator = "\u2026") {
483
- let str = JSON.stringify(
484
- toJson(value),
485
- (_, value2) => {
486
- const type = typeof value2;
487
- if (["undefined"].includes(type)) {
488
- return `{{${String(value2)}}}`;
489
- }
490
- if (type === "number") {
491
- if (Number.isNaN(value2) || !Number.isFinite(value2))
492
- return `{{${value2.toString()}}}`;
493
- }
494
- return value2;
495
- },
496
- " "
497
- );
498
- str = str.replace(/("\{\{.*}}")/g, (_, s) => {
499
- return s.substring(3, s.length - 3);
500
- });
501
- if (maxLength) str = truncate(str, maxLength, indicator);
502
- return str;
503
- }
504
- function merge(...sources) {
505
- if (!sources.length) return void 0;
506
- if (Array.isArray(sources[0])) return Array.prototype.concat(...sources);
507
- return Object.assign({}, ...sources);
508
- }
509
- var ValidationError = class _ValidationError extends ReportableError {
510
- /**
511
- * @param message The validation error message.
512
- * @param origin The error origin, typically API (default) or SERVICE_EXTERNAL
513
- * @param path The property path to the invalid field.
514
- */
515
- constructor(message, origin = ErrorOrigin.API, path = []) {
516
- super(message, origin);
517
- this.path = path;
518
- Object.setPrototypeOf(this, _ValidationError.prototype);
519
- }
520
- get [Symbol.toStringTag]() {
521
- return "ValidationError";
522
- }
523
- toJSON() {
524
- return __spreadProps2(__spreadValues2({}, super.toJSON()), {
525
- origin: this.origin,
526
- path: this.path
527
- });
528
- }
529
- };
530
-
531
- // ../vinyl-validation/dist/index.js
532
- var __defProp3 = Object.defineProperty;
533
- var __defProps3 = Object.defineProperties;
534
- var __getOwnPropDescs3 = Object.getOwnPropertyDescriptors;
535
- var __getOwnPropSymbols3 = Object.getOwnPropertySymbols;
536
- var __hasOwnProp3 = Object.prototype.hasOwnProperty;
537
- var __propIsEnum3 = Object.prototype.propertyIsEnumerable;
538
- var __defNormalProp3 = (obj, key, value) => key in obj ? __defProp3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
539
- var __spreadValues3 = (a, b) => {
540
- for (var prop in b || (b = {}))
541
- if (__hasOwnProp3.call(b, prop))
542
- __defNormalProp3(a, prop, b[prop]);
543
- if (__getOwnPropSymbols3)
544
- for (var prop of __getOwnPropSymbols3(b)) {
545
- if (__propIsEnum3.call(b, prop))
546
- __defNormalProp3(a, prop, b[prop]);
547
- }
548
- return a;
549
- };
550
- var __spreadProps3 = (a, b) => __defProps3(a, __getOwnPropDescs3(b));
551
- var __publicField2 = (obj, key, value) => __defNormalProp3(obj, typeof key !== "symbol" ? key + "" : key, value);
552
- var validatorLocale = {
553
- /**
554
- * The expectation template string with the following replacement tokens:
555
- *
556
- * `{expected}` - The expected description.
557
- * `{actual}` - The actual value.
558
- * `{path}` - The path, dot separated.
559
- */
560
- template: "Expected: {expected}, but was: {actual}. At: {path}"
561
- };
562
- function createValidationExpectationMessage(expectationMessage, input, path, inputStringify = (input2) => stringifyForPrint(input2, 500)) {
563
- return substitute(validatorLocale.template, {
564
- expected: expectationMessage,
565
- actual: inputStringify(input),
566
- path: path.join(".")
567
- });
568
- }
569
- function createValidator(expectationMessage, isValid, inputStringify = (input) => stringifyForPrint(input, 500)) {
570
- return {
571
- description: expectationMessage,
572
- isValid(input) {
573
- return isValid(input);
574
- },
575
- validate(input, _, path = []) {
576
- if (!isValid(input)) {
577
- return [
578
- {
579
- message: createValidationExpectationMessage(
580
- expectationMessage,
581
- input,
582
- path,
583
- inputStringify
584
- ),
585
- path
586
- }
587
- ];
588
- }
589
- return [];
590
- },
591
- assert: (input, origin, path = []) => {
592
- if (!isValid(input)) {
593
- throw new ValidationError(
594
- createValidationExpectationMessage(
595
- expectationMessage,
596
- input,
597
- path,
598
- inputStringify
599
- ),
600
- origin,
601
- path
602
- );
603
- }
604
- }
605
- };
606
- }
607
- function createDeepValidator(description, validate) {
608
- return {
609
- description,
610
- isValid(input) {
611
- return validate(input, { all: false }, []).length === 0;
612
- },
613
- validate(input, options, path = []) {
614
- return validate(input, options != null ? options : { all: false }, path);
615
- },
616
- assert: (input, origin, path = []) => {
617
- const errors = validate(input, { all: false }, path);
618
- if (errors.length) {
619
- const error = errors[0];
620
- throw new ValidationError(error.message, origin, error.path);
621
- }
622
- }
623
- };
624
- }
625
- var locale3 = {
626
- /**
627
- * {value} The child validators' descriptions, joined with `separator`.
628
- *
629
- * groupings of and validators is unimportant,
630
- * and(and(a, b), c) is the same as and(a, and(b, c)), so `a & b & c` is an accurate
631
- * representation for either.
632
- */
633
- template: "{value}",
634
- /**
635
- * The separator with which to join child validator descriptions.
636
- */
637
- separator: " & "
638
- };
639
- function andValidators(...validators) {
640
- return createDeepValidator(
641
- substitute(locale3.template, {
642
- value: validators.map((v) => v.description).join(locale3.separator)
643
- }),
644
- (input, options, path) => {
645
- for (const validator of validators) {
646
- const errors = validator.validate(input, options, path);
647
- if (errors.length) return errors;
648
- }
649
- return [];
650
- }
651
- );
652
- }
653
- var locale22 = {
654
- /**
655
- * {value} - The child validators' descriptions, joined with `separator`.
656
- */
657
- template: "({value})",
658
- /**
659
- * The separator with which to join child validator descriptions.
660
- */
661
- separator: " | "
662
- };
663
- function orValidators(...validators) {
664
- const description = substitute(locale22.template, {
665
- value: validators.map((v) => v.description).join(locale22.separator)
666
- });
667
- return createDeepValidator(description, (input, options, path) => {
668
- let longestErrors = [];
669
- let longestPath = 0;
670
- for (const validator of validators) {
671
- const errors = validator.validate(input, options, path);
672
- if (!errors.length) return errors;
673
- const pathLength = errors.reduce(
674
- (max, m) => Math.max(m.path.length, max),
675
- 0
676
- );
677
- if (pathLength >= longestPath) {
678
- longestErrors = errors;
679
- longestPath = pathLength;
680
- }
681
- }
682
- return longestPath > path.length ? longestErrors : [
683
- {
684
- message: createValidationExpectationMessage(
685
- description,
686
- input,
687
- path
688
- ),
689
- path
690
- }
691
- ];
692
- });
693
- }
694
- var requiredValidationOptions = {
695
- optional: false
696
- };
697
- var SchemaBase = class {
698
- constructor(currentValidator, previousSchema, operation) {
699
- this.currentValidator = currentValidator;
700
- this.previousSchema = previousSchema;
701
- this.operation = operation;
702
- __publicField2(this, "__type", /* @__PURE__ */ invariant());
703
- __publicField2(this, "validator");
704
- __publicField2(this, "_options", requiredValidationOptions);
705
- __publicField2(this, "assert", (input, origin, path) => {
706
- this.validator.assert(input, origin, path);
707
- });
708
- __publicField2(this, "isValid", (input) => this.validator.isValid(input));
709
- __publicField2(this, "validate", (input, options, path) => this.validator.validate(input, options, path));
710
- this.validator = operation == null ? currentValidator : operation(previousSchema, currentValidator);
711
- }
712
- get options() {
713
- return this._options;
714
- }
715
- get description() {
716
- return this.validator.description;
717
- }
718
- /**
719
- * Clones this schema, transforming all validators with the given mutator.
720
- *
721
- * @param transform A transformer which takes an existing validator in the chain and returns
722
- * a new one. Validators should be considered to be immutable; transform should not change the
723
- * input but instead return a new validator.
724
- */
725
- clone(transform = (v) => v) {
726
- const cloned = this.operation ? this.self(
727
- transform(this.currentValidator),
728
- this.previousSchema.clone(transform),
729
- this.operation
730
- ) : this.self(transform(this.currentValidator));
731
- cloned._options = this._options;
732
- return cloned;
733
- }
734
- self(current, previous, operation) {
735
- if (this.constructor.length > 3) {
736
- throw new IllegalArgumentError(
737
- "constructor should have at most three required arguments"
738
- );
739
- }
740
- return new this.constructor(current, previous, operation);
741
- }
742
- /**
743
- * Constructs a new schema with a validator chaining the current validator with the
744
- * provided next in an AND operation.
745
- *
746
- * @param nextValidator The validator to run after the current.
747
- * @return Returns a new Schema instance the same class with a new validator chaining the
748
- * current validator with the given next in an AND operation.
749
- */
750
- chain(nextValidator) {
751
- return this.self(nextValidator, this, andValidators);
752
- }
753
- optional() {
754
- const cloned = this.clone();
755
- cloned._options = __spreadProps3(__spreadValues3({}, cloned.options), {
756
- optional: true
757
- });
758
- return cloned;
759
- }
760
- required() {
761
- const cloned = this.clone();
762
- cloned._options = __spreadProps3(__spreadValues3({}, cloned.options), {
763
- optional: false
764
- });
765
- return cloned;
766
- }
767
- };
768
- var locale32 = {
769
- null: "null",
770
- nullish: "nullish",
771
- undefined: "undefined"
772
- };
773
- var valueValidators = {
774
- any() {
775
- return createValidator("", () => true);
776
- },
777
- /**
778
- * Creates a validator that asserts that the input is nullish.
779
- */
780
- nullish() {
781
- return createValidator(locale32.nullish, (input) => input == null);
782
- },
783
- /**
784
- * Creates a validator that asserts that the input is strictly null.
785
- */
786
- null() {
787
- return createValidator(locale32.null, (input) => input === null);
788
- },
789
- /**
790
- * Creates a validator that asserts that the input is strictly undefined.
791
- */
792
- undefined() {
793
- return createValidator(locale32.undefined, (input) => input === void 0);
794
- }
795
- };
796
- var ValueSchema = class _ValueSchema extends SchemaBase {
797
- /**
798
- * Prepends this validator allowing for null or undefined.
799
- */
800
- maybe() {
801
- return this.or(valueValidators.nullish());
802
- }
803
- /**
804
- * Prepends this validator allowing for null.
805
- */
806
- orNull() {
807
- return this.or(valueValidators.null());
808
- }
809
- /**
810
- * Prepends this validator allowing for undefined.
811
- */
812
- orUndefined() {
813
- return this.or(valueValidators.undefined());
814
- }
815
- /**
816
- * Returns a validator that asserts if this validator and the next passes.
817
- *
818
- * @see andValidators
819
- *
820
- * @param nextValidator The validator to run after the current.
821
- * @return Returns a new ValueSchema intersecting this validator and the next.
822
- */
823
- and(nextValidator) {
824
- return new _ValueSchema(nextValidator, this, andValidators);
825
- }
826
- /**
827
- * Returns a validator that asserts if this validator or the next passes.
828
- *
829
- * Implementation note:
830
- * subclasses should not change the schema instance returned unless all chainable validators
831
- * accept input type 'unknown'.
832
- *
833
- * @param nextValidator The validator to run after the current.
834
- * @return Returns a new ValueSchema providing the union of this validator and the next.
835
- */
836
- or(nextValidator) {
837
- return new _ValueSchema(nextValidator, this, orValidators);
838
- }
839
- };
840
- var locale4 = {
841
- array: "array",
842
- minLength: "at least {value} elements",
843
- maxLength: "at most {value} elements",
844
- exactlyLength: "exactly {value} elements",
845
- actualLength: "length {value}",
846
- withElements: "({value})[]",
847
- tuple: "[{value}]"
848
- };
849
- var arrayValidators = {
850
- /**
851
- * Creates a validator that asserts that the input is an array.
852
- *
853
- * Note: arrays can only be readonly by type system, there is no native readonly
854
- * js array. This validator assumes mutability, use the ArraySchema readonly() method
855
- * to cast to a readonly array.
856
- */
857
- isArray() {
858
- return createValidator(
859
- locale4.array,
860
- (input) => Array.isArray(input)
861
- );
862
- },
863
- /**
864
- * Creates a validator that asserts that every element passes the given validator.
865
- *
866
- * @param elementValidator
867
- */
868
- withElements(elementValidator) {
869
- return createDeepValidator(
870
- substitute(locale4.withElements, {
871
- value: elementValidator.description
872
- }),
873
- (input, options, path) => {
874
- const errors = [];
875
- for (let i = 0; i < input.length; i++) {
876
- const element = input[i];
877
- errors.push(
878
- ...elementValidator.validate(
879
- element,
880
- options,
881
- path.concat(i.toString())
882
- )
883
- );
884
- if (!options.all && errors.length) return errors;
885
- }
886
- return errors;
887
- }
888
- );
889
- },
890
- /**
891
- * Creates a validator that asserts that the input array is a tuple whose elements match
892
- * the given validators.
893
- *
894
- * @param validators
895
- */
896
- tuple(...validators) {
897
- const lengthValidator = createValidator(
898
- substitute(locale4.exactlyLength, {
899
- value: validators.length
900
- }),
901
- (length) => length === validators.length
902
- );
903
- return createDeepValidator(
904
- substitute(locale4.tuple, { value: validators.join(", ") }),
905
- (input, options, path) => {
906
- const errors = [];
907
- errors.push(
908
- ...lengthValidator.validate(input.length, options, path)
909
- );
910
- if (!options.all && errors.length) return errors;
911
- const n = Math.min(validators.length, input.length);
912
- for (let i = 0; i < n; i++) {
913
- const element = input[i];
914
- const validator = validators[i];
915
- errors.push(
916
- ...validator.validate(
917
- element,
918
- options,
919
- path.concat(i.toString())
920
- )
921
- );
922
- if (!options.all && errors.length) return errors;
923
- }
924
- return errors;
925
- }
926
- );
927
- },
928
- /**
929
- * Creates a validator that validates the input array has the given minimum length.
930
- * @param min The minimum number of elements (inclusive)
931
- */
932
- minLength(min) {
933
- return createValidator(
934
- substitute(locale4.minLength, { value: min }),
935
- (input) => input.length >= min,
936
- (input) => substitute(locale4.actualLength, { value: input.length })
937
- );
938
- },
939
- /**
940
- *
941
- * Creates a validator that validates the input array has the given maximum length.
942
- * @param max The maximum number of elements (inclusive)
943
- */
944
- maxLength(max) {
945
- return createValidator(
946
- substitute(locale4.maxLength, { value: max }),
947
- (input) => input.length <= max,
948
- (input) => substitute(locale4.actualLength, { value: input.length })
949
- );
950
- }
951
- };
952
- var _ArraySchema = class _ArraySchema2 extends ValueSchema {
953
- /**
954
- * The base ArraySchema instance validating that the input is an Array.
955
- */
956
- static get base() {
957
- if (this._base == null)
958
- this._base = new _ArraySchema2(arrayValidators.isArray());
959
- return this._base;
960
- }
961
- /**
962
- * Creates a validator that asserts that every element passes the given validator.
963
- *
964
- * @param elementValidator
965
- */
966
- withElements(elementValidator) {
967
- return this.chain(arrayValidators.withElements(elementValidator));
968
- }
969
- /**
970
- * Creates a validator that asserts that the input array is a tuple whose elements match
971
- * the given validators.
972
- *
973
- * @param validators
974
- */
975
- tuple(...validators) {
976
- return this.chain(arrayValidators.tuple(...validators));
977
- }
978
- /**
979
- * Creates a validator that validates the input array has the given minimum length.
980
- * @param min The minimum number of elements (inclusive)
981
- */
982
- minLength(min) {
983
- return this.chain(arrayValidators.minLength(min));
984
- }
985
- /**
986
- *
987
- * Creates a validator that validates the input array has the given maximum length.
988
- * @param max The maximum number of elements (inclusive)
989
- */
990
- maxLength(max) {
991
- return this.chain(arrayValidators.maxLength(max));
992
- }
993
- /**
994
- * Casts to a readonly array.
995
- * This is a shallow cast, elements of the array will not be changed.
996
- */
997
- readonly() {
998
- return this;
999
- }
1000
- /**
1001
- * Casts the type parameter.
1002
- */
1003
- cast() {
1004
- return this;
1005
- }
1006
- };
1007
- __publicField2(_ArraySchema, "_base", null);
1008
- var locale5 = {
1009
- template: "type {value}"
1010
- };
1011
- function typeOfValidator(expected) {
1012
- return createValidator(
1013
- substitute(locale5.template, { value: expected }),
1014
- (input) => {
1015
- return input != null && typeof input === expected;
1016
- }
1017
- );
1018
- }
1019
- var typeOfValidatorCache = {};
1020
- function cachedTypeOfValidator(type) {
1021
- if (!(type in typeOfValidatorCache)) {
1022
- typeOfValidatorCache[type] = typeOfValidator(type);
1023
- }
1024
- return typeOfValidatorCache[type];
1025
- }
1026
- var typeOfValidators = {
1027
- get boolean() {
1028
- return cachedTypeOfValidator("boolean");
1029
- },
1030
- get func() {
1031
- return cachedTypeOfValidator("function");
1032
- },
1033
- get number() {
1034
- return cachedTypeOfValidator("number");
1035
- },
1036
- get object() {
1037
- return cachedTypeOfValidator("object");
1038
- },
1039
- get string() {
1040
- return cachedTypeOfValidator("string");
1041
- },
1042
- get symbol() {
1043
- return cachedTypeOfValidator("symbol");
1044
- }
1045
- };
1046
- var locale6 = {
1047
- length: "at most {value} arguments",
1048
- actualLength: "{value} arguments"
1049
- };
1050
- var functionValidators = {
1051
- length(max) {
1052
- return createValidator(
1053
- substitute(locale6.length, { value: max }),
1054
- (input) => input.length <= max,
1055
- (input) => substitute(locale6.actualLength, { value: input.length })
1056
- );
1057
- }
1058
- };
1059
- var _FunctionSchema = class _FunctionSchema2 extends ValueSchema {
1060
- /**
1061
- * The base Function validator validating that the input is a function.
1062
- */
1063
- static get base() {
1064
- if (this._base == null)
1065
- this._base = new _FunctionSchema2(typeOfValidators.func);
1066
- return this._base;
1067
- }
1068
- length(max) {
1069
- return this.chain(functionValidators.length(max));
1070
- }
1071
- /**
1072
- * Casts the function signature.
1073
- * Function signatures, except for their required number of parameters, cannot be
1074
- * meaningfully validated.
1075
- */
1076
- cast() {
1077
- return this;
1078
- }
1079
- };
1080
- __publicField2(_FunctionSchema, "_base", null);
1081
- var locale7 = {
1082
- set: "Set",
1083
- withElements: "Set<{value}>"
1084
- };
1085
- var setValidators = {
1086
- /**
1087
- * Creates a validator that asserts that the input is a set.
1088
- */
1089
- isSet() {
1090
- return createValidator(
1091
- locale7.set,
1092
- (input) => input instanceof Set
1093
- );
1094
- },
1095
- /**
1096
- * Creates a validator that asserts that every element passes the given validator.
1097
- *
1098
- * @param elementValidator
1099
- */
1100
- withElements(elementValidator) {
1101
- return createDeepValidator(
1102
- substitute(locale7.withElements, {
1103
- value: elementValidator.description
1104
- }),
1105
- (input, options, path) => {
1106
- const errors = [];
1107
- let i = 0;
1108
- for (const element of input) {
1109
- errors.push(
1110
- ...elementValidator.validate(
1111
- element,
1112
- options,
1113
- path.concat(i.toString())
1114
- )
1115
- );
1116
- if (!options.all && errors.length) return errors;
1117
- i++;
1118
- }
1119
- return errors;
1120
- }
1121
- );
1122
- }
1123
- };
1124
- var _SetSchema = class _SetSchema2 extends ValueSchema {
1125
- /**
1126
- * The base SetSchema instance validating that the input is a Set.
1127
- */
1128
- static get base() {
1129
- if (this._base == null)
1130
- this._base = new _SetSchema2(setValidators.isSet());
1131
- return this._base;
1132
- }
1133
- /**
1134
- * Creates a validator that asserts that every element passes the given validator.
1135
- *
1136
- * @param elementValidator
1137
- */
1138
- withElements(elementValidator) {
1139
- return this.chain(setValidators.withElements(elementValidator));
1140
- }
1141
- /**
1142
- * Casts to a readonly set.
1143
- * This is a shallow cast, elements of the array will not be changed.
1144
- */
1145
- readonly() {
1146
- return this;
1147
- }
1148
- /**
1149
- * Casts the parameter type.
1150
- */
1151
- cast() {
1152
- return this;
1153
- }
1154
- };
1155
- __publicField2(_SetSchema, "_base", null);
1156
- var locale8 = {
1157
- gte: "at least {value}",
1158
- gt: "greater than {value}",
1159
- lte: "at most {value}",
1160
- lt: "less than {value}",
1161
- within: "within {min} and {max}",
1162
- safeInteger: "safe integer",
1163
- finite: "finite"
1164
- };
1165
- var numberValidators = {
1166
- /**
1167
- * Creates a validator that asserts that the input number is at least the provided minimum
1168
- * value.
1169
- *
1170
- * @param min The minimum (inclusive) the value may be.
1171
- */
1172
- gte(min) {
1173
- return createValidator(
1174
- substitute(locale8.gte, { value: min }),
1175
- (input) => input >= min
1176
- );
1177
- },
1178
- /**
1179
- * Creates a validator that asserts that the input number is greater than the provided minimum
1180
- * value.
1181
- *
1182
- * @param min The minimum (exclusive) the value may be.
1183
- */
1184
- gt(min) {
1185
- return createValidator(
1186
- substitute(locale8.gt, { value: min }),
1187
- (input) => input > min
1188
- );
1189
- },
1190
- /**
1191
- * Creates a validator that asserts that the input number is at most the provided maximum
1192
- * value.
1193
- *
1194
- * @param max The maximum (inclusive) the value may be.
1195
- */
1196
- lte(max) {
1197
- return createValidator(
1198
- substitute(locale8.lte, { value: max }),
1199
- (input) => input <= max
1200
- );
1201
- },
1202
- /**
1203
- * Creates a validator that asserts that the input number is less than the provided maximum
1204
- * value.
1205
- *
1206
- * @param max The maximum (exclusive) the value may be.
1207
- */
1208
- lt(max) {
1209
- return createValidator(
1210
- substitute(locale8.lt, { value: max }),
1211
- (input) => input < max
1212
- );
1213
- },
1214
- /**
1215
- * Creates a validator that asserts that the input number is at least the provided minimum
1216
- * and at most the provided maximum values.
1217
- *
1218
- * @param min The minimum (inclusive) value the input may be.
1219
- * @param max The maximum (inclusive) value the input may be.
1220
- */
1221
- within(min, max) {
1222
- return createValidator(
1223
- substitute(locale8.within, { min, max }),
1224
- (input) => input >= min && input <= max
1225
- );
1226
- },
1227
- /**
1228
- * Creates a validator that asserts that the input number is finite.
1229
- */
1230
- finite() {
1231
- return createValidator(locale8.finite, (input) => Number.isFinite(input));
1232
- },
1233
- /**
1234
- * Creates a validator that asserts that the input number is a safe integer.
1235
- */
1236
- safeInteger() {
1237
- return createValidator(
1238
- locale8.safeInteger,
1239
- (input) => Number.isSafeInteger(input)
1240
- );
1241
- }
1242
- };
1243
- var _NumberSchema = class _NumberSchema2 extends ValueSchema {
1244
- /**
1245
- * The base Object validator validating that the input is an object.
1246
- */
1247
- static get base() {
1248
- if (this._base == null)
1249
- this._base = new _NumberSchema2(typeOfValidators.number);
1250
- return this._base;
1251
- }
1252
- /**
1253
- * Creates a validator that asserts that the input number is at least the provided minimum
1254
- * value.
1255
- *
1256
- * @param min The minimum (inclusive) the value may be.
1257
- */
1258
- gte(min) {
1259
- return this.chain(numberValidators.gte(min));
1260
- }
1261
- /**
1262
- * Creates a validator that asserts that the input number is greater than the provided minimum
1263
- * value.
1264
- *
1265
- * @param min The minimum (exclusive) the value may be.
1266
- */
1267
- gt(min) {
1268
- return this.chain(numberValidators.gt(min));
1269
- }
1270
- /**
1271
- * Creates a validator that asserts that the input number is at most the provided maximum
1272
- * value.
1273
- *
1274
- * @param max The maximum (inclusive) the value may be.
1275
- */
1276
- lte(max) {
1277
- return this.chain(numberValidators.lte(max));
1278
- }
1279
- /**
1280
- * Creates a validator that asserts that the input number is less than the provided maximum
1281
- * value.
1282
- *
1283
- * @param max The maximum (exclusive) the value may be.
1284
- */
1285
- lt(max) {
1286
- return this.chain(numberValidators.lt(max));
1287
- }
1288
- /**
1289
- * Creates a validator that asserts that the input number is at least the provided minimum
1290
- * and at most the provided maximum values.
1291
- *
1292
- * @param min The minimum (inclusive) value the input may be.
1293
- * @param max The maximum (inclusive) value the input may be.
1294
- */
1295
- within(min, max) {
1296
- return this.chain(numberValidators.within(min, max));
1297
- }
1298
- /**
1299
- * Creates a validator that asserts that the input number is finite.
1300
- */
1301
- finite() {
1302
- return this.chain(numberValidators.finite());
1303
- }
1304
- /**
1305
- * Creates a validator that asserts that the input number is a safe integer.
1306
- */
1307
- safeInteger() {
1308
- return this.chain(numberValidators.safeInteger());
1309
- }
1310
- };
1311
- __publicField2(_NumberSchema, "_base", null);
1312
- function isValidatorWithPartial(validator) {
1313
- return "partial" in validator && "partialDeep" in validator;
1314
- }
1315
- function maybeToDeepPartial(validator) {
1316
- return isValidatorWithPartial(validator) ? validator.partialDeep() : validator;
1317
- }
1318
- function maybeToPartial(validator) {
1319
- return isValidatorWithPartial(validator) ? validator.partial() : validator;
1320
- }
1321
- var locale9 = {
1322
- extend: "{\n{body}\n}",
1323
- prop: "{key}: {value}",
1324
- propSeparator: ",\n",
1325
- indent: " ",
1326
- required: `property '{key}' is required`
1327
- };
1328
- var objectValidators = {
1329
- /**
1330
- * Creates a validator that validates the input has properties that pass their respective
1331
- * validators.
1332
- *
1333
- * @param propertyValidators
1334
- */
1335
- properties(propertyValidators) {
1336
- const propertiesDescriptions = [];
1337
- const keys = ownKeys(propertyValidators);
1338
- for (const key of keys) {
1339
- const validator2 = propertyValidators[key];
1340
- propertiesDescriptions.push(
1341
- substitute(locale9.prop, {
1342
- key: String(key) + (validator2.options.optional ? "?" : ""),
1343
- value: validator2.description
1344
- })
1345
- );
1346
- }
1347
- const description = substitute(locale9.extend, {
1348
- body: propertiesDescriptions.join(locale9.propSeparator).split("\n").map((line) => locale9.indent + line).join("\n")
1349
- });
1350
- const validator = createDeepValidator(
1351
- description,
1352
- (input, options, path) => {
1353
- const errors = [];
1354
- for (const key of keys) {
1355
- const validator2 = propertyValidators[key];
1356
- if (key in input) {
1357
- const value = input[key];
1358
- errors.push(
1359
- ...validator2.validate(
1360
- value,
1361
- options,
1362
- path.concat(String(key))
1363
- )
1364
- );
1365
- } else {
1366
- if (!validator2.options.optional) {
1367
- errors.push({
1368
- message: substitute(locale9.required, { key }),
1369
- path: path.concat(String(key))
1370
- });
1371
- }
1372
- }
1373
- if (!options.all && errors.length) return errors;
1374
- }
1375
- return errors;
1376
- }
1377
- );
1378
- return merge(validator, {
1379
- partial() {
1380
- const optionalPropertyValidators = {};
1381
- for (const key of keys) {
1382
- optionalPropertyValidators[key] = propertyValidators[key].optional();
1383
- }
1384
- return objectValidators.properties(
1385
- optionalPropertyValidators
1386
- );
1387
- },
1388
- partialDeep() {
1389
- const optionalPropertyValidators = {};
1390
- for (const key of keys) {
1391
- optionalPropertyValidators[key] = maybeToDeepPartial(
1392
- propertyValidators[key].optional()
1393
- );
1394
- }
1395
- return objectValidators.properties(
1396
- optionalPropertyValidators
1397
- );
1398
- }
1399
- });
1400
- }
1401
- };
1402
- var _ObjectSchema = class _ObjectSchema2 extends ValueSchema {
1403
- /**
1404
- * The base Object validator validating that the input is an object.
1405
- */
1406
- static get base() {
1407
- if (this._base == null)
1408
- this._base = new _ObjectSchema2(typeOfValidators.object);
1409
- return this._base;
1410
- }
1411
- /**
1412
- * Creates a validator that validates the input has properties that pass their respective
1413
- * validators.
1414
- *
1415
- * @param propertyValidators
1416
- */
1417
- extend(propertyValidators) {
1418
- return this.chain(objectValidators.properties(propertyValidators));
1419
- }
1420
- /**
1421
- * Allows all properties to be undefined.
1422
- */
1423
- partial() {
1424
- return this.clone(maybeToPartial);
1425
- }
1426
- /**
1427
- * Allows all recursive properties to be undefined.
1428
- */
1429
- partialDeep() {
1430
- return this.clone(maybeToDeepPartial);
1431
- }
1432
- /**
1433
- * Casts the type parameter.
1434
- */
1435
- cast() {
1436
- return this;
1437
- }
1438
- };
1439
- __publicField2(_ObjectSchema, "_base", null);
1440
- var locale10 = {
1441
- notEmpty: "not empty",
1442
- minLength: "at least {value} characters",
1443
- maxLength: "at most {value} characters",
1444
- noWhitespace: "no whitespace characters",
1445
- matches: "matches {value}"
1446
- };
1447
- var stringValidators = {
1448
- /**
1449
- * Creates a validator that asserts that the input is not empty.
1450
- */
1451
- notEmpty() {
1452
- return createValidator(locale10.notEmpty, (input) => input !== "");
1453
- },
1454
- /**
1455
- * Creates a validator that asserts that the input string has at least the given minimum
1456
- * length.
1457
- *
1458
- * @param min The string must be at least this length.
1459
- */
1460
- minLength(min) {
1461
- return createValidator(
1462
- substitute(locale10.minLength, { value: min }),
1463
- (input) => input.length >= min
1464
- );
1465
- },
1466
- /**
1467
- * Creates a validator that asserts that the input string has at most the given maximum
1468
- * length.
1469
- *
1470
- * @param max The string must be at most this length.
1471
- */
1472
- maxLength(max) {
1473
- return createValidator(
1474
- substitute(locale10.maxLength, { value: max }),
1475
- (input) => input.length <= max
1476
- );
1477
- },
1478
- /**
1479
- * Creates a validator that asserts that the input string has no whitespace characters.
1480
- * Whitespace characters include space, new line, carriage return, and tab.
1481
- */
1482
- noWhitespace() {
1483
- return createValidator(
1484
- locale10.noWhitespace,
1485
- (input) => input.search(/\s/g) === -1
1486
- );
1487
- },
1488
- /**
1489
- * Creates a validator that asserts that the input string matches the given regex.
1490
- * @param regex
1491
- */
1492
- matches(regex) {
1493
- return createValidator(
1494
- substitute(locale10.matches, { value: regex.toString() }),
1495
- (input) => {
1496
- return regex.test(input);
1497
- }
1498
- );
1499
- }
1500
- };
1501
- var _StringSchema = class _StringSchema2 extends ValueSchema {
1502
- /**
1503
- * The base SetSchema instance validating that the input is a Set.
1504
- */
1505
- static get base() {
1506
- if (this._base == null)
1507
- this._base = new _StringSchema2(typeOfValidators.string);
1508
- return this._base;
1509
- }
1510
- /**
1511
- * Creates a validator that asserts that the input is not empty.
1512
- */
1513
- notEmpty() {
1514
- return this.chain(stringValidators.notEmpty());
1515
- }
1516
- /**
1517
- * Creates a validator that asserts that the input string has at least the given minimum
1518
- * length.
1519
- *
1520
- * @param min The string must be at least this length.
1521
- */
1522
- minLength(min) {
1523
- return this.chain(stringValidators.minLength(min));
1524
- }
1525
- /**
1526
- * Creates a validator that asserts that the input string has at most the given maximum
1527
- * length.
1528
- *
1529
- * @param max The string must be at most this length.
1530
- */
1531
- maxLength(max) {
1532
- return this.chain(stringValidators.maxLength(max));
1533
- }
1534
- /**
1535
- * Creates a validator that asserts that the input string has no whitespace characters.
1536
- * Whitespace characters include space, new line, carriage return, and tab.
1537
- */
1538
- noWhitespace() {
1539
- return this.chain(stringValidators.noWhitespace());
1540
- }
1541
- /**
1542
- * Creates a validator that asserts that the input string matches the given regex.
1543
- * @param regex
1544
- */
1545
- matches(regex) {
1546
- return this.chain(stringValidators.matches(regex));
1547
- }
1548
- };
1549
- __publicField2(_StringSchema, "_base", null);
1550
- var StringSchema = _StringSchema;
1551
- var locale11 = {
1552
- record: "{ [key: {key}]: {value} }"
1553
- };
1554
- var recordValidators = {
1555
- /**
1556
- * Returns a validator that asserts that the object's own enumerable properties has keys and
1557
- * values that match their respective validators.
1558
- *
1559
- * Prototype members are not included.
1560
- * Numeric keys are validated as strings. For example the object `{ [0]: 1 }` will be passed
1561
- * to the key validator as '0'.
1562
- *
1563
- * @param keyValidator Validates each key.
1564
- * @param valueValidator Validates each value.
1565
- */
1566
- record(keyValidator, valueValidator) {
1567
- return createDeepValidator(
1568
- substitute(locale11.record, {
1569
- key: keyValidator.description,
1570
- value: valueValidator.description
1571
- }),
1572
- (input, options, path) => {
1573
- const errors = [];
1574
- for (const key of ownKeys(input)) {
1575
- const keyStr = String(key);
1576
- errors.push(
1577
- ...keyValidator.validate(
1578
- key,
1579
- options,
1580
- path.concat(`[${keyStr}]`)
1581
- )
1582
- );
1583
- if (!options.all && errors.length) return errors;
1584
- const value = input[key];
1585
- errors.push(
1586
- ...valueValidator.validate(
1587
- value,
1588
- options,
1589
- path.concat(keyStr)
1590
- )
1591
- );
1592
- if (!options.all && errors.length) return errors;
1593
- }
1594
- return errors;
1595
- }
1596
- );
1597
- }
1598
- };
1599
- var _RecordSchema = class _RecordSchema2 extends ValueSchema {
1600
- /**
1601
- * The base Object validator validating that the input is an object.
1602
- */
1603
- static get base() {
1604
- if (this._base == null)
1605
- this._base = new _RecordSchema2(typeOfValidators.object);
1606
- return this._base;
1607
- }
1608
- static get defaultKeyValidator() {
1609
- return StringSchema.base;
1610
- }
1611
- /**
1612
- * Returns a validator that asserts that the object's own enumerable properties has keys and
1613
- * values that match their respective validators.
1614
- *
1615
- * Prototype members are not included.
1616
- * Numeric keys are validated as strings. For example the object `{ [0]: 1 }` will be passed
1617
- * to the key validator as '0'.
1618
- *
1619
- * @param keyValidator Validates each key.
1620
- * @param valueValidator Validates each value.
1621
- */
1622
- record(keyValidator, valueValidator) {
1623
- return this.chain(recordValidators.record(keyValidator, valueValidator));
1624
- }
1625
- /**
1626
- * Returns a validator that asserts that the object's own enumerable properties has
1627
- * string keys and values that match the given validator.
1628
- *
1629
- * Prototype members are not included.
1630
- *
1631
- * @param valueValidator Validates each value.
1632
- */
1633
- recordValues(valueValidator) {
1634
- return this.record(_RecordSchema2.defaultKeyValidator, valueValidator);
1635
- }
1636
- /**
1637
- * Casts to a ReadonlyRecord
1638
- */
1639
- readonly() {
1640
- return this;
1641
- }
1642
- /**
1643
- * Casts the type parameter.
1644
- */
1645
- cast() {
1646
- return this;
1647
- }
1648
- };
1649
- __publicField2(_RecordSchema, "_base", null);
1650
- var locale12 = {
1651
- isOneOf: "one of: {value}",
1652
- instanceOf: "instance of {value}",
1653
- oneOfSeparator: " | "
1654
- };
1655
- function isOneOf(...possibleValues) {
1656
- return new ValueSchema(
1657
- createValidator(
1658
- substitute(locale12.isOneOf, {
1659
- value: possibleValues.join(locale12.oneOfSeparator)
1660
- }),
1661
- (input) => possibleValues.includes(input)
1662
- )
1663
- );
1664
- }
1665
-
1666
- // src/types/EncryptionKey.ts
1667
- var encryptionMethodValidator = isOneOf(
1668
- "NONE",
1669
- "AES-128",
1670
- "SAMPLE-AES",
1671
- "SAMPLE-AES-CTR"
1672
- );
1673
-
1674
- // src/types/AlternativeRendition.ts
1675
- var renditionTypeValidator = isOneOf(
1676
- "AUDIO",
1677
- "VIDEO",
1678
- "SUBTITLES",
1679
- "CLOSED-CAPTIONS"
1680
- );
1681
-
1682
- // src/parse/parseUtil.ts
1683
- var LF = char("\n");
1684
- var CR = char("\r");
1685
- function readLine(reader) {
1686
- const line = reader.substringUntil((cc) => cc === LF || cc === CR);
1687
- if (reader.hasNext() && reader.peek === CR) reader.next();
1688
- if (reader.hasNext() && reader.peek === LF) reader.next();
1689
- return line;
1690
- }
1691
- function skipWhitespaceLine(reader) {
1692
- const start = reader.position;
1693
- reader.while((cc) => isWhitespaceChar(cc) && cc !== LF && cc !== CR);
1694
- if (!reader.hasNext() || reader.peek === LF || reader.peek === CR) {
1695
- if (reader.hasNext()) {
1696
- if (reader.peek === CR) reader.next();
1697
- if (reader.hasNext() && reader.peek === LF) reader.next();
1698
- }
1699
- return true;
1700
- }
1701
- reader.position = start;
1702
- return false;
1703
- }
1704
- function addIfPresent(obj, attrs, mappings) {
1705
- for (const [attrKey, objKey] of Object.entries(mappings)) {
1706
- if (attrs[attrKey]) {
1707
- ;
1708
- obj[objKey] = attrs[attrKey];
1709
- }
1710
- }
1711
- return obj;
1712
- }
1713
-
1714
- // src/parse/parseAttributes.ts
1715
- var EQUALS = char("=");
1716
- var COMMA = char(",");
1717
- var QUOTE = char('"');
1718
- function parseAttributes(reader) {
1719
- const attrs = {};
1720
- while (reader.hasNext() && reader.peek !== char("\n") && reader.peek !== char("\r")) {
1721
- const key = reader.substringUntilChar(EQUALS);
1722
- if (!key || !reader.hasNext()) break;
1723
- reader.next();
1724
- let value;
1725
- if (reader.peek === QUOTE) {
1726
- reader.next();
1727
- value = reader.substringUntilChar(QUOTE);
1728
- if (reader.hasNext()) reader.next();
1729
- } else {
1730
- value = reader.substringUntil(
1731
- (cc) => cc === COMMA || cc === char("\n") || cc === char("\r")
1732
- );
1733
- }
1734
- attrs[key] = value;
1735
- if (reader.hasNext() && reader.peek === COMMA) {
1736
- reader.next();
1737
- }
1738
- }
1739
- return attrs;
1740
- }
1741
-
1742
- // src/parse/parseMediaPlaylist.ts
1743
- var HLS_VARIABLE_PATTERN = /\{\$([^}]+)}/g;
1744
- var EXTM3U = "#EXTM3U";
1745
- var EXTINF = "#EXTINF:";
1746
- var EXT_X_TARGETDURATION = "#EXT-X-TARGETDURATION:";
1747
- var EXT_X_MEDIA_SEQUENCE = "#EXT-X-MEDIA-SEQUENCE:";
1748
- var EXT_X_ENDLIST = "#EXT-X-ENDLIST";
1749
- var EXT_X_PLAYLIST_TYPE = "#EXT-X-PLAYLIST-TYPE:";
1750
- var EXT_X_VERSION = "#EXT-X-VERSION:";
1751
- var EXT_X_KEY = "#EXT-X-KEY:";
1752
- var EXT_X_BYTERANGE = "#EXT-X-BYTERANGE:";
1753
- var EXT_X_DISCONTINUITY = "#EXT-X-DISCONTINUITY";
1754
- var EXT_X_PROGRAM_DATE_TIME = "#EXT-X-PROGRAM-DATE-TIME:";
1755
- var EXT_X_MAP = "#EXT-X-MAP:";
1756
- function parseMediaPlaylist(text, variables) {
1757
- const reader = new StringReader(text);
1758
- reader.white();
1759
- if (!reader.stringIf(EXTM3U)) {
1760
- reader.err("Expected #EXTM3U");
1761
- }
1762
- readLine(reader);
1763
- let version = 1;
1764
- let targetDuration = 0;
1765
- let mediaSequence = 0;
1766
- let playlistType = "LIVE";
1767
- let ended = false;
1768
- let currentKey;
1769
- let currentMap;
1770
- let pendingByteRange;
1771
- let pendingDiscontinuity = false;
1772
- let pendingDateTime;
1773
- const segments = [];
1774
- let sequenceCounter = 0;
1775
- while (reader.hasNext()) {
1776
- if (skipWhitespaceLine(reader)) continue;
1777
- const line = readLine(reader);
1778
- const trimmed = line.trim();
1779
- if (!trimmed) continue;
1780
- if (trimmed.startsWith(EXTINF)) {
1781
- const durationStr = trimmed.substring(EXTINF.length).split(",")[0];
1782
- const duration = Number(durationStr);
1783
- let uri = "";
1784
- while (reader.hasNext()) {
1785
- if (skipWhitespaceLine(reader)) continue;
1786
- const nextLine = readLine(reader).trim();
1787
- if (!nextLine.startsWith("#")) {
1788
- uri = variables ? substitute(nextLine, variables, HLS_VARIABLE_PATTERN) : nextLine;
1789
- break;
1790
- }
1791
- if (nextLine.startsWith(EXT_X_BYTERANGE)) {
1792
- const rangeStr = nextLine.substring(EXT_X_BYTERANGE.length);
1793
- pendingByteRange = parseByteRangeString(rangeStr);
1794
- } else if (nextLine === EXT_X_DISCONTINUITY) {
1795
- pendingDiscontinuity = true;
1796
- } else if (nextLine.startsWith(EXT_X_PROGRAM_DATE_TIME)) {
1797
- pendingDateTime = nextLine.substring(
1798
- EXT_X_PROGRAM_DATE_TIME.length
1799
- );
1800
- } else if (nextLine.startsWith(EXT_X_MAP)) {
1801
- const attrStr = nextLine.substring(EXT_X_MAP.length);
1802
- const attrReader = new StringReader(attrStr);
1803
- const attrs = parseAttributes(attrReader);
1804
- const mapUri = attrs["URI"];
1805
- if (mapUri) {
1806
- const byteRangeStr = attrs["BYTERANGE"];
1807
- currentMap = __spreadValues({
1808
- uri: mapUri
1809
- }, byteRangeStr && {
1810
- byteRange: parseByteRangeString(byteRangeStr)
1811
- });
1812
- }
1813
- }
1814
- }
1815
- segments.push(__spreadValues(__spreadProps(__spreadValues(__spreadValues(__spreadValues({
1816
- uri,
1817
- duration,
1818
- sequenceNumber: mediaSequence + sequenceCounter
1819
- }, currentKey && { key: currentKey }), currentMap && { map: currentMap }), pendingByteRange && { byteRange: pendingByteRange }), {
1820
- discontinuity: pendingDiscontinuity
1821
- }), pendingDateTime && { programDateTime: pendingDateTime }));
1822
- sequenceCounter++;
1823
- pendingByteRange = void 0;
1824
- pendingDiscontinuity = false;
1825
- pendingDateTime = void 0;
1826
- } else if (trimmed.startsWith(EXT_X_TARGETDURATION)) {
1827
- targetDuration = Number(
1828
- trimmed.substring(EXT_X_TARGETDURATION.length)
1829
- );
1830
- } else if (trimmed.startsWith(EXT_X_MEDIA_SEQUENCE)) {
1831
- mediaSequence = Number(
1832
- trimmed.substring(EXT_X_MEDIA_SEQUENCE.length)
1833
- );
1834
- } else if (trimmed === EXT_X_ENDLIST) {
1835
- ended = true;
1836
- } else if (trimmed.startsWith(EXT_X_PLAYLIST_TYPE)) {
1837
- const val = trimmed.substring(EXT_X_PLAYLIST_TYPE.length).trim();
1838
- if (val === "VOD" || val === "EVENT") {
1839
- playlistType = val;
1840
- }
1841
- } else if (trimmed.startsWith(EXT_X_VERSION)) {
1842
- version = Number(trimmed.substring(EXT_X_VERSION.length));
1843
- } else if (trimmed.startsWith(EXT_X_KEY)) {
1844
- const attrStr = trimmed.substring(EXT_X_KEY.length);
1845
- const attrReader = new StringReader(attrStr);
1846
- const attrs = parseAttributes(attrReader);
1847
- const method = attrs["METHOD"];
1848
- encryptionMethodValidator.assert(method);
1849
- currentKey = addIfPresent(
1850
- {
1851
- method
1852
- },
1853
- attrs,
1854
- {
1855
- URI: "uri",
1856
- IV: "iv",
1857
- KEYFORMAT: "keyFormat",
1858
- KEYFORMATVERSIONS: "keyFormatVersions"
1859
- }
1860
- );
1861
- } else if (trimmed.startsWith(EXT_X_MAP)) {
1862
- const attrStr = trimmed.substring(EXT_X_MAP.length);
1863
- const attrReader = new StringReader(attrStr);
1864
- const attrs = parseAttributes(attrReader);
1865
- const mapUri = attrs["URI"];
1866
- if (mapUri) {
1867
- const byteRangeStr = attrs["BYTERANGE"];
1868
- currentMap = __spreadValues({
1869
- uri: mapUri
1870
- }, byteRangeStr && {
1871
- byteRange: parseByteRangeString(byteRangeStr)
1872
- });
1873
- }
1874
- } else if (trimmed.startsWith(EXT_X_BYTERANGE)) {
1875
- const rangeStr = trimmed.substring(EXT_X_BYTERANGE.length);
1876
- pendingByteRange = parseByteRangeString(rangeStr);
1877
- } else if (trimmed === EXT_X_DISCONTINUITY) {
1878
- pendingDiscontinuity = true;
1879
- } else if (trimmed.startsWith(EXT_X_PROGRAM_DATE_TIME)) {
1880
- pendingDateTime = trimmed.substring(EXT_X_PROGRAM_DATE_TIME.length);
1881
- }
1882
- }
1883
- return {
1884
- version,
1885
- targetDuration,
1886
- mediaSequence,
1887
- playlistType,
1888
- ended,
1889
- segments
1890
- };
1891
- }
1892
- function parseByteRangeString(str) {
1893
- const parts = str.split("@");
1894
- return {
1895
- length: Number(parts[0]),
1896
- offset: parts.length > 1 ? Number(parts[1]) : 0
1897
- };
1898
- }
1899
-
1900
- // src/parse/parseMainPlaylist.ts
1901
- var EXTM3U2 = "#EXTM3U";
1902
- var EXT_X_STREAM_INF = "#EXT-X-STREAM-INF:";
1903
- var EXT_X_MEDIA = "#EXT-X-MEDIA:";
1904
- var EXT_X_SESSION_DATA = "#EXT-X-SESSION-DATA:";
1905
- var EXT_X_DEFINE = "#EXT-X-DEFINE:";
1906
- function parseMainPlaylist(text) {
1907
- const reader = new StringReader(text);
1908
- reader.white();
1909
- if (!reader.stringIf(EXTM3U2)) {
1910
- reader.err("Expected #EXTM3U");
1911
- }
1912
- readLine(reader);
1913
- const variants = [];
1914
- const alternativeRenditions = [];
1915
- const sessionData = [];
1916
- const defines = {};
1917
- while (reader.hasNext()) {
1918
- if (skipWhitespaceLine(reader)) continue;
1919
- const line = readLine(reader);
1920
- const trimmed = line.trim();
1921
- if (!trimmed) continue;
1922
- if (trimmed.startsWith(EXT_X_STREAM_INF)) {
1923
- const attrStr = trimmed.substring(EXT_X_STREAM_INF.length);
1924
- const attrReader = new StringReader(attrStr);
1925
- const attrs = parseAttributes(attrReader);
1926
- let uri = "";
1927
- while (reader.hasNext()) {
1928
- if (skipWhitespaceLine(reader)) continue;
1929
- uri = readLine(reader).trim();
1930
- break;
1931
- }
1932
- variants.push(
1933
- addIfPresent(
1934
- __spreadValues(__spreadValues({
1935
- bandwidth: Number(attrs["BANDWIDTH"]),
1936
- uri
1937
- }, attrs["FRAME-RATE"] && {
1938
- frameRate: Number(attrs["FRAME-RATE"])
1939
- }), attrs.RESOLUTION && parseResolution(attrs.RESOLUTION)),
1940
- attrs,
1941
- {
1942
- CODECS: "codecs",
1943
- AUDIO: "audioGroup",
1944
- VIDEO: "videoGroup",
1945
- SUBTITLES: "subtitlesGroup",
1946
- "CLOSED-CAPTIONS": "closedCaptionsGroup"
1947
- }
1948
- )
1949
- );
1950
- } else if (trimmed.startsWith(EXT_X_MEDIA)) {
1951
- const attrStr = trimmed.substring(EXT_X_MEDIA.length);
1952
- const attrReader = new StringReader(attrStr);
1953
- const attrs = parseAttributes(attrReader);
1954
- const type = attrs["TYPE"];
1955
- renditionTypeValidator.assert(type);
1956
- alternativeRenditions.push(
1957
- addIfPresent(
1958
- __spreadValues(__spreadValues({
1959
- type,
1960
- groupId: attrs["GROUP-ID"],
1961
- name: attrs["NAME"]
1962
- }, attrs["DEFAULT"] && {
1963
- default: attrs["DEFAULT"] === "YES"
1964
- }), attrs["AUTOSELECT"] && {
1965
- autoSelect: attrs["AUTOSELECT"] === "YES"
1966
- }),
1967
- attrs,
1968
- {
1969
- URI: "uri",
1970
- LANGUAGE: "language"
1971
- }
1972
- )
1973
- );
1974
- } else if (trimmed.startsWith(EXT_X_SESSION_DATA)) {
1975
- const attrStr = trimmed.substring(EXT_X_SESSION_DATA.length);
1976
- const attrReader = new StringReader(attrStr);
1977
- const attrs = parseAttributes(attrReader);
1978
- sessionData.push(
1979
- addIfPresent(
1980
- {
1981
- dataId: attrs["DATA-ID"]
1982
- },
1983
- attrs,
1984
- {
1985
- VALUE: "value",
1986
- URI: "uri",
1987
- LANGUAGE: "language"
1988
- }
1989
- )
1990
- );
1991
- } else if (trimmed.startsWith(EXT_X_DEFINE)) {
1992
- const attrStr = trimmed.substring(EXT_X_DEFINE.length);
1993
- const attrReader = new StringReader(attrStr);
1994
- const attrs = parseAttributes(attrReader);
1995
- if (attrs["NAME"] && attrs["VALUE"]) {
1996
- defines[attrs["NAME"]] = attrs["VALUE"];
1997
- }
1998
- }
1999
- }
2000
- return { variants, alternativeRenditions, sessionData, defines };
2001
- }
2002
- function parseResolution(resolution) {
2003
- const parts = resolution.split("x");
2004
- if (parts.length !== 2) {
2005
- throw new ValidationError(
2006
- "Invalid resolution format, expected WIDTHxHEIGHT"
2007
- );
2008
- }
2009
- const width = Number(parts[0]);
2010
- const height = Number(parts[1]);
2011
- if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) {
2012
- throw new ValidationError(
2013
- "Invalid resolution values, width and height must be positive integers"
2014
- );
2015
- }
2016
- return { width, height };
2017
- }
2018
-
2019
- // test/hlsTestAssets/hls_mainPlaylist.ts
2020
- var hls_mainPlaylist = `#EXTM3U
2021
- #EXT-X-VERSION:6
2022
- #EXT-X-INDEPENDENT-SEGMENTS
2023
-
2024
- #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",NAME="English",LANGUAGE="en",DEFAULT=YES,AUTOSELECT=YES,URI="audio/en.m3u8"
2025
- #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",NAME="Spanish",LANGUAGE="es",DEFAULT=NO,AUTOSELECT=NO,URI="audio/es.m3u8"
2026
- #EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="English",LANGUAGE="en",DEFAULT=YES,AUTOSELECT=YES,URI="subtitles/en.m3u8"
2027
-
2028
- #EXT-X-STREAM-INF:BANDWIDTH=1280000,CODECS="avc1.42e00a,mp4a.40.2",RESOLUTION=640x360,FRAME-RATE=29.97,AUDIO="audio",SUBTITLES="subs"
2029
- low/index.m3u8
2030
- #EXT-X-STREAM-INF:BANDWIDTH=2560000,CODECS="avc1.42e01e,mp4a.40.2",RESOLUTION=854x480,FRAME-RATE=29.97,AUDIO="audio",SUBTITLES="subs"
2031
- mid/index.m3u8
2032
- #EXT-X-STREAM-INF:BANDWIDTH=7680000,CODECS="avc1.42e01f,mp4a.40.2",RESOLUTION=1280x720,FRAME-RATE=29.97,AUDIO="audio",SUBTITLES="subs"
2033
- high/index.m3u8`;
2034
-
2035
- // test/hlsTestAssets/hls_mediaPlaylist.ts
2036
- var hls_mediaPlaylist = `#EXTM3U
2037
- #EXT-X-VERSION:3
2038
- #EXT-X-TARGETDURATION:10
2039
- #EXT-X-MEDIA-SEQUENCE:0
2040
- #EXT-X-PLAYLIST-TYPE:VOD
2041
-
2042
- #EXT-X-KEY:METHOD=AES-128,URI="https://example.com/key.bin",IV=0x99b74007b6254e4bd1c6e03631cad15b
2043
-
2044
- #EXTINF:9.009,
2045
- segment00000.ts
2046
- #EXTINF:9.009,
2047
- segment00001.ts
2048
- #EXTINF:9.009,
2049
- segment00002.ts
2050
- #EXTINF:9.009,
2051
- segment00003.ts
2052
- #EXTINF:9.009,
2053
- segment00004.ts
2054
- #EXTINF:5.005,
2055
- segment00005.ts
2056
-
2057
- #EXT-X-ENDLIST`;
2058
-
2059
- // test/hlsTestAssets/hls_mediaPlaylistWithByteRanges.ts
2060
- var hls_mediaPlaylistWithByteRanges = `#EXTM3U
2061
- #EXT-X-VERSION:4
2062
- #EXT-X-TARGETDURATION:10
2063
- #EXT-X-MEDIA-SEQUENCE:0
2064
-
2065
- #EXTINF:10.0,
2066
- #EXT-X-BYTERANGE:1000000@0
2067
- segment.ts
2068
- #EXTINF:10.0,
2069
- #EXT-X-BYTERANGE:1000000@1000000
2070
- segment.ts
2071
- #EXT-X-DISCONTINUITY
2072
- #EXTINF:10.0,
2073
- #EXT-X-BYTERANGE:1000000@2000000
2074
- segment.ts
2075
-
2076
- #EXT-X-ENDLIST`;
2077
-
2078
- // test/integ/parseHlsManifest.integ.ts
2079
- describe("HLS Parser Integration Tests", () => {
2080
- it("parses HLS main playlist test asset", () => {
2081
- const result = parseMainPlaylist(hls_mainPlaylist);
2082
- expect(result.variants.length).toBe(3);
2083
- expect(result.alternativeRenditions.length).toBe(3);
2084
- expect(result.variants[0].bandwidth).toBe(128e4);
2085
- expect(result.variants[0].uri).toBe("low/index.m3u8");
2086
- expect(result.variants[0].codecs).toBe("avc1.42e00a,mp4a.40.2");
2087
- expect(result.variants[0].width).toBe(640);
2088
- expect(result.variants[0].height).toBe(360);
2089
- const audioRenditions = result.alternativeRenditions.filter(
2090
- (r) => r.type === "AUDIO"
2091
- );
2092
- expect(audioRenditions.length).toBe(2);
2093
- expect(audioRenditions[0].name).toBe("English");
2094
- expect(audioRenditions[0].language).toBe("en");
2095
- expect(audioRenditions[0].default).toBe(true);
2096
- });
2097
- it("parses HLS media playlist test asset", () => {
2098
- const result = parseMediaPlaylist(hls_mediaPlaylist);
2099
- expect(result.version).toBe(3);
2100
- expect(result.targetDuration).toBe(10);
2101
- expect(result.mediaSequence).toBe(0);
2102
- expect(result.playlistType).toBe("VOD");
2103
- expect(result.ended).toBe(true);
2104
- expect(result.segments.length).toBe(6);
2105
- expect(result.segments[0].uri).toBe("segment00000.ts");
2106
- expect(result.segments[0].duration).toBe(9.009);
2107
- expect(result.segments[0].sequenceNumber).toBe(0);
2108
- expect(result.segments[5].duration).toBe(5.005);
2109
- });
2110
- it("parses HLS media playlist with byte ranges", () => {
2111
- var _a, _b, _c;
2112
- const result = parseMediaPlaylist(hls_mediaPlaylistWithByteRanges);
2113
- expect(result.segments.length).toBe(3);
2114
- expect((_a = result.segments[0].byteRange) == null ? void 0 : _a.length).toBe(1e6);
2115
- expect((_b = result.segments[0].byteRange) == null ? void 0 : _b.offset).toBe(0);
2116
- expect((_c = result.segments[1].byteRange) == null ? void 0 : _c.offset).toBe(1e6);
2117
- expect(result.segments[2].discontinuity).toBe(true);
2118
- });
2119
- it("keeps URIs relative in parsed results", () => {
2120
- const result = parseMainPlaylist(hls_mainPlaylist);
2121
- expect(result.variants[0].uri).toBe("low/index.m3u8");
2122
- expect(result.variants[1].uri).toBe("mid/index.m3u8");
2123
- expect(result.variants[2].uri).toBe("high/index.m3u8");
2124
- });
2125
- });
2126
- })();
2127
- //# sourceMappingURL=integ.js.map