Full Code of omergulen/copycat for AI

master c792cf7ff0a7 cached
26 files
98.3 KB
25.4k tokens
41 symbols
1 requests
Download .txt
Repository: omergulen/copycat
Branch: master
Commit: c792cf7ff0a7
Files: 26
Total size: 98.3 KB

Directory structure:
gitextract_qjula_wf/

├── .gitignore
├── LICENSE
├── README.md
├── config/
│   ├── env.js
│   ├── jest/
│   │   ├── cssTransform.js
│   │   └── fileTransform.js
│   ├── paths.js
│   ├── polyfills.js
│   ├── webpack.config.dev.js
│   ├── webpack.config.prod.js
│   └── webpackDevServer.config.js
├── package.json
├── public/
│   ├── app/
│   │   └── background.js
│   ├── index.html
│   └── manifest.json
├── scripts/
│   ├── build.js
│   ├── start.js
│   └── test.js
└── src/
    ├── App.js
    ├── Commands.js
    ├── Constants.js
    ├── Generator.js
    ├── content.js
    ├── index.js
    ├── registerServiceWorker.js
    └── style.css

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
build/
package-lock.json
node_modules/
.idea/
.vscode/
yarn.lock

================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) 2018 Satendra Rai

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: README.md
================================================
[![Chrome Web Store](https://img.shields.io/chrome-web-store/v/dlbnejfbjfikckofdndbjndhhbplmnpj.svg?colorB=%234FC828&style=flat)](https://chrome.google.com/webstore/detail/testing-extension/dlbnejfbjfikckofdndbjndhhbplmnpj)
[![Chrome Web Store Rating](https://img.shields.io/chrome-web-store/stars/ibomigipadcieapbemkegkmadbbanbgm.svg?colorB=%234FC828&label=rating&style=flat)](https://chrome.google.com/webstore/detail/testing-extension/dlbnejfbjfikckofdndbjndhhbplmnpj)
[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg?style=flat)](https://github.com/omergulen/testing-extension/blob/master/LICENSE)

# Copycat - Testing Extension

<img src="./public/icon256.png" />

## (for jest-puppeteer)
This extension is built to ease creating web tests. It is like Selenium-IDE, but for jest-puppeteer (for now).

Also, this extension records actions on your own browser, so it doesn't need to open up new Selenium or Puppeteer window to record your actions on it.

In recording state it records the events which are stated below with the target elements unique selector.

### Supported Actions

#### Click origined events

| Action Key    | Description   |
| --------------------- | ------------- |
| `click`       | Mouse `click` event. |
| `mousedown`       | Mouse `mousedown` event. |
| `drag-and-drop` | If `mouseup` event comes after `mousedown` event and the difference between their coordinates is greater than 10. |

#### Key originated events

| Action Key    | Description   |
| --------------------- | ------------- |
| `keydown`       | Keyboard `keydown` event. It automaticly gathers the `keydown` events into one if they consecutive triggered and their selectors are the same. |
| `combined-keydown`       | It combines special keydown events if they are trigged at the same time, example: `Ctrl+A`. |

#### Page change events

| Action Key    | Description   |
| --------------------- | ------------- |
| `page-change`       | If `onbeforeunload` event is triggered. |
| `click-page-change` | If `onbeforeunload` event of the window comes after `click` or `mousedown` event. |

#### Verify events

Triggers with right click on the element and choose proper verify action.

| Action Key    | Description   |
| --------------------- | ------------- |
| `verify-text`       | It gets the right clicked element's `text` and matches with the `textContent` of the element in the test. |
| `verify-link`       | It gets the right clicked element's `href` and matches with the `href` of the element in the test. |
| `verify-DOM`       | It gets the right clicked element and check if it exists in the test. |

## Installation

### Google Web Store
[Install on Chrome Web Store](https://chrome.google.com/webstore/detail/testing-extension/dlbnejfbjfikckofdndbjndhhbplmnpj)   

<a href="https://chrome.google.com/webstore/detail/testing-extension/dlbnejfbjfikckofdndbjndhhbplmnpj"><img src="https://raw.githubusercontent.com/alrra/browser-logos/master/src/chrome/chrome_128x128.png" width="48" /></a>

or 

### Manual Installation

```
git clone https://github.com/omergulen/copycat.git
```
Go to `copycat` directory run

```
yarn install
```
Now build the extension using
```
yarn build
```
You will see a `build` folder generated inside `[PROJECT_HOME]`

#### Adding Copycat to Chrome

In Chrome browser, go to `chrome://extensions` page and switch on developer mode. This enables the ability to locally install a Chrome extension.

<img src="https://cdn-images-1.medium.com/max/1600/1*OaygCwLSwLakyTqCADbmDw.png" />

Now click on the `LOAD UNPACKED` and browse to `[PROJECT_HOME]\build` ,This will install the React app as a Chrome extension.

When you go to any website and click on extension icon, injected page will toggle.

<img src="./assets/extension_test.png" />

<img src="./assets/extension_test2.png" />

<img src="./assets/close_on_hover.png" />

Remove unwanted actions on hover.

## Usage - Testing Environment

### Installation of jest-puppeteer

```bash
# for jest 22~23
yarn add --save-dev jest-puppeteer@3.9.0 puppeteer jest
# for jest 24+
yarn add --save-dev jest-puppeteer puppeteer jest
```
or

```bash
# for jest 22~23
npm install --save-dev jest-puppeteer@3.9.0 puppeteer jest
# for jest 24+
npm install --save-dev jest-puppeteer puppeteer jest
```

### Update Jest configuration

Create `jest.config.js` in the root of your testing environment.

```
module.exports = {
  "preset": "jest-puppeteer"
}
```


### Creating `__tests__` folder

To work with default `jest-puppeteer` preset, you need to put your test files into the `__tests__` folder in the root of your testing environment.


### Basic Test Output Code

Following test example in the GIF will generate such code. It starts in [my GitHub Profile](https://github.com/omergulen) and clicks one of the pinned repositories (testing-extension) and when page changes it checks for the repository title's `href` is `https://github.com/omergulen/copycat` or not.


```
describe('Test 1', () => {
	beforeAll(async () => {
		await page.goto('https://github.com/omergulen');
	});

	it('Test 1 - 1', async () => {
		await Promise.all([
			page.click(':nth-child(2) > .Box > .pinned-item-list-item-content > .d-flex > .text-bold > .repo'),
			page.waitForNavigation()
		]);
		var nodeLink = await page.$$eval('strong > a', el => el[0].href)
		expect(nodeLink).toBe('https://github.com/omergulen/copycat');
	}, 60000);
});
```


<img src="./assets/test_example.gif" />


### Update Puppeteer configuration _(optional)_

Create `jest-puppeteer.config.js` in the root of your testing environment.
```
module.exports = {
  launch: {
    headless: false, // Disable headless chromium
    defaultViewport: null // Set page fit to the browser
  },
  browserContext: 'default',
}
```

### Adding `test` command to the project configuration

In your project's `package.json` file, insert `"test": "jest"` line into the `"scripts"` object.

It will basicly look something like that:
```
{
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "jest-puppeteer": "^4.3.0"
  },
  "dependencies": {
    "jest": "^24.8.0",
    "puppeteer": "^1.19.0"
  }
}
```

### Running tests

`yarn run test` or `npm run test` will do.

<img src="./assets/run_test.png" />

## Contribution

Bug reports and pull requests are welcome on GitHub at https://github.com/omergulen/testing-extension. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct


## License

The repo is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


================================================
FILE: config/env.js
================================================
'use strict';

const fs = require('fs');
const path = require('path');
const paths = require('./paths');

// Make sure that including paths.js after env.js will read .env variables.
delete require.cache[require.resolve('./paths')];

const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
  throw new Error(
    'The NODE_ENV environment variable is required but was not specified.'
  );
}

// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
var dotenvFiles = [
  `${paths.dotenv}.${NODE_ENV}.local`,
  `${paths.dotenv}.${NODE_ENV}`,
  // Don't include `.env.local` for `test` environment
  // since normally you expect tests to produce the same
  // results for everyone
  NODE_ENV !== 'test' && `${paths.dotenv}.local`,
  paths.dotenv,
].filter(Boolean);

// Load environment variables from .env* files. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.  Variable expansion is supported in .env files.
// https://github.com/motdotla/dotenv
// https://github.com/motdotla/dotenv-expand
dotenvFiles.forEach(dotenvFile => {
  if (fs.existsSync(dotenvFile)) {
    require('dotenv-expand')(
      require('dotenv').config({
        path: dotenvFile,
      })
    );
  }
});

// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebookincubator/create-react-app/issues/253.
// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421
// We also resolve them to make sure all tools using them work consistently.
const appDirectory = fs.realpathSync(process.cwd());
process.env.NODE_PATH = (process.env.NODE_PATH || '')
  .split(path.delimiter)
  .filter(folder => folder && !path.isAbsolute(folder))
  .map(folder => path.resolve(appDirectory, folder))
  .join(path.delimiter);

// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
// injected into the application via DefinePlugin in Webpack configuration.
const REACT_APP = /^REACT_APP_/i;

function getClientEnvironment(publicUrl) {
  const raw = Object.keys(process.env)
    .filter(key => REACT_APP.test(key))
    .reduce(
      (env, key) => {
        env[key] = process.env[key];
        return env;
      },
      {
        // Useful for determining whether we’re running in production mode.
        // Most importantly, it switches React into the correct mode.
        NODE_ENV: process.env.NODE_ENV || 'development',
        // Useful for resolving the correct path to static assets in `public`.
        // For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
        // This should only be used as an escape hatch. Normally you would put
        // images into the `src` and `import` them in code to get their paths.
        PUBLIC_URL: publicUrl,
      }
    );
  // Stringify all values so we can feed into Webpack DefinePlugin
  const stringified = {
    'process.env': Object.keys(raw).reduce((env, key) => {
      env[key] = JSON.stringify(raw[key]);
      return env;
    }, {}),
  };

  return { raw, stringified };
}

module.exports = getClientEnvironment;


================================================
FILE: config/jest/cssTransform.js
================================================
'use strict';

// This is a custom Jest transformer turning style imports into empty objects.
// http://facebook.github.io/jest/docs/en/webpack.html

module.exports = {
  process() {
    return 'module.exports = {};';
  },
  getCacheKey() {
    // The output is always the same.
    return 'cssTransform';
  },
};


================================================
FILE: config/jest/fileTransform.js
================================================
'use strict';

const path = require('path');

// This is a custom Jest transformer turning file imports into filenames.
// http://facebook.github.io/jest/docs/en/webpack.html

module.exports = {
  process(src, filename) {
    return `module.exports = ${JSON.stringify(path.basename(filename))};`;
  },
};


================================================
FILE: config/paths.js
================================================
'use strict';

const path = require('path');
const fs = require('fs');
const url = require('url');

// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);

const envPublicUrl = process.env.PUBLIC_URL;

function ensureSlash(path, needsSlash) {
  const hasSlash = path.endsWith('/');
  if (hasSlash && !needsSlash) {
    return path.substr(path, path.length - 1);
  } else if (!hasSlash && needsSlash) {
    return `${path}/`;
  } else {
    return path;
  }
}

const getPublicUrl = appPackageJson =>
  envPublicUrl || require(appPackageJson).homepage;

// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// Webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
function getServedPath(appPackageJson) {
  const publicUrl = getPublicUrl(appPackageJson);
  const servedUrl =
    envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/');
  return ensureSlash(servedUrl, true);
}

// config after eject: we're in ./config/
module.exports = {
  dotenv: resolveApp('.env'),
  appBuild: resolveApp('build'),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveApp('src/index.js'),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  publicUrl: getPublicUrl(resolveApp('package.json')),
  servedPath: getServedPath(resolveApp('package.json')),
};


================================================
FILE: config/polyfills.js
================================================
'use strict';

if (typeof Promise === 'undefined') {
  // Rejection tracking prevents a common issue where React gets into an
  // inconsistent state due to an error, but it gets swallowed by a Promise,
  // and the user has no idea what causes React's erratic future behavior.
  require('promise/lib/rejection-tracking').enable();
  window.Promise = require('promise/lib/es6-extensions.js');
}

// fetch() polyfill for making API calls.
require('whatwg-fetch');

// Object.assign() is commonly used with React.
// It will use the native implementation if it's present and isn't buggy.
Object.assign = require('object-assign');

// In tests, polyfill requestAnimationFrame since jsdom doesn't provide it yet.
// We don't polyfill it in the browser--this is user's responsibility.
if (process.env.NODE_ENV === 'test') {
  require('raf').polyfill(global);
}


================================================
FILE: config/webpack.config.dev.js
================================================
'use strict';

const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getClientEnvironment = require('./env');
const paths = require('./paths');

// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
const publicPath = '/';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = '';
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);

// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate file.
module.exports = {
  // You may want 'eval' instead if you prefer to see the compiled output in DevTools.
  // See the discussion in https://github.com/facebookincubator/create-react-app/issues/343.
  devtool: 'cheap-module-source-map',
  // These are the "entry points" to our application.
  // This means they will be the "root" imports that are included in JS bundle.
  // The first two entry points enable "hot" CSS and auto-refreshes for JS.
  entry: [
    // We ship a few polyfills by default:
    require.resolve('./polyfills'),
    // Include an alternative client for WebpackDevServer. A client's job is to
    // connect to WebpackDevServer by a socket and get notified about changes.
    // When you save a file, the client will either apply hot updates (in case
    // of CSS changes), or refresh the page (in case of JS changes). When you
    // make a syntax error, this client will display a syntax error overlay.
    // Note: instead of the default WebpackDevServer client, we use a custom one
    // to bring better experience for Create React App users. You can replace
    // the line below with these two lines if you prefer the stock client:
    // require.resolve('webpack-dev-server/client') + '?/',
    // require.resolve('webpack/hot/dev-server'),
    require.resolve('react-dev-utils/webpackHotDevClient'),
    // Finally, this is your app's code:
    paths.appIndexJs,
    // We include the app code last so that if there is a runtime error during
    // initialization, it doesn't blow up the WebpackDevServer client, and
    // changing JS code would still trigger a refresh.
  ],
  output: {
    // Add /* filename */ comments to generated require()s in the output.
    pathinfo: true,
    // This does not produce a real file. It's just the virtual path that is
    // served by WebpackDevServer in development. This is the JS bundle
    // containing code from all our entry points, and the Webpack runtime.
    filename: 'static/js/bundle.js',
    // There are also additional JS chunk files if you use code splitting.
    chunkFilename: 'static/js/[name].chunk.js',
    // This is the URL that app is served from. We use "/" in development.
    publicPath: publicPath,
    // Point sourcemap entries to original disk location (format as URL on Windows)
    devtoolModuleFilenameTemplate: info =>
      path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
  },
  resolve: {
    // This allows you to set a fallback for where Webpack should look for modules.
    // We placed these paths second because we want `node_modules` to "win"
    // if there are any conflicts. This matches Node resolution mechanism.
    // https://github.com/facebookincubator/create-react-app/issues/253
    modules: ['node_modules', paths.appNodeModules].concat(
      // It is guaranteed to exist because we tweak it in `env.js`
      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
    ),
    // These are the reasonable defaults supported by the Node ecosystem.
    // We also include JSX as a common component filename extension to support
    // some tools, although we do not recommend using it, see:
    // https://github.com/facebookincubator/create-react-app/issues/290
    // `web` extension prefixes have been added for better support
    // for React Native Web.
    extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
    alias: {
      
      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web',
    },
    plugins: [
      // Prevents users from importing files from outside of src/ (or node_modules/).
      // This often causes confusion because we only process files within src/ with babel.
      // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
      // please link the files into your node_modules/ and let module-resolution kick in.
      // Make sure your source files are compiled, as they will not be processed in any way.
      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
    ],
  },
  module: {
    strictExportPresence: true,
    rules: [
      // TODO: Disable require.ensure as it's not a standard language feature.
      // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
      // { parser: { requireEnsure: false } },

      // First, run the linter.
      // It's important to do this before Babel processes the JS.
      {
        test: /\.(js|jsx|mjs)$/,
        enforce: 'pre',
        use: [
          {
            options: {
              formatter: eslintFormatter,
              eslintPath: require.resolve('eslint'),
              
            },
            loader: require.resolve('eslint-loader'),
          },
        ],
        include: paths.appSrc,
      },
      {
        // "oneOf" will traverse all following loaders until one will
        // match the requirements. When no loader matches it will fall
        // back to the "file" loader at the end of the loader list.
        oneOf: [
          // "url" loader works like "file" loader except that it embeds assets
          // smaller than specified limit in bytes as data URLs to avoid requests.
          // A missing `test` is equivalent to a match.
          {
            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
            loader: require.resolve('url-loader'),
            options: {
              limit: 10000,
              name: 'static/media/[name].[hash:8].[ext]',
            },
          },
          // Process JS with Babel.
          {
            test: /\.(js|jsx|mjs)$/,
            include: paths.appSrc,
            loader: require.resolve('babel-loader'),
            options: {
              
              // This is a feature of `babel-loader` for webpack (not Babel itself).
              // It enables caching results in ./node_modules/.cache/babel-loader/
              // directory for faster rebuilds.
              cacheDirectory: true,
            },
          },
          // "postcss" loader applies autoprefixer to our CSS.
          // "css" loader resolves paths in CSS and adds assets as dependencies.
          // "style" loader turns CSS into JS modules that inject <style> tags.
          // In production, we use a plugin to extract that CSS to a file, but
          // in development "style" loader enables hot editing of CSS.
          {
            test: /\.css$/,
            use: [
              require.resolve('style-loader'),
              {
                loader: require.resolve('css-loader'),
                options: {
                  importLoaders: 1,
                },
              },
              {
                loader: require.resolve('postcss-loader'),
                options: {
                  // Necessary for external CSS imports to work
                  // https://github.com/facebookincubator/create-react-app/issues/2677
                  ident: 'postcss',
                  plugins: () => [
                    require('postcss-flexbugs-fixes'),
                    autoprefixer({
                      browsers: [
                        '>1%',
                        'last 4 versions',
                        'Firefox ESR',
                        'not ie < 9', // React doesn't support IE8 anyway
                      ],
                      flexbox: 'no-2009',
                    }),
                  ],
                },
              },
            ],
          },
          // "file" loader makes sure those assets get served by WebpackDevServer.
          // When you `import` an asset, you get its (virtual) filename.
          // In production, they would get copied to the `build` folder.
          // This loader doesn't use a "test" so it will catch all modules
          // that fall through the other loaders.
          {
            // Exclude `js` files to keep "css" loader working as it injects
            // its runtime that would otherwise processed through "file" loader.
            // Also exclude `html` and `json` extensions so they get processed
            // by webpacks internal loaders.
            exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
            loader: require.resolve('file-loader'),
            options: {
              name: 'static/media/[name].[hash:8].[ext]',
            },
          },
        ],
      },
      // ** STOP ** Are you adding a new loader?
      // Make sure to add the new loader(s) before the "file" loader.
    ],
  },
  plugins: [
    // Makes some environment variables available in index.html.
    // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In development, this will be an empty string.
    new InterpolateHtmlPlugin(env.raw),
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml,
    }),
    // Add module names to factory functions so they appear in browser profiler.
    new webpack.NamedModulesPlugin(),
    // Makes some environment variables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
    new webpack.DefinePlugin(env.stringified),
    // This is necessary to emit hot updates (currently CSS only):
    new webpack.HotModuleReplacementPlugin(),
    // Watcher doesn't work well if you mistype casing in a path so we use
    // a plugin that prints an error when you attempt to do this.
    // See https://github.com/facebookincubator/create-react-app/issues/240
    new CaseSensitivePathsPlugin(),
    // If you require a missing module and then `npm install` it, you still have
    // to restart the development server for Webpack to discover it. This plugin
    // makes the discovery automatic so you don't have to restart.
    // See https://github.com/facebookincubator/create-react-app/issues/186
    new WatchMissingNodeModulesPlugin(paths.appNodeModules),
    // Moment.js is an extremely popular library that bundles large locale files
    // by default due to how Webpack interprets its code. This is a practical
    // solution that requires the user to opt into importing specific locales.
    // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
    // You can remove this if you don't use Moment.js:
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  ],
  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  node: {
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty',
  },
  // Turn off performance hints during development because we don't do any
  // splitting or minification in interest of speed. These warnings become
  // cumbersome.
  performance: {
    hints: false,
  },
};


================================================
FILE: config/webpack.config.prod.js
================================================
'use strict';

const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');

// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
const publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);

// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
  throw new Error('Production builds must have NODE_ENV=production.');
}

// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].css';

// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
  ? // Making sure that the publicPath goes back to to build folder.
    { publicPath: Array(cssFilename.split('/').length).join('../') }
  : {};

// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
  // Don't attempt to continue if there are any errors.
  bail: true,
  // We generate sourcemaps in production. This is slow but gives good results.
  // You can exclude the *.map files from the build during deployment.
  devtool: shouldUseSourceMap ? 'source-map' : false,
  // In production, we only want to load the polyfills and the app code.
  entry: {
    app: [require.resolve('./polyfills'), paths.appIndexJs],
    content: [require.resolve('./polyfills'), './src/content.js']
  },
  output: {
    // The build folder.
    path: paths.appBuild,
    // Generated JS file names (with nested folders).
    // There will be one main bundle, and one file per asynchronous chunk.
    // We don't currently advertise code splitting but Webpack supports it.
    filename: 'static/js/[name].js',
    chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
    // We inferred the "public path" (such as / or /my-project) from homepage.
    publicPath: publicPath,
    // Point sourcemap entries to original disk location (format as URL on Windows)
    devtoolModuleFilenameTemplate: info =>
      path
        .relative(paths.appSrc, info.absoluteResourcePath)
        .replace(/\\/g, '/'),
  },
  resolve: {
    // This allows you to set a fallback for where Webpack should look for modules.
    // We placed these paths second because we want `node_modules` to "win"
    // if there are any conflicts. This matches Node resolution mechanism.
    // https://github.com/facebookincubator/create-react-app/issues/253
    modules: ['node_modules', paths.appNodeModules].concat(
      // It is guaranteed to exist because we tweak it in `env.js`
      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
    ),
    // These are the reasonable defaults supported by the Node ecosystem.
    // We also include JSX as a common component filename extension to support
    // some tools, although we do not recommend using it, see:
    // https://github.com/facebookincubator/create-react-app/issues/290
    // `web` extension prefixes have been added for better support
    // for React Native Web.
    extensions: ['.web.js', '.mjs', '.js', '.json', '.web.jsx', '.jsx'],
    alias: {
      
      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web',
    },
    plugins: [
      // Prevents users from importing files from outside of src/ (or node_modules/).
      // This often causes confusion because we only process files within src/ with babel.
      // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
      // please link the files into your node_modules/ and let module-resolution kick in.
      // Make sure your source files are compiled, as they will not be processed in any way.
      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
    ],
  },
  module: {
    strictExportPresence: true,
    rules: [
      // TODO: Disable require.ensure as it's not a standard language feature.
      // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
      // { parser: { requireEnsure: false } },

      // First, run the linter.
      // It's important to do this before Babel processes the JS.
      {
        test: /\.(js|jsx|mjs)$/,
        enforce: 'pre',
        use: [
          {
            options: {
              formatter: eslintFormatter,
              eslintPath: require.resolve('eslint'),
              
            },
            loader: require.resolve('eslint-loader'),
          },
        ],
        include: paths.appSrc,
      },
      {
        // "oneOf" will traverse all following loaders until one will
        // match the requirements. When no loader matches it will fall
        // back to the "file" loader at the end of the loader list.
        oneOf: [
          // "url" loader works just like "file" loader but it also embeds
          // assets smaller than specified size as data URLs to avoid requests.
          {
            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
            loader: require.resolve('url-loader'),
            options: {
              limit: 10000,
              name: 'static/media/[name].[hash:8].[ext]',
            },
          },
          // Process JS with Babel.
          {
            test: /\.(js|jsx|mjs)$/,
            include: paths.appSrc,
            loader: require.resolve('babel-loader'),
            options: {
              
              compact: true,
            },
          },
          // The notation here is somewhat confusing.
          // "postcss" loader applies autoprefixer to our CSS.
          // "css" loader resolves paths in CSS and adds assets as dependencies.
          // "style" loader normally turns CSS into JS modules injecting <style>,
          // but unlike in development configuration, we do something different.
          // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
          // (second argument), then grabs the result CSS and puts it into a
          // separate file in our build process. This way we actually ship
          // a single CSS file in production instead of JS code injecting <style>
          // tags. If you use code splitting, however, any async bundles will still
          // use the "style" loader inside the async code so CSS from them won't be
          // in the main CSS file.
          {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract(
              Object.assign(
                {
                  fallback: {
                    loader: require.resolve('style-loader'),
                    options: {
                      hmr: false,
                    },
                  },
                  use: [
                    {
                      loader: require.resolve('css-loader'),
                      options: {
                        importLoaders: 1,
                        minimize: true,
                        sourceMap: shouldUseSourceMap,
                      },
                    },
                    {
                      loader: require.resolve('postcss-loader'),
                      options: {
                        // Necessary for external CSS imports to work
                        // https://github.com/facebookincubator/create-react-app/issues/2677
                        ident: 'postcss',
                        plugins: () => [
                          require('postcss-flexbugs-fixes'),
                          autoprefixer({
                            browsers: [
                              '>1%',
                              'last 4 versions',
                              'Firefox ESR',
                              'not ie < 9', // React doesn't support IE8 anyway
                            ],
                            flexbox: 'no-2009',
                          }),
                        ],
                      },
                    },
                  ],
                },
                extractTextPluginOptions
              )
            ),
            // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
          },
          // "file" loader makes sure assets end up in the `build` folder.
          // When you `import` an asset, you get its filename.
          // This loader doesn't use a "test" so it will catch all modules
          // that fall through the other loaders.
          {
            loader: require.resolve('file-loader'),
            // Exclude `js` files to keep "css" loader working as it injects
            // it's runtime that would otherwise processed through "file" loader.
            // Also exclude `html` and `json` extensions so they get processed
            // by webpacks internal loaders.
            exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
            options: {
              name: 'static/media/[name].[hash:8].[ext]',
            },
          },
          // ** STOP ** Are you adding a new loader?
          // Make sure to add the new loader(s) before the "file" loader.
        ],
      },
    ],
  },
  plugins: [
    // Makes some environment variables available in index.html.
    // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In production, it will be an empty string unless you specify "homepage"
    // in `package.json`, in which case it will be the pathname of that URL.
    new InterpolateHtmlPlugin(env.raw),
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
    }),
    // Makes some environment variables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
    // It is absolutely essential that NODE_ENV was set to production here.
    // Otherwise React will be compiled in the very slow development mode.
    new webpack.DefinePlugin(env.stringified),
    // Minify the code.
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        // Disabled because of an issue with Uglify breaking seemingly valid code:
        // https://github.com/facebookincubator/create-react-app/issues/2376
        // Pending further investigation:
        // https://github.com/mishoo/UglifyJS2/issues/2011
        comparisons: false,
      },
      mangle: {
        safari10: true,
      },
      output: {
        comments: false,
        // Turned on because emoji and regex is not minified properly using default
        // https://github.com/facebookincubator/create-react-app/issues/2488
        ascii_only: true,
      },
      sourceMap: shouldUseSourceMap,
    }),
    // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
    new ExtractTextPlugin({
      filename: cssFilename,
    }),
    // Generate a manifest file which contains a mapping of all asset filenames
    // to their corresponding output file so that tools can pick it up without
    // having to parse `index.html`.
    new ManifestPlugin({
      fileName: 'asset-manifest.json',
    }),
    // Generate a service worker script that will precache, and keep up to date,
    // the HTML & assets that are part of the Webpack build.
    new SWPrecacheWebpackPlugin({
      // By default, a cache-busting query parameter is appended to requests
      // used to populate the caches, to ensure the responses are fresh.
      // If a URL is already hashed by Webpack, then there is no concern
      // about it being stale, and the cache-busting can be skipped.
      dontCacheBustUrlsMatching: /\.\w{8}\./,
      filename: 'service-worker.js',
      logger(message) {
        if (message.indexOf('Total precache size is') === 0) {
          // This message occurs for every build and is a bit too noisy.
          return;
        }
        if (message.indexOf('Skipping static resource') === 0) {
          // This message obscures real errors so we ignore it.
          // https://github.com/facebookincubator/create-react-app/issues/2612
          return;
        }
        console.log(message);
      },
      minify: true,
      // For unknown URLs, fallback to the index page
      navigateFallback: publicUrl + '/index.html',
      // Ignores URLs starting from /__ (useful for Firebase):
      // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
      navigateFallbackWhitelist: [/^(?!\/__).*/],
      // Don't precache sourcemaps (they're large) and build asset manifest:
      staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
    }),
    // Moment.js is an extremely popular library that bundles large locale files
    // by default due to how Webpack interprets its code. This is a practical
    // solution that requires the user to opt into importing specific locales.
    // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
    // You can remove this if you don't use Moment.js:
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  ],
  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  node: {
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty',
  },
};


