Repository: Netflix/pollyjs
Branch: master
Commit: d031861625f5
Files: 393
Total size: 1.1 MB
Directory structure:
gitextract_9hhv16l2/
├── .commitlintrc.js
├── .eslintignore
├── .eslintrc.js
├── .github/
│ ├── issue_template.md
│ └── pull_request_template.md
├── .gitignore
├── .husky/
│ ├── commit-msg
│ └── pre-commit
├── .mocharc.js
├── .prettierrc.js
├── .travis.yml
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── OSSMETADATA
├── README.md
├── docs/
│ ├── .nojekyll
│ ├── _coverpage.md
│ ├── _sidebar.md
│ ├── adapters/
│ │ ├── custom.md
│ │ ├── fetch.md
│ │ ├── node-http.md
│ │ ├── playwright.md
│ │ ├── puppeteer.md
│ │ └── xhr.md
│ ├── api.md
│ ├── assets/
│ │ └── styles.css
│ ├── cli/
│ │ ├── commands.md
│ │ └── overview.md
│ ├── configuration.md
│ ├── examples.md
│ ├── frameworks/
│ │ └── ember-cli.md
│ ├── index.html
│ ├── node-server/
│ │ ├── express-integrations.md
│ │ └── overview.md
│ ├── persisters/
│ │ ├── custom.md
│ │ ├── fs.md
│ │ ├── local-storage.md
│ │ └── rest.md
│ ├── quick-start.md
│ ├── server/
│ │ ├── api.md
│ │ ├── event.md
│ │ ├── events-and-middleware.md
│ │ ├── overview.md
│ │ ├── request.md
│ │ ├── response.md
│ │ └── route-handler.md
│ └── test-frameworks/
│ ├── jest-jasmine.md
│ ├── mocha.md
│ └── qunit.md
├── examples/
│ ├── .eslintrc.js
│ ├── client-server/
│ │ ├── index.html
│ │ ├── package.json
│ │ └── tests/
│ │ ├── events.test.js
│ │ ├── intercept.test.js
│ │ └── setup.js
│ ├── dummy-app/
│ │ ├── .eslintrc.js
│ │ ├── .gitignore
│ │ ├── README.md
│ │ ├── package.json
│ │ ├── public/
│ │ │ ├── index.html
│ │ │ └── manifest.json
│ │ └── src/
│ │ ├── App.js
│ │ ├── index.css
│ │ ├── index.js
│ │ ├── posts.js
│ │ ├── todos.js
│ │ └── users.js
│ ├── jest-node-fetch/
│ │ ├── .eslintrc.js
│ │ ├── __recordings__/
│ │ │ └── jest-node-fetch_1142061259/
│ │ │ ├── posts_1278140380/
│ │ │ │ └── should-return-post_148615714/
│ │ │ │ └── recording.har
│ │ │ └── users_1585235219/
│ │ │ └── should-return-user_4259424139/
│ │ │ └── recording.har
│ │ ├── __tests__/
│ │ │ └── index.test.js
│ │ ├── package.json
│ │ └── src/
│ │ ├── index.js
│ │ ├── posts.js
│ │ └── users.js
│ ├── jest-puppeteer/
│ │ ├── .eslintrc.js
│ │ ├── __recordings__/
│ │ │ └── jest-puppeteer_2726822272/
│ │ │ └── should-be-able-to-navigate-to-all-routes_1130491217/
│ │ │ └── recording.har
│ │ ├── __tests__/
│ │ │ └── dummy-app.test.js
│ │ ├── jest-puppeteer.config.js
│ │ ├── jest.config.js
│ │ └── package.json
│ ├── node-fetch/
│ │ ├── package.json
│ │ ├── recordings/
│ │ │ └── node-fetch_2851505768/
│ │ │ └── should-work_3457346403/
│ │ │ └── recording.har
│ │ └── tests/
│ │ └── node-fetch.test.js
│ ├── puppeteer/
│ │ ├── index.js
│ │ ├── package.json
│ │ └── recordings/
│ │ └── puppeteer_2155046665/
│ │ └── recording.har
│ ├── rest-persister/
│ │ ├── index.html
│ │ ├── package.json
│ │ ├── recordings/
│ │ │ └── REST-Persister_2289553200/
│ │ │ └── should-work_3457346403/
│ │ │ └── recording.har
│ │ └── tests/
│ │ ├── rest-persister.test.js
│ │ └── setup.js
│ └── typescript-jest-node-fetch/
│ ├── __recordings__/
│ │ └── github-api-client_2139812550/
│ │ └── getUser_1648904580/
│ │ └── recording.har
│ ├── jest.config.ts
│ ├── package.json
│ ├── src/
│ │ ├── github-api.test.ts
│ │ ├── github-api.ts
│ │ └── utils/
│ │ └── auto-setup-polly.ts
│ └── tsconfig.json
├── jest.config.js
├── lerna.json
├── package.json
├── packages/
│ └── @pollyjs/
│ ├── adapter/
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── package.json
│ │ ├── rollup.config.test.js
│ │ ├── src/
│ │ │ ├── index.js
│ │ │ └── utils/
│ │ │ ├── dehumanize-time.js
│ │ │ ├── is-expired.js
│ │ │ ├── normalize-recorded-response.js
│ │ │ └── stringify-request.js
│ │ ├── tests/
│ │ │ └── unit/
│ │ │ ├── adapter-test.js
│ │ │ └── utils/
│ │ │ ├── dehumanize-time-test.js
│ │ │ └── is-expired-test.js
│ │ └── types.d.ts
│ ├── adapter-fetch/
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── package.json
│ │ ├── rollup.config.test.js
│ │ ├── src/
│ │ │ ├── index.js
│ │ │ └── utils/
│ │ │ └── serializer-headers.js
│ │ ├── tests/
│ │ │ ├── integration/
│ │ │ │ ├── adapter-test.js
│ │ │ │ ├── persister-local-storage-test.js
│ │ │ │ ├── persister-rest-test.js
│ │ │ │ └── server-test.js
│ │ │ └── utils/
│ │ │ └── polly-config.js
│ │ └── types.d.ts
│ ├── adapter-node-http/
│ │ ├── .eslintrc.js
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── package.json
│ │ ├── rollup.config.js
│ │ ├── rollup.config.shared.js
│ │ ├── rollup.config.test.js
│ │ ├── src/
│ │ │ ├── index.js
│ │ │ └── utils/
│ │ │ ├── get-url-from-options.js
│ │ │ ├── merge-chunks.js
│ │ │ └── url-to-options.js
│ │ ├── tests/
│ │ │ ├── integration/
│ │ │ │ ├── adapter-node-fetch-test.js
│ │ │ │ ├── adapter-test.js
│ │ │ │ └── persister-fs-test.js
│ │ │ ├── jest/
│ │ │ │ └── integration/
│ │ │ │ ├── fetch-test.js
│ │ │ │ └── xhr-test.js
│ │ │ ├── unit/
│ │ │ │ └── utils/
│ │ │ │ └── merge-chunks-test.js
│ │ │ └── utils/
│ │ │ ├── get-buffer-from-stream.js
│ │ │ ├── get-response-from-request.js
│ │ │ ├── native-request.js
│ │ │ └── polly-config.js
│ │ └── types.d.ts
│ ├── adapter-puppeteer/
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── package.json
│ │ ├── rollup.config.js
│ │ ├── rollup.config.test.js
│ │ ├── src/
│ │ │ └── index.js
│ │ ├── tests/
│ │ │ ├── helpers/
│ │ │ │ └── fetch.js
│ │ │ ├── integration/
│ │ │ │ └── adapter-test.js
│ │ │ └── unit/
│ │ │ └── adapter-test.js
│ │ └── types.d.ts
│ ├── adapter-xhr/
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── package.json
│ │ ├── rollup.config.test.js
│ │ ├── src/
│ │ │ ├── index.js
│ │ │ └── utils/
│ │ │ ├── resolve-xhr.js
│ │ │ └── serialize-response-headers.js
│ │ ├── tests/
│ │ │ ├── integration/
│ │ │ │ └── adapter-test.js
│ │ │ └── utils/
│ │ │ └── xhr-request.js
│ │ └── types.d.ts
│ ├── cli/
│ │ ├── .eslintrc.js
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── bin/
│ │ │ └── cli.js
│ │ └── package.json
│ ├── core/
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── package.json
│ │ ├── rollup.config.test.js
│ │ ├── src/
│ │ │ ├── -private/
│ │ │ │ ├── container.js
│ │ │ │ ├── event-emitter.js
│ │ │ │ ├── event.js
│ │ │ │ ├── http-base.js
│ │ │ │ ├── interceptor.js
│ │ │ │ ├── logger.js
│ │ │ │ ├── request.js
│ │ │ │ └── response.js
│ │ │ ├── defaults/
│ │ │ │ └── config.js
│ │ │ ├── index.js
│ │ │ ├── polly.js
│ │ │ ├── server/
│ │ │ │ ├── handler.js
│ │ │ │ ├── index.js
│ │ │ │ ├── middleware.js
│ │ │ │ └── route.js
│ │ │ ├── test-helpers/
│ │ │ │ ├── lib.js
│ │ │ │ ├── mocha.js
│ │ │ │ └── qunit.js
│ │ │ └── utils/
│ │ │ ├── cancel-fn-after-n-times.js
│ │ │ ├── deferred-promise.js
│ │ │ ├── guid-for-recording.js
│ │ │ ├── http-headers.js
│ │ │ ├── merge-configs.js
│ │ │ ├── normalize-request.js
│ │ │ ├── parse-url.js
│ │ │ ├── remove-host-from-url.js
│ │ │ ├── timing.js
│ │ │ └── validators.js
│ │ ├── tests/
│ │ │ └── unit/
│ │ │ ├── -private/
│ │ │ │ ├── container-test.js
│ │ │ │ ├── event-emitter-test.js
│ │ │ │ ├── event-test.js
│ │ │ │ ├── http-base-test.js
│ │ │ │ ├── interceptor-test.js
│ │ │ │ └── response-test.js
│ │ │ ├── index-test.js
│ │ │ ├── polly-test.js
│ │ │ ├── server/
│ │ │ │ ├── handler-test.js
│ │ │ │ └── server-test.js
│ │ │ ├── test-helpers/
│ │ │ │ └── mocha-test.js
│ │ │ └── utils/
│ │ │ ├── deferred-promise-test.js
│ │ │ ├── guid-for-recording-test.js
│ │ │ ├── http-headers-test.js
│ │ │ ├── merge-configs-test.js
│ │ │ ├── normalize-request-test.js
│ │ │ ├── parse-url-test.js
│ │ │ ├── remove-host-from-url-test.js
│ │ │ └── timing-test.js
│ │ └── types.d.ts
│ ├── ember/
│ │ ├── .editorconfig
│ │ ├── .ember-cli
│ │ ├── .eslintignore
│ │ ├── .eslintrc.js
│ │ ├── .gitignore
│ │ ├── .npmignore
│ │ ├── .prettierignore
│ │ ├── .prettierrc.js
│ │ ├── .template-lintrc.js
│ │ ├── .watchmanconfig
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── addon/
│ │ │ └── -private/
│ │ │ └── preconfigure.js
│ │ ├── blueprints/
│ │ │ └── @pollyjs/
│ │ │ └── ember/
│ │ │ ├── files/
│ │ │ │ └── config/
│ │ │ │ └── polly.js
│ │ │ └── index.js
│ │ ├── config/
│ │ │ ├── ember-try.js
│ │ │ ├── environment.js
│ │ │ └── polly.js
│ │ ├── ember-cli-build.js
│ │ ├── index.js
│ │ ├── package.json
│ │ ├── testem.js
│ │ ├── tests/
│ │ │ ├── dummy/
│ │ │ │ ├── app/
│ │ │ │ │ ├── app.js
│ │ │ │ │ ├── components/
│ │ │ │ │ │ └── .gitkeep
│ │ │ │ │ ├── controllers/
│ │ │ │ │ │ └── .gitkeep
│ │ │ │ │ ├── helpers/
│ │ │ │ │ │ └── .gitkeep
│ │ │ │ │ ├── index.html
│ │ │ │ │ ├── models/
│ │ │ │ │ │ └── .gitkeep
│ │ │ │ │ ├── router.js
│ │ │ │ │ ├── routes/
│ │ │ │ │ │ └── .gitkeep
│ │ │ │ │ ├── styles/
│ │ │ │ │ │ └── app.css
│ │ │ │ │ └── templates/
│ │ │ │ │ └── application.hbs
│ │ │ │ ├── config/
│ │ │ │ │ ├── ember-cli-update.json
│ │ │ │ │ ├── environment.js
│ │ │ │ │ ├── optional-features.json
│ │ │ │ │ └── targets.js
│ │ │ │ └── public/
│ │ │ │ └── robots.txt
│ │ │ ├── helpers/
│ │ │ │ └── .gitkeep
│ │ │ ├── index.html
│ │ │ ├── integration/
│ │ │ │ └── .gitkeep
│ │ │ ├── test-helper.js
│ │ │ └── unit/
│ │ │ └── polly-test.js
│ │ └── vendor/
│ │ └── .gitkeep
│ ├── node-server/
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── package.json
│ │ ├── rollup.config.js
│ │ ├── src/
│ │ │ ├── api.js
│ │ │ ├── config.js
│ │ │ ├── express/
│ │ │ │ └── register-api.js
│ │ │ ├── index.js
│ │ │ └── server.js
│ │ └── types.d.ts
│ ├── persister/
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── package.json
│ │ ├── rollup.config.test.js
│ │ ├── src/
│ │ │ ├── har/
│ │ │ │ ├── entry.js
│ │ │ │ ├── index.js
│ │ │ │ ├── log.js
│ │ │ │ ├── request.js
│ │ │ │ ├── response.js
│ │ │ │ └── utils/
│ │ │ │ ├── get-first-header.js
│ │ │ │ └── to-nv-pairs.js
│ │ │ └── index.js
│ │ ├── tests/
│ │ │ └── unit/
│ │ │ ├── har-test.js
│ │ │ └── persister-test.js
│ │ └── types.d.ts
│ ├── persister-fs/
│ │ ├── .eslintrc.js
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── package.json
│ │ ├── rollup.config.js
│ │ ├── rollup.config.test.js
│ │ ├── src/
│ │ │ └── index.js
│ │ ├── tests/
│ │ │ └── unit/
│ │ │ └── persister-test.js
│ │ └── types.d.ts
│ ├── persister-in-memory/
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE
│ │ ├── package.json
│ │ ├── rollup.config.test.js
│ │ ├── src/
│ │ │ └── index.js
│ │ └── types.d.ts
│ ├── persister-local-storage/
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── package.json
│ │ ├── rollup.config.test.js
│ │ ├── src/
│ │ │ └── index.js
│ │ └── types.d.ts
│ ├── persister-rest/
│ │ ├── CHANGELOG.md
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── package.json
│ │ ├── rollup.config.test.js
│ │ ├── src/
│ │ │ ├── ajax.js
│ │ │ └── index.js
│ │ └── types.d.ts
│ └── utils/
│ ├── CHANGELOG.md
│ ├── LICENSE
│ ├── README.md
│ ├── package.json
│ ├── rollup.config.test.js
│ ├── src/
│ │ ├── constants/
│ │ │ ├── actions.js
│ │ │ ├── expiry-strategies.js
│ │ │ ├── http-methods.js
│ │ │ ├── http-status-codes.js
│ │ │ └── modes.js
│ │ ├── index.js
│ │ └── utils/
│ │ ├── assert.js
│ │ ├── build-url.js
│ │ ├── clone-arraybuffer.js
│ │ ├── is-buffer-utf8-representable.js
│ │ ├── polly-error.js
│ │ ├── serializers/
│ │ │ ├── blob.js
│ │ │ ├── buffer.js
│ │ │ ├── form-data.js
│ │ │ └── index.js
│ │ ├── timeout.js
│ │ ├── timestamp.js
│ │ └── url.js
│ ├── tests/
│ │ ├── browser/
│ │ │ └── unit/
│ │ │ └── utils/
│ │ │ └── serializers/
│ │ │ ├── blob.js
│ │ │ └── form-data.js
│ │ ├── node/
│ │ │ └── unit/
│ │ │ └── utils/
│ │ │ └── serializers/
│ │ │ └── buffer.js
│ │ ├── serializer-tests.js
│ │ └── unit/
│ │ └── utils/
│ │ ├── assert-test.js
│ │ ├── build-url-test.js
│ │ ├── polly-error-test.js
│ │ ├── timeout-test.js
│ │ ├── timestamp-test.js
│ │ └── url-test.js
│ └── types.d.ts
├── scripts/
│ ├── require-clean-work-tree.sh
│ ├── require-test-build.sh
│ └── rollup/
│ ├── browser.config.js
│ ├── browser.test.config.js
│ ├── default.config.js
│ ├── jest.test.config.js
│ ├── node.config.js
│ ├── node.test.config.js
│ └── utils.js
├── testem.js
└── tests/
├── helpers/
│ ├── file.js
│ ├── global-node-fetch.js
│ ├── setup-fetch-record.js
│ └── setup-persister.js
├── index.mustache
├── integration/
│ ├── adapter-browser-tests.js
│ ├── adapter-identifier-tests.js
│ ├── adapter-node-tests.js
│ ├── adapter-polly-tests.js
│ ├── adapter-tests.js
│ └── persister-tests.js
├── middleware.js
└── node-setup.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .commitlintrc.js
================================================
/* eslint-env node */
module.exports = {
extends: [
'@commitlint/config-lerna-scopes',
'@commitlint/config-conventional'
],
rules: {
'subject-case': [2, 'always', ['sentence-case']]
}
};
================================================
FILE: .eslintignore
================================================
/packages/@pollyjs/ember/tests/**/index.html
CHANGELOG.md
package.json
node_modules
tmp
build
dist
================================================
FILE: .eslintrc.js
================================================
/* eslint-env node */
module.exports = {
root: true,
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module'
},
plugins: ['import'],
extends: ['eslint:recommended', 'plugin:prettier/recommended'],
globals: {
global: true
},
env: {
browser: true,
es6: true
},
rules: {
'no-console': 'off',
'prefer-const': 'error',
'getter-return': 'error',
'padding-line-between-statements': [
'error',
// require blank lines before all return statements,
{ blankLine: 'always', prev: '*', next: 'return' },
// Require blank lines after every sequence of variable declarations
{ blankLine: 'always', prev: ['const', 'let', 'var'], next: '*' },
{
blankLine: 'any',
prev: ['const', 'let', 'var'],
next: ['const', 'let', 'var']
}
],
'no-restricted-properties': [
2,
{
object: 'Object',
property: 'assign',
message: 'Please use the spread operator instead.'
}
],
// Require that imports occur at the top of the file
'import/first': 'error',
// Require imports to be grouped and ordered consistently
'import/order': [
'error',
{
'newlines-between': 'always'
}
]
},
overrides: [
// test files
{
files: ['tests/**/*.js', '**/*/tests/**/*.js'],
env: {
mocha: true
},
globals: {
chai: true,
expect: true
}
},
{
files: ['**/*/tests/node/**/*.js'],
env: {
browser: false
}
},
{
files: ['**/*/tests/jest/**/*.js'],
env: {
jest: true,
mocha: false
}
}
]
};
================================================
FILE: .github/issue_template.md
================================================
## Prerequisites
- We realize there is a lot of data requested here. We ask only that you do your best to provide as much information as possible so we can better help you.
- Read the [contributing guidelines](https://github.com/Netflix/pollyjs/blob/master/CONTRIBUTING.md).
- Ensure the issue isn't already reported.
- Should be reproducible with the latest @pollyjs package versions.
> _Delete the above section and the instructions in the sections below before submitting_
## Description
If this is a feature request, explain why it should be added. Specific use-cases are best.
For bug reports, please provide as much _relevant_ info as possible.
### Shareable Source
```js
// Avoid posting hundreds of lines of source code.
// Edit to just the relevant portions.
```
### Error Message & Stack Trace
```
COPY THE ERROR MESSAGE, INCLUDING STACK TRACE HERE
```
### Config
Copy the config used to setup the Polly instance:
```js
new Polly('Recording Name', {
// config...
});
```
### Dependencies
Copy the @pollyjs dependencies from `package.json`:
```json
{
"@pollyjs/core": "latest",
"@pollyjs/adapter-x": "latest",
"@pollyjs/persister-x": "latest"
}
```
## Relevant Links
- If your project is public, link to the repo so we can investigate directly.
- **BONUS POINTS:** Create a [minimal reproduction](http://stackoverflow.com/help/mcve) and upload it to GitHub. This will get you the fastest support.
## Environment
Tell us which operating system you are using, as well as which versions of Node.js and npm/yarn. If applicable, include the browser and the corresponding version.
Run the following to get it quickly:
```
node -e "var os=require('os');console.log('Node.js ' + process.version + '\n' + os.platform() + ' ' + os.release())"
npm --version
yarn --version
```
================================================
FILE: .github/pull_request_template.md
================================================
## Description
## Motivation and Context
## Types of Changes
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
## Checklist
- [ ] I have added tests to cover my changes.
- [ ] My change requires a change to the documentation.
- [ ] I have updated the documentation accordingly.
- [ ] My code follows the code style of this project.
- [ ] My commits and the title of this PR follow the [Conventional Commits Specification](https://www.conventionalcommits.org).
- [ ] I have read the [contributing guidelines](https://github.com/Netflix/pollyjs/blob/master/CONTRIBUTING.md).
================================================
FILE: .gitignore
================================================
.DS_Store
node_modules
package-lock.json
lerna-debug.log
packages/**/dist/
yarn-error.log
tmp
build
dist
*.lerna_backup
.npmrc
# Test recordings can write be written here if the test job did not
# get a chance to run to completion. The test will cleans these files up afterwards.
/recordings
# Examples
examples/**/*/yarn.lock
# IDE
.vscode/
.tool-versions
================================================
FILE: .husky/commit-msg
================================================
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
yarn commitlint --edit "$1"
================================================
FILE: .husky/pre-commit
================================================
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
yarn lint-staged
================================================
FILE: .mocharc.js
================================================
module.exports = {
spec: './packages/@pollyjs/*/build/node/*.js',
ui: 'bdd',
require: 'tests/node-setup.js'
};
================================================
FILE: .prettierrc.js
================================================
'use strict';
module.exports = {
singleQuote: true,
trailingComma: 'none'
};
================================================
FILE: .travis.yml
================================================
language: node_js
node_js:
- '12'
- '14'
- '16'
addons:
chrome: stable
cache:
yarn: true
before_install:
- curl -o- -L https://yarnpkg.com/install.sh | bash
- export PATH=$HOME/.yarn/bin:$PATH
install:
- yarn install --frozen-lockfile --non-interactive
script:
- commitlint-travis
- yarn run test:ci
- ./scripts/require-clean-work-tree.sh
================================================
FILE: CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.7](https://github.com/netflix/pollyjs/compare/v6.0.6...v6.0.7) (2025-05-31)
### Bug Fixes
* Undeprecating fetch for node because node supports fetch now ([#506](https://github.com/netflix/pollyjs/issues/506)) ([be0bd6c](https://github.com/netflix/pollyjs/commit/be0bd6ca0035565a1c29770bfc87f0b0754fec27))
## [6.0.6](https://github.com/netflix/pollyjs/compare/v6.0.5...v6.0.6) (2023-07-20)
**Note:** Version bump only for package pollyjs
## [6.0.5](https://github.com/netflix/pollyjs/compare/v6.0.4...v6.0.5) (2022-04-04)
### Bug Fixes
* **persister:** `requests` -> `request` in `HarEntry` declaration ([#441](https://github.com/netflix/pollyjs/issues/441)) ([6466810](https://github.com/netflix/pollyjs/commit/6466810677b6ac2c6a7496335bf40e043ab843e1))
## [6.0.4](https://github.com/netflix/pollyjs/compare/v6.0.3...v6.0.4) (2021-12-10)
### Bug Fixes
* Update types for class methods ([#438](https://github.com/netflix/pollyjs/issues/438)) ([b88655a](https://github.com/netflix/pollyjs/commit/b88655ac1b4ca7348afd45e9aeaa50e998ea68d7))
## [6.0.3](https://github.com/netflix/pollyjs/compare/v6.0.2...v6.0.3) (2021-12-08)
### Bug Fixes
* A few more type fixes ([#437](https://github.com/netflix/pollyjs/issues/437)) ([5e837a2](https://github.com/netflix/pollyjs/commit/5e837a25d28393b764cb66bcae0b29e9273eabe8))
## [6.0.2](https://github.com/netflix/pollyjs/compare/v6.0.1...v6.0.2) (2021-12-07)
### Bug Fixes
* **core:** Fix types for registering adapters and persisters ([#435](https://github.com/netflix/pollyjs/issues/435)) ([cc2fa19](https://github.com/netflix/pollyjs/commit/cc2fa197a5c0a5fdef4602c4a207d31f3e677897))
## [6.0.1](https://github.com/netflix/pollyjs/compare/v6.0.0...v6.0.1) (2021-12-06)
### Bug Fixes
* **ember:** Bump peer dependencies to 6.x ([#432](https://github.com/netflix/pollyjs/issues/432)) ([1529226](https://github.com/netflix/pollyjs/commit/152922688744c8a2f8d89f793dcecf3c2bc40033))
* **types:** add types.d.ts to package.files ([#431](https://github.com/netflix/pollyjs/issues/431)) ([113ee89](https://github.com/netflix/pollyjs/commit/113ee898bcf0467c5c48c15b53fc9198e2e91cb1))
# [6.0.0](https://github.com/netflix/pollyjs/compare/v5.2.0...v6.0.0) (2021-11-30)
### Bug Fixes
* **persister:** Only treat status codes >= 400 as failed ([#430](https://github.com/netflix/pollyjs/issues/430)) ([7658952](https://github.com/netflix/pollyjs/commit/765895232746cd560da6bd566de8a312045b1703))
* fix!: Upgrade url-parse (#426) ([c21ed04](https://github.com/netflix/pollyjs/commit/c21ed048ff9d87a3773458dcfb9758e4fa6582bf)), closes [#426](https://github.com/netflix/pollyjs/issues/426)
* feat!: Cleanup adapter and persister APIs (#429) ([06499fc](https://github.com/netflix/pollyjs/commit/06499fc2d85254b3329db2bec770d173ed32bca0)), closes [#429](https://github.com/netflix/pollyjs/issues/429)
* feat!: Improve logging and add logLevel (#427) ([bef3ee3](https://github.com/netflix/pollyjs/commit/bef3ee39f71dfc2fa4dbeb522dfba16d01243e9f)), closes [#427](https://github.com/netflix/pollyjs/issues/427)
* chore!: Upgrade package dependencies (#421) ([dd23334](https://github.com/netflix/pollyjs/commit/dd23334fa9b64248e4c49c3616237bdc2f12f682)), closes [#421](https://github.com/netflix/pollyjs/issues/421)
* feat!: Use base64 instead of hex encoding for binary data (#420) ([6bb9b36](https://github.com/netflix/pollyjs/commit/6bb9b36522d73f9c079735d9006a12376aee39ea)), closes [#420](https://github.com/netflix/pollyjs/issues/420)
* feat(ember)!: Upgrade to ember octane (#415) ([8559ef8](https://github.com/netflix/pollyjs/commit/8559ef8c600aefaec629870eac5f5c8953e18b16)), closes [#415](https://github.com/netflix/pollyjs/issues/415)
### Features
* **adapter-node-http:** Upgrade nock to v13 ([#424](https://github.com/netflix/pollyjs/issues/424)) ([2d5b59e](https://github.com/netflix/pollyjs/commit/2d5b59ee0c33ea53a64321249246fcae0a616a3f))
* **node-server:** Upgrade dependencies ([#417](https://github.com/netflix/pollyjs/issues/417)) ([246a2f2](https://github.com/netflix/pollyjs/commit/246a2f29a88de9c25fc0739ea5e53a0130a58573))
### BREAKING CHANGES
* Upgrade url-parse to 1.5.0+ to fix CVE-2021-27515. This change could alter the final url generated for a request.
* Adapter
- `passthroughRequest` renamed to `onFetchResponse`
- `respondToRequest` renamed to `onRespond`
* Persister
- `findRecording` renamed to `onFindRecording`
- `saveRecording` renamed to `onSaveRecording`
- `deleteRecording` renamed to `onDeleteRecording`
* The `logging` configuration option has now been replaced with `logLevel`. This allows for more fine-grain control over what should be logged as well as silencing logs altogether.
* Recording file name will no longer have trailing dashes
* Use the standard `encoding` field on the generated har file instead of `_isBinary` and use `base64` encoding instead of `hex` to reduce the payload size.
* Although backwards compatibility is not guaranteed, you can replace all occurrences of `"_isBinary": true` with `"encoding": "hex"` in the recorded HAR files.
* @pollyjs dependencies for @pollyjs/ember have been moved to peer dependencies
# [5.2.0](https://github.com/netflix/pollyjs/compare/v5.1.1...v5.2.0) (2021-11-24)
### Features
* **ember:** Upgrade ember-cli-babel to ^7.26.6 ([#411](https://github.com/netflix/pollyjs/issues/411)) ([4352881](https://github.com/netflix/pollyjs/commit/4352881))
## [5.1.1](https://github.com/netflix/pollyjs/compare/v5.1.0...v5.1.1) (2021-06-02)
### Bug Fixes
* Handle failed arraybuffer instanceof checks ([#393](https://github.com/netflix/pollyjs/issues/393)) ([247be0a](https://github.com/netflix/pollyjs/commit/247be0a))
# [5.1.0](https://github.com/netflix/pollyjs/compare/v5.0.2...v5.1.0) (2020-12-12)
### Bug Fixes
* **adapter-puppeteer:** Add prependListener puppeteer@4.0.0 removed ([#368](https://github.com/netflix/pollyjs/issues/368)) ([6c35fd3](https://github.com/netflix/pollyjs/commit/6c35fd3))
### Features
* **core:** Add `overrideRecordingName` and `configure` to public API ([#372](https://github.com/netflix/pollyjs/issues/372)) ([cdbf513](https://github.com/netflix/pollyjs/commit/cdbf513))
## [5.0.2](https://github.com/netflix/pollyjs/compare/v5.0.1...v5.0.2) (2020-12-06)
### Bug Fixes
* **adapter-node-http:** Remove module monkey patching on disconnect ([#369](https://github.com/netflix/pollyjs/issues/369)) ([0cec43a](https://github.com/netflix/pollyjs/commit/0cec43a))
## [5.0.1](https://github.com/netflix/pollyjs/compare/v5.0.0...v5.0.1) (2020-09-25)
### Bug Fixes
* **adapter-xhr:** Only modify the `responseType` if it was changed ([#363](https://github.com/netflix/pollyjs/issues/363)) ([cff4e2d](https://github.com/netflix/pollyjs/commit/cff4e2d))
# [5.0.0](https://github.com/netflix/pollyjs/compare/v4.3.0...v5.0.0) (2020-06-23)
### Bug Fixes
* **adapter-fetch:** Add statusText to the response ([#341](https://github.com/netflix/pollyjs/issues/341)) ([0d45953](https://github.com/netflix/pollyjs/commit/0d45953))
* **core:** Compute order based on id and recording name ([#342](https://github.com/netflix/pollyjs/issues/342)) ([42004d2](https://github.com/netflix/pollyjs/commit/42004d2))
### Features
* Remove deprecated Persister.name and Adapter.name ([#343](https://github.com/netflix/pollyjs/issues/343)) ([1223ba0](https://github.com/netflix/pollyjs/commit/1223ba0))
### BREAKING CHANGES
* Persister.name and Adapter.name have been replaced with Persister.id and Adapter.id
* **core:** A request's order is will now be computed based on its id and the recording name it will be persisted to.
# [4.3.0](https://github.com/netflix/pollyjs/compare/v4.2.1...v4.3.0) (2020-05-18)
### Features
* **adapter-fetch:** Add support for handling binary data ([#332](https://github.com/netflix/pollyjs/issues/332)) ([111bebf](https://github.com/netflix/pollyjs/commit/111bebf))
* **adapter-xhr:** Add support for handling binary data ([#333](https://github.com/netflix/pollyjs/issues/333)) ([48ea1d7](https://github.com/netflix/pollyjs/commit/48ea1d7))
* **core:** Add `flushRequestsOnStop` configuration option ([#335](https://github.com/netflix/pollyjs/issues/335)) ([ab4a2e1](https://github.com/netflix/pollyjs/commit/ab4a2e1))
## [4.2.1](https://github.com/netflix/pollyjs/compare/v4.2.0...v4.2.1) (2020-04-30)
### Bug Fixes
* **adapter-node-http:** Improve binary response body handling ([#329](https://github.com/netflix/pollyjs/issues/329)) ([9466989](https://github.com/netflix/pollyjs/commit/9466989))
# [4.2.0](https://github.com/netflix/pollyjs/compare/v4.1.0...v4.2.0) (2020-04-29)
### Features
* **node-server:** Pass options to the CORS middleware via `corsOptions` ([3d991f5](https://github.com/netflix/pollyjs/commit/3d991f5))
# [4.1.0](https://github.com/netflix/pollyjs/compare/v4.0.4...v4.1.0) (2020-04-23)
### Bug Fixes
* Improve abort handling ([#320](https://github.com/netflix/pollyjs/issues/320)) ([cc46bb4](https://github.com/netflix/pollyjs/commit/cc46bb4))
* Legacy persisters and adapters should register ([#325](https://github.com/netflix/pollyjs/issues/325)) ([8fd4d19](https://github.com/netflix/pollyjs/commit/8fd4d19))
### Features
* **persister:** Add `disableSortingHarEntries` option ([#321](https://github.com/netflix/pollyjs/issues/321)) ([0003c0e](https://github.com/netflix/pollyjs/commit/0003c0e))
## [4.0.4](https://github.com/netflix/pollyjs/compare/v4.0.3...v4.0.4) (2020-03-21)
### Bug Fixes
* Deprecates adapter & persister `name` in favor of `id` ([#310](https://github.com/netflix/pollyjs/issues/310)) ([41dd093](https://github.com/netflix/pollyjs/commit/41dd093))
* **adapter-node-http:** Bump nock version ([#319](https://github.com/netflix/pollyjs/issues/319)) ([7d361a6](https://github.com/netflix/pollyjs/commit/7d361a6))
## [4.0.3](https://github.com/netflix/pollyjs/compare/v4.0.2...v4.0.3) (2020-01-30)
### Bug Fixes
* **adapter-node-http:** Use requestBodyBuffers to parse body ([#304](https://github.com/netflix/pollyjs/issues/304)) ([113fec5](https://github.com/netflix/pollyjs/commit/113fec5))
## [4.0.2](https://github.com/netflix/pollyjs/compare/v4.0.1...v4.0.2) (2020-01-29)
### Bug Fixes
* **core:** Strict null query param handling ([#302](https://github.com/netflix/pollyjs/issues/302)) ([5cf70aa](https://github.com/netflix/pollyjs/commit/5cf70aa))
## [4.0.1](https://github.com/netflix/pollyjs/compare/v4.0.0...v4.0.1) (2020-01-25)
### Bug Fixes
* **ember:** Config read from project root ([7d6da38](https://github.com/netflix/pollyjs/commit/7d6da38))
# [4.0.0](https://github.com/netflix/pollyjs/compare/v3.0.2...v4.0.0) (2020-01-13)
### Bug Fixes
* **adapter:** Clone the recording entry before mutating it ([#294](https://github.com/netflix/pollyjs/issues/294)) ([d7e1303](https://github.com/netflix/pollyjs/commit/d7e1303))
* **core:** Disconnect from all adapters when `pause` is called ([#291](https://github.com/netflix/pollyjs/issues/291)) ([5c655bf](https://github.com/netflix/pollyjs/commit/5c655bf))
### chore
* Drop node 8 support ([#292](https://github.com/netflix/pollyjs/issues/292)) ([4448be5](https://github.com/netflix/pollyjs/commit/4448be5))
### Features
* **core:** Provide the request as an argument to matchRequestsBy methods ([#293](https://github.com/netflix/pollyjs/issues/293)) ([4e3163f](https://github.com/netflix/pollyjs/commit/4e3163f))
* **core:** Remove deprecated `recordIfExpired` option ([#295](https://github.com/netflix/pollyjs/issues/295)) ([5fe991d](https://github.com/netflix/pollyjs/commit/5fe991d))
### BREAKING CHANGES
* **core:** `recordIfExpired` is no longer supported, please use `expiryStrategy` instead.
* Drop support for Node 8 as it is now EOL
* **core:** Calling `polly.pause()` will now disconnect from all connected adapters instead of setting the mode to passthrough. Calling `polly.play()` will reconnect to the disconnected adapters before pause was called.
## [3.0.2](https://github.com/netflix/pollyjs/compare/v3.0.1...v3.0.2) (2020-01-08)
### Bug Fixes
* **adapter-node-http:** Bump nock version to correctly handle re… ([#289](https://github.com/netflix/pollyjs/issues/289)) ([8d0ae97](https://github.com/netflix/pollyjs/commit/8d0ae97)), closes [#278](https://github.com/netflix/pollyjs/issues/278)
## [3.0.1](https://github.com/netflix/pollyjs/compare/v3.0.0...v3.0.1) (2019-12-25)
### Bug Fixes
* **adapter-fetch:** Fix "failed to construct Request" issue ([#287](https://github.com/netflix/pollyjs/issues/287)) ([d17ab9b](https://github.com/netflix/pollyjs/commit/d17ab9b)), closes [#286](https://github.com/netflix/pollyjs/issues/286)
# [3.0.0](https://github.com/netflix/pollyjs/compare/v2.7.0...v3.0.0) (2019-12-18)
### Bug Fixes
* **ember:** loads polly config for ember by its own module ([#277](https://github.com/netflix/pollyjs/issues/277)) ([0569040](https://github.com/netflix/pollyjs/commit/0569040))
### BREAKING CHANGES
* **ember:** moves location of polly configuration
# [2.7.0](https://github.com/netflix/pollyjs/compare/v2.6.3...v2.7.0) (2019-11-21)
### Bug Fixes
* **adapter-node-http:** Correctly handle uploading binary data ([#257](https://github.com/netflix/pollyjs/issues/257)) ([31f0e0a](https://github.com/netflix/pollyjs/commit/31f0e0a))
### Features
* **adapter-node-http:** Upgrade nock to v11.x ([#273](https://github.com/netflix/pollyjs/issues/273)) ([5d42cbd](https://github.com/netflix/pollyjs/commit/5d42cbd))
## [2.6.3](https://github.com/netflix/pollyjs/compare/v2.6.2...v2.6.3) (2019-09-30)
### Bug Fixes
* use watch strategy ([#236](https://github.com/netflix/pollyjs/issues/236)) ([5b4edf3](https://github.com/netflix/pollyjs/commit/5b4edf3))
* **adapter-fetch:** Correctly handle Request instance passed into fetch ([#259](https://github.com/netflix/pollyjs/issues/259)) ([593ecb9](https://github.com/netflix/pollyjs/commit/593ecb9))
## [2.6.2](https://github.com/netflix/pollyjs/compare/v2.6.1...v2.6.2) (2019-08-05)
### Bug Fixes
* Bowser.getParser empty string UserAgent error ([#246](https://github.com/netflix/pollyjs/issues/246)) ([2c9c4b9](https://github.com/netflix/pollyjs/commit/2c9c4b9))
### Features
* Adds an in-memory persister to test polly internals ([#237](https://github.com/netflix/pollyjs/issues/237)) ([5a6fda6](https://github.com/netflix/pollyjs/commit/5a6fda6))
## [2.6.1](https://github.com/netflix/pollyjs/compare/v2.6.0...v2.6.1) (2019-08-01)
### Bug Fixes
* **persister:** Default to empty string if userAgent is empty ([#242](https://github.com/netflix/pollyjs/issues/242)) ([c46d65c](https://github.com/netflix/pollyjs/commit/c46d65c))
# [2.6.0](https://github.com/netflix/pollyjs/compare/v2.5.0...v2.6.0) (2019-07-17)
### Bug Fixes
* **adapter-fetch:** Handle `Request` objects as URLs ([#220](https://github.com/netflix/pollyjs/issues/220)) ([bb28d54](https://github.com/netflix/pollyjs/commit/bb28d54))
### Features
* **core:** Improved logging ([#217](https://github.com/netflix/pollyjs/issues/217)) ([3e876a8](https://github.com/netflix/pollyjs/commit/3e876a8))
* PollyError and improved adapter error handling ([#234](https://github.com/netflix/pollyjs/issues/234)) ([23a2127](https://github.com/netflix/pollyjs/commit/23a2127))
# [2.5.0](https://github.com/netflix/pollyjs/compare/v2.4.0...v2.5.0) (2019-06-06)
### Features
* **adapter-xhr:** Support `context` option ([65b3c38](https://github.com/netflix/pollyjs/commit/65b3c38))
# [2.4.0](https://github.com/netflix/pollyjs/compare/v2.3.2...v2.4.0) (2019-04-27)
### Features
* **core:** Improved control flow with `times` and `stopPropagation` ([#202](https://github.com/netflix/pollyjs/issues/202)) ([2c8231e](https://github.com/netflix/pollyjs/commit/2c8231e))
## [2.3.2](https://github.com/netflix/pollyjs/compare/v2.3.1...v2.3.2) (2019-04-09)
### Bug Fixes
* **adapter-puppeteer:** Remove other resource type matching ([#197](https://github.com/netflix/pollyjs/issues/197)) ([ea6bfcc](https://github.com/netflix/pollyjs/commit/ea6bfcc))
## [2.3.1](https://github.com/netflix/pollyjs/compare/v2.3.0...v2.3.1) (2019-03-06)
### Bug Fixes
* **adapter-fetch:** Correctly handle key/value pairs headers ([dc0323d](https://github.com/netflix/pollyjs/commit/dc0323d))
# [2.3.0](https://github.com/netflix/pollyjs/compare/v2.2.0...v2.3.0) (2019-02-27)
### Features
* **core:** Filter requests matched by a route handler ([#189](https://github.com/netflix/pollyjs/issues/189)) ([5d57c32](https://github.com/netflix/pollyjs/commit/5d57c32))
# [2.2.0](https://github.com/netflix/pollyjs/compare/v2.1.0...v2.2.0) (2019-02-20)
### Features
* Add `error` event and improve error handling ([#185](https://github.com/netflix/pollyjs/issues/185)) ([3694ebc](https://github.com/netflix/pollyjs/commit/3694ebc))
# [2.1.0](https://github.com/netflix/pollyjs/compare/v2.0.0...v2.1.0) (2019-02-04)
### Bug Fixes
* **adapter:** Log information if request couldn't be found in recording ([#172](https://github.com/netflix/pollyjs/issues/172)) ([8dcdf7b](https://github.com/netflix/pollyjs/commit/8dcdf7b))
* **adapter-xhr:** Xhr.send should not be an async method ([#173](https://github.com/netflix/pollyjs/issues/173)) ([eb3a6eb](https://github.com/netflix/pollyjs/commit/eb3a6eb))
* Correctly handle array header values ([#179](https://github.com/netflix/pollyjs/issues/179)) ([fb7dbb4](https://github.com/netflix/pollyjs/commit/fb7dbb4))
### Features
* **core:** Add removeHeader, removeHeaders, and allow empty headers ([#176](https://github.com/netflix/pollyjs/issues/176)) ([1dfae5a](https://github.com/netflix/pollyjs/commit/1dfae5a))
# [2.0.0](https://github.com/netflix/pollyjs/compare/v1.4.2...v2.0.0) (2019-01-29)
* feat(adapter-node-http): Use `nock` under the hood instead of custom implementation (#166) ([62374f4](https://github.com/netflix/pollyjs/commit/62374f4)), closes [#166](https://github.com/netflix/pollyjs/issues/166)
### Bug Fixes
* **adapter:** Test for navigator before accessing ([#165](https://github.com/netflix/pollyjs/issues/165)) ([7200255](https://github.com/netflix/pollyjs/commit/7200255))
* **ember:** Remove Node 6 from supported versions ([#169](https://github.com/netflix/pollyjs/issues/169)) ([07b2b4e](https://github.com/netflix/pollyjs/commit/07b2b4e))
* **persister:** Only persist post data if a request has a body ([#171](https://github.com/netflix/pollyjs/issues/171)) ([f62d318](https://github.com/netflix/pollyjs/commit/f62d318))
### chore
* Remove support for Node 6 ([#167](https://github.com/netflix/pollyjs/issues/167)) ([a08a8cf](https://github.com/netflix/pollyjs/commit/a08a8cf))
### Features
* Make PollyRequest.respond accept a response object ([#168](https://github.com/netflix/pollyjs/issues/168)) ([5b07b26](https://github.com/netflix/pollyjs/commit/5b07b26))
* Simplify adapter implementation ([#154](https://github.com/netflix/pollyjs/issues/154)) ([12c8601](https://github.com/netflix/pollyjs/commit/12c8601))
### BREAKING CHANGES
* The node-http adapter no longer accepts the `transports` option
* Any adapters calling `pollyRequest.respond` should pass it a response object instead of the previous 3 arguments (statusCode, headers, body).
* Polly will no longer actively support Node 6
* Changes to the base adapter implementation and external facing API
## [1.4.2](https://github.com/netflix/pollyjs/compare/v1.4.1...v1.4.2) (2019-01-16)
### Bug Fixes
* **adapter-node-http:** Fix unhandled rejection if connection fails ([#160](https://github.com/netflix/pollyjs/issues/160)) ([12fcfa7](https://github.com/netflix/pollyjs/commit/12fcfa7))
* **adapter-node-http:** Pause socket on original request ([#162](https://github.com/netflix/pollyjs/issues/162)) ([8f0c56c](https://github.com/netflix/pollyjs/commit/8f0c56c))
### Features
* Lint other filetypes with prettier ([#152](https://github.com/netflix/pollyjs/issues/152)) ([78d1af8](https://github.com/netflix/pollyjs/commit/78d1af8))
## [1.4.1](https://github.com/netflix/pollyjs/compare/v1.4.0...v1.4.1) (2018-12-13)
### Bug Fixes
* **utils:** Support arrays & nested objects in query params ([#148](https://github.com/netflix/pollyjs/issues/148)) ([7e846b0](https://github.com/netflix/pollyjs/commit/7e846b0))
# [1.4.0](https://github.com/netflix/pollyjs/compare/v1.3.2...v1.4.0) (2018-12-07)
### Bug Fixes
* **adapter-fetch:** Deprecate usage in Node in favor of node-http ([#146](https://github.com/netflix/pollyjs/issues/146)) ([001ccdd](https://github.com/netflix/pollyjs/commit/001ccdd))
### Features
* Node HTTP Adapter ([#128](https://github.com/netflix/pollyjs/issues/128)) ([fa059a4](https://github.com/netflix/pollyjs/commit/fa059a4))
## [1.3.2](https://github.com/netflix/pollyjs/compare/v1.3.1...v1.3.2) (2018-11-29)
**Note:** Version bump only for package pollyjs
## [1.3.1](https://github.com/netflix/pollyjs/compare/v1.2.0...v1.3.1) (2018-11-28)
### Bug Fixes
* Support URL objects ([#139](https://github.com/netflix/pollyjs/issues/139)) ([cf0d755](https://github.com/netflix/pollyjs/commit/cf0d755))
* **core:** Handle trailing slashes when generating route names ([#142](https://github.com/netflix/pollyjs/issues/142)) ([19147f7](https://github.com/netflix/pollyjs/commit/19147f7))
* **core:** Ignore `context` options from being deep merged ([#144](https://github.com/netflix/pollyjs/issues/144)) ([2123d83](https://github.com/netflix/pollyjs/commit/2123d83))
* **core:** Support multiple handlers for same paths ([#141](https://github.com/netflix/pollyjs/issues/141)) ([79e04b8](https://github.com/netflix/pollyjs/commit/79e04b8))
### Features
* **core:** Support custom functions in matchRequestsBy config options ([#138](https://github.com/netflix/pollyjs/issues/138)) ([626a84c](https://github.com/netflix/pollyjs/commit/626a84c))
* Add an onIdentifyRequest hook to allow adapter level serialization ([#140](https://github.com/netflix/pollyjs/issues/140)) ([548002c](https://github.com/netflix/pollyjs/commit/548002c))
# 1.2.0 (2018-09-16)
### Bug Fixes
* **adapter-puppeteer:** Do not intercept CORS preflight requests ([#90](https://github.com/netflix/pollyjs/issues/90)) ([53ad433](https://github.com/netflix/pollyjs/commit/53ad433))
* Changes self to global, rollup-plugin-node-globals makes isomorphic ([#54](https://github.com/netflix/pollyjs/issues/54)) ([3811e9d](https://github.com/netflix/pollyjs/commit/3811e9d))
* **core:** Freeze request after emitting afterResponse. ([66a2b64](https://github.com/netflix/pollyjs/commit/66a2b64))
* Allow 204 responses without a body ([#101](https://github.com/netflix/pollyjs/issues/101)) ([20b4125](https://github.com/netflix/pollyjs/commit/20b4125))
* Browser (UMD) build now bundles corejs ([#106](https://github.com/netflix/pollyjs/issues/106)) ([ec62fc0](https://github.com/netflix/pollyjs/commit/ec62fc0))
* Bumping core within Ember ([af4faa1](https://github.com/netflix/pollyjs/commit/af4faa1))
* Config expiresIn can contain periods. i.e, 1.5 weeks ([e9c7aaa](https://github.com/netflix/pollyjs/commit/e9c7aaa))
* Correctly normalize relative URLs ([b9b23cd](https://github.com/netflix/pollyjs/commit/b9b23cd))
* Creator cleanup and persister assertion ([#67](https://github.com/netflix/pollyjs/issues/67)) ([19fee5a](https://github.com/netflix/pollyjs/commit/19fee5a))
* Do not display node server listening banner in quiet mode ([1be57a7](https://github.com/netflix/pollyjs/commit/1be57a7))
* Ensure polly's middleware goes before ember-cli's ([#36](https://github.com/netflix/pollyjs/issues/36)) ([43db361](https://github.com/netflix/pollyjs/commit/43db361))
* Improve support for relative URLs ([#78](https://github.com/netflix/pollyjs/issues/78)) ([2c0083e](https://github.com/netflix/pollyjs/commit/2c0083e)), closes [#76](https://github.com/netflix/pollyjs/issues/76)
* Loosen up global XHR native check ([#69](https://github.com/netflix/pollyjs/issues/69)) ([79cdd96](https://github.com/netflix/pollyjs/commit/79cdd96))
* Proxy route.params onto the request instead of mutating req ([5bcd4f9](https://github.com/netflix/pollyjs/commit/5bcd4f9))
* Puppeteer 1.7.0 support ([#100](https://github.com/netflix/pollyjs/issues/100)) ([e208b38](https://github.com/netflix/pollyjs/commit/e208b38))
* Puppeteer CORS request matching ([#110](https://github.com/netflix/pollyjs/issues/110)) ([7831115](https://github.com/netflix/pollyjs/commit/7831115))
* Rest server on Windows ([be5c473](https://github.com/netflix/pollyjs/commit/be5c473))
* **core:** Set `url` on the fetch Response object ([#44](https://github.com/netflix/pollyjs/issues/44)) ([f5980cf](https://github.com/netflix/pollyjs/commit/f5980cf)), closes [#43](https://github.com/netflix/pollyjs/issues/43)
* **ember:** Fix auto-register and add tests to cover ([24c15bd](https://github.com/netflix/pollyjs/commit/24c15bd))
* **persister:** Handle concurrent find requests ([#88](https://github.com/netflix/pollyjs/issues/88)) ([0e02414](https://github.com/netflix/pollyjs/commit/0e02414))
### Features
* Abort and passthrough from an intercept ([#57](https://github.com/netflix/pollyjs/issues/57)) ([4ebacb8](https://github.com/netflix/pollyjs/commit/4ebacb8))
* Class events and EventEmitter ([#52](https://github.com/netflix/pollyjs/issues/52)) ([0a3d591](https://github.com/netflix/pollyjs/commit/0a3d591))
* Cleanup event handler logic + rename some event names ([78dbb5d](https://github.com/netflix/pollyjs/commit/78dbb5d))
* Convert recordings to be HAR compliant ([#45](https://github.com/netflix/pollyjs/issues/45)) ([e622640](https://github.com/netflix/pollyjs/commit/e622640))
* Custom persister support ([8bb313c](https://github.com/netflix/pollyjs/commit/8bb313c))
* Fetch adapter support for `context` provided via adapterOptions ([#66](https://github.com/netflix/pollyjs/issues/66)) ([82ebd09](https://github.com/netflix/pollyjs/commit/82ebd09))
* Improved adapter and persister registration ([#62](https://github.com/netflix/pollyjs/issues/62)) ([164dbac](https://github.com/netflix/pollyjs/commit/164dbac))
* Keyed persister & adapter options ([#60](https://github.com/netflix/pollyjs/issues/60)) ([29ed8e1](https://github.com/netflix/pollyjs/commit/29ed8e1))
* Make recording size limit configurable ([#40](https://github.com/netflix/pollyjs/issues/40)) ([d4be431](https://github.com/netflix/pollyjs/commit/d4be431))
* Move more response methods to shared base class ([#74](https://github.com/netflix/pollyjs/issues/74)) ([4f845e5](https://github.com/netflix/pollyjs/commit/4f845e5))
* Node File System Persister ([#61](https://github.com/netflix/pollyjs/issues/61)) ([0a0eeca](https://github.com/netflix/pollyjs/commit/0a0eeca))
* Presets persisterOptions.host to the node server default ([0b47838](https://github.com/netflix/pollyjs/commit/0b47838))
* Puppeteer Adapter ([#64](https://github.com/netflix/pollyjs/issues/64)) ([f902c6d](https://github.com/netflix/pollyjs/commit/f902c6d))
* Use status code 204 in place of 404. ([#5](https://github.com/netflix/pollyjs/issues/5)) ([930c492](https://github.com/netflix/pollyjs/commit/930c492))
* **core:** Add `json` property to `Request` ([bb8e1cb](https://github.com/netflix/pollyjs/commit/bb8e1cb)), closes [#7](https://github.com/netflix/pollyjs/issues/7)
* **core:** Default `Response` status code to 200 ([f42a281](https://github.com/netflix/pollyjs/commit/f42a281)), closes [#6](https://github.com/netflix/pollyjs/issues/6)
* Wait for all handled requests to resolve via `.flush()` ([#75](https://github.com/netflix/pollyjs/issues/75)) ([a3113b7](https://github.com/netflix/pollyjs/commit/a3113b7))
* **core:** Normalize headers by lower-casing all keys ([#42](https://github.com/netflix/pollyjs/issues/42)) ([02a4767](https://github.com/netflix/pollyjs/commit/02a4767))
* **core:** Server level configuration ([#80](https://github.com/netflix/pollyjs/issues/80)) ([0f32d9b](https://github.com/netflix/pollyjs/commit/0f32d9b))
* **node-server:** Add cors support to express server to pass-through all requests ([223ce4e](https://github.com/netflix/pollyjs/commit/223ce4e))
* **persister:** Add `keepUnusedRequests` config option ([#108](https://github.com/netflix/pollyjs/issues/108)) ([3f5f5b2](https://github.com/netflix/pollyjs/commit/3f5f5b2))
* **persister:** Cache recordings ([#31](https://github.com/netflix/pollyjs/issues/31)) ([a04d7a7](https://github.com/netflix/pollyjs/commit/a04d7a7))
### Reverts
* "Update commitlint.config.js" ([65e6996](https://github.com/netflix/pollyjs/commit/65e6996))
* Add `json` property to `Request` ([4ea50e8](https://github.com/netflix/pollyjs/commit/4ea50e8))
* Revert "Update commitlint.config.js" ([6624cb5](https://github.com/netflix/pollyjs/commit/6624cb5))
* Revert Use docsify GA plugin ([35ace6f](https://github.com/netflix/pollyjs/commit/35ace6f))
* Use docsify GA plugin ([cf5f1c5](https://github.com/netflix/pollyjs/commit/cf5f1c5))
### BREAKING CHANGES
* __Adapters__
```js
import { XHRAdapter, FetchAdapter } from '@pollyjs/core';
// Register the xhr adapter so its accessible by all future polly instances
Polly.register(XHRAdapter);
polly.configure({
adapters: ['xhr', FetchAdapter]
});
```
__Persister__
```js
import { LocalStoragePersister, RESTPersister } from '@pollyjs/core';
// Register the local-storage persister so its accessible by all future polly instances
Polly.register(LocalStoragePersister);
polly.configure({
persister: 'local-storage'
});
polly.configure({
persister: RESTPersister
});
```
* Recordings now produce HAR compliant json. Please delete existing recordings.
* **core:** With this change, request ids will resolve to a different hash meaning that users will have to rerecord.
* Relative URLs will have different hashes and will
require to re-record.
# Changelog
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing
[](https://lerna.js.org/)
## Getting Started
Install required global dependencies:
```bash
npm install -g yarn
```
Check out the code and go into the pollyjs directory:
```bash
git clone https://github.com/netflix/pollyjs.git
cd pollyjs
```
Install the dependencies and bootstrap the monorepo:
```bash
yarn
```
The code for individual packages of this monorepo are in `packages/@pollyjs/*`.
Within any of the packages in this monorepo you'll generally use the npm
package scripts to manage the project, E.g. `yarn run test` or
`yarn run lint`. Run `yarn run` for a list of available commands.
## Running Tests
### Full Suite
To run the full test suite, from the root directory run:
```bash
yarn test
```
This will perform a full bootstrap, clean and build on all of the sub-packages
and test suite, stand up the node server, run the test suite and then terminate.
### Running only changed tests
While developing, it may become cumbersome to run the entire suite after each change.
In one terminal tab, run the following:
```bash
yarn watch
```
This will build all of the sub-packages and test suite, watch for any changes, and
perform incremental builds when the suite or packages are changed.
Wait until the build settles (i.e. build output stops scrolling). Then, in another tab:
```bash
yarn test:watch
```
This will launch an interactive test runner (`testem`), which will automatically detect
and re-run changed tests. To manually re-run the suite, hit `enter`. To exit, hit `q` and
then `ctrl-c` your watch process. For more information, look at the
[testem docs](https://github.com/testem/testem).
## Running Node Tests with Chrome Inspector
To run the node test suite with node inspector support, run from the root directory:
```bash
yarn test:ci -l Node:debug
```
Next, attach Chrome to the running process by visiting [chrome://inspect/#devices](chrome://inspect/#devices)
## Running Docs
All the documentation can be found in the root level `docs` directory. Running
the following command will stand up the docs server which will watch for
changes.
```bash
yarn docs:serve
```
## Conventional Commits
Lerna depends on the use of the [Conventional Commits Specification](https://conventionalcommits.org/)
to determine the version bump and generate CHANGELOG.md files. Make sure your
commits and the title of your PRs follow the spec. A pre-commit hook and CI test
have been added to further enforce this requirement.
## Tips for Getting Your Pull Request Accepted
1. Make sure all new features are tested and the tests pass.
2. Bug fixes must include a test case demonstrating the error that it fixes.
3. Open an issue first and seek advice for your change before submitting
a pull request. Large features which have never been discussed are
unlikely to be accepted. **You have been warned.**
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Netflix Inc and @pollyjs contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: OSSMETADATA
================================================
osslifecycle=active
================================================
FILE: README.md
================================================
Record, Replay, and Stub HTTP Interactions
[](https://travis-ci.com/Netflix/pollyjs)
[](http://www.apache.org/licenses/LICENSE-2.0)
Polly.JS is a standalone, framework-agnostic JavaScript library that enables recording, replaying, and stubbing of HTTP interactions. By tapping into multiple request APIs across both Node & the browser, Polly.JS is able to mock requests and responses with little to no configuration while giving you the ability to take full control of each request with a simple, powerful, and intuitive API.
> Interested in contributing or just seeing Polly in action? Head over to [CONTRIBUTING.md](CONTRIBUTING.md) to learn how to spin up the project!
## Why Polly?
Keeping fixtures and factories in parity with your APIs can be a time consuming process.
Polly alleviates this process by recording and maintaining actual server responses while also staying flexible.
- Record your test suite's HTTP interactions and replay them during future test runs for fast, deterministic, accurate tests.
- Use Polly's client-side server to modify or intercept requests and responses to simulate different application states (e.g. loading, error, etc.).
## Features
- 🚀 Node & Browser Support
- ⚡️️ Simple, Powerful, & Intuitive API
- 💎 First Class Mocha & QUnit Test Helpers
- 🔥 Intercept, Pass-Through, and Attach Events
- 📼 Record to Disk or Local Storage
- ⏱ Slow Down or Speed Up Time
## Getting Started
Check out the [Quick Start](https://netflix.github.io/pollyjs/#/quick-start) documentation to get started.
## Usage
Let's take a look at what an example test case would look like using Polly.
```js
import { Polly } from '@pollyjs/core';
import XHRAdapter from '@pollyjs/adapter-xhr';
import FetchAdapter from '@pollyjs/adapter-fetch';
import RESTPersister from '@pollyjs/persister-rest';
/*
Register the adapters and persisters we want to use. This way all future
polly instances can access them by name.
*/
Polly.register(XHRAdapter);
Polly.register(FetchAdapter);
Polly.register(RESTPersister);
describe('Netflix Homepage', function () {
it('should be able to sign in', async function () {
/*
Create a new polly instance.
Connect Polly to both fetch and XHR browser APIs. By default, it will
record any requests that it hasn't yet seen while replaying ones it
has already recorded.
*/
const polly = new Polly('Sign In', {
adapters: ['xhr', 'fetch'],
persister: 'rest'
});
const { server } = polly;
/* Intercept all Google Analytic requests and respond with a 200 */
server
.get('/google-analytics/*path')
.intercept((req, res) => res.sendStatus(200));
/* Pass-through all GET requests to /coverage */
server.get('/coverage').passthrough();
/* start: pseudo test code */
await visit('/login');
await fillIn('email', 'polly@netflix.com');
await fillIn('password', '@pollyjs');
await submit();
/* end: pseudo test code */
expect(location.pathname).to.equal('/browse');
/*
Calling `stop` will persist requests as well as disconnect from any
connected browser APIs (e.g. fetch or XHR).
*/
await polly.stop();
});
});
```
The above test case would generate the following [HAR](http://www.softwareishard.com/blog/har-12-spec/)
file which Polly will use to replay the sign-in response when the test is rerun:
```json
{
"log": {
"_recordingName": "Sign In",
"browser": {
"name": "Chrome",
"version": "67.0"
},
"creator": {
"name": "Polly.JS",
"version": "0.5.0",
"comment": "persister:rest"
},
"entries": [
{
"_id": "06f06e6d125cbb80896c41786f9a696a",
"_order": 0,
"cache": {},
"request": {
"bodySize": 51,
"cookies": [],
"headers": [
{
"name": "content-type",
"value": "application/json; charset=utf-8"
}
],
"headersSize": 97,
"httpVersion": "HTTP/1.1",
"method": "POST",
"postData": {
"mimeType": "application/json; charset=utf-8",
"text": "{\"email\":\"polly@netflix.com\",\"password\":\"@pollyjs\"}"
},
"queryString": [],
"url": "https://netflix.com/api/v1/login"
},
"response": {
"bodySize": 0,
"content": {
"mimeType": "text/plain; charset=utf-8",
"size": 0
},
"cookies": [],
"headers": [],
"headersSize": 0,
"httpVersion": "HTTP/1.1",
"redirectURL": "",
"status": 200,
"statusText": "OK"
},
"startedDateTime": "2018-06-29T17:31:55.348Z",
"time": 11,
"timings": {
"blocked": -1,
"connect": -1,
"dns": -1,
"receive": 0,
"send": 0,
"ssl": -1,
"wait": 11
}
}
],
"pages": [],
"version": "1.2"
}
}
```
## Prior Art
The "Client Server" API of Polly is heavily influenced by the very popular mock server library [pretender](https://github.com/pretenderjs/pretender). Pretender supports XHR and Fetch stubbing and is a great lightweight alternative to Polly if your project does not require persisting capabilities or Node adapters.
Thank you to all contributors especially the maintainers: [trek](https://github.com/trek), [stefanpenner](https://github.com/stefanpenner), and [xg-wang](https://github.com/xg-wang).
## Contributors
[//]: contributor-faces
[//]: contributor-faces
## License
Copyright (c) 2018 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
================================================
FILE: docs/.nojekyll
================================================
================================================
FILE: docs/_coverpage.md
================================================

> Record, replay, and stub HTTP interactions.
- 🚀 Node & Browser Support
- ⚡️️ Simple, Powerful, & Intuitive API
- 💎 First Class Mocha & QUnit Test Helpers
- 🔥 Intercept, Pass-Through, and Attach Events
- 📼 Record to Disk or Local Storage
- ⏱ Slow Down or Speed Up Time

================================================
FILE: docs/_sidebar.md
================================================
- Getting Started
- [Overview](README.md)
- [Quick Start](quick-start.md)
- [Examples](examples.md)
- Test Frameworks
- [Mocha](test-frameworks/mocha.md)
- [QUnit](test-frameworks/qunit.md)
- [Jest & Jasmine](test-frameworks/jest-jasmine.md)
- Frameworks
- [Ember CLI](frameworks/ember-cli.md)
- Adapters
- [Fetch](adapters/fetch.md)
- [Node HTTP](adapters/node-http.md)
- [Playwright](adapters/playwright.md)
- [Puppeteer](adapters/puppeteer.md)
- [XHR](adapters/xhr.md)
- [Custom](adapters/custom.md)
- Persisters
- [File System](persisters/fs.md)
- [Local Storage](persisters/local-storage.md)
- [REST](persisters/rest.md)
- [Custom](persisters/custom.md)
- Client Server
- [Overview](server/overview.md)
- [API](server/api.md)
- [Events & Middleware](server/events-and-middleware.md)
- [Route Handler](server/route-handler.md)
- [Request](server/request.md)
- [Response](server/response.md)
- [Event](server/event.md)
- Node Server
- [Overview](node-server/overview.md)
- [Express Integrations](node-server/express-integrations.md)
- CLI
- [Overview](cli/overview.md)
- [Commands](cli/commands.md)
- Reference
- [API](api.md)
- [Configuration](configuration.md)
- [Contributing](CONTRIBUTING.md)
================================================
FILE: docs/adapters/custom.md
================================================
# Custom Adapter
If you need to create your own adapter or modify an pre-existing one, you've come
to the right page!
## Creating a Custom Adapter
The `@pollyjs/adapter` package provides an extendable base adapter class that
contains core logic dependent on by the [Fetch](adapters/fetch)
& [XHR](adapters/xhr) adapters.
### Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/adapter -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/adapter -D
```
### Usage
```js
import Adapter from '@pollyjs/adapter';
class CustomAdapter extends Adapter {
static get id() {
return 'custom';
}
onConnect() {
/* Do something when the adapter is connect to */
}
onDisconnect() {
/* Do something when the adapter is disconnected from */
}
async onFetchResponse(pollyRequest) {
/* Do something when the adapter is connect to */
}
/* optional */
async onRespond(pollyRequest) {
const { statusCode, body, headers } = pollyRequest.response;
/* Deliver the response to the user */
}
}
```
The `Adapter` class provides the `handleRequest()` method which can be
called from `onConnect`. It accepts request parameters and returns a
PollyRequest object with a `response` property.
The `onFetchResponse` method takes a PollyRequest object, makes a real HTTP
request and returns the response as a `{ statusCode, headers, body }` object,
where `body` is a string.
The `onRespond()` method makes sure that the response has been delivered
to the user. `pollyjs.flush()` will wait for all `onResponds()` calls to
finish. You can omit the implementation of this method if no asynchronous
delivery is required.
### Simple Fetch adapter example
The following is a simple example of implementing an adapter for `fetch`. For
full examples, please refer to the source code for the
[Fetch](https://github.com/Netflix/pollyjs/blob/master/packages/@pollyjs/adapter-fetch/src/index.js)
& [XHR](https://github.com/Netflix/pollyjs/blob/master/packages/%40pollyjs/adapter-xhr/src/index.js)
adapters.
```js
class FetchAdapter extends Adapter {
static get id() {
return 'fetch';
}
onConnect() {
this.originalFetch = window.fetch;
window.fetch = async (url, options = {}) => {
const { response } = await this.handleRequest({
url,
method: options.method,
headers: options.headers,
body: options.body
});
return new Response(response.body, {
status: response.statusCode,
statusText: response.statusText,
headers: response.headers
});
};
}
onDisconnect() {
window.fetch = this.originalFetch;
}
async onFetchResponse(pollyRequest) {
const response = await this.originalFetch([
pollyRequest.url,
{
method: pollyRequest.method,
headers: pollyRequest.headers,
body: pollyRequest.body
}
]);
return {
statusCode: response.status,
headers: serializeHeaders(response.headers),
body: await response.text()
};
}
}
```
## Extending from an Existing Adapter
The `@pollyjs/core` package exports the `XHRAdapter` and `FetchAdapter` classes,
allowing you to modify them as needed.
```js
import XHRAdapter from '@pollyjs/adapter-xhr';
import FetchAdapter from '@pollyjs/adapter-fetch';
class CustomXHRAdapter extends XHRAdapter {}
class CustomFetchAdapter extends FetchAdapter {}
```
## Registering & Connecting to a Custom Adapter
You can register and connect to a custom adapter by passing an array to the `adapters`
config where the first element is the name of your adapter and the second is the
adapter class.
```js
// Register and connect to a custom adapter:
new Polly('Custom Adapter', {
adapters: [MyCustomAdapterClass]
});
// Register and connect to a custom adapter via .configure():
const polly = new Polly('Custom Adapter');
polly.configure({
adapters: [MyCustomAdapterClass]
});
```
================================================
FILE: docs/adapters/fetch.md
================================================
# Fetch Adapter
The fetch adapter wraps the global fetch method for seamless
recording and replaying of requests.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/adapter-fetch -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/adapter-fetch -D
```
## Usage
Use the [configure](api#configure), [connectTo](api#connectto), and
[disconnectFrom](api#disconnectfrom) APIs to connect or disconnect from the
adapter.
```js
import { Polly } from '@pollyjs/core';
import FetchAdapter from '@pollyjs/adapter-fetch';
// Register the fetch adapter so its accessible by all future polly instances
Polly.register(FetchAdapter);
const polly = new Polly('', {
adapters: ['fetch']
});
// Disconnect using the `configure` API
polly.configure({ adapters: [] });
// Reconnect using the `connectTo` API
polly.connectTo('fetch');
// Disconnect using the `disconnectFrom` API
polly.disconnectFrom('fetch');
```
## Options
### context
_Type_: `Object`
_Default_: `global|self|window`
The context object which contains the fetch API. Typically this is `window` or `self` in the browser and `global` in node.
**Example**
```js
polly.configure({
adapters: ['fetch'],
adapterOptions: {
fetch: {
context: window
}
}
});
```
================================================
FILE: docs/adapters/node-http.md
================================================
# Node HTTP Adapter
The node-http adapter provides a low level nodejs http request adapter that uses [nock](https://github.com/nock/nock) to patch the [http](https://nodejs.org/api/http.html) and [https](https://nodejs.org/api/https.html) modules in nodejs for seamless recording and replaying of requests.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/adapter-node-http -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/adapter-node-http -D
```
## Usage
Use the [configure](api#configure), [connectTo](api#connectto), and
[disconnectFrom](api#disconnectfrom) APIs to connect or disconnect from the
adapter.
```js
import { Polly } from '@pollyjs/core';
import NodeHttpAdapter from '@pollyjs/adapter-node-http';
// Register the node http adapter so its accessible by all future polly instances
Polly.register(NodeHttpAdapter);
const polly = new Polly('', {
adapters: ['node-http']
});
// Disconnect using the `configure` API
polly.configure({ adapters: [] });
// Reconnect using the `connectTo` API
polly.connectTo('node-http');
// Disconnect using the `disconnectFrom` API
polly.disconnectFrom('node-http');
```
================================================
FILE: docs/adapters/playwright.md
================================================
# Playwright Adapter
The 3rd party [Playwright](https://playwright.dev/) adapter is provided by [@gribnoysup](https://github.com/redabacha). Please follow the readme below for installation and usage instructions.
[README.md](https://raw.githubusercontent.com/redabacha/polly-adapter-playwright/master/README.md ':include :type=markdown')
================================================
FILE: docs/adapters/puppeteer.md
================================================
# Puppeteer Adapter
The [Puppeteer](https://pptr.dev/) adapter attaches events to a given
[page](https://pptr.dev/#?product=Puppeteer&show=api-class-page) instance allowing
you to get the full power of Polly and Puppeteer.
## Installation
?> **NOTE** If you're using Puppeteer 1.7 or 1.8, you'll experience issues using passthrough requests. Please upgrade to the latest version of Puppeteer or use a version prior to 1.7.
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/adapter-puppeteer -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/adapter-puppeteer -D
```
## Usage
Use the [configure](api#configure), [connectTo](api#connectto), and
[disconnectFrom](api#disconnectfrom) APIs to connect or disconnect from the
adapter.
```js
import { Polly } from '@pollyjs/core';
import PuppeteerAdapter from '@pollyjs/adapter-puppeteer';
// Register the puppeteer adapter so its accessible by all future polly instances
Polly.register(PuppeteerAdapter);
const browser = await puppeteer.launch();
const page = await this.browser.newPage();
await page.setRequestInterception(true);
const polly = new Polly('', {
adapters: ['puppeteer'],
adapterOptions: {
puppeteer: { page }
}
});
// Disconnect using the `configure` API
polly.configure({ adapters: [] });
// Reconnect using the `connectTo` API
polly.connectTo('puppeteer');
// Disconnect using the `disconnectFrom` API
polly.disconnectFrom('puppeteer');
```
## Options
### page
_Type_: [Page](https://pptr.dev/#?product=Puppeteer&show=api-class-page)
_Default_: `null`
!> **NOTE:** This is a _required_ option.
The Puppeteer page instance Polly should attach events to in order to intercept
requests.
**Example**
```js
const browser = await puppeteer.launch();
const page = await this.browser.newPage();
await page.setRequestInterception(true);
polly.configure({
adapters: ['puppeteer'],
adapterOptions: {
puppeteer: { page }
}
});
await page.goto('http://netflix.com');
```
### requestResourceTypes
_Type_: `Array`
_Default_: `['xhr', 'fetch']`
The request [resource types](https://pptr.dev/#?product=Puppeteer&show=api-requestresourcetype)
to intercept.
**Example**
```js
polly.configure({
adapterOptions: {
puppeteer {
requestResourceTypes: ['xhr']
}
}
});
```
================================================
FILE: docs/adapters/xhr.md
================================================
# XHR Adapter
The XHR adapter uses Sinon's [Nise](https://github.com/sinonjs/nise) library
to fake the global `XMLHttpRequest` object while wrapping the native one to allow
for seamless recording and replaying of requests.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/adapter-xhr -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/adapter-xhr -D
```
## Usage
Use the [configure](api#configure), [connectTo](api#connectto), and
[disconnectFrom](api#disconnectfrom) APIs to connect or disconnect from the
adapter.
```js
import { Polly } from '@pollyjs/core';
import XHRAdapter from '@pollyjs/adapter-xhr';
// Register the xhr adapter so its accessible by all future polly instances
Polly.register(XHRAdapter);
const polly = new Polly('', {
adapters: ['xhr']
});
// Disconnect using the `configure` API
polly.configure({ adapters: [] });
// Reconnect using the `connectTo` API
polly.connectTo('xhr');
// Disconnect using the `disconnectFrom` API
polly.disconnectFrom('xhr');
```
## Options
### context
_Type_: `Object`
_Default_: `global|self|window`
The context object which contains the XMLHttpRequest object. Typically this is `window` or `self` in the browser and `global` in node.
**Example**
```js
polly.configure({
adapters: ['xhr'],
adapterOptions: {
xhr: {
context: window
}
}
});
```
================================================
FILE: docs/api.md
================================================
# API
## Constructor
Create a new Polly instance.
| Param | Type | Description |
| ------------- | -------- | ------------------------------------------------------------------------- |
| recordingName | `String` | Name of the [recording](api#recordingName) to store the recordings under. |
| config | `Object` | [Configuration](configuration) object |
| **Returns** | `Polly` | |
**Example**
```js
new Polly('', {
/* ... */
});
```
## Events
### create
Emitted when a Polly instance gets created.
!> This is a synchronous event.
**Example**
```js
const listener = polly => {
/* Do Something */
};
Polly.on('create', listener);
Polly.off('create', listener);
Polly.once('create', polly => {
/* Do Something Once */
});
```
### stop
Emitted when a Polly instance has successfully stopped.
**Example**
```js
const listener = polly => {
/* Do Something */
};
Polly.on('stop', listener);
Polly.off('stop', listener);
Polly.once('stop', polly => {
/* Do Something Once */
});
```
## Properties
### recordingName
_Type_: `String`
_Default_: `null`
The recording name the recordings will be stored under. The provided name is
sanitized as well as postfixed with a GUID.
**Example**
```js
new Polly('Wants a Cracker', {
/* ... */
});
```
Will save recordings to the following file:
```text
recordings
└── Wants-a-Cracker_1234
└── recording.json
```
**Example**
?> A recording can also have slashes to better organize recordings.
```js
new Polly('Wants a Cracker/Cheddar');
```
Will save recordings to the following file:
```text
recordings
└── Wants-a-Cracker_1234
└── Cheddar_5678
└── recording.json
```
### mode
_Type_: `String`
_Default_: `'replay'`
The current [mode](configuration#mode) polly is in.
**Example**
```js
const polly = new Polly();
polly.mode; // → 'replay'
polly.record();
polly.mode; // → 'record'
```
### persister
_Type_: `Persister`
_Default_: `null`
The persister used to find and save recordings.
### server
_Type_: `Server`
_Default_: `Server`
Every polly instance has a reference to a [client-side server](server/overview) which you can leverage
to gain full control of all HTTP interactions as well as dictate how the Polly instance
should handle them.
```js
const { server } = polly;
server.get('/movies').passthrough();
server.get('/series').intercept((req, res) => res.sendStatus(200));
```
## Methods
### configure
Configure polly with the given configuration object.
| Param | Type | Description |
| ------ | -------- | ------------------------------------- |
| config | `Object` | [Configuration](configuration) object |
**Example**
```js
polly.configure({ recordIfMissing: false });
```
### record
Puts polly in recording mode. All requests going forward will
be sent to the server and their responses will be recorded.
**Example**
```js
polly.record();
```
### replay
Puts polly in replay mode. All requests going forward will be
played back from a saved recording.
**Example**
```js
polly.replay();
```
### passthrough
Puts polly in pass-through mode. All requests going forward will pass-through
directly to the server without being recorded or replayed.
**Example**
```js
polly.passthrough();
```
### pause
Disconnects the polly instance from all connected adapters. This ensures that
no requests will be handled by the polly instance until calling [play](api#play)
or manually connecting to a new adapter via [connectTo](api#connectTo). The
previously connected adapters will be saved and can be restored by
calling [play](api#play).
?> If using the [Puppeteer Adapter](adapters/puppeteer), you'll need to also
disable request interception via `await page.setRequestInterception(false)`.
**Example**
```js
await fetch('/api/not-a-secret');
polly.pause();
// This and all subsequent requests will no longer be handled by polly
await fetch('/api/secret');
```
### play
Reconnects to the adapters that were disconnected when [pause](api#pause)
was called.
?> If using the [Puppeteer Adapter](adapters/puppeteer), you'll need to also
enable request interception via `await page.setRequestInterception(true)`.
**Example**
```js
await fetch('/api/not-a-secret');
polly.pause();
// This and all subsequent requests will no longer be handled by polly
await fetch('/api/secret');
polly.play();
// This and all subsequent requests will again be handled by polly
await fetch('/api/not-a-secret');
```
### stop
Persist all recordings and disconnect from all adapters.
!> This method is `async` and will resolve once all recordings have
persisted and the instance has successfully torn down.
| Param | Type | Description |
| ------- | --------- | ----------- |
| Returns | `Promise` | |
**Example**
```js
await polly.stop();
```
### connectTo
Connect to an adapter.
| Param | Type | Description |
| ----- | ----------------- | --------------------------------------- |
| name | `String|Function` | The adapter name of class to connect to |
**Example**
```js
polly.connectTo('xhr');
polly.connectTo(XHRAdapter);
```
### disconnectFrom
Disconnect from an adapter.
| Param | Type | Description |
| ----- | ----------------- | -------------------------------------------- |
| name | `String|Function` | The adapter name of class to disconnect from |
**Example**
```js
polly.disconnectFrom('xhr');
polly.disconnectFrom(XHRAdapter);
```
### disconnect
Disconnect from all connected adapters.
**Example**
```js
polly.disconnect();
```
### flush
Returns a Promise that resolves once all requests handled by Polly have resolved.
| Param | Type | Description |
| ------- | --------- | ----------- |
| Returns | `Promise` | |
**Example**
```js
await polly.flush();
```
================================================
FILE: docs/assets/styles.css
================================================
:root {
--theme-color: #e50914;
--theme-color-dark: #b20710;
--text-color-base: #2e2e46;
--text-color-secondary: #646473;
--text-color-tertiary: #81818e;
}
body {
font-size: 100%;
line-height: 1.5;
color: var(--text-color-base);
}
* {
text-decoration: none !important;
}
a {
transition: all 0.3s linear;
}
.github-corner {
z-index: 5;
}
/****** Cover Page ******/
section.cover {
padding-bottom: 112px; /* fixed footer (Netflix) height */
height: auto;
min-height: 100vh;
/**
* Intended to defeat this inline style on initial boot that flashes when on page load:
* https://github.com/docsifyjs/docsify/blob/8352a1e489abc2a7b6361fe02d696e1891a031cd/src/core/render/tpl.js#L56-L70
*/
background: #fff !important;
}
section.cover .cover-main {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
margin: 0;
padding: 32px 16px 0;
}
section.cover img {
width: 400px;
}
section.cover h1 {
margin: 0.625rem 0 1rem;
}
section.cover blockquote,
section.cover blockquote p {
margin: 0;
}
section.cover ul {
font-size: 1.25rem;
line-height: 2rem;
display: grid;
text-align: left;
grid-column-gap: 16px;
grid-row-gap: 20px;
grid-template-columns: repeat(2, 50%);
list-style: none;
max-width: unset;
margin: 1.5em 0;
}
section.cover ul li {
white-space: nowrap;
}
section.cover.show ~ .sidebar,
section.cover.show ~ .sidebar-toggle {
display: none;
}
.cover-main .netflix-logo {
position: fixed;
display: flex;
align-items: center;
background: #ffffff;
bottom: 0;
left: 0;
width: 100%;
padding: 40px;
z-index: 5;
}
.cover-main .netflix-logo .logo {
width: 125px;
height: 32px;
background: url('images/Netflix_Logo.png');
background-size: 100%;
background-repeat: no-repeat;
background-position: center center;
}
.cover-main .buttons {
width: 100%;
}
.cover-main .buttons a {
font-weight: 700;
position: relative;
display: inline-block;
padding: 12px 25px;
font-size: 14px;
text-align: center;
line-height: 18px;
color: #221f1f;
background: #fff;
outline: none;
border: none;
background-color: #fff;
-webkit-appearance: none;
-moz-appearance: none;
cursor: pointer;
margin: 0 1rem;
color: var(--theme-color);
overflow: hidden;
transition: color 0.25s cubic-bezier(0.215, 0.61, 0.355, 1);
vertical-align: baseline;
text-transform: uppercase;
}
.cover-main .buttons a:before,
.cover-main .buttons a:after {
content: '';
display: block;
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
border: 2px solid var(--theme-color);
box-sizing: border-box;
}
.cover-main .buttons a:after {
background: var(--theme-color);
transform: translateX(-101%);
transition: all 0.2s cubic-bezier(0.215, 0.61, 0.355, 1);
}
.cover-main .buttons a:hover {
color: white;
box-shadow: 0 5px 16px rgba(229, 9, 20, 0.3);
}
.cover-main .buttons a:hover:after {
transform: translateX(0);
}
.cover-main .buttons a span {
position: relative;
z-index: 1;
}
@media (max-width: 850px) {
section.cover ul {
grid-template-columns: 100%;
padding: 0;
}
section.cover ul li {
text-align: center;
}
}
@media (max-width: 450px) {
section.cover ul li {
white-space: normal;
}
.cover-main .buttons a {
width: 100%;
margin: 0.2rem 0;
}
}
/****** Sidebar ******/
.sidebar .app-name-link img {
height: 150px;
}
.sidebar ul li a {
font-size: 15px;
}
.sidebar ul li a:hover {
color: var(--theme-color);
}
.app-sub-sidebar li:before {
display: none;
}
.sidebar .search .clear-button {
cursor: pointer;
}
/****** Sidebar Toggle ******/
.sidebar-toggle {
cursor: pointer;
}
body .sidebar-toggle {
background: none;
top: 1.5rem;
left: calc(300px + 1.5rem);
cursor: pointer;
width: 1.5rem;
height: 1.5rem;
padding: 0;
transition: left 0.25s ease-out;
}
body .sidebar-toggle span {
background-color: var(--theme-color);
height: 0.2rem;
width: 1.5rem;
position: absolute;
left: 0;
margin: 0;
transform-origin: 0;
border-radius: 1px;
}
body.close .sidebar-toggle {
transition: left 0.25s ease-out;
width: 1.5rem;
height: 1.5rem;
left: 1.5rem;
}
body.close .sidebar-toggle span {
transform-origin: center;
}
body .sidebar-toggle span:nth-child(1) {
top: 0;
}
body .sidebar-toggle span:nth-child(2) {
top: 0.5rem;
}
body .sidebar-toggle span:nth-child(3) {
top: 1rem;
}
.sidebar-toggle:hover {
opacity: 0.8;
}
.sidebar-toggle .sidebar-toggle-button:hover {
opacity: 1;
}
@media screen and (max-width: 768px) {
body .sidebar-toggle {
left: 1rem;
}
body.close .sidebar-toggle {
left: calc(300px + 1.5rem);
}
}
/****** Markdown General ******/
.markdown-section {
padding: 30px 30px 40px;
}
.markdown-section a {
text-decoration: none;
border-bottom: 0.1rem solid var(--theme-color);
transition: all 0.3s ease;
}
.markdown-section a:hover {
border-color: var(--theme-color-dark);
color: var(--theme-color-dark);
}
.markdown-section a.anchor {
border: none;
}
/****** Markdown Table ******/
.markdown-section table {
display: table;
}
.markdown-section table tr {
border-width: 0.15rem 0;
border-style: solid;
border-color: #f1f1f2;
}
.markdown-section table thead tr {
text-transform: uppercase;
font-size: 90%;
border-top: none;
}
.markdown-section table tbody tr:last-of-type {
border-bottom: none;
}
.markdown-section table tr:nth-child(2n) {
background-color: transparent;
}
.markdown-section table td,
.markdown-section table th {
border: none;
padding: 1.1rem 0.5rem;
text-align: left;
}
.markdown-section table td p {
margin: 0;
}
.markdown-section blockquote {
margin: 1em 0;
}
.markdown-section blockquote > p {
font-weight: 500;
}
.markdown-section em,
.markdown-section blockquote {
color: var(--text-color-tertiary);
}
/****** CODE HIGHLIGHTING ******/
.token.string {
color: #42b983;
}
.token.boolean,
.token.number {
color: var(--theme-color);
}
.lang-bash .token.function,
.lang-json .token.property {
color: #e96900;
}
/****** COPY TO CLIPBOARD ******/
.docsify-copy-code-button {
font-size: 0.7em !important;
}
================================================
FILE: docs/cli/commands.md
================================================
# Commands
As of right now, the Polly CLI only knows one command but expect to see more
in the near future!
## listen
Start up a node server and listen for Polly requests via the
[REST Persister](persisters/rest) to be able to record and replay recordings
to and from disk.
### Usage
```text
Usage: polly listen|l [options]
start the server and listen for requests
Options:
-H, --host host
-p, --port port number (default: 3000)
-n, --api-namespace api namespace (default: polly)
-d, --recordings-dir recordings directory (default: recordings)
-q, --quiet disable the logging
-h, --help output usage information
```
================================================
FILE: docs/cli/overview.md
================================================
# Overview
The `@pollyjs/cli` package provides a standalone CLI to quickly get you setup
and ready to go.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/cli -g
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn global add @pollyjs/cli
```
## Usage
```text
Usage: polly [options] [command]
Options:
-v, --version output the version number
-h, --help output usage information
Commands:
listen|l [options] start the server and listen for requests
```
================================================
FILE: docs/configuration.md
================================================
# Configuration
A Polly instance can be configured by passing a configuration object
to the constructor's 2nd argument:
```js
new Polly('', {
recordIfMissing: false
});
```
Or via the [configure](api#configure) method on the instance:
```js
const polly = new Polly('');
polly.configure({
recordIfMissing: false
});
```
## Defaults
[config.js](https://raw.githubusercontent.com/Netflix/pollyjs/master/packages/@pollyjs/core/src/defaults/config.js ':include :type=code')
## logLevel
_Type_: `'trace' | 'debug' | 'info' | 'warn' | 'error' | 'silent'`
_Default_: `'warn'`
Set the log level for the polly instance.
**Example**
```js
polly.configure({
logLevel: 'info'
});
```
## recordIfMissing
_Type_: `Boolean`
_Default_: `true`
If a request's recording is not found, pass-through to the server and
record the response.
**Example**
```js
polly.configure({
recordIfMissing: true
});
```
## recordFailedRequests
_Type_: `Boolean`
_Default_: `false`
If `false`, Polly will throw when attempting to persist any failed requests.
A request is considered to be a failed request when its response's status code
is `≥ 400`.
**Example**
```js
polly.configure({
recordFailedRequests: true
});
```
## flushRequestsOnStop
_Type_: `Boolean`
_Default_: `false`
Await any unresolved requests handled by the polly instance
(via [flush](api#flush)) when [stop](api#stop) is called.
**Example**
```js
polly.configure({
flushRequestsOnStop: true
});
```
## expiresIn
_Type_: `String`
_Default_: `null`
After how long the recorded request will be considered expired from the time
it was persisted. A recorded request is considered expired if the recording's
`startedDateTime` plus the current `expiresIn` duration is in the past.
**Example**
```js
polly.configure({
expiresIn: '30d5h10m' // expires in 30 days, 5 hours, and 10 minutes
});
polly.configure({
expiresIn: '5 min 10 seconds 100 milliseconds' // expires in 5 minutes, 10 seconds, and 100 milliseconds
});
```
## expiryStrategy
_Type_: `'warn' | 'error' | 'record'`
_Default_: `'warn'`
The strategy for what should occur when Polly tries to use an expired recording in `replay` mode. Can be one of the following:
- `warn`: Log a console warning about the expired recording.
- `error`: Throw an error.
- `record`: Re-record by making a new network request.
**Example**
```js
polly.configure({
expiryStrategy: 'error'
});
```
## mode
_Type_: `String`
_Default_: `'replay'`
The Polly mode. Can be one of the following:
- `replay`: Replay responses from recordings.
- `record`: Force Polly to record all requests. This will overwrite recordings that already exist.
- `passthrough`: Passes all requests through directly to the server without recording or replaying.
**Example**
```js
polly.configure({
mode: 'record'
});
```
## adapters
_Type_: `Array[String|Function]`
_Default_: `[]`
The adapter(s) polly will hook into.
**Example**
```js
import XHRAdapter from '@pollyjs/adapter-xhr';
import FetchAdapter from '@pollyjs/adapter-fetch';
// Register the xhr adapter so its accessible by all future polly instances
Polly.register(XHRAdapter);
polly.configure({
adapters: ['xhr', FetchAdapter]
});
```
## adapterOptions
_Type_: `Object`
_Default_: `{}`
Options to be passed into the adapters keyed by the adapter name.
?> **NOTE:** Check out the appropriate documentation pages for each adapter
for more details.
**Example**
```js
polly.configure({
adapterOptions: {
fetch: {
context: win
}
}
});
```
## persister
_Type_: `String|Function`
_Default_: `null`
The persister to use for recording and replaying requests.
**Example**
```js
import RESTPersister from '@pollyjs/persister-rest';
import LocalStoragePersister from '@pollyjs/persister-local-storage';
// Register the local-storage persister so its accessible by all future polly instances
Polly.register(LocalStoragePersister);
polly.configure({
persister: 'local-storage'
});
polly.configure({
persister: RESTPersister
});
```
## persisterOptions
_Type_: `Object`
_Default_: `{}`
Options to be passed into the persister keyed by the persister name.
?> **NOTE:** Check out the appropriate documentation pages for each persister
for more details.
**Example**
```js
polly.configure({
persisterOptions: {
rest: {
apiNamespace: '/polly'
}
}
});
```
### keepUnusedRequests
_Type_: `Boolean`
_Default_: `false`
When disabled, requests that have not been captured by the running Polly
instance will be removed from any previous recording. This ensures that a
recording will only contain the requests that were made during the lifespan
of the Polly instance. When enabled, new requests will be appended to the
recording file.
**Example**
```js
polly.configure({
persisterOptions: {
keepUnusedRequests: true
}
});
```
### disableSortingHarEntries
_Type_: `Boolean`
_Default_: `false`
When disabled, entries in the the final HAR will be sorted by the request's timestamp.
This is done by default to satisfy the HAR 1.2 spec but can be enabled to improve
diff readability when committing recordings to git.
**Example**
```js
polly.configure({
persisterOptions: {
disableSortingHarEntries: true
}
});
```
## timing
_Type_: `Function`
_Default_: `Timing.fixed(0)`
The timeout delay strategy used when replaying requests.
**Example**
```js
import { Timing } from '@pollyjs/core';
polly.configure({
// Replay requests at 300% the original speed to simulate a 3g connection
timing: Timing.relative(3.0)
});
polly.configure({
// Replay requests with a 200ms delay
timing: Timing.fixed(200)
});
```
## matchRequestsBy
_Type_: `Object`
_Default_:
```js
matchRequestsBy: {
method: true,
headers: true,
body: true,
order: true,
url: {
protocol: true,
username: true,
password: true,
hostname: true,
port: true,
pathname: true,
query: true,
hash: false
}
}
```
Request matching configuration. Each of these options are used to generate
a GUID for the request.
- ### method
_Type_: `Boolean | Function`
_Default_: `true`
The request method (e.g. `GET`, `POST`)
**Example**
```js
polly.configure({
matchRequestsBy: {
method: false
}
});
polly.configure({
matchRequestsBy: {
method(method, req) {
return method.toLowerCase();
}
}
});
```
- ### headers
_Type_: `Boolean | Function | Object`
_Default_: `true`
The request headers.
**Example**
```js
polly.configure({
matchRequestsBy: {
headers: false
}
});
polly.configure({
matchRequestsBy: {
headers(headers, req) {
delete headers['X-AUTH-TOKEN'];
return headers;
}
}
});
```
Specific headers can also be excluded with the following:
**Example**
```js
polly.configure({
matchRequestsBy: {
headers: {
exclude: ['X-AUTH-TOKEN']
}
}
});
```
- ### body
_Type_: `Boolean | Function`
_Default_: `true`
The request body.
!> Please make sure you do not modify the passed in body. If you need to make changes, create a copy of it first. The body function receives the actual request body — any modifications to it will result with it being sent out with the request.
**Example**
```js
polly.configure({
matchRequestsBy: {
body: false
}
});
polly.configure({
matchRequestsBy: {
body(body, req) {
const json = JSON.parse(body);
delete json.email;
return JSON.stringify(json);
}
}
});
```
- ### order
_Type_: `Boolean`
_Default_: `true`
The order the request came in. Take the following scenario:
```js
// Retrieve our model
let model = await fetch('/models/1').then((res) => res.json());
// Modify the model
model.foo = 'bar';
// Save the model with our new change
await fetch('/models/1', { method: 'POST', body: JSON.stringify(model) });
// Get our updated model
model = await fetch('/models/1').then((res) => res.json());
// Assert that our change persisted
expect(model.foo).to.equal('bar');
```
The order of the requests matter since the payload for the first and
last fetch are different.
**Example**
```js
polly.configure({
matchRequestsBy: {
order: false
}
});
```
- ### url
_Type_: `Boolean | Function | Object`
_Default_: `{ protocol: true, username: true, ... }`
The request url.
**Example**
```js
polly.configure({
matchRequestsBy: {
url: false
}
});
polly.configure({
matchRequestsBy: {
url(url, req) {
return url.replace('test', '');
}
}
});
polly.configure({
matchRequestsBy: {
url: {
protocol(protocol) {
return 'https:';
},
query: false
}
}
});
```
- ### url.protocol
_Type_: `Boolean | Function`
_Default_: `true`
The request url protocol (e.g. `http:`).
**Example**
```js
polly.configure({
matchRequestsBy: {
url: {
protocol: false
}
}
});
polly.configure({
matchRequestsBy: {
url: {
protocol(protocol, req) {
return 'https:';
}
}
}
});
```
- ### url.username
_Type_: `Boolean | Function`
_Default_: `true`
Username of basic authentication.
**Example**
```js
polly.configure({
matchRequestsBy: {
url: {
username: false
}
}
});
polly.configure({
matchRequestsBy: {
url: {
username(username, req) {
return 'username';
}
}
}
});
```
- ### url.password
_Type_: `Boolean | Function`
_Default_: `true`
Password of basic authentication.
**Example**
```js
polly.configure({
matchRequestsBy: {
url: {
password: false
}
}
matchRequestsBy: {
url: {
password(password, req) {
return 'password';
}
}
}
});
```
- ### url.hostname
_Type_: `Boolean | Function`
_Default_: `true`
Host name without port number.
**Example**
```js
polly.configure({
matchRequestsBy: {
url: {
hostname: false
}
}
});
polly.configure({
matchRequestsBy: {
url: {
hostname(hostname, req) {
return hostname.replace('.com', '.net');
}
}
}
});
```
- ### url.port
_Type_: `Boolean | Function`
_Default_: `true`
Port number.
**Example**
```js
polly.configure({
matchRequestsBy: {
url: {
port: false
}
}
});
polly.configure({
matchRequestsBy: {
url: {
port(port, req) {
return 3000;
}
}
}
});
```
- ### url.pathname
_Type_: `Boolean | Function`
_Default_: `true`
URL path.
**Example**
```js
polly.configure({
matchRequestsBy: {
url: {
pathname(pathname, req) {
return pathname.replace('/api/v1', '/api');
}
}
}
});
```
- ### url.query
_Type_: `Boolean | Function`
_Default_: `true`
Sorted query string.
**Example**
```js
polly.configure({
matchRequestsBy: {
url: {
query: false
}
}
});
polly.configure({
matchRequestsBy: {
url: {
query(query, req) {
return { ...query, token: '' };
}
}
}
});
```
- ### url.hash
_Type_: `Boolean | Function`
_Default_: `false`
The "fragment" portion of the URL including the pound-sign (`#`).
**Example**
```js
polly.configure({
matchRequestsBy: {
url: {
hash: true
}
}
});
polly.configure({
matchRequestsBy: {
url: {
hash(hash, req) {
return hash.replace(/token=[0-9]+/, '');
}
}
}
});
```
================================================
FILE: docs/examples.md
================================================
# Examples
## Client Server
**[Full Source](https://github.com/Netflix/pollyjs/tree/master/examples/client-server)**
[intercept.test.js](https://raw.githubusercontent.com/Netflix/pollyjs/master/examples/client-server/tests/intercept.test.js ':include :type=code')
[events.test.js](https://raw.githubusercontent.com/Netflix/pollyjs/master/examples/client-server/tests/events.test.js ':include :type=code')
## REST Persister
**[Full Source](https://github.com/Netflix/pollyjs/tree/master/examples/rest-persister)**
[package.json](https://raw.githubusercontent.com/Netflix/pollyjs/master/examples/rest-persister/package.json ':include :type=code')
[rest-persister.test.js](https://raw.githubusercontent.com/Netflix/pollyjs/master/examples/rest-persister/tests/rest-persister.test.js ':include :type=code')
## Node Fetch
**[Full Source](https://github.com/Netflix/pollyjs/tree/master/examples/node-fetch)**
[node-fetch.test.js](https://raw.githubusercontent.com/Netflix/pollyjs/master/examples/node-fetch/tests/node-fetch.test.js ':include :type=code')
## Puppeteer
**[Full Source](https://github.com/Netflix/pollyjs/tree/master/examples/puppeteer)**
[index.js](https://raw.githubusercontent.com/Netflix/pollyjs/master/examples/puppeteer/index.js ':include :type=code')
## Jest + Node Fetch
**[Full Source](https://github.com/Netflix/pollyjs/tree/master/examples/jest-node-fetch)**
[index.test.js](https://raw.githubusercontent.com/Netflix/pollyjs/master/examples/jest-node-fetch/__tests__/index.test.js ':include :type=code')
## TypeScript + Jest + Node Fetch
**[Full Source](https://github.com/Netflix/pollyjs/tree/master/examples/typescript-jest-node-fetch)**
[auto-setup-polly.ts](https://raw.githubusercontent.com/Netflix/pollyjs/master/examples/typescript-jest-node-fetch/src/utils/auto-setup-polly.ts ':include :type=code')
[github-api.test.ts](https://raw.githubusercontent.com/Netflix/pollyjs/master/examples/typescript-jest-node-fetch/src/github-api.test.ts ':include :type=code')
## Jest + Puppeteer
**[Full Source](https://github.com/Netflix/pollyjs/tree/master/examples/jest-puppeteer)**
[dummy-app.test.js](https://raw.githubusercontent.com/Netflix/pollyjs/master/examples/jest-puppeteer/__tests__/dummy-app.test.js ':include :type=code')
================================================
FILE: docs/frameworks/ember-cli.md
================================================
# Ember CLI
Installing the `@pollyjs/ember` addon will import and vendor the necessary
Polly.JS packages as well as register the [Express API](node-server/express-integrations)
required by the [REST Persister](persisters/rest).
?> **NOTE:** By default, this addon installs and registers the
[XHR](adapters/xhr) & [Fetch](adapters/fetch) adapters as well as the
[REST](persisters/rest) & [Local Storage](persisters/local-storage) persisters.
## Installation
```bash
ember install @pollyjs/ember
```
## Configuration
Addon and [server API configuration](node-server/overview#api-configuration) can be
be specified in `/config/polly.js`. The default configuration options are shown below.
```js
module.exports = function(env) {
return {
// Addon Configuration Options
enabled: env !== 'production',
// Server Configuration Options
server: {
apiNamespace: '/polly',
recordingsDir: 'recordings'
}
};
};
```
## Usage
Once installed and configured, you can import and use Polly as documented. Check
out the [Quick Start](quick-start#usage) documentation to get started.
?> For an even better testing experience, check out the provided
[QUnit Test Helper](test-frameworks/qunit)!
================================================
FILE: docs/index.html
================================================
Polly.JS
================================================
FILE: docs/node-server/express-integrations.md
================================================
# Express Integrations
The `@pollyjs/node-server` package exports a `registerExpressAPI` method which
takes in an [Express](http://expressjs.com/) app and a config to register the
necessary routes to be used with the REST Persister.
```js
const { registerExpressAPI } = require('@pollyjs/node-server');
registerExpressAPI(app, config);
```
## Webpack DevServer
```js
const path = require('path');
const { registerExpressAPI } = require('@pollyjs/node-server');
const config = {
devServer: {
before(app) {
registerExpressAPI(app, config);
}
}
};
module.exports = config;
```
## Ember CLI
See the [Ember CLI Addon](frameworks/ember-cli) documentation for more details.
================================================
FILE: docs/node-server/overview.md
================================================
# Overview
The `@pollyjs/node-server` package provides a standalone node server as well as
an express integration to be able to support the [REST Persister](persisters/rest)
so recordings can be saved to and read from disk.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/node-server -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/node-server -D
```
## Server
This packages includes a fully working standalone node server that is pre-configured
with the necessary APIs and middleware to support the [REST Persister](persisters/rest).
The Server constructor accepts a configuration object that can be a combination
of the below listed Server & API options. Once instantiated, you will have
full access to the Express app via the `app` property.
```js
const { Server } = require('@pollyjs/node-server');
const server = new Server({
quiet: true,
port: 4000,
apiNamespace: '/polly'
});
// Add custom business logic to the express server
server.app.get('/custom', () => {
/* Add custom express logic */
});
// Start listening and attach extra logic to the http server
server.listen().on('error', () => {
/* Add http server error logic */
});
```
## Server Configuration
### port
_Type_: `Number`
_Default_: `3000`
```js
new Server({
port: 4000
});
```
### host
_Type_: `String`
_Default_: `undefined`
```js
new Server({
host: 'test.localhost'
});
```
### quiet
_Type_: `Boolean`
_Default_: `false`
Enable/Disable the logging middleware ([morgan](https://github.com/expressjs/morgan)).
```js
new Server({
quiet: true
});
```
### corsOptions
_Type_: `Object | Function`
_Default_: `undefined`
Options passed to the ([CORS](https://github.com/expressjs/cors)) middleware.
```js
new Server({
corsOptions: {
origin: 'http://localhost:4000',
credentials: true
}
});
```
## API Configuration
### recordingsDir
_Type_: `String`
_Default_: `'recordings'`
The root directory to store all recordings.
```js
new Server({
recordingsDir: '__recordings__'
});
registerExpressAPI(app, {
recordingsDir: '__recordings__'
});
```
### apiNamespace
_Type_: `String`
_Default_: `'polly'`
The namespace to mount the polly API on. This should really only be changed
if there is a conflict with the default apiNamespace.
!> If modified, you must provide the new `apiNamespace` to the client side Polly
instance via the [Persister Options](persisters/rest#apinamespace)
```js
new Server({
apiNamespace: '/polly'
});
registerExpressAPI(app, {
apiNamespace: '/polly'
});
```
### recordingSizeLimit
_Type_: `String`
_Default_: `'50mb'`
A recording size can not exceed 50mb by default. If your application exceeds this limit, bump this value to a reasonable limit.
```js
new Server({
recordingSizeLimit: '50mb'
});
registerExpressAPI(app, {
recordingSizeLimit: '50mb'
});
```
================================================
FILE: docs/persisters/custom.md
================================================
# Custom Persister
If you need to create your own persister or modify an pre-existing one, you've come
to the right page!
## Creating a Custom Persister
The `@pollyjs/persister` package provides an extendable base persister class that
contains core logic dependent on by the [REST](persisters/rest)
& [Local Storage](persisters/local-storage) persisters.
### Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/persister -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/persister -D
```
### Usage
```js
import Persister from '@pollyjs/persister';
class CustomPersister extends Persister {
static get id() {
return 'custom';
}
onFindRecording() {}
onSaveRecording() {}
onDeleteRecording() {}
}
```
For better usage examples, please refer to the source code for
the [REST](https://github.com/Netflix/pollyjs/blob/master/packages/%40pollyjs/core/src/persisters/rest/index.js) & [Local Storage](https://github.com/Netflix/pollyjs/blob/master/packages/%40pollyjs/core/src/persisters/local-storage/index.js) persisters.
## Extending from an Existing Persister
The `@pollyjs/core` package exports the `RESTPersister` and `LocalStoragePersister` classes,
allowing you to modify them as needed.
```js
import RESTPersister from '@pollyjs/persister-rest';
import LocalStoragePersister from '@pollyjs/persister-local-storage';
class CustomRESTPersister extends RESTPersister {}
class CustomLocalStoragePersister extends LocalStoragePersister {}
```
## Registering & Connecting to a Custom Persister
You can register and connect to a custom persister by passing an array to the `persister`
config where the first element is the name of your persister and the second is the
persister class.
```js
// Register and connect to a custom persister:
new Polly('Custom Persister', {
persister: MyCustomPersisterClass
});
// Register and connect to a custom persister via .configure():
const polly = new Polly('Custom Persister');
polly.configure({
persister: MyCustomPersisterClass
});
```
================================================
FILE: docs/persisters/fs.md
================================================
# File System Persister
Read and write recordings to and from the file system.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/persister-fs -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/persister-fs -D
```
## Usage
```js
import { Polly } from '@pollyjs/core';
import FSPersister from '@pollyjs/persister-fs';
// Register the fs persister so its accessible by all future polly instances
Polly.register(FSPersister);
new Polly('', {
persister: 'fs'
});
```
## Options
### recordingsDir
_Type_: `String`
_Default_: `'recordings'`
The root directory to store all recordings. Supports both relative and
absolute paths.
**Example**
```js
polly.configure({
persisterOptions: {
fs: {
recordingsDir: '__recordings__'
}
}
});
```
================================================
FILE: docs/persisters/local-storage.md
================================================
# Local Storage Persister
Read and write recordings to and from the browser's Local Storage.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/persister-local-storage -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/persister-local-storage -D
```
## Usage
```js
import { Polly } from '@pollyjs/core';
import LocalStoragePersister from '@pollyjs/persister-local-storage';
// Register the local-storage persister so its accessible by all future polly instances
Polly.register(LocalStoragePersister);
new Polly('', {
persister: 'local-storage'
});
```
## Options
### context
_Type_: `Object`
_Default_: `global|self|window`
The context object which contains the localStorage API.
Typically this is `window` or `self` in the browser and `global` in node.
**Example**
```js
polly.configure({
persisterOptions: {
'local-storage': {
context: window
}
}
});
```
### key
_Type_: `String`
_Default_: `'pollyjs'`
The localStorage key to store the recordings data under.
**Example**
```js
polly.configure({
persisterOptions: {
'local-storage': {
key: '__pollyjs__'
}
}
});
```
================================================
FILE: docs/persisters/rest.md
================================================
# REST Persister
Read and write recordings to and from the file system via a CRUD API hosted
on a server.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/persister-rest -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/persister-rest -D
```
## Setup
This library provides a fully functional [node server](node-server/overview)
as well as a [CLI](cli/overview) to get you up and running.
## Usage
```js
import { Polly } from '@pollyjs/core';
import RESTPersister from '@pollyjs/persister-rest';
// Register the rest persister so its accessible by all future polly instances
Polly.register(RESTPersister);
new Polly('', {
persister: 'rest'
});
```
## Options
### host
_Type_: `String`
_Default_: `'http://localhost:3000'`
The host that the API exists on.
**Example**
```js
polly.configure({
persisterOptions: {
rest: {
host: 'http://localhost.com:4000'
}
}
});
```
### apiNamespace
_Type_: `String`
_Default_: `'/polly'`
The API namespace.
The namespace the Polly API is mounted on. This should really only be changed
if there is a conflict with the default apiNamespace.
!> If modified, you must provide the new `apiNamespace` to the node server
via the [Node Server apiNamespace](node-server/overview#apinamespace) configuration
option.
**Example**
```js
polly.configure({
persisterOptions: {
rest: {
apiNamespace: '/polly'
}
}
});
```
================================================
FILE: docs/quick-start.md
================================================
# Quick Start
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/core -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/core -D
```
## How it Works
Once instantiated, Polly will hook into native implementations (such as fetch & XHR)
via adapters to intercept any outgoing requests. Depending on its current
[mode](configuration#mode) as well as rules defined via the
[client-side server](server/overview), the request will either be replayed, recorded,
passed-through, or intercepted.
## Adapters & Persisters
Before you start using Polly, you'll need to install the necessary adapters and
persisters depending on your application/environment. Adapters provide
functionality that allows Polly to intercept requests via different sources
(e.g. XHR, fetch, Puppeteer) while Persisters provide the functionality to read & write
recorded data (e.g. fs, local-storage).
Check out the appropriate documentation pages for each adapter and persister
for more details such as installation, usage, and available options.
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/adapter-{name} -D
npm install @pollyjs/persister-{name} -D
```
If you want to install them with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/adapter-{name} -D
yarn add @pollyjs/persister-{name} -D
```
Once installed, you can register the adapters and persisters with Polly so
they can easily be referenced by name later.
```js
import { Polly } from '@pollyjs/core';
import FetchAdapter from '@pollyjs/adapter-fetch';
import XHRAdapter from '@pollyjs/adapter-xhr';
import LocalStoragePersister from '@pollyjs/persister-local-storage';
Polly.register(FetchAdapter);
Polly.register(XHRAdapter);
Polly.register(LocalStoragePersister);
new Polly('', {
adapters: ['fetch', 'xhr'],
persister: 'local-storage'
});
```
## Using Polly in the Browser?
Polly fully supports native in-browser usage, but because browsers can't write
to disk in the same way as conventional applications considerations need to be
made for persisting recordings.
If permanent, long-term persistence is not required then you can simply use the
[Local Storage Persister](persisters/local-storage), which writes to
`window.localStorage`.
For conventional file system storage you will need to use the
[REST Persister](persisters/rest) which runs as a separate process listening for
PollyJS activity. The server can be run in 2 ways. Firstly via the provided
[CLI](cli/overview)'s [listen](cli/commands#listen) command:
```bash
npm install @pollyjs/cli -g
polly listen
```
However, secondly there is also a convenient
[Express Integration](node-server/express-integrations) that appends the REST
server's endpoints to an existing server such as
[Webpack's Dev Server](https://webpack.js.org/configuration/dev-server/).
## Usage
Now that you've installed and setup Polly, you're ready to fly. Lets take a
look at what a simple example test case would look like using Polly.
```js
import { Polly } from '@pollyjs/core';
import FetchAdapter from '@pollyjs/adapter-fetch';
import LocalStoragePersister from '@pollyjs/persister-local-storage';
/*
Register the adapters and persisters we want to use. This way all future
polly instances can access them by name.
*/
Polly.register(FetchAdapter);
Polly.register(LocalStoragePersister);
describe('Simple Example', function () {
it('fetches a post', async function () {
/*
Create a new polly instance.
Connect Polly to fetch. By default, it will record any requests that it
hasn't yet seen while replaying ones it has already recorded.
*/
const polly = new Polly('Simple Example', {
adapters: ['fetch'], // Hook into `fetch`
persister: 'local-storage', // Read/write to/from local-storage
logLevel: 'info' // Log requests to console
});
const response = await fetch(
'https://jsonplaceholder.typicode.com/posts/1'
);
const post = await response.json();
expect(response.status).to.equal(200);
expect(post.id).to.equal(1);
/*
Calling `stop` will persist requests as well as disconnect from any
connected adapters.
*/
await polly.stop();
});
});
```
See the Pen Polly.JS Simple Example on CodePen .
The first time the test runs, Polly will record the response for the
`fetch('https://jsonplaceholder.typicode.com/posts/1')` request that was made. You will
see the following in the console:
```text
Recorded ➞ GET https://jsonplaceholder.typicode.com/posts/1 200 • 48ms
```
Once the Polly instance is [stopped](api#stop-1), the persister will generate the
following [HAR](http://www.softwareishard.com/blog/har-12-spec/) file which will
be used to replay the response to that request when the test is rerun:
```json
{
"Simple-Example_823972681": {
"log": {
"_recordingName": "Simple Example",
"browser": {
"name": "Chrome",
"version": "70.0"
},
"creator": {
"comment": "persister:local-storage",
"name": "Polly.JS",
"version": "1.2.0"
},
"entries": [
{
"_id": "ffbc4836d419fc265c3b85cbe1b7f22e",
"_order": 0,
"cache": {},
"request": {
"bodySize": 0,
"cookies": [],
"headers": [],
"headersSize": 63,
"httpVersion": "HTTP/1.1",
"method": "GET",
"queryString": [],
"url": "https://jsonplaceholder.typicode.com/posts/1"
},
"response": {
"bodySize": 292,
"content": {
"mimeType": "application/json; charset=utf-8",
"size": 292,
"text": "{\n \"userId\": 1,\n \"id\": 1,\n \"title\": \"sunt aut facere repellat provident occaecati excepturi optio reprehenderit\",\n \"body\": \"quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto\"\n}"
},
"cookies": [],
"headers": [
{
"name": "cache-control",
"value": "public, max-age=14400"
},
{
"name": "content-type",
"value": "application/json; charset=utf-8"
},
{
"name": "expires",
"value": "Tue, 30 Oct 2018 22:52:42 GMT"
},
{
"name": "pragma",
"value": "no-cache"
}
],
"headersSize": 145,
"httpVersion": "HTTP/1.1",
"redirectURL": "",
"status": 200,
"statusText": "OK"
},
"startedDateTime": "2018-10-30T18:52:42.566Z",
"time": 18,
"timings": {
"blocked": -1,
"connect": -1,
"dns": -1,
"receive": 0,
"send": 0,
"ssl": -1,
"wait": 18
}
}
],
"pages": [],
"version": "1.2"
}
}
}
```
The next time the test is run, Polly will use the recorded response instead
of going out to the server to get a new one. You will see the following in the
console:
```text
Replayed ➞ GET https://jsonplaceholder.typicode.com/posts/1 200 • 1ms
```
## Client-Side Server
Every Polly instance has a reference to a [client-side server](server/overview)
which you can leverage to gain full control of all HTTP interactions as well as
dictate how the Polly instance should handle them.
Lets take a look at how we can modify our previous test case to test against a
post that does not exist.
```js
describe('Simple Client-Side Server Example', function () {
it('fetches an unknown post', async function () {
/*
Create a new polly instance.
Connect Polly to fetch. By default, it will record any requests that it
hasn't yet seen while replaying ones it has already recorded.
*/
const polly = new Polly('Simple Client-Side Server Example', {
adapters: ['fetch'], // Hook into `fetch`
persister: 'local-storage', // Read/write to/from local-storage
logLevel: 'info' // Log requests to console
});
const { server } = polly;
/*
Add a rule via the client-side server to intercept the
`https://jsonplaceholder.typicode.com/posts/404` request and return
an error.
*/
server
.get('https://jsonplaceholder.typicode.com/posts/404')
.intercept((req, res) => {
res.status(404).json({ error: 'Post not found.' });
});
const response = await fetch(
'https://jsonplaceholder.typicode.com/posts/404'
);
const post = await response.json();
expect(response.status).to.equal(404);
expect(post.error).to.equal('Post not found.');
/*
Calling `stop` will persist requests as well as disconnect from any
connected adapters.
*/
await polly.stop();
});
});
```
See the Pen Polly.JS Simple Client-Side Server Example on CodePen .
When the test executes, Polly will detect that we've set a custom intercept rule for
`https://jsonplaceholder.typicode.com/posts/404` and will deffer to the intercept handler
to handle the response for that request. You will see the following in the console:
```text
Intercepted ➞ GET https://jsonplaceholder.typicode.com/posts/404 404 • 1ms
```
## Test Helpers
Using Mocha or QUnit? We've got you covered! Checkout the [Mocha](test-frameworks/mocha) or
[QUnit](test-frameworks/qunit) documentation pages for detailed instructions
on how to use the provided test helpers.
================================================
FILE: docs/server/api.md
================================================
# API
## HTTP Methods
The `GET`, `PUT`, `POST`, `PATCH`, `DELETE`, `MERGE`, `HEAD`, and `OPTIONS` HTTP methods
have a corresponding method on the server instance.
```js
server.get('/ping');
server.put('/ping');
server.post('/ping');
server.patch('/ping');
server.delete('/ping');
server.merge('/ping');
server.head('/ping');
server.options('/ping');
```
Each of these methods returns a [Route Handler](server/route-handler.md) which
you can use to pass-through, intercept, and attach events to.
```js
server.get('/ping').passthrough();
server.put('/ping').intercept((req, res) => res.sendStatus(200));
server.post('/ping').on('request', req => {
/* Do Something */
});
server.patch('/ping').off('request');
```
## any
Declare [Events & Middleware](server/events-and-middleware#middleware) globally
or for a specific route.
**Example**
```js
server.any('/session/:id').on('request', (req, res) => {
req.query.email = 'test@netflix.com';
});
```
## host
Define a block where all methods will inherit the provided host.
**Example**
```js
server.host('http://netflix.com', () => {
// Middleware will be attached to the host
server.any().on('request', req => {});
server.get('/session').intercept(() => {}); // → http://netflix.com/session
});
```
## namespace
Define a block where all methods will inherit the provided namespace.
**Example**
```js
server.namespace('/api', () => {
// Middleware will be attached to the namespace
server.any().on('request', req => {});
server.get('/session').intercept(() => {}); // → /api/session
server.namespace('/v2', () => {
server.get('/session').intercept(() => {}); // → /api/v2/session
});
});
```
## timeout
Returns a promise that will resolve after the given number of milliseconds.
**Example**
```js
server.get('/ping').intercept(async (req, res) => {
await server.timeout(500);
res.sendStatus(200);
});
```
================================================
FILE: docs/server/event.md
================================================
# Event
## Properties
### type
_Type_: `String`
The event type. (e.g. `request`, `response`, `beforePersist`)
## Methods
### stopPropagation
If several event listeners are attached to the same event type, they are called in the order in which they were added. If `stopPropagation` is invoked during one such call, no remaining listeners will be called.
**Example**
```js
server.get('/session/:id').on('beforeResponse', (req, res, event) => {
event.stopPropagation();
res.setHeader('X-SESSION-ID', 'ABC123');
});
server.get('/session/:id').on('beforeResponse', (req, res, event) => {
// This will never be reached
res.setHeader('X-SESSION-ID', 'XYZ456');
});
```
================================================
FILE: docs/server/events-and-middleware.md
================================================
# Events & Middleware
## Events
Events can be attached to a server route using `.on()` and detached via
the `.off()` methods.
?> **NOTE:** Event handlers can be asynchronous. An `async` function can be used
or a `Promise` can be returned.
```js
// Events
server
.get('/')
.on('request', req => {})
.off('request');
// Passthrough w/ Events
server
.get('/')
.passthrough()
.on('beforeResponse', (req, res) => {})
.off('beforeResponse');
// Intercept w/ Events
server
.get('/', (req, res) => {})
.on('request', req => {})
.on('beforeResponse', (req, res) => {});
// Middleware w/ Events
server
.any('/')
.on('request', req => {})
.on('beforeResponse', (req, res) => {});
```
### request
Fires right before the request goes out.
| Param | Type | Description |
| ----- | ------------------------- | -------------------- |
| req | [Request](server/request) | The request instance |
| event | [Event](server/event) | The event instance |
**Example**
```js
server.get('/session').on('request', req => {
req.headers['X-AUTH'] = '';
req.query.email = 'test@app.com';
});
```
### beforeResponse
Fires right before the response materializes and the promise resolves.
| Param | Type | Description |
| ----- | --------------------------- | --------------------- |
| req | [Request](server/request) | The request instance |
| res | [Response](server/response) | The response instance |
| event | [Event](server/event) | The event instance |
**Example**
```js
server.get('/session').on('beforeResponse', (req, res) => {
res.setHeader('X-AUTH', '');
});
```
### response
Fires right after the response has been finalized for the request but before
the response materializes and the promise resolves.
| Param | Type | Description |
| ----- | --------------------------- | --------------------- |
| req | [Request](server/request) | The request instance |
| res | [Response](server/response) | The response instance |
| event | [Event](server/event) | The event instance |
**Example**
```js
server.get('/session').on('response', (req, res) => {
console.log(
`${req.url} took ${req.responseTime}ms with a status of ${res.statusCode}.`
);
});
```
### beforePersist
Fires before the request/response gets persisted.
| Param | Type | Description |
| --------- | ------------------------- | ------------------------------------ |
| req | [Request](server/request) | The request instance |
| recording | `Object` | The recording that will be persisted |
| event | [Event](server/event) | The event instance |
**Example**
```js
server.any().on('beforePersist', (req, recording) => {
recording.request = encrypt(recording.request);
recording.response = encrypt(recording.response);
});
```
### beforeReplay
Fires after retrieving the recorded request/response from the persister
and before the recording materializes into a response.
| Param | Type | Description |
| --------- | ------------------------- | ----------------------- |
| req | [Request](server/request) | The request instance |
| recording | `Object` | The retrieved recording |
| event | [Event](server/event) | The event instance |
**Example**
```js
server.any().on('beforeReplay', (req, recording) => {
recording.request = decrypt(recording.request);
recording.response = decrypt(recording.response);
});
```
### error
Fires when any error gets emitted during the request life-cycle.
| Param | Type | Description |
| ----- | ------------------------- | -------------------- |
| req | [Request](server/request) | The request instance |
| error | Error | The error |
| event | [Event](server/event) | The event instance |
**Example**
```js
server.any().on('error', (req, error) => {
console.error(error);
process.exit(1);
});
```
### abort
Fires when a request is aborted.
| Param | Type | Description |
| ----- | ------------------------- | -------------------- |
| req | [Request](server/request) | The request instance |
| event | [Event](server/event) | The event instance |
**Example**
```js
server.any().on('abort', req => {
console.error('Request aborted.');
process.exit(1);
});
```
## Middleware
Middleware can be added via the `.any()` method.
?> **NOTE:** Middleware events will be executed by the order in which they were
declared.
### Global Middleware
The following is an example of a global middleware that will be attached to all
routes. This middleware in specific overrides the `X-Auth-Token` with a test token.
```js
server.any().on('request', (req, res) => {
req.headers['X-Auth-Token'] = 'abc123';
});
```
### Route Level Middleware
The following is an example of a route level middleware that will be attached to
any route that matches `/session/:id`. This middleware in specific overrides
the email query param with that of a test email.
```js
server.any('/session/:id').on('request', (req, res) => {
req.query.email = 'test@netflix.com';
});
```
================================================
FILE: docs/server/overview.md
================================================
# Overview
Every polly instance has a reference to a client-side server which you can leverage
to gain full control of all HTTP interactions as well as dictate how the Polly instance
should handle them.
## Usage
```js
const polly = new Polly('');
const { server } = polly;
// Events & Middleware
server.any().on('request', (req, res) => {
req.headers['X-Auth-Token'] = 'abc123';
});
// Intercept requests
server.get('/session').intercept((req, res) => {
res.status(200).json({ user: { email: 'test@netflix.com' } });
});
// Passthrough requests
server.get('/coverage').passthrough();
```
## Defining Routes
The server uses [Route Recognizer](https://github.com/tildeio/route-recognizer)
under the hood. This allows you to define static routes, as well as dynamic,
and starred segments.
**Example**
```js
// Static Routes
server.get('/api/v2/users').intercept((req, res) => {
res.sendStatus(200);
});
// Dynamic Segments
server.get('http://netflix.com/movies/:id').intercept((req, res) => {
console.log(req.params.id); // http://netflix.com/movies/1 → '1'
res.sendStatus(200);
});
// Starred Segments
server.get('/secrets/*path').intercept((req, res) => {
console.log(req.params.path); // /secrets/foo/bar → 'foo/bar'
res.status(401).send('Shhh!');
});
```
### Multi Route Handlers
HTTPS methods as well as `.any()` accept a single string
as well as an array of strings.
**Example**
```js
// Match against '/api/v2/users' as well as any child route
server.get(['/api/v2/users', '/api/v2/users/*path']).passthrough();
// Register the same event handler on both '/session' and '/users/session'
server.any(['/session', '/users/session']).on('request', () => {});
```
================================================
FILE: docs/server/request.md
================================================
# Request
## Properties
### method
_Type_: `String`
The request method. (e.g. `GET`, `POST`, `DELETE`)
### url
_Type_: `String`
The request URL.
### protocol
_Type_: `String`
The request url protocol. (e.g. `http://`, `https:`)
### hostname
_Type_: `String`
The request url host name. (e.g. `localhost`, `netflix.com`)
### port
_Type_: `String`
The request url port. (e.g. `3000`)
### pathname
_Type_: `String`
The request url path name. (e.g. `/session`, `/movies/1`)
### hash
_Type_: `String`
The request url hash.
### headers
_Type_: `Object`
_Default_: `{}`
The request headers.
### body
_Type_: `any`
The request body.
### query
_Type_: `Object`
_Default_: `{}`
The request url query parameters.
### params
_Type_: `Object`
_Default_: `{}`
The matching route's path params.
**Example**
```js
server.get('/movies/:id').intercept((req, res) => {
console.log(req.params.id);
});
```
### recordingName
_Type_: `String`
The recording the request should be recorded under.
## Methods
### getHeader
Get a header with a given name.
| Param | Type | Description |
| ----------- | ------------------- | ---------------------- |
| name | `String` | The name of the header |
| **Returns** | `String` \| `Array` | The header value |
**Example**
```js
req.getHeader('Content-Type'); // → application/json
```
### setHeader
Set a header with a given name. If the value is `null` or `undefined`, the header will be
removed.
| Param | Type | Description |
| ----------- | ------------------------- | ------------------------ |
| name | `String` | The name of the header |
| value | `String` \| `Array` | The value for the header |
| **Returns** | [Request](server/request) | The current request |
**Example**
```js
req.setHeader('Content-Length', 42);
```
### setHeaders
Add multiple headers at once. If a value is `null` or `undefined`, the header will be
removed.
| Param | Type | Description |
| ----------- | ------------------------- | --------------------------------- |
| headers | `Object` | The headers to add to the request |
| **Returns** | [Request](server/request) | The current request |
**Example**
```js
req.setHeaders({
Accept: ['text/html', 'image/*'],
'Content-Type': 'application/json',
'Content-Length': 42
});
```
### removeHeader
Remove a header with the given name.
| Param | Type | Description |
| ----------- | ------------------------- | ---------------------- |
| name | `String` | The name of the header |
| **Returns** | [Request](server/request) | The current request |
**Example**
```js
req.removeHeader('Content-Length');
```
### removeHeaders
Remove multiple headers at once.
| Param | Type | Description |
| ----------- | ------------------------- | -------------------------------------- |
| headers | `Array` | The headers to remove from the request |
| **Returns** | [Request](server/request) | The current request |
**Example**
```js
req.removeHeaders(['Content-Type' 'Content-Length']);
```
### hasHeader
Returns 'true' or 'false' depending on if the request has the given header.
| Param | Type | Description |
| ----------- | --------- | ---------------------- |
| name | `String` | The name of the header |
| **Returns** | `Boolean` | |
**Example**
```js
req.hasHeader('X-AUTH'); // → false
```
### type
Sets the request's Content Type.
| Param | Type | Description |
| ----------- | ------------------------- | ------------------- |
| value | `String` | |
| **Returns** | [Request](server/request) | The current request |
### send
Sets the request's body.
- If the body is a `String`, it defaults the content type to `text/html` if does not exist.
- If the body is a `String` and no charset is found, a `utf-8` charset is appended to the content type.
- Body that is a `Boolean`, `Number`, or `Object` gets passed to the [json](#json) method.
| Param | Type | Description |
| ----------- | ------------------------- | ------------------- |
| body | `any` | |
| **Returns** | [Request](server/request) | The current request |
**Example**
```js
req.send('Hello World');
req.send(200);
req.send(true);
req.send();
```
### json
A shortcut method to set the content type to `application/json` if it hasn't
been set already, and call [send](#send) with the stringified object.
| Param | Type | Description |
| ----------- | ------------------------- | ------------------- |
| obj | `Object` | Object to send |
| **Returns** | [Request](server/request) | The current request |
**Example**
```js
req.json({ Hello: 'World' });
```
### jsonBody
A shortcut method that calls JSON.parse on the request's body.
!> This method will throw if the body is an invalid JSON string.
| Param | Type | Description |
| ----------- | -------- | -------------------- |
| **Returns** | `Object` | The JSON parsed body |
**Example**
```js
req.jsonBody();
```
### overrideRecordingName
Override the recording name for the request.
| Param | Type | Description |
| ------------- | -------- | ---------------------- |
| recordingName | `String` | The new recording name |
**Example**
```js
req.overrideRecordingName(req.hostname);
```
### configure
Override configuration options for the request.
| Param | Type | Description |
| ------ | -------- | ------------------------------------- |
| config | `Object` | [Configuration](configuration) object |
**Example**
```js
req.configure({ recordFailedRequests: true });
req.configure({ timing: Timing.relative(3.0) });
req.configure({ logLevel: 'info' });
```
================================================
FILE: docs/server/response.md
================================================
# Response
## Properties
### statusCode
_Type_: `Number`
_Default_: `undefined`
The response's status code.
### headers
_Type_: `Object`
_Default_: `{}`
The response's headers.
### body
_Type_: `String`
_Default_: `undefined`
The response's body.
## Methods
### status
Set the response's status code.
| Param | Type | Description |
| ----------- | --------------------------- | -------------------- |
| status | `Number` | Status code |
| **Returns** | [Response](server/response) | The current response |
**Example**
```js
res.status(200);
```
### getHeader
Get a header with a given name.
| Param | Type | Description |
| ----------- | ------------------- | ---------------------- |
| name | `String` | The name of the header |
| **Returns** | `String` \| `Array` | The header value |
**Example**
```js
res.getHeader('Content-Type'); // → application/json
```
### setHeader
Set a header with a given name. If the value is `null` or `undefined`, the header will be
removed.
| Param | Type | Description |
| ----------- | --------------------------- | ------------------------ |
| name | `String` | The name of the header |
| value | `String` \| `Array` | The value for the header |
| **Returns** | [Response](server/response) | The current response |
**Example**
```js
res.setHeader('Content-Length', 42);
```
### setHeaders
Add multiple headers at once. If a value is `null` or `undefined`, the header will be
removed.
| Param | Type | Description |
| ----------- | --------------------------- | ---------------------------------- |
| headers | `Object` | The headers to add to the response |
| **Returns** | [Response](server/response) | The current response |
**Example**
```js
res.setHeaders({
Accept: ['text/html', 'image/*'],
'Content-Type': 'application/json',
'Content-Length': 42
});
```
### removeHeader
Remove a header with the given name.
| Param | Type | Description |
| ----------- | --------------------------- | ---------------------- |
| name | `String` | The name of the header |
| **Returns** | [Response](server/response) | The current response |
**Example**
```js
res.removeHeader('Content-Length');
```
### removeHeaders
Remove multiple headers at once.
| Param | Type | Description |
| ----------- | --------------------------- | --------------------------------------- |
| headers | `Array` | The headers to remove from the response |
| **Returns** | [Response](server/response) | The current response |
**Example**
```js
res.removeHeaders(['Content-Type' 'Content-Length']);
```
### hasHeader
Returns 'true' or 'false' depending on if the response has the given header.
| Param | Type | Description |
| ----------- | --------- | ---------------------- |
| name | `String` | The name of the header |
| **Returns** | `Boolean` | |
**Example**
```js
res.hasHeader('X-AUTH'); // → false
```
### type
Sets the response's Content Type.
| Param | Type | Description |
| ----------- | --------------------------- | -------------------- |
| value | `String` | |
| **Returns** | [Response](server/response) | The current response |
**Example**
```js
res.type('application/json');
```
### send
Sets the response's body.
- If the body is a `String`, it defaults the content type to `text/html` if does not exist.
- If the body is a `String` and no charset is found, a `utf-8` charset is appended to the content type.
- Body that is a `Boolean`, `Number`, or `Object` gets passed to the [json](#json) method.
| Param | Type | Description |
| ----------- | --------------------------- | -------------------- |
| body | `any` | |
| **Returns** | [Response](server/response) | The current response |
**Example**
```js
res.send('Hello World');
res.send(200);
res.send(true);
res.send();
```
### sendStatus
A shortcut method to set the status to the given status code, set the content
type to `text/plain`, and call [send](#send).
| Param | Type | Description |
| ----------- | --------------------------- | -------------------- |
| status | `Number` | Status code |
| **Returns** | [Response](server/response) | The current response |
**Example**
```js
res.sendStatus(200);
```
### json
A shortcut method to set the content type to `application/json` if it hasn't
been set already, and call [send](#send) with the stringified object.
| Param | Type | Description |
| ----------- | --------------------------- | -------------------- |
| obj | `Object` | Object to send |
| **Returns** | [Response](server/response) | The current response |
**Example**
```js
res.json({ Hello: 'World' });
```
### jsonBody
A shortcut method that calls JSON.parse on the response's body.
!> This method will throw if the body is an invalid JSON string.
| Param | Type | Description |
| ----------- | -------- | -------------------- |
| **Returns** | `Object` | The JSON parsed body |
**Example**
```js
res.jsonBody();
```
### end
Freeze the response and headers so they can no longer be modified.
| Param | Type | Description |
| ----------- | --------------------------- | -------------------- |
| **Returns** | [Response](server/response) | The current response |
**Example**
```js
res.end();
```
================================================
FILE: docs/server/route-handler.md
================================================
# Route Handler
An object that is returned when calling any of the server's HTTP methods as well
as `server.any()`.
## Methods
?> **NOTE:** Event & Intercept handlers can be asynchronous. An `async`
function can be used or a `Promise` can be returned.
### on
Register an [event](server/events-and-middleware) handler.
?> **Tip:** You can attach multiple handlers to a single event. Handlers will be
called in the order they were declared.
| Param | Type | Description |
| ------------- | ---------- | ---------------------------------------------------------------- |
| eventName | `String` | The event name |
| handler | `Function` | The event handler |
| options | `Object` | The event handler options |
| options.times | `number` | Remove listener after being called the specified amount of times |
**Example**
```js
server
.get('/session')
.on('request', (req) => {
req.headers['X-AUTH'] = '';
req.query.email = 'test@app.com';
})
.on('request', () => {
/* Do something else */
})
.on(
'request',
() => {
/* Do something else twice */
},
{ times: 2 }
);
```
### once
Register a one-time [event](server/events-and-middleware) handler.
?> **Tip:** You can attach multiple handlers to a single event. Handlers will be
called in the order they were declared.
| Param | Type | Description |
| --------- | ---------- | ----------------- |
| eventName | `String` | The event name |
| handler | `Function` | The event handler |
**Example**
```js
server
.get('/session')
.once('request', (req) => {
req.headers['X-AUTH'] = '';
req.query.email = 'test@app.com';
})
.once('request', () => {
/* Do something else */
});
```
### off
Un-register an [event](server/events-and-middleware) handler. If no handler
is specified, all event handlers are un-registered for the given event name.
| Param | Type | Description |
| --------- | ---------- | ----------------- |
| eventName | `String` | The event name |
| handler | `Function` | The event handler |
**Example**
```js
const handler = () => {};
server
.get('/session')
.on('request', , handler)
.on('request', () => {})
.off('request', handler) /* Un-register the specified event/handler pair */
.off('request'); /* Un-register all handlers */
```
### intercept
Register an intercept handler. Once set, the [request](server/request) will
never go to server but instead defer to the provided handler to handle
the [response](server/response). If multiple intercept handlers have been
registered, each handler will be called in the order in which it was registered.
| Param | Type | Description |
| ------------- | ---------- | --------------------------------------------------------------- |
| handler | `Function` | The intercept handler |
| options | `Object` | The event handler options |
| options.times | `number` | Remove handler after being called the specified amount of times |
**Example**
```js
server.any('/session').intercept((req, res) => res.sendStatus(200));
server.any('/twice').intercept((req, res) => res.sendStatus(200), { times: 2 });
server.get('/session/:id').intercept((req, res, interceptor) => {
if (req.params.id === '1') {
res.status(200).json({ token: 'ABC123XYZ' });
} else if (req.params.id === '2') {
res.status(404).json({ error: 'Unknown Session' });
} else {
interceptor.abort();
}
});
```
#### Interceptor
_Extends [Event](server/event)_
The `intercept` handler receives a third `interceptor` argument that provides
some utilities.
##### abort
Calling the `abort` method on the interceptor tells the Polly instance to
continue handling the request as if it hasn't been intercepted. This allows you
to only intercept specific types of requests while opting out of others.
**Example**
```js
server.get('/session/:id').intercept((req, res, interceptor) => {
if (req.params.id === '1') {
res.status(200).json({ token: 'ABC123XYZ' });
} else {
interceptor.abort();
}
});
```
##### passthrough
Calling the `passthrough` method on the interceptor tells the Polly instance to
continue handling the request as if it has been declared as a passthrough.
This allows you to only intercept specific types of requests while passing
others through.
**Example**
```js
server.get('/session/:id').intercept((req, res, interceptor) => {
if (req.params.id === '1') {
res.status(200).json({ token: 'ABC123XYZ' });
} else {
interceptor.passthrough();
}
});
```
##### stopPropagation
If several intercept handlers are attached to the same route, they are called in the order in which they were added. If `stopPropagation` is invoked during one such call, no remaining handlers will be called.
**Example**
```js
// First call should return the user and not enter the 2nd handler
server
.get('/session/:id')
.times(1) // Remove this interceptor after it gets called once
.intercept((req, res, interceptor) => {
// Do not continue to the next intercept handler which handles the 404 case
interceptor.stopPropagation();
res.sendStatus(200);
});
server.delete('/session/:id').intercept((req, res) => res.sendStatus(204));
// Second call should 404 since the user no longer exists
server.get('/session/:id').intercept((req, res) => res.sendStatus(404));
await fetch('/session/1'); // --> 200
await fetch('/session/1', { method: 'DELETE' }); // --> 204
await fetch('/session/1'); // --> 404
```
### passthrough
Declare a route as a passthrough meaning any request that matches that route
will directly use the native implementation. Passthrough requests will not be
recorded.
| Param | Type | Description |
| ----------- | --------- | ----------------------------------------------------- |
| passthrough | `boolean` | Enable or disable the passthrough. Defaults to `true` |
**Example**
```js
server.any('/session').passthrough();
server.get('/session/1').passthrough(false);
```
### filter
Filter requests matched by the route handler with a predicate callback function.
This can be useful when trying to match a request by a part of the url, a header,
and/or parts of the request body.
The callback will receive the [Request](server/request)
as an argument. Return `true` to match the request, `false` otherwise.
?> Multiple filters can be chained together. They must all return `true` for the route handler to match the given request.
| Param | Type | Description |
| -------- | ---------- | ----------------------------- |
| callback | `Function` | The filter predicate function |
**Example**
```js
server
.any()
.filter(req => req.hasHeader('Authentication'));
.on('request', req => {
res.setHeader('Authentication', 'test123')
});
server
.get('/users/:id')
.filter(req => req.params.id === '1');
.intercept((req, res) => {
res.status(200).json({ email: 'user1@test.com' });
});
```
### times
Proceeding intercept and event handlers defined will be removed after being called the specified amount of times. The number specified is used as a default value and can be overridden by passing a custom `times` option to the handler.
| Param | Type | Description |
| ----- | -------- | -------------------------------------------------------------------------------------------------- |
| times | `number` | Default times value for proceeding handlers. If no value is provided, the default value is removed |
**Example**
```js
server
.any()
.times(2);
.on('request', req => {});
.intercept((req, res) => {});
.times()
.on('response', (req, res) => {});
// Is the same as:
server
.any()
.on('request', req => {}, { times: 2 });
.intercept((req, res) => {}, { times: 2 });
.on('response', (req, res) => {});
```
### configure
Override configuration options for the given route. All matching middleware and route level configs are merged together and the overrides are applied to the current
Polly instance's config.
!> The following options are not supported to be overridden via the server API:
`mode`, `adapters`, `adapterOptions`, `persister`, `persisterOptions`
| Param | Type | Description |
| ------ | -------- | ------------------------------------- |
| config | `Object` | [Configuration](configuration) object |
**Example**
```js
server.any('/session').configure({ recordFailedRequests: true });
server.get('/users/:id').configure({ timing: Timing.relative(3.0) });
server.get('/users/1').configure({ logLevel: 'info' });
```
### recordingName
Override the recording name for the given route. This allows for grouping common
requests to share a single recording which can drastically help de-clutter test
recordings.
For example, if your tests always make a `/users` or `/session` call, instead of
having each of those requests be recorded for every single test, you can use
this to create a common recording file for them.
| Param | Type | Description |
| ------------- | -------- | ------------------------------------------------------------------------- |
| recordingName | `String` | Name of the [recording](api#recordingName) to store the recordings under. |
**Example**
```js
server.any('/session').recordingName('User Session');
server.get('/users/:id').recordingName('User Data');
server
.get('/users/1')
.recordingName(); /* Fallback to the polly instance's recording name */
```
================================================
FILE: docs/test-frameworks/jest-jasmine.md
================================================
# Jest & Jasmine
Due to the nature of the Jest & Jasmine APIs and their restrictions on accessing
the current running test and its parent modules, we've decided to keep this test helper
as a 3rd party library provided by [@gribnoysup](https://github.com/gribnoysup).
The [setup-polly-jest](https://github.com/gribnoysup/setup-polly-jest) package provides a `setupPolly` utility which will setup a new polly instance for each test as well as stop it once the test has ended.
The Polly instance's recording name is derived from the current test name as well as its
parent module(s).
[README.md](https://raw.githubusercontent.com/gribnoysup/setup-polly-jest/master/README.md ':include :type=markdown')
================================================
FILE: docs/test-frameworks/mocha.md
================================================
# Mocha
The `@pollyjs/core` package provides a `setupMocha` utility which will setup
a new polly instance for each test as well as stop it once the test has ended.
The Polly instance's recording name is derived from the current test name as well as its
parent module(s).
| Param | Type | Description |
| ------ | -------- | ------------------------------------- |
| config | `Object` | [Configuration](configuration) object |
## Usage
### Simple Example {docsify-ignore}
```js
import { setupMocha as setupPolly } from '@pollyjs/core';
describe('Netflix Homepage', function() {
setupPolly({
/* default configuration options */
});
it('should be able to sign in', async function() {
/*
The setupPolly test helper creates a new polly instance which you can
access via `this.polly`. The recording name is generated based on the module
and test names.
*/
this.polly.configure({ recordIfMissing: false });
/* start: pseudo test code */
await visit('/login');
await fillIn('email', 'polly@netflix.com');
await fillIn('password', '@pollyjs');
await submit();
/* end: pseudo test code */
expect(location.pathname).to.equal('/browse');
/*
The setupPolly test helper will call `this.polly.stop()` when your test
has finished.
*/
});
});
```
### Intercept Example {docsify-ignore}
```js
import { setupMocha as setupPolly } from '@pollyjs/core';
describe('module', function() {
setupPolly();
it('does a thing', function() {
const { server } = this.polly;
server
.get('/ping')
.intercept((req, res) => res.sendStatus(200));
expect((await fetch('/ping').status).to.equal(200);
});
});
```
## Test Hook Ordering
Accessing `this.polly` during a test run after the polly instance has been
stopped and destroyed produces the following error:
!> _You are trying to access an instance of Polly that is no longer available._
If you need to do some work before the polly instance gets destroyed or just need more control on when each of the test hooks are called, `setupMocha` can be invoked as a function or accessed as an object with two methods: `setupMocha.beforeEach` and `setupMocha.afterEach`.
Instead of calling `setupMocha()`, register these two hooks separately in the order that fits within your test.
```js
import { setupMocha as setupPolly } from '@pollyjs/core';
describe('Netflix Homepage', function() {
setupPolly.beforeEach({
/* default configuration options */
});
afterEach(function() {
/* do something before the polly instance is destroyed... */
});
setupPolly.afterEach();
it('should be able to sign in', async function() {
/* ... */
});
});
```
## Configuring ember-mocha
If you're using [`ember-mocha`](https://github.com/emberjs/ember-mocha) be sure to use their built-in
[hooks API](https://github.com/emberjs/ember-mocha#setup-tests). Otherwise, Polly's mocha test helper will be unable to teardown Polly between tests.
An example of how to correctly setup Polly with `ember-mocha`:
```js
import { expect } from 'chai';
import { describe, it } from 'mocha';
import { setupApplicationTest } from 'ember-mocha';
import { visit, currentURL } from '@ember/test-helpers';
import { setupMocha as setupPolly } from '@pollyjs/core';
describe('Acceptance | Home', function() {
const hooks = setupApplicationTest();
setupPolly(
{
/* optional config */
},
hooks
);
it('can visit /', async function() {
await visit('/');
expect(currentURL()).to.equal('/');
});
});
```
================================================
FILE: docs/test-frameworks/qunit.md
================================================
# QUnit
The `@pollyjs/core` package provides a `setupQunit` utility which will setup
a new polly instance for each test as well as stop it once the test has ended.
The Polly instance's recording name is derived from the current test name as well as its
parent module(s).
| Param | Type | Description |
| ------ | -------- | ------------------------------------- |
| hooks | `Object` | QUnit hooks object |
| config | `Object` | [Configuration](configuration) object |
## Usage
### Simple Example {docsify-ignore}
```js
import { setupQunit as setupPolly } from '@pollyjs/core';
module('Netflix Homepage', function(hooks) {
setupPolly(hooks, {
/* default configuration options */
});
test('should be able to sign in', async function(assert) {
/*
The setupPolly test helper creates a new polly instance which you can
access via `this.polly`. The recording name is generated based on the module
and test names.
*/
this.polly.configure({ recordIfMissing: false });
/* start: pseudo test code */
await visit('/login');
await fillIn('email', 'polly@netflix.com');
await fillIn('password', '@pollyjs');
await submit();
/* end: pseudo test code */
assert.equal(location.pathname, '/browse');
/*
The setupPolly test helper will call `this.polly.stop()` when your test
has finished.
*/
});
});
```
### Intercept Example {docsify-ignore}
```js
import { setupQunit as setupPolly } from '@pollyjs/core';
module('module', function(hooks) {
setupPolly(hooks);
test('does a thing', function(assert) {
const { server } = this.polly;
server
.get('/ping')
.intercept((req, res) => res.sendStatus(200));
assert.equal((await fetch('/ping').status, 200);
});
});
```
## Test Hook Ordering
Accessing `this.polly` during a test run after the polly instance has been
stopped and destroyed produces the following error:
!> _You are trying to access an instance of Polly that is no longer available._
If you need to do some work before the polly instance gets destroyed or just need more control on when each of the test hooks are called, `setupQunit` can be invoked as a function or accessed as an object with two methods: `setupQunit.beforeEach` and `setupQunit.afterEach`.
Instead of calling `setupQunit()`, register these two hooks separately in the order that fits within your test.
```js
import { setupQunit as setupPolly } from '@pollyjs/core';
module('Netflix Homepage', function(hooks) {
setupPolly.beforeEach(hooks, {
/* default configuration options */
});
hooks.afterEach(function() {
/* do something before the polly instance is destroyed... */
});
setupPolly.afterEach(hooks);
test('should be able to sign in', async function() {
/* ... */
});
});
```
================================================
FILE: examples/.eslintrc.js
================================================
module.exports = {
env: {
node: true,
browser: true
}
};
================================================
FILE: examples/client-server/index.html
================================================
Client Server Tests
================================================
FILE: examples/client-server/package.json
================================================
{
"name": "@pollyjs/client-server-example",
"version": "0.1.0",
"private": true,
"license": "Apache-2.0",
"scripts": {
"test": "http-server -p 3000 -o -c-1 -s"
},
"devDependencies": {
"@pollyjs/adapter-fetch": "*",
"@pollyjs/core": "*",
"@pollyjs/persister-local-storage": "*",
"chai": "*",
"http-server": "*",
"mocha": "*"
}
}
================================================
FILE: examples/client-server/tests/events.test.js
================================================
/* global setupPolly */
describe('Events', function () {
setupPolly({
adapters: ['fetch'],
persister: 'local-storage'
});
it('can help test dynamic data', async function () {
const { server } = this.polly;
let numPosts = 0;
server
.get('https://jsonplaceholder.typicode.com/posts')
.on('response', (_, res) => {
numPosts = res.jsonBody().length;
});
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await res.json();
expect(res.status).to.equal(200);
expect(posts.length).to.equal(numPosts);
});
});
================================================
FILE: examples/client-server/tests/intercept.test.js
================================================
/* global setupPolly */
describe('Intercept', function () {
setupPolly({
adapters: ['fetch'],
persister: 'local-storage'
});
it('can mock valid responses', async function () {
const { server } = this.polly;
server
.get('https://jsonplaceholder.typicode.com/posts/:id')
.intercept((req, res) => {
res.status(200).json({
id: Number(req.params.id),
title: `Post ${req.params.id}`
});
});
const res = await fetch('https://jsonplaceholder.typicode.com/posts/42');
const post = await res.json();
expect(res.status).to.equal(200);
expect(post.id).to.equal(42);
expect(post.title).to.equal('Post 42');
});
it('can mock invalid responses', async function () {
const { server } = this.polly;
server
.get('https://jsonplaceholder.typicode.com/posts/404')
.intercept((_, res) => {
res.status(404).send('Post not found.');
});
const res = await fetch('https://jsonplaceholder.typicode.com/posts/404');
const text = await res.text();
expect(res.status).to.equal(404);
expect(text).to.equal('Post not found.');
});
it('can conditionally intercept requests', async function () {
const { server } = this.polly;
server
.get('https://jsonplaceholder.typicode.com/posts/:id')
.intercept((req, res, interceptor) => {
if (req.params.id === '42') {
res.status(200).send('Life');
} else {
// Abort out of the intercept handler and continue with the request
interceptor.abort();
}
});
let res = await fetch('https://jsonplaceholder.typicode.com/posts/42');
expect(res.status).to.equal(200);
expect(await res.text()).to.equal('Life');
res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
expect(res.status).to.equal(200);
expect((await res.json()).id).to.equal(1);
});
});
================================================
FILE: examples/client-server/tests/setup.js
================================================
// Expose common globals
window.PollyJS = window['@pollyjs/core'];
window.setupPolly = window.PollyJS.setupMocha;
window.expect = window.chai.expect;
// Register the fetch adapter and local-storage persister
window.PollyJS.Polly.register(window['@pollyjs/adapter-fetch']);
window.PollyJS.Polly.register(window['@pollyjs/persister-local-storage']);
// Setup Mocha
mocha.setup({ ui: 'bdd', noHighlighting: true });
================================================
FILE: examples/dummy-app/.eslintrc.js
================================================
module.exports = {
extends: ['plugin:react/recommended'],
settings: {
react: {
version: '16.5.1'
}
}
};
================================================
FILE: examples/dummy-app/.gitignore
================================================
# See https://help.github.com/ignore-files/ for more about ignoring files.
# dependencies
/node_modules
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
================================================
FILE: examples/dummy-app/README.md
================================================
This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
Below you will find some information on how to perform common tasks.
You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md).
## Table of Contents
- [Updating to New Releases](#updating-to-new-releases)
- [Sending Feedback](#sending-feedback)
- [Folder Structure](#folder-structure)
- [Available Scripts](#available-scripts)
- [npm start](#npm-start)
- [npm test](#npm-test)
- [npm run build](#npm-run-build)
- [npm run eject](#npm-run-eject)
- [Supported Browsers](#supported-browsers)
- [Supported Language Features and Polyfills](#supported-language-features-and-polyfills)
- [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor)
- [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor)
- [Debugging in the Editor](#debugging-in-the-editor)
- [Formatting Code Automatically](#formatting-code-automatically)
- [Changing the Page ``](#changing-the-page-title)
- [Installing a Dependency](#installing-a-dependency)
- [Importing a Component](#importing-a-component)
- [Code Splitting](#code-splitting)
- [Adding a Stylesheet](#adding-a-stylesheet)
- [Post-Processing CSS](#post-processing-css)
- [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc)
- [Adding Images, Fonts, and Files](#adding-images-fonts-and-files)
- [Using the `public` Folder](#using-the-public-folder)
- [Changing the HTML](#changing-the-html)
- [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system)
- [When to Use the `public` Folder](#when-to-use-the-public-folder)
- [Using Global Variables](#using-global-variables)
- [Adding Bootstrap](#adding-bootstrap)
- [Using a Custom Theme](#using-a-custom-theme)
- [Adding Flow](#adding-flow)
- [Adding a Router](#adding-a-router)
- [Adding Custom Environment Variables](#adding-custom-environment-variables)
- [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html)
- [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell)
- [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env)
- [Can I Use Decorators?](#can-i-use-decorators)
- [Fetching Data with AJAX Requests](#fetching-data-with-ajax-requests)
- [Integrating with an API Backend](#integrating-with-an-api-backend)
- [Node](#node)
- [Ruby on Rails](#ruby-on-rails)
- [Proxying API Requests in Development](#proxying-api-requests-in-development)
- ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy)
- [Configuring the Proxy Manually](#configuring-the-proxy-manually)
- [Configuring a WebSocket Proxy](#configuring-a-websocket-proxy)
- [Using HTTPS in Development](#using-https-in-development)
- [Generating Dynamic ` ` Tags on the Server](#generating-dynamic-meta-tags-on-the-server)
- [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files)
- [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page)
- [Running Tests](#running-tests)
- [Filename Conventions](#filename-conventions)
- [Command Line Interface](#command-line-interface)
- [Version Control Integration](#version-control-integration)
- [Writing Tests](#writing-tests)
- [Testing Components](#testing-components)
- [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries)
- [Initializing Test Environment](#initializing-test-environment)
- [Focusing and Excluding Tests](#focusing-and-excluding-tests)
- [Coverage Reporting](#coverage-reporting)
- [Continuous Integration](#continuous-integration)
- [Disabling jsdom](#disabling-jsdom)
- [Snapshot Testing](#snapshot-testing)
- [Editor Integration](#editor-integration)
- [Debugging Tests](#debugging-tests)
- [Debugging Tests in Chrome](#debugging-tests-in-chrome)
- [Debugging Tests in Visual Studio Code](#debugging-tests-in-visual-studio-code)
- [Developing Components in Isolation](#developing-components-in-isolation)
- [Getting Started with Storybook](#getting-started-with-storybook)
- [Getting Started with Styleguidist](#getting-started-with-styleguidist)
- [Publishing Components to npm](#publishing-components-to-npm)
- [Making a Progressive Web App](#making-a-progressive-web-app)
- [Opting Out of Caching](#opting-out-of-caching)
- [Offline-First Considerations](#offline-first-considerations)
- [Progressive Web App Metadata](#progressive-web-app-metadata)
- [Analyzing the Bundle Size](#analyzing-the-bundle-size)
- [Deployment](#deployment)
- [Static Server](#static-server)
- [Other Solutions](#other-solutions)
- [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing)
- [Building for Relative Paths](#building-for-relative-paths)
- [Azure](#azure)
- [Firebase](#firebase)
- [GitHub Pages](#github-pages)
- [Heroku](#heroku)
- [Netlify](#netlify)
- [Now](#now)
- [S3 and CloudFront](#s3-and-cloudfront)
- [Surge](#surge)
- [Advanced Configuration](#advanced-configuration)
- [Troubleshooting](#troubleshooting)
- [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes)
- [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra)
- [`npm run build` exits too early](#npm-run-build-exits-too-early)
- [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku)
- [`npm run build` fails to minify](#npm-run-build-fails-to-minify)
- [Moment.js locales are missing](#momentjs-locales-are-missing)
- [Alternatives to Ejecting](#alternatives-to-ejecting)
- [Something Missing?](#something-missing)
## Updating to New Releases
Create React App is divided into two packages:
- `create-react-app` is a global command-line utility that you use to create new projects.
- `react-scripts` is a development dependency in the generated projects (including this one).
You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`.
When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically.
To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions.
In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes.
We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly.
## Sending Feedback
We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues).
## Folder Structure
After creation, your project should look like this:
```
my-app/
README.md
node_modules/
package.json
public/
index.html
favicon.ico
src/
App.css
App.js
App.test.js
index.css
index.js
logo.svg
```
For the project to build, **these files must exist with exact filenames**:
- `public/index.html` is the page template;
- `src/index.js` is the JavaScript entry point.
You can delete or rename the other files.
You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.
You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them.
Only files inside `public` can be used from `public/index.html`.
Read instructions below for using assets from JavaScript and HTML.
You can, however, create more top-level directories.
They will not be included in the production build so you can use them for things like documentation.
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.
See the section about [running tests](#running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.
Your app is ready to be deployed!
See the section about [deployment](#deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
## Supported Browsers
By default, the generated project uses the latest version of React.
You can refer [to the React documentation](https://reactjs.org/docs/react-dom.html#browser-support) for more information about supported browsers.
## Supported Language Features and Polyfills
This project supports a superset of the latest JavaScript standard.
In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports:
- [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016).
- [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017).
- [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal).
- [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal)
- [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (part of stage 3 proposal).
- [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax.
Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-).
While we recommend using experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future.
Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**:
- [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign).
- [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise).
- [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch).
If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them.
Also note that using some newer syntax features like `for...of` or `[...nonArrayValue]` causes Babel to emit code that depends on ES6 runtime features and might not work without a polyfill. When in doubt, use [Babel REPL](https://babeljs.io/repl/) to see what any specific syntax compiles down to.
## Syntax Highlighting in the Editor
To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered.
## Displaying Lint Output in the Editor
> Note: this feature is available with `react-scripts@0.2.0` and higher.
> It also only works with npm 3 or higher.
Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint.
They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do.
You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root:
```js
{
"extends": "react-app"
}
```
Now your editor should report the linting warnings.
Note that even if you edit your `.eslintrc` file further, these changes will **only affect the editor integration**. They won’t affect the terminal and in-browser lint output. This is because Create React App intentionally provides a minimal set of rules that find common mistakes.
If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules.
## Debugging in the Editor
**This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).**
Visual Studio Code and WebStorm support debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools.
### Visual Studio Code
You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed.
Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory.
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "Chrome",
"type": "chrome",
"request": "launch",
"url": "http://localhost:3000",
"webRoot": "${workspaceRoot}/src",
"sourceMapPathOverrides": {
"webpack:///src/*": "${webRoot}/*"
}
}
]
}
```
> Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor.
Having problems with VS Code Debugging? Please see their [troubleshooting guide](https://github.com/Microsoft/vscode-chrome-debug/blob/master/README.md#troubleshooting).
### WebStorm
You would need to have [WebStorm](https://www.jetbrains.com/webstorm/) and [JetBrains IDE Support](https://chrome.google.com/webstore/detail/jetbrains-ide-support/hmhgeddbohgjknpmjagkdomcpobmllji) Chrome extension installed.
In the WebStorm menu `Run` select `Edit Configurations...`. Then click `+` and select `JavaScript Debug`. Paste `http://localhost:3000` into the URL field and save the configuration.
> Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
Start your app by running `npm start`, then press `^D` on macOS or `F9` on Windows and Linux or click the green debug icon to start debugging in WebStorm.
The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine.
## Formatting Code Automatically
Prettier is an opinionated code formatter with support for JavaScript, CSS and JSON. With Prettier you can format the code you write automatically to ensure a code style within your project. See the [Prettier's GitHub page](https://github.com/prettier/prettier) for more information, and look at this [page to see it in action](https://prettier.github.io/prettier/).
To format our code whenever we make a commit in git, we need to install the following dependencies:
```sh
npm install --save husky lint-staged prettier
```
Alternatively you may use `yarn`:
```sh
yarn add husky lint-staged prettier
```
- `husky` makes it easy to use githooks as if they are npm scripts.
- `lint-staged` allows us to run scripts on staged files in git. See this [blog post about lint-staged to learn more about it](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8).
- `prettier` is the JavaScript formatter we will run before commits.
Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root.
Add the following line to `scripts` section:
```diff
"scripts": {
+ "precommit": "lint-staged",
"start": "react-scripts start",
"build": "react-scripts build",
```
Next we add a 'lint-staged' field to the `package.json`, for example:
```diff
"dependencies": {
// ...
},
+ "lint-staged": {
+ "src/**/*.{js,jsx,json,css}": [
+ "prettier --single-quote --write",
+ "git add"
+ ]
+ },
"scripts": {
```
Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run `./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx,json,css}"` to format your entire project for the first time.
Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://prettier.io/docs/en/editors.html) on the Prettier GitHub page.
## Changing the Page ``
You can find the source HTML file in the `public` folder of the generated project. You may edit the `` tag in it to change the title from “React App” to anything else.
Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML.
If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library.
If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files).
## Installing a Dependency
The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`:
```sh
npm install --save react-router
```
Alternatively you may use `yarn`:
```sh
yarn add react-router
```
This works for any library, not just `react-router`.
## Importing a Component
This project setup supports ES6 modules thanks to Babel.
While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead.
For example:
### `Button.js`
```js
import React, { Component } from 'react';
class Button extends Component {
render() {
// ...
}
}
export default Button; // Don’t forget to use export default!
```
### `DangerButton.js`
```js
import React, { Component } from 'react';
import Button from './Button'; // Import a component from another file
class DangerButton extends Component {
render() {
return ;
}
}
export default DangerButton;
```
Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes.
We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`.
Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like.
Learn more about ES6 modules:
- [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281)
- [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html)
- [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules)
## Code Splitting
Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand.
This project setup supports code splitting via [dynamic `import()`](http://2ality.com/2017/01/import-operator.html#loading-code-on-demand). Its [proposal](https://github.com/tc39/proposal-dynamic-import) is in stage 3. The `import()` function-like form takes the module name as an argument and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which always resolves to the namespace object of the module.
Here is an example:
### `moduleA.js`
```js
const moduleA = 'Hello';
export { moduleA };
```
### `App.js`
```js
import React, { Component } from 'react';
class App extends Component {
handleClick = () => {
import('./moduleA')
.then(({ moduleA }) => {
// Use moduleA
})
.catch(err => {
// Handle failure
});
};
render() {
return (
Load
);
}
}
export default App;
```
This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button.
You can also use it with `async` / `await` syntax if you prefer it.
### With React Router
If you are using React Router check out [this tutorial](http://serverless-stack.com/chapters/code-splitting-in-create-react-app.html) on how to use code splitting with it. You can find the companion GitHub repository [here](https://github.com/AnomalyInnovations/serverless-stack-demo-client/tree/code-splitting-in-create-react-app).
Also check out the [Code Splitting](https://reactjs.org/docs/code-splitting.html) section in React documentation.
## Adding a Stylesheet
This project setup uses [Webpack](https://webpack.js.org/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**:
### `Button.css`
```css
.Button {
padding: 20px;
}
```
### `Button.js`
```js
import React, { Component } from 'react';
import './Button.css'; // Tell Webpack that Button.js uses these styles
class Button extends Component {
render() {
// You can use them as regular CSS styles
return
;
}
}
```
**This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-blog/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack.
In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output.
If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool.
## Post-Processing CSS
This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it.
For example, this:
```css
.App {
display: flex;
flex-direction: row;
align-items: center;
}
```
becomes this:
```css
.App {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
```
If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling).
## Adding a CSS Preprocessor (Sass, Less etc.)
Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `` and `` components, we recommend creating a `` component with its own `.Button` styles, that both `` and `` can render (but [not inherit](https://facebook.github.io/react/docs/composition-vs-inheritance.html)).
Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition. You can, however, integrate a CSS preprocessor if you find it valuable. In this walkthrough, we will be using Sass, but you can also use Less, or another alternative.
First, let’s install the command-line interface for Sass:
```sh
npm install --save node-sass-chokidar
```
Alternatively you may use `yarn`:
```sh
yarn add node-sass-chokidar
```
Then in `package.json`, add the following lines to `scripts`:
```diff
"scripts": {
+ "build-css": "node-sass-chokidar src/ -o src/",
+ "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
```
> Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessor’s documentation.
Now you can rename `src/App.css` to `src/App.scss` and run `npm run watch-css`. The watcher will find every Sass file in `src` subdirectories, and create a corresponding CSS file next to it, in our case overwriting `src/App.css`. Since `src/App.js` still imports `src/App.css`, the styles become a part of your application. You can now edit `src/App.scss`, and `src/App.css` will be regenerated.
To share variables between Sass files, you can use Sass imports. For example, `src/App.scss` and other component style files could include `@import "./shared.scss";` with variable definitions.
To enable importing files without using relative paths, you can add the `--include-path` option to the command in `package.json`.
```
"build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
"watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
```
This will allow you to do imports like
```scss
@import 'styles/_colors.scss'; // assuming a styles directory under src/
@import 'nprogress/nprogress'; // importing a css file from the nprogress node module
```
At this point you might want to remove all CSS files from the source control, and add `src/**/*.css` to your `.gitignore` file. It is generally a good practice to keep the build products outside of the source control.
As a final step, you may find it convenient to run `watch-css` automatically with `npm start`, and run `build-css` as a part of `npm run build`. You can use the `&&` operator to execute two scripts sequentially. However, there is no cross-platform way to run two scripts in parallel, so we will install a package for this:
```sh
npm install --save npm-run-all
```
Alternatively you may use `yarn`:
```sh
yarn add npm-run-all
```
Then we can change `start` and `build` scripts to include the CSS preprocessor commands:
```diff
"scripts": {
"build-css": "node-sass-chokidar src/ -o src/",
"watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
- "start": "react-scripts start",
- "build": "react-scripts build",
+ "start-js": "react-scripts start",
+ "start": "npm-run-all -p watch-css start-js",
+ "build-js": "react-scripts build",
+ "build": "npm-run-all build-css build-js",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
```
Now running `npm start` and `npm run build` also builds Sass files.
**Why `node-sass-chokidar`?**
`node-sass` has been reported as having the following issues:
- `node-sass --watch` has been reported to have _performance issues_ in certain conditions when used in a virtual machine or with docker.
- Infinite styles compiling [#1939](https://github.com/facebookincubator/create-react-app/issues/1939)
- `node-sass` has been reported as having issues with detecting new files in a directory [#1891](https://github.com/sass/node-sass/issues/1891)
`node-sass-chokidar` is used here as it addresses these issues.
## Adding Images, Fonts, and Files
With Webpack, using static assets like images and fonts works similarly to CSS.
You can **`import` a file right in a JavaScript module**. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the `src` attribute of an image or the `href` of a link to a PDF.
To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a [data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png. SVG files are excluded due to [#1153](https://github.com/facebookincubator/create-react-app/issues/1153).
Here is an example:
```js
import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png
function Header() {
// Import result is the URL of your image
return ;
}
export default Header;
```
This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths.
This works in CSS too:
```css
.Logo {
background-image: url(./logo.png);
}
```
Webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets.
Please be advised that this is also a custom feature of Webpack.
**It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).
An alternative way of handling static assets is described in the next section.
## Using the `public` Folder
> Note: this feature is available with `react-scripts@0.5.0` and higher.
### Changing the HTML
The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title).
The `
```
Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data right before sending the response. The client code can then read `window.SERVER_DATA` to use it. **Make sure to [sanitize the JSON before sending it to the client](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to XSS attacks.**
## Running Tests
> Note: this feature is available with `react-scripts@0.3.0` and higher. >[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030)
Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try.
Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness.
While Jest provides browser globals such as `window` thanks to [jsdom](https://github.com/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks.
We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App.
### Filename Conventions
Jest will look for test files with any of the following popular naming conventions:
- Files with `.js` suffix in `__tests__` folders.
- Files with `.test.js` suffix.
- Files with `.spec.js` suffix.
The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder.
We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects.
### Command Line Interface
When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code.
The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage” note that the watcher prints after every run:

### Version Control Integration
By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests run fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests.
Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests.
Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository.
### Writing Tests
To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended.
Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this:
```js
import sum from './sum';
it('sums numbers', () => {
expect(sum(1, 2)).toEqual(3);
expect(sum(2, 2)).toEqual(4);
});
```
All `expect()` matchers supported by Jest are [extensively documented here](https://facebook.github.io/jest/docs/en/expect.html#content).
You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](https://facebook.github.io/jest/docs/en/expect.html#tohavebeencalled) to create “spies” or mock functions.
### Testing Components
There is a broad spectrum of component testing techniques. They range from a “smoke test” verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes.
Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components:
```js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render( , div);
});
```
This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot of value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.js`.
When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior.
If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). To install it, run:
```sh
npm install --save enzyme enzyme-adapter-react-16 react-test-renderer
```
Alternatively you may use `yarn`:
```sh
yarn add enzyme enzyme-adapter-react-16 react-test-renderer
```
As of Enzyme 3, you will need to install Enzyme along with an Adapter corresponding to the version of React you are using. (The examples above use the adapter for React 16.)
The adapter will also need to be configured in your [global setup file](#initializing-test-environment):
#### `src/setupTests.js`
```js
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
```
> Note: Keep in mind that if you decide to "eject" before creating `src/setupTests.js`, the resulting `package.json` file won't contain any reference to it. [Read here](#initializing-test-environment) to learn how to add this after ejecting.
Now you can write a smoke test with it:
```js
import React from 'react';
import { shallow } from 'enzyme';
import App from './App';
it('renders without crashing', () => {
shallow( );
});
```
Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a `` that throws, this test will pass. Shallow rendering is great for isolated unit tests, but you may still want to create some full rendering tests to ensure the components integrate correctly. Enzyme supports [full rendering with `mount()`](http://airbnb.io/enzyme/docs/api/mount.html), and you can also use it for testing state changes and component lifecycle.
You can read the [Enzyme documentation](http://airbnb.io/enzyme/) for more testing techniques. Enzyme documentation uses Chai and Sinon for assertions but you don’t have to use them because Jest provides built-in `expect()` and `jest.fn()` for spies.
Here is an example from Enzyme documentation that asserts specific output, rewritten to use Jest matchers:
```js
import React from 'react';
import { shallow } from 'enzyme';
import App from './App';
it('renders welcome message', () => {
const wrapper = shallow( );
const welcome = Welcome to React ;
// expect(wrapper.contains(welcome)).to.equal(true);
expect(wrapper.contains(welcome)).toEqual(true);
});
```
All Jest matchers are [extensively documented here](http://facebook.github.io/jest/docs/en/expect.html).
Nevertheless you can use a third-party assertion library like [Chai](http://chaijs.com/) if you want to, as described below.
Additionally, you might find [jest-enzyme](https://github.com/blainekasten/enzyme-matchers) helpful to simplify your tests with readable matchers. The above `contains` code can be written more simply with jest-enzyme.
```js
expect(wrapper).toContainReact(welcome);
```
To enable this, install `jest-enzyme`:
```sh
npm install --save jest-enzyme
```
Alternatively you may use `yarn`:
```sh
yarn add jest-enzyme
```
Import it in [`src/setupTests.js`](#initializing-test-environment) to make its matchers available in every test:
```js
import 'jest-enzyme';
```
#### Use `react-testing-library`
As an alternative or companion to `enzyme`, you may consider using `react-testing-library`. [`react-testing-library`](https://github.com/kentcdodds/react-testing-library) is a library for testing React components in a way that resembles the way the components are used by end users. It is well suited for unit, integration, and end-to-end testing of React components and applications. It works more directly with DOM nodes, and therefore it's recommended to use with [`jest-dom`](https://github.com/gnapse/jest-dom) for improved assertions.
To install `react-testing-library` and `jest-dom`, you can run:
```sh
npm install --save react-testing-library jest-dom
```
Alternatively you may use `yarn`:
```sh
yarn add react-testing-library jest-dom
```
Similar to `enzyme` you can create a `src/setupTests.js` file to avoid boilerplate in your test files:
```js
// react-testing-library renders your components to document.body,
// this will ensure they're removed after each test.
import 'react-testing-library/cleanup-after-each';
// this adds jest-dom's custom assertions
import 'jest-dom/extend-expect';
```
Here's an example of using `react-testing-library` and `jest-dom` for testing that the ` ` component renders "Welcome to React".
```js
import React from 'react';
import { render } from 'react-testing-library';
import App from './App';
it('renders welcome message', () => {
const { getByText } = render( );
expect(getByText('Welcome to React')).toBeInTheDOM();
});
```
Learn more about the utilities provided by `react-testing-library` to facilitate testing asynchronous interactions as well as selecting form elements from [the `react-testing-library` documentation](https://github.com/kentcdodds/react-testing-library) and [examples](https://codesandbox.io/s/github/kentcdodds/react-testing-library-examples).
### Using Third Party Assertion Libraries
We recommend that you use `expect()` for assertions and `jest.fn()` for spies. If you are having issues with them please [file those against Jest](https://github.com/facebook/jest/issues/new), and we’ll fix them. We intend to keep making them better for React, supporting, for example, [pretty-printing React elements as JSX](https://github.com/facebook/jest/pull/1566).
However, if you are used to other libraries, such as [Chai](http://chaijs.com/) and [Sinon](http://sinonjs.org/), or if you have existing code using them that you’d like to port over, you can import them normally like this:
```js
import sinon from 'sinon';
import { expect } from 'chai';
```
and then use them in your tests like you normally do.
### Initializing Test Environment
> Note: this feature is available with `react-scripts@0.4.0` and higher.
If your app uses a browser API that you need to mock in your tests or if you just need a global setup before running your tests, add a `src/setupTests.js` to your project. It will be automatically executed before running your tests.
For example:
#### `src/setupTests.js`
```js
const localStorageMock = {
getItem: jest.fn(),
setItem: jest.fn(),
clear: jest.fn()
};
global.localStorage = localStorageMock;
```
> Note: Keep in mind that if you decide to "eject" before creating `src/setupTests.js`, the resulting `package.json` file won't contain any reference to it, so you should manually create the property `setupTestFrameworkScriptFile` in the configuration for Jest, something like the following:
> ```js
> "jest": {
> // ...
> "setupTestFrameworkScriptFile": "/src/setupTests.js"
> }
> ```
### Focusing and Excluding Tests
You can replace `it()` with `xit()` to temporarily exclude a test from being executed.
Similarly, `fit()` lets you focus on a specific test without running any other tests.
### Coverage Reporting
Jest has an integrated coverage reporter that works well with ES6 and requires no configuration.
Run `npm test -- --coverage` (note extra `--` in the middle) to include a coverage report like this:

Note that tests run much slower with coverage so it is recommended to run it separately from your normal workflow.
#### Configuration
The default Jest coverage configuration can be overriden by adding any of the following supported keys to a Jest config in your package.json.
Supported overrides:
- [`collectCoverageFrom`](https://facebook.github.io/jest/docs/en/configuration.html#collectcoveragefrom-array)
- [`coverageReporters`](https://facebook.github.io/jest/docs/en/configuration.html#coveragereporters-array-string)
- [`coverageThreshold`](https://facebook.github.io/jest/docs/en/configuration.html#coveragethreshold-object)
- [`snapshotSerializers`](https://facebook.github.io/jest/docs/en/configuration.html#snapshotserializers-array-string)
Example package.json:
```json
{
"name": "your-package",
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx}",
"!/node_modules/",
"!/path/to/dir/"
],
"coverageThreshold": {
"global": {
"branches": 90,
"functions": 90,
"lines": 90,
"statements": 90
}
},
"coverageReporters": ["text"],
"snapshotSerializers": ["my-serializer-module"]
}
}
```
### Continuous Integration
By default `npm test` runs the watcher with interactive CLI. However, you can force it to run tests once and finish the process by setting an environment variable called `CI`.
When creating a build of your application with `npm run build` linter warnings are not checked by default. Like `npm test`, you can force the build to perform a linter warning check by setting the environment variable `CI`. If any warnings are encountered then the build fails.
Popular CI servers already set the environment variable `CI` by default but you can do this yourself too:
### On CI servers
#### Travis CI
1. Following the [Travis Getting started](https://docs.travis-ci.com/user/getting-started/) guide for syncing your GitHub repository with Travis. You may need to initialize some settings manually in your [profile](https://travis-ci.com/profile) page.
1. Add a `.travis.yml` file to your git repository.
```
language: node_js
node_js:
- 6
cache:
directories:
- node_modules
script:
- npm run build
- npm test
```
1. Trigger your first build with a git push.
1. [Customize your Travis CI Build](https://docs.travis-ci.com/user/customizing-the-build/) if needed.
#### CircleCI
Follow [this article](https://medium.com/@knowbody/circleci-and-zeits-now-sh-c9b7eebcd3c1) to set up CircleCI with a Create React App project.
### On your own environment
##### Windows (cmd.exe)
```cmd
set CI=true&&npm test
```
```cmd
set CI=true&&npm run build
```
(Note: the lack of whitespace is intentional.)
##### Windows (Powershell)
```Powershell
($env:CI = $true) -and (npm test)
```
```Powershell
($env:CI = $true) -and (npm run build)
```
##### Linux, macOS (Bash)
```bash
CI=true npm test
```
```bash
CI=true npm run build
```
The test command will force Jest to run tests once instead of launching the watcher.
> If you find yourself doing this often in development, please [file an issue](https://github.com/facebookincubator/create-react-app/issues/new) to tell us about your use case because we want to make watcher the best experience and are open to changing how it works to accommodate more workflows.
The build command will check for linter warnings and fail if any are found.
### Disabling jsdom
By default, the `package.json` of the generated project looks like this:
```js
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom"
```
If you know that none of your tests depend on [jsdom](https://github.com/tmpvar/jsdom), you can safely remove `--env=jsdom`, and your tests will run faster:
```diff
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
- "test": "react-scripts test --env=jsdom"
+ "test": "react-scripts test"
```
To help you make up your mind, here is a list of APIs that **need jsdom**:
- Any browser globals like `window` and `document`
- [`ReactDOM.render()`](https://facebook.github.io/react/docs/top-level-api.html#reactdom.render)
- [`TestUtils.renderIntoDocument()`](https://facebook.github.io/react/docs/test-utils.html#renderintodocument) ([a shortcut](https://github.com/facebook/react/blob/34761cf9a252964abfaab6faf74d473ad95d1f21/src/test/ReactTestUtils.js#L83-L91) for the above)
- [`mount()`](http://airbnb.io/enzyme/docs/api/mount.html) in [Enzyme](http://airbnb.io/enzyme/index.html)
In contrast, **jsdom is not needed** for the following APIs:
- [`TestUtils.createRenderer()`](https://facebook.github.io/react/docs/test-utils.html#shallow-rendering) (shallow rendering)
- [`shallow()`](http://airbnb.io/enzyme/docs/api/shallow.html) in [Enzyme](http://airbnb.io/enzyme/index.html)
Finally, jsdom is also not needed for [snapshot testing](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html).
### Snapshot Testing
Snapshot testing is a feature of Jest that automatically generates text snapshots of your components and saves them on the disk so if the UI output changes, you get notified without manually writing any assertions on the component output. [Read more about snapshot testing.](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html)
### Editor Integration
If you use [Visual Studio Code](https://code.visualstudio.com), there is a [Jest extension](https://github.com/orta/vscode-jest) which works with Create React App out of the box. This provides a lot of IDE-like features while using a text editor: showing the status of a test run with potential fail messages inline, starting and stopping the watcher automatically, and offering one-click snapshot updates.

## Debugging Tests
There are various ways to setup a debugger for your Jest tests. We cover debugging in Chrome and [Visual Studio Code](https://code.visualstudio.com/).
> Note: debugging tests requires Node 8 or higher.
### Debugging Tests in Chrome
Add the following to the `scripts` section in your project's `package.json`
```json
"scripts": {
"test:debug": "react-scripts --inspect-brk test --runInBand --env=jsdom"
}
```
Place `debugger;` statements in any test and run:
```bash
$ npm run test:debug
```
This will start running your Jest tests, but pause before executing to allow a debugger to attach to the process.
Open the following in Chrome
```
about:inspect
```
After opening that link, the Chrome Developer Tools will be displayed. Select `inspect` on your process and a breakpoint will be set at the first line of the react script (this is done simply to give you time to open the developer tools and to prevent Jest from executing before you have time to do so). Click the button that looks like a "play" button in the upper right hand side of the screen to continue execution. When Jest executes the test that contains the debugger statement, execution will pause and you can examine the current scope and call stack.
> Note: the --runInBand cli option makes sure Jest runs test in the same process rather than spawning processes for individual tests. Normally Jest parallelizes test runs across processes but it is hard to debug many processes at the same time.
### Debugging Tests in Visual Studio Code
Debugging Jest tests is supported out of the box for [Visual Studio Code](https://code.visualstudio.com).
Use the following [`launch.json`](https://code.visualstudio.com/docs/editor/debugging#_launch-configurations) configuration file:
```
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug CRA Tests",
"type": "node",
"request": "launch",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/react-scripts",
"args": [
"test",
"--runInBand",
"--no-cache",
"--env=jsdom"
],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
]
}
```
## Developing Components in Isolation
Usually, in an app, you have a lot of UI components, and each of them has many different states.
For an example, a simple button component could have following states:
- In a regular state, with a text label.
- In the disabled mode.
- In a loading state.
Usually, it’s hard to see these states without running a sample app or some examples.
Create React App doesn’t include any tools for this by default, but you can easily add [Storybook for React](https://storybook.js.org) ([source](https://github.com/storybooks/storybook)) or [React Styleguidist](https://react-styleguidist.js.org/) ([source](https://github.com/styleguidist/react-styleguidist)) to your project. **These are third-party tools that let you develop components and see all their states in isolation from your app**.

You can also deploy your Storybook or style guide as a static app. This way, everyone in your team can view and review different states of UI components without starting a backend server or creating an account in your app.
### Getting Started with Storybook
Storybook is a development environment for React UI components. It allows you to browse a component library, view the different states of each component, and interactively develop and test components.
First, install the following npm package globally:
```sh
npm install -g @storybook/cli
```
Then, run the following command inside your app’s directory:
```sh
getstorybook
```
After that, follow the instructions on the screen.
Learn more about React Storybook:
- Screencast: [Getting Started with React Storybook](https://egghead.io/lessons/react-getting-started-with-react-storybook)
- [GitHub Repo](https://github.com/storybooks/storybook)
- [Documentation](https://storybook.js.org/basics/introduction/)
- [Snapshot Testing UI](https://github.com/storybooks/storybook/tree/master/addons/storyshots) with Storybook + addon/storyshot
### Getting Started with Styleguidist
Styleguidist combines a style guide, where all your components are presented on a single page with their props documentation and usage examples, with an environment for developing components in isolation, similar to Storybook. In Styleguidist you write examples in Markdown, where each code snippet is rendered as a live editable playground.
First, install Styleguidist:
```sh
npm install --save react-styleguidist
```
Alternatively you may use `yarn`:
```sh
yarn add react-styleguidist
```
Then, add these scripts to your `package.json`:
```diff
"scripts": {
+ "styleguide": "styleguidist server",
+ "styleguide:build": "styleguidist build",
"start": "react-scripts start",
```
Then, run the following command inside your app’s directory:
```sh
npm run styleguide
```
After that, follow the instructions on the screen.
Learn more about React Styleguidist:
- [GitHub Repo](https://github.com/styleguidist/react-styleguidist)
- [Documentation](https://react-styleguidist.js.org/docs/getting-started.html)
## Publishing Components to npm
Create React App doesn't provide any built-in functionality to publish a component to npm. If you're ready to extract a component from your project so other people can use it, we recommend moving it to a separate directory outside of your project and then using a tool like [nwb](https://github.com/insin/nwb#react-components-and-libraries) to prepare it for publishing.
## Making a Progressive Web App
By default, the production build is a fully functional, offline-first
[Progressive Web App](https://developers.google.com/web/progressive-web-apps/).
Progressive Web Apps are faster and more reliable than traditional web pages, and provide an engaging mobile experience:
- All static site assets are cached so that your page loads fast on subsequent visits, regardless of network connectivity (such as 2G or 3G). Updates are downloaded in the background.
- Your app will work regardless of network state, even if offline. This means your users will be able to use your app at 10,000 feet and on the subway.
- On mobile devices, your app can be added directly to the user's home screen, app icon and all. You can also re-engage users using web **push notifications**. This eliminates the need for the app store.
The [`sw-precache-webpack-plugin`](https://github.com/goldhand/sw-precache-webpack-plugin)
is integrated into production configuration,
and it will take care of generating a service worker file that will automatically
precache all of your local assets and keep them up to date as you deploy updates.
The service worker will use a [cache-first strategy](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-falling-back-to-network)
for handling all requests for local assets, including the initial HTML, ensuring
that your web app is reliably fast, even on a slow or unreliable network.
### Opting Out of Caching
If you would prefer not to enable service workers prior to your initial
production deployment, then remove the call to `registerServiceWorker()`
from [`src/index.js`](src/index.js).
If you had previously enabled service workers in your production deployment and
have decided that you would like to disable them for all your existing users,
you can swap out the call to `registerServiceWorker()` in
[`src/index.js`](src/index.js) first by modifying the service worker import:
```javascript
import { unregister } from './registerServiceWorker';
```
and then call `unregister()` instead.
After the user visits a page that has `unregister()`,
the service worker will be uninstalled. Note that depending on how `/service-worker.js` is served,
it may take up to 24 hours for the cache to be invalidated.
### Offline-First Considerations
1. Service workers [require HTTPS](https://developers.google.com/web/fundamentals/getting-started/primers/service-workers#you_need_https),
although to facilitate local testing, that policy
[does not apply to `localhost`](http://stackoverflow.com/questions/34160509/options-for-testing-service-workers-via-http/34161385#34161385).
If your production web server does not support HTTPS, then the service worker
registration will fail, but the rest of your web app will remain functional.
1. Service workers are [not currently supported](https://jakearchibald.github.io/isserviceworkerready/)
in all web browsers. Service worker registration [won't be attempted](src/registerServiceWorker.js)
on browsers that lack support.
1. The service worker is only enabled in the [production environment](#deployment),
e.g. the output of `npm run build`. It's recommended that you do not enable an
offline-first service worker in a development environment, as it can lead to
frustration when previously cached assets are used and do not include the latest
changes you've made locally.
1. If you _need_ to test your offline-first service worker locally, build
the application (using `npm run build`) and run a simple http server from your
build directory. After running the build script, `create-react-app` will give
instructions for one way to test your production build locally and the [deployment instructions](#deployment) have
instructions for using other methods. _Be sure to always use an
incognito window to avoid complications with your browser cache._
1. If possible, configure your production environment to serve the generated
`service-worker.js` [with HTTP caching disabled](http://stackoverflow.com/questions/38843970/service-worker-javascript-update-frequency-every-24-hours).
If that's not possible—[GitHub Pages](#github-pages), for instance, does not
allow you to change the default 10 minute HTTP cache lifetime—then be aware
that if you visit your production site, and then revisit again before
`service-worker.js` has expired from your HTTP cache, you'll continue to get
the previously cached assets from the service worker. If you have an immediate
need to view your updated production deployment, performing a shift-refresh
will temporarily disable the service worker and retrieve all assets from the
network.
1. Users aren't always familiar with offline-first web apps. It can be useful to
[let the user know](https://developers.google.com/web/fundamentals/instant-and-offline/offline-ux#inform_the_user_when_the_app_is_ready_for_offline_consumption)
when the service worker has finished populating your caches (showing a "This web
app works offline!" message) and also let them know when the service worker has
fetched the latest updates that will be available the next time they load the
page (showing a "New content is available; please refresh." message). Showing
this messages is currently left as an exercise to the developer, but as a
starting point, you can make use of the logic included in [`src/registerServiceWorker.js`](src/registerServiceWorker.js), which
demonstrates which service worker lifecycle events to listen for to detect each
scenario, and which as a default, just logs appropriate messages to the
JavaScript console.
1. By default, the generated service worker file will not intercept or cache any
cross-origin traffic, like HTTP [API requests](#integrating-with-an-api-backend),
images, or embeds loaded from a different domain. If you would like to use a
runtime caching strategy for those requests, you can [`eject`](#npm-run-eject)
and then configure the
[`runtimeCaching`](https://github.com/GoogleChrome/sw-precache#runtimecaching-arrayobject)
option in the `SWPrecacheWebpackPlugin` section of
[`webpack.config.prod.js`](../config/webpack.config.prod.js).
### Progressive Web App Metadata
The default configuration includes a web app manifest located at
[`public/manifest.json`](public/manifest.json), that you can customize with
details specific to your web application.
When a user adds a web app to their homescreen using Chrome or Firefox on
Android, the metadata in [`manifest.json`](public/manifest.json) determines what
icons, names, and branding colors to use when the web app is displayed.
[The Web App Manifest guide](https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/)
provides more context about what each field means, and how your customizations
will affect your users' experience.
## Analyzing the Bundle Size
[Source map explorer](https://www.npmjs.com/package/source-map-explorer) analyzes
JavaScript bundles using the source maps. This helps you understand where code
bloat is coming from.
To add Source map explorer to a Create React App project, follow these steps:
```sh
npm install --save source-map-explorer
```
Alternatively you may use `yarn`:
```sh
yarn add source-map-explorer
```
Then in `package.json`, add the following line to `scripts`:
```diff
"scripts": {
+ "analyze": "source-map-explorer build/static/js/main.*",
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
```
Then to analyze the bundle run the production build then run the analyze
script.
```
npm run build
npm run analyze
```
## Deployment
`npm run build` creates a `build` directory with a production build of your app. Set up your favorite HTTP server so that a visitor to your site is served `index.html`, and requests to static paths like `/static/js/main..js` are served with the contents of the `/static/js/main..js` file.
### Static Server
For environments using [Node](https://nodejs.org/), the easiest way to handle this would be to install [serve](https://github.com/zeit/serve) and let it handle the rest:
```sh
npm install -g serve
serve -s build
```
The last command shown above will serve your static site on the port **5000**. Like many of [serve](https://github.com/zeit/serve)’s internal settings, the port can be adjusted using the `-p` or `--port` flags.
Run this command to get a full list of the options available:
```sh
serve -h
```
### Other Solutions
You don’t necessarily need a static server in order to run a Create React App project in production. It works just as fine integrated into an existing dynamic one.
Here’s a programmatic example using [Node](https://nodejs.org/) and [Express](http://expressjs.com/):
```javascript
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(9000);
```
The choice of your server software isn’t important either. Since Create React App is completely platform-agnostic, there’s no need to explicitly use Node.
The `build` folder with static assets is the only output produced by Create React App.
However this is not quite enough if you use client-side routing. Read the next section if you want to support URLs like `/todos/42` in your single-page app.
### Serving Apps with Client-Side Routing
If you use routers that use the HTML5 [`pushState` history API](https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries) under the hood (for example, [React Router](https://github.com/ReactTraining/react-router) with `browserHistory`), many static file servers will fail. For example, if you used React Router with a route for `/todos/42`, the development server will respond to `localhost:3000/todos/42` properly, but an Express serving a production build as above will not.
This is because when there is a fresh page load for a `/todos/42`, the server looks for the file `build/todos/42` and does not find it. The server needs to be configured to respond to a request to `/todos/42` by serving `index.html`. For example, we can amend our Express example above to serve `index.html` for any unknown paths:
```diff
app.use(express.static(path.join(__dirname, 'build')));
-app.get('/', function (req, res) {
+app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
```
If you’re using [Apache HTTP Server](https://httpd.apache.org/), you need to create a `.htaccess` file in the `public` folder that looks like this:
```
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
```
It will get copied to the `build` folder when you run `npm run build`.
If you’re using [Apache Tomcat](http://tomcat.apache.org/), you need to follow [this Stack Overflow answer](https://stackoverflow.com/a/41249464/4878474).
Now requests to `/todos/42` will be handled correctly both in development and in production.
On a production build, and in a browser that supports [service workers](https://developers.google.com/web/fundamentals/getting-started/primers/service-workers),
the service worker will automatically handle all navigation requests, like for
`/todos/42`, by serving the cached copy of your `index.html`. This
service worker navigation routing can be configured or disabled by
[`eject`ing](#npm-run-eject) and then modifying the
[`navigateFallback`](https://github.com/GoogleChrome/sw-precache#navigatefallback-string)
and [`navigateFallbackWhitelist`](https://github.com/GoogleChrome/sw-precache#navigatefallbackwhitelist-arrayregexp)
options of the `SWPreachePlugin` [configuration](../config/webpack.config.prod.js).
When users install your app to the homescreen of their device the default configuration will make a shortcut to `/index.html`. This may not work for client-side routers which expect the app to be served from `/`. Edit the web app manifest at [`public/manifest.json`](public/manifest.json) and change `start_url` to match the required URL scheme, for example:
```js
"start_url": ".",
```
### Building for Relative Paths
By default, Create React App produces a build assuming your app is hosted at the server root.
To override this, specify the `homepage` in your `package.json`, for example:
```js
"homepage": "http://mywebsite.com/relativepath",
```
This will let Create React App correctly infer the root path to use in the generated HTML file.
**Note**: If you are using `react-router@^4`, you can root ` `s using the `basename` prop on any ``.
More information [here](https://reacttraining.com/react-router/web/api/BrowserRouter/basename-string).
For example:
```js
// renders
```
#### Serving the Same Build from Different Paths
> Note: this feature is available with `react-scripts@0.9.0` and higher.
If you are not using the HTML5 `pushState` history API or not using client-side routing at all, it is unnecessary to specify the URL from which your app will be served. Instead, you can put this in your `package.json`:
```js
"homepage": ".",
```
This will make sure that all the asset paths are relative to `index.html`. You will then be able to move your app from `http://mywebsite.com` to `http://mywebsite.com/relativepath` or even `http://mywebsite.com/relative/path` without having to rebuild it.
### [Azure](https://azure.microsoft.com/)
See [this](https://medium.com/@to_pe/deploying-create-react-app-on-microsoft-azure-c0f6686a4321) blog post on how to deploy your React app to Microsoft Azure.
See [this](https://medium.com/@strid/host-create-react-app-on-azure-986bc40d5bf2#.pycfnafbg) blog post or [this](https://github.com/ulrikaugustsson/azure-appservice-static) repo for a way to use automatic deployment to Azure App Service.
### [Firebase](https://firebase.google.com/)
Install the Firebase CLI if you haven’t already by running `npm install -g firebase-tools`. Sign up for a [Firebase account](https://console.firebase.google.com/) and create a new project. Run `firebase login` and login with your previous created Firebase account.
Then run the `firebase init` command from your project’s root. You need to choose the **Hosting: Configure and deploy Firebase Hosting sites** and choose the Firebase project you created in the previous step. You will need to agree with `database.rules.json` being created, choose `build` as the public directory, and also agree to **Configure as a single-page app** by replying with `y`.
```sh
=== Project Setup
First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add,
but for now we'll just set up a default project.
? What Firebase project do you want to associate as default? Example app (example-app-fd690)
=== Database Setup
Firebase Realtime Database Rules allow you to define how your data should be
structured and when your data can be read from and written to.
? What file should be used for Database Rules? database.rules.json
✔ Database Rules for example-app-fd690 have been downloaded to database.rules.json.
Future modifications to database.rules.json will update Database Rules when you run
firebase deploy.
=== Hosting Setup
Your public directory is the folder (relative to your project directory) that
will contain Hosting assets to uploaded with firebase deploy. If you
have a build process for your assets, use your build's output directory.
? What do you want to use as your public directory? build
? Configure as a single-page app (rewrite all urls to /index.html)? Yes
✔ Wrote build/index.html
i Writing configuration info to firebase.json...
i Writing project information to .firebaserc...
✔ Firebase initialization complete!
```
IMPORTANT: you need to set proper HTTP caching headers for `service-worker.js` file in `firebase.json` file or you will not be able to see changes after first deployment ([issue #2440](https://github.com/facebookincubator/create-react-app/issues/2440)). It should be added inside `"hosting"` key like next:
```
{
"hosting": {
...
"headers": [
{"source": "/service-worker.js", "headers": [{"key": "Cache-Control", "value": "no-cache"}]}
]
...
```
Now, after you create a production build with `npm run build`, you can deploy it by running `firebase deploy`.
```sh
=== Deploying to 'example-app-fd690'...
i deploying database, hosting
✔ database: rules ready to deploy.
i hosting: preparing build directory for upload...
Uploading: [============================== ] 75%✔ hosting: build folder uploaded successfully
✔ hosting: 8 files uploaded successfully
i starting release process (may take several minutes)...
✔ Deploy complete!
Project Console: https://console.firebase.google.com/project/example-app-fd690/overview
Hosting URL: https://example-app-fd690.firebaseapp.com
```
For more information see [Add Firebase to your JavaScript Project](https://firebase.google.com/docs/web/setup).
### [GitHub Pages](https://pages.github.com/)
> Note: this feature is available with `react-scripts@0.2.0` and higher.
#### Step 1: Add `homepage` to `package.json`
**The step below is important!**
**If you skip it, your app will not deploy correctly.**
Open your `package.json` and add a `homepage` field for your project:
```json
"homepage": "https://myusername.github.io/my-app",
```
or for a GitHub user page:
```json
"homepage": "https://myusername.github.io",
```
Create React App uses the `homepage` field to determine the root URL in the built HTML file.
#### Step 2: Install `gh-pages` and add `deploy` to `scripts` in `package.json`
Now, whenever you run `npm run build`, you will see a cheat sheet with instructions on how to deploy to GitHub Pages.
To publish it at [https://myusername.github.io/my-app](https://myusername.github.io/my-app), run:
```sh
npm install --save gh-pages
```
Alternatively you may use `yarn`:
```sh
yarn add gh-pages
```
Add the following scripts in your `package.json`:
```diff
"scripts": {
+ "predeploy": "npm run build",
+ "deploy": "gh-pages -d build",
"start": "react-scripts start",
"build": "react-scripts build",
```
The `predeploy` script will run automatically before `deploy` is run.
If you are deploying to a GitHub user page instead of a project page you'll need to make two
additional modifications:
1. First, change your repository's source branch to be any branch other than **master**.
1. Additionally, tweak your `package.json` scripts to push deployments to **master**:
```diff
"scripts": {
"predeploy": "npm run build",
- "deploy": "gh-pages -d build",
+ "deploy": "gh-pages -b master -d build",
```
#### Step 3: Deploy the site by running `npm run deploy`
Then run:
```sh
npm run deploy
```
#### Step 4: Ensure your project’s settings use `gh-pages`
Finally, make sure **GitHub Pages** option in your GitHub project settings is set to use the `gh-pages` branch:
#### Step 5: Optionally, configure the domain
You can configure a custom domain with GitHub Pages by adding a `CNAME` file to the `public/` folder.
#### Notes on client-side routing
GitHub Pages doesn’t support routers that use the HTML5 `pushState` history API under the hood (for example, React Router using `browserHistory`). This is because when there is a fresh page load for a url like `http://user.github.io/todomvc/todos/42`, where `/todos/42` is a frontend route, the GitHub Pages server returns 404 because it knows nothing of `/todos/42`. If you want to add a router to a project hosted on GitHub Pages, here are a couple of solutions:
- You could switch from using HTML5 history API to routing with hashes. If you use React Router, you can switch to `hashHistory` for this effect, but the URL will be longer and more verbose (for example, `http://user.github.io/todomvc/#/todos/42?_k=yknaj`). [Read more](https://reacttraining.com/react-router/web/api/Router) about different history implementations in React Router.
- Alternatively, you can use a trick to teach GitHub Pages to handle 404 by redirecting to your `index.html` page with a special redirect parameter. You would need to add a `404.html` file with the redirection code to the `build` folder before deploying your project, and you’ll need to add code handling the redirect parameter to `index.html`. You can find a detailed explanation of this technique [in this guide](https://github.com/rafrex/spa-github-pages).
#### Troubleshooting
##### "/dev/tty: No such a device or address"
If, when deploying, you get `/dev/tty: No such a device or address` or a similar error, try the follwing:
1. Create a new [Personal Access Token](https://github.com/settings/tokens)
2. `git remote set-url origin https://:@github.com//` .
3. Try `npm run deploy again`
### [Heroku](https://www.heroku.com/)
Use the [Heroku Buildpack for Create React App](https://github.com/mars/create-react-app-buildpack).
You can find instructions in [Deploying React with Zero Configuration](https://blog.heroku.com/deploying-react-with-zero-configuration).
#### Resolving Heroku Deployment Errors
Sometimes `npm run build` works locally but fails during deploy via Heroku. Following are the most common cases.
##### "Module not found: Error: Cannot resolve 'file' or 'directory'"
If you get something like this:
```
remote: Failed to create a production build. Reason:
remote: Module not found: Error: Cannot resolve 'file' or 'directory'
MyDirectory in /tmp/build_1234/src
```
It means you need to ensure that the lettercase of the file or directory you `import` matches the one you see on your filesystem or on GitHub.
This is important because Linux (the operating system used by Heroku) is case sensitive. So `MyDirectory` and `mydirectory` are two distinct directories and thus, even though the project builds locally, the difference in case breaks the `import` statements on Heroku remotes.
##### "Could not find a required file."
If you exclude or ignore necessary files from the package you will see a error similar this one:
```
remote: Could not find a required file.
remote: Name: `index.html`
remote: Searched in: /tmp/build_a2875fc163b209225122d68916f1d4df/public
remote:
remote: npm ERR! Linux 3.13.0-105-generic
remote: npm ERR! argv "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/node" "/tmp/build_a2875fc163b209225122d68916f1d4df/.heroku/node/bin/npm" "run" "build"
```
In this case, ensure that the file is there with the proper lettercase and that’s not ignored on your local `.gitignore` or `~/.gitignore_global`.
### [Netlify](https://www.netlify.com/)
**To do a manual deploy to Netlify’s CDN:**
```sh
npm install netlify-cli -g
netlify deploy
```
Choose `build` as the path to deploy.
**To setup continuous delivery:**
With this setup Netlify will build and deploy when you push to git or open a pull request:
1. [Start a new netlify project](https://app.netlify.com/signup)
2. Pick your Git hosting service and select your repository
3. Set `yarn build` as the build command and `build` as the publish directory
4. Click `Deploy site`
**Support for client-side routing:**
To support `pushState`, make sure to create a `public/_redirects` file with the following rewrite rules:
```
/* /index.html 200
```
When you build the project, Create React App will place the `public` folder contents into the build output.
### [Now](https://zeit.co/now)
Now offers a zero-configuration single-command deployment. You can use `now` to deploy your app for free.
1. Install the `now` command-line tool either via the recommended [desktop tool](https://zeit.co/download) or via node with `npm install -g now`.
2. Build your app by running `npm run build`.
3. Move into the build directory by running `cd build`.
4. Run `now --name your-project-name` from within the build directory. You will see a **now.sh** URL in your output like this:
```
> Ready! https://your-project-name-tpspyhtdtk.now.sh (copied to clipboard)
```
Paste that URL into your browser when the build is complete, and you will see your deployed app.
Details are available in [this article.](https://zeit.co/blog/unlimited-static)
### [S3](https://aws.amazon.com/s3) and [CloudFront](https://aws.amazon.com/cloudfront/)
See this [blog post](https://medium.com/@omgwtfmarc/deploying-create-react-app-to-s3-or-cloudfront-48dae4ce0af) on how to deploy your React app to Amazon Web Services S3 and CloudFront.
### [Surge](https://surge.sh/)
Install the Surge CLI if you haven’t already by running `npm install -g surge`. Run the `surge` command and log in you or create a new account.
When asked about the project path, make sure to specify the `build` folder, for example:
```sh
project path: /path/to/project/build
```
Note that in order to support routers that use HTML5 `pushState` API, you may want to rename the `index.html` in your build folder to `200.html` before deploying to Surge. This [ensures that every URL falls back to that file](https://surge.sh/help/adding-a-200-page-for-client-side-routing).
## Advanced Configuration
You can adjust various development and production settings by setting environment variables in your shell or with [.env](#adding-development-environment-variables-in-env).
| Variable | Development | Production | Usage |
| :------------------ | :--------------------: | :----------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| BROWSER | :white_check_mark: | :x: | By default, Create React App will open the default system browser, favoring Chrome on macOS. Specify a [browser](https://github.com/sindresorhus/opn#app) to override this behavior, or set it to `none` to disable it completely. If you need to customize the way the browser is launched, you can specify a node script instead. Any arguments passed to `npm start` will also be passed to this script, and the url where your app is served will be the last argument. Your script's file name must have the `.js` extension. |
| HOST | :white_check_mark: | :x: | By default, the development web server binds to `localhost`. You may use this variable to specify a different host. |
| PORT | :white_check_mark: | :x: | By default, the development web server will attempt to listen on port 3000 or prompt you to attempt the next available port. You may use this variable to specify a different port. |
| HTTPS | :white_check_mark: | :x: | When set to `true`, Create React App will run the development server in `https` mode. |
| PUBLIC_URL | :x: | :white_check_mark: | Create React App assumes your application is hosted at the serving web server's root or a subpath as specified in [`package.json` (`homepage`)](#building-for-relative-paths). Normally, Create React App ignores the hostname. You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application. |
| CI | :large_orange_diamond: | :white_check_mark: | When set to `true`, Create React App treats warnings as failures in the build. It also makes the test runner non-watching. Most CIs set this flag by default. |
| REACT_EDITOR | :white_check_mark: | :x: | When an app crashes in development, you will see an error overlay with clickable stack trace. When you click on it, Create React App will try to determine the editor you are using based on currently running processes, and open the relevant source file. You can [send a pull request to detect your editor of choice](https://github.com/facebookincubator/create-react-app/issues/2636). Setting this environment variable overrides the automatic detection. If you do it, make sure your systems [PATH]() environment variable points to your editor’s bin folder. You can also set it to `none` to disable it completely. |
| CHOKIDAR_USEPOLLING | :white_check_mark: | :x: | When set to `true`, the watcher runs in polling mode, as necessary inside a VM. Use this option if `npm start` isn't detecting changes. |
| GENERATE_SOURCEMAP | :x: | :white_check_mark: | When set to `false`, source maps are not generated for a production build. This solves OOM issues on some smaller machines. |
| NODE_PATH | :white_check_mark: | :white_check_mark: | Same as [`NODE_PATH` in Node.js](https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders), but only relative folders are allowed. Can be handy for emulating a monorepo setup by setting `NODE_PATH=src`. |
## Troubleshooting
### `npm start` doesn’t detect changes
When you save a file while `npm start` is running, the browser should refresh with the updated code.
If this doesn’t happen, try one of the following workarounds:
- If your project is in a Dropbox folder, try moving it out.
- If the watcher doesn’t see a file called `index.js` and you’re referencing it by the folder name, you [need to restart the watcher](https://github.com/facebookincubator/create-react-app/issues/1164) due to a Webpack bug.
- Some editors like Vim and IntelliJ have a “safe write” feature that currently breaks the watcher. You will need to disable it. Follow the instructions in [“Adjusting Your Text Editor”](https://webpack.js.org/guides/development/#adjusting-your-text-editor).
- If your project path contains parentheses, try moving the project to a path without them. This is caused by a [Webpack watcher bug](https://github.com/webpack/watchpack/issues/42).
- On Linux and macOS, you might need to [tweak system settings](https://github.com/webpack/docs/wiki/troubleshooting#not-enough-watchers) to allow more watchers.
- If the project runs inside a virtual machine such as (a Vagrant provisioned) VirtualBox, create an `.env` file in your project directory if it doesn’t exist, and add `CHOKIDAR_USEPOLLING=true` to it. This ensures that the next time you run `npm start`, the watcher uses the polling mode, as necessary inside a VM.
If none of these solutions help please leave a comment [in this thread](https://github.com/facebookincubator/create-react-app/issues/659).
### `npm test` hangs on macOS Sierra
If you run `npm test` and the console gets stuck after printing `react-scripts test --env=jsdom` to the console there might be a problem with your [Watchman](https://facebook.github.io/watchman/) installation as described in [facebookincubator/create-react-app#713](https://github.com/facebookincubator/create-react-app/issues/713).
We recommend deleting `node_modules` in your project and running `npm install` (or `yarn` if you use it) first. If it doesn't help, you can try one of the numerous workarounds mentioned in these issues:
- [facebook/jest#1767](https://github.com/facebook/jest/issues/1767)
- [facebook/watchman#358](https://github.com/facebook/watchman/issues/358)
- [ember-cli/ember-cli#6259](https://github.com/ember-cli/ember-cli/issues/6259)
It is reported that installing Watchman 4.7.0 or newer fixes the issue. If you use [Homebrew](http://brew.sh/), you can run these commands to update it:
```
watchman shutdown-server
brew update
brew reinstall watchman
```
You can find [other installation methods](https://facebook.github.io/watchman/docs/install.html#build-install) on the Watchman documentation page.
If this still doesn’t help, try running `launchctl unload -F ~/Library/LaunchAgents/com.github.facebook.watchman.plist`.
There are also reports that _uninstalling_ Watchman fixes the issue. So if nothing else helps, remove it from your system and try again.
### `npm run build` exits too early
It is reported that `npm run build` can fail on machines with limited memory and no swap space, which is common in cloud environments. Even with small projects this command can increase RAM usage in your system by hundreds of megabytes, so if you have less than 1 GB of available memory your build is likely to fail with the following message:
> The build failed because the process exited too early. This probably means the system ran out of memory or someone called `kill -9` on the process.
If you are completely sure that you didn't terminate the process, consider [adding some swap space](https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04) to the machine you’re building on, or build the project locally.
### `npm run build` fails on Heroku
This may be a problem with case sensitive filenames.
Please refer to [this section](#resolving-heroku-deployment-errors).
### Moment.js locales are missing
If you use a [Moment.js](https://momentjs.com/), you might notice that only the English locale is available by default. This is because the locale files are large, and you probably only need a subset of [all the locales provided by Moment.js](https://momentjs.com/#multiple-locale-support).
To add a specific Moment.js locale to your bundle, you need to import it explicitly.
For example:
```js
import moment from 'moment';
import 'moment/locale/fr';
```
If import multiple locales this way, you can later switch between them by calling `moment.locale()` with the locale name:
```js
import moment from 'moment';
import 'moment/locale/fr';
import 'moment/locale/es';
// ...
moment.locale('fr');
```
This will only work for locales that have been explicitly imported before.
### `npm run build` fails to minify
Some third-party packages don't compile their code to ES5 before publishing to npm. This often causes problems in the ecosystem because neither browsers (except for most modern versions) nor some tools currently support all ES6 features. We recommend to publish code on npm as ES5 at least for a few more years.
To resolve this:
1. Open an issue on the dependency's issue tracker and ask that the package be published pre-compiled.
- Note: Create React App can consume both CommonJS and ES modules. For Node.js compatibility, it is recommended that the main entry point is CommonJS. However, they can optionally provide an ES module entry point with the `module` field in `package.json`. Note that **even if a library provides an ES Modules version, it should still precompile other ES6 features to ES5 if it intends to support older browsers**.
2. Fork the package and publish a corrected version yourself.
3. If the dependency is small enough, copy it to your `src/` folder and treat it as application code.
In the future, we might start automatically compiling incompatible third-party modules, but it is not currently supported. This approach would also slow down the production builds.
## Alternatives to Ejecting
[Ejecting](#npm-run-eject) lets you customize anything, but from that point on you have to maintain the configuration and scripts yourself. This can be daunting if you have many similar projects. In such cases instead of ejecting we recommend to _fork_ `react-scripts` and any other packages you need. [This article](https://auth0.com/blog/how-to-configure-create-react-app/) dives into how to do it in depth. You can find more discussion in [this issue](https://github.com/facebookincubator/create-react-app/issues/682).
## Something Missing?
If you have ideas for more “How To” recipes that should be on this page, [let us know](https://github.com/facebookincubator/create-react-app/issues) or [contribute some!](https://github.com/facebookincubator/create-react-app/edit/master/packages/react-scripts/template/README.md)
================================================
FILE: examples/dummy-app/package.json
================================================
{
"name": "@pollyjs/dummy-app",
"version": "0.1.0",
"private": true,
"license": "Apache-2.0",
"dependencies": {
"prop-types": "^15.6.2",
"ra-data-json-server": "^2.3.1",
"react": "^16.5.1",
"react-admin": "^2.3.1",
"react-dom": "^16.5.1",
"react-scripts": "^1.1.5"
},
"scripts": {
"start": "react-scripts start",
"start:ci": "BROWSER=none CI=true yarn start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
================================================
FILE: examples/dummy-app/public/index.html
================================================
Dummy App
You need to enable JavaScript to run this app.
================================================
FILE: examples/dummy-app/public/manifest.json
================================================
{
"short_name": "Dummy App",
"name": "Polly.JS Examples Dummy App",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": "./index.html",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
================================================
FILE: examples/dummy-app/src/App.js
================================================
import React from 'react';
import { Admin, Resource } from 'react-admin';
import jsonServerProvider from 'ra-data-json-server';
import PostIcon from '@material-ui/icons/Book';
import TodoIcon from '@material-ui/icons/ViewList';
import UserIcon from '@material-ui/icons/Group';
import { createMuiTheme } from '@material-ui/core/styles';
import { UserList, UserShow } from './users';
import { TodoList, TodoShow, TodoEdit, TodoCreate } from './todos';
import { PostList, PostShow, PostEdit, PostCreate } from './posts';
const dataProvider = jsonServerProvider('https://jsonplaceholder.typicode.com');
const theme = createMuiTheme({
palette: {
primary: {
light: '#ff5740',
main: '#e50914',
dark: '#aa0000',
contrastText: '#fff'
},
secondary: {
light: '#ff5740',
main: '#e50914',
dark: '#aa0000',
contrastText: '#fff'
}
}
});
const App = () => (
);
export default App;
================================================
FILE: examples/dummy-app/src/index.css
================================================
body {
margin: 0;
padding: 0;
}
================================================
FILE: examples/dummy-app/src/index.js
================================================
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render( , document.getElementById('root'));
================================================
FILE: examples/dummy-app/src/posts.js
================================================
import React from 'react';
import PropTypes from 'prop-types';
import {
List,
Edit,
Create,
Datagrid,
ReferenceField,
TextField,
EditButton,
ShowButton,
DisabledInput,
LongTextInput,
ReferenceInput,
SelectInput,
SimpleForm,
TextInput,
Filter,
Show,
SimpleShowLayout
} from 'react-admin';
const PostFilter = (props) => (
);
const PostTitle = ({ record }) => {
return Posts - {record ? `${record.title}` : ''} ;
};
PostTitle.propTypes = {
record: PropTypes.PropTypes.shape({
title: PropTypes.string
})
};
export const PostList = (props) => (
}
sort={{ field: 'title', order: 'ASC' }}
>
);
export const PostShow = (props) => (
} {...props}>
);
export const PostEdit = (props) => (
} {...props}>
);
export const PostCreate = (props) => (
);
================================================
FILE: examples/dummy-app/src/todos.js
================================================
import React from 'react';
import PropTypes from 'prop-types';
import {
List,
Edit,
Create,
Show,
Datagrid,
BooleanField,
ReferenceField,
TextField,
DisabledInput,
SelectInput,
ShowButton,
EditButton,
SimpleForm,
SimpleShowLayout,
TextInput,
BooleanInput,
ReferenceInput,
Filter
} from 'react-admin';
const TodoFilter = (props) => (
);
const TodoTitle = ({ record }) => {
return Todos - {record ? `${record.title}` : ''} ;
};
TodoTitle.propTypes = {
record: PropTypes.PropTypes.shape({
title: PropTypes.string
})
};
export const TodoList = (props) => (
}
sort={{ field: 'title', order: 'ASC' }}
>
);
export const TodoShow = (props) => (
} {...props}>
);
export const TodoEdit = (props) => (
} {...props}>
);
export const TodoCreate = (props) => (
);
================================================
FILE: examples/dummy-app/src/users.js
================================================
import React from 'react';
import PropTypes from 'prop-types';
import {
List,
Datagrid,
EmailField,
TextField,
Show,
SimpleShowLayout,
ShowButton
} from 'react-admin';
const UserTitle = ({ record }) => {
return Users - {record ? `${record.name}` : ''} ;
};
UserTitle.propTypes = {
record: PropTypes.PropTypes.shape({
name: PropTypes.string
})
};
export const UserList = (props) => (
);
export const UserShow = (props) => (
} {...props}>
);
================================================
FILE: examples/jest-node-fetch/.eslintrc.js
================================================
module.exports = {
env: {
jest: true
}
};
================================================
FILE: examples/jest-node-fetch/__recordings__/jest-node-fetch_1142061259/posts_1278140380/should-return-post_148615714/recording.har
================================================
{
"log": {
"_recordingName": "jest-node-fetch/posts/should return post",
"creator": {
"comment": "persister:fs",
"name": "Polly.JS",
"version": "1.4.1"
},
"entries": [
{
"_id": "41b7d6ef74440e3b785f1634743f9139",
"_order": 0,
"cache": {},
"request": {
"bodySize": 0,
"cookies": [],
"headers": [
{
"name": "accept",
"value": [
"*/*"
]
},
{
"name": "user-agent",
"value": [
"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"
]
},
{
"name": "accept-encoding",
"value": [
"gzip,deflate"
]
},
{
"name": "connection",
"value": [
"close"
]
},
{
"name": "host",
"value": "jsonplaceholder.typicode.com"
}
],
"headersSize": 228,
"httpVersion": "HTTP/1.1",
"method": "GET",
"postData": {
"mimeType": "text/plain"
},
"queryString": [],
"url": "https://jsonplaceholder.typicode.com/posts/1"
},
"response": {
"bodySize": 408,
"content": {
"mimeType": "application/json; charset=utf-8",
"size": 408,
"text": "[\"1f8b0800000000000003558f4b6a04410c43f7730a51eb6cb29d1be40ebd715c0a63e8fa8ccb1e2684dc3d744308012324901fe8eb02945cf4b75aae787d39a2fdd9b0d859ae282b7b4032f0214a279c93fb2e81e9e361953d3054852a61e0533923dd3066d838cace1b7ba55b9413fc3eeae7c1bda7091858b9d4a6c5d67f1d9c9a4b7a1542475fbc67f648079f93d5e27cd36c5bff87471b3b57981019c7dd53166284b4adf7b1c2b3c17928d739890de73a67031fecc680b8de2ca831cae5fb0715c693e824010000\"]"
},
"cookies": [
{
"domain": ".typicode.com",
"expires": "2020-01-10T21:41:12.000Z",
"httpOnly": true,
"name": "__cfduid",
"path": "/",
"value": "d1a5589e8309b42c054255a4709d3a4401547156472"
}
],
"headers": [
{
"name": "date",
"value": "Thu, 10 Jan 2019 21:41:12 GMT"
},
{
"name": "content-type",
"value": "application/json; charset=utf-8"
},
{
"name": "transfer-encoding",
"value": "chunked"
},
{
"name": "connection",
"value": "close"
},
{
"name": "set-cookie",
"value": [
"__cfduid=d1a5589e8309b42c054255a4709d3a4401547156472; expires=Fri, 10-Jan-20 21:41:12 GMT; path=/; domain=.typicode.com; HttpOnly"
]
},
{
"name": "x-powered-by",
"value": "Express"
},
{
"name": "vary",
"value": "Origin, Accept-Encoding"
},
{
"name": "access-control-allow-credentials",
"value": "true"
},
{
"name": "cache-control",
"value": "public, max-age=14400"
},
{
"name": "pragma",
"value": "no-cache"
},
{
"name": "expires",
"value": "Fri, 11 Jan 2019 01:41:12 GMT"
},
{
"name": "x-content-type-options",
"value": "nosniff"
},
{
"name": "etag",
"value": "W/\"124-yiKdLzqO5gfBrJFrcdJ8Yq0LGnU\""
},
{
"name": "via",
"value": "1.1 vegur"
},
{
"name": "cf-cache-status",
"value": "HIT"
},
{
"name": "expect-ct",
"value": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
},
{
"name": "server",
"value": "cloudflare"
},
{
"name": "cf-ray",
"value": "49724e71dcd2bca4-SEA"
},
{
"name": "content-encoding",
"value": "gzip"
}
],
"headersSize": 754,
"httpVersion": "HTTP/1.1",
"redirectURL": "",
"status": 200,
"statusText": "OK"
},
"startedDateTime": "2019-01-10T21:41:11.992Z",
"time": 71,
"timings": {
"blocked": -1,
"connect": -1,
"dns": -1,
"receive": 0,
"send": 0,
"ssl": -1,
"wait": 71
}
}
],
"pages": [],
"version": "1.2"
}
}
================================================
FILE: examples/jest-node-fetch/__recordings__/jest-node-fetch_1142061259/users_1585235219/should-return-user_4259424139/recording.har
================================================
{
"log": {
"_recordingName": "jest-node-fetch/users/should return user",
"creator": {
"comment": "persister:fs",
"name": "Polly.JS",
"version": "1.4.1"
},
"entries": [
{
"_id": "902ec6bd7d5925aefdb6e4091e660f11",
"_order": 0,
"cache": {},
"request": {
"bodySize": 0,
"cookies": [],
"headers": [
{
"name": "accept",
"value": [
"*/*"
]
},
{
"name": "user-agent",
"value": [
"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"
]
},
{
"name": "accept-encoding",
"value": [
"gzip,deflate"
]
},
{
"name": "connection",
"value": [
"close"
]
},
{
"name": "host",
"value": "jsonplaceholder.typicode.com"
}
],
"headersSize": 228,
"httpVersion": "HTTP/1.1",
"method": "GET",
"postData": {
"mimeType": "text/plain"
},
"queryString": [],
"url": "https://jsonplaceholder.typicode.com/users/1"
},
"response": {
"bodySize": 662,
"content": {
"mimeType": "application/json; charset=utf-8",
"size": 662,
"text": "[\"1f8b08000000000000034590cd6e83301084ef3cc5cae71a95000172eacf2187a652d53ec1022bb06a6cb4364d9328ef5e61427ab3e6dbf5eccc250210aa153b481ee6a7c181c40ec481d018823d638f83086872c42b7e61f28b4a032a3d4b5fca34c4f484232b1dd7eabc706c5b26e7c40e2e110080709e89fcbcf136697470505dbffc35c349f960f03cfa18f27cbb8246f9d3acef8f646acb76eafa159dd5d8d8366c559baa2a655a16d90a3bb2776b00a13138cbb488d324af6e533330dd0cca244eb26a2b827c8d00ae21c4d85b130c1259148fb248b7b27c4c13f8cdb759b659821ea976b7e37ba55bea90dbd872b7d0c60e239ad37f0d6b939f76c06e2246f9cad6e03d2ffaa6ffe8195d987a9fb45752e389985a68b422e3a523fe21064313a39686ee2dd62e5c816cc83960422dbd1a08480ec8dfe4dd9cef1a5dff006748ce45fd010000\"]"
},
"cookies": [
{
"domain": ".typicode.com",
"expires": "2020-01-10T21:41:12.000Z",
"httpOnly": true,
"name": "__cfduid",
"path": "/",
"value": "d9290fa7f69379aa1374913e89cbc6aaf1547156472"
}
],
"headers": [
{
"name": "date",
"value": "Thu, 10 Jan 2019 21:41:12 GMT"
},
{
"name": "content-type",
"value": "application/json; charset=utf-8"
},
{
"name": "transfer-encoding",
"value": "chunked"
},
{
"name": "connection",
"value": "close"
},
{
"name": "set-cookie",
"value": [
"__cfduid=d9290fa7f69379aa1374913e89cbc6aaf1547156472; expires=Fri, 10-Jan-20 21:41:12 GMT; path=/; domain=.typicode.com; HttpOnly"
]
},
{
"name": "x-powered-by",
"value": "Express"
},
{
"name": "vary",
"value": "Origin, Accept-Encoding"
},
{
"name": "access-control-allow-credentials",
"value": "true"
},
{
"name": "cache-control",
"value": "public, max-age=14400"
},
{
"name": "pragma",
"value": "no-cache"
},
{
"name": "expires",
"value": "Fri, 11 Jan 2019 01:41:12 GMT"
},
{
"name": "x-content-type-options",
"value": "nosniff"
},
{
"name": "etag",
"value": "W/\"1fd-+2Y3G3w049iSZtw5t1mzSnunngE\""
},
{
"name": "via",
"value": "1.1 vegur"
},
{
"name": "cf-cache-status",
"value": "HIT"
},
{
"name": "expect-ct",
"value": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
},
{
"name": "server",
"value": "cloudflare"
},
{
"name": "cf-ray",
"value": "49724e721ed0bc98-SEA"
},
{
"name": "content-encoding",
"value": "gzip"
}
],
"headersSize": 754,
"httpVersion": "HTTP/1.1",
"redirectURL": "",
"status": 200,
"statusText": "OK"
},
"startedDateTime": "2019-01-10T21:41:12.082Z",
"time": 16,
"timings": {
"blocked": -1,
"connect": -1,
"dns": -1,
"receive": 0,
"send": 0,
"ssl": -1,
"wait": 16
}
}
],
"pages": [],
"version": "1.2"
}
}
================================================
FILE: examples/jest-node-fetch/__tests__/index.test.js
================================================
const path = require('path');
const { Polly } = require('@pollyjs/core');
const { setupPolly } = require('setup-polly-jest');
const NodeHttpAdapter = require('@pollyjs/adapter-node-http');
const FSPersister = require('@pollyjs/persister-fs');
Polly.register(NodeHttpAdapter);
Polly.register(FSPersister);
const { posts, users } = require('../src');
describe('jest-node-fetch', () => {
setupPolly({
adapters: ['node-http'],
persister: 'fs',
persisterOptions: {
fs: {
recordingsDir: path.resolve(__dirname, '../__recordings__')
}
}
});
describe('posts', () => {
it('should return post', async () => {
const post = await posts('1');
expect(post.id).toBe(1);
expect(post.title).toBe(
'sunt aut facere repellat provident occaecati excepturi optio reprehenderit'
);
});
});
describe('users', () => {
it('should return user', async () => {
const user = await users('1');
expect(user.id).toBe(1);
expect(user.name).toBe('Leanne Graham');
expect(user.email).toBe('Sincere@april.biz');
});
});
});
================================================
FILE: examples/jest-node-fetch/package.json
================================================
{
"name": "@pollyjs/jest-node-fetch-example",
"version": "0.1.0",
"private": true,
"license": "Apache-2.0",
"scripts": {
"test": "jest"
},
"devDependencies": {
"@pollyjs/adapter-node-http": "*",
"@pollyjs/core": "*",
"@pollyjs/persister-fs": "*",
"jest": "*",
"node-fetch": "*",
"setup-polly-jest": "*"
}
}
================================================
FILE: examples/jest-node-fetch/src/index.js
================================================
module.exports = {
posts: require('./posts'),
users: require('./users')
};
================================================
FILE: examples/jest-node-fetch/src/posts.js
================================================
const fetch = require('node-fetch');
module.exports = async (id) => {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts/${id}`
);
return await response.json();
};
================================================
FILE: examples/jest-node-fetch/src/users.js
================================================
const fetch = require('node-fetch');
module.exports = async (id) => {
const response = await fetch(
`https://jsonplaceholder.typicode.com/users/${id}`
);
return await response.json();
};
================================================
FILE: examples/jest-puppeteer/.eslintrc.js
================================================
module.exports = {
env: {
jest: true
},
globals: {
page: true,
browser: true,
jestPuppeteer: true
}
};
================================================
FILE: examples/jest-puppeteer/__recordings__/jest-puppeteer_2726822272/should-be-able-to-navigate-to-all-routes_1130491217/recording.har
================================================
{
"log": {
"_recordingName": "jest-puppeteer/should be able to navigate to all routes",
"creator": {
"comment": "persister:fs",
"name": "Polly.JS",
"version": "4.0.2"
},
"entries": [
{
"_id": "7a6a80a84887e23d598869aa95e38bd9",
"_order": 0,
"cache": {},
"request": {
"bodySize": 0,
"cookies": [],
"headers": [
{
"name": "accept",
"value": "application/json"
},
{
"name": "referer",
"value": "http://localhost:3000/"
},
{
"name": "origin",
"value": "http://localhost:3000"
},
{
"name": "user-agent",
"value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3582.0 Safari/537.36"
}
],
"headersSize": 322,
"httpVersion": "HTTP/1.1",
"method": "GET",
"queryString": [
{
"name": "_end",
"value": "10"
},
{
"name": "_order",
"value": "ASC"
},
{
"name": "_sort",
"value": "title"
},
{
"name": "_start",
"value": "0"
}
],
"url": "https://jsonplaceholder.typicode.com/posts?_end=10&_order=ASC&_sort=title&_start=0"
},
"response": {
"bodySize": 2594,
"content": {
"mimeType": "application/json; charset=utf-8",
"size": 2594,
"text": "[\n {\n \"userId\": 3,\n \"id\": 30,\n \"title\": \"a quo magni similique perferendis\",\n \"body\": \"alias dolor cumque\\nimpedit blanditiis non eveniet odio maxime\\nblanditiis amet eius quis tempora quia autem rem\\na provident perspiciatis quia\"\n },\n {\n \"userId\": 9,\n \"id\": 90,\n \"title\": \"ad iusto omnis odit dolor voluptatibus\",\n \"body\": \"minus omnis soluta quia\\nqui sed adipisci voluptates illum ipsam voluptatem\\neligendi officia ut in\\neos soluta similique molestias praesentium blanditiis\"\n },\n {\n \"userId\": 2,\n \"id\": 19,\n \"title\": \"adipisci placeat illum aut reiciendis qui\",\n \"body\": \"illum quis cupiditate provident sit magnam\\nea sed aut omnis\\nveniam maiores ullam consequatur atque\\nadipisci quo iste expedita sit quos voluptas\"\n },\n {\n \"userId\": 7,\n \"id\": 67,\n \"title\": \"aliquid eos sed fuga est maxime repellendus\",\n \"body\": \"reprehenderit id nostrum\\nvoluptas doloremque pariatur sint et accusantium quia quod aspernatur\\net fugiat amet\\nnon sapiente et consequatur necessitatibus molestiae\"\n },\n {\n \"userId\": 3,\n \"id\": 21,\n \"title\": \"asperiores ea ipsam voluptatibus modi minima quia sint\",\n \"body\": \"repellat aliquid praesentium dolorem quo\\nsed totam minus non itaque\\nnihil labore molestiae sunt dolor eveniet hic recusandae veniam\\ntempora et tenetur expedita sunt\"\n },\n {\n \"userId\": 10,\n \"id\": 100,\n \"title\": \"at nam consequatur ea labore ea harum\",\n \"body\": \"cupiditate quo est a modi nesciunt soluta\\nipsa voluptas error itaque dicta in\\nautem qui minus magnam et distinctio eum\\naccusamus ratione error aut\"\n },\n {\n \"userId\": 10,\n \"id\": 91,\n \"title\": \"aut amet sed\",\n \"body\": \"libero voluptate eveniet aperiam sed\\nsunt placeat suscipit molestias\\nsimilique fugit nam natus\\nexpedita consequatur consequatur dolores quia eos et placeat\"\n },\n {\n \"userId\": 5,\n \"id\": 46,\n \"title\": \"aut quo modi neque nostrum ducimus\",\n \"body\": \"voluptatem quisquam iste\\nvoluptatibus natus officiis facilis dolorem\\nquis quas ipsam\\nvel et voluptatum in aliquid\"\n },\n {\n \"userId\": 3,\n \"id\": 24,\n \"title\": \"autem hic labore sunt dolores incidunt\",\n \"body\": \"enim et ex nulla\\nomnis voluptas quia qui\\nvoluptatem consequatur numquam aliquam sunt\\ntotam recusandae id dignissimos aut sed asperiores deserunt\"\n },\n {\n \"userId\": 7,\n \"id\": 62,\n \"title\": \"beatae enim quia vel\",\n \"body\": \"enim aspernatur illo distinctio quae praesentium\\nbeatae alias amet delectus qui voluptate distinctio\\nodit sint accusantium autem omnis\\nquo molestiae omnis ea eveniet optio\"\n }\n]"
},
"cookies": [
{
"domain": ".typicode.com",
"expires": "2020-02-29T07:09:08.000Z",
"httpOnly": true,
"name": "__cfduid",
"path": "/",
"sameSite": "Lax",
"value": "d42dac9bc17ea4fe874662c606ae95df71580368148"
}
],
"headers": [
{
"name": "date",
"value": "Thu, 30 Jan 2020 07:09:08 GMT"
},
{
"name": "via",
"value": "1.1 vegur"
},
{
"name": "x-content-type-options",
"value": "nosniff"
},
{
"name": "cf-cache-status",
"value": "HIT"
},
{
"name": "age",
"value": "3771"
},
{
"name": "x-powered-by",
"value": "Express"
},
{
"name": "status",
"value": "200"
},
{
"name": "content-encoding",
"value": "br"
},
{
"name": "x-total-count",
"value": "100"
},
{
"name": "pragma",
"value": "no-cache"
},
{
"name": "server",
"value": "cloudflare"
},
{
"name": "etag",
"value": "W/\"a22-FI+zdCzw2iL/TSmHe3WZs7jlNFI\""
},
{
"name": "expect-ct",
"value": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
},
{
"name": "vary",
"value": "Origin, Accept-Encoding"
},
{
"name": "content-type",
"value": "application/json; charset=utf-8"
},
{
"name": "access-control-allow-origin",
"value": "http://localhost:3000"
},
{
"name": "access-control-expose-headers",
"value": "X-Total-Count"
},
{
"name": "cache-control",
"value": "max-age=14400"
},
{
"name": "access-control-allow-credentials",
"value": "true"
},
{
"name": "set-cookie",
"value": "__cfduid=d42dac9bc17ea4fe874662c606ae95df71580368148; expires=Sat, 29-Feb-20 07:09:08 GMT; path=/; domain=.typicode.com; HttpOnly; SameSite=Lax"
},
{
"name": "cf-ray",
"value": "55d19e5cff4293b8-SJC"
},
{
"name": "expires",
"value": "-1"
}
],
"headersSize": 826,
"httpVersion": "HTTP/1.1",
"redirectURL": "",
"status": 200,
"statusText": "OK"
},
"startedDateTime": "2020-01-30T07:08:19.576Z",
"time": 167,
"timings": {
"blocked": -1,
"connect": -1,
"dns": -1,
"receive": 0,
"send": 0,
"ssl": -1,
"wait": 167
}
},
{
"_id": "8ce66159473fb131cc371230c3edcb70",
"_order": 0,
"cache": {},
"request": {
"bodySize": 0,
"cookies": [],
"headers": [
{
"name": "accept",
"value": "application/json"
},
{
"name": "referer",
"value": "http://localhost:3000/"
},
{
"name": "origin",
"value": "http://localhost:3000"
},
{
"name": "user-agent",
"value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3582.0 Safari/537.36"
}
],
"headersSize": 313,
"httpVersion": "HTTP/1.1",
"method": "GET",
"queryString": [
{
"_fromType": "array",
"name": "id",
"value": "3"
},
{
"_fromType": "array",
"name": "id",
"value": "9"
},
{
"_fromType": "array",
"name": "id",
"value": "2"
},
{
"_fromType": "array",
"name": "id",
"value": "7"
},
{
"_fromType": "array",
"name": "id",
"value": "10"
},
{
"_fromType": "array",
"name": "id",
"value": "5"
}
],
"url": "https://jsonplaceholder.typicode.com/users?id=3&id=9&id=2&id=7&id=10&id=5"
},
"response": {
"bodySize": 3360,
"content": {
"mimeType": "application/json; charset=utf-8",
"size": 3360,
"text": "[\n {\n \"id\": 2,\n \"name\": \"Ervin Howell\",\n \"username\": \"Antonette\",\n \"email\": \"Shanna@melissa.tv\",\n \"address\": {\n \"street\": \"Victor Plains\",\n \"suite\": \"Suite 879\",\n \"city\": \"Wisokyburgh\",\n \"zipcode\": \"90566-7771\",\n \"geo\": {\n \"lat\": \"-43.9509\",\n \"lng\": \"-34.4618\"\n }\n },\n \"phone\": \"010-692-6593 x09125\",\n \"website\": \"anastasia.net\",\n \"company\": {\n \"name\": \"Deckow-Crist\",\n \"catchPhrase\": \"Proactive didactic contingency\",\n \"bs\": \"synergize scalable supply-chains\"\n }\n },\n {\n \"id\": 3,\n \"name\": \"Clementine Bauch\",\n \"username\": \"Samantha\",\n \"email\": \"Nathan@yesenia.net\",\n \"address\": {\n \"street\": \"Douglas Extension\",\n \"suite\": \"Suite 847\",\n \"city\": \"McKenziehaven\",\n \"zipcode\": \"59590-4157\",\n \"geo\": {\n \"lat\": \"-68.6102\",\n \"lng\": \"-47.0653\"\n }\n },\n \"phone\": \"1-463-123-4447\",\n \"website\": \"ramiro.info\",\n \"company\": {\n \"name\": \"Romaguera-Jacobson\",\n \"catchPhrase\": \"Face to face bifurcated interface\",\n \"bs\": \"e-enable strategic applications\"\n }\n },\n {\n \"id\": 5,\n \"name\": \"Chelsey Dietrich\",\n \"username\": \"Kamren\",\n \"email\": \"Lucio_Hettinger@annie.ca\",\n \"address\": {\n \"street\": \"Skiles Walks\",\n \"suite\": \"Suite 351\",\n \"city\": \"Roscoeview\",\n \"zipcode\": \"33263\",\n \"geo\": {\n \"lat\": \"-31.8129\",\n \"lng\": \"62.5342\"\n }\n },\n \"phone\": \"(254)954-1289\",\n \"website\": \"demarco.info\",\n \"company\": {\n \"name\": \"Keebler LLC\",\n \"catchPhrase\": \"User-centric fault-tolerant solution\",\n \"bs\": \"revolutionize end-to-end systems\"\n }\n },\n {\n \"id\": 7,\n \"name\": \"Kurtis Weissnat\",\n \"username\": \"Elwyn.Skiles\",\n \"email\": \"Telly.Hoeger@billy.biz\",\n \"address\": {\n \"street\": \"Rex Trail\",\n \"suite\": \"Suite 280\",\n \"city\": \"Howemouth\",\n \"zipcode\": \"58804-1099\",\n \"geo\": {\n \"lat\": \"24.8918\",\n \"lng\": \"21.8984\"\n }\n },\n \"phone\": \"210.067.6132\",\n \"website\": \"elvis.io\",\n \"company\": {\n \"name\": \"Johns Group\",\n \"catchPhrase\": \"Configurable multimedia task-force\",\n \"bs\": \"generate enterprise e-tailers\"\n }\n },\n {\n \"id\": 9,\n \"name\": \"Glenna Reichert\",\n \"username\": \"Delphine\",\n \"email\": \"Chaim_McDermott@dana.io\",\n \"address\": {\n \"street\": \"Dayna Park\",\n \"suite\": \"Suite 449\",\n \"city\": \"Bartholomebury\",\n \"zipcode\": \"76495-3109\",\n \"geo\": {\n \"lat\": \"24.6463\",\n \"lng\": \"-168.8889\"\n }\n },\n \"phone\": \"(775)976-6794 x41206\",\n \"website\": \"conrad.com\",\n \"company\": {\n \"name\": \"Yost and Sons\",\n \"catchPhrase\": \"Switchable contextually-based project\",\n \"bs\": \"aggregate real-time technologies\"\n }\n },\n {\n \"id\": 10,\n \"name\": \"Clementina DuBuque\",\n \"username\": \"Moriah.Stanton\",\n \"email\": \"Rey.Padberg@karina.biz\",\n \"address\": {\n \"street\": \"Kattie Turnpike\",\n \"suite\": \"Suite 198\",\n \"city\": \"Lebsackbury\",\n \"zipcode\": \"31428-2261\",\n \"geo\": {\n \"lat\": \"-38.2386\",\n \"lng\": \"57.2232\"\n }\n },\n \"phone\": \"024-648-3804\",\n \"website\": \"ambrose.net\",\n \"company\": {\n \"name\": \"Hoeger LLC\",\n \"catchPhrase\": \"Centralized empowering task-force\",\n \"bs\": \"target end-to-end models\"\n }\n }\n]"
},
"cookies": [
{
"domain": ".typicode.com",
"expires": "2020-02-29T07:09:08.000Z",
"httpOnly": true,
"name": "__cfduid",
"path": "/",
"sameSite": "Lax",
"value": "d42dac9bc17ea4fe874662c606ae95df71580368148"
}
],
"headers": [
{
"name": "date",
"value": "Thu, 30 Jan 2020 07:09:08 GMT"
},
{
"name": "via",
"value": "1.1 vegur"
},
{
"name": "x-content-type-options",
"value": "nosniff"
},
{
"name": "cf-cache-status",
"value": "HIT"
},
{
"name": "age",
"value": "3770"
},
{
"name": "x-powered-by",
"value": "Express"
},
{
"name": "status",
"value": "200"
},
{
"name": "content-encoding",
"value": "br"
},
{
"name": "pragma",
"value": "no-cache"
},
{
"name": "server",
"value": "cloudflare"
},
{
"name": "etag",
"value": "W/\"d20-ZHlyCzvRVweI5qleuamBhoeSO1g\""
},
{
"name": "expect-ct",
"value": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
},
{
"name": "vary",
"value": "Origin, Accept-Encoding"
},
{
"name": "content-type",
"value": "application/json; charset=utf-8"
},
{
"name": "access-control-allow-origin",
"value": "http://localhost:3000"
},
{
"name": "cache-control",
"value": "max-age=14400"
},
{
"name": "access-control-allow-credentials",
"value": "true"
},
{
"name": "set-cookie",
"value": "__cfduid=d42dac9bc17ea4fe874662c606ae95df71580368148; expires=Sat, 29-Feb-20 07:09:08 GMT; path=/; domain=.typicode.com; HttpOnly; SameSite=Lax"
},
{
"name": "cf-ray",
"value": "55d19e5f180293b8-SJC"
},
{
"name": "expires",
"value": "-1"
}
],
"headersSize": 760,
"httpVersion": "HTTP/1.1",
"redirectURL": "",
"status": 200,
"statusText": "OK"
},
"startedDateTime": "2020-01-30T07:08:20.026Z",
"time": 63,
"timings": {
"blocked": -1,
"connect": -1,
"dns": -1,
"receive": 0,
"send": 0,
"ssl": -1,
"wait": 63
}
},
{
"_id": "077d0227d1c3015cc550180e38a7a324",
"_order": 0,
"cache": {},
"request": {
"bodySize": 0,
"cookies": [],
"headers": [
{
"name": "accept",
"value": "application/json"
},
{
"name": "referer",
"value": "http://localhost:3000/"
},
{
"name": "origin",
"value": "http://localhost:3000"
},
{
"name": "user-agent",
"value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3582.0 Safari/537.36"
}
],
"headersSize": 322,
"httpVersion": "HTTP/1.1",
"method": "GET",
"queryString": [
{
"name": "_end",
"value": "10"
},
{
"name": "_order",
"value": "ASC"
},
{
"name": "_sort",
"value": "title"
},
{
"name": "_start",
"value": "0"
}
],
"url": "https://jsonplaceholder.typicode.com/todos?_end=10&_order=ASC&_sort=title&_start=0"
},
"response": {
"bodySize": 1238,
"content": {
"mimeType": "application/json; charset=utf-8",
"size": 1238,
"text": "[\n {\n \"userId\": 6,\n \"id\": 108,\n \"title\": \"a eos eaque nihil et exercitationem incidunt delectus\",\n \"completed\": true\n },\n {\n \"userId\": 1,\n \"id\": 15,\n \"title\": \"ab voluptatum amet voluptas\",\n \"completed\": true\n },\n {\n \"userId\": 8,\n \"id\": 151,\n \"title\": \"accusamus adipisci dicta qui quo ea explicabo sed vero\",\n \"completed\": true\n },\n {\n \"userId\": 1,\n \"id\": 16,\n \"title\": \"accusamus eos facilis sint et aut voluptatem\",\n \"completed\": true\n },\n {\n \"userId\": 10,\n \"id\": 190,\n \"title\": \"accusamus sint iusto et voluptatem exercitationem\",\n \"completed\": true\n },\n {\n \"userId\": 6,\n \"id\": 106,\n \"title\": \"ad illo quis voluptatem temporibus\",\n \"completed\": true\n },\n {\n \"userId\": 2,\n \"id\": 24,\n \"title\": \"adipisci non ad dicta qui amet quaerat doloribus ea\",\n \"completed\": false\n },\n {\n \"userId\": 2,\n \"id\": 26,\n \"title\": \"aliquam aut quasi\",\n \"completed\": true\n },\n {\n \"userId\": 3,\n \"id\": 41,\n \"title\": \"aliquid amet impedit consequatur aspernatur placeat eaque fugiat suscipit\",\n \"completed\": false\n },\n {\n \"userId\": 8,\n \"id\": 149,\n \"title\": \"animi voluptas quod perferendis est\",\n \"completed\": false\n }\n]"
},
"cookies": [
{
"domain": ".typicode.com",
"expires": "2020-02-29T07:09:09.000Z",
"httpOnly": true,
"name": "__cfduid",
"path": "/",
"sameSite": "Lax",
"value": "db5bbdd08302e4f111266efd1f3fd3dd51580368149"
}
],
"headers": [
{
"name": "date",
"value": "Thu, 30 Jan 2020 07:09:09 GMT"
},
{
"name": "via",
"value": "1.1 vegur"
},
{
"name": "x-content-type-options",
"value": "nosniff"
},
{
"name": "cf-cache-status",
"value": "HIT"
},
{
"name": "age",
"value": "3769"
},
{
"name": "x-powered-by",
"value": "Express"
},
{
"name": "status",
"value": "200"
},
{
"name": "content-encoding",
"value": "br"
},
{
"name": "x-total-count",
"value": "200"
},
{
"name": "pragma",
"value": "no-cache"
},
{
"name": "server",
"value": "cloudflare"
},
{
"name": "etag",
"value": "W/\"4d6-FQWFhszsnTQKj5DCOASvDSlF2No\""
},
{
"name": "expect-ct",
"value": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
},
{
"name": "vary",
"value": "Origin, Accept-Encoding"
},
{
"name": "content-type",
"value": "application/json; charset=utf-8"
},
{
"name": "access-control-allow-origin",
"value": "http://localhost:3000"
},
{
"name": "access-control-expose-headers",
"value": "X-Total-Count"
},
{
"name": "cache-control",
"value": "max-age=14400"
},
{
"name": "access-control-allow-credentials",
"value": "true"
},
{
"name": "set-cookie",
"value": "__cfduid=db5bbdd08302e4f111266efd1f3fd3dd51580368149; expires=Sat, 29-Feb-20 07:09:09 GMT; path=/; domain=.typicode.com; HttpOnly; SameSite=Lax"
},
{
"name": "cf-ray",
"value": "55d19e644a2e93b8-SJC"
},
{
"name": "expires",
"value": "-1"
}
],
"headersSize": 826,
"httpVersion": "HTTP/1.1",
"redirectURL": "",
"status": 200,
"statusText": "OK"
},
"startedDateTime": "2020-01-30T07:08:20.861Z",
"time": 367,
"timings": {
"blocked": -1,
"connect": -1,
"dns": -1,
"receive": 0,
"send": 0,
"ssl": -1,
"wait": 367
}
},
{
"_id": "d38053106b03f35c571f5664ed50ad06",
"_order": 0,
"cache": {},
"request": {
"bodySize": 0,
"cookies": [],
"headers": [
{
"name": "accept",
"value": "application/json"
},
{
"name": "referer",
"value": "http://localhost:3000/"
},
{
"name": "origin",
"value": "http://localhost:3000"
},
{
"name": "user-agent",
"value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3582.0 Safari/537.36"
}
],
"headersSize": 321,
"httpVersion": "HTTP/1.1",
"method": "GET",
"queryString": [
{
"name": "_end",
"value": "10"
},
{
"name": "_order",
"value": "ASC"
},
{
"name": "_sort",
"value": "name"
},
{
"name": "_start",
"value": "0"
}
],
"url": "https://jsonplaceholder.typicode.com/users?_end=10&_order=ASC&_sort=name&_start=0"
},
"response": {
"bodySize": 5645,
"content": {
"mimeType": "application/json; charset=utf-8",
"size": 5645,
"text": "[\n {\n \"id\": 5,\n \"name\": \"Chelsey Dietrich\",\n \"username\": \"Kamren\",\n \"email\": \"Lucio_Hettinger@annie.ca\",\n \"address\": {\n \"street\": \"Skiles Walks\",\n \"suite\": \"Suite 351\",\n \"city\": \"Roscoeview\",\n \"zipcode\": \"33263\",\n \"geo\": {\n \"lat\": \"-31.8129\",\n \"lng\": \"62.5342\"\n }\n },\n \"phone\": \"(254)954-1289\",\n \"website\": \"demarco.info\",\n \"company\": {\n \"name\": \"Keebler LLC\",\n \"catchPhrase\": \"User-centric fault-tolerant solution\",\n \"bs\": \"revolutionize end-to-end systems\"\n }\n },\n {\n \"id\": 10,\n \"name\": \"Clementina DuBuque\",\n \"username\": \"Moriah.Stanton\",\n \"email\": \"Rey.Padberg@karina.biz\",\n \"address\": {\n \"street\": \"Kattie Turnpike\",\n \"suite\": \"Suite 198\",\n \"city\": \"Lebsackbury\",\n \"zipcode\": \"31428-2261\",\n \"geo\": {\n \"lat\": \"-38.2386\",\n \"lng\": \"57.2232\"\n }\n },\n \"phone\": \"024-648-3804\",\n \"website\": \"ambrose.net\",\n \"company\": {\n \"name\": \"Hoeger LLC\",\n \"catchPhrase\": \"Centralized empowering task-force\",\n \"bs\": \"target end-to-end models\"\n }\n },\n {\n \"id\": 3,\n \"name\": \"Clementine Bauch\",\n \"username\": \"Samantha\",\n \"email\": \"Nathan@yesenia.net\",\n \"address\": {\n \"street\": \"Douglas Extension\",\n \"suite\": \"Suite 847\",\n \"city\": \"McKenziehaven\",\n \"zipcode\": \"59590-4157\",\n \"geo\": {\n \"lat\": \"-68.6102\",\n \"lng\": \"-47.0653\"\n }\n },\n \"phone\": \"1-463-123-4447\",\n \"website\": \"ramiro.info\",\n \"company\": {\n \"name\": \"Romaguera-Jacobson\",\n \"catchPhrase\": \"Face to face bifurcated interface\",\n \"bs\": \"e-enable strategic applications\"\n }\n },\n {\n \"id\": 2,\n \"name\": \"Ervin Howell\",\n \"username\": \"Antonette\",\n \"email\": \"Shanna@melissa.tv\",\n \"address\": {\n \"street\": \"Victor Plains\",\n \"suite\": \"Suite 879\",\n \"city\": \"Wisokyburgh\",\n \"zipcode\": \"90566-7771\",\n \"geo\": {\n \"lat\": \"-43.9509\",\n \"lng\": \"-34.4618\"\n }\n },\n \"phone\": \"010-692-6593 x09125\",\n \"website\": \"anastasia.net\",\n \"company\": {\n \"name\": \"Deckow-Crist\",\n \"catchPhrase\": \"Proactive didactic contingency\",\n \"bs\": \"synergize scalable supply-chains\"\n }\n },\n {\n \"id\": 9,\n \"name\": \"Glenna Reichert\",\n \"username\": \"Delphine\",\n \"email\": \"Chaim_McDermott@dana.io\",\n \"address\": {\n \"street\": \"Dayna Park\",\n \"suite\": \"Suite 449\",\n \"city\": \"Bartholomebury\",\n \"zipcode\": \"76495-3109\",\n \"geo\": {\n \"lat\": \"24.6463\",\n \"lng\": \"-168.8889\"\n }\n },\n \"phone\": \"(775)976-6794 x41206\",\n \"website\": \"conrad.com\",\n \"company\": {\n \"name\": \"Yost and Sons\",\n \"catchPhrase\": \"Switchable contextually-based project\",\n \"bs\": \"aggregate real-time technologies\"\n }\n },\n {\n \"id\": 7,\n \"name\": \"Kurtis Weissnat\",\n \"username\": \"Elwyn.Skiles\",\n \"email\": \"Telly.Hoeger@billy.biz\",\n \"address\": {\n \"street\": \"Rex Trail\",\n \"suite\": \"Suite 280\",\n \"city\": \"Howemouth\",\n \"zipcode\": \"58804-1099\",\n \"geo\": {\n \"lat\": \"24.8918\",\n \"lng\": \"21.8984\"\n }\n },\n \"phone\": \"210.067.6132\",\n \"website\": \"elvis.io\",\n \"company\": {\n \"name\": \"Johns Group\",\n \"catchPhrase\": \"Configurable multimedia task-force\",\n \"bs\": \"generate enterprise e-tailers\"\n }\n },\n {\n \"id\": 1,\n \"name\": \"Leanne Graham\",\n \"username\": \"Bret\",\n \"email\": \"Sincere@april.biz\",\n \"address\": {\n \"street\": \"Kulas Light\",\n \"suite\": \"Apt. 556\",\n \"city\": \"Gwenborough\",\n \"zipcode\": \"92998-3874\",\n \"geo\": {\n \"lat\": \"-37.3159\",\n \"lng\": \"81.1496\"\n }\n },\n \"phone\": \"1-770-736-8031 x56442\",\n \"website\": \"hildegard.org\",\n \"company\": {\n \"name\": \"Romaguera-Crona\",\n \"catchPhrase\": \"Multi-layered client-server neural-net\",\n \"bs\": \"harness real-time e-markets\"\n }\n },\n {\n \"id\": 6,\n \"name\": \"Mrs. Dennis Schulist\",\n \"username\": \"Leopoldo_Corkery\",\n \"email\": \"Karley_Dach@jasper.info\",\n \"address\": {\n \"street\": \"Norberto Crossing\",\n \"suite\": \"Apt. 950\",\n \"city\": \"South Christy\",\n \"zipcode\": \"23505-1337\",\n \"geo\": {\n \"lat\": \"-71.4197\",\n \"lng\": \"71.7478\"\n }\n },\n \"phone\": \"1-477-935-8478 x6430\",\n \"website\": \"ola.org\",\n \"company\": {\n \"name\": \"Considine-Lockman\",\n \"catchPhrase\": \"Synchronised bottom-line interface\",\n \"bs\": \"e-enable innovative applications\"\n }\n },\n {\n \"id\": 8,\n \"name\": \"Nicholas Runolfsdottir V\",\n \"username\": \"Maxime_Nienow\",\n \"email\": \"Sherwood@rosamond.me\",\n \"address\": {\n \"street\": \"Ellsworth Summit\",\n \"suite\": \"Suite 729\",\n \"city\": \"Aliyaview\",\n \"zipcode\": \"45169\",\n \"geo\": {\n \"lat\": \"-14.3990\",\n \"lng\": \"-120.7677\"\n }\n },\n \"phone\": \"586.493.6943 x140\",\n \"website\": \"jacynthe.com\",\n \"company\": {\n \"name\": \"Abernathy Group\",\n \"catchPhrase\": \"Implemented secondary concept\",\n \"bs\": \"e-enable extensible e-tailers\"\n }\n },\n {\n \"id\": 4,\n \"name\": \"Patricia Lebsack\",\n \"username\": \"Karianne\",\n \"email\": \"Julianne.OConner@kory.org\",\n \"address\": {\n \"street\": \"Hoeger Mall\",\n \"suite\": \"Apt. 692\",\n \"city\": \"South Elvis\",\n \"zipcode\": \"53919-4257\",\n \"geo\": {\n \"lat\": \"29.4572\",\n \"lng\": \"-164.2990\"\n }\n },\n \"phone\": \"493-170-9623 x156\",\n \"website\": \"kale.biz\",\n \"company\": {\n \"name\": \"Robel-Corkery\",\n \"catchPhrase\": \"Multi-tiered zero tolerance productivity\",\n \"bs\": \"transition cutting-edge web services\"\n }\n }\n]"
},
"cookies": [
{
"domain": ".typicode.com",
"expires": "2020-02-29T07:09:09.000Z",
"httpOnly": true,
"name": "__cfduid",
"path": "/",
"sameSite": "Lax",
"value": "db5bbdd08302e4f111266efd1f3fd3dd51580368149"
}
],
"headers": [
{
"name": "date",
"value": "Thu, 30 Jan 2020 07:09:09 GMT"
},
{
"name": "via",
"value": "1.1 vegur"
},
{
"name": "x-content-type-options",
"value": "nosniff"
},
{
"name": "cf-cache-status",
"value": "HIT"
},
{
"name": "age",
"value": "3769"
},
{
"name": "x-powered-by",
"value": "Express"
},
{
"name": "status",
"value": "200"
},
{
"name": "content-encoding",
"value": "br"
},
{
"name": "x-total-count",
"value": "10"
},
{
"name": "pragma",
"value": "no-cache"
},
{
"name": "server",
"value": "cloudflare"
},
{
"name": "etag",
"value": "W/\"160d-effcizVuOlMD7nsyxg4tYeQ+hLc\""
},
{
"name": "expect-ct",
"value": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
},
{
"name": "vary",
"value": "Origin, Accept-Encoding"
},
{
"name": "content-type",
"value": "application/json; charset=utf-8"
},
{
"name": "access-control-allow-origin",
"value": "http://localhost:3000"
},
{
"name": "access-control-expose-headers",
"value": "X-Total-Count"
},
{
"name": "cache-control",
"value": "max-age=14400"
},
{
"name": "access-control-allow-credentials",
"value": "true"
},
{
"name": "set-cookie",
"value": "__cfduid=db5bbdd08302e4f111266efd1f3fd3dd51580368149; expires=Sat, 29-Feb-20 07:09:09 GMT; path=/; domain=.typicode.com; HttpOnly; SameSite=Lax"
},
{
"name": "cf-ray",
"value": "55d19e667b0b93b8-SJC"
},
{
"name": "expires",
"value": "-1"
}
],
"headersSize": 826,
"httpVersion": "HTTP/1.1",
"redirectURL": "",
"status": 200,
"statusText": "OK"
},
"startedDateTime": "2020-01-30T07:08:21.162Z",
"time": 139,
"timings": {
"blocked": -1,
"connect": -1,
"dns": -1,
"receive": 0,
"send": 0,
"ssl": -1,
"wait": 139
}
},
{
"_id": "d7b612efe837babe49ce9ba652d3b68b",
"_order": 0,
"cache": {},
"request": {
"bodySize": 0,
"cookies": [],
"headers": [
{
"name": "accept",
"value": "application/json"
},
{
"name": "referer",
"value": "http://localhost:3000/"
},
{
"name": "origin",
"value": "http://localhost:3000"
},
{
"name": "user-agent",
"value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/72.0.3582.0 Safari/537.36"
}
],
"headersSize": 321,
"httpVersion": "HTTP/1.1",
"method": "GET",
"queryString": [
{
"_fromType": "array",
"name": "id",
"value": "6"
},
{
"_fromType": "array",
"name": "id",
"value": "1"
},
{
"_fromType": "array",
"name": "id",
"value": "8"
},
{
"_fromType": "array",
"name": "id",
"value": "10"
},
{
"_fromType": "array",
"name": "id",
"value": "2"
},
{
"_fromType": "array",
"name": "id",
"value": "3"
}
],
"url": "https://jsonplaceholder.typicode.com/users?id=6&id=1&id=8&id=10&id=2&id=3"
},
"response": {
"bodySize": 3398,
"content": {
"mimeType": "application/json; charset=utf-8",
"size": 3398,
"text": "[\n {\n \"id\": 1,\n \"name\": \"Leanne Graham\",\n \"username\": \"Bret\",\n \"email\": \"Sincere@april.biz\",\n \"address\": {\n \"street\": \"Kulas Light\",\n \"suite\": \"Apt. 556\",\n \"city\": \"Gwenborough\",\n \"zipcode\": \"92998-3874\",\n \"geo\": {\n \"lat\": \"-37.3159\",\n \"lng\": \"81.1496\"\n }\n },\n \"phone\": \"1-770-736-8031 x56442\",\n \"website\": \"hildegard.org\",\n \"company\": {\n \"name\": \"Romaguera-Crona\",\n \"catchPhrase\": \"Multi-layered client-server neural-net\",\n \"bs\": \"harness real-time e-markets\"\n }\n },\n {\n \"id\": 2,\n \"name\": \"Ervin Howell\",\n \"username\": \"Antonette\",\n \"email\": \"Shanna@melissa.tv\",\n \"address\": {\n \"street\": \"Victor Plains\",\n \"suite\": \"Suite 879\",\n \"city\": \"Wisokyburgh\",\n \"zipcode\": \"90566-7771\",\n \"geo\": {\n \"lat\": \"-43.9509\",\n \"lng\": \"-34.4618\"\n }\n },\n \"phone\": \"010-692-6593 x09125\",\n \"website\": \"anastasia.net\",\n \"company\": {\n \"name\": \"Deckow-Crist\",\n \"catchPhrase\": \"Proactive didactic contingency\",\n \"bs\": \"synergize scalable supply-chains\"\n }\n },\n {\n \"id\": 3,\n \"name\": \"Clementine Bauch\",\n \"username\": \"Samantha\",\n \"email\": \"Nathan@yesenia.net\",\n \"address\": {\n \"street\": \"Douglas Extension\",\n \"suite\": \"Suite 847\",\n \"city\": \"McKenziehaven\",\n \"zipcode\": \"59590-4157\",\n \"geo\": {\n \"lat\": \"-68.6102\",\n \"lng\": \"-47.0653\"\n }\n },\n \"phone\": \"1-463-123-4447\",\n \"website\": \"ramiro.info\",\n \"company\": {\n \"name\": \"Romaguera-Jacobson\",\n \"catchPhrase\": \"Face to face bifurcated interface\",\n \"bs\": \"e-enable strategic applications\"\n }\n },\n {\n \"id\": 6,\n \"name\": \"Mrs. Dennis Schulist\",\n \"username\": \"Leopoldo_Corkery\",\n \"email\": \"Karley_Dach@jasper.info\",\n \"address\": {\n \"street\": \"Norberto Crossing\",\n \"suite\": \"Apt. 950\",\n \"city\": \"South Christy\",\n \"zipcode\": \"23505-1337\",\n \"geo\": {\n \"lat\": \"-71.4197\",\n \"lng\": \"71.7478\"\n }\n },\n \"phone\": \"1-477-935-8478 x6430\",\n \"website\": \"ola.org\",\n \"company\": {\n \"name\": \"Considine-Lockman\",\n \"catchPhrase\": \"Synchronised bottom-line interface\",\n \"bs\": \"e-enable innovative applications\"\n }\n },\n {\n \"id\": 8,\n \"name\": \"Nicholas Runolfsdottir V\",\n \"username\": \"Maxime_Nienow\",\n \"email\": \"Sherwood@rosamond.me\",\n \"address\": {\n \"street\": \"Ellsworth Summit\",\n \"suite\": \"Suite 729\",\n \"city\": \"Aliyaview\",\n \"zipcode\": \"45169\",\n \"geo\": {\n \"lat\": \"-14.3990\",\n \"lng\": \"-120.7677\"\n }\n },\n \"phone\": \"586.493.6943 x140\",\n \"website\": \"jacynthe.com\",\n \"company\": {\n \"name\": \"Abernathy Group\",\n \"catchPhrase\": \"Implemented secondary concept\",\n \"bs\": \"e-enable extensible e-tailers\"\n }\n },\n {\n \"id\": 10,\n \"name\": \"Clementina DuBuque\",\n \"username\": \"Moriah.Stanton\",\n \"email\": \"Rey.Padberg@karina.biz\",\n \"address\": {\n \"street\": \"Kattie Turnpike\",\n \"suite\": \"Suite 198\",\n \"city\": \"Lebsackbury\",\n \"zipcode\": \"31428-2261\",\n \"geo\": {\n \"lat\": \"-38.2386\",\n \"lng\": \"57.2232\"\n }\n },\n \"phone\": \"024-648-3804\",\n \"website\": \"ambrose.net\",\n \"company\": {\n \"name\": \"Hoeger LLC\",\n \"catchPhrase\": \"Centralized empowering task-force\",\n \"bs\": \"target end-to-end models\"\n }\n }\n]"
},
"cookies": [
{
"domain": ".typicode.com",
"expires": "2020-02-29T07:09:29.000Z",
"httpOnly": true,
"name": "__cfduid",
"path": "/",
"sameSite": "Lax",
"value": "dc75f0cde25965ab36ea21361cdb3cf8e1580368169"
}
],
"headers": [
{
"name": "date",
"value": "Thu, 30 Jan 2020 07:09:29 GMT"
},
{
"name": "via",
"value": "1.1 vegur"
},
{
"name": "x-content-type-options",
"value": "nosniff"
},
{
"name": "cf-cache-status",
"value": "HIT"
},
{
"name": "age",
"value": "147"
},
{
"name": "x-powered-by",
"value": "Express"
},
{
"name": "status",
"value": "200"
},
{
"name": "content-encoding",
"value": "br"
},
{
"name": "pragma",
"value": "no-cache"
},
{
"name": "server",
"value": "cloudflare"
},
{
"name": "etag",
"value": "W/\"d46-IDCKT5ms1IwADCSNWe91qzz7vsQ\""
},
{
"name": "expect-ct",
"value": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
},
{
"name": "vary",
"value": "Origin, Accept-Encoding"
},
{
"name": "content-type",
"value": "application/json; charset=utf-8"
},
{
"name": "access-control-allow-origin",
"value": "http://localhost:3000"
},
{
"name": "cache-control",
"value": "max-age=14400"
},
{
"name": "access-control-allow-credentials",
"value": "true"
},
{
"name": "set-cookie",
"value": "__cfduid=dc75f0cde25965ab36ea21361cdb3cf8e1580368169; expires=Sat, 29-Feb-20 07:09:29 GMT; path=/; domain=.typicode.com; HttpOnly; SameSite=Lax"
},
{
"name": "cf-ray",
"value": "55d19ee43862937c-SJC"
},
{
"name": "expires",
"value": "-1"
}
],
"headersSize": 759,
"httpVersion": "HTTP/1.1",
"redirectURL": "",
"status": 200,
"statusText": "OK"
},
"startedDateTime": "2020-01-30T07:08:40.845Z",
"time": 629,
"timings": {
"blocked": -1,
"connect": -1,
"dns": -1,
"receive": 0,
"send": 0,
"ssl": -1,
"wait": 629
}
}
],
"pages": [],
"version": "1.2"
}
}
================================================
FILE: examples/jest-puppeteer/__tests__/dummy-app.test.js
================================================
const path = require('path');
const { Polly } = require('@pollyjs/core');
const { setupPolly } = require('setup-polly-jest');
const PuppeteerAdapter = require('@pollyjs/adapter-puppeteer');
const FSPersister = require('@pollyjs/persister-fs');
Polly.register(PuppeteerAdapter);
Polly.register(FSPersister);
describe('jest-puppeteer', () => {
// NOTE: `context.polly` is not accessible until the jasmine/jest hook `before`
// is called. This means it's not accessible in the same tick here. Worth mentioning
// since it trolled me while debugging.
const context = setupPolly({
adapters: ['puppeteer'],
// NOTE: `page` is set by jest.config.js preset "jest-puppeteer"
adapterOptions: { puppeteer: { page } },
persister: 'fs',
persisterOptions: {
fs: {
recordingsDir: path.resolve(__dirname, '../__recordings__')
}
},
matchRequestsBy: {
headers: {
exclude: ['user-agent']
}
}
});
beforeEach(async () => {
jest.setTimeout(60000);
await page.setRequestInterception(true);
const { server } = context.polly;
server.host('http://localhost:3000', () => {
server.get('/sockjs-node/*').intercept((_, res) => res.sendStatus(200));
});
await page.goto('http://localhost:3000', { waitUntil: 'networkidle0' });
});
it('should be able to navigate to all routes', async () => {
const header = await page.$('header');
await expect(page).toMatchElement('tbody > tr', { timeout: 5000 });
await expect(header).toMatch('Posts');
await expect(page).toClick('a', { text: 'Todos' });
await expect(page).toMatchElement('tbody > tr', { timeout: 5000 });
await expect(header).toMatch('Todos');
await expect(page).toClick('a', { text: 'Users' });
await expect(page).toMatchElement('tbody > tr', { timeout: 5000 });
await expect(header).toMatch('Users');
// Wait for all requests to resolve, this can also be replaced with
await context.polly.flush();
});
});
================================================
FILE: examples/jest-puppeteer/jest-puppeteer.config.js
================================================
module.exports = {
launch: {
headless: true
},
server: {
command: '(cd ../dummy-app && yarn start:ci)',
port: 3000,
launchTimeout: 60000
}
};
================================================
FILE: examples/jest-puppeteer/jest.config.js
================================================
module.exports = {
preset: 'jest-puppeteer'
};
================================================
FILE: examples/jest-puppeteer/package.json
================================================
{
"name": "@pollyjs/jest-puppeteer-example",
"version": "0.1.0",
"private": true,
"license": "Apache-2.0",
"scripts": {
"postinstall": "(cd ../dummy-app && yarn install)",
"test": "jest"
},
"devDependencies": {
"@pollyjs/adapter-puppeteer": "^4.0.2",
"@pollyjs/core": "^4.0.2",
"@pollyjs/persister-fs": "^4.0.2",
"jest": "^24.0.0",
"jest-puppeteer": "^4.0.0",
"puppeteer": "1.10.0",
"setup-polly-jest": "^0.6.0"
}
}
================================================
FILE: examples/node-fetch/package.json
================================================
{
"name": "@pollyjs/node-fetch-example",
"version": "0.1.0",
"private": true,
"license": "Apache-2.0",
"scripts": {
"test": "mocha './tests/*.test.js'"
},
"devDependencies": {
"@pollyjs/adapter-node-http": "*",
"@pollyjs/core": "*",
"@pollyjs/persister-fs": "*",
"chai": "*",
"mocha": "*",
"node-fetch": "*"
}
}
================================================
FILE: examples/node-fetch/recordings/node-fetch_2851505768/should-work_3457346403/recording.har
================================================
{
"log": {
"_recordingName": "node-fetch/should work",
"creator": {
"comment": "persister:fs",
"name": "Polly.JS",
"version": "1.2.0"
},
"entries": [
{
"_id": "41b7d6ef74440e3b785f1634743f9139",
"_order": 0,
"cache": {},
"request": {
"bodySize": 0,
"cookies": [],
"headers": [
{
"name": "accept",
"value": [
"*/*"
]
},
{
"name": "user-agent",
"value": [
"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"
]
},
{
"name": "accept-encoding",
"value": [
"gzip,deflate"
]
},
{
"name": "connection",
"value": [
"close"
]
},
{
"name": "host",
"value": "jsonplaceholder.typicode.com"
}
],
"headersSize": 228,
"httpVersion": "HTTP/1.1",
"method": "GET",
"postData": {
"mimeType": "text/plain"
},
"queryString": [],
"url": "https://jsonplaceholder.typicode.com/posts/1"
},
"response": {
"bodySize": 408,
"content": {
"mimeType": "application/json; charset=utf-8",
"size": 408,
"text": "[\"1f8b0800000000000003558f4b6a04410c43f7730a51eb6cb29d1be40ebd715c0a63e8fa8ccb1e2684dc3d744308012324901fe8eb02945cf4b75aae787d39a2fdd9b0d859ae282b7b4032f0214a279c93fb2e81e9e361953d3054852a61e0533923dd3066d838cace1b7ba55b9413fc3eeae7c1bda7091858b9d4a6c5d67f1d9c9a4b7a1542475fbc67f648079f93d5e27cd36c5bff87471b3b57981019c7dd53166284b4adf7b1c2b3c17928d739890de73a67031fecc680b8de2ca831cae5fb0715c693e824010000\"]"
},
"cookies": [
{
"domain": ".typicode.com",
"expires": "2019-12-06T20:53:26.000Z",
"httpOnly": true,
"name": "__cfduid",
"path": "/",
"value": "d9a2a8da0fc8bad42e47cee6b6782bb811544129606"
}
],
"headers": [
{
"name": "date",
"value": "Thu, 06 Dec 2018 20:53:26 GMT"
},
{
"name": "content-type",
"value": "application/json; charset=utf-8"
},
{
"name": "transfer-encoding",
"value": "chunked"
},
{
"name": "connection",
"value": "close"
},
{
"name": "set-cookie",
"value": [
"__cfduid=d9a2a8da0fc8bad42e47cee6b6782bb811544129606; expires=Fri, 06-Dec-19 20:53:26 GMT; path=/; domain=.typicode.com; HttpOnly"
]
},
{
"name": "x-powered-by",
"value": "Express"
},
{
"name": "vary",
"value": "Origin, Accept-Encoding"
},
{
"name": "access-control-allow-credentials",
"value": "true"
},
{
"name": "cache-control",
"value": "public, max-age=14400"
},
{
"name": "pragma",
"value": "no-cache"
},
{
"name": "expires",
"value": "Fri, 07 Dec 2018 00:53:26 GMT"
},
{
"name": "x-content-type-options",
"value": "nosniff"
},
{
"name": "etag",
"value": "W/\"124-yiKdLzqO5gfBrJFrcdJ8Yq0LGnU\""
},
{
"name": "via",
"value": "1.1 vegur"
},
{
"name": "cf-cache-status",
"value": "HIT"
},
{
"name": "expect-ct",
"value": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
},
{
"name": "server",
"value": "cloudflare"
},
{
"name": "cf-ray",
"value": "4851a4585a759354-SJC"
},
{
"name": "content-encoding",
"value": "gzip"
}
],
"headersSize": 754,
"httpVersion": "HTTP/1.1",
"redirectURL": "",
"status": 200,
"statusText": "OK"
},
"startedDateTime": "2018-12-06T20:53:21.087Z",
"time": 130,
"timings": {
"blocked": -1,
"connect": -1,
"dns": -1,
"receive": 0,
"send": 0,
"ssl": -1,
"wait": 130
}
}
],
"pages": [],
"version": "1.2"
}
}
================================================
FILE: examples/node-fetch/tests/node-fetch.test.js
================================================
const path = require('path');
const NodeHttpAdapter = require('@pollyjs/adapter-node-http');
const FSPersister = require('@pollyjs/persister-fs');
const fetch = require('node-fetch');
const { Polly, setupMocha: setupPolly } = require('@pollyjs/core');
const { expect } = require('chai');
Polly.register(NodeHttpAdapter);
Polly.register(FSPersister);
describe('node-fetch', function () {
setupPolly({
adapters: ['node-http'],
persister: 'fs',
persisterOptions: {
fs: {
recordingsDir: path.resolve(__dirname, '../recordings')
}
}
});
it('should work', async function () {
const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const post = await res.json();
expect(res.status).to.equal(200);
expect(post.id).to.equal(1);
});
});
================================================
FILE: examples/puppeteer/index.js
================================================
const path = require('path');
const puppeteer = require('puppeteer');
const { Polly } = require('@pollyjs/core');
const PuppeteerAdapter = require('@pollyjs/adapter-puppeteer');
const FSPersister = require('@pollyjs/persister-fs');
Polly.register(PuppeteerAdapter);
Polly.register(FSPersister);
(async () => {
const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
await page.setRequestInterception(true);
const polly = new Polly('puppeteer', {
adapters: ['puppeteer'],
adapterOptions: { puppeteer: { page } },
persister: 'fs',
persisterOptions: {
fs: {
recordingsDir: path.join(__dirname, 'recordings')
}
}
});
const { server } = polly;
server.host('http://localhost:3000', () => {
server.get('/favicon.ico').passthrough();
server.get('/sockjs-node/*').intercept((_, res) => res.sendStatus(200));
});
await page.goto('http://localhost:3000', { waitUntil: 'networkidle0' });
await polly.flush();
await polly.stop();
await browser.close();
})();
================================================
FILE: examples/puppeteer/package.json
================================================
{
"name": "@pollyjs/puppeteer-example",
"version": "0.1.0",
"private": true,
"license": "Apache-2.0",
"scripts": {
"postinstall": "(cd ../dummy-app && yarn install)",
"start": "start-server-and-test start:server http://localhost:3000 start:puppeteer",
"start:server": "(cd ../dummy-app && yarn start:ci)",
"start:puppeteer": "node index.js"
},
"devDependencies": {
"@pollyjs/adapter-puppeteer": "*",
"@pollyjs/core": "*",
"@pollyjs/persister-fs": "*",
"puppeteer": "*",
"start-server-and-test": "*"
}
}
================================================
FILE: examples/puppeteer/recordings/puppeteer_2155046665/recording.har
================================================
{
"log": {
"_recordingName": "puppeteer",
"creator": {
"comment": "persister:fs",
"name": "Polly.JS",
"version": "1.2.0"
},
"entries": [
{
"_id": "6d6504c5ff77bd0d42862429f4c1312c",
"_order": 0,
"cache": {},
"request": {
"bodySize": 0,
"cookies": [],
"headers": [
{
"name": "accept",
"value": "application/json"
},
{
"name": "referer",
"value": "http://localhost:3000/"
},
{
"name": "origin",
"value": "http://localhost:3000"
},
{
"name": "user-agent",
"value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3542.0 Safari/537.36"
},
{
"name": "content-type",
"value": "application/json"
}
],
"headersSize": 354,
"httpVersion": "HTTP/1.1",
"method": "GET",
"postData": {
"mimeType": "application/json"
},
"queryString": [
{
"name": "_end",
"value": "10"
},
{
"name": "_order",
"value": "ASC"
},
{
"name": "_sort",
"value": "title"
},
{
"name": "_start",
"value": "0"
}
],
"url": "https://jsonplaceholder.typicode.com/posts?_end=10&_order=ASC&_sort=title&_start=0"
},
"response": {
"bodySize": 2594,
"content": {
"mimeType": "application/json; charset=utf-8",
"size": 2594,
"text": "[\n {\n \"userId\": 3,\n \"id\": 30,\n \"title\": \"a quo magni similique perferendis\",\n \"body\": \"alias dolor cumque\\nimpedit blanditiis non eveniet odio maxime\\nblanditiis amet eius quis tempora quia autem rem\\na provident perspiciatis quia\"\n },\n {\n \"userId\": 9,\n \"id\": 90,\n \"title\": \"ad iusto omnis odit dolor voluptatibus\",\n \"body\": \"minus omnis soluta quia\\nqui sed adipisci voluptates illum ipsam voluptatem\\neligendi officia ut in\\neos soluta similique molestias praesentium blanditiis\"\n },\n {\n \"userId\": 2,\n \"id\": 19,\n \"title\": \"adipisci placeat illum aut reiciendis qui\",\n \"body\": \"illum quis cupiditate provident sit magnam\\nea sed aut omnis\\nveniam maiores ullam consequatur atque\\nadipisci quo iste expedita sit quos voluptas\"\n },\n {\n \"userId\": 7,\n \"id\": 67,\n \"title\": \"aliquid eos sed fuga est maxime repellendus\",\n \"body\": \"reprehenderit id nostrum\\nvoluptas doloremque pariatur sint et accusantium quia quod aspernatur\\net fugiat amet\\nnon sapiente et consequatur necessitatibus molestiae\"\n },\n {\n \"userId\": 3,\n \"id\": 21,\n \"title\": \"asperiores ea ipsam voluptatibus modi minima quia sint\",\n \"body\": \"repellat aliquid praesentium dolorem quo\\nsed totam minus non itaque\\nnihil labore molestiae sunt dolor eveniet hic recusandae veniam\\ntempora et tenetur expedita sunt\"\n },\n {\n \"userId\": 10,\n \"id\": 100,\n \"title\": \"at nam consequatur ea labore ea harum\",\n \"body\": \"cupiditate quo est a modi nesciunt soluta\\nipsa voluptas error itaque dicta in\\nautem qui minus magnam et distinctio eum\\naccusamus ratione error aut\"\n },\n {\n \"userId\": 10,\n \"id\": 91,\n \"title\": \"aut amet sed\",\n \"body\": \"libero voluptate eveniet aperiam sed\\nsunt placeat suscipit molestias\\nsimilique fugit nam natus\\nexpedita consequatur consequatur dolores quia eos et placeat\"\n },\n {\n \"userId\": 5,\n \"id\": 46,\n \"title\": \"aut quo modi neque nostrum ducimus\",\n \"body\": \"voluptatem quisquam iste\\nvoluptatibus natus officiis facilis dolorem\\nquis quas ipsam\\nvel et voluptatum in aliquid\"\n },\n {\n \"userId\": 3,\n \"id\": 24,\n \"title\": \"autem hic labore sunt dolores incidunt\",\n \"body\": \"enim et ex nulla\\nomnis voluptas quia qui\\nvoluptatem consequatur numquam aliquam sunt\\ntotam recusandae id dignissimos aut sed asperiores deserunt\"\n },\n {\n \"userId\": 7,\n \"id\": 62,\n \"title\": \"beatae enim quia vel\",\n \"body\": \"enim aspernatur illo distinctio quae praesentium\\nbeatae alias amet delectus qui voluptate distinctio\\nodit sint accusantium autem omnis\\nquo molestiae omnis ea eveniet optio\"\n }\n]"
},
"cookies": [],
"headers": [
{
"name": "date",
"value": "Sun, 16 Sep 2018 23:53:12 GMT"
},
{
"name": "via",
"value": "1.1 vegur"
},
{
"name": "x-content-type-options",
"value": "nosniff"
},
{
"name": "cf-cache-status",
"value": "HIT"
},
{
"name": "x-powered-by",
"value": "Express"
},
{
"name": "status",
"value": "200"
},
{
"name": "content-encoding",
"value": "br"
},
{
"name": "x-total-count",
"value": "100"
},
{
"name": "pragma",
"value": "no-cache"
},
{
"name": "server",
"value": "cloudflare"
},
{
"name": "etag",
"value": "W/\"a22-FI+zdCzw2iL/TSmHe3WZs7jlNFI\""
},
{
"name": "expect-ct",
"value": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
},
{
"name": "vary",
"value": "Origin, Accept-Encoding"
},
{
"name": "content-type",
"value": "application/json; charset=utf-8"
},
{
"name": "access-control-allow-origin",
"value": "http://localhost:3000"
},
{
"name": "access-control-expose-headers",
"value": "X-Total-Count"
},
{
"name": "cache-control",
"value": "public, max-age=14400"
},
{
"name": "access-control-allow-credentials",
"value": "true"
},
{
"name": "cf-ray",
"value": "45b7404dfd0e6be6-SJC"
},
{
"name": "expires",
"value": "Mon, 17 Sep 2018 03:53:12 GMT"
}
],
"headersSize": 693,
"httpVersion": "HTTP/1.1",
"redirectURL": "",
"status": 200,
"statusText": "OK"
},
"startedDateTime": "2018-09-16T23:53:12.472Z",
"time": 191,
"timings": {
"blocked": -1,
"connect": -1,
"dns": -1,
"receive": 0,
"send": 0,
"ssl": -1,
"wait": 191
}
},
{
"_id": "74a9cff42a4c74f8db5d8ad814e9e9a1",
"_order": 0,
"cache": {},
"request": {
"bodySize": 0,
"cookies": [],
"headers": [
{
"name": "accept",
"value": "application/json"
},
{
"name": "referer",
"value": "http://localhost:3000/"
},
{
"name": "origin",
"value": "http://localhost:3000"
},
{
"name": "user-agent",
"value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3542.0 Safari/537.36"
},
{
"name": "content-type",
"value": "application/json"
}
],
"headersSize": 345,
"httpVersion": "HTTP/1.1",
"method": "GET",
"postData": {
"mimeType": "application/json"
},
"queryString": [
{
"name": "id_like",
"value": "3|9|2|7|10|5"
}
],
"url": "https://jsonplaceholder.typicode.com/users?id_like=3%7C9%7C2%7C7%7C10%7C5"
},
"response": {
"bodySize": 3360,
"content": {
"mimeType": "application/json; charset=utf-8",
"size": 3360,
"text": "[\n {\n \"id\": 2,\n \"name\": \"Ervin Howell\",\n \"username\": \"Antonette\",\n \"email\": \"Shanna@melissa.tv\",\n \"address\": {\n \"street\": \"Victor Plains\",\n \"suite\": \"Suite 879\",\n \"city\": \"Wisokyburgh\",\n \"zipcode\": \"90566-7771\",\n \"geo\": {\n \"lat\": \"-43.9509\",\n \"lng\": \"-34.4618\"\n }\n },\n \"phone\": \"010-692-6593 x09125\",\n \"website\": \"anastasia.net\",\n \"company\": {\n \"name\": \"Deckow-Crist\",\n \"catchPhrase\": \"Proactive didactic contingency\",\n \"bs\": \"synergize scalable supply-chains\"\n }\n },\n {\n \"id\": 3,\n \"name\": \"Clementine Bauch\",\n \"username\": \"Samantha\",\n \"email\": \"Nathan@yesenia.net\",\n \"address\": {\n \"street\": \"Douglas Extension\",\n \"suite\": \"Suite 847\",\n \"city\": \"McKenziehaven\",\n \"zipcode\": \"59590-4157\",\n \"geo\": {\n \"lat\": \"-68.6102\",\n \"lng\": \"-47.0653\"\n }\n },\n \"phone\": \"1-463-123-4447\",\n \"website\": \"ramiro.info\",\n \"company\": {\n \"name\": \"Romaguera-Jacobson\",\n \"catchPhrase\": \"Face to face bifurcated interface\",\n \"bs\": \"e-enable strategic applications\"\n }\n },\n {\n \"id\": 5,\n \"name\": \"Chelsey Dietrich\",\n \"username\": \"Kamren\",\n \"email\": \"Lucio_Hettinger@annie.ca\",\n \"address\": {\n \"street\": \"Skiles Walks\",\n \"suite\": \"Suite 351\",\n \"city\": \"Roscoeview\",\n \"zipcode\": \"33263\",\n \"geo\": {\n \"lat\": \"-31.8129\",\n \"lng\": \"62.5342\"\n }\n },\n \"phone\": \"(254)954-1289\",\n \"website\": \"demarco.info\",\n \"company\": {\n \"name\": \"Keebler LLC\",\n \"catchPhrase\": \"User-centric fault-tolerant solution\",\n \"bs\": \"revolutionize end-to-end systems\"\n }\n },\n {\n \"id\": 7,\n \"name\": \"Kurtis Weissnat\",\n \"username\": \"Elwyn.Skiles\",\n \"email\": \"Telly.Hoeger@billy.biz\",\n \"address\": {\n \"street\": \"Rex Trail\",\n \"suite\": \"Suite 280\",\n \"city\": \"Howemouth\",\n \"zipcode\": \"58804-1099\",\n \"geo\": {\n \"lat\": \"24.8918\",\n \"lng\": \"21.8984\"\n }\n },\n \"phone\": \"210.067.6132\",\n \"website\": \"elvis.io\",\n \"company\": {\n \"name\": \"Johns Group\",\n \"catchPhrase\": \"Configurable multimedia task-force\",\n \"bs\": \"generate enterprise e-tailers\"\n }\n },\n {\n \"id\": 9,\n \"name\": \"Glenna Reichert\",\n \"username\": \"Delphine\",\n \"email\": \"Chaim_McDermott@dana.io\",\n \"address\": {\n \"street\": \"Dayna Park\",\n \"suite\": \"Suite 449\",\n \"city\": \"Bartholomebury\",\n \"zipcode\": \"76495-3109\",\n \"geo\": {\n \"lat\": \"24.6463\",\n \"lng\": \"-168.8889\"\n }\n },\n \"phone\": \"(775)976-6794 x41206\",\n \"website\": \"conrad.com\",\n \"company\": {\n \"name\": \"Yost and Sons\",\n \"catchPhrase\": \"Switchable contextually-based project\",\n \"bs\": \"aggregate real-time technologies\"\n }\n },\n {\n \"id\": 10,\n \"name\": \"Clementina DuBuque\",\n \"username\": \"Moriah.Stanton\",\n \"email\": \"Rey.Padberg@karina.biz\",\n \"address\": {\n \"street\": \"Kattie Turnpike\",\n \"suite\": \"Suite 198\",\n \"city\": \"Lebsackbury\",\n \"zipcode\": \"31428-2261\",\n \"geo\": {\n \"lat\": \"-38.2386\",\n \"lng\": \"57.2232\"\n }\n },\n \"phone\": \"024-648-3804\",\n \"website\": \"ambrose.net\",\n \"company\": {\n \"name\": \"Hoeger LLC\",\n \"catchPhrase\": \"Centralized empowering task-force\",\n \"bs\": \"target end-to-end models\"\n }\n }\n]"
},
"cookies": [],
"headers": [
{
"name": "date",
"value": "Sun, 16 Sep 2018 23:53:13 GMT"
},
{
"name": "via",
"value": "1.1 vegur"
},
{
"name": "x-content-type-options",
"value": "nosniff"
},
{
"name": "cf-cache-status",
"value": "HIT"
},
{
"name": "x-powered-by",
"value": "Express"
},
{
"name": "status",
"value": "200"
},
{
"name": "content-encoding",
"value": "br"
},
{
"name": "pragma",
"value": "no-cache"
},
{
"name": "server",
"value": "cloudflare"
},
{
"name": "etag",
"value": "W/\"d20-ZHlyCzvRVweI5qleuamBhoeSO1g\""
},
{
"name": "expect-ct",
"value": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
},
{
"name": "vary",
"value": "Origin, Accept-Encoding"
},
{
"name": "content-type",
"value": "application/json; charset=utf-8"
},
{
"name": "access-control-allow-origin",
"value": "http://localhost:3000"
},
{
"name": "cache-control",
"value": "public, max-age=14400"
},
{
"name": "access-control-allow-credentials",
"value": "true"
},
{
"name": "cf-ray",
"value": "45b74050bd976be6-SJC"
},
{
"name": "expires",
"value": "Mon, 17 Sep 2018 03:53:13 GMT"
}
],
"headersSize": 627,
"httpVersion": "HTTP/1.1",
"redirectURL": "",
"status": 200,
"statusText": "OK"
},
"startedDateTime": "2018-09-16T23:53:12.979Z",
"time": 123,
"timings": {
"blocked": -1,
"connect": -1,
"dns": -1,
"receive": 0,
"send": 0,
"ssl": -1,
"wait": 123
}
}
],
"pages": [],
"version": "1.2"
}
}
================================================
FILE: examples/rest-persister/index.html
================================================
REST Persister Tests
================================================
FILE: examples/rest-persister/package.json
================================================
{
"name": "@pollyjs/rest-persister-example",
"version": "0.1.0",
"private": true,
"license": "Apache-2.0",
"scripts": {
"test": "start-server-and-test test:polly-server http://localhost:3000 test:server",
"test:server": "http-server -p 4000 -o -c-1 -s",
"test:polly-server": "polly listen"
},
"devDependencies": {
"@pollyjs/adapter-fetch": "*",
"@pollyjs/cli": "*",
"@pollyjs/core": "*",
"@pollyjs/persister-rest": "*",
"chai": "*",
"http-server": "*",
"mocha": "*",
"start-server-and-test": "*"
}
}
================================================
FILE: examples/rest-persister/recordings/REST-Persister_2289553200/should-work_3457346403/recording.har
================================================
{
"log": {
"_recordingName": "REST Persister/should work",
"browser": {
"name": "Chrome",
"version": "69.0"
},
"creator": {
"comment": "persister:rest",
"name": "Polly.JS",
"version": "1.2.0"
},
"entries": [
{
"_id": "ffbc4836d419fc265c3b85cbe1b7f22e",
"_order": 0,
"cache": {},
"request": {
"bodySize": 0,
"cookies": [],
"headers": [],
"headersSize": 63,
"httpVersion": "HTTP/1.1",
"method": "GET",
"queryString": [],
"url": "https://jsonplaceholder.typicode.com/posts/1"
},
"response": {
"bodySize": 292,
"content": {
"mimeType": "application/json; charset=utf-8",
"size": 292,
"text": "{\n \"userId\": 1,\n \"id\": 1,\n \"title\": \"sunt aut facere repellat provident occaecati excepturi optio reprehenderit\",\n \"body\": \"quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto\"\n}"
},
"cookies": [],
"headers": [
{
"name": "cache-control",
"value": "public, max-age=14400"
},
{
"name": "content-type",
"value": "application/json; charset=utf-8"
},
{
"name": "expires",
"value": "Wed, 19 Sep 2018 04:14:08 GMT"
},
{
"name": "pragma",
"value": "no-cache"
}
],
"headersSize": 145,
"httpVersion": "HTTP/1.1",
"redirectURL": "",
"status": 200,
"statusText": "OK"
},
"startedDateTime": "2018-09-19T00:14:08.769Z",
"time": 34,
"timings": {
"blocked": -1,
"connect": -1,
"dns": -1,
"receive": 0,
"send": 0,
"ssl": -1,
"wait": 34
}
}
],
"pages": [],
"version": "1.2"
}
}
================================================
FILE: examples/rest-persister/tests/rest-persister.test.js
================================================
/* global setupPolly */
describe('REST Persister', function () {
setupPolly({
adapters: ['fetch'],
persister: 'rest'
});
it('should work', async function () {
const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const post = await res.json();
expect(res.status).to.equal(200);
expect(post.id).to.equal(1);
});
});
================================================
FILE: examples/rest-persister/tests/setup.js
================================================
// Expose common globals
window.PollyJS = window['@pollyjs/core'];
window.setupPolly = window.PollyJS.setupMocha;
window.expect = window.chai.expect;
// Register the fetch adapter and REST persister
window.PollyJS.Polly.register(window['@pollyjs/adapter-fetch']);
window.PollyJS.Polly.register(window['@pollyjs/persister-rest']);
// Setup Mocha
mocha.setup({ ui: 'bdd', noHighlighting: true });
================================================
FILE: examples/typescript-jest-node-fetch/__recordings__/github-api-client_2139812550/getUser_1648904580/recording.har
================================================
{
"log": {
"_recordingName": "github-api client/getUser",
"creator": {
"comment": "persister:fs",
"name": "Polly.JS",
"version": "5.1.1"
},
"entries": [
{
"_id": "daab17694c1a59a0f3781977d2bf32d7",
"_order": 0,
"cache": {},
"request": {
"bodySize": 0,
"cookies": [],
"headers": [
{
"_fromType": "array",
"name": "accept",
"value": "application/json+vnd.github.v3.raw"
},
{
"_fromType": "array",
"name": "content-type",
"value": "application/json"
},
{
"_fromType": "array",
"name": "user-agent",
"value": "node-fetch/1.0 (+https://github.com/bitinn/node-fetch)"
},
{
"_fromType": "array",
"name": "accept-encoding",
"value": "gzip,deflate"
},
{
"_fromType": "array",
"name": "connection",
"value": "close"
},
{
"name": "host",
"value": "api.github.com"
}
],
"headersSize": 269,
"httpVersion": "HTTP/1.1",
"method": "GET",
"queryString": [],
"url": "https://api.github.com/users/netflix"
},
"response": {
"bodySize": 525,
"content": {
"_isBinary": true,
"mimeType": "application/json; charset=utf-8",
"size": 525,
"text": "[\"1f8b080000000000000395935f6f9b3014c5bf0af2338981aceb8a146dd2fe5493d666d25aa9ca4b64c081bb1adbb20d2945fdeebb06b2647998c41360dddfb987eb7b7a2254\",\"0992a4e49ebbbd8017121228487a13afaede5f8744aa82effc01b9fbf2b5db3cdf74dbe45bc39e7455dc8a36fbfdfc72f7fa98dc1fd66b0459cb1c33bbc608acaf9cd336a5743cb4cb125cd5648de52657d271e996b9aa6943c74e1fdbf53b5428cda431b4c4830b2d0d93ce08a398a527e395abc545f7b1eb507daadb2b21d401d94babff91a77f217435be832ce70b20d453e52a8e7342fb6ffea7c1ba595606a0a7fe8177e3252cceddf0628e9d09413307893e7a6ab856835693d9dc8076a0e42c5bff8028a44cc924bcb2d942085ae4bda15906060041dee27acd2247a2a7da40cbf2ce8fc1f09c438b339daf7681a298eb34c785de9c4dc44f1a1cdfb1a2f6f9db336139e68dd5be70dad530f82ef32556e2fe6a263b92ca4688906418da296298303926f7980c501409a1f261f058f643d9e0963965c3e03313b0574602f363aa19f8a44ebcb2f6d3510afb61410586b34ca0a1a92da893b760a3b90c7ea9c6e43cf82998435d0fb90338376df7f83723ac9b4c40be1bef284da20f21998e8675266974cc1506f3ec0b03337ce5e8c5e17530871e92288e17d1f5225e3d24118aa551bcc5de8d2ece6b926811278b287948927415a7abab2d79fb03b458ebc7f1040000\"]"
},
"cookies": [],
"headers": [
{
"name": "server",
"value": "GitHub.com"
},
{
"name": "date",
"value": "Sat, 19 Feb 2022 05:56:54 GMT"
},
{
"name": "content-type",
"value": "application/json; charset=utf-8"
},
{
"name": "cache-control",
"value": "public, max-age=60, s-maxage=60"
},
{
"name": "vary",
"value": "Accept, Accept-Encoding, Accept, X-Requested-With"
},
{
"name": "etag",
"value": "W/\"e7c5ada389fe724c41d8b2248ede8e368c0fdd159f907ca79d9c0a78fa3344cb\""
},
{
"name": "last-modified",
"value": "Wed, 02 Dec 2020 22:31:35 GMT"
},
{
"name": "x-github-media-type",
"value": "github.v3; format=vnd.github.v3.raw"
},
{
"name": "access-control-expose-headers",
"value": "ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Resource, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, X-GitHub-SSO, X-GitHub-Request-Id, Deprecation, Sunset"
},
{
"name": "access-control-allow-origin",
"value": "*"
},
{
"name": "strict-transport-security",
"value": "max-age=31536000; includeSubdomains; preload"
},
{
"name": "x-frame-options",
"value": "deny"
},
{
"name": "x-content-type-options",
"value": "nosniff"
},
{
"name": "x-xss-protection",
"value": "0"
},
{
"name": "referrer-policy",
"value": "origin-when-cross-origin, strict-origin-when-cross-origin"
},
{
"name": "content-security-policy",
"value": "default-src 'none'"
},
{
"name": "content-encoding",
"value": "gzip"
},
{
"name": "x-ratelimit-limit",
"value": "60"
},
{
"name": "x-ratelimit-remaining",
"value": "59"
},
{
"name": "x-ratelimit-reset",
"value": "1645253814"
},
{
"name": "x-ratelimit-resource",
"value": "core"
},
{
"name": "x-ratelimit-used",
"value": "1"
},
{
"name": "accept-ranges",
"value": "bytes"
},
{
"name": "content-length",
"value": "525"
},
{
"name": "x-github-request-id",
"value": "F38D:0289:2486BB0:45D7297:621086A6"
},
{
"name": "connection",
"value": "close"
}
],
"headersSize": 1283,
"httpVersion": "HTTP/1.1",
"redirectURL": "",
"status": 200,
"statusText": "OK"
},
"startedDateTime": "2022-02-19T05:56:54.149Z",
"time": 454,
"timings": {
"blocked": -1,
"connect": -1,
"dns": -1,
"receive": 0,
"send": 0,
"ssl": -1,
"wait": 454
}
}
],
"pages": [],
"version": "1.2"
}
}
================================================
FILE: examples/typescript-jest-node-fetch/jest.config.ts
================================================
import type { Config } from "@jest/types";
const config: Config.InitialOptions = {
rootDir: ".",
preset: "ts-jest",
testEnvironment: "setup-polly-jest/jest-environment-jsdom",
verbose: true,
testPathIgnorePatterns: ["node_modules", "dist"],
resetModules: true,
globals: {
"ts-jest": {
useESM: true,
},
},
transform: { },
};
export default config;
================================================
FILE: examples/typescript-jest-node-fetch/package.json
================================================
{
"name": "@pollyjs/typescript-jest-node-fetch-example",
"version": "1.0.0",
"private": true,
"main": "./dist/index.js",
"type": "commonjs",
"exports": "./dist/index.js",
"scripts": {
"test": "jest --runInBand",
"test:record": "POLLY_MODE=record jest --runInBand --verbose"
},
"keywords": [
"pollyjs",
"test-mocking",
"jest",
"node",
"typescript",
"fetch"
],
"author": "",
"license": "Apache-2.0",
"dependencies": {
"node-fetch": "^2.6.6"
},
"devDependencies": {
"@pollyjs/adapter-fetch": "^5.1.1",
"@pollyjs/adapter-node-http": "^5.1.1",
"@pollyjs/core": "^5.1.1",
"@pollyjs/node-server": "^5.1.1",
"@pollyjs/persister-fs": "^5.1.1",
"@types/jest": "^26.0.0",
"@types/node": "^16.11.11",
"@types/node-fetch": "^2.5.12",
"@types/pollyjs__adapter": "^4.3.1",
"@types/pollyjs__adapter-fetch": "^2.0.1",
"@types/pollyjs__adapter-node-http": "^2.0.1",
"@types/pollyjs__core": "^4.3.3",
"@types/pollyjs__persister": "^4.3.1",
"@types/pollyjs__persister-fs": "^2.0.1",
"@types/pollyjs__utils": "^2.6.1",
"@types/setup-polly-jest": "^0.5.1",
"jest": "^26.6.0",
"nodemon": "^2.0.15",
"setup-polly-jest": "^0.10.0",
"ts-jest": "^26.5.6",
"ts-node": "^10.4.0",
"typescript": "^4.5.2"
}
}
================================================
FILE: examples/typescript-jest-node-fetch/src/github-api.test.ts
================================================
/** @jest-environment setup-polly-jest/jest-environment-node */
import autoSetupPolly from './utils/auto-setup-polly';
import { getUser } from './github-api';
describe('github-api client', () => {
let pollyContext = autoSetupPolly();
beforeEach(() => {
// Intercept /ping healthcheck requests (example)
pollyContext.polly.server
.any("/ping")
.intercept((req, res) => void res.sendStatus(200));
});
it('getUser', async () => {
const user: any = await getUser('netflix');
expect(typeof user).toBe('object');
expect(user?.login).toBe('Netflix');
});
it('getUser: custom interceptor', async () => {
expect.assertions(1);
pollyContext.polly.server
.get('https://api.github.com/users/failing_request_trigger')
.intercept((req, res) => void res.sendStatus(500));
await expect(getUser('failing_request_trigger')).rejects.toThrow(
'Http Error: 500'
);
});
});
================================================
FILE: examples/typescript-jest-node-fetch/src/github-api.ts
================================================
import fetch from "node-fetch";
import type { Response } from "node-fetch";
export const getUser = async (username: string): Promise => {
return fetch(`https://api.github.com/users/${username}`, {
headers: {
"Accept": "application/json+vnd.github.v3.raw",
"Content-type": "application/json",
},
})
.then(checkErrorAndReturnJson);
};
function checkErrorAndReturnJson(response: Response) {
return response.ok
? response.json()
: Promise.reject(new Error(`Http Error: ${response.status}`));
}
================================================
FILE: examples/typescript-jest-node-fetch/src/utils/auto-setup-polly.ts
================================================
import path from "path";
import { setupPolly } from "setup-polly-jest";
import { Polly, PollyConfig } from "@pollyjs/core";
import NodeHttpAdapter from "@pollyjs/adapter-node-http";
import FSPersister from "@pollyjs/persister-fs";
Polly.register(NodeHttpAdapter);
Polly.register(FSPersister);
let recordIfMissing = true;
let mode: PollyConfig['mode'] = 'replay';
switch (process.env.POLLY_MODE) {
case 'record':
mode = 'record';
break;
case 'replay':
mode = 'replay';
break;
case 'offline':
mode = 'replay';
recordIfMissing = false;
break;
}
export default function autoSetupPolly() {
/**
* This persister can be adapted for both Node.js and Browser environments.
*
* TODO: Customize your config.
*/
return setupPolly({
// 🟡 Note: In node, most `fetch` like libraries use the http/https modules.
// `node-fetch` is handled by `NodeHttpAdapter`, NOT the `FetchAdapter`.
adapters: ["node-http"],
mode,
recordIfMissing,
flushRequestsOnStop: true,
logging: false,
recordFailedRequests: true,
persister: "fs",
persisterOptions: {
fs: {
recordingsDir: path.resolve(__dirname, "../../__recordings__"),
},
},
});
}
================================================
FILE: examples/typescript-jest-node-fetch/tsconfig.json
================================================
{
"compilerOptions": {
"target": "ES5",
"lib": ["esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"alwaysStrict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "ESNext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"sourceMap": true,
"baseUrl": ".",
"rootDir": ".",
"outDir": "dist",
"useUnknownInCatchVariables": false
},
"include": ["src"]
}
================================================
FILE: jest.config.js
================================================
/* eslint-env node */
module.exports = {
testURL: 'http://localhost:4000/api',
testMatch: ['**/@pollyjs/*/build/jest/*.js'],
roots: ['/packages/@pollyjs'],
reporters: ['jest-tap-reporter'],
testEnvironment: 'jsdom'
};
================================================
FILE: lerna.json
================================================
{
"version": "6.0.7",
"npmClient": "yarn",
"useWorkspaces": true,
"packages": ["packages/@pollyjs/*"],
"command": {
"publish": {
"allowBranch": "master",
"conventionalCommits": true,
"message": "chore: Publish %s",
"ignoreChanges": ["docs/**", "examples/**", "**/tests/**", "**/*.md"]
}
},
"changelog": {
"repo": "Netflix/pollyjs",
"labels": {
"Tag: Breaking Change": ":boom: Breaking Change",
"Tag: Enhancement": ":rocket: Enhancement",
"Tag: Bug Fix": ":bug: Bug Fix",
"Tag: Documentation": ":memo: Documentation"
}
}
}
================================================
FILE: package.json
================================================
{
"private": true,
"license": "Apache-2.0",
"repository": "https://github.com/netflix/pollyjs",
"contributors": [
{
"name": "Jason Mitchell",
"email": "jason.mitchell.w@gmail.com"
},
{
"name": "Offir Golan",
"email": "offirgolan@gmail.com"
}
],
"workspaces": [
"packages/@pollyjs/*"
],
"lint-staged": {
"*.js": [
"eslint --fix",
"git add"
],
"*.{json,md,html,yml,css}": [
"prettier --ignore-path .eslintignore --write",
"git add"
]
},
"scripts": {
"build:prod": "NODE_ENV=production yarn build && NODE_ENV=production MINIFY=true yarn build",
"build:server": "lerna run build --scope=@pollyjs/node-server --scope=@pollyjs/utils",
"build": "lerna run build --ignore=@pollyjs/ember --parallel",
"clean": "rimraf packages/@pollyjs/*/dist && rimraf packages/@pollyjs/*/build",
"contributors": "npx contributor-faces -e '*\\[bot\\]'",
"docs:publish": "gh-pages --dist docs --dotfiles --message 'chore: Publish docs'",
"docs:serve": "docsify serve ./docs",
"lint:fix": "yarn run lint --fix",
"lint": "eslint .",
"postlint:fix": "prettier --ignore-path .eslintignore --write \"**/*.{json,md,html,yml,css}\"",
"postrelease:publish": "yarn docs:publish",
"prepare": "husky install",
"prerelease:publish": "npm-run-all clean build:prod",
"pretest:ci": "yarn clean && yarn build && yarn test:build",
"pretest": "./scripts/require-test-build.sh",
"release:publish": "lerna publish from-git",
"release:version": "lerna version",
"release": "npm-run-all \"release:version {@}\" release:publish --",
"test:build": "lerna run test:build --parallel",
"test:ci": "testem ci",
"test": "testem",
"watch": "lerna run watch-all --parallel"
},
"devDependencies": {
"@babel/core": "^7.16.0",
"@babel/plugin-external-helpers": "^7.16.0",
"@babel/plugin-proposal-object-rest-spread": "^7.16.0",
"@babel/plugin-transform-runtime": "^7.16.4",
"@babel/preset-env": "^7.16.4",
"@babel/runtime": "^7.16.3",
"@babel/runtime-corejs2": "^7.16.3",
"@commitlint/cli": "^15.0.0",
"@commitlint/config-conventional": "^15.0.0",
"@commitlint/config-lerna-scopes": "^15.0.0",
"@commitlint/travis-cli": "^15.0.0",
"chai": "^4.3.4",
"compression": "^1.7.4",
"contributor-faces": "^1.1.0",
"deepmerge": "^4.2.0",
"docsify-cli": "^4.4.3",
"eslint": "^8.3.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "^2.25.3",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-react": "^7.27.1",
"formdata-polyfill": "^4.0.10",
"gh-pages": "^3.2.3",
"har-validator": "^5.1.3",
"husky": "^7.0.4",
"jest": "^27.3.1",
"jest-tap-reporter": "^1.9.0",
"lerna": "^4.0.0",
"lerna-alias": "^3.0.2",
"lint-staged": "^12.1.2",
"mocha": "^9.1.3",
"npm-run-all": "^4.1.5",
"prettier": "^2.5.0",
"rimraf": "^3.0.2",
"rollup": "^1.14.6",
"rollup-plugin-alias": "^1.5.2",
"rollup-plugin-babel": "^4.4.0",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-json": "^4.0.0",
"rollup-plugin-multi-entry": "^2.1.0",
"rollup-plugin-node-builtins": "^2.1.2",
"rollup-plugin-node-globals": "^1.4.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-terser": "5.0.0",
"testem": "^3.6.0"
}
}
================================================
FILE: packages/@pollyjs/adapter/CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.6](https://github.com/netflix/pollyjs/compare/v6.0.5...v6.0.6) (2023-07-20)
**Note:** Version bump only for package @pollyjs/adapter
## [6.0.4](https://github.com/netflix/pollyjs/compare/v6.0.3...v6.0.4) (2021-12-10)
### Bug Fixes
* Update types for class methods ([#438](https://github.com/netflix/pollyjs/issues/438)) ([b88655a](https://github.com/netflix/pollyjs/commit/b88655ac1b4ca7348afd45e9aeaa50e998ea68d7))
## [6.0.2](https://github.com/netflix/pollyjs/compare/v6.0.1...v6.0.2) (2021-12-07)
### Bug Fixes
* **core:** Fix types for registering adapters and persisters ([#435](https://github.com/netflix/pollyjs/issues/435)) ([cc2fa19](https://github.com/netflix/pollyjs/commit/cc2fa197a5c0a5fdef4602c4a207d31f3e677897))
## [6.0.1](https://github.com/netflix/pollyjs/compare/v6.0.0...v6.0.1) (2021-12-06)
### Bug Fixes
* **types:** add types.d.ts to package.files ([#431](https://github.com/netflix/pollyjs/issues/431)) ([113ee89](https://github.com/netflix/pollyjs/commit/113ee898bcf0467c5c48c15b53fc9198e2e91cb1))
# [6.0.0](https://github.com/netflix/pollyjs/compare/v5.2.0...v6.0.0) (2021-11-30)
* feat!: Cleanup adapter and persister APIs (#429) ([06499fc](https://github.com/netflix/pollyjs/commit/06499fc2d85254b3329db2bec770d173ed32bca0)), closes [#429](https://github.com/netflix/pollyjs/issues/429)
* feat!: Improve logging and add logLevel (#427) ([bef3ee3](https://github.com/netflix/pollyjs/commit/bef3ee39f71dfc2fa4dbeb522dfba16d01243e9f)), closes [#427](https://github.com/netflix/pollyjs/issues/427)
* feat!: Use base64 instead of hex encoding for binary data (#420) ([6bb9b36](https://github.com/netflix/pollyjs/commit/6bb9b36522d73f9c079735d9006a12376aee39ea)), closes [#420](https://github.com/netflix/pollyjs/issues/420)
* feat(ember)!: Upgrade to ember octane (#415) ([8559ef8](https://github.com/netflix/pollyjs/commit/8559ef8c600aefaec629870eac5f5c8953e18b16)), closes [#415](https://github.com/netflix/pollyjs/issues/415)
### BREAKING CHANGES
* - Adapter
- `passthroughRequest` renamed to `onFetchResponse`
- `respondToRequest` renamed to `onRespond`
- Persister
- `findRecording` renamed to `onFindRecording`
- `saveRecording` renamed to `onSaveRecording`
- `deleteRecording` renamed to `onDeleteRecording`
* The `logging` configuration option has now been replaced with `logLevel`. This allows for more fine-grain control over what should be logged as well as silencing logs altogether.
* Use the standard `encoding` field on the generated har file instead of `_isBinary` and use `base64` encoding instead of `hex` to reduce the payload size.
* @pollyjs dependencies have been moved to peer dependencies
## [5.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v5.1.0...v5.1.1) (2021-06-02)
**Note:** Version bump only for package @pollyjs/adapter
# [5.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v4.3.0...v5.0.0) (2020-06-23)
### Features
* Remove deprecated Persister.name and Adapter.name ([#343](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/issues/343)) ([1223ba0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/1223ba0))
### BREAKING CHANGES
* Persister.name and Adapter.name have been replaced with Persister.id and Adapter.id
# [4.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v4.2.1...v4.3.0) (2020-05-18)
**Note:** Version bump only for package @pollyjs/adapter
## [4.2.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v4.2.0...v4.2.1) (2020-04-30)
### Bug Fixes
* **adapter-node-http:** Improve binary response body handling ([#329](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/issues/329)) ([9466989](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/9466989))
# [4.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v4.0.4...v4.1.0) (2020-04-23)
### Bug Fixes
* Improve abort handling ([#320](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/issues/320)) ([cc46bb4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/cc46bb4))
* Legacy persisters and adapters should register ([#325](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/issues/325)) ([8fd4d19](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/8fd4d19))
## [4.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v4.0.3...v4.0.4) (2020-03-21)
### Bug Fixes
* Deprecates adapter & persister `name` in favor of `id` ([#310](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/issues/310)) ([41dd093](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/41dd093))
## [4.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v4.0.1...v4.0.2) (2020-01-29)
**Note:** Version bump only for package @pollyjs/adapter
# [4.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v3.0.2...v4.0.0) (2020-01-13)
### Bug Fixes
* **adapter:** Clone the recording entry before mutating it ([#294](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/issues/294)) ([d7e1303](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/d7e1303))
# [3.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v2.7.0...v3.0.0) (2019-12-18)
**Note:** Version bump only for package @pollyjs/adapter
## [2.6.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v2.6.2...v2.6.3) (2019-09-30)
### Bug Fixes
* use watch strategy ([#236](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/issues/236)) ([5b4edf3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/5b4edf3))
# [2.6.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v2.5.0...v2.6.0) (2019-07-17)
### Features
* PollyError and improved adapter error handling ([#234](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/issues/234)) ([23a2127](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/23a2127))
# [2.4.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v2.3.2...v2.4.0) (2019-04-27)
### Features
* **core:** Improved control flow with `times` and `stopPropagation` ([#202](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/202)) ([2c8231e](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/2c8231e))
# [2.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v2.1.0...v2.2.0) (2019-02-20)
### Features
* Add `error` event and improve error handling ([#185](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/185)) ([3694ebc](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/3694ebc))
# [2.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v2.0.0...v2.1.0) (2019-02-04)
### Bug Fixes
* **adapter:** Log information if request couldn't be found in recording ([#172](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/172)) ([8dcdf7b](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/8dcdf7b))
* Correctly handle array header values ([#179](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/179)) ([fb7dbb4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/fb7dbb4))
# [2.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v1.4.2...v2.0.0) (2019-01-29)
### Bug Fixes
* **adapter:** Test for navigator before accessing ([#165](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/165)) ([7200255](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/7200255))
### Features
* Make PollyRequest.respond accept a response object ([#168](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/168)) ([5b07b26](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/5b07b26))
* Simplify adapter implementation ([#154](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/154)) ([12c8601](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/12c8601))
### BREAKING CHANGES
* Any adapters calling `pollyRequest.respond` should pass it a response object instead of the previous 3 arguments (statusCode, headers, body).
* Changes to the base adapter implementation and external facing API
## [1.4.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v1.4.0...v1.4.1) (2018-12-13)
**Note:** Version bump only for package @pollyjs/adapter
## [1.3.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v1.3.1...v1.3.2) (2018-11-29)
**Note:** Version bump only for package @pollyjs/adapter
## [1.3.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/v1.2.0...v1.3.1) (2018-11-28)
### Features
* Add an onIdentifyRequest hook to allow adapter level serialization ([#140](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/140)) ([548002c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/548002c))
# 1.2.0 (2018-09-16)
### Bug Fixes
* Config expiresIn can contain periods. i.e, 1.5 weeks ([e9c7aaa](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/e9c7aaa))
* Creator cleanup and persister assertion ([#67](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/67)) ([19fee5a](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/19fee5a))
### Features
* Abort and passthrough from an intercept ([#57](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/57)) ([4ebacb8](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/4ebacb8))
* Class events and EventEmitter ([#52](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/52)) ([0a3d591](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/0a3d591))
* Convert recordings to be HAR compliant ([#45](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/45)) ([e622640](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/e622640))
* Custom persister support ([8bb313c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/8bb313c))
* Keyed persister & adapter options ([#60](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/60)) ([29ed8e1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/29ed8e1))
* Node File System Persister ([#61](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/61)) ([0a0eeca](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/0a0eeca))
* Puppeteer Adapter ([#64](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/64)) ([f902c6d](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/f902c6d))
* Wait for all handled requests to resolve via `.flush()` ([#75](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/75)) ([a3113b7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/a3113b7))
* **core:** Server level configuration ([#80](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/80)) ([0f32d9b](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/0f32d9b))
* **persister:** Cache recordings ([#31](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/31)) ([a04d7a7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/a04d7a7))
### BREAKING CHANGES
* Recordings now produce HAR compliant json. Please delete existing recordings.
## [1.1.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/@pollyjs/adapter@1.1.2...@pollyjs/adapter@1.1.3) (2018-08-22)
**Note:** Version bump only for package @pollyjs/adapter
## [1.1.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/@pollyjs/adapter@1.1.1...@pollyjs/adapter@1.1.2) (2018-08-12)
**Note:** Version bump only for package @pollyjs/adapter
## [1.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/@pollyjs/adapter@1.1.0...@pollyjs/adapter@1.1.1) (2018-08-12)
**Note:** Version bump only for package @pollyjs/adapter
# [1.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/@pollyjs/adapter@1.0.0...@pollyjs/adapter@1.1.0) (2018-07-26)
### Features
* Wait for all handled requests to resolve via `.flush()` ([#75](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/75)) ([a3113b7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/a3113b7))
# [1.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/@pollyjs/adapter@0.3.1...@pollyjs/adapter@1.0.0) (2018-07-20)
### Bug Fixes
* Creator cleanup and persister assertion ([#67](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/67)) ([19fee5a](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/19fee5a))
### Features
* Abort and passthrough from an intercept ([#57](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/57)) ([4ebacb8](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/4ebacb8))
* Class events and EventEmitter ([#52](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/52)) ([0a3d591](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/0a3d591))
* Convert recordings to be HAR compliant ([#45](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/45)) ([e622640](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/e622640))
* Keyed persister & adapter options ([#60](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/60)) ([29ed8e1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/29ed8e1))
* Node File System Persister ([#61](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/61)) ([0a0eeca](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/0a0eeca))
* Puppeteer Adapter ([#64](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/64)) ([f902c6d](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/f902c6d))
### BREAKING CHANGES
* Recordings now produce HAR compliant json. Please delete existing recordings.
## [0.3.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/@pollyjs/adapter@0.3.0...@pollyjs/adapter@0.3.1) (2018-06-27)
**Note:** Version bump only for package @pollyjs/adapter
# [0.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/@pollyjs/adapter@0.2.0...@pollyjs/adapter@0.3.0) (2018-06-21)
### Features
* **persister:** Cache recordings ([#31](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter/issues/31)) ([a04d7a7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/a04d7a7))
# [0.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/compare/@pollyjs/adapter@0.1.0...@pollyjs/adapter@0.2.0) (2018-06-16)
### Features
* Custom persister support ([8bb313c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter/commit/8bb313c))
================================================
FILE: packages/@pollyjs/adapter/LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Netflix Inc and @pollyjs contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: packages/@pollyjs/adapter/README.md
================================================
Record, Replay, and Stub HTTP Interactions
[](https://travis-ci.com/Netflix/pollyjs)
[](https://badge.fury.io/js/%40pollyjs%2Fadapter)
[](http://www.apache.org/licenses/LICENSE-2.0)
The `@pollyjs/adapter` package provides an extendable base adapter class that
contains core logic dependent on by the [Fetch](https://netflix.github.io/pollyjs/#/adapters/fetch)
& [XHR](https://netflix.github.io/pollyjs/#/adapters/xhr) adapters.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/adapter -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/adapter -D
```
## Documentation
Check out the [Custom Adapter](https://netflix.github.io/pollyjs/#/adapters/custom)
documentation for more details.
## Usage
```js
import Adapter from '@pollyjs/adapter';
class CustomAdapter extends Adapter {
static get id() {
return 'custom';
}
onConnect() {
/* Do something when the adapter is connect to */
}
onDisconnect() {
/* Do something when the adapter is disconnected from */
}
}
```
For better usage examples, please refer to the source code for
the [Fetch](https://github.com/Netflix/pollyjs/blob/master/packages/%40pollyjs/core/src/adapters/fetch/index.js) & [XHR](https://github.com/Netflix/pollyjs/blob/master/packages/%40pollyjs/core/src/adapters/xhr/index.js) adapters.
## License
Copyright (c) 2018 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
================================================
FILE: packages/@pollyjs/adapter/package.json
================================================
{
"name": "@pollyjs/adapter",
"version": "6.0.6",
"description": "Extendable base adapter class used by @pollyjs",
"main": "dist/cjs/pollyjs-adapter.js",
"module": "dist/es/pollyjs-adapter.js",
"browser": "dist/umd/pollyjs-adapter.js",
"types": "types.d.ts",
"files": [
"src",
"dist",
"types.d.ts"
],
"repository": "https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter",
"scripts": {
"build": "rollup -c ../../../scripts/rollup/default.config.js",
"test:build": "rollup -c rollup.config.test.js",
"test:build:watch": "rollup -c rollup.config.test.js -w",
"build:watch": "yarn build -w",
"watch-all": "npm-run-all --parallel build:watch test:build:watch"
},
"keywords": [
"polly",
"pollyjs",
"adapter"
],
"publishConfig": {
"access": "public"
},
"contributors": [
{
"name": "Jason Mitchell",
"email": "jason.mitchell.w@gmail.com"
},
{
"name": "Offir Golan",
"email": "offirgolan@gmail.com"
}
],
"license": "Apache-2.0",
"dependencies": {
"@pollyjs/utils": "^6.0.6"
},
"devDependencies": {
"rollup": "^1.14.6"
}
}
================================================
FILE: packages/@pollyjs/adapter/rollup.config.test.js
================================================
import createNodeTestConfig from '../../../scripts/rollup/node.test.config';
import createBrowserTestConfig from '../../../scripts/rollup/browser.test.config';
export default [createNodeTestConfig(), createBrowserTestConfig()];
================================================
FILE: packages/@pollyjs/adapter/src/index.js
================================================
import {
ACTIONS,
MODES,
EXPIRY_STRATEGIES,
PollyError,
Serializers,
assert
} from '@pollyjs/utils';
import isExpired from './utils/is-expired';
import stringifyRequest from './utils/stringify-request';
import normalizeRecordedResponse from './utils/normalize-recorded-response';
const REQUEST_HANDLER = Symbol();
export default class Adapter {
constructor(polly) {
this.polly = polly;
this.isConnected = false;
}
static get type() {
return 'adapter';
}
/* eslint-disable-next-line getter-return */
static get id() {
assert('Must override the static `id` getter.');
}
get defaultOptions() {
return {};
}
get options() {
return {
...(this.defaultOptions || {}),
...((this.polly.config.adapterOptions || {})[this.constructor.id] || {})
};
}
get persister() {
return this.polly.persister;
}
connect() {
if (!this.isConnected) {
this.onConnect();
this.isConnected = true;
this.polly.logger.log.debug(
`Connected to ${this.constructor.id} adapter.`
);
}
}
onConnect() {
this.assert('Must implement the `onConnect` hook.');
}
disconnect() {
if (this.isConnected) {
this.onDisconnect();
this.isConnected = false;
this.polly.logger.log.debug(
`Disconnected from ${this.constructor.id} adapter.`
);
}
}
onDisconnect() {
this.assert('Must implement the `onDisconnect` hook.');
}
timeout(pollyRequest, { time }) {
const { timing } = pollyRequest.config;
if (typeof timing === 'function') {
return timing(time);
}
}
async handleRequest(request) {
const pollyRequest = this.polly.registerRequest(request);
try {
pollyRequest.on('identify', (...args) => this.onIdentifyRequest(...args));
await this.onRequest(pollyRequest);
await pollyRequest.init();
await this[REQUEST_HANDLER](pollyRequest);
if (pollyRequest.aborted) {
throw new PollyError('Request aborted.');
}
await this.onRequestFinished(pollyRequest);
} catch (error) {
await this.onRequestFailed(pollyRequest, error);
}
return pollyRequest;
}
async [REQUEST_HANDLER](pollyRequest) {
const { mode } = this.polly;
const { _interceptor: interceptor } = pollyRequest;
if (pollyRequest.aborted) {
return;
}
if (pollyRequest.shouldIntercept) {
await this.intercept(pollyRequest, interceptor);
if (interceptor.shouldIntercept) {
return;
}
}
if (
mode === MODES.PASSTHROUGH ||
pollyRequest.shouldPassthrough ||
interceptor.shouldPassthrough
) {
return this.passthrough(pollyRequest);
}
this.assert(
'A persister must be configured in order to record and replay requests.',
!!this.persister
);
if (mode === MODES.RECORD) {
return this.record(pollyRequest);
}
if (mode === MODES.REPLAY) {
return this.replay(pollyRequest);
}
// This should never be reached. If it did, then something screwy happened.
this.assert(
'Unhandled request: \n' + stringifyRequest(pollyRequest, null, 2)
);
}
async passthrough(pollyRequest) {
pollyRequest.action = ACTIONS.PASSTHROUGH;
return this.onPassthrough(pollyRequest);
}
/**
* @param {PollyRequest} pollyRequest
*/
async onPassthrough(pollyRequest) {
const response = await this.onFetchResponse(pollyRequest);
await pollyRequest.respond(response);
}
async intercept(pollyRequest, interceptor) {
pollyRequest.action = ACTIONS.INTERCEPT;
await pollyRequest._intercept(interceptor);
if (interceptor.shouldIntercept) {
return this.onIntercept(pollyRequest, pollyRequest.response);
}
}
/**
* @param {PollyRequest} pollyRequest
* @param {PollyResponse} pollyResponse
*/
async onIntercept(pollyRequest, pollyResponse) {
await pollyRequest.respond(pollyResponse);
}
async record(pollyRequest) {
pollyRequest.action = ACTIONS.RECORD;
if ('navigator' in global && !navigator.onLine) {
pollyRequest.log.warn(
'[Polly] Recording may fail because the browser is offline.\n' +
`${stringifyRequest(pollyRequest)}`
);
}
return this.onRecord(pollyRequest);
}
/**
* @param {PollyRequest} pollyRequest
*/
async onRecord(pollyRequest) {
await this.onPassthrough(pollyRequest);
if (!pollyRequest.aborted) {
await this.persister.recordRequest(pollyRequest);
}
}
async replay(pollyRequest) {
const { config } = pollyRequest;
const recordingEntry = await this.persister.findEntry(pollyRequest);
if (recordingEntry) {
/*
Clone the recording entry so any changes will not actually persist to
the stored recording.
Note: Using JSON.parse/stringify instead of lodash/cloneDeep since
the recording entry is stored as json.
*/
const clonedRecordingEntry = JSON.parse(JSON.stringify(recordingEntry));
await pollyRequest._emit('beforeReplay', clonedRecordingEntry);
if (isExpired(clonedRecordingEntry.startedDateTime, config.expiresIn)) {
const message =
'Recording for the following request has expired.\n' +
`${stringifyRequest(pollyRequest, null, 2)}`;
switch (config.expiryStrategy) {
// exit into the record flow if expiryStrategy is "record".
case EXPIRY_STRATEGIES.RECORD:
return this.record(pollyRequest);
// throw an error and exit if expiryStrategy is "error".
case EXPIRY_STRATEGIES.ERROR:
this.assert(message);
break;
// log a warning and continue if expiryStrategy is "warn".
case EXPIRY_STRATEGIES.WARN:
pollyRequest.log.warn(`[Polly] ${message}`);
break;
// throw an error if we encounter an unsupported expiryStrategy.
default:
this.assert(
`Invalid config option passed for "expiryStrategy": "${config.expiryStrategy}"`
);
break;
}
}
await this.timeout(pollyRequest, clonedRecordingEntry);
pollyRequest.action = ACTIONS.REPLAY;
return this.onReplay(
pollyRequest,
normalizeRecordedResponse(clonedRecordingEntry.response),
clonedRecordingEntry
);
}
if (config.recordIfMissing) {
return this.record(pollyRequest);
}
this.assert(
'Recording for the following request is not found and `recordIfMissing` is `false`.\n' +
stringifyRequest(pollyRequest, null, 2)
);
}
/**
* @param {PollyRequest} pollyRequest
* @param {Object} normalizedResponse The normalized response generated from the recording entry
* @param {Object} recordingEntry The entire recording entry
*/
async onReplay(pollyRequest, normalizedResponse) {
await pollyRequest.respond(normalizedResponse);
}
assert(message, ...args) {
assert(
`[${this.constructor.type}:${this.constructor.id}] ${message}`,
...args
);
}
/**
* @param {PollyRequest} pollyRequest
*/
onRequest() {}
/**
* @param {PollyRequest} pollyRequest
*/
async onIdentifyRequest(pollyRequest) {
const { identifiers } = pollyRequest;
// Serialize the request body so it can be properly hashed
for (const type of ['blob', 'formData', 'buffer']) {
identifiers.body = await Serializers[type](identifiers.body);
}
}
/**
* @param {PollyRequest} pollyRequest
*/
async onRequestFinished(pollyRequest) {
await this.onRespond(pollyRequest);
pollyRequest.promise.resolve();
}
/**
* @param {PollyRequest} pollyRequest
* @param {Error} [error]
*/
async onRequestFailed(pollyRequest, error) {
const { aborted } = pollyRequest;
error = error || new PollyError('Request failed due to an unknown error.');
try {
if (aborted) {
await pollyRequest._emit('abort');
} else {
await pollyRequest._emit('error', error);
}
await this.onRespond(pollyRequest, error);
} finally {
pollyRequest.promise.reject(error);
}
}
/**
* Make sure the response from a Polly request is delivered to the
* user through the adapter interface.
*
* Calling `pollyjs.flush()` will await this method.
*
* @param {PollyRequest} pollyRequest
* @param {Error} [error]
*/
async onRespond(/* pollyRequest, error */) {}
/**
* @param {PollyRequest} pollyRequest
* @returns {Object({ statusCode: number, headers: Object, body: string })}
*/
async onFetchResponse(/* pollyRequest */) {
this.assert('Must implement the `onFetchResponse` hook.');
}
}
================================================
FILE: packages/@pollyjs/adapter/src/utils/dehumanize-time.js
================================================
const ALPHA_NUMERIC_DOT = /([0-9.]+)([a-zA-Z]+)/g;
const TIMES = {
ms: 1,
millisecond: 1,
milliseconds: 1,
s: 1000,
sec: 1000,
secs: 1000,
second: 1000,
seconds: 1000,
m: 60000,
min: 60000,
mins: 60000,
minute: 60000,
minutes: 60000,
h: 3600000,
hr: 3600000,
hrs: 3600000,
hour: 3600000,
hours: 3600000,
d: 86400000,
day: 86400000,
days: 86400000,
w: 604800000,
wk: 604800000,
wks: 604800000,
week: 604800000,
weeks: 604800000,
y: 31536000000,
yr: 31536000000,
yrs: 31536000000,
year: 31536000000,
years: 31536000000
};
export default function dehumanizeTime(input) {
if (typeof input !== 'string') {
return NaN;
}
const parts = input.replace(/ /g, '').match(ALPHA_NUMERIC_DOT);
const sets = parts.map((part) =>
part.split(ALPHA_NUMERIC_DOT).filter((o) => o)
);
return sets.reduce((accum, [number, unit]) => {
return accum + parseFloat(number) * TIMES[unit];
}, 0);
}
================================================
FILE: packages/@pollyjs/adapter/src/utils/is-expired.js
================================================
import dehumanizeTime from './dehumanize-time';
export default function isExpired(recordedOn, expiresIn) {
if (recordedOn && expiresIn) {
return (
new Date() >
new Date(new Date(recordedOn).getTime() + dehumanizeTime(expiresIn))
);
}
return false;
}
================================================
FILE: packages/@pollyjs/adapter/src/utils/normalize-recorded-response.js
================================================
const { isArray } = Array;
export default function normalizeRecordedResponse(response) {
const { status, statusText, headers, content } = response;
return {
statusText,
statusCode: status,
headers: normalizeHeaders(headers),
body: content && content.text,
encoding: content && content.encoding
};
}
function normalizeHeaders(headers) {
return (headers || []).reduce((accum, { name, value, _fromType }) => {
const existingValue = accum[name];
if (existingValue) {
if (!isArray(existingValue)) {
accum[name] = [existingValue];
}
accum[name].push(value);
} else {
accum[name] = _fromType === 'array' ? [value] : value;
}
return accum;
}, {});
}
================================================
FILE: packages/@pollyjs/adapter/src/utils/stringify-request.js
================================================
export default function stringifyRequest(req, ...args) {
const config = { ...req.config };
// Remove all adapter & persister config options as they can cause a circular
// structure to the final JSON
['adapter', 'adapterOptions', 'persister', 'persisterOptions'].forEach(
(k) => delete config[k]
);
return JSON.stringify(
{
url: req.url,
method: req.method,
headers: req.headers,
body: req.body,
recordingName: req.recordingName,
id: req.id,
order: req.order,
identifiers: req.identifiers,
config
},
...args
);
}
================================================
FILE: packages/@pollyjs/adapter/tests/unit/adapter-test.js
================================================
import Adapter from '../../src';
describe('Unit | Adapter', function () {
it('should exist', function () {
expect(Adapter).to.be.a('function');
});
});
================================================
FILE: packages/@pollyjs/adapter/tests/unit/utils/dehumanize-time-test.js
================================================
import dehumanizeTime from '../../../src/utils/dehumanize-time';
describe('Unit | Utils | dehumanizeTime', function () {
it('should exist', function () {
expect(dehumanizeTime).to.be.a('function');
});
it('should work', function () {
expect(dehumanizeTime(null)).to.be.NaN;
expect(dehumanizeTime(undefined)).to.be.NaN;
expect(dehumanizeTime(true)).to.be.NaN;
expect(dehumanizeTime(false)).to.be.NaN;
[
[['1ms', '1millisecond', '1 milliseconds'], 1],
[['10ms', '10millisecond', '10 milliseconds'], 10],
[['100ms', '100millisecond', '100 milliseconds'], 100],
[['1s', '1sec', '1secs', '1 second', '1 seconds'], 1000],
[['1.5s', '1.5sec', '1.5secs', '1.5 second', '1.5 seconds'], 1500],
[['1m', '1min', '1mins', '1 minute', '1 minutes'], 1000 * 60],
[['1h', '1hr', '1hrs', '1 hour', '1 hours'], 1000 * 60 * 60],
[['1d', '1day', '1 days'], 1000 * 60 * 60 * 24],
[['1w', '1wk', '1wks', '1 week', '1 weeks'], 1000 * 60 * 60 * 24 * 7],
[['1y', '1yr', '1 yrs', '1 year', '1 years'], 1000 * 60 * 60 * 24 * 365],
[
[
'1y 2 wks 3day 4 minutes 5secs 6 ms',
'6 millisecond 5s 4 min 3d 2 weeks 1yrs'
],
33005045006
]
].forEach(([inputs, value]) => {
inputs.forEach((str) => expect(dehumanizeTime(str)).to.equal(value));
});
});
});
================================================
FILE: packages/@pollyjs/adapter/tests/unit/utils/is-expired-test.js
================================================
import isExpired from '../../../src/utils/is-expired';
describe('Unit | Utils | isExpired', function () {
it('should exist', function () {
expect(isExpired).to.be.a('function');
});
it('should work', function () {
[
[undefined, undefined, false],
[null, null, false],
[new Date(), undefined, false],
[undefined, '1 day', false],
[new Date(), '1 day', false],
[new Date('1/1/2018'), '100 years', false],
[new Date('1/1/2017'), '1y', true],
[new Date('1/1/2018'), '1m5d10h', true]
].forEach(([recordedOn, expiresIn, value]) => {
expect(isExpired(recordedOn, expiresIn)).to.equal(value);
});
});
});
================================================
FILE: packages/@pollyjs/adapter/types.d.ts
================================================
import { Polly, Request, Interceptor, Response } from '@pollyjs/core';
export default class Adapter<
TOptions extends {} = {},
TRequest extends Request = Request
> {
static readonly id: string;
static readonly type: string;
constructor(polly: Polly);
polly: Polly;
isConnected: boolean;
readonly defaultOptions: TOptions;
readonly options: TOptions;
persister: Polly['persister'];
connect(): void;
onConnect(): void;
disconnect(): void;
onDisconnect(): void;
private timeout(request: TRequest, options: { time: number }): Promise;
handleRequest(
request: Pick<
TRequest,
'url' | 'method' | 'headers' | 'body' | 'requestArguments'
>
): Promise;
private passthrough(request: TRequest): Promise;
onPassthrough(request: TRequest): Promise;
private intercept(request: TRequest, interceptor: Interceptor): Promise;
onIntercept(request: TRequest, interceptor: Interceptor): Promise;
private record(request: TRequest): Promise;
onRecord(request: TRequest): Promise;
private replay(request: TRequest): Promise;
onReplay(request: TRequest): Promise;
assert(message: string, condition?: boolean): void;
onFetchResponse(
pollyRequest: TRequest
): Promise>;
onRespond(request: TRequest, error?: Error): Promise;
onIdentifyRequest(request: TRequest): Promise;
onRequest(request: TRequest): Promise;
onRequestFinished(request: TRequest): Promise;
onRequestFailed(request: TRequest): Promise;
}
================================================
FILE: packages/@pollyjs/adapter-fetch/CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.7](https://github.com/netflix/pollyjs/compare/v6.0.6...v6.0.7) (2025-05-31)
### Bug Fixes
* Undeprecating fetch for node because node supports fetch now ([#506](https://github.com/netflix/pollyjs/issues/506)) ([be0bd6c](https://github.com/netflix/pollyjs/commit/be0bd6ca0035565a1c29770bfc87f0b0754fec27))
## [6.0.6](https://github.com/netflix/pollyjs/compare/v6.0.5...v6.0.6) (2023-07-20)
**Note:** Version bump only for package @pollyjs/adapter-fetch
## [6.0.5](https://github.com/netflix/pollyjs/compare/v6.0.4...v6.0.5) (2022-04-04)
**Note:** Version bump only for package @pollyjs/adapter-fetch
## [6.0.4](https://github.com/netflix/pollyjs/compare/v6.0.3...v6.0.4) (2021-12-10)
**Note:** Version bump only for package @pollyjs/adapter-fetch
## [6.0.3](https://github.com/netflix/pollyjs/compare/v6.0.2...v6.0.3) (2021-12-08)
**Note:** Version bump only for package @pollyjs/adapter-fetch
## [6.0.2](https://github.com/netflix/pollyjs/compare/v6.0.1...v6.0.2) (2021-12-07)
**Note:** Version bump only for package @pollyjs/adapter-fetch
## [6.0.1](https://github.com/netflix/pollyjs/compare/v6.0.0...v6.0.1) (2021-12-06)
### Bug Fixes
* **types:** add types.d.ts to package.files ([#431](https://github.com/netflix/pollyjs/issues/431)) ([113ee89](https://github.com/netflix/pollyjs/commit/113ee898bcf0467c5c48c15b53fc9198e2e91cb1))
# [6.0.0](https://github.com/netflix/pollyjs/compare/v5.2.0...v6.0.0) (2021-11-30)
* feat!: Cleanup adapter and persister APIs (#429) ([06499fc](https://github.com/netflix/pollyjs/commit/06499fc2d85254b3329db2bec770d173ed32bca0)), closes [#429](https://github.com/netflix/pollyjs/issues/429)
* feat!: Improve logging and add logLevel (#427) ([bef3ee3](https://github.com/netflix/pollyjs/commit/bef3ee39f71dfc2fa4dbeb522dfba16d01243e9f)), closes [#427](https://github.com/netflix/pollyjs/issues/427)
* chore!: Upgrade package dependencies (#421) ([dd23334](https://github.com/netflix/pollyjs/commit/dd23334fa9b64248e4c49c3616237bdc2f12f682)), closes [#421](https://github.com/netflix/pollyjs/issues/421)
* feat!: Use base64 instead of hex encoding for binary data (#420) ([6bb9b36](https://github.com/netflix/pollyjs/commit/6bb9b36522d73f9c079735d9006a12376aee39ea)), closes [#420](https://github.com/netflix/pollyjs/issues/420)
* feat(ember)!: Upgrade to ember octane (#415) ([8559ef8](https://github.com/netflix/pollyjs/commit/8559ef8c600aefaec629870eac5f5c8953e18b16)), closes [#415](https://github.com/netflix/pollyjs/issues/415)
### BREAKING CHANGES
* - Adapter
- `passthroughRequest` renamed to `onFetchResponse`
- `respondToRequest` renamed to `onRespond`
- Persister
- `findRecording` renamed to `onFindRecording`
- `saveRecording` renamed to `onSaveRecording`
- `deleteRecording` renamed to `onDeleteRecording`
* The `logging` configuration option has now been replaced with `logLevel`. This allows for more fine-grain control over what should be logged as well as silencing logs altogether.
* Recording file name will no longer have trailing dashes
* Use the standard `encoding` field on the generated har file instead of `_isBinary` and use `base64` encoding instead of `hex` to reduce the payload size.
* @pollyjs dependencies have been moved to peer dependencies
## [5.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v5.1.0...v5.1.1) (2021-06-02)
### Bug Fixes
* Handle failed arraybuffer instanceof checks ([#393](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/issues/393)) ([247be0a](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/247be0a))
# [5.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v5.0.2...v5.1.0) (2020-12-12)
**Note:** Version bump only for package @pollyjs/adapter-fetch
# [5.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v4.3.0...v5.0.0) (2020-06-23)
### Bug Fixes
* **adapter-fetch:** Add statusText to the response ([#341](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/issues/341)) ([0d45953](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/0d45953))
# [4.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v4.2.1...v4.3.0) (2020-05-18)
### Features
* **adapter-fetch:** Add support for handling binary data ([#332](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/issues/332)) ([111bebf](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/111bebf))
* **adapter-xhr:** Add support for handling binary data ([#333](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/issues/333)) ([48ea1d7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/48ea1d7))
## [4.2.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v4.2.0...v4.2.1) (2020-04-30)
**Note:** Version bump only for package @pollyjs/adapter-fetch
# [4.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v4.0.4...v4.1.0) (2020-04-23)
### Bug Fixes
* Improve abort handling ([#320](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/issues/320)) ([cc46bb4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/cc46bb4))
## [4.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v4.0.3...v4.0.4) (2020-03-21)
### Bug Fixes
* Deprecates adapter & persister `name` in favor of `id` ([#310](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/issues/310)) ([41dd093](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/41dd093))
## [4.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v4.0.1...v4.0.2) (2020-01-29)
**Note:** Version bump only for package @pollyjs/adapter-fetch
# [4.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v3.0.2...v4.0.0) (2020-01-13)
### Bug Fixes
* **core:** Disconnect from all adapters when `pause` is called ([#291](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/issues/291)) ([5c655bf](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/5c655bf))
### BREAKING CHANGES
* **core:** Calling `polly.pause()` will now disconnect from all connected adapters instead of setting the mode to passthrough. Calling `polly.play()` will reconnect to the disconnected adapters before pause was called.
## [3.0.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v3.0.0...v3.0.1) (2019-12-25)
### Bug Fixes
* **adapter-fetch:** Fix "failed to construct Request" issue ([#287](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/issues/287)) ([d17ab9b](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/d17ab9b)), closes [#286](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/issues/286)
# [3.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v2.7.0...v3.0.0) (2019-12-18)
**Note:** Version bump only for package @pollyjs/adapter-fetch
## [2.6.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v2.6.2...v2.6.3) (2019-09-30)
### Bug Fixes
* use watch strategy ([#236](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/issues/236)) ([5b4edf3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/5b4edf3))
* **adapter-fetch:** Correctly handle Request instance passed into fetch ([#259](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/issues/259)) ([593ecb9](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/593ecb9))
## [2.6.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v2.6.1...v2.6.2) (2019-08-05)
### Features
* Adds an in-memory persister to test polly internals ([#237](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/issues/237)) ([5a6fda6](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/5a6fda6))
## [2.6.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v2.6.0...v2.6.1) (2019-08-01)
**Note:** Version bump only for package @pollyjs/adapter-fetch
# [2.6.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v2.5.0...v2.6.0) (2019-07-17)
### Bug Fixes
* **adapter-fetch:** Handle `Request` objects as URLs ([#220](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/issues/220)) ([bb28d54](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/bb28d54))
### Features
* PollyError and improved adapter error handling ([#234](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/issues/234)) ([23a2127](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/23a2127))
# [2.5.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v2.4.0...v2.5.0) (2019-06-06)
**Note:** Version bump only for package @pollyjs/adapter-fetch
# [2.4.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v2.3.2...v2.4.0) (2019-04-27)
### Features
* **core:** Improved control flow with `times` and `stopPropagation` ([#202](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-fetch/issues/202)) ([2c8231e](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/2c8231e))
## [2.3.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v2.3.0...v2.3.1) (2019-03-06)
### Bug Fixes
* **adapter-fetch:** Correctly handle key/value pairs headers ([dc0323d](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/dc0323d))
# [2.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v2.2.0...v2.3.0) (2019-02-27)
### Features
* **core:** Filter requests matched by a route handler ([#189](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-fetch/issues/189)) ([5d57c32](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/5d57c32))
# [2.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v2.1.0...v2.2.0) (2019-02-20)
**Note:** Version bump only for package @pollyjs/adapter-fetch
# [2.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v2.0.0...v2.1.0) (2019-02-04)
**Note:** Version bump only for package @pollyjs/adapter-fetch
# [2.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v1.4.2...v2.0.0) (2019-01-29)
### Features
* Simplify adapter implementation ([#154](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-fetch/issues/154)) ([12c8601](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/12c8601))
### BREAKING CHANGES
* Changes to the base adapter implementation and external facing API
## [1.4.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v1.4.1...v1.4.2) (2019-01-16)
**Note:** Version bump only for package @pollyjs/adapter-fetch
## [1.4.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v1.4.0...v1.4.1) (2018-12-13)
**Note:** Version bump only for package @pollyjs/adapter-fetch
# [1.4.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v1.3.2...v1.4.0) (2018-12-07)
### Bug Fixes
* **adapter-fetch:** Deprecate usage in Node in favor of node-http ([#146](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-fetch/issues/146)) ([001ccdd](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/001ccdd))
## [1.3.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v1.3.1...v1.3.2) (2018-11-29)
**Note:** Version bump only for package @pollyjs/adapter-fetch
## [1.3.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/v1.2.0...v1.3.1) (2018-11-28)
### Bug Fixes
* Support URL objects ([#139](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-fetch/issues/139)) ([cf0d755](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/cf0d755))
* **core:** Ignore `context` options from being deep merged ([#144](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-fetch/issues/144)) ([2123d83](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/2123d83))
### Features
* Add an onIdentifyRequest hook to allow adapter level serialization ([#140](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-fetch/issues/140)) ([548002c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/548002c))
# 1.2.0 (2018-09-16)
### Bug Fixes
* Allow 204 responses without a body ([#101](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-fetch/issues/101)) ([20b4125](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/20b4125))
* Loosen up global XHR native check ([#69](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-fetch/issues/69)) ([79cdd96](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/79cdd96))
### Features
* Fetch adapter support for `context` provided via adapterOptions ([#66](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-fetch/issues/66)) ([82ebd09](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/82ebd09))
## [1.0.5](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/@pollyjs/adapter-fetch@1.0.4...@pollyjs/adapter-fetch@1.0.5) (2018-08-22)
### Bug Fixes
* Allow 204 responses without a body ([#101](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-fetch/issues/101)) ([20b4125](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/20b4125))
## [1.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/@pollyjs/adapter-fetch@1.0.3...@pollyjs/adapter-fetch@1.0.4) (2018-08-12)
**Note:** Version bump only for package @pollyjs/adapter-fetch
## [1.0.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/@pollyjs/adapter-fetch@1.0.2...@pollyjs/adapter-fetch@1.0.3) (2018-08-12)
**Note:** Version bump only for package @pollyjs/adapter-fetch
## [1.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/@pollyjs/adapter-fetch@1.0.1...@pollyjs/adapter-fetch@1.0.2) (2018-08-09)
**Note:** Version bump only for package @pollyjs/adapter-fetch
## [1.0.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/compare/@pollyjs/adapter-fetch@1.0.0...@pollyjs/adapter-fetch@1.0.1) (2018-07-26)
**Note:** Version bump only for package @pollyjs/adapter-fetch
# 1.0.0 (2018-07-20)
### Bug Fixes
* Loosen up global XHR native check ([#69](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-fetch/issues/69)) ([79cdd96](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/79cdd96))
### Features
* Fetch adapter support for `context` provided via adapterOptions ([#66](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-fetch/issues/66)) ([82ebd09](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch/commit/82ebd09))
================================================
FILE: packages/@pollyjs/adapter-fetch/LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Netflix Inc and @pollyjs contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: packages/@pollyjs/adapter-fetch/README.md
================================================
Record, Replay, and Stub HTTP Interactions
[](https://travis-ci.com/Netflix/pollyjs)
[](https://badge.fury.io/js/%40pollyjs%2Fadapter-fetch)
[](http://www.apache.org/licenses/LICENSE-2.0)
The `@pollyjs/adapter-fetch` package provides a fetch adapter that wraps the
global fetch method for seamless recording and replaying of requests.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/adapter-fetch -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/adapter-fetch -D
```
## Documentation
Check out the [Fetch Adapter](https://netflix.github.io/pollyjs/#/adapters/fetch)
documentation for more details.
## Usage
```js
import { Polly } from '@pollyjs/core';
import FetchAdapter from '@pollyjs/adapter-fetch';
Polly.register(FetchAdapter);
new Polly('', {
adapters: ['fetch']
});
```
## License
Copyright (c) 2018 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
================================================
FILE: packages/@pollyjs/adapter-fetch/package.json
================================================
{
"name": "@pollyjs/adapter-fetch",
"version": "6.0.7",
"description": "Fetch adapter for @pollyjs",
"main": "dist/cjs/pollyjs-adapter-fetch.js",
"module": "dist/es/pollyjs-adapter-fetch.js",
"browser": "dist/umd/pollyjs-adapter-fetch.js",
"types": "types.d.ts",
"files": [
"src",
"dist",
"types.d.ts"
],
"repository": "https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch",
"license": "Apache-2.0",
"contributors": [
{
"name": "Jason Mitchell",
"email": "jason.mitchell.w@gmail.com"
},
{
"name": "Offir Golan",
"email": "offirgolan@gmail.com"
}
],
"keywords": [
"polly",
"pollyjs",
"record",
"replay",
"fetch",
"adapter"
],
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "rollup -c ../../../scripts/rollup/default.config.js",
"test:build": "rollup -c rollup.config.test.js",
"test:build:watch": "rollup -c rollup.config.test.js -w",
"build:watch": "yarn build -w",
"watch-all": "npm-run-all --parallel build:watch test:build:watch"
},
"dependencies": {
"@pollyjs/adapter": "^6.0.6",
"@pollyjs/utils": "^6.0.6",
"to-arraybuffer": "^1.0.1"
},
"devDependencies": {
"@pollyjs/core": "^6.0.6",
"@pollyjs/persister-local-storage": "^6.0.6",
"@pollyjs/persister-rest": "^6.0.6",
"rollup": "^1.14.6"
}
}
================================================
FILE: packages/@pollyjs/adapter-fetch/rollup.config.test.js
================================================
import createBrowserTestConfig from '../../../scripts/rollup/browser.test.config';
export default [createBrowserTestConfig()];
================================================
FILE: packages/@pollyjs/adapter-fetch/src/index.js
================================================
import Adapter from '@pollyjs/adapter';
import { cloneArrayBuffer, isBufferUtf8Representable } from '@pollyjs/utils';
import { Buffer } from 'buffer/';
import bufferToArrayBuffer from 'to-arraybuffer';
import serializeHeaders from './utils/serializer-headers';
const { defineProperty } = Object;
const IS_STUBBED = Symbol();
const ABORT_HANDLER = Symbol();
const REQUEST_ARGUMENTS = Symbol();
export default class FetchAdapter extends Adapter {
static get id() {
return 'fetch';
}
get defaultOptions() {
return {
context: global
};
}
onConnect() {
const { context } = this.options;
['fetch', 'Request', 'Response', 'Headers'].forEach((key) =>
this.assert(`${key} global not found.`, !!(context && context[key]))
);
this.assert(
'Running concurrent fetch adapters is unsupported, stop any running Polly instances.',
!context.fetch[IS_STUBBED] && !context.Request[IS_STUBBED]
);
this.nativeFetch = context.fetch;
this.NativeRequest = context.Request;
const NativeRequest = this.NativeRequest;
/*
Patch the Request constructor so we can store all the passed in options.
This allows us to access the `body` directly instead of having to do
`await req.blob()` as well as not having to hard code each option we want
to extract from the Request instance.
*/
context.Request = function Request(url, options) {
const request = new NativeRequest(url, options);
let args;
options = options || {};
/*
The Request constructor can receive another Request instance as
the first argument so we use its arguments and merge it with the
new options.
*/
if (typeof url === 'object' && url[REQUEST_ARGUMENTS]) {
const reqArgs = url[REQUEST_ARGUMENTS];
args = { ...reqArgs, options: { ...reqArgs.options, ...options } };
} else {
args = { url, options };
}
defineProperty(request, REQUEST_ARGUMENTS, { value: args });
// Override the clone method to use our overridden constructor
request.clone = function clone() {
return new context.Request(request);
};
return request;
};
defineProperty(context.Request, IS_STUBBED, { value: true });
context.fetch = (url, options = {}) => {
let respond;
// Support Request object
if (typeof url === 'object' && url[REQUEST_ARGUMENTS]) {
const req = url;
const reqArgs = req[REQUEST_ARGUMENTS];
url = reqArgs.url;
options = { ...reqArgs.options, ...options };
// If a body exists in the Request instance, mimic reading the body
if ('body' in reqArgs.options) {
defineProperty(req, 'bodyUsed', { value: true });
}
}
const promise = new Promise((resolve, reject) => {
respond = ({ response, error }) => {
if (error) {
reject(error);
} else {
resolve(response);
}
};
});
this.handleRequest({
url,
method: options.method || 'GET',
headers: serializeHeaders(new context.Headers(options.headers)),
body: options.body,
requestArguments: { options, respond }
});
return promise;
};
defineProperty(context.fetch, IS_STUBBED, { value: true });
}
onDisconnect() {
const { context } = this.options;
context.fetch = this.nativeFetch;
context.Request = this.NativeRequest;
this.nativeFetch = null;
this.NativeRequest = null;
}
onRequest(pollyRequest) {
const {
options: { signal }
} = pollyRequest.requestArguments;
if (signal) {
if (signal.aborted) {
pollyRequest.abort();
} else {
pollyRequest[ABORT_HANDLER] = () => pollyRequest.abort();
signal.addEventListener('abort', pollyRequest[ABORT_HANDLER]);
}
}
}
async onFetchResponse(pollyRequest) {
const { context } = this.options;
const { options } = pollyRequest.requestArguments;
const response = await this.nativeFetch.apply(context, [
pollyRequest.url,
{
...options,
method: pollyRequest.method,
headers: pollyRequest.headers,
body: pollyRequest.body
}
]);
let arrayBuffer = await response.arrayBuffer();
/*
If the returned array buffer is not an instance of the global ArrayBuffer,
clone it in order to pass Buffer.from's instanceof check. This can happen
when using this adapter with a different context.
https://github.com/feross/buffer/issues/289
*/
if (
arrayBuffer &&
!(arrayBuffer instanceof ArrayBuffer) &&
'byteLength' in arrayBuffer
) {
arrayBuffer = cloneArrayBuffer(arrayBuffer);
}
const buffer = Buffer.from(arrayBuffer);
const isBinaryBuffer = !isBufferUtf8Representable(buffer);
return {
statusCode: response.status,
headers: serializeHeaders(response.headers),
body: buffer.toString(isBinaryBuffer ? 'base64' : 'utf8'),
encoding: isBinaryBuffer ? 'base64' : undefined
};
}
onRespond(pollyRequest, error) {
const {
context: { Response }
} = this.options;
const {
respond,
options: { signal }
} = pollyRequest.requestArguments;
if (signal && pollyRequest[ABORT_HANDLER]) {
signal.removeEventListener('abort', pollyRequest[ABORT_HANDLER]);
}
if (pollyRequest.aborted) {
respond({
error: new DOMException('The user aborted a request.', 'AbortError')
});
return;
}
if (error) {
respond({ error });
return;
}
const { absoluteUrl, response: pollyResponse } = pollyRequest;
const { statusCode, body, encoding } = pollyResponse;
let responseBody = body;
if (statusCode === 204 && responseBody === '') {
responseBody = null;
} else if (encoding) {
responseBody = bufferToArrayBuffer(Buffer.from(body, encoding));
}
const response = new Response(responseBody, {
status: statusCode,
statusText: pollyResponse.statusText,
headers: pollyResponse.headers
});
/*
Response does not allow `url` to be set manually (either via the
constructor or assignment) so force the url property via `defineProperty`.
*/
defineProperty(response, 'url', { value: absoluteUrl });
respond({ response });
}
}
================================================
FILE: packages/@pollyjs/adapter-fetch/src/utils/serializer-headers.js
================================================
/**
* Serialize a Headers instance into a pojo since it cannot be stringified.
* @param {*} headers
*/
export default function serializeHeaders(headers) {
if (headers && typeof headers.forEach === 'function') {
const serializedHeaders = {};
headers.forEach((value, key) => (serializedHeaders[key] = value));
return serializedHeaders;
}
return headers || {};
}
================================================
FILE: packages/@pollyjs/adapter-fetch/tests/integration/adapter-test.js
================================================
import { Polly, setupMocha as setupPolly } from '@pollyjs/core';
import { URL } from '@pollyjs/utils';
import setupFetchRecord from '@pollyjs-tests/helpers/setup-fetch-record';
import adapterTests from '@pollyjs-tests/integration/adapter-tests';
import adapterPollyTests from '@pollyjs-tests/integration/adapter-polly-tests';
import adapterBrowserTests from '@pollyjs-tests/integration/adapter-browser-tests';
import adapterIdentifierTests from '@pollyjs-tests/integration/adapter-identifier-tests';
import { Buffer } from 'buffer/';
import FetchAdapter from '../../src';
import pollyConfig from '../utils/polly-config';
class MockRequest {}
class MockResponse {}
class MockHeaders {}
describe('Integration | Fetch Adapter', function () {
setupPolly.beforeEach(pollyConfig);
setupFetchRecord();
setupPolly.afterEach();
adapterTests();
adapterPollyTests();
adapterBrowserTests();
adapterIdentifierTests();
it('should support URL instances', async function () {
const { server } = this.polly;
server.any(this.recordUrl()).intercept((_, res) => res.sendStatus(200));
const res = await this.fetch(new URL(this.recordUrl()));
expect(res.status).to.equal(200);
});
it('should support array of key/value pair headers', async function () {
const { server } = this.polly;
let headers;
server
.any(this.recordUrl())
.on('request', (req) => {
headers = req.headers;
})
.intercept((_, res) => res.sendStatus(200));
const res = await this.fetchRecord({
headers: [['Content-Type', 'application/json']]
});
expect(res.status).to.equal(200);
expect(headers).to.deep.equal({ 'content-type': 'application/json' });
});
it('should handle aborting a request', async function () {
const { server } = this.polly;
const controller = new AbortController();
let abortEventCalled = false;
let error;
server
.any(this.recordUrl())
.on('request', () => controller.abort())
.on('abort', () => (abortEventCalled = true))
.intercept((_, res) => {
res.sendStatus(200);
});
try {
await this.fetchRecord({ signal: controller.signal });
} catch (e) {
error = e;
}
expect(abortEventCalled).to.equal(true);
expect(error.message).to.contain('The user aborted a request.');
});
it('should handle immediately aborting a request', async function () {
const { server } = this.polly;
const controller = new AbortController();
let abortEventCalled = false;
let error;
server
.any(this.recordUrl())
.on('abort', () => (abortEventCalled = true))
.intercept((_, res) => {
res.sendStatus(200);
});
try {
const promise = this.fetchRecord({ signal: controller.signal });
controller.abort();
await promise;
} catch (e) {
error = e;
}
expect(abortEventCalled).to.equal(true);
expect(error.message).to.contain('The user aborted a request.');
});
it('should be able to download binary content', async function () {
const fetch = async () =>
Buffer.from(
await this.fetch('/assets/32x32.png').then((res) => res.arrayBuffer())
);
this.polly.disconnectFrom(FetchAdapter);
const nativeResponseBuffer = await fetch();
this.polly.connectTo(FetchAdapter);
const recordedResponseBuffer = await fetch();
const { recordingName, config } = this.polly;
await this.polly.stop();
this.polly = new Polly(recordingName, config);
this.polly.replay();
const replayedResponseBuffer = await fetch();
expect(nativeResponseBuffer.equals(recordedResponseBuffer)).to.equal(true);
expect(recordedResponseBuffer.equals(replayedResponseBuffer)).to.equal(
true
);
expect(nativeResponseBuffer.equals(replayedResponseBuffer)).to.equal(true);
});
it('should return status text', async function () {
const { server } = this.polly;
server.any(this.recordUrl()).intercept((_, res) => res.sendStatus(200));
const res = await this.fetch(new Request(this.recordUrl()));
expect(res.statusText).to.equal('OK');
});
describe('Request', function () {
it('should support Request objects', async function () {
const { server } = this.polly;
server.any(this.recordUrl()).intercept((_, res) => res.sendStatus(200));
const res = await this.fetch(new Request(this.recordUrl()));
expect(res.status).to.equal(200);
});
it('should set bodyUsed to true if a body is present', async function () {
const { server } = this.polly;
const request = new Request('/', { method: 'POST', body: '{}' });
server.any().intercept((_, res) => res.sendStatus(200));
expect(request.bodyUsed).to.equal(false);
await this.fetch(request);
expect(request.bodyUsed).to.equal(true);
});
it('should not set bodyUsed to true if a body is not present', async function () {
const { server } = this.polly;
const request = new Request('/');
server.any().intercept((_, res) => res.sendStatus(200));
expect(request.bodyUsed).to.equal(false);
await this.fetch(request);
expect(request.bodyUsed).to.equal(false);
});
function testRequestOptions(createRequest, options) {
return async function () {
const { server } = this.polly;
let receivedOptions;
server.any().intercept((req, res) => {
receivedOptions = req.requestArguments.options;
res.sendStatus(200);
});
const res = await this.fetch(createRequest());
expect(res.status).to.equal(200);
expect(options).to.deep.equal(receivedOptions);
};
}
it(
'should handle no options',
testRequestOptions(() => new Request('/'), {})
);
it(
'should handle simple options',
testRequestOptions(
() =>
new Request('/', { method: 'POST', body: '{}', cache: 'no-cache' }),
{ method: 'POST', body: '{}', cache: 'no-cache' }
)
);
it(
'should handle a cloned request',
testRequestOptions(
() => new Request('/', { method: 'POST', body: '{}' }).clone(),
{ method: 'POST', body: '{}' }
)
);
it(
'should handle a request instance',
testRequestOptions(
() => new Request(new Request('/', { method: 'POST', body: '{}' })),
{ method: 'POST', body: '{}' }
)
);
it(
'should handle a request instance with overrides',
testRequestOptions(
() =>
new Request(new Request('/', { method: 'POST', body: '{}' }), {
method: 'PATCH',
headers: { foo: 'bar' }
}),
{ method: 'PATCH', headers: { foo: 'bar' }, body: '{}' }
)
);
});
});
describe('Integration | Fetch Adapter | Init', function () {
describe('Context', function () {
it(`should assign context's fetch as the native fetch and Request as the native Request`, async function () {
const polly = new Polly('context', { adapters: [] });
const fetch = () => {};
const adapterOptions = {
fetch: {
context: {
fetch,
Request: MockRequest,
Response: MockResponse,
Headers: MockHeaders
}
}
};
polly.configure({ adapters: [FetchAdapter], adapterOptions });
expect(polly.adapters.get('fetch').nativeFetch).to.equal(fetch);
expect(polly.adapters.get('fetch').nativeFetch).to.not.equal(
adapterOptions.fetch.context.fetch
);
expect(polly.adapters.get('fetch').NativeRequest).to.equal(MockRequest);
expect(polly.adapters.get('fetch').NativeRequest).to.not.equal(
adapterOptions.fetch.context.Request
);
expect(function () {
polly.configure({
adapterOptions: { fetch: { context: {} } }
});
}).to.throw(/fetch global not found/);
await polly.stop();
});
it('should throw when context, fetch, Request, Response, and Headers are undefined', async function () {
const polly = new Polly('context', { adapters: [] });
polly.configure({
adapters: [FetchAdapter]
});
expect(function () {
polly.configure({
adapterOptions: { fetch: { context: undefined } }
});
}).to.throw(/fetch global not found/);
expect(function () {
polly.configure({
adapterOptions: {
fetch: {
context: {
fetch: undefined,
Request: MockRequest,
Response: MockResponse,
Headers: MockHeaders
}
}
}
});
}).to.throw(/fetch global not found/);
expect(function () {
polly.configure({
adapterOptions: {
fetch: {
context: {
fetch() {},
Request: undefined,
Response: MockResponse,
Headers: MockHeaders
}
}
}
});
}).to.throw(/Request global not found/);
expect(function () {
polly.configure({
adapterOptions: {
fetch: {
context: {
fetch() {},
Request: MockRequest,
Response: undefined,
Headers: MockHeaders
}
}
}
});
}).to.throw(/Response global not found/);
expect(function () {
polly.configure({
adapterOptions: {
fetch: {
context: {
fetch() {},
Request: MockRequest,
Response: MockResponse,
Headers: undefined
}
}
}
});
}).to.throw(/Headers global not found/);
await polly.stop();
});
});
describe('Concurrency', function () {
it('should prevent concurrent fetch adapter instances', async function () {
const one = new Polly('one');
const two = new Polly('two');
one.connectTo(FetchAdapter);
expect(function () {
two.connectTo(FetchAdapter);
}).to.throw(/Running concurrent fetch adapters is unsupported/);
await one.stop();
await two.stop();
});
it('should allow you to register new instances once stopped', async function () {
const one = new Polly('one');
const two = new Polly('two');
one.connectTo(FetchAdapter);
await one.stop();
expect(function () {
two.connectTo(FetchAdapter);
}).to.not.throw();
await one.stop();
await two.stop();
});
});
});
================================================
FILE: packages/@pollyjs/adapter-fetch/tests/integration/persister-local-storage-test.js
================================================
import { setupMocha as setupPolly } from '@pollyjs/core';
import LocalStoragePersister from '@pollyjs/persister-local-storage';
import setupFetchRecord from '@pollyjs-tests/helpers/setup-fetch-record';
import setupPersister from '@pollyjs-tests/helpers/setup-persister';
import persisterTests from '@pollyjs-tests/integration/persister-tests';
import pollyConfig from '../utils/polly-config';
describe('Integration | Local Storage Persister', function () {
setupPolly.beforeEach({
...pollyConfig,
persister: LocalStoragePersister
});
setupFetchRecord();
setupPersister();
setupPolly.afterEach();
persisterTests();
});
================================================
FILE: packages/@pollyjs/adapter-fetch/tests/integration/persister-rest-test.js
================================================
import { setupMocha as setupPolly } from '@pollyjs/core';
import RESTPersister from '@pollyjs/persister-rest';
import setupFetchRecord from '@pollyjs-tests/helpers/setup-fetch-record';
import setupPersister from '@pollyjs-tests/helpers/setup-persister';
import persisterTests from '@pollyjs-tests/integration/persister-tests';
import pollyConfig from '../utils/polly-config';
describe('Integration | REST Persister', function () {
setupPolly.beforeEach({
...pollyConfig,
persister: RESTPersister,
persisterOptions: {
rest: { host: '' }
}
});
setupFetchRecord();
setupPersister();
setupPolly.afterEach();
persisterTests();
});
================================================
FILE: packages/@pollyjs/adapter-fetch/tests/integration/server-test.js
================================================
import { setupMocha as setupPolly } from '@pollyjs/core';
import { PollyError } from '@pollyjs/utils';
import pollyConfig from '../utils/polly-config';
describe('Integration | Server', function () {
setupPolly(pollyConfig);
it('calls all intercept handlers', async function () {
const { server } = this.polly;
server.any().intercept(async (_, res) => {
await server.timeout(5);
res.status(200);
});
server.any().intercept(async (_, res) => {
await server.timeout(5);
res.setHeader('x-foo', 'bar');
});
server.get('/ping').intercept((_, res) => res.json({ foo: 'bar' }));
const res = await fetch('/ping');
const json = await res.json();
expect(res.status).to.equal(200);
expect(res.headers.get('x-foo')).to.equal('bar');
expect(json).to.deep.equal({ foo: 'bar' });
});
it('breaks out of intercepts when using the interceptor API', async function () {
const { server } = this.polly;
let numIntercepts = 0;
server.namespace('/api/db/ping', () => {
server.any().intercept((_, res) => {
numIntercepts++;
res.status(200);
});
server.any().intercept((_, __, interceptor) => {
numIntercepts++;
interceptor.passthrough();
});
server.get().intercept((_, res) => {
numIntercepts++;
res.status(201);
});
});
expect((await fetch('/api/db/ping')).status).to.equal(404);
expect(numIntercepts).to.equal(2);
});
describe('API', function () {
it('.configure() - merges all configs', async function () {
const { server } = this.polly;
let config;
server.any().configure({ foo: 'foo' });
server.any().configure({ bar: 'bar' });
server
.get('/ping')
.configure({ foo: 'baz' })
.intercept((req, res) => {
config = req.config;
res.sendStatus(200);
});
expect((await fetch('/ping')).status).to.equal(200);
expect(config).to.include({ foo: 'baz', bar: 'bar' });
});
it('.configure() - should throw when trying to override certain options', async function () {
const { server } = this.polly;
// The following options cannot be overridden on a per request basis
[
'mode',
'adapters',
'adapterOptions',
'persister',
'persisterOptions'
].forEach((key) =>
expect(() => server.any().configure({ [key]: 'foo' })).to.throw(
PollyError,
/Invalid configuration option/
)
);
});
it('.recordingName()', async function () {
const { server } = this.polly;
let recordingName;
server
.get('/ping')
.recordingName('Override')
.intercept((req, res) => {
recordingName = req.recordingName;
res.sendStatus(200);
});
expect((await fetch('/ping')).status).to.equal(200);
expect(recordingName).to.equal('Override');
});
it('.recordingName() - should reset when called with no arguments', async function () {
const { server } = this.polly;
let recordingName;
server.any().recordingName('Override');
server
.get('/ping')
.recordingName()
.intercept((req, res) => {
recordingName = req.recordingName;
res.sendStatus(200);
});
expect((await fetch('/ping')).status).to.equal(200);
expect(recordingName).to.not.equal('Override');
});
it('.filter()', async function () {
const { server } = this.polly;
server
.get('/ping')
.filter((req) => req.query.num === '1')
.intercept((req, res) => res.sendStatus(201));
server
.get('/ping')
.filter((req) => req.query.num === '2')
.intercept((req, res) => res.sendStatus(202));
expect((await fetch('/ping?num=1')).status).to.equal(201);
expect((await fetch('/ping?num=2')).status).to.equal(202);
});
it('.filter() + events', async function () {
const { server } = this.polly;
let num;
server
.get('/ping')
.filter((req) => req.query.num === '1')
.on('request', (req) => (num = req.query.num))
.intercept((req, res) => res.sendStatus(201));
server
.get('/ping')
.filter((req) => req.query.num === '2')
.on('request', (req) => (num = req.query.num))
.intercept((req, res) => res.sendStatus(202));
expect((await fetch('/ping?num=1')).status).to.equal(201);
expect(num).to.equal('1');
});
it('.filter() - multiple', async function () {
const { server } = this.polly;
server
.get('/ping')
.filter((req) => req.query.foo === 'foo')
.filter((req) => req.query.bar === 'bar')
.intercept((req, res) => res.sendStatus(201));
server
.get('/ping')
.filter((req) => req.query.foo === 'foo')
.filter((req) => req.query.baz === 'baz')
.intercept((req, res) => res.sendStatus(202));
expect((await fetch('/ping?foo=foo&bar=bar')).status).to.equal(201);
expect((await fetch('/ping?foo=foo&baz=baz')).status).to.equal(202);
});
it('.filter() - can access params', async function () {
const { server } = this.polly;
let id;
server
.get('/ping/:id')
.filter((req) => {
id = req.params.id;
return true;
})
.intercept((req, res) => res.sendStatus(201));
expect((await fetch('/ping/1')).status).to.equal(201);
expect(id).to.equal('1');
});
it('.filter() - should throw when not passed a function', async function () {
const { server } = this.polly;
expect(() => server.any().filter()).to.throw(
PollyError,
/Invalid filter callback provided/
);
});
it('.times()', async function () {
const { server } = this.polly;
let callCount = 0;
server
.get('/ping')
.times(1)
.on('request', () => callCount++)
.times()
.intercept((req, res) => res.sendStatus(200));
expect((await fetch('/ping')).status).to.equal(200);
expect(callCount).to.equal(1);
expect((await fetch('/ping')).status).to.equal(200);
expect(callCount).to.equal(1);
});
it('.intercept(_, { times }) & .on(_, { times })', async function () {
const { server } = this.polly;
let callCount = 0;
const handler = server
.get('/ping')
.on('request', () => callCount++, { times: 1 })
.intercept((req, res) => res.sendStatus(200), { times: 2 });
expect((await fetch('/ping')).status).to.equal(200);
expect(callCount).to.equal(1);
expect((await fetch('/ping')).status).to.equal(200);
expect(callCount).to.equal(1);
expect(handler.has('intercept')).to.be.false;
});
});
describe('Events & Middleware', function () {
it('event: request', async function () {
const { server } = this.polly;
let requestCalled = false;
server
.get('/ping')
.intercept((req, res) => {
expect(requestCalled).to.be.true;
res.sendStatus(200);
})
.on('request', (req) => {
expect(requestCalled).to.be.false;
// Validate that we can modify the request
req.body = 'test';
expect(req.body).to.equal('test');
requestCalled = true;
});
expect((await fetch('/ping')).status).to.equal(200);
expect(requestCalled).to.be.true;
});
it('event: beforeResponse', async function () {
const { server } = this.polly;
let beforeResponseCalled = false;
server
.get('/ping')
.intercept((req, res) => {
expect(beforeResponseCalled).to.be.false;
res.sendStatus(200);
})
.on('beforeResponse', (req, res) => {
expect(beforeResponseCalled).to.be.false;
expect(res.statusCode).to.equal(200);
res.sendStatus(201);
beforeResponseCalled = true;
});
expect((await fetch('/ping')).status).to.equal(201);
expect(beforeResponseCalled).to.be.true;
});
it('event: response', async function () {
const { server } = this.polly;
let responseCalled = false;
server
.get('/ping')
.intercept((req, res) => {
expect(responseCalled).to.be.false;
res.sendStatus(200);
})
.on('response', (req, res) => {
expect(responseCalled).to.be.false;
expect(req.didRespond).to.be.true;
expect(res.statusCode).to.equal(200);
// Validate that the req cant be modified
expect(() => (req.body = 'test')).to.throw(Error);
responseCalled = true;
});
expect((await fetch('/ping')).status).to.equal(200);
expect(responseCalled).to.be.true;
});
it('can register multiple event handlers', async function () {
const { server } = this.polly;
const stack = [];
server
.get('/ping')
.intercept((req, res) => res.sendStatus(200))
.on('request', () => stack.push(1))
.on('request', () => stack.push(2))
.on('beforeResponse', () => stack.push(3))
.on('beforeResponse', () => stack.push(4))
.on('response', () => stack.push(5))
.on('response', () => stack.push(6));
expect((await fetch('/ping')).status).to.equal(200);
expect(stack).to.deep.equal([1, 2, 3, 4, 5, 6]);
});
it('can turn off events', async function () {
const { server } = this.polly;
let requestCalled,
beforeResponseCalled = false;
const handler = server
.get('/ping')
.intercept((req, res) => res.sendStatus(200))
.on('request', () => (requestCalled = true))
.on('beforeResponse', () => (beforeResponseCalled = true));
expect((await fetch('/ping')).status).to.equal(200);
expect(requestCalled).to.be.true;
expect(beforeResponseCalled).to.be.true;
requestCalled = beforeResponseCalled = false;
handler.off('request').off('beforeResponse');
expect((await fetch('/ping')).status).to.equal(200);
expect(requestCalled).to.be.false;
expect(beforeResponseCalled).to.be.false;
});
it('events receive params', async function () {
const { server } = this.polly;
server
.any('/ping')
.on('request', (req) => {
expect(req.params).to.deep.equal({});
})
.on('beforeResponse', (req) => {
expect(req.params).to.deep.equal({});
});
server
.any('/ping/:id')
.on('request', (req) => {
expect(req.params).to.deep.equal({ id: '1' });
})
.on('beforeResponse', (req) => {
expect(req.params).to.deep.equal({ id: '1' });
});
server
.get('/ping/:id/:id2/*path')
.intercept((req, res) => res.sendStatus(200))
.on('request', (req) => {
expect(req.params).to.deep.equal({
id: '1',
id2: '2',
path: 'foo/bar'
});
})
.on('beforeResponse', (req) => {
expect(req.params).to.deep.equal({
id: '1',
id2: '2',
path: 'foo/bar'
});
});
expect((await fetch('/ping/1/2/foo/bar')).status).to.equal(200);
});
it('preserves middleware order', async function () {
const { server } = this.polly;
const requestOrder = [];
const beforeResponseOrder = [];
server
.any()
.on('request', () => {
requestOrder.push(1);
})
.on('beforeResponse', () => {
beforeResponseOrder.push(1);
});
server
.any()
.on('request', () => {
requestOrder.push(2);
})
.on('beforeResponse', () => {
beforeResponseOrder.push(2);
});
server
.any('/ping/:id')
.on('request', async () => {
await server.timeout(5);
requestOrder.push(3);
})
.on('beforeResponse', async () => {
await server.timeout(5);
beforeResponseOrder.push(3);
});
server
.any(['/ping', '/ping/*path'])
.on('request', () => {
requestOrder.push(4);
})
.on('beforeResponse', () => {
beforeResponseOrder.push(4);
});
server
.get('/ping/:id')
.intercept((req, res) => res.sendStatus(200))
.on('request', () => requestOrder.push(5))
.on('beforeResponse', () => beforeResponseOrder.push(5));
expect((await fetch('/ping/1')).status).to.equal(200);
expect(requestOrder).to.deep.equal([1, 2, 3, 4, 5]);
expect(beforeResponseOrder).to.deep.equal([1, 2, 3, 4, 5]);
});
});
describe('Control Flow', function () {
it('can control flow with .times() & .stopPropagation()', async function () {
const { server } = this.polly;
let calledBeforeDelete = false;
let calledAfterDelete = false;
// First call should return the user and not enter the 2nd handler
server
.get('/users/1')
.times(1)
.on('request', (req, e) => {
e.stopPropagation();
calledBeforeDelete = true;
})
.intercept((req, res, interceptor) => {
interceptor.stopPropagation();
res.sendStatus(200);
});
server.delete('/users/1').intercept((req, res) => res.status(204));
// Second call should 404 since the user no longer exists
server
.get('/users/1')
.times(1)
.on('request', () => (calledAfterDelete = true))
.intercept((req, res) => res.sendStatus(404));
expect((await fetch('/users/1')).status).to.equal(200);
expect(calledBeforeDelete).to.be.true;
expect(calledAfterDelete).to.be.false;
calledBeforeDelete = false;
expect((await fetch('/users/1', { method: 'DELETE' })).status).to.equal(
204
);
expect((await fetch('/users/1')).status).to.equal(404);
expect(calledBeforeDelete).to.be.false;
expect(calledAfterDelete).to.be.true;
});
});
});
================================================
FILE: packages/@pollyjs/adapter-fetch/tests/utils/polly-config.js
================================================
import InMemoryPersister from '@pollyjs/persister-in-memory';
import FetchAdapter from '../../src';
export default {
recordFailedRequests: true,
adapters: [FetchAdapter],
persister: InMemoryPersister
};
================================================
FILE: packages/@pollyjs/adapter-fetch/types.d.ts
================================================
import Adapter from '@pollyjs/adapter';
export default class FetchAdapter extends Adapter<{
context?: any;
}> {}
================================================
FILE: packages/@pollyjs/adapter-node-http/.eslintrc.js
================================================
module.exports = {
env: {
browser: false,
node: true
},
overrides: [
{
files: ['tests/jest/**/*.js'],
env: {
browser: true
}
}
]
};
================================================
FILE: packages/@pollyjs/adapter-node-http/CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.6](https://github.com/netflix/pollyjs/compare/v6.0.5...v6.0.6) (2023-07-20)
**Note:** Version bump only for package @pollyjs/adapter-node-http
## [6.0.5](https://github.com/netflix/pollyjs/compare/v6.0.4...v6.0.5) (2022-04-04)
**Note:** Version bump only for package @pollyjs/adapter-node-http
## [6.0.4](https://github.com/netflix/pollyjs/compare/v6.0.3...v6.0.4) (2021-12-10)
**Note:** Version bump only for package @pollyjs/adapter-node-http
## [6.0.3](https://github.com/netflix/pollyjs/compare/v6.0.2...v6.0.3) (2021-12-08)
**Note:** Version bump only for package @pollyjs/adapter-node-http
## [6.0.2](https://github.com/netflix/pollyjs/compare/v6.0.1...v6.0.2) (2021-12-07)
**Note:** Version bump only for package @pollyjs/adapter-node-http
## [6.0.1](https://github.com/netflix/pollyjs/compare/v6.0.0...v6.0.1) (2021-12-06)
### Bug Fixes
* **types:** add types.d.ts to package.files ([#431](https://github.com/netflix/pollyjs/issues/431)) ([113ee89](https://github.com/netflix/pollyjs/commit/113ee898bcf0467c5c48c15b53fc9198e2e91cb1))
# [6.0.0](https://github.com/netflix/pollyjs/compare/v5.2.0...v6.0.0) (2021-11-30)
* feat!: Cleanup adapter and persister APIs (#429) ([06499fc](https://github.com/netflix/pollyjs/commit/06499fc2d85254b3329db2bec770d173ed32bca0)), closes [#429](https://github.com/netflix/pollyjs/issues/429)
* chore!: Upgrade package dependencies (#421) ([dd23334](https://github.com/netflix/pollyjs/commit/dd23334fa9b64248e4c49c3616237bdc2f12f682)), closes [#421](https://github.com/netflix/pollyjs/issues/421)
* feat!: Use base64 instead of hex encoding for binary data (#420) ([6bb9b36](https://github.com/netflix/pollyjs/commit/6bb9b36522d73f9c079735d9006a12376aee39ea)), closes [#420](https://github.com/netflix/pollyjs/issues/420)
* feat(ember)!: Upgrade to ember octane (#415) ([8559ef8](https://github.com/netflix/pollyjs/commit/8559ef8c600aefaec629870eac5f5c8953e18b16)), closes [#415](https://github.com/netflix/pollyjs/issues/415)
### Features
* **adapter-node-http:** Upgrade nock to v13 ([#424](https://github.com/netflix/pollyjs/issues/424)) ([2d5b59e](https://github.com/netflix/pollyjs/commit/2d5b59ee0c33ea53a64321249246fcae0a616a3f))
### BREAKING CHANGES
* - Adapter
- `passthroughRequest` renamed to `onFetchResponse`
- `respondToRequest` renamed to `onRespond`
- Persister
- `findRecording` renamed to `onFindRecording`
- `saveRecording` renamed to `onSaveRecording`
- `deleteRecording` renamed to `onDeleteRecording`
* Recording file name will no longer have trailing dashes
* Use the standard `encoding` field on the generated har file instead of `_isBinary` and use `base64` encoding instead of `hex` to reduce the payload size.
* @pollyjs dependencies have been moved to peer dependencies
## [5.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v5.1.0...v5.1.1) (2021-06-02)
**Note:** Version bump only for package @pollyjs/adapter-node-http
# [5.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v5.0.2...v5.1.0) (2020-12-12)
**Note:** Version bump only for package @pollyjs/adapter-node-http
## [5.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v5.0.1...v5.0.2) (2020-12-06)
### Bug Fixes
* **adapter-node-http:** Remove module monkey patching on disconnect ([#369](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/issues/369)) ([0cec43a](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/0cec43a))
# [5.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v4.3.0...v5.0.0) (2020-06-23)
**Note:** Version bump only for package @pollyjs/adapter-node-http
# [4.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v4.2.1...v4.3.0) (2020-05-18)
### Features
* **adapter-xhr:** Add support for handling binary data ([#333](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/issues/333)) ([48ea1d7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/48ea1d7))
## [4.2.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v4.2.0...v4.2.1) (2020-04-30)
### Bug Fixes
* **adapter-node-http:** Improve binary response body handling ([#329](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/issues/329)) ([9466989](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/9466989))
# [4.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v4.1.0...v4.2.0) (2020-04-29)
**Note:** Version bump only for package @pollyjs/adapter-node-http
# [4.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v4.0.4...v4.1.0) (2020-04-23)
### Bug Fixes
* Improve abort handling ([#320](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/issues/320)) ([cc46bb4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/cc46bb4))
## [4.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v4.0.3...v4.0.4) (2020-03-21)
### Bug Fixes
* Deprecates adapter & persister `name` in favor of `id` ([#310](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/issues/310)) ([41dd093](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/41dd093))
* **adapter-node-http:** Bump nock version ([#319](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/issues/319)) ([7d361a6](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/7d361a6))
## [4.0.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v4.0.2...v4.0.3) (2020-01-30)
### Bug Fixes
* **adapter-node-http:** Use requestBodyBuffers to parse body ([#304](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/issues/304)) ([113fec5](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/113fec5))
## [4.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v4.0.1...v4.0.2) (2020-01-29)
**Note:** Version bump only for package @pollyjs/adapter-node-http
# [4.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v3.0.2...v4.0.0) (2020-01-13)
**Note:** Version bump only for package @pollyjs/adapter-node-http
## [3.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v3.0.1...v3.0.2) (2020-01-08)
### Bug Fixes
* **adapter-node-http:** Bump nock version to correctly handle re… ([#289](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/issues/289)) ([8d0ae97](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/8d0ae97)), closes [#278](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/issues/278)
# [3.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v2.7.0...v3.0.0) (2019-12-18)
**Note:** Version bump only for package @pollyjs/adapter-node-http
# [2.7.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v2.6.3...v2.7.0) (2019-11-21)
### Bug Fixes
* **adapter-node-http:** Correctly handle uploading binary data ([#257](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/issues/257)) ([31f0e0a](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/31f0e0a))
### Features
* **adapter-node-http:** Upgrade nock to v11.x ([#273](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/issues/273)) ([5d42cbd](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/5d42cbd))
## [2.6.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v2.6.2...v2.6.3) (2019-09-30)
### Bug Fixes
* use watch strategy ([#236](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/issues/236)) ([5b4edf3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/5b4edf3))
## [2.6.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v2.6.1...v2.6.2) (2019-08-05)
### Features
* Adds an in-memory persister to test polly internals ([#237](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/issues/237)) ([5a6fda6](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/5a6fda6))
## [2.6.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v2.6.0...v2.6.1) (2019-08-01)
**Note:** Version bump only for package @pollyjs/adapter-node-http
# [2.6.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v2.5.0...v2.6.0) (2019-07-17)
### Features
* PollyError and improved adapter error handling ([#234](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/issues/234)) ([23a2127](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/23a2127))
# [2.5.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v2.4.0...v2.5.0) (2019-06-06)
**Note:** Version bump only for package @pollyjs/adapter-node-http
# [2.4.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v2.3.2...v2.4.0) (2019-04-27)
**Note:** Version bump only for package @pollyjs/adapter-node-http
# [2.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v2.2.0...v2.3.0) (2019-02-27)
**Note:** Version bump only for package @pollyjs/adapter-node-http
# [2.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v2.1.0...v2.2.0) (2019-02-20)
### Features
* Add `error` event and improve error handling ([#185](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-node-http/issues/185)) ([3694ebc](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/3694ebc))
# [2.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v2.0.0...v2.1.0) (2019-02-04)
**Note:** Version bump only for package @pollyjs/adapter-node-http
# [2.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v1.4.2...v2.0.0) (2019-01-29)
### Features
* Simplify adapter implementation ([#154](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-node-http/issues/154)) ([12c8601](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/12c8601))
* feat(adapter-node-http): Use `nock` under the hood instead of custom implementation (#166) ([62374f4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/62374f4)), closes [#166](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/issues/166)
### BREAKING CHANGES
* The node-http adapter no longer accepts the `transports` option
* Changes to the base adapter implementation and external facing API
## [1.4.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v1.4.1...v1.4.2) (2019-01-16)
### Bug Fixes
* **adapter-node-http:** Fix unhandled rejection if connection fails ([#160](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-node-http/issues/160)) ([12fcfa7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/12fcfa7))
* **adapter-node-http:** Pause socket on original request ([#162](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-node-http/issues/162)) ([8f0c56c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/8f0c56c))
## [1.4.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v1.4.0...v1.4.1) (2018-12-13)
**Note:** Version bump only for package @pollyjs/adapter-node-http
# [1.4.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/compare/v1.3.2...v1.4.0) (2018-12-07)
### Features
* Node HTTP Adapter ([#128](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-node-http/issues/128)) ([fa059a4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http/commit/fa059a4))
================================================
FILE: packages/@pollyjs/adapter-node-http/LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Netflix Inc and @pollyjs contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: packages/@pollyjs/adapter-node-http/README.md
================================================
Record, Replay, and Stub HTTP Interactions
[](https://travis-ci.com/Netflix/pollyjs)
[](https://badge.fury.io/js/%40pollyjs%2Fadapter-node-http)
[](http://www.apache.org/licenses/LICENSE-2.0)
The `@pollyjs/adapter-node-http` package provides a low level nodejs http request adapter that uses [nock](https://github.com/nock/nock) to patch the [http](https://nodejs.org/api/http.html) and [https](https://nodejs.org/api/https.html) modules in nodejs for seamless recording and replaying of requests.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/adapter-node-http -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/adapter-node-http -D
```
## Documentation
Check out the [Node HTTP Adapter](https://netflix.github.io/pollyjs/#/adapters/node-http)
documentation for more details.
## Usage
```js
import { Polly } from '@pollyjs/core';
import NodeHTTPAdapter from '@pollyjs/adapter-node-http';
Polly.register(NodeHTTPAdapter);
new Polly('', {
adapters: ['node-http']
});
```
## License
Copyright (c) 2018 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
================================================
FILE: packages/@pollyjs/adapter-node-http/package.json
================================================
{
"name": "@pollyjs/adapter-node-http",
"version": "6.0.6",
"description": "Node HTTP adapter for @pollyjs",
"main": "dist/cjs/pollyjs-adapter-node-http.js",
"module": "dist/es/pollyjs-adapter-node-http.js",
"types": "types.d.ts",
"files": [
"src",
"dist",
"types.d.ts"
],
"repository": "https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-node-http",
"license": "Apache-2.0",
"contributors": [
{
"name": "Yasin Uslu",
"email": "a.yasin.uslu@gmail.com"
},
{
"name": "Jason Mitchell",
"email": "jason.mitchell.w@gmail.com"
},
{
"name": "Offir Golan",
"email": "offirgolan@gmail.com"
}
],
"keywords": [
"polly",
"pollyjs",
"record",
"replay",
"http",
"adapter"
],
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "rollup -c",
"test:build": "rollup -c rollup.config.test.js",
"test:build:watch": "rollup -c rollup.config.test.js -w",
"build:watch": "yarn build -w",
"watch-all": "npm-run-all --parallel build:watch test:build:watch"
},
"dependencies": {
"@pollyjs/adapter": "^6.0.6",
"@pollyjs/utils": "^6.0.6",
"lodash-es": "^4.17.21",
"nock": "^13.2.1"
},
"devDependencies": {
"@pollyjs/core": "^6.0.6",
"@pollyjs/persister-fs": "^6.0.6",
"form-data": "^4.0.0",
"get-stream": "^6.0.1",
"node-fetch": "^2.6.6",
"rollup": "^1.14.6"
}
}
================================================
FILE: packages/@pollyjs/adapter-node-http/rollup.config.js
================================================
import createNodeConfig from '../../../scripts/rollup/node.config';
import { external } from './rollup.config.shared';
export default createNodeConfig({ external });
================================================
FILE: packages/@pollyjs/adapter-node-http/rollup.config.shared.js
================================================
export const external = [
'http',
'https',
'url',
'stream',
'timers',
'tty',
'util',
'os'
];
================================================
FILE: packages/@pollyjs/adapter-node-http/rollup.config.test.js
================================================
import createNodeTestConfig from '../../../scripts/rollup/node.test.config';
import createJestTestConfig from '../../../scripts/rollup/jest.test.config';
import { external } from './rollup.config.shared';
const testExternal = [...external, 'fs', 'path'];
export default [
createNodeTestConfig({ external: testExternal }),
createJestTestConfig({ external: testExternal })
];
================================================
FILE: packages/@pollyjs/adapter-node-http/src/index.js
================================================
import http from 'http';
import https from 'https';
import { URL } from 'url';
import { Readable as ReadableStream } from 'stream';
import nock from 'nock';
import {
normalizeClientRequestArgs,
isUtf8Representable,
isContentEncoded
} from 'nock/lib/common';
import Adapter from '@pollyjs/adapter';
import { HTTP_METHODS } from '@pollyjs/utils';
import getUrlFromOptions from './utils/get-url-from-options';
import mergeChunks from './utils/merge-chunks';
import urlToOptions from './utils/url-to-options';
const IS_STUBBED = Symbol();
const ABORT_HANDLER = Symbol();
const REQUEST_ARGUMENTS = new WeakMap();
// nock begins to intercept network requests on import which is not the
// behavior we want, so restore the original behavior right away.
nock.restore();
export default class HttpAdapter extends Adapter {
static get id() {
return 'node-http';
}
onConnect() {
this.assert(
'Running concurrent node-http adapters is unsupported, stop any running Polly instances.',
!http.ClientRequest[IS_STUBBED]
);
this.assert(
'Running nock concurrently with the node-http adapter is unsupported. Run nock.restore() before connecting to this adapter.',
!nock.isActive()
);
this.NativeClientRequest = http.ClientRequest;
this.setupNock();
// Patch methods overridden by nock to add some missing functionality
this.patchOverriddenMethods();
}
onDisconnect() {
this.unpatchOverriddenMethods();
nock.cleanAll();
nock.restore();
this.NativeClientRequest = null;
}
setupNock() {
const adapter = this;
// Make sure there aren't any other interceptors defined
nock.cleanAll();
// Create our interceptor that will match all hosts
const interceptor = nock(/.*/).persist();
HTTP_METHODS.forEach((m) => {
// Add an intercept for each supported HTTP method that will match all paths
interceptor.intercept(/.*/, m).reply(function (_, _body, respond) {
const { req, method } = this;
const { headers } = req;
const parsedArguments = normalizeClientRequestArgs(
...REQUEST_ARGUMENTS.get(req)
);
const url = getUrlFromOptions(parsedArguments.options);
const requestBodyBuffer = Buffer.concat(req.requestBodyBuffers);
const body = isUtf8Representable(requestBodyBuffer)
? requestBodyBuffer.toString('utf8')
: requestBodyBuffer;
adapter.handleRequest({
url,
method,
headers,
body,
requestArguments: { req, body, respond, parsedArguments }
});
});
});
// Activate nock so it can start to intercept all outgoing requests
nock.activate();
}
patchOverriddenMethods() {
const modules = { http, https };
const { ClientRequest } = http;
// Patch the already overridden ClientRequest class so we can get
// access to the original arguments and use them when creating the
// passthrough request.
http.ClientRequest = function _ClientRequest() {
const req = new ClientRequest(...arguments);
REQUEST_ARGUMENTS.set(req, [...arguments]);
return req;
};
// Add an IS_STUBBED boolean so we can check on onConnect if we've already
// patched the necessary methods.
http.ClientRequest[IS_STUBBED] = true;
// Patch http.request, http.get, https.request, and https.get
// to set some default values which nock doesn't properly set.
Object.keys(modules).forEach((moduleName) => {
const module = modules[moduleName];
const { request, get, globalAgent } = module;
this[moduleName] = {
get,
request
};
function parseArgs() {
const args = normalizeClientRequestArgs(...arguments);
if (moduleName === 'https') {
args.options = {
...{ port: 443, protocol: 'https:', _defaultAgent: globalAgent },
...args.options
};
} else {
args.options = {
...{ port: 80, protocol: 'http:' },
...args.options
};
}
return args;
}
module.request = function _request() {
const { options, callback } = parseArgs(...arguments);
return request(options, callback);
};
module.get = function _get() {
const { options, callback } = parseArgs(...arguments);
return get(options, callback);
};
});
}
unpatchOverriddenMethods() {
const modules = { http, https };
Object.keys(modules).forEach((moduleName) => {
const module = modules[moduleName];
module.request = this[moduleName].request;
module.get = this[moduleName].get;
this[moduleName] = undefined;
});
}
onRequest(pollyRequest) {
const { req } = pollyRequest.requestArguments;
if (req.aborted) {
pollyRequest.abort();
} else {
pollyRequest[ABORT_HANDLER] = () => {
if (!pollyRequest.aborted && (req.aborted || req.destroyed)) {
pollyRequest.abort();
}
};
req.once('abort', pollyRequest[ABORT_HANDLER]);
req.once('close', pollyRequest[ABORT_HANDLER]);
}
}
async onFetchResponse(pollyRequest) {
const { parsedArguments } = pollyRequest.requestArguments;
const { method, headers, body } = pollyRequest;
const { options } = parsedArguments;
const request = new this.NativeClientRequest({
...options,
method,
headers: { ...headers },
...urlToOptions(new URL(pollyRequest.url))
});
const chunks = this.getChunksFromBody(body, headers);
const responsePromise = new Promise((resolve, reject) => {
request.once('response', resolve);
request.once('error', reject);
request.once('timeout', reject);
});
// Write the request body
chunks.forEach((chunk) => request.write(chunk));
request.end();
const response = await responsePromise;
const responseBody = await new Promise((resolve, reject) => {
const chunks = [];
response.on('data', (chunk) => chunks.push(chunk));
response.once('end', () =>
resolve(this.getBodyFromChunks(chunks, response.headers))
);
response.once('error', reject);
});
return {
headers: response.headers,
statusCode: response.statusCode,
body: responseBody.body,
encoding: responseBody.encoding
};
}
async onRespond(pollyRequest, error) {
const { req, respond } = pollyRequest.requestArguments;
const { statusCode, body, headers, encoding } = pollyRequest.response;
if (pollyRequest[ABORT_HANDLER]) {
req.off('abort', pollyRequest[ABORT_HANDLER]);
req.off('close', pollyRequest[ABORT_HANDLER]);
}
if (pollyRequest.aborted) {
// Even if the request has been aborted, we need to respond to the nock
// request in order to resolve its awaiting promise.
respond(null, [0, undefined, {}]);
return;
}
if (error) {
// If an error was received then forward it over to nock so it can
// correctly handle it.
respond(error);
return;
}
const chunks = this.getChunksFromBody(body, headers, encoding);
const stream = new ReadableStream();
// Expose the response data as a stream of chunks since
// it could contain encoded data which is needed
// to be pushed to the response chunk by chunk.
chunks.forEach((chunk) => stream.push(chunk));
stream.push(null);
// Create a promise that will resolve once the request
// has been completed (including errored or aborted). This is needed so
// that the deferred promise used by `polly.flush()` doesn't resolve before
// the response was actually received.
const requestFinishedPromise = new Promise((resolve) => {
if (req.aborted) {
resolve();
} else {
req.once('response', resolve);
req.once('abort', resolve);
req.once('error', resolve);
}
});
respond(null, [statusCode, stream, headers]);
await requestFinishedPromise;
}
getBodyFromChunks(chunks, headers) {
// If content-encoding is set in the header then the body/content
// should not be concatenated. Instead, the chunks should
// be preserved as-is so that each chunk can be mocked individually
if (isContentEncoded(headers)) {
const encodedChunks = chunks.map((chunk) => {
if (!Buffer.isBuffer(chunk)) {
this.assert(
'content-encoded responses must all be binary buffers',
typeof chunk === 'string'
);
chunk = Buffer.from(chunk);
}
return chunk.toString('base64');
});
return {
encoding: 'base64',
body: JSON.stringify(encodedChunks)
};
}
const buffer = mergeChunks(chunks);
const isBinaryBuffer = !isUtf8Representable(buffer);
// The merged buffer can be one of two things:
// 1. A binary buffer which then has to be recorded as a base64 string.
// 2. A string buffer.
return {
encoding: isBinaryBuffer ? 'base64' : undefined,
body: buffer.toString(isBinaryBuffer ? 'base64' : 'utf8')
};
}
getChunksFromBody(body, headers, encoding) {
if (!body) {
return [];
}
if (Buffer.isBuffer(body)) {
return [body];
}
// If content-encoding is set in the header then the body/content
// is as an array of base64 strings
if (isContentEncoded(headers)) {
const encodedChunks = JSON.parse(body);
return encodedChunks.map((chunk) => Buffer.from(chunk, encoding));
}
// The body can be one of two things:
// 1. A base64 string which then means its binary data.
// 2. A utf8 string which means a regular string.
return [Buffer.from(body, encoding ? encoding : 'utf8')];
}
}
================================================
FILE: packages/@pollyjs/adapter-node-http/src/utils/get-url-from-options.js
================================================
import { URL } from '@pollyjs/utils';
/**
* Generate an absolute url from options passed into `new http.ClientRequest`.
*
* @export
* @param {Object} [options]
* @returns {string}
*/
export default function getUrlFromOptions(options = {}) {
if (options.href) {
return options.href;
}
const protocol = options.protocol || `${options.proto}:` || 'http:';
const host = options.hostname || options.host || 'localhost';
const { path, port } = options;
const url = new URL();
url.set('protocol', protocol);
url.set('host', host);
url.set('pathname', path);
if (
port &&
!host.includes(':') &&
(port !== 80 || protocol !== 'http:') &&
(port !== 443 || protocol !== 'https:')
) {
url.set('port', port);
}
return url.href;
}
================================================
FILE: packages/@pollyjs/adapter-node-http/src/utils/merge-chunks.js
================================================
/**
* Merge an array of strings into a single string or concat an array
* of buffers into a single buffer.
*
* @export
* @param {string[] | Buffer[]} [chunks]
* @returns {string | Buffer}
*/
export default function mergeChunks(chunks) {
if (!chunks || chunks.length === 0) {
return Buffer.alloc(0);
}
// We assume that all chunks are Buffer objects if the first is buffer object.
if (!Buffer.isBuffer(chunks[0])) {
// When the chunks are not buffers we assume that they are strings.
return chunks.join('');
}
// Merge all the buffers into a single Buffer object.
return Buffer.concat(chunks);
}
================================================
FILE: packages/@pollyjs/adapter-node-http/src/utils/url-to-options.js
================================================
/**
* Utility function that converts a URL object into an ordinary
* options object as expected by the http.request and https.request APIs.
*
* This was copied from Node's source
* https://github.com/nodejs/node/blob/908292cf1f551c614a733d858528ffb13fb3a524/lib/internal/url.js#L1257
*/
export default function urlToOptions(url) {
const options = {
protocol: url.protocol,
hostname:
typeof url.hostname === 'string' && url.hostname.startsWith('[')
? url.hostname.slice(1, -1)
: url.hostname,
hash: url.hash,
search: url.search,
pathname: url.pathname,
path: `${url.pathname}${url.search || ''}`,
href: url.href
};
if (url.port !== '') {
options.port = Number(url.port);
}
if (url.username || url.password) {
options.auth = `${url.username}:${url.password}`;
}
return options;
}
================================================
FILE: packages/@pollyjs/adapter-node-http/tests/integration/adapter-node-fetch-test.js
================================================
import '@pollyjs-tests/helpers/global-node-fetch';
import setupFetchRecord from '@pollyjs-tests/helpers/setup-fetch-record';
import adapterTests from '@pollyjs-tests/integration/adapter-tests';
import adapterNodeTests from '@pollyjs-tests/integration/adapter-node-tests';
import { setupMocha as setupPolly } from '@pollyjs/core';
import pollyConfig from '../utils/polly-config';
describe('Integration | Node Http Adapter | node-fetch', function () {
setupPolly.beforeEach(pollyConfig);
setupFetchRecord({ host: 'http://localhost:4000' });
setupPolly.afterEach();
adapterTests();
adapterNodeTests();
});
================================================
FILE: packages/@pollyjs/adapter-node-http/tests/integration/adapter-test.js
================================================
import fs from 'fs';
import http from 'http';
import https from 'https';
import path from 'path';
import FormData from 'form-data';
import getStream from 'get-stream';
import adapterIdentifierTests from '@pollyjs-tests/integration/adapter-identifier-tests';
import setupFetchRecord from '@pollyjs-tests/helpers/setup-fetch-record';
import adapterTests from '@pollyjs-tests/integration/adapter-tests';
import { Polly, setupMocha as setupPolly } from '@pollyjs/core';
import NodeHTTPAdapter from '../../src';
import nativeRequest from '../utils/native-request';
import pollyConfig from '../utils/polly-config';
import getResponseFromRequest from '../utils/get-response-from-request';
describe('Integration | Node Http Adapter', function () {
describe('Concurrency', function () {
it('should prevent concurrent Node HTTP adapter instances', async function () {
const one = new Polly('one');
const two = new Polly('two');
one.connectTo(NodeHTTPAdapter);
expect(function () {
two.connectTo(NodeHTTPAdapter);
}).to.throw(/Running concurrent node-http adapters is unsupported/);
await one.stop();
await two.stop();
});
it('should prevent running nock concurrently with the node-http adapter', async function () {
const polly = new Polly('nock');
const nock = require('nock');
nock.activate();
expect(function () {
polly.connectTo(NodeHTTPAdapter);
}).to.throw(
/Running nock concurrently with the node-http adapter is unsupported/
);
nock.restore();
await polly.stop();
});
});
describe('http', function () {
setupPolly.beforeEach(pollyConfig);
setupFetchRecord({
host: 'http://localhost:4000',
fetch: nativeRequest.bind(undefined, http)
});
setupPolly.afterEach();
adapterTests();
adapterIdentifierTests();
commonTests(http);
it('should be able to download binary content', async function () {
const fetch = async () =>
Buffer.from(
await this.relativeFetch('/assets/32x32.png').then((res) =>
res.arrayBuffer()
)
);
this.polly.disconnectFrom(NodeHTTPAdapter);
const nativeResponseBuffer = await fetch();
this.polly.connectTo(NodeHTTPAdapter);
const recordedResponseBuffer = await fetch();
const { recordingName, config } = this.polly;
await this.polly.stop();
this.polly = new Polly(recordingName, config);
this.polly.replay();
const replayedResponseBuffer = await fetch();
expect(nativeResponseBuffer.equals(recordedResponseBuffer)).to.equal(
true
);
expect(recordedResponseBuffer.equals(replayedResponseBuffer)).to.equal(
true
);
expect(nativeResponseBuffer.equals(replayedResponseBuffer)).to.equal(
true
);
});
});
describe('https', function () {
setupPolly(pollyConfig);
commonTests(https);
});
});
function commonTests(transport) {
const { protocol } = transport.globalAgent;
it('should be able to upload a binary data', async function () {
const { server } = this.polly;
const url = `${protocol}//example.com`;
const body = Buffer.from('Node HTTP Adapter', 'base64');
const requests = [];
server.post(url).intercept((req, res) => {
requests.push(req);
res.sendStatus(204);
});
await nativeRequest(transport, url, { method: 'POST', body });
await nativeRequest(transport, url, { method: 'POST', body });
expect(requests).to.have.lengthOf(2);
expect(requests[0].id).to.equal(requests[1].id);
expect(requests[0].body.toString('base64')).to.equal(
body.toString('base64')
);
expect(requests[0].identifiers.body).to.equal(body.toString('base64'));
});
it('should be able to upload form data', async function () {
const url = `${protocol}//example.com/upload`;
const { server } = this.polly;
const formData = new FormData();
let request;
server.post(url).intercept((req, res) => {
request = req;
res.send(201);
});
formData.append(
'upload',
fs.createReadStream(path.resolve(__dirname, '../../package.json'))
);
const body = await getStream(formData);
await nativeRequest(transport, url, {
body,
headers: formData.getHeaders(),
method: 'POST'
});
expect(request).to.exist;
expect(typeof request.body).to.equal('string');
expect(request.body).to.include('@pollyjs/adapter-node-http');
});
it('should handle aborting a request', async function () {
const { server } = this.polly;
const url = `${protocol}//example.com`;
const req = transport.request(url);
let abortEventCalled = false;
server
.any(url)
.on('abort', () => (abortEventCalled = true))
.intercept(async (_, res) => {
await server.timeout(50);
res.sendStatus(200);
});
req.on('socket', () => {
setTimeout(() => {
req.abort();
}, 10);
});
try {
await getResponseFromRequest(req);
} catch (e) {
// no-op
}
await this.polly.flush();
expect(abortEventCalled).to.equal(true);
});
it('should handle immediately aborting a request', async function () {
const { server } = this.polly;
const url = `${protocol}//example.com`;
const req = transport.request(url);
let requestIntercepted = false;
let abortEventCalled = false;
server
.any(url)
.on('abort', () => (abortEventCalled = true))
.intercept(async (_, res) => {
requestIntercepted = true;
res.sendStatus(200);
});
const promise = getResponseFromRequest(req);
req.abort();
try {
await promise;
} catch (e) {
// no-op
}
await this.polly.flush();
// Nock will completely ignore requests that have been immediately aborted
expect(requestIntercepted).to.equal(false);
expect(abortEventCalled).to.equal(false);
});
}
================================================
FILE: packages/@pollyjs/adapter-node-http/tests/integration/persister-fs-test.js
================================================
import http from 'http';
import setupPersister from '@pollyjs-tests/helpers/setup-persister';
import setupFetchRecord from '@pollyjs-tests/helpers/setup-fetch-record';
import persisterTests from '@pollyjs-tests/integration/persister-tests';
import { setupMocha as setupPolly } from '@pollyjs/core';
import FSPersister from '@pollyjs/persister-fs';
import nativeRequest from '../utils/native-request';
import pollyConfig from '../utils/polly-config';
describe('Integration | FS Persister', function () {
setupPolly.beforeEach({
...pollyConfig,
persister: FSPersister,
persisterOptions: {
fs: { recordingsDir: 'tests/recordings' }
}
});
setupFetchRecord({
host: 'http://localhost:4000',
fetch: nativeRequest.bind(undefined, http)
});
setupPersister();
setupPolly.afterEach();
persisterTests();
});
================================================
FILE: packages/@pollyjs/adapter-node-http/tests/jest/integration/fetch-test.js
================================================
import '@pollyjs-tests/helpers/global-node-fetch';
import { Polly } from '@pollyjs/core';
import pollyConfig from '../../utils/polly-config';
describe('Integration | Jest | Fetch', function () {
let polly;
beforeEach(() => {
polly = new Polly('Integration | Jest | Fetch', pollyConfig);
});
afterEach(async () => await polly.stop());
test('it works', async () => {
polly.recordingName += '/it works';
const { persister, recordingId } = polly;
expect((await fetch('http://localhost:4000/api/db/foo')).status).toBe(404);
await persister.persist();
const har = await persister.findRecording(recordingId);
expect(har).toBeDefined();
expect(har.log.entries.length).toBe(1);
expect(har.log.entries[0].request.url.includes('/api/db/foo')).toBe(true);
expect(har.log.entries[0].response.status).toBe(404);
await persister.deleteRecording(recordingId);
expect(persister.findRecording(recordingId)).resolves.toBeNull();
});
});
================================================
FILE: packages/@pollyjs/adapter-node-http/tests/jest/integration/xhr-test.js
================================================
import { Polly } from '@pollyjs/core';
import pollyConfig from '../../utils/polly-config';
function request(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.addEventListener('load', function () {
resolve(xhr);
});
xhr.addEventListener('error', reject);
xhr.open('GET', url, true);
xhr.send();
});
}
describe('Integration | Jest | XHR', function () {
let polly;
beforeEach(() => {
polly = new Polly('Integration | Jest | XHR', pollyConfig);
});
afterEach(async () => await polly.stop());
test('it works', async () => {
polly.recordingName += '/it works';
const { persister, recordingId } = polly;
expect((await request('/api/db/foo')).status).toBe(404);
await persister.persist();
const har = await persister.findRecording(recordingId);
expect(har).toBeDefined();
expect(har.log.entries.length).toBe(1);
expect(har.log.entries[0].request.url.includes('/api/db/foo')).toBe(true);
expect(har.log.entries[0].response.status).toBe(404);
await persister.deleteRecording(recordingId);
expect(persister.findRecording(recordingId)).resolves.toBeNull();
});
});
================================================
FILE: packages/@pollyjs/adapter-node-http/tests/unit/utils/merge-chunks-test.js
================================================
import mergeChunks from '../../../src/utils/merge-chunks';
describe('Unit | Utils | mergeChunks', function () {
it('should exist', function () {
expect(mergeChunks).to.be.a('function');
});
it('should work', function () {
[null, []].forEach((chunks) => {
const buffer = mergeChunks(chunks);
expect(Buffer.isBuffer(buffer)).to.be.true;
expect(buffer.toString()).to.have.lengthOf(0);
});
const str = mergeChunks(['T', 'e', 's', 't']);
expect(Buffer.isBuffer(str)).to.be.false;
expect(str).to.equal('Test');
const buffer = mergeChunks(['T', 'e', 's', 't'].map((c) => Buffer.from(c)));
expect(Buffer.isBuffer(buffer)).to.be.true;
expect(buffer.toString()).to.equal('Test');
});
});
================================================
FILE: packages/@pollyjs/adapter-node-http/tests/utils/get-buffer-from-stream.js
================================================
export default function getBufferFromStream(stream) {
return new Promise((resolve) => {
const chunks = [];
stream.on('data', (chunk) => {
chunks.push(chunk);
});
stream.on('end', () => {
resolve(Buffer.concat(chunks));
});
});
}
================================================
FILE: packages/@pollyjs/adapter-node-http/tests/utils/get-response-from-request.js
================================================
export default function getResponseFromRequest(req, data) {
return new Promise((resolve, reject) => {
req.once('response', resolve);
req.once('error', reject);
req.once('abort', reject);
req.end(data);
});
}
================================================
FILE: packages/@pollyjs/adapter-node-http/tests/utils/native-request.js
================================================
import Url from 'url';
import { Response } from 'node-fetch';
import getResponseFromRequest from './get-response-from-request';
export default async function nativeRequest(transport, url, options) {
const opts = {
...(options || {}),
...Url.parse(url)
};
let reqBody;
if (opts.body) {
reqBody = opts.body;
delete opts.body;
}
const response = await getResponseFromRequest(
transport.request(opts),
reqBody
);
return new Response(response, {
status: response.statusCode,
headers: response.headers
});
}
================================================
FILE: packages/@pollyjs/adapter-node-http/tests/utils/polly-config.js
================================================
import InMemoryPersister from '@pollyjs/persister-in-memory';
import NodeHttpAdapter from '../../src';
export default {
recordFailedRequests: true,
adapters: [NodeHttpAdapter],
persister: InMemoryPersister,
persisterOptions: {}
};
================================================
FILE: packages/@pollyjs/adapter-node-http/types.d.ts
================================================
import Adapter from '@pollyjs/adapter';
export default class NodeHttpAdapter extends Adapter {}
================================================
FILE: packages/@pollyjs/adapter-puppeteer/CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.6](https://github.com/netflix/pollyjs/compare/v6.0.5...v6.0.6) (2023-07-20)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
## [6.0.5](https://github.com/netflix/pollyjs/compare/v6.0.4...v6.0.5) (2022-04-04)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
## [6.0.4](https://github.com/netflix/pollyjs/compare/v6.0.3...v6.0.4) (2021-12-10)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
## [6.0.3](https://github.com/netflix/pollyjs/compare/v6.0.2...v6.0.3) (2021-12-08)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
## [6.0.2](https://github.com/netflix/pollyjs/compare/v6.0.1...v6.0.2) (2021-12-07)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
## [6.0.1](https://github.com/netflix/pollyjs/compare/v6.0.0...v6.0.1) (2021-12-06)
### Bug Fixes
* **types:** add types.d.ts to package.files ([#431](https://github.com/netflix/pollyjs/issues/431)) ([113ee89](https://github.com/netflix/pollyjs/commit/113ee898bcf0467c5c48c15b53fc9198e2e91cb1))
# [6.0.0](https://github.com/netflix/pollyjs/compare/v5.2.0...v6.0.0) (2021-11-30)
* feat!: Cleanup adapter and persister APIs (#429) ([06499fc](https://github.com/netflix/pollyjs/commit/06499fc2d85254b3329db2bec770d173ed32bca0)), closes [#429](https://github.com/netflix/pollyjs/issues/429)
* chore!: Upgrade package dependencies (#421) ([dd23334](https://github.com/netflix/pollyjs/commit/dd23334fa9b64248e4c49c3616237bdc2f12f682)), closes [#421](https://github.com/netflix/pollyjs/issues/421)
* feat(ember)!: Upgrade to ember octane (#415) ([8559ef8](https://github.com/netflix/pollyjs/commit/8559ef8c600aefaec629870eac5f5c8953e18b16)), closes [#415](https://github.com/netflix/pollyjs/issues/415)
### BREAKING CHANGES
* - Adapter
- `passthroughRequest` renamed to `onFetchResponse`
- `respondToRequest` renamed to `onRespond`
- Persister
- `findRecording` renamed to `onFindRecording`
- `saveRecording` renamed to `onSaveRecording`
- `deleteRecording` renamed to `onDeleteRecording`
* Recording file name will no longer have trailing dashes
* @pollyjs dependencies have been moved to peer dependencies
## [5.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v5.1.0...v5.1.1) (2021-06-02)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
# [5.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v5.0.2...v5.1.0) (2020-12-12)
### Bug Fixes
* **adapter-puppeteer:** Add prependListener puppeteer@4.0.0 removed ([#368](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/issues/368)) ([6c35fd3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/6c35fd3))
# [5.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v4.3.0...v5.0.0) (2020-06-23)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
# [4.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v4.2.1...v4.3.0) (2020-05-18)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
## [4.2.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v4.2.0...v4.2.1) (2020-04-30)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
# [4.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v4.1.0...v4.2.0) (2020-04-29)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
# [4.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v4.0.4...v4.1.0) (2020-04-23)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
## [4.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v4.0.3...v4.0.4) (2020-03-21)
### Bug Fixes
* Deprecates adapter & persister `name` in favor of `id` ([#310](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/issues/310)) ([41dd093](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/41dd093))
## [4.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v4.0.1...v4.0.2) (2020-01-29)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
# [4.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v3.0.2...v4.0.0) (2020-01-13)
### Bug Fixes
* **core:** Disconnect from all adapters when `pause` is called ([#291](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/issues/291)) ([5c655bf](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/5c655bf))
### BREAKING CHANGES
* **core:** Calling `polly.pause()` will now disconnect from all connected adapters instead of setting the mode to passthrough. Calling `polly.play()` will reconnect to the disconnected adapters before pause was called.
# [3.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v2.7.0...v3.0.0) (2019-12-18)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
## [2.6.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v2.6.2...v2.6.3) (2019-09-30)
### Bug Fixes
* use watch strategy ([#236](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/issues/236)) ([5b4edf3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/5b4edf3))
## [2.6.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v2.6.1...v2.6.2) (2019-08-05)
### Features
* Adds an in-memory persister to test polly internals ([#237](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/issues/237)) ([5a6fda6](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/5a6fda6))
## [2.6.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v2.6.0...v2.6.1) (2019-08-01)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
# [2.6.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v2.5.0...v2.6.0) (2019-07-17)
### Features
* PollyError and improved adapter error handling ([#234](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/issues/234)) ([23a2127](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/23a2127))
# [2.5.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v2.4.0...v2.5.0) (2019-06-06)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
# [2.4.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v2.3.2...v2.4.0) (2019-04-27)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
## [2.3.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v2.3.1...v2.3.2) (2019-04-09)
### Bug Fixes
* **adapter-puppeteer:** Remove other resource type matching ([#197](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-puppeteer/issues/197)) ([ea6bfcc](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/ea6bfcc))
# [2.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v2.2.0...v2.3.0) (2019-02-27)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
# [2.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v2.1.0...v2.2.0) (2019-02-20)
### Features
* Add `error` event and improve error handling ([#185](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-puppeteer/issues/185)) ([3694ebc](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/3694ebc))
# [2.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v2.0.0...v2.1.0) (2019-02-04)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
# [2.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v1.4.2...v2.0.0) (2019-01-29)
### Features
* Simplify adapter implementation ([#154](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-puppeteer/issues/154)) ([12c8601](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/12c8601))
### BREAKING CHANGES
* Changes to the base adapter implementation and external facing API
## [1.4.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v1.4.1...v1.4.2) (2019-01-16)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
## [1.4.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v1.4.0...v1.4.1) (2018-12-13)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
## [1.3.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v1.3.1...v1.3.2) (2018-11-29)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
## [1.3.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/v1.2.0...v1.3.1) (2018-11-28)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
# 1.2.0 (2018-09-16)
### Bug Fixes
* **adapter-puppeteer:** Do not intercept CORS preflight requests ([#90](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-puppeteer/issues/90)) ([53ad433](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/53ad433))
* Puppeteer 1.7.0 support ([#100](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-puppeteer/issues/100)) ([e208b38](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/e208b38))
* Puppeteer CORS request matching ([#110](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-puppeteer/issues/110)) ([7831115](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/7831115))
### Features
* Puppeteer Adapter ([#64](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-puppeteer/issues/64)) ([f902c6d](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/f902c6d))
* Wait for all handled requests to resolve via `.flush()` ([#75](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-puppeteer/issues/75)) ([a3113b7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/a3113b7))
## [1.1.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/@pollyjs/adapter-puppeteer@1.1.3...@pollyjs/adapter-puppeteer@1.1.4) (2018-08-22)
### Bug Fixes
* Puppeteer 1.7.0 support ([#100](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-puppeteer/issues/100)) ([e208b38](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/e208b38))
## [1.1.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/@pollyjs/adapter-puppeteer@1.1.2...@pollyjs/adapter-puppeteer@1.1.3) (2018-08-12)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
## [1.1.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/@pollyjs/adapter-puppeteer@1.1.1...@pollyjs/adapter-puppeteer@1.1.2) (2018-08-12)
### Bug Fixes
* **adapter-puppeteer:** Do not intercept CORS preflight requests ([#90](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-puppeteer/issues/90)) ([53ad433](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/53ad433))
## [1.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/@pollyjs/adapter-puppeteer@1.1.0...@pollyjs/adapter-puppeteer@1.1.1) (2018-08-09)
**Note:** Version bump only for package @pollyjs/adapter-puppeteer
# [1.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/compare/@pollyjs/adapter-puppeteer@1.0.0...@pollyjs/adapter-puppeteer@1.1.0) (2018-07-26)
### Features
* Wait for all handled requests to resolve via `.flush()` ([#75](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-puppeteer/issues/75)) ([a3113b7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/a3113b7))
# 1.0.0 (2018-07-20)
### Features
* Puppeteer Adapter ([#64](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-puppeteer/issues/64)) ([f902c6d](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer/commit/f902c6d))
================================================
FILE: packages/@pollyjs/adapter-puppeteer/LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Netflix Inc and @pollyjs contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: packages/@pollyjs/adapter-puppeteer/README.md
================================================
Record, Replay, and Stub HTTP Interactions
[](https://travis-ci.com/Netflix/pollyjs)
[](https://badge.fury.io/js/%40pollyjs%2Fadapter-puppeteer)
[](http://www.apache.org/licenses/LICENSE-2.0)
The `@pollyjs/adapter-puppeteer` package provides a [Puppeteer](https://github.com/GoogleChrome/puppeteer) adapter
to be used with `@pollyjs/core`.
## Installation
_If you're using puppeteer 1.7 or 1.8, you'll experience issues with passthrough requests. Please upgrade to the latest version of puppeteer or use a version prior to 1.7_
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/adapter-puppeteer -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/adapter-puppeteer -D
```
## Documentation
Check out the [Puppeteer Adapter](https://netflix.github.io/pollyjs/#/adapters/puppeteer)
documentation for more details.
## Usage
```js
import { Polly } from '@pollyjs/core';
import PuppeteerAdapter from '@pollyjs/adapter-puppeteer';
Polly.register(PuppeteerAdapter);
const browser = await puppeteer.launch();
const page = await this.browser.newPage();
await page.setRequestInterception(true);
new Polly('', {
adapters: ['puppeteer'],
adapterOptions: {
puppeteer: { page }
}
});
await page.goto('https://netflix.com');
```
## License
Copyright (c) 2018 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
================================================
FILE: packages/@pollyjs/adapter-puppeteer/package.json
================================================
{
"name": "@pollyjs/adapter-puppeteer",
"version": "6.0.6",
"description": "File system persister for @pollyjs",
"main": "dist/cjs/pollyjs-adapter-puppeteer.js",
"module": "dist/es/pollyjs-adapter-puppeteer.js",
"types": "types.d.ts",
"files": [
"src",
"dist",
"types.d.ts"
],
"repository": "https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-puppeteer",
"license": "Apache-2.0",
"contributors": [
{
"name": "Jason Mitchell",
"email": "jason.mitchell.w@gmail.com"
},
{
"name": "Offir Golan",
"email": "offirgolan@gmail.com"
}
],
"keywords": [
"polly",
"pollyjs",
"record",
"replay",
"fs",
"file"
],
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "rollup -c ../../../scripts/rollup/default.config.js",
"build:watch": "yarn build -w",
"test:build": "rollup -c rollup.config.test.js",
"test:build:watch": "rollup -c rollup.config.test.js -w",
"watch-all": "npm-run-all --parallel build:watch test:build:watch"
},
"dependencies": {
"@pollyjs/adapter": "^6.0.6",
"@pollyjs/utils": "^6.0.6"
},
"devDependencies": {
"@pollyjs/core": "^6.0.6",
"@pollyjs/persister-fs": "^6.0.6",
"node-fetch": "^2.6.6",
"puppeteer": "1.10.0",
"rollup": "^1.14.6"
}
}
================================================
FILE: packages/@pollyjs/adapter-puppeteer/rollup.config.js
================================================
import createNodeConfig from '../../../scripts/rollup/node.config';
export default createNodeConfig();
================================================
FILE: packages/@pollyjs/adapter-puppeteer/rollup.config.test.js
================================================
import createNodeTestConfig from '../../../scripts/rollup/node.test.config';
export default createNodeTestConfig({
external: ['puppeteer']
});
================================================
FILE: packages/@pollyjs/adapter-puppeteer/src/index.js
================================================
import Adapter from '@pollyjs/adapter';
import { URL } from '@pollyjs/utils';
const LISTENERS = Symbol();
const PASSTHROUGH_PROMISES = Symbol();
const PASSTHROUGH_REQ_ID_QP = 'pollyjs_passthrough_req_id';
export default class PuppeteerAdapter extends Adapter {
static get id() {
return 'puppeteer';
}
get defaultOptions() {
return {
page: null,
requestResourceTypes: ['xhr', 'fetch']
};
}
constructor() {
super(...arguments);
this._requestsMapping = {
passthroughs: new WeakMap(),
pollyRequests: new WeakMap()
};
}
onConnect() {
const { page } = this.options;
this[LISTENERS] = new Map();
this[PASSTHROUGH_PROMISES] = new Map();
this.assert(
'A puppeteer page instance is required.',
!!(page && typeof page === 'object')
);
this.attachToPageEvents(page);
}
onDisconnect() {
this[LISTENERS].forEach((_, target) =>
this._callListenersWith('removeListener', target)
);
}
attachToPageEvents(page) {
const { requestResourceTypes } = this.options;
this[LISTENERS].set(page, {
request: async (request) => {
if (requestResourceTypes.includes(request.resourceType())) {
const url = request.url();
const method = request.method();
const headers = request.headers();
// A CORS preflight request is a CORS request that checks to see
// if the CORS protocol is understood.
const isPreFlightReq =
method === 'OPTIONS' &&
!!headers['origin'] &&
!!headers['access-control-request-method'];
// Do not intercept requests with the Polly passthrough QP
if (url.includes(PASSTHROUGH_REQ_ID_QP)) {
const parsedUrl = new URL(url, true);
// If this is a polly passthrough request
// Get the associated promise object for the request id and set it
// on the request.
if (!isPreFlightReq) {
this._requestsMapping.passthroughs.set(
request,
this[PASSTHROUGH_PROMISES].get(
parsedUrl.query[PASSTHROUGH_REQ_ID_QP]
)
);
}
// Delete the query param to remove any pollyjs footprint
delete parsedUrl.query[PASSTHROUGH_REQ_ID_QP];
// Continue the request with the url override
request.continue({ url: parsedUrl.toString() });
} else if (isPreFlightReq) {
// Do not intercept preflight requests
request.continue();
} else {
this.handleRequest({
headers,
url,
method,
body: request.postData(),
requestArguments: { request }
});
}
} else {
request.continue();
}
},
requestfinished: (request) => {
const response = request.response();
const { passthroughs, pollyRequests } = this._requestsMapping;
// Resolve the passthrough promise with the response if it exists
if (passthroughs.has(request)) {
passthroughs.get(request).resolve(response);
passthroughs.delete(request);
}
// Resolve the deferred pollyRequest promise if it exists
if (pollyRequests.has(request)) {
pollyRequests.get(request).promise._resolve(response);
pollyRequests.delete(request);
}
},
requestfailed: (request) => {
const error = request.failure();
const { passthroughs, pollyRequests } = this._requestsMapping;
// Reject the passthrough promise with the error object if it exists
if (passthroughs.has(request)) {
passthroughs.get(request).reject(error);
passthroughs.delete(request);
}
// Reject the deferred pollyRequest promise with the error object if it exists
if (pollyRequests.has(request)) {
pollyRequests.get(request).promise._reject(error);
pollyRequests.delete(request);
}
},
close: () => this[LISTENERS].delete(page)
});
this._callListenersWith('prependListener', page);
}
onRequest(pollyRequest) {
const { request } = pollyRequest.requestArguments;
const { promise } = pollyRequest;
// Override the deferred promise's resolve and reject to no-op since
// we handle it manually in the `requestfinished` and `requestfailed` events.
promise._resolve = promise.resolve;
promise._reject = promise.reject;
promise.resolve = promise.reject = () => {};
/*
Create an access point to the `pollyRequest` so it can be accessed from
the emitted page events
*/
this._requestsMapping.pollyRequests.set(request, pollyRequest);
}
async onFetchResponse(pollyRequest) {
const { page } = this.options;
const { id, order, url, method, headers, body } = pollyRequest;
const requestId = `${this.polly.recordingId}:${id}:${order}`;
const parsedUrl = new URL(url, true);
parsedUrl.query[PASSTHROUGH_REQ_ID_QP] = requestId;
try {
const response = await new Promise((resolve, reject) => {
this[PASSTHROUGH_PROMISES].set(requestId, { resolve, reject });
// This gets evaluated within the browser's context, meaning that
// this fetch call executes from within the browser.
page.evaluate(
new Function(
'url',
'method',
'headers',
'body',
'return fetch(url, { method, headers, body });'
),
parsedUrl.toString(),
method,
headers,
body
);
});
return {
statusCode: response.status(),
headers: response.headers(),
body: await response.text()
};
} finally {
this[PASSTHROUGH_PROMISES].delete(requestId);
}
}
async onRespond(pollyRequest, error) {
const { request } = pollyRequest.requestArguments;
const { response } = pollyRequest;
if (error) {
// If an error was returned then we force puppeteer to abort the current
// request. This will emit the `requestfailed` page event and allow the end
// user to handle the error.
await request.abort();
} else {
await request.respond({
status: response.statusCode,
headers: response.headers,
body: response.body
});
}
}
_callListenersWith(methodName, target) {
if (this[LISTENERS].has(target)) {
const listeners = this[LISTENERS].get(target);
// puppeteer remove prependListener after v4.0.0, polyfill it if missing
const prependListenerPolyfill = function (event, handler) {
const all = this.emitter.all;
const handlers = all.get(event);
const added = handlers && handlers.unshift(handler);
if (!added) {
all.set(event, [handler]);
}
};
for (const eventName in listeners) {
const prependListener =
target.prependListener || prependListenerPolyfill;
const fn =
methodName === 'prependListener'
? prependListener
: target[methodName];
fn.apply(target, [eventName, listeners[eventName]]);
}
}
}
}
================================================
FILE: packages/@pollyjs/adapter-puppeteer/tests/helpers/fetch.js
================================================
import { Response } from 'node-fetch';
export default async function fetch() {
const res = await this.page.evaluate((...args) => {
// This is run within the browser's context meaning it's using the
// browser's native window.fetch method.
return fetch(...args).then((res) => {
const { url, status, headers } = res;
return res.text().then((body) => {
return { url, status, body, headers };
});
});
}, ...arguments);
return new Response(res.body, res);
}
================================================
FILE: packages/@pollyjs/adapter-puppeteer/tests/integration/adapter-test.js
================================================
import InMemoryPersister from '@pollyjs/persister-in-memory';
import puppeteer from 'puppeteer';
import setupFetchRecord from '@pollyjs-tests/helpers/setup-fetch-record';
import adapterTests from '@pollyjs-tests/integration/adapter-tests';
import { setupMocha as setupPolly } from '@pollyjs/core';
import fetch from '../helpers/fetch';
import PuppeteerAdapter from '../../src';
// The host the API server is on
const HOST = 'http://localhost:4000';
describe('Integration | Puppeteer Adapter', function () {
before(async function () {
this.browser = await puppeteer.launch({ args: ['--no-sandbox'] });
});
after(async function () {
await this.browser.close();
});
setupPolly.beforeEach({
recordFailedRequests: true,
persister: InMemoryPersister,
matchRequestsBy: {
headers: {
exclude: [
// We don't want new recordings when we update chrome
'user-agent',
// This is a unique ID which breaks the request matching
'x-devtools-emulate-network-conditions-client-id'
]
}
}
});
setupFetchRecord.beforeEach({ host: HOST });
beforeEach(function () {
// Override this.fetch here since it needs access to the current context
this.fetch = fetch.bind(this);
});
beforeEach(async function () {
this.page = await this.browser.newPage();
await this.page.goto(`${HOST}/api`);
await this.page.setRequestInterception(true);
this.polly.configure({
adapters: [PuppeteerAdapter],
adapterOptions: {
puppeteer: { page: this.page }
}
});
});
afterEach(async function () {
// Turn off request interception before setupFetchRecord's afterEach so it
// can correctly do it's thing
await this.page.setRequestInterception(false);
});
setupFetchRecord.afterEach();
afterEach(async function () {
await this.page.close();
});
setupPolly.afterEach();
adapterTests();
it('should have resolved requests after flushing', async function () {
// Timeout after 500ms since we could have a hanging while loop
this.timeout(500);
const { server } = this.polly;
const requests = [];
const resolved = [];
let i = 1;
server
.get(this.recordUrl())
.intercept(async (req, res) => {
await server.timeout(5);
res.sendStatus(200);
})
.on('request', (req) => requests.push(req));
this.page.on('requestfinished', () => resolved.push(i++));
this.fetchRecord();
this.fetchRecord();
this.fetchRecord();
// Since it takes time for Puppeteer to execute the request in the browser's
// context, we have to wait until the requests have been made.
while (requests.length !== 3) {
await server.timeout(5);
}
await this.polly.flush();
expect(requests).to.have.lengthOf(3);
requests.forEach((request) => expect(request.didRespond).to.be.true);
expect(resolved).to.have.members([1, 2, 3]);
});
});
================================================
FILE: packages/@pollyjs/adapter-puppeteer/tests/unit/adapter-test.js
================================================
import { setupMocha as setupPolly } from '@pollyjs/core';
import { PollyError } from '@pollyjs/utils';
import PuppeteerAdapter from '../../src';
describe('Unit | Puppeteer Adapter', function () {
setupPolly();
it('should throw without a page instance', function () {
expect(() =>
this.polly.configure({
adapters: [PuppeteerAdapter]
})
).to.throw(PollyError, /A puppeteer page instance is required/);
});
});
================================================
FILE: packages/@pollyjs/adapter-puppeteer/types.d.ts
================================================
import Adapter from '@pollyjs/adapter';
export default class PuppeteerAdapter extends Adapter<{
page: any;
requestResourceTypes?: string[];
}> {}
================================================
FILE: packages/@pollyjs/adapter-xhr/CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.6](https://github.com/netflix/pollyjs/compare/v6.0.5...v6.0.6) (2023-07-20)
**Note:** Version bump only for package @pollyjs/adapter-xhr
## [6.0.5](https://github.com/netflix/pollyjs/compare/v6.0.4...v6.0.5) (2022-04-04)
**Note:** Version bump only for package @pollyjs/adapter-xhr
## [6.0.4](https://github.com/netflix/pollyjs/compare/v6.0.3...v6.0.4) (2021-12-10)
**Note:** Version bump only for package @pollyjs/adapter-xhr
## [6.0.3](https://github.com/netflix/pollyjs/compare/v6.0.2...v6.0.3) (2021-12-08)
**Note:** Version bump only for package @pollyjs/adapter-xhr
## [6.0.2](https://github.com/netflix/pollyjs/compare/v6.0.1...v6.0.2) (2021-12-07)
**Note:** Version bump only for package @pollyjs/adapter-xhr
## [6.0.1](https://github.com/netflix/pollyjs/compare/v6.0.0...v6.0.1) (2021-12-06)
### Bug Fixes
* **types:** add types.d.ts to package.files ([#431](https://github.com/netflix/pollyjs/issues/431)) ([113ee89](https://github.com/netflix/pollyjs/commit/113ee898bcf0467c5c48c15b53fc9198e2e91cb1))
# [6.0.0](https://github.com/netflix/pollyjs/compare/v5.2.0...v6.0.0) (2021-11-30)
* feat!: Cleanup adapter and persister APIs (#429) ([06499fc](https://github.com/netflix/pollyjs/commit/06499fc2d85254b3329db2bec770d173ed32bca0)), closes [#429](https://github.com/netflix/pollyjs/issues/429)
* feat!: Use base64 instead of hex encoding for binary data (#420) ([6bb9b36](https://github.com/netflix/pollyjs/commit/6bb9b36522d73f9c079735d9006a12376aee39ea)), closes [#420](https://github.com/netflix/pollyjs/issues/420)
* feat(ember)!: Upgrade to ember octane (#415) ([8559ef8](https://github.com/netflix/pollyjs/commit/8559ef8c600aefaec629870eac5f5c8953e18b16)), closes [#415](https://github.com/netflix/pollyjs/issues/415)
### BREAKING CHANGES
* - Adapter
- `passthroughRequest` renamed to `onFetchResponse`
- `respondToRequest` renamed to `onRespond`
- Persister
- `findRecording` renamed to `onFindRecording`
- `saveRecording` renamed to `onSaveRecording`
- `deleteRecording` renamed to `onDeleteRecording`
* Use the standard `encoding` field on the generated har file instead of `_isBinary` and use `base64` encoding instead of `hex` to reduce the payload size.
* @pollyjs dependencies have been moved to peer dependencies
## [5.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v5.1.0...v5.1.1) (2021-06-02)
### Bug Fixes
* Handle failed arraybuffer instanceof checks ([#393](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/issues/393)) ([247be0a](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/commit/247be0a))
# [5.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v5.0.2...v5.1.0) (2020-12-12)
**Note:** Version bump only for package @pollyjs/adapter-xhr
## [5.0.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v5.0.0...v5.0.1) (2020-09-25)
### Bug Fixes
* **adapter-xhr:** Only modify the `responseType` if it was changed ([#363](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/issues/363)) ([cff4e2d](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/commit/cff4e2d))
# [5.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v4.3.0...v5.0.0) (2020-06-23)
**Note:** Version bump only for package @pollyjs/adapter-xhr
# [4.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v4.2.1...v4.3.0) (2020-05-18)
### Features
* **adapter-xhr:** Add support for handling binary data ([#333](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/issues/333)) ([48ea1d7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/commit/48ea1d7))
## [4.2.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v4.2.0...v4.2.1) (2020-04-30)
**Note:** Version bump only for package @pollyjs/adapter-xhr
# [4.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v4.0.4...v4.1.0) (2020-04-23)
### Bug Fixes
* Improve abort handling ([#320](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/issues/320)) ([cc46bb4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/commit/cc46bb4))
## [4.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v4.0.3...v4.0.4) (2020-03-21)
### Bug Fixes
* Deprecates adapter & persister `name` in favor of `id` ([#310](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/issues/310)) ([41dd093](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/commit/41dd093))
## [4.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v4.0.1...v4.0.2) (2020-01-29)
**Note:** Version bump only for package @pollyjs/adapter-xhr
# [4.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v3.0.2...v4.0.0) (2020-01-13)
**Note:** Version bump only for package @pollyjs/adapter-xhr
# [3.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v2.7.0...v3.0.0) (2019-12-18)
**Note:** Version bump only for package @pollyjs/adapter-xhr
## [2.6.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v2.6.2...v2.6.3) (2019-09-30)
### Bug Fixes
* use watch strategy ([#236](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/issues/236)) ([5b4edf3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/commit/5b4edf3))
## [2.6.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v2.6.1...v2.6.2) (2019-08-05)
### Features
* Adds an in-memory persister to test polly internals ([#237](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/issues/237)) ([5a6fda6](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/commit/5a6fda6))
## [2.6.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v2.6.0...v2.6.1) (2019-08-01)
**Note:** Version bump only for package @pollyjs/adapter-xhr
# [2.6.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v2.5.0...v2.6.0) (2019-07-17)
**Note:** Version bump only for package @pollyjs/adapter-xhr
# [2.5.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v2.4.0...v2.5.0) (2019-06-06)
### Features
* **adapter-xhr:** Support `context` option ([65b3c38](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/commit/65b3c38))
# [2.4.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v2.3.2...v2.4.0) (2019-04-27)
**Note:** Version bump only for package @pollyjs/adapter-xhr
# [2.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v2.2.0...v2.3.0) (2019-02-27)
**Note:** Version bump only for package @pollyjs/adapter-xhr
# [2.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v2.1.0...v2.2.0) (2019-02-20)
### Features
* Add `error` event and improve error handling ([#185](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-xhr/issues/185)) ([3694ebc](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/commit/3694ebc))
# [2.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v2.0.0...v2.1.0) (2019-02-04)
### Bug Fixes
* **adapter-xhr:** Xhr.send should not be an async method ([#173](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-xhr/issues/173)) ([eb3a6eb](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/commit/eb3a6eb))
# [2.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v1.4.2...v2.0.0) (2019-01-29)
### Features
* Simplify adapter implementation ([#154](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-xhr/issues/154)) ([12c8601](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/commit/12c8601))
### BREAKING CHANGES
* Changes to the base adapter implementation and external facing API
## [1.4.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v1.4.1...v1.4.2) (2019-01-16)
**Note:** Version bump only for package @pollyjs/adapter-xhr
## [1.4.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v1.4.0...v1.4.1) (2018-12-13)
**Note:** Version bump only for package @pollyjs/adapter-xhr
## [1.3.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v1.3.1...v1.3.2) (2018-11-29)
**Note:** Version bump only for package @pollyjs/adapter-xhr
## [1.3.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/v1.2.0...v1.3.1) (2018-11-28)
### Features
* Add an onIdentifyRequest hook to allow adapter level serialization ([#140](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-xhr/issues/140)) ([548002c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/commit/548002c))
# 1.2.0 (2018-09-16)
### Bug Fixes
* Loosen up global XHR native check ([#69](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-xhr/issues/69)) ([79cdd96](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/commit/79cdd96))
## [1.0.5](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/@pollyjs/adapter-xhr@1.0.4...@pollyjs/adapter-xhr@1.0.5) (2018-08-22)
**Note:** Version bump only for package @pollyjs/adapter-xhr
## [1.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/@pollyjs/adapter-xhr@1.0.3...@pollyjs/adapter-xhr@1.0.4) (2018-08-12)
**Note:** Version bump only for package @pollyjs/adapter-xhr
## [1.0.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/@pollyjs/adapter-xhr@1.0.2...@pollyjs/adapter-xhr@1.0.3) (2018-08-12)
**Note:** Version bump only for package @pollyjs/adapter-xhr
## [1.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/@pollyjs/adapter-xhr@1.0.1...@pollyjs/adapter-xhr@1.0.2) (2018-08-09)
**Note:** Version bump only for package @pollyjs/adapter-xhr
## [1.0.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/compare/@pollyjs/adapter-xhr@1.0.0...@pollyjs/adapter-xhr@1.0.1) (2018-07-26)
**Note:** Version bump only for package @pollyjs/adapter-xhr
# 1.0.0 (2018-07-20)
### Bug Fixes
* Loosen up global XHR native check ([#69](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/adapter-xhr/issues/69)) ([79cdd96](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr/commit/79cdd96))
================================================
FILE: packages/@pollyjs/adapter-xhr/LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Netflix Inc and @pollyjs contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: packages/@pollyjs/adapter-xhr/README.md
================================================
Record, Replay, and Stub HTTP Interactions
[](https://travis-ci.com/Netflix/pollyjs)
[](https://badge.fury.io/js/%40pollyjs%2Fadapter-xhr)
[](http://www.apache.org/licenses/LICENSE-2.0)
The `@pollyjs/adapter-xhr` package provides an xhr adapter that uses
Sinon's [Nise](https://github.com/sinonjs/nise) library to fake the global
`XMLHttpRequest` object while wrapping the native one to allow for seamless
recording and replaying of requests.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/adapter-xhr -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/adapter-xhr -D
```
## Documentation
Check out the [XHR Adapter](https://netflix.github.io/pollyjs/#/adapters/xhr)
documentation for more details.
## Usage
```js
import { Polly } from '@pollyjs/core';
import XHRAdapter from '@pollyjs/adapter-xhr';
Polly.register(XHRAdapter);
new Polly('', {
adapters: ['xhr']
});
```
## License
Copyright (c) 2018 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
================================================
FILE: packages/@pollyjs/adapter-xhr/package.json
================================================
{
"name": "@pollyjs/adapter-xhr",
"version": "6.0.6",
"description": "XHR adapter for @pollyjs",
"main": "dist/cjs/pollyjs-adapter-xhr.js",
"module": "dist/es/pollyjs-adapter-xhr.js",
"browser": "dist/umd/pollyjs-adapter-xhr.js",
"types": "types.d.ts",
"files": [
"src",
"dist",
"types.d.ts"
],
"repository": "https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-xhr",
"license": "Apache-2.0",
"contributors": [
{
"name": "Jason Mitchell",
"email": "jason.mitchell.w@gmail.com"
},
{
"name": "Offir Golan",
"email": "offirgolan@gmail.com"
}
],
"keywords": [
"polly",
"pollyjs",
"record",
"replay",
"xhr",
"adapter"
],
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "rollup -c ../../../scripts/rollup/default.config.js",
"build:watch": "yarn build -w",
"test:build": "rollup -c rollup.config.test.js",
"test:build:watch": "rollup -c rollup.config.test.js -w",
"watch-all": "npm-run-all --parallel build:watch test:build:watch"
},
"dependencies": {
"@offirgolan/nise": "^4.1.0",
"@pollyjs/adapter": "^6.0.6",
"@pollyjs/utils": "^6.0.6",
"to-arraybuffer": "^1.0.1"
},
"devDependencies": {
"@pollyjs/core": "^6.0.6",
"@pollyjs/persister-rest": "^6.0.6",
"rollup": "^1.14.6"
}
}
================================================
FILE: packages/@pollyjs/adapter-xhr/rollup.config.test.js
================================================
import createBrowserTestConfig from '../../../scripts/rollup/browser.test.config';
export default [createBrowserTestConfig()];
================================================
FILE: packages/@pollyjs/adapter-xhr/src/index.js
================================================
import fakeXhr from '@offirgolan/nise/lib/fake-xhr';
import Adapter from '@pollyjs/adapter';
import { cloneArrayBuffer, isBufferUtf8Representable } from '@pollyjs/utils';
import { Buffer } from 'buffer/';
import bufferToArrayBuffer from 'to-arraybuffer';
import resolveXhr from './utils/resolve-xhr';
import serializeResponseHeaders from './utils/serialize-response-headers';
const SEND = Symbol();
const ABORT_HANDLER = Symbol();
const stubbedXhrs = new WeakSet();
const BINARY_RESPONSE_TYPES = ['arraybuffer', 'blob'];
export default class XHRAdapter extends Adapter {
static get id() {
return 'xhr';
}
get defaultOptions() {
return {
context: global
};
}
onConnect() {
const { context } = this.options;
const fakeXhrForContext = fakeXhr.fakeXMLHttpRequestFor(context);
this.assert('XHR global not found.', fakeXhrForContext.xhr.supportsXHR);
this.assert(
'Running concurrent XHR adapters is unsupported, stop any running Polly instances.',
!stubbedXhrs.has(context.XMLHttpRequest)
);
this.NativeXMLHttpRequest = context.XMLHttpRequest;
this.xhr = fakeXhrForContext.useFakeXMLHttpRequest();
this.xhr.onCreate = (xhr) => {
xhr[SEND] = xhr.send;
xhr.send = (body) => {
xhr[SEND](body);
this.handleRequest({
url: xhr.url,
method: xhr.method || 'GET',
headers: xhr.requestHeaders,
requestArguments: { xhr },
body
});
};
};
stubbedXhrs.add(context.XMLHttpRequest);
}
onDisconnect() {
const { context } = this.options;
stubbedXhrs.delete(context.XMLHttpRequest);
this.xhr.restore();
}
onRequest(pollyRequest) {
const { xhr } = pollyRequest.requestArguments;
if (xhr.aborted) {
pollyRequest.abort();
} else {
pollyRequest[ABORT_HANDLER] = () => pollyRequest.abort();
xhr.addEventListener('abort', pollyRequest[ABORT_HANDLER]);
}
}
async onFetchResponse(pollyRequest) {
const { xhr: fakeXhr } = pollyRequest.requestArguments;
const xhr = new this.NativeXMLHttpRequest();
xhr.open(
pollyRequest.method,
pollyRequest.url,
fakeXhr.async,
fakeXhr.username,
fakeXhr.password
);
xhr.async = fakeXhr.async;
if (BINARY_RESPONSE_TYPES.includes(fakeXhr.responseType)) {
xhr.responseType = 'arraybuffer';
}
if (fakeXhr.async) {
xhr.timeout = fakeXhr.timeout;
xhr.withCredentials = fakeXhr.withCredentials;
}
for (const h in pollyRequest.headers) {
xhr.setRequestHeader(h, pollyRequest.headers[h]);
}
await resolveXhr(xhr, pollyRequest.body);
let body = xhr.response;
let isBinary = false;
// responseType will either be `arraybuffer` or `text`
if (xhr.responseType === 'arraybuffer') {
let arrayBuffer = xhr.response;
/*
If the returned array buffer is not an instance of the global ArrayBuffer,
clone it in order to pass Buffer.from's instanceof check. This can happen
when using this adapter with a different context.
https://github.com/feross/buffer/issues/289
*/
if (
arrayBuffer &&
!(arrayBuffer instanceof ArrayBuffer) &&
'byteLength' in arrayBuffer
) {
arrayBuffer = cloneArrayBuffer(arrayBuffer);
}
const buffer = Buffer.from(arrayBuffer);
isBinary = !isBufferUtf8Representable(buffer);
body = buffer.toString(isBinary ? 'base64' : 'utf8');
}
return {
statusCode: xhr.status,
headers: serializeResponseHeaders(xhr.getAllResponseHeaders()),
encoding: isBinary ? 'base64' : undefined,
body
};
}
onRespond(pollyRequest, error) {
const { xhr } = pollyRequest.requestArguments;
if (pollyRequest[ABORT_HANDLER]) {
xhr.removeEventListener('abort', pollyRequest[ABORT_HANDLER]);
}
if (pollyRequest.aborted) {
return;
} else if (error) {
// If an error was received then call the `error` method on the fake XHR
// request provided by nise which will simulate a network error on the request.
// The onerror handler will be called and the status will be 0.
// https://github.com/sinonjs/nise/blob/v1.4.10/lib/fake-xhr/index.js#L614-L621
xhr.error();
} else {
const { statusCode, headers, body, encoding } = pollyRequest.response;
let responseBody = body;
if (encoding) {
const buffer = Buffer.from(body, encoding);
if (BINARY_RESPONSE_TYPES.includes(xhr.responseType)) {
responseBody = bufferToArrayBuffer(buffer);
} else {
responseBody = buffer.toString('utf8');
}
}
xhr.respond(statusCode, headers, responseBody);
}
}
}
================================================
FILE: packages/@pollyjs/adapter-xhr/src/utils/resolve-xhr.js
================================================
export default function resolveXhr(xhr, body) {
return new Promise((resolve) => {
xhr.send(body);
if (xhr.async) {
const { onreadystatechange } = xhr;
xhr.onreadystatechange = (...args) => {
onreadystatechange && onreadystatechange.apply(xhr, ...args);
xhr.readyState === XMLHttpRequest.DONE && resolve();
};
} else {
resolve();
}
});
}
================================================
FILE: packages/@pollyjs/adapter-xhr/src/utils/serialize-response-headers.js
================================================
/**
* Serialize response headers which is received as a string, into a pojo
*
* @param {String} responseHeaders
*/
export default function serializeResponseHeaders(responseHeaders) {
if (typeof responseHeaders !== 'string') {
return responseHeaders;
}
return responseHeaders.split('\n').reduce((headers, header) => {
const [key, value] = header.split(':');
if (key) {
headers[key] = value.replace(/(\r|\n|^\s+)/g, '');
}
return headers;
}, {});
}
================================================
FILE: packages/@pollyjs/adapter-xhr/tests/integration/adapter-test.js
================================================
import { Polly, setupMocha as setupPolly } from '@pollyjs/core';
import setupFetchRecord from '@pollyjs-tests/helpers/setup-fetch-record';
import adapterTests from '@pollyjs-tests/integration/adapter-tests';
import adapterBrowserTests from '@pollyjs-tests/integration/adapter-browser-tests';
import adapterIdentifierTests from '@pollyjs-tests/integration/adapter-identifier-tests';
import InMemoryPersister from '@pollyjs/persister-in-memory';
import { Buffer } from 'buffer/';
import xhrRequest from '../utils/xhr-request';
import XHRAdapter from '../../src';
class MockXMLHttpRequest {}
describe('Integration | XHR Adapter', function () {
setupPolly.beforeEach({
recordFailedRequests: true,
adapters: [XHRAdapter],
persister: InMemoryPersister
});
setupFetchRecord({ fetch: xhrRequest });
setupPolly.afterEach();
adapterTests();
adapterBrowserTests();
adapterIdentifierTests();
it('should handle aborting a request', async function () {
const { server } = this.polly;
const xhr = new XMLHttpRequest();
let abortEventCalled;
server
.any(this.recordUrl())
.on('request', () => xhr.abort())
.on('abort', () => (abortEventCalled = true))
.intercept((_, res) => {
res.sendStatus(200);
});
await this.fetchRecord({ xhr });
await this.polly.flush();
expect(abortEventCalled).to.equal(true);
});
it('should handle immediately aborting a request', async function () {
const { server } = this.polly;
const xhr = new XMLHttpRequest();
let abortEventCalled;
server
.any(this.recordUrl())
.on('abort', () => (abortEventCalled = true))
.intercept((_, res) => {
res.sendStatus(200);
});
const promise = this.fetchRecord({ xhr });
xhr.abort();
await promise;
await this.polly.flush();
expect(abortEventCalled).to.equal(true);
});
['arraybuffer', 'blob', 'text'].forEach((responseType) =>
it(`should be able to download binary content (${responseType})`, async function () {
const fetch = async () =>
Buffer.from(
await this.fetch('/assets/32x32.png', {
responseType
}).then((res) => res.arrayBuffer())
);
this.polly.disconnectFrom(XHRAdapter);
const nativeResponseBuffer = await fetch();
this.polly.connectTo(XHRAdapter);
const recordedResponseBuffer = await fetch();
const { recordingName, config } = this.polly;
await this.polly.stop();
this.polly = new Polly(recordingName, config);
this.polly.replay();
const replayedResponseBuffer = await fetch();
expect(nativeResponseBuffer.equals(recordedResponseBuffer)).to.equal(
true
);
expect(recordedResponseBuffer.equals(replayedResponseBuffer)).to.equal(
true
);
expect(nativeResponseBuffer.equals(replayedResponseBuffer)).to.equal(
true
);
})
);
});
describe('Integration | XHR Adapter | Init', function () {
describe('Context', function () {
it(`should assign context's XMLHttpRequest as the native XMLHttpRequest`, async function () {
const polly = new Polly('context', { adapters: [] });
const adapterOptions = {
xhr: {
context: { XMLHttpRequest: MockXMLHttpRequest }
}
};
polly.configure({
adapters: [XHRAdapter],
adapterOptions
});
expect(polly.adapters.get('xhr').NativeXMLHttpRequest).to.equal(
MockXMLHttpRequest
);
expect(polly.adapters.get('xhr').NativeXMLHttpRequest).to.not.equal(
adapterOptions.xhr.context.XMLHttpRequest
);
expect(function () {
polly.configure({
adapterOptions: { xhr: { context: {} } }
});
}).to.throw(/XHR global not found/);
await polly.stop();
});
});
describe('Concurrency', function () {
it('should prevent concurrent XHR adapter instances on the same context', async function () {
const one = new Polly('one');
const two = new Polly('two');
const three = new Polly('three', {
adapterOptions: {
xhr: {
context: { XMLHttpRequest: MockXMLHttpRequest }
}
}
});
one.connectTo(XHRAdapter);
expect(function () {
two.connectTo(XHRAdapter);
}).to.throw(/Running concurrent XHR adapters is unsupported/);
three.connectTo(XHRAdapter);
await one.stop();
await two.stop();
await three.stop();
});
it('should allow you to register new instances once stopped', async function () {
const one = new Polly('one');
const two = new Polly('two');
one.connectTo(XHRAdapter);
await one.stop();
expect(function () {
two.connectTo(XHRAdapter);
}).to.not.throw();
await one.stop();
await two.stop();
});
});
});
================================================
FILE: packages/@pollyjs/adapter-xhr/tests/utils/xhr-request.js
================================================
import serializeResponseHeaders from '../../src/utils/serialize-response-headers';
export default function request(url, obj = {}) {
return new Promise((resolve) => {
const xhr = obj.xhr || new XMLHttpRequest();
xhr.open(obj.method || 'GET', url);
if (obj.headers) {
for (const h in obj.headers) {
xhr.setRequestHeader(h, obj.headers[h]);
}
}
if (obj.responseType) {
xhr.responseType = obj.responseType;
}
xhr.onreadystatechange = () =>
xhr.readyState === XMLHttpRequest.DONE && resolve(xhr);
xhr.onerror = () => resolve(xhr);
xhr.send(obj.body);
}).then((xhr) => {
const responseBody =
xhr.status === 204 && xhr.response === '' ? null : xhr.response;
return new Response(responseBody, {
status: xhr.status || 500,
statusText: xhr.statusText,
headers: serializeResponseHeaders(xhr.getAllResponseHeaders())
});
});
}
================================================
FILE: packages/@pollyjs/adapter-xhr/types.d.ts
================================================
import Adapter from '@pollyjs/adapter';
export default class XHRAdapter extends Adapter<{
context?: any;
}> {}
================================================
FILE: packages/@pollyjs/cli/.eslintrc.js
================================================
module.exports = {
parserOptions: {
sourceType: 'script',
ecmaVersion: 2020
},
env: {
browser: false,
node: true
},
plugins: ['node'],
extends: ['plugin:node/recommended']
};
================================================
FILE: packages/@pollyjs/cli/CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.6](https://github.com/netflix/pollyjs/compare/v6.0.5...v6.0.6) (2023-07-20)
**Note:** Version bump only for package @pollyjs/cli
## [6.0.1](https://github.com/netflix/pollyjs/compare/v6.0.0...v6.0.1) (2021-12-06)
**Note:** Version bump only for package @pollyjs/cli
# [6.0.0](https://github.com/netflix/pollyjs/compare/v5.2.0...v6.0.0) (2021-11-30)
* chore!: Upgrade package dependencies (#421) ([dd23334](https://github.com/netflix/pollyjs/commit/dd23334fa9b64248e4c49c3616237bdc2f12f682)), closes [#421](https://github.com/netflix/pollyjs/issues/421)
* feat(ember)!: Upgrade to ember octane (#415) ([8559ef8](https://github.com/netflix/pollyjs/commit/8559ef8c600aefaec629870eac5f5c8953e18b16)), closes [#415](https://github.com/netflix/pollyjs/issues/415)
### BREAKING CHANGES
* Recording file name will no longer have trailing dashes
* @pollyjs dependencies have been moved to peer dependencies
## [5.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/v5.1.0...v5.1.1) (2021-06-02)
**Note:** Version bump only for package @pollyjs/cli
# [5.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/v4.3.0...v5.0.0) (2020-06-23)
**Note:** Version bump only for package @pollyjs/cli
# [4.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/v4.2.1...v4.3.0) (2020-05-18)
**Note:** Version bump only for package @pollyjs/cli
# [4.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/v4.1.0...v4.2.0) (2020-04-29)
**Note:** Version bump only for package @pollyjs/cli
# [4.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/v4.0.4...v4.1.0) (2020-04-23)
**Note:** Version bump only for package @pollyjs/cli
## [4.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/v4.0.1...v4.0.2) (2020-01-29)
**Note:** Version bump only for package @pollyjs/cli
# [4.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/v3.0.2...v4.0.0) (2020-01-13)
**Note:** Version bump only for package @pollyjs/cli
## [3.0.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/v3.0.0...v3.0.1) (2019-12-25)
**Note:** Version bump only for package @pollyjs/cli
# [3.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/v2.7.0...v3.0.0) (2019-12-18)
**Note:** Version bump only for package @pollyjs/cli
## [2.6.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/v2.6.2...v2.6.3) (2019-09-30)
**Note:** Version bump only for package @pollyjs/cli
# [2.6.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/v2.5.0...v2.6.0) (2019-07-17)
**Note:** Version bump only for package @pollyjs/cli
# [2.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/v2.0.0...v2.1.0) (2019-02-04)
**Note:** Version bump only for package @pollyjs/cli
# [2.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/v1.4.2...v2.0.0) (2019-01-29)
**Note:** Version bump only for package @pollyjs/cli
## [1.4.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/v1.4.0...v1.4.1) (2018-12-13)
**Note:** Version bump only for package @pollyjs/cli
## [1.3.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/v1.3.1...v1.3.2) (2018-11-29)
**Note:** Version bump only for package @pollyjs/cli
## [1.3.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/v1.2.0...v1.3.1) (2018-11-28)
**Note:** Version bump only for package @pollyjs/cli
# 1.2.0 (2018-09-16)
### Features
* Make recording size limit configurable ([#40](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/cli/issues/40)) ([d4be431](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/commit/d4be431))
## [1.0.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/@pollyjs/cli@1.0.2...@pollyjs/cli@1.0.3) (2018-08-22)
**Note:** Version bump only for package @pollyjs/cli
## [1.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/@pollyjs/cli@1.0.1...@pollyjs/cli@1.0.2) (2018-08-12)
**Note:** Version bump only for package @pollyjs/cli
## [1.0.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/@pollyjs/cli@1.0.0...@pollyjs/cli@1.0.1) (2018-08-12)
**Note:** Version bump only for package @pollyjs/cli
# [1.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/@pollyjs/cli@0.2.1...@pollyjs/cli@1.0.0) (2018-07-20)
**Note:** Version bump only for package @pollyjs/cli
## [0.2.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/@pollyjs/cli@0.2.0...@pollyjs/cli@0.2.1) (2018-06-29)
**Note:** Version bump only for package @pollyjs/cli
# [0.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/@pollyjs/cli@0.1.1...@pollyjs/cli@0.2.0) (2018-06-27)
### Features
* Make recording size limit configurable ([#40](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/cli/issues/40)) ([d4be431](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/commit/d4be431))
## [0.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli/compare/@pollyjs/cli@0.1.0...@pollyjs/cli@0.1.1) (2018-06-21)
**Note:** Version bump only for package @pollyjs/cli
================================================
FILE: packages/@pollyjs/cli/LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Netflix Inc and @pollyjs contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: packages/@pollyjs/cli/README.md
================================================
Record, Replay, and Stub HTTP Interactions
[](https://travis-ci.com/Netflix/pollyjs)
[](https://badge.fury.io/js/%40pollyjs%2Fcli)
[](http://www.apache.org/licenses/LICENSE-2.0)
The `@pollyjs/cli` package provides a standalone CLI to quickly get you setup
and ready to go.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/cli -g
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn global add @pollyjs/cli
```
## Documentation
Check out the [CLI](https://netflix.github.io/pollyjs/#/cli/overview)
documentation for more details.
## Usage
```text
Usage: polly [options] [command]
Options:
-v, --version output the version number
-h, --help output usage information
Commands:
listen|l [options] start the server and listen for requests
```
## License
Copyright (c) 2018 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
================================================
FILE: packages/@pollyjs/cli/bin/cli.js
================================================
#!/usr/bin/env node
// Provide a title to the process in `ps`
process.title = 'polly';
const Polly = require('@pollyjs/node-server');
const { program } = require('commander');
const version = require('../package.json').version;
program.name('polly').version(version, '-v, --version');
program
.command('listen')
.alias('l')
.description('start the server and listen for requests')
.option('-H, --host ', 'host')
.option('-p, --port ', 'port number', Polly.Defaults.port)
.option(
'-n, --api-namespace ',
'api namespace',
Polly.Defaults.apiNamespace
)
.option(
'-d, --recordings-dir ',
'recordings directory',
Polly.Defaults.recordingsDir
)
.option(
'-s, --recording-size-limit ',
'recording size limit',
Polly.Defaults.recordingSizeLimit
)
.option('-q, --quiet', 'disable logging')
.action(function (options) {
new Polly.Server(options).listen();
});
program.parse(process.argv);
// if cli was called with no arguments, show help.
if (program.args.length === 0) {
program.help();
}
================================================
FILE: packages/@pollyjs/cli/package.json
================================================
{
"name": "@pollyjs/cli",
"version": "6.0.6",
"description": "@pollyjs CLI",
"files": [
"bin"
],
"repository": "https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/cli",
"keywords": [
"polly",
"pollyjs",
"cli",
"server",
"listen"
],
"publishConfig": {
"access": "public"
},
"contributors": [
{
"name": "Jason Mitchell",
"email": "jason.mitchell.w@gmail.com"
},
{
"name": "Offir Golan",
"email": "offirgolan@gmail.com"
}
],
"license": "Apache-2.0",
"dependencies": {
"@pollyjs/node-server": "^6.0.6",
"commander": "^8.3.0"
},
"devDependencies": {
"npm-run-all": "^4.1.5",
"rimraf": "^3.0.2",
"rollup": "^1.14.6"
},
"bin": {
"polly": "./bin/cli.js"
}
}
================================================
FILE: packages/@pollyjs/core/CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.6](https://github.com/netflix/pollyjs/compare/v6.0.5...v6.0.6) (2023-07-20)
**Note:** Version bump only for package @pollyjs/core
## [6.0.5](https://github.com/netflix/pollyjs/compare/v6.0.4...v6.0.5) (2022-04-04)
**Note:** Version bump only for package @pollyjs/core
## [6.0.4](https://github.com/netflix/pollyjs/compare/v6.0.3...v6.0.4) (2021-12-10)
### Bug Fixes
* Update types for class methods ([#438](https://github.com/netflix/pollyjs/issues/438)) ([b88655a](https://github.com/netflix/pollyjs/commit/b88655ac1b4ca7348afd45e9aeaa50e998ea68d7))
## [6.0.3](https://github.com/netflix/pollyjs/compare/v6.0.2...v6.0.3) (2021-12-08)
### Bug Fixes
* A few more type fixes ([#437](https://github.com/netflix/pollyjs/issues/437)) ([5e837a2](https://github.com/netflix/pollyjs/commit/5e837a25d28393b764cb66bcae0b29e9273eabe8))
## [6.0.2](https://github.com/netflix/pollyjs/compare/v6.0.1...v6.0.2) (2021-12-07)
### Bug Fixes
* **core:** Fix types for registering adapters and persisters ([#435](https://github.com/netflix/pollyjs/issues/435)) ([cc2fa19](https://github.com/netflix/pollyjs/commit/cc2fa197a5c0a5fdef4602c4a207d31f3e677897))
## [6.0.1](https://github.com/netflix/pollyjs/compare/v6.0.0...v6.0.1) (2021-12-06)
### Bug Fixes
* **types:** add types.d.ts to package.files ([#431](https://github.com/netflix/pollyjs/issues/431)) ([113ee89](https://github.com/netflix/pollyjs/commit/113ee898bcf0467c5c48c15b53fc9198e2e91cb1))
# [6.0.0](https://github.com/netflix/pollyjs/compare/v5.2.0...v6.0.0) (2021-11-30)
* fix!: Upgrade url-parse (#426) ([c21ed04](https://github.com/netflix/pollyjs/commit/c21ed048ff9d87a3773458dcfb9758e4fa6582bf)), closes [#426](https://github.com/netflix/pollyjs/issues/426)
* feat!: Cleanup adapter and persister APIs (#429) ([06499fc](https://github.com/netflix/pollyjs/commit/06499fc2d85254b3329db2bec770d173ed32bca0)), closes [#429](https://github.com/netflix/pollyjs/issues/429)
* feat!: Improve logging and add logLevel (#427) ([bef3ee3](https://github.com/netflix/pollyjs/commit/bef3ee39f71dfc2fa4dbeb522dfba16d01243e9f)), closes [#427](https://github.com/netflix/pollyjs/issues/427)
* chore!: Upgrade package dependencies (#421) ([dd23334](https://github.com/netflix/pollyjs/commit/dd23334fa9b64248e4c49c3616237bdc2f12f682)), closes [#421](https://github.com/netflix/pollyjs/issues/421)
* feat!: Use base64 instead of hex encoding for binary data (#420) ([6bb9b36](https://github.com/netflix/pollyjs/commit/6bb9b36522d73f9c079735d9006a12376aee39ea)), closes [#420](https://github.com/netflix/pollyjs/issues/420)
* feat(ember)!: Upgrade to ember octane (#415) ([8559ef8](https://github.com/netflix/pollyjs/commit/8559ef8c600aefaec629870eac5f5c8953e18b16)), closes [#415](https://github.com/netflix/pollyjs/issues/415)
### BREAKING CHANGES
* Upgrade url-version to 1.5.0+ to fix CVE-2021-27515. This change could alter the final url generated for a request.
* - Adapter
- `passthroughRequest` renamed to `onFetchResponse`
- `respondToRequest` renamed to `onRespond`
- Persister
- `findRecording` renamed to `onFindRecording`
- `saveRecording` renamed to `onSaveRecording`
- `deleteRecording` renamed to `onDeleteRecording`
* The `logging` configuration option has now been replaced with `logLevel`. This allows for more fine-grain control over what should be logged as well as silencing logs altogether.
* Recording file name will no longer have trailing dashes
* Use the standard `encoding` field on the generated har file instead of `_isBinary` and use `base64` encoding instead of `hex` to reduce the payload size.
* @pollyjs dependencies have been moved to peer dependencies
## [5.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v5.1.0...v5.1.1) (2021-06-02)
**Note:** Version bump only for package @pollyjs/core
# [5.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v5.0.2...v5.1.0) (2020-12-12)
### Features
* **core:** Add `overrideRecordingName` and `configure` to public API ([#372](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/372)) ([cdbf513](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/cdbf513))
# [5.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v4.3.0...v5.0.0) (2020-06-23)
### Bug Fixes
* **core:** Compute order based on id and recording name ([#342](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/342)) ([42004d2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/42004d2))
### Features
* Remove deprecated Persister.name and Adapter.name ([#343](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/343)) ([1223ba0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/1223ba0))
### BREAKING CHANGES
* Persister.name and Adapter.name have been replaced with Persister.id and Adapter.id
* **core:** A request's order is will now be computed based on its id and the recording name it will be persisted to.
# [4.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v4.2.1...v4.3.0) (2020-05-18)
### Features
* **core:** Add `flushRequestsOnStop` configuration option ([#335](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/335)) ([ab4a2e1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/ab4a2e1))
## [4.2.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v4.2.0...v4.2.1) (2020-04-30)
### Bug Fixes
* **adapter-node-http:** Improve binary response body handling ([#329](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/329)) ([9466989](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/9466989))
# [4.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v4.0.4...v4.1.0) (2020-04-23)
### Bug Fixes
* Improve abort handling ([#320](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/320)) ([cc46bb4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/cc46bb4))
* Legacy persisters and adapters should register ([#325](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/325)) ([8fd4d19](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/8fd4d19))
### Features
* **persister:** Add `disableSortingHarEntries` option ([#321](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/321)) ([0003c0e](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/0003c0e))
## [4.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v4.0.3...v4.0.4) (2020-03-21)
### Bug Fixes
* Deprecates adapter & persister `name` in favor of `id` ([#310](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/310)) ([41dd093](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/41dd093))
## [4.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v4.0.1...v4.0.2) (2020-01-29)
**Note:** Version bump only for package @pollyjs/core
# [4.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v3.0.2...v4.0.0) (2020-01-13)
### Bug Fixes
* **core:** Disconnect from all adapters when `pause` is called ([#291](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/291)) ([5c655bf](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/5c655bf))
### Features
* **core:** Provide the request as an argument to matchRequestsBy methods ([#293](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/293)) ([4e3163f](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/4e3163f))
* **core:** Remove deprecated `recordIfExpired` option ([#295](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/295)) ([5fe991d](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/5fe991d))
### BREAKING CHANGES
* **core:** `recordIfExpired` is no longer supported, please use `expiryStrategy` instead.
* **core:** Calling `polly.pause()` will now disconnect from all connected adapters instead of setting the mode to passthrough. Calling `polly.play()` will reconnect to the disconnected adapters before pause was called.
# [3.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v2.7.0...v3.0.0) (2019-12-18)
**Note:** Version bump only for package @pollyjs/core
## [2.6.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v2.6.2...v2.6.3) (2019-09-30)
### Bug Fixes
* use watch strategy ([#236](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/236)) ([5b4edf3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/5b4edf3))
## [2.6.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v2.6.1...v2.6.2) (2019-08-05)
**Note:** Version bump only for package @pollyjs/core
## [2.6.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v2.6.0...v2.6.1) (2019-08-01)
**Note:** Version bump only for package @pollyjs/core
# [2.6.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v2.5.0...v2.6.0) (2019-07-17)
### Features
* **core:** Improved logging ([#217](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/217)) ([3e876a8](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/3e876a8))
* PollyError and improved adapter error handling ([#234](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/234)) ([23a2127](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/23a2127))
# [2.5.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v2.4.0...v2.5.0) (2019-06-06)
**Note:** Version bump only for package @pollyjs/core
# [2.4.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v2.3.2...v2.4.0) (2019-04-27)
### Features
* **core:** Improved control flow with `times` and `stopPropagation` ([#202](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/202)) ([2c8231e](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/2c8231e))
# [2.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v2.2.0...v2.3.0) (2019-02-27)
### Features
* **core:** Filter requests matched by a route handler ([#189](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/189)) ([5d57c32](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/5d57c32))
# [2.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v2.1.0...v2.2.0) (2019-02-20)
### Features
* Add `error` event and improve error handling ([#185](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/185)) ([3694ebc](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/3694ebc))
# [2.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v2.0.0...v2.1.0) (2019-02-04)
### Features
* **core:** Add removeHeader, removeHeaders, and allow empty headers ([#176](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/176)) ([1dfae5a](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/1dfae5a))
# [2.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v1.4.2...v2.0.0) (2019-01-29)
### Features
* Make PollyRequest.respond accept a response object ([#168](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/168)) ([5b07b26](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/5b07b26))
* feat(adapter-node-http): Use `nock` under the hood instead of custom implementation (#166) ([62374f4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/62374f4)), closes [#166](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/166)
### BREAKING CHANGES
* The node-http adapter no longer accepts the `transports` option
* Any adapters calling `pollyRequest.respond` should pass it a response object instead of the previous 3 arguments (statusCode, headers, body).
## [1.4.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v1.4.1...v1.4.2) (2019-01-16)
### Bug Fixes
* **adapter-node-http:** Fix unhandled rejection if connection fails ([#160](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/160)) ([12fcfa7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/12fcfa7))
## [1.4.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v1.4.0...v1.4.1) (2018-12-13)
**Note:** Version bump only for package @pollyjs/core
# [1.4.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v1.3.2...v1.4.0) (2018-12-07)
**Note:** Version bump only for package @pollyjs/core
## [1.3.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v1.3.1...v1.3.2) (2018-11-29)
**Note:** Version bump only for package @pollyjs/core
## [1.3.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/v1.2.0...v1.3.1) (2018-11-28)
### Bug Fixes
* Support URL objects ([#139](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/139)) ([cf0d755](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/cf0d755))
* **core:** Handle trailing slashes when generating route names ([#142](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/142)) ([19147f7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/19147f7))
* **core:** Ignore `context` options from being deep merged ([#144](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/144)) ([2123d83](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/2123d83))
* **core:** Support multiple handlers for same paths ([#141](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/141)) ([79e04b8](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/79e04b8))
### Features
* **core:** Support custom functions in matchRequestsBy config options ([#138](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/138)) ([626a84c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/626a84c))
* Add an onIdentifyRequest hook to allow adapter level serialization ([#140](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/140)) ([548002c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/548002c))
# 1.2.0 (2018-09-16)
### Bug Fixes
* Changes self to global, rollup-plugin-node-globals makes isomorphic ([#54](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/54)) ([3811e9d](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/3811e9d))
* Correctly normalize relative URLs ([b9b23cd](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/b9b23cd))
* Creator cleanup and persister assertion ([#67](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/67)) ([19fee5a](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/19fee5a))
* Improve support for relative URLs ([#78](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/78)) ([2c0083e](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/2c0083e)), closes [#76](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/76)
* Proxy route.params onto the request instead of mutating req ([5bcd4f9](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/5bcd4f9))
* **adapter-puppeteer:** Do not intercept CORS preflight requests ([#90](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/90)) ([53ad433](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/53ad433))
* **core:** Freeze request after emitting afterResponse. ([66a2b64](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/66a2b64))
* **core:** Set `url` on the fetch Response object ([#44](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/44)) ([f5980cf](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/f5980cf)), closes [#43](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/43)
### Features
* Abort and passthrough from an intercept ([#57](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/57)) ([4ebacb8](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/4ebacb8))
* Class events and EventEmitter ([#52](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/52)) ([0a3d591](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/0a3d591))
* Cleanup event handler logic + rename some event names ([78dbb5d](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/78dbb5d))
* Convert recordings to be HAR compliant ([#45](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/45)) ([e622640](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/e622640))
* Custom persister support ([8bb313c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/8bb313c))
* Fetch adapter support for `context` provided via adapterOptions ([#66](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/66)) ([82ebd09](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/82ebd09))
* Improved adapter and persister registration ([#62](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/62)) ([164dbac](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/164dbac))
* Keyed persister & adapter options ([#60](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/60)) ([29ed8e1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/29ed8e1))
* Move more response methods to shared base class ([#74](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/74)) ([4f845e5](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/4f845e5))
* Node File System Persister ([#61](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/61)) ([0a0eeca](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/0a0eeca))
* Presets persisterOptions.host to the node server default ([0b47838](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/0b47838))
* Puppeteer Adapter ([#64](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/64)) ([f902c6d](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/f902c6d))
* Use status code 204 in place of 404. ([#5](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/5)) ([930c492](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/930c492))
* **core:** Add `json` property to `Request` ([bb8e1cb](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/bb8e1cb)), closes [#7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/7)
* **core:** Default `Response` status code to 200 ([f42a281](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/f42a281)), closes [#6](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/6)
* Wait for all handled requests to resolve via `.flush()` ([#75](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/75)) ([a3113b7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/a3113b7))
* **core:** Normalize headers by lower-casing all keys ([#42](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/42)) ([02a4767](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/02a4767))
* **core:** Server level configuration ([#80](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/80)) ([0f32d9b](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/0f32d9b))
* **persister:** Add `keepUnusedRequests` config option ([#108](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/108)) ([3f5f5b2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/3f5f5b2))
* **persister:** Cache recordings ([#31](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/31)) ([a04d7a7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/a04d7a7))
### Reverts
* Add `json` property to `Request` ([4ea50e8](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/4ea50e8))
### BREAKING CHANGES
* __Adapters__
```js
import { XHRAdapter, FetchAdapter } from '@pollyjs/core';
// Register the xhr adapter so its accessible by all future polly instances
Polly.register(XHRAdapter);
polly.configure({
adapters: ['xhr', FetchAdapter]
});
```
__Persister__
```js
import { LocalStoragePersister, RESTPersister } from '@pollyjs/core';
// Register the local-storage persister so its accessible by all future polly instances
Polly.register(LocalStoragePersister);
polly.configure({
persister: 'local-storage'
});
polly.configure({
persister: RESTPersister
});
```
* Recordings now produce HAR compliant json. Please delete existing recordings.
* **core:** With this change, request ids will resolve to a different hash meaning that users will have to rerecord.
* Relative URLs will have different hashes and will
require to re-record.
## [1.1.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/@pollyjs/core@1.1.3...@pollyjs/core@1.1.4) (2018-08-22)
**Note:** Version bump only for package @pollyjs/core
## [1.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/@pollyjs/core@1.1.0...@pollyjs/core@1.1.1) (2018-08-09)
**Note:** Version bump only for package @pollyjs/core
# [1.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/@pollyjs/core@1.0.0...@pollyjs/core@1.1.0) (2018-07-26)
### Bug Fixes
* Improve support for relative URLs ([#78](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/78)) ([2c0083e](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/2c0083e)), closes [#76](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/76)
### Features
* Move more response methods to shared base class ([#74](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/74)) ([4f845e5](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/4f845e5))
* Wait for all handled requests to resolve via `.flush()` ([#75](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/75)) ([a3113b7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/a3113b7))
# [1.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/@pollyjs/core@0.5.0...@pollyjs/core@1.0.0) (2018-07-20)
### Bug Fixes
* Changes self to global, rollup-plugin-node-globals makes isomorphic ([#54](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/54)) ([3811e9d](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/3811e9d))
* Creator cleanup and persister assertion ([#67](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/67)) ([19fee5a](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/19fee5a))
### Features
* Abort and passthrough from an intercept ([#57](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/57)) ([4ebacb8](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/4ebacb8))
* Class events and EventEmitter ([#52](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/52)) ([0a3d591](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/0a3d591))
* Convert recordings to be HAR compliant ([#45](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/45)) ([e622640](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/e622640))
* Fetch adapter support for `context` provided via adapterOptions ([#66](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/66)) ([82ebd09](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/82ebd09))
* Improved adapter and persister registration ([#62](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/62)) ([164dbac](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/164dbac))
* Keyed persister & adapter options ([#60](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/60)) ([29ed8e1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/29ed8e1))
* Node File System Persister ([#61](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/61)) ([0a0eeca](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/0a0eeca))
* Presets persisterOptions.host to the node server default ([0b47838](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/0b47838))
* Puppeteer Adapter ([#64](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/64)) ([f902c6d](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/f902c6d))
### BREAKING CHANGES
* __Adapters__
```js
import { XHRAdapter, FetchAdapter } from '@pollyjs/core';
// Register the xhr adapter so its accessible by all future polly instances
Polly.register(XHRAdapter);
polly.configure({
adapters: ['xhr', FetchAdapter]
});
```
__Persister__
```js
import { LocalStoragePersister, RESTPersister } from '@pollyjs/core';
// Register the local-storage persister so its accessible by all future polly instances
Polly.register(LocalStoragePersister);
polly.configure({
persister: 'local-storage'
});
polly.configure({
persister: RESTPersister
});
```
* Recordings now produce HAR compliant json. Please delete existing recordings.
# [0.5.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/@pollyjs/core@0.4.0...@pollyjs/core@0.5.0) (2018-06-27)
### Bug Fixes
* **core:** Set `url` on the fetch Response object ([#44](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/44)) ([f5980cf](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/f5980cf)), closes [#43](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/issues/43)
### Features
* **core:** Normalize headers by lower-casing all keys ([#42](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/42)) ([02a4767](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/02a4767))
### BREAKING CHANGES
* **core:** With this change, request ids will resolve to a different hash meaning that users will have to rerecord.
# [0.4.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/@pollyjs/core@0.3.0...@pollyjs/core@0.4.0) (2018-06-22)
### Bug Fixes
* Correctly normalize relative URLs ([b9b23cd](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/b9b23cd))
### BREAKING CHANGES
* Relative URLs will have different hashes and will
require to re-record.
# [0.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/@pollyjs/core@0.2.0...@pollyjs/core@0.3.0) (2018-06-21)
### Features
* **persister:** Cache recordings ([#31](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/core/issues/31)) ([a04d7a7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/a04d7a7))
# [0.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/compare/@pollyjs/core@0.1.0...@pollyjs/core@0.2.0) (2018-06-16)
### Features
* Custom persister support ([8bb313c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core/commit/8bb313c))
================================================
FILE: packages/@pollyjs/core/LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Netflix Inc and @pollyjs contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: packages/@pollyjs/core/README.md
================================================
Record, Replay, and Stub HTTP Interactions
[](https://travis-ci.com/Netflix/pollyjs)
[](https://badge.fury.io/js/%40pollyjs%2Fcore)
[](http://www.apache.org/licenses/LICENSE-2.0)
Polly.JS is a standalone, framework-agnostic JavaScript library that enables recording, replaying, and stubbing of HTTP interactions. By tapping into multiple request APIs across both Node & the browser, Polly.JS is able to mock requests and responses with little to no configuration while giving you the ability to take full control of each request with a simple, powerful, and intuitive API.
> Interested in contributing or just seeing Polly in action? Head over to [CONTRIBUTING.md](CONTRIBUTING.md) to learn how to spin up the project!
## Why Polly?
Keeping fixtures and factories in parity with your APIs can be a time consuming process.
Polly alleviates this process by recording and maintaining actual server responses while also staying flexible.
- Record your test suite's HTTP interactions and replay them during future test runs for fast, deterministic, accurate tests.
- Use Polly's client-side server to modify or intercept requests and responses to simulate different application states (e.g. loading, error, etc.).
## Features
- 🚀 Node & Browser Support
- ⚡️️ Simple, Powerful, & Intuitive API
- 💎 First Class Mocha & QUnit Test Helpers
- 🔥 Intercept, Pass-Through, and Attach Events
- 📼 Record to Disk or Local Storage
- ⏱ Slow Down or Speed Up Time
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/core -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/core -D
```
## Getting Started
Check out the [Quick Start](https://netflix.github.io/pollyjs/#/quick-start) documentation to get started.
## Usage
Let's take a look at what an example test case would look like using Polly.
```js
import { Polly } from '@pollyjs/core';
import XHRAdapter from '@pollyjs/adapter-xhr';
import FetchAdapter from '@pollyjs/adapter-fetch';
import RESTPersister from '@pollyjs/persister-rest';
/*
Register the adapters and persisters we want to use. This way all future
polly instances can access them by name/id.
*/
Polly.register(XHRAdapter);
Polly.register(FetchAdapter);
Polly.register(RESTPersister);
describe('Netflix Homepage', function () {
it('should be able to sign in', async function () {
/*
Create a new polly instance.
Connect Polly to both fetch and XHR browser APIs. By default, it will
record any requests that it hasn't yet seen while replaying ones it
has already recorded.
*/
const polly = new Polly('Sign In', {
adapters: ['xhr', 'fetch'],
persister: 'rest'
});
const { server } = polly;
/* Intercept all Google Analytic requests and respond with a 200 */
server
.get('/google-analytics/*path')
.intercept((req, res) => res.sendStatus(200));
/* Pass-through all GET requests to /coverage */
server.get('/coverage').passthrough();
/* start: pseudo test code */
await visit('/login');
await fillIn('email', 'polly@netflix.com');
await fillIn('password', '@pollyjs');
await submit();
/* end: pseudo test code */
expect(location.pathname).to.equal('/browse');
/*
Calling `stop` will persist requests as well as disconnect from any
connected browser APIs (e.g. fetch or XHR).
*/
await polly.stop();
});
});
```
The above test case would generate the following [HAR](http://www.softwareishard.com/blog/har-12-spec/)
file which Polly will use to replay the sign-in response when the test is rerun:
```json
{
"log": {
"_recordingName": "Sign In",
"browser": {
"name": "Chrome",
"version": "67.0"
},
"creator": {
"name": "Polly.JS",
"version": "0.5.0",
"comment": "persister:rest"
},
"entries": [
{
"_id": "06f06e6d125cbb80896c41786f9a696a",
"_order": 0,
"cache": {},
"request": {
"bodySize": 51,
"cookies": [],
"headers": [
{
"name": "content-type",
"value": "application/json; charset=utf-8"
}
],
"headersSize": 97,
"httpVersion": "HTTP/1.1",
"method": "POST",
"postData": {
"mimeType": "application/json; charset=utf-8",
"text": "{\"email\":\"polly@netflix.com\",\"password\":\"@pollyjs\"}"
},
"queryString": [],
"url": "https://netflix.com/api/v1/login"
},
"response": {
"bodySize": 0,
"content": {
"mimeType": "text/plain; charset=utf-8",
"size": 0
},
"cookies": [],
"headers": [],
"headersSize": 0,
"httpVersion": "HTTP/1.1",
"redirectURL": "",
"status": 200,
"statusText": "OK"
},
"startedDateTime": "2018-06-29T17:31:55.348Z",
"time": 11,
"timings": {
"blocked": -1,
"connect": -1,
"dns": -1,
"receive": 0,
"send": 0,
"ssl": -1,
"wait": 11
}
}
],
"pages": [],
"version": "1.2"
}
}
```
## License
Copyright (c) 2018 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
================================================
FILE: packages/@pollyjs/core/package.json
================================================
{
"name": "@pollyjs/core",
"version": "6.0.6",
"description": "Record, replay, and stub HTTP Interactions",
"main": "dist/cjs/pollyjs-core.js",
"module": "dist/es/pollyjs-core.js",
"browser": "dist/umd/pollyjs-core.js",
"types": "types.d.ts",
"files": [
"src",
"dist",
"types.d.ts"
],
"repository": "https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core",
"scripts": {
"build": "rollup -c ../../../scripts/rollup/default.config.js",
"test:build": "rollup -c rollup.config.test.js",
"test:build:watch": "rollup -c rollup.config.test.js -w",
"build:watch": "yarn build -w",
"watch-all": "npm-run-all --parallel build:watch test:build:watch"
},
"keywords": [
"polly",
"pollyjs",
"vcr",
"record",
"replay",
"recorder",
"test",
"mock"
],
"publishConfig": {
"access": "public"
},
"contributors": [
{
"name": "Jason Mitchell",
"email": "jason.mitchell.w@gmail.com"
},
{
"name": "Offir Golan",
"email": "offirgolan@gmail.com"
}
],
"license": "Apache-2.0",
"dependencies": {
"@pollyjs/utils": "^6.0.6",
"@sindresorhus/fnv1a": "^2.0.1",
"blueimp-md5": "^2.19.0",
"fast-json-stable-stringify": "^2.1.0",
"is-absolute-url": "^3.0.3",
"lodash-es": "^4.17.21",
"loglevel": "^1.8.0",
"route-recognizer": "^0.3.4",
"slugify": "^1.6.3"
},
"devDependencies": {
"@pollyjs/adapter": "^6.0.6",
"@pollyjs/persister": "^6.0.6",
"rollup": "^1.14.6"
}
}
================================================
FILE: packages/@pollyjs/core/rollup.config.test.js
================================================
import createNodeTestConfig from '../../../scripts/rollup/node.test.config';
import createBrowserTestConfig from '../../../scripts/rollup/browser.test.config';
export default [createNodeTestConfig(), createBrowserTestConfig()];
================================================
FILE: packages/@pollyjs/core/src/-private/container.js
================================================
import { assert } from '@pollyjs/utils';
function keyFor(Factory) {
return `${Factory.type}:${Factory.id}`;
}
export class Container {
constructor() {
this._registry = new Map();
}
/**
* Register a factory onto the container.
*
* @param {Function} Factory
*/
register(Factory) {
assert(
`Attempted to register ${Factory} but invalid factory provided. Expected function, received: "${typeof Factory}"`,
typeof Factory === 'function'
);
const { type } = Factory;
const name = Factory.id;
assert(
`Invalid registration id provided. Expected string, received: "${typeof name}"`,
typeof name === 'string'
);
assert(
`Invalid registration type provided. Expected string, received: "${typeof type}"`,
typeof type === 'string'
);
this._registry.set(keyFor(Factory), Factory);
}
/**
* Unregister a factory from the container via a key (e.g. `adapter:fetch`)
* or Factory class.
*
* @param {String|Function} keyOrFactory
*/
unregister(keyOrFactory) {
const { _registry: registry } = this;
const key =
typeof keyOrFactory === 'function' ? keyFor(keyOrFactory) : keyOrFactory;
registry.delete(key);
}
/**
* Lookup a factory by the given key (e.g. `adapter:fetch`)
*
* @param {String} key
* @returns {Function}
*/
lookup(key) {
return this._registry.get(key) || null;
}
/**
* Check if a factory has been registered via a key (e.g. `adapter:fetch`)
* or Factory class.
*
* @param {String|Function} keyOrFactory
* @returns {Boolean}
*/
has(keyOrFactory) {
const { _registry: registry } = this;
const key =
typeof keyOrFactory === 'function' ? keyFor(keyOrFactory) : keyOrFactory;
return registry.has(key);
}
}
================================================
FILE: packages/@pollyjs/core/src/-private/event-emitter.js
================================================
import { assert } from '@pollyjs/utils';
import isObjectLike from 'lodash-es/isObjectLike';
import cancelFnAfterNTimes from '../utils/cancel-fn-after-n-times';
import { validateTimesOption } from '../utils/validators';
import Event from './event';
const EVENTS = Symbol();
const EVENT_NAMES = Symbol();
function assertEventName(eventName, eventNames) {
assert(
`Invalid event name provided. Expected string, received: "${typeof eventName}".`,
typeof eventName === 'string'
);
assert(
`Invalid event name provided: "${eventName}". Possible events: ${[
...eventNames
].join(', ')}.`,
eventNames.has(eventName)
);
}
function assertListener(listener) {
assert(
`Invalid listener provided. Expected function, received: "${typeof listener}".`,
typeof listener === 'function'
);
}
export default class EventEmitter {
/**
* @constructor
* @param {Object} options
* @param {String[]} options.eventNames - Supported events
*/
constructor(options = {}) {
const { eventNames } = options;
assert(
'An array of supported events must be provided via the `eventNames` option.',
Array.isArray(eventNames) && eventNames.length > 0
);
this[EVENTS] = new Map();
this[EVENT_NAMES] = new Set(eventNames);
}
/**
* Returns an array listing the events for which the emitter has
* registered listeners
*
* @returns {String[]}
*/
eventNames() {
const eventNames = [];
this[EVENTS].forEach(
(_, eventName) =>
this.hasListeners(eventName) && eventNames.push(eventName)
);
return eventNames;
}
/**
* Adds the `listener` function to the end of the listeners array for the
* event named `eventName`
*
* @param {String} eventName - The name of the event
* @param {Function} listener - The callback function
* @param {Object} [options={}]
* @param {Number} options.times - listener will be cancelled after this many times
* @returns {EventEmitter}
*/
on(eventName, listener, options = {}) {
assertEventName(eventName, this[EVENT_NAMES]);
assertListener(listener);
const events = this[EVENTS];
const { times } = options;
if (!events.has(eventName)) {
events.set(eventName, new Set());
}
if (times) {
validateTimesOption(times);
const tempListener = cancelFnAfterNTimes(listener, times, () =>
this.off(eventName, tempListener)
);
/*
Remove any existing listener or tempListener that match this one.
For example, if the following would get called:
this.on('request', listener);
this.on('request', listener, { times: 1 });
We want to make sure that there is only one instance of the given
listener for the given event.
*/
this.off(eventName, listener);
// Save the original listener on the temp one so we can easily match it
// given the original.
tempListener.listener = listener;
listener = tempListener;
}
events.get(eventName).add(listener);
return this;
}
/**
* Adds a one-time `listener` function for the event named `eventName`.
* The next time `eventName` is triggered, this listener is removed and
* then invoked.
*
* @param {String} eventName - The name of the event
* @param {Function} listener - The callback function
* @param {Object} [options={}]
* @returns {EventEmitter}
*/
once(eventName, listener, options = {}) {
this.on(eventName, listener, { ...options, times: 1 });
return this;
}
/**
* Removes the specified `listener` from the listener array for
* the event named `eventName`. If `listener` is not provided then it removes
* all listeners, or those of the specified `eventName`.
*
* @param {String} eventName - The name of the event
* @param {Function} [listener] - The callback function
* @returns {EventEmitter}
*/
off(eventName, listener) {
assertEventName(eventName, this[EVENT_NAMES]);
const events = this[EVENTS];
if (this.hasListeners(eventName)) {
if (typeof listener === 'function') {
events.get(eventName).delete(listener);
// Remove any temp listeners that use the provided listener
this.listeners(eventName).forEach((l) => {
if (l.listener === listener) {
events.get(eventName).delete(l);
}
});
} else {
events.get(eventName).clear(eventName);
}
}
return this;
}
/**
* Returns a copy of the array of listeners for the event named `eventName`.
*
* @param {String} eventName - The name of the event
* @returns {Function[]}
*/
listeners(eventName) {
assertEventName(eventName, this[EVENT_NAMES]);
return this.hasListeners(eventName) ? [...this[EVENTS].get(eventName)] : [];
}
/**
* Returns `true` if there are any listeners for the event named `eventName`
* or `false` otherwise.
*
* @param {String} eventName - The name of the event
* @returns {Boolean}
*/
hasListeners(eventName) {
assertEventName(eventName, this[EVENT_NAMES]);
const events = this[EVENTS];
return events.has(eventName) && events.get(eventName).size > 0;
}
/**
* Asynchronously calls each of the `listeners` registered for the event named
* `eventName`, in the order they were registered, passing the supplied
* arguments to each.
*
* Returns a promise that will resolve to `false` if a listener stopped
* propagation, `true` otherwise.
*
* @async
* @param {String} eventName - The name of the event
* @param {any} ...args - The arguments to pass to the listeners
* @returns {Promise}
*/
async emit(eventName, ...args) {
assertEventName(eventName, this[EVENT_NAMES]);
const event = new Event(eventName);
for (const listener of this.listeners(eventName)) {
await listener(...args, event);
if (event.shouldStopPropagating) {
return false;
}
}
return true;
}
/**
* Asynchronously and concurrently calls each of the `listeners` registered
* for the event named `eventName`, in the order they were registered,
* passing the supplied arguments to each.
*
* Returns a promise that will resolve to `false` if a listener stopped
* propagation, `true` otherwise.
*
* @async
* @param {String} eventName - The name of the event
* @param {any} ...args - The arguments to pass to the listeners
* @returns {Promise}
*/
async emitParallel(eventName, ...args) {
assertEventName(eventName, this[EVENT_NAMES]);
const event = new Event(eventName);
await Promise.all(
this.listeners(eventName).map((listener) => listener(...args, event))
);
if (event.shouldStopPropagating) {
return false;
}
return true;
}
/**
* Synchronously calls each of the `listeners` registered for the event named
* `eventName`, in the order they were registered, passing the supplied
* arguments to each.
*
* Throws if a listener's return value is promise-like.
*
* Returns`false` if a listener stopped propagation, `true` otherwise.
*
* @param {String} eventName - The name of the event
* @param {any} ...args - The arguments to pass to the listeners
* @returns {Boolean}
*/
emitSync(eventName, ...args) {
assertEventName(eventName, this[EVENT_NAMES]);
const event = new Event(eventName);
for (const listener of this.listeners(eventName)) {
const returnValue = listener(...args, event);
assert(
`Attempted to emit a synchronous event "${eventName}" but an asynchronous listener was called.`,
!(isObjectLike(returnValue) && typeof returnValue.then === 'function')
);
if (event.shouldStopPropagating) {
return false;
}
}
return true;
}
}
================================================
FILE: packages/@pollyjs/core/src/-private/event.js
================================================
import { assert } from '@pollyjs/utils';
const STOP_PROPAGATION = Symbol();
export default class Event {
constructor(type, props) {
assert(
`Invalid type provided. Expected a non-empty string, received: "${typeof type}".`,
type && typeof type === 'string'
);
Object.defineProperty(this, 'type', { value: type });
// eslint-disable-next-line no-restricted-properties
Object.assign(this, props || {});
this[STOP_PROPAGATION] = false;
}
stopPropagation() {
this[STOP_PROPAGATION] = true;
}
get shouldStopPropagating() {
return this[STOP_PROPAGATION];
}
}
================================================
FILE: packages/@pollyjs/core/src/-private/http-base.js
================================================
import stringify from 'fast-json-stable-stringify';
import HTTPHeaders from '../utils/http-headers';
const { freeze } = Object;
const { parse } = JSON;
export default class HTTPBase {
constructor() {
this.headers = new HTTPHeaders();
}
getHeader(name) {
return this.headers[name];
}
setHeader(name, value) {
this.headers[name] = value;
return this;
}
setHeaders(headers = {}) {
for (const name in headers) {
this.setHeader(name, headers[name]);
}
return this;
}
removeHeader(name) {
this.setHeader(name, null);
return this;
}
removeHeaders(headers = []) {
for (const name of headers) {
this.removeHeader(name);
}
return this;
}
hasHeader(name) {
return !!this.getHeader(name);
}
type(type) {
return this.setHeader('Content-Type', type);
}
send(data) {
let body = data;
switch (typeof body) {
case 'string':
// String defaulting to html
if (!this.hasHeader('Content-Type')) {
this.type('text/html');
}
break;
case 'boolean':
case 'number':
case 'object':
if (body === null) {
body = '';
} else {
return this.json(body);
}
break;
}
if (typeof body === 'string') {
const contentType = this.getHeader('Content-Type');
// Write strings in utf-8
if (contentType && !contentType.includes('charset')) {
this.type(`${contentType}; charset=utf-8`);
}
}
this.body = body;
return this;
}
json(obj) {
if (!this.hasHeader('Content-Type')) {
this.type('application/json');
}
return this.send(stringify(obj));
}
jsonBody() {
return parse(this.body);
}
end() {
freeze(this);
freeze(this.headers);
return this;
}
}
================================================
FILE: packages/@pollyjs/core/src/-private/interceptor.js
================================================
import Event from './event';
const ABORT = Symbol();
const PASSTHROUGH = Symbol();
function setDefaults(interceptor) {
interceptor[ABORT] = false;
interceptor[PASSTHROUGH] = false;
}
export default class Interceptor extends Event {
constructor() {
super('intercept');
setDefaults(this);
}
abort() {
setDefaults(this);
this[ABORT] = true;
}
passthrough() {
setDefaults(this);
this[PASSTHROUGH] = true;
}
get shouldAbort() {
return this[ABORT];
}
get shouldPassthrough() {
return this[PASSTHROUGH];
}
get shouldIntercept() {
return !this.shouldAbort && !this.shouldPassthrough;
}
}
================================================
FILE: packages/@pollyjs/core/src/-private/logger.js
================================================
import { ACTIONS } from '@pollyjs/utils';
import logLevel from 'loglevel';
const FORMATTED_ACTIONS = {
[ACTIONS.RECORD]: 'Recorded',
[ACTIONS.REPLAY]: 'Replayed',
[ACTIONS.INTERCEPT]: 'Intercepted',
[ACTIONS.PASSTHROUGH]: 'Passthrough'
};
export default class Logger {
constructor(polly) {
this.polly = polly;
this.log = logLevel.getLogger(`@pollyjs/core:${this.polly.recordingName}`);
this.log.setLevel(polly.config.logLevel);
}
connect() {
this._middleware = this.polly.server
.any()
.on('error', (...args) => this.logRequestError(...args))
.on('request', (...args) => this.logRequest(...args))
.on('response', (...args) => this.logRequestResponse(...args));
}
disconnect() {
this._middleware.off('error');
this._middleware.off('response');
}
logRequest(request) {
const { log } = request;
const debug = log.getLevel() <= log.levels.DEBUG;
log.info(
`Request: ${request.method} ${request.url}`,
...(debug ? [{ request }] : [])
);
}
logRequestResponse(request, response) {
const { log } = request;
const debug = log.getLevel() <= log.levels.DEBUG;
log.info(
`Response: ${FORMATTED_ACTIONS[request.action]} ➞ ${request.method} ${
request.url
} ${response.statusCode} • ${request.responseTime}ms`,
...(debug ? [{ request, response }] : [])
);
}
logRequestError(request, error) {
const { log } = request;
const debug = log.getLevel() <= log.levels.DEBUG;
log.error(
`Errored ➞ ${request.method} ${request.url}`,
error,
...(debug ? [{ request }] : [])
);
}
}
================================================
FILE: packages/@pollyjs/core/src/-private/request.js
================================================
import md5 from 'blueimp-md5';
import stringify from 'fast-json-stable-stringify';
import isAbsoluteUrl from 'is-absolute-url';
import { URL, assert, timestamp } from '@pollyjs/utils';
import logLevel from 'loglevel';
import NormalizeRequest from '../utils/normalize-request';
import parseUrl from '../utils/parse-url';
import guidForRecording from '../utils/guid-for-recording';
import mergeConfigs from '../utils/merge-configs';
import defer from '../utils/deferred-promise';
import {
validateRecordingName,
validateRequestConfig
} from '../utils/validators';
import HTTPBase from './http-base';
import PollyResponse from './response';
import EventEmitter from './event-emitter';
import Interceptor from './interceptor';
const { keys, freeze } = Object;
const ROUTE = Symbol();
const POLLY = Symbol();
const PARSED_URL = Symbol();
const EVENT_EMITTER = Symbol();
const SUPPORTED_EVENTS = ['identify'];
export default class PollyRequest extends HTTPBase {
constructor(polly, request) {
super();
assert('Url is required.', request.url);
assert(
'Method is required.',
request.method && typeof request.method === 'string'
);
this.didRespond = false;
this.aborted = false;
this.url = request.url;
this.method = request.method.toUpperCase();
this.body = request.body;
this.setHeaders(request.headers);
this.recordingName = polly.recordingName;
this.recordingId = polly.recordingId;
this.requestArguments = freeze(request.requestArguments);
this.promise = defer();
this[POLLY] = polly;
this[EVENT_EMITTER] = new EventEmitter({ eventNames: SUPPORTED_EVENTS });
/*
The action taken with this request (e.g. record, replay, intercept, or passthrough)
This will be set by the adapter.
*/
this.action = null;
// Interceptor instance to be passed to each of the intercept handlers
this._interceptor = new Interceptor();
// Lookup the associated route for this request
this[ROUTE] = polly.server.lookup(this.method, this.url);
// Filter all matched route handlers by this request
this[ROUTE].applyFiltersWithArgs(this);
// Handle config overrides defined by the route
this.configure(this[ROUTE].config());
// Handle recording name override defined by the route
const recordingName = this[ROUTE].recordingName();
if (recordingName) {
this.overrideRecordingName(recordingName);
}
}
get url() {
// Use .toString() to force a rebuild of the url. This guarantees that
// Any changes to the query object get propagated.
return this[PARSED_URL].toString();
}
set url(value) {
// Make sure to coerce the value into a string as the passed value could be
// a WHATWG's URL object.
this[PARSED_URL] = parseUrl(`${value}`, true);
}
get absoluteUrl() {
const { url } = this;
return isAbsoluteUrl(url) ? url : new URL(url).href;
}
get protocol() {
return this[PARSED_URL].protocol;
}
get hostname() {
return this[PARSED_URL].hostname;
}
get port() {
return this[PARSED_URL].port;
}
get origin() {
return this[PARSED_URL].origin;
}
get pathname() {
return this[PARSED_URL].pathname;
}
get query() {
return this[PARSED_URL].query;
}
set query(value) {
this[PARSED_URL].set('query', value);
}
get hash() {
return this[PARSED_URL].hash;
}
set hash(value) {
this[PARSED_URL].set('hash', value);
}
get shouldPassthrough() {
return this[ROUTE].shouldPassthrough();
}
get shouldIntercept() {
return this[ROUTE].shouldIntercept();
}
get log() {
if (this.id) {
const log = logLevel.getLogger(
`@pollyjs/core:${this.recordingName}:${this.id}`
);
log.setLevel(this.config.logLevel);
return log;
} else {
return this[POLLY].logger.log;
}
}
on(eventName, listener) {
this[EVENT_EMITTER].on(eventName, listener);
return this;
}
once(eventName, listener) {
this[EVENT_EMITTER].once(eventName, listener);
return this;
}
off(eventName, listener) {
this[EVENT_EMITTER].off(eventName, listener);
return this;
}
async init() {
// Trigger the `request` event
await this._emit('request');
// Setup the response
this.response = new PollyResponse();
this.didRespond = false;
// Setup this request's identifiers, id, and order
await this._identify();
// Timestamp the request
this.timestamp = timestamp();
}
async respond(response) {
const { statusCode, headers, body, encoding } = response || {};
assert(
'Cannot respond to a request that already has a response.',
!this.didRespond
);
if (this.aborted) {
return;
}
// Timestamp the response
this.response.timestamp = timestamp();
// Set the status code
this.response.status(statusCode);
// Se the headers
this.response.setHeaders(headers);
// Set the body without modifying any headers (instead of using .send())
this.response.body = body;
this.response.encoding = encoding;
// Trigger the `beforeResponse` event
await this._emit('beforeResponse', this.response);
// End the response so it can no longer be modified
this.response.end();
this.responseTime =
new Date(this.response.timestamp).getTime() -
new Date(this.timestamp).getTime();
this.didRespond = true;
this.end();
// Trigger the `response` event
await this._emit('response', this.response);
}
abort() {
this.aborted = true;
}
overrideRecordingName(recordingName) {
validateRecordingName(recordingName);
this.recordingName = recordingName;
this.recordingId = guidForRecording(recordingName);
}
configure(config) {
validateRequestConfig(config);
this.config = mergeConfigs(this[POLLY].config, this.config || {}, config);
}
_intercept() {
return this[ROUTE].intercept(this, this.response, ...arguments);
}
_emit(eventName, ...args) {
return this[ROUTE].emit(eventName, this, ...args);
}
async _identify() {
const polly = this[POLLY];
const { _requests: requests } = polly;
const { matchRequestsBy } = this.config;
this.identifiers = {};
// Iterate through each normalizer
keys(NormalizeRequest).forEach((key) => {
if (this[key] && matchRequestsBy[key]) {
this.identifiers[key] = NormalizeRequest[key](
this[key],
matchRequestsBy[key],
this
);
}
});
// Emit the `identify` event which adapters can use to serialize the request body
await this[EVENT_EMITTER].emit('identify', this);
// Freeze the identifiers so they can no longer be modified
freeze(this.identifiers);
// Guid is a string representation of the identifiers
this.id = md5(stringify(this.identifiers));
// Order is calculated on other requests with the same id and recording id
// Only requests before this current one are taken into account.
this.order =
matchRequestsBy.order && !this.shouldPassthrough && !this.shouldIntercept
? requests
.slice(0, requests.indexOf(this))
.filter(
(r) => r.id === this.id && r.recordingId === this.recordingId
).length
: 0;
this.log.debug('Request Identified:', {
id: this.id,
order: this.order,
identifiers: this.identifiers,
request: this
});
}
}
================================================
FILE: packages/@pollyjs/core/src/-private/response.js
================================================
import { assert, HTTP_STATUS_CODES } from '@pollyjs/utils';
import HTTPBase from './http-base';
const DEFAULT_STATUS_CODE = 200;
export default class PollyResponse extends HTTPBase {
constructor(statusCode, headers, body, encoding) {
super();
this.status(statusCode || DEFAULT_STATUS_CODE);
this.setHeaders(headers);
this.body = body;
this.encoding = encoding;
}
get ok() {
return this.statusCode && this.statusCode >= 200 && this.statusCode < 300;
}
get statusText() {
return (
HTTP_STATUS_CODES[this.statusCode] ||
HTTP_STATUS_CODES[DEFAULT_STATUS_CODE]
);
}
status(statusCode) {
const status = parseInt(statusCode, 10);
assert(
`[Response] Invalid status code: ${status}`,
status >= 100 && status < 600
);
this.statusCode = status;
return this;
}
sendStatus(status) {
this.status(status);
this.type('text/plain');
return this.send(this.statusText);
}
}
================================================
FILE: packages/@pollyjs/core/src/defaults/config.js
================================================
import { MODES, EXPIRY_STRATEGIES } from '@pollyjs/utils';
import logLevel from 'loglevel';
import Timing from '../utils/timing';
export default {
mode: MODES.REPLAY,
adapters: [],
adapterOptions: {},
persister: null,
persisterOptions: {
keepUnusedRequests: false,
disableSortingHarEntries: false
},
logLevel: logLevel.levels.WARN,
flushRequestsOnStop: false,
recordIfMissing: true,
recordFailedRequests: false,
expiresIn: null,
expiryStrategy: EXPIRY_STRATEGIES.WARN,
timing: Timing.fixed(0),
matchRequestsBy: {
method: true,
headers: true,
body: true,
order: true,
url: {
protocol: true,
username: true,
password: true,
hostname: true,
port: true,
pathname: true,
query: true,
hash: false
}
}
};
================================================
FILE: packages/@pollyjs/core/src/index.js
================================================
export { default as Polly } from './polly';
export { default as Timing } from './utils/timing';
export { default as setupQunit } from './test-helpers/qunit';
export { default as setupMocha } from './test-helpers/mocha';
================================================
FILE: packages/@pollyjs/core/src/polly.js
================================================
import { MODES, assert } from '@pollyjs/utils';
import { version } from '../package.json';
import Logger from './-private/logger';
import { Container } from './-private/container';
import DefaultConfig from './defaults/config';
import PollyRequest from './-private/request';
import guidForRecording from './utils/guid-for-recording';
import mergeConfigs from './utils/merge-configs';
import EventEmitter from './-private/event-emitter';
import Server from './server';
import { validateRecordingName } from './utils/validators';
const RECORDING_NAME = Symbol();
const RECORDING_ID = Symbol();
const PAUSED_ADAPTERS = Symbol();
const FACTORY_REGISTRATION = new WeakMap();
const EVENT_EMITTER = new EventEmitter({
eventNames: ['register', 'create', 'stop']
});
/**
* @export
* @class Polly
*/
export default class Polly {
constructor(recordingName, config) {
this.recordingName = recordingName;
this.server = new Server();
this.config = {};
this.container = new Container();
EVENT_EMITTER.emitSync('register', this.container);
/* running adapter instances */
this.adapters = new Map();
/* running persister instance */
this.persister = null;
/* requests over the lifetime of the polly instance */
this._requests = [];
EVENT_EMITTER.emitSync('create', this);
this.configure(config);
}
/**
* Package version.
*
* @readonly
* @public
* @memberof Polly
*/
static get VERSION() {
return version;
}
/**
* @public
* @memberof Polly
*/
get recordingName() {
return this[RECORDING_NAME];
}
set recordingName(name) {
validateRecordingName(name);
this[RECORDING_NAME] = name;
this[RECORDING_ID] = guidForRecording(name);
}
/**
* @readonly
* @public
* @memberof Polly
*/
get recordingId() {
return this[RECORDING_ID];
}
get mode() {
return this.config.mode;
}
set mode(mode) {
const possibleModes = Object.values(MODES);
assert(
`Invalid mode provided: "${mode}". Possible modes: ${possibleModes.join(
', '
)}.`,
possibleModes.includes(mode)
);
this.config.mode = mode;
}
static on(eventName, listener) {
EVENT_EMITTER.on(eventName, listener);
return this;
}
static once(eventName, listener) {
EVENT_EMITTER.once(eventName, listener);
return this;
}
static off(eventName, listener) {
EVENT_EMITTER.off(eventName, listener);
return this;
}
static register(Factory) {
if (!FACTORY_REGISTRATION.has(Factory)) {
FACTORY_REGISTRATION.set(Factory, (container) =>
container.register(Factory)
);
}
this.on('register', FACTORY_REGISTRATION.get(Factory));
return this;
}
static unregister(Factory) {
if (FACTORY_REGISTRATION.has(Factory)) {
this.off('register', FACTORY_REGISTRATION.get(Factory));
}
return this;
}
/**
* @param {Object} [config={}]
* @public
* @memberof Polly
*/
configure(config = {}) {
const { container } = this;
assert(
'Cannot call `configure` once requests have been handled.',
this._requests.length === 0
);
assert(
'Cannot call `configure` on an instance of Polly that is not running.',
this.mode !== MODES.STOPPED
);
// Disconnect from all current adapters before updating the config
this.disconnect();
if (this.logger) {
this.logger.disconnect();
}
// Update the config
this.config = mergeConfigs(DefaultConfig, this.config, config);
// Create a new logger
this.logger = new Logger(this);
this.logger.connect();
// Register and connect to all specified adapters
this.config.adapters.forEach((adapter) => this.connectTo(adapter));
/* Handle Persister */
let { persister } = this.config;
if (persister) {
if (typeof persister === 'function') {
container.register(persister);
persister = persister.id;
}
assert(
`Persister matching the name \`${persister}\` was not registered.`,
container.has(`persister:${persister}`)
);
this.persister = new (container.lookup(`persister:${persister}`))(this);
}
this.logger.log.debug('Polly instance configured.', {
config: this.config
});
}
/**
* @public
* @memberof Polly
*/
record() {
this.mode = MODES.RECORD;
}
/**
* @public
* @memberof Polly
*/
replay() {
this.mode = MODES.REPLAY;
}
/**
* @public
* @memberof Polly
*/
passthrough() {
this.mode = MODES.PASSTHROUGH;
}
/**
* @public
* @memberof Polly
*/
pause() {
this[PAUSED_ADAPTERS] = [...this.adapters.keys()];
this.disconnect();
}
/**
* @public
* @memberof Polly
*/
play() {
if (this[PAUSED_ADAPTERS]) {
this[PAUSED_ADAPTERS].forEach((adapterId) => this.connectTo(adapterId));
delete this[PAUSED_ADAPTERS];
}
}
/**
* @public
* @memberof Polly
*/
async stop() {
if (this.mode !== MODES.STOPPED) {
if (this.config.flushRequestsOnStop) {
await this.flush();
}
this.disconnect();
await (this.persister && this.persister.persist());
this.mode = MODES.STOPPED;
await EVENT_EMITTER.emit('stop', this);
this.logger.log.debug('Polly instance stopped.', {
recordingName: this.recordingName
});
this.logger.disconnect();
}
}
async flush() {
const NOOP = () => {};
await Promise.all(
// The NOOP is there to handle both a resolved and rejected promise
// to ensure the promise resolves regardless of the outcome.
this._requests.map((r) => Promise.resolve(r.promise).then(NOOP, NOOP))
);
}
/**
* @param {String|Function} idOrFactory
* @public
* @memberof Polly
*/
connectTo(idOrAdapter) {
const { container, adapters } = this;
let adapterId = idOrAdapter;
if (typeof idOrAdapter === 'function') {
container.register(idOrAdapter);
adapterId = idOrAdapter.id;
}
assert(
`Adapter matching the name \`${adapterId}\` was not registered.`,
container.has(`adapter:${adapterId}`)
);
this.disconnectFrom(adapterId);
const adapter = new (container.lookup(`adapter:${adapterId}`))(this);
adapter.connect();
adapters.set(adapterId, adapter);
}
/**
* @param {String|Function} idOrAdapter
* @public
* @memberof Polly
*/
disconnectFrom(idOrAdapter) {
const { adapters } = this;
let adapterId = idOrAdapter;
if (typeof idOrAdapter === 'function') {
adapterId = idOrAdapter.id;
}
if (adapters.has(adapterId)) {
adapters.get(adapterId).disconnect();
adapters.delete(adapterId);
}
}
/**
* @public
* @memberof Polly
*/
disconnect() {
for (const adapterId of this.adapters.keys()) {
this.disconnectFrom(adapterId);
}
}
/**
* @param {Object} [request={}]
* @returns {PollyRequest}
* @private
* @memberof Polly
*/
registerRequest(request = {}) {
const pollyRequest = new PollyRequest(this, request);
this._requests.push(pollyRequest);
return pollyRequest;
}
}
================================================
FILE: packages/@pollyjs/core/src/server/handler.js
================================================
import { assert } from '@pollyjs/utils';
import EventEmitter from '../-private/event-emitter';
import cancelFnAfterNTimes from '../utils/cancel-fn-after-n-times';
import {
validateTimesOption,
validateRecordingName,
validateRequestConfig
} from '../utils/validators';
export default class Handler extends Map {
constructor() {
super();
this.set('config', {});
this.set('defaultOptions', {});
this.set('filters', new Set());
this._eventEmitter = new EventEmitter({
eventNames: [
'error',
'abort',
'request',
'beforeReplay',
'beforePersist',
'beforeResponse',
'response'
]
});
}
on(eventName, listener, options = {}) {
this._eventEmitter.on(eventName, listener, {
...this.get('defaultOptions'),
...options
});
return this;
}
once(eventName, listener) {
this._eventEmitter.once(eventName, listener);
return this;
}
off(eventName, listener) {
this._eventEmitter.off(eventName, listener);
return this;
}
passthrough(value = true) {
this.set('passthrough', Boolean(value));
if (this.get('passthrough')) {
this.delete('intercept');
}
return this;
}
intercept(fn, options = {}) {
assert(
`Invalid intercept handler provided. Expected function, received: "${typeof fn}".`,
typeof fn === 'function'
);
options = { ...this.get('defaultOptions'), ...options };
if ('times' in options) {
validateTimesOption(options.times);
fn = cancelFnAfterNTimes(fn, options.times, () =>
this.delete('intercept')
);
}
this.set('intercept', fn);
this.passthrough(false);
return this;
}
recordingName(recordingName) {
if (recordingName) {
validateRecordingName(recordingName);
}
this.set('recordingName', recordingName);
return this;
}
configure(config) {
validateRequestConfig(config);
this.set('config', config);
return this;
}
filter(fn) {
assert(
`Invalid filter callback provided. Expected function, received: "${typeof fn}".`,
typeof fn === 'function'
);
this.get('filters').add(fn);
return this;
}
times(n) {
if (!n && typeof n !== 'number') {
delete this.get('defaultOptions').times;
} else {
validateTimesOption(n);
this.get('defaultOptions').times = n;
}
return this;
}
}
================================================
FILE: packages/@pollyjs/core/src/server/index.js
================================================
import RouteRecognizer from 'route-recognizer';
import castArray from 'lodash-es/castArray';
import { HTTP_METHODS, URL, assert, timeout, buildUrl } from '@pollyjs/utils';
import Route from './route';
import Handler from './handler';
import Middleware from './middleware';
const HOST = Symbol();
const NAMESPACES = Symbol();
const REGISTRY = Symbol();
const MIDDLEWARE = Symbol();
const HANDLERS = Symbol();
const CHARS = {
SLASH: '/',
STAR: '*',
COLON: ':'
};
const { keys } = Object;
function parseUrl(url) {
const parsedUrl = new URL(url);
/*
Use the full origin (http://hostname:port) if the host exists. If there
is no host, URL.origin returns "null" (null as a string) so set host to '/'
*/
const host = parsedUrl.host ? parsedUrl.origin : CHARS.SLASH;
const path = parsedUrl.pathname || CHARS.SLASH;
return { host, path };
}
export default class Server {
constructor() {
this[HOST] = '';
this[REGISTRY] = {};
this[NAMESPACES] = [];
this[MIDDLEWARE] = [];
}
host(path, callback) {
const host = this[HOST];
assert(`[Server] A host cannot be specified within another host.`, !host);
this[HOST] = path;
callback(this);
this[HOST] = host;
}
namespace(path, callback) {
const namespaces = this[NAMESPACES];
this[NAMESPACES] = [...namespaces, path];
callback(this);
this[NAMESPACES] = namespaces;
}
timeout() {
return timeout(...arguments);
}
get() {
return this._register('GET', ...arguments);
}
put() {
return this._register('PUT', ...arguments);
}
post() {
return this._register('POST', ...arguments);
}
delete() {
return this._register('DELETE', ...arguments);
}
patch() {
return this._register('PATCH', ...arguments);
}
merge() {
return this._register('MERGE', ...arguments);
}
head() {
return this._register('HEAD', ...arguments);
}
options() {
return this._register('OPTIONS', ...arguments);
}
any() {
return this._registerMiddleware(...arguments);
}
lookup(method, url) {
return new Route(this._recognize(method, url), this._lookupMiddleware(url));
}
_lookupMiddleware(url) {
const { host, path } = parseUrl(url);
return this[MIDDLEWARE].map((m) => m.match(host, path)).filter(Boolean);
}
_register(method, routes) {
const handler = new Handler();
castArray(routes).forEach((route) => {
const { host, path } = parseUrl(this._buildUrl(route));
const registry = this._registryForHost(host);
const name = this._nameForPath(path);
const router = registry[method.toUpperCase()];
if (router[HANDLERS].has(name)) {
router[HANDLERS].get(name).push(handler);
} else {
router[HANDLERS].set(name, [handler]);
router.add([{ path, handler: router[HANDLERS].get(name) }]);
}
});
return handler;
}
_registerMiddleware(routes) {
const handler = new Handler();
const pathsByHost = {};
castArray(routes).forEach((route) => {
/*
If the route is a '*' or '' and there is no host or namespace
specified, treat the middleware as global so it will match all routes.
*/
if (
(!route || route === CHARS.STAR) &&
!this[HOST] &&
this[NAMESPACES].length === 0
) {
this[MIDDLEWARE].push(new Middleware({ global: true, handler }));
} else {
const { host, path } = parseUrl(this._buildUrl(route));
pathsByHost[host] = pathsByHost[host] || [];
pathsByHost[host].push(path);
}
});
keys(pathsByHost).forEach((host) => {
this[MIDDLEWARE].push(
new Middleware({ host, paths: pathsByHost[host], handler })
);
});
return handler;
}
_recognize(method, url) {
const { host, path } = parseUrl(url);
const registry = this._registryForHost(host);
return registry[method.toUpperCase()].recognize(path);
}
_buildUrl(path) {
return buildUrl(this[HOST], ...this[NAMESPACES], path);
}
/**
* Converts a url path into a name used to combine route handlers by
* normalizing dynamic and star segments
* @param {String} path
* @returns {String}
*/
_nameForPath(path = '') {
const name = path
.split(CHARS.SLASH)
.map((segment) => {
switch (segment.charAt(0)) {
// If this is a dynamic segment (e.g. :id), then just return `:`
// since /path/:id is the same as /path/:uuid
case CHARS.COLON:
return CHARS.COLON;
// If this is a star segment (e.g. *path), then just return `*`
// since /path/*path is the same as /path/*all
case CHARS.STAR:
return CHARS.STAR;
default:
return segment;
}
})
.join(CHARS.SLASH);
// Remove trailing slash, if we result with an empty string, return a slash
return name.replace(/\/$/, '') || CHARS.SLASH;
}
_registryForHost(host) {
if (!this[REGISTRY][host]) {
this[REGISTRY][host] = HTTP_METHODS.reduce((acc, method) => {
acc[method] = new RouteRecognizer();
acc[method][HANDLERS] = new Map();
return acc;
}, {});
}
return this[REGISTRY][host];
}
}
================================================
FILE: packages/@pollyjs/core/src/server/middleware.js
================================================
import RouteRecognizer from 'route-recognizer';
import Route from './route';
const GLOBAL = '__GLOBAL__';
export default class Middleware {
constructor({ host, paths, global, handler }) {
this.global = Boolean(global);
this.handler = handler;
this.host = host;
this.paths = this.global ? [GLOBAL] : paths;
this._routeRecognizer = new RouteRecognizer();
this.paths.forEach((path) =>
this._routeRecognizer.add([{ path, handler: [handler] }])
);
}
match(host, path) {
if (this.global) {
return new Route(this._routeRecognizer.recognize(GLOBAL));
}
if (this.host === host) {
const recognizeResult = this._routeRecognizer.recognize(path);
return recognizeResult && new Route(recognizeResult);
}
}
}
================================================
FILE: packages/@pollyjs/core/src/server/route.js
================================================
import mergeConfigs from '../utils/merge-configs';
const HANDLERS = Symbol();
function requestWithParams(req, { params }) {
return new Proxy(req, {
set(source, prop, value) {
/* NOTE: IE's `Reflect.set` swallows the read-only assignment error */
/* see: https://codepen.io/jasonmit/pen/LrmLaz */
source[prop] = value;
return true;
},
get(source, prop) {
if (prop === 'params') {
// Set the request's params to given route's matched params
return { ...params };
}
return Reflect.get(source, prop);
}
});
}
export default class Route {
/**
*
* @param {RecognizeResults} recognizeResults
* @param {Array} middleware
*/
constructor(recognizeResults, middleware) {
const result = recognizeResults && recognizeResults[0];
this.params = {};
this.queryParams = {};
this.handlers = [];
this.middleware = middleware || [];
if (result) {
this.handlers = result.handler;
this.params = { ...result.params };
this.queryParams = recognizeResults.queryParams;
}
this[HANDLERS] = this._orderedHandlers();
}
shouldPassthrough() {
return Boolean(this._valueFor('passthrough'));
}
shouldIntercept() {
return Boolean(this._valueFor('intercept'));
}
recordingName() {
return this._valueFor('recordingName') || null;
}
config() {
return mergeConfigs(
...this[HANDLERS].map(({ handler }) => handler.get('config'))
);
}
applyFiltersWithArgs(req, ...args) {
this[HANDLERS] = this[HANDLERS].filter(({ route, handler }) =>
[...handler.get('filters')].every((fn) =>
fn(requestWithParams(req, route), ...args)
)
);
}
/**
* Invokes the intercept handlers defined on the routes + middleware.
* @param {PollyRequest} req
* @param {PollyResponse} res
* @param {Interceptor} interceptor
*/
async intercept(req, res, interceptor) {
for (const { route, handler } of this[HANDLERS]) {
if (!interceptor.shouldIntercept || interceptor.shouldStopPropagating) {
return;
}
if (handler.has('intercept')) {
await handler.get('intercept')(
requestWithParams(req, route),
res,
interceptor
);
}
}
}
/**
* Emit an event registered on the handler + all middleware handler events
* @param {String} eventName
* @param {PollyRequest} req
* @param {...args} ...args
*/
async emit(eventName, req, ...args) {
for (const { route, handler } of this[HANDLERS]) {
const shouldContinue = await handler._eventEmitter.emit(
eventName,
requestWithParams(req, route),
...args
);
if (!shouldContinue) {
return;
}
}
}
_orderedHandlers() {
return [...this.middleware, this].reduce((handlers, route) => {
handlers.push(...route.handlers.map((handler) => ({ route, handler })));
return handlers;
}, []);
}
_valueFor(key) {
let value;
for (const { handler } of this[HANDLERS]) {
if (handler.has(key)) {
value = handler.get(key);
}
}
return value;
}
}
================================================
FILE: packages/@pollyjs/core/src/test-helpers/lib.js
================================================
import { PollyError } from '@pollyjs/utils';
import Polly from '../polly';
const { defineProperty } = Object;
export function beforeEach(context, recordingName, defaults) {
defineProperty(context, 'polly', {
writable: true,
enumerable: true,
configurable: true,
value: new Polly(recordingName, defaults)
});
}
export async function afterEach(context, framework) {
await context.polly.stop();
defineProperty(context, 'polly', {
enumerable: true,
configurable: true,
get() {
throw new PollyError(
`You are trying to access an instance of Polly that is no longer available.\n` +
`See: https://netflix.github.io/pollyjs/#/test-frameworks/${framework}?id=test-hook-ordering`
);
}
});
}
================================================
FILE: packages/@pollyjs/core/src/test-helpers/mocha.js
================================================
import { afterEach, beforeEach } from './lib';
function generateRecordingName(context) {
const { currentTest } = context;
const parts = [currentTest.title];
let parent = currentTest.parent;
while (parent && parent.title) {
parts.push(parent.title);
parent = parent.parent;
}
return parts.reverse().join('/');
}
export default function setupMocha(defaults = {}, ctx = global) {
setupMocha.beforeEach(defaults, ctx);
setupMocha.afterEach(ctx);
}
setupMocha.beforeEach = function setupMochaBeforeEach(defaults, ctx = global) {
ctx.beforeEach(function () {
return beforeEach(this, generateRecordingName(this), defaults);
});
};
setupMocha.afterEach = function setupMochaAfterEach(ctx = global) {
ctx.afterEach(function () {
return afterEach(this, 'mocha');
});
};
================================================
FILE: packages/@pollyjs/core/src/test-helpers/qunit.js
================================================
import { afterEach, beforeEach } from './lib';
function generateRecordingName(assert) {
return assert.test.testReport.fullName.join('/');
}
export default function setupQunit(hooks, defaults = {}) {
setupQunit.beforeEach(hooks, defaults);
setupQunit.afterEach(hooks);
}
setupQunit.beforeEach = function setupQunitBeforeEach(hooks, defaults = {}) {
hooks.beforeEach(function () {
return beforeEach(this, generateRecordingName(...arguments), defaults);
});
};
setupQunit.afterEach = function setupQunitAfterEach(hooks) {
hooks.afterEach(function () {
return afterEach(this, 'qunit');
});
};
================================================
FILE: packages/@pollyjs/core/src/utils/cancel-fn-after-n-times.js
================================================
/**
* Create a function that will execute the given fn and call the cancel
* callback after being called n times.
*
* @export
* @param {Function} fn
* @param {Number} nTimes
* @param {Function} cancel
* @returns
*/
export default function cancelFnAfterNTimes(fn, nTimes, cancel) {
let callCount = 0;
return function (...args) {
if (++callCount >= nTimes) {
cancel();
}
return fn(...args);
};
}
================================================
FILE: packages/@pollyjs/core/src/utils/deferred-promise.js
================================================
/**
* Create a deferred promise with `resolve` and `reject` methods.
*/
export default function defer() {
let _resolve;
let _reject;
const promise = new Promise((resolve, reject) => {
_resolve = resolve;
_reject = reject;
});
// Prevent unhandled rejection warnings
promise.catch(() => {});
promise.resolve = _resolve;
promise.reject = _reject;
return promise;
}
================================================
FILE: packages/@pollyjs/core/src/utils/guid-for-recording.js
================================================
import fnv1a from '@sindresorhus/fnv1a';
import slugify from 'slugify';
function sanitize(str) {
// Strip non-alphanumeric chars (\W is the equivalent of [^0-9a-zA-Z_])
return str.replace(/\W/g, '-');
}
function guidFor(str) {
const hash = fnv1a(str).toString();
let slug = slugify(sanitize(str));
// Max the slug at 100 char
slug = slug.substring(0, 100 - hash.length - 1);
return `${slug}_${hash}`;
}
export default function guidForRecording(recording) {
return (recording || '').split('/').map(guidFor).join('/');
}
================================================
FILE: packages/@pollyjs/core/src/utils/http-headers.js
================================================
import isObjectLike from 'lodash-es/isObjectLike';
const { keys } = Object;
const HANDLER = {
get(obj, prop) {
// `prop` can be a Symbol so only lower-case string based props.
return obj[typeof prop === 'string' ? prop.toLowerCase() : prop];
},
set(obj, prop, value) {
if (typeof prop !== 'string') {
return false;
}
if (value === null || typeof value === 'undefined') {
delete obj[prop.toLowerCase()];
} else {
obj[prop.toLowerCase()] = value;
}
return true;
},
deleteProperty(obj, prop) {
if (typeof prop !== 'string') {
return false;
}
delete obj[prop.toLowerCase()];
return true;
}
};
export default function HTTPHeaders(headers) {
const proxy = new Proxy({}, HANDLER);
if (isObjectLike(headers)) {
keys(headers).forEach((h) => (proxy[h] = headers[h]));
}
return proxy;
}
================================================
FILE: packages/@pollyjs/core/src/utils/merge-configs.js
================================================
import mergeWith from 'lodash-es/mergeWith';
function customizer(objValue, srcValue, key) {
// Arrays and `context` options should just replace the existing value
// and not be deep merged.
if (Array.isArray(objValue) || ['context'].includes(key)) {
return srcValue;
}
}
export default function mergeConfigs(...configs) {
return mergeWith({}, ...configs, customizer);
}
================================================
FILE: packages/@pollyjs/core/src/utils/normalize-request.js
================================================
import isObjectLike from 'lodash-es/isObjectLike';
import stringify from 'fast-json-stable-stringify';
import parseUrl from './parse-url';
import HTTPHeaders from './http-headers';
const { keys } = Object;
const { isArray } = Array;
const { parse } = JSON;
function isFunction(fn) {
return typeof fn === 'function';
}
export function method(method, config, req) {
return isFunction(config) ? config(method, req) : method.toUpperCase();
}
export function url(url, config, req) {
let parsedUrl = parseUrl(url, true);
if (isFunction(config)) {
parsedUrl = parseUrl(config(url, req), true);
} else {
// Remove any url properties that have been disabled via the config
keys(config || {}).forEach((key) => {
if (isFunction(config[key])) {
parsedUrl.set(key, config[key](parsedUrl[key], req));
} else if (!config[key]) {
parsedUrl.set(key, '');
}
});
}
// Sort Query Params
if (isObjectLike(parsedUrl.query)) {
parsedUrl.set('query', parse(stringify(parsedUrl.query)));
}
return parsedUrl.href;
}
export function headers(headers, config, req) {
const normalizedHeaders = new HTTPHeaders(headers);
if (isFunction(config)) {
return config(normalizedHeaders, req);
}
if (isObjectLike(config) && isArray(config.exclude)) {
config.exclude.forEach((header) => delete normalizedHeaders[header]);
}
return normalizedHeaders;
}
export function body(body, config, req) {
return isFunction(config) ? config(body, req) : body;
}
export default {
headers,
method,
body,
url
};
================================================
FILE: packages/@pollyjs/core/src/utils/parse-url.js
================================================
import isAbsoluteUrl from 'is-absolute-url';
import { URL } from '@pollyjs/utils';
import removeHostFromUrl from './remove-host-from-url';
/**
* Creates an exact representation of the passed url string with url-parse.
*
* @param {String} url
* @param {...args} args Arguments to pass through to the URL constructor
* @returns {URL} A url-parse URL instance
*/
export default function parseUrl(url, ...args) {
const parsedUrl = new URL(url, ...args);
if (!isAbsoluteUrl(url)) {
if (url.startsWith('//')) {
/*
If the url is protocol-relative, strip out the protocol
*/
parsedUrl.set('protocol', '');
} else {
/*
If the url is relative, setup the parsed url to reflect just that
by removing the host. By default URL sets the host via window.location if
it does not exist.
*/
removeHostFromUrl(parsedUrl);
}
}
return parsedUrl;
}
================================================
FILE: packages/@pollyjs/core/src/utils/remove-host-from-url.js
================================================
/**
* Remove the host, protocol, and slashes from a URL instance.
*
* @param {URL} url
*/
export default function removeHostFromUrl(url) {
url.set('protocol', '');
url.set('host', '');
url.set('slashes', false);
return url;
}
================================================
FILE: packages/@pollyjs/core/src/utils/timing.js
================================================
import { timeout } from '@pollyjs/utils';
export default {
fixed(ms) {
return () => timeout(ms);
},
relative(ratio) {
return (ms) => timeout(ratio * ms);
}
};
================================================
FILE: packages/@pollyjs/core/src/utils/validators.js
================================================
import isObjectLike from 'lodash-es/isObjectLike';
import { assert } from '@pollyjs/utils';
export function validateRecordingName(name) {
assert(
`Invalid recording name provided. Expected string, received: "${typeof name}".`,
typeof name === 'string'
);
assert(
`Invalid recording name provided. Received An empty or blank string.`,
name.trim().length > 0
);
}
export function validateRequestConfig(config) {
assert(
`Invalid config provided. Expected object, received: "${typeof config}".`,
isObjectLike(config) && !Array.isArray(config)
);
// The following options cannot be overridden on a per request basis
[
'mode',
'adapters',
'adapterOptions',
'persister',
'persisterOptions'
].forEach((key) =>
assert(
`Invalid configuration option provided. The "${key}" option cannot be overridden using the server configuration API.`,
!(key in config)
)
);
}
export function validateTimesOption(times) {
assert(
`Invalid number provided. Expected number, received: "${typeof times}".`,
typeof times === 'number'
);
assert(
`Invalid number provided. The number must be greater than 0, received "${typeof times}".`,
times > 0
);
}
================================================
FILE: packages/@pollyjs/core/tests/unit/-private/container-test.js
================================================
import { PollyError } from '@pollyjs/utils';
import { Container } from '../../../src/-private/container';
let container;
class Factory {
static get id() {
return 'factory-id';
}
static get type() {
return 'factory';
}
}
describe('Unit | Container', function () {
it('should exist', function () {
expect(() => new Container()).to.not.throw();
expect(new Container()).to.exist;
});
describe('API', function () {
beforeEach(function () {
container = new Container();
});
it('.register()', function () {
container.register(Factory);
expect(container.has('factory:factory-id')).to.be.true;
});
it('.register() - validation', function () {
class NoId extends Factory {
static get id() {
return undefined;
}
}
class NoType extends Factory {
static get type() {
return undefined;
}
}
expect(() => container.register()).to.throw(
PollyError,
/invalid factory provided/
);
expect(() => container.register(NoId)).to.throw(
PollyError,
/Invalid registration id provided/
);
expect(() => container.register(NoType)).to.throw(
PollyError,
/Invalid registration type provided/
);
});
it('.unregister() - by key', function () {
container.register(Factory);
expect(container.has('factory:factory-id')).to.be.true;
container.unregister('factory:factory-id');
expect(container.has('factory:factory-id')).to.be.false;
});
it('.unregister() - by factory', function () {
container.register(Factory);
expect(container.has('factory:factory-id')).to.be.true;
container.unregister(Factory);
expect(container.has('factory:factory-id')).to.be.false;
});
it('.lookup()', function () {
container.register(Factory);
expect(container.lookup('factory:factory-id')).to.equal(Factory);
expect(container.lookup('factory:bar')).to.be.null;
});
it('.has() - by key', function () {
container.register(Factory);
expect(container.has('factory:factory-id')).to.be.true;
expect(container.has('factory:bar')).to.be.false;
});
it('.has() - by factory', function () {
class ExtendedFactory extends Factory {
static get id() {
return 'extended-factory-id';
}
}
container.register(Factory);
expect(container.has(Factory)).to.be.true;
expect(container.has(ExtendedFactory)).to.be.false;
});
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/-private/event-emitter-test.js
================================================
import { PollyError, timeout } from '@pollyjs/utils';
import EventEmitter from '../../../src/-private/event-emitter';
let emitter;
function assertEventName(methodName) {
expect(() => emitter[methodName]()).to.throw(
PollyError,
/Invalid event name provided. Expected string/
);
expect(() => emitter[methodName]('invalid')).to.throw(
PollyError,
/Possible events: a, b/
);
}
function assertListener(methodName) {
expect(() => emitter[methodName]('a')).to.throw(
PollyError,
/Invalid listener provided/
);
}
describe('Unit | EventEmitter', function () {
it('should exist', function () {
expect(() => new EventEmitter({ eventNames: ['a'] })).to.not.throw();
expect(new EventEmitter({ eventNames: ['a'] })).to.exist;
});
it('should throw without eventNames', function () {
expect(() => new EventEmitter()).to.throw(PollyError);
expect(() => new EventEmitter({ eventNames: [] })).to.throw(
PollyError,
/supported events must be provided/
);
});
describe('API', function () {
beforeEach(function () {
emitter = new EventEmitter({
eventNames: ['a', 'b']
});
});
it('.eventNames()', function () {
const listener = () => {};
expect(emitter.eventNames()).to.have.lengthOf(0);
emitter.on('a', listener);
emitter.on('b', listener);
expect(emitter.eventNames()).to.have.ordered.members(['a', 'b']);
emitter.off('a', listener);
expect(emitter.eventNames()).to.have.ordered.members(['b']);
});
it('.on()', async function () {
assertEventName('on');
assertListener('on');
let listenerCalled = 0;
const listener = () => listenerCalled++;
emitter.on('a', listener);
emitter.on('a', listener);
expect(emitter.listeners('a')).to.have.lengthOf(1);
emitter.on('a', () => {});
expect(emitter.listeners('a')).to.have.lengthOf(2);
await emitter.emit('a');
expect(listenerCalled).to.equal(1);
});
it('.on(listener, { times })', async function () {
assertEventName('on');
assertListener('on');
let listenerCalled = 0;
const listener = () => listenerCalled++;
expect(() => emitter.on('a', listener, { times: '1' })).to.throw(
PollyError,
/Invalid number provided/
);
expect(() => emitter.on('a', listener, { times: -1 })).to.throw(
PollyError,
/The number must be greater than 0/
);
emitter.on('a', listener, { times: 1 });
emitter.on('a', listener, { times: 2 });
expect(emitter.listeners('a')).to.have.lengthOf(1);
await emitter.emit('a');
await emitter.emit('a');
await emitter.emit('a');
expect(listenerCalled).to.equal(2);
expect(emitter.listeners('a')).to.have.lengthOf(0);
});
it('.once()', async function () {
assertEventName('once');
assertListener('once');
let listenerCalled = 0;
const listener = () => listenerCalled++;
emitter.once('a', listener);
expect(emitter.listeners('a')).to.have.lengthOf(1);
await emitter.emit('a');
expect(listenerCalled).to.equal(1);
expect(emitter.listeners('a')).to.have.lengthOf(0);
await emitter.emit('a');
expect(listenerCalled).to.equal(1);
emitter.once('a', listener);
expect(emitter.listeners('a')).to.have.lengthOf(1);
emitter.off('a', listener);
expect(emitter.listeners('a')).to.have.lengthOf(0);
});
it('.off()', async function () {
assertEventName('off');
const listener = () => {};
emitter.on('a', listener);
emitter.on('a', () => {});
emitter.on('a', () => {});
expect(emitter.listeners('a')).to.have.lengthOf(3);
emitter.off('a', listener);
expect(emitter.listeners('a')).to.have.lengthOf(2);
emitter.off('a');
expect(emitter.listeners('a')).to.have.lengthOf(0);
emitter.on('a', listener, { times: 3 });
expect(emitter.listeners('a')).to.have.lengthOf(1);
emitter.off('a', listener);
expect(emitter.listeners('a')).to.have.lengthOf(0);
});
it('.listeners()', async function () {
assertEventName('listeners');
expect(emitter.listeners('a')).to.be.an('array');
expect(emitter.listeners('a')).to.deep.equal([]);
emitter.on('a', () => {});
emitter.on('b', () => {});
emitter.on('b', () => {});
expect(emitter.listeners('a')).to.be.an('array');
expect(emitter.listeners('a')).to.have.lengthOf(1);
expect(emitter.listeners('b')).to.have.lengthOf(2);
emitter.off('b');
expect(emitter.listeners('b')).to.be.an('array');
expect(emitter.listeners('b')).to.have.lengthOf(0);
});
it('.hasListeners()', async function () {
assertEventName('hasListeners');
expect(emitter.hasListeners('a')).to.be.false;
emitter.on('a', () => {});
expect(emitter.hasListeners('a')).to.be.true;
emitter.off('a');
expect(emitter.hasListeners('a')).to.be.false;
});
it('.emit()', async function () {
expect(emitter.emit('a')).to.be.a('promise');
const array = [];
emitter.on('a', () => array.push(1));
emitter.on('a', async () => {
await timeout(10);
array.push(2);
});
emitter.on('a', () => array.push(3));
expect(await emitter.emit('a')).to.be.true;
expect(array).to.have.ordered.members([1, 2, 3]);
});
it('.emit() - stopPropagation', async function () {
const array = [];
emitter.on('a', async (e) => {
e.stopPropagation();
array.push(1);
});
emitter.on('a', () => array.push(2));
expect(await emitter.emit('a')).to.be.false;
expect(array).to.have.ordered.members([1]);
});
it('.emitParallel()', async function () {
expect(emitter.emitParallel('a')).to.be.a('promise');
const array = [];
emitter.on('a', () => array.push(1));
emitter.on('a', async () => {
await timeout(20);
array.push(2);
});
emitter.on('a', async () => {
await timeout(10);
array.push(3);
});
expect(await emitter.emitParallel('a')).to.be.true;
expect(array).to.have.ordered.members([1, 3, 2]);
});
it('.emitParallel() - stopPropagation', async function () {
const array = [];
emitter.on('a', async (e) => {
e.stopPropagation();
array.push(1);
});
emitter.on('a', () => array.push(2));
expect(await emitter.emitParallel('a')).to.be.false;
expect(array).to.have.ordered.members([1, 2]);
});
it('.emitSync()', async function () {
emitter.once('a', () => Promise.resolve());
expect(() => emitter.emitSync('a')).to.throw(
PollyError,
/Attempted to emit a synchronous event/
);
const array = [];
emitter.on('a', () => array.push(1));
emitter.on('a', () => array.push(2));
emitter.on('a', () => array.push(3));
expect(emitter.emitSync('a')).to.be.true;
expect(array).to.have.ordered.members([1, 2, 3]);
});
it('.emitSync() - stopPropagation', async function () {
const array = [];
emitter.on('a', (e) => {
e.stopPropagation();
array.push(1);
});
emitter.on('a', () => array.push(2));
expect(emitter.emitSync('a')).to.be.false;
expect(array).to.have.ordered.members([1]);
});
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/-private/event-test.js
================================================
import { PollyError } from '@pollyjs/utils';
import Event from '../../../src/-private/event';
const EVENT_TYPE = 'foo';
describe('Unit | Event', function () {
it('should exist', function () {
expect(Event).to.be.a('function');
});
it('should throw if no type is specified', function () {
expect(() => new Event()).to.throw(PollyError, /Invalid type provided/);
});
it('should have the correct defaults', function () {
const event = new Event(EVENT_TYPE);
expect(event.type).to.equal(EVENT_TYPE);
expect(event.shouldStopPropagating).to.be.false;
});
it('should not be able to edit the type', function () {
const event = new Event(EVENT_TYPE);
expect(event.type).to.equal(EVENT_TYPE);
expect(() => (event.type = 'bar')).to.throw(Error);
});
it('should be able to attach any other properties', function () {
const event = new Event(EVENT_TYPE, { foo: 1, bar: 2 });
expect(event.foo).to.equal(1);
expect(event.bar).to.equal(2);
});
it('.stopPropagation()', function () {
const event = new Event(EVENT_TYPE);
expect(event.shouldStopPropagating).to.be.false;
event.stopPropagation();
expect(event.shouldStopPropagating).to.be.true;
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/-private/http-base-test.js
================================================
import stringify from 'fast-json-stable-stringify';
import HTTPBase from '../../../src/-private/http-base';
let base;
describe('Unit | HTTPBase', function () {
it('should exist', function () {
expect(() => new HTTPBase()).to.not.throw();
expect(new HTTPBase()).to.exist;
});
describe('API', function () {
beforeEach(function () {
base = new HTTPBase();
});
it('.getHeader()', function () {
const { headers } = base;
base.setHeader('One', '1');
expect(headers).to.deep.equal({ one: '1' });
expect(base.getHeader('One')).to.equal('1');
expect(base.getHeader('one')).to.equal('1');
expect(base.getHeader('Two')).to.be.undefined;
base.removeHeader('One');
expect(base.getHeader('One')).to.be.undefined;
expect(base.getHeader('one')).to.be.undefined;
});
it('.hasHeader()', function () {
const { headers } = base;
base.setHeader('One', '1');
expect(headers).to.deep.equal({ one: '1' });
expect(base.hasHeader('One')).to.be.true;
expect(base.hasHeader('one')).to.be.true;
expect(base.hasHeader('Two')).to.be.false;
base.removeHeader('One');
expect(base.hasHeader('One')).to.be.false;
expect(base.hasHeader('one')).to.be.false;
});
it('.setHeader()', function () {
const { headers } = base;
base.setHeader('One', '1');
expect(headers).to.deep.equal({ one: '1' });
base.setHeader('two', '2');
expect(headers).to.deep.equal({ one: '1', two: '2' });
base.setHeader('Two', null);
expect(headers).to.deep.equal({ one: '1' });
});
it('.setHeaders()', function () {
const { headers } = base;
base.setHeaders({ One: '1', two: '2' });
expect(headers).to.deep.equal({ one: '1', two: '2' });
base.setHeaders({ Three: '3' });
expect(headers).to.deep.equal({ one: '1', two: '2', three: '3' });
base.setHeaders({ Three: null });
expect(headers).to.deep.equal({ one: '1', two: '2' });
});
it('.removeHeader()', function () {
const { headers } = base;
base.setHeaders({ One: '1', Two: '2' });
base.removeHeader('One');
expect(headers).to.deep.equal({ two: '2' });
base.removeHeader('two');
expect(headers).to.deep.equal({});
});
it('.removeHeaders()', function () {
const { headers } = base;
base.setHeaders({ One: '1', Two: '2' });
base.removeHeaders(['One', 'two']);
expect(headers).to.deep.equal({});
});
it('.type()', function () {
base.type('text/plain');
expect(base.getHeader('Content-Type')).to.equal('text/plain');
});
it('.send() - string', function () {
base.send('foo');
expect(base.body).to.equal('foo');
expect(base.getHeader('Content-Type')).to.equal(
'text/html; charset=utf-8'
);
});
it('.send() - boolean, number, & object', function () {
[true, 200, {}].forEach((body) => {
base.type();
base.send(body);
expect(base.body).to.equal(stringify(body));
expect(base.getHeader('Content-Type')).to.equal(
'application/json; charset=utf-8'
);
});
});
it('.send() - null & undefined', function () {
base.type();
base.send(null);
expect(base.body).to.equal('');
expect(base.hasHeader('Content-Type')).to.be.false;
base.type();
base.send();
expect(base.body).to.be.undefined;
expect(base.hasHeader('Content-Type')).to.be.false;
});
it('.send() - should not override existing type', function () {
base.type('text/plain; charset=utf-9000');
base.send('foo');
expect(base.body).to.equal('foo');
expect(base.getHeader('Content-Type')).to.equal(
'text/plain; charset=utf-9000'
);
});
it('.json()', function () {
const obj = { foo: 'bar' };
base.json(obj);
expect(base.body).to.equal(stringify(obj));
expect(base.getHeader('Content-Type')).to.equal(
'application/json; charset=utf-8'
);
});
it('.json() - should not override existing type', function () {
const obj = { foo: 'bar' };
base.type('text/plain; charset=utf-9000');
base.send(obj);
expect(base.body).to.equal(stringify(obj));
expect(base.getHeader('Content-Type')).to.equal(
'text/plain; charset=utf-9000'
);
});
it('.jsonBody()', function () {
const obj = { foo: 'bar' };
expect(() => base.jsonBody()).to.throw(Error);
base.json(obj);
expect(base.jsonBody()).to.deep.equal(obj);
});
it('.end()', function () {
base.setHeader('foo', 'bar');
expect(base.headers).to.deep.equal({ foo: 'bar' });
base.end();
expect(() => base.setHeader('bar', 'baz')).to.throw();
expect(base.headers).to.deep.equal({ foo: 'bar' });
});
it('should be chainable', function () {
expect(base.setHeader('one', '1')).to.equal(base);
expect(base.setHeaders({ one: '1' })).to.equal(base);
expect(base.type('text/plain')).to.equal(base);
expect(base.send('body')).to.equal(base);
expect(base.json({ foo: 'bar' })).to.equal(base);
expect(base.end()).to.equal(base);
});
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/-private/interceptor-test.js
================================================
import Interceptor from '../../../src/-private/interceptor';
describe('Unit | Interceptor', function () {
it('should exist', function () {
expect(Interceptor).to.be.a('function');
});
it('should have the correct defaults', function () {
const interceptor = new Interceptor();
expect(interceptor.type).to.equal('intercept');
expect(interceptor.shouldAbort).to.be.false;
expect(interceptor.shouldPassthrough).to.be.false;
expect(interceptor.shouldIntercept).to.be.true;
expect(interceptor.shouldStopPropagating).to.be.false;
});
it('should disable passthrough when calling abort and vise versa', function () {
const interceptor = new Interceptor();
expect(interceptor.shouldAbort).to.be.false;
expect(interceptor.shouldPassthrough).to.be.false;
interceptor.abort();
expect(interceptor.shouldAbort).to.be.true;
expect(interceptor.shouldPassthrough).to.be.false;
interceptor.passthrough();
expect(interceptor.shouldAbort).to.be.false;
expect(interceptor.shouldPassthrough).to.be.true;
});
it('.abort()', function () {
const interceptor = new Interceptor();
expect(interceptor.shouldAbort).to.be.false;
expect(interceptor.shouldIntercept).to.be.true;
interceptor.abort();
expect(interceptor.shouldAbort).to.be.true;
expect(interceptor.shouldIntercept).to.be.false;
});
it('.passthrough()', function () {
const interceptor = new Interceptor();
expect(interceptor.shouldPassthrough).to.be.false;
expect(interceptor.shouldIntercept).to.be.true;
interceptor.passthrough();
expect(interceptor.shouldPassthrough).to.be.true;
expect(interceptor.shouldIntercept).to.be.false;
});
it('.stopPropagation()', function () {
const interceptor = new Interceptor();
expect(interceptor.shouldStopPropagating).to.be.false;
interceptor.stopPropagation();
expect(interceptor.shouldStopPropagating).to.be.true;
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/-private/response-test.js
================================================
import { PollyError } from '@pollyjs/utils';
import PollyResponse from '../../../src/-private/response';
let response;
describe('Unit | Response', function () {
it('should exist', function () {
expect(() => new PollyResponse()).to.not.throw();
expect(new PollyResponse()).to.exist;
});
it('should have a default status code of 200', function () {
expect(new PollyResponse().statusCode).to.equal(200);
});
it('should default encoding to undefined', function () {
expect(new PollyResponse().encoding).to.be.undefined;
});
describe('API', function () {
beforeEach(function () {
response = new PollyResponse();
});
it('.status()', function () {
[100, '404', 500, '599'].forEach((statusCode) => {
expect(response.status(statusCode).statusCode).to.equal(
Number(statusCode)
);
});
[null, '', 0, 99, 600, 999].forEach((statusCode) => {
expect(() => response.status(statusCode)).to.throw(
PollyError,
/Invalid status code/
);
});
});
it('.sendStatus()', function () {
response.sendStatus(200);
expect(response.body).to.equal('OK');
expect(response.getHeader('Content-Type')).to.equal(
'text/plain; charset=utf-8'
);
});
it('.end()', function () {
response.status(200);
response.setHeader('foo', 'bar');
expect(response.statusCode).to.equal(200);
expect(response.headers).to.deep.equal({ foo: 'bar' });
response.end();
expect(() => response.status(404)).to.throw();
expect(() => response.setHeader('bar', 'baz')).to.throw();
expect(response.statusCode).to.equal(200);
expect(response.headers).to.deep.equal({ foo: 'bar' });
});
it('should be chainable', function () {
expect(response.status(200)).to.equal(response);
expect(response.sendStatus(200)).to.equal(response);
});
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/index-test.js
================================================
import * as PollyExports from '../../src';
describe('Unit | Index', function () {
it('should export all the necessary modules', function () {
['Polly', 'Timing', 'setupQunit', 'setupMocha'].forEach((name) => {
expect(PollyExports[name]).to.be.ok;
});
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/polly-test.js
================================================
import Adapter from '@pollyjs/adapter';
import Persister from '@pollyjs/persister';
import { MODES, PollyError } from '@pollyjs/utils';
import defaults from '../../src/defaults/config';
import Polly from '../../src/polly';
import { Container } from '../../src/-private/container';
import setupPolly from '../../src/test-helpers/mocha';
describe('Unit | Polly', function () {
it('should exist', function () {
expect(Polly).to.be.a('function');
});
it('should have a version', function () {
expect(Polly.VERSION).to.be.a('string');
});
it('should instantiate without throwing', async function () {
await expect(async function () {
const polly = new Polly('recording name');
await polly.stop();
}).to.not.throw();
});
it('should throw with an empty recording name', async function () {
for (const value of [undefined, null, '', '\n\r']) {
const polly = new Polly('test');
expect(() => (polly.recordingName = value)).to.throw(
PollyError,
/Invalid recording name provided/
);
await polly.stop();
}
});
it('should be able to change the recording name', async function () {
const polly = new Polly('squawk');
expect(polly.recordingName).to.equal('squawk');
polly.recordingName = 'squawk squawk';
expect(polly.recordingName).to.equal('squawk squawk');
await polly.stop();
});
it('should update the recording id when the name changes', async function () {
const polly = new Polly('squawk');
expect(polly.recordingName).to.equal('squawk');
expect(polly.recordingId).to.contain('squawk');
polly.recordingName = 'chirp';
expect(polly.recordingName).to.equal('chirp');
expect(polly.recordingId).to.contain('chirp');
await polly.stop();
});
it('can manually set the mode', async function () {
const polly = new Polly('squawk');
expect(polly.mode).to.equal('replay');
polly.mode = 'record';
expect(polly.mode).to.equal('record');
await polly.stop();
});
it('throws on an invalid mode', async function () {
const polly = new Polly('squawk');
expect(() => (polly.mode = 'INVALID')).to.throw(
PollyError,
/Invalid mode provided/
);
await polly.stop();
});
it('it supports custom adapters', async function () {
let connectCalled, disconnectCalled;
class MockAdapter extends Adapter {
static get id() {
return 'mock';
}
onConnect() {
connectCalled = true;
}
onDisconnect() {
disconnectCalled = true;
}
}
const polly = new Polly('recording name', { adapters: [MockAdapter] });
await polly.stop();
expect(connectCalled).to.be.true;
expect(disconnectCalled).to.be.true;
});
it('it supports custom persisters', async function () {
let instantiated, persistCalled;
class MockPersister extends Persister {
static get id() {
return 'mock';
}
constructor() {
super(...arguments);
instantiated = true;
}
persist() {
persistCalled = true;
super.persist(...arguments);
}
}
const polly = new Polly('recording name', { persister: MockPersister });
await polly.stop();
expect(instantiated).to.be.true;
expect(persistCalled).to.be.true;
});
it('calls flush when flushRequestsOnStop is enabled', async function () {
let polly = new Polly('squawk', { flushRequestsOnStop: false });
let flushCalled = false;
polly.flush = async () => {
flushCalled = true;
};
await polly.stop();
expect(flushCalled).to.be.false;
polly = new Polly('squawk', { flushRequestsOnStop: true });
flushCalled = false;
polly.flush = async () => {
flushCalled = true;
};
await polly.stop();
expect(flushCalled).to.be.true;
});
describe('configure', function () {
setupPolly();
it('should not be configurable once requests are handled', async function () {
this.polly._requests.push({});
expect(() => this.polly.configure()).to.throw(
PollyError,
'Cannot call `configure` once requests have been handled.'
);
});
it('should not be configurable once stopped', async function () {
await this.polly.stop();
expect(() => this.polly.configure()).to.throw(
PollyError,
'Cannot call `configure` on an instance of Polly that is not running.'
);
});
it('should deep merge configure options with defaults', async function () {
this.polly.configure({
matchRequestsBy: {
url: {
port: !defaults.matchRequestsBy.url.port
}
}
});
expect(this.polly.config.matchRequestsBy.url.port).to.be.false;
expect(this.polly.config.matchRequestsBy.url).to.deep.equal({
...defaults.matchRequestsBy.url,
port: !defaults.matchRequestsBy.url.port
});
});
it('should not deep merge adapter options', async function () {
class MockAdapterA extends Adapter {
static get id() {
return 'mock-a';
}
onConnect() {}
onDisconnect() {}
}
class MockAdapterB extends MockAdapterA {
static get id() {
return 'mock-b';
}
}
expect(this.polly.config.adapters.length).to.equal(0);
this.polly.configure({ adapters: [MockAdapterA] });
this.polly.configure({ adapters: [MockAdapterB] });
expect(this.polly.config.adapters.length).to.equal(1);
expect(this.polly.adapters.has('mock-a')).to.be.false;
expect(this.polly.adapters.has('mock-b')).to.be.true;
});
it('should connect to new adapters', async function () {
let connectCalled = false;
class MockAdapter extends Adapter {
static get id() {
return 'mock';
}
onConnect() {
connectCalled = true;
}
onDisconnect() {}
}
expect(connectCalled).to.be.false;
this.polly.configure({ adapters: [MockAdapter] });
expect(connectCalled).to.be.true;
});
it('should disconnect from adapters before connecting', async function () {
let connectCount = 0;
let disconnectCount = 0;
class MockAdapter extends Adapter {
static get id() {
return 'mock';
}
onConnect() {
connectCount++;
}
onDisconnect() {
disconnectCount++;
}
}
this.polly.configure({ adapters: [MockAdapter] });
expect(connectCount).to.equal(1);
expect(disconnectCount).to.equal(0);
this.polly.configure({ adapters: [MockAdapter] });
expect(connectCount).to.equal(2);
expect(disconnectCount).to.equal(1);
});
});
describe('API', function () {
setupPolly();
class MockAdapterA extends Adapter {
static get id() {
return 'adapter-a';
}
onConnect() {}
onDisconnect() {}
}
class MockAdapterB extends MockAdapterA {
static get id() {
return 'adapter-b';
}
}
it('.record()', async function () {
this.polly.mode = MODES.REPLAY;
expect(this.polly.mode).to.equal(MODES.REPLAY);
this.polly.record();
expect(this.polly.mode).to.equal(MODES.RECORD);
});
it('.replay()', async function () {
this.polly.mode = MODES.RECORD;
expect(this.polly.mode).to.equal(MODES.RECORD);
this.polly.replay();
expect(this.polly.mode).to.equal(MODES.REPLAY);
});
it('.passthrough()', async function () {
this.polly.mode = MODES.RECORD;
expect(this.polly.mode).to.equal(MODES.RECORD);
this.polly.passthrough();
expect(this.polly.mode).to.equal(MODES.PASSTHROUGH);
});
it('.pause()', async function () {
this.polly.configure({ adapters: [MockAdapterA, MockAdapterB] });
expect([...this.polly.adapters.keys()]).to.deep.equal([
'adapter-a',
'adapter-b'
]);
this.polly.pause();
expect([...this.polly.adapters.keys()]).to.deep.equal([]);
});
it('.play()', async function () {
this.polly.configure({ adapters: [MockAdapterA, MockAdapterB] });
expect([...this.polly.adapters.keys()]).to.deep.equal([
'adapter-a',
'adapter-b'
]);
this.polly.play();
expect([...this.polly.adapters.keys()]).to.deep.equal([
'adapter-a',
'adapter-b'
]);
this.polly.pause();
expect([...this.polly.adapters.keys()]).to.deep.equal([]);
this.polly.play();
expect([...this.polly.adapters.keys()]).to.deep.equal([
'adapter-a',
'adapter-b'
]);
});
it('.stop()', async function () {
this.polly.mode = MODES.RECORD;
expect(this.polly.mode).to.equal(MODES.RECORD);
const promise = this.polly.stop();
expect(promise).to.be.a('promise');
await promise;
expect(this.polly.mode).to.equal(MODES.STOPPED);
});
it('.connectTo()', async function () {
let connectCount = 0;
let disconnectCount = 0;
class MockAdapter extends Adapter {
static get id() {
return 'mock';
}
onConnect() {
connectCount++;
}
onDisconnect() {
disconnectCount++;
}
}
this.polly.container.register(MockAdapter);
this.polly.connectTo('mock');
expect(connectCount).to.equal(1);
expect(disconnectCount).to.equal(0);
this.polly.connectTo(MockAdapter);
expect(connectCount).to.equal(2);
expect(disconnectCount).to.equal(1);
});
it('.disconnectTo()', async function () {
let connectCount = 0;
let disconnectCount = 0;
class MockAdapter extends Adapter {
static get id() {
return 'mock';
}
onConnect() {
connectCount++;
}
onDisconnect() {
disconnectCount++;
}
}
this.polly.container.register(MockAdapter);
this.polly.connectTo('mock');
expect(connectCount).to.equal(1);
this.polly.disconnectFrom('mock');
expect(disconnectCount).to.equal(1);
this.polly.connectTo(MockAdapter);
expect(connectCount).to.equal(2);
this.polly.disconnectFrom(MockAdapter);
expect(disconnectCount).to.equal(2);
});
it('.disconnect()', async function () {
const disconnects = [];
class MockAdapterA extends Adapter {
static get id() {
return 'mock-a';
}
onConnect() {}
onDisconnect() {
disconnects.push(true);
}
}
class MockAdapterB extends MockAdapterA {
static get id() {
return 'mock-b';
}
}
// configure automatically connects to the new adapter
this.polly.configure({ adapters: [MockAdapterA, MockAdapterB] });
expect(disconnects.length).to.equal(0);
expect(this.polly.disconnect());
expect(disconnects.length).to.equal(2);
});
it('.flush()', async function () {
const promise = this.polly.flush();
expect(promise).to.be.a('promise');
await promise;
});
});
describe('Class Methods & Events', function () {
it('should be event-able', function () {
expect(Polly.on).to.be.a('function');
expect(Polly.once).to.be.a('function');
expect(Polly.off).to.be.a('function');
});
describe('Methods', function () {
class MockAdapter extends Adapter {
static get id() {
return 'mock';
}
}
it('.register()', async function () {
Polly.register(MockAdapter);
const polly = new Polly('Test');
expect(polly.container.has('adapter:mock')).to.be.true;
await polly.stop();
Polly.unregister(MockAdapter);
});
it('.unregister()', async function () {
Polly.register(MockAdapter);
let polly = new Polly('Test');
expect(polly.container.has('adapter:mock')).to.be.true;
await polly.stop();
Polly.unregister(MockAdapter);
polly = new Polly('Test');
expect(polly.container.has('adapter:mock')).to.be.false;
await polly.stop();
});
});
describe('Events', function () {
it('register', async function () {
let registerCalled = false;
Polly.once('register', (container) => {
expect(container).to.be.an.instanceof(Container);
registerCalled = true;
});
const polly = new Polly('Test');
expect(registerCalled).to.be.true;
await polly.stop();
});
it('create', async function () {
let createCalled = false;
Polly.once('create', (polly) => {
expect(polly).to.be.an.instanceof(Polly);
createCalled = true;
});
const polly = new Polly('Test');
expect(createCalled).to.be.true;
await polly.stop();
});
it('create - should throw with an async listener', async function () {
Polly.once('create', () => {});
Polly.once('create', () => Promise.resolve());
expect(() => new Polly('Test')).to.throw(PollyError);
});
it('create - configuration order should be preserved', async function () {
Polly.once('create', (polly) => {
polly.configure({ logLevel: 'info', recordIfMissing: false });
});
const polly = new Polly('Test', { recordIfMissing: true });
expect(polly.config.logLevel).to.equal('info');
expect(polly.config.recordIfMissing).to.be.true;
await polly.stop();
});
it('stop', async function () {
let stopCalled = false;
Polly.once('stop', (polly) => {
expect(polly).to.be.an.instanceof(Polly);
expect(polly.mode).to.equal(MODES.STOPPED);
stopCalled = true;
});
const polly = new Polly('Test');
await polly.stop();
expect(stopCalled).to.be.true;
});
});
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/server/handler-test.js
================================================
import Handler from '../../../src/server/handler';
describe('Unit | Server | Handler', function () {
it('should exist', function () {
expect(Handler).to.be.a('function');
});
describe('Events', function () {
it('throws on registering an unknown event name', function () {
expect(() => new Handler().on('unknownEventName')).to.throw(
/Invalid event name provided/
);
});
it('throws on un-registering an unknown event name', function () {
expect(() => new Handler().off('unknownEventName')).to.throw(
/Invalid event name provided/
);
});
it('registers a known event via .on()', function () {
const handler = new Handler();
const { _eventEmitter: eventEmitter } = handler;
expect(eventEmitter.hasListeners('request')).to.be.false;
handler.on('request', () => {});
expect(eventEmitter.hasListeners('request')).to.be.true;
handler.on('request', () => {});
expect(eventEmitter.listeners('request')).to.have.lengthOf(2);
});
it('registers a known event via .on() with { times }', function () {
const handler = new Handler();
const { _eventEmitter: eventEmitter } = handler;
handler.on('request', () => {}, { times: 2 });
expect(eventEmitter.hasListeners('request')).to.be.true;
eventEmitter.emitSync('request');
expect(eventEmitter.hasListeners('request')).to.be.true;
eventEmitter.emitSync('request');
expect(eventEmitter.hasListeners('request')).to.be.false;
});
it('registers a known event via .on() with .times()', function () {
const handler = new Handler();
const { _eventEmitter: eventEmitter } = handler;
handler.times(2).on('request', () => {});
expect(eventEmitter.hasListeners('request')).to.be.true;
eventEmitter.emitSync('request');
expect(eventEmitter.hasListeners('request')).to.be.true;
eventEmitter.emitSync('request');
expect(eventEmitter.hasListeners('request')).to.be.false;
});
it('registers a known event via .on() with .times() and override with { times }', function () {
const handler = new Handler();
const { _eventEmitter: eventEmitter } = handler;
handler.times(2).on('request', () => {}, { times: 1 });
expect(eventEmitter.hasListeners('request')).to.be.true;
eventEmitter.emitSync('request');
expect(eventEmitter.hasListeners('request')).to.be.false;
});
it('registers a known event via .once()', function () {
const handler = new Handler();
const { _eventEmitter: eventEmitter } = handler;
expect(eventEmitter.hasListeners('request')).to.be.false;
handler.once('request', () => {});
expect(eventEmitter.hasListeners('request')).to.be.true;
handler.once('request', () => {});
expect(eventEmitter.listeners('request')).to.have.lengthOf(2);
eventEmitter.emitSync('request');
expect(eventEmitter.hasListeners('request')).to.be.false;
});
it('un-registers a known event via .off()', function () {
const handler = new Handler();
const { _eventEmitter: eventEmitter } = handler;
const fn = () => {};
handler.on('request', fn);
handler.on('request', () => {});
handler.on('request', () => {});
expect(eventEmitter.hasListeners('request')).to.be.true;
expect(eventEmitter.listeners('request')).to.have.lengthOf(3);
handler.off('request', fn);
expect(eventEmitter.hasListeners('request')).to.be.true;
expect(eventEmitter.listeners('request')).to.have.lengthOf(2);
expect(eventEmitter.listeners('request').includes(fn)).to.be.false;
handler.off('request');
expect(eventEmitter.hasListeners('request')).to.be.false;
expect(eventEmitter.listeners('request')).to.have.lengthOf(0);
});
});
describe('.intercept()', function () {
it('registers an intercept handler', function () {
const handler = new Handler();
handler.intercept(() => {});
expect(handler.has('intercept')).to.be.true;
});
it('throws when passing a non-function to intercept', function () {
const handler = new Handler();
[null, undefined, {}, [], ''].forEach((value) => {
expect(() => handler.intercept(value)).to.throw(
/Invalid intercept handler provided/
);
});
});
it('throws when passing an invalid times option', function () {
const handler = new Handler();
['1', -1, 0].forEach((times) => {
expect(() => handler.intercept(() => {}, { times })).to.throw(
/Invalid number provided/
);
});
});
it('registers an intercept handler with { times }', function () {
const handler = new Handler();
handler.intercept(() => {}, { times: 2 });
expect(handler.has('intercept')).to.be.true;
handler.get('intercept')();
expect(handler.has('intercept')).to.be.true;
handler.get('intercept')();
expect(handler.has('intercept')).to.be.false;
});
it('registers an intercept handler with .times()', function () {
const handler = new Handler();
handler.times(2).intercept(() => {});
expect(handler.has('intercept')).to.be.true;
handler.get('intercept')();
expect(handler.has('intercept')).to.be.true;
handler.get('intercept')();
expect(handler.has('intercept')).to.be.false;
});
it('registers an intercept handler with .times() and override with { times }', function () {
const handler = new Handler();
handler.times(2).intercept(() => {}, { times: 1 });
expect(handler.has('intercept')).to.be.true;
handler.get('intercept')();
expect(handler.has('intercept')).to.be.false;
});
});
describe('.passthrough()', function () {
it('should work', function () {
const handler = new Handler();
expect(handler.has('passthrough')).to.be.false;
handler.passthrough();
expect(handler.get('passthrough')).to.be.true;
handler.passthrough(false);
expect(handler.get('passthrough')).to.be.false;
});
it('removes the intercept handler on passthrough', function () {
const handler = new Handler();
handler.intercept(() => {});
expect(handler.has('intercept')).to.be.true;
handler.passthrough();
expect(handler.get('passthrough')).to.be.true;
expect(handler.has('intercept')).to.be.false;
});
it('disables passthrough on intercept', function () {
const handler = new Handler();
handler.passthrough();
expect(handler.get('passthrough')).to.be.true;
expect(handler.has('intercept')).to.be.false;
handler.intercept(() => {});
expect(handler.has('intercept')).to.be.true;
expect(handler.get('passthrough')).to.be.false;
});
});
describe('.recordingName()', function () {
it('should work', function () {
const handler = new Handler();
expect(handler.has('recordingName')).to.be.false;
handler.recordingName('Test');
expect(handler.get('recordingName')).to.equal('Test');
handler.recordingName();
expect(handler.has('recordingName')).to.be.true;
expect(handler.get('recordingName')).to.be.undefined;
});
it('should allow setting a falsy recordingName', function () {
const handler = new Handler();
expect(handler.has('recordingName')).to.be.false;
[false, undefined, null].forEach((value) => {
handler.recordingName(value);
expect(handler.has('recordingName')).to.be.true;
expect(handler.get('recordingName')).to.equal(value);
});
});
it('throws when passing an invalid truthy recording name', function () {
const handler = new Handler();
[1, {}, [], true].forEach((value) => {
expect(() => handler.recordingName(value)).to.throw(
/Invalid recording name provided/
);
});
});
});
describe('.configure()', function () {
it('should work', function () {
const handler = new Handler();
expect(handler.get('config')).to.deep.equal({});
handler.configure({ logLevel: 'info' });
expect(handler.get('config')).to.deep.equal({ logLevel: 'info' });
handler.configure({ recordIfMissing: false });
expect(handler.get('config')).to.deep.equal({ recordIfMissing: false });
handler.configure({});
expect(handler.get('config')).to.deep.equal({});
});
it('throws when passing an invalid config', function () {
const handler = new Handler();
[false, true, null, undefined, 1, []].forEach((config) => {
expect(() => handler.configure(config)).to.throw(
/Invalid config provided/
);
});
[
'mode',
'adapters',
'adapterOptions',
'persister',
'persisterOptions'
].forEach((key) => {
expect(() => handler.configure({ [key]: key })).to.throw(
/Invalid configuration option provided/
);
});
});
});
describe('.filter()', function () {
it('should work', function () {
const handler = new Handler();
const filters = handler.get('filters');
const fn = () => {};
expect(filters.size).to.equal(0);
handler.filter(fn);
expect(filters.size).to.equal(1);
handler.filter(fn);
expect(filters.size).to.equal(1);
handler.filter(() => {});
expect(filters.size).to.equal(2);
});
it('throws when passing an invalid fn', function () {
const handler = new Handler();
[false, true, null, undefined, 1, [], {}, ''].forEach((fn) => {
expect(() => handler.filter(fn)).to.throw(
/Invalid filter callback provided/
);
});
});
});
describe('.times()', function () {
it('should work', function () {
const handler = new Handler();
const defaultOptions = handler.get('defaultOptions');
expect(defaultOptions).to.deep.equal({});
handler.times(1);
expect(defaultOptions).to.deep.equal({ times: 1 });
handler.times(2);
expect(defaultOptions).to.deep.equal({ times: 2 });
handler.times();
expect(defaultOptions).to.deep.equal({});
});
it('throws when passing an invalid times option', function () {
const handler = new Handler();
['1', -1, 0].forEach((times) => {
expect(() => handler.times(times)).to.throw(/Invalid number provided/);
});
});
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/server/server-test.js
================================================
import { HTTP_METHODS } from '@pollyjs/utils';
import Server from '../../../src/server';
let server;
function request(method, path) {
return server.lookup(method, path).handlers[0].get('intercept')();
}
describe('Unit | Server', function () {
it('should exist', function () {
expect(() => new Server()).to.not.throw();
expect(new Server()).to.exist;
});
describe('API', function () {
beforeEach(function () {
server = new Server();
});
it('should handle all HTTP methods', function () {
HTTP_METHODS.forEach((method) => {
server[method.toLowerCase()]('/foo').intercept(() => 200);
expect(request(method, '/foo')).to.equal(200);
});
});
it('should handle multiple routes on all HTTP methods', function () {
HTTP_METHODS.forEach((method) => {
server[method.toLowerCase()]([
`/${method}`,
`/${method}/*path`
]).intercept(() => 200);
expect(request(method, `/${method}`)).to.equal(200);
expect(request(method, `/${method}/foo/bar`)).to.equal(200);
});
});
it('should handle dynamic segments', function () {
server.get('/foo/:seg1').intercept(() => 200);
server.get('/foo/:seg1/bar/:seg2').intercept(() => 400);
expect(request('GET', '/foo/42')).to.equal(200);
expect(request('GET', '/foo/super-secret-guid')).to.equal(200);
expect(request('GET', '/foo/42/bar/abc')).to.equal(400);
});
it('should differentiate hosts with different protocols', function () {
['http', 'https'].forEach((protocol) => {
server.get(`${protocol}://foo.bar`).intercept(() => protocol);
expect(request('GET', `${protocol}://foo.bar`)).to.equal(protocol);
});
});
it('can be scoped to a host', function () {
server.host('http://foo.bar', () => {
server.get('/baz').intercept(() => 200);
});
expect(request('GET', 'http://foo.bar/baz')).to.equal(200);
});
it('can handle index route registration', function () {
server.host('http://foo', () => {
server.get('/').intercept(() => 200);
});
expect(request('GET', 'http://foo')).to.equal(200);
expect(request('GET', 'http://foo/')).to.equal(200);
});
it('should reset the host after scoping', function () {
server.host('http://foo.bar', () => {});
server.get('/foo').intercept(() => 200);
expect(() => request('GET', 'http://foo.bar/foo')).to.throw();
expect(request('GET', '/foo')).to.equal(200);
});
it('should throw when nesting hosts', function () {
expect(() => {
server.host('http://foo.bar', () => {
server.host('http://bar.baz', () => {});
});
}).to.throw();
});
it('should reset the namespace after scoping', function () {
server.namespace('/api', () => {});
server.get('/foo').intercept(() => 200);
expect(() => request('GET', '/api/foo')).to.throw();
expect(request('GET', '/foo')).to.equal(200);
});
it('can be scoped to multiple namespaces', function () {
server.namespace('/api', () => {
server.get('/foo').intercept(() => 'foo');
server.namespace('/v2', () => {
server.get('/bar').intercept(() => 'bar');
});
});
expect(request('GET', '/api/foo')).to.equal('foo');
expect(request('GET', '/api/v2/bar')).to.equal('bar');
});
});
describe('Route Matching', function () {
beforeEach(function () {
server = new Server();
});
function addHandlers(url) {
server.get(url).on('request', () => {});
server.get(url).on('response', () => {});
server.get(url).intercept(() => {});
}
it('should concat handlers for same paths', async function () {
[
'/ping',
'/ping/:id',
'/ping/*path',
'http://ping.com',
'http://ping.com/pong/:id',
'http://ping.com/pong/*path'
].forEach((url) => {
addHandlers(url);
expect(server.lookup('GET', url).handlers).to.have.lengthOf(3);
});
});
it('should concat handlers for same paths with a trailing slash', async function () {
addHandlers('/ping');
expect(server.lookup('GET', '/ping').handlers).to.have.lengthOf(3);
addHandlers('/ping/');
expect(server.lookup('GET', '/ping').handlers).to.have.lengthOf(6);
expect(server.lookup('GET', '/ping/').handlers).to.have.lengthOf(6);
addHandlers('http://ping.com');
expect(server.lookup('GET', 'http://ping.com').handlers).to.have.lengthOf(
3
);
addHandlers('http://ping.com/');
expect(server.lookup('GET', 'http://ping.com').handlers).to.have.lengthOf(
6
);
expect(
server.lookup('GET', 'http://ping.com/').handlers
).to.have.lengthOf(6);
});
it('should concat handlers for same paths with different dynamic segment names', async function () {
addHandlers('/ping/:id');
expect(server.lookup('GET', '/ping/:id').handlers).to.have.lengthOf(3);
addHandlers('/ping/:uuid');
expect(server.lookup('GET', '/ping/:id').handlers).to.have.lengthOf(6);
expect(server.lookup('GET', '/ping/:uuid').handlers).to.have.lengthOf(6);
});
it('should concat handlers for same paths with different star segment names', async function () {
addHandlers('/ping/*path');
expect(server.lookup('GET', '/ping/*path').handlers).to.have.lengthOf(3);
addHandlers('/ping/*rest');
expect(server.lookup('GET', '/ping/*path').handlers).to.have.lengthOf(6);
expect(server.lookup('GET', '/ping/*rest').handlers).to.have.lengthOf(6);
});
it('should concat handlers for same paths with different dynamic and star segment names', async function () {
addHandlers('/ping/:id/pong/*path');
expect(
server.lookup('GET', '/ping/:id/pong/*path').handlers
).to.have.lengthOf(3);
addHandlers('/ping/:uuid/pong/*rest');
expect(
server.lookup('GET', '/ping/:id/pong/*path').handlers
).to.have.lengthOf(6);
expect(
server.lookup('GET', '/ping/:uuid/pong/*rest').handlers
).to.have.lengthOf(6);
});
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/test-helpers/mocha-test.js
================================================
import setupPolly from '../../../src/test-helpers/mocha';
class Sandbox {
constructor(context) {
this.beforeEachCalled = new Set();
this.afterEachCalled = new Set();
this.context = context || { currentTest: { title: 'mockname' } };
}
beforeEach(fn) {
this.beforeEachCalled.add(fn);
fn.call(this.context, undefined);
}
afterEach(fn) {
this.afterEachCalled.add(fn);
fn.call(this.context, undefined);
}
}
describe('Unit | Test Helpers | mocha', function () {
it('should exist', function () {
expect(setupPolly).to.be.a('function');
expect(setupPolly.beforeEach).to.be.a('function');
expect(setupPolly.afterEach).to.be.a('function');
});
it('should invoke beforeEach and afterEach', function () {
const stub = new Sandbox();
setupPolly({}, stub);
expect(stub.beforeEachCalled.size).to.equal(1);
expect(stub.afterEachCalled.size).to.equal(1);
});
it('should create a polly property and set recordingName', function () {
const stub = new Sandbox();
setupPolly({}, stub);
expect(stub.context.polly).to.be.a('object');
expect(stub.context.polly.recordingName).to.equal('mockname');
});
it('should concat title if test is deeply nested', function () {
const stub = new Sandbox({
currentTest: {
title: 'foo',
parent: {
title: 'bar',
parent: {
title: 'baz'
}
}
}
});
setupPolly({}, stub);
expect(stub.context.polly.recordingName).to.equal('baz/bar/foo');
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/utils/deferred-promise-test.js
================================================
import defer from '../../../src/utils/deferred-promise';
describe('Unit | Utils | DeferredPromise', function () {
it('should exist', function () {
expect(defer).to.be.a('function');
expect(defer().resolve).to.be.a('function');
expect(defer().reject).to.be.a('function');
});
it('should resolve when calling .resolve()', async function () {
const promise = defer();
promise.resolve(42);
expect(await promise).to.equal(42);
});
it('should reject when calling .reject()', async function () {
const promise = defer();
promise.reject(new Error('42'));
try {
await promise;
} catch (error) {
expect(error).to.be.an('error');
expect(error.message).to.equal('42');
}
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/utils/guid-for-recording-test.js
================================================
import guidForRecording from '../../../src/utils/guid-for-recording';
describe('Unit | Utils | guidForRecording', function () {
it('should exist', function () {
expect(guidForRecording).to.be.a('function');
});
it('should remove illegal file system characters', function () {
expect(guidForRecording(`'?<>\\:*|"`)).to.equal('_3218500777');
});
it('should create a guid for each segment of the name', function () {
const name = guidForRecording(`foo!/bar%/baz..`);
expect(name).to.equal('foo_2152783170/bar_567945773/baz_1682401886');
});
it('should trim name to 100 characters', function () {
const name = guidForRecording(new Array(200).fill('A').join(''));
expect(name.length).to.be.lte(100);
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/utils/http-headers-test.js
================================================
import HTTPHeaders from '../../../src/utils/http-headers';
const { keys } = Object;
describe('Unit | Utils | HTTPHeaders', function () {
it('should exist', function () {
expect(HTTPHeaders).to.be.a('function');
});
it('should be instantiable', function () {
expect(new HTTPHeaders()).to.be.an('object');
});
it('can be constructed with defaults', function () {
expect(new HTTPHeaders({ A: 'a', b: 'b' })).to.deep.equal({
a: 'a',
b: 'b'
});
});
it('should lower-case keys', function () {
const headers = new HTTPHeaders();
headers['Content-Type'] = 'application/json';
expect(headers['content-type']).to.equal('application/json');
expect(headers['Content-Type']).to.equal('application/json');
expect(headers['CONTENT-TYPE']).to.equal('application/json');
});
it('should allow an empty header value', function () {
const headers = new HTTPHeaders();
headers['Content-Type'] = '';
expect(headers['Content-Type']).to.equal('');
});
it('should delete header regardless of case', function () {
const headers = new HTTPHeaders();
headers['Content-Type'] = 'application/json';
expect(keys(headers)).to.deep.equal(['content-type']);
delete headers['Content-Type'];
expect(keys(headers)).to.deep.equal([]);
headers['Content-Type'] = 'application/json';
expect(keys(headers)).to.deep.equal(['content-type']);
delete headers['CONTENT-TYPE'];
expect(keys(headers)).to.deep.equal([]);
});
it('should delete header when set with a null/undefined value', function () {
const headers = new HTTPHeaders();
headers['Content-Type'] = 'application/json';
expect(keys(headers)).to.deep.equal(['content-type']);
headers['Content-Type'] = null;
expect(keys(headers)).to.deep.equal([]);
headers['Content-Type'] = 'application/json';
expect(keys(headers)).to.deep.equal(['content-type']);
headers['Content-Type'] = undefined;
expect(keys(headers)).to.deep.equal([]);
});
it('should handle a non string getter', function () {
const headers = new HTTPHeaders();
expect(() => headers[Symbol()]).to.not.throw();
});
it('should not allow setting a non string header key', function () {
const headers = new HTTPHeaders();
expect(() => (headers[Symbol()] = 'Foo')).to.throw(TypeError);
});
it('should not allow deleting a non string header key', function () {
const headers = new HTTPHeaders();
expect(() => delete headers[Symbol()]).to.throw(TypeError);
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/utils/merge-configs-test.js
================================================
import mergeConfigs from '../../../src/utils/merge-configs';
describe('Unit | Utils | mergeConfigs', function () {
it('should exist', function () {
expect(mergeConfigs).to.be.a('function');
});
it('should not deep merge context objects', async function () {
const context = {};
const config = mergeConfigs(
{ fetch: {}, xhr: {} },
{ fetch: { context } },
{ xhr: { context } },
{ fetch: {}, xhr: {} }
);
expect(config.fetch.context).to.equal(context);
expect(config.xhr.context).to.equal(context);
});
it('should not deep merge arrays', async function () {
const array = [{}];
const config = mergeConfigs({ array: [] }, { array });
expect(config.array).to.equal(array);
expect(config.array[0]).to.equal(array[0]);
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/utils/normalize-request-test.js
================================================
import {
body,
headers,
method,
url
} from '../../../src/utils/normalize-request';
describe('Unit | Utils | Normalize Request', function () {
it('should exist', function () {
expect(url).to.be.a('function');
expect(body).to.be.a('function');
expect(method).to.be.a('function');
expect(headers).to.be.a('function');
});
describe('method', function () {
it('should handle all verbs', function () {
expect(method('get')).to.equal('GET');
expect(method('put')).to.equal('PUT');
expect(method('post')).to.equal('POST');
expect(method('patch')).to.equal('PATCH');
expect(method('delete')).to.equal('DELETE');
expect(method('option')).to.equal('OPTION');
});
it('should support a custom fn', function () {
expect(method('GET', (m) => m.toLowerCase())).to.equal('get');
});
it('should pass the correct arguments to the custom fn', function () {
const req = {};
method(
'GET',
(method, request) => {
expect(method).to.equal('GET');
expect(request).to.equal(req);
return method;
},
req
);
});
});
describe('headers', function () {
it('should lower-case all header keys', function () {
expect(
headers({
Accept: 'foo',
'Content-Type': 'Bar'
})
).to.deep.equal({
accept: 'foo',
'content-type': 'Bar'
});
});
it('should exclude specified headers', function () {
expect(
headers(
{
Accept: 'foo',
test: 'test',
'Content-Type': 'Bar'
},
{ exclude: ['test', 'content-type'] }
)
).to.deep.equal({ accept: 'foo' });
});
it('should support a custom fn', function () {
expect(
headers(
{
Accept: 'foo',
test: 'test',
'Content-Type': 'Bar'
},
(headers) => {
delete headers.test;
return headers;
}
)
).to.deep.equal({ accept: 'foo', 'content-type': 'Bar' });
});
it('should pass the correct arguments to the custom fn', function () {
const req = {};
const reqHeaders = { foo: 'foo' };
headers(
reqHeaders,
(headers, request) => {
expect(headers).to.deep.equal(reqHeaders);
expect(request).to.equal(req);
return headers;
},
req
);
});
it('should not mutate the original headers in the custom fn', function () {
const reqHeaders = { foo: 'bar' };
expect(
headers(reqHeaders, (headers) => {
delete headers.foo;
return headers;
})
).to.deep.equal({});
expect(reqHeaders).to.deep.equal({ foo: 'bar' });
});
});
describe('url', function () {
it('should sort query params', function () {
expect(url('http://foo.com/?b=1&c=1&a=1', {})).to.equal(
'http://foo.com/?a=1&b=1&c=1'
);
});
it('should respect `matchRequestsBy.url` config', function () {
[
[
/* config options */
'hash',
/* input url */
'http://hash-test.com/?b=1&c=1&a=1#hello=world',
/* expected when true */
[true, 'http://hash-test.com/?a=1&b=1&c=1#hello=world'],
/* expected when false */
[false, 'http://hash-test.com/?a=1&b=1&c=1'],
/* expected when custom fn */
[
(h) => h.replace('=', '!='),
'http://hash-test.com/?a=1&b=1&c=1#hello!=world'
]
],
[
'protocol',
'http://protocol-test.com/',
[true, 'http://protocol-test.com/'],
[false, '//protocol-test.com/'],
[(p) => p.replace('http', 'https'), 'https://protocol-test.com/']
],
[
'query',
'http://query-test.com/?b=1&c=1&a=1',
[true, 'http://query-test.com/?a=1&b=1&c=1'],
[false, 'http://query-test.com/'],
[(q) => ({ ...q, c: 2 }), 'http://query-test.com/?a=1&b=1&c=2']
],
[
'username',
'https://username:password@username-test.com/',
[true, 'https://username:password@username-test.com/'],
[false, 'https://username-test.com/'],
[(u) => `${u}123`, 'https://username123:password@username-test.com/']
],
[
'password',
'https://username:password@password-test.com/',
[true, 'https://username:password@password-test.com/'],
[false, 'https://username@password-test.com/'],
[(p) => `${p}123`, 'https://username:password123@password-test.com/']
],
[
'port',
'https://port-test.com:8000/',
[true, 'https://port-test.com:8000/'],
[false, 'https://port-test.com/'],
[(p) => Number(p) + 1, 'https://port-test.com:8001/']
],
[
'pathname',
'https://pathname-test.com/bar/baz',
[true, 'https://pathname-test.com/bar/baz'],
[false, 'https://pathname-test.com'],
[(p) => p.replace('bar', 'foo'), 'https://pathname-test.com/foo/baz']
]
].forEach(([rule, input, ...options]) => {
options.forEach(([optionValue, expectedOutput]) => {
expect(url(input, { [rule]: optionValue })).to.equal(expectedOutput);
});
});
});
it('should respect relative urls', function () {
expect(url('/some/path')).to.equal('/some/path');
});
it('should support a custom fn', function () {
expect(
url('https://foo.bar/', (url) => url.replace('bar', 'foo'))
).to.equal('https://foo.foo/');
});
it('should pass the correct arguments to the custom fn', function () {
const req = {};
url(
'https://foo.bar',
(url, request) => {
expect(url).to.deep.equal('https://foo.bar');
expect(request).to.equal(req);
return url;
},
req
);
});
it("should pass the correct arguments to the individual `matchRequestsBy.url` option's custom fn", function () {
const req = {};
url(
'https://foo.bar',
{
protocol: (protocol, request) => {
expect(protocol).to.deep.equal('https:');
expect(request).to.equal(req);
return protocol;
}
},
req
);
});
});
describe('body', function () {
it('should support a custom fn', function () {
expect(body('foo', (b) => b.toUpperCase())).to.equal('FOO');
});
it('should pass the correct arguments to the custom fn', function () {
const req = {};
url(
'body',
(body, request) => {
expect(body).to.deep.equal('body');
expect(request).to.equal(req);
return body;
},
req
);
});
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/utils/parse-url-test.js
================================================
import parseUrl from '../../../src/utils/parse-url';
describe('Unit | Utils | parseUrl', function () {
it('should exist', function () {
expect(parseUrl).to.be.a('function');
});
it('should exactly match passed urls', function () {
[
'/movies/1',
'http://netflix.com/movies/1',
'http://netflix.com/movies/1?sort=title&dir=asc'
].forEach((url) => expect(parseUrl(url).href).to.equal(url));
});
it('should passthrough arguments to url-parse', function () {
// Passing true tells url-parse to transform the querystring into an object
expect(parseUrl('/movies/1?sort=title&dir=asc', true).query).to.deep.equal({
sort: 'title',
dir: 'asc'
});
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/utils/remove-host-from-url-test.js
================================================
import { URL } from '@pollyjs/utils';
import removeHost from '../../../src/utils/remove-host-from-url';
describe('Unit | Utils | removeHostFromUrl', function () {
it('should exist', function () {
expect(removeHost).to.be.a('function');
});
it('should remove hostname', function () {
const url = removeHost(new URL('http://foo.com/bar/baz/'));
expect(url.toString()).to.equal('/bar/baz/');
});
it('should remove hostname without a tld', function () {
const url = removeHost(new URL('http://foo/bar/baz/'));
expect(url.toString()).to.equal('/bar/baz/');
});
});
================================================
FILE: packages/@pollyjs/core/tests/unit/utils/timing-test.js
================================================
import Timing from '../../../src/utils/timing';
function fixedTest(ms) {
it(`should handle ${ms}ms`, async function () {
// Fail the test if it exceeds ms + 10ms buffer
this.timeout(ms + 50);
const promise = Timing.fixed(ms)();
let resolved = false;
promise.then(() => (resolved = true));
if (ms) {
setTimeout(() => expect(resolved).to.be.false, ms / 2);
}
setTimeout(() => expect(resolved).to.be.true, ms + 1);
await promise;
});
}
function relativeTest(ratio) {
const timeout = ratio * 100;
it(`should handle a ratio of ${ratio}`, async function () {
// Fail the test if it exceeds timeout + 10ms buffer
this.timeout(timeout + 50);
const promise = Timing.relative(ratio)(100);
let resolved = false;
promise.then(() => (resolved = true));
if (timeout) {
setTimeout(() => expect(resolved).to.be.false, timeout / 2);
}
setTimeout(() => expect(resolved).to.be.true, timeout + 1);
await promise;
});
}
describe('Unit | Utils | Timing', function () {
it('should exist', function () {
expect(Timing).to.be.a('object');
expect(Timing.fixed).to.be.a('function');
expect(Timing.relative).to.be.a('function');
});
describe('fixed', function () {
fixedTest(0);
fixedTest(50);
fixedTest(100);
});
describe('relative', function () {
relativeTest(0);
relativeTest(0.5);
relativeTest(1.0);
relativeTest(2.0);
});
});
================================================
FILE: packages/@pollyjs/core/types.d.ts
================================================
import Adapter from '@pollyjs/adapter';
import Persister from '@pollyjs/persister';
import { Logger, LogLevelDesc } from 'loglevel';
type Newable = { new (...args: any[]): T };
export type MODE = 'record' | 'replay' | 'passthrough' | 'stopped';
export type ACTION = 'record' | 'replay' | 'intercept' | 'passthrough';
export type EXPIRY_STRATEGY = 'record' | 'warn' | 'error';
export const Timing: {
fixed(ms: number): () => Promise;
relative(ratio: number): (ms: number) => Promise;
};
export type MatchBy = (input: T, req: Request) => R;
export type Headers = Record;
export interface PollyConfig {
mode?: MODE | undefined;
adapters?: Array> | undefined;
adapterOptions?:
| {
fetch?: { context?: any } | undefined;
puppeteer?:
| { page?: any; requestResourceTypes?: string[] | undefined }
| undefined;
xhr?: { context?: any } | undefined;
[key: string]: any;
}
| undefined;
persister?: string | Newable | undefined;
persisterOptions?:
| {
keepUnusedRequests?: boolean | undefined;
disableSortingHarEntries?: boolean | undefined;
fs?: { recordingsDir?: string | undefined } | undefined;
'local-storage'?:
| { context?: any; key?: string | undefined }
| undefined;
rest?:
| { host?: string | undefined; apiNamespace?: string | undefined }
| undefined;
[key: string]: any;
}
| undefined;
logLevel?: LogLevelDesc | undefined;
flushRequestsOnStop?: boolean | undefined;
recordIfMissing?: boolean | undefined;
recordFailedRequests?: boolean | undefined;
expiryStrategy?: EXPIRY_STRATEGY | undefined;
expiresIn?: string | null | undefined;
timing?: ((ms: number) => Promise) | (() => Promise) | undefined;
matchRequestsBy?:
| {
method?: boolean | MatchBy | undefined;
headers?:
| boolean
| { exclude: string[] }
| MatchBy
| undefined;
body?: boolean | MatchBy | undefined;
order?: boolean | undefined;
url?:
| boolean
| MatchBy
| {
protocol?: boolean | MatchBy | undefined;
username?: boolean | MatchBy | undefined;
password?: boolean | MatchBy | undefined;
hostname?: boolean | MatchBy | undefined;
port?: boolean | MatchBy | undefined;
pathname?: boolean | MatchBy | undefined;
query?: boolean | MatchBy<{ [key: string]: any }> | undefined;
hash?: boolean | MatchBy | undefined;
}
| undefined;
}
| undefined;
}
export interface HTTPBase {
headers: Headers;
body?: string;
getHeader(name: string): string | string[] | null;
setHeader(name: string, value?: string | string[] | null): this;
setHeaders(headers: Headers): this;
removeHeader(name: string): this;
removeHeaders(headers: string[]): this;
hasHeader(name: string): boolean;
type(contentType: string): this;
send(body: any): this;
json(body: any): this;
jsonBody(): any;
}
export type RequestEvent = 'identify';
export type RequestArguments = { [key: string]: any };
export interface Request
extends HTTPBase {
method: string;
url: string;
readonly absoluteUrl: string;
readonly protocol: string;
readonly hostname: string;
readonly port: string;
readonly pathname: string;
hash: string;
query: { [key: string]: string | string[] };
readonly params: { [key: string]: string };
readonly log: Logger;
readonly requestArguments: TArguments;
recordingName: string;
recordingId: string;
responseTime?: number | undefined;
timestamp?: string | undefined;
didRespond: boolean;
id?: string | undefined;
order?: number | undefined;
action: ACTION | null;
aborted: boolean;
promise: Promise;
response?: Response;
configure(config: Partial): void;
overrideRecordingName(recordingName: string): void;
on(event: RequestEvent, listener: RequestEventListener): this;
once(event: RequestEvent, listener: RequestEventListener): this;
off(event: RequestEvent, listener?: RequestEventListener): this;
}
export interface Response extends HTTPBase {
statusCode: number;
encoding: string | undefined;
readonly statusText: string;
readonly ok: boolean;
status(status: number): this;
sendStatus(status: number): this;
end(): Readonly;
}
export type RequestRouteEvent = 'request';
export type RecordingRouteEvent = 'beforeReplay' | 'beforePersist';
export type ResponseRouteEvent = 'beforeResponse' | 'response';
export type ErrorRouteEvent = 'error';
export type AbortRouteEvent = 'abort';
export interface ListenerEvent {
readonly type: string;
stopPropagation: () => void;
}
export interface Interceptor extends ListenerEvent {
abort(): void;
passthrough(): void;
}
export type ErrorEventListener = (
req: Request,
error: any,
event: ListenerEvent
) => void | Promise;
export type AbortEventListener = (
req: Request,
event: ListenerEvent
) => void | Promise;
export type RequestEventListener = (
req: Request,
event: ListenerEvent
) => void | Promise;
export type RecordingEventListener = (
req: Request,
recording: any,
event: ListenerEvent
) => void | Promise;
export type ResponseEventListener = (
req: Request,
res: Response,
event: ListenerEvent
) => void | Promise;
export type InterceptHandler = (
req: Request,
res: Response,
interceptor: Interceptor
) => void | Promise;
export class RouteHandler {
on(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler;
on(
event: RecordingRouteEvent,
listener: RecordingEventListener
): RouteHandler;
on(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler;
on(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler;
on(event: AbortRouteEvent, listener: AbortEventListener): RouteHandler;
off(event: RequestRouteEvent, listener?: RequestEventListener): RouteHandler;
off(
event: RecordingRouteEvent,
listener?: RecordingEventListener
): RouteHandler;
off(
event: ResponseRouteEvent,
listener?: ResponseEventListener
): RouteHandler;
off(event: ErrorRouteEvent, listener?: ErrorEventListener): RouteHandler;
off(event: AbortRouteEvent, listener?: AbortEventListener): RouteHandler;
once(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler;
once(
event: RecordingRouteEvent,
listener: RecordingEventListener
): RouteHandler;
once(
event: ResponseRouteEvent,
listener: ResponseEventListener
): RouteHandler;
once(event: ErrorRouteEvent, listener: ErrorEventListener): RouteHandler;
once(event: AbortRouteEvent, listener: AbortEventListener): RouteHandler;
filter: (callback: (req: Request) => boolean) => RouteHandler;
passthrough(value?: boolean): RouteHandler;
intercept(fn: InterceptHandler): RouteHandler;
recordingName(recordingName?: string): RouteHandler;
configure(config: Partial): RouteHandler;
times(n?: number): RouteHandler;
}
export class PollyServer {
timeout(ms: number): Promise;
get(routes?: string | string[]): RouteHandler;
put(routes?: string | string[]): RouteHandler;
post(routes?: string | string[]): RouteHandler;
delete(routes?: string | string[]): RouteHandler;
patch(routes?: string | string[]): RouteHandler;
head(routes?: string | string[]): RouteHandler;
options(routes?: string | string[]): RouteHandler;
merge(routes?: string | string[]): RouteHandler;
any(routes?: string | string[]): RouteHandler;
host(host: string, callback: () => void): void;
namespace(path: string, callback: () => void): void;
}
export class PollyLogger {
polly: Polly;
log: Logger;
connect(): void;
disconnect(): void;
logRequest(request: Request): void;
logRequestResponse(request: Request, response: Response): void;
logRequestError(request: Request, error: Error): void;
}
export type PollyEvent = 'create' | 'stop' | 'register';
export type PollyEventListener = (poll: Polly) => void;
export class Polly {
static register(Factory: Newable): void;
static unregister(Factory: Newable): void;
static on(event: PollyEvent, listener: PollyEventListener): void;
static off(event: PollyEvent, listener: PollyEventListener): void;
static once(event: PollyEvent, listener: PollyEventListener): void;
constructor(recordingName: string, options?: PollyConfig);
static VERSION: string;
recordingName: string;
recordingId: string;
mode: MODE;
server: PollyServer;
persister: Persister | null;
adapters: Map;
config: PollyConfig;
logger: PollyLogger;
private _requests: Request[];
pause(): void;
play(): void;
replay(): void;
record(): void;
passthrough(): void;
stop(): Promise;
flush(): Promise;
configure(config: Partial): void;
connectTo(name: string | typeof Adapter): void;
disconnectFrom(name: string | typeof Adapter): void;
disconnect(): void;
}
export const setupMocha: {
(config?: PollyConfig, context?: any): void;
beforeEach: (config?: PollyConfig, context?: any) => void;
afterEach: (context?: any) => void;
};
export const setupQunit: {
(hooks: any, config?: PollyConfig): void;
beforeEach: (hooks: any, config?: PollyConfig) => void;
afterEach: (hooks: any) => void;
};
================================================
FILE: packages/@pollyjs/ember/.editorconfig
================================================
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_size = 2
[*.hbs]
insert_final_newline = false
[*.{diff,md}]
trim_trailing_whitespace = false
================================================
FILE: packages/@pollyjs/ember/.ember-cli
================================================
{
/**
Ember CLI sends analytics information by default. The data is completely
anonymous, but there are times when you might want to disable this behavior.
Setting `disableAnalytics` to true will prevent any data from being sent.
*/
"disableAnalytics": false
}
================================================
FILE: packages/@pollyjs/ember/.eslintignore
================================================
# unconventional js
/blueprints/*/files/
/vendor/
# compiled output
/dist/
/tmp/
# dependencies
/bower_components/
/node_modules/
# misc
/coverage/
!.*
.*/
.eslintcache
# ember-try
/.node_modules.ember-try/
/bower.json.ember-try
/package.json.ember-try
================================================
FILE: packages/@pollyjs/ember/.eslintrc.js
================================================
'use strict';
module.exports = {
root: true,
parser: '@babel/eslint-parser',
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
requireConfigFile: false,
ecmaFeatures: {
legacyDecorators: true
}
},
plugins: ['ember'],
extends: [
'eslint:recommended',
'plugin:ember/recommended',
'plugin:prettier/recommended'
],
env: {
browser: true,
node: true
},
rules: {},
overrides: [
// node files
{
files: [
'./.eslintrc.js',
'./.prettierrc.js',
'./.template-lintrc.js',
'./ember-cli-build.js',
'./index.js',
'./testem.js',
'./blueprints/*/index.js',
'./config/**/*.js',
'./tests/dummy/config/**/*.js'
],
parserOptions: {
sourceType: 'script'
},
env: {
browser: false,
node: true
},
plugins: ['node'],
extends: ['plugin:node/recommended']
},
{
// Test files:
files: ['tests/**/*-test.{js,ts}'],
extends: ['plugin:qunit/recommended']
}
]
};
================================================
FILE: packages/@pollyjs/ember/.gitignore
================================================
# See https://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
/dist/
/tmp/
# dependencies
/bower_components/
/node_modules/
# misc
/.env*
/.pnp*
/.sass-cache
/.eslintcache
/connect.lock
/coverage/
/libpeerconnection.log
/npm-debug.log*
/testem.log
/yarn-error.log
# ember-try
/.node_modules.ember-try/
/bower.json.ember-try
/package.json.ember-try
================================================
FILE: packages/@pollyjs/ember/.npmignore
================================================
# compiled output
/dist/
/tmp/
# dependencies
/bower_components/
# misc
/.bowerrc
/.editorconfig
/.ember-cli
/.env*
/.eslintcache
/.eslintignore
/.eslintrc.js
/.git/
/.gitignore
/.prettierignore
/.prettierrc.js
/.template-lintrc.js
/.travis.yml
/.watchmanconfig
/bower.json
/config/ember-try.js
/CONTRIBUTING.md
/ember-cli-build.js
/testem.js
/tests/
/yarn-error.log
/yarn.lock
.gitkeep
# ember-try
/.node_modules.ember-try/
/bower.json.ember-try
/package.json.ember-try
================================================
FILE: packages/@pollyjs/ember/.prettierignore
================================================
# unconventional js
/blueprints/*/files/
/vendor/
# compiled output
/dist/
/tmp/
# dependencies
/bower_components/
/node_modules/
# misc
/coverage/
!.*
.eslintcache
# ember-try
/.node_modules.ember-try/
/bower.json.ember-try
/package.json.ember-try
================================================
FILE: packages/@pollyjs/ember/.prettierrc.js
================================================
'use strict';
module.exports = {
singleQuote: true,
trailingComma: 'none'
};
================================================
FILE: packages/@pollyjs/ember/.template-lintrc.js
================================================
'use strict';
module.exports = {
extends: 'recommended',
};
================================================
FILE: packages/@pollyjs/ember/.watchmanconfig
================================================
{
"ignore_dirs": ["tmp", "dist", "tests/recordings"]
}
================================================
FILE: packages/@pollyjs/ember/CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.6](https://github.com/netflix/pollyjs/compare/v6.0.5...v6.0.6) (2023-07-20)
**Note:** Version bump only for package @pollyjs/ember
## [6.0.1](https://github.com/netflix/pollyjs/compare/v6.0.0...v6.0.1) (2021-12-06)
### Bug Fixes
* **ember:** Bump peer dependencies to 6.x ([#432](https://github.com/netflix/pollyjs/issues/432)) ([1529226](https://github.com/netflix/pollyjs/commit/152922688744c8a2f8d89f793dcecf3c2bc40033))
# [6.0.0](https://github.com/netflix/pollyjs/compare/v5.2.0...v6.0.0) (2021-11-30)
* feat(ember)!: Upgrade to ember octane (#415) ([8559ef8](https://github.com/netflix/pollyjs/commit/8559ef8c600aefaec629870eac5f5c8953e18b16)), closes [#415](https://github.com/netflix/pollyjs/issues/415)
### BREAKING CHANGES
* @pollyjs dependencies have been moved to peer dependencies
# [5.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v5.1.1...v5.2.0) (2021-11-24)
### Features
* **ember:** Upgrade ember-cli-babel to ^7.26.6 ([#411](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/issues/411)) ([4352881](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/4352881))
## [5.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v5.1.0...v5.1.1) (2021-06-02)
**Note:** Version bump only for package @pollyjs/ember
# [5.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v5.0.2...v5.1.0) (2020-12-12)
**Note:** Version bump only for package @pollyjs/ember
## [5.0.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v5.0.0...v5.0.1) (2020-09-25)
**Note:** Version bump only for package @pollyjs/ember
# [5.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v4.3.0...v5.0.0) (2020-06-23)
**Note:** Version bump only for package @pollyjs/ember
# [4.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v4.2.1...v4.3.0) (2020-05-18)
**Note:** Version bump only for package @pollyjs/ember
## [4.2.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v4.2.0...v4.2.1) (2020-04-30)
**Note:** Version bump only for package @pollyjs/ember
# [4.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v4.1.0...v4.2.0) (2020-04-29)
**Note:** Version bump only for package @pollyjs/ember
# [4.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v4.0.4...v4.1.0) (2020-04-23)
**Note:** Version bump only for package @pollyjs/ember
## [4.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v4.0.3...v4.0.4) (2020-03-21)
**Note:** Version bump only for package @pollyjs/ember
## [4.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v4.0.1...v4.0.2) (2020-01-29)
**Note:** Version bump only for package @pollyjs/ember
## [4.0.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v4.0.0...v4.0.1) (2020-01-25)
### Bug Fixes
* **ember:** Config read from project root ([7d6da38](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/7d6da38))
# [4.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v3.0.2...v4.0.0) (2020-01-13)
### chore
* Drop node 8 support ([#292](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/issues/292)) ([4448be5](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/4448be5))
### BREAKING CHANGES
* Drop support for Node 8 as it is now EOL
## [3.0.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v3.0.0...v3.0.1) (2019-12-25)
**Note:** Version bump only for package @pollyjs/ember
# [3.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v2.7.0...v3.0.0) (2019-12-18)
### Bug Fixes
* **ember:** loads polly config for ember by its own module ([#277](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/issues/277)) ([0569040](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/0569040))
### BREAKING CHANGES
* **ember:** moves location of polly configuration
# [2.7.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v2.6.3...v2.7.0) (2019-11-21)
**Note:** Version bump only for package @pollyjs/ember
## [2.6.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v2.6.2...v2.6.3) (2019-09-30)
**Note:** Version bump only for package @pollyjs/ember
## [2.6.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v2.6.1...v2.6.2) (2019-08-05)
**Note:** Version bump only for package @pollyjs/ember
## [2.6.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v2.6.0...v2.6.1) (2019-08-01)
**Note:** Version bump only for package @pollyjs/ember
# [2.6.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v2.5.0...v2.6.0) (2019-07-17)
**Note:** Version bump only for package @pollyjs/ember
# [2.5.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v2.4.0...v2.5.0) (2019-06-06)
**Note:** Version bump only for package @pollyjs/ember
# [2.4.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v2.3.2...v2.4.0) (2019-04-27)
**Note:** Version bump only for package @pollyjs/ember
## [2.3.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v2.3.0...v2.3.1) (2019-03-06)
**Note:** Version bump only for package @pollyjs/ember
# [2.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v2.2.0...v2.3.0) (2019-02-27)
**Note:** Version bump only for package @pollyjs/ember
# [2.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v2.1.0...v2.2.0) (2019-02-20)
**Note:** Version bump only for package @pollyjs/ember
# [2.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v2.0.0...v2.1.0) (2019-02-04)
**Note:** Version bump only for package @pollyjs/ember
# [2.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v1.4.2...v2.0.0) (2019-01-29)
### Bug Fixes
* **ember:** Remove Node 6 from supported versions ([#169](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/ember/issues/169)) ([07b2b4e](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/07b2b4e))
## [1.4.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v1.4.1...v1.4.2) (2019-01-16)
**Note:** Version bump only for package @pollyjs/ember
## [1.4.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v1.4.0...v1.4.1) (2018-12-13)
**Note:** Version bump only for package @pollyjs/ember
## [1.3.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v1.3.1...v1.3.2) (2018-11-29)
**Note:** Version bump only for package @pollyjs/ember
## [1.3.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/v1.2.0...v1.3.1) (2018-11-28)
**Note:** Version bump only for package @pollyjs/ember
# 1.2.0 (2018-09-16)
### Bug Fixes
* Bumping core within Ember ([af4faa1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/af4faa1))
* Ensure polly's middleware goes before ember-cli's ([#36](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/ember/issues/36)) ([43db361](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/43db361))
* **core:** Set `url` on the fetch Response object ([#44](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/ember/issues/44)) ([f5980cf](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/f5980cf)), closes [#43](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/issues/43)
* **ember:** Fix auto-register and add tests to cover ([24c15bd](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/24c15bd))
### Features
* Class events and EventEmitter ([#52](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/ember/issues/52)) ([0a3d591](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/0a3d591))
* Custom persister support ([8bb313c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/8bb313c))
* Improved adapter and persister registration ([#62](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/ember/issues/62)) ([164dbac](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/164dbac))
* Keyed persister & adapter options ([#60](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/ember/issues/60)) ([29ed8e1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/29ed8e1))
* Make recording size limit configurable ([#40](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/ember/issues/40)) ([d4be431](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/d4be431))
* Node File System Persister ([#61](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/ember/issues/61)) ([0a0eeca](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/0a0eeca))
* Presets persisterOptions.host to the node server default ([0b47838](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/0b47838))
### BREAKING CHANGES
* __Adapters__
```js
import { XHRAdapter, FetchAdapter } from '@pollyjs/core';
// Register the xhr adapter so its accessible by all future polly instances
Polly.register(XHRAdapter);
polly.configure({
adapters: ['xhr', FetchAdapter]
});
```
__Persister__
```js
import { LocalStoragePersister, RESTPersister } from '@pollyjs/core';
// Register the local-storage persister so its accessible by all future polly instances
Polly.register(LocalStoragePersister);
polly.configure({
persister: 'local-storage'
});
polly.configure({
persister: RESTPersister
});
```
## [1.0.5](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/@pollyjs/ember@1.0.4...@pollyjs/ember@1.0.5) (2018-08-22)
### Bug Fixes
* **ember:** Fix auto-register and add tests to cover ([24c15bd](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/24c15bd))
## [1.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/@pollyjs/ember@1.0.3...@pollyjs/ember@1.0.4) (2018-08-12)
**Note:** Version bump only for package @pollyjs/ember
## [1.0.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/@pollyjs/ember@1.0.2...@pollyjs/ember@1.0.3) (2018-08-12)
**Note:** Version bump only for package @pollyjs/ember
## [1.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/@pollyjs/ember@1.0.1...@pollyjs/ember@1.0.2) (2018-08-09)
**Note:** Version bump only for package @pollyjs/ember
## [1.0.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/@pollyjs/ember@1.0.0...@pollyjs/ember@1.0.1) (2018-07-26)
**Note:** Version bump only for package @pollyjs/ember
# [1.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/@pollyjs/ember@0.4.2...@pollyjs/ember@1.0.0) (2018-07-20)
### Features
* Class events and EventEmitter ([#52](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/ember/issues/52)) ([0a3d591](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/0a3d591))
* Improved adapter and persister registration ([#62](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/ember/issues/62)) ([164dbac](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/164dbac))
* Keyed persister & adapter options ([#60](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/ember/issues/60)) ([29ed8e1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/29ed8e1))
* Node File System Persister ([#61](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/ember/issues/61)) ([0a0eeca](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/0a0eeca))
* Presets persisterOptions.host to the node server default ([0b47838](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/0b47838))
### BREAKING CHANGES
* __Adapters__
```js
import { XHRAdapter, FetchAdapter } from '@pollyjs/core';
// Register the xhr adapter so its accessible by all future polly instances
Polly.register(XHRAdapter);
polly.configure({
adapters: ['xhr', FetchAdapter]
});
```
__Persister__
```js
import { LocalStoragePersister, RESTPersister } from '@pollyjs/core';
// Register the local-storage persister so its accessible by all future polly instances
Polly.register(LocalStoragePersister);
polly.configure({
persister: 'local-storage'
});
polly.configure({
persister: RESTPersister
});
```
## [0.4.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/@pollyjs/ember@0.4.1...@pollyjs/ember@0.4.2) (2018-06-29)
**Note:** Version bump only for package @pollyjs/ember
## [0.4.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/@pollyjs/ember@0.4.0...@pollyjs/ember@0.4.1) (2018-06-27)
**Note:** Version bump only for package @pollyjs/ember
# [0.4.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/@pollyjs/ember@0.3.1...@pollyjs/ember@0.4.0) (2018-06-27)
### Bug Fixes
* **core:** Set `url` on the fetch Response object ([#44](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/ember/issues/44)) ([f5980cf](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/f5980cf)), closes [#43](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/issues/43)
### Features
* Make recording size limit configurable ([#40](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/ember/issues/40)) ([d4be431](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/d4be431))
## [0.3.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/@pollyjs/ember@0.3.0...@pollyjs/ember@0.3.1) (2018-06-22)
### Bug Fixes
* Bumping core within Ember ([af4faa1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/af4faa1))
# [0.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/@pollyjs/ember@0.2.1...@pollyjs/ember@0.3.0) (2018-06-22)
**Note:** Version bump only for package @pollyjs/ember
## [0.2.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/@pollyjs/ember@0.2.0...@pollyjs/ember@0.2.1) (2018-06-21)
### Bug Fixes
* Ensure polly's middleware goes before ember-cli's ([#36](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/ember/issues/36)) ([43db361](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/43db361))
# [0.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/compare/@pollyjs/ember@0.1.0...@pollyjs/ember@0.2.0) (2018-06-16)
### Features
* Custom persister support ([8bb313c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember/commit/8bb313c))
================================================
FILE: packages/@pollyjs/ember/LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Netflix Inc and @pollyjs contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: packages/@pollyjs/ember/README.md
================================================
Record, Replay, and Stub HTTP Interactions
[](https://travis-ci.com/Netflix/pollyjs)
[](https://badge.fury.io/js/%40pollyjs%2Fember)
[](http://www.apache.org/licenses/LICENSE-2.0)
Installing the `@pollyjs/ember` addon will import and vendor the necessary
Polly.JS packages as well as register the [Express API](https://netflix.github.io/pollyjs/#/node-server/express-integrations)
required by the [REST Persister](https://netflix.github.io/pollyjs/#/persisters/rest).
## Installation
```bash
ember install @pollyjs/ember
```
## Documentation
Check out the [Ember CLI Addon](https://netflix.github.io/pollyjs/#/frameworks/ember-cli)
documentation for more details.
## Configuration
Addon and [server API configuration](https://netflix.github.io/pollyjs/#/node-server/overview#api-configuration) can be specified in `/config/polly.js`. The default configuration options are shown below.
```js
module.exports = function(env) {
return {
// Addon Configuration Options
enabled: env !== 'production',
// Server Configuration Options
server: {
apiNamespace: '/polly',
recordingsDir: 'recordings'
}
};
};
```
## Usage
Once installed and configured, you can import and use Polly as documented. Check
out the [Quick Start](https://netflix.github.io/pollyjs/#/quick-start#usage) documentation to get started.
> For an even better testing experience, check out the provided [QUnit Test Helper](https://netflix.github.io/pollyjs/#/test-frameworks/qunit)!
## License
Copyright (c) 2018 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
================================================
FILE: packages/@pollyjs/ember/addon/-private/preconfigure.js
================================================
import { Polly } from '@pollyjs/core';
import XHRAdapter from '@pollyjs/adapter-xhr';
import FetchAdapter from '@pollyjs/adapter-fetch';
import RESTPersister from '@pollyjs/persister-rest';
import LocalStoragePersister from '@pollyjs/persister-local-storage';
Polly.register(XHRAdapter);
Polly.register(FetchAdapter);
Polly.register(RESTPersister);
Polly.register(LocalStoragePersister);
Polly.on('create', (polly) => {
polly.configure({
adapters: ['xhr', 'fetch'],
persister: 'rest',
/**
* @pollyjs/ember mounts the express middleware onto to the running
* testem and ember-cli express server and a relative host (an empty `host`)
* is preferred here. Can be overridden at runtime in cases where the
* Polly server is externally hosted.
*/
persisterOptions: { rest: { host: '' } }
});
});
export default Polly;
================================================
FILE: packages/@pollyjs/ember/blueprints/@pollyjs/ember/files/config/polly.js
================================================
/* eslint-env node */
'use strict';
module.exports = function (env) {
return {
enabled: env !== 'production',
server: {
apiNamespace: '/polly',
recordingsDir: 'recordings'
}
};
};
================================================
FILE: packages/@pollyjs/ember/blueprints/@pollyjs/ember/index.js
================================================
'use strict';
module.exports = {
description: 'Setup @pollyjs/ember',
normalizeEntityName() {},
afterInstall() {
return this.addPackagesToProject([
{ name: '@pollyjs/adapter-fetch' },
{ name: '@pollyjs/adapter-xhr' },
{ name: '@pollyjs/core' },
{ name: '@pollyjs/node-server' },
{ name: '@pollyjs/persister-local-storage' },
{ name: '@pollyjs/persister-rest' }
]);
}
};
================================================
FILE: packages/@pollyjs/ember/config/ember-try.js
================================================
'use strict';
const getChannelURL = require('ember-source-channel-url');
const { embroiderSafe, embroiderOptimized } = require('@embroider/test-setup');
module.exports = async function () {
return {
scenarios: [
{
name: 'ember-lts-3.20',
npm: {
devDependencies: {
'ember-source': '~3.20.5'
}
}
},
{
name: 'ember-lts-3.24',
npm: {
devDependencies: {
'ember-source': '~3.24.3'
}
}
},
{
name: 'ember-release',
npm: {
devDependencies: {
'ember-source': await getChannelURL('release')
}
}
},
{
name: 'ember-beta',
npm: {
devDependencies: {
'ember-source': await getChannelURL('beta')
}
}
},
{
name: 'ember-canary',
npm: {
devDependencies: {
'ember-source': await getChannelURL('canary')
}
}
},
{
name: 'ember-default-with-jquery',
env: {
EMBER_OPTIONAL_FEATURES: JSON.stringify({
'jquery-integration': true
})
},
npm: {
devDependencies: {
'@ember/jquery': '^1.1.0'
}
}
},
{
name: 'ember-classic',
env: {
EMBER_OPTIONAL_FEATURES: JSON.stringify({
'application-template-wrapper': true,
'default-async-observers': false,
'template-only-glimmer-components': false
})
},
npm: {
devDependencies: {
'ember-source': '~3.28.0'
},
ember: {
edition: 'classic'
}
}
},
embroiderSafe(),
embroiderOptimized()
]
};
};
================================================
FILE: packages/@pollyjs/ember/config/environment.js
================================================
'use strict';
module.exports = function () {
return {};
};
================================================
FILE: packages/@pollyjs/ember/config/polly.js
================================================
/* eslint-env node */
'use strict';
module.exports = function (env) {
// See: https://netflix.github.io/pollyjs/#/frameworks/ember-cli?id=configuration
return {
enabled: env !== 'production',
server: {
apiNamespace: '/polly',
recordingsDir: 'recordings'
}
};
};
================================================
FILE: packages/@pollyjs/ember/ember-cli-build.js
================================================
'use strict';
const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
module.exports = function (defaults) {
let app = new EmberAddon(defaults, {
// Add options here
});
/*
This build file specifies the options for the dummy test app of this
addon, located in `/tests/dummy`
This build file does *not* influence how the addon or the app using it
behave. You most likely want to be modifying `./index.js` or app's build file
*/
const { maybeEmbroider } = require('@embroider/test-setup');
return maybeEmbroider(app, {
skipBabel: [
{
package: 'qunit'
}
]
});
};
================================================
FILE: packages/@pollyjs/ember/index.js
================================================
/* eslint-env node */
'use strict';
const fs = require('fs');
const path = require('path');
const { registerExpressAPI, Defaults } = require('@pollyjs/node-server');
const parseArgs = require('minimist');
const root = process.cwd();
function determineEnv() {
if (process.env.EMBER_ENV) {
return process.env.EMBER_ENV;
}
let args = parseArgs(process.argv);
let env = args.e || args.env || args.environment;
// Is it "ember b -prod" or "ember build --prod" command?
if (
!env &&
(process.argv.indexOf('-prod') > -1 || process.argv.indexOf('--prod') > -1)
) {
env = 'production';
}
// Is it "ember test" or "ember t" command without explicit env specified?
if (
!env &&
(process.argv.indexOf('test') > -1 || process.argv.indexOf('t') > -1)
) {
env = 'test';
}
return env || 'development';
}
module.exports = {
name: require('./package').name,
_config: null,
init() {
// see: https://github.com/ember-cli/ember-cli/blob/725e129e62bccbf21af55b21180edb8966781f53/lib/models/addon.js#L258
this._super.init && this._super.init.apply(this, arguments);
const env = determineEnv();
this._config = this._pollyConfig(env);
},
treeForAddon() {
if (!this._config.enabled) {
return;
}
return this._super.treeForAddon.apply(this, arguments);
},
contentFor(name) {
if (name !== 'app-prefix' || !this._config.enabled) {
return;
}
return `
(function() {
'use strict';
require('@pollyjs/ember/-private/preconfigure');
})();
`;
},
_pollyConfig(env) {
// defaults
const config = {
enabled: env !== 'production',
server: {}
};
// NOTE: this is because we cannot assume `this.project` is always set.
// If unavailable, we default to process.cwd (root) to determine the project root.
// See: https://github.com/Netflix/pollyjs/issues/276
const projectRoot =
this.project && this.project.root ? this.project.root : root;
const configPath = path.join(projectRoot, 'config', 'polly.js');
if (fs.existsSync(configPath)) {
const configGenerator = require(configPath);
Object.assign(config, configGenerator(env));
}
config.server.recordingsDir = path.join(
projectRoot,
config.server.recordingsDir || Defaults.recordingsDir
);
return config;
},
serverMiddleware(startOptions) {
this.testemMiddleware(startOptions.app);
},
testemMiddleware(app) {
if (this._config.enabled) {
registerExpressAPI(app, this._config.server);
}
}
};
================================================
FILE: packages/@pollyjs/ember/package.json
================================================
{
"name": "@pollyjs/ember",
"version": "6.0.6",
"description": "Use @pollyjs in your Ember-CLI application",
"keywords": [
"polly",
"pollyjs",
"record",
"replay",
"test",
"ember-addon"
],
"repository": "https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/ember",
"license": "Apache-2.0",
"directories": {
"doc": "doc",
"test": "tests"
},
"contributors": [
{
"name": "Jason Mitchell",
"email": "jason.mitchell.w@gmail.com"
},
{
"name": "Offir Golan",
"email": "offirgolan@gmail.com"
}
],
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "ember build",
"start": "ember serve",
"test": "ember test ci --test-port=7300",
"clean": "rimraf dist tmp"
},
"dependencies": {
"ember-auto-import": "^2.2.4",
"ember-cli-babel": "^7.26.6",
"minimist": "^1.2.5"
},
"peerDependencies": {
"@pollyjs/adapter-fetch": "^6.0.0",
"@pollyjs/adapter-xhr": "^6.0.0",
"@pollyjs/core": "^6.0.0",
"@pollyjs/node-server": "^6.0.0",
"@pollyjs/persister-local-storage": "^6.0.0",
"@pollyjs/persister-rest": "^6.0.0"
},
"devDependencies": {
"@babel/eslint-parser": "^7.16.3",
"@ember/optional-features": "^2.0.0",
"@ember/test-helpers": "^2.4.2",
"@embroider/test-setup": "^0.43.5",
"@glimmer/component": "^1.0.4",
"@glimmer/tracking": "^1.0.4",
"broccoli-asset-rev": "^3.0.0",
"ember-cli": "~3.28.4",
"ember-cli-dependency-checker": "^3.2.0",
"ember-cli-htmlbars": "^5.7.1",
"ember-cli-inject-live-reload": "^2.1.0",
"ember-cli-sri": "^2.1.1",
"ember-cli-terser": "^4.0.2",
"ember-disable-prototype-extensions": "^1.1.3",
"ember-export-application-global": "^2.0.1",
"ember-load-initializers": "^2.1.2",
"ember-maybe-import-regenerator": "^0.1.6",
"ember-page-title": "^6.2.2",
"ember-qunit": "^5.1.4",
"ember-resolver": "^8.0.2",
"ember-source": "~3.28.0",
"ember-source-channel-url": "^3.0.0",
"ember-template-lint": "^3.6.0",
"ember-try": "^1.4.0",
"eslint": "^8.3.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-ember": "^10.5.8",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-qunit": "^7.1.0",
"loader.js": "^4.7.0",
"npm-run-all": "^4.1.5",
"prettier": "^2.5.0",
"qunit": "^2.16.0",
"qunit-dom": "^1.6.0",
"rimraf": "^2.6.2",
"webpack": "^5.64.4"
},
"engines": {
"node": "12.* || 14.* || >= 16"
},
"ember": {
"edition": "octane"
},
"ember-addon": {
"configPath": "tests/dummy/config",
"before": [
"proxy-server-middleware"
],
"after": [
"ember-auto-import"
]
}
}
================================================
FILE: packages/@pollyjs/ember/testem.js
================================================
'use strict';
module.exports = {
test_page: 'tests/index.html?hidepassed',
disable_watching: true,
launch_in_ci: ['Chrome'],
launch_in_dev: ['Chrome'],
browser_start_timeout: 120,
browser_args: {
Chrome: {
ci: [
// --no-sandbox is needed when running Chrome inside a container
process.env.CI ? '--no-sandbox' : null,
'--headless',
'--disable-dev-shm-usage',
'--disable-software-rasterizer',
'--mute-audio',
'--remote-debugging-port=0',
'--window-size=1440,900'
].filter(Boolean)
}
}
};
================================================
FILE: packages/@pollyjs/ember/tests/dummy/app/app.js
================================================
import Application from '@ember/application';
import Resolver from 'ember-resolver';
import loadInitializers from 'ember-load-initializers';
import config from 'dummy/config/environment';
export default class App extends Application {
modulePrefix = config.modulePrefix;
podModulePrefix = config.podModulePrefix;
Resolver = Resolver;
}
loadInitializers(App, config.modulePrefix);
================================================
FILE: packages/@pollyjs/ember/tests/dummy/app/components/.gitkeep
================================================
================================================
FILE: packages/@pollyjs/ember/tests/dummy/app/controllers/.gitkeep
================================================
================================================
FILE: packages/@pollyjs/ember/tests/dummy/app/helpers/.gitkeep
================================================
================================================
FILE: packages/@pollyjs/ember/tests/dummy/app/index.html
================================================
Dummy
{{content-for "head"}}
{{content-for "head-footer"}}
{{content-for "body"}}
{{content-for "body-footer"}}
================================================
FILE: packages/@pollyjs/ember/tests/dummy/app/models/.gitkeep
================================================
================================================
FILE: packages/@pollyjs/ember/tests/dummy/app/router.js
================================================
import EmberRouter from '@ember/routing/router';
import config from 'dummy/config/environment';
export default class Router extends EmberRouter {
location = config.locationType;
rootURL = config.rootURL;
}
Router.map(function () {});
================================================
FILE: packages/@pollyjs/ember/tests/dummy/app/routes/.gitkeep
================================================
================================================
FILE: packages/@pollyjs/ember/tests/dummy/app/styles/app.css
================================================
================================================
FILE: packages/@pollyjs/ember/tests/dummy/app/templates/application.hbs
================================================
{{page-title "Dummy"}}
Welcome to Ember
{{outlet}}
================================================
FILE: packages/@pollyjs/ember/tests/dummy/config/ember-cli-update.json
================================================
{
"schemaVersion": "1.0.0",
"packages": [
{
"name": "ember-cli",
"version": "3.28.4",
"blueprints": [
{
"name": "addon",
"outputRepo": "https://github.com/ember-cli/ember-addon-output",
"codemodsSource": "ember-addon-codemods-manifest@1",
"isBaseBlueprint": true,
"options": []
}
]
}
]
}
================================================
FILE: packages/@pollyjs/ember/tests/dummy/config/environment.js
================================================
'use strict';
module.exports = function (environment) {
let ENV = {
modulePrefix: 'dummy',
environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. EMBER_NATIVE_DECORATOR_SUPPORT: true
},
EXTEND_PROTOTYPES: {
// Prevent Ember Data from overriding Date.parse.
Date: false
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
ENV.APP.autoboot = false;
}
if (environment === 'production') {
// here you can enable a production-specific feature
}
return ENV;
};
================================================
FILE: packages/@pollyjs/ember/tests/dummy/config/optional-features.json
================================================
{
"application-template-wrapper": false,
"default-async-observers": true,
"jquery-integration": false,
"template-only-glimmer-components": true
}
================================================
FILE: packages/@pollyjs/ember/tests/dummy/config/targets.js
================================================
'use strict';
const browsers = [
'last 1 Chrome versions',
'last 1 Firefox versions',
'last 1 Safari versions'
];
// Ember's browser support policy is changing, and IE11 support will end in
// v4.0 onwards.
//
// See https://deprecations.emberjs.com/v3.x#toc_3-0-browser-support-policy
//
// If you need IE11 support on a version of Ember that still offers support
// for it, uncomment the code block below.
//
// const isCI = Boolean(process.env.CI);
// const isProduction = process.env.EMBER_ENV === 'production';
//
// if (isCI || isProduction) {
// browsers.push('ie 11');
// }
module.exports = {
browsers
};
================================================
FILE: packages/@pollyjs/ember/tests/dummy/public/robots.txt
================================================
# http://www.robotstxt.org
User-agent: *
Disallow:
================================================
FILE: packages/@pollyjs/ember/tests/helpers/.gitkeep
================================================
================================================
FILE: packages/@pollyjs/ember/tests/index.html
================================================
Dummy Tests
{{content-for "head"}}
{{content-for "test-head"}}
{{content-for "head-footer"}}
{{content-for "test-head-footer"}}
{{content-for "body"}}
{{content-for "test-body"}}
{{content-for "body-footer"}}
{{content-for "test-body-footer"}}
================================================
FILE: packages/@pollyjs/ember/tests/integration/.gitkeep
================================================
================================================
FILE: packages/@pollyjs/ember/tests/test-helper.js
================================================
import Application from 'dummy/app';
import config from 'dummy/config/environment';
import * as QUnit from 'qunit';
import { setApplication } from '@ember/test-helpers';
import { setup } from 'qunit-dom';
import { start } from 'ember-qunit';
setApplication(Application.create(config.APP));
setup(QUnit.assert);
start();
================================================
FILE: packages/@pollyjs/ember/tests/unit/polly-test.js
================================================
import { Polly, Timing, setupQunit as setupPolly } from '@pollyjs/core';
import { module, test } from 'qunit';
module('Unit | Polly | General', function () {
module('Polly', function () {
test('it works', function (assert) {
assert.strictEqual(typeof Polly, 'function');
});
test('it defaults to an empty string for persisterOptions.rest.host', function (assert) {
const polly = new Polly('abc');
assert.strictEqual(polly.config.persisterOptions.rest.host, '');
return polly.stop();
});
});
module('setupPolly', function (hooks) {
setupPolly(hooks);
test('it works', function (assert) {
assert.ok(this.polly);
assert.ok(this.polly instanceof Polly);
});
});
module('setupPolly.[beforeEach,afterEach]', function (hooks) {
// eslint-disable-next-line qunit/no-hooks-from-ancestor-modules
setupPolly.beforeEach(hooks);
// eslint-disable-next-line qunit/no-hooks-from-ancestor-modules
setupPolly.afterEach(hooks);
test('it works', function (assert) {
assert.ok(this.polly);
assert.ok(this.polly instanceof Polly);
});
});
module('Timing', function () {
test('it works', function (assert) {
assert.strictEqual(typeof Timing, 'object');
assert.strictEqual(typeof Timing.fixed, 'function');
assert.strictEqual(typeof Timing.relative, 'function');
});
});
module('auto-registers', function () {
test('adapters', async function (assert) {
const polly = new Polly('adapters');
assert.strictEqual(polly.adapters.size, 2);
await polly.stop();
});
test('persister', async function (assert) {
const polly = new Polly('persister');
assert.strictEqual(typeof polly.persister, 'object');
await polly.stop();
});
});
});
================================================
FILE: packages/@pollyjs/ember/vendor/.gitkeep
================================================
================================================
FILE: packages/@pollyjs/node-server/CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.6](https://github.com/netflix/pollyjs/compare/v6.0.5...v6.0.6) (2023-07-20)
**Note:** Version bump only for package @pollyjs/node-server
## [6.0.1](https://github.com/netflix/pollyjs/compare/v6.0.0...v6.0.1) (2021-12-06)
### Bug Fixes
* **types:** add types.d.ts to package.files ([#431](https://github.com/netflix/pollyjs/issues/431)) ([113ee89](https://github.com/netflix/pollyjs/commit/113ee898bcf0467c5c48c15b53fc9198e2e91cb1))
# [6.0.0](https://github.com/netflix/pollyjs/compare/v5.2.0...v6.0.0) (2021-11-30)
* feat(ember)!: Upgrade to ember octane (#415) ([8559ef8](https://github.com/netflix/pollyjs/commit/8559ef8c600aefaec629870eac5f5c8953e18b16)), closes [#415](https://github.com/netflix/pollyjs/issues/415)
### Features
* **node-server:** Upgrade dependencies ([#417](https://github.com/netflix/pollyjs/issues/417)) ([246a2f2](https://github.com/netflix/pollyjs/commit/246a2f29a88de9c25fc0739ea5e53a0130a58573))
### BREAKING CHANGES
* @pollyjs dependencies have been moved to peer dependencies
## [5.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/v5.1.0...v5.1.1) (2021-06-02)
**Note:** Version bump only for package @pollyjs/node-server
# [5.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/v4.3.0...v5.0.0) (2020-06-23)
**Note:** Version bump only for package @pollyjs/node-server
# [4.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/v4.2.1...v4.3.0) (2020-05-18)
**Note:** Version bump only for package @pollyjs/node-server
# [4.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/v4.1.0...v4.2.0) (2020-04-29)
### Features
* **node-server:** Pass options to the CORS middleware via `corsOptions` ([3d991f5](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/3d991f5))
# [4.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/v4.0.4...v4.1.0) (2020-04-23)
**Note:** Version bump only for package @pollyjs/node-server
## [4.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/v4.0.1...v4.0.2) (2020-01-29)
**Note:** Version bump only for package @pollyjs/node-server
# [4.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/v3.0.2...v4.0.0) (2020-01-13)
**Note:** Version bump only for package @pollyjs/node-server
# [3.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/v2.7.0...v3.0.0) (2019-12-18)
### Bug Fixes
* **ember:** loads polly config for ember by its own module ([#277](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/issues/277)) ([0569040](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/0569040))
### BREAKING CHANGES
* **ember:** moves location of polly configuration
## [2.6.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/v2.6.2...v2.6.3) (2019-09-30)
### Bug Fixes
* use watch strategy ([#236](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/issues/236)) ([5b4edf3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/5b4edf3))
# [2.6.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/v2.5.0...v2.6.0) (2019-07-17)
**Note:** Version bump only for package @pollyjs/node-server
# [2.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/v2.0.0...v2.1.0) (2019-02-04)
**Note:** Version bump only for package @pollyjs/node-server
# [2.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/v1.4.2...v2.0.0) (2019-01-29)
**Note:** Version bump only for package @pollyjs/node-server
## [1.4.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/v1.4.0...v1.4.1) (2018-12-13)
**Note:** Version bump only for package @pollyjs/node-server
## [1.3.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/v1.3.1...v1.3.2) (2018-11-29)
**Note:** Version bump only for package @pollyjs/node-server
## [1.3.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/v1.2.0...v1.3.1) (2018-11-28)
**Note:** Version bump only for package @pollyjs/node-server
# 1.2.0 (2018-09-16)
### Bug Fixes
* Do not display node server listening banner in quiet mode ([1be57a7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/1be57a7))
* Rest server on Windows ([be5c473](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/be5c473))
### Features
* **node-server:** Add cors support to express server to pass-through all requests ([223ce4e](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/223ce4e))
* **persister:** Cache recordings ([#31](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/node-server/issues/31)) ([a04d7a7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/a04d7a7))
* Convert recordings to be HAR compliant ([#45](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/node-server/issues/45)) ([e622640](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/e622640))
* Make recording size limit configurable ([#40](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/node-server/issues/40)) ([d4be431](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/d4be431))
* Node File System Persister ([#61](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/node-server/issues/61)) ([0a0eeca](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/0a0eeca))
* Presets persisterOptions.host to the node server default ([0b47838](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/0b47838))
* Use status code 204 in place of 404. ([#5](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/node-server/issues/5)) ([930c492](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/930c492))
### BREAKING CHANGES
* Recordings now produce HAR compliant json. Please delete existing recordings.
## [1.0.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/@pollyjs/node-server@1.0.2...@pollyjs/node-server@1.0.3) (2018-08-22)
**Note:** Version bump only for package @pollyjs/node-server
## [1.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/@pollyjs/node-server@1.0.1...@pollyjs/node-server@1.0.2) (2018-08-12)
**Note:** Version bump only for package @pollyjs/node-server
## [1.0.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/@pollyjs/node-server@1.0.0...@pollyjs/node-server@1.0.1) (2018-08-12)
**Note:** Version bump only for package @pollyjs/node-server
# [1.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/@pollyjs/node-server@0.4.0...@pollyjs/node-server@1.0.0) (2018-07-20)
### Features
* Convert recordings to be HAR compliant ([#45](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/node-server/issues/45)) ([e622640](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/e622640))
* Node File System Persister ([#61](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/node-server/issues/61)) ([0a0eeca](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/0a0eeca))
* Presets persisterOptions.host to the node server default ([0b47838](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/0b47838))
### BREAKING CHANGES
* Recordings now produce HAR compliant json. Please delete existing recordings.
# [0.4.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/@pollyjs/node-server@0.3.0...@pollyjs/node-server@0.4.0) (2018-06-29)
### Bug Fixes
* Do not display node server listening banner in quiet mode ([1be57a7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/1be57a7))
### Features
* **node-server:** Add cors support to express server to pass-through all requests ([223ce4e](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/223ce4e))
# [0.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/@pollyjs/node-server@0.2.0...@pollyjs/node-server@0.3.0) (2018-06-27)
### Features
* Make recording size limit configurable ([#40](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/node-server/issues/40)) ([d4be431](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/d4be431))
# [0.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/compare/@pollyjs/node-server@0.1.0...@pollyjs/node-server@0.2.0) (2018-06-21)
### Bug Fixes
* Rest server on Windows ([be5c473](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/be5c473))
### Features
* **persister:** Cache recordings ([#31](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/node-server/issues/31)) ([a04d7a7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server/commit/a04d7a7))
================================================
FILE: packages/@pollyjs/node-server/LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Netflix Inc and @pollyjs contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: packages/@pollyjs/node-server/README.md
================================================
Record, Replay, and Stub HTTP Interactions
[](https://travis-ci.com/Netflix/pollyjs)
[](https://badge.fury.io/js/%40pollyjs%2Fnode-server)
[](http://www.apache.org/licenses/LICENSE-2.0)
The `@pollyjs/node-server` package provides a standalone node server as well as
an express integration to be able to support the [REST Persister](https://netflix.github.io/pollyjs/#/persisters/rest) so recordings can be saved to
and read from disk.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/node-server -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/node-server -D
```
## Documentation
Check out the [Node Server](https://netflix.github.io/pollyjs/#/node-server/overview)
documentation for more details.
## Server
This packages includes a fully working standalone node server that is pre-configured
with the necessary APIs and middleware to support the [REST Persister](https://netflix.github.io/pollyjs/#/persisters/rest).
The Server constructor accepts a configuration object that can be a combination
of the below listed Server & API options. Once instantiated, you will have
full access to the Express app via the `app` property.
```js
const { Server } = require('@pollyjs/node-server');
const server = new Server({
quiet: true,
port: 4000,
apiNamespace: '/polly'
});
// Add custom business logic to the express server
server.app.get('/custom', () => {
/* Add custom express logic */
});
// Start listening and attach extra logic to the http server
server.listen().on('error', () => {
/* Add http server error logic */
});
```
## Express Integrations
The `@pollyjs/node-server` package exports a `registerExpressAPI` method which
takes in an [Express](http://expressjs.com/) app and a config to register the
necessary routes to be used with the REST Persister.
```js
const { registerExpressAPI } = require('@pollyjs/node-server');
registerExpressAPI(app, config);
```
## License
Copyright (c) 2018 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
================================================
FILE: packages/@pollyjs/node-server/package.json
================================================
{
"name": "@pollyjs/node-server",
"version": "6.0.6",
"description": "Standalone node server and express integration for @pollyjs",
"main": "dist/cjs/pollyjs-node-server.js",
"module": "dist/es/pollyjs-node-server.js",
"types": "types.d.ts",
"files": [
"src",
"dist",
"types.d.ts"
],
"repository": "https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/node-server",
"license": "Apache-2.0",
"contributors": [
{
"name": "Jason Mitchell",
"email": "jason.mitchell.w@gmail.com"
},
{
"name": "Offir Golan",
"email": "offirgolan@gmail.com"
}
],
"keywords": [
"polly",
"pollyjs",
"server",
"record",
"replay",
"express"
],
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "rollup -c",
"watch": "yarn build -w",
"watch-all": "yarn build"
},
"dependencies": {
"@pollyjs/utils": "^6.0.6",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"fs-extra": "^10.0.0",
"http-graceful-shutdown": "^3.1.5",
"morgan": "^1.10.0",
"nocache": "^3.0.1"
},
"devDependencies": {
"rollup": "^1.14.6"
}
}
================================================
FILE: packages/@pollyjs/node-server/rollup.config.js
================================================
import createNodeConfig from '../../../scripts/rollup/node.config';
export default createNodeConfig({
external: ['path']
});
================================================
FILE: packages/@pollyjs/node-server/src/api.js
================================================
import path from 'path';
import fs from 'fs-extra';
import { assert } from '@pollyjs/utils';
export default class API {
constructor(options = {}) {
const { recordingsDir } = options;
assert(
`Invalid recordings directory provided. Expected string, received: "${typeof recordingsDir}".`,
typeof recordingsDir === 'string'
);
this.recordingsDir = recordingsDir;
}
getRecording(recording) {
const recordingFilename = this.filenameFor(recording);
if (fs.existsSync(recordingFilename)) {
return this.respond(200, fs.readJsonSync(recordingFilename));
}
return this.respond(204);
}
saveRecording(recording, data) {
fs.outputJsonSync(this.filenameFor(recording), data, {
spaces: 2
});
return this.respond(201);
}
deleteRecording(recording) {
const recordingFilename = this.filenameFor(recording);
if (fs.existsSync(recordingFilename)) {
fs.removeSync(recordingFilename);
}
return this.respond(200);
}
filenameFor(recording) {
return path.join(this.recordingsDir, recording, 'recording.har');
}
respond(status, body) {
return { status, body };
}
}
================================================
FILE: packages/@pollyjs/node-server/src/config.js
================================================
export default {
port: 3000,
quiet: false,
recordingSizeLimit: '50mb',
recordingsDir: 'recordings',
apiNamespace: '/polly'
};
================================================
FILE: packages/@pollyjs/node-server/src/express/register-api.js
================================================
import bodyParser from 'body-parser';
import express from 'express';
import nocache from 'nocache';
import API from '../api';
import DefaultConfig from '../config';
function prependSlash(slash = '') {
if (slash.startsWith('/')) {
return slash;
}
return `/${slash}`;
}
export default function registerAPI(app, config) {
config = { ...DefaultConfig, ...config };
config.apiNamespace = prependSlash(config.apiNamespace);
const router = express.Router();
const api = new API({ recordingsDir: config.recordingsDir });
router.use(nocache());
router.get('/:recording', function (req, res) {
const { recording } = req.params;
const { status, body } = api.getRecording(recording);
res.status(status);
if (status === 200) {
res.json(body);
} else {
res.end();
}
});
router.post(
'/:recording',
bodyParser.json({ limit: config.recordingSizeLimit }),
function (req, res) {
const { recording } = req.params;
const { status, body } = api.saveRecording(recording, req.body);
res.status(status).send(body);
}
);
router.delete('/:recording', function (req, res) {
const { recording } = req.params;
const { status, body } = api.deleteRecording(recording);
res.status(status).send(body);
});
app.use(config.apiNamespace, router);
}
================================================
FILE: packages/@pollyjs/node-server/src/index.js
================================================
export { default as API } from './api';
export { default as Server } from './server';
export { default as Defaults } from './config';
export { default as registerExpressAPI } from './express/register-api';
================================================
FILE: packages/@pollyjs/node-server/src/server.js
================================================
/* global process */
import cors from 'cors';
import morgan from 'morgan';
import express from 'express';
import gracefulShutdown from 'http-graceful-shutdown';
import registerAPI from './express/register-api';
import DefaultConfig from './config';
export default class Server {
constructor(config = {}) {
this.config = { ...DefaultConfig, ...config };
this.app = express();
this.app.use(cors(this.config.corsOptions));
if (!this.config.quiet) {
this.app.use(morgan('dev'));
}
// Return 200 on root GET & HEAD to pass health checks
this.app.get('/', (req, res) => res.sendStatus(200));
this.app.head('/', (req, res) => res.sendStatus(200));
registerAPI(this.app, {
recordingsDir: this.config.recordingsDir,
apiNamespace: this.config.apiNamespace
});
}
listen(port, host) {
if (this.server) {
return;
}
port = port || this.config.port;
host = host || this.config.host;
this.server = this.app
.listen(port, host)
.on('listening', () => {
if (!this.config.quiet) {
console.log(`Listening on http://${host || 'localhost'}:${port}/\n`);
}
})
.on('error', (e) => {
if (e.code === 'EADDRINUSE') {
console.error(`Port ${port} already in use.`);
process.exit(1);
} else {
console.error(e);
}
});
gracefulShutdown(this.server);
return this.server;
}
}
================================================
FILE: packages/@pollyjs/node-server/types.d.ts
================================================
import * as http from 'http';
import * as express from 'express';
import * as cors from 'cors';
export interface Config {
port: number;
quiet: boolean;
recordingSizeLimit: string;
recordingsDir: string;
apiNamespace: string;
}
export interface ServerConfig extends Config {
corsOptions?: cors.CorsOptions | undefined;
}
export const Defaults: Config;
export interface APIResponse {
status: number;
body?: any;
}
export class API {
constructor(options: Pick);
getRecordings(recording: string): APIResponse;
saveRecording(recording: string, data: any): APIResponse;
deleteRecording(recording: string): APIResponse;
filenameFor(recording: string): string;
respond(status: number, data?: any): APIResponse;
}
export class Server {
config: ServerConfig;
app: express.Express;
server?: http.Server | undefined;
constructor(options?: Partial);
listen(port?: number, host?: string): http.Server;
}
export function registerExpressAPI(
app: express.Express,
config: Partial
): void;
================================================
FILE: packages/@pollyjs/persister/CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.6](https://github.com/netflix/pollyjs/compare/v6.0.5...v6.0.6) (2023-07-20)
**Note:** Version bump only for package @pollyjs/persister
## [6.0.5](https://github.com/netflix/pollyjs/compare/v6.0.4...v6.0.5) (2022-04-04)
### Bug Fixes
* **persister:** `requests` -> `request` in `HarEntry` declaration ([#441](https://github.com/netflix/pollyjs/issues/441)) ([6466810](https://github.com/netflix/pollyjs/commit/6466810677b6ac2c6a7496335bf40e043ab843e1))
## [6.0.4](https://github.com/netflix/pollyjs/compare/v6.0.3...v6.0.4) (2021-12-10)
### Bug Fixes
* Update types for class methods ([#438](https://github.com/netflix/pollyjs/issues/438)) ([b88655a](https://github.com/netflix/pollyjs/commit/b88655ac1b4ca7348afd45e9aeaa50e998ea68d7))
## [6.0.3](https://github.com/netflix/pollyjs/compare/v6.0.2...v6.0.3) (2021-12-08)
### Bug Fixes
* A few more type fixes ([#437](https://github.com/netflix/pollyjs/issues/437)) ([5e837a2](https://github.com/netflix/pollyjs/commit/5e837a25d28393b764cb66bcae0b29e9273eabe8))
## [6.0.2](https://github.com/netflix/pollyjs/compare/v6.0.1...v6.0.2) (2021-12-07)
### Bug Fixes
* **core:** Fix types for registering adapters and persisters ([#435](https://github.com/netflix/pollyjs/issues/435)) ([cc2fa19](https://github.com/netflix/pollyjs/commit/cc2fa197a5c0a5fdef4602c4a207d31f3e677897))
## [6.0.1](https://github.com/netflix/pollyjs/compare/v6.0.0...v6.0.1) (2021-12-06)
### Bug Fixes
* **types:** add types.d.ts to package.files ([#431](https://github.com/netflix/pollyjs/issues/431)) ([113ee89](https://github.com/netflix/pollyjs/commit/113ee898bcf0467c5c48c15b53fc9198e2e91cb1))
# [6.0.0](https://github.com/netflix/pollyjs/compare/v5.2.0...v6.0.0) (2021-11-30)
### Bug Fixes
* **persister:** Only treat status codes >= 400 as failed ([#430](https://github.com/netflix/pollyjs/issues/430)) ([7658952](https://github.com/netflix/pollyjs/commit/765895232746cd560da6bd566de8a312045b1703))
* feat!: Cleanup adapter and persister APIs (#429) ([06499fc](https://github.com/netflix/pollyjs/commit/06499fc2d85254b3329db2bec770d173ed32bca0)), closes [#429](https://github.com/netflix/pollyjs/issues/429)
* feat!: Improve logging and add logLevel (#427) ([bef3ee3](https://github.com/netflix/pollyjs/commit/bef3ee39f71dfc2fa4dbeb522dfba16d01243e9f)), closes [#427](https://github.com/netflix/pollyjs/issues/427)
* chore!: Upgrade package dependencies (#421) ([dd23334](https://github.com/netflix/pollyjs/commit/dd23334fa9b64248e4c49c3616237bdc2f12f682)), closes [#421](https://github.com/netflix/pollyjs/issues/421)
* feat!: Use base64 instead of hex encoding for binary data (#420) ([6bb9b36](https://github.com/netflix/pollyjs/commit/6bb9b36522d73f9c079735d9006a12376aee39ea)), closes [#420](https://github.com/netflix/pollyjs/issues/420)
* feat(ember)!: Upgrade to ember octane (#415) ([8559ef8](https://github.com/netflix/pollyjs/commit/8559ef8c600aefaec629870eac5f5c8953e18b16)), closes [#415](https://github.com/netflix/pollyjs/issues/415)
### BREAKING CHANGES
* - Adapter
- `passthroughRequest` renamed to `onFetchResponse`
- `respondToRequest` renamed to `onRespond`
- Persister
- `findRecording` renamed to `onFindRecording`
- `saveRecording` renamed to `onSaveRecording`
- `deleteRecording` renamed to `onDeleteRecording`
* The `logging` configuration option has now been replaced with `logLevel`. This allows for more fine-grain control over what should be logged as well as silencing logs altogether.
* Recording file name will no longer have trailing dashes
* Use the standard `encoding` field on the generated har file instead of `_isBinary` and use `base64` encoding instead of `hex` to reduce the payload size.
* @pollyjs dependencies have been moved to peer dependencies
## [5.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v5.1.0...v5.1.1) (2021-06-02)
**Note:** Version bump only for package @pollyjs/persister
# [5.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v4.3.0...v5.0.0) (2020-06-23)
### Features
* Remove deprecated Persister.name and Adapter.name ([#343](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/issues/343)) ([1223ba0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/1223ba0))
### BREAKING CHANGES
* Persister.name and Adapter.name have been replaced with Persister.id and Adapter.id
# [4.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v4.2.1...v4.3.0) (2020-05-18)
**Note:** Version bump only for package @pollyjs/persister
## [4.2.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v4.2.0...v4.2.1) (2020-04-30)
### Bug Fixes
* **adapter-node-http:** Improve binary response body handling ([#329](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/issues/329)) ([9466989](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/9466989))
# [4.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v4.0.4...v4.1.0) (2020-04-23)
### Bug Fixes
* Legacy persisters and adapters should register ([#325](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/issues/325)) ([8fd4d19](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/8fd4d19))
### Features
* **persister:** Add `disableSortingHarEntries` option ([#321](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/issues/321)) ([0003c0e](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/0003c0e))
## [4.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v4.0.3...v4.0.4) (2020-03-21)
### Bug Fixes
* Deprecates adapter & persister `name` in favor of `id` ([#310](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/issues/310)) ([41dd093](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/41dd093))
## [4.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v4.0.1...v4.0.2) (2020-01-29)
**Note:** Version bump only for package @pollyjs/persister
# [4.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v3.0.2...v4.0.0) (2020-01-13)
**Note:** Version bump only for package @pollyjs/persister
# [3.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v2.7.0...v3.0.0) (2019-12-18)
**Note:** Version bump only for package @pollyjs/persister
## [2.6.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v2.6.2...v2.6.3) (2019-09-30)
### Bug Fixes
* use watch strategy ([#236](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/issues/236)) ([5b4edf3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/5b4edf3))
## [2.6.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v2.6.1...v2.6.2) (2019-08-05)
### Bug Fixes
* Bowser.getParser empty string UserAgent error ([#246](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/issues/246)) ([2c9c4b9](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/2c9c4b9))
## [2.6.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v2.6.0...v2.6.1) (2019-08-01)
### Bug Fixes
* **persister:** Default to empty string if userAgent is empty ([#242](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/issues/242)) ([c46d65c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/c46d65c))
# [2.6.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v2.5.0...v2.6.0) (2019-07-17)
**Note:** Version bump only for package @pollyjs/persister
# [2.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v2.0.0...v2.1.0) (2019-02-04)
### Bug Fixes
* Correctly handle array header values ([#179](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/179)) ([fb7dbb4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/fb7dbb4))
# [2.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v1.4.2...v2.0.0) (2019-01-29)
### Bug Fixes
* **persister:** Only persist post data if a request has a body ([#171](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/171)) ([f62d318](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/f62d318))
### Features
* Make PollyRequest.respond accept a response object ([#168](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/168)) ([5b07b26](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/5b07b26))
### BREAKING CHANGES
* Any adapters calling `pollyRequest.respond` should pass it a response object instead of the previous 3 arguments (statusCode, headers, body).
## [1.4.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v1.4.0...v1.4.1) (2018-12-13)
**Note:** Version bump only for package @pollyjs/persister
## [1.3.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v1.3.1...v1.3.2) (2018-11-29)
**Note:** Version bump only for package @pollyjs/persister
## [1.3.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/v1.2.0...v1.3.1) (2018-11-28)
**Note:** Version bump only for package @pollyjs/persister
# 1.2.0 (2018-09-16)
### Bug Fixes
* Creator cleanup and persister assertion ([#67](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/67)) ([19fee5a](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/19fee5a))
* **persister:** Handle concurrent find requests ([#88](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/88)) ([0e02414](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/0e02414))
### Features
* Class events and EventEmitter ([#52](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/52)) ([0a3d591](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/0a3d591))
* Convert recordings to be HAR compliant ([#45](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/45)) ([e622640](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/e622640))
* Custom persister support ([8bb313c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/8bb313c))
* Keyed persister & adapter options ([#60](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/60)) ([29ed8e1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/29ed8e1))
* Node File System Persister ([#61](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/61)) ([0a0eeca](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/0a0eeca))
* **core:** Server level configuration ([#80](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/80)) ([0f32d9b](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/0f32d9b))
* **persister:** Add `keepUnusedRequests` config option ([#108](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/108)) ([3f5f5b2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/3f5f5b2))
* **persister:** Cache recordings ([#31](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/31)) ([a04d7a7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/a04d7a7))
### BREAKING CHANGES
* Recordings now produce HAR compliant json. Please delete existing recordings.
## [1.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/@pollyjs/persister@1.0.3...@pollyjs/persister@1.0.4) (2018-08-22)
**Note:** Version bump only for package @pollyjs/persister
## [1.0.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/@pollyjs/persister@1.0.2...@pollyjs/persister@1.0.3) (2018-08-12)
**Note:** Version bump only for package @pollyjs/persister
## [1.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/@pollyjs/persister@1.0.1...@pollyjs/persister@1.0.2) (2018-08-12)
**Note:** Version bump only for package @pollyjs/persister
## [1.0.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/@pollyjs/persister@1.0.0...@pollyjs/persister@1.0.1) (2018-08-09)
### Bug Fixes
* **persister:** Handle concurrent find requests ([#88](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/88)) ([0e02414](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/0e02414))
# [1.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/@pollyjs/persister@0.2.1...@pollyjs/persister@1.0.0) (2018-07-20)
### Bug Fixes
* Creator cleanup and persister assertion ([#67](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/67)) ([19fee5a](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/19fee5a))
### Features
* Class events and EventEmitter ([#52](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/52)) ([0a3d591](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/0a3d591))
* Convert recordings to be HAR compliant ([#45](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/45)) ([e622640](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/e622640))
* Keyed persister & adapter options ([#60](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/60)) ([29ed8e1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/29ed8e1))
* Node File System Persister ([#61](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/61)) ([0a0eeca](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/0a0eeca))
### BREAKING CHANGES
* Recordings now produce HAR compliant json. Please delete existing recordings.
## [0.2.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/@pollyjs/persister@0.2.0...@pollyjs/persister@0.2.1) (2018-06-27)
**Note:** Version bump only for package @pollyjs/persister
# [0.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/compare/@pollyjs/persister@0.1.0...@pollyjs/persister@0.2.0) (2018-06-21)
### Features
* **persister:** Cache recordings ([#31](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister/issues/31)) ([a04d7a7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/a04d7a7))
# 0.1.0 (2018-06-16)
### Features
* Custom persister support ([8bb313c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister/commit/8bb313c))
================================================
FILE: packages/@pollyjs/persister/LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Netflix Inc and @pollyjs contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: packages/@pollyjs/persister/README.md
================================================
Record, Replay, and Stub HTTP Interactions
[](https://travis-ci.com/Netflix/pollyjs)
[](https://badge.fury.io/js/%40pollyjs%2Fpersister)
[](http://www.apache.org/licenses/LICENSE-2.0)
The `@pollyjs/persister` package provides an extendable base persister class that
contains core logic dependent on by the [REST](https://netflix.github.io/pollyjs/#/persisters/rest)
& [Local Storage](https://netflix.github.io/pollyjs/#/persisters/local-storage) persisters.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/persister -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/persister -D
```
## Documentation
Check out the [Custom Persister](https://netflix.github.io/pollyjs/#/persisters/custom)
documentation for more details.
## Usage
```js
import Persister from '@pollyjs/persister';
class CustomPersister extends Persister {
static get id() {
return 'custom';
}
onFindRecording() {}
onSaveRecording() {}
onDeleteRecording() {}
}
```
For better usage examples, please refer to the source code for
the [REST](https://github.com/Netflix/pollyjs/blob/master/packages/%40pollyjs/core/src/persisters/rest/index.js) & [Local Storage](https://github.com/Netflix/pollyjs/blob/master/packages/%40pollyjs/core/src/persisters/local-storage/index.js) persisters.
## License
Copyright (c) 2018 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
================================================
FILE: packages/@pollyjs/persister/package.json
================================================
{
"name": "@pollyjs/persister",
"version": "6.0.6",
"description": "Extendable base persister class used by @pollyjs",
"main": "dist/cjs/pollyjs-persister.js",
"module": "dist/es/pollyjs-persister.js",
"browser": "dist/umd/pollyjs-persister.js",
"types": "types.d.ts",
"files": [
"src",
"dist",
"types.d.ts"
],
"repository": "https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister",
"scripts": {
"build": "rollup -c ../../../scripts/rollup/default.config.js",
"test:build": "rollup -c rollup.config.test.js",
"test:build:watch": "rollup -c rollup.config.test.js -w",
"build:watch": "yarn build -w",
"watch-all": "npm-run-all --parallel build:watch test:build:watch"
},
"keywords": [
"polly",
"pollyjs",
"persister"
],
"publishConfig": {
"access": "public"
},
"contributors": [
{
"name": "Jason Mitchell",
"email": "jason.mitchell.w@gmail.com"
},
{
"name": "Offir Golan",
"email": "offirgolan@gmail.com"
}
],
"license": "Apache-2.0",
"dependencies": {
"@pollyjs/utils": "^6.0.6",
"@types/set-cookie-parser": "^2.4.1",
"bowser": "^2.4.0",
"fast-json-stable-stringify": "^2.1.0",
"lodash-es": "^4.17.21",
"set-cookie-parser": "^2.4.8",
"utf8-byte-length": "^1.0.4"
},
"devDependencies": {
"har-validator": "^5.1.5",
"rollup": "^1.14.6"
}
}
================================================
FILE: packages/@pollyjs/persister/rollup.config.test.js
================================================
import createNodeTestConfig from '../../../scripts/rollup/node.test.config';
import createBrowserTestConfig from '../../../scripts/rollup/browser.test.config';
export default [createNodeTestConfig(), createBrowserTestConfig()];
================================================
FILE: packages/@pollyjs/persister/src/har/entry.js
================================================
import Request from './request';
import Response from './response';
const { keys } = Object;
function totalTime(timings = {}) {
return keys(timings).reduce(
(total, k) => (timings[k] > 0 ? (total += timings[k]) : total),
0
);
}
export default class Entry {
constructor(request) {
this._id = request.id;
this._order = request.order;
this.startedDateTime = request.timestamp;
this.request = new Request(request);
this.response = new Response(request.response);
this.cache = {};
this.timings = {
blocked: -1,
dns: -1,
connect: -1,
send: 0,
wait: request.responseTime,
receive: 0,
ssl: -1
};
this.time = totalTime(this.timings);
}
}
================================================
FILE: packages/@pollyjs/persister/src/har/index.js
================================================
import Log from './log';
export default class HAR {
constructor(opts = {}) {
this.log = new Log(opts.log);
}
}
================================================
FILE: packages/@pollyjs/persister/src/har/log.js
================================================
import uniqWith from 'lodash-es/uniqWith';
import Bowser from 'bowser';
const bowser =
global.navigator && global.navigator.userAgent
? Bowser.getParser(global.navigator.userAgent).getBrowser()
: null;
const browser =
bowser && bowser.name && bowser.version
? { name: bowser.name, version: bowser.version }
: null;
export default class Log {
constructor(opts = {}) {
// eslint-disable-next-line no-restricted-properties
Object.assign(
this,
{
version: '1.2',
entries: [],
pages: []
},
opts
);
if (!this.browser && browser) {
this.browser = browser;
}
}
addEntries(entries = []) {
this.entries = uniqWith(
// Add the new entries to the front so they take priority
[...entries, ...this.entries],
(a, b) => a._id === b._id && a._order === b._order
);
}
sortEntries() {
this.entries = this.entries.sort(
(a, b) => new Date(a.startedDateTime) - new Date(b.startedDateTime)
);
}
}
================================================
FILE: packages/@pollyjs/persister/src/har/request.js
================================================
import getByteLength from 'utf8-byte-length';
import setCookies from 'set-cookie-parser';
import toNVPairs from './utils/to-nv-pairs';
import getFirstHeader from './utils/get-first-header';
function headersSize(request) {
const keys = [];
const values = [];
request.headers.forEach(({ name, value }) => {
keys.push(name);
values.push(value);
});
const headersString =
request.method + request.url + keys.join() + values.join();
// startline: [method] [url] HTTP/1.1\r\n = 12
// endline: \r\n = 2
// every header + \r\n = * 2
// add 2 for each combined header
return getByteLength(headersString) + keys.length * 2 + 2 + 12 + 2;
}
export default class Request {
constructor(request) {
this.httpVersion = 'HTTP/1.1';
this.url = request.absoluteUrl;
this.method = request.method;
this.headers = toNVPairs(request.headers);
this.headersSize = headersSize(this);
this.queryString = toNVPairs(request.query);
this.cookies = setCookies.parse(request.getHeader('Set-Cookie'));
if (request.body) {
this.postData = {
mimeType: getFirstHeader(request, 'Content-Type') || 'text/plain',
params: []
};
if (typeof request.body === 'string') {
this.postData.text = request.body;
}
}
const contentLength = getFirstHeader(request, 'Content-Length');
if (contentLength) {
this.bodySize = parseInt(contentLength, 10);
} else {
this.bodySize =
this.postData && this.postData.text
? getByteLength(this.postData.text)
: 0;
}
}
}
================================================
FILE: packages/@pollyjs/persister/src/har/response.js
================================================
import getByteLength from 'utf8-byte-length';
import setCookies from 'set-cookie-parser';
import toNVPairs from './utils/to-nv-pairs';
import getFirstHeader from './utils/get-first-header';
function headersSize(response) {
const keys = [];
const values = [];
response.headers.forEach(({ name, value }) => {
keys.push(name);
values.push(value);
});
const headersString = keys.join() + values.join();
// endline: \r\n = 2
// every header + \r\n = * 2
// add 2 for each combined header
return getByteLength(headersString) + keys.length * 2 + 2 + 2;
}
export default class Response {
constructor(response) {
this.httpVersion = 'HTTP/1.1';
this.status = response.statusCode;
this.statusText = response.statusText;
this.headers = toNVPairs(response.headers);
this.headersSize = headersSize(this);
this.cookies = setCookies.parse(response.getHeader('Set-Cookie'));
this.redirectURL = getFirstHeader(response, 'Location') || '';
this.content = {
mimeType: getFirstHeader(response, 'Content-Type') || 'text/plain'
};
if (response.body && typeof response.body === 'string') {
this.content.text = response.body;
if (response.encoding) {
this.content.encoding = response.encoding;
}
}
const contentLength = getFirstHeader(response, 'Content-Length');
if (contentLength) {
this.content.size = parseInt(contentLength, 10);
} else {
this.content.size = this.content.text
? getByteLength(this.content.text)
: 0;
}
this.bodySize = this.content.size;
}
}
================================================
FILE: packages/@pollyjs/persister/src/har/utils/get-first-header.js
================================================
const { isArray } = Array;
/**
* Get the value of the given header name. If the value is an array,
* get the first value.
*
* @export
* @param {PollyRequest | PollyResponse} r
* @param {string} name
* @returns {string | undefined}
*/
export default function getFirstHeader(r, name) {
const value = r.getHeader(name);
if (isArray(value)) {
return value.length > 0 ? value[0] : '';
}
return value;
}
================================================
FILE: packages/@pollyjs/persister/src/har/utils/to-nv-pairs.js
================================================
const { keys } = Object;
const { isArray } = Array;
export default function toNVPairs(o) {
return keys(o || {}).reduce((pairs, name) => {
const value = o[name];
if (isArray(value)) {
// _fromType is used to convert the stored header back into the
// type it originally was. Take the following example:
// { 'content-type': ['text/htm'] }
// => { name: 'content-type', value: 'text/html', _fromType: 'array }
// => { 'content-type': ['text/htm'] }
pairs.push(...value.map((v) => ({ name, value: v, _fromType: 'array' })));
} else {
pairs.push({ name, value });
}
return pairs;
}, []);
}
================================================
FILE: packages/@pollyjs/persister/src/index.js
================================================
import stringify from 'fast-json-stable-stringify';
import { ACTIONS, assert } from '@pollyjs/utils';
import HAR from './har';
import Entry from './har/entry';
const CREATOR_NAME = 'Polly.JS';
export default class Persister {
constructor(polly) {
this.polly = polly;
this.pending = new Map();
this._cache = new Map();
}
static get type() {
return 'persister';
}
/* eslint-disable-next-line getter-return */
static get id() {
assert('Must override the static `id` getter.');
}
get defaultOptions() {
return {};
}
get options() {
return {
...(this.defaultOptions || {}),
...((this.polly.config.persisterOptions || {})[this.constructor.id] || {})
};
}
get hasPending() {
/*
Although the pending map is bucketed by recordingId, the bucket will always
be created with a single item in it so we can assume that if a bucket
exists, then it has items in it.
*/
return this.pending.size > 0;
}
async persist() {
if (!this.hasPending) {
return;
}
const promises = [];
const creator = {
name: CREATOR_NAME,
version: this.polly.constructor.VERSION,
comment: `${this.constructor.type}:${this.constructor.id}`
};
for (const [recordingId, { name, requests }] of this.pending) {
const entries = [];
const recording = await this.findRecording(recordingId);
let har;
if (!recording) {
har = new HAR({ log: { creator, _recordingName: name } });
} else {
har = new HAR(recording);
}
for (const request of requests) {
const entry = new Entry(request);
this.assert(
`Cannot persist response for [${entry.request.method}] ${entry.request.url} because the status code was ${entry.response.status} and \`recordFailedRequests\` is \`false\``,
entry.response.status < 400 || request.config.recordFailedRequests
);
/*
Trigger the `beforePersist` event on each new recorded entry.
NOTE: This must be triggered last as this entry can be used to
modify the payload (i.e. encrypting the request & response).
*/
await request._emit('beforePersist', entry);
entries.push(entry);
}
har.log.addEntries(entries);
if (!this.polly.config.persisterOptions.disableSortingHarEntries) {
har.log.sortEntries();
}
if (!this.polly.config.persisterOptions.keepUnusedRequests) {
this._removeUnusedEntries(recordingId, har);
}
promises.push(this.saveRecording(recordingId, har));
}
await Promise.all(promises);
this.pending.clear();
}
recordRequest(pollyRequest) {
this.assert(
`You must pass a PollyRequest to 'recordRequest'.`,
pollyRequest
);
this.assert(
`Cannot save a request with no response.`,
pollyRequest.didRespond
);
const { recordingId, recordingName } = pollyRequest;
if (!this.pending.has(recordingId)) {
this.pending.set(recordingId, { name: recordingName, requests: [] });
}
this.pending.get(recordingId).requests.push(pollyRequest);
}
async findRecording(recordingId) {
const { _cache: cache } = this;
if (!cache.has(recordingId)) {
const onFindRecording = async () => {
const recording = await this.onFindRecording(recordingId);
if (recording) {
this.assert(
`Recording with id '${recordingId}' is invalid. Please delete the recording so a new one can be created.`,
recording.log && recording.log.creator.name === CREATOR_NAME
);
return recording;
} else {
cache.delete(recordingId);
return null;
}
};
cache.set(recordingId, onFindRecording());
}
return cache.get(recordingId);
}
onFindRecording() {
this.assert('Must implement the `onFindRecording` hook.');
}
async saveRecording(recordingId, har) {
await this.onSaveRecording(...arguments);
this._cache.delete(recordingId);
this.polly.logger.log.debug('Recording saved.', { recordingId, har });
}
onSaveRecording() {
this.assert('Must implement the `onSaveRecording` hook.');
}
async deleteRecording(recordingId) {
await this.onDeleteRecording(...arguments);
this._cache.delete(recordingId);
}
onDeleteRecording() {
this.assert('Must implement the `onDeleteRecording` hook.');
}
async findEntry(pollyRequest) {
const { id, order, recordingId } = pollyRequest;
const recording = await this.findRecording(recordingId);
return (
(recording &&
recording.log.entries.find(
(entry) => entry._id === id && entry._order === order
)) ||
null
);
}
stringify() {
return stringify(...arguments);
}
assert(message, ...args) {
assert(
`[${this.constructor.type}:${this.constructor.id}] ${message}`,
...args
);
}
/**
* Remove all entries from the given HAR that do not match any requests in
* the current Polly instance.
*
* @param {String} recordingId
* @param {HAR} har
*/
_removeUnusedEntries(recordingId, har) {
const requests = this.polly._requests.filter(
(r) =>
r.recordingId === recordingId &&
(r.action === ACTIONS.RECORD || r.action === ACTIONS.REPLAY)
);
har.log.entries = har.log.entries.filter((entry) =>
requests.find((r) => entry._id === r.id && entry._order === r.order)
);
}
}
================================================
FILE: packages/@pollyjs/persister/tests/unit/har-test.js
================================================
import * as validate from 'har-validator/lib/async';
import HAR from '../../src/har';
import Log from '../../src/har/log';
import Entry from '../../src/har/entry';
import Request from '../../src/har/request';
import Response from '../../src/har/response';
describe('Unit | HAR', function () {
it('should exist', function () {
expect(HAR).to.be.a('function');
expect(Log).to.be.a('function');
expect(Entry).to.be.a('function');
expect(Request).to.be.a('function');
expect(Response).to.be.a('function');
});
describe('Log', function () {
it('should merge passed options', async function () {
expect(new Log({ foo: 'foo' })).to.deep.include({ foo: 'foo' });
});
it('should require creator', async function () {
expect(await validate.log(new Log())).to.be.false;
});
it('should be valid', async function () {
expect(
await validate.log(
new Log({
creator: { name: 'Polly.JS', version: '0.0.0' }
})
)
).to.be.true;
});
it('addEntries: Entries should be unique', async function () {
const now = new Date().getTime();
const log = new Log({
entries: [
{
_id: 'abc',
_order: 0,
startedDateTime: new Date(now),
_new: false
},
{
_id: 'def',
_order: 0,
startedDateTime: new Date(now + 10),
_new: false
}
]
});
log.addEntries([
{
_id: 'abc',
_order: 0,
startedDateTime: new Date(now + 100),
_new: true
},
{
_id: 'abc',
_order: 1,
startedDateTime: new Date(now + 105),
_new: true
},
{ _id: 'ghi', _order: 0, startedDateTime: new Date(now), _new: true }
]);
expect(
log.entries.map(({ _id, _order, _new }) => ({ _id, _order, _new }))
).to.include.deep.ordered.members([
{ _id: 'abc', _order: 0, _new: true },
{ _id: 'abc', _order: 1, _new: true },
{ _id: 'ghi', _order: 0, _new: true },
{ _id: 'def', _order: 0, _new: false }
]);
});
it('sortEntries: sorts by startedDateTime', async function () {
const now = new Date().getTime();
const log = new Log({
entries: [
{ _id: 'd', startedDateTime: new Date(now + 15) },
{ _id: 'b', startedDateTime: new Date(now + 5) },
{ _id: 'a', startedDateTime: new Date(now + 0) },
{ _id: 'c', startedDateTime: new Date(now + 10) }
]
});
log.sortEntries();
expect(log.entries.map((e) => e._id)).to.have.deep.ordered.members([
'a',
'b',
'c',
'd'
]);
});
});
});
================================================
FILE: packages/@pollyjs/persister/tests/unit/persister-test.js
================================================
import { timeout } from '@pollyjs/utils';
import Persister from '../../src';
describe('Unit | Persister', function () {
it('should exist', function () {
expect(Persister).to.be.a('function');
});
describe('Caching', function () {
let callCounts, recording;
beforeEach(function () {
callCounts = { find: 0, save: 0, delete: 0 };
recording = {
log: {
creator: {
name: 'Polly.JS'
}
}
};
class CustomPersister extends Persister {
static get id() {
return 'CustomPersister';
}
async onFindRecording() {
callCounts.find++;
await timeout(1);
return recording;
}
async onSaveRecording() {
callCounts.save++;
await timeout(1);
}
async onDeleteRecording() {
callCounts.delete++;
await timeout(1);
}
}
this.persister = new CustomPersister({
logger: {
log: { debug: () => {} }
}
});
});
it('should handle concurrent find requests', async function () {
await Promise.all([
this.persister.findRecording('test'),
this.persister.findRecording('test'),
this.persister.findRecording('test')
]);
expect(callCounts.find).to.equal(1);
});
it('caches', async function () {
await this.persister.findRecording('test');
await this.persister.findRecording('test');
await this.persister.findRecording('test');
expect(callCounts.find).to.equal(1);
});
it('does not cache falsy values', async function () {
recording = null;
await this.persister.findRecording('test');
await Promise.all([
this.persister.findRecording('test'),
this.persister.findRecording('test'),
this.persister.findRecording('test')
]);
await this.persister.findRecording('test');
expect(callCounts.find).to.equal(3);
});
it('busts the cache after a save', async function () {
await this.persister.findRecording('test');
await this.persister.saveRecording('test');
await this.persister.findRecording('test');
await this.persister.findRecording('test');
expect(callCounts.save).to.equal(1);
expect(callCounts.find).to.equal(2);
});
it('busts the cache after a delete', async function () {
await this.persister.findRecording('test');
await this.persister.deleteRecording('test');
await this.persister.findRecording('test');
await this.persister.findRecording('test');
expect(callCounts.delete).to.equal(1);
expect(callCounts.find).to.equal(2);
});
});
});
================================================
FILE: packages/@pollyjs/persister/types.d.ts
================================================
import { Polly, Request } from '@pollyjs/core';
import { Cookie } from 'set-cookie-parser';
type NVObject = { name: string; value: string };
export interface HarRequest {
httpVersion: string;
url: string;
method: string;
headers: NVObject[];
headersSize: number;
queryString: NVObject[];
cookies: Cookie[];
postData?: {
mimeType: string;
params: [];
text?: string;
};
bodySize?: number;
}
export interface HarResponse {
httpVersion: string;
status: number;
statusText: string;
headers: NVObject[];
headersSize: number;
cookies: Cookie[];
content: {
mimeType: string;
text?: string;
encoding?: string;
size?: number;
};
bodySize?: number;
}
export interface HarEntry {
_id: string;
_order: number;
startedDateTime: string;
request: HarRequest;
response: HarResponse;
cache: {};
timings: {
blocked: number;
dns: number;
connect: number;
send: number;
wait: number;
receive: number;
ssl: number;
};
time: number;
}
export interface HarLog {
version: string;
browser: string;
entries: HarEntry[];
pages: [];
addEntries(entries: HarEntry[]): void;
sortEntries(): void;
}
export interface Har {
log: HarLog;
}
export default class Persister {
static readonly id: string;
static readonly type: string;
constructor(polly: Polly);
readonly defaultOptions: TOptions;
readonly options: TOptions;
private pending: Map;
private _cache: Map;
polly: Polly;
hasPending: boolean;
persist(): Promise;
recordRequest(request: Request): void;
private findRecording(recordingId: string): Promise;
onFindRecording(recordingId: string): Promise;
private saveRecording(recordingId: string, har: Har): Promise;
onSaveRecording(recordingId: string, har: Har): Promise;
private deleteRecording(recordingId: string): Promise;
onDeleteRecording(recordingId: string): Promise;
findEntry(request: Request): Promise;
stringify(value: any): string;
assert(message: string, condition?: boolean): void;
}
================================================
FILE: packages/@pollyjs/persister-fs/.eslintrc.js
================================================
module.exports = {
env: {
browser: false,
node: true
}
};
================================================
FILE: packages/@pollyjs/persister-fs/CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.6](https://github.com/netflix/pollyjs/compare/v6.0.5...v6.0.6) (2023-07-20)
**Note:** Version bump only for package @pollyjs/persister-fs
## [6.0.5](https://github.com/netflix/pollyjs/compare/v6.0.4...v6.0.5) (2022-04-04)
**Note:** Version bump only for package @pollyjs/persister-fs
## [6.0.4](https://github.com/netflix/pollyjs/compare/v6.0.3...v6.0.4) (2021-12-10)
**Note:** Version bump only for package @pollyjs/persister-fs
## [6.0.3](https://github.com/netflix/pollyjs/compare/v6.0.2...v6.0.3) (2021-12-08)
**Note:** Version bump only for package @pollyjs/persister-fs
## [6.0.2](https://github.com/netflix/pollyjs/compare/v6.0.1...v6.0.2) (2021-12-07)
**Note:** Version bump only for package @pollyjs/persister-fs
## [6.0.1](https://github.com/netflix/pollyjs/compare/v6.0.0...v6.0.1) (2021-12-06)
### Bug Fixes
* **types:** add types.d.ts to package.files ([#431](https://github.com/netflix/pollyjs/issues/431)) ([113ee89](https://github.com/netflix/pollyjs/commit/113ee898bcf0467c5c48c15b53fc9198e2e91cb1))
# [6.0.0](https://github.com/netflix/pollyjs/compare/v5.2.0...v6.0.0) (2021-11-30)
* feat!: Cleanup adapter and persister APIs (#429) ([06499fc](https://github.com/netflix/pollyjs/commit/06499fc2d85254b3329db2bec770d173ed32bca0)), closes [#429](https://github.com/netflix/pollyjs/issues/429)
* chore!: Upgrade package dependencies (#421) ([dd23334](https://github.com/netflix/pollyjs/commit/dd23334fa9b64248e4c49c3616237bdc2f12f682)), closes [#421](https://github.com/netflix/pollyjs/issues/421)
* feat(ember)!: Upgrade to ember octane (#415) ([8559ef8](https://github.com/netflix/pollyjs/commit/8559ef8c600aefaec629870eac5f5c8953e18b16)), closes [#415](https://github.com/netflix/pollyjs/issues/415)
### BREAKING CHANGES
* - Adapter
- `passthroughRequest` renamed to `onFetchResponse`
- `respondToRequest` renamed to `onRespond`
- Persister
- `findRecording` renamed to `onFindRecording`
- `saveRecording` renamed to `onSaveRecording`
- `deleteRecording` renamed to `onDeleteRecording`
* Recording file name will no longer have trailing dashes
* @pollyjs dependencies have been moved to peer dependencies
## [5.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v5.1.0...v5.1.1) (2021-06-02)
**Note:** Version bump only for package @pollyjs/persister-fs
# [5.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v4.3.0...v5.0.0) (2020-06-23)
**Note:** Version bump only for package @pollyjs/persister-fs
# [4.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v4.2.1...v4.3.0) (2020-05-18)
**Note:** Version bump only for package @pollyjs/persister-fs
## [4.2.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v4.2.0...v4.2.1) (2020-04-30)
**Note:** Version bump only for package @pollyjs/persister-fs
# [4.2.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v4.1.0...v4.2.0) (2020-04-29)
**Note:** Version bump only for package @pollyjs/persister-fs
# [4.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v4.0.4...v4.1.0) (2020-04-23)
**Note:** Version bump only for package @pollyjs/persister-fs
## [4.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v4.0.3...v4.0.4) (2020-03-21)
### Bug Fixes
* Deprecates adapter & persister `name` in favor of `id` ([#310](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/issues/310)) ([41dd093](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/commit/41dd093))
## [4.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v4.0.1...v4.0.2) (2020-01-29)
**Note:** Version bump only for package @pollyjs/persister-fs
# [4.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v3.0.2...v4.0.0) (2020-01-13)
**Note:** Version bump only for package @pollyjs/persister-fs
# [3.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v2.7.0...v3.0.0) (2019-12-18)
**Note:** Version bump only for package @pollyjs/persister-fs
## [2.6.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v2.6.2...v2.6.3) (2019-09-30)
### Bug Fixes
* use watch strategy ([#236](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/issues/236)) ([5b4edf3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/commit/5b4edf3))
## [2.6.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v2.6.1...v2.6.2) (2019-08-05)
**Note:** Version bump only for package @pollyjs/persister-fs
## [2.6.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v2.6.0...v2.6.1) (2019-08-01)
**Note:** Version bump only for package @pollyjs/persister-fs
# [2.6.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v2.5.0...v2.6.0) (2019-07-17)
**Note:** Version bump only for package @pollyjs/persister-fs
# [2.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v2.0.0...v2.1.0) (2019-02-04)
**Note:** Version bump only for package @pollyjs/persister-fs
# [2.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v1.4.2...v2.0.0) (2019-01-29)
**Note:** Version bump only for package @pollyjs/persister-fs
## [1.4.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v1.4.1...v1.4.2) (2019-01-16)
**Note:** Version bump only for package @pollyjs/persister-fs
## [1.4.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v1.4.0...v1.4.1) (2018-12-13)
**Note:** Version bump only for package @pollyjs/persister-fs
## [1.3.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v1.3.1...v1.3.2) (2018-11-29)
**Note:** Version bump only for package @pollyjs/persister-fs
## [1.3.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/v1.2.0...v1.3.1) (2018-11-28)
**Note:** Version bump only for package @pollyjs/persister-fs
# 1.2.0 (2018-09-16)
### Features
* Node File System Persister ([#61](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister-fs/issues/61)) ([0a0eeca](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/commit/0a0eeca))
* Puppeteer Adapter ([#64](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister-fs/issues/64)) ([f902c6d](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/commit/f902c6d))
## [1.0.5](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/@pollyjs/persister-fs@1.0.4...@pollyjs/persister-fs@1.0.5) (2018-08-22)
**Note:** Version bump only for package @pollyjs/persister-fs
## [1.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/@pollyjs/persister-fs@1.0.3...@pollyjs/persister-fs@1.0.4) (2018-08-12)
**Note:** Version bump only for package @pollyjs/persister-fs
## [1.0.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/@pollyjs/persister-fs@1.0.2...@pollyjs/persister-fs@1.0.3) (2018-08-12)
**Note:** Version bump only for package @pollyjs/persister-fs
## [1.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/@pollyjs/persister-fs@1.0.1...@pollyjs/persister-fs@1.0.2) (2018-08-09)
**Note:** Version bump only for package @pollyjs/persister-fs
## [1.0.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/compare/@pollyjs/persister-fs@1.0.0...@pollyjs/persister-fs@1.0.1) (2018-07-26)
**Note:** Version bump only for package @pollyjs/persister-fs
# 1.0.0 (2018-07-20)
### Features
* Node File System Persister ([#61](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister-fs/issues/61)) ([0a0eeca](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/commit/0a0eeca))
* Puppeteer Adapter ([#64](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/persister-fs/issues/64)) ([f902c6d](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs/commit/f902c6d))
================================================
FILE: packages/@pollyjs/persister-fs/LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Netflix Inc and @pollyjs contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: packages/@pollyjs/persister-fs/README.md
================================================
Record, Replay, and Stub HTTP Interactions
[](https://travis-ci.com/Netflix/pollyjs)
[](https://badge.fury.io/js/%40pollyjs%2Fpersister-fs)
[](http://www.apache.org/licenses/LICENSE-2.0)
The `@pollyjs/persister-fs` package provides a node file-system persister
to be used with `@pollyjs/core`.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/persister-fs -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/persister-fs -D
```
## Documentation
Check out the [FS Persister](https://netflix.github.io/pollyjs/#/persisters/fs)
documentation for more details.
## Usage
```js
import { Polly } from '@pollyjs/core';
import FSPersister from '@pollyjs/persister-fs';
Polly.register(FSPersister);
new Polly('', {
persister: ['fs']
});
```
## License
Copyright (c) 2018 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
================================================
FILE: packages/@pollyjs/persister-fs/package.json
================================================
{
"name": "@pollyjs/persister-fs",
"version": "6.0.6",
"description": "File system persister for @pollyjs",
"main": "dist/cjs/pollyjs-persister-fs.js",
"module": "dist/es/pollyjs-persister-fs.js",
"types": "types.d.ts",
"files": [
"src",
"dist",
"types.d.ts"
],
"repository": "https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs",
"license": "Apache-2.0",
"contributors": [
{
"name": "Jason Mitchell",
"email": "jason.mitchell.w@gmail.com"
},
{
"name": "Offir Golan",
"email": "offirgolan@gmail.com"
}
],
"keywords": [
"polly",
"pollyjs",
"record",
"replay",
"fs",
"file"
],
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "rollup -c",
"build:watch": "yarn build -w",
"test:build": "rollup -c rollup.config.test.js",
"test:build:watch": "rollup -c rollup.config.test.js -w",
"watch-all": "npm-run-all --parallel build:watch test:build:watch"
},
"dependencies": {
"@pollyjs/node-server": "^6.0.6",
"@pollyjs/persister": "^6.0.6"
},
"devDependencies": {
"fixturify": "^2.1.1",
"rimraf": "^3.0.2",
"rollup": "^1.14.6"
}
}
================================================
FILE: packages/@pollyjs/persister-fs/rollup.config.js
================================================
import createNodeConfig from '../../../scripts/rollup/node.config';
export default createNodeConfig();
================================================
FILE: packages/@pollyjs/persister-fs/rollup.config.test.js
================================================
import createNodeTestConfig from '../../../scripts/rollup/node.test.config';
export default createNodeTestConfig({
external: ['rimraf', 'fixturify']
});
================================================
FILE: packages/@pollyjs/persister-fs/src/index.js
================================================
import Persister from '@pollyjs/persister';
import { API, Defaults } from '@pollyjs/node-server';
const { parse } = JSON;
export default class FSPersister extends Persister {
constructor() {
super(...arguments);
this.api = new API(this.options);
}
static get id() {
return 'fs';
}
get defaultOptions() {
return {
recordingsDir: Defaults.recordingsDir
};
}
onFindRecording(recordingId) {
return this.api.getRecording(recordingId).body || null;
}
onSaveRecording(recordingId, data) {
/*
Pass the data through the base persister's stringify method so
the output will be consistent with the rest of the persisters.
*/
this.api.saveRecording(recordingId, parse(this.stringify(data)));
}
onDeleteRecording(recordingId) {
this.api.deleteRecording(recordingId);
}
}
================================================
FILE: packages/@pollyjs/persister-fs/tests/unit/persister-test.js
================================================
import rimraf from 'rimraf';
import fixturify from 'fixturify';
import FSPersister from '../../src';
class MockPolly {
constructor(persisterOptions = {}) {
this.config = {
persisterOptions: { fs: persisterOptions || {} }
};
}
}
describe('Unit | FS Persister', function () {
afterEach(function () {
rimraf.sync('recordings');
});
it('should exist', function () {
expect(FSPersister).to.be.a('function');
});
it('should have a id', function () {
expect(FSPersister.id).to.equal('fs');
});
describe('Options', function () {
it('recordingsDir', function () {
let persister = new FSPersister(new MockPolly());
expect(persister.options.recordingsDir)
.to.equal(persister.defaultOptions.recordingsDir)
.and.to.equal('recordings');
persister = new FSPersister(
new MockPolly({
recordingsDir: 'recordings/tmp'
})
);
expect(persister.options.recordingsDir)
.to.equal('recordings/tmp')
.and.to.not.equal(persister.defaultOptions.recordingsDir);
fixturify.writeSync('recordings/tmp', {
'FS-Persister': {
'recording.har': '{}'
}
});
expect(persister.onFindRecording('FS-Persister')).to.deep.equal({});
});
});
describe('API', function () {
beforeEach(function () {
this.persister = new FSPersister(new MockPolly());
fixturify.writeSync('recordings', {
'FS-Persister': {
'recording.har': '{}'
}
});
});
it('onSaveRecording', function () {
expect(this.persister.onFindRecording('FS-Persister')).to.deep.equal({});
this.persister.onSaveRecording('FS-Persister', { foo: 'bar' });
expect(this.persister.onFindRecording('FS-Persister')).to.deep.equal({
foo: 'bar'
});
});
it('onFindRecording', function () {
expect(this.persister.onFindRecording('FS-Persister')).to.deep.equal({});
expect(this.persister.onFindRecording('Does-Not-Exist')).to.be.null;
});
it('onDeleteRecording', function () {
expect(this.persister.onFindRecording('FS-Persister')).to.not.be.null;
this.persister.onDeleteRecording('FS-Persister');
expect(this.persister.onFindRecording('Does-Not-Exist')).to.be.null;
});
});
});
================================================
FILE: packages/@pollyjs/persister-fs/types.d.ts
================================================
import Persister from '@pollyjs/persister';
export default class FSPersister extends Persister<{
recordingsDir?: string;
}> {}
================================================
FILE: packages/@pollyjs/persister-in-memory/CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.6](https://github.com/netflix/pollyjs/compare/v6.0.5...v6.0.6) (2023-07-20)
**Note:** Version bump only for package @pollyjs/persister-in-memory
## [6.0.5](https://github.com/netflix/pollyjs/compare/v6.0.4...v6.0.5) (2022-04-04)
**Note:** Version bump only for package @pollyjs/persister-in-memory
## [6.0.4](https://github.com/netflix/pollyjs/compare/v6.0.3...v6.0.4) (2021-12-10)
**Note:** Version bump only for package @pollyjs/persister-in-memory
## [6.0.3](https://github.com/netflix/pollyjs/compare/v6.0.2...v6.0.3) (2021-12-08)
**Note:** Version bump only for package @pollyjs/persister-in-memory
## [6.0.2](https://github.com/netflix/pollyjs/compare/v6.0.1...v6.0.2) (2021-12-07)
**Note:** Version bump only for package @pollyjs/persister-in-memory
## [6.0.1](https://github.com/netflix/pollyjs/compare/v6.0.0...v6.0.1) (2021-12-06)
### Bug Fixes
* **types:** add types.d.ts to package.files ([#431](https://github.com/netflix/pollyjs/issues/431)) ([113ee89](https://github.com/netflix/pollyjs/commit/113ee898bcf0467c5c48c15b53fc9198e2e91cb1))
# [6.0.0](https://github.com/netflix/pollyjs/compare/v5.2.0...v6.0.0) (2021-11-30)
* feat!: Cleanup adapter and persister APIs (#429) ([06499fc](https://github.com/netflix/pollyjs/commit/06499fc2d85254b3329db2bec770d173ed32bca0)), closes [#429](https://github.com/netflix/pollyjs/issues/429)
### BREAKING CHANGES
* - Adapter
- `passthroughRequest` renamed to `onFetchResponse`
- `respondToRequest` renamed to `onRespond`
- Persister
- `findRecording` renamed to `onFindRecording`
- `saveRecording` renamed to `onSaveRecording`
- `deleteRecording` renamed to `onDeleteRecording`
## [5.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory/compare/v5.1.0...v5.1.1) (2021-06-02)
**Note:** Version bump only for package @pollyjs/persister-in-memory
# [5.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory/compare/v4.3.0...v5.0.0) (2020-06-23)
**Note:** Version bump only for package @pollyjs/persister-in-memory
# [4.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory/compare/v4.2.1...v4.3.0) (2020-05-18)
**Note:** Version bump only for package @pollyjs/persister-in-memory
## [4.2.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory/compare/v4.2.0...v4.2.1) (2020-04-30)
**Note:** Version bump only for package @pollyjs/persister-in-memory
# [4.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory/compare/v4.0.4...v4.1.0) (2020-04-23)
**Note:** Version bump only for package @pollyjs/persister-in-memory
## [4.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory/compare/v4.0.3...v4.0.4) (2020-03-21)
### Bug Fixes
* Deprecates adapter & persister `name` in favor of `id` ([#310](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory/issues/310)) ([41dd093](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory/commit/41dd093))
## [4.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory/compare/v4.0.1...v4.0.2) (2020-01-29)
**Note:** Version bump only for package @pollyjs/persister-in-memory
# [4.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory/compare/v3.0.2...v4.0.0) (2020-01-13)
**Note:** Version bump only for package @pollyjs/persister-in-memory
# [3.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory/compare/v2.7.0...v3.0.0) (2019-12-18)
**Note:** Version bump only for package @pollyjs/persister-in-memory
## [2.6.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory/compare/v2.6.2...v2.6.3) (2019-09-30)
### Bug Fixes
* use watch strategy ([#236](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory/issues/236)) ([5b4edf3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory/commit/5b4edf3))
## [2.6.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory/compare/v2.6.1...v2.6.2) (2019-08-05)
### Features
* Adds an in-memory persister to test polly internals ([#237](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory/issues/237)) ([5a6fda6](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory/commit/5a6fda6))
================================================
FILE: packages/@pollyjs/persister-in-memory/LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Netflix Inc and @pollyjs contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: packages/@pollyjs/persister-in-memory/package.json
================================================
{
"name": "@pollyjs/persister-in-memory",
"version": "6.0.6",
"private": true,
"description": "In memory storage persister for @pollyjs",
"main": "dist/cjs/pollyjs-persister-in-memory.js",
"module": "dist/es/pollyjs-persister-in-memory.js",
"browser": "dist/umd/pollyjs-persister-in-memory.js",
"types": "types.d.ts",
"files": [
"src",
"dist",
"types.d.ts"
],
"repository": "https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-in-memory",
"license": "Apache-2.0",
"contributors": [
{
"name": "Jason Mitchell",
"email": "jason.mitchell.w@gmail.com"
},
{
"name": "Offir Golan",
"email": "offirgolan@gmail.com"
}
],
"keywords": [
"polly",
"pollyjs",
"record",
"replay",
"persister"
],
"publishConfig": {
"access": "private"
},
"scripts": {
"build": "rollup -c ../../../scripts/rollup/default.config.js",
"test:build": "rollup -c rollup.config.test.js",
"test:build:watch": "rollup -c rollup.config.test.js -w",
"build:watch": "yarn build -w",
"watch-all": "npm-run-all --parallel build:watch test:build:watch"
},
"dependencies": {
"@pollyjs/persister": "^6.0.6"
},
"devDependencies": {
"rollup": "^1.14.6"
}
}
================================================
FILE: packages/@pollyjs/persister-in-memory/rollup.config.test.js
================================================
import createNodeTestConfig from '../../../scripts/rollup/node.test.config';
import createBrowserTestConfig from '../../../scripts/rollup/browser.test.config';
export default [createNodeTestConfig(), createBrowserTestConfig()];
================================================
FILE: packages/@pollyjs/persister-in-memory/src/index.js
================================================
import Persister from '@pollyjs/persister';
const store = new Map();
export default class InMemoryPersister extends Persister {
static get id() {
return 'in-memory-persister';
}
onFindRecording(recordingId) {
return store.get(recordingId) || null;
}
onSaveRecording(recordingId, data) {
store.set(recordingId, data);
}
onDeleteRecording(recordingId) {
store.delete(recordingId);
}
}
================================================
FILE: packages/@pollyjs/persister-in-memory/types.d.ts
================================================
import Persister from '@pollyjs/persister';
export default class InMemoryPersister extends Persister {}
================================================
FILE: packages/@pollyjs/persister-local-storage/CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.6](https://github.com/netflix/pollyjs/compare/v6.0.5...v6.0.6) (2023-07-20)
**Note:** Version bump only for package @pollyjs/persister-local-storage
## [6.0.5](https://github.com/netflix/pollyjs/compare/v6.0.4...v6.0.5) (2022-04-04)
**Note:** Version bump only for package @pollyjs/persister-local-storage
## [6.0.4](https://github.com/netflix/pollyjs/compare/v6.0.3...v6.0.4) (2021-12-10)
**Note:** Version bump only for package @pollyjs/persister-local-storage
## [6.0.3](https://github.com/netflix/pollyjs/compare/v6.0.2...v6.0.3) (2021-12-08)
**Note:** Version bump only for package @pollyjs/persister-local-storage
## [6.0.2](https://github.com/netflix/pollyjs/compare/v6.0.1...v6.0.2) (2021-12-07)
**Note:** Version bump only for package @pollyjs/persister-local-storage
## [6.0.1](https://github.com/netflix/pollyjs/compare/v6.0.0...v6.0.1) (2021-12-06)
### Bug Fixes
* **types:** add types.d.ts to package.files ([#431](https://github.com/netflix/pollyjs/issues/431)) ([113ee89](https://github.com/netflix/pollyjs/commit/113ee898bcf0467c5c48c15b53fc9198e2e91cb1))
# [6.0.0](https://github.com/netflix/pollyjs/compare/v5.2.0...v6.0.0) (2021-11-30)
* feat!: Cleanup adapter and persister APIs (#429) ([06499fc](https://github.com/netflix/pollyjs/commit/06499fc2d85254b3329db2bec770d173ed32bca0)), closes [#429](https://github.com/netflix/pollyjs/issues/429)
### BREAKING CHANGES
* - Adapter
- `passthroughRequest` renamed to `onFetchResponse`
- `respondToRequest` renamed to `onRespond`
- Persister
- `findRecording` renamed to `onFindRecording`
- `saveRecording` renamed to `onSaveRecording`
- `deleteRecording` renamed to `onDeleteRecording`
## [5.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v5.1.0...v5.1.1) (2021-06-02)
**Note:** Version bump only for package @pollyjs/persister-local-storage
# [5.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v4.3.0...v5.0.0) (2020-06-23)
**Note:** Version bump only for package @pollyjs/persister-local-storage
# [4.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v4.2.1...v4.3.0) (2020-05-18)
**Note:** Version bump only for package @pollyjs/persister-local-storage
## [4.2.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v4.2.0...v4.2.1) (2020-04-30)
**Note:** Version bump only for package @pollyjs/persister-local-storage
# [4.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v4.0.4...v4.1.0) (2020-04-23)
**Note:** Version bump only for package @pollyjs/persister-local-storage
## [4.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v4.0.3...v4.0.4) (2020-03-21)
### Bug Fixes
* Deprecates adapter & persister `name` in favor of `id` ([#310](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/issues/310)) ([41dd093](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/commit/41dd093))
## [4.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v4.0.1...v4.0.2) (2020-01-29)
**Note:** Version bump only for package @pollyjs/persister-local-storage
# [4.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v3.0.2...v4.0.0) (2020-01-13)
**Note:** Version bump only for package @pollyjs/persister-local-storage
# [3.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v2.7.0...v3.0.0) (2019-12-18)
**Note:** Version bump only for package @pollyjs/persister-local-storage
## [2.6.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v2.6.2...v2.6.3) (2019-09-30)
### Bug Fixes
* use watch strategy ([#236](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/issues/236)) ([5b4edf3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/commit/5b4edf3))
## [2.6.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v2.6.1...v2.6.2) (2019-08-05)
**Note:** Version bump only for package @pollyjs/persister-local-storage
## [2.6.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v2.6.0...v2.6.1) (2019-08-01)
**Note:** Version bump only for package @pollyjs/persister-local-storage
# [2.6.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v2.5.0...v2.6.0) (2019-07-17)
**Note:** Version bump only for package @pollyjs/persister-local-storage
# [2.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v2.0.0...v2.1.0) (2019-02-04)
**Note:** Version bump only for package @pollyjs/persister-local-storage
# [2.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v1.4.2...v2.0.0) (2019-01-29)
**Note:** Version bump only for package @pollyjs/persister-local-storage
## [1.4.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v1.4.0...v1.4.1) (2018-12-13)
**Note:** Version bump only for package @pollyjs/persister-local-storage
## [1.3.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v1.3.1...v1.3.2) (2018-11-29)
**Note:** Version bump only for package @pollyjs/persister-local-storage
## [1.3.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/v1.2.0...v1.3.1) (2018-11-28)
**Note:** Version bump only for package @pollyjs/persister-local-storage
# 1.2.0 (2018-09-16)
**Note:** Version bump only for package @pollyjs/persister-local-storage
## [1.0.5](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/@pollyjs/persister-local-storage@1.0.4...@pollyjs/persister-local-storage@1.0.5) (2018-08-22)
**Note:** Version bump only for package @pollyjs/persister-local-storage
## [1.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/@pollyjs/persister-local-storage@1.0.3...@pollyjs/persister-local-storage@1.0.4) (2018-08-12)
**Note:** Version bump only for package @pollyjs/persister-local-storage
## [1.0.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/@pollyjs/persister-local-storage@1.0.2...@pollyjs/persister-local-storage@1.0.3) (2018-08-12)
**Note:** Version bump only for package @pollyjs/persister-local-storage
## [1.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/@pollyjs/persister-local-storage@1.0.1...@pollyjs/persister-local-storage@1.0.2) (2018-08-09)
**Note:** Version bump only for package @pollyjs/persister-local-storage
## [1.0.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage/compare/@pollyjs/persister-local-storage@1.0.0...@pollyjs/persister-local-storage@1.0.1) (2018-07-26)
**Note:** Version bump only for package @pollyjs/persister-local-storage
# 1.0.0 (2018-07-20)
**Note:** Version bump only for package @pollyjs/persister-local-storage
================================================
FILE: packages/@pollyjs/persister-local-storage/LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Netflix Inc and @pollyjs contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: packages/@pollyjs/persister-local-storage/README.md
================================================
Record, Replay, and Stub HTTP Interactions
[](https://travis-ci.com/Netflix/pollyjs)
[](https://badge.fury.io/js/%40pollyjs%2Fpersister-local-storage)
[](http://www.apache.org/licenses/LICENSE-2.0)
The `@pollyjs/persister-local-storage` package provides a Local Storage
persister that allows to read and write recordings to and from the browser's
Local Storage.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/persister-local-storage -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/persister-local-storage -D
```
## Documentation
Check out the [LocalStorage Persister](https://netflix.github.io/pollyjs/#/persisters/local-storage)
documentation for more details.
## Usage
```js
import { Polly } from '@pollyjs/core';
import LocalStoragePersister from '@pollyjs/persister-local-storage';
Polly.register(LocalStoragePersister);
new Polly('', {
persister: 'local-storage'
});
```
## License
Copyright (c) 2018 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
================================================
FILE: packages/@pollyjs/persister-local-storage/package.json
================================================
{
"name": "@pollyjs/persister-local-storage",
"version": "6.0.6",
"description": "Local storage persister for @pollyjs",
"main": "dist/cjs/pollyjs-persister-local-storage.js",
"module": "dist/es/pollyjs-persister-local-storage.js",
"browser": "dist/umd/pollyjs-persister-local-storage.js",
"types": "types.d.ts",
"files": [
"src",
"dist",
"types.d.ts"
],
"repository": "https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-local-storage",
"license": "Apache-2.0",
"contributors": [
{
"name": "Jason Mitchell",
"email": "jason.mitchell.w@gmail.com"
},
{
"name": "Offir Golan",
"email": "offirgolan@gmail.com"
}
],
"keywords": [
"polly",
"pollyjs",
"record",
"replay",
"local-storage",
"persister"
],
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "rollup -c ../../../scripts/rollup/default.config.js",
"build:watch": "yarn build -w",
"test:build": "rollup -c rollup.config.test.js",
"test:build:watch": "rollup -c rollup.config.test.js -w",
"watch-all": "npm-run-all --parallel build:watch test:build:watch"
},
"dependencies": {
"@pollyjs/persister": "^6.0.6"
},
"devDependencies": {
"rollup": "^1.14.6"
}
}
================================================
FILE: packages/@pollyjs/persister-local-storage/rollup.config.test.js
================================================
import createBrowserTestConfig from '../../../scripts/rollup/browser.test.config';
export default createBrowserTestConfig();
================================================
FILE: packages/@pollyjs/persister-local-storage/src/index.js
================================================
import Persister from '@pollyjs/persister';
const { parse } = JSON;
export default class LocalStoragePersister extends Persister {
static get id() {
return 'local-storage';
}
get defaultOptions() {
return {
key: 'pollyjs',
context: global
};
}
get localStorage() {
const { context } = this.options;
this.assert(
`Could not find "localStorage" on the given context "${context}".`,
context && context.localStorage
);
return context.localStorage;
}
get db() {
const items = this.localStorage.getItem(this.options.key);
return items ? parse(items) : {};
}
set db(db) {
this.localStorage.setItem(this.options.key, this.stringify(db));
}
onFindRecording(recordingId) {
return this.db[recordingId] || null;
}
onSaveRecording(recordingId, data) {
const { db } = this;
db[recordingId] = data;
this.db = db;
}
onDeleteRecording(recordingId) {
const { db } = this;
delete db[recordingId];
this.db = db;
}
}
================================================
FILE: packages/@pollyjs/persister-local-storage/types.d.ts
================================================
import Persister from '@pollyjs/persister';
export default class LocalStoragePersister extends Persister<{
context?: any;
key?: string;
}> {}
================================================
FILE: packages/@pollyjs/persister-rest/CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.6](https://github.com/netflix/pollyjs/compare/v6.0.5...v6.0.6) (2023-07-20)
**Note:** Version bump only for package @pollyjs/persister-rest
## [6.0.5](https://github.com/netflix/pollyjs/compare/v6.0.4...v6.0.5) (2022-04-04)
**Note:** Version bump only for package @pollyjs/persister-rest
## [6.0.4](https://github.com/netflix/pollyjs/compare/v6.0.3...v6.0.4) (2021-12-10)
**Note:** Version bump only for package @pollyjs/persister-rest
## [6.0.3](https://github.com/netflix/pollyjs/compare/v6.0.2...v6.0.3) (2021-12-08)
**Note:** Version bump only for package @pollyjs/persister-rest
## [6.0.2](https://github.com/netflix/pollyjs/compare/v6.0.1...v6.0.2) (2021-12-07)
**Note:** Version bump only for package @pollyjs/persister-rest
## [6.0.1](https://github.com/netflix/pollyjs/compare/v6.0.0...v6.0.1) (2021-12-06)
### Bug Fixes
* **types:** add types.d.ts to package.files ([#431](https://github.com/netflix/pollyjs/issues/431)) ([113ee89](https://github.com/netflix/pollyjs/commit/113ee898bcf0467c5c48c15b53fc9198e2e91cb1))
# [6.0.0](https://github.com/netflix/pollyjs/compare/v5.2.0...v6.0.0) (2021-11-30)
* feat!: Cleanup adapter and persister APIs (#429) ([06499fc](https://github.com/netflix/pollyjs/commit/06499fc2d85254b3329db2bec770d173ed32bca0)), closes [#429](https://github.com/netflix/pollyjs/issues/429)
* feat(ember)!: Upgrade to ember octane (#415) ([8559ef8](https://github.com/netflix/pollyjs/commit/8559ef8c600aefaec629870eac5f5c8953e18b16)), closes [#415](https://github.com/netflix/pollyjs/issues/415)
### BREAKING CHANGES
* - Adapter
- `passthroughRequest` renamed to `onFetchResponse`
- `respondToRequest` renamed to `onRespond`
- Persister
- `findRecording` renamed to `onFindRecording`
- `saveRecording` renamed to `onSaveRecording`
- `deleteRecording` renamed to `onDeleteRecording`
* @pollyjs dependencies have been moved to peer dependencies
## [5.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v5.1.0...v5.1.1) (2021-06-02)
**Note:** Version bump only for package @pollyjs/persister-rest
# [5.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v4.3.0...v5.0.0) (2020-06-23)
**Note:** Version bump only for package @pollyjs/persister-rest
# [4.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v4.2.1...v4.3.0) (2020-05-18)
**Note:** Version bump only for package @pollyjs/persister-rest
## [4.2.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v4.2.0...v4.2.1) (2020-04-30)
**Note:** Version bump only for package @pollyjs/persister-rest
# [4.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v4.0.4...v4.1.0) (2020-04-23)
**Note:** Version bump only for package @pollyjs/persister-rest
## [4.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v4.0.3...v4.0.4) (2020-03-21)
### Bug Fixes
* Deprecates adapter & persister `name` in favor of `id` ([#310](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/issues/310)) ([41dd093](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/commit/41dd093))
## [4.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v4.0.1...v4.0.2) (2020-01-29)
**Note:** Version bump only for package @pollyjs/persister-rest
# [4.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v3.0.2...v4.0.0) (2020-01-13)
**Note:** Version bump only for package @pollyjs/persister-rest
# [3.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v2.7.0...v3.0.0) (2019-12-18)
**Note:** Version bump only for package @pollyjs/persister-rest
## [2.6.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v2.6.2...v2.6.3) (2019-09-30)
### Bug Fixes
* use watch strategy ([#236](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/issues/236)) ([5b4edf3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/commit/5b4edf3))
## [2.6.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v2.6.1...v2.6.2) (2019-08-05)
**Note:** Version bump only for package @pollyjs/persister-rest
## [2.6.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v2.6.0...v2.6.1) (2019-08-01)
**Note:** Version bump only for package @pollyjs/persister-rest
# [2.6.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v2.5.0...v2.6.0) (2019-07-17)
**Note:** Version bump only for package @pollyjs/persister-rest
# [2.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v2.0.0...v2.1.0) (2019-02-04)
**Note:** Version bump only for package @pollyjs/persister-rest
# [2.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v1.4.2...v2.0.0) (2019-01-29)
**Note:** Version bump only for package @pollyjs/persister-rest
## [1.4.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v1.4.0...v1.4.1) (2018-12-13)
**Note:** Version bump only for package @pollyjs/persister-rest
## [1.3.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v1.3.1...v1.3.2) (2018-11-29)
**Note:** Version bump only for package @pollyjs/persister-rest
## [1.3.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/v1.2.0...v1.3.1) (2018-11-28)
**Note:** Version bump only for package @pollyjs/persister-rest
# 1.2.0 (2018-09-16)
**Note:** Version bump only for package @pollyjs/persister-rest
## [1.0.5](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/@pollyjs/persister-rest@1.0.4...@pollyjs/persister-rest@1.0.5) (2018-08-22)
**Note:** Version bump only for package @pollyjs/persister-rest
## [1.0.4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/@pollyjs/persister-rest@1.0.3...@pollyjs/persister-rest@1.0.4) (2018-08-12)
**Note:** Version bump only for package @pollyjs/persister-rest
## [1.0.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/@pollyjs/persister-rest@1.0.2...@pollyjs/persister-rest@1.0.3) (2018-08-12)
**Note:** Version bump only for package @pollyjs/persister-rest
## [1.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/@pollyjs/persister-rest@1.0.1...@pollyjs/persister-rest@1.0.2) (2018-08-09)
**Note:** Version bump only for package @pollyjs/persister-rest
## [1.0.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest/compare/@pollyjs/persister-rest@1.0.0...@pollyjs/persister-rest@1.0.1) (2018-07-26)
**Note:** Version bump only for package @pollyjs/persister-rest
# 1.0.0 (2018-07-20)
**Note:** Version bump only for package @pollyjs/persister-rest
================================================
FILE: packages/@pollyjs/persister-rest/LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Netflix Inc and @pollyjs contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: packages/@pollyjs/persister-rest/README.md
================================================
Record, Replay, and Stub HTTP Interactions
[](https://travis-ci.com/Netflix/pollyjs)
[](https://badge.fury.io/js/%40pollyjs%2Fpersister-rest)
[](http://www.apache.org/licenses/LICENSE-2.0)
The `@pollyjs/persister-rest` package provides a REST API persister that allows
to read and write recordings to and from the file system via a CRUD API hosted
on a server.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/persister-rest -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/persister-rest -D
```
## Documentation
Check out the [REST Persister](https://netflix.github.io/pollyjs/#/persisters/rest)
documentation for more details.
## Usage
```js
import { Polly } from '@pollyjs/core';
import RESTPersister from '@pollyjs/persister-rest';
Polly.register(RESTPersister);
new Polly('', {
persister: 'rest'
});
```
## License
Copyright (c) 2018 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
================================================
FILE: packages/@pollyjs/persister-rest/package.json
================================================
{
"name": "@pollyjs/persister-rest",
"version": "6.0.6",
"description": "REST persister for @pollyjs",
"main": "dist/cjs/pollyjs-persister-rest.js",
"module": "dist/es/pollyjs-persister-rest.js",
"browser": "dist/umd/pollyjs-persister-rest.js",
"types": "types.d.ts",
"files": [
"src",
"dist",
"types.d.ts"
],
"repository": "https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-rest",
"license": "Apache-2.0",
"contributors": [
{
"name": "Jason Mitchell",
"email": "jason.mitchell.w@gmail.com"
},
{
"name": "Offir Golan",
"email": "offirgolan@gmail.com"
}
],
"keywords": [
"polly",
"pollyjs",
"record",
"replay",
"rest",
"persister"
],
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "rollup -c ../../../scripts/rollup/default.config.js",
"test:build": "rollup -c rollup.config.test.js",
"test:build:watch": "rollup -c rollup.config.test.js -w",
"build:watch": "yarn build -w",
"watch-all": "npm-run-all --parallel build:watch test:build:watch"
},
"dependencies": {
"@pollyjs/persister": "^6.0.6",
"@pollyjs/utils": "^6.0.6"
},
"devDependencies": {
"rollup": "^1.14.6"
}
}
================================================
FILE: packages/@pollyjs/persister-rest/rollup.config.test.js
================================================
import createBrowserTestConfig from '../../../scripts/rollup/browser.test.config';
export default createBrowserTestConfig();
================================================
FILE: packages/@pollyjs/persister-rest/src/ajax.js
================================================
const { keys } = Object;
const REQUEST_ASYNC =
!('navigator' in global) || !/PhantomJS/.test(global.navigator.userAgent);
const NativeXMLHttpRequest = global.XMLHttpRequest;
export default function ajax(url, options = {}) {
return new Promise((resolve, reject) => {
const xhr = new NativeXMLHttpRequest();
xhr.open(options.method || 'GET', url, REQUEST_ASYNC);
keys(options.headers || {}).forEach((k) =>
xhr.setRequestHeader(k, options.headers[k])
);
xhr.send(options.body);
if (REQUEST_ASYNC) {
xhr.onreadystatechange = () => {
if (xhr.readyState === NativeXMLHttpRequest.DONE) {
handleResponse(xhr, resolve, reject);
}
};
xhr.onerror = () => reject(xhr);
} else {
handleResponse(xhr, resolve, reject);
}
});
}
function handleResponse(xhr, resolve, reject) {
let body = xhr.response || xhr.responseText;
if (body && typeof body === 'string') {
try {
body = JSON.parse(body);
} catch (e) {
if (!(e instanceof SyntaxError)) {
console.error(e);
}
}
}
return xhr.status >= 200 && xhr.status < 300
? resolve({ body, xhr })
: reject(xhr);
}
================================================
FILE: packages/@pollyjs/persister-rest/src/index.js
================================================
import Persister from '@pollyjs/persister';
import { buildUrl } from '@pollyjs/utils';
import ajax from './ajax';
export default class RestPersister extends Persister {
static get id() {
return 'rest';
}
get defaultOptions() {
return {
host: 'http://localhost:3000',
apiNamespace: '/polly'
};
}
ajax(url, ...args) {
const { host, apiNamespace } = this.options;
return ajax(buildUrl(host, apiNamespace, url), ...args);
}
async onFindRecording(recordingId) {
const response = await this.ajax(`/${encodeURIComponent(recordingId)}`, {
Accept: 'application/json; charset=utf-8'
});
return this._normalize(response);
}
async onSaveRecording(recordingId, data) {
await this.ajax(`/${encodeURIComponent(recordingId)}`, {
method: 'POST',
body: this.stringify(data),
headers: {
'Content-Type': 'application/json; charset=utf-8',
Accept: 'application/json; charset=utf-8'
}
});
}
async onDeleteRecording(recordingId) {
await this.ajax(`/${encodeURIComponent(recordingId)}`, {
method: 'DELETE'
});
}
_normalize({ xhr, body }) {
/**
* 204 - No Content. Polly uses this status code in place of 404
* when interacting with our Rest server to prevent throwing
* request errors in consumer's stdout (console.log)
*/
if (xhr.status === 204) {
/* return null when a record was not found */
return null;
}
return body;
}
}
================================================
FILE: packages/@pollyjs/persister-rest/types.d.ts
================================================
import Persister from '@pollyjs/persister';
export default class RESTPersister extends Persister<{
host?: string;
apiNamespace?: string;
}> {}
================================================
FILE: packages/@pollyjs/utils/CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [6.0.6](https://github.com/netflix/pollyjs/compare/v6.0.5...v6.0.6) (2023-07-20)
**Note:** Version bump only for package @pollyjs/utils
## [6.0.1](https://github.com/netflix/pollyjs/compare/v6.0.0...v6.0.1) (2021-12-06)
### Bug Fixes
* **types:** add types.d.ts to package.files ([#431](https://github.com/netflix/pollyjs/issues/431)) ([113ee89](https://github.com/netflix/pollyjs/commit/113ee898bcf0467c5c48c15b53fc9198e2e91cb1))
# [6.0.0](https://github.com/netflix/pollyjs/compare/v5.2.0...v6.0.0) (2021-11-30)
* fix!: Upgrade url-parse (#426) ([c21ed04](https://github.com/netflix/pollyjs/commit/c21ed048ff9d87a3773458dcfb9758e4fa6582bf)), closes [#426](https://github.com/netflix/pollyjs/issues/426)
* chore!: Upgrade package dependencies (#421) ([dd23334](https://github.com/netflix/pollyjs/commit/dd23334fa9b64248e4c49c3616237bdc2f12f682)), closes [#421](https://github.com/netflix/pollyjs/issues/421)
* feat!: Use base64 instead of hex encoding for binary data (#420) ([6bb9b36](https://github.com/netflix/pollyjs/commit/6bb9b36522d73f9c079735d9006a12376aee39ea)), closes [#420](https://github.com/netflix/pollyjs/issues/420)
* feat(ember)!: Upgrade to ember octane (#415) ([8559ef8](https://github.com/netflix/pollyjs/commit/8559ef8c600aefaec629870eac5f5c8953e18b16)), closes [#415](https://github.com/netflix/pollyjs/issues/415)
### BREAKING CHANGES
* Upgrade url-version to 1.5.0+ to fix CVE-2021-27515. This change could alter the final url generated for a request.
* Recording file name will no longer have trailing dashes
* Use the standard `encoding` field on the generated har file instead of `_isBinary` and use `base64` encoding instead of `hex` to reduce the payload size.
* @pollyjs dependencies have been moved to peer dependencies
## [5.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/v5.1.0...v5.1.1) (2021-06-02)
### Bug Fixes
* Handle failed arraybuffer instanceof checks ([#393](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/issues/393)) ([247be0a](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/247be0a))
# [5.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/v4.3.0...v5.0.0) (2020-06-23)
### Features
* Remove deprecated Persister.name and Adapter.name ([#343](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/issues/343)) ([1223ba0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/1223ba0))
### BREAKING CHANGES
* Persister.name and Adapter.name have been replaced with Persister.id and Adapter.id
# [4.3.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/v4.2.1...v4.3.0) (2020-05-18)
### Features
* **adapter-xhr:** Add support for handling binary data ([#333](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/issues/333)) ([48ea1d7](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/48ea1d7))
# [4.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/v4.0.4...v4.1.0) (2020-04-23)
### Bug Fixes
* Legacy persisters and adapters should register ([#325](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/issues/325)) ([8fd4d19](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/8fd4d19))
## [4.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/v4.0.1...v4.0.2) (2020-01-29)
### Bug Fixes
* **core:** Strict null query param handling ([#302](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/issues/302)) ([5cf70aa](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/5cf70aa))
# [4.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/v3.0.2...v4.0.0) (2020-01-13)
**Note:** Version bump only for package @pollyjs/utils
# [3.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/v2.7.0...v3.0.0) (2019-12-18)
**Note:** Version bump only for package @pollyjs/utils
## [2.6.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/v2.6.2...v2.6.3) (2019-09-30)
### Bug Fixes
* use watch strategy ([#236](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/issues/236)) ([5b4edf3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/5b4edf3))
# [2.6.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/v2.5.0...v2.6.0) (2019-07-17)
### Features
* PollyError and improved adapter error handling ([#234](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/issues/234)) ([23a2127](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/23a2127))
# [2.1.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/v2.0.0...v2.1.0) (2019-02-04)
**Note:** Version bump only for package @pollyjs/utils
# [2.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/v1.4.2...v2.0.0) (2019-01-29)
### Features
* Make PollyRequest.respond accept a response object ([#168](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/utils/issues/168)) ([5b07b26](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/5b07b26))
* feat(adapter-node-http): Use `nock` under the hood instead of custom implementation (#166) ([62374f4](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/62374f4)), closes [#166](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/issues/166)
### BREAKING CHANGES
* The node-http adapter no longer accepts the `transports` option
* Any adapters calling `pollyRequest.respond` should pass it a response object instead of the previous 3 arguments (statusCode, headers, body).
## [1.4.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/v1.4.0...v1.4.1) (2018-12-13)
### Bug Fixes
* **utils:** Support arrays & nested objects in query params ([#148](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/utils/issues/148)) ([7e846b0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/7e846b0))
## [1.3.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/v1.3.1...v1.3.2) (2018-11-29)
**Note:** Version bump only for package @pollyjs/utils
## [1.3.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/v1.2.0...v1.3.1) (2018-11-28)
### Features
* **core:** Support custom functions in matchRequestsBy config options ([#138](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/utils/issues/138)) ([626a84c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/626a84c))
* Add an onIdentifyRequest hook to allow adapter level serialization ([#140](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/utils/issues/140)) ([548002c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/548002c))
# 1.2.0 (2018-09-16)
### Bug Fixes
* **adapter-puppeteer:** Do not intercept CORS preflight requests ([#90](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/utils/issues/90)) ([53ad433](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/53ad433))
### Features
* Convert recordings to be HAR compliant ([#45](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/utils/issues/45)) ([e622640](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/e622640))
* Custom persister support ([8bb313c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/8bb313c))
* Node File System Persister ([#61](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/utils/issues/61)) ([0a0eeca](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/0a0eeca))
* Puppeteer Adapter ([#64](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/utils/issues/64)) ([f902c6d](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/f902c6d))
### BREAKING CHANGES
* Recordings now produce HAR compliant json. Please delete existing recordings.
## [1.0.3](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/@pollyjs/utils@1.0.2...@pollyjs/utils@1.0.3) (2018-08-22)
**Note:** Version bump only for package @pollyjs/utils
## [1.0.2](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/@pollyjs/utils@1.0.1...@pollyjs/utils@1.0.2) (2018-08-12)
**Note:** Version bump only for package @pollyjs/utils
## [1.0.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/@pollyjs/utils@1.0.0...@pollyjs/utils@1.0.1) (2018-08-12)
### Bug Fixes
* **adapter-puppeteer:** Do not intercept CORS preflight requests ([#90](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/utils/issues/90)) ([53ad433](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/53ad433))
# [1.0.0](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/@pollyjs/utils@0.1.1...@pollyjs/utils@1.0.0) (2018-07-20)
### Features
* Convert recordings to be HAR compliant ([#45](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/utils/issues/45)) ([e622640](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/e622640))
* Node File System Persister ([#61](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/utils/issues/61)) ([0a0eeca](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/0a0eeca))
* Puppeteer Adapter ([#64](https://github.com/netflix/pollyjs/tree/master/packages/[@pollyjs](https://github.com/pollyjs)/utils/issues/64)) ([f902c6d](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/f902c6d))
### BREAKING CHANGES
* Recordings now produce HAR compliant json. Please delete existing recordings.
## [0.1.1](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/compare/@pollyjs/utils@0.1.0...@pollyjs/utils@0.1.1) (2018-06-27)
**Note:** Version bump only for package @pollyjs/utils
# 0.1.0 (2018-06-16)
### Features
* Custom persister support ([8bb313c](https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils/commit/8bb313c))
================================================
FILE: packages/@pollyjs/utils/LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 Netflix Inc and @pollyjs contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: packages/@pollyjs/utils/README.md
================================================
Record, Replay, and Stub HTTP Interactions
[](https://travis-ci.com/Netflix/pollyjs)
[](https://badge.fury.io/js/%40pollyjs%2Futils)
[](http://www.apache.org/licenses/LICENSE-2.0)
The `@pollyjs/utils` package provides utilities and constants for other @pollyjs packages.
## Installation
_Note that you must have node (and npm) installed._
```bash
npm install @pollyjs/utils -D
```
If you want to install it with [yarn](https://yarnpkg.com):
```bash
yarn add @pollyjs/utils -D
```
## License
Copyright (c) 2018 Netflix, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
================================================
FILE: packages/@pollyjs/utils/package.json
================================================
{
"name": "@pollyjs/utils",
"version": "6.0.6",
"description": "Shared utilities and constants between @pollyjs packages",
"main": "dist/cjs/pollyjs-utils.js",
"module": "dist/es/pollyjs-utils.js",
"browser": "dist/umd/pollyjs-utils.js",
"types": "types.d.ts",
"files": [
"src",
"dist",
"types.d.ts"
],
"repository": "https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils",
"scripts": {
"build": "rollup -c ../../../scripts/rollup/default.config.js",
"test:build": "rollup -c rollup.config.test.js",
"test:build:watch": "rollup -c rollup.config.test.js -w",
"build:watch": "yarn build -w",
"watch-all": "npm-run-all --parallel build:watch test:build:watch"
},
"keywords": [
"polly",
"pollyjs",
"utils"
],
"publishConfig": {
"access": "public"
},
"contributors": [
{
"name": "Jason Mitchell",
"email": "jason.mitchell.w@gmail.com"
},
{
"name": "Offir Golan",
"email": "offirgolan@gmail.com"
}
],
"license": "Apache-2.0",
"dependencies": {
"qs": "^6.10.1",
"url-parse": "^1.5.3"
},
"devDependencies": {
"rollup": "^1.14.6"
}
}
================================================
FILE: packages/@pollyjs/utils/rollup.config.test.js
================================================
import createNodeTestConfig from '../../../scripts/rollup/node.test.config';
import createBrowserTestConfig from '../../../scripts/rollup/browser.test.config';
export default [createNodeTestConfig(), createBrowserTestConfig()];
================================================
FILE: packages/@pollyjs/utils/src/constants/actions.js
================================================
export default {
RECORD: 'record',
REPLAY: 'replay',
INTERCEPT: 'intercept',
PASSTHROUGH: 'passthrough'
};
================================================
FILE: packages/@pollyjs/utils/src/constants/expiry-strategies.js
================================================
export default {
RECORD: 'record',
WARN: 'warn',
ERROR: 'error'
};
================================================
FILE: packages/@pollyjs/utils/src/constants/http-methods.js
================================================
export default [
'GET',
'PUT',
'POST',
'DELETE',
'PATCH',
'MERGE',
'HEAD',
'OPTIONS'
];
================================================
FILE: packages/@pollyjs/utils/src/constants/http-status-codes.js
================================================
export default {
100: 'Continue',
101: 'Switching Protocols',
200: 'OK',
201: 'Created',
202: 'Accepted',
203: 'Non-Authoritative Information',
204: 'No Content',
205: 'Reset Content',
206: 'Partial Content',
207: 'Multi-Status',
300: 'Multiple Choice',
301: 'Moved Permanently',
302: 'Found',
303: 'See Other',
304: 'Not Modified',
305: 'Use Proxy',
307: 'Temporary Redirect',
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
409: 'Conflict',
410: 'Gone',
411: 'Length Required',
412: 'Precondition Failed',
413: 'Request Entity Too Large',
414: 'Request-URI Too Long',
415: 'Unsupported Media Type',
416: 'Requested Range Not Satisfiable',
417: 'Expectation Failed',
422: 'Unprocessable Entity',
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Timeout',
505: 'HTTP Version Not Supported'
};
================================================
FILE: packages/@pollyjs/utils/src/constants/modes.js
================================================
export default {
RECORD: 'record',
REPLAY: 'replay',
PASSTHROUGH: 'passthrough',
STOPPED: 'stopped'
};
================================================
FILE: packages/@pollyjs/utils/src/index.js
================================================
export { default as MODES } from './constants/modes';
export { default as ACTIONS } from './constants/actions';
export { default as HTTP_METHODS } from './constants/http-methods';
export { default as HTTP_STATUS_CODES } from './constants/http-status-codes';
export { default as EXPIRY_STRATEGIES } from './constants/expiry-strategies';
export { default as assert } from './utils/assert';
export { default as timeout } from './utils/timeout';
export { default as timestamp } from './utils/timestamp';
export { default as buildUrl } from './utils/build-url';
export { default as PollyError } from './utils/polly-error';
export { default as Serializers } from './utils/serializers';
export { default as URL } from './utils/url';
export { default as isBufferUtf8Representable } from './utils/is-buffer-utf8-representable';
export { default as cloneArrayBuffer } from './utils/clone-arraybuffer';
================================================
FILE: packages/@pollyjs/utils/src/utils/assert.js
================================================
import PollyError from './polly-error';
export default function (msg, condition) {
if (!condition) {
throw new PollyError(msg);
}
}
================================================
FILE: packages/@pollyjs/utils/src/utils/build-url.js
================================================
import URL from './url';
export default function buildUrl(...paths) {
const url = new URL(
paths
.map((p) => p && (p + '').trim()) // Trim each string
.filter(Boolean) // Remove empty strings or other falsy paths
.join('/')
);
// Replace 2+ consecutive slashes with 1. (e.g. `///` --> `/`)
url.set('pathname', url.pathname.replace(/\/{2,}/g, '/'));
return url.href;
}
================================================
FILE: packages/@pollyjs/utils/src/utils/clone-arraybuffer.js
================================================
/**
* Clone an array buffer
*
* @param {ArrayBuffer} arrayBuffer
*/
export default function cloneArrayBuffer(arrayBuffer) {
const clonedArrayBuffer = new ArrayBuffer(arrayBuffer.byteLength);
new Uint8Array(clonedArrayBuffer).set(new Uint8Array(arrayBuffer));
return clonedArrayBuffer;
}
================================================
FILE: packages/@pollyjs/utils/src/utils/is-buffer-utf8-representable.js
================================================
import { Buffer } from 'buffer';
/**
* Determine if the given buffer is utf8.
* @param {Buffer} buffer
*/
export default function isBufferUtf8Representable(buffer) {
const utfEncodedBuffer = buffer.toString('utf8');
const reconstructedBuffer = Buffer.from(utfEncodedBuffer, 'utf8');
return reconstructedBuffer.equals(buffer);
}
================================================
FILE: packages/@pollyjs/utils/src/utils/polly-error.js
================================================
export default class PollyError extends Error {
constructor(message, ...args) {
super(`[Polly] ${message}`, ...args);
// Maintains proper stack trace for where our error was thrown (only available on V8)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, PollyError);
}
this.name = 'PollyError';
}
}
================================================
FILE: packages/@pollyjs/utils/src/utils/serializers/blob.js
================================================
export const supportsBlob = (() => {
try {
return !!new Blob();
} catch (e) {
return false;
}
})();
export function readBlob(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onend = reject;
reader.onabort = reject;
reader.onload = () => resolve(reader.result);
reader.readAsDataURL(new Blob([blob], { type: blob.type }));
});
}
export async function serialize(body) {
if (supportsBlob && body instanceof Blob) {
return await readBlob(body);
}
return body;
}
================================================
FILE: packages/@pollyjs/utils/src/utils/serializers/buffer.js
================================================
/* eslint-env node */
export const supportsBuffer = typeof Buffer !== 'undefined';
export const supportsArrayBuffer = typeof ArrayBuffer !== 'undefined';
export function serialize(body) {
if (supportsBuffer && body) {
let buffer;
if (Buffer.isBuffer(body)) {
buffer = body;
} else if (Array.isArray(body) && body.some((c) => Buffer.isBuffer(c))) {
// Body is a chunked array
const chunks = body.map((c) => Buffer.from(c));
buffer = Buffer.concat(chunks);
} else if (`${body}` === '[object ArrayBuffer]') {
buffer = Buffer.from(body);
} else if (supportsArrayBuffer && ArrayBuffer.isView(body)) {
buffer = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
}
if (Buffer.isBuffer(buffer)) {
return buffer.toString('base64');
}
}
return body;
}
================================================
FILE: packages/@pollyjs/utils/src/utils/serializers/form-data.js
================================================
import { supportsBlob, readBlob } from './blob';
export const supportsFormData = typeof FormData !== 'undefined';
export async function serialize(body) {
if (supportsFormData && body instanceof FormData) {
const data = [];
for (const [key, value] of body.entries()) {
if (supportsBlob && value instanceof Blob) {
const blobContent = await readBlob(value);
data.push(`${key}=${blobContent}`);
} else {
data.push(`${key}=${value}`);
}
}
return data.join('\r\n');
}
return body;
}
================================================
FILE: packages/@pollyjs/utils/src/utils/serializers/index.js
================================================
import { serialize as blob } from './blob';
import { serialize as formData } from './form-data';
import { serialize as buffer } from './buffer';
export default { blob, formData, buffer };
================================================
FILE: packages/@pollyjs/utils/src/utils/timeout.js
================================================
export default function timeout(time) {
const ms = parseInt(time, 10);
return new Promise((resolve) =>
ms > 0 ? setTimeout(resolve, ms) : resolve()
);
}
================================================
FILE: packages/@pollyjs/utils/src/utils/timestamp.js
================================================
export default function timestamp() {
return new Date().toISOString();
}
================================================
FILE: packages/@pollyjs/utils/src/utils/url.js
================================================
import URLParse from 'url-parse';
import qs from 'qs';
const ARRAY_FORMAT = Symbol();
const INDICES_REGEX = /\[\d+\]$/;
const BRACKETS_REGEX = /\[\]$/;
function parseQuery(query, options) {
return qs.parse(query, {
plainObjects: true,
ignoreQueryPrefix: true,
strictNullHandling: true,
...options
});
}
function stringifyQuery(obj, options = {}) {
return qs.stringify(obj, {
addQueryPrefix: true,
strictNullHandling: true,
...options
});
}
/**
* Given a query string, determine the array format used. Returns `undefined`
* if one cannot be determined.
*
* @param {String} query
* @returns {String | undefined}
*/
function arrayFormat(query) {
const keys = (query || '')
.replace('?', '')
.split('&')
.map((str) => decodeURIComponent(str.split('=')[0]));
for (const key of keys) {
if (INDICES_REGEX.test(key)) {
// a[0]=b&a[1]=c
return 'indices';
} else if (BRACKETS_REGEX.test(key)) {
// a[]=b&a[]=c
return 'brackets';
}
}
// Look to see if any key has a duplicate
const hasDuplicate = keys.some((key, index) => keys.indexOf(key) !== index);
if (hasDuplicate) {
// 'a=b&a=c'
return 'repeat';
}
}
/**
* An extended url-parse class that uses `qs` instead of the default
* `querystringify` to support array and nested object query param strings.
*/
export default class URL extends URLParse {
constructor(url, parse) {
// Construct the url with an un-parsed querystring
super(url);
if (parse) {
// If we want the querystring to be parsed, use this.set('query', query)
// as it will always parse the string. If there is no initial querystring
// pass an object which will act as the parsed query.
this.set('query', this.query || {});
}
}
/**
* Override set for `query` so we can pass it our custom parser.
* https://github.com/unshiftio/url-parse/blob/1.4.4/index.js#L314-L316
*
* @override
*/
set(part, value, fn) {
if (part === 'query') {
if (value && typeof value === 'string') {
// Save the array format used so when we stringify it,
// we can use the correct format.
this[ARRAY_FORMAT] = arrayFormat(value) || this[ARRAY_FORMAT];
}
return super.set(part, value, parseQuery);
}
return super.set(part, value, fn);
}
/**
* Override toString so we can pass it our custom query stringify method.
* https://github.com/unshiftio/url-parse/blob/1.4.4/index.js#L414
*
* @override
*/
toString() {
return super.toString((obj) =>
stringifyQuery(obj, { arrayFormat: this[ARRAY_FORMAT] })
);
}
}
================================================
FILE: packages/@pollyjs/utils/tests/browser/unit/utils/serializers/blob.js
================================================
import File from '@pollyjs-tests/helpers/file';
import { serialize } from '../../../../../src/utils/serializers/blob';
import serializerTests from '../../../../serializer-tests';
describe('Unit | Utils | Serializers | blob', function () {
serializerTests(serialize);
it('should noop if Blob is not found', function () {
const Blob = Blob;
const blob = new Blob(['blob'], { type: 'text/plain' });
global.Blob = undefined;
expect(serialize(blob)).to.be.equal(blob);
global.Blob = Blob;
});
it('should handle blobs', async function () {
expect(
await serialize(new Blob(['blob'], { type: 'text/plain' }))
).to.equal(`data:text/plain;base64,${btoa('blob')}`);
});
it('should handle files', async function () {
expect(
await serialize(
new File(['file'], 'file.txt', {
type: 'text/plain'
})
)
).to.equal(`data:text/plain;base64,${btoa('file')}`);
});
});
================================================
FILE: packages/@pollyjs/utils/tests/browser/unit/utils/serializers/form-data.js
================================================
import File from '@pollyjs-tests/helpers/file';
import { serialize } from '../../../../../src/utils/serializers/form-data';
import serializerTests from '../../../../serializer-tests';
describe('Unit | Utils | Serializers | form-data', function () {
serializerTests(serialize);
it('should noop if FormData is not found', function () {
const FormData = FormData;
const formData = new FormData();
global.FormData = undefined;
expect(serialize(formData)).to.be.equal(formData);
global.FormData = FormData;
});
it('should handle form-data', async function () {
const formData = new FormData();
formData.append('string', 'string');
formData.append('array', [1, 2]);
formData.append('blob', new Blob(['blob'], { type: 'text/plain' }));
formData.append(
'file',
new File(['file'], 'file.txt', { type: 'text/plain' })
);
const data = await serialize(formData);
expect(data).to.include('string=string');
expect(data).to.include('array=1,2');
expect(data).to.include(`blob=data:text/plain;base64,${btoa('blob')}`);
expect(data).to.include(`file=data:text/plain;base64,${btoa('file')}`);
});
});
================================================
FILE: packages/@pollyjs/utils/tests/node/unit/utils/serializers/buffer.js
================================================
/* eslint-env node */
import { serialize } from '../../../../../src/utils/serializers/buffer';
import serializerTests from '../../../../serializer-tests';
describe('Unit | Utils | Serializers | buffer', function () {
serializerTests(serialize);
it('should noop if Buffer is not found', function () {
const Buffer = Buffer;
const buffer = Buffer.from('buffer');
global.Buffer = undefined;
expect(serialize(buffer)).to.be.equal(buffer);
global.Buffer = Buffer;
});
it('should handle buffers', function () {
const buffer = Buffer.from('buffer');
expect(serialize(buffer)).to.equal(buffer.toString('base64'));
});
it('should handle array of buffers', function () {
const buffers = [Buffer.from('b1'), Buffer.from('b2')];
expect(serialize(buffers)).to.include(buffers[0].toString('base64'));
expect(serialize(buffers)).to.include(buffers[1].toString('base64'));
});
it('should handle a mixed array of buffers and strings', function () {
const buffers = [Buffer.from('b1'), 's1'];
expect(serialize(buffers)).to.include(buffers[0].toString('base64'));
expect(serialize(buffers)).to.include(
Buffer.from(buffers[1]).toString('base64')
);
});
it('should handle an ArrayBuffer', function () {
const buffer = new ArrayBuffer(8);
expect(serialize(buffer)).to.equal(Buffer.from(buffer).toString('base64'));
});
it('should handle an ArrayBufferView', function () {
const buffer = new Uint8Array(8);
expect(serialize(buffer)).to.equal(
Buffer.from(buffer, buffer.byteOffset, buffer.byteLength).toString(
'base64'
)
);
});
});
================================================
FILE: packages/@pollyjs/utils/tests/serializer-tests.js
================================================
export default function serializerTests(serialize) {
it('should exist', function () {
expect(serialize).to.be.a('function');
});
it('should handle empty argument', async function () {
expect(await serialize()).to.be.undefined;
expect(await serialize(null)).to.be.null;
});
it('should handle strings', async function () {
expect(await serialize('')).to.be.equal('');
expect(await serialize('foo')).to.be.equal('foo');
});
}
================================================
FILE: packages/@pollyjs/utils/tests/unit/utils/assert-test.js
================================================
import assert from '../../../src/utils/assert';
import PollyError from '../../../src/utils/polly-error';
describe('Unit | Utils | assert', function () {
it('should exist', function () {
expect(assert).to.be.a('function');
});
it('should throw with a false condition', function () {
expect(() => assert('Test', false)).to.throw(PollyError, /Test/);
});
it('should throw without a condition', function () {
expect(() => assert('Test')).to.throw(PollyError, /Test/);
});
it('should not throw with a true condition', function () {
expect(() => assert('Test', true)).to.not.throw();
});
});
================================================
FILE: packages/@pollyjs/utils/tests/unit/utils/build-url-test.js
================================================
import buildUrl from '../../../src/utils/build-url';
const origin = (global.location && global.location.origin) || '';
describe('Unit | Utils | buildUrl', function () {
it('should exist', function () {
expect(buildUrl).to.be.a('function');
});
it('should remove consecutive slashes', function () {
expect(buildUrl('http://foo.com///bar/baz/')).to.equal(
'http://foo.com/bar/baz/'
);
});
it('should remove empty fragments of the url', function () {
expect(buildUrl('http://foo///bar/////baz')).to.equal('http://foo/bar/baz');
});
it('should remove empty fragments of the url', function () {
expect(buildUrl('/foo/bar/baz')).to.equal(`${origin}/foo/bar/baz`);
});
it('should concat multiple paths together', function () {
expect(buildUrl('/foo', '/bar', null, undefined, false, '/baz')).to.equal(
`${origin}/foo/bar/baz`
);
});
});
================================================
FILE: packages/@pollyjs/utils/tests/unit/utils/polly-error-test.js
================================================
import PollyError from '../../../src/utils/polly-error';
describe('Unit | Utils | PollyError', function () {
it('should exist', function () {
expect(PollyError).to.be.a('function');
});
it('should set the name to PollyError', function () {
const error = new PollyError('Test');
expect(error.name).to.equal('PollyError');
});
it('should prefix the message with [Polly]', function () {
const error = new PollyError('Test');
expect(error.message).to.equal('[Polly] Test');
});
});
================================================
FILE: packages/@pollyjs/utils/tests/unit/utils/timeout-test.js
================================================
import timeout from '../../../src/utils/timeout';
describe('Unit | Utils | timeout', function () {
it('should exist', function () {
expect(timeout).to.be.a('function');
});
it('should return a promise', async function () {
const promise = timeout(10);
expect(promise).to.be.a('promise');
await promise;
});
it('should timeout for the correct amount of ms', async function () {
this.timeout(110);
const promise = timeout(100);
let resolved = false;
promise.then(() => (resolved = true));
setTimeout(() => expect(resolved).to.be.false, 50);
setTimeout(() => expect(resolved).to.be.true, 101);
await promise;
});
});
================================================
FILE: packages/@pollyjs/utils/tests/unit/utils/timestamp-test.js
================================================
import timestamp from '../../../src/utils/timestamp';
describe('Unit | Utils | timestamp', function () {
it('should exist', function () {
expect(timestamp).to.be.a('function');
});
it('should return a string', function () {
expect(timestamp()).to.be.a('string');
});
});
================================================
FILE: packages/@pollyjs/utils/tests/unit/utils/url-test.js
================================================
import URL from '../../../src/utils/url';
const encode = encodeURIComponent;
const decode = decodeURIComponent;
describe('Unit | Utils | URL', function () {
it('should exist', function () {
expect(URL).to.be.a('function');
});
it('should work', function () {
expect(new URL('http://netflix.com/').href).to.equal('http://netflix.com/');
});
it('should should not parse the query string by default', function () {
expect(new URL('http://netflix.com/?foo=bar').query).to.equal('?foo=bar');
});
it('should correctly parse query params', function () {
[
['', {}],
['a&b=', { a: null, b: '' }],
['foo=bar', { foo: 'bar' }],
['a[]=1&a[]=2', { a: ['1', '2'] }],
['a[1]=1&a[0]=2', { a: ['2', '1'] }],
['a=1&a=2', { a: ['1', '2'] }],
['foo[bar][baz]=1', { foo: { bar: { baz: '1' } } }]
].forEach(([query, obj]) => {
expect(new URL(`http://foo.bar/?${query}`, true).query).to.deep.equal(
obj
);
});
});
it('should correctly stringify query params', function () {
[
// Query string will be undefined but we decode it in the assertion
[{}, decode(undefined)],
[{ a: null, b: '' }, 'a&b='],
[{ foo: 'bar' }, 'foo=bar'],
[{ a: ['1', '2'] }, 'a[0]=1&a[1]=2'],
[{ foo: { bar: { baz: '1' } } }, 'foo[bar][baz]=1']
].forEach(([obj, query]) => {
const url = new URL('http://foo.bar', true);
url.set('query', obj);
expect(decode(url.href.split('?')[1])).to.equal(query);
expect(decode(url.toString().split('?')[1])).to.equal(query);
});
});
it('should correctly detect original array formats', function () {
[
'a[0]=1&a[1]=2',
`${encode('a[0]')}=1&${encode('a[1]')}=2`,
'a[]=1&a[]=2',
`${encode('a[]')}=1&${encode('a[]')}=2`,
'a=1&a=2'
].forEach((query) => {
const url = new URL(`http://foo.bar/?${query}`, true);
expect(decode(url.href.split('?')[1])).to.equal(decode(query));
expect(decode(url.toString().split('?')[1])).to.equal(decode(query));
});
});
it('should correctly handle changes in array formats', function () {
const url = new URL(`http://foo.bar`, true);
['a[0]=1&a[1]=2', 'a[]=1&a[]=2', 'a=1&a=2'].forEach((query) => {
url.set('query', query);
expect(decode(url.href.split('?')[1])).to.equal(query);
expect(decode(url.toString().split('?')[1])).to.equal(query);
});
});
});
================================================
FILE: packages/@pollyjs/utils/types.d.ts
================================================
export enum MODES {
RECORD = 'record',
REPLAY = 'replay',
PASSTHROUGH = 'passthrough',
STOPPED = 'stopped'
}
export enum ACTIONS {
RECORD = 'record',
REPLAY = 'replay',
INTERCEPT = 'intercept',
PASSTHROUGH = 'passthrough'
}
export enum EXPIRY_STRATEGIES {
RECORD = 'record',
WARN = 'warn',
ERROR = 'error'
}
================================================
FILE: scripts/require-clean-work-tree.sh
================================================
#!/bin/bash
require_clean_work_tree () {
git rev-parse --verify HEAD >/dev/null || exit 1
git update-index -q --ignore-submodules --refresh
# Disallow unstaged changes in the working tree
if ! git diff-files --quiet --ignore-submodules
then
echo "There are unstaged changes."
git diff-files --name-status -r --ignore-submodules --
exit 1
fi
# Disallow uncommitted changes in the index
if ! git diff-index --cached --quiet --ignore-submodules HEAD --
then
echo "The index contains uncommitted changes."
git diff-index --cached --name-status -r --ignore-submodules HEAD --
exit 1
fi
}
require_clean_work_tree
================================================
FILE: scripts/require-test-build.sh
================================================
#!/usr/bin/env bash
if [ ! -f "./packages/@pollyjs/node-server/dist/cjs/pollyjs-node-server.js" ]; then
echo "Test server build not found. Run either '$ yarn watch' or '$ yarn build:server'"
exit 1
fi
if [ ! -f "./packages/@pollyjs/core/dist/cjs/pollyjs-core.js" ]; then
echo "Build not found. Run either '$ yarn watch' or '$ yarn build'"
exit 1
fi
if [ ! -f "./packages/@pollyjs/core/build/node/test-bundle.cjs.js" ]; then
echo "Test build not found. Run either '$ yarn watch' or '$ yarn test:build'"
exit 1
fi
================================================
FILE: scripts/rollup/browser.config.js
================================================
import deepmerge from 'deepmerge';
import json from 'rollup-plugin-json';
import alias from 'rollup-plugin-alias';
import babel from 'rollup-plugin-babel';
import { terser } from 'rollup-plugin-terser';
import commonjs from 'rollup-plugin-commonjs';
import { rollup as lerna } from 'lerna-alias';
import resolve from 'rollup-plugin-node-resolve';
import globals from 'rollup-plugin-node-globals';
import builtins from 'rollup-plugin-node-builtins';
import { input, output, pkg, minify } from './utils';
export default function createBrowserConfig(options = {}, targets) {
return deepmerge(
{
input,
output: deepmerge(output('umd'), { name: pkg.name }),
plugins: [
alias(lerna()),
json(),
resolve({ browser: true, preferBuiltins: true }),
commonjs(),
babel({
babelrc: false,
runtimeHelpers: true,
exclude: ['../../../node_modules/**'],
presets: [
[
'@babel/preset-env',
{
modules: false,
targets: targets || {
browsers: ['last 2 versions']
}
}
]
],
plugins: [
'@babel/plugin-external-helpers',
['@babel/plugin-transform-runtime', { corejs: 2 }],
['@babel/plugin-proposal-object-rest-spread', { useBuiltIns: true }]
]
}),
globals(),
builtins(),
minify && terser()
],
onwarn(message) {
/* nise uses eval for strings within native fns setTimeout('alert("foo")', 10) */
if (/nise/.test(message) && /eval/.test(message)) {
return;
}
console.error(message);
}
},
options
);
}
================================================
FILE: scripts/rollup/browser.test.config.js
================================================
import deepmerge from 'deepmerge';
import multiEntry from 'rollup-plugin-multi-entry';
import alias from 'rollup-plugin-alias';
import createBrowserConfig from './browser.config';
import { pkg, testsPath } from './utils';
export default function createBrowserTestConfig(options = {}) {
return deepmerge(
createBrowserConfig(
{
input: 'tests/!(node|jest)/**/*-test.js',
output: {
format: 'es',
name: `${pkg.name}-tests`,
file: `./build/browser/test-bundle.es.js`,
intro: `
'use strict'
describe('${pkg.name}', function() {
`,
outro: '});'
},
plugins: [alias({ '@pollyjs-tests': testsPath }), multiEntry()]
},
/* target override */
{
browsers: ['last 2 Chrome versions']
}
),
options
);
}
================================================
FILE: scripts/rollup/default.config.js
================================================
import createBrowserConfig from './browser.config';
import createNodeConfig from './node.config';
export default [createBrowserConfig(), createNodeConfig()];
================================================
FILE: scripts/rollup/jest.test.config.js
================================================
import deepmerge from 'deepmerge';
import createNodeTestConfig from './node.test.config';
import { pkg } from './utils';
export default function createJestTestConfig(options = {}) {
return deepmerge(
createNodeTestConfig({
input: 'tests/jest/**/*-test.js',
output: {
format: 'cjs',
name: `${pkg.name}-tests`,
file: `./build/jest/test-bundle.cjs.js`,
intro: `describe('${pkg.name}', function() {`,
outro: '});'
}
}),
options
);
}
================================================
FILE: scripts/rollup/node.config.js
================================================
import deepmerge from 'deepmerge';
import json from 'rollup-plugin-json';
import babel from 'rollup-plugin-babel';
import { terser } from 'rollup-plugin-terser';
import commonjs from 'rollup-plugin-commonjs';
import resolve from 'rollup-plugin-node-resolve';
import { input, output, pkg, minify } from './utils';
const external = Object.keys(pkg.dependencies || {});
export default function createNodeConfig(options = {}) {
return deepmerge(
{
input,
output: [output('cjs'), output('es')],
external,
plugins: [
json(),
resolve({ preferBuiltins: true }),
commonjs(),
babel({
babelrc: false,
runtimeHelpers: true,
exclude: ['../../../node_modules/**'],
presets: [
[
'@babel/preset-env',
{
modules: false,
targets: {
node: '12.0.0'
}
}
]
],
plugins: [
'@babel/plugin-external-helpers',
['@babel/plugin-transform-runtime', { corejs: 2 }],
['@babel/plugin-proposal-object-rest-spread', { useBuiltIns: true }]
]
}),
minify && terser()
]
},
options
);
}
================================================
FILE: scripts/rollup/node.test.config.js
================================================
import deepmerge from 'deepmerge';
import multiEntry from 'rollup-plugin-multi-entry';
import alias from 'rollup-plugin-alias';
import createNodeConfig from './node.config';
import { pkg, testsPath } from './utils';
const pollyDependencies = Object.keys(pkg.devDependencies || {}).filter((d) =>
d.startsWith('@pollyjs')
);
export default function createNodeTestConfig(options = {}) {
return deepmerge(
createNodeConfig({
input: 'tests/!(browser|jest)/**/*-test.js',
output: {
format: 'cjs',
name: `${pkg.name}-tests`,
file: `./build/node/test-bundle.cjs.js`,
intro: `describe('${pkg.name}', function() {`,
outro: '});'
},
plugins: [alias({ '@pollyjs-tests': testsPath }), multiEntry()],
external: [...pollyDependencies, 'node-fetch', 'chai']
}),
options
);
}
================================================
FILE: scripts/rollup/utils.js
================================================
/* globals require process */
import path from 'path';
export const pkg = require(path.resolve(process.cwd(), './package.json'));
export const production = process.env.NODE_ENV === 'production';
export const minify = process.env.MINIFY === 'true';
const banner = `/**
* ${pkg.name} v${pkg.version}
*
* https://github.com/netflix/pollyjs
*
* Released under the ${pkg.license} License.
*/`;
export const input = './src/index.js';
export const output = (format) => {
return {
format,
file: `./dist/${format}/${pkg.name.replace('@pollyjs/', 'pollyjs-')}.${
minify ? 'min.js' : 'js'
}`,
sourcemap: production,
banner
};
};
export const testsPath = path.resolve(process.cwd(), '../../../tests');
================================================
FILE: testem.js
================================================
/* eslint-env node */
const attachMiddleware = require('./tests/middleware');
module.exports = {
port: 4000,
fail_on_zero_tests: true,
test_page: 'tests/index.mustache',
launch_in_ci: ['Chrome', 'Node', 'Jest', 'Ember', 'ESLint'],
launch_in_dev: ['Chrome', 'Node', 'Jest', 'Ember', 'ESLint'],
watch_files: [
'./scripts/rollup/*',
'./packages/@pollyjs/*/build/**/*',
'./packages/@pollyjs/*/dist/**/*'
],
serve_files: ['./packages/@pollyjs/*/build/browser/*.js'],
browser_args: {
Chrome: {
ci: [
// --no-sandbox is needed when running Chrome inside a container
process.env.CI ? '--no-sandbox' : null,
'--headless',
'--disable-gpu',
'--disable-dev-shm-usage',
'--disable-software-rasterizer',
'--mute-audio',
'--remote-debugging-port=0',
'--window-size=1440,900'
].filter(Boolean)
}
},
middleware: [attachMiddleware],
launchers: {
'Node:debug': {
command: 'mocha --inspect-brk'
},
Node: {
command: 'mocha --reporter tap',
protocol: 'tap'
},
Jest: {
command: 'jest',
protocol: 'tap'
},
Ember: {
command: 'yarn workspace @pollyjs/ember run test',
protocol: 'tap'
},
ESLint: {
command: 'yarn lint --format tap',
protocol: 'tap'
}
}
};
================================================
FILE: tests/helpers/file.js
================================================
/**
* Special thanks to the FormData project.
* Full credit: https://github.com/jimmywarting/FormData (MIT)
*/
const { defineProperties, defineProperty } = Object;
const stringTag = Symbol && Symbol.toStringTag;
let _File;
try {
new File([], '');
_File = File;
} catch (e) {
/**
* @see http://www.w3.org/TR/FileAPI/#dfn-file
* @param {!Array=} chunks
* @param {string=} filename
* @param {{type: (string|undefined), lastModified: (number|undefined)}=}
* opts
* @constructor
* @extends {Blob}
*/
_File = function File(chunks, filename, opts = {}) {
const _this = new Blob(chunks, opts);
const modified =
opts && opts.lastModified !== undefined
? new Date(opts.lastModified)
: new Date();
defineProperties(_this, {
name: {
value: filename
},
lastModifiedDate: {
value: modified
},
lastModified: {
value: +modified
},
toString: {
value() {
return '[object File]';
}
}
});
if (stringTag) {
defineProperty(_this, Symbol.toStringTag, {
value: 'File'
});
}
return _this;
};
}
export default _File;
================================================
FILE: tests/helpers/global-node-fetch.js
================================================
import fetch, { Response, Request, Headers } from 'node-fetch';
global.fetch = fetch;
global.Request = Request;
global.Response = Response;
global.Headers = Headers;
================================================
FILE: tests/helpers/setup-fetch-record.js
================================================
const defaultOptions = {
host: '',
fetch() {
return global.fetch(...arguments);
}
};
function setupFetchRecord(options) {
setupFetchRecord.beforeEach(options);
setupFetchRecord.afterEach();
}
setupFetchRecord.beforeEach = function (options = {}) {
options = { ...defaultOptions, ...options };
beforeEach(function () {
const { host, fetch } = options;
this.fetch = fetch;
this.relativeFetch = (url, options) => this.fetch(`${host}${url}`, options);
this.recordUrl = () =>
`${host}/api/db/${encodeURIComponent(this.polly.recordingId)}`;
this.fetchRecord = (...args) => this.fetch(this.recordUrl(), ...args);
});
};
setupFetchRecord.afterEach = function () {
afterEach(async function () {
// Note: test setup could fail, so we cannot assume this.polly
// was setup before accessing it.
if (this.polly) {
this.polly.pause();
await this.fetchRecord({ method: 'DELETE' });
this.polly.play();
}
});
};
export default setupFetchRecord;
================================================
FILE: tests/helpers/setup-persister.js
================================================
function setupPersister() {
setupPersister.beforeEach();
setupPersister.afterEach();
}
setupPersister.beforeEach = function () {};
setupPersister.afterEach = function () {
afterEach(async function () {
await this.polly.persister.deleteRecording(this.polly.recordingId);
});
};
export default setupPersister;
================================================
FILE: tests/index.mustache
================================================
Polly.JS Tests
{{#css_files}}
{{/css_files}}
{{#serve_files}}
{{/serve_files}}
================================================
FILE: tests/integration/adapter-browser-tests.js
================================================
import 'formdata-polyfill';
import File from '../helpers/file';
export default function adapterBrowserTests() {
it('should handle recording requests posting FormData + Blob/File', async function () {
const { server, recordingName } = this.polly;
const form = new FormData();
form.append('string', recordingName);
form.append('array', [recordingName, recordingName]);
form.append('blob', new Blob([recordingName], { type: 'text/plain' }));
form.append(
'file',
new File([recordingName], 'test.txt', { type: 'text/plain' })
);
server.post('/submit').intercept((req, res) => {
const body = req.identifiers.body;
// Make sure the form data exists in the identifiers
expect(body).to.include(recordingName);
expect(body).to.include(`string=${recordingName}`);
expect(body).to.include(
`array=${[recordingName, recordingName].toString()}`
);
expect(body).to.include(
`blob=data:text/plain;base64,${btoa(recordingName)}`
);
expect(body).to.include(
`file=data:text/plain;base64,${btoa(recordingName)}`
);
res.sendStatus(200);
});
const res = await this.fetch('/submit', { method: 'POST', body: form });
expect(res.status).to.equal(200);
});
it('should handle recording requests posting a Blob', async function () {
const { server, recordingName } = this.polly;
server.post('/submit').intercept((req, res) => {
const dataUrl = `data:text/plain;base64,${btoa(recordingName)}`;
// Make sure the form data exists in the identifiers
expect(req.identifiers.body).to.equal(dataUrl);
res.sendStatus(200);
});
const res = await this.fetch('/submit', {
method: 'POST',
body: new Blob([recordingName], { type: 'text/plain' })
});
expect(res.status).to.equal(200);
});
}
================================================
FILE: tests/integration/adapter-identifier-tests.js
================================================
import set from 'lodash-es/set';
import deepmerge from 'deepmerge';
function adapterIdentifierTests() {
describe('matchRequestsBy', function () {
beforeEach(function () {
const { polly } = this;
polly.server.post('/*').intercept((req, res) => {
res.sendStatus(200);
});
this.requests = captureRequests(polly.server);
});
testConfiguration('method', false, {
expected: {
id: 'e7e58325a54088ab228cd9dbe7558141',
identifiers: {
headers: { 'content-type': 'application/json;charset=utf-8' },
body: '{}',
url: 'http://localhost:4000/pathname?query=param'
}
},
overrides: {
'node-http': {
id: '815b91955669771aa83a74ca27f6fbd8',
identifiers: {
headers: {
host: 'localhost:4000'
}
}
}
}
});
testConfiguration('headers', false, {
expected: {
id: '74e48a0f5e33321aa1aa3f4f65c8ccde',
identifiers: {
method: 'POST',
body: '{}',
url: 'http://localhost:4000/pathname?query=param'
}
}
});
testConfiguration('body', false, {
expected: {
id: 'b0427f53912c03a68ea2d4e923e136a8',
identifiers: {
body: undefined,
headers: { 'content-type': 'application/json;charset=utf-8' },
method: 'POST',
url: 'http://localhost:4000/pathname?query=param'
}
},
overrides: {
'node-http': {
id: 'b58187c060d6d9e8605dc0d2e68a4cc4',
identifiers: {
headers: {
host: 'localhost:4000'
}
}
}
}
});
testConfiguration('order', true, {
expected: {
id: '3dbff3c3fbccd6f97d01be31fc7fdd59',
identifiers: {
headers: { 'content-type': 'application/json;charset=utf-8' },
method: 'POST',
body: '{}',
url: 'http://localhost:4000/pathname?query=param'
}
},
overrides: {
'node-http': {
id: 'd0b5dfe199e75e370366c7570e402283',
identifiers: {
headers: {
host: 'localhost:4000'
}
}
}
}
});
describe('url', function () {
testConfiguration('url', false, {
expected: {
id: '3914e0be4d2f04139554f5ffada7191c',
identifiers: {
headers: { 'content-type': 'application/json;charset=utf-8' },
method: 'POST',
body: '{}'
}
},
overrides: {
'node-http': {
id: 'ecc7560697b752deb2529686affcaa71',
identifiers: {
headers: {
host: 'localhost:4000'
}
}
}
}
});
testConfiguration('url.protocol', false, {
expected: {
id: '79224baf23dc29f8115516cb8fe0546f',
identifiers: {
headers: { 'content-type': 'application/json;charset=utf-8' },
method: 'POST',
body: '{}',
url: '//localhost:4000/pathname?query=param'
}
},
overrides: {
'node-http': {
id: 'c24a09e0bd482ecafea2e6a523a2300c',
identifiers: {
headers: {
host: 'localhost:4000'
}
}
}
}
});
testConfiguration('url.hostname', false, {
expected: {
id: 'e5afacdff75fdbbdee298c4114fe576a',
identifiers: {
headers: { 'content-type': 'application/json;charset=utf-8' },
method: 'POST',
body: '{}',
url: 'http://:4000/pathname?query=param'
}
},
overrides: {
'node-http': {
id: '754af334c21a6367de2f4a96a88b500c',
identifiers: {
headers: {
host: 'localhost:4000'
}
}
}
}
});
testConfiguration('url.pathname', false, {
expected: {
id: 'bb2e8915ffeb6618c7095355ff16d141',
identifiers: {
headers: { 'content-type': 'application/json;charset=utf-8' },
method: 'POST',
body: '{}',
url: 'http://localhost:4000?query=param'
}
},
overrides: {
'node-http': {
id: '3575605055acca2b0d49f70fad6a8ea3',
identifiers: {
headers: {
host: 'localhost:4000'
}
}
}
}
});
testConfiguration('url.port', false, {
expected: {
id: '97705c56f6fc0e59027bef42d87902c3',
identifiers: {
headers: { 'content-type': 'application/json;charset=utf-8' },
method: 'POST',
body: '{}',
url: 'http://localhost/pathname?query=param'
}
},
overrides: {
'node-http': {
id: 'fe9e1be1fbde1268cf010cc0003736cb',
identifiers: {
headers: {
host: 'localhost:4000'
}
}
}
}
});
testConfiguration('url.query', false, {
expected: {
id: '534d71c078b3e446198b5060a560f900',
identifiers: {
headers: { 'content-type': 'application/json;charset=utf-8' },
method: 'POST',
body: '{}',
url: 'http://localhost:4000/pathname'
}
},
overrides: {
'node-http': {
id: '87788eaf035ab979bdd49cf2b4ff43f1',
identifiers: {
headers: {
host: 'localhost:4000'
}
}
}
}
});
testConfiguration('url.hash', true, {
expected: {
id: '80d27c6c94767915e1ac5db46896820e',
identifiers: {
headers: { 'content-type': 'application/json;charset=utf-8' },
method: 'POST',
body: '{}',
url: 'http://localhost:4000/pathname?query=param#abc'
}
},
overrides: {
'node-http': {
id: 'd876bcf1151b72a1b1bdf2a88403d6b3',
identifiers: {
headers: {
host: 'localhost:4000'
}
}
}
}
});
});
});
}
function captureRequests(server) {
const reqs = [];
server.any().on('request', (req) => reqs.push(req));
return reqs;
}
function lookupAdapterName(polly) {
return [...polly.adapters.keys()][0];
}
function testConfiguration(optionName, value, expectedValues) {
it(`${optionName}=${value}`, async function () {
const adapterName = lookupAdapterName(this.polly);
const expectedValue = deepmerge(
expectedValues.expected || {},
(expectedValues.overrides && expectedValues.overrides[adapterName]) || {}
);
const matchRequestsBy = set({}, optionName, value);
this.polly.configure({
matchRequestsBy
});
await this.fetch('http://localhost:4000/pathname?query=param#abc', {
method: 'POST',
body: JSON.stringify({}),
headers: { 'content-type': 'application/json;charset=utf-8' }
});
const [targetRequest] = this.requests;
if (targetRequest.identifiers) {
expect(targetRequest.identifiers).to.deep.equal(
expectedValue.identifiers
);
}
expect(targetRequest.id).to.equal(expectedValue.id);
});
}
export default adapterIdentifierTests;
================================================
FILE: tests/integration/adapter-node-tests.js
================================================
/* eslint-env node */
export default function adapterNodeTests() {
it('should handle recording requests posting a Buffer', async function () {
const { server, recordingName } = this.polly;
const buffer = Buffer.from(recordingName);
const url = `http://example.com/upload`;
server.post(url).intercept((req, res) => {
const body = req.identifiers.body;
// Make sure the buffer exists in the identifiers
expect(body).to.include(buffer.toString());
res.sendStatus(200);
});
const res = await this.fetch(url, { method: 'POST', body: buffer });
expect(res.status).to.equal(200);
});
it('should handle recording requests posting an ArrayBuffer', async function () {
const { server } = this.polly;
const buffer = new ArrayBuffer(8);
const url = `http://example.com/upload`;
server.post(url).intercept((req, res) => {
const body = req.identifiers.body;
// Make sure the buffer exists in the identifiers
expect(body).to.include(Buffer.from(buffer).toString());
res.sendStatus(200);
});
const res = await this.fetch(url, { method: 'POST', body: buffer });
expect(res.status).to.equal(200);
});
}
================================================
FILE: tests/integration/adapter-polly-tests.js
================================================
export default function pollyTests() {
it('should not handle any requests when paused', async function () {
const { server } = this.polly;
const requests = [];
server.any().on('request', (req) => requests.push(req));
await this.fetchRecord();
await this.fetchRecord();
this.polly.pause();
await this.fetchRecord();
await this.fetchRecord();
this.polly.play();
await this.fetchRecord();
expect(requests.length).to.equal(3);
expect(this.polly._requests.length).to.equal(3);
expect(requests.map((r) => r.order)).to.deep.equal([0, 1, 2]);
});
}
================================================
FILE: tests/integration/adapter-tests.js
================================================
import { Polly } from '@pollyjs/core';
import { ACTIONS } from '@pollyjs/utils';
export default function adapterTests() {
it('should respect request order', async function () {
const testOrder = async () => {
let res = await this.fetchRecord();
expect(res.status).to.equal(404);
res = await this.fetchRecord({
method: 'POST',
body: JSON.stringify({ foo: 'bar' }),
headers: { 'Content-Type': 'application/json' }
});
expect(res.status).to.equal(200);
res = await this.fetchRecord();
const json = await res.json();
expect(json).to.deep.equal({ foo: 'bar' });
res = await this.fetchRecord({ method: 'DELETE' });
expect(res.status).to.equal(200);
res = await this.fetchRecord();
expect(res.status).to.equal(404);
};
this.polly.configure({ recordIfMissing: false });
const { recordingName, config } = this.polly;
this.polly.record();
await testOrder();
await this.polly.stop();
this.polly = new Polly(recordingName, config);
this.polly.replay();
await testOrder();
});
it('should respect request order across multiple recordings', async function () {
const recordingName = this.polly.recordingName;
const otherRecordingName = `${this.polly.recordingName}-other`;
const order = {
[recordingName]: [],
[otherRecordingName]: []
};
this.polly.server.any(this.recordUrl()).on('beforeResponse', (req) => {
order[req.recordingName].push(req.order);
});
await this.fetchRecord();
await this.fetchRecord();
this.polly.server.any(this.recordUrl()).recordingName(otherRecordingName);
await this.fetchRecord();
await this.fetchRecord();
this.polly.server.any(this.recordUrl()).recordingName();
await this.fetchRecord();
expect(order[recordingName]).to.have.ordered.members([0, 1, 2]);
expect(order[otherRecordingName]).to.have.ordered.members([0, 1]);
});
it('should properly handle 204 status code response', async function () {
const res = await this.relativeFetch('/echo?status=204');
expect(res.status).to.equal(204);
expect(await res.text()).to.equal('');
});
it('should intercept', async function () {
const { server } = this.polly;
server.any(this.recordUrl()).intercept((_, res) => res.status(201));
server.get(this.recordUrl()).intercept((req, res) => res.json(req.query));
const res = await this.fetch(`${this.recordUrl()}?foo=bar`);
const json = await res.json();
expect(res.status).to.equal(201);
expect(json).to.deep.equal({ foo: 'bar' });
});
it('should passthrough', async function () {
const { server, persister, recordingId } = this.polly;
server.get(this.recordUrl()).passthrough();
expect(await persister.findRecording(recordingId)).to.be.null;
expect((await this.fetchRecord()).status).to.equal(404);
expect(await persister.findRecording(recordingId)).to.be.null;
});
it('should be able to intercept when in passthrough mode', async function () {
const { server } = this.polly;
this.polly.configure({ mode: 'passthrough' });
server
.get(this.recordUrl())
.intercept((req, res) => res.status(200).send('Hello'));
const res = await this.fetchRecord();
const text = await res.text();
expect(res.status).to.equal(200);
expect(text).to.equal('Hello');
});
it('should be able to abort from an intercept', async function () {
const { server } = this.polly;
let responseCalled = false;
server
.get(this.recordUrl())
.intercept((req, res, interceptor) => interceptor.abort())
.on('response', (req) => {
responseCalled = true;
expect(req.action).to.not.equal(ACTIONS.INTERCEPT);
});
expect((await this.fetchRecord()).status).to.equal(404);
expect(responseCalled).to.be.true;
});
it('should be able to passthrough from an intercept', async function () {
const { server, persister, recordingId } = this.polly;
let responseCalled = false;
server
.get(this.recordUrl())
.intercept((req, res, interceptor) => interceptor.passthrough())
.on('response', (req) => {
responseCalled = true;
expect(req.action).to.equal(ACTIONS.PASSTHROUGH);
});
expect(await persister.findRecording(recordingId)).to.be.null;
expect((await this.fetchRecord()).status).to.equal(404);
expect(await persister.findRecording(recordingId)).to.be.null;
expect(responseCalled).to.be.true;
});
it('should call all the life-cycle events', async function () {
const { server } = this.polly;
const events = [];
server
.get(this.recordUrl())
.on('request', () => events.push('request'))
.on('beforeResponse', () => events.push('beforeResponse'))
.on('response', () => events.push('response'));
await this.fetchRecord();
expect(events).to.have.ordered.members([
'request',
'beforeResponse',
'response'
]);
});
it('should call beforeReplay with a cloned recording entry', async function () {
const { recordingId, recordingName, config } = this.polly;
let replayedEntry;
this.polly.record();
await this.fetchRecord();
await this.polly.stop();
this.polly = new Polly(recordingName, config);
this.polly.replay();
const har = await this.polly.persister.findRecording(recordingId);
expect(har).to.be.an('object');
expect(har.log.entries).to.have.lengthOf(1);
this.polly.server
.get(this.recordUrl())
.on('beforeReplay', (_req, entry) => (replayedEntry = entry));
const entry = har.log.entries[0];
await this.fetchRecord();
expect(replayedEntry).to.be.an('object');
expect(entry).to.deep.equal(replayedEntry);
expect(entry).to.not.equal(replayedEntry);
expect(entry.request).to.deep.equal(replayedEntry.request);
expect(entry.request).to.not.equal(replayedEntry.request);
expect(entry.response).to.deep.equal(replayedEntry.response);
expect(entry.response).to.not.equal(replayedEntry.response);
expect(entry.response.content).to.deep.equal(
replayedEntry.response.content
);
expect(entry.response.content).to.not.equal(replayedEntry.response.content);
});
it('should emit an error event', async function () {
const { server } = this.polly;
let error;
this.polly.configure({ recordIfMissing: false });
server.get(this.recordUrl()).on('error', (req, err) => (error = err));
try {
await this.fetchRecord();
} catch (e) {
/* noop */
}
expect(error).to.exist;
expect(error.message).to.match(
/Recording for the following request is not found/
);
});
it('should handle a compressed response', async function () {
const res = await this.relativeFetch('/compress', {
method: 'POST',
body: JSON.stringify({ foo: 'bar' }),
headers: { 'Content-Type': 'application/json' }
});
expect(res.status).to.equal(200);
expect(await res.json()).to.deep.equal({ foo: 'bar' });
});
it('should have resolved requests after flushing', async function () {
// The puppeteer adapter has its own implementation of this test
if (this.polly.adapters.has('puppeteer')) {
this.skip();
}
const { server } = this.polly;
const requests = [];
const resolved = [];
server
.get(this.recordUrl())
.intercept(async (req, res) => {
await server.timeout(5);
res.sendStatus(200);
})
.on('request', (req) => {
requests.push(req);
});
this.fetchRecord().then(() => resolved.push(1));
this.fetchRecord().then(() => resolved.push(2));
this.fetchRecord().then(() => resolved.push(3));
await this.polly.server.timeout(10);
expect(requests).to.have.lengthOf(3);
await this.polly.flush();
requests.forEach((request) => expect(request.didRespond).to.be.true);
expect(resolved).to.have.members([1, 2, 3]);
});
// NOTE: test very unstable because of typicode.com being down
it.skip('should work with CORS requests', async function () {
this.timeout(10000);
const { server } = this.polly;
const apiUrl = 'http://jsonplaceholder.typicode.com';
server.any(`${apiUrl}/*`).passthrough();
let res = await this.fetch(`${apiUrl}/posts/1`);
expect(res.ok).to.be.true;
expect(await res.json()).to.be.an('object');
res = await this.fetch(`${apiUrl}/posts`, {
method: 'POST',
body: JSON.stringify({ foo: 'bar' }),
headers: { 'Content-Type': 'application/json' }
});
expect(res.ok).to.be.true;
});
describe('Expiration', () => {
async function testExpiration() {
const { persister, recordingId } = this.polly;
const url = '/api';
let har;
// request number one - records the request
this.polly.record();
await this.relativeFetch(url);
await persister.persist();
har = await persister.findRecording(recordingId);
expect(har).to.be.an('object');
expect(har.log.entries).to.have.lengthOf(1);
const prevDateTime = har.log.entries[0].startedDateTime;
// wait for the first request to expire
await new Promise((r) => setTimeout(r, 10));
// request number two - the first request is now expired
this.polly.replay();
await this.relativeFetch(url);
await persister.persist();
har = await persister.findRecording(recordingId);
expect(har).to.be.an('object');
expect(har.log.entries).to.have.lengthOf(1);
const nextDateTime = har.log.entries[0].startedDateTime;
// boolean returned is true if re-record occurred
return prevDateTime !== nextDateTime;
}
beforeEach(function () {
this.polly.configure({
expiresIn: '1ms',
matchRequestsBy: {
order: false
}
});
});
afterEach(async function () {
await this.polly.persister.deleteRecording(this.polly.recordingId);
});
it('warns and plays back on expired recording if expiryStrategy is "warn"', async function () {
this.polly.configure({ expiryStrategy: 'warn' });
expect(await testExpiration.call(this)).to.equal(false);
});
it('re-records on expired recording if expiryStrategy is "record"', async function () {
this.polly.configure({ expiryStrategy: 'record' });
expect(await testExpiration.call(this)).to.equal(true);
});
it('throws on expired recording if expiryStrategy is "error"', async function () {
const { server } = this.polly;
let error;
this.polly.configure({ expiryStrategy: 'error' });
server.any().on('error', (req, e) => (error = e));
try {
await testExpiration.call(this);
} catch (e) {
// noop
}
expect(error).to.exist;
expect(error.message).to.match(
/Recording for the following request has expired/
);
});
});
}
================================================
FILE: tests/integration/persister-tests.js
================================================
import { Polly } from '@pollyjs/core';
import * as validate from 'har-validator/lib/async';
export default function persisterTests() {
it('should persist valid HAR', async function () {
const { recordingId, persister } = this.polly;
this.polly.record();
await this.fetchRecord();
await persister.persist();
expect(await validate.har(await persister.findRecording(recordingId))).to.be
.true;
await this.fetchRecord({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ foo: 'bar', bar: 'baz' })
});
await persister.persist();
expect(await validate.har(await persister.findRecording(recordingId))).to.be
.true;
});
it('should have the correct metadata', async function () {
const { recordingId, recordingName, persister } = this.polly;
this.polly.record();
await this.fetchRecord();
await persister.persist();
const har = await persister.findRecording(recordingId);
const { _recordingName, creator, entries } = har.log;
const entry = entries[0];
expect(_recordingName).to.equal(recordingName);
expect(creator.name).to.equal('Polly.JS');
expect(creator.version).to.equal(Polly.VERSION);
expect(creator.comment).to.equal(
`${persister.constructor.type}:${persister.constructor.id}`
);
expect(entry).to.be.an('object');
expect(entry._id).to.a('string');
expect(entry._order).to.equal(0);
});
it('should add new entries to an existing recording', async function () {
const { recordingId, recordingName, config } = this.polly;
let { persister } = this.polly;
const orderedRecordUrl = (order) => `${this.recordUrl()}?order=${order}`;
this.polly.record();
await this.fetch(orderedRecordUrl(1));
await persister.persist();
let har = await persister.findRecording(recordingId);
expect(har.log.entries).to.have.lengthOf(1);
await this.polly.stop();
this.polly = new Polly(recordingName, config);
persister = this.polly.persister;
this.polly.record();
await this.fetch(orderedRecordUrl(1));
await this.fetch(orderedRecordUrl(1));
await this.fetch(orderedRecordUrl(2));
await persister.persist();
har = await persister.findRecording(recordingId);
expect(har.log.entries).to.have.lengthOf(3);
expect(
har.log.entries.filter((e) => e.request.url.includes(orderedRecordUrl(1)))
).to.have.lengthOf(2);
expect(
har.log.entries.filter((e) => e.request.url.includes(orderedRecordUrl(2)))
).to.have.lengthOf(1);
});
it('should emit beforePersist', async function () {
const { persister, server } = this.polly;
let beforePersistCalled = false;
server.get(this.recordUrl()).on('beforePersist', (req /*, res*/) => {
expect(beforePersistCalled).to.be.false;
expect(() => (req.body = 'test')).to.throw(Error);
beforePersistCalled = true;
});
this.polly.record();
await this.fetchRecord();
expect(beforePersistCalled).to.be.false;
await persister.persist();
expect(beforePersistCalled).to.be.true;
});
it('should respect recording name overrides', async function () {
const { server, persister } = this.polly;
const recordingName = 'Default Override';
let recordingId;
server
.get(this.recordUrl())
.recordingName(recordingName)
.on('request', (req) => {
expect(req.recordingName).to.equal(recordingName);
recordingId = req.recordingId;
});
this.polly.record();
await this.fetchRecord();
await persister.persist();
expect(recordingId).to.include('Override');
const har = await persister.findRecording(recordingId);
expect(await validate.har(har)).to.be.true;
expect(har.log.entries).to.have.lengthOf(1);
// Set the new recording name so the afterEach hook deletes the recording
this.polly.recordingName = recordingName;
});
it('should correctly handle array header values', async function () {
const { recordingId, server, persister } = this.polly;
let responseCalled = false;
this.polly.record();
server
.get(this.recordUrl())
.configure({ matchRequestsBy: { order: false } })
.once('beforeResponse', (req, res) => {
res.setHeaders({
string: 'foo',
one: ['foo'],
two: ['foo', 'bar']
});
});
await this.fetchRecord();
await persister.persist();
const har = await persister.findRecording(recordingId);
const { headers } = har.log.entries[0].response;
expect(await validate.har(har)).to.be.true;
expect(
headers.filter(({ _fromType }) => _fromType === 'array')
).to.have.lengthOf(3);
this.polly.replay();
server.get(this.recordUrl()).once('response', (req, res) => {
expect(res.getHeader('string')).to.equal('foo');
expect(res.getHeader('one')).to.deep.equal(['foo']);
expect(res.getHeader('two')).to.deep.equal(['foo', 'bar']);
responseCalled = true;
});
await this.fetchRecord();
expect(responseCalled).to.be.true;
});
it('should correctly handle array header values where a single header is expected', async function () {
const { recordingId, server, persister } = this.polly;
this.polly.record();
server.get(this.recordUrl()).once('beforeResponse', (req, res) => {
res.setHeaders({
Location: ['./index.html'],
'Content-Type': ['application/json']
});
});
await this.fetchRecord();
await persister.persist();
const har = await persister.findRecording(recordingId);
const { content, redirectURL } = har.log.entries[0].response;
expect(await validate.har(har)).to.be.true;
expect(content.mimeType).to.equal('application/json');
expect(redirectURL).to.equal('./index.html');
});
it('should error when persisting a failed request', async function () {
let error;
this.polly.configure({ recordFailedRequests: false });
try {
await this.relativeFetch('/echo?status=400');
await this.polly.stop();
} catch (e) {
error = e;
} finally {
const savedRecording = await this.polly.persister.findRecording(
this.polly.recordingId
);
expect(savedRecording).to.be.null;
expect(error.message).to.contain('Cannot persist response for');
// Clear the pending requests so `this.polly.stop()` in the
// afterEach hook won't bomb.
this.polly.persister.pending.clear();
}
});
it('should not error when persisting a failed request and `recordFailedRequests` is true', async function () {
this.polly.configure({ recordFailedRequests: true });
await this.relativeFetch('/echo?status=400');
await this.polly.stop();
const har = await this.polly.persister.findRecording(
this.polly.recordingId
);
expect(har).to.be.an('object');
expect(har.log.entries).to.have.lengthOf(1);
});
it('should not error when persisting a 302 request and `recordFailedRequests` is false', async function () {
this.polly.configure({ recordFailedRequests: false });
await this.relativeFetch('/echo?status=302');
await this.polly.stop();
const har = await this.polly.persister.findRecording(
this.polly.recordingId
);
expect(har).to.be.an('object');
expect(har.log.entries).to.have.lengthOf(1);
});
it('should remove unused entries when `keepUnusedRequests` is false', async function () {
const { recordingName, recordingId, config } = this.polly;
const orderedRecordUrl = (order) => `${this.recordUrl()}?order=${order}`;
await this.fetch(orderedRecordUrl(1));
await this.fetch(orderedRecordUrl(2));
await this.polly.persister.persist();
let har = await this.polly.persister.findRecording(recordingId);
expect(har).to.be.an('object');
expect(har.log.entries).to.have.lengthOf(2);
await this.polly.stop();
this.polly = new Polly(recordingName, config);
this.polly.replay();
this.polly.configure({
persisterOptions: {
keepUnusedRequests: false
}
});
await this.fetch(orderedRecordUrl(1)); // -> Replay
await this.fetch(orderedRecordUrl(3)); // -> New recording
await this.polly.persister.persist();
har = await this.polly.persister.findRecording(recordingId);
expect(har).to.be.an('object');
expect(har.log.entries).to.have.lengthOf(2);
expect(har.log.entries[0].request.url).to.include(orderedRecordUrl(1));
expect(har.log.entries[1].request.url).to.include(orderedRecordUrl(3));
});
it('should sort the entries by date', async function () {
this.polly.configure({
persisterOptions: {
keepUnusedRequests: true
}
});
const { recordingName, recordingId, config } = this.polly;
const orderedRecordUrl = (order) => `${this.recordUrl()}?order=${order}`;
await this.fetch(orderedRecordUrl(1));
await this.fetch(orderedRecordUrl(2));
await this.polly.persister.persist();
let har = await this.polly.persister.findRecording(recordingId);
expect(har).to.be.an('object');
expect(har.log.entries).to.have.lengthOf(2);
expect(har.log.entries[0].request.url).to.include(orderedRecordUrl(1));
expect(har.log.entries[1].request.url).to.include(orderedRecordUrl(2));
await this.polly.stop();
this.polly = new Polly(recordingName, config);
this.polly.record();
await this.fetch(orderedRecordUrl(3));
await this.fetch(orderedRecordUrl(4));
await this.fetch(orderedRecordUrl(2));
await this.polly.persister.persist();
har = await this.polly.persister.findRecording(recordingId);
expect(har).to.be.an('object');
expect(har.log.entries).to.have.lengthOf(4);
expect(har.log.entries[0].request.url).to.include(orderedRecordUrl(1));
expect(har.log.entries[1].request.url).to.include(orderedRecordUrl(3));
expect(har.log.entries[2].request.url).to.include(orderedRecordUrl(4));
expect(har.log.entries[3].request.url).to.include(orderedRecordUrl(2));
});
it('should not sort the entries by date if `disableSortingHarEntries` is true', async function () {
this.polly.configure({
persisterOptions: {
keepUnusedRequests: true,
disableSortingHarEntries: true
}
});
const { recordingName, recordingId, config } = this.polly;
const orderedRecordUrl = (order) => `${this.recordUrl()}?order=${order}`;
await this.fetch(orderedRecordUrl(1));
await this.fetch(orderedRecordUrl(2));
await this.polly.persister.persist();
let har = await this.polly.persister.findRecording(recordingId);
expect(har).to.be.an('object');
expect(har.log.entries).to.have.lengthOf(2);
expect(har.log.entries[0].request.url).to.include(orderedRecordUrl(1));
expect(har.log.entries[1].request.url).to.include(orderedRecordUrl(2));
await this.polly.stop();
this.polly = new Polly(recordingName, config);
this.polly.replay();
await this.fetch(orderedRecordUrl(3));
await this.fetch(orderedRecordUrl(4));
await this.polly.persister.persist();
har = await this.polly.persister.findRecording(recordingId);
expect(har).to.be.an('object');
expect(har.log.entries).to.have.lengthOf(4);
expect(har.log.entries[0].request.url).to.include(orderedRecordUrl(3));
expect(har.log.entries[1].request.url).to.include(orderedRecordUrl(4));
expect(har.log.entries[2].request.url).to.include(orderedRecordUrl(1));
expect(har.log.entries[3].request.url).to.include(orderedRecordUrl(2));
});
it('should correctly handle binary responses', async function () {
const { recordingId, server, persister } = this.polly;
let har, content;
this.polly.record();
// Non binary content
server.get(this.recordUrl()).once('beforeResponse', (req, res) => {
res.body = 'Some content';
});
await this.fetchRecord();
await persister.persist();
har = await persister.findRecording(recordingId);
content = har.log.entries[0].response.content;
expect(await validate.har(har)).to.be.true;
expect(content.encoding).to.be.undefined;
// Binary content
server.get(this.recordUrl()).once('beforeResponse', (req, res) => {
res.encoding = 'base64';
res.body = 'U29tZSBjb250ZW50';
});
await this.fetchRecord();
await persister.persist();
har = await persister.findRecording(recordingId);
content = har.log.entries[1].response.content;
expect(await validate.har(har)).to.be.true;
expect(content.encoding).to.equal('base64');
// Binary content with no body
server.get(this.recordUrl()).once('beforeResponse', (req, res) => {
res.encoding = 'base64';
res.body = '';
});
await this.fetchRecord();
await persister.persist();
har = await persister.findRecording(recordingId);
content = har.log.entries[2].response.content;
expect(await validate.har(har)).to.be.true;
expect(content.encoding).to.be.undefined;
});
}
================================================
FILE: tests/middleware.js
================================================
/* eslint-env node */
const path = require('path');
const bodyParser = require('body-parser');
const compression = require('compression');
const { registerExpressAPI } = require('../packages/@pollyjs/node-server');
const DB = {};
module.exports = function attachMiddleware(app) {
registerExpressAPI(app, {
recordingsDir: path.join(__dirname, 'recordings')
});
app.get('/assets/:name', (req, res) => {
res.sendFile(path.join(__dirname, 'assets', req.params.name));
});
app.use(bodyParser.json());
app.get('/echo', (req, res) => {
const status = req.query.status;
if (status === '204') {
res.status(204).send();
} else {
res.sendStatus(req.query.status);
}
});
app.post('/compress', compression({ filter: () => true }), (req, res) => {
res.write(JSON.stringify(req.body));
res.end();
});
app.get('/api', (req, res) => {
res.sendStatus(200);
});
app.get('/api/db/:id', (req, res) => {
const { id } = req.params;
if (DB[id]) {
res.status(200).json(DB[id]);
} else {
res.status(404).end();
}
});
app.post('/api/db/:id', (req, res) => {
const { id } = req.params;
DB[id] = req.body;
res.status(200).json(DB[id]);
});
app.delete('/api/db/:id', (req, res) => {
const { id } = req.params;
delete DB[id];
res.status(200).end();
});
};
================================================
FILE: tests/node-setup.js
================================================
/* eslint-env node */
global.expect = require('chai').expect;