@vertexvis/utils 0.24.5-canary.5 → 1.0.0-testing.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.
@@ -3,33 +3,36 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var tslib = require('tslib');
6
- var crypto = require('crypto');
6
+ var fastDeepEqual = require('fast-deep-equal');
7
+ var isSimpleObject = require('is-plain-object');
8
+ var uuid$1 = require('uuid');
7
9
 
8
10
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
9
11
 
10
- var crypto__default = /*#__PURE__*/_interopDefaultLegacy(crypto);
12
+ var fastDeepEqual__default = /*#__PURE__*/_interopDefaultLegacy(fastDeepEqual);
13
+ var isSimpleObject__default = /*#__PURE__*/_interopDefaultLegacy(isSimpleObject);
11
14
 
12
- /**
13
- * Adds a listener to the given `target`, and returns a promise that
14
- * resolves with the first event emitted of the given `type`.
15
- *
16
- * @param target The target to add an event listener to.
17
- * @param type The event type to listen for.
18
- * @param opts Options to pass to `addEventListener`.
19
- * @returns A promise that resolves with the first event emitted of `type`.
20
- */
21
- function once(target, type, opts) {
22
- return tslib.__awaiter(this, void 0, void 0, function () {
23
- return tslib.__generator(this, function (_a) {
24
- return [2 /*return*/, new Promise(function (resolve) {
25
- function handler(event) {
26
- target.removeEventListener(type, handler);
27
- resolve(event);
28
- }
29
- target.addEventListener(type, handler, opts);
30
- })];
31
- });
32
- });
15
+ /**
16
+ * Adds a listener to the given `target`, and returns a promise that
17
+ * resolves with the first event emitted of the given `type`.
18
+ *
19
+ * @param target The target to add an event listener to.
20
+ * @param type The event type to listen for.
21
+ * @param opts Options to pass to `addEventListener`.
22
+ * @returns A promise that resolves with the first event emitted of `type`.
23
+ */
24
+ function once(target, type, opts) {
25
+ return tslib.__awaiter(this, void 0, Promise, function () {
26
+ return tslib.__generator(this, function (_a) {
27
+ return [2 /*return*/, new Promise(function (resolve) {
28
+ function handler(event) {
29
+ target.removeEventListener(type, handler);
30
+ resolve(event);
31
+ }
32
+ target.addEventListener(type, handler, opts);
33
+ })];
34
+ });
35
+ });
33
36
  }
34
37
 
35
38
  var eventTargets = /*#__PURE__*/Object.freeze({
@@ -37,206 +40,210 @@ var eventTargets = /*#__PURE__*/Object.freeze({
37
40
  once: once
38
41
  });
39
42
 
40
- /**
41
- * Converts an async generator to an array of results.
42
- *
43
- * @param generator The generator to convert.
44
- * @returns A promise that resolves with an array of results yielded by the
45
- * generator.
46
- */
47
- function asArray(generator) {
48
- var generator_1, generator_1_1;
49
- var e_1, _a;
50
- return tslib.__awaiter(this, void 0, void 0, function () {
51
- var res, next, e_1_1;
52
- return tslib.__generator(this, function (_b) {
53
- switch (_b.label) {
54
- case 0:
55
- res = [];
56
- _b.label = 1;
57
- case 1:
58
- _b.trys.push([1, 6, 7, 12]);
59
- generator_1 = tslib.__asyncValues(generator);
60
- _b.label = 2;
61
- case 2: return [4 /*yield*/, generator_1.next()];
62
- case 3:
63
- if (!(generator_1_1 = _b.sent(), !generator_1_1.done)) return [3 /*break*/, 5];
64
- next = generator_1_1.value;
65
- res.push(next);
66
- _b.label = 4;
67
- case 4: return [3 /*break*/, 2];
68
- case 5: return [3 /*break*/, 12];
69
- case 6:
70
- e_1_1 = _b.sent();
71
- e_1 = { error: e_1_1 };
72
- return [3 /*break*/, 12];
73
- case 7:
74
- _b.trys.push([7, , 10, 11]);
75
- if (!(generator_1_1 && !generator_1_1.done && (_a = generator_1.return))) return [3 /*break*/, 9];
76
- return [4 /*yield*/, _a.call(generator_1)];
77
- case 8:
78
- _b.sent();
79
- _b.label = 9;
80
- case 9: return [3 /*break*/, 11];
81
- case 10:
82
- if (e_1) throw e_1.error;
83
- return [7 /*endfinally*/];
84
- case 11: return [7 /*endfinally*/];
85
- case 12: return [2 /*return*/, res];
86
- }
87
- });
88
- });
89
- }
90
- function delay() {
91
- var args = [];
92
- for (var _i = 0; _i < arguments.length; _i++) {
93
- args[_i] = arguments[_i];
94
- }
95
- return tslib.__awaiter(this, void 0, void 0, function () {
96
- var ms, promise, delay_1;
97
- return tslib.__generator(this, function (_a) {
98
- switch (_a.label) {
99
- case 0:
100
- ms = args[0];
101
- if (!(typeof ms === 'number')) return [3 /*break*/, 4];
102
- promise = args[1];
103
- delay_1 = new Promise(function (resolve) { return setTimeout(resolve, ms); });
104
- if (!(promise != null)) return [3 /*break*/, 2];
105
- return [4 /*yield*/, delay_1];
106
- case 1:
107
- _a.sent();
108
- return [2 /*return*/, promise];
109
- case 2: return [2 /*return*/, delay_1];
110
- case 3: return [3 /*break*/, 5];
111
- case 4: return [2 /*return*/, Promise.reject(new TypeError('First argument to `delay` must be a number'))];
112
- case 5: return [2 /*return*/];
113
- }
114
- });
115
- });
116
- }
117
- function timeout() {
118
- var args = [];
119
- for (var _i = 0; _i < arguments.length; _i++) {
120
- args[_i] = arguments[_i];
121
- }
122
- return tslib.__awaiter(this, void 0, void 0, function () {
123
- var ms, promise, timer_1, timeout_1, res;
124
- return tslib.__generator(this, function (_a) {
125
- switch (_a.label) {
126
- case 0:
127
- ms = args[0];
128
- if (!(typeof ms === 'number')) return [3 /*break*/, 4];
129
- promise = args[1];
130
- timeout_1 = new Promise(function (_, reject) {
131
- timer_1 = setTimeout(function () { return reject(new Error("Promise timed out after ".concat(ms, "ms"))); }, ms);
132
- });
133
- if (!(promise != null)) return [3 /*break*/, 2];
134
- return [4 /*yield*/, Promise.race([promise, timeout_1])];
135
- case 1:
136
- res = _a.sent();
137
- clearTimeout(timer_1);
138
- return [2 /*return*/, res];
139
- case 2: return [2 /*return*/, timeout_1];
140
- case 3: return [3 /*break*/, 5];
141
- case 4: return [2 /*return*/, Promise.reject('First argument to `timeout` must be a number')];
142
- case 5: return [2 /*return*/];
143
- }
144
- });
145
- });
146
- }
147
- /**
148
- * Executes and reattempts execution of an asynchronous function if it throws an
149
- * error. By default, this function will only retry once and reexecute
150
- * immediately after the previous execution throws. You can configure the number
151
- * of retry attempts and delays with the `maxRetries` and `delaysInMs` options.
152
- *
153
- * The `delaysInMs` is an array of delays in milliseconds for each retry
154
- * attempt. If there are more retry attempts than delays, the last delay will be
155
- * used.
156
- *
157
- * @param process The process to execute.
158
- * @param opts Options to configure retry behavior.
159
- * @returns A promise that resolves with a successful value, or the original
160
- * rejected value if the process fails.
161
- */
162
- function retry(process, opts) {
163
- if (opts === void 0) { opts = {}; }
164
- return tslib.__awaiter(this, void 0, void 0, function () {
165
- function execute(attempt, process, opts) {
166
- return tslib.__awaiter(this, void 0, void 0, function () {
167
- var _a, delaysInMs, _b, maxRetries, delayInMs, e_2;
168
- return tslib.__generator(this, function (_c) {
169
- switch (_c.label) {
170
- case 0:
171
- _a = opts.delaysInMs, delaysInMs = _a === void 0 ? [] : _a, _b = opts.maxRetries, maxRetries = _b === void 0 ? 1 : _b;
172
- _c.label = 1;
173
- case 1:
174
- _c.trys.push([1, 4, , 8]);
175
- delayInMs = attempt === 0 || delaysInMs.length === 0
176
- ? 0
177
- : delaysInMs[Math.min(attempt - 1, delaysInMs.length - 1)];
178
- return [4 /*yield*/, delay(delayInMs)];
179
- case 2:
180
- _c.sent();
181
- return [4 /*yield*/, process()];
182
- case 3: return [2 /*return*/, _c.sent()];
183
- case 4:
184
- e_2 = _c.sent();
185
- if (!(attempt < maxRetries)) return [3 /*break*/, 6];
186
- return [4 /*yield*/, execute(attempt + 1, process, opts)];
187
- case 5: return [2 /*return*/, _c.sent()];
188
- case 6: throw e_2;
189
- case 7: return [3 /*break*/, 8];
190
- case 8: return [2 /*return*/];
191
- }
192
- });
193
- });
194
- }
195
- return tslib.__generator(this, function (_a) {
196
- return [2 /*return*/, execute(0, process, opts)];
197
- });
198
- });
199
- }
200
- /**
201
- * Returns a promise that either resolves with the result of `promise`, or a
202
- * value that indicates the execution was aborted.
203
- *
204
- * **Note:** Because Promises in JS cannot be canceled, an abort signal will not
205
- * cancel the execution of the promise.
206
- *
207
- * @param signal A signal that communicates the process should be aborted.
208
- * @param promise A promise who's value will be returned if not aborted.
209
- * @returns A value indicating if the process was aborted, or the value of
210
- * `promise`.
211
- */
212
- function abort(signal, promise) {
213
- return tslib.__awaiter(this, void 0, void 0, function () {
214
- var controller, pendingAbort, result;
215
- return tslib.__generator(this, function (_a) {
216
- switch (_a.label) {
217
- case 0:
218
- controller = new AbortController();
219
- pendingAbort = once(signal, 'abort', { signal: controller.signal });
220
- return [4 /*yield*/, Promise.race([promise, pendingAbort])];
221
- case 1:
222
- result = _a.sent();
223
- if (isAbortEvent(result)) {
224
- return [2 /*return*/, { aborted: true }];
225
- }
226
- else {
227
- controller.abort();
228
- return [2 /*return*/, { aborted: false, result: result }];
229
- }
230
- }
231
- });
232
- });
233
- }
234
- function isAbortEvent(obj) {
235
- if (obj instanceof Event) {
236
- return obj.type === 'abort';
237
- }
238
- else
239
- return false;
43
+ /**
44
+ * Converts an async generator to an array of results.
45
+ *
46
+ * @param generator The generator to convert.
47
+ * @returns A promise that resolves with an array of results yielded by the
48
+ * generator.
49
+ */
50
+ function asArray(generator) {
51
+ return tslib.__awaiter(this, void 0, Promise, function () {
52
+ var res, next, e_1_1;
53
+ var _a, generator_1, generator_1_1;
54
+ var _b, e_1, _c, _d;
55
+ return tslib.__generator(this, function (_e) {
56
+ switch (_e.label) {
57
+ case 0:
58
+ res = [];
59
+ _e.label = 1;
60
+ case 1:
61
+ _e.trys.push([1, 6, 7, 12]);
62
+ _a = true, generator_1 = tslib.__asyncValues(generator);
63
+ _e.label = 2;
64
+ case 2: return [4 /*yield*/, generator_1.next()];
65
+ case 3:
66
+ if (!(generator_1_1 = _e.sent(), _b = generator_1_1.done, !_b)) return [3 /*break*/, 5];
67
+ _d = generator_1_1.value;
68
+ _a = false;
69
+ next = _d;
70
+ res.push(next);
71
+ _e.label = 4;
72
+ case 4:
73
+ _a = true;
74
+ return [3 /*break*/, 2];
75
+ case 5: return [3 /*break*/, 12];
76
+ case 6:
77
+ e_1_1 = _e.sent();
78
+ e_1 = { error: e_1_1 };
79
+ return [3 /*break*/, 12];
80
+ case 7:
81
+ _e.trys.push([7, , 10, 11]);
82
+ if (!(!_a && !_b && (_c = generator_1.return))) return [3 /*break*/, 9];
83
+ return [4 /*yield*/, _c.call(generator_1)];
84
+ case 8:
85
+ _e.sent();
86
+ _e.label = 9;
87
+ case 9: return [3 /*break*/, 11];
88
+ case 10:
89
+ if (e_1) throw e_1.error;
90
+ return [7 /*endfinally*/];
91
+ case 11: return [7 /*endfinally*/];
92
+ case 12: return [2 /*return*/, res];
93
+ }
94
+ });
95
+ });
96
+ }
97
+ function delay() {
98
+ var args = [];
99
+ for (var _i = 0; _i < arguments.length; _i++) {
100
+ args[_i] = arguments[_i];
101
+ }
102
+ return tslib.__awaiter(this, void 0, Promise, function () {
103
+ var ms, promise, delay_1;
104
+ return tslib.__generator(this, function (_a) {
105
+ switch (_a.label) {
106
+ case 0:
107
+ ms = args[0];
108
+ if (!(typeof ms === 'number')) return [3 /*break*/, 4];
109
+ promise = args[1];
110
+ delay_1 = new Promise(function (resolve) { return setTimeout(resolve, ms); });
111
+ if (!(promise != null)) return [3 /*break*/, 2];
112
+ return [4 /*yield*/, delay_1];
113
+ case 1:
114
+ _a.sent();
115
+ return [2 /*return*/, promise];
116
+ case 2: return [2 /*return*/, delay_1];
117
+ case 3: return [3 /*break*/, 5];
118
+ case 4: return [2 /*return*/, Promise.reject(new TypeError('First argument to `delay` must be a number'))];
119
+ case 5: return [2 /*return*/];
120
+ }
121
+ });
122
+ });
123
+ }
124
+ function timeout() {
125
+ var args = [];
126
+ for (var _i = 0; _i < arguments.length; _i++) {
127
+ args[_i] = arguments[_i];
128
+ }
129
+ return tslib.__awaiter(this, void 0, Promise, function () {
130
+ var ms, promise, timer_1, timeout_1, res;
131
+ return tslib.__generator(this, function (_a) {
132
+ switch (_a.label) {
133
+ case 0:
134
+ ms = args[0];
135
+ if (!(typeof ms === 'number')) return [3 /*break*/, 4];
136
+ promise = args[1];
137
+ timeout_1 = new Promise(function (_, reject) {
138
+ timer_1 = setTimeout(function () { return reject(new Error("Promise timed out after ".concat(ms, "ms"))); }, ms);
139
+ });
140
+ if (!(promise != null)) return [3 /*break*/, 2];
141
+ return [4 /*yield*/, Promise.race([promise, timeout_1])];
142
+ case 1:
143
+ res = _a.sent();
144
+ clearTimeout(timer_1);
145
+ return [2 /*return*/, res];
146
+ case 2: return [2 /*return*/, timeout_1];
147
+ case 3: return [3 /*break*/, 5];
148
+ case 4: return [2 /*return*/, Promise.reject('First argument to `timeout` must be a number')];
149
+ case 5: return [2 /*return*/];
150
+ }
151
+ });
152
+ });
153
+ }
154
+ /**
155
+ * Executes and reattempts execution of an asynchronous function if it throws an
156
+ * error. By default, this function will only retry once and reexecute
157
+ * immediately after the previous execution throws. You can configure the number
158
+ * of retry attempts and delays with the `maxRetries` and `delaysInMs` options.
159
+ *
160
+ * The `delaysInMs` is an array of delays in milliseconds for each retry
161
+ * attempt. If there are more retry attempts than delays, the last delay will be
162
+ * used.
163
+ *
164
+ * @param process The process to execute.
165
+ * @param opts Options to configure retry behavior.
166
+ * @returns A promise that resolves with a successful value, or the original
167
+ * rejected value if the process fails.
168
+ */
169
+ function retry(process_1) {
170
+ return tslib.__awaiter(this, arguments, Promise, function (process, opts) {
171
+ function execute(attempt, process, opts) {
172
+ return tslib.__awaiter(this, void 0, Promise, function () {
173
+ var _a, delaysInMs, _b, maxRetries, delayInMs, e_2;
174
+ return tslib.__generator(this, function (_c) {
175
+ switch (_c.label) {
176
+ case 0:
177
+ _a = opts.delaysInMs, delaysInMs = _a === void 0 ? [] : _a, _b = opts.maxRetries, maxRetries = _b === void 0 ? 1 : _b;
178
+ _c.label = 1;
179
+ case 1:
180
+ _c.trys.push([1, 4, , 8]);
181
+ delayInMs = attempt === 0 || delaysInMs.length === 0
182
+ ? 0
183
+ : delaysInMs[Math.min(attempt - 1, delaysInMs.length - 1)];
184
+ return [4 /*yield*/, delay(delayInMs)];
185
+ case 2:
186
+ _c.sent();
187
+ return [4 /*yield*/, process()];
188
+ case 3: return [2 /*return*/, _c.sent()];
189
+ case 4:
190
+ e_2 = _c.sent();
191
+ if (!(attempt < maxRetries)) return [3 /*break*/, 6];
192
+ return [4 /*yield*/, execute(attempt + 1, process, opts)];
193
+ case 5: return [2 /*return*/, _c.sent()];
194
+ case 6: throw e_2;
195
+ case 7: return [3 /*break*/, 8];
196
+ case 8: return [2 /*return*/];
197
+ }
198
+ });
199
+ });
200
+ }
201
+ if (opts === void 0) { opts = {}; }
202
+ return tslib.__generator(this, function (_a) {
203
+ return [2 /*return*/, execute(0, process, opts)];
204
+ });
205
+ });
206
+ }
207
+ /**
208
+ * Returns a promise that either resolves with the result of `promise`, or a
209
+ * value that indicates the execution was aborted.
210
+ *
211
+ * **Note:** Because Promises in JS cannot be canceled, an abort signal will not
212
+ * cancel the execution of the promise.
213
+ *
214
+ * @param signal A signal that communicates the process should be aborted.
215
+ * @param promise A promise who's value will be returned if not aborted.
216
+ * @returns A value indicating if the process was aborted, or the value of
217
+ * `promise`.
218
+ */
219
+ function abort(signal, promise) {
220
+ return tslib.__awaiter(this, void 0, Promise, function () {
221
+ var controller, pendingAbort, result;
222
+ return tslib.__generator(this, function (_a) {
223
+ switch (_a.label) {
224
+ case 0:
225
+ controller = new AbortController();
226
+ pendingAbort = once(signal, 'abort', { signal: controller.signal });
227
+ return [4 /*yield*/, Promise.race([promise, pendingAbort])];
228
+ case 1:
229
+ result = _a.sent();
230
+ if (isAbortEvent(result)) {
231
+ return [2 /*return*/, { aborted: true }];
232
+ }
233
+ else {
234
+ controller.abort();
235
+ return [2 /*return*/, { aborted: false, result: result }];
236
+ }
237
+ }
238
+ });
239
+ });
240
+ }
241
+ function isAbortEvent(obj) {
242
+ if (obj instanceof Event) {
243
+ return obj.type === 'abort';
244
+ }
245
+ else
246
+ return false;
240
247
  }
241
248
 
242
249
  var async = /*#__PURE__*/Object.freeze({
@@ -248,48 +255,48 @@ var async = /*#__PURE__*/Object.freeze({
248
255
  abort: abort
249
256
  });
250
257
 
251
- /**
252
- * Returns a new `BinaryReader` for an `ArrayBuffer`.
253
- */
254
- var fromArrayBuffer = function (buffer) {
255
- return { offset: 0, data: new DataView(buffer) };
256
- };
257
- /**
258
- * Returns a `BinaryReader` that contains the read Int32 value at the given
259
- * reader's offset. The returned reader will have its offset adjusted so it can
260
- * be passed to the next helper.
261
- */
262
- var readInt32 = function (reader) {
263
- var value = reader.data.getInt32(reader.offset);
264
- return tslib.__assign(tslib.__assign({}, reader), { offset: reader.offset + 4, value: value });
265
- };
266
- /**
267
- * Returns a `BinaryReader` that contains the read UTF-8 string at the given
268
- * reader's offset. The returned reader will have its offset adjusted so it can
269
- * be passed to the next helper.
270
- */
271
- var readUtf8String = function (length, reader) {
272
- var value = String.fromCharCode.apply(null, Array.from(new Uint8Array(reader.data.buffer, reader.offset, length)));
273
- return tslib.__assign(tslib.__assign({}, reader), { offset: reader.offset + length, value: value });
274
- };
275
- /**
276
- * Returns a `BinaryReader` that contains the a signed `Int8Array` start from
277
- * the given reader's offset to the given length. The returned reader will have
278
- * its offset adjusted so it can be passed to the next helper.
279
- */
280
- var readInt8Array = function (length, reader) {
281
- var value = new Int8Array(reader.data.buffer, reader.offset, length);
282
- return tslib.__assign(tslib.__assign({}, reader), { offset: reader.offset + length, value: value });
283
- };
284
- /**
285
- * Returns a `BinaryReader` that contains the a signed `Int8Array` sliced from
286
- * the start of the reader's offset to offset + length. The new reader value has
287
- * an offset of zero, so downstream operations will not bee effected by the
288
- * previous offset
289
- */
290
- var sliceInt8Array = function (length, reader) {
291
- var value = new Int8Array(reader.data.buffer.slice(reader.offset, length + reader.offset));
292
- return tslib.__assign(tslib.__assign({}, reader), { offset: 0, value: value });
258
+ /**
259
+ * Returns a new `BinaryReader` for an `ArrayBuffer`.
260
+ */
261
+ var fromArrayBuffer = function (buffer) {
262
+ return { offset: 0, data: new DataView(buffer) };
263
+ };
264
+ /**
265
+ * Returns a `BinaryReader` that contains the read Int32 value at the given
266
+ * reader's offset. The returned reader will have its offset adjusted so it can
267
+ * be passed to the next helper.
268
+ */
269
+ var readInt32 = function (reader) {
270
+ var value = reader.data.getInt32(reader.offset);
271
+ return tslib.__assign(tslib.__assign({}, reader), { offset: reader.offset + 4, value: value });
272
+ };
273
+ /**
274
+ * Returns a `BinaryReader` that contains the read UTF-8 string at the given
275
+ * reader's offset. The returned reader will have its offset adjusted so it can
276
+ * be passed to the next helper.
277
+ */
278
+ var readUtf8String = function (length, reader) {
279
+ var value = String.fromCharCode.apply(null, Array.from(new Uint8Array(reader.data.buffer, reader.offset, length)));
280
+ return tslib.__assign(tslib.__assign({}, reader), { offset: reader.offset + length, value: value });
281
+ };
282
+ /**
283
+ * Returns a `BinaryReader` that contains the a signed `Int8Array` start from
284
+ * the given reader's offset to the given length. The returned reader will have
285
+ * its offset adjusted so it can be passed to the next helper.
286
+ */
287
+ var readInt8Array = function (length, reader) {
288
+ var value = new Int8Array(reader.data.buffer, reader.offset, length);
289
+ return tslib.__assign(tslib.__assign({}, reader), { offset: reader.offset + length, value: value });
290
+ };
291
+ /**
292
+ * Returns a `BinaryReader` that contains the a signed `Int8Array` sliced from
293
+ * the start of the reader's offset to offset + length. The new reader value has
294
+ * an offset of zero, so downstream operations will not bee effected by the
295
+ * previous offset
296
+ */
297
+ var sliceInt8Array = function (length, reader) {
298
+ var value = new Int8Array(reader.data.buffer.slice(reader.offset, length + reader.offset));
299
+ return tslib.__assign(tslib.__assign({}, reader), { offset: 0, value: value });
293
300
  };
294
301
 
295
302
  var binaryReader = /*#__PURE__*/Object.freeze({
@@ -301,85 +308,85 @@ var binaryReader = /*#__PURE__*/Object.freeze({
301
308
  sliceInt8Array: sliceInt8Array
302
309
  });
303
310
 
304
- var rgbRegex = /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/;
305
- var rgbaRegex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(.+)\s*\)/;
306
- var hexRegex = /^(#|0x)?([A-Fa-f0-9]{6})$/;
307
- /**
308
- * Constructs a new color with the given red, green, blue and alpha values. If
309
- * alpha is undefined, defaults to 1.
310
- */
311
- var create$2 = function (r, g, b, a) {
312
- if (a === void 0) { a = 255; }
313
- return { r: r, g: g, b: b, a: a };
314
- };
315
- /**
316
- * Converts a numeric color value containing red, green and blue values to a
317
- * `Color`. The alpha channel will default to fully opaque.
318
- */
319
- var fromNumber = function (num) {
320
- // tslint:disable:no-bitwise
321
- var normalized = num & 0xffffff;
322
- return create$2((normalized >> 16) & 0xff, (normalized >> 8) & 0xff, normalized & 0xff);
323
- // tslint:enable:no-bitwise
324
- };
325
- /**
326
- * Returns a `Color` from a hex string, or undefined if the color string cannot
327
- * be parsed. Supports hex strings in the format of `"#00FF00"`, `"0x00FF00"` or
328
- * `"00FF00"`.
329
- */
330
- var fromHexString = function (str) {
331
- var match = hexRegex.exec(str);
332
- if (match != null) {
333
- return fromNumber(parseInt(match[2], 16));
334
- }
335
- };
336
- /**
337
- * Creates a `Color` from a CSS color value. This function currently only
338
- * supports `rgb(255, 255, 255)`, `rgba(255, 255, 255, 0.5)` or `"#FFFFFF"`.
339
- * Returns `undefined` if the color cannot be parsed.
340
- */
341
- var fromCss = function (css) {
342
- var rgbMatch = rgbRegex.exec(css);
343
- if (rgbMatch != null) {
344
- return create$2(parseInt(rgbMatch[1]), parseInt(rgbMatch[2]), parseInt(rgbMatch[3]));
345
- }
346
- var rgbaMatch = rgbaRegex.exec(css);
347
- if (rgbaMatch != null) {
348
- return create$2(parseInt(rgbaMatch[1]), parseInt(rgbaMatch[2]), parseInt(rgbaMatch[3]), Math.floor(parseFloat(rgbaMatch[4]) * 255));
349
- }
350
- if (hexRegex.test(css)) {
351
- return fromHexString(css);
352
- }
353
- };
354
- /**
355
- * Converts an array of four values to a `Color`. The sequence of the array is
356
- * expected to be `[r, g, b]` or `[r, g, b, a]`.
357
- */
358
- var fromArray = function (rgba) {
359
- return create$2(rgba[0], rgba[1], rgba[2], rgba[3]);
360
- };
361
- /**
362
- * Returns `true` if the color's alpha channel is 0.
363
- */
364
- var isInvisible = function (color) {
365
- return color.a === 0;
366
- };
367
- /**
368
- * Returns `true` if the alpha channel of this color is fully opaque (255).
369
- */
370
- var isOpaque = function (color) {
371
- return color.a === 255;
372
- };
373
- /**
374
- * Converts a `Color` to a hex string. The returned string will be prefixed with
375
- * `#`.
376
- */
377
- var toHexString = function (color) {
378
- return "#".concat(componentToHex(color.r)).concat(componentToHex(color.g)).concat(componentToHex(color.b));
379
- };
380
- var componentToHex = function (num) {
381
- var hex = num.toString(16);
382
- return hex.length === 1 ? '0' + hex : hex;
311
+ var rgbRegex = /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/;
312
+ var rgbaRegex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(.+)\s*\)/;
313
+ var hexRegex = /^(#|0x)?([A-Fa-f0-9]{6})$/;
314
+ /**
315
+ * Constructs a new color with the given red, green, blue and alpha values. If
316
+ * alpha is undefined, defaults to 1.
317
+ */
318
+ var create$2 = function (r, g, b, a) {
319
+ if (a === void 0) { a = 255; }
320
+ return { r: r, g: g, b: b, a: a };
321
+ };
322
+ /**
323
+ * Converts a numeric color value containing red, green and blue values to a
324
+ * `Color`. The alpha channel will default to fully opaque.
325
+ */
326
+ var fromNumber = function (num) {
327
+ // tslint:disable:no-bitwise
328
+ var normalized = num & 0xffffff;
329
+ return create$2((normalized >> 16) & 0xff, (normalized >> 8) & 0xff, normalized & 0xff);
330
+ // tslint:enable:no-bitwise
331
+ };
332
+ /**
333
+ * Returns a `Color` from a hex string, or undefined if the color string cannot
334
+ * be parsed. Supports hex strings in the format of `"#00FF00"`, `"0x00FF00"` or
335
+ * `"00FF00"`.
336
+ */
337
+ var fromHexString = function (str) {
338
+ var match = hexRegex.exec(str);
339
+ if (match != null) {
340
+ return fromNumber(parseInt(match[2], 16));
341
+ }
342
+ };
343
+ /**
344
+ * Creates a `Color` from a CSS color value. This function currently only
345
+ * supports `rgb(255, 255, 255)`, `rgba(255, 255, 255, 0.5)` or `"#FFFFFF"`.
346
+ * Returns `undefined` if the color cannot be parsed.
347
+ */
348
+ var fromCss = function (css) {
349
+ var rgbMatch = rgbRegex.exec(css);
350
+ if (rgbMatch != null) {
351
+ return create$2(parseInt(rgbMatch[1]), parseInt(rgbMatch[2]), parseInt(rgbMatch[3]));
352
+ }
353
+ var rgbaMatch = rgbaRegex.exec(css);
354
+ if (rgbaMatch != null) {
355
+ return create$2(parseInt(rgbaMatch[1]), parseInt(rgbaMatch[2]), parseInt(rgbaMatch[3]), Math.floor(parseFloat(rgbaMatch[4]) * 255));
356
+ }
357
+ if (hexRegex.test(css)) {
358
+ return fromHexString(css);
359
+ }
360
+ };
361
+ /**
362
+ * Converts an array of four values to a `Color`. The sequence of the array is
363
+ * expected to be `[r, g, b]` or `[r, g, b, a]`.
364
+ */
365
+ var fromArray = function (rgba) {
366
+ return create$2(rgba[0], rgba[1], rgba[2], rgba[3]);
367
+ };
368
+ /**
369
+ * Returns `true` if the color's alpha channel is 0.
370
+ */
371
+ var isInvisible = function (color) {
372
+ return color.a === 0;
373
+ };
374
+ /**
375
+ * Returns `true` if the alpha channel of this color is fully opaque (255).
376
+ */
377
+ var isOpaque = function (color) {
378
+ return color.a === 255;
379
+ };
380
+ /**
381
+ * Converts a `Color` to a hex string. The returned string will be prefixed with
382
+ * `#`.
383
+ */
384
+ var toHexString = function (color) {
385
+ return "#".concat(componentToHex(color.r)).concat(componentToHex(color.g)).concat(componentToHex(color.b));
386
+ };
387
+ var componentToHex = function (num) {
388
+ var hex = num.toString(16);
389
+ return hex.length === 1 ? '0' + hex : hex;
383
390
  };
384
391
 
385
392
  var color = /*#__PURE__*/Object.freeze({
@@ -394,359 +401,359 @@ var color = /*#__PURE__*/Object.freeze({
394
401
  toHexString: toHexString
395
402
  });
396
403
 
397
- /**
398
- * A module for defining functional schemas to map between different types. This
399
- * module is useful for parsing to or from JSON/protobufs to domain types.
400
- *
401
- * Mappers support greedy validation, so all validation errors are aggregated
402
- * and reported vs failing on the first invalid input.
403
- *
404
- * @example
405
- *
406
- * ```ts
407
- * import { Mapper as M } from '@vertexvis/utils';
408
- *
409
- * interface Address {
410
- * address: string;
411
- * city: string;
412
- * state: string;
413
- * zip: string;
414
- * }
415
- *
416
- * interface Person {
417
- * name: string;
418
- * addresses: Address[];
419
- * }
420
- *
421
- * type AddressJson = Partial<Address>;
422
- * type PersonJson = {
423
- * name?: string;
424
- * addresses?: AddressJson[];
425
- * }
426
- *
427
- * const mapAddress: M.Func<AddressJson, Address> = M.defineMapper(
428
- * M.read(
429
- * M.requireProp('address'),
430
- * M.requireProp('city'),
431
- * M.requireProp('state'),
432
- * M.requireProp('zip')
433
- * ),
434
- * ([address, city, state, zip]) => ({
435
- * address, city, state, zip
436
- * })
437
- * );
438
- *
439
- * const mapPerson: M.Func<PersonJson, Person> = M.defineMapper(
440
- * M.read(
441
- * M.requireProp('name'),
442
- * M.mapProp(
443
- * 'addresses',
444
- * M.compose(M.required('addresses'), M.mapArray(mapAddress))
445
- * )
446
- * ),
447
- * ([name, addresses]) => ({ name, addresses })
448
- * );
449
- *
450
- * const person = mapPerson({
451
- * name: 'John',
452
- * addresses: [{ address: '123', city: 'Ames', state: 'IA', zip: '50010' }]
453
- * });
454
- *
455
- * const invalidPerson = mapPerson({
456
- * addresses: [{ city: 'Ames', state: 'IA', zip: '50010' }]
457
- * });
458
- * ```
459
- * // {
460
- * // errors: ["Name is required.", "Address is required."]
461
- * // }
462
- *
463
- * @module
464
- */
465
- /**
466
- * An error that is thrown when validation of a schema fails.
467
- *
468
- * @see {@link ifInvalidThrow} - for throwing errors on invalid input.
469
- */
470
- var MapperValidationError = /** @class */ (function (_super) {
471
- tslib.__extends(MapperValidationError, _super);
472
- function MapperValidationError(errors) {
473
- var _this = _super.call(this, 'Validation error mapping object.') || this;
474
- _this.errors = errors;
475
- Object.setPrototypeOf(_this, MapperValidationError.prototype);
476
- return _this;
477
- }
478
- return MapperValidationError;
479
- }(Error));
480
- /**
481
- * Returns a mapper that asserts the input is not null or not undefined.
482
- *
483
- * @param name A name to report when invalid.
484
- */
485
- function required(name) {
486
- return function (input) {
487
- if (input != null) {
488
- return input;
489
- }
490
- else {
491
- return { errors: ["".concat(name, " is required.")] };
492
- }
493
- };
494
- }
495
- /**
496
- * Returns a mapper that asserts a property on the input is not null or not
497
- * defined.
498
- *
499
- * @param prop The prop to assert.
500
- * @returns A mapper that returns the property's value.
501
- */
502
- function requiredProp(prop) {
503
- return function (obj) {
504
- var value = obj[prop];
505
- if (value != null) {
506
- return value;
507
- }
508
- else {
509
- return { errors: ["".concat(String(prop), " is required")] };
510
- }
511
- };
512
- }
513
- /**
514
- * Returns a mapper that invokes a function if the input is not null or not
515
- * undefined.
516
- *
517
- * @param mapper A mapping function.
518
- */
519
- function ifDefined(mapper) {
520
- return function (input) {
521
- if (input != null) {
522
- return mapper(input);
523
- }
524
- else {
525
- return input;
526
- }
527
- };
528
- }
529
- /**
530
- * Returns a mapper that extracts a property's value.
531
- *
532
- * @param prop The property to extract.
533
- */
534
- function getProp(prop) {
535
- return function (input) {
536
- return input[prop];
537
- };
538
- }
539
- /**
540
- * Returns a mapper that will invoke a mapping function on an input's property.
541
- *
542
- * @param prop The name of the property to map over.
543
- * @param mapper A function that will be invoked with the property's value.
544
- */
545
- function mapProp(prop, mapper) {
546
- return function (input) {
547
- var value = input[prop];
548
- return mapper(value);
549
- };
550
- }
551
- /**
552
- * Returns a mapper that will check if the given property is defined, and if so
553
- * invoke the given mapping function.
554
- *
555
- * @param prop The name of the property to map over.
556
- * @param mapper A function that will be invoked with the property's value if
557
- * the property is defined.
558
- */
559
- function mapRequiredProp(prop, mapper) {
560
- return mapProp(prop, compose(required(prop.toString()), mapper));
561
- }
562
- /**
563
- * Returns a mapper that will invoke a mapper over each value in the input
564
- * array. Returns `Invalid` containing errors for all invalid values in the
565
- * array.
566
- *
567
- * @param mapper A function that will be invoked with each array value.
568
- * @returns
569
- */
570
- function mapArray(mapper) {
571
- return function (inputs) {
572
- if (inputs.length > 0) {
573
- var _a = tslib.__read(inputs), head = _a[0], tail = _a.slice(1);
574
- var first = mapper(head);
575
- return tail.reduce(function (res, input) {
576
- var value = mapper(input);
577
- if (isInvalid(value)) {
578
- return isInvalid(res)
579
- ? { errors: tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(res.errors), false), tslib.__read(value.errors), false) }
580
- : value;
581
- }
582
- else if (isInvalid(res)) {
583
- return res;
584
- }
585
- else {
586
- return tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(res), false), [value], false);
587
- }
588
- }, isInvalid(first) ? first : [first]);
589
- }
590
- else {
591
- return [];
592
- }
593
- };
594
- }
595
- /**
596
- * A type guard that checks if the object is an `Invalid` type.
597
- */
598
- function isInvalid(obj) {
599
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
600
- return obj != null && obj.hasOwnProperty('errors');
601
- }
602
- /**
603
- * Returns a function that throws an error if the input is invalid. Otherwise,
604
- * returns the result.
605
- *
606
- * @param mapper A mapper that will be invoked with the input.
607
- * @throws {@link MapperValidationError} If the input is invalid.
608
- */
609
- function ifInvalidThrow(mapper) {
610
- return function (input) {
611
- var value = mapper(input);
612
- if (isInvalid(value)) {
613
- throw new MapperValidationError(value.errors);
614
- }
615
- else
616
- return value;
617
- };
618
- }
619
- function ifValidThen(obj, f) {
620
- if (isInvalid(obj)) {
621
- return obj;
622
- }
623
- else {
624
- return f(obj);
625
- }
626
- }
627
- function read() {
628
- var mappers = [];
629
- for (var _i = 0; _i < arguments.length; _i++) {
630
- mappers[_i] = arguments[_i];
631
- }
632
- return function (input) {
633
- return mappers.reduce(function (res, decoder) {
634
- var value = decoder(input);
635
- if (isInvalid(value)) {
636
- return isInvalid(res)
637
- ? { errors: tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(res.errors), false), tslib.__read(value.errors), false) }
638
- : value;
639
- }
640
- else if (isInvalid(res)) {
641
- return res;
642
- }
643
- else {
644
- return tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(res), false), [value], false);
645
- }
646
- }, []);
647
- };
648
- }
649
- /* eslint-enable padding-line-between-statements */
650
- /**
651
- * Defines a mapper that reads the values from an input and invokes a builder to
652
- * transform data from one schema to another.
653
- *
654
- * @example
655
- *
656
- * ```ts
657
- * import { Mapper as M } from '@vertexvis/utils';
658
- *
659
- * interface Address {
660
- * address: string;
661
- * city: string;
662
- * state: string;
663
- * zip: string;
664
- * }
665
- *
666
- * interface Person {
667
- * name: string;
668
- * addresses: Address[];
669
- * }
670
- *
671
- * type AddressJson = Partial<Address>;
672
- * type PersonJson = {
673
- * name?: string;
674
- * addresses?: AddressJson[];
675
- * }
676
- *
677
- * const mapAddress: M.Func<AddressJson, Address> = M.defineMapper(
678
- * M.read(
679
- * M.requireProp('address'),
680
- * M.requireProp('city'),
681
- * M.requireProp('state'),
682
- * M.requireProp('zip')
683
- * ),
684
- * ([address, city, state, zip]) => ({
685
- * address, city, state, zip
686
- * })
687
- * );
688
- *
689
- * const mapPerson: M.Func<PersonJson, Person> = M.defineMapper(
690
- * M.read(
691
- * M.requireProp('name'),
692
- * M.mapProp(
693
- * 'addresses',
694
- * M.compose(M.required('addresses'), M.mapArray(mapAddress))
695
- * )
696
- * ),
697
- * ([name, addresses]) => ({ name, addresses })
698
- * )
699
- *
700
- * const person = mapPerson({
701
- * name: 'John',
702
- * addresses: [{ address: '123', city: 'Ames', state: 'IA', zip: '50010' }]
703
- * })
704
- * ```
705
- *
706
- * @param reader The mapper that reads values from the input an creates an
707
- * intermediate format that will be passed to the `builder`.
708
- * @param builder A mapper that takes the output of `reader` and constructs the
709
- * output format.
710
- * @see {@link read} - a helper function to read and validate input values.
711
- */
712
- function defineMapper(reader, builder) {
713
- return function (input) {
714
- var values = reader(input);
715
- return ifValidThen(values, builder);
716
- };
717
- }
718
- function compose() {
719
- var decoders = [];
720
- for (var _i = 0; _i < arguments.length; _i++) {
721
- decoders[_i] = arguments[_i];
722
- }
723
- return function (input) {
724
- return decoders.reduce(function (last, decoder) {
725
- if (isInvalid(last)) {
726
- return last;
727
- }
728
- else {
729
- return decoder(last);
730
- }
731
- }, input);
732
- };
733
- }
734
- function pickFirst() {
735
- var decoders = [];
736
- for (var _i = 0; _i < arguments.length; _i++) {
737
- decoders[_i] = arguments[_i];
738
- }
739
- return function (input) {
740
- return decoders.reduce(function (value, decoder) {
741
- if (value === undefined) {
742
- return decoder(input);
743
- }
744
- else {
745
- return value;
746
- }
747
- }, undefined);
748
- };
749
- }
404
+ /**
405
+ * A module for defining functional schemas to map between different types. This
406
+ * module is useful for parsing to or from JSON/protobufs to domain types.
407
+ *
408
+ * Mappers support greedy validation, so all validation errors are aggregated
409
+ * and reported vs failing on the first invalid input.
410
+ *
411
+ * @example
412
+ *
413
+ * ```ts
414
+ * import { Mapper as M } from '@vertexvis/utils';
415
+ *
416
+ * interface Address {
417
+ * address: string;
418
+ * city: string;
419
+ * state: string;
420
+ * zip: string;
421
+ * }
422
+ *
423
+ * interface Person {
424
+ * name: string;
425
+ * addresses: Address[];
426
+ * }
427
+ *
428
+ * type AddressJson = Partial<Address>;
429
+ * type PersonJson = {
430
+ * name?: string;
431
+ * addresses?: AddressJson[];
432
+ * }
433
+ *
434
+ * const mapAddress: M.Func<AddressJson, Address> = M.defineMapper(
435
+ * M.read(
436
+ * M.requireProp('address'),
437
+ * M.requireProp('city'),
438
+ * M.requireProp('state'),
439
+ * M.requireProp('zip')
440
+ * ),
441
+ * ([address, city, state, zip]) => ({
442
+ * address, city, state, zip
443
+ * })
444
+ * );
445
+ *
446
+ * const mapPerson: M.Func<PersonJson, Person> = M.defineMapper(
447
+ * M.read(
448
+ * M.requireProp('name'),
449
+ * M.mapProp(
450
+ * 'addresses',
451
+ * M.compose(M.required('addresses'), M.mapArray(mapAddress))
452
+ * )
453
+ * ),
454
+ * ([name, addresses]) => ({ name, addresses })
455
+ * );
456
+ *
457
+ * const person = mapPerson({
458
+ * name: 'John',
459
+ * addresses: [{ address: '123', city: 'Ames', state: 'IA', zip: '50010' }]
460
+ * });
461
+ *
462
+ * const invalidPerson = mapPerson({
463
+ * addresses: [{ city: 'Ames', state: 'IA', zip: '50010' }]
464
+ * });
465
+ * ```
466
+ * // {
467
+ * // errors: ["Name is required.", "Address is required."]
468
+ * // }
469
+ *
470
+ * @module
471
+ */
472
+ /**
473
+ * An error that is thrown when validation of a schema fails.
474
+ *
475
+ * @see {@link ifInvalidThrow} - for throwing errors on invalid input.
476
+ */
477
+ var MapperValidationError = /** @class */ (function (_super) {
478
+ tslib.__extends(MapperValidationError, _super);
479
+ function MapperValidationError(errors) {
480
+ var _this = _super.call(this, 'Validation error mapping object.') || this;
481
+ _this.errors = errors;
482
+ Object.setPrototypeOf(_this, MapperValidationError.prototype);
483
+ return _this;
484
+ }
485
+ return MapperValidationError;
486
+ }(Error));
487
+ /**
488
+ * Returns a mapper that asserts the input is not null or not undefined.
489
+ *
490
+ * @param name A name to report when invalid.
491
+ */
492
+ function required(name) {
493
+ return function (input) {
494
+ if (input != null) {
495
+ return input;
496
+ }
497
+ else {
498
+ return { errors: ["".concat(name, " is required.")] };
499
+ }
500
+ };
501
+ }
502
+ /**
503
+ * Returns a mapper that asserts a property on the input is not null or not
504
+ * defined.
505
+ *
506
+ * @param prop The prop to assert.
507
+ * @returns A mapper that returns the property's value.
508
+ */
509
+ function requiredProp(prop) {
510
+ return function (obj) {
511
+ var value = obj[prop];
512
+ if (value != null) {
513
+ return value;
514
+ }
515
+ else {
516
+ return { errors: ["".concat(String(prop), " is required")] };
517
+ }
518
+ };
519
+ }
520
+ /**
521
+ * Returns a mapper that invokes a function if the input is not null or not
522
+ * undefined.
523
+ *
524
+ * @param mapper A mapping function.
525
+ */
526
+ function ifDefined(mapper) {
527
+ return function (input) {
528
+ if (input != null) {
529
+ return mapper(input);
530
+ }
531
+ else {
532
+ return input;
533
+ }
534
+ };
535
+ }
536
+ /**
537
+ * Returns a mapper that extracts a property's value.
538
+ *
539
+ * @param prop The property to extract.
540
+ */
541
+ function getProp(prop) {
542
+ return function (input) {
543
+ return input[prop];
544
+ };
545
+ }
546
+ /**
547
+ * Returns a mapper that will invoke a mapping function on an input's property.
548
+ *
549
+ * @param prop The name of the property to map over.
550
+ * @param mapper A function that will be invoked with the property's value.
551
+ */
552
+ function mapProp(prop, mapper) {
553
+ return function (input) {
554
+ var value = input[prop];
555
+ return mapper(value);
556
+ };
557
+ }
558
+ /**
559
+ * Returns a mapper that will check if the given property is defined, and if so
560
+ * invoke the given mapping function.
561
+ *
562
+ * @param prop The name of the property to map over.
563
+ * @param mapper A function that will be invoked with the property's value if
564
+ * the property is defined.
565
+ */
566
+ function mapRequiredProp(prop, mapper) {
567
+ return mapProp(prop, compose(required(prop.toString()), mapper));
568
+ }
569
+ /**
570
+ * Returns a mapper that will invoke a mapper over each value in the input
571
+ * array. Returns `Invalid` containing errors for all invalid values in the
572
+ * array.
573
+ *
574
+ * @param mapper A function that will be invoked with each array value.
575
+ * @returns
576
+ */
577
+ function mapArray(mapper) {
578
+ return function (inputs) {
579
+ if (inputs.length > 0) {
580
+ var _a = tslib.__read(inputs), head = _a[0], tail = _a.slice(1);
581
+ var first = mapper(head);
582
+ return tail.reduce(function (res, input) {
583
+ var value = mapper(input);
584
+ if (isInvalid(value)) {
585
+ return isInvalid(res)
586
+ ? { errors: tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(res.errors), false), tslib.__read(value.errors), false) }
587
+ : value;
588
+ }
589
+ else if (isInvalid(res)) {
590
+ return res;
591
+ }
592
+ else {
593
+ return tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(res), false), [value], false);
594
+ }
595
+ }, isInvalid(first) ? first : [first]);
596
+ }
597
+ else {
598
+ return [];
599
+ }
600
+ };
601
+ }
602
+ /**
603
+ * A type guard that checks if the object is an `Invalid` type.
604
+ */
605
+ function isInvalid(obj) {
606
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
607
+ return obj != null && obj.hasOwnProperty('errors');
608
+ }
609
+ /**
610
+ * Returns a function that throws an error if the input is invalid. Otherwise,
611
+ * returns the result.
612
+ *
613
+ * @param mapper A mapper that will be invoked with the input.
614
+ * @throws {@link MapperValidationError} If the input is invalid.
615
+ */
616
+ function ifInvalidThrow(mapper) {
617
+ return function (input) {
618
+ var value = mapper(input);
619
+ if (isInvalid(value)) {
620
+ throw new MapperValidationError(value.errors);
621
+ }
622
+ else
623
+ return value;
624
+ };
625
+ }
626
+ function ifValidThen(obj, f) {
627
+ if (isInvalid(obj)) {
628
+ return obj;
629
+ }
630
+ else {
631
+ return f(obj);
632
+ }
633
+ }
634
+ function read() {
635
+ var mappers = [];
636
+ for (var _i = 0; _i < arguments.length; _i++) {
637
+ mappers[_i] = arguments[_i];
638
+ }
639
+ return function (input) {
640
+ return mappers.reduce(function (res, decoder) {
641
+ var value = decoder(input);
642
+ if (isInvalid(value)) {
643
+ return isInvalid(res)
644
+ ? { errors: tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(res.errors), false), tslib.__read(value.errors), false) }
645
+ : value;
646
+ }
647
+ else if (isInvalid(res)) {
648
+ return res;
649
+ }
650
+ else {
651
+ return tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(res), false), [value], false);
652
+ }
653
+ }, []);
654
+ };
655
+ }
656
+ /* eslint-enable padding-line-between-statements */
657
+ /**
658
+ * Defines a mapper that reads the values from an input and invokes a builder to
659
+ * transform data from one schema to another.
660
+ *
661
+ * @example
662
+ *
663
+ * ```ts
664
+ * import { Mapper as M } from '@vertexvis/utils';
665
+ *
666
+ * interface Address {
667
+ * address: string;
668
+ * city: string;
669
+ * state: string;
670
+ * zip: string;
671
+ * }
672
+ *
673
+ * interface Person {
674
+ * name: string;
675
+ * addresses: Address[];
676
+ * }
677
+ *
678
+ * type AddressJson = Partial<Address>;
679
+ * type PersonJson = {
680
+ * name?: string;
681
+ * addresses?: AddressJson[];
682
+ * }
683
+ *
684
+ * const mapAddress: M.Func<AddressJson, Address> = M.defineMapper(
685
+ * M.read(
686
+ * M.requireProp('address'),
687
+ * M.requireProp('city'),
688
+ * M.requireProp('state'),
689
+ * M.requireProp('zip')
690
+ * ),
691
+ * ([address, city, state, zip]) => ({
692
+ * address, city, state, zip
693
+ * })
694
+ * );
695
+ *
696
+ * const mapPerson: M.Func<PersonJson, Person> = M.defineMapper(
697
+ * M.read(
698
+ * M.requireProp('name'),
699
+ * M.mapProp(
700
+ * 'addresses',
701
+ * M.compose(M.required('addresses'), M.mapArray(mapAddress))
702
+ * )
703
+ * ),
704
+ * ([name, addresses]) => ({ name, addresses })
705
+ * )
706
+ *
707
+ * const person = mapPerson({
708
+ * name: 'John',
709
+ * addresses: [{ address: '123', city: 'Ames', state: 'IA', zip: '50010' }]
710
+ * })
711
+ * ```
712
+ *
713
+ * @param reader The mapper that reads values from the input an creates an
714
+ * intermediate format that will be passed to the `builder`.
715
+ * @param builder A mapper that takes the output of `reader` and constructs the
716
+ * output format.
717
+ * @see {@link read} - a helper function to read and validate input values.
718
+ */
719
+ function defineMapper(reader, builder) {
720
+ return function (input) {
721
+ var values = reader(input);
722
+ return ifValidThen(values, builder);
723
+ };
724
+ }
725
+ function compose() {
726
+ var decoders = [];
727
+ for (var _i = 0; _i < arguments.length; _i++) {
728
+ decoders[_i] = arguments[_i];
729
+ }
730
+ return function (input) {
731
+ return decoders.reduce(function (last, decoder) {
732
+ if (isInvalid(last)) {
733
+ return last;
734
+ }
735
+ else {
736
+ return decoder(last);
737
+ }
738
+ }, input);
739
+ };
740
+ }
741
+ function pickFirst() {
742
+ var decoders = [];
743
+ for (var _i = 0; _i < arguments.length; _i++) {
744
+ decoders[_i] = arguments[_i];
745
+ }
746
+ return function (input) {
747
+ return decoders.reduce(function (value, decoder) {
748
+ if (value === undefined) {
749
+ return decoder(input);
750
+ }
751
+ else {
752
+ return value;
753
+ }
754
+ }, undefined);
755
+ };
756
+ }
750
757
  /* eslint-enable padding-line-between-statements */
