declare local var.imgclass STRING;
declare local var.optAllowIOParams BOOL;
declare local var.optRequireValidClass BOOL;

set var.optAllowIOParams = true;
set var.optRequireValidClass = true;

if (req.url.ext ~ "(?i)^(gif|png|jpe?g|webp)$") {

  # Set the Fastly Image Optimizer header
  set req.http.X-Fastly-Imageopto-Api = "fastly";
  
  # Perform mapping of transformation class to native IO
  # params but only on edge servers (not at shield)
  if (fastly.ff.visits_this_service == 0) {
  
    # Optional: remove any query params that are not 'class'
    # to disallow use of native IO parameters by client
    if (!var.optAllowIOParams) {
      set req.url = querystring.filter_except(req.url, "class");
    }
   
    # Convert custom class tokens into native IO params
    if (subfield(req.url.qs, "class", "&")) {
      set var.imgclass = table.lookup(io_classes, subfield(req.url.qs, "class", "&"));

      # Fall back to default
      if (std.strlen(var.imgclass) == 0) {
        set var.imgclass = table.lookup(io_classes, "default");
      }
      
      if (var.imgclass) {
        set req.url = req.url.path + "?" + req.url.qs + "&" + var.imgclass;
        set req.url = querystring.filter(req.url, "class");
      }
    }
    
    # Optional: if no valid class is specified and there's no
    # default, generate a 404 error instead of allowing the
    # original of the image to be served
    if (!var.imgclass && var.optRequireValidClass) {
      error 404;
    }
    
  }
}