================================================
FILE: config/webpackDevServer.config.js
================================================
'use strict';

const errorOverlayMiddleware = require('react-dev-utils/errorOverlayMiddleware');
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');
const ignoredFiles = require('react-dev-utils/ignoredFiles');
const config = require('./webpack.config.dev');
const paths = require('./paths');

const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const host = process.env.HOST || '0.0.0.0';

module.exports = function(proxy, allowedHost) {
  return {
    // WebpackDevServer 2.4.3 introduced a security fix that prevents remote
    // websites from potentially accessing local content through DNS rebinding:
    // https://github.com/webpack/webpack-dev-server/issues/887
    // https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a
    // However, it made several existing use cases such as development in cloud
    // environment or subdomains in development significantly more complicated:
    // https://github.com/facebookincubator/create-react-app/issues/2271
    // https://github.com/facebookincubator/create-react-app/issues/2233
    // While we're investigating better solutions, for now we will take a
    // compromise. Since our WDS configuration only serves files in the `public`
    // folder we won't consider accessing them a vulnerability. However, if you
    // use the `proxy` feature, it gets more dangerous because it can expose
    // remote code execution vulnerabilities in backends like Django and Rails.
    // So we will disable the host check normally, but enable it if you have
    // specified the `proxy` setting. Finally, we let you override it if you
    // really know what you're doing with a special environment variable.
    disableHostCheck:
      !proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true',
    // Enable gzip compression of generated files.
    compress: true,
    // Silence WebpackDevServer's own logs since they're generally not useful.
    // It will still show compile warnings and errors with this setting.
    clientLogLevel: 'none',
    // By default WebpackDevServer serves physical files from current directory
    // in addition to all the virtual build products that it serves from memory.
    // This is confusing because those files won’t automatically be available in
    // production build folder unless we copy them. However, copying the whole
    // project directory is dangerous because we may expose sensitive files.
    // Instead, we establish a convention that only files in `public` directory
    // get served. Our build script will copy `public` into the `build` folder.
    // In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
    // Note that we only recommend to use `public` folder as an escape hatch
    // for files like `favicon.ico`, `manifest.json`, and libraries that are
    // for some reason broken when imported through Webpack. If you just want to
    // use an image, put it in `src` and `import` it from JavaScript instead.
    contentBase: paths.appPublic,
    // By default files from `contentBase` will not trigger a page reload.
    watchContentBase: true,
    // Enable hot reloading server. It will provide /sockjs-node/ endpoint
    // for the WebpackDevServer client so it can learn when the files were
    // updated. The WebpackDevServer client is included as an entry point
    // in the Webpack development configuration. Note that only changes
    // to CSS are currently hot reloaded. JS changes will refresh the browser.
    hot: true,
    // It is important to tell WebpackDevServer to use the same "root" path
    // as we specified in the config. In development, we always serve from /.
    publicPath: config.output.publicPath,
    // WebpackDevServer is noisy by default so we emit custom message instead
    // by listening to the compiler events with `compiler.plugin` calls above.
    quiet: true,
    // Reportedly, this avoids CPU overload on some systems.
    // https://github.com/facebookincubator/create-react-app/issues/293
    // src/node_modules is not ignored to support absolute imports
    // https://github.com/facebookincubator/create-react-app/issues/1065
    watchOptions: {
      ignored: ignoredFiles(paths.appSrc),
    },
    // Enable HTTPS if the HTTPS environment variable is set to 'true'
    https: protocol === 'https',
    host: host,
    overlay: false,
    historyApiFallback: {
      // Paths with dots should still use the history fallback.
      // See https://github.com/facebookincubator/create-react-app/issues/387.
      disableDotRule: true,
    },
    public: allowedHost,
    proxy,
    before(app) {
      // This lets us open files from the runtime error overlay.
      app.use(errorOverlayMiddleware());
      // This service worker file is effectively a 'no-op' that will reset any
      // previous service worker registered for the same host:port combination.
      // We do this in development to avoid hitting the production cache if
      // it used the same host and port.
      // https://github.com/facebookincubator/create-react-app/issues/2272#issuecomment-302832432
      app.use(noopServiceWorkerMiddleware());
    },
  };
};


