From 23768a1a2b835ccdf3603e6c4bd95264c2bd464f Mon Sep 17 00:00:00 2001 From: mbneobrix Date: Sat, 26 Aug 2023 14:51:50 +0530 Subject: [PATCH] Format and Regeneration --- generator/generators/aws/generator.js | 397 +++--- generator/generators/azure/generator.js | 485 +++++--- generator/generators/azure/generator.ts | 272 ++--- generator/generators/do/generator.js | 393 ++++-- generator/generators/do/generator.ts | 212 ++-- generator/generators/googleCloud/generator.js | 1081 +++++++++++------ generator/generators/googleCloud/generator.ts | 725 +++++------ generator/generators/lib/aws/awsHelper.js | 56 +- generator/generators/lib/aws/awsHelper.ts | 52 +- generator/generators/lib/azure/azureHelper.js | 93 +- generator/generators/lib/azure/azureHelper.ts | 108 +- .../generators/lib/googleCloud/gcpHelper.js | 99 +- .../generators/lib/googleCloud/gcpHelper.ts | 116 +- generator/generators/lib/helper.js | 65 +- generator/generators/lib/helper.ts | 62 +- generator/main.js | 62 +- generator/parsers/aws/parser.js | 274 +++-- generator/parsers/azure/parser.js | 276 +++-- generator/parsers/do/parser.js | 275 +++-- generator/parsers/googleCloud/parser.js | 326 +++-- generator/parsers/googleCloud/parser.ts | 98 +- .../generators/googleCloud/generator.test.ts | 312 ++--- generator/transformers/aws/transformer.js | 620 +++++++--- generator/transformers/aws/transformer.ts | 433 +++---- generator/transformers/azure/transformer.js | 662 +++++++--- generator/transformers/azure/transformer.ts | 435 +++---- generator/transformers/do/transformer.js | 656 +++++++--- generator/transformers/do/transformer.ts | 481 ++++---- .../googleCloud/classBasedTransformer.js | 772 ++++++++---- .../googleCloud/classBasedTransformer.ts | 592 ++++----- .../googleCloud/clientBasedTransformer.js | 742 +++++++---- .../googleCloud/clientBasedTransformer.ts | 493 ++++---- 32 files changed, 7221 insertions(+), 4504 deletions(-) diff --git a/generator/generators/aws/generator.js b/generator/generators/aws/generator.js index 61239627..508d06c2 100644 --- a/generator/generators/aws/generator.js +++ b/generator/generators/aws/generator.js @@ -1,145 +1,268 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; +'use strict'; +var __awaiter = + (this && this.__awaiter) || + function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator['throw'](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done + ? resolve(result.value) + : adopt(result.value).then(fulfilled, rejected); + } + step( + (generator = generator.apply(thisArg, _arguments || [])).next() + ); + }); + }; +var __generator = + (this && this.__generator) || + function(thisArg, body) { + var _ = { + label: 0, + sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [], + }, + f, + y, + t, + g; + return ( + (g = { next: verb(0), throw: verb(1), return: verb(2) }), + typeof Symbol === 'function' && + (g[Symbol.iterator] = function() { + return this; + }), + g + ); + function verb(n) { + return function(v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError('Generator is already executing.'); + while (_) + try { + if ( + ((f = 1), + y && + (t = + op[0] & 2 + ? y['return'] + : op[0] + ? y['throw'] || + ((t = y['return']) && t.call(y), 0) + : y.next) && + !(t = t.call(y, op[1])).done) + ) + return t; + if (((y = 0), t)) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if ( + !((t = _.trys), + (t = t.length > 0 && t[t.length - 1])) && + (op[0] === 6 || op[0] === 2) + ) { + _ = 0; + continue; + } + if ( + op[0] === 3 && + (!t || (op[1] > t[0] && op[1] < t[3])) + ) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } + }; exports.__esModule = true; exports.generateAWSClass = exports.extractSDKData = void 0; -var fs = require("fs"); -var typescript_1 = require("typescript"); -var parser_1 = require("../../parsers/aws/parser"); -var transformer_1 = require("../../transformers/aws/transformer"); -var helper_1 = require("../lib/helper"); -var dummyFile = process.cwd() + "/dummyClasses/aws.js"; -var dummyAst = typescript_1.createSourceFile(dummyFile, fs.readFileSync(dummyFile).toString(), typescript_1.ScriptTarget.Latest, true); +var fs = require('fs'); +var typescript_1 = require('typescript'); +var parser_1 = require('../../parsers/aws/parser'); +var transformer_1 = require('../../transformers/aws/transformer'); +var helper_1 = require('../lib/helper'); +var dummyFile = process.cwd() + '/dummyClasses/aws.js'; +var dummyAst = typescript_1.createSourceFile( + dummyFile, + fs.readFileSync(dummyFile).toString(), + typescript_1.ScriptTarget.Latest, + true +); function extractSDKData(sdkClassAst, serviceClass) { - var methods = []; - var functions = []; - Object.keys(serviceClass).map(function (key, index) { - functions.push(serviceClass[key].split(" ")[1]); - }); - sdkClassAst.members.map(function (method) { - if (method.name && functions.includes(method.name.text)) { - var name_1; - Object.keys(serviceClass).map(function (key, index) { - if (serviceClass[key].split(" ")[1] === method.name.text) { - name_1 = key; - } - }); - var parameters_1 = []; - method.parameters.map(function (param) { - if (param.name.text !== "callback") { - var parameter = { - name: param.name.text, - optional: param.questionToken ? true : false, - type: typescript_1.SyntaxKind[param.type.kind], - typeName: null - }; - if (parameter.type === "TypeReference" && param.type.typeName) { - parameter.typeName = param.type.typeName.right.text; - } - parameters_1.push(parameter); - } - }); - methods.push({ - functionName: name_1.toString(), - SDKFunctionName: method.name.text.toString(), - params: parameters_1 - }); - } - }); - var groupedMethods = helper_1.groupers.aws(methods); - methods = helper_1.filters.aws(groupedMethods); - var classData = { - className: sdkClassAst.name.text, - functions: methods, - serviceName: null - }; - return classData; + var methods = []; + var functions = []; + Object.keys(serviceClass).map(function(key, index) { + functions.push(serviceClass[key].split(' ')[1]); + }); + sdkClassAst.members.map(function(method) { + if (method.name && functions.includes(method.name.text)) { + var name_1; + Object.keys(serviceClass).map(function(key, index) { + if (serviceClass[key].split(' ')[1] === method.name.text) { + name_1 = key; + } + }); + var parameters_1 = []; + method.parameters.map(function(param) { + if (param.name.text !== 'callback') { + var parameter = { + name: param.name.text, + optional: param.questionToken ? true : false, + type: typescript_1.SyntaxKind[param.type.kind], + typeName: null, + }; + if ( + parameter.type === 'TypeReference' && + param.type.typeName + ) { + parameter.typeName = param.type.typeName.right.text; + } + parameters_1.push(parameter); + } + }); + methods.push({ + functionName: name_1.toString(), + SDKFunctionName: method.name.text.toString(), + params: parameters_1, + }); + } + }); + var groupedMethods = helper_1.groupers.aws(methods); + methods = helper_1.filters.aws(groupedMethods); + var classData = { + className: sdkClassAst.name.text, + functions: methods, + serviceName: null, + }; + return classData; } exports.extractSDKData = extractSDKData; function generateAWSClass(serviceClass, serviceName) { - var _this = this; - var sdkFile = serviceClass[Object.keys(serviceClass)[0]].split(" ")[0]; - parser_1.getAST(sdkFile).then(function (result) { return __awaiter(_this, void 0, void 0, function () { - var sdkClassAst, classData, output, filePath, dir, e_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - sdkClassAst = result; - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - classData = extractSDKData(sdkClassAst, serviceClass); - classData.serviceName = serviceName; - return [4 /*yield*/, transformer_1.transform(dummyAst, classData)]; - case 2: - output = _a.sent(); - filePath = void 0; - dir = helper_1.getDir(serviceName); - if (!fs.existsSync(process.cwd() + "/generatedClasses/AWS/" + dir)) { - fs.mkdirSync(process.cwd() + "/generatedClasses/AWS/" + dir); - } - if (/^[A-Z]*$/.test(serviceName)) { - filePath = - process.cwd() + - "/generatedClasses/AWS/" + - dir + - "/aws-" + - serviceName + - ".js"; - } - else { - filePath = - process.cwd() + - "/generatedClasses/AWS/" + - dir + - "/aws-" + - serviceName.charAt(0).toLowerCase() + - serviceName.slice(1) + - ".js"; - } - helper_1.printFile(filePath, output); - return [3 /*break*/, 4]; - case 3: - e_1 = _a.sent(); - console.error(e_1); - return [3 /*break*/, 4]; - case 4: return [2 /*return*/]; - } - }); - }); }); + var _this = this; + var sdkFile = serviceClass[Object.keys(serviceClass)[0]].split(' ')[0]; + parser_1.getAST(sdkFile).then(function(result) { + return __awaiter(_this, void 0, void 0, function() { + var sdkClassAst, classData, output, filePath, dir, e_1; + return __generator(this, function(_a) { + switch (_a.label) { + case 0: + sdkClassAst = result; + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + classData = extractSDKData(sdkClassAst, serviceClass); + classData.serviceName = serviceName; + return [ + 4 /*yield*/, + transformer_1.transform(dummyAst, classData), + ]; + case 2: + output = _a.sent(); + filePath = void 0; + dir = helper_1.getDir(serviceName); + if ( + !fs.existsSync( + process.cwd() + '/generatedClasses/AWS/' + dir + ) + ) { + fs.mkdirSync( + process.cwd() + '/generatedClasses/AWS/' + dir + ); + } + if (/^[A-Z]*$/.test(serviceName)) { + filePath = + process.cwd() + + '/generatedClasses/AWS/' + + dir + + '/aws-' + + serviceName + + '.js'; + } else { + filePath = + process.cwd() + + '/generatedClasses/AWS/' + + dir + + '/aws-' + + serviceName.charAt(0).toLowerCase() + + serviceName.slice(1) + + '.js'; + } + helper_1.printFile(filePath, output); + return [3 /*break*/, 4]; + case 3: + e_1 = _a.sent(); + console.error(e_1); + return [3 /*break*/, 4]; + case 4: + return [2 /*return*/]; + } + }); + }); + }); } exports.generateAWSClass = generateAWSClass; diff --git a/generator/generators/azure/generator.js b/generator/generators/azure/generator.js index e04def19..9fecc505 100644 --- a/generator/generators/azure/generator.js +++ b/generator/generators/azure/generator.js @@ -1,178 +1,323 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; +'use strict'; +var __awaiter = + (this && this.__awaiter) || + function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator['throw'](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done + ? resolve(result.value) + : adopt(result.value).then(fulfilled, rejected); + } + step( + (generator = generator.apply(thisArg, _arguments || [])).next() + ); + }); + }; +var __generator = + (this && this.__generator) || + function(thisArg, body) { + var _ = { + label: 0, + sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [], + }, + f, + y, + t, + g; + return ( + (g = { next: verb(0), throw: verb(1), return: verb(2) }), + typeof Symbol === 'function' && + (g[Symbol.iterator] = function() { + return this; + }), + g + ); + function verb(n) { + return function(v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError('Generator is already executing.'); + while (_) + try { + if ( + ((f = 1), + y && + (t = + op[0] & 2 + ? y['return'] + : op[0] + ? y['throw'] || + ((t = y['return']) && t.call(y), 0) + : y.next) && + !(t = t.call(y, op[1])).done) + ) + return t; + if (((y = 0), t)) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if ( + !((t = _.trys), + (t = t.length > 0 && t[t.length - 1])) && + (op[0] === 6 || op[0] === 2) + ) { + _ = 0; + continue; + } + if ( + op[0] === 3 && + (!t || (op[1] > t[0] && op[1] < t[3])) + ) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } + }; exports.__esModule = true; exports.generateAzureClass = exports.extractSDKData = void 0; -var fs = require("fs"); -var typescript_1 = require("typescript"); -var parser_1 = require("../../parsers/azure/parser"); -var transformer_1 = require("../../transformers/azure/transformer"); -var helper_1 = require("../lib/helper"); -var dummyFile = process.cwd() + "/dummyClasses/azure.js"; -var dummyAst = typescript_1.createSourceFile(dummyFile, fs.readFileSync(dummyFile).toString(), typescript_1.ScriptTarget.Latest, true); +var fs = require('fs'); +var typescript_1 = require('typescript'); +var parser_1 = require('../../parsers/azure/parser'); +var transformer_1 = require('../../transformers/azure/transformer'); +var helper_1 = require('../lib/helper'); +var dummyFile = process.cwd() + '/dummyClasses/azure.js'; +var dummyAst = typescript_1.createSourceFile( + dummyFile, + fs.readFileSync(dummyFile).toString(), + typescript_1.ScriptTarget.Latest, + true +); function extractSDKData(sdkFiles, methods) { - var specifiedMethods = JSON.parse(JSON.stringify(methods)); - sdkFiles.map(function (sdkFile) { - sdkFile.ast.members.map(function (member) { - if (typescript_1.SyntaxKind[member.kind] === "Constructor") { - member.parameters.map(function (param) { - var tempStr = param.type.typeName.text.split(/(?=[A-Z])/); - tempStr.pop(); - sdkFile.client = tempStr.join(""); - }); - } - if (typescript_1.SyntaxKind[member.kind] === "MethodDeclaration" && - sdkFile.sdkFunctionNames.includes(member.name.text)) { - var method = methods.find(function (methd) { - return methd.SDKFunctionName === member.name.text && - methd.fileName === sdkFile.fileName; - }); - var parameters = member.parameters.map(function (param) { - return { - name: param.name.text, - optional: param.questionToken ? true : false, - type: typescript_1.SyntaxKind[param.type.kind] - }; - }); - var returnType = typescript_1.SyntaxKind[member.type.kind]; - if (!method.returnType) { - method.params = parameters; - method.returnType = returnType; - method.client = sdkFile.client; - } - else { - var clone = JSON.parse(JSON.stringify(method)); - clone.params = parameters; - clone.returnType = returnType; - clone.client = sdkFile.client; - methods.push(clone); - } - } - }); - }); - if (JSON.stringify(methods) === JSON.stringify(specifiedMethods)) { - throw new Error("Data extraction unsuccessful"); - } - var groupedMethods = helper_1.groupers.azure(methods); - methods = helper_1.filters.azure(groupedMethods); - var classData = { - functions: methods - }; - return classData; + var specifiedMethods = JSON.parse(JSON.stringify(methods)); + sdkFiles.map(function(sdkFile) { + sdkFile.ast.members.map(function(member) { + if (typescript_1.SyntaxKind[member.kind] === 'Constructor') { + member.parameters.map(function(param) { + var tempStr = param.type.typeName.text.split(/(?=[A-Z])/); + tempStr.pop(); + sdkFile.client = tempStr.join(''); + }); + } + if ( + typescript_1.SyntaxKind[member.kind] === 'MethodDeclaration' && + sdkFile.sdkFunctionNames.includes(member.name.text) + ) { + var method = methods.find(function(methd) { + return ( + methd.SDKFunctionName === member.name.text && + methd.fileName === sdkFile.fileName + ); + }); + var parameters = member.parameters.map(function(param) { + return { + name: param.name.text, + optional: param.questionToken ? true : false, + type: typescript_1.SyntaxKind[param.type.kind], + }; + }); + var returnType = typescript_1.SyntaxKind[member.type.kind]; + if (!method.returnType) { + method.params = parameters; + method.returnType = returnType; + method.client = sdkFile.client; + } else { + var clone = JSON.parse(JSON.stringify(method)); + clone.params = parameters; + clone.returnType = returnType; + clone.client = sdkFile.client; + methods.push(clone); + } + } + }); + }); + if (JSON.stringify(methods) === JSON.stringify(specifiedMethods)) { + throw new Error('Data extraction unsuccessful'); + } + var groupedMethods = helper_1.groupers.azure(methods); + methods = helper_1.filters.azure(groupedMethods); + var classData = { + functions: methods, + }; + return classData; } exports.extractSDKData = extractSDKData; function generateAzureClass(serviceClass, serviceName) { - return __awaiter(this, void 0, void 0, function () { - var methods, files, sdkFiles, classData, output, filePath, dir; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - methods = []; - Object.keys(serviceClass).map(function (key, index) { - methods.push({ - pkgName: serviceClass[key].split(" ")[0], - fileName: serviceClass[key].split(" ")[1], - functionName: key, - SDKFunctionName: serviceClass[key].split(" ")[2], - params: [], - returnType: null, - client: null - }); - }); - files = Array.from(new Set(methods.map(function (method) { return method.fileName; }))); - sdkFiles = files.map(function (file) { - return { - fileName: file, - pkgName: methods[0].pkgName, - ast: null, - client: null, - sdkFunctionNames: methods - .filter(function (method) { return method.fileName === file; }) - .map(function (method) { return method.SDKFunctionName; }) - }; - }); - return [4 /*yield*/, Promise.all(sdkFiles.map(function (file) { return __awaiter(_this, void 0, void 0, function () { - var _a; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = file; - return [4 /*yield*/, parser_1.getAST(file)]; - case 1: - _a.ast = _b.sent(); - return [2 /*return*/]; - } - }); - }); }))]; - case 1: - _a.sent(); - classData = extractSDKData(sdkFiles, methods); - classData.serviceName = serviceName; - return [4 /*yield*/, transformer_1.transform(dummyAst, classData)]; - case 2: - output = _a.sent(); - dir = helper_1.getDir(serviceName); - if (!fs.existsSync(process.cwd() + "/generatedClasses/Azure/" + dir)) { - fs.mkdirSync(process.cwd() + "/generatedClasses/Azure/" + dir); - } - if (/^[A-Z]*$/.test(serviceName)) { - filePath = - process.cwd() + - "/generatedClasses/Azure/" + - dir + - "/azure-" + - serviceName + - ".js"; - } - else { - filePath = - process.cwd() + - "/generatedClasses/Azure/" + - dir + - "/azure-" + - serviceName.charAt(0).toLowerCase() + - serviceName.slice(1) + - ".js"; - } - helper_1.printFile(filePath, output); - return [2 /*return*/]; - } - }); - }); + return __awaiter(this, void 0, void 0, function() { + var methods, files, sdkFiles, classData, output, filePath, dir; + var _this = this; + return __generator(this, function(_a) { + switch (_a.label) { + case 0: + methods = []; + Object.keys(serviceClass).map(function(key, index) { + methods.push({ + pkgName: serviceClass[key].split(' ')[0], + fileName: serviceClass[key].split(' ')[1], + functionName: key, + SDKFunctionName: serviceClass[key].split(' ')[2], + params: [], + returnType: null, + client: null, + }); + }); + files = Array.from( + new Set( + methods.map(function(method) { + return method.fileName; + }) + ) + ); + sdkFiles = files.map(function(file) { + return { + fileName: file, + pkgName: methods[0].pkgName, + ast: null, + client: null, + sdkFunctionNames: methods + .filter(function(method) { + return method.fileName === file; + }) + .map(function(method) { + return method.SDKFunctionName; + }), + }; + }); + return [ + 4 /*yield*/, + Promise.all( + sdkFiles.map(function(file) { + return __awaiter( + _this, + void 0, + void 0, + function() { + var _a; + return __generator(this, function(_b) { + switch (_b.label) { + case 0: + _a = file; + return [ + 4 /*yield*/, + parser_1.getAST(file), + ]; + case 1: + _a.ast = _b.sent(); + return [2 /*return*/]; + } + }); + } + ); + }) + ), + ]; + case 1: + _a.sent(); + classData = extractSDKData(sdkFiles, methods); + classData.serviceName = serviceName; + return [ + 4 /*yield*/, + transformer_1.transform(dummyAst, classData), + ]; + case 2: + output = _a.sent(); + dir = helper_1.getDir(serviceName); + if ( + !fs.existsSync( + process.cwd() + '/generatedClasses/Azure/' + dir + ) + ) { + fs.mkdirSync( + process.cwd() + '/generatedClasses/Azure/' + dir + ); + } + if (/^[A-Z]*$/.test(serviceName)) { + filePath = + process.cwd() + + '/generatedClasses/Azure/' + + dir + + '/azure-' + + serviceName + + '.js'; + } else { + filePath = + process.cwd() + + '/generatedClasses/Azure/' + + dir + + '/azure-' + + serviceName.charAt(0).toLowerCase() + + serviceName.slice(1) + + '.js'; + } + helper_1.printFile(filePath, output); + return [2 /*return*/]; + } + }); + }); } exports.generateAzureClass = generateAzureClass; diff --git a/generator/generators/azure/generator.ts b/generator/generators/azure/generator.ts index 2d22cf7f..38839d33 100644 --- a/generator/generators/azure/generator.ts +++ b/generator/generators/azure/generator.ts @@ -1,152 +1,152 @@ -import * as fs from "fs"; -import { createSourceFile, ScriptTarget,SyntaxKind } from "typescript"; +import * as fs from 'fs'; +import { createSourceFile, ScriptTarget, SyntaxKind } from 'typescript'; -import { getAST } from "../../parsers/azure/parser"; -import { transform } from "../../transformers/azure/transformer"; -import { filters, getDir,groupers, printFile } from "../lib/helper"; +import { getAST } from '../../parsers/azure/parser'; +import { transform } from '../../transformers/azure/transformer'; +import { filters, getDir, groupers, printFile } from '../lib/helper'; interface FunctionData { - pkgName: string; - fileName: string; - functionName: string; - SDKFunctionName: string; - params: param[]; - returnType: string; - client: string; + pkgName: string; + fileName: string; + functionName: string; + SDKFunctionName: string; + params: param[]; + returnType: string; + client: string; } interface param { - name: string; - type: string; + name: string; + type: string; } -const dummyFile = process.cwd() + "/dummyClasses/azure.js"; +const dummyFile = process.cwd() + '/dummyClasses/azure.js'; const dummyAst = createSourceFile( - dummyFile, - fs.readFileSync(dummyFile).toString(), - ScriptTarget.Latest, - true + dummyFile, + fs.readFileSync(dummyFile).toString(), + ScriptTarget.Latest, + true ); export function extractSDKData(sdkFiles, methods) { - const specifiedMethods = JSON.parse(JSON.stringify(methods)); - sdkFiles.map(sdkFile => { - sdkFile.ast.members.map(member => { - if (SyntaxKind[member.kind] === "Constructor") { - member.parameters.map(param => { - const tempStr = param.type.typeName.text.split(/(?=[A-Z])/); - tempStr.pop(); - sdkFile.client = tempStr.join(""); - }); - } - - if ( - SyntaxKind[member.kind] === "MethodDeclaration" && - sdkFile.sdkFunctionNames.includes(member.name.text) - ) { - const method = methods.find( - methd => - methd.SDKFunctionName === member.name.text && - methd.fileName === sdkFile.fileName - ); - const parameters = member.parameters.map(param => { - return { - name: param.name.text, - optional: param.questionToken ? true : false, - type: SyntaxKind[param.type.kind] - }; - }); - - const returnType = SyntaxKind[member.type.kind]; - if (!method.returnType) { - method.params = parameters; - method.returnType = returnType; - method.client = sdkFile.client; - } else { - const clone = JSON.parse(JSON.stringify(method)); - clone.params = parameters; - clone.returnType = returnType; - clone.client = sdkFile.client; - methods.push(clone); - } - } - }); - }); - - if (JSON.stringify(methods) === JSON.stringify(specifiedMethods)) { - throw new Error("Data extraction unsuccessful"); - } - - const groupedMethods = groupers.azure(methods); - methods = filters.azure(groupedMethods); - - const classData = { - functions: methods - }; - - return classData; + const specifiedMethods = JSON.parse(JSON.stringify(methods)); + sdkFiles.map(sdkFile => { + sdkFile.ast.members.map(member => { + if (SyntaxKind[member.kind] === 'Constructor') { + member.parameters.map(param => { + const tempStr = param.type.typeName.text.split(/(?=[A-Z])/); + tempStr.pop(); + sdkFile.client = tempStr.join(''); + }); + } + + if ( + SyntaxKind[member.kind] === 'MethodDeclaration' && + sdkFile.sdkFunctionNames.includes(member.name.text) + ) { + const method = methods.find( + methd => + methd.SDKFunctionName === member.name.text && + methd.fileName === sdkFile.fileName + ); + const parameters = member.parameters.map(param => { + return { + name: param.name.text, + optional: param.questionToken ? true : false, + type: SyntaxKind[param.type.kind], + }; + }); + + const returnType = SyntaxKind[member.type.kind]; + if (!method.returnType) { + method.params = parameters; + method.returnType = returnType; + method.client = sdkFile.client; + } else { + const clone = JSON.parse(JSON.stringify(method)); + clone.params = parameters; + clone.returnType = returnType; + clone.client = sdkFile.client; + methods.push(clone); + } + } + }); + }); + + if (JSON.stringify(methods) === JSON.stringify(specifiedMethods)) { + throw new Error('Data extraction unsuccessful'); + } + + const groupedMethods = groupers.azure(methods); + methods = filters.azure(groupedMethods); + + const classData = { + functions: methods, + }; + + return classData; } export async function generateAzureClass(serviceClass, serviceName) { - const methods: FunctionData[] = []; - - Object.keys(serviceClass).map((key, index) => { - methods.push({ - pkgName: serviceClass[key].split(" ")[0], - fileName: serviceClass[key].split(" ")[1], - functionName: key, - SDKFunctionName: serviceClass[key].split(" ")[2], - params: [], - returnType: null, - client: null - }); - }); - - const files = Array.from(new Set(methods.map(method => method.fileName))); - - const sdkFiles = files.map(file => { - return { - fileName: file, - pkgName: methods[0].pkgName, - ast: null, - client: null, - sdkFunctionNames: methods - .filter(method => method.fileName === file) - .map(method => method.SDKFunctionName) - }; - }); - - await Promise.all( - sdkFiles.map(async file => { - file.ast = await getAST(file); - }) - ); - - const classData: any = extractSDKData(sdkFiles, methods); - classData.serviceName = serviceName; - const output = await transform(dummyAst, classData); - let filePath; - const dir = getDir(serviceName); - if (!fs.existsSync(process.cwd() + "/generatedClasses/Azure/" + dir)) { - fs.mkdirSync(process.cwd() + "/generatedClasses/Azure/" + dir); - } - if (/^[A-Z]*$/.test(serviceName)) { - filePath = - process.cwd() + - "/generatedClasses/Azure/" + - dir + - "/azure-" + - serviceName + - ".js"; - } else { - filePath = - process.cwd() + - "/generatedClasses/Azure/" + - dir + - "/azure-" + - serviceName.charAt(0).toLowerCase() + - serviceName.slice(1) + - ".js"; - } - printFile(filePath, output); + const methods: FunctionData[] = []; + + Object.keys(serviceClass).map((key, index) => { + methods.push({ + pkgName: serviceClass[key].split(' ')[0], + fileName: serviceClass[key].split(' ')[1], + functionName: key, + SDKFunctionName: serviceClass[key].split(' ')[2], + params: [], + returnType: null, + client: null, + }); + }); + + const files = Array.from(new Set(methods.map(method => method.fileName))); + + const sdkFiles = files.map(file => { + return { + fileName: file, + pkgName: methods[0].pkgName, + ast: null, + client: null, + sdkFunctionNames: methods + .filter(method => method.fileName === file) + .map(method => method.SDKFunctionName), + }; + }); + + await Promise.all( + sdkFiles.map(async file => { + file.ast = await getAST(file); + }) + ); + + const classData: any = extractSDKData(sdkFiles, methods); + classData.serviceName = serviceName; + const output = await transform(dummyAst, classData); + let filePath; + const dir = getDir(serviceName); + if (!fs.existsSync(process.cwd() + '/generatedClasses/Azure/' + dir)) { + fs.mkdirSync(process.cwd() + '/generatedClasses/Azure/' + dir); + } + if (/^[A-Z]*$/.test(serviceName)) { + filePath = + process.cwd() + + '/generatedClasses/Azure/' + + dir + + '/azure-' + + serviceName + + '.js'; + } else { + filePath = + process.cwd() + + '/generatedClasses/Azure/' + + dir + + '/azure-' + + serviceName.charAt(0).toLowerCase() + + serviceName.slice(1) + + '.js'; + } + printFile(filePath, output); } diff --git a/generator/generators/do/generator.js b/generator/generators/do/generator.js index 9b59d7c2..f6c11156 100644 --- a/generator/generators/do/generator.js +++ b/generator/generators/do/generator.js @@ -1,143 +1,266 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; +'use strict'; +var __awaiter = + (this && this.__awaiter) || + function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator['throw'](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done + ? resolve(result.value) + : adopt(result.value).then(fulfilled, rejected); + } + step( + (generator = generator.apply(thisArg, _arguments || [])).next() + ); + }); + }; +var __generator = + (this && this.__generator) || + function(thisArg, body) { + var _ = { + label: 0, + sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [], + }, + f, + y, + t, + g; + return ( + (g = { next: verb(0), throw: verb(1), return: verb(2) }), + typeof Symbol === 'function' && + (g[Symbol.iterator] = function() { + return this; + }), + g + ); + function verb(n) { + return function(v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError('Generator is already executing.'); + while (_) + try { + if ( + ((f = 1), + y && + (t = + op[0] & 2 + ? y['return'] + : op[0] + ? y['throw'] || + ((t = y['return']) && t.call(y), 0) + : y.next) && + !(t = t.call(y, op[1])).done) + ) + return t; + if (((y = 0), t)) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if ( + !((t = _.trys), + (t = t.length > 0 && t[t.length - 1])) && + (op[0] === 6 || op[0] === 2) + ) { + _ = 0; + continue; + } + if ( + op[0] === 3 && + (!t || (op[1] > t[0] && op[1] < t[3])) + ) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } + }; exports.__esModule = true; exports.generateDOClass = exports.extractSDKData = void 0; -var fs = require("fs"); -var typescript_1 = require("typescript"); -var parser_1 = require("../../parsers/do/parser"); -var transformer_1 = require("../../transformers/do/transformer"); -var helper_1 = require("../lib/helper"); -var dummyFile = process.cwd() + "/dummyClasses/do.js"; -var dummyAst = typescript_1.createSourceFile(dummyFile, fs.readFileSync(dummyFile).toString(), typescript_1.ScriptTarget.Latest, true); +var fs = require('fs'); +var typescript_1 = require('typescript'); +var parser_1 = require('../../parsers/do/parser'); +var transformer_1 = require('../../transformers/do/transformer'); +var helper_1 = require('../lib/helper'); +var dummyFile = process.cwd() + '/dummyClasses/do.js'; +var dummyAst = typescript_1.createSourceFile( + dummyFile, + fs.readFileSync(dummyFile).toString(), + typescript_1.ScriptTarget.Latest, + true +); function extractSDKData(sdkClassAst, serviceClass) { - var methods = []; - var functions = []; - Object.keys(serviceClass).map(function (key, index) { - functions.push(serviceClass[key].split(" ")[1]); - }); - sdkClassAst.members.map(function (method) { - if (method.name && functions.includes(method.name.text)) { - var name_1; - Object.keys(serviceClass).map(function (key, index) { - if (serviceClass[key].split(" ")[1] === method.name.text) { - name_1 = key; - } - }); - var parameters_1 = []; - method.parameters.map(function (param) { - if (param.name.text !== "callback") { - var parameter = { - name: param.name.text, - optional: param.questionToken ? true : false, - type: typescript_1.SyntaxKind[param.type.kind], - typeName: null - }; - if (parameter.type === "TypeReference" && param.type.typeName) { - parameter.typeName = param.type.typeName.text; - } - parameters_1.push(parameter); - } - }); - methods.push({ - functionName: name_1.toString(), - SDKFunctionName: method.name.text.toString(), - params: parameters_1 - }); - } - }); - var classData = { - className: sdkClassAst.name.text, - functions: methods, - serviceName: null - }; - return classData; + var methods = []; + var functions = []; + Object.keys(serviceClass).map(function(key, index) { + functions.push(serviceClass[key].split(' ')[1]); + }); + sdkClassAst.members.map(function(method) { + if (method.name && functions.includes(method.name.text)) { + var name_1; + Object.keys(serviceClass).map(function(key, index) { + if (serviceClass[key].split(' ')[1] === method.name.text) { + name_1 = key; + } + }); + var parameters_1 = []; + method.parameters.map(function(param) { + if (param.name.text !== 'callback') { + var parameter = { + name: param.name.text, + optional: param.questionToken ? true : false, + type: typescript_1.SyntaxKind[param.type.kind], + typeName: null, + }; + if ( + parameter.type === 'TypeReference' && + param.type.typeName + ) { + parameter.typeName = param.type.typeName.text; + } + parameters_1.push(parameter); + } + }); + methods.push({ + functionName: name_1.toString(), + SDKFunctionName: method.name.text.toString(), + params: parameters_1, + }); + } + }); + var classData = { + className: sdkClassAst.name.text, + functions: methods, + serviceName: null, + }; + return classData; } exports.extractSDKData = extractSDKData; function generateDOClass(serviceClass, serviceName) { - var _this = this; - var sdkFile = serviceClass[Object.keys(serviceClass)[0]].split(" ")[0]; - parser_1.getAST(sdkFile).then(function (result) { return __awaiter(_this, void 0, void 0, function () { - var sdkClassAst, classData, output, filePath, dir, e_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - sdkClassAst = result; - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - classData = extractSDKData(sdkClassAst, serviceClass); - classData.serviceName = serviceName; - return [4 /*yield*/, transformer_1.transform(dummyAst, classData)]; - case 2: - output = _a.sent(); - filePath = void 0; - dir = helper_1.getDir(serviceName); - if (!fs.existsSync(process.cwd() + "/generatedClasses/DO/" + dir)) { - fs.mkdirSync(process.cwd() + "/generatedClasses/DO/" + dir); - } - if (/^[A-Z]*$/.test(serviceName)) { - filePath = - process.cwd() + - "/generatedClasses/DO/" + - dir + - "/do-" + - serviceName + - ".js"; - } - else { - filePath = - process.cwd() + - "/generatedClasses/DO/" + - dir + - "/do-" + - serviceName.charAt(0).toLowerCase() + - serviceName.slice(1) + - ".js"; - } - helper_1.printFile(filePath, output); - return [3 /*break*/, 4]; - case 3: - e_1 = _a.sent(); - console.error(e_1); - return [3 /*break*/, 4]; - case 4: return [2 /*return*/]; - } - }); - }); }); + var _this = this; + var sdkFile = serviceClass[Object.keys(serviceClass)[0]].split(' ')[0]; + parser_1.getAST(sdkFile).then(function(result) { + return __awaiter(_this, void 0, void 0, function() { + var sdkClassAst, classData, output, filePath, dir, e_1; + return __generator(this, function(_a) { + switch (_a.label) { + case 0: + sdkClassAst = result; + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + classData = extractSDKData(sdkClassAst, serviceClass); + classData.serviceName = serviceName; + return [ + 4 /*yield*/, + transformer_1.transform(dummyAst, classData), + ]; + case 2: + output = _a.sent(); + filePath = void 0; + dir = helper_1.getDir(serviceName); + if ( + !fs.existsSync( + process.cwd() + '/generatedClasses/DO/' + dir + ) + ) { + fs.mkdirSync( + process.cwd() + '/generatedClasses/DO/' + dir + ); + } + if (/^[A-Z]*$/.test(serviceName)) { + filePath = + process.cwd() + + '/generatedClasses/DO/' + + dir + + '/do-' + + serviceName + + '.js'; + } else { + filePath = + process.cwd() + + '/generatedClasses/DO/' + + dir + + '/do-' + + serviceName.charAt(0).toLowerCase() + + serviceName.slice(1) + + '.js'; + } + helper_1.printFile(filePath, output); + return [3 /*break*/, 4]; + case 3: + e_1 = _a.sent(); + console.error(e_1); + return [3 /*break*/, 4]; + case 4: + return [2 /*return*/]; + } + }); + }); + }); } exports.generateDOClass = generateDOClass; diff --git a/generator/generators/do/generator.ts b/generator/generators/do/generator.ts index 09b6d1ca..7a97277d 100644 --- a/generator/generators/do/generator.ts +++ b/generator/generators/do/generator.ts @@ -1,123 +1,129 @@ -import * as fs from "fs"; -import { createSourceFile, ScriptTarget, SyntaxKind } from "typescript"; +import * as fs from 'fs'; +import { createSourceFile, ScriptTarget, SyntaxKind } from 'typescript'; -import { getAST } from "../../parsers/do/parser"; -import { transform } from "../../transformers/do/transformer"; -import { getDir,printFile } from "../lib/helper"; +import { getAST } from '../../parsers/do/parser'; +import { transform } from '../../transformers/do/transformer'; +import { getDir, printFile } from '../lib/helper'; interface FunctionData { - functionName: string; - SDKFunctionName: string; - params: param[]; + functionName: string; + SDKFunctionName: string; + params: param[]; } interface param { - name: string; - type: string; - typeName: string; + name: string; + type: string; + typeName: string; } interface ClassData { - className: string; - functions: FunctionData[]; - serviceName: string; + className: string; + functions: FunctionData[]; + serviceName: string; } -const dummyFile = process.cwd() + "/dummyClasses/do.js"; +const dummyFile = process.cwd() + '/dummyClasses/do.js'; const dummyAst = createSourceFile( - dummyFile, - fs.readFileSync(dummyFile).toString(), - ScriptTarget.Latest, - true + dummyFile, + fs.readFileSync(dummyFile).toString(), + ScriptTarget.Latest, + true ); export function extractSDKData(sdkClassAst, serviceClass) { - const methods: FunctionData[] = []; - const functions = []; - - Object.keys(serviceClass).map((key, index) => { - functions.push(serviceClass[key].split(" ")[1]); - }); - - sdkClassAst.members.map(method => { - if (method.name && functions.includes(method.name.text)) { - let name; - Object.keys(serviceClass).map((key, index) => { - if (serviceClass[key].split(" ")[1] === method.name.text) { - name = key; - } - }); - - const parameters = []; - method.parameters.map(param => { - if (param.name.text !== "callback") { - const parameter = { - name: param.name.text, - optional: param.questionToken ? true : false, - type: SyntaxKind[param.type.kind], - typeName: null - }; - - if (parameter.type === "TypeReference" && param.type.typeName) { - parameter.typeName = param.type.typeName.text; - } - - parameters.push(parameter); - } - }); - - methods.push({ - functionName: name.toString(), - SDKFunctionName: method.name.text.toString(), - params: parameters - }); - } - }); - - const classData: ClassData = { - className: sdkClassAst.name.text, - functions: methods, - serviceName: null - }; - - return classData; + const methods: FunctionData[] = []; + const functions = []; + + Object.keys(serviceClass).map((key, index) => { + functions.push(serviceClass[key].split(' ')[1]); + }); + + sdkClassAst.members.map(method => { + if (method.name && functions.includes(method.name.text)) { + let name; + Object.keys(serviceClass).map((key, index) => { + if (serviceClass[key].split(' ')[1] === method.name.text) { + name = key; + } + }); + + const parameters = []; + method.parameters.map(param => { + if (param.name.text !== 'callback') { + const parameter = { + name: param.name.text, + optional: param.questionToken ? true : false, + type: SyntaxKind[param.type.kind], + typeName: null, + }; + + if ( + parameter.type === 'TypeReference' && + param.type.typeName + ) { + parameter.typeName = param.type.typeName.text; + } + + parameters.push(parameter); + } + }); + + methods.push({ + functionName: name.toString(), + SDKFunctionName: method.name.text.toString(), + params: parameters, + }); + } + }); + + const classData: ClassData = { + className: sdkClassAst.name.text, + functions: methods, + serviceName: null, + }; + + return classData; } export function generateDOClass(serviceClass, serviceName) { - const sdkFile = serviceClass[Object.keys(serviceClass)[0]].split(" ")[0]; - getAST(sdkFile).then(async result => { - const sdkClassAst = result; - try { - const classData: ClassData = extractSDKData(sdkClassAst, serviceClass); - classData.serviceName = serviceName; - const output = await transform(dummyAst, classData); - let filePath; - const dir = getDir(serviceName); - if (!fs.existsSync(process.cwd() + "/generatedClasses/DO/" + dir)) { - fs.mkdirSync(process.cwd() + "/generatedClasses/DO/" + dir); - } - if (/^[A-Z]*$/.test(serviceName)) { - filePath = - process.cwd() + - "/generatedClasses/DO/" + - dir + - "/do-" + - serviceName + - ".js"; - } else { - filePath = - process.cwd() + - "/generatedClasses/DO/" + - dir + - "/do-" + - serviceName.charAt(0).toLowerCase() + - serviceName.slice(1) + - ".js"; - } - printFile(filePath, output); - } catch (e) { - console.error(e); - } - }); + const sdkFile = serviceClass[Object.keys(serviceClass)[0]].split(' ')[0]; + getAST(sdkFile).then(async result => { + const sdkClassAst = result; + try { + const classData: ClassData = extractSDKData( + sdkClassAst, + serviceClass + ); + classData.serviceName = serviceName; + const output = await transform(dummyAst, classData); + let filePath; + const dir = getDir(serviceName); + if (!fs.existsSync(process.cwd() + '/generatedClasses/DO/' + dir)) { + fs.mkdirSync(process.cwd() + '/generatedClasses/DO/' + dir); + } + if (/^[A-Z]*$/.test(serviceName)) { + filePath = + process.cwd() + + '/generatedClasses/DO/' + + dir + + '/do-' + + serviceName + + '.js'; + } else { + filePath = + process.cwd() + + '/generatedClasses/DO/' + + dir + + '/do-' + + serviceName.charAt(0).toLowerCase() + + serviceName.slice(1) + + '.js'; + } + printFile(filePath, output); + } catch (e) { + console.error(e); + } + }); } diff --git a/generator/generators/googleCloud/generator.js b/generator/generators/googleCloud/generator.js index a06ac192..ea5d502a 100644 --- a/generator/generators/googleCloud/generator.js +++ b/generator/generators/googleCloud/generator.js @@ -1,410 +1,701 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; +'use strict'; +var __awaiter = + (this && this.__awaiter) || + function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator['throw'](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done + ? resolve(result.value) + : adopt(result.value).then(fulfilled, rejected); + } + step( + (generator = generator.apply(thisArg, _arguments || [])).next() + ); + }); + }; +var __generator = + (this && this.__generator) || + function(thisArg, body) { + var _ = { + label: 0, + sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [], + }, + f, + y, + t, + g; + return ( + (g = { next: verb(0), throw: verb(1), return: verb(2) }), + typeof Symbol === 'function' && + (g[Symbol.iterator] = function() { + return this; + }), + g + ); + function verb(n) { + return function(v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError('Generator is already executing.'); + while (_) + try { + if ( + ((f = 1), + y && + (t = + op[0] & 2 + ? y['return'] + : op[0] + ? y['throw'] || + ((t = y['return']) && t.call(y), 0) + : y.next) && + !(t = t.call(y, op[1])).done) + ) + return t; + if (((y = 0), t)) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if ( + !((t = _.trys), + (t = t.length > 0 && t[t.length - 1])) && + (op[0] === 6 || op[0] === 2) + ) { + _ = 0; + continue; + } + if ( + op[0] === 3 && + (!t || (op[1] > t[0] && op[1] < t[3])) + ) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } + }; exports.__esModule = true; exports.generateGCPClass = exports.extractClientBasedSDKdata = exports.extractClassBasedSDKData = void 0; -var fs = require("fs"); -var path = require("path"); -var typescript_1 = require("typescript"); -var parser_1 = require("../../parsers/googleCloud/parser"); -var classBasedTransformer_1 = require("../../transformers/googleCloud/classBasedTransformer"); -var clientBasedTransformer_1 = require("../../transformers/googleCloud/clientBasedTransformer"); -var helper_1 = require("../lib/helper"); -var dummyFile = process.cwd() + "/dummyClasses/gcp.js"; -var dummyAst = typescript_1.createSourceFile(dummyFile, fs.readFileSync(dummyFile).toString(), typescript_1.ScriptTarget.Latest, true); +var fs = require('fs'); +var path = require('path'); +var typescript_1 = require('typescript'); +var parser_1 = require('../../parsers/googleCloud/parser'); +var classBasedTransformer_1 = require('../../transformers/googleCloud/classBasedTransformer'); +var clientBasedTransformer_1 = require('../../transformers/googleCloud/clientBasedTransformer'); +var helper_1 = require('../lib/helper'); +var dummyFile = process.cwd() + '/dummyClasses/gcp.js'; +var dummyAst = typescript_1.createSourceFile( + dummyFile, + fs.readFileSync(dummyFile).toString(), + typescript_1.ScriptTarget.Latest, + true +); function extractClassBasedSDKData(methods, sdkFiles) { - var _this = this; - var specifiedMethods = JSON.parse(JSON.stringify(methods)); - return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () { - var classes_1, extractedData; - return __generator(this, function (_a) { - try { - classes_1 = []; - sdkFiles.map(function (file) { - file.classes.map(function (classAst) { - var classInfo = { - name: classAst.name.text, - methods: [], - properties: [], - constructor: null - }; - classAst.members.map(function (member) { - if (typescript_1.SyntaxKind[member.kind] === "MethodDeclaration") { - var returnType = typescript_1.SyntaxKind[member.type.kind]; - var parameters = member.parameters.map(function (param) { - return { - name: param.name.text, - optional: param.questionToken ? true : false, - type: typescript_1.SyntaxKind[param.type.kind] - }; - }); - var method_1 = { - pkgName: file.pkgName, - version: null, - fileName: file.fileName, - functionName: null, - SDKFunctionName: member.name.text, - params: parameters, - returnType: returnType, - returnTypeName: null, - client: classAst.name.text // Class name - }; - if (returnType === "TypeReference") { - method_1.returnTypeName = member.type.typeName.text; - } - var meth = methods.find(function (meth) { - return meth.SDKFunctionName === method_1.SDKFunctionName && - meth.fileName === method_1.fileName; - }); - method_1.functionName = meth ? meth.functionName : null; - classInfo.methods.push(method_1); - } - if (typescript_1.SyntaxKind[member.kind] === "Constructor") { - var parameters = member.parameters.map(function (param) { - return { - name: param.name.text, - optional: param.questionToken ? true : false, - type: typescript_1.SyntaxKind[param.type.kind], - typeRefName: param.type.typeName - ? param.type.typeName.text - : null - }; - }); - classInfo.constructor = { - parameters: parameters - }; - } - if (typescript_1.SyntaxKind[member.kind] === "PropertyDeclaration") { - var isPrivateProp = member.modifiers && - member.modifiers.some(function (modifier) { return typescript_1.SyntaxKind[modifier.kind] === "PrivateKeyword"; }); - if (!isPrivateProp) { - var prop = { - name: member.name.text, - type: typescript_1.SyntaxKind[member.type.kind], - typeRefName: member.type.typeName - ? member.type.typeName.text - : null - }; - classInfo.properties.push(prop); - } - } - }); - classes_1.push(classInfo); - }); - }); - methods = []; - classes_1.map(function (classData) { - var filteredMethods = classData.methods.filter(function (meth) { return meth.functionName !== null; }); - filteredMethods.map(function (filMeth) { - filMeth.classConstructorData = classData.constructor; - }); - methods = methods.concat(filteredMethods); - }); - extractedData = { - classes: classes_1, - methods: methods - }; - if (JSON.stringify(methods) === JSON.stringify(specifiedMethods)) { - reject(new Error("Data extraction unsuccessful")); - } - else { - resolve(extractedData); - } - } - catch (error) { - reject(error); - } - return [2 /*return*/]; - }); - }); }); + var _this = this; + var specifiedMethods = JSON.parse(JSON.stringify(methods)); + return new Promise(function(resolve, reject) { + return __awaiter(_this, void 0, void 0, function() { + var classes_1, extractedData; + return __generator(this, function(_a) { + try { + classes_1 = []; + sdkFiles.map(function(file) { + file.classes.map(function(classAst) { + var classInfo = { + name: classAst.name.text, + methods: [], + properties: [], + constructor: null, + }; + classAst.members.map(function(member) { + if ( + typescript_1.SyntaxKind[member.kind] === + 'MethodDeclaration' + ) { + var returnType = + typescript_1.SyntaxKind[ + member.type.kind + ]; + var parameters = member.parameters.map( + function(param) { + return { + name: param.name.text, + optional: param.questionToken + ? true + : false, + type: + typescript_1.SyntaxKind[ + param.type.kind + ], + }; + } + ); + var method_1 = { + pkgName: file.pkgName, + version: null, + fileName: file.fileName, + functionName: null, + SDKFunctionName: member.name.text, + params: parameters, + returnType: returnType, + returnTypeName: null, + client: classAst.name.text, // Class name + }; + if (returnType === 'TypeReference') { + method_1.returnTypeName = + member.type.typeName.text; + } + var meth = methods.find(function(meth) { + return ( + meth.SDKFunctionName === + method_1.SDKFunctionName && + meth.fileName === method_1.fileName + ); + }); + method_1.functionName = meth + ? meth.functionName + : null; + classInfo.methods.push(method_1); + } + if ( + typescript_1.SyntaxKind[member.kind] === + 'Constructor' + ) { + var parameters = member.parameters.map( + function(param) { + return { + name: param.name.text, + optional: param.questionToken + ? true + : false, + type: + typescript_1.SyntaxKind[ + param.type.kind + ], + typeRefName: param.type.typeName + ? param.type.typeName.text + : null, + }; + } + ); + classInfo.constructor = { + parameters: parameters, + }; + } + if ( + typescript_1.SyntaxKind[member.kind] === + 'PropertyDeclaration' + ) { + var isPrivateProp = + member.modifiers && + member.modifiers.some(function( + modifier + ) { + return ( + typescript_1.SyntaxKind[ + modifier.kind + ] === 'PrivateKeyword' + ); + }); + if (!isPrivateProp) { + var prop = { + name: member.name.text, + type: + typescript_1.SyntaxKind[ + member.type.kind + ], + typeRefName: member.type.typeName + ? member.type.typeName.text + : null, + }; + classInfo.properties.push(prop); + } + } + }); + classes_1.push(classInfo); + }); + }); + methods = []; + classes_1.map(function(classData) { + var filteredMethods = classData.methods.filter(function( + meth + ) { + return meth.functionName !== null; + }); + filteredMethods.map(function(filMeth) { + filMeth.classConstructorData = + classData.constructor; + }); + methods = methods.concat(filteredMethods); + }); + extractedData = { + classes: classes_1, + methods: methods, + }; + if ( + JSON.stringify(methods) === + JSON.stringify(specifiedMethods) + ) { + reject(new Error('Data extraction unsuccessful')); + } else { + resolve(extractedData); + } + } catch (error) { + reject(error); + } + return [2 /*return*/]; + }); + }); + }); } exports.extractClassBasedSDKData = extractClassBasedSDKData; function extractClientBasedSDKdata(methods, sdkFiles) { - var _this = this; - var specifiedMethods = JSON.parse(JSON.stringify(methods)); - return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - try { - sdkFiles.map(function (sdkFile) { - sdkFile.client = sdkFile.ast.name.text; - sdkFile.ast.members.map(function (member) { - if (typescript_1.SyntaxKind[member.kind] === "MethodDeclaration" && - sdkFile.sdkFunctionNames.includes(member.name.text)) { - var method = methods.find(function (methd) { return methd.SDKFunctionName === member.name.text; }); - var parameters = member.parameters.map(function (param) { - return { - name: param.name.text, - optional: param.questionToken ? true : false, - type: typescript_1.SyntaxKind[param.type.kind] - }; - }); - var returnType = typescript_1.SyntaxKind[member.type.kind]; - if (returnType === "TypeReference") { - method.returnTypeName = member.type.typeName.text; - } - if (!method.returnType) { - method.params = parameters; - method.returnType = returnType; - method.client = sdkFile.client; - } - else { - var clone = JSON.parse(JSON.stringify(method)); - clone.params = parameters; - clone.returnType = returnType; - clone.client = sdkFile.client; - methods.push(clone); - } - } - }); - }); - if (JSON.stringify(methods) === JSON.stringify(specifiedMethods)) { - reject(new Error("Data extraction unsuccessful")); - } - else { - resolve(methods); - } - } - catch (error) { - reject(error); - } - return [2 /*return*/]; - }); - }); }); + var _this = this; + var specifiedMethods = JSON.parse(JSON.stringify(methods)); + return new Promise(function(resolve, reject) { + return __awaiter(_this, void 0, void 0, function() { + return __generator(this, function(_a) { + try { + sdkFiles.map(function(sdkFile) { + sdkFile.client = sdkFile.ast.name.text; + sdkFile.ast.members.map(function(member) { + if ( + typescript_1.SyntaxKind[member.kind] === + 'MethodDeclaration' && + sdkFile.sdkFunctionNames.includes( + member.name.text + ) + ) { + var method = methods.find(function(methd) { + return ( + methd.SDKFunctionName === + member.name.text + ); + }); + var parameters = member.parameters.map(function( + param + ) { + return { + name: param.name.text, + optional: param.questionToken + ? true + : false, + type: + typescript_1.SyntaxKind[ + param.type.kind + ], + }; + }); + var returnType = + typescript_1.SyntaxKind[member.type.kind]; + if (returnType === 'TypeReference') { + method.returnTypeName = + member.type.typeName.text; + } + if (!method.returnType) { + method.params = parameters; + method.returnType = returnType; + method.client = sdkFile.client; + } else { + var clone = JSON.parse( + JSON.stringify(method) + ); + clone.params = parameters; + clone.returnType = returnType; + clone.client = sdkFile.client; + methods.push(clone); + } + } + }); + }); + if ( + JSON.stringify(methods) === + JSON.stringify(specifiedMethods) + ) { + reject(new Error('Data extraction unsuccessful')); + } else { + resolve(methods); + } + } catch (error) { + reject(error); + } + return [2 /*return*/]; + }); + }); + }); } exports.extractClientBasedSDKdata = extractClientBasedSDKdata; function generateClassBasedCode(methods, data, serviceName) { - return __awaiter(this, void 0, void 0, function () { - var dirPath, files, sdkFiles, extractedData, groupedMethods, output, filePath, dir; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - dirPath = "../../../node_modules/@google-cloud/" + methods[0].pkgName + "/build/src/"; - files = fs.readdirSync(path.join(__dirname, dirPath)); - files = files.filter(function (fileName) { - return fileName.split(".")[1] === "d" && fileName.split(".")[2] === "ts"; - }); - sdkFiles = files.map(function (fileName) { - return { - fileName: fileName, - pkgName: methods[0].pkgName, - classes: null, - sdkFunctionNames: methods - .filter(function (method) { return method.fileName === fileName; }) - .map(function (method) { return method.SDKFunctionName; }) - }; - }); - return [4 /*yield*/, Promise.all(sdkFiles.map(function (file) { return __awaiter(_this, void 0, void 0, function () { - var _a; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = file; - return [4 /*yield*/, parser_1.getAST(file, true)]; - case 1: - _a.classes = _b.sent(); - return [2 /*return*/]; - } - }); - }); }))]; - case 1: - _a.sent(); - return [4 /*yield*/, extractClassBasedSDKData(methods, sdkFiles).then(function (result) { return result; })]; - case 2: - extractedData = _a.sent(); - groupedMethods = helper_1.groupers.gcp(extractedData.methods); - methods = helper_1.filters.gcp(groupedMethods); - data.functions = methods; - data.classData = extractedData.classes; - data.serviceName = serviceName; - return [4 /*yield*/, classBasedTransformer_1.classBasedTransform(dummyAst, data)]; - case 3: - output = _a.sent(); - dir = helper_1.getDir(serviceName); - if (!fs.existsSync(process.cwd() + "/generatedClasses/googleCloud/" + dir)) { - fs.mkdirSync(process.cwd() + "/generatedClasses/googleCloud/" + dir); - } - if (/^[A-Z]*$/.test(serviceName)) { - filePath = - process.cwd() + - "/generatedClasses/googleCloud/" + - dir + - "/gcp-" + - serviceName + - ".js"; - } - else { - filePath = - process.cwd() + - "/generatedClasses/googleCloud/" + - dir + - "/gcp-" + - serviceName.charAt(0).toLowerCase() + - serviceName.slice(1) + - ".js"; - } - helper_1.printFile(filePath, output); - return [2 /*return*/]; - } - }); - }); + return __awaiter(this, void 0, void 0, function() { + var dirPath, + files, + sdkFiles, + extractedData, + groupedMethods, + output, + filePath, + dir; + var _this = this; + return __generator(this, function(_a) { + switch (_a.label) { + case 0: + dirPath = + '../../../node_modules/@google-cloud/' + + methods[0].pkgName + + '/build/src/'; + files = fs.readdirSync(path.join(__dirname, dirPath)); + files = files.filter(function(fileName) { + return ( + fileName.split('.')[1] === 'd' && + fileName.split('.')[2] === 'ts' + ); + }); + sdkFiles = files.map(function(fileName) { + return { + fileName: fileName, + pkgName: methods[0].pkgName, + classes: null, + sdkFunctionNames: methods + .filter(function(method) { + return method.fileName === fileName; + }) + .map(function(method) { + return method.SDKFunctionName; + }), + }; + }); + return [ + 4 /*yield*/, + Promise.all( + sdkFiles.map(function(file) { + return __awaiter( + _this, + void 0, + void 0, + function() { + var _a; + return __generator(this, function(_b) { + switch (_b.label) { + case 0: + _a = file; + return [ + 4 /*yield*/, + parser_1.getAST( + file, + true + ), + ]; + case 1: + _a.classes = _b.sent(); + return [2 /*return*/]; + } + }); + } + ); + }) + ), + ]; + case 1: + _a.sent(); + return [ + 4 /*yield*/, + extractClassBasedSDKData(methods, sdkFiles).then( + function(result) { + return result; + } + ), + ]; + case 2: + extractedData = _a.sent(); + groupedMethods = helper_1.groupers.gcp( + extractedData.methods + ); + methods = helper_1.filters.gcp(groupedMethods); + data.functions = methods; + data.classData = extractedData.classes; + data.serviceName = serviceName; + return [ + 4 /*yield*/, + classBasedTransformer_1.classBasedTransform( + dummyAst, + data + ), + ]; + case 3: + output = _a.sent(); + dir = helper_1.getDir(serviceName); + if ( + !fs.existsSync( + process.cwd() + + '/generatedClasses/googleCloud/' + + dir + ) + ) { + fs.mkdirSync( + process.cwd() + + '/generatedClasses/googleCloud/' + + dir + ); + } + if (/^[A-Z]*$/.test(serviceName)) { + filePath = + process.cwd() + + '/generatedClasses/googleCloud/' + + dir + + '/gcp-' + + serviceName + + '.js'; + } else { + filePath = + process.cwd() + + '/generatedClasses/googleCloud/' + + dir + + '/gcp-' + + serviceName.charAt(0).toLowerCase() + + serviceName.slice(1) + + '.js'; + } + helper_1.printFile(filePath, output); + return [2 /*return*/]; + } + }); + }); } function generateClientBasedCode(methods, serviceName) { - return __awaiter(this, void 0, void 0, function () { - var files, sdkFiles, groupedMethods, classData, output, filePath, dir; - var _this = this; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - files = Array.from(new Set(methods.map(function (method) { return method.fileName + " " + method.version; }))); - sdkFiles = files.map(function (file) { - return { - fileName: file.split(" ")[0], - version: file.split(" ")[1], - pkgName: methods[0].pkgName, - ast: null, - client: null, - sdkFunctionNames: methods - .filter(function (method) { return method.fileName === file.split(" ")[0]; }) - .map(function (method) { return method.SDKFunctionName; }) - }; - }); - return [4 /*yield*/, Promise.all(sdkFiles.map(function (file) { return __awaiter(_this, void 0, void 0, function () { - var _a; - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = file; - return [4 /*yield*/, parser_1.getAST(file)]; - case 1: - _a.ast = _b.sent(); - return [2 /*return*/]; - } - }); - }); }))]; - case 1: - _a.sent(); - return [4 /*yield*/, extractClientBasedSDKdata(methods, sdkFiles).then(function (result) { return result; })]; - case 2: - methods = _a.sent(); - groupedMethods = helper_1.groupers.gcp(methods); - methods = helper_1.filters.gcp(groupedMethods); - classData = { - functions: methods, - serviceName: serviceName - }; - return [4 /*yield*/, clientBasedTransformer_1.clientBasedTransform(dummyAst, classData)]; - case 3: - output = _a.sent(); - dir = helper_1.getDir(serviceName); - if (!fs.existsSync(process.cwd() + "/generatedClasses/googleCloud/" + dir)) { - fs.mkdirSync(process.cwd() + "/generatedClasses/googleCloud/" + dir); - } - if (/^[A-Z]*$/.test(serviceName)) { - filePath = - process.cwd() + - "/generatedClasses/googleCloud/" + - dir + - "/gcp-" + - serviceName + - ".js"; - } - else { - filePath = - process.cwd() + - "/generatedClasses/googleCloud/" + - dir + - "/gcp-" + - serviceName.charAt(0).toLowerCase() + - serviceName.slice(1) + - ".js"; - } - helper_1.printFile(filePath, output); - return [2 /*return*/]; - } - }); - }); + return __awaiter(this, void 0, void 0, function() { + var files, sdkFiles, groupedMethods, classData, output, filePath, dir; + var _this = this; + return __generator(this, function(_a) { + switch (_a.label) { + case 0: + files = Array.from( + new Set( + methods.map(function(method) { + return method.fileName + ' ' + method.version; + }) + ) + ); + sdkFiles = files.map(function(file) { + return { + fileName: file.split(' ')[0], + version: file.split(' ')[1], + pkgName: methods[0].pkgName, + ast: null, + client: null, + sdkFunctionNames: methods + .filter(function(method) { + return ( + method.fileName === file.split(' ')[0] + ); + }) + .map(function(method) { + return method.SDKFunctionName; + }), + }; + }); + return [ + 4 /*yield*/, + Promise.all( + sdkFiles.map(function(file) { + return __awaiter( + _this, + void 0, + void 0, + function() { + var _a; + return __generator(this, function(_b) { + switch (_b.label) { + case 0: + _a = file; + return [ + 4 /*yield*/, + parser_1.getAST(file), + ]; + case 1: + _a.ast = _b.sent(); + return [2 /*return*/]; + } + }); + } + ); + }) + ), + ]; + case 1: + _a.sent(); + return [ + 4 /*yield*/, + extractClientBasedSDKdata(methods, sdkFiles).then( + function(result) { + return result; + } + ), + ]; + case 2: + methods = _a.sent(); + groupedMethods = helper_1.groupers.gcp(methods); + methods = helper_1.filters.gcp(groupedMethods); + classData = { + functions: methods, + serviceName: serviceName, + }; + return [ + 4 /*yield*/, + clientBasedTransformer_1.clientBasedTransform( + dummyAst, + classData + ), + ]; + case 3: + output = _a.sent(); + dir = helper_1.getDir(serviceName); + if ( + !fs.existsSync( + process.cwd() + + '/generatedClasses/googleCloud/' + + dir + ) + ) { + fs.mkdirSync( + process.cwd() + + '/generatedClasses/googleCloud/' + + dir + ); + } + if (/^[A-Z]*$/.test(serviceName)) { + filePath = + process.cwd() + + '/generatedClasses/googleCloud/' + + dir + + '/gcp-' + + serviceName + + '.js'; + } else { + filePath = + process.cwd() + + '/generatedClasses/googleCloud/' + + dir + + '/gcp-' + + serviceName.charAt(0).toLowerCase() + + serviceName.slice(1) + + '.js'; + } + helper_1.printFile(filePath, output); + return [2 /*return*/]; + } + }); + }); } function generateGCPClass(serviceClass, serviceName) { - return __awaiter(this, void 0, void 0, function () { - var methods, data; - return __generator(this, function (_a) { - methods = []; - data = {}; - Object.keys(serviceClass).map(function (key, index) { - if (key === "mainClass") { - data.mainClass = serviceClass[key]; - } - else if (serviceClass[key].split(" ")[1].length === 2 && - serviceClass[key].split(" ")[1].charAt(0) === "v") { - methods.push({ - pkgName: serviceClass[key].split(" ")[0], - version: serviceClass[key].split(" ")[1], - fileName: serviceClass[key].split(" ")[2], - functionName: key, - SDKFunctionName: serviceClass[key].split(" ")[3], - params: [], - returnType: null, - returnTypeName: null, - client: null - }); - } - else { - methods.push({ - pkgName: serviceClass[key].split(" ")[0], - version: null, - fileName: serviceClass[key].split(" ")[1], - functionName: key, - SDKFunctionName: serviceClass[key].split(" ")[2], - params: [], - returnType: null, - returnTypeName: null, - client: null - }); - } - }); - if (methods[0].version) { - generateClientBasedCode(methods, serviceName); - } - else { - generateClassBasedCode(methods, data, serviceName); - } - return [2 /*return*/]; - }); - }); + return __awaiter(this, void 0, void 0, function() { + var methods, data; + return __generator(this, function(_a) { + methods = []; + data = {}; + Object.keys(serviceClass).map(function(key, index) { + if (key === 'mainClass') { + data.mainClass = serviceClass[key]; + } else if ( + serviceClass[key].split(' ')[1].length === 2 && + serviceClass[key].split(' ')[1].charAt(0) === 'v' + ) { + methods.push({ + pkgName: serviceClass[key].split(' ')[0], + version: serviceClass[key].split(' ')[1], + fileName: serviceClass[key].split(' ')[2], + functionName: key, + SDKFunctionName: serviceClass[key].split(' ')[3], + params: [], + returnType: null, + returnTypeName: null, + client: null, + }); + } else { + methods.push({ + pkgName: serviceClass[key].split(' ')[0], + version: null, + fileName: serviceClass[key].split(' ')[1], + functionName: key, + SDKFunctionName: serviceClass[key].split(' ')[2], + params: [], + returnType: null, + returnTypeName: null, + client: null, + }); + } + }); + if (methods[0].version) { + generateClientBasedCode(methods, serviceName); + } else { + generateClassBasedCode(methods, data, serviceName); + } + return [2 /*return*/]; + }); + }); } exports.generateGCPClass = generateGCPClass; diff --git a/generator/generators/googleCloud/generator.ts b/generator/generators/googleCloud/generator.ts index df7de192..c3996431 100644 --- a/generator/generators/googleCloud/generator.ts +++ b/generator/generators/googleCloud/generator.ts @@ -1,388 +1,405 @@ -import * as fs from "fs"; -import * as path from "path"; -import { createSourceFile, ScriptTarget,SyntaxKind } from "typescript"; +import * as fs from 'fs'; +import * as path from 'path'; +import { createSourceFile, ScriptTarget, SyntaxKind } from 'typescript'; -import { getAST } from "../../parsers/googleCloud/parser"; -import { classBasedTransform } from "../../transformers/googleCloud/classBasedTransformer"; -import { clientBasedTransform } from "../../transformers/googleCloud/clientBasedTransformer"; -import { filters, getDir,groupers, printFile } from "../lib/helper"; +import { getAST } from '../../parsers/googleCloud/parser'; +import { classBasedTransform } from '../../transformers/googleCloud/classBasedTransformer'; +import { clientBasedTransform } from '../../transformers/googleCloud/clientBasedTransformer'; +import { filters, getDir, groupers, printFile } from '../lib/helper'; interface ClassData { - name: string; - methods: FunctionData[]; - constructor: constructorData; - properties: propertyData[]; + name: string; + methods: FunctionData[]; + constructor: constructorData; + properties: propertyData[]; } interface FunctionData { - pkgName: string; - version: string; - fileName: string; - functionName: string; - SDKFunctionName: string; - params: param[]; - returnType: string; - returnTypeName: string; - client: string; + pkgName: string; + version: string; + fileName: string; + functionName: string; + SDKFunctionName: string; + params: param[]; + returnType: string; + returnTypeName: string; + client: string; } interface propertyData { - name: string; - type: string; + name: string; + type: string; } interface constructorData { - parameters: param[]; + parameters: param[]; } interface param { - name: string; - type: string; - optional: boolean; + name: string; + type: string; + optional: boolean; } -const dummyFile = process.cwd() + "/dummyClasses/gcp.js"; +const dummyFile = process.cwd() + '/dummyClasses/gcp.js'; const dummyAst = createSourceFile( - dummyFile, - fs.readFileSync(dummyFile).toString(), - ScriptTarget.Latest, - true + dummyFile, + fs.readFileSync(dummyFile).toString(), + ScriptTarget.Latest, + true ); export function extractClassBasedSDKData(methods, sdkFiles): any { - const specifiedMethods = JSON.parse(JSON.stringify(methods)); - return new Promise(async (resolve, reject) => { - try { - const classes: ClassData[] = []; - - sdkFiles.map(file => { - file.classes.map(classAst => { - const classInfo: ClassData = { - name: classAst.name.text, - methods: [], - properties: [], - constructor: null - }; - - classAst.members.map(member => { - if (SyntaxKind[member.kind] === "MethodDeclaration") { - const returnType = SyntaxKind[member.type.kind]; - - const parameters = member.parameters.map(param => { - return { - name: param.name.text, - optional: param.questionToken ? true : false, - type: SyntaxKind[param.type.kind] - }; - }); - const method: FunctionData = { - pkgName: file.pkgName, - version: null, - fileName: file.fileName, - functionName: null, - SDKFunctionName: member.name.text, - params: parameters, - returnType: returnType, - returnTypeName: null, - client: classAst.name.text // Class name - }; - - if (returnType === "TypeReference") { - method.returnTypeName = member.type.typeName.text; - } - - const meth = methods.find( - meth => - meth.SDKFunctionName === method.SDKFunctionName && - meth.fileName === method.fileName - ); - method.functionName = meth ? meth.functionName : null; - classInfo.methods.push(method); - } - - if (SyntaxKind[member.kind] === "Constructor") { - const parameters = member.parameters.map(param => { - return { - name: param.name.text, - optional: param.questionToken ? true : false, - type: SyntaxKind[param.type.kind], - typeRefName: param.type.typeName - ? param.type.typeName.text - : null - }; - }); - - classInfo.constructor = { - parameters - }; - } - - if (SyntaxKind[member.kind] === "PropertyDeclaration") { - const isPrivateProp = - member.modifiers && - member.modifiers.some( - modifier => SyntaxKind[modifier.kind] === "PrivateKeyword" - ); - if (!isPrivateProp) { - const prop = { - name: member.name.text, - type: SyntaxKind[member.type.kind], - typeRefName: member.type.typeName - ? member.type.typeName.text - : null - }; - classInfo.properties.push(prop); - } - } - }); - classes.push(classInfo); - }); - }); - - methods = []; - - classes.map(classData => { - const filteredMethods: any = classData.methods.filter( - meth => meth.functionName !== null - ); - filteredMethods.map(filMeth => { - filMeth.classConstructorData = classData.constructor; - }); - - methods = methods.concat(filteredMethods); - }); - - const extractedData = { - classes, - methods - }; - if (JSON.stringify(methods) === JSON.stringify(specifiedMethods)) { - reject(new Error("Data extraction unsuccessful")); - } else { - resolve(extractedData); - } - } catch (error) { - reject(error); - } - }); + const specifiedMethods = JSON.parse(JSON.stringify(methods)); + return new Promise(async (resolve, reject) => { + try { + const classes: ClassData[] = []; + + sdkFiles.map(file => { + file.classes.map(classAst => { + const classInfo: ClassData = { + name: classAst.name.text, + methods: [], + properties: [], + constructor: null, + }; + + classAst.members.map(member => { + if (SyntaxKind[member.kind] === 'MethodDeclaration') { + const returnType = SyntaxKind[member.type.kind]; + + const parameters = member.parameters.map(param => { + return { + name: param.name.text, + optional: param.questionToken + ? true + : false, + type: SyntaxKind[param.type.kind], + }; + }); + const method: FunctionData = { + pkgName: file.pkgName, + version: null, + fileName: file.fileName, + functionName: null, + SDKFunctionName: member.name.text, + params: parameters, + returnType: returnType, + returnTypeName: null, + client: classAst.name.text, // Class name + }; + + if (returnType === 'TypeReference') { + method.returnTypeName = + member.type.typeName.text; + } + + const meth = methods.find( + meth => + meth.SDKFunctionName === + method.SDKFunctionName && + meth.fileName === method.fileName + ); + method.functionName = meth + ? meth.functionName + : null; + classInfo.methods.push(method); + } + + if (SyntaxKind[member.kind] === 'Constructor') { + const parameters = member.parameters.map(param => { + return { + name: param.name.text, + optional: param.questionToken + ? true + : false, + type: SyntaxKind[param.type.kind], + typeRefName: param.type.typeName + ? param.type.typeName.text + : null, + }; + }); + + classInfo.constructor = { + parameters, + }; + } + + if (SyntaxKind[member.kind] === 'PropertyDeclaration') { + const isPrivateProp = + member.modifiers && + member.modifiers.some( + modifier => + SyntaxKind[modifier.kind] === + 'PrivateKeyword' + ); + if (!isPrivateProp) { + const prop = { + name: member.name.text, + type: SyntaxKind[member.type.kind], + typeRefName: member.type.typeName + ? member.type.typeName.text + : null, + }; + classInfo.properties.push(prop); + } + } + }); + classes.push(classInfo); + }); + }); + + methods = []; + + classes.map(classData => { + const filteredMethods: any = classData.methods.filter( + meth => meth.functionName !== null + ); + filteredMethods.map(filMeth => { + filMeth.classConstructorData = classData.constructor; + }); + + methods = methods.concat(filteredMethods); + }); + + const extractedData = { + classes, + methods, + }; + if (JSON.stringify(methods) === JSON.stringify(specifiedMethods)) { + reject(new Error('Data extraction unsuccessful')); + } else { + resolve(extractedData); + } + } catch (error) { + reject(error); + } + }); } export function extractClientBasedSDKdata(methods, sdkFiles): any { - const specifiedMethods = JSON.parse(JSON.stringify(methods)); - return new Promise(async (resolve, reject) => { - try { - sdkFiles.map(sdkFile => { - sdkFile.client = sdkFile.ast.name.text; - sdkFile.ast.members.map(member => { - if ( - SyntaxKind[member.kind] === "MethodDeclaration" && - sdkFile.sdkFunctionNames.includes(member.name.text) - ) { - const method = methods.find( - methd => methd.SDKFunctionName === member.name.text - ); - - const parameters = member.parameters.map(param => { - return { - name: param.name.text, - optional: param.questionToken ? true : false, - type: SyntaxKind[param.type.kind] - }; - }); - - const returnType = SyntaxKind[member.type.kind]; - if (returnType === "TypeReference") { - method.returnTypeName = member.type.typeName.text; - } - - if (!method.returnType) { - method.params = parameters; - method.returnType = returnType; - method.client = sdkFile.client; - } else { - const clone = JSON.parse(JSON.stringify(method)); - clone.params = parameters; - clone.returnType = returnType; - clone.client = sdkFile.client; - methods.push(clone); - } - } - }); - }); - - if (JSON.stringify(methods) === JSON.stringify(specifiedMethods)) { - reject(new Error("Data extraction unsuccessful")); - } else { - resolve(methods); - } - } catch (error) { - reject(error); - } - }); + const specifiedMethods = JSON.parse(JSON.stringify(methods)); + return new Promise(async (resolve, reject) => { + try { + sdkFiles.map(sdkFile => { + sdkFile.client = sdkFile.ast.name.text; + sdkFile.ast.members.map(member => { + if ( + SyntaxKind[member.kind] === 'MethodDeclaration' && + sdkFile.sdkFunctionNames.includes(member.name.text) + ) { + const method = methods.find( + methd => methd.SDKFunctionName === member.name.text + ); + + const parameters = member.parameters.map(param => { + return { + name: param.name.text, + optional: param.questionToken ? true : false, + type: SyntaxKind[param.type.kind], + }; + }); + + const returnType = SyntaxKind[member.type.kind]; + if (returnType === 'TypeReference') { + method.returnTypeName = member.type.typeName.text; + } + + if (!method.returnType) { + method.params = parameters; + method.returnType = returnType; + method.client = sdkFile.client; + } else { + const clone = JSON.parse(JSON.stringify(method)); + clone.params = parameters; + clone.returnType = returnType; + clone.client = sdkFile.client; + methods.push(clone); + } + } + }); + }); + + if (JSON.stringify(methods) === JSON.stringify(specifiedMethods)) { + reject(new Error('Data extraction unsuccessful')); + } else { + resolve(methods); + } + } catch (error) { + reject(error); + } + }); } async function generateClassBasedCode(methods, data, serviceName) { - const dirPath = `../../../node_modules/@google-cloud/${methods[0].pkgName}/build/src/`; - let files = fs.readdirSync(path.join(__dirname, dirPath)); - files = files.filter( - fileName => - fileName.split(".")[1] === "d" && fileName.split(".")[2] === "ts" - ); - - const sdkFiles = files.map(fileName => { - return { - fileName: fileName, - pkgName: methods[0].pkgName, - classes: null, - sdkFunctionNames: methods - .filter(method => method.fileName === fileName) - .map(method => method.SDKFunctionName) - }; - }); - - await Promise.all( - sdkFiles.map(async file => { - file.classes = await getAST(file, true); - }) - ); - - const extractedData = await extractClassBasedSDKData(methods, sdkFiles).then( - result => result - ); - const groupedMethods = groupers.gcp(extractedData.methods); - methods = filters.gcp(groupedMethods); - data.functions = methods; - data.classData = extractedData.classes; - data.serviceName = serviceName; - - const output = await classBasedTransform(dummyAst, data); - let filePath; - const dir = getDir(serviceName); - if (!fs.existsSync(process.cwd() + "/generatedClasses/googleCloud/" + dir)) { - fs.mkdirSync(process.cwd() + "/generatedClasses/googleCloud/" + dir); - } - if (/^[A-Z]*$/.test(serviceName)) { - filePath = - process.cwd() + - "/generatedClasses/googleCloud/" + - dir + - "/gcp-" + - serviceName + - ".js"; - } else { - filePath = - process.cwd() + - "/generatedClasses/googleCloud/" + - dir + - "/gcp-" + - serviceName.charAt(0).toLowerCase() + - serviceName.slice(1) + - ".js"; - } - printFile(filePath, output); + const dirPath = `../../../node_modules/@google-cloud/${methods[0].pkgName}/build/src/`; + let files = fs.readdirSync(path.join(__dirname, dirPath)); + files = files.filter( + fileName => + fileName.split('.')[1] === 'd' && fileName.split('.')[2] === 'ts' + ); + + const sdkFiles = files.map(fileName => { + return { + fileName: fileName, + pkgName: methods[0].pkgName, + classes: null, + sdkFunctionNames: methods + .filter(method => method.fileName === fileName) + .map(method => method.SDKFunctionName), + }; + }); + + await Promise.all( + sdkFiles.map(async file => { + file.classes = await getAST(file, true); + }) + ); + + const extractedData = await extractClassBasedSDKData( + methods, + sdkFiles + ).then(result => result); + const groupedMethods = groupers.gcp(extractedData.methods); + methods = filters.gcp(groupedMethods); + data.functions = methods; + data.classData = extractedData.classes; + data.serviceName = serviceName; + + const output = await classBasedTransform(dummyAst, data); + let filePath; + const dir = getDir(serviceName); + if ( + !fs.existsSync(process.cwd() + '/generatedClasses/googleCloud/' + dir) + ) { + fs.mkdirSync(process.cwd() + '/generatedClasses/googleCloud/' + dir); + } + if (/^[A-Z]*$/.test(serviceName)) { + filePath = + process.cwd() + + '/generatedClasses/googleCloud/' + + dir + + '/gcp-' + + serviceName + + '.js'; + } else { + filePath = + process.cwd() + + '/generatedClasses/googleCloud/' + + dir + + '/gcp-' + + serviceName.charAt(0).toLowerCase() + + serviceName.slice(1) + + '.js'; + } + printFile(filePath, output); } async function generateClientBasedCode(methods, serviceName) { - const files = Array.from( - new Set(methods.map(method => method.fileName + " " + method.version)) - ); - const sdkFiles = files.map(file => { - return { - fileName: (file).split(" ")[0], - version: (file).split(" ")[1], - pkgName: methods[0].pkgName, - ast: null, - client: null, - sdkFunctionNames: methods - .filter(method => method.fileName === (file).split(" ")[0]) - .map(method => method.SDKFunctionName) - }; - }); - - await Promise.all( - sdkFiles.map(async file => { - file.ast = await getAST(file); - }) - ); - - methods = await extractClientBasedSDKdata(methods, sdkFiles).then( - result => result - ); - const groupedMethods = groupers.gcp(methods); - methods = filters.gcp(groupedMethods); - - const classData = { - functions: methods, - serviceName - }; - - const output = await clientBasedTransform(dummyAst, classData); - let filePath; - const dir = getDir(serviceName); - if (!fs.existsSync(process.cwd() + "/generatedClasses/googleCloud/" + dir)) { - fs.mkdirSync(process.cwd() + "/generatedClasses/googleCloud/" + dir); - } - if (/^[A-Z]*$/.test(serviceName)) { - filePath = - process.cwd() + - "/generatedClasses/googleCloud/" + - dir + - "/gcp-" + - serviceName + - ".js"; - } else { - filePath = - process.cwd() + - "/generatedClasses/googleCloud/" + - dir + - "/gcp-" + - serviceName.charAt(0).toLowerCase() + - serviceName.slice(1) + - ".js"; - } - printFile(filePath, output); + const files = Array.from( + new Set(methods.map(method => method.fileName + ' ' + method.version)) + ); + const sdkFiles = files.map(file => { + return { + fileName: (file).split(' ')[0], + version: (file).split(' ')[1], + pkgName: methods[0].pkgName, + ast: null, + client: null, + sdkFunctionNames: methods + .filter( + method => method.fileName === (file).split(' ')[0] + ) + .map(method => method.SDKFunctionName), + }; + }); + + await Promise.all( + sdkFiles.map(async file => { + file.ast = await getAST(file); + }) + ); + + methods = await extractClientBasedSDKdata(methods, sdkFiles).then( + result => result + ); + const groupedMethods = groupers.gcp(methods); + methods = filters.gcp(groupedMethods); + + const classData = { + functions: methods, + serviceName, + }; + + const output = await clientBasedTransform(dummyAst, classData); + let filePath; + const dir = getDir(serviceName); + if ( + !fs.existsSync(process.cwd() + '/generatedClasses/googleCloud/' + dir) + ) { + fs.mkdirSync(process.cwd() + '/generatedClasses/googleCloud/' + dir); + } + if (/^[A-Z]*$/.test(serviceName)) { + filePath = + process.cwd() + + '/generatedClasses/googleCloud/' + + dir + + '/gcp-' + + serviceName + + '.js'; + } else { + filePath = + process.cwd() + + '/generatedClasses/googleCloud/' + + dir + + '/gcp-' + + serviceName.charAt(0).toLowerCase() + + serviceName.slice(1) + + '.js'; + } + printFile(filePath, output); } export async function generateGCPClass(serviceClass, serviceName) { - const methods: FunctionData[] = []; - const data: any = {}; - - Object.keys(serviceClass).map((key, index) => { - if (key === "mainClass") { - data.mainClass = serviceClass[key]; - } else if ( - serviceClass[key].split(" ")[1].length === 2 && - serviceClass[key].split(" ")[1].charAt(0) === "v" - ) { - methods.push({ - pkgName: serviceClass[key].split(" ")[0], - version: serviceClass[key].split(" ")[1], - fileName: serviceClass[key].split(" ")[2], - functionName: key, - SDKFunctionName: serviceClass[key].split(" ")[3], - params: [], - returnType: null, - returnTypeName: null, - client: null - }); - } else { - methods.push({ - pkgName: serviceClass[key].split(" ")[0], - version: null, - fileName: serviceClass[key].split(" ")[1], - functionName: key, - SDKFunctionName: serviceClass[key].split(" ")[2], - params: [], - returnType: null, - returnTypeName: null, - client: null - }); - } - }); - - if (methods[0].version) { - generateClientBasedCode(methods, serviceName); - } else { - generateClassBasedCode(methods, data, serviceName); - } + const methods: FunctionData[] = []; + const data: any = {}; + + Object.keys(serviceClass).map((key, index) => { + if (key === 'mainClass') { + data.mainClass = serviceClass[key]; + } else if ( + serviceClass[key].split(' ')[1].length === 2 && + serviceClass[key].split(' ')[1].charAt(0) === 'v' + ) { + methods.push({ + pkgName: serviceClass[key].split(' ')[0], + version: serviceClass[key].split(' ')[1], + fileName: serviceClass[key].split(' ')[2], + functionName: key, + SDKFunctionName: serviceClass[key].split(' ')[3], + params: [], + returnType: null, + returnTypeName: null, + client: null, + }); + } else { + methods.push({ + pkgName: serviceClass[key].split(' ')[0], + version: null, + fileName: serviceClass[key].split(' ')[1], + functionName: key, + SDKFunctionName: serviceClass[key].split(' ')[2], + params: [], + returnType: null, + returnTypeName: null, + client: null, + }); + } + }); + + if (methods[0].version) { + generateClientBasedCode(methods, serviceName); + } else { + generateClassBasedCode(methods, data, serviceName); + } } diff --git a/generator/generators/lib/aws/awsHelper.js b/generator/generators/lib/aws/awsHelper.js index 440e473f..b43d982f 100644 --- a/generator/generators/lib/aws/awsHelper.js +++ b/generator/generators/lib/aws/awsHelper.js @@ -1,34 +1,38 @@ -"use strict"; +'use strict'; exports.__esModule = true; exports.filterAWSMethods = exports.groupAWSMethods = void 0; function groupAWSMethods(methods) { - var methodArr = Object.values(methods.reduce(function (result, _a) { - var functionName = _a.functionName, SDKFunctionName = _a.SDKFunctionName, params = _a.params; - // Create new group - if (!result[functionName]) - result[functionName] = { - functionName: functionName, - array: [] - }; - // Append to group - result[functionName].array.push({ - functionName: functionName, - SDKFunctionName: SDKFunctionName, - params: params - }); - return result; - }, {})); - return methodArr; + var methodArr = Object.values( + methods.reduce(function(result, _a) { + var functionName = _a.functionName, + SDKFunctionName = _a.SDKFunctionName, + params = _a.params; + // Create new group + if (!result[functionName]) + result[functionName] = { + functionName: functionName, + array: [], + }; + // Append to group + result[functionName].array.push({ + functionName: functionName, + SDKFunctionName: SDKFunctionName, + params: params, + }); + return result; + }, {}) + ); + return methodArr; } exports.groupAWSMethods = groupAWSMethods; function filterAWSMethods(groupedMethods) { - var methods = []; - groupedMethods.map(function (group) { - group.array.sort(function (a, b) { - return a.params.length - b.params.length; - }); - methods.push(group.array.slice(-1)[0]); - }); - return methods; + var methods = []; + groupedMethods.map(function(group) { + group.array.sort(function(a, b) { + return a.params.length - b.params.length; + }); + methods.push(group.array.slice(-1)[0]); + }); + return methods; } exports.filterAWSMethods = filterAWSMethods; diff --git a/generator/generators/lib/aws/awsHelper.ts b/generator/generators/lib/aws/awsHelper.ts index 562bddcd..13ddcd09 100644 --- a/generator/generators/lib/aws/awsHelper.ts +++ b/generator/generators/lib/aws/awsHelper.ts @@ -1,32 +1,32 @@ export function groupAWSMethods(methods): any { - const methodArr = Object.values( - methods.reduce((result, { functionName, SDKFunctionName, params }) => { - // Create new group - if (!result[functionName]) - result[functionName] = { - functionName, - array: [] - }; - // Append to group - result[functionName].array.push({ - functionName, - SDKFunctionName, - params - }); - return result; - }, {}) - ); + const methodArr = Object.values( + methods.reduce((result, { functionName, SDKFunctionName, params }) => { + // Create new group + if (!result[functionName]) + result[functionName] = { + functionName, + array: [], + }; + // Append to group + result[functionName].array.push({ + functionName, + SDKFunctionName, + params, + }); + return result; + }, {}) + ); - return methodArr; + return methodArr; } export function filterAWSMethods(groupedMethods): any { - const methods = []; - groupedMethods.map(group => { - group.array.sort(function(a, b) { - return a.params.length - b.params.length; - }); - methods.push(group.array.slice(-1)[0]); - }); - return methods; + const methods = []; + groupedMethods.map(group => { + group.array.sort(function(a, b) { + return a.params.length - b.params.length; + }); + methods.push(group.array.slice(-1)[0]); + }); + return methods; } diff --git a/generator/generators/lib/azure/azureHelper.js b/generator/generators/lib/azure/azureHelper.js index c0a0f595..38e14b07 100644 --- a/generator/generators/lib/azure/azureHelper.js +++ b/generator/generators/lib/azure/azureHelper.js @@ -1,49 +1,60 @@ -"use strict"; +'use strict'; exports.__esModule = true; exports.filterAzureMethods = exports.groupAzureMethods = void 0; function groupAzureMethods(methods) { - var methodArr = Object.values(methods.reduce(function (result, _a) { - var functionName = _a.functionName, SDKFunctionName = _a.SDKFunctionName, params = _a.params, pkgName = _a.pkgName, fileName = _a.fileName, client = _a.client, returnType = _a.returnType; - // Create new group - if (!result[functionName]) - result[functionName] = { - functionName: functionName, - array: [] - }; - // Append to group - result[functionName].array.push({ - functionName: functionName, - SDKFunctionName: SDKFunctionName, - params: params, - pkgName: pkgName, - fileName: fileName, - client: client, - returnType: returnType - }); - return result; - }, {})); - return methodArr; + var methodArr = Object.values( + methods.reduce(function(result, _a) { + var functionName = _a.functionName, + SDKFunctionName = _a.SDKFunctionName, + params = _a.params, + pkgName = _a.pkgName, + fileName = _a.fileName, + client = _a.client, + returnType = _a.returnType; + // Create new group + if (!result[functionName]) + result[functionName] = { + functionName: functionName, + array: [], + }; + // Append to group + result[functionName].array.push({ + functionName: functionName, + SDKFunctionName: SDKFunctionName, + params: params, + pkgName: pkgName, + fileName: fileName, + client: client, + returnType: returnType, + }); + return result; + }, {}) + ); + return methodArr; } exports.groupAzureMethods = groupAzureMethods; function filterAzureMethods(groupedMethods) { - var methods = []; - groupedMethods.map(function (group) { - if (group.array.length === 1) { - methods.push(group.array[0]); - } - else { - var methodPushed_1 = false; - group.array.map(function (method) { - if (!method.params.find(function (param) { return param.name === "callback"; })) { - methods.push(method); - methodPushed_1 = true; - } - }); - if (!methodPushed_1) { - methods.push(group.array[0]); - } - } - }); - return methods; + var methods = []; + groupedMethods.map(function(group) { + if (group.array.length === 1) { + methods.push(group.array[0]); + } else { + var methodPushed_1 = false; + group.array.map(function(method) { + if ( + !method.params.find(function(param) { + return param.name === 'callback'; + }) + ) { + methods.push(method); + methodPushed_1 = true; + } + }); + if (!methodPushed_1) { + methods.push(group.array[0]); + } + } + }); + return methods; } exports.filterAzureMethods = filterAzureMethods; diff --git a/generator/generators/lib/azure/azureHelper.ts b/generator/generators/lib/azure/azureHelper.ts index e4ffdf0e..d9d752db 100644 --- a/generator/generators/lib/azure/azureHelper.ts +++ b/generator/generators/lib/azure/azureHelper.ts @@ -1,60 +1,60 @@ export function groupAzureMethods(methods): any { - const methodArr = Object.values( - methods.reduce( - ( - result, - { - functionName, - SDKFunctionName, - params, - pkgName, - fileName, - client, - returnType - } - ) => { - // Create new group - if (!result[functionName]) - result[functionName] = { - functionName, - array: [] - }; - // Append to group - result[functionName].array.push({ - functionName, - SDKFunctionName, - params, - pkgName, - fileName, - client, - returnType - }); - return result; - }, - {} - ) - ); + const methodArr = Object.values( + methods.reduce( + ( + result, + { + functionName, + SDKFunctionName, + params, + pkgName, + fileName, + client, + returnType, + } + ) => { + // Create new group + if (!result[functionName]) + result[functionName] = { + functionName, + array: [], + }; + // Append to group + result[functionName].array.push({ + functionName, + SDKFunctionName, + params, + pkgName, + fileName, + client, + returnType, + }); + return result; + }, + {} + ) + ); - return methodArr; + return methodArr; } export function filterAzureMethods(groupedMethods): any { - const methods = []; - groupedMethods.map(group => { - if (group.array.length === 1) { - methods.push(group.array[0]); - } else { - let methodPushed = false; - group.array.map(method => { - if (!method.params.find(param => param.name === "callback")) { - methods.push(method); - methodPushed = true; - } - }); - if (!methodPushed) { - methods.push(group.array[0]); - } - } - }); - return methods; + const methods = []; + groupedMethods.map(group => { + if (group.array.length === 1) { + methods.push(group.array[0]); + } else { + let methodPushed = false; + group.array.map(method => { + if (!method.params.find(param => param.name === 'callback')) { + methods.push(method); + methodPushed = true; + } + }); + if (!methodPushed) { + methods.push(group.array[0]); + } + } + }); + return methods; } diff --git a/generator/generators/lib/googleCloud/gcpHelper.js b/generator/generators/lib/googleCloud/gcpHelper.js index 7ec28cb2..3a8caddd 100644 --- a/generator/generators/lib/googleCloud/gcpHelper.js +++ b/generator/generators/lib/googleCloud/gcpHelper.js @@ -1,51 +1,64 @@ -"use strict"; +'use strict'; exports.__esModule = true; exports.filterGCPMethods = exports.groupGCPMethods = void 0; function groupGCPMethods(methods) { - var methodArr = Object.values(methods.reduce(function (result, _a) { - var functionName = _a.functionName, SDKFunctionName = _a.SDKFunctionName, params = _a.params, pkgName = _a.pkgName, fileName = _a.fileName, client = _a.client, returnType = _a.returnType, returnTypeName = _a.returnTypeName, classConstructorData = _a.classConstructorData; - // Create new group - if (!result[functionName]) - result[functionName] = { - functionName: functionName, - array: [] - }; - // Append to group - result[functionName].array.push({ - functionName: functionName, - SDKFunctionName: SDKFunctionName, - params: params, - pkgName: pkgName, - fileName: fileName, - client: client, - returnType: returnType, - returnTypeName: returnTypeName, - classConstructorData: classConstructorData - }); - return result; - }, {})); - return methodArr; + var methodArr = Object.values( + methods.reduce(function(result, _a) { + var functionName = _a.functionName, + SDKFunctionName = _a.SDKFunctionName, + params = _a.params, + pkgName = _a.pkgName, + fileName = _a.fileName, + client = _a.client, + returnType = _a.returnType, + returnTypeName = _a.returnTypeName, + classConstructorData = _a.classConstructorData; + // Create new group + if (!result[functionName]) + result[functionName] = { + functionName: functionName, + array: [], + }; + // Append to group + result[functionName].array.push({ + functionName: functionName, + SDKFunctionName: SDKFunctionName, + params: params, + pkgName: pkgName, + fileName: fileName, + client: client, + returnType: returnType, + returnTypeName: returnTypeName, + classConstructorData: classConstructorData, + }); + return result; + }, {}) + ); + return methodArr; } exports.groupGCPMethods = groupGCPMethods; function filterGCPMethods(groupedMethods) { - var methods = []; - groupedMethods.map(function (group) { - if (group.array.length === 1) { - methods.push(group.array[0]); - } - else { - var methodPushed_1 = false; - group.array.map(function (method) { - if (!method.params.find(function (param) { return param.name === "callback"; })) { - methods.push(method); - methodPushed_1 = true; - } - }); - if (!methodPushed_1) { - methods.push(group.array[0]); - } - } - }); - return methods; + var methods = []; + groupedMethods.map(function(group) { + if (group.array.length === 1) { + methods.push(group.array[0]); + } else { + var methodPushed_1 = false; + group.array.map(function(method) { + if ( + !method.params.find(function(param) { + return param.name === 'callback'; + }) + ) { + methods.push(method); + methodPushed_1 = true; + } + }); + if (!methodPushed_1) { + methods.push(group.array[0]); + } + } + }); + return methods; } exports.filterGCPMethods = filterGCPMethods; diff --git a/generator/generators/lib/googleCloud/gcpHelper.ts b/generator/generators/lib/googleCloud/gcpHelper.ts index 8541ba6d..ee196b45 100644 --- a/generator/generators/lib/googleCloud/gcpHelper.ts +++ b/generator/generators/lib/googleCloud/gcpHelper.ts @@ -1,64 +1,64 @@ export function groupGCPMethods(methods): any { - const methodArr = Object.values( - methods.reduce( - ( - result, - { - functionName, - SDKFunctionName, - params, - pkgName, - fileName, - client, - returnType, - returnTypeName, - classConstructorData - } - ) => { - // Create new group - if (!result[functionName]) - result[functionName] = { - functionName, - array: [] - }; - // Append to group - result[functionName].array.push({ - functionName, - SDKFunctionName, - params, - pkgName, - fileName, - client, - returnType, - returnTypeName, - classConstructorData - }); - return result; - }, - {} - ) - ); + const methodArr = Object.values( + methods.reduce( + ( + result, + { + functionName, + SDKFunctionName, + params, + pkgName, + fileName, + client, + returnType, + returnTypeName, + classConstructorData, + } + ) => { + // Create new group + if (!result[functionName]) + result[functionName] = { + functionName, + array: [], + }; + // Append to group + result[functionName].array.push({ + functionName, + SDKFunctionName, + params, + pkgName, + fileName, + client, + returnType, + returnTypeName, + classConstructorData, + }); + return result; + }, + {} + ) + ); - return methodArr; + return methodArr; } export function filterGCPMethods(groupedMethods): any { - const methods = []; - groupedMethods.map(group => { - if (group.array.length === 1) { - methods.push(group.array[0]); - } else { - let methodPushed = false; - group.array.map(method => { - if (!method.params.find(param => param.name === "callback")) { - methods.push(method); - methodPushed = true; - } - }); - if (!methodPushed) { - methods.push(group.array[0]); - } - } - }); - return methods; + const methods = []; + groupedMethods.map(group => { + if (group.array.length === 1) { + methods.push(group.array[0]); + } else { + let methodPushed = false; + group.array.map(method => { + if (!method.params.find(param => param.name === 'callback')) { + methods.push(method); + methodPushed = true; + } + }); + if (!methodPushed) { + methods.push(group.array[0]); + } + } + }); + return methods; } diff --git a/generator/generators/lib/helper.js b/generator/generators/lib/helper.js index 6a79b2fd..4fbdb30a 100644 --- a/generator/generators/lib/helper.js +++ b/generator/generators/lib/helper.js @@ -1,48 +1,47 @@ -"use strict"; +'use strict'; exports.__esModule = true; exports.groupers = exports.getDir = exports.filters = exports.printFile = void 0; -var fs = require("fs"); -var awsHelper_1 = require("../lib/aws/awsHelper"); -var awsHelper_2 = require("../lib/aws/awsHelper"); -var azureHelper_1 = require("../lib/azure/azureHelper"); -var azureHelper_2 = require("../lib/azure/azureHelper"); -var gcpHelper_1 = require("../lib/googleCloud/gcpHelper"); -var gcpHelper_2 = require("../lib/googleCloud/gcpHelper"); +var fs = require('fs'); +var awsHelper_1 = require('../lib/aws/awsHelper'); +var awsHelper_2 = require('../lib/aws/awsHelper'); +var azureHelper_1 = require('../lib/azure/azureHelper'); +var azureHelper_2 = require('../lib/azure/azureHelper'); +var gcpHelper_1 = require('../lib/googleCloud/gcpHelper'); +var gcpHelper_2 = require('../lib/googleCloud/gcpHelper'); var dirMap = { - appServices: ["PaaS"], - compute: ["ComputeInstance", "Kubernetes", "Container"], - database: ["NoSqlIndexed", "RDBMS", "NoSql"], - management: ["Monitoring", "KeyManagement", "NotificationService"], - network: ["DNS", "LoadBalancer"], - security: ["IAM"], - storage: ["StorageBucket", "BlockStorage", "ArchivalStorage"], - artificialinteligence: ["Translation"] + appServices: ['PaaS'], + compute: ['ComputeInstance', 'Kubernetes', 'Container'], + database: ['NoSqlIndexed', 'RDBMS', 'NoSql'], + management: ['Monitoring', 'KeyManagement', 'NotificationService'], + network: ['DNS', 'LoadBalancer'], + security: ['IAM'], + storage: ['StorageBucket', 'BlockStorage', 'ArchivalStorage'], + artificialinteligence: ['Translation'], }; function printFile(fileName, data) { - fs.writeFile(fileName, data, function (err) { - if (err) - throw err; - }); + fs.writeFile(fileName, data, function(err) { + if (err) throw err; + }); } exports.printFile = printFile; var groupers = { - aws: awsHelper_1.groupAWSMethods, - gcp: gcpHelper_1.groupGCPMethods, - azure: azureHelper_1.groupAzureMethods + aws: awsHelper_1.groupAWSMethods, + gcp: gcpHelper_1.groupGCPMethods, + azure: azureHelper_1.groupAzureMethods, }; exports.groupers = groupers; var filters = { - aws: awsHelper_2.filterAWSMethods, - gcp: gcpHelper_2.filterGCPMethods, - azure: azureHelper_2.filterAzureMethods + aws: awsHelper_2.filterAWSMethods, + gcp: gcpHelper_2.filterGCPMethods, + azure: azureHelper_2.filterAzureMethods, }; exports.filters = filters; -var getDir = function (service) { - for (var dir in dirMap) { - if (dirMap[dir].includes(service)) { - return dir; - } - } - throw new Error("Not a valid service: " + service); +var getDir = function(service) { + for (var dir in dirMap) { + if (dirMap[dir].includes(service)) { + return dir; + } + } + throw new Error('Not a valid service: ' + service); }; exports.getDir = getDir; diff --git a/generator/generators/lib/helper.ts b/generator/generators/lib/helper.ts index 72d00af0..883aebc9 100644 --- a/generator/generators/lib/helper.ts +++ b/generator/generators/lib/helper.ts @@ -1,48 +1,48 @@ -import * as fs from "fs"; +import * as fs from 'fs'; -import { groupAWSMethods } from "../lib/aws/awsHelper"; -import { filterAWSMethods } from "../lib/aws/awsHelper"; -import { groupAzureMethods } from "../lib/azure/azureHelper"; -import { filterAzureMethods } from "../lib/azure/azureHelper"; -import { groupGCPMethods } from "../lib/googleCloud/gcpHelper"; -import { filterGCPMethods } from "../lib/googleCloud/gcpHelper"; +import { groupAWSMethods } from '../lib/aws/awsHelper'; +import { filterAWSMethods } from '../lib/aws/awsHelper'; +import { groupAzureMethods } from '../lib/azure/azureHelper'; +import { filterAzureMethods } from '../lib/azure/azureHelper'; +import { groupGCPMethods } from '../lib/googleCloud/gcpHelper'; +import { filterGCPMethods } from '../lib/googleCloud/gcpHelper'; const dirMap = { - appServices: ["PaaS"], - compute: ["ComputeInstance", "Kubernetes", "Container"], - database: ["NoSqlIndexed", "RDBMS", "NoSql"], - management: ["Monitoring", "KeyManagement", "NotificationService"], - network: ["DNS", "LoadBalancer"], - security: ["IAM"], - storage: ["StorageBucket", "BlockStorage", "ArchivalStorage"], - artificialinteligence: ["Translation"] + appServices: ['PaaS'], + compute: ['ComputeInstance', 'Kubernetes', 'Container'], + database: ['NoSqlIndexed', 'RDBMS', 'NoSql'], + management: ['Monitoring', 'KeyManagement', 'NotificationService'], + network: ['DNS', 'LoadBalancer'], + security: ['IAM'], + storage: ['StorageBucket', 'BlockStorage', 'ArchivalStorage'], + artificialinteligence: ['Translation'], }; export function printFile(fileName, data) { - fs.writeFile(fileName, data, function(err) { - if (err) throw err; - }); + fs.writeFile(fileName, data, function(err) { + if (err) throw err; + }); } const groupers = { - aws: groupAWSMethods, - gcp: groupGCPMethods, - azure: groupAzureMethods + aws: groupAWSMethods, + gcp: groupGCPMethods, + azure: groupAzureMethods, }; const filters = { - aws: filterAWSMethods, - gcp: filterGCPMethods, - azure: filterAzureMethods + aws: filterAWSMethods, + gcp: filterGCPMethods, + azure: filterAzureMethods, }; const getDir = (service: string): string => { - for (const dir in dirMap) { - if (dirMap[dir].includes(service)) { - return dir; - } - } - throw new Error("Not a valid service: " + service); + for (const dir in dirMap) { + if (dirMap[dir].includes(service)) { + return dir; + } + } + throw new Error('Not a valid service: ' + service); }; -export { filters, getDir,groupers }; +export { filters, getDir, groupers }; diff --git a/generator/main.js b/generator/main.js index b8b6b14c..dc2a8e8b 100644 --- a/generator/main.js +++ b/generator/main.js @@ -1,30 +1,38 @@ -"use strict"; +'use strict'; exports.__esModule = true; -var fs = require("fs"); -var yaml = require("js-yaml"); -var generator_1 = require("./generators/aws/generator"); -var generator_2 = require("./generators/azure/generator"); -var generator_3 = require("./generators/do/generator"); -var generator_4 = require("./generators/googleCloud/generator"); +var fs = require('fs'); +var yaml = require('js-yaml'); +var generator_1 = require('./generators/aws/generator'); +var generator_2 = require('./generators/azure/generator'); +var generator_3 = require('./generators/do/generator'); +var generator_4 = require('./generators/googleCloud/generator'); try { - var services_1 = yaml.safeLoad(fs.readFileSync("node-cloud.yml", "utf8")); - Object.keys(services_1).map(function (service, index) { - Object.keys(services_1[service]).map(function (provider, index1) { - if (provider === "Azure") { - generator_2.generateAzureClass(services_1[service][provider], service); - } - else if (provider === "AWS") { - generator_1.generateAWSClass(services_1[service][provider], service); - } - else if (provider === "GCP") { - generator_4.generateGCPClass(services_1[service][provider], service); - } - else if (provider == "DO") { - generator_3.generateDOClass(services_1[service][provider], service); - } - }); - }); -} -catch (error) { - console.error("Error : ", error); + var services_1 = yaml.safeLoad(fs.readFileSync('node-cloud.yml', 'utf8')); + Object.keys(services_1).map(function(service, index) { + Object.keys(services_1[service]).map(function(provider, index1) { + if (provider === 'Azure') { + generator_2.generateAzureClass( + services_1[service][provider], + service + ); + } else if (provider === 'AWS') { + generator_1.generateAWSClass( + services_1[service][provider], + service + ); + } else if (provider === 'GCP') { + generator_4.generateGCPClass( + services_1[service][provider], + service + ); + } else if (provider == 'DO') { + generator_3.generateDOClass( + services_1[service][provider], + service + ); + } + }); + }); +} catch (error) { + console.error('Error : ', error); } diff --git a/generator/parsers/aws/parser.js b/generator/parsers/aws/parser.js index b285118e..7e661687 100644 --- a/generator/parsers/aws/parser.js +++ b/generator/parsers/aws/parser.js @@ -1,82 +1,202 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; +'use strict'; +var __awaiter = + (this && this.__awaiter) || + function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator['throw'](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done + ? resolve(result.value) + : adopt(result.value).then(fulfilled, rejected); + } + step( + (generator = generator.apply(thisArg, _arguments || [])).next() + ); + }); + }; +var __generator = + (this && this.__generator) || + function(thisArg, body) { + var _ = { + label: 0, + sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [], + }, + f, + y, + t, + g; + return ( + (g = { next: verb(0), throw: verb(1), return: verb(2) }), + typeof Symbol === 'function' && + (g[Symbol.iterator] = function() { + return this; + }), + g + ); + function verb(n) { + return function(v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError('Generator is already executing.'); + while (_) + try { + if ( + ((f = 1), + y && + (t = + op[0] & 2 + ? y['return'] + : op[0] + ? y['throw'] || + ((t = y['return']) && t.call(y), 0) + : y.next) && + !(t = t.call(y, op[1])).done) + ) + return t; + if (((y = 0), t)) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if ( + !((t = _.trys), + (t = t.length > 0 && t[t.length - 1])) && + (op[0] === 6 || op[0] === 2) + ) { + _ = 0; + continue; + } + if ( + op[0] === 3 && + (!t || (op[1] > t[0] && op[1] < t[3])) + ) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } + }; exports.__esModule = true; exports.getAST = void 0; -var fs = require("fs"); -var path = require("path"); -var typescript_1 = require("typescript"); +var fs = require('fs'); +var path = require('path'); +var typescript_1 = require('typescript'); function getAST(sdkFileName) { - var _this = this; - return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () { - var file, ast, cloned_1, error_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 2, , 3]); - file = path.join(__dirname, "../../../node_modules/aws-sdk/clients/" + sdkFileName.toLowerCase()); - ast = typescript_1.createSourceFile(file, fs.readFileSync(file).toString(), typescript_1.ScriptTarget.Latest, true); - cloned_1 = null; - return [4 /*yield*/, ast.forEachChild(function (child) { - if (typescript_1.SyntaxKind[child.kind] === "ClassDeclaration") { - cloned_1 = Object.assign({}, child); - } - })]; - case 1: - _a.sent(); - if (!cloned_1) { - reject(new Error("Class not found!")); - } - else { - resolve(cloned_1); - } - return [3 /*break*/, 3]; - case 2: - error_1 = _a.sent(); - if (error_1.code === "ENOENT") { - reject(new Error("File not found!")); - } - else { - reject(error_1); - } - return [3 /*break*/, 3]; - case 3: return [2 /*return*/]; - } - }); - }); }); + var _this = this; + return new Promise(function(resolve, reject) { + return __awaiter(_this, void 0, void 0, function() { + var file, ast, cloned_1, error_1; + return __generator(this, function(_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + file = path.join( + __dirname, + '../../../node_modules/aws-sdk/clients/' + + sdkFileName.toLowerCase() + ); + ast = typescript_1.createSourceFile( + file, + fs.readFileSync(file).toString(), + typescript_1.ScriptTarget.Latest, + true + ); + cloned_1 = null; + return [ + 4 /*yield*/, + ast.forEachChild(function(child) { + if ( + typescript_1.SyntaxKind[child.kind] === + 'ClassDeclaration' + ) { + cloned_1 = Object.assign({}, child); + } + }), + ]; + case 1: + _a.sent(); + if (!cloned_1) { + reject(new Error('Class not found!')); + } else { + resolve(cloned_1); + } + return [3 /*break*/, 3]; + case 2: + error_1 = _a.sent(); + if (error_1.code === 'ENOENT') { + reject(new Error('File not found!')); + } else { + reject(error_1); + } + return [3 /*break*/, 3]; + case 3: + return [2 /*return*/]; + } + }); + }); + }); } exports.getAST = getAST; diff --git a/generator/parsers/azure/parser.js b/generator/parsers/azure/parser.js index 96fafb87..d88c5450 100644 --- a/generator/parsers/azure/parser.js +++ b/generator/parsers/azure/parser.js @@ -1,82 +1,204 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; +'use strict'; +var __awaiter = + (this && this.__awaiter) || + function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator['throw'](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done + ? resolve(result.value) + : adopt(result.value).then(fulfilled, rejected); + } + step( + (generator = generator.apply(thisArg, _arguments || [])).next() + ); + }); + }; +var __generator = + (this && this.__generator) || + function(thisArg, body) { + var _ = { + label: 0, + sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [], + }, + f, + y, + t, + g; + return ( + (g = { next: verb(0), throw: verb(1), return: verb(2) }), + typeof Symbol === 'function' && + (g[Symbol.iterator] = function() { + return this; + }), + g + ); + function verb(n) { + return function(v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError('Generator is already executing.'); + while (_) + try { + if ( + ((f = 1), + y && + (t = + op[0] & 2 + ? y['return'] + : op[0] + ? y['throw'] || + ((t = y['return']) && t.call(y), 0) + : y.next) && + !(t = t.call(y, op[1])).done) + ) + return t; + if (((y = 0), t)) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if ( + !((t = _.trys), + (t = t.length > 0 && t[t.length - 1])) && + (op[0] === 6 || op[0] === 2) + ) { + _ = 0; + continue; + } + if ( + op[0] === 3 && + (!t || (op[1] > t[0] && op[1] < t[3])) + ) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } + }; exports.__esModule = true; exports.getAST = void 0; -var fs = require("fs"); -var path = require("path"); -var typescript_1 = require("typescript"); +var fs = require('fs'); +var path = require('path'); +var typescript_1 = require('typescript'); function getAST(sdkFileInfo) { - var _this = this; - return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () { - var file, ast, cloned_1, error_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 2, , 3]); - file = path.join(__dirname, "../../../node_modules/@azure/" + sdkFileInfo.pkgName + "/esm/operations/" + sdkFileInfo.fileName); - ast = typescript_1.createSourceFile(file, fs.readFileSync(file).toString(), typescript_1.ScriptTarget.Latest, true); - cloned_1 = null; - return [4 /*yield*/, ast.forEachChild(function (child) { - if (typescript_1.SyntaxKind[child.kind] === "ClassDeclaration") { - cloned_1 = Object.assign({}, child); - } - })]; - case 1: - _a.sent(); - if (!cloned_1) { - reject(new Error("Class not found!")); - } - else { - resolve(cloned_1); - } - return [3 /*break*/, 3]; - case 2: - error_1 = _a.sent(); - if (error_1.code === "ENOENT") { - reject(new Error("File not found!")); - } - else { - reject(error_1); - } - return [3 /*break*/, 3]; - case 3: return [2 /*return*/]; - } - }); - }); }); + var _this = this; + return new Promise(function(resolve, reject) { + return __awaiter(_this, void 0, void 0, function() { + var file, ast, cloned_1, error_1; + return __generator(this, function(_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + file = path.join( + __dirname, + '../../../node_modules/@azure/' + + sdkFileInfo.pkgName + + '/esm/operations/' + + sdkFileInfo.fileName + ); + ast = typescript_1.createSourceFile( + file, + fs.readFileSync(file).toString(), + typescript_1.ScriptTarget.Latest, + true + ); + cloned_1 = null; + return [ + 4 /*yield*/, + ast.forEachChild(function(child) { + if ( + typescript_1.SyntaxKind[child.kind] === + 'ClassDeclaration' + ) { + cloned_1 = Object.assign({}, child); + } + }), + ]; + case 1: + _a.sent(); + if (!cloned_1) { + reject(new Error('Class not found!')); + } else { + resolve(cloned_1); + } + return [3 /*break*/, 3]; + case 2: + error_1 = _a.sent(); + if (error_1.code === 'ENOENT') { + reject(new Error('File not found!')); + } else { + reject(error_1); + } + return [3 /*break*/, 3]; + case 3: + return [2 /*return*/]; + } + }); + }); + }); } exports.getAST = getAST; diff --git a/generator/parsers/do/parser.js b/generator/parsers/do/parser.js index e861342d..e1fb57ec 100644 --- a/generator/parsers/do/parser.js +++ b/generator/parsers/do/parser.js @@ -1,83 +1,202 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; +'use strict'; +var __awaiter = + (this && this.__awaiter) || + function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator['throw'](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done + ? resolve(result.value) + : adopt(result.value).then(fulfilled, rejected); + } + step( + (generator = generator.apply(thisArg, _arguments || [])).next() + ); + }); + }; +var __generator = + (this && this.__generator) || + function(thisArg, body) { + var _ = { + label: 0, + sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [], + }, + f, + y, + t, + g; + return ( + (g = { next: verb(0), throw: verb(1), return: verb(2) }), + typeof Symbol === 'function' && + (g[Symbol.iterator] = function() { + return this; + }), + g + ); + function verb(n) { + return function(v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError('Generator is already executing.'); + while (_) + try { + if ( + ((f = 1), + y && + (t = + op[0] & 2 + ? y['return'] + : op[0] + ? y['throw'] || + ((t = y['return']) && t.call(y), 0) + : y.next) && + !(t = t.call(y, op[1])).done) + ) + return t; + if (((y = 0), t)) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if ( + !((t = _.trys), + (t = t.length > 0 && t[t.length - 1])) && + (op[0] === 6 || op[0] === 2) + ) { + _ = 0; + continue; + } + if ( + op[0] === 3 && + (!t || (op[1] > t[0] && op[1] < t[3])) + ) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } + }; exports.__esModule = true; exports.getAST = void 0; -var fs = require("fs"); -var path = require("path"); -var typescript_1 = require("typescript"); +var fs = require('fs'); +var path = require('path'); +var typescript_1 = require('typescript'); function getAST(sdkFileName) { - var _this = this; - return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () { - var file, ast, cloned_1, error_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 2, , 3]); - file = path.join(__dirname, "../../../node_modules/do-wrapper/dist/modules/" + - sdkFileName.toLowerCase()); - ast = typescript_1.createSourceFile(file, fs.readFileSync(file).toString(), typescript_1.ScriptTarget.Latest, true); - cloned_1 = null; - return [4 /*yield*/, ast.forEachChild(function (child) { - if (typescript_1.SyntaxKind[child.kind] === "ClassDeclaration") { - cloned_1 = Object.assign({}, child); - } - })]; - case 1: - _a.sent(); - if (!cloned_1) { - reject(new Error("Class not found!")); - } - else { - resolve(cloned_1); - } - return [3 /*break*/, 3]; - case 2: - error_1 = _a.sent(); - if (error_1.code === "ENOENT") { - reject(new Error("File not found!")); - } - else { - reject(error_1); - } - return [3 /*break*/, 3]; - case 3: return [2 /*return*/]; - } - }); - }); }); + var _this = this; + return new Promise(function(resolve, reject) { + return __awaiter(_this, void 0, void 0, function() { + var file, ast, cloned_1, error_1; + return __generator(this, function(_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 2, , 3]); + file = path.join( + __dirname, + '../../../node_modules/do-wrapper/dist/modules/' + + sdkFileName.toLowerCase() + ); + ast = typescript_1.createSourceFile( + file, + fs.readFileSync(file).toString(), + typescript_1.ScriptTarget.Latest, + true + ); + cloned_1 = null; + return [ + 4 /*yield*/, + ast.forEachChild(function(child) { + if ( + typescript_1.SyntaxKind[child.kind] === + 'ClassDeclaration' + ) { + cloned_1 = Object.assign({}, child); + } + }), + ]; + case 1: + _a.sent(); + if (!cloned_1) { + reject(new Error('Class not found!')); + } else { + resolve(cloned_1); + } + return [3 /*break*/, 3]; + case 2: + error_1 = _a.sent(); + if (error_1.code === 'ENOENT') { + reject(new Error('File not found!')); + } else { + reject(error_1); + } + return [3 /*break*/, 3]; + case 3: + return [2 /*return*/]; + } + }); + }); + }); } exports.getAST = getAST; diff --git a/generator/parsers/googleCloud/parser.js b/generator/parsers/googleCloud/parser.js index cde5f858..1fcf3819 100644 --- a/generator/parsers/googleCloud/parser.js +++ b/generator/parsers/googleCloud/parser.js @@ -1,102 +1,234 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; +'use strict'; +var __awaiter = + (this && this.__awaiter) || + function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator['throw'](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done + ? resolve(result.value) + : adopt(result.value).then(fulfilled, rejected); + } + step( + (generator = generator.apply(thisArg, _arguments || [])).next() + ); + }); + }; +var __generator = + (this && this.__generator) || + function(thisArg, body) { + var _ = { + label: 0, + sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [], + }, + f, + y, + t, + g; + return ( + (g = { next: verb(0), throw: verb(1), return: verb(2) }), + typeof Symbol === 'function' && + (g[Symbol.iterator] = function() { + return this; + }), + g + ); + function verb(n) { + return function(v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError('Generator is already executing.'); + while (_) + try { + if ( + ((f = 1), + y && + (t = + op[0] & 2 + ? y['return'] + : op[0] + ? y['throw'] || + ((t = y['return']) && t.call(y), 0) + : y.next) && + !(t = t.call(y, op[1])).done) + ) + return t; + if (((y = 0), t)) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if ( + !((t = _.trys), + (t = t.length > 0 && t[t.length - 1])) && + (op[0] === 6 || op[0] === 2) + ) { + _ = 0; + continue; + } + if ( + op[0] === 3 && + (!t || (op[1] > t[0] && op[1] < t[3])) + ) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } + }; exports.__esModule = true; exports.getAST = void 0; -var fs = require("fs"); -var path = require("path"); -var typescript_1 = require("typescript"); +var fs = require('fs'); +var path = require('path'); +var typescript_1 = require('typescript'); function getAST(sdkFileInfo, multi) { - var _this = this; - var filePath; - if (sdkFileInfo.version) { - filePath = "../../../node_modules/@google-cloud/" + sdkFileInfo.pkgName + "/build/src/" + sdkFileInfo.version + "/" + sdkFileInfo.fileName; - } - else { - filePath = "../../../node_modules/@google-cloud/" + sdkFileInfo.pkgName + "/build/src/" + sdkFileInfo.fileName; - } - return new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () { - var file, ast, classes_1, cloned, error_1; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 4, , 5]); - file = path.join(__dirname, filePath); - ast = typescript_1.createSourceFile(file, fs.readFileSync(file).toString(), typescript_1.ScriptTarget.Latest, true); - if (!(multi === true)) return [3 /*break*/, 1]; - classes_1 = []; - ast.forEachChild(function (child) { - if (typescript_1.SyntaxKind[child.kind] === "ClassDeclaration") { - var cloned = Object.assign({}, child); - classes_1.push(cloned); - } - }); - resolve(classes_1); - return [3 /*break*/, 3]; - case 1: - cloned = null; - return [4 /*yield*/, ast.forEachChild(function (child) { - if (typescript_1.SyntaxKind[child.kind] === "ClassDeclaration") { - var cloned_1 = Object.assign({}, child); - return resolve(cloned_1); - } - })]; - case 2: - _a.sent(); - if (!cloned) { - return [2 /*return*/, reject(new Error("Class not found!"))]; - } - else { - return [2 /*return*/, resolve(cloned)]; - } - _a.label = 3; - case 3: return [3 /*break*/, 5]; - case 4: - error_1 = _a.sent(); - if (error_1.code === "ENOENT") { - reject(new Error("File not found!")); - } - else { - reject(error_1); - } - return [3 /*break*/, 5]; - case 5: return [2 /*return*/]; - } - }); - }); }); + var _this = this; + var filePath; + if (sdkFileInfo.version) { + filePath = + '../../../node_modules/@google-cloud/' + + sdkFileInfo.pkgName + + '/build/src/' + + sdkFileInfo.version + + '/' + + sdkFileInfo.fileName; + } else { + filePath = + '../../../node_modules/@google-cloud/' + + sdkFileInfo.pkgName + + '/build/src/' + + sdkFileInfo.fileName; + } + return new Promise(function(resolve, reject) { + return __awaiter(_this, void 0, void 0, function() { + var file, ast, classes_1, cloned, error_1; + return __generator(this, function(_a) { + switch (_a.label) { + case 0: + _a.trys.push([0, 4, , 5]); + file = path.join(__dirname, filePath); + ast = typescript_1.createSourceFile( + file, + fs.readFileSync(file).toString(), + typescript_1.ScriptTarget.Latest, + true + ); + if (!(multi === true)) return [3 /*break*/, 1]; + classes_1 = []; + ast.forEachChild(function(child) { + if ( + typescript_1.SyntaxKind[child.kind] === + 'ClassDeclaration' + ) { + var cloned = Object.assign({}, child); + classes_1.push(cloned); + } + }); + resolve(classes_1); + return [3 /*break*/, 3]; + case 1: + cloned = null; + return [ + 4 /*yield*/, + ast.forEachChild(function(child) { + if ( + typescript_1.SyntaxKind[child.kind] === + 'ClassDeclaration' + ) { + var cloned_1 = Object.assign({}, child); + return resolve(cloned_1); + } + }), + ]; + case 2: + _a.sent(); + if (!cloned) { + return [ + 2 /*return*/, + reject(new Error('Class not found!')), + ]; + } else { + return [2 /*return*/, resolve(cloned)]; + } + _a.label = 3; + case 3: + return [3 /*break*/, 5]; + case 4: + error_1 = _a.sent(); + if (error_1.code === 'ENOENT') { + reject(new Error('File not found!')); + } else { + reject(error_1); + } + return [3 /*break*/, 5]; + case 5: + return [2 /*return*/]; + } + }); + }); + }); } exports.getAST = getAST; diff --git a/generator/parsers/googleCloud/parser.ts b/generator/parsers/googleCloud/parser.ts index 3fd698f2..1cf53b17 100644 --- a/generator/parsers/googleCloud/parser.ts +++ b/generator/parsers/googleCloud/parser.ts @@ -1,55 +1,55 @@ -import * as fs from "fs"; -import * as path from "path"; -import { createSourceFile, ScriptTarget, SyntaxKind } from "typescript"; +import * as fs from 'fs'; +import * as path from 'path'; +import { createSourceFile, ScriptTarget, SyntaxKind } from 'typescript'; export function getAST(sdkFileInfo, multi?: boolean) { - let filePath; - if (sdkFileInfo.version) { - filePath = `../../../node_modules/@google-cloud/${sdkFileInfo.pkgName}/build/src/${sdkFileInfo.version}/${sdkFileInfo.fileName}`; - } else { - filePath = `../../../node_modules/@google-cloud/${sdkFileInfo.pkgName}/build/src/${sdkFileInfo.fileName}`; - } + let filePath; + if (sdkFileInfo.version) { + filePath = `../../../node_modules/@google-cloud/${sdkFileInfo.pkgName}/build/src/${sdkFileInfo.version}/${sdkFileInfo.fileName}`; + } else { + filePath = `../../../node_modules/@google-cloud/${sdkFileInfo.pkgName}/build/src/${sdkFileInfo.fileName}`; + } - return new Promise(async (resolve, reject) => { - try { - const file = path.join(__dirname, filePath); - const ast = createSourceFile( - file, - fs.readFileSync(file).toString(), - ScriptTarget.Latest, - true - ); + return new Promise(async (resolve, reject) => { + try { + const file = path.join(__dirname, filePath); + const ast = createSourceFile( + file, + fs.readFileSync(file).toString(), + ScriptTarget.Latest, + true + ); - if (multi === true) { - const classes = []; - ast.forEachChild(child => { - if (SyntaxKind[child.kind] === "ClassDeclaration") { - const cloned = Object.assign({}, child); - classes.push(cloned); - } - }); - resolve(classes); - } else { - const cloned = null; - await ast.forEachChild(child => { - if (SyntaxKind[child.kind] === "ClassDeclaration") { - const cloned = Object.assign({}, child); - return resolve(cloned); - } - }); + if (multi === true) { + const classes = []; + ast.forEachChild(child => { + if (SyntaxKind[child.kind] === 'ClassDeclaration') { + const cloned = Object.assign({}, child); + classes.push(cloned); + } + }); + resolve(classes); + } else { + const cloned = null; + await ast.forEachChild(child => { + if (SyntaxKind[child.kind] === 'ClassDeclaration') { + const cloned = Object.assign({}, child); + return resolve(cloned); + } + }); - if (!cloned) { - return reject(new Error("Class not found!")); - } else { - return resolve(cloned); - } - } - } catch (error) { - if (error.code === "ENOENT") { - reject(new Error("File not found!")); - } else { - reject(error); - } - } - }); + if (!cloned) { + return reject(new Error('Class not found!')); + } else { + return resolve(cloned); + } + } + } catch (error) { + if (error.code === 'ENOENT') { + reject(new Error('File not found!')); + } else { + reject(error); + } + } + }); } diff --git a/generator/test/generators/googleCloud/generator.test.ts b/generator/test/generators/googleCloud/generator.test.ts index 7d06e419..0702d965 100644 --- a/generator/test/generators/googleCloud/generator.test.ts +++ b/generator/test/generators/googleCloud/generator.test.ts @@ -1,159 +1,163 @@ -import { expect } from "chai"; -import { SyntaxKind } from "typescript"; +import { expect } from 'chai'; +import { SyntaxKind } from 'typescript'; import { - extractClassBasedSDKData, - extractClientBasedSDKdata -} from "../../../generators/googleCloud/generator"; -import { readJsonData, readSourceFile } from "../lib/helper"; - -describe("GCP generator extractClassBasedSDKData", () => { - context("with valid methods and valid AST", () => { - it("should return class data", async () => { - const methods: any = await readJsonData( - "validDataset_1", - "googleCloud", - "methods" - ); - - const sdkFiles: any = await readJsonData( - "validDataset_1", - "googleCloud", - "files" - ); - - await Promise.all( - sdkFiles.map(async file => { - file.classes = []; - const sdkFile: any = await readSourceFile( - "validDataset_1", - "googleCloud" - ); - sdkFile.forEachChild(child => { - if (SyntaxKind[child.kind] === "ClassDeclaration") { - const cloned = Object.assign({}, child); - file.classes.push(cloned); - } - }); - }) - ); - - extractClassBasedSDKData(methods, sdkFiles).then(result => { - expect(result).to.be.an("object"); - expect(result.methods).to.be.an("array"); - }); - }); - }); - - context("with invalid AST", () => { - it("should return Error", async () => { - const methods: any = await readJsonData( - "invalidDataset_1", - "googleCloud", - "methods" - ); - - const sdkFiles: any = await readJsonData( - "invalidDataset_1", - "googleCloud", - "files" - ); - - await Promise.all( - sdkFiles.map(async file => { - file.classes = []; - const sdkFile: any = await readSourceFile( - "invalidDataset_1", - "googleCloud" - ); - sdkFile.forEachChild(child => { - if (SyntaxKind[child.kind] === "ClassDeclaration") { - const cloned = Object.assign({}, child); - file.classes.push(cloned); - } - }); - }) - ); - - extractClassBasedSDKData(methods, sdkFiles).then( - result => {}, - error => { - expect(error.message).to.eql("Data extraction unsuccessful"); - } - ); - }); - }); + extractClassBasedSDKData, + extractClientBasedSDKdata, +} from '../../../generators/googleCloud/generator'; +import { readJsonData, readSourceFile } from '../lib/helper'; + +describe('GCP generator extractClassBasedSDKData', () => { + context('with valid methods and valid AST', () => { + it('should return class data', async () => { + const methods: any = await readJsonData( + 'validDataset_1', + 'googleCloud', + 'methods' + ); + + const sdkFiles: any = await readJsonData( + 'validDataset_1', + 'googleCloud', + 'files' + ); + + await Promise.all( + sdkFiles.map(async file => { + file.classes = []; + const sdkFile: any = await readSourceFile( + 'validDataset_1', + 'googleCloud' + ); + sdkFile.forEachChild(child => { + if (SyntaxKind[child.kind] === 'ClassDeclaration') { + const cloned = Object.assign({}, child); + file.classes.push(cloned); + } + }); + }) + ); + + extractClassBasedSDKData(methods, sdkFiles).then(result => { + expect(result).to.be.an('object'); + expect(result.methods).to.be.an('array'); + }); + }); + }); + + context('with invalid AST', () => { + it('should return Error', async () => { + const methods: any = await readJsonData( + 'invalidDataset_1', + 'googleCloud', + 'methods' + ); + + const sdkFiles: any = await readJsonData( + 'invalidDataset_1', + 'googleCloud', + 'files' + ); + + await Promise.all( + sdkFiles.map(async file => { + file.classes = []; + const sdkFile: any = await readSourceFile( + 'invalidDataset_1', + 'googleCloud' + ); + sdkFile.forEachChild(child => { + if (SyntaxKind[child.kind] === 'ClassDeclaration') { + const cloned = Object.assign({}, child); + file.classes.push(cloned); + } + }); + }) + ); + + extractClassBasedSDKData(methods, sdkFiles).then( + result => {}, + error => { + expect(error.message).to.eql( + 'Data extraction unsuccessful' + ); + } + ); + }); + }); }); -describe("GCP generator extractClientBasedSDKdata", () => { - context("with valid methods and valid AST", () => { - it("should return class data", async () => { - const methods: any = await readJsonData( - "validDataset_2", - "googleCloud", - "methods" - ); - - const sdkFiles: any = await readJsonData( - "validDataset_2", - "googleCloud", - "files" - ); - - await Promise.all( - sdkFiles.map(async file => { - const sdkFile: any = await readSourceFile( - "validDataset_2", - "googleCloud" - ); - sdkFile.forEachChild(child => { - if (SyntaxKind[child.kind] === "ClassDeclaration") { - file.ast = Object.assign({}, child); - } - }); - }) - ); - - extractClientBasedSDKdata(methods, sdkFiles).then(result => { - expect(result).to.be.an("array"); - }); - }); - }); - - context("with invalid AST", () => { - it("should return Error", async () => { - const methods: any = await readJsonData( - "invalidDataset_2", - "googleCloud", - "methods" - ); - - const sdkFiles: any = await readJsonData( - "invalidDataset_2", - "googleCloud", - "files" - ); - - await Promise.all( - sdkFiles.map(async file => { - const sdkFile: any = await readSourceFile( - "invalidDataset_2", - "googleCloud" - ); - sdkFile.forEachChild(child => { - if (SyntaxKind[child.kind] === "ClassDeclaration") { - file.ast = Object.assign({}, child); - } - }); - }) - ); - - extractClientBasedSDKdata(methods, sdkFiles).then( - result => {}, - error => { - expect(error.message).to.eql("Data extraction unsuccessful"); - } - ); - }); - }); +describe('GCP generator extractClientBasedSDKdata', () => { + context('with valid methods and valid AST', () => { + it('should return class data', async () => { + const methods: any = await readJsonData( + 'validDataset_2', + 'googleCloud', + 'methods' + ); + + const sdkFiles: any = await readJsonData( + 'validDataset_2', + 'googleCloud', + 'files' + ); + + await Promise.all( + sdkFiles.map(async file => { + const sdkFile: any = await readSourceFile( + 'validDataset_2', + 'googleCloud' + ); + sdkFile.forEachChild(child => { + if (SyntaxKind[child.kind] === 'ClassDeclaration') { + file.ast = Object.assign({}, child); + } + }); + }) + ); + + extractClientBasedSDKdata(methods, sdkFiles).then(result => { + expect(result).to.be.an('array'); + }); + }); + }); + + context('with invalid AST', () => { + it('should return Error', async () => { + const methods: any = await readJsonData( + 'invalidDataset_2', + 'googleCloud', + 'methods' + ); + + const sdkFiles: any = await readJsonData( + 'invalidDataset_2', + 'googleCloud', + 'files' + ); + + await Promise.all( + sdkFiles.map(async file => { + const sdkFile: any = await readSourceFile( + 'invalidDataset_2', + 'googleCloud' + ); + sdkFile.forEachChild(child => { + if (SyntaxKind[child.kind] === 'ClassDeclaration') { + file.ast = Object.assign({}, child); + } + }); + }) + ); + + extractClientBasedSDKdata(methods, sdkFiles).then( + result => {}, + error => { + expect(error.message).to.eql( + 'Data extraction unsuccessful' + ); + } + ); + }); + }); }); diff --git a/generator/transformers/aws/transformer.js b/generator/transformers/aws/transformer.js index 683ff0a5..da809d1a 100644 --- a/generator/transformers/aws/transformer.js +++ b/generator/transformers/aws/transformer.js @@ -1,200 +1,450 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; +'use strict'; +var __awaiter = + (this && this.__awaiter) || + function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator['throw'](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done + ? resolve(result.value) + : adopt(result.value).then(fulfilled, rejected); + } + step( + (generator = generator.apply(thisArg, _arguments || [])).next() + ); + }); + }; +var __generator = + (this && this.__generator) || + function(thisArg, body) { + var _ = { + label: 0, + sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [], + }, + f, + y, + t, + g; + return ( + (g = { next: verb(0), throw: verb(1), return: verb(2) }), + typeof Symbol === 'function' && + (g[Symbol.iterator] = function() { + return this; + }), + g + ); + function verb(n) { + return function(v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError('Generator is already executing.'); + while (_) + try { + if ( + ((f = 1), + y && + (t = + op[0] & 2 + ? y['return'] + : op[0] + ? y['throw'] || + ((t = y['return']) && t.call(y), 0) + : y.next) && + !(t = t.call(y, op[1])).done) + ) + return t; + if (((y = 0), t)) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if ( + !((t = _.trys), + (t = t.length > 0 && t[t.length - 1])) && + (op[0] === 6 || op[0] === 2) + ) { + _ = 0; + continue; + } + if ( + op[0] === 3 && + (!t || (op[1] > t[0] && op[1] < t[3])) + ) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } + }; exports.__esModule = true; exports.transform = void 0; -var lodash_1 = require("lodash"); -var ts = require("typescript"); +var lodash_1 = require('lodash'); +var ts = require('typescript'); var dummyIdentifiers = [ - "ClassName", - "_sdkClassName", - "SDKClassName", - "SDKFunctionName" + 'ClassName', + '_sdkClassName', + 'SDKClassName', + 'SDKFunctionName', ]; var printer = ts.createPrinter({ - newLine: ts.NewLineKind.LineFeed, - removeComments: false + newLine: ts.NewLineKind.LineFeed, + removeComments: false, }); function addMultiLineComment(node, comment) { - ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, comment, true); + ts.addSyntheticLeadingComment( + node, + ts.SyntaxKind.MultiLineCommentTrivia, + comment, + true + ); } function runTransformation(sourceCode, transformMethod) { - return new Promise(function (resolve, reject) { - try { - var result = ts.transform(sourceCode, [transformMethod]); - var transformedNodes = result.transformed[0]; - var output = printer.printNode(ts.EmitHint.SourceFile, transformedNodes, sourceCode); - resolve(output); - } - catch (error) { - reject(error); - } - }); + return new Promise(function(resolve, reject) { + try { + var result = ts.transform(sourceCode, [transformMethod]); + var transformedNodes = result.transformed[0]; + var output = printer.printNode( + ts.EmitHint.SourceFile, + transformedNodes, + sourceCode + ); + resolve(output); + } catch (error) { + reject(error); + } + }); } function toSourceFile(sourceCode) { - return ts.createSourceFile("dummyClass.js", sourceCode, ts.ScriptTarget.Latest, true); + return ts.createSourceFile( + 'dummyClass.js', + sourceCode, + ts.ScriptTarget.Latest, + true + ); } function transform(code, classData) { - return __awaiter(this, void 0, void 0, function () { - var addFunctions, addIdentifiers, addComments, node, result_1, result_2, result_3; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - addFunctions = function (context) { return function (rootNode) { - function visit(node) { - if (ts.isClassDeclaration(node)) { - var functions_1 = []; - classData.functions.map(function (method) { - var clonedNode = Object.assign({}, node.members[1]); - clonedNode.name = ts.createIdentifier(method.functionName); - functions_1.push(clonedNode); - }); - var updatedClass = ts.updateClassDeclaration(node, node.decorators, node.modifiers, node.name, node.typeParameters, node.heritageClauses, ts.createNodeArray([node.members[0]].concat(functions_1))); - return updatedClass; - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; }; - addIdentifiers = function (context) { return function (rootNode) { - var count = 0; - function visit(node) { - if (ts.isMethodDeclaration(node)) { - var parameters = classData.functions[count].params.map(function (param) { - var paramNode = ts.createParameter(undefined, undefined, undefined, param.name); - if (param.optional) { - paramNode.initializer = ts.createIdentifier("undefined"); - } - return paramNode; - }); - node.parameters = parameters; - } - if (ts.isIdentifier(node) && dummyIdentifiers.includes(node.text)) { - var updatedIdentifier = void 0; - switch (node.text) { - case "ClassName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier("AWS_" + classData.serviceName)); - break; - case "_sdkClassName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier("_" + - classData.className.charAt(0).toLowerCase() + - classData.className.substr(1))); - break; - case "SDKClassName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier(classData.className)); - break; - case "SDKFunctionName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier(classData.functions[count].SDKFunctionName)); - count++; - } - return updatedIdentifier; - } - if (ts.isCallExpression(node)) { - node.expression.forEachChild(function (childNode) { - if (ts.isIdentifier(childNode) && - childNode.text === "SDKFunctionName") { - var args = classData.functions[count].params.map(function (param) { - return ts.createIdentifier(param.name); - }); - node.arguments = args.concat(node.arguments); - } - }); - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; }; - addComments = function (context) { return function (rootNode) { - var count = 0; - function visit(node) { - if (ts.isClassDeclaration(node)) { - addMultiLineComment(node, "This is an auto generated class, please do not change."); - var comment = "*\n * Class to create a " + classData.className + " object\n * @category AWS \n "; - addMultiLineComment(node, comment); - } - if (ts.isMethodDeclaration(node)) { - var parameters = classData.functions[count].params.map(function (param) { - var statment; - if (param.optional) { - statment = "* @param {" + param.typeName + "} [" + param.name + "] - Data required for " + classData.functions[count].SDKFunctionName; - } - else { - statment = "* @param {" + param.typeName + "} " + param.name + " - Data required for " + classData.functions[count].SDKFunctionName; - } - return statment; - }); - var comment = void 0; - if (parameters.length > 0) { - var paramStatments_1 = ""; - parameters.map(function (param) { - paramStatments_1 = paramStatments_1.concat(paramStatments_1 === "" ? "" + param : "\n " + param); - }); - comment = "*\n * Trigers the " + classData.functions[count].SDKFunctionName + " function of " + classData.className + "\n " + paramStatments_1 + "\n * @returns {Promise<" + classData.functions[count].SDKFunctionName + "Response>}\n "; - } - else { - comment = "*\n * Trigers the " + classData.functions[count].SDKFunctionName + " function of " + classData.className + "\n * @returns {Promise<" + classData.functions[count].SDKFunctionName + "Response>}\n "; - } - addMultiLineComment(node, comment); - count++; - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; }; - node = code.statements.find(function (stm) { return ts.isClassDeclaration(stm); }); - if (!classData.className || !classData.functions) { - throw new Error("Input is invalid"); - } - if (!node || !node.members.some(function (member) { return ts.isMethodDeclaration(member); })) { - throw new Error("Code is invalid"); - } - code = lodash_1.cloneDeep(code); - return [4 /*yield*/, runTransformation(code, addFunctions)]; - case 1: - result_1 = _a.sent(); - return [4 /*yield*/, runTransformation(toSourceFile(result_1), addIdentifiers)]; - case 2: - result_2 = _a.sent(); - return [4 /*yield*/, runTransformation(toSourceFile(result_2), addComments)]; - case 3: - result_3 = _a.sent(); - return [2 /*return*/, result_3]; - } - }); - }); + return __awaiter(this, void 0, void 0, function() { + var addFunctions, + addIdentifiers, + addComments, + node, + result_1, + result_2, + result_3; + return __generator(this, function(_a) { + switch (_a.label) { + case 0: + addFunctions = function(context) { + return function(rootNode) { + function visit(node) { + if (ts.isClassDeclaration(node)) { + var functions_1 = []; + classData.functions.map(function(method) { + var clonedNode = Object.assign( + {}, + node.members[1] + ); + clonedNode.name = ts.createIdentifier( + method.functionName + ); + functions_1.push(clonedNode); + }); + var updatedClass = ts.updateClassDeclaration( + node, + node.decorators, + node.modifiers, + node.name, + node.typeParameters, + node.heritageClauses, + ts.createNodeArray( + [node.members[0]].concat( + functions_1 + ) + ) + ); + return updatedClass; + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + }; + addIdentifiers = function(context) { + return function(rootNode) { + var count = 0; + function visit(node) { + if (ts.isMethodDeclaration(node)) { + var parameters = classData.functions[ + count + ].params.map(function(param) { + var paramNode = ts.createParameter( + undefined, + undefined, + undefined, + param.name + ); + if (param.optional) { + paramNode.initializer = ts.createIdentifier( + 'undefined' + ); + } + return paramNode; + }); + node.parameters = parameters; + } + if ( + ts.isIdentifier(node) && + dummyIdentifiers.includes(node.text) + ) { + var updatedIdentifier = void 0; + switch (node.text) { + case 'ClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + 'AWS_' + + classData.serviceName + ) + ); + break; + case '_sdkClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + '_' + + classData.className + .charAt(0) + .toLowerCase() + + classData.className.substr( + 1 + ) + ) + ); + break; + case 'SDKClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.className + ) + ); + break; + case 'SDKFunctionName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.functions[count] + .SDKFunctionName + ) + ); + count++; + } + return updatedIdentifier; + } + if (ts.isCallExpression(node)) { + node.expression.forEachChild(function( + childNode + ) { + if ( + ts.isIdentifier(childNode) && + childNode.text === 'SDKFunctionName' + ) { + var args = classData.functions[ + count + ].params.map(function(param) { + return ts.createIdentifier( + param.name + ); + }); + node.arguments = args.concat( + node.arguments + ); + } + }); + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + }; + addComments = function(context) { + return function(rootNode) { + var count = 0; + function visit(node) { + if (ts.isClassDeclaration(node)) { + addMultiLineComment( + node, + 'This is an auto generated class, please do not change.' + ); + var comment = + '*\n * Class to create a ' + + classData.className + + ' object\n * @category AWS \n '; + addMultiLineComment(node, comment); + } + if (ts.isMethodDeclaration(node)) { + var parameters = classData.functions[ + count + ].params.map(function(param) { + var statment; + if (param.optional) { + statment = + '* @param {' + + param.typeName + + '} [' + + param.name + + '] - Data required for ' + + classData.functions[count] + .SDKFunctionName; + } else { + statment = + '* @param {' + + param.typeName + + '} ' + + param.name + + ' - Data required for ' + + classData.functions[count] + .SDKFunctionName; + } + return statment; + }); + var comment = void 0; + if (parameters.length > 0) { + var paramStatments_1 = ''; + parameters.map(function(param) { + paramStatments_1 = paramStatments_1.concat( + paramStatments_1 === '' + ? '' + param + : '\n ' + param + ); + }); + comment = + '*\n * Trigers the ' + + classData.functions[count] + .SDKFunctionName + + ' function of ' + + classData.className + + '\n ' + + paramStatments_1 + + '\n * @returns {Promise<' + + classData.functions[count] + .SDKFunctionName + + 'Response>}\n '; + } else { + comment = + '*\n * Trigers the ' + + classData.functions[count] + .SDKFunctionName + + ' function of ' + + classData.className + + '\n * @returns {Promise<' + + classData.functions[count] + .SDKFunctionName + + 'Response>}\n '; + } + addMultiLineComment(node, comment); + count++; + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + }; + node = code.statements.find(function(stm) { + return ts.isClassDeclaration(stm); + }); + if (!classData.className || !classData.functions) { + throw new Error('Input is invalid'); + } + if ( + !node || + !node.members.some(function(member) { + return ts.isMethodDeclaration(member); + }) + ) { + throw new Error('Code is invalid'); + } + code = lodash_1.cloneDeep(code); + return [4 /*yield*/, runTransformation(code, addFunctions)]; + case 1: + result_1 = _a.sent(); + return [ + 4 /*yield*/, + runTransformation( + toSourceFile(result_1), + addIdentifiers + ), + ]; + case 2: + result_2 = _a.sent(); + return [ + 4 /*yield*/, + runTransformation(toSourceFile(result_2), addComments), + ]; + case 3: + result_3 = _a.sent(); + return [2 /*return*/, result_3]; + } + }); + }); } exports.transform = transform; diff --git a/generator/transformers/aws/transformer.ts b/generator/transformers/aws/transformer.ts index d97edda1..ed063fe9 100644 --- a/generator/transformers/aws/transformer.ts +++ b/generator/transformers/aws/transformer.ts @@ -1,239 +1,252 @@ -import { cloneDeep } from "lodash"; -import * as ts from "typescript"; +import { cloneDeep } from 'lodash'; +import * as ts from 'typescript'; const dummyIdentifiers = [ - "ClassName", - "_sdkClassName", - "SDKClassName", - "SDKFunctionName" + 'ClassName', + '_sdkClassName', + 'SDKClassName', + 'SDKFunctionName', ]; const printer: ts.Printer = ts.createPrinter({ - newLine: ts.NewLineKind.LineFeed, - removeComments: false + newLine: ts.NewLineKind.LineFeed, + removeComments: false, }); function addMultiLineComment(node, comment: string) { - ts.addSyntheticLeadingComment( - node, - ts.SyntaxKind.MultiLineCommentTrivia, - comment, - true - ); + ts.addSyntheticLeadingComment( + node, + ts.SyntaxKind.MultiLineCommentTrivia, + comment, + true + ); } function runTransformation(sourceCode, transformMethod): Promise { - return new Promise((resolve, reject) => { - try { - const result = ts.transform(sourceCode, [transformMethod]); - const transformedNodes = result.transformed[0]; - const output = printer.printNode( - ts.EmitHint.SourceFile, - transformedNodes, - sourceCode - ); - resolve(output); - } catch (error) { - reject(error); - } - }); + return new Promise((resolve, reject) => { + try { + const result = ts.transform(sourceCode, [transformMethod]); + const transformedNodes = result.transformed[0]; + const output = printer.printNode( + ts.EmitHint.SourceFile, + transformedNodes, + sourceCode + ); + resolve(output); + } catch (error) { + reject(error); + } + }); } function toSourceFile(sourceCode: string): ts.SourceFile { - return ts.createSourceFile( - "dummyClass.js", - sourceCode, - ts.ScriptTarget.Latest, - true - ); + return ts.createSourceFile( + 'dummyClass.js', + sourceCode, + ts.ScriptTarget.Latest, + true + ); } export async function transform( - code: ts.SourceFile, - classData: any + code: ts.SourceFile, + classData: any ): Promise { - const addFunctions = ( - context: ts.TransformationContext - ) => (rootNode: T) => { - function visit(node: ts.Node): ts.Node { - if (ts.isClassDeclaration(node)) { - const functions: any = []; - classData.functions.map(method => { - const clonedNode = Object.assign({}, node.members[1]); - clonedNode.name = ts.createIdentifier(method.functionName); - functions.push(clonedNode); - }); - - const updatedClass = ts.updateClassDeclaration( - node, - node.decorators, - node.modifiers, - node.name, - node.typeParameters, - node.heritageClauses, - ts.createNodeArray([node.members[0]].concat(functions)) - ); - - return updatedClass; - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; - - const addIdentifiers = ( - context: ts.TransformationContext - ) => (rootNode: T) => { - let count = 0; - function visit(node: ts.Node): ts.Node { - if (ts.isMethodDeclaration(node)) { - const parameters = classData.functions[count].params.map(param => { - const paramNode = ts.createParameter( - undefined, - undefined, - undefined, - param.name - ); - - if (param.optional) { - paramNode.initializer = ts.createIdentifier("undefined"); - } - - return paramNode; - }); - - node.parameters = parameters; - } - - if (ts.isIdentifier(node) && dummyIdentifiers.includes(node.text)) { - let updatedIdentifier; - - switch (node.text) { - case "ClassName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier("AWS_" + classData.serviceName) - ); - break; - case "_sdkClassName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier( - "_" + - classData.className.charAt(0).toLowerCase() + - classData.className.substr(1) - ) - ); - break; - case "SDKClassName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier(classData.className) - ); - break; - case "SDKFunctionName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier(classData.functions[count].SDKFunctionName) - ); - count++; - } - - return updatedIdentifier; - } - - if (ts.isCallExpression(node)) { - node.expression.forEachChild(childNode => { - if ( - ts.isIdentifier(childNode) && - childNode.text === "SDKFunctionName" - ) { - const args = classData.functions[count].params.map(param => - ts.createIdentifier(param.name) - ); - node.arguments = args.concat(node.arguments); - } - }); - } - - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; - - const addComments = ( - context: ts.TransformationContext - ) => (rootNode: T) => { - let count = 0; - - function visit(node: ts.Node): ts.Node { - if (ts.isClassDeclaration(node)) { - addMultiLineComment( - node, - "This is an auto generated class, please do not change." - ); - const comment = `* + const addFunctions = ( + context: ts.TransformationContext + ) => (rootNode: T) => { + function visit(node: ts.Node): ts.Node { + if (ts.isClassDeclaration(node)) { + const functions: any = []; + classData.functions.map(method => { + const clonedNode = Object.assign({}, node.members[1]); + clonedNode.name = ts.createIdentifier(method.functionName); + functions.push(clonedNode); + }); + + const updatedClass = ts.updateClassDeclaration( + node, + node.decorators, + node.modifiers, + node.name, + node.typeParameters, + node.heritageClauses, + ts.createNodeArray([node.members[0]].concat(functions)) + ); + + return updatedClass; + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + + const addIdentifiers = ( + context: ts.TransformationContext + ) => (rootNode: T) => { + let count = 0; + function visit(node: ts.Node): ts.Node { + if (ts.isMethodDeclaration(node)) { + const parameters = classData.functions[count].params.map( + param => { + const paramNode = ts.createParameter( + undefined, + undefined, + undefined, + param.name + ); + + if (param.optional) { + paramNode.initializer = ts.createIdentifier( + 'undefined' + ); + } + + return paramNode; + } + ); + + node.parameters = parameters; + } + + if (ts.isIdentifier(node) && dummyIdentifiers.includes(node.text)) { + let updatedIdentifier; + + switch (node.text) { + case 'ClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier('AWS_' + classData.serviceName) + ); + break; + case '_sdkClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + '_' + + classData.className + .charAt(0) + .toLowerCase() + + classData.className.substr(1) + ) + ); + break; + case 'SDKClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier(classData.className) + ); + break; + case 'SDKFunctionName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.functions[count].SDKFunctionName + ) + ); + count++; + } + + return updatedIdentifier; + } + + if (ts.isCallExpression(node)) { + node.expression.forEachChild(childNode => { + if ( + ts.isIdentifier(childNode) && + childNode.text === 'SDKFunctionName' + ) { + const args = classData.functions[count].params.map( + param => ts.createIdentifier(param.name) + ); + node.arguments = args.concat(node.arguments); + } + }); + } + + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + + const addComments = ( + context: ts.TransformationContext + ) => (rootNode: T) => { + let count = 0; + + function visit(node: ts.Node): ts.Node { + if (ts.isClassDeclaration(node)) { + addMultiLineComment( + node, + 'This is an auto generated class, please do not change.' + ); + const comment = `* * Class to create a ${classData.className} object * @category AWS `; - addMultiLineComment(node, comment); - } - - if (ts.isMethodDeclaration(node)) { - const parameters = classData.functions[count].params.map(param => { - let statment; - - if (param.optional) { - statment = `* @param {${param.typeName}} [${param.name}] - Data required for ${classData.functions[count].SDKFunctionName}`; - } else { - statment = `* @param {${param.typeName}} ${param.name} - Data required for ${classData.functions[count].SDKFunctionName}`; - } - return statment; - }); - - let comment; - if (parameters.length > 0) { - let paramStatments: string = ""; - parameters.map(param => { - paramStatments = paramStatments.concat( - paramStatments === "" ? `${param}` : `\n ${param}` - ); - }); - - comment = `* + addMultiLineComment(node, comment); + } + + if (ts.isMethodDeclaration(node)) { + const parameters = classData.functions[count].params.map( + param => { + let statment; + + if (param.optional) { + statment = `* @param {${param.typeName}} [${param.name}] - Data required for ${classData.functions[count].SDKFunctionName}`; + } else { + statment = `* @param {${param.typeName}} ${param.name} - Data required for ${classData.functions[count].SDKFunctionName}`; + } + return statment; + } + ); + + let comment; + if (parameters.length > 0) { + let paramStatments: string = ''; + parameters.map(param => { + paramStatments = paramStatments.concat( + paramStatments === '' ? `${param}` : `\n ${param}` + ); + }); + + comment = `* * Trigers the ${classData.functions[count].SDKFunctionName} function of ${classData.className} ${paramStatments} * @returns {Promise<${classData.functions[count].SDKFunctionName}Response>} `; - } else { - comment = `* + } else { + comment = `* * Trigers the ${classData.functions[count].SDKFunctionName} function of ${classData.className} * @returns {Promise<${classData.functions[count].SDKFunctionName}Response>} `; - } - - addMultiLineComment(node, comment); - count++; - } - - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; - - const node: any = code.statements.find(stm => ts.isClassDeclaration(stm)); - - if (!classData.className || !classData.functions) { - throw new Error("Input is invalid"); - } - - if (!node || !node.members.some(member => ts.isMethodDeclaration(member))) { - throw new Error("Code is invalid"); - } - - code = cloneDeep(code); - - const result_1 = await runTransformation(code, addFunctions); - const result_2 = await runTransformation( - toSourceFile(result_1), - addIdentifiers - ); - const result_3 = await runTransformation(toSourceFile(result_2), addComments); - return result_3; + } + + addMultiLineComment(node, comment); + count++; + } + + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + + const node: any = code.statements.find(stm => ts.isClassDeclaration(stm)); + + if (!classData.className || !classData.functions) { + throw new Error('Input is invalid'); + } + + if (!node || !node.members.some(member => ts.isMethodDeclaration(member))) { + throw new Error('Code is invalid'); + } + + code = cloneDeep(code); + + const result_1 = await runTransformation(code, addFunctions); + const result_2 = await runTransformation( + toSourceFile(result_1), + addIdentifiers + ); + const result_3 = await runTransformation( + toSourceFile(result_2), + addComments + ); + return result_3; } diff --git a/generator/transformers/azure/transformer.js b/generator/transformers/azure/transformer.js index c9f7f03c..069cea3a 100644 --- a/generator/transformers/azure/transformer.js +++ b/generator/transformers/azure/transformer.js @@ -1,212 +1,480 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; +'use strict'; +var __awaiter = + (this && this.__awaiter) || + function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator['throw'](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done + ? resolve(result.value) + : adopt(result.value).then(fulfilled, rejected); + } + step( + (generator = generator.apply(thisArg, _arguments || [])).next() + ); + }); + }; +var __generator = + (this && this.__generator) || + function(thisArg, body) { + var _ = { + label: 0, + sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [], + }, + f, + y, + t, + g; + return ( + (g = { next: verb(0), throw: verb(1), return: verb(2) }), + typeof Symbol === 'function' && + (g[Symbol.iterator] = function() { + return this; + }), + g + ); + function verb(n) { + return function(v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError('Generator is already executing.'); + while (_) + try { + if ( + ((f = 1), + y && + (t = + op[0] & 2 + ? y['return'] + : op[0] + ? y['throw'] || + ((t = y['return']) && t.call(y), 0) + : y.next) && + !(t = t.call(y, op[1])).done) + ) + return t; + if (((y = 0), t)) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if ( + !((t = _.trys), + (t = t.length > 0 && t[t.length - 1])) && + (op[0] === 6 || op[0] === 2) + ) { + _ = 0; + continue; + } + if ( + op[0] === 3 && + (!t || (op[1] > t[0] && op[1] < t[3])) + ) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } + }; exports.__esModule = true; exports.transform = void 0; -var lodash_1 = require("lodash"); -var ts = require("typescript"); +var lodash_1 = require('lodash'); +var ts = require('typescript'); var dummyIdentifiers = [ - "ClassName", - "SDKClassName", - "SDKFunctionName", - "ClientName", - "functionClient" + 'ClassName', + 'SDKClassName', + 'SDKFunctionName', + 'ClientName', + 'functionClient', ]; var printer = ts.createPrinter({ - newLine: ts.NewLineKind.LineFeed, - removeComments: false + newLine: ts.NewLineKind.LineFeed, + removeComments: false, }); function addMultiLineComment(node, comment) { - ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, comment, true); + ts.addSyntheticLeadingComment( + node, + ts.SyntaxKind.MultiLineCommentTrivia, + comment, + true + ); } function runTransformation(sourceCode, transformMethod) { - return new Promise(function (resolve, reject) { - try { - var result = ts.transform(sourceCode, [transformMethod]); - var transformedNodes = result.transformed[0]; - var output = printer.printNode(ts.EmitHint.SourceFile, transformedNodes, sourceCode); - resolve(output); - } - catch (error) { - reject(error); - } - }); + return new Promise(function(resolve, reject) { + try { + var result = ts.transform(sourceCode, [transformMethod]); + var transformedNodes = result.transformed[0]; + var output = printer.printNode( + ts.EmitHint.SourceFile, + transformedNodes, + sourceCode + ); + resolve(output); + } catch (error) { + reject(error); + } + }); } function toSourceFile(sourceCode) { - return ts.createSourceFile("dummyClass.js", sourceCode, ts.ScriptTarget.Latest, true); + return ts.createSourceFile( + 'dummyClass.js', + sourceCode, + ts.ScriptTarget.Latest, + true + ); } function transform(code, classData) { - return __awaiter(this, void 0, void 0, function () { - var node, importStatments, addFunctions, addIdentifiers, addComments, result_1, result_2, result_3; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - node = code.statements.find(function (stm) { return ts.isClassDeclaration(stm); }); - if (!classData.functions) { - throw new Error("Input is invalid"); - } - if (!node || !node.members.some(function (member) { return ts.isMethodDeclaration(member); })) { - throw new Error("Code is invalid"); - } - code = lodash_1.cloneDeep(code); - // import related - classData.clients = Array.from(new Set(classData.functions.map(function (method) { return method.client; }))); - importStatments = new Array(classData.clients.length); - importStatments.fill(Object.assign({}, code.statements[0])); - code.statements = importStatments.concat(code.statements.slice(1)); - addFunctions = function (context) { return function (rootNode) { - function visit(node) { - if (ts.isClassDeclaration(node)) { - var functions_1 = []; - classData.functions.map(function (method) { - var clonedNode = Object.assign({}, node.members[1]); - clonedNode.name = ts.createIdentifier(method.functionName); - functions_1.push(clonedNode); - }); - var updatedClass = ts.updateClassDeclaration(node, node.decorators, node.modifiers, node.name, node.typeParameters, node.heritageClauses, ts.createNodeArray([node.members[0]].concat(functions_1))); - return updatedClass; - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; }; - addIdentifiers = function (context) { return function (rootNode) { - var count = 0; - var clientCount = 0; - function visit(node) { - if (ts.isMethodDeclaration(node)) { - var parameters = classData.functions[count].params.map(function (param) { - var paramNode = ts.createParameter(undefined, undefined, undefined, param.name); - if (param.optional) { - paramNode.initializer = ts.createIdentifier("undefined"); - } - return paramNode; - }); - node.parameters = parameters; - } - if (ts.isStringLiteral(node) && node.text === "pkgName") { - return ts.createStringLiteral("@azure/" + classData.functions[0].pkgName); - } - if (ts.isIdentifier(node) && dummyIdentifiers.includes(node.text)) { - var updatedIdentifier = void 0; - switch (node.text) { - case "ClassName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier("Azure_" + classData.serviceName)); - break; - case "SDKClassName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier(classData.functions[count].fileName.split(".")[0])); - break; - case "functionClient": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier(classData.functions[count].client)); - break; - case "ClientName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier(classData.clients[clientCount])); - clientCount++; - break; - case "SDKFunctionName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier(classData.functions[count].SDKFunctionName)); - count++; - } - return updatedIdentifier; - } - if (ts.isCallExpression(node)) { - node.expression.forEachChild(function (childNode) { - if (ts.isIdentifier(childNode) && - childNode.text === "SDKFunctionName") { - var args = classData.functions[count].params.map(function (param) { - return ts.createIdentifier(param.name); - }); - node.arguments = args; - } - }); - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; }; - addComments = function (context) { return function (rootNode) { - var count = 0; - function visit(node) { - if (ts.isClassDeclaration(node)) { - addMultiLineComment(node, "This is an auto generated class, please do not change."); - var comment = "*\n * Class to create a " + classData.serviceName + " object\n * @category Azure\n "; - addMultiLineComment(node, comment); - } - if (ts.isMethodDeclaration(node)) { - var parameters = classData.functions[count].params.map(function (param) { - var statment; - if (param.optional) { - statment = "* @param {" + param.type + "} [" + param.name + "] - Optional parameter"; - } - else { - statment = "* @param {" + param.type + "} " + param.name + " - Mandatory parameter"; - } - return statment; - }); - var comment = void 0; - if (parameters.length > 0) { - var paramStatments_1 = ""; - parameters.map(function (param) { - paramStatments_1 = paramStatments_1.concat(paramStatments_1 === "" ? "" + param : "\n " + param); - }); - comment = "*\n * Trigers the " + classData.functions[count].SDKFunctionName + " function of " + classData.functions[0].pkgName.split("-")[1] + "\n " + paramStatments_1 + "\n * @returns {Promise<" + classData.functions[count].SDKFunctionName + "Response>}\n "; - } - else { - comment = "*\n * Trigers the " + classData.functions[count].SDKFunctionName + " function of " + classData.functions[0].pkgName.split("-")[1] + "\n * @returns {Promise<" + classData.functions[count].SDKFunctionName + "Response>}\n "; - } - addMultiLineComment(node, comment); - count++; - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; }; - return [4 /*yield*/, runTransformation(code, addFunctions)]; - case 1: - result_1 = _a.sent(); - return [4 /*yield*/, runTransformation(toSourceFile(result_1), addIdentifiers)]; - case 2: - result_2 = _a.sent(); - return [4 /*yield*/, runTransformation(toSourceFile(result_2), addComments)]; - case 3: - result_3 = _a.sent(); - return [2 /*return*/, result_3]; - } - }); - }); + return __awaiter(this, void 0, void 0, function() { + var node, + importStatments, + addFunctions, + addIdentifiers, + addComments, + result_1, + result_2, + result_3; + return __generator(this, function(_a) { + switch (_a.label) { + case 0: + node = code.statements.find(function(stm) { + return ts.isClassDeclaration(stm); + }); + if (!classData.functions) { + throw new Error('Input is invalid'); + } + if ( + !node || + !node.members.some(function(member) { + return ts.isMethodDeclaration(member); + }) + ) { + throw new Error('Code is invalid'); + } + code = lodash_1.cloneDeep(code); + // import related + classData.clients = Array.from( + new Set( + classData.functions.map(function(method) { + return method.client; + }) + ) + ); + importStatments = new Array(classData.clients.length); + importStatments.fill(Object.assign({}, code.statements[0])); + code.statements = importStatments.concat( + code.statements.slice(1) + ); + addFunctions = function(context) { + return function(rootNode) { + function visit(node) { + if (ts.isClassDeclaration(node)) { + var functions_1 = []; + classData.functions.map(function(method) { + var clonedNode = Object.assign( + {}, + node.members[1] + ); + clonedNode.name = ts.createIdentifier( + method.functionName + ); + functions_1.push(clonedNode); + }); + var updatedClass = ts.updateClassDeclaration( + node, + node.decorators, + node.modifiers, + node.name, + node.typeParameters, + node.heritageClauses, + ts.createNodeArray( + [node.members[0]].concat( + functions_1 + ) + ) + ); + return updatedClass; + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + }; + addIdentifiers = function(context) { + return function(rootNode) { + var count = 0; + var clientCount = 0; + function visit(node) { + if (ts.isMethodDeclaration(node)) { + var parameters = classData.functions[ + count + ].params.map(function(param) { + var paramNode = ts.createParameter( + undefined, + undefined, + undefined, + param.name + ); + if (param.optional) { + paramNode.initializer = ts.createIdentifier( + 'undefined' + ); + } + return paramNode; + }); + node.parameters = parameters; + } + if ( + ts.isStringLiteral(node) && + node.text === 'pkgName' + ) { + return ts.createStringLiteral( + '@azure/' + + classData.functions[0].pkgName + ); + } + if ( + ts.isIdentifier(node) && + dummyIdentifiers.includes(node.text) + ) { + var updatedIdentifier = void 0; + switch (node.text) { + case 'ClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + 'Azure_' + + classData.serviceName + ) + ); + break; + case 'SDKClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.functions[ + count + ].fileName.split('.')[0] + ) + ); + break; + case 'functionClient': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.functions[count] + .client + ) + ); + break; + case 'ClientName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.clients[ + clientCount + ] + ) + ); + clientCount++; + break; + case 'SDKFunctionName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.functions[count] + .SDKFunctionName + ) + ); + count++; + } + return updatedIdentifier; + } + if (ts.isCallExpression(node)) { + node.expression.forEachChild(function( + childNode + ) { + if ( + ts.isIdentifier(childNode) && + childNode.text === 'SDKFunctionName' + ) { + var args = classData.functions[ + count + ].params.map(function(param) { + return ts.createIdentifier( + param.name + ); + }); + node.arguments = args; + } + }); + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + }; + addComments = function(context) { + return function(rootNode) { + var count = 0; + function visit(node) { + if (ts.isClassDeclaration(node)) { + addMultiLineComment( + node, + 'This is an auto generated class, please do not change.' + ); + var comment = + '*\n * Class to create a ' + + classData.serviceName + + ' object\n * @category Azure\n '; + addMultiLineComment(node, comment); + } + if (ts.isMethodDeclaration(node)) { + var parameters = classData.functions[ + count + ].params.map(function(param) { + var statment; + if (param.optional) { + statment = + '* @param {' + + param.type + + '} [' + + param.name + + '] - Optional parameter'; + } else { + statment = + '* @param {' + + param.type + + '} ' + + param.name + + ' - Mandatory parameter'; + } + return statment; + }); + var comment = void 0; + if (parameters.length > 0) { + var paramStatments_1 = ''; + parameters.map(function(param) { + paramStatments_1 = paramStatments_1.concat( + paramStatments_1 === '' + ? '' + param + : '\n ' + param + ); + }); + comment = + '*\n * Trigers the ' + + classData.functions[count] + .SDKFunctionName + + ' function of ' + + classData.functions[0].pkgName.split( + '-' + )[1] + + '\n ' + + paramStatments_1 + + '\n * @returns {Promise<' + + classData.functions[count] + .SDKFunctionName + + 'Response>}\n '; + } else { + comment = + '*\n * Trigers the ' + + classData.functions[count] + .SDKFunctionName + + ' function of ' + + classData.functions[0].pkgName.split( + '-' + )[1] + + '\n * @returns {Promise<' + + classData.functions[count] + .SDKFunctionName + + 'Response>}\n '; + } + addMultiLineComment(node, comment); + count++; + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + }; + return [4 /*yield*/, runTransformation(code, addFunctions)]; + case 1: + result_1 = _a.sent(); + return [ + 4 /*yield*/, + runTransformation( + toSourceFile(result_1), + addIdentifiers + ), + ]; + case 2: + result_2 = _a.sent(); + return [ + 4 /*yield*/, + runTransformation(toSourceFile(result_2), addComments), + ]; + case 3: + result_3 = _a.sent(); + return [2 /*return*/, result_3]; + } + }); + }); } exports.transform = transform; diff --git a/generator/transformers/azure/transformer.ts b/generator/transformers/azure/transformer.ts index 53ffb53c..e27a4ef6 100644 --- a/generator/transformers/azure/transformer.ts +++ b/generator/transformers/azure/transformer.ts @@ -1,262 +1,279 @@ -import { cloneDeep } from "lodash"; -import * as ts from "typescript"; +import { cloneDeep } from 'lodash'; +import * as ts from 'typescript'; const dummyIdentifiers = [ - "ClassName", - "SDKClassName", - "SDKFunctionName", - "ClientName", - "functionClient" + 'ClassName', + 'SDKClassName', + 'SDKFunctionName', + 'ClientName', + 'functionClient', ]; const printer: ts.Printer = ts.createPrinter({ - newLine: ts.NewLineKind.LineFeed, - removeComments: false + newLine: ts.NewLineKind.LineFeed, + removeComments: false, }); function addMultiLineComment(node, comment: string) { - ts.addSyntheticLeadingComment( - node, - ts.SyntaxKind.MultiLineCommentTrivia, - comment, - true - ); + ts.addSyntheticLeadingComment( + node, + ts.SyntaxKind.MultiLineCommentTrivia, + comment, + true + ); } function runTransformation(sourceCode, transformMethod): Promise { - return new Promise((resolve, reject) => { - try { - const result = ts.transform(sourceCode, [transformMethod]); - const transformedNodes = result.transformed[0]; - const output = printer.printNode( - ts.EmitHint.SourceFile, - transformedNodes, - sourceCode - ); - resolve(output); - } catch (error) { - reject(error); - } - }); + return new Promise((resolve, reject) => { + try { + const result = ts.transform(sourceCode, [transformMethod]); + const transformedNodes = result.transformed[0]; + const output = printer.printNode( + ts.EmitHint.SourceFile, + transformedNodes, + sourceCode + ); + resolve(output); + } catch (error) { + reject(error); + } + }); } function toSourceFile(sourceCode: string): ts.SourceFile { - return ts.createSourceFile( - "dummyClass.js", - sourceCode, - ts.ScriptTarget.Latest, - true - ); + return ts.createSourceFile( + 'dummyClass.js', + sourceCode, + ts.ScriptTarget.Latest, + true + ); } export async function transform( - code: ts.SourceFile, - classData: any + code: ts.SourceFile, + classData: any ): Promise { - const node: any = code.statements.find(stm => ts.isClassDeclaration(stm)); + const node: any = code.statements.find(stm => ts.isClassDeclaration(stm)); - if (!classData.functions) { - throw new Error("Input is invalid"); - } + if (!classData.functions) { + throw new Error('Input is invalid'); + } - if (!node || !node.members.some(member => ts.isMethodDeclaration(member))) { - throw new Error("Code is invalid"); - } + if (!node || !node.members.some(member => ts.isMethodDeclaration(member))) { + throw new Error('Code is invalid'); + } - code = cloneDeep(code); + code = cloneDeep(code); - // import related - classData.clients = Array.from( - new Set(classData.functions.map(method => method.client)) - ); - const importStatments: any = new Array(classData.clients.length); - importStatments.fill(Object.assign({}, code.statements[0])); - code.statements = importStatments.concat(code.statements.slice(1)); - // import related + // import related + classData.clients = Array.from( + new Set(classData.functions.map(method => method.client)) + ); + const importStatments: any = new Array(classData.clients.length); + importStatments.fill(Object.assign({}, code.statements[0])); + code.statements = importStatments.concat(code.statements.slice(1)); + // import related - const addFunctions = ( - context: ts.TransformationContext - ) => (rootNode: T) => { - function visit(node: ts.Node): ts.Node { - if (ts.isClassDeclaration(node)) { - const functions: any = []; - classData.functions.map(method => { - const clonedNode = Object.assign({}, node.members[1]); - clonedNode.name = ts.createIdentifier(method.functionName); - functions.push(clonedNode); - }); + const addFunctions = ( + context: ts.TransformationContext + ) => (rootNode: T) => { + function visit(node: ts.Node): ts.Node { + if (ts.isClassDeclaration(node)) { + const functions: any = []; + classData.functions.map(method => { + const clonedNode = Object.assign({}, node.members[1]); + clonedNode.name = ts.createIdentifier(method.functionName); + functions.push(clonedNode); + }); - const updatedClass = ts.updateClassDeclaration( - node, - node.decorators, - node.modifiers, - node.name, - node.typeParameters, - node.heritageClauses, - ts.createNodeArray([node.members[0]].concat(functions)) - ); + const updatedClass = ts.updateClassDeclaration( + node, + node.decorators, + node.modifiers, + node.name, + node.typeParameters, + node.heritageClauses, + ts.createNodeArray([node.members[0]].concat(functions)) + ); - return updatedClass; - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; + return updatedClass; + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; - const addIdentifiers = ( - context: ts.TransformationContext - ) => (rootNode: T) => { - let count = 0; - let clientCount = 0; - function visit(node: ts.Node): ts.Node { - if (ts.isMethodDeclaration(node)) { - const parameters = classData.functions[count].params.map(param => { - const paramNode = ts.createParameter( - undefined, - undefined, - undefined, - param.name - ); + const addIdentifiers = ( + context: ts.TransformationContext + ) => (rootNode: T) => { + let count = 0; + let clientCount = 0; + function visit(node: ts.Node): ts.Node { + if (ts.isMethodDeclaration(node)) { + const parameters = classData.functions[count].params.map( + param => { + const paramNode = ts.createParameter( + undefined, + undefined, + undefined, + param.name + ); - if (param.optional) { - paramNode.initializer = ts.createIdentifier("undefined"); - } + if (param.optional) { + paramNode.initializer = ts.createIdentifier( + 'undefined' + ); + } - return paramNode; - }); + return paramNode; + } + ); - node.parameters = parameters; - } + node.parameters = parameters; + } - if (ts.isStringLiteral(node) && node.text === "pkgName") { - return ts.createStringLiteral( - "@azure/" + classData.functions[0].pkgName - ); - } + if (ts.isStringLiteral(node) && node.text === 'pkgName') { + return ts.createStringLiteral( + '@azure/' + classData.functions[0].pkgName + ); + } - if (ts.isIdentifier(node) && dummyIdentifiers.includes(node.text)) { - let updatedIdentifier; - switch (node.text) { - case "ClassName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier("Azure_" + classData.serviceName) - ); - break; - case "SDKClassName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier( - classData.functions[count].fileName.split(".")[0] - ) - ); - break; - case "functionClient": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier(classData.functions[count].client) - ); - break; - case "ClientName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier(classData.clients[clientCount]) - ); - clientCount++; - break; - case "SDKFunctionName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier(classData.functions[count].SDKFunctionName) - ); - count++; - } - return updatedIdentifier; - } + if (ts.isIdentifier(node) && dummyIdentifiers.includes(node.text)) { + let updatedIdentifier; + switch (node.text) { + case 'ClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + 'Azure_' + classData.serviceName + ) + ); + break; + case 'SDKClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.functions[count].fileName.split( + '.' + )[0] + ) + ); + break; + case 'functionClient': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.functions[count].client + ) + ); + break; + case 'ClientName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier(classData.clients[clientCount]) + ); + clientCount++; + break; + case 'SDKFunctionName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.functions[count].SDKFunctionName + ) + ); + count++; + } + return updatedIdentifier; + } - if (ts.isCallExpression(node)) { - node.expression.forEachChild(childNode => { - if ( - ts.isIdentifier(childNode) && - childNode.text === "SDKFunctionName" - ) { - const args = classData.functions[count].params.map(param => - ts.createIdentifier(param.name) - ); - node.arguments = args; - } - }); - } + if (ts.isCallExpression(node)) { + node.expression.forEachChild(childNode => { + if ( + ts.isIdentifier(childNode) && + childNode.text === 'SDKFunctionName' + ) { + const args = classData.functions[count].params.map( + param => ts.createIdentifier(param.name) + ); + node.arguments = args; + } + }); + } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; - const addComments = ( - context: ts.TransformationContext - ) => (rootNode: T) => { - let count = 0; + const addComments = ( + context: ts.TransformationContext + ) => (rootNode: T) => { + let count = 0; - function visit(node: ts.Node): ts.Node { - if (ts.isClassDeclaration(node)) { - addMultiLineComment( - node, - "This is an auto generated class, please do not change." - ); - const comment = `* + function visit(node: ts.Node): ts.Node { + if (ts.isClassDeclaration(node)) { + addMultiLineComment( + node, + 'This is an auto generated class, please do not change.' + ); + const comment = `* * Class to create a ${classData.serviceName} object * @category Azure `; - addMultiLineComment(node, comment); - } + addMultiLineComment(node, comment); + } - if (ts.isMethodDeclaration(node)) { - const parameters = classData.functions[count].params.map(param => { - let statment; + if (ts.isMethodDeclaration(node)) { + const parameters = classData.functions[count].params.map( + param => { + let statment; - if (param.optional) { - statment = `* @param {${param.type}} [${param.name}] - Optional parameter`; - } else { - statment = `* @param {${param.type}} ${param.name} - Mandatory parameter`; - } - return statment; - }); + if (param.optional) { + statment = `* @param {${param.type}} [${param.name}] - Optional parameter`; + } else { + statment = `* @param {${param.type}} ${param.name} - Mandatory parameter`; + } + return statment; + } + ); - let comment; - if (parameters.length > 0) { - let paramStatments: string = ""; - parameters.map(param => { - paramStatments = paramStatments.concat( - paramStatments === "" ? `${param}` : `\n ${param}` - ); - }); + let comment; + if (parameters.length > 0) { + let paramStatments: string = ''; + parameters.map(param => { + paramStatments = paramStatments.concat( + paramStatments === '' ? `${param}` : `\n ${param}` + ); + }); - comment = `* + comment = `* * Trigers the ${classData.functions[count].SDKFunctionName} function of ${ - classData.functions[0].pkgName.split("-")[1] - } + classData.functions[0].pkgName.split('-')[1] + } ${paramStatments} * @returns {Promise<${classData.functions[count].SDKFunctionName}Response>} `; - } else { - comment = `* + } else { + comment = `* * Trigers the ${classData.functions[count].SDKFunctionName} function of ${ - classData.functions[0].pkgName.split("-")[1] - } + classData.functions[0].pkgName.split('-')[1] + } * @returns {Promise<${classData.functions[count].SDKFunctionName}Response>} `; - } + } - addMultiLineComment(node, comment); - count++; - } + addMultiLineComment(node, comment); + count++; + } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; - const result_1 = await runTransformation(code, addFunctions); - const result_2 = await runTransformation( - toSourceFile(result_1), - addIdentifiers - ); - const result_3 = await runTransformation(toSourceFile(result_2), addComments); - return result_3; + const result_1 = await runTransformation(code, addFunctions); + const result_2 = await runTransformation( + toSourceFile(result_1), + addIdentifiers + ); + const result_3 = await runTransformation( + toSourceFile(result_2), + addComments + ); + return result_3; } diff --git a/generator/transformers/do/transformer.js b/generator/transformers/do/transformer.js index 973c8664..30e4c2fb 100644 --- a/generator/transformers/do/transformer.js +++ b/generator/transformers/do/transformer.js @@ -1,212 +1,480 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; +'use strict'; +var __awaiter = + (this && this.__awaiter) || + function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator['throw'](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done + ? resolve(result.value) + : adopt(result.value).then(fulfilled, rejected); + } + step( + (generator = generator.apply(thisArg, _arguments || [])).next() + ); + }); + }; +var __generator = + (this && this.__generator) || + function(thisArg, body) { + var _ = { + label: 0, + sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [], + }, + f, + y, + t, + g; + return ( + (g = { next: verb(0), throw: verb(1), return: verb(2) }), + typeof Symbol === 'function' && + (g[Symbol.iterator] = function() { + return this; + }), + g + ); + function verb(n) { + return function(v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError('Generator is already executing.'); + while (_) + try { + if ( + ((f = 1), + y && + (t = + op[0] & 2 + ? y['return'] + : op[0] + ? y['throw'] || + ((t = y['return']) && t.call(y), 0) + : y.next) && + !(t = t.call(y, op[1])).done) + ) + return t; + if (((y = 0), t)) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if ( + !((t = _.trys), + (t = t.length > 0 && t[t.length - 1])) && + (op[0] === 6 || op[0] === 2) + ) { + _ = 0; + continue; + } + if ( + op[0] === 3 && + (!t || (op[1] > t[0] && op[1] < t[3])) + ) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } + }; exports.__esModule = true; exports.transform = void 0; -var lodash_1 = require("lodash"); -var ts = require("typescript"); +var lodash_1 = require('lodash'); +var ts = require('typescript'); var dummyIdentifiers = [ - "ClassName", - "_sdkClassName", - "SDKClassName", - "SDKFunctionName" + 'ClassName', + '_sdkClassName', + 'SDKClassName', + 'SDKFunctionName', ]; var printer = ts.createPrinter({ - newLine: ts.NewLineKind.LineFeed, - removeComments: false + newLine: ts.NewLineKind.LineFeed, + removeComments: false, }); function addMultiLineComment(node, comment) { - ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, comment, true); + ts.addSyntheticLeadingComment( + node, + ts.SyntaxKind.MultiLineCommentTrivia, + comment, + true + ); } function runTransformation(sourceCode, transformMethod) { - return new Promise(function (resolve, reject) { - try { - var result = ts.transform(sourceCode, [transformMethod]); - var transformedNodes = result.transformed[0]; - var output = printer.printNode(ts.EmitHint.SourceFile, transformedNodes, sourceCode); - resolve(output); - } - catch (error) { - reject(error); - } - }); + return new Promise(function(resolve, reject) { + try { + var result = ts.transform(sourceCode, [transformMethod]); + var transformedNodes = result.transformed[0]; + var output = printer.printNode( + ts.EmitHint.SourceFile, + transformedNodes, + sourceCode + ); + resolve(output); + } catch (error) { + reject(error); + } + }); } function toSourceFile(sourceCode) { - return ts.createSourceFile("dummyClass.js", sourceCode, ts.ScriptTarget.Latest, true); + return ts.createSourceFile( + 'dummyClass.js', + sourceCode, + ts.ScriptTarget.Latest, + true + ); } /* * The Transform function to be called from generator */ function transform(code, classData) { - return __awaiter(this, void 0, void 0, function () { - var addFunctions, addIdentifiers, addComments, node, result_1, result_2, result_3; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - addFunctions = function (context) { return function (rootNode) { - function visit(node) { - if (ts.isClassDeclaration(node)) { - var functions_1 = []; - classData.functions.map(function (method) { - var clonedNode = Object.assign({}, node.members[1]); - // console.log("Cloned Node..........\n");//sdadas - // console.log(clonedNode);//asdasdasdasd - clonedNode.name = ts.createIdentifier(method.functionName); - functions_1.push(clonedNode); - }); - var updatedClass = ts.updateClassDeclaration(node, node.decorators, node.modifiers, node.name, node.typeParameters, node.heritageClauses, ts.createNodeArray([node.members[0]].concat(functions_1))); - return updatedClass; - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; }; - addIdentifiers = function (context) { return function (rootNode) { - var count = 0; - function visit(node) { - if (ts.isMethodDeclaration(node)) { - var parameters = classData.functions[count].params.map(function (param) { - var paramNode = ts.createParameter(undefined, undefined, undefined, param.name); - if (param.optional) { - paramNode.initializer = ts.createIdentifier("undefined"); - } - return paramNode; - }); - node.parameters = parameters; - } - if (ts.isIdentifier(node) && dummyIdentifiers.includes(node.text)) { - var updatedIdentifier = void 0; - switch (node.text) { - case "ClassName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier("DO_" + classData.serviceName)); - break; - case "_sdkClassName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier("_" + - classData.className.charAt(0).toLowerCase() + - classData.className.substr(1))); - break; - case "SDKClassName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier(classData.className.charAt(0).toLowerCase() + - classData.className.substr(1))); - break; - case "SDKFunctionName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier(classData.functions[count].SDKFunctionName)); - count++; - } - return updatedIdentifier; - } - if (ts.isCallExpression(node)) { - node.expression.forEachChild(function (childNode) { - if (ts.isIdentifier(childNode) && - childNode.text === "SDKFunctionName") { - var args = classData.functions[count].params.map(function (param) { - return ts.createIdentifier(param.name); - }); - node.arguments = args.concat(node.arguments); - } - }); - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; }; - addComments = function (context) { return function (rootNode) { - var count = 0; - function visit(node) { - if (ts.isClassDeclaration(node)) { - addMultiLineComment(node, "This is an auto generated class, please do not change."); - var comment = "*\n* Class to create a " + classData.className + " object\n* @category Digital Ocean \n"; - addMultiLineComment(node, comment); - } - if (ts.isMethodDeclaration(node)) { - var parameters = classData.functions[count].params.map(function (param) { - var statment; - if (param.optional) { - if (param.type == "TypeReference") - statment = "* @param {" + param.typeName + "} " + param.name + " - Data required for " + classData.functions[count].SDKFunctionName; - else - statment = "* @param {" + param.type + "} " + param.name + " - Data required for " + classData.functions[count].SDKFunctionName; - } - else { - if (param.type == "TypeReference") - statment = "* @param {" + param.typeName + "} " + param.name + " - Data required for " + classData.functions[count].SDKFunctionName; - else - statment = "* @param {" + param.type + "} " + param.name + " - Data required for " + classData.functions[count].SDKFunctionName; - } - return statment; - }); - var comment = void 0; - if (parameters.length > 0) { - var paramStatments_1 = ""; - parameters.map(function (param) { - paramStatments_1 = paramStatments_1.concat(paramStatments_1 === "" ? "" + param : "\n" + param); - }); - comment = "*\n* Trigers the " + classData.functions[count].SDKFunctionName + " function of " + classData.className + "\n" + paramStatments_1 + "\n* @returns {Promise<" + classData.functions[count].SDKFunctionName + "Response>}\n"; - } - else { - comment = "*\n* Trigers the " + classData.functions[count].SDKFunctionName + " function of " + classData.className + "\n* @returns {Promise<" + classData.functions[count].SDKFunctionName + "Response>}\n"; - } - addMultiLineComment(node, comment); - count++; - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; }; - node = code.statements.find(function (stm) { return ts.isClassDeclaration(stm); }); - if (!classData.className || !classData.functions) { - throw new Error("Input is invalid"); - } - if (!node || !node.members.some(function (member) { return ts.isMethodDeclaration(member); })) { - throw new Error("Code is invalid"); - } - code = lodash_1.cloneDeep(code); - return [4 /*yield*/, runTransformation(code, addFunctions)]; - case 1: - result_1 = _a.sent(); - return [4 /*yield*/, runTransformation(toSourceFile(result_1), addIdentifiers)]; - case 2: - result_2 = _a.sent(); - return [4 /*yield*/, runTransformation(toSourceFile(result_2), addComments)]; - case 3: - result_3 = _a.sent(); - return [2 /*return*/, result_3]; - } - }); - }); + return __awaiter(this, void 0, void 0, function() { + var addFunctions, + addIdentifiers, + addComments, + node, + result_1, + result_2, + result_3; + return __generator(this, function(_a) { + switch (_a.label) { + case 0: + addFunctions = function(context) { + return function(rootNode) { + function visit(node) { + if (ts.isClassDeclaration(node)) { + var functions_1 = []; + classData.functions.map(function(method) { + var clonedNode = Object.assign( + {}, + node.members[1] + ); + // console.log("Cloned Node..........\n");//sdadas + // console.log(clonedNode);//asdasdasdasd + clonedNode.name = ts.createIdentifier( + method.functionName + ); + functions_1.push(clonedNode); + }); + var updatedClass = ts.updateClassDeclaration( + node, + node.decorators, + node.modifiers, + node.name, + node.typeParameters, + node.heritageClauses, + ts.createNodeArray( + [node.members[0]].concat( + functions_1 + ) + ) + ); + return updatedClass; + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + }; + addIdentifiers = function(context) { + return function(rootNode) { + var count = 0; + function visit(node) { + if (ts.isMethodDeclaration(node)) { + var parameters = classData.functions[ + count + ].params.map(function(param) { + var paramNode = ts.createParameter( + undefined, + undefined, + undefined, + param.name + ); + if (param.optional) { + paramNode.initializer = ts.createIdentifier( + 'undefined' + ); + } + return paramNode; + }); + node.parameters = parameters; + } + if ( + ts.isIdentifier(node) && + dummyIdentifiers.includes(node.text) + ) { + var updatedIdentifier = void 0; + switch (node.text) { + case 'ClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + 'DO_' + + classData.serviceName + ) + ); + break; + case '_sdkClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + '_' + + classData.className + .charAt(0) + .toLowerCase() + + classData.className.substr( + 1 + ) + ) + ); + break; + case 'SDKClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.className + .charAt(0) + .toLowerCase() + + classData.className.substr( + 1 + ) + ) + ); + break; + case 'SDKFunctionName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.functions[count] + .SDKFunctionName + ) + ); + count++; + } + return updatedIdentifier; + } + if (ts.isCallExpression(node)) { + node.expression.forEachChild(function( + childNode + ) { + if ( + ts.isIdentifier(childNode) && + childNode.text === 'SDKFunctionName' + ) { + var args = classData.functions[ + count + ].params.map(function(param) { + return ts.createIdentifier( + param.name + ); + }); + node.arguments = args.concat( + node.arguments + ); + } + }); + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + }; + addComments = function(context) { + return function(rootNode) { + var count = 0; + function visit(node) { + if (ts.isClassDeclaration(node)) { + addMultiLineComment( + node, + 'This is an auto generated class, please do not change.' + ); + var comment = + '*\n* Class to create a ' + + classData.className + + ' object\n* @category Digital Ocean \n'; + addMultiLineComment(node, comment); + } + if (ts.isMethodDeclaration(node)) { + var parameters = classData.functions[ + count + ].params.map(function(param) { + var statment; + if (param.optional) { + if (param.type == 'TypeReference') + statment = + '* @param {' + + param.typeName + + '} ' + + param.name + + ' - Data required for ' + + classData.functions[count] + .SDKFunctionName; + else + statment = + '* @param {' + + param.type + + '} ' + + param.name + + ' - Data required for ' + + classData.functions[count] + .SDKFunctionName; + } else { + if (param.type == 'TypeReference') + statment = + '* @param {' + + param.typeName + + '} ' + + param.name + + ' - Data required for ' + + classData.functions[count] + .SDKFunctionName; + else + statment = + '* @param {' + + param.type + + '} ' + + param.name + + ' - Data required for ' + + classData.functions[count] + .SDKFunctionName; + } + return statment; + }); + var comment = void 0; + if (parameters.length > 0) { + var paramStatments_1 = ''; + parameters.map(function(param) { + paramStatments_1 = paramStatments_1.concat( + paramStatments_1 === '' + ? '' + param + : '\n' + param + ); + }); + comment = + '*\n* Trigers the ' + + classData.functions[count] + .SDKFunctionName + + ' function of ' + + classData.className + + '\n' + + paramStatments_1 + + '\n* @returns {Promise<' + + classData.functions[count] + .SDKFunctionName + + 'Response>}\n'; + } else { + comment = + '*\n* Trigers the ' + + classData.functions[count] + .SDKFunctionName + + ' function of ' + + classData.className + + '\n* @returns {Promise<' + + classData.functions[count] + .SDKFunctionName + + 'Response>}\n'; + } + addMultiLineComment(node, comment); + count++; + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + }; + node = code.statements.find(function(stm) { + return ts.isClassDeclaration(stm); + }); + if (!classData.className || !classData.functions) { + throw new Error('Input is invalid'); + } + if ( + !node || + !node.members.some(function(member) { + return ts.isMethodDeclaration(member); + }) + ) { + throw new Error('Code is invalid'); + } + code = lodash_1.cloneDeep(code); + return [4 /*yield*/, runTransformation(code, addFunctions)]; + case 1: + result_1 = _a.sent(); + return [ + 4 /*yield*/, + runTransformation( + toSourceFile(result_1), + addIdentifiers + ), + ]; + case 2: + result_2 = _a.sent(); + return [ + 4 /*yield*/, + runTransformation(toSourceFile(result_2), addComments), + ]; + case 3: + result_3 = _a.sent(); + return [2 /*return*/, result_3]; + } + }); + }); } exports.transform = transform; diff --git a/generator/transformers/do/transformer.ts b/generator/transformers/do/transformer.ts index 93698e25..115ed946 100644 --- a/generator/transformers/do/transformer.ts +++ b/generator/transformers/do/transformer.ts @@ -1,51 +1,51 @@ -import { cloneDeep } from "lodash"; -import * as ts from "typescript"; +import { cloneDeep } from 'lodash'; +import * as ts from 'typescript'; const dummyIdentifiers = [ - "ClassName", - "_sdkClassName", - "SDKClassName", - "SDKFunctionName" + 'ClassName', + '_sdkClassName', + 'SDKClassName', + 'SDKFunctionName', ]; const printer: ts.Printer = ts.createPrinter({ - newLine: ts.NewLineKind.LineFeed, - removeComments: false + newLine: ts.NewLineKind.LineFeed, + removeComments: false, }); function addMultiLineComment(node, comment: string) { - ts.addSyntheticLeadingComment( - node, - ts.SyntaxKind.MultiLineCommentTrivia, - comment, - true - ); + ts.addSyntheticLeadingComment( + node, + ts.SyntaxKind.MultiLineCommentTrivia, + comment, + true + ); } function runTransformation(sourceCode, transformMethod): Promise { - return new Promise((resolve, reject) => { - try { - const result = ts.transform(sourceCode, [transformMethod]); - const transformedNodes = result.transformed[0]; - const output = printer.printNode( - ts.EmitHint.SourceFile, - transformedNodes, - sourceCode - ); - resolve(output); - } catch (error) { - reject(error); - } - }); + return new Promise((resolve, reject) => { + try { + const result = ts.transform(sourceCode, [transformMethod]); + const transformedNodes = result.transformed[0]; + const output = printer.printNode( + ts.EmitHint.SourceFile, + transformedNodes, + sourceCode + ); + resolve(output); + } catch (error) { + reject(error); + } + }); } function toSourceFile(sourceCode: string): ts.SourceFile { - return ts.createSourceFile( - "dummyClass.js", - sourceCode, - ts.ScriptTarget.Latest, - true - ); + return ts.createSourceFile( + 'dummyClass.js', + sourceCode, + ts.ScriptTarget.Latest, + true + ); } /* @@ -53,215 +53,228 @@ function toSourceFile(sourceCode: string): ts.SourceFile { */ export async function transform( - code: ts.SourceFile, - classData: any + code: ts.SourceFile, + classData: any ): Promise { - /* - * Transformation function for adding Functions - */ - const addFunctions = ( - context: ts.TransformationContext - ) => (rootNode: T) => { - function visit(node: ts.Node): ts.Node { - if (ts.isClassDeclaration(node)) { - const functions: any = []; - classData.functions.map(method => { - const clonedNode = Object.assign({}, node.members[1]); - // console.log("Cloned Node..........\n");//sdadas - // console.log(clonedNode);//asdasdasdasd - clonedNode.name = ts.createIdentifier(method.functionName); - functions.push(clonedNode); - }); - - const updatedClass = ts.updateClassDeclaration( - node, - node.decorators, - node.modifiers, - node.name, - node.typeParameters, - node.heritageClauses, - ts.createNodeArray([node.members[0]].concat(functions)) - ); - - return updatedClass; - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; - - /* - * Transformation function for adding Identifiers/Parameters - */ - const addIdentifiers = ( - context: ts.TransformationContext - ) => (rootNode: T) => { - let count = 0; - function visit(node: ts.Node): ts.Node { - if (ts.isMethodDeclaration(node)) { - const parameters = classData.functions[count].params.map(param => { - const paramNode = ts.createParameter( - undefined, - undefined, - undefined, - param.name - ); - - if (param.optional) { - paramNode.initializer = ts.createIdentifier("undefined"); - } - - return paramNode; - }); - - node.parameters = parameters; - } - - if (ts.isIdentifier(node) && dummyIdentifiers.includes(node.text)) { - let updatedIdentifier; - - switch (node.text) { - case "ClassName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier("DO_" + classData.serviceName) - ); - break; - case "_sdkClassName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier( - "_" + - classData.className.charAt(0).toLowerCase() + - classData.className.substr(1) - ) - ); - break; - case "SDKClassName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier( - classData.className.charAt(0).toLowerCase() + - classData.className.substr(1) - ) - ); - break; - case "SDKFunctionName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier(classData.functions[count].SDKFunctionName) - ); - count++; - } - - return updatedIdentifier; - } - - if (ts.isCallExpression(node)) { - node.expression.forEachChild(childNode => { - if ( - ts.isIdentifier(childNode) && - childNode.text === "SDKFunctionName" - ) { - const args = classData.functions[count].params.map(param => - ts.createIdentifier(param.name) - ); - node.arguments = args.concat(node.arguments); - } - }); - } - - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; - - /* - *Transformation function for adding comments - */ - - const addComments = ( - context: ts.TransformationContext - ) => (rootNode: T) => { - let count = 0; - - function visit(node: ts.Node): ts.Node { - if (ts.isClassDeclaration(node)) { - addMultiLineComment( - node, - "This is an auto generated class, please do not change." - ); - const comment = `* + /* + * Transformation function for adding Functions + */ + const addFunctions = ( + context: ts.TransformationContext + ) => (rootNode: T) => { + function visit(node: ts.Node): ts.Node { + if (ts.isClassDeclaration(node)) { + const functions: any = []; + classData.functions.map(method => { + const clonedNode = Object.assign({}, node.members[1]); + // console.log("Cloned Node..........\n");//sdadas + // console.log(clonedNode);//asdasdasdasd + clonedNode.name = ts.createIdentifier(method.functionName); + functions.push(clonedNode); + }); + + const updatedClass = ts.updateClassDeclaration( + node, + node.decorators, + node.modifiers, + node.name, + node.typeParameters, + node.heritageClauses, + ts.createNodeArray([node.members[0]].concat(functions)) + ); + + return updatedClass; + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + + /* + * Transformation function for adding Identifiers/Parameters + */ + const addIdentifiers = ( + context: ts.TransformationContext + ) => (rootNode: T) => { + let count = 0; + function visit(node: ts.Node): ts.Node { + if (ts.isMethodDeclaration(node)) { + const parameters = classData.functions[count].params.map( + param => { + const paramNode = ts.createParameter( + undefined, + undefined, + undefined, + param.name + ); + + if (param.optional) { + paramNode.initializer = ts.createIdentifier( + 'undefined' + ); + } + + return paramNode; + } + ); + + node.parameters = parameters; + } + + if (ts.isIdentifier(node) && dummyIdentifiers.includes(node.text)) { + let updatedIdentifier; + + switch (node.text) { + case 'ClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier('DO_' + classData.serviceName) + ); + break; + case '_sdkClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + '_' + + classData.className + .charAt(0) + .toLowerCase() + + classData.className.substr(1) + ) + ); + break; + case 'SDKClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.className.charAt(0).toLowerCase() + + classData.className.substr(1) + ) + ); + break; + case 'SDKFunctionName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.functions[count].SDKFunctionName + ) + ); + count++; + } + + return updatedIdentifier; + } + + if (ts.isCallExpression(node)) { + node.expression.forEachChild(childNode => { + if ( + ts.isIdentifier(childNode) && + childNode.text === 'SDKFunctionName' + ) { + const args = classData.functions[count].params.map( + param => ts.createIdentifier(param.name) + ); + node.arguments = args.concat(node.arguments); + } + }); + } + + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + + /* + *Transformation function for adding comments + */ + + const addComments = ( + context: ts.TransformationContext + ) => (rootNode: T) => { + let count = 0; + + function visit(node: ts.Node): ts.Node { + if (ts.isClassDeclaration(node)) { + addMultiLineComment( + node, + 'This is an auto generated class, please do not change.' + ); + const comment = `* * Class to create a ${classData.className} object * @category Digital Ocean `; - addMultiLineComment(node, comment); - } - - if (ts.isMethodDeclaration(node)) { - const parameters = classData.functions[count].params.map(param => { - let statment; - - if (param.optional) { - if (param.type == "TypeReference") - statment = `* @param {${param.typeName}} ${param.name} - Data required for ${classData.functions[count].SDKFunctionName}`; - else - statment = `* @param {${param.type}} ${param.name} - Data required for ${classData.functions[count].SDKFunctionName}`; - } else { - if (param.type == "TypeReference") - statment = `* @param {${param.typeName}} ${param.name} - Data required for ${classData.functions[count].SDKFunctionName}`; - else - statment = `* @param {${param.type}} ${param.name} - Data required for ${classData.functions[count].SDKFunctionName}`; - } - return statment; - }); - - let comment; - if (parameters.length > 0) { - let paramStatments: string = ""; - parameters.map(param => { - paramStatments = paramStatments.concat( - paramStatments === "" ? `${param}` : `\n${param}` - ); - }); - - comment = `* + addMultiLineComment(node, comment); + } + + if (ts.isMethodDeclaration(node)) { + const parameters = classData.functions[count].params.map( + param => { + let statment; + + if (param.optional) { + if (param.type == 'TypeReference') + statment = `* @param {${param.typeName}} ${param.name} - Data required for ${classData.functions[count].SDKFunctionName}`; + else + statment = `* @param {${param.type}} ${param.name} - Data required for ${classData.functions[count].SDKFunctionName}`; + } else { + if (param.type == 'TypeReference') + statment = `* @param {${param.typeName}} ${param.name} - Data required for ${classData.functions[count].SDKFunctionName}`; + else + statment = `* @param {${param.type}} ${param.name} - Data required for ${classData.functions[count].SDKFunctionName}`; + } + return statment; + } + ); + + let comment; + if (parameters.length > 0) { + let paramStatments: string = ''; + parameters.map(param => { + paramStatments = paramStatments.concat( + paramStatments === '' ? `${param}` : `\n${param}` + ); + }); + + comment = `* * Trigers the ${classData.functions[count].SDKFunctionName} function of ${classData.className} ${paramStatments} * @returns {Promise<${classData.functions[count].SDKFunctionName}Response>} `; - } else { - comment = `* + } else { + comment = `* * Trigers the ${classData.functions[count].SDKFunctionName} function of ${classData.className} * @returns {Promise<${classData.functions[count].SDKFunctionName}Response>} `; - } - - addMultiLineComment(node, comment); - count++; - } - - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; - - /* - * Code to get node and run tranformations - */ - const node: any = code.statements.find(stm => ts.isClassDeclaration(stm)); - - if (!classData.className || !classData.functions) { - throw new Error("Input is invalid"); - } - - if (!node || !node.members.some(member => ts.isMethodDeclaration(member))) { - throw new Error("Code is invalid"); - } - - code = cloneDeep(code); - - const result_1 = await runTransformation(code, addFunctions); - const result_2 = await runTransformation( - toSourceFile(result_1), - addIdentifiers - ); - const result_3 = await runTransformation(toSourceFile(result_2), addComments); - return result_3; + } + + addMultiLineComment(node, comment); + count++; + } + + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + + /* + * Code to get node and run tranformations + */ + const node: any = code.statements.find(stm => ts.isClassDeclaration(stm)); + + if (!classData.className || !classData.functions) { + throw new Error('Input is invalid'); + } + + if (!node || !node.members.some(member => ts.isMethodDeclaration(member))) { + throw new Error('Code is invalid'); + } + + code = cloneDeep(code); + + const result_1 = await runTransformation(code, addFunctions); + const result_2 = await runTransformation( + toSourceFile(result_1), + addIdentifiers + ); + const result_3 = await runTransformation( + toSourceFile(result_2), + addComments + ); + return result_3; } diff --git a/generator/transformers/googleCloud/classBasedTransformer.js b/generator/transformers/googleCloud/classBasedTransformer.js index f9c776ae..48c30b18 100644 --- a/generator/transformers/googleCloud/classBasedTransformer.js +++ b/generator/transformers/googleCloud/classBasedTransformer.js @@ -1,249 +1,553 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; +'use strict'; +var __awaiter = + (this && this.__awaiter) || + function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator['throw'](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done + ? resolve(result.value) + : adopt(result.value).then(fulfilled, rejected); + } + step( + (generator = generator.apply(thisArg, _arguments || [])).next() + ); + }); + }; +var __generator = + (this && this.__generator) || + function(thisArg, body) { + var _ = { + label: 0, + sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [], + }, + f, + y, + t, + g; + return ( + (g = { next: verb(0), throw: verb(1), return: verb(2) }), + typeof Symbol === 'function' && + (g[Symbol.iterator] = function() { + return this; + }), + g + ); + function verb(n) { + return function(v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError('Generator is already executing.'); + while (_) + try { + if ( + ((f = 1), + y && + (t = + op[0] & 2 + ? y['return'] + : op[0] + ? y['throw'] || + ((t = y['return']) && t.call(y), 0) + : y.next) && + !(t = t.call(y, op[1])).done) + ) + return t; + if (((y = 0), t)) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if ( + !((t = _.trys), + (t = t.length > 0 && t[t.length - 1])) && + (op[0] === 6 || op[0] === 2) + ) { + _ = 0; + continue; + } + if ( + op[0] === 3 && + (!t || (op[1] > t[0] && op[1] < t[3])) + ) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } + }; exports.__esModule = true; exports.classBasedTransform = void 0; -var lodash_1 = require("lodash"); -var ts = require("typescript"); +var lodash_1 = require('lodash'); +var ts = require('typescript'); var dummyIdentifiers = [ - "ClassName", - "SDKFunctionName", - "ClientName", - "_client", - "_clientObj", - "Client", - "_className" + 'ClassName', + 'SDKFunctionName', + 'ClientName', + '_client', + '_clientObj', + 'Client', + '_className', ]; var printer = ts.createPrinter({ - newLine: ts.NewLineKind.LineFeed, - removeComments: false + newLine: ts.NewLineKind.LineFeed, + removeComments: false, }); function addMultiLineComment(node, comment) { - ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, comment, true); + ts.addSyntheticLeadingComment( + node, + ts.SyntaxKind.MultiLineCommentTrivia, + comment, + true + ); } function runTransformation(sourceCode, transformMethod) { - return new Promise(function (resolve, reject) { - try { - var result = ts.transform(sourceCode, [transformMethod]); - var transformedNodes = result.transformed[0]; - var output = printer.printNode(ts.EmitHint.SourceFile, transformedNodes, sourceCode); - resolve(output); - } - catch (error) { - reject(error); - } - }); + return new Promise(function(resolve, reject) { + try { + var result = ts.transform(sourceCode, [transformMethod]); + var transformedNodes = result.transformed[0]; + var output = printer.printNode( + ts.EmitHint.SourceFile, + transformedNodes, + sourceCode + ); + resolve(output); + } catch (error) { + reject(error); + } + }); } function toSourceFile(sourceCode) { - return ts.createSourceFile("dummyClass.js", sourceCode, ts.ScriptTarget.Latest, true); + return ts.createSourceFile( + 'dummyClass.js', + sourceCode, + ts.ScriptTarget.Latest, + true + ); } function classBasedTransform(code, data) { - return __awaiter(this, void 0, void 0, function () { - var node, addFunctions, addIdentifiers, addComments, result_1, result_2, result_3; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - node = code.statements.find(function (stm) { return ts.isClassDeclaration(stm); }); - if (!data.functions || !data.classData) { - throw new Error("Input is invalid"); - } - if (!node || !node.members.some(function (member) { return ts.isMethodDeclaration(member); })) { - throw new Error("Code is invalid"); - } - code = lodash_1.cloneDeep(code); - addFunctions = function (context) { return function (rootNode) { - function visit(node) { - if (ts.isClassDeclaration(node)) { - var functions_1 = []; - data.functions.map(function (method) { - var clonedNode; - if (method.returnTypeName === "Promise") { - if ((method.classConstructorData.parameters[0].type = - "TypeReference" && - !method.classConstructorData.parameters[0].optional)) { - clonedNode = Object.assign({}, node.members[3]); - } - else { - clonedNode = Object.assign({}, node.members[1]); - } - } - else { - clonedNode = Object.assign({}, node.members[2]); - } - clonedNode.name = ts.createIdentifier(method.functionName); - functions_1.push(clonedNode); - }); - var updatedClass = ts.updateClassDeclaration(node, node.decorators, node.modifiers, node.name, node.typeParameters, node.heritageClauses, ts.createNodeArray([node.members[0]].concat(functions_1))); - return updatedClass; - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; }; - addIdentifiers = function (context) { return function (rootNode) { - var count = 0; - function visit(node) { - if (ts.isMethodDeclaration(node)) { - data.functions[count].allParams = []; - var params = []; - if ((data.functions[count].classConstructorData.parameters[0].type = - "TypeReference" && - !data.functions[count].classConstructorData.parameters[0].optional)) { - params.push(data.functions[count].classConstructorData.parameters[0]); - data.functions[count].allParams.push({ - name: "identifier", - optional: true, - type: "string" - }); - } - params = params.concat(data.functions[count].params); - data.functions[count].allParams = data.functions[count].allParams.concat(params); - var parameters = params.map(function (param) { - var paramNode = ts.createParameter(undefined, undefined, undefined, param.name); - if (param.optional) { - paramNode.initializer = ts.createIdentifier("undefined"); - } - return paramNode; - }); - node.parameters = parameters.concat(node.parameters); - } - if (ts.isStringLiteral(node) && node.text === "pkgName") { - return ts.createStringLiteral("@google-cloud/" + data.functions[0].pkgName); - } - if (ts.isIdentifier(node) && dummyIdentifiers.includes(node.text)) { - var updatedIdentifier = void 0; - switch (node.text) { - case "ClassName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier("GCP_" + data.functions[0].pkgName)); - break; - case "ClientName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier(data.mainClass)); - break; - case "SDKFunctionName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier(data.functions[count].SDKFunctionName)); - count++; - break; - case "_className": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier(data.functions[count].client.toLowerCase())); - break; - case "_client": - if ((data.functions[count].classConstructorData.parameters[0].type = - "TypeReference" && - !data.functions[count].classConstructorData.parameters[0] - .optional)) { - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier(data.functions[count].classConstructorData.parameters[0].name)); - } - else { - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier("_" + data.mainClass.toLowerCase())); - } - break; - case "_clientObj": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier("_" + data.mainClass.toLowerCase())); - break; - case "Client": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier(data.mainClass)); - break; - } - return updatedIdentifier; - } - if (ts.isCallExpression(node)) { - node.expression.forEachChild(function (childNode) { - if (ts.isIdentifier(childNode) && - childNode.text === "SDKFunctionName") { - var args = data.functions[count].params.map(function (param) { - return ts.createIdentifier(param.name); - }); - node.arguments = args; - } - }); - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; }; - addComments = function (context) { return function (rootNode) { - var count = 0; - function visit(node) { - if (ts.isClassDeclaration(node)) { - addMultiLineComment(node, "This is an auto generated class, please do not change."); - var comment = "*\n * Class to create a " + data.functions[0].pkgName + " object\n * @category Google Cloud\n "; - addMultiLineComment(node, comment); - } - if (ts.isMethodDeclaration(node)) { - var parameters = data.functions[count].allParams.map(function (param) { - var statment; - if (param.optional) { - statment = "* @param {" + (param.typeRefName ? param.typeRefName : param.type) + "} [" + param.name + "] - Optional parameter"; - } - else { - statment = "* @param {" + (param.typeRefName ? param.typeRefName : param.type) + "} " + param.name + " - Mandatory parameter"; - } - return statment; - }); - var comment = void 0; - if (parameters.length > 0) { - var paramStatments_1 = ""; - parameters.map(function (param) { - paramStatments_1 = paramStatments_1.concat(paramStatments_1 === "" ? "" + param : "\n " + param); - }); - comment = "*\n * Trigers the " + data.functions[count].SDKFunctionName + " function of " + data.functions[0].pkgName + "\n " + paramStatments_1 + "\n * @returns {Promise<" + data.functions[count].SDKFunctionName + "Response>}\n "; - } - else { - comment = "*\n * Trigers the " + data.functions[count].SDKFunctionName + " function of " + data.functions[0].pkgName + "\n * @returns {Promise<" + data.functions[count].SDKFunctionName + "Response>}\n "; - } - addMultiLineComment(node, comment); - count++; - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; }; - return [4 /*yield*/, runTransformation(code, addFunctions)]; - case 1: - result_1 = _a.sent(); - return [4 /*yield*/, runTransformation(toSourceFile(result_1), addIdentifiers)]; - case 2: - result_2 = _a.sent(); - return [4 /*yield*/, runTransformation(toSourceFile(result_2), addComments)]; - case 3: - result_3 = _a.sent(); - return [2 /*return*/, result_3]; - } - }); - }); + return __awaiter(this, void 0, void 0, function() { + var node, + addFunctions, + addIdentifiers, + addComments, + result_1, + result_2, + result_3; + return __generator(this, function(_a) { + switch (_a.label) { + case 0: + node = code.statements.find(function(stm) { + return ts.isClassDeclaration(stm); + }); + if (!data.functions || !data.classData) { + throw new Error('Input is invalid'); + } + if ( + !node || + !node.members.some(function(member) { + return ts.isMethodDeclaration(member); + }) + ) { + throw new Error('Code is invalid'); + } + code = lodash_1.cloneDeep(code); + addFunctions = function(context) { + return function(rootNode) { + function visit(node) { + if (ts.isClassDeclaration(node)) { + var functions_1 = []; + data.functions.map(function(method) { + var clonedNode; + if ( + method.returnTypeName === 'Promise' + ) { + if ( + (method.classConstructorData.parameters[0].type = + 'TypeReference' && + !method.classConstructorData + .parameters[0].optional) + ) { + clonedNode = Object.assign( + {}, + node.members[3] + ); + } else { + clonedNode = Object.assign( + {}, + node.members[1] + ); + } + } else { + clonedNode = Object.assign( + {}, + node.members[2] + ); + } + clonedNode.name = ts.createIdentifier( + method.functionName + ); + functions_1.push(clonedNode); + }); + var updatedClass = ts.updateClassDeclaration( + node, + node.decorators, + node.modifiers, + node.name, + node.typeParameters, + node.heritageClauses, + ts.createNodeArray( + [node.members[0]].concat( + functions_1 + ) + ) + ); + return updatedClass; + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + }; + addIdentifiers = function(context) { + return function(rootNode) { + var count = 0; + function visit(node) { + if (ts.isMethodDeclaration(node)) { + data.functions[count].allParams = []; + var params = []; + if ( + (data.functions[ + count + ].classConstructorData.parameters[0].type = + 'TypeReference' && + !data.functions[count] + .classConstructorData + .parameters[0].optional) + ) { + params.push( + data.functions[count] + .classConstructorData + .parameters[0] + ); + data.functions[count].allParams.push({ + name: 'identifier', + optional: true, + type: 'string', + }); + } + params = params.concat( + data.functions[count].params + ); + data.functions[ + count + ].allParams = data.functions[ + count + ].allParams.concat(params); + var parameters = params.map(function( + param + ) { + var paramNode = ts.createParameter( + undefined, + undefined, + undefined, + param.name + ); + if (param.optional) { + paramNode.initializer = ts.createIdentifier( + 'undefined' + ); + } + return paramNode; + }); + node.parameters = parameters.concat( + node.parameters + ); + } + if ( + ts.isStringLiteral(node) && + node.text === 'pkgName' + ) { + return ts.createStringLiteral( + '@google-cloud/' + + data.functions[0].pkgName + ); + } + if ( + ts.isIdentifier(node) && + dummyIdentifiers.includes(node.text) + ) { + var updatedIdentifier = void 0; + switch (node.text) { + case 'ClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + 'GCP_' + + data.functions[0] + .pkgName + ) + ); + break; + case 'ClientName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + data.mainClass + ) + ); + break; + case 'SDKFunctionName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + data.functions[count] + .SDKFunctionName + ) + ); + count++; + break; + case '_className': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + data.functions[ + count + ].client.toLowerCase() + ) + ); + break; + case '_client': + if ( + (data.functions[ + count + ].classConstructorData.parameters[0].type = + 'TypeReference' && + !data.functions[count] + .classConstructorData + .parameters[0].optional) + ) { + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + data.functions[count] + .classConstructorData + .parameters[0].name + ) + ); + } else { + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + '_' + + data.mainClass.toLowerCase() + ) + ); + } + break; + case '_clientObj': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + '_' + + data.mainClass.toLowerCase() + ) + ); + break; + case 'Client': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + data.mainClass + ) + ); + break; + } + return updatedIdentifier; + } + if (ts.isCallExpression(node)) { + node.expression.forEachChild(function( + childNode + ) { + if ( + ts.isIdentifier(childNode) && + childNode.text === 'SDKFunctionName' + ) { + var args = data.functions[ + count + ].params.map(function(param) { + return ts.createIdentifier( + param.name + ); + }); + node.arguments = args; + } + }); + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + }; + addComments = function(context) { + return function(rootNode) { + var count = 0; + function visit(node) { + if (ts.isClassDeclaration(node)) { + addMultiLineComment( + node, + 'This is an auto generated class, please do not change.' + ); + var comment = + '*\n * Class to create a ' + + data.functions[0].pkgName + + ' object\n * @category Google Cloud\n '; + addMultiLineComment(node, comment); + } + if (ts.isMethodDeclaration(node)) { + var parameters = data.functions[ + count + ].allParams.map(function(param) { + var statment; + if (param.optional) { + statment = + '* @param {' + + (param.typeRefName + ? param.typeRefName + : param.type) + + '} [' + + param.name + + '] - Optional parameter'; + } else { + statment = + '* @param {' + + (param.typeRefName + ? param.typeRefName + : param.type) + + '} ' + + param.name + + ' - Mandatory parameter'; + } + return statment; + }); + var comment = void 0; + if (parameters.length > 0) { + var paramStatments_1 = ''; + parameters.map(function(param) { + paramStatments_1 = paramStatments_1.concat( + paramStatments_1 === '' + ? '' + param + : '\n ' + param + ); + }); + comment = + '*\n * Trigers the ' + + data.functions[count] + .SDKFunctionName + + ' function of ' + + data.functions[0].pkgName + + '\n ' + + paramStatments_1 + + '\n * @returns {Promise<' + + data.functions[count] + .SDKFunctionName + + 'Response>}\n '; + } else { + comment = + '*\n * Trigers the ' + + data.functions[count] + .SDKFunctionName + + ' function of ' + + data.functions[0].pkgName + + '\n * @returns {Promise<' + + data.functions[count] + .SDKFunctionName + + 'Response>}\n '; + } + addMultiLineComment(node, comment); + count++; + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + }; + return [4 /*yield*/, runTransformation(code, addFunctions)]; + case 1: + result_1 = _a.sent(); + return [ + 4 /*yield*/, + runTransformation( + toSourceFile(result_1), + addIdentifiers + ), + ]; + case 2: + result_2 = _a.sent(); + return [ + 4 /*yield*/, + runTransformation(toSourceFile(result_2), addComments), + ]; + case 3: + result_3 = _a.sent(); + return [2 /*return*/, result_3]; + } + }); + }); } exports.classBasedTransform = classBasedTransform; diff --git a/generator/transformers/googleCloud/classBasedTransformer.ts b/generator/transformers/googleCloud/classBasedTransformer.ts index b6290fda..06f0f729 100644 --- a/generator/transformers/googleCloud/classBasedTransformer.ts +++ b/generator/transformers/googleCloud/classBasedTransformer.ts @@ -1,310 +1,340 @@ -import { cloneDeep } from "lodash"; -import * as ts from "typescript"; +import { cloneDeep } from 'lodash'; +import * as ts from 'typescript'; const dummyIdentifiers = [ - "ClassName", - "SDKFunctionName", - "ClientName", - "_client", - "_clientObj", - "Client", - "_className" + 'ClassName', + 'SDKFunctionName', + 'ClientName', + '_client', + '_clientObj', + 'Client', + '_className', ]; const printer: ts.Printer = ts.createPrinter({ - newLine: ts.NewLineKind.LineFeed, - removeComments: false + newLine: ts.NewLineKind.LineFeed, + removeComments: false, }); function addMultiLineComment(node, comment: string) { - ts.addSyntheticLeadingComment( - node, - ts.SyntaxKind.MultiLineCommentTrivia, - comment, - true - ); + ts.addSyntheticLeadingComment( + node, + ts.SyntaxKind.MultiLineCommentTrivia, + comment, + true + ); } function runTransformation(sourceCode, transformMethod): Promise { - return new Promise((resolve, reject) => { - try { - const result = ts.transform(sourceCode, [transformMethod]); - const transformedNodes = result.transformed[0]; - const output = printer.printNode( - ts.EmitHint.SourceFile, - transformedNodes, - sourceCode - ); - resolve(output); - } catch (error) { - reject(error); - } - }); + return new Promise((resolve, reject) => { + try { + const result = ts.transform(sourceCode, [transformMethod]); + const transformedNodes = result.transformed[0]; + const output = printer.printNode( + ts.EmitHint.SourceFile, + transformedNodes, + sourceCode + ); + resolve(output); + } catch (error) { + reject(error); + } + }); } function toSourceFile(sourceCode: string): ts.SourceFile { - return ts.createSourceFile( - "dummyClass.js", - sourceCode, - ts.ScriptTarget.Latest, - true - ); + return ts.createSourceFile( + 'dummyClass.js', + sourceCode, + ts.ScriptTarget.Latest, + true + ); } export async function classBasedTransform( - code: ts.SourceFile, - data: any + code: ts.SourceFile, + data: any ): Promise { - const node: any = code.statements.find(stm => ts.isClassDeclaration(stm)); - - if (!data.functions || !data.classData) { - throw new Error("Input is invalid"); - } - - if (!node || !node.members.some(member => ts.isMethodDeclaration(member))) { - throw new Error("Code is invalid"); - } - - code = cloneDeep(code); - - const addFunctions = ( - context: ts.TransformationContext - ) => (rootNode: T) => { - function visit(node: ts.Node): ts.Node { - if (ts.isClassDeclaration(node)) { - const functions: any = []; - data.functions.map(method => { - let clonedNode; - if (method.returnTypeName === "Promise") { - if ( - (method.classConstructorData.parameters[0].type = - "TypeReference" && - !method.classConstructorData.parameters[0].optional) - ) { - clonedNode = Object.assign({}, node.members[3]); - } else { - clonedNode = Object.assign({}, node.members[1]); - } - } else { - clonedNode = Object.assign({}, node.members[2]); - } - clonedNode.name = ts.createIdentifier(method.functionName); - functions.push(clonedNode); - }); - - const updatedClass = ts.updateClassDeclaration( - node, - node.decorators, - node.modifiers, - node.name, - node.typeParameters, - node.heritageClauses, - ts.createNodeArray([node.members[0]].concat(functions)) - ); - - return updatedClass; - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; - - const addIdentifiers = ( - context: ts.TransformationContext - ) => (rootNode: T) => { - let count = 0; - function visit(node: ts.Node): ts.Node { - if (ts.isMethodDeclaration(node)) { - data.functions[count].allParams = []; - - let params = []; - if ( - (data.functions[count].classConstructorData.parameters[0].type = - "TypeReference" && - !data.functions[count].classConstructorData.parameters[0].optional) - ) { - params.push(data.functions[count].classConstructorData.parameters[0]); - - data.functions[count].allParams.push({ - name: "identifier", - optional: true, - type: "string" - }); - } - - params = params.concat(data.functions[count].params); - data.functions[count].allParams = data.functions[ - count - ].allParams.concat(params); - - const parameters: any = params.map(param => { - const paramNode = ts.createParameter( - undefined, - undefined, - undefined, - param.name - ); - - if (param.optional) { - paramNode.initializer = ts.createIdentifier("undefined"); - } - - return paramNode; - }); - - node.parameters = parameters.concat(node.parameters); - } - - if (ts.isStringLiteral(node) && node.text === "pkgName") { - return ts.createStringLiteral( - "@google-cloud/" + data.functions[0].pkgName - ); - } - - if (ts.isIdentifier(node) && dummyIdentifiers.includes(node.text)) { - let updatedIdentifier; - switch (node.text) { - case "ClassName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier("GCP_" + data.functions[0].pkgName) - ); - break; - case "ClientName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier(data.mainClass) - ); - break; - case "SDKFunctionName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier(data.functions[count].SDKFunctionName) - ); - count++; - break; - case "_className": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier(data.functions[count].client.toLowerCase()) - ); - break; - case "_client": - if ( - (data.functions[count].classConstructorData.parameters[0].type = - "TypeReference" && - !data.functions[count].classConstructorData.parameters[0] - .optional) - ) { - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier( - data.functions[count].classConstructorData.parameters[0].name - ) - ); - } else { - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier("_" + data.mainClass.toLowerCase()) - ); - } - break; - case "_clientObj": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier("_" + data.mainClass.toLowerCase()) - ); - break; - case "Client": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier(data.mainClass) - ); - break; - } - return updatedIdentifier; - } - - if (ts.isCallExpression(node)) { - node.expression.forEachChild(childNode => { - if ( - ts.isIdentifier(childNode) && - childNode.text === "SDKFunctionName" - ) { - const args = data.functions[count].params.map(param => - ts.createIdentifier(param.name) - ); - node.arguments = args; - } - }); - } - - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; - - const addComments = ( - context: ts.TransformationContext - ) => (rootNode: T) => { - let count = 0; - - function visit(node: ts.Node): ts.Node { - if (ts.isClassDeclaration(node)) { - addMultiLineComment( - node, - "This is an auto generated class, please do not change." - ); - const comment = `* + const node: any = code.statements.find(stm => ts.isClassDeclaration(stm)); + + if (!data.functions || !data.classData) { + throw new Error('Input is invalid'); + } + + if (!node || !node.members.some(member => ts.isMethodDeclaration(member))) { + throw new Error('Code is invalid'); + } + + code = cloneDeep(code); + + const addFunctions = ( + context: ts.TransformationContext + ) => (rootNode: T) => { + function visit(node: ts.Node): ts.Node { + if (ts.isClassDeclaration(node)) { + const functions: any = []; + data.functions.map(method => { + let clonedNode; + if (method.returnTypeName === 'Promise') { + if ( + (method.classConstructorData.parameters[0].type = + 'TypeReference' && + !method.classConstructorData.parameters[0] + .optional) + ) { + clonedNode = Object.assign({}, node.members[3]); + } else { + clonedNode = Object.assign({}, node.members[1]); + } + } else { + clonedNode = Object.assign({}, node.members[2]); + } + clonedNode.name = ts.createIdentifier(method.functionName); + functions.push(clonedNode); + }); + + const updatedClass = ts.updateClassDeclaration( + node, + node.decorators, + node.modifiers, + node.name, + node.typeParameters, + node.heritageClauses, + ts.createNodeArray([node.members[0]].concat(functions)) + ); + + return updatedClass; + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + + const addIdentifiers = ( + context: ts.TransformationContext + ) => (rootNode: T) => { + let count = 0; + function visit(node: ts.Node): ts.Node { + if (ts.isMethodDeclaration(node)) { + data.functions[count].allParams = []; + + let params = []; + if ( + (data.functions[ + count + ].classConstructorData.parameters[0].type = + 'TypeReference' && + !data.functions[count].classConstructorData + .parameters[0].optional) + ) { + params.push( + data.functions[count].classConstructorData.parameters[0] + ); + + data.functions[count].allParams.push({ + name: 'identifier', + optional: true, + type: 'string', + }); + } + + params = params.concat(data.functions[count].params); + data.functions[count].allParams = data.functions[ + count + ].allParams.concat(params); + + const parameters: any = params.map(param => { + const paramNode = ts.createParameter( + undefined, + undefined, + undefined, + param.name + ); + + if (param.optional) { + paramNode.initializer = ts.createIdentifier( + 'undefined' + ); + } + + return paramNode; + }); + + node.parameters = parameters.concat(node.parameters); + } + + if (ts.isStringLiteral(node) && node.text === 'pkgName') { + return ts.createStringLiteral( + '@google-cloud/' + data.functions[0].pkgName + ); + } + + if (ts.isIdentifier(node) && dummyIdentifiers.includes(node.text)) { + let updatedIdentifier; + switch (node.text) { + case 'ClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + 'GCP_' + data.functions[0].pkgName + ) + ); + break; + case 'ClientName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier(data.mainClass) + ); + break; + case 'SDKFunctionName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + data.functions[count].SDKFunctionName + ) + ); + count++; + break; + case '_className': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + data.functions[count].client.toLowerCase() + ) + ); + break; + case '_client': + if ( + (data.functions[ + count + ].classConstructorData.parameters[0].type = + 'TypeReference' && + !data.functions[count].classConstructorData + .parameters[0].optional) + ) { + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + data.functions[count].classConstructorData + .parameters[0].name + ) + ); + } else { + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + '_' + data.mainClass.toLowerCase() + ) + ); + } + break; + case '_clientObj': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + '_' + data.mainClass.toLowerCase() + ) + ); + break; + case 'Client': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier(data.mainClass) + ); + break; + } + return updatedIdentifier; + } + + if (ts.isCallExpression(node)) { + node.expression.forEachChild(childNode => { + if ( + ts.isIdentifier(childNode) && + childNode.text === 'SDKFunctionName' + ) { + const args = data.functions[count].params.map(param => + ts.createIdentifier(param.name) + ); + node.arguments = args; + } + }); + } + + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + + const addComments = ( + context: ts.TransformationContext + ) => (rootNode: T) => { + let count = 0; + + function visit(node: ts.Node): ts.Node { + if (ts.isClassDeclaration(node)) { + addMultiLineComment( + node, + 'This is an auto generated class, please do not change.' + ); + const comment = `* * Class to create a ${data.functions[0].pkgName} object * @category Google Cloud `; - addMultiLineComment(node, comment); - } - - if (ts.isMethodDeclaration(node)) { - const parameters = data.functions[count].allParams.map(param => { - let statment; - - if (param.optional) { - statment = `* @param {${ - param.typeRefName ? param.typeRefName : param.type - }} [${param.name}] - Optional parameter`; - } else { - statment = `* @param {${ - param.typeRefName ? param.typeRefName : param.type - }} ${param.name} - Mandatory parameter`; - } - return statment; - }); - - let comment; - if (parameters.length > 0) { - let paramStatments: string = ""; - parameters.map(param => { - paramStatments = paramStatments.concat( - paramStatments === "" ? `${param}` : `\n ${param}` - ); - }); - - comment = `* + addMultiLineComment(node, comment); + } + + if (ts.isMethodDeclaration(node)) { + const parameters = data.functions[count].allParams.map( + param => { + let statment; + + if (param.optional) { + statment = `* @param {${ + param.typeRefName + ? param.typeRefName + : param.type + }} [${param.name}] - Optional parameter`; + } else { + statment = `* @param {${ + param.typeRefName + ? param.typeRefName + : param.type + }} ${param.name} - Mandatory parameter`; + } + return statment; + } + ); + + let comment; + if (parameters.length > 0) { + let paramStatments: string = ''; + parameters.map(param => { + paramStatments = paramStatments.concat( + paramStatments === '' ? `${param}` : `\n ${param}` + ); + }); + + comment = `* * Trigers the ${data.functions[count].SDKFunctionName} function of ${data.functions[0].pkgName} ${paramStatments} * @returns {Promise<${data.functions[count].SDKFunctionName}Response>} `; - } else { - comment = `* + } else { + comment = `* * Trigers the ${data.functions[count].SDKFunctionName} function of ${data.functions[0].pkgName} * @returns {Promise<${data.functions[count].SDKFunctionName}Response>} `; - } - - addMultiLineComment(node, comment); - count++; - } - - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; - - const result_1 = await runTransformation(code, addFunctions); - const result_2 = await runTransformation( - toSourceFile(result_1), - addIdentifiers - ); - const result_3 = await runTransformation(toSourceFile(result_2), addComments); - return result_3; + } + + addMultiLineComment(node, comment); + count++; + } + + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + + const result_1 = await runTransformation(code, addFunctions); + const result_2 = await runTransformation( + toSourceFile(result_1), + addIdentifiers + ); + const result_3 = await runTransformation( + toSourceFile(result_2), + addComments + ); + return result_3; } diff --git a/generator/transformers/googleCloud/clientBasedTransformer.js b/generator/transformers/googleCloud/clientBasedTransformer.js index 81956231..715482e2 100644 --- a/generator/transformers/googleCloud/clientBasedTransformer.js +++ b/generator/transformers/googleCloud/clientBasedTransformer.js @@ -1,236 +1,536 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -}; +'use strict'; +var __awaiter = + (this && this.__awaiter) || + function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P + ? value + : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator['throw'](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done + ? resolve(result.value) + : adopt(result.value).then(fulfilled, rejected); + } + step( + (generator = generator.apply(thisArg, _arguments || [])).next() + ); + }); + }; +var __generator = + (this && this.__generator) || + function(thisArg, body) { + var _ = { + label: 0, + sent: function() { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [], + }, + f, + y, + t, + g; + return ( + (g = { next: verb(0), throw: verb(1), return: verb(2) }), + typeof Symbol === 'function' && + (g[Symbol.iterator] = function() { + return this; + }), + g + ); + function verb(n) { + return function(v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError('Generator is already executing.'); + while (_) + try { + if ( + ((f = 1), + y && + (t = + op[0] & 2 + ? y['return'] + : op[0] + ? y['throw'] || + ((t = y['return']) && t.call(y), 0) + : y.next) && + !(t = t.call(y, op[1])).done) + ) + return t; + if (((y = 0), t)) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if ( + !((t = _.trys), + (t = t.length > 0 && t[t.length - 1])) && + (op[0] === 6 || op[0] === 2) + ) { + _ = 0; + continue; + } + if ( + op[0] === 3 && + (!t || (op[1] > t[0] && op[1] < t[3])) + ) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } + }; exports.__esModule = true; exports.clientBasedTransform = void 0; -var lodash_1 = require("lodash"); -var ts = require("typescript"); +var lodash_1 = require('lodash'); +var ts = require('typescript'); var dummyIdentifiers = [ - "ClassName", - "SDKFunctionName", - "ClientName", - "_client", - "_clientObj", - "Client" + 'ClassName', + 'SDKFunctionName', + 'ClientName', + '_client', + '_clientObj', + 'Client', ]; var printer = ts.createPrinter({ - newLine: ts.NewLineKind.LineFeed, - removeComments: false + newLine: ts.NewLineKind.LineFeed, + removeComments: false, }); function addMultiLineComment(node, comment) { - ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, comment, true); + ts.addSyntheticLeadingComment( + node, + ts.SyntaxKind.MultiLineCommentTrivia, + comment, + true + ); } function runTransformation(sourceCode, transformMethod) { - return new Promise(function (resolve, reject) { - try { - var result = ts.transform(sourceCode, [transformMethod]); - var transformedNodes = result.transformed[0]; - var output = printer.printNode(ts.EmitHint.SourceFile, transformedNodes, sourceCode); - resolve(output); - } - catch (error) { - reject(error); - } - }); + return new Promise(function(resolve, reject) { + try { + var result = ts.transform(sourceCode, [transformMethod]); + var transformedNodes = result.transformed[0]; + var output = printer.printNode( + ts.EmitHint.SourceFile, + transformedNodes, + sourceCode + ); + resolve(output); + } catch (error) { + reject(error); + } + }); } function toSourceFile(sourceCode) { - return ts.createSourceFile("dummyClass.js", sourceCode, ts.ScriptTarget.Latest, true); + return ts.createSourceFile( + 'dummyClass.js', + sourceCode, + ts.ScriptTarget.Latest, + true + ); } function clientBasedTransform(code, classData) { - return __awaiter(this, void 0, void 0, function () { - var node, importStatments, classDeclarationNode, constructorNode, clientObjects, addFunctions, addIdentifiers, addComments, result_1, result_2, result_3; - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - node = code.statements.find(function (stm) { return ts.isClassDeclaration(stm); }); - if (!classData.functions) { - throw new Error("Input is invalid"); - } - if (!node || !node.members.some(function (member) { return ts.isMethodDeclaration(member); })) { - throw new Error("Code is invalid"); - } - code = lodash_1.cloneDeep(code); - // import related - classData.clients = Array.from(new Set(classData.functions.map(function (method) { return method.client; }))); - importStatments = new Array(classData.clients.length); - importStatments.fill(Object.assign({}, code.statements[0])); - code.statements = importStatments.concat(code.statements.slice(1)); - classDeclarationNode = code.statements.find(function (node) { - return ts.isClassDeclaration(node); - }); - constructorNode = classDeclarationNode.members.find(function (node) { return ts.SyntaxKind[node.kind] === "Constructor"; }); - clientObjects = new Array(classData.clients.length); - clientObjects.fill(Object.assign({}, constructorNode.body.statements[0])); - constructorNode.body.statements = clientObjects; - addFunctions = function (context) { return function (rootNode) { - function visit(node) { - if (ts.isClassDeclaration(node)) { - var functions_1 = []; - classData.functions.map(function (method) { - var clonedNode; - if (method.returnTypeName === "Promise") { - clonedNode = Object.assign({}, node.members[1]); - } - else { - clonedNode = Object.assign({}, node.members[2]); - } - clonedNode.name = ts.createIdentifier(method.functionName); - functions_1.push(clonedNode); - }); - var updatedClass = ts.updateClassDeclaration(node, node.decorators, node.modifiers, node.name, node.typeParameters, node.heritageClauses, ts.createNodeArray([node.members[0]].concat(functions_1))); - return updatedClass; - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; }; - addIdentifiers = function (context) { return function (rootNode) { - var count = 0; - var clientCount = 0; - var clientObjCount = 0; - function visit(node) { - if (ts.isMethodDeclaration(node)) { - var parameters = classData.functions[count].params.map(function (param) { - var paramNode = ts.createParameter(undefined, undefined, undefined, param.name); - if (param.optional) { - paramNode.initializer = ts.createIdentifier("undefined"); - } - return paramNode; - }); - node.parameters = parameters; - } - if (ts.isStringLiteral(node) && node.text === "pkgName") { - return ts.createStringLiteral("@google-cloud/" + classData.functions[0].pkgName); - } - if (ts.isIdentifier(node) && dummyIdentifiers.includes(node.text)) { - var updatedIdentifier = void 0; - switch (node.text) { - case "ClassName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier("GCP_" + classData.serviceName)); - break; - case "ClientName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier(classData.clients[clientCount])); - clientCount++; - break; - case "SDKFunctionName": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier(classData.functions[count].SDKFunctionName)); - count++; - break; - case "_client": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier("_" + - classData.functions[count].client.toLowerCase().charAt(0) + - classData.functions[count].client.substr(1))); - break; - case "_clientObj": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier("_" + - classData.clients[clientObjCount].toLowerCase().charAt(0) + - classData.clients[clientObjCount].substr(1))); - break; - case "Client": - updatedIdentifier = ts.updateIdentifier(ts.createIdentifier(classData.clients[clientObjCount])); - clientObjCount++; - break; - } - return updatedIdentifier; - } - if (ts.isCallExpression(node)) { - node.expression.forEachChild(function (childNode) { - if (ts.isIdentifier(childNode) && - childNode.text === "SDKFunctionName") { - var args = classData.functions[count].params.map(function (param) { - return ts.createIdentifier(param.name); - }); - node.arguments = args; - } - }); - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; }; - addComments = function (context) { return function (rootNode) { - var count = 0; - function visit(node) { - if (ts.isClassDeclaration(node)) { - addMultiLineComment(node, "This is an auto generated class, please do not change."); - var comment = "*\n * Class to create a " + classData.serviceName + " object\n * @category Google Cloud\n "; - addMultiLineComment(node, comment); - } - if (ts.isMethodDeclaration(node)) { - var parameters = classData.functions[count].params.map(function (param) { - var statment; - if (param.optional) { - statment = "* @param {" + param.type + "} [" + param.name + "] - Data required for " + classData.functions[count].SDKFunctionName; - } - else { - statment = "* @param {" + param.type + "} " + param.name + " - Data required for " + classData.functions[count].SDKFunctionName; - } - return statment; - }); - var comment = void 0; - if (parameters.length > 0) { - var paramStatments_1 = ""; - parameters.map(function (param) { - paramStatments_1 = paramStatments_1.concat(paramStatments_1 === "" ? "" + param : "\n " + param); - }); - comment = "*\n * Trigers the " + classData.functions[count].SDKFunctionName + " function of " + classData.functions[0].pkgName.split("-")[1] + "\n " + paramStatments_1 + "\n * @returns {Promise<" + classData.functions[count].SDKFunctionName + "Response>}\n "; - } - else { - comment = "*\n * Trigers the " + classData.functions[count].SDKFunctionName + " function of " + classData.functions[0].pkgName.split("-")[1] + "\n * @returns {Promise<" + classData.functions[count].SDKFunctionName + "Response>}\n "; - } - addMultiLineComment(node, comment); - count++; - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; }; - return [4 /*yield*/, runTransformation(code, addFunctions)]; - case 1: - result_1 = _a.sent(); - return [4 /*yield*/, runTransformation(toSourceFile(result_1), addIdentifiers)]; - case 2: - result_2 = _a.sent(); - return [4 /*yield*/, runTransformation(toSourceFile(result_2), addComments)]; - case 3: - result_3 = _a.sent(); - return [2 /*return*/, result_3]; - } - }); - }); + return __awaiter(this, void 0, void 0, function() { + var node, + importStatments, + classDeclarationNode, + constructorNode, + clientObjects, + addFunctions, + addIdentifiers, + addComments, + result_1, + result_2, + result_3; + return __generator(this, function(_a) { + switch (_a.label) { + case 0: + node = code.statements.find(function(stm) { + return ts.isClassDeclaration(stm); + }); + if (!classData.functions) { + throw new Error('Input is invalid'); + } + if ( + !node || + !node.members.some(function(member) { + return ts.isMethodDeclaration(member); + }) + ) { + throw new Error('Code is invalid'); + } + code = lodash_1.cloneDeep(code); + // import related + classData.clients = Array.from( + new Set( + classData.functions.map(function(method) { + return method.client; + }) + ) + ); + importStatments = new Array(classData.clients.length); + importStatments.fill(Object.assign({}, code.statements[0])); + code.statements = importStatments.concat( + code.statements.slice(1) + ); + classDeclarationNode = code.statements.find(function(node) { + return ts.isClassDeclaration(node); + }); + constructorNode = classDeclarationNode.members.find( + function(node) { + return ts.SyntaxKind[node.kind] === 'Constructor'; + } + ); + clientObjects = new Array(classData.clients.length); + clientObjects.fill( + Object.assign({}, constructorNode.body.statements[0]) + ); + constructorNode.body.statements = clientObjects; + addFunctions = function(context) { + return function(rootNode) { + function visit(node) { + if (ts.isClassDeclaration(node)) { + var functions_1 = []; + classData.functions.map(function(method) { + var clonedNode; + if ( + method.returnTypeName === 'Promise' + ) { + clonedNode = Object.assign( + {}, + node.members[1] + ); + } else { + clonedNode = Object.assign( + {}, + node.members[2] + ); + } + clonedNode.name = ts.createIdentifier( + method.functionName + ); + functions_1.push(clonedNode); + }); + var updatedClass = ts.updateClassDeclaration( + node, + node.decorators, + node.modifiers, + node.name, + node.typeParameters, + node.heritageClauses, + ts.createNodeArray( + [node.members[0]].concat( + functions_1 + ) + ) + ); + return updatedClass; + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + }; + addIdentifiers = function(context) { + return function(rootNode) { + var count = 0; + var clientCount = 0; + var clientObjCount = 0; + function visit(node) { + if (ts.isMethodDeclaration(node)) { + var parameters = classData.functions[ + count + ].params.map(function(param) { + var paramNode = ts.createParameter( + undefined, + undefined, + undefined, + param.name + ); + if (param.optional) { + paramNode.initializer = ts.createIdentifier( + 'undefined' + ); + } + return paramNode; + }); + node.parameters = parameters; + } + if ( + ts.isStringLiteral(node) && + node.text === 'pkgName' + ) { + return ts.createStringLiteral( + '@google-cloud/' + + classData.functions[0].pkgName + ); + } + if ( + ts.isIdentifier(node) && + dummyIdentifiers.includes(node.text) + ) { + var updatedIdentifier = void 0; + switch (node.text) { + case 'ClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + 'GCP_' + + classData.serviceName + ) + ); + break; + case 'ClientName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.clients[ + clientCount + ] + ) + ); + clientCount++; + break; + case 'SDKFunctionName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.functions[count] + .SDKFunctionName + ) + ); + count++; + break; + case '_client': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + '_' + + classData.functions[ + count + ].client + .toLowerCase() + .charAt(0) + + classData.functions[ + count + ].client.substr(1) + ) + ); + break; + case '_clientObj': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + '_' + + classData.clients[ + clientObjCount + ] + .toLowerCase() + .charAt(0) + + classData.clients[ + clientObjCount + ].substr(1) + ) + ); + break; + case 'Client': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.clients[ + clientObjCount + ] + ) + ); + clientObjCount++; + break; + } + return updatedIdentifier; + } + if (ts.isCallExpression(node)) { + node.expression.forEachChild(function( + childNode + ) { + if ( + ts.isIdentifier(childNode) && + childNode.text === 'SDKFunctionName' + ) { + var args = classData.functions[ + count + ].params.map(function(param) { + return ts.createIdentifier( + param.name + ); + }); + node.arguments = args; + } + }); + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + }; + addComments = function(context) { + return function(rootNode) { + var count = 0; + function visit(node) { + if (ts.isClassDeclaration(node)) { + addMultiLineComment( + node, + 'This is an auto generated class, please do not change.' + ); + var comment = + '*\n * Class to create a ' + + classData.serviceName + + ' object\n * @category Google Cloud\n '; + addMultiLineComment(node, comment); + } + if (ts.isMethodDeclaration(node)) { + var parameters = classData.functions[ + count + ].params.map(function(param) { + var statment; + if (param.optional) { + statment = + '* @param {' + + param.type + + '} [' + + param.name + + '] - Data required for ' + + classData.functions[count] + .SDKFunctionName; + } else { + statment = + '* @param {' + + param.type + + '} ' + + param.name + + ' - Data required for ' + + classData.functions[count] + .SDKFunctionName; + } + return statment; + }); + var comment = void 0; + if (parameters.length > 0) { + var paramStatments_1 = ''; + parameters.map(function(param) { + paramStatments_1 = paramStatments_1.concat( + paramStatments_1 === '' + ? '' + param + : '\n ' + param + ); + }); + comment = + '*\n * Trigers the ' + + classData.functions[count] + .SDKFunctionName + + ' function of ' + + classData.functions[0].pkgName.split( + '-' + )[1] + + '\n ' + + paramStatments_1 + + '\n * @returns {Promise<' + + classData.functions[count] + .SDKFunctionName + + 'Response>}\n '; + } else { + comment = + '*\n * Trigers the ' + + classData.functions[count] + .SDKFunctionName + + ' function of ' + + classData.functions[0].pkgName.split( + '-' + )[1] + + '\n * @returns {Promise<' + + classData.functions[count] + .SDKFunctionName + + 'Response>}\n '; + } + addMultiLineComment(node, comment); + count++; + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; + }; + return [4 /*yield*/, runTransformation(code, addFunctions)]; + case 1: + result_1 = _a.sent(); + return [ + 4 /*yield*/, + runTransformation( + toSourceFile(result_1), + addIdentifiers + ), + ]; + case 2: + result_2 = _a.sent(); + return [ + 4 /*yield*/, + runTransformation(toSourceFile(result_2), addComments), + ]; + case 3: + result_3 = _a.sent(); + return [2 /*return*/, result_3]; + } + }); + }); } exports.clientBasedTransform = clientBasedTransform; diff --git a/generator/transformers/googleCloud/clientBasedTransformer.ts b/generator/transformers/googleCloud/clientBasedTransformer.ts index bbee5e73..b2819e53 100644 --- a/generator/transformers/googleCloud/clientBasedTransformer.ts +++ b/generator/transformers/googleCloud/clientBasedTransformer.ts @@ -1,292 +1,309 @@ -import { cloneDeep } from "lodash"; -import * as ts from "typescript"; +import { cloneDeep } from 'lodash'; +import * as ts from 'typescript'; const dummyIdentifiers = [ - "ClassName", - "SDKFunctionName", - "ClientName", - "_client", - "_clientObj", - "Client" + 'ClassName', + 'SDKFunctionName', + 'ClientName', + '_client', + '_clientObj', + 'Client', ]; const printer: ts.Printer = ts.createPrinter({ - newLine: ts.NewLineKind.LineFeed, - removeComments: false + newLine: ts.NewLineKind.LineFeed, + removeComments: false, }); function addMultiLineComment(node, comment: string) { - ts.addSyntheticLeadingComment( - node, - ts.SyntaxKind.MultiLineCommentTrivia, - comment, - true - ); + ts.addSyntheticLeadingComment( + node, + ts.SyntaxKind.MultiLineCommentTrivia, + comment, + true + ); } function runTransformation(sourceCode, transformMethod): Promise { - return new Promise((resolve, reject) => { - try { - const result = ts.transform(sourceCode, [transformMethod]); - const transformedNodes = result.transformed[0]; - const output = printer.printNode( - ts.EmitHint.SourceFile, - transformedNodes, - sourceCode - ); - resolve(output); - } catch (error) { - reject(error); - } - }); + return new Promise((resolve, reject) => { + try { + const result = ts.transform(sourceCode, [transformMethod]); + const transformedNodes = result.transformed[0]; + const output = printer.printNode( + ts.EmitHint.SourceFile, + transformedNodes, + sourceCode + ); + resolve(output); + } catch (error) { + reject(error); + } + }); } function toSourceFile(sourceCode: string): ts.SourceFile { - return ts.createSourceFile( - "dummyClass.js", - sourceCode, - ts.ScriptTarget.Latest, - true - ); + return ts.createSourceFile( + 'dummyClass.js', + sourceCode, + ts.ScriptTarget.Latest, + true + ); } export async function clientBasedTransform( - code: ts.SourceFile, - classData: any + code: ts.SourceFile, + classData: any ): Promise { - const node: any = code.statements.find(stm => ts.isClassDeclaration(stm)); + const node: any = code.statements.find(stm => ts.isClassDeclaration(stm)); - if (!classData.functions) { - throw new Error("Input is invalid"); - } + if (!classData.functions) { + throw new Error('Input is invalid'); + } - if (!node || !node.members.some(member => ts.isMethodDeclaration(member))) { - throw new Error("Code is invalid"); - } + if (!node || !node.members.some(member => ts.isMethodDeclaration(member))) { + throw new Error('Code is invalid'); + } - code = cloneDeep(code); + code = cloneDeep(code); - // import related - classData.clients = Array.from( - new Set(classData.functions.map(method => method.client)) - ); - const importStatments: any = new Array(classData.clients.length); - importStatments.fill(Object.assign({}, code.statements[0])); - code.statements = importStatments.concat(code.statements.slice(1)); + // import related + classData.clients = Array.from( + new Set(classData.functions.map(method => method.client)) + ); + const importStatments: any = new Array(classData.clients.length); + importStatments.fill(Object.assign({}, code.statements[0])); + code.statements = importStatments.concat(code.statements.slice(1)); - const classDeclarationNode: any = code.statements.find(node => - ts.isClassDeclaration(node) - ); - const constructorNode: any = classDeclarationNode.members.find( - node => ts.SyntaxKind[node.kind] === "Constructor" - ); - const clientObjects: any = new Array(classData.clients.length); - clientObjects.fill(Object.assign({}, constructorNode.body.statements[0])); - constructorNode.body.statements = clientObjects; - // import related + const classDeclarationNode: any = code.statements.find(node => + ts.isClassDeclaration(node) + ); + const constructorNode: any = classDeclarationNode.members.find( + node => ts.SyntaxKind[node.kind] === 'Constructor' + ); + const clientObjects: any = new Array(classData.clients.length); + clientObjects.fill(Object.assign({}, constructorNode.body.statements[0])); + constructorNode.body.statements = clientObjects; + // import related - const addFunctions = ( - context: ts.TransformationContext - ) => (rootNode: T) => { - function visit(node: ts.Node): ts.Node { - if (ts.isClassDeclaration(node)) { - const functions: any = []; - classData.functions.map(method => { - let clonedNode; - if (method.returnTypeName === "Promise") { - clonedNode = Object.assign({}, node.members[1]); - } else { - clonedNode = Object.assign({}, node.members[2]); - } - clonedNode.name = ts.createIdentifier(method.functionName); - functions.push(clonedNode); - }); + const addFunctions = ( + context: ts.TransformationContext + ) => (rootNode: T) => { + function visit(node: ts.Node): ts.Node { + if (ts.isClassDeclaration(node)) { + const functions: any = []; + classData.functions.map(method => { + let clonedNode; + if (method.returnTypeName === 'Promise') { + clonedNode = Object.assign({}, node.members[1]); + } else { + clonedNode = Object.assign({}, node.members[2]); + } + clonedNode.name = ts.createIdentifier(method.functionName); + functions.push(clonedNode); + }); - const updatedClass = ts.updateClassDeclaration( - node, - node.decorators, - node.modifiers, - node.name, - node.typeParameters, - node.heritageClauses, - ts.createNodeArray([node.members[0]].concat(functions)) - ); + const updatedClass = ts.updateClassDeclaration( + node, + node.decorators, + node.modifiers, + node.name, + node.typeParameters, + node.heritageClauses, + ts.createNodeArray([node.members[0]].concat(functions)) + ); - return updatedClass; - } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; + return updatedClass; + } + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; - const addIdentifiers = ( - context: ts.TransformationContext - ) => (rootNode: T) => { - let count = 0; - let clientCount = 0; - let clientObjCount = 0; - function visit(node: ts.Node): ts.Node { - if (ts.isMethodDeclaration(node)) { - const parameters = classData.functions[count].params.map(param => { - const paramNode = ts.createParameter( - undefined, - undefined, - undefined, - param.name - ); + const addIdentifiers = ( + context: ts.TransformationContext + ) => (rootNode: T) => { + let count = 0; + let clientCount = 0; + let clientObjCount = 0; + function visit(node: ts.Node): ts.Node { + if (ts.isMethodDeclaration(node)) { + const parameters = classData.functions[count].params.map( + param => { + const paramNode = ts.createParameter( + undefined, + undefined, + undefined, + param.name + ); - if (param.optional) { - paramNode.initializer = ts.createIdentifier("undefined"); - } + if (param.optional) { + paramNode.initializer = ts.createIdentifier( + 'undefined' + ); + } - return paramNode; - }); + return paramNode; + } + ); - node.parameters = parameters; - } + node.parameters = parameters; + } - if (ts.isStringLiteral(node) && node.text === "pkgName") { - return ts.createStringLiteral( - "@google-cloud/" + classData.functions[0].pkgName - ); - } + if (ts.isStringLiteral(node) && node.text === 'pkgName') { + return ts.createStringLiteral( + '@google-cloud/' + classData.functions[0].pkgName + ); + } - if (ts.isIdentifier(node) && dummyIdentifiers.includes(node.text)) { - let updatedIdentifier; - switch (node.text) { - case "ClassName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier("GCP_" + classData.serviceName) - ); - break; - case "ClientName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier(classData.clients[clientCount]) - ); - clientCount++; - break; - case "SDKFunctionName": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier(classData.functions[count].SDKFunctionName) - ); - count++; - break; - case "_client": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier( - "_" + - classData.functions[count].client.toLowerCase().charAt(0) + - classData.functions[count].client.substr(1) - ) - ); - break; - case "_clientObj": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier( - "_" + - classData.clients[clientObjCount].toLowerCase().charAt(0) + - classData.clients[clientObjCount].substr(1) - ) - ); - break; - case "Client": - updatedIdentifier = ts.updateIdentifier( - ts.createIdentifier(classData.clients[clientObjCount]) - ); - clientObjCount++; - break; - } - return updatedIdentifier; - } + if (ts.isIdentifier(node) && dummyIdentifiers.includes(node.text)) { + let updatedIdentifier; + switch (node.text) { + case 'ClassName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier('GCP_' + classData.serviceName) + ); + break; + case 'ClientName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier(classData.clients[clientCount]) + ); + clientCount++; + break; + case 'SDKFunctionName': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.functions[count].SDKFunctionName + ) + ); + count++; + break; + case '_client': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + '_' + + classData.functions[count].client + .toLowerCase() + .charAt(0) + + classData.functions[count].client.substr(1) + ) + ); + break; + case '_clientObj': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + '_' + + classData.clients[clientObjCount] + .toLowerCase() + .charAt(0) + + classData.clients[clientObjCount].substr(1) + ) + ); + break; + case 'Client': + updatedIdentifier = ts.updateIdentifier( + ts.createIdentifier( + classData.clients[clientObjCount] + ) + ); + clientObjCount++; + break; + } + return updatedIdentifier; + } - if (ts.isCallExpression(node)) { - node.expression.forEachChild(childNode => { - if ( - ts.isIdentifier(childNode) && - childNode.text === "SDKFunctionName" - ) { - const args = classData.functions[count].params.map(param => - ts.createIdentifier(param.name) - ); - node.arguments = args; - } - }); - } + if (ts.isCallExpression(node)) { + node.expression.forEachChild(childNode => { + if ( + ts.isIdentifier(childNode) && + childNode.text === 'SDKFunctionName' + ) { + const args = classData.functions[count].params.map( + param => ts.createIdentifier(param.name) + ); + node.arguments = args; + } + }); + } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; - const addComments = ( - context: ts.TransformationContext - ) => (rootNode: T) => { - let count = 0; + const addComments = ( + context: ts.TransformationContext + ) => (rootNode: T) => { + let count = 0; - function visit(node: ts.Node): ts.Node { - if (ts.isClassDeclaration(node)) { - addMultiLineComment( - node, - "This is an auto generated class, please do not change." - ); - const comment = `* + function visit(node: ts.Node): ts.Node { + if (ts.isClassDeclaration(node)) { + addMultiLineComment( + node, + 'This is an auto generated class, please do not change.' + ); + const comment = `* * Class to create a ${classData.serviceName} object * @category Google Cloud `; - addMultiLineComment(node, comment); - } + addMultiLineComment(node, comment); + } - if (ts.isMethodDeclaration(node)) { - const parameters = classData.functions[count].params.map(param => { - let statment; + if (ts.isMethodDeclaration(node)) { + const parameters = classData.functions[count].params.map( + param => { + let statment; - if (param.optional) { - statment = `* @param {${param.type}} [${param.name}] - Data required for ${classData.functions[count].SDKFunctionName}`; - } else { - statment = `* @param {${param.type}} ${param.name} - Data required for ${classData.functions[count].SDKFunctionName}`; - } - return statment; - }); + if (param.optional) { + statment = `* @param {${param.type}} [${param.name}] - Data required for ${classData.functions[count].SDKFunctionName}`; + } else { + statment = `* @param {${param.type}} ${param.name} - Data required for ${classData.functions[count].SDKFunctionName}`; + } + return statment; + } + ); - let comment; - if (parameters.length > 0) { - let paramStatments: string = ""; - parameters.map(param => { - paramStatments = paramStatments.concat( - paramStatments === "" ? `${param}` : `\n ${param}` - ); - }); + let comment; + if (parameters.length > 0) { + let paramStatments: string = ''; + parameters.map(param => { + paramStatments = paramStatments.concat( + paramStatments === '' ? `${param}` : `\n ${param}` + ); + }); - comment = `* + comment = `* * Trigers the ${classData.functions[count].SDKFunctionName} function of ${ - classData.functions[0].pkgName.split("-")[1] - } + classData.functions[0].pkgName.split('-')[1] + } ${paramStatments} * @returns {Promise<${classData.functions[count].SDKFunctionName}Response>} `; - } else { - comment = `* + } else { + comment = `* * Trigers the ${classData.functions[count].SDKFunctionName} function of ${ - classData.functions[0].pkgName.split("-")[1] - } + classData.functions[0].pkgName.split('-')[1] + } * @returns {Promise<${classData.functions[count].SDKFunctionName}Response>} `; - } + } - addMultiLineComment(node, comment); - count++; - } + addMultiLineComment(node, comment); + count++; + } - return ts.visitEachChild(node, visit, context); - } - return ts.visitNode(rootNode, visit); - }; + return ts.visitEachChild(node, visit, context); + } + return ts.visitNode(rootNode, visit); + }; - const result_1 = await runTransformation(code, addFunctions); - const result_2 = await runTransformation( - toSourceFile(result_1), - addIdentifiers - ); - const result_3 = await runTransformation(toSourceFile(result_2), addComments); - return result_3; + const result_1 = await runTransformation(code, addFunctions); + const result_2 = await runTransformation( + toSourceFile(result_1), + addIdentifiers + ); + const result_3 = await runTransformation( + toSourceFile(result_2), + addComments + ); + return result_3; }