import { rollup  } from 'rollup';

import rollupDefaults from './rollupDefaults';

function trimNewLines(val) {
	return val
		.replace(/^\n+/, '')
		.replace(/\n+$/, '');
}

let cache;
async function rollupWithCache(options) {
	const bundle = await rollup({
		cache,
		...options
	});
	cache = bundle.cache;
	return bundle;
}

export default function createScriptManager() {
	const scriptsFiles = new Set();

	function registerScript(scriptFile) {
		scriptsFiles.add(scriptFile);
	}

	async function transpileScript(filePath){
		let { inputOptions, outputOptions } = rollupDefaults;
		inputOptions.input = filePath;

		const bundle = await rollupWithCache(inputOptions);
		const { code } = await bundle.generate(outputOptions);

		return code;
	}

	async function embedRegisteredScripts(html) {
		const scripts = await Promise.all([...scriptsFiles].map(file => transpileScript(file)));
		const scriptElements = scripts.map(script => `<script>${trimNewLines(script)}</script>`);

		return html.replace('</body>', `${scriptElements.join('')}</body>`);
	}

	return {
		registerScript,
		embedRegisteredScripts
	};
}

@@ -788,16 +788,79 @@
 html) %7B%0A
+%09%09const transpileScriptfile = (file) =%3E transpileScript(file);%0A
 %09%09const 
@@ -893,26 +893,25 @@
 l(%5B...script
-sF
+f
 iles%5D.map(fi
@@ -912,16 +912,8 @@
 map(
-file =%3E 
 tran
@@ -927,16 +927,14 @@
 ript
-(f
+F
 ile))
-)
 ;%0A%09%09

Update packages/nocms-plugin-directory-resources/src/createScriptManager.js