================================================
FILE: package.json
================================================
{
  "name": "copycat",
  "version": "1.0.5",
  "private": false,
  "dependencies": {
    "autoprefixer": "7.1.6",
    "babel-core": "6.26.0",
    "babel-eslint": "7.2.3",
    "babel-jest": "20.0.3",
    "babel-loader": "7.1.2",
    "babel-preset-react-app": "^3.1.1",
    "babel-runtime": "6.26.0",
    "case-sensitive-paths-webpack-plugin": "2.1.1",
    "chalk": "1.1.3",
    "css-loader": "0.28.7",
    "dotenv": "4.0.0",
    "dotenv-expand": "4.2.0",
    "eslint": "^5.16.0",
    "eslint-config-react-app": "^2.1.0",
    "eslint-loader": "1.9.0",
    "eslint-plugin-flowtype": "2.39.1",
    "eslint-plugin-import": "2.8.0",
    "eslint-plugin-jsx-a11y": "5.1.1",
    "eslint-plugin-react": "7.4.0",
    "extract-text-webpack-plugin": "3.0.2",
    "file-loader": "1.1.5",
    "fs-extra": "3.0.1",
    "html-webpack-plugin": "2.29.0",
    "jest": "20.0.4",
    "js-beautify": "^1.10.2",
    "object-assign": "4.1.1",
    "postcss-flexbugs-fixes": "3.2.0",
    "postcss-loader": "2.0.8",
    "promise": "8.0.1",
    "raf": "3.4.0",
    "react": "^16.4.1",
    "react-dev-utils": "^5.0.1",
    "react-dom": "^16.4.1",
    "react-frame-component": "^4.0.0",
    "resolve": "1.6.0",
    "style-loader": "0.19.0",
    "sw-precache-webpack-plugin": "0.11.4",
    "unique-selector": "^0.4.1",
    "url-loader": "0.6.2",
    "webpack": "3.8.1",
    "webpack-dev-server": ">=3.1.11",
    "webpack-manifest-plugin": "1.3.2",
    "whatwg-fetch": "2.0.3"
  },
  "scripts": {
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "test": "node scripts/test.js --env=jsdom"
  },
  "jest": {
    "collectCoverageFrom": [
      "src/**/*.{js,jsx,mjs}"
    ],
    "setupFiles": [
      "<rootDir>/config/polyfills.js"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
      "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
    ],
    "testEnvironment": "node",
    "testURL": "http://localhost",
    "transform": {
      "^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
    ],
    "moduleNameMapper": {
      "^react-native$": "react-native-web"
    },
    "moduleFileExtensions": [
      "web.js",
      "js",
      "json",
      "web.jsx",
      "jsx",
      "node",
      "mjs"
    ]
  },
  "babel": {
    "presets": [
      "react-app"
    ]
  },
  "eslintConfig": {
    "extends": "react-app"
  }
}

================================================
FILE: public/app/background.js
================================================
'use strict';
// Called when the user clicks on the browser action
chrome.browserAction.onClicked.addListener(function (tab) {
   // Send a message to the active tab
   chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      var activeTab = tabs[0];
      chrome.tabs.sendMessage(activeTab.id, { "message": "clicked_browser_action" });
   });
});

// Extension successfully installed.
chrome.runtime.onInstalled.addListener(function () {
   console.log('The extension has installed.');
});

// Download promp starter / handler
chrome.runtime.onMessage.addListener(
   (request, sender, sendResponse) => {
      if (request.downloadContent) {
         let docContent = request.downloadContent;
         let doc = URL.createObjectURL(new Blob([docContent], { type: 'application/octet-binary' }));
         chrome.downloads.download({ url: doc, filename: "test_name.js", conflictAction: 'overwrite', saveAs: true });
         sendResponse({text:'Download started!'});
      }
   }
);

// Send messsage to active tab (content.js)
var sendMessageToTester = (contextData) => {
   chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      chrome.tabs.sendMessage(tabs[0].id, { verify: true, data: contextData }, function () { });
   });
}

// Context menu click handler
chrome.contextMenus.onClicked.addListener(sendMessageToTester);

// Context menu parent
chrome.contextMenus.create({
   "title": "Copycat - Testing Extension",
   "id": "parent",
   "contexts": ["all", "link"]
});

// Context menu verify-text
chrome.contextMenus.create({
   "id": "verify-text",
   "parentId": "parent",
   "title": "Verify Text",
   "contexts": ["selection"]
});

// Context menu verify-link
chrome.contextMenus.create({
   "id": "verify-link",
   "parentId": "parent",
   "title": "Verify Link",
   "contexts": ["link"]
});


// Context menu verify-dom
chrome.contextMenus.create({
   "id": "verify-dom",
   "parentId": "parent",
   "title": "Verify DOM Element",
   "contexts": ["all"]
});


================================================
FILE: public/index.html
================================================
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <!--
      manifest.json provides metadata used when your web app is added to the
      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>


================================================
FILE: public/manifest.json
================================================
{
  "short_name": "Create a test code without writing a line of code.",
  "name": "Copycat - Testing Extension",
  "version": "1.0.5",
  "manifest_version": 2,
  "icons": {
    "32": "icon32.png",
    "64": "icon64.png",
    "128": "icon128.png",
    "256": "icon256.png",
    "512": "icon512.png",
    "1024": "icon1024.png"
  },
  "background": {
    "scripts": [
      "app/background.js"
    ]
  },
  "permissions": [
    "contextMenus",
    "storage",
    "declarativeContent",
    "activeTab",
    "tabs",
    "contextMenus",
    "downloads"
  ],
  "browser_action": {},
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "css": [
        "/static/css/app.css"
      ],
      "js": [
        "/static/js/content.js"
      ]
    }
  ],
  "web_accessible_resources": [
    "/static/css/content.css"
  ],
  "content_security_policy": "script-src 'self' 'sha256-GgRxrVOKNdB4LrRsVPDSbzvfdV4UqglmviH9GoBJ5jk='; object-src 'self'"
}

================================================
FILE: scripts/build.js
================================================
'use strict';

// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';

// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
  throw err;
});

// Ensure environment variables are read.
require('../config/env');

const path = require('path');
const chalk = require('chalk');
const fs = require('fs-extra');
const webpack = require('webpack');
const config = require('../config/webpack.config.prod');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
const printBuildError = require('react-dev-utils/printBuildError');

const measureFileSizesBeforeBuild =
  FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
const useYarn = fs.existsSync(paths.yarnLockFile);

// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;

// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
  process.exit(1);
}

// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
measureFileSizesBeforeBuild(paths.appBuild)
  .then(previousFileSizes => {
    // Remove all content but keep the directory so that
    // if you're in it, you don't end up in Trash
    fs.emptyDirSync(paths.appBuild);
    // Merge with the public folder
    copyPublicFolder();
    // Start the webpack build
    return build(previousFileSizes);
  })
  .then(
    ({ stats, previousFileSizes, warnings }) => {
      if (warnings.length) {
        console.log(chalk.yellow('Compiled with warnings.\n'));
        console.log(warnings.join('\n\n'));
        console.log(
          '\nSearch for the ' +
            chalk.underline(chalk.yellow('keywords')) +
            ' to learn more about each warning.'
        );
        console.log(
          'To ignore, add ' +
            chalk.cyan('// eslint-disable-next-line') +
            ' to the line before.\n'
        );
      } else {
        console.log(chalk.green('Compiled successfully.\n'));
      }

      console.log('File sizes after gzip:\n');
      printFileSizesAfterBuild(
        stats,
        previousFileSizes,
        paths.appBuild,
        WARN_AFTER_BUNDLE_GZIP_SIZE,
        WARN_AFTER_CHUNK_GZIP_SIZE
      );
      console.log();

      const appPackage = require(paths.appPackageJson);
      const publicUrl = paths.publicUrl;
      const publicPath = config.output.publicPath;
      const buildFolder = path.relative(process.cwd(), paths.appBuild);
      printHostingInstructions(
        appPackage,
        publicUrl,
        publicPath,
        buildFolder,
        useYarn
      );
    },
    err => {
      console.log(chalk.red('Failed to compile.\n'));
      printBuildError(err);
      process.exit(1);
    }
  );

// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
  console.log('Creating an optimized production build...');

  let compiler = webpack(config);
  return new Promise((resolve, reject) => {
    compiler.run((err, stats) => {
      if (err) {
        return reject(err);
      }
      const messages = formatWebpackMessages(stats.toJson({}, true));
      if (messages.errors.length) {
        // Only keep the first error. Others are often indicative
        // of the same problem, but confuse the reader with noise.
        if (messages.errors.length > 1) {
          messages.errors.length = 1;
        }
        return reject(new Error(messages.errors.join('\n\n')));
      }
      if (
        process.env.CI &&
        (typeof process.env.CI !== 'string' ||
          process.env.CI.toLowerCase() !== 'false') &&
        messages.warnings.length
      ) {
        console.log(
          chalk.yellow(
            '\nTreating warnings as errors because process.env.CI = true.\n' +
              'Most CI servers set it automatically.\n'
          )
        );
        return reject(new Error(messages.warnings.join('\n\n')));
      }
      return resolve({
        stats,
        previousFileSizes,
        warnings: messages.warnings,
      });
    });
  });
}

function copyPublicFolder() {
  fs.copySync(paths.appPublic, paths.appBuild, {
    dereference: true,
    filter: file => file !== paths.appHtml,
  });
}


================================================
FILE: scripts/start.js
================================================
'use strict';

// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';

// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
  throw err;
});

// Ensure environment variables are read.
require('../config/env');

const fs = require('fs');
const chalk = require('chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const {
  choosePort,
  createCompiler,
  prepareProxy,
  prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const paths = require('../config/paths');
const config = require('../config/webpack.config.dev');
const createDevServerConfig = require('../config/webpackDevServer.config');

const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;

// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
  process.exit(1);
}

// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';

if (process.env.HOST) {
  console.log(
    chalk.cyan(
      `Attempting to bind to HOST environment variable: ${chalk.yellow(
        chalk.bold(process.env.HOST)
      )}`
    )
  );
  console.log(
    `If this was unintentional, check that you haven't mistakenly set it in your shell.`
  );
  console.log(`Learn more here: ${chalk.yellow('http://bit.ly/2mwWSwH')}`);
  console.log();
}

// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
choosePort(HOST, DEFAULT_PORT)
  .then(port => {
    if (port == null) {
      // We have not found a port.
      return;
    }
    const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
    const appName = require(paths.appPackageJson).name;
    const urls = prepareUrls(protocol, HOST, port);
    // Create a webpack compiler that is configured with custom messages.
    const compiler = createCompiler(webpack, config, appName, urls, useYarn);
    // Load proxy config
    const proxySetting = require(paths.appPackageJson).proxy;
    const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
    // Serve webpack assets generated by the compiler over a web sever.
    const serverConfig = createDevServerConfig(
      proxyConfig,
      urls.lanUrlForConfig
    );
    const devServer = new WebpackDevServer(compiler, serverConfig);
    // Launch WebpackDevServer.
    devServer.listen(port, HOST, err => {
      if (err) {
        return console.log(err);
      }
      if (isInteractive) {
        clearConsole();
      }
      console.log(chalk.cyan('Starting the development server...\n'));
      openBrowser(urls.localUrlForBrowser);
    });

    ['SIGINT', 'SIGTERM'].forEach(function(sig) {
      process.on(sig, function() {
        devServer.close();
        process.exit();
      });
    });
  })
  .catch(err => {
    if (err && err.message) {
      console.log(err.message);
    }
    process.exit(1);
  });


================================================
FILE: scripts/test.js
================================================
'use strict';

// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'test';
process.env.NODE_ENV = 'test';
process.env.PUBLIC_URL = '';

// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
  throw err;
});

// Ensure environment variables are read.
require('../config/env');

const jest = require('jest');
let argv = process.argv.slice(2);

// Watch unless on CI or in coverage mode
if (!process.env.CI && argv.indexOf('--coverage') < 0) {
  argv.push('--watch');
}


jest.run(argv);


================================================
FILE: src/App.js
================================================
import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;


================================================
FILE: src/Commands.js
================================================
import React, { Component } from 'react'
import { eventColors } from './Constants';

export default class Commands extends Component {

  _commandsHandler() {
    var commands = [];
    for (var key in this.props.commands) {
      var event = this.props.commands[key];
      if (event) {
        commands.push(
          <div className="app-action" style={{
            backgroundColor: eventColors[event.type]
          }}>
            <div className="app-action-type">{event.type.toUpperCase()}</div>
            <div className="app-action-target">{event.selector}</div>
            {event.data && event.data.key ? <div className="app-action-info">{event.data.key}</div> : ''}
            {event.data && event.data.mousePos && event.data.mouseTarget ? <div className="app-action-info">{'(' + event.data.mousePos.x + ',' + event.data.mousePos.y + ') to (' + event.data.mouseTarget.x + ',' + event.data.mouseTarget.y + ')'}</div> : ''}
            <button
              id={key}
              className="app-action-remove"
              onClick={(e) => {
                this.props.remove(e.target.id);
              }}>x</button>
          </div>
        )
      }
    }

    return (

      <div>
        {commands.reverse()}
      </div>

    )

  }

  render() {

    return (

      <div className={"app-actions"}>
        {this._commandsHandler()}
      </div>

    )
  }
}


================================================
FILE: src/Constants.js
================================================
// Keys which are not characters
export const keyCommands = [
    "Enter",
    "Backspace",
    "Tab",
    "Meta",
    "Escape",
    "Alt",
    "Control",
    "Shift",
    "CapsLock"
];

// Keys which can be combined
export const combinationKeys = [
    "Meta",
    "Alt",
    "Control",
    "Shift"
];

// The events which will be recorded
export const captureEvents = [
    "keydown",
    "mousedown",
    "mouseup"
];

// Unique selector configuration
export const selectorOptions = {
    selectorTypes: [
        "ID",
        "Class",
        "Tag",
        "NthChild"
    ]
};

// Command box colors according to the action
export const eventColors = {
    "mousedown": "#fff0fe",
    "click": "#f0f4ff",
    "drag-and-drop": "#f0feff",
    "keydown": "#f2fff0",
    "combined-keydown": "#fffce4",
    "verify-text": "#ffebe7",
    "verify-link": "#fdeff9",
    "verify-dom": "#f1f1f1",
    "page-change": "rgba(144, 121, 212, 0.15)",
    "click-page-change": "#d7ffdc"
}

// Chrome.storage key
export const storageKey = "commands";

================================================
FILE: src/Generator.js
================================================
import { keyCommands } from './Constants';

class Generator {

    constructor() {
        this.code = "";
    }

    get rules() {
        return {
            beforeAll: [
                `await page.goto('${this.initURL}');`
            ]
        }
    }

    addRulesInner(rules) {
        rules.forEach(rule => {
            this.code += rule;
        });
    }

    addRules() {
        for (var key in this.rules) {
            var rules = this.rules[key];
            switch (key) {
                case 'beforeAll':
                    this.code += `beforeAll(async () => {`;
                    this.addRulesInner(rules);
                    this.code += `});`;
                    break;
                case 'afterAll':
                    this.code += `afterAll(async () => {`;
                    this.addRulesInner(rules);
                    this.code += `});`;
                    break;
                case 'beforeEach':
                    this.code += `beforeEach(async () => {`;
                    this.addRulesInner(rules);
                    this.code += `};`;
                    break;
            }
        }
    }

    addCommand(command) {
        if (command && command.type) {
            switch (command.type) {
                case 'click':
                    this.code += `await page.click('${command.selector}');`;
                    break;
                case 'keydown':
                    if (keyCommands.includes(command.data.key)) {
                        this.code += `await page.keyboard.press('${command.data.key}');`;
                    } else {
                        this.code += `await page.type('${command.selector}', '${command.data.key}');`
                    }
                    break;
                case 'verify-text':
                    this.code += `var textContent = await page.$$eval('${command.selector}', el => el[0].textContent);`;
                    this.code += `var finalTextContent = textContent.trim();`;
                    this.code += `expect(finalTextContent).toBe('${command.data.key}');`;
                    break;
                case 'verify-dom':
                    this.code += `var elCount = await page.$$eval('${command.selector}', el => el.length);`;
                    this.code += `expect(elCount).toBeGreaterThan(0);`;
                    break;
                case 'verify-link':
                    this.code += `var nodeLink = await page.$$eval('${command.selector}', el => el[0].href);`;
                    this.code += `expect(nodeLink).toBe('${command.data.key}');`;
                    break;
                case 'page-change':
                    this.code += `await page.waitForNavigation({ waitUntil: 'load' });`
                    break;
                case 'click-page-change':
                    this.code += `await Promise.all([`;
                    this.code += `page.click('${command.selector}'),`;
                    this.code += `page.waitForNavigation()]);`;
                    break;
                case 'combined-keydown':
                    command.data.commands.forEach(com => {
                        this.code += `await page.keyboard.down('${com}');`
                    });
                    this.code += `await page.keyboard.press('${command.data.key.slice(-1)}');`;
                    command.data.commands.forEach(com => {
                        this.code += `await page.keyboard.up('${com}');`
                    });
                    break;
                case 'drag-and-drop':
                    this.code += `await page.mouse.move(${command.data.mousePos.x},${command.data.mousePos.y});`;
                    this.code += `await page.mouse.down();`;
                    this.code += `await page.mouse.move(${command.data.mouseTarget.x},${command.data.mouseTarget.y});`;
                    this.code += `await page.mouse.up();`;
                    break;
            }
        }
    }

    addIt(description, commands) {
        this.code += `it('${description}', async () => {`;
        commands.forEach(command => {
            this.addCommand(command);
        });
        this.code += `}, 60000);`;
    }

    addDescription(description, commands) {
        this.code += `describe('${description}', () => {`;
        this.addRules();
        this.addIt('Test 1 - 1', commands);
        this.code += `});`;
    }


    generatePuppeteerCode(commands, initURL) {
        this.initURL = initURL;
        this.addDescription("Test 1", commands);
        return this.code;
    }
}

export default Generator;

================================================
FILE: src/content.js
================================================
/*global chrome*/
/* src/content.js */
import React from 'react';
import ReactDOM from 'react-dom';
import unique from 'unique-selector';
import beautify from 'js-beautify';

import { keyCommands, captureEvents, selectorOptions, storageKey, combinationKeys } from './Constants';
import Generator from './Generator';
import Commands from './Commands';

const app = document.createElement('div');
app.id = "testing-extension";

class Main extends React.Component {

  constructor(props) {
    // Inheritance
    super(props);

    // Method bindings
    this.verify = this.verify.bind(this);
    this.prepareToAddStorage = this.prepareToAddStorage.bind(this);

    // Initial state definition
    this.state = {
      step: 1,
      paused: false,
      copied: false,
    };

    // Message listener for "verify-*" events
    chrome.runtime.onMessage.addListener(
      (request, sender, sendResponse) => {
        if (request.verify) {
          this.verify(request.data)
        }
      }
    );
  }

  componentDidMount = () => {
    // Extension toggle handler
    chrome.storage.sync.get(['toggle', 'paused'], function (res) {
      app.style.display = res.toggle;
      if (res.toggle === 'block') {
        document.body.className += " toggle";
      } else {
        document.body.className = document.body.className.replace("toggle", "").trim();
      }
    });

    // Extension "puased" state updater
    let self = this;
    chrome.storage.sync.get('paused', function (res) {
      self.setState({
        paused: res.paused
      })
    });

    // Extension "recording" state handler
    chrome.storage.sync.get('recording', function (res) {
      switch (res.recording) {
        case 1:
          self.resetHandler();
          break;
        case 2:
          if (self.state.paused) {
            self.pauseHandler();
          } else {
            self.recordHandler();
          }
          break;
        case 3:
          self.stopHandler();
          break;
        default:
          self.resetHandler();
          break;
      }
    });

    // STORAGE (HISTORY)
    chrome.storage.sync.get([storageKey], function (result) {
      var storeArray = result[storageKey] ? result[storageKey] : [];
      self.setState({ storeArray });
    });
  }

  // Sends message to background.js
  sendMessageToBackground = (msg) => {
    chrome.runtime.sendMessage({ downloadContent: msg }, function (response) {
      return;
    });
  }

  // Handling "verify-*" actions
  verify(data) {
    let selection = document.getSelection();
    let node = selection.baseNode.parentNode;
    let newEntry;
    switch (data.menuItemId) {
      case "verify-text":
        newEntry = {
          type: data.menuItemId,
          selector: unique(node, selectorOptions),
          data: {
            key: selection.baseNode.textContent
          }
        };
        break;
      case "verify-dom":
        newEntry = {
          type: data.menuItemId,
          selector: unique(node, selectorOptions),
          data: ""
        };
        break;
      case "verify-link":
        newEntry = {
          type: data.menuItemId,
          selector: unique(node, selectorOptions),
          data: {
            key: data.linkUrl
          }
        };
        break;
      default:
        // if the action is "verify" but not defined, it logs to the console WTF!
        console.log("WTF!")
        return;
    }
    this.addToStorage(newEntry);
  }

  // Is "#element" is in "el"
  isRecursivelyInId(el, id) {
    if (el.id === id) return true;

    while (el.parentNode) {
      el = el.parentNode;
      if (el.id === id) {
        return true;
      }
    }
    return false;
  }

  // .length  without nulls
  calculateStoreLengthWithoutNulls = () => {
    let l = 0;
    this.state.storeArray.forEach(element => {
      if (element) {
        l++;
      }
    });
    return l;
  }

