@astrojs/markdown-remark 0.0.0-add-stable-20231208215901

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,59 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Fred K. Schott
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.
22
+
23
+ """
24
+ This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/sveltejs/kit repository:
25
+
26
+ Copyright (c) 2020 [these people](https://github.com/sveltejs/kit/graphs/contributors)
27
+
28
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
29
+
30
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
31
+
32
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33
+ """
34
+
35
+ """
36
+ This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/vitejs/vite repository:
37
+
38
+ MIT License
39
+
40
+ Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors
41
+
42
+ Permission is hereby granted, free of charge, to any person obtaining a copy
43
+ of this software and associated documentation files (the "Software"), to deal
44
+ in the Software without restriction, including without limitation the rights
45
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
46
+ copies of the Software, and to permit persons to whom the Software is
47
+ furnished to do so, subject to the following conditions:
48
+
49
+ The above copyright notice and this permission notice shall be included in all
50
+ copies or substantial portions of the Software.
51
+
52
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
53
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
54
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
55
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
56
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
57
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
58
+ SOFTWARE.
59
+ """
@@ -0,0 +1,6 @@
1
+ import type { VFileData as Data, VFile } from 'vfile';
2
+ import type { MarkdownAstroData } from './types.js';
3
+ export declare class InvalidAstroDataError extends TypeError {
4
+ }
5
+ export declare function safelyGetAstroData(vfileData: Data): MarkdownAstroData | InvalidAstroDataError;
6
+ export declare function setVfileFrontmatter(vfile: VFile, frontmatter: Record<string, any>): void;
@@ -0,0 +1,31 @@
1
+ function isValidAstroData(obj) {
2
+ if (typeof obj === "object" && obj !== null && obj.hasOwnProperty("frontmatter")) {
3
+ const { frontmatter } = obj;
4
+ try {
5
+ JSON.stringify(frontmatter);
6
+ } catch {
7
+ return false;
8
+ }
9
+ return typeof frontmatter === "object" && frontmatter !== null;
10
+ }
11
+ return false;
12
+ }
13
+ class InvalidAstroDataError extends TypeError {
14
+ }
15
+ function safelyGetAstroData(vfileData) {
16
+ const { astro } = vfileData;
17
+ if (!astro || !isValidAstroData(astro)) {
18
+ return new InvalidAstroDataError();
19
+ }
20
+ return astro;
21
+ }
22
+ function setVfileFrontmatter(vfile, frontmatter) {
23
+ vfile.data ??= {};
24
+ vfile.data.astro ??= {};
25
+ vfile.data.astro.frontmatter = frontmatter;
26
+ }
27
+ export {
28
+ InvalidAstroDataError,
29
+ safelyGetAstroData,
30
+ setVfileFrontmatter
31
+ };
@@ -0,0 +1,13 @@
1
+ import type { AstroMarkdownOptions, MarkdownProcessor } from './types.js';
2
+ export { InvalidAstroDataError, setVfileFrontmatter } from './frontmatter-injection.js';
3
+ export { rehypeHeadingIds } from './rehype-collect-headings.js';
4
+ export { remarkCollectImages } from './remark-collect-images.js';
5
+ export { remarkPrism } from './remark-prism.js';
6
+ export { remarkShiki } from './remark-shiki.js';
7
+ export { createShikiHighlighter, replaceCssVariables, type ShikiHighlighter } from './shiki.js';
8
+ export * from './types.js';
9
+ export declare const markdownConfigDefaults: Required<AstroMarkdownOptions>;
10
+ /**
11
+ * Create a markdown preprocessor to render multiple markdown files
12
+ */
13
+ export declare function createMarkdownProcessor(opts?: AstroMarkdownOptions): Promise<MarkdownProcessor>;
package/dist/index.js ADDED
@@ -0,0 +1,139 @@
1
+ import {
2
+ InvalidAstroDataError,
3
+ safelyGetAstroData,
4
+ setVfileFrontmatter
5
+ } from "./frontmatter-injection.js";
6
+ import { loadPlugins } from "./load-plugins.js";
7
+ import { rehypeHeadingIds } from "./rehype-collect-headings.js";
8
+ import { remarkCollectImages } from "./remark-collect-images.js";
9
+ import { remarkPrism } from "./remark-prism.js";
10
+ import { remarkShiki } from "./remark-shiki.js";
11
+ import rehypeRaw from "rehype-raw";
12
+ import rehypeStringify from "rehype-stringify";
13
+ import remarkGfm from "remark-gfm";
14
+ import remarkParse from "remark-parse";
15
+ import remarkRehype from "remark-rehype";
16
+ import remarkSmartypants from "remark-smartypants";
17
+ import { unified } from "unified";
18
+ import { VFile } from "vfile";
19
+ import { rehypeImages } from "./rehype-images.js";
20
+ import { InvalidAstroDataError as InvalidAstroDataError2, setVfileFrontmatter as setVfileFrontmatter2 } from "./frontmatter-injection.js";
21
+ import { rehypeHeadingIds as rehypeHeadingIds2 } from "./rehype-collect-headings.js";
22
+ import { remarkCollectImages as remarkCollectImages2 } from "./remark-collect-images.js";
23
+ import { remarkPrism as remarkPrism2 } from "./remark-prism.js";
24
+ import { remarkShiki as remarkShiki2 } from "./remark-shiki.js";
25
+ import { createShikiHighlighter, replaceCssVariables } from "./shiki.js";
26
+ export * from "./types.js";
27
+ const markdownConfigDefaults = {
28
+ syntaxHighlight: "shiki",
29
+ shikiConfig: {
30
+ langs: [],
31
+ theme: "github-dark",
32
+ experimentalThemes: {},
33
+ wrap: false
34
+ },
35
+ remarkPlugins: [],
36
+ rehypePlugins: [],
37
+ remarkRehype: {},
38
+ gfm: true,
39
+ smartypants: true
40
+ };
41
+ const isPerformanceBenchmark = Boolean(process.env.ASTRO_PERFORMANCE_BENCHMARK);
42
+ async function createMarkdownProcessor(opts) {
43
+ const {
44
+ syntaxHighlight = markdownConfigDefaults.syntaxHighlight,
45
+ shikiConfig = markdownConfigDefaults.shikiConfig,
46
+ remarkPlugins = markdownConfigDefaults.remarkPlugins,
47
+ rehypePlugins = markdownConfigDefaults.rehypePlugins,
48
+ remarkRehype: remarkRehypeOptions = markdownConfigDefaults.remarkRehype,
49
+ gfm = markdownConfigDefaults.gfm,
50
+ smartypants = markdownConfigDefaults.smartypants
51
+ } = opts ?? {};
52
+ const loadedRemarkPlugins = await Promise.all(loadPlugins(remarkPlugins));
53
+ const loadedRehypePlugins = await Promise.all(loadPlugins(rehypePlugins));
54
+ const parser = unified().use(remarkParse);
55
+ if (!isPerformanceBenchmark) {
56
+ if (gfm) {
57
+ parser.use(remarkGfm);
58
+ }
59
+ if (smartypants) {
60
+ parser.use(remarkSmartypants);
61
+ }
62
+ }
63
+ for (const [plugin, pluginOpts] of loadedRemarkPlugins) {
64
+ parser.use(plugin, pluginOpts);
65
+ }
66
+ if (!isPerformanceBenchmark) {
67
+ if (syntaxHighlight === "shiki") {
68
+ parser.use(remarkShiki, shikiConfig);
69
+ } else if (syntaxHighlight === "prism") {
70
+ parser.use(remarkPrism);
71
+ }
72
+ parser.use(remarkCollectImages);
73
+ }
74
+ parser.use(remarkRehype, {
75
+ allowDangerousHtml: true,
76
+ passThrough: [],
77
+ ...remarkRehypeOptions
78
+ });
79
+ for (const [plugin, pluginOpts] of loadedRehypePlugins) {
80
+ parser.use(plugin, pluginOpts);
81
+ }
82
+ parser.use(rehypeImages());
83
+ if (!isPerformanceBenchmark) {
84
+ parser.use(rehypeHeadingIds);
85
+ }
86
+ parser.use(rehypeRaw).use(rehypeStringify, { allowDangerousHtml: true });
87
+ return {
88
+ async render(content, renderOpts) {
89
+ const vfile = new VFile({ value: content, path: renderOpts?.fileURL });
90
+ setVfileFrontmatter(vfile, renderOpts?.frontmatter ?? {});
91
+ const result = await parser.process(vfile).catch((err) => {
92
+ err = prefixError(err, `Failed to parse Markdown file "${vfile.path}"`);
93
+ console.error(err);
94
+ throw err;
95
+ });
96
+ const astroData = safelyGetAstroData(result.data);
97
+ if (astroData instanceof InvalidAstroDataError) {
98
+ throw astroData;
99
+ }
100
+ return {
101
+ code: String(result.value),
102
+ metadata: {
103
+ headings: result.data.__astroHeadings ?? [],
104
+ imagePaths: result.data.imagePaths ?? /* @__PURE__ */ new Set(),
105
+ frontmatter: astroData.frontmatter ?? {}
106
+ }
107
+ };
108
+ }
109
+ };
110
+ }
111
+ function prefixError(err, prefix) {
112
+ if (err?.message) {
113
+ try {
114
+ err.message = `${prefix}:
115
+ ${err.message}`;
116
+ return err;
117
+ } catch (error) {
118
+ }
119
+ }
120
+ const wrappedError = new Error(`${prefix}${err ? `: ${err}` : ""}`);
121
+ try {
122
+ wrappedError.stack = err.stack;
123
+ wrappedError.cause = err;
124
+ } catch {
125
+ }
126
+ return wrappedError;
127
+ }
128
+ export {
129
+ InvalidAstroDataError2 as InvalidAstroDataError,
130
+ createMarkdownProcessor,
131
+ createShikiHighlighter,
132
+ markdownConfigDefaults,
133
+ rehypeHeadingIds2 as rehypeHeadingIds,
134
+ remarkCollectImages2 as remarkCollectImages,
135
+ remarkPrism2 as remarkPrism,
136
+ remarkShiki2 as remarkShiki,
137
+ replaceCssVariables,
138
+ setVfileFrontmatter2 as setVfileFrontmatter
139
+ };
@@ -0,0 +1 @@
1
+ export { InvalidAstroDataError, safelyGetAstroData } from './frontmatter-injection.js';
@@ -0,0 +1,5 @@
1
+ import { InvalidAstroDataError, safelyGetAstroData } from "./frontmatter-injection.js";
2
+ export {
3
+ InvalidAstroDataError,
4
+ safelyGetAstroData
5
+ };
@@ -0,0 +1,2 @@
1
+ import type * as unified from 'unified';
2
+ export declare function loadPlugins(items: (string | [string, any] | unified.Plugin<any[], any> | [unified.Plugin<any[], any>, any])[]): Promise<[unified.Plugin, any?]>[];
@@ -0,0 +1,31 @@
1
+ import { resolve as importMetaResolve } from "import-meta-resolve";
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ const cwdUrlStr = pathToFileURL(path.join(process.cwd(), "package.json")).toString();
5
+ async function importPlugin(p) {
6
+ if (typeof p === "string") {
7
+ try {
8
+ const importResult2 = await import(p);
9
+ return importResult2.default;
10
+ } catch {
11
+ }
12
+ const resolved = importMetaResolve(p, cwdUrlStr);
13
+ const importResult = await import(resolved);
14
+ return importResult.default;
15
+ }
16
+ return p;
17
+ }
18
+ function loadPlugins(items) {
19
+ return items.map((p) => {
20
+ return new Promise((resolve, reject) => {
21
+ if (Array.isArray(p)) {
22
+ const [plugin, opts] = p;
23
+ return importPlugin(plugin).then((m) => resolve([m, opts])).catch((e) => reject(e));
24
+ }
25
+ return importPlugin(p).then((m) => resolve([m])).catch((e) => reject(e));
26
+ });
27
+ });
28
+ }
29
+ export {
30
+ loadPlugins
31
+ };
@@ -0,0 +1,2 @@
1
+ import type { RehypePlugin } from './types.js';
2
+ export declare function rehypeHeadingIds(): ReturnType<RehypePlugin>;
@@ -0,0 +1,97 @@
1
+ import Slugger from "github-slugger";
2
+ import { visit } from "unist-util-visit";
3
+ import { InvalidAstroDataError, safelyGetAstroData } from "./frontmatter-injection.js";
4
+ const rawNodeTypes = /* @__PURE__ */ new Set(["text", "raw", "mdxTextExpression"]);
5
+ const codeTagNames = /* @__PURE__ */ new Set(["code", "pre"]);
6
+ function rehypeHeadingIds() {
7
+ return function(tree, file) {
8
+ const headings = [];
9
+ const slugger = new Slugger();
10
+ const isMDX = isMDXFile(file);
11
+ const astroData = safelyGetAstroData(file.data);
12
+ visit(tree, (node) => {
13
+ if (node.type !== "element")
14
+ return;
15
+ const { tagName } = node;
16
+ if (tagName[0] !== "h")
17
+ return;
18
+ const [, level] = tagName.match(/h([0-6])/) ?? [];
19
+ if (!level)
20
+ return;
21
+ const depth = Number.parseInt(level);
22
+ let text = "";
23
+ visit(node, (child, __, parent) => {
24
+ if (child.type === "element" || parent == null) {
25
+ return;
26
+ }
27
+ if (child.type === "raw") {
28
+ if (child.value.match(/^\n?<.*>\n?$/)) {
29
+ return;
30
+ }
31
+ }
32
+ if (rawNodeTypes.has(child.type)) {
33
+ if (isMDX || codeTagNames.has(parent.tagName)) {
34
+ let value = child.value;
35
+ if (isMdxTextExpression(child) && !(astroData instanceof InvalidAstroDataError)) {
36
+ const frontmatterPath = getMdxFrontmatterVariablePath(child);
37
+ if (Array.isArray(frontmatterPath) && frontmatterPath.length > 0) {
38
+ const frontmatterValue = getMdxFrontmatterVariableValue(astroData, frontmatterPath);
39
+ if (typeof frontmatterValue === "string") {
40
+ value = frontmatterValue;
41
+ }
42
+ }
43
+ }
44
+ text += value;
45
+ } else {
46
+ text += child.value.replace(/\{/g, "${");
47
+ }
48
+ }
49
+ });
50
+ node.properties = node.properties || {};
51
+ if (typeof node.properties.id !== "string") {
52
+ let slug = slugger.slug(text);
53
+ if (slug.endsWith("-"))
54
+ slug = slug.slice(0, -1);
55
+ node.properties.id = slug;
56
+ }
57
+ headings.push({ depth, slug: node.properties.id, text });
58
+ });
59
+ file.data.__astroHeadings = headings;
60
+ };
61
+ }
62
+ function isMDXFile(file) {
63
+ return Boolean(file.history[0]?.endsWith(".mdx"));
64
+ }
65
+ function getMdxFrontmatterVariablePath(node) {
66
+ if (!node.data?.estree || node.data.estree.body.length !== 1)
67
+ return new Error();
68
+ const statement = node.data.estree.body[0];
69
+ if (statement?.type !== "ExpressionStatement" || statement.expression.type !== "MemberExpression")
70
+ return new Error();
71
+ let expression = statement.expression;
72
+ const expressionPath = [];
73
+ while (expression.type === "MemberExpression" && expression.property.type === (expression.computed ? "Literal" : "Identifier")) {
74
+ expressionPath.push(
75
+ expression.property.type === "Literal" ? String(expression.property.value) : expression.property.name
76
+ );
77
+ expression = expression.object;
78
+ }
79
+ if (expression.type !== "Identifier" || expression.name !== "frontmatter")
80
+ return new Error();
81
+ return expressionPath.reverse();
82
+ }
83
+ function getMdxFrontmatterVariableValue(astroData, path) {
84
+ let value = astroData.frontmatter;
85
+ for (const key of path) {
86
+ if (!value[key])
87
+ return void 0;
88
+ value = value[key];
89
+ }
90
+ return value;
91
+ }
92
+ function isMdxTextExpression(node) {
93
+ return node.type === "mdxTextExpression";
94
+ }
95
+ export {
96
+ rehypeHeadingIds
97
+ };
@@ -0,0 +1,2 @@
1
+ import type { MarkdownVFile } from './types.js';
2
+ export declare function rehypeImages(): () => (tree: any, file: MarkdownVFile) => void;
@@ -0,0 +1,20 @@
1
+ import { visit } from "unist-util-visit";
2
+ function rehypeImages() {
3
+ return () => function(tree, file) {
4
+ visit(tree, (node) => {
5
+ if (node.type !== "element")
6
+ return;
7
+ if (node.tagName !== "img")
8
+ return;
9
+ if (node.properties?.src) {
10
+ if (file.data.imagePaths?.has(node.properties.src)) {
11
+ node.properties["__ASTRO_IMAGE_"] = node.properties.src;
12
+ delete node.properties.src;
13
+ }
14
+ }
15
+ });
16
+ };
17
+ }
18
+ export {
19
+ rehypeImages
20
+ };
@@ -0,0 +1,2 @@
1
+ import type { MarkdownVFile } from './types.js';
2
+ export declare function remarkCollectImages(): (tree: any, vfile: MarkdownVFile) => void;
@@ -0,0 +1,38 @@
1
+ import { definitions } from "mdast-util-definitions";
2
+ import { visit } from "unist-util-visit";
3
+ function remarkCollectImages() {
4
+ return function(tree, vfile) {
5
+ if (typeof vfile?.path !== "string")
6
+ return;
7
+ const definition = definitions(tree);
8
+ const imagePaths = /* @__PURE__ */ new Set();
9
+ visit(tree, ["image", "imageReference"], (node) => {
10
+ if (node.type === "image") {
11
+ if (shouldOptimizeImage(node.url))
12
+ imagePaths.add(node.url);
13
+ }
14
+ if (node.type === "imageReference") {
15
+ const imageDefinition = definition(node.identifier);
16
+ if (imageDefinition) {
17
+ if (shouldOptimizeImage(imageDefinition.url))
18
+ imagePaths.add(imageDefinition.url);
19
+ }
20
+ }
21
+ });
22
+ vfile.data.imagePaths = imagePaths;
23
+ };
24
+ }
25
+ function shouldOptimizeImage(src) {
26
+ return !isValidUrl(src) && !src.startsWith("/");
27
+ }
28
+ function isValidUrl(str) {
29
+ try {
30
+ new URL(str);
31
+ return true;
32
+ } catch {
33
+ return false;
34
+ }
35
+ }
36
+ export {
37
+ remarkCollectImages
38
+ };
@@ -0,0 +1,2 @@
1
+ import type { RemarkPlugin } from './types.js';
2
+ export declare function remarkPrism(): ReturnType<RemarkPlugin>;
@@ -0,0 +1,19 @@
1
+ import { runHighlighterWithAstro } from "@astrojs/prism/dist/highlighter";
2
+ import { visit } from "unist-util-visit";
3
+ function remarkPrism() {
4
+ return function(tree) {
5
+ visit(tree, "code", (node) => {
6
+ let { lang, value } = node;
7
+ node.type = "html";
8
+ let { html, classLanguage } = runHighlighterWithAstro(lang, value);
9
+ let classes = [classLanguage];
10
+ node.value = `<pre class="${classes.join(
11
+ " "
12
+ )}"><code is:raw class="${classLanguage}">${html}</code></pre>`;
13
+ return node;
14
+ });
15
+ };
16
+ }
17
+ export {
18
+ remarkPrism
19
+ };
@@ -0,0 +1,2 @@
1
+ import type { RemarkPlugin, ShikiConfig } from './types.js';
2
+ export declare function remarkShiki(config?: ShikiConfig): ReturnType<RemarkPlugin>;
@@ -0,0 +1,19 @@
1
+ import { visit } from "unist-util-visit";
2
+ import { createShikiHighlighter } from "./shiki.js";
3
+ function remarkShiki(config) {
4
+ let highlighterAsync;
5
+ return async (tree) => {
6
+ highlighterAsync ??= createShikiHighlighter(config);
7
+ const highlighter = await highlighterAsync;
8
+ visit(tree, "code", (node) => {
9
+ const lang = typeof node.lang === "string" ? node.lang : "plaintext";
10
+ const html = highlighter.highlight(node.value, lang);
11
+ node.type = "html";
12
+ node.value = html;
13
+ node.children = [];
14
+ });
15
+ };
16
+ }
17
+ export {
18
+ remarkShiki
19
+ };
@@ -0,0 +1,7 @@
1
+ import type { ShikiConfig } from './types.js';
2
+ export interface ShikiHighlighter {
3
+ highlight(code: string, lang?: string, options?: {
4
+ inline?: boolean;
5
+ }): string;
6
+ }
7
+ export declare function createShikiHighlighter({ langs, theme, experimentalThemes, wrap, }?: ShikiConfig): Promise<ShikiHighlighter>;
package/dist/shiki.js ADDED
@@ -0,0 +1,104 @@
1
+ import { bundledLanguages, getHighlighter } from "shikiji";
2
+ import { visit } from "unist-util-visit";
3
+ const ASTRO_COLOR_REPLACEMENTS = {
4
+ "#000001": "var(--astro-code-color-text)",
5
+ "#000002": "var(--astro-code-color-background)",
6
+ "#000004": "var(--astro-code-token-constant)",
7
+ "#000005": "var(--astro-code-token-string)",
8
+ "#000006": "var(--astro-code-token-comment)",
9
+ "#000007": "var(--astro-code-token-keyword)",
10
+ "#000008": "var(--astro-code-token-parameter)",
11
+ "#000009": "var(--astro-code-token-function)",
12
+ "#000010": "var(--astro-code-token-string-expression)",
13
+ "#000011": "var(--astro-code-token-punctuation)",
14
+ "#000012": "var(--astro-code-token-link)"
15
+ };
16
+ const COLOR_REPLACEMENT_REGEX = new RegExp(
17
+ `(${Object.keys(ASTRO_COLOR_REPLACEMENTS).join("|")})`,
18
+ "g"
19
+ );
20
+ async function createShikiHighlighter({
21
+ langs = [],
22
+ theme = "github-dark",
23
+ experimentalThemes = {},
24
+ wrap = false
25
+ } = {}) {
26
+ const themes = experimentalThemes;
27
+ const highlighter = await getHighlighter({
28
+ langs: langs.length ? langs : Object.keys(bundledLanguages),
29
+ themes: Object.values(themes).length ? Object.values(themes) : [theme]
30
+ });
31
+ const loadedLanguages = highlighter.getLoadedLanguages();
32
+ return {
33
+ highlight(code, lang = "plaintext", options) {
34
+ if (lang !== "plaintext" && !loadedLanguages.includes(lang)) {
35
+ console.warn(`[Shiki] The language "${lang}" doesn't exist, falling back to "plaintext".`);
36
+ lang = "plaintext";
37
+ }
38
+ const themeOptions = Object.values(themes).length ? { themes } : { theme };
39
+ const inline = options?.inline ?? false;
40
+ return highlighter.codeToHtml(code, {
41
+ ...themeOptions,
42
+ lang,
43
+ transforms: {
44
+ pre(node) {
45
+ if (inline) {
46
+ node.tagName = "code";
47
+ }
48
+ const classValue = node.properties.class ?? "";
49
+ const styleValue = node.properties.style ?? "";
50
+ node.properties.class = classValue.replace(/shiki/g, "astro-code");
51
+ if (wrap === false) {
52
+ node.properties.style = styleValue + "; overflow-x: auto;";
53
+ } else if (wrap === true) {
54
+ node.properties.style = styleValue + "; overflow-x: auto; white-space: pre-wrap; word-wrap: break-word;";
55
+ }
56
+ },
57
+ line(node) {
58
+ if (lang === "diff") {
59
+ const innerSpanNode = node.children[0];
60
+ const innerSpanTextNode = innerSpanNode?.type === "element" && innerSpanNode.children?.[0];
61
+ if (innerSpanTextNode && innerSpanTextNode.type === "text") {
62
+ const start = innerSpanTextNode.value[0];
63
+ if (start === "+" || start === "-") {
64
+ innerSpanTextNode.value = innerSpanTextNode.value.slice(1);
65
+ innerSpanNode.children.unshift({
66
+ type: "element",
67
+ tagName: "span",
68
+ properties: { style: "user-select: none;" },
69
+ children: [{ type: "text", value: start }]
70
+ });
71
+ }
72
+ }
73
+ }
74
+ },
75
+ code(node) {
76
+ if (inline) {
77
+ return node.children[0];
78
+ }
79
+ },
80
+ root(node) {
81
+ if (Object.values(experimentalThemes).length) {
82
+ return;
83
+ }
84
+ const themeName = typeof theme === "string" ? theme : theme.name;
85
+ if (themeName === "css-variables") {
86
+ visit(node, "element", (child) => {
87
+ if (child.properties?.style) {
88
+ child.properties.style = replaceCssVariables(child.properties.style);
89
+ }
90
+ });
91
+ }
92
+ }
93
+ }
94
+ });
95
+ }
96
+ };
97
+ }
98
+ function replaceCssVariables(str) {
99
+ return str.replace(COLOR_REPLACEMENT_REGEX, (match) => ASTRO_COLOR_REPLACEMENTS[match] || match);
100
+ }
101
+ export {
102
+ createShikiHighlighter,
103
+ replaceCssVariables
104
+ };
@@ -0,0 +1,74 @@
1
+ import type * as hast from 'hast';
2
+ import type * as mdast from 'mdast';
3
+ import type { Options as RemarkRehypeOptions } from 'remark-rehype';
4
+ import type { BuiltinTheme, LanguageRegistration, ThemeRegistration, ThemeRegistrationRaw } from 'shikiji';
5
+ import type * as unified from 'unified';
6
+ import type { VFile } from 'vfile';
7
+ export type { Node } from 'unist';
8
+ export type MarkdownAstroData = {
9
+ frontmatter: Record<string, any>;
10
+ };
11
+ export type RemarkPlugin<PluginParameters extends any[] = any[]> = unified.Plugin<PluginParameters, mdast.Root>;
12
+ export type RemarkPlugins = (string | [string, any] | RemarkPlugin | [RemarkPlugin, any])[];
13
+ export type RehypePlugin<PluginParameters extends any[] = any[]> = unified.Plugin<PluginParameters, hast.Root>;
14
+ export type RehypePlugins = (string | [string, any] | RehypePlugin | [RehypePlugin, any])[];
15
+ export type RemarkRehype = RemarkRehypeOptions;
16
+ export interface ShikiConfig {
17
+ langs?: LanguageRegistration[];
18
+ theme?: BuiltinTheme | ThemeRegistration | ThemeRegistrationRaw;
19
+ experimentalThemes?: Record<string, BuiltinTheme | ThemeRegistration | ThemeRegistrationRaw>;
20
+ wrap?: boolean | null;
21
+ }
22
+ export interface AstroMarkdownOptions {
23
+ syntaxHighlight?: 'shiki' | 'prism' | false;
24
+ shikiConfig?: ShikiConfig;
25
+ remarkPlugins?: RemarkPlugins;
26
+ rehypePlugins?: RehypePlugins;
27
+ remarkRehype?: RemarkRehype;
28
+ gfm?: boolean;
29
+ smartypants?: boolean;
30
+ }
31
+ export interface ImageMetadata {
32
+ src: string;
33
+ width: number;
34
+ height: number;
35
+ type: string;
36
+ }
37
+ export interface MarkdownProcessor {
38
+ render: (content: string, opts?: MarkdownProcessorRenderOptions) => Promise<MarkdownProcessorRenderResult>;
39
+ }
40
+ export interface MarkdownProcessorRenderOptions {
41
+ /** Used for frontmatter injection plugins */
42
+ frontmatter?: Record<string, any>;
43
+ }
44
+ export interface MarkdownProcessorRenderResult {
45
+ code: string;
46
+ metadata: {
47
+ headings: MarkdownHeading[];
48
+ imagePaths: Set<string>;
49
+ frontmatter: Record<string, any>;
50
+ };
51
+ }
52
+ export interface MarkdownRenderingOptions extends AstroMarkdownOptions, MarkdownProcessorRenderOptions {
53
+ }
54
+ export interface MarkdownHeading {
55
+ depth: number;
56
+ slug: string;
57
+ text: string;
58
+ }
59
+ export interface MarkdownMetadata {
60
+ headings: MarkdownHeading[];
61
+ source: string;
62
+ html: string;
63
+ }
64
+ export interface MarkdownVFile extends VFile {
65
+ data: {
66
+ __astroHeadings?: MarkdownHeading[];
67
+ imagePaths?: Set<string>;
68
+ };
69
+ }
70
+ export interface MarkdownRenderingResult {
71
+ metadata: MarkdownMetadata;
72
+ vfile: MarkdownVFile;
73
+ code: string;
74
+ }
package/dist/types.js ADDED
File without changes
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@astrojs/markdown-remark",
3
+ "version": "0.0.0-add-stable-20231208215901",
4
+ "type": "module",
5
+ "author": "withastro",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/withastro/astro.git",
10
+ "directory": "packages/markdown/remark"
11
+ },
12
+ "bugs": "https://github.com/withastro/astro/issues",
13
+ "homepage": "https://astro.build",
14
+ "main": "./dist/index.js",
15
+ "exports": {
16
+ ".": "./dist/index.js",
17
+ "./dist/internal.js": "./dist/internal.js"
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "dependencies": {
23
+ "@astrojs/prism": "^3.0.0",
24
+ "github-slugger": "^2.0.0",
25
+ "import-meta-resolve": "^4.0.0",
26
+ "mdast-util-definitions": "^6.0.0",
27
+ "rehype-raw": "^7.0.0",
28
+ "rehype-stringify": "^10.0.0",
29
+ "remark-gfm": "^4.0.0",
30
+ "remark-parse": "^11.0.0",
31
+ "remark-rehype": "^11.0.0",
32
+ "remark-smartypants": "^2.0.0",
33
+ "shikiji": "^0.6.13",
34
+ "unified": "^11.0.4",
35
+ "unist-util-visit": "^5.0.0",
36
+ "vfile": "^6.0.1"
37
+ },
38
+ "devDependencies": {
39
+ "@types/chai": "^4.3.10",
40
+ "@types/estree": "^1.0.5",
41
+ "@types/hast": "^3.0.3",
42
+ "@types/mdast": "^4.0.3",
43
+ "@types/mocha": "^10.0.4",
44
+ "@types/unist": "^3.0.2",
45
+ "chai": "^4.3.7",
46
+ "mdast-util-mdx-expression": "^2.0.0",
47
+ "mocha": "^10.2.0",
48
+ "astro-scripts": "0.0.14"
49
+ },
50
+ "publishConfig": {
51
+ "provenance": true
52
+ },
53
+ "scripts": {
54
+ "prepublish": "pnpm build",
55
+ "build": "astro-scripts build \"src/**/*.ts\" && tsc -p tsconfig.json",
56
+ "build:ci": "astro-scripts build \"src/**/*.ts\"",
57
+ "postbuild": "astro-scripts copy \"src/**/*.js\"",
58
+ "dev": "astro-scripts dev \"src/**/*.ts\"",
59
+ "test": "mocha --exit --timeout 20000"
60
+ }
61
+ }