read-excel-file 9.0.9 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -399,7 +399,7 @@ function parseValue(value, schemaEntry, options) {
399
399
  //
400
400
  Array.isArray(schemaEntry.type) ? schemaEntry.type[0] : schemaEntry.type, options);
401
401
  } else {
402
- // If the `type` is not specified for a given schema entry, the default one is `String`.
402
+ // If the `type` is not specified for a given schema entry, the `value` will be returned as is.
403
403
  result = {
404
404
  value: value
405
405
  };
@@ -1 +1 @@
1
- {"version":3,"file":"parseSheetData.js","names":["_Number","_interopRequireDefault","require","_String","_Boolean","_Date","obj","__esModule","_typeof","o","Symbol","iterator","constructor","prototype","_slicedToArray","arr","i","_arrayWithHoles","_iterableToArrayLimit","_unsupportedIterableToArray","_nonIterableRest","r","l","t","e","n","u","a","f","call","next","Object","done","push","value","length","_toArray","_iterableToArray","TypeError","iter","Array","from","isArray","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","enumerable","apply","_objectSpread","arguments","forEach","_defineProperty","getOwnPropertyDescriptors","defineProperties","defineProperty","key","_toPropertyKey","configurable","writable","arg","_toPrimitive","String","input","hint","prim","toPrimitive","undefined","res","Number","_createForOfIteratorHelperLoose","allowArrayLike","it","bind","minLen","_arrayLikeToArray","toString","slice","name","test","len","arr2","parseSheetData","data","schema","optionsCustom","objects","errors","parsedRows","parseSheetDataWithPerRowErrors","parsedRowIndex","_iterator","_step","_step$value","object","rowErrors","concat","map","rowError","row","validateSchema","options","applyDefaultOptions","_data","columns","dataRows","parseDataRow","dataRow","schemaEntry","_parseProperty","parseProperty","isEmptyValue","children","dummyParentObject","PARSED_OBJECT_TREE_START","isRequired","requiredErrors","runPendingRequiredValidations","transformValue","parseObject","path","isEmptyObject","_i","_Object$keys","child","getPropertyPath","columnIndex","column","indexOf","isMissingColumn","_ref","propertyValueWhenColumnIsMissing","parseCellValueWithPossibleErrors","cellValue","_parseCellValue","parseCellValue","errorMessage","error","errorReason","reason","createError","valueType","type","propertyValueWhenCellIsEmpty","parseArrayValue","parseValue","isEmptyArray","reasons","values","parseSeparatedSubstrings","separatorCharacter","substring","_parseValue","result","parseValueOfType","oneOf","errorAndReason","validateOneOf","validate","message","parseValueUsingTypeParser","StringType","NumberType","Date","DateType","Boolean","BooleanType","Error","parsedValue","getNextSubstring","string","startIndex","character","elements","index","_getNextSubstring","_getNextSubstring2","trim","isObject","transformEmptyObject","transformEmptyArray","propertyName","parentObjectPath","parentObjectIsRequired","parentObjectValue","parentObjectValueIsEmpty","parentObjectErrors","isPropertyRequired","_iterator2","_step2","requiredErrorsOfChild","required","_ref2","_i2","_Object$keys2","validateObjectSchemaRequiredProperty","_i3","_Object$keys3","JSON","stringify","DEFAULT_OPTIONS","objectConstructor"],"sources":["../../source/parseSheetData/parseSheetData.js"],"sourcesContent":["import NumberType from './types/Number.js'\r\nimport StringType from './types/String.js'\r\nimport BooleanType from './types/Boolean.js'\r\nimport DateType from './types/Date.js'\r\n\r\n/**\r\n * Converts spreadsheet-alike data structure into an array of JSON objects.\r\n *\r\n * Parameters:\r\n *\r\n * * `data` — An array of rows, each row being an array of cells. The first row should be the list of column headers and the rest of the rows should be the data.\r\n * * `schema` — A \"to JSON\" convertion schema (see above).\r\n * * `options` — (optional) Schema conversion parameters of `read-excel-file`:\r\n * * `propertyValueWhenColumnIsMissing` — By default, when some of the `schema` columns are missing in the input `data`, those properties are set to `undefined` in the output objects. Pass `propertyValueWhenColumnIsMissing: null` to set such \"missing column\" properties to `null` in the output objects.\r\n * * `propertyValueWhenCellIsEmpty` — By default, when it encounters a `null` value in a cell in input `data`, it sets it to `undefined` in the output object. Pass `propertyValueWhenCellIsEmpty: null` to make it set such values as `null`s in output objects.\r\n * // * `shouldSkipRequiredValidationWhenColumnIsMissing: (column: string, { object }) => boolean` — By default, it does apply `required` validation to `schema` properties for which columns are missing in the input `data`. One could pass a custom `shouldSkipRequiredValidationWhenColumnIsMissing(column, { object })` to disable `required` validation for missing columns in some or all cases.\r\n * * `transformEmptyObject(object, { path? })` — By default, it returns `null` for \"empty\" objects. One could override that value using `transformEmptyObject(object, { path })` parameter. The value applies to both top-level object and any nested sub-objects in case of a nested schema, hence the additional (optional) `path?: string` parameter.\r\n * * `transformEmptyArray(array, { path })` — By default, it returns `null` for an \"empty\" array value. One could override that value using `transformEmptyArray(array, { path })` parameter.\r\n * * `separatorCharacter` — By default, it splits array-type cell values by a comma character.\r\n *\r\n * When parsing a property value, in case of an error, the value of that property is gonna be `undefined`.\r\n *\r\n * @param {SheetData} data - An array of rows, each row being an array of cells.\r\n * @param {object} schema\r\n * @param {object} [options]\r\n * @param {any} [options.propertyValueWhenColumnIsMissing] — By default, when some of the `schema` columns are missing in the input `data`, those properties are set to `undefined` in the output objects. Pass `propertyValueWhenColumnIsMissing: null` to set such \"missing column\" properties to `null` in the output objects.\r\n * @param {any} [options.propertyValueWhenCellIsEmpty] — By default, when it encounters a `null` value in a cell in input `data`, it leaves the value as is. Pass a custom `propertyValueWhenCellIsEmpty` to make it set such values to that value.\r\n * // @param {boolean} [options.shouldSkipRequiredValidationWhenColumnIsMissing(column: string, { object })] — By default, it does apply `required` validation to `schema` properties for which columns are missing in the input `data`. One could pass a custom `shouldSkipRequiredValidationWhenColumnIsMissing(column, { object })` to disable `required` validation for missing columns in some or all cases.\r\n * @param {function} [options.transformEmptyObject(object, { path })] — By default, it returns `null` for an \"empty\" resulting object. One could override that value using `transformEmptyObject(object, { path })` parameter. The value applies to both top-level object and any nested sub-objects in case of a nested schema, hence the additional `path?: string` parameter.\r\n * @param {function} [options.transformEmptyArray(array, { path })] — By default, it returns `null` for an \"empty\" array value. One could override that value using `transformEmptyArray(array, { path })` parameter.\r\n * @param {string} [options.separatorCharacter] — When specified, string values will be split by this separator to get the array.\r\n * @return {object} — An object of shape `{ objects, errors }`. Either `objects` or `errors` is going to be `undefined`.\r\n */\r\nexport default function parseSheetData(data, schema, optionsCustom) {\r\n const objects = []\r\n let errors = []\r\n\r\n const parsedRows = parseSheetDataWithPerRowErrors(data, schema, optionsCustom)\r\n let parsedRowIndex = 0\r\n for (const { object, errors: rowErrors } of parsedRows) {\r\n if (rowErrors) {\r\n errors = errors.concat(\r\n rowErrors.map(\r\n // Add row number property to each row error.\r\n rowError => ({ ...rowError, row: parsedRowIndex + 1 })\r\n )\r\n )\r\n } else {\r\n objects.push(object)\r\n }\r\n parsedRowIndex++\r\n }\r\n\r\n if (errors.length > 0) {\r\n return { errors }\r\n }\r\n\r\n return { objects }\r\n}\r\n\r\n// This one is only used in tests.\r\nexport function parseSheetDataWithPerRowErrors(data, schema, optionsCustom) {\r\n validateSchema(schema)\r\n\r\n const options = applyDefaultOptions(optionsCustom)\r\n\r\n const [columns, ...dataRows] = data\r\n\r\n return dataRows.map(row => parseDataRow(row, schema, columns, options))\r\n}\r\n\r\nfunction parseDataRow(dataRow, schema, columns, options) {\r\n // Create a `schemaEntry` for the top-level object.\r\n const schemaEntry = {\r\n schema\r\n }\r\n\r\n // Parse the values in the given data row into an object.\r\n const {\r\n value,\r\n isEmptyValue,\r\n errors,\r\n children\r\n } = parseProperty(dataRow, schemaEntry, undefined, columns, options)\r\n\r\n // Simulate a \"dummy\" parent object for the top-level object.\r\n // It will be used when running `required` validations.\r\n const dummyParentObject = {\r\n // The \"dummy\" parent object has a \"dummy\" value.\r\n // This value is irrelevant because it won't be read anywhere.\r\n value: PARSED_OBJECT_TREE_START,\r\n // The \"dummy\" parent object is empty if the parsed row is empty.\r\n isEmptyValue,\r\n // The \"dummy\" object has the same errors as the parsed row.\r\n errors,\r\n // The parsed object by default is not required to have any data\r\n // so the \"dummy\" object is not required.\r\n isRequired: undefined\r\n }\r\n\r\n // Run any `required` validations.\r\n //\r\n // `required` validations should be run after the entire data row has been parsed,\r\n // i.e. when the entire object structure has been parsed.\r\n // The reason is that a `required` validation could be either a simple boolean or a \"complex\" function.\r\n // In the latter case, the result of a `required()` function may depend on any other property of the object,\r\n // hence the actual `required` flag value could only be obtained after the entire data row has been parsed.\r\n //\r\n // For example, consider a top-level object:\r\n //\r\n // {\r\n // firstName: string,\r\n // lastName: string,\r\n // pet?: { name: string }\r\n // }\r\n //\r\n // A corresponding schema would be:\r\n //\r\n // {\r\n // firstName: {\r\n // required: true\r\n // },\r\n // lastName: {\r\n // required: true\r\n // },\r\n // pet: {\r\n // required: false,\r\n // schema: {\r\n // name: {\r\n // required: true\r\n // }\r\n // }\r\n // }\r\n // }\r\n //\r\n // I.e. when a `pet` exists, it must have a `name`.\r\n //\r\n // In such case, the `required: true` check of the `pet`'s `name` property\r\n // should not be performed if the `pet` is not present, because the `pet` nested object\r\n // is marked as `required: false`, meaning that `pet` data is not required to be present.\r\n //\r\n const requiredErrors = runPendingRequiredValidations(\r\n schemaEntry,\r\n value,\r\n isEmptyValue,\r\n errors,\r\n children,\r\n // Simulate a \"dummy\" parent object for the top-level object.\r\n dummyParentObject.isRequired,\r\n dummyParentObject.value,\r\n dummyParentObject.isEmptyValue,\r\n dummyParentObject.errors,\r\n columns\r\n )\r\n\r\n // If there were any errors, whether caused by `required`\r\n // or occured while parsing the values, return those errors.\r\n if (errors || requiredErrors) {\r\n return {\r\n errors: (errors || []).concat(requiredErrors || [])\r\n }\r\n }\r\n\r\n // Return the parsed object.\r\n return {\r\n object: transformValue(value, isEmptyValue, undefined, options)\r\n }\r\n}\r\n\r\nfunction parseObject(row, schema, path, columns, options) {\r\n const object = {}\r\n let isEmptyObject = true\r\n\r\n let errors = []\r\n\r\n const children = []\r\n\r\n // For each property of the object.\r\n for (const key of Object.keys(schema)) {\r\n const child = parseProperty(row, schema[key], getPropertyPath(key, path), columns, options)\r\n\r\n if (child.errors) {\r\n errors = errors.concat(child.errors)\r\n } else {\r\n object[key] = transformValue(child.value, child.isEmptyValue, getPropertyPath(key, path), options)\r\n // Potentially unmark the object as \"empty\".\r\n if (isEmptyObject && !child.isEmptyValue) {\r\n isEmptyObject = false\r\n }\r\n }\r\n\r\n children.push({\r\n ...child,\r\n // `schemaEntry` will be used when running `required` validation of this property (later),\r\n schemaEntry: schema[key]\r\n })\r\n }\r\n\r\n // If there were any errors, return them.\r\n if (errors.length > 0) {\r\n return {\r\n // Return the errors.\r\n errors,\r\n // Return the `children` because `required` validations still have to be run (later).\r\n children\r\n }\r\n }\r\n\r\n return {\r\n value: object,\r\n isEmptyValue: isEmptyObject,\r\n // Return the `children` because `required` validations still have to be run (later).\r\n children\r\n }\r\n}\r\n\r\nfunction parseProperty(row, schemaEntry, path, columns, options) {\r\n const columnIndex = schemaEntry.column ? columns.indexOf(schemaEntry.column) : undefined\r\n const isMissingColumn = schemaEntry.column ? columnIndex < 0 : undefined\r\n\r\n const {\r\n value,\r\n isEmptyValue,\r\n errors,\r\n children\r\n } = schemaEntry.column\r\n ? (\r\n isMissingColumn\r\n ? { value: options.propertyValueWhenColumnIsMissing, isEmptyValue: true }\r\n : parseCellValueWithPossibleErrors(row[columnIndex], schemaEntry, columnIndex, options)\r\n )\r\n : parseObject(\r\n row,\r\n schemaEntry.schema,\r\n path,\r\n columns,\r\n options\r\n )\r\n\r\n // If there were any errors, return them.\r\n if (errors) {\r\n return {\r\n // Return the errors.\r\n errors,\r\n // Return the `children` because `required` validations still have to be run (later).\r\n children\r\n }\r\n }\r\n\r\n return {\r\n value,\r\n isEmptyValue,\r\n // Return the `children` because `required` validations still have to be run (later).\r\n children\r\n }\r\n}\r\n\r\nfunction parseCellValueWithPossibleErrors(cellValue, schemaEntry, columnIndex, options) {\r\n const {\r\n value,\r\n isEmptyValue,\r\n error: errorMessage,\r\n reason: errorReason\r\n } = parseCellValue(cellValue, schemaEntry, options)\r\n\r\n if (errorMessage) {\r\n const error = createError({\r\n error: errorMessage,\r\n reason: errorReason,\r\n column: schemaEntry.column,\r\n columnIndex,\r\n valueType: schemaEntry.type,\r\n value: cellValue\r\n })\r\n return {\r\n errors: [error]\r\n }\r\n }\r\n\r\n return {\r\n value,\r\n isEmptyValue\r\n }\r\n}\r\n\r\n/**\r\n * Converts a cell value value to a javascript typed value.\r\n * @param {any} cellValue\r\n * @param {object} schemaEntry\r\n * @param {string} propertyPath\r\n * @param {object} options\r\n * @return {{ value?: any, isEmptyValue: boolean } | { error: string, reason?: string }}\r\n */\r\nfunction parseCellValue(cellValue, schemaEntry, options) {\r\n if (cellValue === undefined) {\r\n // This isn't supposed to be possible when reading spreadsheet data:\r\n // cell values are always read as `null` when those cells are empty.\r\n // It's currently impossible for `read-excel-file` to return `undefined` cell value.\r\n // Here it uses some \"sensible default\" fallback by treating `undefined` as \"column missing\".\r\n return {\r\n value: options.propertyValueWhenColumnIsMissing,\r\n isEmptyValue: true\r\n }\r\n }\r\n\r\n if (cellValue === null) {\r\n return {\r\n value: options.propertyValueWhenCellIsEmpty,\r\n isEmptyValue: true\r\n }\r\n }\r\n\r\n // Parse comma-separated cell value.\r\n if (Array.isArray(schemaEntry.type)) {\r\n return parseArrayValue(cellValue, schemaEntry, options)\r\n }\r\n\r\n return parseValue(cellValue, schemaEntry, options)\r\n}\r\n\r\n/**\r\n * Converts textual value to a javascript typed array value.\r\n * @param {any} value\r\n * @param {object} schemaEntry\r\n * @param {object} options\r\n * @return {{ value?: any, isEmptyValue: boolean } | { error: string, reason?: string }}\r\n */\r\nfunction parseArrayValue(value, schemaEntry, options) {\r\n // If the cell value is not a string — i.e. a number, a boolean, a Date —\r\n // then throw an error.\r\n if (typeof value !== 'string') {\r\n return {\r\n error: 'not_a_string'\r\n }\r\n }\r\n\r\n let isEmptyArray = true\r\n\r\n const errors = []\r\n const reasons = []\r\n\r\n const values = parseSeparatedSubstrings(value, options.separatorCharacter).map((substring) => {\r\n // If any substring was already detected to be invalid\r\n // don't attempt to parse any other substrings.\r\n if (errors.length > 0) {\r\n return\r\n }\r\n\r\n // If an empty substring was extracted, it means that there was an out-of-place separator.\r\n if (!substring) {\r\n errors.push('invalid')\r\n reasons.push('syntax')\r\n return\r\n }\r\n\r\n const {\r\n value,\r\n isEmptyValue,\r\n error,\r\n reason\r\n } = parseValue(substring, schemaEntry, options)\r\n\r\n if (error) {\r\n errors.push(error)\r\n reasons.push(reason)\r\n return\r\n }\r\n\r\n if (isEmptyArray && !isEmptyValue) {\r\n isEmptyArray = false\r\n }\r\n\r\n return value\r\n })\r\n\r\n if (errors.length > 0) {\r\n return {\r\n error: errors[0],\r\n reason: reasons[0]\r\n }\r\n }\r\n\r\n return {\r\n value: values,\r\n isEmptyValue: isEmptyArray\r\n }\r\n}\r\n\r\n/**\r\n * Converts textual value to a javascript typed value.\r\n * @param {any} value\r\n * @param {object} schemaEntry\r\n * @param {object} options\r\n * @return {{ value?: any, isEmptyValue: boolean } | { error: string }}\r\n */\r\nexport function parseValue(value, schemaEntry, options) {\r\n // `null` values (i.e. empty cells) don't get parsed.\r\n if (value === null) {\r\n return {\r\n value: null,\r\n isEmptyValue: true\r\n }\r\n }\r\n\r\n // Parse the value according to the `type` that is specified in the schema entry.\r\n let result\r\n if (schemaEntry.type) {\r\n result = parseValueOfType(\r\n value,\r\n // Get the type of the value.\r\n //\r\n // Handle the case if it's a comma-separated value.\r\n // Example `type`: String[]\r\n // Example Input Value: 'Barack Obama, \"String, with, colons\", Donald Trump'\r\n // Example Parsed Value: ['Barack Obama', 'String, with, colons', 'Donald Trump']\r\n //\r\n Array.isArray(schemaEntry.type) ? schemaEntry.type[0] : schemaEntry.type,\r\n options\r\n )\r\n } else {\r\n // If the `type` is not specified for a given schema entry, the default one is `String`.\r\n result = { value }\r\n // throw new Error('Invalid schema entry: no `type` specified:\\n\\n' + JSON.stringify(schemaEntry, null, 2))\r\n }\r\n\r\n // If there was an error when parsing the value then return the error.\r\n if (result.error) {\r\n return result\r\n }\r\n\r\n // If the parsed value is empty, return it.\r\n if (value === null) {\r\n return {\r\n value: null,\r\n isEmptyValue: true\r\n }\r\n }\r\n\r\n // Value is not empty.\r\n // Validate it and return.\r\n\r\n // Perform `oneOf` validation.\r\n if (schemaEntry.oneOf) {\r\n const errorAndReason = validateOneOf(result.value, schemaEntry.oneOf)\r\n if (errorAndReason) {\r\n return errorAndReason\r\n }\r\n }\r\n\r\n // Perform `validate()` validation.\r\n if (schemaEntry.validate) {\r\n try {\r\n schemaEntry.validate(result.value)\r\n } catch (error) {\r\n return { error: error.message }\r\n }\r\n }\r\n\r\n // Return the value.\r\n return {\r\n value: result.value,\r\n isEmptyValue: isEmptyValue(result.value)\r\n }\r\n}\r\n\r\nfunction validateOneOf(value, oneOf) {\r\n if (oneOf.indexOf(value) < 0) {\r\n return { error: 'invalid', reason: 'unknown' }\r\n }\r\n}\r\n\r\n/**\r\n * Converts cell value to a javascript typed value.\r\n * @param {(string|number|boolean|Date)} value\r\n * @param {function} type\r\n * @return {object} Either `{ value: (string|number|Date|boolean) }` or `{ error: string, reason?: string }`\r\n */\r\nfunction parseValueOfType(value, type) {\r\n switch (type) {\r\n case String:\r\n return parseValueUsingTypeParser(value, StringType)\r\n\r\n case Number:\r\n return parseValueUsingTypeParser(value, NumberType)\r\n\r\n case Date:\r\n return parseValueUsingTypeParser(value, DateType)\r\n\r\n case Boolean:\r\n return parseValueUsingTypeParser(value, BooleanType)\r\n\r\n default:\r\n // Validate `type`\r\n if (typeof type !== 'function') {\r\n throw new Error(`Unsupported schema \\`type\\`: ${type && type.name || type}`)\r\n }\r\n return parseValueUsingTypeParser(value, type)\r\n }\r\n}\r\n\r\n/**\r\n * Converts textual value to a custom value using supplied `type`.\r\n * @param {any} value\r\n * @param {function} type\r\n * @return {{ value: any, error: string }}\r\n */\r\nfunction parseValueUsingTypeParser(value, type) {\r\n try {\r\n const parsedValue = type(value)\r\n // Returning `undefined` from a `type` parser is treated as returning `null`.\r\n if (parsedValue === undefined) {\r\n return { value: null }\r\n }\r\n return { value: parsedValue }\r\n } catch (error) {\r\n const result = { error: error.message }\r\n // Built-in types such as `Number` or `Date` may also report\r\n // a specific `reason` of the error.\r\n if (error.reason) {\r\n result.reason = error.reason;\r\n }\r\n return result\r\n }\r\n}\r\n\r\n// Extracts a substring from a string.\r\nexport function getNextSubstring(string, separatorCharacter, startIndex) {\r\n let i = 0\r\n let substring = ''\r\n while (startIndex + i < string.length) {\r\n const character = string[startIndex + i]\r\n if (character === separatorCharacter) {\r\n return [substring, i]\r\n }\r\n // Previously, it used to treat `\"` character similar to how it's treated in `.csv` files:\r\n // any commas inside quotes are ignored. But then I thought that it could introduce more\r\n // issues than it was originally intending to fix, and it also didn't provide an \"escape\" mechanism.\r\n // Overall, a decision was made to simplify the whole thing and drop the concept of quotes as special characters.\r\n //\r\n // else if (character === '\"') {\r\n // const quotedSubstring = getNextSubstring(string, '\"', startIndex + i + 1)\r\n // substring += quotedSubstring[0]\r\n // i += '\"'.length + quotedSubstring[1] + '\"'.length\r\n // }\r\n else {\r\n substring += character\r\n i++\r\n }\r\n }\r\n return [substring, i]\r\n}\r\n\r\n/**\r\n * Parses a string of comma-separated substrings into an array of substrings.\r\n * (the `export` is just for tests)\r\n * @param {string} string — A string of comma-separated substrings.\r\n * @return {string[]} An array of substrings.\r\n */\r\nexport function parseSeparatedSubstrings(string, separatorCharacter) {\r\n const elements = []\r\n let index = 0\r\n while (index < string.length) {\r\n const [substring, length] = getNextSubstring(string, separatorCharacter, index)\r\n index += length + separatorCharacter.length\r\n elements.push(substring.trim())\r\n }\r\n return elements\r\n}\r\n\r\nfunction transformValue(value, isEmptyValue, path, options) {\r\n if (isEmptyValue) {\r\n if (isObject(value)) {\r\n return options.transformEmptyObject(value, { path })\r\n } else if (Array.isArray(value)) {\r\n return options.transformEmptyArray(value, { path })\r\n }\r\n }\r\n return value\r\n}\r\n\r\nfunction getPropertyPath(propertyName, parentObjectPath) {\r\n return `${parentObjectPath ? parentObjectPath + '.' : ''}${propertyName}`\r\n}\r\n\r\n// Recursively runs `required` validations for the parsed data row tree.\r\nfunction runPendingRequiredValidations(\r\n schemaEntry,\r\n value,\r\n isEmptyValue,\r\n errors,\r\n children,\r\n parentObjectIsRequired,\r\n parentObjectValue,\r\n parentObjectValueIsEmpty,\r\n parentObjectErrors,\r\n columns\r\n) {\r\n let requiredErrors = []\r\n\r\n // See if this property is required.\r\n const isRequired = isPropertyRequired(\r\n schemaEntry,\r\n parentObjectIsRequired,\r\n parentObjectValue,\r\n parentObjectValueIsEmpty,\r\n parentObjectErrors\r\n )\r\n\r\n // If this property is required and empty, create a \"required\" error.\r\n if (isRequired && isEmptyValue) {\r\n requiredErrors.push(createError({\r\n error: 'required',\r\n column: schemaEntry.column,\r\n columnIndex: columns.indexOf(schemaEntry.column),\r\n valueType: schemaEntry.type,\r\n value\r\n }))\r\n }\r\n\r\n // Run `required` validations of the children.\r\n if (children) {\r\n for (const child of children) {\r\n const requiredErrorsOfChild = runPendingRequiredValidations(\r\n child.schemaEntry,\r\n child.value,\r\n child.isEmptyValue,\r\n child.errors,\r\n child.children,\r\n // The following properties describe the parent object of the `child`,\r\n // i.e. the current (iterated) object.\r\n isRequired,\r\n value,\r\n isEmptyValue,\r\n errors,\r\n columns\r\n )\r\n if (requiredErrorsOfChild) {\r\n requiredErrors = requiredErrors.concat(requiredErrorsOfChild)\r\n }\r\n }\r\n }\r\n if (requiredErrors.length > 0) {\r\n return requiredErrors\r\n }\r\n}\r\n\r\nfunction isPropertyRequired(\r\n schemaEntry,\r\n parentObjectIsRequired,\r\n parentObjectValue,\r\n parentObjectValueIsEmpty,\r\n parentObjectErrors\r\n) {\r\n // If the parent object is marked as `required: false` then it's allowed\r\n // to be absent entirely from the input data. If that's the case,\r\n // i.e. if the parent object is absent entirely from the input data,\r\n // then any descendant properties of such object are allowed to be absent too,\r\n // which means that they should also be considered being `required: false`.\r\n //\r\n // Also, if the parent object couldn't be parsed due to some non-`required` errors,\r\n // it can't be known whether it's actually empty or not. In case of such uncertainty,\r\n // the code shouldn't attempt to be overly smart and do things that might not be necessary,\r\n // so such parent object is just assumed to be empty in order to not falsly trigger\r\n // any `required` validations that otherwise wouldn't have been run.\r\n // In other words, skipping some `required` validations is better than\r\n // running `required` validations that shouldn't have been run.\r\n //\r\n if (parentObjectIsRequired === false && (parentObjectValueIsEmpty || parentObjectErrors)) {\r\n return false\r\n }\r\n\r\n return schemaEntry.required && (\r\n typeof schemaEntry.required === 'boolean'\r\n ? schemaEntry.required\r\n : (\r\n // If there were any non-`required` errors when parsing the parent object,\r\n // the `parentObject` will be `undefined`. In that case, \"complex\" `required()`\r\n // validations — the ones where `required` is a function — can't really be run\r\n // because those validations assume a fully and correctly parsed parent object\r\n // be passed as an argument, and the thing is that the `parentObject` is unknown.\r\n // As a result, only \"basic\" `required` validations could be run,\r\n // i.e. the ones where `required` is just a boolean, and \"complex\" `required`\r\n // validations, i.e. the ones where `required` is a functions, should be skipped,\r\n // because it's better to skip some `required` errors than to trigger falsy ones.\r\n parentObjectErrors ? false : schemaEntry.required(parentObjectValue)\r\n )\r\n )\r\n}\r\n\r\nfunction createError({\r\n column,\r\n columnIndex,\r\n valueType,\r\n value,\r\n error: errorMessage,\r\n reason\r\n}) {\r\n const error = {\r\n error: errorMessage,\r\n column,\r\n columnIndex,\r\n value\r\n }\r\n if (reason) {\r\n error.reason = reason\r\n }\r\n // * Regular values specify a `type?` property, which is included in the `error` object.\r\n // * Nested objects specify a `schema` property, which is not included in the `error` object.\r\n if (valueType) {\r\n error.type = valueType\r\n }\r\n return error\r\n}\r\n\r\nfunction validateSchema(schema) {\r\n for (const key of Object.keys(schema)) {\r\n const schemaEntry = schema[key]\r\n // Validate that the `schema` is not using a deprecated `type: nestedSchema` format.\r\n if (typeof schemaEntry.type === 'object' && !Array.isArray(schemaEntry.type)) {\r\n throw new Error('When defining a nested schema, use a `schema` property instead of a `type` property')\r\n }\r\n // Validate that every property has a source `column` title specified for it.\r\n if (!schemaEntry.schema) {\r\n if (!schemaEntry.column) {\r\n throw new Error(`\"column\" not defined for schema entry \"${key}\".`)\r\n }\r\n }\r\n }\r\n\r\n // A nested object could have a `required` property but the only allowed value is `false`.\r\n // The reason why `true` value is not allowed is because in case of a \"required\" error\r\n // there's no single column title corresponding to such nested object, and column title\r\n // is required to create a \"required\" error.\r\n validateObjectSchemaRequiredProperty(schema, undefined)\r\n}\r\n\r\nfunction validateObjectSchemaRequiredProperty(schema, required) {\r\n if (required !== undefined && required !== false) {\r\n throw new Error(`In a schema, a nested object can have a \\`required\\` property but the only allowed value is \\`undefined\\` or \\`false\\`. Otherwise, a \"required\" error for a nested object would have to include a specific \\`column\\` title and a nested object doesn't have one. You've specified the following \\`required\\`: ${required}`)\r\n }\r\n // For each property of the described object.\r\n for (const key of Object.keys(schema)) {\r\n // If this property is itself an object.\r\n if (isObject(schema[key].schema)) {\r\n // Validate that a `column` property can't coexist with a `schema` property.\r\n if (schema[key].column) {\r\n throw new Error(`In a schema, \\`column\\` property is only allowed when describing a property value rather than a nested object. Key: ${key}. Schema:\\n${JSON.stringify(schema[key], null, 2)}`)\r\n }\r\n // Recurse into the child object.\r\n validateObjectSchemaRequiredProperty(schema[key].schema, schema[key].required)\r\n }\r\n }\r\n}\r\n\r\nfunction isEmptyValue(value) {\r\n return value === undefined || value === null\r\n}\r\n\r\nconst DEFAULT_OPTIONS = {\r\n propertyValueWhenColumnIsMissing: undefined,\r\n propertyValueWhenCellIsEmpty: null,\r\n // shouldSkipRequiredValidationWhenColumnIsMissing: () => false,\r\n // `transformEmptyObject(object, { path })` applies to both the top-level object\r\n // and any of its nested objects.\r\n transformEmptyObject: () => null,\r\n transformEmptyArray: () => null,\r\n separatorCharacter: ','\r\n}\r\n\r\nfunction applyDefaultOptions(options) {\r\n if (options) {\r\n return {\r\n ...DEFAULT_OPTIONS,\r\n ...options\r\n }\r\n } else {\r\n return DEFAULT_OPTIONS\r\n }\r\n}\r\n\r\n// This `value` marks the start of a tree structure that is parsed from a given data row.\r\nconst PARSED_OBJECT_TREE_START = {}\r\n\r\nconst objectConstructor = {}.constructor\r\n\r\nfunction isObject(object) {\r\n return object !== undefined && object !== null && object.constructor === objectConstructor\r\n}"],"mappings":";;;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,OAAA,GAAA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K3B,SAAS,IAAI2B,MAAM,KAAK,IAAI,IAAIA,MAAM,CAACnF,WAAW,KAAK8L,iBAAiB;AAC5F"}
1
+ {"version":3,"file":"parseSheetData.js","names":["_Number","_interopRequireDefault","require","_String","_Boolean","_Date","obj","__esModule","_typeof","o","Symbol","iterator","constructor","prototype","_slicedToArray","arr","i","_arrayWithHoles","_iterableToArrayLimit","_unsupportedIterableToArray","_nonIterableRest","r","l","t","e","n","u","a","f","call","next","Object","done","push","value","length","_toArray","_iterableToArray","TypeError","iter","Array","from","isArray","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","enumerable","apply","_objectSpread","arguments","forEach","_defineProperty","getOwnPropertyDescriptors","defineProperties","defineProperty","key","_toPropertyKey","configurable","writable","arg","_toPrimitive","String","input","hint","prim","toPrimitive","undefined","res","Number","_createForOfIteratorHelperLoose","allowArrayLike","it","bind","minLen","_arrayLikeToArray","toString","slice","name","test","len","arr2","parseSheetData","data","schema","optionsCustom","objects","errors","parsedRows","parseSheetDataWithPerRowErrors","parsedRowIndex","_iterator","_step","_step$value","object","rowErrors","concat","map","rowError","row","validateSchema","options","applyDefaultOptions","_data","columns","dataRows","parseDataRow","dataRow","schemaEntry","_parseProperty","parseProperty","isEmptyValue","children","dummyParentObject","PARSED_OBJECT_TREE_START","isRequired","requiredErrors","runPendingRequiredValidations","transformValue","parseObject","path","isEmptyObject","_i","_Object$keys","child","getPropertyPath","columnIndex","column","indexOf","isMissingColumn","_ref","propertyValueWhenColumnIsMissing","parseCellValueWithPossibleErrors","cellValue","_parseCellValue","parseCellValue","errorMessage","error","errorReason","reason","createError","valueType","type","propertyValueWhenCellIsEmpty","parseArrayValue","parseValue","isEmptyArray","reasons","values","parseSeparatedSubstrings","separatorCharacter","substring","_parseValue","result","parseValueOfType","oneOf","errorAndReason","validateOneOf","validate","message","parseValueUsingTypeParser","StringType","NumberType","Date","DateType","Boolean","BooleanType","Error","parsedValue","getNextSubstring","string","startIndex","character","elements","index","_getNextSubstring","_getNextSubstring2","trim","isObject","transformEmptyObject","transformEmptyArray","propertyName","parentObjectPath","parentObjectIsRequired","parentObjectValue","parentObjectValueIsEmpty","parentObjectErrors","isPropertyRequired","_iterator2","_step2","requiredErrorsOfChild","required","_ref2","_i2","_Object$keys2","validateObjectSchemaRequiredProperty","_i3","_Object$keys3","JSON","stringify","DEFAULT_OPTIONS","objectConstructor"],"sources":["../../source/parseSheetData/parseSheetData.js"],"sourcesContent":["import NumberType from './types/Number.js'\r\nimport StringType from './types/String.js'\r\nimport BooleanType from './types/Boolean.js'\r\nimport DateType from './types/Date.js'\r\n\r\n/**\r\n * Converts spreadsheet-alike data structure into an array of JSON objects.\r\n *\r\n * Parameters:\r\n *\r\n * * `data` — An array of rows, each row being an array of cells. The first row should be the list of column headers and the rest of the rows should be the data.\r\n * * `schema` — A \"to JSON\" convertion schema (see above).\r\n * * `options` — (optional) Schema conversion parameters of `read-excel-file`:\r\n * * `propertyValueWhenColumnIsMissing` — By default, when some of the `schema` columns are missing in the input `data`, those properties are set to `undefined` in the output objects. Pass `propertyValueWhenColumnIsMissing: null` to set such \"missing column\" properties to `null` in the output objects.\r\n * * `propertyValueWhenCellIsEmpty` — By default, when it encounters a `null` value in a cell in input `data`, it sets it to `undefined` in the output object. Pass `propertyValueWhenCellIsEmpty: null` to make it set such values as `null`s in output objects.\r\n * // * `shouldSkipRequiredValidationWhenColumnIsMissing: (column: string, { object }) => boolean` — By default, it does apply `required` validation to `schema` properties for which columns are missing in the input `data`. One could pass a custom `shouldSkipRequiredValidationWhenColumnIsMissing(column, { object })` to disable `required` validation for missing columns in some or all cases.\r\n * * `transformEmptyObject(object, { path? })` — By default, it returns `null` for \"empty\" objects. One could override that value using `transformEmptyObject(object, { path })` parameter. The value applies to both top-level object and any nested sub-objects in case of a nested schema, hence the additional (optional) `path?: string` parameter.\r\n * * `transformEmptyArray(array, { path })` — By default, it returns `null` for an \"empty\" array value. One could override that value using `transformEmptyArray(array, { path })` parameter.\r\n * * `separatorCharacter` — By default, it splits array-type cell values by a comma character.\r\n *\r\n * When parsing a property value, in case of an error, the value of that property is gonna be `undefined`.\r\n *\r\n * @param {SheetData} data - An array of rows, each row being an array of cells.\r\n * @param {object} schema\r\n * @param {object} [options]\r\n * @param {any} [options.propertyValueWhenColumnIsMissing] — By default, when some of the `schema` columns are missing in the input `data`, those properties are set to `undefined` in the output objects. Pass `propertyValueWhenColumnIsMissing: null` to set such \"missing column\" properties to `null` in the output objects.\r\n * @param {any} [options.propertyValueWhenCellIsEmpty] — By default, when it encounters a `null` value in a cell in input `data`, it leaves the value as is. Pass a custom `propertyValueWhenCellIsEmpty` to make it set such values to that value.\r\n * // @param {boolean} [options.shouldSkipRequiredValidationWhenColumnIsMissing(column: string, { object })] — By default, it does apply `required` validation to `schema` properties for which columns are missing in the input `data`. One could pass a custom `shouldSkipRequiredValidationWhenColumnIsMissing(column, { object })` to disable `required` validation for missing columns in some or all cases.\r\n * @param {function} [options.transformEmptyObject(object, { path })] — By default, it returns `null` for an \"empty\" resulting object. One could override that value using `transformEmptyObject(object, { path })` parameter. The value applies to both top-level object and any nested sub-objects in case of a nested schema, hence the additional `path?: string` parameter.\r\n * @param {function} [options.transformEmptyArray(array, { path })] — By default, it returns `null` for an \"empty\" array value. One could override that value using `transformEmptyArray(array, { path })` parameter.\r\n * @param {string} [options.separatorCharacter] — When specified, string values will be split by this separator to get the array.\r\n * @return {object} — An object of shape `{ objects, errors }`. Either `objects` or `errors` is going to be `undefined`.\r\n */\r\nexport default function parseSheetData(data, schema, optionsCustom) {\r\n const objects = []\r\n let errors = []\r\n\r\n const parsedRows = parseSheetDataWithPerRowErrors(data, schema, optionsCustom)\r\n let parsedRowIndex = 0\r\n for (const { object, errors: rowErrors } of parsedRows) {\r\n if (rowErrors) {\r\n errors = errors.concat(\r\n rowErrors.map(\r\n // Add row number property to each row error.\r\n rowError => ({ ...rowError, row: parsedRowIndex + 1 })\r\n )\r\n )\r\n } else {\r\n objects.push(object)\r\n }\r\n parsedRowIndex++\r\n }\r\n\r\n if (errors.length > 0) {\r\n return { errors }\r\n }\r\n\r\n return { objects }\r\n}\r\n\r\n// This one is only used in tests.\r\nexport function parseSheetDataWithPerRowErrors(data, schema, optionsCustom) {\r\n validateSchema(schema)\r\n\r\n const options = applyDefaultOptions(optionsCustom)\r\n\r\n const [columns, ...dataRows] = data\r\n\r\n return dataRows.map(row => parseDataRow(row, schema, columns, options))\r\n}\r\n\r\nfunction parseDataRow(dataRow, schema, columns, options) {\r\n // Create a `schemaEntry` for the top-level object.\r\n const schemaEntry = {\r\n schema\r\n }\r\n\r\n // Parse the values in the given data row into an object.\r\n const {\r\n value,\r\n isEmptyValue,\r\n errors,\r\n children\r\n } = parseProperty(dataRow, schemaEntry, undefined, columns, options)\r\n\r\n // Simulate a \"dummy\" parent object for the top-level object.\r\n // It will be used when running `required` validations.\r\n const dummyParentObject = {\r\n // The \"dummy\" parent object has a \"dummy\" value.\r\n // This value is irrelevant because it won't be read anywhere.\r\n value: PARSED_OBJECT_TREE_START,\r\n // The \"dummy\" parent object is empty if the parsed row is empty.\r\n isEmptyValue,\r\n // The \"dummy\" object has the same errors as the parsed row.\r\n errors,\r\n // The parsed object by default is not required to have any data\r\n // so the \"dummy\" object is not required.\r\n isRequired: undefined\r\n }\r\n\r\n // Run any `required` validations.\r\n //\r\n // `required` validations should be run after the entire data row has been parsed,\r\n // i.e. when the entire object structure has been parsed.\r\n // The reason is that a `required` validation could be either a simple boolean or a \"complex\" function.\r\n // In the latter case, the result of a `required()` function may depend on any other property of the object,\r\n // hence the actual `required` flag value could only be obtained after the entire data row has been parsed.\r\n //\r\n // For example, consider a top-level object:\r\n //\r\n // {\r\n // firstName: string,\r\n // lastName: string,\r\n // pet?: { name: string }\r\n // }\r\n //\r\n // A corresponding schema would be:\r\n //\r\n // {\r\n // firstName: {\r\n // required: true\r\n // },\r\n // lastName: {\r\n // required: true\r\n // },\r\n // pet: {\r\n // required: false,\r\n // schema: {\r\n // name: {\r\n // required: true\r\n // }\r\n // }\r\n // }\r\n // }\r\n //\r\n // I.e. when a `pet` exists, it must have a `name`.\r\n //\r\n // In such case, the `required: true` check of the `pet`'s `name` property\r\n // should not be performed if the `pet` is not present, because the `pet` nested object\r\n // is marked as `required: false`, meaning that `pet` data is not required to be present.\r\n //\r\n const requiredErrors = runPendingRequiredValidations(\r\n schemaEntry,\r\n value,\r\n isEmptyValue,\r\n errors,\r\n children,\r\n // Simulate a \"dummy\" parent object for the top-level object.\r\n dummyParentObject.isRequired,\r\n dummyParentObject.value,\r\n dummyParentObject.isEmptyValue,\r\n dummyParentObject.errors,\r\n columns\r\n )\r\n\r\n // If there were any errors, whether caused by `required`\r\n // or occured while parsing the values, return those errors.\r\n if (errors || requiredErrors) {\r\n return {\r\n errors: (errors || []).concat(requiredErrors || [])\r\n }\r\n }\r\n\r\n // Return the parsed object.\r\n return {\r\n object: transformValue(value, isEmptyValue, undefined, options)\r\n }\r\n}\r\n\r\nfunction parseObject(row, schema, path, columns, options) {\r\n const object = {}\r\n let isEmptyObject = true\r\n\r\n let errors = []\r\n\r\n const children = []\r\n\r\n // For each property of the object.\r\n for (const key of Object.keys(schema)) {\r\n const child = parseProperty(row, schema[key], getPropertyPath(key, path), columns, options)\r\n\r\n if (child.errors) {\r\n errors = errors.concat(child.errors)\r\n } else {\r\n object[key] = transformValue(child.value, child.isEmptyValue, getPropertyPath(key, path), options)\r\n // Potentially unmark the object as \"empty\".\r\n if (isEmptyObject && !child.isEmptyValue) {\r\n isEmptyObject = false\r\n }\r\n }\r\n\r\n children.push({\r\n ...child,\r\n // `schemaEntry` will be used when running `required` validation of this property (later),\r\n schemaEntry: schema[key]\r\n })\r\n }\r\n\r\n // If there were any errors, return them.\r\n if (errors.length > 0) {\r\n return {\r\n // Return the errors.\r\n errors,\r\n // Return the `children` because `required` validations still have to be run (later).\r\n children\r\n }\r\n }\r\n\r\n return {\r\n value: object,\r\n isEmptyValue: isEmptyObject,\r\n // Return the `children` because `required` validations still have to be run (later).\r\n children\r\n }\r\n}\r\n\r\nfunction parseProperty(row, schemaEntry, path, columns, options) {\r\n const columnIndex = schemaEntry.column ? columns.indexOf(schemaEntry.column) : undefined\r\n const isMissingColumn = schemaEntry.column ? columnIndex < 0 : undefined\r\n\r\n const {\r\n value,\r\n isEmptyValue,\r\n errors,\r\n children\r\n } = schemaEntry.column\r\n ? (\r\n isMissingColumn\r\n ? { value: options.propertyValueWhenColumnIsMissing, isEmptyValue: true }\r\n : parseCellValueWithPossibleErrors(row[columnIndex], schemaEntry, columnIndex, options)\r\n )\r\n : parseObject(\r\n row,\r\n schemaEntry.schema,\r\n path,\r\n columns,\r\n options\r\n )\r\n\r\n // If there were any errors, return them.\r\n if (errors) {\r\n return {\r\n // Return the errors.\r\n errors,\r\n // Return the `children` because `required` validations still have to be run (later).\r\n children\r\n }\r\n }\r\n\r\n return {\r\n value,\r\n isEmptyValue,\r\n // Return the `children` because `required` validations still have to be run (later).\r\n children\r\n }\r\n}\r\n\r\nfunction parseCellValueWithPossibleErrors(cellValue, schemaEntry, columnIndex, options) {\r\n const {\r\n value,\r\n isEmptyValue,\r\n error: errorMessage,\r\n reason: errorReason\r\n } = parseCellValue(cellValue, schemaEntry, options)\r\n\r\n if (errorMessage) {\r\n const error = createError({\r\n error: errorMessage,\r\n reason: errorReason,\r\n column: schemaEntry.column,\r\n columnIndex,\r\n valueType: schemaEntry.type,\r\n value: cellValue\r\n })\r\n return {\r\n errors: [error]\r\n }\r\n }\r\n\r\n return {\r\n value,\r\n isEmptyValue\r\n }\r\n}\r\n\r\n/**\r\n * Converts a cell value value to a javascript typed value.\r\n * @param {any} cellValue\r\n * @param {object} schemaEntry\r\n * @param {string} propertyPath\r\n * @param {object} options\r\n * @return {{ value?: any, isEmptyValue: boolean } | { error: string, reason?: string }}\r\n */\r\nfunction parseCellValue(cellValue, schemaEntry, options) {\r\n if (cellValue === undefined) {\r\n // This isn't supposed to be possible when reading spreadsheet data:\r\n // cell values are always read as `null` when those cells are empty.\r\n // It's currently impossible for `read-excel-file` to return `undefined` cell value.\r\n // Here it uses some \"sensible default\" fallback by treating `undefined` as \"column missing\".\r\n return {\r\n value: options.propertyValueWhenColumnIsMissing,\r\n isEmptyValue: true\r\n }\r\n }\r\n\r\n if (cellValue === null) {\r\n return {\r\n value: options.propertyValueWhenCellIsEmpty,\r\n isEmptyValue: true\r\n }\r\n }\r\n\r\n // Parse comma-separated cell value.\r\n if (Array.isArray(schemaEntry.type)) {\r\n return parseArrayValue(cellValue, schemaEntry, options)\r\n }\r\n\r\n return parseValue(cellValue, schemaEntry, options)\r\n}\r\n\r\n/**\r\n * Converts textual value to a javascript typed array value.\r\n * @param {any} value\r\n * @param {object} schemaEntry\r\n * @param {object} options\r\n * @return {{ value?: any, isEmptyValue: boolean } | { error: string, reason?: string }}\r\n */\r\nfunction parseArrayValue(value, schemaEntry, options) {\r\n // If the cell value is not a string — i.e. a number, a boolean, a Date —\r\n // then throw an error.\r\n if (typeof value !== 'string') {\r\n return {\r\n error: 'not_a_string'\r\n }\r\n }\r\n\r\n let isEmptyArray = true\r\n\r\n const errors = []\r\n const reasons = []\r\n\r\n const values = parseSeparatedSubstrings(value, options.separatorCharacter).map((substring) => {\r\n // If any substring was already detected to be invalid\r\n // don't attempt to parse any other substrings.\r\n if (errors.length > 0) {\r\n return\r\n }\r\n\r\n // If an empty substring was extracted, it means that there was an out-of-place separator.\r\n if (!substring) {\r\n errors.push('invalid')\r\n reasons.push('syntax')\r\n return\r\n }\r\n\r\n const {\r\n value,\r\n isEmptyValue,\r\n error,\r\n reason\r\n } = parseValue(substring, schemaEntry, options)\r\n\r\n if (error) {\r\n errors.push(error)\r\n reasons.push(reason)\r\n return\r\n }\r\n\r\n if (isEmptyArray && !isEmptyValue) {\r\n isEmptyArray = false\r\n }\r\n\r\n return value\r\n })\r\n\r\n if (errors.length > 0) {\r\n return {\r\n error: errors[0],\r\n reason: reasons[0]\r\n }\r\n }\r\n\r\n return {\r\n value: values,\r\n isEmptyValue: isEmptyArray\r\n }\r\n}\r\n\r\n/**\r\n * Converts textual value to a javascript typed value.\r\n * @param {any} value\r\n * @param {object} schemaEntry\r\n * @param {object} options\r\n * @return {{ value?: any, isEmptyValue: boolean } | { error: string }}\r\n */\r\nexport function parseValue(value, schemaEntry, options) {\r\n // `null` values (i.e. empty cells) don't get parsed.\r\n if (value === null) {\r\n return {\r\n value: null,\r\n isEmptyValue: true\r\n }\r\n }\r\n\r\n // Parse the value according to the `type` that is specified in the schema entry.\r\n let result\r\n if (schemaEntry.type) {\r\n result = parseValueOfType(\r\n value,\r\n // Get the type of the value.\r\n //\r\n // Handle the case if it's a comma-separated value.\r\n // Example `type`: String[]\r\n // Example Input Value: 'Barack Obama, \"String, with, colons\", Donald Trump'\r\n // Example Parsed Value: ['Barack Obama', 'String, with, colons', 'Donald Trump']\r\n //\r\n Array.isArray(schemaEntry.type) ? schemaEntry.type[0] : schemaEntry.type,\r\n options\r\n )\r\n } else {\r\n // If the `type` is not specified for a given schema entry, the `value` will be returned as is.\r\n result = { value }\r\n // throw new Error('Invalid schema entry: no `type` specified:\\n\\n' + JSON.stringify(schemaEntry, null, 2))\r\n }\r\n\r\n // If there was an error when parsing the value then return the error.\r\n if (result.error) {\r\n return result\r\n }\r\n\r\n // If the parsed value is empty, return it.\r\n if (value === null) {\r\n return {\r\n value: null,\r\n isEmptyValue: true\r\n }\r\n }\r\n\r\n // Value is not empty.\r\n // Validate it and return.\r\n\r\n // Perform `oneOf` validation.\r\n if (schemaEntry.oneOf) {\r\n const errorAndReason = validateOneOf(result.value, schemaEntry.oneOf)\r\n if (errorAndReason) {\r\n return errorAndReason\r\n }\r\n }\r\n\r\n // Perform `validate()` validation.\r\n if (schemaEntry.validate) {\r\n try {\r\n schemaEntry.validate(result.value)\r\n } catch (error) {\r\n return { error: error.message }\r\n }\r\n }\r\n\r\n // Return the value.\r\n return {\r\n value: result.value,\r\n isEmptyValue: isEmptyValue(result.value)\r\n }\r\n}\r\n\r\nfunction validateOneOf(value, oneOf) {\r\n if (oneOf.indexOf(value) < 0) {\r\n return { error: 'invalid', reason: 'unknown' }\r\n }\r\n}\r\n\r\n/**\r\n * Converts cell value to a javascript typed value.\r\n * @param {(string|number|boolean|Date)} value\r\n * @param {function} type\r\n * @return {object} Either `{ value: (string|number|Date|boolean) }` or `{ error: string, reason?: string }`\r\n */\r\nfunction parseValueOfType(value, type) {\r\n switch (type) {\r\n case String:\r\n return parseValueUsingTypeParser(value, StringType)\r\n\r\n case Number:\r\n return parseValueUsingTypeParser(value, NumberType)\r\n\r\n case Date:\r\n return parseValueUsingTypeParser(value, DateType)\r\n\r\n case Boolean:\r\n return parseValueUsingTypeParser(value, BooleanType)\r\n\r\n default:\r\n // Validate `type`\r\n if (typeof type !== 'function') {\r\n throw new Error(`Unsupported schema \\`type\\`: ${type && type.name || type}`)\r\n }\r\n return parseValueUsingTypeParser(value, type)\r\n }\r\n}\r\n\r\n/**\r\n * Converts textual value to a custom value using supplied `type`.\r\n * @param {any} value\r\n * @param {function} type\r\n * @return {{ value: any, error: string }}\r\n */\r\nfunction parseValueUsingTypeParser(value, type) {\r\n try {\r\n const parsedValue = type(value)\r\n // Returning `undefined` from a `type` parser is treated as returning `null`.\r\n if (parsedValue === undefined) {\r\n return { value: null }\r\n }\r\n return { value: parsedValue }\r\n } catch (error) {\r\n const result = { error: error.message }\r\n // Built-in types such as `Number` or `Date` may also report\r\n // a specific `reason` of the error.\r\n if (error.reason) {\r\n result.reason = error.reason;\r\n }\r\n return result\r\n }\r\n}\r\n\r\n// Extracts a substring from a string.\r\nexport function getNextSubstring(string, separatorCharacter, startIndex) {\r\n let i = 0\r\n let substring = ''\r\n while (startIndex + i < string.length) {\r\n const character = string[startIndex + i]\r\n if (character === separatorCharacter) {\r\n return [substring, i]\r\n }\r\n // Previously, it used to treat `\"` character similar to how it's treated in `.csv` files:\r\n // any commas inside quotes are ignored. But then I thought that it could introduce more\r\n // issues than it was originally intending to fix, and it also didn't provide an \"escape\" mechanism.\r\n // Overall, a decision was made to simplify the whole thing and drop the concept of quotes as special characters.\r\n //\r\n // else if (character === '\"') {\r\n // const quotedSubstring = getNextSubstring(string, '\"', startIndex + i + 1)\r\n // substring += quotedSubstring[0]\r\n // i += '\"'.length + quotedSubstring[1] + '\"'.length\r\n // }\r\n else {\r\n substring += character\r\n i++\r\n }\r\n }\r\n return [substring, i]\r\n}\r\n\r\n/**\r\n * Parses a string of comma-separated substrings into an array of substrings.\r\n * (the `export` is just for tests)\r\n * @param {string} string — A string of comma-separated substrings.\r\n * @return {string[]} An array of substrings.\r\n */\r\nexport function parseSeparatedSubstrings(string, separatorCharacter) {\r\n const elements = []\r\n let index = 0\r\n while (index < string.length) {\r\n const [substring, length] = getNextSubstring(string, separatorCharacter, index)\r\n index += length + separatorCharacter.length\r\n elements.push(substring.trim())\r\n }\r\n return elements\r\n}\r\n\r\nfunction transformValue(value, isEmptyValue, path, options) {\r\n if (isEmptyValue) {\r\n if (isObject(value)) {\r\n return options.transformEmptyObject(value, { path })\r\n } else if (Array.isArray(value)) {\r\n return options.transformEmptyArray(value, { path })\r\n }\r\n }\r\n return value\r\n}\r\n\r\nfunction getPropertyPath(propertyName, parentObjectPath) {\r\n return `${parentObjectPath ? parentObjectPath + '.' : ''}${propertyName}`\r\n}\r\n\r\n// Recursively runs `required` validations for the parsed data row tree.\r\nfunction runPendingRequiredValidations(\r\n schemaEntry,\r\n value,\r\n isEmptyValue,\r\n errors,\r\n children,\r\n parentObjectIsRequired,\r\n parentObjectValue,\r\n parentObjectValueIsEmpty,\r\n parentObjectErrors,\r\n columns\r\n) {\r\n let requiredErrors = []\r\n\r\n // See if this property is required.\r\n const isRequired = isPropertyRequired(\r\n schemaEntry,\r\n parentObjectIsRequired,\r\n parentObjectValue,\r\n parentObjectValueIsEmpty,\r\n parentObjectErrors\r\n )\r\n\r\n // If this property is required and empty, create a \"required\" error.\r\n if (isRequired && isEmptyValue) {\r\n requiredErrors.push(createError({\r\n error: 'required',\r\n column: schemaEntry.column,\r\n columnIndex: columns.indexOf(schemaEntry.column),\r\n valueType: schemaEntry.type,\r\n value\r\n }))\r\n }\r\n\r\n // Run `required` validations of the children.\r\n if (children) {\r\n for (const child of children) {\r\n const requiredErrorsOfChild = runPendingRequiredValidations(\r\n child.schemaEntry,\r\n child.value,\r\n child.isEmptyValue,\r\n child.errors,\r\n child.children,\r\n // The following properties describe the parent object of the `child`,\r\n // i.e. the current (iterated) object.\r\n isRequired,\r\n value,\r\n isEmptyValue,\r\n errors,\r\n columns\r\n )\r\n if (requiredErrorsOfChild) {\r\n requiredErrors = requiredErrors.concat(requiredErrorsOfChild)\r\n }\r\n }\r\n }\r\n if (requiredErrors.length > 0) {\r\n return requiredErrors\r\n }\r\n}\r\n\r\nfunction isPropertyRequired(\r\n schemaEntry,\r\n parentObjectIsRequired,\r\n parentObjectValue,\r\n parentObjectValueIsEmpty,\r\n parentObjectErrors\r\n) {\r\n // If the parent object is marked as `required: false` then it's allowed\r\n // to be absent entirely from the input data. If that's the case,\r\n // i.e. if the parent object is absent entirely from the input data,\r\n // then any descendant properties of such object are allowed to be absent too,\r\n // which means that they should also be considered being `required: false`.\r\n //\r\n // Also, if the parent object couldn't be parsed due to some non-`required` errors,\r\n // it can't be known whether it's actually empty or not. In case of such uncertainty,\r\n // the code shouldn't attempt to be overly smart and do things that might not be necessary,\r\n // so such parent object is just assumed to be empty in order to not falsly trigger\r\n // any `required` validations that otherwise wouldn't have been run.\r\n // In other words, skipping some `required` validations is better than\r\n // running `required` validations that shouldn't have been run.\r\n //\r\n if (parentObjectIsRequired === false && (parentObjectValueIsEmpty || parentObjectErrors)) {\r\n return false\r\n }\r\n\r\n return schemaEntry.required && (\r\n typeof schemaEntry.required === 'boolean'\r\n ? schemaEntry.required\r\n : (\r\n // If there were any non-`required` errors when parsing the parent object,\r\n // the `parentObject` will be `undefined`. In that case, \"complex\" `required()`\r\n // validations — the ones where `required` is a function — can't really be run\r\n // because those validations assume a fully and correctly parsed parent object\r\n // be passed as an argument, and the thing is that the `parentObject` is unknown.\r\n // As a result, only \"basic\" `required` validations could be run,\r\n // i.e. the ones where `required` is just a boolean, and \"complex\" `required`\r\n // validations, i.e. the ones where `required` is a functions, should be skipped,\r\n // because it's better to skip some `required` errors than to trigger falsy ones.\r\n parentObjectErrors ? false : schemaEntry.required(parentObjectValue)\r\n )\r\n )\r\n}\r\n\r\nfunction createError({\r\n column,\r\n columnIndex,\r\n valueType,\r\n value,\r\n error: errorMessage,\r\n reason\r\n}) {\r\n const error = {\r\n error: errorMessage,\r\n column,\r\n columnIndex,\r\n value\r\n }\r\n if (reason) {\r\n error.reason = reason\r\n }\r\n // * Regular values specify a `type?` property, which is included in the `error` object.\r\n // * Nested objects specify a `schema` property, which is not included in the `error` object.\r\n if (valueType) {\r\n error.type = valueType\r\n }\r\n return error\r\n}\r\n\r\nfunction validateSchema(schema) {\r\n for (const key of Object.keys(schema)) {\r\n const schemaEntry = schema[key]\r\n // Validate that the `schema` is not using a deprecated `type: nestedSchema` format.\r\n if (typeof schemaEntry.type === 'object' && !Array.isArray(schemaEntry.type)) {\r\n throw new Error('When defining a nested schema, use a `schema` property instead of a `type` property')\r\n }\r\n // Validate that every property has a source `column` title specified for it.\r\n if (!schemaEntry.schema) {\r\n if (!schemaEntry.column) {\r\n throw new Error(`\"column\" not defined for schema entry \"${key}\".`)\r\n }\r\n }\r\n }\r\n\r\n // A nested object could have a `required` property but the only allowed value is `false`.\r\n // The reason why `true` value is not allowed is because in case of a \"required\" error\r\n // there's no single column title corresponding to such nested object, and column title\r\n // is required to create a \"required\" error.\r\n validateObjectSchemaRequiredProperty(schema, undefined)\r\n}\r\n\r\nfunction validateObjectSchemaRequiredProperty(schema, required) {\r\n if (required !== undefined && required !== false) {\r\n throw new Error(`In a schema, a nested object can have a \\`required\\` property but the only allowed value is \\`undefined\\` or \\`false\\`. Otherwise, a \"required\" error for a nested object would have to include a specific \\`column\\` title and a nested object doesn't have one. You've specified the following \\`required\\`: ${required}`)\r\n }\r\n // For each property of the described object.\r\n for (const key of Object.keys(schema)) {\r\n // If this property is itself an object.\r\n if (isObject(schema[key].schema)) {\r\n // Validate that a `column` property can't coexist with a `schema` property.\r\n if (schema[key].column) {\r\n throw new Error(`In a schema, \\`column\\` property is only allowed when describing a property value rather than a nested object. Key: ${key}. Schema:\\n${JSON.stringify(schema[key], null, 2)}`)\r\n }\r\n // Recurse into the child object.\r\n validateObjectSchemaRequiredProperty(schema[key].schema, schema[key].required)\r\n }\r\n }\r\n}\r\n\r\nfunction isEmptyValue(value) {\r\n return value === undefined || value === null\r\n}\r\n\r\nconst DEFAULT_OPTIONS = {\r\n propertyValueWhenColumnIsMissing: undefined,\r\n propertyValueWhenCellIsEmpty: null,\r\n // shouldSkipRequiredValidationWhenColumnIsMissing: () => false,\r\n // `transformEmptyObject(object, { path })` applies to both the top-level object\r\n // and any of its nested objects.\r\n transformEmptyObject: () => null,\r\n transformEmptyArray: () => null,\r\n separatorCharacter: ','\r\n}\r\n\r\nfunction applyDefaultOptions(options) {\r\n if (options) {\r\n return {\r\n ...DEFAULT_OPTIONS,\r\n ...options\r\n }\r\n } else {\r\n return DEFAULT_OPTIONS\r\n }\r\n}\r\n\r\n// This `value` marks the start of a tree structure that is parsed from a given data row.\r\nconst PARSED_OBJECT_TREE_START = {}\r\n\r\nconst objectConstructor = {}.constructor\r\n\r\nfunction isObject(object) {\r\n return object !== undefined && object !== null && object.constructor === objectConstructor\r\n}"],"mappings":";;;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,OAAA,GAAAF,sBAAA,CAAAC,OAAA;AACA,IAAAE,QAAA,GAAAH,sBAAA,CAAAC,OAAA;AACA,IAAAG,KAAA,GAAAJ,sBAAA,CAAAC,OAAA;AAAsC,SAAAD,uBAAAK,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,gBAAAA,GAAA;AAAA,SAAAE,QAAAC,CAAA,sCAAAD,OAAA,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C,GAAG,iBAAAwC,MAAA,CAAcsG,IAAI,CAACC,SAAS,CAACnH,MAAM,CAAC5B,GAAG,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAE,CAAC;MACjM;MACA;MACA2I,oCAAoC,CAAC/G,MAAM,CAAC5B,GAAG,CAAC,CAAC4B,MAAM,EAAEA,MAAM,CAAC5B,GAAG,CAAC,CAACuI,QAAQ,CAAC;IAChF;EACF;AACF;AAEA,SAAShF,YAAYA,CAAC9E,KAAK,EAAE;EAC3B,OAAOA,KAAK,KAAKkC,SAAS,IAAIlC,KAAK,KAAK,IAAI;AAC9C;AAEA,IAAMuK,eAAe,GAAG;EACtBrE,gCAAgC,EAAEhE,SAAS;EAC3C4E,4BAA4B,EAAE,IAAI;EAClC;EACA;EACA;EACAoC,oBAAoB,EAAE,SAAAA,qBAAA;IAAA,OAAM,IAAI;EAAA;EAChCC,mBAAmB,EAAE,SAAAA,oBAAA;IAAA,OAAM,IAAI;EAAA;EAC/B9B,kBAAkB,EAAE;AACtB,CAAC;AAED,SAAShD,mBAAmBA,CAACD,OAAO,EAAE;EACpC,IAAIA,OAAO,EAAE;IACX,OAAApD,aAAA,CAAAA,aAAA,KACKuJ,eAAe,GACfnG,OAAO;EAEd,CAAC,MAAM;IACL,OAAOmG,eAAe;EACxB;AACF;;AAEA;AACA,IAAMtF,wBAAwB,GAAG,CAAC,CAAC;AAEnC,IAAMuF,iBAAiB,GAAG,CAAC,CAAC,CAAC9L,WAAW;AAExC,SAASuK,QAAQA,CAACpF,MAAM,EAAE;EACxB,OAAOA,MAAM,KAAK3B,SAAS,IAAI2B,MAAM,KAAK,IAAI,IAAIA,MAAM,CAACnF,WAAW,KAAK8L,iBAAiB;AAC5F"}
@@ -4,24 +4,48 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports["default"] = unzipFromStream;
7
+ var _fflate = require("fflate");
7
8
  var _buffer = require("buffer");
8
- var _unzipper = _interopRequireDefault(require("unzipper"));
9
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
10
- // `unzipper` has a bug when it doesn't include "@aws-sdk/client-s3" package in the `dependencies`
11
- // which causes some "bundlers" throw an error.
12
- // https://github.com/ZJONSSON/node-unzipper/issues/330
9
+ // This code was originally submitted by Stian Jensen.
10
+ // https://github.com/catamphetamine/read-excel-file/pull/122
11
+
12
+ // A `*.zip` file consists of individual file entries with the "total" summary section
13
+ // placed at the end of the file rather than at the start of it, which was originally done
14
+ // to allow for easy append of data to a given `.zip` file.
15
+ // https://en.wikipedia.org/wiki/ZIP_(file_format)
16
+ //
17
+ // But this also means that reading a `*.zip` file from a stream can't really be done
18
+ // using the "officially recommended" way of first reading the "total" summary section
19
+ // and only then reading the individual file entries specified in that summary section.
20
+ //
21
+ // So in order to be able to read a `*.zip` file from a stream, some corners have to be cut.
22
+ // For example, the "total" summary section is completely ignored and instead the reader
23
+ // should adopt "data recovery" software approach — it should proactively "scan" the input stream
24
+ // for individual file entries and handle them one-by-one as they come.
13
25
  //
14
- // One workaround is to install "@aws-sdk/client-s3" package manually, which would still lead to increased bundle size.
15
- // If the code is bundled for server-side-use only, that is will not be used in a web browser,
16
- // then the increased bundle size would not be an issue.
26
+ // Such approach doesn't seem to contradict with the XLSX specification
27
+ // because an `*.xlsx` files is supposed to be a normal `.zip` archive
28
+ // without any "trickery" such as "deleted" files or "garbage" data
29
+ // hiding under the hood.
17
30
  //
18
- // Another workaround could be to "alias" "@aws-sdk/client-s3" package in a "bundler" configuration file
19
- // with a path to a `*.js` file containing just "export default null". But that kind of a workaround would also
20
- // result in errors when using other packages that `import` anything from "@aws-sdk/client-s3" package,
21
- // so it's not really a workaround but more of a ticking bomb.
31
+ // So when handling `*.xlsx` file, we assume that each such file must start
32
+ // with an individual file entry followed by another individual file entry, etc.
22
33
  //
23
- // Althernatively, it could use `fflate` if someone writes an example of handling a Node.js stream.
34
+ // When the "summary" section is reached, we assume that the archive has ended.
35
+ //
36
+ // To read a `.zip` archive, the code uses `fflate`'s `Unzip` class
37
+ // with `UnzipInflate` decompression implementation to decompress the data
38
+ // that was previously compressed using `DEFLATE` compressing algorithm,
39
+ // which is what `*.xlsx` files use.
40
+ //
41
+ // The `Unzip` class doesn't speak the Node.js stream interface, and `fflate`'s readme
42
+ // doesn't include a clear "reading a `.zip` file from a Node.js stream" section.
24
43
  // https://github.com/101arrowz/fflate/issues/251
44
+ // Instead, the `Unzip` class has its own `push(chunk)` / `onfile` / `entry.ondata` protocol.
45
+ // This code reads the binary input stream and forwards each chunk of it to `unzip.push()`,
46
+ // and then collects the decompressed file entries.
47
+ //
48
+
25
49
  /**
26
50
  * Reads `*.zip` file contents.
27
51
  * @param {Stream} stream
@@ -33,7 +57,6 @@ function unzipFromStream(stream) {
33
57
  // The `files` object stores the files and their contents.
34
58
  var files = {};
35
59
  return new Promise(function (resolve, reject) {
36
- var promises = [];
37
60
  var errored = false;
38
61
  var onError = function onError(error) {
39
62
  if (!errored) {
@@ -41,83 +64,137 @@ function unzipFromStream(stream) {
41
64
  reject(error);
42
65
  }
43
66
  };
44
- stream
45
- // This first "error" listener catches the original stream errors.
46
- //
47
- // That's because the .pipe() method does not automatically propagate errors
48
- // from a source (input) stream to the destination stream or the end of the pipeline.
49
- // You would need to attach an 'error' event handler to each stream in the chain.
50
- //
51
- // A more convenient alternative would be to use `stream.pipeline()` function:
52
- // `pipeline(stream1, stream2, (error) => { ... })`
53
- //
54
- .on('error', onError)
55
- // Pipe the input stream through the unzipper stream.
56
- .pipe(_unzipper["default"].Parse())
57
- // This second "error" listener catches the unzipper stream errors.
58
- //
59
- // That's because the .pipe() method does not automatically propagate errors
60
- // from a source (input) stream to the destination stream or the end of the pipeline.
61
- // You would need to attach an 'error' event handler to each stream in the chain.
62
- //
63
- // A more convenient alternative would be to use `stream.pipeline()` function:
64
- // `pipeline(stream1, stream2, (error) => { ... })`
65
- //
66
- .on('error', onError)
67
- // The unzipper stream is closed when all `entries` have been reported.
68
- .on('finish', function () {
69
- if (!errored) {
70
- // Wait for all `entries` to be read.
71
- // The second argument of `.then()` function is not required
72
- // but I didn't remove it just to potentially prevent any potential silly bugs
73
- // in case of some potential changes in some potential future.
74
- Promise.all(promises).then(function () {
75
- resolve(files);
76
- }, onError);
67
+ var _createZipFileValidat = createZipFileValidator(function (isValid) {
68
+ if (!isValid) {
69
+ onError(new Error('Invalid `.zip` archive'));
70
+ }
71
+ }),
72
+ validateChunk = _createZipFileValidat.validateChunk;
73
+
74
+ // `Unzip` discovers each individual file entry in the input data stream
75
+ // and then calls the callback function for each such entry.
76
+ var unzip = new _fflate.Unzip(function (entry) {
77
+ // If there already was an error while reading this `.zip` file,
78
+ // ignore any follow-up entries.
79
+ if (errored) {
80
+ return;
81
+ }
82
+
83
+ // Skip directory entries (their names end with a slash).
84
+ // Only files are of any interest.
85
+ if (entry.name.endsWith('/')) {
86
+ return;
77
87
  }
78
- }).on('entry', function (entry) {
88
+
79
89
  // See if this file should be ignored.
80
- var ignore = false;
81
- // `entry.type` could be 'Directory' or 'File'.
82
- // Ignore anything except files.
83
- if (entry.type === 'Directory') {
84
- ignore = true;
90
+ // If it should, this entry won't be processed, i.e. `Unzip` will not try
91
+ // to decompress its data, and will just discard it.
92
+ if (filter && !filter({
93
+ path: entry.name
94
+ })) {
95
+ return;
96
+ }
97
+ var chunks = [];
98
+
99
+ // `entry.ondata` is called with each decompressed chunk of the entry,
100
+ // and a final time with `isLast === true` once the entry is complete.
101
+ entry.ondata = function (error, chunk, isLast) {
102
+ if (error) {
103
+ return onError(error);
104
+ }
105
+ chunks.push(chunk);
106
+ if (isLast) {
107
+ files[entry.name] = _buffer.Buffer.concat(chunks);
108
+ }
109
+ };
110
+
111
+ // Start decompressing this entry.
112
+ entry.start();
113
+ });
114
+
115
+ // Register the decompressor for the data that was compressed using
116
+ // `DEFLATE` compression algorithm (compression method `8`),
117
+ // which is what `.xlsx` files use.
118
+ unzip.register(_fflate.UnzipInflate);
119
+ stream
120
+ // Catch errors emitted from the input stream (for example, a file read error).
121
+ .on('error', onError)
122
+ // When another chunk of data is read from the input stream.
123
+ .on('data', function (chunk) {
124
+ // If there already was an error while reading this `.zip` file,
125
+ // ignore any follow-up data chunks.
126
+ if (errored) {
127
+ return;
85
128
  }
129
+ // Validate the `.zip` archive as its data comes through.
130
+ validateChunk(chunk);
131
+ // If the `.zip` archive is found to be invalid, stop any further
132
+ // processing of it.
86
133
  if (errored) {
87
- ignore = true;
134
+ return;
88
135
  }
89
- if (filter) {
90
- if (!filter({
91
- path: entry.path
92
- })) {
93
- ignore = true;
94
- }
136
+ // Push the next data chunk to `fflate`'s `Unzip` class instance.
137
+ // The `.push()` function is synchronous, meaning that by the time it returns,
138
+ // any complete files entries encountered so far have already been decompressed
139
+ // and populated in the `files` object.
140
+ try {
141
+ unzip.push(chunk, false);
142
+ } catch (error) {
143
+ onError(error);
95
144
  }
96
-
97
- // If this file should be ignored.
98
- if (ignore) {
99
- // Call `entry.autodrain()` when you do not intend to process a specific `entry`'s raw data.
100
- // Otherwise, if an `entry` is not consumed (via .pipe(), .buffer(), or .autodrain()),
101
- // the stream will halt, preventing further file processing.
102
- entry.autodrain().on('error', onError);
145
+ })
146
+ // When there's no more data in the input stream to consume,
147
+ // finish reading the `.zip` archive.
148
+ .on('end', function () {
149
+ // If there were any errors when reading the `.zip` archive,
150
+ // don't `resolve()` with anything.
151
+ if (errored) {
103
152
  return;
104
153
  }
105
- var chunks = [];
106
- promises.push(new Promise(function (resolve) {
107
- // `entry` seems to be a generic Node.js stream.
108
- // `entry.pipe()` pipes the file contents to a stream.
109
- // `entry.stream()` returns a readable stream.
110
- // `entry.buffer()` returns a promise that resolves to a `Buffer` with the file contents.
111
- entry.on('data', function (data) {
112
- chunks.push(data);
113
- }).on('error', function (error) {
114
- onError(error);
115
- }).on('finish', function () {
116
- files[entry.path] = _buffer.Buffer.concat(chunks);
117
- resolve();
118
- });
119
- }));
154
+ try {
155
+ // Signal the end of the archive to `fflate`'s `Unzip` class instance.
156
+ // It will flush any remaining state in it.
157
+ unzip.push(new Uint8Array(0), true);
158
+ // Resolve with the unzipped files.
159
+ resolve(files);
160
+ } catch (error) {
161
+ onError(error);
162
+ }
120
163
  });
121
164
  });
122
165
  }
166
+
167
+ // Every section in a `.zip` archive is marked with 4 bytes, the first two of which
168
+ // are `0x50` and `0x4B`, which reads "PK", referencing the initials of the inventor Phil Katz.
169
+ //
170
+ // It looks like `fflate`'s `Unzip` doesn't ever complain about whatever data is thrown at it.
171
+ // Due to how `.zip` file format is defined, "garbage" data could be placed at various
172
+ // places in it and it'd still be a valid `.zip` archive. It's likely that for this reason
173
+ // `fflate` doesn't ever complain and simply emits no entries when fed any kind of invalid data.
174
+ //
175
+ // In order to introduce some basic validation, here we specifically demand
176
+ // that a `.zip` archive must at least start with an individual file entry
177
+ // because an `.xlsx` file creator softwared really shouldn't attempt doing
178
+ // anything "funny" when writing a file, hence this adherence requirement.
179
+ //
180
+ function createZipFileValidator(onValidationResult) {
181
+ var firstBytesCount = 2;
182
+ var firstBytes = [];
183
+ var firstBytesCheckResult;
184
+ return {
185
+ validateChunk: function validateChunk(chunk) {
186
+ if (firstBytes.length < 2) {
187
+ var i = 0;
188
+ while (i < chunk.length && i < firstBytesCount) {
189
+ firstBytes.push(chunk[i]);
190
+ i++;
191
+ }
192
+ if (firstBytes.length === 2) {
193
+ var isValid = firstBytes[0] === 0x50 && firstBytes[1] === 0x4B;
194
+ onValidationResult(isValid);
195
+ }
196
+ }
197
+ }
198
+ };
199
+ }
123
200
  //# sourceMappingURL=unzipFromStream.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"unzipFromStream.js","names":["_buffer","require","_unzipper","_interopRequireDefault","obj","__esModule","unzipFromStream","stream","_ref","arguments","length","undefined","filter","files","Promise","resolve","reject","promises","errored","onError","error","on","pipe","unzip","Parse","all","then","entry","ignore","type","path","autodrain","chunks","push","data","Buffer","concat"],"sources":["../../source/zip/unzipFromStream.js"],"sourcesContent":["import { Buffer } from 'buffer'\r\n\r\n// `unzipper` has a bug when it doesn't include \"@aws-sdk/client-s3\" package in the `dependencies`\r\n// which causes some \"bundlers\" throw an error.\r\n// https://github.com/ZJONSSON/node-unzipper/issues/330\r\n//\r\n// One workaround is to install \"@aws-sdk/client-s3\" package manually, which would still lead to increased bundle size.\r\n// If the code is bundled for server-side-use only, that is will not be used in a web browser,\r\n// then the increased bundle size would not be an issue.\r\n//\r\n// Another workaround could be to \"alias\" \"@aws-sdk/client-s3\" package in a \"bundler\" configuration file\r\n// with a path to a `*.js` file containing just \"export default null\". But that kind of a workaround would also\r\n// result in errors when using other packages that `import` anything from \"@aws-sdk/client-s3\" package,\r\n// so it's not really a workaround but more of a ticking bomb.\r\n//\r\nimport unzip from 'unzipper'\r\n\r\n// Althernatively, it could use `fflate` if someone writes an example of handling a Node.js stream.\r\n// https://github.com/101arrowz/fflate/issues/251\r\n\r\n/**\r\n * Reads `*.zip` file contents.\r\n * @param {Stream} stream\r\n * @return {Promise<Record<string,Buffer>>} Resolves to an object holding `*.zip` file entries. P.S. `Buffer` is a `Uint8Array`.\r\n */\r\nexport default function unzipFromStream(stream, { filter } = {}) {\r\n\t// The `files` object stores the files and their contents.\r\n\tconst files = {}\r\n\r\n\treturn new Promise((resolve, reject) => {\r\n\t\tconst promises = []\r\n\r\n\t\tlet errored = false\r\n\r\n\t\tconst onError = (error) => {\r\n\t\t\tif (!errored) {\r\n\t\t\t\terrored = true\r\n\t\t\t\treject(error)\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tstream\r\n\t\t\t// This first \"error\" listener catches the original stream errors.\r\n\t\t\t//\r\n\t\t\t// That's because the .pipe() method does not automatically propagate errors\r\n\t\t\t// from a source (input) stream to the destination stream or the end of the pipeline.\r\n\t\t\t// You would need to attach an 'error' event handler to each stream in the chain.\r\n\t\t\t//\r\n\t\t\t// A more convenient alternative would be to use `stream.pipeline()` function:\r\n\t\t\t// `pipeline(stream1, stream2, (error) => { ... })`\r\n\t\t\t//\r\n\t\t\t.on('error', onError)\r\n\t\t\t// Pipe the input stream through the unzipper stream.\r\n\t\t\t.pipe(unzip.Parse())\r\n\t\t\t// This second \"error\" listener catches the unzipper stream errors.\r\n\t\t\t//\r\n\t\t\t// That's because the .pipe() method does not automatically propagate errors\r\n\t\t\t// from a source (input) stream to the destination stream or the end of the pipeline.\r\n\t\t\t// You would need to attach an 'error' event handler to each stream in the chain.\r\n\t\t\t//\r\n\t\t\t// A more convenient alternative would be to use `stream.pipeline()` function:\r\n\t\t\t// `pipeline(stream1, stream2, (error) => { ... })`\r\n\t\t\t//\r\n\t\t\t.on('error', onError)\r\n\t\t\t// The unzipper stream is closed when all `entries` have been reported.\r\n\t\t\t.on('finish', () => {\r\n\t\t\t\tif (!errored) {\r\n\t\t\t\t\t// Wait for all `entries` to be read.\r\n\t\t\t\t\t// The second argument of `.then()` function is not required\r\n\t\t\t\t\t// but I didn't remove it just to potentially prevent any potential silly bugs\r\n\t\t\t\t\t// in case of some potential changes in some potential future.\r\n\t\t\t\t\tPromise.all(promises).then(() => {\r\n\t\t\t\t\t\tresolve(files)\r\n\t\t\t\t\t}, onError)\r\n\t\t\t\t}\r\n\t\t\t})\r\n\t\t\t.on('entry', (entry) => {\r\n\t\t\t\t// See if this file should be ignored.\r\n\t\t\t\tlet ignore = false\r\n\t\t\t\t// `entry.type` could be 'Directory' or 'File'.\r\n\t\t\t\t// Ignore anything except files.\r\n\t\t\t\tif (entry.type === 'Directory') {\r\n\t\t\t\t\tignore = true\r\n\t\t\t\t}\r\n\t\t\t\tif (errored) {\r\n\t\t\t\t\tignore = true\r\n\t\t\t\t}\r\n\t\t\t\tif (filter) {\r\n\t\t\t\t\tif (!filter({ path: entry.path })) {\r\n\t\t\t\t\t\tignore = true\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// If this file should be ignored.\r\n\t\t\t\tif (ignore) {\r\n\t\t\t\t\t// Call `entry.autodrain()` when you do not intend to process a specific `entry`'s raw data.\r\n\t\t\t\t\t// Otherwise, if an `entry` is not consumed (via .pipe(), .buffer(), or .autodrain()),\r\n\t\t\t\t\t// the stream will halt, preventing further file processing.\r\n\t\t\t\t\tentry.autodrain().on('error', onError)\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\r\n\t\t\t\tconst chunks = []\r\n\r\n\t\t\t\tpromises.push(new Promise((resolve) => {\r\n\t\t\t\t\t// `entry` seems to be a generic Node.js stream.\r\n\t\t\t\t\t// `entry.pipe()` pipes the file contents to a stream.\r\n\t\t\t\t\t// `entry.stream()` returns a readable stream.\r\n\t\t\t\t\t// `entry.buffer()` returns a promise that resolves to a `Buffer` with the file contents.\r\n\t\t\t\t\tentry\r\n\t\t\t\t\t\t.on('data', (data) => {\r\n\t\t\t\t\t\t\tchunks.push(data)\r\n\t\t\t\t\t\t})\r\n\t\t\t\t\t\t.on('error', (error) => {\r\n\t\t\t\t\t\t\tonError(error)\r\n\t\t\t\t\t\t})\r\n\t\t\t\t\t\t.on('finish', () => {\r\n\t\t\t\t\t\t\tfiles[entry.path] = Buffer.concat(chunks)\r\n\t\t\t\t\t\t\tresolve()\r\n\t\t\t\t\t\t})\r\n\t\t\t\t}))\r\n\t\t\t})\r\n\t})\r\n}"],"mappings":";;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAeA,IAAAC,SAAA,GAAAC,sBAAA,CAAAF,OAAA;AAA4B,SAAAE,uBAAAC,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,gBAAAA,GAAA;AAb5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AAEA;AACA;AACA;AACA;AACA;AACe,SAASE,eAAeA,CAACC,MAAM,EAAmB;EAAA,IAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAJ,CAAC,CAAC;IAAbG,MAAM,GAAAJ,IAAA,CAANI,MAAM;EACvD;EACA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ACA;QACAD,KAAK,CAACI,SAAS,CAAC,CAAC,CAACV,EAAE,CAAC,OAAO,EAAEF,OAAO,CAAC;QACtC;MACD;MAEA,IAAMa,MAAM,GAAG,EAAE;MAEjBf,QAAQ,CAACgB,IAAI,CAAC,IAAInB,OAAO,CAAC,UAACC,OAAO,EAAK;QACtC;QACA;QACA;QACA;QACAY,KAAK,CACHN,EAAE,CAAC,MAAM,EAAE,UAACa,IAAI,EAAK;UACrBF,MAAM,CAACC,IAAI,CAACC,IAAI,CAAC;QAClB,CAAC,CAAC,CACDb,EAAE,CAAC,OAAO,EAAE,UAACD,KAAK,EAAK;UACvBD,OAAO,CAACC,KAAK,CAAC;QACf,CAAC,CAAC,CACDC,EAAE,CAAC,QAAQ,EAAE,YAAM;UACnBR,KAAK,CAACc,KAAK,CAACG,IAAI,CAAC,GAAGK,cAAM,CAACC,MAAM,CAACJ,MAAM,CAAC;UACzCjB,OAAO,CAAC,CAAC;QACV,CAAC,CAAC;MACJ,CAAC,CAAC,CAAC;IACJ,CAAC,CAAC;EACJ,CAAC,CAAC;AACH"}
1
+ {"version":3,"file":"unzipFromStream.js","names":["_fflate","require","_buffer","unzipFromStream","stream","_ref","arguments","length","undefined","filter","files","Promise","resolve","reject","errored","onError","error","_createZipFileValidat","createZipFileValidator","isValid","Error","validateChunk","unzip","Unzip","entry","name","endsWith","path","chunks","ondata","chunk","isLast","push","Buffer","concat","start","register","UnzipInflate","on","Uint8Array","onValidationResult","firstBytesCount","firstBytes","firstBytesCheckResult","i"],"sources":["../../source/zip/unzipFromStream.js"],"sourcesContent":["// This code was originally submitted by Stian Jensen.\r\n// https://github.com/catamphetamine/read-excel-file/pull/122\r\n\r\n// A `*.zip` file consists of individual file entries with the \"total\" summary section\r\n// placed at the end of the file rather than at the start of it, which was originally done\r\n// to allow for easy append of data to a given `.zip` file.\r\n// https://en.wikipedia.org/wiki/ZIP_(file_format)\r\n//\r\n// But this also means that reading a `*.zip` file from a stream can't really be done\r\n// using the \"officially recommended\" way of first reading the \"total\" summary section\r\n// and only then reading the individual file entries specified in that summary section.\r\n//\r\n// So in order to be able to read a `*.zip` file from a stream, some corners have to be cut.\r\n// For example, the \"total\" summary section is completely ignored and instead the reader\r\n// should adopt \"data recovery\" software approach — it should proactively \"scan\" the input stream\r\n// for individual file entries and handle them one-by-one as they come.\r\n//\r\n// Such approach doesn't seem to contradict with the XLSX specification\r\n// because an `*.xlsx` files is supposed to be a normal `.zip` archive\r\n// without any \"trickery\" such as \"deleted\" files or \"garbage\" data\r\n// hiding under the hood.\r\n//\r\n// So when handling `*.xlsx` file, we assume that each such file must start\r\n// with an individual file entry followed by another individual file entry, etc.\r\n//\r\n// When the \"summary\" section is reached, we assume that the archive has ended.\r\n//\r\n// To read a `.zip` archive, the code uses `fflate`'s `Unzip` class\r\n// with `UnzipInflate` decompression implementation to decompress the data\r\n// that was previously compressed using `DEFLATE` compressing algorithm,\r\n// which is what `*.xlsx` files use.\r\n//\r\n// The `Unzip` class doesn't speak the Node.js stream interface, and `fflate`'s readme\r\n// doesn't include a clear \"reading a `.zip` file from a Node.js stream\" section.\r\n// https://github.com/101arrowz/fflate/issues/251\r\n// Instead, the `Unzip` class has its own `push(chunk)` / `onfile` / `entry.ondata` protocol.\r\n// This code reads the binary input stream and forwards each chunk of it to `unzip.push()`,\r\n// and then collects the decompressed file entries.\r\n//\r\nimport { Unzip, UnzipInflate } from 'fflate'\r\n\r\nimport { Buffer } from 'buffer'\r\n\r\n/**\r\n * Reads `*.zip` file contents.\r\n * @param {Stream} stream\r\n * @return {Promise<Record<string,Buffer>>} Resolves to an object holding `*.zip` file entries. P.S. `Buffer` is a `Uint8Array`.\r\n */\r\nexport default function unzipFromStream(stream, { filter } = {}) {\r\n\t// The `files` object stores the files and their contents.\r\n\tconst files = {}\r\n\r\n\treturn new Promise((resolve, reject) => {\r\n\t\tlet errored = false\r\n\r\n\t\tconst onError = (error) => {\r\n\t\t\tif (!errored) {\r\n\t\t\t\terrored = true\r\n\t\t\t\treject(error)\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst { validateChunk } = createZipFileValidator((isValid) => {\r\n\t\t\tif (!isValid) {\r\n\t\t\t\tonError(new Error('Invalid `.zip` archive'))\r\n\t\t\t}\r\n\t\t})\r\n\r\n\t\t// `Unzip` discovers each individual file entry in the input data stream\r\n\t\t// and then calls the callback function for each such entry.\r\n\t\tconst unzip = new Unzip((entry) => {\r\n\t\t\t// If there already was an error while reading this `.zip` file,\r\n\t\t\t// ignore any follow-up entries.\r\n\t\t\tif (errored) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\r\n\t\t\t// Skip directory entries (their names end with a slash).\r\n\t\t\t// Only files are of any interest.\r\n\t\t\tif (entry.name.endsWith('/')) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\r\n\t\t\t// See if this file should be ignored.\r\n\t\t\t// If it should, this entry won't be processed, i.e. `Unzip` will not try\r\n\t\t\t// to decompress its data, and will just discard it.\r\n\t\t\tif (filter && !filter({ path: entry.name })) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\r\n\t\t\tconst chunks = []\r\n\r\n\t\t\t// `entry.ondata` is called with each decompressed chunk of the entry,\r\n\t\t\t// and a final time with `isLast === true` once the entry is complete.\r\n\t\t\tentry.ondata = (error, chunk, isLast) => {\r\n\t\t\t\tif (error) {\r\n\t\t\t\t\treturn onError(error)\r\n\t\t\t\t}\r\n\t\t\t\tchunks.push(chunk)\r\n\t\t\t\tif (isLast) {\r\n\t\t\t\t\tfiles[entry.name] = Buffer.concat(chunks)\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t// Start decompressing this entry.\r\n\t\t\tentry.start()\r\n\t\t})\r\n\r\n\t\t// Register the decompressor for the data that was compressed using\r\n\t\t// `DEFLATE` compression algorithm (compression method `8`),\r\n\t\t// which is what `.xlsx` files use.\r\n\t\tunzip.register(UnzipInflate)\r\n\r\n\t\tstream\r\n\t\t\t// Catch errors emitted from the input stream (for example, a file read error).\r\n\t\t\t.on('error', onError)\r\n\t\t\t// When another chunk of data is read from the input stream.\r\n\t\t\t.on('data', (chunk) => {\r\n\t\t\t\t// If there already was an error while reading this `.zip` file,\r\n\t\t\t\t// ignore any follow-up data chunks.\r\n\t\t\t\tif (errored) {\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\t\t\t\t// Validate the `.zip` archive as its data comes through.\r\n\t\t\t\tvalidateChunk(chunk)\r\n\t\t\t\t// If the `.zip` archive is found to be invalid, stop any further\r\n\t\t\t\t// processing of it.\r\n\t\t\t\tif (errored) {\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\t\t\t\t// Push the next data chunk to `fflate`'s `Unzip` class instance.\r\n\t\t\t\t// The `.push()` function is synchronous, meaning that by the time it returns,\r\n\t\t\t\t// any complete files entries encountered so far have already been decompressed\r\n\t\t\t\t// and populated in the `files` object.\r\n\t\t\t\ttry {\r\n\t\t\t\t\tunzip.push(chunk, false)\r\n\t\t\t\t} catch (error) {\r\n\t\t\t\t\tonError(error)\r\n\t\t\t\t}\r\n\t\t\t})\r\n\t\t\t// When there's no more data in the input stream to consume,\r\n\t\t\t// finish reading the `.zip` archive.\r\n\t\t\t.on('end', () => {\r\n\t\t\t\t// If there were any errors when reading the `.zip` archive,\r\n\t\t\t\t// don't `resolve()` with anything.\r\n\t\t\t\tif (errored) {\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\t\t\t\ttry {\r\n\t\t\t\t\t// Signal the end of the archive to `fflate`'s `Unzip` class instance.\r\n\t\t\t\t\t// It will flush any remaining state in it.\r\n\t\t\t\t\tunzip.push(new Uint8Array(0), true)\r\n\t\t\t\t\t// Resolve with the unzipped files.\r\n\t\t\t\t\tresolve(files)\r\n\t\t\t\t} catch (error) {\r\n\t\t\t\t\tonError(error)\r\n\t\t\t\t}\r\n\t\t\t})\r\n\t})\r\n}\r\n\r\n// Every section in a `.zip` archive is marked with 4 bytes, the first two of which\r\n// are `0x50` and `0x4B`, which reads \"PK\", referencing the initials of the inventor Phil Katz.\r\n//\r\n// It looks like `fflate`'s `Unzip` doesn't ever complain about whatever data is thrown at it.\r\n// Due to how `.zip` file format is defined, \"garbage\" data could be placed at various\r\n// places in it and it'd still be a valid `.zip` archive. It's likely that for this reason\r\n// `fflate` doesn't ever complain and simply emits no entries when fed any kind of invalid data.\r\n//\r\n// In order to introduce some basic validation, here we specifically demand\r\n// that a `.zip` archive must at least start with an individual file entry\r\n// because an `.xlsx` file creator softwared really shouldn't attempt doing\r\n// anything \"funny\" when writing a file, hence this adherence requirement.\r\n//\r\nfunction createZipFileValidator(onValidationResult) {\r\n\tconst firstBytesCount = 2\r\n\tconst firstBytes = []\r\n\tlet firstBytesCheckResult\r\n\treturn {\r\n\t\tvalidateChunk(chunk) {\r\n\t\t\tif (firstBytes.length < 2) {\r\n\t\t\t\tlet i = 0\r\n\t\t\t\twhile (i < chunk.length && i < firstBytesCount) {\r\n\t\t\t\t\tfirstBytes.push(chunk[i])\r\n\t\t\t\t\ti++\r\n\t\t\t\t}\r\n\t\t\t\tif (firstBytes.length === 2) {\r\n\t\t\t\t\tconst isValid = firstBytes[0] === 0x50 && firstBytes[1] === 0x4B\r\n\t\t\t\t\tonValidationResult(isValid)\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}"],"mappings":";;;;;;AAuCA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,OAAA,GAAAD,OAAA;AAzCA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAKA;AACA;AACA;AACA;AACA;AACe,SAASE,eAAeA,CAACC,MAAM,EAAmB;EAAA,IAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,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