  // Distance of 2 coordinates
  distance = (a, b) => {
    return Math.sqrt(Math.pow((a.x - b.x), 2) + Math.pow((a.y - b.y), 2))
  }

  // Adding prepared actions to state and store
  addToStorage = (entry) => {
    let self = this;
    chrome.storage.sync.get(storageKey, function (result) {
      var storeArray = result[storageKey] ? result[storageKey] : {};
      let id = Object.keys(storeArray).length

      let keyCheckObject = storeArray[id - 1];

      if (keyCheckObject) {

        switch (keyCheckObject.type) {

          case 'mousedown':

            if (entry.type === 'mouseup') {
              let r = self.distance(entry.data.mousePos, keyCheckObject.data.mousePos);
              if (r > 10) {
                keyCheckObject.type = 'drag-and-drop'
                keyCheckObject.data.mouseTarget = { x: entry.data.mousePos.x, y: entry.data.mousePos.y };
              } else {
                keyCheckObject.type = 'click';
              }
            }
            else if (entry.type === 'page-change') {
              keyCheckObject.type = 'click-page-change';
            }
            else if (entry.type === 'mousedown') {
              keyCheckObject.type = 'click';
              storeArray[id + 1] = entry;
            }
            else {
              keyCheckObject.type = entry.type;
              keyCheckObject.data = entry.data;
              keyCheckObject.selector = entry.selector;
            }
            break;

          case 'mouseup':

            storeArray[id] = entry;
            storeArray[id].type = 'click';
            break;

          case 'click':

            if (entry.type === 'page-change') {
              keyCheckObject.type = 'click-page-change';
            } else if (entry.type === 'mouseup') {
              storeArray[id] = entry;
              storeArray[id].type = 'click';
            } else {
              storeArray[id] = entry;
            }
            break;

          case 'keydown':

            if (!keyCommands.includes(keyCheckObject.data.key) && keyCheckObject.selector === entry.selector && !keyCommands.includes(entry.data.key)) {
              keyCheckObject.data.key += entry.data.key;
            } else if (combinationKeys.includes(keyCheckObject.data.key) && keyCheckObject.selector === entry.selector && entry.data.commands && !combinationKeys.includes(entry.data.key)) {
              entry.data.commands.forEach(command => {
                keyCheckObject.type = 'combined-keydown';
                keyCheckObject.data.key += '+' + entry.data.key.toUpperCase();
              });
            } else if (entry.type === 'mouseup') {
              storeArray[id] = entry;
              storeArray[id].type = 'click';
            } else {
              storeArray[id] = entry;
            }
            break;

          default:

            storeArray[id] = entry;
            break;
        }
      } else {

        storeArray[id] = entry;
      }

      var jsonObj = {};

      if (id === 0) {
        jsonObj['initURL'] = document.URL;
      }
      jsonObj[storageKey] = storeArray;

      // update the state
      self.setState({ storeArray });

      // update the store
      chrome.storage.sync.set(jsonObj, function () {
        return
      });
    });
  }

  // Prepare actions before adding them to state and store
  prepareToAddStorage(e) {
    if (!this.isRecursivelyInId(e.target, 'testing-extension')) {
      let commands = [];
      if (e.ctrlKey) commands.push('Ctrl');
      if (e.metaKey) commands.push('Meta');
      if (e.altKey) commands.push('Alt');
      if (e.shiftKey) commands.push('Shift');

      let code = e.key ? e.key : ''
      let mousePos = e.pageX ? { x: e.pageX, y: e.pageY } : ''
      let selector = unique(e.target, selectorOptions);

      let newEntry = {
        type: e.type,
        selector: selector,
        data: {
          key: code,
          mousePos,
          commands
        }
      };

      setTimeout(() => {
        this.addToStorage(newEntry);
      }, 100);
    }

  }

  // Remove specific action from state and store
  remove = (id) => {
    let self = this;
    chrome.storage.sync.get(storageKey, function (result) {
      var storeArray = result[storageKey] ? result[storageKey] : {};

      delete storeArray[id];

      var jsonObj = {};
      jsonObj[storageKey] = storeArray;

      // uptade the state
      self.setState({ storeArray })

      chrome.storage.sync.set(jsonObj, function () {
        return;
      });
    });
  }

  // Start recording
  record = () => {
    captureEvents.forEach(event => {
      window.addEventListener(event, this.prepareToAddStorage)
    });

    // Special case "page-change" event handler
    window.onbeforeunload = (e) => {
      let newEntry = {
        type: 'page-change',
        selector: undefined,
        data: undefined
      };
      setTimeout(() => this.addToStorage(newEntry), 105);
      // this.addToStorage(newEntry);
    }
    this.setState({ paused: false });
  }

  // Stop recording
  stop = () => {
    window.onbeforeunload = null;
    captureEvents.forEach(event => {
      window.removeEventListener(event, this.prepareToAddStorage)
    });
  }

  // Reset state and the store
  reset = () => {
    this.setState({ storeArray: [], copied: false }, () => {
      var jsonObj = {};
      jsonObj[storageKey] = [];
      chrome.storage.sync.set(jsonObj, function () {
        return;
      });
    })
  }

  // Map actions to jest-puppeteer code and call download prompt method (in background.js)
  save = () => {
    let initURL = '';
    chrome.storage.sync.get('initURL', (res) => {
      initURL = res.initURL;
    })
    let self = this;
    chrome.storage.sync.get([storageKey], function (result) {
      var storeArray = result[storageKey] ? result[storageKey] : [];
      var gen = new Generator();
      let code = gen.generatePuppeteerCode(storeArray, initURL);
      let beautifiedCode = beautify(code, { indent_size: 2, space_in_empty_paren: true });
      self.sendMessageToBackground(beautifiedCode);
    });
  }

  copy = () => {
    let initURL = '';
    chrome.storage.sync.get('initURL', (res) => {
      initURL = res.initURL;
    })
    let self = this;
    chrome.storage.sync.get([storageKey], function (result) {
      var storeArray = result[storageKey] ? result[storageKey] : [];
      var gen = new Generator();
      let code = gen.generatePuppeteerCode(storeArray, initURL);
      let beautifiedCode = beautify(code, { indent_size: 2, space_in_empty_paren: true });

      const tempInput = document.createElement("textarea");
      tempInput.value = beautifiedCode;
      document.body.appendChild(tempInput);
      tempInput.select();
      document.execCommand("copy");
      document.body.removeChild(tempInput);

      self.setState({ copied: true })
    });
  }

  // Record button handler
  recordHandler = () => {
    this.record();
    this.storeRecordingState(2);
  }

  // Stop button handler
  stopHandler = () => {
    this.stop();
    this.storeRecordingState(3);
  }

  // Resume button handler
  resumeHandler = () => {
    this.record();
    this.storePausedState(false);
    this.storeRecordingState(2);
  }

  // Pause button handler
  pauseHandler = () => {
    this.stop();
    this.storePausedState(true);
    this.storeRecordingState(2);
  }

  // Reset button handler
  resetHandler = () => {
    this.reset();
    this.storeRecordingState(1);
  }

  // Save recording state
  storeRecordingState = (recordingState) => {
    let self = this;
    chrome.storage.sync.set({ recording: recordingState }, () => {
      self.setState({ step: recordingState });
    })
  }

  // Save recording state
  storePausedState = (paused) => {
    let self = this;
    chrome.storage.sync.set({ paused }, () => {
      self.setState({ paused });
    })
  }

  // Render the DOM
  render() {
    return (
      <div className={'my-extension'}>
        <div className={`app app-step-${this.state.step}`}>
          <div className="app-controls">
            <div className="app-action-step-1">
              <h3 className="app-title">Not Recording</h3>
              <div className="app-buttons">
                <button onClick={this.recordHandler} className="app-record-button">Record</button>
              </div>
              <h6 className="app-subtitle pulse">Click "Record" to start recording...</h6>
            </div>
            <div className="app-action-step-2">
              <h3 className="app-subtitle">{this.state.paused ? 'Paused' : <span className="app-subtitle-recording">Recording</span>}</h3>
              <h2 className="app-title">{this.state.storeArray ? this.calculateStoreLengthWithoutNulls() : 0} Actions</h2>
              <div className="app-buttons">
                {this.state.paused ?
                  <button onClick={this.resumeHandler} className="app-ghost-button for-resume">
                    Resume
                  </button>
                  :
                  <button onClick={this.pauseHandler} className="app-ghost-button for-pause">
                    Pause
                  </button>
                }
                <button onClick={this.stopHandler} className="app-ghost-button for-stop">
                  Stop
                </button>
              </div>
            </div>
            <div className="app-action-step-3">
              <h3 className="app-subtitle">Done!</h3>
              <h2 className="app-title">{this.state.storeArray ? this.calculateStoreLengthWithoutNulls() : 0} Actions</h2>
              <div className="app-buttons">
                <button onClick={this.resetHandler} className="app-ghost-button for-reset">
                  Reset
                </button>
                <button onClick={this.save} className="app-ghost-button for-save">
                  Save
                </button>
                <button onClick={this.copy} className="app-ghost-button for-copy">
                  {this.state.copied ? 'Copied!' : 'Copy'}
                </button>
              </div>
            </div>
          </div>
          {this.state.storeArray ? <Commands remove={this.remove} btnClickHndlr={this.buttonClickHandler} commands={this.state.storeArray} /> : ''}
        </div>
      </div>
    )
  }
}

// Add extension to the page
document.body.appendChild(app);
ReactDOM.render(<Main />, app);

// Toggle listener (Extension icon click handler)
chrome.runtime.onMessage.addListener(
  function (request, sender, sendResponse) {
    if (request.message === "clicked_browser_action") {
      toggle();
    }
  }
);

// Toggle handler 
function toggle() {
  if (app.style.display === "none") {
    chrome.storage.sync.set({ toggle: 'block' }, function () {

      app.style.display = "block";
      document.body.className += " toggle";
    });
  } else {
    chrome.storage.sync.set({ toggle: 'none' }, function () {

      app.style.display = "none";
      document.body.className = document.body.className.replace("toggle", "").trim();
    });
  }
}

================================================
FILE: src/index.js
================================================
import React from 'react';
import ReactDOM from 'react-dom';
import './style.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();


================================================
FILE: src/registerServiceWorker.js
================================================
// In production, we register a service worker to serve assets from local cache.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.

// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.

const isLocalhost = Boolean(
  window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.1/8 is considered localhost for IPv4.
    window.location.hostname.match(
      /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

export default function register() {
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
    // The URL constructor is available in all browsers that support SW.
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
    if (publicUrl.origin !== window.location.origin) {
      // Our service worker won't work if PUBLIC_URL is on a different origin
      // from what our page is served on. This might happen if a CDN is used to
      // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
      return;
    }

    window.addEventListener('load', () => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

      if (isLocalhost) {
        // This is running on localhost. Lets check if a service worker still exists or not.
        checkValidServiceWorker(swUrl);

        // Add some additional logging to localhost, pointing developers to the
        // service worker/PWA documentation.
        navigator.serviceWorker.ready.then(() => {
          console.log(
            'This web app is being served cache-first by a service ' +
              'worker. To learn more, visit https://goo.gl/SC7cgQ'
          );
        });
      } else {
        // Is not local host. Just register service worker
        registerValidSW(swUrl);
      }
    });
  }
}

