diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..3c3629e64 --- /dev/null +++ b/.dockerignore @@ -0,0 +1 @@ +node_modules diff --git a/.editorconfig b/.editorconfig index e717f5eb6..366bdb572 100644 --- a/.editorconfig +++ b/.editorconfig @@ -9,5 +9,15 @@ charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true +[targets/**/fixtures/*] +insert_final_newline = false + +[**/http1.1/fixtures/*] +end_of_line = crlf +insert_final_newline = false + +[**/http1.1/fixtures/jsonObj-multiline] +end_of_line = unset + [*.md] trim_trailing_whitespace = false diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..491fe1370 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +targets/http/http1.1/fixtures text diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 000000000..038b47102 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @erunion \ No newline at end of file diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..4cb1609c7 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,44 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: '/' + schedule: + interval: monthly + labels: + - dependencies + groups: + minor-development-deps: + dependency-type: 'development' + update-types: + - minor + - patch + commit-message: + prefix: chore(deps) + prefix-development: chore(deps-dev) + + - package-ecosystem: npm + directory: '/' + schedule: + interval: monthly + open-pull-requests-limit: 10 + labels: + - dependencies + groups: + minor-development-deps: + dependency-type: 'development' + update-types: + - minor + - patch + minor-production-deps: + dependency-type: 'production' + update-types: + - minor + - patch + commit-message: + prefix: chore(deps) + prefix-development: chore(deps-dev) + ignore: + # stringify-objectis now an ESM package and can't be used here without a rewrite. + - dependency-name: stringify-object + versions: + - '>= 4' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..db5f16158 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,37 @@ +name: CI + +on: + push: + branches: + - main + pull_request: + +jobs: + build: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: + - lts/-1 + - lts/* + - latest + + steps: + - uses: actions/checkout@v6 + + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v6 + with: + node-version: ${{ matrix.node-version }} + + - run: npm cit + + lint: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v6 + + - run: npm ci + - run: npm run lint diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 000000000..8bab8ca93 --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,35 @@ +name: 'CodeQL' + +on: + push: + branches: [main] + pull_request: + branches: [main] + schedule: + - cron: '0 12 * * 1' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: ['javascript'] + + steps: + - name: Checkout repository + uses: actions/checkout@v6 + + - name: Initialize CodeQL + uses: github/codeql-action/init@v4 + with: + languages: ${{ matrix.language }} + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v4 diff --git a/.github/workflows/integration-c.yml b/.github/workflows/integration-c.yml new file mode 100644 index 000000000..3ad289c95 --- /dev/null +++ b/.github/workflows/integration-c.yml @@ -0,0 +1,14 @@ +name: Integrations (C) +on: [push] +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - name: Run tests + run: docker compose run integration_c + + - name: Cleanup + if: always() + run: docker compose down diff --git a/.github/workflows/integration-csharp.yml b/.github/workflows/integration-csharp.yml new file mode 100644 index 000000000..1945764a0 --- /dev/null +++ b/.github/workflows/integration-csharp.yml @@ -0,0 +1,14 @@ +name: Integrations (C#) +on: [push] +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - name: Run tests + run: docker compose run integration_csharp + + - name: Cleanup + if: always() + run: docker compose down diff --git a/.github/workflows/integration-go.yml b/.github/workflows/integration-go.yml new file mode 100644 index 000000000..49754871d --- /dev/null +++ b/.github/workflows/integration-go.yml @@ -0,0 +1,14 @@ +name: Integrations (Go) +on: [push] +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - name: Run tests + run: docker compose run integration_golang + + - name: Cleanup + if: always() + run: docker compose down diff --git a/.github/workflows/integration-node.yml b/.github/workflows/integration-node.yml new file mode 100644 index 000000000..3907c72bb --- /dev/null +++ b/.github/workflows/integration-node.yml @@ -0,0 +1,14 @@ +name: Integrations (Node) +on: [push] +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - name: Run tests + run: docker compose run integration_node + + - name: Cleanup + if: always() + run: docker compose down diff --git a/.github/workflows/integration-php.yml b/.github/workflows/integration-php.yml new file mode 100644 index 000000000..596b42f72 --- /dev/null +++ b/.github/workflows/integration-php.yml @@ -0,0 +1,14 @@ +name: Integrations (PHP) +on: [push] +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - name: Run tests + run: docker compose run integration_php + + - name: Cleanup + if: always() + run: docker compose down diff --git a/.github/workflows/integration-python.yml b/.github/workflows/integration-python.yml new file mode 100644 index 000000000..e09fd6cdf --- /dev/null +++ b/.github/workflows/integration-python.yml @@ -0,0 +1,14 @@ +name: Integrations (Python) +on: [push] +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - name: Run tests + run: docker compose run integration_python + + - name: Cleanup + if: always() + run: docker compose down diff --git a/.github/workflows/integration-shell.yml b/.github/workflows/integration-shell.yml new file mode 100644 index 000000000..24ea6b6f3 --- /dev/null +++ b/.github/workflows/integration-shell.yml @@ -0,0 +1,14 @@ +name: Integrations (Shell) +on: [push] +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - name: Run tests + run: docker compose run integration_shell + + - name: Cleanup + if: always() + run: docker compose down diff --git a/.gitignore b/.gitignore index dddca890c..5077352bf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ *.log -node_modules -coverage* +coverage/ +dist/ +node_modules/ +vendor/ +composer.* diff --git a/.jshintrc b/.jshintrc deleted file mode 100644 index 086f6bacb..000000000 --- a/.jshintrc +++ /dev/null @@ -1,4 +0,0 @@ -{ - "asi": true, - "node": true -} diff --git a/.npmignore b/.npmignore index 59e4f4a9a..b962347fa 100644 --- a/.npmignore +++ b/.npmignore @@ -1,3 +1,7 @@ -.jshintrc -.editorconfig -test +# Ignore everything by default +# NOTE: NPM publish will never ignore package.json, package-lock.json, README, LICENSE, CHANGELOG +# https://npm.github.io/publishing-pkgs-docs/publishing/the-npmignore-file.html +* + +# Don't ignore dist folder +!dist/** diff --git a/.npmrc b/.npmrc new file mode 100644 index 000000000..4eae7876f --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +lockfile-version=3 diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000..cd8a403f5 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,5 @@ +build/ +coverage/ +dist/ +node_modules/ +src/targets/**/fixtures/ diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index bc27bef00..000000000 --- a/.travis.yml +++ /dev/null @@ -1,21 +0,0 @@ -language: node_js - -node_js: - - iojs - - 0.10 - - 0.12 - -before_install: - - sudo apt-get update -qq - - sudo apt-get install -qq --yes python3 php5-curl php5-cli - -after_script: - - npm run codeclimate - -notifications: - webhooks: - urls: - - https://webhooks.gitter.im/e/95c4e911f2486588f98c - on_success: always - on_failure: always - on_start: false diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 000000000..8faf83c1a --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,3 @@ +{ + "recommendations": ["EditorConfig.EditorConfig"] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..90c7e0089 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,15 @@ +{ + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.codeActionsOnSave": { + "source.fixAll": "explicit" + }, + "editor.formatOnSave": true, + + // controlled by the .editorconfig at root since we can't map vscode settings directly to files + // https://github.com/microsoft/vscode/issues/35350 + "files.insertFinalNewline": false, + + "search.exclude": { + "coverage": true + } +} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 82e260334..000000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,139 +0,0 @@ -# Contributing to this project - -Please take a moment to review this document in order to make the contribution -process easy and effective for everyone involved. - -Following these guidelines helps to communicate that you respect the time of -the developers managing and developing this open source project. In return, -they should reciprocate that respect in addressing your issue or assessing -patches and features. - -## Using the issue tracker - -The [issue tracker](/issues) is the preferred channel for [bug reports](#bug-reports), -[features requests](#feature-requests) and [submitting pull requests](#pull-requests), -but please respect the following restrictions: - -* Please **do not** use the issue tracker for personal support requests (use - [Stack Overflow](http://stackoverflow.com) or IRC). - -* Please **do not** derail or troll issues. Keep the discussion on topic and - respect the opinions of others. - -## Bug reports - -A bug is a _demonstrable problem_ that is caused by the code in the repository. -Good bug reports are extremely helpful - thank you! - -Guidelines for bug reports: - -1. **Use the GitHub issue search** — check if the issue has already been - reported. - -2. **Check if the issue has been fixed** — try to reproduce it using the - latest `master` or development branch in the repository. - -3. **Isolate the problem** — create a [reduced test - case](http://css-tricks.com/6263-reduced-test-cases/) and a live example. - -A good bug report shouldn't leave others needing to chase you up for more -information. Please try to be as detailed as possible in your report. What is -your environment? What steps will reproduce the issue? What browser(s) and OS -experience the problem? What would you expect to be the outcome? All these -details will help people to fix any potential bugs. - -Example: - -> Short and descriptive example bug report title -> -> A summary of the issue and the browser/OS environment in which it occurs. If -> suitable, include the steps required to reproduce the bug. -> -> 1. This is the first step -> 2. This is the second step -> 3. Further steps, etc. -> -> `` - a link to the reduced test case -> -> Any other information you want to share that is relevant to the issue being -> reported. This might include the lines of code that you have identified as -> causing the bug, and potential solutions (and your opinions on their -> merits). - -## Feature requests - -Feature requests are welcome. But take a moment to find out whether your idea -fits with the scope and aims of the project. It's up to *you* to make a strong -case to convince the project's developers of the merits of this feature. Please -provide as much detail and context as possible. - -## Pull requests - -Good pull requests (patches, improvements, new features) are a fantastic -help. They should remain focused in scope and avoid containing unrelated -commits. - -**Please ask first** before embarking on any significant pull request (e.g. -implementing features, refactoring code, porting to a different language), -otherwise you risk spending a lot of time working on something that the -project's developers might not want to merge into the project. - -Please adhere to the coding conventions used throughout a project (indentation, -accurate comments, etc.) and any other requirements (such as test coverage). - -Follow this process if you'd like your work considered for inclusion in the -project: - -1. [Fork](http://help.github.com/fork-a-repo/) the project, clone your fork, - and configure the remotes: - - ```bash - # Clone your fork of the repo into the current directory - git clone https://github.com// - # Navigate to the newly cloned directory - cd - # Assign the original repo to a remote called "upstream" - git remote add upstream https://github.com/Mashape/httpsnippet.git - ``` - -2. If you cloned a while ago, get the latest changes from upstream: - - ```bash - git checkout - git pull upstream - ``` - -3. Create a new topic branch (off the main project development branch) to - contain your feature, change, or fix: - - ```bash - git checkout -b - ``` - -4. Commit your changes in logical chunks. Please adhere to these [git commit - message guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) - or your code is unlikely be merged into the main project. Use Git's - [interactive rebase](https://help.github.com/articles/interactive-rebase) - feature to tidy up your commits before making them public. - -5. Locally merge (or rebase) the upstream development branch into your topic branch: - - ```bash - git pull [--rebase] upstream - ``` - -6. Push your topic branch up to your fork: - - ```bash - git push origin - ``` - -7. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/) - with a clear title and description. - -**IMPORTANT**: By submitting a patch, you agree to allow the project owner to -license your work under the same license as that used by the project. - -## Creating New Conversion Targets - -For a info on creating new conversion targets, please review this [guideline](https://github.com/Mashape/httpsnippet/wiki/Creating-Targets) diff --git a/LICENSE b/LICENSE index fbab00b10..b7d3ebfb6 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2015 Mashape (https://www.mashape.com) +Copyright (c) 2024 ReadMe (https://readme.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index b45396cf3..3bb04fcc0 100644 --- a/README.md +++ b/README.md @@ -1,218 +1,214 @@ # HTTP Snippet [![version][npm-version]][npm-url] [![License][npm-license]][license-url] -> HTTP Request snippet generator for *many* languages & tools including: `cURL`, `HTTPie`, `Javascript`, `Node`, `C`, `Java`, `PHP`, `Objective-C`, `Swift`, `Python`, `Ruby`, `C#`, `Go`, `OCaml` and [more](https://github.com/Mashape/httpsnippet/wiki/Targets)! +> HTTP Request snippet generator for _many_ languages & tools including: `cURL`, `HTTPie`, `Javascript`, `Node`, `C`, `Java`, `PHP`, `Objective-C`, `Swift`, `Python`, `Ruby`, `C#`, `Go`, `OCaml` and [more](https://github.com/Kong/httpsnippet/wiki/Targets)! Relies on the popular [HAR](http://www.softwareishard.com/blog/har-12-spec/#request) format to import data and describe HTTP calls. -See it in action on companion service: [APIembed](https://apiembed.com/) +See it in action on [ReadMe](https://docs.readme.com/reference/getopenroles). -[![Build Status][travis-image]][travis-url] -[![Downloads][npm-downloads]][npm-url] -[![Code Climate][codeclimate-quality]][codeclimate-url] -[![Coverage Status][codeclimate-coverage]][codeclimate-url] -[![Dependencies][david-image]][david-url] -[![Gitter][gitter-image]][gitter-url] +[![Build](https://github.com/readmeio/httpsnippet/workflows/CI/badge.svg)](https://github.com/readmeio/httpsnippet) -## Install +## Installation ```shell -# to use in cli -npm install --global httpsnippet - -# to use as a module -npm install --save httpsnippet +npm install --save @readme/httpsnippet ``` ## Usage -``` - - Usage: httpsnippet [options] - - Options: - - -h, --help output usage information - -V, --version output the version number - -t, --target target output - -c, --client [client] target client library - -o, --output write output to directory - -``` - -###### Example +### HTTPSnippet(input [, options]) -process single file: [`example.json`](test/fixtures/requests/full.json) in [HAR Request Object](http://www.softwareishard.com/blog/har-12-spec/#request) format, or full [HAR](http://www.softwareishard.com/blog/har-12-spec/#log) log format: +#### input -```shell -httpsnippet example.json --target node --client unirest --output ./snippets -``` +_Required_ Type: `object` -```shell -$ tree snippets -snippets/ -└── example.js -``` +The [HAR](http://www.softwareishard.com/blog/har-12-spec/#request) request object to generate a snippet for. -process multiple files: +```ts +import { HTTPSnippet } from '@readme/httpsnippet'; -```shell -httpsnippet ./*.json --target node --client request --output ./snippets -``` - -```shell -$ tree snippets/ -snippets/ -├── endpoint-1.js -├── endpoint-2.js -└── endpoint-3.js +const snippet = new HTTPSnippet({ + method: 'GET', + url: 'https://httpbin.org/anything', +}); ``` -## API - -### HTTPSnippet(source) - -#### source +#### options -*Required* Type: `object` -Name of [conversion target](https://github.com/Mashape/httpsnippet/wiki/Targets) +Available options: -```js -var HTTPSnippet = require('httpsnippet'); - -var snippet = new HTTPSnippet({ - method: 'GET', - url: 'http://mockbin.com/request' -}); -``` +- `harIsAlreadyEncoded` (`boolean`): In the event of you supplying a `source` HAR that already contains escaped data (query and cookie parameters)strings, this allows you to disable automatic encoding of those parameters to prevent them from being double-escaped. ### convert(target [, options]) #### target -*Required* -Type: `string` +_Required_ Type: `string` -Name of [conversion target](https://github.com/Mashape/httpsnippet/wiki/Targets) +Name of [conversion target](https://github.com/Kong/httpsnippet/wiki/Targets) #### options Type: `object` -Target options, *see [wiki](https://github.com/Mashape/httpsnippet/wiki/Targets) for details* +Target options, _see [wiki](https://github.com/Kong/httpsnippet/wiki/Targets) for details_ -```js -var HTTPSnippet = require('httpsnippet'); +```ts +import { HTTPSnippet } from '@readme/httpsnippet'; -var snippet = new HTTPSnippet({ +const snippet = new HTTPSnippet({ method: 'GET', - url: 'http://mockbin.com/request' + url: 'https://httpbin.org/anything', }); // generate Node.js: Native output console.log(snippet.convert('node')); // generate Node.js: Native output, indent with tabs -console.log(snippet.convert('node', { - indent: '\t' -})); +console.log( + snippet.convert('node', { + indent: '\t', + }), +); ``` ### convert(target [, client, options]) -#### target +#### Target -*Required* -Type: `string` +_Required_ Type: `string` -Name of [conversion target](https://github.com/Mashape/httpsnippet/wiki/Targets) +Name of [conversion target](https://github.com/Kong/httpsnippet/wiki/Targets) -#### client +#### Client Type: `string` -Name of conversion target [client library](https://github.com/Mashape/httpsnippet/wiki/Targets) +Name of conversion target [client library](https://github.com/Kong/httpsnippet/wiki/Targets) -#### options +#### Options Type: `object` -Target options, *see [wiki](https://github.com/Mashape/httpsnippet/wiki/Targets) for details* +Target options, _see [wiki](https://github.com/Kong/httpsnippet/wiki/Targets) for details_ -```js -var HTTPSnippet = require('httpsnippet'); +```ts +import { HTTPSnippet } from '@readme/httpsnippet'; -var snippet = new HTTPSnippet({ +const snippet = new HTTPSnippet({ method: 'GET', - url: 'http://mockbin.com/request' + url: 'https://httpbin.org/anything', }); // generate Shell: cURL output -console.log(snippet.convert('shell', 'curl', { - indent: '\t' -})); - -// generate Node.js: Unirest output -console.log(snippet.convert('node', 'unirest')); +console.log( + snippet.convert('shell', 'curl', { + indent: '\t', + }), +); + +// generate Node.js: Axios output +console.log(snippet.convert('node', 'axios')); ``` -## Documentation - -At the heart of this module is the [HAR Format](http://www.softwareishard.com/blog/har-12-spec/#request) as the HTTP request description format, please review some of the sample JSON HAR Request objects in [test fixtures](/test/fixtures/requests), or read the [HAR Docs](http://www.softwareishard.com/blog/har-12-spec/#request) for more details. - -For detailed information on each target, please review the [wiki](https://github.com/Mashape/httpsnippet/wiki). +### addTarget(target) -## Bugs and feature requests - -Have a bug or a feature request? Please first read the [issue guidelines](CONTRIBUTING.md#using-the-issue-tracker) and search for existing and closed issues. If your problem or idea is not addressed yet, [please open a new issue](/issues). - -## Contributing +#### target -Please read through our [contributing guidelines](CONTRIBUTING.md). Included are directions for opening issues, coding standards, and notes on development. +_Required_ Type: `object` -For a info on creating new conversion targets, please review this [guideline](https://github.com/Mashape/httpsnippet/wiki/Creating-Targets) +Representation of a [conversion target](https://github.com/Kong/httpsnippet/wiki/Creating-Targets). Can use this to use targets that are not officially supported. -More over, if your pull request contains JavaScript patches or features, you must include relevant unit tests. +```ts +import { customLanguageTarget } from 'httpsnippet-for-my-lang'; +HTTPSnippet.addTarget(customLanguageTarget); +``` -Editor preferences are available in the [editor config](.editorconfig) for easy use in common text editors. Read more and download plugins at . +### addTargetClient(target, client) -## Versioning +#### Target -For transparency into our release cycle and in striving to maintain backward compatibility, this project is maintained under the Semantic Versioning guidelines. Sometimes we screw up, but we'll adhere to these rules whenever possible. +_Required_ Type: `string` -Releases will be numbered with the following format: +Name of [conversion target](https://github.com/Kong/httpsnippet/wiki/Targets) -`..` +#### Client -And constructed with the following guidelines: +_Required_ Type: `object` -- Breaking backward compatibility **bumps the major** while resetting minor and patch -- New additions without breaking backward compatibility **bumps the minor** while resetting the patch -- Bug fixes and misc changes **bumps only the patch** +Representation of a [conversion target client](https://github.com/Kong/httpsnippet/wiki/Creating-Targets). Can use this to use target clients that are not officially supported. -For more information on SemVer, please visit . +```ts +import { customClient } from 'httpsnippet-for-my-node-http-client'; +HTTPSnippet.addTargetClient('node', customClient); +``` -## License +### addClientPlugin(plugin) + +#### Plugin + +_Required_ Type: `object` + +The client plugin to install. + +```ts +addClientPlugin({ + target: 'node', + client: { + info: { + key: 'custom', + title: 'Custom HTTP library', + link: 'https://example.com', + description: 'A custom HTTP library', + extname: '.custom', + }, + convert: () => { + return 'This was generated from a custom client.'; + }, + }, +}); +``` -[MIT](LICENSE) © [Mashape](https://www.mashape.com) +The above example will create a new `custom` client snippet generator for the `node` target. -[license-url]: https://github.com/Mashape/httpsnippet/blob/master/LICENSE +## Documentation -[travis-url]: https://travis-ci.org/Mashape/httpsnippet -[travis-image]: https://img.shields.io/travis/Mashape/httpsnippet.svg?style=flat-square +At the heart of this module is the [HAR Format](http://www.softwareishard.com/blog/har-12-spec/#request) as the HTTP request description format, please review some of the sample JSON HAR Request objects in [test fixtures](/test/fixtures/requests), or read the [HAR Docs](http://www.softwareishard.com/blog/har-12-spec/#request) for more details. -[npm-url]: https://www.npmjs.com/package/httpsnippet -[npm-license]: https://img.shields.io/npm/l/httpsnippet.svg?style=flat-square -[npm-version]: https://img.shields.io/npm/v/httpsnippet.svg?style=flat-square -[npm-downloads]: https://img.shields.io/npm/dm/httpsnippet.svg?style=flat-square +For detailed information on each target, please review the [wiki](https://github.com/Kong/httpsnippet/wiki). + +## Differences from `kong/httpsnippet` + +There are some major differences between this library and the [httpsnippet](https://github.com/Kong/httpsnippet) upstream: + +- Includes a full integration test suite for a handful of clients and targets. +- Does not ship with a CLI component. +- Does not do any HAR schema validation. It's just assumed that the HAR you're supplying to the library is already valid. +- The main `HTTPSnippet` export contains an `options` argument for an `harIsAlreadyEncoded` option for disabling [escaping](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) of cookies and query strings in URLs. + - We added this because all HARs that we interact with already have this data escaped and this option prevents them from being double encoded, thus corrupting the data. +- Does not support the `insecureSkipVerify` option on `go:native`, `node:native`, `ruby:native`, and `shell:curl` as we don't want snippets generated for our users to bypass SSL certificate verification. +- Includes a full plugin system, `#addClientPlugin`, for quick installation of a target client. +- Node + - `fetch` + - Body payloads are treated as an object literal and wrapped within `JSON.stringify()`. We do this to keep those targets looking nicer with those kinds of payloads. This also applies to the JS `fetch` target as well. + - `request` + - Does not provide query string parameters in a `params` argument due to complexities with query encoding. +- PHP + - `guzzle` + - Snippets have `require_once('vendor/autoload.php');` prefixed at the top. +- Python + - `python3` + - Does not ship this client due to its incompatibility with being able to support file uploads. + - `requests` + - Does not provide query string parameters in a `params` argument due to complexities with query encoding. -[codeclimate-url]: https://codeclimate.com/github/Mashape/httpsnippet -[codeclimate-quality]: https://img.shields.io/codeclimate/github/Mashape/httpsnippet.svg?style=flat-square -[codeclimate-coverage]: https://img.shields.io/codeclimate/coverage/github/Mashape/httpsnippet.svg?style=flat-square +## License -[david-url]: https://david-dm.org/Mashape/httpsnippet -[david-image]: https://img.shields.io/david/Mashape/httpsnippet.svg?style=flat-square +[MIT](LICENSE) © [Kong](https://konghq.com) -[gitter-url]: https://gitter.im/Mashape/httpsnippet -[gitter-image]: https://img.shields.io/badge/Gitter-Join%20Chat-blue.svg?style=flat-square +[license-url]: https://github.com/Kong/httpsnippet/blob/master/LICENSE +[npm-url]: https://www.npmjs.com/package/@readme/httpsnippet +[npm-license]: https://img.shields.io/npm/l/@readme/httpsnippet.svg?style=flat-square +[npm-version]: https://img.shields.io/npm/v/@readme/httpsnippet.svg?style=flat-square diff --git a/bin/httpsnippet b/bin/httpsnippet deleted file mode 100755 index fa2383a61..000000000 --- a/bin/httpsnippet +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env node - -'use strict' - -var chalk = require('chalk') -var cmd = require('commander') -var fs = require('fs') -var readFile = require('fs-readfile-promise') -var writeFile = require('fs-writefile-promise') -var HTTPSnippet = require('..') -var path = require('path') -var pkg = require('../package.json') - -cmd - .version(pkg.version) - .usage('[options] ') - .option('-t, --target ', 'target output') - .option('-c, --client [client]', 'target client library') - .option('-o, --output ', 'write output to directory') - .parse(process.argv) - -if (!cmd.args.length || !cmd.target) { - cmd.help() -} - -if (cmd.output) { - var dir = path.resolve(cmd.output) - - if (!fs.existsSync(dir)) { - fs.mkdirSync(dir) - } -} - -cmd.args.forEach(function (fileName) { - var file = path.basename(fileName) - - readFile(fileName) - .then(JSON.parse) - - .catch(function (e) { - console.error('%s %s failed to read JSON: %s', chalk.red('✖'), chalk.cyan.bold(file), chalk.red(e.message)) - }) - - .then(function (data) { - return new HTTPSnippet(data) - }) - - .catch(function (e) { - e.errors.forEach(function (err) { - console.error('%s %s failed validation: (%s: %s) %s', chalk.red('✖'), chalk.cyan.bold(file), chalk.cyan.italic(err.field), chalk.magenta.italic(err.value), chalk.red(err.message)) - }) - }) - - .then(function (snippet) { - return snippet.convert(cmd.target, cmd.client) - }) - - .then(function (output) { - // print - if (!cmd.output) { - return console.log('%s %s > %s [%s] :\n%s', chalk.green('✓'), chalk.cyan.bold(file), chalk.yellow(cmd.target), chalk.yellow(cmd.client ? cmd.client : 'default'), output) - } - - // write to file - var name = path.basename(file, path.extname(file)) - - var filename = path.format({ - dir: dir, - base: name + HTTPSnippet.extname(cmd.target) - }) - - return writeFile(filename, output + '\n', function () { - console.log('%s %s > %s', chalk.green('✓'), chalk.cyan.bold(file), filename) - }) - }) - - .catch(function (e) { - console.error('%s %s fail: %s', chalk.red('✖'), chalk.cyan.bold(file), chalk.red(e.message)) - }) -}) diff --git a/biome.jsonc b/biome.jsonc new file mode 100644 index 000000000..27a8f5fb0 --- /dev/null +++ b/biome.jsonc @@ -0,0 +1,55 @@ +{ + "$schema": "./node_modules/@biomejs/biome/configuration_schema.json", + "extends": ["@readme/standards/biome", "@readme/standards/biome/esm"], + "files": { + "ignoreUnknown": false, + "includes": ["**/*.{cjs,mjs,js,mts,ts}", "!coverage", "!dist", "!src/targets/**/fixtures"], + }, + "linter": { + "enabled": true, + "domains": { + "project": "all", + "test": "all", + }, + "rules": { + "correctness": { + // This is being flagged on Node built-ins. https://github.com/biomejs/biome/issues/8849 + "noUnresolvedImports": "off", + }, + "performance": { + "noAccumulatingSpread": "off", // @fixme + }, + "style": { + "noParameterAssign": "off", // @fixme + "useDefaultSwitchClause": "off", + }, + "suspicious": { + "noExplicitAny": "off", + "noPrototypeBuiltins": "off", + + // We unfortunatley have an `escape` option in our core targets that's being seen as + // shadowing the global `escape` function. + "noShadowRestrictedNames": "off", + }, + }, + }, + "overrides": [ + { + "includes": ["src/**/*.test.ts"], + "linter": { + "rules": { + "correctness": { + // Because we dynamically load test fixtures, and have to use `require` to do so, those + // files need to be `.cjs` files which collides with this extension as it wants them + // to be `.js`. + "useImportExtensions": "off", + + // For the same reasons as `useImportExtensions`, because we load in some `.cjs` files + // in tests those use `module.exports` and do not have a "default" export. + "noUnresolvedImports": "off", + }, + }, + }, + }, + ], +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 000000000..4acd614ca --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,116 @@ +version: '3' +services: + httpbin: + image: mccutchen/go-httpbin + command: ['/bin/go-httpbin', '-port', '8080'] + + # the job of this container is to: + # - host our fake "httpbin.org" + # - terminate SSL + # - forward both 443 and 80 to the httpbin + # + # see integrations/Caddyfile for its config + reverse_proxy: + image: caddy:2.6.4 + depends_on: + - httpbin + volumes: + - ./integrations/https-cert:/https-cert:ro + - ./integrations/Caddyfile:/etc/caddy/Caddyfile + environment: + - HTTPS_CERT_FILE=/https-cert/httpbin.org.pem + - HTTPS_KEY_FILE=/https-cert/httpbin.org-key.pem + networks: + default: + # on the `docker compose` network, this proxy will be aliased as + # httpbin.org. To make this work with HTTPS, each integration test + # container needs to install the root CA contained in + # ./integrations/https-cert/rootCA.pem + aliases: + - httpbin.org + + integration_node: + depends_on: + - reverse_proxy + build: + context: . + dockerfile: integrations/node.Dockerfile + command: 'npx vitest run src/integration.test.ts' + environment: + - HTTPBIN=true + - INTEGRATION_CLIENT=node + - NODE_ENV=integration + - NODE_EXTRA_CA_CERTS=/etc/ssl/certs/ca-certificates.crt + + integration_php: + depends_on: + - reverse_proxy + build: + context: . + dockerfile: integrations/php.Dockerfile + command: 'npx vitest run src/integration.test.ts' + environment: + - HTTPBIN=true + - INTEGRATION_CLIENT=php + - NODE_ENV=integration + + integration_python: + depends_on: + - reverse_proxy + build: + context: . + dockerfile: integrations/python.Dockerfile + command: 'npx vitest run src/integration.test.ts' + environment: + - HTTPBIN=true + - INTEGRATION_CLIENT=python + - NODE_ENV=integration + - REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt + + integration_shell: + depends_on: + - reverse_proxy + build: + context: . + dockerfile: integrations/shell.Dockerfile + command: 'npx vitest run src/integration.test.ts' + environment: + - HTTPBIN=true + - INTEGRATION_CLIENT=shell + - NODE_ENV=integration + + integration_csharp: + depends_on: + - reverse_proxy + build: + context: . + dockerfile: integrations/csharp.Dockerfile + command: 'npx vitest run src/integration.test.ts' + environment: + - HTTPBIN=true + - INTEGRATION_CLIENT=csharp + - NODE_ENV=integration + + integration_c: + depends_on: + - reverse_proxy + build: + context: . + dockerfile: integrations/c.Dockerfile + command: 'npx vitest run src/integration.test.ts' + environment: + - HTTPBIN=true + - INTEGRATION_CLIENT=c + - NODE_ENV=integration + + integration_golang: + depends_on: + - reverse_proxy + build: + context: . + dockerfile: integrations/go.Dockerfile + command: 'npx vitest run src/integration.test.ts' + environment: + - HTTPBIN=true + - INTEGRATION_CLIENT=go + - NODE_ENV=integration diff --git a/integrations/Caddyfile b/integrations/Caddyfile new file mode 100644 index 000000000..50e1540e4 --- /dev/null +++ b/integrations/Caddyfile @@ -0,0 +1,9 @@ +:443 { + reverse_proxy httpbin:8080 + tls /https-cert/httpbin.org.pem /https-cert/httpbin.org-key.pem +} + +:80 { + reverse_proxy httpbin:8080 +} + diff --git a/integrations/c.Dockerfile b/integrations/c.Dockerfile new file mode 100644 index 000000000..6aaac1c52 --- /dev/null +++ b/integrations/c.Dockerfile @@ -0,0 +1,22 @@ +FROM alpine:3.18 + +COPY integrations/https-cert/rootCA.pem /root/integration-test.pem + +# install the integration test certs +RUN apk --no-cache add ca-certificates && \ + rm -rf /var/cache/apk/* && \ + cp /root/integration-test.pem /usr/local/share/ca-certificates/ && \ + update-ca-certificates + +RUN apk update && \ + apk add build-base curl-dev libcurl nodejs npm openssl-dev + +WORKDIR /src + +# add package.json and run npm install so that we only re-do npm install if +# package.json has changed +ADD package.json /src/ +RUN npm install + +ADD . /src + diff --git a/integrations/csharp.Dockerfile b/integrations/csharp.Dockerfile new file mode 100644 index 000000000..c81b9ced0 --- /dev/null +++ b/integrations/csharp.Dockerfile @@ -0,0 +1,39 @@ +FROM node:20-alpine3.18 AS node +FROM mcr.microsoft.com/dotnet/sdk:7.0-alpine3.18 + +COPY integrations/https-cert/rootCA.pem /root/integration-test.pem + +# install the integration test certs +RUN apk --no-cache add ca-certificates && \ + rm -rf /var/cache/apk/* && \ + cp /root/integration-test.pem /usr/local/share/ca-certificates/ && \ + update-ca-certificates + +# copy node stuff from the node image to the dotnet image. Source for the +# necessary files: +# https://github.com/pyodide/pyodide/blob/1691d347d15a2c211cd49aebe6f15d42dfdf2369/Dockerfile#L105 +COPY --from=node /usr/local/bin/node /usr/local/bin/ +COPY --from=node /usr/local/lib/node_modules /usr/local/lib/node_modules +RUN ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \ + && ln -s ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx + +WORKDIR /src + +# - create a "hello world" project. We will later overwrite Program.cs in that +# folder with our test fixtures to run them +# - install RestSharp into that project +# - make a folder with the appropriate structure to hold the test fixtures +RUN dotnet new console -o IntTestCsharp -f net7.0 && \ + cd IntTestCsharp && \ + dotnet add package RestSharp && \ + mkdir -p /src/IntTestCsharp/src/fixtures/files + +# copy the only test fixture into the fixtures dir +ADD src/fixtures/files/hello.txt /src/IntTestCsharp/src/fixtures/files/ + +# add pacakge.json first so we don't have to `npm install` unless it changes +ADD package.json /src/ +RUN npm install + +# keep this last so that once this docker image is built it can be used quickly +ADD . /src diff --git a/integrations/go.Dockerfile b/integrations/go.Dockerfile new file mode 100644 index 000000000..721852b9f --- /dev/null +++ b/integrations/go.Dockerfile @@ -0,0 +1,23 @@ +FROM golang:1.20.5-alpine3.18 + +COPY integrations/https-cert/rootCA.pem /root/integration-test.pem + +# install the integration test certs +RUN apk --no-cache add ca-certificates && \ + rm -rf /var/cache/apk/* && \ + cp /root/integration-test.pem /usr/local/share/ca-certificates/ && \ + update-ca-certificates + +# XXX: do we eventually need to care about getting an exact version of node +# here? If so, see the csharp container for how to do that +RUN apk update && \ + apk add nodejs npm + +WORKDIR /src + +# add pacakge.json first so we don't have to `npm install` unless it changes +ADD package.json /src/ +RUN npm install + +# keep this last so that once this docker image is built it can be used quickly +ADD . /src diff --git a/integrations/https-cert/httpbin.org-key.pem b/integrations/https-cert/httpbin.org-key.pem new file mode 100644 index 000000000..1bc925262 --- /dev/null +++ b/integrations/https-cert/httpbin.org-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCfqXaAuBLPmLnD +uLFqOK4oJBLPds0+m+lkCVEwvcy8ph1/aVH4QvXf/i7kh5aBiO4+S+jx45CK5d/D +cUHU4ivnTu5zA4eIaqvY3PqrSjIYOLMDScHksOfTAVC1Up8CU6ymJWSP+Iz9lDuM +IG7g6N6v/vUhUTYWePbWfkl9GUFGakulwARxUSzjBpy/GaK9fI1SXb62DE4pdLoS +H5wWdpdGXalQlxXZxEEnkBHwTWfdKghJRzA9dHtZU7OtdUkMgE6D5AkxhkRlPPue +57VvVOD9lWbWI5rbOcQeorW5jVkH/R6xDEIlGyUOq6xwgnop+8tXQlgOFbgwZKBn +OQrnqN77AgMBAAECggEAUyDebEJquN+hyL++z7lXI9s0WARY9IIk0ErxlNkdYhNz +REVHwmTKs6caLy5RNHxg3tqTHG4JceghyxaK2hYwGazFBekOhf5UHwNfGBP3ZRkQ +S2P5qeJZsUj8BoxP8dwzBgZuB2+3qMenAVxZnoxgdW3fn0szSBwPGLqD9LhTfh9D +VPaTtk3xucLT7Q2p59Mr9i2LsLSpmlEqpou2kaqqlWqYbR7sogtb+NjkixojYOYh +j7GV+0ryL6ngWGYbGhAo64PQg/szsYmacR8vvUSiiUuxL6AYOxS03q/aGJtQootF +j2cHgk96u/6pwWAtnsu+QGqbN3bOHT0loKjkz5yvEQKBgQDOgwDwlFIerkBxlJi4 +NVrKMwPq22YFHQlFMHhLA8Y6cXe6NGBMSGcgfUIowyS+J+YHxlafKyHKoi8EVY/2 +aeWkAaTitC7pMKUm7m9IVZQuWxDBUdy3JaYBPqcXHSVtLz08NoW8gWvViGpGSo3B +5Q3J9LMTjwUnKwcLwMor3b5t9wKBgQDF7FbJs7hd5lqZqeJKkUbfAbCShUDozJkI +0Vcm1rCSIPMYNgMv5QBpZJHXzPjHRm1xOu/shTWN9ZQcozeorCcipB9W7V7cd8K6 +73L5EEv5up1LzpobsvWUPna+nPct9a4LAIP6tpVrUU6x/4dXTLyw8SzxUr1lpCdg +TJgnZ2pmHQKBgQChlXGTzIogxXlZJcsFP4IlehtTlY3S7HBHefB1yaM+MXBb+wVq +SrCehEPS/zXtr+xWIwO+ERKkqZgeTRCS3zM2y66HUDLwdQaUWrYqJAQI7WpDyVjo +2QV2Ld6xwDV7pB3G0mZ8I8wLTWzSSR14HFBYuCWyZRLEHe+qa5QFFMEe6wKBgQCw +cRiNh6H8U7bA9im9v/UmKSN3+0L6RirHKZhAD3QpUSZllwEQWV4cloNNlnTRcX9v +SdNJTxeHDj6TqQ2dWJsqzpUBsWq3sCvw6jXcwyJ35l0Dj5Lizo8PMQA6vUO9vR8C +v9roToy1ty4okFve/5HXS6l9GP2u9sADoUSjHBZGIQKBgD5TCut1OwE7Ph5eAQaH +drsEkEEuO8h/GcReNCwddU8ISBoWB6y7VIc9cxeO7LeIpL9ued7AEp394mM05HGW +szSs1fz/s7F9Rf+33CaEoAWBnSO5LhmcA5Ebof/8hl7qLLH13x9UDgPtudbRwwnA +zHeF1qwdjvqOQVcebkyo0+Hl +-----END PRIVATE KEY----- diff --git a/integrations/https-cert/httpbin.org.pem b/integrations/https-cert/httpbin.org.pem new file mode 100644 index 000000000..417641904 --- /dev/null +++ b/integrations/https-cert/httpbin.org.pem @@ -0,0 +1,25 @@ +-----BEGIN CERTIFICATE----- +MIIEMzCCApugAwIBAgIRAMzWAqhcZaKPLXJ5TE4l1TMwDQYJKoZIhvcNAQELBQAw +dzEeMBwGA1UEChMVbWtjZXJ0IGRldmVsb3BtZW50IENBMSYwJAYDVQQLDB1sbGlt +bGxpYkBhZGFtYSAoV2lsbGlhbSBNaWxsKTEtMCsGA1UEAwwkbWtjZXJ0IGxsaW1s +bGliQGFkYW1hIChXaWxsaWFtIE1pbGwpMB4XDTIzMDYxODAwNDA1MFoXDTI1MDkx +ODAwNDA1MFowUTEnMCUGA1UEChMebWtjZXJ0IGRldmVsb3BtZW50IGNlcnRpZmlj +YXRlMSYwJAYDVQQLDB1sbGltbGxpYkBhZGFtYSAoV2lsbGlhbSBNaWxsKTCCASIw +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ+pdoC4Es+YucO4sWo4rigkEs92 +zT6b6WQJUTC9zLymHX9pUfhC9d/+LuSHloGI7j5L6PHjkIrl38NxQdTiK+dO7nMD +h4hqq9jc+qtKMhg4swNJweSw59MBULVSnwJTrKYlZI/4jP2UO4wgbuDo3q/+9SFR +NhZ49tZ+SX0ZQUZqS6XABHFRLOMGnL8Zor18jVJdvrYMTil0uhIfnBZ2l0ZdqVCX +FdnEQSeQEfBNZ90qCElHMD10e1lTs611SQyAToPkCTGGRGU8+57ntW9U4P2VZtYj +mts5xB6itbmNWQf9HrEMQiUbJQ6rrHCCein7y1dCWA4VuDBkoGc5Cueo3vsCAwEA +AaNgMF4wDgYDVR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMB8GA1Ud +IwQYMBaAFPmwtEydRa+QvWvDsgTF0I67b664MBYGA1UdEQQPMA2CC2h0dHBiaW4u +b3JnMA0GCSqGSIb3DQEBCwUAA4IBgQB0KyoE2O4ZdLHlAa7rzk77kVX47xCfAso7 +zl0JA2Xrq74Ivx6mOpDIjVrYuWiDjb7KQtD//Zx0sSdj4VknXJ2eadSWvVAXhK9b +PZ1aEAFPADtnqwJ2yWeT57TcFOGwVa14tU5FnETevQ55sprTzLJf9I0NQqoEBvf3 +gM36+Ov9a0DH8q2u24V1q1/jzA8wiOmuQLdwKeaY2tRF0VfH1VPPwuok6LfZ+w+c +A/0Bkk1YZHioAKkejMJCqnrI8mU3KpAAm3ciaSbkYzo36XKpHEcTw5KuOZXmCnvf +J/ebX7Upz32QMPNZGF/tRol/AEPEe9m0ze7TKo6ntKm2ITC3eU8qr64qmjI1YjyA +LY8KC74xhM4m6+Wq3x8q+7WTrZG3LCneeHAimeaMqh6s1K8KWU1LCNo18UghfE7R +yHSl/Lsii3UsPowyeg5s9MxEbxuZAv0rKR8TAGArFvKX27eS6JIVHjU2inkwJLim +gTJEW1e0bjBTdS2mDNVRY4/oU5bMVbs= +-----END CERTIFICATE----- diff --git a/integrations/https-cert/make.sh b/integrations/https-cert/make.sh new file mode 100755 index 000000000..3e6266753 --- /dev/null +++ b/integrations/https-cert/make.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash + +# install https://github.com/FiloSottile/mkcert +mkcert httpbin.org +cp "$(mkcert -CAROOT)"/rootCA.pem . diff --git a/integrations/https-cert/rootCA.pem b/integrations/https-cert/rootCA.pem new file mode 100644 index 000000000..3a8188715 --- /dev/null +++ b/integrations/https-cert/rootCA.pem @@ -0,0 +1,28 @@ +-----BEGIN CERTIFICATE----- +MIIEvjCCAyagAwIBAgIRAIGeVWB23wmaHLVpiVNwUVgwDQYJKoZIhvcNAQELBQAw +dzEeMBwGA1UEChMVbWtjZXJ0IGRldmVsb3BtZW50IENBMSYwJAYDVQQLDB1sbGlt +bGxpYkBhZGFtYSAoV2lsbGlhbSBNaWxsKTEtMCsGA1UEAwwkbWtjZXJ0IGxsaW1s +bGliQGFkYW1hIChXaWxsaWFtIE1pbGwpMB4XDTIzMDYxNzE2Mjc1NFoXDTMzMDYx +NzE2Mjc1NFowdzEeMBwGA1UEChMVbWtjZXJ0IGRldmVsb3BtZW50IENBMSYwJAYD +VQQLDB1sbGltbGxpYkBhZGFtYSAoV2lsbGlhbSBNaWxsKTEtMCsGA1UEAwwkbWtj +ZXJ0IGxsaW1sbGliQGFkYW1hIChXaWxsaWFtIE1pbGwpMIIBojANBgkqhkiG9w0B +AQEFAAOCAY8AMIIBigKCAYEAuHKpfZuUexcqU0F1UzFOyhyF0FQWFxIJu6fhq6rH +/0jYwZdaIwiMiHwFMim42duYJlNZoFmD5msNZi4pP8T8reNUUhgt9ki57rsfGQ99 +arMXZ2o24TP1WMDz3+38jF2UVrT0ZFJ7A9vQYNUdKFxoNvZMC/VS0/Vwg31Jw1wA +Je+AJauoMDjtOQNU6vMLloVrXu//S1bYI3k7ph/7HSAQsNhYA18tW9bClEkC0gtu +mbtzIwvmiuu7bTUSlYQyHMtAE/1RZ9HfTamDtvfFu3k2/mJNuYecGwL0enNhdBng +1ic4iXlDKu6UKBiZK35AgzMntrgusX2Bj7qOmOPoDN88D6qvvwXwqshg+ZYlRDY9 +nCUGAqGo8qs5gx4fEp8GUkCtqFPF/hmh4q8qrjV+XnLI0mtaI8Kql+uxgoa3n55q +dvegCi8dRWXd13ZsrF7o58i5LfsENOYH+SyPtvUc9k7koLUUPK6GuDkNb5kHfX6L +bbSJysK3vzL4A50KfvyYRjMHAgMBAAGjRTBDMA4GA1UdDwEB/wQEAwICBDASBgNV +HRMBAf8ECDAGAQH/AgEAMB0GA1UdDgQWBBT5sLRMnUWvkL1rw7IExdCOu2+uuDAN +BgkqhkiG9w0BAQsFAAOCAYEAdixhKiObZ0eyE1bCRjkVwZKnwAM6/mZpdP3JFpXD +WaLfMZup2nCFJJP40bxq32DU99hqdlRVi8+tQfbsayOwPxGNxbB00R7bNRHNwx1h +FyTCW3kEnbirFyOnN275PBA7n6ZZR3NO9MbxKLSMpDbf2t76Z1mUwCrophekcUlt +XeTzlCItcRzt0g2JZReFds3zVjGxhhdR/n5jV30meY/rTyCjK5TDMCsBlpzsVD5s +CfiSjUIqWVCREBri7VPZweygbYMqI9amrKM8dt1HNjbYppLGsn4ljVW/4hMEqJrw +YJZ/yT9llZDrta1HpzTw50frOt4AppOuW6pvaXeurWvV9hMYLUgg3fo/CuXxCg3A +8EEv3BtDHsb4QvpX7VLmFih/PfZ0E0i4RAH72IRFWpJo/wfUJkdowBk/AfoyG/cj +0gBjNBj69Vd2AQrhX5VG4Qon7iB9YqmLbZItXQrKaonQ3obV19tHJdoW4grxVcq5 +dGqaxsY5xfGMztMqXH3ardCx +-----END CERTIFICATE----- diff --git a/integrations/node.Dockerfile b/integrations/node.Dockerfile new file mode 100755 index 000000000..f599f3082 --- /dev/null +++ b/integrations/node.Dockerfile @@ -0,0 +1,19 @@ +FROM node:18-alpine + +COPY integrations/https-cert/rootCA.pem /root/integration-test.pem + +# install the integration test certs +RUN apk --no-cache add ca-certificates && \ + rm -rf /var/cache/apk/* && \ + cp /root/integration-test.pem /usr/local/share/ca-certificates/ && \ + update-ca-certificates + +WORKDIR /src + +ADD package.json /src/ + +# https://www.npmjs.com/package/axios +RUN npm install axios && \ + npm install + +ADD . /src diff --git a/integrations/php.Dockerfile b/integrations/php.Dockerfile new file mode 100644 index 000000000..1a90f0605 --- /dev/null +++ b/integrations/php.Dockerfile @@ -0,0 +1,28 @@ +FROM composer as builder +WORKDIR /composer/ + +# https://packagist.org/packages/guzzlehttp/guzzle +RUN composer require guzzlehttp/guzzle + +FROM alpine:3.18 + +COPY integrations/https-cert/rootCA.pem /root/integration-test.pem +COPY --from=builder /composer/vendor /src/vendor + +# install the integration test certs +RUN apk --no-cache add ca-certificates && \ + rm -rf /var/cache/apk/* && \ + cp /root/integration-test.pem /usr/local/share/ca-certificates/ && \ + update-ca-certificates + +RUN apk update && \ + apk add nodejs npm php81 php81-fpm php81-opcache php81-curl + +WORKDIR /src + +# add package.json and run npm install so that we only re-do npm install if +# package.json has changed +ADD package.json /src/ +RUN npm install + +ADD . /src diff --git a/integrations/python.Dockerfile b/integrations/python.Dockerfile new file mode 100644 index 000000000..864965702 --- /dev/null +++ b/integrations/python.Dockerfile @@ -0,0 +1,23 @@ +FROM alpine:3.18 + +COPY integrations/https-cert/rootCA.pem /root/integration-test.pem + +# install the integration test certs +RUN apk --no-cache add ca-certificates && \ + rm -rf /var/cache/apk/* && \ + cp /root/integration-test.pem /usr/local/share/ca-certificates/ && \ + update-ca-certificates + +RUN apk update && \ + apk add nodejs npm python3 py3-pip && \ + pip install requests + +WORKDIR /src + +# add package.json and run npm install so that we only re-do npm install if +# package.json has changed +ADD package.json /src/ +RUN npm install + +ADD . /src + diff --git a/integrations/shell.Dockerfile b/integrations/shell.Dockerfile new file mode 100644 index 000000000..0d6297b96 --- /dev/null +++ b/integrations/shell.Dockerfile @@ -0,0 +1,21 @@ +FROM alpine:3.18 + +COPY integrations/https-cert/rootCA.pem /root/integration-test.pem + +# install the integration test cert, curl, and node +RUN apk --no-cache add ca-certificates && \ + rm -rf /var/cache/apk/* && \ + cp /root/integration-test.pem /usr/local/share/ca-certificates/ && \ + update-ca-certificates && \ + apk update && \ + apk add curl && \ + apk add --update nodejs npm + +WORKDIR /src + +# add package.json and run npm install so that we only re-do npm install if +# package.json has changed +ADD package.json /src/ +RUN npm install + +ADD . /src diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 000000000..43454bf85 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,2630 @@ +{ + "name": "@readme/httpsnippet", + "version": "11.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@readme/httpsnippet", + "version": "11.1.0", + "license": "MIT", + "dependencies": { + "qs": "^6.15.0", + "stringify-object": "^3.3.0", + "type-fest": "^5.4.4" + }, + "devDependencies": { + "@biomejs/biome": "^2.4.4", + "@readme/standards": "^2.2.0", + "@types/har-format": "^1.2.15", + "@types/node": "^25.3.0", + "@types/qs": "^6.9.10", + "@types/stringify-object": "^4.0.5", + "@vitest/coverage-v8": "^4.0.2", + "prettier": "^3.0.3", + "require-directory": "^2.1.1", + "tsup": "^8.0.1", + "typescript": "^5.8.3", + "vitest": "^4.0.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.28.5.tgz", + "integrity": "sha512-KKBU1VGYR7ORr3At5HAtUQ+TV3SzRCXmA/8OdDZiLDBIZxVyzXuztPjfLd3BV1PRAQGCMWWSHYhL0F8d5uHBDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.5" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.5.tgz", + "integrity": "sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bcoe/v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz", + "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@biomejs/biome": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.4.4.tgz", + "integrity": "sha512-tigwWS5KfJf0cABVd52NVaXyAVv4qpUXOWJ1rxFL8xF1RVoeS2q/LK+FHgYoKMclJCuRoCWAPy1IXaN9/mS61Q==", + "dev": true, + "license": "MIT OR Apache-2.0", + "bin": { + "biome": "bin/biome" + }, + "engines": { + "node": ">=14.21.3" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/biome" + }, + "optionalDependencies": { + "@biomejs/cli-darwin-arm64": "2.4.4", + "@biomejs/cli-darwin-x64": "2.4.4", + "@biomejs/cli-linux-arm64": "2.4.4", + "@biomejs/cli-linux-arm64-musl": "2.4.4", + "@biomejs/cli-linux-x64": "2.4.4", + "@biomejs/cli-linux-x64-musl": "2.4.4", + "@biomejs/cli-win32-arm64": "2.4.4", + "@biomejs/cli-win32-x64": "2.4.4" + } + }, + "node_modules/@biomejs/cli-darwin-arm64": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.4.4.tgz", + "integrity": "sha512-jZ+Xc6qvD6tTH5jM6eKX44dcbyNqJHssfl2nnwT6vma6B1sj7ZLTGIk6N5QwVBs5xGN52r3trk5fgd3sQ9We9A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-darwin-x64": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.4.4.tgz", + "integrity": "sha512-Dh1a/+W+SUCXhEdL7TiX3ArPTFCQKJTI1mGncZNWfO+6suk+gYA4lNyJcBB+pwvF49uw0pEbUS49BgYOY4hzUg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.4.4.tgz", + "integrity": "sha512-V/NFfbWhsUU6w+m5WYbBenlEAz8eYnSqRMDMAW3K+3v0tYVkNyZn8VU0XPxk/lOqNXLSCCrV7FmV/u3SjCBShg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64-musl": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.4.4.tgz", + "integrity": "sha512-+sPAXq3bxmFwhVFJnSwkSF5Rw2ZAJMH3MF6C9IveAEOdSpgajPhoQhbbAK12SehN9j2QrHpk4J/cHsa/HqWaYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.4.4.tgz", + "integrity": "sha512-R4+ZCDtG9kHArasyBO+UBD6jr/FcFCTH8QkNTOCu0pRJzCWyWC4EtZa2AmUZB5h3e0jD7bRV2KvrENcf8rndBg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64-musl": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.4.4.tgz", + "integrity": "sha512-gGvFTGpOIQDb5CQ2VC0n9Z2UEqlP46c4aNgHmAMytYieTGEcfqhfCFnhs6xjt0S3igE6q5GLuIXtdQt3Izok+g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-arm64": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.4.4.tgz", + "integrity": "sha512-trzCqM7x+Gn832zZHgr28JoYagQNX4CZkUZhMUac2YxvvyDRLJDrb5m9IA7CaZLlX6lTQmADVfLEKP1et1Ma4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-x64": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.4.4.tgz", + "integrity": "sha512-gnOHKVPFAAPrpoPt2t+Q6FZ7RPry/FDV3GcpU53P3PtLNnQjBmKyN2Vh/JtqXet+H4pme8CC76rScwdjDcT1/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz", + "integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz", + "integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz", + "integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz", + "integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.2.tgz", + "integrity": "sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz", + "integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz", + "integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz", + "integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz", + "integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz", + "integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz", + "integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz", + "integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz", + "integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz", + "integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz", + "integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz", + "integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz", + "integrity": "sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz", + "integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz", + "integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz", + "integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz", + "integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz", + "integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz", + "integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz", + "integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz", + "integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz", + "integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.5.tgz", + "integrity": "sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==", + "dev": true, + "dependencies": { + "@jridgewell/set-array": "^1.2.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz", + "integrity": "sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz", + "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@readme/standards": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@readme/standards/-/standards-2.4.0.tgz", + "integrity": "sha512-ThoYbjLk1d10EiBiiN8u8hdJv51GRJanU6yILBexQZE4+aGfFn7O+is/2izVE2Xgj2p8LhLLgYhoeR0SUfe0tQ==", + "dev": true, + "license": "ISC", + "optionalDependencies": { + "@biomejs/biome": "^2.2.3", + "prettier": "^3.6.2" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.44.1.tgz", + "integrity": "sha512-JAcBr1+fgqx20m7Fwe1DxPUl/hPkee6jA6Pl7n1v2EFiktAHenTaXl5aIFjUIEsfn9w3HE4gK1lEgNGMzBDs1w==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.44.1.tgz", + "integrity": "sha512-RurZetXqTu4p+G0ChbnkwBuAtwAbIwJkycw1n6GvlGlBuS4u5qlr5opix8cBAYFJgaY05TWtM+LaoFggUmbZEQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.44.1.tgz", + "integrity": "sha512-fM/xPesi7g2M7chk37LOnmnSTHLG/v2ggWqKj3CCA1rMA4mm5KVBT1fNoswbo1JhPuNNZrVwpTvlCVggv8A2zg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.44.1.tgz", + "integrity": "sha512-gDnWk57urJrkrHQ2WVx9TSVTH7lSlU7E3AFqiko+bgjlh78aJ88/3nycMax52VIVjIm3ObXnDL2H00e/xzoipw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.44.1.tgz", + "integrity": "sha512-wnFQmJ/zPThM5zEGcnDcCJeYJgtSLjh1d//WuHzhf6zT3Md1BvvhJnWoy+HECKu2bMxaIcfWiu3bJgx6z4g2XA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.44.1.tgz", + "integrity": "sha512-uBmIxoJ4493YATvU2c0upGz87f99e3wop7TJgOA/bXMFd2SvKCI7xkxY/5k50bv7J6dw1SXT4MQBQSLn8Bb/Uw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.44.1.tgz", + "integrity": "sha512-n0edDmSHlXFhrlmTK7XBuwKlG5MbS7yleS1cQ9nn4kIeW+dJH+ExqNgQ0RrFRew8Y+0V/x6C5IjsHrJmiHtkxQ==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.44.1.tgz", + "integrity": "sha512-8WVUPy3FtAsKSpyk21kV52HCxB+me6YkbkFHATzC2Yd3yuqHwy2lbFL4alJOLXKljoRw08Zk8/xEj89cLQ/4Nw==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.44.1.tgz", + "integrity": "sha512-yuktAOaeOgorWDeFJggjuCkMGeITfqvPgkIXhDqsfKX8J3jGyxdDZgBV/2kj/2DyPaLiX6bPdjJDTu9RB8lUPQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.44.1.tgz", + "integrity": "sha512-W+GBM4ifET1Plw8pdVaecwUgxmiH23CfAUj32u8knq0JPFyK4weRy6H7ooxYFD19YxBulL0Ktsflg5XS7+7u9g==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loongarch64-gnu": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loongarch64-gnu/-/rollup-linux-loongarch64-gnu-4.44.1.tgz", + "integrity": "sha512-1zqnUEMWp9WrGVuVak6jWTl4fEtrVKfZY7CvcBmUUpxAJ7WcSowPSAWIKa/0o5mBL/Ij50SIf9tuirGx63Ovew==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-powerpc64le-gnu": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.44.1.tgz", + "integrity": "sha512-Rl3JKaRu0LHIx7ExBAAnf0JcOQetQffaw34T8vLlg9b1IhzcBgaIdnvEbbsZq9uZp3uAH+JkHd20Nwn0h9zPjA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.44.1.tgz", + "integrity": "sha512-j5akelU3snyL6K3N/iX7otLBIl347fGwmd95U5gS/7z6T4ftK288jKq3A5lcFKcx7wwzb5rgNvAg3ZbV4BqUSw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.44.1.tgz", + "integrity": "sha512-ppn5llVGgrZw7yxbIm8TTvtj1EoPgYUAbfw0uDjIOzzoqlZlZrLJ/KuiE7uf5EpTpCTrNt1EdtzF0naMm0wGYg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.44.1.tgz", + "integrity": "sha512-Hu6hEdix0oxtUma99jSP7xbvjkUM/ycke/AQQ4EC5g7jNRLLIwjcNwaUy95ZKBJJwg1ZowsclNnjYqzN4zwkAw==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.44.1.tgz", + "integrity": "sha512-EtnsrmZGomz9WxK1bR5079zee3+7a+AdFlghyd6VbAjgRJDbTANJ9dcPIPAi76uG05micpEL+gPGmAKYTschQw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.44.1.tgz", + "integrity": "sha512-iAS4p+J1az6Usn0f8xhgL4PaU878KEtutP4hqw52I4IO6AGoyOkHCxcc4bqufv1tQLdDWFx8lR9YlwxKuv3/3g==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.44.1.tgz", + "integrity": "sha512-NtSJVKcXwcqozOl+FwI41OH3OApDyLk3kqTJgx8+gp6On9ZEt5mYhIsKNPGuaZr3p9T6NWPKGU/03Vw4CNU9qg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.44.1.tgz", + "integrity": "sha512-JYA3qvCOLXSsnTR3oiyGws1Dm0YTuxAAeaYGVlGpUsHqloPcFjPg+X0Fj2qODGLNwQOAcCiQmHub/V007kiH5A==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.44.1.tgz", + "integrity": "sha512-J8o22LuF0kTe7m+8PvW9wk3/bRq5+mRo5Dqo6+vXb7otCm3TPhYOJqOaQtGU9YMWQSL3krMnoOxMr0+9E6F3Ug==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true + }, + "node_modules/@types/har-format": { + "version": "1.2.16", + "resolved": "https://registry.npmjs.org/@types/har-format/-/har-format-1.2.16.tgz", + "integrity": "sha512-fluxdy7ryD3MV6h8pTfTYpy/xQzCFC7m89nOH9y94cNqJ1mDIDPut7MnRHI3F6qRmh/cT2fUjG1MLdCNb4hE9A==", + "dev": true + }, + "node_modules/@types/node": { + "version": "25.3.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.3.0.tgz", + "integrity": "sha512-4K3bqJpXpqfg2XKGK9bpDTc6xO/xoUP/RBWS7AtRMug6zZFaRekiLzjVtAoZMquxoAbzBvy5nxQ7veS5eYzf8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.18.0" + } + }, + "node_modules/@types/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/stringify-object": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@types/stringify-object/-/stringify-object-4.0.5.tgz", + "integrity": "sha512-TzX5V+njkbJ8iJ0mrj+Vqveep/1JBH4SSA3J2wYrE1eUrOhdsjTBCb0kao4EquSQ8KgPpqY4zSVP2vCPWKBElg==", + "dev": true + }, + "node_modules/@vitest/coverage-v8": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.0.18.tgz", + "integrity": "sha512-7i+N2i0+ME+2JFZhfuz7Tg/FqKtilHjGyGvoHYQ6iLV0zahbsJ9sljC9OcFcPDbhYKCet+sG8SsVqlyGvPflZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^1.0.2", + "@vitest/utils": "4.0.18", + "ast-v8-to-istanbul": "^0.3.10", + "istanbul-lib-coverage": "^3.2.2", + "istanbul-lib-report": "^3.0.1", + "istanbul-reports": "^3.2.0", + "magicast": "^0.5.1", + "obug": "^2.1.1", + "std-env": "^3.10.0", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@vitest/browser": "4.0.18", + "vitest": "4.0.18" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + } + }, + "node_modules/@vitest/expect": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.0.18.tgz", + "integrity": "sha512-8sCWUyckXXYvx4opfzVY03EOiYVxyNrHS5QxX3DAIi5dpJAAkyJezHCP77VMX4HKA2LDT/Jpfo8i2r5BE3GnQQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.0.18", + "@vitest/utils": "4.0.18", + "chai": "^6.2.1", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.0.18.tgz", + "integrity": "sha512-HhVd0MDnzzsgevnOWCBj5Otnzobjy5wLBe4EdeeFGv8luMsGcYqDuFRMcttKWZA5vVO8RFjexVovXvAM4JoJDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.0.18", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.0.18.tgz", + "integrity": "sha512-P24GK3GulZWC5tz87ux0m8OADrQIUVDPIjjj65vBXYG17ZeU3qD7r+MNZ1RNv4l8CGU2vtTRqixrOi9fYk/yKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.0.18.tgz", + "integrity": "sha512-rpk9y12PGa22Jg6g5M3UVVnTS7+zycIGk9ZNGN+m6tZHKQb7jrP7/77WfZy13Y/EUDd52NDsLRQhYKtv7XfPQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.0.18", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.0.18.tgz", + "integrity": "sha512-PCiV0rcl7jKQjbgYqjtakly6T1uwv/5BQ9SwBLekVg/EaYeQFPiXcgrC2Y7vDMA8dM1SUEAEV82kgSQIlXNMvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.0.18", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.0.18.tgz", + "integrity": "sha512-cbQt3PTSD7P2OARdVW3qWER5EGq7PHlvE+QfzSC0lbwO+xnt7+XH06ZzFjFRgzUX//JmpxrCu92VdwvEPlWSNw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.0.18.tgz", + "integrity": "sha512-msMRKLMVLWygpK3u2Hybgi4MNjcYJvwTb0Ru09+fOyCXIgT5raYP041DRRdiJiI3k/2U6SEbAETB3YtBrUkCFA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.0.18", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/acorn": { + "version": "8.14.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.1.tgz", + "integrity": "sha512-OvQ/2pUDKmgfCg++xsTX1wGxfTaszcHVcTctW4UJB4hibJx2HXxxO5UmVgyjMa+ZDsiaf5wWLXYpRWMmBI0QHg==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "dev": true + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/ast-v8-to-istanbul": { + "version": "0.3.11", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-0.3.11.tgz", + "integrity": "sha512-Qya9fkoofMjCBNVdWINMjB5KZvkYfaO9/anwkWnjxibpWUxo5iHl2sOdP7/uAqaRuUYuoo8rDwnbaaKVFxoUvw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "estree-walker": "^3.0.3", + "js-tokens": "^10.0.0" + } + }, + "node_modules/bundle-require": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz", + "integrity": "sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==", + "dev": true, + "license": "MIT", + "dependencies": { + "load-tsconfig": "^0.2.3" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "peerDependencies": { + "esbuild": ">=0.18" + } + }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "dev": true, + "engines": { + "node": ">= 6" + } + }, + "node_modules/confbox": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", + "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/consola": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.0.tgz", + "integrity": "sha512-EiPU8G6dQG0GFHNR8ljnZFki/8a+cQwEQ+7wpxdChl02Q8HXlwEZWD5lqAF8vC2sEC3Tehr8hy7vErz88LHyUA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.10.0" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/esbuild": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz", + "integrity": "sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.2", + "@esbuild/android-arm": "0.27.2", + "@esbuild/android-arm64": "0.27.2", + "@esbuild/android-x64": "0.27.2", + "@esbuild/darwin-arm64": "0.27.2", + "@esbuild/darwin-x64": "0.27.2", + "@esbuild/freebsd-arm64": "0.27.2", + "@esbuild/freebsd-x64": "0.27.2", + "@esbuild/linux-arm": "0.27.2", + "@esbuild/linux-arm64": "0.27.2", + "@esbuild/linux-ia32": "0.27.2", + "@esbuild/linux-loong64": "0.27.2", + "@esbuild/linux-mips64el": "0.27.2", + "@esbuild/linux-ppc64": "0.27.2", + "@esbuild/linux-riscv64": "0.27.2", + "@esbuild/linux-s390x": "0.27.2", + "@esbuild/linux-x64": "0.27.2", + "@esbuild/netbsd-arm64": "0.27.2", + "@esbuild/netbsd-x64": "0.27.2", + "@esbuild/openbsd-arm64": "0.27.2", + "@esbuild/openbsd-x64": "0.27.2", + "@esbuild/openharmony-arm64": "0.27.2", + "@esbuild/sunos-x64": "0.27.2", + "@esbuild/win32-arm64": "0.27.2", + "@esbuild/win32-ia32": "0.27.2", + "@esbuild/win32-x64": "0.27.2" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.2.2.tgz", + "integrity": "sha512-JhFGDVJ7tmDJItKhYgJCGLOWjuK9vPxiXoUFLwLDc99NlmklilbiQJwoctZtt13+xMw91MCk/REan6MWHqDjyA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fix-dts-default-cjs-exports": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz", + "integrity": "sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "magic-string": "^0.30.17", + "mlly": "^1.7.4", + "rollup": "^4.34.8" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-own-enumerable-property-symbols": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.2.tgz", + "integrity": "sha512-I0UBV/XOz1XkIJHEUDMZAbzCThU/H8DxmSfmdGcKPnVhu2VfFqr34jr9777IyaTYvxjedWhqVIilEDsCdP5G6g==" + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true, + "license": "MIT" + }, + "node_modules/is-obj": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", + "integrity": "sha512-l4RyHgRqGN4Y3+9JHVrNqO+tN0rV5My76uW5/nuO4K1b6vw5G8d/cmFjP9tRfEsdhZNt0IFdZuK/c2Vr4Nb+Qg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-regexp": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-regexp/-/is-regexp-1.0.0.tgz", + "integrity": "sha512-7zjFAPO4/gwyQAAgRRmqeEeyIICSdmCqa3tsVHMdBzaXXRiqopZL4Cyghg/XulGWrtABTpbnYYzzIRffLkP4oA==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", + "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-reports": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", + "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/joycon": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz", + "integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==", + "dev": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/js-tokens": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", + "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/lilconfig": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.2.tgz", + "integrity": "sha512-eop+wDAvpItUys0FWkHIKeC9ybYrTGbU41U5K7+bttZZeohvnY7M9dZ5kB21GNWiFT2q1OoPTvncPCgSOVO5ow==", + "dev": true, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true + }, + "node_modules/load-tsconfig": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/load-tsconfig/-/load-tsconfig-0.2.5.tgz", + "integrity": "sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/magicast": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.1.tgz", + "integrity": "sha512-xrHS24IxaLrvuo613F719wvOIv9xPHFWQHuvGUBmPnCA/3MQxKI3b+r7n1jAoDHmsbC5bRhTZYR77invLAxVnw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.28.5", + "@babel/types": "^7.28.5", + "source-map-js": "^1.2.1" + } + }, + "node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mlly": { + "version": "1.7.4", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.7.4.tgz", + "integrity": "sha512-qmdSIPC4bDJXgZTCR7XosJiNKySV7O215tsPtDN9iEO/7q/76b/ijtgRu/+epFXSJhijtTCCGp3DWS549P3xKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "acorn": "^8.14.0", + "pathe": "^2.0.1", + "pkg-types": "^1.3.0", + "ufo": "^1.5.4" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true + }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "dev": true, + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.3", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.3.tgz", + "integrity": "sha512-kDCGIbxkDSXE3euJZZXzc6to7fCrKHNI/hSRQnRuQ+BWjFNzZwiFF8fj/6o2t2G9/jTj8PSIYTfCLelLZEeRpA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/obug": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz", + "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT" + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pirates": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.6.tgz", + "integrity": "sha512-saLsH7WeYYPiD25LDuLRRY/i+6HaPYr6G1OUlN39otzkSTxKnubR9RTxS3/Kk50s1g2JTgFwWQDQyplC5/SHZg==", + "dev": true, + "engines": { + "node": ">= 6" + } + }, + "node_modules/pkg-types": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", + "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "confbox": "^0.1.8", + "mlly": "^1.7.4", + "pathe": "^2.0.1" + } + }, + "node_modules/postcss": { + "version": "8.5.6", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", + "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-load-config": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz", + "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "lilconfig": "^3.1.1" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "jiti": ">=1.21.0", + "postcss": ">=8.0.9", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + }, + "postcss": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/prettier": { + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.1.tgz", + "integrity": "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/qs": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.0.tgz", + "integrity": "sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rollup": { + "version": "4.44.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.44.1.tgz", + "integrity": "sha512-x8H8aPvD+xbl0Do8oez5f5o8eMS3trfCghc4HhLAnCkj7Vl0d1JWGs0UF/D886zLW2rOj2QymV/JcSSsw+XDNg==", + "dev": true, + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.44.1", + "@rollup/rollup-android-arm64": "4.44.1", + "@rollup/rollup-darwin-arm64": "4.44.1", + "@rollup/rollup-darwin-x64": "4.44.1", + "@rollup/rollup-freebsd-arm64": "4.44.1", + "@rollup/rollup-freebsd-x64": "4.44.1", + "@rollup/rollup-linux-arm-gnueabihf": "4.44.1", + "@rollup/rollup-linux-arm-musleabihf": "4.44.1", + "@rollup/rollup-linux-arm64-gnu": "4.44.1", + "@rollup/rollup-linux-arm64-musl": "4.44.1", + "@rollup/rollup-linux-loongarch64-gnu": "4.44.1", + "@rollup/rollup-linux-powerpc64le-gnu": "4.44.1", + "@rollup/rollup-linux-riscv64-gnu": "4.44.1", + "@rollup/rollup-linux-riscv64-musl": "4.44.1", + "@rollup/rollup-linux-s390x-gnu": "4.44.1", + "@rollup/rollup-linux-x64-gnu": "4.44.1", + "@rollup/rollup-linux-x64-musl": "4.44.1", + "@rollup/rollup-win32-arm64-msvc": "4.44.1", + "@rollup/rollup-win32-ia32-msvc": "4.44.1", + "@rollup/rollup-win32-x64-msvc": "4.44.1", + "fsevents": "~2.3.2" + } + }, + "node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/source-map": { + "version": "0.7.6", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz", + "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">= 12" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, + "node_modules/stringify-object": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/stringify-object/-/stringify-object-3.3.0.tgz", + "integrity": "sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw==", + "dependencies": { + "get-own-enumerable-property-symbols": "^3.0.0", + "is-obj": "^1.0.1", + "is-regexp": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/sucrase": { + "version": "3.35.1", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", + "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "tinyglobby": "^0.2.11", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tagged-tag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz", + "integrity": "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "dev": true, + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "dev": true, + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyrainbow": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.0.3.tgz", + "integrity": "sha512-PSkbLUoxOFRzJYjjxHJt9xro7D+iilgMX/C9lawzVuYiIdcihh9DXmVibBe8lmcFrRi/VzlPjBxbN7rH24q8/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", + "dev": true, + "bin": { + "tree-kill": "cli.js" + } + }, + "node_modules/ts-interface-checker": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", + "dev": true + }, + "node_modules/tsup": { + "version": "8.5.1", + "resolved": "https://registry.npmjs.org/tsup/-/tsup-8.5.1.tgz", + "integrity": "sha512-xtgkqwdhpKWr3tKPmCkvYmS9xnQK3m3XgxZHwSUjvfTjp7YfXe5tT3GgWi0F2N+ZSMsOeWeZFh7ZZFg5iPhing==", + "dev": true, + "license": "MIT", + "dependencies": { + "bundle-require": "^5.1.0", + "cac": "^6.7.14", + "chokidar": "^4.0.3", + "consola": "^3.4.0", + "debug": "^4.4.0", + "esbuild": "^0.27.0", + "fix-dts-default-cjs-exports": "^1.0.0", + "joycon": "^3.1.1", + "picocolors": "^1.1.1", + "postcss-load-config": "^6.0.1", + "resolve-from": "^5.0.0", + "rollup": "^4.34.8", + "source-map": "^0.7.6", + "sucrase": "^3.35.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.11", + "tree-kill": "^1.2.2" + }, + "bin": { + "tsup": "dist/cli-default.js", + "tsup-node": "dist/cli-node.js" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@microsoft/api-extractor": "^7.36.0", + "@swc/core": "^1", + "postcss": "^8.4.12", + "typescript": ">=4.5.0" + }, + "peerDependenciesMeta": { + "@microsoft/api-extractor": { + "optional": true + }, + "@swc/core": { + "optional": true + }, + "postcss": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/tsup/node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/type-fest": { + "version": "5.4.4", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.4.4.tgz", + "integrity": "sha512-JnTrzGu+zPV3aXIUhnyWJj4z/wigMsdYajGLIYakqyOW1nPllzXEJee0QQbHj+CTIQtXGlAjuK0UY+2xTyjVAw==", + "license": "(MIT OR CC0-1.0)", + "dependencies": { + "tagged-tag": "^1.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/ufo": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.1.tgz", + "integrity": "sha512-9a4/uxlTWJ4+a5i0ooc1rU7C7YOw3wT+UGqdeNNHWnOF9qcMBgLRS+4IYUqbczewFx4mLEig6gawh7X6mFlEkA==", + "dev": true, + "license": "MIT" + }, + "node_modules/undici-types": { + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", + "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.1.tgz", + "integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.27.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.0.18.tgz", + "integrity": "sha512-hOQuK7h0FGKgBAas7v0mSAsnvrIgAvWmRFjmzpJ7SwFHH3g1k2u37JtYwOwmEKhK6ZO3v9ggDBBm0La1LCK4uQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.0.18", + "@vitest/mocker": "4.0.18", + "@vitest/pretty-format": "4.0.18", + "@vitest/runner": "4.0.18", + "@vitest/snapshot": "4.0.18", + "@vitest/spy": "4.0.18", + "@vitest/utils": "4.0.18", + "es-module-lexer": "^1.7.0", + "expect-type": "^1.2.2", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^3.10.0", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.0.3", + "vite": "^6.0.0 || ^7.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.0.18", + "@vitest/browser-preview": "4.0.18", + "@vitest/browser-webdriverio": "4.0.18", + "@vitest/ui": "4.0.18", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/vitest/node_modules/tinyexec": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.2.tgz", + "integrity": "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + } + } +} diff --git a/package.json b/package.json index 2290c525a..1bad5e08b 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,39 @@ { - "version": "1.16.5", - "name": "httpsnippet", + "name": "@readme/httpsnippet", + "version": "11.1.0", "description": "HTTP Request snippet generator for *most* languages", - "author": "Ahmad Nassri (https://www.mashape.com/)", - "homepage": "https://github.com/Mashape/httpsnippet", + "homepage": "https://github.com/readmeio/httpsnippet", "license": "MIT", - "main": "src/index.js", - "bin": "bin/httpsnippet", + "sideEffects": false, + "type": "module", + "exports": { + ".": { + "require": "./dist/index.cjs", + "import": "./dist/index.js" + }, + "./helpers/code-builder": { + "require": "./dist/helpers/code-builder.cjs", + "import": "./dist/helpers/code-builder.js" + }, + "./helpers/reducer": { + "require": "./dist/helpers/reducer.cjs", + "import": "./dist/helpers/reducer.js" + }, + "./targets": { + "require": "./dist/targets/index.cjs", + "import": "./dist/targets/index.js" + }, + "./package.json": "./package.json" + }, + "main": "dist/index.cjs", + "module": "dist/index.js", + "types": "dist/index.d.cts", + "engines": { + "node": ">=18" + }, + "files": [ + "dist" + ], "keywords": [ "api", "clojure", @@ -16,75 +43,60 @@ "har", "http", "httpie", + "httr", "java", "javascript", "jquery", + "kotlin", "objc", "objective-c", "ocaml", "php", "python", - "request", "requests", "ruby", "shell", "snippet", "swift", "swift", - "unirest", "xhr", "xmlhttprequest" ], - "engines": { - "node": ">=0.10" - }, - "files": [ - "bin", - "src" - ], - "repository": "Mashape/httpsnippet", - "bugs": { - "url": "https://github.com/Mashape/httpsnippet/issues" + "repository": { + "type": "git", + "url": "https://github.com/readmeio/httpsnippet.git" }, "scripts": { - "quick": "mocha --no-timeouts --fgrep 'Request Validation' --invert", - "pretest": "standard && echint", - "test": "mocha --no-timeouts", - "posttest": "npm run coverage", - "coverage": "istanbul cover --dir coverage _mocha -- --fgrep 'Request Validation' --invert -R dot", - "codeclimate": "codeclimate < coverage/lcov.info" + "attw": "attw --pack --format table-flipped", + "build": "tsup", + "clean": "rm -rf dist/", + "format": "npm run prettier:write && npx biome check --write", + "lint": "npm run lint:js && npm run prettier && tsc", + "lint:js": "biome check", + "prebuild": "npm run clean", + "prepack": "npm run build", + "prettier": "prettier --check .", + "prettier:write": "prettier --check --write .", + "test": "vitest run --coverage" }, - "standard": { - "ignore": [ - "**/test/fixtures/**" - ] - }, - "echint": { - "ignore": [ - "coverage/**", - "CONTRIBUTING.md", - "test/fixtures/**" - ] + "dependencies": { + "qs": "^6.15.0", + "stringify-object": "^3.3.0", + "type-fest": "^5.4.4" }, "devDependencies": { - "codeclimate-test-reporter": "0.1.1", - "echint": "^1.5.0", - "glob": "^6.0.1", - "istanbul": "^0.4.0", - "mocha": "^2.3.4", + "@biomejs/biome": "^2.4.4", + "@readme/standards": "^2.2.0", + "@types/har-format": "^1.2.15", + "@types/node": "^25.3.0", + "@types/qs": "^6.9.10", + "@types/stringify-object": "^4.0.5", + "@vitest/coverage-v8": "^4.0.2", + "prettier": "^3.0.3", "require-directory": "^2.1.1", - "should": "^7.1.1", - "standard": "^5.4.1" + "tsup": "^8.0.1", + "typescript": "^5.8.3", + "vitest": "^4.0.2" }, - "dependencies": { - "chalk": "^1.1.1", - "commander": "^2.9.0", - "debug": "^2.2.0", - "event-stream": "^3.3.2", - "form-data": "^1.0.0-rc3", - "fs-readfile-promise": "^2.0.1", - "fs-writefile-promise": "^1.0.3", - "har-validator": "^2.0.2", - "pinkie-promise": "^2.0.0" - } + "prettier": "@readme/standards/prettier" } diff --git a/src/fixtures/customTarget.ts b/src/fixtures/customTarget.ts new file mode 100644 index 000000000..56c4029d4 --- /dev/null +++ b/src/fixtures/customTarget.ts @@ -0,0 +1,15 @@ +import type { Target } from '../targets/index.js'; + +import { axios } from '../targets/node/axios/client.js'; + +export const customTarget = { + info: { + key: 'node-variant', + title: 'Node Variant', + extname: '.js', + default: 'axios', + }, + clientsById: { + axios, + }, +} as unknown as Target; diff --git a/test/fixtures/files/hello.txt b/src/fixtures/files/hello.txt similarity index 100% rename from test/fixtures/files/hello.txt rename to src/fixtures/files/hello.txt diff --git a/src/fixtures/mimetypes.ts b/src/fixtures/mimetypes.ts new file mode 100644 index 000000000..8f3290da0 --- /dev/null +++ b/src/fixtures/mimetypes.ts @@ -0,0 +1,84 @@ +import type { Request } from '../index.js'; + +export const mimetypes = { + 'multipart/mixed': { + method: 'POST', + url: 'https://httpbin.org/anything', + postData: { + mimeType: 'multipart/mixed', + text: '', + }, + } as Request, + + 'multipart/related': { + method: 'POST', + url: 'https://httpbin.org/anything', + postData: { + mimeType: 'multipart/related', + text: '', + }, + } as Request, + + 'multipart/form-data': { + method: 'POST', + url: 'https://httpbin.org/anything', + postData: { + mimeType: 'multipart/form-data', + text: '', + }, + } as Request, + + 'multipart/alternative': { + method: 'POST', + url: 'https://httpbin.org/anything', + postData: { + mimeType: 'multipart/alternative', + text: '', + }, + } as Request, + + 'application/x-www-form-urlencoded': { + method: 'POST', + url: 'https://httpbin.org/anything', + postData: { + mimeType: 'application/x-www-form-urlencoded', + text: '', + }, + } as Request, + + 'text/json': { + method: 'POST', + url: 'https://httpbin.org/anything', + postData: { + mimeType: 'text/json', + text: '', + }, + } as Request, + + 'text/x-json': { + method: 'POST', + url: 'https://httpbin.org/anything', + postData: { + mimeType: 'text/x-json', + text: '', + }, + } as Request, + + 'application/x-json': { + method: 'POST', + url: 'https://httpbin.org/anything', + postData: { + mimeType: 'application/x-json', + text: '', + }, + } as Request, + + 'invalid-json': { + method: 'POST', + url: 'https://httpbin.org/anything', + postData: { + mimeType: 'application/json', + text: 'foo/bar', + }, + } as Request, +}; diff --git a/src/fixtures/requests/application-form-encoded.cjs b/src/fixtures/requests/application-form-encoded.cjs new file mode 100644 index 000000000..cdd50e468 --- /dev/null +++ b/src/fixtures/requests/application-form-encoded.cjs @@ -0,0 +1,68 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: [ + { + name: 'content-type', + value: 'application/x-www-form-urlencoded', + }, + ], + postData: { + mimeType: 'application/x-www-form-urlencoded', + params: [ + { + name: 'foo', + value: 'bar', + }, + { + name: 'hello', + value: 'world', + }, + ], + }, + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + args: {}, + data: 'foo=bar&hello=world', + files: {}, + form: { + foo: ['bar'], + hello: ['world'], + }, + headers: { + 'Content-Type': ['application/x-www-form-urlencoded'], + }, + json: null, + method: 'POST', + url: 'https://httpbin.org/anything', + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/requests/application-json.cjs b/src/fixtures/requests/application-json.cjs new file mode 100644 index 000000000..83f2a93fd --- /dev/null +++ b/src/fixtures/requests/application-json.cjs @@ -0,0 +1,71 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: [ + { + name: 'content-type', + value: 'application/json', + }, + ], + postData: { + mimeType: 'application/json', + text: '{"number":1,"string":"f\\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":[]}],"boolean":false}', + }, + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + args: {}, + data: '{\n "number": 1,\n "string": "f\\"oo",\n "arr": [\n 1,\n 2,\n 3\n ],\n "nested": {\n "a": "b"\n },\n "arr_mix": [\n 1,\n "a",\n {\n "arr_mix_nested": []\n }\n ],\n "boolean": false\n}', + files: {}, + form: {}, + headers: { + 'Content-Type': ['application/json'], + }, + json: { + arr: [1, 2, 3], + arr_mix: [ + 1, + 'a', + { + arr_mix_nested: [], + }, + ], + boolean: false, + nested: { + a: 'b', + }, + number: 1, + string: 'f"oo', + }, + method: 'POST', + url: 'https://httpbin.org/anything', + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/requests/cookies.cjs b/src/fixtures/requests/cookies.cjs new file mode 100644 index 000000000..231a46784 --- /dev/null +++ b/src/fixtures/requests/cookies.cjs @@ -0,0 +1,48 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'GET', + url: 'https://httpbin.org/cookies', + cookies: [ + { + name: 'foo', + value: 'bar', + }, + { + name: 'bar', + value: 'baz', + }, + ], + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + bar: 'baz', + foo: 'bar', + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/requests/custom-method.cjs b/src/fixtures/requests/custom-method.cjs new file mode 100644 index 000000000..03806ffb3 --- /dev/null +++ b/src/fixtures/requests/custom-method.cjs @@ -0,0 +1,47 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'PROPFIND', + url: 'https://httpbin.org/anything', + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + args: {}, + headers: {}, + method: 'PROPFIND', + origin: '127.0.0.1:49488', + url: 'https://httpbin.org/anything', + data: '', + files: {}, + form: {}, + json: null, + }), + }, + headersSize: -1, + bodySize: -1, + }, + headersSize: -1, + bodySize: -1, + }, + ], + }, +}; diff --git a/src/fixtures/requests/full.cjs b/src/fixtures/requests/full.cjs new file mode 100644 index 000000000..9107281c4 --- /dev/null +++ b/src/fixtures/requests/full.cjs @@ -0,0 +1,98 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'POST', + url: 'https://httpbin.org/anything?key=value', + httpVersion: 'HTTP/1.1', + queryString: [ + { + name: 'foo', + value: 'bar', + }, + { + name: 'foo', + value: 'baz', + }, + { + name: 'baz', + value: 'abc', + }, + ], + headers: [ + { + name: 'accept', + value: 'application/json', + }, + { + name: 'content-type', + value: 'application/x-www-form-urlencoded', + }, + ], + cookies: [ + { + name: 'foo', + value: 'bar', + }, + { + name: 'bar', + value: 'baz', + }, + ], + postData: { + mimeType: 'application/x-www-form-urlencoded', + params: [ + { + name: 'foo', + value: 'bar', + }, + ], + }, + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + args: { + baz: ['abc'], + foo: ['bar', 'baz'], + key: ['value'], + }, + data: 'foo=bar', + files: {}, + form: { + foo: ['bar'], + }, + headers: { + Accept: ['application/json'], + 'Content-Type': ['application/x-www-form-urlencoded'], + Cookie: ['foo=bar; bar=baz'], + }, + json: null, + method: 'POST', + url: 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value', + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/requests/headers.cjs b/src/fixtures/requests/headers.cjs new file mode 100644 index 000000000..8a4db8be9 --- /dev/null +++ b/src/fixtures/requests/headers.cjs @@ -0,0 +1,59 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'GET', + url: 'https://httpbin.org/headers', + headers: [ + { + name: 'accept', + value: 'application/json', + }, + { + name: 'x-foo', + value: 'Bar', + }, + { + name: 'x-bar', + value: 'Foo', + }, + { + name: 'quoted-value', + value: '"quoted" \'string\'', + }, + ], + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + headers: { + Accept: ['application/json'], + 'X-Bar': ['Foo'], + 'X-Foo': ['Bar'], + }, + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/requests/http-insecure.cjs b/src/fixtures/requests/http-insecure.cjs new file mode 100644 index 000000000..ac7233e4b --- /dev/null +++ b/src/fixtures/requests/http-insecure.cjs @@ -0,0 +1,44 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'GET', + url: 'http://httpbin.org/anything', + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + args: {}, + data: '', + files: {}, + form: {}, + headers: {}, + json: null, + method: 'GET', + url: 'http://httpbin.org/anything', + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/requests/jsonObj-multiline.cjs b/src/fixtures/requests/jsonObj-multiline.cjs new file mode 100644 index 000000000..f7cb37c81 --- /dev/null +++ b/src/fixtures/requests/jsonObj-multiline.cjs @@ -0,0 +1,58 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: [ + { + name: 'content-type', + value: 'application/json', + }, + ], + postData: { + text: '{\n "foo": "bar"\n}', + mimeType: 'application/json', + }, + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + args: {}, + data: '{\n "foo": "bar"\n}', + files: {}, + form: {}, + headers: { + 'Content-Type': ['application/json'], + }, + json: { + foo: 'bar', + }, + method: 'POST', + url: 'https://httpbin.org/anything', + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/requests/jsonObj-null-value.cjs b/src/fixtures/requests/jsonObj-null-value.cjs new file mode 100644 index 000000000..681f45cd1 --- /dev/null +++ b/src/fixtures/requests/jsonObj-null-value.cjs @@ -0,0 +1,65 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: [ + { + name: 'content-type', + value: 'application/json', + }, + ], + postData: { + params: [], + text: '{"foo":null}', + // stored: true, + mimeType: 'application/json', + // size: 0, + // jsonObj: { + // foo: null, + // }, + // paramsObj: false, + }, + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + args: {}, + data: '{"foo":null}', + files: {}, + form: {}, + headers: { + 'Content-Type': ['application/json'], + }, + json: { + foo: null, + }, + method: 'POST', + url: 'https://httpbin.org/anything', + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/requests/multipart-data.cjs b/src/fixtures/requests/multipart-data.cjs new file mode 100644 index 000000000..05c319aca --- /dev/null +++ b/src/fixtures/requests/multipart-data.cjs @@ -0,0 +1,71 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: [ + { + name: 'content-type', + value: 'multipart/form-data', + }, + ], + postData: { + mimeType: 'multipart/form-data', + params: [ + { + name: 'foo', + value: 'Hello World', + fileName: 'src/fixtures/files/hello.txt', + contentType: 'text/plain', + }, + { + name: 'bar', + value: 'Bonjour le monde', + }, + ], + }, + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + args: {}, + data: '', + files: { + foo: 'Hello World', + }, + form: { + bar: ['Bonjour le monde'], + }, + headers: { + 'Content-Type': ['multipart/form-data; boundary=------------------------6e4b42ed3719ed70'], + }, + json: null, + method: 'POST', + url: 'https://httpbin.org/anything', + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/requests/multipart-file.cjs b/src/fixtures/requests/multipart-file.cjs new file mode 100644 index 000000000..1dac00a0e --- /dev/null +++ b/src/fixtures/requests/multipart-file.cjs @@ -0,0 +1,64 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: [ + { + name: 'content-type', + value: 'multipart/form-data', + }, + ], + postData: { + mimeType: 'multipart/form-data', + params: [ + { + name: 'foo', + fileName: 'src/fixtures/files/hello.txt', + contentType: 'text/plain', + }, + ], + }, + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + args: {}, + data: '', + files: { + foo: 'Hello World', + }, + form: {}, + headers: { + 'Content-Type': 'multipart/form-data; boundary=------------------------b74e534478e5833d', + }, + json: null, + method: 'POST', + url: 'https://httpbin.org/anything', + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/requests/multipart-form-data-no-params.cjs b/src/fixtures/requests/multipart-form-data-no-params.cjs new file mode 100644 index 000000000..cb307ba08 --- /dev/null +++ b/src/fixtures/requests/multipart-form-data-no-params.cjs @@ -0,0 +1,53 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: [ + { + name: 'Content-Type', + value: 'multipart/form-data', + }, + ], + postData: { + mimeType: 'multipart/form-data', + }, + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + args: {}, + data: '', + files: {}, + form: {}, + headers: {}, + json: null, + method: 'POST', + url: 'https://httpbin.org/anything', + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/requests/multipart-form-data.cjs b/src/fixtures/requests/multipart-form-data.cjs new file mode 100644 index 000000000..10dd2d146 --- /dev/null +++ b/src/fixtures/requests/multipart-form-data.cjs @@ -0,0 +1,63 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: [ + { + name: 'Content-Type', + value: 'multipart/form-data', + }, + ], + postData: { + mimeType: 'multipart/form-data', + params: [ + { + name: 'foo', + value: 'bar', + }, + ], + }, + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + args: {}, + data: '', + files: {}, + form: { + foo: ['bar'], + }, + headers: { + 'Content-Type': ['multipart/form-data; boundary=------------------------8dd0f6c44b5bc105'], + }, + json: null, + method: 'POST', + url: 'https://httpbin.org/anything', + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/requests/nested.cjs b/src/fixtures/requests/nested.cjs new file mode 100644 index 000000000..40ddfc7ac --- /dev/null +++ b/src/fixtures/requests/nested.cjs @@ -0,0 +1,63 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'GET', + url: 'https://httpbin.org/anything', + httpVersion: 'HTTP/1.1', + queryString: [ + { + name: 'foo[bar]', + value: 'baz,zap', + }, + { + name: 'fiz', + value: 'buz', + }, + { + name: 'key', + value: 'value', + }, + ], + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + args: { + fiz: ['buz'], + 'foo[bar]': ['baz,zap'], + key: ['value'], + }, + data: '', + files: {}, + form: {}, + headers: {}, + json: null, + method: 'GET', + url: 'https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value', + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/requests/postdata-malformed.cjs b/src/fixtures/requests/postdata-malformed.cjs new file mode 100644 index 000000000..9bbb1ce51 --- /dev/null +++ b/src/fixtures/requests/postdata-malformed.cjs @@ -0,0 +1,56 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: [ + { + name: 'content-type', + value: 'application/json', + }, + ], + postData: { + // Per the HAR spec `postData` should always have `mimeType` but this fixture is + // testing when that isn't the case. + }, + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + args: {}, + data: '', + files: {}, + form: {}, + headers: { + 'Content-Type': ['application/json'], + }, + json: null, + method: 'POST', + url: 'https://httpbin.org/anything', + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/requests/query-encoded.cjs b/src/fixtures/requests/query-encoded.cjs new file mode 100644 index 000000000..7745b0646 --- /dev/null +++ b/src/fixtures/requests/query-encoded.cjs @@ -0,0 +1,58 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'GET', + url: 'https://httpbin.org/anything', + httpVersion: 'HTTP/1.1', + queryString: [ + { + name: 'startTime', + value: '2019-06-13T19%3A08%3A25.455Z', + }, + { + name: 'endTime', + value: '2015-09-15T14%3A00%3A12-04%3A00', + }, + ], + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + args: { + endTime: ['2015-09-15T14:00:12-04:00'], + startTime: ['2019-06-13T19:08:25.455Z'], + }, + data: '', + files: {}, + form: {}, + headers: {}, + json: null, + method: 'GET', + url: 'https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00', + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/requests/query.cjs b/src/fixtures/requests/query.cjs new file mode 100644 index 000000000..e7e79aa5f --- /dev/null +++ b/src/fixtures/requests/query.cjs @@ -0,0 +1,63 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'GET', + url: 'https://httpbin.org/anything?key=value', + httpVersion: 'HTTP/1.1', + queryString: [ + { + name: 'foo', + value: 'bar', + }, + { + name: 'foo', + value: 'baz', + }, + { + name: 'baz', + value: 'abc', + }, + ], + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + args: { + baz: ['abc'], + foo: ['bar', 'baz'], + key: ['value'], + }, + data: '', + files: {}, + form: {}, + headers: {}, + json: null, + method: 'GET', + url: 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value', + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/requests/short.cjs b/src/fixtures/requests/short.cjs new file mode 100644 index 000000000..de45ffa5f --- /dev/null +++ b/src/fixtures/requests/short.cjs @@ -0,0 +1,44 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'GET', + url: 'https://httpbin.org/anything', + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + args: {}, + data: '', + files: {}, + form: {}, + headers: {}, + json: null, + method: 'GET', + url: 'https://httpbin.org/anything', + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/requests/text-plain.cjs b/src/fixtures/requests/text-plain.cjs new file mode 100644 index 000000000..5d252e154 --- /dev/null +++ b/src/fixtures/requests/text-plain.cjs @@ -0,0 +1,56 @@ +module.exports = { + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: [ + { + name: 'content-type', + value: 'text/plain', + }, + ], + postData: { + mimeType: 'text/plain', + text: 'Hello World', + }, + }, + response: { + status: 200, + statusText: 'OK', + httpVersion: 'HTTP/1.1', + headers: [ + { + name: 'Content-Type', + value: 'application/json', + }, + ], + content: { + size: -1, + mimeType: 'application/json', + text: JSON.stringify({ + args: {}, + data: 'Hello World', + files: {}, + form: {}, + headers: { + 'Content-Type': ['text/plain'], + }, + json: null, + method: 'POST', + url: 'https://httpbin.org/anything', + }), + }, + headersSize: -1, + bodySize: -1, + }, + }, + ], + }, +}; diff --git a/src/fixtures/runCustomFixtures.ts b/src/fixtures/runCustomFixtures.ts new file mode 100644 index 000000000..5ab179708 --- /dev/null +++ b/src/fixtures/runCustomFixtures.ts @@ -0,0 +1,46 @@ +import type { HTTPSnippetOptions, Request } from '../index.js'; +import type { ClientId, TargetId } from '../targets/index.js'; + +import { writeFileSync } from 'node:fs'; +import { readFile } from 'node:fs/promises'; +import path from 'node:path'; + +import { describe, expect, it } from 'vitest'; + +import { HTTPSnippet } from '../index.js'; + +export interface CustomFixture { + clientId: ClientId; + targetId: TargetId; + tests: { + /** a file path pointing to the expected custom fixture result */ + expected: string; + + input: Request; + it: string; + options: any; + }[]; +} + +export const runCustomFixtures = ({ targetId, clientId, tests }: CustomFixture): void => { + describe(`custom fixtures for ${targetId}:${clientId}`, () => { + it.each(tests.map(t => [t.it, t]))('%s', async (_, { expected: fixtureFile, options, input: request }) => { + const opts: HTTPSnippetOptions = {}; + if (options.harIsAlreadyEncoded) { + opts.harIsAlreadyEncoded = options.harIsAlreadyEncoded; + } + + const snippet = new HTTPSnippet(request, opts); + const result = snippet.convert(targetId, clientId, options)[0]; + const filePath = path.join(import.meta.dirname, '..', 'targets', targetId, clientId, 'fixtures', fixtureFile); + if (process.env.OVERWRITE_EVERYTHING) { + writeFileSync(filePath, String(result)); + } + + const buffer = await readFile(filePath); + const fixture = String(buffer); + + expect(result).toStrictEqual(fixture); + }); + }); +}; diff --git a/src/helpers/__snapshots__/utils.test.ts.snap b/src/helpers/__snapshots__/utils.test.ts.snap new file mode 100644 index 000000000..cc6b060bc --- /dev/null +++ b/src/helpers/__snapshots__/utils.test.ts.snap @@ -0,0 +1,391 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`availableTargets > returns all available targets 1`] = ` +[ + { + "cli": "c", + "clients": [ + { + "description": "Simple REST and HTTP API Client for C", + "extname": ".c", + "key": "libcurl", + "link": "http://curl.haxx.se/libcurl", + "title": "Libcurl", + }, + ], + "default": "libcurl", + "key": "c", + "title": "C", + }, + { + "clients": [ + { + "description": "An idiomatic clojure http client wrapping the apache client.", + "extname": ".clj", + "key": "clj_http", + "link": "https://github.com/dakrone/clj-http", + "title": "clj-http", + }, + ], + "default": "clj_http", + "key": "clojure", + "title": "Clojure", + }, + { + "cli": "dotnet", + "clients": [ + { + "description": ".NET Standard HTTP Client", + "extname": ".cs", + "key": "httpclient", + "link": "https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient", + "title": "HttpClient", + }, + { + "description": "Simple REST and HTTP API Client for .NET", + "extname": ".cs", + "installation": [Function], + "key": "restsharp", + "link": "http://restsharp.org/", + "title": "RestSharp", + }, + ], + "default": "restsharp", + "key": "csharp", + "title": "C#", + }, + { + "cli": "go", + "clients": [ + { + "description": "Golang HTTP client request", + "extname": ".go", + "key": "native", + "link": "http://golang.org/pkg/net/http/#NewRequest", + "title": "NewRequest", + }, + ], + "default": "native", + "key": "go", + "title": "Go", + }, + { + "clients": [ + { + "description": "HTTP/1.1 request string in accordance with RFC 7230", + "extname": null, + "key": "http1.1", + "link": "https://tools.ietf.org/html/rfc7230", + "title": "HTTP/1.1", + }, + ], + "default": "http1.1", + "key": "http", + "title": "HTTP", + }, + { + "clients": [ + { + "description": "Asynchronous Http and WebSocket Client library for Java", + "extname": ".java", + "key": "asynchttp", + "link": "https://github.com/AsyncHttpClient/async-http-client", + "title": "AsyncHttp", + }, + { + "description": "Java Standardized HTTP Client API", + "extname": ".java", + "key": "nethttp", + "link": "https://openjdk.java.net/groups/net/httpclient/intro.html", + "title": "java.net.http", + }, + { + "description": "An HTTP Request Client Library", + "extname": ".java", + "key": "okhttp", + "link": "http://square.github.io/okhttp/", + "title": "OkHttp", + }, + { + "description": "Lightweight HTTP Request Client Library", + "extname": ".java", + "key": "unirest", + "link": "http://unirest.io/java.html", + "title": "Unirest", + }, + ], + "default": "unirest", + "key": "java", + "title": "Java", + }, + { + "clients": [ + { + "description": "W3C Standard API that provides scripted client functionality", + "extname": ".js", + "key": "xhr", + "link": "https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest", + "title": "XMLHttpRequest", + }, + { + "description": "Promise based HTTP client for the browser and node.js", + "extname": ".js", + "installation": [Function], + "key": "axios", + "link": "https://github.com/axios/axios", + "title": "Axios", + }, + { + "description": "Perform asynchronous HTTP requests with the Fetch API", + "extname": ".js", + "key": "fetch", + "link": "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch", + "title": "fetch", + }, + { + "description": "Perform an asynchronous HTTP (Ajax) requests with jQuery", + "extname": ".js", + "key": "jquery", + "link": "http://api.jquery.com/jquery.ajax/", + "title": "jQuery", + }, + ], + "default": "fetch", + "key": "javascript", + "title": "JavaScript", + }, + { + "clients": [ + { + "description": "A JSON represetation of any HAR payload.", + "extname": ".json", + "key": "native", + "link": "https://www.json.org/json-en.html", + "title": "Native JSON", + }, + ], + "default": "native", + "key": "json", + "title": "JSON", + }, + { + "clients": [ + { + "description": "An HTTP Request Client Library", + "extname": ".kt", + "key": "okhttp", + "link": "http://square.github.io/okhttp/", + "title": "OkHttp", + }, + ], + "default": "okhttp", + "key": "kotlin", + "title": "Kotlin", + }, + { + "cli": "node %s", + "clients": [ + { + "description": "Node.js native HTTP interface", + "extname": ".cjs", + "key": "native", + "link": "http://nodejs.org/api/http.html#http_http_request_options_callback", + "title": "HTTP", + }, + { + "description": "Promise based HTTP client for the browser and node.js", + "extname": ".js", + "installation": [Function], + "key": "axios", + "link": "https://github.com/axios/axios", + "title": "Axios", + }, + { + "description": "Perform asynchronous HTTP requests with the Fetch API", + "extname": ".js", + "key": "fetch", + "link": "https://nodejs.org/docs/latest/api/globals.html#fetch", + "title": "fetch", + }, + ], + "default": "fetch", + "key": "node", + "title": "Node.js", + }, + { + "clients": [ + { + "description": "Foundation's NSURLSession request", + "extname": ".m", + "key": "nsurlsession", + "link": "https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/index.html", + "title": "NSURLSession", + }, + ], + "default": "nsurlsession", + "key": "objc", + "title": "Objective-C", + }, + { + "clients": [ + { + "description": "Cohttp is a very lightweight HTTP server using Lwt or Async for OCaml", + "extname": ".ml", + "installation": [Function], + "key": "cohttp", + "link": "https://github.com/mirage/ocaml-cohttp", + "title": "CoHTTP", + }, + ], + "default": "cohttp", + "key": "ocaml", + "title": "OCaml", + }, + { + "cli": "php %s", + "clients": [ + { + "description": "PHP with ext-curl", + "extname": ".php", + "key": "curl", + "link": "http://php.net/manual/en/book.curl.php", + "title": "cURL", + }, + { + "description": "PHP with Guzzle", + "extname": ".php", + "installation": [Function], + "key": "guzzle", + "link": "http://docs.guzzlephp.org/en/stable/", + "title": "Guzzle", + }, + { + "description": "PHP with pecl/http v1", + "extname": ".php", + "key": "http1", + "link": "http://php.net/manual/en/book.http.php", + "title": "HTTP v1", + }, + { + "description": "PHP with pecl/http v2", + "extname": ".php", + "key": "http2", + "link": "http://devel-m6w6.rhcloud.com/mdref/http", + "title": "HTTP v2", + }, + ], + "default": "curl", + "key": "php", + "title": "PHP", + }, + { + "clients": [ + { + "description": "Powershell Invoke-WebRequest client", + "extname": ".ps1", + "key": "webrequest", + "link": "https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Invoke-WebRequest", + "title": "Invoke-WebRequest", + }, + { + "description": "Powershell Invoke-RestMethod client", + "extname": ".ps1", + "key": "restmethod", + "link": "https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Invoke-RestMethod", + "title": "Invoke-RestMethod", + }, + ], + "default": "webrequest", + "key": "powershell", + "title": "Powershell", + }, + { + "cli": "python3 %s", + "clients": [ + { + "description": "Requests HTTP library", + "extname": ".py", + "installation": [Function], + "key": "requests", + "link": "http://docs.python-requests.org/en/latest/api/#requests.request", + "title": "Requests", + }, + ], + "default": "requests", + "key": "python", + "title": "Python", + }, + { + "clients": [ + { + "description": "httr: Tools for Working with URLs and HTTP", + "extname": ".r", + "key": "httr", + "link": "https://cran.r-project.org/web/packages/httr/vignettes/quickstart.html", + "title": "httr", + }, + ], + "default": "httr", + "key": "r", + "title": "R", + }, + { + "clients": [ + { + "description": "Ruby HTTP client", + "extname": ".rb", + "key": "native", + "link": "http://ruby-doc.org/stdlib-2.2.1/libdoc/net/http/rdoc/Net/HTTP.html", + "title": "net::http", + }, + ], + "default": "native", + "key": "ruby", + "title": "Ruby", + }, + { + "cli": "%s", + "clients": [ + { + "description": "cURL is a command line tool and library for transferring data with URL syntax", + "extname": ".sh", + "key": "curl", + "link": "http://curl.haxx.se/", + "title": "cURL", + }, + { + "description": "a CLI, cURL-like tool for humans", + "extname": ".sh", + "installation": [Function], + "key": "httpie", + "link": "http://httpie.org/", + "title": "HTTPie", + }, + { + "description": "a free software package for retrieving files using HTTP, HTTPS", + "extname": ".sh", + "key": "wget", + "link": "https://www.gnu.org/software/wget/", + "title": "Wget", + }, + ], + "default": "curl", + "key": "shell", + "title": "Shell", + }, + { + "clients": [ + { + "description": "Foundation's URLSession request", + "extname": ".swift", + "key": "urlsession", + "link": "https://developer.apple.com/documentation/foundation/urlsession", + "title": "URLSession", + }, + ], + "default": "urlsession", + "key": "swift", + "title": "Swift", + }, +] +`; diff --git a/src/helpers/code-builder.js b/src/helpers/code-builder.js deleted file mode 100644 index 335ea34c0..000000000 --- a/src/helpers/code-builder.js +++ /dev/null @@ -1,103 +0,0 @@ -'use strict' - -var util = require('util') - -/** - * Helper object to format and aggragate lines of code. - * Lines are aggregated in a `code` array, and need to be joined to obtain a proper code snippet. - * - * @class - * - * @param {string} indentation Desired indentation character for aggregated lines of code - * @param {string} join Desired character to join each line of code - */ -var CodeBuilder = function (indentation, join) { - this.code = [] - this.indentation = indentation - this.lineJoin = join || '\n' -} - -/** - * Add given indentation level to given string and format the string (variadic) - * @param {number} [indentationLevel=0] - Desired level of indentation for this line - * @param {string} line - Line of code. Can contain formatting placeholders - * @param {...anyobject} - Parameter to bind to `line`'s formatting placeholders - * @return {string} - * - * @example - * var builder = CodeBuilder('\t') - * - * builder.buildLine('console.log("hello world")') - * // returns: 'console.log("hello world")' - * - * builder.buildLine(2, 'console.log("hello world")') - * // returns: 'console.log("\t\thello world")' - * - * builder.buildLine(2, 'console.log("%s %s")', 'hello', 'world') - * // returns: 'console.log("\t\thello world")' - */ -CodeBuilder.prototype.buildLine = function (indentationLevel, line) { - var lineIndentation = '' - var slice = 2 - if (Object.prototype.toString.call(indentationLevel) === '[object String]') { - slice = 1 - line = indentationLevel - indentationLevel = 0 - } else if (indentationLevel === null) { - return null - } - - while (indentationLevel) { - lineIndentation += this.indentation - indentationLevel-- - } - - var format = Array.prototype.slice.call(arguments, slice, arguments.length) - format.unshift(lineIndentation + line) - - return util.format.apply(this, format) -} - -/** - * Invoke buildLine() and add the line at the top of current lines - * @param {number} [indentationLevel=0] Desired level of indentation for this line - * @param {string} line Line of code - * @return {this} - */ -CodeBuilder.prototype.unshift = function () { - this.code.unshift(this.buildLine.apply(this, arguments)) - - return this -} - -/** - * Invoke buildLine() and add the line at the bottom of current lines - * @param {number} [indentationLevel=0] Desired level of indentation for this line - * @param {string} line Line of code - * @return {this} - */ -CodeBuilder.prototype.push = function () { - this.code.push(this.buildLine.apply(this, arguments)) - - return this -} - -/** - * Add an empty line at the end of current lines - * @return {this} - */ -CodeBuilder.prototype.blank = function () { - this.code.push(null) - - return this -} - -/** - * Concatenate all current lines using the given lineJoin - * @return {string} - */ -CodeBuilder.prototype.join = function () { - return this.code.join(this.lineJoin) -} - -module.exports = CodeBuilder diff --git a/src/helpers/code-builder.test.ts b/src/helpers/code-builder.test.ts new file mode 100644 index 000000000..e75e6a3d9 --- /dev/null +++ b/src/helpers/code-builder.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest'; + +import { CodeBuilder } from './code-builder.js'; + +describe('codeBuilder', () => { + describe('indentLine', () => { + const indent = '\t'; + const builder = new CodeBuilder({ indent }); + const line = 'console.log("hello world")'; + + it('handles a single argument', () => { + const result = builder.indentLine(line); + + expect(result).toStrictEqual(line); + }); + + it('handels indentation', () => { + const result = builder.indentLine(line, 2); + + expect(result).toBe(`${indent.repeat(2)}${line}`); + }); + }); + + describe('addPostProcessor', () => { + it('replaces accordingly with one replacer', () => { + const indent = '\t'; + const { join, addPostProcessor, push } = new CodeBuilder({ indent }); + push('console.log("hello world")'); + addPostProcessor(code => code.replace(/console/, 'REPLACED')); + + expect(join()).toBe('REPLACED.log("hello world")'); + }); + + it('replaces accordingly with multiple replacers', () => { + const indent = '\t'; + const { join, addPostProcessor, push } = new CodeBuilder({ indent }); + push('console.log("hello world")'); + addPostProcessor(code => code.replace(/world/, 'nurse!!')); + addPostProcessor(code => code.toUpperCase()); + + expect(join()).toBe('CONSOLE.LOG("HELLO NURSE!!")'); + }); + }); +}); diff --git a/src/helpers/code-builder.ts b/src/helpers/code-builder.ts new file mode 100644 index 000000000..80fbf4245 --- /dev/null +++ b/src/helpers/code-builder.ts @@ -0,0 +1,85 @@ +const DEFAULT_INDENTATION_CHARACTER = ''; +const DEFAULT_LINE_JOIN = '\n'; + +export type PostProcessor = (unreplacedCode: string) => string; + +export interface CodeBuilderOptions { + /** + * Desired indentation character for aggregated lines of code + * @default '' + */ + indent?: string; + + /** + * Desired character to join each line of code + * @default \n + */ + join?: string; +} + +export class CodeBuilder { + postProcessors: PostProcessor[] = []; + + code: string[] = []; + + indentationCharacter: string = DEFAULT_INDENTATION_CHARACTER; + + lineJoin: string = DEFAULT_LINE_JOIN; + + /** + * Helper object to format and aggragate lines of code. + * Lines are aggregated in a `code` array, and need to be joined to obtain a proper code snippet. + */ + constructor({ indent, join }: CodeBuilderOptions = {}) { + this.indentationCharacter = indent || DEFAULT_INDENTATION_CHARACTER; + this.lineJoin = join ?? DEFAULT_LINE_JOIN; + } + + /** + * Add given indentation level to given line of code + */ + indentLine = (line: string, indentationLevel = 0) => { + const indent = this.indentationCharacter.repeat(indentationLevel); + return `${indent}${line}`; + }; + + /** + * Add the line at the beginning of the current lines + */ + unshift = (line: string, indentationLevel?: number): void => { + const newLine = this.indentLine(line, indentationLevel); + this.code.unshift(newLine); + }; + + /** + * Add the line at the end of the current lines + */ + push = (line: string, indentationLevel?: number): void => { + const newLine = this.indentLine(line, indentationLevel); + this.code.push(newLine); + }; + + /** + * Add an empty line at the end of current lines + */ + blank = (): void => { + this.code.push(''); + }; + + /** + * Concatenate all current lines using the given lineJoin, then apply any replacers that may have been added + */ + join = (): string => { + const unreplacedCode = this.code.join(this.lineJoin); + const replacedOutput = this.postProcessors.reduce((accumulator, replacer) => replacer(accumulator), unreplacedCode); + return replacedOutput; + }; + + /** + * Often when writing modules you may wish to add a literal tag or bit of metadata that you wish to transform after other processing as a final step. + * To do so, you can provide a PostProcessor function and it will be run automatically for you when you call `join()` later on. + */ + addPostProcessor = (postProcessor: PostProcessor): void => { + this.postProcessors = [...this.postProcessors, postProcessor]; + }; +} diff --git a/src/helpers/escape.test.ts b/src/helpers/escape.test.ts new file mode 100644 index 000000000..fef59c6cd --- /dev/null +++ b/src/helpers/escape.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest'; + +import { escapeString } from './escape.js'; + +describe('Escape methods', () => { + describe('escapeString', () => { + it('does nothing to a safe string', () => { + expect(escapeString('hello world')).toBe('hello world'); + }); + + it('escapes double quotes by default', () => { + expect(escapeString('"hello world"')).toBe('\\"hello world\\"'); + }); + + it('escapes newlines by default', () => { + expect(escapeString('hello\r\nworld')).toBe('hello\\r\\nworld'); + }); + + it('escapes backslashes', () => { + expect(escapeString('hello\\world')).toBe('hello\\\\world'); + }); + + it('escapes unrepresentable characters', () => { + expect( + escapeString('hello \u0000'), // 0 = ASCII 'null' character + ).toBe('hello \\u0000'); + }); + }); +}); diff --git a/src/helpers/escape.ts b/src/helpers/escape.ts new file mode 100644 index 000000000..c47925eb3 --- /dev/null +++ b/src/helpers/escape.ts @@ -0,0 +1,91 @@ +export interface EscapeOptions { + /** + * The delimiter that will be used to wrap the string (and so must be escaped + * when used within the string). + * Defaults to " + */ + delimiter?: string; + + /** + * The char to use to escape the delimiter and other special characters. + * Defaults to \ + */ + escapeChar?: string; + + /** + * Whether newlines (\n and \r) should be escaped within the string. + * Defaults to true. + */ + escapeNewlines?: boolean; +} + +/** + * Escape characters within a value to make it safe to insert directly into a + * snippet. Takes options which define the escape requirements. + * + * This is closely based on the JSON-stringify string serialization algorithm, + * but generalized for other string delimiters (e.g. " or ') and different escape + * characters (e.g. Powershell uses `) + * + * See https://tc39.es/ecma262/multipage/structured-data.html#sec-quotejsonstring + * for the complete original algorithm. + */ +export function escapeString(rawValue: any, options: EscapeOptions = {}): string { + const { delimiter = '"', escapeChar = '\\', escapeNewlines = true } = options; + + const stringValue = rawValue.toString(); + + return [...stringValue] + .map(c => { + if (c === '\b') { + return `${escapeChar}b`; + } else if (c === '\t') { + return `${escapeChar}t`; + } else if (c === '\n') { + if (escapeNewlines) { + return `${escapeChar}n`; + } + + return c; // Don't just continue, or this is caught by < \u0020 + } else if (c === '\f') { + return `${escapeChar}f`; + } else if (c === '\r') { + if (escapeNewlines) { + return `${escapeChar}r`; + } + + return c; // Don't just continue, or this is caught by < \u0020 + } else if (c === escapeChar) { + return escapeChar + escapeChar; + } else if (c === delimiter) { + return escapeChar + delimiter; + } else if (c < '\u0020' || c > '\u007E') { + // Delegate the trickier non-ASCII cases to the normal algorithm. Some of these + // are escaped as \uXXXX, whilst others are represented literally. Since we're + // using this primarily for header values that are generally (though not 100% + // strictly?) ASCII-only, this should almost never happen. + return JSON.stringify(c).slice(1, -1); + } + + return c; + }) + .join(''); +} + +/** + * Make a string value safe to insert literally into a snippet within single quotes, + * by escaping problematic characters, including single quotes inside the string, + * backslashes, newlines, and other special characters. + * + * If value is not a string, it will be stringified with .toString() first. + */ +export const escapeForSingleQuotes = (value: any): string => escapeString(value, { delimiter: "'" }); + +/** + * Make a string value safe to insert literally into a snippet within double quotes, + * by escaping problematic characters, including double quotes inside the string, + * backslashes, newlines, and other special characters. + * + * If value is not a string, it will be stringified with .toString() first. + */ +export const escapeForDoubleQuotes = (value: any): string => escapeString(value, { delimiter: '"' }); diff --git a/src/helpers/headers.test.ts b/src/helpers/headers.test.ts new file mode 100644 index 000000000..0b8d6ac49 --- /dev/null +++ b/src/helpers/headers.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest'; + +import { getHeader, getHeaderName, hasHeader } from './headers.js'; + +const headers = { + 'Content-Type': 'multipart/form-data; boundary=---011000010111000001101001', + accept: 'application/json', +}; + +describe('headers', () => { + describe('getHeader', () => { + it('should get a header', () => { + expect(getHeader(headers, 'content-type')).toBe('multipart/form-data; boundary=---011000010111000001101001'); + expect(getHeader(headers, 'content-TYPE')).toBe('multipart/form-data; boundary=---011000010111000001101001'); + expect(getHeader(headers, 'Accept')).toBe('application/json'); + expect(getHeader(headers, 'authorization')).toBeUndefined(); + }); + }); + + describe('getHeaderName', () => { + it('should get a header name', () => { + expect(getHeaderName(headers, 'content-type')).toBe('Content-Type'); + expect(getHeaderName(headers, 'content-TYPE')).toBe('Content-Type'); + expect(getHeaderName(headers, 'Accept')).toBe('accept'); + expect(getHeaderName(headers, 'authorization')).toBeUndefined(); + }); + }); + + describe('hasHeader', () => { + it('should return if a header is present', () => { + expect(hasHeader(headers, 'content-type')).toBe(true); + expect(hasHeader(headers, 'content-TYPE')).toBe(true); + expect(hasHeader(headers, 'Accept')).toBe(true); + expect(hasHeader(headers, 'authorization')).toBe(false); + }); + }); +}); diff --git a/src/helpers/headers.ts b/src/helpers/headers.ts new file mode 100644 index 000000000..c1c288b62 --- /dev/null +++ b/src/helpers/headers.ts @@ -0,0 +1,31 @@ +type Headers = Record; + +/** + * Given a headers object retrieve a specific header out of it via a case-insensitive key. + */ +export const getHeaderName = (headers: Headers, name: string): string | undefined => + Object.keys(headers).find(header => header.toLowerCase() === name.toLowerCase()); + +/** + * Given a headers object retrieve the contents of a header out of it via a case-insensitive key. + */ +export const getHeader = (headers: Headers, name: string): T | undefined => { + const headerName = getHeaderName(headers, name); + if (!headerName) { + return undefined; + } + return headers[headerName]; +}; + +/** + * Determine if a given case-insensitive header exists within a header object. + */ +export const hasHeader = (headers: Headers, name: string): boolean => Boolean(getHeaderName(headers, name)); + +/** + * Determines if a given MIME type is JSON, or a variant of such. + */ +export const isMimeTypeJSON = (mimeType: string): boolean => + ['application/json', 'application/x-json', 'text/json', 'text/x-json', '+json'].some( + type => mimeType.indexOf(type) > -1, + ); diff --git a/src/helpers/reducer.js b/src/helpers/reducer.js deleted file mode 100644 index bc17a0a0d..000000000 --- a/src/helpers/reducer.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict' - -module.exports = function (obj, pair) { - if (obj[pair.name] === undefined) { - obj[pair.name] = pair.value - return obj - } - - // convert to array - var arr = [ - obj[pair.name], - pair.value - ] - - obj[pair.name] = arr - - return obj -} diff --git a/src/helpers/reducer.test.ts b/src/helpers/reducer.test.ts new file mode 100644 index 000000000..7d20ed0a6 --- /dev/null +++ b/src/helpers/reducer.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest'; + +import { reducer } from './reducer.js'; + +describe('reducer', () => { + it('should convert array object pair to key-value object', () => { + const query = [ + { name: 'key', value: 'value' }, + { name: 'foo', value: 'bar' }, + ]; + + const result = query.reduce(reducer, {}); + + expect(result).toMatchObject({ key: 'value', foo: 'bar' }); + }); + + it('should convert multi-dimensional arrays to key=[array] object', () => { + const query = [ + { name: 'key', value: 'value' }, + { name: 'foo', value: 'bar1' }, + { name: 'foo', value: 'bar2' }, + { name: 'foo', value: 'bar3' }, + ]; + + const result = query.reduce(reducer, {}); + + expect(result).toMatchObject({ key: 'value', foo: ['bar1', 'bar2', 'bar3'] }); + }); +}); diff --git a/src/helpers/reducer.ts b/src/helpers/reducer.ts new file mode 100644 index 000000000..7306af0cc --- /dev/null +++ b/src/helpers/reducer.ts @@ -0,0 +1,22 @@ +export type ReducedHelperObject = Record; + +export const reducer = ( + accumulator: ReducedHelperObject, + pair: T, +): ReducedHelperObject => { + const currentValue = accumulator[pair.name]; + if (currentValue === undefined) { + accumulator[pair.name] = pair.value; + return accumulator; + } + + // If we already have it as array just push the value + if (Array.isArray(currentValue)) { + currentValue.push(pair.value); + return accumulator; + } + + // convert to array since now we have more than one value for this key + accumulator[pair.name] = [currentValue, pair.value]; + return accumulator; +}; diff --git a/src/helpers/shell.js b/src/helpers/shell.js deleted file mode 100644 index 12b155b1a..000000000 --- a/src/helpers/shell.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict' - -var util = require('util') - -module.exports = { - /** - * Use 'strong quoting' using single quotes so that we only need - * to deal with nested single quote characters. - * http://wiki.bash-hackers.org/syntax/quoting#strong_quoting - */ - quote: function (value) { - var safe = /^[a-z0-9-_/.@%^=:]+$/i - - // Unless `value` is a simple shell-safe string, quote it. - if (!safe.test(value)) { - return util.format('\'%s\'', value.replace(/'/g, "\'\\'\'")) - } - - return value - }, - - escape: function (value) { - return value.replace(/\r/g, '\\r').replace(/\n/g, '\\n') - } -} diff --git a/src/helpers/shell.ts b/src/helpers/shell.ts new file mode 100644 index 000000000..e06c341a3 --- /dev/null +++ b/src/helpers/shell.ts @@ -0,0 +1,18 @@ +/** + * Use 'strong quoting' using single quotes so that we only need to deal with nested single quote characters. + * see: http://wiki.bash-hackers.org/syntax/quoting#strong_quoting + */ +export const quote = (value = ''): string => { + const safe = /^[a-z0-9-_/.@%^=:]+$/i; + + const isShellSafe = safe.test(value); + + if (isShellSafe) { + return value; + } + + // if the value is not shell safe, then quote it + return `'${value.replace(/'/g, "'\\''")}'`; +}; + +export const escape = (value: string): string => value.replace(/\r/g, '\\r').replace(/\n/g, '\\n'); diff --git a/src/helpers/utils.test.ts b/src/helpers/utils.test.ts new file mode 100644 index 000000000..2a8a9d009 --- /dev/null +++ b/src/helpers/utils.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest'; + +import { availableTargets, extname } from './utils.js'; + +describe('availableTargets', () => { + it('returns all available targets', () => { + expect(availableTargets()).toMatchSnapshot(); + }); + + describe('default value check', () => { + it.each(availableTargets().map(target => [target.title, target]))( + 'should match `default` value with one of the client keys (%s)', + (_, target) => { + expect(target.clients).toContainEqual(expect.objectContaining({ key: target.default })); + }, + ); + }); +}); + +describe('extname', () => { + it('returns the correct extension', () => { + expect(extname('c', 'libcurl')).toBe('.c'); + expect(extname('clojure', 'clj_http')).toBe('.clj'); + expect(extname('javascript', 'axios')).toBe('.js'); + expect(extname('node', 'axios')).toBe('.js'); + }); + + it('returns empty string if the extension is not found', () => { + // @ts-expect-error intentionally incorrect + expect(extname('ziltoid')).toBe(''); + }); +}); diff --git a/src/helpers/utils.ts b/src/helpers/utils.ts new file mode 100644 index 000000000..8a8df05a9 --- /dev/null +++ b/src/helpers/utils.ts @@ -0,0 +1,24 @@ +import type { ClientId, ClientInfo, TargetId, TargetInfo } from '../targets/index.js'; + +import { targets } from '../targets/index.js'; + +export interface AvailableTarget extends TargetInfo { + clients: ClientInfo[]; +} + +export const availableTargets = (): AvailableTarget[] => + Object.keys(targets).map(targetId => ({ + ...targets[targetId as TargetId].info, + clients: Object.keys(targets[targetId as TargetId].clientsById).map( + clientId => targets[targetId as TargetId].clientsById[clientId].info, + ), + })); + +export const extname = (targetId: TargetId, clientId: ClientId): '' | `.${string}` => { + const target = targets[targetId]; + if (!target) { + return ''; + } + + return target.clientsById[clientId]?.info.extname || ''; +}; diff --git a/src/index.js b/src/index.js deleted file mode 100644 index 67d922302..000000000 --- a/src/index.js +++ /dev/null @@ -1,249 +0,0 @@ -'use strict' - -//var debug = require('debug')('httpsnippet') -var debug = console.log; -var es = require('event-stream') -var MultiPartForm = require('form-data') -var qs = require('querystring') -var reducer = require('./helpers/reducer') -var targets = require('./targets') -var url = require('url') -var util = require('util') -var validate = require('har-validator/lib/async') - -// constructor -var HTTPSnippet = function (data) { - var entries - var self = this - var input = util._extend({}, data) - - // prep the main container - self.requests = [] - - // is it har? - if (input.log && input.log.entries) { - entries = input.log.entries - } else { - entries = [{ - request: input - }] - } - - entries.forEach(function (entry) { - // add optional properties to make validation successful - entry.request.httpVersion = entry.request.httpVersion || 'HTTP/1.1' - entry.request.queryString = entry.request.queryString || [] - entry.request.headers = entry.request.headers || [] - entry.request.cookies = entry.request.cookies || [] - entry.request.postData = entry.request.postData || {} - entry.request.postData.mimeType = entry.request.postData.mimeType || 'application/octet-stream' - - entry.request.bodySize = 0 - entry.request.headersSize = 0 - entry.request.postData.size = 0 - - validate.request(entry.request, function (err, valid) { - if (!valid) { - throw err - } - - self.requests.push(self.prepare(entry.request)) - }) - }) -} - -HTTPSnippet.prototype.prepare = function (request) { - // construct utility properties - request.queryObj = {} - request.headersObj = {} - request.cookiesObj = {} - request.allHeaders = {} - request.postData.jsonObj = false - request.postData.paramsObj = false - - // construct query objects - if (request.queryString && request.queryString.length) { - debug('queryString found, constructing queryString pair map') - - request.queryObj = request.queryString.reduce(reducer, {}) - } - - // construct headers objects - if (request.headers && request.headers.length) { - // loweCase header keys - request.headersObj = request.headers.reduceRight(function (headers, header) { - headers[header.name.toLowerCase()] = header.value - return headers - }, {}) - } - - // construct headers objects - if (request.cookies && request.cookies.length) { - request.cookiesObj = request.cookies.reduceRight(function (cookies, cookie) { - cookies[cookie.name] = cookie.value - return cookies - }, {}) - } - - // construct Cookie header - var cookies = request.cookies.map(function (cookie) { - return encodeURIComponent(cookie.name) + '=' + encodeURIComponent(cookie.value) - }) - - if (cookies.length) { - request.allHeaders.cookie = cookies.join('; ') - } - - switch (request.postData.mimeType) { - case 'multipart/mixed': - case 'multipart/related': - case 'multipart/form-data': - case 'multipart/alternative': - // reset values - request.postData.text = '' - request.postData.mimeType = 'multipart/form-data' - - if (request.postData.params) { - var form = new MultiPartForm() - - // easter egg - form._boundary = '---011000010111000001101001' - - request.postData.params.forEach(function (param) { - form.append(param.name, param.value || '', { - filename: param.fileName || null, - contentType: param.contentType || null - }) - }) - - form.pipe(es.map(function (data, cb) { - request.postData.text += data - })) - - request.postData.boundary = form.getBoundary() - request.headersObj['content-type'] = 'multipart/form-data; boundary=' + form.getBoundary() - } - break - - case 'application/x-www-form-urlencoded': - if (!request.postData.params) { - request.postData.text = '' - } else { - request.postData.paramsObj = request.postData.params.reduce(reducer, {}) - - // always overwrite - request.postData.text = qs.stringify(request.postData.paramsObj) - } - break - - case 'text/json': - case 'text/x-json': - case 'application/json': - case 'application/x-json': - request.postData.mimeType = 'application/json' - - if (request.postData.text) { - try { - request.postData.jsonObj = JSON.parse(request.postData.text) - } catch (e) { - debug(e) - - // force back to text/plain - // if headers have proper content-type value, then this should also work - request.postData.mimeType = 'text/plain' - } - } - break - } - - // create allHeaders object - request.allHeaders = util._extend(request.allHeaders, request.headersObj) - - // deconstruct the uri - request.uriObj = url.parse(request.url, true, true) - - // merge all possible queryString values - request.queryObj = util._extend(request.queryObj, request.uriObj.query) - - // reset uriObj values for a clean url - request.uriObj.query = null - request.uriObj.search = null - request.uriObj.path = request.uriObj.pathname - - // keep the base url clean of queryString - request.url = url.format(request.uriObj) - - // update the uri object - request.uriObj.query = request.queryObj - request.uriObj.search = qs.stringify(request.queryObj) - - if (request.uriObj.search) { - request.uriObj.path = request.uriObj.pathname + '?' + request.uriObj.search - } - - // construct a full url - request.fullUrl = url.format(request.uriObj) - - return request -} - -HTTPSnippet.prototype.convert = function (target, client, opts) { - if (!opts && client) { - opts = client - } - - var func = this._matchTarget(target, client) - - if (func) { - var results = this.requests.map(function (request) { - return func(request, opts) - }) - - return results.length === 1 ? results[0] : results - } - - return false -} - -HTTPSnippet.prototype._matchTarget = function (target, client) { - // does it exist? - if (!targets.hasOwnProperty(target)) { - return false - } - - // shorthand - if (typeof client === 'string' && typeof targets[target][client] === 'function') { - return targets[target][client] - } - - // default target - return targets[target][targets[target].info.default] -} - -// exports -module.exports = HTTPSnippet - -module.exports.availableTargets = function () { - return Object.keys(targets).map(function (key) { - var target = util._extend({}, targets[key].info) - var clients = Object.keys(targets[key]) - - .filter(function (prop) { - return !~['info', 'index'].indexOf(prop) - }) - - .map(function (client) { - return targets[key][client].info - }) - - if (clients.length) { - target.clients = clients - } - - return target - }) -} - -module.exports.extname = function (target) { - return targets[target] ? targets[target].info.extname : '' -} diff --git a/src/index.test.ts b/src/index.test.ts new file mode 100644 index 000000000..b2cfb267b --- /dev/null +++ b/src/index.test.ts @@ -0,0 +1,283 @@ +import type { Request } from './index.js'; + +import { describe, expect, it } from 'vitest'; + +import { mimetypes } from './fixtures/mimetypes.js'; +import headers from './fixtures/requests/headers.cjs'; +import query from './fixtures/requests/query.cjs'; +import short from './fixtures/requests/short.cjs'; +import { HTTPSnippet } from './index.js'; + +describe('HTTPSnippet', () => { + it('should return false if no matching target', () => { + const snippet = new HTTPSnippet(short.log.entries[0].request as Request); + + // @ts-expect-error intentionally incorrect + const result = snippet.convert(null); + + expect(result).toStrictEqual([false]); + }); + + describe('repair malformed `postData`', () => { + it('should repair a HAR with an empty `postData` object', () => { + const snippet = new HTTPSnippet({ + method: 'POST', + url: 'https://httpbin.org/anything', + postData: {}, + } as Request); + + snippet.convert('node'); + + const request = snippet.requests[0]; + expect(request.postData).toStrictEqual({ + mimeType: 'application/octet-stream', + }); + }); + + it('should repair a HAR with a `postData` params object missing `mimeType`', () => { + // @ts-expect-error Testing a malformed HAR case. + const snippet = new HTTPSnippet({ + method: 'POST', + url: 'https://httpbin.org/anything', + postData: { + params: [], + }, + } as Request); + snippet.convert('node'); + + const request = snippet.requests[0]; + expect(request.postData).toStrictEqual({ + mimeType: 'application/octet-stream', + params: [], + }); + }); + + it('should repair a HAR with a `postData` text object missing `mimeType`', () => { + const snippet = new HTTPSnippet({ + method: 'POST', + url: 'https://httpbin.org/anything', + postData: { + text: '', + }, + } as Request); + snippet.convert('node'); + + const request = snippet.requests[0]; + expect(request.postData).toStrictEqual({ + mimeType: 'application/octet-stream', + text: '', + }); + }); + }); + + it('should parse HAR file with multiple entries', () => { + const snippet = new HTTPSnippet({ + log: { + version: '1.2', + creator: { + name: 'HTTPSnippet', + version: '1.0.0', + }, + entries: [ + { + request: { + method: 'GET', + url: 'https://httpbin.org/anything', + }, + }, + { + request: { + method: 'POST', + url: 'https://httpbin.org/anything', + }, + }, + ], + }, + }); + + snippet.convert('node'); + + expect(snippet).toHaveProperty('requests'); + expect(Array.isArray(snippet.requests)).toBe(true); + expect(snippet.requests).toHaveLength(2); + }); + + describe('mimetype conversion', () => { + it.each([ + { + input: 'multipart/mixed', + expected: 'multipart/form-data', + }, + { + input: 'multipart/related', + expected: 'multipart/form-data', + }, + { + input: 'multipart/alternative', + expected: 'multipart/form-data', + }, + { + input: 'text/json', + expected: 'application/json', + }, + { + input: 'text/x-json', + expected: 'application/json', + }, + { + input: 'application/x-json', + expected: 'application/json', + }, + { + input: 'invalid-json', + expected: 'text/plain', + }, + ] as { + expected: string; + input: keyof typeof mimetypes; + }[])('mimetype conversion of $input to $output', ({ input, expected }) => { + const snippet = new HTTPSnippet(mimetypes[input]); + snippet.convert('node'); + + const request = snippet.requests[0]; + expect(request.postData.mimeType).toStrictEqual(expected); + }); + }); + + it('should set postData.text to empty string when postData.params is undefined in application/x-www-form-urlencoded', () => { + const snippet = new HTTPSnippet(mimetypes['application/x-www-form-urlencoded']); + snippet.convert('node'); + + const request = snippet.requests[0]; + expect(request.postData.text).toBe(''); + }); + + describe('requestExtras', () => { + describe('uriObj', () => { + it('should add uriObj', () => { + const snippet = new HTTPSnippet(query.log.entries[0].request as Request); + snippet.convert('node'); + + const request = snippet.requests[0]; + + expect(request.uriObj).toMatchObject({ + auth: null, + hash: null, + host: 'httpbin.org', + hostname: 'httpbin.org', + href: 'https://httpbin.org/anything?key=value', + path: '/anything?foo=bar&foo=baz&baz=abc&key=value', + pathname: '/anything', + port: null, + protocol: 'https:', + query: { + baz: 'abc', + key: 'value', + foo: ['bar', 'baz'], + }, + search: 'foo=bar&foo=baz&baz=abc&key=value', + slashes: true, + }); + }); + + it('should fix the `path` property of uriObj to match queryString', () => { + const snippet = new HTTPSnippet(query.log.entries[0].request as Request); + snippet.convert('node'); + + const request = snippet.requests[0]; + expect(request.uriObj.path).toBe('/anything?foo=bar&foo=baz&baz=abc&key=value'); + }); + }); + + describe('queryObj', () => { + it('should add queryObj', () => { + const snippet = new HTTPSnippet(query.log.entries[0].request as Request); + snippet.convert('node'); + + const request = snippet.requests[0]; + expect(request.queryObj).toMatchObject({ baz: 'abc', key: 'value', foo: ['bar', 'baz'] }); + }); + }); + + describe('headersObj', () => { + it('should add headersObj', () => { + const snippet = new HTTPSnippet(headers.log.entries[0].request as Request); + snippet.convert('node'); + + const request = snippet.requests[0]; + expect(request.headersObj).toMatchObject({ + accept: 'application/json', + 'x-foo': 'Bar', + }); + }); + + it('should add headersObj to source object case insensitive when HTTP/1.0', () => { + const snippet = new HTTPSnippet({ + ...headers.log.entries[0].request, + httpVersion: 'HTTP/1.1', + headers: [ + ...headers.log.entries[0].request.headers, + { + name: 'Kong-Admin-Token', + value: 'Ziltoid The Omniscient', + }, + ], + } as Request); + + snippet.convert('node'); + + const request = snippet.requests[0]; + + expect(request.headersObj).toMatchObject({ + 'Kong-Admin-Token': 'Ziltoid The Omniscient', + accept: 'application/json', + 'x-foo': 'Bar', + }); + }); + + it('should add headersObj to source object lowercased when HTTP/2.x', () => { + const snippet = new HTTPSnippet({ + ...headers.log.entries[0].request, + httpVersion: 'HTTP/2', + headers: [ + ...headers.log.entries[0].request.headers, + { + name: 'Kong-Admin-Token', + value: 'Ziltoid The Omniscient', + }, + ], + } as Request); + + snippet.convert('node'); + + const request = snippet.requests[0]; + + expect(request.headersObj).toMatchObject({ + 'kong-admin-token': 'Ziltoid The Omniscient', + accept: 'application/json', + 'x-foo': 'Bar', + }); + }); + }); + + describe('url', () => { + it('should modify the original url to strip query string', () => { + const snippet = new HTTPSnippet(query.log.entries[0].request as Request); + snippet.convert('node'); + + const request = snippet.requests[0]; + expect(request.url).toBe('https://httpbin.org/anything'); + }); + }); + + describe('fullUrl', () => { + it('adds fullURL', () => { + const snippet = new HTTPSnippet(query.log.entries[0].request as Request); + snippet.convert('node'); + + const request = snippet.requests[0]; + expect(request.fullUrl).toBe('https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value'); + }); + }); + }); +}); diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 000000000..e18e0e851 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,386 @@ +/** biome-ignore-all lint/performance/noBarrelFile: This doesn't really have the aspects of being a barrel file. */ +import type { UrlWithParsedQuery } from 'node:url'; +import type { Request as NpmHarRequest, Param, PostDataCommon } from 'har-format'; +import type { Merge } from 'type-fest'; +import type { CodeBuilderOptions } from './helpers/code-builder.js'; +import type { ReducedHelperObject } from './helpers/reducer.js'; +import type { ClientId, TargetId } from './targets/index.js'; + +import { format as urlFormat, parse as urlParse } from 'node:url'; + +import { stringify as queryStringify } from 'qs'; + +import { getHeaderName } from './helpers/headers.js'; +import { reducer } from './helpers/reducer.js'; +import { targets } from './targets/index.js'; + +export { availableTargets, extname } from './helpers/utils.js'; +export { addClientPlugin, addTarget, addTargetClient } from './targets/index.js'; + +/** is this wrong? yes. according to the spec (http://www.softwareishard.com/blog/har-12-spec/#postData) it's technically wrong since `params` and `text` are (by the spec) mutually exclusive. However, in practice, this is not what is often the case. + * + * In general, this library takes a _descriptive_ rather than _perscriptive_ approach (see https://amyrey.web.unc.edu/classes/ling-101-online/tutorials/understanding-prescriptive-vs-descriptive-grammar/). + * + * Then, in addition to that, it really adds to complexity with TypeScript (TypeScript takes this constraint very very seriously) in a way that's not actually super useful. So, we treat this object as though it could have both or either of `params` and/or `text`. + */ +type PostDataBase = PostDataCommon & { + params?: Param[]; + text?: string; +}; + +export type { Client } from './targets/index.js'; + +export type HarRequest = Omit & { postData: PostDataBase }; + +export interface RequestExtras { + allHeaders: ReducedHelperObject; + cookiesObj: ReducedHelperObject; + fullUrl: string; + headersObj: ReducedHelperObject; + postData: PostDataBase & { + boundary?: string; + jsonObj?: ReducedHelperObject; + paramsObj?: ReducedHelperObject; + }; + queryObj: ReducedHelperObject; + uriObj: UrlWithParsedQuery; +} + +export type Request = HarRequest & RequestExtras; + +interface Entry { + request: Partial; +} + +interface HarEntry { + log: { + creator: { + name: string; + version: string; + }; + entries: Entry[]; + version: string; + }; +} + +export type Options = Merge>; + +export interface HTTPSnippetOptions { + harIsAlreadyEncoded?: boolean; +} + +const isHarEntry = (value: any): value is HarEntry => + typeof value === 'object' && + 'log' in value && + typeof value.log === 'object' && + 'entries' in value.log && + Array.isArray(value.log.entries); + +export class HTTPSnippet { + initCalled = false; + + entries: Entry[] = []; + + requests: Request[] = []; + + options: HTTPSnippetOptions = {}; + + constructor(input: HarEntry | HarRequest, opts: HTTPSnippetOptions = {}) { + this.options = { + harIsAlreadyEncoded: false, + ...opts, + }; + + // prep the main container + this.requests = []; + + // is it har? + if (isHarEntry(input)) { + this.entries = input.log.entries; + } else { + this.entries = [ + { + request: input, + }, + ]; + } + } + + init(): HTTPSnippet { + this.initCalled = true; + + this.requests = this.entries.map(({ request }) => { + // add optional properties to make validation successful + const req = { + bodySize: 0, + headersSize: 0, + headers: [], + cookies: [], + httpVersion: 'HTTP/1.1', + queryString: [], + postData: { + mimeType: request.postData?.mimeType || 'application/octet-stream', + }, + ...request, + }; + + // Per the HAR spec `mimeType` needs to always be present if we have a `postData` object. + if (req.postData && !req.postData.mimeType) { + req.postData.mimeType = 'application/octet-stream'; + } + + return this.prepare(req as HarRequest, this.options); + }); + + return this; + } + + prepare( + harRequest: HarRequest, + options: HTTPSnippetOptions, + ): Request & { + allHeaders: Record; + fullUrl: string; + url: string; + uriObj: { + query: ReducedHelperObject; + search: string; + path: string | null; + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + pathname: string | null; + protocol: string | null; + slashes: boolean | null; + port: string | null; + }; + } { + const request: Request = { + ...harRequest, + fullUrl: '', + uriObj: {} as UrlWithParsedQuery, + queryObj: {}, + headersObj: {}, + cookiesObj: {}, + allHeaders: {}, + }; + + // construct query objects + if (request?.queryString.length) { + request.queryObj = request.queryString.reduce(reducer, {}); + } + + // construct headers objects + if (request?.headers.length) { + const http2VersionRegex = /^HTTP\/2/; + request.headersObj = request.headers.reduce((accumulator, { name, value }) => { + const headerName = http2VersionRegex.exec(request.httpVersion) ? name.toLocaleLowerCase() : name; + return { + ...accumulator, + [headerName]: value, + }; + }, {}); + } + + // construct headers objects + if (request?.cookies.length) { + request.cookiesObj = request.cookies.reduceRight( + (accumulator, { name, value }) => ({ + ...accumulator, + [name]: value, + }), + {}, + ); + } + + // construct Cookie header + const cookies = request.cookies?.map(({ name, value }) => { + if (options.harIsAlreadyEncoded) { + return `${name}=${value}`; + } + + return `${encodeURIComponent(name)}=${encodeURIComponent(value)}`; + }); + + if (cookies?.length) { + request.allHeaders.cookie = cookies.join('; '); + } + + switch (request.postData.mimeType) { + case 'multipart/mixed': + case 'multipart/related': + case 'multipart/form-data': + case 'multipart/alternative': + // reset values + request.postData.text = ''; + request.postData.mimeType = 'multipart/form-data'; + + if (request.postData?.params) { + const boundary = '---011000010111000001101001'; // this is binary for "api" (easter egg) + const carriage = `${boundary}--`; + const rn = '\r\n'; + + /*! formdata-polyfill. MIT License. Jimmy Wärting */ + const escapeStr = (str: string) => str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22'); + const normalizeLinefeeds = (value: string) => value.replace(/\r?\n|\r/g, '\r\n'); + + const payload = [`--${boundary}`]; + request.postData?.params.forEach((param, i) => { + const name = param.name; + const value = param.value || ''; + const filename = param.fileName || null; + const contentType = param.contentType || 'application/octet-stream'; + + if (filename) { + payload.push( + `Content-Disposition: form-data; name="${escapeStr(normalizeLinefeeds(name))}"; filename="${filename}"`, + ); + payload.push(`Content-Type: ${contentType}`); + } else { + payload.push(`Content-Disposition: form-data; name="${escape(normalizeLinefeeds(name))}"`); + } + + payload.push(''); + payload.push(normalizeLinefeeds(value)); + + if (i !== (request.postData.params as Param[]).length - 1) { + payload.push(`--${boundary}`); + } + }); + + payload.push(`--${carriage}`); + + request.postData.boundary = boundary; + request.postData.text = payload.join(rn); + + // Since headers are case-sensitive we need to see if there's an existing `Content-Type` header that we can override. + const contentTypeHeader = getHeaderName(request.headersObj, 'content-type') || 'content-type'; + + request.headersObj[contentTypeHeader] = `multipart/form-data; boundary=${boundary}`; + } + break; + + case 'application/x-www-form-urlencoded': + if (!request.postData.params) { + request.postData.text = ''; + } else { + // @ts-expect-error the `har-format` types make this challenging + request.postData.paramsObj = request.postData.params.reduce(reducer, {}); + + // always overwrite + request.postData.text = queryStringify(request.postData.paramsObj); + } + break; + + case 'text/json': + case 'text/x-json': + case 'application/json': + case 'application/x-json': + request.postData.mimeType = 'application/json'; + + if (request.postData.text) { + try { + request.postData.jsonObj = JSON.parse(request.postData.text); + } catch { + // force back to `text/plain` if headers have proper content-type value, then this should also work + request.postData.mimeType = 'text/plain'; + } + } + break; + } + + // create allHeaders object + const allHeaders = { + ...request.allHeaders, + ...request.headersObj, + }; + + const urlWithParsedQuery = urlParse(request.url, true, true); //? + + // query string key/value pairs in with literal querystrings containd within the url + request.queryObj = { + ...request.queryObj, + ...(urlWithParsedQuery.query as ReducedHelperObject), + }; //? + + // reset uriObj values for a clean url + let search: string; + if (options.harIsAlreadyEncoded) { + search = queryStringify(request.queryObj, { + encode: false, + indices: false, + }); + } else { + search = queryStringify(request.queryObj, { + indices: false, + }); + } + + const uriObj = { + ...urlWithParsedQuery, + query: request.queryObj, + search, + path: search ? `${urlWithParsedQuery.pathname}?${search}` : urlWithParsedQuery.pathname, + }; + + // keep the base url clean of queryString + const url = urlFormat({ + ...urlWithParsedQuery, + query: null, + search: null, + }); + + const fullUrl = urlFormat({ + ...urlWithParsedQuery, + ...uriObj, + }); + + return { + ...request, + allHeaders, + fullUrl, + url, + uriObj, + }; + } + + convert(targetId: TargetId, clientId?: ClientId, options?: Options): (string | false)[] { + if (!this.initCalled) { + this.init(); + } + + if (!options && clientId) { + options = { clientId }; + } + + const target = targets[targetId]; + if (!target) { + return [false]; + } + + const { convert } = target.clientsById[clientId || target.info.default]; + const results = this.requests.map(request => convert(request, options)); + return results; + } + + installation(targetId: TargetId, clientId?: ClientId, options?: Options): (string | false)[] { + if (!this.initCalled) { + this.init(); + } + + if (!options && clientId) { + options = { clientId }; + } + + const target = targets[targetId]; + if (!target) { + return [false]; + } + + const { info } = target.clientsById[clientId || target.info.default]; + const results = this.requests.map(request => (info?.installation ? info.installation(request, options) : false)); + return results; + } +} diff --git a/src/integration.test.ts b/src/integration.test.ts new file mode 100644 index 000000000..2e9920e15 --- /dev/null +++ b/src/integration.test.ts @@ -0,0 +1,358 @@ +import type { Response } from 'har-format'; +import type { AvailableTarget } from './helpers/utils.js'; +import type { Request } from './index.js'; +import type { TargetId } from './targets/index.js'; + +import shell from 'node:child_process'; +import { readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { format } from 'node:util'; + +import { describe, expect, test } from 'vitest'; + +import { availableTargets, extname } from './helpers/utils.js'; + +const expectedBasePath = ['src', 'fixtures', 'requests']; + +const ENVIRONMENT_CONFIG = { + docker: { + // Every client + target that we test in an HTTPBin-powered Docker environment. + c: ['libcurl'], + csharp: ['httpclient', 'restsharp'], + go: ['native'], + node: ['axios', 'fetch'], + php: ['curl', 'guzzle'], + python: ['requests'], + shell: ['curl'], + }, + local: { + // When running tests locally, or within a CI environment, we shold limit the targets that + // we're testing so as to not require a mess of dependency requirements that would be better + // served within a container. + node: ['fetch'], + php: ['curl'], + python: ['requests'], + shell: ['curl'], + }, +}; + +// Some environments are not as simple as `interpreter ` Here is where we +// put the instructions for how to run those environments in our docker +// containers +const EXEC_FUNCTION: Record Buffer> = { + csharp: (fixturePath: string) => { + // - copy the given fixture into a file called Program.cs - c# expects + // there to be only one file with top-level code in any project, so we'll + // keep this project around but copy each fixture in as Program.cs + // - run Program.cs and return the output + shell.execSync(`cp ${fixturePath} /src/IntTestCsharp/Program.cs`); + return shell.execSync('cd /src/IntTestCsharp && dotnet run Program.cs'); + }, + c: (fixturePath: string) => { + const inf = `/tmp/${path.basename(fixturePath, '.c')}.c`; + const exe = `/tmp/${path.basename(fixturePath, '.c')}`; + writeFileSync( + inf, + ` +#include +#include +#include + +int main(void) { + ${readFileSync(fixturePath, 'utf8')} +}`, + ); + shell.execSync(`gcc ${inf} -o ${exe} -lcurl`); + return shell.execSync(exe); + }, + go: (fixturePath: string) => { + return shell.execSync(`go run ${fixturePath}`); + }, +}; + +const inputFileNames = readdirSync(path.join(...expectedBasePath), 'utf-8'); + +const fixtures: [string, Request][] = inputFileNames.map(inputFileName => [ + inputFileName.replace(path.extname(inputFileName), ''), + // biome-ignore lint/style/noCommonJs: Because we're dynamically loading fixtures we need to use `require`. + require(path.resolve(...expectedBasePath, inputFileName)), +]); + +/** ignore a set of fixtures from being run in tests */ +const fixtureIgnoreFilter: string[] = [ + // Some targets don't support native file handling without supplying a raw boundary header and + // because the HAR for `multipart-file` doesn't include the files contents, just its filename + // running one of these generated snippets doesn't send anything for the file because the + // FormData API rewrites the incoming full path of `src/fixtures/files/hello.txt` to just + // `hello.txt`. Instead of monkeypatching these targets to have the full file path at time ofb + // this execution suite we're just ignoring this test case as file uploading is well covered by + // the other cases we have. + 'multipart-file', +]; + +const environmentFilter = (): string[] => { + if (process.env.HTTPBIN) { + return Object.keys(ENVIRONMENT_CONFIG.docker); + } else if (process.env.NODE_ENV === 'test') { + return Object.keys(ENVIRONMENT_CONFIG.local); + } + + throw new Error('Unsupported environment supplied to `environmentFilter`.'); +}; + +const clientFilter = (target: TargetId): string[] => { + if (process.env.HTTPBIN) { + return ENVIRONMENT_CONFIG.docker[target]; + } else if (process.env.NODE_ENV === 'test') { + return ENVIRONMENT_CONFIG.local[target]; + } + + throw new Error('Unsupported environment supplied to `clientFilter`.'); +}; + +const testFilter = + (property: keyof T, list: T[keyof T][], ignore = false) => + (item: T) => { + if (!list.length) { + return true; + } else if (ignore) { + return list.length > 0 ? !list.includes(item[property]) : true; + } + + return list.length > 0 ? list.includes(item[property]) : true; + }; + +/** + * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_eval! + */ +function looseJSONParse(obj: any) { + return new Function(`"use strict";return ${obj}`)(); +} + +availableTargets() + .filter(target => target.cli) + .filter(testFilter('key', environmentFilter())) + .forEach(target => { + const { key: targetId, title, clients } = target; + + describe.skipIf(process.env.NODE_ENV === 'test')(`${title} integration tests`, () => { + clients.filter(testFilter('key', clientFilter(target.key))).forEach(({ key: clientId }) => { + // If we're in an HTTPBin-powered Docker environment we only want to run tests for the + // client that our Docker has been configured for. + const shouldSkip = process.env.HTTPBIN && process.env.INTEGRATION_CLIENT !== targetId; + + describe.skipIf(shouldSkip)(`${clientId}`, () => { + fixtures.filter(testFilter(0, fixtureIgnoreFilter, true)).forEach(([fixture, request]) => { + if (fixture === 'custom-method' && clientId === 'restsharp') { + // restsharp doesn't even let you express calling an invalid + // method, there's no point in testing it against this particular + // fixture + return; + } + + integrationTest(clientId, target, fixture, request); + }); + }); + }); + }); + }); + +function integrationTest( + clientId: string, + { key: targetId, cli: targetCLI }: AvailableTarget, + fixture: string, + request: Request, +) { + test(`should return the expected response for \`${fixture}\``, () => { + const fixtureExtension = extname(targetId, clientId); + const basePath = path.join('src', 'targets', targetId, clientId, 'fixtures', `${fixture}${fixtureExtension}`); + + // Clone the fixture we're testing against to another object because for multipart cases + // we're deleting the header, and if we don't clone the fixture to another object, that + // deleted header will cause other tests to fail because it's missing where other tests + // are expecting it. + const har = JSON.parse(JSON.stringify(request)); + const url = har.log.entries[0].request.url; + const harResponse = har.log.entries[0].response as Response; + + let stdout: Buffer | string; + try { + // If there's a runner function, use that; otherwise just call + // + if (EXEC_FUNCTION[targetId]) { + stdout = EXEC_FUNCTION[targetId](basePath); + } else { + stdout = shell.execSync(format(targetCLI, basePath)); + } + } catch (err) { + // If this target throws errors when it can't access a method on the server that + // doesn't exist let's make sure that it only did that on the `custom-method` test, + // otherwise something went wrong! + if (err.message.toLowerCase().match(/405/)) { + expect(fixture).toBe('custom-method'); + return; + } + + throw err; + } + + stdout = stdout.toString().trim(); + + // If the endpoint we're testing against returns HTML we should do a string comparison + // instead of parsing a non-existent JSON response. + if (harResponse.headers.find(header => header.name === 'Content-Type' && header.value === 'text/html')) { + // const stdoutTrimmed = stdout.toString().trim(); + + try { + expect(stdout).toStrictEqual(harResponse.content.text); + } catch { + // Some targets always assume that their response is JSON and for this case + // (`custom-method`) will print out an empty string instead. + expect(stdout).toBe(''); + } + + return; + } + + const expected = JSON.parse(String(harResponse.content.text)); + let response: any; + try { + response = JSON.parse(stdout); + } catch (err) { + // Some JS targets print out their response with `console.log(json)` which creates + // a JSON object that we can't access with `JSON.parse()`. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_eval! + if (!['.js', '.cjs'].includes(fixtureExtension)) { + throw err; + } + + response = looseJSONParse(stdout); + } + + // If we're testing against the `/cookies` or `/headers` endpoints it returns a + // different schema than everything else. + if (url === 'https://httpbin.org/cookies') { + expect(response.cookies).toStrictEqual(expected.cookies); + return; + } else if (url === 'https://httpbin.org/headers') { + expect(response.headers).toStrictEqual( + expect.objectContaining({ + ...expected.headers, + }), + ); + + return; + } + + expect(response.args).toStrictEqual(expected.args); + + // Some targets send files that have a new line at the end of them without that new + // line so we need to make our assertion universal across all targets. + let files = {}; + if (Object.keys(response.files || {}).length) { + files = Object.entries(response.files) + .map(([k, v]) => ({ [k]: String(v).trim() })) + .reduce((prev, next) => Object.assign(prev, next)); + } + + expect(files).toStrictEqual(expected.files); + + expect(response.form || {}).toStrictEqual(expected.form); + expect(response.method).toStrictEqual(expected.method); + expect(response.url).toStrictEqual(expected.url); + + // Because some JS targets may be returning their payloads with `console.log()` that + // method has a default depth, at which point it turns objects into `[Object]`. When + // we then run that through `looseJSONParse` it gets transformed again into + // `[ [Function: Object] ]`. Since we don't have access to the original object context + // from the target snippet, we rewrite our response a bit so that it can partially + // match what we're looking for. + // + // Of course the side effect to this is is that now these test cases may be subject + // to flakiness but without updating the root snippets to not use `console.log()`, + // which we don't want to do, this is the way it's got to be. + if (fixture === 'application-json' && ['.js', '.cjs'].includes(fixtureExtension)) { + const respJSON = response.json; + respJSON.arr_mix[2] = { arr_mix_nested: [] }; + + expect(respJSON).toStrictEqual(expected.json); + } else { + expect(response.json).toStrictEqual(expected.json); + } + + const expectJson = expected.headers?.['Content-Type']?.[0].includes('application/json'); + // if there is a request header containing "multipart/form-data", we're + // expecting a multipart response. We can't check the expected headers here + // because in the case of multipart-form-data-no-params, we don't want to + // assert that the request contained a content-type, since there was no + // content + const expectMultipart = har.log.entries[0].request.headers + ?.find((x: { name: string; value: string }) => x.name.toLowerCase().includes('content-type')) + ?.value?.includes('multipart/form-data'); + + // If we're dealing with a JSON payload, some snippets add indents and new lines to + // the data that is sent to + // HTTPBin (that it then returns back us in the same format) -- to make this `data` + // check target agnostic we need to parse and re-stringify our expectations so that + // this test can universally match them all. + if (expectJson) { + // In our postdata-malformed fixture we're sending a POST payload without any + // content so what HTTPBin sends back to us is a `json: null` and `data: ''`, which + // we need to specially assert here as running `JSON.parse()` on an empty string + // will throw an exception. + if (fixture === 'postdata-malformed' && response.data === '') { + expect(expected.data).toBe(''); + } else { + expect(JSON.stringify(JSON.parse(response.data))).toStrictEqual(JSON.stringify(JSON.parse(expected.data))); + } + // httpbin-go includes multipart/form-data in the `data` response + // field, which I think is sensible. In this case, the response + // includes a randomly-generated boundary and is difficult to + // sensibly match against, so don't check the data attribute + } else if (!expectMultipart) { + expect(response.data).toStrictEqual(expected.data); + } + + // `multipart/form-data` needs some special tests to assert that boundaries were sent + // and received properly. + if (expectMultipart) { + // if the Content type headers don't match identically, check that there + // is a boundary present in the data. If they do match exactly, no need + // to do anything; we tested what we wanted + // + // Except the "multipart-form-data-no-params" fixture, because in this + // test there is no content and so libraries should not be required to + // send a content-type header + if ( + expected.headers['Content-Type']?.[0] !== response.headers['Content-Type']?.[0] && + fixture !== 'multipart-form-data-no-params' + ) { + const contentTypes: string[] = response.headers['Content-Type'][0].split(';').map((p: string) => p.trim()); + + expect(contentTypes).toHaveLength(2); + expect(contentTypes.map(type => type.includes('boundary=')).filter(Boolean)).toHaveLength(1); + } + } else { + // Content-type headers particularly may contain the text-encoding, so we + // can't check for exact equality. For example, "Content-Type: + // text/plain; charset=utf-8" is perfectly valid and we don't want to + // fail it for not having the `text/plain` content type. In the future, + // we may want to try and be more smart about parsing the header value, + // but for now, just check that the expected header value is contained + // anywhere within the received header + const headers = expected.headers as Record; + Object.entries(headers).forEach(([name, value]) => { + // In the postdata-malformed fixture, we're sending a POST without any + // body. Some libraries absolutely refuse to add an `application/json` + // content-type header for a request without a body, which I think is + // sensible. Allow those cases to pass rather than going long miles to + // force libraries to act stupidly. + if (name === 'Content-Type' && fixture === 'postdata-malformed') { + return; + } + expect(response.headers).toHaveProperty(name); + expect(response.headers[name][0]).toContain(value[0]); + }); + } + }); +} diff --git a/src/targets/c/index.js b/src/targets/c/index.js deleted file mode 100644 index 0a6272651..000000000 --- a/src/targets/c/index.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict' - -module.exports = { - info: { - key: 'c', - title: 'C', - extname: '.c', - default: 'libcurl' - }, - - libcurl: require('./libcurl') -} diff --git a/src/targets/c/libcurl.js b/src/targets/c/libcurl.js deleted file mode 100644 index aad328e28..000000000 --- a/src/targets/c/libcurl.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict' - -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var code = new CodeBuilder() - - code.push('CURL *hnd = curl_easy_init();') - .blank() - .push('curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "%s");', source.method.toUpperCase()) - .push('curl_easy_setopt(hnd, CURLOPT_URL, "%s");', source.fullUrl) - - // Add headers, including the cookies - var headers = Object.keys(source.headersObj) - - // construct headers - if (headers.length) { - code.blank() - .push('struct curl_slist *headers = NULL;') - - headers.forEach(function (key) { - code.push('headers = curl_slist_append(headers, "%s: %s");', key, source.headersObj[key]) - }) - - code.push('curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);') - } - - // construct cookies - if (source.allHeaders.cookie) { - code.blank() - .push('curl_easy_setopt(hnd, CURLOPT_COOKIE, "%s");', source.allHeaders.cookie) - } - - if (source.postData.text) { - code.blank() - .push('curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, %s);', JSON.stringify(source.postData.text)) - } - - code.blank() - .push('CURLcode ret = curl_easy_perform(hnd);') - - return code.join() -} - -module.exports.info = { - key: 'libcurl', - title: 'Libcurl', - link: 'http://curl.haxx.se/libcurl/', - description: 'Simple REST and HTTP API Client for C' -} diff --git a/src/targets/c/libcurl/client.ts b/src/targets/c/libcurl/client.ts new file mode 100644 index 000000000..99c1d57bf --- /dev/null +++ b/src/targets/c/libcurl/client.ts @@ -0,0 +1,54 @@ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { escapeForDoubleQuotes } from '../../../helpers/escape.js'; + +export const libcurl: Client = { + info: { + key: 'libcurl', + title: 'Libcurl', + link: 'http://curl.haxx.se/libcurl', + description: 'Simple REST and HTTP API Client for C', + extname: '.c', + }, + convert: ({ method, fullUrl, headersObj, allHeaders, postData }) => { + const { push, blank, join } = new CodeBuilder(); + + push('CURL *hnd = curl_easy_init();'); + blank(); + push(`curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "${method.toUpperCase()}");`); + push('curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout);'); + push(`curl_easy_setopt(hnd, CURLOPT_URL, "${fullUrl}");`); + + // Add headers, including the cookies + const headers = Object.keys(headersObj); + + // construct headers + if (headers.length) { + blank(); + push('struct curl_slist *headers = NULL;'); + + headers.forEach(header => { + push(`headers = curl_slist_append(headers, "${header}: ${escapeForDoubleQuotes(headersObj[header])}");`); + }); + + push('curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);'); + } + + // construct cookies + if (allHeaders.cookie) { + blank(); + push(`curl_easy_setopt(hnd, CURLOPT_COOKIE, "${allHeaders.cookie}");`); + } + + if (postData.text) { + blank(); + push(`curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, ${JSON.stringify(postData.text)});`); + } + + blank(); + push('CURLcode ret = curl_easy_perform(hnd);'); + + return join(); + }, +}; diff --git a/src/targets/c/libcurl/fixtures/application-form-encoded.c b/src/targets/c/libcurl/fixtures/application-form-encoded.c new file mode 100644 index 000000000..67e2c3bc0 --- /dev/null +++ b/src/targets/c/libcurl/fixtures/application-form-encoded.c @@ -0,0 +1,13 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/anything"); + +struct curl_slist *headers = NULL; +headers = curl_slist_append(headers, "content-type: application/x-www-form-urlencoded"); +curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); + +curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "foo=bar&hello=world"); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/application-json.c b/src/targets/c/libcurl/fixtures/application-json.c new file mode 100644 index 000000000..de2a5534f --- /dev/null +++ b/src/targets/c/libcurl/fixtures/application-json.c @@ -0,0 +1,13 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/anything"); + +struct curl_slist *headers = NULL; +headers = curl_slist_append(headers, "content-type: application/json"); +curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); + +curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":[]}],\"boolean\":false}"); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/cookies.c b/src/targets/c/libcurl/fixtures/cookies.c new file mode 100644 index 000000000..c8c4079b6 --- /dev/null +++ b/src/targets/c/libcurl/fixtures/cookies.c @@ -0,0 +1,9 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/cookies"); + +curl_easy_setopt(hnd, CURLOPT_COOKIE, "foo=bar; bar=baz"); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/custom-method.c b/src/targets/c/libcurl/fixtures/custom-method.c new file mode 100644 index 000000000..588bcbf22 --- /dev/null +++ b/src/targets/c/libcurl/fixtures/custom-method.c @@ -0,0 +1,7 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "PROPFIND"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/anything"); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/full.c b/src/targets/c/libcurl/fixtures/full.c new file mode 100644 index 000000000..1a669ff38 --- /dev/null +++ b/src/targets/c/libcurl/fixtures/full.c @@ -0,0 +1,16 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value"); + +struct curl_slist *headers = NULL; +headers = curl_slist_append(headers, "accept: application/json"); +headers = curl_slist_append(headers, "content-type: application/x-www-form-urlencoded"); +curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); + +curl_easy_setopt(hnd, CURLOPT_COOKIE, "foo=bar; bar=baz"); + +curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "foo=bar"); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/headers.c b/src/targets/c/libcurl/fixtures/headers.c new file mode 100644 index 000000000..0163e2c46 --- /dev/null +++ b/src/targets/c/libcurl/fixtures/headers.c @@ -0,0 +1,14 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/headers"); + +struct curl_slist *headers = NULL; +headers = curl_slist_append(headers, "accept: application/json"); +headers = curl_slist_append(headers, "x-foo: Bar"); +headers = curl_slist_append(headers, "x-bar: Foo"); +headers = curl_slist_append(headers, "quoted-value: \"quoted\" 'string'"); +curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/http-insecure.c b/src/targets/c/libcurl/fixtures/http-insecure.c new file mode 100644 index 000000000..f558b6221 --- /dev/null +++ b/src/targets/c/libcurl/fixtures/http-insecure.c @@ -0,0 +1,7 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "http://httpbin.org/anything"); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/jsonObj-multiline.c b/src/targets/c/libcurl/fixtures/jsonObj-multiline.c new file mode 100644 index 000000000..09ccc0841 --- /dev/null +++ b/src/targets/c/libcurl/fixtures/jsonObj-multiline.c @@ -0,0 +1,13 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/anything"); + +struct curl_slist *headers = NULL; +headers = curl_slist_append(headers, "content-type: application/json"); +curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); + +curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "{\n \"foo\": \"bar\"\n}"); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/jsonObj-null-value.c b/src/targets/c/libcurl/fixtures/jsonObj-null-value.c new file mode 100644 index 000000000..7015b0255 --- /dev/null +++ b/src/targets/c/libcurl/fixtures/jsonObj-null-value.c @@ -0,0 +1,13 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/anything"); + +struct curl_slist *headers = NULL; +headers = curl_slist_append(headers, "content-type: application/json"); +curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); + +curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "{\"foo\":null}"); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/multipart-data.c b/src/targets/c/libcurl/fixtures/multipart-data.c new file mode 100644 index 000000000..3969a1b40 --- /dev/null +++ b/src/targets/c/libcurl/fixtures/multipart-data.c @@ -0,0 +1,13 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/anything"); + +struct curl_slist *headers = NULL; +headers = curl_slist_append(headers, "content-type: multipart/form-data; boundary=---011000010111000001101001"); +curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); + +curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"bar\"\r\n\r\nBonjour le monde\r\n-----011000010111000001101001--"); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/multipart-file.c b/src/targets/c/libcurl/fixtures/multipart-file.c new file mode 100644 index 000000000..4747d1df8 --- /dev/null +++ b/src/targets/c/libcurl/fixtures/multipart-file.c @@ -0,0 +1,13 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/anything"); + +struct curl_slist *headers = NULL; +headers = curl_slist_append(headers, "content-type: multipart/form-data; boundary=---011000010111000001101001"); +curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); + +curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--"); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/multipart-form-data-no-params.c b/src/targets/c/libcurl/fixtures/multipart-form-data-no-params.c new file mode 100644 index 000000000..87215127b --- /dev/null +++ b/src/targets/c/libcurl/fixtures/multipart-form-data-no-params.c @@ -0,0 +1,11 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/anything"); + +struct curl_slist *headers = NULL; +headers = curl_slist_append(headers, "Content-Type: multipart/form-data"); +curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/multipart-form-data.c b/src/targets/c/libcurl/fixtures/multipart-form-data.c new file mode 100644 index 000000000..e4cd6b5f6 --- /dev/null +++ b/src/targets/c/libcurl/fixtures/multipart-form-data.c @@ -0,0 +1,13 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/anything"); + +struct curl_slist *headers = NULL; +headers = curl_slist_append(headers, "Content-Type: multipart/form-data; boundary=---011000010111000001101001"); +curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); + +curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--"); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/nested.c b/src/targets/c/libcurl/fixtures/nested.c new file mode 100644 index 000000000..118a4577a --- /dev/null +++ b/src/targets/c/libcurl/fixtures/nested.c @@ -0,0 +1,7 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value"); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/postdata-malformed.c b/src/targets/c/libcurl/fixtures/postdata-malformed.c new file mode 100644 index 000000000..a9e2d4b69 --- /dev/null +++ b/src/targets/c/libcurl/fixtures/postdata-malformed.c @@ -0,0 +1,11 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/anything"); + +struct curl_slist *headers = NULL; +headers = curl_slist_append(headers, "content-type: application/json"); +curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/query-encoded.c b/src/targets/c/libcurl/fixtures/query-encoded.c new file mode 100644 index 000000000..b62b4f375 --- /dev/null +++ b/src/targets/c/libcurl/fixtures/query-encoded.c @@ -0,0 +1,7 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00"); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/query.c b/src/targets/c/libcurl/fixtures/query.c new file mode 100644 index 000000000..a6ea763a6 --- /dev/null +++ b/src/targets/c/libcurl/fixtures/query.c @@ -0,0 +1,7 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value"); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/short.c b/src/targets/c/libcurl/fixtures/short.c new file mode 100644 index 000000000..1f687313a --- /dev/null +++ b/src/targets/c/libcurl/fixtures/short.c @@ -0,0 +1,7 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/anything"); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/libcurl/fixtures/text-plain.c b/src/targets/c/libcurl/fixtures/text-plain.c new file mode 100644 index 000000000..abb7f8eb3 --- /dev/null +++ b/src/targets/c/libcurl/fixtures/text-plain.c @@ -0,0 +1,13 @@ +CURL *hnd = curl_easy_init(); + +curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); +curl_easy_setopt(hnd, CURLOPT_WRITEDATA, stdout); +curl_easy_setopt(hnd, CURLOPT_URL, "https://httpbin.org/anything"); + +struct curl_slist *headers = NULL; +headers = curl_slist_append(headers, "content-type: text/plain"); +curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); + +curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "Hello World"); + +CURLcode ret = curl_easy_perform(hnd); \ No newline at end of file diff --git a/src/targets/c/target.ts b/src/targets/c/target.ts new file mode 100644 index 000000000..8c2dbb10a --- /dev/null +++ b/src/targets/c/target.ts @@ -0,0 +1,15 @@ +import type { Target } from '../index.js'; + +import { libcurl } from './libcurl/client.js'; + +export const c: Target = { + info: { + key: 'c', + title: 'C', + default: 'libcurl', + cli: 'c', + }, + clientsById: { + libcurl, + }, +}; diff --git a/src/targets/clojure/clj_http.js b/src/targets/clojure/clj_http.js deleted file mode 100644 index a75521817..000000000 --- a/src/targets/clojure/clj_http.js +++ /dev/null @@ -1,151 +0,0 @@ -/** - * @description - * HTTP code snippet generator for Clojure using clj-http. - * - * @author - * @tggreene - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var CodeBuilder = require('../../helpers/code-builder') - -var Keyword = function (name) { - this.name = name -} - -Keyword.prototype.toString = function () { - return ':' + this.name -} - -var File = function (path) { - this.path = path -} - -File.prototype.toString = function () { - return '(clojure.java.io/file "' + this.path + '")' -} - -var jsType = function (x) { - return (typeof x !== 'undefined') - ? x.constructor.name.toLowerCase() - : null -} - -var objEmpty = function (x) { - return (jsType(x) === 'object') - ? Object.keys(x).length === 0 - : false -} - -var filterEmpty = function (m) { - Object.keys(m) - .filter(function (x) { return objEmpty(m[x]) }) - .forEach(function (x) { delete m[x] }) - return m -} - -var padBlock = function (x, s) { - var padding = Array.apply(null, Array(x)) - .map(function (_) { - return ' ' - }) - .join('') - return s.replace(/\n/g, '\n' + padding) -} - -var jsToEdn = function (js) { - switch (jsType(js)) { - default: // 'number' 'boolean' - return js.toString() - case 'string': - return '"' + js.replace(/\"/g, '\\"') + '"' - case 'file': - return js.toString() - case 'keyword': - return js.toString() - case 'null': - return 'nil' - case 'regexp': - return '#"' + js.source + '"' - case 'object': // simple vertical format - var obj = Object.keys(js) - .reduce(function (acc, key) { - var val = padBlock(key.length + 2, jsToEdn(js[key])) - return acc + ':' + key + ' ' + val + '\n ' - }, '') - .trim() - return '{' + padBlock(1, obj) + '}' - case 'array': // simple horizontal format - var arr = js.reduce(function (acc, val) { - return acc + ' ' + jsToEdn(val) - }, '').trim() - return '[' + padBlock(1, arr) + ']' - } -} - -module.exports = function (source, options) { - var code = new CodeBuilder(options) - var methods = ['get', 'post', 'put', 'delete', 'patch', 'head', 'options'] - - if (methods.indexOf(source.method.toLowerCase()) === -1) { - return code.push('Method not supported').join() - } - - var params = {headers: source.allHeaders, - 'query-params': source.queryObj} - - switch (source.postData.mimeType) { - case 'application/json': - params['content-type'] = new Keyword('json') - params['form-params'] = source.postData.jsonObj - delete params.headers['content-type'] - break - case 'application/x-www-form-urlencoded': - params['form-params'] = source.postData.paramsObj - delete params.headers['content-type'] - break - case 'text/plain': - params.body = source.postData.text - delete params.headers['content-type'] - break - case 'multipart/form-data': - params.multipart = source.postData.params.map(function (x) { - if (x.fileName && !x.value) { - return {name: x.name, - content: new File(x.fileName)} - } else { - return {name: x.name, - content: x.value} - } - }) - delete params.headers['content-type'] - break - } - - switch (params.headers.accept) { - case 'application/json': - params.accept = new Keyword('json') - delete params.headers.accept - break - } - - code.push('(require \'[clj-http.client :as client])\n') - - if (objEmpty(filterEmpty(params))) { - code.push('(client/%s "%s")', source.method.toLowerCase(), source.url) - } else { - code.push('(client/%s "%s" %s)', source.method.toLowerCase(), source.url, padBlock(11 + source.method.length + source.url.length, jsToEdn(filterEmpty(params)))) - } - - return code.join() -} - -module.exports.info = { - key: 'clj_http', - title: 'clj-http', - link: 'https://github.com/dakrone/clj-http', - description: 'An idiomatic clojure http client wrapping the apache client.' -} diff --git a/src/targets/clojure/clj_http/client.test.ts b/src/targets/clojure/clj_http/client.test.ts new file mode 100644 index 000000000..666ae9ae8 --- /dev/null +++ b/src/targets/clojure/clj_http/client.test.ts @@ -0,0 +1,34 @@ +import type { Request } from '../../../index.js'; + +import { runCustomFixtures } from '../../../fixtures/runCustomFixtures.js'; + +runCustomFixtures({ + targetId: 'clojure', + clientId: 'clj_http', + tests: [ + { + it: 'should not crash if there is no `postData.text`', + input: { + headers: [ + { + name: 'accept', + value: 'application/json', + }, + { + name: 'content-type', + value: 'application/json', + }, + ], + postData: { + mimeType: 'application/json', + }, + bodySize: 0, + method: 'POST', + url: 'https://httpbin.org/anything', + httpVersion: 'HTTP/1.1', + } as Request, + options: {}, + expected: 'should-not-crash.clj', + }, + ], +}); diff --git a/src/targets/clojure/clj_http/client.ts b/src/targets/clojure/clj_http/client.ts new file mode 100644 index 000000000..e9aa02933 --- /dev/null +++ b/src/targets/clojure/clj_http/client.ts @@ -0,0 +1,213 @@ +/** + * @description + * HTTP code snippet generator for Clojure using clj-http. + * + * @author + * @tggreene + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { getHeader, getHeaderName } from '../../../helpers/headers.js'; + +class Keyword { + name = ''; + + constructor(name: string) { + this.name = name; + } + + toString = () => `:${this.name}`; +} + +class File { + path = ''; + + constructor(path: string) { + this.path = path; + } + + toString = () => `(clojure.java.io/file "${this.path}")`; +} + +const jsType = (input?: any) => { + if (input === undefined) { + return null; + } + + if (input === null) { + return 'null'; + } + + return input.constructor.name.toLowerCase(); +}; + +const objEmpty = (input?: any) => { + if (input === undefined) { + return true; + } else if (jsType(input) === 'object') { + return Object.keys(input).length === 0; + } + return false; +}; + +const filterEmpty = (input: Record) => { + Object.keys(input) + .filter(x => objEmpty(input[x])) + .forEach(x => { + delete input[x]; + }); + return input; +}; + +const padBlock = (padSize: number, input: string) => { + const padding = ' '.repeat(padSize); + return input.replace(/\n/g, `\n${padding}`); +}; + +const jsToEdn = (js: any) => { + switch (jsType(js)) { + case 'string': + return `"${js.replace(/"/g, '\\"')}"`; + + case 'file': + return js.toString(); + + case 'keyword': + return js.toString(); + + case 'null': + return 'nil'; + + case 'regexp': + return `#"${js.source}"`; + + case 'object': { + // simple vertical format + const obj = Object.keys(js) + .reduce((accumulator, key) => { + const val = padBlock(key.length + 2, jsToEdn(js[key])); + return `${accumulator}:${key} ${val}\n `; + }, '') + .trim(); + return `{${padBlock(1, obj)}}`; + } + + case 'array': { + // simple horizontal format + const arr = js.reduce((accumulator: string, value: string) => `${accumulator} ${jsToEdn(value)}`, '').trim(); + return `[${padBlock(1, arr)}]`; + } + + default: // 'number' 'boolean' + return js.toString(); + } +}; + +export const clj_http: Client = { + info: { + key: 'clj_http', + title: 'clj-http', + link: 'https://github.com/dakrone/clj-http', + description: 'An idiomatic clojure http client wrapping the apache client.', + extname: '.clj', + }, + convert: ({ queryObj, method, postData, url, allHeaders }, options) => { + const { push, join } = new CodeBuilder({ indent: options?.indent }); + const methods = ['get', 'post', 'put', 'delete', 'patch', 'head', 'options']; + method = method.toLowerCase(); + + if (!methods.includes(method)) { + push('Method not supported'); + return join(); + } + + const params: Record = { + headers: allHeaders, + 'query-params': queryObj, + }; + + switch (postData.mimeType) { + case 'application/json': + { + params['content-type'] = new Keyword('json'); + params['form-params'] = postData.jsonObj; + const header = getHeaderName(params.headers, 'content-type'); + if (header) { + delete params.headers[header]; + } + } + break; + + case 'application/x-www-form-urlencoded': + { + params['form-params'] = postData.paramsObj; + const header = getHeaderName(params.headers, 'content-type'); + if (header) { + delete params.headers[header]; + } + } + break; + + case 'text/plain': + { + params.body = postData.text; + const header = getHeaderName(params.headers, 'content-type'); + if (header) { + delete params.headers[header]; + } + } + break; + + case 'multipart/form-data': { + if (postData.params) { + params.multipart = postData.params.map(param => { + if (param.fileName && !param.value) { + return { + name: param.name, + content: new File(param.fileName), + }; + } + return { + name: param.name, + content: param.value, + }; + }); + + const header = getHeaderName(params.headers, 'content-type'); + if (header) { + delete params.headers[header]; + } + } + break; + } + } + + switch (getHeader(params.headers, 'accept')) { + case 'application/json': + { + params.accept = new Keyword('json'); + + const header = getHeaderName(params.headers, 'accept'); + if (header) { + delete params.headers[header]; + } + } + break; + } + + push("(require '[clj-http.client :as client])\n"); + + if (objEmpty(filterEmpty(params))) { + push(`(client/${method} "${url}")`); + } else { + const padding = 11 + method.length + url.length; + const formattedParams = padBlock(padding, jsToEdn(filterEmpty(params))); + push(`(client/${method} "${url}" ${formattedParams})`); + } + + return join(); + }, +}; diff --git a/src/targets/clojure/clj_http/fixtures/application-form-encoded.clj b/src/targets/clojure/clj_http/fixtures/application-form-encoded.clj new file mode 100644 index 000000000..b933b7ac1 --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/application-form-encoded.clj @@ -0,0 +1,4 @@ +(require '[clj-http.client :as client]) + +(client/post "https://httpbin.org/anything" {:form-params {:foo "bar" + :hello "world"}}) \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/application-json.clj b/src/targets/clojure/clj_http/fixtures/application-json.clj new file mode 100644 index 000000000..03c655498 --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/application-json.clj @@ -0,0 +1,9 @@ +(require '[clj-http.client :as client]) + +(client/post "https://httpbin.org/anything" {:content-type :json + :form-params {:number 1 + :string "f\"oo" + :arr [1 2 3] + :nested {:a "b"} + :arr_mix [1 "a" {:arr_mix_nested []}] + :boolean false}}) \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/cookies.clj b/src/targets/clojure/clj_http/fixtures/cookies.clj new file mode 100644 index 000000000..bffe247ae --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/cookies.clj @@ -0,0 +1,3 @@ +(require '[clj-http.client :as client]) + +(client/get "https://httpbin.org/cookies" {:headers {:cookie "foo=bar; bar=baz"}}) \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/custom-method.clj b/src/targets/clojure/clj_http/fixtures/custom-method.clj new file mode 100644 index 000000000..8eb41a680 --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/custom-method.clj @@ -0,0 +1 @@ +Method not supported \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/full.clj b/src/targets/clojure/clj_http/fixtures/full.clj new file mode 100644 index 000000000..9a8c21735 --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/full.clj @@ -0,0 +1,8 @@ +(require '[clj-http.client :as client]) + +(client/post "https://httpbin.org/anything" {:headers {:cookie "foo=bar; bar=baz"} + :query-params {:foo ["bar" "baz"] + :baz "abc" + :key "value"} + :form-params {:foo "bar"} + :accept :json}) \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/headers.clj b/src/targets/clojure/clj_http/fixtures/headers.clj new file mode 100644 index 000000000..8e02e29ea --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/headers.clj @@ -0,0 +1,6 @@ +(require '[clj-http.client :as client]) + +(client/get "https://httpbin.org/headers" {:headers {:x-foo "Bar" + :x-bar "Foo" + :quoted-value "\"quoted\" 'string'"} + :accept :json}) \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/http-insecure.clj b/src/targets/clojure/clj_http/fixtures/http-insecure.clj new file mode 100644 index 000000000..913c6b9dd --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/http-insecure.clj @@ -0,0 +1,3 @@ +(require '[clj-http.client :as client]) + +(client/get "http://httpbin.org/anything") \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/jsonObj-multiline.clj b/src/targets/clojure/clj_http/fixtures/jsonObj-multiline.clj new file mode 100644 index 000000000..5cbba48b4 --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/jsonObj-multiline.clj @@ -0,0 +1,4 @@ +(require '[clj-http.client :as client]) + +(client/post "https://httpbin.org/anything" {:content-type :json + :form-params {:foo "bar"}}) \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/jsonObj-null-value.clj b/src/targets/clojure/clj_http/fixtures/jsonObj-null-value.clj new file mode 100644 index 000000000..e1e11d6ba --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/jsonObj-null-value.clj @@ -0,0 +1,4 @@ +(require '[clj-http.client :as client]) + +(client/post "https://httpbin.org/anything" {:content-type :json + :form-params {:foo nil}}) \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/multipart-data.clj b/src/targets/clojure/clj_http/fixtures/multipart-data.clj new file mode 100644 index 000000000..23cecbd1a --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/multipart-data.clj @@ -0,0 +1,5 @@ +(require '[clj-http.client :as client]) + +(client/post "https://httpbin.org/anything" {:multipart [{:name "foo" + :content "Hello World"} {:name "bar" + :content "Bonjour le monde"}]}) \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/multipart-file.clj b/src/targets/clojure/clj_http/fixtures/multipart-file.clj new file mode 100644 index 000000000..e3f4a6078 --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/multipart-file.clj @@ -0,0 +1,4 @@ +(require '[clj-http.client :as client]) + +(client/post "https://httpbin.org/anything" {:multipart [{:name "foo" + :content (clojure.java.io/file "src/fixtures/files/hello.txt")}]}) \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/multipart-form-data-no-params.clj b/src/targets/clojure/clj_http/fixtures/multipart-form-data-no-params.clj new file mode 100644 index 000000000..ee1eda5d0 --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/multipart-form-data-no-params.clj @@ -0,0 +1,3 @@ +(require '[clj-http.client :as client]) + +(client/post "https://httpbin.org/anything" {:headers {:Content-Type "multipart/form-data"}}) \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/multipart-form-data.clj b/src/targets/clojure/clj_http/fixtures/multipart-form-data.clj new file mode 100644 index 000000000..74ed1e088 --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/multipart-form-data.clj @@ -0,0 +1,4 @@ +(require '[clj-http.client :as client]) + +(client/post "https://httpbin.org/anything" {:multipart [{:name "foo" + :content "bar"}]}) \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/nested.clj b/src/targets/clojure/clj_http/fixtures/nested.clj new file mode 100644 index 000000000..022c0795f --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/nested.clj @@ -0,0 +1,5 @@ +(require '[clj-http.client :as client]) + +(client/get "https://httpbin.org/anything" {:query-params {:foo[bar] "baz,zap" + :fiz "buz" + :key "value"}}) \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/postdata-malformed.clj b/src/targets/clojure/clj_http/fixtures/postdata-malformed.clj new file mode 100644 index 000000000..04cd98f6a --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/postdata-malformed.clj @@ -0,0 +1,3 @@ +(require '[clj-http.client :as client]) + +(client/post "https://httpbin.org/anything" {:headers {:content-type "application/json"}}) \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/query-encoded.clj b/src/targets/clojure/clj_http/fixtures/query-encoded.clj new file mode 100644 index 000000000..e25e2ed9b --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/query-encoded.clj @@ -0,0 +1,4 @@ +(require '[clj-http.client :as client]) + +(client/get "https://httpbin.org/anything" {:query-params {:startTime "2019-06-13T19%3A08%3A25.455Z" + :endTime "2015-09-15T14%3A00%3A12-04%3A00"}}) \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/query.clj b/src/targets/clojure/clj_http/fixtures/query.clj new file mode 100644 index 000000000..caf287ee7 --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/query.clj @@ -0,0 +1,5 @@ +(require '[clj-http.client :as client]) + +(client/get "https://httpbin.org/anything" {:query-params {:foo ["bar" "baz"] + :baz "abc" + :key "value"}}) \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/short.clj b/src/targets/clojure/clj_http/fixtures/short.clj new file mode 100644 index 000000000..48c3eefc7 --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/short.clj @@ -0,0 +1,3 @@ +(require '[clj-http.client :as client]) + +(client/get "https://httpbin.org/anything") \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/should-not-crash.clj b/src/targets/clojure/clj_http/fixtures/should-not-crash.clj new file mode 100644 index 000000000..382de39e1 --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/should-not-crash.clj @@ -0,0 +1,4 @@ +(require '[clj-http.client :as client]) + +(client/post "https://httpbin.org/anything" {:content-type :json + :accept :json}) \ No newline at end of file diff --git a/src/targets/clojure/clj_http/fixtures/text-plain.clj b/src/targets/clojure/clj_http/fixtures/text-plain.clj new file mode 100644 index 000000000..4f76fb82e --- /dev/null +++ b/src/targets/clojure/clj_http/fixtures/text-plain.clj @@ -0,0 +1,3 @@ +(require '[clj-http.client :as client]) + +(client/post "https://httpbin.org/anything" {:body "Hello World"}) \ No newline at end of file diff --git a/src/targets/clojure/index.js b/src/targets/clojure/index.js deleted file mode 100644 index bf84319a1..000000000 --- a/src/targets/clojure/index.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict' - -module.exports = { - info: { - key: 'clojure', - title: 'Clojure', - extname: '.clj', - default: 'clj_http' - }, - - clj_http: require('./clj_http') -} diff --git a/src/targets/clojure/target.ts b/src/targets/clojure/target.ts new file mode 100644 index 000000000..e09b92235 --- /dev/null +++ b/src/targets/clojure/target.ts @@ -0,0 +1,14 @@ +import type { Target } from '../index.js'; + +import { clj_http } from './clj_http/client.js'; + +export const clojure: Target = { + info: { + key: 'clojure', + title: 'Clojure', + default: 'clj_http', + }, + clientsById: { + clj_http, + }, +}; diff --git a/src/targets/csharp/httpclient/client.ts b/src/targets/csharp/httpclient/client.ts new file mode 100644 index 000000000..a4cc52c87 --- /dev/null +++ b/src/targets/csharp/httpclient/client.ts @@ -0,0 +1,173 @@ +import type { Request } from '../../../index.js'; +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { escapeForDoubleQuotes } from '../../../helpers/escape.js'; +import { getHeader } from '../../../helpers/headers.js'; + +const getDecompressionMethods = (allHeaders: Request['allHeaders']) => { + let acceptEncodings = getHeader(allHeaders, 'accept-encoding'); + if (!acceptEncodings) { + return []; // no decompression + } + + const supportedMethods: Record = { + gzip: 'DecompressionMethods.GZip', + deflate: 'DecompressionMethods.Deflate', + }; + + const methods: string[] = []; + if (typeof acceptEncodings === 'string') { + acceptEncodings = [acceptEncodings]; + } + acceptEncodings.forEach(acceptEncoding => { + acceptEncoding.split(',').forEach(encoding => { + const match = /\s*([^;\s]+)/.exec(encoding); + if (match) { + const method = supportedMethods[match[1]]; + if (method) { + methods.push(method); + } + } + }); + }); + + return methods; +}; + +export const httpclient: Client = { + info: { + key: 'httpclient', + title: 'HttpClient', + link: 'https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient', + description: '.NET Standard HTTP Client', + extname: '.cs', + }, + convert: ({ allHeaders, postData, method, fullUrl }, options) => { + const opts = { + indent: ' ', + ...options, + }; + + const { push, join } = new CodeBuilder({ indent: opts.indent }); + + push('using System.Net.Http.Headers;'); + let clienthandler = ''; + const cookies = Boolean(allHeaders.cookie); + const decompressionMethods = getDecompressionMethods(allHeaders); + if (cookies || decompressionMethods.length) { + clienthandler = 'clientHandler'; + push('var clientHandler = new HttpClientHandler'); + push('{'); + if (cookies) { + // enable setting the cookie header + push('UseCookies = false,', 1); + } + if (decompressionMethods.length) { + // enable decompression for supported methods + push(`AutomaticDecompression = ${decompressionMethods.join(' | ')},`, 1); + } + push('};'); + } + + push(`var client = new HttpClient(${clienthandler});`); + + push('var request = new HttpRequestMessage'); + push('{'); + + const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS', 'TRACE']; + method = method.toUpperCase(); + if (method && methods.includes(method)) { + // buildin method + method = `HttpMethod.${method[0]}${method.substring(1).toLowerCase()}`; + } else { + // custom method + method = `new HttpMethod("${method}")`; + } + push(`Method = ${method},`, 1); + + push(`RequestUri = new Uri("${fullUrl}"),`, 1); + + const headers: (keyof typeof allHeaders)[] = Object.keys(allHeaders).filter(header => { + switch (header.toLowerCase()) { + case 'content-type': + case 'content-length': + case 'accept-encoding': + // skip these headers + return false; + + default: + return true; + } + }); + + if (headers.length) { + push('Headers =', 1); + push('{', 1); + headers.forEach(key => { + push(`{ "${key}", "${escapeForDoubleQuotes(allHeaders[key])}" },`, 2); + }); + push('},', 1); + } + + if (postData.text) { + const contentType = postData.mimeType; + switch (contentType) { + case 'application/x-www-form-urlencoded': + push('Content = new FormUrlEncodedContent(new Dictionary', 1); + push('{', 1); + postData.params?.forEach(param => { + push(`{ "${param.name}", "${param.value}" },`, 2); + }); + push('}),', 1); + break; + + case 'multipart/form-data': + push('Content = new MultipartFormDataContent', 1); + push('{', 1); + postData.params?.forEach(param => { + push(`new StringContent(${JSON.stringify(param.value || '')})`, 2); + push('{', 2); + push('Headers =', 3); + push('{', 3); + if (param.contentType) { + push(`ContentType = new MediaTypeHeaderValue("${param.contentType}"),`, 4); + } + push('ContentDisposition = new ContentDispositionHeaderValue("form-data")', 4); + push('{', 4); + push(`Name = "${param.name}",`, 5); + if (param.fileName) { + push(`FileName = "${param.fileName}",`, 5); + } + push('}', 4); + push('}', 3); + push('},', 2); + }); + + push('},', 1); + break; + + default: + push(`Content = new StringContent(${JSON.stringify(postData.text || '')})`, 1); + push('{', 1); + push('Headers =', 2); + push('{', 2); + push(`ContentType = new MediaTypeHeaderValue("${contentType}")`, 3); + push('}', 2); + push('}', 1); + break; + } + } + push('};'); + + // send and read response + push('using (var response = await client.SendAsync(request))'); + push('{'); + push('response.EnsureSuccessStatusCode();', 1); + push('var body = await response.Content.ReadAsStringAsync();', 1); + push('Console.WriteLine(body);', 1); + push('}'); + + return join(); + }, +}; diff --git a/src/targets/csharp/httpclient/fixtures/application-form-encoded.cs b/src/targets/csharp/httpclient/fixtures/application-form-encoded.cs new file mode 100644 index 000000000..f22835c9c --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/application-form-encoded.cs @@ -0,0 +1,18 @@ +using System.Net.Http.Headers; +var client = new HttpClient(); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Post, + RequestUri = new Uri("https://httpbin.org/anything"), + Content = new FormUrlEncodedContent(new Dictionary + { + { "foo", "bar" }, + { "hello", "world" }, + }), +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/application-json.cs b/src/targets/csharp/httpclient/fixtures/application-json.cs new file mode 100644 index 000000000..1c86003cd --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/application-json.cs @@ -0,0 +1,20 @@ +using System.Net.Http.Headers; +var client = new HttpClient(); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Post, + RequestUri = new Uri("https://httpbin.org/anything"), + Content = new StringContent("{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":[]}],\"boolean\":false}") + { + Headers = + { + ContentType = new MediaTypeHeaderValue("application/json") + } + } +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/cookies.cs b/src/targets/csharp/httpclient/fixtures/cookies.cs new file mode 100644 index 000000000..7529f052d --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/cookies.cs @@ -0,0 +1,21 @@ +using System.Net.Http.Headers; +var clientHandler = new HttpClientHandler +{ + UseCookies = false, +}; +var client = new HttpClient(clientHandler); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Get, + RequestUri = new Uri("https://httpbin.org/cookies"), + Headers = + { + { "cookie", "foo=bar; bar=baz" }, + }, +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/custom-method.cs b/src/targets/csharp/httpclient/fixtures/custom-method.cs new file mode 100644 index 000000000..ad16018c7 --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/custom-method.cs @@ -0,0 +1,13 @@ +using System.Net.Http.Headers; +var client = new HttpClient(); +var request = new HttpRequestMessage +{ + Method = new HttpMethod("PROPFIND"), + RequestUri = new Uri("https://httpbin.org/anything"), +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/full.cs b/src/targets/csharp/httpclient/fixtures/full.cs new file mode 100644 index 000000000..7ea54cfb3 --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/full.cs @@ -0,0 +1,26 @@ +using System.Net.Http.Headers; +var clientHandler = new HttpClientHandler +{ + UseCookies = false, +}; +var client = new HttpClient(clientHandler); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Post, + RequestUri = new Uri("https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value"), + Headers = + { + { "cookie", "foo=bar; bar=baz" }, + { "accept", "application/json" }, + }, + Content = new FormUrlEncodedContent(new Dictionary + { + { "foo", "bar" }, + }), +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/headers.cs b/src/targets/csharp/httpclient/fixtures/headers.cs new file mode 100644 index 000000000..84637daf7 --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/headers.cs @@ -0,0 +1,20 @@ +using System.Net.Http.Headers; +var client = new HttpClient(); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Get, + RequestUri = new Uri("https://httpbin.org/headers"), + Headers = + { + { "accept", "application/json" }, + { "x-foo", "Bar" }, + { "x-bar", "Foo" }, + { "quoted-value", "\"quoted\" 'string'" }, + }, +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/http-insecure.cs b/src/targets/csharp/httpclient/fixtures/http-insecure.cs new file mode 100644 index 000000000..c3db9adfc --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/http-insecure.cs @@ -0,0 +1,13 @@ +using System.Net.Http.Headers; +var client = new HttpClient(); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Get, + RequestUri = new Uri("http://httpbin.org/anything"), +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/jsonObj-multiline.cs b/src/targets/csharp/httpclient/fixtures/jsonObj-multiline.cs new file mode 100644 index 000000000..e0328da61 --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/jsonObj-multiline.cs @@ -0,0 +1,20 @@ +using System.Net.Http.Headers; +var client = new HttpClient(); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Post, + RequestUri = new Uri("https://httpbin.org/anything"), + Content = new StringContent("{\n \"foo\": \"bar\"\n}") + { + Headers = + { + ContentType = new MediaTypeHeaderValue("application/json") + } + } +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/jsonObj-null-value.cs b/src/targets/csharp/httpclient/fixtures/jsonObj-null-value.cs new file mode 100644 index 000000000..3f7f8f4e4 --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/jsonObj-null-value.cs @@ -0,0 +1,20 @@ +using System.Net.Http.Headers; +var client = new HttpClient(); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Post, + RequestUri = new Uri("https://httpbin.org/anything"), + Content = new StringContent("{\"foo\":null}") + { + Headers = + { + ContentType = new MediaTypeHeaderValue("application/json") + } + } +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/multipart-data.cs b/src/targets/csharp/httpclient/fixtures/multipart-data.cs new file mode 100644 index 000000000..5ac446a4b --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/multipart-data.cs @@ -0,0 +1,38 @@ +using System.Net.Http.Headers; +var client = new HttpClient(); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Post, + RequestUri = new Uri("https://httpbin.org/anything"), + Content = new MultipartFormDataContent + { + new StringContent("Hello World") + { + Headers = + { + ContentType = new MediaTypeHeaderValue("text/plain"), + ContentDisposition = new ContentDispositionHeaderValue("form-data") + { + Name = "foo", + FileName = "src/fixtures/files/hello.txt", + } + } + }, + new StringContent("Bonjour le monde") + { + Headers = + { + ContentDisposition = new ContentDispositionHeaderValue("form-data") + { + Name = "bar", + } + } + }, + }, +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/multipart-file.cs b/src/targets/csharp/httpclient/fixtures/multipart-file.cs new file mode 100644 index 000000000..f62e52b65 --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/multipart-file.cs @@ -0,0 +1,28 @@ +using System.Net.Http.Headers; +var client = new HttpClient(); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Post, + RequestUri = new Uri("https://httpbin.org/anything"), + Content = new MultipartFormDataContent + { + new StringContent("") + { + Headers = + { + ContentType = new MediaTypeHeaderValue("text/plain"), + ContentDisposition = new ContentDispositionHeaderValue("form-data") + { + Name = "foo", + FileName = "src/fixtures/files/hello.txt", + } + } + }, + }, +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/multipart-form-data-no-params.cs b/src/targets/csharp/httpclient/fixtures/multipart-form-data-no-params.cs new file mode 100644 index 000000000..ccc9dc155 --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/multipart-form-data-no-params.cs @@ -0,0 +1,13 @@ +using System.Net.Http.Headers; +var client = new HttpClient(); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Post, + RequestUri = new Uri("https://httpbin.org/anything"), +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/multipart-form-data.cs b/src/targets/csharp/httpclient/fixtures/multipart-form-data.cs new file mode 100644 index 000000000..1451520ed --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/multipart-form-data.cs @@ -0,0 +1,26 @@ +using System.Net.Http.Headers; +var client = new HttpClient(); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Post, + RequestUri = new Uri("https://httpbin.org/anything"), + Content = new MultipartFormDataContent + { + new StringContent("bar") + { + Headers = + { + ContentDisposition = new ContentDispositionHeaderValue("form-data") + { + Name = "foo", + } + } + }, + }, +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/nested.cs b/src/targets/csharp/httpclient/fixtures/nested.cs new file mode 100644 index 000000000..3882bb709 --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/nested.cs @@ -0,0 +1,13 @@ +using System.Net.Http.Headers; +var client = new HttpClient(); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Get, + RequestUri = new Uri("https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value"), +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/postdata-malformed.cs b/src/targets/csharp/httpclient/fixtures/postdata-malformed.cs new file mode 100644 index 000000000..ccc9dc155 --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/postdata-malformed.cs @@ -0,0 +1,13 @@ +using System.Net.Http.Headers; +var client = new HttpClient(); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Post, + RequestUri = new Uri("https://httpbin.org/anything"), +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/query-encoded.cs b/src/targets/csharp/httpclient/fixtures/query-encoded.cs new file mode 100644 index 000000000..f82716fc4 --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/query-encoded.cs @@ -0,0 +1,13 @@ +using System.Net.Http.Headers; +var client = new HttpClient(); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Get, + RequestUri = new Uri("https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00"), +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/query.cs b/src/targets/csharp/httpclient/fixtures/query.cs new file mode 100644 index 000000000..34337e509 --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/query.cs @@ -0,0 +1,13 @@ +using System.Net.Http.Headers; +var client = new HttpClient(); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Get, + RequestUri = new Uri("https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value"), +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/short.cs b/src/targets/csharp/httpclient/fixtures/short.cs new file mode 100644 index 000000000..b8eaf7200 --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/short.cs @@ -0,0 +1,13 @@ +using System.Net.Http.Headers; +var client = new HttpClient(); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Get, + RequestUri = new Uri("https://httpbin.org/anything"), +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/httpclient/fixtures/text-plain.cs b/src/targets/csharp/httpclient/fixtures/text-plain.cs new file mode 100644 index 000000000..d61f8d5b9 --- /dev/null +++ b/src/targets/csharp/httpclient/fixtures/text-plain.cs @@ -0,0 +1,20 @@ +using System.Net.Http.Headers; +var client = new HttpClient(); +var request = new HttpRequestMessage +{ + Method = HttpMethod.Post, + RequestUri = new Uri("https://httpbin.org/anything"), + Content = new StringContent("Hello World") + { + Headers = + { + ContentType = new MediaTypeHeaderValue("text/plain") + } + } +}; +using (var response = await client.SendAsync(request)) +{ + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Console.WriteLine(body); +} \ No newline at end of file diff --git a/src/targets/csharp/index.js b/src/targets/csharp/index.js deleted file mode 100644 index 226dd69f4..000000000 --- a/src/targets/csharp/index.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict' - -module.exports = { - info: { - key: 'csharp', - title: 'C#', - extname: '.cs', - default: 'restsharp' - }, - - restsharp: require('./restsharp') -} diff --git a/src/targets/csharp/restsharp.js b/src/targets/csharp/restsharp.js deleted file mode 100644 index 0b8fc2735..000000000 --- a/src/targets/csharp/restsharp.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict' - -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var code = new CodeBuilder() - var methods = [ 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS' ] - - if (methods.indexOf(source.method.toUpperCase()) === -1) { - return 'Method not supported' - } else { - code.push('var client = new RestClient("%s");', source.fullUrl) - code.push('var request = new RestRequest(Method.%s);', source.method.toUpperCase()) - } - - // Add headers, including the cookies - var headers = Object.keys(source.headersObj) - - // construct headers - if (headers.length) { - headers.forEach(function (key) { - code.push('request.AddHeader("%s", "%s");', key, source.headersObj[key]) - }) - } - - // construct cookies - if (source.cookies.length) { - source.cookies.forEach(function (cookie) { - code.push('request.AddCookie("%s", "%s");', cookie.name, cookie.value) - }) - } - - if (source.postData.text) { - code.push('request.AddParameter("%s", %s, ParameterType.RequestBody);', source.allHeaders['content-type'], JSON.stringify(source.postData.text)) - } - - code.push('IRestResponse response = client.Execute(request);') - return code.join() -} - -module.exports.info = { - key: 'restsharp', - title: 'RestSharp', - link: 'http://restsharp.org/', - description: 'Simple REST and HTTP API Client for .NET' -} diff --git a/src/targets/csharp/restsharp/client.ts b/src/targets/csharp/restsharp/client.ts new file mode 100644 index 000000000..f038ae9e7 --- /dev/null +++ b/src/targets/csharp/restsharp/client.ts @@ -0,0 +1,100 @@ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { escapeForDoubleQuotes } from '../../../helpers/escape.js'; + +function title(s: string): string { + return s[0].toUpperCase() + s.slice(1).toLowerCase(); +} + +export const restsharp: Client = { + info: { + key: 'restsharp', + title: 'RestSharp', + link: 'http://restsharp.org/', + description: 'Simple REST and HTTP API Client for .NET', + extname: '.cs', + installation: () => 'dotnet add package RestSharp', + }, + convert: ({ method, fullUrl, headersObj, cookies, postData, uriObj }) => { + const { push, join } = new CodeBuilder(); + const isSupportedMethod = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'].includes( + method.toUpperCase(), + ); + + if (!isSupportedMethod) { + return 'Method not supported'; + } + + push('using RestSharp;\n\n'); + push(`var options = new RestClientOptions("${fullUrl}");`); + push('var client = new RestClient(options);'); + + // The first argument is the sub-path to the base URL, given as the + // constructor to RestClient; for our purposes we're just giving the entire + // URL as the base path so it can be an empty string + push('var request = new RestRequest("");'); + + // If we have multipart form data, set this value. Setting the content-type header manually and then trying to add a mutlipart file parameter + const isMultipart = postData.mimeType && postData.mimeType === 'multipart/form-data'; + if (isMultipart) { + push('request.AlwaysMultipartFormData = true;'); + } + + // Add headers, including the cookies + Object.keys(headersObj).forEach(key => { + // if we have post data, restsharp really wants to set the contentType + // itself; do not add a content-type header or you end up with failures + // which manifest as unhandled exceptions. + // + // The only case where we _do_ want to add it is if there's no postData + // text, in which case there will be no `AddJsonBody` call, and restsharp + // won't know to set the content type + if (postData.mimeType && key.toLowerCase() === 'content-type' && postData.text) { + if (isMultipart && postData.boundary) { + push(`request.FormBoundary = "${postData.boundary}";`); + } + return; + } + push(`request.AddHeader("${key}", "${escapeForDoubleQuotes(headersObj[key])}");`); + }); + + cookies.forEach(({ name, value }) => { + push(`request.AddCookie("${name}", "${escapeForDoubleQuotes(value)}", "${uriObj.pathname}", "${uriObj.host}");`); + }); + + switch (postData.mimeType) { + case 'multipart/form-data': + if (!postData.params) break; + postData.params.forEach(param => { + if (param.fileName) { + push(`request.AddFile("${param.name}", "${param.fileName}");`); + } else { + push(`request.AddParameter("${param.name}", "${param.value}");`); + } + }); + break; + case 'application/x-www-form-urlencoded': + if (!postData.params) break; + postData.params.forEach(param => { + push(`request.AddParameter("${param.name}", "${param.value}");`); + }); + break; + case 'application/json': { + if (!postData.text) break; + const text = JSON.stringify(postData.text); + push(`request.AddJsonBody(${text}, false);`); + break; + } + default: + if (!postData.text) break; + push(`request.AddStringBody("${postData.text}", "${postData.mimeType}");`); + } + + push(`var response = await client.${title(method)}Async(request);\n`); + + push('Console.WriteLine("{0}", response.Content);\n'); + + return join(); + }, +}; diff --git a/src/targets/csharp/restsharp/fixtures/application-form-encoded.cs b/src/targets/csharp/restsharp/fixtures/application-form-encoded.cs new file mode 100644 index 000000000..9e02cbc5a --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/application-form-encoded.cs @@ -0,0 +1,11 @@ +using RestSharp; + + +var options = new RestClientOptions("https://httpbin.org/anything"); +var client = new RestClient(options); +var request = new RestRequest(""); +request.AddParameter("foo", "bar"); +request.AddParameter("hello", "world"); +var response = await client.PostAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/restsharp/fixtures/application-json.cs b/src/targets/csharp/restsharp/fixtures/application-json.cs new file mode 100644 index 000000000..e17c726e3 --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/application-json.cs @@ -0,0 +1,10 @@ +using RestSharp; + + +var options = new RestClientOptions("https://httpbin.org/anything"); +var client = new RestClient(options); +var request = new RestRequest(""); +request.AddJsonBody("{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":[]}],\"boolean\":false}", false); +var response = await client.PostAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/restsharp/fixtures/cookies.cs b/src/targets/csharp/restsharp/fixtures/cookies.cs new file mode 100644 index 000000000..0a35af786 --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/cookies.cs @@ -0,0 +1,11 @@ +using RestSharp; + + +var options = new RestClientOptions("https://httpbin.org/cookies"); +var client = new RestClient(options); +var request = new RestRequest(""); +request.AddCookie("foo", "bar", "/cookies", "httpbin.org"); +request.AddCookie("bar", "baz", "/cookies", "httpbin.org"); +var response = await client.GetAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/restsharp/fixtures/custom-method.cs b/src/targets/csharp/restsharp/fixtures/custom-method.cs new file mode 100644 index 000000000..8eb41a680 --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/custom-method.cs @@ -0,0 +1 @@ +Method not supported \ No newline at end of file diff --git a/src/targets/csharp/restsharp/fixtures/full.cs b/src/targets/csharp/restsharp/fixtures/full.cs new file mode 100644 index 000000000..c31a1260c --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/full.cs @@ -0,0 +1,13 @@ +using RestSharp; + + +var options = new RestClientOptions("https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value"); +var client = new RestClient(options); +var request = new RestRequest(""); +request.AddHeader("accept", "application/json"); +request.AddCookie("foo", "bar", "/anything", "httpbin.org"); +request.AddCookie("bar", "baz", "/anything", "httpbin.org"); +request.AddParameter("foo", "bar"); +var response = await client.PostAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/restsharp/fixtures/headers.cs b/src/targets/csharp/restsharp/fixtures/headers.cs new file mode 100644 index 000000000..94c8e7d0e --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/headers.cs @@ -0,0 +1,13 @@ +using RestSharp; + + +var options = new RestClientOptions("https://httpbin.org/headers"); +var client = new RestClient(options); +var request = new RestRequest(""); +request.AddHeader("accept", "application/json"); +request.AddHeader("x-foo", "Bar"); +request.AddHeader("x-bar", "Foo"); +request.AddHeader("quoted-value", "\"quoted\" 'string'"); +var response = await client.GetAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/restsharp/fixtures/http-insecure.cs b/src/targets/csharp/restsharp/fixtures/http-insecure.cs new file mode 100644 index 000000000..622eba335 --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/http-insecure.cs @@ -0,0 +1,9 @@ +using RestSharp; + + +var options = new RestClientOptions("http://httpbin.org/anything"); +var client = new RestClient(options); +var request = new RestRequest(""); +var response = await client.GetAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/restsharp/fixtures/jsonObj-multiline.cs b/src/targets/csharp/restsharp/fixtures/jsonObj-multiline.cs new file mode 100644 index 000000000..d6e78abb5 --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/jsonObj-multiline.cs @@ -0,0 +1,10 @@ +using RestSharp; + + +var options = new RestClientOptions("https://httpbin.org/anything"); +var client = new RestClient(options); +var request = new RestRequest(""); +request.AddJsonBody("{\n \"foo\": \"bar\"\n}", false); +var response = await client.PostAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/restsharp/fixtures/jsonObj-null-value.cs b/src/targets/csharp/restsharp/fixtures/jsonObj-null-value.cs new file mode 100644 index 000000000..426281408 --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/jsonObj-null-value.cs @@ -0,0 +1,10 @@ +using RestSharp; + + +var options = new RestClientOptions("https://httpbin.org/anything"); +var client = new RestClient(options); +var request = new RestRequest(""); +request.AddJsonBody("{\"foo\":null}", false); +var response = await client.PostAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/restsharp/fixtures/multipart-data.cs b/src/targets/csharp/restsharp/fixtures/multipart-data.cs new file mode 100644 index 000000000..d85aeaa89 --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/multipart-data.cs @@ -0,0 +1,13 @@ +using RestSharp; + + +var options = new RestClientOptions("https://httpbin.org/anything"); +var client = new RestClient(options); +var request = new RestRequest(""); +request.AlwaysMultipartFormData = true; +request.FormBoundary = "---011000010111000001101001"; +request.AddFile("foo", "src/fixtures/files/hello.txt"); +request.AddParameter("bar", "Bonjour le monde"); +var response = await client.PostAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/restsharp/fixtures/multipart-file.cs b/src/targets/csharp/restsharp/fixtures/multipart-file.cs new file mode 100644 index 000000000..f466a53f5 --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/multipart-file.cs @@ -0,0 +1,12 @@ +using RestSharp; + + +var options = new RestClientOptions("https://httpbin.org/anything"); +var client = new RestClient(options); +var request = new RestRequest(""); +request.AlwaysMultipartFormData = true; +request.FormBoundary = "---011000010111000001101001"; +request.AddFile("foo", "src/fixtures/files/hello.txt"); +var response = await client.PostAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/restsharp/fixtures/multipart-form-data-no-params.cs b/src/targets/csharp/restsharp/fixtures/multipart-form-data-no-params.cs new file mode 100644 index 000000000..43b0ce7f1 --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/multipart-form-data-no-params.cs @@ -0,0 +1,11 @@ +using RestSharp; + + +var options = new RestClientOptions("https://httpbin.org/anything"); +var client = new RestClient(options); +var request = new RestRequest(""); +request.AlwaysMultipartFormData = true; +request.AddHeader("Content-Type", "multipart/form-data"); +var response = await client.PostAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/restsharp/fixtures/multipart-form-data.cs b/src/targets/csharp/restsharp/fixtures/multipart-form-data.cs new file mode 100644 index 000000000..545f75c3a --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/multipart-form-data.cs @@ -0,0 +1,12 @@ +using RestSharp; + + +var options = new RestClientOptions("https://httpbin.org/anything"); +var client = new RestClient(options); +var request = new RestRequest(""); +request.AlwaysMultipartFormData = true; +request.FormBoundary = "---011000010111000001101001"; +request.AddParameter("foo", "bar"); +var response = await client.PostAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/restsharp/fixtures/nested.cs b/src/targets/csharp/restsharp/fixtures/nested.cs new file mode 100644 index 000000000..28b1499e3 --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/nested.cs @@ -0,0 +1,9 @@ +using RestSharp; + + +var options = new RestClientOptions("https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value"); +var client = new RestClient(options); +var request = new RestRequest(""); +var response = await client.GetAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/restsharp/fixtures/postdata-malformed.cs b/src/targets/csharp/restsharp/fixtures/postdata-malformed.cs new file mode 100644 index 000000000..652350ce8 --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/postdata-malformed.cs @@ -0,0 +1,10 @@ +using RestSharp; + + +var options = new RestClientOptions("https://httpbin.org/anything"); +var client = new RestClient(options); +var request = new RestRequest(""); +request.AddHeader("content-type", "application/json"); +var response = await client.PostAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/restsharp/fixtures/query-encoded.cs b/src/targets/csharp/restsharp/fixtures/query-encoded.cs new file mode 100644 index 000000000..02c55cf47 --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/query-encoded.cs @@ -0,0 +1,9 @@ +using RestSharp; + + +var options = new RestClientOptions("https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00"); +var client = new RestClient(options); +var request = new RestRequest(""); +var response = await client.GetAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/restsharp/fixtures/query.cs b/src/targets/csharp/restsharp/fixtures/query.cs new file mode 100644 index 000000000..88b0ee5be --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/query.cs @@ -0,0 +1,9 @@ +using RestSharp; + + +var options = new RestClientOptions("https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value"); +var client = new RestClient(options); +var request = new RestRequest(""); +var response = await client.GetAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/restsharp/fixtures/short.cs b/src/targets/csharp/restsharp/fixtures/short.cs new file mode 100644 index 000000000..9ffe93ecf --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/short.cs @@ -0,0 +1,9 @@ +using RestSharp; + + +var options = new RestClientOptions("https://httpbin.org/anything"); +var client = new RestClient(options); +var request = new RestRequest(""); +var response = await client.GetAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/restsharp/fixtures/text-plain.cs b/src/targets/csharp/restsharp/fixtures/text-plain.cs new file mode 100644 index 000000000..62d226580 --- /dev/null +++ b/src/targets/csharp/restsharp/fixtures/text-plain.cs @@ -0,0 +1,10 @@ +using RestSharp; + + +var options = new RestClientOptions("https://httpbin.org/anything"); +var client = new RestClient(options); +var request = new RestRequest(""); +request.AddStringBody("Hello World", "text/plain"); +var response = await client.PostAsync(request); + +Console.WriteLine("{0}", response.Content); diff --git a/src/targets/csharp/target.ts b/src/targets/csharp/target.ts new file mode 100644 index 000000000..365c3c80f --- /dev/null +++ b/src/targets/csharp/target.ts @@ -0,0 +1,18 @@ +import type { Target } from '../index.js'; + +import { httpclient } from './httpclient/client.js'; +import { restsharp } from './restsharp/client.js'; + +export const csharp: Target = { + info: { + key: 'csharp', + title: 'C#', + default: 'restsharp', + cli: 'dotnet', + }, + + clientsById: { + httpclient, + restsharp, + }, +}; diff --git a/src/targets/go/index.js b/src/targets/go/index.js deleted file mode 100644 index 64630875a..000000000 --- a/src/targets/go/index.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict' - -module.exports = { - info: { - key: 'go', - title: 'Go', - extname: '.go', - default: 'native' - }, - - native: require('./native') -} diff --git a/src/targets/go/native.js b/src/targets/go/native.js deleted file mode 100644 index 7ba90e0f0..000000000 --- a/src/targets/go/native.js +++ /dev/null @@ -1,138 +0,0 @@ -/** - * @description - * HTTP code snippet generator for native Go. - * - * @author - * @montanaflynn - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - // Let's Go! - var code = new CodeBuilder('\t') - - // Define Options - var opts = util._extend({ - showBoilerplate: true, - checkErrors: false, - printBody: true, - timeout: -1 - }, options) - - var errorPlaceholder = opts.checkErrors ? 'err' : '_' - - var indent = opts.showBoilerplate ? 1 : 0 - - var errorCheck = function () { - if (opts.checkErrors) { - code.push(indent, 'if err != nil {') - .push(indent + 1, 'panic(err)') - .push(indent, '}') - } - } - - // Create boilerplate - if (opts.showBoilerplate) { - code.push('package main') - .blank() - .push('import (') - .push(indent, '"fmt"') - - if (opts.timeout > 0) { - code.push(indent, '"time"') - } - - if (source.postData.text) { - code.push(indent, '"strings"') - } - - code.push(indent, '"net/http"') - - if (opts.printBody) { - code.push(indent, '"io/ioutil"') - } - - code.push(')') - .blank() - .push('func main() {') - .blank() - } - - // Create client - var client - if (opts.timeout > 0) { - client = 'client' - code.push(indent, 'client := http.Client{') - .push(indent + 1, 'Timeout: time.Duration(%s * time.Second),', opts.timeout) - .push(indent, '}') - .blank() - } else { - client = 'http.DefaultClient' - } - - code.push(indent, 'url := "%s"', source.fullUrl) - .blank() - - // If we have body content or not create the var and reader or nil - if (source.postData.text) { - code.push(indent, 'payload := strings.NewReader(%s)', JSON.stringify(source.postData.text)) - .blank() - .push(indent, 'req, %s := http.NewRequest("%s", url, payload)', errorPlaceholder, source.method) - .blank() - } else { - code.push(indent, 'req, %s := http.NewRequest("%s", url, nil)', errorPlaceholder, source.method) - .blank() - } - - errorCheck() - - // Add headers - if (Object.keys(source.allHeaders).length) { - Object.keys(source.allHeaders).forEach(function (key) { - code.push(indent, 'req.Header.Add("%s", "%s")', key, source.allHeaders[key]) - }) - - code.blank() - } - - // Make request - code.push(indent, 'res, %s := %s.Do(req)', errorPlaceholder, client) - errorCheck() - - // Get Body - if (opts.printBody) { - code.blank() - .push(indent, 'defer res.Body.Close()') - .push(indent, 'body, %s := ioutil.ReadAll(res.Body)', errorPlaceholder) - errorCheck() - } - - // Print it - code.blank() - .push(indent, 'fmt.Println(res)') - - if (opts.printBody) { - code.push(indent, 'fmt.Println(string(body))') - } - - // End main block - if (opts.showBoilerplate) { - code.blank() - .push('}') - } - - return code.join() -} - -module.exports.info = { - key: 'native', - title: 'NewRequest', - link: 'http://golang.org/pkg/net/http/#NewRequest', - description: 'Golang HTTP client request' -} diff --git a/src/targets/go/native/client.test.ts b/src/targets/go/native/client.test.ts new file mode 100644 index 000000000..24e78068d --- /dev/null +++ b/src/targets/go/native/client.test.ts @@ -0,0 +1,43 @@ +import type { Request } from '../../../index.js'; + +import request from '../../../fixtures/requests/full.cjs'; +import { runCustomFixtures } from '../../../fixtures/runCustomFixtures.js'; + +runCustomFixtures({ + targetId: 'go', + clientId: 'native', + tests: [ + { + it: 'should support false boilerplate option', + input: request.log.entries[0].request as Request, + options: { + showBoilerplate: false, + }, + expected: 'boilerplate-option.go', + }, + { + it: 'should support checkErrors option', + input: request.log.entries[0].request as Request, + options: { + checkErrors: true, + }, + expected: 'check-errors-option.go', + }, + { + it: 'should support printBody option', + input: request.log.entries[0].request as Request, + options: { + printBody: false, + }, + expected: 'print-body-option.go', + }, + { + it: 'should support timeout option', + input: request.log.entries[0].request as Request, + options: { + timeout: 30, + }, + expected: 'timeout-option.go', + }, + ], +}); diff --git a/src/targets/go/native/client.ts b/src/targets/go/native/client.ts new file mode 100644 index 000000000..54ebd5284 --- /dev/null +++ b/src/targets/go/native/client.ts @@ -0,0 +1,142 @@ +/** + * @description + * HTTP code snippet generator for native Go. + * + * @author + * @montanaflynn + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { escapeForDoubleQuotes } from '../../../helpers/escape.js'; + +export interface GoNativeOptions { + checkErrors?: boolean; + printBody?: boolean; + showBoilerplate?: boolean; + timeout?: number; +} + +export const native: Client = { + info: { + key: 'native', + title: 'NewRequest', + link: 'http://golang.org/pkg/net/http/#NewRequest', + description: 'Golang HTTP client request', + extname: '.go', + }, + convert: ({ postData, method, allHeaders, fullUrl }, options = {}) => { + const { blank, push, join } = new CodeBuilder({ indent: '\t' }); + + const { showBoilerplate = true, checkErrors = false, printBody = true, timeout = -1 } = options; + + const errorPlaceholder = checkErrors ? 'err' : '_'; + + const indent = showBoilerplate ? 1 : 0; + + const errorCheck = () => { + if (checkErrors) { + push('if err != nil {', indent); + push('panic(err)', indent + 1); + push('}', indent); + } + }; + + // Create boilerplate + if (showBoilerplate) { + push('package main'); + blank(); + push('import ('); + push('"fmt"', indent); + + if (timeout > 0) { + push('"time"', indent); + } + + if (postData.text) { + push('"strings"', indent); + } + + push('"net/http"', indent); + + if (printBody) { + push('"io"', indent); + } + + push(')'); + blank(); + push('func main() {'); + blank(); + } + + // Create client + const hasTimeout = timeout > 0; + const hasClient = hasTimeout; + const client = hasClient ? 'client' : 'http.DefaultClient'; + + if (hasClient) { + push('client := http.Client{', indent); + + if (hasTimeout) { + push(`Timeout: time.Duration(${timeout} * time.Second),`, indent + 1); + } + + push('}', indent); + blank(); + } + + push(`url := "${fullUrl}"`, indent); + blank(); + + // If we have body content or not create the var and reader or nil + if (postData.text) { + push(`payload := strings.NewReader(${JSON.stringify(postData.text)})`, indent); + blank(); + push(`req, ${errorPlaceholder} := http.NewRequest("${method}", url, payload)`, indent); + blank(); + } else { + push(`req, ${errorPlaceholder} := http.NewRequest("${method}", url, nil)`, indent); + blank(); + } + + errorCheck(); + + // Add headers + if (Object.keys(allHeaders).length) { + Object.keys(allHeaders).forEach(key => { + push(`req.Header.Add("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, indent); + }); + + blank(); + } + + // Make request + push(`res, ${errorPlaceholder} := ${client}.Do(req)`, indent); + errorCheck(); + + // Get Body + if (printBody) { + blank(); + push('defer res.Body.Close()', indent); + push(`body, ${errorPlaceholder} := io.ReadAll(res.Body)`, indent); + errorCheck(); + } + + // Print it + blank(); + + if (printBody) { + push('fmt.Println(string(body))', indent); + } + + // End main block + if (showBoilerplate) { + blank(); + push('}'); + } + + return join(); + }, +}; diff --git a/test/fixtures/output/go/native/application-form-encoded.go b/src/targets/go/native/fixtures/application-form-encoded.go similarity index 76% rename from test/fixtures/output/go/native/application-form-encoded.go rename to src/targets/go/native/fixtures/application-form-encoded.go index 5344b4ea0..5f82a58dc 100644 --- a/test/fixtures/output/go/native/application-form-encoded.go +++ b/src/targets/go/native/fixtures/application-form-encoded.go @@ -4,12 +4,12 @@ import ( "fmt" "strings" "net/http" - "io/ioutil" + "io" ) func main() { - url := "http://mockbin.com/har" + url := "https://httpbin.org/anything" payload := strings.NewReader("foo=bar&hello=world") @@ -20,9 +20,8 @@ func main() { res, _ := http.DefaultClient.Do(req) defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) + body, _ := io.ReadAll(res.Body) - fmt.Println(res) fmt.Println(string(body)) -} +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/application-json.go b/src/targets/go/native/fixtures/application-json.go new file mode 100644 index 000000000..fb3d8eef4 --- /dev/null +++ b/src/targets/go/native/fixtures/application-json.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "strings" + "net/http" + "io" +) + +func main() { + + url := "https://httpbin.org/anything" + + payload := strings.NewReader("{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":[]}],\"boolean\":false}") + + req, _ := http.NewRequest("POST", url, payload) + + req.Header.Add("content-type", "application/json") + + res, _ := http.DefaultClient.Do(req) + + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/boilerplate-option.go b/src/targets/go/native/fixtures/boilerplate-option.go new file mode 100644 index 000000000..d6cf79dc8 --- /dev/null +++ b/src/targets/go/native/fixtures/boilerplate-option.go @@ -0,0 +1,16 @@ +url := "https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value" + +payload := strings.NewReader("foo=bar") + +req, _ := http.NewRequest("POST", url, payload) + +req.Header.Add("cookie", "foo=bar; bar=baz") +req.Header.Add("accept", "application/json") +req.Header.Add("content-type", "application/x-www-form-urlencoded") + +res, _ := http.DefaultClient.Do(req) + +defer res.Body.Close() +body, _ := io.ReadAll(res.Body) + +fmt.Println(string(body)) \ No newline at end of file diff --git a/src/targets/go/native/fixtures/check-errors-option.go b/src/targets/go/native/fixtures/check-errors-option.go new file mode 100644 index 000000000..dc89d3d38 --- /dev/null +++ b/src/targets/go/native/fixtures/check-errors-option.go @@ -0,0 +1,38 @@ +package main + +import ( + "fmt" + "strings" + "net/http" + "io" +) + +func main() { + + url := "https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value" + + payload := strings.NewReader("foo=bar") + + req, err := http.NewRequest("POST", url, payload) + + if err != nil { + panic(err) + } + req.Header.Add("cookie", "foo=bar; bar=baz") + req.Header.Add("accept", "application/json") + req.Header.Add("content-type", "application/x-www-form-urlencoded") + + res, err := http.DefaultClient.Do(req) + if err != nil { + panic(err) + } + + defer res.Body.Close() + body, err := io.ReadAll(res.Body) + if err != nil { + panic(err) + } + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/cookies.go b/src/targets/go/native/fixtures/cookies.go new file mode 100644 index 000000000..5e94934ff --- /dev/null +++ b/src/targets/go/native/fixtures/cookies.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + "net/http" + "io" +) + +func main() { + + url := "https://httpbin.org/cookies" + + req, _ := http.NewRequest("GET", url, nil) + + req.Header.Add("cookie", "foo=bar; bar=baz") + + res, _ := http.DefaultClient.Do(req) + + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/custom-method.go b/src/targets/go/native/fixtures/custom-method.go new file mode 100644 index 000000000..d073db5d6 --- /dev/null +++ b/src/targets/go/native/fixtures/custom-method.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" + "net/http" + "io" +) + +func main() { + + url := "https://httpbin.org/anything" + + req, _ := http.NewRequest("PROPFIND", url, nil) + + res, _ := http.DefaultClient.Do(req) + + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/test/fixtures/output/go/native/full.go b/src/targets/go/native/fixtures/full.go similarity index 75% rename from test/fixtures/output/go/native/full.go rename to src/targets/go/native/fixtures/full.go index 7166a6ab2..a9e0dfbba 100644 --- a/test/fixtures/output/go/native/full.go +++ b/src/targets/go/native/fixtures/full.go @@ -4,12 +4,12 @@ import ( "fmt" "strings" "net/http" - "io/ioutil" + "io" ) func main() { - url := "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value" + url := "https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value" payload := strings.NewReader("foo=bar") @@ -22,9 +22,8 @@ func main() { res, _ := http.DefaultClient.Do(req) defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) + body, _ := io.ReadAll(res.Body) - fmt.Println(res) fmt.Println(string(body)) -} +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/headers.go b/src/targets/go/native/fixtures/headers.go new file mode 100644 index 000000000..adc7dca84 --- /dev/null +++ b/src/targets/go/native/fixtures/headers.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "net/http" + "io" +) + +func main() { + + url := "https://httpbin.org/headers" + + req, _ := http.NewRequest("GET", url, nil) + + req.Header.Add("accept", "application/json") + req.Header.Add("x-foo", "Bar") + req.Header.Add("x-bar", "Foo") + req.Header.Add("quoted-value", "\"quoted\" 'string'") + + res, _ := http.DefaultClient.Do(req) + + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/http-insecure.go b/src/targets/go/native/fixtures/http-insecure.go new file mode 100644 index 000000000..876de1801 --- /dev/null +++ b/src/targets/go/native/fixtures/http-insecure.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" + "net/http" + "io" +) + +func main() { + + url := "http://httpbin.org/anything" + + req, _ := http.NewRequest("GET", url, nil) + + res, _ := http.DefaultClient.Do(req) + + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/jsonObj-multiline.go b/src/targets/go/native/fixtures/jsonObj-multiline.go new file mode 100644 index 000000000..c9e0f0d32 --- /dev/null +++ b/src/targets/go/native/fixtures/jsonObj-multiline.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "strings" + "net/http" + "io" +) + +func main() { + + url := "https://httpbin.org/anything" + + payload := strings.NewReader("{\n \"foo\": \"bar\"\n}") + + req, _ := http.NewRequest("POST", url, payload) + + req.Header.Add("content-type", "application/json") + + res, _ := http.DefaultClient.Do(req) + + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/test/fixtures/output/go/native/jsonObj-null-value.go b/src/targets/go/native/fixtures/jsonObj-null-value.go similarity index 75% rename from test/fixtures/output/go/native/jsonObj-null-value.go rename to src/targets/go/native/fixtures/jsonObj-null-value.go index 8d920d7f9..d0ba779f0 100644 --- a/test/fixtures/output/go/native/jsonObj-null-value.go +++ b/src/targets/go/native/fixtures/jsonObj-null-value.go @@ -4,12 +4,12 @@ import ( "fmt" "strings" "net/http" - "io/ioutil" + "io" ) func main() { - url := "http://mockbin.com/har" + url := "https://httpbin.org/anything" payload := strings.NewReader("{\"foo\":null}") @@ -20,9 +20,8 @@ func main() { res, _ := http.DefaultClient.Do(req) defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) + body, _ := io.ReadAll(res.Body) - fmt.Println(res) fmt.Println(string(body)) -} +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/multipart-data.go b/src/targets/go/native/fixtures/multipart-data.go new file mode 100644 index 000000000..07a89749b --- /dev/null +++ b/src/targets/go/native/fixtures/multipart-data.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "strings" + "net/http" + "io" +) + +func main() { + + url := "https://httpbin.org/anything" + + payload := strings.NewReader("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"bar\"\r\n\r\nBonjour le monde\r\n-----011000010111000001101001--") + + req, _ := http.NewRequest("POST", url, payload) + + req.Header.Add("content-type", "multipart/form-data; boundary=---011000010111000001101001") + + res, _ := http.DefaultClient.Do(req) + + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/multipart-file.go b/src/targets/go/native/fixtures/multipart-file.go new file mode 100644 index 000000000..651872e0c --- /dev/null +++ b/src/targets/go/native/fixtures/multipart-file.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "strings" + "net/http" + "io" +) + +func main() { + + url := "https://httpbin.org/anything" + + payload := strings.NewReader("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--") + + req, _ := http.NewRequest("POST", url, payload) + + req.Header.Add("content-type", "multipart/form-data; boundary=---011000010111000001101001") + + res, _ := http.DefaultClient.Do(req) + + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/multipart-form-data-no-params.go b/src/targets/go/native/fixtures/multipart-form-data-no-params.go new file mode 100644 index 000000000..6124d39eb --- /dev/null +++ b/src/targets/go/native/fixtures/multipart-form-data-no-params.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + "net/http" + "io" +) + +func main() { + + url := "https://httpbin.org/anything" + + req, _ := http.NewRequest("POST", url, nil) + + req.Header.Add("Content-Type", "multipart/form-data") + + res, _ := http.DefaultClient.Do(req) + + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/multipart-form-data.go b/src/targets/go/native/fixtures/multipart-form-data.go new file mode 100644 index 000000000..b519753c1 --- /dev/null +++ b/src/targets/go/native/fixtures/multipart-form-data.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "strings" + "net/http" + "io" +) + +func main() { + + url := "https://httpbin.org/anything" + + payload := strings.NewReader("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--") + + req, _ := http.NewRequest("POST", url, payload) + + req.Header.Add("Content-Type", "multipart/form-data; boundary=---011000010111000001101001") + + res, _ := http.DefaultClient.Do(req) + + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/nested.go b/src/targets/go/native/fixtures/nested.go new file mode 100644 index 000000000..40144c1e7 --- /dev/null +++ b/src/targets/go/native/fixtures/nested.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" + "net/http" + "io" +) + +func main() { + + url := "https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value" + + req, _ := http.NewRequest("GET", url, nil) + + res, _ := http.DefaultClient.Do(req) + + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/postdata-malformed.go b/src/targets/go/native/fixtures/postdata-malformed.go new file mode 100644 index 000000000..d83374085 --- /dev/null +++ b/src/targets/go/native/fixtures/postdata-malformed.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + "net/http" + "io" +) + +func main() { + + url := "https://httpbin.org/anything" + + req, _ := http.NewRequest("POST", url, nil) + + req.Header.Add("content-type", "application/json") + + res, _ := http.DefaultClient.Do(req) + + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/print-body-option.go b/src/targets/go/native/fixtures/print-body-option.go new file mode 100644 index 000000000..9609bbffc --- /dev/null +++ b/src/targets/go/native/fixtures/print-body-option.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + "strings" + "net/http" +) + +func main() { + + url := "https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value" + + payload := strings.NewReader("foo=bar") + + req, _ := http.NewRequest("POST", url, payload) + + req.Header.Add("cookie", "foo=bar; bar=baz") + req.Header.Add("accept", "application/json") + req.Header.Add("content-type", "application/x-www-form-urlencoded") + + res, _ := http.DefaultClient.Do(req) + + +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/query-encoded.go b/src/targets/go/native/fixtures/query-encoded.go new file mode 100644 index 000000000..22f416d6f --- /dev/null +++ b/src/targets/go/native/fixtures/query-encoded.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" + "net/http" + "io" +) + +func main() { + + url := "https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00" + + req, _ := http.NewRequest("GET", url, nil) + + res, _ := http.DefaultClient.Do(req) + + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/query.go b/src/targets/go/native/fixtures/query.go new file mode 100644 index 000000000..79e40e0bc --- /dev/null +++ b/src/targets/go/native/fixtures/query.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" + "net/http" + "io" +) + +func main() { + + url := "https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value" + + req, _ := http.NewRequest("GET", url, nil) + + res, _ := http.DefaultClient.Do(req) + + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/short.go b/src/targets/go/native/fixtures/short.go new file mode 100644 index 000000000..4f0faf4e8 --- /dev/null +++ b/src/targets/go/native/fixtures/short.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" + "net/http" + "io" +) + +func main() { + + url := "https://httpbin.org/anything" + + req, _ := http.NewRequest("GET", url, nil) + + res, _ := http.DefaultClient.Do(req) + + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/text-plain.go b/src/targets/go/native/fixtures/text-plain.go new file mode 100644 index 000000000..799eeba2c --- /dev/null +++ b/src/targets/go/native/fixtures/text-plain.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "strings" + "net/http" + "io" +) + +func main() { + + url := "https://httpbin.org/anything" + + payload := strings.NewReader("Hello World") + + req, _ := http.NewRequest("POST", url, payload) + + req.Header.Add("content-type", "text/plain") + + res, _ := http.DefaultClient.Do(req) + + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/src/targets/go/native/fixtures/timeout-option.go b/src/targets/go/native/fixtures/timeout-option.go new file mode 100644 index 000000000..067d89c25 --- /dev/null +++ b/src/targets/go/native/fixtures/timeout-option.go @@ -0,0 +1,34 @@ +package main + +import ( + "fmt" + "time" + "strings" + "net/http" + "io" +) + +func main() { + + client := http.Client{ + Timeout: time.Duration(30 * time.Second), + } + + url := "https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value" + + payload := strings.NewReader("foo=bar") + + req, _ := http.NewRequest("POST", url, payload) + + req.Header.Add("cookie", "foo=bar; bar=baz") + req.Header.Add("accept", "application/json") + req.Header.Add("content-type", "application/x-www-form-urlencoded") + + res, _ := client.Do(req) + + defer res.Body.Close() + body, _ := io.ReadAll(res.Body) + + fmt.Println(string(body)) + +} \ No newline at end of file diff --git a/src/targets/go/target.ts b/src/targets/go/target.ts new file mode 100644 index 000000000..7d7f82fb7 --- /dev/null +++ b/src/targets/go/target.ts @@ -0,0 +1,15 @@ +import type { Target } from '../index.js'; + +import { native } from './native/client.js'; + +export const go: Target = { + info: { + key: 'go', + title: 'Go', + default: 'native', + cli: 'go', + }, + clientsById: { + native, + }, +}; diff --git a/src/targets/http/http1.1/client.ts b/src/targets/http/http1.1/client.ts new file mode 100644 index 000000000..66f833901 --- /dev/null +++ b/src/targets/http/http1.1/client.ts @@ -0,0 +1,90 @@ +/** + * @description + * HTTP code snippet generator to generate raw HTTP/1.1 request strings, + * in accordance to the RFC 7230 (and RFC 7231) specifications. + * + * @author + * @irvinlim + * + * For any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; + +const CRLF = '\r\n'; + +interface Http11Options { + absoluteURI?: boolean; + autoContentLength?: boolean; + autoHost?: boolean; +} + +/** + * Request follows the request message format in accordance to RFC 7230, Section 3. + * Each section is prepended with the RFC and section number. + * See more at https://tools.ietf.org/html/rfc7230#section-3. + */ +export const http11: Client = { + info: { + key: 'http1.1', + title: 'HTTP/1.1', + link: 'https://tools.ietf.org/html/rfc7230', + description: 'HTTP/1.1 request string in accordance with RFC 7230', + extname: null, + }, + convert: ({ method, fullUrl, uriObj, httpVersion, allHeaders, postData }, options) => { + const opts = { + absoluteURI: false, + autoContentLength: true, + autoHost: true, + ...options, + }; + + // RFC 7230 Section 3. Message Format + // All lines have no indentation, and should be terminated with CRLF. + const { blank, push, join } = new CodeBuilder({ indent: '', join: CRLF }); + + // RFC 7230 Section 5.3. Request Target + // Determines if the Request-Line should use 'absolute-form' or 'origin-form'. + // Basically it means whether the "http://domain.com" will prepend the full url. + const requestUrl = opts.absoluteURI ? fullUrl : uriObj.path; + + // RFC 7230 Section 3.1.1. Request-Line + push(`${method} ${requestUrl} ${httpVersion}`); + + const headerKeys = Object.keys(allHeaders); + // RFC 7231 Section 5. Header Fields + headerKeys.forEach(key => { + // Capitalize header keys, even though it's not required by the spec. + const keyCapitalized = key.toLowerCase().replace(/(^|-)(\w)/g, input => input.toUpperCase()); + push(`${keyCapitalized}: ${allHeaders[key]}`); + }); + + // RFC 7230 Section 5.4. Host + // Automatically set Host header if option is on and on header already exists. + if (opts.autoHost && !headerKeys.includes('host')) { + push(`Host: ${uriObj.host}`); + } + + // RFC 7230 Section 3.3.3. Message Body Length + // Automatically set Content-Length header if option is on, postData is present and no header already exists. + if (opts.autoContentLength && postData.text && !headerKeys.includes('content-length')) { + const length = Buffer.byteLength(postData.text, 'ascii').toString(); + push(`Content-Length: ${length}`); + } + + // Add extra line after header section. + blank(); + + // Separate header section and message body section. + const headerSection = join(); + + // RFC 7230 Section 3.3. Message Body + const messageBody = postData.text || ''; + + // RFC 7230 Section 3. Message Format + // Extra CRLF separating the headers from the body. + return `${headerSection}${CRLF}${messageBody}`; + }, +}; diff --git a/src/targets/http/http1.1/fixtures/application-form-encoded b/src/targets/http/http1.1/fixtures/application-form-encoded new file mode 100644 index 000000000..6db19ad27 --- /dev/null +++ b/src/targets/http/http1.1/fixtures/application-form-encoded @@ -0,0 +1,6 @@ +POST /anything HTTP/1.1 +Content-Type: application/x-www-form-urlencoded +Host: httpbin.org +Content-Length: 19 + +foo=bar&hello=world \ No newline at end of file diff --git a/src/targets/http/http1.1/fixtures/application-json b/src/targets/http/http1.1/fixtures/application-json new file mode 100644 index 000000000..dc47d1d71 --- /dev/null +++ b/src/targets/http/http1.1/fixtures/application-json @@ -0,0 +1,6 @@ +POST /anything HTTP/1.1 +Content-Type: application/json +Host: httpbin.org +Content-Length: 118 + +{"number":1,"string":"f\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":[]}],"boolean":false} \ No newline at end of file diff --git a/src/targets/http/http1.1/fixtures/cookies b/src/targets/http/http1.1/fixtures/cookies new file mode 100644 index 000000000..8c3a7a3c3 --- /dev/null +++ b/src/targets/http/http1.1/fixtures/cookies @@ -0,0 +1,4 @@ +GET /cookies HTTP/1.1 +Cookie: foo=bar; bar=baz +Host: httpbin.org + diff --git a/src/targets/http/http1.1/fixtures/custom-method b/src/targets/http/http1.1/fixtures/custom-method new file mode 100644 index 000000000..65ac2a949 --- /dev/null +++ b/src/targets/http/http1.1/fixtures/custom-method @@ -0,0 +1,3 @@ +PROPFIND /anything HTTP/1.1 +Host: httpbin.org + diff --git a/src/targets/http/http1.1/fixtures/full b/src/targets/http/http1.1/fixtures/full new file mode 100644 index 000000000..e48829b2f --- /dev/null +++ b/src/targets/http/http1.1/fixtures/full @@ -0,0 +1,8 @@ +POST /anything?foo=bar&foo=baz&baz=abc&key=value HTTP/1.1 +Cookie: foo=bar; bar=baz +Accept: application/json +Content-Type: application/x-www-form-urlencoded +Host: httpbin.org +Content-Length: 7 + +foo=bar \ No newline at end of file diff --git a/src/targets/http/http1.1/fixtures/headers b/src/targets/http/http1.1/fixtures/headers new file mode 100644 index 000000000..65900ade9 --- /dev/null +++ b/src/targets/http/http1.1/fixtures/headers @@ -0,0 +1,7 @@ +GET /headers HTTP/1.1 +Accept: application/json +X-Foo: Bar +X-Bar: Foo +Quoted-Value: "quoted" 'string' +Host: httpbin.org + diff --git a/src/targets/http/http1.1/fixtures/http-insecure b/src/targets/http/http1.1/fixtures/http-insecure new file mode 100644 index 000000000..bfc33c020 --- /dev/null +++ b/src/targets/http/http1.1/fixtures/http-insecure @@ -0,0 +1,3 @@ +GET /anything HTTP/1.1 +Host: httpbin.org + diff --git a/src/targets/http/http1.1/fixtures/jsonObj-multiline b/src/targets/http/http1.1/fixtures/jsonObj-multiline new file mode 100644 index 000000000..a69aa5676 --- /dev/null +++ b/src/targets/http/http1.1/fixtures/jsonObj-multiline @@ -0,0 +1,8 @@ +POST /anything HTTP/1.1 +Content-Type: application/json +Host: httpbin.org +Content-Length: 18 + +{ + "foo": "bar" +} \ No newline at end of file diff --git a/src/targets/http/http1.1/fixtures/jsonObj-null-value b/src/targets/http/http1.1/fixtures/jsonObj-null-value new file mode 100644 index 000000000..529e38775 --- /dev/null +++ b/src/targets/http/http1.1/fixtures/jsonObj-null-value @@ -0,0 +1,6 @@ +POST /anything HTTP/1.1 +Content-Type: application/json +Host: httpbin.org +Content-Length: 12 + +{"foo":null} \ No newline at end of file diff --git a/src/targets/http/http1.1/fixtures/multipart-data b/src/targets/http/http1.1/fixtures/multipart-data new file mode 100644 index 000000000..b0db0b607 --- /dev/null +++ b/src/targets/http/http1.1/fixtures/multipart-data @@ -0,0 +1,15 @@ +POST /anything HTTP/1.1 +Content-Type: multipart/form-data; boundary=---011000010111000001101001 +Host: httpbin.org +Content-Length: 283 + +-----011000010111000001101001 +Content-Disposition: form-data; name="foo"; filename="src/fixtures/files/hello.txt" +Content-Type: text/plain + +Hello World +-----011000010111000001101001 +Content-Disposition: form-data; name="bar" + +Bonjour le monde +-----011000010111000001101001-- \ No newline at end of file diff --git a/src/targets/http/http1.1/fixtures/multipart-file b/src/targets/http/http1.1/fixtures/multipart-file new file mode 100644 index 000000000..13b7f1bd9 --- /dev/null +++ b/src/targets/http/http1.1/fixtures/multipart-file @@ -0,0 +1,11 @@ +POST /anything HTTP/1.1 +Content-Type: multipart/form-data; boundary=---011000010111000001101001 +Host: httpbin.org +Content-Length: 177 + +-----011000010111000001101001 +Content-Disposition: form-data; name="foo"; filename="src/fixtures/files/hello.txt" +Content-Type: text/plain + + +-----011000010111000001101001-- \ No newline at end of file diff --git a/src/targets/http/http1.1/fixtures/multipart-form-data b/src/targets/http/http1.1/fixtures/multipart-form-data new file mode 100644 index 000000000..cde9fcc99 --- /dev/null +++ b/src/targets/http/http1.1/fixtures/multipart-form-data @@ -0,0 +1,10 @@ +POST /anything HTTP/1.1 +Content-Type: multipart/form-data; boundary=---011000010111000001101001 +Host: httpbin.org +Content-Length: 113 + +-----011000010111000001101001 +Content-Disposition: form-data; name="foo" + +bar +-----011000010111000001101001-- \ No newline at end of file diff --git a/src/targets/http/http1.1/fixtures/multipart-form-data-no-params b/src/targets/http/http1.1/fixtures/multipart-form-data-no-params new file mode 100644 index 000000000..9493b6ff4 --- /dev/null +++ b/src/targets/http/http1.1/fixtures/multipart-form-data-no-params @@ -0,0 +1,4 @@ +POST /anything HTTP/1.1 +Content-Type: multipart/form-data +Host: httpbin.org + diff --git a/src/targets/http/http1.1/fixtures/nested b/src/targets/http/http1.1/fixtures/nested new file mode 100644 index 000000000..f8de57796 --- /dev/null +++ b/src/targets/http/http1.1/fixtures/nested @@ -0,0 +1,3 @@ +GET /anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value HTTP/1.1 +Host: httpbin.org + diff --git a/src/targets/http/http1.1/fixtures/postdata-malformed b/src/targets/http/http1.1/fixtures/postdata-malformed new file mode 100644 index 000000000..653d96ace --- /dev/null +++ b/src/targets/http/http1.1/fixtures/postdata-malformed @@ -0,0 +1,4 @@ +POST /anything HTTP/1.1 +Content-Type: application/json +Host: httpbin.org + diff --git a/src/targets/http/http1.1/fixtures/query b/src/targets/http/http1.1/fixtures/query new file mode 100644 index 000000000..0f511330d --- /dev/null +++ b/src/targets/http/http1.1/fixtures/query @@ -0,0 +1,3 @@ +GET /anything?foo=bar&foo=baz&baz=abc&key=value HTTP/1.1 +Host: httpbin.org + diff --git a/src/targets/http/http1.1/fixtures/query-encoded b/src/targets/http/http1.1/fixtures/query-encoded new file mode 100644 index 000000000..23200265f --- /dev/null +++ b/src/targets/http/http1.1/fixtures/query-encoded @@ -0,0 +1,3 @@ +GET /anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00 HTTP/1.1 +Host: httpbin.org + diff --git a/src/targets/http/http1.1/fixtures/short b/src/targets/http/http1.1/fixtures/short new file mode 100644 index 000000000..bfc33c020 --- /dev/null +++ b/src/targets/http/http1.1/fixtures/short @@ -0,0 +1,3 @@ +GET /anything HTTP/1.1 +Host: httpbin.org + diff --git a/src/targets/http/http1.1/fixtures/text-plain b/src/targets/http/http1.1/fixtures/text-plain new file mode 100644 index 000000000..c2baab0bf --- /dev/null +++ b/src/targets/http/http1.1/fixtures/text-plain @@ -0,0 +1,6 @@ +POST /anything HTTP/1.1 +Content-Type: text/plain +Host: httpbin.org +Content-Length: 11 + +Hello World \ No newline at end of file diff --git a/src/targets/http/target.ts b/src/targets/http/target.ts new file mode 100644 index 000000000..1dce0de1b --- /dev/null +++ b/src/targets/http/target.ts @@ -0,0 +1,14 @@ +import type { Target } from '../index.js'; + +import { http11 } from './http1.1/client.js'; + +export const http: Target = { + info: { + key: 'http', + title: 'HTTP', + default: 'http1.1', + }, + clientsById: { + 'http1.1': http11, + }, +}; diff --git a/src/targets/index.js b/src/targets/index.js deleted file mode 100644 index d4369529d..000000000 --- a/src/targets/index.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict' - -module.exports = { - c: require('./c'), - clojure: require('./clojure'), - csharp: require('./csharp'), - go: require('./go'), - java: require('./java'), - javascript: require('./javascript'), - node: require('./node'), - objc: require('./objc'), - ocaml: require('./ocaml'), - php: require('./php'), - python: require('./python'), - ruby: require('./ruby'), - shell: require('./shell'), - swift: require('./swift') -} diff --git a/src/targets/index.test.ts b/src/targets/index.test.ts new file mode 100644 index 000000000..eb46b3144 --- /dev/null +++ b/src/targets/index.test.ts @@ -0,0 +1,356 @@ +import type { HTTPSnippetOptions, Request } from '../index.js'; +import type { Client, ClientId, ClientPlugin, Target, TargetId } from './index.js'; + +import { readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; + +import { afterEach, describe, expect, it } from 'vitest'; + +import short from '../fixtures/requests/short.cjs'; +import { availableTargets, extname } from '../helpers/utils.js'; +import { HTTPSnippet } from '../index.js'; +import { addClientPlugin, addTarget, addTargetClient, isClient, isTarget, targets } from './index.js'; + +const expectedBasePath = ['src', 'fixtures', 'requests']; + +const inputFileNames = readdirSync(path.join(...expectedBasePath), 'utf-8'); + +const fixtures: [string, Request][] = inputFileNames.map(inputFileName => [ + inputFileName.replace(path.extname(inputFileName), ''), + // biome-ignore lint/style/noCommonJs: Because we're dynamically loading fixtures we need to use `require`. + require(path.resolve(...expectedBasePath, inputFileName)), +]); + +/** useful for debuggin, only run a particular set of targets */ +const targetFilter: TargetId[] = [ + // put your targetId: + // 'node', +]; + +/** useful for debuggin, only run a particular set of targets */ +const clientFilter: ClientId[] = [ + // put your clientId here: + // 'axios', +]; + +/** useful for debuggin, only run a particular set of fixtures */ +const fixtureFilter: string[] = [ + // put the name of the fixture file you want to isolate (excluding `.json`): + // 'multipart-file', +]; + +/** + * This is useful when you want to make a change and overwrite it for every fixture. + * Basically a snapshot reset. + * + * Switch to `true` in debug mode to put into effect. + */ +const OVERWRITE_EVERYTHING = Boolean(process.env.OVERWRITE_EVERYTHING) || false; + +const testFilter = + (property: keyof T, list: T[keyof T][]) => + (item: T) => + list.length > 0 ? list.includes(item[property]) : true; + +describe('request validation', () => { + describe.each( + availableTargets() + .filter(testFilter('key', targetFilter)) + .map(target => [target.key, target]), + )('%s', (title, { key: targetId, clients }) => { + describe.each(clients.filter(testFilter('key', clientFilter)).map(client => [client.key, client]))( + '%s', + (clientId, { extname: fixtureExtension }) => { + it.each(fixtures.filter(testFilter(0, fixtureFilter)))( + 'request should match fixture for "%s.js"', + (fixture, request) => { + const expectedPath = path.join( + 'src', + 'targets', + targetId, + clientId, + 'fixtures', + `${fixture}${extname(targetId, clientId)}`, + ); + + let result: string | string[] | false; + let expected: string; + + try { + const options: HTTPSnippetOptions = {}; + + if (fixture === 'query-encoded') { + // Query strings in this HAR are already escaped. + options.harIsAlreadyEncoded = true; + } + + expected = readFileSync(expectedPath).toString(); + const snippet = new HTTPSnippet(request, options); + + result = snippet.convert(targetId, clientId)[0]; + + if (OVERWRITE_EVERYTHING && result) { + writeFileSync(expectedPath, String(result)); + return; + } + } catch (err) { + if (err.constructor.name === 'HARError') { + throw err; + } + + throw new Error( + `Missing a test file for ${targetId}:${clientId} for the ${fixture} fixture.\nExpected to find the output fixture: \`/src/targets/${targetId}/${clientId}/fixtures/${fixture}${ + fixtureExtension ?? '' + }\``, + ); + } + + expect(result).toStrictEqual(expected); + }, + ); + }, + ); + }); +}); + +describe('isTarget', () => { + it("should throw if you don't provide an object", () => { + // @ts-expect-error intentionally incorrect + expect(() => isTarget(null)).toThrow('you tried to add a target which is not an object, got type: "null"'); + // @ts-expect-error intentionally incorrect + expect(() => isTarget(undefined)).toThrow( + 'you tried to add a target which is not an object, got type: "undefined"', + ); + // @ts-expect-error intentionally incorrect + expect(() => isTarget([])).toThrow('you tried to add a target which is not an object, got type: "array"'); + }); + + it('validates required fields', () => { + // @ts-expect-error intentionally incorrect + expect(() => isTarget({})).toThrow('targets must contain an `info` object'); + // @ts-expect-error intentionally incorrect + expect(() => isTarget({ info: {} })).toThrow('targets must have an `info` object with the property `key`'); + // @ts-expect-error intentionally incorrect + expect(() => isTarget({ info: { key: '' } })).toThrow('target key must be a unique string'); + // @ts-expect-error intentionally incorrect + expect(() => isTarget({ info: { key: null } })).toThrow('target key must be a unique string'); + // @ts-expect-error intentionally incorrect + expect(() => isTarget({ info: { key: undefined } })).toThrow('target key must be a unique string'); + // @ts-expect-error intentionally incorrect + expect(() => isTarget({ info: { key: 'c' } })).toThrow('a target already exists with this key, `c`'); + // @ts-expect-error intentionally incorrect + expect(() => isTarget({ info: { key: 'z' } })).toThrow( + 'targets must have an `info` object with the property `title`', + ); + // @ts-expect-error intentionally incorrect + expect(() => isTarget({ info: { key: 'z', title: '' } })).toThrow('target title must be a non-zero-length string'); + // @ts-expect-error intentionally incorrect + expect(() => isTarget({ info: { key: 'z', title: null } })).toThrow( + 'target title must be a non-zero-length string', + ); + // @ts-expect-error intentionally incorrect + expect(() => isTarget({ info: { key: 'z', title: undefined } })).toThrow( + 'target title must be a non-zero-length string', + ); + // @ts-expect-error intentionally incorrect + expect(() => isTarget({ info: { key: 'z', title: 't', extname: '' } })).toThrow( + 'No clients provided in target z. You must provide the property `clientsById` containg your clients.', + ); + expect(() => + // @ts-expect-error intentionally incorrect + isTarget({ info: { key: 'z', title: 't', extname: '' }, clientsById: {} }), + ).toThrow('No clients provided in target z. You must provide the property `clientsById` containg your clients.'); + expect(() => + // @ts-expect-error intentionally incorrect + isTarget({ info: { key: 'z', title: 't', extname: '' }, clientsById: null }), + ).toThrow('No clients provided in target z. You must provide the property `clientsById` containg your clients.'); + expect(() => + // @ts-expect-error intentionally incorrect + isTarget({ info: { key: 'z', title: 't', extname: '' }, clientsById: undefined }), + ).toThrow('No clients provided in target z. You must provide the property `clientsById` containg your clients.'); + expect(() => + // @ts-expect-error intentionally incorrect + isTarget({ info: { key: 'z', title: 't', extname: '' }, clientsById: { a: {} } }), + ).toThrow('targets must have an `info` object with the property `default`'); + expect(() => + isTarget({ + // @ts-expect-error intentionally incorrect + info: { key: 'z', title: 't', extname: '', default: 'b' }, + // @ts-expect-error intentionally incorrect + clientsById: { a: {} }, + }), + ).toThrow( + 'target z is configured with a default client b, but no such client was found in the property `clientsById` (found ["a"])', + ); + + expect( + isTarget({ + info: { key: 'z' as TargetId, title: 't', default: 'a' }, + clientsById: { + a: { + info: { + key: 'a', + title: 'a', + description: '', + link: '', + extname: null, + }, + convert: () => '', + }, + }, + }), + ).toBe(true); + }); +}); + +describe('isClient', () => { + it('validates the client', () => { + // @ts-expect-error intentionally incorrect + expect(() => isClient(null)).toThrow('clients must be objects'); + // @ts-expect-error intentionally incorrect + expect(() => isClient(undefined)).toThrow('clients must be objects'); + // @ts-expect-error intentionally incorrect + expect(() => isClient({})).toThrow('targets client must contain an `info` object'); + // @ts-expect-error intentionally incorrect + expect(() => isClient({ info: '' })).toThrow('targets client must have an `info` object with property `key`'); + // @ts-expect-error intentionally incorrect + expect(() => isClient({ info: { key: undefined } })).toThrow( + 'client.info.key must contain an identifier unique to this target', + ); + // @ts-expect-error intentionally incorrect + expect(() => isClient({ info: { key: null } })).toThrow( + 'client.info.key must contain an identifier unique to this target', + ); + // @ts-expect-error intentionally incorrect + expect(() => isClient({ info: { key: '' } })).toThrow( + 'client.info.key must contain an identifier unique to this target', + ); + // @ts-expect-error intentionally incorrect + expect(() => isClient({ info: { key: 'a' } })).toThrow( + 'targets client must have an `info` object with property `title`', + ); + // @ts-expect-error intentionally incorrect + expect(() => isClient({ info: { key: 'a', title: '' } })).toThrow( + 'targets client must have an `info` object with property `description`', + ); + // @ts-expect-error intentionally incorrect + expect(() => isClient({ info: { key: 'a', description: '', title: '' } })).toThrow( + 'targets client must have an `info` object with property `link`', + ); + // @ts-expect-error intentionally incorrect + expect(() => isClient({ info: { key: 'a', description: '', title: '', link: '' } })).toThrow( + 'targets client must have an `info` object with the property `extname`', + ); + // @ts-expect-error intentionally incorrect + expect(() => isClient({ info: { key: 'a', title: '', link: '', description: '', extname: '' } })).toThrow( + 'targets client must have a `convert` property containing a conversion function', + ); + expect(() => + // @ts-expect-error intentionally incorrect + isClient({ info: { key: 'a', title: '', link: '', description: '', extname: '' }, convert: '' }), + ).toThrow('targets client must have a `convert` property containing a conversion function'); + expect( + isClient({ + info: { key: 'a', title: '', link: '', description: '', extname: null }, + convert: () => '', + }), + ).toBe(true); + }); +}); + +describe('addTarget', () => { + afterEach(() => { + // @ts-expect-error intentionally incorrect + delete targets.deno; + }); + + it('should add a new custom target', async () => { + const { fetch: fetchClient } = await import('./node/fetch/client.ts'); + + const deno: Target = { + info: { + // @ts-expect-error intentionally incorrect + key: 'deno', + title: 'Deno', + extname: '.js', + default: 'fetch', + }, + clientsById: { + fetch: fetchClient, + }, + }; + + addTarget(deno); + + // @ts-expect-error intentionally incorrect + expect(targets.deno).toBeDefined(); + // @ts-expect-error intentionally incorrect + expect(targets.deno).toStrictEqual(deno); + }); +}); + +describe('addTargetClient', () => { + afterEach(() => { + delete targets.node.clientsById.custom; + }); + + it('should add a new custom target', () => { + const customClient: Client = { + info: { + key: 'custom', + title: 'Custom HTTP library', + link: 'https://example.com', + description: 'A custom HTTP library', + extname: '.custom', + installation: (request, opts) => { + return `brew install ${request.fullUrl}/${opts?.clientId}`; + }, + }, + convert: () => { + return 'This was generated from a custom client.'; + }, + }; + + addTargetClient('node', customClient); + + const snippet = new HTTPSnippet(short.log.entries[0].request as Request, {}); + + const result = snippet.convert('node', 'custom')[0]; + expect(result).toBe('This was generated from a custom client.'); + + const install = snippet.installation('node', 'custom')[0]; + expect(install).toBe('brew install https://httpbin.org/anything/custom'); + }); +}); + +describe('addClientPlugin', () => { + afterEach(() => { + delete targets.node.clientsById.custom; + }); + + it('should add a new custom target', () => { + const customPlugin: ClientPlugin = { + target: 'node', + client: { + info: { + key: 'custom', + title: 'Custom HTTP library', + link: 'https://example.com', + description: 'A custom HTTP library', + extname: '.custom', + }, + convert: () => { + return 'This was generated from a custom client.'; + }, + }, + }; + + addClientPlugin(customPlugin); + + const snippet = new HTTPSnippet(short.log.entries[0].request as Request, {}); + + const result = snippet.convert('node', 'custom')[0]; + + expect(result).toBe('This was generated from a custom client.'); + }); +}); diff --git a/src/targets/index.ts b/src/targets/index.ts new file mode 100644 index 000000000..49fea1189 --- /dev/null +++ b/src/targets/index.ts @@ -0,0 +1,272 @@ +import type { Merge } from 'type-fest'; +import type { CodeBuilderOptions } from '../helpers/code-builder.js'; +import type { Request } from '../index.js'; + +import { c } from './c/target.js'; +import { clojure } from './clojure/target.js'; +import { csharp } from './csharp/target.js'; +import { go } from './go/target.js'; +import { http } from './http/target.js'; +import { java } from './java/target.js'; +import { javascript } from './javascript/target.js'; +import { json } from './json/target.js'; +import { kotlin } from './kotlin/target.js'; +import { node } from './node/target.js'; +import { objc } from './objc/target.js'; +import { ocaml } from './ocaml/target.js'; +import { php } from './php/target.js'; +import { powershell } from './powershell/target.js'; +import { python } from './python/target.js'; +import { r } from './r/target.js'; +import { ruby } from './ruby/target.js'; +import { shell } from './shell/target.js'; +import { swift } from './swift/target.js'; + +export type TargetId = keyof typeof targets; + +export type ClientId = string; + +export interface ClientInfo = Record> { + /** + * A description of the client. + * + * @example Promise based HTTP client for the browser and node.js + */ + description: string; + + /** + * The default file extension for the client. + * + * @example `.js` + */ + extname: Extension; + /** + * Retrieve or generate a command to install the client. + * + * @example () => 'npm install axios --save'; + */ + installation?: Converter; + + /** + * A unique identifier for the client. + * + * This should be a string that is unique to the client for the given target. + * + * @example `axios` + */ + key: ClientId; + + /** + * A link to the documentation or homepage of the client. + * + * @example https://github.com/axios/axios + */ + link: string; + + /** + * The formatted name of the client. + * + * @example Axios + */ + title: string; +} + +export type Converter> = ( + request: Request, + options?: Merge, +) => string; + +export interface Client = Record> { + convert: Converter; + info: ClientInfo; +} + +export interface ClientPlugin = Record> { + client: Client; + target: TargetId; +} + +export type Extension = `.${string}` | null; + +export interface TargetInfo { + cli?: string; + default: string; + key: TargetId; + title: string; +} + +export interface Target { + clientsById: Record; + info: TargetInfo; +} + +type supportedTargets = + | 'c' + | 'clojure' + | 'csharp' + | 'go' + | 'http' + | 'java' + | 'javascript' + | 'json' + | 'kotlin' + | 'node' + | 'objc' + | 'ocaml' + | 'php' + | 'powershell' + | 'python' + | 'r' + | 'ruby' + | 'shell' + | 'swift'; + +export const targets: Record = { + c, + clojure, + csharp, + go, + http, + java, + javascript, + json, + kotlin, + node, + objc, + ocaml, + php, + powershell, + python, + r, + ruby, + shell, + swift, +}; + +export const isTarget = (target: Target): target is Target => { + if (typeof target !== 'object' || target === null || Array.isArray(target)) { + const got = target === null ? 'null' : Array.isArray(target) ? 'array' : typeof target; + throw new Error(`you tried to add a target which is not an object, got type: "${got}"`); + } + + if (!Object.prototype.hasOwnProperty.call(target, 'info')) { + throw new Error('targets must contain an `info` object'); + } + + if (!Object.prototype.hasOwnProperty.call(target.info, 'key')) { + throw new Error('targets must have an `info` object with the property `key`'); + } + + if (!target.info.key) { + throw new Error('target key must be a unique string'); + } + + if (Object.prototype.hasOwnProperty.call(targets, target.info.key)) { + throw new Error(`a target already exists with this key, \`${target.info.key}\``); + } + + if (!Object.prototype.hasOwnProperty.call(target.info, 'title')) { + throw new Error('targets must have an `info` object with the property `title`'); + } + + if (!target.info.title) { + throw new Error('target title must be a non-zero-length string'); + } + + if ( + !Object.prototype.hasOwnProperty.call(target, 'clientsById') || + !target.clientsById || + Object.keys(target.clientsById).length === 0 + ) { + throw new Error( + `No clients provided in target ${target.info.key}. You must provide the property \`clientsById\` containg your clients.`, + ); + } + + if (!Object.prototype.hasOwnProperty.call(target.info, 'default')) { + throw new Error('targets must have an `info` object with the property `default`'); + } + + if (!Object.prototype.hasOwnProperty.call(target.clientsById, target.info.default)) { + throw new Error( + `target ${target.info.key} is configured with a default client ${ + target.info.default + }, but no such client was found in the property \`clientsById\` (found ${JSON.stringify( + Object.keys(target.clientsById), + )})`, + ); + } + + Object.values(target.clientsById).forEach(isClient); + + return true; +}; + +export const addTarget = (target: Target): void => { + if (!isTarget(target)) { + return; + } + targets[target.info.key] = target; +}; + +export const isClient = (client: Client): client is Client => { + if (!client) { + throw new Error('clients must be objects'); + } + + if (!Object.prototype.hasOwnProperty.call(client, 'info')) { + throw new Error('targets client must contain an `info` object'); + } + + if (!Object.prototype.hasOwnProperty.call(client.info, 'key')) { + throw new Error('targets client must have an `info` object with property `key`'); + } + + if (!client.info.key) { + throw new Error('client.info.key must contain an identifier unique to this target'); + } + + if (!Object.prototype.hasOwnProperty.call(client.info, 'title')) { + throw new Error('targets client must have an `info` object with property `title`'); + } + + if (!Object.prototype.hasOwnProperty.call(client.info, 'description')) { + throw new Error('targets client must have an `info` object with property `description`'); + } + + if (!Object.prototype.hasOwnProperty.call(client.info, 'link')) { + throw new Error('targets client must have an `info` object with property `link`'); + } + + if (!Object.prototype.hasOwnProperty.call(client.info, 'extname')) { + throw new Error('targets client must have an `info` object with the property `extname`'); + } + + if (!Object.prototype.hasOwnProperty.call(client, 'convert') || typeof client.convert !== 'function') { + throw new Error('targets client must have a `convert` property containing a conversion function'); + } + + return true; +}; + +export const addClientPlugin = (plugin: ClientPlugin): void => { + addTargetClient(plugin.target, plugin.client); +}; + +export const addTargetClient = (targetId: TargetId, client: Client): void => { + if (!isClient(client)) { + return; + } + + if (!Object.prototype.hasOwnProperty.call(targets, targetId)) { + throw new Error(`Sorry, but no ${targetId} target exists to add clients to`); + } + + if (Object.prototype.hasOwnProperty.call(targets[targetId], client.info.key)) { + throw new Error( + `the target ${targetId} already has a client with the key ${client.info.key}, please use a different key`, + ); + } + + targets[targetId].clientsById[client.info.key] = client; +}; diff --git a/src/targets/java/asynchttp/client.ts b/src/targets/java/asynchttp/client.ts new file mode 100644 index 000000000..1f38478ef --- /dev/null +++ b/src/targets/java/asynchttp/client.ts @@ -0,0 +1,52 @@ +/** + * @description + * Asynchronous Http and WebSocket Client library for Java + * + * @author + * @windard + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { escapeForDoubleQuotes } from '../../../helpers/escape.js'; + +export const asynchttp: Client = { + info: { + key: 'asynchttp', + title: 'AsyncHttp', + link: 'https://github.com/AsyncHttpClient/async-http-client', + description: 'Asynchronous Http and WebSocket Client library for Java', + extname: '.java', + }, + convert: ({ method, allHeaders, postData, fullUrl }, options) => { + const opts = { + indent: ' ', + ...options, + }; + const { blank, push, join } = new CodeBuilder({ indent: opts.indent }); + + push('AsyncHttpClient client = new DefaultAsyncHttpClient();'); + + push(`client.prepare("${method.toUpperCase()}", "${fullUrl}")`); + + // Add headers, including the cookies + Object.keys(allHeaders).forEach(key => { + push(`.setHeader("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, 1); + }); + + if (postData.text) { + push(`.setBody(${JSON.stringify(postData.text)})`, 1); + } + + push('.execute()', 1); + push('.toCompletableFuture()', 1); + push('.thenAccept(System.out::println)', 1); + push('.join();', 1); + blank(); + push('client.close();'); + + return join(); + }, +}; diff --git a/src/targets/java/asynchttp/fixtures/application-form-encoded.java b/src/targets/java/asynchttp/fixtures/application-form-encoded.java new file mode 100644 index 000000000..db36c2104 --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/application-form-encoded.java @@ -0,0 +1,10 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("POST", "https://httpbin.org/anything") + .setHeader("content-type", "application/x-www-form-urlencoded") + .setBody("foo=bar&hello=world") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/application-json.java b/src/targets/java/asynchttp/fixtures/application-json.java new file mode 100644 index 000000000..80ada6bfd --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/application-json.java @@ -0,0 +1,10 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("POST", "https://httpbin.org/anything") + .setHeader("content-type", "application/json") + .setBody("{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":[]}],\"boolean\":false}") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/cookies.java b/src/targets/java/asynchttp/fixtures/cookies.java new file mode 100644 index 000000000..253aaf09a --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/cookies.java @@ -0,0 +1,9 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("GET", "https://httpbin.org/cookies") + .setHeader("cookie", "foo=bar; bar=baz") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/custom-method.java b/src/targets/java/asynchttp/fixtures/custom-method.java new file mode 100644 index 000000000..f6cada097 --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/custom-method.java @@ -0,0 +1,8 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("PROPFIND", "https://httpbin.org/anything") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/full.java b/src/targets/java/asynchttp/fixtures/full.java new file mode 100644 index 000000000..de7352ddb --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/full.java @@ -0,0 +1,12 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("POST", "https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value") + .setHeader("cookie", "foo=bar; bar=baz") + .setHeader("accept", "application/json") + .setHeader("content-type", "application/x-www-form-urlencoded") + .setBody("foo=bar") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/headers.java b/src/targets/java/asynchttp/fixtures/headers.java new file mode 100644 index 000000000..cf3a410f5 --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/headers.java @@ -0,0 +1,12 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("GET", "https://httpbin.org/headers") + .setHeader("accept", "application/json") + .setHeader("x-foo", "Bar") + .setHeader("x-bar", "Foo") + .setHeader("quoted-value", "\"quoted\" 'string'") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/http-insecure.java b/src/targets/java/asynchttp/fixtures/http-insecure.java new file mode 100644 index 000000000..36f66c3e2 --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/http-insecure.java @@ -0,0 +1,8 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("GET", "http://httpbin.org/anything") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/jsonObj-multiline.java b/src/targets/java/asynchttp/fixtures/jsonObj-multiline.java new file mode 100644 index 000000000..7fae7d0cb --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/jsonObj-multiline.java @@ -0,0 +1,10 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("POST", "https://httpbin.org/anything") + .setHeader("content-type", "application/json") + .setBody("{\n \"foo\": \"bar\"\n}") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/jsonObj-null-value.java b/src/targets/java/asynchttp/fixtures/jsonObj-null-value.java new file mode 100644 index 000000000..7dd770aaf --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/jsonObj-null-value.java @@ -0,0 +1,10 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("POST", "https://httpbin.org/anything") + .setHeader("content-type", "application/json") + .setBody("{\"foo\":null}") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/multipart-data.java b/src/targets/java/asynchttp/fixtures/multipart-data.java new file mode 100644 index 000000000..6e118f6fd --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/multipart-data.java @@ -0,0 +1,10 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("POST", "https://httpbin.org/anything") + .setHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001") + .setBody("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"bar\"\r\n\r\nBonjour le monde\r\n-----011000010111000001101001--") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/multipart-file.java b/src/targets/java/asynchttp/fixtures/multipart-file.java new file mode 100644 index 000000000..623982dbe --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/multipart-file.java @@ -0,0 +1,10 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("POST", "https://httpbin.org/anything") + .setHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001") + .setBody("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/multipart-form-data-no-params.java b/src/targets/java/asynchttp/fixtures/multipart-form-data-no-params.java new file mode 100644 index 000000000..ea5f81260 --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/multipart-form-data-no-params.java @@ -0,0 +1,9 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("POST", "https://httpbin.org/anything") + .setHeader("Content-Type", "multipart/form-data") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/multipart-form-data.java b/src/targets/java/asynchttp/fixtures/multipart-form-data.java new file mode 100644 index 000000000..731b01113 --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/multipart-form-data.java @@ -0,0 +1,10 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("POST", "https://httpbin.org/anything") + .setHeader("Content-Type", "multipart/form-data; boundary=---011000010111000001101001") + .setBody("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/nested.java b/src/targets/java/asynchttp/fixtures/nested.java new file mode 100644 index 000000000..4d5528474 --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/nested.java @@ -0,0 +1,8 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("GET", "https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/postdata-malformed.java b/src/targets/java/asynchttp/fixtures/postdata-malformed.java new file mode 100644 index 000000000..18b52d68f --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/postdata-malformed.java @@ -0,0 +1,9 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("POST", "https://httpbin.org/anything") + .setHeader("content-type", "application/json") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/query-encoded.java b/src/targets/java/asynchttp/fixtures/query-encoded.java new file mode 100644 index 000000000..35973c457 --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/query-encoded.java @@ -0,0 +1,8 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("GET", "https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/query.java b/src/targets/java/asynchttp/fixtures/query.java new file mode 100644 index 000000000..1dd8a54f1 --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/query.java @@ -0,0 +1,8 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("GET", "https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/short.java b/src/targets/java/asynchttp/fixtures/short.java new file mode 100644 index 000000000..790b91293 --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/short.java @@ -0,0 +1,8 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("GET", "https://httpbin.org/anything") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/asynchttp/fixtures/text-plain.java b/src/targets/java/asynchttp/fixtures/text-plain.java new file mode 100644 index 000000000..4bb619c8d --- /dev/null +++ b/src/targets/java/asynchttp/fixtures/text-plain.java @@ -0,0 +1,10 @@ +AsyncHttpClient client = new DefaultAsyncHttpClient(); +client.prepare("POST", "https://httpbin.org/anything") + .setHeader("content-type", "text/plain") + .setBody("Hello World") + .execute() + .toCompletableFuture() + .thenAccept(System.out::println) + .join(); + +client.close(); \ No newline at end of file diff --git a/src/targets/java/index.js b/src/targets/java/index.js deleted file mode 100644 index 2d13eefa1..000000000 --- a/src/targets/java/index.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict' - -module.exports = { - info: { - key: 'java', - title: 'Java', - extname: '.java', - default: 'unirest' - }, - - okhttp: require('./okhttp'), - unirest: require('./unirest') -} diff --git a/src/targets/java/nethttp/client.ts b/src/targets/java/nethttp/client.ts new file mode 100644 index 000000000..c1e7df245 --- /dev/null +++ b/src/targets/java/nethttp/client.ts @@ -0,0 +1,60 @@ +/** + * @description + * HTTP code snippet generator for Java using java.net.http. + * + * @author + * @wtetsu + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { escapeForDoubleQuotes } from '../../../helpers/escape.js'; + +export interface NetHttpOptions { + indent?: string; +} + +export const nethttp: Client = { + info: { + key: 'nethttp', + title: 'java.net.http', + link: 'https://openjdk.java.net/groups/net/httpclient/intro.html', + description: 'Java Standardized HTTP Client API', + extname: '.java', + }, + convert: ({ allHeaders, fullUrl, method, postData }, options) => { + const opts = { + indent: ' ', + ...options, + }; + + const { push, join } = new CodeBuilder({ indent: opts.indent }); + + push('HttpRequest request = HttpRequest.newBuilder()'); + push(`.uri(URI.create("${fullUrl}"))`, 2); + + Object.keys(allHeaders).forEach(key => { + push(`.header("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, 2); + }); + + if (postData.text) { + push( + `.method("${method.toUpperCase()}", HttpRequest.BodyPublishers.ofString(${JSON.stringify(postData.text)}))`, + 2, + ); + } else { + push(`.method("${method.toUpperCase()}", HttpRequest.BodyPublishers.noBody())`, 2); + } + + push('.build();', 2); + + push( + 'HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());', + ); + push('System.out.println(response.body());'); + + return join(); + }, +}; diff --git a/src/targets/java/nethttp/fixtures/application-form-encoded.java b/src/targets/java/nethttp/fixtures/application-form-encoded.java new file mode 100644 index 000000000..8148d61b4 --- /dev/null +++ b/src/targets/java/nethttp/fixtures/application-form-encoded.java @@ -0,0 +1,7 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/anything")) + .header("content-type", "application/x-www-form-urlencoded") + .method("POST", HttpRequest.BodyPublishers.ofString("foo=bar&hello=world")) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/application-json.java b/src/targets/java/nethttp/fixtures/application-json.java new file mode 100644 index 000000000..972cc4f4f --- /dev/null +++ b/src/targets/java/nethttp/fixtures/application-json.java @@ -0,0 +1,7 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/anything")) + .header("content-type", "application/json") + .method("POST", HttpRequest.BodyPublishers.ofString("{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":[]}],\"boolean\":false}")) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/cookies.java b/src/targets/java/nethttp/fixtures/cookies.java new file mode 100644 index 000000000..4fcfe4b05 --- /dev/null +++ b/src/targets/java/nethttp/fixtures/cookies.java @@ -0,0 +1,7 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/cookies")) + .header("cookie", "foo=bar; bar=baz") + .method("GET", HttpRequest.BodyPublishers.noBody()) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/custom-method.java b/src/targets/java/nethttp/fixtures/custom-method.java new file mode 100644 index 000000000..11fb6c361 --- /dev/null +++ b/src/targets/java/nethttp/fixtures/custom-method.java @@ -0,0 +1,6 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/anything")) + .method("PROPFIND", HttpRequest.BodyPublishers.noBody()) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/full.java b/src/targets/java/nethttp/fixtures/full.java new file mode 100644 index 000000000..9c497962e --- /dev/null +++ b/src/targets/java/nethttp/fixtures/full.java @@ -0,0 +1,9 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value")) + .header("cookie", "foo=bar; bar=baz") + .header("accept", "application/json") + .header("content-type", "application/x-www-form-urlencoded") + .method("POST", HttpRequest.BodyPublishers.ofString("foo=bar")) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/headers.java b/src/targets/java/nethttp/fixtures/headers.java new file mode 100644 index 000000000..cbe2e7807 --- /dev/null +++ b/src/targets/java/nethttp/fixtures/headers.java @@ -0,0 +1,10 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/headers")) + .header("accept", "application/json") + .header("x-foo", "Bar") + .header("x-bar", "Foo") + .header("quoted-value", "\"quoted\" 'string'") + .method("GET", HttpRequest.BodyPublishers.noBody()) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/http-insecure.java b/src/targets/java/nethttp/fixtures/http-insecure.java new file mode 100644 index 000000000..83c247f65 --- /dev/null +++ b/src/targets/java/nethttp/fixtures/http-insecure.java @@ -0,0 +1,6 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("http://httpbin.org/anything")) + .method("GET", HttpRequest.BodyPublishers.noBody()) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/jsonObj-multiline.java b/src/targets/java/nethttp/fixtures/jsonObj-multiline.java new file mode 100644 index 000000000..d4067bb71 --- /dev/null +++ b/src/targets/java/nethttp/fixtures/jsonObj-multiline.java @@ -0,0 +1,7 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/anything")) + .header("content-type", "application/json") + .method("POST", HttpRequest.BodyPublishers.ofString("{\n \"foo\": \"bar\"\n}")) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/jsonObj-null-value.java b/src/targets/java/nethttp/fixtures/jsonObj-null-value.java new file mode 100644 index 000000000..627fb8e52 --- /dev/null +++ b/src/targets/java/nethttp/fixtures/jsonObj-null-value.java @@ -0,0 +1,7 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/anything")) + .header("content-type", "application/json") + .method("POST", HttpRequest.BodyPublishers.ofString("{\"foo\":null}")) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/multipart-data.java b/src/targets/java/nethttp/fixtures/multipart-data.java new file mode 100644 index 000000000..c77af1c99 --- /dev/null +++ b/src/targets/java/nethttp/fixtures/multipart-data.java @@ -0,0 +1,7 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/anything")) + .header("content-type", "multipart/form-data; boundary=---011000010111000001101001") + .method("POST", HttpRequest.BodyPublishers.ofString("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"bar\"\r\n\r\nBonjour le monde\r\n-----011000010111000001101001--")) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/multipart-file.java b/src/targets/java/nethttp/fixtures/multipart-file.java new file mode 100644 index 000000000..c225700fb --- /dev/null +++ b/src/targets/java/nethttp/fixtures/multipart-file.java @@ -0,0 +1,7 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/anything")) + .header("content-type", "multipart/form-data; boundary=---011000010111000001101001") + .method("POST", HttpRequest.BodyPublishers.ofString("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--")) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/multipart-form-data-no-params.java b/src/targets/java/nethttp/fixtures/multipart-form-data-no-params.java new file mode 100644 index 000000000..a1fc81a1d --- /dev/null +++ b/src/targets/java/nethttp/fixtures/multipart-form-data-no-params.java @@ -0,0 +1,7 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/anything")) + .header("Content-Type", "multipart/form-data") + .method("POST", HttpRequest.BodyPublishers.noBody()) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/multipart-form-data.java b/src/targets/java/nethttp/fixtures/multipart-form-data.java new file mode 100644 index 000000000..6362ce4e8 --- /dev/null +++ b/src/targets/java/nethttp/fixtures/multipart-form-data.java @@ -0,0 +1,7 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/anything")) + .header("Content-Type", "multipart/form-data; boundary=---011000010111000001101001") + .method("POST", HttpRequest.BodyPublishers.ofString("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--")) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/nested.java b/src/targets/java/nethttp/fixtures/nested.java new file mode 100644 index 000000000..fcf0c9a79 --- /dev/null +++ b/src/targets/java/nethttp/fixtures/nested.java @@ -0,0 +1,6 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value")) + .method("GET", HttpRequest.BodyPublishers.noBody()) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/postdata-malformed.java b/src/targets/java/nethttp/fixtures/postdata-malformed.java new file mode 100644 index 000000000..ad7a25696 --- /dev/null +++ b/src/targets/java/nethttp/fixtures/postdata-malformed.java @@ -0,0 +1,7 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/anything")) + .header("content-type", "application/json") + .method("POST", HttpRequest.BodyPublishers.noBody()) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/query-encoded.java b/src/targets/java/nethttp/fixtures/query-encoded.java new file mode 100644 index 000000000..4c352f469 --- /dev/null +++ b/src/targets/java/nethttp/fixtures/query-encoded.java @@ -0,0 +1,6 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00")) + .method("GET", HttpRequest.BodyPublishers.noBody()) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/query.java b/src/targets/java/nethttp/fixtures/query.java new file mode 100644 index 000000000..39b6a94a7 --- /dev/null +++ b/src/targets/java/nethttp/fixtures/query.java @@ -0,0 +1,6 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value")) + .method("GET", HttpRequest.BodyPublishers.noBody()) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/short.java b/src/targets/java/nethttp/fixtures/short.java new file mode 100644 index 000000000..168ef7ae8 --- /dev/null +++ b/src/targets/java/nethttp/fixtures/short.java @@ -0,0 +1,6 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/anything")) + .method("GET", HttpRequest.BodyPublishers.noBody()) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/nethttp/fixtures/text-plain.java b/src/targets/java/nethttp/fixtures/text-plain.java new file mode 100644 index 000000000..66e5eb819 --- /dev/null +++ b/src/targets/java/nethttp/fixtures/text-plain.java @@ -0,0 +1,7 @@ +HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create("https://httpbin.org/anything")) + .header("content-type", "text/plain") + .method("POST", HttpRequest.BodyPublishers.ofString("Hello World")) + .build(); +HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); +System.out.println(response.body()); \ No newline at end of file diff --git a/src/targets/java/okhttp.js b/src/targets/java/okhttp.js deleted file mode 100644 index 829d76a4b..000000000 --- a/src/targets/java/okhttp.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * @description - * HTTP code snippet generator for Java using OkHttp. - * - * @author - * @shashiranjan84 - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ' - }, options) - - var code = new CodeBuilder(opts.indent) - - var methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD'] - - var methodsWithBody = ['POST', 'PUT', 'DELETE', 'PATCH'] - - code.push('OkHttpClient client = new OkHttpClient();') - .blank() - - if (source.postData.text) { - if (source.postData.boundary) { - code.push('MediaType mediaType = MediaType.parse("%s; boundary=%s");', source.postData.mimeType, source.postData.boundary) - } else { - code.push('MediaType mediaType = MediaType.parse("%s");', source.postData.mimeType) - } - code.push('RequestBody body = RequestBody.create(mediaType, %s);', JSON.stringify(source.postData.text)) - } - - code.push('Request request = new Request.Builder()') - code.push(1, '.url("%s")', source.fullUrl) - if (methods.indexOf(source.method.toUpperCase()) === -1) { - if (source.postData.text) { - code.push(1, '.method("%s", body)', source.method.toUpperCase()) - } else { - code.push(1, '.method("%s", null)', source.method.toUpperCase()) - } - } else if (methodsWithBody.indexOf(source.method.toUpperCase()) >= 0) { - if (source.postData.text) { - code.push(1, '.%s(body)', source.method.toLowerCase()) - } else { - code.push(1, '.%s(null)', source.method.toLowerCase()) - } - } else { - code.push(1, '.%s()', source.method.toLowerCase()) - } - - // Add headers, including the cookies - var headers = Object.keys(source.allHeaders) - - // construct headers - if (headers.length) { - headers.forEach(function (key) { - code.push(1, '.addHeader("%s", "%s")', key, source.allHeaders[key]) - }) - } - - code.push(1, '.build();') - .blank() - .push('Response response = client.newCall(request).execute();') - - return code.join() -} - -module.exports.info = { - key: 'okhttp', - title: 'OkHttp', - link: 'http://square.github.io/okhttp/', - description: 'An HTTP Request Client Library' -} diff --git a/src/targets/java/okhttp/client.ts b/src/targets/java/okhttp/client.ts new file mode 100644 index 000000000..5bb5a3452 --- /dev/null +++ b/src/targets/java/okhttp/client.ts @@ -0,0 +1,74 @@ +/** + * @description + * HTTP code snippet generator for Java using OkHttp. + * + * @author + * @shashiranjan84 + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { escapeForDoubleQuotes } from '../../../helpers/escape.js'; + +export const okhttp: Client = { + info: { + key: 'okhttp', + title: 'OkHttp', + link: 'http://square.github.io/okhttp/', + description: 'An HTTP Request Client Library', + extname: '.java', + }, + convert: ({ postData, method, fullUrl, allHeaders }, options) => { + const opts = { + indent: ' ', + ...options, + }; + const { push, blank, join } = new CodeBuilder({ indent: opts.indent }); + + const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD']; + const methodsWithBody = ['POST', 'PUT', 'DELETE', 'PATCH']; + + push('OkHttpClient client = new OkHttpClient();'); + blank(); + + if (postData.text) { + if (postData.boundary) { + push(`MediaType mediaType = MediaType.parse("${postData.mimeType}; boundary=${postData.boundary}");`); + } else { + push(`MediaType mediaType = MediaType.parse("${postData.mimeType}");`); + } + push(`RequestBody body = RequestBody.create(mediaType, ${JSON.stringify(postData.text)});`); + } + + push('Request request = new Request.Builder()'); + push(`.url("${fullUrl}")`, 1); + if (!methods.includes(method.toUpperCase())) { + if (postData.text) { + push(`.method("${method.toUpperCase()}", body)`, 1); + } else { + push(`.method("${method.toUpperCase()}", null)`, 1); + } + } else if (methodsWithBody.includes(method.toUpperCase())) { + if (postData.text) { + push(`.${method.toLowerCase()}(body)`, 1); + } else { + push(`.${method.toLowerCase()}(null)`, 1); + } + } else { + push(`.${method.toLowerCase()}()`, 1); + } + + // Add headers, including the cookies + Object.keys(allHeaders).forEach(key => { + push(`.addHeader("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, 1); + }); + + push('.build();', 1); + blank(); + push('Response response = client.newCall(request).execute();'); + + return join(); + }, +}; diff --git a/src/targets/java/okhttp/fixtures/application-form-encoded.java b/src/targets/java/okhttp/fixtures/application-form-encoded.java new file mode 100644 index 000000000..989ebaa22 --- /dev/null +++ b/src/targets/java/okhttp/fixtures/application-form-encoded.java @@ -0,0 +1,11 @@ +OkHttpClient client = new OkHttpClient(); + +MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); +RequestBody body = RequestBody.create(mediaType, "foo=bar&hello=world"); +Request request = new Request.Builder() + .url("https://httpbin.org/anything") + .post(body) + .addHeader("content-type", "application/x-www-form-urlencoded") + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/application-json.java b/src/targets/java/okhttp/fixtures/application-json.java new file mode 100644 index 000000000..78c5cd5ce --- /dev/null +++ b/src/targets/java/okhttp/fixtures/application-json.java @@ -0,0 +1,11 @@ +OkHttpClient client = new OkHttpClient(); + +MediaType mediaType = MediaType.parse("application/json"); +RequestBody body = RequestBody.create(mediaType, "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":[]}],\"boolean\":false}"); +Request request = new Request.Builder() + .url("https://httpbin.org/anything") + .post(body) + .addHeader("content-type", "application/json") + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/cookies.java b/src/targets/java/okhttp/fixtures/cookies.java new file mode 100644 index 000000000..e5b9597bc --- /dev/null +++ b/src/targets/java/okhttp/fixtures/cookies.java @@ -0,0 +1,9 @@ +OkHttpClient client = new OkHttpClient(); + +Request request = new Request.Builder() + .url("https://httpbin.org/cookies") + .get() + .addHeader("cookie", "foo=bar; bar=baz") + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/custom-method.java b/src/targets/java/okhttp/fixtures/custom-method.java new file mode 100644 index 000000000..9f041bac1 --- /dev/null +++ b/src/targets/java/okhttp/fixtures/custom-method.java @@ -0,0 +1,8 @@ +OkHttpClient client = new OkHttpClient(); + +Request request = new Request.Builder() + .url("https://httpbin.org/anything") + .method("PROPFIND", null) + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/full.java b/src/targets/java/okhttp/fixtures/full.java new file mode 100644 index 000000000..a6de5854b --- /dev/null +++ b/src/targets/java/okhttp/fixtures/full.java @@ -0,0 +1,13 @@ +OkHttpClient client = new OkHttpClient(); + +MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); +RequestBody body = RequestBody.create(mediaType, "foo=bar"); +Request request = new Request.Builder() + .url("https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value") + .post(body) + .addHeader("cookie", "foo=bar; bar=baz") + .addHeader("accept", "application/json") + .addHeader("content-type", "application/x-www-form-urlencoded") + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/headers.java b/src/targets/java/okhttp/fixtures/headers.java new file mode 100644 index 000000000..25f5435ed --- /dev/null +++ b/src/targets/java/okhttp/fixtures/headers.java @@ -0,0 +1,12 @@ +OkHttpClient client = new OkHttpClient(); + +Request request = new Request.Builder() + .url("https://httpbin.org/headers") + .get() + .addHeader("accept", "application/json") + .addHeader("x-foo", "Bar") + .addHeader("x-bar", "Foo") + .addHeader("quoted-value", "\"quoted\" 'string'") + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/http-insecure.java b/src/targets/java/okhttp/fixtures/http-insecure.java new file mode 100644 index 000000000..090854641 --- /dev/null +++ b/src/targets/java/okhttp/fixtures/http-insecure.java @@ -0,0 +1,8 @@ +OkHttpClient client = new OkHttpClient(); + +Request request = new Request.Builder() + .url("http://httpbin.org/anything") + .get() + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/jsonObj-multiline.java b/src/targets/java/okhttp/fixtures/jsonObj-multiline.java new file mode 100644 index 000000000..647db6a54 --- /dev/null +++ b/src/targets/java/okhttp/fixtures/jsonObj-multiline.java @@ -0,0 +1,11 @@ +OkHttpClient client = new OkHttpClient(); + +MediaType mediaType = MediaType.parse("application/json"); +RequestBody body = RequestBody.create(mediaType, "{\n \"foo\": \"bar\"\n}"); +Request request = new Request.Builder() + .url("https://httpbin.org/anything") + .post(body) + .addHeader("content-type", "application/json") + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/jsonObj-null-value.java b/src/targets/java/okhttp/fixtures/jsonObj-null-value.java new file mode 100644 index 000000000..1c57f4392 --- /dev/null +++ b/src/targets/java/okhttp/fixtures/jsonObj-null-value.java @@ -0,0 +1,11 @@ +OkHttpClient client = new OkHttpClient(); + +MediaType mediaType = MediaType.parse("application/json"); +RequestBody body = RequestBody.create(mediaType, "{\"foo\":null}"); +Request request = new Request.Builder() + .url("https://httpbin.org/anything") + .post(body) + .addHeader("content-type", "application/json") + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/multipart-data.java b/src/targets/java/okhttp/fixtures/multipart-data.java new file mode 100644 index 000000000..45ee7bb65 --- /dev/null +++ b/src/targets/java/okhttp/fixtures/multipart-data.java @@ -0,0 +1,11 @@ +OkHttpClient client = new OkHttpClient(); + +MediaType mediaType = MediaType.parse("multipart/form-data; boundary=---011000010111000001101001"); +RequestBody body = RequestBody.create(mediaType, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"bar\"\r\n\r\nBonjour le monde\r\n-----011000010111000001101001--"); +Request request = new Request.Builder() + .url("https://httpbin.org/anything") + .post(body) + .addHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001") + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/multipart-file.java b/src/targets/java/okhttp/fixtures/multipart-file.java new file mode 100644 index 000000000..713ba109d --- /dev/null +++ b/src/targets/java/okhttp/fixtures/multipart-file.java @@ -0,0 +1,11 @@ +OkHttpClient client = new OkHttpClient(); + +MediaType mediaType = MediaType.parse("multipart/form-data; boundary=---011000010111000001101001"); +RequestBody body = RequestBody.create(mediaType, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--"); +Request request = new Request.Builder() + .url("https://httpbin.org/anything") + .post(body) + .addHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001") + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/multipart-form-data-no-params.java b/src/targets/java/okhttp/fixtures/multipart-form-data-no-params.java new file mode 100644 index 000000000..9b948df87 --- /dev/null +++ b/src/targets/java/okhttp/fixtures/multipart-form-data-no-params.java @@ -0,0 +1,9 @@ +OkHttpClient client = new OkHttpClient(); + +Request request = new Request.Builder() + .url("https://httpbin.org/anything") + .post(null) + .addHeader("Content-Type", "multipart/form-data") + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/multipart-form-data.java b/src/targets/java/okhttp/fixtures/multipart-form-data.java new file mode 100644 index 000000000..cafbe51ef --- /dev/null +++ b/src/targets/java/okhttp/fixtures/multipart-form-data.java @@ -0,0 +1,11 @@ +OkHttpClient client = new OkHttpClient(); + +MediaType mediaType = MediaType.parse("multipart/form-data; boundary=---011000010111000001101001"); +RequestBody body = RequestBody.create(mediaType, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--"); +Request request = new Request.Builder() + .url("https://httpbin.org/anything") + .post(body) + .addHeader("Content-Type", "multipart/form-data; boundary=---011000010111000001101001") + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/nested.java b/src/targets/java/okhttp/fixtures/nested.java new file mode 100644 index 000000000..bac1dba92 --- /dev/null +++ b/src/targets/java/okhttp/fixtures/nested.java @@ -0,0 +1,8 @@ +OkHttpClient client = new OkHttpClient(); + +Request request = new Request.Builder() + .url("https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value") + .get() + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/postdata-malformed.java b/src/targets/java/okhttp/fixtures/postdata-malformed.java new file mode 100644 index 000000000..6a80f2f9d --- /dev/null +++ b/src/targets/java/okhttp/fixtures/postdata-malformed.java @@ -0,0 +1,9 @@ +OkHttpClient client = new OkHttpClient(); + +Request request = new Request.Builder() + .url("https://httpbin.org/anything") + .post(null) + .addHeader("content-type", "application/json") + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/query-encoded.java b/src/targets/java/okhttp/fixtures/query-encoded.java new file mode 100644 index 000000000..20bc833c5 --- /dev/null +++ b/src/targets/java/okhttp/fixtures/query-encoded.java @@ -0,0 +1,8 @@ +OkHttpClient client = new OkHttpClient(); + +Request request = new Request.Builder() + .url("https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00") + .get() + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/query.java b/src/targets/java/okhttp/fixtures/query.java new file mode 100644 index 000000000..24a52c866 --- /dev/null +++ b/src/targets/java/okhttp/fixtures/query.java @@ -0,0 +1,8 @@ +OkHttpClient client = new OkHttpClient(); + +Request request = new Request.Builder() + .url("https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value") + .get() + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/short.java b/src/targets/java/okhttp/fixtures/short.java new file mode 100644 index 000000000..cc8ee13fc --- /dev/null +++ b/src/targets/java/okhttp/fixtures/short.java @@ -0,0 +1,8 @@ +OkHttpClient client = new OkHttpClient(); + +Request request = new Request.Builder() + .url("https://httpbin.org/anything") + .get() + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/okhttp/fixtures/text-plain.java b/src/targets/java/okhttp/fixtures/text-plain.java new file mode 100644 index 000000000..a4acfcede --- /dev/null +++ b/src/targets/java/okhttp/fixtures/text-plain.java @@ -0,0 +1,11 @@ +OkHttpClient client = new OkHttpClient(); + +MediaType mediaType = MediaType.parse("text/plain"); +RequestBody body = RequestBody.create(mediaType, "Hello World"); +Request request = new Request.Builder() + .url("https://httpbin.org/anything") + .post(body) + .addHeader("content-type", "text/plain") + .build(); + +Response response = client.newCall(request).execute(); \ No newline at end of file diff --git a/src/targets/java/target.ts b/src/targets/java/target.ts new file mode 100644 index 000000000..c986c3a18 --- /dev/null +++ b/src/targets/java/target.ts @@ -0,0 +1,21 @@ +import type { Target } from '../index.js'; + +import { asynchttp } from './asynchttp/client.js'; +import { nethttp } from './nethttp/client.js'; +import { okhttp } from './okhttp/client.js'; +import { unirest } from './unirest/client.js'; + +export const java: Target = { + info: { + key: 'java', + title: 'Java', + default: 'unirest', + }, + + clientsById: { + asynchttp, + nethttp, + okhttp, + unirest, + }, +}; diff --git a/src/targets/java/unirest.js b/src/targets/java/unirest.js deleted file mode 100644 index 4d686520d..000000000 --- a/src/targets/java/unirest.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * @description - * HTTP code snippet generator for Java using Unirest. - * - * @author - * @shashiranjan84 - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ' - }, options) - - var code = new CodeBuilder(opts.indent) - - var methods = [ 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS' ] - - if (methods.indexOf(source.method.toUpperCase()) === -1) { - code.push('HttpResponse response = Unirest.customMethod("%s","%s")', source.method.toUpperCase(), source.fullUrl) - } else { - code.push('HttpResponse response = Unirest.%s("%s")', source.method.toLowerCase(), source.fullUrl) - } - - // Add headers, including the cookies - var headers = Object.keys(source.allHeaders) - - // construct headers - if (headers.length) { - headers.forEach(function (key) { - code.push(1, '.header("%s", "%s")', key, source.allHeaders[key]) - }) - } - - if (source.postData.text) { - code.push(1, '.body(%s)', JSON.stringify(source.postData.text)) - } - - code.push(1, '.asString();') - - return code.join() -} - -module.exports.info = { - key: 'unirest', - title: 'Unirest', - link: 'http://unirest.io/java.html', - description: 'Lightweight HTTP Request Client Library' -} diff --git a/src/targets/java/unirest/client.ts b/src/targets/java/unirest/client.ts new file mode 100644 index 000000000..55226246b --- /dev/null +++ b/src/targets/java/unirest/client.ts @@ -0,0 +1,52 @@ +/** + * @description + * HTTP code snippet generator for Java using Unirest. + * + * @author + * @shashiranjan84 + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { escapeForDoubleQuotes } from '../../../helpers/escape.js'; + +export const unirest: Client = { + info: { + key: 'unirest', + title: 'Unirest', + link: 'http://unirest.io/java.html', + description: 'Lightweight HTTP Request Client Library', + extname: '.java', + }, + convert: ({ method, allHeaders, postData, fullUrl }, options) => { + const opts = { + indent: ' ', + ...options, + }; + + const { join, push } = new CodeBuilder({ indent: opts.indent }); + + const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']; + + if (!methods.includes(method.toUpperCase())) { + push(`HttpResponse response = Unirest.customMethod("${method.toUpperCase()}","${fullUrl}")`); + } else { + push(`HttpResponse response = Unirest.${method.toLowerCase()}("${fullUrl}")`); + } + + // Add headers, including the cookies + Object.keys(allHeaders).forEach(key => { + push(`.header("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, 1); + }); + + if (postData.text) { + push(`.body(${JSON.stringify(postData.text)})`, 1); + } + + push('.asString();', 1); + + return join(); + }, +}; diff --git a/src/targets/java/unirest/fixtures/application-form-encoded.java b/src/targets/java/unirest/fixtures/application-form-encoded.java new file mode 100644 index 000000000..3c00bfee1 --- /dev/null +++ b/src/targets/java/unirest/fixtures/application-form-encoded.java @@ -0,0 +1,4 @@ +HttpResponse response = Unirest.post("https://httpbin.org/anything") + .header("content-type", "application/x-www-form-urlencoded") + .body("foo=bar&hello=world") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/application-json.java b/src/targets/java/unirest/fixtures/application-json.java new file mode 100644 index 000000000..447f2b759 --- /dev/null +++ b/src/targets/java/unirest/fixtures/application-json.java @@ -0,0 +1,4 @@ +HttpResponse response = Unirest.post("https://httpbin.org/anything") + .header("content-type", "application/json") + .body("{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":[]}],\"boolean\":false}") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/cookies.java b/src/targets/java/unirest/fixtures/cookies.java new file mode 100644 index 000000000..d58c3abf6 --- /dev/null +++ b/src/targets/java/unirest/fixtures/cookies.java @@ -0,0 +1,3 @@ +HttpResponse response = Unirest.get("https://httpbin.org/cookies") + .header("cookie", "foo=bar; bar=baz") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/custom-method.java b/src/targets/java/unirest/fixtures/custom-method.java new file mode 100644 index 000000000..e76d75347 --- /dev/null +++ b/src/targets/java/unirest/fixtures/custom-method.java @@ -0,0 +1,2 @@ +HttpResponse response = Unirest.customMethod("PROPFIND","https://httpbin.org/anything") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/full.java b/src/targets/java/unirest/fixtures/full.java new file mode 100644 index 000000000..676718cd1 --- /dev/null +++ b/src/targets/java/unirest/fixtures/full.java @@ -0,0 +1,6 @@ +HttpResponse response = Unirest.post("https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value") + .header("cookie", "foo=bar; bar=baz") + .header("accept", "application/json") + .header("content-type", "application/x-www-form-urlencoded") + .body("foo=bar") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/headers.java b/src/targets/java/unirest/fixtures/headers.java new file mode 100644 index 000000000..82c347a3f --- /dev/null +++ b/src/targets/java/unirest/fixtures/headers.java @@ -0,0 +1,6 @@ +HttpResponse response = Unirest.get("https://httpbin.org/headers") + .header("accept", "application/json") + .header("x-foo", "Bar") + .header("x-bar", "Foo") + .header("quoted-value", "\"quoted\" 'string'") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/http-insecure.java b/src/targets/java/unirest/fixtures/http-insecure.java new file mode 100644 index 000000000..04aa54b8a --- /dev/null +++ b/src/targets/java/unirest/fixtures/http-insecure.java @@ -0,0 +1,2 @@ +HttpResponse response = Unirest.get("http://httpbin.org/anything") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/jsonObj-multiline.java b/src/targets/java/unirest/fixtures/jsonObj-multiline.java new file mode 100644 index 000000000..be5f54530 --- /dev/null +++ b/src/targets/java/unirest/fixtures/jsonObj-multiline.java @@ -0,0 +1,4 @@ +HttpResponse response = Unirest.post("https://httpbin.org/anything") + .header("content-type", "application/json") + .body("{\n \"foo\": \"bar\"\n}") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/jsonObj-null-value.java b/src/targets/java/unirest/fixtures/jsonObj-null-value.java new file mode 100644 index 000000000..11e819a13 --- /dev/null +++ b/src/targets/java/unirest/fixtures/jsonObj-null-value.java @@ -0,0 +1,4 @@ +HttpResponse response = Unirest.post("https://httpbin.org/anything") + .header("content-type", "application/json") + .body("{\"foo\":null}") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/multipart-data.java b/src/targets/java/unirest/fixtures/multipart-data.java new file mode 100644 index 000000000..0d517412e --- /dev/null +++ b/src/targets/java/unirest/fixtures/multipart-data.java @@ -0,0 +1,4 @@ +HttpResponse response = Unirest.post("https://httpbin.org/anything") + .header("content-type", "multipart/form-data; boundary=---011000010111000001101001") + .body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"bar\"\r\n\r\nBonjour le monde\r\n-----011000010111000001101001--") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/multipart-file.java b/src/targets/java/unirest/fixtures/multipart-file.java new file mode 100644 index 000000000..285119aff --- /dev/null +++ b/src/targets/java/unirest/fixtures/multipart-file.java @@ -0,0 +1,4 @@ +HttpResponse response = Unirest.post("https://httpbin.org/anything") + .header("content-type", "multipart/form-data; boundary=---011000010111000001101001") + .body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/multipart-form-data-no-params.java b/src/targets/java/unirest/fixtures/multipart-form-data-no-params.java new file mode 100644 index 000000000..a1ede1be0 --- /dev/null +++ b/src/targets/java/unirest/fixtures/multipart-form-data-no-params.java @@ -0,0 +1,3 @@ +HttpResponse response = Unirest.post("https://httpbin.org/anything") + .header("Content-Type", "multipart/form-data") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/multipart-form-data.java b/src/targets/java/unirest/fixtures/multipart-form-data.java new file mode 100644 index 000000000..8cbc64d8d --- /dev/null +++ b/src/targets/java/unirest/fixtures/multipart-form-data.java @@ -0,0 +1,4 @@ +HttpResponse response = Unirest.post("https://httpbin.org/anything") + .header("Content-Type", "multipart/form-data; boundary=---011000010111000001101001") + .body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/nested.java b/src/targets/java/unirest/fixtures/nested.java new file mode 100644 index 000000000..fd92d39c4 --- /dev/null +++ b/src/targets/java/unirest/fixtures/nested.java @@ -0,0 +1,2 @@ +HttpResponse response = Unirest.get("https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/postdata-malformed.java b/src/targets/java/unirest/fixtures/postdata-malformed.java new file mode 100644 index 000000000..ad320039a --- /dev/null +++ b/src/targets/java/unirest/fixtures/postdata-malformed.java @@ -0,0 +1,3 @@ +HttpResponse response = Unirest.post("https://httpbin.org/anything") + .header("content-type", "application/json") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/query-encoded.java b/src/targets/java/unirest/fixtures/query-encoded.java new file mode 100644 index 000000000..d965c7275 --- /dev/null +++ b/src/targets/java/unirest/fixtures/query-encoded.java @@ -0,0 +1,2 @@ +HttpResponse response = Unirest.get("https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/query.java b/src/targets/java/unirest/fixtures/query.java new file mode 100644 index 000000000..09bbe7c13 --- /dev/null +++ b/src/targets/java/unirest/fixtures/query.java @@ -0,0 +1,2 @@ +HttpResponse response = Unirest.get("https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/short.java b/src/targets/java/unirest/fixtures/short.java new file mode 100644 index 000000000..9f516f36a --- /dev/null +++ b/src/targets/java/unirest/fixtures/short.java @@ -0,0 +1,2 @@ +HttpResponse response = Unirest.get("https://httpbin.org/anything") + .asString(); \ No newline at end of file diff --git a/src/targets/java/unirest/fixtures/text-plain.java b/src/targets/java/unirest/fixtures/text-plain.java new file mode 100644 index 000000000..67d738f10 --- /dev/null +++ b/src/targets/java/unirest/fixtures/text-plain.java @@ -0,0 +1,4 @@ +HttpResponse response = Unirest.post("https://httpbin.org/anything") + .header("content-type", "text/plain") + .body("Hello World") + .asString(); \ No newline at end of file diff --git a/src/targets/javascript/axios/client.ts b/src/targets/javascript/axios/client.ts new file mode 100644 index 000000000..dc2f0803d --- /dev/null +++ b/src/targets/javascript/axios/client.ts @@ -0,0 +1,107 @@ +/** + * @description + * HTTP code snippet generator for Javascript & Node.js using Axios. + * + * @author + * @rohit-gohri + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import stringifyObject from 'stringify-object'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; + +export const axios: Client = { + info: { + key: 'axios', + title: 'Axios', + link: 'https://github.com/axios/axios', + description: 'Promise based HTTP client for the browser and node.js', + extname: '.js', + installation: () => 'npm install axios --save', + }, + convert: ({ allHeaders, method, url, queryObj, postData }, options) => { + const opts = { + indent: ' ', + ...options, + }; + + const { blank, push, join, addPostProcessor } = new CodeBuilder({ indent: opts.indent }); + + push("import axios from 'axios';"); + blank(); + + const requestOptions: Record = { + method, + url, + }; + + if (Object.keys(queryObj).length) { + requestOptions.params = queryObj; + } + + if (Object.keys(allHeaders).length) { + requestOptions.headers = allHeaders; + } + + switch (postData.mimeType) { + case 'application/x-www-form-urlencoded': + if (postData.params) { + push('const encodedParams = new URLSearchParams();'); + postData.params.forEach(param => { + push(`encodedParams.set('${param.name}', '${param.value}');`); + }); + + blank(); + + requestOptions.data = 'encodedParams,'; + addPostProcessor(code => code.replace(/'encodedParams,'/, 'encodedParams,')); + } + + break; + + case 'application/json': + if (postData.jsonObj) { + requestOptions.data = postData.jsonObj; + } + break; + + case 'multipart/form-data': + if (!postData.params) { + break; + } + + push('const form = new FormData();'); + + postData.params.forEach(param => { + push(`form.append('${param.name}', '${param.value || param.fileName || ''}');`); + }); + + blank(); + + requestOptions.data = '[form]'; + break; + + default: + if (postData.text) { + requestOptions.data = postData.text; + } + } + + const optionString = stringifyObject(requestOptions, { + indent: ' ', + inlineCharacterLimit: 80, + }).replace('"[form]"', 'form'); + push(`const options = ${optionString};`); + blank(); + + push('axios'); + push('.request(options)', 1); + push('.then(res => console.log(res.data))', 1); + push('.catch(err => console.error(err));', 1); + + return join(); + }, +}; diff --git a/src/targets/javascript/axios/fixtures/application-form-encoded.js b/src/targets/javascript/axios/fixtures/application-form-encoded.js new file mode 100644 index 000000000..1a83ea542 --- /dev/null +++ b/src/targets/javascript/axios/fixtures/application-form-encoded.js @@ -0,0 +1,17 @@ +import axios from 'axios'; + +const encodedParams = new URLSearchParams(); +encodedParams.set('foo', 'bar'); +encodedParams.set('hello', 'world'); + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'content-type': 'application/x-www-form-urlencoded'}, + data: encodedParams, +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/application-json.js b/src/targets/javascript/axios/fixtures/application-json.js new file mode 100644 index 000000000..98903a65a --- /dev/null +++ b/src/targets/javascript/axios/fixtures/application-json.js @@ -0,0 +1,20 @@ +import axios from 'axios'; + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'content-type': 'application/json'}, + data: { + number: 1, + string: 'f"oo', + arr: [1, 2, 3], + nested: {a: 'b'}, + arr_mix: [1, 'a', {arr_mix_nested: []}], + boolean: false + } +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/cookies.js b/src/targets/javascript/axios/fixtures/cookies.js new file mode 100644 index 000000000..7e9cf7ae3 --- /dev/null +++ b/src/targets/javascript/axios/fixtures/cookies.js @@ -0,0 +1,12 @@ +import axios from 'axios'; + +const options = { + method: 'GET', + url: 'https://httpbin.org/cookies', + headers: {cookie: 'foo=bar; bar=baz'} +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/custom-method.js b/src/targets/javascript/axios/fixtures/custom-method.js new file mode 100644 index 000000000..4142f5977 --- /dev/null +++ b/src/targets/javascript/axios/fixtures/custom-method.js @@ -0,0 +1,8 @@ +import axios from 'axios'; + +const options = {method: 'PROPFIND', url: 'https://httpbin.org/anything'}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/full.js b/src/targets/javascript/axios/fixtures/full.js new file mode 100644 index 000000000..014bd7340 --- /dev/null +++ b/src/targets/javascript/axios/fixtures/full.js @@ -0,0 +1,21 @@ +import axios from 'axios'; + +const encodedParams = new URLSearchParams(); +encodedParams.set('foo', 'bar'); + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + params: {foo: ['bar', 'baz'], baz: 'abc', key: 'value'}, + headers: { + cookie: 'foo=bar; bar=baz', + accept: 'application/json', + 'content-type': 'application/x-www-form-urlencoded' + }, + data: encodedParams, +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/headers.js b/src/targets/javascript/axios/fixtures/headers.js new file mode 100644 index 000000000..8026a1ee9 --- /dev/null +++ b/src/targets/javascript/axios/fixtures/headers.js @@ -0,0 +1,17 @@ +import axios from 'axios'; + +const options = { + method: 'GET', + url: 'https://httpbin.org/headers', + headers: { + accept: 'application/json', + 'x-foo': 'Bar', + 'x-bar': 'Foo', + 'quoted-value': '"quoted" \'string\'' + } +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/http-insecure.js b/src/targets/javascript/axios/fixtures/http-insecure.js new file mode 100644 index 000000000..0512e2df7 --- /dev/null +++ b/src/targets/javascript/axios/fixtures/http-insecure.js @@ -0,0 +1,8 @@ +import axios from 'axios'; + +const options = {method: 'GET', url: 'http://httpbin.org/anything'}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/jsonObj-multiline.js b/src/targets/javascript/axios/fixtures/jsonObj-multiline.js new file mode 100644 index 000000000..7d41fbc52 --- /dev/null +++ b/src/targets/javascript/axios/fixtures/jsonObj-multiline.js @@ -0,0 +1,13 @@ +import axios from 'axios'; + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'content-type': 'application/json'}, + data: {foo: 'bar'} +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/jsonObj-null-value.js b/src/targets/javascript/axios/fixtures/jsonObj-null-value.js new file mode 100644 index 000000000..3731d644d --- /dev/null +++ b/src/targets/javascript/axios/fixtures/jsonObj-null-value.js @@ -0,0 +1,13 @@ +import axios from 'axios'; + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'content-type': 'application/json'}, + data: {foo: null} +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/multipart-data.js b/src/targets/javascript/axios/fixtures/multipart-data.js new file mode 100644 index 000000000..bb36ba381 --- /dev/null +++ b/src/targets/javascript/axios/fixtures/multipart-data.js @@ -0,0 +1,17 @@ +import axios from 'axios'; + +const form = new FormData(); +form.append('foo', 'Hello World'); +form.append('bar', 'Bonjour le monde'); + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'content-type': 'multipart/form-data; boundary=---011000010111000001101001'}, + data: '[form]' +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/multipart-file.js b/src/targets/javascript/axios/fixtures/multipart-file.js new file mode 100644 index 000000000..6579bbe8c --- /dev/null +++ b/src/targets/javascript/axios/fixtures/multipart-file.js @@ -0,0 +1,16 @@ +import axios from 'axios'; + +const form = new FormData(); +form.append('foo', 'src/fixtures/files/hello.txt'); + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'content-type': 'multipart/form-data; boundary=---011000010111000001101001'}, + data: '[form]' +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/multipart-form-data-no-params.js b/src/targets/javascript/axios/fixtures/multipart-form-data-no-params.js new file mode 100644 index 000000000..57e424c87 --- /dev/null +++ b/src/targets/javascript/axios/fixtures/multipart-form-data-no-params.js @@ -0,0 +1,12 @@ +import axios from 'axios'; + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'Content-Type': 'multipart/form-data'} +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/multipart-form-data.js b/src/targets/javascript/axios/fixtures/multipart-form-data.js new file mode 100644 index 000000000..ec40b9e54 --- /dev/null +++ b/src/targets/javascript/axios/fixtures/multipart-form-data.js @@ -0,0 +1,16 @@ +import axios from 'axios'; + +const form = new FormData(); +form.append('foo', 'bar'); + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'Content-Type': 'multipart/form-data; boundary=---011000010111000001101001'}, + data: '[form]' +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/nested.js b/src/targets/javascript/axios/fixtures/nested.js new file mode 100644 index 000000000..3fffb9755 --- /dev/null +++ b/src/targets/javascript/axios/fixtures/nested.js @@ -0,0 +1,12 @@ +import axios from 'axios'; + +const options = { + method: 'GET', + url: 'https://httpbin.org/anything', + params: {'foo[bar]': 'baz,zap', fiz: 'buz', key: 'value'} +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/postdata-malformed.js b/src/targets/javascript/axios/fixtures/postdata-malformed.js new file mode 100644 index 000000000..f40deb9ed --- /dev/null +++ b/src/targets/javascript/axios/fixtures/postdata-malformed.js @@ -0,0 +1,12 @@ +import axios from 'axios'; + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'content-type': 'application/json'} +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/query-encoded.js b/src/targets/javascript/axios/fixtures/query-encoded.js new file mode 100644 index 000000000..489c9927e --- /dev/null +++ b/src/targets/javascript/axios/fixtures/query-encoded.js @@ -0,0 +1,15 @@ +import axios from 'axios'; + +const options = { + method: 'GET', + url: 'https://httpbin.org/anything', + params: { + startTime: '2019-06-13T19%3A08%3A25.455Z', + endTime: '2015-09-15T14%3A00%3A12-04%3A00' + } +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/query.js b/src/targets/javascript/axios/fixtures/query.js new file mode 100644 index 000000000..39cca5992 --- /dev/null +++ b/src/targets/javascript/axios/fixtures/query.js @@ -0,0 +1,12 @@ +import axios from 'axios'; + +const options = { + method: 'GET', + url: 'https://httpbin.org/anything', + params: {foo: ['bar', 'baz'], baz: 'abc', key: 'value'} +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/short.js b/src/targets/javascript/axios/fixtures/short.js new file mode 100644 index 000000000..ba835ded4 --- /dev/null +++ b/src/targets/javascript/axios/fixtures/short.js @@ -0,0 +1,8 @@ +import axios from 'axios'; + +const options = {method: 'GET', url: 'https://httpbin.org/anything'}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/axios/fixtures/text-plain.js b/src/targets/javascript/axios/fixtures/text-plain.js new file mode 100644 index 000000000..dbe78d903 --- /dev/null +++ b/src/targets/javascript/axios/fixtures/text-plain.js @@ -0,0 +1,13 @@ +import axios from 'axios'; + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'content-type': 'text/plain'}, + data: 'Hello World' +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/client.ts b/src/targets/javascript/fetch/client.ts new file mode 100644 index 000000000..cf0d48307 --- /dev/null +++ b/src/targets/javascript/fetch/client.ts @@ -0,0 +1,130 @@ +/** + * @description + * HTTP code snippet generator for fetch + * + * @author + * @pmdroid + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import stringifyObject from 'stringify-object'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { getHeaderName } from '../../../helpers/headers.js'; + +interface FetchOptions { + credentials?: Record | null; +} + +export const fetch: Client = { + info: { + key: 'fetch', + title: 'fetch', + link: 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch', + description: 'Perform asynchronous HTTP requests with the Fetch API', + extname: '.js', + }, + convert: ({ method, allHeaders, postData, fullUrl }, inputOpts) => { + const opts = { + indent: ' ', + credentials: null, + ...inputOpts, + }; + + const { blank, join, push } = new CodeBuilder({ indent: opts.indent }); + + const options: Record = { + method, + }; + + if (Object.keys(allHeaders).length) { + options.headers = allHeaders; + } + + if (opts.credentials !== null) { + options.credentials = opts.credentials; + } + + switch (postData.mimeType) { + case 'application/x-www-form-urlencoded': + options.body = postData.paramsObj ? postData.paramsObj : postData.text; + break; + + case 'application/json': + if (postData.jsonObj) { + // Though `fetch` doesn't accept JSON objects in the `body` option we're going to + // stringify it when we add this into the snippet further down. + options.body = postData.jsonObj; + } + break; + + case 'multipart/form-data': { + if (!postData.params) { + break; + } + + // The FormData API automatically adds a `Content-Type` header for `multipart/form-data` content and if we add our own here data won't be correctly transmitted. + const contentTypeHeader = getHeaderName(allHeaders, 'content-type'); + if (contentTypeHeader) { + delete allHeaders[contentTypeHeader]; + } + + push('const form = new FormData();'); + + postData.params.forEach(param => { + push(`form.append('${param.name}', '${param.value || param.fileName || ''}');`); + }); + + blank(); + break; + } + + default: + if (postData.text) { + options.body = postData.text; + } + } + + // If we ultimately don't have any headers to send then we shouldn't add an empty object into the request options. + if (options.headers && !Object.keys(options.headers).length) { + delete options.headers; + } + + push( + `const options = ${stringifyObject(options, { + indent: opts.indent, + inlineCharacterLimit: 80, + + // The Fetch API body only accepts string parameters, but stringified JSON can be difficult + // to read, so we keep the object as a literal and use this transform function to wrap the + // literal in a `JSON.stringify` call. + transform: (object, property, originalResult) => { + if (property === 'body') { + if (postData.mimeType === 'application/x-www-form-urlencoded') { + return `new URLSearchParams(${originalResult})`; + } else if (postData.mimeType === 'application/json') { + return `JSON.stringify(${originalResult})`; + } + } + + return originalResult; + }, + })};`, + ); + blank(); + + if (postData.params && postData.mimeType === 'multipart/form-data') { + push('options.body = form;'); + blank(); + } + + push(`fetch('${fullUrl}', options)`); + push('.then(res => res.json())', 1); + push('.then(res => console.log(res))', 1); + push('.catch(err => console.error(err));', 1); + + return join(); + }, +}; diff --git a/src/targets/javascript/fetch/fixtures/application-form-encoded.js b/src/targets/javascript/fetch/fixtures/application-form-encoded.js new file mode 100644 index 000000000..4e0d61445 --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/application-form-encoded.js @@ -0,0 +1,10 @@ +const options = { + method: 'POST', + headers: {'content-type': 'application/x-www-form-urlencoded'}, + body: new URLSearchParams({foo: 'bar', hello: 'world'}) +}; + +fetch('https://httpbin.org/anything', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/application-json.js b/src/targets/javascript/fetch/fixtures/application-json.js new file mode 100644 index 000000000..49568ebfb --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/application-json.js @@ -0,0 +1,17 @@ +const options = { + method: 'POST', + headers: {'content-type': 'application/json'}, + body: JSON.stringify({ + number: 1, + string: 'f"oo', + arr: [1, 2, 3], + nested: {a: 'b'}, + arr_mix: [1, 'a', {arr_mix_nested: []}], + boolean: false + }) +}; + +fetch('https://httpbin.org/anything', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/cookies.js b/src/targets/javascript/fetch/fixtures/cookies.js new file mode 100644 index 000000000..ba1fb515c --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/cookies.js @@ -0,0 +1,6 @@ +const options = {method: 'GET', headers: {cookie: 'foo=bar; bar=baz'}}; + +fetch('https://httpbin.org/cookies', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/custom-method.js b/src/targets/javascript/fetch/fixtures/custom-method.js new file mode 100644 index 000000000..102f9b51e --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/custom-method.js @@ -0,0 +1,6 @@ +const options = {method: 'PROPFIND'}; + +fetch('https://httpbin.org/anything', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/full.js b/src/targets/javascript/fetch/fixtures/full.js new file mode 100644 index 000000000..b26902bb5 --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/full.js @@ -0,0 +1,14 @@ +const options = { + method: 'POST', + headers: { + cookie: 'foo=bar; bar=baz', + accept: 'application/json', + 'content-type': 'application/x-www-form-urlencoded' + }, + body: new URLSearchParams({foo: 'bar'}) +}; + +fetch('https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/headers.js b/src/targets/javascript/fetch/fixtures/headers.js new file mode 100644 index 000000000..3ca72a640 --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/headers.js @@ -0,0 +1,14 @@ +const options = { + method: 'GET', + headers: { + accept: 'application/json', + 'x-foo': 'Bar', + 'x-bar': 'Foo', + 'quoted-value': '"quoted" \'string\'' + } +}; + +fetch('https://httpbin.org/headers', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/http-insecure.js b/src/targets/javascript/fetch/fixtures/http-insecure.js new file mode 100644 index 000000000..60ada7617 --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/http-insecure.js @@ -0,0 +1,6 @@ +const options = {method: 'GET'}; + +fetch('http://httpbin.org/anything', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/jsonObj-multiline.js b/src/targets/javascript/fetch/fixtures/jsonObj-multiline.js new file mode 100644 index 000000000..fc681292a --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/jsonObj-multiline.js @@ -0,0 +1,10 @@ +const options = { + method: 'POST', + headers: {'content-type': 'application/json'}, + body: JSON.stringify({foo: 'bar'}) +}; + +fetch('https://httpbin.org/anything', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/jsonObj-null-value.js b/src/targets/javascript/fetch/fixtures/jsonObj-null-value.js new file mode 100644 index 000000000..305eed6b6 --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/jsonObj-null-value.js @@ -0,0 +1,10 @@ +const options = { + method: 'POST', + headers: {'content-type': 'application/json'}, + body: JSON.stringify({foo: null}) +}; + +fetch('https://httpbin.org/anything', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/multipart-data.js b/src/targets/javascript/fetch/fixtures/multipart-data.js new file mode 100644 index 000000000..ac8664bf9 --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/multipart-data.js @@ -0,0 +1,12 @@ +const form = new FormData(); +form.append('foo', 'Hello World'); +form.append('bar', 'Bonjour le monde'); + +const options = {method: 'POST'}; + +options.body = form; + +fetch('https://httpbin.org/anything', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/multipart-file.js b/src/targets/javascript/fetch/fixtures/multipart-file.js new file mode 100644 index 000000000..039019a1c --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/multipart-file.js @@ -0,0 +1,11 @@ +const form = new FormData(); +form.append('foo', 'src/fixtures/files/hello.txt'); + +const options = {method: 'POST'}; + +options.body = form; + +fetch('https://httpbin.org/anything', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/multipart-form-data-no-params.js b/src/targets/javascript/fetch/fixtures/multipart-form-data-no-params.js new file mode 100644 index 000000000..4b79e19a6 --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/multipart-form-data-no-params.js @@ -0,0 +1,6 @@ +const options = {method: 'POST', headers: {'Content-Type': 'multipart/form-data'}}; + +fetch('https://httpbin.org/anything', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/multipart-form-data.js b/src/targets/javascript/fetch/fixtures/multipart-form-data.js new file mode 100644 index 000000000..7a21714a4 --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/multipart-form-data.js @@ -0,0 +1,11 @@ +const form = new FormData(); +form.append('foo', 'bar'); + +const options = {method: 'POST'}; + +options.body = form; + +fetch('https://httpbin.org/anything', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/nested.js b/src/targets/javascript/fetch/fixtures/nested.js new file mode 100644 index 000000000..97d251384 --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/nested.js @@ -0,0 +1,6 @@ +const options = {method: 'GET'}; + +fetch('https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/postdata-malformed.js b/src/targets/javascript/fetch/fixtures/postdata-malformed.js new file mode 100644 index 000000000..94f81b0a4 --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/postdata-malformed.js @@ -0,0 +1,6 @@ +const options = {method: 'POST', headers: {'content-type': 'application/json'}}; + +fetch('https://httpbin.org/anything', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/query-encoded.js b/src/targets/javascript/fetch/fixtures/query-encoded.js new file mode 100644 index 000000000..14b44cf6c --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/query-encoded.js @@ -0,0 +1,6 @@ +const options = {method: 'GET'}; + +fetch('https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/query.js b/src/targets/javascript/fetch/fixtures/query.js new file mode 100644 index 000000000..22d68dcd3 --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/query.js @@ -0,0 +1,6 @@ +const options = {method: 'GET'}; + +fetch('https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/short.js b/src/targets/javascript/fetch/fixtures/short.js new file mode 100644 index 000000000..68ab8947d --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/short.js @@ -0,0 +1,6 @@ +const options = {method: 'GET'}; + +fetch('https://httpbin.org/anything', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/fetch/fixtures/text-plain.js b/src/targets/javascript/fetch/fixtures/text-plain.js new file mode 100644 index 000000000..5a83b05da --- /dev/null +++ b/src/targets/javascript/fetch/fixtures/text-plain.js @@ -0,0 +1,6 @@ +const options = {method: 'POST', headers: {'content-type': 'text/plain'}, body: 'Hello World'}; + +fetch('https://httpbin.org/anything', options) + .then(res => res.json()) + .then(res => console.log(res)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/javascript/index.js b/src/targets/javascript/index.js deleted file mode 100644 index ecc33c332..000000000 --- a/src/targets/javascript/index.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict' - -module.exports = { - info: { - key: 'javascript', - title: 'JavaScript', - extname: '.js', - default: 'xhr' - }, - - jquery: require('./jq'), - xhr: require('./xhr') -} diff --git a/src/targets/javascript/jq.js b/src/targets/javascript/jq.js deleted file mode 100644 index 4365ae588..000000000 --- a/src/targets/javascript/jq.js +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @description - * HTTP code snippet generator for native XMLHttpRequest - * - * @author - * @AhmadNassri - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ' - }, options) - - var code = new CodeBuilder(opts.indent) - - var settings = { - async: true, - crossDomain: true, - url: source.fullUrl, - method: source.method, - headers: source.allHeaders - } - - switch (source.postData.mimeType) { - case 'application/x-www-form-urlencoded': - settings.data = source.postData.paramsObj ? source.postData.paramsObj : source.postData.text - break - - case 'application/json': - settings.processData = false - settings.data = source.postData.text - break - - case 'multipart/form-data': - code.push('var form = new FormData();') - - source.postData.params.forEach(function (param) { - code.push('form.append(%s, %s);', JSON.stringify(param.name), JSON.stringify(param.value || param.fileName || '')) - }) - - settings.processData = false - settings.contentType = false - settings.mimeType = 'multipart/form-data' - settings.data = '[form]' - - // remove the contentType header - if (~settings.headers['content-type'].indexOf('boundary')) { - delete settings.headers['content-type'] - } - code.blank() - break - - default: - if (source.postData.text) { - settings.data = source.postData.text - } - } - - code.push('var settings = ' + JSON.stringify(settings, null, opts.indent).replace('"[form]"', 'form')) - .blank() - .push('$.ajax(settings).done(function (response) {') - .push(1, 'console.log(response);') - .push('});') - - return code.join() -} - -module.exports.info = { - key: 'jquery', - title: 'jQuery', - link: 'http://api.jquery.com/jquery.ajax/', - description: 'Perform an asynchronous HTTP (Ajax) requests with jQuery' -} diff --git a/src/targets/javascript/jquery/client.ts b/src/targets/javascript/jquery/client.ts new file mode 100644 index 000000000..dbd9d3e7d --- /dev/null +++ b/src/targets/javascript/jquery/client.ts @@ -0,0 +1,96 @@ +/** + * @description + * HTTP code snippet generator for native XMLHttpRequest + * + * @author + * @AhmadNassri + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import stringifyObject from 'stringify-object'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { getHeader, getHeaderName, hasHeader } from '../../../helpers/headers.js'; + +export const jquery: Client = { + info: { + key: 'jquery', + title: 'jQuery', + link: 'http://api.jquery.com/jquery.ajax/', + description: 'Perform an asynchronous HTTP (Ajax) requests with jQuery', + extname: '.js', + }, + convert: ({ fullUrl, method, allHeaders, postData }, options) => { + const opts = { + indent: ' ', + ...options, + }; + + const { blank, push, join } = new CodeBuilder({ indent: opts.indent }); + + const settings: Record = { + async: true, + crossDomain: true, + url: fullUrl, + method, + headers: allHeaders, + }; + + switch (postData.mimeType) { + case 'application/x-www-form-urlencoded': + settings.data = postData.paramsObj ? postData.paramsObj : postData.text; + break; + + case 'application/json': + settings.processData = false; + settings.data = postData.text; + break; + + case 'multipart/form-data': + if (!postData.params) { + break; + } + + push('const form = new FormData();'); + + postData.params.forEach(param => { + push(`form.append('${param.name}', '${param.value || param.fileName || ''}');`); + }); + + settings.processData = false; + settings.contentType = false; + settings.mimeType = 'multipart/form-data'; + settings.data = '[form]'; + + // remove the contentType header + if (hasHeader(allHeaders, 'content-type')) { + if (getHeader(allHeaders, 'content-type')?.includes('boundary')) { + const headerName = getHeaderName(allHeaders, 'content-type'); + if (headerName) { + delete settings.headers[headerName]; + } + } + } + + blank(); + break; + + default: + if (postData.text) { + settings.data = postData.text; + } + } + + const stringifiedSettings = stringifyObject(settings, { indent: opts.indent }).replace("'[form]'", 'form'); + + push(`const settings = ${stringifiedSettings};`); + blank(); + push('$.ajax(settings).done(res => {'); + push('console.log(res);', 1); + push('});'); + + return join(); + }, +}; diff --git a/src/targets/javascript/jquery/fixtures/application-form-encoded.js b/src/targets/javascript/jquery/fixtures/application-form-encoded.js new file mode 100644 index 000000000..fd6020417 --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/application-form-encoded.js @@ -0,0 +1,17 @@ +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/anything', + method: 'POST', + headers: { + 'content-type': 'application/x-www-form-urlencoded' + }, + data: { + foo: 'bar', + hello: 'world' + } +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/application-json.js b/src/targets/javascript/jquery/fixtures/application-json.js new file mode 100644 index 000000000..0599fa68a --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/application-json.js @@ -0,0 +1,15 @@ +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/anything', + method: 'POST', + headers: { + 'content-type': 'application/json' + }, + processData: false, + data: '{"number":1,"string":"f\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":[]}],"boolean":false}' +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/cookies.js b/src/targets/javascript/jquery/fixtures/cookies.js new file mode 100644 index 000000000..18899ddd8 --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/cookies.js @@ -0,0 +1,13 @@ +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/cookies', + method: 'GET', + headers: { + cookie: 'foo=bar; bar=baz' + } +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/custom-method.js b/src/targets/javascript/jquery/fixtures/custom-method.js new file mode 100644 index 000000000..5131ee1db --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/custom-method.js @@ -0,0 +1,11 @@ +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/anything', + method: 'PROPFIND', + headers: {} +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/full.js b/src/targets/javascript/jquery/fixtures/full.js new file mode 100644 index 000000000..a92c8867f --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/full.js @@ -0,0 +1,18 @@ +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value', + method: 'POST', + headers: { + cookie: 'foo=bar; bar=baz', + accept: 'application/json', + 'content-type': 'application/x-www-form-urlencoded' + }, + data: { + foo: 'bar' + } +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/headers.js b/src/targets/javascript/jquery/fixtures/headers.js new file mode 100644 index 000000000..f482429b7 --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/headers.js @@ -0,0 +1,16 @@ +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/headers', + method: 'GET', + headers: { + accept: 'application/json', + 'x-foo': 'Bar', + 'x-bar': 'Foo', + 'quoted-value': '"quoted" \'string\'' + } +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/http-insecure.js b/src/targets/javascript/jquery/fixtures/http-insecure.js new file mode 100644 index 000000000..bcc14a5f3 --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/http-insecure.js @@ -0,0 +1,11 @@ +const settings = { + async: true, + crossDomain: true, + url: 'http://httpbin.org/anything', + method: 'GET', + headers: {} +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/jsonObj-multiline.js b/src/targets/javascript/jquery/fixtures/jsonObj-multiline.js new file mode 100644 index 000000000..361dfd3c7 --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/jsonObj-multiline.js @@ -0,0 +1,15 @@ +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/anything', + method: 'POST', + headers: { + 'content-type': 'application/json' + }, + processData: false, + data: '{\n "foo": "bar"\n}' +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/jsonObj-null-value.js b/src/targets/javascript/jquery/fixtures/jsonObj-null-value.js new file mode 100644 index 000000000..682bf2726 --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/jsonObj-null-value.js @@ -0,0 +1,15 @@ +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/anything', + method: 'POST', + headers: { + 'content-type': 'application/json' + }, + processData: false, + data: '{"foo":null}' +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/multipart-data.js b/src/targets/javascript/jquery/fixtures/multipart-data.js new file mode 100644 index 000000000..48c0ffc10 --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/multipart-data.js @@ -0,0 +1,19 @@ +const form = new FormData(); +form.append('foo', 'Hello World'); +form.append('bar', 'Bonjour le monde'); + +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/anything', + method: 'POST', + headers: {}, + processData: false, + contentType: false, + mimeType: 'multipart/form-data', + data: form +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/multipart-file.js b/src/targets/javascript/jquery/fixtures/multipart-file.js new file mode 100644 index 000000000..43aba5379 --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/multipart-file.js @@ -0,0 +1,18 @@ +const form = new FormData(); +form.append('foo', 'src/fixtures/files/hello.txt'); + +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/anything', + method: 'POST', + headers: {}, + processData: false, + contentType: false, + mimeType: 'multipart/form-data', + data: form +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/multipart-form-data-no-params.js b/src/targets/javascript/jquery/fixtures/multipart-form-data-no-params.js new file mode 100644 index 000000000..da5946035 --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/multipart-form-data-no-params.js @@ -0,0 +1,13 @@ +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/anything', + method: 'POST', + headers: { + 'Content-Type': 'multipart/form-data' + } +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/multipart-form-data.js b/src/targets/javascript/jquery/fixtures/multipart-form-data.js new file mode 100644 index 000000000..68fde42fb --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/multipart-form-data.js @@ -0,0 +1,18 @@ +const form = new FormData(); +form.append('foo', 'bar'); + +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/anything', + method: 'POST', + headers: {}, + processData: false, + contentType: false, + mimeType: 'multipart/form-data', + data: form +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/nested.js b/src/targets/javascript/jquery/fixtures/nested.js new file mode 100644 index 000000000..4aac81436 --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/nested.js @@ -0,0 +1,11 @@ +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value', + method: 'GET', + headers: {} +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/postdata-malformed.js b/src/targets/javascript/jquery/fixtures/postdata-malformed.js new file mode 100644 index 000000000..a588c826c --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/postdata-malformed.js @@ -0,0 +1,13 @@ +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/anything', + method: 'POST', + headers: { + 'content-type': 'application/json' + } +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/query-encoded.js b/src/targets/javascript/jquery/fixtures/query-encoded.js new file mode 100644 index 000000000..cf871a707 --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/query-encoded.js @@ -0,0 +1,11 @@ +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00', + method: 'GET', + headers: {} +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/query.js b/src/targets/javascript/jquery/fixtures/query.js new file mode 100644 index 000000000..9d81c66db --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/query.js @@ -0,0 +1,11 @@ +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value', + method: 'GET', + headers: {} +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/short.js b/src/targets/javascript/jquery/fixtures/short.js new file mode 100644 index 000000000..0aa030eef --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/short.js @@ -0,0 +1,11 @@ +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/anything', + method: 'GET', + headers: {} +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/jquery/fixtures/text-plain.js b/src/targets/javascript/jquery/fixtures/text-plain.js new file mode 100644 index 000000000..d99636080 --- /dev/null +++ b/src/targets/javascript/jquery/fixtures/text-plain.js @@ -0,0 +1,14 @@ +const settings = { + async: true, + crossDomain: true, + url: 'https://httpbin.org/anything', + method: 'POST', + headers: { + 'content-type': 'text/plain' + }, + data: 'Hello World' +}; + +$.ajax(settings).done(res => { + console.log(res); +}); \ No newline at end of file diff --git a/src/targets/javascript/target.ts b/src/targets/javascript/target.ts new file mode 100644 index 000000000..6c58572cb --- /dev/null +++ b/src/targets/javascript/target.ts @@ -0,0 +1,21 @@ +import type { Target } from '../index.js'; + +import { axios } from './axios/client.js'; +import { fetch } from './fetch/client.js'; +import { jquery } from './jquery/client.js'; +import { xhr } from './xhr/client.js'; + +export const javascript: Target = { + info: { + key: 'javascript', + title: 'JavaScript', + default: 'fetch', + }, + + clientsById: { + xhr, + axios, + fetch, + jquery, + }, +}; diff --git a/src/targets/javascript/xhr.js b/src/targets/javascript/xhr.js deleted file mode 100644 index 3f7e69b71..000000000 --- a/src/targets/javascript/xhr.js +++ /dev/null @@ -1,80 +0,0 @@ -/** - * @description - * HTTP code snippet generator for native XMLHttpRequest - * - * @author - * @AhmadNassri - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ', - cors: true - }, options) - - var code = new CodeBuilder(opts.indent) - - switch (source.postData.mimeType) { - case 'application/json': - code.push('var data = JSON.stringify(%s);', JSON.stringify(source.postData.jsonObj, null, opts.indent)) - .push(null) - break - - case 'multipart/form-data': - code.push('var data = new FormData();') - - source.postData.params.forEach(function (param) { - code.push('data.append(%s, %s);', JSON.stringify(param.name), JSON.stringify(param.value || param.fileName || '')) - }) - - // remove the contentType header - if (source.allHeaders['content-type'].indexOf('boundary')) { - delete source.allHeaders['content-type'] - } - - code.blank() - break - - default: - code.push('var data = %s;', JSON.stringify(source.postData.text || null)) - .blank() - } - - code.push('var xhr = new XMLHttpRequest();') - - if (opts.cors) { - code.push('xhr.withCredentials = true;') - } - - code.blank() - .push('xhr.addEventListener("readystatechange", function () {') - .push(1, 'if (this.readyState === this.DONE) {') - .push(2, 'console.log(this.responseText);') - .push(1, '}') - .push('});') - .blank() - .push('xhr.open(%s, %s);', JSON.stringify(source.method), JSON.stringify(source.fullUrl)) - - Object.keys(source.allHeaders).forEach(function (key) { - code.push('xhr.setRequestHeader(%s, %s);', JSON.stringify(key), JSON.stringify(source.allHeaders[key])) - }) - - code.blank() - .push('xhr.send(data);') - - return code.join() -} - -module.exports.info = { - key: 'xhr', - title: 'XMLHttpRequest', - link: 'https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest', - description: 'W3C Standard API that provides scripted client functionality' -} diff --git a/src/targets/javascript/xhr/client.test.ts b/src/targets/javascript/xhr/client.test.ts new file mode 100644 index 000000000..bd66a9ea1 --- /dev/null +++ b/src/targets/javascript/xhr/client.test.ts @@ -0,0 +1,19 @@ +import type { Request } from '../../../index.js'; + +import request from '../../../fixtures/requests/short.cjs'; +import { runCustomFixtures } from '../../../fixtures/runCustomFixtures.js'; + +runCustomFixtures({ + targetId: 'javascript', + clientId: 'xhr', + tests: [ + { + it: 'should not use cors', + input: request.log.entries[0].request as Request, + options: { + cors: false, + }, + expected: 'cors.js', + }, + ], +}); diff --git a/src/targets/javascript/xhr/client.ts b/src/targets/javascript/xhr/client.ts new file mode 100644 index 000000000..33a2d1815 --- /dev/null +++ b/src/targets/javascript/xhr/client.ts @@ -0,0 +1,102 @@ +/** + * @description + * HTTP code snippet generator for native XMLHttpRequest + * + * @author + * @AhmadNassri + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import stringifyObject from 'stringify-object'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { escapeForSingleQuotes } from '../../../helpers/escape.js'; +import { getHeader, getHeaderName, hasHeader } from '../../../helpers/headers.js'; + +export interface XhrOptions { + cors?: boolean; +} + +export const xhr: Client = { + info: { + key: 'xhr', + title: 'XMLHttpRequest', + link: 'https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest', + description: 'W3C Standard API that provides scripted client functionality', + extname: '.js', + }, + convert: ({ postData, allHeaders, method, fullUrl }, options) => { + const opts = { + indent: ' ', + cors: true, + ...options, + }; + + const { blank, push, join } = new CodeBuilder({ indent: opts.indent }); + + switch (postData.mimeType) { + case 'application/json': + push( + `const data = JSON.stringify(${stringifyObject(postData.jsonObj, { + indent: opts.indent, + })});`, + ); + blank(); + break; + + case 'multipart/form-data': + if (!postData.params) { + break; + } + + push('const data = new FormData();'); + + postData.params.forEach(param => { + push(`data.append('${param.name}', '${param.value || param.fileName || ''}');`); + }); + + // remove the contentType header + if (hasHeader(allHeaders, 'content-type')) { + if (getHeader(allHeaders, 'content-type')?.includes('boundary')) { + const headerName = getHeaderName(allHeaders, 'content-type'); + if (headerName) { + delete allHeaders[headerName]; + } + } + } + + blank(); + break; + + default: + push(`const data = ${postData.text ? `'${postData.text}'` : 'null'};`); + blank(); + } + + push('const xhr = new XMLHttpRequest();'); + + if (opts.cors) { + push('xhr.withCredentials = true;'); + } + + blank(); + push("xhr.addEventListener('readystatechange', function () {"); + push('if (this.readyState === this.DONE) {', 1); + push('console.log(this.responseText);', 2); + push('}', 1); + push('});'); + blank(); + push(`xhr.open('${method}', '${fullUrl}');`); + + Object.keys(allHeaders).forEach(key => { + push(`xhr.setRequestHeader('${key}', '${escapeForSingleQuotes(allHeaders[key])}');`); + }); + + blank(); + push('xhr.send(data);'); + + return join(); + }, +}; diff --git a/src/targets/javascript/xhr/fixtures/application-form-encoded.js b/src/targets/javascript/xhr/fixtures/application-form-encoded.js new file mode 100644 index 000000000..e745ca388 --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/application-form-encoded.js @@ -0,0 +1,15 @@ +const data = 'foo=bar&hello=world'; + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('POST', 'https://httpbin.org/anything'); +xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/application-json.js b/src/targets/javascript/xhr/fixtures/application-json.js new file mode 100644 index 000000000..05109f1f6 --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/application-json.js @@ -0,0 +1,34 @@ +const data = JSON.stringify({ + number: 1, + string: 'f"oo', + arr: [ + 1, + 2, + 3 + ], + nested: { + a: 'b' + }, + arr_mix: [ + 1, + 'a', + { + arr_mix_nested: [] + } + ], + boolean: false +}); + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('POST', 'https://httpbin.org/anything'); +xhr.setRequestHeader('content-type', 'application/json'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/cookies.js b/src/targets/javascript/xhr/fixtures/cookies.js new file mode 100644 index 000000000..303865891 --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/cookies.js @@ -0,0 +1,15 @@ +const data = null; + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('GET', 'https://httpbin.org/cookies'); +xhr.setRequestHeader('cookie', 'foo=bar; bar=baz'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/cors.js b/src/targets/javascript/xhr/fixtures/cors.js new file mode 100644 index 000000000..7be5b75a7 --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/cors.js @@ -0,0 +1,13 @@ +const data = null; + +const xhr = new XMLHttpRequest(); + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('GET', 'https://httpbin.org/anything'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/custom-method.js b/src/targets/javascript/xhr/fixtures/custom-method.js new file mode 100644 index 000000000..b7249c740 --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/custom-method.js @@ -0,0 +1,14 @@ +const data = null; + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('PROPFIND', 'https://httpbin.org/anything'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/full.js b/src/targets/javascript/xhr/fixtures/full.js new file mode 100644 index 000000000..e3190633e --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/full.js @@ -0,0 +1,17 @@ +const data = 'foo=bar'; + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('POST', 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value'); +xhr.setRequestHeader('cookie', 'foo=bar; bar=baz'); +xhr.setRequestHeader('accept', 'application/json'); +xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/headers.js b/src/targets/javascript/xhr/fixtures/headers.js new file mode 100644 index 000000000..919deb13a --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/headers.js @@ -0,0 +1,18 @@ +const data = null; + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('GET', 'https://httpbin.org/headers'); +xhr.setRequestHeader('accept', 'application/json'); +xhr.setRequestHeader('x-foo', 'Bar'); +xhr.setRequestHeader('x-bar', 'Foo'); +xhr.setRequestHeader('quoted-value', '"quoted" \'string\''); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/http-insecure.js b/src/targets/javascript/xhr/fixtures/http-insecure.js new file mode 100644 index 000000000..006f993bf --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/http-insecure.js @@ -0,0 +1,14 @@ +const data = null; + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('GET', 'http://httpbin.org/anything'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/jsonObj-multiline.js b/src/targets/javascript/xhr/fixtures/jsonObj-multiline.js new file mode 100644 index 000000000..db126cbe6 --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/jsonObj-multiline.js @@ -0,0 +1,17 @@ +const data = JSON.stringify({ + foo: 'bar' +}); + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('POST', 'https://httpbin.org/anything'); +xhr.setRequestHeader('content-type', 'application/json'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/jsonObj-null-value.js b/src/targets/javascript/xhr/fixtures/jsonObj-null-value.js new file mode 100644 index 000000000..92befdc34 --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/jsonObj-null-value.js @@ -0,0 +1,17 @@ +const data = JSON.stringify({ + foo: null +}); + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('POST', 'https://httpbin.org/anything'); +xhr.setRequestHeader('content-type', 'application/json'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/multipart-data.js b/src/targets/javascript/xhr/fixtures/multipart-data.js new file mode 100644 index 000000000..0dabcfeaf --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/multipart-data.js @@ -0,0 +1,16 @@ +const data = new FormData(); +data.append('foo', 'Hello World'); +data.append('bar', 'Bonjour le monde'); + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('POST', 'https://httpbin.org/anything'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/multipart-file.js b/src/targets/javascript/xhr/fixtures/multipart-file.js new file mode 100644 index 000000000..aaca03d25 --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/multipart-file.js @@ -0,0 +1,15 @@ +const data = new FormData(); +data.append('foo', 'src/fixtures/files/hello.txt'); + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('POST', 'https://httpbin.org/anything'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/multipart-form-data-no-params.js b/src/targets/javascript/xhr/fixtures/multipart-form-data-no-params.js new file mode 100644 index 000000000..96179647d --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/multipart-form-data-no-params.js @@ -0,0 +1,13 @@ +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('POST', 'https://httpbin.org/anything'); +xhr.setRequestHeader('Content-Type', 'multipart/form-data'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/multipart-form-data.js b/src/targets/javascript/xhr/fixtures/multipart-form-data.js new file mode 100644 index 000000000..2c4d372e3 --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/multipart-form-data.js @@ -0,0 +1,15 @@ +const data = new FormData(); +data.append('foo', 'bar'); + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('POST', 'https://httpbin.org/anything'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/nested.js b/src/targets/javascript/xhr/fixtures/nested.js new file mode 100644 index 000000000..37d2cdee4 --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/nested.js @@ -0,0 +1,14 @@ +const data = null; + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('GET', 'https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/postdata-malformed.js b/src/targets/javascript/xhr/fixtures/postdata-malformed.js new file mode 100644 index 000000000..51ea31877 --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/postdata-malformed.js @@ -0,0 +1,15 @@ +const data = null; + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('POST', 'https://httpbin.org/anything'); +xhr.setRequestHeader('content-type', 'application/json'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/query-encoded.js b/src/targets/javascript/xhr/fixtures/query-encoded.js new file mode 100644 index 000000000..59626c98d --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/query-encoded.js @@ -0,0 +1,14 @@ +const data = null; + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('GET', 'https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/query.js b/src/targets/javascript/xhr/fixtures/query.js new file mode 100644 index 000000000..5cc3bb5ce --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/query.js @@ -0,0 +1,14 @@ +const data = null; + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('GET', 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/short.js b/src/targets/javascript/xhr/fixtures/short.js new file mode 100644 index 000000000..d7184f2f4 --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/short.js @@ -0,0 +1,14 @@ +const data = null; + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('GET', 'https://httpbin.org/anything'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/javascript/xhr/fixtures/text-plain.js b/src/targets/javascript/xhr/fixtures/text-plain.js new file mode 100644 index 000000000..6665974bc --- /dev/null +++ b/src/targets/javascript/xhr/fixtures/text-plain.js @@ -0,0 +1,15 @@ +const data = 'Hello World'; + +const xhr = new XMLHttpRequest(); +xhr.withCredentials = true; + +xhr.addEventListener('readystatechange', function () { + if (this.readyState === this.DONE) { + console.log(this.responseText); + } +}); + +xhr.open('POST', 'https://httpbin.org/anything'); +xhr.setRequestHeader('content-type', 'text/plain'); + +xhr.send(data); \ No newline at end of file diff --git a/src/targets/json/native/client.ts b/src/targets/json/native/client.ts new file mode 100644 index 000000000..5c7d03b99 --- /dev/null +++ b/src/targets/json/native/client.ts @@ -0,0 +1,66 @@ +/** + * @description + * HTTP code snippet generator to generate raw JSON payload objects. + * + * @author + * @erunion + * + * For any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { ReducedHelperObject } from '../../../helpers/reducer.js'; +import type { Client } from '../../index.js'; + +export const native: Client = { + info: { + key: 'native', + title: 'Native JSON', + link: 'https://www.json.org/json-en.html', + description: 'A JSON represetation of any HAR payload.', + extname: '.json', + }, + convert: ({ postData }, inputOpts) => { + const opts = { + indent: ' ', + ...inputOpts, + }; + + let payload: ReducedHelperObject | string | undefined = ''; + + switch (postData.mimeType) { + case 'application/x-www-form-urlencoded': + payload = postData.paramsObj ? postData.paramsObj : postData.text; + break; + + case 'application/json': + if (postData.jsonObj) { + payload = postData.jsonObj; + } + break; + + case 'multipart/form-data': { + if (!postData.params) { + break; + } + + const multipartPayload: Record = {}; + postData.params.forEach(param => { + multipartPayload[param.name] = param.value; + }); + + payload = multipartPayload; + break; + } + + default: + if (postData.text) { + payload = postData.text; + } + } + + if (typeof payload === 'undefined' || payload === '') { + return 'No JSON body'; + } + + return JSON.stringify(payload, null, opts.indent); + }, +}; diff --git a/src/targets/json/native/fixtures/application-form-encoded.json b/src/targets/json/native/fixtures/application-form-encoded.json new file mode 100644 index 000000000..600263097 --- /dev/null +++ b/src/targets/json/native/fixtures/application-form-encoded.json @@ -0,0 +1,4 @@ +{ + "foo": "bar", + "hello": "world" +} \ No newline at end of file diff --git a/src/targets/json/native/fixtures/application-json.json b/src/targets/json/native/fixtures/application-json.json new file mode 100644 index 000000000..e3b8fc43a --- /dev/null +++ b/src/targets/json/native/fixtures/application-json.json @@ -0,0 +1,20 @@ +{ + "number": 1, + "string": "f\"oo", + "arr": [ + 1, + 2, + 3 + ], + "nested": { + "a": "b" + }, + "arr_mix": [ + 1, + "a", + { + "arr_mix_nested": [] + } + ], + "boolean": false +} \ No newline at end of file diff --git a/src/targets/json/native/fixtures/cookies.json b/src/targets/json/native/fixtures/cookies.json new file mode 100644 index 000000000..f24694d81 --- /dev/null +++ b/src/targets/json/native/fixtures/cookies.json @@ -0,0 +1 @@ +No JSON body \ No newline at end of file diff --git a/src/targets/json/native/fixtures/custom-method.json b/src/targets/json/native/fixtures/custom-method.json new file mode 100644 index 000000000..f24694d81 --- /dev/null +++ b/src/targets/json/native/fixtures/custom-method.json @@ -0,0 +1 @@ +No JSON body \ No newline at end of file diff --git a/src/targets/json/native/fixtures/full.json b/src/targets/json/native/fixtures/full.json new file mode 100644 index 000000000..b42f309e7 --- /dev/null +++ b/src/targets/json/native/fixtures/full.json @@ -0,0 +1,3 @@ +{ + "foo": "bar" +} \ No newline at end of file diff --git a/src/targets/json/native/fixtures/headers.json b/src/targets/json/native/fixtures/headers.json new file mode 100644 index 000000000..f24694d81 --- /dev/null +++ b/src/targets/json/native/fixtures/headers.json @@ -0,0 +1 @@ +No JSON body \ No newline at end of file diff --git a/src/targets/json/native/fixtures/http-insecure.json b/src/targets/json/native/fixtures/http-insecure.json new file mode 100644 index 000000000..f24694d81 --- /dev/null +++ b/src/targets/json/native/fixtures/http-insecure.json @@ -0,0 +1 @@ +No JSON body \ No newline at end of file diff --git a/src/targets/json/native/fixtures/jsonObj-multiline.json b/src/targets/json/native/fixtures/jsonObj-multiline.json new file mode 100644 index 000000000..b42f309e7 --- /dev/null +++ b/src/targets/json/native/fixtures/jsonObj-multiline.json @@ -0,0 +1,3 @@ +{ + "foo": "bar" +} \ No newline at end of file diff --git a/src/targets/json/native/fixtures/jsonObj-null-value.json b/src/targets/json/native/fixtures/jsonObj-null-value.json new file mode 100644 index 000000000..59b836c5f --- /dev/null +++ b/src/targets/json/native/fixtures/jsonObj-null-value.json @@ -0,0 +1,3 @@ +{ + "foo": null +} \ No newline at end of file diff --git a/src/targets/json/native/fixtures/multipart-data.json b/src/targets/json/native/fixtures/multipart-data.json new file mode 100644 index 000000000..da0801132 --- /dev/null +++ b/src/targets/json/native/fixtures/multipart-data.json @@ -0,0 +1,4 @@ +{ + "foo": "Hello World", + "bar": "Bonjour le monde" +} \ No newline at end of file diff --git a/src/targets/json/native/fixtures/multipart-file.json b/src/targets/json/native/fixtures/multipart-file.json new file mode 100644 index 000000000..9e26dfeeb --- /dev/null +++ b/src/targets/json/native/fixtures/multipart-file.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/src/targets/json/native/fixtures/multipart-form-data-no-params.json b/src/targets/json/native/fixtures/multipart-form-data-no-params.json new file mode 100644 index 000000000..f24694d81 --- /dev/null +++ b/src/targets/json/native/fixtures/multipart-form-data-no-params.json @@ -0,0 +1 @@ +No JSON body \ No newline at end of file diff --git a/src/targets/json/native/fixtures/multipart-form-data.json b/src/targets/json/native/fixtures/multipart-form-data.json new file mode 100644 index 000000000..b42f309e7 --- /dev/null +++ b/src/targets/json/native/fixtures/multipart-form-data.json @@ -0,0 +1,3 @@ +{ + "foo": "bar" +} \ No newline at end of file diff --git a/src/targets/json/native/fixtures/nested.json b/src/targets/json/native/fixtures/nested.json new file mode 100644 index 000000000..f24694d81 --- /dev/null +++ b/src/targets/json/native/fixtures/nested.json @@ -0,0 +1 @@ +No JSON body \ No newline at end of file diff --git a/src/targets/json/native/fixtures/postdata-malformed.json b/src/targets/json/native/fixtures/postdata-malformed.json new file mode 100644 index 000000000..f24694d81 --- /dev/null +++ b/src/targets/json/native/fixtures/postdata-malformed.json @@ -0,0 +1 @@ +No JSON body \ No newline at end of file diff --git a/src/targets/json/native/fixtures/query-encoded.json b/src/targets/json/native/fixtures/query-encoded.json new file mode 100644 index 000000000..f24694d81 --- /dev/null +++ b/src/targets/json/native/fixtures/query-encoded.json @@ -0,0 +1 @@ +No JSON body \ No newline at end of file diff --git a/src/targets/json/native/fixtures/query.json b/src/targets/json/native/fixtures/query.json new file mode 100644 index 000000000..f24694d81 --- /dev/null +++ b/src/targets/json/native/fixtures/query.json @@ -0,0 +1 @@ +No JSON body \ No newline at end of file diff --git a/src/targets/json/native/fixtures/short.json b/src/targets/json/native/fixtures/short.json new file mode 100644 index 000000000..f24694d81 --- /dev/null +++ b/src/targets/json/native/fixtures/short.json @@ -0,0 +1 @@ +No JSON body \ No newline at end of file diff --git a/src/targets/json/native/fixtures/text-plain.json b/src/targets/json/native/fixtures/text-plain.json new file mode 100644 index 000000000..be5d95a19 --- /dev/null +++ b/src/targets/json/native/fixtures/text-plain.json @@ -0,0 +1 @@ +"Hello World" \ No newline at end of file diff --git a/src/targets/json/target.ts b/src/targets/json/target.ts new file mode 100644 index 000000000..86936ba4d --- /dev/null +++ b/src/targets/json/target.ts @@ -0,0 +1,14 @@ +import type { Target } from '../index.js'; + +import { native } from './native/client.js'; + +export const json: Target = { + info: { + key: 'json', + title: 'JSON', + default: 'native', + }, + clientsById: { + native, + }, +}; diff --git a/src/targets/kotlin/okhttp/client.ts b/src/targets/kotlin/okhttp/client.ts new file mode 100644 index 000000000..c6a2a5b22 --- /dev/null +++ b/src/targets/kotlin/okhttp/client.ts @@ -0,0 +1,75 @@ +/** + * @description + * HTTP code snippet generator for Kotlin using OkHttp. + * + * @author + * @seanghay + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { escapeForDoubleQuotes } from '../../../helpers/escape.js'; + +export const okhttp: Client = { + info: { + key: 'okhttp', + title: 'OkHttp', + link: 'http://square.github.io/okhttp/', + description: 'An HTTP Request Client Library', + extname: '.kt', + }, + convert: ({ postData, fullUrl, method, allHeaders }, options) => { + const opts = { + indent: ' ', + ...options, + }; + const { blank, join, push } = new CodeBuilder({ indent: opts.indent }); + + const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD']; + + const methodsWithBody = ['POST', 'PUT', 'DELETE', 'PATCH']; + + push('val client = OkHttpClient()'); + blank(); + + if (postData.text) { + if (postData.boundary) { + push(`val mediaType = MediaType.parse("${postData.mimeType}; boundary=${postData.boundary}")`); + } else { + push(`val mediaType = MediaType.parse("${postData.mimeType}")`); + } + push(`val body = RequestBody.create(mediaType, ${JSON.stringify(postData.text)})`); + } + + push('val request = Request.Builder()'); + push(`.url("${fullUrl}")`, 1); + if (!methods.includes(method.toUpperCase())) { + if (postData.text) { + push(`.method("${method.toUpperCase()}", body)`, 1); + } else { + push(`.method("${method.toUpperCase()}", null)`, 1); + } + } else if (methodsWithBody.includes(method.toUpperCase())) { + if (postData.text) { + push(`.${method.toLowerCase()}(body)`, 1); + } else { + push(`.${method.toLowerCase()}(null)`, 1); + } + } else { + push(`.${method.toLowerCase()}()`, 1); + } + + // Add headers, including the cookies + Object.keys(allHeaders).forEach(key => { + push(`.addHeader("${key}", "${escapeForDoubleQuotes(allHeaders[key])}")`, 1); + }); + + push('.build()', 1); + blank(); + push('val response = client.newCall(request).execute()'); + + return join(); + }, +}; diff --git a/src/targets/kotlin/okhttp/fixtures/application-form-encoded.kt b/src/targets/kotlin/okhttp/fixtures/application-form-encoded.kt new file mode 100644 index 000000000..d75fa3b99 --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/application-form-encoded.kt @@ -0,0 +1,11 @@ +val client = OkHttpClient() + +val mediaType = MediaType.parse("application/x-www-form-urlencoded") +val body = RequestBody.create(mediaType, "foo=bar&hello=world") +val request = Request.Builder() + .url("https://httpbin.org/anything") + .post(body) + .addHeader("content-type", "application/x-www-form-urlencoded") + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/application-json.kt b/src/targets/kotlin/okhttp/fixtures/application-json.kt new file mode 100644 index 000000000..57d53bc06 --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/application-json.kt @@ -0,0 +1,11 @@ +val client = OkHttpClient() + +val mediaType = MediaType.parse("application/json") +val body = RequestBody.create(mediaType, "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":[]}],\"boolean\":false}") +val request = Request.Builder() + .url("https://httpbin.org/anything") + .post(body) + .addHeader("content-type", "application/json") + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/cookies.kt b/src/targets/kotlin/okhttp/fixtures/cookies.kt new file mode 100644 index 000000000..cd7ec557d --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/cookies.kt @@ -0,0 +1,9 @@ +val client = OkHttpClient() + +val request = Request.Builder() + .url("https://httpbin.org/cookies") + .get() + .addHeader("cookie", "foo=bar; bar=baz") + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/custom-method.kt b/src/targets/kotlin/okhttp/fixtures/custom-method.kt new file mode 100644 index 000000000..de8fba805 --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/custom-method.kt @@ -0,0 +1,8 @@ +val client = OkHttpClient() + +val request = Request.Builder() + .url("https://httpbin.org/anything") + .method("PROPFIND", null) + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/full.kt b/src/targets/kotlin/okhttp/fixtures/full.kt new file mode 100644 index 000000000..a5f33ca6e --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/full.kt @@ -0,0 +1,13 @@ +val client = OkHttpClient() + +val mediaType = MediaType.parse("application/x-www-form-urlencoded") +val body = RequestBody.create(mediaType, "foo=bar") +val request = Request.Builder() + .url("https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value") + .post(body) + .addHeader("cookie", "foo=bar; bar=baz") + .addHeader("accept", "application/json") + .addHeader("content-type", "application/x-www-form-urlencoded") + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/headers.kt b/src/targets/kotlin/okhttp/fixtures/headers.kt new file mode 100644 index 000000000..a4a23a279 --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/headers.kt @@ -0,0 +1,12 @@ +val client = OkHttpClient() + +val request = Request.Builder() + .url("https://httpbin.org/headers") + .get() + .addHeader("accept", "application/json") + .addHeader("x-foo", "Bar") + .addHeader("x-bar", "Foo") + .addHeader("quoted-value", "\"quoted\" 'string'") + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/http-insecure.kt b/src/targets/kotlin/okhttp/fixtures/http-insecure.kt new file mode 100644 index 000000000..ddfaf84b7 --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/http-insecure.kt @@ -0,0 +1,8 @@ +val client = OkHttpClient() + +val request = Request.Builder() + .url("http://httpbin.org/anything") + .get() + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/jsonObj-multiline.kt b/src/targets/kotlin/okhttp/fixtures/jsonObj-multiline.kt new file mode 100644 index 000000000..9707bd24c --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/jsonObj-multiline.kt @@ -0,0 +1,11 @@ +val client = OkHttpClient() + +val mediaType = MediaType.parse("application/json") +val body = RequestBody.create(mediaType, "{\n \"foo\": \"bar\"\n}") +val request = Request.Builder() + .url("https://httpbin.org/anything") + .post(body) + .addHeader("content-type", "application/json") + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/jsonObj-null-value.kt b/src/targets/kotlin/okhttp/fixtures/jsonObj-null-value.kt new file mode 100644 index 000000000..95b286c51 --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/jsonObj-null-value.kt @@ -0,0 +1,11 @@ +val client = OkHttpClient() + +val mediaType = MediaType.parse("application/json") +val body = RequestBody.create(mediaType, "{\"foo\":null}") +val request = Request.Builder() + .url("https://httpbin.org/anything") + .post(body) + .addHeader("content-type", "application/json") + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/multipart-data.kt b/src/targets/kotlin/okhttp/fixtures/multipart-data.kt new file mode 100644 index 000000000..adc042888 --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/multipart-data.kt @@ -0,0 +1,11 @@ +val client = OkHttpClient() + +val mediaType = MediaType.parse("multipart/form-data; boundary=---011000010111000001101001") +val body = RequestBody.create(mediaType, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"bar\"\r\n\r\nBonjour le monde\r\n-----011000010111000001101001--") +val request = Request.Builder() + .url("https://httpbin.org/anything") + .post(body) + .addHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001") + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/multipart-file.kt b/src/targets/kotlin/okhttp/fixtures/multipart-file.kt new file mode 100644 index 000000000..3f1908c00 --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/multipart-file.kt @@ -0,0 +1,11 @@ +val client = OkHttpClient() + +val mediaType = MediaType.parse("multipart/form-data; boundary=---011000010111000001101001") +val body = RequestBody.create(mediaType, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--") +val request = Request.Builder() + .url("https://httpbin.org/anything") + .post(body) + .addHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001") + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/multipart-form-data-no-params.kt b/src/targets/kotlin/okhttp/fixtures/multipart-form-data-no-params.kt new file mode 100644 index 000000000..dc80c47af --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/multipart-form-data-no-params.kt @@ -0,0 +1,9 @@ +val client = OkHttpClient() + +val request = Request.Builder() + .url("https://httpbin.org/anything") + .post(null) + .addHeader("Content-Type", "multipart/form-data") + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/multipart-form-data.kt b/src/targets/kotlin/okhttp/fixtures/multipart-form-data.kt new file mode 100644 index 000000000..7967ff2c1 --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/multipart-form-data.kt @@ -0,0 +1,11 @@ +val client = OkHttpClient() + +val mediaType = MediaType.parse("multipart/form-data; boundary=---011000010111000001101001") +val body = RequestBody.create(mediaType, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--") +val request = Request.Builder() + .url("https://httpbin.org/anything") + .post(body) + .addHeader("Content-Type", "multipart/form-data; boundary=---011000010111000001101001") + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/nested.kt b/src/targets/kotlin/okhttp/fixtures/nested.kt new file mode 100644 index 000000000..8d2451393 --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/nested.kt @@ -0,0 +1,8 @@ +val client = OkHttpClient() + +val request = Request.Builder() + .url("https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value") + .get() + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/postdata-malformed.kt b/src/targets/kotlin/okhttp/fixtures/postdata-malformed.kt new file mode 100644 index 000000000..2f230e374 --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/postdata-malformed.kt @@ -0,0 +1,9 @@ +val client = OkHttpClient() + +val request = Request.Builder() + .url("https://httpbin.org/anything") + .post(null) + .addHeader("content-type", "application/json") + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/query-encoded.kt b/src/targets/kotlin/okhttp/fixtures/query-encoded.kt new file mode 100644 index 000000000..b57e57fd9 --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/query-encoded.kt @@ -0,0 +1,8 @@ +val client = OkHttpClient() + +val request = Request.Builder() + .url("https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00") + .get() + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/query.kt b/src/targets/kotlin/okhttp/fixtures/query.kt new file mode 100644 index 000000000..94f68a1dc --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/query.kt @@ -0,0 +1,8 @@ +val client = OkHttpClient() + +val request = Request.Builder() + .url("https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value") + .get() + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/short.kt b/src/targets/kotlin/okhttp/fixtures/short.kt new file mode 100644 index 000000000..cb4b990c0 --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/short.kt @@ -0,0 +1,8 @@ +val client = OkHttpClient() + +val request = Request.Builder() + .url("https://httpbin.org/anything") + .get() + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/okhttp/fixtures/text-plain.kt b/src/targets/kotlin/okhttp/fixtures/text-plain.kt new file mode 100644 index 000000000..d6cf0f9fd --- /dev/null +++ b/src/targets/kotlin/okhttp/fixtures/text-plain.kt @@ -0,0 +1,11 @@ +val client = OkHttpClient() + +val mediaType = MediaType.parse("text/plain") +val body = RequestBody.create(mediaType, "Hello World") +val request = Request.Builder() + .url("https://httpbin.org/anything") + .post(body) + .addHeader("content-type", "text/plain") + .build() + +val response = client.newCall(request).execute() \ No newline at end of file diff --git a/src/targets/kotlin/target.ts b/src/targets/kotlin/target.ts new file mode 100644 index 000000000..d62933f60 --- /dev/null +++ b/src/targets/kotlin/target.ts @@ -0,0 +1,14 @@ +import type { Target } from '../index.js'; + +import { okhttp } from './okhttp/client.js'; + +export const kotlin: Target = { + info: { + key: 'kotlin', + title: 'Kotlin', + default: 'okhttp', + }, + clientsById: { + okhttp, + }, +}; diff --git a/src/targets/node/axios/client.ts b/src/targets/node/axios/client.ts new file mode 100644 index 000000000..ffc85438d --- /dev/null +++ b/src/targets/node/axios/client.ts @@ -0,0 +1,83 @@ +/** + * @description + * HTTP code snippet generator for Javascript & Node.js using Axios. + * + * @author + * @rohit-gohri + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import stringifyObject from 'stringify-object'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; + +export const axios: Client = { + info: { + key: 'axios', + title: 'Axios', + link: 'https://github.com/axios/axios', + description: 'Promise based HTTP client for the browser and node.js', + extname: '.js', + installation: () => 'npm install axios --save', + }, + convert: ({ method, fullUrl, allHeaders, postData }, options) => { + const opts = { + indent: ' ', + ...options, + }; + const { blank, join, push, addPostProcessor } = new CodeBuilder({ indent: opts.indent }); + + push("import axios from 'axios';"); + blank(); + + const reqOpts: Record = { + method, + url: fullUrl, + }; + + if (Object.keys(allHeaders).length) { + reqOpts.headers = allHeaders; + } + + switch (postData.mimeType) { + case 'application/x-www-form-urlencoded': + if (postData.params) { + push('const encodedParams = new URLSearchParams();'); + postData.params.forEach(param => { + push(`encodedParams.set('${param.name}', '${param.value}');`); + }); + + blank(); + + reqOpts.data = 'encodedParams,'; + addPostProcessor(code => code.replace(/'encodedParams,'/, 'encodedParams,')); + } + + break; + + case 'application/json': + if (postData.jsonObj) { + reqOpts.data = postData.jsonObj; + } + break; + + default: + if (postData.text) { + reqOpts.data = postData.text; + } + } + + const stringifiedOptions = stringifyObject(reqOpts, { indent: ' ', inlineCharacterLimit: 80 }); + push(`const options = ${stringifiedOptions};`); + blank(); + + push('axios'); + push('.request(options)', 1); + push('.then(res => console.log(res.data))', 1); + push('.catch(err => console.error(err));', 1); + + return join(); + }, +}; diff --git a/src/targets/node/axios/fixtures/application-form-encoded.js b/src/targets/node/axios/fixtures/application-form-encoded.js new file mode 100644 index 000000000..1a83ea542 --- /dev/null +++ b/src/targets/node/axios/fixtures/application-form-encoded.js @@ -0,0 +1,17 @@ +import axios from 'axios'; + +const encodedParams = new URLSearchParams(); +encodedParams.set('foo', 'bar'); +encodedParams.set('hello', 'world'); + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'content-type': 'application/x-www-form-urlencoded'}, + data: encodedParams, +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/application-json.js b/src/targets/node/axios/fixtures/application-json.js new file mode 100644 index 000000000..98903a65a --- /dev/null +++ b/src/targets/node/axios/fixtures/application-json.js @@ -0,0 +1,20 @@ +import axios from 'axios'; + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'content-type': 'application/json'}, + data: { + number: 1, + string: 'f"oo', + arr: [1, 2, 3], + nested: {a: 'b'}, + arr_mix: [1, 'a', {arr_mix_nested: []}], + boolean: false + } +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/cookies.js b/src/targets/node/axios/fixtures/cookies.js new file mode 100644 index 000000000..7e9cf7ae3 --- /dev/null +++ b/src/targets/node/axios/fixtures/cookies.js @@ -0,0 +1,12 @@ +import axios from 'axios'; + +const options = { + method: 'GET', + url: 'https://httpbin.org/cookies', + headers: {cookie: 'foo=bar; bar=baz'} +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/custom-method.js b/src/targets/node/axios/fixtures/custom-method.js new file mode 100644 index 000000000..4142f5977 --- /dev/null +++ b/src/targets/node/axios/fixtures/custom-method.js @@ -0,0 +1,8 @@ +import axios from 'axios'; + +const options = {method: 'PROPFIND', url: 'https://httpbin.org/anything'}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/full.js b/src/targets/node/axios/fixtures/full.js new file mode 100644 index 000000000..fce011d95 --- /dev/null +++ b/src/targets/node/axios/fixtures/full.js @@ -0,0 +1,20 @@ +import axios from 'axios'; + +const encodedParams = new URLSearchParams(); +encodedParams.set('foo', 'bar'); + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value', + headers: { + cookie: 'foo=bar; bar=baz', + accept: 'application/json', + 'content-type': 'application/x-www-form-urlencoded' + }, + data: encodedParams, +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/headers.js b/src/targets/node/axios/fixtures/headers.js new file mode 100644 index 000000000..8026a1ee9 --- /dev/null +++ b/src/targets/node/axios/fixtures/headers.js @@ -0,0 +1,17 @@ +import axios from 'axios'; + +const options = { + method: 'GET', + url: 'https://httpbin.org/headers', + headers: { + accept: 'application/json', + 'x-foo': 'Bar', + 'x-bar': 'Foo', + 'quoted-value': '"quoted" \'string\'' + } +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/http-insecure.js b/src/targets/node/axios/fixtures/http-insecure.js new file mode 100644 index 000000000..0512e2df7 --- /dev/null +++ b/src/targets/node/axios/fixtures/http-insecure.js @@ -0,0 +1,8 @@ +import axios from 'axios'; + +const options = {method: 'GET', url: 'http://httpbin.org/anything'}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/jsonObj-multiline.js b/src/targets/node/axios/fixtures/jsonObj-multiline.js new file mode 100644 index 000000000..7d41fbc52 --- /dev/null +++ b/src/targets/node/axios/fixtures/jsonObj-multiline.js @@ -0,0 +1,13 @@ +import axios from 'axios'; + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'content-type': 'application/json'}, + data: {foo: 'bar'} +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/jsonObj-null-value.js b/src/targets/node/axios/fixtures/jsonObj-null-value.js new file mode 100644 index 000000000..3731d644d --- /dev/null +++ b/src/targets/node/axios/fixtures/jsonObj-null-value.js @@ -0,0 +1,13 @@ +import axios from 'axios'; + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'content-type': 'application/json'}, + data: {foo: null} +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/multipart-data.js b/src/targets/node/axios/fixtures/multipart-data.js new file mode 100644 index 000000000..d8672a082 --- /dev/null +++ b/src/targets/node/axios/fixtures/multipart-data.js @@ -0,0 +1,13 @@ +import axios from 'axios'; + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'content-type': 'multipart/form-data; boundary=---011000010111000001101001'}, + data: '-----011000010111000001101001\r\nContent-Disposition: form-data; name="foo"; filename="src/fixtures/files/hello.txt"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name="bar"\r\n\r\nBonjour le monde\r\n-----011000010111000001101001--' +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/multipart-file.js b/src/targets/node/axios/fixtures/multipart-file.js new file mode 100644 index 000000000..8f53fc1eb --- /dev/null +++ b/src/targets/node/axios/fixtures/multipart-file.js @@ -0,0 +1,13 @@ +import axios from 'axios'; + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'content-type': 'multipart/form-data; boundary=---011000010111000001101001'}, + data: '-----011000010111000001101001\r\nContent-Disposition: form-data; name="foo"; filename="src/fixtures/files/hello.txt"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--' +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/multipart-form-data-no-params.js b/src/targets/node/axios/fixtures/multipart-form-data-no-params.js new file mode 100644 index 000000000..57e424c87 --- /dev/null +++ b/src/targets/node/axios/fixtures/multipart-form-data-no-params.js @@ -0,0 +1,12 @@ +import axios from 'axios'; + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'Content-Type': 'multipart/form-data'} +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/multipart-form-data.js b/src/targets/node/axios/fixtures/multipart-form-data.js new file mode 100644 index 000000000..45f7a10fb --- /dev/null +++ b/src/targets/node/axios/fixtures/multipart-form-data.js @@ -0,0 +1,13 @@ +import axios from 'axios'; + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'Content-Type': 'multipart/form-data; boundary=---011000010111000001101001'}, + data: '-----011000010111000001101001\r\nContent-Disposition: form-data; name="foo"\r\n\r\nbar\r\n-----011000010111000001101001--' +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/nested.js b/src/targets/node/axios/fixtures/nested.js new file mode 100644 index 000000000..62373db83 --- /dev/null +++ b/src/targets/node/axios/fixtures/nested.js @@ -0,0 +1,11 @@ +import axios from 'axios'; + +const options = { + method: 'GET', + url: 'https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value' +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/postdata-malformed.js b/src/targets/node/axios/fixtures/postdata-malformed.js new file mode 100644 index 000000000..f40deb9ed --- /dev/null +++ b/src/targets/node/axios/fixtures/postdata-malformed.js @@ -0,0 +1,12 @@ +import axios from 'axios'; + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'content-type': 'application/json'} +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/query-encoded.js b/src/targets/node/axios/fixtures/query-encoded.js new file mode 100644 index 000000000..c53a743a0 --- /dev/null +++ b/src/targets/node/axios/fixtures/query-encoded.js @@ -0,0 +1,11 @@ +import axios from 'axios'; + +const options = { + method: 'GET', + url: 'https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00' +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/query.js b/src/targets/node/axios/fixtures/query.js new file mode 100644 index 000000000..7833a75b3 --- /dev/null +++ b/src/targets/node/axios/fixtures/query.js @@ -0,0 +1,11 @@ +import axios from 'axios'; + +const options = { + method: 'GET', + url: 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value' +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/short.js b/src/targets/node/axios/fixtures/short.js new file mode 100644 index 000000000..ba835ded4 --- /dev/null +++ b/src/targets/node/axios/fixtures/short.js @@ -0,0 +1,8 @@ +import axios from 'axios'; + +const options = {method: 'GET', url: 'https://httpbin.org/anything'}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/axios/fixtures/text-plain.js b/src/targets/node/axios/fixtures/text-plain.js new file mode 100644 index 000000000..dbe78d903 --- /dev/null +++ b/src/targets/node/axios/fixtures/text-plain.js @@ -0,0 +1,13 @@ +import axios from 'axios'; + +const options = { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: {'content-type': 'text/plain'}, + data: 'Hello World' +}; + +axios + .request(options) + .then(res => console.log(res.data)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/client.ts b/src/targets/node/fetch/client.ts new file mode 100644 index 000000000..a5b8a2947 --- /dev/null +++ b/src/targets/node/fetch/client.ts @@ -0,0 +1,146 @@ +import type { Client } from '../../index.js'; + +import stringifyObject from 'stringify-object'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { getHeaderName } from '../../../helpers/headers.js'; + +export const fetch: Client = { + info: { + key: 'fetch', + title: 'fetch', + link: 'https://nodejs.org/docs/latest/api/globals.html#fetch', + description: 'Perform asynchronous HTTP requests with the Fetch API', + extname: '.js', + }, + convert: ({ method, fullUrl, postData, headersObj, cookies }, options) => { + const opts = { + indent: ' ', + ...options, + }; + + let includeFS = false; + const { blank, push, join, unshift } = new CodeBuilder({ indent: opts.indent }); + + const url = fullUrl; + const reqOpts: Record = { + method, + }; + + if (Object.keys(headersObj).length) { + reqOpts.headers = headersObj; + } + + switch (postData.mimeType) { + case 'application/x-www-form-urlencoded': + push('const encodedParams = new URLSearchParams();'); + + postData.params?.forEach(param => { + push(`encodedParams.set('${param.name}', '${param.value}');`); + }); + + reqOpts.body = 'encodedParams'; + blank(); + break; + + case 'application/json': + if (postData.jsonObj) { + // Though `fetch` doesn't accept JSON objects in the `body` option we're going to + // stringify it when we add this into the snippet further down. + reqOpts.body = postData.jsonObj; + } + break; + + case 'multipart/form-data': { + if (!postData.params) { + break; + } + + // The FormData API automatically adds a `Content-Type` header for `multipart/form-data` content and if we add our own here data won't be correctly transmitted. + const contentTypeHeader = getHeaderName(headersObj, 'content-type'); + if (contentTypeHeader) { + delete headersObj[contentTypeHeader]; + } + + push('const formData = new FormData();'); + + postData.params.forEach(param => { + if (!param.fileName && !param.fileName && !param.contentType) { + push(`formData.append('${param.name}', '${param.value}');`); + return; + } + + if (param.fileName) { + includeFS = true; + + // Whenever we drop support for Node 18 we can change this blob work to use + // `fs.openAsBlob('filename')`. + push( + `formData.append('${param.name}', await new Response(fs.createReadStream('${param.fileName}')).blob());`, + ); + } + }); + + reqOpts.body = 'formData'; + blank(); + break; + } + + default: + if (postData.text) { + reqOpts.body = postData.text; + } + } + + // construct cookies argument + if (cookies.length) { + const cookiesString = cookies + .map(({ name, value }) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`) + .join('; '); + if (reqOpts.headers) { + reqOpts.headers.cookie = cookiesString; + } else { + reqOpts.headers = {}; + reqOpts.headers.cookie = cookiesString; + } + } + + push(`const url = '${url}';`); + + // If we ultimately don't have any headers to send then we shouldn't add an empty object into the request options. + if (reqOpts.headers && !Object.keys(reqOpts.headers).length) { + delete reqOpts.headers; + } + + const stringifiedOptions = stringifyObject(reqOpts, { + indent: ' ', + inlineCharacterLimit: 80, + + // The Fetch API body only accepts string parameters, but stringified JSON can be difficult to + // read, so we keep the object as a literal and use this transform function to wrap the literal + // in a `JSON.stringify` call. + transform: (object, property, originalResult) => { + if (property === 'body' && postData.mimeType === 'application/json') { + return `JSON.stringify(${originalResult})`; + } + + return originalResult; + }, + }); + push(`const options = ${stringifiedOptions};`); + blank(); + + if (includeFS) { + unshift("import fs from 'fs';\n"); + } + + push('fetch(url, options)'); + push('.then(res => res.json())', 1); + push('.then(json => console.log(json))', 1); + push('.catch(err => console.error(err));', 1); + + return join() + .replace(/'encodedParams'/, 'encodedParams') + .replace(/'formData'/, 'formData'); + }, +}; diff --git a/src/targets/node/fetch/fixtures/application-form-encoded.js b/src/targets/node/fetch/fixtures/application-form-encoded.js new file mode 100644 index 000000000..9c6404a2b --- /dev/null +++ b/src/targets/node/fetch/fixtures/application-form-encoded.js @@ -0,0 +1,15 @@ +const encodedParams = new URLSearchParams(); +encodedParams.set('foo', 'bar'); +encodedParams.set('hello', 'world'); + +const url = 'https://httpbin.org/anything'; +const options = { + method: 'POST', + headers: {'content-type': 'application/x-www-form-urlencoded'}, + body: encodedParams +}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/application-json.js b/src/targets/node/fetch/fixtures/application-json.js new file mode 100644 index 000000000..73489d7b6 --- /dev/null +++ b/src/targets/node/fetch/fixtures/application-json.js @@ -0,0 +1,18 @@ +const url = 'https://httpbin.org/anything'; +const options = { + method: 'POST', + headers: {'content-type': 'application/json'}, + body: JSON.stringify({ + number: 1, + string: 'f"oo', + arr: [1, 2, 3], + nested: {a: 'b'}, + arr_mix: [1, 'a', {arr_mix_nested: []}], + boolean: false + }) +}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/cookies.js b/src/targets/node/fetch/fixtures/cookies.js new file mode 100644 index 000000000..ab9629359 --- /dev/null +++ b/src/targets/node/fetch/fixtures/cookies.js @@ -0,0 +1,7 @@ +const url = 'https://httpbin.org/cookies'; +const options = {method: 'GET', headers: {cookie: 'foo=bar; bar=baz'}}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/custom-method.js b/src/targets/node/fetch/fixtures/custom-method.js new file mode 100644 index 000000000..781a8c46c --- /dev/null +++ b/src/targets/node/fetch/fixtures/custom-method.js @@ -0,0 +1,7 @@ +const url = 'https://httpbin.org/anything'; +const options = {method: 'PROPFIND'}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/full.js b/src/targets/node/fetch/fixtures/full.js new file mode 100644 index 000000000..d33052c27 --- /dev/null +++ b/src/targets/node/fetch/fixtures/full.js @@ -0,0 +1,18 @@ +const encodedParams = new URLSearchParams(); +encodedParams.set('foo', 'bar'); + +const url = 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value'; +const options = { + method: 'POST', + headers: { + accept: 'application/json', + 'content-type': 'application/x-www-form-urlencoded', + cookie: 'foo=bar; bar=baz' + }, + body: encodedParams +}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/headers.js b/src/targets/node/fetch/fixtures/headers.js new file mode 100644 index 000000000..edf72d140 --- /dev/null +++ b/src/targets/node/fetch/fixtures/headers.js @@ -0,0 +1,15 @@ +const url = 'https://httpbin.org/headers'; +const options = { + method: 'GET', + headers: { + accept: 'application/json', + 'x-foo': 'Bar', + 'x-bar': 'Foo', + 'quoted-value': '"quoted" \'string\'' + } +}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/http-insecure.js b/src/targets/node/fetch/fixtures/http-insecure.js new file mode 100644 index 000000000..5a9ed7362 --- /dev/null +++ b/src/targets/node/fetch/fixtures/http-insecure.js @@ -0,0 +1,7 @@ +const url = 'http://httpbin.org/anything'; +const options = {method: 'GET'}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/jsonObj-multiline.js b/src/targets/node/fetch/fixtures/jsonObj-multiline.js new file mode 100644 index 000000000..a9b92d58e --- /dev/null +++ b/src/targets/node/fetch/fixtures/jsonObj-multiline.js @@ -0,0 +1,11 @@ +const url = 'https://httpbin.org/anything'; +const options = { + method: 'POST', + headers: {'content-type': 'application/json'}, + body: JSON.stringify({foo: 'bar'}) +}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/jsonObj-null-value.js b/src/targets/node/fetch/fixtures/jsonObj-null-value.js new file mode 100644 index 000000000..4eb4892fb --- /dev/null +++ b/src/targets/node/fetch/fixtures/jsonObj-null-value.js @@ -0,0 +1,11 @@ +const url = 'https://httpbin.org/anything'; +const options = { + method: 'POST', + headers: {'content-type': 'application/json'}, + body: JSON.stringify({foo: null}) +}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/multipart-data.js b/src/targets/node/fetch/fixtures/multipart-data.js new file mode 100644 index 000000000..ca964a322 --- /dev/null +++ b/src/targets/node/fetch/fixtures/multipart-data.js @@ -0,0 +1,13 @@ +import fs from 'fs'; + +const formData = new FormData(); +formData.append('foo', await new Response(fs.createReadStream('src/fixtures/files/hello.txt')).blob()); +formData.append('bar', 'Bonjour le monde'); + +const url = 'https://httpbin.org/anything'; +const options = {method: 'POST', body: formData}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/multipart-file.js b/src/targets/node/fetch/fixtures/multipart-file.js new file mode 100644 index 000000000..02fc790b9 --- /dev/null +++ b/src/targets/node/fetch/fixtures/multipart-file.js @@ -0,0 +1,12 @@ +import fs from 'fs'; + +const formData = new FormData(); +formData.append('foo', await new Response(fs.createReadStream('src/fixtures/files/hello.txt')).blob()); + +const url = 'https://httpbin.org/anything'; +const options = {method: 'POST', body: formData}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/multipart-form-data-no-params.js b/src/targets/node/fetch/fixtures/multipart-form-data-no-params.js new file mode 100644 index 000000000..053f56470 --- /dev/null +++ b/src/targets/node/fetch/fixtures/multipart-form-data-no-params.js @@ -0,0 +1,7 @@ +const url = 'https://httpbin.org/anything'; +const options = {method: 'POST', headers: {'Content-Type': 'multipart/form-data'}}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/multipart-form-data.js b/src/targets/node/fetch/fixtures/multipart-form-data.js new file mode 100644 index 000000000..874d6b15a --- /dev/null +++ b/src/targets/node/fetch/fixtures/multipart-form-data.js @@ -0,0 +1,10 @@ +const formData = new FormData(); +formData.append('foo', 'bar'); + +const url = 'https://httpbin.org/anything'; +const options = {method: 'POST', body: formData}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/nested.js b/src/targets/node/fetch/fixtures/nested.js new file mode 100644 index 000000000..af78c1dac --- /dev/null +++ b/src/targets/node/fetch/fixtures/nested.js @@ -0,0 +1,7 @@ +const url = 'https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value'; +const options = {method: 'GET'}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/postdata-malformed.js b/src/targets/node/fetch/fixtures/postdata-malformed.js new file mode 100644 index 000000000..76c3abf25 --- /dev/null +++ b/src/targets/node/fetch/fixtures/postdata-malformed.js @@ -0,0 +1,7 @@ +const url = 'https://httpbin.org/anything'; +const options = {method: 'POST', headers: {'content-type': 'application/json'}}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/query-encoded.js b/src/targets/node/fetch/fixtures/query-encoded.js new file mode 100644 index 000000000..5bb1a33ae --- /dev/null +++ b/src/targets/node/fetch/fixtures/query-encoded.js @@ -0,0 +1,7 @@ +const url = 'https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00'; +const options = {method: 'GET'}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/query.js b/src/targets/node/fetch/fixtures/query.js new file mode 100644 index 000000000..d18e8763b --- /dev/null +++ b/src/targets/node/fetch/fixtures/query.js @@ -0,0 +1,7 @@ +const url = 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value'; +const options = {method: 'GET'}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/short.js b/src/targets/node/fetch/fixtures/short.js new file mode 100644 index 000000000..1deb47f08 --- /dev/null +++ b/src/targets/node/fetch/fixtures/short.js @@ -0,0 +1,7 @@ +const url = 'https://httpbin.org/anything'; +const options = {method: 'GET'}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/fetch/fixtures/text-plain.js b/src/targets/node/fetch/fixtures/text-plain.js new file mode 100644 index 000000000..aa55a9300 --- /dev/null +++ b/src/targets/node/fetch/fixtures/text-plain.js @@ -0,0 +1,7 @@ +const url = 'https://httpbin.org/anything'; +const options = {method: 'POST', headers: {'content-type': 'text/plain'}, body: 'Hello World'}; + +fetch(url, options) + .then(res => res.json()) + .then(json => console.log(json)) + .catch(err => console.error(err)); \ No newline at end of file diff --git a/src/targets/node/index.js b/src/targets/node/index.js deleted file mode 100644 index 1e4d9e352..000000000 --- a/src/targets/node/index.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict' - -module.exports = { - info: { - key: 'node', - title: 'Node.js', - extname: '.js', - default: 'native' - }, - - native: require('./native'), - request: require('./request'), - unirest: require('./unirest') -} diff --git a/src/targets/node/native.js b/src/targets/node/native.js deleted file mode 100644 index 3d0f18923..000000000 --- a/src/targets/node/native.js +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @description - * HTTP code snippet generator for native Node.js. - * - * @author - * @AhmadNassri - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ' - }, options) - - var code = new CodeBuilder(opts.indent) - - var reqOpts = { - method: source.method, - hostname: source.uriObj.hostname, - port: source.uriObj.port, - path: source.uriObj.path, - headers: source.allHeaders - } - - code.push('var http = require("%s");', source.uriObj.protocol.replace(':', '')) - - code.blank() - .push('var options = %s;', JSON.stringify(reqOpts, null, opts.indent)) - .blank() - .push('var req = http.request(options, function (res) {') - .push(1, 'var chunks = [];') - .blank() - .push(1, 'res.on("data", function (chunk) {') - .push(2, 'chunks.push(chunk);') - .push(1, '});') - .blank() - .push(1, 'res.on("end", function () {') - .push(2, 'var body = Buffer.concat(chunks);') - .push(2, 'console.log(body.toString());') - .push(1, '});') - .push('});') - .blank() - - switch (source.postData.mimeType) { - case 'application/x-www-form-urlencoded': - if (source.postData.paramsObj) { - code.unshift('var qs = require("querystring");') - code.push('req.write(qs.stringify(%s));', util.inspect(source.postData.paramsObj, { - depth: null - })) - } - break - - case 'application/json': - if (source.postData.jsonObj) { - code.push('req.write(JSON.stringify(%s));', util.inspect(source.postData.jsonObj, { - depth: null - })) - } - break - - default: - if (source.postData.text) { - code.push('req.write(%s);', JSON.stringify(source.postData.text, null, opts.indent)) - } - } - - code.push('req.end();') - - return code.join() -} - -module.exports.info = { - key: 'native', - title: 'HTTP', - link: 'http://nodejs.org/api/http.html#http_http_request_options_callback', - description: 'Node.js native HTTP interface' -} diff --git a/src/targets/node/native/client.ts b/src/targets/node/native/client.ts new file mode 100644 index 000000000..498c5ffab --- /dev/null +++ b/src/targets/node/native/client.ts @@ -0,0 +1,89 @@ +/** + * @description + * HTTP code snippet generator for native Node.js. + * + * @author + * @AhmadNassri + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import stringifyObject from 'stringify-object'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; + +export const native: Client = { + info: { + key: 'native', + title: 'HTTP', + link: 'http://nodejs.org/api/http.html#http_http_request_options_callback', + description: 'Node.js native HTTP interface', + extname: '.cjs', + }, + convert: ({ uriObj, method, allHeaders, postData }, options = {}) => { + const { indent = ' ' } = options; + const { blank, join, push, unshift } = new CodeBuilder({ indent }); + + const reqOpts = { + method, + hostname: uriObj.hostname, + port: uriObj.port, + path: uriObj.path, + headers: allHeaders, + }; + + push(`const http = require('${uriObj.protocol?.replace(':', '')}');`); + + blank(); + push(`const options = ${stringifyObject(reqOpts, { indent })};`); + blank(); + push('const req = http.request(options, function (res) {'); + push('const chunks = [];', 1); + blank(); + push("res.on('data', function (chunk) {", 1); + push('chunks.push(chunk);', 2); + push('});', 1); + blank(); + push("res.on('end', function () {", 1); + push('const body = Buffer.concat(chunks);', 2); + push('console.log(body.toString());', 2); + push('});', 1); + push('});'); + blank(); + + switch (postData.mimeType) { + case 'application/x-www-form-urlencoded': + if (postData.paramsObj) { + unshift("const qs = require('querystring');"); + push( + `req.write(qs.stringify(${stringifyObject(postData.paramsObj, { + indent: ' ', + inlineCharacterLimit: 80, + })}));`, + ); + } + break; + + case 'application/json': + if (postData.jsonObj) { + push( + `req.write(JSON.stringify(${stringifyObject(postData.jsonObj, { + indent: ' ', + inlineCharacterLimit: 80, + })}));`, + ); + } + break; + + default: + if (postData.text) { + push(`req.write(${stringifyObject(postData.text, { indent })});`); + } + } + + push('req.end();'); + + return join(); + }, +}; diff --git a/src/targets/node/native/fixtures/application-form-encoded.cjs b/src/targets/node/native/fixtures/application-form-encoded.cjs new file mode 100644 index 000000000..057ff692f --- /dev/null +++ b/src/targets/node/native/fixtures/application-form-encoded.cjs @@ -0,0 +1,28 @@ +const qs = require('querystring'); +const http = require('https'); + +const options = { + method: 'POST', + hostname: 'httpbin.org', + port: null, + path: '/anything', + headers: { + 'content-type': 'application/x-www-form-urlencoded' + } +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.write(qs.stringify({foo: 'bar', hello: 'world'})); +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/application-json.cjs b/src/targets/node/native/fixtures/application-json.cjs new file mode 100644 index 000000000..5129f834c --- /dev/null +++ b/src/targets/node/native/fixtures/application-json.cjs @@ -0,0 +1,34 @@ +const http = require('https'); + +const options = { + method: 'POST', + hostname: 'httpbin.org', + port: null, + path: '/anything', + headers: { + 'content-type': 'application/json' + } +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.write(JSON.stringify({ + number: 1, + string: 'f"oo', + arr: [1, 2, 3], + nested: {a: 'b'}, + arr_mix: [1, 'a', {arr_mix_nested: []}], + boolean: false +})); +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/cookies.cjs b/src/targets/node/native/fixtures/cookies.cjs new file mode 100644 index 000000000..76e950855 --- /dev/null +++ b/src/targets/node/native/fixtures/cookies.cjs @@ -0,0 +1,26 @@ +const http = require('https'); + +const options = { + method: 'GET', + hostname: 'httpbin.org', + port: null, + path: '/cookies', + headers: { + cookie: 'foo=bar; bar=baz' + } +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/custom-method.cjs b/src/targets/node/native/fixtures/custom-method.cjs new file mode 100644 index 000000000..0640c9991 --- /dev/null +++ b/src/targets/node/native/fixtures/custom-method.cjs @@ -0,0 +1,24 @@ +const http = require('https'); + +const options = { + method: 'PROPFIND', + hostname: 'httpbin.org', + port: null, + path: '/anything', + headers: {} +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/full.cjs b/src/targets/node/native/fixtures/full.cjs new file mode 100644 index 000000000..dee3821b2 --- /dev/null +++ b/src/targets/node/native/fixtures/full.cjs @@ -0,0 +1,30 @@ +const qs = require('querystring'); +const http = require('https'); + +const options = { + method: 'POST', + hostname: 'httpbin.org', + port: null, + path: '/anything?foo=bar&foo=baz&baz=abc&key=value', + headers: { + cookie: 'foo=bar; bar=baz', + accept: 'application/json', + 'content-type': 'application/x-www-form-urlencoded' + } +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.write(qs.stringify({foo: 'bar'})); +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/headers.cjs b/src/targets/node/native/fixtures/headers.cjs new file mode 100644 index 000000000..80e694461 --- /dev/null +++ b/src/targets/node/native/fixtures/headers.cjs @@ -0,0 +1,29 @@ +const http = require('https'); + +const options = { + method: 'GET', + hostname: 'httpbin.org', + port: null, + path: '/headers', + headers: { + accept: 'application/json', + 'x-foo': 'Bar', + 'x-bar': 'Foo', + 'quoted-value': '"quoted" \'string\'' + } +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/http-insecure.cjs b/src/targets/node/native/fixtures/http-insecure.cjs new file mode 100644 index 000000000..c39f9a68e --- /dev/null +++ b/src/targets/node/native/fixtures/http-insecure.cjs @@ -0,0 +1,24 @@ +const http = require('http'); + +const options = { + method: 'GET', + hostname: 'httpbin.org', + port: null, + path: '/anything', + headers: {} +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/jsonObj-multiline.cjs b/src/targets/node/native/fixtures/jsonObj-multiline.cjs new file mode 100644 index 000000000..ba61989d1 --- /dev/null +++ b/src/targets/node/native/fixtures/jsonObj-multiline.cjs @@ -0,0 +1,27 @@ +const http = require('https'); + +const options = { + method: 'POST', + hostname: 'httpbin.org', + port: null, + path: '/anything', + headers: { + 'content-type': 'application/json' + } +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.write(JSON.stringify({foo: 'bar'})); +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/jsonObj-null-value.cjs b/src/targets/node/native/fixtures/jsonObj-null-value.cjs new file mode 100644 index 000000000..5a5648288 --- /dev/null +++ b/src/targets/node/native/fixtures/jsonObj-null-value.cjs @@ -0,0 +1,27 @@ +const http = require('https'); + +const options = { + method: 'POST', + hostname: 'httpbin.org', + port: null, + path: '/anything', + headers: { + 'content-type': 'application/json' + } +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.write(JSON.stringify({foo: null})); +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/multipart-data.cjs b/src/targets/node/native/fixtures/multipart-data.cjs new file mode 100644 index 000000000..9470e8ae1 --- /dev/null +++ b/src/targets/node/native/fixtures/multipart-data.cjs @@ -0,0 +1,27 @@ +const http = require('https'); + +const options = { + method: 'POST', + hostname: 'httpbin.org', + port: null, + path: '/anything', + headers: { + 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' + } +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.write('-----011000010111000001101001\r\nContent-Disposition: form-data; name="foo"; filename="src/fixtures/files/hello.txt"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name="bar"\r\n\r\nBonjour le monde\r\n-----011000010111000001101001--'); +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/multipart-file.cjs b/src/targets/node/native/fixtures/multipart-file.cjs new file mode 100644 index 000000000..aefa51da4 --- /dev/null +++ b/src/targets/node/native/fixtures/multipart-file.cjs @@ -0,0 +1,27 @@ +const http = require('https'); + +const options = { + method: 'POST', + hostname: 'httpbin.org', + port: null, + path: '/anything', + headers: { + 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' + } +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.write('-----011000010111000001101001\r\nContent-Disposition: form-data; name="foo"; filename="src/fixtures/files/hello.txt"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--'); +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/multipart-form-data-no-params.cjs b/src/targets/node/native/fixtures/multipart-form-data-no-params.cjs new file mode 100644 index 000000000..98bbf669a --- /dev/null +++ b/src/targets/node/native/fixtures/multipart-form-data-no-params.cjs @@ -0,0 +1,26 @@ +const http = require('https'); + +const options = { + method: 'POST', + hostname: 'httpbin.org', + port: null, + path: '/anything', + headers: { + 'Content-Type': 'multipart/form-data' + } +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/multipart-form-data.cjs b/src/targets/node/native/fixtures/multipart-form-data.cjs new file mode 100644 index 000000000..e914bad77 --- /dev/null +++ b/src/targets/node/native/fixtures/multipart-form-data.cjs @@ -0,0 +1,27 @@ +const http = require('https'); + +const options = { + method: 'POST', + hostname: 'httpbin.org', + port: null, + path: '/anything', + headers: { + 'Content-Type': 'multipart/form-data; boundary=---011000010111000001101001' + } +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.write('-----011000010111000001101001\r\nContent-Disposition: form-data; name="foo"\r\n\r\nbar\r\n-----011000010111000001101001--'); +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/nested.cjs b/src/targets/node/native/fixtures/nested.cjs new file mode 100644 index 000000000..9d0afd9e1 --- /dev/null +++ b/src/targets/node/native/fixtures/nested.cjs @@ -0,0 +1,24 @@ +const http = require('https'); + +const options = { + method: 'GET', + hostname: 'httpbin.org', + port: null, + path: '/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value', + headers: {} +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/postdata-malformed.cjs b/src/targets/node/native/fixtures/postdata-malformed.cjs new file mode 100644 index 000000000..78f3ca704 --- /dev/null +++ b/src/targets/node/native/fixtures/postdata-malformed.cjs @@ -0,0 +1,26 @@ +const http = require('https'); + +const options = { + method: 'POST', + hostname: 'httpbin.org', + port: null, + path: '/anything', + headers: { + 'content-type': 'application/json' + } +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/query-encoded.cjs b/src/targets/node/native/fixtures/query-encoded.cjs new file mode 100644 index 000000000..d57697168 --- /dev/null +++ b/src/targets/node/native/fixtures/query-encoded.cjs @@ -0,0 +1,24 @@ +const http = require('https'); + +const options = { + method: 'GET', + hostname: 'httpbin.org', + port: null, + path: '/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00', + headers: {} +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/query.cjs b/src/targets/node/native/fixtures/query.cjs new file mode 100644 index 000000000..74da137db --- /dev/null +++ b/src/targets/node/native/fixtures/query.cjs @@ -0,0 +1,24 @@ +const http = require('https'); + +const options = { + method: 'GET', + hostname: 'httpbin.org', + port: null, + path: '/anything?foo=bar&foo=baz&baz=abc&key=value', + headers: {} +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/short.cjs b/src/targets/node/native/fixtures/short.cjs new file mode 100644 index 000000000..b726546d8 --- /dev/null +++ b/src/targets/node/native/fixtures/short.cjs @@ -0,0 +1,24 @@ +const http = require('https'); + +const options = { + method: 'GET', + hostname: 'httpbin.org', + port: null, + path: '/anything', + headers: {} +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.end(); \ No newline at end of file diff --git a/src/targets/node/native/fixtures/text-plain.cjs b/src/targets/node/native/fixtures/text-plain.cjs new file mode 100644 index 000000000..4fb117878 --- /dev/null +++ b/src/targets/node/native/fixtures/text-plain.cjs @@ -0,0 +1,27 @@ +const http = require('https'); + +const options = { + method: 'POST', + hostname: 'httpbin.org', + port: null, + path: '/anything', + headers: { + 'content-type': 'text/plain' + } +}; + +const req = http.request(options, function (res) { + const chunks = []; + + res.on('data', function (chunk) { + chunks.push(chunk); + }); + + res.on('end', function () { + const body = Buffer.concat(chunks); + console.log(body.toString()); + }); +}); + +req.write('Hello World'); +req.end(); \ No newline at end of file diff --git a/src/targets/node/request.js b/src/targets/node/request.js deleted file mode 100644 index ea0330784..000000000 --- a/src/targets/node/request.js +++ /dev/null @@ -1,125 +0,0 @@ -/** - * @description - * HTTP code snippet generator for Node.js using Request. - * - * @author - * @AhmadNassri - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ' - }, options) - - var includeFS = false - var code = new CodeBuilder(opts.indent) - - code.push('var request = require("request");') - .blank() - - var reqOpts = { - method: source.method, - url: source.url - } - - if (Object.keys(source.queryObj).length) { - reqOpts.qs = source.queryObj - } - - if (Object.keys(source.headersObj).length) { - reqOpts.headers = source.headersObj - } - - switch (source.postData.mimeType) { - case 'application/x-www-form-urlencoded': - reqOpts.form = source.postData.paramsObj - break - - case 'application/json': - if (source.postData.jsonObj) { - reqOpts.body = source.postData.jsonObj - reqOpts.json = true - } - break - - case 'multipart/form-data': - reqOpts.formData = {} - - source.postData.params.forEach(function (param) { - var attachement = {} - - if (!param.fileName && !param.fileName && !param.contentType) { - reqOpts.formData[param.name] = param.value - return - } - - if (param.fileName && !param.value) { - includeFS = true - - attachement.value = 'fs.createReadStream("' + param.fileName + '")' - } else if (param.value) { - attachement.value = param.value - } - - if (param.fileName) { - attachement.options = { - filename: param.fileName, - contentType: param.contentType ? param.contentType : null - } - } - - reqOpts.formData[param.name] = attachement - }) - break - - default: - if (source.postData.text) { - reqOpts.body = source.postData.text - } - } - - // construct cookies argument - if (source.cookies.length) { - reqOpts.jar = 'JAR' - - code.push('var jar = request.jar();') - - var url = source.url - - source.cookies.forEach(function (cookie) { - code.push('jar.setCookie(request.cookie("%s=%s"), "%s");', encodeURIComponent(cookie.name), encodeURIComponent(cookie.value), url) - }) - code.blank() - } - - if (includeFS) { - code.unshift('var fs = require("fs");') - } - - code.push('var options = %s;', util.inspect(reqOpts, { depth: null })) - .blank() - - code.push(util.format('request(options, %s', 'function (error, response, body) {')) - - .push(1, 'if (error) throw new Error(error);') - .blank() - .push(1, 'console.log(body);') - .push('});') - .blank() - - return code.join().replace('"JAR"', 'jar').replace(/"fs\.createReadStream\(\\\"(.+)\\\"\)\"/, 'fs.createReadStream("$1")') -} - -module.exports.info = { - key: 'request', - title: 'Request', - link: 'https://github.com/request/request', - description: 'Simplified HTTP request client' -} diff --git a/src/targets/node/target.ts b/src/targets/node/target.ts new file mode 100644 index 000000000..77307bfd8 --- /dev/null +++ b/src/targets/node/target.ts @@ -0,0 +1,19 @@ +import type { Target } from '../index.js'; + +import { axios } from './axios/client.js'; +import { fetch } from './fetch/client.js'; +import { native } from './native/client.js'; + +export const node: Target = { + info: { + key: 'node', + title: 'Node.js', + default: 'fetch', + cli: 'node %s', + }, + clientsById: { + native, + axios, + fetch, + }, +}; diff --git a/src/targets/node/unirest.js b/src/targets/node/unirest.js deleted file mode 100644 index daa4bf894..000000000 --- a/src/targets/node/unirest.js +++ /dev/null @@ -1,116 +0,0 @@ -/** - * @description - * HTTP code snippet generator for Node.js using Unirest. - * - * @author - * @AhmadNassri - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ' - }, options) - - var includeFS = false - var code = new CodeBuilder(opts.indent) - - code.push('var unirest = require("unirest");') - .blank() - .push('var req = unirest("%s", "%s");', source.method, source.url) - .blank() - - if (source.cookies.length) { - code.push('var CookieJar = unirest.jar();') - - source.cookies.forEach(function (cookie) { - code.push('CookieJar.add("%s=%s","%s");', encodeURIComponent(cookie.name), encodeURIComponent(cookie.value), source.url) - }) - - code.push('req.jar(CookieJar);') - .blank() - } - - if (Object.keys(source.queryObj).length) { - code.push('req.query(%s);', JSON.stringify(source.queryObj, null, opts.indent)) - .blank() - } - - if (Object.keys(source.headersObj).length) { - code.push('req.headers(%s);', JSON.stringify(source.headersObj, null, opts.indent)) - .blank() - } - - switch (source.postData.mimeType) { - case 'application/x-www-form-urlencoded': - if (source.postData.paramsObj) { - code.push('req.form(%s);', JSON.stringify(source.postData.paramsObj, null, opts.indent)) - } - break - - case 'application/json': - if (source.postData.jsonObj) { - code.push('req.type("json");') - .push('req.send(%s);', JSON.stringify(source.postData.jsonObj, null, opts.indent)) - } - break - - case 'multipart/form-data': - var multipart = [] - - source.postData.params.forEach(function (param) { - var part = {} - - if (param.fileName && !param.value) { - includeFS = true - - part.body = 'fs.createReadStream("' + param.fileName + '")' - } else if (param.value) { - part.body = param.value - } - - if (part.body) { - if (param.contentType) { - part['content-type'] = param.contentType - } - - multipart.push(part) - } - }) - - code.push('req.multipart(%s);', JSON.stringify(multipart, null, opts.indent)) - break - - default: - if (source.postData.text) { - code.push(opts.indent + 'req.send(%s);', JSON.stringify(source.postData.text, null, opts.indent)) - } - } - - if (includeFS) { - code.unshift('var fs = require("fs");') - } - - code.blank() - .push('req.end(function (res) {') - .push(1, 'if (res.error) throw new Error(res.error);') - .blank() - .push(1, 'console.log(res.body);') - .push('});') - .blank() - - return code.join().replace(/"fs\.createReadStream\(\\\"(.+)\\\"\)\"/, 'fs.createReadStream("$1")') -} - -module.exports.info = { - key: 'unirest', - title: 'Unirest', - link: 'http://unirest.io/nodejs.html', - description: 'Lightweight HTTP Request Client Library' -} diff --git a/src/targets/objc/helpers.js b/src/targets/objc/helpers.js deleted file mode 100644 index 111429157..000000000 --- a/src/targets/objc/helpers.js +++ /dev/null @@ -1,73 +0,0 @@ -'use strict' - -var util = require('util') - -module.exports = { - /** - * Create an string of given length filled with blank spaces - * - * @param {number} length Length of the array to return - * @return {string} - */ - blankString: function (length) { - return Array.apply(null, new Array(length)).map(String.prototype.valueOf, ' ').join('') - }, - - /** - * Create a string corresponding to a valid declaration and initialization of an Objective-C object literal. - * - * @param {string} nsClass Class of the litteral - * @param {string} name Desired name of the instance - * @param {Object} parameters Key-value object of parameters to translate to an Objective-C object litearal - * @param {boolean} indent If true, will declare the litteral by indenting each new key/value pair. - * @return {string} A valid Objective-C declaration and initialization of an Objective-C object litteral. - * - * @example - * nsDeclaration('NSDictionary', 'params', {a: 'b', c: 'd'}, true) - * // returns: - * NSDictionary *params = @{ @"a": @"b", - * @"c": @"d" }; - * - * nsDeclaration('NSDictionary', 'params', {a: 'b', c: 'd'}) - * // returns: - * NSDictionary *params = @{ @"a": @"b", @"c": @"d" }; - */ - nsDeclaration: function (nsClass, name, parameters, indent) { - var opening = nsClass + ' *' + name + ' = ' - var literal = this.literalRepresentation(parameters, indent ? opening.length : undefined) - return opening + literal + ';' - }, - - /** - * Create a valid Objective-C string of a literal value according to its type. - * - * @param {*} value Any JavaScript literal - * @return {string} - */ - literalRepresentation: function (value, indentation) { - var join = indentation === undefined ? ', ' : ',\n ' + this.blankString(indentation) - - switch (Object.prototype.toString.call(value)) { - case '[object Number]': - return '@' + value - case '[object Array]': - var values_representation = value.map(function (v) { - return this.literalRepresentation(v) - }.bind(this)) - return '@[ ' + values_representation.join(join) + ' ]' - case '[object Object]': - var keyValuePairs = [] - for (var k in value) { - keyValuePairs.push(util.format('@"%s": %s', k, this.literalRepresentation(value[k]))) - } - return '@{ ' + keyValuePairs.join(join) + ' }' - case '[object Boolean]': - return value ? '@YES' : '@NO' - default: - if (value === null || value === undefined) { - return '' - } - return '@"' + value.toString().replace(/"/g, '\\"') + '"' - } - } -} diff --git a/src/targets/objc/helpers.ts b/src/targets/objc/helpers.ts new file mode 100644 index 000000000..0f11335ab --- /dev/null +++ b/src/targets/objc/helpers.ts @@ -0,0 +1,60 @@ +/** + * Create a string corresponding to a valid declaration and initialization of an Objective-C object literal. + * + * @param nsClass Class of the litteral + * @param name Desired name of the instance + * @param parameters Key-value object of parameters to translate to an Objective-C object litearal + * @param indent If true, will declare the litteral by indenting each new key/value pair. + * @return A valid Objective-C declaration and initialization of an Objective-C object litteral. + * + * @example + * nsDeclaration('NSDictionary', 'params', {a: 'b', c: 'd'}, true) + * // returns: + * NSDictionary *params = @{ @"a": @"b", + * @"c": @"d" }; + * + * nsDeclaration('NSDictionary', 'params', {a: 'b', c: 'd'}) + * // returns: + * NSDictionary *params = @{ @"a": @"b", @"c": @"d" }; + */ +export const nsDeclaration = (nsClass: string, name: string, parameters: Record, indent?: boolean) => { + const opening = `${nsClass} *${name} = `; + const literal = literalRepresentation(parameters, indent ? opening.length : undefined); + return `${opening}${literal};`; +}; + +/** + * Create a valid Objective-C string of a literal value according to its type. + * + * @param value Any JavaScript literal + */ +export const literalRepresentation = (value: any, indentation?: number): string => { + const join = indentation === undefined ? ', ' : `,\n ${' '.repeat(indentation)}`; + + switch (Object.prototype.toString.call(value)) { + case '[object Number]': + return `@${value}`; + + case '[object Array]': { + const valuesRepresentation = value.map((val: any) => literalRepresentation(val)); + return `@[ ${valuesRepresentation.join(join)} ]`; + } + + case '[object Object]': { + const keyValuePairs: string[] = []; + Object.keys(value).forEach(key => { + keyValuePairs.push(`@"${key}": ${literalRepresentation(value[key])}`); + }); + return `@{ ${keyValuePairs.join(join)} }`; + } + + case '[object Boolean]': + return value ? '@YES' : '@NO'; + + default: + if (value === null || value === undefined) { + return ''; + } + return `@"${value.toString().replace(/"/g, '\\"')}"`; + } +}; diff --git a/src/targets/objc/index.js b/src/targets/objc/index.js deleted file mode 100644 index 4f7d2550f..000000000 --- a/src/targets/objc/index.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict' - -module.exports = { - info: { - key: 'objc', - title: 'Objective-C', - extname: '.m', - default: 'nsurlsession' - }, - - nsurlsession: require('./nsurlsession') -} diff --git a/src/targets/objc/nsurlsession.js b/src/targets/objc/nsurlsession.js deleted file mode 100644 index 1d68c271e..000000000 --- a/src/targets/objc/nsurlsession.js +++ /dev/null @@ -1,136 +0,0 @@ -/** - * @description - * HTTP code snippet generator for Objective-C using NSURLSession. - * - * @author - * @thibaultCha - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var util = require('util') -var helpers = require('./helpers') -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ', - pretty: true, - timeout: '10' - }, options) - - var code = new CodeBuilder(opts.indent) - // Markers for headers to be created as litteral objects and later be set on the NSURLRequest if exist - var req = { - hasHeaders: false, - hasBody: false - } - - // We just want to make sure people understand that is the only dependency - code.push('#import ') - - if (Object.keys(source.allHeaders).length) { - req.hasHeaders = true - code.blank() - .push(helpers.nsDeclaration('NSDictionary', 'headers', source.allHeaders, opts.pretty)) - } - - if (source.postData.text || source.postData.jsonObj || source.postData.params) { - req.hasBody = true - - switch (source.postData.mimeType) { - case 'application/x-www-form-urlencoded': - // By appending parameters one by one in the resulting snippet, - // we make it easier for the user to edit it according to his or her needs after pasting. - // The user can just add/remove lines adding/removing body parameters. - code.blank() - .push('NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"%s=%s" dataUsingEncoding:NSUTF8StringEncoding]];', - source.postData.params[0].name, source.postData.params[0].value) - for (var i = 1, len = source.postData.params.length; i < len; i++) { - code.push('[postData appendData:[@"&%s=%s" dataUsingEncoding:NSUTF8StringEncoding]];', - source.postData.params[i].name, source.postData.params[i].value) - } - break - - case 'application/json': - if (source.postData.jsonObj) { - code.push(helpers.nsDeclaration('NSDictionary', 'parameters', source.postData.jsonObj, opts.pretty)) - .blank() - .push('NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];') - } - break - - case 'multipart/form-data': - // By appending multipart parameters one by one in the resulting snippet, - // we make it easier for the user to edit it according to his or her needs after pasting. - // The user can just edit the parameters NSDictionary or put this part of a snippet in a multipart builder method. - code.push(helpers.nsDeclaration('NSArray', 'parameters', source.postData.params, opts.pretty)) - .push('NSString *boundary = @"%s";', source.postData.boundary) - .blank() - .push('NSError *error;') - .push('NSMutableString *body = [NSMutableString string];') - .push('for (NSDictionary *param in parameters) {') - .push(1, '[body appendFormat:@"--%@\\r\\n", boundary];') - .push(1, 'if (param[@"fileName"]) {') - .push(2, '[body appendFormat:@"Content-Disposition:form-data; name=\\"%@\\"; filename=\\"%@\\"\\r\\n", param[@"name"], param[@"fileName"]];') - .push(2, '[body appendFormat:@"Content-Type: %@\\r\\n\\r\\n", param[@"contentType"]];') - .push(2, '[body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSUTF8StringEncoding error:&error]];') - .push(2, 'if (error) {') - .push(3, 'NSLog(@"%@", error);') - .push(2, '}') - .push(1, '} else {') - .push(2, '[body appendFormat:@"Content-Disposition:form-data; name=\\"%@\\"\\r\\n\\r\\n", param[@"name"]];') - .push(2, '[body appendFormat:@"%@", param[@"value"]];') - .push(1, '}') - .push('}') - .push('[body appendFormat:@"\\r\\n--%@--\\r\\n", boundary];') - .push('NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];') - break - - default: - code.blank() - .push('NSData *postData = [[NSData alloc] initWithData:[@"' + source.postData.text + '" dataUsingEncoding:NSUTF8StringEncoding]];') - } - } - - code.blank() - .push('NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"' + source.fullUrl + '"]') - // NSURLRequestUseProtocolCachePolicy is the default policy, let's just always set it to avoid confusion. - .push(' cachePolicy:NSURLRequestUseProtocolCachePolicy') - .push(' timeoutInterval:' + parseInt(opts.timeout, 10).toFixed(1) + '];') - .push('[request setHTTPMethod:@"' + source.method + '"];') - - if (req.hasHeaders) { - code.push('[request setAllHTTPHeaderFields:headers];') - } - - if (req.hasBody) { - code.push('[request setHTTPBody:postData];') - } - - code.blank() - // Retrieving the shared session will be less verbose than creating a new one. - .push('NSURLSession *session = [NSURLSession sharedSession];') - .push('NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request') - .push(' completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {') - .push(1, ' if (error) {') - .push(2, ' NSLog(@"%@", error);') - .push(1, ' } else {') - // Casting the NSURLResponse to NSHTTPURLResponse so the user can see the status . - .push(2, ' NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;') - .push(2, ' NSLog(@"%@", httpResponse);') - .push(1, ' }') - .push(' }];') - .push('[dataTask resume];') - - return code.join() -} - -module.exports.info = { - key: 'nsurlsession', - title: 'NSURLSession', - link: 'https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/index.html', - description: 'Foundation\'s NSURLSession request' -} diff --git a/src/targets/objc/nsurlsession/client.test.ts b/src/targets/objc/nsurlsession/client.test.ts new file mode 100644 index 000000000..4f20ded38 --- /dev/null +++ b/src/targets/objc/nsurlsession/client.test.ts @@ -0,0 +1,37 @@ +import type { Request } from '../../../index.js'; + +import full from '../../../fixtures/requests/full.cjs'; +import jsonNullValue from '../../../fixtures/requests/jsonObj-null-value.cjs'; +import short from '../../../fixtures/requests/short.cjs'; +import { runCustomFixtures } from '../../../fixtures/runCustomFixtures.js'; + +runCustomFixtures({ + targetId: 'objc', + clientId: 'nsurlsession', + tests: [ + { + it: 'should support an indent option', + input: short.log.entries[0].request as Request, + options: { indent: ' ' }, + expected: 'indent-option.m', + }, + { + it: 'should support a timeout option', + input: short.log.entries[0].request as Request, + options: { timeout: 5 }, + expected: 'timeout-option.m', + }, + { + it: 'should support pretty option', + input: full.log.entries[0].request as Request, + options: { pretty: false }, + expected: 'pretty-option.m', + }, + { + it: 'should support json object with null value', + input: jsonNullValue as unknown as Request, + options: { pretty: false }, + expected: 'json-with-null-value.m', + }, + ], +}); diff --git a/src/targets/objc/nsurlsession/client.ts b/src/targets/objc/nsurlsession/client.ts new file mode 100644 index 000000000..776df06f1 --- /dev/null +++ b/src/targets/objc/nsurlsession/client.ts @@ -0,0 +1,165 @@ +/** + * @description + * HTTP code snippet generator for Objective-C using NSURLSession. + * + * @author + * @thibaultCha + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { nsDeclaration } from '../helpers.js'; + +export interface NsurlsessionOptions { + pretty?: boolean; + timeout?: number; +} + +export const nsurlsession: Client = { + info: { + key: 'nsurlsession', + title: 'NSURLSession', + link: 'https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/index.html', + description: "Foundation's NSURLSession request", + extname: '.m', + }, + convert: ({ allHeaders, postData, method, fullUrl }, options) => { + const opts = { + indent: ' ', + pretty: true, + timeout: 10, + ...options, + }; + + const { push, join, blank } = new CodeBuilder({ indent: opts.indent }); + // Markers for headers to be created as literal objects and later be set on the NSURLRequest if exist + const req = { + hasHeaders: false, + hasBody: false, + }; + + // We just want to make sure people understand that is the only dependency + push('#import '); + + if (Object.keys(allHeaders).length) { + req.hasHeaders = true; + blank(); + push(nsDeclaration('NSDictionary', 'headers', allHeaders, opts.pretty)); + } + + if (postData.text || postData.jsonObj || postData.params) { + req.hasBody = true; + + switch (postData.mimeType) { + case 'application/x-www-form-urlencoded': + if (postData.params?.length) { + // By appending parameters one by one in the resulting snippet, + // we make it easier for the user to edit it according to his or her needs after pasting. + // The user can just add/remove lines adding/removing body parameters. + blank(); + + const [head, ...tail] = postData.params; + push( + `NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"${head.name}=${head.value}" dataUsingEncoding:NSUTF8StringEncoding]];`, + ); + + tail.forEach(({ name, value }) => { + push(`[postData appendData:[@"&${name}=${value}" dataUsingEncoding:NSUTF8StringEncoding]];`); + }); + } else { + req.hasBody = false; + } + break; + + case 'application/json': + if (postData.jsonObj) { + push(nsDeclaration('NSDictionary', 'parameters', postData.jsonObj, opts.pretty)); + blank(); + push('NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];'); + } + break; + + case 'multipart/form-data': + // By appending multipart parameters one by one in the resulting snippet, + // we make it easier for the user to edit it according to his or her needs after pasting. + // The user can just edit the parameters NSDictionary or put this part of a snippet in a multipart builder method. + push(nsDeclaration('NSArray', 'parameters', postData.params || [], opts.pretty)); + push(`NSString *boundary = @"${postData.boundary}";`); + blank(); + push('NSError *error;'); + push('NSMutableString *body = [NSMutableString string];'); + push('for (NSDictionary *param in parameters) {'); + push('[body appendFormat:@"--%@\\r\\n", boundary];', 1); + push('if (param[@"fileName"]) {', 1); + push( + '[body appendFormat:@"Content-Disposition:form-data; name=\\"%@\\"; filename=\\"%@\\"\\r\\n", param[@"name"], param[@"fileName"]];', + 2, + ); + push('[body appendFormat:@"Content-Type: %@\\r\\n\\r\\n", param[@"contentType"]];', 2); + push( + '[body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSUTF8StringEncoding error:&error]];', + 2, + ); + push('if (error) {', 2); + push('NSLog(@"%@", error);', 3); + push('}', 2); + push('} else {', 1); + push('[body appendFormat:@"Content-Disposition:form-data; name=\\"%@\\"\\r\\n\\r\\n", param[@"name"]];', 2); + push('[body appendFormat:@"%@", param[@"value"]];', 2); + push('}', 1); + push('}'); + push('[body appendFormat:@"\\r\\n--%@--\\r\\n", boundary];'); + push('NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];'); + break; + + default: + blank(); + push( + `NSData *postData = [[NSData alloc] initWithData:[@"${postData.text}" dataUsingEncoding:NSUTF8StringEncoding]];`, + ); + } + } + + blank(); + push(`NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"${fullUrl}"]`); + + // NSURLRequestUseProtocolCachePolicy is the default policy, let's just always set it to avoid confusion. + push(' cachePolicy:NSURLRequestUseProtocolCachePolicy'); + push(` timeoutInterval:${opts.timeout.toFixed(1)}];`); + push(`[request setHTTPMethod:@"${method}"];`); + + if (req.hasHeaders) { + push('[request setAllHTTPHeaderFields:headers];'); + } + + if (req.hasBody) { + push('[request setHTTPBody:postData];'); + } + + blank(); + + // Retrieving the shared session will be less verbose than creating a new one. + push('NSURLSession *session = [NSURLSession sharedSession];'); + push('NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request'); + push( + ' completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {', + ); + push(' if (error) {', 1); + push(' NSLog(@"%@", error);', 2); + push(' } else {', 1); + + // Casting the NSURLResponse to NSHTTPURLResponse so the user can see the status . + push( + ' NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;', + 2, + ); + push(' NSLog(@"%@", httpResponse);', 2); + push(' }', 1); + push(' }];'); + push('[dataTask resume];'); + + return join(); + }, +}; diff --git a/test/fixtures/output/objc/nsurlsession/application-form-encoded.m b/src/targets/objc/nsurlsession/fixtures/application-form-encoded.m similarity index 94% rename from test/fixtures/output/objc/nsurlsession/application-form-encoded.m rename to src/targets/objc/nsurlsession/fixtures/application-form-encoded.m index 7ebd26e19..57dbfc75b 100644 --- a/test/fixtures/output/objc/nsurlsession/application-form-encoded.m +++ b/src/targets/objc/nsurlsession/fixtures/application-form-encoded.m @@ -5,7 +5,7 @@ NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"foo=bar" dataUsingEncoding:NSUTF8StringEncoding]]; [postData appendData:[@"&hello=world" dataUsingEncoding:NSUTF8StringEncoding]]; -NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [request setHTTPMethod:@"POST"]; @@ -22,4 +22,4 @@ NSLog(@"%@", httpResponse); } }]; -[dataTask resume]; +[dataTask resume]; \ No newline at end of file diff --git a/test/fixtures/output/objc/nsurlsession/application-json.m b/src/targets/objc/nsurlsession/fixtures/application-json.m similarity index 94% rename from test/fixtures/output/objc/nsurlsession/application-json.m rename to src/targets/objc/nsurlsession/fixtures/application-json.m index 0249be026..74a32703b 100644 --- a/test/fixtures/output/objc/nsurlsession/application-json.m +++ b/src/targets/objc/nsurlsession/fixtures/application-json.m @@ -5,12 +5,12 @@ @"string": @"f\"oo", @"arr": @[ @1, @2, @3 ], @"nested": @{ @"a": @"b" }, - @"arr_mix": @[ @1, @"a", @{ @"arr_mix_nested": @{ } } ], + @"arr_mix": @[ @1, @"a", @{ @"arr_mix_nested": @[ ] } ], @"boolean": @NO }; NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil]; -NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [request setHTTPMethod:@"POST"]; @@ -27,4 +27,4 @@ NSLog(@"%@", httpResponse); } }]; -[dataTask resume]; +[dataTask resume]; \ No newline at end of file diff --git a/test/fixtures/output/objc/nsurlsession/cookies.m b/src/targets/objc/nsurlsession/fixtures/cookies.m similarity index 91% rename from test/fixtures/output/objc/nsurlsession/cookies.m rename to src/targets/objc/nsurlsession/fixtures/cookies.m index 36e10f131..1364b5015 100644 --- a/test/fixtures/output/objc/nsurlsession/cookies.m +++ b/src/targets/objc/nsurlsession/fixtures/cookies.m @@ -2,10 +2,10 @@ NSDictionary *headers = @{ @"cookie": @"foo=bar; bar=baz" }; -NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/cookies"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; -[request setHTTPMethod:@"POST"]; +[request setHTTPMethod:@"GET"]; [request setAllHTTPHeaderFields:headers]; NSURLSession *session = [NSURLSession sharedSession]; @@ -18,4 +18,4 @@ NSLog(@"%@", httpResponse); } }]; -[dataTask resume]; +[dataTask resume]; \ No newline at end of file diff --git a/test/fixtures/output/objc/nsurlsession/custom-method.m b/src/targets/objc/nsurlsession/fixtures/custom-method.m similarity index 93% rename from test/fixtures/output/objc/nsurlsession/custom-method.m rename to src/targets/objc/nsurlsession/fixtures/custom-method.m index 10e9e6752..6d88cd3cb 100644 --- a/test/fixtures/output/objc/nsurlsession/custom-method.m +++ b/src/targets/objc/nsurlsession/fixtures/custom-method.m @@ -1,6 +1,6 @@ #import -NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [request setHTTPMethod:@"PROPFIND"]; @@ -15,4 +15,4 @@ NSLog(@"%@", httpResponse); } }]; -[dataTask resume]; +[dataTask resume]; \ No newline at end of file diff --git a/test/fixtures/output/objc/nsurlsession/full.m b/src/targets/objc/nsurlsession/fixtures/full.m similarity index 92% rename from test/fixtures/output/objc/nsurlsession/full.m rename to src/targets/objc/nsurlsession/fixtures/full.m index 52216b8eb..2a0080a4d 100644 --- a/test/fixtures/output/objc/nsurlsession/full.m +++ b/src/targets/objc/nsurlsession/fixtures/full.m @@ -6,7 +6,7 @@ NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"foo=bar" dataUsingEncoding:NSUTF8StringEncoding]]; -NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"] +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [request setHTTPMethod:@"POST"]; @@ -23,4 +23,4 @@ NSLog(@"%@", httpResponse); } }]; -[dataTask resume]; +[dataTask resume]; \ No newline at end of file diff --git a/test/fixtures/output/objc/nsurlsession/headers.m b/src/targets/objc/nsurlsession/fixtures/headers.m similarity index 82% rename from test/fixtures/output/objc/nsurlsession/headers.m rename to src/targets/objc/nsurlsession/fixtures/headers.m index 1d226ff5b..28e9ebfd1 100644 --- a/test/fixtures/output/objc/nsurlsession/headers.m +++ b/src/targets/objc/nsurlsession/fixtures/headers.m @@ -1,9 +1,11 @@ #import NSDictionary *headers = @{ @"accept": @"application/json", - @"x-foo": @"Bar" }; + @"x-foo": @"Bar", + @"x-bar": @"Foo", + @"quoted-value": @"\"quoted\" 'string'" }; -NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/headers"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [request setHTTPMethod:@"GET"]; @@ -19,4 +21,4 @@ NSLog(@"%@", httpResponse); } }]; -[dataTask resume]; +[dataTask resume]; \ No newline at end of file diff --git a/src/targets/objc/nsurlsession/fixtures/http-insecure.m b/src/targets/objc/nsurlsession/fixtures/http-insecure.m new file mode 100644 index 000000000..0b3597a67 --- /dev/null +++ b/src/targets/objc/nsurlsession/fixtures/http-insecure.m @@ -0,0 +1,18 @@ +#import + +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://httpbin.org/anything"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + timeoutInterval:10.0]; +[request setHTTPMethod:@"GET"]; + +NSURLSession *session = [NSURLSession sharedSession]; +NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + if (error) { + NSLog(@"%@", error); + } else { + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + NSLog(@"%@", httpResponse); + } + }]; +[dataTask resume]; \ No newline at end of file diff --git a/src/targets/objc/nsurlsession/fixtures/indent-option.m b/src/targets/objc/nsurlsession/fixtures/indent-option.m new file mode 100644 index 000000000..d0b322e02 --- /dev/null +++ b/src/targets/objc/nsurlsession/fixtures/indent-option.m @@ -0,0 +1,18 @@ +#import + +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + timeoutInterval:10.0]; +[request setHTTPMethod:@"GET"]; + +NSURLSession *session = [NSURLSession sharedSession]; +NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + if (error) { + NSLog(@"%@", error); + } else { + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + NSLog(@"%@", httpResponse); + } + }]; +[dataTask resume]; \ No newline at end of file diff --git a/src/targets/objc/nsurlsession/fixtures/json-with-null-value.m b/src/targets/objc/nsurlsession/fixtures/json-with-null-value.m new file mode 100644 index 000000000..3b380687d --- /dev/null +++ b/src/targets/objc/nsurlsession/fixtures/json-with-null-value.m @@ -0,0 +1,25 @@ +#import + +NSDictionary *headers = @{ @"content-type": @"application/json" }; +NSDictionary *parameters = @{ @"foo": }; + +NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil]; + +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + timeoutInterval:10.0]; +[request setHTTPMethod:@"POST"]; +[request setAllHTTPHeaderFields:headers]; +[request setHTTPBody:postData]; + +NSURLSession *session = [NSURLSession sharedSession]; +NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + if (error) { + NSLog(@"%@", error); + } else { + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + NSLog(@"%@", httpResponse); + } + }]; +[dataTask resume]; \ No newline at end of file diff --git a/src/targets/objc/nsurlsession/fixtures/jsonObj-multiline.m b/src/targets/objc/nsurlsession/fixtures/jsonObj-multiline.m new file mode 100644 index 000000000..de6689150 --- /dev/null +++ b/src/targets/objc/nsurlsession/fixtures/jsonObj-multiline.m @@ -0,0 +1,25 @@ +#import + +NSDictionary *headers = @{ @"content-type": @"application/json" }; +NSDictionary *parameters = @{ @"foo": @"bar" }; + +NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil]; + +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + timeoutInterval:10.0]; +[request setHTTPMethod:@"POST"]; +[request setAllHTTPHeaderFields:headers]; +[request setHTTPBody:postData]; + +NSURLSession *session = [NSURLSession sharedSession]; +NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + if (error) { + NSLog(@"%@", error); + } else { + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + NSLog(@"%@", httpResponse); + } + }]; +[dataTask resume]; \ No newline at end of file diff --git a/test/fixtures/output/objc/nsurlsession/jsonObj-null-value.m b/src/targets/objc/nsurlsession/fixtures/jsonObj-null-value.m similarity index 94% rename from test/fixtures/output/objc/nsurlsession/jsonObj-null-value.m rename to src/targets/objc/nsurlsession/fixtures/jsonObj-null-value.m index c13b4275b..3b380687d 100644 --- a/test/fixtures/output/objc/nsurlsession/jsonObj-null-value.m +++ b/src/targets/objc/nsurlsession/fixtures/jsonObj-null-value.m @@ -5,7 +5,7 @@ NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil]; -NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [request setHTTPMethod:@"POST"]; @@ -22,4 +22,4 @@ NSLog(@"%@", httpResponse); } }]; -[dataTask resume]; +[dataTask resume]; \ No newline at end of file diff --git a/test/fixtures/output/objc/nsurlsession/multipart-data.m b/src/targets/objc/nsurlsession/fixtures/multipart-data.m similarity index 90% rename from test/fixtures/output/objc/nsurlsession/multipart-data.m rename to src/targets/objc/nsurlsession/fixtures/multipart-data.m index 8b8d0de52..d97200615 100644 --- a/test/fixtures/output/objc/nsurlsession/multipart-data.m +++ b/src/targets/objc/nsurlsession/fixtures/multipart-data.m @@ -1,7 +1,8 @@ #import NSDictionary *headers = @{ @"content-type": @"multipart/form-data; boundary=---011000010111000001101001" }; -NSArray *parameters = @[ @{ @"name": @"foo", @"value": @"Hello World", @"fileName": @"hello.txt", @"contentType": @"text/plain" } ]; +NSArray *parameters = @[ @{ @"name": @"foo", @"value": @"Hello World", @"fileName": @"src/fixtures/files/hello.txt", @"contentType": @"text/plain" }, + @{ @"name": @"bar", @"value": @"Bonjour le monde" } ]; NSString *boundary = @"---011000010111000001101001"; NSError *error; @@ -23,7 +24,7 @@ [body appendFormat:@"\r\n--%@--\r\n", boundary]; NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding]; -NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [request setHTTPMethod:@"POST"]; @@ -40,4 +41,4 @@ NSLog(@"%@", httpResponse); } }]; -[dataTask resume]; +[dataTask resume]; \ No newline at end of file diff --git a/test/fixtures/output/objc/nsurlsession/multipart-file.m b/src/targets/objc/nsurlsession/fixtures/multipart-file.m similarity index 91% rename from test/fixtures/output/objc/nsurlsession/multipart-file.m rename to src/targets/objc/nsurlsession/fixtures/multipart-file.m index 0b68070e2..6abc132ee 100644 --- a/test/fixtures/output/objc/nsurlsession/multipart-file.m +++ b/src/targets/objc/nsurlsession/fixtures/multipart-file.m @@ -1,7 +1,7 @@ #import NSDictionary *headers = @{ @"content-type": @"multipart/form-data; boundary=---011000010111000001101001" }; -NSArray *parameters = @[ @{ @"name": @"foo", @"fileName": @"test/fixtures/files/hello.txt", @"contentType": @"text/plain" } ]; +NSArray *parameters = @[ @{ @"name": @"foo", @"fileName": @"src/fixtures/files/hello.txt", @"contentType": @"text/plain" } ]; NSString *boundary = @"---011000010111000001101001"; NSError *error; @@ -23,7 +23,7 @@ [body appendFormat:@"\r\n--%@--\r\n", boundary]; NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding]; -NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [request setHTTPMethod:@"POST"]; @@ -40,4 +40,4 @@ NSLog(@"%@", httpResponse); } }]; -[dataTask resume]; +[dataTask resume]; \ No newline at end of file diff --git a/src/targets/objc/nsurlsession/fixtures/multipart-form-data-no-params.m b/src/targets/objc/nsurlsession/fixtures/multipart-form-data-no-params.m new file mode 100644 index 000000000..224985f93 --- /dev/null +++ b/src/targets/objc/nsurlsession/fixtures/multipart-form-data-no-params.m @@ -0,0 +1,21 @@ +#import + +NSDictionary *headers = @{ @"Content-Type": @"multipart/form-data" }; + +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + timeoutInterval:10.0]; +[request setHTTPMethod:@"POST"]; +[request setAllHTTPHeaderFields:headers]; + +NSURLSession *session = [NSURLSession sharedSession]; +NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + if (error) { + NSLog(@"%@", error); + } else { + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + NSLog(@"%@", httpResponse); + } + }]; +[dataTask resume]; \ No newline at end of file diff --git a/test/fixtures/output/objc/nsurlsession/multipart-form-data.m b/src/targets/objc/nsurlsession/fixtures/multipart-form-data.m similarity index 93% rename from test/fixtures/output/objc/nsurlsession/multipart-form-data.m rename to src/targets/objc/nsurlsession/fixtures/multipart-form-data.m index 3c4648d02..63cbd423a 100644 --- a/test/fixtures/output/objc/nsurlsession/multipart-form-data.m +++ b/src/targets/objc/nsurlsession/fixtures/multipart-form-data.m @@ -1,6 +1,6 @@ #import -NSDictionary *headers = @{ @"content-type": @"multipart/form-data; boundary=---011000010111000001101001" }; +NSDictionary *headers = @{ @"Content-Type": @"multipart/form-data; boundary=---011000010111000001101001" }; NSArray *parameters = @[ @{ @"name": @"foo", @"value": @"bar" } ]; NSString *boundary = @"---011000010111000001101001"; @@ -23,7 +23,7 @@ [body appendFormat:@"\r\n--%@--\r\n", boundary]; NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding]; -NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [request setHTTPMethod:@"POST"]; @@ -40,4 +40,4 @@ NSLog(@"%@", httpResponse); } }]; -[dataTask resume]; +[dataTask resume]; \ No newline at end of file diff --git a/src/targets/objc/nsurlsession/fixtures/nested.m b/src/targets/objc/nsurlsession/fixtures/nested.m new file mode 100644 index 000000000..cbe01866e --- /dev/null +++ b/src/targets/objc/nsurlsession/fixtures/nested.m @@ -0,0 +1,18 @@ +#import + +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + timeoutInterval:10.0]; +[request setHTTPMethod:@"GET"]; + +NSURLSession *session = [NSURLSession sharedSession]; +NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + if (error) { + NSLog(@"%@", error); + } else { + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + NSLog(@"%@", httpResponse); + } + }]; +[dataTask resume]; \ No newline at end of file diff --git a/src/targets/objc/nsurlsession/fixtures/postdata-malformed.m b/src/targets/objc/nsurlsession/fixtures/postdata-malformed.m new file mode 100644 index 000000000..c0704fb03 --- /dev/null +++ b/src/targets/objc/nsurlsession/fixtures/postdata-malformed.m @@ -0,0 +1,21 @@ +#import + +NSDictionary *headers = @{ @"content-type": @"application/json" }; + +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + timeoutInterval:10.0]; +[request setHTTPMethod:@"POST"]; +[request setAllHTTPHeaderFields:headers]; + +NSURLSession *session = [NSURLSession sharedSession]; +NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + if (error) { + NSLog(@"%@", error); + } else { + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + NSLog(@"%@", httpResponse); + } + }]; +[dataTask resume]; \ No newline at end of file diff --git a/src/targets/objc/nsurlsession/fixtures/pretty-option.m b/src/targets/objc/nsurlsession/fixtures/pretty-option.m new file mode 100644 index 000000000..ed233e3b2 --- /dev/null +++ b/src/targets/objc/nsurlsession/fixtures/pretty-option.m @@ -0,0 +1,24 @@ +#import + +NSDictionary *headers = @{ @"cookie": @"foo=bar; bar=baz", @"accept": @"application/json", @"content-type": @"application/x-www-form-urlencoded" }; + +NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"foo=bar" dataUsingEncoding:NSUTF8StringEncoding]]; + +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + timeoutInterval:10.0]; +[request setHTTPMethod:@"POST"]; +[request setAllHTTPHeaderFields:headers]; +[request setHTTPBody:postData]; + +NSURLSession *session = [NSURLSession sharedSession]; +NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + if (error) { + NSLog(@"%@", error); + } else { + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + NSLog(@"%@", httpResponse); + } + }]; +[dataTask resume]; \ No newline at end of file diff --git a/src/targets/objc/nsurlsession/fixtures/query-encoded.m b/src/targets/objc/nsurlsession/fixtures/query-encoded.m new file mode 100644 index 000000000..fc01ee9c2 --- /dev/null +++ b/src/targets/objc/nsurlsession/fixtures/query-encoded.m @@ -0,0 +1,18 @@ +#import + +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + timeoutInterval:10.0]; +[request setHTTPMethod:@"GET"]; + +NSURLSession *session = [NSURLSession sharedSession]; +NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + if (error) { + NSLog(@"%@", error); + } else { + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + NSLog(@"%@", httpResponse); + } + }]; +[dataTask resume]; \ No newline at end of file diff --git a/test/fixtures/output/objc/nsurlsession/query.m b/src/targets/objc/nsurlsession/fixtures/query.m similarity index 90% rename from test/fixtures/output/objc/nsurlsession/query.m rename to src/targets/objc/nsurlsession/fixtures/query.m index 81cadfb31..80f6c00f1 100644 --- a/test/fixtures/output/objc/nsurlsession/query.m +++ b/src/targets/objc/nsurlsession/fixtures/query.m @@ -1,6 +1,6 @@ #import -NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"] +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [request setHTTPMethod:@"GET"]; @@ -15,4 +15,4 @@ NSLog(@"%@", httpResponse); } }]; -[dataTask resume]; +[dataTask resume]; \ No newline at end of file diff --git a/test/fixtures/output/objc/nsurlsession/short.m b/src/targets/objc/nsurlsession/fixtures/short.m similarity index 93% rename from test/fixtures/output/objc/nsurlsession/short.m rename to src/targets/objc/nsurlsession/fixtures/short.m index f3309b267..2e05f0061 100644 --- a/test/fixtures/output/objc/nsurlsession/short.m +++ b/src/targets/objc/nsurlsession/fixtures/short.m @@ -1,6 +1,6 @@ #import -NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [request setHTTPMethod:@"GET"]; @@ -15,4 +15,4 @@ NSLog(@"%@", httpResponse); } }]; -[dataTask resume]; +[dataTask resume]; \ No newline at end of file diff --git a/test/fixtures/output/objc/nsurlsession/text-plain.m b/src/targets/objc/nsurlsession/fixtures/text-plain.m similarity index 94% rename from test/fixtures/output/objc/nsurlsession/text-plain.m rename to src/targets/objc/nsurlsession/fixtures/text-plain.m index 7532a994a..8fa59b854 100644 --- a/test/fixtures/output/objc/nsurlsession/text-plain.m +++ b/src/targets/objc/nsurlsession/fixtures/text-plain.m @@ -4,7 +4,7 @@ NSData *postData = [[NSData alloc] initWithData:[@"Hello World" dataUsingEncoding:NSUTF8StringEncoding]]; -NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [request setHTTPMethod:@"POST"]; @@ -21,4 +21,4 @@ NSLog(@"%@", httpResponse); } }]; -[dataTask resume]; +[dataTask resume]; \ No newline at end of file diff --git a/src/targets/objc/nsurlsession/fixtures/timeout-option.m b/src/targets/objc/nsurlsession/fixtures/timeout-option.m new file mode 100644 index 000000000..d770cd916 --- /dev/null +++ b/src/targets/objc/nsurlsession/fixtures/timeout-option.m @@ -0,0 +1,18 @@ +#import + +NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://httpbin.org/anything"] + cachePolicy:NSURLRequestUseProtocolCachePolicy + timeoutInterval:5.0]; +[request setHTTPMethod:@"GET"]; + +NSURLSession *session = [NSURLSession sharedSession]; +NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + if (error) { + NSLog(@"%@", error); + } else { + NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; + NSLog(@"%@", httpResponse); + } + }]; +[dataTask resume]; \ No newline at end of file diff --git a/src/targets/objc/target.ts b/src/targets/objc/target.ts new file mode 100644 index 000000000..6674d5135 --- /dev/null +++ b/src/targets/objc/target.ts @@ -0,0 +1,14 @@ +import type { Target } from '../index.js'; + +import { nsurlsession } from './nsurlsession/client.js'; + +export const objc: Target = { + info: { + key: 'objc', + title: 'Objective-C', + default: 'nsurlsession', + }, + clientsById: { + nsurlsession, + }, +}; diff --git a/src/targets/ocaml/cohttp.js b/src/targets/ocaml/cohttp.js deleted file mode 100644 index ae89592f9..000000000 --- a/src/targets/ocaml/cohttp.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @description - * HTTP code snippet generator for OCaml using CoHTTP. - * - * @author - * @SGrondin - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ' - }, options) - - var methods = ['get', 'post', 'head', 'delete', 'patch', 'put', 'options'] - var code = new CodeBuilder(opts.indent) - - code.push('open Cohttp_lwt_unix') - .push('open Cohttp') - .push('open Lwt') - .blank() - .push('let uri = Uri.of_string "%s" in', source.fullUrl) - - // Add headers, including the cookies - var headers = Object.keys(source.allHeaders) - - if (headers.length === 1) { - code.push('let headers = Header.add (Header.init ()) "%s" "%s" in', headers[0], source.allHeaders[headers[0]]) - } else if (headers.length > 1) { - code.push('let headers = Header.add_list (Header.init ()) [') - - headers.forEach(function (key) { - code.push(1, '("%s", "%s");', key, source.allHeaders[key]) - }) - - code.push('] in') - } - - // Add body - if (source.postData.text) { - // Just text - code.push('let body = Cohttp_lwt_body.of_string %s in', JSON.stringify(source.postData.text)) - } - - // Do the request - code.blank() - - code.push('Client.call %s%s%s uri', - headers.length ? '~headers ' : '', - source.postData.text ? '~body ' : '', - (methods.indexOf(source.method.toLowerCase()) >= 0 ? ('`' + source.method.toUpperCase()) : '(Code.method_of_string "' + source.method + '")') - ) - - // Catch result - code.push('>>= fun (res, body_stream) ->') - .push(1, '(* Do stuff with the result *)') - - return code.join() -} - -module.exports.info = { - key: 'cohttp', - title: 'CoHTTP', - link: 'https://github.com/mirage/ocaml-cohttp', - description: 'Cohttp is a very lightweight HTTP server using Lwt or Async for OCaml' -} diff --git a/src/targets/ocaml/cohttp/client.ts b/src/targets/ocaml/cohttp/client.ts new file mode 100644 index 000000000..47d3f342c --- /dev/null +++ b/src/targets/ocaml/cohttp/client.ts @@ -0,0 +1,79 @@ +/** + * @description + * HTTP code snippet generator for OCaml using CoHTTP. + * + * @author + * @SGrondin + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { escapeForDoubleQuotes } from '../../../helpers/escape.js'; + +export const cohttp: Client = { + info: { + key: 'cohttp', + title: 'CoHTTP', + link: 'https://github.com/mirage/ocaml-cohttp', + description: 'Cohttp is a very lightweight HTTP server using Lwt or Async for OCaml', + extname: '.ml', + installation: () => 'opam install cohttp-lwt-unix cohttp-async', + }, + convert: ({ fullUrl, allHeaders, postData, method }, options) => { + const opts = { + indent: ' ', + ...options, + }; + + const methods = ['get', 'post', 'head', 'delete', 'patch', 'put', 'options']; + const { push, blank, join } = new CodeBuilder({ indent: opts.indent }); + + push('open Cohttp_lwt_unix'); + push('open Cohttp'); + push('open Lwt'); + blank(); + push(`let uri = Uri.of_string "${fullUrl}" in`); + + // Add headers, including the cookies + const headers = Object.keys(allHeaders); + + if (headers.length === 1) { + push( + `let headers = Header.add (Header.init ()) "${headers[0]}" "${escapeForDoubleQuotes( + allHeaders[headers[0]], + )}" in`, + ); + } else if (headers.length > 1) { + push('let headers = Header.add_list (Header.init ()) ['); + headers.forEach(key => { + push(`("${key}", "${escapeForDoubleQuotes(allHeaders[key])}");`, 1); + }); + push('] in'); + } + + // Add body + if (postData.text) { + // Just text + push(`let body = Cohttp_lwt_body.of_string ${JSON.stringify(postData.text)} in`); + } + + // Do the request + blank(); + + const h = headers.length ? '~headers ' : ''; + const b = postData.text ? '~body ' : ''; + const m = methods.includes(method.toLowerCase()) + ? `\`${method.toUpperCase()}` + : `(Code.method_of_string "${method}")`; + + push(`Client.call ${h}${b}${m} uri`); + + // Catch result + push('>>= fun (res, body_stream) ->'); + push('(* Do stuff with the result *)', 1); + + return join(); + }, +}; diff --git a/src/targets/ocaml/cohttp/fixtures/application-form-encoded.ml b/src/targets/ocaml/cohttp/fixtures/application-form-encoded.ml new file mode 100644 index 000000000..5a83a2c56 --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/application-form-encoded.ml @@ -0,0 +1,11 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/anything" in +let headers = Header.add (Header.init ()) "content-type" "application/x-www-form-urlencoded" in +let body = Cohttp_lwt_body.of_string "foo=bar&hello=world" in + +Client.call ~headers ~body `POST uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/application-json.ml b/src/targets/ocaml/cohttp/fixtures/application-json.ml new file mode 100644 index 000000000..f43380e9c --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/application-json.ml @@ -0,0 +1,11 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/anything" in +let headers = Header.add (Header.init ()) "content-type" "application/json" in +let body = Cohttp_lwt_body.of_string "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":[]}],\"boolean\":false}" in + +Client.call ~headers ~body `POST uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/cookies.ml b/src/targets/ocaml/cohttp/fixtures/cookies.ml new file mode 100644 index 000000000..707bb9ea8 --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/cookies.ml @@ -0,0 +1,10 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/cookies" in +let headers = Header.add (Header.init ()) "cookie" "foo=bar; bar=baz" in + +Client.call ~headers `GET uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/custom-method.ml b/src/targets/ocaml/cohttp/fixtures/custom-method.ml new file mode 100644 index 000000000..09f4bec69 --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/custom-method.ml @@ -0,0 +1,9 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/anything" in + +Client.call (Code.method_of_string "PROPFIND") uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/full.ml b/src/targets/ocaml/cohttp/fixtures/full.ml new file mode 100644 index 000000000..757d90994 --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/full.ml @@ -0,0 +1,15 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value" in +let headers = Header.add_list (Header.init ()) [ + ("cookie", "foo=bar; bar=baz"); + ("accept", "application/json"); + ("content-type", "application/x-www-form-urlencoded"); +] in +let body = Cohttp_lwt_body.of_string "foo=bar" in + +Client.call ~headers ~body `POST uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/headers.ml b/src/targets/ocaml/cohttp/fixtures/headers.ml new file mode 100644 index 000000000..3f4c417b4 --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/headers.ml @@ -0,0 +1,15 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/headers" in +let headers = Header.add_list (Header.init ()) [ + ("accept", "application/json"); + ("x-foo", "Bar"); + ("x-bar", "Foo"); + ("quoted-value", "\"quoted\" 'string'"); +] in + +Client.call ~headers `GET uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/http-insecure.ml b/src/targets/ocaml/cohttp/fixtures/http-insecure.ml new file mode 100644 index 000000000..18e9e0b40 --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/http-insecure.ml @@ -0,0 +1,9 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "http://httpbin.org/anything" in + +Client.call `GET uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/jsonObj-multiline.ml b/src/targets/ocaml/cohttp/fixtures/jsonObj-multiline.ml new file mode 100644 index 000000000..89a1a1f42 --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/jsonObj-multiline.ml @@ -0,0 +1,11 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/anything" in +let headers = Header.add (Header.init ()) "content-type" "application/json" in +let body = Cohttp_lwt_body.of_string "{\n \"foo\": \"bar\"\n}" in + +Client.call ~headers ~body `POST uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/jsonObj-null-value.ml b/src/targets/ocaml/cohttp/fixtures/jsonObj-null-value.ml new file mode 100644 index 000000000..4e659ea0f --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/jsonObj-null-value.ml @@ -0,0 +1,11 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/anything" in +let headers = Header.add (Header.init ()) "content-type" "application/json" in +let body = Cohttp_lwt_body.of_string "{\"foo\":null}" in + +Client.call ~headers ~body `POST uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/multipart-data.ml b/src/targets/ocaml/cohttp/fixtures/multipart-data.ml new file mode 100644 index 000000000..1c7d1cb0d --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/multipart-data.ml @@ -0,0 +1,11 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/anything" in +let headers = Header.add (Header.init ()) "content-type" "multipart/form-data; boundary=---011000010111000001101001" in +let body = Cohttp_lwt_body.of_string "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"bar\"\r\n\r\nBonjour le monde\r\n-----011000010111000001101001--" in + +Client.call ~headers ~body `POST uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/multipart-file.ml b/src/targets/ocaml/cohttp/fixtures/multipart-file.ml new file mode 100644 index 000000000..ab98f5170 --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/multipart-file.ml @@ -0,0 +1,11 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/anything" in +let headers = Header.add (Header.init ()) "content-type" "multipart/form-data; boundary=---011000010111000001101001" in +let body = Cohttp_lwt_body.of_string "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--" in + +Client.call ~headers ~body `POST uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/multipart-form-data-no-params.ml b/src/targets/ocaml/cohttp/fixtures/multipart-form-data-no-params.ml new file mode 100644 index 000000000..23edeebc8 --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/multipart-form-data-no-params.ml @@ -0,0 +1,10 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/anything" in +let headers = Header.add (Header.init ()) "Content-Type" "multipart/form-data" in + +Client.call ~headers `POST uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/multipart-form-data.ml b/src/targets/ocaml/cohttp/fixtures/multipart-form-data.ml new file mode 100644 index 000000000..2551bc14e --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/multipart-form-data.ml @@ -0,0 +1,11 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/anything" in +let headers = Header.add (Header.init ()) "Content-Type" "multipart/form-data; boundary=---011000010111000001101001" in +let body = Cohttp_lwt_body.of_string "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--" in + +Client.call ~headers ~body `POST uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/nested.ml b/src/targets/ocaml/cohttp/fixtures/nested.ml new file mode 100644 index 000000000..2396bd53c --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/nested.ml @@ -0,0 +1,9 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value" in + +Client.call `GET uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/postdata-malformed.ml b/src/targets/ocaml/cohttp/fixtures/postdata-malformed.ml new file mode 100644 index 000000000..6e3e028e5 --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/postdata-malformed.ml @@ -0,0 +1,10 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/anything" in +let headers = Header.add (Header.init ()) "content-type" "application/json" in + +Client.call ~headers `POST uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/query-encoded.ml b/src/targets/ocaml/cohttp/fixtures/query-encoded.ml new file mode 100644 index 000000000..3de865f83 --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/query-encoded.ml @@ -0,0 +1,9 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00" in + +Client.call `GET uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/query.ml b/src/targets/ocaml/cohttp/fixtures/query.ml new file mode 100644 index 000000000..42a1b07e5 --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/query.ml @@ -0,0 +1,9 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value" in + +Client.call `GET uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/short.ml b/src/targets/ocaml/cohttp/fixtures/short.ml new file mode 100644 index 000000000..4d505d0a1 --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/short.ml @@ -0,0 +1,9 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/anything" in + +Client.call `GET uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/cohttp/fixtures/text-plain.ml b/src/targets/ocaml/cohttp/fixtures/text-plain.ml new file mode 100644 index 000000000..201f39bd5 --- /dev/null +++ b/src/targets/ocaml/cohttp/fixtures/text-plain.ml @@ -0,0 +1,11 @@ +open Cohttp_lwt_unix +open Cohttp +open Lwt + +let uri = Uri.of_string "https://httpbin.org/anything" in +let headers = Header.add (Header.init ()) "content-type" "text/plain" in +let body = Cohttp_lwt_body.of_string "Hello World" in + +Client.call ~headers ~body `POST uri +>>= fun (res, body_stream) -> + (* Do stuff with the result *) \ No newline at end of file diff --git a/src/targets/ocaml/index.js b/src/targets/ocaml/index.js deleted file mode 100644 index 6fe00a888..000000000 --- a/src/targets/ocaml/index.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict' - -module.exports = { - info: { - key: 'ocaml', - title: 'OCaml', - extname: '.ml', - default: 'cohttp' - }, - - cohttp: require('./cohttp') -} diff --git a/src/targets/ocaml/target.ts b/src/targets/ocaml/target.ts new file mode 100644 index 000000000..f80b8ec04 --- /dev/null +++ b/src/targets/ocaml/target.ts @@ -0,0 +1,14 @@ +import type { Target } from '../index.js'; + +import { cohttp } from './cohttp/client.js'; + +export const ocaml: Target = { + info: { + key: 'ocaml', + title: 'OCaml', + default: 'cohttp', + }, + clientsById: { + cohttp, + }, +}; diff --git a/src/targets/php/curl.js b/src/targets/php/curl.js deleted file mode 100644 index 97aebc29d..000000000 --- a/src/targets/php/curl.js +++ /dev/null @@ -1,138 +0,0 @@ -/** - * @description - * HTTP code snippet generator for PHP using curl-ext. - * - * @author - * @AhmadNassri - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var opts = util._extend({ - closingTag: false, - indent: ' ', - maxRedirects: 10, - namedErrors: false, - noTags: false, - shortTags: false, - timeout: 30 - }, options) - - var code = new CodeBuilder(opts.indent) - - if (!opts.noTags) { - code.push(opts.shortTags ? ' %s,', option.name, option.escape ? JSON.stringify(option.value) : option.value)) - } - }) - - // construct cookies - var cookies = source.cookies.map(function (cookie) { - return encodeURIComponent(cookie.name) + '=' + encodeURIComponent(cookie.value) - }) - - if (cookies.length) { - curlopts.push(util.format('CURLOPT_COOKIE => "%s",', cookies.join('; '))) - } - - // construct cookies - var headers = Object.keys(source.headersObj).sort().map(function (key) { - return util.format('"%s: %s"', key, source.headersObj[key]) - }) - - if (headers.length) { - curlopts.push('CURLOPT_HTTPHEADER => array(') - .push(1, headers.join(',\n' + opts.indent + opts.indent)) - .push('),') - } - - code.push(1, curlopts.join()) - .push('));') - .blank() - .push('$response = curl_exec($curl);') - .push('$err = curl_error($curl);') - .blank() - .push('curl_close($curl);') - .blank() - .push('if ($err) {') - - if (opts.namedErrors) { - code.push(1, 'echo array_flip(get_defined_constants(true)["curl"])[$err];') - } else { - code.push(1, 'echo "cURL Error #:" . $err;') - } - - code.push('} else {') - .push(1, 'echo $response;') - .push('}') - - if (!opts.noTags && opts.closingTag) { - code.blank() - .push('?>') - } - - return code.join() -} - -module.exports.info = { - key: 'curl', - title: 'cURL', - link: 'http://php.net/manual/en/book.curl.php', - description: 'PHP with ext-curl' -} diff --git a/src/targets/php/curl/client.ts b/src/targets/php/curl/client.ts new file mode 100644 index 000000000..65c1397a3 --- /dev/null +++ b/src/targets/php/curl/client.ts @@ -0,0 +1,160 @@ +/** + * @description + * HTTP code snippet generator for PHP using curl-ext. + * + * @author + * @AhmadNassri + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { escapeForDoubleQuotes } from '../../../helpers/escape.js'; +import { convertType } from '../helpers.js'; + +export interface CurlOptions { + closingTag?: boolean; + maxRedirects?: number; + namedErrors?: boolean; + noTags?: boolean; + shortTags?: boolean; + timeout?: number; +} + +export const curl: Client = { + info: { + key: 'curl', + title: 'cURL', + link: 'http://php.net/manual/en/book.curl.php', + description: 'PHP with ext-curl', + extname: '.php', + }, + convert: ({ uriObj, postData, fullUrl, method, httpVersion, cookies, headersObj }, options = {}) => { + const { + closingTag = false, + indent = ' ', + maxRedirects = 10, + namedErrors = false, + noTags = false, + shortTags = false, + timeout = 30, + } = options; + + const { push, blank, join } = new CodeBuilder({ indent }); + + if (!noTags) { + push(shortTags ? ' { + if (value !== null && value !== undefined) { + curlopts.push(`${name} => ${escape ? JSON.stringify(value) : value},`); + } + }); + + // construct cookies + const curlCookies = cookies.map(cookie => `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`); + if (curlCookies.length) { + curlopts.push(`CURLOPT_COOKIE => "${curlCookies.join('; ')}",`); + } + + // construct cookies + const headers = Object.keys(headersObj) + .sort() + .map(key => `"${key}: ${escapeForDoubleQuotes(headersObj[key])}"`); + + if (headers.length) { + curlopts.push('CURLOPT_HTTPHEADER => ['); + curlopts.push(headers.join(`,\n${indent}${indent}`), 1); + curlopts.push('],'); + } + + push(curlopts.join(), 1); + push(']);'); + blank(); + push('$response = curl_exec($curl);'); + push('$err = curl_error($curl);'); + blank(); + push('curl_close($curl);'); + blank(); + push('if ($err) {'); + + if (namedErrors) { + push('echo array_flip(get_defined_constants(true)["curl"])[$err];', 1); + } else { + push('echo "cURL Error #:" . $err;', 1); + } + + push('} else {'); + push('echo $response;', 1); + push('}'); + + if (!noTags && closingTag) { + blank(); + push('?>'); + } + + return join(); + }, +}; diff --git a/src/targets/php/curl/fixtures/application-form-encoded.php b/src/targets/php/curl/fixtures/application-form-encoded.php new file mode 100644 index 000000000..ea9f36c69 --- /dev/null +++ b/src/targets/php/curl/fixtures/application-form-encoded.php @@ -0,0 +1,28 @@ + "https://httpbin.org/anything", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => "foo=bar&hello=world", + CURLOPT_HTTPHEADER => [ + "content-type: application/x-www-form-urlencoded" + ], +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/application-json.php b/src/targets/php/curl/fixtures/application-json.php new file mode 100644 index 000000000..aa8436206 --- /dev/null +++ b/src/targets/php/curl/fixtures/application-json.php @@ -0,0 +1,49 @@ + "https://httpbin.org/anything", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => json_encode([ + 'number' => 1, + 'string' => 'f"oo', + 'arr' => [ + 1, + 2, + 3 + ], + 'nested' => [ + 'a' => 'b' + ], + 'arr_mix' => [ + 1, + 'a', + [ + 'arr_mix_nested' => [ + + ] + ] + ], + 'boolean' => false + ]), + CURLOPT_HTTPHEADER => [ + "content-type: application/json" + ], +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/cookies.php b/src/targets/php/curl/fixtures/cookies.php new file mode 100644 index 000000000..cde4cd045 --- /dev/null +++ b/src/targets/php/curl/fixtures/cookies.php @@ -0,0 +1,25 @@ + "https://httpbin.org/cookies", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "GET", + CURLOPT_COOKIE => "foo=bar; bar=baz", +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/custom-method.php b/src/targets/php/curl/fixtures/custom-method.php new file mode 100644 index 000000000..adce1384c --- /dev/null +++ b/src/targets/php/curl/fixtures/custom-method.php @@ -0,0 +1,24 @@ + "https://httpbin.org/anything", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "PROPFIND", +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/full.php b/src/targets/php/curl/fixtures/full.php new file mode 100644 index 000000000..bec20752c --- /dev/null +++ b/src/targets/php/curl/fixtures/full.php @@ -0,0 +1,30 @@ + "https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => "foo=bar", + CURLOPT_COOKIE => "foo=bar; bar=baz", + CURLOPT_HTTPHEADER => [ + "accept: application/json", + "content-type: application/x-www-form-urlencoded" + ], +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/headers.php b/src/targets/php/curl/fixtures/headers.php new file mode 100644 index 000000000..d290664fa --- /dev/null +++ b/src/targets/php/curl/fixtures/headers.php @@ -0,0 +1,30 @@ + "https://httpbin.org/headers", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "GET", + CURLOPT_HTTPHEADER => [ + "accept: application/json", + "quoted-value: \"quoted\" 'string'", + "x-bar: Foo", + "x-foo: Bar" + ], +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/http-insecure.php b/src/targets/php/curl/fixtures/http-insecure.php new file mode 100644 index 000000000..2330663f0 --- /dev/null +++ b/src/targets/php/curl/fixtures/http-insecure.php @@ -0,0 +1,24 @@ + "http://httpbin.org/anything", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "GET", +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/jsonObj-multiline.php b/src/targets/php/curl/fixtures/jsonObj-multiline.php new file mode 100644 index 000000000..c7469c350 --- /dev/null +++ b/src/targets/php/curl/fixtures/jsonObj-multiline.php @@ -0,0 +1,30 @@ + "https://httpbin.org/anything", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => json_encode([ + 'foo' => 'bar' + ]), + CURLOPT_HTTPHEADER => [ + "content-type: application/json" + ], +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/jsonObj-null-value.php b/src/targets/php/curl/fixtures/jsonObj-null-value.php new file mode 100644 index 000000000..595e49868 --- /dev/null +++ b/src/targets/php/curl/fixtures/jsonObj-null-value.php @@ -0,0 +1,30 @@ + "https://httpbin.org/anything", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => json_encode([ + 'foo' => null + ]), + CURLOPT_HTTPHEADER => [ + "content-type: application/json" + ], +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/multipart-data.php b/src/targets/php/curl/fixtures/multipart-data.php new file mode 100644 index 000000000..c2130d267 --- /dev/null +++ b/src/targets/php/curl/fixtures/multipart-data.php @@ -0,0 +1,28 @@ + "https://httpbin.org/anything", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"bar\"\r\n\r\nBonjour le monde\r\n-----011000010111000001101001--", + CURLOPT_HTTPHEADER => [ + "content-type: multipart/form-data; boundary=---011000010111000001101001" + ], +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/multipart-file.php b/src/targets/php/curl/fixtures/multipart-file.php new file mode 100644 index 000000000..c76bd53e2 --- /dev/null +++ b/src/targets/php/curl/fixtures/multipart-file.php @@ -0,0 +1,28 @@ + "https://httpbin.org/anything", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--", + CURLOPT_HTTPHEADER => [ + "content-type: multipart/form-data; boundary=---011000010111000001101001" + ], +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/multipart-form-data-no-params.php b/src/targets/php/curl/fixtures/multipart-form-data-no-params.php new file mode 100644 index 000000000..a43530654 --- /dev/null +++ b/src/targets/php/curl/fixtures/multipart-form-data-no-params.php @@ -0,0 +1,28 @@ + "https://httpbin.org/anything", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => "", + CURLOPT_HTTPHEADER => [ + "Content-Type: multipart/form-data" + ], +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/multipart-form-data.php b/src/targets/php/curl/fixtures/multipart-form-data.php new file mode 100644 index 000000000..ff8725e28 --- /dev/null +++ b/src/targets/php/curl/fixtures/multipart-form-data.php @@ -0,0 +1,28 @@ + "https://httpbin.org/anything", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--", + CURLOPT_HTTPHEADER => [ + "Content-Type: multipart/form-data; boundary=---011000010111000001101001" + ], +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/nested.php b/src/targets/php/curl/fixtures/nested.php new file mode 100644 index 000000000..67bc5fffd --- /dev/null +++ b/src/targets/php/curl/fixtures/nested.php @@ -0,0 +1,24 @@ + "https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "GET", +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/postdata-malformed.php b/src/targets/php/curl/fixtures/postdata-malformed.php new file mode 100644 index 000000000..312177d07 --- /dev/null +++ b/src/targets/php/curl/fixtures/postdata-malformed.php @@ -0,0 +1,27 @@ + "https://httpbin.org/anything", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_HTTPHEADER => [ + "content-type: application/json" + ], +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/query-encoded.php b/src/targets/php/curl/fixtures/query-encoded.php new file mode 100644 index 000000000..62a54ef99 --- /dev/null +++ b/src/targets/php/curl/fixtures/query-encoded.php @@ -0,0 +1,24 @@ + "https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "GET", +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/query.php b/src/targets/php/curl/fixtures/query.php new file mode 100644 index 000000000..6a9bd8f10 --- /dev/null +++ b/src/targets/php/curl/fixtures/query.php @@ -0,0 +1,24 @@ + "https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "GET", +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/short.php b/src/targets/php/curl/fixtures/short.php new file mode 100644 index 000000000..47a16e0ae --- /dev/null +++ b/src/targets/php/curl/fixtures/short.php @@ -0,0 +1,24 @@ + "https://httpbin.org/anything", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "GET", +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/curl/fixtures/text-plain.php b/src/targets/php/curl/fixtures/text-plain.php new file mode 100644 index 000000000..a4e70404a --- /dev/null +++ b/src/targets/php/curl/fixtures/text-plain.php @@ -0,0 +1,28 @@ + "https://httpbin.org/anything", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => "Hello World", + CURLOPT_HTTPHEADER => [ + "content-type: text/plain" + ], +]); + +$response = curl_exec($curl); +$err = curl_error($curl); + +curl_close($curl); + +if ($err) { + echo "cURL Error #:" . $err; +} else { + echo $response; +} \ No newline at end of file diff --git a/src/targets/php/guzzle/client.ts b/src/targets/php/guzzle/client.ts new file mode 100644 index 000000000..cca1ec76e --- /dev/null +++ b/src/targets/php/guzzle/client.ts @@ -0,0 +1,152 @@ +/** + * @description + * HTTP code snippet generator for PHP using Guzzle. + * + * @author @RobertoArruda + * @author @erunion + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { escapeForSingleQuotes } from '../../../helpers/escape.js'; +import { getHeader, getHeaderName, hasHeader } from '../../../helpers/headers.js'; +import { convertType } from '../helpers.js'; + +export interface GuzzleOptions { + closingTag?: boolean; + indent?: string; + noTags?: boolean; + shortTags?: boolean; +} + +export const guzzle: Client = { + info: { + key: 'guzzle', + title: 'Guzzle', + link: 'http://docs.guzzlephp.org/en/stable/', + description: 'PHP with Guzzle', + extname: '.php', + installation: () => 'composer require guzzlehttp/guzzle', + }, + convert: ({ postData, fullUrl, method, cookies, headersObj }, options) => { + const opts = { + closingTag: false, + indent: ' ', + noTags: false, + shortTags: false, + ...options, + }; + + const { push, blank, join } = new CodeBuilder({ indent: opts.indent }); + const { code: requestCode, push: requestPush, join: requestJoin } = new CodeBuilder({ indent: opts.indent }); + + if (!opts.noTags) { + push(opts.shortTags ? ' ${convertType(postData.paramsObj, opts.indent + opts.indent, opts.indent)},`, 1); + break; + + case 'multipart/form-data': { + interface MultipartField { + contents: string | undefined; + filename?: string; + headers?: Record; + name: string; + } + + const fields: MultipartField[] = []; + + if (postData.params) { + postData.params.forEach(param => { + if (param.fileName) { + const field: MultipartField = { + name: param.name, + filename: param.fileName, + contents: param.value, + }; + + if (param.contentType) { + field.headers = { 'Content-Type': param.contentType }; + } + + fields.push(field); + } else if (param.value) { + fields.push({ + name: param.name, + contents: param.value, + }); + } + }); + } + + if (fields.length) { + requestPush(`'multipart' => ${convertType(fields, opts.indent + opts.indent, opts.indent)}`, 1); + + // Guzzle adds its own boundary for multipart requests. + if (hasHeader(headersObj, 'content-type')) { + if (getHeader(headersObj, 'content-type')?.indexOf('boundary')) { + const headerName = getHeaderName(headersObj, 'content-type'); + if (headerName) { + delete headersObj[headerName]; + } + } + } + } + break; + } + + default: + if (postData.text) { + requestPush(`'body' => ${convertType(postData.text)},`, 1); + } + } + + // construct headers + const headers = Object.keys(headersObj) + .sort() + .map(key => `${opts.indent}${opts.indent}'${key}' => '${escapeForSingleQuotes(headersObj[key])}',`); + + // construct cookies + const cookieString = cookies + .map(cookie => `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`) + .join('; '); + if (cookieString.length) { + headers.push(`${opts.indent}${opts.indent}'cookie' => '${escapeForSingleQuotes(cookieString)}',`); + } + + if (headers.length) { + requestPush("'headers' => [", 1); + requestPush(headers.join('\n')); + requestPush('],', 1); + } + + push('$client = new \\GuzzleHttp\\Client();'); + blank(); + + if (requestCode.length) { + push(`$response = $client->request('${method}', '${fullUrl}', [`); + push(requestJoin()); + push(']);'); + } else { + push(`$response = $client->request('${method}', '${fullUrl}');`); + } + + blank(); + push('echo $response->getBody();'); + + if (!opts.noTags && opts.closingTag) { + blank(); + push('?>'); + } + + return join(); + }, +}; diff --git a/src/targets/php/guzzle/fixtures/application-form-encoded.php b/src/targets/php/guzzle/fixtures/application-form-encoded.php new file mode 100644 index 000000000..a2076afe6 --- /dev/null +++ b/src/targets/php/guzzle/fixtures/application-form-encoded.php @@ -0,0 +1,16 @@ +request('POST', 'https://httpbin.org/anything', [ + 'form_params' => [ + 'foo' => 'bar', + 'hello' => 'world' + ], + 'headers' => [ + 'content-type' => 'application/x-www-form-urlencoded', + ], +]); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/application-json.php b/src/targets/php/guzzle/fixtures/application-json.php new file mode 100644 index 000000000..0b467af57 --- /dev/null +++ b/src/targets/php/guzzle/fixtures/application-json.php @@ -0,0 +1,13 @@ +request('POST', 'https://httpbin.org/anything', [ + 'body' => '{"number":1,"string":"f\\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":[]}],"boolean":false}', + 'headers' => [ + 'content-type' => 'application/json', + ], +]); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/cookies.php b/src/targets/php/guzzle/fixtures/cookies.php new file mode 100644 index 000000000..8ebc475be --- /dev/null +++ b/src/targets/php/guzzle/fixtures/cookies.php @@ -0,0 +1,12 @@ +request('GET', 'https://httpbin.org/cookies', [ + 'headers' => [ + 'cookie' => 'foo=bar; bar=baz', + ], +]); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/custom-method.php b/src/targets/php/guzzle/fixtures/custom-method.php new file mode 100644 index 000000000..6c924744e --- /dev/null +++ b/src/targets/php/guzzle/fixtures/custom-method.php @@ -0,0 +1,8 @@ +request('PROPFIND', 'https://httpbin.org/anything'); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/full.php b/src/targets/php/guzzle/fixtures/full.php new file mode 100644 index 000000000..649874c5a --- /dev/null +++ b/src/targets/php/guzzle/fixtures/full.php @@ -0,0 +1,17 @@ +request('POST', 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value', [ + 'form_params' => [ + 'foo' => 'bar' + ], + 'headers' => [ + 'accept' => 'application/json', + 'content-type' => 'application/x-www-form-urlencoded', + 'cookie' => 'foo=bar; bar=baz', + ], +]); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/headers.php b/src/targets/php/guzzle/fixtures/headers.php new file mode 100644 index 000000000..0367424b4 --- /dev/null +++ b/src/targets/php/guzzle/fixtures/headers.php @@ -0,0 +1,15 @@ +request('GET', 'https://httpbin.org/headers', [ + 'headers' => [ + 'accept' => 'application/json', + 'quoted-value' => '"quoted" \'string\'', + 'x-bar' => 'Foo', + 'x-foo' => 'Bar', + ], +]); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/http-insecure.php b/src/targets/php/guzzle/fixtures/http-insecure.php new file mode 100644 index 000000000..5578058f2 --- /dev/null +++ b/src/targets/php/guzzle/fixtures/http-insecure.php @@ -0,0 +1,8 @@ +request('GET', 'http://httpbin.org/anything'); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/jsonObj-multiline.php b/src/targets/php/guzzle/fixtures/jsonObj-multiline.php new file mode 100644 index 000000000..ecc8217d4 --- /dev/null +++ b/src/targets/php/guzzle/fixtures/jsonObj-multiline.php @@ -0,0 +1,15 @@ +request('POST', 'https://httpbin.org/anything', [ + 'body' => '{ + "foo": "bar" +}', + 'headers' => [ + 'content-type' => 'application/json', + ], +]); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/jsonObj-null-value.php b/src/targets/php/guzzle/fixtures/jsonObj-null-value.php new file mode 100644 index 000000000..c06d57ce8 --- /dev/null +++ b/src/targets/php/guzzle/fixtures/jsonObj-null-value.php @@ -0,0 +1,13 @@ +request('POST', 'https://httpbin.org/anything', [ + 'body' => '{"foo":null}', + 'headers' => [ + 'content-type' => 'application/json', + ], +]); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/multipart-data.php b/src/targets/php/guzzle/fixtures/multipart-data.php new file mode 100644 index 000000000..6c1c92278 --- /dev/null +++ b/src/targets/php/guzzle/fixtures/multipart-data.php @@ -0,0 +1,23 @@ +request('POST', 'https://httpbin.org/anything', [ + 'multipart' => [ + [ + 'name' => 'foo', + 'filename' => 'src/fixtures/files/hello.txt', + 'contents' => 'Hello World', + 'headers' => [ + 'Content-Type' => 'text/plain' + ] + ], + [ + 'name' => 'bar', + 'contents' => 'Bonjour le monde' + ] + ] +]); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/multipart-file.php b/src/targets/php/guzzle/fixtures/multipart-file.php new file mode 100644 index 000000000..d793a7faa --- /dev/null +++ b/src/targets/php/guzzle/fixtures/multipart-file.php @@ -0,0 +1,19 @@ +request('POST', 'https://httpbin.org/anything', [ + 'multipart' => [ + [ + 'name' => 'foo', + 'filename' => 'src/fixtures/files/hello.txt', + 'contents' => null, + 'headers' => [ + 'Content-Type' => 'text/plain' + ] + ] + ] +]); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/multipart-form-data-no-params.php b/src/targets/php/guzzle/fixtures/multipart-form-data-no-params.php new file mode 100644 index 000000000..8a05dec4e --- /dev/null +++ b/src/targets/php/guzzle/fixtures/multipart-form-data-no-params.php @@ -0,0 +1,12 @@ +request('POST', 'https://httpbin.org/anything', [ + 'headers' => [ + 'Content-Type' => 'multipart/form-data', + ], +]); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/multipart-form-data.php b/src/targets/php/guzzle/fixtures/multipart-form-data.php new file mode 100644 index 000000000..f8d67b7fc --- /dev/null +++ b/src/targets/php/guzzle/fixtures/multipart-form-data.php @@ -0,0 +1,15 @@ +request('POST', 'https://httpbin.org/anything', [ + 'multipart' => [ + [ + 'name' => 'foo', + 'contents' => 'bar' + ] + ] +]); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/nested.php b/src/targets/php/guzzle/fixtures/nested.php new file mode 100644 index 000000000..974b9ee91 --- /dev/null +++ b/src/targets/php/guzzle/fixtures/nested.php @@ -0,0 +1,8 @@ +request('GET', 'https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value'); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/postdata-malformed.php b/src/targets/php/guzzle/fixtures/postdata-malformed.php new file mode 100644 index 000000000..d3b254fd6 --- /dev/null +++ b/src/targets/php/guzzle/fixtures/postdata-malformed.php @@ -0,0 +1,12 @@ +request('POST', 'https://httpbin.org/anything', [ + 'headers' => [ + 'content-type' => 'application/json', + ], +]); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/query-encoded.php b/src/targets/php/guzzle/fixtures/query-encoded.php new file mode 100644 index 000000000..01a94e0b3 --- /dev/null +++ b/src/targets/php/guzzle/fixtures/query-encoded.php @@ -0,0 +1,8 @@ +request('GET', 'https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00'); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/query.php b/src/targets/php/guzzle/fixtures/query.php new file mode 100644 index 000000000..1408b7d37 --- /dev/null +++ b/src/targets/php/guzzle/fixtures/query.php @@ -0,0 +1,8 @@ +request('GET', 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value'); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/short.php b/src/targets/php/guzzle/fixtures/short.php new file mode 100644 index 000000000..b98d97378 --- /dev/null +++ b/src/targets/php/guzzle/fixtures/short.php @@ -0,0 +1,8 @@ +request('GET', 'https://httpbin.org/anything'); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/guzzle/fixtures/text-plain.php b/src/targets/php/guzzle/fixtures/text-plain.php new file mode 100644 index 000000000..1c0c4ecdb --- /dev/null +++ b/src/targets/php/guzzle/fixtures/text-plain.php @@ -0,0 +1,13 @@ +request('POST', 'https://httpbin.org/anything', [ + 'body' => 'Hello World', + 'headers' => [ + 'content-type' => 'text/plain', + ], +]); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/helpers.js b/src/targets/php/helpers.js deleted file mode 100644 index c6b2562ed..000000000 --- a/src/targets/php/helpers.js +++ /dev/null @@ -1,85 +0,0 @@ -'use strict' - -var convert = function (obj, indent, last_indent) { - var i, result - - if (!last_indent) { - last_indent = '' - } - - switch (Object.prototype.toString.call(obj)) { - case '[object Null]': - result = 'null' - break - - case '[object Undefined]': - result = 'null' - break - - case '[object String]': - result = "'" + obj.replace(/\\/g, '\\\\').replace(/\'/g, "\'") + "'" - break - - case '[object Number]': - result = obj.toString() - break - - case '[object Array]': - result = [] - - obj.forEach(function (item) { - result.push(convert(item, indent + indent, indent)) - }) - - result = 'array(\n' + indent + result.join(',\n' + indent) + '\n' + last_indent + ')' - break - - case '[object Object]': - result = [] - for (i in obj) { - if (obj.hasOwnProperty(i)) { - result.push(convert(i, indent) + ' => ' + convert(obj[i], indent + indent, indent)) - } - } - result = 'array(\n' + indent + result.join(',\n' + indent) + '\n' + last_indent + ')' - break - - default: - result = 'null' - } - - return result -} - -module.exports = { - convert: convert, - methods: [ - 'ACL', - 'BASELINE_CONTROL', - 'CHECKIN', - 'CHECKOUT', - 'CONNECT', - 'COPY', - 'DELETE', - 'GET', - 'HEAD', - 'LABEL', - 'LOCK', - 'MERGE', - 'MKACTIVITY', - 'MKCOL', - 'MKWORKSPACE', - 'MOVE', - 'OPTIONS', - 'POST', - 'PROPFIND', - 'PROPPATCH', - 'PUT', - 'REPORT', - 'TRACE', - 'UNCHECKOUT', - 'UNLOCK', - 'UPDATE', - 'VERSION_CONTROL' - ] -} diff --git a/src/targets/php/helpers.ts b/src/targets/php/helpers.ts new file mode 100644 index 000000000..dcb3c8b7e --- /dev/null +++ b/src/targets/php/helpers.ts @@ -0,0 +1,71 @@ +import { escapeString } from '../../helpers/escape.js'; + +export const convertType = (obj: any[] | any, indent?: string, lastIndent?: string): string | 'null' => { + lastIndent = lastIndent || ''; + indent = indent || ''; + + switch (Object.prototype.toString.call(obj)) { + case '[object Boolean]': + return obj; + + case '[object Null]': + return 'null'; + + case '[object Undefined]': + return 'null'; + + case '[object String]': + return `'${escapeString(obj, { delimiter: "'", escapeNewlines: false })}'`; + + case '[object Number]': + return obj.toString(); + + case '[object Array]': { + const contents = obj.map((item: any) => convertType(item, `${indent}${indent}`, indent)).join(`,\n${indent}`); + return `[\n${indent}${contents}\n${lastIndent}]`; + } + + case '[object Object]': { + const result: string[] = []; + for (const i in obj) { + if (Object.prototype.hasOwnProperty.call(obj, i)) { + result.push(`${convertType(i, indent)} => ${convertType(obj[i], `${indent}${indent}`, indent)}`); + } + } + return `[\n${indent}${result.join(`,\n${indent}`)}\n${lastIndent}]`; + } + + default: + return 'null'; + } +}; + +export const supportedMethods = [ + 'ACL', + 'BASELINE_CONTROL', + 'CHECKIN', + 'CHECKOUT', + 'CONNECT', + 'COPY', + 'DELETE', + 'GET', + 'HEAD', + 'LABEL', + 'LOCK', + 'MERGE', + 'MKACTIVITY', + 'MKCOL', + 'MKWORKSPACE', + 'MOVE', + 'OPTIONS', + 'POST', + 'PROPFIND', + 'PROPPATCH', + 'PUT', + 'REPORT', + 'TRACE', + 'UNCHECKOUT', + 'UNLOCK', + 'UPDATE', + 'VERSION_CONTROL', +] as const; diff --git a/src/targets/php/http1.js b/src/targets/php/http1.js deleted file mode 100644 index b4429a474..000000000 --- a/src/targets/php/http1.js +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @description - * HTTP code snippet generator for PHP using curl-ext. - * - * @author - * @AhmadNassri - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var util = require('util') -var helpers = require('./helpers') -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var opts = util._extend({ - closingTag: false, - indent: ' ', - noTags: false, - shortTags: false - }, options) - - var code = new CodeBuilder(opts.indent) - - if (!opts.noTags) { - code.push(opts.shortTags ? 'setUrl(%s);', helpers.convert(source.url)) - - if (~helpers.methods.indexOf(source.method.toUpperCase())) { - code.push('$request->setMethod(HTTP_METH_%s);', source.method.toUpperCase()) - } else { - code.push('$request->setMethod(HttpRequest::HTTP_METH_%s);', source.method.toUpperCase()) - } - - code.blank() - - if (Object.keys(source.queryObj).length) { - code.push('$request->setQueryData(%s);', helpers.convert(source.queryObj, opts.indent)) - .blank() - } - - if (Object.keys(source.headersObj).length) { - code.push('$request->setHeaders(%s);', helpers.convert(source.headersObj, opts.indent)) - .blank() - } - - if (Object.keys(source.cookiesObj).length) { - code.push('$request->setCookies(%s);', helpers.convert(source.cookiesObj, opts.indent)) - .blank() - } - - switch (source.postData.mimeType) { - case 'application/x-www-form-urlencoded': - code.push('$request->setContentType(%s);', helpers.convert(source.postData.mimeType)) - .push('$request->setPostFields(%s);', helpers.convert(source.postData.paramsObj, opts.indent)) - .blank() - break - - default: - if (source.postData.text) { - code.push('$request->setBody(%s);', helpers.convert(source.postData.text)) - .blank() - } - } - - code.push('try {') - .push(1, '$response = $request->send();') - .blank() - .push(1, 'echo $response->getBody();') - .push('} catch (HttpException $ex) {') - .push(1, 'echo $ex;') - .push('}') - - if (!opts.noTags && opts.closingTag) { - code.blank() - .push('?>') - } - - return code.join() -} - -module.exports.info = { - key: 'http1', - title: 'HTTP v1', - link: 'http://php.net/manual/en/book.http.php', - description: 'PHP with pecl/http v1' -} diff --git a/src/targets/php/http1/client.ts b/src/targets/php/http1/client.ts new file mode 100644 index 000000000..ac1c1c388 --- /dev/null +++ b/src/targets/php/http1/client.ts @@ -0,0 +1,104 @@ +/** + * @description + * HTTP code snippet generator for PHP using curl-ext. + * + * @author + * @AhmadNassri + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { convertType, supportedMethods } from '../helpers.js'; + +export interface Http1Options { + closingTag?: boolean; + noTags?: boolean; + shortTags?: boolean; +} + +export const http1: Client = { + info: { + key: 'http1', + title: 'HTTP v1', + link: 'http://php.net/manual/en/book.http.php', + description: 'PHP with pecl/http v1', + extname: '.php', + }, + convert: ({ method, url, postData, queryObj, headersObj, cookiesObj }, options = {}) => { + const { closingTag = false, indent = ' ', noTags = false, shortTags = false } = options; + + const { push, blank, join } = new CodeBuilder({ indent }); + + if (!noTags) { + push(shortTags ? 'setUrl(${convertType(url)});`); + + if (supportedMethods.includes(method.toUpperCase() as (typeof supportedMethods)[number])) { + push(`$request->setMethod(HTTP_METH_${method.toUpperCase()});`); + } else { + push(`$request->setMethod(HttpRequest::HTTP_METH_${method.toUpperCase()});`); + } + + blank(); + + if (Object.keys(queryObj).length) { + push(`$request->setQueryData(${convertType(queryObj, indent)});`); + blank(); + } + + if (Object.keys(headersObj).length) { + push(`$request->setHeaders(${convertType(headersObj, indent)});`); + blank(); + } + + if (Object.keys(cookiesObj).length) { + push(`$request->setCookies(${convertType(cookiesObj, indent)});`); + blank(); + } + + switch (postData.mimeType) { + case 'application/x-www-form-urlencoded': + push(`$request->setContentType(${convertType(postData.mimeType)});`); + push(`$request->setPostFields(${convertType(postData.paramsObj, indent)});`); + blank(); + break; + + case 'application/json': + push(`$request->setContentType(${convertType(postData.mimeType)});`); + push(`$request->setBody(json_encode(${convertType(postData.jsonObj, indent)}));`); + blank(); + break; + + default: + if (postData.text) { + push(`$request->setBody(${convertType(postData.text)});`); + blank(); + } + } + + push('try {'); + push('$response = $request->send();', 1); + blank(); + push('echo $response->getBody();', 1); + push('} catch (HttpException $ex) {'); + push('echo $ex;', 1); + push('}'); + + if (!noTags && closingTag) { + blank(); + push('?>'); + } + + return join(); + }, +}; diff --git a/src/targets/php/http1/fixtures/application-form-encoded.php b/src/targets/php/http1/fixtures/application-form-encoded.php new file mode 100644 index 000000000..70f0a1319 --- /dev/null +++ b/src/targets/php/http1/fixtures/application-form-encoded.php @@ -0,0 +1,23 @@ +setUrl('https://httpbin.org/anything'); +$request->setMethod(HTTP_METH_POST); + +$request->setHeaders([ + 'content-type' => 'application/x-www-form-urlencoded' +]); + +$request->setContentType('application/x-www-form-urlencoded'); +$request->setPostFields([ + 'foo' => 'bar', + 'hello' => 'world' +]); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/application-json.php b/src/targets/php/http1/fixtures/application-json.php new file mode 100644 index 000000000..9ae5873ba --- /dev/null +++ b/src/targets/php/http1/fixtures/application-json.php @@ -0,0 +1,41 @@ +setUrl('https://httpbin.org/anything'); +$request->setMethod(HTTP_METH_POST); + +$request->setHeaders([ + 'content-type' => 'application/json' +]); + +$request->setContentType('application/json'); +$request->setBody(json_encode([ + 'number' => 1, + 'string' => 'f"oo', + 'arr' => [ + 1, + 2, + 3 + ], + 'nested' => [ + 'a' => 'b' + ], + 'arr_mix' => [ + 1, + 'a', + [ + 'arr_mix_nested' => [ + + ] + ] + ], + 'boolean' => false +])); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/cookies.php b/src/targets/php/http1/fixtures/cookies.php new file mode 100644 index 000000000..63eb695ea --- /dev/null +++ b/src/targets/php/http1/fixtures/cookies.php @@ -0,0 +1,18 @@ +setUrl('https://httpbin.org/cookies'); +$request->setMethod(HTTP_METH_GET); + +$request->setCookies([ + 'bar' => 'baz', + 'foo' => 'bar' +]); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/custom-method.php b/src/targets/php/http1/fixtures/custom-method.php new file mode 100644 index 000000000..d5ca9ad63 --- /dev/null +++ b/src/targets/php/http1/fixtures/custom-method.php @@ -0,0 +1,13 @@ +setUrl('https://httpbin.org/anything'); +$request->setMethod(HTTP_METH_PROPFIND); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/full.php b/src/targets/php/http1/fixtures/full.php new file mode 100644 index 000000000..4db0a0935 --- /dev/null +++ b/src/targets/php/http1/fixtures/full.php @@ -0,0 +1,37 @@ +setUrl('https://httpbin.org/anything'); +$request->setMethod(HTTP_METH_POST); + +$request->setQueryData([ + 'foo' => [ + 'bar', + 'baz' + ], + 'baz' => 'abc', + 'key' => 'value' +]); + +$request->setHeaders([ + 'accept' => 'application/json', + 'content-type' => 'application/x-www-form-urlencoded' +]); + +$request->setCookies([ + 'bar' => 'baz', + 'foo' => 'bar' +]); + +$request->setContentType('application/x-www-form-urlencoded'); +$request->setPostFields([ + 'foo' => 'bar' +]); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/headers.php b/src/targets/php/http1/fixtures/headers.php new file mode 100644 index 000000000..385adb6fa --- /dev/null +++ b/src/targets/php/http1/fixtures/headers.php @@ -0,0 +1,20 @@ +setUrl('https://httpbin.org/headers'); +$request->setMethod(HTTP_METH_GET); + +$request->setHeaders([ + 'accept' => 'application/json', + 'x-foo' => 'Bar', + 'x-bar' => 'Foo', + 'quoted-value' => '"quoted" \'string\'' +]); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/http-insecure.php b/src/targets/php/http1/fixtures/http-insecure.php new file mode 100644 index 000000000..425d90742 --- /dev/null +++ b/src/targets/php/http1/fixtures/http-insecure.php @@ -0,0 +1,13 @@ +setUrl('http://httpbin.org/anything'); +$request->setMethod(HTTP_METH_GET); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/jsonObj-multiline.php b/src/targets/php/http1/fixtures/jsonObj-multiline.php new file mode 100644 index 000000000..200952e40 --- /dev/null +++ b/src/targets/php/http1/fixtures/jsonObj-multiline.php @@ -0,0 +1,22 @@ +setUrl('https://httpbin.org/anything'); +$request->setMethod(HTTP_METH_POST); + +$request->setHeaders([ + 'content-type' => 'application/json' +]); + +$request->setContentType('application/json'); +$request->setBody(json_encode([ + 'foo' => 'bar' +])); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/jsonObj-null-value.php b/src/targets/php/http1/fixtures/jsonObj-null-value.php new file mode 100644 index 000000000..8aed3989c --- /dev/null +++ b/src/targets/php/http1/fixtures/jsonObj-null-value.php @@ -0,0 +1,22 @@ +setUrl('https://httpbin.org/anything'); +$request->setMethod(HTTP_METH_POST); + +$request->setHeaders([ + 'content-type' => 'application/json' +]); + +$request->setContentType('application/json'); +$request->setBody(json_encode([ + 'foo' => null +])); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/multipart-data.php b/src/targets/php/http1/fixtures/multipart-data.php new file mode 100644 index 000000000..3636106a7 --- /dev/null +++ b/src/targets/php/http1/fixtures/multipart-data.php @@ -0,0 +1,28 @@ +setUrl('https://httpbin.org/anything'); +$request->setMethod(HTTP_METH_POST); + +$request->setHeaders([ + 'content-type' => 'multipart/form-data; boundary=---011000010111000001101001' +]); + +$request->setBody('-----011000010111000001101001 +Content-Disposition: form-data; name="foo"; filename="src/fixtures/files/hello.txt" +Content-Type: text/plain + +Hello World +-----011000010111000001101001 +Content-Disposition: form-data; name="bar" + +Bonjour le monde +-----011000010111000001101001--'); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/multipart-file.php b/src/targets/php/http1/fixtures/multipart-file.php new file mode 100644 index 000000000..c4e5f5f56 --- /dev/null +++ b/src/targets/php/http1/fixtures/multipart-file.php @@ -0,0 +1,24 @@ +setUrl('https://httpbin.org/anything'); +$request->setMethod(HTTP_METH_POST); + +$request->setHeaders([ + 'content-type' => 'multipart/form-data; boundary=---011000010111000001101001' +]); + +$request->setBody('-----011000010111000001101001 +Content-Disposition: form-data; name="foo"; filename="src/fixtures/files/hello.txt" +Content-Type: text/plain + + +-----011000010111000001101001--'); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/multipart-form-data-no-params.php b/src/targets/php/http1/fixtures/multipart-form-data-no-params.php new file mode 100644 index 000000000..0e43c8f77 --- /dev/null +++ b/src/targets/php/http1/fixtures/multipart-form-data-no-params.php @@ -0,0 +1,17 @@ +setUrl('https://httpbin.org/anything'); +$request->setMethod(HTTP_METH_POST); + +$request->setHeaders([ + 'Content-Type' => 'multipart/form-data' +]); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/multipart-form-data.php b/src/targets/php/http1/fixtures/multipart-form-data.php new file mode 100644 index 000000000..7d94018f1 --- /dev/null +++ b/src/targets/php/http1/fixtures/multipart-form-data.php @@ -0,0 +1,23 @@ +setUrl('https://httpbin.org/anything'); +$request->setMethod(HTTP_METH_POST); + +$request->setHeaders([ + 'Content-Type' => 'multipart/form-data; boundary=---011000010111000001101001' +]); + +$request->setBody('-----011000010111000001101001 +Content-Disposition: form-data; name="foo" + +bar +-----011000010111000001101001--'); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/nested.php b/src/targets/php/http1/fixtures/nested.php new file mode 100644 index 000000000..40f89968e --- /dev/null +++ b/src/targets/php/http1/fixtures/nested.php @@ -0,0 +1,19 @@ +setUrl('https://httpbin.org/anything'); +$request->setMethod(HTTP_METH_GET); + +$request->setQueryData([ + 'foo[bar]' => 'baz,zap', + 'fiz' => 'buz', + 'key' => 'value' +]); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/postdata-malformed.php b/src/targets/php/http1/fixtures/postdata-malformed.php new file mode 100644 index 000000000..4ed5022ab --- /dev/null +++ b/src/targets/php/http1/fixtures/postdata-malformed.php @@ -0,0 +1,17 @@ +setUrl('https://httpbin.org/anything'); +$request->setMethod(HTTP_METH_POST); + +$request->setHeaders([ + 'content-type' => 'application/json' +]); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/query-encoded.php b/src/targets/php/http1/fixtures/query-encoded.php new file mode 100644 index 000000000..434c0ea83 --- /dev/null +++ b/src/targets/php/http1/fixtures/query-encoded.php @@ -0,0 +1,18 @@ +setUrl('https://httpbin.org/anything'); +$request->setMethod(HTTP_METH_GET); + +$request->setQueryData([ + 'startTime' => '2019-06-13T19%3A08%3A25.455Z', + 'endTime' => '2015-09-15T14%3A00%3A12-04%3A00' +]); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/query.php b/src/targets/php/http1/fixtures/query.php new file mode 100644 index 000000000..231c48cdb --- /dev/null +++ b/src/targets/php/http1/fixtures/query.php @@ -0,0 +1,22 @@ +setUrl('https://httpbin.org/anything'); +$request->setMethod(HTTP_METH_GET); + +$request->setQueryData([ + 'foo' => [ + 'bar', + 'baz' + ], + 'baz' => 'abc', + 'key' => 'value' +]); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/short.php b/src/targets/php/http1/fixtures/short.php new file mode 100644 index 000000000..bd838355f --- /dev/null +++ b/src/targets/php/http1/fixtures/short.php @@ -0,0 +1,13 @@ +setUrl('https://httpbin.org/anything'); +$request->setMethod(HTTP_METH_GET); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http1/fixtures/text-plain.php b/src/targets/php/http1/fixtures/text-plain.php new file mode 100644 index 000000000..d0abb8e3d --- /dev/null +++ b/src/targets/php/http1/fixtures/text-plain.php @@ -0,0 +1,19 @@ +setUrl('https://httpbin.org/anything'); +$request->setMethod(HTTP_METH_POST); + +$request->setHeaders([ + 'content-type' => 'text/plain' +]); + +$request->setBody('Hello World'); + +try { + $response = $request->send(); + + echo $response->getBody(); +} catch (HttpException $ex) { + echo $ex; +} \ No newline at end of file diff --git a/src/targets/php/http2.js b/src/targets/php/http2.js deleted file mode 100644 index 9b90617e7..000000000 --- a/src/targets/php/http2.js +++ /dev/null @@ -1,129 +0,0 @@ -/** - * @description - * HTTP code snippet generator for PHP using curl-ext. - * - * @author - * @AhmadNassri - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var util = require('util') -var helpers = require('./helpers') -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var opts = util._extend({ - closingTag: false, - indent: ' ', - noTags: false, - shortTags: false - }, options) - - var code = new CodeBuilder(opts.indent) - var hasBody = false - - if (!opts.noTags) { - code.push(opts.shortTags ? 'append(new http\\QueryString(%s));', helpers.convert(source.postData.paramsObj, opts.indent)) - .blank() - hasBody = true - break - - case 'multipart/form-data': - var files = [] - var fields = {} - - source.postData.params.forEach(function (param) { - if (param.fileName) { - files.push({ - name: param.name, - type: param.contentType, - file: param.fileName, - data: param.value - }) - } else if (param.value) { - fields[param.name] = param.value - } - }) - - code.push('$body = new http\\Message\\Body;') - .push('$body->addForm(%s, %s);', - Object.keys(fields).length ? helpers.convert(fields, opts.indent) : 'NULL', - files.length ? helpers.convert(files, opts.indent) : 'NULL' - ) - - // remove the contentType header - if (~source.headersObj['content-type'].indexOf('boundary')) { - delete source.headersObj['content-type'] - } - - code.blank() - - hasBody = true - break - - default: - if (source.postData.text) { - code.push('$body = new http\\Message\\Body;') - .push('$body->append(%s);', helpers.convert(source.postData.text)) - .blank() - hasBody = true - } - } - - code.push('$request->setRequestUrl(%s);', helpers.convert(source.url)) - .push('$request->setRequestMethod(%s);', helpers.convert(source.method)) - - if (hasBody) { - code.push('$request->setBody($body);') - .blank() - } - - if (Object.keys(source.queryObj).length) { - code.push('$request->setQuery(new http\\QueryString(%s));', helpers.convert(source.queryObj, opts.indent)) - .blank() - } - - if (Object.keys(source.headersObj).length) { - code.push('$request->setHeaders(%s);', helpers.convert(source.headersObj, opts.indent)) - .blank() - } - - if (Object.keys(source.cookiesObj).length) { - code.blank() - .push('$client->setCookies(%s);', helpers.convert(source.cookiesObj, opts.indent)) - .blank() - } - - code.push('$client->enqueue($request)->send();') - .push('$response = $client->getResponse();') - .blank() - .push('echo $response->getBody();') - - if (!opts.noTags && opts.closingTag) { - code.blank() - .push('?>') - } - - return code.join() -} - -module.exports.info = { - key: 'http2', - title: 'HTTP v2', - link: 'http://devel-m6w6.rhcloud.com/mdref/http', - description: 'PHP with pecl/http v2' -} diff --git a/src/targets/php/http2/client.ts b/src/targets/php/http2/client.ts new file mode 100644 index 000000000..5568e4b53 --- /dev/null +++ b/src/targets/php/http2/client.ts @@ -0,0 +1,154 @@ +/** + * @description + * HTTP code snippet generator for PHP using curl-ext. + * + * @author + * @AhmadNassri + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { getHeader, getHeaderName, hasHeader } from '../../../helpers/headers.js'; +import { convertType } from '../helpers.js'; + +export interface Http2Options { + closingTag?: boolean; + noTags?: boolean; + shortTags?: boolean; +} + +export const http2: Client = { + info: { + key: 'http2', + title: 'HTTP v2', + link: 'http://devel-m6w6.rhcloud.com/mdref/http', + description: 'PHP with pecl/http v2', + extname: '.php', + }, + convert: ({ postData, headersObj, method, queryObj, cookiesObj, url }, options = {}) => { + const { closingTag = false, indent = ' ', noTags = false, shortTags = false } = options; + + const { push, blank, join } = new CodeBuilder({ indent }); + let hasBody = false; + + if (!noTags) { + push(shortTags ? 'append(new http\\QueryString(${convertType(postData.paramsObj, indent)}));`); + blank(); + hasBody = true; + break; + + case 'multipart/form-data': { + if (!postData.params) { + break; + } + + const files: { + [anything: string]: string | undefined; + data: string | undefined; + file: string; + name: string; + type: string | undefined; + }[] = []; + const fields: Record = {}; + postData.params.forEach(({ name, fileName, value, contentType }) => { + if (fileName) { + files.push({ + name, + type: contentType, + file: fileName, + data: value, + }); + return; + } + if (value) { + fields[name] = value; + } + }); + + const field = Object.keys(fields).length ? convertType(fields, indent) : 'null'; + const formValue = files.length ? convertType(files, indent) : 'null'; + + push('$body = new http\\Message\\Body;'); + push(`$body->addForm(${field}, ${formValue});`); + + // remove the contentType header + if (hasHeader(headersObj, 'content-type')) { + if (getHeader(headersObj, 'content-type')?.indexOf('boundary')) { + const headerName = getHeaderName(headersObj, 'content-type'); + if (headerName) { + delete headersObj[headerName]; + } + } + } + + blank(); + + hasBody = true; + break; + } + + case 'application/json': + push('$body = new http\\Message\\Body;'); + push(`$body->append(json_encode(${convertType(postData.jsonObj, indent)}));`); + hasBody = true; + break; + + default: + if (postData.text) { + push('$body = new http\\Message\\Body;'); + push(`$body->append(${convertType(postData.text)});`); + blank(); + hasBody = true; + } + } + + push(`$request->setRequestUrl(${convertType(url)});`); + push(`$request->setRequestMethod(${convertType(method)});`); + + if (hasBody) { + push('$request->setBody($body);'); + blank(); + } + + if (Object.keys(queryObj).length) { + push(`$request->setQuery(new http\\QueryString(${convertType(queryObj, indent)}));`); + blank(); + } + + if (Object.keys(headersObj).length) { + push(`$request->setHeaders(${convertType(headersObj, indent)});`); + blank(); + } + + if (Object.keys(cookiesObj).length) { + blank(); + push(`$client->setCookies(${convertType(cookiesObj, indent)});`); + blank(); + } + + push('$client->enqueue($request)->send();'); + push('$response = $client->getResponse();'); + blank(); + push('echo $response->getBody();'); + + if (!noTags && closingTag) { + blank(); + push('?>'); + } + + return join(); + }, +}; diff --git a/src/targets/php/http2/fixtures/application-form-encoded.php b/src/targets/php/http2/fixtures/application-form-encoded.php new file mode 100644 index 000000000..d32e5ebd8 --- /dev/null +++ b/src/targets/php/http2/fixtures/application-form-encoded.php @@ -0,0 +1,23 @@ +append(new http\QueryString([ + 'foo' => 'bar', + 'hello' => 'world' +])); + +$request->setRequestUrl('https://httpbin.org/anything'); +$request->setRequestMethod('POST'); +$request->setBody($body); + +$request->setHeaders([ + 'content-type' => 'application/x-www-form-urlencoded' +]); + +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/application-json.php b/src/targets/php/http2/fixtures/application-json.php new file mode 100644 index 000000000..4e572ff8a --- /dev/null +++ b/src/targets/php/http2/fixtures/application-json.php @@ -0,0 +1,40 @@ +append(json_encode([ + 'number' => 1, + 'string' => 'f"oo', + 'arr' => [ + 1, + 2, + 3 + ], + 'nested' => [ + 'a' => 'b' + ], + 'arr_mix' => [ + 1, + 'a', + [ + 'arr_mix_nested' => [ + + ] + ] + ], + 'boolean' => false +])); +$request->setRequestUrl('https://httpbin.org/anything'); +$request->setRequestMethod('POST'); +$request->setBody($body); + +$request->setHeaders([ + 'content-type' => 'application/json' +]); + +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/cookies.php b/src/targets/php/http2/fixtures/cookies.php new file mode 100644 index 000000000..498200dd1 --- /dev/null +++ b/src/targets/php/http2/fixtures/cookies.php @@ -0,0 +1,17 @@ +setRequestUrl('https://httpbin.org/cookies'); +$request->setRequestMethod('GET'); + +$client->setCookies([ + 'bar' => 'baz', + 'foo' => 'bar' +]); + +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/custom-method.php b/src/targets/php/http2/fixtures/custom-method.php new file mode 100644 index 000000000..a362a58c6 --- /dev/null +++ b/src/targets/php/http2/fixtures/custom-method.php @@ -0,0 +1,11 @@ +setRequestUrl('https://httpbin.org/anything'); +$request->setRequestMethod('PROPFIND'); +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/full.php b/src/targets/php/http2/fixtures/full.php new file mode 100644 index 000000000..c58af7cf6 --- /dev/null +++ b/src/targets/php/http2/fixtures/full.php @@ -0,0 +1,38 @@ +append(new http\QueryString([ + 'foo' => 'bar' +])); + +$request->setRequestUrl('https://httpbin.org/anything'); +$request->setRequestMethod('POST'); +$request->setBody($body); + +$request->setQuery(new http\QueryString([ + 'foo' => [ + 'bar', + 'baz' + ], + 'baz' => 'abc', + 'key' => 'value' +])); + +$request->setHeaders([ + 'accept' => 'application/json', + 'content-type' => 'application/x-www-form-urlencoded' +]); + + +$client->setCookies([ + 'bar' => 'baz', + 'foo' => 'bar' +]); + +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/headers.php b/src/targets/php/http2/fixtures/headers.php new file mode 100644 index 000000000..b401ef5df --- /dev/null +++ b/src/targets/php/http2/fixtures/headers.php @@ -0,0 +1,18 @@ +setRequestUrl('https://httpbin.org/headers'); +$request->setRequestMethod('GET'); +$request->setHeaders([ + 'accept' => 'application/json', + 'x-foo' => 'Bar', + 'x-bar' => 'Foo', + 'quoted-value' => '"quoted" \'string\'' +]); + +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/http-insecure.php b/src/targets/php/http2/fixtures/http-insecure.php new file mode 100644 index 000000000..458bb2981 --- /dev/null +++ b/src/targets/php/http2/fixtures/http-insecure.php @@ -0,0 +1,11 @@ +setRequestUrl('http://httpbin.org/anything'); +$request->setRequestMethod('GET'); +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/jsonObj-multiline.php b/src/targets/php/http2/fixtures/jsonObj-multiline.php new file mode 100644 index 000000000..b738a6676 --- /dev/null +++ b/src/targets/php/http2/fixtures/jsonObj-multiline.php @@ -0,0 +1,21 @@ +append(json_encode([ + 'foo' => 'bar' +])); +$request->setRequestUrl('https://httpbin.org/anything'); +$request->setRequestMethod('POST'); +$request->setBody($body); + +$request->setHeaders([ + 'content-type' => 'application/json' +]); + +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/jsonObj-null-value.php b/src/targets/php/http2/fixtures/jsonObj-null-value.php new file mode 100644 index 000000000..c4db37d23 --- /dev/null +++ b/src/targets/php/http2/fixtures/jsonObj-null-value.php @@ -0,0 +1,21 @@ +append(json_encode([ + 'foo' => null +])); +$request->setRequestUrl('https://httpbin.org/anything'); +$request->setRequestMethod('POST'); +$request->setBody($body); + +$request->setHeaders([ + 'content-type' => 'application/json' +]); + +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/multipart-data.php b/src/targets/php/http2/fixtures/multipart-data.php new file mode 100644 index 000000000..0c8afd9ac --- /dev/null +++ b/src/targets/php/http2/fixtures/multipart-data.php @@ -0,0 +1,25 @@ +addForm([ + 'bar' => 'Bonjour le monde' +], [ + [ + 'name' => 'foo', + 'type' => 'text/plain', + 'file' => 'src/fixtures/files/hello.txt', + 'data' => 'Hello World' + ] +]); + +$request->setRequestUrl('https://httpbin.org/anything'); +$request->setRequestMethod('POST'); +$request->setBody($body); + +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/multipart-file.php b/src/targets/php/http2/fixtures/multipart-file.php new file mode 100644 index 000000000..0fd6b895c --- /dev/null +++ b/src/targets/php/http2/fixtures/multipart-file.php @@ -0,0 +1,23 @@ +addForm(null, [ + [ + 'name' => 'foo', + 'type' => 'text/plain', + 'file' => 'src/fixtures/files/hello.txt', + 'data' => null + ] +]); + +$request->setRequestUrl('https://httpbin.org/anything'); +$request->setRequestMethod('POST'); +$request->setBody($body); + +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/multipart-form-data-no-params.php b/src/targets/php/http2/fixtures/multipart-form-data-no-params.php new file mode 100644 index 000000000..12bb859c7 --- /dev/null +++ b/src/targets/php/http2/fixtures/multipart-form-data-no-params.php @@ -0,0 +1,15 @@ +setRequestUrl('https://httpbin.org/anything'); +$request->setRequestMethod('POST'); +$request->setHeaders([ + 'Content-Type' => 'multipart/form-data' +]); + +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/multipart-form-data.php b/src/targets/php/http2/fixtures/multipart-form-data.php new file mode 100644 index 000000000..82fedc0d9 --- /dev/null +++ b/src/targets/php/http2/fixtures/multipart-form-data.php @@ -0,0 +1,18 @@ +addForm([ + 'foo' => 'bar' +], null); + +$request->setRequestUrl('https://httpbin.org/anything'); +$request->setRequestMethod('POST'); +$request->setBody($body); + +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/nested.php b/src/targets/php/http2/fixtures/nested.php new file mode 100644 index 000000000..d91a64ddc --- /dev/null +++ b/src/targets/php/http2/fixtures/nested.php @@ -0,0 +1,17 @@ +setRequestUrl('https://httpbin.org/anything'); +$request->setRequestMethod('GET'); +$request->setQuery(new http\QueryString([ + 'foo[bar]' => 'baz,zap', + 'fiz' => 'buz', + 'key' => 'value' +])); + +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/postdata-malformed.php b/src/targets/php/http2/fixtures/postdata-malformed.php new file mode 100644 index 000000000..17dc58c62 --- /dev/null +++ b/src/targets/php/http2/fixtures/postdata-malformed.php @@ -0,0 +1,15 @@ +setRequestUrl('https://httpbin.org/anything'); +$request->setRequestMethod('POST'); +$request->setHeaders([ + 'content-type' => 'application/json' +]); + +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/query-encoded.php b/src/targets/php/http2/fixtures/query-encoded.php new file mode 100644 index 000000000..0c2a4764d --- /dev/null +++ b/src/targets/php/http2/fixtures/query-encoded.php @@ -0,0 +1,16 @@ +setRequestUrl('https://httpbin.org/anything'); +$request->setRequestMethod('GET'); +$request->setQuery(new http\QueryString([ + 'startTime' => '2019-06-13T19%3A08%3A25.455Z', + 'endTime' => '2015-09-15T14%3A00%3A12-04%3A00' +])); + +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/query.php b/src/targets/php/http2/fixtures/query.php new file mode 100644 index 000000000..a32e58f14 --- /dev/null +++ b/src/targets/php/http2/fixtures/query.php @@ -0,0 +1,20 @@ +setRequestUrl('https://httpbin.org/anything'); +$request->setRequestMethod('GET'); +$request->setQuery(new http\QueryString([ + 'foo' => [ + 'bar', + 'baz' + ], + 'baz' => 'abc', + 'key' => 'value' +])); + +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/short.php b/src/targets/php/http2/fixtures/short.php new file mode 100644 index 000000000..92f5223df --- /dev/null +++ b/src/targets/php/http2/fixtures/short.php @@ -0,0 +1,11 @@ +setRequestUrl('https://httpbin.org/anything'); +$request->setRequestMethod('GET'); +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/http2/fixtures/text-plain.php b/src/targets/php/http2/fixtures/text-plain.php new file mode 100644 index 000000000..5974dfcf2 --- /dev/null +++ b/src/targets/php/http2/fixtures/text-plain.php @@ -0,0 +1,20 @@ +append('Hello World'); + +$request->setRequestUrl('https://httpbin.org/anything'); +$request->setRequestMethod('POST'); +$request->setBody($body); + +$request->setHeaders([ + 'content-type' => 'text/plain' +]); + +$client->enqueue($request)->send(); +$response = $client->getResponse(); + +echo $response->getBody(); \ No newline at end of file diff --git a/src/targets/php/index.js b/src/targets/php/index.js deleted file mode 100644 index 39f6bfa1a..000000000 --- a/src/targets/php/index.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict' - -module.exports = { - info: { - key: 'php', - title: 'PHP', - extname: '.php', - default: 'curl' - }, - - curl: require('./curl'), - http1: require('./http1'), - http2: require('./http2') -} diff --git a/src/targets/php/target.ts b/src/targets/php/target.ts new file mode 100644 index 000000000..70bb7243a --- /dev/null +++ b/src/targets/php/target.ts @@ -0,0 +1,21 @@ +import type { Target } from '../index.js'; + +import { curl } from './curl/client.js'; +import { guzzle } from './guzzle/client.js'; +import { http1 } from './http1/client.js'; +import { http2 } from './http2/client.js'; + +export const php: Target = { + info: { + key: 'php', + title: 'PHP', + default: 'curl', + cli: 'php %s', + }, + clientsById: { + curl, + guzzle, + http1, + http2, + }, +}; diff --git a/src/targets/powershell/common.ts b/src/targets/powershell/common.ts new file mode 100644 index 000000000..80db499bd --- /dev/null +++ b/src/targets/powershell/common.ts @@ -0,0 +1,62 @@ +import type { Converter } from '../index.js'; + +import { CodeBuilder } from '../../helpers/code-builder.js'; +import { escapeString } from '../../helpers/escape.js'; +import { getHeader } from '../../helpers/headers.js'; + +export type PowershellCommand = 'Invoke-RestMethod' | 'Invoke-WebRequest'; + +export const generatePowershellConvert = (command: PowershellCommand): Converter => { + const convert: Converter = ({ method, headersObj, cookies, uriObj, fullUrl, postData, allHeaders }) => { + const { push, join } = new CodeBuilder(); + const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']; + + if (!methods.includes(method.toUpperCase())) { + return 'Method not supported'; + } + + const commandOptions = []; + + // Add headers, including the cookies + const headers = Object.keys(headersObj); + + // construct headers + if (headers.length) { + push('$headers=@{}'); + headers.forEach(key => { + if (key !== 'connection') { + // Not allowed + push(`$headers.Add("${key}", "${escapeString(headersObj[key], { escapeChar: '`' })}")`); + } + }); + commandOptions.push('-Headers $headers'); + } + + // construct cookies + if (cookies.length) { + push('$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession'); + + cookies.forEach(cookie => { + push('$cookie = New-Object System.Net.Cookie'); + + push(`$cookie.Name = '${cookie.name}'`); + push(`$cookie.Value = '${cookie.value}'`); + push(`$cookie.Domain = '${uriObj.host}'`); + + push('$session.Cookies.Add($cookie)'); + }); + commandOptions.push('-WebSession $session'); + } + + if (postData.text) { + commandOptions.push( + `-ContentType '${escapeString(getHeader(allHeaders, 'content-type'), { delimiter: "'", escapeChar: '`' })}'`, + ); + commandOptions.push(`-Body '${postData.text}'`); + } + + push(`$response = ${command} -Uri '${fullUrl}' -Method ${method} ${commandOptions.join(' ')}`.trim()); + return join(); + }; + return convert; +}; diff --git a/src/targets/powershell/restmethod/client.ts b/src/targets/powershell/restmethod/client.ts new file mode 100644 index 000000000..4eddeee02 --- /dev/null +++ b/src/targets/powershell/restmethod/client.ts @@ -0,0 +1,14 @@ +import type { Client } from '../../index.js'; + +import { generatePowershellConvert } from '../common.js'; + +export const restmethod: Client = { + info: { + key: 'restmethod', + title: 'Invoke-RestMethod', + link: 'https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Invoke-RestMethod', + description: 'Powershell Invoke-RestMethod client', + extname: '.ps1', + }, + convert: generatePowershellConvert('Invoke-RestMethod'), +}; diff --git a/src/targets/powershell/restmethod/fixtures/application-form-encoded.ps1 b/src/targets/powershell/restmethod/fixtures/application-form-encoded.ps1 new file mode 100644 index 000000000..4c34aae3a --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/application-form-encoded.ps1 @@ -0,0 +1,3 @@ +$headers=@{} +$headers.Add("content-type", "application/x-www-form-urlencoded") +$response = Invoke-RestMethod -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers -ContentType 'application/x-www-form-urlencoded' -Body 'foo=bar&hello=world' \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/application-json.ps1 b/src/targets/powershell/restmethod/fixtures/application-json.ps1 new file mode 100644 index 000000000..e045d9b44 --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/application-json.ps1 @@ -0,0 +1,3 @@ +$headers=@{} +$headers.Add("content-type", "application/json") +$response = Invoke-RestMethod -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers -ContentType 'application/json' -Body '{"number":1,"string":"f\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":[]}],"boolean":false}' \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/cookies.ps1 b/src/targets/powershell/restmethod/fixtures/cookies.ps1 new file mode 100644 index 000000000..becd7b246 --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/cookies.ps1 @@ -0,0 +1,12 @@ +$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession +$cookie = New-Object System.Net.Cookie +$cookie.Name = 'foo' +$cookie.Value = 'bar' +$cookie.Domain = 'httpbin.org' +$session.Cookies.Add($cookie) +$cookie = New-Object System.Net.Cookie +$cookie.Name = 'bar' +$cookie.Value = 'baz' +$cookie.Domain = 'httpbin.org' +$session.Cookies.Add($cookie) +$response = Invoke-RestMethod -Uri 'https://httpbin.org/cookies' -Method GET -WebSession $session \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/custom-method.ps1 b/src/targets/powershell/restmethod/fixtures/custom-method.ps1 new file mode 100644 index 000000000..8eb41a680 --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/custom-method.ps1 @@ -0,0 +1 @@ +Method not supported \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/full.ps1 b/src/targets/powershell/restmethod/fixtures/full.ps1 new file mode 100644 index 000000000..3af9b8fa0 --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/full.ps1 @@ -0,0 +1,15 @@ +$headers=@{} +$headers.Add("accept", "application/json") +$headers.Add("content-type", "application/x-www-form-urlencoded") +$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession +$cookie = New-Object System.Net.Cookie +$cookie.Name = 'foo' +$cookie.Value = 'bar' +$cookie.Domain = 'httpbin.org' +$session.Cookies.Add($cookie) +$cookie = New-Object System.Net.Cookie +$cookie.Name = 'bar' +$cookie.Value = 'baz' +$cookie.Domain = 'httpbin.org' +$session.Cookies.Add($cookie) +$response = Invoke-RestMethod -Uri 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value' -Method POST -Headers $headers -WebSession $session -ContentType 'application/x-www-form-urlencoded' -Body 'foo=bar' \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/headers.ps1 b/src/targets/powershell/restmethod/fixtures/headers.ps1 new file mode 100644 index 000000000..826ccd3d2 --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/headers.ps1 @@ -0,0 +1,6 @@ +$headers=@{} +$headers.Add("accept", "application/json") +$headers.Add("x-foo", "Bar") +$headers.Add("x-bar", "Foo") +$headers.Add("quoted-value", "`"quoted`" 'string'") +$response = Invoke-RestMethod -Uri 'https://httpbin.org/headers' -Method GET -Headers $headers \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/http-insecure.ps1 b/src/targets/powershell/restmethod/fixtures/http-insecure.ps1 new file mode 100644 index 000000000..877c4a8a8 --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/http-insecure.ps1 @@ -0,0 +1 @@ +$response = Invoke-RestMethod -Uri 'http://httpbin.org/anything' -Method GET \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/jsonObj-multiline.ps1 b/src/targets/powershell/restmethod/fixtures/jsonObj-multiline.ps1 new file mode 100644 index 000000000..97ec21699 --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/jsonObj-multiline.ps1 @@ -0,0 +1,5 @@ +$headers=@{} +$headers.Add("content-type", "application/json") +$response = Invoke-RestMethod -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers -ContentType 'application/json' -Body '{ + "foo": "bar" +}' \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/jsonObj-null-value.ps1 b/src/targets/powershell/restmethod/fixtures/jsonObj-null-value.ps1 new file mode 100644 index 000000000..b49509526 --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/jsonObj-null-value.ps1 @@ -0,0 +1,3 @@ +$headers=@{} +$headers.Add("content-type", "application/json") +$response = Invoke-RestMethod -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers -ContentType 'application/json' -Body '{"foo":null}' \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/multipart-data.ps1 b/src/targets/powershell/restmethod/fixtures/multipart-data.ps1 new file mode 100644 index 000000000..4073bd282 --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/multipart-data.ps1 @@ -0,0 +1,12 @@ +$headers=@{} +$headers.Add("content-type", "multipart/form-data; boundary=---011000010111000001101001") +$response = Invoke-RestMethod -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers -ContentType 'multipart/form-data; boundary=---011000010111000001101001' -Body '-----011000010111000001101001 +Content-Disposition: form-data; name="foo"; filename="src/fixtures/files/hello.txt" +Content-Type: text/plain + +Hello World +-----011000010111000001101001 +Content-Disposition: form-data; name="bar" + +Bonjour le monde +-----011000010111000001101001--' \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/multipart-file.ps1 b/src/targets/powershell/restmethod/fixtures/multipart-file.ps1 new file mode 100644 index 000000000..8fc069e4f --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/multipart-file.ps1 @@ -0,0 +1,8 @@ +$headers=@{} +$headers.Add("content-type", "multipart/form-data; boundary=---011000010111000001101001") +$response = Invoke-RestMethod -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers -ContentType 'multipart/form-data; boundary=---011000010111000001101001' -Body '-----011000010111000001101001 +Content-Disposition: form-data; name="foo"; filename="src/fixtures/files/hello.txt" +Content-Type: text/plain + + +-----011000010111000001101001--' \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/multipart-form-data-no-params.ps1 b/src/targets/powershell/restmethod/fixtures/multipart-form-data-no-params.ps1 new file mode 100644 index 000000000..564a0b275 --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/multipart-form-data-no-params.ps1 @@ -0,0 +1,3 @@ +$headers=@{} +$headers.Add("Content-Type", "multipart/form-data") +$response = Invoke-RestMethod -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/multipart-form-data.ps1 b/src/targets/powershell/restmethod/fixtures/multipart-form-data.ps1 new file mode 100644 index 000000000..f75249092 --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/multipart-form-data.ps1 @@ -0,0 +1,7 @@ +$headers=@{} +$headers.Add("Content-Type", "multipart/form-data; boundary=---011000010111000001101001") +$response = Invoke-RestMethod -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers -ContentType 'multipart/form-data; boundary=---011000010111000001101001' -Body '-----011000010111000001101001 +Content-Disposition: form-data; name="foo" + +bar +-----011000010111000001101001--' \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/nested.ps1 b/src/targets/powershell/restmethod/fixtures/nested.ps1 new file mode 100644 index 000000000..e2cf0efab --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/nested.ps1 @@ -0,0 +1 @@ +$response = Invoke-RestMethod -Uri 'https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value' -Method GET \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/postdata-malformed.ps1 b/src/targets/powershell/restmethod/fixtures/postdata-malformed.ps1 new file mode 100644 index 000000000..0ba7f1328 --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/postdata-malformed.ps1 @@ -0,0 +1,3 @@ +$headers=@{} +$headers.Add("content-type", "application/json") +$response = Invoke-RestMethod -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/query-encoded.ps1 b/src/targets/powershell/restmethod/fixtures/query-encoded.ps1 new file mode 100644 index 000000000..d8254a5b4 --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/query-encoded.ps1 @@ -0,0 +1 @@ +$response = Invoke-RestMethod -Uri 'https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00' -Method GET \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/query.ps1 b/src/targets/powershell/restmethod/fixtures/query.ps1 new file mode 100644 index 000000000..7ce65a7f1 --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/query.ps1 @@ -0,0 +1 @@ +$response = Invoke-RestMethod -Uri 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value' -Method GET \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/short.ps1 b/src/targets/powershell/restmethod/fixtures/short.ps1 new file mode 100644 index 000000000..40de98ee8 --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/short.ps1 @@ -0,0 +1 @@ +$response = Invoke-RestMethod -Uri 'https://httpbin.org/anything' -Method GET \ No newline at end of file diff --git a/src/targets/powershell/restmethod/fixtures/text-plain.ps1 b/src/targets/powershell/restmethod/fixtures/text-plain.ps1 new file mode 100644 index 000000000..2c89af8cb --- /dev/null +++ b/src/targets/powershell/restmethod/fixtures/text-plain.ps1 @@ -0,0 +1,3 @@ +$headers=@{} +$headers.Add("content-type", "text/plain") +$response = Invoke-RestMethod -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers -ContentType 'text/plain' -Body 'Hello World' \ No newline at end of file diff --git a/src/targets/powershell/target.ts b/src/targets/powershell/target.ts new file mode 100644 index 000000000..8bfc898e0 --- /dev/null +++ b/src/targets/powershell/target.ts @@ -0,0 +1,16 @@ +import type { Target } from '../index.js'; + +import { restmethod } from './restmethod/client.js'; +import { webrequest } from './webrequest/client.js'; + +export const powershell: Target = { + info: { + key: 'powershell', + title: 'Powershell', + default: 'webrequest', + }, + clientsById: { + webrequest, + restmethod, + }, +}; diff --git a/src/targets/powershell/webrequest/client.ts b/src/targets/powershell/webrequest/client.ts new file mode 100644 index 000000000..383b52fce --- /dev/null +++ b/src/targets/powershell/webrequest/client.ts @@ -0,0 +1,14 @@ +import type { Client } from '../../index.js'; + +import { generatePowershellConvert } from '../common.js'; + +export const webrequest: Client = { + info: { + key: 'webrequest', + title: 'Invoke-WebRequest', + link: 'https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Invoke-WebRequest', + description: 'Powershell Invoke-WebRequest client', + extname: '.ps1', + }, + convert: generatePowershellConvert('Invoke-WebRequest'), +}; diff --git a/src/targets/powershell/webrequest/fixtures/application-form-encoded.ps1 b/src/targets/powershell/webrequest/fixtures/application-form-encoded.ps1 new file mode 100644 index 000000000..5270e4c6c --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/application-form-encoded.ps1 @@ -0,0 +1,3 @@ +$headers=@{} +$headers.Add("content-type", "application/x-www-form-urlencoded") +$response = Invoke-WebRequest -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers -ContentType 'application/x-www-form-urlencoded' -Body 'foo=bar&hello=world' \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/application-json.ps1 b/src/targets/powershell/webrequest/fixtures/application-json.ps1 new file mode 100644 index 000000000..8ff3844f2 --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/application-json.ps1 @@ -0,0 +1,3 @@ +$headers=@{} +$headers.Add("content-type", "application/json") +$response = Invoke-WebRequest -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers -ContentType 'application/json' -Body '{"number":1,"string":"f\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":[]}],"boolean":false}' \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/cookies.ps1 b/src/targets/powershell/webrequest/fixtures/cookies.ps1 new file mode 100644 index 000000000..e94cfb6ed --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/cookies.ps1 @@ -0,0 +1,12 @@ +$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession +$cookie = New-Object System.Net.Cookie +$cookie.Name = 'foo' +$cookie.Value = 'bar' +$cookie.Domain = 'httpbin.org' +$session.Cookies.Add($cookie) +$cookie = New-Object System.Net.Cookie +$cookie.Name = 'bar' +$cookie.Value = 'baz' +$cookie.Domain = 'httpbin.org' +$session.Cookies.Add($cookie) +$response = Invoke-WebRequest -Uri 'https://httpbin.org/cookies' -Method GET -WebSession $session \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/custom-method.ps1 b/src/targets/powershell/webrequest/fixtures/custom-method.ps1 new file mode 100644 index 000000000..8eb41a680 --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/custom-method.ps1 @@ -0,0 +1 @@ +Method not supported \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/full.ps1 b/src/targets/powershell/webrequest/fixtures/full.ps1 new file mode 100644 index 000000000..0840cf848 --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/full.ps1 @@ -0,0 +1,15 @@ +$headers=@{} +$headers.Add("accept", "application/json") +$headers.Add("content-type", "application/x-www-form-urlencoded") +$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession +$cookie = New-Object System.Net.Cookie +$cookie.Name = 'foo' +$cookie.Value = 'bar' +$cookie.Domain = 'httpbin.org' +$session.Cookies.Add($cookie) +$cookie = New-Object System.Net.Cookie +$cookie.Name = 'bar' +$cookie.Value = 'baz' +$cookie.Domain = 'httpbin.org' +$session.Cookies.Add($cookie) +$response = Invoke-WebRequest -Uri 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value' -Method POST -Headers $headers -WebSession $session -ContentType 'application/x-www-form-urlencoded' -Body 'foo=bar' \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/headers.ps1 b/src/targets/powershell/webrequest/fixtures/headers.ps1 new file mode 100644 index 000000000..756d7efa7 --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/headers.ps1 @@ -0,0 +1,6 @@ +$headers=@{} +$headers.Add("accept", "application/json") +$headers.Add("x-foo", "Bar") +$headers.Add("x-bar", "Foo") +$headers.Add("quoted-value", "`"quoted`" 'string'") +$response = Invoke-WebRequest -Uri 'https://httpbin.org/headers' -Method GET -Headers $headers \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/http-insecure.ps1 b/src/targets/powershell/webrequest/fixtures/http-insecure.ps1 new file mode 100644 index 000000000..a414ebe9e --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/http-insecure.ps1 @@ -0,0 +1 @@ +$response = Invoke-WebRequest -Uri 'http://httpbin.org/anything' -Method GET \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/jsonObj-multiline.ps1 b/src/targets/powershell/webrequest/fixtures/jsonObj-multiline.ps1 new file mode 100644 index 000000000..bd31a1c86 --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/jsonObj-multiline.ps1 @@ -0,0 +1,5 @@ +$headers=@{} +$headers.Add("content-type", "application/json") +$response = Invoke-WebRequest -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers -ContentType 'application/json' -Body '{ + "foo": "bar" +}' \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/jsonObj-null-value.ps1 b/src/targets/powershell/webrequest/fixtures/jsonObj-null-value.ps1 new file mode 100644 index 000000000..7b77968b4 --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/jsonObj-null-value.ps1 @@ -0,0 +1,3 @@ +$headers=@{} +$headers.Add("content-type", "application/json") +$response = Invoke-WebRequest -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers -ContentType 'application/json' -Body '{"foo":null}' \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/multipart-data.ps1 b/src/targets/powershell/webrequest/fixtures/multipart-data.ps1 new file mode 100644 index 000000000..29281a0f7 --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/multipart-data.ps1 @@ -0,0 +1,12 @@ +$headers=@{} +$headers.Add("content-type", "multipart/form-data; boundary=---011000010111000001101001") +$response = Invoke-WebRequest -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers -ContentType 'multipart/form-data; boundary=---011000010111000001101001' -Body '-----011000010111000001101001 +Content-Disposition: form-data; name="foo"; filename="src/fixtures/files/hello.txt" +Content-Type: text/plain + +Hello World +-----011000010111000001101001 +Content-Disposition: form-data; name="bar" + +Bonjour le monde +-----011000010111000001101001--' \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/multipart-file.ps1 b/src/targets/powershell/webrequest/fixtures/multipart-file.ps1 new file mode 100644 index 000000000..120321a6a --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/multipart-file.ps1 @@ -0,0 +1,8 @@ +$headers=@{} +$headers.Add("content-type", "multipart/form-data; boundary=---011000010111000001101001") +$response = Invoke-WebRequest -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers -ContentType 'multipart/form-data; boundary=---011000010111000001101001' -Body '-----011000010111000001101001 +Content-Disposition: form-data; name="foo"; filename="src/fixtures/files/hello.txt" +Content-Type: text/plain + + +-----011000010111000001101001--' \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/multipart-form-data-no-params.ps1 b/src/targets/powershell/webrequest/fixtures/multipart-form-data-no-params.ps1 new file mode 100644 index 000000000..48aeea78a --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/multipart-form-data-no-params.ps1 @@ -0,0 +1,3 @@ +$headers=@{} +$headers.Add("Content-Type", "multipart/form-data") +$response = Invoke-WebRequest -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/multipart-form-data.ps1 b/src/targets/powershell/webrequest/fixtures/multipart-form-data.ps1 new file mode 100644 index 000000000..8c7f3c140 --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/multipart-form-data.ps1 @@ -0,0 +1,7 @@ +$headers=@{} +$headers.Add("Content-Type", "multipart/form-data; boundary=---011000010111000001101001") +$response = Invoke-WebRequest -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers -ContentType 'multipart/form-data; boundary=---011000010111000001101001' -Body '-----011000010111000001101001 +Content-Disposition: form-data; name="foo" + +bar +-----011000010111000001101001--' \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/nested.ps1 b/src/targets/powershell/webrequest/fixtures/nested.ps1 new file mode 100644 index 000000000..1dee2ea65 --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/nested.ps1 @@ -0,0 +1 @@ +$response = Invoke-WebRequest -Uri 'https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value' -Method GET \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/postdata-malformed.ps1 b/src/targets/powershell/webrequest/fixtures/postdata-malformed.ps1 new file mode 100644 index 000000000..c79628ad4 --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/postdata-malformed.ps1 @@ -0,0 +1,3 @@ +$headers=@{} +$headers.Add("content-type", "application/json") +$response = Invoke-WebRequest -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/query-encoded.ps1 b/src/targets/powershell/webrequest/fixtures/query-encoded.ps1 new file mode 100644 index 000000000..f62a77eb6 --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/query-encoded.ps1 @@ -0,0 +1 @@ +$response = Invoke-WebRequest -Uri 'https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00' -Method GET \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/query.ps1 b/src/targets/powershell/webrequest/fixtures/query.ps1 new file mode 100644 index 000000000..d1e9fd190 --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/query.ps1 @@ -0,0 +1 @@ +$response = Invoke-WebRequest -Uri 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value' -Method GET \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/short.ps1 b/src/targets/powershell/webrequest/fixtures/short.ps1 new file mode 100644 index 000000000..d6367b3d6 --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/short.ps1 @@ -0,0 +1 @@ +$response = Invoke-WebRequest -Uri 'https://httpbin.org/anything' -Method GET \ No newline at end of file diff --git a/src/targets/powershell/webrequest/fixtures/text-plain.ps1 b/src/targets/powershell/webrequest/fixtures/text-plain.ps1 new file mode 100644 index 000000000..f460cc153 --- /dev/null +++ b/src/targets/powershell/webrequest/fixtures/text-plain.ps1 @@ -0,0 +1,3 @@ +$headers=@{} +$headers.Add("content-type", "text/plain") +$response = Invoke-WebRequest -Uri 'https://httpbin.org/anything' -Method POST -Headers $headers -ContentType 'text/plain' -Body 'Hello World' \ No newline at end of file diff --git a/src/targets/python/helpers.ts b/src/targets/python/helpers.ts new file mode 100644 index 000000000..e39cc987a --- /dev/null +++ b/src/targets/python/helpers.ts @@ -0,0 +1,76 @@ +/** + * Create a string corresponding to a Dictionary or Array literal representation with pretty option + * and indentation. + */ +function concatValues( + concatType: 'array' | 'object', + values: any, + pretty: boolean, + indentation: string, + indentLevel: number, +) { + const currentIndent = indentation.repeat(indentLevel); + const closingBraceIndent = indentation.repeat(indentLevel - 1); + const join = pretty ? `,\n${currentIndent}` : ', '; + const openingBrace = concatType === 'object' ? '{' : '['; + const closingBrace = concatType === 'object' ? '}' : ']'; + + if (pretty) { + return `${openingBrace}\n${currentIndent}${values.join(join)}\n${closingBraceIndent}${closingBrace}`; + } + + if (concatType === 'object' && values.length > 0) { + return `${openingBrace} ${values.join(join)} ${closingBrace}`; + } + + return `${openingBrace}${values.join(join)}${closingBrace}`; +} + +/** + * Create a valid Python string of a literal value according to its type. + * + * @param {*} value Any JavaScript literal + * @param {Object} opts Target options + * @return {string} + */ +export const literalRepresentation = (value: any, opts: Record, indentLevel?: number): any => { + indentLevel = indentLevel === undefined ? 1 : indentLevel + 1; + + switch (Object.prototype.toString.call(value)) { + case '[object Number]': + return value; + + case '[object Array]': { + let pretty = false; + const valuesRepresentation: any = (value as any[]).map(v => { + // Switch to prettify if the value is a dictionary with multiple keys + if (Object.prototype.toString.call(v) === '[object Object]') { + pretty = Object.keys(v).length > 1; + } + return literalRepresentation(v, opts, indentLevel); + }); + return concatValues('array', valuesRepresentation, pretty, opts.indent, indentLevel); + } + + case '[object Object]': { + const keyValuePairs = []; + for (const key in value) { + keyValuePairs.push(`"${key}": ${literalRepresentation(value[key], opts, indentLevel)}`); + } + + return concatValues('object', keyValuePairs, opts.pretty && keyValuePairs.length > 1, opts.indent, indentLevel); + } + + case '[object Null]': + return 'None'; + + case '[object Boolean]': + return value ? 'True' : 'False'; + + default: + if (value === null || value === undefined) { + return ''; + } + return `"${value.toString().replace(/"/g, '\\"')}"`; + } +}; diff --git a/src/targets/python/index.js b/src/targets/python/index.js deleted file mode 100644 index 38f5ee736..000000000 --- a/src/targets/python/index.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict' - -module.exports = { - info: { - key: 'python', - title: 'Python', - extname: '.py', - default: 'python3' - }, - - python3: require('./python3'), - requests: require('./requests') -} diff --git a/src/targets/python/python3.js b/src/targets/python/python3.js deleted file mode 100644 index 753a6571a..000000000 --- a/src/targets/python/python3.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * @description - * HTTP code snippet generator for native Python3. - * - * @author - * @montanaflynn - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var code = new CodeBuilder() - // Start Request - code.push('import http.client') - .blank() - - // Check which protocol to be used for the client connection - var protocol = source.uriObj.protocol - if (protocol === 'https:') { - code.push('conn = http.client.HTTPSConnection("%s")', source.uriObj.host) - .blank() - } else { - code.push('conn = http.client.HTTPConnection("%s")', source.uriObj.host) - .blank() - } - - // Create payload string if it exists - var payload = JSON.stringify(source.postData.text) - if (payload) { - code.push('payload = %s', payload) - .blank() - } - - // Create Headers - var header - var headers = source.allHeaders - var headerCount = Object.keys(headers).length - if (headerCount === 1) { - for (header in headers) { - code.push('headers = { \'%s\': "%s" }', header, headers[header]) - .blank() - } - } else if (headerCount > 1) { - var count = 1 - - code.push('headers = {') - - for (header in headers) { - if (count++ !== headerCount) { - code.push(' \'%s\': "%s",', header, headers[header]) - } else { - code.push(' \'%s\': "%s"', header, headers[header]) - } - } - - code.push(' }') - .blank() - } - - // Make Request - var method = source.method - var path = source.uriObj.path - if (payload && headerCount) { - code.push('conn.request("%s", "%s", payload, headers)', method, path) - } else if (payload && !headerCount) { - code.push('conn.request("%s", "%s", payload)', method, path) - } else if (!payload && headerCount) { - code.push('conn.request("%s", "%s", headers=headers)', method, path) - } else { - code.push('conn.request("%s", "%s")', method, path) - } - - // Get Response - code.blank() - .push('res = conn.getresponse()') - .push('data = res.read()') - .blank() - .push('print(data.decode("utf-8"))') - - return code.join() -} - -module.exports.info = { - key: 'python3', - title: 'http.client', - link: 'https://docs.python.org/3/library/http.client.html', - description: 'Python3 HTTP Client' -} diff --git a/src/targets/python/requests.js b/src/targets/python/requests.js deleted file mode 100644 index 299eff9d7..000000000 --- a/src/targets/python/requests.js +++ /dev/null @@ -1,104 +0,0 @@ -/** - * @description - * HTTP code snippet generator for Python using Requests - * - * @author - * @montanaflynn - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - // Start snippet - var code = new CodeBuilder(' ') - - // Import requests - code.push('import requests') - .blank() - - // Set URL - code.push('url = "%s"', source.url) - .blank() - - // Construct query string - if (source.queryString.length) { - var qs = 'querystring = ' + JSON.stringify(source.queryObj) - - code.push(qs) - .blank() - } - - // Construct payload - var payload = JSON.stringify(source.postData.text) - - if (payload) { - code.push('payload = %s', payload) - } - - // Construct headers - var header - var headers = source.allHeaders - var headerCount = Object.keys(headers).length - - if (headerCount === 1) { - for (header in headers) { - code.push('headers = {\'%s\': \'%s\'}', header, headers[header]) - .blank() - } - } else if (headerCount > 1) { - var count = 1 - - code.push('headers = {') - - for (header in headers) { - if (count++ !== headerCount) { - code.push(1, '\'%s\': "%s",', header, headers[header]) - } else { - code.push(1, '\'%s\': "%s"', header, headers[header]) - } - } - - code.push(1, '}') - .blank() - } - - // Construct request - var method = source.method - var request = util.format('response = requests.request("%s", url', method) - - if (payload) { - request += ', data=payload' - } - - if (headerCount > 0) { - request += ', headers=headers' - } - - if (qs) { - request += ', params=querystring' - } - - request += ')' - - code.push(request) - .blank() - - // Print response - .push('print(response.text)') - - return code.join() -} - -module.exports.info = { - key: 'requests', - title: 'Requests', - link: 'http://docs.python-requests.org/en/latest/api/#requests.request', - description: 'Requests HTTP library' -} - -// response = requests.request("POST", url, data=payload, headers=headers, params=querystring) diff --git a/src/targets/python/requests/client.test.ts b/src/targets/python/requests/client.test.ts new file mode 100644 index 000000000..6d1b3f9bf --- /dev/null +++ b/src/targets/python/requests/client.test.ts @@ -0,0 +1,18 @@ +import type { Request } from '../../../index.js'; + +import { runCustomFixtures } from '../../../fixtures/runCustomFixtures.js'; + +runCustomFixtures({ + targetId: 'python', + clientId: 'requests', + tests: [ + { + expected: 'query-params.py', + options: { + showBoilerplate: false, + }, + input: { method: 'GET', url: 'https://httpbin.org/anything?param=value' } as Request, + it: "should support query parameters provided in HAR's url", + }, + ], +}); diff --git a/src/targets/python/requests/client.ts b/src/targets/python/requests/client.ts new file mode 100644 index 000000000..0b2f6cb8b --- /dev/null +++ b/src/targets/python/requests/client.ts @@ -0,0 +1,190 @@ +/** + * @description + * HTTP code snippet generator for Python using Requests + * + * @author + * @montanaflynn + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { escapeForDoubleQuotes } from '../../../helpers/escape.js'; +import { getHeaderName } from '../../../helpers/headers.js'; +import { literalRepresentation } from '../helpers.js'; + +const builtInMethods = ['HEAD', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']; + +export interface RequestsOptions { + pretty?: true; +} + +export const requests: Client = { + info: { + key: 'requests', + title: 'Requests', + link: 'http://docs.python-requests.org/en/latest/api/#requests.request', + description: 'Requests HTTP library', + extname: '.py', + installation: () => 'python -m pip install requests', + }, + convert: ({ fullUrl, postData, allHeaders, method }, options) => { + const opts = { + indent: ' ', + pretty: true, + ...options, + }; + // Start snippet + const { push, blank, join, addPostProcessor } = new CodeBuilder({ indent: opts.indent }); + + // Import requests + push('import requests'); + blank(); + + // Set URL + push(`url = "${fullUrl}"`); + blank(); + + const headers = allHeaders; + + // Construct payload + let payload: Record = {}; + const files: Record = {}; + + let hasFiles = false; + let hasPayload = false; + let jsonPayload = false; + switch (postData.mimeType) { + case 'application/json': + if (postData.jsonObj) { + push(`payload = ${literalRepresentation(postData.jsonObj, opts)}`); + jsonPayload = true; + hasPayload = true; + } + break; + + case 'multipart/form-data': + if (!postData.params) { + break; + } + + payload = {}; + postData.params.forEach(p => { + if (p.fileName) { + if (p.contentType) { + files[p.name] = `('${p.fileName}', open('${p.fileName}', 'rb'), '${p.contentType}')`; + } else { + files[p.name] = `('${p.fileName}', open('${p.fileName}', 'rb'))`; + } + + hasFiles = true; + } else { + payload[p.name] = p.value; + hasPayload = true; + } + }); + + if (hasFiles) { + push(`files = ${literalRepresentation(files, opts)}`); + + if (hasPayload) { + push(`payload = ${literalRepresentation(payload, opts)}`); + } + + // The requests library will only automatically add a `multipart/form-data` header if there are files being sent. If we're **only** sending form data we still need to send the boundary ourselves. + const headerName = getHeaderName(headers, 'content-type'); + if (headerName) { + delete headers[headerName]; + } + } else { + const nonFilePayload = JSON.stringify(postData.text); + if (nonFilePayload) { + push(`payload = ${nonFilePayload}`); + hasPayload = true; + } + } + + // The `open()` call must be a literal in the code snippet. + addPostProcessor(code => + code + .replace(/"\('(.+)', open\('(.+)', 'rb'\)\)"/g, '("$1", open("$2", "rb"))') + .replace(/"\('(.+)', open\('(.+)', 'rb'\), '(.+)'\)"/g, '("$1", open("$2", "rb"), "$3")'), + ); + break; + + default: { + if (postData.mimeType === 'application/x-www-form-urlencoded' && postData.paramsObj) { + push(`payload = ${literalRepresentation(postData.paramsObj, opts)}`); + hasPayload = true; + break; + } + + const stringPayload = JSON.stringify(postData.text); + if (stringPayload) { + push(`payload = ${stringPayload}`); + hasPayload = true; + } + } + } + + // Construct headers + const headerCount = Object.keys(headers).length; + + if (headerCount === 0 && (hasPayload || hasFiles)) { + // If we don't have any heads but we do have a payload we should put a blank line here between that payload consturction and our execution of the requests library. + blank(); + } else if (headerCount === 1) { + Object.keys(headers).forEach(header => { + push(`headers = {"${header}": "${escapeForDoubleQuotes(headers[header])}"}`); + blank(); + }); + } else if (headerCount > 1) { + let count = 1; + + push('headers = {'); + + Object.keys(headers).forEach(header => { + if (count !== headerCount) { + push(`"${header}": "${escapeForDoubleQuotes(headers[header])}",`, 1); + } else { + push(`"${header}": "${escapeForDoubleQuotes(headers[header])}"`, 1); + } + count += 1; + }); + + push('}'); + blank(); + } + + // Construct request + let request = builtInMethods.includes(method) + ? `response = requests.${method.toLowerCase()}(url` + : `response = requests.request("${method}", url`; + + if (hasPayload) { + if (jsonPayload) { + request += ', json=payload'; + } else { + request += ', data=payload'; + } + } + + if (hasFiles) { + request += ', files=files'; + } + + if (headerCount > 0) { + request += ', headers=headers'; + } + + request += ')'; + + push(request); + blank(); + + push('print(response.text)'); + + return join(); + }, +}; diff --git a/src/targets/python/requests/fixtures/application-form-encoded.py b/src/targets/python/requests/fixtures/application-form-encoded.py new file mode 100644 index 000000000..e6a53e6d5 --- /dev/null +++ b/src/targets/python/requests/fixtures/application-form-encoded.py @@ -0,0 +1,13 @@ +import requests + +url = "https://httpbin.org/anything" + +payload = { + "foo": "bar", + "hello": "world" +} +headers = {"content-type": "application/x-www-form-urlencoded"} + +response = requests.post(url, data=payload, headers=headers) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/application-json.py b/src/targets/python/requests/fixtures/application-json.py new file mode 100644 index 000000000..e1825be43 --- /dev/null +++ b/src/targets/python/requests/fixtures/application-json.py @@ -0,0 +1,17 @@ +import requests + +url = "https://httpbin.org/anything" + +payload = { + "number": 1, + "string": "f\"oo", + "arr": [1, 2, 3], + "nested": { "a": "b" }, + "arr_mix": [1, "a", { "arr_mix_nested": [] }], + "boolean": False +} +headers = {"content-type": "application/json"} + +response = requests.post(url, json=payload, headers=headers) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/cookies.py b/src/targets/python/requests/fixtures/cookies.py new file mode 100644 index 000000000..76ffd221a --- /dev/null +++ b/src/targets/python/requests/fixtures/cookies.py @@ -0,0 +1,9 @@ +import requests + +url = "https://httpbin.org/cookies" + +headers = {"cookie": "foo=bar; bar=baz"} + +response = requests.get(url, headers=headers) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/custom-method.py b/src/targets/python/requests/fixtures/custom-method.py new file mode 100644 index 000000000..9acbc2b1b --- /dev/null +++ b/src/targets/python/requests/fixtures/custom-method.py @@ -0,0 +1,7 @@ +import requests + +url = "https://httpbin.org/anything" + +response = requests.request("PROPFIND", url) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/full.py b/src/targets/python/requests/fixtures/full.py new file mode 100644 index 000000000..754b0d328 --- /dev/null +++ b/src/targets/python/requests/fixtures/full.py @@ -0,0 +1,14 @@ +import requests + +url = "https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value" + +payload = { "foo": "bar" } +headers = { + "cookie": "foo=bar; bar=baz", + "accept": "application/json", + "content-type": "application/x-www-form-urlencoded" +} + +response = requests.post(url, data=payload, headers=headers) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/headers.py b/src/targets/python/requests/fixtures/headers.py new file mode 100644 index 000000000..e6e7f9bc9 --- /dev/null +++ b/src/targets/python/requests/fixtures/headers.py @@ -0,0 +1,14 @@ +import requests + +url = "https://httpbin.org/headers" + +headers = { + "accept": "application/json", + "x-foo": "Bar", + "x-bar": "Foo", + "quoted-value": "\"quoted\" 'string'" +} + +response = requests.get(url, headers=headers) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/http-insecure.py b/src/targets/python/requests/fixtures/http-insecure.py new file mode 100644 index 000000000..6d5f48ad4 --- /dev/null +++ b/src/targets/python/requests/fixtures/http-insecure.py @@ -0,0 +1,7 @@ +import requests + +url = "http://httpbin.org/anything" + +response = requests.get(url) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/jsonObj-multiline.py b/src/targets/python/requests/fixtures/jsonObj-multiline.py new file mode 100644 index 000000000..18e2537aa --- /dev/null +++ b/src/targets/python/requests/fixtures/jsonObj-multiline.py @@ -0,0 +1,10 @@ +import requests + +url = "https://httpbin.org/anything" + +payload = { "foo": "bar" } +headers = {"content-type": "application/json"} + +response = requests.post(url, json=payload, headers=headers) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/jsonObj-null-value.py b/src/targets/python/requests/fixtures/jsonObj-null-value.py new file mode 100644 index 000000000..9162f431b --- /dev/null +++ b/src/targets/python/requests/fixtures/jsonObj-null-value.py @@ -0,0 +1,10 @@ +import requests + +url = "https://httpbin.org/anything" + +payload = { "foo": None } +headers = {"content-type": "application/json"} + +response = requests.post(url, json=payload, headers=headers) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/multipart-data.py b/src/targets/python/requests/fixtures/multipart-data.py new file mode 100644 index 000000000..b07fbeea2 --- /dev/null +++ b/src/targets/python/requests/fixtures/multipart-data.py @@ -0,0 +1,10 @@ +import requests + +url = "https://httpbin.org/anything" + +files = { "foo": ("src/fixtures/files/hello.txt", open("src/fixtures/files/hello.txt", "rb"), "text/plain") } +payload = { "bar": "Bonjour le monde" } + +response = requests.post(url, data=payload, files=files) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/multipart-file.py b/src/targets/python/requests/fixtures/multipart-file.py new file mode 100644 index 000000000..59911c52c --- /dev/null +++ b/src/targets/python/requests/fixtures/multipart-file.py @@ -0,0 +1,9 @@ +import requests + +url = "https://httpbin.org/anything" + +files = { "foo": ("src/fixtures/files/hello.txt", open("src/fixtures/files/hello.txt", "rb"), "text/plain") } + +response = requests.post(url, files=files) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/multipart-form-data-no-params.py b/src/targets/python/requests/fixtures/multipart-form-data-no-params.py new file mode 100644 index 000000000..5758a83ca --- /dev/null +++ b/src/targets/python/requests/fixtures/multipart-form-data-no-params.py @@ -0,0 +1,9 @@ +import requests + +url = "https://httpbin.org/anything" + +headers = {"Content-Type": "multipart/form-data"} + +response = requests.post(url, headers=headers) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/multipart-form-data.py b/src/targets/python/requests/fixtures/multipart-form-data.py new file mode 100644 index 000000000..4adceef96 --- /dev/null +++ b/src/targets/python/requests/fixtures/multipart-form-data.py @@ -0,0 +1,10 @@ +import requests + +url = "https://httpbin.org/anything" + +payload = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--" +headers = {"Content-Type": "multipart/form-data; boundary=---011000010111000001101001"} + +response = requests.post(url, data=payload, headers=headers) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/nested.py b/src/targets/python/requests/fixtures/nested.py new file mode 100644 index 000000000..0ca3fba54 --- /dev/null +++ b/src/targets/python/requests/fixtures/nested.py @@ -0,0 +1,7 @@ +import requests + +url = "https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value" + +response = requests.get(url) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/postdata-malformed.py b/src/targets/python/requests/fixtures/postdata-malformed.py new file mode 100644 index 000000000..c50809394 --- /dev/null +++ b/src/targets/python/requests/fixtures/postdata-malformed.py @@ -0,0 +1,9 @@ +import requests + +url = "https://httpbin.org/anything" + +headers = {"content-type": "application/json"} + +response = requests.post(url, headers=headers) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/query-encoded.py b/src/targets/python/requests/fixtures/query-encoded.py new file mode 100644 index 000000000..0c9018c7c --- /dev/null +++ b/src/targets/python/requests/fixtures/query-encoded.py @@ -0,0 +1,7 @@ +import requests + +url = "https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00" + +response = requests.get(url) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/query-params.py b/src/targets/python/requests/fixtures/query-params.py new file mode 100644 index 000000000..a8c34eced --- /dev/null +++ b/src/targets/python/requests/fixtures/query-params.py @@ -0,0 +1,7 @@ +import requests + +url = "https://httpbin.org/anything?param=value" + +response = requests.get(url) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/query.py b/src/targets/python/requests/fixtures/query.py new file mode 100644 index 000000000..49fcaceac --- /dev/null +++ b/src/targets/python/requests/fixtures/query.py @@ -0,0 +1,7 @@ +import requests + +url = "https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value" + +response = requests.get(url) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/short.py b/src/targets/python/requests/fixtures/short.py new file mode 100644 index 000000000..36eef9fee --- /dev/null +++ b/src/targets/python/requests/fixtures/short.py @@ -0,0 +1,7 @@ +import requests + +url = "https://httpbin.org/anything" + +response = requests.get(url) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/requests/fixtures/text-plain.py b/src/targets/python/requests/fixtures/text-plain.py new file mode 100644 index 000000000..f921aecfb --- /dev/null +++ b/src/targets/python/requests/fixtures/text-plain.py @@ -0,0 +1,10 @@ +import requests + +url = "https://httpbin.org/anything" + +payload = "Hello World" +headers = {"content-type": "text/plain"} + +response = requests.post(url, data=payload, headers=headers) + +print(response.text) \ No newline at end of file diff --git a/src/targets/python/target.ts b/src/targets/python/target.ts new file mode 100644 index 000000000..2ed415ba1 --- /dev/null +++ b/src/targets/python/target.ts @@ -0,0 +1,15 @@ +import type { Target } from '../index.js'; + +import { requests } from './requests/client.js'; + +export const python: Target = { + info: { + key: 'python', + title: 'Python', + default: 'requests', + cli: 'python3 %s', + }, + clientsById: { + requests, + }, +}; diff --git a/src/targets/r/httr/client.test.ts b/src/targets/r/httr/client.test.ts new file mode 100644 index 000000000..e2b5e5e96 --- /dev/null +++ b/src/targets/r/httr/client.test.ts @@ -0,0 +1,30 @@ +import type { Request } from '../../../index.js'; + +import { runCustomFixtures } from '../../../fixtures/runCustomFixtures.js'; + +runCustomFixtures({ + targetId: 'r', + clientId: 'httr', + tests: [ + { + it: "should properly concatenate query strings that aren't nested", + input: { + method: 'GET', + url: 'https://httpbin.org/anything', + httpVersion: 'HTTP/1.1', + queryString: [ + { + name: 'perPage', + value: '100', + }, + { + name: 'page', + value: '1', + }, + ], + } as Request, + options: {}, + expected: 'query-two-params.r', + }, + ], +}); diff --git a/src/targets/r/httr/client.ts b/src/targets/r/httr/client.ts new file mode 100644 index 000000000..9a7a422af --- /dev/null +++ b/src/targets/r/httr/client.ts @@ -0,0 +1,143 @@ +/** + * @description + * HTTP code snippet generator for R using httr + * + * @author + * @gabrielakoreeda + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { escapeForDoubleQuotes, escapeForSingleQuotes } from '../../../helpers/escape.js'; +import { getHeader } from '../../../helpers/headers.js'; + +export const httr: Client = { + info: { + key: 'httr', + title: 'httr', + link: 'https://cran.r-project.org/web/packages/httr/vignettes/quickstart.html', + description: 'httr: Tools for Working with URLs and HTTP', + extname: '.r', + }, + convert: ({ url, queryObj, queryString, postData, allHeaders, method }) => { + // Start snippet + const { push, blank, join } = new CodeBuilder(); + + // Import httr + push('library(httr)'); + blank(); + + // Set URL + push(`url <- "${url}"`); + blank(); + + // Construct query string + const qs = queryObj; + delete queryObj.key; + + const queryCount = Object.keys(qs).length; + if (queryString.length === 1) { + push(`queryString <- list(${Object.keys(qs)} = "${Object.values(qs).toString()}")`); + blank(); + } else if (queryString.length > 1) { + push('queryString <- list('); + + Object.keys(qs).forEach((query, i) => { + if (i !== queryCount - 1) { + push(` ${query} = "${qs[query].toString()}",`); + } else { + push(` ${query} = "${qs[query].toString()}"`); + } + }); + + push(')'); + blank(); + } + + // Construct payload + const payload = JSON.stringify(postData.text); + + if (payload) { + push(`payload <- ${payload}`); + blank(); + } + + // Define encode + if (postData.text || postData.jsonObj || postData.params) { + switch (postData.mimeType) { + case 'application/x-www-form-urlencoded': + push('encode <- "form"'); + blank(); + break; + + case 'application/json': + push('encode <- "json"'); + blank(); + break; + + case 'multipart/form-data': + push('encode <- "multipart"'); + blank(); + break; + + default: + push('encode <- "raw"'); + blank(); + break; + } + } + + // Construct headers + const cookieHeader = getHeader(allHeaders, 'cookie'); + const acceptHeader = getHeader(allHeaders, 'accept'); + + const setCookies = cookieHeader + ? `set_cookies(\`${String(cookieHeader).replace(/;/g, '", `').replace(/` /g, '`').replace(/[=]/g, '` = "')}")` + : undefined; + + const setAccept = acceptHeader ? `accept("${escapeForDoubleQuotes(acceptHeader)}")` : undefined; + + const setContentType = `content_type("${escapeForDoubleQuotes(postData.mimeType)}")`; + + const otherHeaders = Object.entries(allHeaders) + // These headers are all handled separately: + .filter(([key]) => !['cookie', 'accept', 'content-type'].includes(key.toLowerCase())) + .map(([key, value]) => `'${key}' = '${escapeForSingleQuotes(value)}'`) + .join(', '); + + const setHeaders = otherHeaders ? `add_headers(${otherHeaders})` : undefined; + + // Construct request + let request = `response <- VERB("${method}", url`; + + if (payload) { + request += ', body = payload'; + } + + if (queryString.length) { + request += ', query = queryString'; + } + + const headerAdditions = [setHeaders, setContentType, setAccept, setCookies].filter(x => !!x).join(', '); + + if (headerAdditions) { + request += `, ${headerAdditions}`; + } + + if (postData.text || postData.jsonObj || postData.params) { + request += ', encode = encode'; + } + + request += ')'; + + push(request); + + blank(); + // Print response + push('content(response, "text")'); + + return join(); + }, +}; diff --git a/src/targets/r/httr/fixtures/application-form-encoded.r b/src/targets/r/httr/fixtures/application-form-encoded.r new file mode 100644 index 000000000..a9d20442c --- /dev/null +++ b/src/targets/r/httr/fixtures/application-form-encoded.r @@ -0,0 +1,11 @@ +library(httr) + +url <- "https://httpbin.org/anything" + +payload <- "foo=bar&hello=world" + +encode <- "form" + +response <- VERB("POST", url, body = payload, content_type("application/x-www-form-urlencoded"), encode = encode) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/application-json.r b/src/targets/r/httr/fixtures/application-json.r new file mode 100644 index 000000000..ae00f416c --- /dev/null +++ b/src/targets/r/httr/fixtures/application-json.r @@ -0,0 +1,11 @@ +library(httr) + +url <- "https://httpbin.org/anything" + +payload <- "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":[]}],\"boolean\":false}" + +encode <- "json" + +response <- VERB("POST", url, body = payload, content_type("application/json"), encode = encode) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/cookies.r b/src/targets/r/httr/fixtures/cookies.r new file mode 100644 index 000000000..535007a28 --- /dev/null +++ b/src/targets/r/httr/fixtures/cookies.r @@ -0,0 +1,7 @@ +library(httr) + +url <- "https://httpbin.org/cookies" + +response <- VERB("GET", url, content_type("application/octet-stream"), set_cookies(`foo` = "bar", `bar` = "baz")) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/custom-method.r b/src/targets/r/httr/fixtures/custom-method.r new file mode 100644 index 000000000..46a33eefe --- /dev/null +++ b/src/targets/r/httr/fixtures/custom-method.r @@ -0,0 +1,7 @@ +library(httr) + +url <- "https://httpbin.org/anything" + +response <- VERB("PROPFIND", url, content_type("application/octet-stream")) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/full.r b/src/targets/r/httr/fixtures/full.r new file mode 100644 index 000000000..9c5de5745 --- /dev/null +++ b/src/targets/r/httr/fixtures/full.r @@ -0,0 +1,16 @@ +library(httr) + +url <- "https://httpbin.org/anything" + +queryString <- list( + foo = "bar,baz", + baz = "abc" +) + +payload <- "foo=bar" + +encode <- "form" + +response <- VERB("POST", url, body = payload, query = queryString, content_type("application/x-www-form-urlencoded"), accept("application/json"), set_cookies(`foo` = "bar", `bar` = "baz"), encode = encode) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/headers.r b/src/targets/r/httr/fixtures/headers.r new file mode 100644 index 000000000..1f78ffbd5 --- /dev/null +++ b/src/targets/r/httr/fixtures/headers.r @@ -0,0 +1,7 @@ +library(httr) + +url <- "https://httpbin.org/headers" + +response <- VERB("GET", url, add_headers('x-foo' = 'Bar', 'x-bar' = 'Foo', 'quoted-value' = '"quoted" \'string\''), content_type("application/octet-stream"), accept("application/json")) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/http-insecure.r b/src/targets/r/httr/fixtures/http-insecure.r new file mode 100644 index 000000000..a12bc4bc9 --- /dev/null +++ b/src/targets/r/httr/fixtures/http-insecure.r @@ -0,0 +1,7 @@ +library(httr) + +url <- "http://httpbin.org/anything" + +response <- VERB("GET", url, content_type("application/octet-stream")) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/jsonObj-multiline.r b/src/targets/r/httr/fixtures/jsonObj-multiline.r new file mode 100644 index 000000000..0fd84d43e --- /dev/null +++ b/src/targets/r/httr/fixtures/jsonObj-multiline.r @@ -0,0 +1,11 @@ +library(httr) + +url <- "https://httpbin.org/anything" + +payload <- "{\n \"foo\": \"bar\"\n}" + +encode <- "json" + +response <- VERB("POST", url, body = payload, content_type("application/json"), encode = encode) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/jsonObj-null-value.r b/src/targets/r/httr/fixtures/jsonObj-null-value.r new file mode 100644 index 000000000..962f02531 --- /dev/null +++ b/src/targets/r/httr/fixtures/jsonObj-null-value.r @@ -0,0 +1,11 @@ +library(httr) + +url <- "https://httpbin.org/anything" + +payload <- "{\"foo\":null}" + +encode <- "json" + +response <- VERB("POST", url, body = payload, content_type("application/json"), encode = encode) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/multipart-data.r b/src/targets/r/httr/fixtures/multipart-data.r new file mode 100644 index 000000000..bdc35201e --- /dev/null +++ b/src/targets/r/httr/fixtures/multipart-data.r @@ -0,0 +1,11 @@ +library(httr) + +url <- "https://httpbin.org/anything" + +payload <- "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"bar\"\r\n\r\nBonjour le monde\r\n-----011000010111000001101001--" + +encode <- "multipart" + +response <- VERB("POST", url, body = payload, content_type("multipart/form-data"), encode = encode) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/multipart-file.r b/src/targets/r/httr/fixtures/multipart-file.r new file mode 100644 index 000000000..8c0f62662 --- /dev/null +++ b/src/targets/r/httr/fixtures/multipart-file.r @@ -0,0 +1,11 @@ +library(httr) + +url <- "https://httpbin.org/anything" + +payload <- "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--" + +encode <- "multipart" + +response <- VERB("POST", url, body = payload, content_type("multipart/form-data"), encode = encode) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/multipart-form-data-no-params.r b/src/targets/r/httr/fixtures/multipart-form-data-no-params.r new file mode 100644 index 000000000..d67a893e2 --- /dev/null +++ b/src/targets/r/httr/fixtures/multipart-form-data-no-params.r @@ -0,0 +1,9 @@ +library(httr) + +url <- "https://httpbin.org/anything" + +payload <- "" + +response <- VERB("POST", url, body = payload, content_type("multipart/form-data")) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/multipart-form-data.r b/src/targets/r/httr/fixtures/multipart-form-data.r new file mode 100644 index 000000000..05f080f20 --- /dev/null +++ b/src/targets/r/httr/fixtures/multipart-form-data.r @@ -0,0 +1,11 @@ +library(httr) + +url <- "https://httpbin.org/anything" + +payload <- "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--" + +encode <- "multipart" + +response <- VERB("POST", url, body = payload, content_type("multipart/form-data"), encode = encode) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/nested.r b/src/targets/r/httr/fixtures/nested.r new file mode 100644 index 000000000..d85114940 --- /dev/null +++ b/src/targets/r/httr/fixtures/nested.r @@ -0,0 +1,12 @@ +library(httr) + +url <- "https://httpbin.org/anything" + +queryString <- list( + foo[bar] = "baz,zap", + fiz = "buz" +) + +response <- VERB("GET", url, query = queryString, content_type("application/octet-stream")) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/postdata-malformed.r b/src/targets/r/httr/fixtures/postdata-malformed.r new file mode 100644 index 000000000..f3843ac86 --- /dev/null +++ b/src/targets/r/httr/fixtures/postdata-malformed.r @@ -0,0 +1,7 @@ +library(httr) + +url <- "https://httpbin.org/anything" + +response <- VERB("POST", url, content_type("application/octet-stream")) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/query-encoded.r b/src/targets/r/httr/fixtures/query-encoded.r new file mode 100644 index 000000000..acea9ec0d --- /dev/null +++ b/src/targets/r/httr/fixtures/query-encoded.r @@ -0,0 +1,12 @@ +library(httr) + +url <- "https://httpbin.org/anything" + +queryString <- list( + startTime = "2019-06-13T19%3A08%3A25.455Z", + endTime = "2015-09-15T14%3A00%3A12-04%3A00" +) + +response <- VERB("GET", url, query = queryString, content_type("application/octet-stream")) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/query-two-params.r b/src/targets/r/httr/fixtures/query-two-params.r new file mode 100644 index 000000000..a5e3f9d99 --- /dev/null +++ b/src/targets/r/httr/fixtures/query-two-params.r @@ -0,0 +1,12 @@ +library(httr) + +url <- "https://httpbin.org/anything" + +queryString <- list( + perPage = "100", + page = "1" +) + +response <- VERB("GET", url, query = queryString, content_type("application/octet-stream")) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/query.r b/src/targets/r/httr/fixtures/query.r new file mode 100644 index 000000000..2102318f0 --- /dev/null +++ b/src/targets/r/httr/fixtures/query.r @@ -0,0 +1,12 @@ +library(httr) + +url <- "https://httpbin.org/anything" + +queryString <- list( + foo = "bar,baz", + baz = "abc" +) + +response <- VERB("GET", url, query = queryString, content_type("application/octet-stream")) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/short.r b/src/targets/r/httr/fixtures/short.r new file mode 100644 index 000000000..084032ccd --- /dev/null +++ b/src/targets/r/httr/fixtures/short.r @@ -0,0 +1,7 @@ +library(httr) + +url <- "https://httpbin.org/anything" + +response <- VERB("GET", url, content_type("application/octet-stream")) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/httr/fixtures/text-plain.r b/src/targets/r/httr/fixtures/text-plain.r new file mode 100644 index 000000000..476416fb1 --- /dev/null +++ b/src/targets/r/httr/fixtures/text-plain.r @@ -0,0 +1,11 @@ +library(httr) + +url <- "https://httpbin.org/anything" + +payload <- "Hello World" + +encode <- "raw" + +response <- VERB("POST", url, body = payload, content_type("text/plain"), encode = encode) + +content(response, "text") \ No newline at end of file diff --git a/src/targets/r/target.ts b/src/targets/r/target.ts new file mode 100644 index 000000000..dd4f9ad64 --- /dev/null +++ b/src/targets/r/target.ts @@ -0,0 +1,14 @@ +import type { Target } from '../index.js'; + +import { httr } from './httr/client.js'; + +export const r: Target = { + info: { + key: 'r', + title: 'R', + default: 'httr', + }, + clientsById: { + httr, + }, +}; diff --git a/src/targets/ruby/index.js b/src/targets/ruby/index.js deleted file mode 100644 index 1118a1b80..000000000 --- a/src/targets/ruby/index.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict' - -module.exports = { - info: { - key: 'ruby', - title: 'Ruby', - extname: '.rb', - default: 'native' - }, - - native: require('./native') -} diff --git a/src/targets/ruby/native.js b/src/targets/ruby/native.js deleted file mode 100644 index b1254b744..000000000 --- a/src/targets/ruby/native.js +++ /dev/null @@ -1,60 +0,0 @@ -'use strict' - -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var code = new CodeBuilder() - - code.push('require \'uri\'') - .push('require \'net/http\'') - .blank() - - // To support custom methods we check for the supported methods - // and if doesn't exist then we build a custom class for it - var method = source.method.toUpperCase() - var methods = ['GET', 'POST', 'HEAD', 'DELETE', 'PATCH', 'PUT', 'OPTIONS', 'COPY', 'LOCK', 'UNLOCK', 'MOVE', 'TRACE'] - var capMethod = method.charAt(0) + method.substring(1).toLowerCase() - if (methods.indexOf(method) < 0) { - code.push('class Net::HTTP::%s < Net::HTTPRequest', capMethod) - .push(' METHOD = \'%s\'', method.toUpperCase()) - .push(' REQUEST_HAS_BODY = \'%s\'', source.postData.text ? 'true' : 'false') - .push(' RESPONSE_HAS_BODY = true') - .push('end') - .blank() - } - - code.push('url = URI("%s")', source.fullUrl) - .blank() - .push('http = Net::HTTP.new(url.host, url.port)') - - if (source.uriObj.protocol === 'https:') { - code.push('http.use_ssl = true') - } - - code.blank() - .push('request = Net::HTTP::%s.new(url)', capMethod) - - var headers = Object.keys(source.allHeaders) - if (headers.length) { - headers.forEach(function (key) { - code.push('request["%s"] = \'%s\'', key, source.allHeaders[key]) - }) - } - - if (source.postData.text) { - code.push('request.body = %s', JSON.stringify(source.postData.text)) - } - - code.blank() - .push('response = http.request(request)') - .push('puts response.read_body') - - return code.join() -} - -module.exports.info = { - key: 'native', - title: 'net::http', - link: 'http://ruby-doc.org/stdlib-2.2.1/libdoc/net/http/rdoc/Net/HTTP.html', - description: 'Ruby HTTP client' -} diff --git a/src/targets/ruby/native/client.ts b/src/targets/ruby/native/client.ts new file mode 100644 index 000000000..e9c268213 --- /dev/null +++ b/src/targets/ruby/native/client.ts @@ -0,0 +1,76 @@ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { escapeForSingleQuotes } from '../../../helpers/escape.js'; + +export const native: Client = { + info: { + key: 'native', + title: 'net::http', + link: 'http://ruby-doc.org/stdlib-2.2.1/libdoc/net/http/rdoc/Net/HTTP.html', + description: 'Ruby HTTP client', + extname: '.rb', + }, + convert: ({ uriObj, method: rawMethod, fullUrl, postData, allHeaders }) => { + const { push, blank, join } = new CodeBuilder(); + + push("require 'uri'"); + push("require 'net/http'"); + blank(); + + // To support custom methods we check for the supported methods + // and if doesn't exist then we build a custom class for it + const method = rawMethod.toUpperCase(); + const methods = [ + 'GET', + 'POST', + 'HEAD', + 'DELETE', + 'PATCH', + 'PUT', + 'OPTIONS', + 'COPY', + 'LOCK', + 'UNLOCK', + 'MOVE', + 'TRACE', + ]; + const capMethod = method.charAt(0) + method.substring(1).toLowerCase(); + if (!methods.includes(method)) { + push(`class Net::HTTP::${capMethod} < Net::HTTPRequest`); + push(` METHOD = '${method.toUpperCase()}'`); + push(` REQUEST_HAS_BODY = '${postData.text ? 'true' : 'false'}'`); + push(' RESPONSE_HAS_BODY = true'); + push('end'); + blank(); + } + + push(`url = URI("${fullUrl}")`); + blank(); + push('http = Net::HTTP.new(url.host, url.port)'); + + if (uriObj.protocol === 'https:') { + push('http.use_ssl = true'); + } + + blank(); + push(`request = Net::HTTP::${capMethod}.new(url)`); + + const headers = Object.keys(allHeaders); + if (headers.length) { + headers.forEach(key => { + push(`request["${key}"] = '${escapeForSingleQuotes(allHeaders[key])}'`); + }); + } + + if (postData.text) { + push(`request.body = ${JSON.stringify(postData.text)}`); + } + + blank(); + push('response = http.request(request)'); + push('puts response.read_body'); + + return join(); + }, +}; diff --git a/src/targets/ruby/native/fixtures/application-form-encoded.rb b/src/targets/ruby/native/fixtures/application-form-encoded.rb new file mode 100644 index 000000000..4f1489c77 --- /dev/null +++ b/src/targets/ruby/native/fixtures/application-form-encoded.rb @@ -0,0 +1,14 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/anything") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true + +request = Net::HTTP::Post.new(url) +request["content-type"] = 'application/x-www-form-urlencoded' +request.body = "foo=bar&hello=world" + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/application-json.rb b/src/targets/ruby/native/fixtures/application-json.rb new file mode 100644 index 000000000..cc7380dee --- /dev/null +++ b/src/targets/ruby/native/fixtures/application-json.rb @@ -0,0 +1,14 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/anything") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true + +request = Net::HTTP::Post.new(url) +request["content-type"] = 'application/json' +request.body = "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":[]}],\"boolean\":false}" + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/cookies.rb b/src/targets/ruby/native/fixtures/cookies.rb new file mode 100644 index 000000000..2ba59a8b3 --- /dev/null +++ b/src/targets/ruby/native/fixtures/cookies.rb @@ -0,0 +1,13 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/cookies") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true + +request = Net::HTTP::Get.new(url) +request["cookie"] = 'foo=bar; bar=baz' + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/test/fixtures/output/ruby/native/custom-method.rb b/src/targets/ruby/native/fixtures/custom-method.rb similarity index 76% rename from test/fixtures/output/ruby/native/custom-method.rb rename to src/targets/ruby/native/fixtures/custom-method.rb index d3d4566e7..b791ed4f7 100644 --- a/test/fixtures/output/ruby/native/custom-method.rb +++ b/src/targets/ruby/native/fixtures/custom-method.rb @@ -7,11 +7,12 @@ class Net::HTTP::Propfind < Net::HTTPRequest RESPONSE_HAS_BODY = true end -url = URI("http://mockbin.com/har") +url = URI("https://httpbin.org/anything") http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true request = Net::HTTP::Propfind.new(url) response = http.request(request) -puts response.read_body +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/full.rb b/src/targets/ruby/native/fixtures/full.rb new file mode 100644 index 000000000..13bb1f0ab --- /dev/null +++ b/src/targets/ruby/native/fixtures/full.rb @@ -0,0 +1,16 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true + +request = Net::HTTP::Post.new(url) +request["cookie"] = 'foo=bar; bar=baz' +request["accept"] = 'application/json' +request["content-type"] = 'application/x-www-form-urlencoded' +request.body = "foo=bar" + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/headers.rb b/src/targets/ruby/native/fixtures/headers.rb new file mode 100644 index 000000000..c28276813 --- /dev/null +++ b/src/targets/ruby/native/fixtures/headers.rb @@ -0,0 +1,16 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/headers") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true + +request = Net::HTTP::Get.new(url) +request["accept"] = 'application/json' +request["x-foo"] = 'Bar' +request["x-bar"] = 'Foo' +request["quoted-value"] = '"quoted" \'string\'' + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/http-insecure.rb b/src/targets/ruby/native/fixtures/http-insecure.rb new file mode 100644 index 000000000..54ce4e7d3 --- /dev/null +++ b/src/targets/ruby/native/fixtures/http-insecure.rb @@ -0,0 +1,11 @@ +require 'uri' +require 'net/http' + +url = URI("http://httpbin.org/anything") + +http = Net::HTTP.new(url.host, url.port) + +request = Net::HTTP::Get.new(url) + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/insecure-skip-verify.rb b/src/targets/ruby/native/fixtures/insecure-skip-verify.rb new file mode 100644 index 000000000..14ee76567 --- /dev/null +++ b/src/targets/ruby/native/fixtures/insecure-skip-verify.rb @@ -0,0 +1,13 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/anything") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true +http.verify_mode = OpenSSL::SSL::VERIFY_NONE + +request = Net::HTTP::Get.new(url) + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/jsonObj-multiline.rb b/src/targets/ruby/native/fixtures/jsonObj-multiline.rb new file mode 100644 index 000000000..427de9a2b --- /dev/null +++ b/src/targets/ruby/native/fixtures/jsonObj-multiline.rb @@ -0,0 +1,14 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/anything") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true + +request = Net::HTTP::Post.new(url) +request["content-type"] = 'application/json' +request.body = "{\n \"foo\": \"bar\"\n}" + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/jsonObj-null-value.rb b/src/targets/ruby/native/fixtures/jsonObj-null-value.rb new file mode 100644 index 000000000..00198d87b --- /dev/null +++ b/src/targets/ruby/native/fixtures/jsonObj-null-value.rb @@ -0,0 +1,14 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/anything") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true + +request = Net::HTTP::Post.new(url) +request["content-type"] = 'application/json' +request.body = "{\"foo\":null}" + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/multipart-data.rb b/src/targets/ruby/native/fixtures/multipart-data.rb new file mode 100644 index 000000000..1af607d20 --- /dev/null +++ b/src/targets/ruby/native/fixtures/multipart-data.rb @@ -0,0 +1,14 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/anything") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true + +request = Net::HTTP::Post.new(url) +request["content-type"] = 'multipart/form-data; boundary=---011000010111000001101001' +request.body = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"bar\"\r\n\r\nBonjour le monde\r\n-----011000010111000001101001--" + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/multipart-file.rb b/src/targets/ruby/native/fixtures/multipart-file.rb new file mode 100644 index 000000000..1ba5250a9 --- /dev/null +++ b/src/targets/ruby/native/fixtures/multipart-file.rb @@ -0,0 +1,14 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/anything") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true + +request = Net::HTTP::Post.new(url) +request["content-type"] = 'multipart/form-data; boundary=---011000010111000001101001' +request.body = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"src/fixtures/files/hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--" + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/multipart-form-data-no-params.rb b/src/targets/ruby/native/fixtures/multipart-form-data-no-params.rb new file mode 100644 index 000000000..d6038d6ea --- /dev/null +++ b/src/targets/ruby/native/fixtures/multipart-form-data-no-params.rb @@ -0,0 +1,13 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/anything") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true + +request = Net::HTTP::Post.new(url) +request["Content-Type"] = 'multipart/form-data' + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/multipart-form-data.rb b/src/targets/ruby/native/fixtures/multipart-form-data.rb new file mode 100644 index 000000000..1ce7cd7ce --- /dev/null +++ b/src/targets/ruby/native/fixtures/multipart-form-data.rb @@ -0,0 +1,14 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/anything") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true + +request = Net::HTTP::Post.new(url) +request["Content-Type"] = 'multipart/form-data; boundary=---011000010111000001101001' +request.body = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--" + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/nested.rb b/src/targets/ruby/native/fixtures/nested.rb new file mode 100644 index 000000000..408ffe5c9 --- /dev/null +++ b/src/targets/ruby/native/fixtures/nested.rb @@ -0,0 +1,12 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true + +request = Net::HTTP::Get.new(url) + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/postdata-malformed.rb b/src/targets/ruby/native/fixtures/postdata-malformed.rb new file mode 100644 index 000000000..507b4b789 --- /dev/null +++ b/src/targets/ruby/native/fixtures/postdata-malformed.rb @@ -0,0 +1,13 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/anything") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true + +request = Net::HTTP::Post.new(url) +request["content-type"] = 'application/json' + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/query-encoded.rb b/src/targets/ruby/native/fixtures/query-encoded.rb new file mode 100644 index 000000000..3d8231f74 --- /dev/null +++ b/src/targets/ruby/native/fixtures/query-encoded.rb @@ -0,0 +1,12 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true + +request = Net::HTTP::Get.new(url) + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/query.rb b/src/targets/ruby/native/fixtures/query.rb new file mode 100644 index 000000000..e75117e32 --- /dev/null +++ b/src/targets/ruby/native/fixtures/query.rb @@ -0,0 +1,12 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true + +request = Net::HTTP::Get.new(url) + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/short.rb b/src/targets/ruby/native/fixtures/short.rb new file mode 100644 index 000000000..3732cb674 --- /dev/null +++ b/src/targets/ruby/native/fixtures/short.rb @@ -0,0 +1,12 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/anything") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true + +request = Net::HTTP::Get.new(url) + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/native/fixtures/text-plain.rb b/src/targets/ruby/native/fixtures/text-plain.rb new file mode 100644 index 000000000..65bd8ae13 --- /dev/null +++ b/src/targets/ruby/native/fixtures/text-plain.rb @@ -0,0 +1,14 @@ +require 'uri' +require 'net/http' + +url = URI("https://httpbin.org/anything") + +http = Net::HTTP.new(url.host, url.port) +http.use_ssl = true + +request = Net::HTTP::Post.new(url) +request["content-type"] = 'text/plain' +request.body = "Hello World" + +response = http.request(request) +puts response.read_body \ No newline at end of file diff --git a/src/targets/ruby/target.ts b/src/targets/ruby/target.ts new file mode 100644 index 000000000..132efbb0a --- /dev/null +++ b/src/targets/ruby/target.ts @@ -0,0 +1,14 @@ +import type { Target } from '../index.js'; + +import { native } from './native/client.js'; + +export const ruby: Target = { + info: { + key: 'ruby', + title: 'Ruby', + default: 'native', + }, + clientsById: { + native, + }, +}; diff --git a/src/targets/shell/curl.js b/src/targets/shell/curl.js deleted file mode 100644 index ebd68bb02..000000000 --- a/src/targets/shell/curl.js +++ /dev/null @@ -1,91 +0,0 @@ -/** - * @description - * HTTP code snippet generator for the Shell using cURL. - * - * @author - * @AhmadNassri - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var util = require('util') -var helpers = require('../../helpers/shell') -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ', - short: false, - binary: false - }, options) - - var code = new CodeBuilder(opts.indent, opts.indent !== false ? ' \\\n' + opts.indent : ' ') - - code.push('curl %s %s', opts.short ? '-X' : '--request', source.method) - .push(util.format('%s%s', opts.short ? '' : '--url ', helpers.quote(source.fullUrl))) - - if (source.httpVersion === 'HTTP/1.0') { - code.push(opts.short ? '-0' : '--http1.0') - } - - // construct headers - Object.keys(source.headersObj).sort().forEach(function (key) { - var header = util.format('%s: %s', key, source.headersObj[key]) - code.push('%s %s', opts.short ? '-H' : '--header', helpers.quote(header)) - }) - - if (source.allHeaders.cookie) { - code.push('%s %s', opts.short ? '-b' : '--cookie', helpers.quote(source.allHeaders.cookie)) - } - - // construct post params - switch (source.postData.mimeType) { - case 'multipart/form-data': - source.postData.params.map(function (param) { - var post = util.format('%s=%s', param.name, param.value) - - if (param.fileName && !param.value) { - post = util.format('%s=@%s', param.name, param.fileName) - } - - code.push('%s %s', opts.short ? '-F' : '--form', helpers.quote(post)) - }) - break - - case 'application/x-www-form-urlencoded': - if (source.postData.params) { - source.postData.params.map(function (param) { - code.push( - '%s %s', opts.binary ? '--data-binary' : (opts.short ? '-d' : '--data'), - helpers.quote(util.format('%s=%s', param.name, param.value)) - ) - }) - } else { - code.push( - '%s %s', opts.binary ? '--data-binary' : (opts.short ? '-d' : '--data'), - helpers.escape(helpers.quote(source.postData.text)) - ) - } - break - - default: - // raw request body - if (source.postData.text) { - code.push( - '%s %s', opts.binary ? '--data-binary' : (opts.short ? '-d' : '--data'), - helpers.escape(helpers.quote(source.postData.text)) - ) - } - } - - return code.join() -} - -module.exports.info = { - key: 'curl', - title: 'cURL', - link: 'http://curl.haxx.se/', - description: 'cURL is a command line tool and library for transferring data with URL syntax' -} diff --git a/src/targets/shell/curl/client.test.ts b/src/targets/shell/curl/client.test.ts new file mode 100644 index 000000000..d0cf3b742 --- /dev/null +++ b/src/targets/shell/curl/client.test.ts @@ -0,0 +1,203 @@ +import type { Request } from '../../../index.js'; + +import applicationFormEncoded from '../../../fixtures/requests/application-form-encoded.cjs'; +import full from '../../../fixtures/requests/full.cjs'; +import nested from '../../../fixtures/requests/nested.cjs'; +import { runCustomFixtures } from '../../../fixtures/runCustomFixtures.js'; + +runCustomFixtures({ + targetId: 'shell', + clientId: 'curl', + tests: [ + { + it: 'should use short options', + input: full.log.entries[0].request as Request, + options: { short: true, indent: false }, + expected: 'short-options.sh', + }, + { + it: 'should use binary option', + input: full.log.entries[0].request as Request, + options: { + short: true, + indent: false, + binary: true, + }, + expected: 'binary-option.sh', + }, + { + it: 'should use short globoff option', + input: nested.log.entries[0].request as Request, + options: { + short: true, + indent: false, + globOff: true, + }, + expected: 'globoff-option.sh', + }, + { + it: 'should use long globoff option', + input: nested.log.entries[0].request as Request, + options: { + indent: false, + globOff: true, + }, + expected: 'long-globoff-option.sh', + }, + { + it: 'should not de-glob when globoff is false', + input: nested.log.entries[0].request as Request, + options: { + indent: false, + globOff: false, + }, + expected: 'dont-deglob.sh', + }, + { + it: 'should use --http1.0 for HTTP/1.0', + input: { + method: 'GET', + url: 'https://httpbin.org/anything', + httpVersion: 'HTTP/1.0', + } as Request, + options: { + indent: false, + }, + expected: 'http10.sh', + }, + { + it: 'should use custom indentation', + input: full.log.entries[0].request as Request, + options: { + indent: '@', + }, + expected: 'custom-indentation.sh', + }, + { + it: 'should url encode the params key', + input: { + ...applicationFormEncoded.log.entries[0].request, + postData: { + mimeType: 'application/x-www-form-urlencoded', + params: [ + { name: 'user name', value: 'John Doe' }, + { name: '$filter', value: 'by id' }, + ], + }, + } as Request, + options: {}, + expected: 'urlencode.sh', + }, + { + it: 'should use --data-urlencode for form-urlencoded params with special characters in values', + input: { + ...applicationFormEncoded.log.entries[0].request, + postData: { + mimeType: 'application/x-www-form-urlencoded', + params: [ + { name: 'query', value: 'hello world' }, + { name: 'filter', value: 'status=active&type=user' }, + ], + }, + } as Request, + options: {}, + expected: 'urlencode-values.sh', + }, + { + it: 'should send JSON-encoded data with single quotes within a HEREDOC', + input: { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: [ + { + name: 'content-type', + value: 'application/json', + }, + ], + postData: { + mimeType: 'application/json', + text: '{"number":1,"string":"f\'oo"}', + }, + } as Request, + options: {}, + expected: 'heredoc-json-encoded-data.sh', + }, + { + it: 'should keep JSON payloads that are smaller than 20 characters on one line', + input: { + method: 'POST', + url: 'https://httpbin.org/anything', + headers: [ + { + name: 'content-type', + value: 'application/json', + }, + ], + postData: { + text: '{"foo": "bar"}', + mimeType: 'application/json', + }, + } as Request, + options: {}, + expected: 'json-payloads-smaller-than-20-characters.sh', + }, + + // `harIsAlreadyEncoded` option + { + it: 'should not double-encode already encoded data with `harIsAlreadyEncoded`', + input: { + cookies: [{ name: 'user', value: encodeURIComponent('abc^') }], + queryString: [ + { name: 'stringPound', value: encodeURIComponent('somethign¬hing=true') }, + { name: 'stringHash', value: encodeURIComponent('hash#data') }, + { name: 'stringArray', value: encodeURIComponent('where[4]=10') }, + { name: 'stringWeird', value: encodeURIComponent('properties["$email"] == "testing"') }, + { name: 'array', value: encodeURIComponent('something¬hing=true') }, + { name: 'array', value: encodeURIComponent('nothing&something=false') }, + { name: 'array', value: encodeURIComponent('another item') }, + ], + method: 'POST', + url: 'https://httpbin.org/anything', + httpVersion: 'HTTP/1.1', + } as Request, + options: { + harIsAlreadyEncoded: true, + }, + expected: 'harIsAlreadyEncoded-option-already-encoded.sh', + }, + { + it: 'should escape brackets in query strings when `harIsAlreadyEncoded` is `true` and `escapeBrackets` is `true`', + input: { + method: 'GET', + url: 'https://httpbin.org/anything', + httpVersion: 'HTTP/1.1', + queryString: [ + { + name: 'where', + value: '[["$attributed_flow","=","FLOW_ID"]]', + }, + ], + } as Request, + options: { + harIsAlreadyEncoded: true, + // escapeBrackets: true, // @todo this need to be enabled? + }, + expected: 'harIsAlreadyEncoded=option-escape-brackets.sh', + }, + { + it: 'should use --compressed for requests that accept encodings', + input: { + method: 'GET', + url: 'https://httpbin.org/anything', + headers: [ + { + name: 'accept-encoding', + value: 'deflate, gzip, br', + }, + ], + } as Request, + options: {}, + expected: 'accept-encoding-compressed.sh', + }, + ], +}); diff --git a/src/targets/shell/curl/client.ts b/src/targets/shell/curl/client.ts new file mode 100644 index 000000000..2dee8cfcd --- /dev/null +++ b/src/targets/shell/curl/client.ts @@ -0,0 +1,202 @@ +/** + * @description + * + * HTTP code snippet generator for the Shell using cURL. + * + * @author + * @AhmadNassri + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { getHeader, getHeaderName, isMimeTypeJSON } from '../../../helpers/headers.js'; +import { quote } from '../../../helpers/shell.js'; + +export interface CurlOptions { + binary?: boolean; + globOff?: boolean; + indent?: string | false; + prettifyJson?: boolean; + short?: boolean; +} + +/** + * This is a const record with keys that correspond to the long names and values that correspond to the short names for cURL arguments. + */ +const params = { + 'http1.0': '0', + 'url ': '', + cookie: 'b', + data: 'd', + form: 'F', + globoff: 'g', + header: 'H', + insecure: 'k', + request: 'X', +} as const; + +const getArg = (short: boolean) => (longName: keyof typeof params) => { + if (short) { + const shortName = params[longName]; + if (!shortName) { + return ''; + } + return `-${shortName}`; + } + return `--${longName}`; +}; + +export const curl: Client = { + info: { + key: 'curl', + title: 'cURL', + link: 'http://curl.haxx.se/', + description: 'cURL is a command line tool and library for transferring data with URL syntax', + extname: '.sh', + }, + convert: ({ fullUrl, method, httpVersion, headersObj, allHeaders, postData }, options = {}) => { + const { indent = ' ', short = false, binary = false, globOff = false } = options; + + // In the interest of having nicer looking snippets JSON should be indented separately from the + // main command argument indentation. + const indentJSON = ' '; + + const { push, join } = new CodeBuilder({ + ...(typeof indent === 'string' ? { indent } : {}), + join: indent !== false ? ` \\\n${indent}` : ' ', + }); + + const arg = getArg(short); + + let formattedUrl = quote(fullUrl); + + push(`curl ${arg('request')} ${method}`); + if (globOff) { + formattedUrl = unescape(formattedUrl); + push(arg('globoff')); + } + push(`${arg('url ')}${formattedUrl}`); + + if (httpVersion === 'HTTP/1.0') { + push(arg('http1.0')); + } + + if (getHeader(allHeaders, 'accept-encoding')) { + // note: there is no shorthand for this cURL option + push('--compressed'); + } + + // if multipart form data, we want to remove the boundary + if (postData.mimeType === 'multipart/form-data') { + const contentTypeHeaderName = getHeaderName(headersObj, 'content-type'); + if (contentTypeHeaderName) { + const contentTypeHeader = headersObj[contentTypeHeaderName]; + if (contentTypeHeaderName && contentTypeHeader) { + // remove the leading semi colon and boundary + // up to the next semi colon or the end of string + const noBoundary = String(contentTypeHeader).replace(/; boundary.+?(?=(;|$))/, ''); + + // replace the content-type header with no boundary in both headersObj and allHeaders + headersObj[contentTypeHeaderName] = noBoundary; + allHeaders[contentTypeHeaderName] = noBoundary; + } + } + } + + // construct headers + Object.keys(headersObj) + .sort() + .forEach(key => { + const header = `${key}: ${headersObj[key]}`; + push(`${arg('header')} ${quote(header)}`); + }); + + if (allHeaders.cookie) { + push(`${arg('cookie')} ${quote(allHeaders.cookie as string)}`); + } + + // construct post params + switch (postData.mimeType) { + case 'multipart/form-data': + postData.params?.forEach(param => { + let post = ''; + // If the parameter is a filename, we want to put shell quotes around + // it rather than URL quoting it. Curl wants `file='@img copy.jpg'` + // not `file=@img%20copy.jpg`, which it will fail to find + if (param.fileName) { + post = `${param.name}='@${param.fileName}'`; + } else { + post = quote(`${param.name}=${param.value}`); + } + + push(`${arg('form')} ${post}`); + }); + break; + + case 'application/x-www-form-urlencoded': + if (postData.params) { + postData.params.forEach(param => { + const encoded = encodeURIComponent(param.name); + const name = encoded !== param.name ? encoded : param.name; + const flag = binary ? '--data-binary' : '--data-urlencode'; + push(`${flag} ${quote(`${name}=${param.value}`)}`); + }); + } else { + push(`${binary ? '--data-binary' : arg('data')} ${quote(postData.text)}`); + } + break; + + default: { + // raw request body + if (!postData.text) { + break; + } + + let builtPayload = false; + + // If we're dealing with a JSON variant, and our payload is JSON let's make it look a little + // nicer. + if (isMimeTypeJSON(postData.mimeType)) { + // If our postData is less than 20 characters, let's keep it all on one line so as to not + // make the snippet overly lengthy + if (postData.text.length > 20) { + try { + const jsonPayload = JSON.parse(postData.text); + + // If the JSON object has a single quote we should prepare it inside of a HEREDOC + // because the single quote in something like `string's` can't be escaped when used + // with `--data`. + // + // Basically this boils down to `--data @- < 0) { + push( + `${binary ? '--data-binary' : arg('data')} @- < = { + info: { + key: 'httpie', + title: 'HTTPie', + link: 'http://httpie.org/', + description: 'a CLI, cURL-like tool for humans', + extname: '.sh', + installation: () => 'brew install httpie', + }, + convert: ({ allHeaders, postData, queryObj, fullUrl, method, url }, options) => { + const opts = { + body: false, + cert: false, + headers: false, + indent: ' ', + pretty: false, + print: false, + queryParams: false, + short: false, + style: false, + timeout: false, + verbose: false, + verify: false, + ...options, + }; + + const { push, join, unshift } = new CodeBuilder({ + indent: opts.indent, + // @ts-expect-error SEEMS LEGIT + join: opts.indent !== false ? ` \\\n${opts.indent}` : ' ', + }); + + let raw = false; + const flags = []; + + if (opts.headers) { + flags.push(opts.short ? '-h' : '--headers'); + } + + if (opts.body) { + flags.push(opts.short ? '-b' : '--body'); + } + + if (opts.verbose) { + flags.push(opts.short ? '-v' : '--verbose'); + } + + if (opts.print) { + flags.push(`${opts.short ? '-p' : '--print'}=${opts.print}`); + } + + if (opts.verify) { + flags.push(`--verify=${opts.verify}`); + } + + if (opts.cert) { + flags.push(`--cert=${opts.cert}`); + } + + if (opts.pretty) { + flags.push(`--pretty=${opts.pretty}`); + } + + if (opts.style) { + flags.push(`--style=${opts.style}`); + } + + if (opts.timeout) { + flags.push(`--timeout=${opts.timeout}`); + } + + // construct query params + if (opts.queryParams) { + Object.keys(queryObj).forEach(name => { + const value = queryObj[name]; + + if (Array.isArray(value)) { + value.forEach(val => { + push(`${name}==${quote(val)}`); + }); + } else { + push(`${name}==${quote(value)}`); + } + }); + } + + // construct headers + Object.keys(allHeaders) + .sort() + .forEach(key => { + push(`${key}:${quote(allHeaders[key] as string)}`); + }); + + if (postData.mimeType === 'application/x-www-form-urlencoded') { + // construct post params + if (postData.params?.length) { + flags.push(opts.short ? '-f' : '--form'); + + postData.params.forEach(param => { + push(`${param.name}=${quote(param.value)}`); + }); + } + } else { + raw = true; + } + + const cliFlags = flags.length ? `${flags.join(' ')} ` : ''; + url = quote(opts.queryParams ? url : fullUrl); + unshift(`http ${cliFlags}${method} ${url}`); + + if (raw && postData.text) { + const postDataText = quote(postData.text); + unshift(`echo ${postDataText} | `); + } + + return join(); + }, +}; diff --git a/src/targets/shell/httpie/fixtures/application-form-encoded.sh b/src/targets/shell/httpie/fixtures/application-form-encoded.sh new file mode 100644 index 000000000..35bc74d2e --- /dev/null +++ b/src/targets/shell/httpie/fixtures/application-form-encoded.sh @@ -0,0 +1,4 @@ +http --form POST https://httpbin.org/anything \ + content-type:application/x-www-form-urlencoded \ + foo=bar \ + hello=world \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/application-json.sh b/src/targets/shell/httpie/fixtures/application-json.sh new file mode 100644 index 000000000..4eac570e9 --- /dev/null +++ b/src/targets/shell/httpie/fixtures/application-json.sh @@ -0,0 +1,3 @@ +echo '{"number":1,"string":"f\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":[]}],"boolean":false}' | \ + http POST https://httpbin.org/anything \ + content-type:application/json \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/build-parameters.sh b/src/targets/shell/httpie/fixtures/build-parameters.sh new file mode 100644 index 000000000..cc68fa3ad --- /dev/null +++ b/src/targets/shell/httpie/fixtures/build-parameters.sh @@ -0,0 +1 @@ +http -f POST https://httpbin.org/anything content-type:application/x-www-form-urlencoded foo=bar hello=world \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/cookies.sh b/src/targets/shell/httpie/fixtures/cookies.sh new file mode 100644 index 000000000..d3f6e10b4 --- /dev/null +++ b/src/targets/shell/httpie/fixtures/cookies.sh @@ -0,0 +1,2 @@ +http GET https://httpbin.org/cookies \ + cookie:'foo=bar; bar=baz' \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/custom-indentation.sh b/src/targets/shell/httpie/fixtures/custom-indentation.sh new file mode 100644 index 000000000..840228976 --- /dev/null +++ b/src/targets/shell/httpie/fixtures/custom-indentation.sh @@ -0,0 +1,5 @@ +http --form POST 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value' \ +@accept:application/json \ +@content-type:application/x-www-form-urlencoded \ +@cookie:'foo=bar; bar=baz' \ +@foo=bar \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/custom-method.sh b/src/targets/shell/httpie/fixtures/custom-method.sh new file mode 100644 index 000000000..94ce833e8 --- /dev/null +++ b/src/targets/shell/httpie/fixtures/custom-method.sh @@ -0,0 +1 @@ +http PROPFIND https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/full.sh b/src/targets/shell/httpie/fixtures/full.sh new file mode 100644 index 000000000..b419cadfe --- /dev/null +++ b/src/targets/shell/httpie/fixtures/full.sh @@ -0,0 +1,5 @@ +http --form POST 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value' \ + accept:application/json \ + content-type:application/x-www-form-urlencoded \ + cookie:'foo=bar; bar=baz' \ + foo=bar \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/headers.sh b/src/targets/shell/httpie/fixtures/headers.sh new file mode 100644 index 000000000..f645f1b39 --- /dev/null +++ b/src/targets/shell/httpie/fixtures/headers.sh @@ -0,0 +1,5 @@ +http GET https://httpbin.org/headers \ + accept:application/json \ + quoted-value:'"quoted" '\''string'\''' \ + x-bar:Foo \ + x-foo:Bar \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/http-insecure.sh b/src/targets/shell/httpie/fixtures/http-insecure.sh new file mode 100644 index 000000000..47dd04bff --- /dev/null +++ b/src/targets/shell/httpie/fixtures/http-insecure.sh @@ -0,0 +1 @@ +http GET http://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/jsonObj-multiline.sh b/src/targets/shell/httpie/fixtures/jsonObj-multiline.sh new file mode 100644 index 000000000..422fbb620 --- /dev/null +++ b/src/targets/shell/httpie/fixtures/jsonObj-multiline.sh @@ -0,0 +1,5 @@ +echo '{ + "foo": "bar" +}' | \ + http POST https://httpbin.org/anything \ + content-type:application/json \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/jsonObj-null-value.sh b/src/targets/shell/httpie/fixtures/jsonObj-null-value.sh new file mode 100644 index 000000000..ac7ac5a05 --- /dev/null +++ b/src/targets/shell/httpie/fixtures/jsonObj-null-value.sh @@ -0,0 +1,3 @@ +echo '{"foo":null}' | \ + http POST https://httpbin.org/anything \ + content-type:application/json \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/long-flags.sh b/src/targets/shell/httpie/fixtures/long-flags.sh new file mode 100644 index 000000000..ca1e4a8e6 --- /dev/null +++ b/src/targets/shell/httpie/fixtures/long-flags.sh @@ -0,0 +1 @@ +http --headers --body --verbose --print=y --verify=v --cert=foo --pretty=x --style=z --timeout=1 GET https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/multipart-data.sh b/src/targets/shell/httpie/fixtures/multipart-data.sh new file mode 100644 index 000000000..65e8761bb --- /dev/null +++ b/src/targets/shell/httpie/fixtures/multipart-data.sh @@ -0,0 +1,12 @@ +echo '-----011000010111000001101001 +Content-Disposition: form-data; name="foo"; filename="src/fixtures/files/hello.txt" +Content-Type: text/plain + +Hello World +-----011000010111000001101001 +Content-Disposition: form-data; name="bar" + +Bonjour le monde +-----011000010111000001101001--' | \ + http POST https://httpbin.org/anything \ + content-type:'multipart/form-data; boundary=---011000010111000001101001' \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/multipart-file.sh b/src/targets/shell/httpie/fixtures/multipart-file.sh new file mode 100644 index 000000000..9d8af4a2b --- /dev/null +++ b/src/targets/shell/httpie/fixtures/multipart-file.sh @@ -0,0 +1,8 @@ +echo '-----011000010111000001101001 +Content-Disposition: form-data; name="foo"; filename="src/fixtures/files/hello.txt" +Content-Type: text/plain + + +-----011000010111000001101001--' | \ + http POST https://httpbin.org/anything \ + content-type:'multipart/form-data; boundary=---011000010111000001101001' \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/multipart-form-data-no-params.sh b/src/targets/shell/httpie/fixtures/multipart-form-data-no-params.sh new file mode 100644 index 000000000..cc643fba1 --- /dev/null +++ b/src/targets/shell/httpie/fixtures/multipart-form-data-no-params.sh @@ -0,0 +1,2 @@ +http POST https://httpbin.org/anything \ + Content-Type:multipart/form-data \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/multipart-form-data.sh b/src/targets/shell/httpie/fixtures/multipart-form-data.sh new file mode 100644 index 000000000..d58677e62 --- /dev/null +++ b/src/targets/shell/httpie/fixtures/multipart-form-data.sh @@ -0,0 +1,7 @@ +echo '-----011000010111000001101001 +Content-Disposition: form-data; name="foo" + +bar +-----011000010111000001101001--' | \ + http POST https://httpbin.org/anything \ + Content-Type:'multipart/form-data; boundary=---011000010111000001101001' \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/nested.sh b/src/targets/shell/httpie/fixtures/nested.sh new file mode 100644 index 000000000..6ed37919b --- /dev/null +++ b/src/targets/shell/httpie/fixtures/nested.sh @@ -0,0 +1 @@ +http GET 'https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value' \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/postdata-malformed.sh b/src/targets/shell/httpie/fixtures/postdata-malformed.sh new file mode 100644 index 000000000..9716bde3f --- /dev/null +++ b/src/targets/shell/httpie/fixtures/postdata-malformed.sh @@ -0,0 +1,2 @@ +http POST https://httpbin.org/anything \ + content-type:application/json \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/query-encoded.sh b/src/targets/shell/httpie/fixtures/query-encoded.sh new file mode 100644 index 000000000..1869e9640 --- /dev/null +++ b/src/targets/shell/httpie/fixtures/query-encoded.sh @@ -0,0 +1 @@ +http GET 'https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00' \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/query.sh b/src/targets/shell/httpie/fixtures/query.sh new file mode 100644 index 000000000..e72e7726d --- /dev/null +++ b/src/targets/shell/httpie/fixtures/query.sh @@ -0,0 +1 @@ +http GET 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value' \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/querystring-parameters.sh b/src/targets/shell/httpie/fixtures/querystring-parameters.sh new file mode 100644 index 000000000..07a98707d --- /dev/null +++ b/src/targets/shell/httpie/fixtures/querystring-parameters.sh @@ -0,0 +1 @@ +http GET https://httpbin.org/anything foo==bar foo==baz baz==abc key==value \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/short-flags.sh b/src/targets/shell/httpie/fixtures/short-flags.sh new file mode 100644 index 000000000..1e3ad77da --- /dev/null +++ b/src/targets/shell/httpie/fixtures/short-flags.sh @@ -0,0 +1 @@ +http -h -b -v -p=y --verify=v --cert=foo --pretty=x --style=z --timeout=1 GET https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/short.sh b/src/targets/shell/httpie/fixtures/short.sh new file mode 100644 index 000000000..753546ffa --- /dev/null +++ b/src/targets/shell/httpie/fixtures/short.sh @@ -0,0 +1 @@ +http GET https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/text-plain.sh b/src/targets/shell/httpie/fixtures/text-plain.sh new file mode 100644 index 000000000..8e5f89cb7 --- /dev/null +++ b/src/targets/shell/httpie/fixtures/text-plain.sh @@ -0,0 +1,3 @@ +echo 'Hello World' | \ + http POST https://httpbin.org/anything \ + content-type:text/plain \ No newline at end of file diff --git a/src/targets/shell/httpie/fixtures/verbose-output.sh b/src/targets/shell/httpie/fixtures/verbose-output.sh new file mode 100644 index 000000000..3b53383c6 --- /dev/null +++ b/src/targets/shell/httpie/fixtures/verbose-output.sh @@ -0,0 +1 @@ +http --verbose GET https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/index.js b/src/targets/shell/index.js deleted file mode 100644 index 0f5fc05f0..000000000 --- a/src/targets/shell/index.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict' - -module.exports = { - info: { - key: 'shell', - title: 'Shell', - extname: '.sh', - default: 'curl' - }, - - curl: require('./curl'), - httpie: require('./httpie'), - wget: require('./wget') -} diff --git a/src/targets/shell/target.ts b/src/targets/shell/target.ts new file mode 100644 index 000000000..513a84b5c --- /dev/null +++ b/src/targets/shell/target.ts @@ -0,0 +1,19 @@ +import type { Target } from '../index.js'; + +import { curl } from './curl/client.js'; +import { httpie } from './httpie/client.js'; +import { wget } from './wget/client.js'; + +export const shell: Target = { + info: { + key: 'shell', + title: 'Shell', + default: 'curl', + cli: '%s', + }, + clientsById: { + curl, + httpie, + wget, + }, +}; diff --git a/src/targets/shell/wget.js b/src/targets/shell/wget.js deleted file mode 100644 index 5bce77ab0..000000000 --- a/src/targets/shell/wget.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * @description - * HTTP code snippet generator for the Shell using Wget. - * - * @author - * @AhmadNassri - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var util = require('util') -var helpers = require('../../helpers/shell') -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ', - short: false, - verbose: false - }, options) - - var code = new CodeBuilder(opts.indent, opts.indent !== false ? ' \\\n' + opts.indent : ' ') - - if (opts.verbose) { - code.push('wget %s', opts.short ? '-v' : '--verbose') - } else { - code.push('wget %s', opts.short ? '-q' : '--quiet') - } - - code.push('--method %s', helpers.quote(source.method)) - - Object.keys(source.allHeaders).forEach(function (key) { - var header = util.format('%s: %s', key, source.allHeaders[key]) - code.push('--header %s', helpers.quote(header)) - }) - - if (source.postData.text) { - code.push('--body-data ' + helpers.escape(helpers.quote(source.postData.text))) - } - - code.push(opts.short ? '-O' : '--output-document') - .push('- %s', helpers.quote(source.fullUrl)) - - return code.join() -} - -module.exports.info = { - key: 'wget', - title: 'Wget', - link: 'https://www.gnu.org/software/wget/', - description: 'a free software package for retrieving files using HTTP, HTTPS' -} diff --git a/src/targets/shell/wget/client.test.ts b/src/targets/shell/wget/client.test.ts new file mode 100644 index 000000000..1ca553c38 --- /dev/null +++ b/src/targets/shell/wget/client.test.ts @@ -0,0 +1,36 @@ +import type { Request } from '../../../index.js'; + +import full from '../../../fixtures/requests/full.cjs'; +import short from '../../../fixtures/requests/short.cjs'; +import { runCustomFixtures } from '../../../fixtures/runCustomFixtures.js'; + +runCustomFixtures({ + targetId: 'shell', + clientId: 'wget', + tests: [ + { + it: 'should use short options', + input: full.log.entries[0].request as Request, + options: { short: true, indent: false }, + expected: 'short-options.sh', + }, + { + it: 'should ask for -v output', + input: short.log.entries[0].request as Request, + options: { short: true, indent: false, verbose: true }, + expected: 'v-output.sh', + }, + { + it: 'should ask for --verbose output', + input: short.log.entries[0].request as Request, + options: { short: false, indent: false, verbose: true }, + expected: 'verbose-output.sh', + }, + { + it: 'should use custom indentation', + input: full.log.entries[0].request as Request, + options: { indent: '@' }, + expected: 'custom-indentation.sh', + }, + ], +}); diff --git a/src/targets/shell/wget/client.ts b/src/targets/shell/wget/client.ts new file mode 100644 index 000000000..8091bd3e5 --- /dev/null +++ b/src/targets/shell/wget/client.ts @@ -0,0 +1,64 @@ +/** + * @description + * HTTP code snippet generator for the Shell using Wget. + * + * @author + * @AhmadNassri + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { escape, quote } from '../../../helpers/shell.js'; + +export interface WgetOptions { + indent?: string | false; + short?: boolean; + verbose?: boolean; +} + +export const wget: Client = { + info: { + key: 'wget', + title: 'Wget', + link: 'https://www.gnu.org/software/wget/', + description: 'a free software package for retrieving files using HTTP, HTTPS', + extname: '.sh', + }, + convert: ({ method, postData, allHeaders, fullUrl }, options) => { + const opts = { + indent: ' ', + short: false, + verbose: false, + ...options, + }; + + const { push, join } = new CodeBuilder({ + ...(typeof opts.indent === 'string' ? { indent: opts.indent } : {}), + join: opts.indent !== false ? ` \\\n${opts.indent}` : ' ', + }); + + if (opts.verbose) { + push(`wget ${opts.short ? '-v' : '--verbose'}`); + } else { + push(`wget ${opts.short ? '-q' : '--quiet'}`); + } + + push(`--method ${quote(method)}`); + + Object.keys(allHeaders).forEach(key => { + const header = `${key}: ${allHeaders[key]}`; + push(`--header ${quote(header)}`); + }); + + if (postData.text) { + push(`--body-data ${escape(quote(postData.text))}`); + } + + push(opts.short ? '-O' : '--output-document'); + push(`- ${quote(fullUrl)}`); + + return join(); + }, +}; diff --git a/src/targets/shell/wget/fixtures/application-form-encoded.sh b/src/targets/shell/wget/fixtures/application-form-encoded.sh new file mode 100644 index 000000000..36d43a466 --- /dev/null +++ b/src/targets/shell/wget/fixtures/application-form-encoded.sh @@ -0,0 +1,6 @@ +wget --quiet \ + --method POST \ + --header 'content-type: application/x-www-form-urlencoded' \ + --body-data 'foo=bar&hello=world' \ + --output-document \ + - https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/application-json.sh b/src/targets/shell/wget/fixtures/application-json.sh new file mode 100644 index 000000000..d066d8204 --- /dev/null +++ b/src/targets/shell/wget/fixtures/application-json.sh @@ -0,0 +1,6 @@ +wget --quiet \ + --method POST \ + --header 'content-type: application/json' \ + --body-data '{"number":1,"string":"f\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":[]}],"boolean":false}' \ + --output-document \ + - https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/cookies.sh b/src/targets/shell/wget/fixtures/cookies.sh new file mode 100644 index 000000000..50d431425 --- /dev/null +++ b/src/targets/shell/wget/fixtures/cookies.sh @@ -0,0 +1,5 @@ +wget --quiet \ + --method GET \ + --header 'cookie: foo=bar; bar=baz' \ + --output-document \ + - https://httpbin.org/cookies \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/custom-indentation.sh b/src/targets/shell/wget/fixtures/custom-indentation.sh new file mode 100644 index 000000000..7373a114a --- /dev/null +++ b/src/targets/shell/wget/fixtures/custom-indentation.sh @@ -0,0 +1,8 @@ +wget --quiet \ +@--method POST \ +@--header 'cookie: foo=bar; bar=baz' \ +@--header 'accept: application/json' \ +@--header 'content-type: application/x-www-form-urlencoded' \ +@--body-data foo=bar \ +@--output-document \ +@- 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value' \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/custom-method.sh b/src/targets/shell/wget/fixtures/custom-method.sh new file mode 100644 index 000000000..336fe2dd4 --- /dev/null +++ b/src/targets/shell/wget/fixtures/custom-method.sh @@ -0,0 +1,4 @@ +wget --quiet \ + --method PROPFIND \ + --output-document \ + - https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/full.sh b/src/targets/shell/wget/fixtures/full.sh new file mode 100644 index 000000000..7a54a8e0c --- /dev/null +++ b/src/targets/shell/wget/fixtures/full.sh @@ -0,0 +1,8 @@ +wget --quiet \ + --method POST \ + --header 'cookie: foo=bar; bar=baz' \ + --header 'accept: application/json' \ + --header 'content-type: application/x-www-form-urlencoded' \ + --body-data foo=bar \ + --output-document \ + - 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value' \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/headers.sh b/src/targets/shell/wget/fixtures/headers.sh new file mode 100644 index 000000000..41fc7df35 --- /dev/null +++ b/src/targets/shell/wget/fixtures/headers.sh @@ -0,0 +1,8 @@ +wget --quiet \ + --method GET \ + --header 'accept: application/json' \ + --header 'x-foo: Bar' \ + --header 'x-bar: Foo' \ + --header 'quoted-value: "quoted" '\''string'\''' \ + --output-document \ + - https://httpbin.org/headers \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/http-insecure.sh b/src/targets/shell/wget/fixtures/http-insecure.sh new file mode 100644 index 000000000..05eac2d45 --- /dev/null +++ b/src/targets/shell/wget/fixtures/http-insecure.sh @@ -0,0 +1,4 @@ +wget --quiet \ + --method GET \ + --output-document \ + - http://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/jsonObj-multiline.sh b/src/targets/shell/wget/fixtures/jsonObj-multiline.sh new file mode 100644 index 000000000..384463d92 --- /dev/null +++ b/src/targets/shell/wget/fixtures/jsonObj-multiline.sh @@ -0,0 +1,6 @@ +wget --quiet \ + --method POST \ + --header 'content-type: application/json' \ + --body-data '{\n "foo": "bar"\n}' \ + --output-document \ + - https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/jsonObj-null-value.sh b/src/targets/shell/wget/fixtures/jsonObj-null-value.sh new file mode 100644 index 000000000..84322d912 --- /dev/null +++ b/src/targets/shell/wget/fixtures/jsonObj-null-value.sh @@ -0,0 +1,6 @@ +wget --quiet \ + --method POST \ + --header 'content-type: application/json' \ + --body-data '{"foo":null}' \ + --output-document \ + - https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/multipart-data.sh b/src/targets/shell/wget/fixtures/multipart-data.sh new file mode 100644 index 000000000..a92b72793 --- /dev/null +++ b/src/targets/shell/wget/fixtures/multipart-data.sh @@ -0,0 +1,6 @@ +wget --quiet \ + --method POST \ + --header 'content-type: multipart/form-data; boundary=---011000010111000001101001' \ + --body-data '-----011000010111000001101001\r\nContent-Disposition: form-data; name="foo"; filename="src/fixtures/files/hello.txt"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001\r\nContent-Disposition: form-data; name="bar"\r\n\r\nBonjour le monde\r\n-----011000010111000001101001--' \ + --output-document \ + - https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/multipart-file.sh b/src/targets/shell/wget/fixtures/multipart-file.sh new file mode 100644 index 000000000..dbc0765db --- /dev/null +++ b/src/targets/shell/wget/fixtures/multipart-file.sh @@ -0,0 +1,6 @@ +wget --quiet \ + --method POST \ + --header 'content-type: multipart/form-data; boundary=---011000010111000001101001' \ + --body-data '-----011000010111000001101001\r\nContent-Disposition: form-data; name="foo"; filename="src/fixtures/files/hello.txt"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--' \ + --output-document \ + - https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/multipart-form-data-no-params.sh b/src/targets/shell/wget/fixtures/multipart-form-data-no-params.sh new file mode 100644 index 000000000..f3e250012 --- /dev/null +++ b/src/targets/shell/wget/fixtures/multipart-form-data-no-params.sh @@ -0,0 +1,5 @@ +wget --quiet \ + --method POST \ + --header 'Content-Type: multipart/form-data' \ + --output-document \ + - https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/multipart-form-data.sh b/src/targets/shell/wget/fixtures/multipart-form-data.sh new file mode 100644 index 000000000..317e04fde --- /dev/null +++ b/src/targets/shell/wget/fixtures/multipart-form-data.sh @@ -0,0 +1,6 @@ +wget --quiet \ + --method POST \ + --header 'Content-Type: multipart/form-data; boundary=---011000010111000001101001' \ + --body-data '-----011000010111000001101001\r\nContent-Disposition: form-data; name="foo"\r\n\r\nbar\r\n-----011000010111000001101001--' \ + --output-document \ + - https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/nested.sh b/src/targets/shell/wget/fixtures/nested.sh new file mode 100644 index 000000000..595b015b2 --- /dev/null +++ b/src/targets/shell/wget/fixtures/nested.sh @@ -0,0 +1,4 @@ +wget --quiet \ + --method GET \ + --output-document \ + - 'https://httpbin.org/anything?foo%5Bbar%5D=baz%2Czap&fiz=buz&key=value' \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/postdata-malformed.sh b/src/targets/shell/wget/fixtures/postdata-malformed.sh new file mode 100644 index 000000000..eb1fe7ce8 --- /dev/null +++ b/src/targets/shell/wget/fixtures/postdata-malformed.sh @@ -0,0 +1,5 @@ +wget --quiet \ + --method POST \ + --header 'content-type: application/json' \ + --output-document \ + - https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/query-encoded.sh b/src/targets/shell/wget/fixtures/query-encoded.sh new file mode 100644 index 000000000..5be801b68 --- /dev/null +++ b/src/targets/shell/wget/fixtures/query-encoded.sh @@ -0,0 +1,4 @@ +wget --quiet \ + --method GET \ + --output-document \ + - 'https://httpbin.org/anything?startTime=2019-06-13T19%3A08%3A25.455Z&endTime=2015-09-15T14%3A00%3A12-04%3A00' \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/query.sh b/src/targets/shell/wget/fixtures/query.sh new file mode 100644 index 000000000..1cce8fcbe --- /dev/null +++ b/src/targets/shell/wget/fixtures/query.sh @@ -0,0 +1,4 @@ +wget --quiet \ + --method GET \ + --output-document \ + - 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value' \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/short-options.sh b/src/targets/shell/wget/fixtures/short-options.sh new file mode 100644 index 000000000..7fa9c2ca2 --- /dev/null +++ b/src/targets/shell/wget/fixtures/short-options.sh @@ -0,0 +1 @@ +wget -q --method POST --header 'cookie: foo=bar; bar=baz' --header 'accept: application/json' --header 'content-type: application/x-www-form-urlencoded' --body-data foo=bar -O - 'https://httpbin.org/anything?foo=bar&foo=baz&baz=abc&key=value' \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/short.sh b/src/targets/shell/wget/fixtures/short.sh new file mode 100644 index 000000000..ce9f75ad8 --- /dev/null +++ b/src/targets/shell/wget/fixtures/short.sh @@ -0,0 +1,4 @@ +wget --quiet \ + --method GET \ + --output-document \ + - https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/text-plain.sh b/src/targets/shell/wget/fixtures/text-plain.sh new file mode 100644 index 000000000..e8abeb59d --- /dev/null +++ b/src/targets/shell/wget/fixtures/text-plain.sh @@ -0,0 +1,6 @@ +wget --quiet \ + --method POST \ + --header 'content-type: text/plain' \ + --body-data 'Hello World' \ + --output-document \ + - https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/v-output.sh b/src/targets/shell/wget/fixtures/v-output.sh new file mode 100644 index 000000000..d794dba50 --- /dev/null +++ b/src/targets/shell/wget/fixtures/v-output.sh @@ -0,0 +1 @@ +wget -v --method GET -O - https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/shell/wget/fixtures/verbose-output.sh b/src/targets/shell/wget/fixtures/verbose-output.sh new file mode 100644 index 000000000..6c1494ca6 --- /dev/null +++ b/src/targets/shell/wget/fixtures/verbose-output.sh @@ -0,0 +1 @@ +wget --verbose --method GET --output-document - https://httpbin.org/anything \ No newline at end of file diff --git a/src/targets/swift/helpers.js b/src/targets/swift/helpers.js deleted file mode 100644 index fdc26fd82..000000000 --- a/src/targets/swift/helpers.js +++ /dev/null @@ -1,83 +0,0 @@ -'use strict' - -var util = require('util') - -/** - * Create an string of given length filled with blank spaces - * - * @param {number} length Length of the array to return - * @return {string} - */ -function buildString (length, str) { - return Array.apply(null, new Array(length)).map(String.prototype.valueOf, str).join('') -} - -/** - * Create a string corresponding to a Dictionary or Array literal representation with pretty option - * and indentation. - */ -function concatArray (arr, pretty, indentation, indentLevel) { - var currentIndent = buildString(indentLevel, indentation) - var closingBraceIndent = buildString(indentLevel - 1, indentation) - var join = pretty ? ',\n' + currentIndent : ', ' - - if (pretty) { - return '[\n' + currentIndent + arr.join(join) + '\n' + closingBraceIndent + ']' - } else { - return '[' + arr.join(join) + ']' - } -} - -module.exports = { - /** - * Create a string corresponding to a valid declaration and initialization of a Swift array or dictionary literal - * - * @param {string} name Desired name of the instance - * @param {Object} parameters Key-value object of parameters to translate to a Swift object litearal - * @param {Object} opts Target options - * @return {string} - */ - literalDeclaration: function (name, parameters, opts) { - return util.format('let %s = %s', name, this.literalRepresentation(parameters, opts)) - }, - - /** - * Create a valid Swift string of a literal value according to its type. - * - * @param {*} value Any JavaScript literal - * @param {Object} opts Target options - * @return {string} - */ - literalRepresentation: function (value, opts, indentLevel) { - indentLevel = indentLevel === undefined ? 1 : indentLevel + 1 - - switch (Object.prototype.toString.call(value)) { - case '[object Number]': - return value - case '[object Array]': - // Don't prettify arrays nto not take too much space - var pretty = false - var valuesRepresentation = value.map(function (v) { - // Switch to prettify if the value is a dictionary with multiple keys - if (Object.prototype.toString.call(v) === '[object Object]') { - pretty = Object.keys(v).length > 1 - } - return this.literalRepresentation(v, opts, indentLevel) - }.bind(this)) - return concatArray(valuesRepresentation, pretty, opts.indent, indentLevel) - case '[object Object]': - var keyValuePairs = [] - for (var k in value) { - keyValuePairs.push(util.format('"%s": %s', k, this.literalRepresentation(value[k], opts, indentLevel))) - } - return concatArray(keyValuePairs, opts.pretty && keyValuePairs.length > 1, opts.indent, indentLevel) - case '[object Boolean]': - return value.toString() - default: - if (value === null || value === undefined) { - return '' - } - return '"' + value.toString().replace(/"/g, '\\"') + '"' - } - } -} diff --git a/src/targets/swift/helpers.ts b/src/targets/swift/helpers.ts new file mode 100644 index 000000000..faea62925 --- /dev/null +++ b/src/targets/swift/helpers.ts @@ -0,0 +1,85 @@ +/** + * Create an string of given length filled with blank spaces + * + * @param length Length of the array to return + * @param str String to pad out with + */ +const buildString = (length: number, str: string) => str.repeat(length); + +/** + * Create a string corresponding to a Dictionary or Array literal representation with pretty option and indentation. + */ +const concatArray = (arr: T[], pretty: boolean, indentation: string, indentLevel: number) => { + const currentIndent = buildString(indentLevel, indentation); + const closingBraceIndent = buildString(indentLevel - 1, indentation); + const join = pretty ? `,\n${currentIndent}` : ', '; + + if (pretty) { + return `[\n${currentIndent}${arr.join(join)}\n${closingBraceIndent}]`; + } + return `[${arr.join(join)}]`; +}; + +/** + * Create a string corresponding to a valid declaration and initialization of a Swift array or dictionary literal + * + * @param name Desired name of the instance + * @param parameters Key-value object of parameters to translate to a Swift object litearal + * @param opts Target options + * @return {string} + */ +export const literalDeclaration = (name: string, parameters: T, opts: U) => + `let ${name} = ${literalRepresentation(parameters, opts)}`; + +/** + * Create a valid Swift string of a literal value according to its type. + * + * @param value Any JavaScript literal + * @param opts Target options + */ +export const literalRepresentation = (value: T, opts: U, indentLevel?: number): number | string => { + indentLevel = indentLevel === undefined ? 1 : indentLevel + 1; + + switch (Object.prototype.toString.call(value)) { + case '[object Number]': + return value as unknown as number; + + case '[object Array]': { + // Don't prettify arrays nto not take too much space + let pretty = false; + const valuesRepresentation = (value as unknown as any[]).map((v: any) => { + // Switch to prettify if the value is a dictionary with multiple keys + if (Object.prototype.toString.call(v) === '[object Object]') { + pretty = Object.keys(v).length > 1; + } + return literalRepresentation(v, opts, indentLevel); + }); + // @ts-expect-error needs better types + return concatArray(valuesRepresentation, pretty, opts.indent, indentLevel); + } + + case '[object Object]': { + const keyValuePairs = []; + for (const key in value) { + keyValuePairs.push(`"${key}": ${literalRepresentation(value[key], opts, indentLevel)}`); + } + return concatArray( + keyValuePairs, + // @ts-expect-error needs better types + opts.pretty && keyValuePairs.length > 1, + // @ts-expect-error needs better types + opts.indent, + indentLevel, + ); + } + + case '[object Boolean]': + return (value as unknown as boolean).toString(); + + default: + if (value === null || value === undefined) { + return 'nil'; + } + return `"${(value as any).toString().replace(/"/g, '\\"')}"`; + } +}; diff --git a/src/targets/swift/index.js b/src/targets/swift/index.js deleted file mode 100644 index fba4dfea2..000000000 --- a/src/targets/swift/index.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict' - -module.exports = { - info: { - key: 'swift', - title: 'Swift', - extname: '.swift', - default: 'nsurlsession' - }, - - nsurlsession: require('./nsurlsession') -} diff --git a/src/targets/swift/nsurlsession.js b/src/targets/swift/nsurlsession.js deleted file mode 100644 index 6bf6f7819..000000000 --- a/src/targets/swift/nsurlsession.js +++ /dev/null @@ -1,139 +0,0 @@ -/** - * @description - * HTTP code snippet generator for Swift using NSURLSession. - * - * @author - * @thibaultCha - * - * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. - */ - -'use strict' - -var util = require('util') -var helpers = require('./helpers') -var CodeBuilder = require('../../helpers/code-builder') - -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ', - pretty: true, - timeout: '10' - }, options) - - var code = new CodeBuilder(opts.indent) - - // Markers for headers to be created as litteral objects and later be set on the NSURLRequest if exist - var req = { - hasHeaders: false, - hasBody: false - } - - // We just want to make sure people understand that is the only dependency - code.push('import Foundation') - - if (Object.keys(source.allHeaders).length) { - req.hasHeaders = true - code.blank() - .push(helpers.literalDeclaration('headers', source.allHeaders, opts)) - } - - if (source.postData.text || source.postData.jsonObj || source.postData.params) { - req.hasBody = true - - switch (source.postData.mimeType) { - case 'application/x-www-form-urlencoded': - // By appending parameters one by one in the resulting snippet, - // we make it easier for the user to edit it according to his or her needs after pasting. - // The user can just add/remove lines adding/removing body parameters. - code.blank() - .push('let postData = NSMutableData(data: "%s=%s".data(using: String.Encoding.utf8)!)', source.postData.params[0].name, source.postData.params[0].value) - for (var i = 1, len = source.postData.params.length; i < len; i++) { - code.push('postData.append("&%s=%s".data(using: String.Encoding.utf8)!)', source.postData.params[i].name, source.postData.params[i].value) - } - break - - case 'application/json': - if (source.postData.jsonObj) { - code.push(helpers.literalDeclaration('parameters', source.postData.jsonObj, opts), 'as [String : Any]') - .blank() - .push('let postData = JSONSerialization.data(withJSONObject: parameters, options: [])') - } - break - - case 'multipart/form-data': - /** - * By appending multipart parameters one by one in the resulting snippet, - * we make it easier for the user to edit it according to his or her needs after pasting. - * The user can just edit the parameters NSDictionary or put this part of a snippet in a multipart builder method. - */ - code.push(helpers.literalDeclaration('parameters', source.postData.params, opts)) - .blank() - .push('let boundary = "%s"', source.postData.boundary) - .blank() - .push('var body = ""') - .push('var error: NSError? = nil') - .push('for param in parameters {') - .push(1, 'let paramName = param["name"]!') - .push(1, 'body += "--\\(boundary)\\r\\n"') - .push(1, 'body += "Content-Disposition:form-data; name=\\"\\(paramName)\\""') - .push(1, 'if let filename = param["fileName"] {') - .push(2, 'let contentType = param["content-type"]!') - .push(2, 'let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8)') - .push(2, 'if (error != nil) {') - .push(3, 'print(error)') - .push(2, '}') - .push(2, 'body += "; filename=\\"\\(filename)\\"\\r\\n"') - .push(2, 'body += "Content-Type: \\(contentType)\\r\\n\\r\\n"') - .push(2, 'body += fileContent') - .push(1, '} else if let paramValue = param["value"] {') - .push(2, 'body += "\\r\\n\\r\\n\\(paramValue)"') - .push(1, '}') - .push('}') - break - - default: - code.blank() - .push('let postData = NSData(data: "%s".data(using: String.Encoding.utf8)!)', source.postData.text) - } - } - - code.blank() - // NSURLRequestUseProtocolCachePolicy is the default policy, let's just always set it to avoid confusion. - .push('let request = NSMutableURLRequest(url: NSURL(string: "%s")! as URL,', source.fullUrl) - .push(' cachePolicy: .useProtocolCachePolicy,') - .push(' timeoutInterval: %s)', parseInt(opts.timeout, 10).toFixed(1)) - .push('request.httpMethod = "%s"', source.method) - - if (req.hasHeaders) { - code.push('request.allHTTPHeaderFields = headers') - } - - if (req.hasBody) { - code.push('request.httpBody = postData as Data') - } - - code.blank() - // Retrieving the shared session will be less verbose than creating a new one. - .push('let session = URLSession.shared') - .push('let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in') - .push(1, 'if (error != nil) {') - .push(2, 'print(error)') - .push(1, '} else {') - // Casting the NSURLResponse to NSHTTPURLResponse so the user can see the status . - .push(2, 'let httpResponse = response as? HTTPURLResponse') - .push(2, 'print(httpResponse)') - .push(1, '}') - .push('})') - .blank() - .push('dataTask.resume()') - - return code.join() -} - -module.exports.info = { - key: 'nsurlsession', - title: 'NSURLSession', - link: 'https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/index.html', - description: 'Foundation\'s NSURLSession request' -} diff --git a/src/targets/swift/target.ts b/src/targets/swift/target.ts new file mode 100644 index 000000000..8c85c6215 --- /dev/null +++ b/src/targets/swift/target.ts @@ -0,0 +1,14 @@ +import type { Target } from '../index.js'; + +import { urlsession } from './urlsession/client.js'; + +export const swift: Target = { + info: { + key: 'swift', + title: 'Swift', + default: 'urlsession', + }, + clientsById: { + urlsession, + }, +}; diff --git a/src/targets/swift/urlsession/client.test.ts b/src/targets/swift/urlsession/client.test.ts new file mode 100644 index 000000000..d4401fb49 --- /dev/null +++ b/src/targets/swift/urlsession/client.test.ts @@ -0,0 +1,45 @@ +import type { Request } from '../../../index.js'; + +import full from '../../../fixtures/requests/full.cjs'; +import jsonNullValue from '../../../fixtures/requests/jsonObj-null-value.cjs'; +import short from '../../../fixtures/requests/short.cjs'; +import { runCustomFixtures } from '../../../fixtures/runCustomFixtures.js'; + +runCustomFixtures({ + targetId: 'swift', + clientId: 'urlsession', + tests: [ + { + it: 'should support an indent option', + input: short.log.entries[0].request as Request, + options: { + indent: ' ', + }, + expected: 'indent-option.swift', + }, + { + it: 'should support a timeout option', + input: short.log.entries[0].request as Request, + options: { + timeout: 5, + }, + expected: 'timeout-option.swift', + }, + { + it: 'should support pretty option', + input: full.log.entries[0].request as Request, + options: { + pretty: false, + }, + expected: 'pretty-option.swift', + }, + { + it: 'should support json object with null value', + input: jsonNullValue.log.entries[0].request as unknown as Request, + options: { + pretty: false, + }, + expected: 'json-null-value.swift', + }, + ], +}); diff --git a/src/targets/swift/urlsession/client.ts b/src/targets/swift/urlsession/client.ts new file mode 100644 index 000000000..e904984af --- /dev/null +++ b/src/targets/swift/urlsession/client.ts @@ -0,0 +1,160 @@ +/** + * @description + * HTTP code snippet generator for Swift using URLSession. + * + * @author + * @thibaultCha + * + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. + */ +import type { Client } from '../../index.js'; + +import { CodeBuilder } from '../../../helpers/code-builder.js'; +import { literalDeclaration, literalRepresentation } from '../helpers.js'; + +export interface UrlsessionOptions { + pretty?: boolean; + timeout?: number | string; +} + +export const urlsession: Client = { + info: { + key: 'urlsession', + title: 'URLSession', + link: 'https://developer.apple.com/documentation/foundation/urlsession', + description: "Foundation's URLSession request", + extname: '.swift', + }, + convert: ({ allHeaders, postData, uriObj, queryObj, method }, options) => { + const opts = { + indent: ' ', + pretty: true, + timeout: 10, + ...options, + }; + + const { push, blank, join } = new CodeBuilder({ indent: opts.indent }); + + push('import Foundation'); + blank(); + + const hasBody = postData.text || postData.jsonObj || postData.params; + if (hasBody) { + switch (postData.mimeType) { + case 'application/x-www-form-urlencoded': + // By appending parameters one by one in the resulting snippet, + // we make it easier for the user to edit it according to his or her needs after pasting. + // The user can just add/remove lines adding/removing body parameters. + if (postData.params?.length) { + const parameters = postData.params.map(p => `"${p.name}": "${p.value}"`); + if (opts.pretty) { + push('let parameters = ['); + parameters.forEach(param => { + push(`${param},`, 1); + }); + push(']'); + } else { + push(`let parameters = [${parameters.join(', ')}]`); + } + + push('let joinedParameters = parameters.map { "\\($0.key)=\\($0.value)" }.joined(separator: "&")'); + push('let postData = Data(joinedParameters.utf8)'); + blank(); + } + break; + + case 'application/json': + if (postData.jsonObj) { + push(`${literalDeclaration('parameters', postData.jsonObj, opts)} as [String : Any?]`); + blank(); + push('let postData = try JSONSerialization.data(withJSONObject: parameters, options: [])'); + blank(); + } + break; + + case 'multipart/form-data': + /** + * By appending multipart parameters one by one in the resulting snippet, + * we make it easier for the user to edit it according to his or her needs after pasting. + * The user can just edit the parameters Dictionary or put this part of a snippet in a multipart builder method. + */ + + push(literalDeclaration('parameters', postData.params, opts)); + blank(); + push(`let boundary = "${postData.boundary}"`); + blank(); + push('var body = ""'); + push('for param in parameters {'); + push('let paramName = param["name"]!', 1); + push('body += "--\\(boundary)\\r\\n"', 1); + push('body += "Content-Disposition:form-data; name=\\"\\(paramName)\\""', 1); + push('if let filename = param["fileName"] {', 1); + push('let contentType = param["contentType"]!', 2); + push('let fileContent = try String(contentsOfFile: filename, encoding: .utf8)', 2); + push('body += "; filename=\\"\\(filename)\\"\\r\\n"', 2); + push('body += "Content-Type: \\(contentType)\\r\\n\\r\\n"', 2); + push('body += fileContent', 2); + push('} else if let paramValue = param["value"] {', 1); + push('body += "\\r\\n\\r\\n\\(paramValue)"', 2); + push('}', 1); + push('}'); + blank(); + push('let postData = Data(body.utf8)'); + blank(); + break; + + default: + push(`let postData = Data("${postData.text}".utf8)`); + blank(); + } + } + + push(`let url = URL(string: "${uriObj.href}")!`); + + const queries = queryObj ? Object.entries(queryObj) : []; + if (queries.length < 1) { + push('var request = URLRequest(url: url)'); + } else { + push('var components = URLComponents(url: url, resolvingAgainstBaseURL: true)!'); + push('let queryItems: [URLQueryItem] = ['); + + queries.forEach(query => { + const key = query[0]; + const value = query[1]; + switch (Object.prototype.toString.call(value)) { + case '[object String]': + push(`URLQueryItem(name: "${key}", value: "${value}"),`, 1); + break; + case '[object Array]': + (value as string[]).forEach((val: string) => { + push(`URLQueryItem(name: "${key}", value: "${val}"),`, 1); + }); + break; + } + }); + push(']'); + push('components.queryItems = components.queryItems.map { $0 + queryItems } ?? queryItems'); + + blank(); + push('var request = URLRequest(url: components.url!)'); + } + + push(`request.httpMethod = "${method}"`); + push(`request.timeoutInterval = ${opts.timeout}`); + + if (Object.keys(allHeaders).length) { + push(`request.allHTTPHeaderFields = ${literalRepresentation(allHeaders, opts)}`); + } + + if (hasBody) { + push('request.httpBody = postData'); + } + + blank(); + + push('let (data, _) = try await URLSession.shared.data(for: request)'); + push('print(String(decoding: data, as: UTF8.self))'); + + return join(); + }, +}; diff --git a/src/targets/swift/urlsession/fixtures/application-form-encoded.swift b/src/targets/swift/urlsession/fixtures/application-form-encoded.swift new file mode 100644 index 000000000..b79554db0 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/application-form-encoded.swift @@ -0,0 +1,18 @@ +import Foundation + +let parameters = [ + "foo": "bar", + "hello": "world", +] +let joinedParameters = parameters.map { "\($0.key)=\($0.value)" }.joined(separator: "&") +let postData = Data(joinedParameters.utf8) + +let url = URL(string: "https://httpbin.org/anything")! +var request = URLRequest(url: url) +request.httpMethod = "POST" +request.timeoutInterval = 10 +request.allHTTPHeaderFields = ["content-type": "application/x-www-form-urlencoded"] +request.httpBody = postData + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/application-json.swift b/src/targets/swift/urlsession/fixtures/application-json.swift new file mode 100644 index 000000000..39508bf62 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/application-json.swift @@ -0,0 +1,22 @@ +import Foundation + +let parameters = [ + "number": 1, + "string": "f\"oo", + "arr": [1, 2, 3], + "nested": ["a": "b"], + "arr_mix": [1, "a", ["arr_mix_nested": []]], + "boolean": false +] as [String : Any?] + +let postData = try JSONSerialization.data(withJSONObject: parameters, options: []) + +let url = URL(string: "https://httpbin.org/anything")! +var request = URLRequest(url: url) +request.httpMethod = "POST" +request.timeoutInterval = 10 +request.allHTTPHeaderFields = ["content-type": "application/json"] +request.httpBody = postData + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/cookies.swift b/src/targets/swift/urlsession/fixtures/cookies.swift new file mode 100644 index 000000000..cd1ea1906 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/cookies.swift @@ -0,0 +1,10 @@ +import Foundation + +let url = URL(string: "https://httpbin.org/cookies")! +var request = URLRequest(url: url) +request.httpMethod = "GET" +request.timeoutInterval = 10 +request.allHTTPHeaderFields = ["cookie": "foo=bar; bar=baz"] + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/custom-method.swift b/src/targets/swift/urlsession/fixtures/custom-method.swift new file mode 100644 index 000000000..118ff4933 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/custom-method.swift @@ -0,0 +1,9 @@ +import Foundation + +let url = URL(string: "https://httpbin.org/anything")! +var request = URLRequest(url: url) +request.httpMethod = "PROPFIND" +request.timeoutInterval = 10 + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/full.swift b/src/targets/swift/urlsession/fixtures/full.swift new file mode 100644 index 000000000..65ca5fcac --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/full.swift @@ -0,0 +1,30 @@ +import Foundation + +let parameters = [ + "foo": "bar", +] +let joinedParameters = parameters.map { "\($0.key)=\($0.value)" }.joined(separator: "&") +let postData = Data(joinedParameters.utf8) + +let url = URL(string: "https://httpbin.org/anything?key=value")! +var components = URLComponents(url: url, resolvingAgainstBaseURL: true)! +let queryItems: [URLQueryItem] = [ + URLQueryItem(name: "foo", value: "bar"), + URLQueryItem(name: "foo", value: "baz"), + URLQueryItem(name: "baz", value: "abc"), + URLQueryItem(name: "key", value: "value"), +] +components.queryItems = components.queryItems.map { $0 + queryItems } ?? queryItems + +var request = URLRequest(url: components.url!) +request.httpMethod = "POST" +request.timeoutInterval = 10 +request.allHTTPHeaderFields = [ + "cookie": "foo=bar; bar=baz", + "accept": "application/json", + "content-type": "application/x-www-form-urlencoded" +] +request.httpBody = postData + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/headers.swift b/src/targets/swift/urlsession/fixtures/headers.swift new file mode 100644 index 000000000..3a48c3d7d --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/headers.swift @@ -0,0 +1,15 @@ +import Foundation + +let url = URL(string: "https://httpbin.org/headers")! +var request = URLRequest(url: url) +request.httpMethod = "GET" +request.timeoutInterval = 10 +request.allHTTPHeaderFields = [ + "accept": "application/json", + "x-foo": "Bar", + "x-bar": "Foo", + "quoted-value": "\"quoted\" 'string'" +] + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/http-insecure.swift b/src/targets/swift/urlsession/fixtures/http-insecure.swift new file mode 100644 index 000000000..ec6724995 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/http-insecure.swift @@ -0,0 +1,9 @@ +import Foundation + +let url = URL(string: "http://httpbin.org/anything")! +var request = URLRequest(url: url) +request.httpMethod = "GET" +request.timeoutInterval = 10 + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/indent-option.swift b/src/targets/swift/urlsession/fixtures/indent-option.swift new file mode 100644 index 000000000..3a536dee1 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/indent-option.swift @@ -0,0 +1,9 @@ +import Foundation + +let url = URL(string: "https://httpbin.org/anything")! +var request = URLRequest(url: url) +request.httpMethod = "GET" +request.timeoutInterval = 10 + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/json-null-value.swift b/src/targets/swift/urlsession/fixtures/json-null-value.swift new file mode 100644 index 000000000..05c778801 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/json-null-value.swift @@ -0,0 +1,15 @@ +import Foundation + +let parameters = ["foo": nil] as [String : Any?] + +let postData = try JSONSerialization.data(withJSONObject: parameters, options: []) + +let url = URL(string: "https://httpbin.org/anything")! +var request = URLRequest(url: url) +request.httpMethod = "POST" +request.timeoutInterval = 10 +request.allHTTPHeaderFields = ["content-type": "application/json"] +request.httpBody = postData + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/jsonObj-multiline.swift b/src/targets/swift/urlsession/fixtures/jsonObj-multiline.swift new file mode 100644 index 000000000..9d52037e9 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/jsonObj-multiline.swift @@ -0,0 +1,15 @@ +import Foundation + +let parameters = ["foo": "bar"] as [String : Any?] + +let postData = try JSONSerialization.data(withJSONObject: parameters, options: []) + +let url = URL(string: "https://httpbin.org/anything")! +var request = URLRequest(url: url) +request.httpMethod = "POST" +request.timeoutInterval = 10 +request.allHTTPHeaderFields = ["content-type": "application/json"] +request.httpBody = postData + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/jsonObj-null-value.swift b/src/targets/swift/urlsession/fixtures/jsonObj-null-value.swift new file mode 100644 index 000000000..05c778801 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/jsonObj-null-value.swift @@ -0,0 +1,15 @@ +import Foundation + +let parameters = ["foo": nil] as [String : Any?] + +let postData = try JSONSerialization.data(withJSONObject: parameters, options: []) + +let url = URL(string: "https://httpbin.org/anything")! +var request = URLRequest(url: url) +request.httpMethod = "POST" +request.timeoutInterval = 10 +request.allHTTPHeaderFields = ["content-type": "application/json"] +request.httpBody = postData + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/multipart-data.swift b/src/targets/swift/urlsession/fixtures/multipart-data.swift new file mode 100644 index 000000000..caa96a7ea --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/multipart-data.swift @@ -0,0 +1,44 @@ +import Foundation + +let parameters = [ + [ + "name": "foo", + "value": "Hello World", + "fileName": "src/fixtures/files/hello.txt", + "contentType": "text/plain" + ], + [ + "name": "bar", + "value": "Bonjour le monde" + ] +] + +let boundary = "---011000010111000001101001" + +var body = "" +for param in parameters { + let paramName = param["name"]! + body += "--\(boundary)\r\n" + body += "Content-Disposition:form-data; name=\"\(paramName)\"" + if let filename = param["fileName"] { + let contentType = param["contentType"]! + let fileContent = try String(contentsOfFile: filename, encoding: .utf8) + body += "; filename=\"\(filename)\"\r\n" + body += "Content-Type: \(contentType)\r\n\r\n" + body += fileContent + } else if let paramValue = param["value"] { + body += "\r\n\r\n\(paramValue)" + } +} + +let postData = Data(body.utf8) + +let url = URL(string: "https://httpbin.org/anything")! +var request = URLRequest(url: url) +request.httpMethod = "POST" +request.timeoutInterval = 10 +request.allHTTPHeaderFields = ["content-type": "multipart/form-data; boundary=---011000010111000001101001"] +request.httpBody = postData + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/multipart-file.swift b/src/targets/swift/urlsession/fixtures/multipart-file.swift new file mode 100644 index 000000000..56ad78d56 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/multipart-file.swift @@ -0,0 +1,39 @@ +import Foundation + +let parameters = [ + [ + "name": "foo", + "fileName": "src/fixtures/files/hello.txt", + "contentType": "text/plain" + ] +] + +let boundary = "---011000010111000001101001" + +var body = "" +for param in parameters { + let paramName = param["name"]! + body += "--\(boundary)\r\n" + body += "Content-Disposition:form-data; name=\"\(paramName)\"" + if let filename = param["fileName"] { + let contentType = param["contentType"]! + let fileContent = try String(contentsOfFile: filename, encoding: .utf8) + body += "; filename=\"\(filename)\"\r\n" + body += "Content-Type: \(contentType)\r\n\r\n" + body += fileContent + } else if let paramValue = param["value"] { + body += "\r\n\r\n\(paramValue)" + } +} + +let postData = Data(body.utf8) + +let url = URL(string: "https://httpbin.org/anything")! +var request = URLRequest(url: url) +request.httpMethod = "POST" +request.timeoutInterval = 10 +request.allHTTPHeaderFields = ["content-type": "multipart/form-data; boundary=---011000010111000001101001"] +request.httpBody = postData + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/multipart-form-data-no-params.swift b/src/targets/swift/urlsession/fixtures/multipart-form-data-no-params.swift new file mode 100644 index 000000000..5b0f3e986 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/multipart-form-data-no-params.swift @@ -0,0 +1,10 @@ +import Foundation + +let url = URL(string: "https://httpbin.org/anything")! +var request = URLRequest(url: url) +request.httpMethod = "POST" +request.timeoutInterval = 10 +request.allHTTPHeaderFields = ["Content-Type": "multipart/form-data"] + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/multipart-form-data.swift b/src/targets/swift/urlsession/fixtures/multipart-form-data.swift new file mode 100644 index 000000000..c31e98f87 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/multipart-form-data.swift @@ -0,0 +1,38 @@ +import Foundation + +let parameters = [ + [ + "name": "foo", + "value": "bar" + ] +] + +let boundary = "---011000010111000001101001" + +var body = "" +for param in parameters { + let paramName = param["name"]! + body += "--\(boundary)\r\n" + body += "Content-Disposition:form-data; name=\"\(paramName)\"" + if let filename = param["fileName"] { + let contentType = param["contentType"]! + let fileContent = try String(contentsOfFile: filename, encoding: .utf8) + body += "; filename=\"\(filename)\"\r\n" + body += "Content-Type: \(contentType)\r\n\r\n" + body += fileContent + } else if let paramValue = param["value"] { + body += "\r\n\r\n\(paramValue)" + } +} + +let postData = Data(body.utf8) + +let url = URL(string: "https://httpbin.org/anything")! +var request = URLRequest(url: url) +request.httpMethod = "POST" +request.timeoutInterval = 10 +request.allHTTPHeaderFields = ["Content-Type": "multipart/form-data; boundary=---011000010111000001101001"] +request.httpBody = postData + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/nested.swift b/src/targets/swift/urlsession/fixtures/nested.swift new file mode 100644 index 000000000..ead43cc60 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/nested.swift @@ -0,0 +1,17 @@ +import Foundation + +let url = URL(string: "https://httpbin.org/anything")! +var components = URLComponents(url: url, resolvingAgainstBaseURL: true)! +let queryItems: [URLQueryItem] = [ + URLQueryItem(name: "foo[bar]", value: "baz,zap"), + URLQueryItem(name: "fiz", value: "buz"), + URLQueryItem(name: "key", value: "value"), +] +components.queryItems = components.queryItems.map { $0 + queryItems } ?? queryItems + +var request = URLRequest(url: components.url!) +request.httpMethod = "GET" +request.timeoutInterval = 10 + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/postdata-malformed.swift b/src/targets/swift/urlsession/fixtures/postdata-malformed.swift new file mode 100644 index 000000000..70f169a07 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/postdata-malformed.swift @@ -0,0 +1,10 @@ +import Foundation + +let url = URL(string: "https://httpbin.org/anything")! +var request = URLRequest(url: url) +request.httpMethod = "POST" +request.timeoutInterval = 10 +request.allHTTPHeaderFields = ["content-type": "application/json"] + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/pretty-option.swift b/src/targets/swift/urlsession/fixtures/pretty-option.swift new file mode 100644 index 000000000..5af163617 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/pretty-option.swift @@ -0,0 +1,24 @@ +import Foundation + +let parameters = ["foo": "bar"] +let joinedParameters = parameters.map { "\($0.key)=\($0.value)" }.joined(separator: "&") +let postData = Data(joinedParameters.utf8) + +let url = URL(string: "https://httpbin.org/anything?key=value")! +var components = URLComponents(url: url, resolvingAgainstBaseURL: true)! +let queryItems: [URLQueryItem] = [ + URLQueryItem(name: "foo", value: "bar"), + URLQueryItem(name: "foo", value: "baz"), + URLQueryItem(name: "baz", value: "abc"), + URLQueryItem(name: "key", value: "value"), +] +components.queryItems = components.queryItems.map { $0 + queryItems } ?? queryItems + +var request = URLRequest(url: components.url!) +request.httpMethod = "POST" +request.timeoutInterval = 10 +request.allHTTPHeaderFields = ["cookie": "foo=bar; bar=baz", "accept": "application/json", "content-type": "application/x-www-form-urlencoded"] +request.httpBody = postData + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/query-encoded.swift b/src/targets/swift/urlsession/fixtures/query-encoded.swift new file mode 100644 index 000000000..9c62da4e5 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/query-encoded.swift @@ -0,0 +1,16 @@ +import Foundation + +let url = URL(string: "https://httpbin.org/anything")! +var components = URLComponents(url: url, resolvingAgainstBaseURL: true)! +let queryItems: [URLQueryItem] = [ + URLQueryItem(name: "startTime", value: "2019-06-13T19%3A08%3A25.455Z"), + URLQueryItem(name: "endTime", value: "2015-09-15T14%3A00%3A12-04%3A00"), +] +components.queryItems = components.queryItems.map { $0 + queryItems } ?? queryItems + +var request = URLRequest(url: components.url!) +request.httpMethod = "GET" +request.timeoutInterval = 10 + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/query.swift b/src/targets/swift/urlsession/fixtures/query.swift new file mode 100644 index 000000000..66cb4c12f --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/query.swift @@ -0,0 +1,18 @@ +import Foundation + +let url = URL(string: "https://httpbin.org/anything?key=value")! +var components = URLComponents(url: url, resolvingAgainstBaseURL: true)! +let queryItems: [URLQueryItem] = [ + URLQueryItem(name: "foo", value: "bar"), + URLQueryItem(name: "foo", value: "baz"), + URLQueryItem(name: "baz", value: "abc"), + URLQueryItem(name: "key", value: "value"), +] +components.queryItems = components.queryItems.map { $0 + queryItems } ?? queryItems + +var request = URLRequest(url: components.url!) +request.httpMethod = "GET" +request.timeoutInterval = 10 + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/short.swift b/src/targets/swift/urlsession/fixtures/short.swift new file mode 100644 index 000000000..3a536dee1 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/short.swift @@ -0,0 +1,9 @@ +import Foundation + +let url = URL(string: "https://httpbin.org/anything")! +var request = URLRequest(url: url) +request.httpMethod = "GET" +request.timeoutInterval = 10 + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/text-plain.swift b/src/targets/swift/urlsession/fixtures/text-plain.swift new file mode 100644 index 000000000..9fb8c0d67 --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/text-plain.swift @@ -0,0 +1,13 @@ +import Foundation + +let postData = Data("Hello World".utf8) + +let url = URL(string: "https://httpbin.org/anything")! +var request = URLRequest(url: url) +request.httpMethod = "POST" +request.timeoutInterval = 10 +request.allHTTPHeaderFields = ["content-type": "text/plain"] +request.httpBody = postData + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/src/targets/swift/urlsession/fixtures/timeout-option.swift b/src/targets/swift/urlsession/fixtures/timeout-option.swift new file mode 100644 index 000000000..0ed67b65c --- /dev/null +++ b/src/targets/swift/urlsession/fixtures/timeout-option.swift @@ -0,0 +1,9 @@ +import Foundation + +let url = URL(string: "https://httpbin.org/anything")! +var request = URLRequest(url: url) +request.httpMethod = "GET" +request.timeoutInterval = 5 + +let (data, _) = try await URLSession.shared.data(for: request) +print(String(decoding: data, as: UTF8.self)) \ No newline at end of file diff --git a/test/fixtures/available-targets.json b/test/fixtures/available-targets.json deleted file mode 100644 index effe17ef6..000000000 --- a/test/fixtures/available-targets.json +++ /dev/null @@ -1,252 +0,0 @@ -[ - { - "key": "shell", - "title": "Shell", - "extname": ".sh", - "default": "curl", - "clients": [ - { - "key": "curl", - "title": "cURL", - "link": "http://curl.haxx.se/", - "description": "cURL is a command line tool and library for transferring data with URL syntax" - }, - { - "key": "httpie", - "title": "HTTPie", - "link": "http://httpie.org/", - "description": "a CLI, cURL-like tool for humans" - }, - { - "key": "wget", - "title": "Wget", - "link": "https://www.gnu.org/software/wget/", - "description": "a free software package for retrieving files using HTTP, HTTPS" - } - ] - }, - { - "key": "node", - "title": "Node.js", - "extname": ".js", - "default": "native", - "clients": [ - { - "key": "native", - "title": "HTTP", - "link": "http://nodejs.org/api/http.html#http_http_request_options_callback", - "description": "Node.js native HTTP interface" - }, - { - "key": "request", - "title": "Request", - "link": "https://github.com/request/request", - "description": "Simplified HTTP request client" - }, - { - "key": "unirest", - "title": "Unirest", - "link": "http://unirest.io/nodejs.html", - "description": "Lightweight HTTP Request Client Library" - } - ] - }, - { - "key": "javascript", - "title": "JavaScript", - "extname": ".js", - "default": "xhr", - "clients": [ - { - "key": "jquery", - "title": "jQuery", - "link": "http://api.jquery.com/jquery.ajax/", - "description": "Perform an asynchronous HTTP (Ajax) requests with jQuery" - }, - { - "key": "xhr", - "title": "XMLHttpRequest", - "link": "https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest", - "description": "W3C Standard API that provides scripted client functionality" - } - ] - }, - { - "key": "ocaml", - "title": "OCaml", - "extname": ".ml", - "default": "cohttp", - "clients": [ - { - "key": "cohttp", - "title": "CoHTTP", - "link": "https://github.com/mirage/ocaml-cohttp", - "description": "Cohttp is a very lightweight HTTP server using Lwt or Async for OCaml" - } - ] - }, - { - "key": "php", - "title": "PHP", - "extname": ".php", - "default": "curl", - "clients": [ - { - "key": "curl", - "title": "cURL", - "link": "http://php.net/manual/en/book.curl.php", - "description": "PHP with ext-curl" - }, - { - "key": "http1", - "title": "HTTP v1", - "link": "http://php.net/manual/en/book.http.php", - "description": "PHP with pecl/http v1" - }, - { - "key": "http2", - "title": "HTTP v2", - "link": "http://devel-m6w6.rhcloud.com/mdref/http", - "description": "PHP with pecl/http v2" - } - ] - }, - { - "key": "python", - "title": "Python", - "extname": ".py", - "default": "python3", - "clients": [ - { - "key": "python3", - "title": "http.client", - "link": "https://docs.python.org/3/library/http.client.html", - "description": "Python3 HTTP Client" - }, - { - "key": "requests", - "title": "Requests", - "link": "http://docs.python-requests.org/en/latest/api/#requests.request", - "description": "Requests HTTP library" - } - ] - }, - { - "key": "objc", - "title": "Objective-C", - "extname": ".m", - "default": "nsurlsession", - "clients": [ - { - "key": "nsurlsession", - "title": "NSURLSession", - "link": "https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/index.html", - "description": "Foundation's NSURLSession request" - } - ] - }, - { - "key": "swift", - "title": "Swift", - "extname": ".swift", - "default": "nsurlsession", - "clients": [ - { - "key": "nsurlsession", - "title": "NSURLSession", - "link": "https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/index.html", - "description": "Foundation's NSURLSession request" - } - ] - }, - { - "key": "go", - "title": "Go", - "extname": ".go", - "default": "native", - "clients": [ - { - "key": "native", - "title": "NewRequest", - "link": "http://golang.org/pkg/net/http/#NewRequest", - "description": "Golang HTTP client request" - } - ] - }, - { - "key": "java", - "title": "Java", - "extname": ".java", - "default": "unirest", - "clients": [ - { - "key": "okhttp", - "title": "OkHttp", - "link": "http://square.github.io/okhttp/", - "description": "An HTTP Request Client Library" - }, - { - "key": "unirest", - "title": "Unirest", - "link": "http://unirest.io/java.html", - "description": "Lightweight HTTP Request Client Library" - } - ] - }, - { - "key": "ruby", - "title": "Ruby", - "extname": ".rb", - "default": "native", - "clients": [ - { - "key": "native", - "title": "net::http", - "link": "http://ruby-doc.org/stdlib-2.2.1/libdoc/net/http/rdoc/Net/HTTP.html", - "description": "Ruby HTTP client" - } - ] - }, - { - "key": "csharp", - "title": "C#", - "extname": ".cs", - "default": "restsharp", - "clients": [ - { - "key": "restsharp", - "title": "RestSharp", - "link": "http://restsharp.org/", - "description": "Simple REST and HTTP API Client for .NET" - } - ] - }, - { - "key": "clojure", - "title": "Clojure", - "extname": ".clj", - "default": "clj_http", - "clients": [ - { - "key": "clj_http", - "title": "clj-http", - "link": "https://github.com/dakrone/clj-http", - "description": "An idiomatic clojure http client wrapping the apache client." - } - ] - }, - { - "key": "c", - "title": "C", - "extname": ".c", - "default": "libcurl", - "clients": [ - { - "key": "libcurl", - "title": "Libcurl", - "link": "http://curl.haxx.se/libcurl/", - "description": "Simple REST and HTTP API Client for C" - } - ] - } -] diff --git a/test/fixtures/cli.json b/test/fixtures/cli.json deleted file mode 100644 index 70cbcd19c..000000000 --- a/test/fixtures/cli.json +++ /dev/null @@ -1,25 +0,0 @@ -[ - { - "run": "node %s", - "target":"node", - "clients": [ - "native" - ] - }, - - { - "run": "php %s", - "target": "php", - "clients": [ - "curl" - ] - }, - - { - "run": "python3 %s", - "target": "python", - "clients": [ - "python3" - ] - } -] diff --git a/test/fixtures/curl/http1.json b/test/fixtures/curl/http1.json deleted file mode 100644 index db0c3d8ce..000000000 --- a/test/fixtures/curl/http1.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "method": "GET", - "url": "http://mockbin.com/request", - "httpVersion": "HTTP/1.0" -} diff --git a/test/fixtures/curl/index.js b/test/fixtures/curl/index.js deleted file mode 100644 index 0d8e0250c..000000000 --- a/test/fixtures/curl/index.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('require-directory')(module); diff --git a/test/fixtures/har.json b/test/fixtures/har.json deleted file mode 100644 index a48c0715a..000000000 --- a/test/fixtures/har.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "log": { - "version": "1.2", - "creator": { - "name": "HTTPSnippet", - "version": "1.0.0" - }, - "entries": [ - { - "request": { - "method": "GET", - "url": "http://mockbin.com/har" - } - }, - { - "request": { - "method": "POST", - "url": "http://mockbin.com/har" - } - } - ] - } -} diff --git a/test/fixtures/index.js b/test/fixtures/index.js deleted file mode 100644 index da75cf83d..000000000 --- a/test/fixtures/index.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict' - -module.exports = require('require-directory')(module, {exclude: /output/}) diff --git a/test/fixtures/mimetypes.json b/test/fixtures/mimetypes.json deleted file mode 100644 index eb292c8d2..000000000 --- a/test/fixtures/mimetypes.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "multipart/mixed": { - "method": "POST", - "url": "http://mockbin.com/har", - "postData": { - "mimeType": "multipart/mixed" - } - }, - - "multipart/related": { - "method": "POST", - "url": "http://mockbin.com/har", - "postData": { - "mimeType": "multipart/related" - } - }, - - "multipart/form-data": { - "method": "POST", - "url": "http://mockbin.com/har", - "postData": { - "mimeType": "multipart/form-data" - } - }, - - "multipart/alternative": { - "method": "POST", - "url": "http://mockbin.com/har", - "postData": { - "mimeType": "multipart/alternative" - } - }, - - "application/x-www-form-urlencoded": { - "method": "POST", - "url": "http://mockbin.com/har", - "postData": { - "mimeType": "application/x-www-form-urlencoded" - } - }, - - "text/json": { - "method": "POST", - "url": "http://mockbin.com/har", - "postData": { - "mimeType": "text/json" - } - }, - - "text/x-json": { - "method": "POST", - "url": "http://mockbin.com/har", - "postData": { - "mimeType": "text/x-json" - } - }, - - "application/x-json": { - "method": "POST", - "url": "http://mockbin.com/har", - "postData": { - "mimeType": "application/x-json" - } - }, - - "invalid-json": { - "method": "POST", - "url": "http://mockbin.com/har", - "postData": { - "mimeType": "application/json", - "text": "foo/bar" - } - } -} diff --git a/test/fixtures/output/c/libcurl/application-form-encoded.c b/test/fixtures/output/c/libcurl/application-form-encoded.c deleted file mode 100644 index bf14b1134..000000000 --- a/test/fixtures/output/c/libcurl/application-form-encoded.c +++ /dev/null @@ -1,12 +0,0 @@ -CURL *hnd = curl_easy_init(); - -curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); -curl_easy_setopt(hnd, CURLOPT_URL, "http://mockbin.com/har"); - -struct curl_slist *headers = NULL; -headers = curl_slist_append(headers, "content-type: application/x-www-form-urlencoded"); -curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); - -curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "foo=bar&hello=world"); - -CURLcode ret = curl_easy_perform(hnd); diff --git a/test/fixtures/output/c/libcurl/application-json.c b/test/fixtures/output/c/libcurl/application-json.c deleted file mode 100644 index e1318a578..000000000 --- a/test/fixtures/output/c/libcurl/application-json.c +++ /dev/null @@ -1,12 +0,0 @@ -CURL *hnd = curl_easy_init(); - -curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); -curl_easy_setopt(hnd, CURLOPT_URL, "http://mockbin.com/har"); - -struct curl_slist *headers = NULL; -headers = curl_slist_append(headers, "content-type: application/json"); -curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); - -curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":{}}],\"boolean\":false}"); - -CURLcode ret = curl_easy_perform(hnd); diff --git a/test/fixtures/output/c/libcurl/cookies.c b/test/fixtures/output/c/libcurl/cookies.c deleted file mode 100644 index 92fa7053d..000000000 --- a/test/fixtures/output/c/libcurl/cookies.c +++ /dev/null @@ -1,8 +0,0 @@ -CURL *hnd = curl_easy_init(); - -curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); -curl_easy_setopt(hnd, CURLOPT_URL, "http://mockbin.com/har"); - -curl_easy_setopt(hnd, CURLOPT_COOKIE, "foo=bar; bar=baz"); - -CURLcode ret = curl_easy_perform(hnd); diff --git a/test/fixtures/output/c/libcurl/custom-method.c b/test/fixtures/output/c/libcurl/custom-method.c deleted file mode 100644 index 12045a0b3..000000000 --- a/test/fixtures/output/c/libcurl/custom-method.c +++ /dev/null @@ -1,6 +0,0 @@ -CURL *hnd = curl_easy_init(); - -curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "PROPFIND"); -curl_easy_setopt(hnd, CURLOPT_URL, "http://mockbin.com/har"); - -CURLcode ret = curl_easy_perform(hnd); diff --git a/test/fixtures/output/c/libcurl/full.c b/test/fixtures/output/c/libcurl/full.c deleted file mode 100644 index 4b47fb2d5..000000000 --- a/test/fixtures/output/c/libcurl/full.c +++ /dev/null @@ -1,15 +0,0 @@ -CURL *hnd = curl_easy_init(); - -curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); -curl_easy_setopt(hnd, CURLOPT_URL, "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"); - -struct curl_slist *headers = NULL; -headers = curl_slist_append(headers, "content-type: application/x-www-form-urlencoded"); -headers = curl_slist_append(headers, "accept: application/json"); -curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); - -curl_easy_setopt(hnd, CURLOPT_COOKIE, "foo=bar; bar=baz"); - -curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "foo=bar"); - -CURLcode ret = curl_easy_perform(hnd); diff --git a/test/fixtures/output/c/libcurl/headers.c b/test/fixtures/output/c/libcurl/headers.c deleted file mode 100644 index 3ae9a1299..000000000 --- a/test/fixtures/output/c/libcurl/headers.c +++ /dev/null @@ -1,11 +0,0 @@ -CURL *hnd = curl_easy_init(); - -curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET"); -curl_easy_setopt(hnd, CURLOPT_URL, "http://mockbin.com/har"); - -struct curl_slist *headers = NULL; -headers = curl_slist_append(headers, "x-foo: Bar"); -headers = curl_slist_append(headers, "accept: application/json"); -curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); - -CURLcode ret = curl_easy_perform(hnd); diff --git a/test/fixtures/output/c/libcurl/https.c b/test/fixtures/output/c/libcurl/https.c deleted file mode 100644 index d5e403be3..000000000 --- a/test/fixtures/output/c/libcurl/https.c +++ /dev/null @@ -1,6 +0,0 @@ -CURL *hnd = curl_easy_init(); - -curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET"); -curl_easy_setopt(hnd, CURLOPT_URL, "https://mockbin.com/har"); - -CURLcode ret = curl_easy_perform(hnd); diff --git a/test/fixtures/output/c/libcurl/jsonObj-null-value.c b/test/fixtures/output/c/libcurl/jsonObj-null-value.c deleted file mode 100644 index 0f66eb801..000000000 --- a/test/fixtures/output/c/libcurl/jsonObj-null-value.c +++ /dev/null @@ -1,12 +0,0 @@ -CURL *hnd = curl_easy_init(); - -curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); -curl_easy_setopt(hnd, CURLOPT_URL, "http://mockbin.com/har"); - -struct curl_slist *headers = NULL; -headers = curl_slist_append(headers, "content-type: application/json"); -curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); - -curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "{\"foo\":null}"); - -CURLcode ret = curl_easy_perform(hnd); diff --git a/test/fixtures/output/c/libcurl/multipart-data.c b/test/fixtures/output/c/libcurl/multipart-data.c deleted file mode 100644 index 80cccdb02..000000000 --- a/test/fixtures/output/c/libcurl/multipart-data.c +++ /dev/null @@ -1,12 +0,0 @@ -CURL *hnd = curl_easy_init(); - -curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); -curl_easy_setopt(hnd, CURLOPT_URL, "http://mockbin.com/har"); - -struct curl_slist *headers = NULL; -headers = curl_slist_append(headers, "content-type: multipart/form-data; boundary=---011000010111000001101001"); -curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); - -curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001--\r\n"); - -CURLcode ret = curl_easy_perform(hnd); diff --git a/test/fixtures/output/c/libcurl/multipart-file.c b/test/fixtures/output/c/libcurl/multipart-file.c deleted file mode 100644 index 90e125278..000000000 --- a/test/fixtures/output/c/libcurl/multipart-file.c +++ /dev/null @@ -1,12 +0,0 @@ -CURL *hnd = curl_easy_init(); - -curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); -curl_easy_setopt(hnd, CURLOPT_URL, "http://mockbin.com/har"); - -struct curl_slist *headers = NULL; -headers = curl_slist_append(headers, "content-type: multipart/form-data; boundary=---011000010111000001101001"); -curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); - -curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--\r\n"); - -CURLcode ret = curl_easy_perform(hnd); diff --git a/test/fixtures/output/c/libcurl/multipart-form-data.c b/test/fixtures/output/c/libcurl/multipart-form-data.c deleted file mode 100644 index 232a092fc..000000000 --- a/test/fixtures/output/c/libcurl/multipart-form-data.c +++ /dev/null @@ -1,12 +0,0 @@ -CURL *hnd = curl_easy_init(); - -curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); -curl_easy_setopt(hnd, CURLOPT_URL, "http://mockbin.com/har"); - -struct curl_slist *headers = NULL; -headers = curl_slist_append(headers, "content-type: multipart/form-data; boundary=---011000010111000001101001"); -curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); - -curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--\r\n"); - -CURLcode ret = curl_easy_perform(hnd); diff --git a/test/fixtures/output/c/libcurl/query.c b/test/fixtures/output/c/libcurl/query.c deleted file mode 100644 index 709188c90..000000000 --- a/test/fixtures/output/c/libcurl/query.c +++ /dev/null @@ -1,6 +0,0 @@ -CURL *hnd = curl_easy_init(); - -curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET"); -curl_easy_setopt(hnd, CURLOPT_URL, "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"); - -CURLcode ret = curl_easy_perform(hnd); diff --git a/test/fixtures/output/c/libcurl/short.c b/test/fixtures/output/c/libcurl/short.c deleted file mode 100644 index c858ae76d..000000000 --- a/test/fixtures/output/c/libcurl/short.c +++ /dev/null @@ -1,6 +0,0 @@ -CURL *hnd = curl_easy_init(); - -curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET"); -curl_easy_setopt(hnd, CURLOPT_URL, "http://mockbin.com/har"); - -CURLcode ret = curl_easy_perform(hnd); diff --git a/test/fixtures/output/c/libcurl/text-plain.c b/test/fixtures/output/c/libcurl/text-plain.c deleted file mode 100644 index 5d8b1fd22..000000000 --- a/test/fixtures/output/c/libcurl/text-plain.c +++ /dev/null @@ -1,12 +0,0 @@ -CURL *hnd = curl_easy_init(); - -curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST"); -curl_easy_setopt(hnd, CURLOPT_URL, "http://mockbin.com/har"); - -struct curl_slist *headers = NULL; -headers = curl_slist_append(headers, "content-type: text/plain"); -curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers); - -curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "Hello World"); - -CURLcode ret = curl_easy_perform(hnd); diff --git a/test/fixtures/output/clojure/clj_http/application-form-encoded.clj b/test/fixtures/output/clojure/clj_http/application-form-encoded.clj deleted file mode 100644 index 5abefec9a..000000000 --- a/test/fixtures/output/clojure/clj_http/application-form-encoded.clj +++ /dev/null @@ -1,4 +0,0 @@ -(require '[clj-http.client :as client]) - -(client/post "http://mockbin.com/har" {:form-params {:foo "bar" - :hello "world"}}) diff --git a/test/fixtures/output/clojure/clj_http/application-json.clj b/test/fixtures/output/clojure/clj_http/application-json.clj deleted file mode 100644 index d2eeaa38c..000000000 --- a/test/fixtures/output/clojure/clj_http/application-json.clj +++ /dev/null @@ -1,9 +0,0 @@ -(require '[clj-http.client :as client]) - -(client/post "http://mockbin.com/har" {:content-type :json - :form-params {:number 1 - :string "f\"oo" - :arr [1 2 3] - :nested {:a "b"} - :arr_mix [1 "a" {:arr_mix_nested {}}] - :boolean false}}) diff --git a/test/fixtures/output/clojure/clj_http/cookies.clj b/test/fixtures/output/clojure/clj_http/cookies.clj deleted file mode 100644 index eaea2a4ea..000000000 --- a/test/fixtures/output/clojure/clj_http/cookies.clj +++ /dev/null @@ -1,3 +0,0 @@ -(require '[clj-http.client :as client]) - -(client/post "http://mockbin.com/har" {:headers {:cookie "foo=bar; bar=baz"}}) diff --git a/test/fixtures/output/clojure/clj_http/custom-method.clj b/test/fixtures/output/clojure/clj_http/custom-method.clj deleted file mode 100644 index 5e5237a54..000000000 --- a/test/fixtures/output/clojure/clj_http/custom-method.clj +++ /dev/null @@ -1 +0,0 @@ -Method not supported diff --git a/test/fixtures/output/clojure/clj_http/full.clj b/test/fixtures/output/clojure/clj_http/full.clj deleted file mode 100644 index e4282c83d..000000000 --- a/test/fixtures/output/clojure/clj_http/full.clj +++ /dev/null @@ -1,8 +0,0 @@ -(require '[clj-http.client :as client]) - -(client/post "http://mockbin.com/har" {:headers {:cookie "foo=bar; bar=baz"} - :query-params {:foo ["bar" "baz"] - :baz "abc" - :key "value"} - :form-params {:foo "bar"} - :accept :json}) diff --git a/test/fixtures/output/clojure/clj_http/headers.clj b/test/fixtures/output/clojure/clj_http/headers.clj deleted file mode 100644 index d2816fb53..000000000 --- a/test/fixtures/output/clojure/clj_http/headers.clj +++ /dev/null @@ -1,4 +0,0 @@ -(require '[clj-http.client :as client]) - -(client/get "http://mockbin.com/har" {:headers {:x-foo "Bar"} - :accept :json}) diff --git a/test/fixtures/output/clojure/clj_http/https.clj b/test/fixtures/output/clojure/clj_http/https.clj deleted file mode 100644 index f81797cf7..000000000 --- a/test/fixtures/output/clojure/clj_http/https.clj +++ /dev/null @@ -1,3 +0,0 @@ -(require '[clj-http.client :as client]) - -(client/get "https://mockbin.com/har") diff --git a/test/fixtures/output/clojure/clj_http/multipart-data.clj b/test/fixtures/output/clojure/clj_http/multipart-data.clj deleted file mode 100644 index 57c8bdaff..000000000 --- a/test/fixtures/output/clojure/clj_http/multipart-data.clj +++ /dev/null @@ -1,4 +0,0 @@ -(require '[clj-http.client :as client]) - -(client/post "http://mockbin.com/har" {:multipart [{:name "foo" - :content "Hello World"}]}) diff --git a/test/fixtures/output/clojure/clj_http/multipart-file.clj b/test/fixtures/output/clojure/clj_http/multipart-file.clj deleted file mode 100644 index dd97b412c..000000000 --- a/test/fixtures/output/clojure/clj_http/multipart-file.clj +++ /dev/null @@ -1,4 +0,0 @@ -(require '[clj-http.client :as client]) - -(client/post "http://mockbin.com/har" {:multipart [{:name "foo" - :content (clojure.java.io/file "test/fixtures/files/hello.txt")}]}) diff --git a/test/fixtures/output/clojure/clj_http/multipart-form-data.clj b/test/fixtures/output/clojure/clj_http/multipart-form-data.clj deleted file mode 100644 index 2091d2a80..000000000 --- a/test/fixtures/output/clojure/clj_http/multipart-form-data.clj +++ /dev/null @@ -1,4 +0,0 @@ -(require '[clj-http.client :as client]) - -(client/post "http://mockbin.com/har" {:multipart [{:name "foo" - :content "bar"}]}) diff --git a/test/fixtures/output/clojure/clj_http/query.clj b/test/fixtures/output/clojure/clj_http/query.clj deleted file mode 100644 index 63f3c2ddc..000000000 --- a/test/fixtures/output/clojure/clj_http/query.clj +++ /dev/null @@ -1,5 +0,0 @@ -(require '[clj-http.client :as client]) - -(client/get "http://mockbin.com/har" {:query-params {:foo ["bar" "baz"] - :baz "abc" - :key "value"}}) diff --git a/test/fixtures/output/clojure/clj_http/short.clj b/test/fixtures/output/clojure/clj_http/short.clj deleted file mode 100644 index b6f67a52c..000000000 --- a/test/fixtures/output/clojure/clj_http/short.clj +++ /dev/null @@ -1,3 +0,0 @@ -(require '[clj-http.client :as client]) - -(client/get "http://mockbin.com/har") diff --git a/test/fixtures/output/clojure/clj_http/text-plain.clj b/test/fixtures/output/clojure/clj_http/text-plain.clj deleted file mode 100644 index 206f5245d..000000000 --- a/test/fixtures/output/clojure/clj_http/text-plain.clj +++ /dev/null @@ -1,3 +0,0 @@ -(require '[clj-http.client :as client]) - -(client/post "http://mockbin.com/har" {:body "Hello World"}) diff --git a/test/fixtures/output/csharp/restsharp/application-form-encoded.cs b/test/fixtures/output/csharp/restsharp/application-form-encoded.cs deleted file mode 100644 index 96f3f8b69..000000000 --- a/test/fixtures/output/csharp/restsharp/application-form-encoded.cs +++ /dev/null @@ -1,5 +0,0 @@ -var client = new RestClient("http://mockbin.com/har"); -var request = new RestRequest(Method.POST); -request.AddHeader("content-type", "application/x-www-form-urlencoded"); -request.AddParameter("application/x-www-form-urlencoded", "foo=bar&hello=world", ParameterType.RequestBody); -IRestResponse response = client.Execute(request); diff --git a/test/fixtures/output/csharp/restsharp/application-json.cs b/test/fixtures/output/csharp/restsharp/application-json.cs deleted file mode 100644 index 30a977be9..000000000 --- a/test/fixtures/output/csharp/restsharp/application-json.cs +++ /dev/null @@ -1,5 +0,0 @@ -var client = new RestClient("http://mockbin.com/har"); -var request = new RestRequest(Method.POST); -request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":{}}],\"boolean\":false}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request); diff --git a/test/fixtures/output/csharp/restsharp/cookies.cs b/test/fixtures/output/csharp/restsharp/cookies.cs deleted file mode 100644 index 910b4f580..000000000 --- a/test/fixtures/output/csharp/restsharp/cookies.cs +++ /dev/null @@ -1,5 +0,0 @@ -var client = new RestClient("http://mockbin.com/har"); -var request = new RestRequest(Method.POST); -request.AddCookie("foo", "bar"); -request.AddCookie("bar", "baz"); -IRestResponse response = client.Execute(request); diff --git a/test/fixtures/output/csharp/restsharp/custom-method.cs b/test/fixtures/output/csharp/restsharp/custom-method.cs deleted file mode 100644 index 5e5237a54..000000000 --- a/test/fixtures/output/csharp/restsharp/custom-method.cs +++ /dev/null @@ -1 +0,0 @@ -Method not supported diff --git a/test/fixtures/output/csharp/restsharp/full.cs b/test/fixtures/output/csharp/restsharp/full.cs deleted file mode 100644 index 6ae958e6c..000000000 --- a/test/fixtures/output/csharp/restsharp/full.cs +++ /dev/null @@ -1,8 +0,0 @@ -var client = new RestClient("http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"); -var request = new RestRequest(Method.POST); -request.AddHeader("content-type", "application/x-www-form-urlencoded"); -request.AddHeader("accept", "application/json"); -request.AddCookie("foo", "bar"); -request.AddCookie("bar", "baz"); -request.AddParameter("application/x-www-form-urlencoded", "foo=bar", ParameterType.RequestBody); -IRestResponse response = client.Execute(request); diff --git a/test/fixtures/output/csharp/restsharp/headers.cs b/test/fixtures/output/csharp/restsharp/headers.cs deleted file mode 100644 index df9ee86f5..000000000 --- a/test/fixtures/output/csharp/restsharp/headers.cs +++ /dev/null @@ -1,5 +0,0 @@ -var client = new RestClient("http://mockbin.com/har"); -var request = new RestRequest(Method.GET); -request.AddHeader("x-foo", "Bar"); -request.AddHeader("accept", "application/json"); -IRestResponse response = client.Execute(request); diff --git a/test/fixtures/output/csharp/restsharp/https.cs b/test/fixtures/output/csharp/restsharp/https.cs deleted file mode 100644 index 8be49d72b..000000000 --- a/test/fixtures/output/csharp/restsharp/https.cs +++ /dev/null @@ -1,3 +0,0 @@ -var client = new RestClient("https://mockbin.com/har"); -var request = new RestRequest(Method.GET); -IRestResponse response = client.Execute(request); diff --git a/test/fixtures/output/csharp/restsharp/jsonObj-null-value.cs b/test/fixtures/output/csharp/restsharp/jsonObj-null-value.cs deleted file mode 100644 index fda921531..000000000 --- a/test/fixtures/output/csharp/restsharp/jsonObj-null-value.cs +++ /dev/null @@ -1,5 +0,0 @@ -var client = new RestClient("http://mockbin.com/har"); -var request = new RestRequest(Method.POST); -request.AddHeader("content-type", "application/json"); -request.AddParameter("application/json", "{\"foo\":null}", ParameterType.RequestBody); -IRestResponse response = client.Execute(request); diff --git a/test/fixtures/output/csharp/restsharp/multipart-data.cs b/test/fixtures/output/csharp/restsharp/multipart-data.cs deleted file mode 100644 index 9db5bec09..000000000 --- a/test/fixtures/output/csharp/restsharp/multipart-data.cs +++ /dev/null @@ -1,5 +0,0 @@ -var client = new RestClient("http://mockbin.com/har"); -var request = new RestRequest(Method.POST); -request.AddHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001"); -request.AddParameter("multipart/form-data; boundary=---011000010111000001101001", "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001--\r\n", ParameterType.RequestBody); -IRestResponse response = client.Execute(request); diff --git a/test/fixtures/output/csharp/restsharp/multipart-file.cs b/test/fixtures/output/csharp/restsharp/multipart-file.cs deleted file mode 100644 index d91e66b4c..000000000 --- a/test/fixtures/output/csharp/restsharp/multipart-file.cs +++ /dev/null @@ -1,5 +0,0 @@ -var client = new RestClient("http://mockbin.com/har"); -var request = new RestRequest(Method.POST); -request.AddHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001"); -request.AddParameter("multipart/form-data; boundary=---011000010111000001101001", "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--\r\n", ParameterType.RequestBody); -IRestResponse response = client.Execute(request); diff --git a/test/fixtures/output/csharp/restsharp/multipart-form-data.cs b/test/fixtures/output/csharp/restsharp/multipart-form-data.cs deleted file mode 100644 index 1ad23e37a..000000000 --- a/test/fixtures/output/csharp/restsharp/multipart-form-data.cs +++ /dev/null @@ -1,5 +0,0 @@ -var client = new RestClient("http://mockbin.com/har"); -var request = new RestRequest(Method.POST); -request.AddHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001"); -request.AddParameter("multipart/form-data; boundary=---011000010111000001101001", "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--\r\n", ParameterType.RequestBody); -IRestResponse response = client.Execute(request); diff --git a/test/fixtures/output/csharp/restsharp/query.cs b/test/fixtures/output/csharp/restsharp/query.cs deleted file mode 100644 index 938453075..000000000 --- a/test/fixtures/output/csharp/restsharp/query.cs +++ /dev/null @@ -1,3 +0,0 @@ -var client = new RestClient("http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"); -var request = new RestRequest(Method.GET); -IRestResponse response = client.Execute(request); diff --git a/test/fixtures/output/csharp/restsharp/short.cs b/test/fixtures/output/csharp/restsharp/short.cs deleted file mode 100644 index eb5c9f510..000000000 --- a/test/fixtures/output/csharp/restsharp/short.cs +++ /dev/null @@ -1,3 +0,0 @@ -var client = new RestClient("http://mockbin.com/har"); -var request = new RestRequest(Method.GET); -IRestResponse response = client.Execute(request); diff --git a/test/fixtures/output/csharp/restsharp/text-plain.cs b/test/fixtures/output/csharp/restsharp/text-plain.cs deleted file mode 100644 index 958eb97d4..000000000 --- a/test/fixtures/output/csharp/restsharp/text-plain.cs +++ /dev/null @@ -1,5 +0,0 @@ -var client = new RestClient("http://mockbin.com/har"); -var request = new RestRequest(Method.POST); -request.AddHeader("content-type", "text/plain"); -request.AddParameter("text/plain", "Hello World", ParameterType.RequestBody); -IRestResponse response = client.Execute(request); diff --git a/test/fixtures/output/go/native/application-json.go b/test/fixtures/output/go/native/application-json.go deleted file mode 100644 index c9dba6a0b..000000000 --- a/test/fixtures/output/go/native/application-json.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - "strings" - "net/http" - "io/ioutil" -) - -func main() { - - url := "http://mockbin.com/har" - - payload := strings.NewReader("{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":{}}],\"boolean\":false}") - - req, _ := http.NewRequest("POST", url, payload) - - req.Header.Add("content-type", "application/json") - - res, _ := http.DefaultClient.Do(req) - - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - - fmt.Println(res) - fmt.Println(string(body)) - -} diff --git a/test/fixtures/output/go/native/cookies.go b/test/fixtures/output/go/native/cookies.go deleted file mode 100644 index cd706384e..000000000 --- a/test/fixtures/output/go/native/cookies.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "fmt" - "net/http" - "io/ioutil" -) - -func main() { - - url := "http://mockbin.com/har" - - req, _ := http.NewRequest("POST", url, nil) - - req.Header.Add("cookie", "foo=bar; bar=baz") - - res, _ := http.DefaultClient.Do(req) - - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - - fmt.Println(res) - fmt.Println(string(body)) - -} diff --git a/test/fixtures/output/go/native/custom-method.go b/test/fixtures/output/go/native/custom-method.go deleted file mode 100644 index 00c86aeb8..000000000 --- a/test/fixtures/output/go/native/custom-method.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - "net/http" - "io/ioutil" -) - -func main() { - - url := "http://mockbin.com/har" - - req, _ := http.NewRequest("PROPFIND", url, nil) - - res, _ := http.DefaultClient.Do(req) - - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - - fmt.Println(res) - fmt.Println(string(body)) - -} diff --git a/test/fixtures/output/go/native/headers.go b/test/fixtures/output/go/native/headers.go deleted file mode 100644 index 0d09039ff..000000000 --- a/test/fixtures/output/go/native/headers.go +++ /dev/null @@ -1,26 +0,0 @@ -package main - -import ( - "fmt" - "net/http" - "io/ioutil" -) - -func main() { - - url := "http://mockbin.com/har" - - req, _ := http.NewRequest("GET", url, nil) - - req.Header.Add("accept", "application/json") - req.Header.Add("x-foo", "Bar") - - res, _ := http.DefaultClient.Do(req) - - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - - fmt.Println(res) - fmt.Println(string(body)) - -} diff --git a/test/fixtures/output/go/native/https.go b/test/fixtures/output/go/native/https.go deleted file mode 100644 index 40e77239d..000000000 --- a/test/fixtures/output/go/native/https.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - "net/http" - "io/ioutil" -) - -func main() { - - url := "https://mockbin.com/har" - - req, _ := http.NewRequest("GET", url, nil) - - res, _ := http.DefaultClient.Do(req) - - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - - fmt.Println(res) - fmt.Println(string(body)) - -} diff --git a/test/fixtures/output/go/native/multipart-data.go b/test/fixtures/output/go/native/multipart-data.go deleted file mode 100644 index 3bc875abc..000000000 --- a/test/fixtures/output/go/native/multipart-data.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - "strings" - "net/http" - "io/ioutil" -) - -func main() { - - url := "http://mockbin.com/har" - - payload := strings.NewReader("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001--\r\n") - - req, _ := http.NewRequest("POST", url, payload) - - req.Header.Add("content-type", "multipart/form-data; boundary=---011000010111000001101001") - - res, _ := http.DefaultClient.Do(req) - - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - - fmt.Println(res) - fmt.Println(string(body)) - -} diff --git a/test/fixtures/output/go/native/multipart-file.go b/test/fixtures/output/go/native/multipart-file.go deleted file mode 100644 index 931cd280b..000000000 --- a/test/fixtures/output/go/native/multipart-file.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - "strings" - "net/http" - "io/ioutil" -) - -func main() { - - url := "http://mockbin.com/har" - - payload := strings.NewReader("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--\r\n") - - req, _ := http.NewRequest("POST", url, payload) - - req.Header.Add("content-type", "multipart/form-data; boundary=---011000010111000001101001") - - res, _ := http.DefaultClient.Do(req) - - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - - fmt.Println(res) - fmt.Println(string(body)) - -} diff --git a/test/fixtures/output/go/native/multipart-form-data.go b/test/fixtures/output/go/native/multipart-form-data.go deleted file mode 100644 index d587d473f..000000000 --- a/test/fixtures/output/go/native/multipart-form-data.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - "strings" - "net/http" - "io/ioutil" -) - -func main() { - - url := "http://mockbin.com/har" - - payload := strings.NewReader("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--\r\n") - - req, _ := http.NewRequest("POST", url, payload) - - req.Header.Add("content-type", "multipart/form-data; boundary=---011000010111000001101001") - - res, _ := http.DefaultClient.Do(req) - - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - - fmt.Println(res) - fmt.Println(string(body)) - -} diff --git a/test/fixtures/output/go/native/query.go b/test/fixtures/output/go/native/query.go deleted file mode 100644 index e2e47aca6..000000000 --- a/test/fixtures/output/go/native/query.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - "net/http" - "io/ioutil" -) - -func main() { - - url := "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value" - - req, _ := http.NewRequest("GET", url, nil) - - res, _ := http.DefaultClient.Do(req) - - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - - fmt.Println(res) - fmt.Println(string(body)) - -} diff --git a/test/fixtures/output/go/native/short.go b/test/fixtures/output/go/native/short.go deleted file mode 100644 index 441f2a062..000000000 --- a/test/fixtures/output/go/native/short.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - "net/http" - "io/ioutil" -) - -func main() { - - url := "http://mockbin.com/har" - - req, _ := http.NewRequest("GET", url, nil) - - res, _ := http.DefaultClient.Do(req) - - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - - fmt.Println(res) - fmt.Println(string(body)) - -} diff --git a/test/fixtures/output/go/native/text-plain.go b/test/fixtures/output/go/native/text-plain.go deleted file mode 100644 index ccf1c7a6b..000000000 --- a/test/fixtures/output/go/native/text-plain.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "fmt" - "strings" - "net/http" - "io/ioutil" -) - -func main() { - - url := "http://mockbin.com/har" - - payload := strings.NewReader("Hello World") - - req, _ := http.NewRequest("POST", url, payload) - - req.Header.Add("content-type", "text/plain") - - res, _ := http.DefaultClient.Do(req) - - defer res.Body.Close() - body, _ := ioutil.ReadAll(res.Body) - - fmt.Println(res) - fmt.Println(string(body)) - -} diff --git a/test/fixtures/output/java/okhttp/application-form-encoded.java b/test/fixtures/output/java/okhttp/application-form-encoded.java deleted file mode 100644 index 0521f0074..000000000 --- a/test/fixtures/output/java/okhttp/application-form-encoded.java +++ /dev/null @@ -1,11 +0,0 @@ -OkHttpClient client = new OkHttpClient(); - -MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); -RequestBody body = RequestBody.create(mediaType, "foo=bar&hello=world"); -Request request = new Request.Builder() - .url("http://mockbin.com/har") - .post(body) - .addHeader("content-type", "application/x-www-form-urlencoded") - .build(); - -Response response = client.newCall(request).execute(); diff --git a/test/fixtures/output/java/okhttp/application-json.java b/test/fixtures/output/java/okhttp/application-json.java deleted file mode 100644 index a344381db..000000000 --- a/test/fixtures/output/java/okhttp/application-json.java +++ /dev/null @@ -1,11 +0,0 @@ -OkHttpClient client = new OkHttpClient(); - -MediaType mediaType = MediaType.parse("application/json"); -RequestBody body = RequestBody.create(mediaType, "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":{}}],\"boolean\":false}"); -Request request = new Request.Builder() - .url("http://mockbin.com/har") - .post(body) - .addHeader("content-type", "application/json") - .build(); - -Response response = client.newCall(request).execute(); diff --git a/test/fixtures/output/java/okhttp/cookies.java b/test/fixtures/output/java/okhttp/cookies.java deleted file mode 100644 index 033501272..000000000 --- a/test/fixtures/output/java/okhttp/cookies.java +++ /dev/null @@ -1,9 +0,0 @@ -OkHttpClient client = new OkHttpClient(); - -Request request = new Request.Builder() - .url("http://mockbin.com/har") - .post(null) - .addHeader("cookie", "foo=bar; bar=baz") - .build(); - -Response response = client.newCall(request).execute(); diff --git a/test/fixtures/output/java/okhttp/custom-method.java b/test/fixtures/output/java/okhttp/custom-method.java deleted file mode 100644 index 817d75ff0..000000000 --- a/test/fixtures/output/java/okhttp/custom-method.java +++ /dev/null @@ -1,8 +0,0 @@ -OkHttpClient client = new OkHttpClient(); - -Request request = new Request.Builder() - .url("http://mockbin.com/har") - .method("PROPFIND", null) - .build(); - -Response response = client.newCall(request).execute(); diff --git a/test/fixtures/output/java/okhttp/full.java b/test/fixtures/output/java/okhttp/full.java deleted file mode 100644 index 8b8ee15b5..000000000 --- a/test/fixtures/output/java/okhttp/full.java +++ /dev/null @@ -1,13 +0,0 @@ -OkHttpClient client = new OkHttpClient(); - -MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); -RequestBody body = RequestBody.create(mediaType, "foo=bar"); -Request request = new Request.Builder() - .url("http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value") - .post(body) - .addHeader("cookie", "foo=bar; bar=baz") - .addHeader("accept", "application/json") - .addHeader("content-type", "application/x-www-form-urlencoded") - .build(); - -Response response = client.newCall(request).execute(); diff --git a/test/fixtures/output/java/okhttp/headers.java b/test/fixtures/output/java/okhttp/headers.java deleted file mode 100644 index 081a33adb..000000000 --- a/test/fixtures/output/java/okhttp/headers.java +++ /dev/null @@ -1,10 +0,0 @@ -OkHttpClient client = new OkHttpClient(); - -Request request = new Request.Builder() - .url("http://mockbin.com/har") - .get() - .addHeader("accept", "application/json") - .addHeader("x-foo", "Bar") - .build(); - -Response response = client.newCall(request).execute(); diff --git a/test/fixtures/output/java/okhttp/https.java b/test/fixtures/output/java/okhttp/https.java deleted file mode 100644 index f9be6532f..000000000 --- a/test/fixtures/output/java/okhttp/https.java +++ /dev/null @@ -1,8 +0,0 @@ -OkHttpClient client = new OkHttpClient(); - -Request request = new Request.Builder() - .url("https://mockbin.com/har") - .get() - .build(); - -Response response = client.newCall(request).execute(); diff --git a/test/fixtures/output/java/okhttp/jsonObj-null-value.java b/test/fixtures/output/java/okhttp/jsonObj-null-value.java deleted file mode 100644 index 15b8482a7..000000000 --- a/test/fixtures/output/java/okhttp/jsonObj-null-value.java +++ /dev/null @@ -1,11 +0,0 @@ -OkHttpClient client = new OkHttpClient(); - -MediaType mediaType = MediaType.parse("application/json"); -RequestBody body = RequestBody.create(mediaType, "{\"foo\":null}"); -Request request = new Request.Builder() - .url("http://mockbin.com/har") - .post(body) - .addHeader("content-type", "application/json") - .build(); - -Response response = client.newCall(request).execute(); diff --git a/test/fixtures/output/java/okhttp/multipart-data.java b/test/fixtures/output/java/okhttp/multipart-data.java deleted file mode 100644 index 9ad294f82..000000000 --- a/test/fixtures/output/java/okhttp/multipart-data.java +++ /dev/null @@ -1,11 +0,0 @@ -OkHttpClient client = new OkHttpClient(); - -MediaType mediaType = MediaType.parse("multipart/form-data; boundary=---011000010111000001101001"); -RequestBody body = RequestBody.create(mediaType, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001--\r\n"); -Request request = new Request.Builder() - .url("http://mockbin.com/har") - .post(body) - .addHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001") - .build(); - -Response response = client.newCall(request).execute(); diff --git a/test/fixtures/output/java/okhttp/multipart-file.java b/test/fixtures/output/java/okhttp/multipart-file.java deleted file mode 100644 index 6d771f173..000000000 --- a/test/fixtures/output/java/okhttp/multipart-file.java +++ /dev/null @@ -1,11 +0,0 @@ -OkHttpClient client = new OkHttpClient(); - -MediaType mediaType = MediaType.parse("multipart/form-data; boundary=---011000010111000001101001"); -RequestBody body = RequestBody.create(mediaType, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--\r\n"); -Request request = new Request.Builder() - .url("http://mockbin.com/har") - .post(body) - .addHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001") - .build(); - -Response response = client.newCall(request).execute(); diff --git a/test/fixtures/output/java/okhttp/multipart-form-data.java b/test/fixtures/output/java/okhttp/multipart-form-data.java deleted file mode 100644 index ab1e1d2c4..000000000 --- a/test/fixtures/output/java/okhttp/multipart-form-data.java +++ /dev/null @@ -1,11 +0,0 @@ -OkHttpClient client = new OkHttpClient(); - -MediaType mediaType = MediaType.parse("multipart/form-data; boundary=---011000010111000001101001"); -RequestBody body = RequestBody.create(mediaType, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--\r\n"); -Request request = new Request.Builder() - .url("http://mockbin.com/har") - .post(body) - .addHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001") - .build(); - -Response response = client.newCall(request).execute(); diff --git a/test/fixtures/output/java/okhttp/query.java b/test/fixtures/output/java/okhttp/query.java deleted file mode 100644 index e105dd434..000000000 --- a/test/fixtures/output/java/okhttp/query.java +++ /dev/null @@ -1,8 +0,0 @@ -OkHttpClient client = new OkHttpClient(); - -Request request = new Request.Builder() - .url("http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value") - .get() - .build(); - -Response response = client.newCall(request).execute(); diff --git a/test/fixtures/output/java/okhttp/short.java b/test/fixtures/output/java/okhttp/short.java deleted file mode 100644 index 5bd44ca99..000000000 --- a/test/fixtures/output/java/okhttp/short.java +++ /dev/null @@ -1,8 +0,0 @@ -OkHttpClient client = new OkHttpClient(); - -Request request = new Request.Builder() - .url("http://mockbin.com/har") - .get() - .build(); - -Response response = client.newCall(request).execute(); diff --git a/test/fixtures/output/java/okhttp/text-plain.java b/test/fixtures/output/java/okhttp/text-plain.java deleted file mode 100644 index 5501c9aab..000000000 --- a/test/fixtures/output/java/okhttp/text-plain.java +++ /dev/null @@ -1,11 +0,0 @@ -OkHttpClient client = new OkHttpClient(); - -MediaType mediaType = MediaType.parse("text/plain"); -RequestBody body = RequestBody.create(mediaType, "Hello World"); -Request request = new Request.Builder() - .url("http://mockbin.com/har") - .post(body) - .addHeader("content-type", "text/plain") - .build(); - -Response response = client.newCall(request).execute(); diff --git a/test/fixtures/output/java/unirest/application-form-encoded.java b/test/fixtures/output/java/unirest/application-form-encoded.java deleted file mode 100644 index 81508b841..000000000 --- a/test/fixtures/output/java/unirest/application-form-encoded.java +++ /dev/null @@ -1,4 +0,0 @@ -HttpResponse response = Unirest.post("http://mockbin.com/har") - .header("content-type", "application/x-www-form-urlencoded") - .body("foo=bar&hello=world") - .asString(); diff --git a/test/fixtures/output/java/unirest/application-json.java b/test/fixtures/output/java/unirest/application-json.java deleted file mode 100644 index 1fd5e3227..000000000 --- a/test/fixtures/output/java/unirest/application-json.java +++ /dev/null @@ -1,4 +0,0 @@ -HttpResponse response = Unirest.post("http://mockbin.com/har") - .header("content-type", "application/json") - .body("{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":{}}],\"boolean\":false}") - .asString(); diff --git a/test/fixtures/output/java/unirest/cookies.java b/test/fixtures/output/java/unirest/cookies.java deleted file mode 100644 index ceb408800..000000000 --- a/test/fixtures/output/java/unirest/cookies.java +++ /dev/null @@ -1,3 +0,0 @@ -HttpResponse response = Unirest.post("http://mockbin.com/har") - .header("cookie", "foo=bar; bar=baz") - .asString(); diff --git a/test/fixtures/output/java/unirest/custom-method.java b/test/fixtures/output/java/unirest/custom-method.java deleted file mode 100644 index 6ca6d7f29..000000000 --- a/test/fixtures/output/java/unirest/custom-method.java +++ /dev/null @@ -1,2 +0,0 @@ -HttpResponse response = Unirest.customMethod("PROPFIND","http://mockbin.com/har") - .asString(); diff --git a/test/fixtures/output/java/unirest/full.java b/test/fixtures/output/java/unirest/full.java deleted file mode 100644 index f6014e56c..000000000 --- a/test/fixtures/output/java/unirest/full.java +++ /dev/null @@ -1,6 +0,0 @@ -HttpResponse response = Unirest.post("http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value") - .header("cookie", "foo=bar; bar=baz") - .header("accept", "application/json") - .header("content-type", "application/x-www-form-urlencoded") - .body("foo=bar") - .asString(); diff --git a/test/fixtures/output/java/unirest/headers.java b/test/fixtures/output/java/unirest/headers.java deleted file mode 100644 index 142cf4e75..000000000 --- a/test/fixtures/output/java/unirest/headers.java +++ /dev/null @@ -1,4 +0,0 @@ -HttpResponse response = Unirest.get("http://mockbin.com/har") - .header("accept", "application/json") - .header("x-foo", "Bar") - .asString(); diff --git a/test/fixtures/output/java/unirest/https.java b/test/fixtures/output/java/unirest/https.java deleted file mode 100644 index 6e8269128..000000000 --- a/test/fixtures/output/java/unirest/https.java +++ /dev/null @@ -1,2 +0,0 @@ -HttpResponse response = Unirest.get("https://mockbin.com/har") - .asString(); diff --git a/test/fixtures/output/java/unirest/jsonObj-null-value.java b/test/fixtures/output/java/unirest/jsonObj-null-value.java deleted file mode 100644 index 87a010192..000000000 --- a/test/fixtures/output/java/unirest/jsonObj-null-value.java +++ /dev/null @@ -1,4 +0,0 @@ -HttpResponse response = Unirest.post("http://mockbin.com/har") - .header("content-type", "application/json") - .body("{\"foo\":null}") - .asString(); diff --git a/test/fixtures/output/java/unirest/multipart-data.java b/test/fixtures/output/java/unirest/multipart-data.java deleted file mode 100644 index f5266e32d..000000000 --- a/test/fixtures/output/java/unirest/multipart-data.java +++ /dev/null @@ -1,4 +0,0 @@ -HttpResponse response = Unirest.post("http://mockbin.com/har") - .header("content-type", "multipart/form-data; boundary=---011000010111000001101001") - .body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001--\r\n") - .asString(); diff --git a/test/fixtures/output/java/unirest/multipart-file.java b/test/fixtures/output/java/unirest/multipart-file.java deleted file mode 100644 index 4b9cc83bf..000000000 --- a/test/fixtures/output/java/unirest/multipart-file.java +++ /dev/null @@ -1,4 +0,0 @@ -HttpResponse response = Unirest.post("http://mockbin.com/har") - .header("content-type", "multipart/form-data; boundary=---011000010111000001101001") - .body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--\r\n") - .asString(); diff --git a/test/fixtures/output/java/unirest/multipart-form-data.java b/test/fixtures/output/java/unirest/multipart-form-data.java deleted file mode 100644 index 38ce54749..000000000 --- a/test/fixtures/output/java/unirest/multipart-form-data.java +++ /dev/null @@ -1,4 +0,0 @@ -HttpResponse response = Unirest.post("http://mockbin.com/har") - .header("content-type", "multipart/form-data; boundary=---011000010111000001101001") - .body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--\r\n") - .asString(); diff --git a/test/fixtures/output/java/unirest/query.java b/test/fixtures/output/java/unirest/query.java deleted file mode 100644 index cd3424219..000000000 --- a/test/fixtures/output/java/unirest/query.java +++ /dev/null @@ -1,2 +0,0 @@ -HttpResponse response = Unirest.get("http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value") - .asString(); diff --git a/test/fixtures/output/java/unirest/short.java b/test/fixtures/output/java/unirest/short.java deleted file mode 100644 index 994b244e4..000000000 --- a/test/fixtures/output/java/unirest/short.java +++ /dev/null @@ -1,2 +0,0 @@ -HttpResponse response = Unirest.get("http://mockbin.com/har") - .asString(); diff --git a/test/fixtures/output/java/unirest/text-plain.java b/test/fixtures/output/java/unirest/text-plain.java deleted file mode 100644 index b68fb04d5..000000000 --- a/test/fixtures/output/java/unirest/text-plain.java +++ /dev/null @@ -1,4 +0,0 @@ -HttpResponse response = Unirest.post("http://mockbin.com/har") - .header("content-type", "text/plain") - .body("Hello World") - .asString(); diff --git a/test/fixtures/output/javascript/jquery/application-form-encoded.js b/test/fixtures/output/javascript/jquery/application-form-encoded.js deleted file mode 100644 index dc296cc3e..000000000 --- a/test/fixtures/output/javascript/jquery/application-form-encoded.js +++ /dev/null @@ -1,17 +0,0 @@ -var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "POST", - "headers": { - "content-type": "application/x-www-form-urlencoded" - }, - "data": { - "foo": "bar", - "hello": "world" - } -} - -$.ajax(settings).done(function (response) { - console.log(response); -}); diff --git a/test/fixtures/output/javascript/jquery/application-json.js b/test/fixtures/output/javascript/jquery/application-json.js deleted file mode 100644 index 0b53728b3..000000000 --- a/test/fixtures/output/javascript/jquery/application-json.js +++ /dev/null @@ -1,15 +0,0 @@ -var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "POST", - "headers": { - "content-type": "application/json" - }, - "processData": false, - "data": "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":{}}],\"boolean\":false}" -} - -$.ajax(settings).done(function (response) { - console.log(response); -}); diff --git a/test/fixtures/output/javascript/jquery/cookies.js b/test/fixtures/output/javascript/jquery/cookies.js deleted file mode 100644 index f65a8d048..000000000 --- a/test/fixtures/output/javascript/jquery/cookies.js +++ /dev/null @@ -1,13 +0,0 @@ -var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "POST", - "headers": { - "cookie": "foo=bar; bar=baz" - } -} - -$.ajax(settings).done(function (response) { - console.log(response); -}); diff --git a/test/fixtures/output/javascript/jquery/custom-method.js b/test/fixtures/output/javascript/jquery/custom-method.js deleted file mode 100644 index ba4185299..000000000 --- a/test/fixtures/output/javascript/jquery/custom-method.js +++ /dev/null @@ -1,11 +0,0 @@ -var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "PROPFIND", - "headers": {} -} - -$.ajax(settings).done(function (response) { - console.log(response); -}); diff --git a/test/fixtures/output/javascript/jquery/full.js b/test/fixtures/output/javascript/jquery/full.js deleted file mode 100644 index 50f7cf609..000000000 --- a/test/fixtures/output/javascript/jquery/full.js +++ /dev/null @@ -1,18 +0,0 @@ -var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value", - "method": "POST", - "headers": { - "cookie": "foo=bar; bar=baz", - "accept": "application/json", - "content-type": "application/x-www-form-urlencoded" - }, - "data": { - "foo": "bar" - } -} - -$.ajax(settings).done(function (response) { - console.log(response); -}); diff --git a/test/fixtures/output/javascript/jquery/headers.js b/test/fixtures/output/javascript/jquery/headers.js deleted file mode 100644 index 030e7f6ff..000000000 --- a/test/fixtures/output/javascript/jquery/headers.js +++ /dev/null @@ -1,14 +0,0 @@ -var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "GET", - "headers": { - "accept": "application/json", - "x-foo": "Bar" - } -} - -$.ajax(settings).done(function (response) { - console.log(response); -}); diff --git a/test/fixtures/output/javascript/jquery/https.js b/test/fixtures/output/javascript/jquery/https.js deleted file mode 100644 index 418bfba7f..000000000 --- a/test/fixtures/output/javascript/jquery/https.js +++ /dev/null @@ -1,11 +0,0 @@ -var settings = { - "async": true, - "crossDomain": true, - "url": "https://mockbin.com/har", - "method": "GET", - "headers": {} -} - -$.ajax(settings).done(function (response) { - console.log(response); -}); diff --git a/test/fixtures/output/javascript/jquery/jsonObj-null-value.js b/test/fixtures/output/javascript/jquery/jsonObj-null-value.js deleted file mode 100644 index a8b88b785..000000000 --- a/test/fixtures/output/javascript/jquery/jsonObj-null-value.js +++ /dev/null @@ -1,15 +0,0 @@ -var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "POST", - "headers": { - "content-type": "application/json" - }, - "processData": false, - "data": "{\"foo\":null}" -} - -$.ajax(settings).done(function (response) { - console.log(response); -}); diff --git a/test/fixtures/output/javascript/jquery/multipart-data.js b/test/fixtures/output/javascript/jquery/multipart-data.js deleted file mode 100644 index 8dea93d99..000000000 --- a/test/fixtures/output/javascript/jquery/multipart-data.js +++ /dev/null @@ -1,18 +0,0 @@ -var form = new FormData(); -form.append("foo", "Hello World"); - -var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "POST", - "headers": {}, - "processData": false, - "contentType": false, - "mimeType": "multipart/form-data", - "data": form -} - -$.ajax(settings).done(function (response) { - console.log(response); -}); diff --git a/test/fixtures/output/javascript/jquery/multipart-file.js b/test/fixtures/output/javascript/jquery/multipart-file.js deleted file mode 100644 index 12006dd89..000000000 --- a/test/fixtures/output/javascript/jquery/multipart-file.js +++ /dev/null @@ -1,18 +0,0 @@ -var form = new FormData(); -form.append("foo", "test/fixtures/files/hello.txt"); - -var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "POST", - "headers": {}, - "processData": false, - "contentType": false, - "mimeType": "multipart/form-data", - "data": form -} - -$.ajax(settings).done(function (response) { - console.log(response); -}); diff --git a/test/fixtures/output/javascript/jquery/multipart-form-data.js b/test/fixtures/output/javascript/jquery/multipart-form-data.js deleted file mode 100644 index 584b8d9ec..000000000 --- a/test/fixtures/output/javascript/jquery/multipart-form-data.js +++ /dev/null @@ -1,18 +0,0 @@ -var form = new FormData(); -form.append("foo", "bar"); - -var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "POST", - "headers": {}, - "processData": false, - "contentType": false, - "mimeType": "multipart/form-data", - "data": form -} - -$.ajax(settings).done(function (response) { - console.log(response); -}); diff --git a/test/fixtures/output/javascript/jquery/query.js b/test/fixtures/output/javascript/jquery/query.js deleted file mode 100644 index 15a0663e4..000000000 --- a/test/fixtures/output/javascript/jquery/query.js +++ /dev/null @@ -1,11 +0,0 @@ -var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value", - "method": "GET", - "headers": {} -} - -$.ajax(settings).done(function (response) { - console.log(response); -}); diff --git a/test/fixtures/output/javascript/jquery/short.js b/test/fixtures/output/javascript/jquery/short.js deleted file mode 100644 index 45e3bdd07..000000000 --- a/test/fixtures/output/javascript/jquery/short.js +++ /dev/null @@ -1,11 +0,0 @@ -var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "GET", - "headers": {} -} - -$.ajax(settings).done(function (response) { - console.log(response); -}); diff --git a/test/fixtures/output/javascript/jquery/text-plain.js b/test/fixtures/output/javascript/jquery/text-plain.js deleted file mode 100644 index 58debb2de..000000000 --- a/test/fixtures/output/javascript/jquery/text-plain.js +++ /dev/null @@ -1,14 +0,0 @@ -var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "POST", - "headers": { - "content-type": "text/plain" - }, - "data": "Hello World" -} - -$.ajax(settings).done(function (response) { - console.log(response); -}); diff --git a/test/fixtures/output/javascript/xhr/application-form-encoded.js b/test/fixtures/output/javascript/xhr/application-form-encoded.js deleted file mode 100644 index 90cfc66a6..000000000 --- a/test/fixtures/output/javascript/xhr/application-form-encoded.js +++ /dev/null @@ -1,15 +0,0 @@ -var data = "foo=bar&hello=world"; - -var xhr = new XMLHttpRequest(); -xhr.withCredentials = true; - -xhr.addEventListener("readystatechange", function () { - if (this.readyState === this.DONE) { - console.log(this.responseText); - } -}); - -xhr.open("POST", "http://mockbin.com/har"); -xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded"); - -xhr.send(data); diff --git a/test/fixtures/output/javascript/xhr/application-json.js b/test/fixtures/output/javascript/xhr/application-json.js deleted file mode 100644 index 98508d808..000000000 --- a/test/fixtures/output/javascript/xhr/application-json.js +++ /dev/null @@ -1,34 +0,0 @@ -var data = JSON.stringify({ - "number": 1, - "string": "f\"oo", - "arr": [ - 1, - 2, - 3 - ], - "nested": { - "a": "b" - }, - "arr_mix": [ - 1, - "a", - { - "arr_mix_nested": {} - } - ], - "boolean": false -}); - -var xhr = new XMLHttpRequest(); -xhr.withCredentials = true; - -xhr.addEventListener("readystatechange", function () { - if (this.readyState === this.DONE) { - console.log(this.responseText); - } -}); - -xhr.open("POST", "http://mockbin.com/har"); -xhr.setRequestHeader("content-type", "application/json"); - -xhr.send(data); diff --git a/test/fixtures/output/javascript/xhr/cookies.js b/test/fixtures/output/javascript/xhr/cookies.js deleted file mode 100644 index d110546ea..000000000 --- a/test/fixtures/output/javascript/xhr/cookies.js +++ /dev/null @@ -1,15 +0,0 @@ -var data = null; - -var xhr = new XMLHttpRequest(); -xhr.withCredentials = true; - -xhr.addEventListener("readystatechange", function () { - if (this.readyState === this.DONE) { - console.log(this.responseText); - } -}); - -xhr.open("POST", "http://mockbin.com/har"); -xhr.setRequestHeader("cookie", "foo=bar; bar=baz"); - -xhr.send(data); diff --git a/test/fixtures/output/javascript/xhr/custom-method.js b/test/fixtures/output/javascript/xhr/custom-method.js deleted file mode 100644 index 6da6675c3..000000000 --- a/test/fixtures/output/javascript/xhr/custom-method.js +++ /dev/null @@ -1,14 +0,0 @@ -var data = null; - -var xhr = new XMLHttpRequest(); -xhr.withCredentials = true; - -xhr.addEventListener("readystatechange", function () { - if (this.readyState === this.DONE) { - console.log(this.responseText); - } -}); - -xhr.open("PROPFIND", "http://mockbin.com/har"); - -xhr.send(data); diff --git a/test/fixtures/output/javascript/xhr/full.js b/test/fixtures/output/javascript/xhr/full.js deleted file mode 100644 index 55547738f..000000000 --- a/test/fixtures/output/javascript/xhr/full.js +++ /dev/null @@ -1,17 +0,0 @@ -var data = "foo=bar"; - -var xhr = new XMLHttpRequest(); -xhr.withCredentials = true; - -xhr.addEventListener("readystatechange", function () { - if (this.readyState === this.DONE) { - console.log(this.responseText); - } -}); - -xhr.open("POST", "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"); -xhr.setRequestHeader("cookie", "foo=bar; bar=baz"); -xhr.setRequestHeader("accept", "application/json"); -xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded"); - -xhr.send(data); diff --git a/test/fixtures/output/javascript/xhr/headers.js b/test/fixtures/output/javascript/xhr/headers.js deleted file mode 100644 index 27e9347bc..000000000 --- a/test/fixtures/output/javascript/xhr/headers.js +++ /dev/null @@ -1,16 +0,0 @@ -var data = null; - -var xhr = new XMLHttpRequest(); -xhr.withCredentials = true; - -xhr.addEventListener("readystatechange", function () { - if (this.readyState === this.DONE) { - console.log(this.responseText); - } -}); - -xhr.open("GET", "http://mockbin.com/har"); -xhr.setRequestHeader("accept", "application/json"); -xhr.setRequestHeader("x-foo", "Bar"); - -xhr.send(data); diff --git a/test/fixtures/output/javascript/xhr/https.js b/test/fixtures/output/javascript/xhr/https.js deleted file mode 100644 index 6f2e8f34f..000000000 --- a/test/fixtures/output/javascript/xhr/https.js +++ /dev/null @@ -1,14 +0,0 @@ -var data = null; - -var xhr = new XMLHttpRequest(); -xhr.withCredentials = true; - -xhr.addEventListener("readystatechange", function () { - if (this.readyState === this.DONE) { - console.log(this.responseText); - } -}); - -xhr.open("GET", "https://mockbin.com/har"); - -xhr.send(data); diff --git a/test/fixtures/output/javascript/xhr/jsonObj-null-value.js b/test/fixtures/output/javascript/xhr/jsonObj-null-value.js deleted file mode 100644 index 8105f6446..000000000 --- a/test/fixtures/output/javascript/xhr/jsonObj-null-value.js +++ /dev/null @@ -1,17 +0,0 @@ -var data = JSON.stringify({ - "foo": null -}); - -var xhr = new XMLHttpRequest(); -xhr.withCredentials = true; - -xhr.addEventListener("readystatechange", function () { - if (this.readyState === this.DONE) { - console.log(this.responseText); - } -}); - -xhr.open("POST", "http://mockbin.com/har"); -xhr.setRequestHeader("content-type", "application/json"); - -xhr.send(data); diff --git a/test/fixtures/output/javascript/xhr/multipart-data.js b/test/fixtures/output/javascript/xhr/multipart-data.js deleted file mode 100644 index 2b7f42579..000000000 --- a/test/fixtures/output/javascript/xhr/multipart-data.js +++ /dev/null @@ -1,15 +0,0 @@ -var data = new FormData(); -data.append("foo", "Hello World"); - -var xhr = new XMLHttpRequest(); -xhr.withCredentials = true; - -xhr.addEventListener("readystatechange", function () { - if (this.readyState === this.DONE) { - console.log(this.responseText); - } -}); - -xhr.open("POST", "http://mockbin.com/har"); - -xhr.send(data); diff --git a/test/fixtures/output/javascript/xhr/multipart-file.js b/test/fixtures/output/javascript/xhr/multipart-file.js deleted file mode 100644 index a5326f2a3..000000000 --- a/test/fixtures/output/javascript/xhr/multipart-file.js +++ /dev/null @@ -1,15 +0,0 @@ -var data = new FormData(); -data.append("foo", "test/fixtures/files/hello.txt"); - -var xhr = new XMLHttpRequest(); -xhr.withCredentials = true; - -xhr.addEventListener("readystatechange", function () { - if (this.readyState === this.DONE) { - console.log(this.responseText); - } -}); - -xhr.open("POST", "http://mockbin.com/har"); - -xhr.send(data); diff --git a/test/fixtures/output/javascript/xhr/multipart-form-data.js b/test/fixtures/output/javascript/xhr/multipart-form-data.js deleted file mode 100644 index 574bafff5..000000000 --- a/test/fixtures/output/javascript/xhr/multipart-form-data.js +++ /dev/null @@ -1,15 +0,0 @@ -var data = new FormData(); -data.append("foo", "bar"); - -var xhr = new XMLHttpRequest(); -xhr.withCredentials = true; - -xhr.addEventListener("readystatechange", function () { - if (this.readyState === this.DONE) { - console.log(this.responseText); - } -}); - -xhr.open("POST", "http://mockbin.com/har"); - -xhr.send(data); diff --git a/test/fixtures/output/javascript/xhr/query.js b/test/fixtures/output/javascript/xhr/query.js deleted file mode 100644 index b9cfa0d23..000000000 --- a/test/fixtures/output/javascript/xhr/query.js +++ /dev/null @@ -1,14 +0,0 @@ -var data = null; - -var xhr = new XMLHttpRequest(); -xhr.withCredentials = true; - -xhr.addEventListener("readystatechange", function () { - if (this.readyState === this.DONE) { - console.log(this.responseText); - } -}); - -xhr.open("GET", "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"); - -xhr.send(data); diff --git a/test/fixtures/output/javascript/xhr/short.js b/test/fixtures/output/javascript/xhr/short.js deleted file mode 100644 index af35e7675..000000000 --- a/test/fixtures/output/javascript/xhr/short.js +++ /dev/null @@ -1,14 +0,0 @@ -var data = null; - -var xhr = new XMLHttpRequest(); -xhr.withCredentials = true; - -xhr.addEventListener("readystatechange", function () { - if (this.readyState === this.DONE) { - console.log(this.responseText); - } -}); - -xhr.open("GET", "http://mockbin.com/har"); - -xhr.send(data); diff --git a/test/fixtures/output/javascript/xhr/text-plain.js b/test/fixtures/output/javascript/xhr/text-plain.js deleted file mode 100644 index 6b6ca5171..000000000 --- a/test/fixtures/output/javascript/xhr/text-plain.js +++ /dev/null @@ -1,15 +0,0 @@ -var data = "Hello World"; - -var xhr = new XMLHttpRequest(); -xhr.withCredentials = true; - -xhr.addEventListener("readystatechange", function () { - if (this.readyState === this.DONE) { - console.log(this.responseText); - } -}); - -xhr.open("POST", "http://mockbin.com/har"); -xhr.setRequestHeader("content-type", "text/plain"); - -xhr.send(data); diff --git a/test/fixtures/output/node/native/application-form-encoded.js b/test/fixtures/output/node/native/application-form-encoded.js deleted file mode 100644 index 8989be7cf..000000000 --- a/test/fixtures/output/node/native/application-form-encoded.js +++ /dev/null @@ -1,28 +0,0 @@ -var qs = require("querystring"); -var http = require("http"); - -var options = { - "method": "POST", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": { - "content-type": "application/x-www-form-urlencoded" - } -}; - -var req = http.request(options, function (res) { - var chunks = []; - - res.on("data", function (chunk) { - chunks.push(chunk); - }); - - res.on("end", function () { - var body = Buffer.concat(chunks); - console.log(body.toString()); - }); -}); - -req.write(qs.stringify({ foo: 'bar', hello: 'world' })); -req.end(); diff --git a/test/fixtures/output/node/native/application-json.js b/test/fixtures/output/node/native/application-json.js deleted file mode 100644 index 5d972636d..000000000 --- a/test/fixtures/output/node/native/application-json.js +++ /dev/null @@ -1,32 +0,0 @@ -var http = require("http"); - -var options = { - "method": "POST", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": { - "content-type": "application/json" - } -}; - -var req = http.request(options, function (res) { - var chunks = []; - - res.on("data", function (chunk) { - chunks.push(chunk); - }); - - res.on("end", function () { - var body = Buffer.concat(chunks); - console.log(body.toString()); - }); -}); - -req.write(JSON.stringify({ number: 1, - string: 'f"oo', - arr: [ 1, 2, 3 ], - nested: { a: 'b' }, - arr_mix: [ 1, 'a', { arr_mix_nested: {} } ], - boolean: false })); -req.end(); diff --git a/test/fixtures/output/node/native/cookies.js b/test/fixtures/output/node/native/cookies.js deleted file mode 100644 index 39e75389d..000000000 --- a/test/fixtures/output/node/native/cookies.js +++ /dev/null @@ -1,26 +0,0 @@ -var http = require("http"); - -var options = { - "method": "POST", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": { - "cookie": "foo=bar; bar=baz" - } -}; - -var req = http.request(options, function (res) { - var chunks = []; - - res.on("data", function (chunk) { - chunks.push(chunk); - }); - - res.on("end", function () { - var body = Buffer.concat(chunks); - console.log(body.toString()); - }); -}); - -req.end(); diff --git a/test/fixtures/output/node/native/custom-method.js b/test/fixtures/output/node/native/custom-method.js deleted file mode 100644 index f87f77499..000000000 --- a/test/fixtures/output/node/native/custom-method.js +++ /dev/null @@ -1,24 +0,0 @@ -var http = require("http"); - -var options = { - "method": "PROPFIND", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": {} -}; - -var req = http.request(options, function (res) { - var chunks = []; - - res.on("data", function (chunk) { - chunks.push(chunk); - }); - - res.on("end", function () { - var body = Buffer.concat(chunks); - console.log(body.toString()); - }); -}); - -req.end(); diff --git a/test/fixtures/output/node/native/full.js b/test/fixtures/output/node/native/full.js deleted file mode 100644 index f094004ec..000000000 --- a/test/fixtures/output/node/native/full.js +++ /dev/null @@ -1,30 +0,0 @@ -var qs = require("querystring"); -var http = require("http"); - -var options = { - "method": "POST", - "hostname": "mockbin.com", - "port": null, - "path": "/har?foo=bar&foo=baz&baz=abc&key=value", - "headers": { - "cookie": "foo=bar; bar=baz", - "accept": "application/json", - "content-type": "application/x-www-form-urlencoded" - } -}; - -var req = http.request(options, function (res) { - var chunks = []; - - res.on("data", function (chunk) { - chunks.push(chunk); - }); - - res.on("end", function () { - var body = Buffer.concat(chunks); - console.log(body.toString()); - }); -}); - -req.write(qs.stringify({ foo: 'bar' })); -req.end(); diff --git a/test/fixtures/output/node/native/headers.js b/test/fixtures/output/node/native/headers.js deleted file mode 100644 index 21d094b48..000000000 --- a/test/fixtures/output/node/native/headers.js +++ /dev/null @@ -1,27 +0,0 @@ -var http = require("http"); - -var options = { - "method": "GET", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": { - "accept": "application/json", - "x-foo": "Bar" - } -}; - -var req = http.request(options, function (res) { - var chunks = []; - - res.on("data", function (chunk) { - chunks.push(chunk); - }); - - res.on("end", function () { - var body = Buffer.concat(chunks); - console.log(body.toString()); - }); -}); - -req.end(); diff --git a/test/fixtures/output/node/native/https.js b/test/fixtures/output/node/native/https.js deleted file mode 100644 index 5dd0a44b6..000000000 --- a/test/fixtures/output/node/native/https.js +++ /dev/null @@ -1,24 +0,0 @@ -var http = require("https"); - -var options = { - "method": "GET", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": {} -}; - -var req = http.request(options, function (res) { - var chunks = []; - - res.on("data", function (chunk) { - chunks.push(chunk); - }); - - res.on("end", function () { - var body = Buffer.concat(chunks); - console.log(body.toString()); - }); -}); - -req.end(); diff --git a/test/fixtures/output/node/native/jsonObj-null-value.js b/test/fixtures/output/node/native/jsonObj-null-value.js deleted file mode 100644 index f55d5a8fe..000000000 --- a/test/fixtures/output/node/native/jsonObj-null-value.js +++ /dev/null @@ -1,27 +0,0 @@ -var http = require("http"); - -var options = { - "method": "POST", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": { - "content-type": "application/json" - } -}; - -var req = http.request(options, function (res) { - var chunks = []; - - res.on("data", function (chunk) { - chunks.push(chunk); - }); - - res.on("end", function () { - var body = Buffer.concat(chunks); - console.log(body.toString()); - }); -}); - -req.write(JSON.stringify({ foo: null })); -req.end(); diff --git a/test/fixtures/output/node/native/multipart-data.js b/test/fixtures/output/node/native/multipart-data.js deleted file mode 100644 index 61d527c1f..000000000 --- a/test/fixtures/output/node/native/multipart-data.js +++ /dev/null @@ -1,27 +0,0 @@ -var http = require("http"); - -var options = { - "method": "POST", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": { - "content-type": "multipart/form-data; boundary=---011000010111000001101001" - } -}; - -var req = http.request(options, function (res) { - var chunks = []; - - res.on("data", function (chunk) { - chunks.push(chunk); - }); - - res.on("end", function () { - var body = Buffer.concat(chunks); - console.log(body.toString()); - }); -}); - -req.write("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001--\r\n"); -req.end(); diff --git a/test/fixtures/output/node/native/multipart-file.js b/test/fixtures/output/node/native/multipart-file.js deleted file mode 100644 index 17023a88d..000000000 --- a/test/fixtures/output/node/native/multipart-file.js +++ /dev/null @@ -1,27 +0,0 @@ -var http = require("http"); - -var options = { - "method": "POST", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": { - "content-type": "multipart/form-data; boundary=---011000010111000001101001" - } -}; - -var req = http.request(options, function (res) { - var chunks = []; - - res.on("data", function (chunk) { - chunks.push(chunk); - }); - - res.on("end", function () { - var body = Buffer.concat(chunks); - console.log(body.toString()); - }); -}); - -req.write("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--\r\n"); -req.end(); diff --git a/test/fixtures/output/node/native/multipart-form-data.js b/test/fixtures/output/node/native/multipart-form-data.js deleted file mode 100644 index 55244c444..000000000 --- a/test/fixtures/output/node/native/multipart-form-data.js +++ /dev/null @@ -1,27 +0,0 @@ -var http = require("http"); - -var options = { - "method": "POST", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": { - "content-type": "multipart/form-data; boundary=---011000010111000001101001" - } -}; - -var req = http.request(options, function (res) { - var chunks = []; - - res.on("data", function (chunk) { - chunks.push(chunk); - }); - - res.on("end", function () { - var body = Buffer.concat(chunks); - console.log(body.toString()); - }); -}); - -req.write("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--\r\n"); -req.end(); diff --git a/test/fixtures/output/node/native/query.js b/test/fixtures/output/node/native/query.js deleted file mode 100644 index c706f8217..000000000 --- a/test/fixtures/output/node/native/query.js +++ /dev/null @@ -1,24 +0,0 @@ -var http = require("http"); - -var options = { - "method": "GET", - "hostname": "mockbin.com", - "port": null, - "path": "/har?foo=bar&foo=baz&baz=abc&key=value", - "headers": {} -}; - -var req = http.request(options, function (res) { - var chunks = []; - - res.on("data", function (chunk) { - chunks.push(chunk); - }); - - res.on("end", function () { - var body = Buffer.concat(chunks); - console.log(body.toString()); - }); -}); - -req.end(); diff --git a/test/fixtures/output/node/native/short.js b/test/fixtures/output/node/native/short.js deleted file mode 100644 index 1c25ff701..000000000 --- a/test/fixtures/output/node/native/short.js +++ /dev/null @@ -1,24 +0,0 @@ -var http = require("http"); - -var options = { - "method": "GET", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": {} -}; - -var req = http.request(options, function (res) { - var chunks = []; - - res.on("data", function (chunk) { - chunks.push(chunk); - }); - - res.on("end", function () { - var body = Buffer.concat(chunks); - console.log(body.toString()); - }); -}); - -req.end(); diff --git a/test/fixtures/output/node/native/text-plain.js b/test/fixtures/output/node/native/text-plain.js deleted file mode 100644 index f733d8149..000000000 --- a/test/fixtures/output/node/native/text-plain.js +++ /dev/null @@ -1,27 +0,0 @@ -var http = require("http"); - -var options = { - "method": "POST", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": { - "content-type": "text/plain" - } -}; - -var req = http.request(options, function (res) { - var chunks = []; - - res.on("data", function (chunk) { - chunks.push(chunk); - }); - - res.on("end", function () { - var body = Buffer.concat(chunks); - console.log(body.toString()); - }); -}); - -req.write("Hello World"); -req.end(); diff --git a/test/fixtures/output/node/request/application-form-encoded.js b/test/fixtures/output/node/request/application-form-encoded.js deleted file mode 100644 index d3fcebd66..000000000 --- a/test/fixtures/output/node/request/application-form-encoded.js +++ /dev/null @@ -1,13 +0,0 @@ -var request = require("request"); - -var options = { method: 'POST', - url: 'http://mockbin.com/har', - headers: { 'content-type': 'application/x-www-form-urlencoded' }, - form: { foo: 'bar', hello: 'world' } }; - -request(options, function (error, response, body) { - if (error) throw new Error(error); - - console.log(body); -}); - diff --git a/test/fixtures/output/node/request/application-json.js b/test/fixtures/output/node/request/application-json.js deleted file mode 100644 index ac6377828..000000000 --- a/test/fixtures/output/node/request/application-json.js +++ /dev/null @@ -1,20 +0,0 @@ -var request = require("request"); - -var options = { method: 'POST', - url: 'http://mockbin.com/har', - headers: { 'content-type': 'application/json' }, - body: - { number: 1, - string: 'f"oo', - arr: [ 1, 2, 3 ], - nested: { a: 'b' }, - arr_mix: [ 1, 'a', { arr_mix_nested: {} } ], - boolean: false }, - json: true }; - -request(options, function (error, response, body) { - if (error) throw new Error(error); - - console.log(body); -}); - diff --git a/test/fixtures/output/node/request/cookies.js b/test/fixtures/output/node/request/cookies.js deleted file mode 100644 index 65a3b2f5c..000000000 --- a/test/fixtures/output/node/request/cookies.js +++ /dev/null @@ -1,14 +0,0 @@ -var request = require("request"); - -var jar = request.jar(); -jar.setCookie(request.cookie("foo=bar"), "http://mockbin.com/har"); -jar.setCookie(request.cookie("bar=baz"), "http://mockbin.com/har"); - -var options = { method: 'POST', url: 'http://mockbin.com/har', jar: 'JAR' }; - -request(options, function (error, response, body) { - if (error) throw new Error(error); - - console.log(body); -}); - diff --git a/test/fixtures/output/node/request/custom-method.js b/test/fixtures/output/node/request/custom-method.js deleted file mode 100644 index 951498c59..000000000 --- a/test/fixtures/output/node/request/custom-method.js +++ /dev/null @@ -1,10 +0,0 @@ -var request = require("request"); - -var options = { method: 'PROPFIND', url: 'http://mockbin.com/har' }; - -request(options, function (error, response, body) { - if (error) throw new Error(error); - - console.log(body); -}); - diff --git a/test/fixtures/output/node/request/full.js b/test/fixtures/output/node/request/full.js deleted file mode 100644 index 76b2ad68b..000000000 --- a/test/fixtures/output/node/request/full.js +++ /dev/null @@ -1,21 +0,0 @@ -var request = require("request"); - -var jar = request.jar(); -jar.setCookie(request.cookie("foo=bar"), "http://mockbin.com/har"); -jar.setCookie(request.cookie("bar=baz"), "http://mockbin.com/har"); - -var options = { method: 'POST', - url: 'http://mockbin.com/har', - qs: { foo: [ 'bar', 'baz' ], baz: 'abc', key: 'value' }, - headers: - { 'content-type': 'application/x-www-form-urlencoded', - accept: 'application/json' }, - form: { foo: 'bar' }, - jar: 'JAR' }; - -request(options, function (error, response, body) { - if (error) throw new Error(error); - - console.log(body); -}); - diff --git a/test/fixtures/output/node/request/headers.js b/test/fixtures/output/node/request/headers.js deleted file mode 100644 index d3b8c88fb..000000000 --- a/test/fixtures/output/node/request/headers.js +++ /dev/null @@ -1,12 +0,0 @@ -var request = require("request"); - -var options = { method: 'GET', - url: 'http://mockbin.com/har', - headers: { 'x-foo': 'Bar', accept: 'application/json' } }; - -request(options, function (error, response, body) { - if (error) throw new Error(error); - - console.log(body); -}); - diff --git a/test/fixtures/output/node/request/https.js b/test/fixtures/output/node/request/https.js deleted file mode 100644 index bb29e04a2..000000000 --- a/test/fixtures/output/node/request/https.js +++ /dev/null @@ -1,10 +0,0 @@ -var request = require("request"); - -var options = { method: 'GET', url: 'https://mockbin.com/har' }; - -request(options, function (error, response, body) { - if (error) throw new Error(error); - - console.log(body); -}); - diff --git a/test/fixtures/output/node/request/jsonObj-null-value.js b/test/fixtures/output/node/request/jsonObj-null-value.js deleted file mode 100644 index 41dee9694..000000000 --- a/test/fixtures/output/node/request/jsonObj-null-value.js +++ /dev/null @@ -1,14 +0,0 @@ -var request = require("request"); - -var options = { method: 'POST', - url: 'http://mockbin.com/har', - headers: { 'content-type': 'application/json' }, - body: { foo: null }, - json: true }; - -request(options, function (error, response, body) { - if (error) throw new Error(error); - - console.log(body); -}); - diff --git a/test/fixtures/output/node/request/multipart-data.js b/test/fixtures/output/node/request/multipart-data.js deleted file mode 100644 index c7aee53ca..000000000 --- a/test/fixtures/output/node/request/multipart-data.js +++ /dev/null @@ -1,16 +0,0 @@ -var request = require("request"); - -var options = { method: 'POST', - url: 'http://mockbin.com/har', - headers: { 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' }, - formData: - { foo: - { value: 'Hello World', - options: { filename: 'hello.txt', contentType: 'text/plain' } } } }; - -request(options, function (error, response, body) { - if (error) throw new Error(error); - - console.log(body); -}); - diff --git a/test/fixtures/output/node/request/multipart-file.js b/test/fixtures/output/node/request/multipart-file.js deleted file mode 100644 index 13793258b..000000000 --- a/test/fixtures/output/node/request/multipart-file.js +++ /dev/null @@ -1,19 +0,0 @@ -var fs = require("fs"); -var request = require("request"); - -var options = { method: 'POST', - url: 'http://mockbin.com/har', - headers: { 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' }, - formData: - { foo: - { value: 'fs.createReadStream("test/fixtures/files/hello.txt")', - options: - { filename: 'test/fixtures/files/hello.txt', - contentType: 'text/plain' } } } }; - -request(options, function (error, response, body) { - if (error) throw new Error(error); - - console.log(body); -}); - diff --git a/test/fixtures/output/node/request/multipart-form-data.js b/test/fixtures/output/node/request/multipart-form-data.js deleted file mode 100644 index 45a230657..000000000 --- a/test/fixtures/output/node/request/multipart-form-data.js +++ /dev/null @@ -1,13 +0,0 @@ -var request = require("request"); - -var options = { method: 'POST', - url: 'http://mockbin.com/har', - headers: { 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' }, - formData: { foo: 'bar' } }; - -request(options, function (error, response, body) { - if (error) throw new Error(error); - - console.log(body); -}); - diff --git a/test/fixtures/output/node/request/query.js b/test/fixtures/output/node/request/query.js deleted file mode 100644 index 73dc806d7..000000000 --- a/test/fixtures/output/node/request/query.js +++ /dev/null @@ -1,12 +0,0 @@ -var request = require("request"); - -var options = { method: 'GET', - url: 'http://mockbin.com/har', - qs: { foo: [ 'bar', 'baz' ], baz: 'abc', key: 'value' } }; - -request(options, function (error, response, body) { - if (error) throw new Error(error); - - console.log(body); -}); - diff --git a/test/fixtures/output/node/request/short.js b/test/fixtures/output/node/request/short.js deleted file mode 100644 index 0bb35585b..000000000 --- a/test/fixtures/output/node/request/short.js +++ /dev/null @@ -1,10 +0,0 @@ -var request = require("request"); - -var options = { method: 'GET', url: 'http://mockbin.com/har' }; - -request(options, function (error, response, body) { - if (error) throw new Error(error); - - console.log(body); -}); - diff --git a/test/fixtures/output/node/request/text-plain.js b/test/fixtures/output/node/request/text-plain.js deleted file mode 100644 index 359506dab..000000000 --- a/test/fixtures/output/node/request/text-plain.js +++ /dev/null @@ -1,13 +0,0 @@ -var request = require("request"); - -var options = { method: 'POST', - url: 'http://mockbin.com/har', - headers: { 'content-type': 'text/plain' }, - body: 'Hello World' }; - -request(options, function (error, response, body) { - if (error) throw new Error(error); - - console.log(body); -}); - diff --git a/test/fixtures/output/node/unirest/application-form-encoded.js b/test/fixtures/output/node/unirest/application-form-encoded.js deleted file mode 100644 index 5f410768b..000000000 --- a/test/fixtures/output/node/unirest/application-form-encoded.js +++ /dev/null @@ -1,19 +0,0 @@ -var unirest = require("unirest"); - -var req = unirest("POST", "http://mockbin.com/har"); - -req.headers({ - "content-type": "application/x-www-form-urlencoded" -}); - -req.form({ - "foo": "bar", - "hello": "world" -}); - -req.end(function (res) { - if (res.error) throw new Error(res.error); - - console.log(res.body); -}); - diff --git a/test/fixtures/output/node/unirest/application-json.js b/test/fixtures/output/node/unirest/application-json.js deleted file mode 100644 index ba8d8202a..000000000 --- a/test/fixtures/output/node/unirest/application-json.js +++ /dev/null @@ -1,36 +0,0 @@ -var unirest = require("unirest"); - -var req = unirest("POST", "http://mockbin.com/har"); - -req.headers({ - "content-type": "application/json" -}); - -req.type("json"); -req.send({ - "number": 1, - "string": "f\"oo", - "arr": [ - 1, - 2, - 3 - ], - "nested": { - "a": "b" - }, - "arr_mix": [ - 1, - "a", - { - "arr_mix_nested": {} - } - ], - "boolean": false -}); - -req.end(function (res) { - if (res.error) throw new Error(res.error); - - console.log(res.body); -}); - diff --git a/test/fixtures/output/node/unirest/cookies.js b/test/fixtures/output/node/unirest/cookies.js deleted file mode 100644 index 6d8d62d41..000000000 --- a/test/fixtures/output/node/unirest/cookies.js +++ /dev/null @@ -1,16 +0,0 @@ -var unirest = require("unirest"); - -var req = unirest("POST", "http://mockbin.com/har"); - -var CookieJar = unirest.jar(); -CookieJar.add("foo=bar","http://mockbin.com/har"); -CookieJar.add("bar=baz","http://mockbin.com/har"); -req.jar(CookieJar); - - -req.end(function (res) { - if (res.error) throw new Error(res.error); - - console.log(res.body); -}); - diff --git a/test/fixtures/output/node/unirest/custom-method.js b/test/fixtures/output/node/unirest/custom-method.js deleted file mode 100644 index 3e5bb5fa5..000000000 --- a/test/fixtures/output/node/unirest/custom-method.js +++ /dev/null @@ -1,11 +0,0 @@ -var unirest = require("unirest"); - -var req = unirest("PROPFIND", "http://mockbin.com/har"); - - -req.end(function (res) { - if (res.error) throw new Error(res.error); - - console.log(res.body); -}); - diff --git a/test/fixtures/output/node/unirest/full.js b/test/fixtures/output/node/unirest/full.js deleted file mode 100644 index 1a92d1fac..000000000 --- a/test/fixtures/output/node/unirest/full.js +++ /dev/null @@ -1,33 +0,0 @@ -var unirest = require("unirest"); - -var req = unirest("POST", "http://mockbin.com/har"); - -var CookieJar = unirest.jar(); -CookieJar.add("foo=bar","http://mockbin.com/har"); -CookieJar.add("bar=baz","http://mockbin.com/har"); -req.jar(CookieJar); - -req.query({ - "foo": [ - "bar", - "baz" - ], - "baz": "abc", - "key": "value" -}); - -req.headers({ - "content-type": "application/x-www-form-urlencoded", - "accept": "application/json" -}); - -req.form({ - "foo": "bar" -}); - -req.end(function (res) { - if (res.error) throw new Error(res.error); - - console.log(res.body); -}); - diff --git a/test/fixtures/output/node/unirest/headers.js b/test/fixtures/output/node/unirest/headers.js deleted file mode 100644 index 9d8be3811..000000000 --- a/test/fixtures/output/node/unirest/headers.js +++ /dev/null @@ -1,16 +0,0 @@ -var unirest = require("unirest"); - -var req = unirest("GET", "http://mockbin.com/har"); - -req.headers({ - "x-foo": "Bar", - "accept": "application/json" -}); - - -req.end(function (res) { - if (res.error) throw new Error(res.error); - - console.log(res.body); -}); - diff --git a/test/fixtures/output/node/unirest/https.js b/test/fixtures/output/node/unirest/https.js deleted file mode 100644 index ec5faf337..000000000 --- a/test/fixtures/output/node/unirest/https.js +++ /dev/null @@ -1,11 +0,0 @@ -var unirest = require("unirest"); - -var req = unirest("GET", "https://mockbin.com/har"); - - -req.end(function (res) { - if (res.error) throw new Error(res.error); - - console.log(res.body); -}); - diff --git a/test/fixtures/output/node/unirest/jsonObj-null-value.js b/test/fixtures/output/node/unirest/jsonObj-null-value.js deleted file mode 100644 index f898c6024..000000000 --- a/test/fixtures/output/node/unirest/jsonObj-null-value.js +++ /dev/null @@ -1,19 +0,0 @@ -var unirest = require("unirest"); - -var req = unirest("POST", "http://mockbin.com/har"); - -req.headers({ - "content-type": "application/json" -}); - -req.type("json"); -req.send({ - "foo": null -}); - -req.end(function (res) { - if (res.error) throw new Error(res.error); - - console.log(res.body); -}); - diff --git a/test/fixtures/output/node/unirest/multipart-data.js b/test/fixtures/output/node/unirest/multipart-data.js deleted file mode 100644 index bdf8da515..000000000 --- a/test/fixtures/output/node/unirest/multipart-data.js +++ /dev/null @@ -1,21 +0,0 @@ -var unirest = require("unirest"); - -var req = unirest("POST", "http://mockbin.com/har"); - -req.headers({ - "content-type": "multipart/form-data; boundary=---011000010111000001101001" -}); - -req.multipart([ - { - "body": "Hello World", - "content-type": "text/plain" - } -]); - -req.end(function (res) { - if (res.error) throw new Error(res.error); - - console.log(res.body); -}); - diff --git a/test/fixtures/output/node/unirest/multipart-file.js b/test/fixtures/output/node/unirest/multipart-file.js deleted file mode 100644 index c8efe878a..000000000 --- a/test/fixtures/output/node/unirest/multipart-file.js +++ /dev/null @@ -1,22 +0,0 @@ -var fs = require("fs"); -var unirest = require("unirest"); - -var req = unirest("POST", "http://mockbin.com/har"); - -req.headers({ - "content-type": "multipart/form-data; boundary=---011000010111000001101001" -}); - -req.multipart([ - { - "body": fs.createReadStream("test/fixtures/files/hello.txt"), - "content-type": "text/plain" - } -]); - -req.end(function (res) { - if (res.error) throw new Error(res.error); - - console.log(res.body); -}); - diff --git a/test/fixtures/output/node/unirest/multipart-form-data.js b/test/fixtures/output/node/unirest/multipart-form-data.js deleted file mode 100644 index ea358a350..000000000 --- a/test/fixtures/output/node/unirest/multipart-form-data.js +++ /dev/null @@ -1,20 +0,0 @@ -var unirest = require("unirest"); - -var req = unirest("POST", "http://mockbin.com/har"); - -req.headers({ - "content-type": "multipart/form-data; boundary=---011000010111000001101001" -}); - -req.multipart([ - { - "body": "bar" - } -]); - -req.end(function (res) { - if (res.error) throw new Error(res.error); - - console.log(res.body); -}); - diff --git a/test/fixtures/output/node/unirest/query.js b/test/fixtures/output/node/unirest/query.js deleted file mode 100644 index 464e2f941..000000000 --- a/test/fixtures/output/node/unirest/query.js +++ /dev/null @@ -1,20 +0,0 @@ -var unirest = require("unirest"); - -var req = unirest("GET", "http://mockbin.com/har"); - -req.query({ - "foo": [ - "bar", - "baz" - ], - "baz": "abc", - "key": "value" -}); - - -req.end(function (res) { - if (res.error) throw new Error(res.error); - - console.log(res.body); -}); - diff --git a/test/fixtures/output/node/unirest/short.js b/test/fixtures/output/node/unirest/short.js deleted file mode 100644 index 95a778b52..000000000 --- a/test/fixtures/output/node/unirest/short.js +++ /dev/null @@ -1,11 +0,0 @@ -var unirest = require("unirest"); - -var req = unirest("GET", "http://mockbin.com/har"); - - -req.end(function (res) { - if (res.error) throw new Error(res.error); - - console.log(res.body); -}); - diff --git a/test/fixtures/output/node/unirest/text-plain.js b/test/fixtures/output/node/unirest/text-plain.js deleted file mode 100644 index bffa7ee03..000000000 --- a/test/fixtures/output/node/unirest/text-plain.js +++ /dev/null @@ -1,16 +0,0 @@ -var unirest = require("unirest"); - -var req = unirest("POST", "http://mockbin.com/har"); - -req.headers({ - "content-type": "text/plain" -}); - - req.send("Hello World"); - -req.end(function (res) { - if (res.error) throw new Error(res.error); - - console.log(res.body); -}); - diff --git a/test/fixtures/output/objc/nsurlsession/https.m b/test/fixtures/output/objc/nsurlsession/https.m deleted file mode 100644 index b5ef41ea9..000000000 --- a/test/fixtures/output/objc/nsurlsession/https.m +++ /dev/null @@ -1,18 +0,0 @@ -#import - -NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://mockbin.com/har"] - cachePolicy:NSURLRequestUseProtocolCachePolicy - timeoutInterval:10.0]; -[request setHTTPMethod:@"GET"]; - -NSURLSession *session = [NSURLSession sharedSession]; -NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request - completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { - if (error) { - NSLog(@"%@", error); - } else { - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; - NSLog(@"%@", httpResponse); - } - }]; -[dataTask resume]; diff --git a/test/fixtures/output/ocaml/cohttp/application-form-encoded.ml b/test/fixtures/output/ocaml/cohttp/application-form-encoded.ml deleted file mode 100644 index 8480d692e..000000000 --- a/test/fixtures/output/ocaml/cohttp/application-form-encoded.ml +++ /dev/null @@ -1,11 +0,0 @@ -open Cohttp_lwt_unix -open Cohttp -open Lwt - -let uri = Uri.of_string "http://mockbin.com/har" in -let headers = Header.add (Header.init ()) "content-type" "application/x-www-form-urlencoded" in -let body = Cohttp_lwt_body.of_string "foo=bar&hello=world" in - -Client.call ~headers ~body `POST uri ->>= fun (res, body_stream) -> - (* Do stuff with the result *) diff --git a/test/fixtures/output/ocaml/cohttp/application-json.ml b/test/fixtures/output/ocaml/cohttp/application-json.ml deleted file mode 100644 index dda6e550d..000000000 --- a/test/fixtures/output/ocaml/cohttp/application-json.ml +++ /dev/null @@ -1,11 +0,0 @@ -open Cohttp_lwt_unix -open Cohttp -open Lwt - -let uri = Uri.of_string "http://mockbin.com/har" in -let headers = Header.add (Header.init ()) "content-type" "application/json" in -let body = Cohttp_lwt_body.of_string "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":{}}],\"boolean\":false}" in - -Client.call ~headers ~body `POST uri ->>= fun (res, body_stream) -> - (* Do stuff with the result *) diff --git a/test/fixtures/output/ocaml/cohttp/cookies.ml b/test/fixtures/output/ocaml/cohttp/cookies.ml deleted file mode 100644 index fdf6dccf3..000000000 --- a/test/fixtures/output/ocaml/cohttp/cookies.ml +++ /dev/null @@ -1,10 +0,0 @@ -open Cohttp_lwt_unix -open Cohttp -open Lwt - -let uri = Uri.of_string "http://mockbin.com/har" in -let headers = Header.add (Header.init ()) "cookie" "foo=bar; bar=baz" in - -Client.call ~headers `POST uri ->>= fun (res, body_stream) -> - (* Do stuff with the result *) diff --git a/test/fixtures/output/ocaml/cohttp/custom-method.ml b/test/fixtures/output/ocaml/cohttp/custom-method.ml deleted file mode 100644 index fac0d1263..000000000 --- a/test/fixtures/output/ocaml/cohttp/custom-method.ml +++ /dev/null @@ -1,9 +0,0 @@ -open Cohttp_lwt_unix -open Cohttp -open Lwt - -let uri = Uri.of_string "http://mockbin.com/har" in - -Client.call (Code.method_of_string "PROPFIND") uri ->>= fun (res, body_stream) -> - (* Do stuff with the result *) diff --git a/test/fixtures/output/ocaml/cohttp/full.ml b/test/fixtures/output/ocaml/cohttp/full.ml deleted file mode 100644 index c4b1dc04a..000000000 --- a/test/fixtures/output/ocaml/cohttp/full.ml +++ /dev/null @@ -1,15 +0,0 @@ -open Cohttp_lwt_unix -open Cohttp -open Lwt - -let uri = Uri.of_string "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value" in -let headers = Header.add_list (Header.init ()) [ - ("cookie", "foo=bar; bar=baz"); - ("accept", "application/json"); - ("content-type", "application/x-www-form-urlencoded"); -] in -let body = Cohttp_lwt_body.of_string "foo=bar" in - -Client.call ~headers ~body `POST uri ->>= fun (res, body_stream) -> - (* Do stuff with the result *) diff --git a/test/fixtures/output/ocaml/cohttp/headers.ml b/test/fixtures/output/ocaml/cohttp/headers.ml deleted file mode 100644 index 6755d5a22..000000000 --- a/test/fixtures/output/ocaml/cohttp/headers.ml +++ /dev/null @@ -1,13 +0,0 @@ -open Cohttp_lwt_unix -open Cohttp -open Lwt - -let uri = Uri.of_string "http://mockbin.com/har" in -let headers = Header.add_list (Header.init ()) [ - ("accept", "application/json"); - ("x-foo", "Bar"); -] in - -Client.call ~headers `GET uri ->>= fun (res, body_stream) -> - (* Do stuff with the result *) diff --git a/test/fixtures/output/ocaml/cohttp/https.ml b/test/fixtures/output/ocaml/cohttp/https.ml deleted file mode 100644 index bb68b33b6..000000000 --- a/test/fixtures/output/ocaml/cohttp/https.ml +++ /dev/null @@ -1,9 +0,0 @@ -open Cohttp_lwt_unix -open Cohttp -open Lwt - -let uri = Uri.of_string "https://mockbin.com/har" in - -Client.call `GET uri ->>= fun (res, body_stream) -> - (* Do stuff with the result *) diff --git a/test/fixtures/output/ocaml/cohttp/jsonObj-null-value.ml b/test/fixtures/output/ocaml/cohttp/jsonObj-null-value.ml deleted file mode 100644 index 20fbc6a4f..000000000 --- a/test/fixtures/output/ocaml/cohttp/jsonObj-null-value.ml +++ /dev/null @@ -1,11 +0,0 @@ -open Cohttp_lwt_unix -open Cohttp -open Lwt - -let uri = Uri.of_string "http://mockbin.com/har" in -let headers = Header.add (Header.init ()) "content-type" "application/json" in -let body = Cohttp_lwt_body.of_string "{\"foo\":null}" in - -Client.call ~headers ~body `POST uri ->>= fun (res, body_stream) -> - (* Do stuff with the result *) diff --git a/test/fixtures/output/ocaml/cohttp/multipart-data.ml b/test/fixtures/output/ocaml/cohttp/multipart-data.ml deleted file mode 100644 index 3d5b3c062..000000000 --- a/test/fixtures/output/ocaml/cohttp/multipart-data.ml +++ /dev/null @@ -1,11 +0,0 @@ -open Cohttp_lwt_unix -open Cohttp -open Lwt - -let uri = Uri.of_string "http://mockbin.com/har" in -let headers = Header.add (Header.init ()) "content-type" "multipart/form-data; boundary=---011000010111000001101001" in -let body = Cohttp_lwt_body.of_string "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001--\r\n" in - -Client.call ~headers ~body `POST uri ->>= fun (res, body_stream) -> - (* Do stuff with the result *) diff --git a/test/fixtures/output/ocaml/cohttp/multipart-file.ml b/test/fixtures/output/ocaml/cohttp/multipart-file.ml deleted file mode 100644 index 96f8794ed..000000000 --- a/test/fixtures/output/ocaml/cohttp/multipart-file.ml +++ /dev/null @@ -1,11 +0,0 @@ -open Cohttp_lwt_unix -open Cohttp -open Lwt - -let uri = Uri.of_string "http://mockbin.com/har" in -let headers = Header.add (Header.init ()) "content-type" "multipart/form-data; boundary=---011000010111000001101001" in -let body = Cohttp_lwt_body.of_string "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--\r\n" in - -Client.call ~headers ~body `POST uri ->>= fun (res, body_stream) -> - (* Do stuff with the result *) diff --git a/test/fixtures/output/ocaml/cohttp/multipart-form-data.ml b/test/fixtures/output/ocaml/cohttp/multipart-form-data.ml deleted file mode 100644 index 488c3e41b..000000000 --- a/test/fixtures/output/ocaml/cohttp/multipart-form-data.ml +++ /dev/null @@ -1,11 +0,0 @@ -open Cohttp_lwt_unix -open Cohttp -open Lwt - -let uri = Uri.of_string "http://mockbin.com/har" in -let headers = Header.add (Header.init ()) "content-type" "multipart/form-data; boundary=---011000010111000001101001" in -let body = Cohttp_lwt_body.of_string "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--\r\n" in - -Client.call ~headers ~body `POST uri ->>= fun (res, body_stream) -> - (* Do stuff with the result *) diff --git a/test/fixtures/output/ocaml/cohttp/query.ml b/test/fixtures/output/ocaml/cohttp/query.ml deleted file mode 100644 index 8634f1ab1..000000000 --- a/test/fixtures/output/ocaml/cohttp/query.ml +++ /dev/null @@ -1,9 +0,0 @@ -open Cohttp_lwt_unix -open Cohttp -open Lwt - -let uri = Uri.of_string "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value" in - -Client.call `GET uri ->>= fun (res, body_stream) -> - (* Do stuff with the result *) diff --git a/test/fixtures/output/ocaml/cohttp/short.ml b/test/fixtures/output/ocaml/cohttp/short.ml deleted file mode 100644 index 189bc3f53..000000000 --- a/test/fixtures/output/ocaml/cohttp/short.ml +++ /dev/null @@ -1,9 +0,0 @@ -open Cohttp_lwt_unix -open Cohttp -open Lwt - -let uri = Uri.of_string "http://mockbin.com/har" in - -Client.call `GET uri ->>= fun (res, body_stream) -> - (* Do stuff with the result *) diff --git a/test/fixtures/output/ocaml/cohttp/text-plain.ml b/test/fixtures/output/ocaml/cohttp/text-plain.ml deleted file mode 100644 index 28148e744..000000000 --- a/test/fixtures/output/ocaml/cohttp/text-plain.ml +++ /dev/null @@ -1,11 +0,0 @@ -open Cohttp_lwt_unix -open Cohttp -open Lwt - -let uri = Uri.of_string "http://mockbin.com/har" in -let headers = Header.add (Header.init ()) "content-type" "text/plain" in -let body = Cohttp_lwt_body.of_string "Hello World" in - -Client.call ~headers ~body `POST uri ->>= fun (res, body_stream) -> - (* Do stuff with the result *) diff --git a/test/fixtures/output/php/curl/application-form-encoded.php b/test/fixtures/output/php/curl/application-form-encoded.php deleted file mode 100644 index ca76dc0af..000000000 --- a/test/fixtures/output/php/curl/application-form-encoded.php +++ /dev/null @@ -1,28 +0,0 @@ - "http://mockbin.com/har", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "foo=bar&hello=world", - CURLOPT_HTTPHEADER => array( - "content-type: application/x-www-form-urlencoded" - ), -)); - -$response = curl_exec($curl); -$err = curl_error($curl); - -curl_close($curl); - -if ($err) { - echo "cURL Error #:" . $err; -} else { - echo $response; -} diff --git a/test/fixtures/output/php/curl/application-json.php b/test/fixtures/output/php/curl/application-json.php deleted file mode 100644 index 595bcd167..000000000 --- a/test/fixtures/output/php/curl/application-json.php +++ /dev/null @@ -1,28 +0,0 @@ - "http://mockbin.com/har", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":{}}],\"boolean\":false}", - CURLOPT_HTTPHEADER => array( - "content-type: application/json" - ), -)); - -$response = curl_exec($curl); -$err = curl_error($curl); - -curl_close($curl); - -if ($err) { - echo "cURL Error #:" . $err; -} else { - echo $response; -} diff --git a/test/fixtures/output/php/curl/cookies.php b/test/fixtures/output/php/curl/cookies.php deleted file mode 100644 index 1f6ab0c63..000000000 --- a/test/fixtures/output/php/curl/cookies.php +++ /dev/null @@ -1,25 +0,0 @@ - "http://mockbin.com/har", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_COOKIE => "foo=bar; bar=baz", -)); - -$response = curl_exec($curl); -$err = curl_error($curl); - -curl_close($curl); - -if ($err) { - echo "cURL Error #:" . $err; -} else { - echo $response; -} diff --git a/test/fixtures/output/php/curl/custom-method.php b/test/fixtures/output/php/curl/custom-method.php deleted file mode 100644 index b12fac445..000000000 --- a/test/fixtures/output/php/curl/custom-method.php +++ /dev/null @@ -1,24 +0,0 @@ - "http://mockbin.com/har", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "PROPFIND", -)); - -$response = curl_exec($curl); -$err = curl_error($curl); - -curl_close($curl); - -if ($err) { - echo "cURL Error #:" . $err; -} else { - echo $response; -} diff --git a/test/fixtures/output/php/curl/full.php b/test/fixtures/output/php/curl/full.php deleted file mode 100644 index 4208fd484..000000000 --- a/test/fixtures/output/php/curl/full.php +++ /dev/null @@ -1,30 +0,0 @@ - "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "foo=bar", - CURLOPT_COOKIE => "foo=bar; bar=baz", - CURLOPT_HTTPHEADER => array( - "accept: application/json", - "content-type: application/x-www-form-urlencoded" - ), -)); - -$response = curl_exec($curl); -$err = curl_error($curl); - -curl_close($curl); - -if ($err) { - echo "cURL Error #:" . $err; -} else { - echo $response; -} diff --git a/test/fixtures/output/php/curl/headers.php b/test/fixtures/output/php/curl/headers.php deleted file mode 100644 index 1e080520d..000000000 --- a/test/fixtures/output/php/curl/headers.php +++ /dev/null @@ -1,28 +0,0 @@ - "http://mockbin.com/har", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "GET", - CURLOPT_HTTPHEADER => array( - "accept: application/json", - "x-foo: Bar" - ), -)); - -$response = curl_exec($curl); -$err = curl_error($curl); - -curl_close($curl); - -if ($err) { - echo "cURL Error #:" . $err; -} else { - echo $response; -} diff --git a/test/fixtures/output/php/curl/https.php b/test/fixtures/output/php/curl/https.php deleted file mode 100644 index 01b00b21d..000000000 --- a/test/fixtures/output/php/curl/https.php +++ /dev/null @@ -1,24 +0,0 @@ - "https://mockbin.com/har", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "GET", -)); - -$response = curl_exec($curl); -$err = curl_error($curl); - -curl_close($curl); - -if ($err) { - echo "cURL Error #:" . $err; -} else { - echo $response; -} diff --git a/test/fixtures/output/php/curl/jsonObj-null-value.php b/test/fixtures/output/php/curl/jsonObj-null-value.php deleted file mode 100644 index 91194a4a1..000000000 --- a/test/fixtures/output/php/curl/jsonObj-null-value.php +++ /dev/null @@ -1,28 +0,0 @@ - "http://mockbin.com/har", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "{\"foo\":null}", - CURLOPT_HTTPHEADER => array( - "content-type: application/json" - ), -)); - -$response = curl_exec($curl); -$err = curl_error($curl); - -curl_close($curl); - -if ($err) { - echo "cURL Error #:" . $err; -} else { - echo $response; -} diff --git a/test/fixtures/output/php/curl/multipart-data.php b/test/fixtures/output/php/curl/multipart-data.php deleted file mode 100644 index 944a4c374..000000000 --- a/test/fixtures/output/php/curl/multipart-data.php +++ /dev/null @@ -1,28 +0,0 @@ - "http://mockbin.com/har", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001--\r\n", - CURLOPT_HTTPHEADER => array( - "content-type: multipart/form-data; boundary=---011000010111000001101001" - ), -)); - -$response = curl_exec($curl); -$err = curl_error($curl); - -curl_close($curl); - -if ($err) { - echo "cURL Error #:" . $err; -} else { - echo $response; -} diff --git a/test/fixtures/output/php/curl/multipart-file.php b/test/fixtures/output/php/curl/multipart-file.php deleted file mode 100644 index 160b27705..000000000 --- a/test/fixtures/output/php/curl/multipart-file.php +++ /dev/null @@ -1,28 +0,0 @@ - "http://mockbin.com/har", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--\r\n", - CURLOPT_HTTPHEADER => array( - "content-type: multipart/form-data; boundary=---011000010111000001101001" - ), -)); - -$response = curl_exec($curl); -$err = curl_error($curl); - -curl_close($curl); - -if ($err) { - echo "cURL Error #:" . $err; -} else { - echo $response; -} diff --git a/test/fixtures/output/php/curl/multipart-form-data.php b/test/fixtures/output/php/curl/multipart-form-data.php deleted file mode 100644 index f815f6c56..000000000 --- a/test/fixtures/output/php/curl/multipart-form-data.php +++ /dev/null @@ -1,28 +0,0 @@ - "http://mockbin.com/har", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--\r\n", - CURLOPT_HTTPHEADER => array( - "content-type: multipart/form-data; boundary=---011000010111000001101001" - ), -)); - -$response = curl_exec($curl); -$err = curl_error($curl); - -curl_close($curl); - -if ($err) { - echo "cURL Error #:" . $err; -} else { - echo $response; -} diff --git a/test/fixtures/output/php/curl/query.php b/test/fixtures/output/php/curl/query.php deleted file mode 100644 index d85fc7815..000000000 --- a/test/fixtures/output/php/curl/query.php +++ /dev/null @@ -1,24 +0,0 @@ - "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "GET", -)); - -$response = curl_exec($curl); -$err = curl_error($curl); - -curl_close($curl); - -if ($err) { - echo "cURL Error #:" . $err; -} else { - echo $response; -} diff --git a/test/fixtures/output/php/curl/short.php b/test/fixtures/output/php/curl/short.php deleted file mode 100644 index c67fb150f..000000000 --- a/test/fixtures/output/php/curl/short.php +++ /dev/null @@ -1,24 +0,0 @@ - "http://mockbin.com/har", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "GET", -)); - -$response = curl_exec($curl); -$err = curl_error($curl); - -curl_close($curl); - -if ($err) { - echo "cURL Error #:" . $err; -} else { - echo $response; -} diff --git a/test/fixtures/output/php/curl/text-plain.php b/test/fixtures/output/php/curl/text-plain.php deleted file mode 100644 index 6306b9213..000000000 --- a/test/fixtures/output/php/curl/text-plain.php +++ /dev/null @@ -1,28 +0,0 @@ - "http://mockbin.com/har", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => "Hello World", - CURLOPT_HTTPHEADER => array( - "content-type: text/plain" - ), -)); - -$response = curl_exec($curl); -$err = curl_error($curl); - -curl_close($curl); - -if ($err) { - echo "cURL Error #:" . $err; -} else { - echo $response; -} diff --git a/test/fixtures/output/php/http1/application-form-encoded.php b/test/fixtures/output/php/http1/application-form-encoded.php deleted file mode 100644 index 32d4112bd..000000000 --- a/test/fixtures/output/php/http1/application-form-encoded.php +++ /dev/null @@ -1,23 +0,0 @@ -setUrl('http://mockbin.com/har'); -$request->setMethod(HTTP_METH_POST); - -$request->setHeaders(array( - 'content-type' => 'application/x-www-form-urlencoded' -)); - -$request->setContentType('application/x-www-form-urlencoded'); -$request->setPostFields(array( - 'foo' => 'bar', - 'hello' => 'world' -)); - -try { - $response = $request->send(); - - echo $response->getBody(); -} catch (HttpException $ex) { - echo $ex; -} diff --git a/test/fixtures/output/php/http1/application-json.php b/test/fixtures/output/php/http1/application-json.php deleted file mode 100644 index 2abde643d..000000000 --- a/test/fixtures/output/php/http1/application-json.php +++ /dev/null @@ -1,19 +0,0 @@ -setUrl('http://mockbin.com/har'); -$request->setMethod(HTTP_METH_POST); - -$request->setHeaders(array( - 'content-type' => 'application/json' -)); - -$request->setBody('{"number":1,"string":"f\\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":{}}],"boolean":false}'); - -try { - $response = $request->send(); - - echo $response->getBody(); -} catch (HttpException $ex) { - echo $ex; -} diff --git a/test/fixtures/output/php/http1/cookies.php b/test/fixtures/output/php/http1/cookies.php deleted file mode 100644 index 1dfcf609b..000000000 --- a/test/fixtures/output/php/http1/cookies.php +++ /dev/null @@ -1,18 +0,0 @@ -setUrl('http://mockbin.com/har'); -$request->setMethod(HTTP_METH_POST); - -$request->setCookies(array( - 'bar' => 'baz', - 'foo' => 'bar' -)); - -try { - $response = $request->send(); - - echo $response->getBody(); -} catch (HttpException $ex) { - echo $ex; -} diff --git a/test/fixtures/output/php/http1/custom-method.php b/test/fixtures/output/php/http1/custom-method.php deleted file mode 100644 index ba4f9293f..000000000 --- a/test/fixtures/output/php/http1/custom-method.php +++ /dev/null @@ -1,13 +0,0 @@ -setUrl('http://mockbin.com/har'); -$request->setMethod(HTTP_METH_PROPFIND); - -try { - $response = $request->send(); - - echo $response->getBody(); -} catch (HttpException $ex) { - echo $ex; -} diff --git a/test/fixtures/output/php/http1/full.php b/test/fixtures/output/php/http1/full.php deleted file mode 100644 index 712f1e0ec..000000000 --- a/test/fixtures/output/php/http1/full.php +++ /dev/null @@ -1,37 +0,0 @@ -setUrl('http://mockbin.com/har'); -$request->setMethod(HTTP_METH_POST); - -$request->setQueryData(array( - 'foo' => array( - 'bar', - 'baz' - ), - 'baz' => 'abc', - 'key' => 'value' -)); - -$request->setHeaders(array( - 'content-type' => 'application/x-www-form-urlencoded', - 'accept' => 'application/json' -)); - -$request->setCookies(array( - 'bar' => 'baz', - 'foo' => 'bar' -)); - -$request->setContentType('application/x-www-form-urlencoded'); -$request->setPostFields(array( - 'foo' => 'bar' -)); - -try { - $response = $request->send(); - - echo $response->getBody(); -} catch (HttpException $ex) { - echo $ex; -} diff --git a/test/fixtures/output/php/http1/headers.php b/test/fixtures/output/php/http1/headers.php deleted file mode 100644 index 819e46a4d..000000000 --- a/test/fixtures/output/php/http1/headers.php +++ /dev/null @@ -1,18 +0,0 @@ -setUrl('http://mockbin.com/har'); -$request->setMethod(HTTP_METH_GET); - -$request->setHeaders(array( - 'x-foo' => 'Bar', - 'accept' => 'application/json' -)); - -try { - $response = $request->send(); - - echo $response->getBody(); -} catch (HttpException $ex) { - echo $ex; -} diff --git a/test/fixtures/output/php/http1/https.php b/test/fixtures/output/php/http1/https.php deleted file mode 100644 index dadd0653b..000000000 --- a/test/fixtures/output/php/http1/https.php +++ /dev/null @@ -1,13 +0,0 @@ -setUrl('https://mockbin.com/har'); -$request->setMethod(HTTP_METH_GET); - -try { - $response = $request->send(); - - echo $response->getBody(); -} catch (HttpException $ex) { - echo $ex; -} diff --git a/test/fixtures/output/php/http1/jsonObj-null-value.php b/test/fixtures/output/php/http1/jsonObj-null-value.php deleted file mode 100644 index 216298351..000000000 --- a/test/fixtures/output/php/http1/jsonObj-null-value.php +++ /dev/null @@ -1,19 +0,0 @@ -setUrl('http://mockbin.com/har'); -$request->setMethod(HTTP_METH_POST); - -$request->setHeaders(array( - 'content-type' => 'application/json' -)); - -$request->setBody('{"foo":null}'); - -try { - $response = $request->send(); - - echo $response->getBody(); -} catch (HttpException $ex) { - echo $ex; -} diff --git a/test/fixtures/output/php/http1/multipart-data.php b/test/fixtures/output/php/http1/multipart-data.php deleted file mode 100644 index d5e20ac4d..000000000 --- a/test/fixtures/output/php/http1/multipart-data.php +++ /dev/null @@ -1,25 +0,0 @@ -setUrl('http://mockbin.com/har'); -$request->setMethod(HTTP_METH_POST); - -$request->setHeaders(array( - 'content-type' => 'multipart/form-data; boundary=---011000010111000001101001' -)); - -$request->setBody('-----011000010111000001101001 -Content-Disposition: form-data; name="foo"; filename="hello.txt" -Content-Type: text/plain - -Hello World ------011000010111000001101001-- -'); - -try { - $response = $request->send(); - - echo $response->getBody(); -} catch (HttpException $ex) { - echo $ex; -} diff --git a/test/fixtures/output/php/http1/multipart-file.php b/test/fixtures/output/php/http1/multipart-file.php deleted file mode 100644 index 721be8237..000000000 --- a/test/fixtures/output/php/http1/multipart-file.php +++ /dev/null @@ -1,25 +0,0 @@ -setUrl('http://mockbin.com/har'); -$request->setMethod(HTTP_METH_POST); - -$request->setHeaders(array( - 'content-type' => 'multipart/form-data; boundary=---011000010111000001101001' -)); - -$request->setBody('-----011000010111000001101001 -Content-Disposition: form-data; name="foo"; filename="hello.txt" -Content-Type: text/plain - - ------011000010111000001101001-- -'); - -try { - $response = $request->send(); - - echo $response->getBody(); -} catch (HttpException $ex) { - echo $ex; -} diff --git a/test/fixtures/output/php/http1/multipart-form-data.php b/test/fixtures/output/php/http1/multipart-form-data.php deleted file mode 100644 index c78c84f8e..000000000 --- a/test/fixtures/output/php/http1/multipart-form-data.php +++ /dev/null @@ -1,24 +0,0 @@ -setUrl('http://mockbin.com/har'); -$request->setMethod(HTTP_METH_POST); - -$request->setHeaders(array( - 'content-type' => 'multipart/form-data; boundary=---011000010111000001101001' -)); - -$request->setBody('-----011000010111000001101001 -Content-Disposition: form-data; name="foo" - -bar ------011000010111000001101001-- -'); - -try { - $response = $request->send(); - - echo $response->getBody(); -} catch (HttpException $ex) { - echo $ex; -} diff --git a/test/fixtures/output/php/http1/query.php b/test/fixtures/output/php/http1/query.php deleted file mode 100644 index ec8a949b5..000000000 --- a/test/fixtures/output/php/http1/query.php +++ /dev/null @@ -1,22 +0,0 @@ -setUrl('http://mockbin.com/har'); -$request->setMethod(HTTP_METH_GET); - -$request->setQueryData(array( - 'foo' => array( - 'bar', - 'baz' - ), - 'baz' => 'abc', - 'key' => 'value' -)); - -try { - $response = $request->send(); - - echo $response->getBody(); -} catch (HttpException $ex) { - echo $ex; -} diff --git a/test/fixtures/output/php/http1/short.php b/test/fixtures/output/php/http1/short.php deleted file mode 100644 index 3a7fa9a3c..000000000 --- a/test/fixtures/output/php/http1/short.php +++ /dev/null @@ -1,13 +0,0 @@ -setUrl('http://mockbin.com/har'); -$request->setMethod(HTTP_METH_GET); - -try { - $response = $request->send(); - - echo $response->getBody(); -} catch (HttpException $ex) { - echo $ex; -} diff --git a/test/fixtures/output/php/http1/text-plain.php b/test/fixtures/output/php/http1/text-plain.php deleted file mode 100644 index 1e8938682..000000000 --- a/test/fixtures/output/php/http1/text-plain.php +++ /dev/null @@ -1,19 +0,0 @@ -setUrl('http://mockbin.com/har'); -$request->setMethod(HTTP_METH_POST); - -$request->setHeaders(array( - 'content-type' => 'text/plain' -)); - -$request->setBody('Hello World'); - -try { - $response = $request->send(); - - echo $response->getBody(); -} catch (HttpException $ex) { - echo $ex; -} diff --git a/test/fixtures/output/php/http2/application-form-encoded.php b/test/fixtures/output/php/http2/application-form-encoded.php deleted file mode 100644 index 573ecbcbb..000000000 --- a/test/fixtures/output/php/http2/application-form-encoded.php +++ /dev/null @@ -1,23 +0,0 @@ -append(new http\QueryString(array( - 'foo' => 'bar', - 'hello' => 'world' -))); - -$request->setRequestUrl('http://mockbin.com/har'); -$request->setRequestMethod('POST'); -$request->setBody($body); - -$request->setHeaders(array( - 'content-type' => 'application/x-www-form-urlencoded' -)); - -$client->enqueue($request)->send(); -$response = $client->getResponse(); - -echo $response->getBody(); diff --git a/test/fixtures/output/php/http2/application-json.php b/test/fixtures/output/php/http2/application-json.php deleted file mode 100644 index f4305c773..000000000 --- a/test/fixtures/output/php/http2/application-json.php +++ /dev/null @@ -1,20 +0,0 @@ -append('{"number":1,"string":"f\\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":{}}],"boolean":false}'); - -$request->setRequestUrl('http://mockbin.com/har'); -$request->setRequestMethod('POST'); -$request->setBody($body); - -$request->setHeaders(array( - 'content-type' => 'application/json' -)); - -$client->enqueue($request)->send(); -$response = $client->getResponse(); - -echo $response->getBody(); diff --git a/test/fixtures/output/php/http2/cookies.php b/test/fixtures/output/php/http2/cookies.php deleted file mode 100644 index 0502c6d66..000000000 --- a/test/fixtures/output/php/http2/cookies.php +++ /dev/null @@ -1,17 +0,0 @@ -setRequestUrl('http://mockbin.com/har'); -$request->setRequestMethod('POST'); - -$client->setCookies(array( - 'bar' => 'baz', - 'foo' => 'bar' -)); - -$client->enqueue($request)->send(); -$response = $client->getResponse(); - -echo $response->getBody(); diff --git a/test/fixtures/output/php/http2/custom-method.php b/test/fixtures/output/php/http2/custom-method.php deleted file mode 100644 index 6d4897297..000000000 --- a/test/fixtures/output/php/http2/custom-method.php +++ /dev/null @@ -1,11 +0,0 @@ -setRequestUrl('http://mockbin.com/har'); -$request->setRequestMethod('PROPFIND'); -$client->enqueue($request)->send(); -$response = $client->getResponse(); - -echo $response->getBody(); diff --git a/test/fixtures/output/php/http2/full.php b/test/fixtures/output/php/http2/full.php deleted file mode 100644 index 0a9a5a42c..000000000 --- a/test/fixtures/output/php/http2/full.php +++ /dev/null @@ -1,38 +0,0 @@ -append(new http\QueryString(array( - 'foo' => 'bar' -))); - -$request->setRequestUrl('http://mockbin.com/har'); -$request->setRequestMethod('POST'); -$request->setBody($body); - -$request->setQuery(new http\QueryString(array( - 'foo' => array( - 'bar', - 'baz' - ), - 'baz' => 'abc', - 'key' => 'value' -))); - -$request->setHeaders(array( - 'content-type' => 'application/x-www-form-urlencoded', - 'accept' => 'application/json' -)); - - -$client->setCookies(array( - 'bar' => 'baz', - 'foo' => 'bar' -)); - -$client->enqueue($request)->send(); -$response = $client->getResponse(); - -echo $response->getBody(); diff --git a/test/fixtures/output/php/http2/headers.php b/test/fixtures/output/php/http2/headers.php deleted file mode 100644 index 66ab89618..000000000 --- a/test/fixtures/output/php/http2/headers.php +++ /dev/null @@ -1,16 +0,0 @@ -setRequestUrl('http://mockbin.com/har'); -$request->setRequestMethod('GET'); -$request->setHeaders(array( - 'x-foo' => 'Bar', - 'accept' => 'application/json' -)); - -$client->enqueue($request)->send(); -$response = $client->getResponse(); - -echo $response->getBody(); diff --git a/test/fixtures/output/php/http2/https.php b/test/fixtures/output/php/http2/https.php deleted file mode 100644 index 12a233eae..000000000 --- a/test/fixtures/output/php/http2/https.php +++ /dev/null @@ -1,11 +0,0 @@ -setRequestUrl('https://mockbin.com/har'); -$request->setRequestMethod('GET'); -$client->enqueue($request)->send(); -$response = $client->getResponse(); - -echo $response->getBody(); diff --git a/test/fixtures/output/php/http2/jsonObj-null-value.php b/test/fixtures/output/php/http2/jsonObj-null-value.php deleted file mode 100644 index d122998e8..000000000 --- a/test/fixtures/output/php/http2/jsonObj-null-value.php +++ /dev/null @@ -1,20 +0,0 @@ -append('{"foo":null}'); - -$request->setRequestUrl('http://mockbin.com/har'); -$request->setRequestMethod('POST'); -$request->setBody($body); - -$request->setHeaders(array( - 'content-type' => 'application/json' -)); - -$client->enqueue($request)->send(); -$response = $client->getResponse(); - -echo $response->getBody(); diff --git a/test/fixtures/output/php/http2/multipart-data.php b/test/fixtures/output/php/http2/multipart-data.php deleted file mode 100644 index 8ec5acf35..000000000 --- a/test/fixtures/output/php/http2/multipart-data.php +++ /dev/null @@ -1,23 +0,0 @@ -addForm(NULL, array( - array( - 'name' => 'foo', - 'type' => 'text/plain', - 'file' => 'hello.txt', - 'data' => 'Hello World' - ) -)); - -$request->setRequestUrl('http://mockbin.com/har'); -$request->setRequestMethod('POST'); -$request->setBody($body); - -$client->enqueue($request)->send(); -$response = $client->getResponse(); - -echo $response->getBody(); diff --git a/test/fixtures/output/php/http2/multipart-file.php b/test/fixtures/output/php/http2/multipart-file.php deleted file mode 100644 index 2fbb7db52..000000000 --- a/test/fixtures/output/php/http2/multipart-file.php +++ /dev/null @@ -1,23 +0,0 @@ -addForm(NULL, array( - array( - 'name' => 'foo', - 'type' => 'text/plain', - 'file' => 'test/fixtures/files/hello.txt', - 'data' => null - ) -)); - -$request->setRequestUrl('http://mockbin.com/har'); -$request->setRequestMethod('POST'); -$request->setBody($body); - -$client->enqueue($request)->send(); -$response = $client->getResponse(); - -echo $response->getBody(); diff --git a/test/fixtures/output/php/http2/multipart-form-data.php b/test/fixtures/output/php/http2/multipart-form-data.php deleted file mode 100644 index ba2799d53..000000000 --- a/test/fixtures/output/php/http2/multipart-form-data.php +++ /dev/null @@ -1,18 +0,0 @@ -addForm(array( - 'foo' => 'bar' -), NULL); - -$request->setRequestUrl('http://mockbin.com/har'); -$request->setRequestMethod('POST'); -$request->setBody($body); - -$client->enqueue($request)->send(); -$response = $client->getResponse(); - -echo $response->getBody(); diff --git a/test/fixtures/output/php/http2/query.php b/test/fixtures/output/php/http2/query.php deleted file mode 100644 index effd119a5..000000000 --- a/test/fixtures/output/php/http2/query.php +++ /dev/null @@ -1,20 +0,0 @@ -setRequestUrl('http://mockbin.com/har'); -$request->setRequestMethod('GET'); -$request->setQuery(new http\QueryString(array( - 'foo' => array( - 'bar', - 'baz' - ), - 'baz' => 'abc', - 'key' => 'value' -))); - -$client->enqueue($request)->send(); -$response = $client->getResponse(); - -echo $response->getBody(); diff --git a/test/fixtures/output/php/http2/short.php b/test/fixtures/output/php/http2/short.php deleted file mode 100644 index 1f4dba9a7..000000000 --- a/test/fixtures/output/php/http2/short.php +++ /dev/null @@ -1,11 +0,0 @@ -setRequestUrl('http://mockbin.com/har'); -$request->setRequestMethod('GET'); -$client->enqueue($request)->send(); -$response = $client->getResponse(); - -echo $response->getBody(); diff --git a/test/fixtures/output/php/http2/text-plain.php b/test/fixtures/output/php/http2/text-plain.php deleted file mode 100644 index 099e9c5a3..000000000 --- a/test/fixtures/output/php/http2/text-plain.php +++ /dev/null @@ -1,20 +0,0 @@ -append('Hello World'); - -$request->setRequestUrl('http://mockbin.com/har'); -$request->setRequestMethod('POST'); -$request->setBody($body); - -$request->setHeaders(array( - 'content-type' => 'text/plain' -)); - -$client->enqueue($request)->send(); -$response = $client->getResponse(); - -echo $response->getBody(); diff --git a/test/fixtures/output/python/python3/application-form-encoded.py b/test/fixtures/output/python/python3/application-form-encoded.py deleted file mode 100644 index e7857cbff..000000000 --- a/test/fixtures/output/python/python3/application-form-encoded.py +++ /dev/null @@ -1,14 +0,0 @@ -import http.client - -conn = http.client.HTTPConnection("mockbin.com") - -payload = "foo=bar&hello=world" - -headers = { 'content-type': "application/x-www-form-urlencoded" } - -conn.request("POST", "/har", payload, headers) - -res = conn.getresponse() -data = res.read() - -print(data.decode("utf-8")) diff --git a/test/fixtures/output/python/python3/application-json.py b/test/fixtures/output/python/python3/application-json.py deleted file mode 100644 index ce36a23d8..000000000 --- a/test/fixtures/output/python/python3/application-json.py +++ /dev/null @@ -1,14 +0,0 @@ -import http.client - -conn = http.client.HTTPConnection("mockbin.com") - -payload = "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":{}}],\"boolean\":false}" - -headers = { 'content-type': "application/json" } - -conn.request("POST", "/har", payload, headers) - -res = conn.getresponse() -data = res.read() - -print(data.decode("utf-8")) diff --git a/test/fixtures/output/python/python3/cookies.py b/test/fixtures/output/python/python3/cookies.py deleted file mode 100644 index 46530ca7a..000000000 --- a/test/fixtures/output/python/python3/cookies.py +++ /dev/null @@ -1,12 +0,0 @@ -import http.client - -conn = http.client.HTTPConnection("mockbin.com") - -headers = { 'cookie': "foo=bar; bar=baz" } - -conn.request("POST", "/har", headers=headers) - -res = conn.getresponse() -data = res.read() - -print(data.decode("utf-8")) diff --git a/test/fixtures/output/python/python3/custom-method.py b/test/fixtures/output/python/python3/custom-method.py deleted file mode 100644 index 0f510e377..000000000 --- a/test/fixtures/output/python/python3/custom-method.py +++ /dev/null @@ -1,10 +0,0 @@ -import http.client - -conn = http.client.HTTPConnection("mockbin.com") - -conn.request("PROPFIND", "/har") - -res = conn.getresponse() -data = res.read() - -print(data.decode("utf-8")) diff --git a/test/fixtures/output/python/python3/full.py b/test/fixtures/output/python/python3/full.py deleted file mode 100644 index 6329ea984..000000000 --- a/test/fixtures/output/python/python3/full.py +++ /dev/null @@ -1,18 +0,0 @@ -import http.client - -conn = http.client.HTTPConnection("mockbin.com") - -payload = "foo=bar" - -headers = { - 'cookie': "foo=bar; bar=baz", - 'accept': "application/json", - 'content-type': "application/x-www-form-urlencoded" - } - -conn.request("POST", "/har?foo=bar&foo=baz&baz=abc&key=value", payload, headers) - -res = conn.getresponse() -data = res.read() - -print(data.decode("utf-8")) diff --git a/test/fixtures/output/python/python3/headers.py b/test/fixtures/output/python/python3/headers.py deleted file mode 100644 index fc2004476..000000000 --- a/test/fixtures/output/python/python3/headers.py +++ /dev/null @@ -1,15 +0,0 @@ -import http.client - -conn = http.client.HTTPConnection("mockbin.com") - -headers = { - 'accept': "application/json", - 'x-foo': "Bar" - } - -conn.request("GET", "/har", headers=headers) - -res = conn.getresponse() -data = res.read() - -print(data.decode("utf-8")) diff --git a/test/fixtures/output/python/python3/https.py b/test/fixtures/output/python/python3/https.py deleted file mode 100644 index f9df79d35..000000000 --- a/test/fixtures/output/python/python3/https.py +++ /dev/null @@ -1,10 +0,0 @@ -import http.client - -conn = http.client.HTTPSConnection("mockbin.com") - -conn.request("GET", "/har") - -res = conn.getresponse() -data = res.read() - -print(data.decode("utf-8")) diff --git a/test/fixtures/output/python/python3/jsonObj-null-value.py b/test/fixtures/output/python/python3/jsonObj-null-value.py deleted file mode 100644 index 99249bf2e..000000000 --- a/test/fixtures/output/python/python3/jsonObj-null-value.py +++ /dev/null @@ -1,14 +0,0 @@ -import http.client - -conn = http.client.HTTPConnection("mockbin.com") - -payload = "{\"foo\":null}" - -headers = { 'content-type': "application/json" } - -conn.request("POST", "/har", payload, headers) - -res = conn.getresponse() -data = res.read() - -print(data.decode("utf-8")) diff --git a/test/fixtures/output/python/python3/multipart-data.py b/test/fixtures/output/python/python3/multipart-data.py deleted file mode 100644 index 7ed5b404e..000000000 --- a/test/fixtures/output/python/python3/multipart-data.py +++ /dev/null @@ -1,14 +0,0 @@ -import http.client - -conn = http.client.HTTPConnection("mockbin.com") - -payload = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001--\r\n" - -headers = { 'content-type': "multipart/form-data; boundary=---011000010111000001101001" } - -conn.request("POST", "/har", payload, headers) - -res = conn.getresponse() -data = res.read() - -print(data.decode("utf-8")) diff --git a/test/fixtures/output/python/python3/multipart-file.py b/test/fixtures/output/python/python3/multipart-file.py deleted file mode 100644 index 681ec08c2..000000000 --- a/test/fixtures/output/python/python3/multipart-file.py +++ /dev/null @@ -1,14 +0,0 @@ -import http.client - -conn = http.client.HTTPConnection("mockbin.com") - -payload = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--\r\n" - -headers = { 'content-type': "multipart/form-data; boundary=---011000010111000001101001" } - -conn.request("POST", "/har", payload, headers) - -res = conn.getresponse() -data = res.read() - -print(data.decode("utf-8")) diff --git a/test/fixtures/output/python/python3/multipart-form-data.py b/test/fixtures/output/python/python3/multipart-form-data.py deleted file mode 100644 index 42bb17546..000000000 --- a/test/fixtures/output/python/python3/multipart-form-data.py +++ /dev/null @@ -1,14 +0,0 @@ -import http.client - -conn = http.client.HTTPConnection("mockbin.com") - -payload = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--\r\n" - -headers = { 'content-type': "multipart/form-data; boundary=---011000010111000001101001" } - -conn.request("POST", "/har", payload, headers) - -res = conn.getresponse() -data = res.read() - -print(data.decode("utf-8")) diff --git a/test/fixtures/output/python/python3/query.py b/test/fixtures/output/python/python3/query.py deleted file mode 100644 index d882e3b42..000000000 --- a/test/fixtures/output/python/python3/query.py +++ /dev/null @@ -1,10 +0,0 @@ -import http.client - -conn = http.client.HTTPConnection("mockbin.com") - -conn.request("GET", "/har?foo=bar&foo=baz&baz=abc&key=value") - -res = conn.getresponse() -data = res.read() - -print(data.decode("utf-8")) diff --git a/test/fixtures/output/python/python3/short.py b/test/fixtures/output/python/python3/short.py deleted file mode 100644 index e8e657f80..000000000 --- a/test/fixtures/output/python/python3/short.py +++ /dev/null @@ -1,10 +0,0 @@ -import http.client - -conn = http.client.HTTPConnection("mockbin.com") - -conn.request("GET", "/har") - -res = conn.getresponse() -data = res.read() - -print(data.decode("utf-8")) diff --git a/test/fixtures/output/python/python3/text-plain.py b/test/fixtures/output/python/python3/text-plain.py deleted file mode 100644 index f00466b98..000000000 --- a/test/fixtures/output/python/python3/text-plain.py +++ /dev/null @@ -1,14 +0,0 @@ -import http.client - -conn = http.client.HTTPConnection("mockbin.com") - -payload = "Hello World" - -headers = { 'content-type': "text/plain" } - -conn.request("POST", "/har", payload, headers) - -res = conn.getresponse() -data = res.read() - -print(data.decode("utf-8")) diff --git a/test/fixtures/output/python/requests/application-form-encoded.py b/test/fixtures/output/python/requests/application-form-encoded.py deleted file mode 100644 index 54556d0f1..000000000 --- a/test/fixtures/output/python/requests/application-form-encoded.py +++ /dev/null @@ -1,10 +0,0 @@ -import requests - -url = "http://mockbin.com/har" - -payload = "foo=bar&hello=world" -headers = {'content-type': 'application/x-www-form-urlencoded'} - -response = requests.request("POST", url, data=payload, headers=headers) - -print(response.text) diff --git a/test/fixtures/output/python/requests/application-json.py b/test/fixtures/output/python/requests/application-json.py deleted file mode 100644 index a60dcd215..000000000 --- a/test/fixtures/output/python/requests/application-json.py +++ /dev/null @@ -1,10 +0,0 @@ -import requests - -url = "http://mockbin.com/har" - -payload = "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":{}}],\"boolean\":false}" -headers = {'content-type': 'application/json'} - -response = requests.request("POST", url, data=payload, headers=headers) - -print(response.text) diff --git a/test/fixtures/output/python/requests/cookies.py b/test/fixtures/output/python/requests/cookies.py deleted file mode 100644 index 96977a509..000000000 --- a/test/fixtures/output/python/requests/cookies.py +++ /dev/null @@ -1,9 +0,0 @@ -import requests - -url = "http://mockbin.com/har" - -headers = {'cookie': 'foo=bar; bar=baz'} - -response = requests.request("POST", url, headers=headers) - -print(response.text) diff --git a/test/fixtures/output/python/requests/custom-method.py b/test/fixtures/output/python/requests/custom-method.py deleted file mode 100644 index 8a848a56d..000000000 --- a/test/fixtures/output/python/requests/custom-method.py +++ /dev/null @@ -1,7 +0,0 @@ -import requests - -url = "http://mockbin.com/har" - -response = requests.request("PROPFIND", url) - -print(response.text) diff --git a/test/fixtures/output/python/requests/full.py b/test/fixtures/output/python/requests/full.py deleted file mode 100644 index 621d12a22..000000000 --- a/test/fixtures/output/python/requests/full.py +++ /dev/null @@ -1,16 +0,0 @@ -import requests - -url = "http://mockbin.com/har" - -querystring = {"foo":["bar","baz"],"baz":"abc","key":"value"} - -payload = "foo=bar" -headers = { - 'cookie': "foo=bar; bar=baz", - 'accept': "application/json", - 'content-type': "application/x-www-form-urlencoded" - } - -response = requests.request("POST", url, data=payload, headers=headers, params=querystring) - -print(response.text) diff --git a/test/fixtures/output/python/requests/headers.py b/test/fixtures/output/python/requests/headers.py deleted file mode 100644 index 847323fb6..000000000 --- a/test/fixtures/output/python/requests/headers.py +++ /dev/null @@ -1,12 +0,0 @@ -import requests - -url = "http://mockbin.com/har" - -headers = { - 'accept': "application/json", - 'x-foo': "Bar" - } - -response = requests.request("GET", url, headers=headers) - -print(response.text) diff --git a/test/fixtures/output/python/requests/https.py b/test/fixtures/output/python/requests/https.py deleted file mode 100644 index af4660bfb..000000000 --- a/test/fixtures/output/python/requests/https.py +++ /dev/null @@ -1,7 +0,0 @@ -import requests - -url = "https://mockbin.com/har" - -response = requests.request("GET", url) - -print(response.text) diff --git a/test/fixtures/output/python/requests/jsonObj-null-value.py b/test/fixtures/output/python/requests/jsonObj-null-value.py deleted file mode 100644 index 99d3a6bcc..000000000 --- a/test/fixtures/output/python/requests/jsonObj-null-value.py +++ /dev/null @@ -1,10 +0,0 @@ -import requests - -url = "http://mockbin.com/har" - -payload = "{\"foo\":null}" -headers = {'content-type': 'application/json'} - -response = requests.request("POST", url, data=payload, headers=headers) - -print(response.text) diff --git a/test/fixtures/output/python/requests/multipart-data.py b/test/fixtures/output/python/requests/multipart-data.py deleted file mode 100644 index 4b9cc5c81..000000000 --- a/test/fixtures/output/python/requests/multipart-data.py +++ /dev/null @@ -1,10 +0,0 @@ -import requests - -url = "http://mockbin.com/har" - -payload = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001--\r\n" -headers = {'content-type': 'multipart/form-data; boundary=---011000010111000001101001'} - -response = requests.request("POST", url, data=payload, headers=headers) - -print(response.text) diff --git a/test/fixtures/output/python/requests/multipart-file.py b/test/fixtures/output/python/requests/multipart-file.py deleted file mode 100644 index 5c3188b84..000000000 --- a/test/fixtures/output/python/requests/multipart-file.py +++ /dev/null @@ -1,10 +0,0 @@ -import requests - -url = "http://mockbin.com/har" - -payload = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--\r\n" -headers = {'content-type': 'multipart/form-data; boundary=---011000010111000001101001'} - -response = requests.request("POST", url, data=payload, headers=headers) - -print(response.text) diff --git a/test/fixtures/output/python/requests/multipart-form-data.py b/test/fixtures/output/python/requests/multipart-form-data.py deleted file mode 100644 index 77bbb3438..000000000 --- a/test/fixtures/output/python/requests/multipart-form-data.py +++ /dev/null @@ -1,10 +0,0 @@ -import requests - -url = "http://mockbin.com/har" - -payload = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--\r\n" -headers = {'content-type': 'multipart/form-data; boundary=---011000010111000001101001'} - -response = requests.request("POST", url, data=payload, headers=headers) - -print(response.text) diff --git a/test/fixtures/output/python/requests/query.py b/test/fixtures/output/python/requests/query.py deleted file mode 100644 index 8ba063238..000000000 --- a/test/fixtures/output/python/requests/query.py +++ /dev/null @@ -1,9 +0,0 @@ -import requests - -url = "http://mockbin.com/har" - -querystring = {"foo":["bar","baz"],"baz":"abc","key":"value"} - -response = requests.request("GET", url, params=querystring) - -print(response.text) diff --git a/test/fixtures/output/python/requests/short.py b/test/fixtures/output/python/requests/short.py deleted file mode 100644 index 58f057e8b..000000000 --- a/test/fixtures/output/python/requests/short.py +++ /dev/null @@ -1,7 +0,0 @@ -import requests - -url = "http://mockbin.com/har" - -response = requests.request("GET", url) - -print(response.text) diff --git a/test/fixtures/output/python/requests/text-plain.py b/test/fixtures/output/python/requests/text-plain.py deleted file mode 100644 index ba42964e3..000000000 --- a/test/fixtures/output/python/requests/text-plain.py +++ /dev/null @@ -1,10 +0,0 @@ -import requests - -url = "http://mockbin.com/har" - -payload = "Hello World" -headers = {'content-type': 'text/plain'} - -response = requests.request("POST", url, data=payload, headers=headers) - -print(response.text) diff --git a/test/fixtures/output/ruby/native/application-form-encoded.rb b/test/fixtures/output/ruby/native/application-form-encoded.rb deleted file mode 100644 index b22b26b52..000000000 --- a/test/fixtures/output/ruby/native/application-form-encoded.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'uri' -require 'net/http' - -url = URI("http://mockbin.com/har") - -http = Net::HTTP.new(url.host, url.port) - -request = Net::HTTP::Post.new(url) -request["content-type"] = 'application/x-www-form-urlencoded' -request.body = "foo=bar&hello=world" - -response = http.request(request) -puts response.read_body diff --git a/test/fixtures/output/ruby/native/application-json.rb b/test/fixtures/output/ruby/native/application-json.rb deleted file mode 100644 index 78c310fa8..000000000 --- a/test/fixtures/output/ruby/native/application-json.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'uri' -require 'net/http' - -url = URI("http://mockbin.com/har") - -http = Net::HTTP.new(url.host, url.port) - -request = Net::HTTP::Post.new(url) -request["content-type"] = 'application/json' -request.body = "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":{}}],\"boolean\":false}" - -response = http.request(request) -puts response.read_body diff --git a/test/fixtures/output/ruby/native/cookies.rb b/test/fixtures/output/ruby/native/cookies.rb deleted file mode 100644 index 3283fafca..000000000 --- a/test/fixtures/output/ruby/native/cookies.rb +++ /dev/null @@ -1,12 +0,0 @@ -require 'uri' -require 'net/http' - -url = URI("http://mockbin.com/har") - -http = Net::HTTP.new(url.host, url.port) - -request = Net::HTTP::Post.new(url) -request["cookie"] = 'foo=bar; bar=baz' - -response = http.request(request) -puts response.read_body diff --git a/test/fixtures/output/ruby/native/full.rb b/test/fixtures/output/ruby/native/full.rb deleted file mode 100644 index 992c58642..000000000 --- a/test/fixtures/output/ruby/native/full.rb +++ /dev/null @@ -1,15 +0,0 @@ -require 'uri' -require 'net/http' - -url = URI("http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value") - -http = Net::HTTP.new(url.host, url.port) - -request = Net::HTTP::Post.new(url) -request["cookie"] = 'foo=bar; bar=baz' -request["accept"] = 'application/json' -request["content-type"] = 'application/x-www-form-urlencoded' -request.body = "foo=bar" - -response = http.request(request) -puts response.read_body diff --git a/test/fixtures/output/ruby/native/headers.rb b/test/fixtures/output/ruby/native/headers.rb deleted file mode 100644 index f2a4dba9a..000000000 --- a/test/fixtures/output/ruby/native/headers.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'uri' -require 'net/http' - -url = URI("http://mockbin.com/har") - -http = Net::HTTP.new(url.host, url.port) - -request = Net::HTTP::Get.new(url) -request["accept"] = 'application/json' -request["x-foo"] = 'Bar' - -response = http.request(request) -puts response.read_body diff --git a/test/fixtures/output/ruby/native/https.rb b/test/fixtures/output/ruby/native/https.rb deleted file mode 100644 index 51fbc6166..000000000 --- a/test/fixtures/output/ruby/native/https.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'uri' -require 'net/http' - -url = URI("https://mockbin.com/har") - -http = Net::HTTP.new(url.host, url.port) -http.use_ssl = true -http.verify_mode = OpenSSL::SSL::VERIFY_NONE - -request = Net::HTTP::Get.new(url) - -response = http.request(request) -puts response.read_body diff --git a/test/fixtures/output/ruby/native/jsonObj-null-value.rb b/test/fixtures/output/ruby/native/jsonObj-null-value.rb deleted file mode 100644 index b73ffff47..000000000 --- a/test/fixtures/output/ruby/native/jsonObj-null-value.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'uri' -require 'net/http' - -url = URI("http://mockbin.com/har") - -http = Net::HTTP.new(url.host, url.port) - -request = Net::HTTP::Post.new(url) -request["content-type"] = 'application/json' -request.body = "{\"foo\":null}" - -response = http.request(request) -puts response.read_body diff --git a/test/fixtures/output/ruby/native/multipart-data.rb b/test/fixtures/output/ruby/native/multipart-data.rb deleted file mode 100644 index 4b5613fde..000000000 --- a/test/fixtures/output/ruby/native/multipart-data.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'uri' -require 'net/http' - -url = URI("http://mockbin.com/har") - -http = Net::HTTP.new(url.host, url.port) - -request = Net::HTTP::Post.new(url) -request["content-type"] = 'multipart/form-data; boundary=---011000010111000001101001' -request.body = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001--\r\n" - -response = http.request(request) -puts response.read_body diff --git a/test/fixtures/output/ruby/native/multipart-file.rb b/test/fixtures/output/ruby/native/multipart-file.rb deleted file mode 100644 index bbf6c8845..000000000 --- a/test/fixtures/output/ruby/native/multipart-file.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'uri' -require 'net/http' - -url = URI("http://mockbin.com/har") - -http = Net::HTTP.new(url.host, url.port) - -request = Net::HTTP::Post.new(url) -request["content-type"] = 'multipart/form-data; boundary=---011000010111000001101001' -request.body = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--\r\n" - -response = http.request(request) -puts response.read_body diff --git a/test/fixtures/output/ruby/native/multipart-form-data.rb b/test/fixtures/output/ruby/native/multipart-form-data.rb deleted file mode 100644 index 60d18faf3..000000000 --- a/test/fixtures/output/ruby/native/multipart-form-data.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'uri' -require 'net/http' - -url = URI("http://mockbin.com/har") - -http = Net::HTTP.new(url.host, url.port) - -request = Net::HTTP::Post.new(url) -request["content-type"] = 'multipart/form-data; boundary=---011000010111000001101001' -request.body = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--\r\n" - -response = http.request(request) -puts response.read_body diff --git a/test/fixtures/output/ruby/native/query.rb b/test/fixtures/output/ruby/native/query.rb deleted file mode 100644 index ef6881c28..000000000 --- a/test/fixtures/output/ruby/native/query.rb +++ /dev/null @@ -1,11 +0,0 @@ -require 'uri' -require 'net/http' - -url = URI("http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value") - -http = Net::HTTP.new(url.host, url.port) - -request = Net::HTTP::Get.new(url) - -response = http.request(request) -puts response.read_body diff --git a/test/fixtures/output/ruby/native/short.rb b/test/fixtures/output/ruby/native/short.rb deleted file mode 100644 index 7761eb998..000000000 --- a/test/fixtures/output/ruby/native/short.rb +++ /dev/null @@ -1,11 +0,0 @@ -require 'uri' -require 'net/http' - -url = URI("http://mockbin.com/har") - -http = Net::HTTP.new(url.host, url.port) - -request = Net::HTTP::Get.new(url) - -response = http.request(request) -puts response.read_body diff --git a/test/fixtures/output/ruby/native/text-plain.rb b/test/fixtures/output/ruby/native/text-plain.rb deleted file mode 100644 index 813c15ac1..000000000 --- a/test/fixtures/output/ruby/native/text-plain.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'uri' -require 'net/http' - -url = URI("http://mockbin.com/har") - -http = Net::HTTP.new(url.host, url.port) - -request = Net::HTTP::Post.new(url) -request["content-type"] = 'text/plain' -request.body = "Hello World" - -response = http.request(request) -puts response.read_body diff --git a/test/fixtures/output/shell/curl/application-form-encoded.sh b/test/fixtures/output/shell/curl/application-form-encoded.sh deleted file mode 100644 index c1bc4fb32..000000000 --- a/test/fixtures/output/shell/curl/application-form-encoded.sh +++ /dev/null @@ -1,5 +0,0 @@ -curl --request POST \ - --url http://mockbin.com/har \ - --header 'content-type: application/x-www-form-urlencoded' \ - --data foo=bar \ - --data hello=world diff --git a/test/fixtures/output/shell/curl/application-json.sh b/test/fixtures/output/shell/curl/application-json.sh deleted file mode 100644 index f7b19eb9f..000000000 --- a/test/fixtures/output/shell/curl/application-json.sh +++ /dev/null @@ -1,4 +0,0 @@ -curl --request POST \ - --url http://mockbin.com/har \ - --header 'content-type: application/json' \ - --data '{"number":1,"string":"f\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":{}}],"boolean":false}' diff --git a/test/fixtures/output/shell/curl/cookies.sh b/test/fixtures/output/shell/curl/cookies.sh deleted file mode 100644 index 74c6eb12a..000000000 --- a/test/fixtures/output/shell/curl/cookies.sh +++ /dev/null @@ -1,3 +0,0 @@ -curl --request POST \ - --url http://mockbin.com/har \ - --cookie 'foo=bar; bar=baz' diff --git a/test/fixtures/output/shell/curl/custom-method.sh b/test/fixtures/output/shell/curl/custom-method.sh deleted file mode 100644 index e6cef28d8..000000000 --- a/test/fixtures/output/shell/curl/custom-method.sh +++ /dev/null @@ -1,2 +0,0 @@ -curl --request PROPFIND \ - --url http://mockbin.com/har diff --git a/test/fixtures/output/shell/curl/full.sh b/test/fixtures/output/shell/curl/full.sh deleted file mode 100644 index 9d9c396dd..000000000 --- a/test/fixtures/output/shell/curl/full.sh +++ /dev/null @@ -1,6 +0,0 @@ -curl --request POST \ - --url 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' \ - --header 'accept: application/json' \ - --header 'content-type: application/x-www-form-urlencoded' \ - --cookie 'foo=bar; bar=baz' \ - --data foo=bar diff --git a/test/fixtures/output/shell/curl/headers.sh b/test/fixtures/output/shell/curl/headers.sh deleted file mode 100644 index c41513681..000000000 --- a/test/fixtures/output/shell/curl/headers.sh +++ /dev/null @@ -1,4 +0,0 @@ -curl --request GET \ - --url http://mockbin.com/har \ - --header 'accept: application/json' \ - --header 'x-foo: Bar' diff --git a/test/fixtures/output/shell/curl/http1.sh b/test/fixtures/output/shell/curl/http1.sh deleted file mode 100644 index 2dbff472f..000000000 --- a/test/fixtures/output/shell/curl/http1.sh +++ /dev/null @@ -1,3 +0,0 @@ -curl --request GET \ - --url "http://mockbin.com/request" \ - --http1.0 diff --git a/test/fixtures/output/shell/curl/https.sh b/test/fixtures/output/shell/curl/https.sh deleted file mode 100644 index 8acb41f99..000000000 --- a/test/fixtures/output/shell/curl/https.sh +++ /dev/null @@ -1,2 +0,0 @@ -curl --request GET \ - --url https://mockbin.com/har diff --git a/test/fixtures/output/shell/curl/jsonObj-null-value.sh b/test/fixtures/output/shell/curl/jsonObj-null-value.sh deleted file mode 100644 index 51152e664..000000000 --- a/test/fixtures/output/shell/curl/jsonObj-null-value.sh +++ /dev/null @@ -1,4 +0,0 @@ -curl --request POST \ - --url http://mockbin.com/har \ - --header 'content-type: application/json' \ - --data '{"foo":null}' diff --git a/test/fixtures/output/shell/curl/multipart-data.sh b/test/fixtures/output/shell/curl/multipart-data.sh deleted file mode 100644 index 8dee5514c..000000000 --- a/test/fixtures/output/shell/curl/multipart-data.sh +++ /dev/null @@ -1,4 +0,0 @@ -curl --request POST \ - --url http://mockbin.com/har \ - --header 'content-type: multipart/form-data; boundary=---011000010111000001101001' \ - --form 'foo=Hello World' diff --git a/test/fixtures/output/shell/curl/multipart-file.sh b/test/fixtures/output/shell/curl/multipart-file.sh deleted file mode 100644 index e054807c6..000000000 --- a/test/fixtures/output/shell/curl/multipart-file.sh +++ /dev/null @@ -1,4 +0,0 @@ -curl --request POST \ - --url http://mockbin.com/har \ - --header 'content-type: multipart/form-data; boundary=---011000010111000001101001' \ - --form foo=@test/fixtures/files/hello.txt diff --git a/test/fixtures/output/shell/curl/multipart-form-data.sh b/test/fixtures/output/shell/curl/multipart-form-data.sh deleted file mode 100644 index d7b10e7ee..000000000 --- a/test/fixtures/output/shell/curl/multipart-form-data.sh +++ /dev/null @@ -1,4 +0,0 @@ -curl --request POST \ - --url http://mockbin.com/har \ - --header 'content-type: multipart/form-data; boundary=---011000010111000001101001' \ - --form foo=bar diff --git a/test/fixtures/output/shell/curl/query.sh b/test/fixtures/output/shell/curl/query.sh deleted file mode 100644 index 488bd4a18..000000000 --- a/test/fixtures/output/shell/curl/query.sh +++ /dev/null @@ -1,2 +0,0 @@ -curl --request GET \ - --url 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' diff --git a/test/fixtures/output/shell/curl/short.sh b/test/fixtures/output/shell/curl/short.sh deleted file mode 100644 index ffe0460d8..000000000 --- a/test/fixtures/output/shell/curl/short.sh +++ /dev/null @@ -1,2 +0,0 @@ -curl --request GET \ - --url http://mockbin.com/har diff --git a/test/fixtures/output/shell/curl/text-plain.sh b/test/fixtures/output/shell/curl/text-plain.sh deleted file mode 100644 index 511b8f24f..000000000 --- a/test/fixtures/output/shell/curl/text-plain.sh +++ /dev/null @@ -1,4 +0,0 @@ -curl --request POST \ - --url http://mockbin.com/har \ - --header 'content-type: text/plain' \ - --data 'Hello World' diff --git a/test/fixtures/output/shell/httpie/application-form-encoded.sh b/test/fixtures/output/shell/httpie/application-form-encoded.sh deleted file mode 100644 index e7bb5a320..000000000 --- a/test/fixtures/output/shell/httpie/application-form-encoded.sh +++ /dev/null @@ -1,4 +0,0 @@ -http --form POST http://mockbin.com/har \ - content-type:application/x-www-form-urlencoded \ - foo=bar \ - hello=world diff --git a/test/fixtures/output/shell/httpie/application-json.sh b/test/fixtures/output/shell/httpie/application-json.sh deleted file mode 100644 index 073a2583c..000000000 --- a/test/fixtures/output/shell/httpie/application-json.sh +++ /dev/null @@ -1,3 +0,0 @@ -echo '{"number":1,"string":"f\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":{}}],"boolean":false}' | \ - http POST http://mockbin.com/har \ - content-type:application/json diff --git a/test/fixtures/output/shell/httpie/cookies.sh b/test/fixtures/output/shell/httpie/cookies.sh deleted file mode 100644 index 791a3f58a..000000000 --- a/test/fixtures/output/shell/httpie/cookies.sh +++ /dev/null @@ -1,2 +0,0 @@ -http POST http://mockbin.com/har \ - cookie:'foo=bar; bar=baz' diff --git a/test/fixtures/output/shell/httpie/custom-method.sh b/test/fixtures/output/shell/httpie/custom-method.sh deleted file mode 100644 index 296e12b74..000000000 --- a/test/fixtures/output/shell/httpie/custom-method.sh +++ /dev/null @@ -1 +0,0 @@ -http PROPFIND http://mockbin.com/har diff --git a/test/fixtures/output/shell/httpie/full.sh b/test/fixtures/output/shell/httpie/full.sh deleted file mode 100644 index ede01f420..000000000 --- a/test/fixtures/output/shell/httpie/full.sh +++ /dev/null @@ -1,5 +0,0 @@ -http --form POST 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' \ - accept:application/json \ - content-type:application/x-www-form-urlencoded \ - cookie:'foo=bar; bar=baz' \ - foo=bar diff --git a/test/fixtures/output/shell/httpie/headers.sh b/test/fixtures/output/shell/httpie/headers.sh deleted file mode 100644 index 427ae7840..000000000 --- a/test/fixtures/output/shell/httpie/headers.sh +++ /dev/null @@ -1,3 +0,0 @@ -http GET http://mockbin.com/har \ - accept:application/json \ - x-foo:Bar diff --git a/test/fixtures/output/shell/httpie/https.sh b/test/fixtures/output/shell/httpie/https.sh deleted file mode 100644 index 97035e11f..000000000 --- a/test/fixtures/output/shell/httpie/https.sh +++ /dev/null @@ -1 +0,0 @@ -http GET https://mockbin.com/har diff --git a/test/fixtures/output/shell/httpie/jsonObj-null-value.sh b/test/fixtures/output/shell/httpie/jsonObj-null-value.sh deleted file mode 100644 index a2fd31358..000000000 --- a/test/fixtures/output/shell/httpie/jsonObj-null-value.sh +++ /dev/null @@ -1,3 +0,0 @@ -echo '{"foo":null}' | \ - http POST http://mockbin.com/har \ - content-type:application/json diff --git a/test/fixtures/output/shell/httpie/multipart-data.sh b/test/fixtures/output/shell/httpie/multipart-data.sh deleted file mode 100644 index 5cb1606a1..000000000 --- a/test/fixtures/output/shell/httpie/multipart-data.sh +++ /dev/null @@ -1,9 +0,0 @@ -echo '-----011000010111000001101001 -Content-Disposition: form-data; name="foo"; filename="hello.txt" -Content-Type: text/plain - -Hello World ------011000010111000001101001-- -' | \ - http POST http://mockbin.com/har \ - content-type:'multipart/form-data; boundary=---011000010111000001101001' diff --git a/test/fixtures/output/shell/httpie/multipart-file.sh b/test/fixtures/output/shell/httpie/multipart-file.sh deleted file mode 100644 index 550a40ee1..000000000 --- a/test/fixtures/output/shell/httpie/multipart-file.sh +++ /dev/null @@ -1,9 +0,0 @@ -echo '-----011000010111000001101001 -Content-Disposition: form-data; name="foo"; filename="hello.txt" -Content-Type: text/plain - - ------011000010111000001101001-- -' | \ - http POST http://mockbin.com/har \ - content-type:'multipart/form-data; boundary=---011000010111000001101001' diff --git a/test/fixtures/output/shell/httpie/multipart-form-data.sh b/test/fixtures/output/shell/httpie/multipart-form-data.sh deleted file mode 100644 index a177c60e5..000000000 --- a/test/fixtures/output/shell/httpie/multipart-form-data.sh +++ /dev/null @@ -1,8 +0,0 @@ -echo '-----011000010111000001101001 -Content-Disposition: form-data; name="foo" - -bar ------011000010111000001101001-- -' | \ - http POST http://mockbin.com/har \ - content-type:'multipart/form-data; boundary=---011000010111000001101001' diff --git a/test/fixtures/output/shell/httpie/query.sh b/test/fixtures/output/shell/httpie/query.sh deleted file mode 100644 index a38d1af26..000000000 --- a/test/fixtures/output/shell/httpie/query.sh +++ /dev/null @@ -1 +0,0 @@ -http GET 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' diff --git a/test/fixtures/output/shell/httpie/short.sh b/test/fixtures/output/shell/httpie/short.sh deleted file mode 100644 index bb18e9d36..000000000 --- a/test/fixtures/output/shell/httpie/short.sh +++ /dev/null @@ -1 +0,0 @@ -http GET http://mockbin.com/har diff --git a/test/fixtures/output/shell/httpie/text-plain.sh b/test/fixtures/output/shell/httpie/text-plain.sh deleted file mode 100644 index ac5657d34..000000000 --- a/test/fixtures/output/shell/httpie/text-plain.sh +++ /dev/null @@ -1,3 +0,0 @@ -echo 'Hello World' | \ - http POST http://mockbin.com/har \ - content-type:text/plain diff --git a/test/fixtures/output/shell/wget/application-form-encoded.sh b/test/fixtures/output/shell/wget/application-form-encoded.sh deleted file mode 100644 index a7f1ab106..000000000 --- a/test/fixtures/output/shell/wget/application-form-encoded.sh +++ /dev/null @@ -1,6 +0,0 @@ -wget --quiet \ - --method POST \ - --header 'content-type: application/x-www-form-urlencoded' \ - --body-data 'foo=bar&hello=world' \ - --output-document \ - - http://mockbin.com/har diff --git a/test/fixtures/output/shell/wget/application-json.sh b/test/fixtures/output/shell/wget/application-json.sh deleted file mode 100644 index c89593c15..000000000 --- a/test/fixtures/output/shell/wget/application-json.sh +++ /dev/null @@ -1,6 +0,0 @@ -wget --quiet \ - --method POST \ - --header 'content-type: application/json' \ - --body-data '{"number":1,"string":"f\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":{}}],"boolean":false}' \ - --output-document \ - - http://mockbin.com/har diff --git a/test/fixtures/output/shell/wget/cookies.sh b/test/fixtures/output/shell/wget/cookies.sh deleted file mode 100644 index 797c6baca..000000000 --- a/test/fixtures/output/shell/wget/cookies.sh +++ /dev/null @@ -1,5 +0,0 @@ -wget --quiet \ - --method POST \ - --header 'cookie: foo=bar; bar=baz' \ - --output-document \ - - http://mockbin.com/har diff --git a/test/fixtures/output/shell/wget/custom-method.sh b/test/fixtures/output/shell/wget/custom-method.sh deleted file mode 100644 index 3faea5fe1..000000000 --- a/test/fixtures/output/shell/wget/custom-method.sh +++ /dev/null @@ -1,4 +0,0 @@ -wget --quiet \ - --method PROPFIND \ - --output-document \ - - http://mockbin.com/har diff --git a/test/fixtures/output/shell/wget/full.sh b/test/fixtures/output/shell/wget/full.sh deleted file mode 100644 index e15037a97..000000000 --- a/test/fixtures/output/shell/wget/full.sh +++ /dev/null @@ -1,8 +0,0 @@ -wget --quiet \ - --method POST \ - --header 'cookie: foo=bar; bar=baz' \ - --header 'accept: application/json' \ - --header 'content-type: application/x-www-form-urlencoded' \ - --body-data foo=bar \ - --output-document \ - - 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' diff --git a/test/fixtures/output/shell/wget/headers.sh b/test/fixtures/output/shell/wget/headers.sh deleted file mode 100644 index e39f0904d..000000000 --- a/test/fixtures/output/shell/wget/headers.sh +++ /dev/null @@ -1,6 +0,0 @@ -wget --quiet \ - --method GET \ - --header 'accept: application/json' \ - --header 'x-foo: Bar' \ - --output-document \ - - http://mockbin.com/har diff --git a/test/fixtures/output/shell/wget/https.sh b/test/fixtures/output/shell/wget/https.sh deleted file mode 100644 index 590a3f02a..000000000 --- a/test/fixtures/output/shell/wget/https.sh +++ /dev/null @@ -1,4 +0,0 @@ -wget --quiet \ - --method GET \ - --output-document \ - - https://mockbin.com/har diff --git a/test/fixtures/output/shell/wget/jsonObj-null-value.sh b/test/fixtures/output/shell/wget/jsonObj-null-value.sh deleted file mode 100644 index cec705118..000000000 --- a/test/fixtures/output/shell/wget/jsonObj-null-value.sh +++ /dev/null @@ -1,6 +0,0 @@ -wget --quiet \ - --method POST \ - --header 'content-type: application/json' \ - --body-data '{"foo":null}' \ - --output-document \ - - http://mockbin.com/har diff --git a/test/fixtures/output/shell/wget/multipart-data.sh b/test/fixtures/output/shell/wget/multipart-data.sh deleted file mode 100644 index 77cf09f86..000000000 --- a/test/fixtures/output/shell/wget/multipart-data.sh +++ /dev/null @@ -1,6 +0,0 @@ -wget --quiet \ - --method POST \ - --header 'content-type: multipart/form-data; boundary=---011000010111000001101001' \ - --body-data '-----011000010111000001101001\r\nContent-Disposition: form-data; name="foo"; filename="hello.txt"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001--\r\n' \ - --output-document \ - - http://mockbin.com/har diff --git a/test/fixtures/output/shell/wget/multipart-file.sh b/test/fixtures/output/shell/wget/multipart-file.sh deleted file mode 100644 index cc997764f..000000000 --- a/test/fixtures/output/shell/wget/multipart-file.sh +++ /dev/null @@ -1,6 +0,0 @@ -wget --quiet \ - --method POST \ - --header 'content-type: multipart/form-data; boundary=---011000010111000001101001' \ - --body-data '-----011000010111000001101001\r\nContent-Disposition: form-data; name="foo"; filename="hello.txt"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--\r\n' \ - --output-document \ - - http://mockbin.com/har diff --git a/test/fixtures/output/shell/wget/multipart-form-data.sh b/test/fixtures/output/shell/wget/multipart-form-data.sh deleted file mode 100644 index 8ccf44a74..000000000 --- a/test/fixtures/output/shell/wget/multipart-form-data.sh +++ /dev/null @@ -1,6 +0,0 @@ -wget --quiet \ - --method POST \ - --header 'content-type: multipart/form-data; boundary=---011000010111000001101001' \ - --body-data '-----011000010111000001101001\r\nContent-Disposition: form-data; name="foo"\r\n\r\nbar\r\n-----011000010111000001101001--\r\n' \ - --output-document \ - - http://mockbin.com/har diff --git a/test/fixtures/output/shell/wget/query.sh b/test/fixtures/output/shell/wget/query.sh deleted file mode 100644 index 4b1097e18..000000000 --- a/test/fixtures/output/shell/wget/query.sh +++ /dev/null @@ -1,4 +0,0 @@ -wget --quiet \ - --method GET \ - --output-document \ - - 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' diff --git a/test/fixtures/output/shell/wget/short.sh b/test/fixtures/output/shell/wget/short.sh deleted file mode 100644 index e2101d85f..000000000 --- a/test/fixtures/output/shell/wget/short.sh +++ /dev/null @@ -1,4 +0,0 @@ -wget --quiet \ - --method GET \ - --output-document \ - - http://mockbin.com/har diff --git a/test/fixtures/output/shell/wget/text-plain.sh b/test/fixtures/output/shell/wget/text-plain.sh deleted file mode 100644 index 754ac9fd0..000000000 --- a/test/fixtures/output/shell/wget/text-plain.sh +++ /dev/null @@ -1,6 +0,0 @@ -wget --quiet \ - --method POST \ - --header 'content-type: text/plain' \ - --body-data 'Hello World' \ - --output-document \ - - http://mockbin.com/har diff --git a/test/fixtures/output/swift/nsurlsession/application-form-encoded.swift b/test/fixtures/output/swift/nsurlsession/application-form-encoded.swift deleted file mode 100644 index d60979ddd..000000000 --- a/test/fixtures/output/swift/nsurlsession/application-form-encoded.swift +++ /dev/null @@ -1,25 +0,0 @@ -import Foundation - -let headers = ["content-type": "application/x-www-form-urlencoded"] - -let postData = NSMutableData(data: "foo=bar".data(using: String.Encoding.utf8)!) -postData.append("&hello=world".data(using: String.Encoding.utf8)!) - -let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, - cachePolicy: .useProtocolCachePolicy, - timeoutInterval: 10.0) -request.httpMethod = "POST" -request.allHTTPHeaderFields = headers -request.httpBody = postData as Data - -let session = URLSession.shared -let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - } else { - let httpResponse = response as? HTTPURLResponse - print(httpResponse) - } -}) - -dataTask.resume() diff --git a/test/fixtures/output/swift/nsurlsession/application-json.swift b/test/fixtures/output/swift/nsurlsession/application-json.swift deleted file mode 100644 index 93825f49b..000000000 --- a/test/fixtures/output/swift/nsurlsession/application-json.swift +++ /dev/null @@ -1,32 +0,0 @@ -import Foundation - -let headers = ["content-type": "application/json"] -let parameters = [ - "number": 1, - "string": "f\"oo", - "arr": [1, 2, 3], - "nested": ["a": "b"], - "arr_mix": [1, "a", ["arr_mix_nested": []]], - "boolean": false -] as [String : Any] - -let postData = JSONSerialization.data(withJSONObject: parameters, options: []) - -let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, - cachePolicy: .useProtocolCachePolicy, - timeoutInterval: 10.0) -request.httpMethod = "POST" -request.allHTTPHeaderFields = headers -request.httpBody = postData as Data - -let session = URLSession.shared -let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - } else { - let httpResponse = response as? HTTPURLResponse - print(httpResponse) - } -}) - -dataTask.resume() diff --git a/test/fixtures/output/swift/nsurlsession/cookies.swift b/test/fixtures/output/swift/nsurlsession/cookies.swift deleted file mode 100644 index 3f1202d46..000000000 --- a/test/fixtures/output/swift/nsurlsession/cookies.swift +++ /dev/null @@ -1,21 +0,0 @@ -import Foundation - -let headers = ["cookie": "foo=bar; bar=baz"] - -let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, - cachePolicy: .useProtocolCachePolicy, - timeoutInterval: 10.0) -request.httpMethod = "POST" -request.allHTTPHeaderFields = headers - -let session = URLSession.shared -let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - } else { - let httpResponse = response as? HTTPURLResponse - print(httpResponse) - } -}) - -dataTask.resume() diff --git a/test/fixtures/output/swift/nsurlsession/custom-method.swift b/test/fixtures/output/swift/nsurlsession/custom-method.swift deleted file mode 100644 index 597a5f8ac..000000000 --- a/test/fixtures/output/swift/nsurlsession/custom-method.swift +++ /dev/null @@ -1,18 +0,0 @@ -import Foundation - -let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, - cachePolicy: .useProtocolCachePolicy, - timeoutInterval: 10.0) -request.httpMethod = "PROPFIND" - -let session = URLSession.shared -let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - } else { - let httpResponse = response as? HTTPURLResponse - print(httpResponse) - } -}) - -dataTask.resume() diff --git a/test/fixtures/output/swift/nsurlsession/full.swift b/test/fixtures/output/swift/nsurlsession/full.swift deleted file mode 100644 index 1d4784ec3..000000000 --- a/test/fixtures/output/swift/nsurlsession/full.swift +++ /dev/null @@ -1,28 +0,0 @@ -import Foundation - -let headers = [ - "cookie": "foo=bar; bar=baz", - "accept": "application/json", - "content-type": "application/x-www-form-urlencoded" -] - -let postData = NSMutableData(data: "foo=bar".data(using: String.Encoding.utf8)!) - -let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value")! as URL, - cachePolicy: .useProtocolCachePolicy, - timeoutInterval: 10.0) -request.httpMethod = "POST" -request.allHTTPHeaderFields = headers -request.httpBody = postData as Data - -let session = URLSession.shared -let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - } else { - let httpResponse = response as? HTTPURLResponse - print(httpResponse) - } -}) - -dataTask.resume() diff --git a/test/fixtures/output/swift/nsurlsession/headers.swift b/test/fixtures/output/swift/nsurlsession/headers.swift deleted file mode 100644 index 8902e1ace..000000000 --- a/test/fixtures/output/swift/nsurlsession/headers.swift +++ /dev/null @@ -1,24 +0,0 @@ -import Foundation - -let headers = [ - "accept": "application/json", - "x-foo": "Bar" -] - -let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, - cachePolicy: .useProtocolCachePolicy, - timeoutInterval: 10.0) -request.httpMethod = "GET" -request.allHTTPHeaderFields = headers - -let session = URLSession.shared -let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - } else { - let httpResponse = response as? HTTPURLResponse - print(httpResponse) - } -}) - -dataTask.resume() diff --git a/test/fixtures/output/swift/nsurlsession/https.swift b/test/fixtures/output/swift/nsurlsession/https.swift deleted file mode 100644 index 8a4313cb4..000000000 --- a/test/fixtures/output/swift/nsurlsession/https.swift +++ /dev/null @@ -1,18 +0,0 @@ -import Foundation - -let request = NSMutableURLRequest(url: NSURL(string: "https://mockbin.com/har")! as URL, - cachePolicy: .useProtocolCachePolicy, - timeoutInterval: 10.0) -request.httpMethod = "GET" - -let session = URLSession.shared -let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - } else { - let httpResponse = response as? HTTPURLResponse - print(httpResponse) - } -}) - -dataTask.resume() diff --git a/test/fixtures/output/swift/nsurlsession/jsonObj-null-value.swift b/test/fixtures/output/swift/nsurlsession/jsonObj-null-value.swift deleted file mode 100644 index a9b5aeeaa..000000000 --- a/test/fixtures/output/swift/nsurlsession/jsonObj-null-value.swift +++ /dev/null @@ -1,25 +0,0 @@ -import Foundation - -let headers = ["content-type": "application/json"] -let parameters = ["foo": ] as [String : Any] - -let postData = JSONSerialization.data(withJSONObject: parameters, options: []) - -let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, - cachePolicy: .useProtocolCachePolicy, - timeoutInterval: 10.0) -request.httpMethod = "POST" -request.allHTTPHeaderFields = headers -request.httpBody = postData as Data - -let session = URLSession.shared -let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - } else { - let httpResponse = response as? HTTPURLResponse - print(httpResponse) - } -}) - -dataTask.resume() diff --git a/test/fixtures/output/swift/nsurlsession/multipart-data.swift b/test/fixtures/output/swift/nsurlsession/multipart-data.swift deleted file mode 100644 index 0bcf1a3d6..000000000 --- a/test/fixtures/output/swift/nsurlsession/multipart-data.swift +++ /dev/null @@ -1,52 +0,0 @@ -import Foundation - -let headers = ["content-type": "multipart/form-data; boundary=---011000010111000001101001"] -let parameters = [ - [ - "name": "foo", - "value": "Hello World", - "fileName": "hello.txt", - "contentType": "text/plain" - ] -] - -let boundary = "---011000010111000001101001" - -var body = "" -var error: NSError? = nil -for param in parameters { - let paramName = param["name"]! - body += "--\(boundary)\r\n" - body += "Content-Disposition:form-data; name=\"\(paramName)\"" - if let filename = param["fileName"] { - let contentType = param["content-type"]! - let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8) - if (error != nil) { - print(error) - } - body += "; filename=\"\(filename)\"\r\n" - body += "Content-Type: \(contentType)\r\n\r\n" - body += fileContent - } else if let paramValue = param["value"] { - body += "\r\n\r\n\(paramValue)" - } -} - -let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, - cachePolicy: .useProtocolCachePolicy, - timeoutInterval: 10.0) -request.httpMethod = "POST" -request.allHTTPHeaderFields = headers -request.httpBody = postData as Data - -let session = URLSession.shared -let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - } else { - let httpResponse = response as? HTTPURLResponse - print(httpResponse) - } -}) - -dataTask.resume() diff --git a/test/fixtures/output/swift/nsurlsession/multipart-file.swift b/test/fixtures/output/swift/nsurlsession/multipart-file.swift deleted file mode 100644 index 294461216..000000000 --- a/test/fixtures/output/swift/nsurlsession/multipart-file.swift +++ /dev/null @@ -1,51 +0,0 @@ -import Foundation - -let headers = ["content-type": "multipart/form-data; boundary=---011000010111000001101001"] -let parameters = [ - [ - "name": "foo", - "fileName": "test/fixtures/files/hello.txt", - "contentType": "text/plain" - ] -] - -let boundary = "---011000010111000001101001" - -var body = "" -var error: NSError? = nil -for param in parameters { - let paramName = param["name"]! - body += "--\(boundary)\r\n" - body += "Content-Disposition:form-data; name=\"\(paramName)\"" - if let filename = param["fileName"] { - let contentType = param["content-type"]! - let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8) - if (error != nil) { - print(error) - } - body += "; filename=\"\(filename)\"\r\n" - body += "Content-Type: \(contentType)\r\n\r\n" - body += fileContent - } else if let paramValue = param["value"] { - body += "\r\n\r\n\(paramValue)" - } -} - -let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, - cachePolicy: .useProtocolCachePolicy, - timeoutInterval: 10.0) -request.httpMethod = "POST" -request.allHTTPHeaderFields = headers -request.httpBody = postData as Data - -let session = URLSession.shared -let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - } else { - let httpResponse = response as? HTTPURLResponse - print(httpResponse) - } -}) - -dataTask.resume() diff --git a/test/fixtures/output/swift/nsurlsession/multipart-form-data.swift b/test/fixtures/output/swift/nsurlsession/multipart-form-data.swift deleted file mode 100644 index bafceef17..000000000 --- a/test/fixtures/output/swift/nsurlsession/multipart-form-data.swift +++ /dev/null @@ -1,50 +0,0 @@ -import Foundation - -let headers = ["content-type": "multipart/form-data; boundary=---011000010111000001101001"] -let parameters = [ - [ - "name": "foo", - "value": "bar" - ] -] - -let boundary = "---011000010111000001101001" - -var body = "" -var error: NSError? = nil -for param in parameters { - let paramName = param["name"]! - body += "--\(boundary)\r\n" - body += "Content-Disposition:form-data; name=\"\(paramName)\"" - if let filename = param["fileName"] { - let contentType = param["content-type"]! - let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8) - if (error != nil) { - print(error) - } - body += "; filename=\"\(filename)\"\r\n" - body += "Content-Type: \(contentType)\r\n\r\n" - body += fileContent - } else if let paramValue = param["value"] { - body += "\r\n\r\n\(paramValue)" - } -} - -let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, - cachePolicy: .useProtocolCachePolicy, - timeoutInterval: 10.0) -request.httpMethod = "POST" -request.allHTTPHeaderFields = headers -request.httpBody = postData as Data - -let session = URLSession.shared -let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - } else { - let httpResponse = response as? HTTPURLResponse - print(httpResponse) - } -}) - -dataTask.resume() diff --git a/test/fixtures/output/swift/nsurlsession/query.swift b/test/fixtures/output/swift/nsurlsession/query.swift deleted file mode 100644 index 8325525e2..000000000 --- a/test/fixtures/output/swift/nsurlsession/query.swift +++ /dev/null @@ -1,18 +0,0 @@ -import Foundation - -let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value")! as URL, - cachePolicy: .useProtocolCachePolicy, - timeoutInterval: 10.0) -request.httpMethod = "GET" - -let session = URLSession.shared -let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - } else { - let httpResponse = response as? HTTPURLResponse - print(httpResponse) - } -}) - -dataTask.resume() diff --git a/test/fixtures/output/swift/nsurlsession/short.swift b/test/fixtures/output/swift/nsurlsession/short.swift deleted file mode 100644 index 1f4cd26a8..000000000 --- a/test/fixtures/output/swift/nsurlsession/short.swift +++ /dev/null @@ -1,18 +0,0 @@ -import Foundation - -let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, - cachePolicy: .useProtocolCachePolicy, - timeoutInterval: 10.0) -request.httpMethod = "GET" - -let session = URLSession.shared -let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - } else { - let httpResponse = response as? HTTPURLResponse - print(httpResponse) - } -}) - -dataTask.resume() diff --git a/test/fixtures/output/swift/nsurlsession/text-plain.swift b/test/fixtures/output/swift/nsurlsession/text-plain.swift deleted file mode 100644 index 910b4ac2c..000000000 --- a/test/fixtures/output/swift/nsurlsession/text-plain.swift +++ /dev/null @@ -1,24 +0,0 @@ -import Foundation - -let headers = ["content-type": "text/plain"] - -let postData = NSData(data: "Hello World".data(using: String.Encoding.utf8)!) - -let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, - cachePolicy: .useProtocolCachePolicy, - timeoutInterval: 10.0) -request.httpMethod = "POST" -request.allHTTPHeaderFields = headers -request.httpBody = postData as Data - -let session = URLSession.shared -let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in - if (error != nil) { - print(error) - } else { - let httpResponse = response as? HTTPURLResponse - print(httpResponse) - } -}) - -dataTask.resume() diff --git a/test/fixtures/requests/application-form-encoded.json b/test/fixtures/requests/application-form-encoded.json deleted file mode 100644 index 8dae7d794..000000000 --- a/test/fixtures/requests/application-form-encoded.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "method": "POST", - "url": "http://mockbin.com/har", - "headers": [ - { - "name": "content-type", - "value": "application/x-www-form-urlencoded" - } - ], - "postData": { - "mimeType": "application/x-www-form-urlencoded", - "params": [ - { - "name": "foo", - "value": "bar" - }, - { - "name": "hello", - "value": "world" - } - ] - } -} diff --git a/test/fixtures/requests/application-json.json b/test/fixtures/requests/application-json.json deleted file mode 100644 index 3b62f0d79..000000000 --- a/test/fixtures/requests/application-json.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "method": "POST", - "url": "http://mockbin.com/har", - "headers": [ - { - "name": "content-type", - "value": "application/json" - } - ], - "postData": { - "mimeType": "application/json", - "text": "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":{}}],\"boolean\":false}" - } -} diff --git a/test/fixtures/requests/cookies.json b/test/fixtures/requests/cookies.json deleted file mode 100644 index 248907cf6..000000000 --- a/test/fixtures/requests/cookies.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "method": "POST", - "url": "http://mockbin.com/har", - "cookies": [ - { - "name": "foo", - "value": "bar" - }, - { - "name": "bar", - "value": "baz" - } - ] -} diff --git a/test/fixtures/requests/custom-method.json b/test/fixtures/requests/custom-method.json deleted file mode 100644 index 346d7145a..000000000 --- a/test/fixtures/requests/custom-method.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "method": "PROPFIND", - "url": "http://mockbin.com/har" -} diff --git a/test/fixtures/requests/full.json b/test/fixtures/requests/full.json deleted file mode 100644 index 640839a1f..000000000 --- a/test/fixtures/requests/full.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "method": "POST", - "url": "http://mockbin.com/har?key=value", - "httpVersion": "HTTP/1.1", - "queryString": [ - { - "name": "foo", - "value": "bar" - }, - { - "name": "foo", - "value": "baz" - }, - { - "name": "baz", - "value": "abc" - } - ], - "headers": [ - { - "name": "accept", - "value": "application/json" - }, - { - "name": "content-type", - "value": "application/x-www-form-urlencoded" - } - ], - "cookies": [ - { - "name": "foo", - "value": "bar" - }, - { - "name": "bar", - "value": "baz" - } - ], - "postData": { - "mimeType": "application/x-www-form-urlencoded", - "params": [ - { - "name": "foo", - "value": "bar" - } - ] - } -} diff --git a/test/fixtures/requests/headers.json b/test/fixtures/requests/headers.json deleted file mode 100644 index 6f41b3820..000000000 --- a/test/fixtures/requests/headers.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "method": "GET", - "url": "http://mockbin.com/har", - "headers": [ - { - "name": "accept", - "value": "application/json" - }, - { - "name": "x-foo", - "value": "Bar" - } - ] -} diff --git a/test/fixtures/requests/https.json b/test/fixtures/requests/https.json deleted file mode 100644 index 339a88e6e..000000000 --- a/test/fixtures/requests/https.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "method": "GET", - "url": "https://mockbin.com/har" -} diff --git a/test/fixtures/requests/index.js b/test/fixtures/requests/index.js deleted file mode 100644 index 0d8e0250c..000000000 --- a/test/fixtures/requests/index.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('require-directory')(module); diff --git a/test/fixtures/requests/jsonObj-null-value.json b/test/fixtures/requests/jsonObj-null-value.json deleted file mode 100644 index c08860ac2..000000000 --- a/test/fixtures/requests/jsonObj-null-value.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "url": "http://mockbin.com/har", - "method": "POST", - "headers": [{ - "name": "content-type", - "value": "application/json" - }], - "postData": { - "params": [], - "text": "{\"foo\":null}", - "stored": true, - "mimeType": "application/json", - "size": 0, - "jsonObj": { - "foo":null - }, - "paramsObj": false - } -} diff --git a/test/fixtures/requests/multipart-data.json b/test/fixtures/requests/multipart-data.json deleted file mode 100644 index fb9098fdb..000000000 --- a/test/fixtures/requests/multipart-data.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "method": "POST", - "url": "http://mockbin.com/har", - "headers": [ - { - "name": "content-type", - "value": "multipart/form-data" - } - ], - "postData": { - "mimeType": "multipart/form-data", - "params": [ - { - "name": "foo", - "value": "Hello World", - "fileName": "hello.txt", - "contentType": "text/plain" - } - ] - } -} diff --git a/test/fixtures/requests/multipart-file.json b/test/fixtures/requests/multipart-file.json deleted file mode 100644 index 8623c1d3c..000000000 --- a/test/fixtures/requests/multipart-file.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "method": "POST", - "url": "http://mockbin.com/har", - "headers": [ - { - "name": "content-type", - "value": "multipart/form-data" - } - ], - "postData": { - "mimeType": "multipart/form-data", - "params": [ - { - "name": "foo", - "fileName": "test/fixtures/files/hello.txt", - "contentType": "text/plain" - } - ] - } -} diff --git a/test/fixtures/requests/multipart-form-data.json b/test/fixtures/requests/multipart-form-data.json deleted file mode 100644 index 4db5eeea6..000000000 --- a/test/fixtures/requests/multipart-form-data.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "method": "POST", - "url": "http://mockbin.com/har", - "headers": [ - { - "name": "content-type", - "value": "multipart/form-data" - } - ], - "postData": { - "mimeType": "multipart/form-data", - "params": [ - { - "name": "foo", - "value": "bar" - } - ] - } -} diff --git a/test/fixtures/requests/query.json b/test/fixtures/requests/query.json deleted file mode 100644 index 5d2e61452..000000000 --- a/test/fixtures/requests/query.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "method": "GET", - "url": "http://mockbin.com/har?key=value", - "httpVersion": "HTTP/1.1", - "queryString": [ - { - "name": "foo", - "value": "bar" - }, - { - "name": "foo", - "value": "baz" - }, - { - "name": "baz", - "value": "abc" - } - ] -} diff --git a/test/fixtures/requests/short.json b/test/fixtures/requests/short.json deleted file mode 100644 index a4d8f00a1..000000000 --- a/test/fixtures/requests/short.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "method": "GET", - "url": "http://mockbin.com/har" -} diff --git a/test/fixtures/requests/text-plain.json b/test/fixtures/requests/text-plain.json deleted file mode 100644 index 6f6f3072c..000000000 --- a/test/fixtures/requests/text-plain.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "method": "POST", - "url": "http://mockbin.com/har", - "headers": [ - { - "name": "content-type", - "value": "text/plain" - } - ], - "postData": { - "mimeType": "text/plain", - "text": "Hello World" - } -} diff --git a/test/index.js b/test/index.js deleted file mode 100644 index 62a837164..000000000 --- a/test/index.js +++ /dev/null @@ -1,193 +0,0 @@ -/* global describe, it */ - -'use strict' - -var fixtures = require('./fixtures') -var HTTPSnippet = require('../src') - -var should = require('should') - -describe('HTTPSnippet', function () { - it('should return false if no matching target', function (done) { - var snippet = new HTTPSnippet(fixtures.requests.short) - - snippet.convert(null).should.eql(false) - - done() - }) - - it('should fail validation', function (done) { - var snippet; - - /* eslint-disable no-extra-parens */ - (function () { - snippet = new HTTPSnippet({yolo: 'foo'}) - }).should.throw(Error) - - should.not.exist(snippet) - - done() - }) - - it('should parse HAR file with multiple entries', function (done) { - var snippet = new HTTPSnippet(fixtures.har) - - snippet.should.have.property('requests').and.be.an.Array - snippet.requests.length.should.equal(2) - - var results = snippet.convert('shell') - - results.should.be.an.Array - results.length.should.equal(2) - - done() - }) - - it('should convert multipart/mixed to multipart/form-data', function (done) { - var req = new HTTPSnippet(fixtures.mimetypes['multipart/mixed']).requests[0] - - req.postData.mimeType.should.eql('multipart/form-data') - - done() - }) - - it('should convert multipart/related to multipart/form-data', function (done) { - var req = new HTTPSnippet(fixtures.mimetypes['multipart/related']).requests[0] - - req.postData.mimeType.should.eql('multipart/form-data') - - done() - }) - - it('should convert multipart/alternative to multipart/form-data', function (done) { - var req = new HTTPSnippet(fixtures.mimetypes['multipart/alternative']).requests[0] - - req.postData.mimeType.should.eql('multipart/form-data') - - done() - }) - - it('should convert text/json to application/json', function (done) { - var req = new HTTPSnippet(fixtures.mimetypes['text/json']).requests[0] - - req.postData.mimeType.should.eql('application/json') - - done() - }) - - it('should convert text/x-json to application/json', function (done) { - var req = new HTTPSnippet(fixtures.mimetypes['text/x-json']).requests[0] - - req.postData.mimeType.should.eql('application/json') - - done() - }) - - it('should convert application/x-json to application/json', function (done) { - var req = new HTTPSnippet(fixtures.mimetypes['application/x-json']).requests[0] - - req.postData.mimeType.should.eql('application/json') - - done() - }) - - it('should gracefully fallback if not able to parse JSON', function (done) { - var req = new HTTPSnippet(fixtures.mimetypes['invalid-json']).requests[0] - - req.postData.mimeType.should.eql('text/plain') - - done() - }) - - it('should set postData.text = empty string when postData.params === undefined in application/x-www-form-urlencoded', function (done) { - var req = new HTTPSnippet(fixtures.mimetypes['application/x-www-form-urlencoded']).requests[0] - - req.postData.text.should.eql('') - - done() - }) - - it('should add "uriObj" to source object', function (done) { - var req = new HTTPSnippet(fixtures.requests.query).requests[0] - - req.uriObj.should.be.an.Object - req.uriObj.should.eql({ - auth: null, - hash: null, - host: 'mockbin.com', - hostname: 'mockbin.com', - href: 'http://mockbin.com/har?key=value', - path: '/har?foo=bar&foo=baz&baz=abc&key=value', - pathname: '/har', - port: null, - protocol: 'http:', - query: { - baz: 'abc', - key: 'value', - foo: [ - 'bar', - 'baz' - ] - }, - search: 'foo=bar&foo=baz&baz=abc&key=value', - slashes: true - }) - - done() - }) - - it('should add "queryObj" to source object', function (done) { - var req = new HTTPSnippet(fixtures.requests.query).requests[0] - - req.queryObj.should.be.an.Object - req.queryObj.should.eql({ - baz: 'abc', - key: 'value', - foo: [ - 'bar', - 'baz' - ] - }) - - done() - }) - - it('should add "headersObj" to source object', function (done) { - var req = new HTTPSnippet(fixtures.requests.headers).requests[0] - - req.headersObj.should.be.an.Object - req.headersObj.should.eql({ - 'accept': 'application/json', - 'x-foo': 'Bar' - }) - - done() - }) - - it('should modify orignal url to strip query string', function (done) { - var req = new HTTPSnippet(fixtures.requests.query).requests[0] - - req.url.should.be.a.String - req.url.should.eql('http://mockbin.com/har') - - done() - }) - - it('should add "fullUrl" to source object', function (done) { - var req = new HTTPSnippet(fixtures.requests.query).requests[0] - - req.fullUrl.should.be.a.String - req.fullUrl.should.eql('http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value') - - done() - }) - - it('should fix "path" property of "uriObj" to match queryString', function (done) { - var req = new HTTPSnippet(fixtures.requests.query).requests[0] - - req.uriObj.path.should.be.a.String - req.uriObj.path.should.eql('/har?foo=bar&foo=baz&baz=abc&key=value') - - done() - }) -}) diff --git a/test/reducer.js b/test/reducer.js deleted file mode 100644 index 2bbbbedd8..000000000 --- a/test/reducer.js +++ /dev/null @@ -1,38 +0,0 @@ -/* global describe, it */ - -'use strict' - -var reducer = require('../src/helpers/reducer') - -require('should') - -describe('Reducer', function () { - it('should convert array object pair to key-value object', function (done) { - var query = [ - {name: 'key', value: 'value'}, - {name: 'foo', value: 'bar'} - ] - - var obj = query.reduce(reducer, {}) - - obj.should.be.an.Object - obj.should.eql({key: 'value', foo: 'bar'}) - - done() - }) - - it('should convert multi-dimensional arrays to key=[array] object', function (done) { - var query = [ - {name: 'key', value: 'value'}, - {name: 'foo', value: 'bar1'}, - {name: 'foo', value: 'bar2'} - ] - - var obj = query.reduce(reducer, {}) - - obj.should.be.an.Object - obj.should.eql({key: 'value', foo: ['bar1', 'bar2']}) - - done() - }) -}) diff --git a/test/requests.js b/test/requests.js deleted file mode 100644 index ae3abb930..000000000 --- a/test/requests.js +++ /dev/null @@ -1,68 +0,0 @@ -/* global describe, it */ - -'use strict' - -var fixtures = require('./fixtures') -var HTTPSnippet = require('../src') -var targets = require('../src/targets') -var shell = require('child_process') -var util = require('util') - -require('should') - -var base = './test/fixtures/output/' -var requests = [ 'application-form-encoded', - 'application-json', - 'cookies', - 'custom-method', - 'headers', - 'https', - 'multipart-data', - 'multipart-form-data', - 'short' -] - -// test all the things! -fixtures.cli.forEach(function (cli) { - describe(targets[cli.target].info.title + ' Request Validation', function () { - cli.clients.forEach(function (client) { - requests.forEach(function (request) { - it(client + ' request should match mock for ' + request, function (done) { - var stdout = '' - var fixture = cli.target + '/' + client + '/' + request + HTTPSnippet.extname(cli.target) - var command = util.format(cli.run, base + fixture) - - var ls = shell.exec(command) - - ls.stdout.on('data', function (data) { - stdout += data - }) - - ls.on('exit', function (code) { - try { - var har = JSON.parse(stdout) - } catch (err) { - err.should.be.null - } - - // make an exception for multipart/form-data - if (fixtures.requests[request].headers) { - fixtures.requests[request].headers.forEach(function (header, index) { - if (header.name === 'content-type' && header.value === 'multipart/form-data') { - delete fixtures.requests[request].headers[index] - } - }) - } - - har.should.have.property('log') - har.log.should.have.property('entries').and.be.Array - har.log.entries[0].should.have.property('request') - har.log.entries[0].request.should.containDeep(fixtures.requests[request]) - - done() - }) - }) - }) - }) - }) -}) diff --git a/test/targets.js b/test/targets.js deleted file mode 100644 index be1aa0dde..000000000 --- a/test/targets.js +++ /dev/null @@ -1,102 +0,0 @@ -/* global describe, it */ - -'use strict' - -var fixtures = require('./fixtures') -var fs = require('fs') -var glob = require('glob') -var HTTPSnippet = require('../src') -var path = require('path') -var should = require('should') -var targets = require('../src/targets') - -var base = './test/fixtures/output/' - -// read all output files -var output = glob.sync('**/*', {cwd: base, nodir: true}).reduce(function (obj, name) { - obj[name] = fs.readFileSync(base + name) - return obj -}, {}) - -var clearInfo = function (key) { - return !~['info', 'index'].indexOf(key) -} - -var itShouldHaveTests = function (target, client) { - it(target + ' should have tests', function (done) { - fs.readdir(path.join(__dirname, 'targets', target), function (err, files) { - should.not.exist(err) - files.length.should.be.above(0) - files.should.containEql(client + '.js') - done() - }) - }) -} - -var itShouldHaveInfo = function (name, obj) { - it(name + ' should have info method', function () { - obj.should.have.property('info').and.be.an.Object - obj.info.key.should.equal(name).and.be.a.String - obj.info.title.should.be.a.String - }) -} - -var itShouldHaveRequestTestOutputFixture = function (request, target, path) { - var fixture = target + '/' + path + request + HTTPSnippet.extname(target) - - it('should have output test for ' + request, function () { - Object.keys(output).indexOf(fixture).should.be.greaterThan(-1, 'Missing ' + fixture + ' fixture file for target: ' + target + '. Snippet tests will be skipped.') - }) -} - -var itShouldGenerateOutput = function (request, path, target, client) { - var fixture = path + request + HTTPSnippet.extname(target) - - it('should generate ' + request + ' snippet', function () { - if (Object.keys(output).indexOf(fixture) === -1) { - this.skip() - } - var instance = new HTTPSnippet(fixtures.requests[request]) - var result = instance.convert(target, client) + '\n' - - result.should.be.a.String - result.should.equal(output[fixture].toString()) - }) -} - -describe('Available Targets', function () { - var targets = HTTPSnippet.availableTargets() - - targets.forEach(function (target) { - it('available-targets.json should include ' + target.title, function () { - fixtures['available-targets'].should.containEql(target) - }) - }) -}) - -// test all the things! -Object.keys(targets).forEach(function (target) { - describe(targets[target].info.title, function () { - itShouldHaveInfo(target, targets[target]) - - Object.keys(targets[target]).filter(clearInfo).forEach(function (client) { - describe(client, function () { - itShouldHaveInfo(client, targets[target][client]) - - itShouldHaveTests(target, client) - - var test = require(path.join(__dirname, 'targets', target, client)) - - test(HTTPSnippet, fixtures) - - describe('snippets', function () { - Object.keys(fixtures.requests).filter(clearInfo).forEach(function (request) { - itShouldHaveRequestTestOutputFixture(request, target, client + '/') - - itShouldGenerateOutput(request, target + '/' + client + '/', target, client) - }) - }) - }) - }) - }) -}) diff --git a/test/targets/c/libcurl.js b/test/targets/c/libcurl.js deleted file mode 100644 index 9ad8c1790..000000000 --- a/test/targets/c/libcurl.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict' - -require('should') - -module.exports = function (snippet, fixtures) {} diff --git a/test/targets/clojure/clj_http.js b/test/targets/clojure/clj_http.js deleted file mode 100644 index 9ad8c1790..000000000 --- a/test/targets/clojure/clj_http.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict' - -require('should') - -module.exports = function (snippet, fixtures) {} diff --git a/test/targets/csharp/restsharp.js b/test/targets/csharp/restsharp.js deleted file mode 100644 index 9ad8c1790..000000000 --- a/test/targets/csharp/restsharp.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict' - -require('should') - -module.exports = function (snippet, fixtures) {} diff --git a/test/targets/go/native.js b/test/targets/go/native.js deleted file mode 100644 index a2afafcf5..000000000 --- a/test/targets/go/native.js +++ /dev/null @@ -1,40 +0,0 @@ -/* global it */ - -'use strict' - -require('should') - -module.exports = function (HTTPSnippet, fixtures) { - it('should support false boilerplate option', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('go', 'native', { - showBoilerplate: false - }) - - result.should.be.a.String - result.should.eql('url := \"http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value\"\n\npayload := strings.NewReader(\"foo=bar\")\n\nreq, _ := http.NewRequest(\"POST\", url, payload)\n\nreq.Header.Add(\"cookie\", \"foo=bar; bar=baz\")\nreq.Header.Add(\"accept\", \"application/json\")\nreq.Header.Add(\"content-type\", \"application/x-www-form-urlencoded\")\n\nres, _ := http.DefaultClient.Do(req)\n\ndefer res.Body.Close()\nbody, _ := ioutil.ReadAll(res.Body)\n\nfmt.Println(res)\nfmt.Println(string(body))') - }) - it('should support checkErrors option', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('go', 'native', { - checkErrors: true - }) - - result.should.be.a.String - result.should.eql('package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"net/http\"\n\t\"io/ioutil\"\n)\n\nfunc main() {\n\n\turl := \"http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value\"\n\n\tpayload := strings.NewReader(\"foo=bar\")\n\n\treq, err := http.NewRequest(\"POST\", url, payload)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Add(\"cookie\", \"foo=bar; bar=baz\")\n\treq.Header.Add(\"accept\", \"application/json\")\n\treq.Header.Add(\"content-type\", \"application/x-www-form-urlencoded\")\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(res)\n\tfmt.Println(string(body))\n\n}') - }) - it('should support printBody option', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('go', 'native', { - printBody: false - }) - - result.should.be.a.String - result.should.eql('package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"net/http\"\n)\n\nfunc main() {\n\n\turl := \"http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value\"\n\n\tpayload := strings.NewReader(\"foo=bar\")\n\n\treq, _ := http.NewRequest(\"POST\", url, payload)\n\n\treq.Header.Add(\"cookie\", \"foo=bar; bar=baz\")\n\treq.Header.Add(\"accept\", \"application/json\")\n\treq.Header.Add(\"content-type\", \"application/x-www-form-urlencoded\")\n\n\tres, _ := http.DefaultClient.Do(req)\n\n\tfmt.Println(res)\n\n}') - }) - it('should support timeout option', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('go', 'native', { - timeout: 30 - }) - - result.should.be.a.String - result.should.eql('package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\t\"strings\"\n\t\"net/http\"\n\t\"io/ioutil\"\n)\n\nfunc main() {\n\n\tclient := http.Client{\n\t\tTimeout: time.Duration(30 * time.Second),\n\t}\n\n\turl := \"http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value\"\n\n\tpayload := strings.NewReader(\"foo=bar\")\n\n\treq, _ := http.NewRequest(\"POST\", url, payload)\n\n\treq.Header.Add(\"cookie\", \"foo=bar; bar=baz\")\n\treq.Header.Add(\"accept\", \"application/json\")\n\treq.Header.Add(\"content-type\", \"application/x-www-form-urlencoded\")\n\n\tres, _ := client.Do(req)\n\n\tdefer res.Body.Close()\n\tbody, _ := ioutil.ReadAll(res.Body)\n\n\tfmt.Println(res)\n\tfmt.Println(string(body))\n\n}') - }) -} diff --git a/test/targets/java/okhttp.js b/test/targets/java/okhttp.js deleted file mode 100644 index 9ad8c1790..000000000 --- a/test/targets/java/okhttp.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict' - -require('should') - -module.exports = function (snippet, fixtures) {} diff --git a/test/targets/java/unirest.js b/test/targets/java/unirest.js deleted file mode 100644 index 9ad8c1790..000000000 --- a/test/targets/java/unirest.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict' - -require('should') - -module.exports = function (snippet, fixtures) {} diff --git a/test/targets/javascript/jquery.js b/test/targets/javascript/jquery.js deleted file mode 100644 index b77cc77e7..000000000 --- a/test/targets/javascript/jquery.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict' - -module.exports = function (snippet, fixtures) {} diff --git a/test/targets/javascript/xhr.js b/test/targets/javascript/xhr.js deleted file mode 100644 index a4ff8528d..000000000 --- a/test/targets/javascript/xhr.js +++ /dev/null @@ -1,16 +0,0 @@ -/* global it */ - -'use strict' - -require('should') - -module.exports = function (HTTPSnippet, fixtures) { - it('should not use cors', function () { - var result = new HTTPSnippet(fixtures.requests.short).convert('javascript', 'xhr', { - cors: false - }) - - result.should.be.a.String - result.replace(/\n/g, '').should.eql('var data = null;var xhr = new XMLHttpRequest();xhr.addEventListener("readystatechange", function () { if (this.readyState === this.DONE) { console.log(this.responseText); }});xhr.open("GET", "http://mockbin.com/har");xhr.send(data);') - }) -} diff --git a/test/targets/node/native.js b/test/targets/node/native.js deleted file mode 100644 index b77cc77e7..000000000 --- a/test/targets/node/native.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict' - -module.exports = function (snippet, fixtures) {} diff --git a/test/targets/node/request.js b/test/targets/node/request.js deleted file mode 100644 index b77cc77e7..000000000 --- a/test/targets/node/request.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict' - -module.exports = function (snippet, fixtures) {} diff --git a/test/targets/node/unirest.js b/test/targets/node/unirest.js deleted file mode 100644 index b77cc77e7..000000000 --- a/test/targets/node/unirest.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict' - -module.exports = function (snippet, fixtures) {} diff --git a/test/targets/objc/nsurlsession.js b/test/targets/objc/nsurlsession.js deleted file mode 100644 index dcf9b8331..000000000 --- a/test/targets/objc/nsurlsession.js +++ /dev/null @@ -1,41 +0,0 @@ -/* global it */ - -'use strict' - -require('should') - -module.exports = function (HTTPSnippet, fixtures) { - it('should support an indent option', function () { - var result = new HTTPSnippet(fixtures.requests.short).convert('objc', { - indent: ' ' - }) - - result.should.be.a.String - result.replace(/\n/g, '').should.eql('#import NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];[request setHTTPMethod:@"GET"];NSURLSession *session = [NSURLSession sharedSession];NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"%@", error); } else { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; NSLog(@"%@", httpResponse); } }];[dataTask resume];') - }) - it('should support a timeout option', function () { - var result = new HTTPSnippet(fixtures.requests.short).convert('objc', { - timeout: 5 - }) - - result.should.be.a.String - result.replace(/\n/g, '').should.eql('#import NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];[request setHTTPMethod:@"GET"];NSURLSession *session = [NSURLSession sharedSession];NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"%@", error); } else { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; NSLog(@"%@", httpResponse); } }];[dataTask resume];') - }) - it('should support pretty option', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('objc', { - pretty: false - }) - - result.should.be.a.String - result.replace(/\n/g, '').should.eql('#import NSDictionary *headers = @{ @"cookie": @"foo=bar; bar=baz", @"accept": @"application/json", @"content-type": @"application/x-www-form-urlencoded" };NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"foo=bar" dataUsingEncoding:NSUTF8StringEncoding]];NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];[request setHTTPMethod:@"POST"];[request setAllHTTPHeaderFields:headers];[request setHTTPBody:postData];NSURLSession *session = [NSURLSession sharedSession];NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"%@", error); } else { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; NSLog(@"%@", httpResponse); } }];[dataTask resume];') - }) - - it('should support json object with null value', function () { - var result = new HTTPSnippet(fixtures.requests['jsonObj-null-value']).convert('objc', { - pretty: false - }) - - result.should.be.a.String - result.replace(/\n/g, '').should.eql('#import NSDictionary *headers = @{ @"content-type": @"application/json" };NSDictionary *parameters = @{ @"foo": };NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];[request setHTTPMethod:@"POST"];[request setAllHTTPHeaderFields:headers];[request setHTTPBody:postData];NSURLSession *session = [NSURLSession sharedSession];NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"%@", error); } else { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; NSLog(@"%@", httpResponse); } }];[dataTask resume];') - }) -} diff --git a/test/targets/ocaml/cohttp.js b/test/targets/ocaml/cohttp.js deleted file mode 100644 index b77cc77e7..000000000 --- a/test/targets/ocaml/cohttp.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict' - -module.exports = function (snippet, fixtures) {} diff --git a/test/targets/php/curl.js b/test/targets/php/curl.js deleted file mode 100644 index b77cc77e7..000000000 --- a/test/targets/php/curl.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict' - -module.exports = function (snippet, fixtures) {} diff --git a/test/targets/php/http1.js b/test/targets/php/http1.js deleted file mode 100644 index b77cc77e7..000000000 --- a/test/targets/php/http1.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict' - -module.exports = function (snippet, fixtures) {} diff --git a/test/targets/php/http2.js b/test/targets/php/http2.js deleted file mode 100644 index b77cc77e7..000000000 --- a/test/targets/php/http2.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict' - -module.exports = function (snippet, fixtures) {} diff --git a/test/targets/python/python3.js b/test/targets/python/python3.js deleted file mode 100644 index ce4678eb9..000000000 --- a/test/targets/python/python3.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict' - -require('should') - -module.exports = function (snippet, fixtures) { -} diff --git a/test/targets/python/requests.js b/test/targets/python/requests.js deleted file mode 100644 index ce4678eb9..000000000 --- a/test/targets/python/requests.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict' - -require('should') - -module.exports = function (snippet, fixtures) { -} diff --git a/test/targets/ruby/native.js b/test/targets/ruby/native.js deleted file mode 100644 index b77cc77e7..000000000 --- a/test/targets/ruby/native.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict' - -module.exports = function (snippet, fixtures) {} diff --git a/test/targets/shell/curl.js b/test/targets/shell/curl.js deleted file mode 100644 index 2206a6e3d..000000000 --- a/test/targets/shell/curl.js +++ /dev/null @@ -1,46 +0,0 @@ -/* global it */ - -'use strict' - -require('should') - -module.exports = function (HTTPSnippet, fixtures) { - it('should use short options', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('shell', 'curl', { - short: true, - indent: false - }) - - result.should.be.a.String - result.should.eql("curl -X POST 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' -H 'accept: application/json' -H 'content-type: application/x-www-form-urlencoded' -b 'foo=bar; bar=baz' -d foo=bar") - }) - - it('should use binary option', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('shell', 'curl', { - short: true, - indent: false, - binary: true - }) - - result.should.be.a.String - result.should.eql("curl -X POST 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' -H 'accept: application/json' -H 'content-type: application/x-www-form-urlencoded' -b 'foo=bar; bar=baz' --data-binary foo=bar") - }) - - it('should use --http1.0 for HTTP/1.0', function () { - var result = new HTTPSnippet(fixtures.curl.http1).convert('shell', 'curl', { - indent: false - }) - - result.should.be.a.String - result.should.eql('curl --request GET --url http://mockbin.com/request --http1.0') - }) - - it('should use custom indentation', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('shell', 'curl', { - indent: '@' - }) - - result.should.be.a.String - result.replace(/\\\n/g, '').should.eql("curl --request POST @--url 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' @--header 'accept: application/json' @--header 'content-type: application/x-www-form-urlencoded' @--cookie 'foo=bar; bar=baz' @--data foo=bar") - }) -} diff --git a/test/targets/shell/httpie.js b/test/targets/shell/httpie.js deleted file mode 100644 index 8a07a8655..000000000 --- a/test/targets/shell/httpie.js +++ /dev/null @@ -1,94 +0,0 @@ -/* global it */ - -'use strict' - -require('should') - -module.exports = function (HTTPSnippet, fixtures) { - it('should ask for verbose output', function () { - var result = new HTTPSnippet(fixtures.requests.short).convert('shell', 'httpie', { - indent: false, - verbose: true - }) - - result.should.be.a.String - result.should.eql('http --verbose GET http://mockbin.com/har') - }) - - it('should use short flags', function () { - var result = new HTTPSnippet(fixtures.requests.short).convert('shell', 'httpie', { - body: true, - cert: 'foo', - headers: true, - indent: false, - pretty: 'x', - print: 'x', - short: true, - style: 'x', - timeout: 1, - verbose: true, - verify: 'x' - }) - - result.should.be.a.String - result.should.eql('http -h -b -v -p=x --verify=x --cert=foo --pretty=x --style=x --timeout=1 GET http://mockbin.com/har') - }) - - it('should use long flags', function () { - var result = new HTTPSnippet(fixtures.requests.short).convert('shell', 'httpie', { - body: true, - cert: 'foo', - headers: true, - indent: false, - pretty: 'x', - print: 'x', - style: 'x', - timeout: 1, - verbose: true, - verify: 'x' - }) - - result.should.be.a.String - result.should.eql('http --headers --body --verbose --print=x --verify=x --cert=foo --pretty=x --style=x --timeout=1 GET http://mockbin.com/har') - }) - - it('should use custom indentation', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('shell', 'httpie', { - indent: '@' - }) - - result.should.be.a.String - result.replace(/\\\n/g, '').should.eql("http --form POST 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' @accept:application/json @content-type:application/x-www-form-urlencoded @cookie:'foo=bar; bar=baz' @foo=bar") - }) - - it('should use queryString parameters', function () { - var result = new HTTPSnippet(fixtures.requests.query).convert('shell', 'httpie', { - indent: false, - queryParams: true - }) - - result.should.be.a.String - result.replace(/\\\n/g, '').should.eql('http GET http://mockbin.com/har foo==bar foo==baz baz==abc key==value') - }) - - it('should build parameterized output of query string', function () { - var result = new HTTPSnippet(fixtures.requests.query).convert('shell', 'httpie', { - indent: false, - queryParams: true - }) - - result.should.be.a.String - result.replace(/\\\n/g, '').should.eql('http GET http://mockbin.com/har foo==bar foo==baz baz==abc key==value') - }) - - it('should build parameterized output of post data', function () { - var result = new HTTPSnippet(fixtures.requests['application-form-encoded']).convert('shell', 'httpie', { - short: true, - indent: false, - queryParams: true - }) - - result.should.be.a.String - result.replace(/\\\n/g, '').should.eql('http -f POST http://mockbin.com/har content-type:application/x-www-form-urlencoded foo=bar hello=world') - }) -} diff --git a/test/targets/shell/wget.js b/test/targets/shell/wget.js deleted file mode 100644 index 3b3386a28..000000000 --- a/test/targets/shell/wget.js +++ /dev/null @@ -1,48 +0,0 @@ -/* global it */ - -'use strict' - -require('should') - -module.exports = function (HTTPSnippet, fixtures) { - it('should use short options', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('shell', 'wget', { - short: true, - indent: false - }) - - result.should.be.a.String - result.should.eql("wget -q --method POST --header 'cookie: foo=bar; bar=baz' --header 'accept: application/json' --header 'content-type: application/x-www-form-urlencoded' --body-data foo=bar -O - 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value'") - }) - - it('should ask for -v output', function () { - var result = new HTTPSnippet(fixtures.requests.short).convert('shell', 'wget', { - short: true, - indent: false, - verbose: true - }) - - result.should.be.a.String - result.should.eql('wget -v --method GET -O - http://mockbin.com/har') - }) - - it('should ask for --verbose output', function () { - var result = new HTTPSnippet(fixtures.requests.short).convert('shell', 'wget', { - short: false, - indent: false, - verbose: true - }) - - result.should.be.a.String - result.should.eql('wget --verbose --method GET --output-document - http://mockbin.com/har') - }) - - it('should use custom indentation', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('shell', 'wget', { - indent: '@' - }) - - result.should.be.a.String - result.replace(/\\\n/g, '').should.eql("wget --quiet @--method POST @--header 'cookie: foo=bar; bar=baz' @--header 'accept: application/json' @--header 'content-type: application/x-www-form-urlencoded' @--body-data foo=bar @--output-document @- 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value'") - }) -} diff --git a/test/targets/swift/nsurlsession.js b/test/targets/swift/nsurlsession.js deleted file mode 100644 index 4d2a09a47..000000000 --- a/test/targets/swift/nsurlsession.js +++ /dev/null @@ -1,40 +0,0 @@ -/* global it */ - -'use strict' - -require('should') - -module.exports = function (HTTPSnippet, fixtures) { - it('should support an indent option', function () { - var result = new HTTPSnippet(fixtures.requests.short).convert('swift', { - indent: ' ' - }) - - result.should.be.a.String - result.replace(/\n/g, '').should.eql('import Foundationlet request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)request.httpMethod = "GET"let session = URLSession.sharedlet dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) }})dataTask.resume()') - }) - it('should support a timeout option', function () { - var result = new HTTPSnippet(fixtures.requests.short).convert('swift', { - timeout: 5 - }) - - result.should.be.a.String - result.replace(/\n/g, '').should.eql('import Foundationlet request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 5.0)request.httpMethod = "GET"let session = URLSession.sharedlet dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) }})dataTask.resume()') - }) - it('should support pretty option', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('swift', { - pretty: false - }) - - result.should.be.a.String - result.replace(/\n/g, '').should.eql('import Foundationlet headers = ["cookie": "foo=bar; bar=baz", "accept": "application/json", "content-type": "application/x-www-form-urlencoded"]let postData = NSMutableData(data: "foo=bar".data(using: String.Encoding.utf8)!)let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)request.httpMethod = "POST"request.allHTTPHeaderFields = headersrequest.httpBody = postData as Datalet session = URLSession.sharedlet dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) }})dataTask.resume()') - }) - it('should support json object with null value', function () { - var result = new HTTPSnippet(fixtures.requests['jsonObj-null-value']).convert('swift', { - pretty: false - }) - - result.should.be.a.String - result.replace(/\n/g, '').should.eql('import Foundationlet headers = ["content-type": "application/json"]let parameters = ["foo": ] as [String : Any]let postData = JSONSerialization.data(withJSONObject: parameters, options: [])let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)request.httpMethod = "POST"request.allHTTPHeaderFields = headersrequest.httpBody = postData as Datalet session = URLSession.sharedlet dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) }})dataTask.resume()') - }) -} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 000000000..427757859 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "declaration": true, + "esModuleInterop": true, + "isolatedDeclarations": true, + "lib": ["DOM", "ES2020"], + "module": "ESNext", + "moduleResolution": "Bundler", + "noEmit": true, + "outDir": "dist", + "resolveJsonModule": true, + "strict": true, + "target": "ES2020", + // Allows us to not have to typeguard in catches. + // https://bobbyhadz.com/blog/typescript-object-is-of-type-unknown + "useUnknownInCatchVariables": false, + "verbatimModuleSyntax": true + }, + "exclude": ["dist/", "./src/fixtures/", "**/*.test.ts"], + "include": ["./src/**/*"] +} diff --git a/tsup.config.ts b/tsup.config.ts new file mode 100644 index 000000000..58c52bf7b --- /dev/null +++ b/tsup.config.ts @@ -0,0 +1,16 @@ +import { defineConfig } from 'tsup'; + +// biome-ignore lint/style/noDefaultExport: `tsup` uses default exports. +export default defineConfig(options => ({ + ...options, + + cjsInterop: true, + dts: true, + entry: ['src/index.ts', 'src/helpers/code-builder.ts', 'src/helpers/reducer.ts', 'src/targets/index.ts'], + format: ['esm', 'cjs'], + shims: true, + silent: !options.watch, + sourcemap: true, + treeshake: true, + tsconfig: './tsconfig.json', +}));