@astrojs/markdown-remark 0.0.0-10745-20240410180016

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 { VFile, VFileData as Data } 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,15 @@
1
+ import type { Root } from 'hast';
2
+ type Highlighter = (code: string, language: string, options?: {
3
+ meta?: string;
4
+ }) => Promise<string>;
5
+ /**
6
+ * A hast utility to syntax highlight code blocks with a given syntax highlighter.
7
+ *
8
+ * @param tree
9
+ * The hast tree in which to syntax highlight code blocks.
10
+ * @param highlighter
11
+ * A fnction which receives the code and language, and returns the HTML of a syntax
12
+ * highlighted `<pre>` element.
13
+ */
14
+ export declare function highlightCodeBlocks(tree: Root, highlighter: Highlighter): Promise<void>;
15
+ export {};
@@ -0,0 +1,53 @@
1
+ import { fromHtml } from "hast-util-from-html";
2
+ import { toText } from "hast-util-to-text";
3
+ import { removePosition } from "unist-util-remove-position";
4
+ import { visitParents } from "unist-util-visit-parents";
5
+ const languagePattern = /\blanguage-(\S+)\b/;
6
+ async function highlightCodeBlocks(tree, highlighter) {
7
+ const nodes = [];
8
+ visitParents(tree, { type: "element", tagName: "code" }, (node, ancestors) => {
9
+ const parent = ancestors.at(-1);
10
+ if (parent?.type !== "element" || parent.tagName !== "pre") {
11
+ return;
12
+ }
13
+ if (parent.children.length !== 1) {
14
+ return;
15
+ }
16
+ let languageMatch;
17
+ let { className } = node.properties;
18
+ if (typeof className === "string") {
19
+ languageMatch = className.match(languagePattern);
20
+ } else if (Array.isArray(className)) {
21
+ for (const cls of className) {
22
+ if (typeof cls !== "string") {
23
+ continue;
24
+ }
25
+ languageMatch = cls.match(languagePattern);
26
+ if (languageMatch) {
27
+ break;
28
+ }
29
+ }
30
+ }
31
+ if (languageMatch?.[1] === "math") {
32
+ return;
33
+ }
34
+ nodes.push({
35
+ node,
36
+ language: languageMatch?.[1] || "plaintext",
37
+ parent,
38
+ grandParent: ancestors.at(-2)
39
+ });
40
+ });
41
+ for (const { node, language, grandParent, parent } of nodes) {
42
+ const meta = node.data?.meta ?? node.properties.metastring ?? void 0;
43
+ const code = toText(node, { whitespace: "pre" });
44
+ const html = await highlighter(code, language, { meta });
45
+ const replacement = fromHtml(html, { fragment: true }).children[0];
46
+ removePosition(replacement);
47
+ const index = grandParent.children.indexOf(parent);
48
+ grandParent.children[index] = replacement;
49
+ }
50
+ }
51
+ export {
52
+ highlightCodeBlocks
53
+ };
@@ -0,0 +1,2 @@
1
+ import type * as unified from 'unified';
2
+ export declare function importPlugin(p: string): Promise<unified.Plugin>;
@@ -0,0 +1,7 @@
1
+ async function importPlugin(p) {
2
+ const importResult = await import(p);
3
+ return importResult.default;
4
+ }
5
+ export {
6
+ importPlugin
7
+ };
@@ -0,0 +1,2 @@
1
+ import type * as unified from 'unified';
2
+ export declare function importPlugin(p: string): Promise<unified.Plugin>;
@@ -0,0 +1,18 @@
1
+ import path from "node:path";
2
+ import { pathToFileURL } from "node:url";
3
+ import { resolve as importMetaResolve } from "import-meta-resolve";
4
+ let cwdUrlStr;
5
+ async function importPlugin(p) {
6
+ try {
7
+ const importResult2 = await import(p);
8
+ return importResult2.default;
9
+ } catch {
10
+ }
11
+ cwdUrlStr ??= pathToFileURL(path.join(process.cwd(), "package.json")).toString();
12
+ const resolved = importMetaResolve(p, cwdUrlStr);
13
+ const importResult = await import(resolved);
14
+ return importResult.default;
15
+ }
16
+ export {
17
+ importPlugin
18
+ };
@@ -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 { rehypePrism } from './rehype-prism.js';
6
+ export { rehypeShiki } from './rehype-shiki.js';
7
+ export { createShikiHighlighter, 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,141 @@
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 { rehypePrism } from "./rehype-prism.js";
9
+ import { rehypeShiki } from "./rehype-shiki.js";
10
+ import { remarkCollectImages } from "./remark-collect-images.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 { rehypePrism as rehypePrism2 } from "./rehype-prism.js";
24
+ import { rehypeShiki as rehypeShiki2 } from "./rehype-shiki.js";
25
+ import { createShikiHighlighter } from "./shiki.js";
26
+ export * from "./types.js";
27
+ const markdownConfigDefaults = {
28
+ syntaxHighlight: "shiki",
29
+ shikiConfig: {
30
+ langs: [],
31
+ theme: "github-dark",
32
+ themes: {},
33
+ wrap: false,
34
+ transformers: []
35
+ },
36
+ remarkPlugins: [],
37
+ rehypePlugins: [],
38
+ remarkRehype: {},
39
+ gfm: true,
40
+ smartypants: true
41
+ };
42
+ const isPerformanceBenchmark = Boolean(process.env.ASTRO_PERFORMANCE_BENCHMARK);
43
+ async function createMarkdownProcessor(opts) {
44
+ const {
45
+ syntaxHighlight = markdownConfigDefaults.syntaxHighlight,
46
+ shikiConfig = markdownConfigDefaults.shikiConfig,
47
+ remarkPlugins = markdownConfigDefaults.remarkPlugins,
48
+ rehypePlugins = markdownConfigDefaults.rehypePlugins,
49
+ remarkRehype: remarkRehypeOptions = markdownConfigDefaults.remarkRehype,
50
+ gfm = markdownConfigDefaults.gfm,
51
+ smartypants = markdownConfigDefaults.smartypants
52
+ } = opts ?? {};
53
+ const loadedRemarkPlugins = await Promise.all(loadPlugins(remarkPlugins));
54
+ const loadedRehypePlugins = await Promise.all(loadPlugins(rehypePlugins));
55
+ const parser = unified().use(remarkParse);
56
+ if (!isPerformanceBenchmark) {
57
+ if (gfm) {
58
+ parser.use(remarkGfm);
59
+ }
60
+ if (smartypants) {
61
+ parser.use(remarkSmartypants);
62
+ }
63
+ }
64
+ for (const [plugin, pluginOpts] of loadedRemarkPlugins) {
65
+ parser.use(plugin, pluginOpts);
66
+ }
67
+ if (!isPerformanceBenchmark) {
68
+ parser.use(remarkCollectImages);
69
+ }
70
+ parser.use(remarkRehype, {
71
+ allowDangerousHtml: true,
72
+ passThrough: [],
73
+ ...remarkRehypeOptions
74
+ });
75
+ if (!isPerformanceBenchmark) {
76
+ if (syntaxHighlight === "shiki") {
77
+ parser.use(rehypeShiki, shikiConfig);
78
+ } else if (syntaxHighlight === "prism") {
79
+ parser.use(rehypePrism);
80
+ }
81
+ }
82
+ for (const [plugin, pluginOpts] of loadedRehypePlugins) {
83
+ parser.use(plugin, pluginOpts);
84
+ }
85
+ parser.use(rehypeImages());
86
+ if (!isPerformanceBenchmark) {
87
+ parser.use(rehypeHeadingIds);
88
+ }
89
+ parser.use(rehypeRaw).use(rehypeStringify, { allowDangerousHtml: true });
90
+ return {
91
+ async render(content, renderOpts) {
92
+ const vfile = new VFile({ value: content, path: renderOpts?.fileURL });
93
+ setVfileFrontmatter(vfile, renderOpts?.frontmatter ?? {});
94
+ const result = await parser.process(vfile).catch((err) => {
95
+ err = prefixError(err, `Failed to parse Markdown file "${vfile.path}"`);
96
+ console.error(err);
97
+ throw err;
98
+ });
99
+ const astroData = safelyGetAstroData(result.data);
100
+ if (astroData instanceof InvalidAstroDataError) {
101
+ throw astroData;
102
+ }
103
+ return {
104
+ code: String(result.value),
105
+ metadata: {
106
+ headings: result.data.__astroHeadings ?? [],
107
+ imagePaths: result.data.imagePaths ?? /* @__PURE__ */ new Set(),
108
+ frontmatter: astroData.frontmatter ?? {}
109
+ }
110
+ };
111
+ }
112
+ };
113
+ }
114
+ function prefixError(err, prefix) {
115
+ if (err?.message) {
116
+ try {
117
+ err.message = `${prefix}:
118
+ ${err.message}`;
119
+ return err;
120
+ } catch (error) {
121
+ }
122
+ }
123
+ const wrappedError = new Error(`${prefix}${err ? `: ${err}` : ""}`);
124
+ try {
125
+ wrappedError.stack = err.stack;
126
+ wrappedError.cause = err;
127
+ } catch {
128
+ }
129
+ return wrappedError;
130
+ }
131
+ export {
132
+ InvalidAstroDataError2 as InvalidAstroDataError,
133
+ createMarkdownProcessor,
134
+ createShikiHighlighter,
135
+ markdownConfigDefaults,
136
+ rehypeHeadingIds2 as rehypeHeadingIds,
137
+ rehypePrism2 as rehypePrism,
138
+ rehypeShiki2 as rehypeShiki,
139
+ remarkCollectImages2 as remarkCollectImages,
140
+ setVfileFrontmatter2 as setVfileFrontmatter
141
+ };
@@ -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,22 @@
1
+ import { importPlugin as _importPlugin } from "#import-plugin";
2
+ async function importPlugin(p) {
3
+ if (typeof p === "string") {
4
+ return await _importPlugin(p);
5
+ } else {
6
+ return p;
7
+ }
8
+ }
9
+ function loadPlugins(items) {
10
+ return items.map((p) => {
11
+ return new Promise((resolve, reject) => {
12
+ if (Array.isArray(p)) {
13
+ const [plugin, opts] = p;
14
+ return importPlugin(plugin).then((m) => resolve([m, opts])).catch((e) => reject(e));
15
+ }
16
+ return importPlugin(p).then((m) => resolve([m])).catch((e) => reject(e));
17
+ });
18
+ });
19
+ }
20
+ export {
21
+ loadPlugins
22
+ };
@@ -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,27 @@
1
+ import { visit } from "unist-util-visit";
2
+ function rehypeImages() {
3
+ return () => function(tree, file) {
4
+ const imageOccurrenceMap = /* @__PURE__ */ new Map();
5
+ visit(tree, (node) => {
6
+ if (node.type !== "element")
7
+ return;
8
+ if (node.tagName !== "img")
9
+ return;
10
+ if (node.properties?.src) {
11
+ node.properties.src = decodeURI(node.properties.src);
12
+ if (file.data.imagePaths?.has(node.properties.src)) {
13
+ const { ...props } = node.properties;
14
+ const index = imageOccurrenceMap.get(node.properties.src) || 0;
15
+ imageOccurrenceMap.set(node.properties.src, index + 1);
16
+ node.properties["__ASTRO_IMAGE_"] = JSON.stringify({ ...props, index });
17
+ Object.keys(props).forEach((prop) => {
18
+ delete node.properties[prop];
19
+ });
20
+ }
21
+ }
22
+ });
23
+ };
24
+ }
25
+ export {
26
+ rehypeImages
27
+ };
@@ -0,0 +1,3 @@
1
+ import type { Root } from 'hast';
2
+ import type { Plugin } from 'unified';
3
+ export declare const rehypePrism: Plugin<[], Root>;
@@ -0,0 +1,15 @@
1
+ import { runHighlighterWithAstro } from "@astrojs/prism/dist/highlighter";
2
+ import { highlightCodeBlocks } from "./highlight.js";
3
+ const rehypePrism = () => {
4
+ return async (tree) => {
5
+ await highlightCodeBlocks(tree, (code, language) => {
6
+ let { html, classLanguage } = runHighlighterWithAstro(language, code);
7
+ return Promise.resolve(
8
+ `<pre class="${classLanguage}" data-language="${language}"><code is:raw class="${classLanguage}">${html}</code></pre>`
9
+ );
10
+ });
11
+ };
12
+ };
13
+ export {
14
+ rehypePrism
15
+ };
@@ -0,0 +1,4 @@
1
+ import type { Root } from 'hast';
2
+ import type { Plugin } from 'unified';
3
+ import type { ShikiConfig } from './types.js';
4
+ export declare const rehypeShiki: Plugin<[ShikiConfig?], Root>;
@@ -0,0 +1,13 @@
1
+ import { highlightCodeBlocks } from "./highlight.js";
2
+ import { createShikiHighlighter } from "./shiki.js";
3
+ const rehypeShiki = (config) => {
4
+ let highlighterAsync;
5
+ return async (tree) => {
6
+ highlighterAsync ??= createShikiHighlighter(config);
7
+ const highlighter = await highlighterAsync;
8
+ await highlightCodeBlocks(tree, highlighter.highlight);
9
+ };
10
+ };
11
+ export {
12
+ rehypeShiki
13
+ };
@@ -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,12 @@
1
+ import type { ShikiConfig } from './types.js';
2
+ export interface ShikiHighlighter {
3
+ highlight(code: string, lang?: string, options?: {
4
+ inline?: boolean;
5
+ attributes?: Record<string, string>;
6
+ /**
7
+ * Raw `meta` information to be used by Shiki transformers
8
+ */
9
+ meta?: string;
10
+ }): Promise<string>;
11
+ }
12
+ export declare function createShikiHighlighter({ langs, theme, themes, wrap, transformers, }?: ShikiConfig): Promise<ShikiHighlighter>;
package/dist/shiki.js ADDED
@@ -0,0 +1,124 @@
1
+ import {
2
+ createCssVariablesTheme,
3
+ getHighlighter,
4
+ isSpecialLang
5
+ } from "shiki";
6
+ import { visit } from "unist-util-visit";
7
+ const ASTRO_COLOR_REPLACEMENTS = {
8
+ "--astro-code-foreground": "--astro-code-color-text",
9
+ "--astro-code-background": "--astro-code-color-background"
10
+ };
11
+ const COLOR_REPLACEMENT_REGEX = new RegExp(
12
+ `${Object.keys(ASTRO_COLOR_REPLACEMENTS).join("|")}`,
13
+ "g"
14
+ );
15
+ let _cssVariablesTheme;
16
+ const cssVariablesTheme = () => _cssVariablesTheme ?? (_cssVariablesTheme = createCssVariablesTheme({ variablePrefix: "--astro-code-" }));
17
+ async function createShikiHighlighter({
18
+ langs = [],
19
+ theme = "github-dark",
20
+ themes = {},
21
+ wrap = false,
22
+ transformers = []
23
+ } = {}) {
24
+ theme = theme === "css-variables" ? cssVariablesTheme() : theme;
25
+ const highlighter = await getHighlighter({
26
+ langs: ["plaintext", ...langs],
27
+ themes: Object.values(themes).length ? Object.values(themes) : [theme]
28
+ });
29
+ return {
30
+ async highlight(code, lang = "plaintext", options) {
31
+ const loadedLanguages = highlighter.getLoadedLanguages();
32
+ if (!isSpecialLang(lang) && !loadedLanguages.includes(lang)) {
33
+ try {
34
+ await highlighter.loadLanguage(lang);
35
+ } catch (_err) {
36
+ console.warn(
37
+ `[Shiki] The language "${lang}" doesn't exist, falling back to "plaintext".`
38
+ );
39
+ lang = "plaintext";
40
+ }
41
+ }
42
+ const themeOptions = Object.values(themes).length ? { themes } : { theme };
43
+ const inline = options?.inline ?? false;
44
+ return highlighter.codeToHtml(code, {
45
+ ...themeOptions,
46
+ lang,
47
+ // NOTE: while we can spread `options.attributes` here so that Shiki can auto-serialize this as rendered
48
+ // attributes on the top-level tag, it's not clear whether it is fine to pass all attributes as meta, as
49
+ // they're technically not meta, nor parsed from Shiki's `parseMetaString` API.
50
+ meta: options?.meta ? { __raw: options?.meta } : void 0,
51
+ transformers: [
52
+ {
53
+ pre(node) {
54
+ if (inline) {
55
+ node.tagName = "code";
56
+ }
57
+ const {
58
+ class: attributesClass,
59
+ style: attributesStyle,
60
+ ...rest
61
+ } = options?.attributes ?? {};
62
+ Object.assign(node.properties, rest);
63
+ const classValue = (normalizePropAsString(node.properties.class) ?? "") + (attributesClass ? ` ${attributesClass}` : "");
64
+ const styleValue = (normalizePropAsString(node.properties.style) ?? "") + (attributesStyle ? `; ${attributesStyle}` : "");
65
+ node.properties.class = classValue.replace(/shiki/g, "astro-code");
66
+ node.properties.dataLanguage = lang;
67
+ if (wrap === false) {
68
+ node.properties.style = styleValue + "; overflow-x: auto;";
69
+ } else if (wrap === true) {
70
+ node.properties.style = styleValue + "; overflow-x: auto; white-space: pre-wrap; word-wrap: break-word;";
71
+ }
72
+ },
73
+ line(node) {
74
+ if (lang === "diff") {
75
+ const innerSpanNode = node.children[0];
76
+ const innerSpanTextNode = innerSpanNode?.type === "element" && innerSpanNode.children?.[0];
77
+ if (innerSpanTextNode && innerSpanTextNode.type === "text") {
78
+ const start = innerSpanTextNode.value[0];
79
+ if (start === "+" || start === "-") {
80
+ innerSpanTextNode.value = innerSpanTextNode.value.slice(1);
81
+ innerSpanNode.children.unshift({
82
+ type: "element",
83
+ tagName: "span",
84
+ properties: { style: "user-select: none;" },
85
+ children: [{ type: "text", value: start }]
86
+ });
87
+ }
88
+ }
89
+ }
90
+ },
91
+ code(node) {
92
+ if (inline) {
93
+ return node.children[0];
94
+ }
95
+ },
96
+ root(node) {
97
+ if (Object.values(themes).length) {
98
+ return;
99
+ }
100
+ const themeName = typeof theme === "string" ? theme : theme.name;
101
+ if (themeName === "css-variables") {
102
+ visit(node, "element", (child) => {
103
+ if (child.properties?.style) {
104
+ child.properties.style = replaceCssVariables(child.properties.style);
105
+ }
106
+ });
107
+ }
108
+ }
109
+ },
110
+ ...transformers
111
+ ]
112
+ });
113
+ }
114
+ };
115
+ }
116
+ function normalizePropAsString(value) {
117
+ return Array.isArray(value) ? value.join(" ") : value;
118
+ }
119
+ function replaceCssVariables(str) {
120
+ return str.replace(COLOR_REPLACEMENT_REGEX, (match) => ASTRO_COLOR_REPLACEMENTS[match] || match);
121
+ }
122
+ export {
123
+ createShikiHighlighter
124
+ };
@@ -0,0 +1,58 @@
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, ShikiTransformer, ThemeRegistration, ThemeRegistrationRaw } from 'shiki';
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 type ThemePresets = BuiltinTheme | 'css-variables';
17
+ export interface ShikiConfig {
18
+ langs?: LanguageRegistration[];
19
+ theme?: ThemePresets | ThemeRegistration | ThemeRegistrationRaw;
20
+ themes?: Record<string, ThemePresets | ThemeRegistration | ThemeRegistrationRaw>;
21
+ wrap?: boolean | null;
22
+ transformers?: ShikiTransformer[];
23
+ }
24
+ export interface AstroMarkdownOptions {
25
+ syntaxHighlight?: 'shiki' | 'prism' | false;
26
+ shikiConfig?: ShikiConfig;
27
+ remarkPlugins?: RemarkPlugins;
28
+ rehypePlugins?: RehypePlugins;
29
+ remarkRehype?: RemarkRehype;
30
+ gfm?: boolean;
31
+ smartypants?: boolean;
32
+ }
33
+ export interface MarkdownProcessor {
34
+ render: (content: string, opts?: MarkdownProcessorRenderOptions) => Promise<MarkdownProcessorRenderResult>;
35
+ }
36
+ export interface MarkdownProcessorRenderOptions {
37
+ /** Used for frontmatter injection plugins */
38
+ frontmatter?: Record<string, any>;
39
+ }
40
+ export interface MarkdownProcessorRenderResult {
41
+ code: string;
42
+ metadata: {
43
+ headings: MarkdownHeading[];
44
+ imagePaths: Set<string>;
45
+ frontmatter: Record<string, any>;
46
+ };
47
+ }
48
+ export interface MarkdownHeading {
49
+ depth: number;
50
+ slug: string;
51
+ text: string;
52
+ }
53
+ export interface MarkdownVFile extends VFile {
54
+ data: {
55
+ __astroHeadings?: MarkdownHeading[];
56
+ imagePaths?: Set<string>;
57
+ };
58
+ }
package/dist/types.js ADDED
File without changes
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "@astrojs/markdown-remark",
3
+ "version": "0.0.0-10745-20240410180016",
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
+ "imports": {
20
+ "#import-plugin": {
21
+ "browser": "./dist/import-plugin-browser.js",
22
+ "default": "./dist/import-plugin-default.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "dependencies": {
29
+ "@astrojs/prism": "0.0.0-10745-20240410180016",
30
+ "github-slugger": "^2.0.0",
31
+ "hast-util-from-html": "^2.0.0",
32
+ "hast-util-to-text": "^4.0.0",
33
+ "import-meta-resolve": "^4.0.0",
34
+ "mdast-util-definitions": "^6.0.0",
35
+ "rehype-raw": "^7.0.0",
36
+ "rehype-stringify": "^10.0.0",
37
+ "remark-gfm": "^4.0.0",
38
+ "remark-parse": "^11.0.0",
39
+ "remark-rehype": "^11.0.0",
40
+ "remark-smartypants": "^2.0.0",
41
+ "shiki": "^1.1.2",
42
+ "unified": "^11.0.4",
43
+ "unist-util-remove-position": "^5.0.0",
44
+ "unist-util-visit": "^5.0.0",
45
+ "unist-util-visit-parents": "^6.0.0",
46
+ "vfile": "^6.0.1"
47
+ },
48
+ "devDependencies": {
49
+ "@types/chai": "^4.3.10",
50
+ "@types/estree": "^1.0.5",
51
+ "@types/hast": "^3.0.3",
52
+ "@types/mdast": "^4.0.3",
53
+ "@types/mocha": "^10.0.4",
54
+ "@types/unist": "^3.0.2",
55
+ "esbuild": "^0.19.6",
56
+ "mdast-util-mdx-expression": "^2.0.0",
57
+ "astro-scripts": "0.0.14"
58
+ },
59
+ "publishConfig": {
60
+ "provenance": true
61
+ },
62
+ "scripts": {
63
+ "prepublish": "pnpm build",
64
+ "build": "astro-scripts build \"src/**/*.ts\" && tsc -p tsconfig.json",
65
+ "build:ci": "astro-scripts build \"src/**/*.ts\"",
66
+ "postbuild": "astro-scripts copy \"src/**/*.js\"",
67
+ "dev": "astro-scripts dev \"src/**/*.ts\"",
68
+ "test": "astro-scripts test \"test/**/*.test.js\""
69
+ }
70
+ }