csv-stringify
Version:
CSV stringifier implementing the Node.js `stream.Transform` API
1,490 lines (1,195 loc) • 230 kB
JavaScript
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.stringify = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
(function (Buffer,setImmediate){(function (){
"use strict";
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
/*
CSV Stringify
Please look at the [project documentation](https://csv.js.org/stringify/) for
additional information.
*/
var _require = require('stream'),
Transform = _require.Transform;
var bom_utf8 = Buffer.from([239, 187, 191]);
var Stringifier = /*#__PURE__*/function (_Transform) {
_inherits(Stringifier, _Transform);
var _super = _createSuper(Stringifier);
function Stringifier() {
var _this;
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Stringifier);
_this = _super.call(this, _objectSpread(_objectSpread({}, {
writableObjectMode: true
}), opts));
var options = {};
var err; // Merge with user options
for (var opt in opts) {
options[underscore(opt)] = opts[opt];
}
if (err = _this.normalize(options)) throw err;
switch (options.record_delimiter) {
case 'auto':
options.record_delimiter = null;
break;
case 'unix':
options.record_delimiter = "\n";
break;
case 'mac':
options.record_delimiter = "\r";
break;
case 'windows':
options.record_delimiter = "\r\n";
break;
case 'ascii':
options.record_delimiter = "\x1E";
break;
case 'unicode':
options.record_delimiter = "\u2028";
break;
} // Expose options
_this.options = options; // Internal state
_this.state = {
stop: false
}; // Information
_this.info = {
records: 0
};
return _this;
}
_createClass(Stringifier, [{
key: "normalize",
value: function normalize(options) {
// Normalize option `bom`
if (options.bom === undefined || options.bom === null || options.bom === false) {
options.bom = false;
} else if (options.bom !== true) {
return new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', ['option `bom` is optional and must be a boolean value,', "got ".concat(JSON.stringify(options.bom))]);
} // Normalize option `delimiter`
if (options.delimiter === undefined || options.delimiter === null) {
options.delimiter = ',';
} else if (Buffer.isBuffer(options.delimiter)) {
options.delimiter = options.delimiter.toString();
} else if (typeof options.delimiter !== 'string') {
return new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', ['option `delimiter` must be a buffer or a string,', "got ".concat(JSON.stringify(options.delimiter))]);
} // Normalize option `quote`
if (options.quote === undefined || options.quote === null) {
options.quote = '"';
} else if (options.quote === true) {
options.quote = '"';
} else if (options.quote === false) {
options.quote = '';
} else if (Buffer.isBuffer(options.quote)) {
options.quote = options.quote.toString();
} else if (typeof options.quote !== 'string') {
return new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', ['option `quote` must be a boolean, a buffer or a string,', "got ".concat(JSON.stringify(options.quote))]);
} // Normalize option `quoted`
if (options.quoted === undefined || options.quoted === null) {
options.quoted = false;
} else {// todo
} // Normalize option `quoted_empty`
if (options.quoted_empty === undefined || options.quoted_empty === null) {
options.quoted_empty = undefined;
} else {// todo
} // Normalize option `quoted_match`
if (options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false) {
options.quoted_match = null;
} else if (!Array.isArray(options.quoted_match)) {
options.quoted_match = [options.quoted_match];
}
if (options.quoted_match) {
var _iterator = _createForOfIteratorHelper(options.quoted_match),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var quoted_match = _step.value;
var isString = typeof quoted_match === 'string';
var isRegExp = quoted_match instanceof RegExp;
if (!isString && !isRegExp) {
return Error("Invalid Option: quoted_match must be a string or a regex, got ".concat(JSON.stringify(quoted_match)));
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
} // Normalize option `quoted_string`
if (options.quoted_string === undefined || options.quoted_string === null) {
options.quoted_string = false;
} else {// todo
} // Normalize option `eof`
if (options.eof === undefined || options.eof === null) {
options.eof = true;
} else {// todo
} // Normalize option `escape`
if (options.escape === undefined || options.escape === null) {
options.escape = '"';
} else if (Buffer.isBuffer(options.escape)) {
options.escape = options.escape.toString();
} else if (typeof options.escape !== 'string') {
return Error("Invalid Option: escape must be a buffer or a string, got ".concat(JSON.stringify(options.escape)));
}
if (options.escape.length > 1) {
return Error("Invalid Option: escape must be one character, got ".concat(options.escape.length, " characters"));
} // Normalize option `header`
if (options.header === undefined || options.header === null) {
options.header = false;
} else {// todo
} // Normalize option `columns`
options.columns = this.normalize_columns(options.columns); // Normalize option `quoted`
if (options.quoted === undefined || options.quoted === null) {
options.quoted = false;
} else {// todo
} // Normalize option `cast`
if (options.cast === undefined || options.cast === null) {
options.cast = {};
} else {// todo
} // Normalize option cast.bigint
if (options.cast.bigint === undefined || options.cast.bigint === null) {
// Cast boolean to string by default
options.cast.bigint = function (value) {
return '' + value;
};
} // Normalize option cast.boolean
if (options.cast["boolean"] === undefined || options.cast["boolean"] === null) {
// Cast boolean to string by default
options.cast["boolean"] = function (value) {
return value ? '1' : '';
};
} // Normalize option cast.date
if (options.cast.date === undefined || options.cast.date === null) {
// Cast date to timestamp string by default
options.cast.date = function (value) {
return '' + value.getTime();
};
} // Normalize option cast.number
if (options.cast.number === undefined || options.cast.number === null) {
// Cast number to string using native casting by default
options.cast.number = function (value) {
return '' + value;
};
} // Normalize option cast.object
if (options.cast.object === undefined || options.cast.object === null) {
// Stringify object as JSON by default
options.cast.object = function (value) {
return JSON.stringify(value);
};
} // Normalize option cast.string
if (options.cast.string === undefined || options.cast.string === null) {
// Leave string untouched
options.cast.string = function (value) {
return value;
};
} // Normalize option `record_delimiter`
if (options.record_delimiter === undefined || options.record_delimiter === null) {
options.record_delimiter = '\n';
} else if (Buffer.isBuffer(options.record_delimiter)) {
options.record_delimiter = options.record_delimiter.toString();
} else if (typeof options.record_delimiter !== 'string') {
return Error("Invalid Option: record_delimiter must be a buffer or a string, got ".concat(JSON.stringify(options.record_delimiter)));
}
}
}, {
key: "_transform",
value: function _transform(chunk, encoding, callback) {
if (this.state.stop === true) {
return;
} // Chunk validation
if (!Array.isArray(chunk) && _typeof(chunk) !== 'object') {
this.state.stop = true;
return callback(Error("Invalid Record: expect an array or an object, got ".concat(JSON.stringify(chunk))));
} // Detect columns from the first record
if (this.info.records === 0) {
if (Array.isArray(chunk)) {
if (this.options.header === true && !this.options.columns) {
this.state.stop = true;
return callback(Error('Undiscoverable Columns: header option requires column option or object records'));
}
} else if (this.options.columns === undefined || this.options.columns === null) {
this.options.columns = this.normalize_columns(Object.keys(chunk));
}
} // Emit the header
if (this.info.records === 0) {
this.bom();
this.headers();
} // Emit and stringify the record if an object or an array
try {
this.emit('record', chunk, this.info.records);
} catch (err) {
this.state.stop = true;
return this.emit('error', err);
} // Convert the record into a string
var chunk_string;
if (this.options.eof) {
chunk_string = this.stringify(chunk);
if (chunk_string === undefined) {
return;
} else {
chunk_string = chunk_string + this.options.record_delimiter;
}
} else {
chunk_string = this.stringify(chunk);
if (chunk_string === undefined) {
return;
} else {
if (this.options.header || this.info.records) {
chunk_string = this.options.record_delimiter + chunk_string;
}
}
} // Emit the csv
this.info.records++;
this.push(chunk_string);
callback();
}
}, {
key: "_flush",
value: function _flush(callback) {
if (this.info.records === 0) {
this.bom();
this.headers();
}
callback();
}
}, {
key: "stringify",
value: function stringify(chunk) {
var _this2 = this;
var chunkIsHeader = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (_typeof(chunk) !== 'object') {
return chunk;
}
var _this$options = this.options,
columns = _this$options.columns,
header = _this$options.header;
var record = []; // Record is an array
if (Array.isArray(chunk)) {
// We are getting an array but the user has specified output columns. In
// this case, we respect the columns indexes
if (columns) {
chunk.splice(columns.length);
} // Cast record elements
for (var _i = 0; _i < chunk.length; _i++) {
var field = chunk[_i];
var _this$__cast = this.__cast(field, {
index: _i,
column: _i,
records: this.info.records,
header: chunkIsHeader
}),
_this$__cast2 = _slicedToArray(_this$__cast, 2),
_err = _this$__cast2[0],
value = _this$__cast2[1];
if (_err) {
this.emit('error', _err);
return;
}
record[_i] = [value, field];
} // Record is a literal object
} else {
if (columns) {
for (var _i2 = 0; _i2 < columns.length; _i2++) {
var _field = get(chunk, columns[_i2].key);
var _this$__cast3 = this.__cast(_field, {
index: _i2,
column: columns[_i2].key,
records: this.info.records,
header: chunkIsHeader
}),
_this$__cast4 = _slicedToArray(_this$__cast3, 2),
_err2 = _this$__cast4[0],
_value = _this$__cast4[1];
if (_err2) {
this.emit('error', _err2);
return;
}
record[_i2] = [_value, _field];
}
} else {
var _iterator2 = _createForOfIteratorHelper(chunk),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var column = _step2.value;
var _field2 = chunk[column];
var _this$__cast5 = this.__cast(_field2, {
index: i,
column: columns[i].key,
records: this.info.records,
header: chunkIsHeader
}),
_this$__cast6 = _slicedToArray(_this$__cast5, 2),
_err3 = _this$__cast6[0],
_value2 = _this$__cast6[1];
if (_err3) {
this.emit('error', _err3);
return;
}
record.push([_value2, _field2]);
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
}
}
var csvrecord = '';
var _loop = function _loop(_i3) {
var options = void 0,
err = void 0;
var _record$_i = _slicedToArray(record[_i3], 2),
value = _record$_i[0],
field = _record$_i[1];
if (typeof value === "string") {
options = _this2.options;
} else if (isObject(value)) {
// let { value, ...options } = value
options = value;
value = options.value;
delete options.value;
if (typeof value !== "string" && value !== undefined && value !== null) {
_this2.emit("error", Error("Invalid Casting Value: returned value must return a string, null or undefined, got ".concat(JSON.stringify(value))));
return {
v: void 0
};
}
options = _objectSpread(_objectSpread({}, _this2.options), options);
if (err = _this2.normalize(options)) {
_this2.emit("error", err);
return {
v: void 0
};
}
} else if (value === undefined || value === null) {
options = _this2.options;
} else {
_this2.emit("error", Error("Invalid Casting Value: returned value must return a string, an object, null or undefined, got ".concat(JSON.stringify(value))));
return {
v: void 0
};
}
var _options = options,
delimiter = _options.delimiter,
escape = _options.escape,
quote = _options.quote,
quoted = _options.quoted,
quoted_empty = _options.quoted_empty,
quoted_string = _options.quoted_string,
quoted_match = _options.quoted_match,
record_delimiter = _options.record_delimiter;
if (value) {
if (typeof value !== 'string') {
_this2.emit("error", Error("Formatter must return a string, null or undefined, got ".concat(JSON.stringify(value))));
return {
v: null
};
}
var containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0;
var containsQuote = quote !== '' && value.indexOf(quote) >= 0;
var containsEscape = value.indexOf(escape) >= 0 && escape !== quote;
var containsRecordDelimiter = value.indexOf(record_delimiter) >= 0;
var quotedString = quoted_string && typeof field === 'string';
var quotedMatch = quoted_match && quoted_match.filter(function (quoted_match) {
if (typeof quoted_match === 'string') {
return value.indexOf(quoted_match) !== -1;
} else {
return quoted_match.test(value);
}
});
quotedMatch = quotedMatch && quotedMatch.length > 0;
var shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch;
if (shouldQuote === true && containsEscape === true) {
var regexp = escape === '\\' ? new RegExp(escape + escape, 'g') : new RegExp(escape, 'g');
value = value.replace(regexp, escape + escape);
}
if (containsQuote === true) {
var _regexp = new RegExp(quote, 'g');
value = value.replace(_regexp, escape + quote);
}
if (shouldQuote === true) {
value = quote + value + quote;
}
csvrecord += value;
} else if (quoted_empty === true || field === '' && quoted_string === true && quoted_empty !== false) {
csvrecord += quote + quote;
}
if (_i3 !== record.length - 1) {
csvrecord += delimiter;
}
};
for (var _i3 = 0; _i3 < record.length; _i3++) {
var _ret = _loop(_i3);
if (_typeof(_ret) === "object") return _ret.v;
}
return csvrecord;
}
}, {
key: "bom",
value: function bom() {
if (this.options.bom !== true) {
return;
}
this.push(bom_utf8);
}
}, {
key: "headers",
value: function headers() {
if (this.options.header === false) {
return;
}
if (this.options.columns === undefined) {
return;
}
var headers = this.options.columns.map(function (column) {
return column.header;
});
if (this.options.eof) {
headers = this.stringify(headers, true) + this.options.record_delimiter;
} else {
headers = this.stringify(headers);
}
this.push(headers);
}
}, {
key: "__cast",
value: function __cast(value, context) {
var type = _typeof(value);
try {
if (type === 'string') {
// Fine for 99% of the cases
return [undefined, this.options.cast.string(value, context)];
} else if (type === 'bigint') {
return [undefined, this.options.cast.bigint(value, context)];
} else if (type === 'number') {
return [undefined, this.options.cast.number(value, context)];
} else if (type === 'boolean') {
return [undefined, this.options.cast["boolean"](value, context)];
} else if (value instanceof Date) {
return [undefined, this.options.cast.date(value, context)];
} else if (type === 'object' && value !== null) {
return [undefined, this.options.cast.object(value, context)];
} else {
return [undefined, value, value];
}
} catch (err) {
return [err];
}
}
}, {
key: "normalize_columns",
value: function normalize_columns(columns) {
if (columns === undefined || columns === null) {
return undefined;
}
if (_typeof(columns) !== 'object') {
throw Error('Invalid option "columns": expect an array or an object');
}
if (!Array.isArray(columns)) {
var newcolumns = [];
for (var k in columns) {
newcolumns.push({
key: k,
header: columns[k]
});
}
columns = newcolumns;
} else {
var _newcolumns = [];
var _iterator3 = _createForOfIteratorHelper(columns),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var column = _step3.value;
if (typeof column === 'string') {
_newcolumns.push({
key: column,
header: column
});
} else if (_typeof(column) === 'object' && column !== undefined && !Array.isArray(column)) {
if (!column.key) {
throw Error('Invalid column definition: property "key" is required');
}
if (column.header === undefined) {
column.header = column.key;
}
_newcolumns.push(column);
} else {
throw Error('Invalid column definition: expect a string or an object');
}
}
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
columns = _newcolumns;
}
return columns;
}
}]);
return Stringifier;
}(Transform);
var stringify = function stringify() {
var data, options, callback;
for (var _i4 in arguments) {
var argument = arguments[_i4];
var type = _typeof(argument);
if (data === undefined && Array.isArray(argument)) {
data = argument;
} else if (options === undefined && isObject(argument)) {
options = argument;
} else if (callback === undefined && type === 'function') {
callback = argument;
} else {
throw new CsvError('CSV_INVALID_ARGUMENT', ['Invalid argument:', "got ".concat(JSON.stringify(argument), " at index ").concat(_i4)]);
}
}
var stringifier = new Stringifier(options);
if (callback) {
var chunks = [];
stringifier.on('readable', function () {
var chunk;
while ((chunk = this.read()) !== null) {
chunks.push(chunk);
}
});
stringifier.on('error', function (err) {
callback(err);
});
stringifier.on('end', function () {
callback(undefined, chunks.join(''));
});
}
if (data !== undefined) {
// Give a chance for events to be registered later
if (typeof setImmediate === 'function') {
setImmediate(function () {
var _iterator4 = _createForOfIteratorHelper(data),
_step4;
try {
for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
var record = _step4.value;
stringifier.write(record);
}
} catch (err) {
_iterator4.e(err);
} finally {
_iterator4.f();
}
stringifier.end();
});
} else {
var _iterator5 = _createForOfIteratorHelper(data),
_step5;
try {
for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
var record = _step5.value;
stringifier.write(record);
}
} catch (err) {
_iterator5.e(err);
} finally {
_iterator5.f();
}
stringifier.end();
}
}
return stringifier;
};
var CsvError = /*#__PURE__*/function (_Error) {
_inherits(CsvError, _Error);
var _super2 = _createSuper(CsvError);
function CsvError(code, message) {
var _this3;
_classCallCheck(this, CsvError);
if (Array.isArray(message)) message = message.join(' ');
_this3 = _super2.call(this, message);
if (Error.captureStackTrace !== undefined) {
Error.captureStackTrace(_assertThisInitialized(_this3), CsvError);
}
_this3.code = code;
for (var _len = arguments.length, contexts = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
contexts[_key - 2] = arguments[_key];
}
for (var _i5 = 0, _contexts = contexts; _i5 < _contexts.length; _i5++) {
var context = _contexts[_i5];
for (var key in context) {
var value = context[key];
_this3[key] = Buffer.isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value));
}
}
return _this3;
}
return CsvError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
stringify.Stringifier = Stringifier;
stringify.CsvError = CsvError;
module.exports = stringify;
var isObject = function isObject(obj) {
return _typeof(obj) === 'object' && obj !== null && !Array.isArray(obj);
};
var underscore = function underscore(str) {
return str.replace(/([A-Z])/g, function (_, match) {
return '_' + match.toLowerCase();
});
}; // Lodash implementation of `get`
var charCodeOfDot = '.'.charCodeAt(0);
var reEscapeChar = /\\(\\)?/g;
var rePropName = RegExp( // Match anything that isn't a dot or bracket.
'[^.[\\]]+' + '|' + // Or match property names within brackets.
'\\[(?:' + // Match a non-string expression.
'([^"\'][^[]*)' + '|' + // Or match strings (supports escaping characters).
'(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + ')\\]' + '|' + // Or match "" as the space between consecutive dots or empty brackets.
'(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))', 'g');
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
var reIsPlainProp = /^\w*$/;
var getTag = function getTag(value) {
if (!value) value === undefined ? '[object Undefined]' : '[object Null]';
return Object.prototype.toString.call(value);
};
var isKey = function isKey(value, object) {
if (Array.isArray(value)) {
return false;
}
var type = _typeof(value);
if (type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
};
var isSymbol = function isSymbol(value) {
var type = _typeof(value);
return type === 'symbol' || type === 'object' && value && getTag(value) === '[object Symbol]';
};
var stringToPath = function stringToPath(string) {
var result = [];
if (string.charCodeAt(0) === charCodeOfDot) {
result.push('');
}
string.replace(rePropName, function (match, expression, quote, subString) {
var key = match;
if (quote) {
key = subString.replace(reEscapeChar, '$1');
} else if (expression) {
key = expression.trim();
}
result.push(key);
});
return result;
};
var castPath = function castPath(value, object) {
if (Array.isArray(value)) {
return value;
} else {
return isKey(value, object) ? [value] : stringToPath(value);
}
};
var toKey = function toKey(value) {
if (typeof value === 'string' || isSymbol(value)) return value;
var result = "".concat(value);
return result == '0' && 1 / value == -INFINITY ? '-0' : result;
};
var get = function get(object, path) {
path = castPath(path, object);
var index = 0;
var length = path.length;
while (object != null && index < length) {
object = object[toKey(path[index++])];
}
return index && index === length ? object : undefined;
};
}).call(this)}).call(this,require("buffer").Buffer,require("timers").setImmediate)
},{"buffer":4,"stream":10,"timers":26}],2:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function getLens (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=')
if (validLen === -1) validLen = len
var placeHoldersLen = validLen === len
? 0
: 4 - (validLen % 4)
return [validLen, placeHoldersLen]
}
// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function _byteLength (b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function toByteArray (b64) {
var tmp
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
var curByte = 0
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0
? validLen - 4
: validLen
var i
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)]
arr[curByte++] = (tmp >> 16) & 0xFF
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] +
lookup[num >> 12 & 0x3F] +
lookup[num >> 6 & 0x3F] +
lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF)
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
)
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1]
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
)
}
return parts.join('')
}
},{}],3:[function(require,module,exports){
},{}],4:[function(require,module,exports){
(function (Buffer){(function (){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
return arr.foo() === 42
} catch (e) {
return false
}
}
Object.defineProperty(Buffer.prototype, 'parent', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.buffer
}
})
Object.defineProperty(Buffer.prototype, 'offset', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.byteOffset
}
})
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('The value "' + length + '" is invalid for option "size"')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
buf.__proto__ = Buffer.prototype
return buf
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new TypeError(
'The "string" argument must be of type string. Received type number'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species != null &&
Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
})
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
if (ArrayBuffer.isView(value)) {
return fromArrayLike(value)
}
if (value == null) {
throw TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
if (isInstance(value, ArrayBuffer) ||
(value && isInstance(value.buffer, ArrayBuffer))) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'number') {
throw new TypeError(
'The "value" argument must not be of type number. Received type number'
)
}
var valueOf = value.valueOf && value.valueOf()
if (valueOf != null && valueOf !== value) {
return Buffer.from(valueOf, encodingOrOffset, length)
}
var b = fromObject(value)
if (b) return b
if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
typeof value[Symbol.toPrimitive] === 'function') {
return Buffer.from(
value[Symbol.toPrimitive]('string'), encodingOrOffset, length
)
}
throw new TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be of type number')
} else if (size < 0) {
throw new RangeError('The value "' + size + '" is invalid for option "size"')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
var length = byteLength(string, encoding) | 0
var buf = createBuffer(length)
var actual = buf.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('"offset" is outside of buffer bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('"length" is outside of buffer bounds')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj.length !== undefined) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return b != null && b._isBuffer === true &&
b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}
Buffer.compare = function compare (a, b) {
if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError(
'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
)
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf