vite-plugin-svelte-md 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Yosuke Ota
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,171 @@
1
+ # vite-plugin-svelte-md
2
+
3
+ Markdown with Svelte for Vite
4
+
5
+ _`vite-plugin-svelte-md` is heavily inspired by [vite-plugin-md](https://github.com/antfu/vite-plugin-md) package._
6
+
7
+ <!--
8
+ [![NPM license](https://img.shields.io/npm/l/vite-plugin-svelte-md.svg)](https://www.npmjs.com/package/vite-plugin-svelte-md)
9
+ [![NPM version](https://img.shields.io/npm/v/vite-plugin-svelte-md.svg)](https://www.npmjs.com/package/vite-plugin-svelte-md)
10
+ [![NPM downloads](https://img.shields.io/badge/dynamic/json.svg?label=downloads&colorB=green&suffix=/day&query=$.downloads&uri=https://api.npmjs.org//downloads/point/last-day/vite-plugin-svelte-md&maxAge=3600)](http://www.npmtrends.com/vite-plugin-svelte-md)
11
+ [![NPM downloads](https://img.shields.io/npm/dw/vite-plugin-svelte-md.svg)](http://www.npmtrends.com/vite-plugin-svelte-md)
12
+ [![NPM downloads](https://img.shields.io/npm/dm/vite-plugin-svelte-md.svg)](http://www.npmtrends.com/vite-plugin-svelte-md)
13
+ [![NPM downloads](https://img.shields.io/npm/dy/vite-plugin-svelte-md.svg)](http://www.npmtrends.com/vite-plugin-svelte-md)
14
+ [![NPM downloads](https://img.shields.io/npm/dt/vite-plugin-svelte-md.svg)](http://www.npmtrends.com/vite-plugin-svelte-md)
15
+ [![Build Status](https://github.com/ota-meshi/vite-plugin-svelte-md/workflows/CI/badge.svg?branch=main)](https://github.com/ota-meshi/vite-plugin-svelte-md/actions?query=workflow%3ACI)
16
+ [![Coverage Status](https://coveralls.io/repos/github/ota-meshi/vite-plugin-svelte-md/badge.svg?branch=main)](https://coveralls.io/github/ota-meshi/vite-plugin-svelte-md?branch=main)
17
+ -->
18
+
19
+ ## 📛 Features
20
+
21
+ This plugin converts markdown files to Svelte component templates.
22
+ Combined with [the Svelte plugin](https://github.com/sveltejs/vite-plugin-svelte), you can convert markdown files to Svelte components.
23
+
24
+ For example, Input:
25
+
26
+ ```md
27
+ ---
28
+ title: Markdown to Svelte
29
+ ---
30
+
31
+ # Convert Markdown to Svelte Component
32
+
33
+ - List
34
+ - List
35
+ - List
36
+
37
+ <script>
38
+ import MyComponent from './MyComponent.svelte'
39
+ </script>
40
+
41
+ <MyComponent>You can use Svelte components in Markdown</MyComponent>
42
+ ```
43
+
44
+ Output:
45
+
46
+ ```svelte
47
+ <script context="module">
48
+ export const frontmatter = { title: "Markdown to Svelte" };
49
+ </script>
50
+
51
+ <script>
52
+ import MyComponent from "./MyComponent.svelte";
53
+ </script>
54
+
55
+ <svelte:head>
56
+ <title>Markdown to Svelte</title>
57
+ <meta property="og:title" content="Markdown to Svelte" />
58
+ </svelte:head>
59
+
60
+ <div class="markdown-body">
61
+ <h1>Convert Markdown to Svelte Component</h1>
62
+ <ul>
63
+ <li>List</li>
64
+ <li>List</li>
65
+ <li>List</li>
66
+ </ul>
67
+
68
+ <p>
69
+ <MyComponent>You can use Svelte components in Markdown</MyComponent>
70
+ </p>
71
+ </div>
72
+ ```
73
+
74
+ ## 💿 Installation
75
+
76
+ ```bash
77
+ npm install --save-dev vite-plugin-svelte-md
78
+ ```
79
+
80
+ ## 📖 Usage
81
+
82
+ ### with [Vite]
83
+
84
+ Add it to `vite.config.js`
85
+
86
+ ```ts
87
+ // vite.config.js
88
+ import { defineConfig } from "vite";
89
+ import { svelte } from "@sveltejs/vite-plugin-svelte";
90
+ import svelteMd from "vite-plugin-svelte-md";
91
+
92
+ export default defineConfig({
93
+ plugins: [
94
+ svelte({
95
+ extensions: [".svelte", ".md"], // <--
96
+ }),
97
+ svelteMd(), // <--
98
+ ],
99
+ });
100
+ ```
101
+
102
+ ### with [SvelteKit]
103
+
104
+ Add it to `svelte.config.js`
105
+
106
+ ```js
107
+ // svelte.config.js
108
+ import svelteMd from "vite-plugin-svelte-md";
109
+
110
+ /** @type {import('@sveltejs/kit').Config} */
111
+ const config = {
112
+ extensions: [".svelte", ".md"], // <--
113
+ kit: {
114
+ vite: {
115
+ plugins: [
116
+ svelteMd(), // <--
117
+ ],
118
+ },
119
+ },
120
+ };
121
+ ```
122
+
123
+ [sveltekit]: https://kit.svelte.dev/
124
+ [vite]: https://vitejs.dev/
125
+
126
+ ### Options
127
+
128
+ ```js
129
+ import svelteMd from "vite-plugin-svelte-md";
130
+ svelteMd({
131
+ headEnabled: true,
132
+ markdownItOptions: {},
133
+ markdownItUses: [],
134
+ wrapperClasses: "markdown-body",
135
+ });
136
+ ```
137
+
138
+ #### `headEnabled`
139
+
140
+ Enables head tag generation from frontmatter. The default is `true`.
141
+
142
+ #### `markdownItOptions`
143
+
144
+ [markdown-it](https://github.com/markdown-it/markdown-it)'s option.
145
+ See [markdown-it's docs](https://markdown-it.github.io/markdown-it/) for more details.
146
+
147
+ #### `markdownItUses`
148
+
149
+ An array of [markdown-it](https://github.com/markdown-it/markdown-it)'s plugins.
150
+
151
+ Example:
152
+
153
+ ```js
154
+ svelteMd({
155
+ markdownItUses: [require("markdown-it-anchor"), require("markdown-it-prism")],
156
+ });
157
+ ```
158
+
159
+ #### `wrapperClasses`
160
+
161
+ The class name of the div that wraps the content.
162
+
163
+ ## :beers: Contributing
164
+
165
+ Welcome contributing!
166
+
167
+ Please use GitHub's Issues/PRs.
168
+
169
+ ## :lock: License
170
+
171
+ See the [LICENSE](LICENSE) file for license rights and limitations (MIT).
package/lib/index.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { Plugin } from 'vite';
2
+ import MarkdownIt from 'markdown-it';
3
+ import { FilterPattern } from '@rollup/pluginutils';
4
+
5
+ interface Options {
6
+ /**
7
+ * Enable head support
8
+ *
9
+ * @default true
10
+ */
11
+ headEnabled?: boolean;
12
+ /**
13
+ * Options passed to Markdown It
14
+ */
15
+ markdownItOptions?: MarkdownIt.Options;
16
+ /**
17
+ * Plugins for Markdown It
18
+ */
19
+ markdownItUses?: (MarkdownIt.PluginSimple | [MarkdownIt.PluginSimple | MarkdownIt.PluginWithOptions, any] | any)[];
20
+ /**
21
+ * Class names for wrapper div
22
+ *
23
+ * @default 'markdown-body'
24
+ */
25
+ wrapperClasses?: string | string[];
26
+ include?: FilterPattern;
27
+ exclude?: FilterPattern;
28
+ }
29
+
30
+ /**
31
+ * Creates vite-plugin-svelte-md
32
+ */
33
+ declare function export_default(options?: Options): Plugin;
34
+
35
+ export { export_default as default };
package/lib/index.js ADDED
@@ -0,0 +1,304 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
25
+ var __export = (target, all) => {
26
+ __markAsModule(target);
27
+ for (var name in all)
28
+ __defProp(target, name, { get: all[name], enumerable: true });
29
+ };
30
+ var __reExport = (target, module2, desc) => {
31
+ if (module2 && typeof module2 === "object" || typeof module2 === "function") {
32
+ for (let key of __getOwnPropNames(module2))
33
+ if (!__hasOwnProp.call(target, key) && key !== "default")
34
+ __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
35
+ }
36
+ return target;
37
+ };
38
+ var __toModule = (module2) => {
39
+ return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
40
+ };
41
+
42
+ // src/index.ts
43
+ __export(exports, {
44
+ default: () => src_default
45
+ });
46
+ var import_pluginutils = __toModule(require("@rollup/pluginutils"));
47
+
48
+ // src/markdown.ts
49
+ var import_markdown_it = __toModule(require("markdown-it"));
50
+ var import_gray_matter = __toModule(require("gray-matter"));
51
+
52
+ // src/markdown-it-svelte-tags/index.ts
53
+ var SVELTE_TAGS_RE = /^(?:<svelte:[a-z][^>]*>|<\/svelte:[a-z]+>)/u;
54
+ function plugin(md) {
55
+ md.inline.ruler.push("svelte-tags", (state) => {
56
+ if (!state.md.options.html) {
57
+ return false;
58
+ }
59
+ const pos = state.pos;
60
+ const text = state.src.slice(pos);
61
+ const match = SVELTE_TAGS_RE.exec(text);
62
+ if (!match) {
63
+ return false;
64
+ }
65
+ const token = state.push("html_inline", "", 0);
66
+ token.content = state.src.slice(pos, pos + match[0].length);
67
+ state.pos += match[0].length;
68
+ return true;
69
+ });
70
+ }
71
+
72
+ // src/utils.ts
73
+ function toArray(n) {
74
+ if (!Array.isArray(n))
75
+ return [n];
76
+ return n;
77
+ }
78
+
79
+ // src/head.ts
80
+ var headProperties = [
81
+ "title",
82
+ "meta",
83
+ "link",
84
+ "base",
85
+ "style",
86
+ "script",
87
+ "htmlAttrs",
88
+ "bodyAttrs"
89
+ ];
90
+ function preprocessHead(frontmatter, options) {
91
+ if (!options.headEnabled)
92
+ return frontmatter;
93
+ const head = frontmatter;
94
+ const meta = Array.isArray(head.meta) ? [...head.meta] : [];
95
+ if (head.title) {
96
+ if (!meta.find((i) => i.property === "og:title"))
97
+ meta.push({ property: "og:title", content: head.title });
98
+ }
99
+ if (head.description) {
100
+ if (!meta.find((i) => i.property === "og:description"))
101
+ meta.push({
102
+ property: "og:description",
103
+ content: head.description
104
+ });
105
+ if (!meta.find((i) => i.name === "description"))
106
+ meta.push({ name: "description", content: head.description });
107
+ }
108
+ if (head.image) {
109
+ if (!meta.find((i) => i.property === "og:image"))
110
+ meta.push({ property: "og:image", content: head.image });
111
+ if (!meta.find((i) => i.property === "twitter:card"))
112
+ meta.push({
113
+ name: "twitter:card",
114
+ content: "summary_large_image"
115
+ });
116
+ }
117
+ const result = {};
118
+ for (const [key, value] of Object.entries(head)) {
119
+ if (headProperties.includes(key))
120
+ result[key] = value;
121
+ }
122
+ if (meta.length > 0) {
123
+ result.meta = meta;
124
+ }
125
+ return Object.entries(result).length === 0 ? null : result;
126
+ }
127
+ function headObjToTags(obj) {
128
+ const tags = [];
129
+ for (const key of Object.keys(obj)) {
130
+ if (obj[key] == null)
131
+ continue;
132
+ if (key === "title") {
133
+ tags.push(`<title>${obj[key]}</title>`);
134
+ } else if (key === "base") {
135
+ tags.push(`<base ${attrs(__spreadValues({ key: "default" }, obj[key]))}>`);
136
+ } else if (headProperties.includes(key)) {
137
+ const value = obj[key];
138
+ if (Array.isArray(value)) {
139
+ value.forEach((item) => {
140
+ tags.push(`<${key} ${attrs(item)}>`);
141
+ });
142
+ } else if (value) {
143
+ tags.push(`<${key} ${attrs(value)}>`);
144
+ }
145
+ }
146
+ }
147
+ return tags;
148
+ function attrs(o) {
149
+ return Object.entries(o).map(([k, v]) => `${k}="${`${v}`.replace(/"/gu, "&quot;")}"`).join(" ");
150
+ }
151
+ }
152
+
153
+ // src/markdown.ts
154
+ var SCRIPTS_RE = /(<script[^>]*>)([\s\S]*?)<\/script>/gu;
155
+ var SVELTE_TAGS_RE2 = /(<svelte:[a-z][^>]*>)([\s\S]*?)<\/svelte:[a-z]+>/gu;
156
+ var GET_SVELTE_TAG_NAME_RE = /^svelte:[a-z]+/u;
157
+ var IS_MODULE_CONTEXT_RE = /\bcontext\s*=\s*["']?module["']?/u;
158
+ var IS_SVELTE_TAG_NAME_RE = /^svelte:[a-z]+$/u;
159
+ var TagContent = class {
160
+ constructor(tagName, defaultAttrs) {
161
+ this.startTag = "";
162
+ this.contents = [];
163
+ this.tagName = tagName;
164
+ this.defaultAttrs = defaultAttrs;
165
+ }
166
+ toTag() {
167
+ return `${this.startTag || `<${this.tagName}${this.defaultAttrs ? ` ${this.defaultAttrs}` : ""}>`}
168
+ ${this.contents.join("\n")}
169
+ </${this.tagName}>`;
170
+ }
171
+ addTag(startTag, content) {
172
+ if (!this.startTag) {
173
+ this.startTag = startTag;
174
+ }
175
+ this.contents.push(content);
176
+ }
177
+ add(content) {
178
+ this.contents.push(content);
179
+ }
180
+ prepend(content) {
181
+ this.contents.unshift(content);
182
+ }
183
+ };
184
+ function parseHtml(html) {
185
+ const moduleContext = new TagContent("script", 'context="module"');
186
+ const instanceScript = new TagContent("script");
187
+ const svelteTags = [];
188
+ let newHtml = html.replace(SCRIPTS_RE, (_, startTag, script) => {
189
+ let scriptContent = instanceScript;
190
+ if (IS_MODULE_CONTEXT_RE.test(startTag)) {
191
+ scriptContent = moduleContext;
192
+ }
193
+ scriptContent.addTag(startTag, script);
194
+ return "";
195
+ });
196
+ newHtml = newHtml.replace(SVELTE_TAGS_RE2, (_, startTag, inner) => {
197
+ const tagName = GET_SVELTE_TAG_NAME_RE.exec(startTag.slice(1))[0].toLowerCase();
198
+ let svelteTag = svelteTags.find((tag) => tag.tagName === tagName);
199
+ if (!svelteTag) {
200
+ svelteTag = new TagContent(tagName);
201
+ svelteTags.push(svelteTag);
202
+ }
203
+ svelteTag.addTag(startTag, inner);
204
+ return "";
205
+ });
206
+ return { html: newHtml, moduleContext, instanceScript, svelteTags };
207
+ }
208
+ function createMarkdownProcessor(options) {
209
+ const markdownIt = new import_markdown_it.default(__spreadValues({
210
+ html: true,
211
+ linkify: true,
212
+ typographer: true
213
+ }, options.markdownItOptions));
214
+ markdownIt.linkify.set({ fuzzyLink: false });
215
+ const originalValidateLink = markdownIt.validateLink;
216
+ markdownIt.validateLink = (url) => {
217
+ if (!originalValidateLink(url)) {
218
+ return false;
219
+ }
220
+ return !IS_SVELTE_TAG_NAME_RE.test(url);
221
+ };
222
+ markdownIt.use(plugin);
223
+ options.markdownItUses.forEach((e) => {
224
+ const [plugin2, options2] = toArray(e);
225
+ markdownIt.use(plugin2, options2);
226
+ });
227
+ return (id, text) => {
228
+ var _a, _b;
229
+ const raw = text.trimEnd();
230
+ const { wrapperClasses, headEnabled } = options;
231
+ const parsedFrontmatter = (0, import_gray_matter.default)(raw);
232
+ const plainMarkdown = (_a = parsedFrontmatter == null ? void 0 : parsedFrontmatter.content) != null ? _a : raw;
233
+ let html = markdownIt.render(plainMarkdown, { id });
234
+ if (wrapperClasses) {
235
+ html = `<div class="${wrapperClasses}">${html}</div>`;
236
+ }
237
+ const parsedHtml = parseHtml(html);
238
+ const { head, frontmatter } = frontmatterPreprocess((_b = parsedFrontmatter == null ? void 0 : parsedFrontmatter.data) != null ? _b : {}, options);
239
+ parsedHtml.moduleContext.prepend(`export const frontmatter = ${JSON.stringify(frontmatter)}`);
240
+ if (headEnabled && head) {
241
+ let svelteHead = parsedHtml.svelteTags.find((tag) => tag.tagName === "svelte:head");
242
+ if (!svelteHead) {
243
+ svelteHead = new TagContent("svelte:head");
244
+ parsedHtml.svelteTags.push(svelteHead);
245
+ }
246
+ svelteHead.add(`${headObjToTags(head).join("\n")}`);
247
+ }
248
+ const svelteSfc = `${parsedHtml.moduleContext.toTag()}
249
+ ${parsedHtml.instanceScript.toTag()}
250
+ ${parsedHtml.svelteTags.map((tag) => tag.toTag()).join("\n")}
251
+ ${parsedHtml.html}`;
252
+ return svelteSfc;
253
+ };
254
+ }
255
+ function frontmatterPreprocess(frontmatter, options) {
256
+ const head = preprocessHead(frontmatter, options);
257
+ return { head, frontmatter };
258
+ }
259
+
260
+ // src/options.ts
261
+ function resolveOptions(userOptions) {
262
+ var _a;
263
+ const options = __spreadProps(__spreadValues({
264
+ headEnabled: true,
265
+ markdownItOptions: {},
266
+ markdownItUses: [],
267
+ include: null,
268
+ exclude: null
269
+ }, userOptions), {
270
+ wrapperClasses: toArray((_a = userOptions.wrapperClasses) != null ? _a : "markdown-body").filter((i) => i).join(" ")
271
+ });
272
+ return options;
273
+ }
274
+
275
+ // src/index.ts
276
+ function src_default(options = {}) {
277
+ const resolvedOptions = resolveOptions(options);
278
+ const mdToSvelte = createMarkdownProcessor(resolvedOptions);
279
+ const filter = (0, import_pluginutils.createFilter)(resolvedOptions.include || /\.md$/, resolvedOptions.exclude);
280
+ return {
281
+ name: "vite-plugin-svelte-md",
282
+ enforce: "pre",
283
+ transform(raw, id) {
284
+ if (!filter(id))
285
+ return void 0;
286
+ try {
287
+ return mdToSvelte(id, raw);
288
+ } catch (e) {
289
+ this.error(e);
290
+ }
291
+ return void 0;
292
+ },
293
+ handleHotUpdate(ctx) {
294
+ if (!filter(ctx.file))
295
+ return;
296
+ const defaultRead = ctx.read;
297
+ ctx.read = async function() {
298
+ return mdToSvelte(ctx.file, await defaultRead());
299
+ };
300
+ }
301
+ };
302
+ }
303
+ // Annotate the CommonJS export names for ESM import in node:
304
+ 0 && (module.exports = {});
package/lib/index.mjs ADDED
@@ -0,0 +1,281 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+
21
+ // src/index.ts
22
+ import { createFilter } from "@rollup/pluginutils";
23
+
24
+ // src/markdown.ts
25
+ import MarkdownIt from "markdown-it";
26
+ import grayMatter from "gray-matter";
27
+
28
+ // src/markdown-it-svelte-tags/index.ts
29
+ var SVELTE_TAGS_RE = /^(?:<svelte:[a-z][^>]*>|<\/svelte:[a-z]+>)/u;
30
+ function plugin(md) {
31
+ md.inline.ruler.push("svelte-tags", (state) => {
32
+ if (!state.md.options.html) {
33
+ return false;
34
+ }
35
+ const pos = state.pos;
36
+ const text = state.src.slice(pos);
37
+ const match = SVELTE_TAGS_RE.exec(text);
38
+ if (!match) {
39
+ return false;
40
+ }
41
+ const token = state.push("html_inline", "", 0);
42
+ token.content = state.src.slice(pos, pos + match[0].length);
43
+ state.pos += match[0].length;
44
+ return true;
45
+ });
46
+ }
47
+
48
+ // src/utils.ts
49
+ function toArray(n) {
50
+ if (!Array.isArray(n))
51
+ return [n];
52
+ return n;
53
+ }
54
+
55
+ // src/head.ts
56
+ var headProperties = [
57
+ "title",
58
+ "meta",
59
+ "link",
60
+ "base",
61
+ "style",
62
+ "script",
63
+ "htmlAttrs",
64
+ "bodyAttrs"
65
+ ];
66
+ function preprocessHead(frontmatter, options) {
67
+ if (!options.headEnabled)
68
+ return frontmatter;
69
+ const head = frontmatter;
70
+ const meta = Array.isArray(head.meta) ? [...head.meta] : [];
71
+ if (head.title) {
72
+ if (!meta.find((i) => i.property === "og:title"))
73
+ meta.push({ property: "og:title", content: head.title });
74
+ }
75
+ if (head.description) {
76
+ if (!meta.find((i) => i.property === "og:description"))
77
+ meta.push({
78
+ property: "og:description",
79
+ content: head.description
80
+ });
81
+ if (!meta.find((i) => i.name === "description"))
82
+ meta.push({ name: "description", content: head.description });
83
+ }
84
+ if (head.image) {
85
+ if (!meta.find((i) => i.property === "og:image"))
86
+ meta.push({ property: "og:image", content: head.image });
87
+ if (!meta.find((i) => i.property === "twitter:card"))
88
+ meta.push({
89
+ name: "twitter:card",
90
+ content: "summary_large_image"
91
+ });
92
+ }
93
+ const result = {};
94
+ for (const [key, value] of Object.entries(head)) {
95
+ if (headProperties.includes(key))
96
+ result[key] = value;
97
+ }
98
+ if (meta.length > 0) {
99
+ result.meta = meta;
100
+ }
101
+ return Object.entries(result).length === 0 ? null : result;
102
+ }
103
+ function headObjToTags(obj) {
104
+ const tags = [];
105
+ for (const key of Object.keys(obj)) {
106
+ if (obj[key] == null)
107
+ continue;
108
+ if (key === "title") {
109
+ tags.push(`<title>${obj[key]}</title>`);
110
+ } else if (key === "base") {
111
+ tags.push(`<base ${attrs(__spreadValues({ key: "default" }, obj[key]))}>`);
112
+ } else if (headProperties.includes(key)) {
113
+ const value = obj[key];
114
+ if (Array.isArray(value)) {
115
+ value.forEach((item) => {
116
+ tags.push(`<${key} ${attrs(item)}>`);
117
+ });
118
+ } else if (value) {
119
+ tags.push(`<${key} ${attrs(value)}>`);
120
+ }
121
+ }
122
+ }
123
+ return tags;
124
+ function attrs(o) {
125
+ return Object.entries(o).map(([k, v]) => `${k}="${`${v}`.replace(/"/gu, "&quot;")}"`).join(" ");
126
+ }
127
+ }
128
+
129
+ // src/markdown.ts
130
+ var SCRIPTS_RE = /(<script[^>]*>)([\s\S]*?)<\/script>/gu;
131
+ var SVELTE_TAGS_RE2 = /(<svelte:[a-z][^>]*>)([\s\S]*?)<\/svelte:[a-z]+>/gu;
132
+ var GET_SVELTE_TAG_NAME_RE = /^svelte:[a-z]+/u;
133
+ var IS_MODULE_CONTEXT_RE = /\bcontext\s*=\s*["']?module["']?/u;
134
+ var IS_SVELTE_TAG_NAME_RE = /^svelte:[a-z]+$/u;
135
+ var TagContent = class {
136
+ constructor(tagName, defaultAttrs) {
137
+ this.startTag = "";
138
+ this.contents = [];
139
+ this.tagName = tagName;
140
+ this.defaultAttrs = defaultAttrs;
141
+ }
142
+ toTag() {
143
+ return `${this.startTag || `<${this.tagName}${this.defaultAttrs ? ` ${this.defaultAttrs}` : ""}>`}
144
+ ${this.contents.join("\n")}
145
+ </${this.tagName}>`;
146
+ }
147
+ addTag(startTag, content) {
148
+ if (!this.startTag) {
149
+ this.startTag = startTag;
150
+ }
151
+ this.contents.push(content);
152
+ }
153
+ add(content) {
154
+ this.contents.push(content);
155
+ }
156
+ prepend(content) {
157
+ this.contents.unshift(content);
158
+ }
159
+ };
160
+ function parseHtml(html) {
161
+ const moduleContext = new TagContent("script", 'context="module"');
162
+ const instanceScript = new TagContent("script");
163
+ const svelteTags = [];
164
+ let newHtml = html.replace(SCRIPTS_RE, (_, startTag, script) => {
165
+ let scriptContent = instanceScript;
166
+ if (IS_MODULE_CONTEXT_RE.test(startTag)) {
167
+ scriptContent = moduleContext;
168
+ }
169
+ scriptContent.addTag(startTag, script);
170
+ return "";
171
+ });
172
+ newHtml = newHtml.replace(SVELTE_TAGS_RE2, (_, startTag, inner) => {
173
+ const tagName = GET_SVELTE_TAG_NAME_RE.exec(startTag.slice(1))[0].toLowerCase();
174
+ let svelteTag = svelteTags.find((tag) => tag.tagName === tagName);
175
+ if (!svelteTag) {
176
+ svelteTag = new TagContent(tagName);
177
+ svelteTags.push(svelteTag);
178
+ }
179
+ svelteTag.addTag(startTag, inner);
180
+ return "";
181
+ });
182
+ return { html: newHtml, moduleContext, instanceScript, svelteTags };
183
+ }
184
+ function createMarkdownProcessor(options) {
185
+ const markdownIt = new MarkdownIt(__spreadValues({
186
+ html: true,
187
+ linkify: true,
188
+ typographer: true
189
+ }, options.markdownItOptions));
190
+ markdownIt.linkify.set({ fuzzyLink: false });
191
+ const originalValidateLink = markdownIt.validateLink;
192
+ markdownIt.validateLink = (url) => {
193
+ if (!originalValidateLink(url)) {
194
+ return false;
195
+ }
196
+ return !IS_SVELTE_TAG_NAME_RE.test(url);
197
+ };
198
+ markdownIt.use(plugin);
199
+ options.markdownItUses.forEach((e) => {
200
+ const [plugin2, options2] = toArray(e);
201
+ markdownIt.use(plugin2, options2);
202
+ });
203
+ return (id, text) => {
204
+ var _a, _b;
205
+ const raw = text.trimEnd();
206
+ const { wrapperClasses, headEnabled } = options;
207
+ const parsedFrontmatter = grayMatter(raw);
208
+ const plainMarkdown = (_a = parsedFrontmatter == null ? void 0 : parsedFrontmatter.content) != null ? _a : raw;
209
+ let html = markdownIt.render(plainMarkdown, { id });
210
+ if (wrapperClasses) {
211
+ html = `<div class="${wrapperClasses}">${html}</div>`;
212
+ }
213
+ const parsedHtml = parseHtml(html);
214
+ const { head, frontmatter } = frontmatterPreprocess((_b = parsedFrontmatter == null ? void 0 : parsedFrontmatter.data) != null ? _b : {}, options);
215
+ parsedHtml.moduleContext.prepend(`export const frontmatter = ${JSON.stringify(frontmatter)}`);
216
+ if (headEnabled && head) {
217
+ let svelteHead = parsedHtml.svelteTags.find((tag) => tag.tagName === "svelte:head");
218
+ if (!svelteHead) {
219
+ svelteHead = new TagContent("svelte:head");
220
+ parsedHtml.svelteTags.push(svelteHead);
221
+ }
222
+ svelteHead.add(`${headObjToTags(head).join("\n")}`);
223
+ }
224
+ const svelteSfc = `${parsedHtml.moduleContext.toTag()}
225
+ ${parsedHtml.instanceScript.toTag()}
226
+ ${parsedHtml.svelteTags.map((tag) => tag.toTag()).join("\n")}
227
+ ${parsedHtml.html}`;
228
+ return svelteSfc;
229
+ };
230
+ }
231
+ function frontmatterPreprocess(frontmatter, options) {
232
+ const head = preprocessHead(frontmatter, options);
233
+ return { head, frontmatter };
234
+ }
235
+
236
+ // src/options.ts
237
+ function resolveOptions(userOptions) {
238
+ var _a;
239
+ const options = __spreadProps(__spreadValues({
240
+ headEnabled: true,
241
+ markdownItOptions: {},
242
+ markdownItUses: [],
243
+ include: null,
244
+ exclude: null
245
+ }, userOptions), {
246
+ wrapperClasses: toArray((_a = userOptions.wrapperClasses) != null ? _a : "markdown-body").filter((i) => i).join(" ")
247
+ });
248
+ return options;
249
+ }
250
+
251
+ // src/index.ts
252
+ function src_default(options = {}) {
253
+ const resolvedOptions = resolveOptions(options);
254
+ const mdToSvelte = createMarkdownProcessor(resolvedOptions);
255
+ const filter = createFilter(resolvedOptions.include || /\.md$/, resolvedOptions.exclude);
256
+ return {
257
+ name: "vite-plugin-svelte-md",
258
+ enforce: "pre",
259
+ transform(raw, id) {
260
+ if (!filter(id))
261
+ return void 0;
262
+ try {
263
+ return mdToSvelte(id, raw);
264
+ } catch (e) {
265
+ this.error(e);
266
+ }
267
+ return void 0;
268
+ },
269
+ handleHotUpdate(ctx) {
270
+ if (!filter(ctx.file))
271
+ return;
272
+ const defaultRead = ctx.read;
273
+ ctx.read = async function() {
274
+ return mdToSvelte(ctx.file, await defaultRead());
275
+ };
276
+ }
277
+ };
278
+ }
279
+ export {
280
+ src_default as default
281
+ };
package/package.json ADDED
@@ -0,0 +1,87 @@
1
+ {
2
+ "name": "vite-plugin-svelte-md",
3
+ "version": "0.1.0",
4
+ "description": "Vite plugin to convert markdown to svelte template",
5
+ "files": [
6
+ "lib"
7
+ ],
8
+ "main": "./lib/index.js",
9
+ "module": "./lib/index.mjs",
10
+ "exports": {
11
+ ".": {
12
+ "import": "./lib/index.mjs",
13
+ "require": "./lib/index.js"
14
+ }
15
+ },
16
+ "types": "./lib/index.d.ts",
17
+ "scripts": {
18
+ "prebuild": "npm run -s clean",
19
+ "build": "tsup",
20
+ "clean": "rimraf .nyc_output lib coverage",
21
+ "lint": "eslint . --ext .js,.ts,.json",
22
+ "eslint-fix": "npm run lint -- --fix",
23
+ "format:docs": "prettier README.md --write",
24
+ "test": "mocha --require ts-node/register \"tests/**/*.ts\" --reporter dot --timeout 60000",
25
+ "cover": "nyc --reporter=lcov npm run test",
26
+ "debug": "mocha --require ts-node/register/transpile-only \"tests/**/*.ts\" --reporter dot",
27
+ "update-snap": "mocha --require ts-node/register/transpile-only \"tests/**/*.ts\" --reporter dot --update",
28
+ "preversion": "npm run lint && npm test"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/ota-meshi/vite-plugin-svelte-md.git"
33
+ },
34
+ "keywords": [
35
+ "vite",
36
+ "vite-plugin",
37
+ "svelte",
38
+ "markdown",
39
+ "markdown-it"
40
+ ],
41
+ "author": "Yosuke Ota",
42
+ "funding": "https://github.com/sponsors/ota-meshi",
43
+ "license": "MIT",
44
+ "bugs": {
45
+ "url": "https://github.com/ota-meshi/vite-plugin-svelte-md/issues"
46
+ },
47
+ "homepage": "https://github.com/ota-meshi/vite-plugin-svelte-md#readme",
48
+ "peerDependencies": {
49
+ "vite": "^2.0.0"
50
+ },
51
+ "dependencies": {
52
+ "@rollup/pluginutils": "^4.1.1",
53
+ "gray-matter": "^4.0.3",
54
+ "markdown-it": "^12.2.0"
55
+ },
56
+ "devDependencies": {
57
+ "@ota-meshi/eslint-plugin": "^0.10.0",
58
+ "@types/chai": "^4.2.22",
59
+ "@types/estree": "0.0.50",
60
+ "@types/markdown-it": "^12.2.3",
61
+ "@types/mocha": "^9.0.0",
62
+ "@types/node": "^16.11.11",
63
+ "@typescript-eslint/eslint-plugin": "^5.5.0",
64
+ "@typescript-eslint/parser": "^5.5.0",
65
+ "chai": "^4.3.4",
66
+ "eslint": "^8.3.0",
67
+ "eslint-config-prettier": "^8.3.0",
68
+ "eslint-plugin-eslint-comments": "^3.2.0",
69
+ "eslint-plugin-json-schema-validator": "^2.1.10",
70
+ "eslint-plugin-jsonc": "^2.0.0",
71
+ "eslint-plugin-node": "^11.1.0",
72
+ "eslint-plugin-node-dependencies": "^0.6.0",
73
+ "eslint-plugin-prettier": "^4.0.0",
74
+ "eslint-plugin-regexp": "^1.0.0",
75
+ "mocha": "^9.1.3",
76
+ "mocha-chai-jest-snapshot": "^1.1.3",
77
+ "nyc": "^15.1.0",
78
+ "prettier": "^2.5.0",
79
+ "prettier-plugin-svelte": "^2.5.0",
80
+ "rimraf": "^3.0.2",
81
+ "svelte": "^3.44.2",
82
+ "ts-node": "^10.4.0",
83
+ "tsup": "^5.10.0",
84
+ "typescript": "^4.5.2",
85
+ "vite": "^2.6.14"
86
+ }
87
+ }