'use strict';

const unplugin = require('unplugin');
const transform = require('./transform.cjs');
require('acorn');
require('magic-string');
require('estree-walker');

const unctxPlugin = unplugin.createUnplugin(
  (options = {}) => {
    const transformer = transform.createTransformer(options);
    return {
      name: "unctx:transform",
      enforce: "post",
      transformInclude: options.transformInclude,
      transform: {
        filter: options.transformFilter ?? transformer.filter,
        handler(code, id) {
          const result = transformer.transform(code);
          if (result) {
            return {
              code: result.code,
              map: result.magicString.generateMap({
                source: id,
                includeContent: true
              })
            };
          }
        }
      }
    };
  }
);

exports.unctxPlugin = unctxPlugin;
