json.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.flattenJSON = void 0;
  4. const buffer_1 = require("@jsonjoy.com/fs-node-builtins/lib/internal/buffer");
  5. const path_1 = require("@jsonjoy.com/fs-node-builtins/lib/path");
  6. const pathJoin = path_1.posix ? path_1.posix.join : path_1.join;
  7. const flattenJSON = (nestedJSON) => {
  8. const flatJSON = {};
  9. function flatten(pathPrefix, node) {
  10. for (const path in node) {
  11. const contentOrNode = node[path];
  12. // TODO: Can we avoid using `join` here? Just concatenate?
  13. const joinedPath = pathJoin(pathPrefix, path);
  14. if (typeof contentOrNode === 'string' || contentOrNode instanceof buffer_1.Buffer) {
  15. flatJSON[joinedPath] = contentOrNode;
  16. }
  17. else if (typeof contentOrNode === 'object' &&
  18. contentOrNode !== null &&
  19. !(contentOrNode instanceof buffer_1.Buffer) &&
  20. Object.keys(contentOrNode).length > 0) {
  21. // empty directories need an explicit entry and therefore get handled in `else`, non-empty ones are implicitly considered
  22. flatten(joinedPath, contentOrNode);
  23. }
  24. else {
  25. // without this branch null, empty-object or non-object entries would not be handled in the same way
  26. // by both fromJSON() and fromNestedJSON()
  27. flatJSON[joinedPath] = null;
  28. }
  29. }
  30. }
  31. flatten('', nestedJSON);
  32. return flatJSON;
  33. };
  34. exports.flattenJSON = flattenJSON;
  35. //# sourceMappingURL=json.js.map