[
  {
    "path": ".editorconfig",
    "content": "root = true\n\n[*]\nindent_style = space\nindent_size = 2\nend_of_line = lf\ncharset = utf-8\ntrim_trailing_whitespace = true\ninsert_final_newline = true\n\n[*.md]\ntrim_trailing_whitespace = false\n\n[*.test.ts]\ntrim_trailing_whitespace = false\n"
  },
  {
    "path": ".eslintrc",
    "content": "{\n  \"extends\": [\"xo-typescript\", \"rem\", \"prettier\"],\n  \"plugins\": [\"prettier\"],\n  \"env\": {\n    \"jest\": true\n  },\n  \"rules\": {\n    \"unicorn/filename-case\": \"off\",\n    \"unicorn/no-abusive-eslint-disable\": \"off\",\n    \"@typescript-eslint/no-var-requires\": \"off\",\n    \"@typescript-eslint/restrict-template-expressions\": \"off\"\n  }\n}\n"
  },
  {
    "path": ".gitattributes",
    "content": "* text=auto\n"
  },
  {
    "path": ".gitignore",
    "content": "node_modules\ntest/fixture/output\n*.log\ndist/\n"
  },
  {
    "path": ".prettierrc",
    "content": "\"@egoist/prettier-config\"\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) egoist <0x142857@gmail.com> (https://github.com/egoist)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "\n# vue-compile\n\nCompile the blocks in Vue single-file components to JS/CSS from Babel/Sass/Stylus.\n\n## Why This Approach\n\nYou may want to publish `.vue` files instead of transformed `.js` files on npm because the `.vue` file is preferred in some scenarioes, e.g. `vue-server-renderer` can inline critical CSS from `<style>` blocks.\n\nThis tool will transform each block in the `.vue` file to their standard conterparts like `sass` -> `css` so your users don't have to install additional libraries to compile it. \n\nIt also provides a `--preserve-ts-block` flag if you don't want to transpile TypeScript, because tools like Vite supports TypeScript out of the box. In this way you don't need to generate `.d.ts` for your Vue components either, thanks to [Volar](https://github.com/johnsoncodehk/volar).\n\n\n## Install\n\n```bash\nyarn global add vue-compile\n# or\nnpm i -g vue-compile\n```\n\n## Usage\n\n```bash\n# normalize a .vue file\nvue-compile example.vue -o output.vue\n# normalize a directory\n# non .vue files will be simply copied to output directory\nvue-compile src -o lib\n```\n\n__Then you can publish normalized `.vue` files to npm registry without compiling them to `.js` files.__\n\nSupported transforms (via `lang` attribute):\n\n- `<template>` tag:\n  - `html` (default)\n- `<script>` tag: \n  - `babel` (default): use our default [babel preset](./lib/babel/preset.js) or your own `.babelrc`\n  - `ts` `typescript`: use our default [babel preset](./lib/babel/preset.js) + `@babel/preset-typescript`, you can use `--preserve-ts-block` flag to preserve types, i.e. disable typescript transformation\n- `<style>` tag: \n  - `postcss` (default): use your own `postcss.config.js`\n  - `stylus` `sass` `scss`\n- Custom blocks: They are not touched.\n\nGotchas:\n\n- We only handle `src` attribute for `<style>` blocks, we simply replace the extension with `.css` and remove the `lang` attribute.\n\n<details><summary>Example</summary><br>\n\nIn:\n\n```vue\n<template>\n  <div class=\"foo\">\n    {{ count }}\n  </div>\n</template>\n\n<script>\nexport default {\n  data() {\n    return {\n      count: 0\n    }\n  }\n}\n</script>\n\n<style lang=\"scss\" src=\"./foo.scss\">\n\n<style lang=\"stylus\" scoped>\n@import './colors.styl'\n\n.foo \n  color: $color\n</style>\n```\n\nOut:\n\n```vue\n<template>  \n  <div class=\"foo\">\n    {{ count }}\n  </div>\n</template>\n\n<script>\nexport default {\n  data: function data() {\n    return {\n      count: 0\n    };\n  }\n};\n</script>\n\n<style src=\"./foo.css\">\n\n<style scoped>\n.foo {\n  color: #f00;\n}\n</style>\n```\n</details>\n\n### Compile Standalone CSS Files\n\nCSS files like `.css` `.scss` `.sass` `.styl` will be compiled to output directory with `.css` extension, all relevant `import` statements in `.js` `.ts` or `<script>` blocks will be changed to use `.css` extension as well.\n\nYou can exclude them using the `--exclude \"**/*.{css,scss,sass,styl}\"` flag.\n\n## Contributing\n\n1. Fork it!\n2. Create your feature branch: `git checkout -b my-new-feature`\n3. Commit your changes: `git commit -am 'Add some feature'`\n4. Push to the branch: `git push origin my-new-feature`\n5. Submit a pull request :D\n\n\n## Author\n\n**vue-compile** © [egoist](https://github.com/egoist), Released under the [MIT](./LICENSE) License.<br>\nAuthored and maintained by egoist with help from contributors ([list](https://github.com/egoist/vue-compile/contributors)).\n\n> [github.com/egoist](https://github.com/egoist) · GitHub [@egoist](https://github.com/egoist) · Twitter [@_egoistlily](https://twitter.com/_egoistlily)\n"
  },
  {
    "path": "babel.js",
    "content": "/* eslint-disable */\nmodule.exports = require('./dist/babel/preset')\n"
  },
  {
    "path": "circle.yml",
    "content": "version: 2\njobs:\n  build:\n    docker:\n      - image: circleci/node:latest\n    branches:\n      ignore:\n        - gh-pages # list of branches to ignore\n        - /release\\/.*/ # or ignore regexes\n    steps:\n      - checkout\n      - restore_cache:\n          key: dependency-cache-{{ checksum \"yarn.lock\" }}\n      - run:\n          name: install dependences\n          command: yarn\n      - save_cache:\n          key: dependency-cache-{{ checksum \"yarn.lock\" }}\n          paths:\n            - ./node_modules\n      - run:\n          name: test\n          command: yarn test\n      - run:\n          name: release\n          command: npx semantic-release\n"
  },
  {
    "path": "jest.config.js",
    "content": "module.exports = {\n  testEnvironment: 'node',\n  transform: {\n    '^.+\\\\.tsx?$': '@sucrase/jest-plugin',\n  },\n  testRegex: '(/__test__/.*|(\\\\.|/)(test|spec))\\\\.tsx?$',\n  testPathIgnorePatterns: ['/node_modules/', '/dist/', '/types/'],\n  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"vue-compile\",\n  \"version\": \"0.0.0-semantic-release\",\n  \"description\": \"Pre-compile each blocks of your Vue single-file components.\",\n  \"repository\": {\n    \"url\": \"egoist/vue-compile\",\n    \"type\": \"git\"\n  },\n  \"main\": \"dist/index.js\",\n  \"bin\": \"dist/cli.js\",\n  \"types\": \"dist/index.d.ts\",\n  \"files\": [\n    \"dist/\",\n    \"babel.js\"\n  ],\n  \"scripts\": {\n    \"test\": \"npm run lint && jest\",\n    \"lint\": \"eslint src/**/*.ts\",\n    \"build\": \"tsc -p tsconfig.build.json\",\n    \"prepublishOnly\": \"npm run build\",\n    \"postinstall\": \"node -e \\\"console.log('\\\\u001b[35m\\\\u001b[1mLove vue-compile? You can now donate to support the author:\\\\u001b[22m\\\\u001b[39m\\\\n> \\\\u001b[36mhttps://github.com/sponsors/egoist\\\\u001b[39m')\\\"\"\n  },\n  \"author\": \"egoist <0x142857@gmail.com>\",\n  \"license\": \"MIT\",\n  \"dependencies\": {\n    \"@babel/core\": \"^7.13.15\",\n    \"@babel/plugin-syntax-typescript\": \"^7.12.13\",\n    \"@babel/preset-env\": \"^7.13.15\",\n    \"@babel/preset-typescript\": \"^7.13.0\",\n    \"@vue/compiler-sfc\": \"^3.0.11\",\n    \"cac\": \"^6.7.2\",\n    \"chalk\": \"^4.1.0\",\n    \"chokidar\": \"^3.5.1\",\n    \"debug\": \"^4.3.1\",\n    \"fast-glob\": \"^3.2.5\",\n    \"fs-extra\": \"^9.1.0\",\n    \"is-binary-path\": \"^2.1.0\",\n    \"joycon\": \"^3.0.1\",\n    \"lodash.clonedeep\": \"^4.5.0\",\n    \"postcss\": \"^8.2.10\",\n    \"postcss-load-config\": \"^3.0.1\",\n    \"resolve\": \"^1.20.0\",\n    \"resolve-from\": \"^5.0.0\",\n    \"stringify-attributes\": \"^2.0.0\"\n  },\n  \"devDependencies\": {\n    \"@egoist/prettier-config\": \"^0.1.0\",\n    \"@sucrase/jest-plugin\": \"^2.1.0\",\n    \"@types/debug\": \"^4.1.4\",\n    \"@types/fs-extra\": \"^8.0.0\",\n    \"@types/is-binary-path\": \"^2.1.0\",\n    \"@types/jest\": \"^26.0.14\",\n    \"@types/lodash.clonedeep\": \"^4.5.6\",\n    \"@types/node-sass\": \"^4.11.0\",\n    \"@types/stringify-attributes\": \"^2.0.0\",\n    \"@typescript-eslint/eslint-plugin\": \"^4.22.0\",\n    \"@typescript-eslint/parser\": \"^4.22.0\",\n    \"eslint\": \"^7.24.0\",\n    \"eslint-config-prettier\": \"^8.2.0\",\n    \"eslint-config-rem\": \"^4.0.0\",\n    \"eslint-config-xo-typescript\": \"^0.38.0\",\n    \"eslint-plugin-prettier\": \"^3.4.0\",\n    \"husky\": \"^4.3.0\",\n    \"jest\": \"^24.8.0\",\n    \"lint-staged\": \"^10.4.0\",\n    \"prettier\": \"^2.2.1\",\n    \"stylus\": \"^0.54.5\",\n    \"typescript\": \"^4.2.4\",\n    \"vue\": \"^3.0.11\"\n  },\n  \"husky\": {\n    \"hooks\": {\n      \"pre-commit\": \"lint-staged\"\n    }\n  },\n  \"lint-staged\": {\n    \"{src}/**/*.ts\": [\n      \"eslint --fix\"\n    ]\n  },\n  \"release\": {\n    \"branch\": \"master\"\n  }\n}\n"
  },
  {
    "path": "src/babel/preset.ts",
    "content": "import { PluginObj, types as Types } from '@babel/core'\nimport { cssExtensionsRe } from '../utils'\n\nexport default (_: any, opts: { transformTypeScript: boolean }) => {\n  const presets = []\n  if (opts.transformTypeScript) {\n    presets.push(require.resolve('@babel/preset-typescript'))\n  }\n  presets.push([\n    require.resolve('@babel/preset-env'),\n    {\n      modules: false,\n      targets: {\n        edge: '79',\n        // Node 12 is no longer maintained, and let's pretend Node 13 didn't exist\n        node: '14',\n      },\n    },\n  ])\n\n  const plugins = [replaceExtensionInImports]\n  if (!opts.transformTypeScript) {\n    plugins.push(require('@babel/plugin-syntax-typescript'))\n  }\n\n  return {\n    presets,\n    plugins,\n  }\n}\n\nfunction replaceExtensionInImports(opts: { types: typeof Types }): PluginObj {\n  const { types: t } = opts\n  return {\n    name: 'replace-extension-in-imports',\n    visitor: {\n      ImportDeclaration(path) {\n        if (cssExtensionsRe.test(path.node.source.value)) {\n          path.node.source.value = path.node.source.value.replace(\n            cssExtensionsRe,\n            '.css',\n          )\n        }\n      },\n      CallExpression(path) {\n        if ((path.node.callee as Types.Identifier).name === 'require') {\n          const arg: any = path.get('arguments.0')\n          if (arg) {\n            const res = arg.evaluate()\n            if (res.confident && cssExtensionsRe.test(res.value)) {\n              path.node.arguments = [\n                t.stringLiteral(res.value.replace(cssExtensionsRe, '.css')),\n              ]\n            }\n          }\n        }\n      },\n    },\n  }\n}\n"
  },
  {
    "path": "src/cli.ts",
    "content": "#!/usr/bin/env node\nimport path from 'path'\nimport chalk from 'chalk'\n\nif (parseInt(process.versions.node, 10) < 8) {\n  console.error(\n    chalk.red('The \"vue-compile\" module requires Node.js 8 or above!'),\n  )\n  console.error(chalk.dim(`Current version: ${process.versions.node}`))\n  process.exit(1)\n}\n\nasync function main(): Promise<void> {\n  const { cac } = await import('cac')\n  // eslint-disable-next-line @typescript-eslint/no-var-requires\n  const { version } = require('../package.json')\n\n  const cli = cac('vue-compile')\n\n  cli\n    .command('[input]', 'Normalize input file or directory', {\n      ignoreOptionDefaultValue: true,\n    })\n    .usage('[input] [options]')\n    .action(async (input: string, flags: any) => {\n      const options = {\n        input,\n        ...flags,\n      }\n\n      if (!options.input) {\n        delete options.input\n      }\n\n      if (options.debug === true) {\n        process.env.DEBUG = 'vue-compile:*'\n      } else if (typeof options.debug === 'string') {\n        process.env.DEBUG = `vue-compile:${options.debug}`\n      }\n\n      const { createCompiler } = await import('.')\n\n      if (!options.input) {\n        cli.outputHelp()\n        return\n      }\n\n      const compiler = createCompiler(options)\n\n      compiler.on('normalized', async (input: string, output: string) => {\n        if (!compiler.options.debug) {\n          const { humanlizePath } = await import('./utils')\n\n          console.log(\n            `${chalk.magenta(humanlizePath(input))} ${chalk.dim(\n              '->',\n            )} ${chalk.green(humanlizePath(output))}`,\n          )\n        }\n      })\n\n      await compiler.normalize().catch(handleError)\n\n      if (flags.watch) {\n        const { watch } = await import('chokidar')\n        watch('.', {\n          cwd: compiler.isInputFile\n            ? path.resolve(path.dirname(input))\n            : path.resolve(input),\n          ignoreInitial: true,\n          ignorePermissionErrors: true,\n          ignored: '**/{node_modules,dist,.git,public}/**',\n        }).on('all', (_, file) => {\n          console.log(chalk.bold(`Rebuilding because ${file} changed..`))\n          compiler.normalize().catch(handleError)\n        })\n      }\n    })\n    .option('-o, --output <file|directory>', 'Output path')\n    .option(\n      '-i, --include <glob>',\n      'A glob pattern to include from input directory',\n    )\n    .option(\n      '-e, --exclude <glob>',\n      'A glob pattern to exclude from input directory',\n    )\n    .option('--no-babelrc', 'Disable .babelrc file')\n    .option('--preserve-ts-block', `Preserve TypeScript types in script block`)\n    .option('-w, --watch', 'Enable watch mode')\n\n  cli.option('--debug', 'Show debug logs')\n\n  cli.version(version)\n  cli.help()\n\n  cli.parse()\n}\n\nfunction handleError(error: Error): void {\n  console.error(error.stack)\n  process.exit(1)\n}\n\nmain().catch(handleError)\n"
  },
  {
    "path": "src/compileScript.ts",
    "content": "import { SFCScriptBlock } from '@vue/compiler-sfc'\nimport { notSupportedLang } from './utils'\nimport { ScriptCompilerContext } from './types'\n\nexport const compileScript = async (\n  script: SFCScriptBlock | null,\n  ctx: ScriptCompilerContext,\n): Promise<SFCScriptBlock | null> => {\n  if (!script) return script\n\n  const code = script.content.replace(/^\\/\\/$/gm, '')\n\n  if (\n    !script.lang ||\n    script.lang === 'esnext' ||\n    script.lang === 'babel' ||\n    script.lang === 'ts' ||\n    script.lang === 'typescript'\n  ) {\n    script.content = await import(\n      './script-compilers/babel'\n    ).then(async ({ compile }) => compile(code, ctx))\n  } else {\n    throw new Error(notSupportedLang(script.lang, 'script'))\n  }\n\n  return script\n}\n"
  },
  {
    "path": "src/compileStyles.ts",
    "content": "import { SFCStyleBlock } from '@vue/compiler-sfc'\nimport { notSupportedLang } from './utils'\n\nexport const compileStyles = async (\n  styles: SFCStyleBlock[],\n  { filename }: { filename: string },\n): Promise<SFCStyleBlock[]> => {\n  return Promise.all(\n    styles.map(async (style) => {\n      // Do not handle \"src\" import\n      // Until we figure out how to handle it\n      if (style.src) return style\n\n      const { content } = style\n\n      if (style.lang === 'stylus') {\n        style.content = await require('./style-compilers/stylus').compile(\n          content,\n          {\n            filename,\n          },\n        )\n      } else if (!style.lang || style.lang === 'postcss') {\n        style.content = await require('./style-compilers/postcss').compile(\n          content,\n          {\n            filename,\n          },\n        )\n      } else if (style.lang === 'scss' || style.lang === 'sass') {\n        style.content = await require('./style-compilers/sass').compile(\n          content,\n          {\n            filename,\n            indentedSyntax: style.lang === 'sass',\n          },\n        )\n      } else if (style.lang) {\n        throw new Error(notSupportedLang(style.lang, 'style'))\n      }\n\n      return style\n    }),\n  )\n}\n"
  },
  {
    "path": "src/compileTemplate.ts",
    "content": "import { SFCTemplateBlock } from '@vue/compiler-sfc'\n\nexport const compileTemplate = <T = SFCTemplateBlock | null>(template: T): T =>\n  template\n"
  },
  {
    "path": "src/importLocal.ts",
    "content": "import resolveFrom from 'resolve-from'\n\nexport const importLocal = (dir: string, name: string, fallback?: string): any => {\n  const found =\n    resolveFrom.silent(dir, name) ||\n    (fallback && resolveFrom.silent(dir, fallback))\n\n  if (!found) {\n    throw new Error(\n      `You need to install \"${name}\"${\n        fallback ? ` or \"${fallback}\"` : ''\n      } in current directory!`\n    )\n  }\n\n  return require(found)\n}\n"
  },
  {
    "path": "src/index.ts",
    "content": "import path from 'path'\nimport { EventEmitter } from 'events'\nimport fs from 'fs-extra'\nimport JoyCon from 'joycon'\nimport isBinaryPath from 'is-binary-path'\nimport createDebug from 'debug'\nimport { parse } from '@vue/compiler-sfc'\nimport glob from 'fast-glob'\nimport cloneDeep from 'lodash.clonedeep'\nimport {\n  replaceContants,\n  cssExtensionsRe,\n  jsExtensionsRe,\n  isDefined,\n} from './utils'\nimport { compileScript } from './compileScript'\nimport { compileStyles } from './compileStyles'\nimport { compileTemplate } from './compileTemplate'\nimport { writeSFC } from './writeSFC'\n\nconst debug = createDebug('vue-compile:cli')\n\ntype OptionContants = Record<string, string | boolean | number>\n\ninterface InputOptions {\n  config?: boolean | string\n  input: string\n  output: string\n  constants?: OptionContants\n  babelrc?: boolean\n  include?: string[]\n  exclude?: string[]\n  debug?: boolean\n  preserveTsBlock?: boolean\n}\n\ninterface NormalizedOptions {\n  input: string\n  output: string\n  constants?: OptionContants\n  babelrc?: boolean\n  include?: string[]\n  exclude?: string[]\n  debug?: boolean\n  preserveTsBlock?: boolean\n}\n\nclass VueCompile extends EventEmitter {\n  options: NormalizedOptions\n\n  isInputFile?: boolean\n\n  constructor(options: InputOptions) {\n    super()\n\n    if (options.config !== false) {\n      const joycon = new JoyCon({\n        files: [\n          typeof options.config === 'string'\n            ? options.config\n            : 'vue-compile.config.js',\n        ],\n        stopDir: path.dirname(process.cwd()),\n      })\n      const { data: config, path: configPath } = joycon.loadSync()\n\n      if (configPath) {\n        debug(`Using config file: ${configPath}`)\n      }\n\n      options = { ...options, ...config }\n    }\n\n    this.options = this.normalizeOptions(options)\n    this.isInputFile = fs.statSync(this.options.input).isFile()\n  }\n\n  normalizeOptions(options: InputOptions): NormalizedOptions {\n    return {\n      ...options,\n      input: path.resolve(options.input),\n      output: path.resolve(options.output),\n    }\n  }\n\n  async normalize(): Promise<void> {\n    if (!this.options.input) {\n      return\n    }\n\n    if (this.isInputFile) {\n      if (!this.options.output) {\n        throw new Error('You must specify the path to output file.')\n      }\n\n      await this.normalizeFile(this.options.input, this.options.output)\n    } else {\n      if (!this.options.output) {\n        throw new Error('You must specify the path to output directory.')\n      }\n\n      await this.normalizeDir(this.options.input, this.options.output)\n    }\n  }\n\n  async normalizeFile(input: string, outFile: string): Promise<void> {\n    if (isBinaryPath(input)) {\n      const buffer = await fs.readFile(input)\n      return this.writeBinary(buffer, {\n        filename: input,\n        outFile,\n      })\n    }\n\n    let source = await fs.readFile(input, 'utf8')\n    source = replaceContants(source, this.options.constants)\n\n    const ctx = {\n      filename: input,\n      outFile,\n      babelrc: this.options.babelrc,\n      transformTypeScript: true,\n    }\n\n    if (!input.endsWith('.vue')) {\n      return this.writeText(source, ctx)\n    }\n\n    ctx.transformTypeScript = !this.options.preserveTsBlock\n\n    const sfc = cloneDeep(\n      parse(source, {\n        filename: input,\n      }),\n    )\n\n    const script = await compileScript(sfc.descriptor.script, ctx)\n    const scriptSetup = await compileScript(sfc.descriptor.scriptSetup, ctx)\n    const template = compileTemplate(sfc.descriptor.template)\n    const styles = await compileStyles(sfc.descriptor.styles, ctx)\n\n    await writeSFC(\n      {\n        scripts: [script, scriptSetup].filter(isDefined).sort((a, b) => {\n          return a.loc.start > b.loc.start ? -1 : 1\n        }),\n        styles,\n        template,\n        customBlocks: sfc.descriptor.customBlocks,\n        preserveTsBlock: this.options.preserveTsBlock,\n      },\n      outFile,\n    )\n\n    this.emit('normalized', input, outFile)\n  }\n\n  async normalizeDir(input: string, outDir: string): Promise<void> {\n    const include = [...(this.options.include ?? [])]\n    const exclude = [...(this.options.exclude ?? [])]\n    const files = await glob(include.length > 0 ? include : ['**/*'], {\n      cwd: input,\n      ignore: ['**/node_modules/**'].concat(exclude),\n    })\n\n    await Promise.all(\n      files.map(async (file: string) => {\n        return this.normalizeFile(\n          path.join(input, file),\n          path.join(outDir, file),\n        )\n      }),\n    )\n  }\n\n  async writeText(\n    source: string,\n    {\n      filename,\n      outFile,\n      babelrc,\n      transformTypeScript,\n    }: {\n      filename: string\n      outFile: string\n      babelrc?: boolean\n      transformTypeScript: boolean\n    },\n  ): Promise<void> {\n    let output\n\n    if (jsExtensionsRe.test(filename)) {\n      output = await import('./script-compilers/babel').then(\n        async ({ compile }) => {\n          return compile(source, {\n            filename,\n            babelrc,\n            transformTypeScript,\n          })\n        },\n      )\n    } else if (filename.endsWith('.css')) {\n      output = await import('./style-compilers/postcss').then(\n        async ({ compile }) => {\n          return compile(source, { filename })\n        },\n      )\n    } else if (/\\.s[ac]ss$/.test(filename)) {\n      const basename = path.basename(filename)\n      if (basename.startsWith('_')) {\n        // Ignore sass partial files\n        return\n      }\n\n      output = await import('./style-compilers/sass').then(\n        async ({ compile }) => {\n          return compile(source, {\n            filename,\n            indentedSyntax: filename.endsWith('.sass'),\n          })\n        },\n      )\n    } else if (/\\.styl(us)?/.test(filename)) {\n      output = await import('./style-compilers/stylus').then(\n        async ({ compile }) => {\n          return compile(source, {\n            filename,\n          })\n        },\n      )\n    } else {\n      output = source\n    }\n\n    outFile = outFile.replace(cssExtensionsRe, '.css')\n    outFile = outFile.replace(jsExtensionsRe, '.js')\n\n    await fs.outputFile(outFile, output, 'utf8')\n\n    this.emit('normalized', filename, outFile)\n  }\n\n  async writeBinary(\n    source: Buffer,\n    { filename, outFile }: { filename: string; outFile: string },\n  ): Promise<void> {\n    await fs.outputFile(outFile, source, 'utf8')\n\n    this.emit('normalized', filename, outFile)\n  }\n}\n\nexport const createCompiler = (opts: InputOptions): VueCompile =>\n  new VueCompile(opts)\n"
  },
  {
    "path": "src/script-compilers/babel.ts",
    "content": "import path from 'path'\nimport createDebug from 'debug'\nimport { TransformOptions } from '@babel/core'\nimport preset from '../babel/preset'\nimport { ScriptCompilerContext } from '../types'\nimport { getBabelConfigFile } from '../utils'\n\nconst debug = createDebug('vue-compile:script')\n\nexport const compile = async (\n  code: string,\n  { filename, babelrc, transformTypeScript }: ScriptCompilerContext,\n): Promise<string> => {\n  const cwd = path.dirname(filename)\n\n  const babelConfigFile = getBabelConfigFile(cwd, babelrc)\n\n  const config: TransformOptions = {\n    filename: filename.endsWith('.vue') ? `${filename}.vue.ts` : filename,\n    presets: [[preset, { transformTypeScript }]],\n  }\n\n  if (babelConfigFile) {\n    config.babelrc = true\n    debug(`Using Babel config file at ${babelConfigFile}`)\n  } else {\n    config.babelrc = false\n  }\n\n  return require('@babel/core').transform(code, config).code\n}\n"
  },
  {
    "path": "src/style-compilers/postcss.ts",
    "content": "import path from 'path'\nimport createDebug from 'debug'\n\nconst debug = createDebug('vue-compile:style')\n\nconst cache = new Map()\n\nexport const compile = async (\n  code: string,\n  { filename }: { filename: string }\n): Promise<string> => {\n  const ctx = {\n    file: {\n      extname: path.extname(filename),\n      dirname: path.dirname(filename),\n      basename: path.basename(filename)\n    },\n    options: {}\n  }\n\n  const cwd = path.dirname(filename)\n  const config =\n    cache.get(cwd) ||\n    (await require('postcss-load-config')(ctx, cwd, {\n      argv: false\n    }).catch((error: Error) => {\n      if (error.message.includes('No PostCSS Config found in')) {\n        return {}\n      }\n\n      throw error\n    }))\n  cache.set(cwd, config)\n\n  if (config.file) {\n    debug(`Using PostCSS config file at ${config.file}`)\n  }\n\n  const options = {\n    from: filename,\n    map: false,\n    ...config.options\n  }\n\n  return import('postcss').then(async postcss => {\n    return postcss\n      .default(config.plugins || [])\n      .process(code, options)\n      .then(res => res.css)\n  })\n}\n"
  },
  {
    "path": "src/style-compilers/sass.ts",
    "content": "import path from 'path'\nimport { promisify } from 'util'\nimport { SassRenderCallback, Options as SassRenderOptions } from 'node-sass'\nimport { importLocal } from '../importLocal'\n\nconst moduleRe = /^~([a-z0-9]|@).+/i\n\nconst getUrlOfPartial = (url: string): string => {\n  const parsedUrl = path.parse(url)\n  return `${parsedUrl.dir}${path.sep}_${parsedUrl.base}`\n}\n\ntype SassRender = (\n  options: SassRenderOptions,\n  callback: SassRenderCallback,\n) => void\n\nexport const compile = async (\n  code: string,\n  { filename, indentedSyntax }: { filename: string; indentedSyntax?: boolean },\n): Promise<string> => {\n  const sass: { render: SassRender } = importLocal(\n    path.dirname(filename),\n    'sass',\n    'node-sass',\n  )\n  const res = await promisify(sass.render.bind(sass))({\n    file: filename,\n    data: code,\n    indentedSyntax,\n    sourceMap: false,\n    importer: [\n      (url, importer, done) => {\n        if (!moduleRe.test(url)) {\n          done({ file: url })\n          return\n        }\n\n        const moduleUrl = url.slice(1)\n        const partialUrl = getUrlOfPartial(moduleUrl)\n\n        const options = {\n          basedir: path.dirname(importer),\n          extensions: ['.scss', '.sass', '.css'],\n        }\n        const finishImport = (id: string): void => {\n          done({\n            // Do not add `.css` extension in order to inline the file\n            file: id.endsWith('.css') ? id.replace(/\\.css$/, '') : id,\n          })\n        }\n\n        const next = (): void => {\n          // Catch all resolving errors, return the original file and pass responsibility back to other custom importers\n          done({ file: url })\n        }\n\n        const resolvePromise = promisify(require('resolve'))\n\n        // Give precedence to importing a partial\n        resolvePromise(partialUrl, options)\n          .then(finishImport)\n          .catch((error: any) => {\n            if (error.code === 'MODULE_NOT_FOUND' || error.code === 'ENOENT') {\n              resolvePromise(moduleUrl, options).then(finishImport).catch(next)\n            } else {\n              next()\n            }\n          })\n      },\n    ],\n  })\n\n  return res.css.toString()\n}\n"
  },
  {
    "path": "src/style-compilers/stylus.ts",
    "content": "import path from 'path'\nimport { promisify } from 'util'\nimport { importLocal } from '../importLocal'\n\nexport const compile = async (code: string, { filename }: { filename: string }): Promise<string> => {\n  const stylus = importLocal(path.dirname(filename), 'stylus')\n  return promisify(stylus.render.bind(stylus))(code, { filename })\n}\n"
  },
  {
    "path": "src/types.ts",
    "content": "export interface ScriptCompilerContext {\n  filename: string\n  babelrc?: boolean\n  transformTypeScript: boolean\n}\n"
  },
  {
    "path": "src/utils.ts",
    "content": "import path from 'path'\nimport { loadPartialConfig } from '@babel/core'\n\nexport const humanlizePath = (p: string): string =>\n  path.relative(process.cwd(), p)\n\nexport const notSupportedLang = (lang: string, tag: string): string => {\n  return `\"${lang}\" is not supported for <${tag}> tag currently, wanna contribute this feature?`\n}\n\nfunction escapeRe(str: string): string {\n  return str.replace(/[-[\\]/{}()*+?.\\\\^$|]/g, '\\\\$&')\n}\n\nexport const replaceContants = (\n  content: string,\n  constants?: Record<string, any>,\n): string => {\n  if (!constants) return content\n\n  const RE = new RegExp(\n    `\\\\b(${Object.keys(constants).map(escapeRe).join('|')})\\\\b`,\n    'g',\n  )\n  content = content.replace(RE, (_, p1) => {\n    return constants[p1]\n  })\n\n  return content\n}\n\nexport const cssExtensionsRe = /\\.(css|s[ac]ss|styl(us)?)$/\n\nexport const jsExtensionsRe = /\\.[jt]sx?$/\n\nconst babelConfigCache: Map<string, string | undefined> = new Map()\n\n/**\n * Find babel config file in cwd\n * @param cwd\n * @param babelrc Whether to load babel config file\n */\nexport const getBabelConfigFile = (cwd: string, babelrc?: boolean) => {\n  const file: string | undefined =\n    babelrc === false\n      ? undefined\n      : babelConfigCache.get(cwd) ?? loadPartialConfig()?.babelrc\n\n  babelConfigCache.set(cwd, file)\n\n  return file\n}\n\nexport function isDefined<T>(value: T | undefined | null): value is T {\n  return value != null\n}\n"
  },
  {
    "path": "src/writeSFC.ts",
    "content": "import path from 'path'\nimport fs from 'fs-extra'\nimport stringifyAttrs from 'stringify-attributes'\nimport {\n  SFCScriptBlock,\n  SFCStyleBlock,\n  SFCTemplateBlock,\n  SFCBlock,\n} from '@vue/compiler-sfc'\nimport { cssExtensionsRe } from './utils'\n\nexport const writeSFC = async (\n  {\n    scripts,\n    styles,\n    template,\n    customBlocks,\n    preserveTsBlock,\n  }: {\n    scripts: SFCScriptBlock[]\n    styles: SFCStyleBlock[]\n    template: SFCTemplateBlock | null\n    customBlocks: SFCBlock[]\n    preserveTsBlock?: boolean\n  },\n  outFile: string,\n): Promise<void> => {\n  const parts = []\n\n  if (template) {\n    parts.push(\n      `<template${stringifyAttrs(template.attrs)}>${template.content\n        .replace(/\\n$/, '')\n        .replace(/^/gm, '  ')}\\n</template>`,\n    )\n  }\n\n  scripts.forEach((script) => {\n    parts.push(\n      `<script${preserveTsBlock && script.lang === 'ts' ? ' lang=\"ts\"' : ''}${\n        script.setup ? ' setup' : ''\n      }>\\n${script.content.trim()}\\n</script>`,\n    )\n  })\n\n  if (styles.length > 0) {\n    for (const style of styles) {\n      const attrs = { ...style.attrs }\n      delete attrs.lang\n\n      if (style.src) {\n        attrs.src = style.src.replace(cssExtensionsRe, '.css')\n        parts.push(`<style${stringifyAttrs(attrs)}></style>`)\n      } else {\n        parts.push(\n          `<style${stringifyAttrs(attrs)}>\\n${style.content.trim()}\\n</style>`,\n        )\n      }\n    }\n  }\n\n  if (customBlocks) {\n    for (const block of customBlocks) {\n      parts.push(\n        `<${block.type}${stringifyAttrs(block.attrs)}>${\n          block.content ? block.content.trim() : ''\n        }</${block.type}>`,\n      )\n    }\n  }\n\n  await fs.ensureDir(path.dirname(outFile))\n  await fs.writeFile(outFile, parts.join('\\n\\n'), 'utf8')\n}\n"
  },
  {
    "path": "test/fixture/custom-blocks/foo.vue",
    "content": "<template>\n  <div></div>\n</template>\n\n<script>\nexport default {\n\n}\n</script>\n\n<foo>\nthis is a custom block\n</foo>\n"
  },
  {
    "path": "test/fixture/keep-async-function/foo.vue",
    "content": "<script lang=\"ts\">\nexport default {\n  async setup() {\n    console.log('a')\n  },\n}\n</script>\n"
  },
  {
    "path": "test/fixture/keep-ts-block/foo.vue",
    "content": "<script lang=\"ts\">\nexport default {\n  setup() {\n    let a: string = '1'\n    return {\n      a,\n    }\n  },\n}\n</script>\n"
  },
  {
    "path": "test/fixture/script-block/foo.vue",
    "content": "<script lang=\"ts\">\nimport { ref } from 'vue'\nexport default {\n  setup() {\n    const a = ref('a')\n    return {\n      a: a.value ?? 'a',\n    }\n  },\n}\n</script>\n"
  },
  {
    "path": "test/fixture/script-setup/foo.vue",
    "content": "<script lang=\"ts\">\nexport const foo = 'foo'\n</script>\n\n<script lang=\"ts\" setup>\nimport { defineProps, PropType } from 'vue'\n\nconst props = defineProps({\n  foo: Number as PropType<number>,\n})\n</script>\n\n<template>\n  <div>{{ props.foo }}</div>\n</template>\n"
  },
  {
    "path": "test/index.test.ts",
    "content": "import path from 'path'\nimport fs from 'fs-extra'\nimport { createCompiler } from '../src'\n\nconst fixture = (...args: string[]): string =>\n  path.resolve(__dirname, 'fixture', ...args)\nconst tmp = (name: string): string => fixture('output', name)\n\ntest('script block', async () => {\n  const outDir = tmp('script-block')\n  const compiler = createCompiler({\n    input: fixture('script-block'),\n    output: outDir,\n  })\n  await compiler.normalize()\n  const content = await fs.readFile(path.join(outDir, 'foo.vue'), 'utf8')\n  expect(content).toMatchInlineSnapshot(`\n    \"<script>\n    import { ref } from 'vue';\n    export default {\n      setup() {\n        var _a$value;\n\n        const a = ref('a');\n        return {\n          a: (_a$value = a.value) !== null && _a$value !== void 0 ? _a$value : 'a'\n        };\n      }\n\n    };\n    </script>\"\n  `)\n})\n\ntest('script setup', async () => {\n  const outDir = tmp('script-setup')\n  const compiler = createCompiler({\n    input: fixture('script-setup'),\n    output: outDir,\n  })\n  await compiler.normalize()\n  const content = await fs.readFile(path.join(outDir, 'foo.vue'), 'utf8')\n  expect(content).toMatchInlineSnapshot(`\n    \"<template>  \n        <div>{{ props.foo }}</div>\n    </template>\n\n    <script>\n    export const foo = 'foo';\n    </script>\n\n    <script setup>\n    import { defineProps } from 'vue';\n    const props = defineProps({\n      foo: Number\n    });\n    </script>\"\n  `)\n})\n\ntest('custom blocks', async () => {\n  const outDir = tmp('custom-blocks')\n  const compiler = createCompiler({\n    input: fixture('custom-blocks'),\n    output: outDir,\n  })\n  await compiler.normalize()\n  const content = await fs.readFile(path.join(outDir, 'foo.vue'), 'utf8')\n  expect(content).toMatchInlineSnapshot(`\n                                        \"<template>  \n                                            <div></div>\n                                        </template>\n\n                                        <script>\n                                        export default {};\n                                        </script>\n\n                                        <foo>this is a custom block</foo>\"\n                    `)\n})\n\ntest('keep ts block', async () => {\n  const outDir = tmp('keep-ts-block')\n  const compiler = createCompiler({\n    input: fixture('keep-ts-block'),\n    output: outDir,\n    preserveTsBlock: true,\n  })\n  await compiler.normalize()\n  const content = await fs.readFile(path.join(outDir, 'foo.vue'), 'utf8')\n  expect(content).toMatchInlineSnapshot(`\n    \"<script lang=\\\\\"ts\\\\\">\n    export default {\n      setup() {\n        let a: string = '1';\n        return {\n          a\n        };\n      }\n\n    };\n    </script>\"\n  `)\n})\n\ntest('keep-async-function', async () => {\n  const outDir = tmp('keep-async-function')\n  const compiler = createCompiler({\n    input: fixture('keep-async-function'),\n    output: outDir,\n    preserveTsBlock: true,\n  })\n  await compiler.normalize()\n  const content = await fs.readFile(path.join(outDir, 'foo.vue'), 'utf8')\n  expect(content).toMatchInlineSnapshot(`\n        \"<script lang=\\\\\"ts\\\\\">\n        export default {\n          async setup() {\n            console.log('a');\n          }\n\n        };\n        </script>\"\n    `)\n})\n"
  },
  {
    "path": "tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.json\",\n  \"compilerOptions\": {\n    \"outDir\": \"./dist\",\n    \"declaration\": true,\n    \"skipLibCheck\": true\n  },\n  \"include\": [\"src\"]\n}\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    /* Basic Options */\n    // \"incremental\": true,                   /* Enable incremental compilation */\n    \"target\": \"es2019\" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */,\n    \"module\": \"commonjs\" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,\n    // \"lib\": [],                             /* Specify library files to be included in the compilation. */\n    // \"allowJs\": true,                       /* Allow javascript files to be compiled. */\n    // \"checkJs\": true,                       /* Report errors in .js files. */\n    // \"jsx\": \"preserve\",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */\n    // \"declaration\": true,                   /* Generates corresponding '.d.ts' file. */\n    // \"declarationMap\": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */\n    // \"sourceMap\": true,                     /* Generates corresponding '.map' file. */\n    // \"outFile\": \"./\",                       /* Concatenate and emit output to single file. */\n    // \"rootDir\": \"./\",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */\n    // \"composite\": true,                     /* Enable project compilation */\n    // \"tsBuildInfoFile\": \"./\",               /* Specify file to store incremental compilation information */\n    // \"removeComments\": true,                /* Do not emit comments to output. */\n    // \"noEmit\": true,                        /* Do not emit outputs. */\n    // \"importHelpers\": true,                 /* Import emit helpers from 'tslib'. */\n    // \"downlevelIteration\": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */\n    // \"isolatedModules\": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */\n\n    /* Strict Type-Checking Options */\n    \"strict\": true /* Enable all strict type-checking options. */,\n    \"noImplicitAny\": true /* Raise error on expressions and declarations with an implied 'any' type. */,\n    \"strictNullChecks\": true /* Enable strict null checks. */,\n    \"strictFunctionTypes\": true /* Enable strict checking of function types. */,\n    \"strictBindCallApply\": true /* Enable strict 'bind', 'call', and 'apply' methods on functions. */,\n    \"strictPropertyInitialization\": true /* Enable strict checking of property initialization in classes. */,\n    \"noImplicitThis\": true /* Raise error on 'this' expressions with an implied 'any' type. */,\n    \"alwaysStrict\": true /* Parse in strict mode and emit \"use strict\" for each source file. */,\n\n    /* Additional Checks */\n    \"noUnusedLocals\": true /* Report errors on unused locals. */,\n    \"noUnusedParameters\": true /* Report errors on unused parameters. */,\n    \"noImplicitReturns\": true /* Report error when not all code paths in function return a value. */,\n    // \"noFallthroughCasesInSwitch\": true,    /* Report errors for fallthrough cases in switch statement. */\n\n    /* Module Resolution Options */\n    \"moduleResolution\": \"node\" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,\n    // \"baseUrl\": \"./\",                       /* Base directory to resolve non-absolute module names. */\n    // \"paths\": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */\n    // \"rootDirs\": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */\n    // \"typeRoots\": [],                       /* List of folders to include type definitions from. */\n    // \"types\": [],                           /* Type declaration files to be included in compilation. */\n    // \"allowSyntheticDefaultImports\": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */\n    \"esModuleInterop\": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */\n    // \"preserveSymlinks\": true,              /* Do not resolve the real path of symlinks. */\n    // \"allowUmdGlobalAccess\": true,          /* Allow accessing UMD globals from modules. */\n\n    /* Source Map Options */\n    // \"sourceRoot\": \"\",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */\n    // \"mapRoot\": \"\",                         /* Specify the location where debugger should locate map files instead of generated locations. */\n    // \"inlineSourceMap\": true,               /* Emit a single file with source maps instead of having a separate file. */\n    // \"inlineSources\": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */\n\n    /* Experimental Options */\n    // \"experimentalDecorators\": true,        /* Enables experimental support for ES7 decorators. */\n    // \"emitDecoratorMetadata\": true,         /* Enables experimental support for emitting type metadata for decorators. */\n  }\n}\n"
  }
]