[
  {
    "path": ".babelrc",
    "content": "{\n  \"presets\": [\"react\", \"es2015\", \"stage-1\"],\n  \"env\": {\n    \"development\": {\n      \"presets\": [\"react-hmre\"]\n    },\n    \"lib\": {\n      \"plugins\": [\n        [\n          \"babel-plugin-webpack-loaders\",\n          {\n            \"config\": \"./webpack.config.lib.js\",\n            \"verbose\": false,\n          }\n        ]\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": ".builderrc",
    "content": "---\narchetypes:\n  - component-archetype"
  },
  {
    "path": ".editorconfig",
    "content": "# EditorConfig helps developers define and maintain consistent\n# coding styles between different editors and IDEs\n# editorconfig.org\n\nroot = true\n\n\n[*]\n\n# Change these settings to your own preference\nindent_style = space\nindent_size = 2\n\n# We recommend you to keep these unchanged\nend_of_line = lf\ncharset = utf-8\ntrim_trailing_whitespace = true\ninsert_final_newline = true\n\n[*.md]\ntrim_trailing_whitespace = false"
  },
  {
    "path": ".eslintrc",
    "content": "{\n  \"extends\": \"rackt\",\n  \"ecmaFeatures\": {\n    \"jsx\": true,\n    \"modules\": true\n  },\n  \"env\": {\n    \"browser\": true,\n    \"node\": true,\n    \"mocha\": true\n  },\n  \"parser\": \"babel-eslint\",\n  \"rules\": {\n    \"quotes\": [2, \"single\"],\n    \"strict\": [2, \"never\"],\n    \"babel/generator-star-spacing\": 1,\n    \"babel/object-shorthand\": 1,\n    \"babel/no-await-in-loop\": 1,\n    \"react/jsx-uses-react\": 2,\n    \"react/jsx-uses-vars\": 2,\n    \"react/react-in-jsx-scope\": 2\n  },\n  \"plugins\": [\n    \"babel\",\n    \"react\"\n  ]\n}\n"
  },
  {
    "path": ".gitignore",
    "content": ".DS_Store\nnode_modules\nnpm-debug.log\ndist\n.nyc_output\ncoverage\nlib"
  },
  {
    "path": ".npmignore",
    "content": ".DS_Store\n*.log\nsrc\ntest\nexamples\ndocs\ndemo\ncoverage\n*.sublime-project\n*.sublime-workspace\n"
  },
  {
    "path": ".travis.yml",
    "content": "sudo: false\nlanguage: node_js\ncache:\n  directories:\n    - node_modules\nbranches:\n  only:\n    - master\nnotifications:\n  email: false\nnode_js:\n  - \"5.1.0\"\nbefore_install:\n  - npm i -g npm@^3.0.0\nbefore_script:\n  - npm prune\nscript:\n  - npm run test:cover\n  - npm run check-coverage\n  - npm run build\nafter_success:\n  - npm run report-coverage\n  - npm run semantic-release\nbranches:\n  except:\n    - \"/^v\\\\d+\\\\.\\\\d+\\\\.\\\\d+$/\"\n"
  },
  {
    "path": ".travis.yml-old",
    "content": "sudo: false\nlanguage: node_js\ncache:\n  directories:\n    - node_modules\nbranches:\n  only:\n    - master\nnotifications:\n  email: false\nnode_js:\n  - \"5.1.0\"\nbefore_install:\n  - npm i -g npm@^3.0.0\nbefore_script:\n  - npm prune\nscript:\n  - npm run test:cover\n  - npm run check-coverage\n  - npm run build\nafter_success:\n  - npm run report-coverage\n  - npm run semantic-release\nbranches:\n  except:\n    - \"/^v\\\\d+\\\\.\\\\d+\\\\.\\\\d+$/\"\n"
  },
  {
    "path": "LICENSE",
    "content": "Creative Commons Legal Code\n\nCC0 1.0 Universal\n\n    CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE\n    LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN\n    ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS\n    INFORMATION ON AN \"AS-IS\" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES\n    REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS\n    PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM\n    THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED\n    HEREUNDER.\n\nStatement of Purpose\n\nThe laws of most jurisdictions throughout the world automatically confer\nexclusive Copyright and Related Rights (defined below) upon the creator\nand subsequent owner(s) (each and all, an \"owner\") of an original work of\nauthorship and/or a database (each, a \"Work\").\n\nCertain owners wish to permanently relinquish those rights to a Work for\nthe purpose of contributing to a commons of creative, cultural and\nscientific works (\"Commons\") that the public can reliably and without fear\nof later claims of infringement build upon, modify, incorporate in other\nworks, reuse and redistribute as freely as possible in any form whatsoever\nand for any purposes, including without limitation commercial purposes.\nThese owners may contribute to the Commons to promote the ideal of a free\nculture and the further production of creative, cultural and scientific\nworks, or to gain reputation or greater distribution for their Work in\npart through the use and efforts of others.\n\nFor these and/or other purposes and motivations, and without any\nexpectation of additional consideration or compensation, the person\nassociating CC0 with a Work (the \"Affirmer\"), to the extent that he or she\nis an owner of Copyright and Related Rights in the Work, voluntarily\nelects to apply CC0 to the Work and publicly distribute the Work under its\nterms, with knowledge of his or her Copyright and Related Rights in the\nWork and the meaning and intended legal effect of CC0 on those rights.\n\n1. Copyright and Related Rights. A Work made available under CC0 may be\nprotected by copyright and related or neighboring rights (\"Copyright and\nRelated Rights\"). Copyright and Related Rights include, but are not\nlimited to, the following:\n\n  i. the right to reproduce, adapt, distribute, perform, display,\n     communicate, and translate a Work;\n ii. moral rights retained by the original author(s) and/or performer(s);\niii. publicity and privacy rights pertaining to a person's image or\n     likeness depicted in a Work;\n iv. rights protecting against unfair competition in regards to a Work,\n     subject to the limitations in paragraph 4(a), below;\n  v. rights protecting the extraction, dissemination, use and reuse of data\n     in a Work;\n vi. database rights (such as those arising under Directive 96/9/EC of the\n     European Parliament and of the Council of 11 March 1996 on the legal\n     protection of databases, and under any national implementation\n     thereof, including any amended or successor version of such\n     directive); and\nvii. other similar, equivalent or corresponding rights throughout the\n     world based on applicable law or treaty, and any national\n     implementations thereof.\n\n2. Waiver. To the greatest extent permitted by, but not in contravention\nof, applicable law, Affirmer hereby overtly, fully, permanently,\nirrevocably and unconditionally waives, abandons, and surrenders all of\nAffirmer's Copyright and Related Rights and associated claims and causes\nof action, whether now known or unknown (including existing as well as\nfuture claims and causes of action), in the Work (i) in all territories\nworldwide, (ii) for the maximum duration provided by applicable law or\ntreaty (including future time extensions), (iii) in any current or future\nmedium and for any number of copies, and (iv) for any purpose whatsoever,\nincluding without limitation commercial, advertising or promotional\npurposes (the \"Waiver\"). Affirmer makes the Waiver for the benefit of each\nmember of the public at large and to the detriment of Affirmer's heirs and\nsuccessors, fully intending that such Waiver shall not be subject to\nrevocation, rescission, cancellation, termination, or any other legal or\nequitable action to disrupt the quiet enjoyment of the Work by the public\nas contemplated by Affirmer's express Statement of Purpose.\n\n3. Public License Fallback. Should any part of the Waiver for any reason\nbe judged legally invalid or ineffective under applicable law, then the\nWaiver shall be preserved to the maximum extent permitted taking into\naccount Affirmer's express Statement of Purpose. In addition, to the\nextent the Waiver is so judged Affirmer hereby grants to each affected\nperson a royalty-free, non transferable, non sublicensable, non exclusive,\nirrevocable and unconditional license to exercise Affirmer's Copyright and\nRelated Rights in the Work (i) in all territories worldwide, (ii) for the\nmaximum duration provided by applicable law or treaty (including future\ntime extensions), (iii) in any current or future medium and for any number\nof copies, and (iv) for any purpose whatsoever, including without\nlimitation commercial, advertising or promotional purposes (the\n\"License\"). The License shall be deemed effective as of the date CC0 was\napplied by Affirmer to the Work. Should any part of the License for any\nreason be judged legally invalid or ineffective under applicable law, such\npartial invalidity or ineffectiveness shall not invalidate the remainder\nof the License, and in such case Affirmer hereby affirms that he or she\nwill not (i) exercise any of his or her remaining Copyright and Related\nRights in the Work or (ii) assert any associated claims and causes of\naction with respect to the Work, in either case contrary to Affirmer's\nexpress Statement of Purpose.\n\n4. Limitations and Disclaimers.\n\n a. No trademark or patent rights held by Affirmer are waived, abandoned,\n    surrendered, licensed or otherwise affected by this document.\n b. Affirmer offers the Work as-is and makes no representations or\n    warranties of any kind concerning the Work, express, implied,\n    statutory or otherwise, including without limitation warranties of\n    title, merchantability, fitness for a particular purpose, non\n    infringement, or the absence of latent or other defects, accuracy, or\n    the present or absence of errors, whether or not discoverable, all to\n    the greatest extent permissible under applicable law.\n c. Affirmer disclaims responsibility for clearing rights of other persons\n    that may apply to the Work or any use thereof, including without\n    limitation any person's Copyright and Related Rights in the Work.\n    Further, Affirmer disclaims responsibility for obtaining any necessary\n    consents, permissions or other rights required for any use of the\n    Work.\n d. Affirmer understands and acknowledges that Creative Commons is not a\n    party to this document and has no duty or obligation with respect to\n    this CC0 or use of the Work.\n"
  },
  {
    "path": "README.md",
    "content": "# Redux Swarmlog\n\n[![travis build](https://img.shields.io/travis/philholden/redux-swarmlog.svg?style=flat-square)](https://travis-ci.org/philholden/redux-swarmlog) [![version](https://img.shields.io/npm/v/@philholden/redux-swarmlog.svg?style=flat-square)](http://npm.im/@philholden/redux-swarmlog)\n\n[![Video](http://img.youtube.com/vi/M99djS07Ph8/0.jpg)](http://www.youtube.com/watch?v=M99djS07Ph8)\n\n_(Click image to watch React Europe lightning video)_\n\n<a href=\"https://egghead.io/lessons/react-redux-peer-to-peer-todomvc-over-webrtc-using-swarmlog\" target=\"_blank\">![ScreenShot](https://raw.github.com/philholden/todomvc-redux-swarmlog/master/redux-swarmlog-egghead.png)</a>\n\n_(Click image to watch Egghead.io intro video)_\n\nA super simple way of writing distributed Redux applications. The [Redux](https://github.com/reactjs/redux) action log is persisted in an IndexDB and synced with other peers via a [WebRTC Swarm](https://github.com/mafintosh/webrtc-swarm) using [Swarmlog](https://github.com/substack/swarmlog).\n\nWhen an application reloads the Redux store is initialsed by reducing all the persisted actions in the IndexDB and syncing any new actions from remote peers. Watch the Egghead video above to find out more.\n\n## Pros\n\n* offline data by default\n* super simple mental model for writing distributed apps\n* UIs update automatically as remote actions come in \n* works offline by default\n* scales globally for free with no bandwidth or storage costs for the developer\n* the developer is not responsible for client data\n* friends not cooperations hold user data \n* public / private key authentication is lighter weight than user accounts\n* time travel \n\n## Cons\n\n  * Action logs use more bandwidth than raw data so initial sync could be slow for a very long log.\n  \n  __workaround:__ Break down long logs into lots of smaller logs e.g. log per month, week or day. Only fetch the most recent log if its all thats needed\n  \n  * Extra storage space needed on client\n  \n  __workaround:__ The price of SSDs is falling very rapidly. Stop thinking about cloud and thin client, but cache encrypted data where it is needed. This gives privacy, enables working offline, provides backups and can act as a CDN. Once you start using a distributed system like Git you soon stop thinking about the extra space it requires. \n\n  * Permanence: even if an action deletes an item it can still be retrieved from the log.\n  \n __workaround:__ Use a log for versioning other logs. Every so often the main log is reduced and a single action is written to a new log which creates the store in the current state. The old log is marked as stale in the version log and its database is deleted (purging old actions).\n \n  * Can't get most up to date data if the peer holding it is offline\n\n  __workaround:__ A small device like a Raspberry PI kept online should be all that is needed to make sure there is always at least one up to date source of truth. With 5G and IoT we are heading towards an era of always online small connected devices. Let's start thinking that way now.\n\n## Play to Strengths\n\nRedux Swarmlog works well for apps that support some kind of physical live event. Because you know the action log will be short and the users will be online at the same time. Examples might be providing subtitles via mobile phone for a theatre show or letting a teacher see in realtime how each individuals in a class is answering a question. \n"
  },
  {
    "path": "consume.html",
    "content": "<!doctype html>\n<html>\n  <head>\n    <title>React Transform Boilerplate</title>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    <script src=\"/static/consume.js\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "devServer.js",
    "content": "var path = require('path')  // eslint-disable-line no-var\nvar express = require('express')  // eslint-disable-line no-var\nvar webpack = require('webpack')  // eslint-disable-line no-var\nvar config = require('./webpack.config.dev') // eslint-disable-line no-var\nvar compression = require('compression') // eslint-disable-line no-var\nvar ssbKeys = require('ssb-keys')\n\n// var requestProxy = require('express-request-proxy')\n// var objectAssign = require('object-assign')\n\nvar app = express() // eslint-disable-line no-var\nvar server = require('http').createServer(app) // eslint-disable-line no-var\nvar io = require('socket.io')(server) // eslint-disable-line no-var\n\nvar compiler = webpack(config) // eslint-disable-line no-var\nvar port = 3000 // eslint-disable-line no-var\n\napp.use(require('webpack-dev-middleware')(compiler, {\n  noInfo: true,\n  publicPath: config.output.publicPath\n}))\n\napp.use(require('webpack-hot-middleware')(compiler))\n\napp.use(compression({\n  threshold: 512\n}))\n\napp.use('/', express.static('.'))\napp.get('/keys/', (req, res) => {\n  res.setHeader('Content-Type', 'application/json')\n  res.send(JSON.stringify(require('ssb-keys').generate()))\n})\n\n// app.all('*', function(req, res, next) {\n//   var url = require('url').parse(req.url)\n//   var conf = objectAssign({}, req, {\n//     url: 'http://127.0.0.1:8888' + url.pathname,\n//     timeout: 120000\n//   })\n//   requestProxy(conf)(req, res, next)\n// })\n\n// app.get('*', function (req, res) {\n//   res.sendFile(path.join(__dirname, 'index.html'))\n// })\n\nserver.listen(port, '0.0.0.0', function (err) {\n  if (err) {\n    console.log(err) // eslint-disable-line no-console\n    return\n  }\n  console.log('Listening at http://localhost:' + port) // eslint-disable-line no-console\n})\n\nio.on('connection', function (socket) {\n  io.set('origins', '*:*')\n  console.log('connected') // eslint-disable-line no-console\n  socket.emit('update', 'connected')\n  socket.on('single', function () {\n    socket.emit('update', 'single')\n  })\n  socket.on('publish', function (data) {\n    io.sockets.emit('update', data)\n  })\n})\n"
  },
  {
    "path": "examples/consume.html",
    "content": "<!doctype html>\n<html>\n  <head>\n    <title>React Transform Boilerplate</title>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    <script src=\"/static/consume.js\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "examples/index.html",
    "content": "<!doctype html>\n<html>\n  <head>\n    <title>React Transform Boilerplate</title>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    <script src=\"/static/bundle.js\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "examples/keys.json",
    "content": "{\n  \"curve\": \"ed25519\",\n  \"public\": \"q8oQyaB0t9k8bAog6om+q86FRbBoYUklC0eQToR+nw8=.ed25519\",\n  \"private\": \"PmS89eOtLC35JJlcRMquh6qS8oHG4uZpQQcpw3aRHHWryhDJoHS32TxsCiDqib6rzoVFsGhhSSULR5BOhH6fDw==.ed25519\",\n  \"id\": \"@q8oQyaB0t9k8bAog6om+q86FRbBoYUklC0eQToR+nw8=.ed25519\"\n}\n"
  },
  {
    "path": "examples/publish.html",
    "content": "<!doctype html>\n<html>\n  <head>\n    <title>React Transform Boilerplate</title>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    <script src=\"/static/publish.js\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "examples/src/__tests__/index.test.js",
    "content": "import test from 'ava'\nimport is from 'is_js'\nimport React from 'react'\nimport { createRenderer } from 'react-addons-test-utils'\nimport expect from 'expect'\nimport expectJSX from 'expect-jsx'\nimport { HelloWorld } from '../App'\n\nexpect.extend(expectJSX)\n\ntest('is an array of numbers', t => {\n  t.true(\n    [ 1, 2, 3 ].every(item => typeof item === 'number')\n  )\n})\n\ntest('1 is in array', t => {\n  t.true(\n    is.inArray(1, [ 1, 2, 3 ])\n  )\n})\n\ntest('MyComponent default render', () => {\n  const renderer = createRenderer()\n\n  renderer.render(\n    <HelloWorld />\n  )\n  expect(\n    renderer.getRenderOutput()\n  )\n  .toEqualJSX(\n    <div>Hello World.</div>\n  )\n})\n"
  },
  {
    "path": "examples/src/__tests__/null-compiler.js",
    "content": "// Prevent Mocha from compiling class\nfunction noop() {\n  return null\n}\n\nrequire.extensions['.css'] = noop\nrequire.extensions['.png'] = noop\n"
  },
  {
    "path": "examples/src/actions/index.js",
    "content": "export const ADD_SONG_STORE = 'ADD_SONG_STORE'\nexport const REMOVE_SONG_STORE = 'REMOVE_SONG_STORE'\nexport const PUT_SONG_IN_SONG_STORE = 'PUT_SONG_IN_SONG_STORE'\nexport const REMOVE_SONG_FROM_SONG_STORE = 'REMOVE_SONG_FROM_SONG_STORE'\nexport const ADD_SONG_STORE_SUCCEEDED = 'ADD_SONG_STORE_SUCCEEDED'\nexport const REMOVE_SONG_STORE_SUCCEEDED = 'REMOVE_SONG_STORE_SUCCEEDED'\n\nexport const songStoreActions = [\n  ADD_SONG_STORE,\n  REMOVE_SONG_STORE,\n  PUT_SONG_IN_SONG_STORE,\n  REMOVE_SONG_FROM_SONG_STORE,\n  ADD_SONG_STORE_SUCCEEDED\n]\n\nexport function addSongStore(swarmLogMeta) {\n  return {\n    type: ADD_SONG_STORE,\n    swarmLogMeta\n  }\n}\n\nexport function addSongStoreSucceeded(swarmLogMeta) {\n  return {\n    type: ADD_SONG_STORE_SUCCEEDED,\n    swarmLogMeta\n  }\n}\n\nexport function removeSongStore(songStoreId) {\n  return {\n    type: REMOVE_SONG_STORE,\n    songStoreId\n  }\n}\n\nexport function removeSongStoreSucceeded(songStoreId) {\n  return {\n    type: REMOVE_SONG_STORE_SUCCEEDED,\n    songStoreId\n  }\n}\n\nexport function putSongInSongStore(songStoreId, song) {\n  return {\n    type: PUT_SONG_IN_SONG_STORE,\n    songStoreId,\n    song,\n    reduxSwarmLogId: songStoreId\n  }\n}\n\nexport function removeSongFromSongStore(songStoreId, songId) {\n  return {\n    type: REMOVE_SONG_FROM_SONG_STORE,\n    songStoreId,\n    songId,\n    reduxSwarmLogId: songStoreId\n  }\n}\n"
  },
  {
    "path": "examples/src/api.js",
    "content": "\nexport function generateKeys() {\n  return fetch(`/keys`, {\n    method: 'get',\n    headers: {\n      'Accept': 'application/json',\n      'Content-Type': 'text/plain'\n    }\n  })\n  .then((res) => {\n    if (res.status >= 400) {\n      throw new Error('Bad response from server')\n    }\n    return res.json()\n  })\n  .catch(function (err) {\n    throw new Error('Bad response from server: ', err.message)\n  })\n}\n"
  },
  {
    "path": "examples/src/components/app.js",
    "content": "import React, { Component } from 'react'\nimport { connect } from 'react-redux'\nimport SongStoreListContainer from './song-store-list-container'\n\n\nclass App extends Component {\n  render() {\n    return (\n      <div>\n      <SongStoreListContainer />\n      <pre>\n        {\n        //  JSON.stringify(this.props.state, null, 2)\n        }\n      </pre>\n      </div>\n\n    )\n  }\n}\n\nexport default connect(state => ({ state }))(App)\n"
  },
  {
    "path": "examples/src/components/song-item-container.js",
    "content": "import React from 'react'\nimport { connect } from 'react-redux'\n\nimport {\n  removeSongFromSongStore\n} from '../actions/index'\n\nconst SongItem = ({ song, onRemove }) => {\n  return (\n    <div>\n      <span style={styles.songStoreTitle}>{ song.id }</span>\n      {' '}\n      <button onClick={onRemove}>Remove</button>\n    </div>\n  )\n}\n\nconst mapStateToProps = (\n  { songStores },\n  { songStoreId, songId }\n) => {\n  return {\n    songStoreId,\n    song: songStores[songStoreId].songs[songId]\n  }\n}\n\nconst mapDispatchToProps = (dispatch, { songStoreId, songId }) => ({\n  onRemove: () => dispatch(removeSongFromSongStore(\n    songStoreId,\n    songId\n  ))\n})\n\nconst SongItemContainer = connect(\n  mapStateToProps,\n  mapDispatchToProps\n) (SongItem)\n\nexport default SongItemContainer\n\nconst styles = {\n  songStoreTitle: {\n    fontSize: 16,\n    fontFamily: 'sans-serif'\n  }\n}\n"
  },
  {
    "path": "examples/src/components/song-list-container.js",
    "content": "import React from 'react'\nimport { connect } from 'react-redux'\nimport { bindActionCreators } from 'redux'\nimport SongItemContainer from './song-item-container'\nimport {\n  putSongInSongStore\n} from '../actions/index'\n\n\nconst AddSongForm = ({\n  songStoreId,\n  putSongInSongStore\n}) => {\n  let input\n\n  const onAddSong = e => {\n    e.preventDefault()\n    putSongInSongStore(\n      songStoreId,\n      {\n        id: input.value,\n        name: input.value\n      }\n    )\n  }\n\n  return (\n    <div>\n      <form onSubmit={onAddSong}>\n        <input type=\"text\" ref={el => input = el} />\n        {' '}\n        <button onClick={onAddSong}>Add Song</button>\n      </form>\n    </div>\n  )\n}\n\nconst SongList = ({\n  songIds,\n  songStoreId,\n  putSongInSongStore\n}) => {\n\n  return (\n    <div>\n      {\n        songIds.map(songId => (\n          <SongItemContainer\n            songId={songId}\n            songStoreId={songStoreId}\n            key={songId}\n          />\n        ))\n      }\n\n      <AddSongForm { ...{\n        songStoreId,\n        putSongInSongStore\n      } } />\n    </div>\n  )\n}\n\nconst mapStateToProps = (\n  { songStores },\n  { songStoreId }\n) => {\n  const songs = songStores[songStoreId].songs\n  return {\n    songStoreId,\n    songIds: Object.keys(songs)\n  }\n}\n\nconst mapDispatchToProps = dispatch => bindActionCreators({\n  putSongInSongStore\n}, dispatch)\n\nconst SongListContainer = connect(\n  mapStateToProps,\n  mapDispatchToProps\n) (SongList)\n\nexport default SongListContainer\n\nconst styles = {\n  songStoreTitle: {\n    fontSize: 20,\n    fontWeight: 'bold',\n    fontFamily: 'sans-serif'\n  }\n}\n"
  },
  {
    "path": "examples/src/components/song-store-item-container.js",
    "content": "import React from 'react'\nimport { connect } from 'react-redux'\nimport SongListContainer from './song-list-container'\n\nimport {\n  removeSongStore\n} from '../actions/index'\n\nconst SongStoreItem = ({ name, keys, id, onRemove }) => {\n  return (\n    <div style={styles.outer}>\n      <div style={styles.hr}>\n        <span style={styles.songStoreTitle}>{ name }</span>\n        {' '}\n        <button onClick={onRemove}>Remove</button>\n      </div>\n      <SongListContainer songStoreId={id} />\n      <div style={styles.keys}>\n        <b>public key:</b> <input value={keys.public} readOnly={true}/><br />\n        <b>private key:</b> <input value={keys.private} readOnly={true}/><br />\n      </div>\n    </div>\n  )\n}\n\nconst mapStateToProps = ({ songStores }, { id }) => {\n  const { swarmLogMeta } = songStores[id]\n  return {\n    ...swarmLogMeta\n  }\n}\n\nconst mapDispatchToProps = (dispatch, { id }) => ({\n  onRemove: () => dispatch(removeSongStore(id))\n})\n\nconst SongStoreItemContainer = connect(\n  mapStateToProps,\n  mapDispatchToProps\n) (SongStoreItem)\n\nexport default SongStoreItemContainer\n\nconst styles = {\n  songStoreTitle: {\n    fontSize: 20,\n    fontWeight: 'bold',\n  },\n  outer: {\n    border: '1px solid #ccc',\n    borderRadius: 3,\n    padding: 20,\n    fontFamily: 'sans-serif',\n    lineHeight: 1.8,\n    marginBottom: '1em'\n  },\n  hr: {\n    borderBottom: '2px solid #eee',\n    margin: '0 0 7px'\n  },\n  keys: {\n    fontSize: 11,\n  }\n}\n"
  },
  {
    "path": "examples/src/components/song-store-list-container.js",
    "content": "import React from 'react'\nimport { connect } from 'react-redux'\nimport { bindActionCreators } from 'redux'\nimport SongStoreSyncContainer from './song-store-sync-container'\nimport SongStoreItemContainer from './song-store-item-container'\nimport {\n  addSongStore\n} from '../actions/index'\n\nconst SongStoreList = ({\n  songStores\n}) => {\n  let input\n  return (\n    <div>\n      { songStores.map(({ id }) => (\n          <SongStoreItemContainer id={id} key={id} />\n        ))\n      }\n      <SongStoreSyncContainer />\n    </div>\n  )\n}\n\nconst mapStateToProps = ({ songStores }) => ({\n  songStores: Object.keys(songStores)\n    .map(key => ({\n      ...songStores[key].swarmLogMeta\n    }))\n})\n\n// const mapDispatchToProps = dispatch => bindActionCreators({\n//   addSongStore\n// }, dispatch)\n\nconst SongStoreListContainer = connect(\n  mapStateToProps,\n  null\n) (SongStoreList)\n\nexport default SongStoreListContainer\n\nconst styles = {\n  songStoreTitle: {\n    fontSize: 20,\n    fontWeight: 'bold',\n    fontFamily: 'sans-serif'\n  },\n  inputWrapper: {\n    margin: '6px 0'\n  }\n}\n"
  },
  {
    "path": "examples/src/components/song-store-sync-container.js",
    "content": "import React from 'react'\nimport { connect } from 'react-redux'\nimport { bindActionCreators } from 'redux'\nimport {\n  addSongStore\n} from '../actions/index'\n\n\nconst SongStoreSync = ({\n  addSongStore\n}) => {\n  let publicKey, privateKey, name\n  const onSyncSongStore = e => {\n    e.preventDefault()\n    const pub = publicKey.value\n    const priv = privateKey.value\n\n    let swarmLogMeta = { name : name.value }\n    if (pub !== '' && pub) {\n      swarmLogMeta.keys = {\n        public: pub\n      }\n      if (priv !== '' && priv) {\n        swarmLogMeta.keys.private = priv\n      }\n    }\n    addSongStore(swarmLogMeta)\n  }\n  return (\n    <form onSubmit={onSyncSongStore} style={styles.outer}>\n      <div style={styles.hr}>\n        <span style={styles.songStoreTitle}>Add & Sync Stores</span>\n      </div>\n      <div style={styles.row}>\n        <div style={styles.inputs}>\n          <input key=\"1\" type=\"text\" ref={el => name = el}/> Name <br/>\n          <input key=\"2\" type=\"text\" ref={el => publicKey = el}/> Public <br/>\n          <input key=\"3\" type=\"text\" ref={el => privateKey = el}/> Private <br/>\n          <button>Add Store</button>\n        </div>\n        <ul style={styles.ul}>\n          <li>To add a new local store just fill in name</li>\n          <li>To sync a remote store add a name (can be anything) then add private and public keys to give read write access or just the public key for read only access</li>\n        </ul>\n      </div>\n    </form>\n  )\n}\n\n// const mapStateToProps = ({ songStores }) => ({\n//   songStores: Object.keys(songStores)\n//     .map(key => ({\n//       ...songStores[key].swarmLogMeta\n//     }))\n// })\n\nconst mapDispatchToProps = dispatch => bindActionCreators({\n  addSongStore\n}, dispatch)\n\nconst SongStoreSyncContainer = connect(\n  null,\n  mapDispatchToProps\n) (SongStoreSync)\n\nexport default SongStoreSyncContainer\n\nconst styles = {\n  songStoreTitle: {\n    fontSize: 20,\n    fontWeight: 'bold'\n  },\n  hr: {\n    borderBottom: '2px solid #eee',\n    margin: '0 0 7px'\n  },\n  outer: {\n    border: '1px solid #ccc',\n    borderRadius: 3,\n    padding: 20,\n    fontFamily: 'sans-serif',\n    lineHeight: 1.8,\n    marginBottom: '1em'\n  },\n  row: {\n    display: 'flex',\n    alignItems: 'center'\n  },\n  inputs: {\n    flexBasis: 260\n  },\n  ul: {\n    fontSize: 12,\n    marginTop: 0,\n    maxWidth: 300\n  }\n}\n"
  },
  {
    "path": "examples/src/consume.js",
    "content": "import swarmlog from 'swarmlog'\nimport memdb from 'memdb'\n\nconst log = swarmlog({\n  publicKey: require('../keys.json').public,\n  sodium: require('chloride/browser'),\n  db: memdb(),\n  valueEncoding: 'json',\n  hubs: [ 'https://signalhub.mafintosh.com' ]\n})\n\nlog.createReadStream({ live: true })\n  .on('data', function (data) {\n    //console.log('RECEIVED', data.key, data.value)\n    const logEl = document.createElement('div')\n    logEl.innerHTML = `<b>RECEIVED:</b> ${JSON.stringify(data.value)}`\n    document.body.insertBefore(logEl, document.body.firstChild)\n  })\n"
  },
  {
    "path": "examples/src/generate-keys.js",
    "content": "import supercop from '../supercop.js'\n\nimport crypto from 'crypto'\n\nexport default function generateKeys() {\n  return require('../keys-old.json')\n  const keys = supercop.createKeypair()\n  return {\n    curve: `ed25519`,\n    public: `${keys.pubKey.toString('base64')}.ed25519`,\n    private: `${keys.privKey.toString('base64')}.ed25519`,\n    id: `@${keys.pubKey.toString('base64')}.ed25519`,\n//    id: crypto.createHash('sha256').update(keys.pubKey).digest('base64')+'.sha256',\n    hashKey: crypto.createHash('sha256').update(keys.pubKey).digest('hex'),\n  }\n}\n"
  },
  {
    "path": "examples/src/index.js",
    "content": "import React from 'react'\nimport { render } from 'react-dom'\nimport { Provider } from 'react-redux'\nimport App from './components/App'\nimport rootReducer from './reducers/index'\nimport { generateKeys } from './api'\nimport * as _actions from './actions/index'\nimport { sagaMiddleware } from './sagas'\nimport { bindActionCreators } from 'redux'\n\nimport {\n  createStore,\n  applyMiddleware,\n  compose\n} from 'redux'\n\nimport phil from '../../lib/index'\n\nimport {\n  configureReduxSwarmLog,\n  reduxSwarmLogMiddleware,\n  getSwarmLogsFromDb\n}\n//from '../../src/redux-swarmlog'\nfrom '../../lib/index'\n\nconsole.log({\n  configureReduxSwarmLog,\n  reduxSwarmLogMiddleware,\n  getSwarmLogsFromDb\n},phil)\n\nconst store = createStore(\n  rootReducer,\n  compose(\n    applyMiddleware(\n      reduxSwarmLogMiddleware,\n      sagaMiddleware\n    ),\n    window.devToolsExtension ? window.devToolsExtension() : f => f\n  )\n)\n\nconst actions = bindActionCreators(_actions, store.dispatch)\n\nwindow.actions = actions\nwindow.dispatch = store.dispatch\n\nconfigureReduxSwarmLog({\n  reduxStore: store,\n  generateKeys,\n  logSampleActions,\n  logLevel: 1\n})\n\ngetSwarmLogsFromDb()\n  .then(reduxSwarmLogs => {\n    if (reduxSwarmLogs.length === 0) {\n      actions.addSongStore({ name: 'My Songs' })\n    } else {\n      reduxSwarmLogs.forEach(actions.addSongStore)\n    }\n  })\n\nrender(\n  <Provider store={store}>\n    <App />\n  </Provider>,\n  document.getElementById('root')\n)\n\nfunction logSampleActions({ id, keys, name }) {\n  console.log(\n`\n%cthe following actions can be dispatched from the console:\n\n%c// clone song store over rtc on remote machine or in incognito window\n%cactions.addSongStore({\n  name: '${name} Clone',\n  keys: {\n    public: '${keys.public}',\n    private: '${keys.private}'\n  }\n})\n\n%c// add song\n%cactions.putSongInSongStore('${id}', {id: 'hello', text: 'world'})\n\n%c// remove song\n%cactions.removeSongFromSongStore('${id}', 'hello')\n\n%c// add new local song store\n%cactions.addSongStore({ name: 'New Song Store' })\n\n%c// remove song store\n%cactions.removeSongStore('${id}')\n\n`,\n'font-weight: bold',\n'font-style: italic; color: #888',\n'color: #559',\n'font-style: italic; color: #888',\n'color: #559',\n'font-style: italic; color: #888',\n'color: #559',\n'font-style: italic; color: #888',\n'color: #559',\n'font-style: italic; color: #888',\n'color: #559'\n)\n}\n"
  },
  {
    "path": "examples/src/publish.js",
    "content": "import swarmlog from 'swarmlog'\nimport memdb from 'memdb'\nimport leveljs from 'level-js'\nimport levelup from 'levelup'\nimport sodium from 'chloride/browser'\n\n//window.Key = Key\n\nwindow.sodium = sodium\n\nwindow.db = memdb()\n//window.db = levelup('foo', { db: leveljs })\n//indexedDB.deleteDatabase('IDBWrapper-foo')\n\nconst log = swarmlog({\n  keys: require('../keys.json'),\n  sodium,\n  db: window.db,\n  valueEncoding: 'json',\n  hubs: [ 'https://signalhub.mafintosh.com' ]\n})\n\nlet times = 0\nsetInterval(function () {\n  const data = { message: 'HELLO!x' + times }\n  log.append(data)\n  times++\n  const logEl = document.createElement('div')\n  logEl.innerHTML = `<b>SENT:</b> ${JSON.stringify(data)}`\n  document.body.insertBefore(logEl, document.body.firstChild)\n}, 3000)\n\nlog.createReadStream({ live: true })\n  .on('data', function (data) {\n    const logEl = document.createElement('div')\n    logEl.innerHTML = `<b>RECEIVED:</b> ${JSON.stringify(data.value)}`\n    document.body.insertBefore(logEl, document.body.firstChild)\n  })\n"
  },
  {
    "path": "examples/src/reducers/index.js",
    "content": "import { combineReducers } from 'redux'\nimport songStores from './song-stores'\n\nexport default combineReducers({\n  songStores\n})\n"
  },
  {
    "path": "examples/src/reducers/song-stores.js",
    "content": "import {\n  ADD_SONG_STORE,\n  ADD_SONG_STORE_SUCCEEDED,\n  REMOVE_SONG_STORE_SUCCEEDED,\n  PUT_SONG_IN_SONG_STORE,\n  REMOVE_SONG_FROM_SONG_STORE\n} from '../actions/index'\n\nexport function root(state = {}, action) {\n  switch (action.type) {\n    case ADD_SONG_STORE:\n    case REMOVE_SONG_STORE:\n    case PUT_SONG_IN_SONG_STORE:\n    case REMOVE_SONG_FROM_SONG_STORE:\n      return {\n        ...state,\n        songStores: songStores(state.songStores, action)\n      }\n    default:\n      return state\n  }\n}\n\nexport default function songStores(state = {}, action) {\n  switch (action.type) {\n    case ADD_SONG_STORE_SUCCEEDED:\n      console.log(action, action.swarmLogMeta.id,action.swarmLogMeta)\n      return {\n        ...state,\n        [action.swarmLogMeta.id]: {\n//          id: action.songStoreId,\n          swarmLogMeta: { ...action.swarmLogMeta },\n          songs: {}\n        }\n      }\n    case REMOVE_SONG_STORE_SUCCEEDED: {\n      const songStores = { ...state }\n      delete songStores[action.songStoreId]\n      return songStores\n    }\n    case PUT_SONG_IN_SONG_STORE:\n    case REMOVE_SONG_FROM_SONG_STORE:\n      return {\n        ...state,\n        [action.songStoreId]: songStore(state[action.songStoreId], action)\n      }\n    default:\n      return state\n  }\n}\n\nfunction songStore(state = {}, action) {\n  const songs = { ...state.songs }\n  switch (action.type) {\n    case PUT_SONG_IN_SONG_STORE:\n      return {\n        ...state,\n        songs: {\n          ...songs,\n          [action.song.id]: action.song\n        }\n      }\n    case REMOVE_SONG_FROM_SONG_STORE: {\n      delete songs[action.songId]\n//      console.log(`delete ${action.id}` + songs)\n      return { ...state, songs }\n    }\n    default:\n      return state\n  }\n}\n\nexport function getSong(state, songStoreId, songId) {\n  return state.songStores[songStoreId][songId]\n}\n"
  },
  {
    "path": "examples/src/sagas/index.js",
    "content": "import { takeEvery } from 'redux-saga'\nimport { put, call } from 'redux-saga/effects'\nimport { generateKeys } from '../api'\nimport createSagaMiddleware from 'redux-saga'\n\nimport {\n  keyToUriId,\n  getSwarmLogsFromDb,\n  addReduxSwarmLog,\n  removeReduxSwarmLog\n}\n//from '../../../src/redux-swarmlog'\nfrom '../../../lib/index'\n\nimport {\n  ADD_SONG_STORE,\n  REMOVE_SONG_STORE,\n  addSongStoreSucceeded,\n  removeSongStoreSucceeded\n} from '../actions/index'\n\nexport const sagaMiddleware = createSagaMiddleware(\n  removeSongStore,\n  addSongStore\n)\n\nfunction *addSongStore() {\n  yield* takeEvery(ADD_SONG_STORE, getKeys)\n}\n\nfunction *getKeys(action) {\n  let swarmLogMeta = action.swarmLogMeta || {}\n  if (!action.swarmLogMeta.keys) {\n    swarmLogMeta.keys = yield call(generateKeys)\n    //swarmLogMeta.id = `${swarmLogMeta.name.replace(/\\s/g,'_')}-${swarmLogMeta.keys.public}`\n  }\n  yield addReduxSwarmLog(swarmLogMeta)\n  yield put(addSongStoreSucceeded(swarmLogMeta))\n}\n\nfunction *removeSongStore() {\n  yield* takeEvery(REMOVE_SONG_STORE, removeSongStoreFromDb)\n}\n\nfunction *removeSongStoreFromDb(action) {\n  yield removeReduxSwarmLog(action.songStoreId)\n  yield put(removeSongStoreSucceeded(action.songStoreId))\n}\n\n"
  },
  {
    "path": "index.html",
    "content": "<!doctype html>\n<html>\n  <head>\n    <title>React Transform Boilerplate</title>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    <script src=\"/static/bundle.js\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "keys.json",
    "content": "{\n  \"public\":\"qkN3S7AlBASCD6azVLqdPuWkp+TyU3g9RlfwCZA1yQ0=.ed25519\",\n  \"publicSuper\":\"btb+H8Z//WHc7HS1+u54DD0jnRObljx5mskPVxi3VkI=.ed25519\",\n  \"private\":\"O7GOCmou9JwXJtvDkhS17lSGbPokB3FoKB2FN67go5OqQ3dLsCUEBIIPprNUup0+5aSn5PJTeD1GV/AJkDXJDQ==.ed25519\",\n  \"privateSuper\":\"UA3MhnzUijBQYmetVrXJzoN0vAF/BunXqw32aqGeyW+DPssqSA87/kyN6TzBkbyqksVrlm0Ookhr5rcYkH+HkA==.ed25519\"\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"@philholden/redux-swarmlog\",\n  \"version\": \"0.0.1-semantic\",\n  \"description\": \"nothing\",\n  \"main\": \"lib/index.js\",\n  \"scripts\": {\n    \"clean\": \"rimraf lib dist\",\n    \"build:webpack\": \"cross-env NODE_ENV=production webpack --config webpack.config.prod.js\",\n    \"build:babel\": \"NODE_ENV=lib babel src --out-dir lib\",\n    \"build\": \"npm run clean && npm run build:webpack\",\n    \"start\": \"node devServer.js\",\n    \"lint\": \"eslint src\",\n    \"commit\": \"git-cz\",\n    \"open-coverage\": \"open ./coverage/lcov-report/index.html\",\n    \"check-coverage\": \"nyc check-coverage --statements 0 --branches 0 --functions 0 --lines 0\",\n    \"report-coverage\": \"nyc report --reporter=text-lcov | codecov\",\n    \"test\": \"NODE_ENV=test ava src/**/*.test.js --require babel-register --require ./src/__tests__/null-compiler\",\n    \"test:watch\": \"nodemon -w src --exec 'npm t -- --verbose'\",\n    \"test:cover\": \"nyc --reporter=lcov --reporter=text npm t\",\n    \"semantic-release\": \"semantic-release pre && npm publish --access=public && semantic-release post\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/philholden/redux-swarmlog.git\"\n  },\n  \"keywords\": [\n    \"react\",\n    \"reactjs\",\n    \"boilerplate\",\n    \"hot\",\n    \"reload\",\n    \"hmr\",\n    \"live\",\n    \"edit\",\n    \"webpack\",\n    \"babel\",\n    \"react-transform\"\n  ],\n  \"author\": \"Phil Holden (http://github.com/philholden)\",\n  \"license\": \"MIT\",\n  \"bugs\": {\n    \"url\": \"https://github.com/philholden/redux-swarmlog/issues\"\n  },\n  \"homepage\": \"https://github.com/philholden/redux-swarmlog/\",\n  \"devDependencies\": {\n    \"ava\": \"^0.14.0\",\n    \"babel-cli\": \"^6.4.0\",\n    \"babel-core\": \"^6.3.15\",\n    \"babel-eslint\": \"^5.0.0-beta4\",\n    \"babel-loader\": \"^6.2.0\",\n    \"babel-plugin-webpack-loaders\": \"^0.1.0\",\n    \"babel-polyfill\": \"^6.7.4\",\n    \"babel-preset-es2015\": \"^6.3.13\",\n    \"babel-preset-react\": \"^6.3.13\",\n    \"babel-preset-react-hmre\": \"^1.0.0\",\n    \"babel-preset-stage-1\": \"^6.5.0\",\n    \"babel-preset-stage-2\": \"^6.3.13\",\n    \"babel-register\": \"^6.3.13\",\n    \"brfs\": \"^1.4.3\",\n    \"chloride\": \"^2.1.1\",\n    \"codecov.io\": \"0.1.6\",\n    \"coffee-script\": \"^1.10.0\",\n    \"commitizen\": \"^2.7.6\",\n    \"compression\": \"^1.6.0\",\n    \"conventional-changelog\": \"^1.1.0\",\n    \"cross-env\": \"^1.0.6\",\n    \"cz-conventional-changelog\": \"^1.1.5\",\n    \"eslint\": \"^1.10.3\",\n    \"eslint-config-rackt\": \"^1.1.1\",\n    \"eslint-plugin-babel\": \"^3.0.0\",\n    \"eslint-plugin-react\": \"^3.11.3\",\n    \"eventsource-polyfill\": \"^0.9.6\",\n    \"expect\": \"^1.13.4\",\n    \"expect-jsx\": \"^2.2.2\",\n    \"express\": \"^4.13.3\",\n    \"file-loader\": \"^0.8.5\",\n    \"ghooks\": \"0.3.2\",\n    \"guid\": \"0.0.12\",\n    \"is_js\": \"^0.7.6\",\n    \"json-loader\": \"^0.5.4\",\n    \"keypair\": \"^1.0.0\",\n    \"level-js\": \"^2.2.3\",\n    \"levelup\": \"^1.3.1\",\n    \"libsodium\": \"^0.3.0\",\n    \"malloc\": \"^1.1.0\",\n    \"memdb\": \"^1.3.1\",\n    \"mock-fs\": \"^3.8.0\",\n    \"nodemon\": \"^1.8.1\",\n    \"nyc\": \"^5.3.0\",\n    \"react\": \"^15.0.1\",\n    \"react-addons-test-utils\": \"^15.0.1\",\n    \"react-dom\": \"^15.0.1\",\n    \"react-redux\": \"^4.4.2\",\n    \"redux\": \"^3.4.0\",\n    \"redux-saga\": \"^0.9.5\",\n    \"rimraf\": \"^2.4.3\",\n    \"semantic-release\": \"^4.3.5\",\n    \"socket.io\": \"^1.4.0\",\n    \"ssb-keys\": \"^5.0.1\",\n    \"swarmlog\": \"^1.4.0\",\n    \"transform-loader\": \"^0.2.3\",\n    \"url-loader\": \"^0.5.7\",\n    \"webpack\": \"^1.12.9\",\n    \"webpack-dev-middleware\": \"^1.4.0\",\n    \"webpack-hot-middleware\": \"^2.6.0\"\n  },\n  \"config\": {\n    \"ghooks\": {\n      \"pre-commit\": \"npm run test\"\n    },\n    \"commitizen\": {\n      \"path\": \"node_modules/cz-conventional-changelog\"\n    }\n  },\n  \"release\": {\n    \"debug\": false\n  }\n}\n"
  },
  {
    "path": "publish.html",
    "content": "<!doctype html>\n<html>\n  <head>\n    <title>React Transform Boilerplate</title>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    <script src=\"/static/publish.js\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "src/__tests__/index.test.js",
    "content": "import test from 'ava'\nimport is from 'is_js'\nimport React from 'react'\nimport { createRenderer } from 'react-addons-test-utils'\nimport expect from 'expect'\nimport expectJSX from 'expect-jsx'\n//import { HelloWorld } from '../App'\n\nexpect.extend(expectJSX)\n\ntest('is an array of numbers', t => {\n  t.true(\n    [ 1, 2, 3 ].every(item => typeof item === 'number')\n  )\n})\n\ntest('1 is in the array', t => {\n  t.true(\n    is.inArray(1, [ 1, 2, 3 ])\n  )\n})\n\n// test('MyComponent default render', () => {\n//   const renderer = createRenderer()\n\n//   renderer.render(\n//     <HelloWorld />\n//   )\n//   expect(\n//     renderer.getRenderOutput()\n//   )\n//   .toEqualJSX(\n//     <div>Hello World.</div>\n//   )\n// })\n"
  },
  {
    "path": "src/__tests__/null-compiler.js",
    "content": "// Prevent Mocha from compiling class\nfunction noop() {\n  return null\n}\n\nrequire.extensions['.css'] = noop\nrequire.extensions['.png'] = noop\n"
  },
  {
    "path": "src/index.js",
    "content": "import * as rds from './redux-swarmlog'\n\nmodule.exports = rds\n"
  },
  {
    "path": "src/redux-swarmlog.js",
    "content": "import swarmlog from 'swarmlog'\nimport leveljs from 'level-js'\nimport levelup from 'levelup'\nimport { randomBytes } from 'crypto'\n\nconst sessionId = randomBytes(32).toString('base64')\nconst reduxSwarmLogsDb = levelup('swarmlogs', { db: leveljs })\nlet _reduxSwarmLogs = {}\nlet _reduxStore\nlet _logLevel\nlet _logSampleActions = (...args) => {\n  if (_logLevel) console.log(args)\n}\n\nwindow.levelup = levelup\nwindow.clearTables = clearTables\n\nexport function clearTables() {\n  indexedDB.deleteDatabase('IDBWrapper-foo')\n  indexedDB.deleteDatabase('IDBWrapper-swarmlogs')\n  Object.keys(_reduxSwarmLogs).forEach(key => {\n    indexedDB.deleteDatabase(`IDBWrapper-${key}`)\n  })\n}\n\nexport const keyToUriId = (key) =>\n  key\n    .replace(/\\//g,'_')\n    .replace(/\\+/g,'-')\n    .replace(/=+\\.ed25519/,'')\n\nexport const uriIdToKey = (uriId) =>\n  uriId\n    .replace(/\\_/g,'/')\n    .replace(/\\-/g,'+') +\n    (uriId.length > 70 ? '=' : '') +\n    '=.ed25519'\n\nexport function getSwarmLogsFromDb() {\n  return new Promise((resolve, reject) => {\n    const reduxSwarmLogs = []\n    reduxSwarmLogsDb.createReadStream()\n    .on('data', data => {\n      const value = JSON.parse(data.value)\n      logJson(`hydrating from indexedDB`, value.id)\n      reduxSwarmLogs.push(value)\n    })\n    .on('error', err => reject(err))\n    .on('end', () => resolve(reduxSwarmLogs))\n  })\n}\n\nexport function removeReduxSwarmLog(id) {\n  return new Promise((resolve, reject) => {\n    const reduxSwarmLog = _reduxSwarmLogs[id]\n    //console.log(_reduxSwarmLogs, id, reduxSwarmLog.db.close)\n    reduxSwarmLog.db.close()\n    const req = indexedDB.deleteDatabase(`IDBWrapper-${id}`)\n    req.onsuccess = () => {\n      console.log(`database deleted`)\n      reduxSwarmLogsDb.del(reduxSwarmLog.keys.public, err => {\n        if (err) {\n          console.log(`Couldn't delete database entry`)\n          reject()\n        } else {\n          console.log(`database entry deleted`)\n          resolve(`Database removed`)\n        }\n      })\n    }\n\n    req.onerror = () => {\n      console.log(`Couldn't delete database`)\n      reject()\n    }\n\n    req.onblocked = () => {\n      console.log(`Couldn't delete database blocked`)\n      reject()\n    }\n  })\n}\n\nexport function addReduxSwarmLog(props) {\n  return new Promise((resolve, reject) => {\n    props.id = keyToUriId(props.keys.public)\n    const { name, keys, id } = props\n    const propsJson = JSON.stringify(props, null, 2)\n\n    if (_reduxSwarmLogs[id]) {\n      console.log(`store named ${name} already exists`)\n      resolve(_reduxSwarmLogs[id])\n      return\n    }\n\n    reduxSwarmLogsDb.get(id, (err, value) => {\n      if (err && err.notFound) {\n        reduxSwarmLogsDb.put(keys.public, propsJson, (err) => {\n          if (err) return reject(err)\n        })\n      }\n      _reduxSwarmLogs[id] = new ReduxSwarmLog({\n        name,\n        keys,\n        id\n      })\n      _logSampleActions(props)\n      resolve(_reduxSwarmLogs[id])\n    })\n  })\n}\n\nwindow.addReduxSwarmLog = addReduxSwarmLog\n\nexport function configureReduxSwarmLog({\n  reduxStore,\n  logSampleActions = _logSampleActions,\n  logLevel = 1\n}) {\n  _reduxStore = reduxStore\n  _logSampleActions = logSampleActions\n  _logLevel = logLevel\n}\n\nexport function reduxSwarmLogMiddleware() {\n  return next => action => {\n    const reduxSwarmLog = _reduxSwarmLogs[action.reduxSwarmLogId]\n    if (!action.fromSwarm && reduxSwarmLog && reduxSwarmLog.keys.private) {\n      action = {\n        ...action,\n        swarmLogSessionId: sessionId\n      }\n      if(reduxSwarmLog) {\n        reduxSwarmLog.log.append(action)\n        logJson('RTC SENT', action)\n      }\n    }\n    next(action)\n  }\n}\n\nexport default class ReduxSwarmLog {\n  constructor({ name, keys, id }) {\n    this.db = levelup(id, { db: leveljs })\n    this.keys = keys\n    this.log = this.getSwarmLog()\n    this.name = name\n    this.startReadStream()\n    this.id = id\n    logJson(\n      `CREATING ReduxSwarmLog ${name} and start listening`,\n      this.keys,\n      'green'\n    )\n  }\n\n  getSwarmLog() {\n    return swarmlog({\n      keys: this.keys,\n      sodium: require('chloride/browser'),\n      db: this.db,\n      valueEncoding: 'json',\n      hubs: [ 'https://signalhub.mafintosh.com' ]\n    })\n  }\n\n  startReadStream() {\n    this.log.createReadStream({ live: true })\n    .on('data', function (data) {\n      const action = data.value\n      if (action.swarmLogSessionId !== sessionId) {\n        _reduxStore.dispatch({\n          ...action,\n          fromSwarm: true\n        })\n      }\n      logJson('RTC RECEIVED', data.value)\n    })\n  }\n}\n\nfunction logJson(message, payload, color='black') {\n  if (!_logLevel) return\n  console.log(\n`\n%c${message}:\n\n%c${\n  typeof payload === 'string' ?\n  payload:\n  JSON.stringify(payload, null, 2)\n}\n\n`,\n    `font-weight: bold; color: ${color}`,\n    'font-weight: normal'\n  )\n}\n"
  },
  {
    "path": "webpack.config.dev.js",
    "content": "'use strict'\n\nlet path = require('path')\nlet webpack = require('webpack')\n\nconsole.log(__dirname)\n\nmodule.exports = {\n  // node: {\n  //   fs: 'empty'\n  // },\n\n  entry:{\n    bundle: [\n      'babel-polyfill',\n      'eventsource-polyfill', // necessary for hot reloading with IE\n      'webpack-hot-middleware/client',\n      './examples/src/index'\n    ],\n    publish: [\n      'eventsource-polyfill', // necessary for hot reloading with IE\n      'webpack-hot-middleware/client',\n      './examples/src/publish'\n    ],\n    consume: [\n      'eventsource-polyfill', // necessary for hot reloading with IE\n      'webpack-hot-middleware/client',\n      './examples/src/consume'\n    ]\n\n\n  },\n  output: {\n    path: path.join(__dirname, 'dist'),\n    filename: '[name].js',\n    publicPath: '/static/'\n  },\n  plugins: [\n    new webpack.HotModuleReplacementPlugin(),\n    new webpack.NoErrorsPlugin()\n  ],\n  resolve: {\n    modulesDirectories: [\n      path.join(__dirname, 'src'),\n      path.join(__dirname, 'examples', 'src'),\n      'node_modules',\n      'node_modules/component-archetype/node_modules'\n    ]\n  },\n  module: {\n    postLoaders: [\n      {\n        loader: 'transform?brfs'\n      }\n    ],\n    loaders: [\n      {\n        test: /\\.jsx?/,\n        loader: require.resolve('babel-loader'),\n        include: [\n          path.join(__dirname, 'src'),\n          path.join(__dirname, 'examples', 'src')\n        ]\n      },\n      {\n        test: /\\.png$/,\n        loader: require.resolve('url-loader') + '?limit=100000'\n      },\n      {\n        test: /\\.json$/,\n        loader: require.resolve('json-loader')\n      },\n      // {\n      //   test: /\\.js$/,\n      //   loader: 'transform?brfs'\n      // }\n\n    ]\n  }\n}\n"
  },
  {
    "path": "webpack.config.lib.js",
    "content": "var path = require('path') // eslint-disable-line no-var\n//var ExtractTextPlugin = require('extract-text-webpack-plugin') // eslint-disable-line no-var\n\nmodule.exports = {\n  output: {\n    libraryTarget: 'commonjs2',\n    path: path.join(__dirname, 'lib'),\n    publicPath: '/lib/'\n  },\n//  plugins: [\n//    new ExtractTextPlugin(path.parse(process.argv[2]).name + '.css')\n//  ],\n  module: {\n    loaders: [\n      {\n        test: /\\.png$/,\n        loaders: [ 'url-loader?limit=7000' ]\n      }\n    ]\n  }\n}\n"
  },
  {
    "path": "webpack.config.prod.js",
    "content": "var path = require('path') // eslint-disable-line no-var\nvar webpack = require('webpack') // eslint-disable-line no-var\n\nmodule.exports = {\n  devtool: 'source-map',\n  entry: [\n    './src/index'\n  ],\n  output: {\n    // export itself to a global var\n    libraryTarget: 'commonjs2',\n    // name of the global var: \"Foo\"\n    library: 'redux-swarmlog',\n    path: path.join(__dirname, 'lib'),\n    filename: 'index.js',\n    publicPath: '/static/'\n  },\n  plugins: [\n    new webpack.optimize.OccurenceOrderPlugin(),\n    new webpack.DefinePlugin({\n      'process.env': {\n        'NODE_ENV': JSON.stringify('production')\n      }\n    }),\n    new webpack.optimize.UglifyJsPlugin({\n      compressor: {\n        warnings: false\n      }\n    })\n  ],\n  resolve: {\n    modulesDirectories: [\n      path.join(__dirname, 'src'),\n      'node_modules',\n      'node_modules/component-archetype/node_modules'\n    ]\n  },\n  module: {\n    postLoaders: [\n      {\n        loader: 'transform?brfs'\n      }\n    ],\n    loaders: [\n      {\n        test: /\\.jsx?/,\n        loader: require.resolve('babel-loader'),\n        include: [\n          path.join(__dirname, 'src'),\n          path.join(__dirname, 'examples', 'src')\n        ]\n      },\n      {\n        test: /\\.png$/,\n        loader: require.resolve('url-loader') + '?limit=100000'\n      },\n      {\n        test: /\\.json$/,\n        loader: require.resolve('json-loader')\n      },\n      // {\n      //   test: /\\.js$/,\n      //   loader: 'transform?brfs'\n      // }\n\n    ]\n  }\n}\n"
  }
]