@amplitude/ampli
Version:
Amplitude CLI
352 lines (351 loc) • 12.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.userKey = exports.deserializeConfig = exports.projectConfigPaths = exports.userConfigPaths = exports.getSettings = exports.initSettings = exports.Settings = void 0;
const Conf = require("conf");
const path = require("path");
const schema_1 = require("./schema");
const SettingsLoadError_1 = require("../errors/SettingsLoadError");
const mergeConflicts_1 = require("../util/git/mergeConflicts");
const types_1 = require("../types");
const constants_1 = require("../constants");
const LEGACY_FILE_NAME = '';
const CONFIG_FILE_NAME = 'ampli';
const LEGACY_FILE_EXTENSION = 'itlyrc';
const CONFIG_FILE_EXTENSION = 'json';
const ACCESS_TOKEN = 'OAuthAccessToken';
const ID_TOKEN = 'OAuthIdToken';
const REFRESH_TOKEN = 'OAuthRefreshToken';
const EXPIRES_AT = 'OAuthExpiresAt';
const configParser = {
serialize: (value) => JSON.stringify(value, null, 2),
deserialize: deserializeConfig,
};
class Settings {
init(createUserConfig, createProjectConfig, createUserTokensConfig) {
this.createUserConfig = createUserConfig;
this.createProjectConfig = createProjectConfig;
this.createUserTokensConfig = createUserTokensConfig;
}
get user() {
if (!this.userConfig) {
this.userConfig = this.createUserConfig();
}
return this.userConfig;
}
get project() {
if (!this.projectConfig) {
this.projectConfig = this.createProjectConfig();
}
return this.projectConfig;
}
get userTokens() {
if (this.createUserTokensConfig == null) {
return this.user;
}
if (!this.userTokensConfig) {
this.userTokensConfig = this.createUserTokensConfig();
}
return this.userTokensConfig;
}
set(key, value, level) {
if (value === undefined) {
throw new Error(`Something went wrong and we're not able to proceed (there was a problem persisting '${key}' to settings). Please contact us at https://support.amplitude.com.`);
}
if (level === 'user') {
this.user.set(key, value);
}
else if (level === 'project') {
this.project.set(key, value);
}
else {
this.userTokens.set(key, value);
}
}
get(key, level) {
if (level === 'user') {
return this.user.get(key);
}
if (level === 'project') {
return this.project.get(key);
}
return this.userTokens.get(key);
}
setUserValue(userId, key, value, level) {
this.set(userKey(userId.id, userId.zone, key), value, level);
}
setProjectValue(key, value) {
this.set(key, value, 'project');
}
getUserValue(userId, key, level) {
return this.get(userKey(userId.id, userId.zone, key), level);
}
getProjectValue(key) {
return this.get(key, 'project');
}
hasProjectValue(key) {
return this.project.has(key);
}
unsetProjectValue(key) {
if (this.hasProjectValue(key)) {
this.project.delete(key);
}
}
projectUser() {
const orgId = this.getOrgId();
if (!orgId) {
return undefined;
}
const zone = this.getZone() || types_1.DEFAULT_ZONE;
return this.users(zone).find(u => u.orgs && u.orgs.some((org) => org.id === orgId));
}
getOrgId() {
return this.getProjectValue('OrgId');
}
setOrgId(orgId) {
this.setProjectValue('OrgId', orgId);
}
getWorkspaceId() {
return this.getProjectValue('WorkspaceId');
}
setWorkspaceId(workspaceId) {
this.setProjectValue('WorkspaceId', workspaceId);
}
setUser(user) {
this.setUserValue({ id: user.id, zone: user.zone }, 'User', user, 'user');
}
getSourceId() {
return this.getProjectValue('SourceId');
}
setSourceId(sourceId) {
this.setProjectValue('SourceId', sourceId);
}
getRuntime(allRuntimes) {
const code = this.getProjectValue('Runtime');
const platform = this.getProjectValue('Platform');
const language = this.getProjectValue('Language');
const sdk = this.getProjectValue('SDK');
if (platform && language && sdk) {
const runtime = allRuntimes.find(r => r.platform.name === platform && r.language.name === language && r.sdk === sdk);
if (runtime) {
return runtime;
}
}
if (code) {
return allRuntimes.find(r => r.code === code);
}
return undefined;
}
getRawRuntime() {
const code = this.getProjectValue('Runtime');
const platform = this.getProjectValue('Platform');
const language = this.getProjectValue('Language');
const sdk = this.getProjectValue('SDK');
return { code, platform, language, sdk };
}
setRuntime(runtime) {
this.setProjectValue('Runtime', runtime.code);
this.setProjectValue('Platform', runtime.platform.name);
this.setProjectValue('Language', runtime.language.name);
this.setProjectValue('SDK', runtime.sdk);
}
getBranch() {
return this.getProjectValue('Branch');
}
setBranch(branch) {
this.setProjectValue('Branch', branch);
}
unsetBranch() {
this.unsetProjectValue('Branch');
}
getVersion() {
return this.getProjectValue('Version');
}
setVersion(version) {
this.setProjectValue('Version', version);
}
getVersionId() {
return this.getProjectValue('VersionId');
}
setVersionId(versionId) {
this.setProjectValue('VersionId', versionId);
}
getPath() {
return this.getProjectValue('Path');
}
setPath(projectPath) {
this.setProjectValue('Path', projectPath);
}
getZone() {
return this.getProjectValue('Zone');
}
setZone(zone) {
this.setProjectValue('Zone', zone);
}
getOmitApiKeys() {
return this.getProjectValue('OmitApiKeys');
}
setOmitApiKeys(omitApiKeys) {
if (omitApiKeys) {
this.setProjectValue('OmitApiKeys', omitApiKeys);
}
else {
this.unsetProjectValue('OmitApiKeys');
}
}
getSourceDirs() {
return this.getProjectValue('SourceDirs');
}
setSourceDirs(sourceDirs) {
if (sourceDirs.length > 0) {
this.setProjectValue('SourceDirs', sourceDirs);
}
else {
this.unsetProjectValue('SourceDirs');
}
}
getInstanceNames() {
return this.getProjectValue('InstanceNames');
}
setInstanceNames(instanceNames) {
if (instanceNames.length > 0) {
this.setProjectValue('InstanceNames', instanceNames);
}
else {
this.unsetProjectValue('InstanceNames');
}
}
hasOAuthToken() {
const { userId, token } = this.getOAuthToken();
if (!userId) {
return false;
}
const { refresh_token, access_token, id_token, expires_in } = token;
return !!refresh_token && !!access_token && !!id_token && !!expires_in;
}
getOAuthToken(userId) {
if (!userId) {
const user = this.projectUser();
if (!user) {
return {
userId: undefined,
token: {},
};
}
userId = { id: user.id, zone: user.zone };
}
const expiresAt = this.getUserValue(userId, EXPIRES_AT, 'user-tokens');
const expiresIn = expiresAt ? ((new Date(expiresAt).getTime() - new Date().getTime()) / 1000) : -1;
return {
userId,
token: {
refresh_token: this.getUserValue(userId, REFRESH_TOKEN, 'user-tokens'),
access_token: this.getUserValue(userId, ACCESS_TOKEN, 'user-tokens'),
id_token: this.getUserValue(userId, ID_TOKEN, 'user-tokens'),
expires_in: expiresIn.toString(),
},
};
}
setOAuthToken(userId, accessToken) {
const { data: token } = accessToken;
if (token.refresh_token) {
this.setUserValue(userId, REFRESH_TOKEN, token.refresh_token, 'user-tokens');
}
this.setUserValue(userId, ACCESS_TOKEN, token.access_token, 'user-tokens');
this.setUserValue(userId, ID_TOKEN, token.id_token, 'user-tokens');
this.setUserValue(userId, EXPIRES_AT, accessToken.expires, 'user-tokens');
}
users(zone, includeExpired = false) {
const users = [];
const now = new Date();
for (const item of this.user) {
let user = item[1].User;
const oAuthExpiresAt = item[1].OAuthExpiresAt;
const accessTokenExpiresAt = oAuthExpiresAt ? new Date(oAuthExpiresAt) : undefined;
const refreshTokenExpiredAt = accessTokenExpiresAt
? new Date((accessTokenExpiresAt.getTime() + (constants_1.OAuthRefreshTokenTTLHours - constants_1.OAuthAccessTokenTTLHours) * 60 * 60 * 1000))
: undefined;
if (user && (includeExpired || !refreshTokenExpiredAt || now < refreshTokenExpiredAt)) {
user = user.zone ? user : Object.assign(Object.assign({}, user), { zone: types_1.DEFAULT_ZONE });
if (!zone || user.zone === zone) {
users.push(user);
}
}
}
return users;
}
deleteUserData(user) {
const key = userKey(user.id, user.zone, '');
if (this.user.has(key)) {
this.user.delete(key);
}
}
}
exports.Settings = Settings;
let settingsInstance;
function initSettings(config) {
const CONFIG_OPTIONS = {
configName: CONFIG_FILE_NAME,
projectName: '',
projectSuffix: '',
fileExtension: CONFIG_FILE_EXTENSION,
serialize: configParser.serialize,
deserialize: configParser.deserialize,
accessPropertiesByDotNotation: true,
clearInvalidConfig: false,
};
const createUserConfig = () => new Conf(Object.assign(Object.assign({}, CONFIG_OPTIONS), { cwd: userDir(config === null || config === void 0 ? void 0 : config.userDir), schema: Object.assign({}, schema_1.userLevel) }));
const createProjectConfig = () => new Conf(Object.assign(Object.assign({}, CONFIG_OPTIONS), { cwd: projectDir(config === null || config === void 0 ? void 0 : config.projectDir), schema: Object.assign({}, schema_1.projectLevel) }));
const createUserTokensConfig = (config === null || config === void 0 ? void 0 : config.userTokensDir) != null
? () => new Conf(Object.assign(Object.assign({}, CONFIG_OPTIONS), { cwd: userDir(config === null || config === void 0 ? void 0 : config.userTokensDir), schema: Object.assign({}, schema_1.userLevel) }))
: undefined;
if (settingsInstance == null) {
settingsInstance = new Settings();
}
settingsInstance.init(createUserConfig, createProjectConfig, createUserTokensConfig);
return settingsInstance;
}
exports.initSettings = initSettings;
function getSettings() {
if (!settingsInstance) {
throw new Error(`Settings should be initialized.`);
}
return settingsInstance;
}
exports.getSettings = getSettings;
function userDir(dir) {
return dir || process.env.HOME || process.env.USERPROFILE || '';
}
function projectDir(dir) {
return dir || process.env.ITLYRC_PATH || process.cwd();
}
function userConfigPaths(dir) {
return {
legacy: path.join(userDir(dir), `${LEGACY_FILE_NAME}.${LEGACY_FILE_EXTENSION}`),
current: path.join(userDir(dir), `${CONFIG_FILE_NAME}.${CONFIG_FILE_EXTENSION}`),
};
}
exports.userConfigPaths = userConfigPaths;
function projectConfigPaths(dir) {
return {
legacy: path.join(projectDir(dir), `${LEGACY_FILE_NAME}.${LEGACY_FILE_EXTENSION}`),
current: path.join(projectDir(dir), `${CONFIG_FILE_NAME}.${CONFIG_FILE_EXTENSION}`),
};
}
exports.projectConfigPaths = projectConfigPaths;
function deserializeConfig(text) {
let config = {};
try {
config = JSON.parse(text);
}
catch (e) {
throw new SettingsLoadError_1.default(mergeConflicts_1.hasMergeConflicts(text)
? SettingsLoadError_1.SettingsLoadErrorCode.MERGE_CONFLICTS
: SettingsLoadError_1.SettingsLoadErrorCode.UNHANDLED_EXCEPTION);
}
return config;
}
exports.deserializeConfig = deserializeConfig;
function userKey(userId, zone, key) {
return `User${zone !== types_1.DEFAULT_ZONE ? `[${zone}]` : ''}-${userId.replace(/\./g, '-')}${key ? `.${key}` : ''}`;
}
exports.userKey = userKey;