{"size": 1564, "ext": "js", "max_stars_repo_path": "modules/zip/src/zip-loader.js", "max_stars_repo_name": "nshen/loaders.gl", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/zip/src/zip-loader.js", "max_issues_repo_name": "nshen/loaders.gl", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/zip/src/zip-loader.js", "max_forks_repo_name": "nshen/loaders.gl", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.5094339623, "max_line_length": 92, "alphanum_fraction": 0.5645780051}
import JSZip from 'jszip';

export const ZipLoader = {
  name: 'Zip Archive',
  extensions: ['zip'],
  category: 'archive',
  parse: parseZipAsync
};

// TODO - Could return a map of promises, perhaps as an option...
function parseZipAsync(data, options) {
  const promises = [];
  const fileMap = {};

  const jsZip = new JSZip();
  return (
    jsZip
      .loadAsync(data, options)
      .then(zip => {
        // start to load each file in this zip
        zip.forEach((relativePath, zipEntry) => {
          const subFilename = zipEntry.name;

          const promise = jsZip
            .file(subFilename)
            // jszip supports both arraybuffer and text, the main loaders.gl types
            // https://stuk.github.io/jszip/documentation/api_zipobject/async.html
            .async(options.dataType || 'arraybuffer')
            .then(arrayBuffer => {
              // Store file data in map
              fileMap[relativePath] = arrayBuffer;
            })
            .catch(error => {
              options.log.error(`Unable to read ${subFilename} from zip archive: ${error}`);
              // Store error in place of data in map
              fileMap[relativePath] = error;
            });

          // Ensure Promise.all doesn't ignore rejected promises.
          promises.push(promise.catch(e => e));
        });

        return Promise.all(promises);
      })
      // Return fileMap
      .then(() => fileMap)
      .catch(error => {
        options.log.error(`Unable to read zip archive: ${error}`);
        throw error;
      })
  );
}