751
758
 
752
759
  var mapper = /*#__PURE__*/Object.freeze({
@@ -767,186 +774,96 @@ var mapper = /*#__PURE__*/Object.freeze({
767
774
  pickFirst: pickFirst
768
775
  });
769
776
 
770
- // do not edit .js files directly - edit src/index.jst
771
-
772
-
773
-
774
- var fastDeepEqual = function equal(a, b) {
775
- if (a === b) return true;
776
-
777
- if (a && b && typeof a == 'object' && typeof b == 'object') {
778
- if (a.constructor !== b.constructor) return false;
779
-
780
- var length, i, keys;
781
- if (Array.isArray(a)) {
782
- length = a.length;
783
- if (length != b.length) return false;
784
- for (i = length; i-- !== 0;)
785
- if (!equal(a[i], b[i])) return false;
786
- return true;
777
+ function defaults() {
778
+ var objects = [];
779
+ for (var _i = 0; _i < arguments.length; _i++) {
780
+ objects[_i] = arguments[_i];
787
781
  }
788
-
789
-
790
-
791
- if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
792
- if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
793
- if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
794
-
795
- keys = Object.keys(a);
796
- length = keys.length;
797
- if (length !== Object.keys(b).length) return false;
798
-
799
- for (i = length; i-- !== 0;)
800
- if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
801
-
802
- for (i = length; i-- !== 0;) {
803
- var key = keys[i];
804
-
805
- if (!equal(a[key], b[key])) return false;
782
+ var _a = tslib.__read(objects), a = _a[0], other = _a.slice(1);
783
+ var result = tslib.__assign({}, a);
784
+ if (other.length === 0) {
785
+ return result;
806
786
  }
807
-
808
- return true;
809
- }
810
-
811
- // true if both NaN, false otherwise
812
- return a!==a && b!==b;
813
- };
814
-
815
- /*!
816
- * isobject <https://github.com/jonschlinkert/isobject>
787
+ else if (other.length === 1) {
788
+ var b = other[0];
789
+ for (var key in b) {
790
+ if (result[key] == null) {
791
+ result[key] = b[key];
792
+ }
793
+ else if (isPlainObject(result[key])) {
794
+ result[key] = defaults(result[key], b[key]);
795
+ }
796
+ }
797
+ return result;
798
+ }
799
+ else {
800
+ return other.reduce(function (result, next) { return defaults(result, next); }, a);
801
+ }
802
+ }
803
+ /* eslint-enable padding-line-between-statements */
804
+ /**
805
+ * Returns `true` if this is a plain object, which is defined by a type created
806
+ * by the `Object` constructor. Returns `false` otherwise.
817
807
  *
818
- * Copyright (c) 2014-2017, Jon Schlinkert.
819
- * Released under the MIT License.
808
+ * @example
809
+ * ```
810
+ * isPlainObject(Object.create({})); //=> true
811
+ * isPlainObject(Object.create(Object.prototype)); //=> true
812
+ * isPlainObject({foo: 'bar'}); //=> true
813
+ * isPlainObject({}); //=> true
814
+ *
815
+ * isPlainObject(1); //=> false
816
+ * isPlainObject(['foo', 'bar']); //=> false
817
+ * isPlainObject([]); //=> false
818
+ * isPlainObject(new Foo); //=> false
819
+ * isPlainObject(null); //=> false
820
+ * isPlainObject(Object.create(null)); //=> false
821
+ * ```
820
822
  */
821
-
822
- function isObject(val) {
823
- return val != null && typeof val === 'object' && Array.isArray(val) === false;
823
+ function isPlainObject(obj) {
824
+ return isSimpleObject__default["default"](obj);
824
825
  }
825
-
826
- /*!
827
- * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
826
+ /**
827
+ * Performs a deep comparison of two objects and returns `true` if they're
828
+ * equal.
829
+ *
830
+ * This method supports comparing arrays, array buffers, booleans, date objects,
831
+ * error objects, maps, numbers, Object objects, regexes, sets, strings,
832
+ * symbols, and typed arrays. Object objects are compared by their own, not
833
+ * inherited, enumerable properties. Functions and DOM nodes are compared by
834
+ * strict equality, i.e. ===.
828
835
  *
829
- * Copyright (c) 2014-2017, Jon Schlinkert.
830
- * Released under the MIT License.
836
+ * @param a The object to compare with `b`.
837
+ * @param b The object to compare with `a`.
838
+ * @returns `true` if the two objects are equal. Otherwise `false`.
831
839
  */
832
-
833
- function isObjectObject(o) {
834
- return isObject(o) === true
835
- && Object.prototype.toString.call(o) === '[object Object]';
840
+ function isEqual$1(a, b) {
841
+ return fastDeepEqual__default["default"](a, b);
836
842
  }
837
-
838
- function isPlainObject$1(o) {
839
- var ctor,prot;
840
-
841
- if (isObjectObject(o) === false) return false;
842
-
843
- // If has modified constructor
844
- ctor = o.constructor;
845
- if (typeof ctor !== 'function') return false;
846
-
847
- // If has modified prototype
848
- prot = ctor.prototype;
849
- if (isObjectObject(prot) === false) return false;
850
-
851
- // If constructor does not have an Object-specific method
852
- if (prot.hasOwnProperty('isPrototypeOf') === false) {
853
- return false;
854
- }
855
-
856
- // Most likely a plain Object
857
- return true;
843
+ function toPairs(obj) {
844
+ if (obj != null) {
845
+ return Object.keys(obj).map(function (key) { return [key, obj[key]]; });
846
+ }
847
+ else {
848
+ return [];
849
+ }
850
+ }
851
+ function fromPairs(pairs) {
852
+ if (Array.isArray(pairs)) {
853
+ return pairs.reduce(function (result, pair) {
854
+ var _a;
855
+ if (pair != null) {
856
+ return tslib.__assign(tslib.__assign({}, result), (_a = {}, _a[pair[0]] = pair[1], _a));
857
+ }
858
+ else {
859
+ return result;
860
+ }
861
+ }, {});
862
+ }
863
+ else {
864
+ return {};
865
+ }
858
866
  }
859
-
860
- function defaults() {
861
- var objects = [];
862
- for (var _i = 0; _i < arguments.length; _i++) {
863
- objects[_i] = arguments[_i];
864
- }
865
- var _a = tslib.__read(objects), a = _a[0], other = _a.slice(1);
866
- var result = tslib.__assign({}, a);
867
- if (other.length === 0) {
868
- return result;
869
- }
870
- else if (other.length === 1) {
871
- var b = other[0];
872
- for (var key in b) {
873
- if (result[key] == null) {
874
- result[key] = b[key];
875
- }
876
- else if (isPlainObject(result[key])) {
877
- result[key] = defaults(result[key], b[key]);
878
- }
879
- }
880
- return result;
881
- }
882
- else {
883
- return other.reduce(function (result, next) { return defaults(result, next); }, a);
884
- }
885
- }
886
- /* eslint-enable padding-line-between-statements */
887
- /**
888
- * Returns `true` if this is a plain object, which is defined by a type created
889
- * by the `Object` constructor. Returns `false` otherwise.
890
- *
891
- * @example
892
- * ```
893
- * isPlainObject(Object.create({})); //=> true
894
- * isPlainObject(Object.create(Object.prototype)); //=> true
895
- * isPlainObject({foo: 'bar'}); //=> true
896
- * isPlainObject({}); //=> true
897
- *
898
- * isPlainObject(1); //=> false
899
- * isPlainObject(['foo', 'bar']); //=> false
900
- * isPlainObject([]); //=> false
901
- * isPlainObject(new Foo); //=> false
902
- * isPlainObject(null); //=> false
903
- * isPlainObject(Object.create(null)); //=> false
904
- * ```
905
- */
906
- function isPlainObject(obj) {
907
- return isPlainObject$1(obj);
908
- }
909
- /**
910
- * Performs a deep comparison of two objects and returns `true` if they're
911
- * equal.
912
- *
913
- * This method supports comparing arrays, array buffers, booleans, date objects,
914
- * error objects, maps, numbers, Object objects, regexes, sets, strings,
915
- * symbols, and typed arrays. Object objects are compared by their own, not
916
- * inherited, enumerable properties. Functions and DOM nodes are compared by
917
- * strict equality, i.e. ===.
918
- *
919
- * @param a The object to compare with `b`.
920
- * @param b The object to compare with `a`.
921
- * @returns `true` if the two objects are equal. Otherwise `false`.
922
- */
923
- function isEqual$1(a, b) {
924
- return fastDeepEqual(a, b);
925
- }
926
- function toPairs(obj) {
927
- if (obj != null) {
928
- return Object.keys(obj).map(function (key) { return [key, obj[key]]; });
929
- }
930
- else {
931
- return [];
932
- }
933
- }
934
- function fromPairs(pairs) {
935
- if (Array.isArray(pairs)) {
936
- return pairs.reduce(function (result, pair) {
937
- var _a;
938
- if (pair != null) {
939
- return tslib.__assign(tslib.__assign({}, result), (_a = {}, _a[pair[0]] = pair[1], _a));
940
- }
941
- else {
942
- return result;
943
- }
944
- }, {});
945
- }
946
- else {
947
- return {};
948
- }
949
- }
950
867
  /* eslint-enable padding-line-between-statements */
951
868
 
952
869
  var objects = /*#__PURE__*/Object.freeze({
@@ -958,136 +875,136 @@ var objects = /*#__PURE__*/Object.freeze({
958
875
  fromPairs: fromPairs
959
876
  });
960
877
 
961
- /**
962
- * Returns a new `Range` with the given start and end points.
963
- */
964
- var create$1 = function (start, end) { return ({ start: start, end: end }); };
965
- /**
966
- * Returns a new `Range` with the start and end points at the given position.
967
- */
968
- var at = function (position) { return ({
969
- start: position,
970
- end: position,
971
- }); };
972
- /**
973
- * Returns a new `Range` with the given start point and length.
974
- */
975
- var withLength = function (start, len) { return ({
976
- start: start,
977
- end: start + len - 1,
978
- }); };
979
- /**
980
- * Returns a range with the start and end points shifted by the given distance.
981
- */
982
- var add = function (distance, range) {
983
- return create$1(range.start + distance, range.end + distance);
984
- };
985
- /**
986
- * Returns a range such that `range` is constrained to the start and end points
987
- * of `to`. The function will try to maintain the length of the range, but will
988
- * shrink the range if its length is greater than `to`.
989
- */
990
- var constrain = function (range, to) {
991
- if (contains(range, to)) {
992
- return range;
993
- }
994
- else if (length(range) > length(to)) {
995
- return to;
996
- }
997
- else if (range.start < to.start) {
998
- return create$1(to.start, to.start + length(range) - 1);
999
- }
1000
- else {
1001
- return create$1(to.end - length(range) + 1, to.end);
1002
- }
1003
- };
1004
- /**
1005
- * Checks if the given number or range is contained within another range.
1006
- */
1007
- var contains = function (numOrRange, range) {
1008
- if (typeof numOrRange === 'number') {
1009
- return range.start <= numOrRange && numOrRange <= range.end;
1010
- }
1011
- else {
1012
- return contains(numOrRange.start, range) && contains(numOrRange.end, range);
1013
- }
1014
- };
1015
- /**
1016
- * Returns a range that represents the overlap between `other` and `range`. If
1017
- * the two ranges do not intersect, then `undefined` is returned.
1018
- * @param other
1019
- * @param range
1020
- */
1021
- var intersection = function (other, range) {
1022
- if (intersects(other, range)) {
1023
- return create$1(Math.max(other.start, range.start), Math.min(other.end, range.end));
1024
- }
1025
- };
1026
- /**
1027
- * Returns `true` if `other` intersects with `range`.
1028
- */
1029
- var intersects = function (other, range) {
1030
- return ((other.start <= range.end && other.end >= range.start) ||
1031
- (range.start <= other.end && range.end >= other.start));
1032
- };
1033
- /**
1034
- * Checks if a range has the same starting point as another range.
1035
- */
1036
- var isAt = function (other, range) {
1037
- return other.start === range.start;
1038
- };
1039
- /**
1040
- * Returns `true` if a range's start point is after the starting point of
1041
- * another range.
1042
- */
1043
- var isAfter = function (other, range) {
1044
- return other.start > range.start;
1045
- };
1046
- /**
1047
- * Returns `true` if a range start at or is after another range.
1048
- */
1049
- var isAtOrAfter = function (other, range) {
1050
- return isAt(other, range) || isAfter(other, range);
1051
- };
1052
- /**
1053
- * Returns `true` if a range's starting point is before another range's starting
1054
- * point.
1055
- */
1056
- var isBefore = function (other, range) {
1057
- return other.start < range.start;
1058
- };
1059
- /**
1060
- * Returns `true` if a range's starting point is at or before another range's
1061
- * starting point.
1062
- */
1063
- var isAtOrBefore = function (other, range) {
1064
- return isAt(other, range) || isBefore(other, range);
1065
- };
1066
- /**
1067
- * Returns the length of a range.
1068
- */
1069
- var length = function (range) {
1070
- return range.end - range.start + 1;
1071
- };
1072
- /**
1073
- * Returns a `Range` with its start and end points subtracted by the given
1074
- * distance.
1075
- */
1076
- var subtract = function (distance, range) {
1077
- return add(distance * -1, range);
1078
- };
1079
- /**
1080
- * Adjusts either the start or end position of a range so that its contained
1081
- * within another range. Unlike `constrain`, this will not attempt to retain
1082
- * the range's length.
1083
- *
1084
- * If `other` does not intersect with `to`, then the range cannot be truncated
1085
- * and `undefined` is returned.
1086
- */
1087
- var truncate = function (other, to) {
1088
- if (intersects(to, other)) {
1089
- return create$1(Math.max(other.start, to.start), Math.min(other.end, to.end));
1090
- }
878
+ /**
879
+ * Returns a new `Range` with the given start and end points.
880
+ */
881
+ var create$1 = function (start, end) { return ({ start: start, end: end }); };
882
+ /**
883
+ * Returns a new `Range` with the start and end points at the given position.
884
+ */
885
+ var at = function (position) { return ({
886
+ start: position,
887
+ end: position,
888
+ }); };
889
+ /**
890
+ * Returns a new `Range` with the given start point and length.
891
+ */
892
+ var withLength = function (start, len) { return ({
893
+ start: start,
894
+ end: start + len - 1,
895
+ }); };
896
+ /**
897
+ * Returns a range with the start and end points shifted by the given distance.
898
+ */
899
+ var add = function (distance, range) {
900
+ return create$1(range.start + distance, range.end + distance);
901
+ };
902
+ /**
903
+ * Returns a range such that `range` is constrained to the start and end points
904
+ * of `to`. The function will try to maintain the length of the range, but will
905
+ * shrink the range if its length is greater than `to`.
906
+ */
907
+ var constrain = function (range, to) {
908
+ if (contains(range, to)) {
909
+ return range;
910
+ }
911
+ else if (length(range) > length(to)) {
912
+ return to;
913
+ }
914
+ else if (range.start < to.start) {
915
+ return create$1(to.start, to.start + length(range) - 1);
916
+ }
917
+ else {
918
+ return create$1(to.end - length(range) + 1, to.end);
919
+ }
920
+ };
921
+ /**
922
+ * Checks if the given number or range is contained within another range.
923
+ */
924
+ var contains = function (numOrRange, range) {
925
+ if (typeof numOrRange === 'number') {
926
+ return range.start <= numOrRange && numOrRange <= range.end;
927
+ }
928
+ else {
929
+ return contains(numOrRange.start, range) && contains(numOrRange.end, range);
930
+ }
931
+ };
932
+ /**
933
+ * Returns a range that represents the overlap between `other` and `range`. If
934
+ * the two ranges do not intersect, then `undefined` is returned.
935
+ * @param other
936
+ * @param range
937
+ */
938
+ var intersection = function (other, range) {
939
+ if (intersects(other, range)) {
940
+ return create$1(Math.max(other.start, range.start), Math.min(other.end, range.end));
941
+ }
942
+ };
943
+ /**
944
+ * Returns `true` if `other` intersects with `range`.
945
+ */
946
+ var intersects = function (other, range) {
947
+ return ((other.start <= range.end && other.end >= range.start) ||
948
+ (range.start <= other.end && range.end >= other.start));
949
+ };
950
+ /**
951
+ * Checks if a range has the same starting point as another range.
952
+ */
953
+ var isAt = function (other, range) {
954
+ return other.start === range.start;
955
+ };
956
+ /**
957
+ * Returns `true` if a range's start point is after the starting point of
958
+ * another range.
959
+ */
960
+ var isAfter = function (other, range) {
961
+ return other.start > range.start;
962
+ };
963
+ /**
964
+ * Returns `true` if a range start at or is after another range.
965
+ */
966
+ var isAtOrAfter = function (other, range) {
967
+ return isAt(other, range) || isAfter(other, range);
968
+ };
969
+ /**
970
+ * Returns `true` if a range's starting point is before another range's starting
971
+ * point.
972
+ */
973
+ var isBefore = function (other, range) {
974
+ return other.start < range.start;
975
+ };
976
+ /**
977
+ * Returns `true` if a range's starting point is at or before another range's
978
+ * starting point.
979
+ */
980
+ var isAtOrBefore = function (other, range) {
981
+ return isAt(other, range) || isBefore(other, range);
982
+ };
983
+ /**
984
+ * Returns the length of a range.
985
+ */
986
+ var length = function (range) {
987
+ return range.end - range.start + 1;
988
+ };
989
+ /**
990
+ * Returns a `Range` with its start and end points subtracted by the given
991
+ * distance.
992
+ */
993
+ var subtract = function (distance, range) {
994
+ return add(distance * -1, range);
995
+ };
996
+ /**
997
+ * Adjusts either the start or end position of a range so that its contained
998
+ * within another range. Unlike `constrain`, this will not attempt to retain
999
+ * the range's length.
1000
+ *
1001
+ * If `other` does not intersect with `to`, then the range cannot be truncated
1002
+ * and `undefined` is returned.
1003
+ */
1004
+ var truncate = function (other, to) {
1005
+ if (intersects(to, other)) {
1006
+ return create$1(Math.max(other.start, to.start), Math.min(other.end, to.end));
1007
+ }
1091
1008
  };
1092
1009
 
1093
1010
  var range = /*#__PURE__*/Object.freeze({
@@ -1110,25 +1027,25 @@ var range = /*#__PURE__*/Object.freeze({
1110
1027
  truncate: truncate
1111
1028
  });
1112
1029
 
1113
- function diffSet(a, b) {
1114
- var e_1, _a;
1115
- var res = new Set();
1116
- try {
1117
- for (var b_1 = tslib.__values(b), b_1_1 = b_1.next(); !b_1_1.done; b_1_1 = b_1.next()) {
1118
- var item = b_1_1.value;
1119
- if (!a.has(item)) {
1120
- res.add(item);
1121
- }
1122
- }
1123
- }
1124
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1125
- finally {
1126
- try {
1127
- if (b_1_1 && !b_1_1.done && (_a = b_1.return)) _a.call(b_1);
1128
- }
1129
- finally { if (e_1) throw e_1.error; }
1130
- }
1131
- return res;
1030
+ function diffSet(a, b) {
1031
+ var e_1, _a;
1032
+ var res = new Set();
1033
+ try {
1034
+ for (var b_1 = tslib.__values(b), b_1_1 = b_1.next(); !b_1_1.done; b_1_1 = b_1.next()) {
1035
+ var item = b_1_1.value;
1036
+ if (!a.has(item)) {
1037
+ res.add(item);
1038
+ }
1039
+ }
1040
+ }
1041
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1042
+ finally {
1043
+ try {
1044
+ if (b_1_1 && !b_1_1.done && (_a = b_1.return)) _a.call(b_1);
1045
+ }
1046
+ finally { if (e_1) throw e_1.error; }
1047
+ }
1048
+ return res;
1132
1049
  }
1133
1050
 
1134
1051
  var sets = /*#__PURE__*/Object.freeze({
@@ -1136,17 +1053,17 @@ var sets = /*#__PURE__*/Object.freeze({
1136
1053
  diffSet: diffSet
1137
1054
  });
1138
1055
 
1139
- var trimStartRegex = /^\W+/;
1140
- var trimEndRegex = /\W+$/;
1141
- var trimStartAndEndRegex = /^\W+|\W+$/g;
1142
- function trimStart(str) {
1143
- return str.replace(trimStartRegex, '');
1144
- }
1145
- function trimEnd(str) {
1146
- return str.replace(trimEndRegex, '');
1147
- }
1148
- function trim(str) {
1149
- return str.replace(trimStartAndEndRegex, '');
1056
+ var trimStartRegex = /^\W+/;
1057
+ var trimEndRegex = /\W+$/;
1058
+ var trimStartAndEndRegex = /^\W+|\W+$/g;
1059
+ function trimStart(str) {
1060
+ return str.replace(trimStartRegex, '');
1061
+ }
1062
+ function trimEnd(str) {
1063
+ return str.replace(trimEndRegex, '');
1064
+ }
1065
+ function trim(str) {
1066
+ return str.replace(trimStartAndEndRegex, '');
1150
1067
  }
1151
1068
 
1152
1069
  var strings = /*#__PURE__*/Object.freeze({
@@ -1156,178 +1073,178 @@ var strings = /*#__PURE__*/Object.freeze({
1156
1073
  trim: trim
1157
1074
  });
1158
1075
 
1159
- /**
1160
- * A comparator that sorts a number or string in ascending order.
1161
- */
1162
- var asc = function (a, b) {
1163
- if (a < b) {
1164
- return -1;
1165
- }
1166
- else if (a > b) {
1167
- return 1;
1168
- }
1169
- else {
1170
- return 0;
1171
- }
1172
- };
1173
- /**
1174
- * A comparator that plucks the first element of an array and passes that value
1175
- * to the given comparator for sorting.
1176
- */
1177
- var head = function (comparator) {
1178
- return function (_a, _b) {
1179
- var _c = tslib.__read(_a, 1), a = _c[0];
1180
- var _d = tslib.__read(_b, 1), b = _d[0];
1181
- return comparator(a, b);
1182
- };
1076
+ /**
1077
+ * A comparator that sorts a number or string in ascending order.
1078
+ */
1079
+ var asc = function (a, b) {
1080
+ if (a < b) {
1081
+ return -1;
1082
+ }
1083
+ else if (a > b) {
1084
+ return 1;
1085
+ }
1086
+ else {
1087
+ return 0;
1088
+ }
1089
+ };
1090
+ /**
1091
+ * A comparator that plucks the first element of an array and passes that value
1092
+ * to the given comparator for sorting.
1093
+ */
1094
+ var head = function (comparator) {
1095
+ return function (_a, _b) {
1096
+ var _c = tslib.__read(_a, 1), a = _c[0];
1097
+ var _d = tslib.__read(_b, 1), b = _d[0];
1098
+ return comparator(a, b);
1099
+ };
1183
1100
  };
1184
1101
 
1185
- /**
1186
- * Parses a URI string according to RFC 3986. If the URI is an empty string,
1187
- * then an empty object is returned.
1188
- *
1189
- * See https://tools.ietf.org/html/rfc3986#appendix-B for parsing rules.
1190
- *
1191
- * @param uri The URI to parse.
1192
- */
1193
- var parse = function (uri) {
1194
- var regex = /^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
1195
- var match = regex.exec(uri);
1196
- if (match != null) {
1197
- return {
1198
- scheme: match[2],
1199
- authority: match[4],
1200
- path: match[5],
1201
- query: match[7],
1202
- fragment: match[9],
1203
- };
1204
- }
1205
- else {
1206
- return {};
1207
- }
1208
- };
1209
- /**
1210
- * Convenience method to create a URI from a base string and add params if present
1211
- * @param base
1212
- * @param params
1213
- */
1214
- var parseAndAddParams = function (baseStr, params) {
1215
- var base = parse(baseStr);
1216
- return params ? addQueryParams(params, base) : base;
1217
- };
1218
- var isEqual = function (a, b) {
1219
- var queryA = JSON.stringify(sortByQueryName(queryAsArray(a)));
1220
- var queryB = JSON.stringify(sortByQueryName(queryAsArray(b)));
1221
- return (a.scheme === b.scheme &&
1222
- a.authority === b.authority &&
1223
- a.path === b.path &&
1224
- a.fragment === b.fragment &&
1225
- queryA === queryB);
1226
- };
1227
- var replacePath = function (path, uri) {
1228
- var pathWithForwardSlash = path[0] === '/' ? path : "/".concat(path);
1229
- return tslib.__assign(tslib.__assign({}, uri), { path: pathWithForwardSlash });
1230
- };
1231
- var pathAsArray = function (uri) {
1232
- return uri.path != null ? sanitizePath(uri.path.split('/')) : [];
1233
- };
1234
- var appendPath = function (path, uri) {
1235
- var beforeParts = pathAsArray(uri);
1236
- var afterParts = sanitizePath(path.split('/'));
1237
- return replacePath(beforeParts.concat(afterParts).join('/'), uri);
1238
- };
1239
- var addQueryString = function (query, uri) {
1240
- var queryArray = stringAsQueryArray(query);
1241
- return addQueryEntries(queryArray, uri);
1242
- };
1243
- var addQueryEntry = function (query, uri) {
1244
- if (query[1] != null) {
1245
- var newQuery = tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(queryAsArray(uri)), false), [query], false);
1246
- return tslib.__assign(tslib.__assign({}, uri), { query: newQuery
1247
- .map(function (entry) { return entry.map(encodeURIComponent).join('='); })
1248
- .join('&') });
1249
- }
1250
- else {
1251
- return uri;
1252
- }
1253
- };
1254
- var addQueryEntries = function (entries, uri) {
1255
- return entries.reduce(function (result, entry) { return addQueryEntry(entry, result); }, uri);
1256
- };
1257
- var addQueryParams = function (params, uri) {
1258
- return mapAsEntries(params).reduce(function (result, entry) { return addQueryEntry(entry, result); }, uri);
1259
- };
1260
- var replaceFragment = function (fragment, uri) {
1261
- return tslib.__assign(tslib.__assign({}, uri), { fragment: fragment });
1262
- };
1263
- /**
1264
- * Return an array of name/value pairs representing the query string of a URI.
1265
- * The returned names and values will be URI decoded. If the query string is
1266
- * empty, then an empty array is returned.
1267
- *
1268
- * @param uri A URI to return the query string for.
1269
- */
1270
- var queryAsArray = function (uri) {
1271
- if (uri.query != null) {
1272
- return stringAsQueryArray(uri.query);
1273
- }
1274
- else {
1275
- return [];
1276
- }
1277
- };
1278
- var stringAsQueryArray = function (queryString) {
1279
- return queryString
1280
- .split('&')
1281
- .map(function (param) {
1282
- return param.split('=').map(function (value) { return decodeURIComponent(value); });
1283
- });
1284
- };
1285
- /**
1286
- * Return a map containing a URI's query string names and their values. The
1287
- * returned names and values will be URI decoded. If the query string contains
1288
- * multiple instances of the same name, then the last occurrence will be used.
1289
- *
1290
- * If the query string is empty, an empty map is returned.
1291
- *
1292
- * @param uri A URI to return the query string for.
1293
- */
1294
- var queryAsMap = function (uri) {
1295
- return queryAsArray(uri).reduce(function (map, _a) {
1296
- var _b;
1297
- var _c = tslib.__read(_a, 2), name = _c[0], value = _c[1];
1298
- return tslib.__assign(tslib.__assign({}, map), (_b = {}, _b[name] = value, _b));
1299
- }, {});
1300
- };
1301
- var toString = function (uri) {
1302
- var result = '';
1303
- if (uri.scheme != null && uri.scheme.length > 0) {
1304
- result = "".concat(uri.scheme, ":");
1305
- }
1306
- if (uri.authority != null && uri.authority.length > 0) {
1307
- result += "//".concat(uri.authority);
1308
- }
1309
- result += uri.path;
1310
- if (uri.query != null && uri.query.length > 0) {
1311
- result += "?".concat(uri.query);
1312
- }
1313
- if (uri.fragment != null && uri.fragment.length > 0) {
1314
- result += "#".concat(uri.fragment);
1315
- }
1316
- return result;
1317
- };
1318
- var sanitizePath = function (path) {
1319
- return path.filter(function (segment) { return segment.length > 0; });
1320
- };
1321
- var mapAsEntries = function (map) {
1322
- var entries = [];
1323
- for (var key in map) {
1324
- entries.push([key, map[key]]);
1325
- }
1326
- return entries;
1327
- };
1328
- var sortByQueryName = function (entries) {
1329
- return entries.concat().sort(head(asc));
1330
- };
1102
+ /**
1103
+ * Parses a URI string according to RFC 3986. If the URI is an empty string,
1104
+ * then an empty object is returned.
1105
+ *
1106
+ * See https://tools.ietf.org/html/rfc3986#appendix-B for parsing rules.
1107
+ *
1108
+ * @param uri The URI to parse.
1109
+ */
1110
+ var parse = function (uri) {
1111
+ var regex = /^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
1112
+ var match = regex.exec(uri);
1113
+ if (match != null) {
1114
+ return {
1115
+ scheme: match[2],
1116
+ authority: match[4],
1117
+ path: match[5],
1118
+ query: match[7],
1119
+ fragment: match[9],
1120
+ };
1121
+ }
1122
+ else {
1123
+ return {};
1124
+ }
1125
+ };
1126
+ /**
1127
+ * Convenience method to create a URI from a base string and add params if present
1128
+ * @param base
1129
+ * @param params
1130
+ */
1131
+ var parseAndAddParams = function (baseStr, params) {
1132
+ var base = parse(baseStr);
1133
+ return params ? addQueryParams(params, base) : base;
1134
+ };
1135
+ var isEqual = function (a, b) {
1136
+ var queryA = JSON.stringify(sortByQueryName(queryAsArray(a)));
1137
+ var queryB = JSON.stringify(sortByQueryName(queryAsArray(b)));
1138
+ return (a.scheme === b.scheme &&
1139
+ a.authority === b.authority &&
1140
+ a.path === b.path &&
1141
+ a.fragment === b.fragment &&
1142
+ queryA === queryB);
1143
+ };
1144
+ var replacePath = function (path, uri) {
1145
+ var pathWithForwardSlash = path[0] === '/' ? path : "/".concat(path);
1146
+ return tslib.__assign(tslib.__assign({}, uri), { path: pathWithForwardSlash });
1147
+ };
1148
+ var pathAsArray = function (uri) {
1149
+ return uri.path != null ? sanitizePath(uri.path.split('/')) : [];
1150
+ };
1151
+ var appendPath = function (path, uri) {
1152
+ var beforeParts = pathAsArray(uri);
1153
+ var afterParts = sanitizePath(path.split('/'));
1154
+ return replacePath(beforeParts.concat(afterParts).join('/'), uri);
1155
+ };
1156
+ var addQueryString = function (query, uri) {
1157
+ var queryArray = stringAsQueryArray(query);
1158
+ return addQueryEntries(queryArray, uri);
1159
+ };
1160
+ var addQueryEntry = function (query, uri) {
1161
+ if (query[1] != null) {
1162
+ var newQuery = tslib.__spreadArray(tslib.__spreadArray([], tslib.__read(queryAsArray(uri)), false), [query], false);
1163
+ return tslib.__assign(tslib.__assign({}, uri), { query: newQuery
1164
+ .map(function (entry) { return entry.map(encodeURIComponent).join('='); })
1165
+ .join('&') });
1166
+ }
1167
+ else {
1168
+ return uri;
1169
+ }
1170
+ };
1171
+ var addQueryEntries = function (entries, uri) {
1172
+ return entries.reduce(function (result, entry) { return addQueryEntry(entry, result); }, uri);
1173
+ };
1174
+ var addQueryParams = function (params, uri) {
1175
+ return mapAsEntries(params).reduce(function (result, entry) { return addQueryEntry(entry, result); }, uri);
1176
+ };
1177
+ var replaceFragment = function (fragment, uri) {
1178
+ return tslib.__assign(tslib.__assign({}, uri), { fragment: fragment });
1179
+ };
1180
+ /**
1181
+ * Return an array of name/value pairs representing the query string of a URI.
1182
+ * The returned names and values will be URI decoded. If the query string is
1183
+ * empty, then an empty array is returned.
1184
+ *
1185
+ * @param uri A URI to return the query string for.
1186
+ */
1187
+ var queryAsArray = function (uri) {
1188
+ if (uri.query != null) {
1189
+ return stringAsQueryArray(uri.query);
1190
+ }
1191
+ else {
1192
+ return [];
1193
+ }
1194
+ };
1195
+ var stringAsQueryArray = function (queryString) {
1196
+ return queryString
1197
+ .split('&')
1198
+ .map(function (param) {
1199
+ return param.split('=').map(function (value) { return decodeURIComponent(value); });
1200
+ });
1201
+ };
1202
+ /**
1203
+ * Return a map containing a URI's query string names and their values. The
1204
+ * returned names and values will be URI decoded. If the query string contains
1205
+ * multiple instances of the same name, then the last occurrence will be used.
1206
+ *
1207
+ * If the query string is empty, an empty map is returned.
1208
+ *
1209
+ * @param uri A URI to return the query string for.
1210
+ */
1211
+ var queryAsMap = function (uri) {
1212
+ return queryAsArray(uri).reduce(function (map, _a) {
1213
+ var _b;
1214
+ var _c = tslib.__read(_a, 2), name = _c[0], value = _c[1];
1215
+ return tslib.__assign(tslib.__assign({}, map), (_b = {}, _b[name] = value, _b));
1216
+ }, {});
1217
+ };
1218
+ var toString = function (uri) {
1219
+ var result = '';
1220
+ if (uri.scheme != null && uri.scheme.length > 0) {
1221
+ result = "".concat(uri.scheme, ":");
1222
+ }
1223
+ if (uri.authority != null && uri.authority.length > 0) {
1224
+ result += "//".concat(uri.authority);
1225
+ }
1226
+ result += uri.path;
1227
+ if (uri.query != null && uri.query.length > 0) {
1228
+ result += "?".concat(uri.query);
1229
+ }
1230
+ if (uri.fragment != null && uri.fragment.length > 0) {
1231
+ result += "#".concat(uri.fragment);
1232
+ }
1233
+ return result;
1234
+ };
1235
+ var sanitizePath = function (path) {
1236
+ return path.filter(function (segment) { return segment.length > 0; });
1237
+ };
1238
+ var mapAsEntries = function (map) {
1239
+ var entries = [];
1240
+ for (var key in map) {
1241
+ entries.push([key, map[key]]);
1242
+ }
1243
+ return entries;
1244
+ };
1245
+ var sortByQueryName = function (entries) {
1246
+ return entries.concat().sort(head(asc));
1247
+ };
1331
1248
  /* eslint-enable @typescript-eslint/no-explicit-any */
1332
1249
 
1333
1250
  var uri = /*#__PURE__*/Object.freeze({
@@ -1348,96 +1265,31 @@ var uri = /*#__PURE__*/Object.freeze({
1348
1265
  toString: toString
1349
1266
  });
1350
1267
 
1351
- const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate
1352
-
1353
- let poolPtr = rnds8Pool.length;
1354
- function rng() {
1355
- if (poolPtr > rnds8Pool.length - 16) {
1356
- crypto__default["default"].randomFillSync(rnds8Pool);
1357
- poolPtr = 0;
1358
- }
1359
-
1360
- return rnds8Pool.slice(poolPtr, poolPtr += 16);
1361
- }
1362
-
1363
- var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
1364
-
1365
- function validate(uuid) {
1366
- return typeof uuid === 'string' && REGEX.test(uuid);
1268
+ function create() {
1269
+ return uuid$1.v4();
1367
1270
  }
1368
-
1369
- /**
1370
- * Convert array of 16 byte values to UUID string format of the form:
1371
- * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
1372
- */
1373
-
1374
- const byteToHex = [];
1375
-
1376
- for (let i = 0; i < 256; ++i) {
1377
- byteToHex.push((i + 0x100).toString(16).substr(1));
1378
- }
1379
-
1380
- function stringify(arr, offset = 0) {
1381
- // Note: Be careful editing this code! It's been tuned for performance
1382
- // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
1383
- const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
1384
- // of the following:
1385
- // - One or more input array values don't map to a hex octet (leading to
1386
- // "undefined" in the uuid)
1387
- // - Invalid input values for the RFC `version` or `variant` fields
1388
-
1389
- if (!validate(uuid)) {
1390
- throw TypeError('Stringified UUID is invalid');
1391
- }
1392
-
1393
- return uuid;
1394
- }
1395
-
1396
- function v4(options, buf, offset) {
1397
- options = options || {};
1398
- const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
1399
-
1400
- rnds[6] = rnds[6] & 0x0f | 0x40;
1401
- rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
1402
-
1403
- if (buf) {
1404
- offset = offset || 0;
1405
-
1406
- for (let i = 0; i < 16; ++i) {
1407
- buf[offset + i] = rnds[i];
1271
+ function fromMsbLsb(msb, lsb) {
1272
+ function digits(val, ds) {
1273
+ var hi = BigInt(1) << (ds * BigInt(4));
1274
+ return (hi | (val & (hi - BigInt(1)))).toString(16).substring(1);
1408
1275
  }
1409
-
1410
- return buf;
1411
- }
1412
-
1413
- return stringify(rnds);
1276
+ var msbB = typeof msb === 'string' ? BigInt(msb) : msb;
1277
+ var lsbB = typeof lsb === 'string' ? BigInt(lsb) : lsb;
1278
+ var sec1 = digits(msbB >> BigInt(32), BigInt(8));
1279
+ var sec2 = digits(msbB >> BigInt(16), BigInt(4));
1280
+ var sec3 = digits(msbB, BigInt(4));
1281
+ var sec4 = digits(lsbB >> BigInt(48), BigInt(4));
1282
+ var sec5 = digits(lsbB, BigInt(12));
1283
+ return "".concat(sec1, "-").concat(sec2, "-").concat(sec3, "-").concat(sec4, "-").concat(sec5);
1414
1284
  }
1415
-
1416
- function create() {
1417
- return v4();
1418
- }
1419
- function fromMsbLsb(msb, lsb) {
1420
- function digits(val, ds) {
1421
- var hi = BigInt(1) << (ds * BigInt(4));
1422
- return (hi | (val & (hi - BigInt(1)))).toString(16).substring(1);
1423
- }
1424
- var msbB = typeof msb === 'string' ? BigInt(msb) : msb;
1425
- var lsbB = typeof lsb === 'string' ? BigInt(lsb) : lsb;
1426
- var sec1 = digits(msbB >> BigInt(32), BigInt(8));
1427
- var sec2 = digits(msbB >> BigInt(16), BigInt(4));
1428
- var sec3 = digits(msbB, BigInt(4));
1429
- var sec4 = digits(lsbB >> BigInt(48), BigInt(4));
1430
- var sec5 = digits(lsbB, BigInt(12));
1431
- return "".concat(sec1, "-").concat(sec2, "-").concat(sec3, "-").concat(sec4, "-").concat(sec5);
1432
- }
1433
- function toMsbLsb(id) {
1434
- var _a = tslib.__read(id.split('-'), 5), c1 = _a[0], c2 = _a[1], c3 = _a[2], c4 = _a[3], c5 = _a[4];
1435
- if (c1 == null || c2 == null || c3 == null || c4 == null || c5 == null) {
1436
- throw new Error("Invalid UUID string ".concat(id));
1437
- }
1438
- var msb = BigInt.asIntN(64, BigInt("0x".concat(c1 + c2 + c3)));
1439
- var lsb = BigInt.asIntN(64, BigInt("0x".concat(c4 + c5)));
1440
- return { msb: msb.toString(), lsb: lsb.toString() };
1285
+ function toMsbLsb(id) {
1286
+ var _a = tslib.__read(id.split('-'), 5), c1 = _a[0], c2 = _a[1], c3 = _a[2], c4 = _a[3], c5 = _a[4];
1287
+ if (c1 == null || c2 == null || c3 == null || c4 == null || c5 == null) {
1288
+ throw new Error("Invalid UUID string ".concat(id));
1289
+ }
1290
+ var msb = BigInt.asIntN(64, BigInt("0x".concat(c1 + c2 + c3)));
1291
+ var lsb = BigInt.asIntN(64, BigInt("0x".concat(c4 + c5)));
1292
+ return { msb: msb.toString(), lsb: lsb.toString() };
1441
1293
  }
1442
1294
 
1443
1295
  var uuid = /*#__PURE__*/Object.freeze({
@@ -1447,65 +1299,68 @@ var uuid = /*#__PURE__*/Object.freeze({
1447
1299
  toMsbLsb: toMsbLsb
1448
1300
  });
1449
1301
 
1450
- var EventDispatcher = /** @class */ (function () {
1451
- function EventDispatcher() {
1452
- this.listeners = [];
1453
- }
1454
- EventDispatcher.prototype.on = function (listener, opts) {
1455
- var _this = this;
1456
- var _a;
1457
- if (opts === void 0) { opts = {}; }
1458
- this.listeners.push(listener);
1459
- var controller = new AbortController();
1460
- controller.signal.addEventListener('abort', function () { return _this.off(listener); });
1461
- (_a = opts.abort) === null || _a === void 0 ? void 0 : _a.addEventListener('abort', function () { return controller.abort(); });
1462
- return { dispose: function () { return controller.abort(); } };
1463
- };
1464
- EventDispatcher.prototype.once = function (opts) {
1465
- var _this = this;
1466
- if (opts === void 0) { opts = {}; }
1467
- return new Promise(function (resolve) {
1468
- _this.on(function (event) { return resolve(event); }, opts);
1469
- });
1470
- };
1471
- EventDispatcher.prototype.onceWhen = function (predicate, opts) {
1472
- var _a;
1473
- if (opts === void 0) { opts = {}; }
1474
- return tslib.__awaiter(this, void 0, void 0, function () {
1475
- var controller;
1476
- var _this = this;
1477
- return tslib.__generator(this, function (_b) {
1478
- controller = new AbortController();
1479
- (_a = opts.abort) === null || _a === void 0 ? void 0 : _a.addEventListener('abort', function () { return controller.abort(); });
1480
- return [2 /*return*/, new Promise(function (resolve) {
1481
- _this.when(predicate, function (event) {
1482
- if (predicate(event)) {
1483
- controller.abort();
1484
- resolve(event);
1485
- }
1486
- }, tslib.__assign(tslib.__assign({}, opts), { abort: controller.signal }));
1487
- })];
1488
- });
1489
- });
1490
- };
1491
- EventDispatcher.prototype.when = function (predicate, listener, opts) {
1492
- if (opts === void 0) { opts = {}; }
1493
- return this.on(function (event) {
1494
- if (predicate(event)) {
1495
- listener(event);
1496
- }
1497
- }, opts);
1498
- };
1499
- EventDispatcher.prototype.off = function (listener) {
1500
- var index = this.listeners.indexOf(listener);
1501
- if (index !== -1) {
1502
- this.listeners.splice(index, 1);
1503
- }
1504
- };
1505
- EventDispatcher.prototype.emit = function (event) {
1506
- this.listeners.forEach(function (listener) { return listener(event); });
1507
- };
1508
- return EventDispatcher;
1302
+ var EventDispatcher = /** @class */ (function () {
1303
+ function EventDispatcher() {
1304
+ this.listeners = [];
1305
+ }
1306
+ EventDispatcher.prototype.on = function (listener, opts) {
1307
+ var _this = this;
1308
+ var _a;
1309
+ if (opts === void 0) { opts = {}; }
1310
+ this.listeners.push(listener);
1311
+ var controller = new AbortController();
1312
+ controller.signal.addEventListener('abort', function () { return _this.off(listener); });
1313
+ (_a = opts.abort) === null || _a === void 0 ? void 0 : _a.addEventListener('abort', function () { return controller.abort(); });
1314
+ return { dispose: function () { return controller.abort(); } };
1315
+ };
1316
+ EventDispatcher.prototype.once = function (opts) {
1317
+ var _this = this;
1318
+ if (opts === void 0) { opts = {}; }
1319
+ return new Promise(function (resolve) {
1320
+ var subscription = _this.on(function (event) {
1321
+ subscription.dispose();
1322
+ resolve(event);
1323
+ }, opts);
1324
+ });
1325
+ };
1326
+ EventDispatcher.prototype.onceWhen = function (predicate_1) {
1327
+ return tslib.__awaiter(this, arguments, Promise, function (predicate, opts) {
1328
+ var controller;
1329
+ var _this = this;
1330
+ var _a;
1331
+ if (opts === void 0) { opts = {}; }
1332
+ return tslib.__generator(this, function (_b) {
1333
+ controller = new AbortController();
1334
+ (_a = opts.abort) === null || _a === void 0 ? void 0 : _a.addEventListener('abort', function () { return controller.abort(); });
1335
+ return [2 /*return*/, new Promise(function (resolve) {
1336
+ _this.when(predicate, function (event) {
1337
+ if (predicate(event)) {
1338
+ controller.abort();
1339
+ resolve(event);
1340
+ }
1341
+ }, tslib.__assign(tslib.__assign({}, opts), { abort: controller.signal }));
1342
+ })];
1343
+ });
1344
+ });
1345
+ };
1346
+ EventDispatcher.prototype.when = function (predicate, listener, opts) {
1347
+ if (opts === void 0) { opts = {}; }
1348
+ return this.on(function (event) {
1349
+ if (predicate(event)) {
1350
+ listener(event);
1351
+ }
1352
+ }, opts);
1353
+ };
1354
+ EventDispatcher.prototype.off = function (listener) {
1355
+ var index = this.listeners.indexOf(listener);
1356
+ if (index !== -1) {
1357
+ this.listeners.splice(index, 1);
1358
+ }
1359
+ };
1360
+ EventDispatcher.prototype.emit = function (event) {
1361
+ this.listeners.forEach(function (listener) { return listener(event); });
1362
+ };
1363
+ return EventDispatcher;
1509
1364
  }());
1510
1365
 
1511
1366
  exports.Async = async;