[
  {
    "path": ".babelrc",
    "content": "{\n  \"presets\": [[\"env\", { \"targets\": { \"node\": true } }], \"stage-3\", \"react\"]\n}\n"
  },
  {
    "path": ".gitignore",
    "content": "# Logs\nlogs\n*.log\n\n# Dependencies\nnode_modules\n\n# Debug log from npm\nnpm-debug.log\n\n# Jest\ncoverage\n\n# Flow\nflow-coverage\nflow-typed\n\n# Build output\ndist"
  },
  {
    "path": ".nvmrc",
    "content": "8\n"
  },
  {
    "path": ".travis.yml",
    "content": "sudo: false\nlanguage: node_js\ncache:\n  yarn: true\n  directories:\n    - node_modules\nnode_js:\n- '8'\nscript:\n- npm run precommit\nafter_success:\n# Deploy code coverage report to codecov.io\n- npm run test:coverage:deploy\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2017 Sean Matheson, Ben Newman\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "### Update\n\nI haven't been focusing on this library as I tend to reach for Next.js for my SSR needs. If anyone is interested in maintaining the library further I am happy to add you as a collaborator to the project. \n\nAs an alternative I can highly recommend [react-ssr-prepass](https://github.com/FormidableLabs/react-ssr-prepass), developed by @kitten of Formidable Labs, which provides the same functionality with built in support for suspense.\n\n### Disclaimer\n\nThis library does not operate in an idiomatic manner against React. It makes some assumptions about the internals of React and makes calls against Components directly. This is a risk as it likely to break with future releases of React, i.e. the upcoming Suspense release.\n\nPersonally, I've found this library helpful in providing me with a solution for my server side rendering data fetching needs. That being said I very much look forward to being able to move over to Suspense as soon as it is stable and avoid having to use hacks/workarounds such as this library.\n\nPlease consider carefully before adopting this library. If you are happy to take on the risk I would recommend you write an abstraction over it that will allow you to easily remove/replace it from your codebase with Suspense or another more idiomatic solution.\n\n----\n\n\n# react-tree-walker 🌲\n\nWalk a React (or Preact) element tree, executing a \"visitor\" function against each element.\n\n[![npm](https://img.shields.io/npm/v/react-tree-walker.svg?style=flat-square)](http://npm.im/react-tree-walker)\n[![MIT License](https://img.shields.io/npm/l/react-tree-walker.svg?style=flat-square)](http://opensource.org/licenses/MIT)\n[![Travis](https://img.shields.io/travis/ctrlplusb/react-tree-walker.svg?style=flat-square)](https://travis-ci.org/ctrlplusb/react-tree-walker)\n[![Codecov](https://img.shields.io/codecov/c/github/ctrlplusb/react-tree-walker.svg?style=flat-square)](https://codecov.io/github/ctrlplusb/react-tree-walker)\n\n## TOCs\n\n* [Introduction](#introduction)\n* [Illustrative Example](#illustrative-example)\n* [Order of Execution](#order-of-execution)\n* [API](#api)\n\n## Introduction\n\nInspired/lifted from the awesome [`react-apollo`](https://github.com/apollostack/react-apollo) project. 😗\n\nThis modified version expands upon the design, making it `Promise` based, allowing the visitor to return a `Promise`, which would subsequently delay the tree walking until the `Promise` is resolved. The tree is still walked in a depth-first fashion.\n\nWith this you could, for example, perform pre-rendering parses on your React element tree to do things like data prefetching. Which can be especially helpful when dealing with declarative APIs such as the one provided by React Router 4.\n\n# Illustrative Example\n\nIn the below example we will create a visitor that will walk a React application, looking for any \"class\" component that has a `getData` method on it. We will then execute the `getData` function, storing the results into an array.\n\n```jsx\nimport reactTreeWalker from 'react-tree-walker'\n\nclass DataFetcher extends React.Component {\n  constructor(props) {\n    super(props)\n    this.getData = this.getData.bind(this)\n  }\n\n  getData() {\n    // Supports promises! You could call an API for example to fetch some\n    // data, or do whatever \"bootstrapping\" you desire.\n    return Promise.resolve(this.props.id)\n  }\n\n  render() {\n    return <div>{this.props.children}</div>\n  }\n}\n\nconst app = (\n  <div>\n    <h1>Hello World!</h1>\n    <DataFetcher id={1} />\n    <DataFetcher id={2}>\n      <DataFetcher id={3}>\n        <DataFetcher id={4} />\n      </DataFetcher>\n    </DataFetcher>\n    <DataFetcher id={5} />\n  </div>\n)\n\nconst values = []\n\n// You provide this! See the API docs below for full details.\nfunction visitor(element, instance) {\n  if (instance && typeof instance.getData) {\n    return instance.getData().then(value => {\n      values.push(value)\n      // Return \"false\" to indicate that we do not want to visit \"3\"'s children,\n      // therefore we do not expect \"4\" to make it into our values array.\n      return value !== 3\n    })\n  }\n}\n\nreactTreeWalker(app, visitor)\n  .then(() => {\n    console.log(values) // [1, 2, 3, 5];\n    // Now is a good time to call React's renderToString whilst exposing\n    // whatever values you built up to your app.\n  })\n  // since v3.0.0 you need to do your own error handling!\n  .catch(err => console.error(err))\n```\n\nNot a particularly useful piece of code, but hopefully it is illustrative enough as to indicate the posibilities. One could use this to warm a cache or a `redux` state, subsequently performing a `renderToString` execution with all the required data in place.\n\n## Order of Execution\n\n`react-tree-walker` walks your React application in a depth-first fashion, i.e. from the top down, visiting each child until their are no more children available before moving on to the next element. We can illustrate this behaviour using the below example:\n\n```jsx\n<div>\n  <h1>Foo</h1>\n  <section>\n    <p>One</p>\n    <p>Two</p>\n  </section>\n  <Footer />\n</div>\n```\n\nIn this example the order of elements being visited would be:\n\n    div -> h1 -> \"Foo\" -> section -> p -> \"One\" -> p -> \"Two\" -> Footer\n\nWhilst your application is being walked its behaviour will be much the same as if it were being rendered on the server - i.e. the `componentWillMount` lifecycle will be executed for any \"class\" components, and context provided by any components will be passed down and become available to child components.\n\nDespite emulating a server side render, the tree walking process is far cheaper as it doesn't actually perform any rendering of the element tree to a string. It simply interogates your app building up an object/element tree. The really expensive cycles will likely be the API calls that you make. 😀\n\nThat being said you do have a bail-out ability allowing you to suspend the traversal down a branch of the tree. To do so you simply need to return `false` from your visitor function, or if returning a `Promise` ensure that the `Promise` resolves a `false` for the same behaviour.\n\n## API\n\nThe API is very simple at the moment, only exposing a single function. We will describe the API of the `reactTreeWalker` function below as well as the API for the `visitor` function that `reactTreeWalker` expects as a parameter.\n\n---\n\n### **reactTreeWalker**\n\nThe default export of the library. The function that performs the magic.\n\n```javascript\nconst reactTreeWalker = require('react-tree-walker')\n```\n\n_or_\n\n```javascript\nimport reactTreeWalker from 'react-tree-walker'\n```\n\n**Parameters**\n\n* **tree** (React/Preact element, _required_)\n\n  The react application you wish to walk.\n\n  e.g. `<div>Hello world</div>`\n\n* **visitor** (`Function`, _required_)\n\n  The function you wish to execute against _each_ element that is walked on the `tree`.\n\n  See its [API docs](#visitor) below.\n\n* **context** (`Object`, _optional_)\n\n  Any root context you wish to provide to your application.\n\n  e.g. `{ myContextItem: 'foo' }`\n\n* **options** (`Object`, _optional_)\n\n  Additional options/configuration. It currently supports the following values:\n\n  * _componentWillUnmount_: Enable this to have the `componentWillUnmount` lifecycle event be executed whilst walking your tree. Defaults to `false`. This was added as an experimental additional flag to help with applications where they have critical disposal logic being executed within the `componentWillUnmount` lifecycle event.\n\n**Returns**\n\nA `Promise` that resolves when the tree walking is completed.\n\n---\n\n### **visitor**\n\nThe function that you create and provide to `reactTreeWalker`.\n\nIt should encapsulates the logic you wish to execute against each element.\n\n**Parameters**\n\n* **element** (React/Preact element, _required_)\n\n  The current element being walked.\n\n* **instance** (Component Instance, _optional_)\n\n  If the current element being walked is a \"class\" Component then this will contain the instance of the Component - allowing you to interface with its methods etc.\n\n* **context** (`Object`, _required_)\n\n  The React context that is available to the current element. `react-tree-walker` emulates React in exposing context down the tree.\n\n* **childContext** (`Object`, _optional_)\n\n  If the current element being walked is a \"class\" Component and it exposes additional \"child\" context (via the `getChildContext` method) then this will contain the context that is being provided by the component instance.\n\n**Returns**\n\nIf you return `false` then the children of the current element will not be visited.\n\ne.g.\n\n```javascript\nfunction visitor(element) {\n  if (element.type === 'menu') {\n    // We will not traverse the children for any <menu /> nodes\n    return 'false'\n  }\n}\n```\n\nYou can also return a `Promise` which will cause the tree walking to wait for the `Promise` to be resolved before attempting to visit the children for the current element.\n\n```javascript\nfunction visitor(element, instance) {\n  // This will make every visit take 1 second to execution.\n  return new Promise(resolve => setTimeout(resolve, 1000))\n}\n```\n\nYou can make the Promise resolve a `false` to indicate that you do not want the children of the current element to be visited.\n\n```javascript\nfunction visitor(element, instance) {\n  // Only the first element will be executed, and it will take 1 second to complete.\n  return (\n    new Promise(resolve => setTimeout(resolve, 1000))\n      // This prevents any walking down the current elements children\n      .then(() => false)\n  )\n}\n```\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"react-tree-walker\",\n  \"version\": \"4.3.0\",\n  \"description\": \"Walk a React element tree, executing a provided function against each node.\",\n  \"license\": \"MIT\",\n  \"main\": \"dist/react-tree-walker.js\",\n  \"files\": [\n    \"*.js\",\n    \"*.md\",\n    \"dist\"\n  ],\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/ctrlplusb/react-tree-walker.git\"\n  },\n  \"homepage\": \"https://github.com/ctrlplusb/react-tree-walker#readme\",\n  \"author\": \"Sean Matheson <sean@ctrlplusb.com>\",\n  \"keywords\": [\n    \"react\",\n    \"react-element\",\n    \"util\",\n    \"tree\",\n    \"visitor\"\n  ],\n  \"scripts\": {\n    \"build\": \"node ./tools/scripts/build.js\",\n    \"clean\": \"rimraf ./dist && rimraf ./coverage\",\n    \"lint\": \"eslint src\",\n    \"precommit\": \"lint-staged && npm run test\",\n    \"prepublish\": \"npm run build\",\n    \"test\": \"jest\",\n    \"test:coverage\": \"npm run test -- --coverage\",\n    \"test:coverage:deploy\": \"npm run test:coverage && codecov\"\n  },\n  \"peerDependencies\": {\n    \"react\": \"^0.14.0 || ^15.0.0 || ^16.0.0\"\n  },\n  \"devDependencies\": {\n    \"app-root-dir\": \"1.0.2\",\n    \"babel-cli\": \"^6.26.0\",\n    \"babel-core\": \"^6.26.3\",\n    \"babel-eslint\": \"^8.2.6\",\n    \"babel-jest\": \"^23.4.2\",\n    \"babel-plugin-external-helpers\": \"^6.22.0\",\n    \"babel-polyfill\": \"^6.26.0\",\n    \"babel-preset-env\": \"^1.7.0\",\n    \"babel-preset-react\": \"6.24.1\",\n    \"babel-preset-stage-3\": \"6.24.1\",\n    \"babel-register\": \"^6.26.0\",\n    \"change-case\": \"^3.0.2\",\n    \"codecov\": \"^3.0.4\",\n    \"cross-env\": \"^5.2.0\",\n    \"enzyme\": \"^3.4.1\",\n    \"enzyme-to-json\": \"^3.3.4\",\n    \"eslint\": \"^4.19.1\",\n    \"eslint-config-airbnb\": \"^17.0.0\",\n    \"eslint-config-prettier\": \"^2.6.0\",\n    \"eslint-plugin-import\": \"^2.14.0\",\n    \"eslint-plugin-jsx-a11y\": \"^6.1.1\",\n    \"eslint-plugin-react\": \"^7.10.0\",\n    \"gzip-size\": \"^5.0.0\",\n    \"husky\": \"^0.14.3\",\n    \"in-publish\": \"2.0.0\",\n    \"jest\": \"^23.5.0\",\n    \"lint-staged\": \"^7.2.2\",\n    \"preact\": \"^8.3.0\",\n    \"prettier\": \"^1.14.2\",\n    \"pretty-bytes\": \"5.1.0\",\n    \"prop-types\": \"^15.6.2\",\n    \"ramda\": \"^0.25.0\",\n    \"react\": \"^16.4.2\",\n    \"react-addons-test-utils\": \"^15.6.2\",\n    \"react-dom\": \"^16.4.2\",\n    \"readline-sync\": \"1.4.9\",\n    \"rimraf\": \"^2.6.2\",\n    \"rollup\": \"^0.64.1\",\n    \"rollup-plugin-babel\": \"^3.0.7\",\n    \"rollup-plugin-uglify\": \"^4.0.0\"\n  },\n  \"jest\": {\n    \"collectCoverageFrom\": [\n      \"src/**/*.{js,jsx}\"\n    ],\n    \"snapshotSerializers\": [\n      \"<rootDir>/node_modules/enzyme-to-json/serializer\"\n    ],\n    \"testPathIgnorePatterns\": [\n      \"<rootDir>/(coverage|dist|node_modules|tools)/\"\n    ]\n  },\n  \"eslintConfig\": {\n    \"root\": true,\n    \"parser\": \"babel-eslint\",\n    \"env\": {\n      \"browser\": true,\n      \"es6\": true,\n      \"node\": true,\n      \"jest\": true\n    },\n    \"extends\": [\n      \"airbnb\",\n      \"prettier\",\n      \"prettier/react\",\n      \"prettier/standard\"\n    ],\n    \"rules\": {\n      \"camelcase\": 0,\n      \"import/prefer-default-export\": 0,\n      \"import/no-extraneous-dependencies\": 0,\n      \"no-nested-ternary\": 0,\n      \"no-underscore-dangle\": 0,\n      \"react/destructuring-assignment\": 0,\n      \"react/no-array-index-key\": 0,\n      \"react/react-in-jsx-scope\": 0,\n      \"semi\": [\n        2,\n        \"never\"\n      ],\n      \"react/forbid-prop-types\": 0,\n      \"react/jsx-filename-extension\": 0,\n      \"react/sort-comp\": 0\n    }\n  },\n  \"eslintIgnore\": [\n    \"node_modules/\",\n    \"dist/\",\n    \"coverage/\"\n  ],\n  \"prettier\": {\n    \"semi\": false,\n    \"singleQuote\": true,\n    \"trailingComma\": \"all\"\n  },\n  \"lint-staged\": {\n    \"*.js\": [\n      \"prettier --write \\\"src/**/*.js\\\"\",\n      \"git add\"\n    ]\n  }\n}\n"
  },
  {
    "path": "rollup-min.config.js",
    "content": "const { uglify } = require('rollup-plugin-uglify')\nconst packageJson = require('./package.json')\n\nconst baseConfig = require('./rollup.config.js')\n\nbaseConfig.plugins.push(uglify())\nbaseConfig.output.file = `dist/${packageJson.name}.min.js`\n\nmodule.exports = baseConfig\n"
  },
  {
    "path": "rollup.config.js",
    "content": "const babel = require('rollup-plugin-babel')\nconst changeCase = require('change-case')\nconst packageJson = require('./package.json')\n\nprocess.env.BABEL_ENV = 'production'\n\nmodule.exports = {\n  external: ['react'],\n  input: 'src/index.js',\n  output: {\n    file: `dist/${packageJson.name}.js`,\n    format: 'cjs',\n    sourcemap: true,\n    name: changeCase\n      .titleCase(packageJson.name.replace(/-/g, ' '))\n      .replace(/ /g, ''),\n  },\n  plugins: [\n    babel({\n      babelrc: false,\n      exclude: 'node_modules/**',\n      presets: [['env', { modules: false }], 'stage-3', 'react'],\n      plugins: ['external-helpers'],\n    }),\n  ],\n}\n"
  },
  {
    "path": "src/__tests__/index.test.js",
    "content": "/* eslint-disable react/sort-comp */\n/* eslint-disable react/no-multi-comp */\n/* eslint-disable react/prop-types */\n/* eslint-disable react/prefer-stateless-function */\n/* eslint-disable react/require-default-props */\n/* eslint-disable class-methods-use-this */\n\nimport React, {\n  createElement as reactCreateElement,\n  Component as ReactComponent,\n} from 'react'\nimport ReactDOM from 'react-dom'\nimport {\n  createElement as preactCreateElement,\n  Component as PreactComponent,\n} from 'preact'\nimport PropTypes from 'prop-types'\nimport reactTreeWalker from '../index'\n\nconst resolveLater = result =>\n  new Promise(resolve =>\n    setTimeout(() => {\n      resolve(result)\n    }, 10),\n  )\n\ndescribe('reactTreeWalker', () => {\n  describe('react + preact', () => {\n    ;[\n      { Component: ReactComponent, h: reactCreateElement },\n      { Component: PreactComponent, h: preactCreateElement },\n    ].forEach(({ Component, h }) => {\n      const Stateless = jest.fn(({ children }) => <div>{children}</div>)\n      Stateless.contextTypes = { theContext: PropTypes.string.isRequired }\n\n      class Stateful extends Component {\n        getData() {\n          return typeof this.props.data === 'function'\n            ? this.props.data()\n            : this.props.data\n        }\n\n        render() {\n          return h('div', null, this.props.children)\n        }\n      }\n\n      const createTree = ({ async } = { async: false }) => {\n        const Foo = Stateful\n        const Bob = Stateless\n        return h('div', null, [\n          h('h1', null, 'Hello World!'),\n          h(Foo, { data: async ? () => resolveLater(1) : 1 }),\n          h(\n            Foo,\n            {\n              data: async ? () => resolveLater(2) : 2,\n            },\n            h('div', null, [\n              h(\n                Bob,\n                null,\n                h(Foo, {\n                  children: [\n                    h(Foo, { data: async ? () => resolveLater(5) : 5 }),\n                    h(Foo, { data: async ? () => resolveLater(6) : 6 }),\n                  ],\n                  data: async ? () => resolveLater(4) : 4,\n                }),\n              ),\n              h('div', null, 'hi!'),\n            ]),\n          ),\n          h(Foo, { data: async ? () => resolveLater(3) : 3 }),\n        ])\n      }\n\n      it('simple sync visitor', () => {\n        const actual = []\n        const visitor = (element, instance) => {\n          if (instance && typeof instance.getData === 'function') {\n            const data = instance.getData()\n            actual.push(data)\n          }\n        }\n        return reactTreeWalker(createTree(), visitor).then(() => {\n          const expected = [1, 2, 4, 5, 6, 3]\n          expect(actual).toEqual(expected)\n        })\n      })\n\n      it('promise based visitor', () => {\n        const actual = []\n        const visitor = (element, instance) => {\n          if (instance && typeof instance.getData === 'function') {\n            return instance.getData().then(data => {\n              actual.push(data)\n              return true\n            })\n          }\n          return true\n        }\n        return reactTreeWalker(createTree({ async: true }), visitor).then(\n          () => {\n            const expected = [1, 2, 4, 5, 6, 3]\n            expect(actual).toEqual(expected)\n          },\n        )\n      })\n\n      it('promise based visitor stops resolving', () => {\n        const actual = []\n        const visitor = (element, instance) => {\n          if (instance && typeof instance.getData === 'function') {\n            return instance.getData().then(data => {\n              actual.push(data)\n              return data !== 4\n            })\n          }\n          return true\n        }\n        return reactTreeWalker(createTree({ async: true }), visitor).then(\n          () => {\n            const expected = [1, 2, 4, 3]\n            expect(actual).toEqual(expected)\n          },\n        )\n      })\n\n      it('componentWillMount & setState', () => {\n        let actual = {}\n\n        class Foo extends Component {\n          constructor(props) {\n            super(props)\n            this.state = { foo: 'foo' }\n          }\n\n          componentWillMount() {\n            this.setState({ foo: 'bar' })\n            this.setState((state, props) => ({\n              other: `I am ${props.value} ${state.foo}`,\n            }))\n          }\n\n          render() {\n            actual = this.state\n            return h('div', null, this.state.foo)\n          }\n        }\n\n        return reactTreeWalker(h(Foo, { value: 'foo' }), () => true).then(\n          () => {\n            const expected = { foo: 'bar', other: 'I am foo bar' }\n            expect(actual).toMatchObject(expected)\n          },\n        )\n      })\n\n      it('UNSAFE_componentWillMount', () => {\n        let actual = {}\n\n        class Foo extends Component {\n          constructor(props) {\n            super(props)\n            this.state = { foo: 'foo' }\n          }\n\n          UNSAFE_componentWillMount() {\n            this.setState({ foo: 'bar' })\n          }\n\n          render() {\n            actual = this.state\n            return h('div', null, this.state.foo)\n          }\n        }\n\n        return reactTreeWalker(h(Foo, { value: 'foo' }), () => true).then(\n          () => {\n            const expected = { foo: 'bar' }\n            expect(actual).toMatchObject(expected)\n          },\n        )\n      })\n\n      it('getDerivedStateFromProps', () => {\n        let actual = {}\n\n        class Foo extends Component {\n          constructor(props) {\n            super(props)\n            this.state = { foo: 'foo' }\n          }\n\n          static getDerivedStateFromProps(props, state) {\n            return { foo: `${state.foo}bar` }\n          }\n\n          render() {\n            actual = this.state\n            return h('div', null, this.state.foo)\n          }\n        }\n\n        return reactTreeWalker(h(Foo, { value: 'foo' }), () => true).then(\n          () => {\n            const expected = { foo: 'foobar' }\n            expect(actual).toMatchObject(expected)\n          },\n        )\n      })\n\n      it('calls componentWillUnmount', () => {\n        let called = true\n\n        class Foo extends Component {\n          componentWillUnmount() {\n            called = true\n          }\n\n          render() {\n            return 'foo'\n          }\n        }\n\n        return reactTreeWalker(h(Foo), () => true, null, {\n          componentWillUnmount: true,\n        }).then(() => {\n          expect(called).toBeTruthy()\n        })\n      })\n\n      it('getChildContext', () => {\n        class Foo extends Component {\n          getChildContext() {\n            return { foo: 'val' }\n          }\n\n          render() {\n            return h('div', null, this.props.children)\n          }\n        }\n\n        let actual\n        function Bar(props, context) {\n          actual = context\n          return 'bar'\n        }\n        Bar.contextTypes = { foo: PropTypes.string.isRequired }\n\n        return reactTreeWalker(h(Foo, null, h(Bar)), () => true).then(() => {\n          const expected = { foo: 'val' }\n          expect(actual).toMatchObject(expected)\n        })\n      })\n\n      it('works with instance-as-result component', () => {\n        class Foo extends Component {\n          render() {\n            return h('div', null, [\n              h(Stateful, { data: 1 }),\n              h(Stateful, { data: 2 }),\n            ])\n          }\n        }\n        const Bar = props => new Foo(props)\n        const actual = []\n        const visitor = (element, instance) => {\n          if (instance && typeof instance.getData === 'function') {\n            const data = instance.getData()\n            actual.push(data)\n          }\n        }\n        return reactTreeWalker(h(Bar), visitor).then(() => {\n          const expected = [1, 2]\n          expect(actual).toEqual(expected)\n        })\n      })\n\n      describe('error handling', () => {\n        it('throws async visitor errors', () => {\n          const tree = createTree({ async: true })\n          const actual = []\n          const visitor = (element, instance) => {\n            if (instance && typeof instance.getData === 'function') {\n              return instance.getData().then(data => {\n                actual.push(data)\n                if (data === 4) {\n                  return Promise.reject(new Error('Visitor made 💩'))\n                }\n                return true\n              })\n            }\n            return true\n          }\n          return reactTreeWalker(tree, visitor).then(\n            () => {\n              throw new Error('Expected error was not thrown')\n            },\n            err => {\n              expect(err).toMatchObject(new Error('Visitor made 💩'))\n              expect(actual).toEqual([1, 2, 4])\n            },\n          )\n        })\n\n        it('throws sync visitor errors', () => {\n          const tree = createTree()\n          const actual = []\n          const visitor = (element, instance) => {\n            if (instance && typeof instance.getData === 'function') {\n              const data = instance.getData()\n              actual.push(data)\n              if (data === 4) {\n                throw new Error('Visitor made 💩')\n              }\n            }\n            return true\n          }\n          return reactTreeWalker(tree, visitor).then(\n            () => {\n              throw new Error('Expected error was not thrown')\n            },\n            err => {\n              expect(err).toMatchObject(new Error('Visitor made 💩'))\n              expect(actual).toEqual([1, 2, 4])\n            },\n          )\n        })\n      })\n\n      it('complex context configuration', () => {\n        class Wrapper extends Component {\n          getChildContext() {\n            this.id = 0\n\n            return {\n              foo: {\n                getNextId: () => {\n                  this.id += 1\n                  return this.id\n                },\n              },\n            }\n          }\n\n          render() {\n            return this.props.children\n          }\n        }\n\n        const ids = []\n        class Baz extends Component {\n          getData() {\n            if (!this.context.foo) {\n              return undefined\n            }\n            return new Promise(resolve => setTimeout(resolve, 1000)).then(\n              () => {\n                this.resolved = true\n                ids.push(this.context.foo.getNextId())\n              },\n            )\n          }\n\n          render() {\n            return this.resolved ? this.props.children : null\n          }\n        }\n\n        const visitor = (element, instance) => {\n          if (instance && typeof instance.getData === 'function') {\n            return instance.getData()\n          }\n          return undefined\n        }\n\n        const app = h(\n          Wrapper,\n          null,\n          h(\n            'div',\n            null,\n            h(Baz, null, h('div', null, [h(Baz), h(Baz), h(Baz)])),\n          ),\n        )\n\n        return reactTreeWalker(app, visitor).then(() => {\n          expect(ids).toEqual([1, 2, 3, 4])\n        })\n      })\n    })\n  })\n\n  describe('react', () => {\n    it('supports new context API', () => {\n      const { Provider, Consumer } = React.createContext()\n\n      class Foo extends React.Component {\n        render() {\n          return this.props.children\n        }\n      }\n\n      const tree = (\n        <Provider\n          value={{\n            message: 'Message',\n            identity: x => x,\n          }}\n        >\n          <Consumer>\n            {({ message, identity }) => (\n              <strong>\n                <i>{`${message}: ${identity('Hello world')}`}</i>\n              </strong>\n            )}\n          </Consumer>\n          bar\n          <Foo>foo</Foo>\n        </Provider>\n      )\n\n      const elements = []\n      return reactTreeWalker(tree, element => {\n        elements.push(element)\n      }).then(() => {\n        expect(elements.pop()).toBe('foo')\n        expect(elements.pop().type).toBe(Foo)\n        expect(elements.pop()).toBe('bar')\n        expect(elements.pop()).toBe('Message: Hello world')\n        expect(elements.pop().type).toBe('i')\n        expect(elements.pop().type).toBe('strong')\n      })\n    })\n\n    it('supports portals', () => {\n      class Foo extends ReactComponent {\n        getData() {\n          return this.props.data\n        }\n\n        render() {\n          return 'foo'\n        }\n      }\n\n      function Baz() {\n        return ReactDOM.createPortal(\n          <div>\n            <Foo data={1} />\n            <Foo data={2} />\n          </div>,\n          document.createElement('div'),\n        )\n      }\n\n      const actual = []\n      const visitor = (element, instance) => {\n        if (instance && typeof instance.getData === 'function') {\n          const data = instance.getData()\n          actual.push(data)\n        }\n      }\n      return reactTreeWalker(<Baz />, visitor).then(() => {\n        const expected = [1, 2]\n        expect(actual).toEqual(expected)\n      })\n    })\n\n    it('supports forwardRef', () => {\n      class Foo extends ReactComponent {\n        render() {\n          return this.props.children\n        }\n      }\n\n      const Bar = React.forwardRef((props, ref) => <Foo ref={ref} {...props} />)\n      const ref = React.createRef()\n\n      const tree = <Bar ref={ref}>foo</Bar>\n\n      const elements = []\n      return reactTreeWalker(tree, element => {\n        elements.push(element)\n      }).then(() => {\n        expect(elements.pop()).toBe('foo')\n        expect(elements.pop().type).toBe(Foo)\n        expect(elements.pop().type).toBe(Bar)\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "src/index.js",
    "content": "/* eslint-disable no-console */\n\n// Inspired by the awesome work by the Apollo team: 😘\n// https://github.com/apollographql/react-apollo/blob/master/src/getDataFromTree.ts\n//\n// This version has been adapted to be Promise based and support native Preact.\n\nconst defaultOptions = {\n  componentWillUnmount: false,\n}\n\nconst forwardRefSymbol = Symbol.for('react.forward_ref')\n\n// Lifted from https://github.com/sindresorhus/p-reduce\n// Thanks @sindresorhus! 🙏\nconst pReduce = (iterable, reducer, initVal) =>\n  new Promise((resolve, reject) => {\n    const iterator = iterable[Symbol.iterator]()\n    let i = 0\n\n    const next = total => {\n      const el = iterator.next()\n\n      if (el.done) {\n        resolve(total)\n        return\n      }\n\n      Promise.all([total, el.value])\n        .then(value => {\n          // eslint-disable-next-line no-plusplus\n          next(reducer(value[0], value[1], i++))\n        })\n        .catch(reject)\n    }\n\n    next(initVal)\n  })\n\n// Lifted from https://github.com/sindresorhus/p-map-series\n// Thanks @sindresorhus! 🙏\nconst pMapSeries = (iterable, iterator) => {\n  const ret = []\n\n  return pReduce(iterable, (a, b, i) =>\n    Promise.resolve(iterator(b, i)).then(val => {\n      ret.push(val)\n    }),\n  ).then(() => ret)\n}\n\nconst ensureChild = child =>\n  child && typeof child.render === 'function'\n    ? ensureChild(child.render())\n    : child\n\n// Preact puts children directly on element, and React via props\nconst getChildren = element =>\n  element.props && element.props.children\n    ? element.props.children\n    : element.children\n      ? element.children\n      : undefined\n\n// Preact uses \"nodeName\", React uses \"type\"\nconst getType = element => element.type || element.nodeName\n\n// Preact uses \"attributes\", React uses \"props\"\nconst getProps = element => element.props || element.attributes\n\nconst isReactElement = element => !!getType(element)\n\nconst isClassComponent = Comp =>\n  Comp.prototype &&\n  (Comp.prototype.render ||\n    Comp.prototype.isReactComponent ||\n    Comp.prototype.isPureReactComponent)\n\nconst isForwardRef = Comp =>\n  Comp.type && Comp.type.$$typeof === forwardRefSymbol\n\nconst providesChildContext = instance => !!instance.getChildContext\n\n// Recurse a React Element tree, running the provided visitor against each element.\n// If a visitor call returns `false` then we will not recurse into the respective\n// elements children.\nexport default function reactTreeWalker(\n  tree,\n  visitor,\n  context,\n  options = defaultOptions,\n) {\n  return new Promise((resolve, reject) => {\n    const safeVisitor = (...args) => {\n      try {\n        return visitor(...args)\n      } catch (err) {\n        reject(err)\n      }\n      return undefined\n    }\n\n    const recursive = (currentElement, currentContext) => {\n      if (Array.isArray(currentElement)) {\n        return Promise.all(\n          currentElement.map(item => recursive(item, currentContext)),\n        )\n      }\n\n      if (!currentElement) {\n        return Promise.resolve()\n      }\n\n      if (\n        typeof currentElement === 'string' ||\n        typeof currentElement === 'number'\n      ) {\n        // Just visit these, they are leaves so we don't keep traversing.\n        safeVisitor(currentElement, null, currentContext)\n        return Promise.resolve()\n      }\n\n      if (currentElement.type) {\n        const _context =\n          currentElement.type._context ||\n          (currentElement.type.Provider &&\n            currentElement.type.Provider._context)\n\n        if (_context) {\n          if ('value' in currentElement.props) {\n            // <Provider>\n            // eslint-disable-next-line no-param-reassign\n            currentElement.type._context._currentValue =\n              currentElement.props.value\n          }\n\n          if (typeof currentElement.props.children === 'function') {\n            // <Consumer>\n            const el = currentElement.props.children(_context._currentValue)\n            return recursive(el, currentContext)\n          }\n        }\n      }\n\n      if (isReactElement(currentElement)) {\n        return new Promise(innerResolve => {\n          const visitCurrentElement = (\n            render,\n            compInstance,\n            elContext,\n            childContext,\n          ) =>\n            Promise.resolve(\n              safeVisitor(\n                currentElement,\n                compInstance,\n                elContext,\n                childContext,\n              ),\n            )\n              .then(result => {\n                if (result !== false) {\n                  // A false wasn't returned so we will attempt to visit the children\n                  // for the current element.\n                  const tempChildren = render()\n                  const children = ensureChild(tempChildren)\n                  if (children) {\n                    if (Array.isArray(children)) {\n                      // If its a react Children collection we need to breadth-first\n                      // traverse each of them, and pMapSeries allows us to do a\n                      // depth-first traversal that respects Promises. Thanks @sindresorhus!\n                      return pMapSeries(\n                        children,\n                        child =>\n                          child\n                            ? recursive(child, childContext)\n                            : Promise.resolve(),\n                      )\n                        .then(innerResolve, reject)\n                        .catch(reject)\n                    }\n                    // Otherwise we pass the individual child to the next recursion.\n                    return recursive(children, childContext)\n                      .then(innerResolve, reject)\n                      .catch(reject)\n                  }\n                }\n                return undefined\n              })\n              .catch(reject)\n\n          if (\n            typeof getType(currentElement) === 'function' ||\n            isForwardRef(currentElement)\n          ) {\n            const Component = getType(currentElement)\n            const props = Object.assign(\n              {},\n              Component.defaultProps,\n              getProps(currentElement),\n              // For Preact support so that the props get passed into render\n              // function.\n              {\n                children: getChildren(currentElement),\n              },\n            )\n            if (isForwardRef(currentElement)) {\n              visitCurrentElement(\n                () => currentElement.type.render(props),\n                null,\n                currentContext,\n                currentContext,\n              ).then(innerResolve)\n            } else if (isClassComponent(Component)) {\n              // Class component\n              const instance = new Component(props, currentContext)\n\n              // In case the user doesn't pass these to super in the constructor\n              Object.defineProperty(instance, 'props', {\n                value: instance.props || props,\n              })\n              instance.context = instance.context || currentContext\n              // set the instance state to null (not undefined) if not set, to match React behaviour\n              instance.state = instance.state || null\n\n              // Make the setState synchronous.\n              instance.setState = newState => {\n                if (typeof newState === 'function') {\n                  // eslint-disable-next-line no-param-reassign\n                  newState = newState(\n                    instance.state,\n                    instance.props,\n                    instance.context,\n                  )\n                }\n                instance.state = Object.assign({}, instance.state, newState)\n              }\n\n              if (Component.getDerivedStateFromProps) {\n                const result = Component.getDerivedStateFromProps(\n                  instance.props,\n                  instance.state,\n                )\n                if (result !== null) {\n                  instance.state = Object.assign({}, instance.state, result)\n                }\n              } else if (instance.UNSAFE_componentWillMount) {\n                instance.UNSAFE_componentWillMount()\n              } else if (instance.componentWillMount) {\n                instance.componentWillMount()\n              }\n\n              const childContext = providesChildContext(instance)\n                ? Object.assign({}, currentContext, instance.getChildContext())\n                : currentContext\n\n              visitCurrentElement(\n                // Note: preact API also allows props and state to be referenced\n                // as arguments to the render func, so we pass them through\n                // here\n                () => instance.render(instance.props, instance.state),\n                instance,\n                currentContext,\n                childContext,\n              )\n                .then(() => {\n                  if (\n                    options.componentWillUnmount &&\n                    instance.componentWillUnmount\n                  ) {\n                    instance.componentWillUnmount()\n                  }\n                })\n                .then(innerResolve)\n            } else {\n              // Stateless Functional Component\n              visitCurrentElement(\n                () => Component(props, currentContext),\n                null,\n                currentContext,\n                currentContext,\n              ).then(innerResolve)\n            }\n          } else {\n            // A basic element, such as a dom node, string, number etc.\n            visitCurrentElement(\n              () => getChildren(currentElement),\n              null,\n              currentContext,\n              currentContext,\n            ).then(innerResolve)\n          }\n        })\n      }\n\n      // Portals\n      if (\n        currentElement.containerInfo &&\n        currentElement.children &&\n        currentElement.children.props &&\n        Array.isArray(currentElement.children.props.children)\n      ) {\n        return Promise.all(\n          currentElement.children.props.children.map(child =>\n            recursive(child, currentContext),\n          ),\n        )\n      }\n\n      return Promise.resolve()\n    }\n\n    recursive(tree, context).then(resolve, reject)\n  })\n}\n"
  },
  {
    "path": "todo.tasks",
    "content": "☐ support array types\n  if (Array.isArray(element)) {\n    element.forEach(item => walkTree(item, context, visitor));\n    return;\n  }"
  },
  {
    "path": "tools/.eslintrc",
    "content": "{\n  \"rules\": {\n    \"no-console\": 0,\n    \"import/no-extraneous-dependencies\": 0\n  }\n}\n"
  },
  {
    "path": "tools/scripts/build.js",
    "content": "const { readFileSync } = require('fs')\nconst { inInstall } = require('in-publish')\nconst prettyBytes = require('pretty-bytes')\nconst gzipSize = require('gzip-size')\nconst { pipe } = require('ramda')\nconst { exec } = require('../utils')\nconst packageJson = require('../../package.json')\n\nif (inInstall()) {\n  process.exit(0)\n}\n\nconst nodeEnv = Object.assign({}, process.env, {\n  NODE_ENV: 'production',\n})\n\nexec('npx rollup -c rollup-min.config.js', nodeEnv)\nexec('npx rollup -c rollup.config.js', nodeEnv)\n\nfunction fileGZipSize(path) {\n  return pipe(readFileSync, gzipSize.sync, prettyBytes)(path)\n}\n\nconsole.log(\n  `\\ngzipped, the build is ${fileGZipSize(`dist/${packageJson.name}.min.js`)}`,\n)\n"
  },
  {
    "path": "tools/utils.js",
    "content": "const { execSync } = require('child_process')\nconst appRootDir = require('app-root-dir')\n\nfunction exec(command) {\n  execSync(command, { stdio: 'inherit', cwd: appRootDir.get() })\n}\n\nmodule.exports = {\n  exec,\n}\n"
  },
  {
    "path": "wallaby.js",
    "content": "const fs = require('fs')\nconst path = require('path')\n\nprocess.env.NODE_ENV = 'test'\n\nconst babelConfigContents = fs.readFileSync(path.join(__dirname, '.babelrc'))\nconst babelConfig = JSON.parse(babelConfigContents)\n\nmodule.exports = wallaby => ({\n  files: ['src/**/*.js', { pattern: 'src/**/*.test.js', ignore: true }],\n  tests: ['src/**/*.test.js'],\n  testFramework: 'jest',\n  env: {\n    type: 'node',\n    runner: 'node',\n  },\n  compilers: {\n    'src/**/*.js': wallaby.compilers.babel(babelConfig),\n  },\n})\n"
  }
]