function registerValidSW(swUrl) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              // At this point, the old content will have been purged and
              // the fresh content will have been added to the cache.
              // It's the perfect time to display a "New content is
              // available; please refresh." message in your web app.
              console.log('New content is available; please refresh.');
            } else {
              // At this point, everything has been precached.
              // It's the perfect time to display a
              // "Content is cached for offline use." message.
              console.log('Content is cached for offline use.');
            }
          }
        };
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:', error);
    });
}

function checkValidServiceWorker(swUrl) {
  // Check if the service worker can be found. If it can't reload the page.
  fetch(swUrl)
    .then(response => {
      // Ensure service worker exists, and that we really are getting a JS file.
      if (
        response.status === 404 ||
        response.headers.get('content-type').indexOf('javascript') === -1
      ) {
        // No service worker found. Probably a different app. Reload the page.
        navigator.serviceWorker.ready.then(registration => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        // Service worker found. Proceed as normal.
        registerValidSW(swUrl);
      }
    })
    .catch(() => {
      console.log(
        'No internet connection found. App is running in offline mode.'
      );
    });
}

export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then(registration => {
      registration.unregister();
    });
  }
}


================================================
FILE: src/style.css
================================================
@import url("https://fonts.googleapis.com/css?family=DM+Sans:400,500,700&display=swap");

.toggle {
  padding-right: 400px;
}

#testing-extension {
  position: fixed;
  top: 0;
  right: 0;
  width: 400px;
  background-color: #fff;
  z-index: 999999999 !important;
  border-left: 1px solid #ddd;
  box-shadow: -4px 10px 10px rgba(0, 0, 0, 0.2);
  height: 100vh;
}

#testing-extension .app {
  width: 400px;
  height: 100vh;
  padding: 20px;
  box-sizing: border-box;
}

#testing-extension .app * {
  all: unset;
  box-sizing: border-box;
  font-family: "DM Sans", sans-serif;
  line-height: 1;
}

#testing-extension .app-controls {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  flex-direction: column;
  transition: 0.3s;
}

#testing-extension .app-controls>* {
  width: 100%;
}

#testing-extension .app-title {
  font-size: 24px;
  display: block;
  text-align: center;
  font-weight: 500;
  margin-bottom: 16px;
}

#testing-extension .app-record-button {
  padding: 10px 10px 10px 30px;
  align-self: center;
  color: #fff;
  background-color: #07b94b;
  cursor: pointer;
  border-radius: 4px;
  position: relative;
}

#testing-extension .app-record-button:before {
  content: "";
  position: absolute;
  left: 10px;
  top: 50%;
  -webkit-transform: translateY(-50%);
  transform: translateY(-50%);
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #fff;
}

#testing-extension .app-subtitle-recording {
  position: relative;
}

#testing-extension .app-subtitle-recording:before {
  content: "";
  position: absolute;
  left: -14px;
  top: 3px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: red;
  -webkit-animation-name: app-pulse;
  animation-name: app-pulse;
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-iteration-count: infinite;
  animation-iteration-count: infinite;
}

#testing-extension .app-actions {
  display: flex;
  flex-direction: column;
  overflow: auto;
  height: calc(100vh - 170px);
}

#testing-extension .app-action {
  display: flex;
  flex-direction: column;
  padding: 20px;
  border-radius: 4px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  background-color: #f4f4f4;
  position: relative;
  margin-bottom: 4px;
}

#testing-extension .app-action+#testing-extension .app-action {
  margin-top: 14px;
}

#testing-extension .app-action-type {
  align-self: flex-start;
  padding: 6px;
  background-color: rgba(0, 0, 0, 0.1);
  margin-bottom: 12px;
  font-weight: 500;
  font-size: 13px;
  letter-spacing: 2px;
  border-radius: 4px;
}

#testing-extension .app-action-target {
  font-family: monospace;
}

#testing-extension .app-action-info {
  font-size: 14px;
  line-height: 1.4;
  background-color: #fff;
  margin-top: 12px;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

#testing-extension .app-action-remove {
  position: absolute;
  top: 0;
  opacity: 0;
  visibility: hidden;
  transition: 0.3s;
  right: 0;
  width: 25px;
  height: 25px;
  cursor: pointer;
  border: 0;
  background: 0;
  padding: 0;
  background-repeat: no-repeat;
  background-size: 10px;
  border-radius: 0 0 0 6px;
  background-position: center;
  background-color: rgba(0, 0, 0, 0.1);
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 212.982 212.982'%3e%3cpath d='M131.804 106.491l75.936-75.936c6.99-6.99 6.99-18.323 0-25.312-6.99-6.99-18.322-6.99-25.312 0L106.491 81.18 30.554 5.242c-6.99-6.99-18.322-6.99-25.312 0-6.989 6.99-6.989 18.323 0 25.312l75.937 75.936-75.937 75.937c-6.989 6.99-6.989 18.323 0 25.312 6.99 6.99 18.322 6.99 25.312 0l75.937-75.937 75.937 75.937c6.989 6.99 18.322 6.99 25.312 0 6.99-6.99 6.99-18.322 0-25.312l-75.936-75.936z' fill-rule='evenodd' clip-rule='evenodd'/%3e%3c/svg%3e");
  color: transparent;
}

#testing-extension .app-action-remove:hover {
  background-color: rgba(0, 0, 0, 0.2);
}

#testing-extension .app-action:hover .app-action-remove {
  opacity: 1;
  visibility: visible;
}

#testing-extension .app-subtitle {
  margin-bottom: 6px;
  color: rgba(0, 0, 0, 0.5);
  font-size: 15px;
  text-align: center;
  display: block;
  width: 100%;
}

#testing-extension .app-buttons {
  display: flex;
  justify-content: center;
  text-align: center;
  margin-bottom: 20px;
}

#testing-extension .app-ghost-button {
  margin: 0 5px;
  display: inline-block;
  border-radius: 4px;
  padding: 10px 10px 10px 30px;
  background-position: left;
  color: #fff;
  cursor: pointer;
  background-size: 14px;
  background-repeat: no-repeat;
  background-position: 10px 50%;
}

#testing-extension .app-ghost-button.for-pause {
  background-color: orange;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg fill='white' xmlns='http://www.w3.org/2000/svg' width='45.975' height='45.975'%3e%3cpath d='M13.987 0a5 5 0 0 0-5 5v35.975c0 2.763 2.238 5 5 5s5-2.238 5-5V5c0-2.762-2.237-5-5-5zM31.987 0a5 5 0 0 0-5 5v35.975c0 2.762 2.238 5 5 5s5-2.238 5-5V5a5 5 0 0 0-5-5z'/%3e%3c/svg%3e");
}

#testing-extension .app-ghost-button.for-resume {
  background-color: #07b94b;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath d='M 8 5.5 C 7.172 5.5 6.5 6.172 6.5 7 L 6.5 22 C 6.5 22.828 7.172 23.5 8 23.5 C 8.828 23.5 9.5 22.828 9.5 22 L 9.5 7 C 9.5 6.172 8.828 5.5 8 5.5 z M 13.5 5.5 A 1 1 0 0 0 12.5 6.5 A 1 1 0 0 0 12.5 6.5039062 L 12.5 14.5 L 12.5 22.496094 A 1 1 0 0 0 12.5 22.5 A 1 1 0 0 0 13.5 23.5 A 1 1 0 0 0 14.091797 23.304688 L 14.09375 23.304688 A 1 1 0 0 0 14.121094 23.283203 L 25.041016 15.341797 A 1 1 0 0 0 25.5 14.5 A 1 1 0 0 0 25.056641 13.669922 L 14.09375 5.6953125 A 1 1 0 0 0 13.5 5.5 z' fill='%23fff'%3e%3c/path%3e%3c/svg%3e");
}

#testing-extension .app-ghost-button.for-stop {
  background-color: #d40000;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 491.858 491.858'%3e%3cpath d='M491.858 475.862c0 8.833-7.162 15.996-15.996 15.996H15.996C7.16 491.858 0 484.696 0 475.862V15.996C0 7.16 7.16 0 15.996 0h459.866c8.834 0 15.996 7.16 15.996 15.996v459.866z' fill='white'/%3e%3c/svg%3e");
  background-size: 10px;
}

#testing-extension .app-ghost-button.for-reset {
  background-color: #d40000;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' fill='white' version='1' width='439' height='439'%3e%3cpath d='M427 20c-7-4-14-2-20 4l-37 37a222 222 0 0 0-236-44A221 221 0 0 0 17 134a213 213 0 0 0 0 170 221 221 0 0 0 117 117 213 213 0 0 0 179-3c29-14 54-33 75-59 2-1 2-4 2-6l-3-6-39-39c-2-2-4-3-7-3-3 1-5 2-6 4a143 143 0 0 1-116 56A147 147 0 0 1 73 219 147 147 0 0 1 219 73c39 0 72 13 100 39l-39 40c-6 5-8 12-4 19 3 8 8 12 16 12h128c5 0 10-2 13-6 4-3 6-8 6-13V37c0-8-4-14-12-17z'/%3e%3c/svg%3e");
}

#testing-extension .app-ghost-button.for-save {
  background-color: #07b94b;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' height='683' viewBox='0 0 512 512' width='683'%3e%3cpath d='M410 279L256 432 102 279l28-29 106 106V0h40v356l106-106zm102 193H0v40h512zm0 0' fill='%23fff'/%3e%3c/svg%3e");
}

#testing-extension .app-ghost-button.for-copy {
  background-color: #007bff;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' height='683' viewBox='0 0 512 512' width='683'%3e%3cpath d='M433.941 65.941l-51.882-51.882A48 48 0 0 0 348.118 0H176c-26.51 0-48 21.49-48 48v48H48c-26.51 0-48 21.49-48 48v320c0 26.51 21.49 48 48 48h224c26.51 0 48-21.49 48-48v-48h80c26.51 0 48-21.49 48-48V99.882a48 48 0 0 0-14.059-33.941zM266 464H54a6 6 0 0 1-6-6V150a6 6 0 0 1 6-6h74v224c0 26.51 21.49 48 48 48h96v42a6 6 0 0 1-6 6zm128-96H182a6 6 0 0 1-6-6V54a6 6 0 0 1 6-6h106v88c0 13.255 10.745 24 24 24h88v202a6 6 0 0 1-6 6zm6-256h-64V48h9.632c1.591 0 3.117.632 4.243 1.757l48.368 48.368a6 6 0 0 1 1.757 4.243V112z' fill='%23fff'/%3e%3c/svg%3e");
}

#testing-extension .app.app-step-1 {
  overflow: hidden;
}

#testing-extension .app.app-step-1 .app-controls {
  height: 100%;
  transition: 0.3s;
}

