From dd7e5fe9a05a70fb6d5cb2d4d58c3ed398bbe6b9 Mon Sep 17 00:00:00 2001 From: Ritesh Kumar Date: Wed, 16 Aug 2017 21:01:30 +0530 Subject: [PATCH] add google verification tag --- components/ConversionPanel.js | 290 ++++++++++-------- components/Layout.js | 134 ++++++--- package.json | 4 + pages/css-to-js.js | 56 ++-- pages/html-to-jsx.js | 33 +- pages/index.js | 32 +- pages/json-to-flow-types.js | 36 +-- pages/json-to-ts-interface.js | 36 +-- utils/babel-plugin-js-to-prop-types.js | 63 ++-- utils/css-to-js.js | 179 ++++++----- utils/dummy-json.js | 4 +- utils/json-to-ts-flow.js | 400 +++++++++++++++---------- yarn.lock | 4 + 13 files changed, 722 insertions(+), 549 deletions(-) diff --git a/components/ConversionPanel.js b/components/ConversionPanel.js index b624bae..55a3659 100644 --- a/components/ConversionPanel.js +++ b/components/ConversionPanel.js @@ -1,22 +1,22 @@ -import React, { PureComponent } from 'react' -import Router from 'next/router' -import isBrowser from 'is-in-browser' -import copy from 'copy-text-to-clipboard' +import React, { PureComponent } from "react"; +import Router from "next/router"; +import isBrowser from "is-in-browser"; +import copy from "copy-text-to-clipboard"; -const theme = 'tomorrow' +const theme = "tomorrow"; -let brace -let AceEditor +let brace; +let AceEditor; if (isBrowser) { - brace = require('brace').default - AceEditor = require('react-ace').default + brace = require("brace").default; + AceEditor = require("react-ace").default; - require('brace/mode/javascript') - require(`brace/theme/${theme}`) - require('brace/mode/json') - require('brace/mode/typescript') - require('brace/mode/css') - require('brace/mode/html') + require("brace/mode/javascript"); + require(`brace/theme/${theme}`); + require("brace/mode/json"); + require("brace/mode/typescript"); + require("brace/mode/css"); + require("brace/mode/html"); } // const prettierParsers = { @@ -27,11 +27,11 @@ if (isBrowser) { // } const prettifyMap = { - css: 'css_beautify', - json: 'js_beautify', - html: 'html_beautify', - typescript: 'js_beautify' -} + css: "css_beautify", + json: "js_beautify", + html: "html_beautify", + typescript: "js_beautify" +}; type Props = { leftMode: ?string, @@ -43,112 +43,123 @@ type Props = { initialCheckboxValue: boolean, leftTitle: string, rightTitle: string -} +}; export default class ConversionPanel extends PureComponent { - props : Props + props: Props; static defaultProps = { - leftMode: 'javascript', - rightMode: 'javascript', - pathname: '/' - } + leftMode: "javascript", + rightMode: "javascript", + pathname: "/" + }; - constructor (props) { - super(props) + constructor(props) { + super(props); this.state = { - resultValue: '', - value: '', - info: '', - infoType: '' - } + resultValue: "", + value: "", + info: "", + infoType: "" + }; } - componentDidMount () { - const code = this.props.url.query.code || this.props.defaultText + componentDidMount() { + const code = this.props.url.query.code || this.props.defaultText; this.setState({ value: code, resultValue: this.props.getTransformedValue(code) - }) + }); } onChange = (newValue: string) => { try { - const code = this.props.getTransformedValue(newValue) + const code = this.props.getTransformedValue(newValue); this.setState({ resultValue: code, - info: '', - infoType: '' - }) + info: "", + infoType: "" + }); - this.setCodeInUrl(newValue) + this.setCodeInUrl(newValue); } catch (e) { this.setState({ info: e.message, - infoType: 'error' - }) + infoType: "error" + }); } this.setState({ value: newValue - }) - } + }); + }; - setCodeInUrl = (code) => { + setCodeInUrl = code => { Router.replace({ pathname: this.props.url.pathname, query: { code } - }) - } + }); + }; toggleCheckbox = (e: MouseEvent) => { - const checked = e.currentTarget.checked + const checked = e.currentTarget.checked; if (this.props.onCheckboxChange) { this.props.onCheckboxChange(checked, () => { this.setState({ resultValue: this.props.getTransformedValue(this.state.value) - }) - }) + }); + }); } - } + }; setResult = (result: string) => { - this.setState({ - value: result - }, () => { - this.setCodeInUrl(result) - }) - } + this.setState( + { + value: result + }, + () => { + this.setCodeInUrl(result); + } + ); + }; prettifyCode = () => { - debugger - const { leftMode } = this.props - const { value } = this.state + debugger; + const { leftMode } = this.props; + const { value } = this.state; - this.setResult(window[prettifyMap[leftMode]](value, {indent_size: 2})) - } + this.setResult(window[prettifyMap[leftMode]](value, { indent_size: 2 })); + }; copyCode = () => { - copy(this.state.resultValue) + copy(this.state.resultValue); this.setState({ - info: 'Code copied to clipboard.', - infoType: 'success' - }) - } + info: "Code copied to clipboard.", + infoType: "success" + }); + }; - render () { - const { leftMode, rightMode, onCheckboxChange, checkboxText, initialCheckboxValue, leftTitle, rightTitle } = this.props - const {infoType, resultValue, value, info} = this.state + render() { + const { + leftMode, + rightMode, + onCheckboxChange, + checkboxText, + initialCheckboxValue, + leftTitle, + rightTitle + } = this.props; + const { infoType, resultValue, value, info } = this.state; return (
- - +
- ) -} \ No newline at end of file + ); +} diff --git a/package.json b/package.json index 580f479..c3cff9a 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ "build": "next build", "dev": "next dev", "analyze": "cross-env ANALYZE=1 next build", + "format": "prettier --write **/*.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], @@ -31,5 +32,8 @@ "react-dom": "^15.6.1", "react-github-corner": "^0.3.0", "webpack-bundle-analyzer": "^2.9.0" + }, + "devDependencies": { + "prettier": "^1.5.3" } } diff --git a/pages/css-to-js.js b/pages/css-to-js.js index 2e8e75b..967ec24 100644 --- a/pages/css-to-js.js +++ b/pages/css-to-js.js @@ -1,9 +1,9 @@ -import React, { PureComponent } from 'react' -import plugin from '../utils/css-to-js' -import Layout from '../components/Layout' -import ConversionPanel from '../components/ConversionPanel' -import transform from 'css-to-react-native' -import kebabCase from 'lodash/kebabCase' +import React, { PureComponent } from "react"; +import plugin from "../utils/css-to-js"; +import Layout from "../components/Layout"; +import ConversionPanel from "../components/ConversionPanel"; +import transform from "css-to-react-native"; +import kebabCase from "lodash/kebabCase"; const defaultText = `.main-wrapper { flex-direction: row; @@ -25,35 +25,36 @@ li { color: whitesmoke; line-height: 44px; } -` +`; export default class Css2Js extends PureComponent { state = { isRn: false - } + }; getRnCode = (newValue: string) => { - const styles = {} - const code = eval('(' + plugin(newValue).split('=')[1] + ')') + const styles = {}; + const code = eval("(" + plugin(newValue).split("=")[1] + ")"); Object.keys(code).forEach(key => { - styles[key] = {} - const arr = [] + styles[key] = {}; + const arr = []; Object.keys(code[key]).forEach(key2 => { - arr.push([ - kebabCase(key2), - code[key][key2] - ]) - }) - styles[key] = transform(arr) - }) - return styles - } + arr.push([kebabCase(key2), code[key][key2]]); + }); + styles[key] = transform(arr); + }); + return styles; + }; getTransformedValue = (newValue: string) => { - return this.state.isRn ? `const styles = StyleSheet.create(${JSON.stringify(this.getRnCode(newValue))})` : plugin(newValue) - } + return this.state.isRn + ? `const styles = StyleSheet.create(${JSON.stringify( + this.getRnCode(newValue) + )})` + : plugin(newValue); + }; - render () { + render() { return ( this.setState({isRn: checked}, cb)} + onCheckboxChange={(checked, cb) => + this.setState({ isRn: checked }, cb)} checkboxText="React Native" /> - ) + ); } } diff --git a/pages/html-to-jsx.js b/pages/html-to-jsx.js index 65a2ed2..0e4fc50 100644 --- a/pages/html-to-jsx.js +++ b/pages/html-to-jsx.js @@ -1,29 +1,29 @@ -import React, { PureComponent } from 'react' -import HTMLtoJSX from '@tsuyoshiwada/htmltojsx' -import Layout from '../components/Layout' -import ConversionPanel from '../components/ConversionPanel' +import React, { PureComponent } from "react"; +import HTMLtoJSX from "@tsuyoshiwada/htmltojsx"; +import Layout from "../components/Layout"; +import ConversionPanel from "../components/ConversionPanel"; const converter = new HTMLtoJSX({ createClass: false, - outputClassName: 'MainComponent' -}) + outputClassName: "MainComponent" +}); const defaultText = `
Hello world! -
` +`; export default class Css2Js extends PureComponent { - state={ + state = { createClass: false - } + }; getTransformedValue = (newValue: string) => { - converter.config.createClass = this.state.createClass - return converter.convert(newValue) - } + converter.config.createClass = this.state.createClass; + return converter.convert(newValue); + }; - render () { + render() { return ( this.setState({createClass: checked}, cb)} + onCheckboxChange={(checked: boolean, cb: Function) => + this.setState({ createClass: checked }, cb)} /> - ) + ); } } diff --git a/pages/index.js b/pages/index.js index 69d3b71..44cac2f 100644 --- a/pages/index.js +++ b/pages/index.js @@ -1,22 +1,22 @@ -import React, { PureComponent } from 'react' -import plugin from '../utils/babel-plugin-js-to-prop-types' -import Layout from '../components/Layout' -import { transform } from 'babel-standalone' -import defaultText from '../utils/dummy-json' +import React, { PureComponent } from "react"; +import plugin from "../utils/babel-plugin-js-to-prop-types"; +import Layout from "../components/Layout"; +import { transform } from "babel-standalone"; +import defaultText from "../utils/dummy-json"; -import ConversionPanel from '../components/ConversionPanel' +import ConversionPanel from "../components/ConversionPanel"; export default class Main extends PureComponent { - getTransformedValue = (newValue) => { - newValue = 'const propTypes = ' + newValue - const {code} = transform(newValue, { - presets: ['es2015'], + getTransformedValue = newValue => { + newValue = "const propTypes = " + newValue; + const { code } = transform(newValue, { + presets: ["es2015"], plugins: [plugin] - }) - return code - } + }); + return code; + }; - render () { + render() { return ( - ) + ); } } diff --git a/pages/json-to-flow-types.js b/pages/json-to-flow-types.js index 0286c6e..3c7d261 100644 --- a/pages/json-to-flow-types.js +++ b/pages/json-to-flow-types.js @@ -1,35 +1,37 @@ -import React, { PureComponent } from 'react' -import dynamic from 'next/dynamic' -import { Json2dts, toValidJSON } from '../utils/json-to-ts-flow' -import Layout from '../components/Layout' -import ConversionPanel from '../components/ConversionPanel' -import defaultText from '../utils/dummy-json' +import React, { PureComponent } from "react"; +import dynamic from "next/dynamic"; +import { Json2dts, toValidJSON } from "../utils/json-to-ts-flow"; +import Layout from "../components/Layout"; +import ConversionPanel from "../components/ConversionPanel"; +import defaultText from "../utils/dummy-json"; export default class Json2Ts extends PureComponent { - getTransformedValue = (newValue) => { - const converter = new Json2dts() - let text2Obj = JSON.parse(toValidJSON(newValue)) - if (typeof text2Obj !== 'object' || Array.isArray(text2Obj)) { - throw new Error('Pass a valid JSON Object. Arrays are not acceptable even though they are valid JSON.') + getTransformedValue = newValue => { + const converter = new Json2dts(); + let text2Obj = JSON.parse(toValidJSON(newValue)); + if (typeof text2Obj !== "object" || Array.isArray(text2Obj)) { + throw new Error( + "Pass a valid JSON Object. Arrays are not acceptable even though they are valid JSON." + ); } - converter.parse(text2Obj, 'props') - return converter.getCode(true) - } + converter.parse(text2Obj, "props"); + return converter.getCode(true); + }; - render () { + render() { return ( - ) + ); } } diff --git a/pages/json-to-ts-interface.js b/pages/json-to-ts-interface.js index 2074660..7f60ef0 100644 --- a/pages/json-to-ts-interface.js +++ b/pages/json-to-ts-interface.js @@ -1,35 +1,37 @@ -import React, { PureComponent } from 'react' -import dynamic from 'next/dynamic' -import { Json2dts, toValidJSON } from '../utils/json-to-ts-flow' -import Layout from '../components/Layout' -import ConversionPanel from '../components/ConversionPanel' -import defaultText from '../utils/dummy-json' +import React, { PureComponent } from "react"; +import dynamic from "next/dynamic"; +import { Json2dts, toValidJSON } from "../utils/json-to-ts-flow"; +import Layout from "../components/Layout"; +import ConversionPanel from "../components/ConversionPanel"; +import defaultText from "../utils/dummy-json"; export default class Json2Ts extends PureComponent { - getTransformedValue = (newValue) => { - const converter = new Json2dts() - let text2Obj = JSON.parse(toValidJSON(newValue)) - if (typeof text2Obj !== 'object' || Array.isArray(text2Obj)) { - throw new Error('Pass a valid JSON Object. Arrays are not acceptable even though they are valid JSON.') + getTransformedValue = newValue => { + const converter = new Json2dts(); + let text2Obj = JSON.parse(toValidJSON(newValue)); + if (typeof text2Obj !== "object" || Array.isArray(text2Obj)) { + throw new Error( + "Pass a valid JSON Object. Arrays are not acceptable even though they are valid JSON." + ); } - converter.parse(text2Obj, 'RootJson') - return converter.getCode() - } + converter.parse(text2Obj, "RootJson"); + return converter.getCode(); + }; - render () { + render() { return ( - ) + ); } } diff --git a/utils/babel-plugin-js-to-prop-types.js b/utils/babel-plugin-js-to-prop-types.js index cbccfc8..e330448 100644 --- a/utils/babel-plugin-js-to-prop-types.js +++ b/utils/babel-plugin-js-to-prop-types.js @@ -1,43 +1,54 @@ -import uniqBy from 'lodash/uniqBy' -import isEmpty from 'lodash/isEmpty' +import uniqBy from "lodash/uniqBy"; +import isEmpty from "lodash/isEmpty"; /** * This is a babel plugin that converts an object to PropTypes * @param t * @returns {{visitor: {ArrayExpression: (function(*)), NullLiteral: (function(*)), StringLiteral: (function(*)), NumericLiteral: (function(*)), ArrowFunctionExpression: (function(*)), FunctionExpression: (function(*)), BooleanLiteral: (function(*)), Program: (function(*, *)), ObjectExpression: (function(*))}}} */ -export default function ({types: t}) { +export default function({ types: t }) { return { visitor: { ArrayExpression(path) { if (t.isCallExpression(path.parent)) return; - let uniqueElements = uniqBy(path.node.elements, 'type'); + let uniqueElements = uniqBy(path.node.elements, "type"); - if(t.isObjectExpression(uniqueElements[0])) { - uniqueElements = [t.callExpression( - t.memberExpression(t.identifier("PropTypes"), t.identifier("shape")), - uniqueElements - )] - } - - if ((!isEmpty(uniqueElements) && uniqueElements.length === 1) || t.isCallExpression(uniqueElements)) { - path.replaceWith( + if (t.isObjectExpression(uniqueElements[0])) { + uniqueElements = [ t.callExpression( - t.memberExpression(t.identifier("PropTypes"), t.identifier("arrayOf")), + t.memberExpression( + t.identifier("PropTypes"), + t.identifier("shape") + ), uniqueElements ) - ) + ]; + } + + if ( + (!isEmpty(uniqueElements) && uniqueElements.length === 1) || + t.isCallExpression(uniqueElements) + ) { + path.replaceWith( + t.callExpression( + t.memberExpression( + t.identifier("PropTypes"), + t.identifier("arrayOf") + ), + uniqueElements + ) + ); } else { - path.replaceWith(t.identifier('PropTypes.array')) + path.replaceWith(t.identifier("PropTypes.array")); } }, NullLiteral(path) { - path.replaceWith(t.identifier('PropTypes.any')) + path.replaceWith(t.identifier("PropTypes.any")); }, StringLiteral(path) { - if (path.parentKey === 'key') return; + if (path.parentKey === "key") return; path.replaceWith(t.identifier(`PropTypes.string`)); }, @@ -54,7 +65,7 @@ export default function ({types: t}) { }, BooleanLiteral(path) { - path.replaceWith(t.identifier('PropTypes.bool')) + path.replaceWith(t.identifier("PropTypes.bool")); }, Program(path) { @@ -66,18 +77,24 @@ export default function ({types: t}) { }, ObjectExpression(path) { - if (t.isVariableDeclarator(path.parent) || t.isCallExpression(path.parent)) + if ( + t.isVariableDeclarator(path.parent) || + t.isCallExpression(path.parent) + ) return; const elements = [path.node]; path.replaceWith( t.callExpression( - t.memberExpression(t.identifier("PropTypes"), t.identifier("shape")), + t.memberExpression( + t.identifier("PropTypes"), + t.identifier("shape") + ), elements ) ); } } - } -} \ No newline at end of file + }; +} diff --git a/utils/css-to-js.js b/utils/css-to-js.js index b8ccba8..d7ce3cf 100644 --- a/utils/css-to-js.js +++ b/utils/css-to-js.js @@ -1,94 +1,92 @@ -const SPACE = ' '; -function toProperty(name){ - if(name.charAt(0) === "-") name = name.slice(0); +const SPACE = " "; +function toProperty(name) { + if (name.charAt(0) === "-") name = name.slice(0); - return name.replace(/[^a-z0-9]([a-z0-9])?/gi, function(v, l){ - if(l) return l.toUpperCase(); + return name.replace(/[^a-z0-9]([a-z0-9])?/gi, function(v, l) { + if (l) return l.toUpperCase(); return ""; - }) ; + }); } -function toSelectors(name){ - const names = name.split(',') +function toSelectors(name) { + const names = name.split(","); - return names.map(function(name){ + return names.map(function(name) { name = name.trim(); - let newName = '' + let newName = ""; - if(name.charAt(0) === "."){ + if (name.charAt(0) === ".") { newName += "Class"; name = name.slice(1); - }else if(name.charAt(0) === "#"){ + } else if (name.charAt(0) === "#") { newName += "Id"; name = name.slice(1); - }else{ + } else { newName += "Element"; } - return name.replace(/([^a-z0-9])([a-z0-9])?/gi, function(v, c, l){ - if(l) return (c === "," || c === " ") ? l.toLowerCase() : l.toUpperCase(); - return ""; - }) + newName; - + return ( + name.replace(/([^a-z0-9])([a-z0-9])?/gi, function(v, c, l) { + if (l) + return c === "," || c === " " ? l.toLowerCase() : l.toUpperCase(); + return ""; + }) + newName + ); }); - } -function tokenizer(code){ - +function tokenizer(code) { const tokens = []; - let token = ''; - const whitespc = ['\r\n', '\n\r', '\n', '\r']; - let lastChar = '\0'; - let nextChar = '\0'; - let char = '\0'; - const specialChars = ["{","}",":",";"]; - const specialCharsPB = ["{","}",";"]; + let token = ""; + const whitespc = ["\r\n", "\n\r", "\n", "\r"]; + let lastChar = "\0"; + let nextChar = "\0"; + let char = "\0"; + const specialChars = ["{", "}", ":", ";"]; + const specialCharsPB = ["{", "}", ";"]; let sc = null; let inBrackets = false; - for(let i = 0; i < code.length; i++){ - - if(i) lastChar = code.charAt(i-1); + for (let i = 0; i < code.length; i++) { + if (i) lastChar = code.charAt(i - 1); char = code.charAt(i); - if(i+1 < code.length) nextChar = code.charAt(i+1); + if (i + 1 < code.length) nextChar = code.charAt(i + 1); - if(~whitespc.indexOf(char) && ~whitespc.indexOf(lastChar)){ + if (~whitespc.indexOf(char) && ~whitespc.indexOf(lastChar)) { continue; } sc = inBrackets ? specialChars : specialCharsPB; - - - if(~sc.indexOf(char)){ - if(char === "{") inBrackets = true; - if(char === "}") inBrackets = false; + if (~sc.indexOf(char)) { + if (char === "{") inBrackets = true; + if (char === "}") inBrackets = false; tokens.push(token); tokens.push(char); - token = ''; + token = ""; continue; } token += char; - } - if(token) tokens.push(token); - + if (token) tokens.push(token); return tokens - .map(function(token){ return token.trim(); }) - .filter(function(token){ return token; }); - + .map(function(token) { + return token.trim(); + }) + .filter(function(token) { + return token; + }); } -function convertoToJS(tokens){ - const items = [] - let actualItem = null - let actualProp = null - function readSelector(token){ - const selectors = toSelectors(token) +function convertoToJS(tokens) { + const items = []; + let actualItem = null; + let actualProp = null; + function readSelector(token) { + const selectors = toSelectors(token); actualItem = { originalValue: token, @@ -102,109 +100,100 @@ function convertoToJS(tokens){ return readBracketO; } - function readBracketO(token){ - - if(token !== "{") throw new Error("expected '{' "); + function readBracketO(token) { + if (token !== "{") throw new Error("expected '{' "); return readProperty; } - function readBracketC(token){ - if(token !== "}") throw new Error("expected '}' "); + function readBracketC(token) { + if (token !== "}") throw new Error("expected '}' "); return readSelector; } - function readDefinition(token){ - if(token !== ":") throw new Error("expected ':' "); + function readDefinition(token) { + if (token !== ":") throw new Error("expected ':' "); return readValue; } - function readProperty(token){ + function readProperty(token) { + if (token === "}") return readBracketC(token); - if(token === "}") return readBracketC(token); - - const property = toProperty(token) + const property = toProperty(token); actualProp = property; - if(!actualItem.values[property]){ + if (!actualItem.values[property]) { actualItem.values[property] = []; } return readDefinition; } - function readValue(token){ - + function readValue(token) { actualItem.values[actualProp].push(token); return readFinal; } - function readFinal(token){ - if(token === "}") return readBracketC(token); - if(token !== ";") throw new Error("expected ';' "); + function readFinal(token) { + if (token === "}") return readBracketC(token); + if (token !== ";") throw new Error("expected ';' "); return readProperty; } - let nextAction = readSelector - let i = 0 - tokens.forEach(function(token){ + let nextAction = readSelector; + let i = 0; + tokens.forEach(function(token) { i++; nextAction = nextAction(token); - }); return renderJS(items); - } -function renderJS(items){ - - let objects = ['const styles = {'] +function renderJS(items) { + let objects = ["const styles = {"]; objects = objects.concat(items.map(renderItem).join(",")); objects.push("}"); return objects.join("\n"); } -function renderItem(item){ +function renderItem(item) { + const code = ["\n//" + item.originalValue]; - const code = ['\n//' + item.originalValue] + let properties = []; - let properties = [] - - for(const prop in item.values){ - if(item.values.hasOwnProperty(prop)) { + for (const prop in item.values) { + if (item.values.hasOwnProperty(prop)) { const propitem = { name: prop, value: item.values[prop][item.values[prop].length - 1] - } - let markup = '"' + }; + let markup = '"'; if (~propitem.value.indexOf('"')) { markup = "'"; propitem.value = propitem.value.replace(/'/gi, "\\'"); } - properties.push(SPACE + SPACE + propitem.name + ": " + markup + propitem.value + markup); + properties.push( + SPACE + SPACE + propitem.name + ": " + markup + propitem.value + markup + ); } } - properties = properties.map(function(x){ return SPACE + x; }); - - item.selectors.forEach(function(i){ + properties = properties.map(function(x) { + return SPACE + x; + }); + item.selectors.forEach(function(i) { code.push(SPACE + i + ": {"); code.push(properties.join(",\n")); code.push(SPACE + "}"); - }); return code.join("\n"); - } - -export default function transformCode (code) { - return convertoToJS(tokenizer(code)) +export default function transformCode(code) { + return convertoToJS(tokenizer(code)); } - - diff --git a/utils/dummy-json.js b/utils/dummy-json.js index 39268da..750a463 100644 --- a/utils/dummy-json.js +++ b/utils/dummy-json.js @@ -40,6 +40,6 @@ const x = `{ } ] } - ` + `; -export default x \ No newline at end of file +export default x; diff --git a/utils/json-to-ts-flow.js b/utils/json-to-ts-flow.js index 758efb4..0c6945b 100644 --- a/utils/json-to-ts-flow.js +++ b/utils/json-to-ts-flow.js @@ -1,79 +1,107 @@ var is; -(function (is) { +(function(is) { var ObjProto = Object.prototype; var ArrayProto = Array.prototype; var toString = ObjProto.toString; var hasOwn = ObjProto.hasOwnProperty; - var index_of = (ArrayProto.indexOf ? - function (arr, val) { return arr.indexOf(val); } : - function (arr, val) { - for (var i = 0, l = arr.length; i < l; i++) { - if (arr[i] === val) { - return i; - } + var index_of = ArrayProto.indexOf + ? function(arr, val) { + return arr.indexOf(val); } - return -1; - }); + : function(arr, val) { + for (var i = 0, l = arr.length; i < l; i++) { + if (arr[i] === val) { + return i; + } + } + return -1; + }; function string(s) { - return (typeof s === 'string') || s instanceof String; + return typeof s === "string" || s instanceof String; } is.string = string; - function number(n) { return (typeof n === 'number') || n instanceof Number; } + function number(n) { + return typeof n === "number" || n instanceof Number; + } is.number = number; - function boolean(b) { return b === !!b || b instanceof Boolean; } + function boolean(b) { + return b === !!b || b instanceof Boolean; + } is.boolean = boolean; - function fn(f) { return (typeof f === 'function'); } + function fn(f) { + return typeof f === "function"; + } is.fn = fn; - ; - is.array = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; }; - function object(o) { return o === Object(o); } + is.array = + Array.isArray || + function(a) { + return toString.call(a) === "[object Array]"; + }; + function object(o) { + return o === Object(o); + } is.object = object; - ; - function regex(r) { return !!(r && r.test && r.exec && (r.ignoreCase || r.ignoreCase === false)); } + function regex(r) { + return !!( + r && + r.test && + r.exec && + (r.ignoreCase || r.ignoreCase === false) + ); + } is.regex = regex; - ; - is.element = (typeof HTMLElement !== 'undefined' ? - function (e) { return (e instanceof HTMLElement); } : - function (e) { return !!(e && e.nodeType === 1); }); - function numeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } + is.element = + typeof HTMLElement !== "undefined" + ? function(e) { + return e instanceof HTMLElement; + } + : function(e) { + return !!(e && e.nodeType === 1); + }; + function numeric(n) { + return !isNaN(parseFloat(n)) && isFinite(n); + } is.numeric = numeric; - ; function hash(o) { - if (!o || typeof o !== 'object' || is.element(o) || (typeof window !== 'undefined' && o === window) || - (o.constructor && !hasOwn.call(o, 'constructor') && !hasOwn.call(o.constructor.prototype, 'isPrototypeOf'))) { + if ( + !o || + typeof o !== "object" || + is.element(o) || + (typeof window !== "undefined" && o === window) || + (o.constructor && + !hasOwn.call(o, "constructor") && + !hasOwn.call(o.constructor.prototype, "isPrototypeOf")) + ) { return false; } - for (var key in o) { } - return (key === undefined || hasOwn.call(o, key)); + for (var key in o) { + } + return key === undefined || hasOwn.call(o, key); } is.hash = hash; - ; function inside(container, val) { if (is.array(container)) { return index_of(container, val) > -1; - } - else if (is.object(container)) { + } else if (is.object(container)) { for (var prop in container) { if (hasOwn.call(container, prop) && container[prop] === val) { return true; } } return false; - } - else { + } else { return false; } } is.inside = inside; - ; - function set(v) { return v !== null && v !== (void 0); } + function set(v) { + return v !== null && v !== void 0; + } is.set = set; - ; function empty(container) { if (is.array(container)) { return container.length === 0; - } - else if (is.object(container)) { + } else if (is.object(container)) { if (is.fn(container.valueOf) && !is.object(container.valueOf())) { return is.empty(container.valueOf()); } @@ -83,8 +111,7 @@ var is; } } return true; - } - else { + } else { return !container; } } @@ -95,7 +122,6 @@ function SHA1(msg) { var t4 = (n << s) | (n >>> (32 - s)); return t4; } - ; function lsb_hex(val) { var str = ""; var i; @@ -108,7 +134,6 @@ function SHA1(msg) { } return str; } - ; function cvt_hex(val) { var str = ""; var i; @@ -119,7 +144,6 @@ function SHA1(msg) { } return str; } - ; function Utf8Encode(string) { string = string.replace(/\r\n/g, "\n"); var utftext = ""; @@ -127,12 +151,10 @@ function SHA1(msg) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); - } - else if ((c > 127) && (c < 2048)) { + } else if (c > 127 && c < 2048) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); - } - else { + } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); @@ -140,23 +162,25 @@ function SHA1(msg) { } return utftext; } - ; var blockstart; var i, j; var W = new Array(80); var H0 = 0x67452301; - var H1 = 0xEFCDAB89; - var H2 = 0x98BADCFE; + var H1 = 0xefcdab89; + var H2 = 0x98badcfe; var H3 = 0x10325476; - var H4 = 0xC3D2E1F0; + var H4 = 0xc3d2e1f0; var A, B, C, D, E; var temp; msg = Utf8Encode(msg); var msg_len = msg.length; var word_array = new Array(); for (i = 0; i < msg_len - 3; i += 4) { - j = msg.charCodeAt(i) << 24 | msg.charCodeAt(i + 1) << 16 | - msg.charCodeAt(i + 2) << 8 | msg.charCodeAt(i + 3); + j = + (msg.charCodeAt(i) << 24) | + (msg.charCodeAt(i + 1) << 16) | + (msg.charCodeAt(i + 2) << 8) | + msg.charCodeAt(i + 3); word_array.push(j); } switch (msg_len % 4) { @@ -164,23 +188,28 @@ function SHA1(msg) { i = 0x080000000; break; case 1: - i = msg.charCodeAt(msg_len - 1) << 24 | 0x0800000; + i = (msg.charCodeAt(msg_len - 1) << 24) | 0x0800000; break; case 2: - i = msg.charCodeAt(msg_len - 2) << 24 | msg.charCodeAt(msg_len - 1) << 16 | 0x08000; + i = + (msg.charCodeAt(msg_len - 2) << 24) | + (msg.charCodeAt(msg_len - 1) << 16) | + 0x08000; break; case 3: - i = msg.charCodeAt(msg_len - 3) << 24 | msg.charCodeAt(msg_len - 2) << 16 | msg.charCodeAt(msg_len - 1) << 8 | 0x80; + i = + (msg.charCodeAt(msg_len - 3) << 24) | + (msg.charCodeAt(msg_len - 2) << 16) | + (msg.charCodeAt(msg_len - 1) << 8) | + 0x80; break; } word_array.push(i); - while ((word_array.length % 16) != 14) - word_array.push(0); + while (word_array.length % 16 != 14) word_array.push(0); word_array.push(msg_len >>> 29); word_array.push((msg_len << 3) & 0x0ffffffff); for (blockstart = 0; blockstart < word_array.length; blockstart += 16) { - for (i = 0; i < 16; i++) - W[i] = word_array[blockstart + i]; + for (i = 0; i < 16; i++) W[i] = word_array[blockstart + i]; for (i = 16; i <= 79; i++) W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); A = H0; @@ -189,7 +218,9 @@ function SHA1(msg) { D = H3; E = H4; for (i = 0; i <= 19; i++) { - temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff; + temp = + (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5a827999) & + 0x0ffffffff; E = D; D = C; C = rotate_left(B, 30); @@ -197,7 +228,8 @@ function SHA1(msg) { A = temp; } for (i = 20; i <= 39; i++) { - temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff; + temp = + (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ed9eba1) & 0x0ffffffff; E = D; D = C; C = rotate_left(B, 30); @@ -205,7 +237,13 @@ function SHA1(msg) { A = temp; } for (i = 40; i <= 59; i++) { - temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff; + temp = + (rotate_left(A, 5) + + ((B & C) | (B & D) | (C & D)) + + E + + W[i] + + 0x8f1bbcdc) & + 0x0ffffffff; E = D; D = C; C = rotate_left(B, 30); @@ -213,7 +251,8 @@ function SHA1(msg) { A = temp; } for (i = 60; i <= 79; i++) { - temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff; + temp = + (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xca62c1d6) & 0x0ffffffff; E = D; D = C; C = rotate_left(B, 30); @@ -226,41 +265,48 @@ function SHA1(msg) { H3 = (H3 + D) & 0x0ffffffff; H4 = (H4 + E) & 0x0ffffffff; } - var temp2 = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4); + var temp2 = + cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4); return temp2.toLowerCase(); } -var Types = (function () { - function Types() { - } - Types.STRING = 'string'; - Types.NUMBER = 'number'; - Types.BOOLEAN = 'boolean'; - Types.ARRAY = '[]'; +var Types = (function() { + function Types() {} + Types.STRING = "string"; + Types.NUMBER = "number"; + Types.BOOLEAN = "boolean"; + Types.ARRAY = "[]"; return Types; })(); exports.Types = Types; -var Json2dts = (function () { +var Json2dts = (function() { function Json2dts() { - this.is_value_consistent = function (o) { + this.is_value_consistent = function(o) { var _this = this; if (this.size(o) == 0) { return true; - } - else { + } else { if (!is.array(o)) { o = this.values(o); } var n = o[0]; - var nn = (is.object(n) ? this.generate_signature(n) : typeof n); - return Object.keys(o).every(function (key) { - return (is.object(o[key]) ? _this.generate_signature(o[key]) : typeof o[key]) == nn; + var nn = is.object(n) ? this.generate_signature(n) : typeof n; + return Object.keys(o).every(function(key) { + return ( + (is.object(o[key]) + ? _this.generate_signature(o[key]) + : typeof o[key]) == nn + ); }); } }; } - Json2dts.prototype.parse = function (obj, objectName, moduleName) { - if (objectName === void 0) { objectName = "_RootInterface"; } - if (moduleName === void 0) { moduleName = ""; } + Json2dts.prototype.parse = function(obj, objectName, moduleName) { + if (objectName === void 0) { + objectName = "_RootInterface"; + } + if (moduleName === void 0) { + moduleName = ""; + } this.moduleName = moduleName; this.classes = {}; this.classesCache = {}; @@ -268,32 +314,37 @@ var Json2dts = (function () { this.analyse_object(obj, objectName); return this.classes; }; - Json2dts.prototype.getCode = function (flow) { + Json2dts.prototype.getCode = function(flow) { var _this = this; var output; var classes = {}; var outputModule = this.moduleName == "" ? false : true; var interfaceTab = outputModule ? "\t" : ""; var propertyTab = interfaceTab + "\t"; - Object.keys(this.classes).map(function (clsName) { - output = flow ? interfaceTab + "type " + clsName + ' = \n' + interfaceTab + '{\n' : - interfaceTab + "interface " + clsName + ' \n' + interfaceTab + '{\n' - Object.keys(_this.classes[clsName]).map(function (key) { - output += propertyTab + key + ':' + _this.classes[clsName][key] + ';\n'; + Object.keys(this.classes).map(function(clsName) { + output = flow + ? interfaceTab + "type " + clsName + " = \n" + interfaceTab + "{\n" + : interfaceTab + "interface " + clsName + " \n" + interfaceTab + "{\n"; + Object.keys(_this.classes[clsName]).map(function(key) { + output += propertyTab + key + ":" + _this.classes[clsName][key] + ";\n"; }); - output += interfaceTab + '}\n\n'; + output += interfaceTab + "}\n\n"; classes[clsName] = output; }); output = outputModule ? "module " + this.moduleName + "\n{\n" : ""; - Object.keys(classes).sort().forEach(function (key) { output += classes[key]; }); + Object.keys(classes).sort().forEach(function(key) { + output += classes[key]; + }); return output + (outputModule ? "\n}" : ""); }; - Json2dts.prototype.analyse_object = function (obj, objectName) { + Json2dts.prototype.analyse_object = function(obj, objectName) { var _this = this; - if (objectName === void 0) { objectName = "json"; } + if (objectName === void 0) { + objectName = "json"; + } objectName = this.getInterfaceType(objectName, obj); this.classes[objectName] = this.classes[objectName] || {}; - Object.keys(obj).map(function (key) { + Object.keys(obj).map(function(key) { var type = "string"; var sha = ""; var value = obj[key]; @@ -312,14 +363,12 @@ var Json2dts = (function () { if (_this.is_value_consistent(value)) { if (_this.size(value) == 0) { type = "any[]"; - } - else { + } else { if (is.object(value[0])) { - type = _this.getInterfaceType(key, value[0]) + '[]'; + type = _this.getInterfaceType(key, value[0]) + "[]"; _this.analyse_object(value[0], key); - } - else { - type = _this.getBasicType(value[0]) + '[]'; + } else { + type = _this.getBasicType(value[0]) + "[]"; } } } @@ -332,15 +381,14 @@ var Json2dts = (function () { } break; } - if (_this.hasSpecialChars((key))) { - key = '\"' + key + '\"'; + if (_this.hasSpecialChars(key)) { + key = '"' + key + '"'; } _this.classes[objectName][key] = type; }); }; - Json2dts.prototype.objectParser = function (key) { - }; - Json2dts.prototype.getBasicType = function (value) { + Json2dts.prototype.objectParser = function(key) {}; + Json2dts.prototype.getBasicType = function(value) { var type = Types.STRING; switch (true) { case is.string(value): @@ -355,15 +403,19 @@ var Json2dts = (function () { } return type; }; - Json2dts.prototype.getInterfaceType = function (key, value) { + Json2dts.prototype.getInterfaceType = function(key, value) { // get a valid className - key = key.replace(/_/gi, ' ').replace(/-/gi, ' ').replace(/\w\S*/g, function (txt) { - return txt.charAt(0).toUpperCase() + txt.substr(1); - }).replace(/ /gi, ''); + key = key + .replace(/_/gi, " ") + .replace(/-/gi, " ") + .replace(/\w\S*/g, function(txt) { + return txt.charAt(0).toUpperCase() + txt.substr(1); + }) + .replace(/ /gi, ""); var currentObjectSignature = this.generate_signature(value); - var isKnownClass = Object.keys(this.classesCache).indexOf(currentObjectSignature) != -1; - if (isKnownClass) - return this.classesCache[currentObjectSignature]; + var isKnownClass = + Object.keys(this.classesCache).indexOf(currentObjectSignature) != -1; + if (isKnownClass) return this.classesCache[currentObjectSignature]; if (this.classesInUse[key] != undefined) { this.classesInUse[key]++; this.classesCache[currentObjectSignature] = key + this.classesInUse[key]; @@ -373,32 +425,44 @@ var Json2dts = (function () { this.classesInUse[key] = 0; return key; }; - Json2dts.prototype.size = function (obj) { - if (obj == null) - return 0; - return (obj.length === +obj.length) ? obj.length : Object.keys(obj).length; + Json2dts.prototype.size = function(obj) { + if (obj == null) return 0; + return obj.length === +obj.length ? obj.length : Object.keys(obj).length; }; - Json2dts.prototype.values = function (obj) { - return Object.keys(obj).map(function (key) { return obj[key]; }); + Json2dts.prototype.values = function(obj) { + return Object.keys(obj).map(function(key) { + return obj[key]; + }); }; - Json2dts.prototype.generate_signature = function (o) { + Json2dts.prototype.generate_signature = function(o) { if (is.object(o)) { - return SHA1(Object.keys(o).map(function (n) { - return n.toLowerCase(); - }).sort().join('|')); - } - else { - return SHA1(Object.keys(o).map(function (n) { - return typeof n; - }).sort().join('|')); + return SHA1( + Object.keys(o) + .map(function(n) { + return n.toLowerCase(); + }) + .sort() + .join("|") + ); + } else { + return SHA1( + Object.keys(o) + .map(function(n) { + return typeof n; + }) + .sort() + .join("|") + ); } }; - Json2dts.prototype.hasSpecialChars = function (str) { + Json2dts.prototype.hasSpecialChars = function(str) { return /[ ~`!#$%\^&*+=\-\[\]\\';,\/{}|\\":<>\?]/g.test(str); }; - Json2dts.prototype.keysrt = function (key, desc) { - if (desc === void 0) { desc = false; } - return function (a, b) { + Json2dts.prototype.keysrt = function(key, desc) { + if (desc === void 0) { + desc = false; + } + return function(a, b) { return desc ? ~~(a[key] < b[key]) : ~~(a[key] > b[key]); }; }; @@ -406,38 +470,56 @@ var Json2dts = (function () { })(); exports.Json2dts = Json2dts; function extractLineFeeds(s) { - return s.replace(/[^\n]+/g, ''); + return s.replace(/[^\n]+/g, ""); } function toValidJSON(input, keepLineNumbers) { - if (keepLineNumbers === void 0) { keepLineNumbers = false; } + if (keepLineNumbers === void 0) { + keepLineNumbers = false; + } var UNESCAPE_MAP = { '\\"': '"', "\\`": "`", "\\'": "'" }; - var ML_ESCAPE_MAP = { '\n': '\\n', "\r": '\\r', "\t": '\\t', '"': '\\"' }; - function unescapeQuotes(r) { return UNESCAPE_MAP[r] || r; } - return input.replace(/`(?:\\.|[^`])*`|'(?:\\.|[^'])*'|"(?:\\.|[^"])*"|\/\*[^]*?\*\/|\/\/.*\n?/g, function (s) { - if (s.charAt(0) == '/') { - return keepLineNumbers ? extractLineFeeds(s) : ''; - } - else { - return s; - } - }) - .replace(/(?:true|false|null)(?=[^\w_$]|$)|([a-zA-Z_$][\w_$]*)|`((?:\\.|[^`])*)`|'((?:\\.|[^'])*)'|"(?:\\.|[^"])*"|(,)(?=\s*[}\]])/g, function (s, identifier, multilineQuote, singleQuote, lonelyComma) { - if (lonelyComma) { - return ''; + var ML_ESCAPE_MAP = { "\n": "\\n", "\r": "\\r", "\t": "\\t", '"': '\\"' }; + function unescapeQuotes(r) { + return UNESCAPE_MAP[r] || r; + } + return input + .replace( + /`(?:\\.|[^`])*`|'(?:\\.|[^'])*'|"(?:\\.|[^"])*"|\/\*[^]*?\*\/|\/\/.*\n?/g, + function(s) { + if (s.charAt(0) == "/") { + return keepLineNumbers ? extractLineFeeds(s) : ""; + } else { + return s; + } } - else if (identifier != null) { - return '"' + identifier + '"'; + ) + .replace( + /(?:true|false|null)(?=[^\w_$]|$)|([a-zA-Z_$][\w_$]*)|`((?:\\.|[^`])*)`|'((?:\\.|[^'])*)'|"(?:\\.|[^"])*"|(,)(?=\s*[}\]])/g, + function(s, identifier, multilineQuote, singleQuote, lonelyComma) { + if (lonelyComma) { + return ""; + } else if (identifier != null) { + return '"' + identifier + '"'; + } else if (multilineQuote != null) { + return ( + '"' + + multilineQuote + .replace(/\\./g, unescapeQuotes) + .replace(/[\n\r\t"]/g, function(r) { + return ML_ESCAPE_MAP[r]; + }) + + '"' + + (keepLineNumbers ? extractLineFeeds(multilineQuote) : "") + ); + } else if (singleQuote != null) { + return ( + '"' + + singleQuote.replace(/\\./g, unescapeQuotes).replace(/"/g, '\\"') + + '"' + ); + } else { + return s; + } } - else if (multilineQuote != null) { - return '"' + multilineQuote.replace(/\\./g, unescapeQuotes).replace(/[\n\r\t"]/g, function (r) { return ML_ESCAPE_MAP[r]; }) + - '"' + (keepLineNumbers ? extractLineFeeds(multilineQuote) : ''); - } - else if (singleQuote != null) { - return '"' + singleQuote.replace(/\\./g, unescapeQuotes).replace(/"/g, '\\"') + '"'; - } - else { - return s; - } - }); + ); } exports.toValidJSON = toValidJSON; diff --git a/yarn.lock b/yarn.lock index cd5be36..eac1996 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3203,6 +3203,10 @@ preserve@^0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b" +prettier@^1.5.3: + version "1.5.3" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.5.3.tgz#59dadc683345ec6b88f88b94ed4ae7e1da394bfe" + pretty@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/pretty/-/pretty-2.0.0.tgz#adbc7960b7bbfe289a557dc5f737619a220d06a5"