Skip to content

Commit

Permalink
chore: lint fix
Browse files Browse the repository at this point in the history
  • Loading branch information
nivedin committed Jul 10, 2024
1 parent 9b209ef commit e44a4de
Show file tree
Hide file tree
Showing 12 changed files with 83 additions and 87 deletions.
7 changes: 3 additions & 4 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ on:
jobs:
scan:
permissions:
packages: write
packages: write
contents: write # publish sbom to GH releases/tag assets
runs-on: ubuntu-latest
steps:
Expand Down Expand Up @@ -74,14 +74,14 @@ jobs:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
fetch-depth: 0

- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20.9.0
registry-url: 'https://registry.npmjs.org'

- name: Install
run: npm ci

Expand All @@ -92,4 +92,3 @@ jobs:
run: npm publish --no-git-checks --provenance --tag ${{ github.sha }}
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ jobs:
id: core_tag_and_release
with:
tag: v${{ env.TAG }}
name: "httpsnippet v${{ env.TAG }} 📦"
name: 'httpsnippet v${{ env.TAG }} 📦'
generateReleaseNotes: true
prerelease: false
draft: false
draft: false
3 changes: 1 addition & 2 deletions .github/workflows/sast.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ on:
pull_request: {}
push:
branches:
- master
- master
workflow_dispatch: {}


jobs:
semgrep:
name: Semgrep SAST
Expand Down
20 changes: 6 additions & 14 deletions src/helpers/escape.test.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,26 @@
import { escapeString } from './escape';