#testing-extension .app.app-step-1 .app-actions {
  display: none;
}

#testing-extension .app.app-step-1 .app-action-step-2,
#testing-extension .app.app-step-1 .app-action-step-3 {
  height: 0;
  overflow: hidden;
  opacity: 0;
  visibility: hidden;
}

#testing-extension .app.app-step-2 .app-controls {
  height: 150px;
}

#testing-extension .app.app-step-2 .app-action-step-2 {
  visibility: visible;
  opacity: 1;
}

#testing-extension .app.app-step-2 .app-action-step-1,
#testing-extension .app.app-step-2 .app-action-step-3 {
  height: 0;
  overflow: hidden;
  opacity: 0;
  visibility: hidden;
}

#testing-extension .app.app-step-3 .app-controls {
  height: 150px;
}

#testing-extension .app.app-step-3 .app-action-step-3 {
  visibility: visible;
  opacity: 1;
}

#testing-extension .app.app-step-3 .app-action-step-2,
#testing-extension .app.app-step-3 .app-action-step-1 {
  height: 0;
  overflow: hidden;
  opacity: 0;
  visibility: hidden;
}

#testing-extension .pulse {
  -webkit-animation-name: app-pulse;
  animation-name: app-pulse;
  -webkit-animation-duration: 1.6s;
  animation-duration: 1.6s;
  -webkit-animation-iteration-count: infinite;
  animation-iteration-count: infinite;
}

@-webkit-keyframes app-pulse {
  50% {
    opacity: 0.1;
  }
}

@keyframes app-pulse {
  50% {
    opacity: 0.1;
  }
}
Download .txt
gitextract_qjula_wf/

├── .gitignore
├── LICENSE
├── README.md
├── config/
│   ├── env.js
│   ├── jest/
│   │   ├── cssTransform.js
│   │   └── fileTransform.js
│   ├── paths.js
│   ├── polyfills.js
│   ├── webpack.config.dev.js
│   ├── webpack.config.prod.js
│   └── webpackDevServer.config.js
├── package.json
├── public/
│   ├── app/
│   │   └── background.js
│   ├── index.html
│   └── manifest.json
├── scripts/
│   ├── build.js
│   ├── start.js
│   └── test.js
└── src/
    ├── App.js
    ├── Commands.js
    ├── Constants.js
    ├── Generator.js
    ├── content.js
    ├── index.js
    ├── registerServiceWorker.js
    └── style.css
Download .txt
SYMBOL INDEX (41 symbols across 13 files)

FILE: config/env.js
  constant NODE_ENV (line 10) | const NODE_ENV = process.env.NODE_ENV;
  constant REACT_APP (line 61) | const REACT_APP = /^REACT_APP_/i;
  function getClientEnvironment (line 63) | function getClientEnvironment(publicUrl) {

FILE: config/jest/cssTransform.js
  method process (line 7) | process() {
  method getCacheKey (line 10) | getCacheKey() {

FILE: config/jest/fileTransform.js
  method process (line 9) | process(src, filename) {

FILE: config/paths.js
  function ensureSlash (line 14) | function ensureSlash(path, needsSlash) {
  function getServedPath (line 34) | function getServedPath(appPackageJson) {

FILE: config/webpack.config.prod.js
  method logger (line 308) | logger(message) {

FILE: config/webpackDevServer.config.js
  method before (line 84) | before(app) {

FILE: scripts/build.js
  constant WARN_AFTER_BUNDLE_GZIP_SIZE (line 35) | const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
  constant WARN_AFTER_CHUNK_GZIP_SIZE (line 36) | const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
  function build (line 104) | function build(previousFileSizes) {
  function copyPublicFolder (line 145) | function copyPublicFolder() {

FILE: scripts/start.js
  constant DEFAULT_PORT (line 43) | const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
  constant HOST (line 44) | const HOST = process.env.HOST || '0.0.0.0';

FILE: src/App.js
  class App (line 3) | class App extends Component {
    method render (line 4) | render() {

FILE: src/Commands.js
  class Commands (line 4) | class Commands extends Component {
    method _commandsHandler (line 6) | _commandsHandler() {
    method render (line 40) | render() {

FILE: src/Generator.js
  class Generator (line 3) | class Generator {
    method constructor (line 5) | constructor() {
    method rules (line 9) | get rules() {
    method addRulesInner (line 17) | addRulesInner(rules) {
    method addRules (line 23) | addRules() {
    method addCommand (line 46) | addCommand(command) {
    method addIt (line 99) | addIt(description, commands) {
    method addDescription (line 107) | addDescription(description, commands) {
    method generatePuppeteerCode (line 115) | generatePuppeteerCode(commands, initURL) {

FILE: src/content.js
  class Main (line 15) | class Main extends React.Component {
    method constructor (line 17) | constructor(props) {
    method verify (line 98) | verify(data) {
    method isRecursivelyInId (line 137) | isRecursivelyInId(el, id) {
    method prepareToAddStorage (line 266) | prepareToAddStorage(e) {
    method render (line 441) | render() {
  function toggle (line 508) | function toggle() {

FILE: src/registerServiceWorker.js
  function register (line 21) | function register() {
  function registerValidSW (line 55) | function registerValidSW(swUrl) {
  function checkValidServiceWorker (line 84) | function checkValidServiceWorker(swUrl) {
  function unregister (line 111) | function unregister() {
Condensed preview — 26 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (106K chars).
[
  {
    "path": ".gitignore",
    "chars": 64,
    "preview": "build/\npackage-lock.json\nnode_modules/\n.idea/\n.vscode/\nyarn.lock"
  },
  {
    "path": "LICENSE",
    "chars": 1069,
    "preview": "MIT License\n\nCopyright (c) 2018 Satendra Rai\n\nPermission is hereby granted, free of charge, to any person obtaining a co"
  },
  {
    "path": "README.md",
    "chars": 6655,
    "preview": "[![Chrome Web Store](https://img.shields.io/chrome-web-store/v/dlbnejfbjfikckofdndbjndhhbplmnpj.svg?colorB=%234FC828&sty"
  },
  {
    "path": "config/env.js",
    "chars": 3505,
    "preview": "'use strict';\n\nconst fs = require('fs');\nconst path = require('path');\nconst paths = require('./paths');\n\n// Make sure t"
  },
  {
    "path": "config/jest/cssTransform.js",
    "chars": 314,
    "preview": "'use strict';\n\n// This is a custom Jest transformer turning style imports into empty objects.\n// http://facebook.github."
  },
  {
    "path": "config/jest/fileTransform.js",
    "chars": 305,
    "preview": "'use strict';\n\nconst path = require('path');\n\n// This is a custom Jest transformer turning file imports into filenames.\n"
  },
  {
    "path": "config/paths.js",
    "chars": 1975,
    "preview": "'use strict';\n\nconst path = require('path');\nconst fs = require('fs');\nconst url = require('url');\n\n// Make sure any sym"
  },
  {
    "path": "config/polyfills.js",
    "chars": 856,
    "preview": "'use strict';\n\nif (typeof Promise === 'undefined') {\n  // Rejection tracking prevents a common issue where React gets in"
  },
  {
    "path": "config/webpack.config.dev.js",
    "chars": 12349,
    "preview": "'use strict';\n\nconst autoprefixer = require('autoprefixer');\nconst path = require('path');\nconst webpack = require('webp"
  },
  {
    "path": "config/webpack.config.prod.js",
    "chars": 15471,
    "preview": "'use strict';\n\nconst autoprefixer = require('autoprefixer');\nconst path = require('path');\nconst webpack = require('webp"
  },
  {
    "path": "config/webpackDevServer.config.js",
    "chars": 5358,
    "preview": "'use strict';\n\nconst errorOverlayMiddleware = require('react-dev-utils/errorOverlayMiddleware');\nconst noopServiceWorker"
  },
  {
    "path": "package.json",
    "chars": 2591,
    "preview": "{\n  \"name\": \"copycat\",\n  \"version\": \"1.0.5\",\n  \"private\": false,\n  \"dependencies\": {\n    \"autoprefixer\": \"7.1.6\",\n    \"b"
  },
  {
    "path": "public/app/background.js",
    "chars": 2021,
    "preview": "'use strict';\n// Called when the user clicks on the browser action\nchrome.browserAction.onClicked.addListener(function ("
  },
  {
    "path": "public/index.html",
    "chars": 1590,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\">\n    <meta name=\"viewport\" content=\"width=device-wid"
  },
  {
    "path": "public/manifest.json",
    "chars": 964,
    "preview": "{\n  \"short_name\": \"Create a test code without writing a line of code.\",\n  \"name\": \"Copycat - Testing Extension\",\n  \"vers"
  },
  {
    "path": "scripts/build.js",
    "chars": 4915,
    "preview": "'use strict';\n\n// Do this as the first thing so that any code reading it knows the right env.\nprocess.env.BABEL_ENV = 'p"
  },
  {
    "path": "scripts/start.js",
    "chars": 3517,
    "preview": "'use strict';\n\n// Do this as the first thing so that any code reading it knows the right env.\nprocess.env.BABEL_ENV = 'd"
  },
  {
    "path": "scripts/test.js",
    "chars": 732,
    "preview": "'use strict';\n\n// Do this as the first thing so that any code reading it knows the right env.\nprocess.env.BABEL_ENV = 't"
  },
  {
    "path": "src/App.js",
    "chars": 412,
    "preview": "import React, { Component } from 'react';\n\nclass App extends Component {\n  render() {\n    return (\n      <div className="
  },
  {
    "path": "src/Commands.js",
    "chars": 1380,
    "preview": "import React, { Component } from 'react'\nimport { eventColors } from './Constants';\n\nexport default class Commands exten"
  },
  {
    "path": "src/Constants.js",
    "chars": 1038,
    "preview": "// Keys which are not characters\nexport const keyCommands = [\n    \"Enter\",\n    \"Backspace\",\n    \"Tab\",\n    \"Meta\",\n    \""
  },
  {
    "path": "src/Generator.js",
    "chars": 4559,
    "preview": "import { keyCommands } from './Constants';\n\nclass Generator {\n\n    constructor() {\n        this.code = \"\";\n    }\n\n    ge"
  },
  {
    "path": "src/content.js",
    "chars": 14898,
    "preview": "/*global chrome*/\n/* src/content.js */\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport unique from '"
  },
  {
    "path": "src/index.js",
    "chars": 254,
    "preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport './style.css';\nimport App from './App';\nimport regis"
  },
  {
    "path": "src/registerServiceWorker.js",
    "chars": 4384,
    "preview": "// In production, we register a service worker to serve assets from local cache.\n\n// This lets the app load faster on su"
  },
  {
    "path": "src/style.css",
    "chars": 9440,
    "preview": "@import url(\"https://fonts.googleapis.com/css?family=DM+Sans:400,500,700&display=swap\");\n\n.toggle {\n  padding-right: 400"
  }
]

About this extraction

This page contains the full source code of the omergulen/copycat GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 26 files (98.3 KB), approximately 25.4k tokens, and a symbol index with 41 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!