/* Write Custom Media from Common JS file
/* ==========================================================================
192051
async function writeCustomMediaToCjsFile(to, customMedia) {
	const jsContents = Object.keys(customMedia).reduce((jsLines, name) => {
		jsLines.push(`\t\t'${escapeForJS(name)}': '${escapeForJS(customMedia[name])}'`);

		return jsLines;
	}, []).join(',\n');
	const js = `module.exports = {\n\tcustomMedia: {\n${jsContents}\n\t}\n};\n`;

	await writeFile(to, js);
}
359948
function _replaceMediaSources( xmlDoc, mediaMap ) {
    if ( !mediaMap ) {
        return xmlDoc;
    }

    // iterate through each element with a src attribute
    xmlDoc.find( '//*[@src] | //a[@href]' ).forEach( mediaEl => {
        const attribute = ( mediaEl.name().toLowerCase() === 'a' ) ? 'href' : 'src';
        const src = mediaEl.attr( attribute ).value();
        const matches = src ? src.match( /jr:\/\/[\w-]+\/(.+)/ ) : null;
        const filename = matches && matches.length ? matches[ 1 ] : null;
        const replacement = filename ? mediaMap[ filename ] : null;
        if ( replacement ) {
            mediaEl.attr( attribute, replacement );
        }
    } );

    // add form logo <img> element if applicable
    const formLogo = mediaMap[ 'form_logo.png' ];
    const formLogoEl = xmlDoc.get( '//*[@class="form-logo"]' );
    if ( formLogo && formLogoEl ) {
        formLogoEl
            .node( 'img' )
            .attr( 'src', formLogo )
            .attr( 'alt', 'form logo' );
    }

    return xmlDoc;
}
457596
async function writeCustomPropertiesToMjsFile(to, customProperties) {
	const mjsContents = Object.keys(customProperties).reduce((mjsLines, name) => {
		mjsLines.push(`\t'${escapeForJS(name)}': '${escapeForJS(customProperties[name])}'`);

		return mjsLines;
	}, []).join(',\n');
	const mjs = `export const customProperties = {\n${mjsContents}\n};\n`;

	await writeFile(to, mjs);
}
654719
function processItem(item, options, processDone) {

  if (!item.path) {
    item.path = options.clientLibRoot;
  }

  options.verbose && console.log("\n\nprocessing clientlib: " + item.name);

  // remove current files if exists
  removeClientLib(item, function (err) {

    var clientLibPath = item.outputPath || path.join(item.path, item.name);

    // create clientlib directory
    fse.mkdirsSync(clientLibPath);

    var serializationFormat = (item.serializationFormat === SERIALIZATION_FORMAT_XML) ? SERIALIZATION_FORMAT_XML : SERIALIZATION_FORMAT_JSON;

    options.verbose && console.log("Write node configuration using serialization format: " + serializationFormat);

    if (serializationFormat === SERIALIZATION_FORMAT_JSON) {
        // write configuration JSON
        writeClientLibJson(item, options);
    } else {
        writeClientLibXml(item, options);
    }

    var assetList = normalizeAssets(clientLibPath, item.assets);

    // iterate through assets
    async.eachSeries(assetList, function (asset, assetDone) {

      // write clientlib creator files
      if (asset.type === "js" || asset.type === "css") {
        options.verbose && console.log("");
        writeAssetTxt(clientLibPath, asset, options);
      }

      // copy files for given asset
      async.eachSeries(asset.files, function (fileItem, copyDone) {
        if (fileItem.src == fileItem.dest) {
          options.verbose && console.log(`${fileItem.src} already in output directory`);
          return copyDone();
        }
        options.verbose && console.log("copy:", fileItem.src, fileItem.dest);
        if (options.dry) {
          return copyDone();
        }

        // create directories separately or it will be copied recursively
        if (fs.lstatSync(fileItem.src).isDirectory()) {
          fs.mkdir(fileItem.dest, copyDone);
        } else {
          fse.copy(fileItem.src, fileItem.dest, copyDone);
        }
      }, assetDone);

    }, processDone);
  });
}
239592
function browserifyTransform(file) {
    var chunks = [];

    var write = function(buffer) {
      chunks.push(buffer);
    };

    var end = function() {
      var content = Buffer.concat(chunks).toString('utf8');
      // convention fileName == key for shim options
      var fileName = file.match(/([^\/]+)(?=\.\w+$)/)[0];
      this.queue(commonjsify(content, options[fileName]));
      this.queue(null);
    };

    return through(write, end);
  }
305279
function writeFile(filename, content) {
  fs.writeFileSync(filename, JSON.stringify(content, null, 2));
}
1282581
function(file, content, callback) {
			fs.writeFile(file, content, 'ascii', function(err) {
				callback(err ? err : null);
			});
		}
615687
function writeFile(config, format) {

    // default is .js
    let extname = ".js";

    if (format === "YAML") {
        extname = ".yml";
    } else if (format === "JSON") {
        extname = ".json";
    }

    const installedESLint = config.installedESLint;

    delete config.installedESLint;

    ConfigFile.write(config, `./.eslintrc${extname}`);
    log.info(`Successfully created .eslintrc${extname} file in ${process.cwd()}`);

    if (installedESLint) {
        log.info("ESLint was installed locally. We recommend using this local copy instead of your globally-installed copy.");
    }
}
1340884
function buildJsFileContent(lines) {
    var ls = lines
        .map(l => l
            // remove space at beginning of line
            .replace(/^\s*/g, "")
            // remove space at end of line
            .replace(/\s*$/g, "")
            // convert \ to \\
            .replace(/\\/g, "\\\\")
            // convert " to \"
            .replace(/"/g, "\\\"")
            // convert " { " to "{"
            .replace(/\s*\{\s*/g, "{")
            // convert " : " to ":"
            .replace(/\s*:\s*/g, ":"))
        .join("")
        // remove comments
        .replace(/\/\*.+?\*\//g, "");

    return [
        // add css string
        `var css = "${ls}";`,
        "var enabled = false;",
        "",
        // add function which injects css into page
        "function enable () {",
        "\tif (enabled) return;",
        "\tenabled = true;",
        "",
        "\tvar el = document.createElement('style');",
        "\tel.innerHTML = css;",
        "",
        "\tvar parent = document.head || document.body;",
        "\tparent.firstChild ?",
        "\t\tparent.insertBefore(el, parent.firstChild) :",
        "\t\tparent.appendChild(el);",
        "}",
        "",
        "export {",
        "\tenable",
        "}"
    ].join("\n");
}
642459
async function writeCustomPropertiesToJsonFile(to, customProperties) {
	const jsonContent = JSON.stringify({
		'custom-properties': customProperties
	}, null, '  ');
	const json = `${jsonContent}\n`;

	await writeFile(to, json);
}
1118398
function jsCompile(content, file)
{
  // make it as a child of this module
  // Would be nice to actually make it transparent
  // and pretend it to be child of the caller module
  // but there is no obvious way, yet
  var jsMod = new Module(file, module);

  // override parents to exclude configly from the chain
  // it's like this js file is included directly
  // from the file that included `configly`
  while (jsMod.parent
    && typeof jsMod.parent.id === 'string'
    && jsMod.parent.id.match(/\/node_modules\/configly\//)
    && jsMod.parent.parent) {
    /* istanbul ignore next */
    jsMod.parent = jsMod.parent.parent;
  }

  // generate node_modules paths for the file
  jsMod.paths = Module._nodeModulePaths(path.dirname(file));

  // execute the module
  jsMod._compile(content, file);
  // return just exported object
  return jsMod.exports;
}
688540
function writeHTMLFile(options) {
  return new Promise(function(resolve, reject) {
    var templateFile = path.join(__dirname, '../template/cli.html');
     // read our template file
     fs.readFile(templateFile, 'utf8', function (err,data) {
      if (err) {
        reject(err);
      }
      // insert the generated json data
      var result = data.replace('{{ insertJSONHere }}', 'var embeddedJsonData = '+ options.json + ';');

      // write file to directory
      fs.writeFile(path.join(options.directory, 'index.html'), result, 'utf8', function (err) {
         if (err) {
          reject(err);
         }
         resolve(options.directory);
      });
    });
  });
}
971647
function write(file, cb) {
  if(file === undefined) file = this._file;

  if(file === DEFAULT_FILE) {
    return this.emit(
      'error', new Error('cannot write to default configuration'));
  }

  var sync = typeof cb !== 'function'
    , stream
    , save
    , encoder = new Encoder(this.options)
    , lines = this._lines
    , size = 32
    , i = 0
    , len = (lines.length / size);


  if(!file || typeof file !== 'string' && !(file instanceof Writable)){
    return this.emit('error',
      new Error('cannot write configuration, path or stream expected'));
  }

  if(typeof file === 'string') {
    file = resolve(file);
    save = file + Constants.SAVE;
  }

  if(sync && file && typeof file === 'string') {
    try {
      fs.writeFileSync(save, encoder.parse(this._lines));
      fs.renameSync(save, file);
    }catch(e) {
      /* istanbul ignore next: hard to mock a rename(2) error */
      return this.emit('error', e);
    }
    return encoder;
  }

  if(file instanceof Writable) {
    stream = file;
  }else{
    stream = fs.createWriteStream(save, this.options.read)
  }

  this.once('write', cb);

  function onFinish() {

    function onRename(err) {
      encoder.removeAllListeners('error');
      stream.removeAllListeners('error');
      /* istanbul ignore next: hard to mock a rename(2) error */
      if(err) return this.emit('error', err);
      this.emit('write', this);
    }

    onRename = onRename.bind(this);

    if(save) {
      fs.rename(save, file, onRename);
    }else{
      onRename();
    }

  }

  var onError = this.onError.bind(this);
  encoder.on('error', onError);
  stream.on('error', onError);

  stream.on('finish', onFinish.bind(this));
  encoder.pipe(stream);

  if((lines.length % size) !== 0) len++;

  // not a very large config
  if(lines.length < size) {
    encoder.end(lines);
    return encoder;
  }

  // split the work for larger config files
  function writeLines() {
    var chunk = lines.slice(i * size, (i * size) + size);

    // all done
    if(!chunk.length) {
      return encoder.end();
    }

    // ensure we get correct line break between
    // line chunks, the encoder joins lines on EOL
    // this means that the last line in the chunk array
    // does not have an EOL, we need to ensure it does
    if(i > 0) {
      chunk.unshift('');
    }

    // write out the line chunk
    encoder.write(chunk);
    setImmediate(writeLines);
    i++;
  }

  writeLines();
  return encoder;
}
787151
function promiseWriteFile(targetPath, content, tabs = 2) {
  const fileName = targetPath.split('/').pop();
  let contentHolder = content;

  if (targetPath.endsWith('.json')) {
    contentHolder = JSON.stringify(contentHolder, null, tabs);
  }

  return new Promise((resolve, reject) => {
    fs.writeFile(targetPath, contentHolder, err => {
      if (err) reject(err);

      resolve({
        path: targetPath,
        fileName,
        content: contentHolder
      });
    });
  });
}
770829
function makeWriteFile(anonDefRegExp, namespaceWithDot, layer) {
        function writeFile(name, contents) {
            logger.trace('Saving plugin-optimized file: ' + name);
            file.saveUtf8File(name, contents);
        }

        writeFile.asModule = function (moduleName, fileName, contents) {
            writeFile(fileName,
                build.toTransport(anonDefRegExp, namespaceWithDot, moduleName, fileName, contents, layer));
        };

        return writeFile;
    }
326488
async function exportCustomSelectorsToJsonFile(to, customSelectors) {
	const jsonContent = JSON.stringify({
		'custom-selectors': customSelectors
	}, null, '  ');
	const json = `${jsonContent}\n`;

	await writeFile(to, json);
}
1018569
function createStoryJS(c, src) {
  /* VARS
  ================================================== */
  var storyjs_embedjs, t, te, x,
    isCDN         = false,
    js_version        = "2.24",
    ready = {
      timeout:  "",
      checks:   0,
      finished: false,
      js:     false,
      css:    false,
      font: {
        css:  false
      }
    },
    path = {
      base:   embed_path,
      css:    embed_path + "css/",
      js:     embed_path + "js/",
      font: {
        google: false,
        css:  embed_path + "css/fonts/",
        js:   "//ajax.googleapis.com/ajax/libs/webfont/1/webfont.js"
      }
    },
    storyjs_e_config = {
      version:  js_version,
      debug:    false,
      type:   'timeline',
      id:     'storyjs',
      embed_id: 'timeline-embed',
      is_embed:   true,
      width:    '100%',
      height:   '100%',
      source:   'https://docs.google.com/spreadsheet/pub?key=0Agl_Dv6iEbDadFYzRjJPUGktY0NkWXFUWkVIZDNGRHc&output=html',
      lang:   'en',
      font:   'default',
      start_at_end: false,
      timenav_position: 'bottom',
      css:    path.css + 'timeline.css?'+js_version,
      js:     '',
      api_keys: {
        google:       "",
        flickr:       "",
        twitter:      ""
      },
      gmap_key:   ""
    }
  /* BUILD CONFIG
  ================================================== */
  if (typeof c == 'object') {
    for (x in c) {
      if (Object.prototype.hasOwnProperty.call(c, x)) {
        storyjs_e_config[x] = c[x];
      }
    }
  }

  if (typeof src != 'undefined') {
    storyjs_e_config.source = src;
  }

  /* CDN VERSION?
  ================================================== */
  if (typeof url_config == 'object') {
    isCDN = true;

    /* IS THE SOURCE GOOGLE SPREADSHEET WITH JUST THE KEY?
     * this is probably too clever a test but don't mess too much in case backwards compatibility
     * but we shouldn't put a rull URL into the key...
    ================================================== */
    if (!(storyjs_e_config.source.match("docs.google.com") 
        || storyjs_e_config.source.match("json$") 
        || storyjs_e_config.source.match("storify") 
        || storyjs_e_config.source.match("^http") 
      )) {
      storyjs_e_config.source = "https://docs.google.com/spreadsheet/pub?key=" + storyjs_e_config.source + "&output=html";
    }

  }

  /* DETERMINE TYPE
  ================================================== */
  if (storyjs_e_config.js.match("/")) {

  } else {
    storyjs_e_config.css  = path.css + storyjs_e_config.type + ".css?" + js_version;

    // Use unminified js file if in debug mode
    storyjs_e_config.js   = path.js  + storyjs_e_config.type;
    if (storyjs_e_config.debug) {
      storyjs_e_config.js += ".js?"  + js_version;
    } else {
      storyjs_e_config.js += "-min.js?"  + js_version;
    }

    storyjs_e_config.id   = "storyjs-" + storyjs_e_config.type;
  }

  /* PREPARE
  ================================================== */
  createEmbedDiv();

  /* Load CSS
  ================================================== */
  LoadLib.css(storyjs_e_config.css, onloaded_css);

  /* Load FONT
  ================================================== */
  if (storyjs_e_config.font == "default") {
    ready.font.css    = true;
  } else {
    // FONT CSS
    var fn;
    if (storyjs_e_config.font.match("/")) {
      fn        = storyjs_e_config.font.split(".css")[0].split("/");
      path.font.name  = fn[fn.length -1];
      path.font.css = storyjs_e_config.font;
    } else {
      path.font.name  = storyjs_e_config.font;
      path.font.css = path.font.css + "font."+storyjs_e_config.font.toLowerCase()+".css?" + js_version;
    }
    LoadLib.css(path.font.css, onloaded_font_css);
  }
    LoadLib.js(storyjs_e_config.js, onloaded_js);

  /* On Loaded
  ================================================== */

  function onloaded_js() {
    ready.js = true;
    onloaded_check();
  }

  function onloaded_css() {
    ready.css = true;
    onloaded_check();
  }
  function onloaded_font_css() {
    ready.font.css = true;
    onloaded_check();
  }
  function onloaded_check() {
    if (ready.checks > 40) {
      return;
      alert("Error Loading Files");
    } else {
      ready.checks++;
      if (ready.js && ready.css && ready.font.css) {
        if (!ready.finished) {
          ready.finished = true;
          buildEmbed();
        }
      } else {
        ready.timeout = setTimeout('onloaded_check_again();', 250);
      }
    }
  };
  this.onloaded_check_again = function() {
    onloaded_check();
  };

  /* Build Timeline
  ================================================== */
  function createEmbedDiv() {
    var embed_classname = "tl-timeline-embed";

    t = document.createElement('div');

    if (storyjs_e_config.embed_id != "") {
      te = document.getElementById(storyjs_e_config.embed_id);
    } else {
      te = document.getElementById("timeline-embed");
    }

    te.appendChild(t);
    t.setAttribute("id", storyjs_e_config.id);

    if (storyjs_e_config.width.toString().match("%") ) {
      te.style.width = storyjs_e_config.width.split("%")[0] + "%";
    } else {
      storyjs_e_config.width = storyjs_e_config.width - 2;
      te.style.width = (storyjs_e_config.width) + 'px';
    }

    if (storyjs_e_config.height.toString().match("%")) {
      te.style.height = storyjs_e_config.height;
      embed_classname += " tl-timeline-full-embed";
      te.style.height = storyjs_e_config.height.split("%")[0] + "%";

    } else if (storyjs_e_config.width.toString().match("%")) {
      embed_classname += " tl-timeline-full-embed";
      storyjs_e_config.height = storyjs_e_config.height - 16;
      te.style.height = (storyjs_e_config.height) + 'px';
    }else {
      embed_classname += " sized-embed";
      storyjs_e_config.height = storyjs_e_config.height - 16;
      te.style.height = (storyjs_e_config.height) + 'px';
    }

    te.setAttribute("class", embed_classname);
    te.setAttribute("className", embed_classname);
    t.style.position = 'relative';
  }

  function buildEmbed() {
    TL.debug = storyjs_e_config.debug;

    storyjs_e_config['ga_property_id'] = 'UA-27829802-4';
    storyjs_e_config.language = storyjs_e_config.lang;
    if (storyjs_e_config.width == '100%') {
      storyjs_e_config.is_full_embed = true;
    }
    window.timeline = new TL.Timeline('timeline-embed', storyjs_e_config.source, storyjs_e_config);

  }

}