@bigbinary/neeto-molecules 1.0.114 → 1.0.115

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,2524 @@
1
+ 'use strict';
2
+
3
+ var React = require('react');
4
+ var formik = require('formik');
5
+ var neetoIcons = require('@bigbinary/neeto-icons');
6
+ var neetoui = require('@bigbinary/neetoui');
7
+ var formik$1 = require('@bigbinary/neetoui/formik');
8
+ var reactI18next = require('react-i18next');
9
+ var i18next = require('i18next');
10
+ var require$$0 = require('stream');
11
+ var ramda = require('ramda');
12
+ var yup = require('yup');
13
+
14
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
15
+
16
+ var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
17
+ var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
18
+
19
+ function _extends() {
20
+ _extends = Object.assign ? Object.assign.bind() : function (target) {
21
+ for (var i = 1; i < arguments.length; i++) {
22
+ var source = arguments[i];
23
+ for (var key in source) {
24
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
25
+ target[key] = source[key];
26
+ }
27
+ }
28
+ }
29
+ return target;
30
+ };
31
+ return _extends.apply(this, arguments);
32
+ }
33
+
34
+ function _arrayLikeToArray(arr, len) {
35
+ if (len == null || len > arr.length) len = arr.length;
36
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
37
+ return arr2;
38
+ }
39
+
40
+ function _arrayWithoutHoles(arr) {
41
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
42
+ }
43
+
44
+ function _iterableToArray(iter) {
45
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
46
+ }
47
+
48
+ function _unsupportedIterableToArray(o, minLen) {
49
+ if (!o) return;
50
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
51
+ var n = Object.prototype.toString.call(o).slice(8, -1);
52
+ if (n === "Object" && o.constructor) n = o.constructor.name;
53
+ if (n === "Map" || n === "Set") return Array.from(o);
54
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
55
+ }
56
+
57
+ function _nonIterableSpread() {
58
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
59
+ }
60
+
61
+ function _toConsumableArray(arr) {
62
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
63
+ }
64
+
65
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
66
+ try {
67
+ var info = gen[key](arg);
68
+ var value = info.value;
69
+ } catch (error) {
70
+ reject(error);
71
+ return;
72
+ }
73
+ if (info.done) {
74
+ resolve(value);
75
+ } else {
76
+ Promise.resolve(value).then(_next, _throw);
77
+ }
78
+ }
79
+ function _asyncToGenerator(fn) {
80
+ return function () {
81
+ var self = this,
82
+ args = arguments;
83
+ return new Promise(function (resolve, reject) {
84
+ var gen = fn.apply(self, args);
85
+ function _next(value) {
86
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
87
+ }
88
+ function _throw(err) {
89
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
90
+ }
91
+ _next(undefined);
92
+ });
93
+ };
94
+ }
95
+
96
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
97
+
98
+ var regeneratorRuntime$1 = {exports: {}};
99
+
100
+ var _typeof = {exports: {}};
101
+
102
+ (function (module) {
103
+ function _typeof(obj) {
104
+ "@babel/helpers - typeof";
105
+
106
+ return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
107
+ return typeof obj;
108
+ } : function (obj) {
109
+ return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
110
+ }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(obj);
111
+ }
112
+ module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
113
+ } (_typeof));
114
+
115
+ (function (module) {
116
+ var _typeof$1 = _typeof.exports["default"];
117
+ function _regeneratorRuntime() {
118
+ module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
119
+ return exports;
120
+ }, module.exports.__esModule = true, module.exports["default"] = module.exports;
121
+ var exports = {},
122
+ Op = Object.prototype,
123
+ hasOwn = Op.hasOwnProperty,
124
+ defineProperty = Object.defineProperty || function (obj, key, desc) {
125
+ obj[key] = desc.value;
126
+ },
127
+ $Symbol = "function" == typeof Symbol ? Symbol : {},
128
+ iteratorSymbol = $Symbol.iterator || "@@iterator",
129
+ asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
130
+ toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
131
+ function define(obj, key, value) {
132
+ return Object.defineProperty(obj, key, {
133
+ value: value,
134
+ enumerable: !0,
135
+ configurable: !0,
136
+ writable: !0
137
+ }), obj[key];
138
+ }
139
+ try {
140
+ define({}, "");
141
+ } catch (err) {
142
+ define = function define(obj, key, value) {
143
+ return obj[key] = value;
144
+ };
145
+ }
146
+ function wrap(innerFn, outerFn, self, tryLocsList) {
147
+ var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
148
+ generator = Object.create(protoGenerator.prototype),
149
+ context = new Context(tryLocsList || []);
150
+ return defineProperty(generator, "_invoke", {
151
+ value: makeInvokeMethod(innerFn, self, context)
152
+ }), generator;
153
+ }
154
+ function tryCatch(fn, obj, arg) {
155
+ try {
156
+ return {
157
+ type: "normal",
158
+ arg: fn.call(obj, arg)
159
+ };
160
+ } catch (err) {
161
+ return {
162
+ type: "throw",
163
+ arg: err
164
+ };
165
+ }
166
+ }
167
+ exports.wrap = wrap;
168
+ var ContinueSentinel = {};
169
+ function Generator() {}
170
+ function GeneratorFunction() {}
171
+ function GeneratorFunctionPrototype() {}
172
+ var IteratorPrototype = {};
173
+ define(IteratorPrototype, iteratorSymbol, function () {
174
+ return this;
175
+ });
176
+ var getProto = Object.getPrototypeOf,
177
+ NativeIteratorPrototype = getProto && getProto(getProto(values([])));
178
+ NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
179
+ var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
180
+ function defineIteratorMethods(prototype) {
181
+ ["next", "throw", "return"].forEach(function (method) {
182
+ define(prototype, method, function (arg) {
183
+ return this._invoke(method, arg);
184
+ });
185
+ });
186
+ }
187
+ function AsyncIterator(generator, PromiseImpl) {
188
+ function invoke(method, arg, resolve, reject) {
189
+ var record = tryCatch(generator[method], generator, arg);
190
+ if ("throw" !== record.type) {
191
+ var result = record.arg,
192
+ value = result.value;
193
+ return value && "object" == _typeof$1(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
194
+ invoke("next", value, resolve, reject);
195
+ }, function (err) {
196
+ invoke("throw", err, resolve, reject);
197
+ }) : PromiseImpl.resolve(value).then(function (unwrapped) {
198
+ result.value = unwrapped, resolve(result);
199
+ }, function (error) {
200
+ return invoke("throw", error, resolve, reject);
201
+ });
202
+ }
203
+ reject(record.arg);
204
+ }
205
+ var previousPromise;
206
+ defineProperty(this, "_invoke", {
207
+ value: function value(method, arg) {
208
+ function callInvokeWithMethodAndArg() {
209
+ return new PromiseImpl(function (resolve, reject) {
210
+ invoke(method, arg, resolve, reject);
211
+ });
212
+ }
213
+ return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
214
+ }
215
+ });
216
+ }
217
+ function makeInvokeMethod(innerFn, self, context) {
218
+ var state = "suspendedStart";
219
+ return function (method, arg) {
220
+ if ("executing" === state) throw new Error("Generator is already running");
221
+ if ("completed" === state) {
222
+ if ("throw" === method) throw arg;
223
+ return doneResult();
224
+ }
225
+ for (context.method = method, context.arg = arg;;) {
226
+ var delegate = context.delegate;
227
+ if (delegate) {
228
+ var delegateResult = maybeInvokeDelegate(delegate, context);
229
+ if (delegateResult) {
230
+ if (delegateResult === ContinueSentinel) continue;
231
+ return delegateResult;
232
+ }
233
+ }
234
+ if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
235
+ if ("suspendedStart" === state) throw state = "completed", context.arg;
236
+ context.dispatchException(context.arg);
237
+ } else "return" === context.method && context.abrupt("return", context.arg);
238
+ state = "executing";
239
+ var record = tryCatch(innerFn, self, context);
240
+ if ("normal" === record.type) {
241
+ if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
242
+ return {
243
+ value: record.arg,
244
+ done: context.done
245
+ };
246
+ }
247
+ "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
248
+ }
249
+ };
250
+ }
251
+ function maybeInvokeDelegate(delegate, context) {
252
+ var methodName = context.method,
253
+ method = delegate.iterator[methodName];
254
+ if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel;
255
+ var record = tryCatch(method, delegate.iterator, context.arg);
256
+ if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
257
+ var info = record.arg;
258
+ return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
259
+ }
260
+ function pushTryEntry(locs) {
261
+ var entry = {
262
+ tryLoc: locs[0]
263
+ };
264
+ 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
265
+ }
266
+ function resetTryEntry(entry) {
267
+ var record = entry.completion || {};
268
+ record.type = "normal", delete record.arg, entry.completion = record;
269
+ }
270
+ function Context(tryLocsList) {
271
+ this.tryEntries = [{
272
+ tryLoc: "root"
273
+ }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
274
+ }
275
+ function values(iterable) {
276
+ if (iterable) {
277
+ var iteratorMethod = iterable[iteratorSymbol];
278
+ if (iteratorMethod) return iteratorMethod.call(iterable);
279
+ if ("function" == typeof iterable.next) return iterable;
280
+ if (!isNaN(iterable.length)) {
281
+ var i = -1,
282
+ next = function next() {
283
+ for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
284
+ return next.value = undefined, next.done = !0, next;
285
+ };
286
+ return next.next = next;
287
+ }
288
+ }
289
+ return {
290
+ next: doneResult
291
+ };
292
+ }
293
+ function doneResult() {
294
+ return {
295
+ value: undefined,
296
+ done: !0
297
+ };
298
+ }
299
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
300
+ value: GeneratorFunctionPrototype,
301
+ configurable: !0
302
+ }), defineProperty(GeneratorFunctionPrototype, "constructor", {
303
+ value: GeneratorFunction,
304
+ configurable: !0
305
+ }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
306
+ var ctor = "function" == typeof genFun && genFun.constructor;
307
+ return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
308
+ }, exports.mark = function (genFun) {
309
+ return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
310
+ }, exports.awrap = function (arg) {
311
+ return {
312
+ __await: arg
313
+ };
314
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
315
+ return this;
316
+ }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
317
+ void 0 === PromiseImpl && (PromiseImpl = Promise);
318
+ var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
319
+ return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
320
+ return result.done ? result.value : iter.next();
321
+ });
322
+ }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
323
+ return this;
324
+ }), define(Gp, "toString", function () {
325
+ return "[object Generator]";
326
+ }), exports.keys = function (val) {
327
+ var object = Object(val),
328
+ keys = [];
329
+ for (var key in object) keys.push(key);
330
+ return keys.reverse(), function next() {
331
+ for (; keys.length;) {
332
+ var key = keys.pop();
333
+ if (key in object) return next.value = key, next.done = !1, next;
334
+ }
335
+ return next.done = !0, next;
336
+ };
337
+ }, exports.values = values, Context.prototype = {
338
+ constructor: Context,
339
+ reset: function reset(skipTempReset) {
340
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
341
+ },
342
+ stop: function stop() {
343
+ this.done = !0;
344
+ var rootRecord = this.tryEntries[0].completion;
345
+ if ("throw" === rootRecord.type) throw rootRecord.arg;
346
+ return this.rval;
347
+ },
348
+ dispatchException: function dispatchException(exception) {
349
+ if (this.done) throw exception;
350
+ var context = this;
351
+ function handle(loc, caught) {
352
+ return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
353
+ }
354
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
355
+ var entry = this.tryEntries[i],
356
+ record = entry.completion;
357
+ if ("root" === entry.tryLoc) return handle("end");
358
+ if (entry.tryLoc <= this.prev) {
359
+ var hasCatch = hasOwn.call(entry, "catchLoc"),
360
+ hasFinally = hasOwn.call(entry, "finallyLoc");
361
+ if (hasCatch && hasFinally) {
362
+ if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
363
+ if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
364
+ } else if (hasCatch) {
365
+ if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
366
+ } else {
367
+ if (!hasFinally) throw new Error("try statement without catch or finally");
368
+ if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
369
+ }
370
+ }
371
+ }
372
+ },
373
+ abrupt: function abrupt(type, arg) {
374
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
375
+ var entry = this.tryEntries[i];
376
+ if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
377
+ var finallyEntry = entry;
378
+ break;
379
+ }
380
+ }
381
+ finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
382
+ var record = finallyEntry ? finallyEntry.completion : {};
383
+ return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
384
+ },
385
+ complete: function complete(record, afterLoc) {
386
+ if ("throw" === record.type) throw record.arg;
387
+ return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
388
+ },
389
+ finish: function finish(finallyLoc) {
390
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
391
+ var entry = this.tryEntries[i];
392
+ if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
393
+ }
394
+ },
395
+ "catch": function _catch(tryLoc) {
396
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
397
+ var entry = this.tryEntries[i];
398
+ if (entry.tryLoc === tryLoc) {
399
+ var record = entry.completion;
400
+ if ("throw" === record.type) {
401
+ var thrown = record.arg;
402
+ resetTryEntry(entry);
403
+ }
404
+ return thrown;
405
+ }
406
+ }
407
+ throw new Error("illegal catch attempt");
408
+ },
409
+ delegateYield: function delegateYield(iterable, resultName, nextLoc) {
410
+ return this.delegate = {
411
+ iterator: values(iterable),
412
+ resultName: resultName,
413
+ nextLoc: nextLoc
414
+ }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
415
+ }
416
+ }, exports;
417
+ }
418
+ module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
419
+ } (regeneratorRuntime$1));
420
+
421
+ // TODO(Babel 8): Remove this file.
422
+
423
+ var runtime = regeneratorRuntime$1.exports();
424
+ var regenerator = runtime;
425
+
426
+ // Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
427
+ try {
428
+ regeneratorRuntime = runtime;
429
+ } catch (accidentalStrictMode) {
430
+ if (typeof globalThis === "object") {
431
+ globalThis.regeneratorRuntime = runtime;
432
+ } else {
433
+ Function("r", "regeneratorRuntime = r")(runtime);
434
+ }
435
+ }
436
+
437
+ var ALLOWED_FILE_PICKER_TYPES = [".csv"];
438
+
439
+ var FilePicker = function FilePicker(_ref) {
440
+ var _ref$types = _ref.types,
441
+ types = _ref$types === void 0 ? [] : _ref$types,
442
+ onChange = _ref.onChange,
443
+ children = _ref.children;
444
+ var inputRef = React.useRef();
445
+ var accept = types.reduce(function (acc, ext) {
446
+ return "".concat(acc, ", ").concat(ext);
447
+ }, "");
448
+ var handleInputChange = function handleInputChange(_ref2) {
449
+ var target = _ref2.target;
450
+ if (!target.files) return;
451
+ onChange(target.files);
452
+
453
+ // This will trigger handleClick when same file is uploaded again.
454
+ inputRef.current.value = "";
455
+ handleClick();
456
+ };
457
+ var handleClick = function handleClick() {
458
+ if (!inputRef.current) return;
459
+ inputRef.current.click();
460
+ };
461
+ return /*#__PURE__*/React__default["default"].createElement(React__default["default"].Fragment, null, /*#__PURE__*/React__default["default"].createElement("div", {
462
+ onClick: handleClick
463
+ }, children), /*#__PURE__*/React__default["default"].createElement("input", {
464
+ accept: accept,
465
+ className: "hidden",
466
+ ref: inputRef,
467
+ type: "file",
468
+ onChange: handleInputChange
469
+ }));
470
+ };
471
+
472
+ var papaparse = {exports: {}};
473
+
474
+ /* @license
475
+ Papa Parse
476
+ v5.4.0
477
+ https://github.com/mholt/PapaParse
478
+ License: MIT
479
+ */
480
+
481
+ (function (module, exports) {
482
+ (function(root, factory)
483
+ {
484
+ /* globals define */
485
+ {
486
+ // Node. Does not work with strict CommonJS, but
487
+ // only CommonJS-like environments that support module.exports,
488
+ // like Node.
489
+ module.exports = factory();
490
+ }
491
+ // in strict mode we cannot access arguments.callee, so we need a named reference to
492
+ // stringify the factory method for the blob worker
493
+ // eslint-disable-next-line func-name
494
+ }(commonjsGlobal, function moduleFactory()
495
+ {
496
+
497
+ var global = (function() {
498
+ // alternative method, similar to `Function('return this')()`
499
+ // but without using `eval` (which is disabled when
500
+ // using Content Security Policy).
501
+
502
+ if (typeof self !== 'undefined') { return self; }
503
+ if (typeof window !== 'undefined') { return window; }
504
+ if (typeof global !== 'undefined') { return global; }
505
+
506
+ // When running tests none of the above have been defined
507
+ return {};
508
+ })();
509
+
510
+
511
+ function getWorkerBlob() {
512
+ var URL = global.URL || global.webkitURL || null;
513
+ var code = moduleFactory.toString();
514
+ 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'})));
515
+ }
516
+
517
+ var IS_WORKER = !global.document && !!global.postMessage,
518
+ IS_PAPA_WORKER = global.IS_PAPA_WORKER || false;
519
+
520
+ var workers = {}, workerIdCounter = 0;
521
+
522
+ var Papa = {};
523
+
524
+ Papa.parse = CsvToJson;
525
+ Papa.unparse = JsonToCsv;
526
+
527
+ Papa.RECORD_SEP = String.fromCharCode(30);
528
+ Papa.UNIT_SEP = String.fromCharCode(31);
529
+ Papa.BYTE_ORDER_MARK = '\ufeff';
530
+ Papa.BAD_DELIMITERS = ['\r', '\n', '"', Papa.BYTE_ORDER_MARK];
531
+ Papa.WORKERS_SUPPORTED = !IS_WORKER && !!global.Worker;
532
+ Papa.NODE_STREAM_INPUT = 1;
533
+
534
+ // Configurable chunk sizes for local and remote files, respectively
535
+ Papa.LocalChunkSize = 1024 * 1024 * 10; // 10 MB
536
+ Papa.RemoteChunkSize = 1024 * 1024 * 5; // 5 MB
537
+ Papa.DefaultDelimiter = ','; // Used if not specified and detection fails
538
+
539
+ // Exposed for testing and development only
540
+ Papa.Parser = Parser;
541
+ Papa.ParserHandle = ParserHandle;
542
+ Papa.NetworkStreamer = NetworkStreamer;
543
+ Papa.FileStreamer = FileStreamer;
544
+ Papa.StringStreamer = StringStreamer;
545
+ Papa.ReadableStreamStreamer = ReadableStreamStreamer;
546
+ if (typeof PAPA_BROWSER_CONTEXT === 'undefined') {
547
+ Papa.DuplexStreamStreamer = DuplexStreamStreamer;
548
+ }
549
+
550
+ if (global.jQuery)
551
+ {
552
+ var $ = global.jQuery;
553
+ $.fn.parse = function(options)
554
+ {
555
+ var config = options.config || {};
556
+ var queue = [];
557
+
558
+ this.each(function(idx)
559
+ {
560
+ var supported = $(this).prop('tagName').toUpperCase() === 'INPUT'
561
+ && $(this).attr('type').toLowerCase() === 'file'
562
+ && global.FileReader;
563
+
564
+ if (!supported || !this.files || this.files.length === 0)
565
+ return true; // continue to next input element
566
+
567
+ for (var i = 0; i < this.files.length; i++)
568
+ {
569
+ queue.push({
570
+ file: this.files[i],
571
+ inputElem: this,
572
+ instanceConfig: $.extend({}, config)
573
+ });
574
+ }
575
+ });
576
+
577
+ parseNextFile(); // begin parsing
578
+ return this; // maintains chainability
579
+
580
+
581
+ function parseNextFile()
582
+ {
583
+ if (queue.length === 0)
584
+ {
585
+ if (isFunction(options.complete))
586
+ options.complete();
587
+ return;
588
+ }
589
+
590
+ var f = queue[0];
591
+
592
+ if (isFunction(options.before))
593
+ {
594
+ var returned = options.before(f.file, f.inputElem);
595
+
596
+ if (typeof returned === 'object')
597
+ {
598
+ if (returned.action === 'abort')
599
+ {
600
+ error('AbortError', f.file, f.inputElem, returned.reason);
601
+ return; // Aborts all queued files immediately
602
+ }
603
+ else if (returned.action === 'skip')
604
+ {
605
+ fileComplete(); // parse the next file in the queue, if any
606
+ return;
607
+ }
608
+ else if (typeof returned.config === 'object')
609
+ f.instanceConfig = $.extend(f.instanceConfig, returned.config);
610
+ }
611
+ else if (returned === 'skip')
612
+ {
613
+ fileComplete(); // parse the next file in the queue, if any
614
+ return;
615
+ }
616
+ }
617
+
618
+ // Wrap up the user's complete callback, if any, so that ours also gets executed
619
+ var userCompleteFunc = f.instanceConfig.complete;
620
+ f.instanceConfig.complete = function(results)
621
+ {
622
+ if (isFunction(userCompleteFunc))
623
+ userCompleteFunc(results, f.file, f.inputElem);
624
+ fileComplete();
625
+ };
626
+
627
+ Papa.parse(f.file, f.instanceConfig);
628
+ }
629
+
630
+ function error(name, file, elem, reason)
631
+ {
632
+ if (isFunction(options.error))
633
+ options.error({name: name}, file, elem, reason);
634
+ }
635
+
636
+ function fileComplete()
637
+ {
638
+ queue.splice(0, 1);
639
+ parseNextFile();
640
+ }
641
+ };
642
+ }
643
+
644
+
645
+ if (IS_PAPA_WORKER)
646
+ {
647
+ global.onmessage = workerThreadReceivedMessage;
648
+ }
649
+
650
+
651
+
652
+
653
+ function CsvToJson(_input, _config)
654
+ {
655
+ _config = _config || {};
656
+ var dynamicTyping = _config.dynamicTyping || false;
657
+ if (isFunction(dynamicTyping)) {
658
+ _config.dynamicTypingFunction = dynamicTyping;
659
+ // Will be filled on first row call
660
+ dynamicTyping = {};
661
+ }
662
+ _config.dynamicTyping = dynamicTyping;
663
+
664
+ _config.transform = isFunction(_config.transform) ? _config.transform : false;
665
+
666
+ if (_config.worker && Papa.WORKERS_SUPPORTED)
667
+ {
668
+ var w = newWorker();
669
+
670
+ w.userStep = _config.step;
671
+ w.userChunk = _config.chunk;
672
+ w.userComplete = _config.complete;
673
+ w.userError = _config.error;
674
+
675
+ _config.step = isFunction(_config.step);
676
+ _config.chunk = isFunction(_config.chunk);
677
+ _config.complete = isFunction(_config.complete);
678
+ _config.error = isFunction(_config.error);
679
+ delete _config.worker; // prevent infinite loop
680
+
681
+ w.postMessage({
682
+ input: _input,
683
+ config: _config,
684
+ workerId: w.id
685
+ });
686
+
687
+ return;
688
+ }
689
+
690
+ var streamer = null;
691
+ if (_input === Papa.NODE_STREAM_INPUT && typeof PAPA_BROWSER_CONTEXT === 'undefined')
692
+ {
693
+ // create a node Duplex stream for use
694
+ // with .pipe
695
+ streamer = new DuplexStreamStreamer(_config);
696
+ return streamer.getStream();
697
+ }
698
+ else if (typeof _input === 'string')
699
+ {
700
+ _input = stripBom(_input);
701
+ if (_config.download)
702
+ streamer = new NetworkStreamer(_config);
703
+ else
704
+ streamer = new StringStreamer(_config);
705
+ }
706
+ else if (_input.readable === true && isFunction(_input.read) && isFunction(_input.on))
707
+ {
708
+ streamer = new ReadableStreamStreamer(_config);
709
+ }
710
+ else if ((global.File && _input instanceof File) || _input instanceof Object) // ...Safari. (see issue #106)
711
+ streamer = new FileStreamer(_config);
712
+
713
+ return streamer.stream(_input);
714
+
715
+ // Strip character from UTF-8 BOM encoded files that cause issue parsing the file
716
+ function stripBom(string) {
717
+ if (string.charCodeAt(0) === 0xfeff) {
718
+ return string.slice(1);
719
+ }
720
+ return string;
721
+ }
722
+ }
723
+
724
+
725
+
726
+
727
+
728
+
729
+ function JsonToCsv(_input, _config)
730
+ {
731
+ // Default configuration
732
+
733
+ /** whether to surround every datum with quotes */
734
+ var _quotes = false;
735
+
736
+ /** whether to write headers */
737
+ var _writeHeader = true;
738
+
739
+ /** delimiting character(s) */
740
+ var _delimiter = ',';
741
+
742
+ /** newline character(s) */
743
+ var _newline = '\r\n';
744
+
745
+ /** quote character */
746
+ var _quoteChar = '"';
747
+
748
+ /** escaped quote character, either "" or <config.escapeChar>" */
749
+ var _escapedQuote = _quoteChar + _quoteChar;
750
+
751
+ /** whether to skip empty lines */
752
+ var _skipEmptyLines = false;
753
+
754
+ /** the columns (keys) we expect when we unparse objects */
755
+ var _columns = null;
756
+
757
+ /** whether to prevent outputting cells that can be parsed as formulae by spreadsheet software (Excel and LibreOffice) */
758
+ var _escapeFormulae = false;
759
+
760
+ unpackConfig();
761
+
762
+ var quoteCharRegex = new RegExp(escapeRegExp(_quoteChar), 'g');
763
+
764
+ if (typeof _input === 'string')
765
+ _input = JSON.parse(_input);
766
+
767
+ if (Array.isArray(_input))
768
+ {
769
+ if (!_input.length || Array.isArray(_input[0]))
770
+ return serialize(null, _input, _skipEmptyLines);
771
+ else if (typeof _input[0] === 'object')
772
+ return serialize(_columns || Object.keys(_input[0]), _input, _skipEmptyLines);
773
+ }
774
+ else if (typeof _input === 'object')
775
+ {
776
+ if (typeof _input.data === 'string')
777
+ _input.data = JSON.parse(_input.data);
778
+
779
+ if (Array.isArray(_input.data))
780
+ {
781
+ if (!_input.fields)
782
+ _input.fields = _input.meta && _input.meta.fields || _columns;
783
+
784
+ if (!_input.fields)
785
+ _input.fields = Array.isArray(_input.data[0])
786
+ ? _input.fields
787
+ : typeof _input.data[0] === 'object'
788
+ ? Object.keys(_input.data[0])
789
+ : [];
790
+
791
+ if (!(Array.isArray(_input.data[0])) && typeof _input.data[0] !== 'object')
792
+ _input.data = [_input.data]; // handles input like [1,2,3] or ['asdf']
793
+ }
794
+
795
+ return serialize(_input.fields || [], _input.data || [], _skipEmptyLines);
796
+ }
797
+
798
+ // Default (any valid paths should return before this)
799
+ throw new Error('Unable to serialize unrecognized input');
800
+
801
+
802
+ function unpackConfig()
803
+ {
804
+ if (typeof _config !== 'object')
805
+ return;
806
+
807
+ if (typeof _config.delimiter === 'string'
808
+ && !Papa.BAD_DELIMITERS.filter(function(value) { return _config.delimiter.indexOf(value) !== -1; }).length)
809
+ {
810
+ _delimiter = _config.delimiter;
811
+ }
812
+
813
+ if (typeof _config.quotes === 'boolean'
814
+ || typeof _config.quotes === 'function'
815
+ || Array.isArray(_config.quotes))
816
+ _quotes = _config.quotes;
817
+
818
+ if (typeof _config.skipEmptyLines === 'boolean'
819
+ || typeof _config.skipEmptyLines === 'string')
820
+ _skipEmptyLines = _config.skipEmptyLines;
821
+
822
+ if (typeof _config.newline === 'string')
823
+ _newline = _config.newline;
824
+
825
+ if (typeof _config.quoteChar === 'string')
826
+ _quoteChar = _config.quoteChar;
827
+
828
+ if (typeof _config.header === 'boolean')
829
+ _writeHeader = _config.header;
830
+
831
+ if (Array.isArray(_config.columns)) {
832
+
833
+ if (_config.columns.length === 0) throw new Error('Option columns is empty');
834
+
835
+ _columns = _config.columns;
836
+ }
837
+
838
+ if (_config.escapeChar !== undefined) {
839
+ _escapedQuote = _config.escapeChar + _quoteChar;
840
+ }
841
+
842
+ if (typeof _config.escapeFormulae === 'boolean' || _config.escapeFormulae instanceof RegExp) {
843
+ _escapeFormulae = _config.escapeFormulae instanceof RegExp ? _config.escapeFormulae : /^[=+\-@\t\r].*$/;
844
+ }
845
+ }
846
+
847
+ /** The double for loop that iterates the data and writes out a CSV string including header row */
848
+ function serialize(fields, data, skipEmptyLines)
849
+ {
850
+ var csv = '';
851
+
852
+ if (typeof fields === 'string')
853
+ fields = JSON.parse(fields);
854
+ if (typeof data === 'string')
855
+ data = JSON.parse(data);
856
+
857
+ var hasHeader = Array.isArray(fields) && fields.length > 0;
858
+ var dataKeyedByField = !(Array.isArray(data[0]));
859
+
860
+ // If there a header row, write it first
861
+ if (hasHeader && _writeHeader)
862
+ {
863
+ for (var i = 0; i < fields.length; i++)
864
+ {
865
+ if (i > 0)
866
+ csv += _delimiter;
867
+ csv += safe(fields[i], i);
868
+ }
869
+ if (data.length > 0)
870
+ csv += _newline;
871
+ }
872
+
873
+ // Then write out the data
874
+ for (var row = 0; row < data.length; row++)
875
+ {
876
+ var maxCol = hasHeader ? fields.length : data[row].length;
877
+
878
+ var emptyLine = false;
879
+ var nullLine = hasHeader ? Object.keys(data[row]).length === 0 : data[row].length === 0;
880
+ if (skipEmptyLines && !hasHeader)
881
+ {
882
+ emptyLine = skipEmptyLines === 'greedy' ? data[row].join('').trim() === '' : data[row].length === 1 && data[row][0].length === 0;
883
+ }
884
+ if (skipEmptyLines === 'greedy' && hasHeader) {
885
+ var line = [];
886
+ for (var c = 0; c < maxCol; c++) {
887
+ var cx = dataKeyedByField ? fields[c] : c;
888
+ line.push(data[row][cx]);
889
+ }
890
+ emptyLine = line.join('').trim() === '';
891
+ }
892
+ if (!emptyLine)
893
+ {
894
+ for (var col = 0; col < maxCol; col++)
895
+ {
896
+ if (col > 0 && !nullLine)
897
+ csv += _delimiter;
898
+ var colIdx = hasHeader && dataKeyedByField ? fields[col] : col;
899
+ csv += safe(data[row][colIdx], col);
900
+ }
901
+ if (row < data.length - 1 && (!skipEmptyLines || (maxCol > 0 && !nullLine)))
902
+ {
903
+ csv += _newline;
904
+ }
905
+ }
906
+ }
907
+ return csv;
908
+ }
909
+
910
+ /** Encloses a value around quotes if needed (makes a value safe for CSV insertion) */
911
+ function safe(str, col)
912
+ {
913
+ if (typeof str === 'undefined' || str === null)
914
+ return '';
915
+
916
+ if (str.constructor === Date)
917
+ return JSON.stringify(str).slice(1, 25);
918
+
919
+ var needsQuotes = false;
920
+
921
+ if (_escapeFormulae && typeof str === "string" && _escapeFormulae.test(str)) {
922
+ str = "'" + str;
923
+ needsQuotes = true;
924
+ }
925
+
926
+ var escapedQuoteStr = str.toString().replace(quoteCharRegex, _escapedQuote);
927
+
928
+ needsQuotes = needsQuotes
929
+ || _quotes === true
930
+ || (typeof _quotes === 'function' && _quotes(str, col))
931
+ || (Array.isArray(_quotes) && _quotes[col])
932
+ || hasAny(escapedQuoteStr, Papa.BAD_DELIMITERS)
933
+ || escapedQuoteStr.indexOf(_delimiter) > -1
934
+ || escapedQuoteStr.charAt(0) === ' '
935
+ || escapedQuoteStr.charAt(escapedQuoteStr.length - 1) === ' ';
936
+
937
+ return needsQuotes ? _quoteChar + escapedQuoteStr + _quoteChar : escapedQuoteStr;
938
+ }
939
+
940
+ function hasAny(str, substrings)
941
+ {
942
+ for (var i = 0; i < substrings.length; i++)
943
+ if (str.indexOf(substrings[i]) > -1)
944
+ return true;
945
+ return false;
946
+ }
947
+ }
948
+
949
+ /** ChunkStreamer is the base prototype for various streamer implementations. */
950
+ function ChunkStreamer(config)
951
+ {
952
+ this._handle = null;
953
+ this._finished = false;
954
+ this._completed = false;
955
+ this._halted = false;
956
+ this._input = null;
957
+ this._baseIndex = 0;
958
+ this._partialLine = '';
959
+ this._rowCount = 0;
960
+ this._start = 0;
961
+ this._nextChunk = null;
962
+ this.isFirstChunk = true;
963
+ this._completeResults = {
964
+ data: [],
965
+ errors: [],
966
+ meta: {}
967
+ };
968
+ replaceConfig.call(this, config);
969
+
970
+ this.parseChunk = function(chunk, isFakeChunk)
971
+ {
972
+ // First chunk pre-processing
973
+ if (this.isFirstChunk && isFunction(this._config.beforeFirstChunk))
974
+ {
975
+ var modifiedChunk = this._config.beforeFirstChunk(chunk);
976
+ if (modifiedChunk !== undefined)
977
+ chunk = modifiedChunk;
978
+ }
979
+ this.isFirstChunk = false;
980
+ this._halted = false;
981
+
982
+ // Rejoin the line we likely just split in two by chunking the file
983
+ var aggregate = this._partialLine + chunk;
984
+ this._partialLine = '';
985
+
986
+ var results = this._handle.parse(aggregate, this._baseIndex, !this._finished);
987
+
988
+ if (this._handle.paused() || this._handle.aborted()) {
989
+ this._halted = true;
990
+ return;
991
+ }
992
+
993
+ var lastIndex = results.meta.cursor;
994
+
995
+ if (!this._finished)
996
+ {
997
+ this._partialLine = aggregate.substring(lastIndex - this._baseIndex);
998
+ this._baseIndex = lastIndex;
999
+ }
1000
+
1001
+ if (results && results.data)
1002
+ this._rowCount += results.data.length;
1003
+
1004
+ var finishedIncludingPreview = this._finished || (this._config.preview && this._rowCount >= this._config.preview);
1005
+
1006
+ if (IS_PAPA_WORKER)
1007
+ {
1008
+ global.postMessage({
1009
+ results: results,
1010
+ workerId: Papa.WORKER_ID,
1011
+ finished: finishedIncludingPreview
1012
+ });
1013
+ }
1014
+ else if (isFunction(this._config.chunk) && !isFakeChunk)
1015
+ {
1016
+ this._config.chunk(results, this._handle);
1017
+ if (this._handle.paused() || this._handle.aborted()) {
1018
+ this._halted = true;
1019
+ return;
1020
+ }
1021
+ results = undefined;
1022
+ this._completeResults = undefined;
1023
+ }
1024
+
1025
+ if (!this._config.step && !this._config.chunk) {
1026
+ this._completeResults.data = this._completeResults.data.concat(results.data);
1027
+ this._completeResults.errors = this._completeResults.errors.concat(results.errors);
1028
+ this._completeResults.meta = results.meta;
1029
+ }
1030
+
1031
+ if (!this._completed && finishedIncludingPreview && isFunction(this._config.complete) && (!results || !results.meta.aborted)) {
1032
+ this._config.complete(this._completeResults, this._input);
1033
+ this._completed = true;
1034
+ }
1035
+
1036
+ if (!finishedIncludingPreview && (!results || !results.meta.paused))
1037
+ this._nextChunk();
1038
+
1039
+ return results;
1040
+ };
1041
+
1042
+ this._sendError = function(error)
1043
+ {
1044
+ if (isFunction(this._config.error))
1045
+ this._config.error(error);
1046
+ else if (IS_PAPA_WORKER && this._config.error)
1047
+ {
1048
+ global.postMessage({
1049
+ workerId: Papa.WORKER_ID,
1050
+ error: error,
1051
+ finished: false
1052
+ });
1053
+ }
1054
+ };
1055
+
1056
+ function replaceConfig(config)
1057
+ {
1058
+ // Deep-copy the config so we can edit it
1059
+ var configCopy = copy(config);
1060
+ configCopy.chunkSize = parseInt(configCopy.chunkSize); // parseInt VERY important so we don't concatenate strings!
1061
+ if (!config.step && !config.chunk)
1062
+ configCopy.chunkSize = null; // disable Range header if not streaming; bad values break IIS - see issue #196
1063
+ this._handle = new ParserHandle(configCopy);
1064
+ this._handle.streamer = this;
1065
+ this._config = configCopy; // persist the copy to the caller
1066
+ }
1067
+ }
1068
+
1069
+
1070
+ function NetworkStreamer(config)
1071
+ {
1072
+ config = config || {};
1073
+ if (!config.chunkSize)
1074
+ config.chunkSize = Papa.RemoteChunkSize;
1075
+ ChunkStreamer.call(this, config);
1076
+
1077
+ var xhr;
1078
+
1079
+ if (IS_WORKER)
1080
+ {
1081
+ this._nextChunk = function()
1082
+ {
1083
+ this._readChunk();
1084
+ this._chunkLoaded();
1085
+ };
1086
+ }
1087
+ else
1088
+ {
1089
+ this._nextChunk = function()
1090
+ {
1091
+ this._readChunk();
1092
+ };
1093
+ }
1094
+
1095
+ this.stream = function(url)
1096
+ {
1097
+ this._input = url;
1098
+ this._nextChunk(); // Starts streaming
1099
+ };
1100
+
1101
+ this._readChunk = function()
1102
+ {
1103
+ if (this._finished)
1104
+ {
1105
+ this._chunkLoaded();
1106
+ return;
1107
+ }
1108
+
1109
+ xhr = new XMLHttpRequest();
1110
+
1111
+ if (this._config.withCredentials)
1112
+ {
1113
+ xhr.withCredentials = this._config.withCredentials;
1114
+ }
1115
+
1116
+ if (!IS_WORKER)
1117
+ {
1118
+ xhr.onload = bindFunction(this._chunkLoaded, this);
1119
+ xhr.onerror = bindFunction(this._chunkError, this);
1120
+ }
1121
+
1122
+ xhr.open(this._config.downloadRequestBody ? 'POST' : 'GET', this._input, !IS_WORKER);
1123
+ // Headers can only be set when once the request state is OPENED
1124
+ if (this._config.downloadRequestHeaders)
1125
+ {
1126
+ var headers = this._config.downloadRequestHeaders;
1127
+
1128
+ for (var headerName in headers)
1129
+ {
1130
+ xhr.setRequestHeader(headerName, headers[headerName]);
1131
+ }
1132
+ }
1133
+
1134
+ if (this._config.chunkSize)
1135
+ {
1136
+ var end = this._start + this._config.chunkSize - 1; // minus one because byte range is inclusive
1137
+ xhr.setRequestHeader('Range', 'bytes=' + this._start + '-' + end);
1138
+ }
1139
+
1140
+ try {
1141
+ xhr.send(this._config.downloadRequestBody);
1142
+ }
1143
+ catch (err) {
1144
+ this._chunkError(err.message);
1145
+ }
1146
+
1147
+ if (IS_WORKER && xhr.status === 0)
1148
+ this._chunkError();
1149
+ };
1150
+
1151
+ this._chunkLoaded = function()
1152
+ {
1153
+ if (xhr.readyState !== 4)
1154
+ return;
1155
+
1156
+ if (xhr.status < 200 || xhr.status >= 400)
1157
+ {
1158
+ this._chunkError();
1159
+ return;
1160
+ }
1161
+
1162
+ // Use chunckSize as it may be a diference on reponse lentgh due to characters with more than 1 byte
1163
+ this._start += this._config.chunkSize ? this._config.chunkSize : xhr.responseText.length;
1164
+ this._finished = !this._config.chunkSize || this._start >= getFileSize(xhr);
1165
+ this.parseChunk(xhr.responseText);
1166
+ };
1167
+
1168
+ this._chunkError = function(errorMessage)
1169
+ {
1170
+ var errorText = xhr.statusText || errorMessage;
1171
+ this._sendError(new Error(errorText));
1172
+ };
1173
+
1174
+ function getFileSize(xhr)
1175
+ {
1176
+ var contentRange = xhr.getResponseHeader('Content-Range');
1177
+ if (contentRange === null) { // no content range, then finish!
1178
+ return -1;
1179
+ }
1180
+ return parseInt(contentRange.substring(contentRange.lastIndexOf('/') + 1));
1181
+ }
1182
+ }
1183
+ NetworkStreamer.prototype = Object.create(ChunkStreamer.prototype);
1184
+ NetworkStreamer.prototype.constructor = NetworkStreamer;
1185
+
1186
+
1187
+ function FileStreamer(config)
1188
+ {
1189
+ config = config || {};
1190
+ if (!config.chunkSize)
1191
+ config.chunkSize = Papa.LocalChunkSize;
1192
+ ChunkStreamer.call(this, config);
1193
+
1194
+ var reader, slice;
1195
+
1196
+ // FileReader is better than FileReaderSync (even in worker) - see http://stackoverflow.com/q/24708649/1048862
1197
+ // But Firefox is a pill, too - see issue #76: https://github.com/mholt/PapaParse/issues/76
1198
+ var usingAsyncReader = typeof FileReader !== 'undefined'; // Safari doesn't consider it a function - see issue #105
1199
+
1200
+ this.stream = function(file)
1201
+ {
1202
+ this._input = file;
1203
+ slice = file.slice || file.webkitSlice || file.mozSlice;
1204
+
1205
+ if (usingAsyncReader)
1206
+ {
1207
+ reader = new FileReader(); // Preferred method of reading files, even in workers
1208
+ reader.onload = bindFunction(this._chunkLoaded, this);
1209
+ reader.onerror = bindFunction(this._chunkError, this);
1210
+ }
1211
+ else
1212
+ reader = new FileReaderSync(); // Hack for running in a web worker in Firefox
1213
+
1214
+ this._nextChunk(); // Starts streaming
1215
+ };
1216
+
1217
+ this._nextChunk = function()
1218
+ {
1219
+ if (!this._finished && (!this._config.preview || this._rowCount < this._config.preview))
1220
+ this._readChunk();
1221
+ };
1222
+
1223
+ this._readChunk = function()
1224
+ {
1225
+ var input = this._input;
1226
+ if (this._config.chunkSize)
1227
+ {
1228
+ var end = Math.min(this._start + this._config.chunkSize, this._input.size);
1229
+ input = slice.call(input, this._start, end);
1230
+ }
1231
+ var txt = reader.readAsText(input, this._config.encoding);
1232
+ if (!usingAsyncReader)
1233
+ this._chunkLoaded({ target: { result: txt } }); // mimic the async signature
1234
+ };
1235
+
1236
+ this._chunkLoaded = function(event)
1237
+ {
1238
+ // Very important to increment start each time before handling results
1239
+ this._start += this._config.chunkSize;
1240
+ this._finished = !this._config.chunkSize || this._start >= this._input.size;
1241
+ this.parseChunk(event.target.result);
1242
+ };
1243
+
1244
+ this._chunkError = function()
1245
+ {
1246
+ this._sendError(reader.error);
1247
+ };
1248
+
1249
+ }
1250
+ FileStreamer.prototype = Object.create(ChunkStreamer.prototype);
1251
+ FileStreamer.prototype.constructor = FileStreamer;
1252
+
1253
+
1254
+ function StringStreamer(config)
1255
+ {
1256
+ config = config || {};
1257
+ ChunkStreamer.call(this, config);
1258
+
1259
+ var remaining;
1260
+ this.stream = function(s)
1261
+ {
1262
+ remaining = s;
1263
+ return this._nextChunk();
1264
+ };
1265
+ this._nextChunk = function()
1266
+ {
1267
+ if (this._finished) return;
1268
+ var size = this._config.chunkSize;
1269
+ var chunk;
1270
+ if(size) {
1271
+ chunk = remaining.substring(0, size);
1272
+ remaining = remaining.substring(size);
1273
+ } else {
1274
+ chunk = remaining;
1275
+ remaining = '';
1276
+ }
1277
+ this._finished = !remaining;
1278
+ return this.parseChunk(chunk);
1279
+ };
1280
+ }
1281
+ StringStreamer.prototype = Object.create(StringStreamer.prototype);
1282
+ StringStreamer.prototype.constructor = StringStreamer;
1283
+
1284
+
1285
+ function ReadableStreamStreamer(config)
1286
+ {
1287
+ config = config || {};
1288
+
1289
+ ChunkStreamer.call(this, config);
1290
+
1291
+ var queue = [];
1292
+ var parseOnData = true;
1293
+ var streamHasEnded = false;
1294
+
1295
+ this.pause = function()
1296
+ {
1297
+ ChunkStreamer.prototype.pause.apply(this, arguments);
1298
+ this._input.pause();
1299
+ };
1300
+
1301
+ this.resume = function()
1302
+ {
1303
+ ChunkStreamer.prototype.resume.apply(this, arguments);
1304
+ this._input.resume();
1305
+ };
1306
+
1307
+ this.stream = function(stream)
1308
+ {
1309
+ this._input = stream;
1310
+
1311
+ this._input.on('data', this._streamData);
1312
+ this._input.on('end', this._streamEnd);
1313
+ this._input.on('error', this._streamError);
1314
+ };
1315
+
1316
+ this._checkIsFinished = function()
1317
+ {
1318
+ if (streamHasEnded && queue.length === 1) {
1319
+ this._finished = true;
1320
+ }
1321
+ };
1322
+
1323
+ this._nextChunk = function()
1324
+ {
1325
+ this._checkIsFinished();
1326
+ if (queue.length)
1327
+ {
1328
+ this.parseChunk(queue.shift());
1329
+ }
1330
+ else
1331
+ {
1332
+ parseOnData = true;
1333
+ }
1334
+ };
1335
+
1336
+ this._streamData = bindFunction(function(chunk)
1337
+ {
1338
+ try
1339
+ {
1340
+ queue.push(typeof chunk === 'string' ? chunk : chunk.toString(this._config.encoding));
1341
+
1342
+ if (parseOnData)
1343
+ {
1344
+ parseOnData = false;
1345
+ this._checkIsFinished();
1346
+ this.parseChunk(queue.shift());
1347
+ }
1348
+ }
1349
+ catch (error)
1350
+ {
1351
+ this._streamError(error);
1352
+ }
1353
+ }, this);
1354
+
1355
+ this._streamError = bindFunction(function(error)
1356
+ {
1357
+ this._streamCleanUp();
1358
+ this._sendError(error);
1359
+ }, this);
1360
+
1361
+ this._streamEnd = bindFunction(function()
1362
+ {
1363
+ this._streamCleanUp();
1364
+ streamHasEnded = true;
1365
+ this._streamData('');
1366
+ }, this);
1367
+
1368
+ this._streamCleanUp = bindFunction(function()
1369
+ {
1370
+ this._input.removeListener('data', this._streamData);
1371
+ this._input.removeListener('end', this._streamEnd);
1372
+ this._input.removeListener('error', this._streamError);
1373
+ }, this);
1374
+ }
1375
+ ReadableStreamStreamer.prototype = Object.create(ChunkStreamer.prototype);
1376
+ ReadableStreamStreamer.prototype.constructor = ReadableStreamStreamer;
1377
+
1378
+
1379
+ function DuplexStreamStreamer(_config) {
1380
+ var Duplex = require$$0__default["default"].Duplex;
1381
+ var config = copy(_config);
1382
+ var parseOnWrite = true;
1383
+ var writeStreamHasFinished = false;
1384
+ var parseCallbackQueue = [];
1385
+ var stream = null;
1386
+
1387
+ this._onCsvData = function(results)
1388
+ {
1389
+ var data = results.data;
1390
+ if (!stream.push(data) && !this._handle.paused()) {
1391
+ // the writeable consumer buffer has filled up
1392
+ // so we need to pause until more items
1393
+ // can be processed
1394
+ this._handle.pause();
1395
+ }
1396
+ };
1397
+
1398
+ this._onCsvComplete = function()
1399
+ {
1400
+ // node will finish the read stream when
1401
+ // null is pushed
1402
+ stream.push(null);
1403
+ };
1404
+
1405
+ config.step = bindFunction(this._onCsvData, this);
1406
+ config.complete = bindFunction(this._onCsvComplete, this);
1407
+ ChunkStreamer.call(this, config);
1408
+
1409
+ this._nextChunk = function()
1410
+ {
1411
+ if (writeStreamHasFinished && parseCallbackQueue.length === 1) {
1412
+ this._finished = true;
1413
+ }
1414
+ if (parseCallbackQueue.length) {
1415
+ parseCallbackQueue.shift()();
1416
+ } else {
1417
+ parseOnWrite = true;
1418
+ }
1419
+ };
1420
+
1421
+ this._addToParseQueue = function(chunk, callback)
1422
+ {
1423
+ // add to queue so that we can indicate
1424
+ // completion via callback
1425
+ // node will automatically pause the incoming stream
1426
+ // when too many items have been added without their
1427
+ // callback being invoked
1428
+ parseCallbackQueue.push(bindFunction(function() {
1429
+ this.parseChunk(typeof chunk === 'string' ? chunk : chunk.toString(config.encoding));
1430
+ if (isFunction(callback)) {
1431
+ return callback();
1432
+ }
1433
+ }, this));
1434
+ if (parseOnWrite) {
1435
+ parseOnWrite = false;
1436
+ this._nextChunk();
1437
+ }
1438
+ };
1439
+
1440
+ this._onRead = function()
1441
+ {
1442
+ if (this._handle.paused()) {
1443
+ // the writeable consumer can handle more data
1444
+ // so resume the chunk parsing
1445
+ this._handle.resume();
1446
+ }
1447
+ };
1448
+
1449
+ this._onWrite = function(chunk, encoding, callback)
1450
+ {
1451
+ this._addToParseQueue(chunk, callback);
1452
+ };
1453
+
1454
+ this._onWriteComplete = function()
1455
+ {
1456
+ writeStreamHasFinished = true;
1457
+ // have to write empty string
1458
+ // so parser knows its done
1459
+ this._addToParseQueue('');
1460
+ };
1461
+
1462
+ this.getStream = function()
1463
+ {
1464
+ return stream;
1465
+ };
1466
+ stream = new Duplex({
1467
+ readableObjectMode: true,
1468
+ decodeStrings: false,
1469
+ read: bindFunction(this._onRead, this),
1470
+ write: bindFunction(this._onWrite, this)
1471
+ });
1472
+ stream.once('finish', bindFunction(this._onWriteComplete, this));
1473
+ }
1474
+ if (typeof PAPA_BROWSER_CONTEXT === 'undefined') {
1475
+ DuplexStreamStreamer.prototype = Object.create(ChunkStreamer.prototype);
1476
+ DuplexStreamStreamer.prototype.constructor = DuplexStreamStreamer;
1477
+ }
1478
+
1479
+
1480
+ // Use one ParserHandle per entire CSV file or string
1481
+ function ParserHandle(_config)
1482
+ {
1483
+ // One goal is to minimize the use of regular expressions...
1484
+ var MAX_FLOAT = Math.pow(2, 53);
1485
+ var MIN_FLOAT = -MAX_FLOAT;
1486
+ var FLOAT = /^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/;
1487
+ 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)))$/;
1488
+ var self = this;
1489
+ var _stepCounter = 0; // Number of times step was called (number of rows parsed)
1490
+ var _rowCounter = 0; // Number of rows that have been parsed so far
1491
+ var _input; // The input being parsed
1492
+ var _parser; // The core parser being used
1493
+ var _paused = false; // Whether we are paused or not
1494
+ var _aborted = false; // Whether the parser has aborted or not
1495
+ var _delimiterError; // Temporary state between delimiter detection and processing results
1496
+ var _fields = []; // Fields are from the header row of the input, if there is one
1497
+ var _results = { // The last results returned from the parser
1498
+ data: [],
1499
+ errors: [],
1500
+ meta: {}
1501
+ };
1502
+
1503
+ if (isFunction(_config.step))
1504
+ {
1505
+ var userStep = _config.step;
1506
+ _config.step = function(results)
1507
+ {
1508
+ _results = results;
1509
+
1510
+ if (needsHeaderRow())
1511
+ processResults();
1512
+ else // only call user's step function after header row
1513
+ {
1514
+ processResults();
1515
+
1516
+ // It's possbile that this line was empty and there's no row here after all
1517
+ if (_results.data.length === 0)
1518
+ return;
1519
+
1520
+ _stepCounter += results.data.length;
1521
+ if (_config.preview && _stepCounter > _config.preview)
1522
+ _parser.abort();
1523
+ else {
1524
+ _results.data = _results.data[0];
1525
+ userStep(_results, self);
1526
+ }
1527
+ }
1528
+ };
1529
+ }
1530
+
1531
+ /**
1532
+ * Parses input. Most users won't need, and shouldn't mess with, the baseIndex
1533
+ * and ignoreLastRow parameters. They are used by streamers (wrapper functions)
1534
+ * when an input comes in multiple chunks, like from a file.
1535
+ */
1536
+ this.parse = function(input, baseIndex, ignoreLastRow)
1537
+ {
1538
+ var quoteChar = _config.quoteChar || '"';
1539
+ if (!_config.newline)
1540
+ _config.newline = guessLineEndings(input, quoteChar);
1541
+
1542
+ _delimiterError = false;
1543
+ if (!_config.delimiter)
1544
+ {
1545
+ var delimGuess = guessDelimiter(input, _config.newline, _config.skipEmptyLines, _config.comments, _config.delimitersToGuess);
1546
+ if (delimGuess.successful)
1547
+ _config.delimiter = delimGuess.bestDelimiter;
1548
+ else
1549
+ {
1550
+ _delimiterError = true; // add error after parsing (otherwise it would be overwritten)
1551
+ _config.delimiter = Papa.DefaultDelimiter;
1552
+ }
1553
+ _results.meta.delimiter = _config.delimiter;
1554
+ }
1555
+ else if(isFunction(_config.delimiter))
1556
+ {
1557
+ _config.delimiter = _config.delimiter(input);
1558
+ _results.meta.delimiter = _config.delimiter;
1559
+ }
1560
+
1561
+ var parserConfig = copy(_config);
1562
+ if (_config.preview && _config.header)
1563
+ parserConfig.preview++; // to compensate for header row
1564
+
1565
+ _input = input;
1566
+ _parser = new Parser(parserConfig);
1567
+ _results = _parser.parse(_input, baseIndex, ignoreLastRow);
1568
+ processResults();
1569
+ return _paused ? { meta: { paused: true } } : (_results || { meta: { paused: false } });
1570
+ };
1571
+
1572
+ this.paused = function()
1573
+ {
1574
+ return _paused;
1575
+ };
1576
+
1577
+ this.pause = function()
1578
+ {
1579
+ _paused = true;
1580
+ _parser.abort();
1581
+
1582
+ // If it is streaming via "chunking", the reader will start appending correctly already so no need to substring,
1583
+ // otherwise we can get duplicate content within a row
1584
+ _input = isFunction(_config.chunk) ? "" : _input.substring(_parser.getCharIndex());
1585
+ };
1586
+
1587
+ this.resume = function()
1588
+ {
1589
+ if(self.streamer._halted) {
1590
+ _paused = false;
1591
+ self.streamer.parseChunk(_input, true);
1592
+ } else {
1593
+ // Bugfix: #636 In case the processing hasn't halted yet
1594
+ // wait for it to halt in order to resume
1595
+ setTimeout(self.resume, 3);
1596
+ }
1597
+ };
1598
+
1599
+ this.aborted = function()
1600
+ {
1601
+ return _aborted;
1602
+ };
1603
+
1604
+ this.abort = function()
1605
+ {
1606
+ _aborted = true;
1607
+ _parser.abort();
1608
+ _results.meta.aborted = true;
1609
+ if (isFunction(_config.complete))
1610
+ _config.complete(_results);
1611
+ _input = '';
1612
+ };
1613
+
1614
+ function testEmptyLine(s) {
1615
+ return _config.skipEmptyLines === 'greedy' ? s.join('').trim() === '' : s.length === 1 && s[0].length === 0;
1616
+ }
1617
+
1618
+ function testFloat(s) {
1619
+ if (FLOAT.test(s)) {
1620
+ var floatValue = parseFloat(s);
1621
+ if (floatValue > MIN_FLOAT && floatValue < MAX_FLOAT) {
1622
+ return true;
1623
+ }
1624
+ }
1625
+ return false;
1626
+ }
1627
+
1628
+ function processResults()
1629
+ {
1630
+ if (_results && _delimiterError)
1631
+ {
1632
+ addError('Delimiter', 'UndetectableDelimiter', 'Unable to auto-detect delimiting character; defaulted to \'' + Papa.DefaultDelimiter + '\'');
1633
+ _delimiterError = false;
1634
+ }
1635
+
1636
+ if (_config.skipEmptyLines)
1637
+ {
1638
+ _results.data = _results.data.filter(function(d) {
1639
+ return !testEmptyLine(d);
1640
+ });
1641
+ }
1642
+
1643
+ if (needsHeaderRow())
1644
+ fillHeaderFields();
1645
+
1646
+ return applyHeaderAndDynamicTypingAndTransformation();
1647
+ }
1648
+
1649
+ function needsHeaderRow()
1650
+ {
1651
+ return _config.header && _fields.length === 0;
1652
+ }
1653
+
1654
+ function fillHeaderFields()
1655
+ {
1656
+ if (!_results)
1657
+ return;
1658
+
1659
+ function addHeader(header, i)
1660
+ {
1661
+ if (isFunction(_config.transformHeader))
1662
+ header = _config.transformHeader(header, i);
1663
+
1664
+ _fields.push(header);
1665
+ }
1666
+
1667
+ if (Array.isArray(_results.data[0]))
1668
+ {
1669
+ for (var i = 0; needsHeaderRow() && i < _results.data.length; i++)
1670
+ _results.data[i].forEach(addHeader);
1671
+
1672
+ _results.data.splice(0, 1);
1673
+ }
1674
+ // if _results.data[0] is not an array, we are in a step where _results.data is the row.
1675
+ else
1676
+ _results.data.forEach(addHeader);
1677
+ }
1678
+
1679
+ function shouldApplyDynamicTyping(field) {
1680
+ // Cache function values to avoid calling it for each row
1681
+ if (_config.dynamicTypingFunction && _config.dynamicTyping[field] === undefined) {
1682
+ _config.dynamicTyping[field] = _config.dynamicTypingFunction(field);
1683
+ }
1684
+ return (_config.dynamicTyping[field] || _config.dynamicTyping) === true;
1685
+ }
1686
+
1687
+ function parseDynamic(field, value)
1688
+ {
1689
+ if (shouldApplyDynamicTyping(field))
1690
+ {
1691
+ if (value === 'true' || value === 'TRUE')
1692
+ return true;
1693
+ else if (value === 'false' || value === 'FALSE')
1694
+ return false;
1695
+ else if (testFloat(value))
1696
+ return parseFloat(value);
1697
+ else if (ISO_DATE.test(value))
1698
+ return new Date(value);
1699
+ else
1700
+ return (value === '' ? null : value);
1701
+ }
1702
+ return value;
1703
+ }
1704
+
1705
+ function applyHeaderAndDynamicTypingAndTransformation()
1706
+ {
1707
+ if (!_results || (!_config.header && !_config.dynamicTyping && !_config.transform))
1708
+ return _results;
1709
+
1710
+ function processRow(rowSource, i)
1711
+ {
1712
+ var row = _config.header ? {} : [];
1713
+
1714
+ var j;
1715
+ for (j = 0; j < rowSource.length; j++)
1716
+ {
1717
+ var field = j;
1718
+ var value = rowSource[j];
1719
+
1720
+ if (_config.header)
1721
+ field = j >= _fields.length ? '__parsed_extra' : _fields[j];
1722
+
1723
+ if (_config.transform)
1724
+ value = _config.transform(value,field);
1725
+
1726
+ value = parseDynamic(field, value);
1727
+
1728
+ if (field === '__parsed_extra')
1729
+ {
1730
+ row[field] = row[field] || [];
1731
+ row[field].push(value);
1732
+ }
1733
+ else
1734
+ row[field] = value;
1735
+ }
1736
+
1737
+
1738
+ if (_config.header)
1739
+ {
1740
+ if (j > _fields.length)
1741
+ addError('FieldMismatch', 'TooManyFields', 'Too many fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i);
1742
+ else if (j < _fields.length)
1743
+ addError('FieldMismatch', 'TooFewFields', 'Too few fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i);
1744
+ }
1745
+
1746
+ return row;
1747
+ }
1748
+
1749
+ var incrementBy = 1;
1750
+ if (!_results.data.length || Array.isArray(_results.data[0]))
1751
+ {
1752
+ _results.data = _results.data.map(processRow);
1753
+ incrementBy = _results.data.length;
1754
+ }
1755
+ else
1756
+ _results.data = processRow(_results.data, 0);
1757
+
1758
+
1759
+ if (_config.header && _results.meta)
1760
+ _results.meta.fields = _fields;
1761
+
1762
+ _rowCounter += incrementBy;
1763
+ return _results;
1764
+ }
1765
+
1766
+ function guessDelimiter(input, newline, skipEmptyLines, comments, delimitersToGuess) {
1767
+ var bestDelim, bestDelta, fieldCountPrevRow, maxFieldCount;
1768
+
1769
+ delimitersToGuess = delimitersToGuess || [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP];
1770
+
1771
+ for (var i = 0; i < delimitersToGuess.length; i++) {
1772
+ var delim = delimitersToGuess[i];
1773
+ var delta = 0, avgFieldCount = 0, emptyLinesCount = 0;
1774
+ fieldCountPrevRow = undefined;
1775
+
1776
+ var preview = new Parser({
1777
+ comments: comments,
1778
+ delimiter: delim,
1779
+ newline: newline,
1780
+ preview: 10
1781
+ }).parse(input);
1782
+
1783
+ for (var j = 0; j < preview.data.length; j++) {
1784
+ if (skipEmptyLines && testEmptyLine(preview.data[j])) {
1785
+ emptyLinesCount++;
1786
+ continue;
1787
+ }
1788
+ var fieldCount = preview.data[j].length;
1789
+ avgFieldCount += fieldCount;
1790
+
1791
+ if (typeof fieldCountPrevRow === 'undefined') {
1792
+ fieldCountPrevRow = fieldCount;
1793
+ continue;
1794
+ }
1795
+ else if (fieldCount > 0) {
1796
+ delta += Math.abs(fieldCount - fieldCountPrevRow);
1797
+ fieldCountPrevRow = fieldCount;
1798
+ }
1799
+ }
1800
+
1801
+ if (preview.data.length > 0)
1802
+ avgFieldCount /= (preview.data.length - emptyLinesCount);
1803
+
1804
+ if ((typeof bestDelta === 'undefined' || delta <= bestDelta)
1805
+ && (typeof maxFieldCount === 'undefined' || avgFieldCount > maxFieldCount) && avgFieldCount > 1.99) {
1806
+ bestDelta = delta;
1807
+ bestDelim = delim;
1808
+ maxFieldCount = avgFieldCount;
1809
+ }
1810
+ }
1811
+
1812
+ _config.delimiter = bestDelim;
1813
+
1814
+ return {
1815
+ successful: !!bestDelim,
1816
+ bestDelimiter: bestDelim
1817
+ };
1818
+ }
1819
+
1820
+ function guessLineEndings(input, quoteChar)
1821
+ {
1822
+ input = input.substring(0, 1024 * 1024); // max length 1 MB
1823
+ // Replace all the text inside quotes
1824
+ var re = new RegExp(escapeRegExp(quoteChar) + '([^]*?)' + escapeRegExp(quoteChar), 'gm');
1825
+ input = input.replace(re, '');
1826
+
1827
+ var r = input.split('\r');
1828
+
1829
+ var n = input.split('\n');
1830
+
1831
+ var nAppearsFirst = (n.length > 1 && n[0].length < r[0].length);
1832
+
1833
+ if (r.length === 1 || nAppearsFirst)
1834
+ return '\n';
1835
+
1836
+ var numWithN = 0;
1837
+ for (var i = 0; i < r.length; i++)
1838
+ {
1839
+ if (r[i][0] === '\n')
1840
+ numWithN++;
1841
+ }
1842
+
1843
+ return numWithN >= r.length / 2 ? '\r\n' : '\r';
1844
+ }
1845
+
1846
+ function addError(type, code, msg, row)
1847
+ {
1848
+ var error = {
1849
+ type: type,
1850
+ code: code,
1851
+ message: msg
1852
+ };
1853
+ if(row !== undefined) {
1854
+ error.row = row;
1855
+ }
1856
+ _results.errors.push(error);
1857
+ }
1858
+ }
1859
+
1860
+ /** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions */
1861
+ function escapeRegExp(string)
1862
+ {
1863
+ return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
1864
+ }
1865
+
1866
+ /** The core parser implements speedy and correct CSV parsing */
1867
+ function Parser(config)
1868
+ {
1869
+ // Unpack the config object
1870
+ config = config || {};
1871
+ var delim = config.delimiter;
1872
+ var newline = config.newline;
1873
+ var comments = config.comments;
1874
+ var step = config.step;
1875
+ var preview = config.preview;
1876
+ var fastMode = config.fastMode;
1877
+ var quoteChar;
1878
+ if (config.quoteChar === undefined || config.quoteChar === null) {
1879
+ quoteChar = '"';
1880
+ } else {
1881
+ quoteChar = config.quoteChar;
1882
+ }
1883
+ var escapeChar = quoteChar;
1884
+ if (config.escapeChar !== undefined) {
1885
+ escapeChar = config.escapeChar;
1886
+ }
1887
+
1888
+ // Delimiter must be valid
1889
+ if (typeof delim !== 'string'
1890
+ || Papa.BAD_DELIMITERS.indexOf(delim) > -1)
1891
+ delim = ',';
1892
+
1893
+ // Comment character must be valid
1894
+ if (comments === delim)
1895
+ throw new Error('Comment character same as delimiter');
1896
+ else if (comments === true)
1897
+ comments = '#';
1898
+ else if (typeof comments !== 'string'
1899
+ || Papa.BAD_DELIMITERS.indexOf(comments) > -1)
1900
+ comments = false;
1901
+
1902
+ // Newline must be valid: \r, \n, or \r\n
1903
+ if (newline !== '\n' && newline !== '\r' && newline !== '\r\n')
1904
+ newline = '\n';
1905
+
1906
+ // We're gonna need these at the Parser scope
1907
+ var cursor = 0;
1908
+ var aborted = false;
1909
+
1910
+ this.parse = function(input, baseIndex, ignoreLastRow)
1911
+ {
1912
+ // For some reason, in Chrome, this speeds things up (!?)
1913
+ if (typeof input !== 'string')
1914
+ throw new Error('Input must be a string');
1915
+
1916
+ // We don't need to compute some of these every time parse() is called,
1917
+ // but having them in a more local scope seems to perform better
1918
+ var inputLen = input.length,
1919
+ delimLen = delim.length,
1920
+ newlineLen = newline.length,
1921
+ commentsLen = comments.length;
1922
+ var stepIsFunction = isFunction(step);
1923
+
1924
+ // Establish starting state
1925
+ cursor = 0;
1926
+ var data = [], errors = [], row = [], lastCursor = 0;
1927
+
1928
+ if (!input)
1929
+ return returnable();
1930
+
1931
+ // Rename headers if there are duplicates
1932
+ if (config.header)
1933
+ {
1934
+ var firstLine = input.split(newline)[0];
1935
+ var headers = firstLine.split(delim);
1936
+ var separator = '_';
1937
+ var headerMap = [];
1938
+ var headerCount = {};
1939
+ var duplicateHeaders = false;
1940
+
1941
+ for (var j in headers) {
1942
+ var header = headers[j];
1943
+ if (isFunction(config.transformHeader))
1944
+ header = config.transformHeader(header, j);
1945
+ var headerName = header;
1946
+
1947
+ var count = headerCount[header] || 0;
1948
+ if (count > 0) {
1949
+ duplicateHeaders = true;
1950
+ headerName = header + separator + count;
1951
+ }
1952
+ headerCount[header] = count + 1;
1953
+
1954
+ headerMap.push(headerName);
1955
+ }
1956
+ if (duplicateHeaders) {
1957
+ var editedInput = input.split(newline);
1958
+ editedInput[0] = headerMap.join(delim);
1959
+ input = editedInput.join(newline);
1960
+ }
1961
+ }
1962
+ if (fastMode || (fastMode !== false && input.indexOf(quoteChar) === -1))
1963
+ {
1964
+ var rows = input.split(newline);
1965
+ for (var i = 0; i < rows.length; i++)
1966
+ {
1967
+ row = rows[i];
1968
+ cursor += row.length;
1969
+ if (i !== rows.length - 1)
1970
+ cursor += newline.length;
1971
+ else if (ignoreLastRow)
1972
+ return returnable();
1973
+ if (comments && row.substring(0, commentsLen) === comments)
1974
+ continue;
1975
+ if (stepIsFunction)
1976
+ {
1977
+ data = [];
1978
+ pushRow(row.split(delim));
1979
+ doStep();
1980
+ if (aborted)
1981
+ return returnable();
1982
+ }
1983
+ else
1984
+ pushRow(row.split(delim));
1985
+ if (preview && i >= preview)
1986
+ {
1987
+ data = data.slice(0, preview);
1988
+ return returnable(true);
1989
+ }
1990
+ }
1991
+ return returnable();
1992
+ }
1993
+
1994
+ var nextDelim = input.indexOf(delim, cursor);
1995
+ var nextNewline = input.indexOf(newline, cursor);
1996
+ var quoteCharRegex = new RegExp(escapeRegExp(escapeChar) + escapeRegExp(quoteChar), 'g');
1997
+ var quoteSearch = input.indexOf(quoteChar, cursor);
1998
+
1999
+ // Parser loop
2000
+ for (;;)
2001
+ {
2002
+ // Field has opening quote
2003
+ if (input[cursor] === quoteChar)
2004
+ {
2005
+ // Start our search for the closing quote where the cursor is
2006
+ quoteSearch = cursor;
2007
+
2008
+ // Skip the opening quote
2009
+ cursor++;
2010
+
2011
+ for (;;)
2012
+ {
2013
+ // Find closing quote
2014
+ quoteSearch = input.indexOf(quoteChar, quoteSearch + 1);
2015
+
2016
+ //No other quotes are found - no other delimiters
2017
+ if (quoteSearch === -1)
2018
+ {
2019
+ if (!ignoreLastRow) {
2020
+ // No closing quote... what a pity
2021
+ errors.push({
2022
+ type: 'Quotes',
2023
+ code: 'MissingQuotes',
2024
+ message: 'Quoted field unterminated',
2025
+ row: data.length, // row has yet to be inserted
2026
+ index: cursor
2027
+ });
2028
+ }
2029
+ return finish();
2030
+ }
2031
+
2032
+ // Closing quote at EOF
2033
+ if (quoteSearch === inputLen - 1)
2034
+ {
2035
+ var value = input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar);
2036
+ return finish(value);
2037
+ }
2038
+
2039
+ // If this quote is escaped, it's part of the data; skip it
2040
+ // If the quote character is the escape character, then check if the next character is the escape character
2041
+ if (quoteChar === escapeChar && input[quoteSearch + 1] === escapeChar)
2042
+ {
2043
+ quoteSearch++;
2044
+ continue;
2045
+ }
2046
+
2047
+ // If the quote character is not the escape character, then check if the previous character was the escape character
2048
+ if (quoteChar !== escapeChar && quoteSearch !== 0 && input[quoteSearch - 1] === escapeChar)
2049
+ {
2050
+ continue;
2051
+ }
2052
+
2053
+ if(nextDelim !== -1 && nextDelim < (quoteSearch + 1)) {
2054
+ nextDelim = input.indexOf(delim, (quoteSearch + 1));
2055
+ }
2056
+ if(nextNewline !== -1 && nextNewline < (quoteSearch + 1)) {
2057
+ nextNewline = input.indexOf(newline, (quoteSearch + 1));
2058
+ }
2059
+ // Check up to nextDelim or nextNewline, whichever is closest
2060
+ var checkUpTo = nextNewline === -1 ? nextDelim : Math.min(nextDelim, nextNewline);
2061
+ var spacesBetweenQuoteAndDelimiter = extraSpaces(checkUpTo);
2062
+
2063
+ // Closing quote followed by delimiter or 'unnecessary spaces + delimiter'
2064
+ if (input.substr(quoteSearch + 1 + spacesBetweenQuoteAndDelimiter, delimLen) === delim)
2065
+ {
2066
+ row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar));
2067
+ cursor = quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen;
2068
+
2069
+ // If char after following delimiter is not quoteChar, we find next quote char position
2070
+ if (input[quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen] !== quoteChar)
2071
+ {
2072
+ quoteSearch = input.indexOf(quoteChar, cursor);
2073
+ }
2074
+ nextDelim = input.indexOf(delim, cursor);
2075
+ nextNewline = input.indexOf(newline, cursor);
2076
+ break;
2077
+ }
2078
+
2079
+ var spacesBetweenQuoteAndNewLine = extraSpaces(nextNewline);
2080
+
2081
+ // Closing quote followed by newline or 'unnecessary spaces + newLine'
2082
+ if (input.substring(quoteSearch + 1 + spacesBetweenQuoteAndNewLine, quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen) === newline)
2083
+ {
2084
+ row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar));
2085
+ saveRow(quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen);
2086
+ nextDelim = input.indexOf(delim, cursor); // because we may have skipped the nextDelim in the quoted field
2087
+ quoteSearch = input.indexOf(quoteChar, cursor); // we search for first quote in next line
2088
+
2089
+ if (stepIsFunction)
2090
+ {
2091
+ doStep();
2092
+ if (aborted)
2093
+ return returnable();
2094
+ }
2095
+
2096
+ if (preview && data.length >= preview)
2097
+ return returnable(true);
2098
+
2099
+ break;
2100
+ }
2101
+
2102
+
2103
+ // 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
2104
+ errors.push({
2105
+ type: 'Quotes',
2106
+ code: 'InvalidQuotes',
2107
+ message: 'Trailing quote on quoted field is malformed',
2108
+ row: data.length, // row has yet to be inserted
2109
+ index: cursor
2110
+ });
2111
+
2112
+ quoteSearch++;
2113
+ continue;
2114
+
2115
+ }
2116
+
2117
+ continue;
2118
+ }
2119
+
2120
+ // Comment found at start of new line
2121
+ if (comments && row.length === 0 && input.substring(cursor, cursor + commentsLen) === comments)
2122
+ {
2123
+ if (nextNewline === -1) // Comment ends at EOF
2124
+ return returnable();
2125
+ cursor = nextNewline + newlineLen;
2126
+ nextNewline = input.indexOf(newline, cursor);
2127
+ nextDelim = input.indexOf(delim, cursor);
2128
+ continue;
2129
+ }
2130
+
2131
+ // Next delimiter comes before next newline, so we've reached end of field
2132
+ if (nextDelim !== -1 && (nextDelim < nextNewline || nextNewline === -1))
2133
+ {
2134
+ row.push(input.substring(cursor, nextDelim));
2135
+ cursor = nextDelim + delimLen;
2136
+ // we look for next delimiter char
2137
+ nextDelim = input.indexOf(delim, cursor);
2138
+ continue;
2139
+ }
2140
+
2141
+ // End of row
2142
+ if (nextNewline !== -1)
2143
+ {
2144
+ row.push(input.substring(cursor, nextNewline));
2145
+ saveRow(nextNewline + newlineLen);
2146
+
2147
+ if (stepIsFunction)
2148
+ {
2149
+ doStep();
2150
+ if (aborted)
2151
+ return returnable();
2152
+ }
2153
+
2154
+ if (preview && data.length >= preview)
2155
+ return returnable(true);
2156
+
2157
+ continue;
2158
+ }
2159
+
2160
+ break;
2161
+ }
2162
+
2163
+
2164
+ return finish();
2165
+
2166
+
2167
+ function pushRow(row)
2168
+ {
2169
+ data.push(row);
2170
+ lastCursor = cursor;
2171
+ }
2172
+
2173
+ /**
2174
+ * checks if there are extra spaces after closing quote and given index without any text
2175
+ * if Yes, returns the number of spaces
2176
+ */
2177
+ function extraSpaces(index) {
2178
+ var spaceLength = 0;
2179
+ if (index !== -1) {
2180
+ var textBetweenClosingQuoteAndIndex = input.substring(quoteSearch + 1, index);
2181
+ if (textBetweenClosingQuoteAndIndex && textBetweenClosingQuoteAndIndex.trim() === '') {
2182
+ spaceLength = textBetweenClosingQuoteAndIndex.length;
2183
+ }
2184
+ }
2185
+ return spaceLength;
2186
+ }
2187
+
2188
+ /**
2189
+ * Appends the remaining input from cursor to the end into
2190
+ * row, saves the row, calls step, and returns the results.
2191
+ */
2192
+ function finish(value)
2193
+ {
2194
+ if (ignoreLastRow)
2195
+ return returnable();
2196
+ if (typeof value === 'undefined')
2197
+ value = input.substring(cursor);
2198
+ row.push(value);
2199
+ cursor = inputLen; // important in case parsing is paused
2200
+ pushRow(row);
2201
+ if (stepIsFunction)
2202
+ doStep();
2203
+ return returnable();
2204
+ }
2205
+
2206
+ /**
2207
+ * Appends the current row to the results. It sets the cursor
2208
+ * to newCursor and finds the nextNewline. The caller should
2209
+ * take care to execute user's step function and check for
2210
+ * preview and end parsing if necessary.
2211
+ */
2212
+ function saveRow(newCursor)
2213
+ {
2214
+ cursor = newCursor;
2215
+ pushRow(row);
2216
+ row = [];
2217
+ nextNewline = input.indexOf(newline, cursor);
2218
+ }
2219
+
2220
+ /** Returns an object with the results, errors, and meta. */
2221
+ function returnable(stopped)
2222
+ {
2223
+ return {
2224
+ data: data,
2225
+ errors: errors,
2226
+ meta: {
2227
+ delimiter: delim,
2228
+ linebreak: newline,
2229
+ aborted: aborted,
2230
+ truncated: !!stopped,
2231
+ cursor: lastCursor + (baseIndex || 0)
2232
+ }
2233
+ };
2234
+ }
2235
+
2236
+ /** Executes the user's step function and resets data & errors. */
2237
+ function doStep()
2238
+ {
2239
+ step(returnable());
2240
+ data = [];
2241
+ errors = [];
2242
+ }
2243
+ };
2244
+
2245
+ /** Sets the abort flag */
2246
+ this.abort = function()
2247
+ {
2248
+ aborted = true;
2249
+ };
2250
+
2251
+ /** Gets the cursor position */
2252
+ this.getCharIndex = function()
2253
+ {
2254
+ return cursor;
2255
+ };
2256
+ }
2257
+
2258
+
2259
+ function newWorker()
2260
+ {
2261
+ if (!Papa.WORKERS_SUPPORTED)
2262
+ return false;
2263
+
2264
+ var workerUrl = getWorkerBlob();
2265
+ var w = new global.Worker(workerUrl);
2266
+ w.onmessage = mainThreadReceivedMessage;
2267
+ w.id = workerIdCounter++;
2268
+ workers[w.id] = w;
2269
+ return w;
2270
+ }
2271
+
2272
+ /** Callback when main thread receives a message */
2273
+ function mainThreadReceivedMessage(e)
2274
+ {
2275
+ var msg = e.data;
2276
+ var worker = workers[msg.workerId];
2277
+ var aborted = false;
2278
+
2279
+ if (msg.error)
2280
+ worker.userError(msg.error, msg.file);
2281
+ else if (msg.results && msg.results.data)
2282
+ {
2283
+ var abort = function() {
2284
+ aborted = true;
2285
+ completeWorker(msg.workerId, { data: [], errors: [], meta: { aborted: true } });
2286
+ };
2287
+
2288
+ var handle = {
2289
+ abort: abort,
2290
+ pause: notImplemented,
2291
+ resume: notImplemented
2292
+ };
2293
+
2294
+ if (isFunction(worker.userStep))
2295
+ {
2296
+ for (var i = 0; i < msg.results.data.length; i++)
2297
+ {
2298
+ worker.userStep({
2299
+ data: msg.results.data[i],
2300
+ errors: msg.results.errors,
2301
+ meta: msg.results.meta
2302
+ }, handle);
2303
+ if (aborted)
2304
+ break;
2305
+ }
2306
+ delete msg.results; // free memory ASAP
2307
+ }
2308
+ else if (isFunction(worker.userChunk))
2309
+ {
2310
+ worker.userChunk(msg.results, handle, msg.file);
2311
+ delete msg.results;
2312
+ }
2313
+ }
2314
+
2315
+ if (msg.finished && !aborted)
2316
+ completeWorker(msg.workerId, msg.results);
2317
+ }
2318
+
2319
+ function completeWorker(workerId, results) {
2320
+ var worker = workers[workerId];
2321
+ if (isFunction(worker.userComplete))
2322
+ worker.userComplete(results);
2323
+ worker.terminate();
2324
+ delete workers[workerId];
2325
+ }
2326
+
2327
+ function notImplemented() {
2328
+ throw new Error('Not implemented.');
2329
+ }
2330
+
2331
+ /** Callback when worker thread receives a message */
2332
+ function workerThreadReceivedMessage(e)
2333
+ {
2334
+ var msg = e.data;
2335
+
2336
+ if (typeof Papa.WORKER_ID === 'undefined' && msg)
2337
+ Papa.WORKER_ID = msg.workerId;
2338
+
2339
+ if (typeof msg.input === 'string')
2340
+ {
2341
+ global.postMessage({
2342
+ workerId: Papa.WORKER_ID,
2343
+ results: Papa.parse(msg.input, msg.config),
2344
+ finished: true
2345
+ });
2346
+ }
2347
+ else if ((global.File && msg.input instanceof File) || msg.input instanceof Object) // thank you, Safari (see issue #106)
2348
+ {
2349
+ var results = Papa.parse(msg.input, msg.config);
2350
+ if (results)
2351
+ global.postMessage({
2352
+ workerId: Papa.WORKER_ID,
2353
+ results: results,
2354
+ finished: true
2355
+ });
2356
+ }
2357
+ }
2358
+
2359
+ /** Makes a deep copy of an array or object (mostly) */
2360
+ function copy(obj)
2361
+ {
2362
+ if (typeof obj !== 'object' || obj === null)
2363
+ return obj;
2364
+ var cpy = Array.isArray(obj) ? [] : {};
2365
+ for (var key in obj)
2366
+ cpy[key] = copy(obj[key]);
2367
+ return cpy;
2368
+ }
2369
+
2370
+ function bindFunction(f, self)
2371
+ {
2372
+ return function() { f.apply(self, arguments); };
2373
+ }
2374
+
2375
+ function isFunction(func)
2376
+ {
2377
+ return typeof func === 'function';
2378
+ }
2379
+
2380
+ return Papa;
2381
+ }));
2382
+ } (papaparse));
2383
+
2384
+ var Papa = papaparse.exports;
2385
+
2386
+ var isValidEmail = function isValidEmail(email) {
2387
+ return yup.string().email().isValidSync(email);
2388
+ };
2389
+ var createEmailOptions = function createEmailOptions() {
2390
+ var emails = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
2391
+ return emails.map(function (email) {
2392
+ return {
2393
+ label: email,
2394
+ value: email,
2395
+ valid: isValidEmail(email)
2396
+ };
2397
+ });
2398
+ };
2399
+ var parseCsvEmails = /*#__PURE__*/function () {
2400
+ var _ref = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(file, onSuccess) {
2401
+ return regenerator.wrap(function _callee$(_context) {
2402
+ while (1) switch (_context.prev = _context.next) {
2403
+ case 0:
2404
+ Papa.parse(file, {
2405
+ header: true,
2406
+ skipEmptyLines: true,
2407
+ transformHeader: function transformHeader(h) {
2408
+ return h.toLowerCase().replace(/\W/g, "");
2409
+ },
2410
+ complete: function complete(results) {
2411
+ var _results$meta$fields;
2412
+ var isEmailFieldPresent = (_results$meta$fields = results.meta.fields) === null || _results$meta$fields === void 0 ? void 0 : _results$meta$fields.includes("email");
2413
+ if (isEmailFieldPresent) {
2414
+ var emails = results.data.filter(ramda.prop("email")).map(function (item) {
2415
+ return item.email.trim();
2416
+ });
2417
+ onSuccess(createEmailOptions(emails));
2418
+ } else {
2419
+ neetoui.Toastr.error(i18next.t("neetoMolecules.sendToFields.errors.invalidCsv"));
2420
+ }
2421
+ }
2422
+ });
2423
+ case 1:
2424
+ case "end":
2425
+ return _context.stop();
2426
+ }
2427
+ }, _callee);
2428
+ }));
2429
+ return function parseCsvEmails(_x, _x2) {
2430
+ return _ref.apply(this, arguments);
2431
+ };
2432
+ }();
2433
+
2434
+ var SendToFields = function SendToFields(_ref) {
2435
+ var emailInputProps = _ref.emailInputProps,
2436
+ ccInputProps = _ref.ccInputProps,
2437
+ bccInputProps = _ref.bccInputProps,
2438
+ _ref$showUploadCsvBut = _ref.showUploadCsvButton,
2439
+ showUploadCsvButton = _ref$showUploadCsvBut === void 0 ? false : _ref$showUploadCsvBut,
2440
+ _ref$showCcBccButton = _ref.showCcBccButton,
2441
+ showCcBccButton = _ref$showCcBccButton === void 0 ? false : _ref$showCcBccButton;
2442
+ var sendToFieldRef = React.useRef();
2443
+ var _useFormikContext = formik.useFormikContext(),
2444
+ _useFormikContext$val = _useFormikContext.values,
2445
+ showCopyEmails = _useFormikContext$val.showCopyEmails,
2446
+ existingSendToEmails = _useFormikContext$val[emailInputProps.name || "sendTo"],
2447
+ setFieldValue = _useFormikContext.setFieldValue;
2448
+ var _useTranslation = reactI18next.useTranslation(),
2449
+ t = _useTranslation.t;
2450
+ var handleCSVFile = /*#__PURE__*/function () {
2451
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(files) {
2452
+ var _sendToFieldRef$curre, onSuccess;
2453
+ return regenerator.wrap(function _callee$(_context) {
2454
+ while (1) switch (_context.prev = _context.next) {
2455
+ case 0:
2456
+ _context.prev = 0;
2457
+ onSuccess = function onSuccess(values) {
2458
+ return setFieldValue(emailInputProps.name || "sendTo", [].concat(_toConsumableArray(existingSendToEmails), _toConsumableArray(values)));
2459
+ };
2460
+ _context.next = 4;
2461
+ return parseCsvEmails(files[0], onSuccess);
2462
+ case 4:
2463
+ (_sendToFieldRef$curre = sendToFieldRef.current) === null || _sendToFieldRef$curre === void 0 ? void 0 : _sendToFieldRef$curre.focus();
2464
+ _context.next = 10;
2465
+ break;
2466
+ case 7:
2467
+ _context.prev = 7;
2468
+ _context.t0 = _context["catch"](0);
2469
+ neetoui.Toastr.error(_context.t0);
2470
+ case 10:
2471
+ case "end":
2472
+ return _context.stop();
2473
+ }
2474
+ }, _callee, null, [[0, 7]]);
2475
+ }));
2476
+ return function handleCSVFile(_x) {
2477
+ return _ref2.apply(this, arguments);
2478
+ };
2479
+ }();
2480
+ var handelCcBccButtonClick = function handelCcBccButtonClick(e) {
2481
+ e.stopPropagation();
2482
+ setFieldValue("showCopyEmails", !showCopyEmails);
2483
+ };
2484
+ return /*#__PURE__*/React__default["default"].createElement("div", {
2485
+ className: "relative w-full flex-col gap-2"
2486
+ }, showUploadCsvButton && /*#__PURE__*/React__default["default"].createElement("div", {
2487
+ className: "absolute top-0 right-1"
2488
+ }, /*#__PURE__*/React__default["default"].createElement(FilePicker, {
2489
+ types: ALLOWED_FILE_PICKER_TYPES,
2490
+ onChange: handleCSVFile
2491
+ }, /*#__PURE__*/React__default["default"].createElement(neetoui.Button, {
2492
+ "data-cy": "upload-csv-button",
2493
+ icon: neetoIcons.Upload,
2494
+ label: t("neetoMolecules.emailForm.uploadCSV"),
2495
+ size: "small",
2496
+ style: "link",
2497
+ tooltipProps: {
2498
+ content: t("neetoMolecules.sendToFields.uploadCsvTooltip"),
2499
+ position: "right"
2500
+ }
2501
+ }))), /*#__PURE__*/React__default["default"].createElement(formik$1.MultiEmailInput, _extends({
2502
+ "data-testid": "emails",
2503
+ name: "sendTo",
2504
+ ref: sendToFieldRef
2505
+ }, emailInputProps, {
2506
+ suffix: showCcBccButton && /*#__PURE__*/React__default["default"].createElement(neetoui.Button, {
2507
+ "data-cy": "cc-bcc-button",
2508
+ "data-testid": "cc-bcc-button",
2509
+ label: t("neetoMolecules.emailForm.labels.ccBcc"),
2510
+ size: "small",
2511
+ style: "link",
2512
+ onClick: handelCcBccButtonClick
2513
+ })
2514
+ })), showCopyEmails && /*#__PURE__*/React__default["default"].createElement("div", {
2515
+ className: "mt-5 flex w-full flex-col gap-6"
2516
+ }, /*#__PURE__*/React__default["default"].createElement(formik$1.MultiEmailInput, _extends({
2517
+ name: "sendToBcc"
2518
+ }, ccInputProps)), /*#__PURE__*/React__default["default"].createElement(formik$1.MultiEmailInput, _extends({
2519
+ name: "sendToCc"
2520
+ }, bccInputProps))));
2521
+ };
2522
+
2523
+ module.exports = SendToFields;
2524
+ //# sourceMappingURL=SendToFields.cjs.js.map