| 1 | import * as markodown from "./mod"; |
| 2 | import * as marko from "@marko/compiler"; |
| 3 | import type * as rollup from "rollup"; |
| 4 | import * as path from "node:path"; |
| 5 | |
| 6 | export type RollupPluginOptions = |
| 7 | & Omit<markodown.TransformOptions, "source" | "format"> |
| 8 | & { |
| 9 | marko?: typeof marko; |
| 10 | markoOptions?: marko.Config; |
| 11 | }; |
| 12 | |
| 13 | /** |
| 14 | * Rollup bundling plugin for markodown files. |
| 15 | */ |
| 16 | export default function rollupPlugin( |
| 17 | options: RollupPluginOptions = {}, |
| 18 | ): rollup.Plugin { |
| 19 | const { compile } = options.marko ?? marko; |
| 20 | return { |
| 21 | name: "@clo/markodown/rollup.ts", |
| 22 | load: { |
| 23 | filter: { id: /\.(?:mdo|mkd)|-md\.marko$/ }, |
| 24 | order: "pre", |
| 25 | async handler(id) { |
| 26 | const source = await this.fs.readFile(id, { encoding: "utf8" }); |
| 27 | const result = markodown.transform({ |
| 28 | ...options, |
| 29 | source, |
| 30 | selfImport: "./" + path.basename(id), |
| 31 | }); |
| 32 | |
| 33 | if (!result.success) { |
| 34 | for (const err of result.errors) { |
| 35 | this.error({ |
| 36 | message: err.message, |
| 37 | loc: { |
| 38 | file: id, |
| 39 | line: err.line, |
| 40 | column: err.column - 1, |
| 41 | }, |
| 42 | }); |
| 43 | } |
| 44 | return null; |
| 45 | } |
| 46 | |
| 47 | console.log(result); |
| 48 | |
| 49 | // TODO: source maps! |
| 50 | // TODO: parse marko errors |
| 51 | const { code, meta } = await compile( |
| 52 | result.text, |
| 53 | id + ".marko", |
| 54 | { |
| 55 | sourceMaps: true, |
| 56 | ...options?.markoOptions, |
| 57 | }, |
| 58 | ); |
| 59 | |
| 60 | for (const file of meta.watchFiles ?? []) { |
| 61 | this.addWatchFile(file); |
| 62 | } |
| 63 | |
| 64 | return { code }; |
| 65 | }, |
| 66 | }, |
| 67 | }; |
| 68 | } |