'use strict';

const { resolve } = require('path');

const { addGenErrorHandler } = require('../../../../error');
const { mapValues, renderTemplate } = require('../../../../utilities');

const TEMPLATE = resolve(__dirname, './graphiql.mustache');

// Returns HTML document loading a GraphQL debugger
// TODO: replace with graphiql-workspace
// TODO: do not use CDN
// TODO: do proper web app setup, not all-in-one HTML file
//
// @param {object} options
// @param {string} options.endpointURL - the relative or absolute URL for
// the endpoint which GraphiQL will make queries to
// @param {string} [options.query] - the GraphQL query to pre-fill
// @param {object|json} [options.variables] - variables to pre-fill
// @param {string} [options.operationName] - the operationName to pre-fill
// @param {string} [options.result] - the result of the query to pre-fill
//
// @returns {string} document - HTML document
const renderGraphiql = function (input) {
  // Those must be valid JavaScript, so must JSON-stringified
  const dataToEscape = getDataToEscape(input);
  // Those must be valid HTML
  const dataNotToEscape = {};
  const data = { ...escapeData(dataToEscape), ...dataNotToEscape };

  return renderTemplate({ template: TEMPLATE, data });
};

const eRenderGraphiql = addGenErrorHandler(renderGraphiql, {
  message: 'Could not render GraphiQL HTML document',
  reason: 'UTILITY_ERROR',
});

const getDataToEscape = function (input) {
  return {
    endpointURL: input.endpointURL,
    query: input.query || '',
    variables: input.variables || '',
    operationName: input.operationName || '',
  };
};

const escapeData = function (dataToEscape) {
  return mapValues(dataToEscape, data => escapeJSON(data));
};

const escapeJSON = function (string = null) {
  return JSON.stringify(string, null, 2);
};

module.exports = {
  renderGraphiql: eRenderGraphiql,
};

@@ -1430,157 +1430,238 @@
 on (
-input) %7B%0A  return %7B%0A    endpointURL: input.endpointURL,%0A    query: input.query %7C%7C '',%0A    variables: input.variables %7C%7C '',%0A    operationName: input.
+%7B%0A  endpointURL,%0A  query = '',%0A  variables = '',%0A  operationName = '',%0A%7D) %7B%0A  const variablesA = typeof variables === 'object'%0A    ? JSON.stringify(variables)%0A    : variables;%0A  return %7B endpointURL, query, variables: variablesA, 
 oper
@@ -1674,17 +1674,8 @@
 ame 
-%7C%7C '',%0A  
 %7D;%0A%7D

Fix GraphiQL variables transtyping