How to use @optimizely/js-sdk-utils - 10 common examples

To help you get started, we’ve selected a few @optimizely/js-sdk-utils examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github optimizely / javascript-sdk / packages / optimizely-sdk / lib / core / bucketer / index.js View on Github external
// Return if user is bucketed into a different experiment than the one specified
        if (bucketedExperimentId !== bucketerParams.experimentId) {
          var notBucketedIntoExperimentOfGroupLogMessage = sprintf(LOG_MESSAGES.USER_NOT_BUCKETED_INTO_EXPERIMENT_IN_GROUP, MODULE_NAME, bucketerParams.userId, bucketerParams.experimentKey, groupId);
          bucketerParams.logger.log(LOG_LEVEL.INFO, notBucketedIntoExperimentOfGroupLogMessage);
          return null;
        }

        // Continue bucketing if user is bucketed into specified experiment
        var bucketedIntoExperimentOfGroupLogMessage = sprintf(LOG_MESSAGES.USER_BUCKETED_INTO_EXPERIMENT_IN_GROUP, MODULE_NAME, bucketerParams.userId, bucketerParams.experimentKey, groupId);
        bucketerParams.logger.log(LOG_LEVEL.INFO, bucketedIntoExperimentOfGroupLogMessage);
      }
    }
    var bucketingId = sprintf('%s%s', bucketerParams.bucketingId, bucketerParams.experimentId);
    var bucketValue = module.exports._generateBucketValue(bucketingId);

    var bucketedUserLogMessage = sprintf(LOG_MESSAGES.USER_ASSIGNED_TO_VARIATION_BUCKET, MODULE_NAME, bucketValue, bucketerParams.userId);
    bucketerParams.logger.log(LOG_LEVEL.DEBUG, bucketedUserLogMessage);

    var entityId = module.exports._findBucket(bucketValue, bucketerParams.trafficAllocationConfig);
    if (entityId === null || entityId === '') {
      var userHasNoVariationLogMessage = sprintf(LOG_MESSAGES.USER_HAS_NO_VARIATION, MODULE_NAME, bucketerParams.userId, bucketerParams.experimentKey);
      bucketerParams.logger.log(LOG_LEVEL.DEBUG, userHasNoVariationLogMessage);
    } else if (!bucketerParams.variationIdMap.hasOwnProperty(entityId)) {
      var invalidVariationIdLogMessage = sprintf(LOG_MESSAGES.INVALID_VARIATION_ID, MODULE_NAME);
      bucketerParams.logger.log(LOG_LEVEL.WARNING, invalidVariationIdLogMessage);
      return null;
    } else {
      var variationKey = bucketerParams.variationIdMap[entityId].key;
      var userInVariationLogMessage = sprintf(LOG_MESSAGES.USER_HAS_VARIATION, MODULE_NAME, bucketerParams.userId, variationKey, bucketerParams.experimentKey);
      bucketerParams.logger.log(LOG_LEVEL.INFO, userInVariationLogMessage);
    }
github optimizely / javascript-sdk / packages / optimizely-sdk / lib / core / bucketer / index.js View on Github external
return null;
        }

        // Return if user is bucketed into a different experiment than the one specified
        if (bucketedExperimentId !== bucketerParams.experimentId) {
          var notBucketedIntoExperimentOfGroupLogMessage = sprintf(LOG_MESSAGES.USER_NOT_BUCKETED_INTO_EXPERIMENT_IN_GROUP, MODULE_NAME, bucketerParams.userId, bucketerParams.experimentKey, groupId);
          bucketerParams.logger.log(LOG_LEVEL.INFO, notBucketedIntoExperimentOfGroupLogMessage);
          return null;
        }

        // Continue bucketing if user is bucketed into specified experiment
        var bucketedIntoExperimentOfGroupLogMessage = sprintf(LOG_MESSAGES.USER_BUCKETED_INTO_EXPERIMENT_IN_GROUP, MODULE_NAME, bucketerParams.userId, bucketerParams.experimentKey, groupId);
        bucketerParams.logger.log(LOG_LEVEL.INFO, bucketedIntoExperimentOfGroupLogMessage);
      }
    }
    var bucketingId = sprintf('%s%s', bucketerParams.bucketingId, bucketerParams.experimentId);
    var bucketValue = module.exports._generateBucketValue(bucketingId);

    var bucketedUserLogMessage = sprintf(LOG_MESSAGES.USER_ASSIGNED_TO_VARIATION_BUCKET, MODULE_NAME, bucketValue, bucketerParams.userId);
    bucketerParams.logger.log(LOG_LEVEL.DEBUG, bucketedUserLogMessage);

    var entityId = module.exports._findBucket(bucketValue, bucketerParams.trafficAllocationConfig);
    if (entityId === null || entityId === '') {
      var userHasNoVariationLogMessage = sprintf(LOG_MESSAGES.USER_HAS_NO_VARIATION, MODULE_NAME, bucketerParams.userId, bucketerParams.experimentKey);
      bucketerParams.logger.log(LOG_LEVEL.DEBUG, userHasNoVariationLogMessage);
    } else if (!bucketerParams.variationIdMap.hasOwnProperty(entityId)) {
      var invalidVariationIdLogMessage = sprintf(LOG_MESSAGES.INVALID_VARIATION_ID, MODULE_NAME);
      bucketerParams.logger.log(LOG_LEVEL.WARNING, invalidVariationIdLogMessage);
      return null;
    } else {
      var variationKey = bucketerParams.variationIdMap[entityId].key;
      var userInVariationLogMessage = sprintf(LOG_MESSAGES.USER_HAS_VARIATION, MODULE_NAME, bucketerParams.userId, variationKey, bucketerParams.experimentKey);
github optimizely / javascript-sdk / packages / models / src / models.ts View on Github external
// these must be constructed separately
    variations: Variation[]
    group?: Group
  }) {
    this._id = id
    this._status = status
    this._key = key
    this._layerId = layerId
    this._audienceIds = audienceIds
    this._variations = variations
    this._forcedVariations = forcedVariations
    this._group = group

    this.trafficAllocation = new OptimizelyTrafficAllocation({
      allocations: trafficAllocation,
      entityIdMap: keyBy(variations, variation => variation.id),
    })
  }
github optimizely / javascript-sdk / packages / optimizely-sdk / lib / core / project_config / project_config_manager.tests.js View on Github external
it('should call the error handler and fulfill onReady with an unsuccessful result if neither datafile nor sdkKey are passed into the constructor', function() {
    var manager = new projectConfigManager.ProjectConfigManager({
      skipJSONValidation: true,
    });
    sinon.assert.calledOnce(globalStubErrorHandler.handleError);
    var errorMessage = globalStubErrorHandler.handleError.lastCall.args[0].message;
    assert.strictEqual(errorMessage, sprintf(ERROR_MESSAGES.DATAFILE_AND_SDK_KEY_MISSING, 'PROJECT_CONFIG_MANAGER'));
    return manager.onReady().then(function(result) {
      assert.include(result, {
        success: false,
      });
    });
  });
github optimizely / javascript-sdk / packages / event-processor / __tests__ / v1EventProcessor.spec.ts View on Github external
sendNotifications: jest.fn()
      }

      const processor = new LogTierV1EventProcessor({
        dispatcher,
        notificationCenter,
        maxQueueSize: 1,
      })
      processor.start()

      const impressionEvent1 = createImpressionEvent()
      processor.process(impressionEvent1)

      expect(notificationCenter.sendNotifications).toBeCalledTimes(1)
      const event = (dispatcher.dispatchEvent as jest.Mock).mock.calls[0][0]
      expect(notificationCenter.sendNotifications).toBeCalledWith(NOTIFICATION_TYPES.LOG_EVENT, event)
    })
  })
github optimizely / javascript-sdk / packages / optimizely-sdk / lib / core / custom_attribute_condition_evaluator / index.js View on Github external
var userValue = userAttributes[conditionName];
  var userValueType = typeof userValue;
  var conditionValue = condition.value;

  if (!fns.isFinite(conditionValue)) {
    logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNEXPECTED_CONDITION_VALUE, MODULE_NAME, JSON.stringify(condition)));
    return null;
  }

  if (userValue === null) {
    logger.log(LOG_LEVEL.DEBUG, sprintf(LOG_MESSAGES.UNEXPECTED_TYPE_NULL, MODULE_NAME, JSON.stringify(condition), conditionName));
    return null;
  }

  if (!fns.isNumber(userValue)) {
    logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.UNEXPECTED_TYPE, MODULE_NAME, JSON.stringify(condition), userValueType, conditionName));
    return null;
  }

  if (!fns.isFinite(userValue)) {
    logger.log(LOG_LEVEL.WARNING, sprintf(LOG_MESSAGES.OUT_OF_BOUNDS, MODULE_NAME, JSON.stringify(condition), conditionName));
    return null;
  }

  return userValue > conditionValue;
}
github optimizely / javascript-sdk / packages / optimizely-sdk / lib / optimizely / index.js View on Github external
);
    return null;
  }

  var decision = this.decisionService.getVariationForFeature(this.configObj, featureFlag, userId, attributes);
  var variableValue;
  if (decision.variation !== null) {
    variableValue = projectConfig.getVariableValueForVariation(
      this.configObj,
      variable,
      decision.variation,
      this.logger
    );
    this.logger.log(
      LOG_LEVEL.INFO,
      sprintf(
        LOG_MESSAGES.USER_RECEIVED_VARIABLE_VALUE,
        MODULE_NAME,
        variableKey,
        featureFlag.key,
        variableValue,
        userId
      )
    );
  } else {
    variableValue = variable.defaultValue;
    this.logger.log(
      LOG_LEVEL.INFO,
      sprintf(LOG_MESSAGES.USER_RECEIVED_DEFAULT_VARIABLE_VALUE, MODULE_NAME, userId, variableKey, featureFlag.key)
    );
  }
github optimizely / javascript-sdk / packages / optimizely-sdk / lib / core / project_config / index.js View on Github external
tryCreatingProjectConfig: function(config) {
    configValidator.validateDatafile(config.datafile);
    if (config.skipJSONValidation === true) {
      config.logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.SKIPPING_JSON_VALIDATION, MODULE_NAME));
    } else if (config.jsonSchemaValidator) {
      config.jsonSchemaValidator.validate(projectConfigSchema, config.datafile);
      config.logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.VALID_DATAFILE, MODULE_NAME));
    }
    return module.exports.createProjectConfig(config.datafile);
  },
};
github optimizely / javascript-sdk / packages / optimizely-sdk / lib / core / decision_service / index.js View on Github external
DecisionService.prototype.__getWhitelistedVariation = function(experiment, userId) {
  if (!fns.isEmpty(experiment.forcedVariations) && experiment.forcedVariations.hasOwnProperty(userId)) {
    var forcedVariationKey = experiment.forcedVariations[userId];
    if (experiment.variationKeyMap.hasOwnProperty(forcedVariationKey)) {
      var forcedBucketingSucceededMessageLog = sprintf(LOG_MESSAGES.USER_FORCED_IN_VARIATION, MODULE_NAME, userId, forcedVariationKey);
      this.logger.log(LOG_LEVEL.INFO, forcedBucketingSucceededMessageLog);
      return experiment.variationKeyMap[forcedVariationKey];
    } else {
      var forcedBucketingFailedMessageLog = sprintf(LOG_MESSAGES.FORCED_BUCKETING_FAILED, MODULE_NAME, forcedVariationKey, userId);
      this.logger.log(LOG_LEVEL.ERROR, forcedBucketingFailedMessageLog);
      return null;
    }
  }

  return null;
};
github optimizely / javascript-sdk / packages / optimizely-sdk / lib / utils / json_schema_validator / index.js View on Github external
if (!jsonSchema) {
      throw new Error(sprintf(ERROR_MESSAGES.JSON_SCHEMA_EXPECTED, MODULE_NAME));
    }

    if (!jsonObject) {
      throw new Error(sprintf(ERROR_MESSAGES.NO_JSON_PROVIDED, MODULE_NAME));
    }

    var result = validate(jsonObject, jsonSchema);
    if (result.valid) {
      return true;
    } else {
      if (fns.isArray(result.errors)) {
        throw new Error(sprintf(ERROR_MESSAGES.INVALID_DATAFILE, MODULE_NAME, result.errors[0].property, result.errors[0].message));
      }
      throw new Error(sprintf(ERROR_MESSAGES.INVALID_JSON, MODULE_NAME));
    }
  }
};