/**
* @author Raj Dye - raj@rajdye.com
* Copyright (c) 2014 Institute for Sustainable Performance of Buildings (Superb)
*/
goog.provide('lgb.simulation.model.BaseModel');
goog.require('lgb.core.BaseClass');
/**
* @constructor
*/
lgb.simulation.model.BaseModel = function() {
};
lgb.simulation.model.BaseModel.prototype.getClassName = function() {
var fullClassName = this.getFullClassName();
var ary = fullClassName.split('.');
var len = ary.length;
var className = ary[len-1];
return className;
};
lgb.simulation.model.BaseModel.prototype.getClassReference = function() {
var fullClassName = this.getFullClassName();
var classReference = eval(fullClassName);
return classReference;
};
lgb.simulation.model.BaseModel.prototype.toJSON = function() {
return this.toJSONHelper_();
};
lgb.simulation.model.BaseModel.prototype.toJSONHelper_ = function() {
var serializeType = this.serializeType;
if ( undefined == serializeType) {
serializeType = true;
}
var jsonObject = {};
if (serializeType) {
jsonObject.t = this.getClassName();
}
var classReference = this.getClassReference();
if (undefined != classReference.fieldPrimitivesEx_) {
var fieldPrimitivesEx = classReference.fieldPrimitivesEx_;
for(var jsFieldName in fieldPrimitivesEx) {
var jsonFieldName = fieldPrimitivesEx[jsFieldName];
jsonObject[jsonFieldName] = this[jsFieldName];
}
}
if (undefined != classReference.fieldObjectsEx_) {
var fieldObjectsEx = classReference.fieldObjectsEx_;
for(var jsFieldName in fieldObjectsEx) {
var fieldObject = fieldObjectsEx[jsFieldName];
var jsonFieldName = fieldObject.jsonFieldName;
var fieldClassReference = fieldObject.classReference;
if (this[jsFieldName] != null) {
var fieldValue = this[jsFieldName];
if (fieldClassReference == lgb.simulation.model.voManaged.SerializableVector) {
if (fieldValue instanceof Array) {
var sv = new lgb.simulation.model.voManaged.SerializableVector(fieldObject.itemTypeString, fieldValue);
jsonObject[jsonFieldName] = sv;
} else {
debugger;
}
} else {
jsonObject[jsonFieldName] = fieldValue;
}
}
}
}
return jsonObject;
};
const ts = require('typescript');
const path = require('path');
const Documentation = require('./Documentation');
module.exports = checkSources;
/**
* @param {!Array<!import('../Source')>} sources
*/
function checkSources(sources) {
// special treatment for Events.js
const classEvents = new Map();
const eventsSource = sources.find(source => source.name() === 'Events.js');
if (eventsSource) {
const {Events} = require(eventsSource.filePath());
for (const [className, events] of Object.entries(Events))
classEvents.set(className, Array.from(Object.values(events)).filter(e => typeof e === 'string').map(e => Documentation.Member.createEvent(e)));
}
const excludeClasses = new Set([]);
const program = ts.createProgram({
options: {
allowJs: true,
target: ts.ScriptTarget.ES2017
},
rootNames: sources.map(source => source.filePath())
});
const checker = program.getTypeChecker();
const sourceFiles = program.getSourceFiles();
/** @type {!Array<!Documentation.Class>} */
const classes = [];
/** @type {!Map<string, string>} */
const inheritance = new Map();
sourceFiles.filter(x => !x.fileName.includes('node_modules')).map(x => visit(x));
const errors = [];
const documentation = new Documentation(recreateClassesWithInheritance(classes, inheritance));
return {errors, documentation};
/**
* @param {!Array<!Documentation.Class>} classes
* @param {!Map<string, string>} inheritance
* @return {!Array<!Documentation.Class>}
*/
function recreateClassesWithInheritance(classes, inheritance) {
const classesByName = new Map(classes.map(cls => [cls.name, cls]));
return classes.map(cls => {
const membersMap = new Map();
for (let wp = cls; wp; wp = classesByName.get(inheritance.get(wp.name))) {
for (const member of wp.membersArray) {
// Member was overridden.
const memberId = member.kind + ':' + member.name;
if (membersMap.has(memberId))
continue;
membersMap.set(memberId, member);
}
}
return new Documentation.Class(cls.name, Array.from(membersMap.values()));
});
}
/**
* @param {!ts.Node} node
*/
function visit(node) {
if (ts.isClassDeclaration(node) || ts.isClassExpression(node)) {
const symbol = node.name ? checker.getSymbolAtLocation(node.name) : node.symbol;
let className = symbol.getName();
if (className === '__class') {
let parent = node;
while (parent.parent)
parent = parent.parent;
className = path.basename(parent.fileName, '.js');
}
if (className && !excludeClasses.has(className)) {
classes.push(serializeClass(className, symbol, node));
const parentClassName = parentClass(node);
if (parentClassName)
inheritance.set(className, parentClassName);
excludeClasses.add(className);
}
}
ts.forEachChild(node, visit);
}
function parentClass(classNode) {
for (const herigateClause of classNode.heritageClauses || []) {
for (const heritageType of herigateClause.types) {
const parentClassName = heritageType.expression.escapedText;
return parentClassName;
}
}
return null;
}
function serializeSymbol(symbol, circular = []) {
const type = checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration);
const name = symbol.getName();
if (symbol.valueDeclaration.dotDotDotToken) {
const innerType = serializeType(type.typeArguments[0], circular);
innerType.name = '...' + innerType.name;
return Documentation.Member.createProperty('...' + name, innerType);
}
return Documentation.Member.createProperty(name, serializeType(type, circular));
}
/**
* @param {!ts.ObjectType} type
*/
function isRegularObject(type) {
if (type.isIntersection())
return true;
if (!type.objectFlags)
return false;
if (!('aliasSymbol' in type))
return false;
if (type.getConstructSignatures().length)
return false;
if (type.getCallSignatures().length)
return false;
return true;
}
/**
* @param {!ts.Type} type
* @return {!Documentation.Type}
*/
function serializeType(type, circular = []) {
let typeName = checker.typeToString(type);
if (typeName === 'any' || typeName === '{ [x: string]: string; }')
typeName = 'Object';
const nextCircular = [typeName].concat(circular);
if (isRegularObject(type)) {
let properties = undefined;
if (!circular.includes(typeName))
properties = type.getProperties().map(property => serializeSymbol(property, nextCircular));
return new Documentation.Type('Object', properties);
}
if (type.isUnion() && typeName.includes('|')) {
const types = type.types.map(type => serializeType(type, circular));
const name = types.map(type => type.name).join('|');
const properties = [].concat(...types.map(type => type.properties));
return new Documentation.Type(name.replace(/false\|true/g, 'boolean'), properties);
}
if (type.typeArguments) {
const properties = [];
const innerTypeNames = [];
for (const typeArgument of type.typeArguments) {
const innerType = serializeType(typeArgument, nextCircular);
if (innerType.properties)
properties.push(...innerType.properties);
innerTypeNames.push(innerType.name);
}
if (innerTypeNames.length === 1 && innerTypeNames[0] === 'void')
return new Documentation.Type(type.symbol.name);
return new Documentation.Type(`${type.symbol.name}<${innerTypeNames.join(', ')}>`, properties);
}
return new Documentation.Type(typeName, []);
}
/**
* @param {string} className
* @param {!ts.Symbol} symbol
* @return {}
*/
function serializeClass(className, symbol, node) {
/** @type {!Array<!Documentation.Member>} */
const members = classEvents.get(className) || [];
for (const [name, member] of symbol.members || []) {
if (name.startsWith('_'))
continue;
const memberType = checker.getTypeOfSymbolAtLocation(member, member.valueDeclaration);
const signature = memberType.getCallSignatures()[0];
if (signature)
members.push(serializeSignature(name, signature));
else
members.push(serializeProperty(name, memberType));
}
return new Documentation.Class(className, members);
}
/**
* @param {string} name
* @param {!ts.Signature} signature
*/
function serializeSignature(name, signature) {
const parameters = signature.parameters.map(s => serializeSymbol(s));
const returnType = serializeType(signature.getReturnType());
return Documentation.Member.createMethod(name, parameters, returnType.name !== 'void' ? returnType : null);
}
/**
* @param {string} name
* @param {!ts.Type} type
*/
function serializeProperty(name, type) {
return Documentation.Member.createProperty(name, serializeType(type));
}
}
/**
* Copyright 2011 Microsoft Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Module dependencies.
var https = require('https');
var util = require('util');
var fs = require('fs');
var url = require('url');
var tunnel = require('tunnel');
var WebResource = require('../../http/webresource');
var ServiceClient = require('./serviceclient');
var Constants = require('../../util/constants');
var HeaderConstants = Constants.HeaderConstants;
// Expose 'ServiceManagementClient'.
exports = module.exports = ServiceManagementClient;
/**
* Error messages.
*/
ServiceManagementClient.missingKeyValue = 'Client private key certificate is required';
ServiceManagementClient.missingCertValue = 'Client public certificate is required';
ServiceManagementClient.invalidSerializeType = 'serializetype must be XML or JSON';
// Default API Version
ServiceManagementClient.DefaultAPIVersion = '2012-03-01';
// Default serialization Type: XML or JSON
ServiceManagementClient.DefaultSerializeType = 'JSON';
/**
* Creates a new ServiceClient object.
*
* @constructor
* @param {string} hostOptions The host options to override defaults.
* {
* host: 'management.core.windows.net',
* port: optional port number
* apiversion: '2012-03-01',
* serializetype: 'XML'
* }
*/
function ServiceManagementClient(authentication, hostOptions) {
ServiceManagementClient.super_.call(this);
this._setAuthentication(authentication);
this._setServiceHost(hostOptions);
this._setDefaultProxy();
}
util.inherits(ServiceManagementClient, ServiceClient);
/**
* Sets the client authentication credentials using provided values
* private key and public certificate values may be passed as strings, or will be read from files
*
* @return {Void}
*/
ServiceManagementClient.prototype._setAuthentication = function(authentication) {
this.keyvalue = null;
this.certvalue = null;
if (authentication) {
if (typeof authentication.keyvalue === 'string' && authentication.keyvalue.length > 0) {
this.keyvalue = authentication.keyvalue;
} else if (typeof authentication.keyfile === 'string' && authentication.keyfile.length > 0) {
this.keyvalue = fs.readFileSync(authentication.keyfile, 'ascii');
}
if (typeof authentication.certvalue === 'string' && authentication.certvalue.length > 0) {
this.certvalue = authentication.certvalue;
} else if (typeof authentication.certfile === 'string' && authentication.certfile.length > 0) {
this.certvalue = fs.readFileSync(authentication.certfile, 'ascii');
}
}
if (this.keyvalue === null || this.keyvalue.length === 0) {
var keyfile = process.env[ServiceClient.EnvironmentVariables.AZURE_KEYFILE];
if (typeof keyfile === 'string' && keyfile.length > 0) {
this.keyvalue = fs.readFileSync(keyfile, 'ascii');
}
}
if (this.certvalue === null || this.certvalue.length === 0) {
var certfile = process.env[ServiceClient.EnvironmentVariables.AZURE_CERTFILE];
if (typeof certfile === 'string' && certfile.length > 0) {
this.certvalue = fs.readFileSync(certfile, 'ascii');
}
}
if (this.keyvalue === null || this.keyvalue.length === 0) {
throw new Error(ServiceManagementClient.missingKeyValue);
}
if (this.certvalue === null || this.certvalue.length === 0) {
throw new Error(ServiceManagementClient.missingCertValue);
}
};
/**
* Sets the service host options using provided values
* Options are host name, serialization type, and API version string
* If not specified, then the defaults are used
*
* @return {Void}
*/
ServiceManagementClient.prototype._setServiceHost = function(hostOptions) {
this.host = ServiceClient.CLOUD_SERVICE_MANAGEMENT_HOST;
this.apiversion = ServiceManagementClient.DefaultAPIVersion;
this.serializetype = ServiceManagementClient.DefaultSerializeType;
this.port = null;
this.protocol = Constants.HTTPS;
if (hostOptions) {
if (hostOptions.host) {
this.host = hostOptions.host;
}
if (hostOptions.apiversion) {
this.apiversion = hostOptions.apiversion;
}
if (hostOptions.serializetype) {
if (hostOptions.serializetype != 'XML' && hostOptions.serializetype != 'JSON') {
throw new Error(ServiceManagementClient.invalidSerializeType);
}
this.serializetype = hostOptions.serializetype;
}
if (hostOptions.port) {
this.port = hostOptions.port;
}
}
};
/**
* Get the content-type string based on serializeType
*
* @return {string}
*/
ServiceManagementClient.prototype._getContentType = function() {
if (this.serializetype === 'XML') {
return 'application/xml';
} else {
return 'application/json';
}
};
/**
* Get the accept header string based on serializeType
*
* @return {string}
*/
ServiceManagementClient.prototype._getAcceptType = function() {
if (this.serializetype === 'XML') {
return 'application/xml';
} else {
return 'application/json';
}
};
/**
* Builds the request options to be passed to the http.request method.
*
* @param {WebResource} webResource The webresource where to build the options from.
* @param {object} options The request options.
* @param {function(error, requestOptions)} callback The callback function.
* @return {undefined}
*/
ServiceManagementClient.prototype._buildRequestOptions = function(webResource, options, callback) {
var self = this;
webResource.addOptionalHeader(HeaderConstants.CONTENT_TYPE, self._getContentType());
webResource.addOptionalHeader(HeaderConstants.ACCEPT_HEADER, self._getAcceptType());
webResource.addOptionalHeader(HeaderConstants.ACCEPT_CHARSET_HEADER, 'UTF-8');
webResource.addOptionalHeader(HeaderConstants.STORAGE_VERSION_HEADER, self.apiversion);
webResource.addOptionalHeader(HeaderConstants.HOST_HEADER, self.host);
var requestOptions = null;
requestOptions = {
method: webResource.httpVerb,
path: webResource.path,
key: self.keyvalue,
cert: self.certvalue,
host: self.host,
headers: webResource.headers
};
if (self.port) {
requestOptions.port = self.port;
}
self._setAgent(self, requestOptions, self.protocol.substr(0, 5).toLowerCase() === Constants.HTTPS);
callback(null, requestOptions);
};
/**
* Sets the service host default proxy from the environment.
* Can be overridden by calling _setProxyUrl or _setProxy
*
*/
ServiceManagementClient.prototype._setDefaultProxy = function() {
var proxyUrl = this._loadEnvironmentProxyValue();
this._setProxyUrl(proxyUrl);
};
/*
* Sets proxy object from a proxy url.
*
* @param {string} proxyurl url of proxy server. ex: http:corpproxy:80
* if null or undefined, clears proxy
*/
ServiceManagementClient.prototype._setProxyUrl = function(proxyurl) {
if (proxyurl) {
var parsedUrl = url.parse(proxyurl);
if (!parsedUrl.port) {
parsedUrl.port = 80;
}
this._setProxy({
host: parsedUrl.hostname,
port: parsedUrl.port
},
parsedUrl.protocol.substr(0, 5).toLowerCase() === Constants.HTTPS);
} else {
this._setProxy(null);
}
};
/*
* Sets proxy object specified by caller.
*
* @param {object} proxy proxy to use for tunneling
* {
* host: hostname
* port: port number
* proxyAuth: 'user:password' for basic auth
* headers: {...} headers for proxy server
* key: key for proxy server
* ca: ca for proxy server
* cert: cert for proxy server
* }
* if null or undefined, clears proxy
* @param {bool} isHTTPS true - use https to proxy. Otherwise use http.
*/
ServiceManagementClient.prototype._setProxy = function(proxy, isHTTPS) {
if (proxy) {
this.useTunnelProxy = true;
this.proxy = proxy;
this.proxyIsHTTPS = isHTTPS || false;
} else {
this.useTunnelProxy = false;
this.proxy = null;
}
};
/**
* Set the Agent to use for the request
* Result depends on proxy settings and protocol
*
* @param {object} reqopts request options for request
* @param {bool} isHTTPS true - use https to proxy. Otherwise use http.
*/
ServiceManagementClient.prototype._setAgent = function(self, reqopts, isHTTPS) {
if (self.useTunnelProxy && self.proxy) {
var agentinfo = {
proxy: self.proxy
};
if (reqopts.key) {
agentinfo.key = reqopts.key;
}
if (reqopts.cert) {
agentinfo.cert = reqopts.cert;
}
if (this.maxSockets) {
agentinfo.maxSockets = self.maxSockets;
}
if (isHTTPS) {
if (self.proxyIsHTTPS) {
reqopts.agent = tunnel.httpsOverHttps(agentinfo);
} else {
reqopts.agent = tunnel.httpsOverHttp(agentinfo);
}
} else {
if (self.proxyIsHTTPS) {
reqopts.agent = tunnel.httpOverHttps(agentinfo);
} else {
reqopts.agent = tunnel.httpOverHttp(agentinfo);
}
}
} else if (isHTTPS) {
reqopts.agent = new https.Agent(reqopts);
}
};
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// @ts-check
const path = require('path');
const fs = require('fs');
const Documentation = require('./documentation');
const { parseApi } = require('./api_parser');
const PROJECT_DIR = path.join(__dirname, '..', '..');
{
const documentation = parseApi(path.join(PROJECT_DIR, 'docs', 'src', 'api'));
documentation.setLinkRenderer(item => {
const { clazz, param, option } = item;
if (param)
return `\`${param}\``;
if (option)
return `\`${option}\``;
if (clazz)
return `\`${clazz.name}\``;
});
documentation.generateSourceCodeComments();
const result = serialize(documentation);
console.log(JSON.stringify(result));
}
/**
* @param {Documentation} documentation
*/
function serialize(documentation) {
return documentation.classesArray.map(serializeClass);
}
/**
* @param {Documentation.Class} clazz
*/
function serializeClass(clazz) {
const result = { name: clazz.name, spec: clazz.spec };
if (clazz.extends)
result.extends = clazz.extends;
result.langs = clazz.langs;
if (result.langs && result.langs.types) {
for (const key in result.langs.types)
result.langs.types[key] = serializeType(result.langs.types[key]);
}
if (clazz.comment)
result.comment = clazz.comment;
result.members = clazz.membersArray.map(serializeMember);
return result;
}
/**
* @param {Documentation.Member} member
*/
function serializeMember(member) {
const result = /** @type {any} */ ({ ...member });
sanitize(result);
result.args = member.argsArray.map(serializeProperty);
if (member.type)
result.type = serializeType(member.type)
return result;
}
function serializeProperty(arg) {
const result = { ...arg };
sanitize(result);
if (arg.type)
result.type = serializeType(arg.type, arg.name === 'options')
return result;
}
function sanitize(result) {
delete result.args;
delete result.argsArray;
delete result.clazz;
delete result.enclosingMethod;
}
/**
* @param {Documentation.Type} type
* @param {boolean} sortProperties
*/
function serializeType(type, sortProperties = false) {
/** @type {any} */
const result = { ...type };
if (type.properties)
result.properties = (sortProperties ? type.sortedProperties() : type.properties).map(serializeProperty);
if (type.union)
result.union = type.union.map(type => serializeType(type));
if (type.templates)
result.templates = type.templates.map(type => serializeType(type));
if (type.args)
result.args = type.args.map(type => serializeType(type));
if (type.returnType)
result.returnType = serializeType(type.returnType);
return result;
}
Accelerate Your Automation Test Cycles With LambdaTest
Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.