prisma-yml
Version:
<a href="https://www.prismagraphql.com"><img src="https://imgur.com/HUu10rH.png" width="248" /></a>
401 lines • 18.3 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
var _ = require("lodash");
var replaceall = require("replaceall");
var BbPromise = require("bluebird");
var Output_1 = require("./Output");
var Variables = /** @class */ (function () {
function Variables(fileName, options, out, envVars) {
if (options === void 0) { options = {}; }
if (out === void 0) { out = new Output_1.Output(); }
this.overwriteSyntax = RegExp(/,/g);
this.envRefSyntax = RegExp(/^env:/g);
this.selfRefSyntax = RegExp(/^self:/g);
this.stringRefSyntax = RegExp(/('.*')|(".*")/g);
this.optRefSyntax = RegExp(/^opt:/g);
this.variableSyntax = RegExp(
/* tslint:disable-next-line */
'\\${([ ~:a-zA-Z0-9._\'",\\-\\/\\(\\)]+?)}', 'g');
this.out = out;
this.fileName = fileName;
this.options = options;
this.envVars = envVars || process.env;
// this.fileRefSyntax = RegExp(/^file\((~?[a-zA-Z0-9._\-/]+?)\)/g);
// this.cfRefSyntax = RegExp(/^cf:/g);
// this.s3RefSyntax = RegExp(/^s3:(.+?)\/(.+)$/);
// this.ssmRefSyntax = RegExp(/^ssm:([a-zA-Z0-9_.-/]+)[~]?(true|false)?/);
}
Variables.prototype.populateJson = function (json) {
var _this = this;
this.json = json;
return this.populateObject(this.json).then(function () {
return BbPromise.resolve(_this.json);
});
};
Variables.prototype.populateObject = function (objectToPopulate) {
var _this = this;
var populateAll = [];
var deepMapValues = function (object, callback, propertyPath) {
var deepMapValuesIteratee = function (value, key) {
return deepMapValues(value, callback, propertyPath ? propertyPath.concat(key) : [key]);
};
if (_.isArray(object)) {
return _.map(object, deepMapValuesIteratee);
}
else if (_.isObject(object) &&
!_.isDate(object) &&
!_.isRegExp(object) &&
!_.isFunction(object)) {
return _.extend({}, object, _.mapValues(object, deepMapValuesIteratee));
}
return callback(object, propertyPath);
};
deepMapValues(objectToPopulate, function (property, propertyPath) {
if (typeof property === 'string') {
var populateSingleProperty = _this.populateProperty(property, true)
.then(function (newProperty) {
return _.set(objectToPopulate, propertyPath, newProperty);
})
.return();
populateAll.push(populateSingleProperty);
}
});
return BbPromise.all(populateAll).then(function () { return objectToPopulate; });
};
Variables.prototype.populateProperty = function (propertyParam, populateInPlace) {
var _this = this;
var property = populateInPlace ? propertyParam : _.cloneDeep(propertyParam);
var allValuesToPopulate = [];
var warned = false;
if (typeof property === 'string' && property.match(this.variableSyntax)) {
property.match(this.variableSyntax).forEach(function (matchedString) {
var variableString = matchedString
.replace(_this.variableSyntax, function (match, varName) { return varName.trim(); })
.replace(/\s/g, '');
var singleValueToPopulate = null;
if (variableString.match(_this.overwriteSyntax)) {
singleValueToPopulate = _this.overwrite(variableString);
}
else {
singleValueToPopulate = _this.getValueFromSource(variableString).then(function (valueToPopulate) {
if (typeof valueToPopulate === 'object') {
return _this.populateObject(valueToPopulate);
}
return valueToPopulate;
});
}
singleValueToPopulate = singleValueToPopulate.then(function (valueToPopulate) {
if (_this.warnIfNotFound(variableString, valueToPopulate)) {
warned = true;
}
return _this.populateVariable(property, matchedString, valueToPopulate).then(function (newProperty) {
property = newProperty;
return BbPromise.resolve(property);
});
});
allValuesToPopulate.push(singleValueToPopulate);
});
return BbPromise.all(allValuesToPopulate).then(function () {
if (property !== _this.json && !warned) {
return _this.populateProperty(property);
}
return BbPromise.resolve(property);
});
}
// return property;
return BbPromise.resolve(property);
};
Variables.prototype.populateVariable = function (propertyParam, matchedString, valueToPopulate) {
var property = propertyParam;
if (typeof valueToPopulate === 'string') {
property = replaceall(matchedString, valueToPopulate, property);
}
else {
if (property !== matchedString) {
if (typeof valueToPopulate === 'number') {
property = replaceall(matchedString, String(valueToPopulate), property);
}
else {
var errorMessage = [
'Trying to populate non string value into',
" a string for variable " + matchedString + ".",
' Please make sure the value of the property is a string.',
].join('');
this.out.warn(this.out.getErrorPrefix(this.fileName, 'warning') + errorMessage);
}
return BbPromise.resolve(property);
}
property = valueToPopulate;
}
return BbPromise.resolve(property);
};
Variables.prototype.overwrite = function (variableStringsString) {
var _this = this;
var finalValue;
var variableStringsArray = variableStringsString.split(',');
var allValuesFromSource = variableStringsArray.map(function (variableString) {
return _this.getValueFromSource(variableString);
});
return BbPromise.all(allValuesFromSource).then(function (valuesFromSources) {
valuesFromSources.find(function (valueFromSource) {
finalValue = valueFromSource;
return (finalValue !== null &&
typeof finalValue !== 'undefined' &&
!(typeof finalValue === 'object' && _.isEmpty(finalValue)));
});
return BbPromise.resolve(finalValue);
});
};
Variables.prototype.getValueFromSource = function (variableString) {
if (variableString.match(this.envRefSyntax)) {
return this.getValueFromEnv(variableString);
}
else if (variableString.match(this.optRefSyntax)) {
return this.getValueFromOptions(variableString);
}
else if (variableString.match(this.selfRefSyntax)) {
return this.getValueFromSelf(variableString);
// } else if (variableString.match(this.fileRefSyntax)) {
// return this.getValueFromFile(variableString);
// } else if (variableString.match(this.cfRefSyntax)) {
// return this.getValueFromCf(variableString);
// } else if (variableString.match(this.s3RefSyntax)) {
// return this.getValueFromS3(variableString);
}
else if (variableString.match(this.stringRefSyntax)) {
return this.getValueFromString(variableString);
// } else if (variableString.match(this.ssmRefSyntax)) {
// return this.getValueFromSsm(variableString);
}
var errorMessage = [
"Invalid variable reference syntax for variable " + variableString + ".",
' You can only reference env vars, options, & files.',
' You can check our docs for more info.',
].join('');
this.out.warn(this.out.getErrorPrefix(this.fileName, 'warning') + errorMessage);
};
Variables.prototype.getValueFromEnv = function (variableString) {
var requestedEnvVar = variableString.split(':')[1];
var valueToPopulate = requestedEnvVar !== '' || '' in this.envVars
? this.envVars[requestedEnvVar]
: this.envVars;
return BbPromise.resolve(valueToPopulate);
};
Variables.prototype.getValueFromString = function (variableString) {
var valueToPopulate = variableString.replace(/^['"]|['"]$/g, '');
return BbPromise.resolve(valueToPopulate);
};
Variables.prototype.getValueFromOptions = function (variableString) {
var requestedOption = variableString.split(':')[1];
var valueToPopulate = requestedOption !== '' || '' in this.options
? this.options[requestedOption]
: this.options;
return BbPromise.resolve(valueToPopulate);
};
Variables.prototype.getValueFromSelf = function (variableString) {
var valueToPopulate = this.json;
var deepProperties = variableString.split(':')[1].split('.');
return this.getDeepValue(deepProperties, valueToPopulate);
};
// getValueFromFile(variableString) {
// const matchedFileRefString = variableString.match(this.fileRefSyntax)[0];
// const referencedFileRelativePath = matchedFileRefString
// .replace(this.fileRefSyntax, (match, varName) => varName.trim())
// .replace('~', os.homedir());
//
// const referencedFileFullPath = (path.isAbsolute(referencedFileRelativePath) ?
// referencedFileRelativePath :
// path.join(this.prisma.config.servicePath, referencedFileRelativePath));
// let fileExtension = referencedFileRelativePath.split('.');
// fileExtension = fileExtension[fileExtension.length - 1];
// // Validate file exists
// if (!this.prisma.utils.fileExistsSync(referencedFileFullPath)) {
// return BbPromise.resolve(undefined);
// }
//
// let valueToPopulate;
//
// // Process JS files
// if (fileExtension === 'js') {
// const jsFile = require(referencedFileFullPath); // eslint-disable-line global-require
// const variableArray = variableString.split(':');
// let returnValueFunction;
// if (variableArray[1]) {
// let jsModule = variableArray[1];
// jsModule = jsModule.split('.')[0];
// returnValueFunction = jsFile[jsModule];
// } else {
// returnValueFunction = jsFile;
// }
//
// if (typeof returnValueFunction !== 'function') {
// throw new this.prisma.classes
// .Error([
// 'Invalid variable syntax when referencing',
// ` file "${referencedFileRelativePath}".`,
// ' Check if your javascript is exporting a function that returns a value.',
// ].join(''));
// }
// valueToPopulate = returnValueFunction.call(jsFile);
//
// return BbPromise.resolve(valueToPopulate).then(valueToPopulateResolved => {
// let deepProperties = variableString.replace(matchedFileRefString, '');
// deepProperties = deepProperties.slice(1).split('.');
// deepProperties.splice(0, 1);
// return this.getDeepValue(deepProperties, valueToPopulateResolved)
// .then(deepValueToPopulateResolved => {
// if (typeof deepValueToPopulateResolved === 'undefined') {
// const errorMessage = [
// 'Invalid variable syntax when referencing',
// ` file "${referencedFileRelativePath}".`,
// ' Check if your javascript is returning the correct data.',
// ].join('');
// throw new this.prisma.classes
// .Error(errorMessage);
// }
// return BbPromise.resolve(deepValueToPopulateResolved);
// });
// });
// }
//
// // Process everything except JS
// if (fileExtension !== 'js') {
// valueToPopulate = this.prisma.utils.readFileSync(referencedFileFullPath);
// if (matchedFileRefString !== variableString) {
// let deepProperties = variableString
// .replace(matchedFileRefString, '');
// if (deepProperties.substring(0, 1) !== ':') {
// const errorMessage = [
// 'Invalid variable syntax when referencing',
// ` file "${referencedFileRelativePath}" sub properties`,
// ' Please use ":" to reference sub properties.',
// ].join('');
// throw new this.prisma.classes
// .Error(errorMessage);
// }
// deepProperties = deepProperties.slice(1).split('.');
// return this.getDeepValue(deepProperties, valueToPopulate);
// }
// }
// return BbPromise.resolve(valueToPopulate);
// }
//
// getValueFromCf(variableString) {
// const variableStringWithoutSource = variableString.split(':')[1].split('.');
// const stackName = variableStringWithoutSource[0];
// const outputLogicalId = variableStringWithoutSource[1];
// return this.prisma.getProvider('aws')
// .request('CloudFormation',
// 'describeStacks',
// { StackName: stackName },
// this.options.stage,
// this.options.region)
// .then(result => {
// const outputs = result.Stacks[0].Outputs;
// const output = outputs.find(x => x.OutputKey === outputLogicalId);
//
// if (output === undefined) {
// const errorMessage = [
// 'Trying to request a non exported variable from CloudFormation.',
// ` Stack name: "${stackName}"`,
// ` Requested variable: "${outputLogicalId}".`,
// ].join('');
// throw new this.prisma.classes
// .Error(errorMessage);
// }
//
// return output.OutputValue;
// });
// }
//
// getValueFromS3(variableString) {
// const groups = variableString.match(this.s3RefSyntax);
// const bucket = groups[1];
// const key = groups[2];
// return this.prisma.getProvider('aws')
// .request('S3',
// 'getObject',
// {
// Bucket: bucket,
// Key: key,
// },
// this.options.stage,
// this.options.region)
// .then(
// response => response.Body.toString(),
// err => {
// const errorMessage = `Error getting value for ${variableString}. ${err.message}`;
// throw new this.prisma.classes.Error(errorMessage);
// }
// );
// }
//
// getValueFromSsm(variableString) {
// const groups = variableString.match(this.ssmRefSyntax);
// const param = groups[1];
// const decrypt = (groups[2] === 'true');
// return this.prisma.getProvider('aws')
// .request('SSM',
// 'getParameter',
// {
// Name: param,
// WithDecryption: decrypt,
// },
// this.options.stage,
// this.options.region)
// .then(
// response => BbPromise.resolve(response.Parameter.Value),
// err => {
// const expectedErrorMessage = `Parameter ${param} not found.`;
// if (err.message !== expectedErrorMessage) {
// throw new this.prisma.classes.Error(err.message);
// }
// return BbPromise.resolve(undefined);
// }
// );
// }
Variables.prototype.getDeepValue = function (deepProperties, valueToPopulate) {
var _this = this;
return BbPromise.reduce(deepProperties, function (computedValueToPopulateParam, subProperty) {
var computedValueToPopulate = computedValueToPopulateParam;
if (typeof computedValueToPopulate === 'undefined') {
computedValueToPopulate = {};
}
else if (subProperty !== '' || '' in computedValueToPopulate) {
computedValueToPopulate = computedValueToPopulate[subProperty];
}
if (typeof computedValueToPopulate === 'string' &&
computedValueToPopulate.match(_this.variableSyntax)) {
return _this.populateProperty(computedValueToPopulate);
}
return BbPromise.resolve(computedValueToPopulate);
}, valueToPopulate);
};
Variables.prototype.warnIfNotFound = function (variableString, valueToPopulate) {
if (valueToPopulate === null ||
typeof valueToPopulate === 'undefined' ||
(typeof valueToPopulate === 'object' && _.isEmpty(valueToPopulate))) {
var varType = void 0;
if (variableString.match(this.envRefSyntax)) {
varType = 'environment variable';
}
else if (variableString.match(this.optRefSyntax)) {
varType = 'option';
}
else if (variableString.match(this.selfRefSyntax)) {
varType = 'self reference';
// } else if (variableString.match(this.fileRefSyntax)) {
// varType = 'file';
// } else if (variableString.match(this.ssmRefSyntax)) {
// varType = 'SSM parameter';
}
this.out.warn(this.out.getErrorPrefix(this.fileName, 'warning') +
("A valid " + varType + " to satisfy the declaration '" + variableString + "' could not be found."));
return true;
}
return false;
};
return Variables;
}());
exports.Variables = Variables;
//# sourceMappingURL=Variables.js.map
;