@bigbinary/neeto-email-notifications-frontend 2.2.22 → 2.2.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2167 @@
1
+ 'use strict';
2
+
3
+ var React = require('react');
4
+ var require$$0 = require('stream');
5
+ var reactQuery = require('@tanstack/react-query');
6
+ var neetoCist = require('@bigbinary/neeto-cist');
7
+ var constants = require('@bigbinary/neeto-commons-frontend/constants');
8
+ var reactUtils = require('@bigbinary/neeto-commons-frontend/react-utils');
9
+ var ramda = require('ramda');
10
+ var axios = require('axios');
11
+
12
+ function _interopNamespaceDefault(e) {
13
+ var n = Object.create(null);
14
+ if (e) {
15
+ Object.keys(e).forEach(function (k) {
16
+ if (k !== 'default') {
17
+ var d = Object.getOwnPropertyDescriptor(e, k);
18
+ Object.defineProperty(n, k, d.get ? d : {
19
+ enumerable: true,
20
+ get: function () { return e[k]; }
21
+ });
22
+ }
23
+ });
24
+ }
25
+ n.default = e;
26
+ return Object.freeze(n);
27
+ }
28
+
29
+ var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
30
+
31
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
32
+
33
+ function getDefaultExportFromCjs (x) {
34
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
35
+ }
36
+
37
+ var propTypes = {exports: {}};
38
+
39
+ /**
40
+ * Copyright (c) 2013-present, Facebook, Inc.
41
+ *
42
+ * This source code is licensed under the MIT license found in the
43
+ * LICENSE file in the root directory of this source tree.
44
+ */
45
+
46
+ var ReactPropTypesSecret_1;
47
+ var hasRequiredReactPropTypesSecret;
48
+
49
+ function requireReactPropTypesSecret () {
50
+ if (hasRequiredReactPropTypesSecret) return ReactPropTypesSecret_1;
51
+ hasRequiredReactPropTypesSecret = 1;
52
+
53
+ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
54
+
55
+ ReactPropTypesSecret_1 = ReactPropTypesSecret;
56
+ return ReactPropTypesSecret_1;
57
+ }
58
+
59
+ /**
60
+ * Copyright (c) 2013-present, Facebook, Inc.
61
+ *
62
+ * This source code is licensed under the MIT license found in the
63
+ * LICENSE file in the root directory of this source tree.
64
+ */
65
+
66
+ var factoryWithThrowingShims;
67
+ var hasRequiredFactoryWithThrowingShims;
68
+
69
+ function requireFactoryWithThrowingShims () {
70
+ if (hasRequiredFactoryWithThrowingShims) return factoryWithThrowingShims;
71
+ hasRequiredFactoryWithThrowingShims = 1;
72
+
73
+ var ReactPropTypesSecret = requireReactPropTypesSecret();
74
+
75
+ function emptyFunction() {}
76
+ function emptyFunctionWithReset() {}
77
+ emptyFunctionWithReset.resetWarningCache = emptyFunction;
78
+
79
+ factoryWithThrowingShims = function() {
80
+ function shim(props, propName, componentName, location, propFullName, secret) {
81
+ if (secret === ReactPropTypesSecret) {
82
+ // It is still safe when called from React.
83
+ return;
84
+ }
85
+ var err = new Error(
86
+ 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
87
+ 'Use PropTypes.checkPropTypes() to call them. ' +
88
+ 'Read more at http://fb.me/use-check-prop-types'
89
+ );
90
+ err.name = 'Invariant Violation';
91
+ throw err;
92
+ } shim.isRequired = shim;
93
+ function getShim() {
94
+ return shim;
95
+ } // Important!
96
+ // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
97
+ var ReactPropTypes = {
98
+ array: shim,
99
+ bigint: shim,
100
+ bool: shim,
101
+ func: shim,
102
+ number: shim,
103
+ object: shim,
104
+ string: shim,
105
+ symbol: shim,
106
+
107
+ any: shim,
108
+ arrayOf: getShim,
109
+ element: shim,
110
+ elementType: shim,
111
+ instanceOf: getShim,
112
+ node: shim,
113
+ objectOf: getShim,
114
+ oneOf: getShim,
115
+ oneOfType: getShim,
116
+ shape: getShim,
117
+ exact: getShim,
118
+
119
+ checkPropTypes: emptyFunctionWithReset,
120
+ resetWarningCache: emptyFunction
121
+ };
122
+
123
+ ReactPropTypes.PropTypes = ReactPropTypes;
124
+
125
+ return ReactPropTypes;
126
+ };
127
+ return factoryWithThrowingShims;
128
+ }
129
+
130
+ /**
131
+ * Copyright (c) 2013-present, Facebook, Inc.
132
+ *
133
+ * This source code is licensed under the MIT license found in the
134
+ * LICENSE file in the root directory of this source tree.
135
+ */
136
+
137
+ {
138
+ // By explicitly using `prop-types` you are opting into new production behavior.
139
+ // http://fb.me/prop-types-in-prod
140
+ propTypes.exports = requireFactoryWithThrowingShims()();
141
+ }
142
+
143
+ var propTypesExports = propTypes.exports;
144
+ var PropTypes = /*@__PURE__*/getDefaultExportFromCjs(propTypesExports);
145
+
146
+ var _rect, _path;
147
+ function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
148
+ var SvgAvatarPlaceholder = function SvgAvatarPlaceholder(props) {
149
+ return /*#__PURE__*/React__namespace.createElement("svg", _extends({
150
+ xmlns: "http://www.w3.org/2000/svg",
151
+ width: 32,
152
+ height: 32,
153
+ fill: "none"
154
+ }, props), _rect || (_rect = /*#__PURE__*/React__namespace.createElement("rect", {
155
+ width: 31.558,
156
+ height: 31.558,
157
+ fill: "#F1F3F4",
158
+ rx: 15.779
159
+ })), _path || (_path = /*#__PURE__*/React__namespace.createElement("path", {
160
+ fill: "#C2C8CC",
161
+ d: "M15.778 15.778a2.892 2.892 0 1 0 0-5.786 2.892 2.892 0 1 0 0 5.786m0 1.446c-1.931 0-5.786.97-5.786 2.893v1.447h11.572v-1.447c0-1.924-3.855-2.893-5.786-2.893"
162
+ })));
163
+ };
164
+
165
+ var papaparse = {exports: {}};
166
+
167
+ /* @license
168
+ Papa Parse
169
+ v5.5.3
170
+ https://github.com/mholt/PapaParse
171
+ License: MIT
172
+ */
173
+
174
+ (function (module, exports$1) {
175
+ (function(root, factory)
176
+ {
177
+ /* globals define */
178
+ {
179
+ // Node. Does not work with strict CommonJS, but
180
+ // only CommonJS-like environments that support module.exports,
181
+ // like Node.
182
+ module.exports = factory();
183
+ }
184
+ // in strict mode we cannot access arguments.callee, so we need a named reference to
185
+ // stringify the factory method for the blob worker
186
+ // eslint-disable-next-line func-name
187
+ }(commonjsGlobal, function moduleFactory()
188
+ {
189
+
190
+ var global = (function() {
191
+ // alternative method, similar to `Function('return this')()`
192
+ // but without using `eval` (which is disabled when
193
+ // using Content Security Policy).
194
+
195
+ if (typeof self !== 'undefined') { return self; }
196
+ if (typeof window !== 'undefined') { return window; }
197
+ if (typeof global !== 'undefined') { return global; }
198
+
199
+ // When running tests none of the above have been defined
200
+ return {};
201
+ })();
202
+
203
+
204
+ function getWorkerBlob() {
205
+ var URL = global.URL || global.webkitURL || null;
206
+ var code = moduleFactory.toString();
207
+ return Papa.BLOB_URL || (Papa.BLOB_URL = URL.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ", '(', code, ')();'], {type: 'text/javascript'})));
208
+ }
209
+
210
+ var IS_WORKER = !global.document && !!global.postMessage,
211
+ IS_PAPA_WORKER = global.IS_PAPA_WORKER || false;
212
+
213
+ var workers = {}, workerIdCounter = 0;
214
+
215
+ var Papa = {};
216
+
217
+ Papa.parse = CsvToJson;
218
+ Papa.unparse = JsonToCsv;
219
+
220
+ Papa.RECORD_SEP = String.fromCharCode(30);
221
+ Papa.UNIT_SEP = String.fromCharCode(31);
222
+ Papa.BYTE_ORDER_MARK = '\ufeff';
223
+ Papa.BAD_DELIMITERS = ['\r', '\n', '"', Papa.BYTE_ORDER_MARK];
224
+ Papa.WORKERS_SUPPORTED = !IS_WORKER && !!global.Worker;
225
+ Papa.NODE_STREAM_INPUT = 1;
226
+
227
+ // Configurable chunk sizes for local and remote files, respectively
228
+ Papa.LocalChunkSize = 1024 * 1024 * 10; // 10 MB
229
+ Papa.RemoteChunkSize = 1024 * 1024 * 5; // 5 MB
230
+ Papa.DefaultDelimiter = ','; // Used if not specified and detection fails
231
+
232
+ // Exposed for testing and development only
233
+ Papa.Parser = Parser;
234
+ Papa.ParserHandle = ParserHandle;
235
+ Papa.NetworkStreamer = NetworkStreamer;
236
+ Papa.FileStreamer = FileStreamer;
237
+ Papa.StringStreamer = StringStreamer;
238
+ Papa.ReadableStreamStreamer = ReadableStreamStreamer;
239
+ if (typeof PAPA_BROWSER_CONTEXT === 'undefined') {
240
+ Papa.DuplexStreamStreamer = DuplexStreamStreamer;
241
+ }
242
+
243
+ if (global.jQuery)
244
+ {
245
+ var $ = global.jQuery;
246
+ $.fn.parse = function(options)
247
+ {
248
+ var config = options.config || {};
249
+ var queue = [];
250
+
251
+ this.each(function(idx)
252
+ {
253
+ var supported = $(this).prop('tagName').toUpperCase() === 'INPUT'
254
+ && $(this).attr('type').toLowerCase() === 'file'
255
+ && global.FileReader;
256
+
257
+ if (!supported || !this.files || this.files.length === 0)
258
+ return true; // continue to next input element
259
+
260
+ for (var i = 0; i < this.files.length; i++)
261
+ {
262
+ queue.push({
263
+ file: this.files[i],
264
+ inputElem: this,
265
+ instanceConfig: $.extend({}, config)
266
+ });
267
+ }
268
+ });
269
+
270
+ parseNextFile(); // begin parsing
271
+ return this; // maintains chainability
272
+
273
+
274
+ function parseNextFile()
275
+ {
276
+ if (queue.length === 0)
277
+ {
278
+ if (isFunction(options.complete))
279
+ options.complete();
280
+ return;
281
+ }
282
+
283
+ var f = queue[0];
284
+
285
+ if (isFunction(options.before))
286
+ {
287
+ var returned = options.before(f.file, f.inputElem);
288
+
289
+ if (typeof returned === 'object')
290
+ {
291
+ if (returned.action === 'abort')
292
+ {
293
+ error('AbortError', f.file, f.inputElem, returned.reason);
294
+ return; // Aborts all queued files immediately
295
+ }
296
+ else if (returned.action === 'skip')
297
+ {
298
+ fileComplete(); // parse the next file in the queue, if any
299
+ return;
300
+ }
301
+ else if (typeof returned.config === 'object')
302
+ f.instanceConfig = $.extend(f.instanceConfig, returned.config);
303
+ }
304
+ else if (returned === 'skip')
305
+ {
306
+ fileComplete(); // parse the next file in the queue, if any
307
+ return;
308
+ }
309
+ }
310
+
311
+ // Wrap up the user's complete callback, if any, so that ours also gets executed
312
+ var userCompleteFunc = f.instanceConfig.complete;
313
+ f.instanceConfig.complete = function(results)
314
+ {
315
+ if (isFunction(userCompleteFunc))
316
+ userCompleteFunc(results, f.file, f.inputElem);
317
+ fileComplete();
318
+ };
319
+
320
+ Papa.parse(f.file, f.instanceConfig);
321
+ }
322
+
323
+ function error(name, file, elem, reason)
324
+ {
325
+ if (isFunction(options.error))
326
+ options.error({name: name}, file, elem, reason);
327
+ }
328
+
329
+ function fileComplete()
330
+ {
331
+ queue.splice(0, 1);
332
+ parseNextFile();
333
+ }
334
+ };
335
+ }
336
+
337
+
338
+ if (IS_PAPA_WORKER)
339
+ {
340
+ global.onmessage = workerThreadReceivedMessage;
341
+ }
342
+
343
+
344
+
345
+
346
+ function CsvToJson(_input, _config)
347
+ {
348
+ _config = _config || {};
349
+ var dynamicTyping = _config.dynamicTyping || false;
350
+ if (isFunction(dynamicTyping)) {
351
+ _config.dynamicTypingFunction = dynamicTyping;
352
+ // Will be filled on first row call
353
+ dynamicTyping = {};
354
+ }
355
+ _config.dynamicTyping = dynamicTyping;
356
+
357
+ _config.transform = isFunction(_config.transform) ? _config.transform : false;
358
+
359
+ if (_config.worker && Papa.WORKERS_SUPPORTED)
360
+ {
361
+ var w = newWorker();
362
+
363
+ w.userStep = _config.step;
364
+ w.userChunk = _config.chunk;
365
+ w.userComplete = _config.complete;
366
+ w.userError = _config.error;
367
+
368
+ _config.step = isFunction(_config.step);
369
+ _config.chunk = isFunction(_config.chunk);
370
+ _config.complete = isFunction(_config.complete);
371
+ _config.error = isFunction(_config.error);
372
+ delete _config.worker; // prevent infinite loop
373
+
374
+ w.postMessage({
375
+ input: _input,
376
+ config: _config,
377
+ workerId: w.id
378
+ });
379
+
380
+ return;
381
+ }
382
+
383
+ var streamer = null;
384
+ if (_input === Papa.NODE_STREAM_INPUT && typeof PAPA_BROWSER_CONTEXT === 'undefined')
385
+ {
386
+ // create a node Duplex stream for use
387
+ // with .pipe
388
+ streamer = new DuplexStreamStreamer(_config);
389
+ return streamer.getStream();
390
+ }
391
+ else if (typeof _input === 'string')
392
+ {
393
+ _input = stripBom(_input);
394
+ if (_config.download)
395
+ streamer = new NetworkStreamer(_config);
396
+ else
397
+ streamer = new StringStreamer(_config);
398
+ }
399
+ else if (_input.readable === true && isFunction(_input.read) && isFunction(_input.on))
400
+ {
401
+ streamer = new ReadableStreamStreamer(_config);
402
+ }
403
+ else if ((global.File && _input instanceof File) || _input instanceof Object) // ...Safari. (see issue #106)
404
+ streamer = new FileStreamer(_config);
405
+
406
+ return streamer.stream(_input);
407
+
408
+ // Strip character from UTF-8 BOM encoded files that cause issue parsing the file
409
+ function stripBom(string) {
410
+ if (string.charCodeAt(0) === 0xfeff) {
411
+ return string.slice(1);
412
+ }
413
+ return string;
414
+ }
415
+ }
416
+
417
+
418
+
419
+
420
+
421
+
422
+ function JsonToCsv(_input, _config)
423
+ {
424
+ // Default configuration
425
+
426
+ /** whether to surround every datum with quotes */
427
+ var _quotes = false;
428
+
429
+ /** whether to write headers */
430
+ var _writeHeader = true;
431
+
432
+ /** delimiting character(s) */
433
+ var _delimiter = ',';
434
+
435
+ /** newline character(s) */
436
+ var _newline = '\r\n';
437
+
438
+ /** quote character */
439
+ var _quoteChar = '"';
440
+
441
+ /** escaped quote character, either "" or <config.escapeChar>" */
442
+ var _escapedQuote = _quoteChar + _quoteChar;
443
+
444
+ /** whether to skip empty lines */
445
+ var _skipEmptyLines = false;
446
+
447
+ /** the columns (keys) we expect when we unparse objects */
448
+ var _columns = null;
449
+
450
+ /** whether to prevent outputting cells that can be parsed as formulae by spreadsheet software (Excel and LibreOffice) */
451
+ var _escapeFormulae = false;
452
+
453
+ unpackConfig();
454
+
455
+ var quoteCharRegex = new RegExp(escapeRegExp(_quoteChar), 'g');
456
+
457
+ if (typeof _input === 'string')
458
+ _input = JSON.parse(_input);
459
+
460
+ if (Array.isArray(_input))
461
+ {
462
+ if (!_input.length || Array.isArray(_input[0]))
463
+ return serialize(null, _input, _skipEmptyLines);
464
+ else if (typeof _input[0] === 'object')
465
+ return serialize(_columns || Object.keys(_input[0]), _input, _skipEmptyLines);
466
+ }
467
+ else if (typeof _input === 'object')
468
+ {
469
+ if (typeof _input.data === 'string')
470
+ _input.data = JSON.parse(_input.data);
471
+
472
+ if (Array.isArray(_input.data))
473
+ {
474
+ if (!_input.fields)
475
+ _input.fields = _input.meta && _input.meta.fields || _columns;
476
+
477
+ if (!_input.fields)
478
+ _input.fields = Array.isArray(_input.data[0])
479
+ ? _input.fields
480
+ : typeof _input.data[0] === 'object'
481
+ ? Object.keys(_input.data[0])
482
+ : [];
483
+
484
+ if (!(Array.isArray(_input.data[0])) && typeof _input.data[0] !== 'object')
485
+ _input.data = [_input.data]; // handles input like [1,2,3] or ['asdf']
486
+ }
487
+
488
+ return serialize(_input.fields || [], _input.data || [], _skipEmptyLines);
489
+ }
490
+
491
+ // Default (any valid paths should return before this)
492
+ throw new Error('Unable to serialize unrecognized input');
493
+
494
+
495
+ function unpackConfig()
496
+ {
497
+ if (typeof _config !== 'object')
498
+ return;
499
+
500
+ if (typeof _config.delimiter === 'string'
501
+ && !Papa.BAD_DELIMITERS.filter(function(value) { return _config.delimiter.indexOf(value) !== -1; }).length)
502
+ {
503
+ _delimiter = _config.delimiter;
504
+ }
505
+
506
+ if (typeof _config.quotes === 'boolean'
507
+ || typeof _config.quotes === 'function'
508
+ || Array.isArray(_config.quotes))
509
+ _quotes = _config.quotes;
510
+
511
+ if (typeof _config.skipEmptyLines === 'boolean'
512
+ || typeof _config.skipEmptyLines === 'string')
513
+ _skipEmptyLines = _config.skipEmptyLines;
514
+
515
+ if (typeof _config.newline === 'string')
516
+ _newline = _config.newline;
517
+
518
+ if (typeof _config.quoteChar === 'string')
519
+ _quoteChar = _config.quoteChar;
520
+
521
+ if (typeof _config.header === 'boolean')
522
+ _writeHeader = _config.header;
523
+
524
+ if (Array.isArray(_config.columns)) {
525
+
526
+ if (_config.columns.length === 0) throw new Error('Option columns is empty');
527
+
528
+ _columns = _config.columns;
529
+ }
530
+
531
+ if (_config.escapeChar !== undefined) {
532
+ _escapedQuote = _config.escapeChar + _quoteChar;
533
+ }
534
+
535
+ if (_config.escapeFormulae instanceof RegExp) {
536
+ _escapeFormulae = _config.escapeFormulae;
537
+ } else if (typeof _config.escapeFormulae === 'boolean' && _config.escapeFormulae) {
538
+ _escapeFormulae = /^[=+\-@\t\r].*$/;
539
+ }
540
+ }
541
+
542
+ /** The double for loop that iterates the data and writes out a CSV string including header row */
543
+ function serialize(fields, data, skipEmptyLines)
544
+ {
545
+ var csv = '';
546
+
547
+ if (typeof fields === 'string')
548
+ fields = JSON.parse(fields);
549
+ if (typeof data === 'string')
550
+ data = JSON.parse(data);
551
+
552
+ var hasHeader = Array.isArray(fields) && fields.length > 0;
553
+ var dataKeyedByField = !(Array.isArray(data[0]));
554
+
555
+ // If there a header row, write it first
556
+ if (hasHeader && _writeHeader)
557
+ {
558
+ for (var i = 0; i < fields.length; i++)
559
+ {
560
+ if (i > 0)
561
+ csv += _delimiter;
562
+ csv += safe(fields[i], i);
563
+ }
564
+ if (data.length > 0)
565
+ csv += _newline;
566
+ }
567
+
568
+ // Then write out the data
569
+ for (var row = 0; row < data.length; row++)
570
+ {
571
+ var maxCol = hasHeader ? fields.length : data[row].length;
572
+
573
+ var emptyLine = false;
574
+ var nullLine = hasHeader ? Object.keys(data[row]).length === 0 : data[row].length === 0;
575
+ if (skipEmptyLines && !hasHeader)
576
+ {
577
+ emptyLine = skipEmptyLines === 'greedy' ? data[row].join('').trim() === '' : data[row].length === 1 && data[row][0].length === 0;
578
+ }
579
+ if (skipEmptyLines === 'greedy' && hasHeader) {
580
+ var line = [];
581
+ for (var c = 0; c < maxCol; c++) {
582
+ var cx = dataKeyedByField ? fields[c] : c;
583
+ line.push(data[row][cx]);
584
+ }
585
+ emptyLine = line.join('').trim() === '';
586
+ }
587
+ if (!emptyLine)
588
+ {
589
+ for (var col = 0; col < maxCol; col++)
590
+ {
591
+ if (col > 0 && !nullLine)
592
+ csv += _delimiter;
593
+ var colIdx = hasHeader && dataKeyedByField ? fields[col] : col;
594
+ csv += safe(data[row][colIdx], col);
595
+ }
596
+ if (row < data.length - 1 && (!skipEmptyLines || (maxCol > 0 && !nullLine)))
597
+ {
598
+ csv += _newline;
599
+ }
600
+ }
601
+ }
602
+ return csv;
603
+ }
604
+
605
+ /** Encloses a value around quotes if needed (makes a value safe for CSV insertion) */
606
+ function safe(str, col)
607
+ {
608
+ if (typeof str === 'undefined' || str === null)
609
+ return '';
610
+
611
+ if (str.constructor === Date)
612
+ return JSON.stringify(str).slice(1, 25);
613
+
614
+ var needsQuotes = false;
615
+
616
+ if (_escapeFormulae && typeof str === "string" && _escapeFormulae.test(str)) {
617
+ str = "'" + str;
618
+ needsQuotes = true;
619
+ }
620
+
621
+ var escapedQuoteStr = str.toString().replace(quoteCharRegex, _escapedQuote);
622
+
623
+ needsQuotes = needsQuotes
624
+ || _quotes === true
625
+ || (typeof _quotes === 'function' && _quotes(str, col))
626
+ || (Array.isArray(_quotes) && _quotes[col])
627
+ || hasAny(escapedQuoteStr, Papa.BAD_DELIMITERS)
628
+ || escapedQuoteStr.indexOf(_delimiter) > -1
629
+ || escapedQuoteStr.charAt(0) === ' '
630
+ || escapedQuoteStr.charAt(escapedQuoteStr.length - 1) === ' ';
631
+
632
+ return needsQuotes ? _quoteChar + escapedQuoteStr + _quoteChar : escapedQuoteStr;
633
+ }
634
+
635
+ function hasAny(str, substrings)
636
+ {
637
+ for (var i = 0; i < substrings.length; i++)
638
+ if (str.indexOf(substrings[i]) > -1)
639
+ return true;
640
+ return false;
641
+ }
642
+ }
643
+
644
+
645
+ /** ChunkStreamer is the base prototype for various streamer implementations. */
646
+ function ChunkStreamer(config)
647
+ {
648
+ this._handle = null;
649
+ this._finished = false;
650
+ this._completed = false;
651
+ this._halted = false;
652
+ this._input = null;
653
+ this._baseIndex = 0;
654
+ this._partialLine = '';
655
+ this._rowCount = 0;
656
+ this._start = 0;
657
+ this._nextChunk = null;
658
+ this.isFirstChunk = true;
659
+ this._completeResults = {
660
+ data: [],
661
+ errors: [],
662
+ meta: {}
663
+ };
664
+ replaceConfig.call(this, config);
665
+
666
+ this.parseChunk = function(chunk, isFakeChunk)
667
+ {
668
+ // First chunk pre-processing
669
+ const skipFirstNLines = parseInt(this._config.skipFirstNLines) || 0;
670
+ if (this.isFirstChunk && skipFirstNLines > 0) {
671
+ let _newline = this._config.newline;
672
+ if (!_newline) {
673
+ const quoteChar = this._config.quoteChar || '"';
674
+ _newline = this._handle.guessLineEndings(chunk, quoteChar);
675
+ }
676
+ const splitChunk = chunk.split(_newline);
677
+ chunk = [...splitChunk.slice(skipFirstNLines)].join(_newline);
678
+ }
679
+ if (this.isFirstChunk && isFunction(this._config.beforeFirstChunk))
680
+ {
681
+ var modifiedChunk = this._config.beforeFirstChunk(chunk);
682
+ if (modifiedChunk !== undefined)
683
+ chunk = modifiedChunk;
684
+ }
685
+ this.isFirstChunk = false;
686
+ this._halted = false;
687
+
688
+ // Rejoin the line we likely just split in two by chunking the file
689
+ var aggregate = this._partialLine + chunk;
690
+ this._partialLine = '';
691
+ var results = this._handle.parse(aggregate, this._baseIndex, !this._finished);
692
+
693
+ if (this._handle.paused() || this._handle.aborted()) {
694
+ this._halted = true;
695
+ return;
696
+ }
697
+
698
+ var lastIndex = results.meta.cursor;
699
+
700
+ if (!this._finished)
701
+ {
702
+ this._partialLine = aggregate.substring(lastIndex - this._baseIndex);
703
+ this._baseIndex = lastIndex;
704
+ }
705
+
706
+ if (results && results.data)
707
+ this._rowCount += results.data.length;
708
+
709
+ var finishedIncludingPreview = this._finished || (this._config.preview && this._rowCount >= this._config.preview);
710
+
711
+ if (IS_PAPA_WORKER)
712
+ {
713
+ global.postMessage({
714
+ results: results,
715
+ workerId: Papa.WORKER_ID,
716
+ finished: finishedIncludingPreview
717
+ });
718
+ }
719
+ else if (isFunction(this._config.chunk) && !isFakeChunk)
720
+ {
721
+ this._config.chunk(results, this._handle);
722
+ if (this._handle.paused() || this._handle.aborted()) {
723
+ this._halted = true;
724
+ return;
725
+ }
726
+ results = undefined;
727
+ this._completeResults = undefined;
728
+ }
729
+
730
+ if (!this._config.step && !this._config.chunk) {
731
+ this._completeResults.data = this._completeResults.data.concat(results.data);
732
+ this._completeResults.errors = this._completeResults.errors.concat(results.errors);
733
+ this._completeResults.meta = results.meta;
734
+ }
735
+
736
+ if (!this._completed && finishedIncludingPreview && isFunction(this._config.complete) && (!results || !results.meta.aborted)) {
737
+ this._config.complete(this._completeResults, this._input);
738
+ this._completed = true;
739
+ }
740
+
741
+ if (!finishedIncludingPreview && (!results || !results.meta.paused))
742
+ this._nextChunk();
743
+
744
+ return results;
745
+ };
746
+
747
+ this._sendError = function(error)
748
+ {
749
+ if (isFunction(this._config.error))
750
+ this._config.error(error);
751
+ else if (IS_PAPA_WORKER && this._config.error)
752
+ {
753
+ global.postMessage({
754
+ workerId: Papa.WORKER_ID,
755
+ error: error,
756
+ finished: false
757
+ });
758
+ }
759
+ };
760
+
761
+ function replaceConfig(config)
762
+ {
763
+ // Deep-copy the config so we can edit it
764
+ var configCopy = copy(config);
765
+ configCopy.chunkSize = parseInt(configCopy.chunkSize); // parseInt VERY important so we don't concatenate strings!
766
+ if (!config.step && !config.chunk)
767
+ configCopy.chunkSize = null; // disable Range header if not streaming; bad values break IIS - see issue #196
768
+ this._handle = new ParserHandle(configCopy);
769
+ this._handle.streamer = this;
770
+ this._config = configCopy; // persist the copy to the caller
771
+ }
772
+ }
773
+
774
+
775
+ function NetworkStreamer(config)
776
+ {
777
+ config = config || {};
778
+ if (!config.chunkSize)
779
+ config.chunkSize = Papa.RemoteChunkSize;
780
+ ChunkStreamer.call(this, config);
781
+
782
+ var xhr;
783
+
784
+ if (IS_WORKER)
785
+ {
786
+ this._nextChunk = function()
787
+ {
788
+ this._readChunk();
789
+ this._chunkLoaded();
790
+ };
791
+ }
792
+ else
793
+ {
794
+ this._nextChunk = function()
795
+ {
796
+ this._readChunk();
797
+ };
798
+ }
799
+
800
+ this.stream = function(url)
801
+ {
802
+ this._input = url;
803
+ this._nextChunk(); // Starts streaming
804
+ };
805
+
806
+ this._readChunk = function()
807
+ {
808
+ if (this._finished)
809
+ {
810
+ this._chunkLoaded();
811
+ return;
812
+ }
813
+
814
+ xhr = new XMLHttpRequest();
815
+
816
+ if (this._config.withCredentials)
817
+ {
818
+ xhr.withCredentials = this._config.withCredentials;
819
+ }
820
+
821
+ if (!IS_WORKER)
822
+ {
823
+ xhr.onload = bindFunction(this._chunkLoaded, this);
824
+ xhr.onerror = bindFunction(this._chunkError, this);
825
+ }
826
+
827
+ xhr.open(this._config.downloadRequestBody ? 'POST' : 'GET', this._input, !IS_WORKER);
828
+ // Headers can only be set when once the request state is OPENED
829
+ if (this._config.downloadRequestHeaders)
830
+ {
831
+ var headers = this._config.downloadRequestHeaders;
832
+
833
+ for (var headerName in headers)
834
+ {
835
+ xhr.setRequestHeader(headerName, headers[headerName]);
836
+ }
837
+ }
838
+
839
+ if (this._config.chunkSize)
840
+ {
841
+ var end = this._start + this._config.chunkSize - 1; // minus one because byte range is inclusive
842
+ xhr.setRequestHeader('Range', 'bytes=' + this._start + '-' + end);
843
+ }
844
+
845
+ try {
846
+ xhr.send(this._config.downloadRequestBody);
847
+ }
848
+ catch (err) {
849
+ this._chunkError(err.message);
850
+ }
851
+
852
+ if (IS_WORKER && xhr.status === 0)
853
+ this._chunkError();
854
+ };
855
+
856
+ this._chunkLoaded = function()
857
+ {
858
+ if (xhr.readyState !== 4)
859
+ return;
860
+
861
+ if (xhr.status < 200 || xhr.status >= 400)
862
+ {
863
+ this._chunkError();
864
+ return;
865
+ }
866
+
867
+ // Use chunckSize as it may be a diference on reponse lentgh due to characters with more than 1 byte
868
+ this._start += this._config.chunkSize ? this._config.chunkSize : xhr.responseText.length;
869
+ this._finished = !this._config.chunkSize || this._start >= getFileSize(xhr);
870
+ this.parseChunk(xhr.responseText);
871
+ };
872
+
873
+ this._chunkError = function(errorMessage)
874
+ {
875
+ var errorText = xhr.statusText || errorMessage;
876
+ this._sendError(new Error(errorText));
877
+ };
878
+
879
+ function getFileSize(xhr)
880
+ {
881
+ var contentRange = xhr.getResponseHeader('Content-Range');
882
+ if (contentRange === null) { // no content range, then finish!
883
+ return -1;
884
+ }
885
+ return parseInt(contentRange.substring(contentRange.lastIndexOf('/') + 1));
886
+ }
887
+ }
888
+ NetworkStreamer.prototype = Object.create(ChunkStreamer.prototype);
889
+ NetworkStreamer.prototype.constructor = NetworkStreamer;
890
+
891
+
892
+ function FileStreamer(config)
893
+ {
894
+ config = config || {};
895
+ if (!config.chunkSize)
896
+ config.chunkSize = Papa.LocalChunkSize;
897
+ ChunkStreamer.call(this, config);
898
+
899
+ var reader, slice;
900
+
901
+ // FileReader is better than FileReaderSync (even in worker) - see http://stackoverflow.com/q/24708649/1048862
902
+ // But Firefox is a pill, too - see issue #76: https://github.com/mholt/PapaParse/issues/76
903
+ var usingAsyncReader = typeof FileReader !== 'undefined'; // Safari doesn't consider it a function - see issue #105
904
+
905
+ this.stream = function(file)
906
+ {
907
+ this._input = file;
908
+ slice = file.slice || file.webkitSlice || file.mozSlice;
909
+
910
+ if (usingAsyncReader)
911
+ {
912
+ reader = new FileReader(); // Preferred method of reading files, even in workers
913
+ reader.onload = bindFunction(this._chunkLoaded, this);
914
+ reader.onerror = bindFunction(this._chunkError, this);
915
+ }
916
+ else
917
+ reader = new FileReaderSync(); // Hack for running in a web worker in Firefox
918
+
919
+ this._nextChunk(); // Starts streaming
920
+ };
921
+
922
+ this._nextChunk = function()
923
+ {
924
+ if (!this._finished && (!this._config.preview || this._rowCount < this._config.preview))
925
+ this._readChunk();
926
+ };
927
+
928
+ this._readChunk = function()
929
+ {
930
+ var input = this._input;
931
+ if (this._config.chunkSize)
932
+ {
933
+ var end = Math.min(this._start + this._config.chunkSize, this._input.size);
934
+ input = slice.call(input, this._start, end);
935
+ }
936
+ var txt = reader.readAsText(input, this._config.encoding);
937
+ if (!usingAsyncReader)
938
+ this._chunkLoaded({ target: { result: txt } }); // mimic the async signature
939
+ };
940
+
941
+ this._chunkLoaded = function(event)
942
+ {
943
+ // Very important to increment start each time before handling results
944
+ this._start += this._config.chunkSize;
945
+ this._finished = !this._config.chunkSize || this._start >= this._input.size;
946
+ this.parseChunk(event.target.result);
947
+ };
948
+
949
+ this._chunkError = function()
950
+ {
951
+ this._sendError(reader.error);
952
+ };
953
+
954
+ }
955
+ FileStreamer.prototype = Object.create(ChunkStreamer.prototype);
956
+ FileStreamer.prototype.constructor = FileStreamer;
957
+
958
+
959
+ function StringStreamer(config)
960
+ {
961
+ config = config || {};
962
+ ChunkStreamer.call(this, config);
963
+
964
+ var remaining;
965
+ this.stream = function(s)
966
+ {
967
+ remaining = s;
968
+ return this._nextChunk();
969
+ };
970
+ this._nextChunk = function()
971
+ {
972
+ if (this._finished) return;
973
+ var size = this._config.chunkSize;
974
+ var chunk;
975
+ if(size) {
976
+ chunk = remaining.substring(0, size);
977
+ remaining = remaining.substring(size);
978
+ } else {
979
+ chunk = remaining;
980
+ remaining = '';
981
+ }
982
+ this._finished = !remaining;
983
+ return this.parseChunk(chunk);
984
+ };
985
+ }
986
+ StringStreamer.prototype = Object.create(StringStreamer.prototype);
987
+ StringStreamer.prototype.constructor = StringStreamer;
988
+
989
+
990
+ function ReadableStreamStreamer(config)
991
+ {
992
+ config = config || {};
993
+
994
+ ChunkStreamer.call(this, config);
995
+
996
+ var queue = [];
997
+ var parseOnData = true;
998
+ var streamHasEnded = false;
999
+
1000
+ this.pause = function()
1001
+ {
1002
+ ChunkStreamer.prototype.pause.apply(this, arguments);
1003
+ this._input.pause();
1004
+ };
1005
+
1006
+ this.resume = function()
1007
+ {
1008
+ ChunkStreamer.prototype.resume.apply(this, arguments);
1009
+ this._input.resume();
1010
+ };
1011
+
1012
+ this.stream = function(stream)
1013
+ {
1014
+ this._input = stream;
1015
+
1016
+ this._input.on('data', this._streamData);
1017
+ this._input.on('end', this._streamEnd);
1018
+ this._input.on('error', this._streamError);
1019
+ };
1020
+
1021
+ this._checkIsFinished = function()
1022
+ {
1023
+ if (streamHasEnded && queue.length === 1) {
1024
+ this._finished = true;
1025
+ }
1026
+ };
1027
+
1028
+ this._nextChunk = function()
1029
+ {
1030
+ this._checkIsFinished();
1031
+ if (queue.length)
1032
+ {
1033
+ this.parseChunk(queue.shift());
1034
+ }
1035
+ else
1036
+ {
1037
+ parseOnData = true;
1038
+ }
1039
+ };
1040
+
1041
+ this._streamData = bindFunction(function(chunk)
1042
+ {
1043
+ try
1044
+ {
1045
+ queue.push(typeof chunk === 'string' ? chunk : chunk.toString(this._config.encoding));
1046
+
1047
+ if (parseOnData)
1048
+ {
1049
+ parseOnData = false;
1050
+ this._checkIsFinished();
1051
+ this.parseChunk(queue.shift());
1052
+ }
1053
+ }
1054
+ catch (error)
1055
+ {
1056
+ this._streamError(error);
1057
+ }
1058
+ }, this);
1059
+
1060
+ this._streamError = bindFunction(function(error)
1061
+ {
1062
+ this._streamCleanUp();
1063
+ this._sendError(error);
1064
+ }, this);
1065
+
1066
+ this._streamEnd = bindFunction(function()
1067
+ {
1068
+ this._streamCleanUp();
1069
+ streamHasEnded = true;
1070
+ this._streamData('');
1071
+ }, this);
1072
+
1073
+ this._streamCleanUp = bindFunction(function()
1074
+ {
1075
+ this._input.removeListener('data', this._streamData);
1076
+ this._input.removeListener('end', this._streamEnd);
1077
+ this._input.removeListener('error', this._streamError);
1078
+ }, this);
1079
+ }
1080
+ ReadableStreamStreamer.prototype = Object.create(ChunkStreamer.prototype);
1081
+ ReadableStreamStreamer.prototype.constructor = ReadableStreamStreamer;
1082
+
1083
+
1084
+ function DuplexStreamStreamer(_config) {
1085
+ var Duplex = require$$0.Duplex;
1086
+ var config = copy(_config);
1087
+ var parseOnWrite = true;
1088
+ var writeStreamHasFinished = false;
1089
+ var parseCallbackQueue = [];
1090
+ var stream = null;
1091
+
1092
+ this._onCsvData = function(results)
1093
+ {
1094
+ var data = results.data;
1095
+ if (!stream.push(data) && !this._handle.paused()) {
1096
+ // the writeable consumer buffer has filled up
1097
+ // so we need to pause until more items
1098
+ // can be processed
1099
+ this._handle.pause();
1100
+ }
1101
+ };
1102
+
1103
+ this._onCsvComplete = function()
1104
+ {
1105
+ // node will finish the read stream when
1106
+ // null is pushed
1107
+ stream.push(null);
1108
+ };
1109
+
1110
+ config.step = bindFunction(this._onCsvData, this);
1111
+ config.complete = bindFunction(this._onCsvComplete, this);
1112
+ ChunkStreamer.call(this, config);
1113
+
1114
+ this._nextChunk = function()
1115
+ {
1116
+ if (writeStreamHasFinished && parseCallbackQueue.length === 1) {
1117
+ this._finished = true;
1118
+ }
1119
+ if (parseCallbackQueue.length) {
1120
+ parseCallbackQueue.shift()();
1121
+ } else {
1122
+ parseOnWrite = true;
1123
+ }
1124
+ };
1125
+
1126
+ this._addToParseQueue = function(chunk, callback)
1127
+ {
1128
+ // add to queue so that we can indicate
1129
+ // completion via callback
1130
+ // node will automatically pause the incoming stream
1131
+ // when too many items have been added without their
1132
+ // callback being invoked
1133
+ parseCallbackQueue.push(bindFunction(function() {
1134
+ this.parseChunk(typeof chunk === 'string' ? chunk : chunk.toString(config.encoding));
1135
+ if (isFunction(callback)) {
1136
+ return callback();
1137
+ }
1138
+ }, this));
1139
+ if (parseOnWrite) {
1140
+ parseOnWrite = false;
1141
+ this._nextChunk();
1142
+ }
1143
+ };
1144
+
1145
+ this._onRead = function()
1146
+ {
1147
+ if (this._handle.paused()) {
1148
+ // the writeable consumer can handle more data
1149
+ // so resume the chunk parsing
1150
+ this._handle.resume();
1151
+ }
1152
+ };
1153
+
1154
+ this._onWrite = function(chunk, encoding, callback)
1155
+ {
1156
+ this._addToParseQueue(chunk, callback);
1157
+ };
1158
+
1159
+ this._onWriteComplete = function()
1160
+ {
1161
+ writeStreamHasFinished = true;
1162
+ // have to write empty string
1163
+ // so parser knows its done
1164
+ this._addToParseQueue('');
1165
+ };
1166
+
1167
+ this.getStream = function()
1168
+ {
1169
+ return stream;
1170
+ };
1171
+ stream = new Duplex({
1172
+ readableObjectMode: true,
1173
+ decodeStrings: false,
1174
+ read: bindFunction(this._onRead, this),
1175
+ write: bindFunction(this._onWrite, this)
1176
+ });
1177
+ stream.once('finish', bindFunction(this._onWriteComplete, this));
1178
+ }
1179
+ if (typeof PAPA_BROWSER_CONTEXT === 'undefined') {
1180
+ DuplexStreamStreamer.prototype = Object.create(ChunkStreamer.prototype);
1181
+ DuplexStreamStreamer.prototype.constructor = DuplexStreamStreamer;
1182
+ }
1183
+
1184
+
1185
+ // Use one ParserHandle per entire CSV file or string
1186
+ function ParserHandle(_config)
1187
+ {
1188
+ // One goal is to minimize the use of regular expressions...
1189
+ var MAX_FLOAT = Math.pow(2, 53);
1190
+ var MIN_FLOAT = -MAX_FLOAT;
1191
+ var FLOAT = /^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/;
1192
+ var ISO_DATE = /^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/;
1193
+ var self = this;
1194
+ var _stepCounter = 0; // Number of times step was called (number of rows parsed)
1195
+ var _rowCounter = 0; // Number of rows that have been parsed so far
1196
+ var _input; // The input being parsed
1197
+ var _parser; // The core parser being used
1198
+ var _paused = false; // Whether we are paused or not
1199
+ var _aborted = false; // Whether the parser has aborted or not
1200
+ var _delimiterError; // Temporary state between delimiter detection and processing results
1201
+ var _fields = []; // Fields are from the header row of the input, if there is one
1202
+ var _results = { // The last results returned from the parser
1203
+ data: [],
1204
+ errors: [],
1205
+ meta: {}
1206
+ };
1207
+
1208
+ if (isFunction(_config.step))
1209
+ {
1210
+ var userStep = _config.step;
1211
+ _config.step = function(results)
1212
+ {
1213
+ _results = results;
1214
+
1215
+ if (needsHeaderRow())
1216
+ processResults();
1217
+ else // only call user's step function after header row
1218
+ {
1219
+ processResults();
1220
+
1221
+ // It's possbile that this line was empty and there's no row here after all
1222
+ if (_results.data.length === 0)
1223
+ return;
1224
+
1225
+ _stepCounter += results.data.length;
1226
+ if (_config.preview && _stepCounter > _config.preview)
1227
+ _parser.abort();
1228
+ else {
1229
+ _results.data = _results.data[0];
1230
+ userStep(_results, self);
1231
+ }
1232
+ }
1233
+ };
1234
+ }
1235
+
1236
+ /**
1237
+ * Parses input. Most users won't need, and shouldn't mess with, the baseIndex
1238
+ * and ignoreLastRow parameters. They are used by streamers (wrapper functions)
1239
+ * when an input comes in multiple chunks, like from a file.
1240
+ */
1241
+ this.parse = function(input, baseIndex, ignoreLastRow)
1242
+ {
1243
+ var quoteChar = _config.quoteChar || '"';
1244
+ if (!_config.newline)
1245
+ _config.newline = this.guessLineEndings(input, quoteChar);
1246
+
1247
+ _delimiterError = false;
1248
+ if (!_config.delimiter)
1249
+ {
1250
+ var delimGuess = guessDelimiter(input, _config.newline, _config.skipEmptyLines, _config.comments, _config.delimitersToGuess);
1251
+ if (delimGuess.successful)
1252
+ _config.delimiter = delimGuess.bestDelimiter;
1253
+ else
1254
+ {
1255
+ _delimiterError = true; // add error after parsing (otherwise it would be overwritten)
1256
+ _config.delimiter = Papa.DefaultDelimiter;
1257
+ }
1258
+ _results.meta.delimiter = _config.delimiter;
1259
+ }
1260
+ else if(isFunction(_config.delimiter))
1261
+ {
1262
+ _config.delimiter = _config.delimiter(input);
1263
+ _results.meta.delimiter = _config.delimiter;
1264
+ }
1265
+
1266
+ var parserConfig = copy(_config);
1267
+ if (_config.preview && _config.header)
1268
+ parserConfig.preview++; // to compensate for header row
1269
+
1270
+ _input = input;
1271
+ _parser = new Parser(parserConfig);
1272
+ _results = _parser.parse(_input, baseIndex, ignoreLastRow);
1273
+ processResults();
1274
+ return _paused ? { meta: { paused: true } } : (_results || { meta: { paused: false } });
1275
+ };
1276
+
1277
+ this.paused = function()
1278
+ {
1279
+ return _paused;
1280
+ };
1281
+
1282
+ this.pause = function()
1283
+ {
1284
+ _paused = true;
1285
+ _parser.abort();
1286
+
1287
+ // If it is streaming via "chunking", the reader will start appending correctly already so no need to substring,
1288
+ // otherwise we can get duplicate content within a row
1289
+ _input = isFunction(_config.chunk) ? "" : _input.substring(_parser.getCharIndex());
1290
+ };
1291
+
1292
+ this.resume = function()
1293
+ {
1294
+ if(self.streamer._halted) {
1295
+ _paused = false;
1296
+ self.streamer.parseChunk(_input, true);
1297
+ } else {
1298
+ // Bugfix: #636 In case the processing hasn't halted yet
1299
+ // wait for it to halt in order to resume
1300
+ setTimeout(self.resume, 3);
1301
+ }
1302
+ };
1303
+
1304
+ this.aborted = function()
1305
+ {
1306
+ return _aborted;
1307
+ };
1308
+
1309
+ this.abort = function()
1310
+ {
1311
+ _aborted = true;
1312
+ _parser.abort();
1313
+ _results.meta.aborted = true;
1314
+ if (isFunction(_config.complete))
1315
+ _config.complete(_results);
1316
+ _input = '';
1317
+ };
1318
+
1319
+ this.guessLineEndings = function(input, quoteChar)
1320
+ {
1321
+ input = input.substring(0, 1024 * 1024); // max length 1 MB
1322
+ // Replace all the text inside quotes
1323
+ var re = new RegExp(escapeRegExp(quoteChar) + '([^]*?)' + escapeRegExp(quoteChar), 'gm');
1324
+ input = input.replace(re, '');
1325
+
1326
+ var r = input.split('\r');
1327
+
1328
+ var n = input.split('\n');
1329
+
1330
+ var nAppearsFirst = (n.length > 1 && n[0].length < r[0].length);
1331
+
1332
+ if (r.length === 1 || nAppearsFirst)
1333
+ return '\n';
1334
+
1335
+ var numWithN = 0;
1336
+ for (var i = 0; i < r.length; i++)
1337
+ {
1338
+ if (r[i][0] === '\n')
1339
+ numWithN++;
1340
+ }
1341
+
1342
+ return numWithN >= r.length / 2 ? '\r\n' : '\r';
1343
+ };
1344
+
1345
+ function testEmptyLine(s) {
1346
+ return _config.skipEmptyLines === 'greedy' ? s.join('').trim() === '' : s.length === 1 && s[0].length === 0;
1347
+ }
1348
+
1349
+ function testFloat(s) {
1350
+ if (FLOAT.test(s)) {
1351
+ var floatValue = parseFloat(s);
1352
+ if (floatValue > MIN_FLOAT && floatValue < MAX_FLOAT) {
1353
+ return true;
1354
+ }
1355
+ }
1356
+ return false;
1357
+ }
1358
+
1359
+ function processResults()
1360
+ {
1361
+ if (_results && _delimiterError)
1362
+ {
1363
+ addError('Delimiter', 'UndetectableDelimiter', 'Unable to auto-detect delimiting character; defaulted to \'' + Papa.DefaultDelimiter + '\'');
1364
+ _delimiterError = false;
1365
+ }
1366
+
1367
+ if (_config.skipEmptyLines)
1368
+ {
1369
+ _results.data = _results.data.filter(function(d) {
1370
+ return !testEmptyLine(d);
1371
+ });
1372
+ }
1373
+
1374
+ if (needsHeaderRow())
1375
+ fillHeaderFields();
1376
+
1377
+ return applyHeaderAndDynamicTypingAndTransformation();
1378
+ }
1379
+
1380
+ function needsHeaderRow()
1381
+ {
1382
+ return _config.header && _fields.length === 0;
1383
+ }
1384
+
1385
+ function fillHeaderFields()
1386
+ {
1387
+ if (!_results)
1388
+ return;
1389
+
1390
+ function addHeader(header, i)
1391
+ {
1392
+ if (isFunction(_config.transformHeader))
1393
+ header = _config.transformHeader(header, i);
1394
+
1395
+ _fields.push(header);
1396
+ }
1397
+
1398
+ if (Array.isArray(_results.data[0]))
1399
+ {
1400
+ for (var i = 0; needsHeaderRow() && i < _results.data.length; i++)
1401
+ _results.data[i].forEach(addHeader);
1402
+
1403
+ _results.data.splice(0, 1);
1404
+ }
1405
+ // if _results.data[0] is not an array, we are in a step where _results.data is the row.
1406
+ else
1407
+ _results.data.forEach(addHeader);
1408
+ }
1409
+
1410
+ function shouldApplyDynamicTyping(field) {
1411
+ // Cache function values to avoid calling it for each row
1412
+ if (_config.dynamicTypingFunction && _config.dynamicTyping[field] === undefined) {
1413
+ _config.dynamicTyping[field] = _config.dynamicTypingFunction(field);
1414
+ }
1415
+ return (_config.dynamicTyping[field] || _config.dynamicTyping) === true;
1416
+ }
1417
+
1418
+ function parseDynamic(field, value)
1419
+ {
1420
+ if (shouldApplyDynamicTyping(field))
1421
+ {
1422
+ if (value === 'true' || value === 'TRUE')
1423
+ return true;
1424
+ else if (value === 'false' || value === 'FALSE')
1425
+ return false;
1426
+ else if (testFloat(value))
1427
+ return parseFloat(value);
1428
+ else if (ISO_DATE.test(value))
1429
+ return new Date(value);
1430
+ else
1431
+ return (value === '' ? null : value);
1432
+ }
1433
+ return value;
1434
+ }
1435
+
1436
+ function applyHeaderAndDynamicTypingAndTransformation()
1437
+ {
1438
+ if (!_results || (!_config.header && !_config.dynamicTyping && !_config.transform))
1439
+ return _results;
1440
+
1441
+ function processRow(rowSource, i)
1442
+ {
1443
+ var row = _config.header ? {} : [];
1444
+
1445
+ var j;
1446
+ for (j = 0; j < rowSource.length; j++)
1447
+ {
1448
+ var field = j;
1449
+ var value = rowSource[j];
1450
+
1451
+ if (_config.header)
1452
+ field = j >= _fields.length ? '__parsed_extra' : _fields[j];
1453
+
1454
+ if (_config.transform)
1455
+ value = _config.transform(value,field);
1456
+
1457
+ value = parseDynamic(field, value);
1458
+
1459
+ if (field === '__parsed_extra')
1460
+ {
1461
+ row[field] = row[field] || [];
1462
+ row[field].push(value);
1463
+ }
1464
+ else
1465
+ row[field] = value;
1466
+ }
1467
+
1468
+
1469
+ if (_config.header)
1470
+ {
1471
+ if (j > _fields.length)
1472
+ addError('FieldMismatch', 'TooManyFields', 'Too many fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i);
1473
+ else if (j < _fields.length)
1474
+ addError('FieldMismatch', 'TooFewFields', 'Too few fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i);
1475
+ }
1476
+
1477
+ return row;
1478
+ }
1479
+
1480
+ var incrementBy = 1;
1481
+ if (!_results.data.length || Array.isArray(_results.data[0]))
1482
+ {
1483
+ _results.data = _results.data.map(processRow);
1484
+ incrementBy = _results.data.length;
1485
+ }
1486
+ else
1487
+ _results.data = processRow(_results.data, 0);
1488
+
1489
+
1490
+ if (_config.header && _results.meta)
1491
+ _results.meta.fields = _fields;
1492
+
1493
+ _rowCounter += incrementBy;
1494
+ return _results;
1495
+ }
1496
+
1497
+ function guessDelimiter(input, newline, skipEmptyLines, comments, delimitersToGuess) {
1498
+ var bestDelim, bestDelta, fieldCountPrevRow, maxFieldCount;
1499
+
1500
+ delimitersToGuess = delimitersToGuess || [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP];
1501
+
1502
+ for (var i = 0; i < delimitersToGuess.length; i++) {
1503
+ var delim = delimitersToGuess[i];
1504
+ var delta = 0, avgFieldCount = 0, emptyLinesCount = 0;
1505
+ fieldCountPrevRow = undefined;
1506
+
1507
+ var preview = new Parser({
1508
+ comments: comments,
1509
+ delimiter: delim,
1510
+ newline: newline,
1511
+ preview: 10
1512
+ }).parse(input);
1513
+
1514
+ for (var j = 0; j < preview.data.length; j++) {
1515
+ if (skipEmptyLines && testEmptyLine(preview.data[j])) {
1516
+ emptyLinesCount++;
1517
+ continue;
1518
+ }
1519
+ var fieldCount = preview.data[j].length;
1520
+ avgFieldCount += fieldCount;
1521
+
1522
+ if (typeof fieldCountPrevRow === 'undefined') {
1523
+ fieldCountPrevRow = fieldCount;
1524
+ continue;
1525
+ }
1526
+ else if (fieldCount > 0) {
1527
+ delta += Math.abs(fieldCount - fieldCountPrevRow);
1528
+ fieldCountPrevRow = fieldCount;
1529
+ }
1530
+ }
1531
+
1532
+ if (preview.data.length > 0)
1533
+ avgFieldCount /= (preview.data.length - emptyLinesCount);
1534
+
1535
+ if ((typeof bestDelta === 'undefined' || delta <= bestDelta)
1536
+ && (typeof maxFieldCount === 'undefined' || avgFieldCount > maxFieldCount) && avgFieldCount > 1.99) {
1537
+ bestDelta = delta;
1538
+ bestDelim = delim;
1539
+ maxFieldCount = avgFieldCount;
1540
+ }
1541
+ }
1542
+
1543
+ _config.delimiter = bestDelim;
1544
+
1545
+ return {
1546
+ successful: !!bestDelim,
1547
+ bestDelimiter: bestDelim
1548
+ };
1549
+ }
1550
+
1551
+ function addError(type, code, msg, row)
1552
+ {
1553
+ var error = {
1554
+ type: type,
1555
+ code: code,
1556
+ message: msg
1557
+ };
1558
+ if(row !== undefined) {
1559
+ error.row = row;
1560
+ }
1561
+ _results.errors.push(error);
1562
+ }
1563
+ }
1564
+
1565
+ /** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions */
1566
+ function escapeRegExp(string)
1567
+ {
1568
+ return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
1569
+ }
1570
+
1571
+ /** The core parser implements speedy and correct CSV parsing */
1572
+ function Parser(config)
1573
+ {
1574
+ // Unpack the config object
1575
+ config = config || {};
1576
+ var delim = config.delimiter;
1577
+ var newline = config.newline;
1578
+ var comments = config.comments;
1579
+ var step = config.step;
1580
+ var preview = config.preview;
1581
+ var fastMode = config.fastMode;
1582
+ var quoteChar;
1583
+ var renamedHeaders = null;
1584
+ var headerParsed = false;
1585
+
1586
+ if (config.quoteChar === undefined || config.quoteChar === null) {
1587
+ quoteChar = '"';
1588
+ } else {
1589
+ quoteChar = config.quoteChar;
1590
+ }
1591
+ var escapeChar = quoteChar;
1592
+ if (config.escapeChar !== undefined) {
1593
+ escapeChar = config.escapeChar;
1594
+ }
1595
+
1596
+ // Delimiter must be valid
1597
+ if (typeof delim !== 'string'
1598
+ || Papa.BAD_DELIMITERS.indexOf(delim) > -1)
1599
+ delim = ',';
1600
+
1601
+ // Comment character must be valid
1602
+ if (comments === delim)
1603
+ throw new Error('Comment character same as delimiter');
1604
+ else if (comments === true)
1605
+ comments = '#';
1606
+ else if (typeof comments !== 'string'
1607
+ || Papa.BAD_DELIMITERS.indexOf(comments) > -1)
1608
+ comments = false;
1609
+
1610
+ // Newline must be valid: \r, \n, or \r\n
1611
+ if (newline !== '\n' && newline !== '\r' && newline !== '\r\n')
1612
+ newline = '\n';
1613
+
1614
+ // We're gonna need these at the Parser scope
1615
+ var cursor = 0;
1616
+ var aborted = false;
1617
+
1618
+ this.parse = function(input, baseIndex, ignoreLastRow)
1619
+ {
1620
+ // For some reason, in Chrome, this speeds things up (!?)
1621
+ if (typeof input !== 'string')
1622
+ throw new Error('Input must be a string');
1623
+
1624
+ // We don't need to compute some of these every time parse() is called,
1625
+ // but having them in a more local scope seems to perform better
1626
+ var inputLen = input.length,
1627
+ delimLen = delim.length,
1628
+ newlineLen = newline.length,
1629
+ commentsLen = comments.length;
1630
+ var stepIsFunction = isFunction(step);
1631
+
1632
+ // Establish starting state
1633
+ cursor = 0;
1634
+ var data = [], errors = [], row = [], lastCursor = 0;
1635
+
1636
+ if (!input)
1637
+ return returnable();
1638
+
1639
+ if (fastMode || (fastMode !== false && input.indexOf(quoteChar) === -1))
1640
+ {
1641
+ var rows = input.split(newline);
1642
+ for (var i = 0; i < rows.length; i++)
1643
+ {
1644
+ row = rows[i];
1645
+ cursor += row.length;
1646
+
1647
+ if (i !== rows.length - 1)
1648
+ cursor += newline.length;
1649
+ else if (ignoreLastRow)
1650
+ return returnable();
1651
+ if (comments && row.substring(0, commentsLen) === comments)
1652
+ continue;
1653
+ if (stepIsFunction)
1654
+ {
1655
+ data = [];
1656
+ pushRow(row.split(delim));
1657
+ doStep();
1658
+ if (aborted)
1659
+ return returnable();
1660
+ }
1661
+ else
1662
+ pushRow(row.split(delim));
1663
+ if (preview && i >= preview)
1664
+ {
1665
+ data = data.slice(0, preview);
1666
+ return returnable(true);
1667
+ }
1668
+ }
1669
+ return returnable();
1670
+ }
1671
+
1672
+ var nextDelim = input.indexOf(delim, cursor);
1673
+ var nextNewline = input.indexOf(newline, cursor);
1674
+ var quoteCharRegex = new RegExp(escapeRegExp(escapeChar) + escapeRegExp(quoteChar), 'g');
1675
+ var quoteSearch = input.indexOf(quoteChar, cursor);
1676
+
1677
+ // Parser loop
1678
+ for (;;)
1679
+ {
1680
+ // Field has opening quote
1681
+ if (input[cursor] === quoteChar)
1682
+ {
1683
+ // Start our search for the closing quote where the cursor is
1684
+ quoteSearch = cursor;
1685
+
1686
+ // Skip the opening quote
1687
+ cursor++;
1688
+
1689
+ for (;;)
1690
+ {
1691
+ // Find closing quote
1692
+ quoteSearch = input.indexOf(quoteChar, quoteSearch + 1);
1693
+
1694
+ //No other quotes are found - no other delimiters
1695
+ if (quoteSearch === -1)
1696
+ {
1697
+ if (!ignoreLastRow) {
1698
+ // No closing quote... what a pity
1699
+ errors.push({
1700
+ type: 'Quotes',
1701
+ code: 'MissingQuotes',
1702
+ message: 'Quoted field unterminated',
1703
+ row: data.length, // row has yet to be inserted
1704
+ index: cursor
1705
+ });
1706
+ }
1707
+ return finish();
1708
+ }
1709
+
1710
+ // Closing quote at EOF
1711
+ if (quoteSearch === inputLen - 1)
1712
+ {
1713
+ var value = input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar);
1714
+ return finish(value);
1715
+ }
1716
+
1717
+ // If this quote is escaped, it's part of the data; skip it
1718
+ // If the quote character is the escape character, then check if the next character is the escape character
1719
+ if (quoteChar === escapeChar && input[quoteSearch + 1] === escapeChar)
1720
+ {
1721
+ quoteSearch++;
1722
+ continue;
1723
+ }
1724
+
1725
+ // If the quote character is not the escape character, then check if the previous character was the escape character
1726
+ if (quoteChar !== escapeChar && quoteSearch !== 0 && input[quoteSearch - 1] === escapeChar)
1727
+ {
1728
+ continue;
1729
+ }
1730
+
1731
+ if(nextDelim !== -1 && nextDelim < (quoteSearch + 1)) {
1732
+ nextDelim = input.indexOf(delim, (quoteSearch + 1));
1733
+ }
1734
+ if(nextNewline !== -1 && nextNewline < (quoteSearch + 1)) {
1735
+ nextNewline = input.indexOf(newline, (quoteSearch + 1));
1736
+ }
1737
+ // Check up to nextDelim or nextNewline, whichever is closest
1738
+ var checkUpTo = nextNewline === -1 ? nextDelim : Math.min(nextDelim, nextNewline);
1739
+ var spacesBetweenQuoteAndDelimiter = extraSpaces(checkUpTo);
1740
+
1741
+ // Closing quote followed by delimiter or 'unnecessary spaces + delimiter'
1742
+ if (input.substr(quoteSearch + 1 + spacesBetweenQuoteAndDelimiter, delimLen) === delim)
1743
+ {
1744
+ row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar));
1745
+ cursor = quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen;
1746
+
1747
+ // If char after following delimiter is not quoteChar, we find next quote char position
1748
+ if (input[quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen] !== quoteChar)
1749
+ {
1750
+ quoteSearch = input.indexOf(quoteChar, cursor);
1751
+ }
1752
+ nextDelim = input.indexOf(delim, cursor);
1753
+ nextNewline = input.indexOf(newline, cursor);
1754
+ break;
1755
+ }
1756
+
1757
+ var spacesBetweenQuoteAndNewLine = extraSpaces(nextNewline);
1758
+
1759
+ // Closing quote followed by newline or 'unnecessary spaces + newLine'
1760
+ if (input.substring(quoteSearch + 1 + spacesBetweenQuoteAndNewLine, quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen) === newline)
1761
+ {
1762
+ row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar));
1763
+ saveRow(quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen);
1764
+ nextDelim = input.indexOf(delim, cursor); // because we may have skipped the nextDelim in the quoted field
1765
+ quoteSearch = input.indexOf(quoteChar, cursor); // we search for first quote in next line
1766
+
1767
+ if (stepIsFunction)
1768
+ {
1769
+ doStep();
1770
+ if (aborted)
1771
+ return returnable();
1772
+ }
1773
+
1774
+ if (preview && data.length >= preview)
1775
+ return returnable(true);
1776
+
1777
+ break;
1778
+ }
1779
+
1780
+
1781
+ // Checks for valid closing quotes are complete (escaped quotes or quote followed by EOF/delimiter/newline) -- assume these quotes are part of an invalid text string
1782
+ errors.push({
1783
+ type: 'Quotes',
1784
+ code: 'InvalidQuotes',
1785
+ message: 'Trailing quote on quoted field is malformed',
1786
+ row: data.length, // row has yet to be inserted
1787
+ index: cursor
1788
+ });
1789
+
1790
+ quoteSearch++;
1791
+ continue;
1792
+
1793
+ }
1794
+
1795
+ continue;
1796
+ }
1797
+
1798
+ // Comment found at start of new line
1799
+ if (comments && row.length === 0 && input.substring(cursor, cursor + commentsLen) === comments)
1800
+ {
1801
+ if (nextNewline === -1) // Comment ends at EOF
1802
+ return returnable();
1803
+ cursor = nextNewline + newlineLen;
1804
+ nextNewline = input.indexOf(newline, cursor);
1805
+ nextDelim = input.indexOf(delim, cursor);
1806
+ continue;
1807
+ }
1808
+
1809
+ // Next delimiter comes before next newline, so we've reached end of field
1810
+ if (nextDelim !== -1 && (nextDelim < nextNewline || nextNewline === -1))
1811
+ {
1812
+ row.push(input.substring(cursor, nextDelim));
1813
+ cursor = nextDelim + delimLen;
1814
+ // we look for next delimiter char
1815
+ nextDelim = input.indexOf(delim, cursor);
1816
+ continue;
1817
+ }
1818
+
1819
+ // End of row
1820
+ if (nextNewline !== -1)
1821
+ {
1822
+ row.push(input.substring(cursor, nextNewline));
1823
+ saveRow(nextNewline + newlineLen);
1824
+
1825
+ if (stepIsFunction)
1826
+ {
1827
+ doStep();
1828
+ if (aborted)
1829
+ return returnable();
1830
+ }
1831
+
1832
+ if (preview && data.length >= preview)
1833
+ return returnable(true);
1834
+
1835
+ continue;
1836
+ }
1837
+
1838
+ break;
1839
+ }
1840
+
1841
+ return finish();
1842
+
1843
+
1844
+ function pushRow(row)
1845
+ {
1846
+ data.push(row);
1847
+ lastCursor = cursor;
1848
+ }
1849
+
1850
+ /**
1851
+ * checks if there are extra spaces after closing quote and given index without any text
1852
+ * if Yes, returns the number of spaces
1853
+ */
1854
+ function extraSpaces(index) {
1855
+ var spaceLength = 0;
1856
+ if (index !== -1) {
1857
+ var textBetweenClosingQuoteAndIndex = input.substring(quoteSearch + 1, index);
1858
+ if (textBetweenClosingQuoteAndIndex && textBetweenClosingQuoteAndIndex.trim() === '') {
1859
+ spaceLength = textBetweenClosingQuoteAndIndex.length;
1860
+ }
1861
+ }
1862
+ return spaceLength;
1863
+ }
1864
+
1865
+ /**
1866
+ * Appends the remaining input from cursor to the end into
1867
+ * row, saves the row, calls step, and returns the results.
1868
+ */
1869
+ function finish(value)
1870
+ {
1871
+ if (ignoreLastRow)
1872
+ return returnable();
1873
+ if (typeof value === 'undefined')
1874
+ value = input.substring(cursor);
1875
+ row.push(value);
1876
+ cursor = inputLen; // important in case parsing is paused
1877
+ pushRow(row);
1878
+ if (stepIsFunction)
1879
+ doStep();
1880
+ return returnable();
1881
+ }
1882
+
1883
+ /**
1884
+ * Appends the current row to the results. It sets the cursor
1885
+ * to newCursor and finds the nextNewline. The caller should
1886
+ * take care to execute user's step function and check for
1887
+ * preview and end parsing if necessary.
1888
+ */
1889
+ function saveRow(newCursor)
1890
+ {
1891
+ cursor = newCursor;
1892
+ pushRow(row);
1893
+ row = [];
1894
+ nextNewline = input.indexOf(newline, cursor);
1895
+ }
1896
+
1897
+ /** Returns an object with the results, errors, and meta. */
1898
+ function returnable(stopped)
1899
+ {
1900
+ if (config.header && !baseIndex && data.length && !headerParsed)
1901
+ {
1902
+ const result = data[0];
1903
+ const headerCount = Object.create(null); // To track the count of each base header
1904
+ const usedHeaders = new Set(result); // To track used headers and avoid duplicates
1905
+ let duplicateHeaders = false;
1906
+
1907
+ for (let i = 0; i < result.length; i++) {
1908
+ let header = result[i];
1909
+ if (isFunction(config.transformHeader))
1910
+ header = config.transformHeader(header, i);
1911
+
1912
+ if (!headerCount[header]) {
1913
+ headerCount[header] = 1;
1914
+ result[i] = header;
1915
+ } else {
1916
+ let newHeader;
1917
+ let suffixCount = headerCount[header];
1918
+
1919
+ // Find a unique new header
1920
+ do {
1921
+ newHeader = `${header}_${suffixCount}`;
1922
+ suffixCount++;
1923
+ } while (usedHeaders.has(newHeader));
1924
+
1925
+ usedHeaders.add(newHeader); // Mark this new Header as used
1926
+ result[i] = newHeader;
1927
+ headerCount[header]++;
1928
+ duplicateHeaders = true;
1929
+ if (renamedHeaders === null) {
1930
+ renamedHeaders = {};
1931
+ }
1932
+ renamedHeaders[newHeader] = header;
1933
+ }
1934
+
1935
+ usedHeaders.add(header); // Ensure the original header is marked as used
1936
+ }
1937
+ if (duplicateHeaders) {
1938
+ console.warn('Duplicate headers found and renamed.');
1939
+ }
1940
+ headerParsed = true;
1941
+ }
1942
+ return {
1943
+ data: data,
1944
+ errors: errors,
1945
+ meta: {
1946
+ delimiter: delim,
1947
+ linebreak: newline,
1948
+ aborted: aborted,
1949
+ truncated: !!stopped,
1950
+ cursor: lastCursor + (baseIndex || 0),
1951
+ renamedHeaders: renamedHeaders
1952
+ }
1953
+ };
1954
+ }
1955
+
1956
+ /** Executes the user's step function and resets data & errors. */
1957
+ function doStep()
1958
+ {
1959
+ step(returnable());
1960
+ data = [];
1961
+ errors = [];
1962
+ }
1963
+ };
1964
+
1965
+ /** Sets the abort flag */
1966
+ this.abort = function()
1967
+ {
1968
+ aborted = true;
1969
+ };
1970
+
1971
+ /** Gets the cursor position */
1972
+ this.getCharIndex = function()
1973
+ {
1974
+ return cursor;
1975
+ };
1976
+ }
1977
+
1978
+
1979
+ function newWorker()
1980
+ {
1981
+ if (!Papa.WORKERS_SUPPORTED)
1982
+ return false;
1983
+
1984
+ var workerUrl = getWorkerBlob();
1985
+ var w = new global.Worker(workerUrl);
1986
+ w.onmessage = mainThreadReceivedMessage;
1987
+ w.id = workerIdCounter++;
1988
+ workers[w.id] = w;
1989
+ return w;
1990
+ }
1991
+
1992
+ /** Callback when main thread receives a message */
1993
+ function mainThreadReceivedMessage(e)
1994
+ {
1995
+ var msg = e.data;
1996
+ var worker = workers[msg.workerId];
1997
+ var aborted = false;
1998
+
1999
+ if (msg.error)
2000
+ worker.userError(msg.error, msg.file);
2001
+ else if (msg.results && msg.results.data)
2002
+ {
2003
+ var abort = function() {
2004
+ aborted = true;
2005
+ completeWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } });
2006
+ };
2007
+
2008
+ var handle = {
2009
+ abort: abort,
2010
+ pause: notImplemented,
2011
+ resume: notImplemented
2012
+ };
2013
+
2014
+ if (isFunction(worker.userStep))
2015
+ {
2016
+ for (var i = 0; i < msg.results.data.length; i++)
2017
+ {
2018
+ worker.userStep({
2019
+ data: msg.results.data[i],
2020
+ errors: msg.results.errors,
2021
+ meta: msg.results.meta
2022
+ }, handle);
2023
+ if (aborted)
2024
+ break;
2025
+ }
2026
+ delete msg.results; // free memory ASAP
2027
+ }
2028
+ else if (isFunction(worker.userChunk))
2029
+ {
2030
+ worker.userChunk(msg.results, handle, msg.file);
2031
+ delete msg.results;
2032
+ }
2033
+ }
2034
+
2035
+ if (msg.finished && !aborted)
2036
+ completeWorker(msg.workerId, msg.results);
2037
+ }
2038
+
2039
+ function completeWorker(workerId, results) {
2040
+ var worker = workers[workerId];
2041
+ if (isFunction(worker.userComplete))
2042
+ worker.userComplete(results);
2043
+ worker.terminate();
2044
+ delete workers[workerId];
2045
+ }
2046
+
2047
+ function notImplemented() {
2048
+ throw new Error('Not implemented.');
2049
+ }
2050
+
2051
+ /** Callback when worker thread receives a message */
2052
+ function workerThreadReceivedMessage(e)
2053
+ {
2054
+ var msg = e.data;
2055
+
2056
+ if (typeof Papa.WORKER_ID === 'undefined' && msg)
2057
+ Papa.WORKER_ID = msg.workerId;
2058
+
2059
+ if (typeof msg.input === 'string')
2060
+ {
2061
+ global.postMessage({
2062
+ workerId: Papa.WORKER_ID,
2063
+ results: Papa.parse(msg.input, msg.config),
2064
+ finished: true
2065
+ });
2066
+ }
2067
+ else if ((global.File && msg.input instanceof File) || msg.input instanceof Object) // thank you, Safari (see issue #106)
2068
+ {
2069
+ var results = Papa.parse(msg.input, msg.config);
2070
+ if (results)
2071
+ global.postMessage({
2072
+ workerId: Papa.WORKER_ID,
2073
+ results: results,
2074
+ finished: true
2075
+ });
2076
+ }
2077
+ }
2078
+
2079
+ /** Makes a deep copy of an array or object (mostly) */
2080
+ function copy(obj)
2081
+ {
2082
+ if (typeof obj !== 'object' || obj === null)
2083
+ return obj;
2084
+ var cpy = Array.isArray(obj) ? [] : {};
2085
+ for (var key in obj)
2086
+ cpy[key] = copy(obj[key]);
2087
+ return cpy;
2088
+ }
2089
+
2090
+ function bindFunction(f, self)
2091
+ {
2092
+ return function() { f.apply(self, arguments); };
2093
+ }
2094
+ function isFunction(func)
2095
+ {
2096
+ return typeof func === 'function';
2097
+ }
2098
+
2099
+ return Papa;
2100
+ }));
2101
+ } (papaparse));
2102
+
2103
+ var papaparseExports = papaparse.exports;
2104
+ var Papa = /*@__PURE__*/getDefaultExportFromCjs(papaparseExports);
2105
+
2106
+ var EMAIL_NOTIFICATIONS_BASE_URL = "neeto_email_notifications/email_notification";
2107
+ var RESET_EMAIL_NOTIFICATIONS_TO_DEFAULT_URL = "".concat(EMAIL_NOTIFICATIONS_BASE_URL, "/reset_to_default");
2108
+
2109
+ var fetch = function fetch(params) {
2110
+ return axios.get(EMAIL_NOTIFICATIONS_BASE_URL, {
2111
+ params: params
2112
+ });
2113
+ };
2114
+ var update = function update(payload) {
2115
+ return axios.put(EMAIL_NOTIFICATIONS_BASE_URL, payload);
2116
+ };
2117
+ var resetToDefault = function resetToDefault(params) {
2118
+ return axios.post(RESET_EMAIL_NOTIFICATIONS_TO_DEFAULT_URL, params);
2119
+ };
2120
+ var emailNotificationsApi = {
2121
+ fetch: fetch,
2122
+ update: update,
2123
+ resetToDefault: resetToDefault
2124
+ };
2125
+
2126
+ var QUERY_KEYS = {
2127
+ NEETO_EMAIL_NOTIFICATIONS: "neeto-email-notifications"
2128
+ };
2129
+
2130
+ var useFetchEmailNotifications = function useFetchEmailNotifications(params) {
2131
+ return reactQuery.useQuery({
2132
+ queryKey: [QUERY_KEYS.NEETO_EMAIL_NOTIFICATIONS, params["notificationHolderId"], params["customFields"]],
2133
+ queryFn: function queryFn() {
2134
+ return emailNotificationsApi.fetch(params);
2135
+ },
2136
+ staleTime: constants.DEFAULT_STALE_TIME,
2137
+ select: ramda.prop("emailNotification"),
2138
+ enabled: neetoCist.isNotEmpty(params)
2139
+ });
2140
+ };
2141
+ var useUpdateEmailNotification = function useUpdateEmailNotification() {
2142
+ return reactUtils.useMutationWithInvalidation(function (params) {
2143
+ return emailNotificationsApi.update(params);
2144
+ }, {
2145
+ keysToInvalidate: [function (_, _ref) {
2146
+ var notificationHolderId = _ref.notificationHolderId;
2147
+ return [QUERY_KEYS.NEETO_EMAIL_NOTIFICATIONS, notificationHolderId];
2148
+ }]
2149
+ });
2150
+ };
2151
+ var useResetEmailNotificationToDefault = function useResetEmailNotificationToDefault() {
2152
+ return reactUtils.useMutationWithInvalidation(emailNotificationsApi.resetToDefault, {
2153
+ keysToInvalidate: [function (_, _ref2) {
2154
+ var notificationHolderId = _ref2.notificationHolderId,
2155
+ customFields = _ref2.customFields;
2156
+ return [QUERY_KEYS.NEETO_EMAIL_NOTIFICATIONS, notificationHolderId, customFields];
2157
+ }]
2158
+ });
2159
+ };
2160
+
2161
+ exports.Papa = Papa;
2162
+ exports.PropTypes = PropTypes;
2163
+ exports.SvgAvatarPlaceholder = SvgAvatarPlaceholder;
2164
+ exports.useFetchEmailNotifications = useFetchEmailNotifications;
2165
+ exports.useResetEmailNotificationToDefault = useResetEmailNotificationToDefault;
2166
+ exports.useUpdateEmailNotification = useUpdateEmailNotification;
2167
+ //# sourceMappingURL=emailNotificationApi-TbcNMxTw.js.map