describe('Escape methods', () => {
describe('escape methods', () => {
describe('escapeString', () => {
it('does nothing to a safe string', () => {
expect(
escapeString("hello world")
).toBe("hello world");
expect(escapeString('hello world')).toBe('hello world');
});

it('escapes double quotes by default', () => {
expect(
escapeString('"hello world"')
).toBe('\\"hello world\\"');
expect(escapeString('"hello world"')).toBe('\\"hello world\\"');
});

it('escapes newlines by default', () => {
expect(
escapeString('hello\r\nworld')
).toBe('hello\\r\\nworld');
expect(escapeString('hello\r\nworld')).toBe('hello\\r\\nworld');
});

it('escapes backslashes', () => {
expect(
escapeString('hello\\world')
).toBe('hello\\\\world');
expect(escapeString('hello\\world')).toBe('hello\\\\world');
});

it('escapes unrepresentable characters', () => {
expect(
escapeString('hello \u0000') // 0 = ASCII 'null' character
escapeString('hello \u0000'), // 0 = ASCII 'null' character
).toBe('hello \\u0000');
});
});
Expand Down
80 changes: 38 additions & 42 deletions src/helpers/escape.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,47 +31,45 @@ export interface EscapeOptions {
* for the complete original algorithm.
*/
export function escapeString(rawValue: any, options: EscapeOptions = {}) {
const {
delimiter = '"',
escapeChar = '\\',
escapeNewlines = true
} = options;
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';
} else {
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';
} else {
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);
} else {
return c;
}
}).join('');
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('');
}

/**
Expand All @@ -81,8 +79,7 @@ export function escapeString(rawValue: any, options: EscapeOptions = {}) {
*
* If value is not a string, it will be stringified with .toString() first.
*/
export const escapeForSingleQuotes = (value: any) =>
escapeString(value, { delimiter: "'" });
export const escapeForSingleQuotes = (value: any) => escapeString(value, { delimiter: "'" });

/**
* Make a string value safe to insert literally into a snippet within double quotes,
Expand All @@ -91,5 +88,4 @@ export const escapeForSingleQuotes = (value: any) =>
*
* If value is not a string, it will be stringified with .toString() first.
*/
export const escapeForDoubleQuotes = (value: any) =>
escapeString(value, { delimiter: '"' });
export const escapeForDoubleQuotes = (value: any) => escapeString(value, { delimiter: '"' });
6 changes: 5 additions & 1 deletion src/targets/c/libcurl/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ export const libcurl: Client = {
push('struct curl_slist *headers = NULL;');

headers.forEach(header => {
push(`headers = curl_slist_append(headers, "${header}: ${escapeForDoubleQuotes(headersObj[header])}");`);
push(
`headers = curl_slist_append(headers, "${header}: ${escapeForDoubleQuotes(
headersObj[header],
)}");`,
);
});

push('curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);');
Expand Down
4 changes: 3 additions & 1 deletion src/targets/ocaml/cohttp/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ export const cohttp: Client = {

if (headers.length === 1) {
push(
`let headers = Header.add (Header.init ()) "${headers[0]}" "${escapeForDoubleQuotes(allHeaders[headers[0]])}" in`,
`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 ()) [');
Expand Down
8 changes: 6 additions & 2 deletions src/targets/php/guzzle/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,15 +123,19 @@ export const guzzle: Client<GuzzleOptions> = {
const headers = Object.keys(headersObj)
.sort()
.map(function (key) {
return `${opts.indent}${opts.indent}'${key}' => '${escapeForSingleQuotes(headersObj[key])}',`;
return `${
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)}',`);
headers.push(
`${opts.indent}${opts.indent}'cookie' => '${escapeForSingleQuotes(cookieString)}',`,
);
}

if (headers.length) {
Expand Down
2 changes: 1 addition & 1 deletion src/targets/php/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { escapeString } from "../../helpers/escape";
import { escapeString } from '../../helpers/escape';

export const convertType = (obj: any[] | any, indent?: string, lastIndent?: string) => {
lastIndent = lastIndent || '';
Expand Down
9 changes: 6 additions & 3 deletions src/targets/powershell/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,12 @@ export const generatePowershellConvert = (command: PowershellCommand) => {
}

if (postData.text) {
commandOptions.push(`-ContentType '${
escapeString(getHeader(allHeaders, 'content-type'), { delimiter: "'", escapeChar: '`' })
}'`);
commandOptions.push(
`-ContentType '${escapeString(getHeader(allHeaders, 'content-type'), {
delimiter: "'",
escapeChar: '`',
})}'`,
);
commandOptions.push(`-Body '${postData.text}'`);
}

Expand Down
25 changes: 11 additions & 14 deletions src/targets/r/httr/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,31 +98,26 @@ export const httr: Client = {

// Construct headers
const cookieHeader = getHeader(allHeaders, 'cookie');
let acceptHeader = getHeader(allHeaders, 'accept');
const acceptHeader = getHeader(allHeaders, 'accept');

const setCookies = cookieHeader
? `set_cookies(\`${String(cookieHeader)
.replace(/;/g, '", `')
.replace(/` /g, '`')
.replace(/[=]/g, '` = "')
}")`
: undefined
.replace(/[=]/g, '` = "')}")`
: undefined;

const setAccept = acceptHeader
? `accept("${escapeForDoubleQuotes(acceptHeader)}")`
: undefined
const setAccept = acceptHeader ? `accept("${escapeForDoubleQuotes(acceptHeader)}")` : undefined;

const setContentType = `content_type("${escapeForDoubleQuotes(postData.mimeType)}")`
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(', ')
.join(', ');

const setHeaders = otherHeaders
? `add_headers(${otherHeaders})`
: undefined
const setHeaders = otherHeaders ? `add_headers(${otherHeaders})` : undefined;

// Construct request
let request = `response <- VERB("${method}", url`;
Expand All @@ -135,10 +130,12 @@ export const httr: Client = {
request += ', query = queryString';
}

const headerAdditions = [setHeaders, setContentType, setAccept, setCookies].filter(x => !!x).join(', ');
const headerAdditions = [setHeaders, setContentType, setAccept, setCookies]
.filter(x => !!x)
.join(', ');

if (headerAdditions) {
request += ', ' + headerAdditions
request += `, ${ headerAdditions}`;
}

if (postData.text || postData.jsonObj || postData.params) {
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.build.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"downlevelIteration": true,
"lib": ["ESNext"],
"declaration": true,
"declarationMap": true,
"declarationMap": true
},
"include": ["src"],
"exclude": ["dist", "**/*.test.ts"]
Expand Down

0 comments on commit e44a4de

Please sign in to comment.