Files
insomnia/app/templating/utils.js
T
Gregory Schier d675222bdd Merge develop for 5.1.0 (#246)
* Add Slack badge to README

* Add Twitter badge

* Appveyor badge

* Fix badges again on README

* Fix Twitter badge link

* Simplify README.md

* Migrate Travis secure items to Travis project settings (#198)

* Remove docker linux build (using Travis now) (#199)

* Fix travis build

* Update Issue and PR templates (#200)

* Add template for future pull requests

* Format issue template like pull request template

* Will not clear selected file if dialog is dismissed (#202)

* #183, Body type "Text -> Other" reverts to previous body type (#193)

* ISSUE#183

* Adding condition to check mime-type to other

* Removing older changes for fixing issue.

* Save full response to a file (#207)

* Save full response to a file

* Add a new button on the response preview pane
* Save full response to file when button clicked

* Update after PR comments

* It's a Response, not a Request

* Remove file extension requirement

* Implement lazy tag rendering and some fixes (#211)

* expanding to 3 decimals (#213)

* Update PULL_REQUEST_TEMPLATE.md (#214)

* Show build info in console (#216)

* Add waiting message in dev mode while webpack compile happens

* Switch license from GPL to AGPL (#221)

* Default remote URLs to production

* Don't use Curl's cookie handling (#220)

* Some improvements to the response tag

* Add tests for XPath response queries

* Refactor conditional element syntax

* Add option to toggle Menu Bar showing for Windows/Linux (#225)

* Add option to toggle MenuBar showing on Windows/Linux

* Extract Toggling Menu Bar functionality to App Container. Default show Menu Bar. Remove tip from Response Pane.

* Finalize {% response ... %} Tag (#224)

* Some improvements to the response tag

* Add tests for XPath response queries

* Refactor conditional element syntax

* Update nunjucks-tags.js

* Better Nunjucks Tag Editor (#234)

* Helper to tokenize Nunjucks tag

* More granular types

* Add tag definitions

* Improve editor to be more WYSIWYG

* Fixed tests

* Added raw response tag

* A few improvements to tag editor enum

* fix NTLM typo (#244)

* Tweaks and fixes for next release (#245)
2017-05-24 09:25:22 -07:00

146 lines
3.8 KiB
JavaScript

/**
* Get list of paths to all primitive types in nested object
* @param {object} obj - object to analyse
* @param {String} [prefix] - base path to prefix to all paths
* @returns {Array} - list of paths
*/
export function getKeys (obj, prefix = '') {
let allKeys = [];
if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; i++) {
allKeys = [...allKeys, ...getKeys(obj[i], `${prefix}[${i}]`)];
}
} else if (typeof obj === 'object') {
for (const key of Object.keys(obj)) {
const newPrefix = prefix ? `${prefix}.${key}` : key;
allKeys = [...allKeys, ...getKeys(obj[key], newPrefix)];
}
} else if (typeof obj === 'function') {
// Skip functions
} else if (prefix) {
allKeys.push({name: prefix, value: obj});
}
return allKeys;
}
/**
* Parse a Nunjucks tag string into a usable abject
* @param {string} tagStr - the template string for the tag
* @return {object} parsed tag data
*/
export function tokenizeTag (tagStr) {
// ~~~~~~~~ //
// Sanitize //
// ~~~~~~~~ //
const withoutEnds = tagStr
.trim()
.replace(/^{%/, '')
.replace(/%}$/, '')
.trim();
const nameMatch = withoutEnds.match(/^[a-zA-Z_$][0-9a-zA-Z_$]*/);
const name = nameMatch ? nameMatch[0] : withoutEnds;
const argsStr = withoutEnds.slice(name.length);
// ~~~~~~~~~~~~~ //
// Tokenize Args //
// ~~~~~~~~~~~~~ //
const args = [];
let quotedBy = null;
let currentArg = null;
for (let i = 0; i < argsStr.length; i++) {
const c = argsStr.charAt(i);
// Do nothing if we're still on a space o comma
if (currentArg === null && c.match(/[\s,]/)) {
continue;
}
// Start a new single-quoted string
if (currentArg === null && c === "'") {
currentArg = '';
quotedBy = "'";
continue;
}
// Start a new double-quoted string
if (currentArg === null && c === '"') {
currentArg = '';
quotedBy = '"';
continue;
}
// Start a new unquoted string
if (currentArg === null) {
currentArg = c;
quotedBy = null;
continue;
}
const endQuoted = quotedBy && c === quotedBy;
const endUnquoted = !quotedBy && c === ',';
const finalChar = i === argsStr.length - 1;
const argCompleted = endQuoted || endUnquoted;
// Append current char to argument
if (!argCompleted && currentArg !== null) {
if (c === '\\') {
// Handle backslashes
i += 1;
currentArg += argsStr.charAt(i);
} else {
currentArg += c;
}
}
// End current argument
if (currentArg !== null && (argCompleted || finalChar)) {
let arg;
if (quotedBy) {
arg = {type: 'string', value: currentArg, quotedBy};
} else if (['true', 'false'].includes(currentArg)) {
arg = {type: 'boolean', value: currentArg};
} else if (currentArg.match(/^\d*\.?\d*$/)) {
arg = {type: 'number', value: currentArg};
} else if (currentArg.match(/^[a-zA-Z_$][0-9a-zA-Z_$]*$/)) {
arg = {type: 'variable', value: currentArg};
} else {
arg = {type: 'expression', value: currentArg};
}
args.push(arg);
currentArg = null;
quotedBy = null;
}
}
return {name, args};
}
/**
* Convert a tokenized tag back into a Nunjucks string
* @param {object} tagData - tag data to serialize
* @return {string} tag as a Nunjucks string
*/
export function unTokenizeTag (tagData) {
const args = [];
for (const arg of tagData.args) {
if (arg.type === 'string') {
const q = arg.quotedBy || "'";
const re = new RegExp(`([^\\\\])${q}`, 'g');
const str = arg.value.replace(re, `$1\\${q}`);
args.push(`${q}${str}${q}`);
} else {
args.push(arg.value);
}
}
const argsStr = args.join(', ');
return `{% ${tagData.name} ${argsStr} %}`;
}