import fs from 'fs';
import replace from 'rollup-plugin-replace';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import json from 'rollup-plugin-json';
import sucrase from 'rollup-plugin-sucrase';
import typescript from 'rollup-plugin-typescript';
import pkg from './package.json';

const is_publish = !!process.env.PUBLISH;

const tsPlugin = is_publish
	? typescript({
		include: 'src/**',
		typescript: require('typescript')
	})
	: sucrase({
		transforms: ['typescript']
	});

export default [
	/* internal.[m]js */
	{
		input: `src/internal/index.ts`,
		output: [
			{
				file: `internal.mjs`,
				format: 'esm',
				paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
			},
			{
				file: `internal.js`,
				format: 'cjs',
				paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
			}
		],
		external: id => id.startsWith('svelte/'),

		plugins: [
			tsPlugin,
			{
				generateBundle(options, bundle) {
					const mod = bundle['internal.mjs'];
					if (mod) {
						fs.writeFileSync('src/compile/internal-exports.ts', `// This file is automatically generated\nexport default new Set(${JSON.stringify(mod.exports)});`);
					}
				}
			}]
	},

	/* compiler.js */
	{
		input: 'src/compiler.ts',
		plugins: [
			replace({
				__VERSION__: pkg.version
			}),
			resolve(),
			commonjs({
				include: ['node_modules/**']
			}),
			json(),
			tsPlugin
		],
		output: {
			file: 'compiler.js',
			format: is_publish ? 'umd' : 'cjs',
			name: 'svelte',
			sourcemap: true,
		},
		external: is_publish
			? []
			: id => id === 'acorn' || id === 'magic-string' || id.startsWith('css-tree')
	},

	/* motion.mjs */
	{
		input: `src/motion/index.ts`,
		output: [
			{
				file: `motion.mjs`,
				format: 'esm',
				paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
			},
			{
				file: `motion.js`,
				format: 'cjs',
				paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
			}
		],
		plugins: [
			tsPlugin
		],
		external: id => id.startsWith('svelte/')
	},

	// everything else
	...['index', 'easing', 'transition', 'animate', 'store'].map(name => ({
		input: `src/${name}.ts`,
		output: [
			{
				file: `${name}.mjs`,
				format: 'esm',
				paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
			},
			{
				file: `${name}.js`,
				format: 'cjs',
				paths: id => id.startsWith('svelte/') && id.replace('svelte', '.')
			}
		],
		plugins: [
			tsPlugin
		],
		external: id => id.startsWith('svelte/')
	}))
];